From c0f08be124322a6e7eb51a4f181aa491ce2d2b0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Sun, 29 Nov 2026 04:00:48 -0700 Subject: [PATCH] feat: per-VM CPU affinity, disk snapshots, SSH helpers and VM window actions Backend - Per-VM CPU affinity (vmstart/affinity.go, affinity_flow.go): modes auto / all / P-cores / non-LP-E / custom, saved in the VM folder, applied to the QEMU process on start (GUI and CLI) and live via SetVMAffinity; copied on clone. Start summary logs the resolved mapping. Host report gains CPU topology helpers (mask <-> CPU list). - Offline qcow2 restore points via qemu-img (driver/reims/snapshot.go, snapshot_flow.go): list / create / restore / delete. - SSH helpers (ssh_flow.go): remembered user, open a terminal, write an ~/.ssh/config entry, open VS Code Remote-SSH. - FocusVMWindow brings the QEMU window forward (restoring it if minimized); CopyVMScreenshot copies a full-resolution frame to the clipboard. - DeliverPathsToGuest copies dropped host files into the shared folder; main.go enables Wails file drop on elements marked --wails-drop-target. - VM note (.reims-go-note) and a storage breakdown (extras_flow.go). Frontend - VM page: running state's "Show Window" and the screen preview use FocusVMWindow; camera button and More-menu item copy a screenshot; editable note under the name; SSH row shows the saved user with Terminal / config / VS Code actions; restore-point list; install guide steps can be ticked off; drop files onto the page to send them. - Sidebar right-click menu per VM (start, show window, screenshot, stop, restart, settings, folders, clone, delete); double-click and Ctrl+Enter still run the main action. - AffinityDialog opened from the VM menu and VM settings. Co-Authored-By: Claude Opus 5.5 --- frontend/package.json | 1 + frontend/package.json.md5 | 2 +- frontend/pnpm-lock.yaml | 29 ++ frontend/src/App.tsx | 143 +++++-- frontend/src/components/AffinityDialog.tsx | 379 +++++++++++++++++ frontend/src/components/HostView.tsx | 62 ++- frontend/src/components/LogPanel.tsx | 97 +++-- frontend/src/components/SettingsModal.tsx | 27 +- frontend/src/components/Sidebar.tsx | 98 ++++- frontend/src/components/VMPage.tsx | 450 +++++++++++++++++++-- frontend/src/i18n.ts | 172 +++++++- frontend/src/styles/app.css | 156 +++++++ frontend/src/types.ts | 13 + frontend/src/wails.ts | 18 +- frontend/wailsjs/go/app/App.d.ts | 34 ++ frontend/wailsjs/go/app/App.js | 68 ++++ frontend/wailsjs/go/models.ts | 143 +++++++ internal/app/affinity_flow.go | 160 ++++++++ internal/app/affinity_flow_test.go | 46 +++ internal/app/app.go | 17 +- internal/app/clone_flow.go | 19 +- internal/app/extras_flow.go | 122 ++++++ internal/app/extras_snapshot_test.go | 64 +++ internal/app/guesttools_flow.go | 38 ++ internal/app/snapshot_flow.go | 91 +++++ internal/app/ssh_flow.go | 203 ++++++++++ internal/app/ssh_flow_test.go | 50 +++ internal/app/thumbnail_flow.go | 59 +++ internal/app/vm_monitor.go | 29 +- internal/cli/start.go | 11 +- internal/driver/reims/snapshot.go | 118 ++++++ internal/host/foreground_other.go | 3 + internal/host/foreground_windows.go | 75 +++- internal/host/host.go | 102 ++++- internal/host/host_other.go | 15 +- internal/host/host_test.go | 13 + internal/host/host_windows.go | 101 ++++- internal/host/host_windows_test.go | 35 ++ internal/vmstart/affinity.go | 356 ++++++++++++++++ internal/vmstart/affinity_test.go | 85 ++++ main.go | 6 + 41 files changed, 3511 insertions(+), 199 deletions(-) create mode 100644 frontend/src/components/AffinityDialog.tsx create mode 100644 internal/app/affinity_flow.go create mode 100644 internal/app/affinity_flow_test.go create mode 100644 internal/app/extras_flow.go create mode 100644 internal/app/extras_snapshot_test.go create mode 100644 internal/app/snapshot_flow.go create mode 100644 internal/app/ssh_flow.go create mode 100644 internal/app/ssh_flow_test.go create mode 100644 internal/driver/reims/snapshot.go create mode 100644 internal/host/host_windows_test.go create mode 100644 internal/vmstart/affinity.go create mode 100644 internal/vmstart/affinity_test.go diff --git a/frontend/package.json b/frontend/package.json index 4b3571a..0d8a525 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -11,6 +11,7 @@ "dependencies": { "@fontsource-variable/inter": "^5.3.0", "@radix-ui/react-alert-dialog": "^1.2.1", + "@radix-ui/react-context-menu": "^2.4.1", "@radix-ui/react-dialog": "^1.3.1", "@radix-ui/react-dropdown-menu": "^2.2.1", "@radix-ui/react-toast": "^1.3.1", diff --git a/frontend/package.json.md5 b/frontend/package.json.md5 index e90a398..8fad74e 100644 --- a/frontend/package.json.md5 +++ b/frontend/package.json.md5 @@ -1 +1 @@ -64168eba4b0b33765a8a7ffa2b52319b \ No newline at end of file +7e79b2e7f508739db05e8626e40423b5 \ No newline at end of file diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml index ea36577..c810baf 100644 --- a/frontend/pnpm-lock.yaml +++ b/frontend/pnpm-lock.yaml @@ -14,6 +14,9 @@ importers: '@radix-ui/react-alert-dialog': specifier: ^1.2.1 version: 1.2.1(@types/react-dom@19.3.0(@types/react@19.3.3))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-context-menu': + specifier: ^2.4.1 + version: 2.4.1(@types/react-dom@19.3.0(@types/react@19.3.3))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) '@radix-ui/react-dialog': specifier: ^1.3.1 version: 1.3.1(@types/react-dom@19.3.0(@types/react@19.3.3))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) @@ -378,6 +381,19 @@ packages: '@types/react': optional: true + '@radix-ui/react-context-menu@2.4.1': + resolution: {integrity: sha512-Pddn3Z8lio3/ChxyXaEP3jHTTo1LTHCWwF8+mG1chQlWijP+ttVHBKwezrQTiV6Mj670ojvumqvuGh+mdv33iQ==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + '@radix-ui/react-context@1.3.0': resolution: {integrity: sha512-v5AYEocMISkbJ+1fTXzZpiFv7NRr3D2WiYbLIKf+FkmJ8VkP6d503eV2n34MFussHXY1pcoq3yfJiQH77dc4Mg==} peerDependencies: @@ -1363,6 +1379,19 @@ snapshots: optionalDependencies: '@types/react': 19.3.3 + '@radix-ui/react-context-menu@2.4.1(@types/react-dom@19.3.0(@types/react@19.3.3))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@radix-ui/primitive': 1.2.0 + '@radix-ui/react-context': 1.3.0(@types/react@19.3.3)(react@19.3.1) + '@radix-ui/react-menu': 2.2.1(@types/react-dom@19.3.0(@types/react@19.3.3))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@19.3.0(@types/react@19.3.3))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-use-controllable-state': 1.3.0(@types/react@19.3.3)(react@19.3.1) + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + optionalDependencies: + '@types/react': 19.3.3 + '@types/react-dom': 19.3.0(@types/react@19.3.3) + '@radix-ui/react-context@1.3.0(@types/react@19.3.3)(react@19.3.1)': dependencies: react: 19.3.1 diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index ffb3110..5799367 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,6 +1,7 @@ import { Minus, Moon, Square, Sun, X } from 'lucide-react' import React, { useCallback, useEffect, useRef, useState } from 'react' import { CreateWizard, WizardDraft } from './components/CreateWizard' +import { AffinityDialog } from './components/AffinityDialog' import { DeleteDialog } from './components/DeleteDialog' import { CloneDialog } from './components/CloneDialog' import { OnlineRecoveryDialog } from './components/OnlineRecoveryDialog' @@ -12,7 +13,7 @@ import { SettingsModal } from './components/SettingsModal' import { Setup } from './components/Setup' import { HOST_ID, INSTALLERS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar' import { InstallersPage } from './components/InstallersPage' -import { VMAction, VMPage, canShowVMWindow } from './components/VMPage' +import { VMAction, VMPage } from './components/VMPage' import { I18nKey, t } from './i18n' import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format' import { LogLine, appendLog } from './lib/logs' @@ -20,18 +21,18 @@ import { currentTask, upsertTask } from './lib/tasks' import { AppState, CachedInstaller, CreateOpts, Locale, RuntimeSource, Task, VMDetail, VMStats } from './types' import { Tip, TooltipProvider } from './ui/controls' import { Toaster, useToasts } from './ui/toast' -import { api, events, optionalApi } from './wails' -import { WindowMinimise, WindowToggleMaximise } from '../wailsjs/runtime/runtime' +import { api, events } from './wails' +import { OnFileDrop, OnFileDropOff, WindowMinimise, WindowToggleMaximise } from '../wailsjs/runtime/runtime' const errText = (e: unknown) => String(e).replace(/^Error:\s*/, '') const failKey: Record = { start: 'failStart', + focus: 'failFocus', + screenshot: 'failScreenshot', stop: 'failStop', forceStop: 'failStop', restart: 'failRestart', - showWindow: 'failShowWindow', - copyScreenshot: 'failScreenshot', eject: 'failEject', finishInstall: 'failFinishInstall', enterRecovery: 'failEnterRecovery', @@ -56,11 +57,14 @@ export const App: React.FC = () => { const [showWizard, setShowWizard] = useState(false) const [wizardDraft, setWizardDraft] = useState(null) const [showSettings, setShowSettings] = useState(false) + const [affinityTarget, setAffinityTarget] = useState(null) + const [affinityVersion, setAffinityVersion] = useState(0) const [deleteTarget, setDeleteTarget] = useState(null) const [cloneSource, setCloneSource] = useState(null) const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState(null) const [sendTextTarget, setSendTextTarget] = useState(null) const [busy, setBusy] = useState>({}) + const [dropping, setDropping] = useState(false) const [loadError, setLoadError] = useState('') const [themeMode, setThemeModeState] = useState(() => { try { @@ -331,32 +335,11 @@ export const App: React.FC = () => { } } - const onVMAction = (action: VMAction) => { - if (selectedVM) vmAction(selectedVM.name, action) - } - - // The state's own main action (Start, or Show Window while running), shared by - // Ctrl+Enter and a double-click in the sidebar. - const primaryAction = (name: string) => { - const vm = vms.find((v) => v.name === name) - if (!vm || busy[name]) return - const st = state?.transitions[name] ?? vm.state - if (st === 'stopped') vmAction(name, 'start') - else if (st === 'running' && canShowVMWindow()) vmAction(name, 'showWindow') - } - - const vmAction = (name: string, action: VMAction) => { - const isRunning = vms.find((v) => v.name === name)?.state === 'running' + const onVMActionFor = (name: string, action: VMAction, isRunning: boolean) => { switch (action) { - case 'showWindow': { - const focus = optionalApi('FocusVMWindow') - return focus ? runVMAction(name, action, () => focus(name)) : undefined - } - case 'copyScreenshot': { - const shot = optionalApi('CopyVMScreenshot') - return shot ? runVMAction(name, action, () => shot(name), tr('toastScreenshotCopied')) : undefined - } case 'start': return runVMAction(name, action, () => api.StartVM(name)) + case 'focus': return api.FocusVMWindow(name).catch((e) => fail(tr('failFocus'), e)) + case 'screenshot': return runVMAction(name, action, () => api.CopyVMScreenshot(name), tr('toastScreenshotCopied')) case 'stop': return runVMAction(name, action, () => api.StopVM(name, false), tr('toastStopped', { name })) case 'forceStop': return runVMAction(name, action, () => api.StopVM(name, true), tr('toastStopped', { name })) case 'restart': return runVMAction(name, action, () => api.RestartVM(name)) @@ -382,6 +365,32 @@ export const App: React.FC = () => { } } + const onVMAction = (action: VMAction) => { + if (!selectedVM) return + return onVMActionFor(selectedVM.name, action, selectedVM.state === 'running') + } + + const onSidebarContextAction = (name: string, action: VMAction | 'settings') => { + if (action === 'settings') { + setSelected(name) + api.GetVMDetail(name).then((d) => { setDetail(d); setShowSettings(true) }).catch((e) => fail(tr('failGeneric'), e)) + return + } + const vm = vms.find((v) => v.name === name) + const st = state?.transitions[name] ?? vm?.state ?? 'stopped' + onVMActionFor(name, action, st === 'running') + } + + // The state's own main action (Start, or Show Window while running), shared by + // Ctrl+Enter and a double-click in the sidebar. + const primaryAction = (name: string) => { + const vm = vms.find((v) => v.name === name) + if (!vm || busy[name]) return + const st = state?.transitions[name] ?? vm.state + if (st === 'stopped') onVMActionFor(name, 'start', false) + else if (st === 'running') onVMActionFor(name, 'focus', true) + } + const confirmDelete = (keepFiles: boolean) => { const name = deleteTarget setDeleteTarget(null) @@ -501,7 +510,7 @@ export const App: React.FC = () => { const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {}) shortcutRef.current = (e: KeyboardEvent) => { if (!e.ctrlKey || e.altKey || e.metaKey) return - if (showWizard || showSettings || deleteTarget || sendTextTarget) return + if (showWizard || showSettings || affinityTarget || deleteTarget || sendTextTarget) return const k = e.key.toLowerCase() if (k === 'n') { e.preventDefault(); openWizard() } else if (k === ',' && detail) { e.preventDefault(); setShowSettings(true) } @@ -514,6 +523,47 @@ export const App: React.FC = () => { return () => window.removeEventListener('keydown', h) }, []) + // 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 (
@@ -568,6 +618,7 @@ export const App: React.FC = () => { onSelect={setSelected} onActivate={primaryAction} onNew={openWizard} + onVMContextAction={onSidebarContextAction} downloading={Object.values(taskMap).some((x) => x.kind === 'installer-download' && x.status === 'running')} /> @@ -598,6 +649,7 @@ export const App: React.FC = () => { busyAction={busy[selectedVM.name]} onAction={onVMAction} onSettings={() => setShowSettings(true)} + onOpenAffinity={() => setAffinityTarget(selectedVM.name)} onDelete={() => setDeleteTarget(selectedVM.name)} onViewLogs={() => { openLogs('serial'); loadSerial() }} onCopy={copy} @@ -625,6 +677,9 @@ export const App: React.FC = () => { }) .catch((e) => fail(tr('failGuestTools'), e)) }} + onToast={(title) => toasts.push({ kind: 'ok', title })} + onError={fail} + dropping={dropping} /> ) : selected === SETTINGS_ID ? ( { state={state} locale={locale} onRefresh={refresh} + onNewVM={openWizard} onError={fail} runtimeTask={runtimeTask} onChannel={setChannel} @@ -674,6 +730,7 @@ export const App: React.FC = () => { onCancelTask={cancelTask} host={state?.host} runningVMs={runningVMCount} + onCopy={copy} /> )} @@ -697,6 +754,8 @@ export const App: React.FC = () => { running={effectiveState === 'running'} onCopy={copy} onDiskChanged={refresh} + onOpenAffinity={() => setAffinityTarget(detail.name)} + affinityVersion={affinityVersion} onClose={() => setShowSettings(false)} onSaved={() => { setShowSettings(false) @@ -706,6 +765,30 @@ export const App: React.FC = () => { /> )} + {affinityTarget && state && ( + 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() + }} + /> + )} + {deleteTarget && ( setDeleteTarget(null)} onConfirm={confirmDelete} /> )} diff --git a/frontend/src/components/AffinityDialog.tsx b/frontend/src/components/AffinityDialog.tsx new file mode 100644 index 0000000..1e9a08f --- /dev/null +++ b/frontend/src/components/AffinityDialog.tsx @@ -0,0 +1,379 @@ +import { AlertTriangle, Check, Cpu } from 'lucide-react' +import React, { useEffect, useMemo, useState } from 'react' +import { I18nKey, t } from '../i18n' +import { HostReport, Locale, LogicalCPUInfo, VMAffinityMode, VMAffinityStatus } from '../types' +import { Button } from '../ui/controls' +import { Modal } from '../ui/dialog' +import { Segmented, Switch } from '../ui/settings' +import { api } from '../wails' + +interface Props { + locale: Locale + vmName: string + vcpus: number + host: HostReport + globalAutoPin: boolean + onClose: () => void + onApplied: (status: VMAffinityStatus) => void +} + +function buildTopology(host: HostReport): LogicalCPUInfo[] { + if (host.cpu_topology && host.cpu_topology.length > 0) { + return host.cpu_topology + } + const n = Math.min(Math.max(host.logical_cpus || 1, 1), 64) + return Array.from({ length: n }, (_, i) => ({ + index: i, + core_index: i, + tier: 'standard', + smt: false, + })) +} + +function maskHexFromCPUs(cpus: number[]): string { + let mask = 0n + for (const idx of cpus) { + if (idx >= 0 && idx < 64) { + mask |= 1n << BigInt(idx) + } + } + return '0x' + mask.toString(16).toUpperCase() +} + +function resolveAutoPreview(topology: LogicalCPUInfo[], host: HostReport, globalAutoPin: boolean, vcpus: number): number[] { + const all = topology.map((c) => c.index) + if (!globalAutoPin || !host.has_hybrid_cores) return all + const pCPUs = topology.filter((c) => c.tier === 'p').map((c) => c.index) + if (pCPUs.length >= vcpus + 1 && pCPUs.length > 0) return pCPUs + if ((host.lpe_core_count ?? 0) > 0) { + const nonLPE = topology.filter((c) => c.tier !== 'lpe').map((c) => c.index) + if (nonLPE.length >= vcpus + 1 && nonLPE.length > 0) return nonLPE + } + return all +} + +export function formatAffinitySummary(locale: Locale, status: VMAffinityStatus | null): string { + if (!status) return '—' + const tr = (k: I18nKey, v?: Record) => t(locale, k, v) + const count = status.effective_cpus?.length ?? 0 + const mask = status.effective_mask_hex || '0x0' + switch (status.mode) { + case 'all': + return tr('affinitySummaryAll', { count }) + case 'pcores': + return tr('affinitySummaryPCores', { count, mask }) + case 'non_lpe': + return tr('affinitySummaryNonLPE', { count, mask }) + case 'custom': + return tr('affinitySummaryCustom', { count, mask }) + default: { + const effLabel = status.effective_mode === 'pcores' + ? tr('affinityModePCores') + : status.effective_mode === 'non_lpe' + ? tr('affinityModeNonLPE') + : tr('affinityModeAll') + return tr('affinitySummaryAuto', { eff: effLabel, count }) + } + } +} + +export const AffinityDialog: React.FC = ({ + locale, vmName, vcpus, host, globalAutoPin, onClose, onApplied, +}) => { + const tr = (k: I18nKey, v?: Record) => t(locale, k, v) + const topology = useMemo(() => buildTopology(host), [host]) + const allIndices = useMemo(() => topology.map((c) => c.index), [topology]) + const hasSMT = useMemo(() => topology.some((c) => c.smt), [topology]) + + const [status, setStatus] = useState(null) + const [loading, setLoading] = useState(true) + const [saving, setSaving] = useState(false) + const [err, setErr] = useState('') + + const [mode, setMode] = useState('auto') + const [selected, setSelected] = useState(allIndices) + const [disableEcoQoS, setDisableEcoQoS] = useState(true) + + useEffect(() => { + let live = true + setLoading(true) + setErr('') + api.GetVMAffinity(vmName) + .then((st) => { + if (!live) return + setStatus(st) + setMode(st.mode || 'auto') + const initial = st.mode === 'custom' && st.cpus?.length > 0 + ? st.cpus + : (st.effective_cpus?.length > 0 ? st.effective_cpus : allIndices) + setSelected([...initial].sort((a, b) => a - b)) + setDisableEcoQoS(st.disable_eco_qos) + }) + .catch((e) => { + if (live) setErr(String(e).replace(/^Error:\s*/, '')) + }) + .finally(() => { + if (live) setLoading(false) + }) + return () => { live = false } + }, [vmName, allIndices]) + + const selectedSet = useMemo(() => new Set(selected), [selected]) + const effectiveVCPUs = status?.vcpus || vcpus + const maskHex = useMemo(() => maskHexFromCPUs(selected), [selected]) + + const applyPreset = (nextMode: VMAffinityMode) => { + setMode(nextMode) + setErr('') + switch (nextMode) { + case 'all': + setSelected(allIndices) + break + case 'pcores': { + const list = topology.filter((c) => c.tier === 'p').map((c) => c.index) + setSelected(list.length > 0 ? list : allIndices) + break + } + case 'non_lpe': { + const list = topology.filter((c) => c.tier !== 'lpe').map((c) => c.index) + setSelected(list.length > 0 ? list : allIndices) + break + } + case 'auto': + setSelected(resolveAutoPreview(topology, host, globalAutoPin, effectiveVCPUs)) + break + case 'custom': + break + } + } + + const toggleCPU = (idx: number) => { + setMode('custom') + setErr('') + setSelected((prev) => { + const s = new Set(prev) + if (s.has(idx)) s.delete(idx) + else s.add(idx) + return Array.from(s).sort((a, b) => a - b) + }) + } + + const pickCustomList = (list: number[]) => { + setMode('custom') + setErr('') + setSelected([...new Set(list)].sort((a, b) => a - b)) + } + + const physicalOnlyList = useMemo(() => { + const seen = new Set() + const out: number[] = [] + for (const c of topology) { + if (!seen.has(c.core_index)) { + seen.add(c.core_index) + out.push(c.index) + } + } + return out + }, [topology]) + + const modeOptions: { value: VMAffinityMode; label: string }[] = [ + { value: 'auto', label: tr('affinityModeAuto') }, + { value: 'all', label: tr('affinityModeAll') }, + ...(host.has_hybrid_cores ? [{ value: 'pcores' as const, label: tr('affinityModePCores') }] : []), + ...((host.lpe_core_count ?? 0) > 0 ? [{ value: 'non_lpe' as const, label: tr('affinityModeNonLPE') }] : []), + { value: 'custom', label: tr('affinityModeCustom') }, + ] + + const modeHintKey: Record = { + auto: 'affinityModeAutoHint', + all: 'affinityModeAllHint', + pcores: 'affinityModePCoresHint', + non_lpe: 'affinityModeNonLPEHint', + custom: 'affinityModeCustomHint', + } + + const emptyCustom = mode === 'custom' && selected.length === 0 + const oversubscribed = effectiveVCPUs > 0 && selected.length > 0 && selected.length < effectiveVCPUs + const allSelected = selected.length === allIndices.length && allIndices.length > 0 + + const handleSave = async () => { + if (emptyCustom) { + setErr(tr('affinityNeedOne')) + return + } + setSaving(true) + setErr('') + try { + const updated = await api.SetVMAffinity(vmName, { + mode, + cpus: mode === 'custom' ? selected : [], + disable_eco_qos: disableEcoQoS, + }) + onApplied(updated) + } catch (e) { + setErr(String(e).replace(/^Error:\s*/, '')) + } finally { + setSaving(false) + } + } + + const subtitle = status?.running && status.pid + ? tr('affinitySubtitleRunning', { pid: status.pid, vcpus: effectiveVCPUs }) + : tr('affinitySubtitleStopped', { vcpus: effectiveVCPUs }) + + const tierLabel = (tier: string) => { + if (tier === 'p') return 'P' + if (tier === 'e') return 'E' + if (tier === 'lpe') return 'LP-E' + return '' + } + + return ( + +
+
+ applyPreset(m as VMAffinityMode)} + options={modeOptions} + /> +

{tr(modeHintKey[mode])}

+
+ +
+ + {hasSMT && ( + + )} + {allIndices.length > 1 && ( + + )} + {host.has_hybrid_cores && ( + + )} + {(host.lpe_core_count ?? 0) > 0 && ( + + )} +
+ +
+ {topology.map((cpu) => { + const checked = selectedSet.has(cpu.index) + const tLabel = tierLabel(cpu.tier) + return ( + + ) + })} +
+ +
+ + + {status?.running && status.live_mask_hex && ( + + {tr('affinityLiveMask', { mask: status.live_mask_hex, count: status.live_cpus?.length ?? 0 })} + + )} +
+ + {oversubscribed && ( +
+ + +
+ )} + +
+
+
{tr('affinityEcoQoS')}
+
{tr('affinityEcoQoSDesc')}
+
+ +
+ + {err &&
{err}
} +
+ +
+ + +
+
+ ) +} diff --git a/frontend/src/components/HostView.tsx b/frontend/src/components/HostView.tsx index 6d61a8f..f8ec8d6 100644 --- a/frontend/src/components/HostView.tsx +++ b/frontend/src/components/HostView.tsx @@ -1,8 +1,9 @@ -import { Cpu, HardDrive, MemoryStick, RefreshCw, ShieldCheck } from 'lucide-react' -import React, { useState } from 'react' +import { Cpu, HardDrive, MemoryStick, Plus, RefreshCw, ShieldCheck } from 'lucide-react' +import React, { useEffect, useState } from 'react' import { I18nKey, t } from '../i18n' +import { formatBytes } from '../lib/format' import { findOptimization, kernelIrqchipHint, optBadgeClass, optStatusLabel } from '../lib/optimizations' -import { AppState, Locale, RuntimeSource, Task } from '../types' +import { AppState, Locale, RuntimeSource, StorageBreakdown, Task } from '../types' import { Button, IconButton } from '../ui/controls' import { api } from '../wails' import { RuntimeOnline } from './RuntimeOnline' @@ -11,6 +12,7 @@ interface Props { state: AppState locale: Locale onRefresh: () => void + onNewVM?: () => void onError: (title: string, e: unknown) => void runtimeTask: Task | null onChannel: (alpha: boolean) => void @@ -19,12 +21,19 @@ interface Props { onCancelTask: (id: string) => void } -export const HostView: React.FC = ({ state, locale, onRefresh, onError, runtimeTask, onChannel, onSource, onInstallRuntime, onCancelTask }) => { +export const HostView: React.FC = ({ state, locale, onRefresh, onNewVM, onError, runtimeTask, onChannel, onSource, onInstallRuntime, onCancelTask }) => { const [importing, setImporting] = useState(false) const [enabling, setEnabling] = useState(false) const [openingSched, setOpeningSched] = useState(false) + const [storage, setStorage] = useState(null) const { host, config, runtimes, optimizations } = state const tr = (k: I18nKey, v?: Record) => t(locale, k, v) + + useEffect(() => { + let live = true + api.GetStorageBreakdown().then((s) => { if (live) setStorage(s) }).catch(() => {}) + return () => { live = false } + }, [state.config.data_root, state.vms?.length, state.runtimes?.length]) const irqOpt = findOptimization(optimizations, 'kernel_irqchip') const rebootOpt = findOptimization(optimizations, 'cold_reboot') const gpuOpt = findOptimization(optimizations, 'discrete_gpu') @@ -82,6 +91,16 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onError, r
+ {(state.vms?.length ?? 0) === 0 && host.whpx === 'ready' && !!state.active_runtime && onNewVM && ( +
+

{tr('welcomeTitle')}

+

{tr('welcomeSub')}

+ +
+ )} +
@@ -122,6 +141,41 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onError, r
+ {storage && storage.total_bytes > 0 && (() => { + const tot = Math.max(storage.total_bytes, 1) + const vmsPct = (storage.vms_bytes / tot) * 100 + const instPct = (storage.installers_bytes / tot) * 100 + const rtPct = (storage.runtimes_bytes / tot) * 100 + return ( +
+
+ {tr('storageBreakdownTitle')} + + {formatBytes(storage.total_bytes)} +
+
+ ) + })()} +
{tr('hostRuntime')} diff --git a/frontend/src/components/LogPanel.tsx b/frontend/src/components/LogPanel.tsx index 9d63e1f..f9d2f64 100644 --- a/frontend/src/components/LogPanel.tsx +++ b/frontend/src/components/LogPanel.tsx @@ -1,5 +1,5 @@ -import { ArrowDown, ChevronDown, ChevronUp, Eraser, HardDrive, LoaderCircle, MemoryStick, Pause, RefreshCw } from 'lucide-react' -import React, { useLayoutEffect, useRef, useState } from 'react' +import { ArrowDown, ChevronDown, ChevronUp, Copy, Eraser, HardDrive, LoaderCircle, MemoryStick, Pause, RefreshCw } from 'lucide-react' +import React, { useLayoutEffect, useMemo, useRef, useState } from 'react' import { t } from '../i18n' import { LogLine } from '../lib/logs' import { taskDetail, taskTitle } from '../lib/tasks' @@ -27,6 +27,7 @@ interface Props { onCancelTask: (id: string) => void host?: HostReport runningVMs?: number + onCopy?: (text: string) => void } /** Sticks to the bottom until the user scrolls up; offers "jump to latest" then. */ @@ -59,10 +60,38 @@ const MAX_LOG_HEIGHT = 520 export const LogPanel: React.FC = ({ locale, open, onToggle, tab, onTab, lines, unseenErrors, onClear, serialText, qemuText, showSerial, onRefreshSerial, onRefreshQemu, - task, runningTasks, onCancelTask, host, runningVMs = 0, + task, runningTasks, onCancelTask, host, runningVMs = 0, onCopy, }) => { const tr = (k: Parameters[1], v?: Record) => t(locale, k, v) - const content = tab === 'app' ? lines : tab === 'serial' ? serialText : qemuText + const [query, setQuery] = useState('') + const [errorsOnly, setErrorsOnly] = useState(false) + + const q = query.trim().toLowerCase() + const filteredLines = useMemo(() => { + return lines.filter((l) => { + if (errorsOnly && l.level !== 'error' && l.level !== 'warn') return false + if (q && !l.line.toLowerCase().includes(q) && !l.source.toLowerCase().includes(q)) return false + return true + }) + }, [lines, errorsOnly, q]) + + const filteredText = useMemo(() => { + const raw = tab === 'serial' ? serialText : qemuText + if (!q || !raw) return raw + return raw.split('\n').filter((line) => line.toLowerCase().includes(q)).join('\n') + }, [tab, serialText, qemuText, q]) + + const copyVisible = () => { + if (!onCopy) return + if (tab === 'app') { + const txt = filteredLines.map((l) => `${l.ts} [${l.source}] ${l.line}`).join('\n') + if (txt) onCopy(txt) + } else if (filteredText) { + onCopy(filteredText) + } + } + + const content = tab === 'app' ? filteredLines : filteredText const { ref, stuck, onScroll, jump } = useStickToBottom(content, open) const memPct = host @@ -191,21 +220,45 @@ export const LogPanel: React.FC = ({ ) : null} {open && ( -
- - {showSerial && ( - <> - - - + <> + setQuery(e.target.value)} + /> + {tab === 'app' && ( + )} -
+
+ + {showSerial && ( + <> + + + + )} +
+ + )} + {open && onCopy && ( + } onClick={copyVisible} /> )} {open && tab === 'app' && lines.length > 0 && ( } onClick={onClear} /> @@ -235,18 +288,16 @@ export const LogPanel: React.FC = ({
{tab === 'app' - ? (lines.length === 0 + ? (filteredLines.length === 0 ? {tr('logsEmpty')} - : lines.map((l) => ( + : filteredLines.map((l) => (
{l.ts} {l.source} {l.line}
))) - : tab === 'serial' - ? (serialText || {tr('logsEmpty')}) - : (qemuText || {tr('logsEmpty')})} + : (filteredText || {tr('logsEmpty')})}
{!stuck && ( + } + /> + )} void onNew: () => void + onVMContextAction?: (name: string, action: VMAction | 'settings') => void /** An installer download is running (busy dot on the Installers entry). */ downloading?: boolean } @@ -43,7 +46,10 @@ function useVMIcons(vms: VMListItem[], transitions: Record) { return icons } -export const Sidebar: React.FC = ({ locale, vms, transitions, selected, hostReady, onSelect, onActivate, onNew, downloading }) => { +export const Sidebar: React.FC = ({ + locale, vms, transitions, selected, hostReady, onSelect, onActivate, onNew, onVMContextAction, downloading, +}) => { + const tr = (k: I18nKey) => t(locale, k) const listRef = useRef(null) const ids = [...vms.map((v) => v.name), INSTALLERS_ID, HOST_ID, SETTINGS_ID] const icons = useVMIcons(vms, transitions) @@ -62,7 +68,7 @@ export const Sidebar: React.FC = ({ locale, vms, transitions, selected, h listRef.current?.querySelector(`[data-id="${CSS.escape(ids[next])}"]`)?.focus() } - const item = ( + const navBtn = ( id: string, label: string, icon: React.ReactNode, @@ -97,15 +103,18 @@ export const Sidebar: React.FC = ({ locale, vms, transitions, selected, h