Files
Reims-Go/frontend/src/components/AppSettingsPage.tsx
T
Dnyo666 ff99d8d702 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
2026-12-03 13:39:08 +08:00

628 lines
24 KiB
TypeScript

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, 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'
export type ThemeMode = 'light' | 'dark' | 'system'
type HostDNSMode = 'system' | 'doh'
const DEFAULT_DOH_URL = 'https://dns.alidns.com/dns-query'
const CUSTOM_DOH_VALUE = '__custom__'
const DOH_PRESETS: ReadonlyArray<{ url: string; labelKey: I18nKey; host: string }> = [
{ url: 'https://dns.alidns.com/dns-query', labelKey: 'hostDNSPresetAliDNS', host: 'dns.alidns.com' },
{ url: 'https://doh.pub/dns-query', labelKey: 'hostDNSPresetDNSPod', host: 'doh.pub' },
{ url: 'https://cloudflare-dns.com/dns-query', labelKey: 'hostDNSPresetCloudflare', host: 'cloudflare-dns.com' },
{ url: 'https://dns.google/dns-query', labelKey: 'hostDNSPresetGoogle', host: 'dns.google' },
]
function normalizeHostDNSMode(mode?: string): HostDNSMode {
return mode === 'doh' ? 'doh' : 'system'
}
function normalizeDoHURL(url?: string): string {
const trimmed = url?.trim() ?? ''
return trimmed || DEFAULT_DOH_URL
}
function isPresetDoHURL(url: string): boolean {
return DOH_PRESETS.some((p) => p.url === url)
}
function isValidDoHURL(raw: string): boolean {
const trimmed = raw.trim()
if (!trimmed.startsWith('https://')) return false
try {
const parsed = new URL(trimmed)
return parsed.protocol === 'https:' && Boolean(parsed.hostname) && !parsed.username && !parsed.password && !parsed.hash
} catch {
return false
}
}
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<Props> = ({
state, locale, locales, tasks, themeMode, canLight = true, canDark = true, onThemeMode, onSetLocale, onRefresh, onToast, onError,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const { host, config, optimizations } = state
const quitMode = state.quit_mode
const [savedDnsMode, setSavedDnsMode] = useState<HostDNSMode>(() => normalizeHostDNSMode(config.host_dns_mode))
const [savedDohUrl, setSavedDohUrl] = useState<string>(() => normalizeDoHURL(config.host_dns_doh_url))
const [dnsMode, setDnsMode] = useState<HostDNSMode>(() => normalizeHostDNSMode(config.host_dns_mode))
const [dohUrl, setDohUrl] = useState<string>(() => normalizeDoHURL(config.host_dns_doh_url))
const [dohCustom, setDohCustom] = useState<boolean>(() => !isPresetDoHURL(normalizeDoHURL(config.host_dns_doh_url)))
const [dohDraft, setDohDraft] = useState<string>(() => normalizeDoHURL(config.host_dns_doh_url))
const [dnsSaving, setDnsSaving] = useState(false)
const [dnsSavedHint, setDnsSavedHint] = useState(false)
const [dnsValidationErr, setDnsValidationErr] = useState('')
const [dnsTesting, setDnsTesting] = useState(false)
const [dnsTestResult, setDnsTestResult] = useState<
| { ok: true; domain: string; addresses: string[]; elapsedMs: number }
| { ok: false; reason: string }
| null
>(null)
const dnsEditSeq = useRef(0)
const dnsTestSeq = useRef(0)
useEffect(() => {
let live = true
const seq = ++dnsEditSeq.current
dnsTestSeq.current += 1
setDnsValidationErr('')
setDnsSavedHint(false)
setDnsTestResult(null)
setDnsTesting(false)
setDnsSaving(false)
api.GetHostDNSConfig()
.then((cfg) => {
if (!live || !cfg || dnsEditSeq.current !== seq) return
const mode = normalizeHostDNSMode(cfg.mode)
const url = normalizeDoHURL(cfg.doh_url)
setSavedDnsMode(mode)
setSavedDohUrl(url)
setDnsMode(mode)
setDohUrl(url)
setDohDraft(url)
setDohCustom(!isPresetDoHURL(url))
})
.catch((e) => console.warn('[settings] GetHostDNSConfig failed:', e))
return () => { live = false }
}, [config.data_root])
const pcoreOpt = findOptimization(optimizations, 'pcore_pin')
const missingFontScript = state.missing_font_hint || ''
const memSpecLabel = host.memory_spec?.speed_mhz
? `${host.memory_spec.speed_mhz} MHz${host.memory_spec.type_name ? ` ${host.memory_spec.type_name}` : ''}`
: ''
const guard = (fn: () => Promise<unknown>) => async () => {
try {
await fn()
onRefresh()
} catch (e) {
onError(tr('failGeneric'), e)
}
}
const pickDataRoot = guard(async () => {
const dir = await api.PickDirectory(tr('hostDataRoot'))
if (dir) await api.SetDataRoot(dir)
})
const saveHostDNS = async (nextMode: HostDNSMode, nextUrl: string, nextCustom: boolean) => {
const seq = ++dnsEditSeq.current
resetDNSTest()
setDnsSaving(true)
setDnsValidationErr('')
setDnsSavedHint(false)
try {
await api.SetHostDNSConfig({ mode: nextMode, doh_url: nextUrl })
if (dnsEditSeq.current !== seq) return
setSavedDnsMode(nextMode)
setSavedDohUrl(nextUrl)
setDnsMode(nextMode)
setDohUrl(nextUrl)
setDohDraft(nextUrl)
setDohCustom(nextCustom)
setDnsSavedHint(true)
onRefresh()
} catch (e) {
if (dnsEditSeq.current === seq) {
onError(tr('failGeneric'), e)
}
} finally {
if (dnsEditSeq.current === seq) {
setDnsSaving(false)
}
}
}
const resetDNSTest = () => {
dnsTestSeq.current += 1
setDnsTesting(false)
setDnsTestResult(null)
}
const handleDNSModeChange = (nextMode: HostDNSMode) => {
if (nextMode === dnsMode || dnsSaving) return
void saveHostDNS(nextMode, savedDohUrl, dohCustom)
}
const handleDoHPresetChange = (val: string) => {
if (dnsSaving) return
resetDNSTest()
setDnsSavedHint(false)
if (val === CUSTOM_DOH_VALUE) {
dnsEditSeq.current += 1
setDohCustom(true)
setDohDraft(dohUrl)
setDnsValidationErr('')
return
}
if (val !== savedDohUrl || dnsMode !== savedDnsMode) {
void saveHostDNS(dnsMode, val, false)
} else {
dnsEditSeq.current += 1
setDohCustom(false)
setDohDraft(val)
setDnsValidationErr('')
}
}
const commitCustomDoH = (forceSave: boolean) => {
if (dnsSaving) return
const nextUrl = dohDraft.trim()
if (!isValidDoHURL(nextUrl)) {
setDnsValidationErr(tr('hostDNSInvalidURL'))
setDnsSavedHint(false)
return
}
setDnsValidationErr('')
if (!forceSave && nextUrl === savedDohUrl && dnsMode === savedDnsMode) return
setDnsTestResult(null)
void saveHostDNS(dnsMode, nextUrl, true)
}
const handleTestHostDNS = async () => {
if (dnsTesting || dnsSaving) return
const targetUrl = dohCustom ? dohDraft.trim() : dohUrl
if (!isValidDoHURL(targetUrl)) {
setDnsValidationErr(tr('hostDNSInvalidURL'))
setDnsTestResult(null)
return
}
const testSeq = ++dnsTestSeq.current
setDnsValidationErr('')
setDnsSavedHint(false)
setDnsTesting(true)
setDnsTestResult(null)
try {
const res = await api.TestHostDNS({ mode: dnsMode, doh_url: targetUrl })
if (dnsTestSeq.current !== testSeq) return
setDnsTestResult({
ok: true,
domain: res.domain || 'example.com',
addresses: res.addresses ?? [],
elapsedMs: res.elapsed_ms ?? 0,
})
} catch (e) {
if (dnsTestSeq.current !== testSeq) return
const parsed = parseAppError(e)
setDnsTestResult({ ok: false, reason: parsed.summary || String(e) })
} finally {
if (dnsTestSeq.current === testSeq) {
setDnsTesting(false)
}
}
}
const dohSelectValue = dohCustom ? CUSTOM_DOH_VALUE : (isPresetDoHURL(dohUrl) ? dohUrl : CUSTOM_DOH_VALUE)
const showDoHExtra = dohCustom || Boolean(dnsValidationErr) || dnsSavedHint || dnsTestResult !== null
const forceQuit = async () => {
try {
await api.ForceQuitApp()
} catch (e) {
onError(tr('quitFailed'), e)
}
}
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 (
<div className="page rg-p-settings">
<header className="page-head">
<div className="page-title"><h1>{tr('sidebarSettings')}</h1></div>
</header>
<section className="section">
<div className="section-title">{tr('settingsGeneral')}</div>
<div className="list">
<div className="row">
<div className="row-main">
<div className="row-title">{tr('hostDataRoot')}</div>
<div className="row-sub mono">{config.data_root}</div>
</div>
<div className="row-right"><Button onClick={pickDataRoot}>{tr('choose')}</Button></div>
</div>
<div className="row">
<div className="row-main">
<div className="row-title">
{tr('autoPinPCores')}
<span className={`badge rg-p-badge ${optBadgeClass(pcoreOpt?.status)}`}>
{optStatusLabel(locale, pcoreOpt?.status)}
</span>
</div>
<div className="row-sub">
{pcoreOpt?.supported
? tr('optPCoreSub', { detail: pcoreOpt.detail ?? `${host.p_core_count}P+${host.e_core_count}E` })
: tr('optPCoreUnavailable')}
</div>
</div>
<div className="row-right">
<Switch
label={tr('autoPinPCores')}
disabled={!pcoreOpt?.supported}
checked={!!pcoreOpt?.supported && config.auto_pin_pcores}
onChange={(checked) => guard(() => api.SetAutoPinPCores(checked))()}
/>
</div>
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('syncHostMemorySMBIOS')}</div>
<div className="row-sub">
{memSpecLabel
? tr('syncHostMemorySMBIOSSub', { spec: memSpecLabel })
: tr('syncHostMemorySMBIOSUnavailable')}
</div>
</div>
<div className="row-right">
<Switch
label={tr('syncHostMemorySMBIOS')}
disabled={!memSpecLabel}
checked={!!memSpecLabel && !!config.sync_host_memory_smbios}
onChange={(checked) => guard(() => api.SetSyncHostMemorySMBIOS(checked))()}
/>
</div>
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('minimizeToTray')}</div>
<div className="row-sub">{tr('minimizeToTraySub')}</div>
</div>
<div className="row-right">
<Switch
label={tr('minimizeToTray')}
checked={config.minimize_to_tray !== false}
onChange={(checked) => guard(() => api.SetMinimizeToTray(checked))()}
/>
</div>
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('hostDNSModeTitle')}</div>
<div className="row-sub">
{tr(dnsMode === 'doh' ? 'hostDNSModeDoHSub' : 'hostDNSModeSystemSub')}
</div>
</div>
<div className="row-right">
<PopupSelect<HostDNSMode>
label={tr('hostDNSModeTitle')}
value={dnsMode}
onChange={handleDNSModeChange}
options={[
{ value: 'system', label: tr('hostDNSModeSystem') },
{ value: 'doh', label: tr('hostDNSModeDoH') },
]}
/>
</div>
</div>
<div className="row row-stack">
<div className="row-head">
<div className="row-main">
<div className="row-title">{tr('hostDNSDoHTitle')}</div>
<div className="row-sub">{tr('hostDNSDoHSub')}</div>
</div>
<div className="row-right">
<PopupSelect
label={tr('hostDNSDoHTitle')}
value={dohSelectValue}
onChange={handleDoHPresetChange}
options={[
...DOH_PRESETS.map((p) => ({
value: p.url,
label: tr(p.labelKey),
detail: p.host,
})),
{ value: CUSTOM_DOH_VALUE, label: tr('hostDNSPresetCustom') },
]}
/>
<Button busy={dnsTesting} disabled={dnsSaving} onClick={() => void handleTestHostDNS()}>
{tr(dnsTesting ? 'hostDNSTesting' : 'hostDNSTest')}
</Button>
</div>
</div>
{showDoHExtra && (
<div className="host-dns-extra">
{dohCustom && (
<div className="host-dns-custom">
<input
className="input rg-p-input mono"
type="url"
value={dohDraft}
spellCheck={false}
autoComplete="off"
placeholder={tr('hostDNSCustomPlaceholder')}
aria-label={tr('hostDNSDoHTitle')}
aria-invalid={dnsValidationErr ? true : undefined}
onChange={(e) => {
setDohDraft(e.target.value)
setDnsValidationErr('')
setDnsSavedHint(false)
resetDNSTest()
}}
onBlur={() => commitCustomDoH(false)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault()
commitCustomDoH(true)
}
}}
/>
<Button
busy={dnsSaving}
disabled={dnsSaving || !dohDraft.trim()}
onMouseDown={(e) => e.preventDefault()}
onClick={() => commitCustomDoH(true)}
>
{tr('save')}
</Button>
</div>
)}
{dnsValidationErr && (
<div className="host-dns-feedback danger-text" role="alert">
<CircleAlert size={13} aria-hidden="true" />
<span>{dnsValidationErr}</span>
</div>
)}
{!dnsValidationErr && dnsSavedHint && (
<div className="host-dns-feedback ok-text" role="status">
<Check size={13} aria-hidden="true" />
<span>{tr('hostDNSSaved')}</span>
</div>
)}
{dnsTestResult && (
<div
className={`host-dns-feedback ${dnsTestResult.ok ? 'ok-text' : 'danger-text'}`}
role={dnsTestResult.ok ? 'status' : 'alert'}
>
{dnsTestResult.ok ? <Check size={13} aria-hidden="true" /> : <CircleAlert size={13} aria-hidden="true" />}
<span className={dnsTestResult.ok ? 'mono' : undefined}>
{dnsTestResult.ok
? tr('hostDNSTestOK', {
domain: dnsTestResult.domain,
ips: dnsTestResult.addresses.slice(0, 2).join(', '),
ms: dnsTestResult.elapsedMs,
})
: tr('hostDNSTestFailed', { reason: dnsTestResult.reason })}
</span>
</div>
)}
</div>
)}
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('forceQuitAppTitle')}</div>
<div className="row-sub">{tr('forceQuitAppSub')}</div>
</div>
<div className="row-right">
<Button variant="danger" onClick={forceQuit} busy={quitMode === 'force'} icon={<PowerOff size={14} aria-hidden="true" />}>
{tr(quitMode === 'force' ? 'forceQuitInProgress' : 'forceQuitAppButton')}
</Button>
</div>
</div>
</div>
</section>
<section className="section">
<div className="section-title">{tr('settingsVirtualization')}</div>
<div className="list">
<div className="row">
<div className="row-main">
<div className="row-title">{tr('hypervisorSwitchGateTitle')}</div>
<div className="row-sub">
{hvView.supported ? tr('hypervisorSwitchGateSub') : tr('whpxUnsupported')}
</div>
</div>
<div className="row-right">
<Switch
label={tr('hypervisorSwitchGateTitle')}
disabled={!hvView.supported || hypervisorBusy}
checked={hvView.gateEnabled}
onChange={(checked) => guard(() => api.SetEnableHypervisorSwitch(checked))()}
/>
</div>
</div>
{hvView.expanded && (
<div className="row row-stack">
<div className="row-head">
<div className="row-main">
<div className="row-title">
{tr('hypervisorBootRowTitle')}
<span className={`badge rg-p-badge ${hvView.badgeClass}`}>{hvView.badgeLabel}</span>
</div>
<div className="row-sub">{hvView.subLabel}</div>
</div>
<div className="row-right">
<Tip label={tr('hypervisorStopVMsFirst')} disabled={!hvView.disableBlockedByVMs}>
<span className="tip-anchor" tabIndex={hvView.disableBlockedByVMs ? 0 : undefined}>
<Button
variant={hvView.actionVariant}
busy={hypervisorBusy}
disabled={hypervisorBusy || hvView.disableBlockedByVMs}
onClick={() => setConfirmHypervisor({ enable: hvView.targetEnable, isUndo: hvView.isUndo })}
>
{hvView.actionLabel}
</Button>
</span>
</Tip>
</div>
</div>
{hvView.showHVCINotice && (
<div className="host-dns-extra">
<div className="hypervisor-hvci-notice warn-text">
<CircleAlert size={13} aria-hidden="true" />
<span>
{tr('hypervisorHVCINotice')}{' '}
<button type="button" className="link-btn" onClick={() => void openCoreIsolation()}>
{tr('hypervisorOpenCoreIsolation')}
</button>
</span>
</div>
</div>
)}
</div>
)}
</div>
</section>
<section className="section">
<div className="section-title">{tr('settingsAppearance')}</div>
<div className="list">
<div className="row">
<div className="row-main">
<div className="row-title">{tr('themeLabel')}</div>
{(!canDark || !canLight) && (
<div className="row-sub">{tr(!canDark ? 'themePluginDarkDisabled' : 'themePluginLightDisabled')}</div>
)}
</div>
<div className="row-right">
<Segmented
label={tr('themeLabel')}
value={themeMode}
onChange={onThemeMode}
options={[
{ value: 'light', label: tr('themeLight'), disabled: !canLight },
{ value: 'dark', label: tr('themeDark'), disabled: !canDark },
{ value: 'system', label: tr('themeSystem'), disabled: !canLight || !canDark },
]}
/>
</div>
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('language')}</div>
<div className="row-sub">{tr('languageSub')}</div>
{missingFontScript && (
<div className="row-sub warn-text">{tr('fontMissingFoDHint', { script: missingFontScript })}</div>
)}
</div>
<div className="row-right">
<PopupSelect
label={tr('language')}
value={config.locale || 'auto'}
onChange={onSetLocale}
options={getLocaleOptions(locales, locale, state.detected_locale)}
/>
</div>
</div>
</div>
</section>
{confirmHypervisor && (
<Modal
className="md"
title={tr(confirmHypervisor.enable ? 'hypervisorConfirmOnTitle' : 'hypervisorConfirmOffTitle')}
closeLabel={tr('close')}
tone={confirmHypervisor.enable ? 'neutral' : 'warn'}
dismissable={!hypervisorBusy}
onClose={() => setConfirmHypervisor(null)}
>
<div className="dialog-body dialog-prose">
{confirmHypervisor.enable ? (
<p>{tr('hypervisorConfirmOnBody')}</p>
) : (
<>
<p>{tr('hypervisorConfirmOffBody')}</p>
{(host.hvci_enabled || host.vbs_running) && (
<p className="warn-text">{tr('hypervisorHVCINotice')}</p>
)}
<p>{tr('hypervisorConfirmOffBitLocker')}</p>
</>
)}
</div>
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" disabled={hypervisorBusy} onClick={() => setConfirmHypervisor(null)}>
{tr('cancel')}
</Button>
<Button variant="primary" busy={hypervisorBusy} onClick={() => void runSetHypervisorBoot(confirmHypervisor)}>
{tr(confirmHypervisor.enable ? 'hypervisorConfirmEnableBtn' : 'hypervisorConfirmDisableBtn')}
</Button>
</span>
</div>
</Modal>
)}
</div>
)
}