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

2225 lines
70 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"
"errors"
"image"
"regexp"
"strings"
"sync"
"time"
"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"
)
// Options tunes runner polling intervals (short in unit tests, steady in production).
type Options struct {
PollInterval time.Duration
Stage3Interval time.Duration
PostActionWait time.Duration
Watchdog WatchdogConfig
NowFunc func() time.Time
DisableSleep bool
}
func defaultOptions() Options {
return Options{
PollInterval: 1500 * time.Millisecond,
Stage3Interval: 15 * time.Second,
PostActionWait: 1200 * time.Millisecond,
Watchdog: defaultWatchdogConfig(),
NowFunc: time.Now,
}
}
// RunStatusView is the read-only snapshot returned by `autoinstall/status`.
type RunStatusView struct {
VM string `json:"vm"`
Stage string `json:"stage"`
Status string `json:"status"`
Message string `json:"message,omitempty"`
PauseReason string `json:"pause_reason,omitempty"`
UnknownPageSummary string `json:"unknown_page_summary,omitempty"`
MatchedRules []string `json:"matched_rules,omitempty"`
FinishInstallDone bool `json:"finish_install_done,omitempty"`
SaveUnlockCredential bool `json:"save_unlock_credential,omitempty"`
StartedAt string `json:"started_at,omitempty"`
UpdatedAt string `json:"updated_at,omitempty"`
}
// Runner executes the Stage 0–6 offline macOS unattended install state machine
// for one VM, supporting safe pauses, user takeover, checkpointing, and resume.
type Runner struct {
host hostclient.HostAPI
locator vision.VisualLocator
rules *rules.Engine
dataDir string
cfg RunConfig
opts Options
mu sync.Mutex
cp Checkpoint
cpSeq uint64
saveMu sync.Mutex
savedSeq uint64
inheritedRunningStage bool
terminalNotReadyPolls int
resumeCh chan struct{}
cancel context.CancelFunc
started bool
stopped bool
onDone func()
doneOnce sync.Once
done chan struct{}
}
const staleRunningCheckpointTTL = 2 * time.Hour
// New creates a Runner initialized with a pre-opened VisualLocator and rules.Engine.
func New(host hostclient.HostAPI, locator vision.VisualLocator, ruleEngine *rules.Engine, dataDir string, cfg RunConfig, opts Options) (*Runner, error) {
if err := ValidateConfig(&cfg); err != nil {
return nil, err
}
def := defaultOptions()
if opts.PollInterval <= 0 {
opts.PollInterval = def.PollInterval
}
if opts.Stage3Interval <= 0 {
opts.Stage3Interval = def.Stage3Interval
}
if opts.PostActionWait <= 0 {
opts.PostActionWait = def.PostActionWait
}
if opts.NowFunc == nil {
opts.NowFunc = def.NowFunc
}
now := opts.NowFunc().UTC()
cp := Checkpoint{
Version: 1,
VM: cfg.VM,
Stage: StagePreflight,
Status: StatusRunning,
Config: cfg,
StartedAt: now,
UpdatedAt: now,
}
inheritedRunning := false
if prev, ok := LoadCheckpoint(dataDir, cfg.VM); ok && prev.Stage != "" {
switch prev.Status {
case StatusPausedForUser:
cp.Stage = prev.Stage
cp.FinishInstallDone = prev.FinishInstallDone
cp.ProvisionFallbackNeeded = prev.ProvisionFallbackNeeded
cp.MatchedRules = prev.MatchedRules
case StatusRunning:
// Only inherit an interrupted StatusRunning stage if the checkpoint is
// recent; stale crash remnants fall back to StageBootRecovery so screen
// recognition re-orients safely.
if prev.UpdatedAt.IsZero() || now.Sub(prev.UpdatedAt) <= staleRunningCheckpointTTL {
cp.Stage = prev.Stage
inheritedRunning = true
} else {
cp.Stage = StageBootRecovery
}
cp.FinishInstallDone = prev.FinishInstallDone
cp.ProvisionFallbackNeeded = prev.ProvisionFallbackNeeded
cp.MatchedRules = prev.MatchedRules
}
}
return &Runner{
host: host,
locator: locator,
rules: ruleEngine,
dataDir: dataDir,
cfg: cfg,
opts: opts,
cp: cp,
inheritedRunningStage: inheritedRunning,
resumeCh: make(chan struct{}, 1),
done: make(chan struct{}),
}, nil
}
// SetOnDone registers a cleanup callback invoked synchronously right before
// Wait() unblocks (used by Service to close OCR handles before StopAll returns).
func (r *Runner) SetOnDone(fn func()) {
r.mu.Lock()
r.onDone = fn
r.mu.Unlock()
}
func (r *Runner) finishDone() {
r.doneOnce.Do(func() {
r.mu.Lock()
fn := r.onDone
r.onDone = nil
r.mu.Unlock()
if fn != nil {
fn()
}
close(r.done)
})
}
// Start launches the Stage 0–6 state machine in a background goroutine.
func (r *Runner) Start(parent context.Context) {
if parent == nil {
parent = context.Background()
}
ctx, cancel := context.WithCancel(parent)
r.mu.Lock()
if r.started {
r.mu.Unlock()
cancel()
return
}
r.started = true
if r.stopped {
r.mu.Unlock()
cancel()
r.finishDone()
return
}
r.cancel = cancel
r.mu.Unlock()
go func() {
defer r.finishDone()
defer cancel()
r.run(ctx)
}()
}
// Wait blocks until the runner finishes, pauses permanently, or is stopped.
func (r *Runner) Wait() { <-r.done }
func (r *Runner) snapshotCheckpointLocked() (uint64, Checkpoint) {
r.cpSeq++
return r.cpSeq, cloneCheckpoint(r.cp)
}
func (r *Runner) persistCheckpoint(seq uint64, snap Checkpoint) {
r.saveMu.Lock()
defer r.saveMu.Unlock()
if seq < r.savedSeq {
return
}
if saveCheckpoint(r.dataDir, snap) == nil {
r.savedSeq = seq
}
}
// Resume unblocks a runner sitting in paused_for_user.
func (r *Runner) Resume() {
var (
seq uint64
snap Checkpoint
save bool
)
r.mu.Lock()
if r.cp.Status == StatusPausedForUser {
r.cp.Status = StatusRunning
r.cp.PauseReason = ""
seq, snap = r.snapshotCheckpointLocked()
save = true
select {
case r.resumeCh <- struct{}{}:
default:
}
}
r.mu.Unlock()
if save {
r.persistCheckpoint(seq, snap)
}
}
// PauseByUser transitions an active runner cleanly into paused_for_user when
// the user clicks Pause on the host HUD or VM detail page.
func (r *Runner) PauseByUser(reason string) {
if strings.TrimSpace(reason) == "" {
reason = "user_paused"
}
var (
seq uint64
snap Checkpoint
save bool
)
r.mu.Lock()
if r.cp.Status == StatusRunning {
r.cp.Status = StatusPausedForUser
r.cp.PauseReason = reason
r.cp.Message = "Paused by user; click Resume to continue"
// Drain any stale resume token so the new pause cannot be skipped.
select {
case <-r.resumeCh:
default:
}
seq, snap = r.snapshotCheckpointLocked()
save = true
}
r.mu.Unlock()
if save {
r.persistCheckpoint(seq, snap)
}
}
// NotifyTakeover transitions an active runner cleanly into paused_for_user.
func (r *Runner) NotifyTakeover(reason string) {
var (
seq uint64
snap Checkpoint
save bool
)
r.mu.Lock()
if r.cp.Status == StatusRunning {
r.cp.Status = StatusPausedForUser
r.cp.PauseReason = "user_takeover:" + reason
r.cp.Message = "Paused after physical keyboard/mouse takeover; click Resume to continue"
select {
case <-r.resumeCh:
default:
}
seq, snap = r.snapshotCheckpointLocked()
save = true
}
r.mu.Unlock()
if save {
r.persistCheckpoint(seq, snap)
}
}
// Stop cancels the runner immediately.
func (r *Runner) Stop() {
r.StopWithOutcome(StatusStopped, "", "Stopped by user")
}
// StopWithOutcome transitions an active runner to a terminal status (such as
// StatusFailed when host permission is denied) and cancels execution right away.
func (r *Runner) StopWithOutcome(status, pauseReason, message string) {
if strings.TrimSpace(status) == "" {
status = StatusStopped
}
var (
seq uint64
snap Checkpoint
save bool
)
r.mu.Lock()
r.stopped = true
cancel := r.cancel
started := r.started
if r.cp.Status == StatusRunning || r.cp.Status == StatusPausedForUser {
r.cp.Status = status
r.cp.PauseReason = strings.TrimSpace(pauseReason)
if strings.TrimSpace(message) != "" {
r.cp.Message = strings.TrimSpace(message)
}
seq, snap = r.snapshotCheckpointLocked()
save = true
}
r.mu.Unlock()
if save {
r.persistCheckpoint(seq, snap)
}
if cancel != nil {
cancel()
} else if !started {
r.finishDone()
}
}
func (r *Runner) markCanceledIfActive() {
r.mu.Lock()
active := r.cp.Status == StatusRunning || r.cp.Status == StatusPausedForUser
r.mu.Unlock()
if active {
r.setState(context.Background(), "", StatusStopped, "Stopped", "")
}
}
func isPermissionDeniedError(err error) bool {
if err == nil {
return false
}
msg := strings.ToLower(err.Error())
for _, needle := range []string{
"confirmation_denied",
"permission_denied",
"not_authorized",
"requires high-risk permission approval",
"requires permission approval",
"lacks permission",
"has not approved high-risk permission",
} {
if strings.Contains(msg, needle) {
return true
}
}
return false
}
// Status returns a read-only view of the runner's current progress.
func (r *Runner) Status() RunStatusView {
r.mu.Lock()
defer r.mu.Unlock()
return RunStatusView{
VM: r.cp.VM,
Stage: r.cp.Stage,
Status: r.cp.Status,
Message: r.cp.Message,
PauseReason: r.cp.PauseReason,
UnknownPageSummary: r.cp.UnknownPageSummary,
MatchedRules: append([]string(nil), r.cp.MatchedRules...),
FinishInstallDone: r.cp.FinishInstallDone,
SaveUnlockCredential: r.cp.Config.SaveUnlockCredential,
StartedAt: r.cp.StartedAt.Format(time.RFC3339),
UpdatedAt: r.cp.UpdatedAt.Format(time.RFC3339),
}
}
func (r *Runner) setState(ctx context.Context, stage, status, message, pauseReason string) {
r.mu.Lock()
if stage != "" {
r.cp.Stage = stage
}
if status != "" {
r.cp.Status = status
}
r.cp.Message = message
r.cp.PauseReason = pauseReason
r.cp.UpdatedAt = r.opts.NowFunc().UTC()
seq, snap := r.snapshotCheckpointLocked()
paused := r.cp.Status == StatusPausedForUser
curStage := r.cp.Stage
curStatus := r.cp.Status
r.mu.Unlock()
r.persistCheckpoint(seq, snap)
sessionStage := curStage
if r.cfg.IsRecoveryOnly() && curStage == StageSetupAssistant && curStatus != StatusCompleted {
sessionStage = "stage5_wait_reboot"
}
_ = r.host.UpdateSession(ctx, pluginsdk.SessionUpdateRequest{
VM: r.cfg.VM,
Stage: sessionStage,
Status: curStatus,
Message: message,
PausedForUser: &paused,
})
}
func (r *Runner) recordRule(ruleID string) {
r.mu.Lock()
r.cp.MatchedRules = append(r.cp.MatchedRules, ruleID)
seq, snap := r.snapshotCheckpointLocked()
r.mu.Unlock()
r.persistCheckpoint(seq, snap)
}
func (r *Runner) pauseAndWaitResume(ctx context.Context, reason, message, rawScreenText string) error {
r.mu.Lock()
if r.stopped || ctx.Err() != nil {
r.mu.Unlock()
return context.Canceled
}
if rawScreenText != "" {
r.cp.UnknownPageSummary = RedactDiagnosticText(rawScreenText, r.cfg)
}
r.cp.Status = StatusPausedForUser
r.cp.Message = message
r.cp.PauseReason = reason
r.cp.UpdatedAt = r.opts.NowFunc().UTC()
// Drain any stale buffered resume signal before blocking on this pause so an
// earlier Pause+Resume cycle can never bypass a safety or unknown-page stop.
select {
case <-r.resumeCh:
default:
}
seq, snap := r.snapshotCheckpointLocked()
curStage := r.cp.Stage
r.mu.Unlock()
r.persistCheckpoint(seq, snap)
paused := true
sessionStage := curStage
if r.cfg.IsRecoveryOnly() && curStage == StageSetupAssistant {
sessionStage = "stage5_wait_reboot"
}
_ = r.host.UpdateSession(ctx, pluginsdk.SessionUpdateRequest{
VM: r.cfg.VM,
Stage: sessionStage,
Status: StatusPausedForUser,
Message: message,
PausedForUser: &paused,
})
_ = r.host.Notify(ctx, "macOS Auto-Install Paused", message)
return r.waitResumeOnly(ctx)
}
func (r *Runner) sleep(ctx context.Context, d time.Duration) error {
if r.opts.DisableSleep || d <= 0 {
return ctx.Err()
}
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
return nil
}
}
func (r *Runner) run(ctx context.Context) {
wd := NewWatchdog(r.opts.Watchdog, r.opts.NowFunc())
// Stage 0: Open visible host session with input-lock policy and confirmation.
// Preserve a resumed checkpoint stage or an early user pause if already set.
initialStage := r.currentStage()
if initialStage == "" {
initialStage = StagePreflight
}
if !r.isPaused() {
r.setState(ctx, initialStage, StatusRunning, "Requesting host session and installation authorization", "")
}
defer func() {
_ = r.host.EndSession(context.Background(), r.cfg.VM)
}()
if err := r.host.BeginSession(ctx, pluginsdk.SessionBeginRequest{
VM: r.cfg.VM,
Label: "macOS Auto-Install",
Stage: initialStage,
TakeoverPolicy: "lock",
RequestProtectedPhaseAuth: true,
PreferUntilPhaseExit: true,
}); err != nil {
reason := "session_begin_failed"
if isPermissionDeniedError(err) {
if strings.Contains(strings.ToLower(err.Error()), "confirmation_denied") {
reason = "confirmation_denied"
} else {
reason = "permission_denied"
}
}
r.fail(ctx, reason, err.Error())
return
}
// If this run inherited an interrupted StatusRunning stage in Recovery while
// telemetry already reports the VM in normal phase, re-orient safely instead
// of sending Recovery hotkeys or terminal commands.
if r.inheritedRunningStage {
cur := r.currentStage()
if cur == StageOfflineTerminal || cur == StageInstallWait {
if tel, tErr := r.host.Telemetry(ctx, r.cfg.VM); tErr == nil && strings.EqualFold(strings.TrimSpace(tel.Phase), "normal") {
nextStage := StageBootRecovery
if r.isFinishInstallDone() {
nextStage = StageSetupAssistant
}
r.setState(ctx, nextStage, StatusRunning, "Re-orienting after interrupted run", "")
}
}
}
for {
if ctx.Err() != nil {
r.markCanceledIfActive()
return
}
if r.isPaused() {
if err := r.waitResumeOnly(ctx); err != nil {
return
}
continue
}
stage := r.currentStage()
var err error
switch stage {
case StagePreflight, StageBootRecovery:
err = r.stepBootRecovery(ctx, wd)
case StageOfflineTerminal:
err = r.stepOfflineTerminal(ctx, wd)
case StageInstallWait:
err = r.stepInstallWait(ctx, wd)
case StageFinishInstall:
err = r.stepFinishInstall(ctx, wd)
case StageSetupAssistant:
err = r.stepSetupAssistant(ctx, wd)
case StageDesktopReady:
err = r.stepDesktopReady(ctx)
default:
r.setState(ctx, StageBootRecovery, StatusRunning, "Waiting for macOS Recovery", "")
}
if err == nil && r.currentStatus() == StatusCompleted {
return
}
if err != nil {
if errors.Is(err, context.Canceled) {
r.markCanceledIfActive()
return
}
if strings.Contains(err.Error(), "session_paused") {
r.PauseByUser("user_paused")
if wErr := r.waitResumeOnly(ctx); wErr != nil {
return
}
continue
}
if strings.Contains(err.Error(), "user_takeover") {
if pErr := r.pauseAndWaitResume(ctx, "user_takeover", "Paused after user input takeover; click Resume to continue", ""); pErr != nil {
return
}
continue
}
if isPermissionDeniedError(err) {
r.fail(ctx, "permission_denied", err.Error())
return
}
r.fail(ctx, "stage_error", err.Error())
return
}
}
}
func (r *Runner) isPaused() bool {
r.mu.Lock()
defer r.mu.Unlock()
return r.cp.Status == StatusPausedForUser
}
func (r *Runner) waitIfPaused(ctx context.Context) error {
if !r.isPaused() {
return nil
}
return r.waitResumeOnly(ctx)
}
func (r *Runner) currentStage() string {
r.mu.Lock()
defer r.mu.Unlock()
return r.cp.Stage
}
func (r *Runner) currentStatus() string {
r.mu.Lock()
defer r.mu.Unlock()
return r.cp.Status
}
func (r *Runner) waitResumeOnly(ctx context.Context) error {
for {
r.mu.Lock()
st := r.cp.Status
stopped := r.stopped
r.mu.Unlock()
if stopped || ctx.Err() != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return context.Canceled
}
if st != StatusPausedForUser {
if st != StatusRunning {
return context.Canceled
}
r.setState(ctx, "", StatusRunning, "Resuming auto-install...", "")
return nil
}
select {
case <-ctx.Done():
return ctx.Err()
case <-r.resumeCh:
}
}
}
func (r *Runner) fail(ctx context.Context, reason, msg string) {
r.mu.Lock()
alreadyDenied := r.cp.Status == StatusFailed && (r.cp.PauseReason == "confirmation_denied" || r.cp.PauseReason == "permission_denied")
existingMsg := r.cp.Message
r.mu.Unlock()
if alreadyDenied {
if existingMsg != "" {
msg = existingMsg
}
_ = r.host.Notify(context.Background(), "macOS Auto-Install Stopped", msg)
return
}
r.setState(context.Background(), "", StatusFailed, msg, reason)
_ = r.host.Notify(context.Background(), "macOS Auto-Install Stopped", msg)
}
func (r *Runner) captureFull(ctx context.Context) (image.Image, hostclient.ScreenshotMeta, error) {
zero := 0
return r.host.Screenshot(ctx, pluginsdk.ScreenshotRequest{
VM: r.cfg.VM,
Format: "png",
MaxEdge: &zero,
})
}
func (r *Runner) clickPoint(ctx context.Context, pt image.Point, w, h int) error {
if err := r.host.PointerMove(ctx, r.cfg.VM, pt.X, pt.Y, w, h); err != nil {
return err
}
return r.host.PointerClick(ctx, r.cfg.VM, "left")
}
func (r *Runner) clickOnImage(ctx context.Context, img image.Image, pt image.Point) error {
b := img.Bounds()
return r.clickPoint(ctx, pt, b.Dx(), b.Dy())
}
// Stage 1: Wait for Recovery environment, skip optional language selector.
func (r *Runner) stepBootRecovery(ctx context.Context, wd *Watchdog) error {
if err := r.waitIfPaused(ctx); err != nil {
return err
}
r.setState(ctx, StageBootRecovery, StatusRunning, "Waiting for macOS Recovery screen", "")
tel, _ := r.host.Telemetry(ctx, r.cfg.VM)
if reason, detail, tripped := wd.Check(r.opts.NowFunc(), tel, StageBootRecovery, false); tripped {
if err := r.pauseAndWaitResume(ctx, reason, "Watchdog halted boot: "+detail, detail); err != nil {
return err
}
wd.ResetAfterResume(r.opts.NowFunc())
return nil
}
img, meta, err := r.captureFull(ctx)
if err != nil {
if strings.Contains(err.Error(), "vm_not_running") || strings.Contains(err.Error(), "confirmation_required") {
return r.sleep(ctx, r.opts.PollInterval)
}
return err
}
if meta.Blank || vision.DetectAppleProgress(img) {
return r.sleep(ctx, r.opts.PollInterval)
}
menuScan, err := r.locator.ScanROI(ctx, img, "menu_bar", nil)
if err != nil {
return err
}
bodyScan, err := r.locator.ScanROI(ctx, img, "body", nil)
if err != nil {
return err
}
roiTexts := map[string]string{"menu_bar": menuScan.Text, "body": bodyScan.Text, "full": menuScan.Text + "\n" + bodyScan.Text}
if rule, ok := r.rules.MatchScreen("recovery", roiTexts); ok {
if rule.ID == "recovery.language" {
if err := r.waitIfPaused(ctx); err != nil {
return err
}
r.recordRule(rule.ID)
if err := r.host.KeyPress(ctx, r.cfg.VM, "ret"); err != nil {
return err
}
return r.sleep(ctx, r.opts.PostActionWait)
}
if rule.ID == "recovery.main" {
r.setState(ctx, StageOfflineTerminal, StatusRunning, "Recovery ready; launching Terminal", "")
return nil
}
}
if _, _, hasUtil := rules.FindHit(menuScan.Lines, recoveryUtilitiesLabels, true); hasUtil || isTerminalMenuBar(menuScan.Text) {
r.setState(ctx, StageOfflineTerminal, StatusRunning, "Recovery ready; launching Terminal", "")
return nil
}
// Check if VM already reached provisioned first-boot, Login Screen, Desktop, or Setup Assistant (e.g. resumed mid-install).
if hasBootMilestone(tel, "serial:provision_ready") || r.looksLikeLoginScreen(ctx, img) || r.looksLikeDesktop(ctx, img) || r.looksLikeSetupAssistant(ctx, img) {
if r.isFinishInstallDone() {
r.setState(ctx, StageSetupAssistant, StatusRunning, "Detected installed macOS screen", "")
} else {
r.setState(ctx, StageFinishInstall, StatusRunning, "Detected installed macOS first boot; exiting recovery", "")
}
return nil
}
return r.sleep(ctx, r.opts.PollInterval)
}
var recoveryUtilitiesLabels = []string{"Utilities", "实用工具", "工具程式", "ユーティリティ"}
var recoveryTerminalLabels = []string{"Terminal", "终端", "終端機", "ターミナル"}
func isTerminalMenuBar(menuText string) bool {
for _, tok := range recoveryTerminalLabels {
if rules.MatchPhrase(menuText, tok, true) {
return true
}
}
return false
}
func terminalLooksReady(termText string) bool {
for _, tok := range []string{"-zsh", "-bash", "root#", "bash-", "zsh", "-sh-3.2#", "sh-3.2#", "-sh-3.2", "sh-3.2"} {
if rules.MatchPhrase(termText, tok, false) {
return true
}
}
return false
}
// waitForTerminalReady polls up to maxChecks times for Terminal to become
// foreground and/or print a shell prompt. Returns (opened, shellReady, error).
func (r *Runner) waitForTerminalReady(ctx context.Context, maxChecks int) (bool, bool, error) {
if maxChecks <= 0 {
maxChecks = 1
}
opened := false
for i := 0; i < maxChecks; i++ {
if err := r.waitIfPaused(ctx); err != nil {
return false, false, err
}
if err := r.sleep(ctx, r.opts.PostActionWait); err != nil {
return false, false, err
}
wImg, wMeta, err := r.captureFull(ctx)
if err != nil {
if errors.Is(err, context.Canceled) || isPermissionDeniedError(err) ||
strings.Contains(err.Error(), "vm_not_running") ||
strings.Contains(err.Error(), "session_paused") ||
strings.Contains(err.Error(), "user_takeover") {
return false, false, err
}
continue
}
if wMeta.Blank {
continue
}
if mScan, err := r.locator.ScanROI(ctx, wImg, "menu_bar", nil); err == nil && isTerminalMenuBar(mScan.Text) {
opened = true
}
if tScan, err := r.locator.ScanROI(ctx, wImg, "terminal", nil); err == nil && terminalLooksReady(tScan.Text) {
return true, true, nil
}
if r.opts.DisableSleep {
break
}
}
return opened, false, nil
}
// Stage 2A: Detect Recovery ready -> Shift+Cmd+T (fallback: Utilities -> Terminal) -> sh /Volumes/REIMSHELP/install.sh
func (r *Runner) stepOfflineTerminal(ctx context.Context, wd *Watchdog) error {
if err := r.waitIfPaused(ctx); err != nil {
return err
}
img, meta, err := r.captureFull(ctx)
if err != nil {
if strings.Contains(err.Error(), "vm_not_running") || strings.Contains(err.Error(), "confirmation_required") {
return r.sleep(ctx, r.opts.PollInterval)
}
return err
}
if meta.Blank || vision.DetectAppleProgress(img) {
return r.sleep(ctx, r.opts.PollInterval)
}
menuScan, err := r.locator.ScanROI(ctx, img, "menu_bar", nil)
if err != nil {
return err
}
terminalAlreadyOpen := false
terminalForeground := isTerminalMenuBar(menuScan.Text)
// If Terminal is already the foreground app (e.g. after resuming a paused session),
// inspect its output directly instead of re-launching Terminal.
if terminalForeground {
termText := ""
if termScan, err := r.locator.ScanROI(ctx, img, "terminal", nil); err == nil {
termText = termScan.Text
if rules.MatchPhrase(termScan.Text, "REIMS_INSTALLPKG_UNSUPPORTED", true) {
r.markProvisionFallbackNeeded()
}
if kw, danger := rules.DetectTerminalHighRiskKeyword(termScan.Text); danger {
r.terminalNotReadyPolls = 0
return r.pauseAndWaitResume(ctx, "terminal_safety_stop:"+kw, "恢复终端安全暂停("+kw+")", termScan.Text)
}
if terminalShowsInstallProgress(termScan.Text) {
r.terminalNotReadyPolls = 0
r.setState(ctx, StageInstallWait, StatusRunning, "正在写入 macOS 安装文件(自动监测跨重启进度)", "")
return nil
}
if terminalLooksReady(termScan.Text) {
r.terminalNotReadyPolls = 0
terminalAlreadyOpen = true
}
}
if !terminalAlreadyOpen {
// Terminal is already foreground but shell prompt is not ready yet; wait a
// bounded number of polls instead of re-launching Terminal or spinning forever.
r.terminalNotReadyPolls++
if !r.opts.DisableSleep && r.terminalNotReadyPolls <= 3 {
return r.sleep(ctx, r.opts.PollInterval)
}
r.terminalNotReadyPolls = 0
return r.pauseAndWaitResume(ctx, "terminal_not_ready", "终端已打开但未检测到命令提示符,请确认终端就绪后点击继续", termText)
}
} else {
r.terminalNotReadyPolls = 0
}
if !terminalAlreadyOpen {
_, utilPt, hasUtil := rules.FindHit(menuScan.Lines, recoveryUtilitiesLabels, true)
bodyScan, _ := r.locator.ScanROI(ctx, img, "body", nil)
roiTexts := map[string]string{"menu_bar": menuScan.Text, "body": bodyScan.Text, "full": menuScan.Text + "\n" + bodyScan.Text}
matchedRule, hasRule := r.rules.MatchScreen("recovery", roiTexts)
if hasRule && matchedRule.ID == "recovery.language" {
if err := r.waitIfPaused(ctx); err != nil {
return err
}
r.recordRule(matchedRule.ID)
if err := r.host.KeyPress(ctx, r.cfg.VM, "ret"); err != nil {
return err
}
return r.sleep(ctx, r.opts.PostActionWait)
}
recoveryReady := hasUtil || (hasRule && matchedRule.ID == "recovery.main")
if !recoveryReady {
// If install.sh already finished and rebooted into Login Screen or Setup Assistant while resumed, advance directly.
tel, _ := r.host.Telemetry(ctx, r.cfg.VM)
if hasBootMilestone(tel, "serial:provision_ready") || r.looksLikeLoginScreen(ctx, img) || r.looksLikeSetupAssistant(ctx, img) {
if r.isFinishInstallDone() {
r.setState(ctx, StageSetupAssistant, StatusRunning, "检测到系统首次启动,继续后续流程", "")
} else {
r.setState(ctx, StageFinishInstall, StatusRunning, "检测到系统首次启动,移除安装介质并重启", "")
}
return nil
}
return r.sleep(ctx, r.opts.PollInterval)
}
// 1. Primary path: launch Terminal via Shift+Cmd+T hotkey once Recovery is ready.
if err := r.waitIfPaused(ctx); err != nil {
return err
}
r.setState(ctx, StageOfflineTerminal, StatusRunning, "已识别恢复界面,使用快捷键打开终端", "")
opened, shellReady := false, false
if err := r.host.KeyPress(ctx, r.cfg.VM, "t", "shift", "meta_l"); err != nil {
if errors.Is(err, context.Canceled) || isPermissionDeniedError(err) ||
strings.Contains(err.Error(), "session_paused") ||
strings.Contains(err.Error(), "user_takeover") {
return err
}
// Non-fatal hotkey error: fall through cleanly to Utilities -> Terminal menu click.
} else {
var wErr error
opened, shellReady, wErr = r.waitForTerminalReady(ctx, 3)
if wErr != nil {
return wErr
}
}
if opened || shellReady {
r.recordRule("recovery.open_terminal_hotkey")
if !shellReady {
checks := 3
if r.opts.DisableSleep {
checks = 1
}
o2, s2, wErr := r.waitForTerminalReady(ctx, checks)
if wErr != nil {
return wErr
}
opened = opened || o2
shellReady = shellReady || s2
}
} else {
// 2. Fallback path: open Utilities -> Terminal via OCR menu clicks.
if !hasUtil {
return r.pauseAndWaitResume(ctx, "terminal_open_failed", "快捷键未打开恢复终端,且未定位到「实用工具」菜单", menuScan.Text)
}
if err := r.waitIfPaused(ctx); err != nil {
return err
}
r.setState(ctx, StageOfflineTerminal, StatusRunning, "快捷键未拉起终端,改由菜单打开终端", "")
if err := r.clickOnImage(ctx, img, utilPt); err != nil {
return err
}
if err := r.sleep(ctx, r.opts.PostActionWait); err != nil {
return err
}
dropImg, _, err := r.captureFull(ctx)
if err != nil {
return err
}
dropScan, err := r.locator.ScanROI(ctx, dropImg, "menu_dropdown", &utilPt)
if err != nil {
return err
}
_, termPt, ok := rules.FindHit(dropScan.Lines, recoveryTerminalLabels, true)
if !ok {
return r.pauseAndWaitResume(ctx, "terminal_menu_missing", "未在「实用工具」下拉菜单中找到「终端」", dropScan.Text)
}
if err := r.waitIfPaused(ctx); err != nil {
return err
}
if err := r.clickOnImage(ctx, dropImg, termPt); err != nil {
return err
}
r.recordRule("recovery.open_terminal_menu_fallback")
checks := 4
if r.opts.DisableSleep {
checks = 1
}
o2, s2, wErr := r.waitForTerminalReady(ctx, checks)
if wErr != nil {
return wErr
}
opened = o2
shellReady = s2
}
if !shellReady {
return r.pauseAndWaitResume(ctx, "terminal_not_ready", "恢复终端尚未显示命令提示符,请确认焦点在终端窗口后点击继续", menuScan.Text)
}
}
// 3. Type REIMSHELP offline install command.
if err := r.waitIfPaused(ctx); err != nil {
return err
}
r.recordRule("recovery.offline_install_script")
r.setState(ctx, StageOfflineTerminal, StatusRunning, "正在终端输入并运行离线安装脚本", "")
if _, err := r.host.TypeText(ctx, r.cfg.VM, "sh /Volumes/REIMSHELP/install.sh\n"); err != nil {
return err
}
// 4. Watch terminal output: proceed on formatting/extracting/startosinstall, pause immediately on non-empty disk or error.
for attempt := 0; attempt < 25; attempt++ {
if err := r.waitIfPaused(ctx); err != nil {
return err
}
if err := r.sleep(ctx, r.opts.PollInterval); err != nil {
return err
}
tImg, tMeta, err := r.captureFull(ctx)
if err != nil {
if strings.Contains(err.Error(), "vm_not_running") {
r.setState(ctx, StageInstallWait, StatusRunning, "Installer rebooting into macOS install stage", "")
return nil
}
return err
}
if tMeta.Blank || vision.DetectAppleProgress(tImg) {
r.setState(ctx, StageInstallWait, StatusRunning, "macOS installation started", "")
return nil
}
termScan, err := r.locator.ScanROI(ctx, tImg, "terminal", nil)
if err != nil {
return err
}
if rules.MatchPhrase(termScan.Text, "REIMS_INSTALLPKG_UNSUPPORTED", true) {
r.markProvisionFallbackNeeded()
}
if kw, danger := rules.DetectTerminalHighRiskKeyword(termScan.Text); danger {
return r.pauseAndWaitResume(ctx, "terminal_safety_stop:"+kw, "恢复终端安全暂停("+kw+")", termScan.Text)
}
if terminalShowsInstallProgress(termScan.Text) {
r.setState(ctx, StageInstallWait, StatusRunning, "正在写入 macOS 安装文件(自动监测跨重启进度)", "")
return nil
}
}
return r.pauseAndWaitResume(ctx, "terminal_unconfirmed", "未能确认终端内 install.sh 是否启动,查看终端后点继续", "")
}
func terminalShowsInstallProgress(text string) bool {
for _, okToken := range []string{
"detected blank VM disk",
"Started erase on disk",
"Finished erase on disk",
"Using target volume",
"Macintosh HD",
"Formatting",
"Extracting",
"Copying",
"SharedSupport",
"startosinstall",
"provision.pkg",
"REIMS_INSTALLPKG_UNSUPPORTED",
"Preparing to run macOS Installer",
} {
if rules.MatchPhrase(text, okToken, true) {
return true
}
}
return false
}
// Stage 3: Dual-signal monitor across 2–4 reboots & Win10 cold reboots:
//
// Signal 1 (Zero-OCR): serial console milestone `serial:provision_ready`
// Signal 2 (OCR fallback): Login Screen, Desktop, or Setup Assistant detection
// guarded against false positives while Recovery Terminal is still running.
func (r *Runner) stepInstallWait(ctx context.Context, wd *Watchdog) error {
r.setState(ctx, StageInstallWait, StatusRunning, "正在等待 macOS 跨重启安装完成", "")
var prevFrame image.Image
sawTerminal := false
sawRebootOrProgress := false
confirmStreak := 0
requiredConfirms := 2
if r.opts.DisableSleep {
requiredConfirms = 1
}
initialXNU := -1
initialColdReboots := -1
checkWatchdog := func(tel pluginsdk.VMTelemetry, visualChanged bool) (bool, error) {
if reason, detail, tripped := wd.Check(r.opts.NowFunc(), tel, StageInstallWait, visualChanged); tripped {
if err := r.pauseAndWaitResume(ctx, reason, "Install watchdog paused: "+detail, detail); err != nil {
return false, err
}
wd.ResetAfterResume(r.opts.NowFunc())
return true, nil
}
return false, nil
}
for {
if err := r.waitIfPaused(ctx); err != nil {
return err
}
tel, _ := r.host.Telemetry(ctx, r.cfg.VM)
xnuCount := telemetryMilestoneCount(tel, "serial:xnu")
if initialXNU < 0 {
initialXNU = xnuCount
} else if xnuCount != initialXNU && xnuCount > 0 {
sawRebootOrProgress = true
}
if initialColdReboots < 0 {
initialColdReboots = tel.ColdRebootCount
} else if tel.ColdRebootCount > initialColdReboots {
sawRebootOrProgress = true
}
// Signal 1 (Zero-OCR): one-shot LaunchDaemon emitted REIMS_PROVISION_BOOT_OK on first boot.
if hasBootMilestone(tel, "serial:provision_ready") {
wd.ResetRebootWindow(r.opts.NowFunc())
r.recordRule("provision.serial_ready")
r.setState(ctx, StageFinishInstall, StatusRunning, "检测到首启就绪信号,退出恢复模式并重启", "")
return nil
}
img, meta, err := r.captureFull(ctx)
visualChanged := false
if err == nil && img != nil {
if prevFrame != nil {
visualChanged = vision.FrameDiffRatio(prevFrame, img) > 0.015
}
prevFrame = img
}
// Tolerate brief stopped state during Win10 WHPX cold reboots or installer restarts.
if err != nil {
if errors.Is(err, context.Canceled) || isPermissionDeniedError(err) ||
strings.Contains(err.Error(), "session_paused") ||
strings.Contains(err.Error(), "user_takeover") {
return err
}
if resumed, wdErr := checkWatchdog(tel, visualChanged); wdErr != nil {
return wdErr
} else if resumed {
continue
}
if strings.Contains(err.Error(), "vm_not_running") || strings.Contains(err.Error(), "confirmation_required") {
sawRebootOrProgress = true
confirmStreak = 0
if sErr := r.sleep(ctx, r.opts.Stage3Interval); sErr != nil {
return sErr
}
continue
}
return err
}
if meta.Blank || vision.DetectAppleProgress(img) {
sawRebootOrProgress = true
confirmStreak = 0
if resumed, wdErr := checkWatchdog(tel, visualChanged); wdErr != nil {
return wdErr
} else if resumed {
continue
}
if sErr := r.sleep(ctx, r.opts.Stage3Interval); sErr != nil {
return sErr
}
continue
}
// Guard: while Recovery or Terminal is still on screen, NEVER misclassify
// terminal log timestamps or "Restarting..." lines as installed macOS.
menuScan, _ := r.locator.ScanROI(ctx, img, "menu_bar", nil)
titleScan, _ := r.locator.ScanROI(ctx, img, "title_band", nil)
bodyScan, _ := r.locator.ScanROI(ctx, img, "body", nil)
if isRecoveryOrTerminalScreen(menuScan.Text, titleScan.Text, bodyScan.Text) {
sawTerminal = true
confirmStreak = 0
if resumed, wdErr := checkWatchdog(tel, visualChanged); wdErr != nil {
return wdErr
} else if resumed {
continue
}
if sErr := r.sleep(ctx, r.opts.Stage3Interval); sErr != nil {
return sErr
}
continue
}
// Signal 2 (OCR fallback): evaluate installed macOS screens BEFORE
// tripping non-fatal watchdog checks so a completed install landing on
// Setup Assistant / Login Screen / Desktop advances cleanly instead of
// falsely pausing on boot-cycle counts.
modalScan, _ := r.locator.ScanROI(ctx, img, "modal", nil)
actionScan, _ := r.locator.ScanROI(ctx, img, "action_bar", nil)
loginScan, _ := r.locator.ScanROI(ctx, img, "login_band", nil)
isDesktop := vision.DetectDesktopReady(menuScan.Lines, modalScan.Text)
_, _, isLogin := r.detectLoginScreen(menuScan, titleScan, bodyScan, modalScan, loginScan)
isLoginOrDesktop := isDesktop || isLogin
isSetup := !isLoginOrDesktop && r.matchesSetupAssistant(menuScan, titleScan, bodyScan, modalScan, actionScan, loginScan)
// If we observed Recovery Terminal earlier in this Stage 3 wait and have
// not seen a reboot signal yet, guard Login/Desktop heuristics against
// transient terminal frames; explicit Setup Assistant screens cannot
// occur inside Recovery Terminal.
if sawTerminal && !sawRebootOrProgress && !isSetup {
confirmStreak = 0
if resumed, wdErr := checkWatchdog(tel, visualChanged); wdErr != nil {
return wdErr
} else if resumed {
continue
}
if sErr := r.sleep(ctx, r.opts.Stage3Interval); sErr != nil {
return sErr
}
continue
}
if isLoginOrDesktop || isSetup {
confirmStreak++
if confirmStreak >= requiredConfirms {
wd.ResetRebootWindow(r.opts.NowFunc())
if isLoginOrDesktop {
r.recordRule("provision.login_or_desktop_detected")
r.setState(ctx, StageFinishInstall, StatusRunning, "检测到系统首次启动,正在退出恢复模式并重启", "")
} else {
r.setState(ctx, StageFinishInstall, StatusRunning, "检测到设置助理,正在退出恢复模式并重启", "")
}
return nil
}
if sErr := r.sleep(ctx, 4*time.Second); sErr != nil {
return sErr
}
continue
}
confirmStreak = 0
if resumed, wdErr := checkWatchdog(tel, visualChanged); wdErr != nil {
return wdErr
} else if resumed {
continue
}
if sErr := r.sleep(ctx, r.opts.Stage3Interval); sErr != nil {
return sErr
}
}
}
func (r *Runner) isFinishInstallDone() bool {
r.mu.Lock()
defer r.mu.Unlock()
return r.cp.FinishInstallDone
}
func (r *Runner) markProvisionFallbackNeeded() {
var (
seq uint64
snap Checkpoint
save bool
)
r.mu.Lock()
if !r.cp.ProvisionFallbackNeeded {
r.cp.ProvisionFallbackNeeded = true
seq, snap = r.snapshotCheckpointLocked()
save = true
}
r.mu.Unlock()
if save {
r.persistCheckpoint(seq, snap)
}
}
func (r *Runner) isProvisionFallbackNeeded() bool {
r.mu.Lock()
defer r.mu.Unlock()
return r.cp.ProvisionFallbackNeeded
}
func hasBootMilestone(tel pluginsdk.VMTelemetry, key string) bool {
return telemetryMilestoneCount(tel, key) > 0
}
func telemetryMilestoneCount(tel pluginsdk.VMTelemetry, key string) int {
for _, m := range tel.BootMilestones {
if m.Key == key {
if m.Count > 0 {
return m.Count
}
return 1
}
}
return 0
}
func finishInstallNeedsRestart(phase string, res map[string]any) bool {
if !strings.EqualFold(strings.TrimSpace(phase), "normal") || res == nil {
return true
}
// Only skip restart when the driver explicitly reported zero pending hardware/recovery changes.
if _, hasFlags := res["installer_ejected"]; !hasFlags {
return true
}
for _, k := range []string{"installer_ejected", "network_enabled", "upgraded_nvme", "recovery_pending", "helper_stripped"} {
if v, _ := res[k].(bool); v {
return true
}
}
return false
}
// Stage 4: Eject installer, strip REIMSHELP & REIMSPROV, enable network (never mount REIMSTOOLS), and restart VM.
func (r *Runner) stepFinishInstall(ctx context.Context, wd *Watchdog) error {
if err := r.waitIfPaused(ctx); err != nil {
return err
}
if !r.isFinishInstallDone() {
tel, _ := r.host.Telemetry(ctx, r.cfg.VM)
r.setState(ctx, StageFinishInstall, StatusRunning, "正在退出恢复模式并启用网络", "")
res, err := r.host.FinishInstall(ctx, r.cfg.VM)
if err != nil {
return err
}
r.mu.Lock()
r.cp.FinishInstallDone = true
seq, snap := r.snapshotCheckpointLocked()
r.mu.Unlock()
r.persistCheckpoint(seq, snap)
if finishInstallNeedsRestart(tel.Phase, res) {
if err := r.waitIfPaused(ctx); err != nil {
return err
}
r.setState(ctx, StageFinishInstall, StatusRunning, "正在重启进入已安装的 macOS", "")
if _, err := r.host.RestartVM(ctx, r.cfg.VM); err != nil {
return err
}
wd.ResetRebootWindow(r.opts.NowFunc())
}
}
nextMsg := "Waiting for Setup Assistant after restart"
if r.cfg.IsRecoveryOnly() {
nextMsg = "正在等待重启进入 macOS 系统"
} else if r.cfg.HasProvisionDisk && !r.isProvisionFallbackNeeded() {
nextMsg = "Waiting for macOS login screen after restart"
}
r.setState(ctx, StageSetupAssistant, StatusRunning, nextMsg, "")
return r.sleep(ctx, r.opts.PostActionWait)
}
// Stage 5: In recovery_only mode, confirm macOS booted post-restart and release
// input cleanly. In full mode, unlock Login Screen via DPAPI TypeSecret and run
// the declarative JSON rule loop for any remaining Setup Assistant pages.
func (r *Runner) stepSetupAssistant(ctx context.Context, wd *Watchdog) error {
lastRuleID := ""
sameRuleRetries := 0
unknownStreak := 0
loginAttempts := 0
clockWakeAttempted := false
checkWatchdog := func(tel pluginsdk.VMTelemetry) (bool, error) {
if reason, detail, tripped := wd.Check(r.opts.NowFunc(), tel, StageSetupAssistant, false); tripped {
if err := r.pauseAndWaitResume(ctx, reason, "Watchdog paused during Setup Assistant: "+detail, detail); err != nil {
return false, err
}
wd.ResetAfterResume(r.opts.NowFunc())
return true, nil
}
return false, nil
}
for {
if err := r.waitIfPaused(ctx); err != nil {
return err
}
tel, _ := r.host.Telemetry(ctx, r.cfg.VM)
img, meta, err := r.captureFull(ctx)
if err != nil {
if errors.Is(err, context.Canceled) || isPermissionDeniedError(err) ||
strings.Contains(err.Error(), "session_paused") ||
strings.Contains(err.Error(), "user_takeover") {
return err
}
if resumed, wdErr := checkWatchdog(tel); wdErr != nil {
return wdErr
} else if resumed {
continue
}
if strings.Contains(err.Error(), "vm_not_running") || strings.Contains(err.Error(), "confirmation_required") {
if sErr := r.sleep(ctx, r.opts.PollInterval); sErr != nil {
return sErr
}
continue
}
return err
}
if meta.Blank || vision.DetectAppleProgress(img) {
if resumed, wdErr := checkWatchdog(tel); wdErr != nil {
return wdErr
} else if resumed {
continue
}
if sErr := r.sleep(ctx, r.opts.PollInterval); sErr != nil {
return sErr
}
continue
}
// Check if we already reached Desktop or Keyboard Setup Assistant.
menuScan, err := r.locator.ScanROI(ctx, img, "menu_bar", nil)
if err != nil {
return err
}
modalScan, err := r.locator.ScanROI(ctx, img, "modal", nil)
if err != nil {
return err
}
if r.cfg.IsRecoveryOnly() {
if vision.DetectDesktopReady(menuScan.Lines, modalScan.Text) {
r.completeRecoveryOnly(ctx)
return nil
}
if _, ok := r.rules.MatchScreen("desktop", map[string]string{"modal": modalScan.Text, "full": modalScan.Text}); ok {
r.completeRecoveryOnly(ctx)
return nil
}
titleScan, err := r.locator.ScanROI(ctx, img, "title_band", nil)
if err != nil {
return err
}
bodyScan, err := r.locator.ScanROI(ctx, img, "body", nil)
if err != nil {
return err
}
if isRecoveryOrTerminalScreen(menuScan.Text, titleScan.Text, bodyScan.Text) {
if resumed, wdErr := checkWatchdog(tel); wdErr != nil {
return wdErr
} else if resumed {
continue
}
if sErr := r.sleep(ctx, r.opts.PollInterval); sErr != nil {
return sErr
}
continue
}
actionScan, _ := r.locator.ScanROI(ctx, img, "action_bar", nil)
loginScan, _ := r.locator.ScanROI(ctx, img, "login_band", nil)
isSetup := r.matchesSetupAssistant(menuScan, titleScan, bodyScan, modalScan, actionScan, loginScan)
_, _, isLogin := r.detectLoginScreen(menuScan, titleScan, bodyScan, modalScan, loginScan)
if isSetup || isLogin {
r.completeRecoveryOnly(ctx)
return nil
}
if resumed, wdErr := checkWatchdog(tel); wdErr != nil {
return wdErr
} else if resumed {
continue
}
if sErr := r.sleep(ctx, r.opts.PollInterval); sErr != nil {
return sErr
}
continue
}
if resumed, wdErr := checkWatchdog(tel); wdErr != nil {
return wdErr
} else if resumed {
continue
}
if _, ok := r.rules.MatchScreen("desktop", map[string]string{"modal": modalScan.Text, "full": modalScan.Text}); ok {
r.setState(ctx, StageDesktopReady, StatusRunning, "Closing Keyboard Setup Assistant", "")
return nil
}
if vision.DetectDesktopReady(menuScan.Lines, modalScan.Text) {
r.setState(ctx, StageDesktopReady, StatusRunning, "Verifying usable macOS desktop", "")
return nil
}
titleScan, err := r.locator.ScanROI(ctx, img, "title_band", nil)
if err != nil {
return err
}
bodyScan, err := r.locator.ScanROI(ctx, img, "body", nil)
if err != nil {
return err
}
roiTexts := map[string]string{
"menu_bar": menuScan.Text,
"modal": modalScan.Text,
"title_band": titleScan.Text,
"body": bodyScan.Text,
"full": strings.Join([]string{modalScan.Text, titleScan.Text, bodyScan.Text}, "\n"),
}
rule, matched := r.rules.MatchScreen("setup_assistant", roiTexts)
if !matched {
// Provisioned macOS lands directly on the macOS Login Screen (bottom login_band on Sonoma/Sequoia/Tahoe): unlock via DPAPI TypeSecret.
loginScan, _ := r.locator.ScanROI(ctx, img, "login_band", nil)
if loginPt, confident, isLogin := r.detectLoginScreen(menuScan, titleScan, bodyScan, modalScan, loginScan); isLogin {
unknownStreak = 0
if err := r.tryUnlockLoginScreen(ctx, img, loginPt, confident, roiTexts["full"], &loginAttempts, &clockWakeAttempted); err != nil {
return err
}
continue
}
if kw, danger := rules.DetectHighRiskKeyword(roiTexts["full"]); danger {
return r.pauseAndWaitResume(ctx, "high_risk_unmatched:"+kw, "Paused on high-risk prompt ("+kw+"); complete manually then click Resume", roiTexts["full"])
}
unknownStreak++
if unknownStreak >= 2 {
unknownStreak = 0
if err := r.pauseAndWaitResume(ctx, "unknown_setup_page", "Paused on unrecognized Setup Assistant screen; complete this step and click Resume", roiTexts["full"]); err != nil {
return err
}
} else if err := r.sleep(ctx, r.opts.PollInterval); err != nil {
return err
}
continue
}
unknownStreak = 0
// High-risk keyword safety check when rule does not explicitly allow it.
if !rule.AllowHighRisk {
if kw, danger := rules.DetectHighRiskKeyword(roiTexts["full"]); danger {
return r.pauseAndWaitResume(ctx, "high_risk_guard:"+kw, "Paused for safety ("+kw+") on "+rule.ID, roiTexts["full"])
}
}
if rule.RequiresSLA && !r.cfg.SLAAccepted {
return r.pauseAndWaitResume(ctx, "sla_not_accepted", "Apple SLA confirmation required before clicking Agree", roiTexts["full"])
}
if rule.ID == lastRuleID {
sameRuleRetries++
maxRetries := rule.Verify.MaxRetries
if maxRetries <= 0 {
maxRetries = 2
}
if sameRuleRetries > maxRetries {
sameRuleRetries = 0
if err := r.pauseAndWaitResume(ctx, "retry_limit:"+rule.ID, "Screen did not advance after retrying "+rule.ID+"; complete manually and click Resume", roiTexts["full"]); err != nil {
return err
}
continue
}
} else {
lastRuleID = rule.ID
sameRuleRetries = 0
}
r.setState(ctx, StageSetupAssistant, StatusRunning, "Setup Assistant: "+rule.ID, "")
if err := r.executeRuleActions(ctx, img, meta, rule, bodyScan); err != nil {
return err
}
r.recordRule(rule.ID)
if err := r.waitAfterRuleAction(ctx, img, rule); err != nil {
return err
}
}
}
// waitAfterRuleAction sleeps PostActionWait and, when the rule declares a longer
// verify.wait_change_ms budget, waits for a visual frame change before letting
// the loop retry the same rule on slow transitions (e.g. create_account / terms).
func (r *Runner) waitAfterRuleAction(ctx context.Context, beforeImg image.Image, rule rules.Rule) error {
if err := r.sleep(ctx, r.opts.PostActionWait); err != nil {
return err
}
budget := time.Duration(rule.Verify.WaitChangeMS) * time.Millisecond
if r.opts.DisableSleep || beforeImg == nil || budget <= r.opts.PostActionWait {
return nil
}
step := r.opts.PostActionWait
if step < 500*time.Millisecond {
step = 500 * time.Millisecond
}
if step > 2*time.Second {
step = 2 * time.Second
}
deadline := r.opts.NowFunc().Add(budget - r.opts.PostActionWait)
for {
if err := r.waitIfPaused(ctx); err != nil {
return err
}
nextImg, nextMeta, err := r.captureFull(ctx)
if err != nil {
if errors.Is(err, context.Canceled) || isPermissionDeniedError(err) ||
strings.Contains(err.Error(), "vm_not_running") ||
strings.Contains(err.Error(), "session_paused") ||
strings.Contains(err.Error(), "user_takeover") {
return err
}
return nil
}
if nextMeta.Blank || nextImg == nil || vision.FrameDiffRatio(beforeImg, nextImg) > 0.015 {
return nil
}
rem := deadline.Sub(r.opts.NowFunc())
if rem <= 0 {
return nil
}
if rem > step {
rem = step
}
if err := r.sleep(ctx, rem); err != nil {
return err
}
}
}
func (r *Runner) executeRuleActions(ctx context.Context, img image.Image, meta hostclient.ScreenshotMeta, rule rules.Rule, bodyScan vision.ROIScan) error {
for _, act := range rule.Actions {
if err := r.waitIfPaused(ctx); err != nil {
return err
}
switch act.Op {
case "key":
if err := r.host.KeyPress(ctx, r.cfg.VM, act.Key, act.Modifiers...); err != nil {
return err
}
case "click_circle_or_key":
b := img.Bounds()
roi := vision.ResolveROI(act.ROI, b.Dx(), b.Dy(), nil)
if pt, ok := vision.DetectCircularButton(img, roi); ok {
if err := r.clickOnImage(ctx, img, pt); err != nil {
return err
}
} else {
k := act.FallbackKey
if k == "" {
k = "spc"
}
if err := r.host.KeyPress(ctx, r.cfg.VM, k); err != nil {
return err
}
}
case "click_ocr":
scan, err := r.locator.ScanROI(ctx, img, act.ROI, nil)
if err != nil {
return err
}
_, pt, ok := rules.FindHit(scan.Lines, act.AnyOf, act.Fuzzy)
if !ok {
// Fallback to blue button scan in the same ROI.
btns, _ := r.locator.ScanButtons(ctx, img, act.ROI)
for _, b := range btns {
for _, cand := range act.AnyOf {
if rules.MatchPhrase(b.Text, cand, act.Fuzzy) {
pt, ok = b.Center, true
break
}
}
if ok {
break
}
}
}
if !ok {
return r.pauseAndWaitResume(ctx, "control_not_found:"+rule.ID, "Target button not found on "+rule.ID, scan.Text)
}
if err := r.clickOnImage(ctx, img, pt); err != nil {
return err
}
case "click_blue_button":
btns, err := r.locator.ScanButtons(ctx, img, act.ROI)
if err != nil {
return err
}
var target image.Point
found := false
for _, b := range btns {
if !b.Enabled {
continue
}
for _, cand := range act.AnyOf {
if rules.MatchPhrase(b.Text, cand, act.Fuzzy) {
target, found = b.Center, true
break
}
}
if found {
break
}
}
if !found {
scan, err := r.locator.ScanROI(ctx, img, act.ROI, nil)
if err == nil {
if _, pt, ok := rules.FindHit(scan.Lines, act.AnyOf, act.Fuzzy); ok {
target, found = pt, true
}
}
}
if !found && len(btns) == 1 && btns[0].Enabled {
target, found = btns[0].Center, true
}
if !found {
return r.pauseAndWaitResume(ctx, "blue_button_not_found:"+rule.ID, "Primary button not ready on "+rule.ID, "")
}
if err := r.clickOnImage(ctx, img, target); err != nil {
return err
}
case "ensure_checkbox":
scan, err := r.locator.ScanROI(ctx, img, act.ROI, nil)
if err != nil {
return err
}
if ln, _, ok := rules.FindHit(scan.Lines, act.AnyOf, act.Fuzzy); ok {
checked, _, boxPt := vision.ProbeCheckboxState(img, ln.Rect)
want := false
if act.WantChecked != nil {
want = *act.WantChecked
}
if checked != want {
if err := r.clickOnImage(ctx, img, boxPt); err != nil {
return err
}
}
}
case "select_pref_ocr":
cands := r.preferenceCandidates(act.PrefKey)
if len(cands) > 0 {
if _, pt, ok := rules.FindHit(bodyScan.Lines, cands, true); ok {
if err := r.clickOnImage(ctx, img, pt); err != nil {
return err
}
}
}
case "fill_account_form":
if err := r.fillAccountForm(ctx, img, meta, bodyScan); err != nil {
return err
}
case "pause_for_user":
return r.pauseAndWaitResume(ctx, act.PauseReason, "Paused for user action on "+rule.ID, bodyScan.Text)
}
}
return nil
}
func (r *Runner) preferenceCandidates(prefKey string) []string {
switch prefKey {
case "appearance":
switch strings.ToLower(r.cfg.Appearance) {
case "dark":
return []string{"Dark", "深色"}
case "light":
return []string{"Light", "浅色", "淺色"}
default:
return []string{"Auto", "自动", "自動"}
}
case "age_range":
return []string{"18 or older", "Adult", "18 岁及以上", "成年"}
default:
return nil
}
}
// findFormFieldLabel prefers exact or short form-field label lines (e.g.
// "Password" / "密码:") over longer instructional sentences containing the word
// "password", preventing clicks on subtitle text that would leave a plaintext
// field focused before TypeSecret runs.
func findFormFieldLabel(lines []ocr.Line, labels []string) (ocr.Line, bool) {
// Pass 1: exact normalized full-line match (strips trailing ":" / ":").
for _, cand := range labels {
want := rules.NormalizeText(cand)
if want == "" {
continue
}
for _, ln := range lines {
if !ln.Rect.Empty() && rules.NormalizeText(ln.Text) == want {
return ln, true
}
}
}
// Pass 2: short label line (<= 20 compact runes) matching candidate.
for _, cand := range labels {
for _, ln := range lines {
if !ln.Rect.Empty() && compactRuneCount(ln.Text) <= 20 && rules.MatchPhrase(ln.Text, cand, true) {
return ln, true
}
}
}
return ocr.Line{}, false
}
func (r *Runner) tryUnlockLoginScreen(ctx context.Context, img image.Image, loginPt image.Point, confident bool, fullText string, loginAttempts *int, clockWakeAttempted *bool) error {
if !confident {
// Clock-header-only frames can resemble screensavers or non-password overlays.
// Never inject a DPAPI secret blindly without an explicit password prompt or
// confirmed user login chrome: send one harmless Shift key to wake the login
// pill, and if still unconfirmed pause for the user.
if !*clockWakeAttempted {
*clockWakeAttempted = true
if err := r.host.KeyPress(ctx, r.cfg.VM, "shift"); err != nil {
return err
}
return r.sleep(ctx, r.opts.PostActionWait)
}
*clockWakeAttempted = false
return r.pauseAndWaitResume(ctx, "login_screen_unconfirmed", "检测到锁屏时钟界面但未定位到密码输入框,请手动输入密码后点击继续", fullText)
}
*clockWakeAttempted = false
*loginAttempts++
if *loginAttempts > 3 {
*loginAttempts = 0
return r.pauseAndWaitResume(ctx, "login_unlock_failed", "macOS 登录界面未能自动解锁,手动输入密码后点击继续", fullText)
}
r.setState(ctx, StageSetupAssistant, StatusRunning, "Unlocking provisioned macOS login screen via DPAPI credential", "")
if loginPt != (image.Point{}) {
if err := r.clickOnImage(ctx, img, loginPt); err != nil {
return err
}
if err := r.sleep(ctx, r.opts.PostActionWait); err != nil {
return err
}
}
beforeImg, _, bErr := r.captureFull(ctx)
if bErr != nil || beforeImg == nil {
beforeImg = img
}
if _, err := r.host.TypeSecret(ctx, r.cfg.VM, r.cfg.SecretSetting); err != nil {
return err
}
// Verify mask bullet pixels changed in the password field region before
// pressing Return so we never submit or retry credentials into a non-password control.
afterImg, _, aErr := r.captureFull(ctx)
if aErr != nil || beforeImg == nil || afterImg == nil {
if *loginAttempts > 0 {
*loginAttempts--
}
return r.pauseAndWaitResume(ctx, "login_unlock_failed", "未能截取登录密码框输入反馈画面,请手动输入密码后点击继续", fullText)
}
b := afterImg.Bounds()
maskROI := vision.ResolveROI("login_band", b.Dx(), b.Dy(), nil).Add(b.Min)
if loginPt != (image.Point{}) {
clickBox := image.Rect(loginPt.X-180, loginPt.Y-36, loginPt.X+180, loginPt.Y+44).Intersect(b)
if !clickBox.Empty() {
maskROI = maskROI.Union(clickBox)
}
}
if !vision.DetectMaskDotsDelta(beforeImg, afterImg, maskROI) {
*loginAttempts = 0
return r.pauseAndWaitResume(ctx, "login_unlock_failed", "未检测到登录密码框输入反馈,请手动输入密码后点击继续", fullText)
}
if err := r.host.KeyPress(ctx, r.cfg.VM, "ret"); err != nil {
return err
}
r.recordRule("provision.login_unlock")
waitDur := r.opts.PostActionWait
if waitDur < 3*time.Second {
waitDur = 3 * time.Second
}
return r.sleep(ctx, waitDur)
}
func (r *Runner) fillAccountForm(ctx context.Context, img image.Image, _ hostclient.ScreenshotMeta, bodyScan vision.ROIScan) error {
// 1. Full Name (non-secret ASCII via console.type).
if ln, ok := findFormFieldLabel(bodyScan.Lines, []string{"Full Name", "全名"}); ok {
if pt, _, found := vision.DetectInputFieldNearLabel(img, ln.Rect); found {
if err := r.clickOnImage(ctx, img, pt); err != nil {
return err
}
if err := r.host.KeyPress(ctx, r.cfg.VM, "a", "meta_l"); err != nil {
return err
}
if _, err := r.host.TypeText(ctx, r.cfg.VM, r.cfg.FullName); err != nil {
return err
}
}
}
// 2. Account Name (select-all + overwrite auto-filled shortname).
if ln, ok := findFormFieldLabel(bodyScan.Lines, []string{"Account Name", "账户名称", "帳號名稱"}); ok {
if pt, _, found := vision.DetectInputFieldNearLabel(img, ln.Rect); found {
if err := r.clickOnImage(ctx, img, pt); err != nil {
return err
}
if err := r.host.KeyPress(ctx, r.cfg.VM, "a", "meta_l"); err != nil {
return err
}
if _, err := r.host.TypeText(ctx, r.cfg.VM, r.cfg.AccountName); err != nil {
return err
}
}
}
// 3. Password & Verify strictly via DPAPI host/console.typeSecret (never OCR password fields).
passwordFieldsFilled := 0
for _, labels := range [][]string{
{"Password", "密码", "密碼"},
{"Verify", "验证", "驗證"},
} {
ln, ok := findFormFieldLabel(bodyScan.Lines, labels)
if !ok {
return r.pauseAndWaitResume(ctx, "account_form_incomplete", "Could not locate Password and Verify fields safely; fill the account form manually and click Resume", bodyScan.Text)
}
pt, fieldRect, found := vision.DetectInputFieldNearLabel(img, ln.Rect)
if !found {
return r.pauseAndWaitResume(ctx, "account_form_incomplete", "Could not confirm Password/Verify input box next to label; fill the account form manually and click Resume", bodyScan.Text)
}
beforeImg, _, _ := r.captureFull(ctx)
if beforeImg == nil {
beforeImg = img
}
if err := r.clickOnImage(ctx, img, pt); err != nil {
return err
}
if err := r.host.KeyPress(ctx, r.cfg.VM, "a", "meta_l"); err != nil {
return err
}
if _, err := r.host.TypeSecret(ctx, r.cfg.VM, r.cfg.SecretSetting); err != nil {
return err
}
// Verify bullet mask delta without ever sending password box to OCR.
afterImg, _, aErr := r.captureFull(ctx)
if aErr != nil || afterImg == nil || !vision.DetectMaskDotsDelta(beforeImg, afterImg, fieldRect) {
return r.pauseAndWaitResume(ctx, "account_form_incomplete", "Could not verify password bullet input in Password/Verify field; fill the account form manually and click Resume", bodyScan.Text)
}
passwordFieldsFilled++
}
if passwordFieldsFilled < 2 {
return r.pauseAndWaitResume(ctx, "account_form_incomplete", "Could not locate Password and Verify fields safely; fill the account form manually and click Resume", bodyScan.Text)
}
return nil
}
func (r *Runner) looksLikeSetupAssistant(ctx context.Context, img image.Image) bool {
menuScan, _ := r.locator.ScanROI(ctx, img, "menu_bar", nil)
titleScan, err := r.locator.ScanROI(ctx, img, "title_band", nil)
if err != nil {
return false
}
bodyScan, _ := r.locator.ScanROI(ctx, img, "body", nil)
modalScan, _ := r.locator.ScanROI(ctx, img, "modal", nil)
actionScan, _ := r.locator.ScanROI(ctx, img, "action_bar", nil)
loginScan, _ := r.locator.ScanROI(ctx, img, "login_band", nil)
return r.matchesSetupAssistant(menuScan, titleScan, bodyScan, modalScan, actionScan, loginScan)
}
func (r *Runner) matchesSetupAssistant(menuScan, titleScan, bodyScan, modalScan, actionScan, loginScan vision.ROIScan) bool {
if isRecoveryOrTerminalScreen(menuScan.Text, titleScan.Text, bodyScan.Text) {
return false
}
roiTexts := map[string]string{
"menu_bar": menuScan.Text,
"modal": modalScan.Text,
"title_band": titleScan.Text,
"body": bodyScan.Text,
"full": strings.Join([]string{modalScan.Text, titleScan.Text, bodyScan.Text}, "\n"),
}
if r.rules != nil {
if _, ok := r.rules.MatchScreen("setup_assistant", roiTexts); ok {
return true
}
}
return looksLikeSetupAssistantFallback(titleScan.Text, bodyScan.Text, actionScan.Text, loginScan.Text)
}
func looksLikeSetupAssistantFallback(titleText, bodyText, actionText, loginText string) bool {
footer := actionText + "\n" + loginText
for _, phrase := range []string{
"set up your mac",
"using voiceover",
"command-option-f5",
"view accessibility options",
"旁白设置",
"通过旁白",
"听取如何通过",
"查看辅助功能选项",
"檢視輔助使用選項",
"voiceoverを使って",
} {
if rules.MatchPhrase(footer, phrase, true) {
return true
}
}
// Detect the alphabetical Country/Region list in Setup Assistant when at
// least two distinct entries appear together in body/title.
regionText := titleText + "\n" + bodyText
countryHits := 0
for _, country := range []string{
"阿尔巴尼亚", "阿尔及利亚", "阿富汗", "阿拉伯联合酋长国", "阿鲁巴", "阿塞拜疆",
"阿爾巴尼亞", "阿爾及利亞",
"afghanistan", "albania", "algeria", "andorra", "angola",
"アイスランド", "アイルランド", "アゼルバイジャン", "アフガニスタン",
} {
if rules.MatchPhrase(regionText, country, true) {
countryHits++
if countryHits >= 2 {
return true
}
}
}
return false
}
func (r *Runner) looksLikeDesktop(ctx context.Context, img image.Image) bool {
menuScan, err := r.locator.ScanROI(ctx, img, "menu_bar", nil)
if err != nil {
return false
}
modalScan, _ := r.locator.ScanROI(ctx, img, "modal", nil)
return vision.DetectDesktopReady(menuScan.Lines, modalScan.Text)
}
func (r *Runner) looksLikeLoginScreen(ctx context.Context, img image.Image) bool {
menuScan, _ := r.locator.ScanROI(ctx, img, "menu_bar", nil)
titleScan, err := r.locator.ScanROI(ctx, img, "title_band", nil)
if err != nil {
return false
}
bodyScan, _ := r.locator.ScanROI(ctx, img, "body", nil)
modalScan, _ := r.locator.ScanROI(ctx, img, "modal", nil)
loginScan, _ := r.locator.ScanROI(ctx, img, "login_band", nil)
_, _, ok := r.detectLoginScreen(menuScan, titleScan, bodyScan, modalScan, loginScan)
return ok
}
var (
reLockClockTime = regexp.MustCompile(`(?:[01]?\d|2[0-3])\s*[::]\s*[0-5]\d`)
reLogTimeWithSecs = regexp.MustCompile(`\d{1,2}\s*[::]\s*\d{2}\s*[::]\s*\d{2}`)
reFourDigitYear = regexp.MustCompile(`\b20\d{2}\b`)
reLockDateEN = regexp.MustCompile(`\b(?:mon|monday|tue|tuesday|wed|wednesday|thu|thursday|fri|friday|sat|saturday|sun|sunday|jan|january|feb|february|mar|march|apr|april|may|jun|june|jul|july|aug|august|sep|sept|september|oct|october|nov|november|dec|december)\b`)
reLockDateCJK = regexp.MustCompile(`(?:\d{1,2}\s*月\s*\d{1,2}\s*日|周\s*[一二三四五六日天]|星期\s*[一二三四五六日天]|[월화수목금토일]요일)`)
)
func compactRuneCount(s string) int {
n := 0
for _, r := range s {
if r != ' ' && r != '\t' && r != '\n' && r != '\r' {
n++
}
}
return n
}
// isRecoveryOrTerminalScreen returns true when the frame clearly shows macOS
// Recovery utilities, Terminal, or startosinstall shell output.
func isRecoveryOrTerminalScreen(menuText, titleText, bodyText string) bool {
for _, menuTok := range []string{
"Terminal", "终端", "終端機", "ターミナル",
"Utilities", "实用工具", "工具程式", "ユーティリティ",
"Recovery", "恢复", "恢復",
"Shell", "Edit", "编辑", "編輯", "File", "文件", "Window", "窗口", "視窗",
} {
if rules.MatchPhrase(menuText, menuTok, true) {
return true
}
}
combined := titleText + "\n" + bodyText
if terminalLooksReady(combined) || terminalShowsInstallProgress(combined) {
return true
}
for _, recTok := range []string{
"Reinstall macOS", "重新安装 macOS", "重新安裝 macOS",
"Disk Utility", "磁盘工具", "磁碟工具程式",
"REIMSHELP", "REIMSPROV", "install.sh", "agreetolicense", "diskutil",
} {
if rules.MatchPhrase(combined, recTok, true) {
return true
}
}
return false
}
// looksLikeMacOSLockClockHeader matches the large centered date + clock header
// rendered in title_band (Y=8%–36%) on macOS Sonoma / Sequoia / Tahoe Lock and
// Login screens, strictly rejecting Terminal logs, Recovery, Desktop, and
// Setup Assistant screens.
func looksLikeMacOSLockClockHeader(menuText, titleText, bodyText string) bool {
if strings.TrimSpace(titleText) == "" {
return false
}
if isRecoveryOrTerminalScreen(menuText, titleText, bodyText) {
return false
}
for _, nonLogin := range []string{"Finder", "访达", "訪達"} {
if rules.MatchPhrase(menuText, nonLogin, true) {
return false
}
}
// On Sonoma/Sequoia/Tahoe Lock Screen, title_band holds ONLY the short date+clock
// header (<= 40 non-space runes) and body (Y=26%-80%) is clean wallpaper (<= 16 runes).
if compactRuneCount(titleText) > 40 || compactRuneCount(bodyText) > 16 {
return false
}
// Terminal/log lines often include years (2026-...), seconds (08:54:12), or shell punctuation.
if reFourDigitYear.MatchString(titleText) || reLogTimeWithSecs.MatchString(titleText) {
return false
}
if strings.ContainsAny(titleText, `[]/\=%#$_;"<>|`) {
return false
}
if !reLockClockTime.MatchString(titleText) {
return false
}
low := strings.ToLower(titleText)
return reLockDateCJK.MatchString(titleText) || reLockDateEN.MatchString(low)
}
// detectLoginScreen identifies the macOS Login Window (after Setup Assistant is
// skipped by REIMSPROV, including Sonoma/Sequoia/Tahoe's bottom-anchored login
// pill in login_band and large centered date+clock header in title_band) and
// returns an optional click point, whether the match has explicit password/user
// confidence (safe for DPAPI password injection), and whether a login screen
// was detected.
func (r *Runner) detectLoginScreen(menuScan, titleScan, bodyScan, modalScan, loginScan vision.ROIScan) (image.Point, bool, bool) {
if isRecoveryOrTerminalScreen(menuScan.Text, titleScan.Text, bodyScan.Text) {
return image.Point{}, false, false
}
scans := []vision.ROIScan{loginScan, bodyScan, modalScan, titleScan}
var allLines []ocr.Line
var textParts []string
for _, sc := range scans {
allLines = append(allLines, sc.Lines...)
if sc.Text != "" {
textParts = append(textParts, sc.Text)
}
}
fullText := strings.Join(textParts, "\n")
promptPhrases := []string{
"Touch ID or Enter Password",
"Your password is required to log in",
"Enter Password",
"触控 ID 或输入密码",
"Touch ID 或输入密码",
"你必须输入密码才能登录",
"必须输入密码才能登录",
"输入密码",
"輸入密碼",
"パスワードを入力",
}
if _, pt, ok := rules.FindHit(allLines, promptPhrases, true); ok {
return pt, true, true
}
for _, phrase := range promptPhrases {
if rules.MatchPhrase(fullText, phrase, true) {
return image.Point{}, true, true
}
}
// Only match account name inside bottom login_band when body is clean wallpaper
// (never inside Terminal output where e.g. "test" + "Restarting..." appear).
if compactRuneCount(bodyScan.Text) <= 24 {
for _, name := range []string{strings.TrimSpace(r.cfg.FullName), strings.TrimSpace(r.cfg.AccountName)} {
if len(name) < 2 {
continue
}
if _, pt, ok := rules.FindHit(loginScan.Lines, []string{name}, false); ok {
for _, chrome := range []string{"Shut Down", "Restart", "Sleep", "Cancel", "关机", "重新启动", "睡眠", "取消", "登录", "密码", "Password", "Log In"} {
if rules.MatchPhrase(loginScan.Text, chrome, true) {
return pt, true, true
}
}
}
}
}
// Sonoma/Sequoia/Tahoe Login Window renders a large centered date+clock
// header in title_band even when the tiny frosted password pill at Y=90%
// sits over complex wallpaper or low-contrast glass. Mark confident=false so
// callers never blindly inject passwords without explicit prompt verification.
if looksLikeMacOSLockClockHeader(menuScan.Text, titleScan.Text, bodyScan.Text) {
return image.Point{}, false, true
}
return image.Point{}, false, false
}
// Stage 6: Close Keyboard Setup Assistant if open and require 2 consecutive desktop-ready frames.
func (r *Runner) stepDesktopReady(ctx context.Context) error {
stableHits := 0
for attempt := 0; attempt < 20; attempt++ {
if err := r.waitIfPaused(ctx); err != nil {
return err
}
img, meta, err := r.captureFull(ctx)
if err != nil {
if strings.Contains(err.Error(), "vm_not_running") || strings.Contains(err.Error(), "confirmation_required") {
if sErr := r.sleep(ctx, r.opts.PollInterval); sErr != nil {
return sErr
}
continue
}
return err
}
if meta.Blank {
stableHits = 0
if err := r.sleep(ctx, r.opts.PollInterval); err != nil {
return err
}
continue
}
modalScan, err := r.locator.ScanROI(ctx, img, "modal", nil)
if err != nil {
return err
}
if rule, ok := r.rules.MatchScreen("desktop", map[string]string{"modal": modalScan.Text, "full": modalScan.Text}); ok {
if err := r.waitIfPaused(ctx); err != nil {
return err
}
r.recordRule(rule.ID)
stableHits = 0
if err := r.host.KeyPress(ctx, r.cfg.VM, "q", "meta_l"); err != nil {
return err
}
if err := r.sleep(ctx, r.opts.PostActionWait); err != nil {
return err
}
continue
}
menuScan, err := r.locator.ScanROI(ctx, img, "menu_bar", nil)
if err != nil {
return err
}
if vision.DetectDesktopReady(menuScan.Lines, modalScan.Text) {
stableHits++
if stableHits >= 2 {
if err := r.waitIfPaused(ctx); err != nil {
return err
}
r.setState(ctx, StageDesktopReady, StatusCompleted, "macOS desktop ready", "")
_ = r.host.Notify(ctx, "macOS Auto-Install Complete", "macOS has reached a usable desktop")
return nil
}
} else {
stableHits = 0
}
if err := r.sleep(ctx, r.opts.PollInterval); err != nil {
return err
}
}
return r.pauseAndWaitResume(ctx, "desktop_unconfirmed", "Could not confirm desktop readiness after Setup Assistant", "")
}
func (r *Runner) completeRecoveryOnly(ctx context.Context) {
r.recordRule("recovery_only.system_booted")
r.setState(ctx, StageDesktopReady, StatusCompleted, "已完成恢复模式安装并进入 macOS,画面输入已解锁", "")
_ = r.host.Notify(ctx, "macOS 恢复安装完成", "已自动退出恢复模式并进入系统,现在可操作画面")
}
// ProbeOCR exposes Stage 0 OCR language pack probing for preflight RPCs.
func ProbeOCR(guestLang, dataDir, preferredBackend string) ocr.ProbeReport {
return ocr.Probe(guestLang, dataDir, preferredBackend)
}