From 322cd9cabd165afe6540ad644b55ae1e316fe544 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=A3=A0=E6=B8=9A=E5=90=AC=E6=BD=AE?= <108173440+reiasu2@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:45:16 +0800 Subject: [PATCH 01/28] feat(display,input,ui): add opt-in custom borderless fullscreen toggle hotkey --- frontend/src/App.tsx | 6 + frontend/src/components/AppSettingsPage.tsx | 286 +++++++++++++++++- frontend/src/components/TitleMenus.tsx | 6 +- frontend/src/components/VMPage.tsx | 10 +- frontend/src/i18n/domains/settings.gen.ts | 22 ++ frontend/src/i18n/keys.gen.ts | 11 + frontend/src/lib/fullscreenHotkey.ts | 255 ++++++++++++++++ frontend/src/styles/app.css | 27 +- frontend/wailsjs/go/app/App.d.ts | 28 +- frontend/wailsjs/go/app/App.js | 56 ++-- frontend/wailsjs/go/models.ts | 36 +++ internal/app/app.go | 16 +- internal/app/fullscreen_hotkey_flow.go | 162 ++++++++++ internal/app/fullscreen_hotkey_flow_test.go | 178 +++++++++++ internal/config/config.go | 18 +- internal/config/config_test.go | 24 ++ internal/host/fullscreen_hotkey.go | 234 ++++++++++++++ internal/host/fullscreen_hotkey_other.go | 15 + internal/host/fullscreen_hotkey_test.go | 156 ++++++++++ internal/host/fullscreen_hotkey_windows.go | 223 ++++++++++++++ .../host/fullscreen_hotkey_windows_test.go | 47 +++ internal/host/fullscreen_windows.go | 5 + internal/host/input_service.go | 3 + locales/en-US/settings.json | 13 +- locales/zh-CN/settings.json | 13 +- 25 files changed, 1799 insertions(+), 51 deletions(-) create mode 100644 frontend/src/lib/fullscreenHotkey.ts create mode 100644 internal/app/fullscreen_hotkey_flow.go create mode 100644 internal/app/fullscreen_hotkey_flow_test.go create mode 100644 internal/host/fullscreen_hotkey.go create mode 100644 internal/host/fullscreen_hotkey_other.go create mode 100644 internal/host/fullscreen_hotkey_test.go create mode 100644 internal/host/fullscreen_hotkey_windows.go create mode 100644 internal/host/fullscreen_hotkey_windows_test.go diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index bd29262..4a49470 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -14,6 +14,7 @@ import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Si import { VMAction, VMPage } from './components/VMPage' import { buildFallbackChain, I18nKey, localeDir, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n' import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format' +import { resolveFullscreenHotkey } from './lib/fullscreenHotkey' import { LogLine, appendLog } from './lib/logs' import { macOSMajor } from './macos/macosRelease' import { currentTask, finishedTaskTTL, isActiveInstallerTask, pruneFinishedTasks, upsertTask } from './lib/tasks' @@ -344,6 +345,9 @@ export const App: React.FC = () => { const pending = selectedVM ? (state?.pending_changes[vmRefKey(selectedVM)] ?? []) : [] const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime const canSuspend = state?.can_suspend ?? false + const fullscreenHotkey = state?.config.fullscreen_hotkey_enabled + ? resolveFullscreenHotkey(state.config.fullscreen_hotkey) + : undefined onTaskRef.current = (task: Task) => { if (task.kind === 'app-update' && task.status === 'failed' && !notifiedTasks.current.has(task.id)) { @@ -1038,6 +1042,7 @@ export const App: React.FC = () => { graphics: detail?.name === selectedVM.name ? detail.graphics : undefined, canSuspend, } : null} + fullscreenHotkey={fullscreenHotkey} onNewVM={openWizard} onVMAction={onVMAction} onVMSettings={() => { if (detail && effectiveState !== 'suspended') setShowSettings(true) }} @@ -1234,6 +1239,7 @@ export const App: React.FC = () => { }} onToast={(title) => toasts.push({ kind: 'ok', title })} onError={fail} + fullscreenHotkey={fullscreenHotkey} dropping={dropping} pluginUI={pluginUI} /> diff --git a/frontend/src/components/AppSettingsPage.tsx b/frontend/src/components/AppSettingsPage.tsx index 30f2954..d687d18 100644 --- a/frontend/src/components/AppSettingsPage.tsx +++ b/frontend/src/components/AppSettingsPage.tsx @@ -1,7 +1,13 @@ -import React, { useEffect, useRef, useState } from 'react' -import { Check, CircleAlert, PowerOff } from 'lucide-react' +import React, { useCallback, useEffect, useRef, useState } from 'react' +import { Check, CircleAlert, Keyboard, PowerOff, RotateCcw } from 'lucide-react' import '../i18n/domains/settings.gen' import { getLocaleOptions, I18nKey, parseAppError, t } from '../i18n' +import { + captureFullscreenHotkeyEvent, + DEFAULT_FULLSCREEN_HOTKEY, + resolveFullscreenHotkey, + splitFullscreenHotkey, +} from '../lib/fullscreenHotkey' import { findOptimization, optBadgeClass, optStatusLabel } from '../lib/optimizations' import { AppState, Locale, ResolvedLocalePack } from '../types' import { Button } from '../ui/controls' @@ -247,6 +253,198 @@ export const AppSettingsPage: React.FC = ({ } } + const [hotkeyStatus, setHotkeyStatus] = useState<{ + enabled: boolean + hotkey: string + default_hotkey: string + hook_active: boolean + }>(() => ({ + enabled: !!config.fullscreen_hotkey_enabled, + hotkey: resolveFullscreenHotkey(config.fullscreen_hotkey), + default_hotkey: DEFAULT_FULLSCREEN_HOTKEY, + hook_active: false, + })) + const [hotkeyBusy, setHotkeyBusy] = useState(false) + const [hotkeyLoading, setHotkeyLoading] = useState(true) + const [recordingHotkey, setRecordingHotkey] = useState(false) + const [hotkeyError, setHotkeyError] = useState('') + const hotkeyRowRef = useRef(null) + const suppressedCodeRef = useRef(null) + const hotkeyReqSeqRef = useRef(0) + const hotkeyMountedRef = useRef(true) + const hotkeyStatusRef = useRef(hotkeyStatus) + hotkeyStatusRef.current = hotkeyStatus + const hotkeyBusyRef = useRef(hotkeyBusy) + hotkeyBusyRef.current = hotkeyBusy + const hotkeyLoadingRef = useRef(hotkeyLoading) + hotkeyLoadingRef.current = hotkeyLoading + const localeRef = useRef(locale) + localeRef.current = locale + + useEffect(() => { + hotkeyMountedRef.current = true + return () => { hotkeyMountedRef.current = false } + }, []) + + useEffect(() => { + const seq = ++hotkeyReqSeqRef.current + setHotkeyLoading(true) + setRecordingHotkey(false) + setHotkeyError('') + api.GetFullscreenHotkey() + .then((status) => { + if (!hotkeyMountedRef.current || hotkeyReqSeqRef.current !== seq) return + if (!status) return + const def = status.default_hotkey || DEFAULT_FULLSCREEN_HOTKEY + setHotkeyStatus({ + enabled: !!status.enabled, + hotkey: resolveFullscreenHotkey(status.hotkey, def), + default_hotkey: def, + hook_active: !!status.hook_active, + }) + }) + .catch((e) => { + console.warn('[settings] GetFullscreenHotkey failed:', e) + }) + .finally(() => { + if (hotkeyMountedRef.current && hotkeyReqSeqRef.current === seq) { + setHotkeyLoading(false) + } + }) + }, [config.data_root]) + + const saveFullscreenHotkey = useCallback(async (nextEnabled: boolean, nextHotkey: string) => { + if (hotkeyBusyRef.current || hotkeyLoadingRef.current) return + const seq = ++hotkeyReqSeqRef.current + setHotkeyBusy(true) + setHotkeyError('') + try { + const status = await api.SetFullscreenHotkey({ enabled: nextEnabled, hotkey: nextHotkey }) + if (!hotkeyMountedRef.current || hotkeyReqSeqRef.current !== seq) return + const def = status.default_hotkey || DEFAULT_FULLSCREEN_HOTKEY + setHotkeyStatus({ + enabled: !!status.enabled, + hotkey: resolveFullscreenHotkey(status.hotkey, def), + default_hotkey: def, + hook_active: !!status.hook_active, + }) + setRecordingHotkey(false) + onRefresh() + } catch (e) { + if (!hotkeyMountedRef.current || hotkeyReqSeqRef.current !== seq) return + setRecordingHotkey(false) + const summary = parseAppError(e).summary + setHotkeyError(summary || t(localeRef.current, 'fullscreenHotkeySaveFailed')) + onError(t(localeRef.current, 'fullscreenHotkeySaveFailed'), e) + } finally { + if (hotkeyMountedRef.current && hotkeyReqSeqRef.current === seq) { + setHotkeyBusy(false) + } + } + }, [onError, onRefresh]) + + const saveHotkeyRef = useRef(saveFullscreenHotkey) + saveHotkeyRef.current = saveFullscreenHotkey + + useEffect(() => { + const onSuppressedKeyDown = (e: KeyboardEvent) => { + const code = suppressedCodeRef.current + if (!code) return + if ((e.code || e.key) === code) { + e.preventDefault() + e.stopPropagation() + e.stopImmediatePropagation() + } + } + const onSuppressedKeyUp = (e: KeyboardEvent) => { + const code = suppressedCodeRef.current + if (!code) return + if ((e.code || e.key) === code) { + suppressedCodeRef.current = null + e.preventDefault() + e.stopPropagation() + e.stopImmediatePropagation() + } + } + const onSuppressedBlur = () => { + suppressedCodeRef.current = null + } + window.addEventListener('keydown', onSuppressedKeyDown, true) + window.addEventListener('keyup', onSuppressedKeyUp, true) + window.addEventListener('blur', onSuppressedBlur) + return () => { + suppressedCodeRef.current = null + window.removeEventListener('keydown', onSuppressedKeyDown, true) + window.removeEventListener('keyup', onSuppressedKeyUp, true) + window.removeEventListener('blur', onSuppressedBlur) + } + }, []) + + useEffect(() => { + if (!recordingHotkey) return + const onKeyDown = (e: KeyboardEvent) => { + if (hotkeyBusyRef.current || hotkeyLoadingRef.current) return + e.preventDefault() + e.stopPropagation() + e.stopImmediatePropagation() + const res = captureFullscreenHotkeyEvent(e) + if (res.kind === 'ignore') return + if (res.kind === 'cancel') { + suppressedCodeRef.current = e.code || e.key || null + setRecordingHotkey(false) + setHotkeyError('') + return + } + if (res.kind === 'error') { + const loc = localeRef.current + if (res.reason === 'needs_modifier') { + setHotkeyError(t(loc, 'fullscreenHotkeyErrNeedsModifier')) + } else if (res.reason === 'reserved') { + setHotkeyError(t(loc, 'fullscreenHotkeyErrReserved', { hotkey: res.hotkey ?? '' })) + } else { + setHotkeyError(t(loc, 'fullscreenHotkeyErrUnsupported')) + } + return + } + // Keep swallowing auto-repeat and keyup for the captured key so holding + // e.g. Ctrl+N / Ctrl+B / Ctrl+L cannot trigger app-level shortcuts. + suppressedCodeRef.current = e.code || e.key || null + setRecordingHotkey(false) + setHotkeyError('') + void saveHotkeyRef.current(hotkeyStatusRef.current.enabled, res.hotkey) + } + const onBlur = () => { + setRecordingHotkey(false) + } + const onOutsidePointer = (e: PointerEvent) => { + const row = hotkeyRowRef.current + if (row && e.target instanceof Node && !row.contains(e.target)) { + setRecordingHotkey(false) + } + } + const onFocusIn = (e: FocusEvent) => { + const row = hotkeyRowRef.current + if (row && e.target instanceof Node && !row.contains(e.target)) { + setRecordingHotkey(false) + } + } + window.addEventListener('keydown', onKeyDown, true) + window.addEventListener('blur', onBlur) + document.addEventListener('pointerdown', onOutsidePointer, true) + document.addEventListener('focusin', onFocusIn, true) + return () => { + window.removeEventListener('keydown', onKeyDown, true) + window.removeEventListener('blur', onBlur) + document.removeEventListener('pointerdown', onOutsidePointer, true) + document.removeEventListener('focusin', onFocusIn, true) + } + }, [recordingHotkey]) + + const hotkeyDisabled = hotkeyBusy || hotkeyLoading + + const hotkeyParts = splitFullscreenHotkey(hotkeyStatus.hotkey) + const isDefaultHotkey = hotkeyStatus.hotkey === hotkeyStatus.default_hotkey + return (
@@ -261,7 +459,7 @@ export const AppSettingsPage: React.FC = ({
{tr('hostDataRoot')}
{config.data_root}
-
+
@@ -317,6 +515,88 @@ export const AppSettingsPage: React.FC = ({ />
+
+
+
+
{tr('fullscreenHotkeyTitle')}
+
{tr('fullscreenHotkeySub')}
+
+
+ { + setRecordingHotkey(false) + void saveFullscreenHotkey(checked, hotkeyStatus.hotkey) + }} + /> +
+
+
+
+ {hotkeyParts.map((part, idx) => ( + + {idx > 0 && } + {part} + + ))} +
+
+ + {recordingHotkey ? ( + + ) : ( + + )} +
+
+ {recordingHotkey && ( +
{tr('fullscreenHotkeyRecordHint')}
+ )} + {hotkeyError && ( +
+
+ )} +
{tr('hostDNSModeTitle')}
diff --git a/frontend/src/components/TitleMenus.tsx b/frontend/src/components/TitleMenus.tsx index bd95879..e6ab39e 100644 --- a/frontend/src/components/TitleMenus.tsx +++ b/frontend/src/components/TitleMenus.tsx @@ -28,6 +28,8 @@ interface Props { onThemeMode: (mode: ThemeMode) => void /** The selected VM and its current state, or null on the system pages. */ vm: { name: string; driver_id?: string; state: string; busy: boolean; graphics?: string; canSuspend: boolean } | null + /** Active global fullscreen toggle shortcut when enabled, else undefined. */ + fullscreenHotkey?: string onNewVM: () => void onVMAction: (action: VMAction) => void onVMSettings: () => void @@ -45,7 +47,7 @@ interface Props { */ export const TitleMenus: React.FC = ({ locale, sidebarOpen, onToggleSidebar, logsOpen, onToggleLogs, themeMode, canLight = true, canDark = true, onThemeMode, - vm, onNewVM, onVMAction, onVMSettings, onVMDelete, onNavigate, onOpenURL, appVersion, + vm, fullscreenHotkey, onNewVM, onVMAction, onVMSettings, onVMDelete, onNavigate, onOpenURL, appVersion, }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const [menuState, setMenuState] = useState<{ id: MenuId | null; switched: boolean }>({ id: null, switched: false }) @@ -226,7 +228,7 @@ export const TitleMenus: React.FC = ({ ? item(tr('resume'), () => onVMAction('resume'), { shortcut: vm?.canSuspend ? 'Ctrl+Enter' : undefined, disabled: vmBusy || !vm?.canSuspend }) : item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })} {suspended && !vm?.canSuspend && {tr('resumeUnavailable')}} - {item(fullscreenLabel, () => onVMAction('fullscreen'), { disabled: vmBusy || !canFullscreen })} + {item(fullscreenLabel, () => onVMAction('fullscreen'), { shortcut: fullscreenHotkey, disabled: vmBusy || !canFullscreen })} {item(tr('suspend'), () => onVMAction('suspend'), { disabled: vmBusy || !running || !vm?.canSuspend })} {item(tr('stop'), () => onVMAction('stop'), { disabled: vmBusy || !running })} {item(tr('restart'), () => onVMAction('restart'), { disabled: vmBusy || !running })} diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index 148331c..b22db81 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -124,6 +124,8 @@ interface Props { onDeliverFile: () => void onToast: (title: string) => void onError: (title: string, e: unknown) => void + /** Active global fullscreen toggle shortcut when enabled, else undefined. */ + fullscreenHotkey?: string dropping?: boolean pluginUI?: PluginUIContributions | null } @@ -178,7 +180,7 @@ interface Spec { } export const VMPage: React.FC = ({ - locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI, + locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, fullscreenHotkey, dropping, pluginUI, }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const busy = busyAction !== undefined @@ -573,9 +575,9 @@ export const VMPage: React.FC = ({ <> {detail?.graphics !== 'vmware-svga' && ( onAction('fullscreen')}> - {stats?.window_fullscreen - ? <> {tr('exitFullscreen')} - : <> {tr('enterFullscreen')}} + {stats?.window_fullscreen ? : } + {tr(stats?.window_fullscreen ? 'exitFullscreen' : 'enterFullscreen')} + {fullscreenHotkey && {fullscreenHotkey}} )} onAction('restart')}> diff --git a/frontend/src/i18n/domains/settings.gen.ts b/frontend/src/i18n/domains/settings.gen.ts index 8af0b59..4da7fc8 100644 --- a/frontend/src/i18n/domains/settings.gen.ts +++ b/frontend/src/i18n/domains/settings.gen.ts @@ -185,6 +185,17 @@ export const settingsZh: Record = { "forceQuitAppTitle": "强制退出 Reims-Go", "forceQuitInProgress": "正在强制退出…", "fullscreenDecoupledHint": "窗口铺满屏幕;下方分辨率可独立设为原生或超采样 HiDPI(如 4K 1.5× = 5120×2880),由 GPU 自动缩放", + "fullscreenHotkeyCurrentAria": "当前全屏快捷键:{hotkey}", + "fullscreenHotkeyErrNeedsModifier": "非 F1–F12 按键需配合修饰键(Ctrl、Shift、Alt 或 Win)", + "fullscreenHotkeyErrReserved": "{hotkey} 为 Windows 系统保留快捷键,无法使用", + "fullscreenHotkeyErrUnsupported": "不支持该按键,可用字母、数字、F1–F12 及常用功能键", + "fullscreenHotkeyListening": "按下组合键…", + "fullscreenHotkeyRecord": "录制快捷键", + "fullscreenHotkeyRecordHint": "直接按下组合键完成设置,按 Esc 取消", + "fullscreenHotkeyReset": "恢复默认", + "fullscreenHotkeySaveFailed": "保存全屏快捷键失败", + "fullscreenHotkeySub": "仅在聚焦运行中的虚拟机窗口时生效,关闭后保留已自定义快捷键", + "fullscreenHotkeyTitle": "快速切换全屏快捷键", "fullscreenLaunch": "无边框全屏启动", "fullscreenLaunchHint": "启动后直接进入无边框全屏", "gpuAutoOption": "自动(优先独显)", @@ -670,6 +681,17 @@ export const settingsEn: Record = { "forceQuitAppTitle": "Force quit Reims-Go", "forceQuitInProgress": "Force quitting…", "fullscreenDecoupledHint": "Fills the monitor; pick native or supersampled HiDPI (e.g. 5120×2880 for 4K 1.5×) below, scaled on the GPU", + "fullscreenHotkeyCurrentAria": "Current fullscreen shortcut: {hotkey}", + "fullscreenHotkeyErrNeedsModifier": "Keys other than F1–F12 require a modifier (Ctrl, Shift, Alt, or Win)", + "fullscreenHotkeyErrReserved": "{hotkey} is reserved by Windows and cannot be used", + "fullscreenHotkeyErrUnsupported": "Key not supported; use letters, numbers, F1–F12, or navigation keys", + "fullscreenHotkeyListening": "Press keys…", + "fullscreenHotkeyRecord": "Record shortcut", + "fullscreenHotkeyRecordHint": "Press a key combination to set, or Esc to cancel", + "fullscreenHotkeyReset": "Reset to default", + "fullscreenHotkeySaveFailed": "Could not save fullscreen shortcut", + "fullscreenHotkeySub": "Active only while a running VM window is focused; custom shortcuts are kept when turned off", + "fullscreenHotkeyTitle": "Fullscreen toggle shortcut", "fullscreenLaunch": "Launch borderless fullscreen", "fullscreenLaunchHint": "Opens macOS in borderless full screen", "gpuAutoOption": "Automatic (prefers discrete)", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 08f24dd..609207c 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -307,6 +307,17 @@ export type I18nKey = | "forceQuitInProgress" | "forceStop" | "fullscreenDecoupledHint" + | "fullscreenHotkeyCurrentAria" + | "fullscreenHotkeyErrNeedsModifier" + | "fullscreenHotkeyErrReserved" + | "fullscreenHotkeyErrUnsupported" + | "fullscreenHotkeyListening" + | "fullscreenHotkeyRecord" + | "fullscreenHotkeyRecordHint" + | "fullscreenHotkeyReset" + | "fullscreenHotkeySaveFailed" + | "fullscreenHotkeySub" + | "fullscreenHotkeyTitle" | "fullscreenLaunch" | "fullscreenLaunchHint" | "gpuAuto" diff --git a/frontend/src/lib/fullscreenHotkey.ts b/frontend/src/lib/fullscreenHotkey.ts new file mode 100644 index 0000000..b000f9a --- /dev/null +++ b/frontend/src/lib/fullscreenHotkey.ts @@ -0,0 +1,255 @@ +export const DEFAULT_FULLSCREEN_HOTKEY = 'Ctrl+Shift+F' + +export interface HotkeyModifiers { + ctrl: boolean + shift: boolean + alt: boolean + win: boolean +} + +export interface HotkeyKeyEventLike { + code?: string + key?: string + ctrlKey?: boolean + shiftKey?: boolean + altKey?: boolean + metaKey?: boolean + repeat?: boolean +} + +export type FullscreenHotkeyErrorReason = 'unsupported' | 'needs_modifier' | 'reserved' + +export type FullscreenHotkeyCaptureResult = + | { kind: 'cancel' } + | { kind: 'ignore' } + | { kind: 'ok'; hotkey: string } + | { kind: 'error'; reason: FullscreenHotkeyErrorReason; hotkey?: string } + +export type FullscreenHotkeyParseResult = + | { ok: true; hotkey: string } + | { ok: false; reason: FullscreenHotkeyErrorReason | 'invalid'; hotkey?: string } + +const MODIFIER_CODES = new Set([ + 'ControlLeft', + 'ControlRight', + 'ShiftLeft', + 'ShiftRight', + 'AltLeft', + 'AltRight', + 'MetaLeft', + 'MetaRight', + 'OSLeft', + 'OSRight', +]) + +const MODIFIER_KEYS = new Set([ + 'Control', + 'Shift', + 'Alt', + 'AltGraph', + 'Meta', + 'OS', +]) + +const BACKEND_NAMED_KEYS: Record = { + ENTER: 'Enter', + RETURN: 'Enter', + SPACE: 'Space', + TAB: 'Tab', + ESCAPE: 'Escape', + ESC: 'Escape', + BACKSPACE: 'Backspace', + INSERT: 'Insert', + DELETE: 'Delete', + HOME: 'Home', + END: 'End', + PAGEUP: 'PageUp', + PAGEDOWN: 'PageDown', + UP: 'Up', + DOWN: 'Down', + LEFT: 'Left', + RIGHT: 'Right', +} + +const EVENT_KEY_ALIASES: Record = { + ...BACKEND_NAMED_KEYS, + SPACEBAR: 'Space', + DEL: 'Delete', + ARROWUP: 'Up', + ARROWDOWN: 'Down', + ARROWLEFT: 'Left', + ARROWRIGHT: 'Right', +} + +const CODE_TO_KEY: Record = { + Enter: 'Enter', + NumpadEnter: 'Enter', + Space: 'Space', + Tab: 'Tab', + Escape: 'Escape', + Backspace: 'Backspace', + Insert: 'Insert', + Delete: 'Delete', + Home: 'Home', + End: 'End', + PageUp: 'PageUp', + PageDown: 'PageDown', + ArrowUp: 'Up', + ArrowDown: 'Down', + ArrowLeft: 'Left', + ArrowRight: 'Right', +} + +export function isFunctionKey(key: string): boolean { + return /^F(?:[1-9]|1[0-2])$/.test(key) +} + +export function isReservedFullscreenHotkey(mods: HotkeyModifiers, key: string): boolean { + return ( + (mods.ctrl && mods.alt && key === 'Delete') || + (mods.alt && (key === 'F4' || key === 'Tab')) || + (mods.win && key === 'L') + ) +} + +function formatCanonical(mods: HotkeyModifiers, key: string): string { + const parts: string[] = [] + if (mods.ctrl) parts.push('Ctrl') + if (mods.shift) parts.push('Shift') + if (mods.alt) parts.push('Alt') + if (mods.win) parts.push('Win') + parts.push(key) + return parts.join('+') +} + +// Matches Go's strings.TrimSpace (Unicode White_Space, notably excluding U+FEFF). +function trimGoSpace(s: string): string { + return s.replace(/^[\t\n\v\f\r \u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+|[\t\n\v\f\r \u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+$/g, '') +} + +function normalizePrimaryToken(token: string, aliases: Record = BACKEND_NAMED_KEYS): string | null { + const upper = trimGoSpace(token).toUpperCase() + if (!upper) return null + if (/^[A-Z0-9]$/.test(upper)) return upper + if (/^F(?:[1-9]|1[0-2])$/.test(upper)) return upper + return aliases[upper] ?? null +} + +function mapEventPrimaryKey(e: HotkeyKeyEventLike): string | null { + const code = (e.code ?? '').trim() + const key = e.key ?? '' + // Numpad digits/operators have distinct Windows VK codes from top-row digits, + // so avoid falling back to e.key for unmapped Numpad keys. + if (code.startsWith('Numpad') && code !== 'NumpadEnter') return null + + // Prefer layout-aware ASCII letters from e.key so non-US layouts (e.g. QWERTZ) + // record the same virtual key letter that Windows WH_KEYBOARD_LL receives. + if (/^[a-zA-Z]$/.test(key)) return key.toUpperCase() + + if (code) { + const letter = /^Key([A-Z])$/.exec(code) + if (letter) return letter[1] + const digit = /^Digit([0-9])$/.exec(code) + if (digit) return digit[1] + if (/^F(?:[1-9]|1[0-2])$/.test(code)) return code + if (code in CODE_TO_KEY) return CODE_TO_KEY[code] + } + if (key === ' ') return 'Space' + return normalizePrimaryToken(key, EVENT_KEY_ALIASES) +} + +export function parseFullscreenHotkey(raw: string): FullscreenHotkeyParseResult { + const input = trimGoSpace(raw) || DEFAULT_FULLSCREEN_HOTKEY + const mods: HotkeyModifiers = { ctrl: false, shift: false, alt: false, win: false } + let primary = '' + + for (const part of input.split('+')) { + const token = trimGoSpace(part).toUpperCase() + if (!token) return { ok: false, reason: 'invalid' } + if (token === 'CTRL' || token === 'CONTROL') { + if (mods.ctrl) return { ok: false, reason: 'invalid' } + mods.ctrl = true + continue + } + if (token === 'SHIFT') { + if (mods.shift) return { ok: false, reason: 'invalid' } + mods.shift = true + continue + } + if (token === 'ALT' || token === 'OPTION') { + if (mods.alt) return { ok: false, reason: 'invalid' } + mods.alt = true + continue + } + if (token === 'WIN' || token === 'META' || token === 'SUPER') { + if (mods.win) return { ok: false, reason: 'invalid' } + mods.win = true + continue + } + if (primary) return { ok: false, reason: 'invalid' } + const mapped = normalizePrimaryToken(token) + if (!mapped) return { ok: false, reason: 'unsupported' } + primary = mapped + } + + if (!primary) return { ok: false, reason: 'invalid' } + const hasModifier = mods.ctrl || mods.shift || mods.alt || mods.win + if (!hasModifier && !isFunctionKey(primary)) { + return { ok: false, reason: 'needs_modifier', hotkey: primary } + } + const canonical = formatCanonical(mods, primary) + if (isReservedFullscreenHotkey(mods, primary)) { + return { ok: false, reason: 'reserved', hotkey: canonical } + } + return { ok: true, hotkey: canonical } +} + +export function resolveFullscreenHotkey(raw?: string, fallback = DEFAULT_FULLSCREEN_HOTKEY): string { + const parsed = parseFullscreenHotkey(raw ?? '') + return parsed.ok ? parsed.hotkey : fallback +} + +export function splitFullscreenHotkey(hotkey: string): string[] { + return hotkey + .split('+') + .map((part) => part.trim()) + .filter(Boolean) +} + +export function captureFullscreenHotkeyEvent(e: HotkeyKeyEventLike): FullscreenHotkeyCaptureResult { + if (e.repeat) return { kind: 'ignore' } + + const code = (e.code ?? '').trim() + const key = e.key ?? '' + if (MODIFIER_CODES.has(code) || MODIFIER_KEYS.has(key)) { + return { kind: 'ignore' } + } + + const mods: HotkeyModifiers = { + ctrl: !!e.ctrlKey, + shift: !!e.shiftKey, + alt: !!e.altKey, + win: !!e.metaKey, + } + const hasModifier = mods.ctrl || mods.shift || mods.alt || mods.win + + if (!hasModifier && (code === 'Escape' || key === 'Escape' || key === 'Esc')) { + return { kind: 'cancel' } + } + + const primary = mapEventPrimaryKey(e) + if (!primary) { + return { kind: 'error', reason: 'unsupported' } + } + + if (!hasModifier && !isFunctionKey(primary)) { + return { kind: 'error', reason: 'needs_modifier', hotkey: primary } + } + + const canonical = formatCanonical(mods, primary) + if (isReservedFullscreenHotkey(mods, primary)) { + return { kind: 'error', reason: 'reserved', hotkey: canonical } + } + + return { kind: 'ok', hotkey: canonical } +} diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 1c57776..bc139ea 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -652,6 +652,29 @@ h1, h2, h3, p { margin: 0; } .host-dns-custom > .input { flex: 1; min-width: 0; } .host-dns-feedback { display: inline-flex; align-items: center; gap: 6px; font-size: var(--fs-12); line-height: 1.45; overflow-wrap: anywhere; font-variant-numeric: tabular-nums; } .host-dns-feedback > svg { flex-shrink: 0; } +.row.hotkey-row { flex-direction: column; align-items: stretch; gap: var(--sp-3); } +.hotkey-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); width: 100%; } +.hotkey-controls { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: var(--sp-2) var(--sp-3); } +.hotkey-keys { display: inline-flex; align-items: center; flex-wrap: wrap; gap: 5px; } +.hotkey-keys[data-inactive="true"] { opacity: 0.62; } +.hotkey-cap { + display: inline-flex; align-items: center; justify-content: center; + min-width: 26px; height: 26px; padding: 0 8px; + border-radius: var(--r-sm); border: 1px solid var(--border-strong); + background: var(--surface-card-elevated); box-shadow: var(--shadow-btn); + font-family: var(--font-mono); font-size: var(--fs-12); font-weight: var(--fw-medium); + color: var(--text); line-height: 1; +} +.hotkey-plus { font-size: var(--fs-11); color: var(--text-3); user-select: none; } +.hotkey-actions { display: flex; align-items: center; flex-wrap: wrap; gap: var(--sp-2); } +.hotkey-record-btn.is-recording { + border-color: var(--accent); + background: var(--accent-soft); + color: var(--accent-soft-text); +} +.hotkey-hint { font-size: var(--fs-12); color: var(--text-3); } +.hotkey-error { display: flex; align-items: flex-start; gap: 6px; font-size: var(--fs-12); color: var(--danger-text); } +.hotkey-error svg { flex-shrink: 0; margin-top: 2px; } .badge { display: inline-flex; align-items: center; height: 20px; padding: 0 8px; border-radius: 999px; font-size: 11.5px; font-weight: var(--fw-medium); white-space: nowrap; flex-shrink: 0; background: var(--surface-active); color: var(--text-2); } .badge-accent { background: var(--accent-soft); color: var(--accent-soft-text); } @@ -2019,7 +2042,7 @@ button.status-issue + .status-metric { margin-left: 6px; } } @container (max-width: 520px) { - .row, .row-head, .srow-head { flex-wrap: wrap; gap: var(--sp-2) var(--sp-4); } + .row, .row-head, .hotkey-head, .srow-head { flex-wrap: wrap; gap: var(--sp-2) var(--sp-4); } .row-main, .srow-text { flex: 1 1 220px; } .row-right, .srow-ctrl { flex-wrap: wrap; max-width: 100%; min-width: 0; } } @@ -2029,7 +2052,7 @@ button.status-issue + .status-metric { margin-left: 6px; } .review-group:last-child .review-rows { grid-template-columns: max-content 1fr; } .vm-spec-card { grid-template-columns: repeat(2, minmax(0, 1fr)); padding: 12px 14px; } .affinity-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } - .conn-row, .srow-head, .row, .row-head, .page-head { flex-wrap: wrap; gap: var(--sp-2) var(--sp-4); } + .conn-row, .srow-head, .row, .row-head, .hotkey-head, .page-head { flex-wrap: wrap; gap: var(--sp-2) var(--sp-4); } .row-main, .srow-text { flex: 1 1 220px; } .conn-ctrl, .row-right, .srow-ctrl { flex-wrap: wrap; max-width: 100%; min-width: 0; } .plugin-search-wrap, .plugin-search { width: 100%; } diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index 53c1aad..6998225 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -40,14 +40,6 @@ export function CompactVMDisk(arg1:string):Promise; export function CompactVMDiskWithDriver(arg1:string,arg2:string):Promise; -export function OptimizeVMDisk(arg1:string):Promise; - -export function OptimizeVMDiskWithDriver(arg1:string,arg2:string):Promise; - -export function OpenWindowsSecurityExclusions():Promise; - -export function GetDefenderExclusionCommand():Promise; - export function CompleteSetup(arg1:string):Promise; export function CopyVMScreenshot(arg1:string):Promise; @@ -122,6 +114,10 @@ export function GenerateVMSMBIOS(arg1:string):Promise; export function GetActiveTheme():Promise; +export function GetDefenderExclusionCommand():Promise; + +export function GetFullscreenHotkey():Promise; + export function GetGuestToolsHostDNS(arg1:string):Promise; export function GetHostDNSConfig():Promise; @@ -142,8 +138,6 @@ export function GetVMAffinity(arg1:string):Promise; export function GetVMAffinityWithDriver(arg1:string,arg2:string):Promise; -export function GetVMKeymap(arg1:string):Promise; - export function GetVMDetail(arg1:string):Promise; export function GetVMDisplayWithDriver(arg1:string,arg2:string):Promise; @@ -152,6 +146,8 @@ export function GetVMDriveShareSettings(arg1:string):Promise; +export function GetVMKeymap(arg1:string):Promise; + export function GetVMMacOS(arg1:string):Promise; export function GetVMNote(arg1:string):Promise; @@ -228,6 +224,12 @@ export function OpenVSCodeSSH(arg1:string,arg2:string):Promise; export function OpenVSCodeSSHWithDriver(arg1:string,arg2:string,arg3:string):Promise; +export function OpenWindowsSecurityExclusions():Promise; + +export function OptimizeVMDisk(arg1:string):Promise; + +export function OptimizeVMDiskWithDriver(arg1:string,arg2:string):Promise; + export function PanelBridgeCall(arg1:string,arg2:string,arg3:Record):Promise; export function PeekPluginMarket(arg1:string,arg2:string):Promise; @@ -286,6 +288,8 @@ export function SetAutoPinPCores(arg1:boolean):Promise; export function SetDataRoot(arg1:string):Promise; +export function SetFullscreenHotkey(arg1:app.FullscreenHotkeyConfig):Promise; + export function SetGuestPreventSleep(arg1:string,arg2:boolean):Promise; export function SetGuestToolsHostDNS(arg1:string,arg2:boolean):Promise; @@ -308,10 +312,10 @@ export function SetVMAffinityWithDriver(arg1:string,arg2:string,arg3:app.VMAffin export function SetVMDisplayWithDriver(arg1:string,arg2:string,arg3:string):Promise; -export function SetVMKeymap(arg1:string,arg2:app.VMKeymapUpdate):Promise; - export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array):Promise; +export function SetVMKeymap(arg1:string,arg2:app.VMKeymapUpdate):Promise; + export function SetVMNote(arg1:string,arg2:string):Promise; export function SetVMSSHUser(arg1:string,arg2:string):Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index 2f1b093..4f9eb91 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -58,22 +58,6 @@ export function CompactVMDiskWithDriver(arg1, arg2) { return window['go']['app']['App']['CompactVMDiskWithDriver'](arg1, arg2); } -export function OptimizeVMDisk(arg1) { - return window['go']['app']['App']['OptimizeVMDisk'](arg1); -} - -export function OptimizeVMDiskWithDriver(arg1, arg2) { - return window['go']['app']['App']['OptimizeVMDiskWithDriver'](arg1, arg2); -} - -export function OpenWindowsSecurityExclusions() { - return window['go']['app']['App']['OpenWindowsSecurityExclusions'](); -} - -export function GetDefenderExclusionCommand() { - return window['go']['app']['App']['GetDefenderExclusionCommand'](); -} - export function CompleteSetup(arg1) { return window['go']['app']['App']['CompleteSetup'](arg1); } @@ -222,6 +206,14 @@ export function GetActiveTheme() { return window['go']['app']['App']['GetActiveTheme'](); } +export function GetDefenderExclusionCommand() { + return window['go']['app']['App']['GetDefenderExclusionCommand'](); +} + +export function GetFullscreenHotkey() { + return window['go']['app']['App']['GetFullscreenHotkey'](); +} + export function GetGuestToolsHostDNS(arg1) { return window['go']['app']['App']['GetGuestToolsHostDNS'](arg1); } @@ -262,10 +254,6 @@ export function GetVMAffinityWithDriver(arg1, arg2) { return window['go']['app']['App']['GetVMAffinityWithDriver'](arg1, arg2); } -export function GetVMKeymap(arg1) { - return window['go']['app']['App']['GetVMKeymap'](arg1); -} - export function GetVMDetail(arg1) { return window['go']['app']['App']['GetVMDetail'](arg1); } @@ -282,6 +270,10 @@ export function GetVMInfo(arg1, arg2) { return window['go']['app']['App']['GetVMInfo'](arg1, arg2); } +export function GetVMKeymap(arg1) { + return window['go']['app']['App']['GetVMKeymap'](arg1); +} + export function GetVMMacOS(arg1) { return window['go']['app']['App']['GetVMMacOS'](arg1); } @@ -434,6 +426,18 @@ export function OpenVSCodeSSHWithDriver(arg1, arg2, arg3) { return window['go']['app']['App']['OpenVSCodeSSHWithDriver'](arg1, arg2, arg3); } +export function OpenWindowsSecurityExclusions() { + return window['go']['app']['App']['OpenWindowsSecurityExclusions'](); +} + +export function OptimizeVMDisk(arg1) { + return window['go']['app']['App']['OptimizeVMDisk'](arg1); +} + +export function OptimizeVMDiskWithDriver(arg1, arg2) { + return window['go']['app']['App']['OptimizeVMDiskWithDriver'](arg1, arg2); +} + export function PanelBridgeCall(arg1, arg2, arg3) { return window['go']['app']['App']['PanelBridgeCall'](arg1, arg2, arg3); } @@ -550,6 +554,10 @@ export function SetDataRoot(arg1) { return window['go']['app']['App']['SetDataRoot'](arg1); } +export function SetFullscreenHotkey(arg1) { + return window['go']['app']['App']['SetFullscreenHotkey'](arg1); +} + export function SetGuestPreventSleep(arg1, arg2) { return window['go']['app']['App']['SetGuestPreventSleep'](arg1, arg2); } @@ -594,14 +602,14 @@ export function SetVMDisplayWithDriver(arg1, arg2, arg3) { return window['go']['app']['App']['SetVMDisplayWithDriver'](arg1, arg2, arg3); } -export function SetVMKeymap(arg1, arg2) { - return window['go']['app']['App']['SetVMKeymap'](arg1, arg2); -} - export function SetVMDriveShareSettings(arg1, arg2, arg3) { return window['go']['app']['App']['SetVMDriveShareSettings'](arg1, arg2, arg3); } +export function SetVMKeymap(arg1, arg2) { + return window['go']['app']['App']['SetVMKeymap'](arg1, arg2); +} + export function SetVMNote(arg1, arg2) { return window['go']['app']['App']['SetVMNote'](arg1, arg2); } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 89b5108..1c88320 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -246,6 +246,38 @@ export namespace app { return a; } } + export class FullscreenHotkeyConfig { + enabled: boolean; + hotkey: string; + + static createFrom(source: any = {}) { + return new FullscreenHotkeyConfig(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.enabled = source["enabled"]; + this.hotkey = source["hotkey"]; + } + } + export class FullscreenHotkeyStatus { + enabled: boolean; + hotkey: string; + default_hotkey: string; + hook_active: boolean; + + static createFrom(source: any = {}) { + return new FullscreenHotkeyStatus(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.enabled = source["enabled"]; + this.hotkey = source["hotkey"]; + this.default_hotkey = source["default_hotkey"]; + this.hook_active = source["hook_active"]; + } + } export class GuestToolsHostDNSStatus { host_dns_enabled: boolean; host_dns_active: boolean; @@ -675,6 +707,8 @@ export namespace config { sync_host_memory_smbios?: boolean; host_dns_mode?: string; host_dns_doh_url?: string; + fullscreen_hotkey_enabled?: boolean; + fullscreen_hotkey?: string; static createFrom(source: any = {}) { return new Config(source); @@ -693,6 +727,8 @@ export namespace config { this.sync_host_memory_smbios = source["sync_host_memory_smbios"]; this.host_dns_mode = source["host_dns_mode"]; this.host_dns_doh_url = source["host_dns_doh_url"]; + this.fullscreen_hotkey_enabled = source["fullscreen_hotkey_enabled"]; + this.fullscreen_hotkey = source["fullscreen_hotkey"]; } } diff --git a/internal/app/app.go b/internal/app/app.go index 320e621..214c18f 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -139,6 +139,9 @@ type App struct { keymapPIDs map[string]int fallbackInputSvc *host.InputService inputShuttingDown bool + fullscreenHotkey host.FullscreenHotkeyService + fullscreenSyncMu sync.Mutex + fullscreenTargets fullscreenHotkeyTargetCache } // Lifecycle exposes Wails lifecycle callbacks without exporting them as @@ -197,6 +200,7 @@ func (a *App) startup(ctx context.Context) { a.openDataRoot() } a.initPlugins() + a.syncFullscreenHotkeyTargets() // Without a plugin manager, run the IME bridge and Guest Tools directly. // With one, their plugins own them, and a plugin switched off stays off. a.mu.Lock() @@ -258,6 +262,7 @@ func (a *App) shutdown(ctx context.Context) { a.inputShuttingDown = true fallback := a.fallbackInputSvc a.mu.Unlock() + a.fullscreenHotkey.Close() if fallback != nil { fallback.Close() } @@ -468,6 +473,7 @@ func (a *App) pollVMs(ctx context.Context) { ib.SetTargets(imeTargets) } a.syncKeymapRules() + a.syncFullscreenHotkeyTargets() if tm != nil { effLoc := i18n.EffectiveLocale(loc) if runningCount >= 1 { @@ -972,6 +978,8 @@ func (a *App) SetDataRoot(dir string) error { curMinToTray := a.cfg.MinimizeToTray curSyncHostMemSMBIOS := a.cfg.SyncHostMemorySMBIOS curHostDNS := a.hostDNSConfigLocked() + curFullscreenHotkeyEnabled := a.cfg.FullscreenHotkeyEnabled + curFullscreenHotkey := a.cfg.FullscreenHotkey for _, v := range a.lastVMs { if v.State == "running" || v.State == "starting" || v.State == "stopping" || v.State == "suspending" || v.State == "resuming" { a.mu.Unlock() @@ -1018,6 +1026,8 @@ func (a *App) SetDataRoot(dir string) error { nextCfg.MinimizeToTray = curMinToTray nextCfg.SyncHostMemorySMBIOS = curSyncHostMemSMBIOS nextCfg.HostDNSMode, nextCfg.HostDNSDoHURL = curHostDNS.Mode, curHostDNS.DoHURL + nextCfg.FullscreenHotkeyEnabled = curFullscreenHotkeyEnabled + nextCfg.FullscreenHotkey = curFullscreenHotkey } if err := nextCfg.EnsureDirs(); err != nil { return err @@ -1046,8 +1056,12 @@ func (a *App) SetDataRoot(dir string) error { // Leaving a read-only folder starts the plugins and polling it held back, // even when the user picked the same folder again after fixing it. - if filepath.Clean(prev) != filepath.Clean(dir) || wasReadOnly { + rootChanged := filepath.Clean(prev) != filepath.Clean(dir) || wasReadOnly + if rootChanged { a.resetDataRootCaches() + } + a.syncFullscreenHotkeyTargets() + if rootChanged { a.reloadPlugins() a.wakePoll() if a.ctx != nil { diff --git a/internal/app/fullscreen_hotkey_flow.go b/internal/app/fullscreen_hotkey_flow.go new file mode 100644 index 0000000..f0413fb --- /dev/null +++ b/internal/app/fullscreen_hotkey_flow.go @@ -0,0 +1,162 @@ +package app + +import ( + "strings" + + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/host" +) + +type FullscreenHotkeyConfig struct { + Enabled bool `json:"enabled"` + Hotkey string `json:"hotkey"` +} + +type FullscreenHotkeyStatus struct { + Enabled bool `json:"enabled"` + Hotkey string `json:"hotkey"` + DefaultHotkey string `json:"default_hotkey"` + HookActive bool `json:"hook_active"` +} + +type fullscreenHotkeyVM struct { + driverID string + target host.IMETarget +} + +type fullscreenHotkeyTargetCache struct { + root string + legacy bool + supported map[fullscreenHotkeyVM]bool +} + +func (a *App) GetFullscreenHotkey() FullscreenHotkeyStatus { + a.mu.Lock() + defer a.mu.Unlock() + return FullscreenHotkeyStatus{ + Enabled: a.cfg.FullscreenHotkeyEnabled, + Hotkey: effectiveFullscreenHotkey(a.cfg.FullscreenHotkey), + DefaultHotkey: host.DefaultFullscreenHotkey, + HookActive: a.fullscreenHotkey.HookActive(), + } +} + +func (a *App) SetFullscreenHotkey(req FullscreenHotkeyConfig) (FullscreenHotkeyStatus, error) { + if err := a.requireWritableDataRoot(); err != nil { + return FullscreenHotkeyStatus{}, err + } + _, canonical, err := host.ParseFullscreenHotkey(req.Hotkey) + if err != nil { + return FullscreenHotkeyStatus{}, err + } + a.mu.Lock() + oldEnabled, oldHotkey := a.cfg.FullscreenHotkeyEnabled, a.cfg.FullscreenHotkey + if req.Enabled != oldEnabled && strings.TrimSpace(req.Hotkey) == "" { + canonical = effectiveFullscreenHotkey(oldHotkey) + } + a.cfg.FullscreenHotkeyEnabled = req.Enabled + a.cfg.FullscreenHotkey = canonical + if err := a.saveConfigLocked(); err != nil { + a.cfg.FullscreenHotkeyEnabled = oldEnabled + a.cfg.FullscreenHotkey = oldHotkey + a.mu.Unlock() + return FullscreenHotkeyStatus{}, err + } + a.mu.Unlock() + + a.syncFullscreenHotkeyTargets() + a.emitLifecycleStateChanged() + return a.GetFullscreenHotkey(), nil +} + +func effectiveFullscreenHotkey(raw string) string { + _, canonical, err := host.ParseFullscreenHotkey(raw) + if err != nil { + return host.DefaultFullscreenHotkey + } + return canonical +} + +func (a *App) syncFullscreenHotkeyTargets() { + a.fullscreenSyncMu.Lock() + defer a.fullscreenSyncMu.Unlock() + a.mu.Lock() + enabled, raw, root := a.cfg.FullscreenHotkeyEnabled, a.cfg.FullscreenHotkey, a.cfg.DataRoot + vms, legacy := a.lastVMs, a.lifecycleSvc == nil + a.mu.Unlock() + hotkey, _, err := host.ParseFullscreenHotkey(raw) + if err != nil { + hotkey, _, _ = host.ParseFullscreenHotkey(host.DefaultFullscreenHotkey) + } + var targets []host.IMETarget + var cache fullscreenHotkeyTargetCache + if enabled { + cache = a.fullscreenTargets + if cache.root != root || cache.legacy != legacy { + cache = fullscreenHotkeyTargetCache{root: root, legacy: legacy} + } + targets, cache.supported = a.fullscreenHotkeyTargets(vms, legacy, cache.supported) + } + a.mu.Lock() + defer a.mu.Unlock() + if a.cfg.DataRoot == root && a.cfg.FullscreenHotkeyEnabled == enabled && a.cfg.FullscreenHotkey == raw { + a.fullscreenTargets = cache + a.fullscreenHotkey.Sync(enabled, hotkey, targets, a.onFullscreenHotkey) + } +} + +func (a *App) fullscreenHotkeyTargets(vms []driver.VMListItem, legacy bool, cached map[fullscreenHotkeyVM]bool) ([]host.IMETarget, map[fullscreenHotkeyVM]bool) { + var targets []host.IMETarget + support := make(map[fullscreenHotkeyVM]bool, len(cached)) + for _, vm := range vms { + if vm.State != "running" || vm.PID == nil || *vm.PID <= 0 { + continue + } + target := host.IMETarget{VMName: vm.Name, VMDir: vm.Dir, PID: uint32(*vm.PID)} + key := fullscreenHotkeyVM{driverID: vm.DriverID, target: target} + supported, known := cached[key] + if !known { + supported, known = a.fullscreenHotkeySupported(vm, legacy) + if !known { + continue + } + } + support[key] = supported + if supported { + targets = append(targets, target) + } + } + return targets, support +} + +func (a *App) fullscreenHotkeySupported(vm driver.VMListItem, legacy bool) (supported, known bool) { + // Only cache running details so a lookup that races startup can be retried. + if legacy { + detail, err := a.GetVMDetail(vm.Name) + return detail.Graphics != "vmware-svga", err == nil && detail.State == "running" + } + detail, err := a.resolveVMInfo(vm.DriverID, vm.Name) + return detail.DriverData["graphics"] != "vmware-svga", err == nil && detail.State == "running" +} + +func (a *App) onFullscreenHotkey(target host.IMETarget, hwnd uintptr) { + a.mu.Lock() + if a.inputShuttingDown || !a.cfg.FullscreenHotkeyEnabled { + a.mu.Unlock() + return + } + for _, vm := range a.lastVMs { + if vm.State != "running" || vm.Name != target.VMName || vm.Dir != target.VMDir || vm.PID == nil || *vm.PID != int(target.PID) { + continue + } + a.mu.Unlock() + if !host.IsForegroundDisplayWindow(hwnd, target.PID) { + return + } + if _, err := a.ToggleVMFullscreenWithDriver(vm.DriverID, target.VMName); err != nil { + a.emitVMLogForDriver(vm.DriverID, target.VMName, err.Error()) + } + return + } + a.mu.Unlock() +} diff --git a/internal/app/fullscreen_hotkey_flow_test.go b/internal/app/fullscreen_hotkey_flow_test.go new file mode 100644 index 0000000..a89fc70 --- /dev/null +++ b/internal/app/fullscreen_hotkey_flow_test.go @@ -0,0 +1,178 @@ +package app + +import ( + "bytes" + "context" + "os" + "path/filepath" + "runtime" + "slices" + "testing" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/plugin" + "github.com/Nwflower/reims-go/internal/plugin/builtin" +) + +func TestFullscreenHotkeySettings(t *testing.T) { + a := &App{cfg: &config.Config{DataRoot: t.TempDir()}} + t.Cleanup(a.fullscreenHotkey.Close) + want := FullscreenHotkeyStatus{Hotkey: host.DefaultFullscreenHotkey, DefaultHotkey: host.DefaultFullscreenHotkey} + if got := a.GetFullscreenHotkey(); got != want { + t.Fatalf("default status = %+v, want %+v", got, want) + } + + want.Enabled = true + want.Hotkey = "Ctrl+Alt+Enter" + got, err := a.SetFullscreenHotkey(FullscreenHotkeyConfig{Enabled: true, Hotkey: "option+return+control"}) + if err != nil || got != want { + t.Fatalf("enabled status = %+v, %v, want %+v", got, err, want) + } + path := filepath.Join(a.cfg.DataRoot, "reims-go.json") + before, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if _, err := a.SetFullscreenHotkey(FullscreenHotkeyConfig{Hotkey: "Alt+Tab"}); err == nil { + t.Fatal("invalid request succeeded") + } + after, err := os.ReadFile(path) + if err != nil || !bytes.Equal(before, after) || a.GetFullscreenHotkey() != want { + t.Fatalf("invalid update changed settings: read error = %v, status = %+v", err, a.GetFullscreenHotkey()) + } + + want.Enabled = false + got, err = a.SetFullscreenHotkey(FullscreenHotkeyConfig{}) + if err != nil || got != want { + t.Fatalf("disabled status = %+v, %v, want %+v", got, err, want) + } + saved, err := config.Load(path) + if err != nil { + t.Fatal(err) + } + if saved.FullscreenHotkeyEnabled || saved.FullscreenHotkey != want.Hotkey { + t.Fatalf("saved settings = %t, %q", saved.FullscreenHotkeyEnabled, saved.FullscreenHotkey) + } + want.Enabled = true + got, err = a.SetFullscreenHotkey(FullscreenHotkeyConfig{Enabled: true}) + if err != nil || got != want { + t.Fatalf("re-enabled status = %+v, %v, want %+v", got, err, want) + } +} + +func TestFullscreenHotkeySyncWithInputPluginDisabled(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "reims-go.json") + if err := os.WriteFile(path, []byte(`{"fullscreen_hotkey_enabled":true,"fullscreen_hotkey":"Alt+Tab","auto_pin_pcores":false}`), 0o644); err != nil { + t.Fatal(err) + } + cfg, err := config.Load(path) + if err != nil { + t.Fatal(err) + } + pid := 1234 + svgaPID := 1235 + const driverID = driver.BuiltinReimsMacOSDriverID + d := &fullscreenHotkeyTestDriver{appSecondDriver: appSecondDriver{id: driverID, vms: []driver.VMInfo{ + {Name: "mac", DriverID: driverID, Directory: dir, State: "running", PID: &pid}, + {Name: "svga", DriverID: driverID, Directory: dir, State: "running", PID: &svgaPID, DriverData: map[string]any{"graphics": "vmware-svga"}}, + }}} + a := newDisplayTestApp(t, d) + a.cfg = cfg + mgr, err := plugin.NewManager(plugin.ManagerOptions{DataRoot: dir, HostVersion: "0.0.0"}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(mgr.Close) + t.Cleanup(a.fullscreenHotkey.Close) + a.pluginMgr = mgr + if err := builtin.RegisterAll(mgr.Registry(), builtin.HostCallbacks{}, mgr.DesiredFor); err != nil { + t.Fatal(err) + } + mgr.Registry().Reconcile(context.Background()) + if a.getInputService() == nil { + t.Fatal("input plugin did not start") + } + if err := mgr.Disable(context.Background(), builtin.IDInput); err != nil { + t.Fatal(err) + } + if a.getInputService() != nil { + t.Fatal("input service is still present after disabling the plugin") + } + a.lastVMs, err = a.listVMsInternal(context.Background()) + if err != nil { + t.Fatal(err) + } + wantTargets := []host.IMETarget{{VMName: "mac", VMDir: dir, PID: uint32(pid)}} + if got, _ := a.fullscreenHotkeyTargets(a.lastVMs, false, nil); !slices.Equal(got, wantTargets) { + t.Fatalf("fullscreen targets = %+v, want %+v", got, wantTargets) + } + a.syncFullscreenHotkeyTargets() + d.shows = 0 + samePID := pid + a.lastVMs[0].PID = &samePID + a.syncFullscreenHotkeyTargets() + if d.shows != 0 { + t.Fatalf("steady poll resolved %d VM details", d.shows) + } + newPID := pid + 2 + a.lastVMs[0].PID = &newPID + a.syncFullscreenHotkeyTargets() + if d.shows != 1 { + t.Fatalf("PID change resolved %d VM details, want 1", d.shows) + } + a.lastVMs[0].PID = &pid + a.syncFullscreenHotkeyTargets() + got := a.GetFullscreenHotkey() + if !got.Enabled || got.Hotkey != host.DefaultFullscreenHotkey || got.HookActive != (runtime.GOOS == "windows") || + cfg.AutoPinPCores || cfg.FullscreenHotkey != "Alt+Tab" { + t.Fatalf("unexpected fallback status or config: %+v, %+v", got, cfg) + } + logCount := len(a.recentLogs) + a.onFullscreenHotkey(wantTargets[0], 0) + if len(a.recentLogs) != logCount { + t.Fatal("shortcut attempted to toggle a VM without its foreground window") + } + if runtime.GOOS == "windows" { + blocked := newDisplayTestApp(t, d) + blocked.cfg.DataRoot = t.TempDir() + blocked.lastVMs = a.lastVMs + t.Cleanup(blocked.fullscreenHotkey.Close) + status, err := blocked.SetFullscreenHotkey(FullscreenHotkeyConfig{Enabled: true, Hotkey: "F8"}) + if err != nil || !status.Enabled || status.HookActive { + t.Fatalf("failed hook installation status = %+v, %v", status, err) + } + } + a.lastVMs = slices.DeleteFunc(a.lastVMs, func(vm driver.VMListItem) bool { return vm.Name == "mac" }) + a.syncFullscreenHotkeyTargets() + if got := a.GetFullscreenHotkey(); got.HookActive { + t.Fatalf("hook still installed with only SVGA running: %+v", got) + } +} + +type fullscreenHotkeyTestDriver struct { + appSecondDriver + shows int +} + +func (d *fullscreenHotkeyTestDriver) Show(ctx context.Context, name string) (driver.VMInfo, error) { + d.shows++ + return d.appSecondDriver.Show(ctx, name) +} + +func TestFullscreenHotkeySaveFailure(t *testing.T) { + dir := t.TempDir() + if err := os.Mkdir(filepath.Join(dir, "reims-go.json"), 0o755); err != nil { + t.Fatal(err) + } + a := &App{cfg: &config.Config{DataRoot: dir, FullscreenHotkey: "F8"}} + t.Cleanup(a.fullscreenHotkey.Close) + if _, err := a.SetFullscreenHotkey(FullscreenHotkeyConfig{Enabled: true, Hotkey: "F9"}); err == nil { + t.Fatal("save to a directory succeeded") + } + if got := a.GetFullscreenHotkey(); got.Enabled || got.Hotkey != "F8" || got.HookActive { + t.Fatalf("failed save changed app settings: %+v", got) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 3e5063d..0078a02 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -32,6 +32,9 @@ type Config struct { SyncHostMemorySMBIOS bool `json:"sync_host_memory_smbios,omitempty"` HostDNSMode string `json:"host_dns_mode,omitempty"` HostDNSDoHURL string `json:"host_dns_doh_url,omitempty"` + + FullscreenHotkeyEnabled bool `json:"fullscreen_hotkey_enabled,omitempty"` + FullscreenHotkey string `json:"fullscreen_hotkey,omitempty"` } // ShouldMinimizeToTray returns true when closing the main window should hide to tray. @@ -209,9 +212,22 @@ func Load(path string) (*Config, error) { return nil, err } cfg := Default() - if err := json.Unmarshal(raw, cfg); err != nil { + disk := struct { + *Config + FullscreenHotkeyEnabled json.RawMessage `json:"fullscreen_hotkey_enabled"` + FullscreenHotkey json.RawMessage `json:"fullscreen_hotkey"` + }{Config: cfg} + if err := json.Unmarshal(raw, &disk); err != nil { return nil, err } + if len(disk.FullscreenHotkeyEnabled) != 0 { + // The optional shortcut fields retain their defaults on a type mismatch. + _ = json.Unmarshal(disk.FullscreenHotkeyEnabled, &cfg.FullscreenHotkeyEnabled) + } + if len(disk.FullscreenHotkey) != 0 { + _ = json.Unmarshal(disk.FullscreenHotkey, &cfg.FullscreenHotkey) + cfg.FullscreenHotkey = strings.TrimSpace(cfg.FullscreenHotkey) + } if cfg.DataRoot == "" { cfg.DataRoot = filepath.Dir(path) } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index d95dc1f..02c118e 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -51,6 +51,30 @@ func TestFirstLaunchNeedsSetupUntilAFolderIsChosen(t *testing.T) { } } +func TestLoadFullscreenHotkeyFields(t *testing.T) { + for _, tc := range []struct { + name, raw, hotkey string + enabled bool + }{ + {"invalid key", `{"auto_pin_pcores":false,"fullscreen_hotkey":123,"fullscreen_hotkey_enabled":true}`, "", true}, + {"invalid enabled", `{"auto_pin_pcores":false,"fullscreen_hotkey":" Ctrl+F ","fullscreen_hotkey_enabled":"yes"}`, "Ctrl+F", false}, + } { + t.Run(tc.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "reims-go.json") + if err := os.WriteFile(path, []byte(tc.raw), 0o644); err != nil { + t.Fatal(err) + } + cfg, err := Load(path) + if err != nil { + t.Fatal(err) + } + if cfg.AutoPinPCores || cfg.FullscreenHotkey != tc.hotkey || cfg.FullscreenHotkeyEnabled != tc.enabled { + t.Fatalf("unexpected config: %+v", cfg) + } + }) + } +} + func TestExistingInstallIsAdoptedWithoutAsking(t *testing.T) { legacy := isolate(t) cfg := Default() diff --git a/internal/host/fullscreen_hotkey.go b/internal/host/fullscreen_hotkey.go new file mode 100644 index 0000000..e15b92d --- /dev/null +++ b/internal/host/fullscreen_hotkey.go @@ -0,0 +1,234 @@ +package host + +import ( + "fmt" + "strings" + "sync" + "sync/atomic" +) + +const DefaultFullscreenHotkey = "Ctrl+Shift+F" + +type FullscreenHotkey struct { + Ctrl, Shift, Alt, Win bool + VK uint32 + Key string +} + +var fullscreenNamedKeys = map[string]struct { + vk uint32 + key string +}{ + "ENTER": {0x0D, "Enter"}, "RETURN": {0x0D, "Enter"}, + "SPACE": {0x20, "Space"}, "TAB": {0x09, "Tab"}, + "ESCAPE": {0x1B, "Escape"}, "ESC": {0x1B, "Escape"}, + "BACKSPACE": {0x08, "Backspace"}, + "INSERT": {0x2D, "Insert"}, "DELETE": {0x2E, "Delete"}, + "HOME": {0x24, "Home"}, "END": {0x23, "End"}, + "PAGEUP": {0x21, "PageUp"}, "PAGEDOWN": {0x22, "PageDown"}, + "UP": {0x26, "Up"}, "DOWN": {0x28, "Down"}, + "LEFT": {0x25, "Left"}, "RIGHT": {0x27, "Right"}, +} + +func ParseFullscreenHotkey(raw string) (FullscreenHotkey, string, error) { + if strings.TrimSpace(raw) == "" { + raw = DefaultFullscreenHotkey + } + var hk FullscreenHotkey + for _, part := range strings.Split(raw, "+") { + token := strings.ToUpper(strings.TrimSpace(part)) + var mod *bool + switch token { + case "CTRL", "CONTROL": + mod = &hk.Ctrl + case "SHIFT": + mod = &hk.Shift + case "ALT", "OPTION": + mod = &hk.Alt + case "WIN", "META", "SUPER": + mod = &hk.Win + } + if mod != nil { + if *mod { + return FullscreenHotkey{}, "", fmt.Errorf("duplicate hotkey modifier %q", part) + } + *mod = true + continue + } + if hk.VK != 0 { + return FullscreenHotkey{}, "", fmt.Errorf("expected one hotkey key, found additional key %q", part) + } + switch { + case len(token) == 1 && (token[0] >= 'A' && token[0] <= 'Z' || token[0] >= '0' && token[0] <= '9'): + hk.VK, hk.Key = uint32(token[0]), token + case len(token) == 2 && token[0] == 'F' && token[1] >= '1' && token[1] <= '9': + hk.VK, hk.Key = 0x70+uint32(token[1]-'1'), token + case token == "F10" || token == "F11" || token == "F12": + hk.VK, hk.Key = 0x79+uint32(token[2]-'0'), token + default: + key, ok := fullscreenNamedKeys[token] + if !ok { + return FullscreenHotkey{}, "", fmt.Errorf("unsupported hotkey key %q", part) + } + hk.VK, hk.Key = key.vk, key.key + } + } + if hk.VK == 0 { + return FullscreenHotkey{}, "", fmt.Errorf("hotkey requires a key") + } + var parts []string + if hk.Ctrl { + parts = append(parts, "Ctrl") + } + if hk.Shift { + parts = append(parts, "Shift") + } + if hk.Alt { + parts = append(parts, "Alt") + } + if hk.Win { + parts = append(parts, "Win") + } + if len(parts) == 0 && (hk.VK < 0x70 || hk.VK > 0x7B) { + return FullscreenHotkey{}, "", fmt.Errorf("hotkey %q requires a modifier", hk.Key) + } + canonical := strings.Join(append(parts, hk.Key), "+") + if hk.Ctrl && hk.Alt && hk.Key == "Delete" || hk.Alt && (hk.Key == "F4" || hk.Key == "Tab") || hk.Win && hk.Key == "L" { + return FullscreenHotkey{}, "", fmt.Errorf("hotkey %q is reserved by Windows", canonical) + } + return hk, canonical, nil +} + +type FullscreenHotkeyMods struct{ Ctrl, Shift, Alt, Win bool } + +type FullscreenHotkeyMatcher struct { + Hotkey FullscreenHotkey + down bool + suppressedVK uint32 +} + +func (m *FullscreenHotkeyMatcher) Handle(vk uint32, isDown bool, isForegroundVM bool, mods FullscreenHotkeyMods) (consume bool, trigger bool) { + if vk != 0 && vk == m.suppressedVK { + if !isDown { + m.suppressedVK = 0 + } + return true, false + } + if vk != m.Hotkey.VK { + return false, false + } + if !isDown { + m.down = false + return false, false + } + if m.down { + return false, false + } + if m.suppressedVK == 0 && isForegroundVM && mods == (FullscreenHotkeyMods{ + Ctrl: m.Hotkey.Ctrl, Shift: m.Hotkey.Shift, Alt: m.Hotkey.Alt, Win: m.Hotkey.Win, + }) { + m.suppressedVK = vk + return true, true + } + m.down = true + return false, false +} + +func (m *FullscreenHotkeyMatcher) Reset() { + m.down = false + m.suppressedVK = 0 +} + +func (m *FullscreenHotkeyMatcher) setHotkey(hotkey FullscreenHotkey) { + if hotkey != m.Hotkey { + m.down = false + m.Hotkey = hotkey + } +} + +const ( + vkLShift = 0xA0 + vkRShift = 0xA1 +) + +var fullscreenModifierVKs = [...]uint32{vkLCtrl, vkRCtrl, vkLShift, vkRShift, vkLAlt, vkRAlt, vkLWin, vkRWin} + +type fullscreenPhysicalModifiers struct { + down [len(fullscreenModifierVKs)]bool + asyncReliable [len(fullscreenModifierVKs)]bool +} + +func (m *fullscreenPhysicalModifiers) handle(vk uint32, down, injected, remapped bool) { + for i, modifier := range fullscreenModifierVKs { + if vk != modifier { + continue + } + m.asyncReliable[i] = !injected && !remapped + if !injected { + m.down[i] = down + } + return + } +} + +func (m *fullscreenPhysicalModifiers) mods() FullscreenHotkeyMods { + return FullscreenHotkeyMods{ + Ctrl: m.down[0] || m.down[1], Shift: m.down[2] || m.down[3], + Alt: m.down[4] || m.down[5], Win: m.down[6] || m.down[7], + } +} + +type fullscreenHotkeySettings struct { + hotkey FullscreenHotkey + targets map[uint32]IMETarget + onTrigger func(IMETarget, uintptr) +} + +// FullscreenHotkeyService owns the shortcut hook independently of input plugins. +type FullscreenHotkeyService struct { + mu sync.Mutex + settings atomic.Pointer[fullscreenHotkeySettings] + hook *fullscreenHotkeyHook + closed bool +} + +func (s *FullscreenHotkeyService) Sync(enabled bool, hotkey FullscreenHotkey, targets []IMETarget, onTrigger func(IMETarget, uintptr)) { + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return + } + if !enabled || len(targets) == 0 { + s.stopLocked() + return + } + byPID := make(map[uint32]IMETarget, len(targets)) + for _, target := range targets { + byPID[target.PID] = target + } + s.settings.Store(&fullscreenHotkeySettings{hotkey: hotkey, targets: byPID, onTrigger: onTrigger}) + if s.hook == nil || !s.hook.active() { + s.hook = startFullscreenHotkeyHook(s) + } +} + +func (s *FullscreenHotkeyService) HookActive() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.hook != nil && s.hook.active() +} + +func (s *FullscreenHotkeyService) Close() { + s.mu.Lock() + defer s.mu.Unlock() + s.closed = true + s.stopLocked() +} + +func (s *FullscreenHotkeyService) stopLocked() { + s.settings.Store(nil) + if s.hook != nil { + s.hook.Close() + s.hook = nil + } +} diff --git a/internal/host/fullscreen_hotkey_other.go b/internal/host/fullscreen_hotkey_other.go new file mode 100644 index 0000000..c980170 --- /dev/null +++ b/internal/host/fullscreen_hotkey_other.go @@ -0,0 +1,15 @@ +//go:build !windows + +package host + +type fullscreenHotkeyHook struct{} + +func startFullscreenHotkeyHook(_ *FullscreenHotkeyService) *fullscreenHotkeyHook { return nil } + +func (h *fullscreenHotkeyHook) Close() {} + +func (h *fullscreenHotkeyHook) active() bool { return false } + +func prioritizeFullscreenHotkeyHook() {} + +func IsForegroundDisplayWindow(_ uintptr, _ uint32) bool { return false } diff --git a/internal/host/fullscreen_hotkey_test.go b/internal/host/fullscreen_hotkey_test.go new file mode 100644 index 0000000..a5f3bc9 --- /dev/null +++ b/internal/host/fullscreen_hotkey_test.go @@ -0,0 +1,156 @@ +package host + +import ( + "runtime" + "testing" +) + +func TestParseFullscreenHotkey(t *testing.T) { + for _, tc := range []struct { + raw, canonical string + want FullscreenHotkey + }{ + {"", DefaultFullscreenHotkey, FullscreenHotkey{Ctrl: true, Shift: true, VK: 'F', Key: "F"}}, + {" \t ", DefaultFullscreenHotkey, FullscreenHotkey{Ctrl: true, Shift: true, VK: 'F', Key: "F"}}, + {" meta + return + option + SHIFT + control ", "Ctrl+Shift+Alt+Win+Enter", FullscreenHotkey{Ctrl: true, Shift: true, Alt: true, Win: true, VK: 0x0D, Key: "Enter"}}, + {"super+esc", "Win+Escape", FullscreenHotkey{Win: true, VK: 0x1B, Key: "Escape"}}, + {"Ctrl+0", "Ctrl+0", FullscreenHotkey{Ctrl: true, VK: '0', Key: "0"}}, + {"f1", "F1", FullscreenHotkey{VK: 0x70, Key: "F1"}}, + {"f9", "F9", FullscreenHotkey{VK: 0x78, Key: "F9"}}, + {"F10", "F10", FullscreenHotkey{VK: 0x79, Key: "F10"}}, + {"F12", "F12", FullscreenHotkey{VK: 0x7B, Key: "F12"}}, + {"alt+pagedown", "Alt+PageDown", FullscreenHotkey{Alt: true, VK: 0x22, Key: "PageDown"}}, + {"shift+space", "Shift+Space", FullscreenHotkey{Shift: true, VK: 0x20, Key: "Space"}}, + } { + t.Run(tc.raw, func(t *testing.T) { + hk, canonical, err := ParseFullscreenHotkey(tc.raw) + if err != nil || hk != tc.want || canonical != tc.canonical { + t.Fatalf("got %+v, %q, %v; want %+v, %q", hk, canonical, err, tc.want, tc.canonical) + } + }) + } + for _, raw := range []string{ + "Ctrl+Shift", "Ctrl+A+B", "Ctrl+Control+A", "Option+Alt+F1", "Meta+Win+F1", + "A", "7", "Tab", "Ctrl++F", "F0", "F01", "Ctrl+F13", "Ctrl+F24", + "delete+alt+control", "Alt+F4", "Alt+Tab", "Win+L", "Alt+Shift+Tab", + } { + t.Run(raw, func(t *testing.T) { + if _, _, err := ParseFullscreenHotkey(raw); err == nil { + t.Fatalf("accepted invalid hotkey %q", raw) + } + }) + } +} + +func TestFullscreenHotkeyMatcher(t *testing.T) { + hk, _, err := ParseFullscreenHotkey(DefaultFullscreenHotkey) + if err != nil { + t.Fatal(err) + } + matcher := FullscreenHotkeyMatcher{Hotkey: hk} + mods := FullscreenHotkeyMods{Ctrl: true, Shift: true} + extra := FullscreenHotkeyMods{Ctrl: true, Shift: true, Alt: true} + for _, step := range []struct { + name string + key uint32 + down, foreground bool + mods FullscreenHotkeyMods + consume, trigger bool + }{ + {"other key", 'G', true, true, mods, false, false}, + {"first press outside VM", 'F', true, false, mods, false, false}, + {"unmatched press repeats inside VM", 'F', true, true, mods, false, false}, + {"unmatched release", 'F', false, true, mods, false, false}, + {"extra modifier", 'F', true, true, extra, false, false}, + {"release extra modifier chord", 'F', false, true, extra, false, false}, + {"match", 'F', true, true, mods, true, true}, + {"auto repeat", 'F', true, true, mods, true, false}, + {"repeat after focus and modifier change", 'F', true, false, FullscreenHotkeyMods{}, true, false}, + {"release after focus change", 'F', false, false, FullscreenHotkeyMods{}, true, false}, + {"second release", 'F', false, false, mods, false, false}, + {"next press", 'F', true, true, mods, true, true}, + } { + consume, trigger := matcher.Handle(step.key, step.down, step.foreground, step.mods) + if consume != step.consume || trigger != step.trigger { + t.Fatalf("%s: got (%v, %v), want (%v, %v)", step.name, consume, trigger, step.consume, step.trigger) + } + } + matcher.Reset() + if consume, trigger := matcher.Handle('F', false, false, mods); consume || trigger { + t.Fatalf("reset left suppression active: (%v, %v)", consume, trigger) + } +} + +func TestFullscreenHotkeyHookLifecycle(t *testing.T) { + svc := &FullscreenHotkeyService{} + t.Cleanup(svc.Close) + targets := []IMETarget{{VMName: "mac", PID: 1234}} + callback := func(IMETarget, uintptr) {} + hotkey, _, _ := ParseFullscreenHotkey("") + assertHook := func(want bool) { + t.Helper() + if got := svc.HookActive(); got != want { + t.Fatalf("fullscreen hook installed = %t, want %t", got, want) + } + } + svc.Sync(true, hotkey, nil, callback) + assertHook(false) + svc.Sync(true, hotkey, targets, callback) + assertHook(runtime.GOOS == "windows") + svc.Sync(true, hotkey, nil, callback) + assertHook(false) + svc.Sync(true, hotkey, targets, callback) + assertHook(runtime.GOOS == "windows") + svc.Sync(false, hotkey, targets, callback) + assertHook(false) + svc.Sync(true, hotkey, targets, callback) + assertHook(runtime.GOOS == "windows") + svc.Close() + svc.Sync(true, hotkey, targets, callback) + assertHook(false) +} + +func TestFullscreenHotkeyReconfigurationWhileHeld(t *testing.T) { + f8, _, _ := ParseFullscreenHotkey("F8") + f9, _, _ := ParseFullscreenHotkey("F9") + m := FullscreenHotkeyMatcher{Hotkey: f8} + if consume, trigger := m.Handle(f8.VK, true, true, FullscreenHotkeyMods{}); !consume || !trigger { + t.Fatalf("F8 down = (%t, %t)", consume, trigger) + } + m.setHotkey(f9) + for _, down := range []bool{true, false} { + if consume, trigger := m.Handle(f8.VK, down, false, FullscreenHotkeyMods{}); !consume || trigger { + t.Fatalf("old F8 event down=%t = (%t, %t)", down, consume, trigger) + } + } + if consume, trigger := m.Handle(f9.VK, true, true, FullscreenHotkeyMods{}); !consume || !trigger { + t.Fatalf("F9 down = (%t, %t)", consume, trigger) + } + m.Reset() + if consume, trigger := m.Handle(f9.VK, true, true, FullscreenHotkeyMods{}); !consume || !trigger { + t.Fatalf("F9 down after reset = (%t, %t)", consume, trigger) + } +} + +func TestFullscreenPhysicalModifiersIgnoreInjectedKeys(t *testing.T) { + for i := 0; i < len(fullscreenModifierVKs); i += 2 { + left, right := fullscreenModifierVKs[i], fullscreenModifierVKs[i+1] + var m fullscreenPhysicalModifiers + m.handle(left, true, false, true) + first := m.mods() + if first == (FullscreenHotkeyMods{}) { + t.Fatalf("physical modifier %#x was ignored", left) + } + m.handle(left, false, true, true) + m.handle(right, true, false, true) + m.handle(left, false, false, true) + if got := m.mods(); got != first { + t.Fatalf("physical right modifier %#x: got %+v, want %+v", right, got, first) + } + m.handle(right, false, false, true) + m.handle(left, true, true, true) + if got := m.mods(); got != (FullscreenHotkeyMods{}) { + t.Fatalf("injected modifier %#x changed physical state: %+v", left, got) + } + } +} diff --git a/internal/host/fullscreen_hotkey_windows.go b/internal/host/fullscreen_hotkey_windows.go new file mode 100644 index 0000000..23e1a41 --- /dev/null +++ b/internal/host/fullscreen_hotkey_windows.go @@ -0,0 +1,223 @@ +//go:build windows + +package host + +import ( + "log" + "runtime" + "sync" + "sync/atomic" + "syscall" + "unsafe" +) + +var ( + fullscreenHotkeyCallback = sync.OnceValue(func() uintptr { return syscall.NewCallback(fullscreenKeyboardProc) }) + activeFullscreenHotkey atomic.Pointer[fullscreenHotkeyHook] +) + +const wmPrioritizeFullscreenHotkey = 0x8002 + +type fullscreenHotkeyHook struct { + service *FullscreenHotkeyService + threadID uintptr + done chan struct{} + triggers chan fullscreenHotkeyEvent + matcher FullscreenHotkeyMatcher + physical fullscreenPhysicalModifiers + pending sync.Map +} + +type fullscreenHotkeyEvent struct { + target IMETarget + hotkey FullscreenHotkey + hwnd uintptr +} + +func startFullscreenHotkeyHook(service *FullscreenHotkeyService) *fullscreenHotkeyHook { + h := &fullscreenHotkeyHook{ + service: service, + done: make(chan struct{}), + triggers: make(chan fullscreenHotkeyEvent, 16), + } + ready := make(chan bool) + go h.run(ready) + if !<-ready { + <-h.done + return nil + } + go h.dispatch() + return h +} + +func (h *fullscreenHotkeyHook) run(ready chan<- bool) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + defer close(h.done) + h.threadID, _, _ = procGetCurrentThreadId.Call() + var msg winMsg + procPeekMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0, pmNoRemove) + if !activeFullscreenHotkey.CompareAndSwap(nil, h) { + ready <- false + return + } + defer activeFullscreenHotkey.CompareAndSwap(h, nil) + if keymapInputDesktopAccessible() { + keymapActive := activeKeymapHook.Load() != nil + for _, vk := range fullscreenModifierVKs { + // Ctrl may already be held by key mapping when this hook starts. + if keymapActive && (vk == vkLCtrl || vk == vkRCtrl) { + continue + } + h.physical.handle(vk, keymapPhysicalDown(vk), false, keymapActive && hostModifiers[vk] != "") + } + } + timer, _, _ := procKeymapSetTimer.Call(0, 0, 50, 0) + if timer == 0 { + ready <- false + return + } + defer procKeymapKillTimer.Call(0, timer) + module, _, _ := procGetModuleHandleW.Call(0) + hook, _, _ := procSetWindowsHookExW.Call(whKeyboardLL, fullscreenHotkeyCallback(), module, 0) + if hook == 0 { + ready <- false + return + } + defer func() { procUnhookWindowsHookEx.Call(hook) }() + ready <- true + for { + result, _, _ := procGetMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0) + if int32(result) <= 0 { + return + } + switch msg.message { + case wmTimer: + h.reconcilePhysical() + case wmPrioritizeFullscreenHotkey: + // The newest hook runs first. See physical keys before key mapping can swallow them. + next, _, err := procSetWindowsHookExW.Call(whKeyboardLL, fullscreenHotkeyCallback(), module, 0) + if next == 0 { + log.Printf("fullscreen hotkey: SetWindowsHookExW failed while reprioritizing the keyboard hook; exiting hook loop: %v", err) + return + } + procUnhookWindowsHookEx.Call(hook) + hook = next + } + } +} + +func (h *fullscreenHotkeyHook) Close() { + procPostThreadMessageW.Call(h.threadID, wmQuit, 0, 0) + <-h.done +} + +func (h *fullscreenHotkeyHook) active() bool { + select { + case <-h.done: + return false + default: + return true + } +} + +func prioritizeFullscreenHotkeyHook() { + if h := activeFullscreenHotkey.Load(); h != nil { + procPostThreadMessageW.Call(h.threadID, wmPrioritizeFullscreenHotkey, 0, 0) + } +} + +func fullscreenKeyboardProc(code int32, message uintptr, kbd *kbdLLHookStruct) uintptr { + if code == hcAction && kbd != nil { + switch message { + case wmKeyDown, wmSysKeyDown, wmKeyUp, wmSysKeyUp: + if h := activeFullscreenHotkey.Load(); h != nil && + h.handleKey(kbd.vkCode, message == wmKeyDown || message == wmSysKeyDown, kbd.flags&llkhfInjected != 0) { + return 1 + } + } + } + result, _, _ := procCallNextHookEx.Call(0, uintptr(code), message, uintptr(unsafe.Pointer(kbd))) + return result +} + +func (h *fullscreenHotkeyHook) handleKey(vk uint32, down, injected bool) bool { + h.physical.handle(vk, down, injected, activeKeymapHook.Load() != nil && hostModifiers[vk] != "") + if injected { + return false + } + settings := h.service.settings.Load() + if settings == nil { + return false + } + h.matcher.setHotkey(settings.hotkey) + if vk != settings.hotkey.VK && vk != h.matcher.suppressedVK { + return false + } + if !keymapInputDesktopAccessible() { + h.resetKeys() + return false + } + if !down || h.matcher.down || h.matcher.suppressedVK != 0 { + consume, _ := h.matcher.Handle(vk, down, false, FullscreenHotkeyMods{}) + return consume + } + window, _, _ := procGetForegroundWindow.Call() + pid := windowPID(window) + target, found := settings.targets[pid] + consume, trigger := h.matcher.Handle(vk, down, found && isProcessDisplayWindow(window, pid), h.physical.mods()) + if trigger { + if _, pending := h.pending.LoadOrStore(pid, struct{}{}); !pending { + select { + case h.triggers <- fullscreenHotkeyEvent{target: target, hotkey: settings.hotkey, hwnd: window}: + default: + h.pending.Delete(pid) + } + } + } + return consume +} + +func (h *fullscreenHotkeyHook) resetKeys() { + h.matcher.Reset() + h.physical = fullscreenPhysicalModifiers{} +} + +func (h *fullscreenHotkeyHook) reconcilePhysical() { + if !keymapInputDesktopAccessible() { + h.resetKeys() + return + } + if h.matcher.suppressedVK != 0 { + // A swallowed down does not update GetAsyncKeyState. + return + } + if h.matcher.down && !keymapPhysicalDown(h.matcher.Hotkey.VK) { + h.matcher.Reset() + } + for i, vk := range fullscreenModifierVKs { + if h.physical.down[i] && h.physical.asyncReliable[i] && !keymapPhysicalDown(vk) { + h.physical.down[i] = false + } + } +} + +func (h *fullscreenHotkeyHook) dispatch() { + for { + select { + case <-h.done: + return + case event := <-h.triggers: + select { + case <-h.done: + default: + settings := h.service.settings.Load() + if settings != nil && settings.hotkey == event.hotkey && + settings.targets[event.target.PID] == event.target { + settings.onTrigger(event.target, event.hwnd) + } + } + h.pending.Delete(event.target.PID) + } + } +} diff --git a/internal/host/fullscreen_hotkey_windows_test.go b/internal/host/fullscreen_hotkey_windows_test.go new file mode 100644 index 0000000..a293d06 --- /dev/null +++ b/internal/host/fullscreen_hotkey_windows_test.go @@ -0,0 +1,47 @@ +package host + +import ( + "testing" + "time" +) + +func TestFullscreenHotkeyDispatchAfterInputServiceCloses(t *testing.T) { + input := NewInputService(nil) + input.Close() + service := &FullscreenHotkeyService{} + t.Cleanup(service.Close) + target := IMETarget{VMName: "mac", PID: 1234} + hotkey, _, _ := ParseFullscreenHotkey("F8") + received := make(chan fullscreenHotkeyEvent, 1) + service.Sync(true, hotkey, []IMETarget{target}, func(target IMETarget, hwnd uintptr) { + received <- fullscreenHotkeyEvent{target: target, hwnd: hwnd} + }) + if !service.HookActive() { + t.Fatal("fullscreen hook did not start after closing the input service") + } + service.hook.triggers <- fullscreenHotkeyEvent{target: target, hotkey: hotkey, hwnd: 42} + select { + case got := <-received: + if got.target != target || got.hwnd != 42 { + t.Fatalf("dispatched event = %+v", got) + } + case <-time.After(time.Second): + t.Fatal("fullscreen event did not reach the callback") + } +} + +func TestFullscreenHotkeyResetClearsPhysicalAndSuppressedKeys(t *testing.T) { + hotkey, _, _ := ParseFullscreenHotkey("Ctrl+F8") + h := fullscreenHotkeyHook{matcher: FullscreenHotkeyMatcher{Hotkey: hotkey}} + h.physical.handle(vkLCtrl, true, false, false) + if consume, trigger := h.matcher.Handle(hotkey.VK, true, true, h.physical.mods()); !consume || !trigger { + t.Fatalf("initial chord = (%t, %t)", consume, trigger) + } + h.resetKeys() + if h.matcher.suppressedVK != 0 || h.physical.mods() != (FullscreenHotkeyMods{}) { + t.Fatal("reset left held keys behind") + } + if consume, trigger := h.matcher.Handle(hotkey.VK, false, true, h.physical.mods()); consume || trigger { + t.Fatalf("release after reset = (%t, %t)", consume, trigger) + } +} diff --git a/internal/host/fullscreen_windows.go b/internal/host/fullscreen_windows.go index a6439d0..1872ac0 100644 --- a/internal/host/fullscreen_windows.go +++ b/internal/host/fullscreen_windows.go @@ -86,6 +86,11 @@ func isProcessDisplayWindow(hwnd uintptr, pid uint32) bool { return hasDisplayClientArea(hwnd) } +func IsForegroundDisplayWindow(hwnd uintptr, pid uint32) bool { + fg, _, _ := procGetForegroundWindow.Call() + return fg == hwnd && isProcessDisplayWindow(hwnd, pid) +} + func hasDisplayClientArea(hwnd uintptr) bool { var client WindowRect if iconic, _, _ := procIsIconic.Call(hwnd); iconic == 0 { diff --git a/internal/host/input_service.go b/internal/host/input_service.go index 4d4e35b..9020033 100644 --- a/internal/host/input_service.go +++ b/internal/host/input_service.go @@ -238,6 +238,9 @@ func (s *InputService) reconcileKeymapLocked() { s.keymapHook = nil } else if len(next.targets) != 0 && s.keymapHook == nil { s.keymapHook = startKeymapHook(s) + if s.keymapHook != nil { + prioritizeFullscreenHotkeyHook() + } } } diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index edcd654..fab65c8 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -493,5 +493,16 @@ "guestTimezoneLosAngeles": "Los Angeles", "guestTimezoneNewYork": "New York", "guestTimezoneSydney": "Sydney", - "guestTimezoneUTC": "UTC" + "guestTimezoneUTC": "UTC", + "fullscreenHotkeyTitle": "Fullscreen toggle shortcut", + "fullscreenHotkeySub": "Active only while a running VM window is focused; custom shortcuts are kept when turned off", + "fullscreenHotkeyRecord": "Record shortcut", + "fullscreenHotkeyListening": "Press keys…", + "fullscreenHotkeyRecordHint": "Press a key combination to set, or Esc to cancel", + "fullscreenHotkeyReset": "Reset to default", + "fullscreenHotkeyErrNeedsModifier": "Keys other than F1–F12 require a modifier (Ctrl, Shift, Alt, or Win)", + "fullscreenHotkeyErrReserved": "{hotkey} is reserved by Windows and cannot be used", + "fullscreenHotkeyErrUnsupported": "Key not supported; use letters, numbers, F1–F12, or navigation keys", + "fullscreenHotkeySaveFailed": "Could not save fullscreen shortcut", + "fullscreenHotkeyCurrentAria": "Current fullscreen shortcut: {hotkey}" } diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index 10d29e3..fa4990c 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -493,5 +493,16 @@ "guestTimezoneLosAngeles": "洛杉矶", "guestTimezoneNewYork": "纽约", "guestTimezoneSydney": "悉尼", - "guestTimezoneUTC": "UTC(协调世界时)" + "guestTimezoneUTC": "UTC(协调世界时)", + "fullscreenHotkeyTitle": "快速切换全屏快捷键", + "fullscreenHotkeySub": "仅在聚焦运行中的虚拟机窗口时生效,关闭后保留已自定义快捷键", + "fullscreenHotkeyRecord": "录制快捷键", + "fullscreenHotkeyListening": "按下组合键…", + "fullscreenHotkeyRecordHint": "直接按下组合键完成设置,按 Esc 取消", + "fullscreenHotkeyReset": "恢复默认", + "fullscreenHotkeyErrNeedsModifier": "非 F1–F12 按键需配合修饰键(Ctrl、Shift、Alt 或 Win)", + "fullscreenHotkeyErrReserved": "{hotkey} 为 Windows 系统保留快捷键,无法使用", + "fullscreenHotkeyErrUnsupported": "不支持该按键,可用字母、数字、F1–F12 及常用功能键", + "fullscreenHotkeySaveFailed": "保存全屏快捷键失败", + "fullscreenHotkeyCurrentAria": "当前全屏快捷键:{hotkey}" } From 70e65d931be3a4da4c420c17790cbf3a04d626b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=A3=A0=E6=B8=9A=E5=90=AC=E6=BD=AE?= <108173440+reiasu2@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:50:08 +0800 Subject: [PATCH 02/28] fix(guesttools,app): fix default WebDAV share mount, fallback sync, and shared dir drift --- changes/fix-shared-folder-sync.json | 7 + frontend/src/components/VMPage.tsx | 2 +- internal/app/folder_share_flow.go | 12 +- internal/app/guesttools_flow.go | 29 ++- internal/app/guesttools_shared_dir_test.go | 166 +++++++++++++ internal/guesttools/file_sync.sh | 36 ++- internal/guesttools/file_sync_agent_test.go | 135 ++++++++++ internal/guesttools/folder_agent_test.go | 5 +- internal/guesttools/folder_share.go | 3 +- internal/guesttools/image.go | 91 +++++-- internal/guesttools/keymap_agent_test.go | 2 +- internal/guesttools/share_mount_test.go | 257 ++++++++++++++++++++ 12 files changed, 700 insertions(+), 45 deletions(-) create mode 100644 changes/fix-shared-folder-sync.json create mode 100644 internal/app/guesttools_shared_dir_test.go create mode 100644 internal/guesttools/file_sync_agent_test.go create mode 100644 internal/guesttools/share_mount_test.go diff --git a/changes/fix-shared-folder-sync.json b/changes/fix-shared-folder-sync.json new file mode 100644 index 0000000..62965ff --- /dev/null +++ b/changes/fix-shared-folder-sync.json @@ -0,0 +1,7 @@ +{ + "group": "fixes", + "order": 0, + "authors": ["reiasu2"], + "zh": "修复默认共享文件夹 WebDAV 认证挂载与失效重连、兜底同步同名覆盖和单文件异常中止,以及便携目录移动后的共享路径漂移(需在虚拟机内重新安装 Guest Tools 升级至 v11)。", + "en": "Fix default shared-folder WebDAV credential mounting and stale-mount recovery, fallback sync same-name overwrites and single-file stat aborts, and shared-folder path drift after moving a portable directory (reinstall Guest Tools in macOS to upgrade to v11)." +} diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index 148331c..d52e875 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -1062,7 +1062,7 @@ export const VMPage: React.FC = ({ const gtMountMode = stats?.guest_tools_mount_mode || detail.guest_tools_mount_mode || '' const gtSleepActive = stats?.guest_tools_sleep_guard ?? detail.guest_tools_sleep_active ?? false const gtAgentVersion = stats?.guest_tools_agent_version ?? detail.guest_tools_agent_version ?? 0 - const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < 12 + const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < 13 const gtAttachPending = running && pending.some((p) => p.field === 'guest_tools' && p.to === 'attached') // Plugin switched off: show the state and hide controls that would only fail. const gtOff = !!detail.guest_tools_disabled diff --git a/internal/app/folder_share_flow.go b/internal/app/folder_share_flow.go index 745d650..28f2f75 100644 --- a/internal/app/folder_share_flow.go +++ b/internal/app/folder_share_flow.go @@ -214,8 +214,8 @@ func (a *App) resolveSharedFolders(cfg guesttools.VMConfig, policy folderPathPol func (a *App) validatedShareConfig(cfg guesttools.VMConfig) (guesttools.VMConfig, SharedFolderSettings) { cfg = validatedDriveConfigForVolumes(cfg, shareableFixedDrives()) - if cfg.SharedDir == "" { - cfg.SharedDir = a.vmSharedDir(cfg.VMName) + if sharedDir := a.vmSharedDir(cfg.VMName); sharedDir != "" { + cfg.SharedDir = sharedDir } if len(cfg.SharedFolders) == 0 { cfg.ResolvedFolders = nil @@ -257,8 +257,8 @@ func (a *App) GetVMSharedFolderSettings(name string) (SharedFolderSettings, erro if err != nil { return SharedFolderSettings{}, fmt.Errorf("shared folder: corrupt_config") } - if cfg.SharedDir == "" { - cfg.SharedDir = a.vmSharedDir(name) + if sharedDir := a.vmSharedDir(name); sharedDir != "" { + cfg.SharedDir = sharedDir } settings, _ := a.resolveSharedFolders(cfg, a.folderPolicy()) return settings, nil @@ -315,8 +315,8 @@ func (a *App) changeVMSharedFolder(vmName, vmDir, folderID, action, hostPath str return SharedFolderSettings{}, fmt.Errorf("shared folder: corrupt_config") } cfg.VMName, cfg.Port = vmName, port - if cfg.SharedDir == "" { - cfg.SharedDir = a.vmSharedDir(vmName) + if sharedDir := a.vmSharedDir(vmName); sharedDir != "" { + cfg.SharedDir = sharedDir } id, validID := guesttools.NormalizeFolderID(folderID) diff --git a/internal/app/guesttools_flow.go b/internal/app/guesttools_flow.go index ada1fbf..974f634 100644 --- a/internal/app/guesttools_flow.go +++ b/internal/app/guesttools_flow.go @@ -68,9 +68,11 @@ func (a *App) loadAndRegisterGuestTools(srv *guesttools.Server, port int, vmDir, func (a *App) vmSharedDir(name string) string { a.mu.Lock() - dir := filepath.Join(a.cfg.SharedDir(), name) - a.mu.Unlock() - return dir + defer a.mu.Unlock() + if a.cfg == nil { + return "" + } + return filepath.Join(a.cfg.SharedDir(), name) } func (a *App) guestToolsImagePath(name string) string { @@ -232,10 +234,12 @@ func (a *App) registerSavedGuestToolsConfig(srv *guesttools.Server, port int, na return } cfg.VMName = name - if cfg.SharedDir == "" { - cfg.SharedDir = a.vmSharedDir(name) + sharedDir := a.vmSharedDir(name) + sharedDirChanged := sharedDir != "" && cfg.SharedDir != sharedDir + if sharedDirChanged { + cfg.SharedDir = sharedDir } - if cfg.Port != port { + if sharedDirChanged || cfg.Port != port { cfg.Port = port if err := guesttools.SaveVMConfig(vmDir, cfg); err != nil { a.emitLog(name, "Warning: could not save Guest Tools config: "+err.Error()) @@ -253,12 +257,16 @@ func (a *App) populateGuestToolsDetail(d *reims.VMDetail, epoch uint64) { } d.GuestToolsAttached = reims.HasGuestToolsArgs(d.ExtraArgs) d.GuestToolsDisabled = !a.guestToolsEnabled() - d.SharedDir = a.vmSharedDir(d.Name) + sharedDir := a.vmSharedDir(d.Name) + d.SharedDir = sharedDir unlock := a.lockGuestToolsVM(d.Name) defer unlock() if a.vmDeleteEpoch(d.Name) != epoch { return } + if err := requireGuestToolsVM(d.Directory); err != nil { + return + } cfg, ok, err := guesttools.ReadVMConfigStrict(d.Directory) if err != nil { a.emitLog(d.Name, "Warning: could not load Guest Tools config: "+err.Error()) @@ -268,8 +276,11 @@ func (a *App) populateGuestToolsDetail(d *reims.VMDetail, epoch uint64) { cfg.VMName = d.Name d.GuestToolsConfigured = true d.GuestToolsPreventSleep = cfg.PreventSleep - if cfg.SharedDir != "" { - d.SharedDir = cfg.SharedDir + if sharedDir != "" && cfg.SharedDir != sharedDir { + cfg.SharedDir = sharedDir + if err := guesttools.SaveVMConfig(d.Directory, cfg); err != nil { + a.emitLog(d.Name, "Warning: could not save Guest Tools config: "+err.Error()) + } } if srv, _, err := a.ensureGuestToolsBridge(); err == nil { if err := a.registerGuestToolsConfig(srv, d.Directory, cfg); err != nil { diff --git a/internal/app/guesttools_shared_dir_test.go b/internal/app/guesttools_shared_dir_test.go new file mode 100644 index 0000000..1b3ef6c --- /dev/null +++ b/internal/app/guesttools_shared_dir_test.go @@ -0,0 +1,166 @@ +package app + +import ( + "context" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/guesttools" + "github.com/Nwflower/reims-go/internal/host" +) + +func TestGuestToolsRepairsMovedSharedDir(t *testing.T) { + for _, scenario := range []struct { + name string + detail bool + changePort bool + emptyPath bool + }{ + {name: "saved_config_same_port"}, + {name: "saved_config_changed_port", changePort: true}, + {name: "saved_config_empty_path", emptyPath: true}, + {name: "detail", detail: true}, + } { + t.Run(scenario.name, func(t *testing.T) { + root := t.TempDir() + vm := folderTestVM(t, folderTestDir(t, root, "current")) + srv := guesttools.NewTransportServer(nil) + port, err := srv.Start(-1) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = srv.Close(context.Background()) }) + a := &App{cfg: &config.Config{DataRoot: filepath.Dir(vm.Directory)}, guestTools: srv} + wantDir := a.vmSharedDir(vm.Name) + folderTestDir(t, wantDir) + if err := os.WriteFile(filepath.Join(wantDir, "current.txt"), []byte("current"), 0o600); err != nil { + t.Fatal(err) + } + cfg := guesttools.VMConfig{VMName: vm.Name, Token: strings.Repeat("a", 64), Port: port} + if !scenario.emptyPath { + cfg.SharedDir = folderTestDir(t, root, "previous", "shared", vm.Name) + if err := os.WriteFile(filepath.Join(cfg.SharedDir, "previous.txt"), []byte("previous"), 0o600); err != nil { + t.Fatal(err) + } + } + if scenario.changePort { + cfg.Port++ + } + if err := guesttools.SaveVMConfig(vm.Directory, cfg); err != nil { + t.Fatal(err) + } + + epoch := a.vmDeleteEpoch(vm.Name) + if scenario.detail { + a.populateGuestToolsDetail(&vm, epoch) + if !vm.GuestToolsConfigured || vm.SharedDir != wantDir { + t.Fatalf("configured = %v, detail SharedDir = %q, want %q", vm.GuestToolsConfigured, vm.SharedDir, wantDir) + } + } else { + a.registerSavedGuestToolsConfig(srv, port, vm.Name, vm.Directory, epoch) + } + saved, ok, err := guesttools.ReadVMConfigStrict(vm.Directory) + if err != nil || !ok || saved.SharedDir != wantDir || saved.Port != port || saved.Token != cfg.Token { + t.Fatalf("saved config present = %v, SharedDir = %q, port = %d, token preserved = %v, err = %v", + ok, saved.SharedDir, saved.Port, saved.Token == cfg.Token, err) + } + req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/v1/files?sync=1", port), nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer "+cfg.Token) + client := &http.Client{Transport: &http.Transport{DisableKeepAlives: true}} + resp, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil || resp.StatusCode != http.StatusOK || !strings.HasSuffix(string(body), "\tcurrent.txt\n") || + strings.Contains(string(body), "previous.txt") { + t.Fatalf("registered share listing: %s %q (%v)", resp.Status, body, err) + } + }) + } +} + +func TestPopulateGuestToolsDetailSkipsDeletedVM(t *testing.T) { + root := t.TempDir() + vm := folderTestVM(t, folderTestDir(t, root, "current")) + a := &App{cfg: &config.Config{DataRoot: filepath.Dir(vm.Directory)}} + oldDir := folderTestDir(t, root, "previous", "shared", vm.Name) + cfg := guesttools.VMConfig{VMName: vm.Name, Token: strings.Repeat("b", 64), Port: 19847, SharedDir: oldDir} + if err := guesttools.SaveVMConfig(vm.Directory, cfg); err != nil { + t.Fatal(err) + } + if err := os.Remove(filepath.Join(vm.Directory, "vm.toml")); err != nil { + t.Fatal(err) + } + + a.populateGuestToolsDetail(&vm, a.vmDeleteEpoch(vm.Name)) + if vm.GuestToolsConfigured { + t.Fatal("deleted VM should not be marked configured") + } + saved, ok, err := guesttools.ReadVMConfigStrict(vm.Directory) + if err != nil || !ok || saved.SharedDir != oldDir { + t.Fatalf("deleted VM config was modified: ok=%v sharedDir=%q want=%q err=%v", ok, saved.SharedDir, oldDir, err) + } +} + +func TestSharedFolderFlowAlignsMovedSharedDirAndNilCfg(t *testing.T) { + t.Setenv("LOCALAPPDATA", "") + root := t.TempDir() + preserved := folderTestDir(t, root, "custom-shared") + nilCfgApp := &App{} + validated, _ := nilCfgApp.validatedShareConfig(guesttools.VMConfig{ + VMName: "mac", + Token: strings.Repeat("c", 64), + SharedDir: preserved, + }) + if validated.SharedDir != preserved { + t.Fatalf("nil cfg should preserve SharedDir: got %q want %q", validated.SharedDir, preserved) + } + + vm := folderTestVM(t, folderTestDir(t, root, "current")) + srv := guesttools.NewTransportServer(nil) + t.Cleanup(func() { _ = srv.Close(context.Background()) }) + a := &App{cfg: &config.Config{DataRoot: filepath.Dir(vm.Directory)}, guestTools: srv} + a.resolveFolderVolume = func(path string) (host.DirectoryVolume, error) { + return host.DirectoryVolume{CanonicalPath: path, VolumeGUID: "vol-1", FixedInternal: true}, nil + } + wantDir := a.vmSharedDir(vm.Name) + folderTestDir(t, wantDir) + oldDir := folderTestDir(t, root, "previous", "shared", vm.Name) + cfg := guesttools.VMConfig{ + VMName: vm.Name, + Token: strings.Repeat("d", 64), + Port: 19847, + SharedDir: oldDir, + SharedFolders: []guesttools.SharedFolderConfig{ + {ID: "current", Name: "Current", HostPath: wantDir, VolumeGUID: "vol-1", Enabled: true}, + }, + } + if err := guesttools.SaveVMConfig(vm.Directory, cfg); err != nil { + t.Fatal(err) + } + // validatedShareConfig aligns SharedDir to wantDir, so an entry pointing at wantDir cannot resolve. + aligned, settings := a.validatedShareConfig(cfg) + if aligned.SharedDir != wantDir || len(aligned.ResolvedFolders) != 0 || settings.Folders[0].Available { + t.Fatalf("validatedShareConfig did not align SharedDir: got=%q resolved=%d folder=%+v", + aligned.SharedDir, len(aligned.ResolvedFolders), settings.Folders[0]) + } + // Adding the old moved SharedDir succeeds because changeVMSharedFolder aligns SharedDir to wantDir. + if _, err := a.changeVMSharedFolder(vm.Name, vm.Directory, "", "add", oldDir, a.vmDeleteEpoch(vm.Name)); err != nil { + t.Fatalf("add previous shared dir after move: %v", err) + } + saved, ok, err := guesttools.ReadVMConfigStrict(vm.Directory) + if err != nil || !ok || saved.SharedDir != wantDir { + t.Fatalf("changeVMSharedFolder did not align SharedDir: ok=%v got=%q want=%q err=%v", ok, saved.SharedDir, wantDir, err) + } +} diff --git a/internal/guesttools/file_sync.sh b/internal/guesttools/file_sync.sh index 58397ca..f9feffb 100644 --- a/internal/guesttools/file_sync.sh +++ b/internal/guesttools/file_sync.sh @@ -31,7 +31,11 @@ sync_files() { for file do rel=${file#"$root"/./} case "$rel" in *"$tab"*|*"$newline"*|*"$cr"*) continue ;; esac - row=$(stat -f "%m${tab}%z${tab}%Fm:%Fc:%i:%z" "$file") || exit 1 + row=$(stat -f "%m${tab}%z${tab}%Fm:%Fc:%i:%z" "$file") || { + # An unreadable file cannot confirm a deletion. + printf "\t\t\t%s\n" "$rel" + continue + } printf "%s\t%s\n" "$row" "$rel" done ' sh "$SHARE_SYNC" "$TAB" {} + > "$sync_local" 2>/dev/null; then @@ -52,18 +56,36 @@ sync_files() { } } FILENAME == ARGV[3] && $4 != "" { + if ($3 == "") { unreadable[$4] = 1; next } localTime[$4] = $1; localSize[$4] = $2; local[$4] = $3; paths[$4] = 1 } END { for (p in paths) { + if (p in unreadable) continue l = p in local; r = p in remote paired = state[p] != "" && state[p] != "different" op = "" if (l && r) { - if (remoteTime[p] + 0 > localTime[p] + 2) op = "download" - else if (localTime[p] + 0 > remoteTime[p] + 2 && localSize[p] <= 268435456) op = "upload" - else if (extended != "" && localTime[p] == remoteTime[p] && localSize[p] == remoteSize[p] && - (local[p] != previousLocal[p] || remote[p] != previousRemote[p])) op = "verify" + compareByMeta = 0 + if (extended != "" && paired) { + if (remote[p] != previousRemote[p] && local[p] == previousLocal[p]) op = "download" + else if (local[p] != previousLocal[p] && remote[p] == previousRemote[p]) { + if (localSize[p] <= 268435456) op = "upload" + } else if (local[p] != previousLocal[p] && remote[p] != previousRemote[p]) { + compareByMeta = 1 + } + } else { + compareByMeta = 1 + } + if (compareByMeta) { + if (remoteTime[p] + 0 > localTime[p] + 2) op = "download" + else if (localTime[p] + 0 > remoteTime[p] + 2 && localSize[p] <= 268435456) op = "upload" + else if (localSize[p] != remoteSize[p]) { + if (remoteTime[p] + 0 >= localTime[p] + 0) op = "download" + else if (localSize[p] <= 268435456) op = "upload" + } else if (extended != "" && localTime[p] == remoteTime[p] && localSize[p] == remoteSize[p] && + (local[p] != previousLocal[p] || remote[p] != previousRemote[p])) op = "verify" + } } else if (r) { op = paired && remote[p] == previousRemote[p] ? "delete-host" : "download" } else if (l) { @@ -176,7 +198,7 @@ sync_apply_file() { case "$sync_op" in download) sync_part="$TMP_DIR/sync-download.part" - if sync_request -fsS -m 60 "$@" -D "$sync_headers" -o "$sync_part" "$sync_url" 2>/dev/null; then + if sync_request -fsS --connect-timeout 10 --speed-time 30 --speed-limit 1024 "$@" -D "$sync_headers" -o "$sync_part" "$sync_url" 2>/dev/null; then sync_download_digest="" if [ -n "$sync_scope" ]; then sync_download_digest=$(hash_file "$sync_part") @@ -195,7 +217,7 @@ sync_apply_file() { if [ -n "$sync_scope" ] && [ "$sync_host_rev" = - ]; then set -- "$@" -H 'If-None-Match: *' fi - if sync_request -fsS -m 60 "$@" -X PUT --data-binary "@$sync_target" -D "$sync_headers" -o /dev/null \ + if sync_request -fsS --connect-timeout 10 --speed-time 30 --speed-limit 1024 "$@" -X PUT --data-binary "@$sync_target" -D "$sync_headers" -o /dev/null \ "$sync_url&mtime=$sync_guest_time" 2>/dev/null && [ -n "$sync_scope" ] && [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ]; then sync_record "$sync_guest_rev" "$(sync_header ETag)" "$(sync_header X-Reims-File-SHA256)" diff --git a/internal/guesttools/file_sync_agent_test.go b/internal/guesttools/file_sync_agent_test.go new file mode 100644 index 0000000..d2d8565 --- /dev/null +++ b/internal/guesttools/file_sync_agent_test.go @@ -0,0 +1,135 @@ +package guesttools + +import "testing" + +func TestGuestAgentFallbackSync(t *testing.T) { + out := runShareShell(t, folderShellFixture+fileSyncFixture+guestFileSync+` +printf old >"$SHARE_SYNC/older" +printf old >"$SHARE_SYNC/same-second" +printf new >"$SHARE_SYNC/guest-change" +printf new >"$SHARE_SYNC/guest-older" +printf big >"$SHARE_SYNC/guest-oversize" +printf old >"$SHARE_SYNC/unchanged-drift" +printf old >"$SHARE_SYNC/unreadable" +printf old >"$SHARE_SYNC/size-download" +printf new >"$SHARE_SYNC/size-upload" +printf old >"$SHARE_SYNC/verify" +printf 'old\t"old"\tdigest\t%s\n' older same-second guest-change guest-older guest-oversize unchanged-drift unreadable >"$APP_DIR/file-sync-abcd-root.tsv" +printf '%s\n' \ + '50 3 "new" older' \ + '100 3 "new" same-second' \ + '100 3 "old" guest-change' \ + '100 3 "old" guest-older' \ + '100 3 "old" guest-oversize' \ + '50 3 "old" unchanged-drift' \ + '100 3 "old" unreadable' \ + '100 4 "new" size-download' \ + '99 4 "old" size-upload' \ + '100 3 "old" verify' \ + '100 3 "new" new-file' | tr ' ' '\t' >listing +sync_files +for path in older same-second new-file; do + expect "$(cat "$SHARE_SYNC/$path")" new +done +expect "$(cat "$SHARE_SYNC/size-download")" long +expect "$(cat "$SHARE_SYNC/guest-oversize")" big +expect "$(cat "$SHARE_SYNC/unchanged-drift")" old +expect "$(cat "$SHARE_SYNC/unreadable")" old +expect "$(cat "$SHARE_SYNC/verify")" old +expect "$(awk -F '\t' '$6 == "unreadable" { print $1 }' "$sync_plan")" "" +expect "$(awk -F '\t' '$6 == "guest-oversize" { print $1 }' "$sync_plan")" "" +expect "$(awk -F '\t' '$6 == "unchanged-drift" { print $1 }' "$sync_plan")" "" +expect "$(sort calls)" "$(printf '%s\n' \ + 'GET new-file' 'GET older' 'GET same-second' 'GET size-download' \ + 'HEAD verify' 'PUT guest-change' 'PUT guest-older' 'PUT size-upload')" +expect "$(awk -F '\t' '$4 == "unreadable" { print $1, $2, $3 }' "$APP_DIR/file-sync-abcd-root.tsv")" 'old "old" digest' +`, map[string]string{"stat": fileSyncStat}) + if out != "" { + t.Fatalf("unexpected sync output: %s", out) + } +} + +const fileSyncStat = `#!/bin/sh +set -eu +[ "$1" = -f ] +case "$2" in + '%d-%i-%B') printf 'root\n' ;; + '%Fm:%Fc:%i:%z') cat "$3"; printf '\n' ;; + *) + case "${3##*/}" in + unreadable) exit 1 ;; + guest-older) printf '50\t3\t%s\n' "$(cat "$3")" ;; + guest-oversize) printf '90\t268435457\t%s\n' "$(cat "$3")" ;; + *) printf '100\t3\t%s\n' "$(cat "$3")" ;; + esac + ;; +esac +` + +const fileSyncFixture = ` +SHARE_SYNC="$HOME/ReimsShare" +mkdir -p "$SHARE_SYNC" "$APP_DIR" +TAB=$(printf '\t') +urlencode() { printf '%s' "$1"; } +hash_file() { printf 'digest\n'; } + +curl() { + method=GET + limits= + headers= + scope= + condition= + auth= + while [ "$#" -gt 1 ]; do + case "$1" in + -X) method=$2; shift ;; + -I) method=HEAD ;; + -D) headers=$2; shift ;; + -o) output=$2; shift ;; + -m|--connect-timeout|--speed-time|--speed-limit) limits="$limits $1 $2"; shift ;; + -H) + case "$2" in + 'Authorization: Bearer '*) auth=${2#Authorization: Bearer } ;; + 'X-Reims-Sync-Scope: '*) scope=${2#X-Reims-Sync-Scope: } ;; + 'If-Match: '*) condition=${2#If-Match: } ;; + *) exit 1 ;; + esac + shift + ;; + --data-binary) data=${2#@}; shift ;; + -fsS) ;; + *) exit 1 ;; + esac + shift + done + [ "$auth" = "$REIMS_TOKEN" ] || exit 1 + if [ "$1" = "$REIMS_HOST_URL/v1/files?sync=1" ]; then + printf 'X-Reims-Sync-Scope: abcd\n' >"$headers" + cp listing "$output" + return + fi + path=${1#"$REIMS_HOST_URL/v1/file?path="} + path=${path%%&*} + [ "$scope" = abcd ] || exit 1 + case "$method" in + GET|PUT) [ "$limits" = ' --connect-timeout 10 --speed-time 30 --speed-limit 1024' ] || exit 1 ;; + HEAD) [ "$limits" = ' -m 15' ] || exit 1 ;; + *) exit 1 ;; + esac + case "$method:$path:$condition" in + GET:older:\"new\"|GET:same-second:\"new\"|GET:new-file:\"new\") + printf new >"$output" + ;; + GET:size-download:\"new\") + printf long >"$output" + ;; + PUT:guest-change:\"old\"|PUT:guest-older:\"old\"|PUT:size-upload:\"old\") + [ "$(cat "$data")" = new ] || exit 1 + ;; + HEAD:verify:\"old\") ;; + *) exit 1 ;; + esac + printf '%s %s\n' "$method" "$path" >>calls + printf 'ETag: "new"\nX-Reims-File-SHA256: digest\n' >"$headers" +} +` diff --git a/internal/guesttools/folder_agent_test.go b/internal/guesttools/folder_agent_test.go index 453fac3..a9f46b3 100644 --- a/internal/guesttools/folder_agent_test.go +++ b/internal/guesttools/folder_agent_test.go @@ -43,8 +43,9 @@ func TestGuestAgentFolderMounts(t *testing.T) { "/Volumes/REIMSTOOLS/Disable-Host-DNS.command", "$PWD/media/Disable-Host-DNS.command", ) uninstall = dnsPaths.Replace(uninstall) - if CurrentAgentVersion != HostDNSAgentVersion { - t.Fatalf("CurrentAgentVersion = %d, want Host DNS version %d", CurrentAgentVersion, HostDNSAgentVersion) + if CurrentAgentVersion != SharedFolderWebDAVAgentVersion || SharedFolderWebDAVAgentVersion <= HostDNSAgentVersion { + t.Fatalf("CurrentAgentVersion = %d, want shared-folder WebDAV version %d newer than Host DNS version %d", + CurrentAgentVersion, SharedFolderWebDAVAgentVersion, HostDNSAgentVersion) } versionMarker := `"agent_version\":` + strconv.Itoa(CurrentAgentVersion) + `,` if !strings.Contains(agent, versionMarker) || !strings.Contains(install, "Reims Guest Tools installed") { diff --git a/internal/guesttools/folder_share.go b/internal/guesttools/folder_share.go index dc2460f..f642bcc 100644 --- a/internal/guesttools/folder_share.go +++ b/internal/guesttools/folder_share.go @@ -17,7 +17,8 @@ const SharedFolderAgentVersion = 9 const KeymapAgentVersion = 10 const TimezoneAgentVersion = 11 const HostDNSAgentVersion = 12 -const CurrentAgentVersion = HostDNSAgentVersion +const SharedFolderWebDAVAgentVersion = 13 +const CurrentAgentVersion = SharedFolderWebDAVAgentVersion type SharedFolderConfig struct { ID string `json:"id"` diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index 9622677..7fb4285 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -207,29 +207,69 @@ update_desktop_link() { } mount_mode="sync" +share_mount_failed="0" +share_probe_failures=0 +share_unresponsive_logged="0" ensure_webdav_mount() { [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] && [ -n "$REIMS_VM" ] || return 0 - if is_reims_dav_mounted "$SHARE_MOUNT" "/dav/$(urlencode "$REIMS_VM")/"; then - mount_mode="webdav" - update_desktop_link "$SHARE_MOUNT" - return 0 - fi - if is_drive_mounted "$SHARE_MOUNT" || ! command -v mount_webdav >/dev/null 2>&1; then + if [ -L "$SHARE_MOUNT" ]; then + share_probe_failures=0 mount_mode="sync" update_desktop_link "$SHARE_SYNC" return 0 fi - host_addr=${REIMS_HOST_URL#http://} - host_addr=${host_addr#https://} - host_addr=${host_addr%/} - dav_url="http://reims:${REIMS_TOKEN}@${host_addr}/dav/$(urlencode "$REIMS_VM")/" - mkdir -p "$SHARE_MOUNT" - if mount_webdav -v "ReimsShare" "$dav_url" "$SHARE_MOUNT" >/dev/null 2>&1 || \ - mount_webdav "$dav_url" "$SHARE_MOUNT" >/dev/null 2>&1; then + share_route="/dav/$(urlencode "$REIMS_VM")/" + case "$(reims_dav_mount_match "$SHARE_MOUNT" "$share_route")" in + exact) + if [ -d "$SHARE_MOUNT" ] && ls "$SHARE_MOUNT" >/dev/null 2>&1; then + share_mount_failed="0" + share_probe_failures=0 + share_unresponsive_logged="0" + else + share_probe_failures=$((share_probe_failures + 1)) + fi + if [ "$share_probe_failures" -lt 3 ]; then + mount_mode="webdav" + update_desktop_link "$SHARE_MOUNT" + return 0 + fi + if [ "$share_unresponsive_logged" = "0" ]; then + printf 'ReimsShare: WebDAV mount is unresponsive\n' >&2 + share_unresponsive_logged="1" + fi + umount "$SHARE_MOUNT" >/dev/null 2>&1 || umount -f "$SHARE_MOUNT" >/dev/null 2>&1 || true + ;; + stale) + share_probe_failures=0 + unmount_shared_folder "$SHARE_MOUNT" || umount -f "$SHARE_MOUNT" >/dev/null 2>&1 || true + ;; + *) + share_probe_failures=0 + ;; + esac + + if is_drive_mounted "$SHARE_MOUNT" || ! command -v mount_webdav >/dev/null 2>&1 || + ! mkdir -p "$SHARE_MOUNT" 2>/dev/null || ! share_entries=$(ls -A "$SHARE_MOUNT" 2>/dev/null) || [ -n "$share_entries" ]; then + mount_mode="sync" + update_desktop_link "$SHARE_SYNC" + return 0 + fi + dav_url="${REIMS_HOST_URL%/}$share_route" + share_exit=0 + share_error=$(mount_authenticated_webdav -v "ReimsShare" "$dav_url" "$SHARE_MOUNT" 2>&1 >/dev/null) || share_exit=$? + if [ "$share_exit" -eq 0 ]; then + share_mount_failed="0" + share_probe_failures=0 + share_unresponsive_logged="0" mount_mode="webdav" update_desktop_link "$SHARE_MOUNT" else + if [ "$share_mount_failed" = "0" ]; then + printf 'ReimsShare: mount failed (exit %s)\n' "$share_exit" >&2 + [ -z "$share_error" ] || printf '%s\n' "$share_error" >&2 + share_mount_failed="1" + fi mount_mode="sync" update_desktop_link "$SHARE_SYNC" fi @@ -1080,11 +1120,14 @@ unmount_unused_drives() { done } -is_reims_dav_mounted() { - [ -n "${REIMS_VM:-}" ] && [ -n "${REIMS_HOST_URL:-}" ] || return 1 +reims_dav_mount_match() { + [ -n "${REIMS_VM:-}" ] && [ -n "${REIMS_HOST_URL:-}" ] || return 0 mount_host=${REIMS_HOST_URL#http://} mount_host=${mount_host#https://} - mount 2>/dev/null | awk -v target=" on $1 (" -v expected="${mount_host%/}${2%/}" ' + mount_host_clean=${mount_host%/} + mount_host_name=${mount_host%%/*} + mount_host_name=${mount_host_name%:*} + mount 2>/dev/null | awk -v target=" on $1 (" -v expected="${mount_host_clean}${2%/}" -v expected_host="$mount_host_name" -v expected_route="${2%/}" ' match($0, /^https?:\/\//) && (pos = index($0, target)) { split(substr($0, pos + length(target)), options, /[,)]/) if (options[1] != "webdav") next @@ -1095,12 +1138,24 @@ is_reims_dav_mounted() { sub(/^.*@/, "", host) route = substr(source, slash) sub(/\/$/, "", route) - if (host route == expected) found = 1 + if (host route == expected) { + matched = "exact" + exit + } + host_name = host + sub(/:[0-9]+$/, "", host_name) + if (host_name == expected_host && route == expected_route) { + matched = "stale" + } } - END { exit !found } + END { if (matched != "") print matched } ' } +is_reims_dav_mounted() { + [ "$(reims_dav_mount_match "$1" "$2")" = "exact" ] +} + owns_folder_mount_point() { if is_drive_mounted "$1"; then is_reims_dav_mounted "$1" "/dav-folders/$(urlencode "${REIMS_VM:-}")/${1##*/}/" diff --git a/internal/guesttools/keymap_agent_test.go b/internal/guesttools/keymap_agent_test.go index 6504c35..71c5d47 100644 --- a/internal/guesttools/keymap_agent_test.go +++ b/internal/guesttools/keymap_agent_test.go @@ -24,7 +24,7 @@ func TestGuestAgentKeymapScript(t *testing.T) { start := strings.Index(agent, "apply_hidutil_carrier() {") end := strings.Index(agent, "load_conf() {") if start < 0 || end <= start || !strings.Contains(agent, `"agent_version\":`+strconv.Itoa(CurrentAgentVersion)+`,\"keymap_active\":$keymap_active`) { - t.Fatal("missing guest keymap script or version 11 status") + t.Fatal("missing guest keymap script or current agent version in status") } for _, input := range []string{"(null)", "(\n)", "({ HIDKeyboardModifierMappingSrc = 30064771184; HIDKeyboardModifierMappingDst = 30064771299; })"} { t.Run(input, func(t *testing.T) { diff --git a/internal/guesttools/share_mount_test.go b/internal/guesttools/share_mount_test.go new file mode 100644 index 0000000..155c494 --- /dev/null +++ b/internal/guesttools/share_mount_test.go @@ -0,0 +1,257 @@ +package guesttools + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + "time" +) + +func runShareShell(t *testing.T, script string, helpers map[string]string) string { + t.Helper() + lockShellFixture(t) + sh, err := exec.LookPath("sh") + if runtime.GOOS == "windows" { + gitSh := filepath.Join(os.Getenv("ProgramFiles"), "Git", "bin", "sh.exe") + if _, statErr := os.Stat(gitSh); statErr == nil { + sh, err = gitSh, nil + } + } + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + for name, helper := range helpers { + if err := os.WriteFile(filepath.Join(dir, name), []byte(helper), 0o755); err != nil { + t.Fatal(err) + } + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, sh, "-s") + cmd.Dir = dir + cmd.Env = append(os.Environ(), "LC_ALL=C", "MSYS=winsymlinks:lnk") + cmd.Stdin = strings.NewReader(script) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("sh: %v\n%s", err, out) + } + return string(out) +} + +func TestGuestAgentDefaultWebDAVMount(t *testing.T) { + agent := string(GuestAgentScript()) + mounts := scriptSection(t, agent, "urlencode() {", "\nhash_file() {") + + scriptSection(t, agent, "update_desktop_link() {", "\nsleep_active=") + + scriptSection(t, agent, "\ndrive_mount_failures=", "\nmount_shared_folder() {") + for _, scenario := range []struct { + name, check, output string + }{ + {"authenticated_and_healthy", ` +fail_mount=22 +ensure_webdav_mount +check_mode sync +expect "$share_exit" 22 +fail_mount=0 +ensure_webdav_mount +check_mode webdav +expect "$share_exit" 0 +ensure_webdav_mount +check_mode webdav +expect "$share_mount_failed" 0 +expect "$(cat calls)" "$(printf 'mount\nmount')" +expect "$(ls -A "$TMP_DIR")" "" +`, "ReimsShare: mount failed (exit 22)\nAuthentication failed\n"}, + {"failed_retry_and_log_reset", ` +fail_mount=22 +ensure_webdav_mount +check_mode sync +ensure_webdav_mount +check_mode sync +fail_mount=0 +ensure_webdav_mount +check_mode webdav +umount "$SHARE_MOUNT" +fail_mount=47 +ensure_webdav_mount +check_mode sync +expect "$share_exit" 47 +expect "$(cat calls)" "$(printf 'mount\nmount\nmount\numount\nmount')" +`, "ReimsShare: mount failed (exit 22)\nAuthentication failed\nReimsShare: mount failed (exit 47)\nAuthentication failed\n"}, + {"symbolic_link", ` +ln -s "$SHARE_SYNC" "$SHARE_MOUNT" +ensure_webdav_mount +check_mode sync +test -L "$SHARE_MOUNT" +expect "$(cat calls)" "" +`, ""}, + {"nonempty_directory", ` +mkdir "$SHARE_MOUNT" +printf 'keep' >"$SHARE_MOUNT/.local" +ensure_webdav_mount +check_mode sync +expect "$(cat "$SHARE_MOUNT/.local")" keep +expect "$(cat calls)" "" +`, ""}, + {"single_failed_probe", ` +seed_mount "${REIMS_HOST_URL%/}/dav/mac%20test/" webdav +unresponsive=1 +busy=normal +ensure_webdav_mount +check_mode webdav +expect "$(cat calls)" "" +`, ""}, + {"three_failed_probes", ` +seed_mount "${REIMS_HOST_URL%/}/dav/mac%20test/" webdav +unresponsive=1 +busy=normal +ensure_webdav_mount +check_mode webdav +ensure_webdav_mount +check_mode webdav +expect "$(cat calls)" "" +ensure_webdav_mount +check_mode webdav +expect "$(cat calls)" "$(printf 'umount\numount -f\nmount')" +`, "ReimsShare: WebDAV mount is unresponsive\n"}, + {"successful_probe_resets_failures", ` +seed_mount "${REIMS_HOST_URL%/}/dav/mac%20test/" webdav +unresponsive=1 +busy=normal +ensure_webdav_mount +ensure_webdav_mount +unresponsive=0 +ensure_webdav_mount +check_mode webdav +expect "$share_probe_failures" 0 +unresponsive=1 +ensure_webdav_mount +ensure_webdav_mount +check_mode webdav +expect "$(cat calls)" "" +ensure_webdav_mount +check_mode webdav +expect "$(cat calls)" "$(printf 'umount\numount -f\nmount')" +`, "ReimsShare: WebDAV mount is unresponsive\n"}, + {"busy_zombie", ` +seed_mount "${REIMS_HOST_URL%/}/dav/mac%20test/" webdav +unresponsive=1 +busy=all +ensure_webdav_mount +ensure_webdav_mount +check_mode webdav +expect "$(cat calls)" "" +ensure_webdav_mount +check_mode sync +ensure_webdav_mount +check_mode sync +expect "$(cat calls)" "$(printf 'umount\numount -f\numount\numount -f')" +`, "ReimsShare: WebDAV mount is unresponsive\n"}, + {"old_port", ` +seed_mount "http://10.0.2.2:19846/dav/mac%20test/" webdav +ensure_webdav_mount +check_mode webdav +expect "$(cat calls)" "$(printf 'umount\nmount')" +`, ""}, + {"busy_old_port", ` +seed_mount "http://10.0.2.2:19846/dav/mac%20test/" webdav +busy=all +ensure_webdav_mount +check_mode sync +expect "$(cat calls)" "$(printf 'umount\numount -f')" +`, ""}, + {"foreign_webdav_host", ` +seed_mount "https://cloud.example.com/dav/mac%20test/" webdav +ensure_webdav_mount +check_mode sync +expect "$(cat calls)" "" +`, ""}, + {"other_vm_webdav", ` +seed_mount "http://10.0.2.2:19847/dav/other-vm/" webdav +ensure_webdav_mount +check_mode sync +expect "$(cat calls)" "" +`, ""}, + {"other_filesystem", ` +seed_mount /dev/disk2 apfs +ensure_webdav_mount +check_mode sync +expect "$(cat calls)" "" +`, ""}, + } { + t.Run(scenario.name, func(t *testing.T) { + out := runShareShell(t, folderShellFixture+defaultShareMountFixture+mounts+scenario.check, + map[string]string{"mount_webdav": defaultShareMountWebDAV}) + if out != scenario.output { + t.Fatalf("mount log = %q, want %q", out, scenario.output) + } + }) + } +} + +const defaultShareMountFixture = ` +REIMS_HOST_URL=http://10.0.2.2:19847/ +REIMS_VM="mac test" +SHARE_MOUNT="$HOME/Reims Share Mount" +SHARE_SYNC="$HOME/Reims Share" +DESKTOP_LINK="$HOME/Desktop/ReimsShare" +export SHARE_MOUNT +mkdir "$SHARE_SYNC" +unresponsive=0 +umount() { + if [ "$1" = -f ]; then + printf 'umount -f\n' >>calls + shift + [ "$busy" != all ] || return 1 + else + printf 'umount\n' >>calls + [ "$busy" = 0 ] || return 1 + fi + expect "$1" "$SHARE_MOUNT" + : >mounts + unresponsive=0 +} +ls() { + if [ "$unresponsive" = 1 ] && [ "$1" = "$SHARE_MOUNT" ]; then return 1; fi + command ls "$@" +} +seed_mount() { + mkdir "$SHARE_MOUNT" + printf '%s on %s (%s)\n' "$1" "$SHARE_MOUNT" "$2" >mounts +} +check_mode() { + expect "$mount_mode" "$1" + if [ "$1" = webdav ]; then + expect "$(readlink "$DESKTOP_LINK")" "$SHARE_MOUNT" + expect "$(cat mounts)" "${REIMS_HOST_URL%/}/dav/mac%20test/ on $SHARE_MOUNT (webdav)" + else + expect "$(readlink "$DESKTOP_LINK")" "$SHARE_SYNC" + fi +} +` + +const defaultShareMountWebDAV = `#!/usr/bin/perl +use strict; +use warnings; +my $url = "http://10.0.2.2:19847/dav/mac%20test/"; +my $target = $ENV{SHARE_MOUNT}; +die "Unexpected mount options" unless @ARGV == 7 && + "@ARGV[0..4]" eq "-a 3 -S -v ReimsShare" && $ARGV[5] eq $url && $ARGV[6] eq $target; +open(my $auth, "<&=3") or die "Missing credential descriptor: $!"; +seek($auth, 0, 0) or die "Credential descriptor is not seekable: $!"; +binmode($auth); +die "Invalid credential payload" unless do { local $/; <$auth> } eq pack("Na5Na5NNN", 5, "reims", 5, "token", 0, 0, 0); +open(my $calls, ">>", "calls") or die "Could not record mount call: $!"; +print $calls "mount\n"; +if ($ENV{fail_mount}) { + print STDERR "Authentication failed\n"; + exit $ENV{fail_mount}; +} +die "Mount point already in use" if -s "mounts"; +open(my $mounts, ">", "mounts") or die "Could not record mount: $!"; +print $mounts "$url on $target (webdav)\n"; +` From b108f58cb06ee0f0c1b140948db41c58fbe99dea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=A3=A0=E6=B8=9A=E5=90=AC=E6=BD=AE?= <108173440+reiasu2@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:28:12 +0800 Subject: [PATCH 03/28] fix(guesttools): decouple fallback file sync from control loop Run fallback sync_files in a non-overlapping background subshell with a completion marker and zombie-state fallback so large shared directories never starve apply_host_config, report_status (30s keymap freshness), or sync_clipboard. Also prioritize sync_keymap_carrier before drive/folder mounts in apply_host_config and run keymap teardown before killing/reaping the background sync worker in cleanup(). --- changes/fix-shared-folder-sync.json | 4 +- internal/guesttools/control_loop_test.go | 154 +++++++++++++++++++++++ internal/guesttools/image.go | 41 +++++- 3 files changed, 194 insertions(+), 5 deletions(-) create mode 100644 internal/guesttools/control_loop_test.go diff --git a/changes/fix-shared-folder-sync.json b/changes/fix-shared-folder-sync.json index 62965ff..33e5923 100644 --- a/changes/fix-shared-folder-sync.json +++ b/changes/fix-shared-folder-sync.json @@ -2,6 +2,6 @@ "group": "fixes", "order": 0, "authors": ["reiasu2"], - "zh": "修复默认共享文件夹 WebDAV 认证挂载与失效重连、兜底同步同名覆盖和单文件异常中止,以及便携目录移动后的共享路径漂移(需在虚拟机内重新安装 Guest Tools 升级至 v11)。", - "en": "Fix default shared-folder WebDAV credential mounting and stale-mount recovery, fallback sync same-name overwrites and single-file stat aborts, and shared-folder path drift after moving a portable directory (reinstall Guest Tools in macOS to upgrade to v11)." + "zh": "修复默认共享文件夹 WebDAV 认证挂载与失效重连、兜底同步同名覆盖与单文件异常中止、大目录兜底同步阻塞心跳与修饰键映射,以及便携目录移动后的共享路径漂移(需在虚拟机内重新安装 Guest Tools 升级至 `v13`)。", + "en": "Fix default shared-folder WebDAV credential mounting and stale-mount recovery, fallback sync same-name overwrites and single-file stat aborts, large-directory fallback sync blocking status heartbeats and modifier key remapping, and shared-folder path drift after moving a portable directory (reinstall Guest Tools in macOS to upgrade to `v13`)." } diff --git a/internal/guesttools/control_loop_test.go b/internal/guesttools/control_loop_test.go new file mode 100644 index 0000000..8946eed --- /dev/null +++ b/internal/guesttools/control_loop_test.go @@ -0,0 +1,154 @@ +package guesttools + +import "testing" + +func TestGuestAgentFileSyncControlLoop(t *testing.T) { + agent := string(GuestAgentScript()) + state := scriptSection(t, agent, "\nFILE_SYNC_PID=", "\nkeymap_active=") + cleanup := scriptSection(t, agent, "\ncleanup() {", "\n\n") + worker := scriptSection(t, agent, "\nreap_file_sync() {", "\ntext_input_loop &") + config := scriptSection(t, agent, "\napply_host_config() {", "\nreport_status() {") + loop := scriptSection(t, agent, "\nwhile :; do\n", "\ndone") + "done\n" + fixture := fileSyncControlSetup + state + cleanup + worker + fileSyncControlStubs + + t.Run("control_loop", func(t *testing.T) { + runShareShell(t, fixture+config+fileSyncControlExercise+loop, nil) + }) + t.Run("cleanup_running_worker", func(t *testing.T) { + runShareShell(t, fixture+` +report_status() { [ "$1" = 1 ]; } +sync_files() { + : > "$TMP_DIR/sync-download.part" + sleep 30 >/dev/null 2>&1 & + child=$! + printf '%s\n' "$child" > child.pid + : > ready-0 + command wait "$child" +} +run_file_sync_async +await_file ready-0 +worker_pid=$FILE_SYNC_PID +start_sec=$(date +%s) +cleanup +elapsed=$(( $(date +%s) - start_sec )) +trap - EXIT +child_pid=$(cat child.pid) +command kill "$child_pid" 2>/dev/null || true +[ "$elapsed" -lt 5 ] || fail "cleanup blocked for ${elapsed}s waiting on foreground child" +check "$(cat reaped)" "$worker_pid" "cleanup reaped the worker" +check "$(cat parent-cleanup)" disable "parent cleanup disabled the keymap once" +[ ! -f "$FILE_SYNC_DONE" ] && [ ! -f "$TMP_DIR/sync-download.part" ] || + fail "cleanup left files from the terminated worker" +[ ! -f "$INJECT_LOCK" ] || fail "cleanup left the injection lock" +if command kill -0 "$worker_pid" 2>/dev/null; then fail "worker survived cleanup"; fi +`, nil) + }) +} + +const fileSyncControlSetup = `set -eu +TMP_DIR=. +INJECT_LOCK=./injecting +CAFFEINATE_PID="" +TEXT_INPUT_PID="" +keymap_applied=true +tick=0 +: > "$INJECT_LOCK" +: > parent-cleanup +` + +const fileSyncControlStubs = ` +fail() { printf '%s\n' "$*" >&2; exit 1; } +check() { [ "$1" = "$2" ] || fail "$3: expected '$2', got '$1'"; } +await_file() { + tries=0 + until [ -f "$1" ]; do + tries=$((tries + 1)) + [ "$tries" -le 200 ] || fail "timed out waiting for $1" + sleep 0.05 + done +} +apply_hidutil_carrier() { printf '%s\n' "$1" >> parent-cleanup; } + +# Model a completed child that still answers kill -0 until wait. +kill() { + [ "$1" != -0 ] || return 0 + command kill "$@" +} +wait() { + printf '%s\n' "$1" >> reaped + command wait "$@" +} +sync_files() { + printf '%s\n' "$tick" >> started + : > "$TMP_DIR/sync-download.part" + : > "ready-$tick" + until [ -f "release-$tick" ]; do + command kill -0 "$$" 2>/dev/null || return 1 + sleep 0.05 + done +} +` + +const fileSyncControlExercise = ` +REIMS_HOST_URL=http://stub +REIMS_TOKEN=token +clip_enabled=1 +mount_mode=sync +: > "$FILE_SYNC_DONE" +load_conf() { :; } +ensure_webdav_mount() { + if [ "$tick" -eq 15 ]; then mount_mode=webdav; fi +} +curl() { printf '%s\n' '{"shared_folders_count":2}'; } +sync_keymap_carrier() { printf '%s keymap\n' "$tick" >> config; } +sync_drive_mounts() { printf '%s drives\n' "$tick" >> config; } +sync_folder_mounts() { printf '%s folders=%s\n' "$tick" "$1" >> config; } +sync_timezone() { :; } +report_status() { printf '%s\n' "$tick" >> status; } +sync_clipboard() { + printf '%s\n' "$tick" >> clipboard + case "$tick" in + 1) + first_pid=$FILE_SYNC_PID + [ -n "$first_pid" ] || fail "first fallback tick did not start a worker" + await_file ready-0 + [ ! -f "$FILE_SYNC_DONE" ] || fail "worker started with a stale completion marker" + ;; + 10) + check "$FILE_SYNC_PID" "$first_pid" "only one worker ran while the first was blocked" + check "$(cat started)" 0 "fallback runs before the gate opens" + check "$(cat status)" "$(printf '0\n5\n10')" "status ticks while the worker is blocked" + check "$(cat clipboard)" "$(printf '%s\n' 0 1 2 3 4 5 6 7 8 9 10)" "clipboard ticks while the worker is blocked" + check "$(cat config)" "$(printf '%s\n' '0 keymap' '0 drives' '0 folders=2' \ + '5 keymap' '5 drives' '5 folders=2' '10 keymap' '10 drives' '10 folders=2')" "host config order" + : > release-0 + await_file "$FILE_SYNC_DONE" + [ ! -s parent-cleanup ] && [ -f "$INJECT_LOCK" ] || fail "worker ran parent cleanup" + [ ! -f "$TMP_DIR/sync-download.part" ] || fail "worker left a partial download" + ;; + 11) + check "$FILE_SYNC_PID" "" "first worker PID after reaping" + check "$(cat reaped)" "$first_pid" "first worker was waited on" + ;; + 13) + second_pid=$FILE_SYNC_PID + [ -n "$second_pid" ] || fail "no second fallback worker started" + await_file ready-12 + check "$(cat started)" "$(printf '0\n12')" "fallback restarted after reaping" + ;; + 15) + check "$mount_mode" webdav "the mount recovered during the second sync" + check "$FILE_SYNC_PID" "$second_pid" "second worker was still running at the mode switch" + : > release-12 + await_file "$FILE_SYNC_DONE" + ;; + 17) + check "$FILE_SYNC_PID" "" "completed worker was cleared in WebDAV mode" + [ ! -f "$FILE_SYNC_DONE" ] || fail "completion marker remained after reaping in WebDAV mode" + check "$(cat reaped)" "$(printf '%s\n' "$first_pid" "$second_pid")" "both workers were waited on" + check "$(cat started)" "$(printf '0\n12')" "WebDAV did not start a fallback worker" + exit 0 + ;; + esac +} +` diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index 7fb4285..1ca1231 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -143,6 +143,8 @@ rm -f "$INJECT_LOCK" 2>/dev/null || true CAFFEINATE_PID="" TEXT_INPUT_PID="" +FILE_SYNC_PID="" +FILE_SYNC_DONE="$TMP_DIR/file-sync.done" keymap_active="false" keymap_applied="false" ` + guestKeymapCarrier + guestTimezoneAgent + guestTimezoneConfig + ` @@ -152,13 +154,20 @@ cleanup() { apply_hidutil_carrier disable report_status 1 fi + if [ -n "${FILE_SYNC_PID:-}" ]; then + if [ ! -f "$FILE_SYNC_DONE" ]; then + pkill -P "$FILE_SYNC_PID" 2>/dev/null || true + kill "$FILE_SYNC_PID" 2>/dev/null || true + fi + wait "$FILE_SYNC_PID" 2>/dev/null || true + fi if [ -n "$CAFFEINATE_PID" ]; then kill "$CAFFEINATE_PID" 2>/dev/null || true fi if [ -n "$TEXT_INPUT_PID" ]; then kill "$TEXT_INPUT_PID" 2>/dev/null || true fi - rm -f "$INJECT_LOCK" 2>/dev/null || true + rm -f "$INJECT_LOCK" ${FILE_SYNC_DONE:+"$FILE_SYNC_DONE"} ${TMP_DIR:+"$TMP_DIR/sync-download.part"} 2>/dev/null || true } trap cleanup EXIT trap 'exit 0' INT TERM @@ -482,10 +491,10 @@ apply_host_config() { [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0 cfg_json=$(curl -fsS -m 3 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/config" 2>/dev/null || true) [ -n "$cfg_json" ] || return 0 + sync_keymap_carrier "$cfg_json" sync_drive_mounts "$cfg_json" folders_count=$(printf '%s\n' "$cfg_json" | sed -n 's/.*"shared_folders_count"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p') sync_folder_mounts "${folders_count:-0}" - sync_keymap_carrier "$cfg_json" sync_timezone "$cfg_json" if printf '%s' "$cfg_json" | grep -q '"clipboard_enabled"[[:space:]]*:[[:space:]]*false'; then clip_enabled="0" @@ -748,10 +757,36 @@ text_input_loop() { done } +reap_file_sync() { + [ -n "$FILE_SYNC_PID" ] || return 0 + # A completed child can still answer kill -0 until it is reaped. + if [ ! -f "$FILE_SYNC_DONE" ] && kill -0 "$FILE_SYNC_PID" 2>/dev/null; then + case "$(ps -o stat= -p "$FILE_SYNC_PID" 2>/dev/null || true)" in + *Z*) ;; + *) return 0 ;; + esac + fi + wait "$FILE_SYNC_PID" 2>/dev/null || true + FILE_SYNC_PID="" + rm -f "$FILE_SYNC_DONE" 2>/dev/null || true +} + +run_file_sync_async() { + [ -z "$FILE_SYNC_PID" ] || return 0 + rm -f "$FILE_SYNC_DONE" || return + ( + trap 'rm -f "$TMP_DIR/sync-download.part" 2>/dev/null || true; : > "$FILE_SYNC_DONE"' EXIT + trap - INT TERM + sync_files + ) & + FILE_SYNC_PID=$! +} + text_input_loop & TEXT_INPUT_PID=$! while :; do + reap_file_sync if [ $((tick % 5)) -eq 0 ]; then load_conf ensure_webdav_mount @@ -764,7 +799,7 @@ while :; do sleep 3 fi if [ "$mount_mode" != "webdav" ] && [ $((tick % 2)) -eq 0 ]; then - sync_files + run_file_sync_async fi tick=$((tick + 1)) done From 2a153b42d75ef8a1ed88cf94ce1908707b34200c Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Thu, 3 Dec 2026 10:40:12 +0800 Subject: [PATCH 04/28] docs: require upgrade compatibility checks in PR review --- .github/PULL_REQUEST_TEMPLATE.md | 1 + docs/pr-review-guidelines.md | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 6cb6273..afa089e 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -12,5 +12,6 @@ ## 合并前核对 - [ ] 改动归属清晰,跨仓实现已按职责拆分并附上游源码或提交依据 +- [ ] 涉及默认值、配置迁移或插件行为时,已附上[已有用户升级兼容性](https://github.com/Nwflower/Reims-Go/blob/main/docs/pr-review-guidelines.md#已有用户升级兼容性)验证记录 - [ ] `node scripts/debug/check.mjs`、`node scripts/changelog.mjs check` 与 `node scripts/test.mjs ci` 通过 - [ ] 面向用户或集成方的变化已写入 `changes/.json`(纯内部重构无需添加) diff --git a/docs/pr-review-guidelines.md b/docs/pr-review-guidelines.md index b2cfe2b..3662750 100644 --- a/docs/pr-review-guidelines.md +++ b/docs/pr-review-guidelines.md @@ -49,9 +49,18 @@ - [ ] 差异中的客户端、内核、独立依赖和分发变更均已注明归属。跨仓实现已拆分并可追溯。 - [ ] 客户端能独立通过其 CI。行为变更已按影响验证 GUI、CLI 或两者的正常入口。 +- [ ] 涉及默认值、配置迁移或插件行为时,已按[已有用户升级兼容性](#已有用户升级兼容性)核对升级后的实际行为。 - [ ] 底层或打包改动有负责仓库的验证证据。涉及运行时发布时,核对 `manifest.json` 中的来源提交、补丁与能力声明,以及相应的 [`alpha` 准入与 `stable` 冒烟要求](architecture.md#便携运行时与跨仓边界)。 - [ ] 上游行为已定位到对应提交和源码行号。真机或兼容性覆盖不足的场景标明「待验证」,合并前明确其对客户端发布和能力开放的影响。 +### 已有用户升级兼容性 + +- 客户端或插件升级后,首次启动、读取旧配置及保存无关设置都必须保留已有用户设置的生效行为。按旧版实际语义处理显式配置、字段缺失或留空、继承系统设置和明确关闭。新增字段的默认值须区分全新安装和已有用户升级,迁移须保留用户原有选择及其生效范围。 +- DNS、DoH、代理等影响请求去向的变更,必须保留原有的解析和转发路径。已有自定义 DNS 或代理须继续生效,原先跟随系统或未配置专用上游的用户须继续沿用原有行为。新的第三方上游或回退路径须经用户显式选择才可生效,即使相关插件已经启用。 +- PR 须使用受支持旧版生成的配置或等效测试夹具,覆盖受影响的已配置、未配置和明确关闭状态。涉及插件时还须检查升级前已启用与未启用的状态。记录升级前后的生效行为和配置,网络变更同时核对正常路径和回退路径的实际请求目的地。全新安装的结果单独记录。 + +发现升级会静默覆盖已有配置,或因默认值、迁移或启用逻辑改变已有设置的生效行为时,须修复后才能合并。缺少受影响场景的升级验证时,须补齐验证后才能合并。 + ## 4. 自动审核 [PR Review](../.github/workflows/pr-review.yml) 在 PR 新建、重新打开、转为就绪或推送新提交时运行,覆盖来自 Fork 的 PR。草稿 PR 以及提交说明包含 `[skip ci]`、`[ci skip]`、`[no ci]`、`[skip actions]` 或 `[actions skip]` 的推送不会触发自动审核,仍可通过手动触发运行。`github-actions[bot]` 提交 `Comment` 类型的 Review,能定位到改动行或相邻上下文行的问题会随附行内评论。审核建议供维护者参考,合并仍按本仓库的人工审查流程执行。 From ff99d8d7020af191c8542f8f56b4e0d64de1a78b Mon Sep 17 00:00:00 2001 From: Dnyo666 Date: Thu, 3 Dec 2026 13:39:08 +0800 Subject: [PATCH 05/28] feat(host,ui): add opt-in Hyper-V boot switch and hypervisor launch detection (#122) - Distinguish hypervisor launch disabled (hypervisor_off) from BIOS/UEFI virtualization disabled (no_hypervisor) via unprivileged Win32 & DeviceGuard probes without spawning background PowerShell/BCD processes - Add default-off `enable_hypervisor_switch` preference in Settings -> General with confirmation modal, active VM/task guards, HVCI notice, same-boot undo, and single-UAC System32 execution without auto-restarting Windows - Update Engine page, first-run Setup, `reims-go doctor`, and VM startprep diagnostics for `hypervisor_off` and pending boot states --- changes/settings-hyperv-switch.json | 7 + docs/architecture.md | 2 +- frontend/package.json | 2 +- frontend/scripts/test-hypervisor.mjs | 131 ++++++++++ frontend/scripts/test-i18n.mjs | 2 + frontend/src/App.tsx | 2 + frontend/src/components/AppSettingsPage.tsx | 142 ++++++++++- frontend/src/components/HostView.tsx | 22 +- frontend/src/components/Setup.tsx | 25 +- frontend/src/i18n/domains/settings.gen.ts | 72 ++++++ frontend/src/i18n/keys.gen.ts | 36 +++ frontend/src/lib/hypervisor.ts | 150 +++++++++++ frontend/src/styles/app.css | 6 + frontend/src/types.ts | 3 +- frontend/wailsjs/go/app/App.d.ts | 6 + frontend/wailsjs/go/app/App.js | 12 + frontend/wailsjs/go/models.ts | 10 + internal/app/app.go | 10 +- internal/app/hypervisor_flow.go | 147 +++++++++++ internal/app/hypervisor_flow_test.go | 240 ++++++++++++++++++ internal/cli/cli.go | 2 + internal/config/config.go | 4 + internal/config/config_test.go | 40 +++ internal/host/host.go | 13 +- internal/host/host_windows.go | 47 ++-- internal/host/hypervisor.go | 267 ++++++++++++++++++++ internal/host/hypervisor_other.go | 21 ++ internal/host/hypervisor_test.go | 188 ++++++++++++++ internal/host/hypervisor_windows.go | 255 +++++++++++++++++++ internal/host/hypervisor_windows_test.go | 131 ++++++++++ internal/i18n/catalog_gen.go | 12 + internal/macos/startprep/startprep.go | 2 + internal/macos/startprep/startprep_test.go | 6 + locales/en-US/native.json | 8 +- locales/en-US/settings.json | 38 ++- locales/zh-CN/native.json | 8 +- locales/zh-CN/settings.json | 38 ++- 37 files changed, 2044 insertions(+), 63 deletions(-) create mode 100644 changes/settings-hyperv-switch.json create mode 100644 frontend/scripts/test-hypervisor.mjs create mode 100644 frontend/src/lib/hypervisor.ts create mode 100644 internal/app/hypervisor_flow.go create mode 100644 internal/app/hypervisor_flow_test.go create mode 100644 internal/host/hypervisor.go create mode 100644 internal/host/hypervisor_other.go create mode 100644 internal/host/hypervisor_test.go create mode 100644 internal/host/hypervisor_windows.go create mode 100644 internal/host/hypervisor_windows_test.go diff --git a/changes/settings-hyperv-switch.json b/changes/settings-hyperv-switch.json new file mode 100644 index 0000000..c8545d3 --- /dev/null +++ b/changes/settings-hyperv-switch.json @@ -0,0 +1,7 @@ +{ + "group": "new", + "order": 0, + "authors": ["Dnyo666"], + "zh": "「设置」页新增默认关闭的「Hyper-V 启动切换」选项,开启后可确认切换 Windows Hypervisor 下次启动状态以兼容独占模式的 VMware,并在「内核」页区分 Hypervisor 关闭与 BIOS 虚拟化未开启。 [#122](https://github.com/Nwflower/Reims-Go/issues/122)", + "en": "Add an opt-in Hyper-V boot switch in Settings to toggle Windows Hypervisor launch on next boot for exclusive-mode VMware coexistence, and distinguish hypervisor launch off from disabled BIOS virtualization on the Engine page. [#122](https://github.com/Nwflower/Reims-Go/issues/122)" +} diff --git a/docs/architecture.md b/docs/architecture.md index 48c42bc..6373a2d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -65,7 +65,7 @@ Npcap 桥接由可停用的内置扩展提供,通过逐台虚拟机的本地 U ### 宿主机体检与资源约束 -系统虚拟化状态通过免提权接口探测,仅在组件缺失且用户明确确认后才请求管理员授权开启。显卡探测扫描系统显示驱动中的 Vulkan 描述文件,自动剔除失效路径与虚拟显示适配器。处理器拓扑探测区分性能核、能效核与低功耗核,支持在虚拟机运行中实时调整进程亲和性。 +系统虚拟化状态通过免提权接口探测,区分平台组件缺失、Hypervisor 启动项关闭与固件虚拟化未开启,并只读检查内核隔离状态;启用平台组件或在「设置」开启可选的启动项切换均须经用户确认与管理员授权,且不自动重启系统。显卡探测扫描系统显示驱动中的 Vulkan 描述文件,自动剔除失效路径与虚拟显示适配器。处理器拓扑探测区分性能核、能效核与低功耗核,支持在虚拟机运行中实时调整进程亲和性。 由于 QEMU 在 Windows 上启动虚拟机时会一次性提交整块客体内存,启动前预检评估的是系统当前剩余可提交内存与页面文件可扩展空间之和(后者受所在磁盘剩余空间约束,固定大小或禁用页面文件时扩展量为零),在内存余量不足时提前拦截。 diff --git a/frontend/package.json b/frontend/package.json index 9e40275..17da4b4 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -5,7 +5,7 @@ "type": "module", "scripts": { "dev": "vite", - "test": "node --test --test-concurrency=2 scripts/test-i18n.mjs scripts/test-keymap.mjs scripts/test-plugins.mjs scripts/test-tasks.mjs scripts/test-display-presets.mjs scripts/test-guest-tools.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs", + "test": "node --test --test-concurrency=2 scripts/test-i18n.mjs scripts/test-keymap.mjs scripts/test-plugins.mjs scripts/test-tasks.mjs scripts/test-display-presets.mjs scripts/test-guest-tools.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs scripts/test-hypervisor.mjs", "typecheck": "tsc --noEmit", "bundle": "vite build && node scripts/check-ui-contract.mjs", "build": "tsc --noEmit && pnpm run bundle", diff --git a/frontend/scripts/test-hypervisor.mjs b/frontend/scripts/test-hypervisor.mjs new file mode 100644 index 0000000..b7c9d29 --- /dev/null +++ b/frontend/scripts/test-hypervisor.mjs @@ -0,0 +1,131 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { loadTestModule } from './load-test-module.mjs' + +const { + buildHypervisorSettingsView, + describeHostWHPX, + hasHypervisorBlockingWork, + t, +} = await loadTestModule(`export * from './lib/hypervisor'; export { t } from './i18n'`) + +test('hypervisor switch gate is off and collapsed by default to preserve existing UX', () => { + const view = buildHypervisorSettingsView( + 'zh-CN', + { whpx: 'ready', pending_hypervisor_boot: '', hvci_enabled: false, vbs_running: false }, + {}, + false, + ) + assert.equal(view.supported, true) + assert.equal(view.gateEnabled, false) + assert.equal(view.expanded, false) +}) + +test('unlocked hypervisor settings reflect active, off, pending, undo, and HVCI states', () => { + const active = buildHypervisorSettingsView( + 'en-US', + { whpx: 'ready', pending_hypervisor_boot: '', hvci_enabled: true, vbs_running: true }, + { enable_hypervisor_switch: true }, + false, + ) + assert.equal(active.expanded, true) + assert.equal(active.badgeClass, 'badge-ok') + assert.equal(active.targetEnable, false) + assert.equal(active.isUndo, false) + assert.equal(active.actionVariant, 'secondary') + assert.equal(active.disableBlockedByVMs, false) + assert.equal(active.showHVCINotice, true) + + const blocked = buildHypervisorSettingsView( + 'en-US', + { whpx: 'ready', pending_hypervisor_boot: '', hvci_enabled: false, vbs_running: false }, + { enable_hypervisor_switch: true }, + true, + ) + assert.equal(blocked.disableBlockedByVMs, true) + + const pendingOff = buildHypervisorSettingsView( + 'en-US', + { whpx: 'ready', pending_hypervisor_boot: 'off', hvci_enabled: false, vbs_running: false }, + { enable_hypervisor_switch: true }, + false, + ) + assert.equal(pendingOff.isUndo, true) + assert.equal(pendingOff.targetEnable, true) + assert.equal(pendingOff.badgeClass, 'badge-warn') + + const hvOff = buildHypervisorSettingsView( + 'en-US', + { whpx: 'hypervisor_off', pending_hypervisor_boot: '', hvci_enabled: false, vbs_running: false }, + { enable_hypervisor_switch: true }, + true, // running VMs check should never block enabling Hyper-V + ) + assert.equal(hvOff.targetEnable, true) + assert.equal(hvOff.actionVariant, 'primary') + assert.equal(hvOff.disableBlockedByVMs, false) + assert.equal(hvOff.showHVCINotice, false) +}) + +test('hasHypervisorBlockingWork detects running/transitioning VMs and vm-create tasks only', () => { + assert.equal(hasHypervisorBlockingWork([{ name: 'a', state: 'stopped' }], {}, []), false) + assert.equal(hasHypervisorBlockingWork([{ name: 'a', state: 'suspended' }], {}, []), false) + assert.equal(hasHypervisorBlockingWork([{ name: 'a', state: 'running' }], {}, []), true) + assert.equal(hasHypervisorBlockingWork([{ name: 'a', state: 'stopped' }], { a: 'starting' }, []), true) + assert.equal( + hasHypervisorBlockingWork( + [{ name: 'a', state: 'stopped' }], + {}, + [{ id: 't1', kind: 'installer-download', status: 'running' }], + ), + false, + ) + assert.equal( + hasHypervisorBlockingWork( + [{ name: 'a', state: 'stopped' }], + {}, + [{ id: 't2', kind: 'vm-create', status: 'running' }], + ), + true, + ) +}) + +test('describeHostWHPX distinguishes hypervisor_off from BIOS no_hypervisor and pending states', () => { + const ready = describeHostWHPX('zh-CN', { whpx: 'ready', pending_hypervisor_boot: '' }) + assert.equal(ready.tone, 'ok') + assert.equal(ready.canEnable, false) + + const hvOff = describeHostWHPX('zh-CN', { whpx: 'hypervisor_off', pending_hypervisor_boot: '' }) + assert.equal(hvOff.tone, 'warn') + assert.equal(hvOff.canEnable, true) + + const noHv = describeHostWHPX('zh-CN', { whpx: 'no_hypervisor', pending_hypervisor_boot: '' }) + assert.equal(noHv.tone, 'warn') + assert.equal(noHv.canEnable, false) + + const pendingOn = describeHostWHPX('zh-CN', { whpx: 'hypervisor_off', pending_hypervisor_boot: 'auto' }) + assert.equal(pendingOn.tone, 'warn') + assert.equal(pendingOn.canEnable, false) + + // When WHPX is currently ready and pending === 'off', the hint must clarify + // that WHPX is still active right now and will turn off after restarting Windows. + const pendingOffZh = describeHostWHPX('zh-CN', { whpx: 'ready', pending_hypervisor_boot: 'off' }) + assert.equal(pendingOffZh.tone, 'warn') + assert.equal(pendingOffZh.canEnable, false) + assert.notEqual(pendingOffZh.hint, pendingOn.hint) + assert.match(pendingOffZh.hint, /当前可用/) + + const pendingOffEn = describeHostWHPX('en-US', { whpx: 'ready', pending_hypervisor_boot: 'off' }) + assert.match(pendingOffEn.hint, /Active now/i) +}) + +test('hypervisor action buttons and short notices follow design-guidelines copy rules', () => { + for (const key of ['hypervisorActionDisable', 'hypervisorActionEnable', 'hypervisorActionUndo', 'hypervisorOpenCoreIsolation', 'hypervisorConfirmDisableBtn', 'hypervisorConfirmEnableBtn']) { + const zh = t('zh-CN', key) + const en = t('en-US', key) + assert.ok(zh.length >= 2 && zh.length <= 5, `zh-CN button ${key}="${zh}" must be 2–5 chars`) + assert.doesNotMatch(zh, /[。!!请您]|成功/, `zh-CN button ${key}="${zh}" violates copy rules`) + assert.doesNotMatch(en, /[.!]$/, `en-US button ${key}="${en}" must not end with punctuation`) + } +}) + + diff --git a/frontend/scripts/test-i18n.mjs b/frontend/scripts/test-i18n.mjs index a4f7e2d..52b22cf 100644 --- a/frontend/scripts/test-i18n.mjs +++ b/frontend/scripts/test-i18n.mjs @@ -52,6 +52,8 @@ test('lazy i18n domain keys are always backed by domain .gen imports', () => { 'PluginPanelFrame.tsx', 'SchemaForm.tsx', 'optimizations.ts', + // 仅由延迟加载的 AppSettingsPage、HostView、Setup 共用,自带 settings.gen 域注册。 + 'hypervisor.ts', ]) for (const file of walkFiles(srcDir, ['.ts', '.tsx'])) { diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 868e486..d76329c 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1280,12 +1280,14 @@ export const App: React.FC = () => { state={state} locale={locale} locales={pluginUI?.locales} + tasks={Object.values(taskMap)} themeMode={effectiveThemeMode} canLight={canLight} canDark={canDark} onThemeMode={setThemeMode} onSetLocale={setLang} onRefresh={refresh} + onToast={(title) => toasts.push({ kind: 'ok', title })} onError={fail} /> ) : selected === ABOUT_ID ? ( diff --git a/frontend/src/components/AppSettingsPage.tsx b/frontend/src/components/AppSettingsPage.tsx index 30f2954..1530e58 100644 --- a/frontend/src/components/AppSettingsPage.tsx +++ b/frontend/src/components/AppSettingsPage.tsx @@ -2,9 +2,11 @@ import React, { useEffect, useRef, useState } from 'react' import { Check, CircleAlert, PowerOff } from 'lucide-react' import '../i18n/domains/settings.gen' import { getLocaleOptions, I18nKey, parseAppError, t } from '../i18n' +import { buildHypervisorSettingsView, hasHypervisorBlockingWork } from '../lib/hypervisor' import { findOptimization, optBadgeClass, optStatusLabel } from '../lib/optimizations' -import { AppState, Locale, ResolvedLocalePack } from '../types' -import { Button } from '../ui/controls' +import { AppState, Locale, ResolvedLocalePack, Task } from '../types' +import { Button, Tip } from '../ui/controls' +import { Modal } from '../ui/dialog' import { PopupSelect, Segmented, Switch } from '../ui/settings' import { api } from '../wails' @@ -50,17 +52,19 @@ interface Props { state: AppState locale: Locale locales?: ResolvedLocalePack[] + tasks?: Task[] themeMode: ThemeMode canLight?: boolean canDark?: boolean onThemeMode: (mode: ThemeMode) => void onSetLocale: (l: Locale) => void onRefresh: () => void + onToast?: (title: string) => void onError: (title: string, e: unknown) => void } export const AppSettingsPage: React.FC = ({ - state, locale, locales, themeMode, canLight = true, canDark = true, onThemeMode, onSetLocale, onRefresh, onError, + state, locale, locales, tasks, themeMode, canLight = true, canDark = true, onThemeMode, onSetLocale, onRefresh, onToast, onError, }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const { host, config, optimizations } = state @@ -247,6 +251,40 @@ export const AppSettingsPage: React.FC = ({ } } + const [hypervisorBusy, setHypervisorBusy] = useState(false) + const [confirmHypervisor, setConfirmHypervisor] = useState<{ enable: boolean; isUndo: boolean } | null>(null) + const blockingWork = hasHypervisorBlockingWork(state.vms, state.transitions, tasks) + const hvView = buildHypervisorSettingsView(locale, host, config, blockingWork) + + const openCoreIsolation = async () => { + try { + await api.OpenWindowsCoreIsolation() + } catch (e) { + onError(tr('failGeneric'), e) + } + } + + const runSetHypervisorBoot = async (target: { enable: boolean; isUndo: boolean }) => { + setConfirmHypervisor(null) + setHypervisorBusy(true) + try { + const changed = await api.SetHypervisorBoot(target.enable) + if (!changed) return + onToast?.(tr( + target.isUndo + ? 'toastHypervisorUndone' + : target.enable + ? 'toastHypervisorPendingOn' + : 'toastHypervisorPendingOff', + )) + onRefresh() + } catch (e) { + onError(tr('failGeneric'), e) + } finally { + setHypervisorBusy(false) + } + } + return (
@@ -444,6 +482,68 @@ export const AppSettingsPage: React.FC = ({
+
+
{tr('settingsVirtualization')}
+
+
+
+
{tr('hypervisorSwitchGateTitle')}
+
+ {hvView.supported ? tr('hypervisorSwitchGateSub') : tr('whpxUnsupported')} +
+
+
+ guard(() => api.SetEnableHypervisorSwitch(checked))()} + /> +
+
+ {hvView.expanded && ( +
+
+
+
+ {tr('hypervisorBootRowTitle')} + {hvView.badgeLabel} +
+
{hvView.subLabel}
+
+
+ + + + + +
+
+ {hvView.showHVCINotice && ( +
+
+
+
+ )} +
+ )} +
+
+
{tr('settingsAppearance')}
@@ -486,6 +586,42 @@ export const AppSettingsPage: React.FC = ({
+ + {confirmHypervisor && ( + setConfirmHypervisor(null)} + > +
+ {confirmHypervisor.enable ? ( +

{tr('hypervisorConfirmOnBody')}

+ ) : ( + <> +

{tr('hypervisorConfirmOffBody')}

+ {(host.hvci_enabled || host.vbs_running) && ( +

{tr('hypervisorHVCINotice')}

+ )} +

{tr('hypervisorConfirmOffBitLocker')}

+ + )} +
+
+ + + + + +
+
+ )}
) } diff --git a/frontend/src/components/HostView.tsx b/frontend/src/components/HostView.tsx index 3436a8c..85cd338 100644 --- a/frontend/src/components/HostView.tsx +++ b/frontend/src/components/HostView.tsx @@ -4,6 +4,7 @@ import '../i18n/domains/settings.gen' import '../i18n/domains/wizard.gen' import { I18nKey, t } from '../i18n' import { formatBytes, gpuCompatHint, gpuKey, gpuMetaLine, sameGPU } from '../lib/format' +import { describeHostWHPX } from '../lib/hypervisor' import { AppState, Locale, StorageBreakdown, Task } from '../types' import { Button, IconButton } from '../ui/controls' import { api } from '../wails' @@ -37,12 +38,7 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onNewVM, o return () => { live = false } }, [state.config.data_root, state.vms?.length, state.runtimes?.length]) - const whpx = { - ready: { short: tr('whpxReady'), hint: '', tone: 'ok' }, - no_hypervisor: { short: tr('whpxNoHvShort'), hint: tr('whpxNoHv'), tone: 'warn' }, - missing: { short: tr('whpxMissingShort'), hint: tr('whpxMissing'), tone: 'warn' }, - unsupported: { short: tr('whpxUnsupportedShort'), hint: tr('whpxUnsupported'), tone: 'warn' }, - }[host.whpx] ?? { short: host.whpx, hint: '', tone: 'warn' } + const whpx = describeHostWHPX(locale, host) const guard = (fn: () => Promise) => async () => { try { @@ -55,8 +51,16 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onNewVM, o const enableWHPX = async () => { setEnabling(true) - await guard(() => api.EnableWHPX())() - setEnabling(false) + try { + const changed = await api.SetHypervisorBoot(true) + if (!changed) return + onToast?.(tr('toastHypervisorPendingOn')) + onRefresh() + } catch (e) { + onError(tr('failGeneric'), e) + } finally { + setEnabling(false) + } } const importRuntime = async () => { @@ -113,7 +117,7 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onNewVM, o {tr('whpxTitle')}
{whpx.short}
- {host.whpx === 'missing' ? ( + {whpx.canEnable ? ( ) : whpx.hint ? (
{whpx.hint}
diff --git a/frontend/src/components/Setup.tsx b/frontend/src/components/Setup.tsx index 2eaa4ff..f3bb741 100644 --- a/frontend/src/components/Setup.tsx +++ b/frontend/src/components/Setup.tsx @@ -7,6 +7,7 @@ import { AppState, DataRootCheck, DataRootChoice, Locale, MarketCatalogItem, Res import { Button } from '../ui/controls' import { PopupSelect } from '../ui/settings' import { gpuCompatHint, recommendedMemoryGB, shortGPUName } from '../lib/format' +import { describeHostWHPX } from '../lib/hypervisor' import { api } from '../wails' import { PluginAppIcon } from './PluginAppIcon' import { RuntimeOnline } from './RuntimeOnline' @@ -198,15 +199,23 @@ const FolderStep: React.FC = ({ locale, locales, state, tr, onLocale, ) } -const RuntimeStep: React.FC = ({ locale, tr, state, runtimeTask, onChannel, onInstallRuntime, onCancelTask, onImportRuntime, onFinish, onError }) => { +const RuntimeStep: React.FC = ({ locale, tr, state, runtimeTask, onChannel, onInstallRuntime, onCancelTask, onImportRuntime, onFolderDone, onFinish, onError }) => { const ready = !!state.active_runtime const { host } = state const [enabling, setEnabling] = useState(false) const enableWHPX = async () => { setEnabling(true) - try { await api.EnableWHPX() } catch (e) { onError(tr('failGeneric'), e) } finally { setEnabling(false) } + try { + const changed = await api.SetHypervisorBoot(true) + if (changed) onFolderDone() + } catch (e) { + onError(tr('failGeneric'), e) + } finally { + setEnabling(false) + } } - const whpxOK = host.whpx === 'ready' + const whpx = describeHostWHPX(locale, host) + const whpxOK = whpx.tone === 'ok' const gpu = host.recommended_gpu ?? (host.gpus ?? []).find((g) => g.kind !== 'virtual') const gpuHint = gpuCompatHint(locale, gpu) const gpuOK = !host.vulkan_probe_error && !!gpu && gpu.compat !== 'warn' && gpu.compat !== 'unsupported' @@ -223,18 +232,16 @@ const RuntimeStep: React.FC = ({ locale, tr, state, runtimeTask, onCh
{tr('hostWHPX')}
- {!whpxOK && ( -
- {tr(host.whpx === 'missing' ? 'whpxMissing' : host.whpx === 'no_hypervisor' ? 'whpxNoHv' : 'whpxUnsupported')} -
+ {whpx.hint && ( +
{whpx.hint}
)}
- {host.whpx === 'missing' ? ( + {whpx.canEnable ? ( ) : ( - {tr(whpxOK ? 'whpxReady' : host.whpx === 'no_hypervisor' ? 'whpxNoHvShort' : 'whpxUnsupportedShort')} + {whpx.short} )}
diff --git a/frontend/src/i18n/domains/settings.gen.ts b/frontend/src/i18n/domains/settings.gen.ts index 6fdc8f4..4b6777a 100644 --- a/frontend/src/i18n/domains/settings.gen.ts +++ b/frontend/src/i18n/domains/settings.gen.ts @@ -307,6 +307,32 @@ export const settingsZh: Record = { "hostRAMTotal": "共 {n} GB", "hostRuntime": "运行时", "hostWHPX": "Windows 虚拟机监控程序平台", + "hypervisorActionDisable": "切换为关闭", + "hypervisorActionEnable": "切换为开启", + "hypervisorActionUndo": "撤销更改", + "hypervisorBadgeActive": "已激活", + "hypervisorBadgeOff": "已关闭", + "hypervisorBadgePendingOff": "下次启动关闭", + "hypervisorBadgePendingOn": "下次启动开启", + "hypervisorBootRowTitle": "Windows Hypervisor", + "hypervisorConfirmDisableBtn": "确认关闭", + "hypervisorConfirmEnableBtn": "确认开启", + "hypervisorConfirmOffBitLocker": "若系统盘开启了自定义策略的 BitLocker,修改引导配置前确认已备好恢复密钥。此操作不会自动重启电脑。", + "hypervisorConfirmOffBody": "手动重启 Windows 后,独占硬件虚拟化的 VMware 可正常运行,Reims-Go、WSL2 与 Docker Desktop 将暂时无法启动虚拟机。", + "hypervisorConfirmOffTitle": "下次启动关闭 Windows Hypervisor", + "hypervisorConfirmOnBody": "配置 Windows 在下次启动时加载 Hypervisor(缺少平台组件时一并启用)。手动重启 Windows 后 Reims-Go 与 WSL2 即可正常使用,此操作不会自动重启电脑。", + "hypervisorConfirmOnTitle": "下次启动开启 Windows Hypervisor", + "hypervisorHVCINotice": "内存完整性(内核隔离)处于开启状态,重启后若仍占用虚拟化可在 Windows 安全中心调整", + "hypervisorOpenCoreIsolation": "打开设置", + "hypervisorStopVMsFirst": "先关闭所有运行中的虚拟机再关闭 Hyper-V", + "hypervisorSubActive": "当前运行中,支持 Reims-Go 与 WSL2;切换为关闭并重启后可供独占模式 VMware 使用", + "hypervisorSubMissing": "尚未启用 Windows 虚拟机监控程序平台,切换为开启并重启后可运行 Reims-Go", + "hypervisorSubNoHv": "未检测到活跃虚拟化,确认 BIOS 已开启 VT-x / AMD-V 后可设为随系统启动", + "hypervisorSubOff": "当前未随系统启动,适合独占模式 VMware;切换为开启并重启后可运行 Reims-Go", + "hypervisorSubPendingOff": "已设为下次启动关闭,手动重启 Windows 后生效", + "hypervisorSubPendingOn": "已设为随系统启动,手动重启 Windows 后生效", + "hypervisorSwitchGateSub": "与独占硬件虚拟化的 VMware 交替使用时开启,开启此项本身不修改系统配置", + "hypervisorSwitchGateTitle": "Hyper-V 启动切换", "imagesNoSourcesDesc": "请在「插件」页面启用至少一个镜像源插件(例如 macOS 镜像源)以浏览和下载系统镜像。", "imagesNoSourcesTitle": "未启用镜像源插件", "imagesOpenPlugins": "前往插件", @@ -438,6 +464,7 @@ export const settingsZh: Record = { "settingsAppearance": "外观与语言", "settingsGeneral": "常规", "settingsTitle": "{name}", + "settingsVirtualization": "虚拟化共存", "smbiosApplied": "已写入新的 OpenCore 设备码,下次启动虚拟机生效", "smbiosApply": "写入新设备码", "smbiosCheckHint": "建议将序列号复制到 checkcoverage.apple.com 确认显示「无效序列号」(未被真机占用)后再写入。", @@ -497,6 +524,9 @@ export const settingsZh: Record = { "themeLabel": "外观", "themePluginDarkDisabled": "默认主题插件已停用,深色与跟随系统外观不可用", "themePluginLightDisabled": "当前主题仅支持深色外观", + "toastHypervisorPendingOff": "已设为下次启动关闭,重启 Windows 后生效", + "toastHypervisorPendingOn": "已设为随系统启动,重启 Windows 后生效", + "toastHypervisorUndone": "已恢复当前启动设置", "updateDownloadInstall": "下载并安装", "updateDownloadingSub": "正在下载 {v}", "updateFailedSub": "下载或校验失败,可以重试", @@ -509,10 +539,16 @@ export const settingsZh: Record = { "welcomeCheckHost": "先完成内核环境配置 →", "welcomeSub": "选择系统来源、分配核数与显卡,几步完成配置", "welcomeTitle": "创建第一台 macOS 虚拟机", + "whpxHvOff": "Hypervisor 启动已关闭,启用后重启 Windows", + "whpxHvOffShort": "已关闭", "whpxMissing": "启用后需要重启 Windows", "whpxMissingShort": "未启用", "whpxNoHv": "在 BIOS 中开启 Intel VT-x / AMD-V", "whpxNoHvShort": "未激活", + "whpxPendingHint": "手动重启 Windows 后生效", + "whpxPendingOffHint": "当前可用,重启 Windows 后关闭", + "whpxPendingOffShort": "待重启关闭", + "whpxPendingOnShort": "待重启开启", "whpxReady": "就绪", "whpxTitle": "WHPX", "whpxUnsupported": "当前不是 Windows 宿主", @@ -825,6 +861,32 @@ export const settingsEn: Record = { "hostRAMTotal": "{n} GB total", "hostRuntime": "Runtime", "hostWHPX": "Windows Hypervisor Platform", + "hypervisorActionDisable": "Disable on boot", + "hypervisorActionEnable": "Enable on boot", + "hypervisorActionUndo": "Undo change", + "hypervisorBadgeActive": "Active", + "hypervisorBadgeOff": "Turned off", + "hypervisorBadgePendingOff": "Disabling on restart", + "hypervisorBadgePendingOn": "Enabling on restart", + "hypervisorBootRowTitle": "Windows Hypervisor", + "hypervisorConfirmDisableBtn": "Disable on boot", + "hypervisorConfirmEnableBtn": "Enable on boot", + "hypervisorConfirmOffBitLocker": "If your system drive uses BitLocker with custom boot validation, keep your recovery key handy before changing boot settings. Windows will not restart automatically.", + "hypervisorConfirmOffBody": "After you restart Windows, exclusive-mode VMware can use hardware virtualization directly, while Reims-Go, WSL2, and Docker Desktop will pause until re-enabled.", + "hypervisorConfirmOffTitle": "Disable Windows Hypervisor on next boot", + "hypervisorConfirmOnBody": "Configures Windows to launch the hypervisor on next boot (and enables Windows Hypervisor Platform if missing). Restart Windows manually to run Reims-Go and WSL2; Windows will not restart automatically.", + "hypervisorConfirmOnTitle": "Enable Windows Hypervisor on next boot", + "hypervisorHVCINotice": "Memory integrity (Core isolation) is on and may keep virtualization active after restart", + "hypervisorOpenCoreIsolation": "Open settings", + "hypervisorStopVMsFirst": "Stop all running VMs before disabling Hyper-V", + "hypervisorSubActive": "Running now for Reims-Go and WSL2; disable and restart Windows to use exclusive-mode VMware", + "hypervisorSubMissing": "Windows Hypervisor Platform is not enabled yet; enable and restart Windows to run Reims-Go", + "hypervisorSubNoHv": "No active hypervisor detected; ensure VT-x / AMD-V is on in BIOS, then enable on boot", + "hypervisorSubOff": "Not launched on boot for exclusive-mode VMware; enable and restart Windows to run Reims-Go", + "hypervisorSubPendingOff": "Set to stay off on next boot; restart Windows manually to apply", + "hypervisorSubPendingOn": "Set to launch on next boot; restart Windows manually to apply", + "hypervisorSwitchGateSub": "Unlock when alternating with exclusive-mode VMware; turning this on alone changes no system settings", + "hypervisorSwitchGateTitle": "Hyper-V boot switch", "imagesNoSourcesDesc": "Enable at least one image source plugin (such as macOS Images) in Plugins to browse and download system images.", "imagesNoSourcesTitle": "No image source plugins enabled", "imagesOpenPlugins": "Open Plugins", @@ -956,6 +1018,7 @@ export const settingsEn: Record = { "settingsAppearance": "Appearance \u0026 language", "settingsGeneral": "General", "settingsTitle": "{name}", + "settingsVirtualization": "Virtualization coexistence", "smbiosApplied": "Updated OpenCore SMBIOS identity. Applies on next start", "smbiosApply": "Write new codes", "smbiosCheckHint": "Tip: check the serial at checkcoverage.apple.com and verify it reports invalid (not registered to a real Mac) before writing.", @@ -1015,6 +1078,9 @@ export const settingsEn: Record = { "themeLabel": "Appearance", "themePluginDarkDisabled": "Default theme plugin is disabled; dark and system appearances are unavailable", "themePluginLightDisabled": "The active theme supports dark appearance only", + "toastHypervisorPendingOff": "Hypervisor set to off on next boot — restart Windows to apply", + "toastHypervisorPendingOn": "Hypervisor set to launch on boot — restart Windows to apply", + "toastHypervisorUndone": "Restored current hypervisor boot setting", "updateDownloadInstall": "Download and install", "updateDownloadingSub": "Downloading {v}", "updateFailedSub": "Download or verification failed; try again", @@ -1027,10 +1093,16 @@ export const settingsEn: Record = { "welcomeCheckHost": "Set up Engine first →", "welcomeSub": "Pick an installer, assign cores and GPU, and launch in minutes", "welcomeTitle": "Create your first macOS VM", + "whpxHvOff": "Hypervisor launch is off — enable and restart Windows", + "whpxHvOffShort": "Turned off", "whpxMissing": "Windows restarts after enabling", "whpxMissingShort": "Off", "whpxNoHv": "Turn on Intel VT-x / AMD-V in BIOS", "whpxNoHvShort": "Inactive", + "whpxPendingHint": "Takes effect after restarting Windows", + "whpxPendingOffHint": "Active now · turns off after restart", + "whpxPendingOffShort": "Disable on restart", + "whpxPendingOnShort": "Enable on restart", "whpxReady": "Ready", "whpxTitle": "WHPX", "whpxUnsupported": "This host isn’t Windows", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 4558da5..d25122b 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -501,6 +501,32 @@ export type I18nKey = | "hostReady" | "hostRuntime" | "hostWHPX" + | "hypervisorActionDisable" + | "hypervisorActionEnable" + | "hypervisorActionUndo" + | "hypervisorBadgeActive" + | "hypervisorBadgeOff" + | "hypervisorBadgePendingOff" + | "hypervisorBadgePendingOn" + | "hypervisorBootRowTitle" + | "hypervisorConfirmDisableBtn" + | "hypervisorConfirmEnableBtn" + | "hypervisorConfirmOffBitLocker" + | "hypervisorConfirmOffBody" + | "hypervisorConfirmOffTitle" + | "hypervisorConfirmOnBody" + | "hypervisorConfirmOnTitle" + | "hypervisorHVCINotice" + | "hypervisorOpenCoreIsolation" + | "hypervisorStopVMsFirst" + | "hypervisorSubActive" + | "hypervisorSubMissing" + | "hypervisorSubNoHv" + | "hypervisorSubOff" + | "hypervisorSubPendingOff" + | "hypervisorSubPendingOn" + | "hypervisorSwitchGateSub" + | "hypervisorSwitchGateTitle" | "imagesNoSourcesDesc" | "imagesNoSourcesTitle" | "imagesOpenPlugins" @@ -854,6 +880,7 @@ export type I18nKey = | "settingsEllipsis" | "settingsGeneral" | "settingsTitle" + | "settingsVirtualization" | "setupCheck" | "setupContinue" | "setupDesc" @@ -1065,6 +1092,9 @@ export type I18nKey = | "toastGuestToolsDetachedNextStart" | "toastHostDNSOff" | "toastHostDNSOn" + | "toastHypervisorPendingOff" + | "toastHypervisorPendingOn" + | "toastHypervisorUndone" | "toastInstallFinished" | "toastInstallerAttached" | "toastInstallerAttachedNextStart" @@ -1129,10 +1159,16 @@ export type I18nKey = | "welcomeCheckHost" | "welcomeSub" | "welcomeTitle" + | "whpxHvOff" + | "whpxHvOffShort" | "whpxMissing" | "whpxMissingShort" | "whpxNoHv" | "whpxNoHvShort" + | "whpxPendingHint" + | "whpxPendingOffHint" + | "whpxPendingOffShort" + | "whpxPendingOnShort" | "whpxReady" | "whpxTitle" | "whpxUnsupported" diff --git a/frontend/src/lib/hypervisor.ts b/frontend/src/lib/hypervisor.ts new file mode 100644 index 0000000..dc5613b --- /dev/null +++ b/frontend/src/lib/hypervisor.ts @@ -0,0 +1,150 @@ +import '../i18n/domains/settings.gen' +import { I18nKey, t } from '../i18n' +import { vmRefKey } from './vmRef' +import type { Config, HostReport, Locale, Task, VMListItem } from '../types' + +export interface HypervisorSettingsView { + supported: boolean + gateEnabled: boolean + expanded: boolean + badgeClass: 'badge-ok' | 'badge-warn' | 'badge-accent' + badgeLabel: string + subLabel: string + actionLabel: string + actionVariant: 'primary' | 'secondary' + targetEnable: boolean + isUndo: boolean + disableBlockedByVMs: boolean + showHVCINotice: boolean +} + +export interface HostWHPXSummary { + short: string + hint: string + tone: 'ok' | 'warn' + canEnable: boolean +} + +const BLOCKING_VM_STATES = new Set(['running', 'starting', 'stopping', 'suspending', 'resuming']) + +export function hasHypervisorBlockingWork( + vms: VMListItem[] | null | undefined, + transitions: Record | undefined, + tasks?: Task[], +): boolean { + for (const vm of vms ?? []) { + const st = transitions?.[vmRefKey(vm)] ?? transitions?.[vm.name] ?? vm.state + if (BLOCKING_VM_STATES.has(st)) return true + } + if (transitions) { + for (const tr of Object.values(transitions)) { + if (tr && BLOCKING_VM_STATES.has(tr)) return true + } + } + for (const task of tasks ?? []) { + if (task.status === 'running' && task.kind === 'vm-create') return true + } + return false +} + +export function buildHypervisorSettingsView( + locale: Locale, + host: Pick, + config: Pick, + hasBlockingWork: boolean, +): HypervisorSettingsView { + const tr = (k: I18nKey) => t(locale, k) + const supported = host.whpx !== 'unsupported' + const gateEnabled = supported && Boolean(config.enable_hypervisor_switch) + const pending = host.pending_hypervisor_boot === 'auto' || host.pending_hypervisor_boot === 'off' + ? host.pending_hypervisor_boot + : '' + const isUndo = pending !== '' + const effectiveOn = pending === 'auto' ? true : pending === 'off' ? false : host.whpx === 'ready' + const targetEnable = !effectiveOn + + let badgeClass: HypervisorSettingsView['badgeClass'] = 'badge-warn' + let badgeKey: I18nKey = 'whpxNoHvShort' + let subKey: I18nKey = 'hypervisorSubNoHv' + + if (pending === 'off') { + badgeClass = 'badge-warn' + badgeKey = 'hypervisorBadgePendingOff' + subKey = 'hypervisorSubPendingOff' + } else if (pending === 'auto') { + badgeClass = 'badge-accent' + badgeKey = 'hypervisorBadgePendingOn' + subKey = 'hypervisorSubPendingOn' + } else if (host.whpx === 'ready') { + badgeClass = 'badge-ok' + badgeKey = 'hypervisorBadgeActive' + subKey = 'hypervisorSubActive' + } else if (host.whpx === 'hypervisor_off') { + badgeClass = 'badge-warn' + badgeKey = 'hypervisorBadgeOff' + subKey = 'hypervisorSubOff' + } else if (host.whpx === 'missing') { + badgeClass = 'badge-warn' + badgeKey = 'whpxMissingShort' + subKey = 'hypervisorSubMissing' + } + + const actionKey: I18nKey = isUndo + ? 'hypervisorActionUndo' + : effectiveOn + ? 'hypervisorActionDisable' + : 'hypervisorActionEnable' + const actionVariant: 'primary' | 'secondary' = !isUndo && !effectiveOn ? 'primary' : 'secondary' + const disableBlockedByVMs = !targetEnable && hasBlockingWork + const showHVCINotice = Boolean(host.hvci_enabled || host.vbs_running) && (pending === 'off' || host.whpx === 'ready') + + return { + supported, + gateEnabled, + expanded: gateEnabled, + badgeClass, + badgeLabel: tr(badgeKey), + subLabel: tr(subKey), + actionLabel: tr(actionKey), + actionVariant, + targetEnable, + isUndo, + disableBlockedByVMs, + showHVCINotice, + } +} + +export function describeHostWHPX( + locale: Locale, + host: Pick, +): HostWHPXSummary { + const tr = (k: I18nKey) => t(locale, k) + if (host.pending_hypervisor_boot === 'auto') { + return { + short: tr('whpxPendingOnShort'), + hint: tr('whpxPendingHint'), + tone: 'warn', + canEnable: false, + } + } + if (host.pending_hypervisor_boot === 'off') { + return { + short: tr('whpxPendingOffShort'), + hint: tr(host.whpx === 'ready' ? 'whpxPendingOffHint' : 'whpxPendingHint'), + tone: 'warn', + canEnable: false, + } + } + switch (host.whpx) { + case 'ready': + return { short: tr('whpxReady'), hint: '', tone: 'ok', canEnable: false } + case 'hypervisor_off': + return { short: tr('whpxHvOffShort'), hint: tr('whpxHvOff'), tone: 'warn', canEnable: true } + case 'missing': + return { short: tr('whpxMissingShort'), hint: tr('whpxMissing'), tone: 'warn', canEnable: true } + case 'no_hypervisor': + return { short: tr('whpxNoHvShort'), hint: tr('whpxNoHv'), tone: 'warn', canEnable: false } + default: + return { short: tr('whpxUnsupportedShort'), hint: tr('whpxUnsupported'), tone: 'warn', canEnable: false } + } +} diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 6b280b3..0265f6d 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -652,6 +652,10 @@ h1, h2, h3, p { margin: 0; } .host-dns-custom > .input { flex: 1; min-width: 0; } .host-dns-feedback { display: inline-flex; align-items: center; gap: 6px; font-size: var(--fs-12); line-height: 1.45; overflow-wrap: anywhere; font-variant-numeric: tabular-nums; } .host-dns-feedback > svg { flex-shrink: 0; } +.tip-anchor { display: inline-flex; border-radius: var(--r-md); } +.hypervisor-hvci-notice { display: flex; align-items: flex-start; gap: 6px; font-size: var(--fs-12); line-height: 1.48; overflow-wrap: anywhere; } +.hypervisor-hvci-notice > svg { flex-shrink: 0; margin-top: 2px; } +.hypervisor-hvci-notice .link-btn { white-space: nowrap; margin-inline-start: 4px; font-weight: var(--fw-medium); } .badge { display: inline-flex; align-items: center; height: 20px; padding: 0 8px; border-radius: 999px; font-size: 11.5px; font-weight: var(--fw-medium); white-space: nowrap; flex-shrink: 0; background: var(--surface-active); color: var(--text-2); } .badge-accent { background: var(--accent-soft); color: var(--accent-soft-text); } @@ -937,6 +941,8 @@ button.status-issue + .status-metric { margin-left: 6px; } box-shadow: var(--shadow-overlay), var(--highlight-top); } .dialog.sm { width: 420px; } +.dialog.md { width: 480px; } +.dialog-prose { font-size: var(--fs-13); color: var(--text-2); line-height: 1.55; gap: var(--sp-3); } .dialog-head { flex-shrink: 0; display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); padding-block: 14px; padding-inline: 22px 14px; border-bottom: 1px solid var(--border); } .dialog-title { font-size: var(--fs-16); font-weight: var(--fw-strong); letter-spacing: -0.01em; text-wrap: balance; } .dialog-desc { font-size: var(--fs-13); color: var(--text-2); margin-top: 2px; overflow-wrap: anywhere; } diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 6a11833..6005a68 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -35,7 +35,8 @@ export type Optimization = Model & { } export type HostReport = Omit, 'gpus' | 'recommended_gpu'> & { - whpx: 'ready' | 'no_hypervisor' | 'missing' | 'unsupported' + whpx: 'ready' | 'hypervisor_off' | 'no_hypervisor' | 'missing' | 'unsupported' + pending_hypervisor_boot?: 'auto' | 'off' | '' gpus: GPUInfo[] recommended_gpu?: GPUInfo } diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index f09bcf4..8910edf 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -232,6 +232,8 @@ export function OpenVSCodeSSH(arg1:string,arg2:string):Promise; export function OpenVSCodeSSHWithDriver(arg1:string,arg2:string,arg3:string):Promise; +export function OpenWindowsCoreIsolation():Promise; + export function OpenWindowsSecurityExclusions():Promise; export function OptimizeVMDisk(arg1:string):Promise; @@ -296,12 +298,16 @@ export function SetAutoPinPCores(arg1:boolean):Promise; export function SetDataRoot(arg1:string):Promise; +export function SetEnableHypervisorSwitch(arg1:boolean):Promise; + export function SetGuestPreventSleep(arg1:string,arg2:boolean):Promise; export function SetGuestToolsHostDNS(arg1:string,arg2:boolean):Promise; export function SetHostDNSConfig(arg1:guesttools.HostDNSConfig):Promise; +export function SetHypervisorBoot(arg1:boolean):Promise; + export function SetLocale(arg1:string):Promise; export function SetMinimizeToTray(arg1:boolean):Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index 660c568..2ad352b 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -442,6 +442,10 @@ export function OpenVSCodeSSHWithDriver(arg1, arg2, arg3) { return window['go']['app']['App']['OpenVSCodeSSHWithDriver'](arg1, arg2, arg3); } +export function OpenWindowsCoreIsolation() { + return window['go']['app']['App']['OpenWindowsCoreIsolation'](); +} + export function OpenWindowsSecurityExclusions() { return window['go']['app']['App']['OpenWindowsSecurityExclusions'](); } @@ -570,6 +574,10 @@ export function SetDataRoot(arg1) { return window['go']['app']['App']['SetDataRoot'](arg1); } +export function SetEnableHypervisorSwitch(arg1) { + return window['go']['app']['App']['SetEnableHypervisorSwitch'](arg1); +} + export function SetGuestPreventSleep(arg1, arg2) { return window['go']['app']['App']['SetGuestPreventSleep'](arg1, arg2); } @@ -582,6 +590,10 @@ export function SetHostDNSConfig(arg1) { return window['go']['app']['App']['SetHostDNSConfig'](arg1); } +export function SetHypervisorBoot(arg1) { + return window['go']['app']['App']['SetHypervisorBoot'](arg1); +} + export function SetLocale(arg1) { return window['go']['app']['App']['SetLocale'](arg1); } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 256eb10..de22a69 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -778,6 +778,7 @@ export namespace config { sync_host_memory_smbios?: boolean; host_dns_mode?: string; host_dns_doh_url?: string; + enable_hypervisor_switch?: boolean; static createFrom(source: any = {}) { return new Config(source); @@ -796,6 +797,7 @@ export namespace config { this.sync_host_memory_smbios = source["sync_host_memory_smbios"]; this.host_dns_mode = source["host_dns_mode"]; this.host_dns_doh_url = source["host_dns_doh_url"]; + this.enable_hypervisor_switch = source["enable_hypervisor_switch"]; } } @@ -1272,6 +1274,10 @@ export namespace host { free_disk_gb: number; whpx: string; whpx_caps: WHPXCapabilities; + firmware_virt_enabled?: boolean; + hvci_enabled?: boolean; + vbs_running?: boolean; + pending_hypervisor_boot?: string; needs_cold_reboot_workaround: boolean; gpus: GPUInfo[]; vulkan_probe_error?: string; @@ -1322,6 +1328,10 @@ export namespace host { this.free_disk_gb = source["free_disk_gb"]; this.whpx = source["whpx"]; this.whpx_caps = this.convertValues(source["whpx_caps"], WHPXCapabilities); + this.firmware_virt_enabled = source["firmware_virt_enabled"]; + this.hvci_enabled = source["hvci_enabled"]; + this.vbs_running = source["vbs_running"]; + this.pending_hypervisor_boot = source["pending_hypervisor_boot"]; this.needs_cold_reboot_workaround = source["needs_cold_reboot_workaround"]; this.gpus = this.convertValues(source["gpus"], GPUInfo); this.vulkan_probe_error = source["vulkan_probe_error"]; diff --git a/internal/app/app.go b/internal/app/app.go index f545fb3..e54a045 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -760,6 +760,9 @@ func (a *App) GetState() AppState { a.mu.Unlock() rep := host.Inspect(cfgCopy.DataRoot) + if needsSetup || rootStatus.ReadOnly { + rep.PendingHypervisorBoot = host.ReadPendingHypervisorBoot("", rep.WHPX) + } runtimes, _ := rt.List(&cfgCopy) active, _ := rt.ResolveActive(&cfgCopy) // The poller's list (≤ polledMaxAge old, and invalidated by wakePoll after @@ -1023,6 +1026,7 @@ func (a *App) SetDataRoot(dir string) error { curAppUpdateChannel := a.cfg.AppUpdateChannel curMinToTray := a.cfg.MinimizeToTray curSyncHostMemSMBIOS := a.cfg.SyncHostMemorySMBIOS + curEnableHvSwitch := a.cfg.EnableHypervisorSwitch curHostDNS := a.hostDNSConfigLocked() for _, v := range a.lastVMs { if v.State == "running" || v.State == "starting" || v.State == "stopping" || v.State == "suspending" || v.State == "resuming" { @@ -1069,6 +1073,7 @@ func (a *App) SetDataRoot(dir string) error { nextCfg.AppUpdateChannel = curAppUpdateChannel nextCfg.MinimizeToTray = curMinToTray nextCfg.SyncHostMemorySMBIOS = curSyncHostMemSMBIOS + nextCfg.EnableHypervisorSwitch = curEnableHvSwitch nextCfg.HostDNSMode, nextCfg.HostDNSDoHURL = curHostDNS.Mode, curHostDNS.DoHURL } if err := nextCfg.EnsureDirs(); err != nil { @@ -1124,11 +1129,6 @@ func (a *App) PickFile(title, pattern string) (string, error) { return wailsRuntime.OpenFileDialog(a.ctx, opts) } -func (a *App) EnableWHPX() error { - a.emitLog("host", "Requesting Windows UAC to enable HypervisorPlatform...") - return host.EnableWHPXElevated() -} - // OpenProcessorScheduling opens Windows' Performance Options as administrator // (one UAC prompt) for the processor scheduling choice. Declining the prompt // is not an error. diff --git a/internal/app/hypervisor_flow.go b/internal/app/hypervisor_flow.go new file mode 100644 index 0000000..b4681df --- /dev/null +++ b/internal/app/hypervisor_flow.go @@ -0,0 +1,147 @@ +package app + +import ( + "context" + "errors" + + "github.com/Nwflower/reims-go/internal/dataroot" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" + wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" +) + +var ( + inspectHostForHypervisor = host.Inspect + setHypervisorBootElevatedFn = host.SetHypervisorBootElevated + recordPendingHypervisorBootFn = host.RecordPendingHypervisorBoot + openWindowsCoreIsolationHostFn = host.OpenWindowsCoreIsolation +) + +// SetEnableHypervisorSwitch persists the user's opt-in preference to unlock the +// Hyper-V / WHPX boot switch in Settings. Toggling this flag alone never runs +// any system virtualization or boot configuration command. +func (a *App) SetEnableHypervisorSwitch(enabled bool) error { + a.mu.Lock() + prev := a.cfg.EnableHypervisorSwitch + a.cfg.EnableHypervisorSwitch = enabled + err := a.saveConfigLocked() + if err != nil { + a.cfg.EnableHypervisorSwitch = prev + } + ctx := a.ctx + a.mu.Unlock() + if err == nil && ctx != nil { + wailsRuntime.EventsEmit(ctx, "reims:state-changed", true) + } + return err +} + +// EnableWHPX enables Windows Hypervisor Platform (if missing) and sets Windows +// hypervisor boot launch to auto via UAC. Declining UAC is a no-op. +func (a *App) EnableWHPX() error { + _, err := a.setHypervisorBootInternal(true) + return err +} + +// SetHypervisorBoot prompts for UAC and updates Windows hypervisor boot launch +// (`auto` when enable is true, `off` when false). It returns changed=false with +// err=nil when the person declines the UAC prompt, and never restarts Windows. +func (a *App) SetHypervisorBoot(enable bool) (bool, error) { + return a.setHypervisorBootInternal(enable) +} + +func (a *App) setHypervisorBootInternal(enable bool) (bool, error) { + a.mu.Lock() + loc := i18n.EffectiveLocale(a.cfg.Locale) + dataRoot := a.cfg.DataRoot + needsSetup := a.needsSetup + rootStatus := a.root + ctx := a.ctx + if rootStatus.ReadOnly { + a.mu.Unlock() + return false, dataroot.Error(loc, rootStatus) + } + if !enable { + for _, v := range a.lastVMs { + if isHypervisorBlockingVMState(v.State) { + a.mu.Unlock() + return false, i18n.NewCodedError(loc, "E_HOST_HYPERVISOR_BUSY_VMS", "err.hypervisor.busy_vms", nil, nil) + } + } + for _, tr := range a.transitions { + if tr != "" { + a.mu.Unlock() + return false, i18n.NewCodedError(loc, "E_HOST_HYPERVISOR_BUSY_VMS", "err.hypervisor.busy_vms", nil, nil) + } + } + } + a.mu.Unlock() + + if !enable { + if a.dataRootUsable() { + if vms, err := a.polledVMs(context.Background()); err == nil { + for _, v := range vms { + if isHypervisorBlockingVMState(v.State) { + return false, i18n.NewCodedError(loc, "E_HOST_HYPERVISOR_BUSY_VMS", "err.hypervisor.busy_vms", nil, nil) + } + } + } + } + for _, t := range tasks.list() { + if t.Status == TaskRunning && t.Kind == "vm-create" { + return false, i18n.NewCodedError(loc, "E_HOST_HYPERVISOR_BUSY_TASKS", "err.hypervisor.busy_tasks", nil, nil) + } + } + } + + persistRoot := dataRoot + if needsSetup || rootStatus.ReadOnly { + persistRoot = "" + } + rep := inspectHostForHypervisor(persistRoot) + if rep.WHPX == host.WHPXUnsupported { + return false, i18n.NewCodedError(loc, "E_HOST_HYPERVISOR_UNSUPPORTED", "err.hypervisor.unsupported", nil, nil) + } + + if enable { + a.emitLog("host", "Requesting Windows UAC to enable hypervisor launch on next boot...") + } else { + a.emitLog("host", "Requesting Windows UAC to disable hypervisor launch on next boot...") + } + + if err := setHypervisorBootElevatedFn(a.baseCtx(), enable); err != nil { + if errors.Is(err, host.ErrElevationDeclined) { + a.emitLog("host", "UAC prompt declined; hypervisor boot configuration unchanged") + return false, nil + } + a.emitLog("host", "Hypervisor boot configuration failed: "+err.Error()) + return false, i18n.NewCodedError(loc, "E_HOST_HYPERVISOR_SET_FAILED", "err.hypervisor.set_failed", nil, err) + } + + pending := recordPendingHypervisorBootFn(persistRoot, rep.WHPX, enable) + if pending == "" { + a.emitLog("host", "Restored Windows hypervisor boot configuration to match current session") + } else { + a.emitLog("host", "Updated Windows hypervisor boot configuration (next boot: "+pending+"); restart Windows manually to apply") + } + if ctx != nil { + wailsRuntime.EventsEmit(ctx, "reims:state-changed", true) + } + return true, nil +} + +func isHypervisorBlockingVMState(state string) bool { + switch state { + case "running", "starting", "stopping", "suspending", "resuming": + return true + default: + return false + } +} + +// OpenWindowsCoreIsolation opens Windows Security's Core Isolation page so the +// user can inspect or adjust Memory Integrity (HVCI) themselves. +func (a *App) OpenWindowsCoreIsolation() error { + a.emitLog("host", "Opening Windows Security Core Isolation settings...") + return openWindowsCoreIsolationHostFn() +} diff --git a/internal/app/hypervisor_flow_test.go b/internal/app/hypervisor_flow_test.go new file mode 100644 index 0000000..86abeab --- /dev/null +++ b/internal/app/hypervisor_flow_test.go @@ -0,0 +1,240 @@ +package app + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/dataroot" + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" +) + +func osMkdirAllForTest(p string) error { return os.MkdirAll(p, 0o755) } + +func fileExistsForTest(p string) bool { + _, err := os.Stat(p) + return err == nil +} + +func datarootStatusBusyForTest(dir string) dataroot.Status { + return dataroot.Status{Dir: dir, ReadOnly: true, Reason: dataroot.ReasonBusy} +} + +func TestHypervisorSwitchGateAndBootGuards(t *testing.T) { + origInspect := inspectHostForHypervisor + origSet := setHypervisorBootElevatedFn + origRecord := recordPendingHypervisorBootFn + t.Cleanup(func() { + inspectHostForHypervisor = origInspect + setHypervisorBootElevatedFn = origSet + recordPendingHypervisorBootFn = origRecord + }) + + dir := t.TempDir() + cfg := config.Default() + cfg.DataRoot = dir + cfg.Locale = i18n.ZhCN + a := &App{ + cfg: cfg, + transitions: make(map[string]string), + pendingChanges: make(map[string][]PendingChange), + } + + var elevatedCalls int + var lastEnable bool + var mockSetErr error + liveWHPX := host.WHPXReady + var recordedPending string + + inspectHostForHypervisor = func(dataRoot string) host.Report { + return host.Report{DataRoot: dataRoot, WHPX: liveWHPX} + } + setHypervisorBootElevatedFn = func(_ context.Context, enable bool) error { + elevatedCalls++ + lastEnable = enable + return mockSetErr + } + recordPendingHypervisorBootFn = func(_ string, st host.WHPXState, enable bool) string { + recordedPending = host.ResolvePendingHypervisorTarget(st, enable) + return recordedPending + } + + // 1. Default off; toggling the UI gate persists locally without invoking UAC. + if a.cfg.EnableHypervisorSwitch { + t.Fatal("EnableHypervisorSwitch must default to false") + } + if err := a.SetEnableHypervisorSwitch(true); err != nil { + t.Fatalf("SetEnableHypervisorSwitch(true): %v", err) + } + if elevatedCalls != 0 { + t.Fatalf("SetEnableHypervisorSwitch must never run elevated commands, got %d calls", elevatedCalls) + } + saved, err := config.Load(filepath.Join(dir, "reims-go.json")) + if err != nil || !saved.EnableHypervisorSwitch { + t.Fatalf("persisted config EnableHypervisorSwitch=%v err=%v", saved != nil && saved.EnableHypervisorSwitch, err) + } + + // 2. Running VM blocks disabling Hyper-V before UAC is even requested. + a.lastVMs = []driver.VMListItem{{Name: "mac", State: "running"}} + a.lastVMsAt = time.Now() + if changed, err := a.SetHypervisorBoot(false); err == nil || changed { + t.Fatalf("expected busy VM error, got changed=%v err=%v", changed, err) + } else { + var coded *i18n.CodedError + if !errors.As(err, &coded) || coded.Code != "E_HOST_HYPERVISOR_BUSY_VMS" { + t.Fatalf("unexpected coded error: %#v (%v)", coded, err) + } + } + if elevatedCalls != 0 { + t.Fatalf("busy VM must block before UAC, got %d calls", elevatedCalls) + } + + // 3. Stopped VM + active vm-create task also blocks disabling Hyper-V. + a.lastVMs = []driver.VMListItem{{Name: "mac", State: "stopped"}} + taskID := tasks.start("vm-create", "new-mac", "new-mac", func() {}) + if changed, err := a.SetHypervisorBoot(false); err == nil || changed { + tasks.finish(taskID, "", context.Canceled) + t.Fatalf("expected busy task error, got changed=%v err=%v", changed, err) + } else { + var coded *i18n.CodedError + if !errors.As(err, &coded) || coded.Code != "E_HOST_HYPERVISOR_BUSY_TASKS" { + tasks.finish(taskID, "", context.Canceled) + t.Fatalf("unexpected task coded error: %#v (%v)", coded, err) + } + } + tasks.finish(taskID, "", context.Canceled) + tasks.dismiss(taskID) + + // 4. Declining UAC returns (false, nil) and leaves pending state untouched. + mockSetErr = host.ErrElevationDeclined + if changed, err := a.SetHypervisorBoot(false); err != nil || changed { + t.Fatalf("UAC decline should return (false, nil), got (%v, %v)", changed, err) + } + if err := a.EnableWHPX(); err != nil { + t.Fatalf("EnableWHPX on UAC decline should return nil, got %v", err) + } + if recordedPending != "" { + t.Fatalf("UAC decline must not record pending boot, got %q", recordedPending) + } + + // 5. Command failure returns structured E_HOST_HYPERVISOR_SET_FAILED. + mockSetErr = &host.HypervisorExecError{Command: "bcdedit", ExitCode: 1} + if changed, err := a.SetHypervisorBoot(false); err == nil || changed { + t.Fatalf("expected exec failure error, got (%v, %v)", changed, err) + } else { + var coded *i18n.CodedError + if !errors.As(err, &coded) || coded.Code != "E_HOST_HYPERVISOR_SET_FAILED" { + t.Fatalf("unexpected exec coded error: %#v (%v)", coded, err) + } + } + + // 6. Successful disable while WHPXReady sets pending="off", and undo clears it. + mockSetErr = nil + if changed, err := a.SetHypervisorBoot(false); err != nil || !changed { + t.Fatalf("SetHypervisorBoot(false) = (%v, %v), want (true, nil)", changed, err) + } + if lastEnable != false || recordedPending != host.HypervisorBootOff { + t.Fatalf("after disable: lastEnable=%v pending=%q", lastEnable, recordedPending) + } + if changed, err := a.SetHypervisorBoot(true); err != nil || !changed { + t.Fatalf("undo SetHypervisorBoot(true) = (%v, %v), want (true, nil)", changed, err) + } + if lastEnable != true || recordedPending != "" { + t.Fatalf("after undo: lastEnable=%v pending=%q", lastEnable, recordedPending) + } + + // 7. EnableWHPX when hypervisor_off sets pending="auto". + liveWHPX = host.WHPXHypervisorOff + if err := a.EnableWHPX(); err != nil { + t.Fatalf("EnableWHPX from hypervisor_off: %v", err) + } + if lastEnable != true || recordedPending != host.HypervisorBootAuto { + t.Fatalf("after EnableWHPX: lastEnable=%v pending=%q", lastEnable, recordedPending) + } +} + +func TestHypervisorReadOnlyAndFirstRunIsolation(t *testing.T) { + origInspect := inspectHostForHypervisor + origSet := setHypervisorBootElevatedFn + t.Cleanup(func() { + inspectHostForHypervisor = origInspect + setHypervisorBootElevatedFn = origSet + }) + + dir := t.TempDir() + // Pre-create /tmp to prove neither read-only mode nor unconfirmed first-run + // writes hypervisor-boot-pending.json into it. + if err := config.Default().EnsureDirs(); false { + t.Fatal(err) + } + tmpSub := filepath.Join(dir, "tmp") + if err := osMkdirAllForTest(tmpSub); err != nil { + t.Fatal(err) + } + + var elevatedCalls int + inspectHostForHypervisor = func(dataRoot string) host.Report { + return host.Report{DataRoot: dataRoot, WHPX: host.WHPXMissing} + } + setHypervisorBootElevatedFn = func(_ context.Context, _ bool) error { + elevatedCalls++ + return nil + } + + // Case A: Read-only data root must roll back in-memory EnableHypervisorSwitch + // on save failure and block SetHypervisorBoot before UAC or disk writes. + roCfg := config.Default() + roCfg.DataRoot = dir + roCfg.Locale = i18n.EnUS + roApp := &App{ + cfg: roCfg, + transitions: make(map[string]string), + pendingChanges: make(map[string][]PendingChange), + root: datarootStatusBusyForTest(dir), + } + if err := roApp.SetEnableHypervisorSwitch(true); err == nil { + t.Fatal("expected SetEnableHypervisorSwitch to fail in read-only mode") + } + if roApp.cfg.EnableHypervisorSwitch { + t.Fatal("in-memory EnableHypervisorSwitch leaked to true after failed read-only save") + } + if changed, err := roApp.SetHypervisorBoot(false); err == nil || changed { + t.Fatalf("expected SetHypervisorBoot(false) to fail in read-only mode, got (%v, %v)", changed, err) + } + if elevatedCalls != 0 { + t.Fatalf("read-only mode must block before UAC, got %d elevated calls", elevatedCalls) + } + if fileExistsForTest(filepath.Join(tmpSub, "hypervisor-boot-pending.json")) { + t.Fatal("read-only mode must never write hypervisor-boot-pending.json") + } + + // Case B: First-run setup (needsSetup=true) allows EnableWHPX in memory, + // but must never write to the unconfirmed default candidate folder on disk. + firstCfg := config.Default() + firstCfg.DataRoot = dir + firstCfg.Locale = i18n.ZhCN + firstApp := &App{ + cfg: firstCfg, + needsSetup: true, + transitions: make(map[string]string), + pendingChanges: make(map[string][]PendingChange), + } + if err := firstApp.EnableWHPX(); err != nil { + t.Fatalf("EnableWHPX during first-run setup: %v", err) + } + if elevatedCalls != 1 { + t.Fatalf("expected 1 elevated call during first-run EnableWHPX, got %d", elevatedCalls) + } + if fileExistsForTest(filepath.Join(tmpSub, "hypervisor-boot-pending.json")) { + t.Fatal("first-run EnableWHPX must not write to unconfirmed candidate dataRoot/tmp") + } + // Clean up in-memory pending state. + _ = host.RecordPendingHypervisorBoot("", host.WHPXReady, true) +} + diff --git a/internal/cli/cli.go b/internal/cli/cli.go index cbcef61..265b4f4 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -186,6 +186,8 @@ func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error { switch rep.WHPX { case host.WHPXReady: whpxKey = "doctor.whpx.ok" + case host.WHPXHypervisorOff: + whpxKey = "doctor.whpx.hypervisor_off" case host.WHPXNoHypervisor: whpxKey = "doctor.whpx.no_hv" case host.WHPXMissing: diff --git a/internal/config/config.go b/internal/config/config.go index 3e5063d..90e2b75 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -32,6 +32,10 @@ type Config struct { SyncHostMemorySMBIOS bool `json:"sync_host_memory_smbios,omitempty"` HostDNSMode string `json:"host_dns_mode,omitempty"` HostDNSDoHURL string `json:"host_dns_doh_url,omitempty"` + // EnableHypervisorSwitch unlocks the Hyper-V / WHPX boot launch switch in + // Settings for users who alternate with exclusive-mode VMware. Off by + // default; toggling this preference alone never alters Windows boot config. + EnableHypervisorSwitch bool `json:"enable_hypervisor_switch,omitempty"` } // ShouldMinimizeToTray returns true when closing the main window should hide to tray. diff --git a/internal/config/config_test.go b/internal/config/config_test.go index d95dc1f..a031860 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -113,3 +113,43 @@ func TestFirstRunNeedsItsOwnLocationFile(t *testing.T) { t.Fatalf("normal launch: %v", err) } } + +func TestHypervisorSwitchDefaultsOffAndRoundTrips(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "reims-go.json") + + def := Default() + def.DataRoot = dir + if def.EnableHypervisorSwitch { + t.Fatalf("Default().EnableHypervisorSwitch must be false by default") + } + if err := Save(path, def); err != nil { + t.Fatal(err) + } + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if string(raw) == "" || filepath.Base(path) != "reims-go.json" { + t.Fatalf("unexpected saved config: %q", string(raw)) + } + loaded, err := Load(path) + if err != nil { + t.Fatal(err) + } + if loaded.EnableHypervisorSwitch { + t.Fatalf("loaded default config must keep EnableHypervisorSwitch=false") + } + + loaded.EnableHypervisorSwitch = true + if err := Save(path, loaded); err != nil { + t.Fatal(err) + } + reloaded, err := Load(path) + if err != nil { + t.Fatal(err) + } + if !reloaded.EnableHypervisorSwitch { + t.Fatalf("expected EnableHypervisorSwitch=true after opting in") + } +} diff --git a/internal/host/host.go b/internal/host/host.go index ba09151..4cf511e 100644 --- a/internal/host/host.go +++ b/internal/host/host.go @@ -38,10 +38,11 @@ type GPUInfo struct { type WHPXState string const ( - WHPXReady WHPXState = "ready" - WHPXNoHypervisor WHPXState = "no_hypervisor" - WHPXMissing WHPXState = "missing" - WHPXUnsupported WHPXState = "unsupported" + WHPXReady WHPXState = "ready" + WHPXHypervisorOff WHPXState = "hypervisor_off" + WHPXNoHypervisor WHPXState = "no_hypervisor" + WHPXMissing WHPXState = "missing" + WHPXUnsupported WHPXState = "unsupported" ) type WHPXCapabilities struct { @@ -95,6 +96,10 @@ type Report struct { FreeDiskGB float64 `json:"free_disk_gb"` WHPX WHPXState `json:"whpx"` WHPXCaps WHPXCapabilities `json:"whpx_caps"` + FirmwareVirtEnabled bool `json:"firmware_virt_enabled,omitempty"` + HVCIEnabled bool `json:"hvci_enabled,omitempty"` + VBSRunning bool `json:"vbs_running,omitempty"` + PendingHypervisorBoot string `json:"pending_hypervisor_boot,omitempty"` NeedsColdRebootWorkaround bool `json:"needs_cold_reboot_workaround"` GPUs []GPUInfo `json:"gpus"` VulkanProbeError string `json:"vulkan_probe_error,omitempty"` diff --git a/internal/host/host_windows.go b/internal/host/host_windows.go index 1c749b2..6c42092 100644 --- a/internal/host/host_windows.go +++ b/internal/host/host_windows.go @@ -3,6 +3,7 @@ package host import ( + "context" "encoding/binary" "fmt" "math/bits" @@ -124,6 +125,8 @@ func Inspect(dataRoot string) Report { cp := *st.memSpec memSpecCopy = &cp } + whpx, firmwareVirt := probeWHPXAndFirmware() + hvciEnabled, vbsRunning := probeDeviceGuard() rep := Report{ DefenderRealtimeActive: probeDefenderRealtime(), OS: "windows", @@ -131,7 +134,11 @@ func Inspect(dataRoot string) Report { LogicalCPUs: runtime.NumCPU(), DataRoot: dataRoot, Timezone: DetectHostTimezone(), - WHPX: probeWHPX(), + WHPX: whpx, + FirmwareVirtEnabled: firmwareVirt, + HVCIEnabled: hvciEnabled, + VBSRunning: vbsRunning, + PendingHypervisorBoot: ReadPendingHypervisorBoot(dataRoot, whpx), NeedsColdRebootWorkaround: st.needsColdReboot, GPUs: gpusCopy, VulkanProbeError: st.vulkanProbeError, @@ -266,33 +273,26 @@ func DisableProcessPowerThrottling(pid uint32) error { return nil } -// EnableWHPXElevated invokes a standard Windows UAC prompt to enable Windows Hypervisor Platform. +// EnableWHPXElevated invokes a standard Windows UAC prompt to enable Windows +// Hypervisor Platform (if missing) and set hypervisorlaunchtype to auto. func EnableWHPXElevated() error { - verb, _ := syscall.UTF16PtrFromString("runas") - file, _ := syscall.UTF16PtrFromString("powershell.exe") - params, _ := syscall.UTF16PtrFromString(`-NoProfile -Command "Enable-WindowsOptionalFeature -Online -FeatureName HypervisorPlatform -All -NoRestart; Write-Host 'Done. Please restart Windows.'; Start-Sleep -Seconds 3"`) - r, _, err := procShellExecuteW.Call( - 0, - uintptr(unsafe.Pointer(verb)), - uintptr(unsafe.Pointer(file)), - uintptr(unsafe.Pointer(params)), - 0, - 1, // SW_SHOWNORMAL - ) - if r <= 32 { - return fmt.Errorf("ShellExecuteW runas failed (code %d): %w", r, err) - } - return nil + return SetHypervisorBootElevated(context.Background(), true) } func probeWHPX() WHPXState { + st, _ := probeWHPXAndFirmware() + return st +} + +func probeWHPXAndFirmware() (WHPXState, bool) { + firmwareVirt := probeFirmwareVirtEnabled() mod := syscall.NewLazyDLL("WinHvPlatform.dll") if err := mod.Load(); err != nil { - return WHPXMissing + return ClassifyWHPXState(false, false, firmwareVirt), firmwareVirt } proc := mod.NewProc("WHvGetCapability") if err := proc.Find(); err != nil { - return WHPXMissing + return ClassifyWHPXState(false, false, firmwareVirt), firmwareVirt } var capVal uint64 var written uint32 @@ -302,13 +302,8 @@ func probeWHPX() WHPXState { uintptr(unsafe.Sizeof(capVal)), uintptr(unsafe.Pointer(&written)), ) - if int32(hr) < 0 { - return WHPXNoHypervisor - } - if capVal&1 != 0 { - return WHPXReady - } - return WHPXNoHypervisor + hvPresent := int32(hr) >= 0 && (capVal&1) != 0 + return ClassifyWHPXState(true, hvPresent, firmwareVirt), hvPresent || firmwareVirt } // probeNeedsColdRebootWorkaround reports true on Windows hosts whose WinHvPlatform.dll diff --git a/internal/host/hypervisor.go b/internal/host/hypervisor.go new file mode 100644 index 0000000..b074105 --- /dev/null +++ b/internal/host/hypervisor.go @@ -0,0 +1,267 @@ +package host + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "sync" +) + +const ( + HypervisorBootAuto = "auto" + HypervisorBootOff = "off" + + // bootEpochToleranceSec absorbs small wall-clock NTP adjustments when the + // fallback wall-clock boot epoch is used without a kernel volatile boot marker. + bootEpochToleranceSec = 120 + pendingBootFileName = "hypervisor-boot-pending.json" +) + +// HypervisorExecError reports a non-zero exit code from an elevated Windows +// virtualization configuration command (bcdedit / dism). +type HypervisorExecError struct { + Command string + ExitCode uint32 +} + +func (e *HypervisorExecError) Error() string { + return fmt.Sprintf("%s exited with code %d (0x%X)", e.Command, e.ExitCode, e.ExitCode) +} + +// ClassifyWHPXState maps unprivileged Windows capability probes into a concrete +// WHPX readiness state, distinguishing "hypervisor launch turned off in BCD" +// (where firmware virtualization is still available) from BIOS VT-x/AMD-V off. +func ClassifyWHPXState(dllPresent, hypervisorPresent, firmwareVirtEnabled bool) WHPXState { + if !dllPresent { + return WHPXMissing + } + if hypervisorPresent { + return WHPXReady + } + if firmwareVirtEnabled { + return WHPXHypervisorOff + } + return WHPXNoHypervisor +} + +// EvaluateDeviceGuard interprets unprivileged DeviceGuard registry values into +// HVCI (Memory Integrity) and VBS running flags. +func EvaluateDeviceGuard(vbsEnable, hvciEnabled, secureKernelRunning uint32) (hvci, vbs bool) { + hvci = hvciEnabled == 1 + vbs = secureKernelRunning == 1 || vbsEnable == 1 + return hvci, vbs +} + +type bootSession struct { + Marker string + EpochSec int64 + TickMs uint64 +} + +func (s bootSession) valid() bool { + return s.Marker != "" || s.EpochSec > 0 +} + +type pendingHypervisorRecord struct { + BootMarker string `json:"boot_marker,omitempty"` + BootEpoch int64 `json:"boot_epoch"` + TickMs uint64 `json:"tick_ms,omitempty"` + Target string `json:"target"` // "auto" | "off" +} + +var ( + pendingBootMu sync.Mutex + pendingBootMem *pendingHypervisorRecord + pendingBootPath string +) + +func absInt64(v int64) int64 { + if v < 0 { + return -v + } + return v +} + +func sameBootSession(saved pendingHypervisorRecord, cur bootSession) bool { + if !cur.valid() { + return false + } + // Monotonic uptime guard: within a single OS boot session (including across + // S3 sleep or S4 hibernate), GetTickCount64 never goes backwards, whereas a + // fast reboot resets uptime back near zero. + if saved.TickMs > 0 && cur.TickMs > 0 && cur.TickMs < saved.TickMs { + return false + } + if saved.BootMarker != "" && cur.Marker != "" { + return saved.BootMarker == cur.Marker + } + if saved.BootEpoch <= 0 || cur.EpochSec <= 0 { + return false + } + return absInt64(saved.BootEpoch-cur.EpochSec) <= bootEpochToleranceSec +} + +// ResolvePendingHypervisorTarget computes the new pending boot target after a +// successful SetHypervisorBootElevated(enable) call against liveState. +// Returning "" means the requested boot state matches the currently running +// state (for example, undoing a pending change before restarting Windows). +func ResolvePendingHypervisorTarget(liveState WHPXState, enable bool) string { + if enable { + if liveState == WHPXReady { + return "" + } + return HypervisorBootAuto + } + if liveState != WHPXReady { + return "" + } + return HypervisorBootOff +} + +func pendingBootFilePath(dataRoot string) string { + if dataRoot == "" { + return "" + } + return filepath.Join(dataRoot, "tmp", pendingBootFileName) +} + +func writePendingFileAtomic(path string, data []byte) error { + dir := filepath.Dir(path) + f, err := os.CreateTemp(dir, ".hypervisor-pending-*") + if err != nil { + return err + } + tmpName := f.Name() + if _, err := f.Write(data); err != nil { + _ = f.Close() + _ = os.Remove(tmpName) + return err + } + if err := f.Close(); err != nil { + _ = os.Remove(tmpName) + return err + } + if err := os.Rename(tmpName, path); err != nil { + _ = os.Remove(tmpName) + return err + } + return nil +} + +// RecordPendingHypervisorBoot records (or clears) the pending hypervisor boot +// mode for the current OS boot session. If /tmp already exists, it is +// also persisted atomically there so reopening Reims-Go before restarting +// Windows retains the indicator without writing to uninitialized paths. +func RecordPendingHypervisorBoot(dataRoot string, liveState WHPXState, enable bool) string { + return recordPendingHypervisorBootSession(dataRoot, liveState, enable, currentBootSession()) +} + +func recordPendingHypervisorBootAt(dataRoot string, liveState WHPXState, enable bool, bootEpoch int64) string { + return recordPendingHypervisorBootSession(dataRoot, liveState, enable, bootSession{EpochSec: bootEpoch}) +} + +func recordPendingHypervisorBootSession(dataRoot string, liveState WHPXState, enable bool, sess bootSession) string { + target := ResolvePendingHypervisorTarget(liveState, enable) + pendingBootMu.Lock() + defer pendingBootMu.Unlock() + + p := pendingBootFilePath(dataRoot) + if target == "" || !sess.valid() { + pendingBootMem = nil + if p != "" { + _ = os.Remove(p) + } + if pendingBootPath != "" && pendingBootPath != p { + _ = os.Remove(pendingBootPath) + } + pendingBootPath = "" + return "" + } + + rec := pendingHypervisorRecord{ + BootMarker: sess.Marker, + BootEpoch: sess.EpochSec, + TickMs: sess.TickMs, + Target: target, + } + pendingBootMem = &rec + if p != "" { + tmpDir := filepath.Dir(p) + if st, err := os.Stat(tmpDir); err == nil && st.IsDir() { + if raw, merr := json.Marshal(rec); merr == nil { + if writePendingFileAtomic(p, append(raw, '\n')) == nil { + if pendingBootPath != "" && pendingBootPath != p { + _ = os.Remove(pendingBootPath) + } + pendingBootPath = p + } + } + } + } + return target +} + +// ReadPendingHypervisorBoot returns "auto", "off", or "" for the current Windows +// boot session. Read-only: never creates directories or writes files during Inspect. +func ReadPendingHypervisorBoot(dataRoot string, liveState WHPXState) string { + return readPendingHypervisorBootSession(dataRoot, liveState, currentBootSession()) +} + +func readPendingHypervisorBootAt(dataRoot string, liveState WHPXState, bootEpoch int64) string { + return readPendingHypervisorBootSession(dataRoot, liveState, bootSession{EpochSec: bootEpoch}) +} + +func readPendingHypervisorBootSession(dataRoot string, liveState WHPXState, sess bootSession) string { + if !sess.valid() { + return "" + } + validTarget := func(rec pendingHypervisorRecord) string { + if !sameBootSession(rec, sess) { + return "" + } + switch rec.Target { + case HypervisorBootAuto: + if liveState == WHPXReady { + return "" + } + return HypervisorBootAuto + case HypervisorBootOff: + if liveState != WHPXReady { + return "" + } + return HypervisorBootOff + default: + return "" + } + } + + pendingBootMu.Lock() + if pendingBootMem != nil { + t := validTarget(*pendingBootMem) + if t == "" { + pendingBootMem = nil + pendingBootPath = "" + } + pendingBootMu.Unlock() + if t != "" { + return t + } + } else { + pendingBootMu.Unlock() + } + + p := pendingBootFilePath(dataRoot) + if p == "" { + return "" + } + raw, err := os.ReadFile(p) + if err != nil { + return "" + } + var rec pendingHypervisorRecord + if json.Unmarshal(raw, &rec) != nil { + return "" + } + return validTarget(rec) +} diff --git a/internal/host/hypervisor_other.go b/internal/host/hypervisor_other.go new file mode 100644 index 0000000..26dae2f --- /dev/null +++ b/internal/host/hypervisor_other.go @@ -0,0 +1,21 @@ +//go:build !windows + +package host + +import ( + "context" + "fmt" + "runtime" +) + +func currentBootSession() bootSession { + return bootSession{} +} + +func SetHypervisorBootElevated(_ context.Context, _ bool) error { + return fmt.Errorf("hypervisor boot configuration is only supported on Windows (current OS: %s)", runtime.GOOS) +} + +func OpenWindowsCoreIsolation() error { + return fmt.Errorf("Windows Security Core Isolation is only available on Windows (current OS: %s)", runtime.GOOS) +} diff --git a/internal/host/hypervisor_test.go b/internal/host/hypervisor_test.go new file mode 100644 index 0000000..5d53262 --- /dev/null +++ b/internal/host/hypervisor_test.go @@ -0,0 +1,188 @@ +package host + +import ( + "os" + "path/filepath" + "testing" +) + +func TestClassifyWHPXState(t *testing.T) { + cases := []struct { + name string + dll bool + hvPresent bool + firmVirt bool + want WHPXState + }{ + {"missing dll without firmware virt", false, false, false, WHPXMissing}, + {"missing dll with firmware virt", false, false, true, WHPXMissing}, + {"hypervisor running (firmware virt reported false under root partition)", true, true, false, WHPXReady}, + {"hypervisor running (firmware virt true)", true, true, true, WHPXReady}, + {"hypervisor launch off with BIOS virtualization enabled", true, false, true, WHPXHypervisorOff}, + {"BIOS virtualization off or nested guest without VMX", true, false, false, WHPXNoHypervisor}, + } + for _, tc := range cases { + if got := ClassifyWHPXState(tc.dll, tc.hvPresent, tc.firmVirt); got != tc.want { + t.Errorf("%s: ClassifyWHPXState(%v, %v, %v) = %q, want %q", tc.name, tc.dll, tc.hvPresent, tc.firmVirt, got, tc.want) + } + } +} + +func TestEvaluateDeviceGuard(t *testing.T) { + cases := []struct { + name string + vbs, hvci, secureKernel uint32 + wantHVCI, wantVBSRunning bool + }{ + {"all off", 0, 0, 0, false, false}, + {"hvci scenario enabled with secure kernel running and top-level vbs 0", 0, 1, 1, true, true}, + {"hvci scenario enabled pending reboot", 0, 1, 0, true, false}, + {"top-level vbs enabled without hvci", 1, 0, 0, false, true}, + {"secure kernel running without hvci", 0, 0, 1, false, true}, + } + for _, tc := range cases { + hvci, vbs := EvaluateDeviceGuard(tc.vbs, tc.hvci, tc.secureKernel) + if hvci != tc.wantHVCI || vbs != tc.wantVBSRunning { + t.Errorf("%s: EvaluateDeviceGuard(%d, %d, %d) = (%v, %v), want (%v, %v)", + tc.name, tc.vbs, tc.hvci, tc.secureKernel, hvci, vbs, tc.wantHVCI, tc.wantVBSRunning) + } + } +} + +func TestPendingHypervisorBootLifecycle(t *testing.T) { + defer func() { + pendingBootMu.Lock() + pendingBootMem = nil + pendingBootMu.Unlock() + }() + + root := t.TempDir() + // Before /tmp exists, ReadPendingHypervisorBoot must not create files, + // while in-memory state still tracks the current session. + const boot1 = int64(1_700_000_000) + if got := recordPendingHypervisorBootAt(root, WHPXReady, false, boot1); got != HypervisorBootOff { + t.Fatalf("record disable while ready = %q, want %q", got, HypervisorBootOff) + } + if _, err := os.Stat(filepath.Join(root, "tmp")); !os.IsNotExist(err) { + t.Fatalf("must not create /tmp before setup; stat err=%v", err) + } + if got := readPendingHypervisorBootAt(root, WHPXReady, boot1+30); got != HypervisorBootOff { + t.Fatalf("read within NTP tolerance = %q, want %q", got, HypervisorBootOff) + } + + // Undoing (setting enable=true while WHPX is still live Ready) clears pending state. + if got := recordPendingHypervisorBootAt(root, WHPXReady, true, boot1+35); got != "" { + t.Fatalf("undo back to live state = %q, want empty", got) + } + if got := readPendingHypervisorBootAt(root, WHPXReady, boot1+35); got != "" { + t.Fatalf("read after undo = %q, want empty", got) + } + + // With /tmp present, record persists across process restarts (simulated by clearing memory) + // within the same Windows boot session, and expires once Windows reboots (boot2). + if err := os.MkdirAll(filepath.Join(root, "tmp"), 0o755); err != nil { + t.Fatal(err) + } + if got := recordPendingHypervisorBootAt(root, WHPXHypervisorOff, true, boot1); got != HypervisorBootAuto { + t.Fatalf("record enable while hypervisor_off = %q, want %q", got, HypervisorBootAuto) + } + pendingBootMu.Lock() + pendingBootMem = nil + pendingBootMu.Unlock() + + if got := readPendingHypervisorBootAt(root, WHPXHypervisorOff, boot1+10); got != HypervisorBootAuto { + t.Fatalf("read from disk in same boot = %q, want %q", got, HypervisorBootAuto) + } + // Simulated OS reboot (boot epoch jumps by 600s): stale record is ignored. + const boot2 = boot1 + 600 + if got := readPendingHypervisorBootAt(root, WHPXHypervisorOff, boot2); got != "" { + t.Fatalf("read after simulated reboot = %q, want empty", got) + } + // Also ignored if live state already converged to target in same boot. + if got := readPendingHypervisorBootAt(root, WHPXReady, boot1+10); got != "" { + t.Fatalf("read once live state is WHPXReady = %q, want empty", got) + } +} + +func TestPendingHypervisorBootUndoAcrossDataRoots(t *testing.T) { + defer func() { + pendingBootMu.Lock() + pendingBootMem = nil + pendingBootPath = "" + pendingBootMu.Unlock() + }() + + rootA := t.TempDir() + rootB := t.TempDir() + if err := os.MkdirAll(filepath.Join(rootA, "tmp"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(rootB, "tmp"), 0o755); err != nil { + t.Fatal(err) + } + + const boot1 = int64(1_700_000_000) + if got := recordPendingHypervisorBootAt(rootA, WHPXReady, false, boot1); got != HypervisorBootOff { + t.Fatalf("record disable in rootA = %q, want %q", got, HypervisorBootOff) + } + // Verify atomic write leaves no leftover temporary files in /tmp. + entries, err := os.ReadDir(filepath.Join(rootA, "tmp")) + if err != nil || len(entries) != 1 || entries[0].Name() != pendingBootFileName { + t.Fatalf("unexpected files in rootA/tmp after atomic write: %v (err=%v)", entries, err) + } + + // User switches DataRoot to rootB and clicks Undo before restarting Windows. + if got := recordPendingHypervisorBootAt(rootB, WHPXReady, true, boot1+5); got != "" { + t.Fatalf("undo in rootB = %q, want empty", got) + } + // Simulate restarting Reims-Go process and switching back to rootA in the same boot session: + // stale pending file in rootA/tmp must have been cleaned up on undo. + pendingBootMu.Lock() + pendingBootMem = nil + pendingBootPath = "" + pendingBootMu.Unlock() + if got := readPendingHypervisorBootAt(rootA, WHPXReady, boot1+10); got != "" { + t.Fatalf("stale pending record remained in rootA after undo in rootB: got %q, want empty", got) + } +} + +func TestPendingHypervisorBootFastRebootAndSleepResilience(t *testing.T) { + defer func() { + pendingBootMu.Lock() + pendingBootMem = nil + pendingBootPath = "" + pendingBootMu.Unlock() + }() + + root := t.TempDir() + if err := os.MkdirAll(filepath.Join(root, "tmp"), 0o755); err != nil { + t.Fatal(err) + } + + // 1. S3 sleep / S4 hibernate wake: wall-clock minus GetTickCount64 drifts by 3600s + // (> 120s tolerance), while kernel volatile BootMarker stays identical and TickMs increases. + sessBeforeSleep := bootSession{Marker: "hw:1a2b3c4d", EpochSec: 1_700_000_000, TickMs: 25_000} + if got := recordPendingHypervisorBootSession(root, WHPXReady, false, sessBeforeSleep); got != HypervisorBootOff { + t.Fatalf("record before sleep = %q, want %q", got, HypervisorBootOff) + } + sessAfterSleep := bootSession{Marker: "hw:1a2b3c4d", EpochSec: 1_700_003_600, TickMs: 30_000} + if got := readPendingHypervisorBootSession(root, WHPXReady, sessAfterSleep); got != HypervisorBootOff { + t.Fatalf("pending state lost after sleep drift: got %q, want %q", got, HypervisorBootOff) + } + + // 2. Fast NVMe reboot (completed in 30s, well within 120s wall-clock tolerance): + // both volatile BootMarker change AND monotonic TickMs reset expire the stale record. + sessFastRebootMarker := bootSession{Marker: "hw:9f8e7d6c", EpochSec: 1_700_000_030, TickMs: 40_000} + if got := readPendingHypervisorBootSession(root, WHPXReady, sessFastRebootMarker); got != "" { + t.Fatalf("fast reboot with new boot marker must expire pending state, got %q", got) + } + + // Fallback path (no volatile marker): monotonic TickMs reset from 60s -> 8s detects fast reboot. + sessFallbackBefore := bootSession{EpochSec: 1_700_000_000, TickMs: 60_000} + _ = recordPendingHypervisorBootSession(root, WHPXReady, false, sessFallbackBefore) + sessFallbackFastReboot := bootSession{EpochSec: 1_700_000_065, TickMs: 8_000} + if got := readPendingHypervisorBootSession(root, WHPXReady, sessFallbackFastReboot); got != "" { + t.Fatalf("fallback fast reboot with reset TickMs must expire pending state, got %q", got) + } +} + diff --git a/internal/host/hypervisor_windows.go b/internal/host/hypervisor_windows.go new file mode 100644 index 0000000..7974aed --- /dev/null +++ b/internal/host/hypervisor_windows.go @@ -0,0 +1,255 @@ +//go:build windows + +package host + +import ( + "context" + "errors" + "fmt" + "path/filepath" + "syscall" + "time" + "unsafe" + + "golang.org/x/sys/windows" + "golang.org/x/sys/windows/registry" +) + +const ( + pfVirtFirmwareEnabled = 21 + seeMaskNoCloseProcess = 0x00000040 + swHide = 0 + errorSuccessRebootRequired = 3010 + + volatileHardwareSystemKey = `HARDWARE\DESCRIPTION\System` + deviceGuardKey = `SYSTEM\CurrentControlSet\Control\DeviceGuard` + hvciScenarioKey = `SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity` + keyGuardStatusSubKey = `SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\KeyGuard\Status` +) + +var ( + procIsProcessorFeaturePresent = kernel32.NewProc("IsProcessorFeaturePresent") + procGetTickCount64 = kernel32.NewProc("GetTickCount64") + procShellExecuteExW = shell32.NewProc("ShellExecuteExW") +) + +type shellExecuteInfoW struct { + cbSize uint32 + fMask uint32 + hwnd uintptr + lpVerb *uint16 + lpFile *uint16 + lpParameters *uint16 + lpDirectory *uint16 + nShow int32 + hInstApp uintptr + lpIDList uintptr + lpClass *uint16 + hkeyClass uintptr + dwHotKey uint32 + hIconOrMon uintptr + hProcess windows.Handle +} + +func currentBootSession() bootSession { + var tickMs uint64 + var epochSec int64 + if procGetTickCount64.Find() == nil { + raw, _, _ := procGetTickCount64.Call() + tickMs = uint64(raw) + if tickMs > 0 { + epochSec = time.Now().Unix() - int64(tickMs/1000) + } + } + return bootSession{ + Marker: probeVolatileBootMarker(), + EpochSec: epochSec, + TickMs: tickMs, + } +} + +func currentBootEpochSec() int64 { + return currentBootSession().EpochSec +} + +// probeVolatileBootMarker reads the LastWriteTime of HKLM\HARDWARE\DESCRIPTION\System, +// an in-memory REG_OPTION_VOLATILE hive recreated by the Windows kernel on every OS +// boot. Unlike wall-clock minus GetTickCount64, it stays constant across S3 sleep, +// S4 hibernate, and NTP clock jumps, while changing immediately on even a fast reboot. +func probeVolatileBootMarker() string { + k, err := registry.OpenKey(registry.LOCAL_MACHINE, volatileHardwareSystemKey, registry.QUERY_VALUE) + if err != nil { + return "" + } + defer k.Close() + st, err := k.Stat() + if err != nil { + return "" + } + ns := st.ModTime().UnixNano() + if ns <= 0 { + return "" + } + return fmt.Sprintf("hw:%x", ns) +} + +func probeFirmwareVirtEnabled() bool { + if procIsProcessorFeaturePresent.Find() != nil { + return false + } + r, _, _ := procIsProcessorFeaturePresent.Call(uintptr(pfVirtFirmwareEnabled)) + return r != 0 +} + +func probeDeviceGuard() (hvciEnabled, vbsRunning bool) { + vbsVal, _ := regReadDWORD(hkeyLocalMachine, deviceGuardKey, "EnableVirtualizationBasedSecurity") + hvciVal, _ := regReadDWORD(hkeyLocalMachine, hvciScenarioKey, "Enabled") + skVal, _ := regReadDWORD(hkeyLocalMachine, keyGuardStatusSubKey, "IsSecureKernelRunning") + return EvaluateDeviceGuard(vbsVal, hvciVal, skVal) +} + +func hasWinHvPlatformDLL() bool { + mod := syscall.NewLazyDLL("WinHvPlatform.dll") + if mod.Load() != nil { + return false + } + return mod.NewProc("WHvGetCapability").Find() == nil +} + +// buildEnableMissingWHPXCmdLine builds the cmd.exe /V:ON /d /s /c argument +// string that enables HypervisorPlatform via DISM (accepting both 0 and 3010 +// ERROR_SUCCESS_REBOOT_REQUIRED) and then sets hypervisorlaunchtype to auto. +func buildEnableMissingWHPXCmdLine(dismCmd, bcdeditCmd string) string { + return fmt.Sprintf( + `/V:ON /d /s /c "%s & if !errorlevel! equ 0 (%s) else if !errorlevel! equ %d (%s) else (exit /b !errorlevel!)"`, + dismCmd, + bcdeditCmd, + errorSuccessRebootRequired, + bcdeditCmd, + ) +} + +// SetHypervisorBootElevated prompts for Windows UAC confirmation and updates +// the Windows hypervisor boot launch configuration (`bcdedit /set {current} +// hypervisorlaunchtype auto|off`). When enabling on a host that has not yet +// installed Windows Hypervisor Platform (`WinHvPlatform.dll`), it enables +// `HypervisorPlatform` via DISM in the same single UAC elevation. +// +// It never restarts Windows automatically. If the user declines the UAC prompt, +// ErrElevationDeclined is returned. +func SetHypervisorBootElevated(ctx context.Context, enable bool) error { + sysDir, err := windows.GetSystemDirectory() + if err != nil || sysDir == "" { + return fmt.Errorf("resolve Windows System32 directory: %w", err) + } + bcdeditPath := filepath.Join(sysDir, "bcdedit.exe") + if !enable { + code, err := runElevatedWait(ctx, bcdeditPath, `/set {current} hypervisorlaunchtype off`) + if err != nil { + return err + } + if code != 0 { + return &HypervisorExecError{Command: "bcdedit", ExitCode: code} + } + return nil + } + + if hasWinHvPlatformDLL() { + code, err := runElevatedWait(ctx, bcdeditPath, `/set {current} hypervisorlaunchtype auto`) + if err != nil { + return err + } + if code != 0 { + return &HypervisorExecError{Command: "bcdedit", ExitCode: code} + } + return nil + } + + cmdPath := filepath.Join(sysDir, "cmd.exe") + dismPath := filepath.Join(sysDir, "dism.exe") + dismCmd := fmt.Sprintf(`"%s" /Online /Enable-Feature /FeatureName:HypervisorPlatform /All /Quiet /NoRestart`, dismPath) + bcdCmd := fmt.Sprintf(`"%s" /set {current} hypervisorlaunchtype auto`, bcdeditPath) + params := buildEnableMissingWHPXCmdLine(dismCmd, bcdCmd) + + code, err := runElevatedWait(ctx, cmdPath, params) + if err != nil { + return err + } + if code != 0 && code != errorSuccessRebootRequired { + return &HypervisorExecError{Command: "dism+bcdedit", ExitCode: code} + } + return nil +} + +func runElevatedWait(ctx context.Context, exePath, params string) (uint32, error) { + if ctx != nil && ctx.Err() != nil { + return 0, ctx.Err() + } + verbPtr, err := syscall.UTF16PtrFromString("runas") + if err != nil { + return 0, err + } + filePtr, err := syscall.UTF16PtrFromString(exePath) + if err != nil { + return 0, err + } + paramPtr, err := syscall.UTF16PtrFromString(params) + if err != nil { + return 0, err + } + + sei := shellExecuteInfoW{ + fMask: seeMaskNoCloseProcess, + lpVerb: verbPtr, + lpFile: filePtr, + lpParameters: paramPtr, + nShow: swHide, + } + sei.cbSize = uint32(unsafe.Sizeof(sei)) + + r, _, callErr := procShellExecuteExW.Call(uintptr(unsafe.Pointer(&sei))) + if r == 0 { + if errors.Is(callErr, windows.ERROR_CANCELLED) || + errors.Is(callErr, windows.ERROR_ACCESS_DENIED) || + sei.hInstApp == seErrAccessDenied { + return 0, ErrElevationDeclined + } + return 0, fmt.Errorf("ShellExecuteExW runas %s failed (inst=%d): %w", filepath.Base(exePath), sei.hInstApp, callErr) + } + if sei.hProcess == 0 { + return 0, nil + } + defer windows.CloseHandle(sei.hProcess) + + for { + event, werr := windows.WaitForSingleObject(sei.hProcess, 200) + if werr != nil { + return 0, fmt.Errorf("WaitForSingleObject(%s): %w", filepath.Base(exePath), werr) + } + if event == windows.WAIT_OBJECT_0 { + break + } + if event != uint32(windows.WAIT_TIMEOUT) { + return 0, fmt.Errorf("WaitForSingleObject(%s): unexpected status 0x%X", filepath.Base(exePath), event) + } + if ctx != nil && ctx.Err() != nil { + return 0, ctx.Err() + } + } + + var exitCode uint32 + if err := windows.GetExitCodeProcess(sei.hProcess, &exitCode); err != nil { + return 0, fmt.Errorf("GetExitCodeProcess(%s): %w", filepath.Base(exePath), err) + } + return exitCode, nil +} + +// OpenWindowsCoreIsolation opens Windows Security's Core Isolation page so the +// user can inspect or toggle Memory Integrity (HVCI) themselves. +func OpenWindowsCoreIsolation() error { + err := windows.ShellExecute(0, windows.StringToUTF16Ptr("open"), windows.StringToUTF16Ptr("windowsdefender://coreisolation/"), nil, nil, windows.SW_SHOWNORMAL) + if err != nil { + return fmt.Errorf("open Windows Security Core Isolation: %w", err) + } + return nil +} diff --git a/internal/host/hypervisor_windows_test.go b/internal/host/hypervisor_windows_test.go new file mode 100644 index 0000000..ca1d34a --- /dev/null +++ b/internal/host/hypervisor_windows_test.go @@ -0,0 +1,131 @@ +//go:build windows + +package host + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "syscall" + "testing" + + "golang.org/x/sys/windows" +) + +func TestBuildEnableMissingWHPXCmdLineExitCodes(t *testing.T) { + sysDir, err := windows.GetSystemDirectory() + if err != nil { + t.Fatalf("GetSystemDirectory: %v", err) + } + cmdExe := filepath.Join(sysDir, "cmd.exe") + + cases := []struct { + name string + dismCode int + bcdCode int + wantExit int + }{ + {"dism 0 and bcdedit 0 succeeds", 0, 0, 0}, + {"dism 3010 reboot-required and bcdedit 0 succeeds", 3010, 0, 0}, + {"dism failure 87 aborts without running bcdedit", 87, 0, 87}, + {"dism 3010 followed by bcdedit failure 1 propagates 1", 3010, 1, 1}, + } + + for _, tc := range cases { + dismMock := `cmd.exe /c exit ` + itoa(tc.dismCode) + bcdMock := `cmd.exe /c exit ` + itoa(tc.bcdCode) + rawArgs := buildEnableMissingWHPXCmdLine(dismMock, bcdMock) + + c := exec.Command(cmdExe) + c.SysProcAttr = &syscall.SysProcAttr{CmdLine: `"` + cmdExe + `" ` + rawArgs} + err := c.Run() + got := 0 + if err != nil { + exitErr, ok := err.(*exec.ExitError) + if !ok { + t.Fatalf("%s: unexpected exec error: %v", tc.name, err) + } + got = exitErr.ExitCode() + } + if got != tc.wantExit { + t.Errorf("%s: exit code = %d, want %d (args=%s)", tc.name, got, tc.wantExit, rawArgs) + } + } +} + +func TestWindowsBootEpochAndUnprivilegedVirtualizationProbes(t *testing.T) { + sess1 := currentBootSession() + sess2 := currentBootSession() + if sess1.EpochSec <= 0 { + t.Fatalf("expected positive Windows boot epoch, got %d", sess1.EpochSec) + } + if sess1.Marker == "" || sess1.Marker != sess2.Marker { + t.Fatalf("expected stable non-empty volatile boot marker, got %q vs %q", sess1.Marker, sess2.Marker) + } + if sess2.TickMs < sess1.TickMs { + t.Fatalf("expected monotonic TickMs, got %d -> %d", sess1.TickMs, sess2.TickMs) + } + // Canceled context must abort runElevatedWait before invoking ShellExecuteExW / UAC. + canceledCtx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := runElevatedWait(canceledCtx, `C:\Windows\System32\bcdedit.exe`, `/enum`); !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled before UAC, got %v", err) + } + // Ensure unprivileged DeviceGuard and firmware virtualization probes never panic or fail. + _, _ = probeDeviceGuard() + _ = probeFirmwareVirtEnabled() +} + +func TestBuildEnableMissingWHPXCmdLineQuotedPathsWithSpaces(t *testing.T) { + sysDir, err := windows.GetSystemDirectory() + if err != nil { + t.Fatalf("GetSystemDirectory: %v", err) + } + cmdExe := filepath.Join(sysDir, "cmd.exe") + + spacedDir := filepath.Join(t.TempDir(), "System Tools With Spaces") + if err := os.MkdirAll(spacedDir, 0o755); err != nil { + t.Fatal(err) + } + dismBat := filepath.Join(spacedDir, "mock dism.cmd") + bcdBat := filepath.Join(spacedDir, "mock bcdedit.cmd") + markerFile := filepath.Join(spacedDir, "bcd ran.txt") + if err := os.WriteFile(dismBat, []byte("@exit /b 3010\r\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(bcdBat, []byte(fmt.Sprintf("@echo ok>\"%s\" & exit /b 0\r\n", markerFile)), 0o644); err != nil { + t.Fatal(err) + } + + dismCmd := fmt.Sprintf(`"call "%s""`, dismBat) + // Also test realistic direct quoted executable invocation (`"C:\...\cmd.exe" /c ...`) + dismCmd = fmt.Sprintf(`"%s" /d /c ""%s""`, cmdExe, dismBat) + bcdCmd := fmt.Sprintf(`"%s" /d /c ""%s""`, cmdExe, bcdBat) + rawArgs := buildEnableMissingWHPXCmdLine(dismCmd, bcdCmd) + + c := exec.Command(cmdExe) + c.SysProcAttr = &syscall.SysProcAttr{CmdLine: `"` + cmdExe + `" ` + rawArgs} + if err := c.Run(); err != nil { + t.Fatalf("quoted spaced command failed: %v (args=%s)", err, rawArgs) + } + if _, err := os.Stat(markerFile); err != nil { + t.Fatalf("expected chained bcdedit mock to run after DISM 3010, stat err=%v", err) + } +} + +func itoa(v int) string { + if v == 0 { + return "0" + } + var buf [20]byte + i := len(buf) + for v > 0 { + i-- + buf[i] = byte('0' + v%10) + v /= 10 + } + return string(buf[i:]) +} diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 320ecb0..2f5e5b4 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -116,6 +116,7 @@ var catalog = map[Locale]map[string]string{ "doctor.runtime.none": "尚未安装(运行 reims-go runtime install <压缩包> 导入)", "doctor.title": "Reims-Go 宿主机环境体检", "doctor.whpx": "Windows 虚拟机监控程序平台 (WHPX)", + "doctor.whpx.hypervisor_off": "未随系统启动(BIOS 虚拟化已开启,Hypervisor 启动已关闭;启用并重启 Windows 后可用)", "doctor.whpx.missing": "未启用(请点击一键启用 HypervisorPlatform 并重启 Windows)", "doctor.whpx.no_hv": "已加载 WinHvPlatform.dll,但未检测到虚拟化(请在 BIOS 开启 VT-x/AMD-V)", "doctor.whpx.ok": "可用(WinHvPlatform.dll 已就绪,hypervisor 运行中)", @@ -166,6 +167,10 @@ var catalog = map[Locale]map[string]string{ "err.gpu_icd_stale": "原显卡的 Vulkan ICD 文件已不存在({path})。在设置 → 图形与显示器中重新选择显卡,或选择自动", "err.gpu_vulkan_floor": "宿主显卡不满足 Reims vGPU 的 Vulkan 1.3 硬件要求。请更新显卡驱动,或在设置中将虚拟显卡切为 VMware SVGA(软件渲染)", "err.guest_tools_disabled": "Guest Tools 传输服务已在插件页停用,启用后才能使用剪贴板、共享文件夹与防休眠", + "err.hypervisor.busy_tasks": "等待虚拟机创建任务结束或取消后再更改系统虚拟化启动设置", + "err.hypervisor.busy_vms": "关闭所有运行中或正在切换状态的虚拟机后再更改系统虚拟化启动设置", + "err.hypervisor.set_failed": "未能修改 Windows Hypervisor 启动设置", + "err.hypervisor.unsupported": "当前系统不支持切换 Windows Hypervisor 启动设置", "err.macos.disabled": "「macOS 虚拟机支持」插件已停用,请先在插件页启用", "err.plugin.high_risk_unapproved": "插件「{id}」包含高危权限,需要先确认授权后才能启用", "err.plugin.in_use": "插件「{id}」正在被虚拟机使用,无法停用或卸载:{reason}", @@ -198,6 +203,7 @@ var catalog = map[Locale]map[string]string{ "err.update_relaunch": "新版本已安装,但没能自动重新打开,请手动启动 Reims-Go", "err.vm_not_running": "虚拟机 {name} 未运行", "err.vm_window_not_found": "找不到 {name} 的显示窗口", + "err.whpx_hypervisor_off": "Windows Hypervisor 启动项当前处于关闭状态(常见于兼容独占模式的 VMware)。在「设置」或「内核」页启用并手动重启 Windows 后再启动虚拟机", "err.whpx_missing": "未启用 Windows 虚拟机监控程序平台(WHPX)。在「宿主机」页启用 WHPX 并重启 Windows 后再启动虚拟机", "err.whpx_no_hypervisor": "Windows Hypervisor 虚拟化引擎未激活(与磁盘空间无关)。确认 BIOS 已开启 Intel VT-x / AMD SVM,在「宿主机」页启用 WHPX,以管理员运行 bcdedit /set hypervisorlaunchtype auto,然后重启 Windows", "err.whpx_unsupported": "当前系统不支持 Windows 虚拟机监控程序平台(WHPX),需要 Windows 10 1803 或更高版本", @@ -795,6 +801,7 @@ var catalog = map[Locale]map[string]string{ "doctor.runtime.none": "Not installed (run `reims-go runtime install `)", "doctor.title": "Reims-Go Host Environment Check", "doctor.whpx": "Windows Hypervisor Platform (WHPX)", + "doctor.whpx.hypervisor_off": "Turned off on boot (BIOS virtualization is on, hypervisor launch is off; enable and restart Windows)", "doctor.whpx.missing": "Not enabled (enable Windows Hypervisor Platform and restart Windows)", "doctor.whpx.no_hv": "WinHvPlatform.dll present, but no hypervisor detected (enable VT-x/AMD-V in BIOS)", "doctor.whpx.ok": "Ready (WinHvPlatform.dll active, hypervisor running)", @@ -845,6 +852,10 @@ var catalog = map[Locale]map[string]string{ "err.gpu_icd_stale": "The selected GPU's Vulkan ICD file no longer exists ({path}). In Settings → Graphics & displays, reselect the GPU or choose Automatic", "err.gpu_vulkan_floor": "Host GPU does not meet Reims vGPU's Vulkan 1.3 requirements. Update GPU drivers or switch graphics to VMware SVGA (software rendering) in VM Settings", "err.guest_tools_disabled": "Guest Tools Transport is turned off on the Plugins page; turn it on to use clipboard, shared folders and keep-awake", + "err.hypervisor.busy_tasks": "Wait for active VM creation tasks to finish or cancel them before changing host virtualization boot settings", + "err.hypervisor.busy_vms": "Stop all running or transitioning virtual machines before changing host virtualization boot settings", + "err.hypervisor.set_failed": "Could not update Windows Hypervisor boot settings", + "err.hypervisor.unsupported": "Switching Windows Hypervisor boot settings is only supported on Windows", "err.macos.disabled": "macOS VM Support is disabled; enable it on the Plugins page first", "err.plugin.high_risk_unapproved": "Plugin “{id}” requests high-risk permissions and requires confirmation before enabling", "err.plugin.in_use": "Plugin “{id}” is currently in use and cannot be disabled or removed: {reason}", @@ -877,6 +888,7 @@ var catalog = map[Locale]map[string]string{ "err.update_relaunch": "The new version is installed but didn't reopen; start Reims-Go again", "err.vm_not_running": "VM {name} is not running", "err.vm_window_not_found": "Couldn’t find the display window for {name}", + "err.whpx_hypervisor_off": "Windows Hypervisor launch is currently turned off (commonly used for exclusive-mode VMware). Enable it in Settings or on the Engine page and restart Windows before starting the VM", "err.whpx_missing": "Windows Hypervisor Platform (WHPX) is not enabled. Enable WHPX on the Host page and restart Windows before starting the VM", "err.whpx_no_hypervisor": "Windows Hypervisor is not active (unrelated to disk space). Ensure Intel VT-x / AMD SVM is enabled in BIOS, enable WHPX on the Host page, run `bcdedit /set hypervisorlaunchtype auto` as Administrator, and restart Windows", "err.whpx_unsupported": "Windows Hypervisor Platform (WHPX) is not supported on this OS; Windows 10 1803 or newer is required", diff --git a/internal/macos/startprep/startprep.go b/internal/macos/startprep/startprep.go index 12f7fe3..b46bac3 100644 --- a/internal/macos/startprep/startprep.go +++ b/internal/macos/startprep/startprep.go @@ -54,6 +54,8 @@ func (p *Prep) CheckWHPX(rep host.Report) error { return nil case host.WHPXMissing: return fmt.Errorf("%s", i18n.T(p.cfg.Locale, "err.whpx_missing")) + case host.WHPXHypervisorOff: + return fmt.Errorf("%s", i18n.T(p.cfg.Locale, "err.whpx_hypervisor_off")) case host.WHPXNoHypervisor: return fmt.Errorf("%s", i18n.T(p.cfg.Locale, "err.whpx_no_hypervisor")) default: diff --git a/internal/macos/startprep/startprep_test.go b/internal/macos/startprep/startprep_test.go index 39b968e..10f9497 100644 --- a/internal/macos/startprep/startprep_test.go +++ b/internal/macos/startprep/startprep_test.go @@ -16,6 +16,12 @@ func TestCheckWHPX(t *testing.T) { if err := pZh.CheckWHPX(host.Report{WHPX: host.WHPXReady}); err != nil { t.Fatalf("WHPXReady should pass, got %v", err) } + if err := pZh.CheckWHPX(host.Report{WHPX: host.WHPXHypervisorOff}); err == nil || !strings.Contains(err.Error(), "VMware") { + t.Fatalf("WHPXHypervisorOff (zh-CN) = %v", err) + } + if err := pEn.CheckWHPX(host.Report{WHPX: host.WHPXHypervisorOff}); err == nil || !strings.Contains(err.Error(), "VMware") { + t.Fatalf("WHPXHypervisorOff (en-US) = %v", err) + } if err := pZh.CheckWHPX(host.Report{WHPX: host.WHPXNoHypervisor}); err == nil || !strings.Contains(err.Error(), "hypervisorlaunchtype") { t.Fatalf("WHPXNoHypervisor (zh-CN) = %v", err) } diff --git a/locales/en-US/native.json b/locales/en-US/native.json index 804377d..bb417c9 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -1174,5 +1174,11 @@ "err.dataroot.damaged": "The data version record in {dir} is damaged. The folder was opened read-only and nothing was changed. If it comes from this or an older version, you can repair the record in the app", "err.dataroot.locked": "Another Reims-Go process is upgrading the data folder {dir}. Try again once it finishes", "err.dataroot.migration_failed": "Upgrading the data folder {dir} failed, so nothing more is written to it. Try again or choose another data folder", - "err.dataroot.needs_setup": "Choose a data folder in first-run setup first" + "err.dataroot.needs_setup": "Choose a data folder in first-run setup first", + "doctor.whpx.hypervisor_off": "Turned off on boot (BIOS virtualization is on, hypervisor launch is off; enable and restart Windows)", + "err.whpx_hypervisor_off": "Windows Hypervisor launch is currently turned off (commonly used for exclusive-mode VMware). Enable it in Settings or on the Engine page and restart Windows before starting the VM", + "err.hypervisor.busy_vms": "Stop all running or transitioning virtual machines before changing host virtualization boot settings", + "err.hypervisor.busy_tasks": "Wait for active VM creation tasks to finish or cancel them before changing host virtualization boot settings", + "err.hypervisor.set_failed": "Could not update Windows Hypervisor boot settings", + "err.hypervisor.unsupported": "Switching Windows Hypervisor boot settings is only supported on Windows" } diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index 4cfb447..e818183 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -526,5 +526,41 @@ "guestTimezoneLosAngeles": "Los Angeles", "guestTimezoneNewYork": "New York", "guestTimezoneSydney": "Sydney", - "guestTimezoneUTC": "UTC" + "guestTimezoneUTC": "UTC", + "whpxHvOffShort": "Turned off", + "whpxHvOff": "Hypervisor launch is off — enable and restart Windows", + "whpxPendingOnShort": "Enable on restart", + "whpxPendingOffShort": "Disable on restart", + "whpxPendingHint": "Takes effect after restarting Windows", + "whpxPendingOffHint": "Active now · turns off after restart", + "settingsVirtualization": "Virtualization coexistence", + "hypervisorSwitchGateTitle": "Hyper-V boot switch", + "hypervisorSwitchGateSub": "Unlock when alternating with exclusive-mode VMware; turning this on alone changes no system settings", + "hypervisorBootRowTitle": "Windows Hypervisor", + "hypervisorBadgeActive": "Active", + "hypervisorBadgeOff": "Turned off", + "hypervisorBadgePendingOn": "Enabling on restart", + "hypervisorBadgePendingOff": "Disabling on restart", + "hypervisorSubActive": "Running now for Reims-Go and WSL2; disable and restart Windows to use exclusive-mode VMware", + "hypervisorSubOff": "Not launched on boot for exclusive-mode VMware; enable and restart Windows to run Reims-Go", + "hypervisorSubMissing": "Windows Hypervisor Platform is not enabled yet; enable and restart Windows to run Reims-Go", + "hypervisorSubNoHv": "No active hypervisor detected; ensure VT-x / AMD-V is on in BIOS, then enable on boot", + "hypervisorSubPendingOff": "Set to stay off on next boot; restart Windows manually to apply", + "hypervisorSubPendingOn": "Set to launch on next boot; restart Windows manually to apply", + "hypervisorActionDisable": "Disable on boot", + "hypervisorActionEnable": "Enable on boot", + "hypervisorActionUndo": "Undo change", + "hypervisorStopVMsFirst": "Stop all running VMs before disabling Hyper-V", + "hypervisorHVCINotice": "Memory integrity (Core isolation) is on and may keep virtualization active after restart", + "hypervisorOpenCoreIsolation": "Open settings", + "hypervisorConfirmOffTitle": "Disable Windows Hypervisor on next boot", + "hypervisorConfirmOffBody": "After you restart Windows, exclusive-mode VMware can use hardware virtualization directly, while Reims-Go, WSL2, and Docker Desktop will pause until re-enabled.", + "hypervisorConfirmOffBitLocker": "If your system drive uses BitLocker with custom boot validation, keep your recovery key handy before changing boot settings. Windows will not restart automatically.", + "hypervisorConfirmOnTitle": "Enable Windows Hypervisor on next boot", + "hypervisorConfirmOnBody": "Configures Windows to launch the hypervisor on next boot (and enables Windows Hypervisor Platform if missing). Restart Windows manually to run Reims-Go and WSL2; Windows will not restart automatically.", + "hypervisorConfirmDisableBtn": "Disable on boot", + "hypervisorConfirmEnableBtn": "Enable on boot", + "toastHypervisorPendingOff": "Hypervisor set to off on next boot — restart Windows to apply", + "toastHypervisorPendingOn": "Hypervisor set to launch on boot — restart Windows to apply", + "toastHypervisorUndone": "Restored current hypervisor boot setting" } diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index 909a776..84dd6eb 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -1174,5 +1174,11 @@ "err.dataroot.damaged": "数据目录 {dir} 的数据版本记录已损坏,已以只读方式打开,没有做任何修改。确认目录来自当前或更早的版本后,可在界面中修复版本记录", "err.dataroot.locked": "数据目录 {dir} 正被另一个 Reims-Go 进程升级,请等它完成后重试", "err.dataroot.migration_failed": "升级数据目录 {dir} 时出错,已停止写入。可以重试,或选择其他数据目录", - "err.dataroot.needs_setup": "请先在首次设置中选择数据目录" + "err.dataroot.needs_setup": "请先在首次设置中选择数据目录", + "doctor.whpx.hypervisor_off": "未随系统启动(BIOS 虚拟化已开启,Hypervisor 启动已关闭;启用并重启 Windows 后可用)", + "err.whpx_hypervisor_off": "Windows Hypervisor 启动项当前处于关闭状态(常见于兼容独占模式的 VMware)。在「设置」或「内核」页启用并手动重启 Windows 后再启动虚拟机", + "err.hypervisor.busy_vms": "关闭所有运行中或正在切换状态的虚拟机后再更改系统虚拟化启动设置", + "err.hypervisor.busy_tasks": "等待虚拟机创建任务结束或取消后再更改系统虚拟化启动设置", + "err.hypervisor.set_failed": "未能修改 Windows Hypervisor 启动设置", + "err.hypervisor.unsupported": "当前系统不支持切换 Windows Hypervisor 启动设置" } diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index db573f7..d516bc5 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -526,5 +526,41 @@ "guestTimezoneLosAngeles": "洛杉矶", "guestTimezoneNewYork": "纽约", "guestTimezoneSydney": "悉尼", - "guestTimezoneUTC": "UTC(协调世界时)" + "guestTimezoneUTC": "UTC(协调世界时)", + "whpxHvOffShort": "已关闭", + "whpxHvOff": "Hypervisor 启动已关闭,启用后重启 Windows", + "whpxPendingOnShort": "待重启开启", + "whpxPendingOffShort": "待重启关闭", + "whpxPendingHint": "手动重启 Windows 后生效", + "whpxPendingOffHint": "当前可用,重启 Windows 后关闭", + "settingsVirtualization": "虚拟化共存", + "hypervisorSwitchGateTitle": "Hyper-V 启动切换", + "hypervisorSwitchGateSub": "与独占硬件虚拟化的 VMware 交替使用时开启,开启此项本身不修改系统配置", + "hypervisorBootRowTitle": "Windows Hypervisor", + "hypervisorBadgeActive": "已激活", + "hypervisorBadgeOff": "已关闭", + "hypervisorBadgePendingOn": "下次启动开启", + "hypervisorBadgePendingOff": "下次启动关闭", + "hypervisorSubActive": "当前运行中,支持 Reims-Go 与 WSL2;切换为关闭并重启后可供独占模式 VMware 使用", + "hypervisorSubOff": "当前未随系统启动,适合独占模式 VMware;切换为开启并重启后可运行 Reims-Go", + "hypervisorSubMissing": "尚未启用 Windows 虚拟机监控程序平台,切换为开启并重启后可运行 Reims-Go", + "hypervisorSubNoHv": "未检测到活跃虚拟化,确认 BIOS 已开启 VT-x / AMD-V 后可设为随系统启动", + "hypervisorSubPendingOff": "已设为下次启动关闭,手动重启 Windows 后生效", + "hypervisorSubPendingOn": "已设为随系统启动,手动重启 Windows 后生效", + "hypervisorActionDisable": "切换为关闭", + "hypervisorActionEnable": "切换为开启", + "hypervisorActionUndo": "撤销更改", + "hypervisorStopVMsFirst": "先关闭所有运行中的虚拟机再关闭 Hyper-V", + "hypervisorHVCINotice": "内存完整性(内核隔离)处于开启状态,重启后若仍占用虚拟化可在 Windows 安全中心调整", + "hypervisorOpenCoreIsolation": "打开设置", + "hypervisorConfirmOffTitle": "下次启动关闭 Windows Hypervisor", + "hypervisorConfirmOffBody": "手动重启 Windows 后,独占硬件虚拟化的 VMware 可正常运行,Reims-Go、WSL2 与 Docker Desktop 将暂时无法启动虚拟机。", + "hypervisorConfirmOffBitLocker": "若系统盘开启了自定义策略的 BitLocker,修改引导配置前确认已备好恢复密钥。此操作不会自动重启电脑。", + "hypervisorConfirmOnTitle": "下次启动开启 Windows Hypervisor", + "hypervisorConfirmOnBody": "配置 Windows 在下次启动时加载 Hypervisor(缺少平台组件时一并启用)。手动重启 Windows 后 Reims-Go 与 WSL2 即可正常使用,此操作不会自动重启电脑。", + "hypervisorConfirmDisableBtn": "确认关闭", + "hypervisorConfirmEnableBtn": "确认开启", + "toastHypervisorPendingOff": "已设为下次启动关闭,重启 Windows 后生效", + "toastHypervisorPendingOn": "已设为随系统启动,重启 Windows 后生效", + "toastHypervisorUndone": "已恢复当前启动设置" } From fa3e1e28896457a826a559535b5413d8791e29f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Wed, 2 Dec 2026 23:11:13 -0700 Subject: [PATCH 06/28] feat: add plugin views and expand the sandboxed page bridge Plugins can add pages to the sidebar, VM tabs, Settings and dialogs. Their pages can now use host forms and navigation, VM and settings access, authorized file I/O, task progress, controlled HTTP requests, events and private storage. Plugin pages cannot change allow_ai_access, which stays the user's per-VM consent. Closing a page cancels its unfinished tasks, and running plugin tasks no longer block changing the data folder. Co-Authored-By: Claude Opus 5.5 --- changes/plugin-view-capabilities.json | 7 + docs/plugin-architecture.md | 10 +- frontend/bridge-contract.json | 67 ++-- frontend/scripts/test-plugins.mjs | 198 ++++++++++++ frontend/src/App.tsx | 156 ++++++++- frontend/src/components/AppSettingsPage.tsx | 25 +- frontend/src/components/PluginPanelFrame.tsx | 272 +++++++++++++--- frontend/src/components/PluginViewHost.tsx | 72 +++++ frontend/src/components/PluginsPage.tsx | 8 +- frontend/src/components/Sidebar.tsx | 20 +- frontend/src/i18n/domains/core.gen.ts | 8 + frontend/src/i18n/keys.gen.ts | 4 + frontend/src/lib/bridgeContract.ts | 19 +- frontend/src/lib/pluginAssets.ts | 16 + frontend/src/lib/pluginViewActions.ts | 137 ++++++++ frontend/src/lib/pluginViewEvents.ts | 13 + frontend/src/lib/pluginViewRouter.ts | 72 +++++ frontend/src/styles/app.css | 6 + frontend/src/styles/ui-contract.ts | 6 +- frontend/src/types.ts | 1 + frontend/src/ui/dialog.tsx | 10 +- frontend/ui-contract.json | 14 +- frontend/wailsjs/go/models.ts | 48 +++ internal/app/app.go | 11 +- internal/app/computer_use_host.go | 6 +- internal/app/plugin_bridge_data_test.go | 322 +++++++++++++++++++ internal/app/plugin_bridge_events.go | 62 ++++ internal/app/plugin_bridge_files.go | 222 +++++++++++++ internal/app/plugin_bridge_net.go | 165 ++++++++++ internal/app/plugin_bridge_settings.go | 138 ++++++++ internal/app/plugin_bridge_tasks.go | 195 +++++++++++ internal/app/plugin_bridge_ui.go | 162 ++++++++++ internal/app/plugin_bridge_vm.go | 38 +++ internal/app/plugins_flow.go | 166 +++++++++- internal/app/plugins_flow_test.go | 135 ++++++++ internal/app/tasks.go | 20 +- internal/i18n/catalog_gen.go | 9 + internal/plugin/contract.go | 77 ++--- internal/plugin/contract_test.go | 23 +- internal/plugin/manager.go | 50 +++ internal/plugin/registry.go | 62 ++++ internal/plugin/view_storage.go | 172 ++++++++++ internal/plugin/view_storage_test.go | 101 ++++++ internal/plugin/views_test.go | 47 +++ locales/en-US/core.json | 4 + locales/zh-CN/core.json | 4 + 46 files changed, 3197 insertions(+), 183 deletions(-) create mode 100644 changes/plugin-view-capabilities.json create mode 100644 frontend/src/components/PluginViewHost.tsx create mode 100644 frontend/src/lib/pluginAssets.ts create mode 100644 frontend/src/lib/pluginViewActions.ts create mode 100644 frontend/src/lib/pluginViewEvents.ts create mode 100644 frontend/src/lib/pluginViewRouter.ts create mode 100644 internal/app/plugin_bridge_data_test.go create mode 100644 internal/app/plugin_bridge_events.go create mode 100644 internal/app/plugin_bridge_files.go create mode 100644 internal/app/plugin_bridge_net.go create mode 100644 internal/app/plugin_bridge_settings.go create mode 100644 internal/app/plugin_bridge_tasks.go create mode 100644 internal/app/plugin_bridge_ui.go create mode 100644 internal/app/plugin_bridge_vm.go create mode 100644 internal/app/plugins_flow_test.go create mode 100644 internal/plugin/view_storage.go create mode 100644 internal/plugin/view_storage_test.go create mode 100644 internal/plugin/views_test.go diff --git a/changes/plugin-view-capabilities.json b/changes/plugin-view-capabilities.json new file mode 100644 index 0000000..c403eaa --- /dev/null +++ b/changes/plugin-view-capabilities.json @@ -0,0 +1,7 @@ +{ + "group": "new", + "order": 0, + "authors": ["Nwflower"], + "zh": "沙箱页面插件新增四种视图位置、宿主表单与导航、虚拟机和设置访问、授权文件读写、任务进度、受控网络请求及事件订阅,并支持确认、复制、外链和私有存储。", + "en": "Add four view locations, host forms and navigation, VM and settings access, authorized file I/O, task progress, controlled HTTP requests, and event subscriptions to sandboxed plugins, alongside confirmations, clipboard copy, external links, and private storage." +} diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 5e72e54..9347a73 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -54,7 +54,15 @@ Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 V 已激活的外部主题在重启客户端和升级插件后自动保留,并在脚本变更重新批准后带版本哈希参数重载;仅停用或卸载所属主题插件时回退内置默认主题并清空当前配色方案,安全模式或命令行停用无关插件不会影响当前主题。从市场安装并启用主题插件时,仅当当前仍处于内置默认主题才自动切换为该插件的首个主题,不覆盖用户已选的其他外部主题。 -自定义界面优先采用 JSON Schema 声明式设置(支持标记敏感项、全局或按虚拟机作用域及生效时机);确需自绘界面的插件使用 `sandbox="allow-scripts"` 且禁联网的沙箱 `iframe`,通过消息桥请求通知、通用虚拟机列表、插件自有命令与多语种词包,所有本地 HTTP 服务均拒绝来自沙箱 `iframe` 或空来源的跨站请求。 +自定义界面优先采用 JSON Schema 声明式设置(支持标记敏感项、全局或按虚拟机作用域及生效时机);确需自绘界面的插件使用 `sandbox="allow-scripts"` 且禁联网的沙箱 `iframe`,通过消息桥请求通知、通用虚拟机列表、插件自有命令与多语种词包,所有本地 HTTP 服务均拒绝来自沙箱 `iframe` 或空来源的跨站请求。`contributes.views` 可在侧栏、VM 标签页、全局设置页或对话框中挂载完整视图,视图随插件作用域注册和释放,停用后自动回退到对应内置页面。视图的 `when` 支持 `vmState==<状态>` 与 `theme==`,条件不满足时宿主隐藏入口和页面。`minWidth` 设置页面的最小宽度,空间不足时横向滚动。 + +页面可通过 `ui.confirm` 请求确认框,通过 `ui.showForm` 打开声明式表单,通过 `ui.copy` 复制文本,通过 `ui.openExternal` 打开经宿主校验的 HTTPS 外链,并使用 `ui.setTitle`、`ui.setBadge` 更新当前视图元数据。`ui.openView` 仅打开本插件声明的视图,`ui.close` 关闭当前视图或顶层对话框,`ui.navigate` 进入内置宿主页面;这些操作不会关闭应用窗口。确认框使用 `ui:notify` 权限,其他界面动作使用 `ui:slot` 权限。 + +`vm.get` 返回不含宿主路径的虚拟机详情。`settings.get` 与 `settings.set` 仅访问本插件清单声明的设置,校验类型、枚举、数值范围和 app/VM 作用域;秘密值读取时保持掩码,写入时沿用现有加密保存。`allow_ai_access` 记录用户对单台虚拟机的授权,只能由用户在宿主设置中修改。`storage.get`、`storage.set`、`storage.list` 与 `storage.delete` 提供按插件隔离且重启后保留的 JSON 键值存储,需要 `fs:plugin_data` 权限;存储键、单值与总大小均有上限,文件损坏时明确报错,不自动清空已有状态。 + +`file.pick` 与 `file.save` 通过原生对话框取得插件专属文件句柄,`file.read` 与 `file.write` 只接受这些句柄,不接受任意宿主路径,支持 UTF-8 和 Base64,单个文件上限为 8 MiB。`task.start`、`task.update` 与 `task.finish` 复用底部任务进度区,任务按插件归属校验,支持协作取消。页面关闭或重新加载时,宿主取消该页面未结束的任务;停用、卸载或切换数据目录会取消任务并撤销文件句柄。 + +`net.fetch` 按清单中的 `net:<主机>` 发起请求,支持文本、JSON 和 Base64 响应,重定向目标逐次重新授权,不回传 `Set-Cookie`。`events.subscribe` 与 `events.unsubscribe` 管理 `vm.stateChanged`、`view.visibilityChanged` 和 `task.updated` 订阅;VM 事件要求 `vm:read`,任务事件只发送本插件任务,视图可见性事件在订阅时先发送当前状态。`theme.changed` 与 `locale.changed` 无需订阅即会送达。 公开契约按语义化版本分为三个独立版本面,插件在 `plugin.json` 的 `engines` 中声明兼容范围: diff --git a/frontend/bridge-contract.json b/frontend/bridge-contract.json index 3614e76..a967b6e 100644 --- a/frontend/bridge-contract.json +++ b/frontend/bridge-contract.json @@ -4,45 +4,44 @@ "hello", "i18n.getBundle", "ui.notify", + "ui.confirm", + "ui.copy", + "ui.openExternal", + "ui.showForm", + "ui.setTitle", + "ui.setBadge", + "ui.openView", + "ui.close", + "ui.navigate", "vm.list", - "command.invoke" + "vm.get", + "command.invoke", + "settings.get", + "settings.set", + "storage.get", + "storage.set", + "storage.list", + "storage.delete", + "file.pick", + "file.save", + "file.read", + "file.write", + "task.start", + "task.update", + "task.finish", + "net.fetch", + "events.subscribe", + "events.unsubscribe" ], "events": [ "theme.changed", - "locale.changed" + "locale.changed", + "vm.stateChanged", + "view.visibilityChanged", + "task.updated" ], "experimental": { - "methods": [ - "ui.confirm", - "ui.showForm", - "ui.setTitle", - "ui.setBadge", - "ui.openView", - "ui.close", - "ui.navigate", - "ui.openExternal", - "vm.get", - "settings.get", - "settings.set", - "storage.get", - "storage.set", - "storage.list", - "storage.delete", - "file.pick", - "file.save", - "file.read", - "file.write", - "task.start", - "task.update", - "task.finish", - "net.fetch", - "events.subscribe", - "events.unsubscribe" - ], - "events": [ - "vm.stateChanged", - "view.visibilityChanged", - "task.updated" - ] + "methods": [], + "events": [] } } diff --git a/frontend/scripts/test-plugins.mjs b/frontend/scripts/test-plugins.mjs index 4923c05..a50c89b 100644 --- a/frontend/scripts/test-plugins.mjs +++ b/frontend/scripts/test-plugins.mjs @@ -10,6 +10,10 @@ const appCSSPath = path.resolve(__dirname, '../src/styles/app.css') const { hasVisibleDialog, isDialogElementVisible } = await loadTestModule(`export * from './lib/dialogState'`) const { resolvePluginApprovalNotice } = await loadTestModule(`export { resolvePluginApprovalNotice } from './components/PluginParts'`) +const { createPluginTaskScope, initialFormValues, invokePluginViewAction, missingFormFields } = await loadTestModule(`export * from './lib/pluginViewActions'`) +const { openPluginView, closePluginView, emptyPluginViewState, matchViewCondition, prunePluginViews } = await loadTestModule(`export * from './lib/pluginViewRouter'`) +const { publishPluginHostEvent, subscribePluginHostEvents } = await loadTestModule(`export * from './lib/pluginViewEvents'`) +const { buildSafePluginAssetURL } = await loadTestModule(`export * from './lib/pluginAssets'`) function fakeDialog({ display = 'block', @@ -118,3 +122,197 @@ test('dialog body children and plugin scan lists disable flex shrinking so tall assert.match(css, /\.dialog-body\s*>\s*\*\s*\{[^}]*flex-shrink\s*:\s*0/) assert.match(css, /\.plugin-scan-section\s*>\s*\.list\s*\{[^}]*flex-shrink\s*:\s*0/) }) + +test('packaged view assets stay on the same-origin plugin asset server', () => { + assert.equal(buildSafePluginAssetURL('abc123', 'vendor.tool', 'icons/console.svg'), '/plugin-assets/abc123/vendor.tool/icons/console.svg') + assert.equal(buildSafePluginAssetURL('abc123', 'vendor.tool', '../secret'), null) + assert.equal(buildSafePluginAssetURL('abc123', 'vendor.tool', 'icons\\secret.svg'), null) + assert.equal(buildSafePluginAssetURL('abc123', 'vendor.tool', 'https://example.com/icon.svg'), null) + assert.equal(buildSafePluginAssetURL('not-safe', 'vendor.tool', 'icon.svg'), null) +}) + +test('plugin confirmation runs only after host validation and returns the user choice', async () => { + const steps = [] + const result = await invokePluginViewAction('ui.confirm', { message: 'Publish?' }, { + invoke: async (method, params) => { + steps.push(['invoke', method, params.message]) + return { message: params.message, danger: true } + }, + confirm: async (request) => { + steps.push(['confirm', request.message, request.danger]) + return true + }, + copy: async () => { throw new Error('unexpected copy') }, + }) + assert.deepEqual(result, { confirmed: true }) + assert.deepEqual(steps, [ + ['invoke', 'ui.confirm', 'Publish?'], + ['confirm', 'Publish?', true], + ]) +}) + +test('plugin clipboard write waits for host approval and is skipped on rejection', async () => { + const copied = [] + const result = await invokePluginViewAction('ui.copy', { text: 'first\nsecond' }, { + invoke: async () => ({ text: 'first\nsecond' }), + confirm: async () => { throw new Error('unexpected confirmation') }, + copy: async (text) => { copied.push(text) }, + }) + assert.deepEqual(result, { ok: true }) + assert.deepEqual(copied, ['first\nsecond']) + + await assert.rejects(invokePluginViewAction('ui.copy', { text: 'secret' }, { + invoke: async () => { throw new Error('permission denied') }, + confirm: async () => false, + copy: async (text) => { copied.push(text) }, + }), /permission denied/) + assert.deepEqual(copied, ['first\nsecond']) +}) + +test('other plugin bridge methods pass through without UI interception', async () => { + const result = await invokePluginViewAction('storage.list', {}, { + invoke: async (method) => ({ keys: method === 'storage.list' ? ['draft'] : [] }), + confirm: async () => { throw new Error('unexpected confirmation') }, + copy: async () => { throw new Error('unexpected copy') }, + }) + assert.deepEqual(result, { keys: ['draft'] }) +}) + +test('plugin view router preserves return state, handles dialogs, and prunes disabled views', () => { + const sidebar = { pluginId: 'vendor.tool', viewId: 'console', location: 'sidebar' } + const settings = { pluginId: 'vendor.tool', viewId: 'settings', location: 'settings' } + const tab = { pluginId: 'vendor.tool', viewId: 'metrics', location: 'vm.tab', vm: 'builtin.macos:mac' } + const dialog = { pluginId: 'vendor.tool', viewId: 'editor', location: 'dialog' } + let state = openPluginView(emptyPluginViewState, sidebar) + state = openPluginView(state, sidebar) + assert.equal(state.returnStack.length, 0, 'duplicate open must not push history') + state = openPluginView(state, settings) + assert.equal(state.route.viewId, 'settings') + assert.equal(state.returnStack.length, 1) + state = closePluginView(state).state + assert.equal(state.route.viewId, 'console') + state = openPluginView(state, tab) + state = closePluginView(state).state + assert.equal(state.route, null, 'VM tab closes to overview') + state = openPluginView(state, dialog) + state = openPluginView(state, dialog) + assert.equal(state.dialogs.length, 1, 'duplicate dialog only focuses the existing one') + state = closePluginView(state).state + assert.equal(state.dialogs.length, 0) + state = openPluginView(state, sidebar) + state = prunePluginViews(state, new Set(), () => false) + assert.deepEqual(state, emptyPluginViewState) +}) + +test('plugin event bus delivers only while subscribed', () => { + const received = [] + const off = subscribePluginHostEvents((event, data) => { received.push([event, data]) }) + publishPluginHostEvent('task.updated', { id: 'task-1' }) + off() + publishPluginHostEvent('task.updated', { id: 'task-2' }) + assert.deepEqual(received, [['task.updated', { id: 'task-1' }]]) +}) + +test('plugin form, metadata, navigation, and subscriptions execute after host validation', async () => { + const steps = [] + const view = { id: 'editor', pluginId: 'vendor.tool', location: 'dialog', title: 'Editor', entry: 'index.html' } + const handlers = { + invoke: async (method) => { + steps.push(['invoke', method]) + if (method === 'ui.showForm') return { title: 'Edit', schema: { properties: {} }, values: { name: 'demo' } } + if (method === 'ui.openView') return view + if (method === 'ui.setTitle') return { title: 'Live' } + if (method === 'ui.setBadge') return { text: '2', tone: 'warn' } + if (method.startsWith('events.')) return { events: method === 'events.unsubscribe' ? [] : ['task.updated'] } + if (method === 'ui.navigate') return { page: 'settings' } + return { ok: true } + }, + confirm: async () => { throw new Error('unexpected confirmation') }, + showForm: async (request) => { steps.push(['form', request.values.name]); return { confirmed: true, values: request.values } }, + copy: async () => { throw new Error('unexpected copy') }, + setTitle: (title) => { steps.push(['title', title]) }, + setBadge: (text, tone) => { steps.push(['badge', text, tone]) }, + openView: (opened, vm) => { steps.push(['open', opened.id, vm]) }, + close: async () => ({ closed: true }), + navigate: (target) => { steps.push(['navigate', target.page]) }, + subscribe: (events) => { steps.push(['subscribe', ...events]) }, + unsubscribe: (events) => { steps.push(['unsubscribe', events.length]) }, + } + assert.deepEqual(await invokePluginViewAction('ui.showForm', {}, handlers), { confirmed: true, values: { name: 'demo' } }) + assert.deepEqual(await invokePluginViewAction('ui.openView', { vm: 'vm-1' }, handlers), { ok: true }) + assert.deepEqual(await invokePluginViewAction('ui.setTitle', {}, handlers), { title: 'Live' }) + assert.deepEqual(await invokePluginViewAction('ui.setBadge', {}, handlers), { text: '2', tone: 'warn' }) + assert.deepEqual(await invokePluginViewAction('events.subscribe', {}, handlers), { events: ['task.updated'] }) + assert.deepEqual(await invokePluginViewAction('events.unsubscribe', {}, handlers), { events: [] }) + assert.deepEqual(await invokePluginViewAction('ui.navigate', {}, handlers), { ok: true }) + assert.deepEqual(steps, [ + ['invoke', 'ui.showForm'], ['form', 'demo'], + ['invoke', 'ui.openView'], ['open', 'editor', 'vm-1'], + ['invoke', 'ui.setTitle'], ['title', 'Live'], + ['invoke', 'ui.setBadge'], ['badge', '2', 'warn'], + ['invoke', 'events.subscribe'], ['subscribe', 'task.updated'], + ['invoke', 'events.unsubscribe'], ['unsubscribe', 0], + ['invoke', 'ui.navigate'], ['navigate', 'settings'], + ]) +}) + +test('closing a plugin view restores the page it was opened from', () => { + const sidebar = { pluginId: 'vendor.tool', viewId: 'console', location: 'sidebar', from: 'host' } + const tab = { pluginId: 'vendor.tool', viewId: 'metrics', location: 'vm.tab', vm: 'builtin.macos:mac', from: 'builtin.macos:mac' } + const settings = { pluginId: 'vendor.tool', viewId: 'settings', location: 'settings', from: 'builtin.macos:mac' } + + const back = closePluginView(openPluginView(openPluginView(emptyPluginViewState, tab), settings)) + assert.equal(back.state.route.viewId, 'metrics') + assert.equal(back.page, 'builtin.macos:mac', 'the VM must be selected again under its tab') + + let state = openPluginView(openPluginView(emptyPluginViewState, { ...tab, viewId: 'other' }), tab) + state = closePluginView(state).state + state = closePluginView(openPluginView(state, sidebar)).state + assert.equal(state.route, null, 'a tab left through Overview must not reopen') +}) + +test('reopening a plugin dialog returns to it and keeps the ones below', () => { + const dialog = (viewId) => ({ pluginId: 'vendor.tool', viewId, location: 'dialog' }) + let state = ['a', 'b', 'c'].reduce((current, id) => openPluginView(current, dialog(id)), emptyPluginViewState) + state = openPluginView(state, dialog('b')) + assert.deepEqual(state.dialogs.map((item) => item.viewId), ['a', 'b']) +}) + +test('view conditions match the state they name', () => { + assert.equal(matchViewCondition(undefined, {}), true) + assert.equal(matchViewCondition('default', {}), true) + assert.equal(matchViewCondition('vmState == running', { vmState: 'running' }), true) + assert.equal(matchViewCondition('vmState==running', { vmState: 'stopped' }), false) + assert.equal(matchViewCondition('unknown', {}), false) +}) + +test('plugin forms start from the displayed values and report empty required fields', () => { + const schema = { properties: { + mode: { type: 'string', enum: ['dev', 'prod'] }, + count: { type: 'integer', minimum: 2 }, + enabled: { type: 'boolean' }, + label: { type: 'string', default: 'x' }, + name: { type: 'string', required: true }, + } } + const values = initialFormValues(schema, { label: 'given' }) + assert.deepEqual(values, { mode: 'dev', count: 2, enabled: false, label: 'given', name: '' }) + assert.deepEqual(missingFormFields(schema, values), ['name']) + assert.deepEqual(missingFormFields(schema, { ...values, name: 'demo' }), []) +}) + +test('closing a plugin page cancels only its unfinished tasks', async () => { + const canceled = [] + let next = 0 + const scope = createPluginTaskScope(async (method, params) => { + if (method === 'task.start') return { id: `task-${++next}` } + if (params.status === 'canceled') canceled.push(params.id) + return {} + }) + await scope.invoke('task.start', {}) + await scope.invoke('task.start', {}) + await scope.invoke('task.finish', { id: 'task-1' }) + const late = scope.invoke('task.start', {}) + scope.close() + await late + assert.deepEqual(canceled, ['task-2', 'task-3']) +}) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 868e486..f9ba677 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -11,6 +11,8 @@ import { TitleMenus } from './components/TitleMenus' import { UpdateCapsule, UpdatePhase } from './components/UpdateCapsule' import { DataRootReadOnly } from './components/DataRootReadOnly' import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar' +import { PluginViewHost } from './components/PluginViewHost' +import { locText } from './components/SchemaForm' import { VMAction, VMBusyAction, VMPage } from './components/VMPage' import { buildFallbackChain, I18nKey, localeDir, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n' import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format' @@ -21,7 +23,10 @@ import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFo import { hasVisibleDialog } from './lib/dialogState' import { latestVMStatsWithDriver, refreshSubscribedVMStats, refreshVMStatsWithDriver } from './lib/vmStats' import { vmRefKey } from './lib/vmRef' -import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail } from './types' +import { closePluginView, emptyPluginViewState, matchViewCondition, openPluginView, pluginViewKey, prunePluginViews, type PluginViewRoute, type PluginViewState } from './lib/pluginViewRouter' +import { publishPluginHostEvent } from './lib/pluginViewEvents' +import { buildSafePluginAssetURL } from './lib/pluginAssets' +import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail, ViewContribution } from './types' import { Button, Tip, TooltipProvider } from './ui/controls' import { ConfirmDialog, Modal } from './ui/dialog' import { Toaster, useToasts } from './ui/toast' @@ -74,7 +79,7 @@ const failKey: Record = { export const App: React.FC = () => { const [state, setState] = useState(null) - const [selected, setSelected] = useState(HOST_ID) + const [selected, setSelectedPage] = useState(HOST_ID) const [appUpdate, setAppUpdate] = useState(null) // Check for a new release once the app is up, then every 6 hours, so the // sidebar's update button shows up without opening the About page. @@ -119,6 +124,13 @@ export const App: React.FC = () => { typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches, ) const [pluginUI, setPluginUI] = useState(null) + const [pluginViewState, setPluginViewState] = useState(emptyPluginViewState) + const [pluginViewMeta, setPluginViewMeta] = useState>({}) + // Host navigation always leaves plugin views, even when the target page is already selected underneath. + const setSelected = useCallback((id: string) => { + setPluginViewState(emptyPluginViewState) + setSelectedPage(id) + }, []) const [activeThemePayload, setActiveThemePayload] = useState(null) const [themeRevision, setThemeRevision] = useState(0) @@ -206,7 +218,7 @@ export const App: React.FC = () => { const s = await api.GetState() setState(s) setLoadError('') - setSelected((cur) => { + setSelectedPage((cur) => { if (PAGE_IDS.includes(cur)) return cur if ((s.vms ?? []).some((v) => vmRefKey(v) === cur || v.name === cur)) return cur return s.vms && s.vms.length > 0 ? vmRefKey(s.vms[0]) : HOST_ID @@ -272,6 +284,97 @@ export const App: React.FC = () => { ? vms.find((v) => vmRefKey(v) === selected) ?? vms.find((v) => v.name === selected) : undefined + const pluginViews = pluginUI?.views ?? [] + const findVM = (ref: string) => vms.find((item) => vmRefKey(item) === ref || item.name === ref) + const viewAvailable = (view: ViewContribution, vmRef?: string) => { + const vm = vmRef ? findVM(vmRef) : selectedVM + return matchViewCondition(view.when, { vmState: vm ? state?.transitions[vmRefKey(vm)] ?? vm.state : '', theme }) + } + const openView = (view: ViewContribution, targetVM?: string) => { + const route: PluginViewRoute = { pluginId: view.pluginId ?? '', viewId: view.id, location: view.location as PluginViewRoute['location'], vm: targetVM, from: selected } + if (view.location === 'vm.tab') { + const target = findVM(targetVM || (selectedVM ? vmRefKey(selectedVM) : '')) + if (!target) throw new Error('A valid VM is required for this view') + route.vm = vmRefKey(target) + } + if (!viewAvailable(view, route.vm)) throw new Error('This view is not available in the current state') + if (view.location === 'vm.tab') setSelectedPage(route.vm!) + else if (view.location === 'settings') setSelectedPage(SETTINGS_ID) + setPluginViewState((current) => openPluginView(current, route)) + } + const closeView = () => { + const result = closePluginView(pluginViewState) + setPluginViewState(result.state) + if (result.page && (PAGE_IDS.includes(result.page) || findVM(result.page))) setSelectedPage(result.page) + return { closed: result.closed } + } + const navigateHost = (target: { page?: string; vm?: string }) => { + if (target.vm) { + const vm = findVM(target.vm) + if (!vm) throw new Error(`Unknown VM: ${target.vm}`) + setSelected(vmRefKey(vm)) + return + } + const pages: Record = { host: HOST_ID, images: INSTALLERS_ID, plugins: PLUGINS_ID, settings: SETTINGS_ID, about: ABOUT_ID } + const page = pages[target.page ?? ''] + if (!page) throw new Error(`Unknown page: ${target.page}`) + setSelected(page) + } + const updateViewMetadata = (view: ViewContribution, metadata: { title?: string; badge?: { text: string; tone: string } }) => { + const key = pluginViewKey({ pluginId: view.pluginId ?? '', viewId: view.id }) + setPluginViewMeta((current) => ({ ...current, [key]: { ...current[key], ...metadata } })) + } + useEffect(() => { + const valid = new Set(pluginViews.map((view) => pluginViewKey({ pluginId: view.pluginId ?? '', viewId: view.id }))) + setPluginViewState((current) => prunePluginViews(current, valid, (vm) => !!vm && vms.some((item) => vmRefKey(item) === vm))) + setPluginViewMeta((current) => Object.fromEntries(Object.entries(current).filter(([key]) => valid.has(key)))) + }, [pluginUI?.views, state?.vms]) + const findRouteView = (route: PluginViewRoute) => + pluginViews.find((view) => (view.pluginId ?? '') === route.pluginId && view.id === route.viewId && view.location === route.location) + const routedView = pluginViewState.route ? findRouteView(pluginViewState.route) : undefined + const activePluginView = routedView && viewAvailable(routedView, pluginViewState.route?.vm) ? routedView : undefined + const activePluginRoute = activePluginView ? pluginViewState.route : null + const renderPluginView = (route: PluginViewRoute, view: ViewContribution, dialog = false) => ( + updateViewMetadata(view, metadata)} + onOpenView={openView} + onCloseView={closeView} + onNavigate={navigateHost} + /> + ) + const renderVMTabs = () => { + if (!selectedVM) return null + const tabs = pluginViews.filter((view) => view.location === 'vm.tab' && viewAvailable(view)) + if (tabs.length === 0) return null + return ( +
+ + {tabs.map((view) => { + const key = pluginViewKey({ pluginId: view.pluginId ?? '', viewId: view.id }) + const selectedTab = activePluginRoute?.location === 'vm.tab' && pluginViewKey(activePluginRoute) === key + const badge = pluginViewMeta[key]?.badge + return ( + + ) + })} +
+ ) + } + + const sidebarSelected = activePluginRoute?.location === 'sidebar' ? `__plugin_view__:${pluginViewKey(activePluginRoute)}` : selected + useEffect(() => { if (!selectedVM) { setDetail(null); return } api.GetVMDetail(selectedVM.name).then(setDetail).catch(() => setDetail(null)) @@ -318,6 +421,15 @@ export const App: React.FC = () => { } const locale: Locale = resolveActiveLocale(state?.config.locale, pluginUI?.locales, state?.detected_locale) const dir = localeDir(locale) + const settingsPluginViews = pluginViews.filter((view) => view.location === 'settings' && viewAvailable(view)).map((view) => { + const key = pluginViewKey({ pluginId: view.pluginId ?? '', viewId: view.id }) + return { id: key, title: locText(view.title, locale, view.id), badge: pluginViewMeta[key]?.badge?.text, onOpen: () => openView(view) } + }) + const sidebarPluginViews = pluginViews.filter((view) => view.location === 'sidebar' && viewAvailable(view)).map((view) => { + const key = pluginViewKey({ pluginId: view.pluginId ?? '', viewId: view.id }) + const icon = view.icon ? buildSafePluginAssetURL(pluginUI?.asset_token ?? '', view.pluginId, view.icon) ?? undefined : undefined + return { id: `__plugin_view__:${key}`, view, title: locText(view.title, locale, view.id), badge: pluginViewMeta[key]?.badge?.text, icon } + }) useEffect(() => { const html = document.documentElement html.lang = locale === 'en-XA' ? 'en' : locale @@ -348,6 +460,7 @@ export const App: React.FC = () => { const canSuspend = state?.can_suspend ?? false onTaskRef.current = (task: Task) => { + publishPluginHostEvent('task.updated', task) if (task.kind === 'app-update' && task.status === 'failed' && !notifiedTasks.current.has(task.id)) { notifiedTasks.current.set(task.id, task.updated_at) fail(tr('updateFailed'), task.error ?? '') @@ -468,7 +581,7 @@ export const App: React.FC = () => { const showReadOnly = !!state && !showSetup && !!state.data_root_status?.read_only // UI Contract v2 read-only document state attributes. - const currentView = showSetup ? 'setup' : selected === HOST_ID ? 'host' : selected === INSTALLERS_ID ? 'installers' : selected === PLUGINS_ID ? 'plugins' : selected === SETTINGS_ID ? 'settings' : selected === ABOUT_ID ? 'about' : 'vm' + const currentView = showSetup ? 'setup' : activePluginRoute?.location === 'sidebar' ? 'plugins' : activePluginRoute?.location === 'settings' ? 'settings' : activePluginRoute?.location === 'vm.tab' ? 'vm' : selected === HOST_ID ? 'host' : selected === INSTALLERS_ID ? 'installers' : selected === PLUGINS_ID ? 'plugins' : selected === SETTINGS_ID ? 'settings' : selected === ABOUT_ID ? 'about' : 'vm' const isBusyAny = Object.keys(busy).length > 0 || runningTasks > 0 const hasAnyError = unseenErrors > 0 || !!loadError const uiStateRef = useRef({ @@ -526,7 +639,9 @@ export const App: React.FC = () => { for (const v of vms) { const key = vmRefKey(v) if (prev[key] !== undefined && prev[key] !== next[key]) { - emitThemeEvent('vm.stateChanged', { vm: key, name: v.name, driver: v.driver_id ?? '', from: prev[key], to: next[key] }) + const payload = { vm: key, name: v.name, driver: v.driver_id ?? '', from: prev[key], to: next[key] } + emitThemeEvent('vm.stateChanged', payload) + publishPluginHostEvent('vm.stateChanged', payload) } } }, [vms, state?.transitions]) @@ -1144,11 +1259,16 @@ export const App: React.FC = () => { vms={vms} transitions={state?.transitions ?? {}} busyActions={busy} - selected={selected} + selected={sidebarSelected} hostReady={hostReady} canSuspend={canSuspend} onSelect={(id) => { - setSelected(id) + if (id.startsWith('__plugin_view__:')) { + const item = sidebarPluginViews.find((entry) => entry.id === id) + if (item) openView(item.view) + } else { + setSelected(id) + } if (sidebarOpen && window.matchMedia('(max-width: 768px)').matches) { toggleSidebar() } @@ -1161,6 +1281,7 @@ export const App: React.FC = () => { downloading={Object.values(taskMap).some(isActiveInstallerTask)} safeMode={state?.safe_mode} updateDot={!!appUpdate?.has_update} + pluginViews={sidebarPluginViews} updateCard={showUpdateCard ? ( {
{loadError ?
{loadError}
: …}
+ ) : activePluginRoute && activePluginView ? ( + <> + {activePluginRoute.location === 'vm.tab' && renderVMTabs()} + {renderPluginView(activePluginRoute, activePluginView)} + ) : selected === INSTALLERS_ID ? ( { onError={fail} onThemeChanged={() => setThemeRevision((r) => r + 1)} onLocaleSwitch={(l) => void setLang(l)} + onOpenView={openView} + onNavigate={navigateHost} /> ) : selectedVM ? ( - + {renderVMTabs()} + { onError={fail} dropping={dropping} pluginUI={pluginUI} - /> + /> + ) : selected === SETTINGS_ID ? ( { themeMode={effectiveThemeMode} canLight={canLight} canDark={canDark} + pluginViews={settingsPluginViews} onThemeMode={setThemeMode} onSetLocale={setLang} onRefresh={refresh} @@ -1491,6 +1623,12 @@ export const App: React.FC = () => { /> )} + {/* Every open dialog stays mounted so the ones underneath keep their state. */} + {pluginViewState.dialogs.map((route) => { + const view = findRouteView(route) + return view && renderPluginView(route, view, true) + })} + {/* Outside the isolated shell so toasts stay above dialogs and the overlay layer. */} diff --git a/frontend/src/components/AppSettingsPage.tsx b/frontend/src/components/AppSettingsPage.tsx index 30f2954..f97665b 100644 --- a/frontend/src/components/AppSettingsPage.tsx +++ b/frontend/src/components/AppSettingsPage.tsx @@ -53,6 +53,8 @@ interface Props { themeMode: ThemeMode canLight?: boolean canDark?: boolean + /** Plugin views declared for this page. */ + pluginViews?: { id: string; title: string; badge?: string; onOpen: () => void }[] onThemeMode: (mode: ThemeMode) => void onSetLocale: (l: Locale) => void onRefresh: () => void @@ -60,7 +62,7 @@ interface Props { } export const AppSettingsPage: React.FC = ({ - state, locale, locales, themeMode, canLight = true, canDark = true, onThemeMode, onSetLocale, onRefresh, onError, + state, locale, locales, themeMode, canLight = true, canDark = true, pluginViews = [], onThemeMode, onSetLocale, onRefresh, onError, }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const { host, config, optimizations } = state @@ -486,6 +488,27 @@ export const AppSettingsPage: React.FC = ({
+ + {pluginViews.length > 0 && ( +
+
{tr('sidebarPlugins')}
+
+ {pluginViews.map((view) => ( +
+
+
+ {view.title} + {view.badge && {view.badge}} +
+
+
+ +
+
+ ))} +
+
+ )} ) } diff --git a/frontend/src/components/PluginPanelFrame.tsx b/frontend/src/components/PluginPanelFrame.tsx index 0937e5a..b645c52 100644 --- a/frontend/src/components/PluginPanelFrame.tsx +++ b/frontend/src/components/PluginPanelFrame.tsx @@ -1,10 +1,18 @@ import { AlertTriangle } from 'lucide-react' import React, { useEffect, useRef, useState } from 'react' import { getPluginMessageBundle, localeDir, parseAppError, t } from '../i18n' -import { Locale, PanelContribution } from '../types' +import { Locale, PanelContribution, ViewContribution } from '../types' import { Button } from '../ui/controls' +import { ConfirmDialog } from '../ui/dialog' import { api } from '../wails' -import { locText } from './SchemaForm' +import { ClipboardSetText } from '../../wailsjs/runtime/runtime' +import { + createPluginTaskScope, initialFormValues, invokePluginViewAction, missingFormFields, + PluginConfirmRequest, PluginFormRequest, PluginFormResult, +} from '../lib/pluginViewActions' +import { buildSafePluginAssetURL } from '../lib/pluginAssets' +import { subscribePluginHostEvents } from '../lib/pluginViewEvents' +import { locText, SchemaForm } from './SchemaForm' interface Props { locale: Locale @@ -15,40 +23,130 @@ interface Props { headless?: boolean /** Upper bound for the iframe height in px (defaults to 480 for inline panels). */ maxHeight?: number + /** Narrower containers scroll horizontally instead of shrinking the page below this width. */ + minWidth?: number /** Incrementing this reloads the iframe cleanly. */ refreshSignal?: number + viewLocation?: ViewContribution['location'] + vm?: string + onOpenView?: (view: ViewContribution, vm?: string) => void + onCloseView?: () => { closed: boolean } + onNavigate?: (target: { page?: string; vm?: string }) => void + onMetadata?: (metadata: { title?: string; badge?: { text: string; tone: string } }) => void } -/** - * Sandboxed L4 iframe panel verifying window identity (`event.source === iframe.contentWindow` - * and opaque `null` origin) and routing Host API calls through `PanelBridgeCall`. - */ -const RE_SAFE_TOKEN = /^[a-f0-9]+$/ -const RE_SAFE_PLUGIN_ID = /^[a-z0-9][a-z0-9._-]*$/ -const RE_SAFE_ENTRY_SEG = /^[a-zA-Z0-9._@ -]+$/ - -function buildSafePanelSrc(assetToken: string, pluginId: string | undefined, entry: string | undefined): string | null { - if (!assetToken || !RE_SAFE_TOKEN.test(assetToken)) return null - if (!pluginId || !RE_SAFE_PLUGIN_ID.test(pluginId) || pluginId.includes('..')) return null - const raw = (entry || 'index.html').trim().replace(/^\/+/, '') - if (!raw || raw.includes('\\') || raw.includes('?') || raw.includes('#') || /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(raw)) { - return null - } - const segs = raw.split('/') - for (const seg of segs) { - if (!seg || seg === '.' || seg === '..' || !RE_SAFE_ENTRY_SEG.test(seg)) return null - } - return `/plugin-assets/${encodeURIComponent(assetToken)}/${encodeURIComponent(pluginId)}/${segs.map(encodeURIComponent).join('/')}` -} - +/** Sandboxed plugin frame with identity-checked host RPC and local UI effects. */ export const PluginPanelFrame: React.FC = ({ - locale, panel, assetToken, appearance, headless, maxHeight = 480, refreshSignal = 0, + locale, panel, assetToken, appearance, headless, maxHeight = 480, minWidth, refreshSignal = 0, + viewLocation, vm, onOpenView, onCloseView, onNavigate, onMetadata, }) => { const iframeRef = useRef(null) + const wrapperRef = useRef(null) const localeRef = useRef(locale) localeRef.current = locale const [failed, setFailed] = useState(false) const [nonce, setNonce] = useState(0) + const [titleOverride, setTitleOverride] = useState(null) + const [badge, setBadge] = useState<{ text: string; tone: string } | null>(null) + const metadataRef = useRef<{ title?: string; badge?: { text: string; tone: string } }>({}) + const actionContextRef = useRef({ vm, onOpenView, onCloseView, onNavigate, onMetadata }) + actionContextRef.current = { vm, onOpenView, onCloseView, onNavigate, onMetadata } + const [confirmRequest, setConfirmRequest] = useState(null) + const confirmResolverRef = useRef<((confirmed: boolean) => void) | null>(null) + const [formRequest, setFormRequest] = useState(null) + const [formError, setFormError] = useState('') + const formResolverRef = useRef<((result: PluginFormResult) => void) | null>(null) + const subscriptionsRef = useRef>(new Set()) + const intersectingRef = useRef(true) + const lastVisibilityRef = useRef(null) + + const src = buildSafePluginAssetURL(assetToken, panel.pluginId, panel.entry) + const title = titleOverride || locText(panel.title, locale, panel.id) + + const updateMetadata = (patch: { title?: string; badge?: { text: string; tone: string } }) => { + metadataRef.current = { ...metadataRef.current, ...patch } + if (patch.title !== undefined) setTitleOverride(patch.title) + if ('badge' in patch) setBadge(patch.badge ?? null) + actionContextRef.current.onMetadata?.(metadataRef.current) + } + + const finishConfirmation = (confirmed: boolean) => { + const resolve = confirmResolverRef.current + confirmResolverRef.current = null + setConfirmRequest(null) + resolve?.(confirmed) + } + + const requestConfirmation = (request: PluginConfirmRequest) => new Promise((resolve, reject) => { + if (confirmResolverRef.current || formResolverRef.current) { + reject(new Error('A plugin dialog is already pending')) + return + } + confirmResolverRef.current = resolve + setConfirmRequest(request) + }) + + const finishForm = (confirmed: boolean) => { + const resolve = formResolverRef.current + formResolverRef.current = null + const values = formRequest?.values + setFormRequest(null) + resolve?.(confirmed ? { confirmed: true, values } : { confirmed: false }) + } + + const requestForm = (request: PluginFormRequest) => new Promise((resolve, reject) => { + if (confirmResolverRef.current || formResolverRef.current) { + reject(new Error('A plugin dialog is already pending')) + return + } + formResolverRef.current = resolve + setFormError('') + setFormRequest({ ...request, values: initialFormValues(request.schema, request.values) }) + }) + + const submitForm = (e: React.MouseEvent, request: PluginFormRequest) => { + const missing = missingFormFields(request.schema, request.values) + if (missing.length === 0) { + finishForm(true) + return + } + e.preventDefault() + const fields = missing.map((key) => locText(request.schema.properties?.[key]?.title, locale, key)).join(', ') + setFormError(t(locale, 'formRequiredFields', { fields })) + } + + const emitVisibility = (reason: string, force = false) => { + const visible = !document.hidden && intersectingRef.current + if (!force && lastVisibilityRef.current === visible) return + lastVisibilityRef.current = visible + if (!subscriptionsRef.current.has('view.visibilityChanged')) return + iframeRef.current?.contentWindow?.postMessage({ + type: 'reims:event', event: 'view.visibilityChanged', data: { visible, reason }, + }, '*') + } + + const subscribe = (events: string[]) => { + for (const event of events) subscriptionsRef.current.add(event) + if (events.includes('view.visibilityChanged')) emitVisibility('subscribe', true) + } + + const unsubscribe = (events: string[]) => { + if (events.length === 0) subscriptionsRef.current.clear() + else for (const event of events) subscriptionsRef.current.delete(event) + } + + useEffect(() => { + setConfirmRequest(null) + setFormRequest(null) + subscriptionsRef.current.clear() + lastVisibilityRef.current = null + return () => { + confirmResolverRef.current?.(false) + confirmResolverRef.current = null + formResolverRef.current?.({ confirmed: false }) + formResolverRef.current = null + } + }, [src, nonce]) useEffect(() => { if (refreshSignal > 0) { @@ -57,7 +155,30 @@ export const PluginPanelFrame: React.FC = ({ } }, [refreshSignal]) - const src = buildSafePanelSrc(assetToken, panel.pluginId, panel.entry) + useEffect(() => { + const onVisibility = () => emitVisibility('document') + document.addEventListener('visibilitychange', onVisibility) + const observer = typeof IntersectionObserver === 'undefined' ? null : new IntersectionObserver((entries) => { + intersectingRef.current = entries[0]?.isIntersecting ?? true + emitVisibility('viewport') + }) + if (wrapperRef.current) observer?.observe(wrapperRef.current) + emitVisibility('mount', true) + return () => { + document.removeEventListener('visibilitychange', onVisibility) + observer?.disconnect() + subscriptionsRef.current.clear() + } + }, [src, nonce]) + + useEffect(() => subscribePluginHostEvents((event, data) => { + if (!subscriptionsRef.current.has(event)) return + if (event === 'task.updated') { + const task = data as { kind?: string } + if (task.kind !== `plugin:${panel.pluginId}`) return + } + iframeRef.current?.contentWindow?.postMessage({ type: 'reims:event', event, data }, '*') + }), [panel.pluginId, nonce, src]) const syncTheme = () => { const win = iframeRef.current?.contentWindow @@ -69,10 +190,8 @@ export const PluginPanelFrame: React.FC = ({ } const dir = localeDir(locale) const messages = getPluginMessageBundle(panel.pluginId ?? '', locale) - // bridgeApi 1.0 events (bridgeContract.ts). win.postMessage({ type: 'reims:event', event: 'theme.changed', data: { appearance, tokens } }, '*') win.postMessage({ type: 'reims:event', event: 'locale.changed', data: { locale, dir, messages } }, '*') - // Pre-1.0 message types, kept for panels written before the bridge contract. win.postMessage({ type: 'reims:theme', appearance, locale, dir, tokens, messages }, '*') win.postMessage({ type: 'reims:i18n', locale, dir, messages }, '*') } @@ -85,30 +204,48 @@ export const PluginPanelFrame: React.FC = ({ useEffect(() => { if (!src) return let cancelled = false - + const taskScope = createPluginTaskScope((method, input) => api.PanelBridgeCall(panel.pluginId ?? '', method, input)) const onMessage = async (e: MessageEvent) => { const win = iframeRef.current?.contentWindow - // Require opaque origin and exact contentWindow identity for sandbox="allow-scripts". if (!win || e.source !== win || e.origin !== 'null') return const msg = e.data if (!msg || typeof msg !== 'object' || msg.type !== 'reims:rpc' || typeof msg.id !== 'string' || typeof msg.method !== 'string') return const rawParams = msg.params - const params: Record = - rawParams && typeof rawParams === 'object' && !Array.isArray(rawParams) - ? (rawParams as Record) - : {} + const params: Record = rawParams && typeof rawParams === 'object' && !Array.isArray(rawParams) ? rawParams : {} try { if (msg.method === 'i18n.getBundle') { const curLocale = localeRef.current - const bundle = { - locale: curLocale, - dir: localeDir(curLocale), - messages: getPluginMessageBundle(panel.pluginId ?? '', curLocale), - } + const bundle = { locale: curLocale, dir: localeDir(curLocale), messages: getPluginMessageBundle(panel.pluginId ?? '', curLocale) } win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: true, result: bundle }, '*') return } - const result = await api.PanelBridgeCall(panel.pluginId ?? '', msg.method, params) + const result = await invokePluginViewAction(msg.method, params, { + invoke: taskScope.invoke, + confirm: requestConfirmation, + showForm: requestForm, + copy: async (text) => { + if (!await ClipboardSetText(text)) throw new Error('The clipboard is unavailable') + }, + setTitle: (nextTitle) => updateMetadata({ title: nextTitle }), + setBadge: (text, tone) => updateMetadata({ badge: text ? { text, tone } : undefined }), + openView: (view, targetVM) => { + const context = actionContextRef.current + if (!context.onOpenView) throw new Error('not_supported') + context.onOpenView(view, targetVM ?? context.vm) + }, + close: async () => { + const context = actionContextRef.current + if (!context.onCloseView) throw new Error('not_supported') + return context.onCloseView() + }, + navigate: (target) => { + const context = actionContextRef.current + if (!context.onNavigate) throw new Error('not_supported') + context.onNavigate(target) + }, + subscribe, + unsubscribe, + }) if (cancelled || iframeRef.current?.contentWindow !== win) return win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: true, result }, '*') } catch (err) { @@ -116,10 +253,10 @@ export const PluginPanelFrame: React.FC = ({ win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: false, error: parseAppError(err).summary || 'RPC failed' }, '*') } } - window.addEventListener('message', onMessage) return () => { cancelled = true + taskScope.close() window.removeEventListener('message', onMessage) } }, [panel.pluginId, nonce, src]) @@ -131,30 +268,65 @@ export const PluginPanelFrame: React.FC = ({