1670 lines
74 KiB
TypeScript
1670 lines
74 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 './macos/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 { DataRootReadOnly } from './components/DataRootReadOnly'
|
|
import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar'
|
|
import { PluginViewHost } from './components/PluginViewHost'
|
|
import { locText } from './components/SchemaForm'
|
|
import { VMAction, VMBusyAction, 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 './macos/macosRelease'
|
|
import { currentTask, finishedTaskTTL, isActiveInstallerTask, pruneFinishedTasks, upsertTask } from './lib/tasks'
|
|
import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, emitThemeEvent, notifyInteractiveThemeState, type UIStateSnapshot } from './lib/themeEngine'
|
|
import { hasVisibleDialog } from './lib/dialogState'
|
|
import { latestVMStatsWithDriver, refreshSubscribedVMStats, refreshVMStatsWithDriver } from './lib/vmStats'
|
|
import { vmRefKey } from './lib/vmRef'
|
|
import { closePluginDialog, closePluginView, emptyPluginViewState, matchViewCondition, openPluginView, pluginViewKey, prunePluginViews, type PluginViewRoute, type PluginViewState } from './lib/pluginViewRouter'
|
|
import { publishPluginHostEvent } from './lib/pluginViewEvents'
|
|
import { buildSafePluginAssetURL } from './lib/pluginAssets'
|
|
import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail, ViewContribution } from './types'
|
|
import { Button, Tip, TooltipProvider } from './ui/controls'
|
|
import { ConfirmDialog, Modal } from './ui/dialog'
|
|
import { Toaster, useToasts } from './ui/toast'
|
|
import { BrandMark, ThemeDecorations, ThemeVisualsProvider } from './ui/themeVisuals'
|
|
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 ImagesPage = lazy(() => import('./components/ImagesPage').then((m) => ({ default: m.ImagesPage })))
|
|
const InstallersPage = lazy(() => import('./macos/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<VMBusyAction, I18nKey> = {
|
|
start: 'failStart',
|
|
suspend: 'failSuspend',
|
|
resume: 'failResume',
|
|
discardSuspend: 'failDiscardSuspend',
|
|
focus: 'failFocus',
|
|
fullscreen: 'failFullscreen',
|
|
screenshot: 'failScreenshot',
|
|
pluginCommand: 'failGeneric',
|
|
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, setSelectedPage] = 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((e) => console.warn('[app] CheckAppUpdate failed:', e)) }
|
|
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<{ name: string; driverID: string } | null>(null)
|
|
const [affinityVersion, setAffinityVersion] = useState(0)
|
|
const [deleteTarget, setDeleteTarget] = useState<string | null>(null)
|
|
const [discardSuspendTarget, setDiscardSuspendTarget] = useState<string | null>(null)
|
|
const [cloneSource, setCloneSource] = useState<{ name: string; driverID: string } | null>(null)
|
|
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
|
|
const [sendTextTarget, setSendTextTarget] = useState<string | null>(null)
|
|
const [busy, setBusy] = useState<Record<string, VMBusyAction>>({})
|
|
const busyOpsRef = useRef<Map<string, Map<number, VMBusyAction>>>(new Map())
|
|
const nextBusyTokenRef = useRef(0)
|
|
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 (e) {
|
|
console.warn('[app] read theme preference failed:', e)
|
|
}
|
|
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 [pluginViewState, setPluginViewState] = useState<PluginViewState>(emptyPluginViewState)
|
|
const [pluginViewMeta, setPluginViewMeta] = useState<Record<string, { title?: string; badge?: { text: string; tone: string } }>>({})
|
|
// Host navigation always leaves plugin views, even when the target page is already selected underneath.
|
|
const setSelected = useCallback((id: string) => {
|
|
setPluginViewState(emptyPluginViewState)
|
|
setSelectedPage(id)
|
|
}, [])
|
|
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 (e) {
|
|
console.warn('[app] persist theme preference failed:', e)
|
|
}
|
|
}
|
|
|
|
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 (e) { console.warn('[app] persist sidebar state failed:', e) }
|
|
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 onHostDropAckRef = useRef<(ack: { status: string; error?: string }) => 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('')
|
|
setSelectedPage((cur) => {
|
|
if (PAGE_IDS.includes(cur)) return cur
|
|
if ((s.vms ?? []).some((v) => vmRefKey(v) === cur || v.name === cur)) return cur
|
|
return s.vms && s.vms.length > 0 ? vmRefKey(s.vms[0]) : HOST_ID
|
|
})
|
|
if (reloadDetail) setDetailRevision((revision) => revision + 1)
|
|
} catch (e) {
|
|
setLoadError(errText(e))
|
|
}
|
|
}, [])
|
|
|
|
useEffect(() => {
|
|
void refresh()
|
|
events.emitUIPong()
|
|
const offPing = events.onUIPing(() => { events.emitUIPong() })
|
|
const offState = events.onStateChanged(() => {
|
|
refresh(true)
|
|
refreshSubscribedVMStats()
|
|
setThemeRevision((r) => r + 1)
|
|
})
|
|
// Logs never pop the panel open (see docs/design-guidelines.md); 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))
|
|
})
|
|
// Tasks: seed from the backend, then follow events.
|
|
api.GetTasks().then((list) => {
|
|
setTaskMap((prev) => (list ?? []).reduce(upsertTask, prev))
|
|
}).catch((e) => console.warn('[app] GetTasks failed:', e))
|
|
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[vmRefKey(v)] ?? v.state) === 'running').length
|
|
const selectedVM = !PAGE_IDS.includes(selected)
|
|
? vms.find((v) => vmRefKey(v) === selected) ?? vms.find((v) => v.name === selected)
|
|
: undefined
|
|
|
|
const pluginViews = pluginUI?.views ?? []
|
|
const findVM = (ref: string) => vms.find((item) => vmRefKey(item) === ref || item.name === ref)
|
|
const viewAvailable = (view: ViewContribution, vmRef?: string) => {
|
|
const vm = vmRef ? findVM(vmRef) : undefined
|
|
return matchViewCondition(view.when, { vmState: vm ? state?.transitions[vmRefKey(vm)] ?? vm.state : '', theme })
|
|
}
|
|
const openView = (view: ViewContribution, targetVM?: string) => {
|
|
const route: PluginViewRoute = { pluginId: view.pluginId ?? '', viewId: view.id, location: view.location as PluginViewRoute['location'], vm: targetVM, from: selected }
|
|
if (view.location === 'vm.tab') {
|
|
const target = findVM(targetVM || (selectedVM ? vmRefKey(selectedVM) : ''))
|
|
if (!target) throw new Error('A valid VM is required for this view')
|
|
route.vm = vmRefKey(target)
|
|
}
|
|
if (!route.vm && view.when?.split('==')[0].trim() === 'vmState' && selectedVM) route.vm = vmRefKey(selectedVM)
|
|
if (!viewAvailable(view, route.vm)) throw new Error('This view is not available in the current state')
|
|
if (view.location === 'vm.tab') setSelectedPage(route.vm!)
|
|
else if (view.location === 'settings') setSelectedPage(SETTINGS_ID)
|
|
setPluginViewState((current) => openPluginView(current, route))
|
|
}
|
|
const openViewFromClick = (view: ViewContribution, targetVM?: string) => {
|
|
try {
|
|
openView(view, targetVM)
|
|
} catch (error) {
|
|
fail(tr('open'), error)
|
|
}
|
|
}
|
|
const closeView = () => {
|
|
const result = closePluginView(pluginViewState)
|
|
setPluginViewState(result.state)
|
|
if (result.page && (PAGE_IDS.includes(result.page) || findVM(result.page))) setSelectedPage(result.page)
|
|
return { closed: result.closed }
|
|
}
|
|
const navigateHost = (target: { page?: string; vm?: string }) => {
|
|
if (target.vm) {
|
|
const vm = findVM(target.vm)
|
|
if (!vm) throw new Error(`Unknown VM: ${target.vm}`)
|
|
setSelected(vmRefKey(vm))
|
|
return
|
|
}
|
|
const pages: Record<string, string> = { host: HOST_ID, images: INSTALLERS_ID, plugins: PLUGINS_ID, settings: SETTINGS_ID, about: ABOUT_ID }
|
|
const page = pages[target.page ?? '']
|
|
if (!page) throw new Error(`Unknown page: ${target.page}`)
|
|
setSelected(page)
|
|
}
|
|
const updateViewMetadata = (view: ViewContribution, metadata: { title?: string; badge?: { text: string; tone: string } }) => {
|
|
const key = pluginViewKey({ pluginId: view.pluginId ?? '', viewId: view.id })
|
|
setPluginViewMeta((current) => ({ ...current, [key]: { ...current[key], ...metadata } }))
|
|
}
|
|
useEffect(() => {
|
|
const valid = new Set(pluginViews.map((view) => pluginViewKey({ pluginId: view.pluginId ?? '', viewId: view.id })))
|
|
setPluginViewState((current) => prunePluginViews(current, valid, (vm) => !!vm && vms.some((item) => vmRefKey(item) === vm), (route) => {
|
|
const view = findRouteView(route)
|
|
return !!view && viewAvailable(view, route.vm)
|
|
}))
|
|
setPluginViewMeta((current) => Object.fromEntries(Object.entries(current).filter(([key]) => valid.has(key))))
|
|
}, [pluginUI?.views, state?.vms, state?.transitions, selected, theme])
|
|
const findRouteView = (route: PluginViewRoute) =>
|
|
pluginViews.find((view) => (view.pluginId ?? '') === route.pluginId && view.id === route.viewId && view.location === route.location)
|
|
const routedView = pluginViewState.route ? findRouteView(pluginViewState.route) : undefined
|
|
const activePluginView = routedView && viewAvailable(routedView, pluginViewState.route?.vm) ? routedView : undefined
|
|
const activePluginRoute = activePluginView ? pluginViewState.route : null
|
|
const renderPluginView = (route: PluginViewRoute, view: ViewContribution, dialog = false) => (
|
|
<PluginViewHost
|
|
key={`${pluginViewKey(route)}:${route.vm ?? ''}:${dialog ? 'dialog' : 'page'}`}
|
|
view={view}
|
|
locale={locale}
|
|
appearance={theme}
|
|
assetToken={pluginUI?.asset_token ?? ''}
|
|
vm={route.vm}
|
|
dialog={dialog}
|
|
metadata={pluginViewMeta[pluginViewKey(route)]}
|
|
onMetadata={(metadata) => updateViewMetadata(view, metadata)}
|
|
onOpenView={openView}
|
|
onCloseView={dialog ? () => {
|
|
setPluginViewState((current) => closePluginDialog(current, route))
|
|
return { closed: true }
|
|
} : closeView}
|
|
onNavigate={navigateHost}
|
|
/>
|
|
)
|
|
const renderVMTabs = () => {
|
|
if (!selectedVM) return null
|
|
const tabs = pluginViews.filter((view) => view.location === 'vm.tab' && viewAvailable(view, vmRefKey(selectedVM)))
|
|
if (tabs.length === 0) return null
|
|
return (
|
|
<div className="tabs rg-p-tabs" role="tablist" aria-label={tr('overview')}>
|
|
<button type="button" role="tab" className="tab rg-p-tab" aria-selected={!activePluginRoute || activePluginRoute.location !== 'vm.tab'} onClick={closeView}>
|
|
{tr('overview')}
|
|
</button>
|
|
{tabs.map((view) => {
|
|
const key = pluginViewKey({ pluginId: view.pluginId ?? '', viewId: view.id })
|
|
const selectedTab = activePluginRoute?.location === 'vm.tab' && pluginViewKey(activePluginRoute) === key
|
|
const badge = pluginViewMeta[key]?.badge
|
|
return (
|
|
<button key={key} type="button" role="tab" className="tab rg-p-tab" aria-selected={selectedTab} onClick={() => openViewFromClick(view, vmRefKey(selectedVM))}>
|
|
{locText(view.title, locale, view.id)}{badge ? ` · ${badge.text}` : ''}
|
|
</button>
|
|
)
|
|
})}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
const sidebarSelected = activePluginRoute?.location === 'sidebar' ? `__plugin_view__:${pluginViewKey(activePluginRoute)}` : selected
|
|
|
|
useEffect(() => {
|
|
if (!selectedVM) { setDetail(null); return }
|
|
api.GetVMDetail(selectedVM.name).then(setDetail).catch(() => setDetail(null))
|
|
}, [selectedVM?.name, selectedVM?.driver_id, selectedVM?.state, state?.transitions[selectedVM ? vmRefKey(selectedVM) : ''], 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((e) => console.warn('[app] GetVMNote failed:', vm.name, e))
|
|
}
|
|
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((e) => console.warn('[app] GetVMMacOS failed:', vm.name, e))
|
|
}
|
|
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)
|
|
const settingsPluginViews = pluginViews.filter((view) => view.location === 'settings' && viewAvailable(view, selectedVM ? vmRefKey(selectedVM) : undefined)).map((view) => {
|
|
const key = pluginViewKey({ pluginId: view.pluginId ?? '', viewId: view.id })
|
|
return { id: key, title: locText(view.title, locale, view.id), badge: pluginViewMeta[key]?.badge?.text, onOpen: () => openViewFromClick(view) }
|
|
})
|
|
const sidebarPluginViews = pluginViews.filter((view) => view.location === 'sidebar' && viewAvailable(view, selectedVM ? vmRefKey(selectedVM) : undefined)).map((view) => {
|
|
const key = pluginViewKey({ pluginId: view.pluginId ?? '', viewId: view.id })
|
|
const icon = view.icon ? buildSafePluginAssetURL(pluginUI?.asset_token ?? '', view.pluginId, view.icon) ?? undefined : undefined
|
|
return { id: `__plugin_view__:${key}`, view, title: locText(view.title, locale, view.id), badge: pluginViewMeta[key]?.badge?.text, icon }
|
|
})
|
|
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 pushToast = toasts.push
|
|
useEffect(() => events.onRuntimeWarning((message) => {
|
|
const { summary, code, rawDetail } = parseAppError(message)
|
|
pushToast({
|
|
kind: 'warning',
|
|
title: summary,
|
|
errorCode: code,
|
|
rawDetail,
|
|
detailsLabel: t(locale, 'errRawDetailsToggle'),
|
|
copyDetailsLabel: t(locale, 'errCopyDetails'),
|
|
})
|
|
}), [locale, pushToast])
|
|
useEffect(() => events.onHostDrop(({ delivered, mode }) => {
|
|
if (mode !== 'l1_share' || delivered.length === 0) return
|
|
const title = delivered.length === 1
|
|
? t(locale, 'toastFileDelivered', { name: delivered[0] })
|
|
: t(locale, 'toastFilesDelivered', { n: delivered.length })
|
|
pushToast({ kind: 'ok', title })
|
|
}), [locale, pushToast])
|
|
useEffect(() => events.onHostDropAck((ack) => onHostDropAckRef.current(ack)), [])
|
|
const effectiveState = selectedVM ? (state?.transitions[vmRefKey(selectedVM)] ?? selectedVM.state) : ''
|
|
const pending = selectedVM ? (state?.pending_changes[vmRefKey(selectedVM)] ?? []) : []
|
|
const fixedModeSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'display-fixed-mode') ?? false
|
|
const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime
|
|
const canSuspend = state?.can_suspend ?? false
|
|
|
|
onTaskRef.current = (task: Task) => {
|
|
publishPluginHostEvent('task.updated', 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 (e) { console.warn('[app] clear dismissed update failed:', e) }
|
|
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 (e) { console.warn('[app] persist dismissed update failed:', e) }
|
|
}
|
|
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 (e) {
|
|
console.warn('[app] track last app version failed:', e)
|
|
}
|
|
}, [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) {
|
|
if (parseAppError(e).code === 'E_RUNTIME_ACTIVATION') await refresh()
|
|
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')
|
|
// The data folder opened read-only (internal/dataroot): nothing in it may be
|
|
// changed, so the workspace gives way to a screen that explains why.
|
|
const showReadOnly = !!state && !showSetup && !!state.data_root_status?.read_only
|
|
|
|
// UI Contract v2 read-only document state attributes.
|
|
const currentView = showSetup ? 'setup' : activePluginRoute?.location === 'sidebar' ? 'plugins' : activePluginRoute?.location === 'settings' ? 'settings' : activePluginRoute?.location === 'vm.tab' ? 'vm' : 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[vmRefKey(v)] ?? 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[vmRefKey(v)] ?? 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, reducedMotion])
|
|
|
|
// UI SDK event stream (ui-contract UI_CONTRACT_SDK_EVENTS). emitThemeEvent is
|
|
// a no-op unless an interactive theme is loaded; payloads carry no paths.
|
|
const selectedRef = selectedVM ? vmRefKey(selectedVM) : ''
|
|
useEffect(() => {
|
|
emitThemeEvent('view.changed', { view: currentView, vm: selectedRef })
|
|
}, [currentView, selectedRef])
|
|
const vmStatesRef = useRef<Record<string, string> | null>(null)
|
|
useEffect(() => {
|
|
const next: Record<string, string> = {}
|
|
for (const v of vms) next[vmRefKey(v)] = state?.transitions[vmRefKey(v)] ?? v.state
|
|
const prev = vmStatesRef.current
|
|
vmStatesRef.current = next
|
|
if (!prev) return
|
|
for (const v of vms) {
|
|
const key = vmRefKey(v)
|
|
if (prev[key] !== undefined && prev[key] !== next[key]) {
|
|
const payload = { vm: key, name: v.name, driver: v.driver_id ?? '', from: prev[key], to: next[key] }
|
|
emitThemeEvent('vm.stateChanged', payload)
|
|
publishPluginHostEvent('vm.stateChanged', payload)
|
|
}
|
|
}
|
|
}, [vms, state?.transitions])
|
|
const taskStatesRef = useRef<Record<string, { status: string; percent: number }> | null>(null)
|
|
useEffect(() => {
|
|
const prev = taskStatesRef.current
|
|
const next: Record<string, { status: string; percent: number }> = {}
|
|
for (const t of Object.values(taskMap)) next[t.id] = { status: t.status, percent: t.percent }
|
|
taskStatesRef.current = next
|
|
if (!prev) return
|
|
for (const t of Object.values(taskMap)) {
|
|
const was = prev[t.id]
|
|
const info = { id: t.id, kind: t.kind, vm: t.vm ?? '', percent: t.percent }
|
|
if (!was && t.status === 'running') emitThemeEvent('task.started', info)
|
|
else if (was?.status === 'running' && t.status === 'running' && was.percent !== t.percent) emitThemeEvent('task.progress', info)
|
|
if ((!was || was.status === 'running') && t.status !== 'running') emitThemeEvent('task.finished', { ...info, status: t.status })
|
|
}
|
|
}, [taskMap])
|
|
|
|
// Refresh contributions together with the active theme after registry changes.
|
|
useEffect(() => {
|
|
let live = true
|
|
api.GetActiveTheme().then((theme) => {
|
|
if (live) setActiveThemePayload(theme)
|
|
}).catch((e) => console.warn('[app] GetActiveTheme failed:', e))
|
|
api.GetPluginUIContributions().then((contributions) => {
|
|
if (live) setPluginUI(contributions)
|
|
}).catch((e) => {
|
|
console.warn('[app] GetPluginUIContributions failed:', e)
|
|
if (live) setPluginUI((previous) => previous ?? {} as PluginUIContributions)
|
|
})
|
|
return () => { live = false }
|
|
}, [themeRevision, state?.safe_mode])
|
|
|
|
useEffect(() => {
|
|
void applyActiveTheme(
|
|
activeThemePayload,
|
|
theme,
|
|
() => uiStateRef.current,
|
|
{
|
|
toggleSidebar,
|
|
openSettings: () => setSelected(SETTINGS_ID),
|
|
focusVMWindow: (vmName) => { void api.FocusVMWindow(vmName).catch((e) => console.warn('[theme] FocusVMWindow failed:', vmName, e)) },
|
|
},
|
|
)
|
|
// 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 logDriverID = vms.find((v) => v.name === name)?.driver_id ?? ''
|
|
const text = await api.ReadVMLogsWithDriver(logDriverID, 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: parsed.code === 'E_RUNTIME_ACTIVATION' ? tr('runtimeActivationFailed') : title,
|
|
description: parsed.summary,
|
|
errorCode: parsed.code,
|
|
rawDetail: parsed.rawDetail,
|
|
detailsLabel: tr('errRawDetailsToggle'),
|
|
copyDetailsLabel: tr('errCopyDetails'),
|
|
action: { label: tr('viewLogs'), onClick: () => openLogs('app') },
|
|
})
|
|
}
|
|
onHostDropAckRef.current = (ack) => {
|
|
if (ack.status === 'failed') fail(tr('failDrop'), ack.error || '')
|
|
}
|
|
|
|
const activeVMBusy = (name: string): VMBusyAction | undefined => {
|
|
const ops = busyOpsRef.current.get(name)
|
|
if (!ops || ops.size === 0) return undefined
|
|
let latest: VMBusyAction | undefined
|
|
for (const act of ops.values()) latest = act
|
|
return latest
|
|
}
|
|
|
|
const syncBusyState = () => {
|
|
const next: Record<string, VMBusyAction> = Object.create(null)
|
|
for (const [vmName, ops] of busyOpsRef.current) {
|
|
let latest: VMBusyAction | undefined
|
|
for (const act of ops.values()) latest = act
|
|
if (latest) next[vmName] = latest
|
|
}
|
|
setBusy(next)
|
|
}
|
|
|
|
const beginVMBusy = (name: string, action: VMBusyAction): number | null => {
|
|
const ops = busyOpsRef.current.get(name)
|
|
if (ops && ops.size > 0) {
|
|
if (action !== 'forceStop') return null
|
|
for (const act of ops.values()) {
|
|
if (act === 'forceStop') return null
|
|
}
|
|
}
|
|
const token = ++nextBusyTokenRef.current
|
|
const vmOps = ops ?? new Map<number, VMBusyAction>()
|
|
vmOps.set(token, action)
|
|
busyOpsRef.current.set(name, vmOps)
|
|
syncBusyState()
|
|
return token
|
|
}
|
|
|
|
const endVMBusy = (name: string, token: number) => {
|
|
const ops = busyOpsRef.current.get(name)
|
|
if (!ops || !ops.delete(token)) return
|
|
if (ops.size === 0) busyOpsRef.current.delete(name)
|
|
syncBusyState()
|
|
}
|
|
|
|
const runVMAction = async (name: string, action: VMBusyAction, fn: () => Promise<void>, okTitle?: string) => {
|
|
const token = beginVMBusy(name, action)
|
|
if (token === null) return
|
|
try {
|
|
await fn()
|
|
if (okTitle) toasts.push({ kind: 'ok', title: okTitle })
|
|
await refresh()
|
|
} catch (e) {
|
|
fail(tr(failKey[action]), e)
|
|
} finally {
|
|
endVMBusy(name, token)
|
|
}
|
|
}
|
|
|
|
// 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>) => {
|
|
const token = beginVMBusy(name, 'type')
|
|
if (token === null) return
|
|
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 {
|
|
endVMBusy(name, token)
|
|
}
|
|
}
|
|
|
|
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
|
|
}
|
|
}
|
|
const token = beginVMBusy(name, 'attachInstaller')
|
|
if (token === null) return
|
|
try {
|
|
const fileName = await api.AttachInstaller(name, picked)
|
|
toasts.push({
|
|
kind: 'ok',
|
|
title: tr(running ? 'toastInstallerAttachedNextStart' : 'toastInstallerAttached', { name: fileName }),
|
|
})
|
|
await refresh()
|
|
} finally {
|
|
endVMBusy(name, token)
|
|
}
|
|
} catch (e) {
|
|
fail(tr('failAttachInstaller'), e)
|
|
}
|
|
}
|
|
|
|
const onVMActionFor = (name: string, action: VMAction, isRunning: boolean) => {
|
|
const actionVM = vms.find((v) => vmRefKey(v) === name) ?? vms.find((v) => v.name === name)
|
|
const actionDriverID = actionVM?.driver_id ?? ''
|
|
name = actionVM?.name ?? name
|
|
if (!canSuspend && (action === 'suspend' || action === 'resume')) return
|
|
const activeBusy = activeVMBusy(name)
|
|
if (
|
|
activeBusy
|
|
&& action !== 'openFolder'
|
|
&& action !== 'openSharedFolder'
|
|
&& (action !== 'forceStop' || activeBusy === 'forceStop')
|
|
) {
|
|
return
|
|
}
|
|
switch (action) {
|
|
case 'start': return runVMAction(name, action, () => api.StartVMWithDriver(actionDriverID, name))
|
|
case 'suspend': return runVMAction(name, action, () => api.SuspendVMWithDriver(actionDriverID, name), tr('toastSuspended', { name }))
|
|
case 'resume': return runVMAction(name, action, () => api.ResumeVMWithDriver(actionDriverID, name), tr('toastResumed', { name }))
|
|
case 'discardSuspend': return setDiscardSuspendTarget(actionVM ? vmRefKey(actionVM) : name)
|
|
case 'focus': return api.FocusVMWindowWithDriver(actionDriverID, name).catch((e) => fail(tr('failFocus'), e))
|
|
case 'fullscreen':
|
|
return runVMAction(name, action, async () => {
|
|
const isFullscreen = await api.ToggleVMFullscreenWithDriver(actionDriverID, name)
|
|
refreshVMStatsWithDriver(actionDriverID, name, { window_fullscreen: isFullscreen })
|
|
})
|
|
case 'screenshot': return runVMAction(name, action, () => api.CopyVMScreenshotWithDriver(actionDriverID, name), tr('toastScreenshotCopied'))
|
|
case 'stop': return runVMAction(name, action, () => api.StopVMWithDriver(actionDriverID, name, false), tr('toastStopped', { name }))
|
|
case 'forceStop': return runVMAction(name, action, () => api.StopVMWithDriver(actionDriverID, name, true), tr('toastStopped', { name }))
|
|
case 'restart': return runVMAction(name, action, () => api.RestartVMWithDriver(actionDriverID, name))
|
|
case 'eject': return runVMAction(name, action, () => api.EjectInstallerWithDriver(actionDriverID, 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.ExportDiagnosticsWithDriver(actionDriverID, name) }, tr('toastDiagExported'))
|
|
case 'cloneVM':
|
|
return setCloneSource({ name, driverID: actionDriverID })
|
|
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(actionVM ? vmRefKey(actionVM) : name)
|
|
}
|
|
}
|
|
|
|
const onVMAction = (action: VMAction) => {
|
|
if (!selectedVM) return
|
|
return onVMActionFor(vmRefKey(selectedVM), action, selectedVM.state === 'running')
|
|
}
|
|
|
|
const onSidebarContextAction = (name: string, action: VMAction | 'settings') => {
|
|
const vm = vms.find((v) => vmRefKey(v) === name) ?? vms.find((v) => v.name === name)
|
|
const st = state?.transitions[vm ? vmRefKey(vm) : name] ?? vm?.state ?? 'stopped'
|
|
if (action === 'settings') {
|
|
if (st === 'suspended' || st === 'suspending' || st === 'resuming') return
|
|
setSelected(name)
|
|
api.GetVMDetail(vm?.name ?? name).then((d) => { setDetail(d); setShowSettings(true) }).catch((e) => fail(tr('failGeneric'), e))
|
|
return
|
|
}
|
|
onVMActionFor(name, action, st === 'running')
|
|
}
|
|
|
|
// The state's own main action (Start, Resume while suspended, 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) => vmRefKey(v) === name) ?? vms.find((v) => v.name === name)
|
|
if (!vm || activeVMBusy(vm.name)) return
|
|
const key = vmRefKey(vm)
|
|
const st = state?.transitions[key] ?? vm.state
|
|
if (st === 'stopped') onVMActionFor(key, 'start', false)
|
|
else if (st === 'suspended') onVMActionFor(key, 'resume', false)
|
|
else if (st === 'running') onVMActionFor(key, 'focus', true)
|
|
}
|
|
|
|
const confirmDelete = (keepFiles: boolean) => {
|
|
const target = deleteTarget
|
|
setDeleteTarget(null)
|
|
const targetVM = vms.find((v) => vmRefKey(v) === target) ?? vms.find((v) => v.name === target)
|
|
const name = targetVM?.name ?? target
|
|
const driverID = targetVM?.driver_id ?? ''
|
|
if (name) runVMAction(name, 'delete', () => api.DeleteVMWithDriver(driverID, name, keepFiles), tr('toastDeleted', { name }))
|
|
}
|
|
|
|
const confirmDiscardSuspend = () => {
|
|
const target = discardSuspendTarget
|
|
setDiscardSuspendTarget(null)
|
|
const targetVM = vms.find((v) => vmRefKey(v) === target) ?? vms.find((v) => v.name === target)
|
|
const name = targetVM?.name ?? target
|
|
const driverID = targetVM?.driver_id ?? ''
|
|
if (name) runVMAction(name, 'discardSuspend', () => api.DiscardSuspendWithDriver(driverID, name), tr('toastDiscardSuspend', { 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.name, 'cloneVM', async () => {
|
|
await api.CloneVMCoWWithDriver(src.driverID, src.name, cloneName)
|
|
setSelected(vmRefKey({ name: cloneName, driver_id: src.driverID }))
|
|
}, 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: true,
|
|
network_mode: 'nat',
|
|
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()
|
|
const parsed = parseAppError(e)
|
|
if (parsed.code === 'E_NETWORK_CREATE_BRIDGE_PENDING') {
|
|
setSelected(name)
|
|
toasts.push({
|
|
kind: 'error',
|
|
title: tr('toastCreated', { name }),
|
|
description: parsed.summary,
|
|
errorCode: parsed.code,
|
|
rawDetail: parsed.rawDetail,
|
|
detailsLabel: tr('errRawDetailsToggle'),
|
|
copyDetailsLabel: tr('errCopyDetails'),
|
|
action: { label: tr('settings'), onClick: () => {
|
|
api.GetVMDetail(name).then((d) => { setDetail(d); setSelected(name); setShowSettings(true) }).catch((err) => fail(tr('failGeneric'), err))
|
|
} },
|
|
})
|
|
return
|
|
}
|
|
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
|
|
}
|
|
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 (see docs/design-guidelines.md). Dialogs own the keyboard while open.
|
|
const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {})
|
|
const appDialogOpen = showSetup || showReadOnly || showWizard || showSettings || affinityTarget || deleteTarget ||
|
|
discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate
|
|
shortcutRef.current = (e: KeyboardEvent) => {
|
|
if (!e.ctrlKey || e.altKey || e.metaKey) return
|
|
if (appDialogOpen) return
|
|
if (hasVisibleDialog()) return
|
|
const k = e.key.toLowerCase()
|
|
if (k === 'n') { e.preventDefault(); openWizard() }
|
|
else if (k === ',' && detail && effectiveState !== 'suspended' && effectiveState !== 'suspending' && effectiveState !== 'resuming') { 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(vmRefKey(selectedVM)) }
|
|
}
|
|
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() })
|
|
const offDiscard = events.onTrayDiscardSuspend((name) => {
|
|
setSelected(name)
|
|
setDiscardSuspendTarget(name)
|
|
})
|
|
return () => { offSelect(); offNew(); offDiscard() }
|
|
}, [])
|
|
|
|
// 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 (
|
|
<ThemeVisualsProvider payload={activeThemePayload}>
|
|
<TooltipProvider>
|
|
<div className="app-shell rg-p-shell">
|
|
<div className="rg-layer rg-layer-background" data-rg-layer="layer.background" aria-hidden="true" />
|
|
<header className="titlebar rg-p-titlebar" onDoubleClick={() => WindowToggleMaximise()}>
|
|
{showSetup || showReadOnly || !state ? (
|
|
<div className="brand rg-p-brand">
|
|
<BrandMark className="brand-mark" />
|
|
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,
|
|
driver_id: selectedVM.driver_id,
|
|
state: effectiveState,
|
|
busy: Object.prototype.hasOwnProperty.call(busy, selectedVM.name),
|
|
graphics: detail?.name === selectedVM.name ? detail.graphics : undefined,
|
|
canSuspend,
|
|
} : null}
|
|
onNewVM={openWizard}
|
|
onVMAction={onVMAction}
|
|
onVMSettings={() => { if (detail && effectiveState !== 'suspended') 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="rg-slot-anchor titlebar-center" data-rg-slot="titlebar.center" />
|
|
<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}
|
|
onPluginsChanged={() => setThemeRevision((r) => r + 1)}
|
|
onFolderDone={folderDone}
|
|
onFinish={() => setSetupStage(null)}
|
|
onError={fail}
|
|
onChannel={setChannel}
|
|
onInstallRuntime={installRuntime}
|
|
onCancelTask={cancelTask}
|
|
onImportRuntime={importRuntime}
|
|
/>
|
|
</Suspense>
|
|
) : showReadOnly && state ? (
|
|
<DataRootReadOnly
|
|
locale={locale}
|
|
status={state.data_root_status}
|
|
message={state.data_root_message ?? ''}
|
|
onChanged={() => { void refresh() }}
|
|
onError={fail}
|
|
/>
|
|
) : (
|
|
<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 ?? {}}
|
|
busyActions={busy}
|
|
selected={sidebarSelected}
|
|
hostReady={hostReady}
|
|
canSuspend={canSuspend}
|
|
onSelect={(id) => {
|
|
if (id.startsWith('__plugin_view__:')) {
|
|
const item = sidebarPluginViews.find((entry) => entry.id === id)
|
|
if (item) openViewFromClick(item.view)
|
|
} else {
|
|
setSelected(id)
|
|
}
|
|
if (sidebarOpen && window.matchMedia('(max-width: 768px)').matches) {
|
|
toggleSidebar()
|
|
}
|
|
}}
|
|
displayNames={displayNames}
|
|
macosMajors={macosMajors}
|
|
onActivate={primaryAction}
|
|
onNew={openWizard}
|
|
onVMContextAction={onSidebarContextAction}
|
|
downloading={Object.values(taskMap).some(isActiveInstallerTask)}
|
|
safeMode={state?.safe_mode}
|
|
updateDot={!!appUpdate?.has_update}
|
|
pluginViews={sidebarPluginViews}
|
|
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">
|
|
{state?.vm_list_error && <div className="notice notice-error" role="alert">{state.vm_list_error}</div>}
|
|
<Suspense fallback={null}>
|
|
{!state ? (
|
|
<div className="page">
|
|
{loadError ? <div className="notice notice-error">{loadError}</div> : <span className="muted">…</span>}
|
|
</div>
|
|
) : activePluginRoute && activePluginView ? (
|
|
<>
|
|
{activePluginRoute.location === 'vm.tab' && renderVMTabs()}
|
|
{renderPluginView(activePluginRoute, activePluginView)}
|
|
</>
|
|
) : selected === INSTALLERS_ID ? (
|
|
<ImagesPage
|
|
locale={locale}
|
|
appearance={theme}
|
|
pluginUI={pluginUI}
|
|
onOpenPlugins={() => setSelected(PLUGINS_ID)}
|
|
renderNativeSource={(nativeId, opts) => (
|
|
nativeId === 'macos' ? (
|
|
<Suspense fallback={null}>
|
|
<InstallersPage
|
|
locale={locale}
|
|
host={state.host}
|
|
tasks={Object.values(taskMap)}
|
|
refreshSignal={opts.refreshSignal}
|
|
onBusyChange={opts.onBusyChange}
|
|
onCreateWithInstaller={openWizardWithInstaller}
|
|
onError={fail}
|
|
onToast={(title) => toasts.push({ kind: 'ok', title })}
|
|
/>
|
|
</Suspense>
|
|
) : null
|
|
)}
|
|
/>
|
|
) : selected === PLUGINS_ID ? (
|
|
<PluginsPage
|
|
locale={locale}
|
|
appearance={theme}
|
|
safeMode={state.safe_mode}
|
|
onRefresh={refresh}
|
|
onError={fail}
|
|
onThemeChanged={() => setThemeRevision((r) => r + 1)}
|
|
onLocaleSwitch={(l) => void setLang(l)}
|
|
onOpenView={openView}
|
|
onNavigate={navigateHost}
|
|
/>
|
|
) : selectedVM ? (
|
|
<>
|
|
{renderVMTabs()}
|
|
<VMPage
|
|
locale={locale}
|
|
name={selectedVM.name}
|
|
driverID={selectedVM.driver_id ?? ''}
|
|
displayName={displayNames[selectedVM.name] ?? ''}
|
|
onDisplayNameSaved={(n) => setDisplayNames((m) => ({ ...m, [selectedVM.name]: n }))}
|
|
macosMajor={macosMajors[selectedVM.name] ?? null}
|
|
state={effectiveState}
|
|
canSuspend={canSuspend}
|
|
currentAgentVersion={state.current_agent_version}
|
|
guideActive={state.active_guides?.includes(selectedVM.name) ?? false}
|
|
installGuideEnabled={!!state.install_guide_enabled}
|
|
detail={detail}
|
|
host={state.host}
|
|
pending={pending}
|
|
busyAction={Object.prototype.hasOwnProperty.call(busy, selectedVM.name) ? busy[selectedVM.name] : undefined}
|
|
onAction={onVMAction}
|
|
onPluginCommand={(pluginID, command, title) => {
|
|
const name = selectedVM.name
|
|
void runVMAction(name, 'pluginCommand', async () => {
|
|
await api.InvokePluginCommand(pluginID, command, { vm: name })
|
|
}, title)
|
|
}}
|
|
onSettings={() => setShowSettings(true)}
|
|
onOpenAffinity={() => setAffinityTarget({ name: selectedVM.name, driverID: selectedVM.driver_id ?? '' })}
|
|
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}
|
|
tasks={Object.values(taskMap)}
|
|
themeMode={effectiveThemeMode}
|
|
canLight={canLight}
|
|
canDark={canDark}
|
|
pluginViews={settingsPluginViews}
|
|
onThemeMode={setThemeMode}
|
|
onSetLocale={setLang}
|
|
onRefresh={refresh}
|
|
onToast={(title) => toasts.push({ kind: 'ok', title })}
|
|
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}
|
|
onImportRuntime={importRuntime}
|
|
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}
|
|
fixedModeSupported={fixedModeSupported}
|
|
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}
|
|
driverID={selectedVM?.driver_id ?? ''}
|
|
stats={latestVMStatsWithDriver(selectedVM?.driver_id ?? '', detail.name)}
|
|
host={state.host}
|
|
fixedModeSupported={fixedModeSupported}
|
|
optimizations={state.optimizations}
|
|
running={effectiveState === 'running'}
|
|
onCopy={copy}
|
|
onDiskChanged={refresh}
|
|
onOpenAffinity={() => setAffinityTarget({ name: detail.name, driverID: selectedVM?.driver_id ?? '' })}
|
|
affinityVersion={affinityVersion}
|
|
onHostChanged={refresh}
|
|
onToast={toasts.push}
|
|
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.name}
|
|
driverID={affinityTarget.driverID}
|
|
vcpus={detail?.name === affinityTarget.name ? 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} />
|
|
)}
|
|
|
|
{discardSuspendTarget && (() => {
|
|
const targetVM = vms.find((v) => vmRefKey(v) === discardSuspendTarget) ?? vms.find((v) => v.name === discardSuspendTarget)
|
|
const targetName = targetVM?.name ?? discardSuspendTarget
|
|
return (
|
|
<ConfirmDialog
|
|
title={tr('discardSuspendTitle', { name: displayNames[targetName] || targetName })}
|
|
description={tr('discardSuspendDesc')}
|
|
cancelLabel={tr('cancel')}
|
|
confirmLabel={tr('discardSuspendConfirm')}
|
|
onCancel={() => setDiscardSuspendTarget(null)}
|
|
onConfirm={confirmDiscardSuspend}
|
|
/>
|
|
)
|
|
})()}
|
|
|
|
{cloneSource && (
|
|
<CloneDialog
|
|
locale={locale}
|
|
sourceName={cloneSource.name}
|
|
defaultCloneName={`${cloneSource.name}-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(latestVMStatsWithDriver(selectedVM?.driver_id ?? '', sendTextTarget)?.guest_tools_connected ?? detail?.guest_tools_connected)}
|
|
onCancel={() => setSendTextTarget(null)}
|
|
onConfirm={(text) => {
|
|
const target = sendTextTarget
|
|
setSendTextTarget(null)
|
|
typeInto(target, () => api.TypeText(target, text))
|
|
}}
|
|
/>
|
|
)}
|
|
|
|
{/* Every open dialog stays mounted so the ones underneath keep their state. */}
|
|
{pluginViewState.dialogs.map((route) => {
|
|
const view = findRouteView(route)
|
|
return view && renderPluginView(route, view, true)
|
|
})}
|
|
|
|
<div className="rg-layer rg-layer-overlay" data-rg-layer="layer.overlay" aria-hidden="true" />
|
|
</div>
|
|
{/* Outside the isolated shell so toasts stay above dialogs and the overlay layer. */}
|
|
<Toaster items={toasts.items} onRemove={toasts.remove} closeLabel={tr('close')} dir={dir} />
|
|
<ThemeDecorations payload={activeThemePayload} snap={uiStateRef.current} locale={locale} />
|
|
</TooltipProvider>
|
|
</ThemeVisualsProvider>
|
|
)
|
|
}
|