Files
Reims-Go/internal/app/agent_session_lock_test.go
T
球球 7fd1947bef feat(plugin,host,macos,ui): 实现 Agent 受控接管、受保护阶段确认、离线预配置与自动装机基础 (#103, #105, #129) (#134)
* feat(plugin,host,ui): add agent session takeover, protected-phase confirmation, and autoinstall host foundation

* feat(macos,ui,cli): add offline REIMSPROV first-boot provisioning to skip Setup Assistant (#129)

Builds a per-VM read-only REIMSPROV disk image containing a pure-Go XAR Distribution flat package (provision.pkg) and an offline Recovery fallback script (provision-offline.sh). Passwords are hashed in memory to Apple SALTED-SHA512-PBKDF2 bplist00 ShadowHashData (never persisted in plaintext, no auto-login or NOPASSWD sudo). Uses native OpenDirectory.framework (JXA NSData) + dseditgroup under SIP-enabled live bootinstalld and dslocal plist + PlistBuddy under offline Recovery, skips Setup Assistant and Keyboard Setup Assistant, pre-stages Guest Tools, integrates with CreateWizard / VMPage / vm provision CLI / StartAutoInstall, and zero-wipes on finish_install, normal cold start, or DeleteVM.

* feat(autoinstall,host,ui): add input-locked session shield, recovery-only mode, and restart grace cap

Adds the real-machine end-to-end verified baseline for automatic macOS installation: (1) takeover_policy 'lock' with transparent Win32 VM client-area input shield, low-level key/mouse lock preserving host escape shortcuts (Alt+Tab/Alt+Esc/Win), HUD & UI Pause/Resume controls, and write guards while paused; (2) decoupled recovery_only vs full (REIMSPROV) modes in StartAutoInstall, CreateWizard, and VMAutoInstallPanel; (3) graceful_timeout_sec cap (default 10s) on automated built-in macOS host/vm.restart so Setup Assistant/Login Window restarts do not stall 90s on ACPI; (4) additional modifier aliases in console manager and agent-session/telemetry cleanup on VM deletion.

* feat(autoinstall,overlay,plugin): add built-in macOS auto-install plugin, dynamic island overlay, and review fixes

* fix(app,host,macos,ui): address PR #134 automated review findings

- Frontend & i18n:
  - Fix UTF-8/GBK mojibake in VMPage.tsx.
  - Emit reims:confirm-resolved on timeout/cancel/resolve so frontend modals auto-close and surface errors cleanly; stop submitCreate from continuing after PrepareVMProvision failure.
  - Gate AutoInstallPanel RapidOCR download button on preflight can_download_ocr when pinned default assets are unavailable.
- App / Sessions / Confirm / Lifecycle:
  - Add 30s denial cooldown for protected-phase confirmation prompts and revoke (pluginID, vmKey) grants on non-completed session exits.
  - Fix sessionOverlay / activeAgentSessions data race, remove duplicate permission-denied invocation, guard against clobbering other sessions or completed overlays, and unify VM key normalization.
  - Grant protected-phase confirmation and attach lock-mode session + watcher when resuming auto-install without an active session.
  - Unify FinishInstall and host/vm.finishInstall result handling and persist .reims-go-provision-ready across restarts.
  - Preserve non-timeout stop errors in restartMacOSVMLocked instead of force-killing.
- Host Takeover Hooks:
  - Require both keyboard and mouse WH_*_LL hooks (rolling back partial installs), initialize thread message queue before ready, reset started state on error/exit for retry, and report hook failures.
- macOS Provisioning & Autoinstall Engine:
  - Track REIMSPROV staged/wipe-pending/ready lifecycle markers, exclude "restore" recovery marker from re-attaching REIMSPROV, fail explicitly on offline admin plist creation failure, and report wipe failures.
  - Serialize per-VM Start/Stop/Resume with stop generation tokens, guard ROI fast-path against maxDim overflow, switch hostclient early-event buffer to FIFO eviction, fix untyped nil Engine return, tighten negation & high-risk fuzzy matching, preserve ackedQemuErrors across RebootWindow resets, and re-orient/expire stale inherited running checkpoints.
  - Document verified Windows SDK IDL vtable slots for WinOCR (live-tested on Windows) and add regression tests across app, host, macosdriver, startprep, installer, and autoinstall packages.

* fix(app,cli,host,macos,ui): address PR #134 second automated review findings

- CLI & Desktop Control Channel:
  - Add __reims_host__ / autoinstall desktop control channel with data_root verification so CLI status, resume, and stop talk directly to the live desktop runner instead of splitting checkpoint state or launching doomed short-lived CLI runners.
  - Merge live runners with on-disk checkpoints when listing status without a VM argument.
- App Sessions, Confirmations, Downloads & Telemetry:
  - Scope single-VM not_authorized errors to the target VM in handleSessionBegin and resolveComputerUseVM so active sessions on other VMs are not aborted.
  - Exclude stopped and suspended VMs from hasUnboundAgentSession fast-polling.
  - Revoke protected-phase grants when a VM disappears from poll results.
  - Require manifest Secret:true validation before storing auto-install passwords and remove the unsafe default account_password fallback.
  - Reject userinfo URLs in allow_custom_mirror, gate custom-mirror exemption strictly on plugin.ErrNetOriginNotDeclared, and keep redirect SSRF checks enabled on loopback custom mirrors.
  - Preserve VM telemetry milestones across suspend-resume and Win10 cold-reboot restarts while still resetting on fresh cold boots.
  - Log a warning when Guest Tools bridge is unavailable while preparing REIMSPROV.
  - Clarify CallHostAPI authorization/audit contract and add regression test proving built-in plugins enforce catalog permissions and audit logging.
- Host Takeover & Guest Tools:
  - Track locked mouse button presses via a 5-button bitmask so ButtonUp events from drags started outside the VM window are never swallowed.
  - Align active-window-reporter.js permissions to 0o100755 across ToolsDiskFiles, ToolsProvisionFiles, and postinstall.
- macOS Provisioning & Autoinstall Engine (OCR / Vision / Rules / Runner):
  - Never delete an unwiped REIMSPROV image on OpenFile/Write/Sync failure; persist wipe-pending marker and return error for retry.
  - Harden live postinstall preference writes with chmod 600, plutil -lint, chown, and cfprefsd flush.
  - Rewrite Windows RapidOCR C ABI structs and result extraction to match RapidAI/RapidOcrOnnx@675e73fe4c include/OcrLiteCApi.h:27-70 and src/OcrLiteCApi.cpp:12-160 (5-arg OcrInit verified).
  - Inspect PE32/PE32+ IMAGE_DIRECTORY_ENTRY_IMPORT directly to require onnxruntime.dll only for dynamically linked RapidOcrOnnx.dll builds.
  - Validate cfg.VM and use collision-free SHA-256-suffixed checkpoint paths with read fallback; redact PII/paths/UUIDs/MACs/IPs/tokens in diagnostic summaries; snapshot checkpoints before releasing r.mu for serialized disk I/O.
  - Add contrast/border/focus-ring ok return to DetectInputFieldNearLabel, enforce mask-dots verification in fillAccountForm and login screens, refuse blind password typing on clock-only lock screens, confirm shell readiness before typing install.sh, and prefer isolated button lines over modal prose in FindHit.
- Frontend:
  - Require explicit Apple SLA confirmation in both recovery_only and full modes across AutoInstallPanel and CreateWizard, with unit tests in frontend/scripts/test-autoinstall.mjs.

* fix(app,cli,host,macos,ui): address PR #134 third automated review findings

Addresses all confirmed findings from Review #6204465334 (commit d516350)
with targeted regression tests and hardens verified COM vtable bindings:

- App & Session Lifecycle:
  - Track hostPaused separately in agentSession so plugin host/session.update
    (paused_for_user=false) cannot clear physical user takeover or explicit
    PauseAgentSession holds; only host ResumeAgentSession or timed takeover
    expiry clears them.
  - Give each auto-install session watcher a monotonic watchGen + cancelable
    child context so restarting/resuming auto-install on the same VM cancels
    any superseded watcher and prevents stale timeout or secret cleanup.
  - Bound fast 500ms unbound-PID discovery for running VMs to
    sessionDiscoverGraceWindow via unboundSince (refreshed on restart/rebind).
  - Keep non-blocking buffered confirm resolution send inside confirmMu for
    clear mutual exclusion with cancelPendingConfirmations.
  - Clear cold-reboot telemetry preserveNextBoot via defer on all early-return
    and StartVM-failure paths in watchColdReboot.
  - Rebuild REIMSPROV with current StartAutoInstall credentials (preserving
    install_guest_tools) whenever VM is stopped instead of reusing stale images.
- CLI & macOS Provisioning / StartPrep:
  - Refuse `vm provision --clear` and overwriting existing REIMSPROV while the
    VM is running or paused.
  - Guard live "/" root in postinstall against macOS Recovery/Installer
    (/System/Installation/CDIS), forbid "/" in provision-offline.sh, and scope
    chmod 644 strictly to com.apple.keyboardtype.plist.
  - Reject unknown -* options in REIMSHELP/install.sh (including after --erase).
  - Defer clearing the one-shot REIMSPROV staged marker until after
    setExtraArgs (startprep) and StartWithCompat (macosdriver) succeed.
  - Preserve pending RestartFrom guards in AdvancePostInstallHandoff when
    checkpoint is already at StepDesktop.
- Host Input & Session Overlay:
  - Filter injected keyboard events (LLKHF_INJECTED / LLKHF_LOWER_IL_INJECTED)
    in locked-input mode consistently with the mouse hook.
  - Clean up exited overlay entries in entry.run() and recreate dead entries on
    Manager.Upsert when CreateWindowExW fails or exits early.
  - Cache the static island base surface (shell + icons + DirectWrite text) and
    measured text metrics across breathing frames, raising timerBreathMs to 100ms.
  - Replace magic Direct2D/DirectWrite vtable indices with named d2d1.h /
    dwrite.h constants, check EndDraw HRESULT, and add a live Windows DirectWrite
    rendering smoke test.
- Autoinstall OCR, Rules, Watchdog & Runner:
  - Persist and verify a per-file SHA-256 manifest.json in <dataDir>/ocr/
    before loading RapidOcrOnnx.dll / onnxruntime.dll; reject duplicate
    whitelisted basenames in offline zip imports.
  - Signal WinOCREngine.Close() before acquiring e.mu and add bounded wait +
    channel wakeup in Recognize so Close() immediately cancels in-flight OCR.
  - Fall back to installed RapidOCR when WinOCR initialization fails in Open(),
    and distinguish needs_rapidocr_import from needs_rapidocr_download in Probe.
  - Pause instead of pressing Return when post-TypeSecret login screenshot fails.
  - Re-baseline ColdRebootCount in Watchdog.ResetRebootWindow / ResetAfterResume.
  - Tighten recovery.main specificity (drop bare "Disk Utility"), guard 4-5 char
    pure-ASCII needles from sliding-window fuzzy collisions, use Unicode word
    boundaries for short names (<4 runes) in RedactDiagnosticText, and honor
    rule verify.wait_change_ms with early exit on visual frame diff.

* fix(autoinstall): handle CJK short-name redaction, sh-3.2 prompt bound, and OCR re-import pruning
2026-12-06 15:46:39 +08:00

247 lines
9.7 KiB
Go

package app
import (
"context"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
)
func TestFormatSessionStageAndOverlayStep(t *testing.T) {
cases := []struct {
loc i18n.Locale
raw string
want string
}{
{i18n.ZhCN, "stage0_preflight", "环境准备"},
{i18n.ZhCN, "stage1_boot_recovery", "步骤 1 · 进入恢复环境"},
{i18n.ZhCN, "stage2a_offline_terminal", "步骤 2 · 运行离线安装脚本"},
{i18n.ZhCN, "stage2_disk_utility", "步骤 2 · 磁盘工具抹盘"},
{i18n.ZhCN, "stage3_install_wait", "步骤 3 · 等待系统安装"},
{i18n.ZhCN, "stage3_reinstall_macos", "步骤 3 · 安装 macOS"},
{i18n.ZhCN, "stage3_wait_reboot", "步骤 3 · 等待系统重启"},
{i18n.ZhCN, "stage4_finish_install", "步骤 4 · 退出恢复并重启"},
{i18n.ZhCN, "stage4_setup_assistant", "步骤 4 · 完成设置助理"},
{i18n.ZhCN, "stage5_wait_reboot", "步骤 5 · 等待系统重启"},
{i18n.ZhCN, "stage5_guest_tools", "步骤 5 · 安装 Guest Tools"},
{i18n.ZhCN, "正在抹掉 APFS 磁盘", "正在抹掉 APFS 磁盘"},
{i18n.EnUS, "stage0_preflight", "Preflight check"},
{i18n.EnUS, "stage1_boot_recovery", "Step 1 · Boot into Recovery"},
{i18n.EnUS, "stage2a_offline_terminal", "Step 2 · Run offline installer"},
{i18n.EnUS, "stage3_install_wait", "Step 3 · Wait for macOS install"},
{i18n.EnUS, "stage3_wait_reboot", "Step 3 · Waiting for reboot"},
{i18n.EnUS, "stage4_finish_install", "Step 4 · Exit recovery and restart"},
{i18n.EnUS, "Step 2/5: Formatting volume", "Step 2/5: Formatting volume"},
}
for _, tc := range cases {
if got := formatSessionStage(tc.loc, tc.raw); got != tc.want {
t.Errorf("formatSessionStage(%s, %q) = %q, want %q", tc.loc, tc.raw, got, tc.want)
}
}
a := &App{}
view := AgentSessionView{
Stage: "stage2_disk_utility",
Message: "正在抹掉磁盘",
InputLocked: true,
}
step := a.sessionOverlayStep(i18n.ZhCN, view)
if step != "步骤 2 · 磁盘工具抹盘" {
t.Fatalf("sessionOverlayStep = %q, want 步骤 2 · 磁盘工具抹盘", step)
}
status := a.sessionOverlayStatusLine(i18n.ZhCN, view, step)
if status != "画面已锁定防干扰 · 正在抹掉磁盘" {
t.Fatalf("sessionOverlayStatusLine = %q, want 画面已锁定防干扰 · 正在抹掉磁盘", status)
}
// Syncing autoinstall/status progress updates session stage & message without clobbering user pause.
vm := driver.VMInfo{DriverID: driver.BuiltinReimsMacOSDriverID, Name: "tahoe-step-test"}
key := vm.Ref().Key()
a.beginAgentSession(nil, "reims.autoinstall", vm, "macOS Auto-Install", "stage0_preflight", "lock", true)
a.syncAutoInstallSessionProgress(key, "reims.autoinstall", "stage2_disk_utility", "点击抹掉")
views := a.activeAgentSessions()
if len(views) != 1 || views[0].Stage != "stage2_disk_utility" || views[0].Message != "点击抹掉" {
t.Fatalf("syncAutoInstallSessionProgress did not update session: %+v", views)
}
if err := a.PauseAgentSession(vm.DriverID, vm.Name); err != nil {
t.Fatal(err)
}
a.syncAutoInstallSessionProgress(key, "reims.autoinstall", "stage2_disk_utility", "should not overwrite pause msg")
views = a.activeAgentSessions()
if views[0].Message == "should not overwrite pause msg" {
t.Fatalf("syncAutoInstallSessionProgress overwrote paused user message: %+v", views[0])
}
}
func TestAgentSessionLockPauseResumeAndWriteGuard(t *testing.T) {
a := &App{}
vm := driver.VMInfo{
DriverID: driver.BuiltinReimsMacOSDriverID,
Name: "tahoe-lock-test",
}
vmKey := vm.Ref().Key()
a.beginAgentSession(nil, "reims.autoinstall", vm, "macOS Auto-Install", "stage1_boot_recovery", "lock", true)
views := a.activeAgentSessions()
if len(views) != 1 {
t.Fatalf("ActiveAgentSessions len = %d, want 1", len(views))
}
if views[0].TakeoverPolicy != "lock" || !views[0].InputLocked || views[0].PausedForUser {
t.Fatalf("expected active locked session, got %+v", views[0])
}
if err := a.checkUserTakeover(vmKey, vm.Name); err != nil {
t.Fatalf("running locked session should allow plugin QMP writes, got %v", err)
}
// Pausing from HUD/UI must unlock VM input and reject any in-flight plugin QMP writes.
if err := a.PauseAgentSession(vm.DriverID, vm.Name); err != nil {
t.Fatalf("PauseAgentSession: %v", err)
}
views = a.activeAgentSessions()
if len(views) != 1 || !views[0].PausedForUser || views[0].InputLocked {
t.Fatalf("expected paused & unlocked session, got %+v", views)
}
if err := a.checkUserTakeover(vmKey, vm.Name); err == nil {
t.Fatal("paused session must block in-flight plugin QMP writes")
}
// Resuming must re-lock VM input and allow plugin QMP writes again.
if err := a.ResumeAgentSession(vm.DriverID, vm.Name); err != nil {
t.Fatalf("ResumeAgentSession: %v", err)
}
views = a.activeAgentSessions()
if len(views) != 1 || views[0].PausedForUser || !views[0].InputLocked {
t.Fatalf("expected resumed & re-locked session, got %+v", views)
}
if err := a.checkUserTakeover(vmKey, vm.Name); err != nil {
t.Fatalf("resumed session should allow plugin QMP writes again, got %v", err)
}
a.endAgentSession(nil, "reims.autoinstall", vmKey, "completed")
if got := len(a.activeAgentSessions()); got != 0 {
t.Fatalf("expected 0 active sessions after end, got %d", got)
}
}
func TestAgentSessionUnboundDiscoveryAndImmediatePIDBind(t *testing.T) {
a := &App{}
vm := driver.VMInfo{
DriverID: driver.BuiltinReimsMacOSDriverID,
Name: "tahoe-bind-test",
}
vmKey := vm.Ref().Key()
if a.hasActiveAgentSessions() || a.hasUnboundAgentSession() {
t.Fatal("idle app should report no active or unbound agent sessions")
}
// Starting a session before the VM PID is known marks it unbound so pollVMs uses fast discovery.
a.beginAgentSession(nil, "reims.autoinstall", vm, "macOS Auto-Install", "stage0_preflight", "lock", true)
if !a.hasActiveAgentSessions() || !a.hasUnboundAgentSession() {
t.Fatal("new session without live PID must be tracked as active & unbound")
}
// Binding a freshly observed live PID (e.g., from first screenshot/write or VM start) resolves it immediately.
a.bindAgentSessionPID(vmKey, 42424)
if a.hasUnboundAgentSession() {
t.Fatal("bindAgentSessionPID should clear unbound state immediately")
}
if !a.hasActiveAgentSessions() {
t.Fatal("session should remain active after PID binding")
}
// A rate-limited concurrent refresh (stale cache + probe skipped within 300ms)
// must NOT wipe the already-bound PID back to 0.
a.mu.Lock()
a.ctx = context.Background()
a.lastVMs = nil
a.lastVMsAt = time.Now()
a.mu.Unlock()
a.sessionMu.Lock()
a.agentSessions[vmKey].lastPIDProbeAt = time.Now()
a.sessionMu.Unlock()
a.refreshAgentSessionVisuals(vmKey)
if a.hasUnboundAgentSession() {
t.Fatal("rate-limited refresh clobbered bound lastOverlayPID back to 0")
}
a.closeAgentSessions()
}
func TestComputerUseLocaleResolvesAuto(t *testing.T) {
a := &App{cfg: &config.Config{Locale: i18n.Auto}}
got := a.computerUseLocale()
if got == "" || got == i18n.Auto {
t.Fatalf("computerUseLocale() for Auto = %q, want concrete resolved locale", got)
}
if want := i18n.EffectiveLocale(i18n.Auto); got != want {
t.Fatalf("computerUseLocale() = %q, want %q", got, want)
}
a.cfg.Locale = i18n.EnUS
if got := a.computerUseLocale(); got != i18n.EnUS {
t.Fatalf("computerUseLocale() for en-US = %q, want en-US", got)
}
}
func TestCompletedSessionRetainsCompletedOverlayAndUnlocksInput(t *testing.T) {
a := &App{cfg: &config.Config{Locale: i18n.ZhCN}}
vm := driver.VMInfo{
DriverID: driver.BuiltinReimsMacOSDriverID,
Name: "tahoe-recovery-done",
}
vmKey := vm.Ref().Key()
const pluginID = "builtin.macos.autoinstall"
a.grantEphemeralVMAccess(pluginID, vmKey)
a.grantProtectedPhase(pluginID, vmKey, driver.PhaseInstaller, 0, true)
a.beginAgentSession(nil, pluginID, vm, "macOS Auto-Install", "stage3_install_wait", "lock", true)
a.bindAgentSessionPID(vmKey, 31337)
// Mark completed (as runner.completeRecoveryOnly does right before EndSession).
a.sessionMu.Lock()
sess := a.agentSessions[vmKey]
sess.stage = "stage6_desktop_ready"
sess.status = "completed"
sess.message = "已完成恢复模式安装并进入 macOS,画面输入已解锁"
a.sessionMu.Unlock()
if step := a.sessionOverlayStep(i18n.ZhCN, a.activeAgentSessions()[0]); step != "已完成" {
t.Fatalf("sessionOverlayStep for completed = %q, want 已完成", step)
}
st := a.completedSessionOverlayState(i18n.ZhCN, sess, 31337, true)
if !st.Completed || st.InputLocked || st.CanPause || st.CanResume {
t.Fatalf("completed overlay state must unlock input and hide pause/resume: %+v", st)
}
if st.StepText != "已完成" || st.CloseLabel != "关闭" {
t.Fatalf("unexpected completed overlay labels: StepText=%q CloseLabel=%q", st.StepText, st.CloseLabel)
}
// Ending the completed session exits active control, revokes grants, and retains completed overlay tracking.
a.endAgentSession(nil, pluginID, vmKey, "session_ended")
if len(a.activeAgentSessions()) != 0 {
t.Fatal("completed session must not remain in ActiveAgentSessions")
}
if a.hasEphemeralVMAccess(pluginID, vmKey) {
t.Fatal("completed session must revoke ephemeral VM access")
}
if _, ok := a.lookupProtectedPhaseGrant(pluginID, vmKey); ok {
t.Fatal("completed session must revoke protected-phase grant")
}
if !a.isCompletedOverlay(vmKey) {
t.Fatal("expected completed overlay marker to remain active until dismissed or VM stops")
}
// Polling while VM is stopped cleans up the completed overlay automatically.
a.mu.Lock()
a.lastVMs = []driver.VMListItem{{DriverID: vm.DriverID, Name: vm.Name, State: "stopped"}}
a.lastVMsAt = time.Now()
a.mu.Unlock()
a.cleanupStaleCompletedOverlays()
if a.isCompletedOverlay(vmKey) {
t.Fatal("completed overlay marker should be cleared when VM stops")
}
}