Files
Reims-Go/internal/console/manager.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

447 lines
12 KiB
Go

// Package console serializes host-owned QMP console operations per VM.
package console
import (
"context"
"errors"
"fmt"
"path/filepath"
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/Nwflower/reims-go/internal/filelock"
"github.com/Nwflower/reims-go/internal/qmp"
)
const vmLifecycleLockFile = ".reims-go-vm-operation.lock"
// Manager arbitrates screen and input operations so concurrent host features
// never open competing QMP clients for the same VM.
type Manager struct {
mu sync.Mutex
locks map[string]*vmLock
dial func(context.Context, string) (qmpSession, error)
}
type vmLock struct {
semaphore chan struct{}
users int
}
type lockScopeKey struct{}
type lockScope struct {
manager *Manager
key string
active atomic.Bool
}
type qmpSession interface {
qmp.Executor
qmp.QueryExecutor
Screendump(string) (string, error)
Close() error
}
func NewManager() *Manager {
return &Manager{
locks: make(map[string]*vmLock),
dial: func(ctx context.Context, vmDir string) (qmpSession, error) {
return qmp.Dial(ctx, "unix", qmp.SocketPath(vmDir))
},
}
}
// WithVM serializes a lifecycle operation with computer-use requests for the
// same VM. Nested operations inherit the lock scope through their context.
func (m *Manager) WithVM(ctx context.Context, vmDir string, operation func(context.Context) error) error {
return m.withVM(ctx, vmDir, operation)
}
// Forget is retained for lifecycle hooks. Each QMP operation closes its
// connection before returning, so no session remains to release.
func (m *Manager) Forget(_ context.Context, _ string) error {
return nil
}
// Close is retained for the service lifecycle. The manager owns no persistent
// QMP connections.
func (m *Manager) Close() {
}
// Screendump writes one PPM frame while holding the VM's console lock.
func (m *Manager) Screendump(ctx context.Context, vmDir, path string) (string, error) {
var format string
err := m.withConn(ctx, vmDir, func(conn qmpSession) error {
var err error
format, err = conn.Screendump(path)
return err
})
return format, err
}
// ScreendumpDisplay selects a specific guest display under the same console lock.
func (m *Manager) ScreendumpDisplay(ctx context.Context, vmDir, path, device string, head int) (string, error) {
var format string
err := m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
var err error
format, err = qmp.ScreendumpDisplay(conn, path, device, head)
return err
})
return format, err
}
// TypeText sends US-layout key strokes as one serialized console job.
func (m *Manager) TypeText(ctx context.Context, vmDir, text string, progress func(done, total int)) (int, error) {
strokes, err := qmp.Strokes(text)
if err != nil {
return 0, err
}
if len(strokes) == 0 {
return 0, errors.New("nothing to type")
}
done := 0
err = m.withConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.TypeStrokes(ctx, conn, strokes, 20*time.Millisecond, 15*time.Millisecond, func(n int) {
done = n
if progress != nil {
progress(n, len(strokes))
}
})
})
return done, err
}
// SendAbsoluteClickAndPaste clicks at normalized coordinates and presses Command+V
// while holding the VM's exclusive console lock.
func (m *Manager) SendAbsoluteClickAndPaste(ctx context.Context, vmDir string, normX, normY float64, activateClick bool, commandKey string, focusWait time.Duration) error {
if focusWait <= 0 {
focusWait = 120 * time.Millisecond
}
return m.withConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.ClickAndPaste(ctx, conn, normX, normY, activateClick, 550*time.Millisecond, 25*time.Millisecond, focusWait, 25*time.Millisecond, commandKey)
})
}
// SendPasteShortcut sends Command+V through the same exclusive console path.
func (m *Manager) SendPasteShortcut(ctx context.Context, vmDir string) error {
return m.SendPasteShortcutCombo(ctx, vmDir, "")
}
// SendPasteShortcutCombo presses a guest's paste combination (such as
// "ctrl+shift+v") through the exclusive console path; an empty combo means
// the macOS default.
func (m *Manager) SendPasteShortcutCombo(ctx context.Context, vmDir, combo string) error {
if strings.TrimSpace(combo) == "" {
combo = qmp.DefaultPasteCombo
}
key, modifiers, err := qmp.ParseKeyCombo(combo)
if err != nil {
return err
}
return m.withConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.PressCombo(ctx, conn, 25*time.Millisecond, key, modifiers...)
})
}
func (m *Manager) PointerAvailable(ctx context.Context, vmDir string) (bool, error) {
var available bool
err := m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
mice, err := qmp.QueryMice(conn)
if err == nil {
available = qmp.HasCurrentAbsoluteMouse(mice)
}
return err
})
return available, err
}
func (m *Manager) MouseMove(ctx context.Context, vmDir string, x, y, width, height int) error {
return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.MouseMove(conn, x, y, width, height)
})
}
func (m *Manager) MouseButton(ctx context.Context, vmDir, button string, down bool) error {
return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.MouseButton(conn, button, down)
})
}
func (m *Manager) MouseButtonAt(ctx context.Context, vmDir string, x, y, width, height int, button string, down bool) error {
return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.MouseButtonAt(conn, x, y, width, height, button, down)
})
}
func (m *Manager) SendKey(ctx context.Context, vmDir, key string, down bool) error {
return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.SendKey(conn, key, down)
})
}
func (m *Manager) ReleaseInputs(ctx context.Context, vmDir string, keys, buttons []string) error {
return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.ReleaseInputs(conn, keys, buttons)
})
}
func (m *Manager) MouseClick(ctx context.Context, vmDir, button string) error {
return m.withConn(ctx, vmDir, func(conn qmpSession) error {
if err := qmp.MouseButton(conn, button, true); err != nil {
return err
}
released := false
defer func() {
if !released {
_ = qmp.MouseButton(conn, button, false)
}
}()
timer := time.NewTimer(50 * time.Millisecond)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
}
if err := qmp.MouseButton(conn, button, false); err != nil {
return err
}
released = true
return nil
})
}
func (m *Manager) MouseScroll(ctx context.Context, vmDir string, delta int, horizontal bool) error {
return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.MouseScroll(conn, delta, horizontal)
})
}
func (m *Manager) PressKey(ctx context.Context, vmDir, key string, modifiers ...string) error {
key, err := normalizeKeyCode(key)
if err != nil {
return err
}
normalizedModifiers := make([]string, len(modifiers))
for i, modifier := range modifiers {
normalizedModifiers[i], err = normalizeModifier(modifier)
if err != nil {
return err
}
}
return m.withConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.PressCombo(ctx, conn, 25*time.Millisecond, key, normalizedModifiers...)
})
}
func normalizeKeyCode(key string) (string, error) {
if key == " " {
return "spc", nil
}
code := strings.ToLower(strings.TrimSpace(key))
switch code {
case "space":
code = "spc"
case "escape":
code = "esc"
case "enter", "return":
code = "ret"
case "pageup":
code = "page_up"
case "pagedown":
code = "page_down"
}
if code == "" {
return "", errors.New("key is required")
}
for _, r := range code {
if (r < 'a' || r > 'z') && (r < '0' || r > '9') && r != '_' {
return "", fmt.Errorf("unsupported key code %q", key)
}
}
return code, nil
}
// NormalizeHeldKey maps a key or modifier name to the QMP key code that
// SendKey and ReleaseInputs take, so a caller can hold Command as well as A.
func NormalizeHeldKey(key string) (string, error) {
if code, err := normalizeModifier(key); err == nil {
return code, nil
}
return normalizeKeyCode(key)
}
func normalizeModifier(modifier string) (string, error) {
code := strings.ToLower(strings.TrimSpace(modifier))
switch code {
case "cmd", "command", "meta", "super":
code = "meta_l"
case "shift_l":
code = "shift"
case "ctrl", "ctrl_l", "control":
code = "ctrl"
case "alt_l", "option", "option_l":
code = "alt"
case "option_r":
code = "alt_r"
}
switch code {
case "shift", "shift_r", "ctrl", "ctrl_r", "alt", "alt_r", "meta_l", "meta_r":
return code, nil
default:
return "", fmt.Errorf("unsupported key modifier %q", modifier)
}
}
func (m *Manager) withConn(ctx context.Context, vmDir string, operation func(qmpSession) error) error {
return m.withConnMode(ctx, vmDir, false, operation)
}
// Single-command operations can close their connection on cancellation.
// Multi-command jobs need it to release any held guest keys or buttons.
func (m *Manager) withCancelableConn(ctx context.Context, vmDir string, operation func(qmpSession) error) error {
return m.withConnMode(ctx, vmDir, true, operation)
}
func (m *Manager) withConnMode(ctx context.Context, vmDir string, cancelIO bool, operation func(qmpSession) error) error {
if operation == nil {
return errors.New("console operation is unavailable")
}
key, err := lockKey(vmDir)
if err != nil {
return err
}
nested := m.hasLockScope(ctx, key)
release, err := m.acquire(ctx, vmDir)
if err != nil {
return err
}
defer release()
if !nested {
unlockFile, err := filelock.Acquire(ctx, filepath.Join(vmDir, vmLifecycleLockFile), 25*time.Millisecond)
if err != nil {
return err
}
defer unlockFile()
}
// QEMU serves one QMP client at a time. Keep both locks through this
// short-lived connection and close it before releasing them.
dial := m.dial
if dial == nil {
dial = func(ctx context.Context, vmDir string) (qmpSession, error) {
return qmp.Dial(ctx, "unix", qmp.SocketPath(vmDir))
}
}
conn, err := dial(ctx, vmDir)
if err != nil {
return err
}
closeConn := sync.OnceFunc(func() { _ = conn.Close() })
defer closeConn()
if cancelIO {
stopCancel := context.AfterFunc(ctx, closeConn)
defer stopCancel()
}
return operation(conn)
}
func (m *Manager) withVM(ctx context.Context, vmDir string, operation func(context.Context) error) error {
if operation == nil {
return errors.New("console operation is unavailable")
}
key, err := lockKey(vmDir)
if err != nil {
return err
}
if m.hasLockScope(ctx, key) {
return operation(ctx)
}
release, err := m.acquire(ctx, vmDir)
if err != nil {
return err
}
defer release()
scope := &lockScope{manager: m, key: key}
scope.active.Store(true)
defer scope.active.Store(false)
return operation(context.WithValue(ctx, lockScopeKey{}, scope))
}
func (m *Manager) acquire(ctx context.Context, vmDir string) (func(), error) {
if m == nil {
return nil, errors.New("console manager is unavailable")
}
if ctx == nil {
return nil, errors.New("console context is unavailable")
}
key, err := lockKey(vmDir)
if err != nil {
return nil, err
}
if m.hasLockScope(ctx, key) {
return func() {}, nil
}
m.mu.Lock()
if m.locks == nil {
m.locks = make(map[string]*vmLock)
}
lock := m.locks[key]
if lock == nil {
lock = &vmLock{semaphore: make(chan struct{}, 1)}
m.locks[key] = lock
}
lock.users++
m.mu.Unlock()
select {
case lock.semaphore <- struct{}{}:
var once sync.Once
return func() {
once.Do(func() {
<-lock.semaphore
m.release(key, lock)
})
}, nil
case <-ctx.Done():
m.release(key, lock)
return nil, ctx.Err()
}
}
func (m *Manager) hasLockScope(ctx context.Context, key string) bool {
if ctx == nil {
return false
}
scope, ok := ctx.Value(lockScopeKey{}).(*lockScope)
return ok && scope.manager == m && scope.key == key && scope.active.Load()
}
func (m *Manager) release(key string, lock *vmLock) {
m.mu.Lock()
defer m.mu.Unlock()
lock.users--
if lock.users == 0 && m.locks[key] == lock {
delete(m.locks, key)
}
}
func lockKey(vmDir string) (string, error) {
if strings.TrimSpace(vmDir) == "" {
return "", errors.New("VM directory is unavailable")
}
abs, err := filepath.Abs(vmDir)
if err != nil {
return "", fmt.Errorf("resolve VM directory: %w", err)
}
key := filepath.Clean(abs)
if runtime.GOOS == "windows" {
key = strings.ToLower(key)
}
return key, nil
}