Files
Reims-Go/frontend/src/components/SettingsModal.tsx
T
NwflowerandClaude Opus 5.5 9e4bc98c7d feat(settings): rebuild VM settings as an interactive System Settings-style panel
- Merge 10 categories into 6 (General, CPU & Memory, Graphics & Displays,
  Storage & Network, Input & Audio, Advanced) with coloured nav icons
- New ui/settings.tsx primitives: row shell, switch, segmented control with
  sliding highlight, slider + number field with recommended/risky zones,
  option cards with screen-shape previews
- Host-aware CPU/memory recommendations (recommendedCPUs, memorySafeLimitGB)
- Rows explain why they are disabled (graphics while running, SSH without
  network, controller with installer attached, GPU under VMware SVGA)
- Per-row change marks and revert, per-category change counts, footer
  summary, Revert all, Ctrl+S; Save disabled with no changes
- Validation issues attach to their row and jump to its page; inline check
  for custom resolutions
- Fix duplicate resolution label/input

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 09:53:05 -07:00

631 lines
24 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { CircleAlert, Cpu, HardDrive, Info, Keyboard, LucideIcon, Monitor, Wrench } from 'lucide-react'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import { I18nKey, t } from '../i18n'
import {
MEMORY_MARKS,
memorySafeLimitGB,
parseMemoryGB,
recommendedCPUs,
recommendedDisplayPresets,
recommendedMemoryGB,
shortGPUName,
sshCommand,
} from '../lib/format'
import {
applyKernelIrqchip,
findOptimization,
kernelIrqchipHint,
optBadgeClass,
optStatusLabel,
parseKernelIrqchip,
} from '../lib/optimizations'
import { HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMDetail } from '../types'
import { Button } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { NumberField, OptionCards, RangeField, ScreenArt, Segmented, SetGroup, SetRow, SetValue, Switch } from '../ui/settings'
import { backend } from '../wails'
// VM settings (docs/shell-design.md §4): 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<keyof SetOpts, 'name' | 'audio_backend'>
const FIELD_CAT: Record<Field, Cat> = {
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',
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':
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,
network: detail.network,
ssh_port: detail.ssh_port,
stop_timeout: detail.stop_timeout,
extra_args: detail.extra_args,
}
}
interface Props {
locale: Locale
detail: VMDetail
host: HostReport
optimizations?: Optimization[]
running: boolean
onClose: () => void
onSaved: () => void
}
export const SettingsModal: React.FC<Props> = ({ locale, detail, host, optimizations, running, onClose, onSaved }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const irqOpt = findOptimization(optimizations, 'kernel_irqchip')
const base = useMemo(() => baseline(detail, host), [detail, host])
const [cat, setCat] = useState<Cat>('compute')
const [busy, setBusy] = useState(false)
const [issues, setIssues] = useState<ValidationIssue[]>([])
const [err, setErr] = useState('')
const [form, setForm] = useState<SetOpts>(base)
const pane = useRef<HTMLDivElement>(null)
const presets = recommendedDisplayPresets(host)
const presetHit = presets.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))
const set = (patch: Partial<SetOpts>) => {
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<SetOpts>)
if (f === 'resolution') setCustomRes(!presets.some((p) => same('resolution', p.resolution, base.resolution)))
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<HTMLElement>('[data-error]')
el?.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
}, [issues, cat])
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<string, unknown>)[f] = form[f]
const iss = await backend.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 backend.applyVMSettings(diff)
onSaved()
} catch (e) {
setErr(String(e).replace(/^Error:\s*/, ''))
} finally {
setBusy(false)
}
}
const resetAll = () => {
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 = (
<>
<SetGroup note={tr('platformReadonly')}>
<SetValue title={tr('vmName')} value={detail.name} />
<SetValue title={tr('fieldKind')} value={detail.kind || '—'} />
<SetValue title={tr('fieldCPUModel')} value={detail.cpu_model || '—'} mono />
<SetValue title={tr('opencore')} value={detail.has_opencore ? tr('configured') : '—'} />
<SetValue title={tr('fieldDir')} value={detail.directory} mono />
</SetGroup>
</>
)
const cpuOver = (form.cpus ?? 0) > threads - 2 && threads > 2
const memOver = memGB > memSafe
const compute = (
<>
<SetGroup title={tr('factCPU')}>
<SetRow
{...rowProps('cpus')}
title={tr('vcpus')}
desc={cpuOver ? <span className="warn-text">{tr('cpuOverHint')}</span> : tr('cpuRecHint', { rec: cpuRec, n: threads })}
block={
<RangeField
label={tr('vcpus')}
value={form.cpus ?? cpuRec}
min={1}
max={threads}
unit={tr('coresUnit')}
onChange={(cpus) => 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) }))}
/>
}
/>
</SetGroup>
<SetGroup title={tr('factMemory')}>
<SetRow
{...rowProps('memory')}
title={tr('guestMemory')}
desc={memOver
? <span className="warn-text">{tr('memOverHint')}</span>
: 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={
<RangeField
label={tr('guestMemory')}
value={memGB}
min={2}
max={memMax}
unit="GB"
onChange={(gb) => 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) }))}
/>
}
/>
</SetGroup>
</>
)
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: g.vulkan_icd,
title: shortGPUName(g.name),
sub: g.kind === 'discrete' ? tr('gpuKindDiscrete') : g.kind === 'integrated' ? tr('gpuKindIntegrated') : 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 vgpu = form.graphics !== 'vmware-svga'
const resValue = customRes ? CUSTOM : presets.find((p) => same('resolution', p.resolution, form.resolution))?.resolution
const resArt = (r: string) => {
const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(r)
return m ? <ScreenArt w={Number(m[1])} h={Number(m[2])} /> : <ScreenArt w={16} h={10} />
}
const display = (
<>
<SetGroup title={tr('groupGraphics')}>
<SetRow
{...rowProps('graphics')}
title={tr('graphicsBackend')}
desc={vgpu ? tr('graphicsReimsDesc') : tr('graphicsSvgaDesc')}
disabled={running}
reason={tr('graphicsRunningReason')}
control={
<Segmented
label={tr('graphicsBackend')}
value={form.graphics}
onChange={(graphics) => set({ graphics })}
options={[
{ value: 'reims-vgpu', label: tr('graphicsReimsShort') },
{ value: 'vmware-svga', label: tr('graphicsSvgaShort') },
]}
/>
}
/>
<SetRow
{...rowProps('gpu')}
title={tr('gpuSelect')}
desc={realGPUs.length === 0 ? <span className="warn-text">{tr('gpuUnavailableHint')}</span> : undefined}
disabled={!vgpu}
reason={tr('gpuSvgaReason')}
block={<OptionCards label={tr('gpuSelect')} value={gpuOptions.find((o) => normPath(o.value) === normPath(form.gpu))?.value} onChange={(gpu) => set({ gpu })} options={gpuOptions} />}
/>
</SetGroup>
<SetGroup title={tr('displayGroup')}>
<SetRow
{...rowProps('resolution')}
error={issueOf('resolution') ?? (resBad ? tr('resInvalid') : undefined)}
title={tr('resolution')}
desc={host.primary_display
? tr('hostDisplayHint', {
w: host.primary_display.width,
h: host.primary_display.height,
scale: host.primary_display.scale_pct || 100,
rec: host.recommended_resolution || '1920x1080',
})
: undefined}
block={
<>
<OptionCards
label={tr('resolution')}
value={resValue}
onChange={(v) => {
if (v === CUSTOM) { setCustomRes(true); return }
setCustomRes(false)
set({ resolution: v })
}}
options={[
...presets.map((p) => ({
value: p.resolution,
title: p.label,
art: resArt(p.resolution),
badges: [p.hidpi ? tr('hidpiPresetBadge') : '', p.recommended ? tr('recommendedBadge') : ''].filter(Boolean),
})),
{ value: CUSTOM, title: tr('resCustom'), sub: tr('resCustomSub'), art: <span className="screen-art custom" aria-hidden="true" /> },
]}
/>
{customRes && (
<input
className="input mono res-input"
aria-label={tr('resolution')}
placeholder="2560x1600"
autoFocus
value={form.resolution ?? ''}
onChange={(e) => set({ resolution: e.target.value })}
/>
)}
</>
}
/>
<SetRow
{...rowProps('displays')}
title={tr('displays')}
desc={(host.displays?.length ?? 0) > 1 ? tr('multiDisplayHint', { n: host.displays?.length ?? 1 }) : undefined}
control={
<Segmented
label={tr('displays')}
value={form.displays ?? 1}
onChange={(displays) => set({ displays })}
options={[1, 2, 3, 4].map((n) => ({ value: n, label: String(n) }))}
/>
}
/>
<SetRow
{...rowProps('borderless')}
title={tr('fullscreenLaunch')}
desc={tr('fullscreenLaunchHint')}
control={<Switch label={tr('fullscreenLaunch')} checked={!!form.borderless} onChange={(borderless) => set({ borderless })} />}
/>
</SetGroup>
</>
)
const storage = (
<>
<SetGroup title={tr('catStorage')}>
<SetValue title={tr('fieldDisk')} value={detail.disk} mono />
<SetRow
{...rowProps('disk_controller')}
title={tr('diskController')}
desc={detail.has_installer
? tr('diskControllerInstallHint')
: form.disk_controller === 'ahci' ? tr('diskControllerNvmeHint') : undefined}
disabled={detail.has_installer}
reason={tr('diskControllerWarn')}
control={
<Segmented
label={tr('diskController')}
value={form.disk_controller}
onChange={(disk_controller) => set({ disk_controller })}
options={[
{ value: 'ahci', label: 'SATA' },
{ value: 'nvme', label: 'NVMe' },
{ value: 'virtio', label: 'VirtIO' },
]}
/>
}
/>
</SetGroup>
<SetGroup title={tr('catNetwork')}>
<SetRow
{...rowProps('network')}
title={tr('enableNetwork')}
desc={tr('networkDesc')}
control={<Switch label={tr('enableNetwork')} checked={!!form.network} onChange={(network) => set({ network })} />}
/>
<SetRow
{...rowProps('ssh_port')}
title={tr('sshForward')}
desc={sshOn ? <code className="inline-code">{sshCommand(form.ssh_port ?? 0)}</code> : tr('sshOffDesc')}
disabled={!form.network}
reason={tr('sshNeedsNetwork')}
control={
<div className="hstack">
{sshOn && (
<NumberField label={tr('sshPort')} value={form.ssh_port ?? 0} min={1} max={65535} onChange={(ssh_port) => set({ ssh_port })} />
)}
<Switch
label={tr('sshForward')}
checked={sshOn}
onChange={(on) => set({ ssh_port: on ? (base.ssh_port || 2222) : 0 })}
/>
</div>
}
/>
</SetGroup>
</>
)
const input = (
<>
<SetGroup title={tr('catInput')} note={tr('macKeymapHint')}>
<SetRow
{...rowProps('capture')}
title={tr('captureInput')}
desc={tr('captureInputHint')}
control={<Switch label={tr('captureInput')} checked={!!form.capture} onChange={(capture) => set({ capture })} />}
/>
</SetGroup>
<SetGroup title={tr('catAudio')}>
<SetRow
{...rowProps('audio')}
title={tr('enableAudio')}
desc={tr('audioDesc')}
control={<Switch label={tr('enableAudio')} checked={!!form.audio} onChange={(audio) => set({ audio })} />}
/>
</SetGroup>
</>
)
const irqMode = parseKernelIrqchip(form.extra_args)
const advanced = (
<>
<SetGroup title={tr('catLogs')}>
<SetRow
{...rowProps('logs')}
title={tr('enableLogs')}
control={<Switch label={tr('enableLogs')} checked={!!form.logs} onChange={(logs) => set({ logs })} />}
/>
<SetRow
{...rowProps('log_level')}
title={tr('logLevel')}
block={
<div className="stack-2">
<Segmented
label={tr('logLevel')}
value={customLog ? CUSTOM : (form.log_level || 'info')}
onChange={(v) => {
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 && (
<input
className="input mono"
aria-label={tr('logLevel')}
placeholder="info,reims=debug"
value={form.log_level ?? ''}
onChange={(e) => set({ log_level: e.target.value })}
/>
)}
</div>
}
/>
</SetGroup>
<SetGroup title={tr('groupPerformance')}>
<SetRow
{...rowProps('extra_args')}
dirty={parseKernelIrqchip(form.extra_args) !== parseKernelIrqchip(base.extra_args)}
onReset={() => set({ extra_args: applyKernelIrqchip(form.extra_args, parseKernelIrqchip(base.extra_args)) })}
error={undefined}
field={undefined}
title={tr('kernelIrqchipLabel')}
desc={
<>
<span className={`badge ${optBadgeClass(irqOpt?.status)}`}>{optStatusLabel(locale, irqOpt?.status)}</span>
{' '}
<span className={irqOpt?.status === 'unavailable' && irqOpt.detail?.startsWith('0x') ? 'warn-text' : ''}>{kernelIrqchipHint(locale, irqOpt)}</span>
</>
}
control={
<Segmented
label={tr('kernelIrqchipLabel')}
value={irqMode}
onChange={(mode) => 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') },
]}
/>
}
/>
</SetGroup>
<SetGroup title={tr('groupQemu')}>
<SetRow
{...rowProps('stop_timeout')}
title={tr('stopTimeout')}
desc={tr('stopTimeoutHint')}
control={<NumberField label={tr('stopTimeout')} value={form.stop_timeout ?? 90} min={0} max={3600} onChange={(stop_timeout) => set({ stop_timeout })} />}
/>
<SetRow
{...rowProps('extra_args')}
title={tr('extraArgs')}
desc={tr('extraArgsDesc')}
block={<input className="input mono" aria-label={tr('extraArgs')} value={form.extra_args ?? ''} onChange={(e) => set({ extra_args: e.target.value })} />}
/>
</SetGroup>
</>
)
const pages: Record<Cat, React.ReactNode> = { general, compute, display, storage, input, advanced }
return (
<Modal
className="settings-dialog"
title={tr('settingsTitle', { name: detail.name })}
subtitle={`${tr(running ? 'state_running' : 'state_stopped')} · ${tr('appliesNextStart')}`}
closeLabel={tr('close')}
dismissable={!busy}
onClose={onClose}
>
<div className="settings-split" onKeyDown={onKeyDown}>
<nav className="settings-nav" aria-label={tr('settings')}>
{CATS.map((c) => {
const n = changedIn(c.id)
const bad = issueIn(c.id)
const Icon = c.icon
return (
<button
key={c.id}
type="button"
className="nav-item"
aria-selected={cat === c.id}
aria-current={cat === c.id ? 'page' : undefined}
onClick={() => setCat(c.id)}
>
<span className={`nav-icon-badge nav-icon-cat-${c.id}`} aria-hidden="true"><Icon size={14} /></span>
<span className="nav-label">{tr(c.label)}</span>
{bad
? <CircleAlert size={14} className="nav-issue" aria-label={tr('navHasIssue')} />
: n > 0 && <span className="nav-count" aria-label={tr('pendingChanges', { n })}>{n}</span>}
</button>
)
})}
</nav>
<div className="settings-pane" ref={pane}>
<h2 className="settings-pane-title">{tr(CATS.find((c) => c.id === cat)!.label)}</h2>
{err && <div className="notice notice-error">{err}</div>}
{strayIssues.length > 0 && (
<div className="notice notice-error">
<ul>{strayIssues.map((i) => <li key={i.field + i.code}>{i.message}</li>)}</ul>
</div>
)}
{pages[cat]}
</div>
</div>
<div className="dialog-foot">
<span className="foot-status" aria-live="polite">
{changed.length > 0
? <><span className="dirty-dot" aria-hidden="true" />{tr('pendingChanges', { n: changed.length })}</>
: <span className="muted">{tr('noChanges')}</span>}
{changed.length > 0 && (
<button type="button" className="link-btn" disabled={busy} onClick={resetAll}>{tr('resetAll')}</button>
)}
</span>
<span className="hstack">
<Button variant="ghost" disabled={busy} onClick={onClose}>{tr('cancel')}</Button>
<Button variant="primary" busy={busy} disabled={changed.length === 0 || localBlock} onClick={handleSave} title="Ctrl+S">
{tr('save')}
</Button>
</span>
</div>
</Modal>
)
}