* refactor: 收拢核心管线、强化错误处理、优化热路径与更新体积 * fix: preserve download recovery and bound PBZX decoding Keep VM diagnostics available during plugin initialization failures and verify settings through the unified driver lifecycle.
1544 lines
70 KiB
TypeScript
1544 lines
70 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 { AppDialogs } from './components/AppDialogs'
|
|
import { OnlineRecoveryDialog } from './macos/OnlineRecoveryDialog'
|
|
import { LogPanel, LogTab } from './components/LogPanel'
|
|
import { TitleMenus } from './components/TitleMenus'
|
|
import { UpdateCapsule } 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 { CreatingVMView } from './components/CreatingVMView'
|
|
import { VMPage } from './components/VMPage'
|
|
import { buildFallbackChain, I18nKey, localeDir, locText, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
|
|
import { defaultGuestLang, recommendedMemoryGB } from './lib/format'
|
|
import { initialWizardResolution } from './lib/displayResolution'
|
|
import { isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints'
|
|
import { resolveFullscreenHotkey } from './lib/fullscreenHotkey'
|
|
import { LogLine, appendLog, createLogLine } from './lib/logs'
|
|
import { macOSMajor } from './macos/macosRelease'
|
|
import { creatingVMTasks, currentTask, finishedTaskTTL, isActiveInstallerTask, pruneFinishedTasks, upsertTask } from './lib/tasks'
|
|
import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, notifyInteractiveThemeState } from './lib/themeEngine'
|
|
import type { UIStateSnapshot } from './lib/uiSdk'
|
|
import { hasVisibleDialog } from './lib/dialogState'
|
|
import { refreshSubscribedVMStats, refreshVMStats } from './lib/vmStats'
|
|
import { useAppearance } from './lib/useAppearance'
|
|
import { useAppUpdate } from './lib/useAppUpdate'
|
|
import { useFileDrop } from './lib/useFileDrop'
|
|
import { useThemeEvents } from './lib/useThemeEvents'
|
|
import { useVMBusy } from './lib/useVMBusy'
|
|
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, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMAction, VMBusyAction, VMDetail, VMInfo, VMListItem, ViewContribution } from './types'
|
|
import { Tip, TooltipProvider } from './ui/controls'
|
|
import { errorToast, Toaster, type ToastInput, useToasts } from './ui/toast'
|
|
import { BrandMark, ThemeDecorations, ThemeVisualsProvider } from './ui/themeVisuals'
|
|
import { api, DROP_NETWORK_VOLUMES_DENIED, events, WindowMinimise, WindowToggleMaximise, type ElevationPrompt } from './wails'
|
|
|
|
// Opened on demand, so each is its own chunk and stays out of the startup
|
|
// bundle: first-run setup, and the Engine / Installers / Settings pages.
|
|
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 PluginViewHost = lazy(() => import('./components/PluginViewHost').then((m) => ({ default: m.PluginViewHost })))
|
|
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
|
|
|
|
type HostDropAck = { status: string; error?: string }
|
|
|
|
export function showHostDropAck(
|
|
ack: HostDropAck,
|
|
locale: Locale,
|
|
pushToast: (toast: ToastInput) => void,
|
|
fail: (title: string, error: string) => void,
|
|
) {
|
|
if (ack.status !== 'failed') return
|
|
if (ack.error === DROP_NETWORK_VOLUMES_DENIED) {
|
|
pushToast({
|
|
kind: 'error',
|
|
title: t(locale, 'gtDropAccessLimited'),
|
|
description: t(locale, 'gtDropAccessHint'),
|
|
})
|
|
return
|
|
}
|
|
fail(t(locale, 'failDrop'), ack.error || '')
|
|
}
|
|
|
|
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 [detail, setDetail] = useState<VMDetail | null>(null)
|
|
// GetVMInfo for the selected non-macOS VM; macOS VMs use `detail` (GetVMDetail).
|
|
const [vmInfoLoaded, setVMInfoLoaded] = useState<VMInfo | null>(null)
|
|
const [detailRevision, setDetailRevision] = useState(0)
|
|
const [showWizard, setShowWizard] = useState(false)
|
|
const [wizardDraft, setWizardDraft] = useState<WizardDraft | null>(null)
|
|
const [pendingCreates, setPendingCreates] = useState<string[]>([])
|
|
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 [closeDownloadsOpen, setCloseDownloadsOpen] = useState(false)
|
|
const [elevationQueue, setElevationQueue] = useState<ElevationPrompt[]>([])
|
|
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 vmBusy = useVMBusy()
|
|
const [loadError, setLoadError] = useState('')
|
|
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 { theme, themeMode, canLight, canDark, setThemeMode, reducedMotion } = useAppearance(themeAppearanceCap)
|
|
|
|
// 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 (e) { console.warn('[app] read sidebar state failed:', e); 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: HostDropAck) => 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 line = createLogLine(entry)
|
|
if (!logsOpenRef.current && line.level === 'error') {
|
|
setUnseenErrors((n) => n + 1)
|
|
}
|
|
setLogLines((prev) => appendLog(prev, line))
|
|
})
|
|
// 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 existingVMNames = new Set(vms.map((v) => v.name))
|
|
const creatingTasks = creatingVMTasks(taskMap, existingVMNames)
|
|
const creatingByName = new Map(creatingTasks.map((t) => [t.subject, t]))
|
|
const creatingItems: { name: string; task?: Task }[] = [
|
|
...creatingTasks.map((t) => ({ name: t.subject, task: t })),
|
|
...pendingCreates
|
|
.filter((name) => !existingVMNames.has(name) && !creatingByName.has(name))
|
|
.map((name) => ({ name })),
|
|
]
|
|
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 selectedCreating = !selectedVM && !PAGE_IDS.includes(selected)
|
|
? creatingItems.find((item) => item.name === selected)
|
|
: undefined
|
|
|
|
const selectedIsMacOS = !!selectedVM && isMacOSDriver(selectedVM.driver_id)
|
|
const selectedTransition = state?.transitions[selectedVM ? vmRefKey(selectedVM) : '']
|
|
const pluginViews = pluginUI?.views ?? []
|
|
const findVM = (ref: string | null | undefined) =>
|
|
ref ? vms.find((v) => vmRefKey(v) === ref) ?? vms.find((v) => v.name === ref) : undefined
|
|
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) => (
|
|
<Suspense key={`${pluginViewKey(route)}:${route.vm ?? ''}:${dialog ? 'dialog' : 'page'}`} fallback={null}>
|
|
<PluginViewHost
|
|
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}
|
|
/>
|
|
</Suspense>
|
|
)
|
|
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 || !selectedIsMacOS) { setDetail(null); return }
|
|
let live = true
|
|
api.GetVMDetail(selectedVM.name)
|
|
.then((d) => { if (live) setDetail(d) })
|
|
.catch((e) => {
|
|
console.warn('[app] GetVMDetail failed:', selectedVM.name, e)
|
|
if (live) setDetail(null)
|
|
})
|
|
return () => { live = false }
|
|
}, [selectedVM?.name, selectedVM?.driver_id, selectedVM?.state, selectedTransition, selectedIsMacOS, detailRevision, state?.active_runtime?.commit, state?.runtime_capture_supported])
|
|
|
|
useEffect(() => {
|
|
if (!selectedVM || selectedIsMacOS) { setVMInfoLoaded(null); return }
|
|
let live = true
|
|
api.GetVMInfo(selectedVM.driver_id ?? '', selectedVM.name)
|
|
.then((info) => { if (live) setVMInfoLoaded(info) })
|
|
.catch((e) => {
|
|
console.warn('[app] GetVMInfo failed:', selectedVM.name, e)
|
|
if (live) setVMInfoLoaded(null)
|
|
})
|
|
return () => { live = false }
|
|
}, [selectedVM?.name, selectedVM?.driver_id, selectedVM?.state, selectedTransition, selectedIsMacOS, detailRevision])
|
|
// The polled list entry is fresher than the loaded detail for state, readiness and endpoints.
|
|
const vmInfo = selectedVM && !selectedIsMacOS ? liveVMInfo(selectedVM, vmInfoLoaded) : null
|
|
const selectedFeatures = vmFeatures(selectedVM)
|
|
const canSuspendVM = (vm: VMListItem | undefined) => {
|
|
const f = vmFeatures(vm)
|
|
return f.macos ? canSuspend : f.suspend
|
|
}
|
|
const vmsRef = useRef(vms)
|
|
vmsRef.current = vms
|
|
|
|
// Display names (the VM's note, .reims-go-note), keyed by VM reference: the
|
|
// sidebar and page title show them in place of the VM's name, which stays the
|
|
// identifier. Same-name VMs of different drivers keep separate notes.
|
|
const [displayNames, setDisplayNames] = useState<Record<string, string>>({})
|
|
const vmRefsKey = vms.map((v) => vmRefKey(v)).join('|')
|
|
useEffect(() => {
|
|
let live = true
|
|
for (const vm of vms) {
|
|
const key = vmRefKey(vm)
|
|
api.GetVMNote(vm.driver_id ?? '', vm.name)
|
|
.then((n) => { if (live) setDisplayNames((m) => ({ ...m, [key]: (n ?? '').trim() })) })
|
|
.catch((e) => console.warn('[app] GetVMNote failed:', key, e))
|
|
}
|
|
return () => { live = false }
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [vmRefsKey])
|
|
|
|
// Each macOS VM's major version for its icon: the release recorded at
|
|
// creation (.reims-go-macos), else a guess from its name or display name.
|
|
// Other drivers' VMs have no macOS release and are never asked.
|
|
const [releases, setReleases] = useState<Record<string, string>>({})
|
|
useEffect(() => {
|
|
let live = true
|
|
for (const vm of vms) {
|
|
if (!isMacOSDriver(vm.driver_id)) continue
|
|
const key = vmRefKey(vm)
|
|
api.GetVMMacOS(vm.name)
|
|
.then((r) => { if (live) setReleases((m) => ({ ...m, [key]: (r ?? '').trim() })) })
|
|
.catch((e) => console.warn('[app] GetVMMacOS failed:', key, e))
|
|
}
|
|
return () => { live = false }
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [vmRefsKey])
|
|
const macosMajors: Record<string, number | null> = {}
|
|
for (const vm of vms) {
|
|
const key = vmRefKey(vm)
|
|
macosMajors[key] = isMacOSDriver(vm.driver_id) ? macOSMajor(releases[key], vm.name, displayNames[key]) : null
|
|
}
|
|
|
|
// 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 diskCacheSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'win32-native-aio') ?? false
|
|
const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime
|
|
const canSuspend = state?.can_suspend ?? false
|
|
const fullscreenHotkey = state?.config.fullscreen_hotkey_enabled
|
|
? resolveFullscreenHotkey(state.config.fullscreen_hotkey)
|
|
: undefined
|
|
|
|
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 appChannelSeqRef = useRef(0)
|
|
const appChannelPendingRef = useRef<'stable' | 'alpha' | 'dev' | null>(null)
|
|
const appChannelFlushRef = useRef<Promise<void> | null>(null)
|
|
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') => {
|
|
const seq = ++appChannelSeqRef.current
|
|
setState((prev) => (prev ? { ...prev, config: { ...prev.config, app_update_channel: ch } } : prev))
|
|
appChannelPendingRef.current = ch
|
|
if (!appChannelFlushRef.current) {
|
|
appChannelFlushRef.current = (async () => {
|
|
while (appChannelPendingRef.current !== null) {
|
|
const target = appChannelPendingRef.current
|
|
appChannelPendingRef.current = null
|
|
await api.SetAppUpdateChannel(target)
|
|
}
|
|
})().finally(() => {
|
|
appChannelFlushRef.current = null
|
|
})
|
|
}
|
|
try {
|
|
await appChannelFlushRef.current
|
|
} catch (e) {
|
|
if (appChannelSeqRef.current === seq) {
|
|
appChannelPendingRef.current = null
|
|
void refresh()
|
|
throw e
|
|
}
|
|
return
|
|
}
|
|
if (appChannelSeqRef.current !== seq) return
|
|
await update.recheck(false)
|
|
if (appChannelSeqRef.current === seq) void refresh()
|
|
}
|
|
const cancelTask = (id: string) => { api.CancelTask(id).catch((e) => fail(tr('failGeneric'), e)) }
|
|
|
|
// 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 () => {
|
|
try {
|
|
const s = await api.GetState()
|
|
setState(s)
|
|
setSetupStage(s?.active_runtime ? null : 'runtime')
|
|
} catch (e) {
|
|
console.warn('[app] GetState after setup failed:', e)
|
|
fail(tr('failGeneric'), e)
|
|
setSetupStage('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(vmBusy.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])
|
|
|
|
useThemeEvents({ view: currentView, selectedVM: selectedVM ? vmRefKey(selectedVM) : '', vms, transitions: state?.transitions, tasks: 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) => {
|
|
const vm = vmsRef.current.find((v) => vmRefKey(v) === vmName) ?? vmsRef.current.find((v) => v.name === vmName)
|
|
void api.FocusVMWindow(vm?.driver_id ?? '', vm?.name ?? 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 logVM = name === selectedVM?.name ? selectedVM : vms.find((v) => v.name === name)
|
|
const logDriverID = logVM?.driver_id ?? ''
|
|
const text = await api.ReadVMLogs(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 toast = errorToast(locale, title, e)
|
|
toasts.push({
|
|
...toast,
|
|
title: toast.errorCode === 'E_RUNTIME_ACTIVATION' ? tr('runtimeActivationFailed') : title,
|
|
action: { label: tr('viewLogs'), onClick: () => openLogs('app') },
|
|
})
|
|
}
|
|
const update = useAppUpdate({ ready: !!state, tasks: taskMap, runningVMCount, onError: (e) => fail(tr('updateFailed'), e) })
|
|
onHostDropAckRef.current = (ack) => showHostDropAck(ack, locale, toasts.push, fail)
|
|
|
|
const runVMAction = async (name: string, action: VMBusyAction, fn: () => Promise<void>, okTitle?: string) => {
|
|
const token = vmBusy.begin(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 {
|
|
vmBusy.end(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 (busyKey: string, fn: () => Promise<number>) => {
|
|
const token = vmBusy.begin(busyKey, '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 {
|
|
vmBusy.end(busyKey, token)
|
|
}
|
|
}
|
|
|
|
const attachInstaller = async (busyKey: string, 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 = vmBusy.begin(busyKey, '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 {
|
|
vmBusy.end(busyKey, token)
|
|
}
|
|
} catch (e) {
|
|
fail(tr('failAttachInstaller'), e)
|
|
}
|
|
}
|
|
|
|
// Hosted VMs have no window: the primary action is their best ready endpoint.
|
|
const openEndpoint = (vm: VMListItem, kind: string) => {
|
|
api.OpenVMEndpoint(vm.driver_id ?? '', vm.name, kind, '').catch((e) => fail(tr('failEndpointOpen'), e))
|
|
}
|
|
const openPrimaryEndpoint = (vm: VMListItem) => {
|
|
const { primary } = splitEndpoints(vm.endpoints)
|
|
if (primary) openEndpoint(vm, primary.kind)
|
|
}
|
|
|
|
// Actions that only the macOS driver implements (name-based or macOS guest features).
|
|
const MACOS_ONLY_ACTIONS: readonly VMAction[] = [
|
|
'finishInstall', 'enterRecovery', 'attachInstaller', 'attachGuestTools', 'detachGuestTools',
|
|
'openSharedFolder', 'upgradeNVMe', 'openFolder',
|
|
]
|
|
|
|
const onVMActionFor = (ref: string, action: VMAction, isRunning: boolean) => {
|
|
const actionVM = findVM(ref)
|
|
const actionDriverID = actionVM?.driver_id ?? ''
|
|
const key = actionVM ? vmRefKey(actionVM) : ref
|
|
const name = actionVM?.name ?? ref
|
|
const features = vmFeatures(actionVM)
|
|
if (!canSuspendVM(actionVM) && (action === 'suspend' || action === 'resume')) return
|
|
if (!features.macos && MACOS_ONLY_ACTIONS.includes(action)) return
|
|
if (action === 'fullscreen' && !features.fullscreen) return
|
|
if (action === 'screenshot' && !features.screenshot) return
|
|
if ((action === 'type' || action === 'sendText') && !features.sendText) return
|
|
if (action === 'focus' && !features.window) {
|
|
if (actionVM) openPrimaryEndpoint(actionVM)
|
|
return
|
|
}
|
|
const activeBusy = vmBusy.current(key)
|
|
if (
|
|
activeBusy
|
|
&& action !== 'openFolder'
|
|
&& action !== 'openSharedFolder'
|
|
&& (action !== 'forceStop' || activeBusy === 'forceStop')
|
|
) {
|
|
return
|
|
}
|
|
switch (action) {
|
|
case 'start': return runVMAction(key, action, () => api.StartVM(actionDriverID, name))
|
|
case 'suspend': return runVMAction(key, action, () => api.SuspendVM(actionDriverID, name), tr('toastSuspended', { name }))
|
|
case 'resume': return runVMAction(key, action, () => api.ResumeVM(actionDriverID, name), tr('toastResumed', { name }))
|
|
case 'discardSuspend': return setDiscardSuspendTarget(key)
|
|
case 'focus': return api.FocusVMWindow(actionDriverID, name).catch((e) => fail(tr('failFocus'), e))
|
|
case 'fullscreen':
|
|
return runVMAction(key, action, async () => {
|
|
const isFullscreen = await api.ToggleVMFullscreen(actionDriverID, name)
|
|
refreshVMStats(actionDriverID, name, { window_fullscreen: isFullscreen })
|
|
})
|
|
case 'screenshot': return runVMAction(key, action, () => api.CopyVMScreenshot(actionDriverID, name), tr('toastScreenshotCopied'))
|
|
case 'stop': return runVMAction(key, action, () => api.StopVM(actionDriverID, name, false), tr('toastStopped', { name }))
|
|
case 'forceStop': return runVMAction(key, action, () => api.StopVM(actionDriverID, name, true), tr('toastStopped', { name }))
|
|
case 'restart': return runVMAction(key, action, () => api.RestartVM(actionDriverID, name))
|
|
case 'eject': return runVMAction(key, action, () => api.EjectInstaller(actionDriverID, name), tr('toastEjected'))
|
|
case 'finishInstall': return runVMAction(key, action, () => api.FinishInstall(name), tr(isRunning ? 'toastExitRecoveryNextStart' : 'toastInstallFinished'))
|
|
case 'enterRecovery': return runVMAction(key, action, () => api.EnterRecovery(name), tr(isRunning ? 'toastEnterRecoveryNextStart' : 'toastEnterRecovery'))
|
|
case 'attachInstaller': return attachInstaller(key, name, isRunning)
|
|
case 'attachGuestTools': return runVMAction(key, action, () => api.AttachGuestTools(name), tr(isRunning ? 'toastGuestToolsAttachedNextStart' : 'toastGuestToolsAttached'))
|
|
case 'detachGuestTools': return runVMAction(key, action, () => api.DetachGuestTools(name), tr(isRunning ? 'toastGuestToolsDetachedNextStart' : 'toastGuestToolsDetached'))
|
|
case 'openSharedFolder':
|
|
return api.OpenSharedFolder(name).catch((e) => fail(tr('failOpenFolder'), e))
|
|
case 'upgradeNVMe':
|
|
return runVMAction(key, action, () => api.UpgradeDiskToNVMe(name), tr(isRunning ? 'toastNVMeNextStart' : 'toastNVMeReady'))
|
|
case 'exportDiagnostics':
|
|
return runVMAction(key, action, async () => { await api.ExportDiagnostics(actionDriverID, name) }, tr('toastDiagExported'))
|
|
case 'cloneVM':
|
|
if (!features.clone) return
|
|
return setCloneSource({ name, driverID: actionDriverID })
|
|
case 'type': return typeInto(key, () => api.TypeClipboard(actionDriverID, name))
|
|
case 'sendText': return setSendTextTarget(key)
|
|
case 'openFolder':
|
|
return api.OpenVMFolder(name).catch((e) => fail(tr('failOpenFolder'), e))
|
|
case 'delete': return setDeleteTarget(key)
|
|
}
|
|
}
|
|
|
|
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
|
|
// The settings dialog edits a macOS VM's detail; other drivers' VMs have none.
|
|
if (vm && !isMacOSDriver(vm.driver_id)) 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. A running hosted VM has no window; its action is its
|
|
// best ready endpoint, and nothing when none is ready.
|
|
const primaryAction = (name: string) => {
|
|
const vm = findVM(name)
|
|
if (!vm) return
|
|
const key = vmRefKey(vm)
|
|
if (vmBusy.current(key)) return
|
|
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 = findVM(target)
|
|
const name = targetVM?.name ?? target
|
|
const driverID = targetVM?.driver_id ?? ''
|
|
const key = targetVM ? vmRefKey(targetVM) : (name ?? '')
|
|
if (name) runVMAction(key, 'delete', () => api.DeleteVM(driverID, name, keepFiles), tr('toastDeleted', { name }))
|
|
}
|
|
|
|
const confirmDiscardSuspend = () => {
|
|
const target = discardSuspendTarget
|
|
setDiscardSuspendTarget(null)
|
|
const targetVM = findVM(target)
|
|
const name = targetVM?.name ?? target
|
|
const driverID = targetVM?.driver_id ?? ''
|
|
const key = targetVM ? vmRefKey(targetVM) : (name ?? '')
|
|
if (name) runVMAction(key, 'discardSuspend', () => api.DiscardSuspend(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(vmRefKey({ name: src.name, driver_id: src.driverID }), 'cloneVM', async () => {
|
|
await api.CloneVMCoW(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
|
|
const graphics = state.host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga'
|
|
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,
|
|
gpu: state.host.recommended_gpu?.vulkan_icd ?? 'auto',
|
|
...initialWizardResolution(state.host, fixedModeSupported, graphics),
|
|
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 shows in the sidebar,
|
|
// main view, and status bar. 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'
|
|
setPendingCreates((prev) => (prev.includes(name) ? prev : [...prev, name]))
|
|
setSelected(name)
|
|
api.CreateVM(payload)
|
|
.then(() => {
|
|
toasts.push({ kind: 'ok', title: tr('toastCreated', { name }) })
|
|
setSelected(name)
|
|
return refresh()
|
|
})
|
|
.catch((e) => {
|
|
void refresh()
|
|
if (parseAppError(e).code === 'E_NETWORK_CREATE_BRIDGE_PENDING') {
|
|
setSelected(name)
|
|
toasts.push({
|
|
...errorToast(locale, tr('toastCreated', { name }), e),
|
|
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({
|
|
...errorToast(locale, tr('failCreate', { name }), e),
|
|
action: { label: tr('backToEdit'), onClick: () => { setWizardDraft(draft); setShowWizard(true) } },
|
|
})
|
|
})
|
|
.finally(() => {
|
|
setPendingCreates((prev) => prev.filter((item) => item !== name))
|
|
})
|
|
}
|
|
|
|
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 || update.confirming || closeDownloadsOpen || elevationQueue.length > 0
|
|
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() }
|
|
}, [])
|
|
|
|
// Closing the window while a download runs asks first (beforeClose in Go).
|
|
useEffect(() => events.onConfirmCloseDownloads(() => setCloseDownloadsOpen(true)), [])
|
|
// Controlled elevation request from a guest driver plugin (elevate_flow.go).
|
|
useEffect(() => {
|
|
const offRequest = events.onElevateRequest((req) => setElevationQueue((q) => [...q, req]))
|
|
const offResolved = events.onElevateResolved((id) => setElevationQueue((q) => (
|
|
q.some((item) => item.id === id) ? q.filter((item) => item.id !== id) : q
|
|
)))
|
|
return () => { offRequest(); offResolved() }
|
|
}, [])
|
|
|
|
// Files dropped on the window go to the selected VM's shared folder.
|
|
const dropping = useFileDrop(!!selectedVM && !!detail && !detail.has_installer && !detail.recovery_mode, (paths) => {
|
|
if (!selectedVM) return
|
|
api.DeliverPathsToGuest(selectedVM.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))
|
|
})
|
|
|
|
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={themeMode}
|
|
canLight={canLight}
|
|
canDark={canDark}
|
|
onThemeMode={setThemeMode}
|
|
vm={selectedVM ? {
|
|
name: selectedVM.name,
|
|
driver_id: selectedVM.driver_id,
|
|
state: effectiveState,
|
|
busy: vmRefKey(selectedVM) in vmBusy.busy,
|
|
graphics: detail?.name === selectedVM.name ? detail.graphics : undefined,
|
|
canSuspend: canSuspendVM(selectedVM),
|
|
features: selectedFeatures,
|
|
} : null}
|
|
fullscreenHotkey={fullscreenHotkey}
|
|
onNewVM={openWizard}
|
|
onVMAction={onVMAction}
|
|
onVMSettings={() => { if (detail && effectiveState !== 'suspended') setShowSettings(true) }}
|
|
onVMDelete={() => { if (selectedVM) setDeleteTarget(vmRefKey(selectedVM)) }}
|
|
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={() => setThemeMode(theme === 'light' ? 'dark' : 'light')}
|
|
>
|
|
{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={vmBusy.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={!!update.info?.has_update}
|
|
pluginViews={sidebarPluginViews}
|
|
creatingVMs={creatingItems.map((item) => ({ name: item.name, percent: item.task?.percent ?? -1 }))}
|
|
updateCard={update.shown ? (
|
|
<UpdateCapsule
|
|
locale={locale}
|
|
phase={update.installing ? 'ready' : update.phase}
|
|
latest={update.info?.latest ?? ''}
|
|
task={update.task}
|
|
onOpen={() => setSelected(ABOUT_ID)}
|
|
onDownload={update.download}
|
|
onCancel={() => { if (update.task) cancelTask(update.task.id) }}
|
|
onInstall={update.install}
|
|
onDismiss={update.dismiss}
|
|
/>
|
|
) : 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}
|
|
runtimeCommit={state.active_runtime?.commit}
|
|
onRefresh={refresh}
|
|
onError={fail}
|
|
onThemeChanged={() => setThemeRevision((r) => r + 1)}
|
|
onLocaleSwitch={(l) => void setLang(l)}
|
|
onOpenView={openView}
|
|
onNavigate={navigateHost}
|
|
/>
|
|
) : selectedCreating ? (
|
|
<CreatingVMView
|
|
locale={locale}
|
|
name={selectedCreating.name}
|
|
task={selectedCreating.task}
|
|
onCancel={cancelTask}
|
|
onViewLogs={() => openLogs('app')}
|
|
/>
|
|
) : selectedVM ? (
|
|
<>
|
|
{renderVMTabs()}
|
|
<VMPage
|
|
locale={locale}
|
|
name={selectedVM.name}
|
|
driverID={selectedVM.driver_id ?? ''}
|
|
displayName={displayNames[vmRefKey(selectedVM)] ?? ''}
|
|
onDisplayNameSaved={(n) => setDisplayNames((m) => ({ ...m, [vmRefKey(selectedVM)]: n }))}
|
|
macosMajor={macosMajors[vmRefKey(selectedVM)] ?? null}
|
|
state={effectiveState}
|
|
canSuspend={canSuspendVM(selectedVM)}
|
|
currentAgentVersion={state.current_agent_version}
|
|
guideActive={selectedIsMacOS && (state.active_guides?.includes(selectedVM.name) ?? false)}
|
|
installGuideEnabled={!!state.install_guide_enabled}
|
|
detail={detail}
|
|
vmInfo={vmInfo}
|
|
host={state.host}
|
|
pending={pending}
|
|
busyAction={vmBusy.busy[vmRefKey(selectedVM)]}
|
|
onAction={onVMAction}
|
|
onPluginCommand={(pluginID, command, title) => {
|
|
const name = selectedVM.name
|
|
const key = vmRefKey(selectedVM)
|
|
void runVMAction(key, 'pluginCommand', async () => {
|
|
await api.InvokePluginCommand(pluginID, command, { vm: name })
|
|
}, title)
|
|
}}
|
|
onSettings={() => setShowSettings(true)}
|
|
onOpenAffinity={() => setAffinityTarget({ name: selectedVM.name, driverID: selectedVM.driver_id ?? '' })}
|
|
onDelete={() => setDeleteTarget(vmRefKey(selectedVM))}
|
|
onViewLogs={() => { openLogs('serial'); loadSerial() }}
|
|
onCopy={copy}
|
|
onTypeText={(text) => typeInto(vmRefKey(selectedVM), () => api.TypeText(selectedVM.driver_id ?? '', selectedVM.name, text))}
|
|
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}
|
|
fullscreenHotkey={fullscreenHotkey}
|
|
dropping={dropping}
|
|
pluginUI={pluginUI}
|
|
/>
|
|
</>
|
|
) : selected === SETTINGS_ID ? (
|
|
<AppSettingsPage
|
|
state={state}
|
|
locale={locale}
|
|
locales={pluginUI?.locales}
|
|
tasks={Object.values(taskMap)}
|
|
themeMode={themeMode}
|
|
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={update.info}
|
|
onAppUpdate={update.setInfo}
|
|
updatePhase={update.phase}
|
|
updateTask={update.task}
|
|
installing={update.installing}
|
|
onDownloadUpdate={update.download}
|
|
onCancelUpdate={() => { if (update.task) cancelTask(update.task.id) }}
|
|
onInstallUpdate={update.install}
|
|
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)}
|
|
/>
|
|
)}
|
|
|
|
<AppDialogs
|
|
locale={locale}
|
|
state={state}
|
|
detail={detail}
|
|
selectedVM={selectedVM}
|
|
selectedIsMacOS={selectedIsMacOS}
|
|
effectiveState={effectiveState}
|
|
fixedModeSupported={fixedModeSupported}
|
|
diskCacheSupported={diskCacheSupported}
|
|
runningVMCount={runningVMCount}
|
|
tasks={Object.values(taskMap)}
|
|
displayNames={displayNames}
|
|
showWizard={showWizard}
|
|
wizardDraft={wizardDraft}
|
|
onCloseWizard={() => { setShowWizard(false); setWizardDraft(null) }}
|
|
onSubmitCreate={submitCreate}
|
|
showSettings={showSettings}
|
|
onCloseSettings={() => setShowSettings(false)}
|
|
onSavedSettings={() => {
|
|
setShowSettings(false)
|
|
toasts.push({ kind: 'ok', title: tr(effectiveState === 'running' ? 'toastSavedNextStart' : 'toastSaved') })
|
|
refresh()
|
|
}}
|
|
affinityTarget={affinityTarget}
|
|
affinityVersion={affinityVersion}
|
|
onOpenAffinity={setAffinityTarget}
|
|
onCloseAffinity={() => setAffinityTarget(null)}
|
|
onAffinityApplied={(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()
|
|
}}
|
|
updateConfirming={update.confirming}
|
|
updateLatest={update.info?.latest ?? ''}
|
|
onCancelInstallUpdate={() => update.cancelInstall()}
|
|
onConfirmInstallUpdate={update.confirmInstall}
|
|
deleteTarget={deleteTarget}
|
|
onCancelDelete={() => setDeleteTarget(null)}
|
|
onConfirmDelete={confirmDelete}
|
|
closeDownloadsOpen={closeDownloadsOpen}
|
|
onCancelCloseDownloads={() => setCloseDownloadsOpen(false)}
|
|
elevationQueue={elevationQueue}
|
|
onResolveElevation={(id, approved) => {
|
|
setElevationQueue((q) => q.filter((item) => item.id !== id))
|
|
api.ResolveElevationRequest(id, approved).catch((e) => console.warn('[app] ResolveElevationRequest failed:', e))
|
|
}}
|
|
discardSuspendTarget={discardSuspendTarget}
|
|
onCancelDiscardSuspend={() => setDiscardSuspendTarget(null)}
|
|
onConfirmDiscardSuspend={confirmDiscardSuspend}
|
|
cloneSource={cloneSource}
|
|
onCancelClone={() => setCloneSource(null)}
|
|
onConfirmClone={confirmClone}
|
|
sendTextTarget={sendTextTarget}
|
|
onCancelSendText={() => setSendTextTarget(null)}
|
|
onConfirmSendText={(key, driverID, name, text) => {
|
|
setSendTextTarget(null)
|
|
typeInto(key, () => api.TypeText(driverID, name, text))
|
|
}}
|
|
pluginDialogs={pluginViewState.dialogs}
|
|
findRouteView={findRouteView}
|
|
renderPluginView={renderPluginView}
|
|
findVM={findVM}
|
|
onCopy={copy}
|
|
onRefresh={refresh}
|
|
onToast={toasts.push}
|
|
/>
|
|
|
|
{onlineRecoveryTarget && (
|
|
<OnlineRecoveryDialog
|
|
locale={locale}
|
|
name={onlineRecoveryTarget}
|
|
onCancel={() => setOnlineRecoveryTarget(null)}
|
|
onConfirm={confirmOnlineRecovery}
|
|
/>
|
|
)}
|
|
|
|
<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>
|
|
)
|
|
}
|