Files
Reims-Go/frontend/src/App.tsx
T
Nwflower 1e80caa255 Merge pull request #13 from icaruszezen/fix/sync-installer-download-progress
Sync VM creation macOS installer downloads with the Installers page, sidebar busy dot, and CreateWizard via the in-process installer coordinator (relates to #11).

Review hardening applied during merge:
- Serialize initial phase/snapshot replay against live subscriber updates in ensureInstallerForTask to avoid backward progress overwrites
- Guard installerDownloads.complete with defer so unexpected download panics cannot leak active entries or deadlock joined waiters
- Regenerate i18n catalogs with cmd/i18ngen after merging with main
2026-11-30 01:08:03 -07:00

1261 lines
52 KiB
TypeScript

import { Minus, Moon, Square, Sun, X } from 'lucide-react'
import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react'
import type { WizardDraft } from './components/CreateWizard'
import { DeleteDialog } from './components/DeleteDialog'
import { CloneDialog } from './components/CloneDialog'
import { OnlineRecoveryDialog } from './components/OnlineRecoveryDialog'
import { SendTextDialog } from './components/SendTextDialog'
import type { ThemeMode } from './components/AppSettingsPage'
import { LogPanel, LogTab } from './components/LogPanel'
import { TitleMenus } from './components/TitleMenus'
import { UpdateCapsule, UpdatePhase } from './components/UpdateCapsule'
import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar'
import { VMAction, VMPage } from './components/VMPage'
import { buildFallbackChain, I18nKey, localeDir, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format'
import { LogLine, appendLog } from './lib/logs'
import { macOSMajor } from './lib/macosRelease'
import { currentTask, finishedTaskTTL, isActiveInstallerTask, pruneFinishedTasks, upsertTask } from './lib/tasks'
import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, notifyInteractiveThemeState, type UIStateSnapshot } from './lib/themeEngine'
import { latestVMStats } from './lib/vmStats'
import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail } from './types'
import { Button, Tip, TooltipProvider } from './ui/controls'
import { Modal } from './ui/dialog'
import { Toaster, useToasts } from './ui/toast'
import { api, events, OnFileDrop, OnFileDropOff, WindowMinimise, WindowToggleMaximise } from './wails'
// Opened on demand, so each is its own chunk and stays out of the startup
// bundle: the wizard, VM settings and affinity dialogs, first-run setup, and
// the Engine / Installers / Settings pages.
const CreateWizard = lazy(() => import('./components/CreateWizard').then((m) => ({ default: m.CreateWizard })))
const SettingsModal = lazy(() => import('./components/SettingsModal').then((m) => ({ default: m.SettingsModal })))
const AffinityDialog = lazy(() => import('./components/AffinityDialog').then((m) => ({ default: m.AffinityDialog })))
const Setup = lazy(() => import('./components/Setup').then((m) => ({ default: m.Setup })))
const HostView = lazy(() => import('./components/HostView').then((m) => ({ default: m.HostView })))
const InstallersPage = lazy(() => import('./components/InstallersPage').then((m) => ({ default: m.InstallersPage })))
const PluginsPage = lazy(() => import('./components/PluginsPage').then((m) => ({ default: m.PluginsPage })))
const AppSettingsPage = lazy(() => import('./components/AppSettingsPage').then((m) => ({ default: m.AppSettingsPage })))
const AboutPage = lazy(() => import('./components/AboutPage').then((m) => ({ default: m.AboutPage })))
const errText = (e: unknown) => parseAppError(e).summary
const failKey: Record<VMAction, I18nKey> = {
start: 'failStart',
focus: 'failFocus',
screenshot: 'failScreenshot',
stop: 'failStop',
forceStop: 'failStop',
restart: 'failRestart',
eject: 'failEject',
finishInstall: 'failFinishInstall',
enterRecovery: 'failEnterRecovery',
attachInstaller: 'failAttachInstaller',
attachGuestTools: 'failGuestTools',
detachGuestTools: 'failGuestTools',
openSharedFolder: 'failOpenFolder',
upgradeNVMe: 'failUpgradeNVMe',
exportDiagnostics: 'failExportDiagnostics',
cloneVM: 'failCloneVM',
type: 'failType',
sendText: 'failType',
delete: 'failDelete',
openFolder: 'failOpenFolder',
}
export const App: React.FC = () => {
const [state, setState] = useState<AppState | null>(null)
const [selected, setSelected] = useState<string>(HOST_ID)
const [appUpdate, setAppUpdate] = useState<AppUpdateInfo | null>(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.
const stateReady = !!state
useEffect(() => {
if (!stateReady) return
const check = () => { api.CheckAppUpdate(false).then(setAppUpdate).catch(() => {}) }
check()
const id = window.setInterval(check, 6 * 60 * 60 * 1000)
return () => window.clearInterval(id)
}, [stateReady])
const [detail, setDetail] = useState<VMDetail | null>(null)
const [detailRevision, setDetailRevision] = useState(0)
const [showWizard, setShowWizard] = useState(false)
const [wizardDraft, setWizardDraft] = useState<WizardDraft | null>(null)
const [showSettings, setShowSettings] = useState(false)
const [affinityTarget, setAffinityTarget] = useState<string | null>(null)
const [affinityVersion, setAffinityVersion] = useState(0)
const [deleteTarget, setDeleteTarget] = useState<string | null>(null)
const [cloneSource, setCloneSource] = useState<string | null>(null)
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
const [sendTextTarget, setSendTextTarget] = useState<string | null>(null)
const [busy, setBusy] = useState<Record<string, VMAction>>({})
const [dropping, setDropping] = useState(false)
const [loadError, setLoadError] = useState('')
const [themeMode, setThemeModeState] = useState<ThemeMode>(() => {
try {
const saved = localStorage.getItem('reims-go-theme')
if (saved === 'dark' || saved === 'light') return saved
} catch {}
return 'system'
})
const [sysDark, setSysDark] = useState<boolean>(() =>
typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-color-scheme: dark)').matches,
)
const [reducedMotion, setReducedMotion] = useState<boolean>(() =>
typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches,
)
const [pluginUI, setPluginUI] = useState<PluginUIContributions | null>(null)
const [activeThemePayload, setActiveThemePayload] = useState<ActiveThemePayload | null>(null)
const [themeRevision, setThemeRevision] = useState(0)
const activeThemeContrib = activeThemePayload?.theme
?? (pluginUI?.themes ?? []).find((th) => th.id === (activeThemePayload?.theme_id || 'builtin.theme.default'))
?? null
const themeAppearanceCap: 'light' | 'dark' | 'both' =
pluginUI === null
? 'both'
: activeThemeContrib
? (activeThemeContrib.appearance === 'light' || activeThemeContrib.appearance === 'dark' ? activeThemeContrib.appearance : 'both')
: 'light'
const canLight = themeAppearanceCap === 'both' || themeAppearanceCap === 'light'
const canDark = themeAppearanceCap === 'both' || themeAppearanceCap === 'dark'
const theme: 'light' | 'dark' = !canDark ? 'light' : !canLight ? 'dark' : (themeMode === 'system' ? (sysDark ? 'dark' : 'light') : themeMode)
const effectiveThemeMode: ThemeMode = !canDark ? 'light' : !canLight ? 'dark' : themeMode
useEffect(() => {
document.documentElement.dataset.theme = theme
events.emitTheme(theme)
}, [theme])
useEffect(() => {
document.documentElement.dataset.motion = reducedMotion ? 'reduced' : 'full'
}, [reducedMotion])
useEffect(() => {
const mq = window.matchMedia?.('(prefers-color-scheme: dark)')
if (!mq) return
const onChange = (e: MediaQueryListEvent) => setSysDark(e.matches)
mq.addEventListener('change', onChange)
return () => mq.removeEventListener('change', onChange)
}, [])
useEffect(() => {
const mq = window.matchMedia?.('(prefers-reduced-motion: reduce)')
if (!mq) return
const onChange = (e: MediaQueryListEvent) => setReducedMotion(e.matches)
mq.addEventListener('change', onChange)
return () => mq.removeEventListener('change', onChange)
}, [])
const setThemeMode = (mode: ThemeMode) => {
setThemeModeState(mode)
try {
if (mode === 'system') localStorage.removeItem('reims-go-theme')
else localStorage.setItem('reims-go-theme', mode)
} catch {}
}
const toggleTheme = () => {
if (!canLight || !canDark) return
setThemeMode(theme === 'light' ? 'dark' : 'light')
}
// Sidebar can be hidden (Ctrl+B or the title-bar toggle); remembered per user.
const [sidebarOpen, setSidebarOpen] = useState<boolean>(() => {
try { return localStorage.getItem('reims-go-sidebar') !== 'hidden' } catch { return true }
})
const toggleSidebar = () => setSidebarOpen((open) => {
try { localStorage.setItem('reims-go-sidebar', open ? 'hidden' : 'shown') } catch {}
return !open
})
const [logsOpen, setLogsOpen] = useState(false)
const [logTab, setLogTab] = useState<LogTab>('app')
const [logLines, setLogLines] = useState<LogLine[]>([])
const [serialLog, setSerialLog] = useState('')
const [qemuLog, setQemuLog] = useState('')
const [unseenErrors, setUnseenErrors] = useState(0)
const logsOpenRef = useRef(logsOpen)
logsOpenRef.current = logsOpen
const [taskMap, setTaskMap] = useState<Record<string, Task>>({})
const onTaskRef = useRef<(task: Task) => void>(() => {})
const notifiedTasks = useRef(new Map<string, number>())
const [setupStage, setSetupStage] = useState<'folder' | 'runtime' | null>(null)
const toasts = useToasts()
const refresh = useCallback(async (reloadDetail = false) => {
try {
const s = await api.GetState()
setState(s)
setLoadError('')
setSelected((cur) => {
if (PAGE_IDS.includes(cur)) return cur
if ((s.vms ?? []).some((v) => v.name === cur)) return cur
return s.vms && s.vms.length > 0 ? s.vms[0].name : HOST_ID
})
if (reloadDetail) setDetailRevision((revision) => revision + 1)
} catch (e) {
setLoadError(errText(e))
}
}, [])
useEffect(() => {
Promise.all([
api.GetPluginUIContributions().catch(() => null),
refresh(),
]).then(([pui]) => {
if (pui) {
setPluginLocales(pui.locales)
setPluginUI(pui)
} else {
setPluginUI({} as PluginUIContributions)
}
})
events.emitUIPong()
const offPing = events.onUIPing(() => { events.emitUIPong() })
const offState = events.onStateChanged(() => {
refresh(true)
setThemeRevision((r) => r + 1)
})
// Logs never pop the panel open (docs/design-guidelines.md §7.3); errors only bump a badge.
const offLog = events.onLog((entry) => {
if (!entry || typeof entry !== 'object') return
const lineText = typeof entry.line === 'string' ? entry.line : String(entry.line ?? '')
if (!logsOpenRef.current && /\b(error|failed|fatal|panic)\b/i.test(lineText)) {
setUnseenErrors((n) => n + 1)
}
setLogLines((prev) => appendLog(prev, entry))
})
api.GetActiveTheme().then(setActiveThemePayload).catch(() => {})
// Tasks: seed from the backend, then follow events.
api.GetTasks().then((list) => {
setTaskMap((prev) => (list ?? []).reduce(upsertTask, prev))
}).catch(() => {})
const offTask = events.onTask((task) => onTaskRef.current(task))
const onVisibility = () => {
if (!document.hidden) {
events.emitUIPong()
void refresh()
}
}
document.addEventListener('visibilitychange', onVisibility)
// Keep host telemetry (memory load, free disk) fresh while the window is visible.
const hostTimer = window.setInterval(() => {
if (!document.hidden) void refresh()
const cutoff = Date.now() - finishedTaskTTL
setTaskMap((prev) => pruneFinishedTasks(prev, cutoff))
for (const [id, updatedAt] of notifiedTasks.current) {
if (updatedAt < cutoff) notifiedTasks.current.delete(id)
}
}, 10000)
return () => {
offPing()
offState()
offLog()
offTask()
document.removeEventListener('visibilitychange', onVisibility)
window.clearInterval(hostTimer)
}
}, [refresh])
const vms = state?.vms ?? []
const runningVMCount = vms.filter((v) => (state?.transitions[v.name] ?? v.state) === 'running').length
const selectedVM = !PAGE_IDS.includes(selected)
? vms.find((v) => v.name === selected)
: undefined
useEffect(() => {
if (!selectedVM) { setDetail(null); return }
api.GetVMDetail(selectedVM.name).then(setDetail).catch(() => setDetail(null))
}, [selectedVM?.name, selectedVM?.state, state?.transitions[selectedVM?.name ?? ''], detailRevision])
// Display names (the VM's note, .reims-go-note): shown in place of the VM's
// name in the sidebar and page title; the name itself stays the identifier.
const [displayNames, setDisplayNames] = useState<Record<string, string>>({})
const vmNamesKey = vms.map((v) => v.name).join('|')
useEffect(() => {
let live = true
for (const vm of vms) {
api.GetVMNote(vm.name)
.then((n) => { if (live) setDisplayNames((m) => ({ ...m, [vm.name]: (n ?? '').trim() })) })
.catch(() => {})
}
return () => { live = false }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [vmNamesKey])
// Each VM's macOS major version for its icon: the release recorded at
// creation (.reims-go-macos), else a guess from its name or display name.
const [releases, setReleases] = useState<Record<string, string>>({})
useEffect(() => {
let live = true
for (const vm of vms) {
api.GetVMMacOS(vm.name)
.then((r) => { if (live) setReleases((m) => ({ ...m, [vm.name]: (r ?? '').trim() })) })
.catch(() => {})
}
return () => { live = false }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [vmNamesKey])
const macosMajors: Record<string, number | null> = {}
for (const vm of vms) macosMajors[vm.name] = macOSMajor(releases[vm.name], vm.name, displayNames[vm.name])
// Live VM stats are polled by lib/vmStats.ts and read where they are shown
// (VMPage), so a 3-second tick no longer re-renders the whole App.
const lastPluginLocalesRef = useRef<typeof pluginUI>(undefined)
if (lastPluginLocalesRef.current !== pluginUI) {
lastPluginLocalesRef.current = pluginUI
setPluginLocales(pluginUI?.locales)
}
const locale: Locale = resolveActiveLocale(state?.config.locale, pluginUI?.locales, state?.detected_locale)
const dir = localeDir(locale)
useEffect(() => {
const html = document.documentElement
html.lang = locale === 'en-XA' ? 'en' : locale
html.dir = dir
html.dataset.locale = locale
const chain = buildFallbackChain(locale, pluginUI?.locales)
const fontPack = chain
.map((step) => pluginUI?.locales?.find((p) => p.locale === step))
.find((p) => p?.fonts && p.fonts.length > 0)
applyActiveLocaleFonts(fontPack?.fonts)
}, [locale, dir, pluginUI?.locales])
useEffect(() => () => { disposeActiveThemeAndLocaleFonts() }, [])
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const effectiveState = selectedVM ? (state?.transitions[selectedVM.name] ?? selectedVM.state) : ''
const pending = selectedVM ? (state?.pending_changes[selectedVM.name] ?? []) : []
const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime
onTaskRef.current = (task: 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 ?? '')
}
// Toast once per finished download; only live events reach here, not the seed list.
const notify = task.kind === 'installer-download' || task.kind === 'recovery-download' || task.kind === 'runtime-install'
if (task.status !== 'running' && notify && !notifiedTasks.current.has(task.id)) {
notifiedTasks.current.set(task.id, task.updated_at)
const isRuntime = task.kind === 'runtime-install'
const isRecovery = task.kind === 'recovery-download'
if (task.status === 'done') {
if (isRecovery) {
toasts.push({ kind: 'ok', title: tr('toastOnlineRecoveryAttached', { name: task.subject }) })
refresh()
} else {
toasts.push({ kind: 'ok', title: isRuntime ? tr('toastRuntimeReady', { v: task.result || task.subject }) : tr('toastInstallerReady', { v: task.subject }) })
}
} else if (task.status === 'canceled') {
const wasQueued = task.step.toLowerCase().includes('waiting for another download')
toasts.push({ kind: 'ok', title: tr(wasQueued ? 'toastQueueCanceled' : 'toastDownloadPaused') })
} else fail(tr(isRuntime ? 'failRuntime' : isRecovery ? 'failAttachInstaller' : 'failDownload'), task.error ?? '')
}
setTaskMap((prev) => upsertTask(prev, task))
}
const { task: activeTask, running: runningTasks } = currentTask(taskMap)
const runtimeTask = Object.values(taskMap)
.filter((x) => x.kind === 'runtime-install')
.sort((a, b) => b.updated_at - a.updated_at)[0] ?? null
const installRuntime = (commit: string) => {
api.InstallRuntimeOnline(commit).catch((e) => fail(tr('failRuntime'), e))
}
const setChannel = (alpha: boolean) => {
api.SetRuntimeChannel(alpha ? 'alpha' : 'stable').then(() => refresh()).catch((e) => fail(tr('failGeneric'), e))
}
const appUpdateChannel = state?.config.app_update_channel === 'alpha' || state?.config.app_update_channel === 'dev'
? state.config.app_update_channel
: 'stable'
const setAppUpdateChannel = async (ch: 'stable' | 'alpha' | 'dev') => {
await api.SetAppUpdateChannel(ch)
setDismissedUpdate('')
try { localStorage.removeItem('reims-go-update-dismissed') } catch {}
await refresh()
try {
setAppUpdate(await api.CheckAppUpdate(true))
} catch (e) {
setAppUpdate(null)
throw e
}
}
const cancelTask = (id: string) => { api.CancelTask(id).catch((e) => fail(tr('failGeneric'), e)) }
// In-app update: one task per release; its state drives the sidebar capsule
// and the About page alike.
const updateTask = appUpdate?.has_update
? Object.values(taskMap)
.filter((x) => x.kind === 'app-update' && x.subject === appUpdate.latest)
.sort((a, b) => b.updated_at - a.updated_at)[0] ?? null
: null
const updatePhase: UpdatePhase = !appUpdate?.has_update ? 'none'
: updateTask?.status === 'running' ? 'downloading'
: updateTask?.status === 'done' ? 'ready'
: updateTask?.status === 'failed' ? 'failed'
: 'available'
const [dismissedUpdate, setDismissedUpdate] = useState<string>(() => {
try { return localStorage.getItem('reims-go-update-dismissed') ?? '' } catch { return '' }
})
const dismissUpdate = () => {
if (!appUpdate) return
setDismissedUpdate(appUpdate.latest)
try { localStorage.setItem('reims-go-update-dismissed', appUpdate.latest) } catch {}
}
const [confirmUpdate, setConfirmUpdate] = useState(false)
const [installingUpdate, setInstallingUpdate] = useState(false)
const downloadUpdate = () => { api.DownloadAppUpdate().catch((e) => fail(tr('updateFailed'), e)) }
const runInstallUpdate = () => {
setConfirmUpdate(false)
setInstallingUpdate(true)
api.InstallAppUpdate().catch((e) => {
setInstallingUpdate(false)
fail(tr('updateFailed'), e)
})
}
// Restarting leaves VMs running but pauses the host-guest bridges: say so first.
const installUpdate = () => { if (runningVMCount > 0) setConfirmUpdate(true); else runInstallUpdate() }
const showUpdateCard = updatePhase !== 'none' && !(updatePhase === 'available' && dismissedUpdate === appUpdate?.latest)
// One toast after an update restart: the version changed since the last run.
useEffect(() => {
const v = state?.app_version
if (!v || pluginUI === null) return
try {
const last = localStorage.getItem('reims-go-last-version')
if (last && last !== v) toasts.push({ kind: 'ok', title: tr('updateDoneToast', { v }) })
localStorage.setItem('reims-go-last-version', v)
} catch {}
}, [state?.app_version, pluginUI !== null])
const importRuntime = async () => {
try {
const file = await api.PickFile(tr('importRuntime'), '*.tar.zst;*.zip')
if (!file) return
await api.InstallRuntimeArchive(file)
await refresh()
} catch (e) {
fail(tr('failRuntime'), e)
}
}
const folderDone = async () => {
const s = await api.GetState().catch(() => null)
if (s) setState(s)
setSetupStage(s?.active_runtime ? null : 'runtime')
}
const showSetup = !!state && (state.needs_setup || setupStage === 'runtime')
// UI Contract v1 read-only document state attributes (§5.1).
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 isBusyAny = Object.keys(busy).length > 0 || runningTasks > 0
const hasAnyError = unseenErrors > 0 || !!loadError
const uiStateRef = useRef<UIStateSnapshot>({
appearance: theme,
motion: reducedMotion ? 'reduced' : 'full',
locale,
dir,
view: currentView,
vmName: selectedVM?.name ?? '',
vmState: effectiveState,
busy: isBusyAny,
hasError: hasAnyError,
sidebarCollapsed: !sidebarOpen,
safeMode: !!state?.safe_mode,
vms: vms.map((v) => ({ name: v.name, state: state?.transitions[v.name] ?? v.state })),
})
uiStateRef.current = {
appearance: theme,
motion: reducedMotion ? 'reduced' : 'full',
locale,
dir,
view: currentView,
vmName: selectedVM?.name ?? '',
vmState: effectiveState,
busy: isBusyAny,
hasError: hasAnyError,
sidebarCollapsed: !sidebarOpen,
safeMode: !!state?.safe_mode,
vms: vms.map((v) => ({ name: v.name, state: state?.transitions[v.name] ?? v.state })),
}
useEffect(() => {
const el = document.documentElement
el.dataset.view = currentView
el.dataset.vmState = effectiveState || 'none'
el.dataset.busy = String(isBusyAny)
el.dataset.hasError = String(hasAnyError)
el.dataset.sidebarCollapsed = String(!sidebarOpen)
el.dataset.safeMode = String(!!state?.safe_mode)
notifyInteractiveThemeState(uiStateRef.current)
}, [currentView, effectiveState, isBusyAny, hasAnyError, sidebarOpen, state?.safe_mode, locale, dir, theme])
// Apply active theme pack (zero extra CSS for builtin default theme, §5.1 & §8.1).
useEffect(() => {
api.GetActiveTheme().then(setActiveThemePayload).catch(() => {})
api.GetPluginUIContributions().then(setPluginUI).catch(() => {})
}, [themeRevision, state?.safe_mode])
useEffect(() => {
void applyActiveTheme(
activeThemePayload,
theme,
() => uiStateRef.current,
{
toggleSidebar,
openSettings: () => setSelected(SETTINGS_ID),
focusVMWindow: (vmName) => { void api.FocusVMWindow(vmName).catch(() => {}) },
},
)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeThemePayload, theme])
const openLogs = (tab: LogTab = 'app') => {
setLogTab(tab)
setLogsOpen(true)
setUnseenErrors(0)
}
const toggleLogs = () => {
setLogsOpen((o) => !o)
setUnseenErrors(0)
}
const loadVMLog = async (serial: boolean, name = selectedVM?.name) => {
if (!name) return
try {
const text = await api.ReadVMLogs(name, serial)
if (serial) setSerialLog(text)
else setQemuLog(text)
} catch (e) {
if (serial) setSerialLog(errText(e))
else setQemuLog(errText(e))
}
}
const loadSerial = (name?: string) => loadVMLog(true, name)
const loadQemu = (name?: string) => loadVMLog(false, name)
const fail = (title: string, e: unknown) => {
const parsed = parseAppError(e)
toasts.push({
kind: 'error',
title,
description: parsed.summary,
errorCode: parsed.code,
rawDetail: parsed.rawDetail,
detailsLabel: tr('errRawDetailsToggle'),
copyDetailsLabel: tr('errCopyDetails'),
action: { label: tr('viewLogs'), onClick: () => openLogs('app') },
})
}
const runVMAction = async (name: string, action: VMAction, fn: () => Promise<void>, okTitle?: string) => {
setBusy((b) => ({ ...b, [name]: action }))
try {
await fn()
if (okTitle) toasts.push({ kind: 'ok', title: okTitle })
await refresh()
} catch (e) {
fail(tr(failKey[action]), e)
} finally {
setBusy((b) => {
const { [name]: _, ...rest } = b
return rest
})
}
}
// Paste as keystrokes: the backend refuses text a US keyboard can't type
// (ErrNotTypeable in type_flow.go), which gets a message of its own.
const typeInto = async (name: string, fn: () => Promise<number>) => {
setBusy((b) => ({ ...b, [name]: 'type' }))
try {
const n = await fn()
toasts.push({ kind: 'ok', title: tr('toastTyped', { n }) })
} catch (e) {
if (errText(e).includes('not typeable')) {
toasts.push({ kind: 'error', title: tr('failType'), description: tr('typeUntypeable') })
} else {
fail(tr('failType'), e)
}
} finally {
setBusy((b) => {
const { [name]: _, ...rest } = b
return rest
})
}
}
const attachInstaller = async (name: string, running: boolean) => {
try {
const cached = (await api.ListInstallers()) ?? []
const hasCached = cached.some(
(x) => !x.partial && (x.kind === 'offline' || x.kind === 'online' || /\.(img|dmg)$/i.test(x.name)),
)
let picked = ''
if (!hasCached) {
picked = await api.PickFile(tr('pickRecoveryTitle'), '*.img;*.dmg')
if (!picked) {
setOnlineRecoveryTarget(name)
return
}
}
setBusy((b) => ({ ...b, [name]: 'attachInstaller' }))
try {
const fileName = await api.AttachInstaller(name, picked)
toasts.push({
kind: 'ok',
title: tr(running ? 'toastInstallerAttachedNextStart' : 'toastInstallerAttached', { name: fileName }),
})
await refresh()
} finally {
setBusy((b) => {
const { [name]: _, ...rest } = b
return rest
})
}
} catch (e) {
fail(tr('failAttachInstaller'), e)
}
}
const onVMActionFor = (name: string, action: VMAction, isRunning: boolean) => {
switch (action) {
case 'start': return runVMAction(name, action, () => api.StartVM(name))
case 'focus': return api.FocusVMWindow(name).catch((e) => fail(tr('failFocus'), e))
case 'screenshot': return runVMAction(name, action, () => api.CopyVMScreenshot(name), tr('toastScreenshotCopied'))
case 'stop': return runVMAction(name, action, () => api.StopVM(name, false), tr('toastStopped', { name }))
case 'forceStop': return runVMAction(name, action, () => api.StopVM(name, true), tr('toastStopped', { name }))
case 'restart': return runVMAction(name, action, () => api.RestartVM(name))
case 'eject': return runVMAction(name, action, () => api.EjectInstaller(name), tr('toastEjected'))
case 'finishInstall': return runVMAction(name, action, () => api.FinishInstall(name), tr(isRunning ? 'toastExitRecoveryNextStart' : 'toastInstallFinished'))
case 'enterRecovery': return runVMAction(name, action, () => api.EnterRecovery(name), tr(isRunning ? 'toastEnterRecoveryNextStart' : 'toastEnterRecovery'))
case 'attachInstaller': return attachInstaller(name, isRunning)
case 'attachGuestTools': return runVMAction(name, action, () => api.AttachGuestTools(name), tr(isRunning ? 'toastGuestToolsAttachedNextStart' : 'toastGuestToolsAttached'))
case 'detachGuestTools': return runVMAction(name, action, () => api.DetachGuestTools(name), tr(isRunning ? 'toastGuestToolsDetachedNextStart' : 'toastGuestToolsDetached'))
case 'openSharedFolder':
return api.OpenSharedFolder(name).catch((e) => fail(tr('failOpenFolder'), e))
case 'upgradeNVMe':
return runVMAction(name, action, () => api.UpgradeDiskToNVMe(name), tr(isRunning ? 'toastNVMeNextStart' : 'toastNVMeReady'))
case 'exportDiagnostics':
return runVMAction(name, action, async () => { await api.ExportDiagnostics(name) }, tr('toastDiagExported'))
case 'cloneVM':
return setCloneSource(name)
case 'type': return typeInto(name, () => api.TypeClipboard(name))
case 'sendText': return setSendTextTarget(name)
case 'openFolder':
return api.OpenVMFolder(name).catch((e) => fail(tr('failOpenFolder'), e))
case 'delete': return setDeleteTarget(name)
}
}
const onVMAction = (action: VMAction) => {
if (!selectedVM) return
return onVMActionFor(selectedVM.name, action, selectedVM.state === 'running')
}
const onSidebarContextAction = (name: string, action: VMAction | 'settings') => {
if (action === 'settings') {
setSelected(name)
api.GetVMDetail(name).then((d) => { setDetail(d); setShowSettings(true) }).catch((e) => fail(tr('failGeneric'), e))
return
}
const vm = vms.find((v) => v.name === name)
const st = state?.transitions[name] ?? vm?.state ?? 'stopped'
onVMActionFor(name, action, st === 'running')
}
// The state's own main action (Start, or Show Window while running), shared by
// Ctrl+Enter and a double-click in the sidebar.
const primaryAction = (name: string) => {
const vm = vms.find((v) => v.name === name)
if (!vm || busy[name]) return
const st = state?.transitions[name] ?? vm.state
if (st === 'stopped') onVMActionFor(name, 'start', false)
else if (st === 'running') onVMActionFor(name, 'focus', true)
}
const confirmDelete = (keepFiles: boolean) => {
const name = deleteTarget
setDeleteTarget(null)
if (name) runVMAction(name, 'delete', () => api.DeleteVM(name, keepFiles), tr('toastDeleted', { name }))
}
const confirmOnlineRecovery = () => {
const name = onlineRecoveryTarget
setOnlineRecoveryTarget(null)
if (!name) return
api.DownloadAndAttachOnlineRecovery(name, 'latest')
.then(() => toasts.push({ kind: 'ok', title: tr('toastOnlineRecoveryStarted') }))
.catch((e) => fail(tr('failAttachInstaller'), e))
}
const confirmClone = (cloneName: string) => {
const src = cloneSource
setCloneSource(null)
if (!src) return
runVMAction(src, 'cloneVM', async () => {
await api.CloneVMCoW(src, cloneName)
setSelected(cloneName)
}, tr('toastCloned', { name: cloneName }))
}
const openWizard = () => {
if (!state?.active_runtime) {
setSelected(HOST_ID)
toasts.push({ kind: 'error', title: tr('noRuntimeAlert') })
return
}
setWizardDraft(null)
setShowWizard(true)
}
const openWizardWithInstaller = (item: CachedInstaller) => {
if (!state?.active_runtime) {
setSelected(HOST_ID)
toasts.push({ kind: 'error', title: tr('noRuntimeAlert') })
return
}
const existing = new Set((state.vms ?? []).map((v) => v.name.toLowerCase()))
let defaultName = 'macos-tahoe'
for (let i = 2; existing.has(defaultName.toLowerCase()); i++) {
defaultName = `macos-tahoe-${i}`
}
const isOffline = item.kind === 'offline' && !!item.version
setWizardDraft({
step: 1,
opts: {
name: defaultName,
dir: '',
source_mode: isOffline ? 'offline' : 'installer',
macos: isOffline ? item.version : '',
offline: isOffline,
installer: isOffline ? '' : item.path,
cpus: state.host.logical_cpus >= 12 ? 8 : 4,
memory: `${recommendedMemoryGB(state.host)}G`,
disk_size: '128G',
disk_mode: 'copy',
disk_controller: 'nvme',
graphics: 'reims-vgpu',
gpu: state.host.recommended_gpu?.vulkan_icd ?? 'auto',
resolution: recommendedResolution(state.host),
displays: 1,
borderless: false,
capture: false,
audio: true,
network: !isOffline,
ssh_port: 0,
logs: true,
guest_lang: defaultGuestLang(locale),
start: true,
},
})
setShowWizard(true)
}
// The wizard closes as soon as the create starts; progress lives in the status bar
// (vm-create task). On failure or cancel the toast offers returning to the wizard.
const submitCreate = (payload: CreateOpts, draft: WizardDraft) => {
setShowWizard(false)
setWizardDraft(null)
const name = payload.name
const hasDownload = payload.source_mode === 'offline' || payload.source_mode === 'apple'
api.CreateVM(payload)
.then(() => {
toasts.push({ kind: 'ok', title: tr('toastCreated', { name }) })
setSelected(name)
return refresh()
})
.catch((e) => {
void refresh()
if (/\bcontext canceled\b/i.test(errText(e))) {
toasts.push({
kind: 'ok',
title: tr('toastCreateCanceled', { name }),
description: hasDownload ? tr('toastCreateCanceledPartial') : undefined,
action: { label: tr('backToEdit'), onClick: () => { setWizardDraft(draft); setShowWizard(true) } },
})
return
}
const parsed = parseAppError(e)
toasts.push({
kind: 'error',
title: tr('failCreate', { name }),
description: parsed.summary,
errorCode: parsed.code,
rawDetail: parsed.rawDetail,
detailsLabel: tr('errRawDetailsToggle'),
copyDetailsLabel: tr('errCopyDetails'),
action: { label: tr('backToEdit'), onClick: () => { setWizardDraft(draft); setShowWizard(true) } },
})
})
}
const copy = async (text: string) => {
try {
await navigator.clipboard.writeText(text)
toasts.push({ kind: 'ok', title: tr('toastCopied') })
} catch (e) {
fail(tr('failGeneric'), e)
}
}
const setLang = async (l: Locale) => {
await api.SetLocale(l)
refresh()
}
// Global shortcuts (docs/design-guidelines.md §6). Dialogs own the keyboard while open.
const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {})
shortcutRef.current = (e: KeyboardEvent) => {
if (!e.ctrlKey || e.altKey || e.metaKey) return
if (showSetup || showWizard || showSettings || affinityTarget || deleteTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate) return
if (document.querySelector('[role="dialog"], [role="alertdialog"]')) return
const k = e.key.toLowerCase()
if (k === 'n') { e.preventDefault(); openWizard() }
else if (k === ',' && detail) { e.preventDefault(); setShowSettings(true) }
else if (k === 'l') { e.preventDefault(); toggleLogs() }
else if (k === 'b' && !showSetup) { e.preventDefault(); toggleSidebar() }
else if (k === 'enter' && selectedVM && !e.shiftKey) { e.preventDefault(); primaryAction(selectedVM.name) }
}
useEffect(() => {
const h = (e: KeyboardEvent) => shortcutRef.current(e)
window.addEventListener('keydown', h)
return () => window.removeEventListener('keydown', h)
}, [])
// Tray menu: "Show in Reims-Go" selects that VM; "New VM…" opens the wizard.
// The backend has already brought the window to the front.
const openWizardRef = useRef(openWizard)
openWizardRef.current = openWizard
useEffect(() => {
const offSelect = events.onTraySelectVM((name) => { setSelected(name) })
const offNew = events.onTrayNewVM(() => { openWizardRef.current() })
return () => { offSelect(); offNew() }
}, [])
// Native Wails file drag-and-drop delivery into the selected VM's shared folder.
const dropTargetRef = useRef<{ name: string; ready: boolean }>({ name: '', ready: false })
dropTargetRef.current = {
name: selectedVM?.name ?? '',
ready: !!selectedVM && !!detail && !detail.has_installer && !detail.recovery_mode,
}
useEffect(() => {
let depth = 0
const onEnter = (e: DragEvent) => {
if (!dropTargetRef.current.ready) return
if (e.dataTransfer?.types?.includes('Files')) { depth++; setDropping(true) }
}
const onLeave = () => {
depth = Math.max(0, depth - 1)
if (depth === 0) setDropping(false)
}
const onDropEnd = () => { depth = 0; setDropping(false) }
window.addEventListener('dragenter', onEnter)
window.addEventListener('dragleave', onLeave)
window.addEventListener('drop', onDropEnd)
OnFileDrop((_x, _y, paths) => {
depth = 0
setDropping(false)
const cur = dropTargetRef.current
if (!cur.ready || !cur.name || !paths || paths.length === 0) return
api.DeliverPathsToGuest(cur.name, paths)
.then((delivered) => {
if (!delivered || delivered.length === 0) return
if (delivered.length === 1) toasts.push({ kind: 'ok', title: tr('toastFileDelivered', { name: delivered[0] }) })
else toasts.push({ kind: 'ok', title: tr('toastFilesDelivered', { n: delivered.length }) })
})
.catch((e) => fail(tr('failGuestTools'), e))
}, true)
return () => {
window.removeEventListener('dragenter', onEnter)
window.removeEventListener('dragleave', onLeave)
window.removeEventListener('drop', onDropEnd)
OnFileDropOff()
}
}, [])
return (
<TooltipProvider>
<div className="app-shell rg-p-shell">
<header className="titlebar rg-p-titlebar" onDoubleClick={() => WindowToggleMaximise()}>
{showSetup || !state ? (
<div className="brand rg-p-brand">
<img className="brand-mark" src="/logo.svg" alt="" aria-hidden="true" />
Reims-Go
</div>
) : (
<TitleMenus
locale={locale}
sidebarOpen={sidebarOpen}
onToggleSidebar={toggleSidebar}
logsOpen={logsOpen}
onToggleLogs={toggleLogs}
themeMode={effectiveThemeMode}
canLight={canLight}
canDark={canDark}
onThemeMode={setThemeMode}
vm={selectedVM ? { name: selectedVM.name, state: effectiveState, busy: !!busy[selectedVM.name] } : null}
onNewVM={openWizard}
onVMAction={onVMAction}
onVMSettings={() => { if (detail) setShowSettings(true) }}
onVMDelete={() => { if (selectedVM) setDeleteTarget(selectedVM.name) }}
onNavigate={setSelected}
onOpenURL={(url) => { api.OpenURL(url).catch((e) => fail(tr('failGeneric'), e)) }}
appVersion={state.app_version}
/>
)}
<div className="titlebar-right" onDoubleClick={(e) => e.stopPropagation()}>
{canLight && canDark && (
<Tip label={tr(theme === 'light' ? 'themeSwitchDark' : 'themeSwitchLight')}>
<button
type="button"
className="theme-toggle"
aria-label={tr(theme === 'light' ? 'themeSwitchDark' : 'themeSwitchLight')}
onClick={toggleTheme}
>
{theme === 'light' ? <Moon size={14} aria-hidden="true" /> : <Sun size={14} aria-hidden="true" />}
</button>
</Tip>
)}
<div className="win-controls">
<button type="button" className="win-btn" aria-label={tr('minimize')} onClick={() => WindowMinimise()}><Minus size={14} aria-hidden="true" /></button>
<button type="button" className="win-btn" aria-label={tr('maximize')} onClick={() => WindowToggleMaximise()}><Square size={12} aria-hidden="true" /></button>
<button type="button" className="win-btn close" aria-label={tr('closeWindow')} onClick={() => api.RequestClose()}><X size={15} aria-hidden="true" /></button>
</div>
</div>
</header>
{state?.safe_mode && (
<div className="safe-mode-banner" role="status">
<span>{tr('safeModeBanner')}</span>
<button type="button" className="link-btn" onClick={() => setSelected(PLUGINS_ID)}>
{tr('safeModeManagePlugins')}
</button>
</div>
)}
{showSetup && state ? (
<Suspense fallback={null}>
<Setup
locale={locale}
locales={pluginUI?.locales}
state={state}
stage={state.needs_setup ? 'folder' : 'runtime'}
runtimeTask={runtimeTask}
onLocale={setLang}
onFolderDone={folderDone}
onFinish={() => setSetupStage(null)}
onError={fail}
onChannel={setChannel}
onInstallRuntime={installRuntime}
onCancelTask={cancelTask}
onImportRuntime={importRuntime}
/>
</Suspense>
) : (
<div className={`workspace rg-p-workspace${sidebarOpen ? '' : ' sidebar-hidden'}`}>
{sidebarOpen && <div className="sidebar-backdrop" aria-hidden="true" onClick={toggleSidebar} />}
<Sidebar
locale={locale}
vms={vms}
transitions={state?.transitions ?? {}}
selected={selected}
hostReady={hostReady}
onSelect={setSelected}
displayNames={displayNames}
macosMajors={macosMajors}
onActivate={primaryAction}
onNew={openWizard}
onVMContextAction={onSidebarContextAction}
downloading={Object.values(taskMap).some(isActiveInstallerTask)}
safeMode={state?.safe_mode}
updateDot={!!appUpdate?.has_update}
updateCard={showUpdateCard ? (
<UpdateCapsule
locale={locale}
phase={installingUpdate ? 'ready' : updatePhase}
latest={appUpdate?.latest ?? ''}
task={updateTask}
onOpen={() => setSelected(ABOUT_ID)}
onDownload={downloadUpdate}
onCancel={() => { if (updateTask) cancelTask(updateTask.id) }}
onInstall={installUpdate}
onDismiss={dismissUpdate}
/>
) : null}
/>
<main className="main rg-p-main">
<div className="scroll">
<Suspense fallback={null}>
{!state ? (
<div className="page">
{loadError ? <div className="notice notice-error">{loadError}</div> : <span className="muted">…</span>}
</div>
) : selected === INSTALLERS_ID ? (
<InstallersPage
locale={locale}
host={state.host}
tasks={Object.values(taskMap)}
onCreateWithInstaller={openWizardWithInstaller}
onError={fail}
onToast={(title) => toasts.push({ kind: 'ok', title })}
/>
) : selected === PLUGINS_ID ? (
<PluginsPage
locale={locale}
appearance={theme}
safeMode={state.safe_mode}
onRefresh={refresh}
onError={fail}
onThemeChanged={() => setThemeRevision((r) => r + 1)}
/>
) : selectedVM ? (
<VMPage
locale={locale}
name={selectedVM.name}
displayName={displayNames[selectedVM.name] ?? ''}
onDisplayNameSaved={(n) => setDisplayNames((m) => ({ ...m, [selectedVM.name]: n }))}
macosMajor={macosMajors[selectedVM.name] ?? null}
state={effectiveState}
guideActive={state.active_guides?.includes(selectedVM.name) ?? false}
installGuideEnabled={!!state.install_guide_enabled}
detail={detail}
host={state.host}
pending={pending}
busyAction={busy[selectedVM.name]}
onAction={onVMAction}
onSettings={() => setShowSettings(true)}
onOpenAffinity={() => setAffinityTarget(selectedVM.name)}
onDelete={() => setDeleteTarget(selectedVM.name)}
onViewLogs={() => { openLogs('serial'); loadSerial() }}
onCopy={copy}
onTypeText={(text) => typeInto(selectedVM.name, () => api.TypeText(selectedVM.name, text))}
onToggleBorderless={(enabled) => {
api.ToggleBorderless(selectedVM.name, enabled)
.then(() => {
toasts.push({ kind: 'ok', title: tr(effectiveState === 'running' ? 'toastBorderlessNextStart' : 'toastBorderlessUpdated') })
return refresh()
})
.catch((e) => fail(tr('failGeneric'), e))
}}
onTogglePreventSleep={(enabled) => {
api.SetGuestPreventSleep(selectedVM.name, enabled)
.then(() => {
toasts.push({ kind: 'ok', title: tr(enabled ? 'toastPreventSleepOn' : 'toastPreventSleepOff') })
return refresh()
})
.catch((e) => fail(tr('failGuestTools'), e))
}}
onDeliverFile={() => {
api.DeliverFileToGuest(selectedVM.name)
.then((fileName) => {
if (fileName) toasts.push({ kind: 'ok', title: tr('toastFileDelivered', { name: fileName }) })
})
.catch((e) => fail(tr('failGuestTools'), e))
}}
onToast={(title) => toasts.push({ kind: 'ok', title })}
onError={fail}
dropping={dropping}
pluginUI={pluginUI}
/>
) : selected === SETTINGS_ID ? (
<AppSettingsPage
state={state}
locale={locale}
locales={pluginUI?.locales}
themeMode={effectiveThemeMode}
canLight={canLight}
canDark={canDark}
onThemeMode={setThemeMode}
onSetLocale={setLang}
onRefresh={refresh}
onError={fail}
/>
) : selected === ABOUT_ID ? (
<AboutPage
locale={locale}
appVersion={state.app_version}
appUpdateChannel={appUpdateChannel}
onAppUpdateChannel={setAppUpdateChannel}
appUpdate={appUpdate}
onAppUpdate={setAppUpdate}
updatePhase={updatePhase}
updateTask={updateTask}
installing={installingUpdate}
onDownloadUpdate={downloadUpdate}
onCancelUpdate={() => { if (updateTask) cancelTask(updateTask.id) }}
onInstallUpdate={installUpdate}
onCopy={copy}
onError={fail}
/>
) : (
<HostView
state={state}
locale={locale}
onRefresh={refresh}
onNewVM={openWizard}
onError={fail}
onToast={(title) => toasts.push({ kind: 'ok', title })}
runtimeTask={runtimeTask}
onChannel={setChannel}
onInstallRuntime={installRuntime}
onCancelTask={cancelTask}
/>
)}
</Suspense>
</div>
</main>
</div>
)}
{!showSetup && (
<LogPanel
locale={locale}
open={logsOpen}
onToggle={toggleLogs}
tab={selectedVM ? logTab : 'app'}
onTab={(tab) => { setLogTab(tab); if (tab === 'serial') loadSerial(); if (tab === 'qemu') loadQemu() }}
lines={logLines}
unseenErrors={unseenErrors}
onClear={() => setLogLines([])}
serialText={serialLog}
qemuText={qemuLog}
showSerial={!!selectedVM}
onRefreshSerial={() => loadSerial()}
onRefreshQemu={() => loadQemu()}
task={activeTask}
runningTasks={runningTasks}
onCancelTask={cancelTask}
host={state?.host}
runningVMs={runningVMCount}
onCopy={copy}
hostReady={hostReady}
onOpenHost={() => setSelected(HOST_ID)}
/>
)}
{showWizard && state && (
<Suspense fallback={null}>
<CreateWizard
locale={locale}
host={state.host}
tasks={Object.values(taskMap)}
draft={wizardDraft}
onClose={() => { setShowWizard(false); setWizardDraft(null) }}
onSubmit={submitCreate}
/>
</Suspense>
)}
{showSettings && state && detail && (
<Suspense fallback={null}>
<SettingsModal
locale={locale}
detail={detail}
stats={latestVMStats(detail.name)}
host={state.host}
optimizations={state.optimizations}
running={effectiveState === 'running'}
onCopy={copy}
onDiskChanged={refresh}
onOpenAffinity={() => setAffinityTarget(detail.name)}
affinityVersion={affinityVersion}
onHostChanged={refresh}
onClose={() => setShowSettings(false)}
onSaved={() => {
setShowSettings(false)
toasts.push({ kind: 'ok', title: tr(effectiveState === 'running' ? 'toastSavedNextStart' : 'toastSaved') })
refresh()
}}
/>
</Suspense>
)}
{affinityTarget && state && (
<Suspense fallback={null}>
<AffinityDialog
locale={locale}
vmName={affinityTarget}
vcpus={detail?.name === affinityTarget ? detail.cpus : 4}
host={state.host}
globalAutoPin={state.config.auto_pin_pcores}
onClose={() => setAffinityTarget(null)}
onApplied={(st) => {
setAffinityTarget(null)
setAffinityVersion((v) => v + 1)
const count = st.effective_cpus?.length ?? 0
const mask = st.live_mask_hex || st.effective_mask_hex || '0x0'
toasts.push({
kind: 'ok',
title: st.running
? tr('toastAffinityApplied', { count, mask })
: tr('toastAffinitySaved'),
})
refresh()
}}
/>
</Suspense>
)}
{confirmUpdate && (
<Modal
title={tr('updateConfirmTitle', { v: appUpdate?.latest ?? '' })}
closeLabel={tr('close')}
onClose={() => setConfirmUpdate(false)}
>
<div className="stack-2" style={{ padding: 'var(--sp-4)', fontSize: 'var(--fs-13)', color: 'var(--text-2)' }}>
<p style={{ margin: 0 }}>{tr('updateConfirmBody', { n: runningVMCount })}</p>
{state?.host.needs_cold_reboot_workaround && <p style={{ margin: 0 }}>{tr('updateConfirmWin10')}</p>}
</div>
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" onClick={() => setConfirmUpdate(false)}>{tr('cancel')}</Button>
<Button variant="primary" onClick={runInstallUpdate}>{tr('updateRestart')}</Button>
</span>
</div>
</Modal>
)}
{deleteTarget && (
<DeleteDialog locale={locale} name={deleteTarget} onCancel={() => setDeleteTarget(null)} onConfirm={confirmDelete} />
)}
{cloneSource && (
<CloneDialog
locale={locale}
sourceName={cloneSource}
defaultCloneName={`${cloneSource}-clone`}
onCancel={() => setCloneSource(null)}
onConfirm={confirmClone}
/>
)}
{onlineRecoveryTarget && (
<OnlineRecoveryDialog
locale={locale}
name={onlineRecoveryTarget}
onCancel={() => setOnlineRecoveryTarget(null)}
onConfirm={confirmOnlineRecovery}
/>
)}
{sendTextTarget && (
<SendTextDialog
locale={locale}
vmName={sendTextTarget}
guestToolsConnected={Boolean(latestVMStats(sendTextTarget)?.guest_tools_connected ?? detail?.guest_tools_connected)}
onCancel={() => setSendTextTarget(null)}
onConfirm={(text) => {
const target = sendTextTarget
setSendTextTarget(null)
typeInto(target, () => api.TypeText(target, text))
}}
/>
)}
<Toaster items={toasts.items} onRemove={toasts.remove} closeLabel={tr('close')} dir={dir} />
</div>
</TooltipProvider>
)
}