import { Check, ChevronRight, CircleAlert, CircleCheck, CloudDownload, Copy, Disc3, HardDrive, LucideIcon, Package } from 'lucide-react' import React, { Suspense, lazy, useEffect, useState } from 'react' import '../i18n/domains/wizard.gen' import '../i18n/domains/settings.gen' import { I18nKey, locText, parseAppError, t } from '../i18n' import { GUEST_LANG_PRESETS, guestLangOptions, MEMORY_MARKS, controllerLabel, defaultGuestLang, findGPU, formatMemory, gpuCompatHint, gpuLabel, gpuOptionValue, guestLangLabel, memorySafeLimitGB, parseMemoryGB, recommendedCPUs, canKeepDisplayPreset, fullscreenDisplayPresets, FullscreenDisplayPreset, hidpiLooksLike, hostDisplayAdvice, hostDisplayDesc, windowDisplayPresets, recommendedMemoryGB, recommendedResolution, shortGPUName, splitLangLabel, sshCommand, } from '../lib/format' import { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, Task, ValidationIssue } from '../types' import { findActiveOfflineTask, taskInstallerPhase } from '../lib/tasks' import { Button, IconButton } from '../ui/controls' import { NumberField, PopupSelect, RangeField, Segmented, SetGroup, SetRow, Switch } from '../ui/settings' import { Modal } from '../ui/dialog' import { api } from '../wails' const SchemaForm = lazy(() => import('./SchemaForm').then((m) => ({ default: m.SchemaForm }))) const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos' /** Reopen the wizard where the user left it (e.g. after a failed create). */ export interface WizardDraft { opts: CreateOpts step: number } interface Props { locale: Locale host: HostReport fixedModeSupported?: boolean tasks?: Task[] draft?: WizardDraft | null onClose: () => void /** Called with the cleaned payload; the caller runs the create in the background. */ onSubmit: (payload: CreateOpts, draft: WizardDraft) => void } const REVIEW_STEP = 5 // Which wizard step owns each ValidationIssue.field (internal/macos/reims/reims.go ValidateCreate). const STEP_OF_FIELD: Record = { installer: 1, disk: 1, macos: 1, guest_lang: 1, cpus: 2, memory: 2, disk_size: 3, disk_controller: 3, graphics: 4, gpu: 4, resolution: 4, displays: 4, ssh_port: 4, } const stepOfIssue = (i: ValidationIssue) => STEP_OF_FIELD[i.field] ?? REVIEW_STEP // Step ① as large cards, one per way to get macOS (Parallels / UTM style). const SOURCES: { mode: 'offline' | 'apple' | 'installer' | 'disk'; icon: LucideIcon; title: I18nKey; sub: I18nKey }[] = [ { mode: 'offline', icon: Package, title: 'srcOfflineTitle', sub: 'srcOfflineSub' }, { mode: 'apple', icon: CloudDownload, title: 'srcAppleTitle', sub: 'srcAppleSub' }, { mode: 'installer', icon: Disc3, title: 'srcInstallerTitle', sub: 'srcInstallerSub' }, { mode: 'disk', icon: HardDrive, title: 'srcDiskTitle', sub: 'srcDiskSub' }, ] export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported = false, tasks = [], draft, onClose, onSubmit }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const [step, setStep] = useState(draft?.step ?? 1) // Once the user has reached the review step, keep validating so step markers stay current. const [reviewed, setReviewed] = useState(draft?.step === REVIEW_STEP) const [checking, setChecking] = useState(false) const [err, setErr] = useState('') const [issues, setIssues] = useState([]) const [cmdPreview, setCmdPreview] = useState('') const [drivers, setDrivers] = useState([]) const [driverID, setDriverID] = useState(BUILTIN_MACOS_DRIVER) const [driverOpts, setDriverOpts] = useState>({}) const [driverCreating, setDriverCreating] = useState(false) useEffect(() => { let live = true api.ListDrivers().then((list) => { if (live) setDrivers(list ?? []) }).catch((e) => console.warn('[wizard] ListDrivers failed:', e)) return () => { live = false } }, []) const activeDriver = drivers.find((d) => d.id === driverID) const isCustomDriver = driverID !== BUILTIN_MACOS_DRIVER && !!activeDriver const [opts, setOpts] = useState(draft?.opts ?? { name: 'macos-tahoe', dir: '', // Offline by default: installs an exact release without guest network access // (`reims-ctl create --help`, upstream 3731afd). source_mode: 'offline', macos: '', offline: true, installer: '', cpus: recommendedCPUs(host), memory: `${recommendedMemoryGB(host)}G`, disk_size: '128G', disk: '', disk_mode: 'copy', disk_controller: 'nvme', graphics: host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga', // Default to "auto" rather than a DriverStore FileRepository ICD path so // Windows GPU driver updates never break existing VM configs. gpu: 'auto', resolution: recommendedResolution(host), displays: 1, borderless: false, capture: false, audio: true, network: false, ssh_port: 0, logs: true, guest_lang: defaultGuestLang(locale), start: true, }) const set = (patch: Partial) => setOpts((o) => ({ ...o, ...patch })) const windowPresets = windowDisplayPresets(host, fixedModeSupported) const fullscreenPresets = fullscreenDisplayPresets(host) const buildPayload = (): CreateOpts => { const p: CreateOpts = { ...opts, offline: opts.source_mode === 'offline' } if (p.source_mode === 'offline') { p.installer = '' p.disk = '' } else if (p.source_mode === 'apple') { p.installer = '' p.disk = '' } else if (p.source_mode === 'installer') { p.macos = '' p.disk = '' } else { p.macos = '' p.installer = '' p.disk_size = '' } return p } useEffect(() => { if (step === REVIEW_STEP) setReviewed(true) }, [step]) // Offline releases come from Apple's catalog (a few seconds); downloaded ones are marked. const [releases, setReleases] = useState(null) const [cached, setCached] = useState([]) const [releasesErr, setReleasesErr] = useState('') useEffect(() => { if (opts.source_mode !== 'offline' || releases) return let live = true api.ListInstallers().then((l) => { if (live) setCached(l ?? []) }).catch((e) => console.warn('[wizard] ListInstallers failed:', e)) api.ListOfflineReleases() .then((list) => { if (!live) return setReleases(list ?? []) if (!opts.macos && list && list.length > 0) set({ macos: list[0].version }) }) .catch((e) => { if (live) setReleasesErr(String(e).replace(/^Error:\s*/, '')) }) return () => { live = false } }, [opts.source_mode]) const isCached = (v: string) => cached.some((c) => c.kind === 'offline' && !c.partial && c.version === v) const activeRelease = (v: string) => findActiveOfflineTask(tasks, v) const chosenRelease = releases?.find((r) => r.version === opts.macos) // reims-util pre-allocates the whole image as it starts (19.7 GB for an 18.4 GB release, measured). const needGB = chosenRelease && !isCached(chosenRelease.version) && !activeRelease(chosenRelease.version) ? Math.ceil((chosenRelease.size * 1.1) / 1e9) : 0 useEffect(() => { if (!reviewed && step !== REVIEW_STEP) return let live = true setChecking(true) const timer = setTimeout(() => { const payload = buildPayload() Promise.all([api.ValidateCreate(payload), api.PreviewCreate(payload)]) .then(([iss, cmd]) => { if (!live) return setIssues(iss ?? []) setCmdPreview(cmd) setErr('') }) .catch((e) => { if (live) setErr(parseAppError(e).summary) }) .finally(() => { if (live) setChecking(false) }) }, 200) return () => { live = false; clearTimeout(timer) } }, [step, reviewed, opts]) const pickDir = async () => { const dir = await api.PickDirectory(tr('vmDir')) if (dir) set({ dir }) } const pickFile = async (field: 'installer' | 'disk', pattern: string) => { const f = await api.PickFile(tr(field === 'installer' ? 'sourceInstaller' : 'sourceDisk'), pattern) if (f) set({ [field]: f }) } const handleCreate = () => onSubmit(buildPayload(), { opts, step: REVIEW_STEP }) const issueSteps = new Set(reviewed ? issues.map(stepOfIssue) : []) const realGPUs = (host.gpus ?? []).filter((g) => g.kind !== 'virtual') const selectedGPU = findGPU(host, opts.gpu) const selectedGPUHint = gpuCompatHint(locale, selectedGPU) 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(opts.memory) ?? memRec) const steps: I18nKey[] = ['step1', 'step2', 'step3', 'step4', 'step5'] return (
{err &&
{err}
}
{step === 1 && ( <> {drivers.length > 1 && ( ({ value: d.id, label: locText(d.name, locale, d.id), }))} onChange={(id) => { setDriverID(id); setErr('') }} /> } /> )} {isCustomDriver ? (
set({ name: e.target.value })} />} /> {activeDriver.create_schema && ( )}
) : ( <>
{SOURCES.map((s) => { const Icon = s.icon const on = opts.source_mode === s.mode return ( ) })}
{opts.source_mode === 'apple' && ( set({ macos })} options={[{ value: 'tahoe', label: 'macOS Tahoe' }]} />} /> )} {opts.source_mode === 'offline' && ( {tr('offlineListFailedDetail', { err: releasesErr })} : needGB > 0 && host.free_disk_gb > 0 && host.free_disk_gb < needGB + 10 ? {tr('offlineSpaceWarn', { free: host.free_disk_gb.toFixed(0), need: needGB })} : tr('offlineHint')} control={!releases ? {releasesErr ? '—' : tr('offlineLoading')} : ( set({ macos })} options={releases.map((r) => { const active = activeRelease(r.version) const statusTag = isCached(r.version) ? tr('offlineCached') : active ? tr(taskInstallerPhase(active.primary) === 'queued' ? 'offlineQueued' : 'offlineDownloading') : '' return { value: r.version, label: `macOS ${r.version}`, detail: `${(r.size / 1e9).toFixed(1)} GB${statusTag ? ` · ${statusTag}` : ''}`, } })} /> )} /> )} {(opts.source_mode === 'installer' || opts.source_mode === 'disk') && (() => { const isInstaller = opts.source_mode === 'installer' const file = (isInstaller ? opts.installer : opts.disk) ?? '' return ( {file} : tr('wizNoFile')} control={ } /> ) })()} set({ guest_lang })} options={guestLangOptions(locale)} /> } /> )} )} {step === 2 && ( threads - 2 && threads > 2 ? {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) }))} /> } /> memSafe ? {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) }))} /> } /> )} {step === 3 && ( {opts.source_mode !== 'disk' ? ( set({ disk_size })} options={Array.from(new Set(['64G', '128G', '256G', '512G', opts.disk_size ?? '128G'])).map((v) => ({ value: v, label: formatMemory(v) }))} /> } /> ) : ( set({ disk_mode })} options={[ { value: 'copy' as const, label: tr('diskModeCopy') }, { value: 'in-place' as const, label: tr('diskModeInPlace') }, ]} /> } /> )} set({ disk_controller })} options={[ { value: 'nvme' as const, label: 'NVMe' }, { value: 'ahci' as const, label: 'SATA' }, ...(opts.source_mode === 'disk' ? [{ value: 'virtio' as const, label: 'VirtIO' }] : []), ]} /> } /> )} {step === 4 && ( <> set({ graphics })} options={[ { value: 'reims-vgpu' as const, label: tr('graphicsReimsShort') }, { value: 'vmware-svga' as const, label: tr('graphicsSvgaShort') }, ]} /> } /> {tr('gpuUnavailableHint')} ) : selectedGPUHint ? ( {selectedGPUHint}{' '} ) : undefined } control={ set({ gpu })} options={[ { value: 'auto', label: tr('gpuAutoTitle'), detail: host.recommended_gpu ? shortGPUName(host.recommended_gpu.name) : undefined }, ...realGPUs.map((g) => ({ value: gpuOptionValue(g, realGPUs), label: shortGPUName(g.name), detail: g.compat === 'unsupported' ? tr('gpuCompatUnsupported') : g.compat === 'warn' ? tr('gpuCompatWarn') : g.vulkan_version ? `Vulkan ${g.vulkan_version}` : undefined, })), ]} /> } /> set({ resolution })} options={(opts.borderless ? fullscreenPresets : windowPresets).map((p: FullscreenDisplayPreset) => ({ value: p.resolution, label: p.label, detail: [ p.hidpi ? `${tr('hidpiPresetBadge')} · ${hidpiLooksLike(p.resolution, tr) ?? ''}` : '', p.scaleBadge ?? '', p.native ? tr('resNativeBadge') : '', p.scaleToFit ? tr('resScaleToFitWindow') : '', p.recommended ? tr('recommendedBadge') : '', ].filter(Boolean).join(' · ') || undefined, }))} /> } /> set({ displays })} options={[1, 2, 3, 4].map((d) => ({ value: d, label: String(d) }))} /> } /> set({ network })} />} /> 0 ? {sshCommand(opts.ssh_port ?? 0)} : tr('sshOffDesc')} disabled={!opts.network} reason={tr('sshNeedsNetwork')} control={
{(opts.ssh_port ?? 0) > 0 && ( set({ ssh_port })} /> )} 0} onChange={(on) => set({ ssh_port: on ? 2222 : 0 })} />
} /> set({ audio })} />} /> set({ capture })} />} /> { const list = borderless ? fullscreenPresets : windowPresets const keep = list.some((p) => canKeepDisplayPreset(p, opts.resolution, borderless)) const fallback = list.find((p) => p.recommended)?.resolution ?? list[0]?.resolution ?? opts.resolution set(keep ? { borderless } : { borderless, resolution: fallback }) }} /> } /> set({ logs })} />} />
)} {step === 5 && ( set({ name })} onPickDir={pickDir} onDir={(dir) => set({ dir })} onStartAfter={(start) => set({ start })} /> )}
{isCustomDriver ? ( ) : step < REVIEW_STEP ? ( ) : ( )}
) } interface ReviewProps { locale: Locale host: HostReport opts: CreateOpts issues: ValidationIssue[] checking: boolean command: string onEdit: (step: number) => void onName: (name: string) => void onDir: (dir: string) => void onPickDir: () => void onStartAfter: (start: boolean) => void } type Row = { label: string; value: string; mono?: boolean } const fileName = (p?: string) => (p ?? '').split(/[\\/]/).pop() || (p ?? '') /** Step ⑤: what will be created, grouped by the step that set it, with the CLI equivalent folded away. */ const Review: React.FC = ({ locale, host, opts, issues, checking, command, onEdit, onName, onDir, onPickDir, onStartAfter }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const [copied, setCopied] = useState(false) const onOff = (b?: boolean) => tr(b ? 'summaryOn' : 'off') const source = opts.source_mode === 'offline' ? tr('summaryOfflineSource', { v: opts.macos ?? '' }) : opts.source_mode === 'apple' ? tr('summaryAppleSource', { v: opts.macos === 'tahoe' ? 'macOS 26 Tahoe' : (opts.macos ?? '') }) : opts.source_mode === 'installer' ? tr('summaryInstallerSource', { file: fileName(opts.installer) }) : tr('summaryDiskSource', { file: fileName(opts.disk) }) const res = (opts.resolution ?? '').replace(/x/i, ' × ') const graphicsRows: Row[] = opts.graphics === 'reims-vgpu' ? [ { label: tr('factGraphics'), value: `${gpuLabel(locale, opts.gpu, host)} · reims-vgpu` }, { label: tr('resolution'), value: (opts.displays ?? 1) > 1 ? `${opts.displays} × (${res})` : res }, ] : [{ label: tr('factGraphics'), value: `${tr('softwareGraphics')} · vmware-svga` }] const groups: { step: number; title: I18nKey; rows: Row[] }[] = [ { step: 1, title: 'step1', rows: [ { label: tr('summarySource'), value: source }, { label: tr('guestLangShort'), value: guestLangLabel(locale, opts.guest_lang) }, ], }, { step: 2, title: 'step2', rows: [ { label: tr('factCPU'), value: tr('cores', { n: opts.cpus }) }, { label: tr('factMemory'), value: formatMemory(opts.memory) }, ], }, { step: 3, title: 'step3', rows: [ ...(opts.source_mode !== 'disk' ? [{ label: tr('diskSize'), value: tr('summaryDiskGrow', { size: formatMemory(opts.disk_size ?? '') }) }] : [{ label: tr('diskMode'), value: tr(opts.disk_mode === 'in-place' ? 'diskModeInPlace' : 'diskModeCopy') }]), { label: tr('diskController'), value: controllerLabel(opts.disk_controller ?? 'nvme') }, ], }, { step: 4, title: 'step4', rows: [ ...graphicsRows, { label: tr('fieldAudio'), value: onOff(opts.audio) }, { label: tr('fieldNetwork'), value: onOff(opts.network) }, { label: tr('captureInput'), value: onOff(opts.capture) }, { label: tr('summarySSH'), value: opts.ssh_port ? tr('summarySSHPort', { n: opts.ssh_port }) : tr('off') }, { label: tr('summaryLogs'), value: onOff(opts.logs) }, ], }, ] const nameIssue = issues.find((i) => i.field === 'name')?.message const general = issues.filter((i) => stepOfIssue(i) === REVIEW_STEP && i.field !== 'name') const copy = async () => { try { await navigator.clipboard.writeText(command) setCopied(true) setTimeout(() => setCopied(false), 1500) } catch (e) { // clipboard unavailable; the text stays selectable console.warn('[wizard] clipboard write failed:', e) } } return ( <> onName(e.target.value)} spellCheck={false} />} /> {opts.dir} : tr('summaryDefaultDir')} control={
{opts.dir && }
} /> } />
{checking && issues.length === 0 ? (
{tr('validationChecking')}
) : issues.length > 0 ? (
{tr('issuesCount', { n: issues.length })}
) : (
{tr('validationPassed')}
)} {general.length > 0 && (
    {general.map((i) =>
  • {i.message}
  • )}
)}
{groups.map((g) => { const own = issues.filter((i) => stepOfIssue(i) === g.step) return (
{tr(g.title)}
{g.rows.map((r) => (
{r.label}
{r.value}
))}
{own.length > 0 && (
    {own.map((i) =>
  • {i.message}
  • )}
)}
) })}
{tr('commandToggle')}
{tr('commandToggleHint')}
{command || '…'}
: } disabled={!command} onClick={copy} />
) }