import { CircleAlert, Copy, Cpu, HardDrive, Info, Keyboard, LucideIcon, Monitor, Wrench } from 'lucide-react' import React, { Suspense, lazy, useEffect, useMemo, useRef, useState } from 'react' import '../i18n/domains/settings.gen' import { I18nKey, parseAppError, t } from '../i18n' import { GUEST_LANG_PRESETS, guestLangOptions, MEMORY_MARKS, findGPU, formatBytes, gpuCompatHint, gpuOptionValue, memorySafeLimitGB, parseMemoryGB, recommendedCPUs, fullscreenDisplayPresets, FullscreenDisplayPreset, hidpiLooksLike, hostDisplayAdvice, hostDisplayDesc, recommendedDisplayPresets, recommendedMemoryGB, recommendedResolution, shortGPUName, sshCommand, } from '../lib/format' import { applyKernelIrqchip, findOptimization, kernelIrqchipHint, parseKernelIrqchip } from '../lib/optimizations' import { DiskCompactResult, DiskResizeResult, DriveShareSettings, HostReport, Locale, Optimization, PluginInfo, SetOpts, ValidationIssue, VMAffinityStatus, VMDetail, VMStats } from '../types' import { Button, IconButton } from '../ui/controls' import { Modal } from '../ui/dialog' import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, SetValue, Switch } from '../ui/settings' import { api } from '../wails' import { formatAffinitySummary } from './AffinityDialog' const SchemaForm = lazy(() => import('./SchemaForm').then((m) => ({ default: m.SchemaForm }))) // VM settings (docs/design-guidelines.md §2–3): edits are staged here and written in // one `reims-ctl set` on Save, because upstream applies every change on the // next start. Each row marks itself when it differs from the VM's current // value and can be put back on its own. type Cat = 'general' | 'compute' | 'display' | 'storage' | 'input' | 'advanced' const CATS: { id: Cat; label: I18nKey; icon: LucideIcon }[] = [ { id: 'general', label: 'catGeneral', icon: Info }, { id: 'compute', label: 'catCompute', icon: Cpu }, { id: 'display', label: 'catGraphics', icon: Monitor }, { id: 'storage', label: 'catStorageNet', icon: HardDrive }, { id: 'input', label: 'catInputAudio', icon: Keyboard }, { id: 'advanced', label: 'catAdvanced', icon: Wrench }, ] type Field = Exclude const FIELD_CAT: Record = { guest_lang: 'general', cpus: 'compute', memory: 'compute', graphics: 'display', gpu: 'display', resolution: 'display', displays: 'display', borderless: 'display', disk_controller: 'storage', network: 'storage', ssh_port: 'storage', capture: 'input', audio: 'input', audio_backend: 'input', logs: 'advanced', log_level: 'advanced', stop_timeout: 'advanced', extra_args: 'advanced', } const FIELDS = Object.keys(FIELD_CAT) as Field[] const LOG_LEVELS = ['error', 'warn', 'info', 'debug', 'trace'] as const const CUSTOM = '__custom' const RES_RE = /^\s*\d{3,5}\s*[x×]\s*\d{3,5}\s*$/i const normPath = (s: string | undefined) => (s ?? '').replace(/\//g, '\\').toLowerCase() const normRes = (s: string | undefined) => (s ?? '').replace(/\s/g, '').replace(/×/g, 'x').toLowerCase() /** Whether two values of a field mean the same thing to reims-ctl. */ function same(field: Field, a: SetOpts[Field], b: SetOpts[Field]): boolean { switch (field) { case 'memory': return parseMemoryGB(a as string) === parseMemoryGB(b as string) case 'gpu': return normPath(a as string) === normPath(b as string) case 'resolution': return normRes(a as string) === normRes(b as string) case 'log_level': case 'extra_args': case 'audio_backend': case 'guest_lang': return String(a ?? '').trim() === String(b ?? '').trim() default: return a === b } } function baseline(detail: VMDetail, host: HostReport): SetOpts { // Match the stored ICD path to the host's spelling so the GPU card lights up. const icd = (host.gpus ?? []).find((g) => normPath(g.vulkan_icd) === normPath(detail.gpu))?.vulkan_icd return { name: detail.name, cpus: detail.cpus, memory: detail.memory, graphics: detail.graphics, displays: detail.displays || 1, disk_controller: detail.disk_controller, resolution: detail.resolution, borderless: detail.borderless, capture: detail.capture, gpu: icd ?? (detail.gpu || 'auto'), logs: detail.logs, log_level: detail.log_level, audio: detail.audio, audio_backend: detail.audio_backend || 'auto', network: detail.network, ssh_port: detail.ssh_port, stop_timeout: detail.stop_timeout, extra_args: detail.extra_args, guest_lang: detail.guest_lang || 'en-US:0', } } interface Props { locale: Locale detail: VMDetail stats?: VMStats | null host: HostReport optimizations?: Optimization[] running: boolean onCopy?: (text: string) => void onDiskChanged?: () => void onOpenAffinity?: () => void affinityVersion?: number /** Re-probe the host, e.g. after Windows' processor scheduling may have changed. */ onHostChanged?: () => void onClose: () => void onSaved: () => void } export const SettingsModal: React.FC = ({ locale, detail, stats, host, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onHostChanged, onClose, onSaved }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const irqOpt = findOptimization(optimizations, 'kernel_irqchip') const base = useMemo(() => baseline(detail, host), [detail, host]) const [cat, setCat] = useState('compute') const [busy, setBusy] = useState(false) const [issues, setIssues] = useState([]) const [err, setErr] = useState('') const [form, setForm] = useState(base) const [resizeInput, setResizeInput] = useState('+64G') const [diskOpBusy, setDiskOpBusy] = useState<'resize' | 'compact' | ''>('') const [resizeResult, setResizeResult] = useState(null) const [compactResult, setCompactResult] = useState(null) const [driveSettings, setDriveSettings] = useState(null) const [driveBusy, setDriveBusy] = useState(false) const driveBusyRef = useRef(false) const activeVMNameRef = useRef(detail.name) activeVMNameRef.current = detail.name const [driveErr, setDriveErr] = useState('') const [affinityStatus, setAffinityStatus] = useState(null) const [vmPlugins, setVmPlugins] = useState([]) const [vmPluginVals, setVmPluginVals] = useState>>({}) const pane = useRef(null) useEffect(() => { let live = true Promise.all([api.ListPlugins(), api.GetVMPluginSettings(detail.name)]) .then(([list, vals]) => { if (!live) return const activeWithVM = (list ?? []).filter((p) => (p.state === 'active' || p.state === 'degraded') && !!p.settings) setVmPlugins(activeWithVM) setVmPluginVals((vals ?? {}) as Record>) }) .catch(() => {}) return () => { live = false } }, [detail.name]) const updateVMPluginSetting = (pluginID: string, next: Record) => { setVmPluginVals((prev) => ({ ...prev, [pluginID]: next })) void api.SetPluginSettings(pluginID, detail.name, next).catch((e) => setErr(parseAppError(e).summary)) } const renderVMPluginGroup = (group: string) => { const matched = vmPlugins.filter((p) => p.settings && (p.settings['x-group'] === group || Object.values(p.settings.properties ?? {}).some((prop) => prop['x-group'] === group))) if (matched.length === 0) return null return ( {matched.map((p) => ( updateVMPluginSetting(p.id, next)} /> ))} ) } const presets = recommendedDisplayPresets(host) const fsPresets = fullscreenDisplayPresets(host) const activePresets: FullscreenDisplayPreset[] = form.borderless ? fsPresets : presets const presetHit = activePresets.some((p) => same('resolution', p.resolution, form.resolution)) const [customRes, setCustomRes] = useState(!presetHit) const [customLog, setCustomLog] = useState(!!form.log_level && !(LOG_LEVELS as readonly string[]).includes(form.log_level)) // The detail the panel opened with can be a stale one (reopened right after // a save, before the refreshed detail arrives): follow newer details until // the person changes something. const edited = useRef(false) useEffect(() => { if (edited.current) return setForm(base) const list = base.borderless ? fsPresets : presets setCustomRes(!list.some((p) => same('resolution', p.resolution, base.resolution))) setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level)) }, [base]) // presets come from host, which base already follows const set = (patch: Partial) => { edited.current = true setForm((f) => ({ ...f, ...patch })) const touched = Object.keys(patch) setIssues((list) => list.filter((i) => !touched.includes(i.field))) } const dirty = (f: Field) => !same(f, form[f], base[f]) const reset = (f: Field) => () => { set({ [f]: base[f] } as Partial) if (f === 'resolution' || f === 'borderless') { const nextBorderless = f === 'borderless' ? base.borderless : form.borderless const nextRes = f === 'resolution' ? base.resolution : form.resolution const list = nextBorderless ? fsPresets : presets setCustomRes(!list.some((p) => same('resolution', p.resolution, nextRes))) } if (f === 'log_level') setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level)) } const changed = FIELDS.filter(dirty) const changedIn = (c: Cat) => changed.filter((f) => FIELD_CAT[f] === c).length const issueOf = (f: Field) => issues.find((i) => i.field === f)?.message const issueIn = (c: Cat) => issues.some((i) => FIELD_CAT[i.field as Field] === c) || (c === 'display' && resBad) const strayIssues = issues.filter((i) => !(i.field in FIELD_CAT)) // Inline checks the backend would also reject, so the row says it first. const resBad = customRes && !RES_RE.test(form.resolution ?? '') const sshOn = (form.ssh_port ?? 0) > 0 const localBlock = resBad const rowProps = (f: Field) => ({ field: f, dirty: dirty(f), onReset: reset(f), resetLabel: tr('resetField'), error: issueOf(f), }) // Scroll the first row with an error into view after switching to its page. useEffect(() => { if (issues.length === 0) return const el = pane.current?.querySelector('[data-error]') el?.scrollIntoView({ block: 'nearest', behavior: 'smooth' }) }, [issues, cat]) useEffect(() => { let active = true setDriveSettings(null) setDriveErr('') api.GetVMDriveShareSettings(detail.name) .then((settings) => { if (active) setDriveSettings(settings) }) .catch((e) => { if (active) setDriveErr(parseAppError(e).summary) }) return () => { active = false } }, [detail.name]) useEffect(() => { let active = true api.GetVMAffinity(detail.name) .then((st) => { if (active) setAffinityStatus(st) }) .catch(() => {}) return () => { active = false } }, [detail.name, running, affinityVersion]) const updateDriveShares = async (enabled: boolean, selected: string[]) => { if (driveBusyRef.current || !driveSettings) return driveBusyRef.current = true const vmName = detail.name setDriveBusy(true) setDriveErr('') try { const next = await api.SetVMDriveShareSettings(vmName, enabled, selected) if (activeVMNameRef.current === vmName) setDriveSettings(next) } catch (e) { if (activeVMNameRef.current === vmName) setDriveErr(parseAppError(e).summary) } finally { driveBusyRef.current = false setDriveBusy(false) } } const selectedDrives = () => (driveSettings?.drives ?? []).filter((d) => d.selected).map((d) => d.drive) // Windows-wide, not staged with Save: one UAC prompt opens Windows' own // Performance Options, and the new choice shows after the host refresh. const [openingSched, setOpeningSched] = useState(false) const openScheduling = async () => { setOpeningSched(true) try { await api.OpenProcessorScheduling() onHostChanged?.() } catch (e) { setErr(parseAppError(e).summary) } finally { setOpeningSched(false) } } const handleSave = async () => { if (busy || changed.length === 0 || localBlock) return setErr('') setIssues([]) setBusy(true) try { const diff: SetOpts = { name: detail.name } for (const f of changed) (diff as unknown as Record)[f] = form[f] const iss = await api.ValidateSet(diff) if (iss && iss.length > 0) { setIssues(iss) const first = iss.map((i) => FIELD_CAT[i.field as Field]).find(Boolean) if (first) setCat(first) return } await api.ApplyVMSettings(diff) onSaved() } catch (e) { setErr(parseAppError(e).summary) } finally { setBusy(false) } } const resetAll = () => { edited.current = false setForm(base) setIssues([]) setCustomRes(!presets.some((p) => same('resolution', p.resolution, base.resolution))) setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level)) } const onKeyDown = (e: React.KeyboardEvent) => { if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') { e.preventDefault() void handleSave() } } const realGPUs = (host.gpus ?? []).filter((g) => g.kind !== 'virtual') const threads = Math.max(host.logical_cpus || 0, 1) const cpuRec = recommendedCPUs(host) const memRec = recommendedMemoryGB(host) const memSafe = memorySafeLimitGB(host) const memMax = Math.max(Math.floor((host.total_ram_gb || 16) * 0.85), memRec, 4) const memGB = Math.round(parseMemoryGB(form.memory) ?? memRec) // ── Pages ──────────────────────────────────────────────── const general = ( <> set({ guest_lang })} options={[ ...guestLangOptions(locale), ...(form.guest_lang && !GUEST_LANG_PRESETS.some((p) => p.value === form.guest_lang) ? [{ value: form.guest_lang, label: form.guest_lang }] : []), ]} /> } /> {renderVMPluginGroup('collaboration')} ) const irqMode = parseKernelIrqchip(form.extra_args) const cpuOver = (form.cpus ?? 0) > threads - 2 && threads > 2 const memOver = memGB > memSafe const compute = ( <> {tr('cpuOverHint')} : tr('cpuRecHint', { rec: cpuRec, n: threads })} block={ set({ cpus })} recommend={[Math.min(4, cpuRec), cpuRec]} warnFrom={threads > 2 ? threads - 1 : undefined} marks={[1, 2, 4, 6, 8, 12, 16, 24, 32, 48, 64].concat(threads).map((n) => ({ value: n, label: String(n) }))} /> } /> {onOpenAffinity && ( {tr('memOverHint')} : host.commit_avail_gb > 0 ? tr('memCommitHint', { avail: host.commit_avail_gb.toFixed(1), rec: memRec }) : tr('memRecHint', { rec: memRec, n: host.total_ram_gb.toFixed(0) })} block={ set({ memory: `${gb}G` })} recommend={[Math.min(4, memRec), memRec]} warnFrom={memSafe + 1} marks={MEMORY_MARKS.concat(memMax).map((n) => ({ value: n, label: String(n) }))} /> } /> set({ extra_args: applyKernelIrqchip(form.extra_args, parseKernelIrqchip(base.extra_args)) })} error={undefined} field={undefined} title={tr('kernelIrqchipLabel')} desc={{kernelIrqchipHint(locale, irqOpt)}} control={ set({ extra_args: applyKernelIrqchip(form.extra_args, mode) })} options={[ { value: 'auto', label: tr('kernelIrqchipAuto') }, { value: 'on', label: tr('kernelIrqchipOn'), disabled: !irqOpt?.supported }, { value: 'off', label: tr('kernelIrqchipOff') }, ]} /> } /> {tr('optSchedNowPrograms')} : tr('optSchedSub') } control={} /> ) const gpuOptions = [ { value: 'auto', title: tr('gpuAutoTitle'), sub: host.recommended_gpu ? tr('gpuAutoSub', { name: shortGPUName(host.recommended_gpu.name) }) : tr('gpuAutoOption'), }, ...realGPUs.map((g) => ({ value: gpuOptionValue(g, realGPUs), title: shortGPUName(g.name), sub: [ g.kind === 'discrete' ? tr('gpuKindDiscrete') : g.kind === 'integrated' ? tr('gpuKindIntegrated') : '', g.compat === 'unsupported' ? tr('gpuCompatUnsupported') : g.compat === 'warn' ? tr('gpuCompatWarn') : '', ] .filter(Boolean) .join(' · ') || undefined, })), ] if (form.gpu && form.gpu !== 'auto' && !gpuOptions.some((o) => normPath(o.value) === normPath(form.gpu))) { gpuOptions.push({ value: form.gpu, title: form.gpu.split(/[\\/]/).pop() || form.gpu, sub: tr('gpuCustomIcd') }) } const selectedGPU = findGPU(host, form.gpu) const selectedGPUHint = gpuCompatHint(locale, selectedGPU) const vgpu = form.graphics !== 'vmware-svga' const pd = host.primary_display const hidpiAdvice = hostDisplayAdvice(host, tr) const resValue = customRes ? CUSTOM : activePresets.find((p) => same('resolution', p.resolution, form.resolution))?.resolution const toggleBorderless = (borderless: boolean) => { const targetPresets = borderless ? fsPresets : presets if (!customRes && !targetPresets.some((p) => same('resolution', p.resolution, form.resolution))) { const nextRes = borderless ? (pd ? `${pd.width}x${pd.height}` : targetPresets[0]?.resolution ?? form.resolution) : recommendedResolution(host) set({ borderless, resolution: nextRes }) return } set({ borderless }) } const resArt = (r: string) => { const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(r) return m ? : } const display = ( <> set({ graphics })} options={[ { value: 'reims-vgpu', label: tr('graphicsReimsShort') }, { value: 'vmware-svga', label: tr('graphicsSvgaShort') }, ]} /> } /> {tr('gpuUnavailableHint')} ) : selectedGPUHint ? ( {selectedGPUHint} {!running && vgpu && ( <> {' '} )} ) : undefined } disabled={!vgpu} reason={tr('gpuSvgaReason')} block={ normPath(o.value) === normPath(form.gpu))?.value} onChange={(gpu) => set({ gpu })} options={gpuOptions} />} /> } /> { if (v === CUSTOM) { setCustomRes(true); return } setCustomRes(false) set({ resolution: v }) }} options={[ ...activePresets.map((p) => ({ value: p.resolution, title: p.label, sub: p.hidpi ? hidpiLooksLike(p.resolution, tr) : undefined, art: resArt(p.resolution), badges: [ p.hidpi ? tr('hidpiPresetBadge') : '', p.scaleBadge ?? '', p.native ? tr('resNativeBadge') : '', p.recommended ? tr('recommendedBadge') : '', ].filter(Boolean), })), { value: CUSTOM, title: tr('resCustom'), sub: tr('resCustomSub'), art: ) const handleResizeDisk = async () => { if (running || diskOpBusy || !resizeInput.trim()) return setErr('') setDiskOpBusy('resize') try { const res = await api.ResizeVMDisk(detail.name, resizeInput.trim()) setResizeResult(res) onDiskChanged?.() } catch (e) { setErr(parseAppError(e).summary) } finally { setDiskOpBusy('') } } const handleCompactDisk = async () => { if (running || diskOpBusy) return setErr('') setDiskOpBusy('compact') try { const res = await api.CompactVMDisk(detail.name) setCompactResult(res) onDiskChanged?.() } catch (e) { setErr(parseAppError(e).summary) } finally { setDiskOpBusy('') } } const isQcow2 = !stats?.disk_format || stats.disk_format === 'qcow2' const diskControllerDesc = detail.has_installer ? tr('diskControllerInstallHint') : form.disk_controller === 'virtio' ? tr('diskControllerVirtioHint') : form.disk_controller === 'nvme' ? tr('diskControllerNvmeReadyHint') : tr('diskControllerNvmeHint') const storage = ( <> {stats && stats.disk_virtual_bytes > 0 && ( )} {stats && ((stats.disk_backing_depth ?? 0) >= 2 || stats.disk_backing_broken) && ( )} set({ disk_controller })} options={[ { value: 'ahci', label: 'SATA' }, { value: 'nvme', label: 'NVMe' }, { value: 'virtio', label: 'VirtIO' }, ]} /> } />
{['+32G', '+64G', '+128G', '256G', '512G'].map((v) => ( ))}
setResizeInput(e.target.value)} placeholder="+64G / 256G" />
{resizeResult && (
{tr('diskResizeDone', { size: formatBytes(resizeResult.new_virtual_bytes, locale) })}
{resizeResult.guest_expand_cmd} {onCopy && ( } onClick={() => onCopy(resizeResult.guest_expand_cmd)} /> )}
)} } /> 0 ? tr('diskCompactDone', { before: formatBytes(compactResult.before_bytes, locale), after: formatBytes(compactResult.after_bytes, locale), reclaimed: formatBytes(compactResult.reclaimed_bytes, locale), }) : tr('diskCompactNoGain') : tr('diskCompactDesc')} disabled={running || !isQcow2} reason={running ? tr('stopBeforeDiskOp') : tr('diskCompactQcow2Only')} control={ } />
void updateDriveShares(enabled, selectedDrives())} /> } /> {detail.guest_tools_disabled &&
{tr('gtStatusOffTip')}
} {driveErr &&
{driveErr}
} {driveSettings?.enabled && selectedDrives().length > 0 && (detail.guest_tools_agent_version ?? 0) < driveSettings.required_agent_version && (
{tr('driveShareNeedsTools', { version: driveSettings.required_agent_version })}
)} {/* Drives are only worth choosing once sharing is on. */} {driveSettings?.enabled && driveSettings.drives.map((drive) => { const title = `Windows (${drive.drive}:)` return ( {tr('driveShareSystem')} : undefined} disabled={driveBusy || !!detail.guest_tools_disabled} control={ { const next = selectedDrives().filter((letter) => letter !== drive.drive) if (enabled) next.push(drive.drive) void updateDriveShares(driveSettings?.enabled ?? false, next) }} /> } /> ) })} {driveSettings && driveSettings.drives.length === 0 && ( )}
set({ network })} />} /> {sshCommand(form.ssh_port ?? 0)} : tr('sshOffDesc')} disabled={!form.network} reason={tr('sshNeedsNetwork')} control={
{sshOn && ( set({ ssh_port })} /> )} set({ ssh_port: on ? (base.ssh_port || 2222) : 0 })} />
} />
) const hostAudio = host.audio const audioOutSummary = hostAudio ? hostAudio.output_count > 0 ? `${hostAudio.output_count}${hostAudio.output_devices?.length ? ` · ${hostAudio.output_devices.slice(0, 2).join(', ')}` : ''}` : tr('hostAudioMissingOut') : '—' const audioInSummary = hostAudio ? hostAudio.input_count > 0 ? `${hostAudio.input_count}${hostAudio.input_devices?.length ? ` · ${hostAudio.input_devices.slice(0, 2).join(', ')}` : ''}` : tr('hostAudioMissingIn') : '—' const input = ( <> set({ capture })} />} /> {renderVMPluginGroup('keyboard')} set({ audio })} />} /> set({ audio_backend })} options={[ { value: 'auto', label: tr('audioBackendAuto') }, { value: 'dsound', label: tr('audioBackendDsound') }, { value: 'none', label: tr('audioBackendNone') }, // A backend set elsewhere (`reims-ctl set --audio-backend wav`) still shows as chosen. ...(['auto', 'dsound', 'none'].includes(form.audio_backend || 'auto') ? [] : [{ value: form.audio_backend as string, label: form.audio_backend as string }]), ]} /> } /> {hostAudio && ( <> )} ) const advanced = ( <> set({ logs })} />} /> { if (v === CUSTOM) { setCustomLog(true); return } setCustomLog(false) set({ log_level: v }) }} options={[...LOG_LEVELS.map((l) => ({ value: l as string, label: l })), { value: CUSTOM, label: tr('logLevelCustom') }]} /> {customLog && ( set({ log_level: e.target.value })} /> )} } /> set({ stop_timeout })} />} /> set({ extra_args: e.target.value })} />} /> ) const pages: Record = { general, compute, display, storage, input, advanced } return (

{tr(CATS.find((c) => c.id === cat)!.label)}

{err &&
{err}
} {strayIssues.length > 0 && (
    {strayIssues.map((i) =>
  • {i.message}
  • )}
)}
{pages[cat]}
{changed.length > 0 ? <>
) }