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 <noreply@anthropic.com>
This commit is contained in:
1 parent
dac10a52bc
commit
c0f08be124
41 files changed
+3511
-199
No files matched your search
@@ -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",
|
||||
|
||||
@@ -1 +1 @@
|
||||
64168eba4b0b33765a8a7ffa2b52319b
|
||||
7e79b2e7f508739db05e8626e40423b5
|
||||
Generated
+29
@@ -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
|
||||
|
||||
+113
-30
@@ -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<VMAction, I18nKey> = {
|
||||
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<WizardDraft | null>(null)
|
||||
const [showSettings, setShowSettings] = useState(false)
|
||||
const [affinityTarget, setAffinityTarget] = useState<string | null>(null)
|
||||
const [affinityVersion, setAffinityVersion] = useState(0)
|
||||
const [deleteTarget, setDeleteTarget] = useState<string | null>(null)
|
||||
const [cloneSource, setCloneSource] = useState<string | null>(null)
|
||||
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
|
||||
const [sendTextTarget, setSendTextTarget] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState<Record<string, VMAction>>({})
|
||||
const [dropping, setDropping] = useState(false)
|
||||
const [loadError, setLoadError] = useState('')
|
||||
const [themeMode, setThemeModeState] = useState<ThemeMode>(() => {
|
||||
try {
|
||||
@@ -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 (
|
||||
<TooltipProvider>
|
||||
<div className="app-shell">
|
||||
@@ -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 ? (
|
||||
<AppSettingsPage
|
||||
@@ -641,6 +696,7 @@ export const App: React.FC = () => {
|
||||
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 && (
|
||||
<AffinityDialog
|
||||
locale={locale}
|
||||
vmName={affinityTarget}
|
||||
vcpus={detail?.name === affinityTarget ? detail.cpus : 4}
|
||||
host={state.host}
|
||||
globalAutoPin={state.config.auto_pin_pcores}
|
||||
onClose={() => setAffinityTarget(null)}
|
||||
onApplied={(st) => {
|
||||
setAffinityTarget(null)
|
||||
setAffinityVersion((v) => v + 1)
|
||||
const count = st.effective_cpus?.length ?? 0
|
||||
const mask = st.live_mask_hex || st.effective_mask_hex || '0x0'
|
||||
toasts.push({
|
||||
kind: 'ok',
|
||||
title: st.running
|
||||
? tr('toastAffinityApplied', { count, mask })
|
||||
: tr('toastAffinitySaved'),
|
||||
})
|
||||
refresh()
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{deleteTarget && (
|
||||
<DeleteDialog locale={locale} name={deleteTarget} onCancel={() => setDeleteTarget(null)} onConfirm={confirmDelete} />
|
||||
)}
|
||||
|
||||
@@ -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<string, string | number>) => 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<Props> = ({
|
||||
locale, vmName, vcpus, host, globalAutoPin, onClose, onApplied,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => 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<VMAffinityStatus | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [err, setErr] = useState('')
|
||||
|
||||
const [mode, setMode] = useState<VMAffinityMode>('auto')
|
||||
const [selected, setSelected] = useState<number[]>(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<number>()
|
||||
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<VMAffinityMode, I18nKey> = {
|
||||
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 (
|
||||
<Modal
|
||||
title={`${tr('affinityTitle')} — ${vmName}`}
|
||||
subtitle={subtitle}
|
||||
closeLabel={tr('close')}
|
||||
dismissable={!saving}
|
||||
onClose={onClose}
|
||||
className="affinity-dialog"
|
||||
>
|
||||
<div className="dialog-body affinity-body">
|
||||
<div className="affinity-mode-bar">
|
||||
<Segmented
|
||||
label={tr('affinityTitle')}
|
||||
value={mode}
|
||||
onChange={(m) => applyPreset(m as VMAffinityMode)}
|
||||
options={modeOptions}
|
||||
/>
|
||||
<p className="affinity-hint">{tr(modeHintKey[mode])}</p>
|
||||
</div>
|
||||
|
||||
<div className="affinity-quick-bar">
|
||||
<button
|
||||
type="button"
|
||||
className={`affinity-chip${allSelected ? ' is-active' : ''}`}
|
||||
disabled={loading || saving}
|
||||
onClick={() => pickCustomList(allSelected ? [allIndices[0]] : allIndices)}
|
||||
>
|
||||
{tr('affinitySelectAll')}
|
||||
</button>
|
||||
{hasSMT && (
|
||||
<button
|
||||
type="button"
|
||||
className="affinity-chip"
|
||||
disabled={loading || saving}
|
||||
onClick={() => pickCustomList(physicalOnlyList)}
|
||||
>
|
||||
{tr('affinityPhysicalOnly')}
|
||||
</button>
|
||||
)}
|
||||
{allIndices.length > 1 && (
|
||||
<button
|
||||
type="button"
|
||||
className="affinity-chip"
|
||||
disabled={loading || saving}
|
||||
onClick={() => pickCustomList(allIndices.filter((i) => i !== 0))}
|
||||
>
|
||||
{tr('affinityExcludeCPU0')}
|
||||
</button>
|
||||
)}
|
||||
{host.has_hybrid_cores && (
|
||||
<button
|
||||
type="button"
|
||||
className="affinity-chip"
|
||||
disabled={loading || saving}
|
||||
onClick={() => pickCustomList(topology.filter((c) => c.tier === 'p').map((c) => c.index))}
|
||||
>
|
||||
{tr('affinityOnlyPCores')}
|
||||
</button>
|
||||
)}
|
||||
{(host.lpe_core_count ?? 0) > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
className="affinity-chip"
|
||||
disabled={loading || saving}
|
||||
onClick={() => pickCustomList(topology.filter((c) => c.tier !== 'lpe').map((c) => c.index))}
|
||||
>
|
||||
{tr('affinityAvoidLPE')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="affinity-grid" role="group" aria-label={tr('affinityTitle')}>
|
||||
{topology.map((cpu) => {
|
||||
const checked = selectedSet.has(cpu.index)
|
||||
const tLabel = tierLabel(cpu.tier)
|
||||
return (
|
||||
<button
|
||||
key={cpu.index}
|
||||
type="button"
|
||||
role="checkbox"
|
||||
aria-checked={checked}
|
||||
disabled={loading || saving}
|
||||
className={`affinity-cpu${checked ? ' is-checked' : ''}${cpu.tier === 'lpe' ? ' is-lpe' : ''}`}
|
||||
onClick={() => toggleCPU(cpu.index)}
|
||||
>
|
||||
<span className="affinity-check" aria-hidden="true">
|
||||
{checked && <Check size={12} strokeWidth={3} />}
|
||||
</span>
|
||||
<span className="affinity-cpu-name tnum">CPU {cpu.index}</span>
|
||||
<span className="affinity-cpu-meta">
|
||||
{cpu.smt && <span className="affinity-core-tag tnum">C{cpu.core_index}</span>}
|
||||
{tLabel && <span className={`affinity-tier tier-${cpu.tier}`}>{tLabel}</span>}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="affinity-summary">
|
||||
<span className="mono tnum">
|
||||
<Cpu size={13} aria-hidden="true" />{' '}
|
||||
{tr('affinitySelectedSummary', { selected: selected.length, total: topology.length, mask: maskHex })}
|
||||
</span>
|
||||
{status?.running && status.live_mask_hex && (
|
||||
<span className="affinity-live mono tnum">
|
||||
{tr('affinityLiveMask', { mask: status.live_mask_hex, count: status.live_cpus?.length ?? 0 })}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{oversubscribed && (
|
||||
<div className="notice" role="status">
|
||||
<span className="notice-main">
|
||||
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{tr('affinityOversubWarn', { selected: selected.length, vcpus: effectiveVCPUs })}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="affinity-eco-row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('affinityEcoQoS')}</div>
|
||||
<div className="row-sub">{tr('affinityEcoQoSDesc')}</div>
|
||||
</div>
|
||||
<Switch
|
||||
label={tr('affinityEcoQoS')}
|
||||
checked={disableEcoQoS}
|
||||
disabled={loading || saving}
|
||||
onChange={setDisableEcoQoS}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{err && <div className="notice notice-error" role="alert">{err}</div>}
|
||||
</div>
|
||||
|
||||
<div className="dialog-foot">
|
||||
<Button onClick={onClose} disabled={saving}>{tr('cancel')}</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
busy={saving}
|
||||
disabled={loading || emptyCustom}
|
||||
onClick={() => void handleSave()}
|
||||
>
|
||||
{status?.running ? tr('affinityApplyNow') : tr('affinitySave')}
|
||||
</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -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<Props> = ({ state, locale, onRefresh, onError, runtimeTask, onChannel, onSource, onInstallRuntime, onCancelTask }) => {
|
||||
export const HostView: React.FC<Props> = ({ 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<StorageBreakdown | null>(null)
|
||||
const { host, config, runtimes, optimizations } = state
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => 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<Props> = ({ state, locale, onRefresh, onError, r
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{(state.vms?.length ?? 0) === 0 && host.whpx === 'ready' && !!state.active_runtime && onNewVM && (
|
||||
<section className="welcome-card">
|
||||
<h1>{tr('welcomeTitle')}</h1>
|
||||
<p>{tr('welcomeSub')}</p>
|
||||
<Button variant="primary" icon={<Plus size={14} aria-hidden="true" />} onClick={onNewVM}>
|
||||
{tr('newVM')}
|
||||
</Button>
|
||||
</section>
|
||||
)}
|
||||
|
||||
<div className="tiles">
|
||||
<div className="tile">
|
||||
<div className="tile-head">
|
||||
@@ -122,6 +141,41 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, r
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{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 (
|
||||
<section className="card">
|
||||
<div className="card-title">
|
||||
<span>{tr('storageBreakdownTitle')}</span>
|
||||
<span className="spacer" />
|
||||
<span className="muted tnum" style={{ fontSize: 12, fontWeight: 500 }}>{formatBytes(storage.total_bytes)}</span>
|
||||
</div>
|
||||
<div className="storage-bar" aria-hidden="true">
|
||||
{vmsPct > 0 && <div className="storage-seg-vms" style={{ width: `${vmsPct}%` }} />}
|
||||
{instPct > 0 && <div className="storage-seg-inst" style={{ width: `${instPct}%` }} />}
|
||||
{rtPct > 0 && <div className="storage-seg-rt" style={{ width: `${rtPct}%` }} />}
|
||||
</div>
|
||||
<div className="storage-legend">
|
||||
<span className="storage-legend-item">
|
||||
<span className="storage-dot storage-seg-vms" aria-hidden="true" />
|
||||
{tr('storageVMs')} · {formatBytes(storage.vms_bytes)}
|
||||
</span>
|
||||
<span className="storage-legend-item">
|
||||
<span className="storage-dot storage-seg-inst" aria-hidden="true" />
|
||||
{tr('storageInstallers')} · {formatBytes(storage.installers_bytes)}
|
||||
</span>
|
||||
<span className="storage-legend-item">
|
||||
<span className="storage-dot storage-seg-rt" aria-hidden="true" />
|
||||
{tr('storageRuntimes')} · {formatBytes(storage.runtimes_bytes)}
|
||||
</span>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
})()}
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">
|
||||
{tr('hostRuntime')}
|
||||
|
||||
@@ -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<Props> = ({
|
||||
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<typeof t>[1], v?: Record<string, string | number>) => 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<Props> = ({
|
||||
) : null}
|
||||
<span className="spacer" />
|
||||
{open && (
|
||||
<div className="tabs" role="tablist">
|
||||
<button type="button" role="tab" className="tab" aria-selected={tab === 'app'} onClick={() => onTab('app')}>
|
||||
{tr('logActivity')}
|
||||
</button>
|
||||
{showSerial && (
|
||||
<>
|
||||
<button type="button" role="tab" className="tab" aria-selected={tab === 'serial'} onClick={() => onTab('serial')}>
|
||||
{tr('logSerial')}
|
||||
</button>
|
||||
<button type="button" role="tab" className="tab" aria-selected={tab === 'qemu'} onClick={() => onTab('qemu')}>
|
||||
{tr('logQemu')}
|
||||
</button>
|
||||
</>
|
||||
<>
|
||||
<input
|
||||
type="search"
|
||||
className="log-filter-input"
|
||||
value={query}
|
||||
placeholder={tr('logSearchPlaceholder')}
|
||||
aria-label={tr('logSearchPlaceholder')}
|
||||
spellCheck={false}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
{tab === 'app' && (
|
||||
<button
|
||||
type="button"
|
||||
className="log-filter-pill"
|
||||
aria-pressed={errorsOnly}
|
||||
onClick={() => setErrorsOnly((v) => !v)}
|
||||
>
|
||||
{tr('logErrorsOnly')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="tabs" role="tablist">
|
||||
<button type="button" role="tab" className="tab" aria-selected={tab === 'app'} onClick={() => onTab('app')}>
|
||||
{tr('logActivity')}
|
||||
</button>
|
||||
{showSerial && (
|
||||
<>
|
||||
<button type="button" role="tab" className="tab" aria-selected={tab === 'serial'} onClick={() => onTab('serial')}>
|
||||
{tr('logSerial')}
|
||||
</button>
|
||||
<button type="button" role="tab" className="tab" aria-selected={tab === 'qemu'} onClick={() => onTab('qemu')}>
|
||||
{tr('logQemu')}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{open && onCopy && (
|
||||
<IconButton small tipSide="top" label={tr('logCopy')} icon={<Copy size={14} />} onClick={copyVisible} />
|
||||
)}
|
||||
{open && tab === 'app' && lines.length > 0 && (
|
||||
<IconButton small tipSide="top" label={tr('clear')} icon={<Eraser size={14} />} onClick={onClear} />
|
||||
@@ -235,18 +288,16 @@ export const LogPanel: React.FC<Props> = ({
|
||||
<div className="logs-body-wrap">
|
||||
<div className="logs-body" style={{ height }} ref={ref} onScroll={onScroll} role="log" aria-live="off">
|
||||
{tab === 'app'
|
||||
? (lines.length === 0
|
||||
? (filteredLines.length === 0
|
||||
? <span className="muted">{tr('logsEmpty')}</span>
|
||||
: lines.map((l) => (
|
||||
: filteredLines.map((l) => (
|
||||
<div key={l.id} className={`log-line ${l.level}`}>
|
||||
<span className="log-ts">{l.ts}</span>
|
||||
<span className="log-src">{l.source}</span>
|
||||
<span className="log-msg">{l.line}</span>
|
||||
</div>
|
||||
)))
|
||||
: tab === 'serial'
|
||||
? (serialText || <span className="muted">{tr('logsEmpty')}</span>)
|
||||
: (qemuText || <span className="muted">{tr('logsEmpty')}</span>)}
|
||||
: (filteredText || <span className="muted">{tr('logsEmpty')}</span>)}
|
||||
</div>
|
||||
{!stuck && (
|
||||
<Button className="jump-latest" icon={<ArrowDown size={14} />} onClick={jump}>
|
||||
|
||||
@@ -25,11 +25,12 @@ import {
|
||||
optStatusLabel,
|
||||
parseKernelIrqchip,
|
||||
} from '../lib/optimizations'
|
||||
import { DiskCompactResult, DiskResizeResult, DriveShareSettings, HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMDetail, VMStats } from '../types'
|
||||
import { DiskCompactResult, DiskResizeResult, DriveShareSettings, HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMAffinityStatus, VMDetail, VMStats } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, SetValue, Switch } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
import { formatAffinitySummary } from './AffinityDialog'
|
||||
|
||||
// VM settings (docs/shell-design.md §4): edits are staged here and written in
|
||||
// one `reims-ctl set` on Save, because upstream applies every change on the
|
||||
@@ -128,11 +129,13 @@ interface Props {
|
||||
running: boolean
|
||||
onCopy?: (text: string) => void
|
||||
onDiskChanged?: () => void
|
||||
onOpenAffinity?: () => void
|
||||
affinityVersion?: number
|
||||
onClose: () => void
|
||||
onSaved: () => void
|
||||
}
|
||||
|
||||
export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, optimizations, running, onCopy, onDiskChanged, onClose, onSaved }) => {
|
||||
export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onClose, onSaved }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const irqOpt = findOptimization(optimizations, 'kernel_irqchip')
|
||||
const base = useMemo(() => baseline(detail, host), [detail, host])
|
||||
@@ -152,6 +155,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
const activeVMNameRef = useRef(detail.name)
|
||||
activeVMNameRef.current = detail.name
|
||||
const [driveErr, setDriveErr] = useState('')
|
||||
const [affinityStatus, setAffinityStatus] = useState<VMAffinityStatus | null>(null)
|
||||
const pane = useRef<HTMLDivElement>(null)
|
||||
|
||||
const presets = recommendedDisplayPresets(host)
|
||||
@@ -218,6 +222,14 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
return () => { active = false }
|
||||
}, [detail.name])
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
api.GetVMAffinity(detail.name)
|
||||
.then((st) => { if (active) setAffinityStatus(st) })
|
||||
.catch(() => {})
|
||||
return () => { active = false }
|
||||
}, [detail.name, running, affinityVersion])
|
||||
|
||||
const updateDriveShares = async (enabled: boolean, selected: string[]) => {
|
||||
if (driveBusyRef.current || !driveSettings) return
|
||||
driveBusyRef.current = true
|
||||
@@ -341,6 +353,17 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{onOpenAffinity && (
|
||||
<SetRow
|
||||
title={tr('affinityTitle')}
|
||||
desc={affinityStatus ? `${formatAffinitySummary(locale, affinityStatus)} · ${tr('affinityRowDesc')}` : tr('affinityRowDesc')}
|
||||
control={
|
||||
<Button variant="secondary" icon={<Cpu size={13} aria-hidden="true" />} onClick={onOpenAffinity}>
|
||||
{tr('affinityConfigure')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</SetGroup>
|
||||
<SetGroup title={tr('factMemory')}>
|
||||
<SetRow
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { Cpu, Download, Monitor, Plus, Settings } from 'lucide-react'
|
||||
import * as Ctx from '@radix-ui/react-context-menu'
|
||||
import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Monitor, Play, Plus, Power, RotateCw, Settings, Square, Trash } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { Locale, VMListItem } from '../types'
|
||||
import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
|
||||
import { api } from '../wails'
|
||||
import { VMAction } from './VMPage'
|
||||
|
||||
export const HOST_ID = '__host__'
|
||||
export const INSTALLERS_ID = '__installers__'
|
||||
@@ -19,6 +21,7 @@ interface Props {
|
||||
/** Double-click on a VM: its main action (start, or show its window). */
|
||||
onActivate?: (name: string) => 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<string, string>) {
|
||||
return icons
|
||||
}
|
||||
|
||||
export const Sidebar: React.FC<Props> = ({ locale, vms, transitions, selected, hostReady, onSelect, onActivate, onNew, downloading }) => {
|
||||
export const Sidebar: React.FC<Props> = ({
|
||||
locale, vms, transitions, selected, hostReady, onSelect, onActivate, onNew, onVMContextAction, downloading,
|
||||
}) => {
|
||||
const tr = (k: I18nKey) => t(locale, k)
|
||||
const listRef = useRef<HTMLDivElement>(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<Props> = ({ locale, vms, transitions, selected, h
|
||||
listRef.current?.querySelector<HTMLElement>(`[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<Props> = ({ locale, vms, transitions, selected, h
|
||||
<div className="sidebar-wrap">
|
||||
<aside className="sidebar">
|
||||
<div className="sidebar-head">
|
||||
<span>{t(locale, 'sidebarVMs')}</span>
|
||||
<IconButton small label={t(locale, 'newVM')} shortcut="Ctrl+N" icon={<Plus size={15} />} onClick={onNew} tipSide="right" />
|
||||
<span>{tr('sidebarVMs')}</span>
|
||||
<IconButton small label={tr('newVM')} shortcut="Ctrl+N" icon={<Plus size={15} />} onClick={onNew} tipSide="right" />
|
||||
</div>
|
||||
<div className="nav" role="listbox" aria-label={t(locale, 'sidebarVMs')} ref={listRef} onKeyDown={onKeyDown}>
|
||||
{vms.length === 0 && <div className="nav-empty">{t(locale, 'emptyVMs')}</div>}
|
||||
<div className="nav" role="listbox" aria-label={tr('sidebarVMs')} ref={listRef} onKeyDown={onKeyDown}>
|
||||
{vms.length === 0 && <div className="nav-empty">{tr('emptyVMs')}</div>}
|
||||
{vms.map((vm) => {
|
||||
const st = transitions[vm.name] ?? vm.state
|
||||
const running = st === 'running'
|
||||
const stopped = st === 'stopped'
|
||||
const transitioning = st === 'starting' || st === 'stopping'
|
||||
const src = icons[vm.name]
|
||||
return item(
|
||||
const trigger = navBtn(
|
||||
vm.name,
|
||||
vm.name,
|
||||
src ? <img src={src} alt="" draggable={false} /> : <Monitor size={13} />,
|
||||
@@ -114,28 +123,83 @@ export const Sidebar: React.FC<Props> = ({ locale, vms, transitions, selected, h
|
||||
statusKind(st),
|
||||
onActivate ? () => onActivate(vm.name) : undefined,
|
||||
)
|
||||
if (!onVMContextAction) return trigger
|
||||
return (
|
||||
<Ctx.Root key={vm.name}>
|
||||
<Ctx.Trigger asChild>{trigger}</Ctx.Trigger>
|
||||
<Ctx.Portal>
|
||||
<Ctx.Content className="menu">
|
||||
{stopped && (
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'start')}>
|
||||
<Play size={14} /> {tr('start')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
{running && (
|
||||
<>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'focus')}>
|
||||
<AppWindow size={14} /> {tr('showWindow')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'screenshot')}>
|
||||
<Camera size={14} /> {tr('copyScreenshot')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'stop')}>
|
||||
<Square size={14} /> {tr('stop')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'restart')}>
|
||||
<RotateCw size={14} /> {tr('restart')}
|
||||
</Ctx.Item>
|
||||
</>
|
||||
)}
|
||||
{(running || transitioning) && (
|
||||
<Ctx.Item className="menu-item danger" onSelect={() => onVMContextAction(vm.name, 'forceStop')}>
|
||||
<Power size={14} /> {tr('forceStop')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
<Ctx.Separator className="menu-sep" />
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'settings')}>
|
||||
<Settings size={14} /> {tr('settingsEllipsis')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'openSharedFolder')}>
|
||||
<FolderOpen size={14} /> {tr('openSharedFolder')}
|
||||
</Ctx.Item>
|
||||
{stopped && (
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'cloneVM')}>
|
||||
<CopyPlus size={14} /> {tr('cloneVM')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'openFolder')}>
|
||||
<FolderOpen size={14} /> {tr('openFolder')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Separator className="menu-sep" />
|
||||
<Ctx.Item className="menu-item danger" disabled={running || transitioning} onSelect={() => onVMContextAction(vm.name, 'delete')}>
|
||||
<Trash size={14} /> {tr('delete')}
|
||||
</Ctx.Item>
|
||||
</Ctx.Content>
|
||||
</Ctx.Portal>
|
||||
</Ctx.Root>
|
||||
)
|
||||
})}
|
||||
<div className="sidebar-sep" role="presentation" />
|
||||
<div className="sidebar-section-label" aria-hidden="true">{t(locale, 'sidebarSystem')}</div>
|
||||
{item(
|
||||
<div className="sidebar-section-label" aria-hidden="true">{tr('sidebarSystem')}</div>
|
||||
{navBtn(
|
||||
INSTALLERS_ID,
|
||||
t(locale, 'sidebarInstallers'),
|
||||
tr('sidebarInstallers'),
|
||||
<Download size={13} />,
|
||||
'nav-icon-installers',
|
||||
downloading ? t(locale, 'state_starting') : '',
|
||||
downloading ? tr('state_starting') : '',
|
||||
downloading ? 'busy' : null,
|
||||
)}
|
||||
{item(
|
||||
{navBtn(
|
||||
HOST_ID,
|
||||
t(locale, 'sidebarHost'),
|
||||
tr('sidebarHost'),
|
||||
<Cpu size={13} />,
|
||||
'nav-icon-host',
|
||||
t(locale, hostReady ? 'hostReady' : 'hostNeedsAction'),
|
||||
tr(hostReady ? 'hostReady' : 'hostNeedsAction'),
|
||||
hostReady ? 'running' : 'warn',
|
||||
)}
|
||||
{item(
|
||||
{navBtn(
|
||||
SETTINGS_ID,
|
||||
t(locale, 'sidebarSettings'),
|
||||
tr('sidebarSettings'),
|
||||
<Settings size={13} />,
|
||||
'nav-icon-settings',
|
||||
'',
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as Alert from '@radix-ui/react-alert-dialog'
|
||||
import * as Menu from '@radix-ui/react-dropdown-menu'
|
||||
import {
|
||||
Activity,
|
||||
@@ -5,29 +6,37 @@ import {
|
||||
AppWindow,
|
||||
Archive,
|
||||
Camera,
|
||||
Check,
|
||||
ChevronRight,
|
||||
Code2,
|
||||
Copy,
|
||||
CopyPlus,
|
||||
Cpu,
|
||||
Disc,
|
||||
Ellipsis,
|
||||
FileCode2,
|
||||
FolderOpen,
|
||||
Globe,
|
||||
HardDrive,
|
||||
History,
|
||||
Info,
|
||||
Keyboard,
|
||||
LifeBuoy,
|
||||
MemoryStick,
|
||||
Monitor,
|
||||
Network,
|
||||
Pencil,
|
||||
Play,
|
||||
Plus,
|
||||
Power,
|
||||
RotateCcw,
|
||||
RotateCw,
|
||||
Settings,
|
||||
Square,
|
||||
Terminal,
|
||||
Trash,
|
||||
Upload,
|
||||
UserRound,
|
||||
} from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
@@ -35,8 +44,8 @@ import {
|
||||
controllerLabel, formatBytes, formatDiskUsage, formatMemory, formatUptime, graphicsLabel, guestLangLabel,
|
||||
parseMemoryGB, pendingChangeText, splitLangLabel, sshCommand,
|
||||
} from '../lib/format'
|
||||
import { HostReport, Locale, PendingChange, VMDetail, VMStats, VMThumbnail } from '../types'
|
||||
import { api, optionalApi } from '../wails'
|
||||
import { DiskSnapshot, HostReport, Locale, PendingChange, VMDetail, VMStats, VMThumbnail } from '../types'
|
||||
import { api } from '../wails'
|
||||
import { Button, IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
|
||||
import { Switch } from '../ui/settings'
|
||||
|
||||
@@ -45,8 +54,8 @@ export type VMAction =
|
||||
| 'stop'
|
||||
| 'forceStop'
|
||||
| 'restart'
|
||||
| 'showWindow'
|
||||
| 'copyScreenshot'
|
||||
| 'focus'
|
||||
| 'screenshot'
|
||||
| 'eject'
|
||||
| 'finishInstall'
|
||||
| 'enterRecovery'
|
||||
@@ -68,9 +77,6 @@ const OFFLINE_INSTALL_CMD = 'sh /Volumes/REIMSHELP/install.sh'
|
||||
const GUEST_TOOLS_INSTALL_CMD = 'sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command'
|
||||
export const PRIMARY_SHORTCUT = 'Ctrl+Enter'
|
||||
|
||||
/** Whether the running backend can bring a VM's window to the front. */
|
||||
export const canShowVMWindow = () => !!optionalApi('FocusVMWindow')
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
name: string
|
||||
@@ -82,6 +88,7 @@ interface Props {
|
||||
busyAction?: VMAction
|
||||
onAction: (action: VMAction) => void
|
||||
onSettings: () => void
|
||||
onOpenAffinity: () => void
|
||||
onDelete: () => void
|
||||
onViewLogs: () => void
|
||||
onCopy: (text: string) => void
|
||||
@@ -89,6 +96,9 @@ interface Props {
|
||||
onToggleBorderless: (enabled: boolean) => void
|
||||
onTogglePreventSleep: (enabled: boolean) => void
|
||||
onDeliverFile: () => void
|
||||
onToast: (title: string) => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
dropping?: boolean
|
||||
}
|
||||
|
||||
type Tone = '' | ' warn' | ' high'
|
||||
@@ -105,14 +115,12 @@ interface Spec {
|
||||
}
|
||||
|
||||
export const VMPage: React.FC<Props> = ({
|
||||
locale, name, state, detail, stats, host, pending, busyAction, onAction, onSettings, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile,
|
||||
locale, name, state, detail, stats, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const busy = busyAction !== undefined
|
||||
const running = state === 'running'
|
||||
const transitioning = state === 'starting' || state === 'stopping'
|
||||
const canShow = canShowVMWindow()
|
||||
const canScreenshot = !!optionalApi('CopyVMScreenshot')
|
||||
|
||||
// Screen thumbnail (thumbnail_flow.go): a fresh frame every 15 s while the VM
|
||||
// runs, otherwise the last frame saved. Skipped while this window is hidden;
|
||||
@@ -130,6 +138,151 @@ export const VMPage: React.FC<Props> = ({
|
||||
return () => { live = false; if (timer) window.clearInterval(timer) }
|
||||
}, [name, running])
|
||||
|
||||
// Optional single-line VM note (.reims-go-note)
|
||||
const [note, setNote] = useState('')
|
||||
const [editingNote, setEditingNote] = useState(false)
|
||||
const [noteDraft, setNoteDraft] = useState('')
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
setEditingNote(false)
|
||||
api.GetVMNote(name).then((n) => { if (live) setNote(n ?? '') }).catch(() => { if (live) setNote('') })
|
||||
return () => { live = false }
|
||||
}, [name])
|
||||
const saveNote = async () => {
|
||||
const cleaned = noteDraft.trim()
|
||||
setEditingNote(false)
|
||||
if (cleaned === note) return
|
||||
try {
|
||||
await api.SetVMNote(name, cleaned)
|
||||
setNote(cleaned)
|
||||
} catch (e) {
|
||||
onError(tr('failGeneric'), e)
|
||||
}
|
||||
}
|
||||
|
||||
// Remembered SSH username (.reims-go-ssh-user)
|
||||
const [sshUser, setSshUser] = useState('')
|
||||
const [sshUserDialog, setSshUserDialog] = useState(false)
|
||||
const [sshUserDraft, setSshUserDraft] = useState('')
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
api.GetVMSSHUser(name).then((u) => { if (live) setSshUser(u ?? '') }).catch(() => { if (live) setSshUser('') })
|
||||
return () => { live = false }
|
||||
}, [name])
|
||||
|
||||
const openSSHTerminal = () => {
|
||||
api.OpenSSHTerminal(name, sshUser).catch((e) => onError(tr('failSSH'), e))
|
||||
}
|
||||
const writeSSHConfig = () => {
|
||||
api.WriteSSHConfig(name, sshUser)
|
||||
.then((alias) => onToast(tr('toastSSHConfigWritten', { alias })))
|
||||
.catch((e) => onError(tr('failSSH'), e))
|
||||
}
|
||||
const openVSCodeSSH = () => {
|
||||
api.OpenVSCodeSSH(name, sshUser).catch((e) => onError(tr('failSSH'), e))
|
||||
}
|
||||
const saveSSHUser = async () => {
|
||||
const next = sshUserDraft.trim()
|
||||
setSshUserDialog(false)
|
||||
try {
|
||||
await api.SetVMSSHUser(name, next)
|
||||
setSshUser(next)
|
||||
onToast(tr('toastSSHUserSaved'))
|
||||
} catch (e) {
|
||||
onError(tr('failSSH'), e)
|
||||
}
|
||||
}
|
||||
|
||||
// Interactive install guide step checkboxes (persisted per VM in localStorage)
|
||||
const guideKey = `reims-go-guide:${name}`
|
||||
const [doneSteps, setDoneSteps] = useState<number[]>([])
|
||||
useEffect(() => {
|
||||
try {
|
||||
const raw = localStorage.getItem(guideKey)
|
||||
setDoneSteps(raw ? JSON.parse(raw) : [])
|
||||
} catch {
|
||||
setDoneSteps([])
|
||||
}
|
||||
}, [guideKey])
|
||||
const toggleGuideStep = (step: number) => {
|
||||
setDoneSteps((prev) => {
|
||||
const next = prev.includes(step) ? prev.filter((x) => x !== step) : [...prev, step]
|
||||
try { localStorage.setItem(guideKey, JSON.stringify(next)) } catch {}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
// Offline qcow2 restore points (snapshot_flow.go)
|
||||
const isQcow2 = !!detail && /\.qcow2$/i.test(detail.disk ?? '')
|
||||
const showSnapshots = !!detail && !detail.has_installer && !detail.recovery_mode && isQcow2
|
||||
const [snapshots, setSnapshots] = useState<DiskSnapshot[]>([])
|
||||
const [creatingSnap, setCreatingSnap] = useState(false)
|
||||
const [snapDraft, setSnapDraft] = useState('')
|
||||
const [snapBusy, setSnapBusy] = useState('')
|
||||
const [restoreTarget, setRestoreTarget] = useState<string | null>(null)
|
||||
|
||||
const loadSnapshots = () => {
|
||||
if (!showSnapshots) { setSnapshots([]); return }
|
||||
api.ListSnapshots(name).then((list) => setSnapshots(list ?? [])).catch(() => setSnapshots([]))
|
||||
}
|
||||
useEffect(() => {
|
||||
setCreatingSnap(false)
|
||||
setSnapDraft('')
|
||||
setRestoreTarget(null)
|
||||
loadSnapshots()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [name, showSnapshots, state])
|
||||
|
||||
const handleCreateSnapshot = async () => {
|
||||
const label = snapDraft.trim()
|
||||
if (!label) return
|
||||
setSnapBusy('create')
|
||||
try {
|
||||
await api.CreateSnapshot(name, label)
|
||||
setSnapDraft('')
|
||||
setCreatingSnap(false)
|
||||
onToast(tr('toastSnapshotCreated', { name: label }))
|
||||
loadSnapshots()
|
||||
} catch (e) {
|
||||
onError(tr('failSnapshot'), e)
|
||||
} finally {
|
||||
setSnapBusy('')
|
||||
}
|
||||
}
|
||||
const handleRestoreSnapshot = async (snapName: string) => {
|
||||
setRestoreTarget(null)
|
||||
setSnapBusy(`restore:${snapName}`)
|
||||
try {
|
||||
await api.RestoreSnapshot(name, snapName)
|
||||
onToast(tr('toastSnapshotRestored', { name: snapName }))
|
||||
loadSnapshots()
|
||||
} catch (e) {
|
||||
onError(tr('failSnapshot'), e)
|
||||
} finally {
|
||||
setSnapBusy('')
|
||||
}
|
||||
}
|
||||
const handleDeleteSnapshot = async (snapName: string) => {
|
||||
setSnapBusy(`delete:${snapName}`)
|
||||
try {
|
||||
await api.DeleteSnapshot(name, snapName)
|
||||
onToast(tr('toastSnapshotDeleted', { name: snapName }))
|
||||
loadSnapshots()
|
||||
} catch (e) {
|
||||
onError(tr('failSnapshot'), e)
|
||||
} finally {
|
||||
setSnapBusy('')
|
||||
}
|
||||
}
|
||||
const formatSnapTime = (sec: number) => {
|
||||
if (!sec) return ''
|
||||
try {
|
||||
return new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }).format(new Date(sec * 1000))
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
// One primary action per state (docs/ui-redesign.md §3.2): Start while
|
||||
// stopped, Show Window while running. Ctrl+Enter triggers it (App.tsx).
|
||||
let primary: React.ReactNode = null
|
||||
@@ -147,15 +300,13 @@ export const VMPage: React.FC<Props> = ({
|
||||
} else if (state === 'stopping') {
|
||||
primary = <Button busy>{tr('state_stopping')}</Button>
|
||||
} else if (running) {
|
||||
if (canShow) {
|
||||
primary = (
|
||||
<Tip label={tr('showWindow')} shortcut={PRIMARY_SHORTCUT}>
|
||||
<Button variant="primary" icon={<AppWindow size={14} aria-hidden="true" />} busy={busyAction === 'showWindow'} disabled={busy} onClick={() => onAction('showWindow')}>
|
||||
{tr('showWindow')}
|
||||
</Button>
|
||||
</Tip>
|
||||
)
|
||||
}
|
||||
primary = (
|
||||
<Tip label={tr('showWindow')} shortcut={PRIMARY_SHORTCUT}>
|
||||
<Button variant="primary" icon={<AppWindow size={14} aria-hidden="true" />} busy={busyAction === 'focus'} disabled={busy} onClick={() => onAction('focus')}>
|
||||
{tr('showWindow')}
|
||||
</Button>
|
||||
</Tip>
|
||||
)
|
||||
secondary = (
|
||||
<Button icon={<Square size={12} aria-hidden="true" />} busy={busyAction === 'stop'} disabled={busy} onClick={() => onAction('stop')}>{tr('stop')}</Button>
|
||||
)
|
||||
@@ -187,11 +338,9 @@ export const VMPage: React.FC<Props> = ({
|
||||
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('type')}>
|
||||
<Keyboard size={14} /> {tr('typeClipboard')}
|
||||
</Menu.Item>
|
||||
{canScreenshot && (
|
||||
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('copyScreenshot')}>
|
||||
<Camera size={14} /> {tr('copyScreenshot')}
|
||||
</Menu.Item>
|
||||
)}
|
||||
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('screenshot')}>
|
||||
<Camera size={14} /> {tr('copyScreenshot')}
|
||||
</Menu.Item>
|
||||
<Menu.Separator className="menu-sep" />
|
||||
</>
|
||||
)}
|
||||
@@ -211,6 +360,9 @@ export const VMPage: React.FC<Props> = ({
|
||||
</Menu.Item>
|
||||
</>
|
||||
)}
|
||||
<Menu.Item className="menu-item" onSelect={onOpenAffinity}>
|
||||
<Cpu size={14} /> {tr('affinityMenu')}
|
||||
</Menu.Item>
|
||||
<Menu.Separator className="menu-sep" />
|
||||
</>
|
||||
)}
|
||||
@@ -308,19 +460,57 @@ export const VMPage: React.FC<Props> = ({
|
||||
}
|
||||
|
||||
const pillClass = running ? ' is-running' : state === 'broken' ? ' is-broken' : transitioning ? ' is-busy' : ''
|
||||
const dropStyle = detail && !installing
|
||||
? ({ '--wails-drop-target': 'drop' } as React.CSSProperties)
|
||||
: undefined
|
||||
|
||||
return (
|
||||
<div className="page vm-page">
|
||||
<div className="page vm-page vm-page-drop" style={dropStyle}>
|
||||
{dropping && (
|
||||
<div className="drop-banner" role="status" aria-live="polite">
|
||||
<Upload size={16} aria-hidden="true" />
|
||||
<span>{tr('dropFilesHint')}</span>
|
||||
</div>
|
||||
)}
|
||||
<section className="vm-hero" aria-labelledby="vm-name">
|
||||
<VMScreen
|
||||
thumb={thumb}
|
||||
running={running}
|
||||
startLabel={tr('start')}
|
||||
showLabel={tr('showWindow')}
|
||||
shotLabel={tr('copyScreenshot')}
|
||||
onStart={state === 'stopped' && !busy ? () => onAction('start') : undefined}
|
||||
onShow={running && canShow && !busy ? () => onAction('showWindow') : undefined}
|
||||
onShow={running && !busy ? () => onAction('focus') : undefined}
|
||||
onScreenshot={running && !busy ? () => onAction('screenshot') : undefined}
|
||||
/>
|
||||
<h1 className="vm-hero-name" id="vm-name">{name}</h1>
|
||||
<div className="vm-note-row">
|
||||
{editingNote ? (
|
||||
<input
|
||||
className="vm-note-input"
|
||||
value={noteDraft}
|
||||
maxLength={120}
|
||||
placeholder={tr('vmNotePlaceholder')}
|
||||
aria-label={tr('vmNoteEdit')}
|
||||
autoFocus
|
||||
onChange={(e) => setNoteDraft(e.target.value)}
|
||||
onBlur={() => void saveNote()}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') { e.preventDefault(); void saveNote() }
|
||||
if (e.key === 'Escape') { e.preventDefault(); setEditingNote(false) }
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="vm-note-btn"
|
||||
onClick={() => { setNoteDraft(note); setEditingNote(true) }}
|
||||
>
|
||||
<Pencil size={11} aria-hidden="true" />
|
||||
<span>{note || tr('vmNotePlaceholder')}</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className={`vm-hero-pill${pillClass}`} role="status">
|
||||
<StatusShape kind={statusKind(state)} />
|
||||
<span>{tr(`state_${state}` as I18nKey)}</span>
|
||||
@@ -428,9 +618,23 @@ export const VMPage: React.FC<Props> = ({
|
||||
{tr('finishInstall')}
|
||||
</Button>
|
||||
)
|
||||
const step = (n: number, body: React.ReactNode) => (
|
||||
<li className="guide-step"><span className="guide-step-num">{n}</span><span className="guide-step-body">{body}</span></li>
|
||||
)
|
||||
// Each step's number is a checkbox the user ticks off (kept per VM).
|
||||
const step = (n: number, body: React.ReactNode) => {
|
||||
const done = doneSteps.includes(n)
|
||||
return (
|
||||
<li className={`guide-step${done ? ' is-done' : ''}`}>
|
||||
<button
|
||||
type="button"
|
||||
className={`guide-step-btn${done ? ' done' : ''}`}
|
||||
aria-pressed={done}
|
||||
onClick={() => toggleGuideStep(n)}
|
||||
>
|
||||
{done ? <Check size={12} aria-hidden="true" /> : n}
|
||||
</button>
|
||||
<span className="guide-step-body">{body}</span>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<section className="card" aria-labelledby="guide-title">
|
||||
<h2 className="card-title" id="guide-title">
|
||||
@@ -514,6 +718,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
gtStatus = tr('gtStatusNone'); gtTip = tr('gtNotInstalledDesc')
|
||||
}
|
||||
const showInstallCmd = detail.guest_tools_attached && (!gtConnected || needsUpgrade)
|
||||
const sshText = sshUser ? `ssh -p ${detail.ssh_port} ${sshUser}@127.0.0.1` : sshCommand(detail.ssh_port)
|
||||
|
||||
return (
|
||||
<section className="section" aria-labelledby="conn-title">
|
||||
@@ -526,9 +731,35 @@ export const VMPage: React.FC<Props> = ({
|
||||
</div>
|
||||
<div className="conn-ctrl">
|
||||
<div className="ssh-pill">
|
||||
<code>{sshCommand(detail.ssh_port)}</code>
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={13} />} onClick={() => onCopy(sshCommand(detail.ssh_port))} />
|
||||
<code>{sshText}</code>
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={13} />} onClick={() => onCopy(sshText)} />
|
||||
</div>
|
||||
<Button icon={<Terminal size={13} aria-hidden="true" />} onClick={openSSHTerminal}>
|
||||
{tr('sshOpenTerminal')}
|
||||
</Button>
|
||||
<Menu.Root>
|
||||
<Tip label={tr('sshMore')}>
|
||||
<Menu.Trigger asChild>
|
||||
<button type="button" className="icon-btn sm" aria-label={tr('sshMore')}>
|
||||
<Ellipsis size={14} />
|
||||
</button>
|
||||
</Menu.Trigger>
|
||||
</Tip>
|
||||
<Menu.Portal>
|
||||
<Menu.Content className="menu" align="end" sideOffset={4} collisionPadding={8}>
|
||||
<Menu.Item className="menu-item" onSelect={writeSSHConfig}>
|
||||
<FileCode2 size={14} /> {tr('sshWriteConfig')}
|
||||
</Menu.Item>
|
||||
<Menu.Item className="menu-item" onSelect={openVSCodeSSH}>
|
||||
<Code2 size={14} /> {tr('sshOpenVSCode')}
|
||||
</Menu.Item>
|
||||
<Menu.Separator className="menu-sep" />
|
||||
<Menu.Item className="menu-item" onSelect={() => { setSshUserDraft(sshUser); setSshUserDialog(true) }}>
|
||||
<UserRound size={14} /> {tr('sshSetUser')}
|
||||
</Menu.Item>
|
||||
</Menu.Content>
|
||||
</Menu.Portal>
|
||||
</Menu.Root>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -608,6 +839,86 @@ export const VMPage: React.FC<Props> = ({
|
||||
)
|
||||
})()}
|
||||
|
||||
{showSnapshots && (
|
||||
<section className="section">
|
||||
<div className="section-title">
|
||||
<span className="hstack">
|
||||
<History size={14} aria-hidden="true" />
|
||||
<span>{tr('snapshotsTitle')}</span>
|
||||
<span className="snap-meta-hint">· {tr('snapshotHint')}</span>
|
||||
</span>
|
||||
<Tip label={running || transitioning ? tr('snapshotStopFirst') : tr('snapshotCreate')}>
|
||||
<span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
icon={<Plus size={13} aria-hidden="true" />}
|
||||
disabled={running || transitioning || !!snapBusy}
|
||||
onClick={() => setCreatingSnap((v) => !v)}
|
||||
>
|
||||
{tr('snapshotCreate')}
|
||||
</Button>
|
||||
</span>
|
||||
</Tip>
|
||||
</div>
|
||||
<div className="conn-list">
|
||||
{creatingSnap && (
|
||||
<div className="snap-create-bar">
|
||||
<input
|
||||
className="input"
|
||||
value={snapDraft}
|
||||
maxLength={64}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder={tr('snapshotNamePlaceholder')}
|
||||
autoFocus
|
||||
onChange={(e) => setSnapDraft(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && snapDraft.trim()) { e.preventDefault(); void handleCreateSnapshot() }
|
||||
if (e.key === 'Escape') { e.preventDefault(); setCreatingSnap(false) }
|
||||
}}
|
||||
/>
|
||||
<Button variant="primary" busy={snapBusy === 'create'} disabled={!snapDraft.trim() || !!snapBusy} onClick={() => void handleCreateSnapshot()}>
|
||||
{tr('save')}
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={() => setCreatingSnap(false)}>{tr('cancel')}</Button>
|
||||
</div>
|
||||
)}
|
||||
{snapshots.length === 0 ? (
|
||||
<div className="conn-row">
|
||||
<span className="conn-meta">{tr('snapshotEmpty')}</span>
|
||||
</div>
|
||||
) : (
|
||||
snapshots.map((s) => (
|
||||
<div className="conn-row" key={s.id || s.name}>
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">{s.name}</span>
|
||||
{s.created_at > 0 && <span className="conn-meta tnum">{formatSnapTime(s.created_at)}</span>}
|
||||
</div>
|
||||
<div className="conn-ctrl">
|
||||
<Button
|
||||
icon={<RotateCcw size={13} aria-hidden="true" />}
|
||||
busy={snapBusy === `restore:${s.name}`}
|
||||
disabled={running || transitioning || !!snapBusy}
|
||||
onClick={() => setRestoreTarget(s.name)}
|
||||
>
|
||||
{tr('snapshotRestore')}
|
||||
</Button>
|
||||
<IconButton
|
||||
small
|
||||
label={tr('snapshotDelete')}
|
||||
icon={<Trash size={14} />}
|
||||
busy={snapBusy === `delete:${s.name}`}
|
||||
disabled={running || transitioning || !!snapBusy}
|
||||
onClick={() => void handleDeleteSnapshot(s.name)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{detail && (
|
||||
<details className="tech">
|
||||
<summary><ChevronRight size={14} aria-hidden="true" /> {tr('techInfo')}</summary>
|
||||
@@ -642,24 +953,81 @@ export const VMPage: React.FC<Props> = ({
|
||||
<kbd>Ctrl+Alt+Win</kbd> {tr('shortcutBarRelease')}
|
||||
</p>
|
||||
) : null)}
|
||||
|
||||
{sshUserDialog && (
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) setSshUserDialog(false) }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog sm">
|
||||
<div className="dialog-body">
|
||||
<Alert.Title className="dialog-title">{tr('sshUserTitle')}</Alert.Title>
|
||||
<Alert.Description className="dialog-desc">{tr('sshUserDesc')}</Alert.Description>
|
||||
<div className="field field-spaced">
|
||||
<input
|
||||
className="input mono"
|
||||
value={sshUserDraft}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder={tr('sshUserPlaceholder')}
|
||||
autoFocus
|
||||
onChange={(e) => setSshUserDraft(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); void saveSSHUser() } }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild><button type="button" className="btn">{tr('cancel')}</button></Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button type="button" className="btn btn-primary" onClick={() => void saveSSHUser()}>{tr('save')}</button>
|
||||
</Alert.Action>
|
||||
</div>
|
||||
</Alert.Content>
|
||||
</Alert.Portal>
|
||||
</Alert.Root>
|
||||
)}
|
||||
|
||||
{restoreTarget && (
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) setRestoreTarget(null) }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog sm">
|
||||
<div className="dialog-body">
|
||||
<Alert.Title className="dialog-title">{tr('snapshotRestoreTitle', { name: restoreTarget })}</Alert.Title>
|
||||
<Alert.Description className="dialog-desc">{tr('snapshotRestoreDesc')}</Alert.Description>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild><button type="button" className="btn">{tr('cancel')}</button></Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button type="button" className="btn btn-danger" onClick={() => void handleRestoreSnapshot(restoreTarget)}>
|
||||
{tr('snapshotRestore')}
|
||||
</button>
|
||||
</Alert.Action>
|
||||
</div>
|
||||
</Alert.Content>
|
||||
</Alert.Portal>
|
||||
</Alert.Root>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The VM's own screen as its picture (as UTM and Parallels do): live while it
|
||||
* runs (click to bring its window forward), the last frame dimmed while it is
|
||||
* stopped (hover shows a start button), and the iMac drawing until a frame
|
||||
* exists. Each new frame fades in over the previous one.
|
||||
* runs (click to bring its window forward; a camera button copies a
|
||||
* screenshot), the last frame dimmed while it is stopped (hover shows a start
|
||||
* button), and the iMac drawing until a frame exists. Each new frame fades in
|
||||
* over the previous one.
|
||||
*/
|
||||
const VMScreen: React.FC<{
|
||||
thumb: VMThumbnail | null
|
||||
running: boolean
|
||||
startLabel: string
|
||||
showLabel: string
|
||||
shotLabel: string
|
||||
onStart?: () => void
|
||||
onShow?: () => void
|
||||
}> = ({ thumb, running, startLabel, showLabel, onStart, onShow }) => {
|
||||
onScreenshot?: () => void
|
||||
}> = ({ thumb, running, startLabel, showLabel, shotLabel, onStart, onShow, onScreenshot }) => {
|
||||
const prev = useRef<string>('')
|
||||
const shown = thumb?.data_url ?? ''
|
||||
const under = prev.current !== shown ? prev.current : ''
|
||||
@@ -684,6 +1052,18 @@ const VMScreen: React.FC<{
|
||||
<div className={`vm-screen${running ? ' is-live' : ' is-idle'}`} style={under ? { backgroundImage: `url(${under})` } : undefined}>
|
||||
<img key={thumb?.captured_at} className="vm-screen-img" src={shown} alt="" draggable={false} />
|
||||
{running && <span className="vm-screen-live" aria-hidden="true" />}
|
||||
{running && onScreenshot && (
|
||||
<Tip label={shotLabel} side="left">
|
||||
<button
|
||||
type="button"
|
||||
className="vm-screen-shot"
|
||||
aria-label={shotLabel}
|
||||
onClick={(e) => { e.stopPropagation(); onScreenshot() }}
|
||||
>
|
||||
<Camera size={14} aria-hidden="true" />
|
||||
</button>
|
||||
</Tip>
|
||||
)}
|
||||
{overlay}
|
||||
</div>
|
||||
<div className="vm-display-stand" aria-hidden="true" />
|
||||
|
||||
+162
-10
@@ -47,6 +47,50 @@ const dict = {
|
||||
themeLight: '浅色',
|
||||
themeDark: '深色',
|
||||
themeSystem: '跟随系统',
|
||||
showWindow: '显示窗口',
|
||||
copyScreenshot: '截屏并复制',
|
||||
toastScreenshotCopied: '已复制虚拟机画面',
|
||||
failFocus: '无法定位虚拟机窗口',
|
||||
failScreenshot: '截屏失败',
|
||||
dropFilesHint: '松开以投递到 macOS 共享目录',
|
||||
toastFilesDelivered: '已投递 {n} 个文件到共享目录',
|
||||
sshOpenTerminal: '终端',
|
||||
sshMore: 'SSH 工具',
|
||||
sshWriteConfig: '写入 ~/.ssh/config',
|
||||
sshOpenVSCode: '用 VS Code 打开',
|
||||
sshSetUser: '设置 SSH 用户名…',
|
||||
sshUserTitle: 'SSH 登录用户名',
|
||||
sshUserDesc: '用于打开终端、写入 ~/.ssh/config 和 VS Code 直连(留空则连接时不带用户名)',
|
||||
sshUserPlaceholder: '例如 admin',
|
||||
toastSSHConfigWritten: '已写入 Host {alias}',
|
||||
toastSSHUserSaved: '已保存 SSH 用户名',
|
||||
failSSH: 'SSH 操作失败',
|
||||
snapshotsTitle: '恢复点',
|
||||
snapshotCreate: '创建恢复点',
|
||||
snapshotEmpty: '尚未创建恢复点,升级系统或大改环境前可先留档',
|
||||
snapshotHint: '停机快照 · 非异地备份',
|
||||
snapshotNamePlaceholder: '例如:升级 macOS 前',
|
||||
snapshotRestore: '回滚',
|
||||
snapshotRestoreTitle: '回滚到「{name}」?',
|
||||
snapshotRestoreDesc: '当前磁盘在此恢复点之后的改动将被覆盖,且无法撤销。',
|
||||
snapshotDelete: '删除恢复点',
|
||||
snapshotStopFirst: '停止虚拟机后才可管理恢复点',
|
||||
toastSnapshotCreated: '已创建恢复点 {name}',
|
||||
toastSnapshotRestored: '已回滚到 {name}',
|
||||
toastSnapshotDeleted: '已删除恢复点 {name}',
|
||||
failSnapshot: '恢复点操作失败',
|
||||
vmNotePlaceholder: '添加备注…',
|
||||
vmNoteEdit: '编辑备注',
|
||||
logSearchPlaceholder: '筛选日志…',
|
||||
logErrorsOnly: '仅错误/警告',
|
||||
logCopy: '复制日志',
|
||||
storageBreakdownTitle: '空间分布',
|
||||
storageVMs: '虚拟机磁盘',
|
||||
storageInstallers: '安装包',
|
||||
storageRuntimes: '运行时',
|
||||
welcomeTitle: '创建第一台 macOS 虚拟机',
|
||||
welcomeSub: '选择系统来源、分配核数与显卡,几步完成配置',
|
||||
welcomeCheckHost: '先完成内核环境配置 →',
|
||||
|
||||
// Actions
|
||||
newVM: '新建虚拟机',
|
||||
@@ -428,6 +472,43 @@ const dict = {
|
||||
driveShareNeedsTools: '需要 Guest Tools {version} 或更新版本。运行中的 VM 要先重启以更新 REIMSTOOLS,然后在 macOS 中重新运行安装命令',
|
||||
driveShareMasterOff: '先开启 Windows 盘符共享',
|
||||
driveShareNoDrives: '没有可共享的内部固定磁盘',
|
||||
affinityTitle: '处理器相关性',
|
||||
affinityMenu: '处理器相关性…',
|
||||
affinityConfigure: '配置…',
|
||||
affinityRowDesc: '控制 QEMU 进程在哪些宿主机逻辑处理器上运行(实时生效,无需重启)',
|
||||
affinitySubtitleRunning: '运行中(PID {pid})· {vcpus} vCPU · 修改后立即生效',
|
||||
affinitySubtitleStopped: '已停止 · {vcpus} vCPU · 下次启动时自动生效',
|
||||
affinityModeAuto: '自动',
|
||||
affinityModeAll: '所有处理器',
|
||||
affinityModePCores: '仅 P 核',
|
||||
affinityModeNonLPE: 'P + E 核',
|
||||
affinityModeCustom: '自定义',
|
||||
affinityModeAutoHint: '跟随全局策略,在混合大小核处理器上自动避开超售与低功耗核。',
|
||||
affinityModeAllHint: '允许 Windows 将 QEMU 调度到全部宿主机逻辑处理器。',
|
||||
affinityModePCoresHint: '仅在性能核(P-Core)上运行,减少大小核混调引起的抖动。',
|
||||
affinityModeNonLPEHint: '在性能核与能效核(P + E)上运行,仅排除慢速低功耗核(LP-E)。',
|
||||
affinityModeCustomHint: '勾选允许运行 QEMU 的逻辑处理器,等价于 Windows 任务管理器的处理器相关性。',
|
||||
affinitySelectAll: '所有处理器',
|
||||
affinityPhysicalOnly: '仅物理核',
|
||||
affinityExcludeCPU0: '排除 CPU 0',
|
||||
affinityOnlyPCores: '仅 P 核',
|
||||
affinityAvoidLPE: '避开 LP-E',
|
||||
affinitySelectedSummary: '已选 {selected} / {total} 个逻辑处理器 · 掩码 {mask}',
|
||||
affinityLiveMask: 'Windows 当前生效:{mask}({count} 线程)',
|
||||
affinityOversubWarn: '当前只勾选了 {selected} 个逻辑处理器,少于虚拟机分配的 {vcpus} 个 vCPU,可能导致明显卡顿。',
|
||||
affinityNeedOne: '请至少勾选 1 个逻辑处理器',
|
||||
affinityEcoQoS: '禁用 Windows 效率模式节流 (EcoQoS)',
|
||||
affinityEcoQoSDesc: '防止 Windows 11 在窗口失焦或后台运行时把 QEMU 线程压缩到 2 个低功耗核心',
|
||||
affinityApplyNow: '立即应用',
|
||||
affinitySave: '保存',
|
||||
affinitySummaryAuto: '自动({eff} · {count} 线程)',
|
||||
affinitySummaryAll: '所有处理器({count} 线程)',
|
||||
affinitySummaryPCores: '仅 P 核({count} 线程 · {mask})',
|
||||
affinitySummaryNonLPE: 'P + E 核({count} 线程 · {mask})',
|
||||
affinitySummaryCustom: '自定义({count} 线程 · {mask})',
|
||||
toastAffinityApplied: '处理器相关性已应用({count} 个逻辑处理器 · {mask})',
|
||||
toastAffinitySaved: '处理器相关性已保存,下次启动时生效',
|
||||
failAffinity: '设置处理器相关性失败',
|
||||
networkDesc: '通过 NAT 共享宿主的网络连接',
|
||||
sshForward: 'SSH 端口转发',
|
||||
sshOffDesc: '把宿主的一个端口转发到 macOS 的 22 端口',
|
||||
@@ -550,11 +631,6 @@ const dict = {
|
||||
statsUptime: '运行时长',
|
||||
statsDiskSub: '实际 {actual} / 上限 {virtual}',
|
||||
// VM page (2026-11-29 redesign)
|
||||
showWindow: '显示窗口',
|
||||
copyScreenshot: '复制屏幕截图',
|
||||
toastScreenshotCopied: '屏幕截图已复制',
|
||||
failShowWindow: '没有找到虚拟机窗口',
|
||||
failScreenshot: '截图失败',
|
||||
on: '开启',
|
||||
netShared: '共享网络',
|
||||
netOff: '无网络',
|
||||
@@ -619,6 +695,50 @@ const dict = {
|
||||
themeLight: 'Light',
|
||||
themeDark: 'Dark',
|
||||
themeSystem: 'System',
|
||||
showWindow: 'Show window',
|
||||
copyScreenshot: 'Copy screenshot',
|
||||
toastScreenshotCopied: 'VM screenshot copied',
|
||||
failFocus: 'Could not focus VM window',
|
||||
failScreenshot: 'Screenshot failed',
|
||||
dropFilesHint: 'Drop files to send to macOS shared folder',
|
||||
toastFilesDelivered: 'Sent {n} files to shared folder',
|
||||
sshOpenTerminal: 'Terminal',
|
||||
sshMore: 'SSH tools',
|
||||
sshWriteConfig: 'Write ~/.ssh/config',
|
||||
sshOpenVSCode: 'Open in VS Code',
|
||||
sshSetUser: 'Set SSH username…',
|
||||
sshUserTitle: 'SSH login username',
|
||||
sshUserDesc: 'Used for Terminal, ~/.ssh/config, and VS Code Remote-SSH (leave empty to omit user)',
|
||||
sshUserPlaceholder: 'e.g. admin',
|
||||
toastSSHConfigWritten: 'Wrote Host {alias}',
|
||||
toastSSHUserSaved: 'Saved SSH username',
|
||||
failSSH: 'SSH action failed',
|
||||
snapshotsTitle: 'Restore points',
|
||||
snapshotCreate: 'New restore point',
|
||||
snapshotEmpty: 'No restore points yet — save one before OS updates or major changes',
|
||||
snapshotHint: 'Offline snapshots · Not a backup',
|
||||
snapshotNamePlaceholder: 'e.g. before-macos-update',
|
||||
snapshotRestore: 'Restore',
|
||||
snapshotRestoreTitle: 'Restore "{name}"?',
|
||||
snapshotRestoreDesc: 'Disk changes made after this restore point will be overwritten and cannot be undone.',
|
||||
snapshotDelete: 'Delete restore point',
|
||||
snapshotStopFirst: 'Stop the VM before managing restore points',
|
||||
toastSnapshotCreated: 'Created restore point {name}',
|
||||
toastSnapshotRestored: 'Restored to {name}',
|
||||
toastSnapshotDeleted: 'Deleted restore point {name}',
|
||||
failSnapshot: 'Restore point failed',
|
||||
vmNotePlaceholder: 'Add a note…',
|
||||
vmNoteEdit: 'Edit note',
|
||||
logSearchPlaceholder: 'Filter logs…',
|
||||
logErrorsOnly: 'Errors & warnings',
|
||||
logCopy: 'Copy logs',
|
||||
storageBreakdownTitle: 'Storage breakdown',
|
||||
storageVMs: 'VM disks',
|
||||
storageInstallers: 'Installers',
|
||||
storageRuntimes: 'Runtimes',
|
||||
welcomeTitle: 'Create your first macOS VM',
|
||||
welcomeSub: 'Pick an installer, assign cores and GPU, and launch in minutes',
|
||||
welcomeCheckHost: 'Set up Engine first →',
|
||||
|
||||
newVM: 'New virtual machine',
|
||||
start: 'Start',
|
||||
@@ -989,6 +1109,43 @@ const dict = {
|
||||
driveShareNeedsTools: 'Requires Guest Tools {version} or newer. Restart a running VM to update REIMSTOOLS, then run the install command in macOS again',
|
||||
driveShareMasterOff: 'Turn on Windows drive sharing first',
|
||||
driveShareNoDrives: 'No internal fixed disks are available to share',
|
||||
affinityTitle: 'Processor Affinity',
|
||||
affinityMenu: 'Processor Affinity…',
|
||||
affinityConfigure: 'Configure…',
|
||||
affinityRowDesc: 'Choose which host logical CPUs QEMU can run on (applies live without restarting)',
|
||||
affinitySubtitleRunning: 'Running (PID {pid}) · {vcpus} vCPU · Applies immediately',
|
||||
affinitySubtitleStopped: 'Stopped · {vcpus} vCPU · Applied on next start',
|
||||
affinityModeAuto: 'Auto',
|
||||
affinityModeAll: 'All CPUs',
|
||||
affinityModePCores: 'P-Cores',
|
||||
affinityModeNonLPE: 'P + E',
|
||||
affinityModeCustom: 'Custom',
|
||||
affinityModeAutoHint: 'Follows global policy and avoids oversubscription and slow LP-E cores on hybrid CPUs.',
|
||||
affinityModeAllHint: 'Allows Windows to schedule QEMU across all host logical processors.',
|
||||
affinityModePCoresHint: 'Restricts QEMU to performance cores (P-cores) to minimize scheduling jitter.',
|
||||
affinityModeNonLPEHint: 'Runs QEMU on P + E cores while excluding slow SoC LP-E cores.',
|
||||
affinityModeCustomHint: 'Check the host logical CPUs allowed to run QEMU — identical to Windows Task Manager affinity.',
|
||||
affinitySelectAll: 'All CPUs',
|
||||
affinityPhysicalOnly: 'Physical cores only',
|
||||
affinityExcludeCPU0: 'Exclude CPU 0',
|
||||
affinityOnlyPCores: 'P-cores only',
|
||||
affinityAvoidLPE: 'Exclude LP-E',
|
||||
affinitySelectedSummary: '{selected} / {total} logical CPUs selected · Mask {mask}',
|
||||
affinityLiveMask: 'Active in Windows: {mask} ({count} threads)',
|
||||
affinityOversubWarn: 'Only {selected} logical CPUs selected for {vcpus} guest vCPUs; this may cause noticeable stalls.',
|
||||
affinityNeedOne: 'Select at least 1 logical CPU',
|
||||
affinityEcoQoS: 'Disable Windows EcoQoS power throttling',
|
||||
affinityEcoQoSDesc: 'Prevents Windows 11 from parking unfocused/background QEMU threads onto 2 low-power cores',
|
||||
affinityApplyNow: 'Apply Now',
|
||||
affinitySave: 'Save',
|
||||
affinitySummaryAuto: 'Auto ({eff} · {count}T)',
|
||||
affinitySummaryAll: 'All CPUs ({count}T)',
|
||||
affinitySummaryPCores: 'P-Cores ({count}T · {mask})',
|
||||
affinitySummaryNonLPE: 'P + E ({count}T · {mask})',
|
||||
affinitySummaryCustom: 'Custom ({count}T · {mask})',
|
||||
toastAffinityApplied: 'Processor affinity applied ({count} logical CPUs · {mask})',
|
||||
toastAffinitySaved: 'Processor affinity saved for next start',
|
||||
failAffinity: 'Could not update processor affinity',
|
||||
networkDesc: 'Shares the host connection through NAT',
|
||||
sshForward: 'SSH port forwarding',
|
||||
sshOffDesc: 'Forwards a host port to port 22 in macOS',
|
||||
@@ -1107,11 +1264,6 @@ const dict = {
|
||||
toastBorderlessNextStart: 'Fullscreen launch saved — applies on next restart',
|
||||
statsCPU: 'QEMU CPU',
|
||||
statsMemory: 'Host RAM',
|
||||
showWindow: 'Show Window',
|
||||
copyScreenshot: 'Copy Screenshot',
|
||||
toastScreenshotCopied: 'Screenshot copied',
|
||||
failShowWindow: "Couldn't find the VM window",
|
||||
failScreenshot: "Couldn't take a screenshot",
|
||||
on: 'On',
|
||||
netShared: 'Shared network',
|
||||
netOff: 'No network',
|
||||
|
||||
@@ -1180,6 +1180,62 @@ h1, h2, h3, p { margin: 0; }
|
||||
/* The assistant keeps one size across steps, like macOS setup assistants. */
|
||||
.dialog.wizard-dialog { width: 760px; height: min(660px, calc(100vh - 80px)); }
|
||||
|
||||
/* Processor affinity / CPU core mapping dialog */
|
||||
.dialog.affinity-dialog { width: 640px; max-width: calc(100vw - 48px); }
|
||||
.affinity-body { display: flex; flex-direction: column; gap: 12px; }
|
||||
.affinity-mode-bar { display: flex; flex-direction: column; gap: 6px; }
|
||||
.affinity-hint { font-size: var(--fs-12); color: var(--text-3); }
|
||||
.affinity-quick-bar { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.affinity-chip {
|
||||
height: 26px; padding: 0 10px; border-radius: 999px;
|
||||
border: 1px solid var(--border-strong); background: var(--surface-1); color: var(--text-2);
|
||||
font-size: var(--fs-12); font-weight: var(--fw-medium); cursor: pointer;
|
||||
transition: background var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out);
|
||||
}
|
||||
.affinity-chip:hover:not(:disabled) { background: var(--surface-hover); color: var(--text); }
|
||||
.affinity-chip.is-active { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); }
|
||||
.affinity-chip:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
.affinity-grid {
|
||||
display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px;
|
||||
max-height: 248px; overflow-y: auto; padding: 2px;
|
||||
}
|
||||
.affinity-cpu {
|
||||
display: flex; align-items: center; gap: 7px; padding: 7px 9px;
|
||||
border-radius: var(--r-md); border: 1px solid var(--border-strong);
|
||||
background: var(--surface-1); color: var(--text-2); cursor: pointer; text-align: left;
|
||||
transition: background var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), transform var(--dur-press) var(--ease-out);
|
||||
}
|
||||
.affinity-cpu:hover:not(:disabled) { background: var(--surface-hover); color: var(--text); }
|
||||
.affinity-cpu:active:not(:disabled) { transform: scale(0.98); }
|
||||
.affinity-cpu.is-checked { border-color: var(--accent); background: var(--accent-soft); color: var(--text); }
|
||||
.affinity-cpu.is-lpe:not(.is-checked) { opacity: 0.72; }
|
||||
.affinity-check {
|
||||
width: 16px; height: 16px; border-radius: 4px; flex-shrink: 0;
|
||||
border: 1.5px solid var(--border-strong); background: var(--surface-0);
|
||||
display: grid; place-items: center; color: #fff;
|
||||
}
|
||||
.affinity-cpu.is-checked .affinity-check { border-color: var(--accent); background: var(--accent); }
|
||||
.affinity-cpu-name { font-size: var(--fs-12); font-weight: var(--fw-medium); white-space: nowrap; }
|
||||
.affinity-cpu-meta { margin-left: auto; display: inline-flex; align-items: center; gap: 4px; }
|
||||
.affinity-core-tag { font-size: 10px; color: var(--text-3); }
|
||||
.affinity-tier {
|
||||
font-size: 10px; font-weight: var(--fw-strong); line-height: 1; padding: 2px 5px; border-radius: 999px;
|
||||
}
|
||||
.affinity-tier.tier-p { background: rgba(0, 122, 255, 0.14); color: var(--accent); }
|
||||
.affinity-tier.tier-e { background: rgba(52, 199, 89, 0.15); color: var(--status-running); }
|
||||
.affinity-tier.tier-lpe { background: rgba(255, 159, 10, 0.16); color: var(--status-busy); }
|
||||
.affinity-summary {
|
||||
display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px;
|
||||
padding: 8px 10px; border-radius: var(--r-md); background: var(--surface-1); border: 1px solid var(--border);
|
||||
font-size: var(--fs-12); color: var(--text-2);
|
||||
}
|
||||
.affinity-summary > span { display: inline-flex; align-items: center; gap: 5px; }
|
||||
.affinity-live { color: var(--status-running); }
|
||||
.affinity-eco-row {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 12px;
|
||||
padding: 10px 12px; border-radius: var(--r-md); background: var(--surface-1); border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
/* Reduced motion: stop decorative loops & positional motion */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.status-busy, .vm-screen-live, .skeleton-bar { animation: none; }
|
||||
@@ -1190,3 +1246,103 @@ h1, h2, h3, p { margin: 0; }
|
||||
animation-duration: 140ms;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── v0.2.6 Enhancements: Screenshot, Note, Dropzone, Snapshots, Log Filter, Welcome ── */
|
||||
.vm-screen.is-live { cursor: pointer; }
|
||||
.vm-screen-shot {
|
||||
position: absolute; right: 8px; bottom: 8px; z-index: 3;
|
||||
width: 30px; height: 30px; border: 1px solid rgba(255, 255, 255, 0.22); border-radius: 8px;
|
||||
display: grid; place-items: center; cursor: pointer;
|
||||
background: rgba(20, 22, 28, 0.68); color: #ffffff;
|
||||
backdrop-filter: blur(10px);
|
||||
opacity: 0; transform: translateY(3px);
|
||||
transition: opacity var(--dur-fast) var(--ease-out), transform var(--dur-fast) var(--ease-out), background var(--dur-fast) var(--ease-out);
|
||||
}
|
||||
.vm-screen:hover .vm-screen-shot,
|
||||
.vm-screen-shot:focus-visible { opacity: 1; transform: translateY(0); }
|
||||
.vm-screen-shot:hover { background: rgba(20, 22, 28, 0.88); }
|
||||
.vm-screen-shot:active { transform: scale(0.94); }
|
||||
|
||||
.vm-note-row { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-height: 22px; max-width: 100%; }
|
||||
.vm-note-btn {
|
||||
display: inline-flex; align-items: center; gap: 5px; max-width: 420px;
|
||||
padding: 2px 8px; border: none; border-radius: 6px; background: transparent;
|
||||
font-size: var(--fs-12); color: var(--text-3); cursor: pointer;
|
||||
transition: background var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out);
|
||||
}
|
||||
.vm-note-btn:hover { background: var(--surface-hover); color: var(--text-2); }
|
||||
.vm-note-btn span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.vm-note-input {
|
||||
width: 280px; max-width: 100%; height: 26px; padding: 0 8px; text-align: center;
|
||||
border-radius: var(--r-sm); border: 1px solid var(--accent); background: var(--surface-input);
|
||||
color: var(--text); font: inherit; font-size: var(--fs-12); box-shadow: var(--focus-ring);
|
||||
}
|
||||
|
||||
.vm-page-drop { position: relative; }
|
||||
.drop-banner {
|
||||
position: sticky; top: 0; z-index: 20;
|
||||
display: flex; align-items: center; justify-content: center; gap: 8px;
|
||||
padding: 12px 16px; border-radius: var(--r-lg);
|
||||
background: var(--accent-soft); border: 1.5px dashed var(--accent);
|
||||
color: var(--accent-soft-text); font-size: var(--fs-13); font-weight: var(--fw-medium);
|
||||
backdrop-filter: var(--blur-overlay);
|
||||
}
|
||||
|
||||
/* Interactive install stepper */
|
||||
.guide-step-btn {
|
||||
width: 22px; height: 22px; padding: 0; border-radius: 50%; flex-shrink: 0; margin-top: 1px;
|
||||
display: grid; place-items: center; border: none; cursor: pointer;
|
||||
background: var(--accent-soft); color: var(--accent-soft-text);
|
||||
font-size: var(--fs-11); font-weight: var(--fw-strong); font-variant-numeric: tabular-nums;
|
||||
transition: background var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), transform var(--dur-press) var(--ease-out);
|
||||
}
|
||||
.guide-step-btn:active { transform: scale(0.92); }
|
||||
.guide-step-btn.done { background: var(--ok-soft); color: var(--ok-text); }
|
||||
.guide-step.is-done .guide-step-body { opacity: 0.62; }
|
||||
|
||||
/* Inline snapshot creation bar */
|
||||
.snap-create-bar {
|
||||
display: flex; align-items: center; gap: 8px;
|
||||
padding: 10px 16px; background: var(--surface-1);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.snap-create-bar .input { flex: 1; height: 29px; }
|
||||
.snap-meta-hint { font-size: var(--fs-12); font-weight: var(--fw-regular); color: var(--text-3); }
|
||||
|
||||
/* Log filter controls */
|
||||
.log-filter-input {
|
||||
width: 148px; height: 22px; padding: 0 8px;
|
||||
border-radius: var(--r-sm); border: 1px solid var(--border-strong);
|
||||
background: var(--surface-input); color: var(--text); font: inherit; font-size: var(--fs-12);
|
||||
}
|
||||
.log-filter-input:focus { border-color: var(--accent); box-shadow: var(--focus-ring); }
|
||||
.log-filter-pill {
|
||||
height: 22px; padding: 0 8px; border-radius: var(--r-sm);
|
||||
border: 1px solid var(--border); background: transparent;
|
||||
color: var(--text-3); font-size: 11.5px; cursor: pointer;
|
||||
transition: background var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out);
|
||||
}
|
||||
.log-filter-pill:hover { color: var(--text); background: var(--surface-hover); }
|
||||
.log-filter-pill[aria-pressed="true"] { background: var(--warn-soft); border-color: transparent; color: var(--warn-text); font-weight: var(--fw-medium); }
|
||||
|
||||
/* Storage breakdown bar (Engine page) */
|
||||
.storage-bar {
|
||||
display: flex; height: 8px; border-radius: 999px; overflow: hidden;
|
||||
background: var(--surface-active); gap: 2px;
|
||||
}
|
||||
.storage-seg-vms { background: var(--accent); }
|
||||
.storage-seg-inst { background: var(--status-running); }
|
||||
.storage-seg-rt { background: #7a78ff; }
|
||||
.storage-legend { display: flex; flex-wrap: wrap; gap: 14px; font-size: var(--fs-12); color: var(--text-2); font-variant-numeric: tabular-nums; }
|
||||
.storage-legend-item { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.storage-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
|
||||
|
||||
/* Zero-VM welcome state */
|
||||
.welcome-card {
|
||||
display: flex; flex-direction: column; align-items: center; text-align: center; gap: 12px;
|
||||
padding: 40px 28px; margin-top: 24px;
|
||||
background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-xl);
|
||||
box-shadow: var(--shadow-card);
|
||||
}
|
||||
.welcome-card h1 { font-size: 22px; font-weight: 700; letter-spacing: -0.02em; }
|
||||
.welcome-card p { font-size: var(--fs-13); color: var(--text-2); max-width: 380px; }
|
||||
@@ -20,6 +20,7 @@ export type DisplayInfo = host.DisplayInfo
|
||||
export type DisplayPreset = host.DisplayPreset
|
||||
export type AudioInfo = host.AudioInfo
|
||||
export type WHPXCapabilities = host.WHPXCapabilities
|
||||
export type LogicalCPUInfo = host.LogicalCPUInfo
|
||||
|
||||
export type GPUInfo = Model<host.GPUInfo> & {
|
||||
kind: 'discrete' | 'integrated' | 'virtual' | 'unknown'
|
||||
@@ -65,11 +66,23 @@ export type AppUpdateInfo = version.UpdateInfo
|
||||
export type VMDetail = reims.VMDetail
|
||||
export type VMStats = app.VMStats
|
||||
export type DriveShareSettings = Model<app.DriveShareSettings>
|
||||
export type VMAffinityMode = 'auto' | 'all' | 'pcores' | 'non_lpe' | 'custom'
|
||||
export type VMAffinityUpdate = {
|
||||
mode: VMAffinityMode
|
||||
cpus?: number[]
|
||||
disable_eco_qos: boolean
|
||||
}
|
||||
export type VMAffinityStatus = Omit<Model<app.VMAffinityStatus>, 'mode' | 'effective_mode'> & {
|
||||
mode: VMAffinityMode
|
||||
effective_mode: VMAffinityMode
|
||||
}
|
||||
/** One frame of a VM's screen (internal/app/thumbnail_flow.go). Empty data_url: none yet. */
|
||||
export type VMThumbnail = app.VMThumbnail
|
||||
export type ValidationIssue = reims.ValidationIssue
|
||||
export type DiskResizeResult = reims.DiskResizeResult
|
||||
export type DiskCompactResult = reims.DiskCompactResult
|
||||
export type DiskSnapshot = reims.DiskSnapshot
|
||||
export type StorageBreakdown = Model<app.StorageBreakdown>
|
||||
export type SetOpts = reims.SetOpts
|
||||
|
||||
export type CreateOpts = Model<reims.CreateOpts> & {
|
||||
|
||||
+3
-15
@@ -3,12 +3,14 @@
|
||||
// re-typed here; everything else passes through unchanged.
|
||||
import * as Go from '../wailsjs/go/app/App'
|
||||
import { EventsOn } from '../wailsjs/runtime/runtime'
|
||||
import type { AppState, CachedInstaller, DataRootChoice, LogEntry, RemoteRuntime, Task } from './types'
|
||||
import type { AppState, CachedInstaller, DataRootChoice, LogEntry, RemoteRuntime, Task, VMAffinityStatus, VMAffinityUpdate } from './types'
|
||||
|
||||
export const api = {
|
||||
...Go,
|
||||
GetState: Go.GetState as () => Promise<AppState>,
|
||||
GetTasks: Go.GetTasks as () => Promise<Task[]>,
|
||||
GetVMAffinity: Go.GetVMAffinity as (name: string) => Promise<VMAffinityStatus>,
|
||||
SetVMAffinity: Go.SetVMAffinity as (name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
|
||||
ListInstallers: Go.ListInstallers as () => Promise<CachedInstaller[] | null>,
|
||||
ListRemoteRuntimes: Go.ListRemoteRuntimes as () => Promise<RemoteRuntime[] | null>,
|
||||
SuggestDataRoots: Go.SuggestDataRoots as () => Promise<DataRootChoice[] | null>,
|
||||
@@ -19,17 +21,3 @@ export const events = {
|
||||
onStateChanged: (cb: () => void) => EventsOn('reims:state-changed', cb),
|
||||
onLog: (cb: (entry: LogEntry) => void) => EventsOn('reims:log', cb),
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls a newer backend adds (FocusVMWindow, CopyVMScreenshot). Looked up at
|
||||
* run time so the UI offers them only when the running backend has them;
|
||||
* undefined otherwise.
|
||||
*/
|
||||
type OptionalCalls = {
|
||||
FocusVMWindow: (name: string) => Promise<void>
|
||||
CopyVMScreenshot: (name: string) => Promise<void>
|
||||
}
|
||||
export function optionalApi<K extends keyof OptionalCalls>(key: K): OptionalCalls[K] | undefined {
|
||||
const fn = (window as unknown as { go?: { app?: { App?: Record<string, unknown> } } }).go?.app?.App?.[key]
|
||||
return typeof fn === 'function' ? (fn as OptionalCalls[K]) : undefined
|
||||
}
|
||||
Vendored
+34
@@ -24,14 +24,22 @@ export function CompactVMDisk(arg1:string):Promise<reims.DiskCompactResult>;
|
||||
|
||||
export function CompleteSetup(arg1:string):Promise<void>;
|
||||
|
||||
export function CopyVMScreenshot(arg1:string):Promise<void>;
|
||||
|
||||
export function CreateSnapshot(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function CreateVM(arg1:reims.CreateOpts):Promise<void>;
|
||||
|
||||
export function DeleteInstaller(arg1:string):Promise<void>;
|
||||
|
||||
export function DeleteSnapshot(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function DeleteVM(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function DeliverFileToGuest(arg1:string):Promise<string>;
|
||||
|
||||
export function DeliverPathsToGuest(arg1:string,arg2:Array<string>):Promise<Array<string>>;
|
||||
|
||||
export function DetachGuestTools(arg1:string):Promise<void>;
|
||||
|
||||
export function DismissTask(arg1:string):Promise<void>;
|
||||
@@ -50,14 +58,24 @@ export function ExportDiagnostics(arg1:string):Promise<string>;
|
||||
|
||||
export function FinishInstall(arg1:string):Promise<void>;
|
||||
|
||||
export function FocusVMWindow(arg1:string):Promise<void>;
|
||||
|
||||
export function GetState():Promise<app.AppState>;
|
||||
|
||||
export function GetStorageBreakdown():Promise<app.StorageBreakdown>;
|
||||
|
||||
export function GetTasks():Promise<Array<app.Task>>;
|
||||
|
||||
export function GetVMAffinity(arg1:string):Promise<app.VMAffinityStatus>;
|
||||
|
||||
export function GetVMDetail(arg1:string):Promise<reims.VMDetail>;
|
||||
|
||||
export function GetVMDriveShareSettings(arg1:string):Promise<app.DriveShareSettings>;
|
||||
|
||||
export function GetVMNote(arg1:string):Promise<string>;
|
||||
|
||||
export function GetVMSSHUser(arg1:string):Promise<string>;
|
||||
|
||||
export function GetVMStats(arg1:string):Promise<app.VMStats>;
|
||||
|
||||
export function GetVMThumbnail(arg1:string):Promise<app.VMThumbnail>;
|
||||
@@ -72,14 +90,20 @@ export function ListOfflineReleases():Promise<Array<installer.Release>>;
|
||||
|
||||
export function ListRemoteRuntimes():Promise<Array<runtime.Remote>>;
|
||||
|
||||
export function ListSnapshots(arg1:string):Promise<Array<reims.DiskSnapshot>>;
|
||||
|
||||
export function OpenProcessorScheduling():Promise<void>;
|
||||
|
||||
export function OpenSSHTerminal(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function OpenSharedFolder(arg1:string):Promise<void>;
|
||||
|
||||
export function OpenURL(arg1:string):Promise<void>;
|
||||
|
||||
export function OpenVMFolder(arg1:string):Promise<void>;
|
||||
|
||||
export function OpenVSCodeSSH(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function PickDirectory(arg1:string):Promise<string>;
|
||||
|
||||
export function PickFile(arg1:string,arg2:string):Promise<string>;
|
||||
@@ -96,6 +120,8 @@ export function ResizeVMDisk(arg1:string,arg2:string):Promise<reims.DiskResizeRe
|
||||
|
||||
export function RestartVM(arg1:string):Promise<void>;
|
||||
|
||||
export function RestoreSnapshot(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function SetAutoPinPCores(arg1:boolean):Promise<void>;
|
||||
|
||||
export function SetDataRoot(arg1:string):Promise<void>;
|
||||
@@ -110,8 +136,14 @@ export function SetRuntimeChannel(arg1:string):Promise<void>;
|
||||
|
||||
export function SetRuntimeSource(arg1:string):Promise<void>;
|
||||
|
||||
export function SetVMAffinity(arg1:string,arg2:app.VMAffinityUpdate):Promise<app.VMAffinityStatus>;
|
||||
|
||||
export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array<string>):Promise<app.DriveShareSettings>;
|
||||
|
||||
export function SetVMNote(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function SetVMSSHUser(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function ShowMainWindow():Promise<void>;
|
||||
|
||||
export function StartVM(arg1:string):Promise<void>;
|
||||
@@ -133,3 +165,5 @@ export function UseRuntime(arg1:string):Promise<void>;
|
||||
export function ValidateCreate(arg1:reims.CreateOpts):Promise<Array<reims.ValidationIssue>>;
|
||||
|
||||
export function ValidateSet(arg1:reims.SetOpts):Promise<Array<reims.ValidationIssue>>;
|
||||
|
||||
export function WriteSSHConfig(arg1:string,arg2:string):Promise<string>;
|
||||
@@ -38,6 +38,14 @@ export function CompleteSetup(arg1) {
|
||||
return window['go']['app']['App']['CompleteSetup'](arg1);
|
||||
}
|
||||
|
||||
export function CopyVMScreenshot(arg1) {
|
||||
return window['go']['app']['App']['CopyVMScreenshot'](arg1);
|
||||
}
|
||||
|
||||
export function CreateSnapshot(arg1, arg2) {
|
||||
return window['go']['app']['App']['CreateSnapshot'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CreateVM(arg1) {
|
||||
return window['go']['app']['App']['CreateVM'](arg1);
|
||||
}
|
||||
@@ -46,6 +54,10 @@ export function DeleteInstaller(arg1) {
|
||||
return window['go']['app']['App']['DeleteInstaller'](arg1);
|
||||
}
|
||||
|
||||
export function DeleteSnapshot(arg1, arg2) {
|
||||
return window['go']['app']['App']['DeleteSnapshot'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function DeleteVM(arg1, arg2) {
|
||||
return window['go']['app']['App']['DeleteVM'](arg1, arg2);
|
||||
}
|
||||
@@ -54,6 +66,10 @@ export function DeliverFileToGuest(arg1) {
|
||||
return window['go']['app']['App']['DeliverFileToGuest'](arg1);
|
||||
}
|
||||
|
||||
export function DeliverPathsToGuest(arg1, arg2) {
|
||||
return window['go']['app']['App']['DeliverPathsToGuest'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function DetachGuestTools(arg1) {
|
||||
return window['go']['app']['App']['DetachGuestTools'](arg1);
|
||||
}
|
||||
@@ -90,14 +106,26 @@ export function FinishInstall(arg1) {
|
||||
return window['go']['app']['App']['FinishInstall'](arg1);
|
||||
}
|
||||
|
||||
export function FocusVMWindow(arg1) {
|
||||
return window['go']['app']['App']['FocusVMWindow'](arg1);
|
||||
}
|
||||
|
||||
export function GetState() {
|
||||
return window['go']['app']['App']['GetState']();
|
||||
}
|
||||
|
||||
export function GetStorageBreakdown() {
|
||||
return window['go']['app']['App']['GetStorageBreakdown']();
|
||||
}
|
||||
|
||||
export function GetTasks() {
|
||||
return window['go']['app']['App']['GetTasks']();
|
||||
}
|
||||
|
||||
export function GetVMAffinity(arg1) {
|
||||
return window['go']['app']['App']['GetVMAffinity'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMDetail(arg1) {
|
||||
return window['go']['app']['App']['GetVMDetail'](arg1);
|
||||
}
|
||||
@@ -106,6 +134,14 @@ export function GetVMDriveShareSettings(arg1) {
|
||||
return window['go']['app']['App']['GetVMDriveShareSettings'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMNote(arg1) {
|
||||
return window['go']['app']['App']['GetVMNote'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMSSHUser(arg1) {
|
||||
return window['go']['app']['App']['GetVMSSHUser'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMStats(arg1) {
|
||||
return window['go']['app']['App']['GetVMStats'](arg1);
|
||||
}
|
||||
@@ -134,10 +170,18 @@ export function ListRemoteRuntimes() {
|
||||
return window['go']['app']['App']['ListRemoteRuntimes']();
|
||||
}
|
||||
|
||||
export function ListSnapshots(arg1) {
|
||||
return window['go']['app']['App']['ListSnapshots'](arg1);
|
||||
}
|
||||
|
||||
export function OpenProcessorScheduling() {
|
||||
return window['go']['app']['App']['OpenProcessorScheduling']();
|
||||
}
|
||||
|
||||
export function OpenSSHTerminal(arg1, arg2) {
|
||||
return window['go']['app']['App']['OpenSSHTerminal'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function OpenSharedFolder(arg1) {
|
||||
return window['go']['app']['App']['OpenSharedFolder'](arg1);
|
||||
}
|
||||
@@ -150,6 +194,10 @@ export function OpenVMFolder(arg1) {
|
||||
return window['go']['app']['App']['OpenVMFolder'](arg1);
|
||||
}
|
||||
|
||||
export function OpenVSCodeSSH(arg1, arg2) {
|
||||
return window['go']['app']['App']['OpenVSCodeSSH'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function PickDirectory(arg1) {
|
||||
return window['go']['app']['App']['PickDirectory'](arg1);
|
||||
}
|
||||
@@ -182,6 +230,10 @@ export function RestartVM(arg1) {
|
||||
return window['go']['app']['App']['RestartVM'](arg1);
|
||||
}
|
||||
|
||||
export function RestoreSnapshot(arg1, arg2) {
|
||||
return window['go']['app']['App']['RestoreSnapshot'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SetAutoPinPCores(arg1) {
|
||||
return window['go']['app']['App']['SetAutoPinPCores'](arg1);
|
||||
}
|
||||
@@ -210,10 +262,22 @@ export function SetRuntimeSource(arg1) {
|
||||
return window['go']['app']['App']['SetRuntimeSource'](arg1);
|
||||
}
|
||||
|
||||
export function SetVMAffinity(arg1, arg2) {
|
||||
return window['go']['app']['App']['SetVMAffinity'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SetVMDriveShareSettings(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMDriveShareSettings'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function SetVMNote(arg1, arg2) {
|
||||
return window['go']['app']['App']['SetVMNote'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SetVMSSHUser(arg1, arg2) {
|
||||
return window['go']['app']['App']['SetVMSSHUser'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function ShowMainWindow() {
|
||||
return window['go']['app']['App']['ShowMainWindow']();
|
||||
}
|
||||
@@ -257,3 +321,7 @@ export function ValidateCreate(arg1) {
|
||||
export function ValidateSet(arg1) {
|
||||
return window['go']['app']['App']['ValidateSet'](arg1);
|
||||
}
|
||||
|
||||
export function WriteSSHConfig(arg1, arg2) {
|
||||
return window['go']['app']['App']['WriteSSHConfig'](arg1, arg2);
|
||||
}
|
||||
@@ -160,6 +160,58 @@ export namespace app {
|
||||
this.to = source["to"];
|
||||
}
|
||||
}
|
||||
export class VMStorageItem {
|
||||
name: string;
|
||||
bytes: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new VMStorageItem(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.name = source["name"];
|
||||
this.bytes = source["bytes"];
|
||||
}
|
||||
}
|
||||
export class StorageBreakdown {
|
||||
vms_bytes: number;
|
||||
installers_bytes: number;
|
||||
runtimes_bytes: number;
|
||||
total_bytes: number;
|
||||
vms: VMStorageItem[];
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new StorageBreakdown(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.vms_bytes = source["vms_bytes"];
|
||||
this.installers_bytes = source["installers_bytes"];
|
||||
this.runtimes_bytes = source["runtimes_bytes"];
|
||||
this.total_bytes = source["total_bytes"];
|
||||
this.vms = this.convertValues(source["vms"], VMStorageItem);
|
||||
}
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
}
|
||||
if (a.slice && a.map) {
|
||||
return (a as any[]).map(elem => this.convertValues(elem, classs));
|
||||
} else if ("object" === typeof a) {
|
||||
if (asMap) {
|
||||
for (const key of Object.keys(a)) {
|
||||
a[key] = new classs(a[key]);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
return new classs(a);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class Task {
|
||||
id: string;
|
||||
kind: string;
|
||||
@@ -200,6 +252,58 @@ export namespace app {
|
||||
this.updated_at = source["updated_at"];
|
||||
}
|
||||
}
|
||||
export class VMAffinityStatus {
|
||||
mode: string;
|
||||
cpus: number[];
|
||||
disable_eco_qos: boolean;
|
||||
effective_mode: string;
|
||||
effective_cpus: number[];
|
||||
effective_mask_hex: string;
|
||||
vcpus: number;
|
||||
oversubscribed: boolean;
|
||||
running: boolean;
|
||||
pid?: number;
|
||||
live_cpus?: number[];
|
||||
live_mask_hex?: string;
|
||||
live_read_error?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new VMAffinityStatus(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.mode = source["mode"];
|
||||
this.cpus = source["cpus"];
|
||||
this.disable_eco_qos = source["disable_eco_qos"];
|
||||
this.effective_mode = source["effective_mode"];
|
||||
this.effective_cpus = source["effective_cpus"];
|
||||
this.effective_mask_hex = source["effective_mask_hex"];
|
||||
this.vcpus = source["vcpus"];
|
||||
this.oversubscribed = source["oversubscribed"];
|
||||
this.running = source["running"];
|
||||
this.pid = source["pid"];
|
||||
this.live_cpus = source["live_cpus"];
|
||||
this.live_mask_hex = source["live_mask_hex"];
|
||||
this.live_read_error = source["live_read_error"];
|
||||
}
|
||||
}
|
||||
export class VMAffinityUpdate {
|
||||
mode: string;
|
||||
cpus?: number[];
|
||||
disable_eco_qos: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new VMAffinityUpdate(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.mode = source["mode"];
|
||||
this.cpus = source["cpus"];
|
||||
this.disable_eco_qos = source["disable_eco_qos"];
|
||||
}
|
||||
}
|
||||
export class VMStats {
|
||||
name: string;
|
||||
running: boolean;
|
||||
@@ -236,6 +340,7 @@ export namespace app {
|
||||
this.guest_tools_sleep_guard = source["guest_tools_sleep_guard"];
|
||||
}
|
||||
}
|
||||
|
||||
export class VMThumbnail {
|
||||
data_url: string;
|
||||
captured_at: number;
|
||||
@@ -368,6 +473,24 @@ export namespace host {
|
||||
this.kind = source["kind"];
|
||||
}
|
||||
}
|
||||
export class LogicalCPUInfo {
|
||||
index: number;
|
||||
core_index: number;
|
||||
tier: string;
|
||||
smt: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new LogicalCPUInfo(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.index = source["index"];
|
||||
this.core_index = source["core_index"];
|
||||
this.tier = source["tier"];
|
||||
this.smt = source["smt"];
|
||||
}
|
||||
}
|
||||
export class Optimization {
|
||||
id: string;
|
||||
status: string;
|
||||
@@ -424,6 +547,7 @@ export namespace host {
|
||||
non_lpe_mask?: number;
|
||||
non_lpe_mask_hex?: string;
|
||||
non_lpe_logical_cpus?: number[];
|
||||
cpu_topology?: LogicalCPUInfo[];
|
||||
total_ram_gb: number;
|
||||
avail_ram_gb: number;
|
||||
memory_load_pct: number;
|
||||
@@ -467,6 +591,7 @@ export namespace host {
|
||||
this.non_lpe_mask = source["non_lpe_mask"];
|
||||
this.non_lpe_mask_hex = source["non_lpe_mask_hex"];
|
||||
this.non_lpe_logical_cpus = source["non_lpe_logical_cpus"];
|
||||
this.cpu_topology = this.convertValues(source["cpu_topology"], LogicalCPUInfo);
|
||||
this.total_ram_gb = source["total_ram_gb"];
|
||||
this.avail_ram_gb = source["avail_ram_gb"];
|
||||
this.memory_load_pct = source["memory_load_pct"];
|
||||
@@ -660,6 +785,24 @@ export namespace reims {
|
||||
this.guest_expand_cmd = source["guest_expand_cmd"];
|
||||
}
|
||||
}
|
||||
export class DiskSnapshot {
|
||||
id: string;
|
||||
name: string;
|
||||
created_at: number;
|
||||
vm_state_bytes: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DiskSnapshot(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.id = source["id"];
|
||||
this.name = source["name"];
|
||||
this.created_at = source["created_at"];
|
||||
this.vm_state_bytes = source["vm_state_bytes"];
|
||||
}
|
||||
}
|
||||
export class SetOpts {
|
||||
name: string;
|
||||
cpus?: number;
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// VMAffinityUpdate is the payload passed from the UI to save and live-apply a
|
||||
// VM's CPU affinity mapping and EcoQoS power-throttling policy.
|
||||
type VMAffinityUpdate struct {
|
||||
Mode string `json:"mode"`
|
||||
CPUs []int `json:"cpus,omitempty"`
|
||||
DisableEcoQoS bool `json:"disable_eco_qos"`
|
||||
}
|
||||
|
||||
// VMAffinityStatus describes both the saved per-VM affinity policy and the live
|
||||
// QEMU process affinity state (when the VM is running).
|
||||
type VMAffinityStatus struct {
|
||||
Mode string `json:"mode"`
|
||||
CPUs []int `json:"cpus"`
|
||||
DisableEcoQoS bool `json:"disable_eco_qos"`
|
||||
EffectiveMode string `json:"effective_mode"`
|
||||
EffectiveCPUs []int `json:"effective_cpus"`
|
||||
EffectiveMaskHex string `json:"effective_mask_hex"`
|
||||
VCPUs int `json:"vcpus"`
|
||||
Oversubscribed bool `json:"oversubscribed"`
|
||||
Running bool `json:"running"`
|
||||
PID int `json:"pid,omitempty"`
|
||||
LiveCPUs []int `json:"live_cpus,omitempty"`
|
||||
LiveMaskHex string `json:"live_mask_hex,omitempty"`
|
||||
LiveReadError string `json:"live_read_error,omitempty"`
|
||||
}
|
||||
|
||||
func (a *App) findRunningVMPID(ctx context.Context, name string) int {
|
||||
if c, err := a.client(); err == nil {
|
||||
if vms, lerr := c.List(ctx); lerr == nil {
|
||||
for _, vm := range vms {
|
||||
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
|
||||
return *vm.PID
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for _, vm := range a.lastVMs {
|
||||
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
|
||||
return *vm.PID
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func buildVMAffinityStatus(detail reims.VMDetail, rep host.Report, globalAutoPin bool, pid int) VMAffinityStatus {
|
||||
cfg := vmstart.ReadVMAffinity(detail.Directory)
|
||||
res := vmstart.ResolveVMAffinity(cfg, globalAutoPin, rep, detail.CPUs)
|
||||
savedCPUs := cfg.CPUs
|
||||
if savedCPUs == nil {
|
||||
savedCPUs = []int{}
|
||||
}
|
||||
effCPUs := res.CPUs
|
||||
if effCPUs == nil {
|
||||
effCPUs = []int{}
|
||||
}
|
||||
st := VMAffinityStatus{
|
||||
Mode: string(res.ConfigMode),
|
||||
CPUs: savedCPUs,
|
||||
DisableEcoQoS: res.DisableEcoQoS,
|
||||
EffectiveMode: string(res.EffectiveMode),
|
||||
EffectiveCPUs: effCPUs,
|
||||
EffectiveMaskHex: res.MaskHex,
|
||||
VCPUs: detail.CPUs,
|
||||
Oversubscribed: detail.CPUs > 0 && len(effCPUs) > 0 && len(effCPUs) < detail.CPUs,
|
||||
Running: detail.State == "running" || pid > 0,
|
||||
PID: pid,
|
||||
}
|
||||
if pid > 0 {
|
||||
if procMask, _, err := host.GetProcessAffinityMask(uint32(pid)); err == nil {
|
||||
limit := rep.LogicalCPUs
|
||||
if limit <= 0 || limit > 64 {
|
||||
limit = 64
|
||||
}
|
||||
st.LiveCPUs = host.MaskToCPUs(procMask, limit)
|
||||
st.LiveMaskHex = fmt.Sprintf("0x%X", procMask)
|
||||
} else {
|
||||
st.LiveReadError = err.Error()
|
||||
}
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// GetVMAffinity returns the per-VM processor affinity configuration, resolved
|
||||
// effective CPU set, and live QEMU process affinity mask when running.
|
||||
func (a *App) GetVMAffinity(name string) (VMAffinityStatus, error) {
|
||||
detail, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return VMAffinityStatus{}, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
root := a.cfg.DataRoot
|
||||
globalAutoPin := a.cfg.AutoPinPCores
|
||||
a.mu.Unlock()
|
||||
rep := host.Inspect(root)
|
||||
pid := 0
|
||||
if detail.State == "running" {
|
||||
pid = a.findRunningVMPID(a.baseCtx(), name)
|
||||
}
|
||||
return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), nil
|
||||
}
|
||||
|
||||
// SetVMAffinity saves a VM's processor affinity mapping and immediately applies
|
||||
// it (plus EcoQoS power-throttling control) to the running QEMU process if active.
|
||||
func (a *App) SetVMAffinity(name string, req VMAffinityUpdate) (VMAffinityStatus, error) {
|
||||
detail, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return VMAffinityStatus{}, err
|
||||
}
|
||||
if detail.Directory == "" {
|
||||
return VMAffinityStatus{}, fmt.Errorf("VM %s has no directory", name)
|
||||
}
|
||||
a.mu.Lock()
|
||||
root := a.cfg.DataRoot
|
||||
globalAutoPin := a.cfg.AutoPinPCores
|
||||
loc := a.cfg.Locale
|
||||
a.mu.Unlock()
|
||||
|
||||
rep := host.Inspect(root)
|
||||
eco := req.DisableEcoQoS
|
||||
if _, err := vmstart.SaveVMAffinity(detail.Directory, vmstart.VMAffinityConfig{
|
||||
Mode: vmstart.AffinityMode(req.Mode),
|
||||
CPUs: req.CPUs,
|
||||
DisableEcoQoS: &eco,
|
||||
}, rep.LogicalCPUs); err != nil {
|
||||
return VMAffinityStatus{}, err
|
||||
}
|
||||
|
||||
pid := 0
|
||||
if detail.State == "running" {
|
||||
pid = a.findRunningVMPID(a.baseCtx(), name)
|
||||
}
|
||||
if pid > 0 {
|
||||
line, applyErr := vmstart.ApplyVMAffinity(loc, rep, detail.Directory, globalAutoPin, pid, detail.CPUs, true)
|
||||
if line != "" {
|
||||
a.emitLog(name, line)
|
||||
}
|
||||
if applyErr != nil {
|
||||
return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), applyErr
|
||||
}
|
||||
}
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), nil
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
func TestBuildVMAffinityStatus(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
eco := true
|
||||
if _, err := vmstart.SaveVMAffinity(dir, vmstart.VMAffinityConfig{
|
||||
Mode: vmstart.AffinityCustom,
|
||||
CPUs: []int{0, 2, 4, 6},
|
||||
DisableEcoQoS: &eco,
|
||||
}, 16); err != nil {
|
||||
t.Fatalf("SaveVMAffinity: %v", err)
|
||||
}
|
||||
|
||||
rep := host.Report{LogicalCPUs: 16}
|
||||
st := buildVMAffinityStatus(reims.VMDetail{
|
||||
Name: "test-vm",
|
||||
Directory: dir,
|
||||
CPUs: 6,
|
||||
State: "stopped",
|
||||
}, rep, true, 0)
|
||||
|
||||
if st.Mode != "custom" || st.EffectiveMode != "custom" {
|
||||
t.Fatalf("modes = (%s, %s), want custom", st.Mode, st.EffectiveMode)
|
||||
}
|
||||
if !reflect.DeepEqual(st.EffectiveCPUs, []int{0, 2, 4, 6}) {
|
||||
t.Fatalf("EffectiveCPUs = %v", st.EffectiveCPUs)
|
||||
}
|
||||
if st.EffectiveMaskHex != "0x55" {
|
||||
t.Fatalf("EffectiveMaskHex = %s, want 0x55", st.EffectiveMaskHex)
|
||||
}
|
||||
if !st.Oversubscribed {
|
||||
t.Fatalf("expected Oversubscribed=true for 4 CPUs < 6 vCPUs")
|
||||
}
|
||||
if !st.DisableEcoQoS {
|
||||
t.Fatalf("expected DisableEcoQoS=true")
|
||||
}
|
||||
}
|
||||
+11
-6
@@ -221,6 +221,7 @@ func (a *App) pollVMs(ctx context.Context) {
|
||||
watchExits(ctx, vms, exitWatched, a.wakePoll)
|
||||
type pinCandidate struct {
|
||||
name string
|
||||
dir string
|
||||
pid int
|
||||
}
|
||||
var toPin []pinCandidate
|
||||
@@ -252,11 +253,9 @@ func (a *App) pollVMs(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if autoPin && vm.State == "running" && vm.PID != nil && *vm.PID > 0 && !pinnedPIDs[*vm.PID] {
|
||||
if cachedHost.HasHybridCores && cachedHost.PCoreMask > 0 {
|
||||
pinnedPIDs[*vm.PID] = true
|
||||
toPin = append(toPin, pinCandidate{name: vm.Name, pid: *vm.PID})
|
||||
}
|
||||
if vm.State == "running" && vm.PID != nil && *vm.PID > 0 && !pinnedPIDs[*vm.PID] {
|
||||
pinnedPIDs[*vm.PID] = true
|
||||
toPin = append(toPin, pinCandidate{name: vm.Name, dir: vm.Dir, pid: *vm.PID})
|
||||
}
|
||||
fmt.Fprintf(&b, "%s:%s:%s;", vm.Name, vm.State, a.transitions[vm.Name])
|
||||
}
|
||||
@@ -279,12 +278,18 @@ func (a *App) pollVMs(ctx context.Context) {
|
||||
}
|
||||
for _, cand := range toPin {
|
||||
vmCPUs := 0
|
||||
vmDir := cand.dir
|
||||
if c, cerr := a.client(); cerr == nil {
|
||||
if det, derr := c.Show(ctx, cand.name); derr == nil {
|
||||
vmCPUs = det.CPUs
|
||||
if vmDir == "" {
|
||||
vmDir = det.Directory
|
||||
}
|
||||
}
|
||||
}
|
||||
a.emitLog(cand.name, vmstart.PinQEMU(loc, cachedHost, cand.pid, vmCPUs))
|
||||
if line, _ := vmstart.ApplyVMAffinity(loc, cachedHost, vmDir, autoPin, cand.pid, vmCPUs, false); line != "" {
|
||||
a.emitLog(cand.name, line)
|
||||
}
|
||||
}
|
||||
if sig != lastSig {
|
||||
lastSig = sig
|
||||
|
||||
@@ -116,14 +116,21 @@ func (a *App) CloneVMCoW(sourceName, cloneName string) error {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone settings: %v", serr))
|
||||
}
|
||||
}
|
||||
if src.GuestLang != "" {
|
||||
if src.GuestLang != "" || vmstart.HasSavedVMAffinity(src.Directory) {
|
||||
if cloned, serr := c.Show(ctx, cloneName); serr == nil && cloned.Directory != "" {
|
||||
prep, lerr := a.prep(cloneName)
|
||||
if lerr == nil {
|
||||
lerr = prep.ApplyGuestLang(ctx, cloned.Directory, src.GuestLang, false)
|
||||
if src.GuestLang != "" {
|
||||
prep, lerr := a.prep(cloneName)
|
||||
if lerr == nil {
|
||||
lerr = prep.ApplyGuestLang(ctx, cloned.Directory, src.GuestLang, false)
|
||||
}
|
||||
if lerr != nil {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone language (%s): %v", src.GuestLang, lerr))
|
||||
}
|
||||
}
|
||||
if lerr != nil {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone language (%s): %v", src.GuestLang, lerr))
|
||||
if vmstart.HasSavedVMAffinity(src.Directory) {
|
||||
if _, aerr := vmstart.SaveVMAffinity(cloned.Directory, vmstart.ReadVMAffinity(src.Directory), rep.LogicalCPUs); aerr != nil {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not copy CPU affinity setting: %v", aerr))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
)
|
||||
|
||||
const vmNoteFileName = ".reims-go-note"
|
||||
|
||||
// VMStorageItem is one VM's disk footprint under DataRoot.
|
||||
type VMStorageItem struct {
|
||||
Name string `json:"name"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
}
|
||||
|
||||
// StorageBreakdown summarizes how DataRoot space is distributed across VMs,
|
||||
// cached macOS installers, and portable runtimes.
|
||||
type StorageBreakdown struct {
|
||||
VMsBytes int64 `json:"vms_bytes"`
|
||||
InstallersBytes int64 `json:"installers_bytes"`
|
||||
RuntimesBytes int64 `json:"runtimes_bytes"`
|
||||
TotalBytes int64 `json:"total_bytes"`
|
||||
VMs []VMStorageItem `json:"vms"`
|
||||
}
|
||||
|
||||
// GetVMNote returns the optional single-line note saved for a VM.
|
||||
func (a *App) GetVMNote(name string) string {
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil || d.Directory == "" {
|
||||
return ""
|
||||
}
|
||||
b, err := os.ReadFile(filepath.Join(d.Directory, vmNoteFileName))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
|
||||
// SetVMNote stores a short single-line note next to the VM directory.
|
||||
func (a *App) SetVMNote(name, note string) error {
|
||||
note = sanitizeVMNote(note)
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.Directory == "" {
|
||||
return fmt.Errorf("VM directory not found")
|
||||
}
|
||||
p := filepath.Join(d.Directory, vmNoteFileName)
|
||||
if note == "" {
|
||||
_ = os.Remove(p)
|
||||
return nil
|
||||
}
|
||||
return os.WriteFile(p, []byte(note+"\n"), 0o644)
|
||||
}
|
||||
|
||||
func sanitizeVMNote(note string) string {
|
||||
note = strings.ReplaceAll(note, "\r", " ")
|
||||
note = strings.ReplaceAll(note, "\n", " ")
|
||||
note = strings.TrimSpace(note)
|
||||
runes := []rune(note)
|
||||
if len(runes) > 120 {
|
||||
return string(runes[:120])
|
||||
}
|
||||
return note
|
||||
}
|
||||
|
||||
// GetStorageBreakdown computes disk usage across DataRoot subdirectories.
|
||||
func (a *App) GetStorageBreakdown() StorageBreakdown {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
vmsDir := filepath.Join(cfgCopy.XDGDataDir(), "reims-vgpu", "vms")
|
||||
return computeStorageBreakdown(vmsDir, installer.Dir(&cfgCopy), cfgCopy.RuntimesDir(), cfgCopy.ImagesDir())
|
||||
}
|
||||
|
||||
func computeStorageBreakdown(vmsDir, installersDir, runtimesDir, imagesDir string) StorageBreakdown {
|
||||
var out StorageBreakdown
|
||||
if entries, err := os.ReadDir(vmsDir); err == nil {
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() {
|
||||
continue
|
||||
}
|
||||
sz := dirSizeBytes(filepath.Join(vmsDir, e.Name()))
|
||||
out.VMs = append(out.VMs, VMStorageItem{Name: e.Name(), Bytes: sz})
|
||||
out.VMsBytes += sz
|
||||
}
|
||||
}
|
||||
if imgBytes := dirSizeBytes(imagesDir); imgBytes > 0 {
|
||||
out.VMsBytes += imgBytes
|
||||
}
|
||||
sort.Slice(out.VMs, func(i, j int) bool {
|
||||
return out.VMs[i].Bytes > out.VMs[j].Bytes
|
||||
})
|
||||
out.InstallersBytes = dirSizeBytes(installersDir)
|
||||
out.RuntimesBytes = dirSizeBytes(runtimesDir)
|
||||
out.TotalBytes = out.VMsBytes + out.InstallersBytes + out.RuntimesBytes
|
||||
return out
|
||||
}
|
||||
|
||||
func dirSizeBytes(root string) int64 {
|
||||
if root == "" {
|
||||
return 0
|
||||
}
|
||||
var total int64
|
||||
_ = filepath.WalkDir(root, func(_ string, d fs.DirEntry, err error) error {
|
||||
if err != nil || d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
if info, err := d.Info(); err == nil {
|
||||
total += info.Size()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return total
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
)
|
||||
|
||||
func TestParseDiskSnapshotsJSON(t *testing.T) {
|
||||
raw := []byte(`{
|
||||
"format": "qcow2",
|
||||
"snapshots": [
|
||||
{"id": "1", "name": "before-ota", "vm-state-size": 0, "date-sec": 1764400000},
|
||||
{"id": "2", "name": "clean-xcode", "vm-state-size": 0, "date-sec": 1764403600}
|
||||
]
|
||||
}`)
|
||||
fmtName, snaps, err := reims.ParseDiskSnapshotsJSON(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fmtName != "qcow2" || len(snaps) != 2 || snaps[0].Name != "before-ota" || snaps[1].CreatedAt != 1764403600 {
|
||||
t.Fatalf("unexpected snapshots: format=%q snaps=%+v", fmtName, snaps)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSnapshotName(t *testing.T) {
|
||||
if got, err := reims.ValidateSnapshotName(" before-ota-26.2 "); err != nil || got != "before-ota-26.2" {
|
||||
t.Fatalf("valid name failed: %q %v", got, err)
|
||||
}
|
||||
if _, err := reims.ValidateSnapshotName(" "); err == nil {
|
||||
t.Fatal("expected error for empty snapshot name")
|
||||
}
|
||||
if _, err := reims.ValidateSnapshotName(`bad"quote`); err == nil {
|
||||
t.Fatal("expected error for quote in snapshot name")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeVMNoteAndStorageBreakdown(t *testing.T) {
|
||||
if got := sanitizeVMNote(" Xcode 26\nBuilder "); got != "Xcode 26 Builder" {
|
||||
t.Fatalf("sanitizeVMNote = %q", got)
|
||||
}
|
||||
root := t.TempDir()
|
||||
vms := filepath.Join(root, "vms")
|
||||
inst := filepath.Join(root, "installers")
|
||||
rtDir := filepath.Join(root, "runtimes")
|
||||
_ = os.MkdirAll(filepath.Join(vms, "mac-a"), 0o755)
|
||||
_ = os.MkdirAll(filepath.Join(vms, "mac-b"), 0o755)
|
||||
_ = os.MkdirAll(inst, 0o755)
|
||||
_ = os.MkdirAll(rtDir, 0o755)
|
||||
_ = os.WriteFile(filepath.Join(vms, "mac-a", "disk.qcow2"), make([]byte, 200), 0o644)
|
||||
_ = os.WriteFile(filepath.Join(vms, "mac-b", "disk.qcow2"), make([]byte, 500), 0o644)
|
||||
_ = os.WriteFile(filepath.Join(inst, "tahoe.img"), make([]byte, 1000), 0o644)
|
||||
_ = os.WriteFile(filepath.Join(rtDir, "qemu.exe"), make([]byte, 300), 0o644)
|
||||
|
||||
bd := computeStorageBreakdown(vms, inst, rtDir, "")
|
||||
if bd.VMsBytes != 700 || bd.InstallersBytes != 1000 || bd.RuntimesBytes != 300 || bd.TotalBytes != 2000 {
|
||||
t.Fatalf("breakdown = %+v", bd)
|
||||
}
|
||||
if len(bd.VMs) != 2 || bd.VMs[0].Name != "mac-b" || bd.VMs[0].Bytes != 500 {
|
||||
t.Fatalf("VMs order = %+v", bd.VMs)
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
@@ -311,6 +312,43 @@ func (a *App) DeliverFileToGuest(name string) (string, error) {
|
||||
if err != nil || picked == "" {
|
||||
return "", err
|
||||
}
|
||||
return a.deliverHostFile(name, picked)
|
||||
}
|
||||
|
||||
// DeliverPathsToGuest copies one or more dropped host file paths into
|
||||
// `<DataRoot>/shared/<vmName>`, skipping directories.
|
||||
func (a *App) DeliverPathsToGuest(name string, paths []string) ([]string, error) {
|
||||
if len(paths) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var delivered []string
|
||||
var lastErr error
|
||||
for _, p := range paths {
|
||||
if strings.TrimSpace(p) == "" {
|
||||
continue
|
||||
}
|
||||
st, err := os.Stat(p)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
if st.IsDir() {
|
||||
continue
|
||||
}
|
||||
base, err := a.deliverHostFile(name, p)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
delivered = append(delivered, base)
|
||||
}
|
||||
if len(delivered) == 0 && lastErr != nil {
|
||||
return nil, lastErr
|
||||
}
|
||||
return delivered, nil
|
||||
}
|
||||
|
||||
func (a *App) deliverHostFile(name, picked string) (string, error) {
|
||||
sharedDir := a.vmSharedDir(name)
|
||||
if err := os.MkdirAll(sharedDir, 0o755); err != nil {
|
||||
return "", err
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// ListSnapshots returns all internal qcow2 restore points for a VM, newest first.
|
||||
func (a *App) ListSnapshots(name string) ([]reims.DiskSnapshot, error) {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
diskPath := resolveVMDiskPath(d)
|
||||
if diskPath == "" || !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") {
|
||||
return nil, nil
|
||||
}
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
snaps, err := reims.ListDiskSnapshots(a.baseCtx(), active.QemuImgPath(), env, diskPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sort.SliceStable(snaps, func(i, j int) bool {
|
||||
return snaps[i].CreatedAt > snaps[j].CreatedAt
|
||||
})
|
||||
return snaps, nil
|
||||
}
|
||||
|
||||
// CreateSnapshot creates a named offline restore point inside a stopped VM's qcow2 disk.
|
||||
func (a *App) CreateSnapshot(name, snapName string) error {
|
||||
return a.runSnapshotOp(name, "-c", snapName, "Created restore point")
|
||||
}
|
||||
|
||||
// RestoreSnapshot rolls back a stopped VM's qcow2 disk to the named restore point.
|
||||
func (a *App) RestoreSnapshot(name, snapName string) error {
|
||||
return a.runSnapshotOp(name, "-a", snapName, "Restored restore point")
|
||||
}
|
||||
|
||||
// DeleteSnapshot removes a named restore point from a stopped VM's qcow2 disk.
|
||||
func (a *App) DeleteSnapshot(name, snapName string) error {
|
||||
return a.runSnapshotOp(name, "-d", snapName, "Deleted restore point")
|
||||
}
|
||||
|
||||
func (a *App) runSnapshotOp(name, flag, snapName, verb string) error {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
ctx := a.baseCtx()
|
||||
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
return fmt.Errorf("stop %s before managing restore points", name)
|
||||
}
|
||||
diskPath := resolveVMDiskPath(d)
|
||||
if diskPath == "" {
|
||||
return fmt.Errorf("VM %s has no disk path", name)
|
||||
}
|
||||
if !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") {
|
||||
return fmt.Errorf("restore points are only supported on .qcow2 disks")
|
||||
}
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
if err := reims.RunDiskSnapshot(ctx, active.QemuImgPath(), env, flag, snapName, diskPath); err != nil {
|
||||
return err
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("%s %q", verb, strings.TrimSpace(snapName)))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const sshUserFileName = ".reims-go-ssh-user"
|
||||
|
||||
var safeSSHUserRe = regexp.MustCompile(`^[A-Za-z0-9._-]+$`)
|
||||
|
||||
// sshHostAlias returns a stable ~/.ssh/config Host alias for a VM.
|
||||
func sshHostAlias(vmName string) string {
|
||||
var b strings.Builder
|
||||
b.WriteString("reims-")
|
||||
for _, r := range strings.ToLower(strings.TrimSpace(vmName)) {
|
||||
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
|
||||
b.WriteRune(r)
|
||||
} else {
|
||||
b.WriteByte('-')
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// GetVMSSHUser returns the remembered SSH login user for a VM (empty if unset).
|
||||
func (a *App) GetVMSSHUser(name string) string {
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil || d.Directory == "" {
|
||||
return ""
|
||||
}
|
||||
b, err := os.ReadFile(filepath.Join(d.Directory, sshUserFileName))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
|
||||
// SetVMSSHUser persists the preferred SSH login user for a VM.
|
||||
func (a *App) SetVMSSHUser(name, user string) error {
|
||||
user = strings.TrimSpace(user)
|
||||
if user != "" && !safeSSHUserRe.MatchString(user) {
|
||||
return fmt.Errorf("invalid SSH username %q", user)
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.Directory == "" {
|
||||
return fmt.Errorf("VM directory not found")
|
||||
}
|
||||
p := filepath.Join(d.Directory, sshUserFileName)
|
||||
if user == "" {
|
||||
_ = os.Remove(p)
|
||||
return nil
|
||||
}
|
||||
return os.WriteFile(p, []byte(user+"\n"), 0o644)
|
||||
}
|
||||
|
||||
// OpenSSHTerminal launches an interactive Windows Terminal (falling back to
|
||||
// PowerShell) connected to the VM's forwarded SSH port.
|
||||
func (a *App) OpenSSHTerminal(name, user string) error {
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !d.Network || d.SSHPort <= 0 {
|
||||
return fmt.Errorf("SSH port forwarding is not enabled for %s", name)
|
||||
}
|
||||
user = strings.TrimSpace(user)
|
||||
if user == "" {
|
||||
user = a.GetVMSSHUser(name)
|
||||
} else if !safeSSHUserRe.MatchString(user) {
|
||||
return fmt.Errorf("invalid SSH username %q", user)
|
||||
} else {
|
||||
_ = a.SetVMSSHUser(name, user)
|
||||
}
|
||||
target := "127.0.0.1"
|
||||
if user != "" {
|
||||
target = user + "@127.0.0.1"
|
||||
}
|
||||
portStr := fmt.Sprintf("%d", d.SSHPort)
|
||||
var cmd *exec.Cmd
|
||||
if wt, err := exec.LookPath("wt.exe"); err == nil {
|
||||
cmd = exec.Command(wt, "new-tab", "--title", name, "ssh", "-p", portStr, target)
|
||||
} else if ps, err := exec.LookPath("powershell.exe"); err == nil {
|
||||
cmd = exec.Command(ps, "-NoExit", "-Command", fmt.Sprintf("ssh -p %s %s", portStr, target))
|
||||
} else {
|
||||
return fmt.Errorf("neither Windows Terminal (wt.exe) nor powershell.exe was found")
|
||||
}
|
||||
if err := cmd.Start(); err != nil {
|
||||
return fmt.Errorf("open SSH terminal: %w", err)
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Opened SSH terminal (%s -p %s)", target, portStr))
|
||||
return nil
|
||||
}
|
||||
|
||||
// WriteSSHConfig idempotently writes or updates a Host block for the VM in
|
||||
// ~/.ssh/config and returns the configured Host alias (e.g. "reims-macos-tahoe").
|
||||
func (a *App) WriteSSHConfig(name, user string) (string, error) {
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !d.Network || d.SSHPort <= 0 {
|
||||
return "", fmt.Errorf("SSH port forwarding is not enabled for %s", name)
|
||||
}
|
||||
user = strings.TrimSpace(user)
|
||||
if user == "" {
|
||||
user = a.GetVMSSHUser(name)
|
||||
} else if !safeSSHUserRe.MatchString(user) {
|
||||
return "", fmt.Errorf("invalid SSH username %q", user)
|
||||
} else {
|
||||
_ = a.SetVMSSHUser(name, user)
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("locate home directory: %w", err)
|
||||
}
|
||||
sshDir := filepath.Join(home, ".ssh")
|
||||
if err := os.MkdirAll(sshDir, 0o700); err != nil {
|
||||
return "", fmt.Errorf("create ~/.ssh: %w", err)
|
||||
}
|
||||
cfgPath := filepath.Join(sshDir, "config")
|
||||
alias := sshHostAlias(name)
|
||||
if err := upsertSSHConfigBlock(cfgPath, name, alias, d.SSHPort, user); err != nil {
|
||||
return "", err
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Updated ~/.ssh/config with Host %s (127.0.0.1:%d)", alias, d.SSHPort))
|
||||
return alias, nil
|
||||
}
|
||||
|
||||
// OpenVSCodeSSH ensures the VM's Host block is present in ~/.ssh/config and
|
||||
// launches VS Code (falling back to Cursor) in Remote-SSH mode.
|
||||
func (a *App) OpenVSCodeSSH(name, user string) error {
|
||||
alias, err := a.WriteSSHConfig(name, user)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var bin string
|
||||
for _, cand := range []string{"code.cmd", "code", "cursor.cmd", "cursor"} {
|
||||
if p, err := exec.LookPath(cand); err == nil {
|
||||
bin = p
|
||||
break
|
||||
}
|
||||
}
|
||||
if bin == "" {
|
||||
return fmt.Errorf("VS Code or Cursor CLI not found on PATH (Host %s has been written to ~/.ssh/config)", alias)
|
||||
}
|
||||
cmd := exec.Command(bin, "--remote", "ssh-remote+"+alias)
|
||||
if err := cmd.Start(); err != nil {
|
||||
return fmt.Errorf("launch editor Remote-SSH: %w", err)
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Launched %s Remote-SSH for %s", filepath.Base(bin), alias))
|
||||
return nil
|
||||
}
|
||||
|
||||
func upsertSSHConfigBlock(cfgPath, vmName, alias string, port int, user string) error {
|
||||
startMark := fmt.Sprintf("# >>> reims-go:%s >>>", vmName)
|
||||
endMark := fmt.Sprintf("# <<< reims-go:%s <<<", vmName)
|
||||
|
||||
var block strings.Builder
|
||||
block.WriteString(startMark + "\n")
|
||||
block.WriteString(fmt.Sprintf("Host %s\n", alias))
|
||||
block.WriteString(" HostName 127.0.0.1\n")
|
||||
block.WriteString(fmt.Sprintf(" Port %d\n", port))
|
||||
if user != "" {
|
||||
block.WriteString(fmt.Sprintf(" User %s\n", user))
|
||||
}
|
||||
block.WriteString(" StrictHostKeyChecking accept-new\n")
|
||||
block.WriteString(endMark + "\n")
|
||||
|
||||
existingBytes, err := os.ReadFile(cfgPath)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
content := strings.ReplaceAll(string(existingBytes), "\r\n", "\n")
|
||||
|
||||
var updated string
|
||||
if si := strings.Index(content, startMark); si >= 0 {
|
||||
if ei := strings.Index(content[si:], endMark); ei >= 0 {
|
||||
endPos := si + ei + len(endMark)
|
||||
if endPos < len(content) && content[endPos] == '\n' {
|
||||
endPos++
|
||||
}
|
||||
updated = content[:si] + block.String() + content[endPos:]
|
||||
}
|
||||
}
|
||||
if updated == "" {
|
||||
if content != "" && !strings.HasSuffix(content, "\n") {
|
||||
content += "\n"
|
||||
}
|
||||
if content != "" && !strings.HasSuffix(content, "\n\n") {
|
||||
content += "\n"
|
||||
}
|
||||
updated = content + block.String()
|
||||
}
|
||||
return os.WriteFile(cfgPath, []byte(updated), 0o600)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSSHHostAlias(t *testing.T) {
|
||||
if got := sshHostAlias("macos-tahoe"); got != "reims-macos-tahoe" {
|
||||
t.Fatalf("alias = %q", got)
|
||||
}
|
||||
if got := sshHostAlias("My Mac 26"); got != "reims-my-mac-26" {
|
||||
t.Fatalf("alias = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpsertSSHConfigBlockIdempotent(t *testing.T) {
|
||||
cfg := filepath.Join(t.TempDir(), "config")
|
||||
initial := "Host prod\n HostName 10.0.0.5\n"
|
||||
if err := os.WriteFile(cfg, []byte(initial), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := upsertSSHConfigBlock(cfg, "macos-tahoe", "reims-macos-tahoe", 2222, "alice"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b1, _ := os.ReadFile(cfg)
|
||||
s1 := string(b1)
|
||||
if !strings.Contains(s1, "Host prod") || !strings.Contains(s1, "Host reims-macos-tahoe") || !strings.Contains(s1, "Port 2222") || !strings.Contains(s1, "User alice") {
|
||||
t.Fatalf("unexpected first config:\n%s", s1)
|
||||
}
|
||||
|
||||
// Updating port and user must replace the block in place without duplicating it.
|
||||
if err := upsertSSHConfigBlock(cfg, "macos-tahoe", "reims-macos-tahoe", 2223, "bob"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b2, _ := os.ReadFile(cfg)
|
||||
s2 := string(b2)
|
||||
if strings.Count(s2, "Host reims-macos-tahoe") != 1 {
|
||||
t.Fatalf("expected single block, got:\n%s", s2)
|
||||
}
|
||||
if !strings.Contains(s2, "Port 2223") || !strings.Contains(s2, "User bob") || strings.Contains(s2, "User alice") {
|
||||
t.Fatalf("block not updated:\n%s", s2)
|
||||
}
|
||||
if !strings.Contains(s2, "Host prod") {
|
||||
t.Fatalf("existing user config lost:\n%s", s2)
|
||||
}
|
||||
}
|
||||
@@ -6,13 +6,17 @@ package app
|
||||
// show its last screen. Nothing here touches vm.toml or the guest.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"image/png"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
"github.com/Nwflower/reims-go/internal/thumb"
|
||||
@@ -53,6 +57,61 @@ func (a *App) GetVMThumbnail(name string) (VMThumbnail, error) {
|
||||
return readThumb(path, false), nil
|
||||
}
|
||||
|
||||
// FocusVMWindow brings a running VM's QEMU display window to the foreground,
|
||||
// restoring it first if minimized (docs/ui-redesign.md §6 B5).
|
||||
func (a *App) FocusVMWindow(name string) error {
|
||||
vm, ok := a.polledVM(name)
|
||||
if !ok || vm.State != "running" || vm.PID == nil || *vm.PID <= 0 {
|
||||
return fmt.Errorf("VM %s is not running", name)
|
||||
}
|
||||
if !host.FocusProcessWindow(uint32(*vm.PID)) {
|
||||
return fmt.Errorf("could not locate display window for %s", name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CopyVMScreenshot captures a full-resolution frame from a running VM over QMP
|
||||
// and writes it as a PNG/DIB image to the Windows clipboard.
|
||||
func (a *App) CopyVMScreenshot(name string) error {
|
||||
vm, ok := a.polledVM(name)
|
||||
if !ok || vm.State != "running" || vm.Dir == "" {
|
||||
return fmt.Errorf("VM %s is not running", name)
|
||||
}
|
||||
l, _ := thumbLocks.LoadOrStore(name, &sync.Mutex{})
|
||||
mu := l.(*sync.Mutex)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
a.mu.Lock()
|
||||
tmp := a.cfg.TempDir()
|
||||
a.mu.Unlock()
|
||||
if err := os.MkdirAll(tmp, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
raw := filepath.Join(tmp, "screenshot-"+name)
|
||||
defer os.Remove(raw)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
format, err := qmp.ScreendumpVM(ctx, vm.Dir, raw)
|
||||
if err != nil {
|
||||
return fmt.Errorf("capture screen: %w", err)
|
||||
}
|
||||
img, err := thumb.Load(raw, format)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode screen: %w", err)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, img); err != nil {
|
||||
return fmt.Errorf("encode PNG: %w", err)
|
||||
}
|
||||
if err := (guesttools.OSClipboard{}).WritePNG(buf.Bytes()); err != nil {
|
||||
return fmt.Errorf("copy image to clipboard: %w", err)
|
||||
}
|
||||
a.emitLog(name, "Copied VM screenshot to clipboard")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) captureThumb(name, path string) (VMThumbnail, bool) {
|
||||
typing.mu.Lock()
|
||||
busy := typing.busy[name]
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
// vmMonitors holds per-VM background log tailers & boot/install heartbeats.
|
||||
@@ -364,24 +365,13 @@ func (a *App) emitStartSummary(name string, detail reims.VMDetail, rep host.Repo
|
||||
case strings.Contains(lowExtra, "kernel-irqchip=on"):
|
||||
irqMode = "on"
|
||||
}
|
||||
plan := host.SelectSafeAffinity(rep, detail.CPUs)
|
||||
pinStr := vmstart.AffinitySummary(loc, rep, detail.Directory, pinPCores, detail.CPUs)
|
||||
if loc == i18n.ZhCN {
|
||||
coldStr := "关闭"
|
||||
if qmpAddr != "" {
|
||||
coldStr = "开启"
|
||||
}
|
||||
pinStr := "关"
|
||||
if pinPCores && rep.HasHybridCores {
|
||||
switch plan.Mode {
|
||||
case "pcores":
|
||||
pinStr = fmt.Sprintf("开(%dP/%d线程)", plan.CoreCount, plan.ThreadCount)
|
||||
case "non_lpe":
|
||||
pinStr = fmt.Sprintf("P+E(%d核/%d线程,避开LP-E)", plan.CoreCount, plan.ThreadCount)
|
||||
default:
|
||||
pinStr = fmt.Sprintf("自动跳过(%d核≥%dP线程)", detail.CPUs, plan.PThreads)
|
||||
}
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("[启动] 运行时 %s · %d 核 / %s(可用提交内存 %.1f GB)· 图形 %s · 磁盘 %s · irqchip=%s · 绑P核=%s · Win10冷重启=%s",
|
||||
a.emitLog(name, fmt.Sprintf("[启动] 运行时 %s · %d 核 / %s(可用提交内存 %.1f GB)· 图形 %s · 磁盘 %s · irqchip=%s · 核心映射=%s · Win10冷重启=%s",
|
||||
rtCommit, detail.CPUs, detail.Memory, rep.CommitAvailGB, detail.Graphics, strings.ToUpper(detail.DiskController), irqMode, pinStr, coldStr))
|
||||
return
|
||||
}
|
||||
@@ -389,17 +379,6 @@ func (a *App) emitStartSummary(name string, detail reims.VMDetail, rep host.Repo
|
||||
if qmpAddr != "" {
|
||||
coldStr = "on"
|
||||
}
|
||||
pinStr := "off"
|
||||
if pinPCores && rep.HasHybridCores {
|
||||
switch plan.Mode {
|
||||
case "pcores":
|
||||
pinStr = fmt.Sprintf("on(%dP/%dT)", plan.CoreCount, plan.ThreadCount)
|
||||
case "non_lpe":
|
||||
pinStr = fmt.Sprintf("P+E(%dC/%dT,no-LPE)", plan.CoreCount, plan.ThreadCount)
|
||||
default:
|
||||
pinStr = fmt.Sprintf("skipped(%dvCPU>=%dPT)", detail.CPUs, plan.PThreads)
|
||||
}
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("[start] runtime %s · %d vCPU / %s (commit free %.1f GB) · graphics %s · disk %s · irqchip=%s · P-core=%s · Win10-cold-reboot=%s",
|
||||
a.emitLog(name, fmt.Sprintf("[start] runtime %s · %d vCPU / %s (commit free %.1f GB) · graphics %s · disk %s · irqchip=%s · affinity=%s · Win10-cold-reboot=%s",
|
||||
rtCommit, detail.CPUs, detail.Memory, rep.CommitAvailGB, detail.Graphics, strings.ToUpper(detail.DiskController), irqMode, pinStr, coldStr))
|
||||
}
|
||||
@@ -51,16 +51,19 @@ func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name s
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if !cfg.AutoPinPCores || !rep.HasHybridCores || rep.PCoreMask == 0 {
|
||||
return nil
|
||||
}
|
||||
vms, err := prep.Client.List(ctx)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
for _, vm := range vms {
|
||||
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
|
||||
fmt.Fprintln(os.Stderr, vmstart.PinQEMU(cfg.Locale, rep, *vm.PID, d.CPUs))
|
||||
vmDir := vm.Dir
|
||||
if vmDir == "" {
|
||||
vmDir = d.Directory
|
||||
}
|
||||
if line, _ := vmstart.ApplyVMAffinity(cfg.Locale, rep, vmDir, cfg.AutoPinPCores, *vm.PID, d.CPUs, false); line != "" {
|
||||
fmt.Fprintln(os.Stderr, line)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package reims
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// DiskSnapshot describes one internal qcow2 snapshot returned by `qemu-img info --output=json`.
|
||||
type DiskSnapshot struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
CreatedAt int64 `json:"created_at"` // Unix seconds
|
||||
VMStateBytes int64 `json:"vm_state_bytes"` // 0 for offline disk-only snapshots
|
||||
}
|
||||
|
||||
type qemuImgInfoJSON struct {
|
||||
Format string `json:"format"`
|
||||
Snapshots []struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
VMStateSize int64 `json:"vm-state-size"`
|
||||
DateSec int64 `json:"date-sec"`
|
||||
} `json:"snapshots"`
|
||||
}
|
||||
|
||||
// ParseDiskSnapshotsJSON parses `qemu-img info --output=json` output.
|
||||
func ParseDiskSnapshotsJSON(raw []byte) (string, []DiskSnapshot, error) {
|
||||
var info qemuImgInfoJSON
|
||||
if err := json.Unmarshal(raw, &info); err != nil {
|
||||
return "", nil, fmt.Errorf("parse qemu-img info json: %w", err)
|
||||
}
|
||||
out := make([]DiskSnapshot, 0, len(info.Snapshots))
|
||||
for _, s := range info.Snapshots {
|
||||
out = append(out, DiskSnapshot{
|
||||
ID: s.ID,
|
||||
Name: s.Name,
|
||||
CreatedAt: s.DateSec,
|
||||
VMStateBytes: s.VMStateSize,
|
||||
})
|
||||
}
|
||||
return strings.ToLower(strings.TrimSpace(info.Format)), out, nil
|
||||
}
|
||||
|
||||
// ListDiskSnapshots lists internal qcow2 snapshots via `qemu-img info --output=json`.
|
||||
func ListDiskSnapshots(ctx context.Context, qemuImgPath string, env []string, diskPath string) ([]DiskSnapshot, error) {
|
||||
if _, err := os.Stat(qemuImgPath); err != nil {
|
||||
return nil, fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, qemuImgPath, "info", "--output=json", diskPath)
|
||||
configureCmd(cmd)
|
||||
cmd.Env = env
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
msg := strings.TrimSpace(stderr.String())
|
||||
if msg != "" {
|
||||
return nil, fmt.Errorf("qemu-img info %s: %s", filepath.Base(diskPath), msg)
|
||||
}
|
||||
return nil, fmt.Errorf("qemu-img info %s: %w", filepath.Base(diskPath), err)
|
||||
}
|
||||
format, snaps, err := ParseDiskSnapshotsJSON(stdout.Bytes())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if format != "qcow2" {
|
||||
return nil, nil
|
||||
}
|
||||
return snaps, nil
|
||||
}
|
||||
|
||||
// ValidateSnapshotName checks that a snapshot tag is safe for `qemu-img snapshot`.
|
||||
func ValidateSnapshotName(snapName string) (string, error) {
|
||||
snapName = strings.TrimSpace(snapName)
|
||||
if snapName == "" {
|
||||
return "", fmt.Errorf("snapshot name is required")
|
||||
}
|
||||
if len([]rune(snapName)) > 64 {
|
||||
return "", fmt.Errorf("snapshot name must be 64 characters or fewer")
|
||||
}
|
||||
for _, r := range snapName {
|
||||
if r < 0x20 || r == 0x7f || r == '"' || r == '\'' || r == '`' || r == '\\' {
|
||||
return "", fmt.Errorf("snapshot name contains invalid characters")
|
||||
}
|
||||
}
|
||||
return snapName, nil
|
||||
}
|
||||
|
||||
// RunDiskSnapshot executes `qemu-img snapshot <flag> <snapName> <diskPath>`
|
||||
// where flag is "-c" (create), "-a" (apply/restore), or "-d" (delete).
|
||||
func RunDiskSnapshot(ctx context.Context, qemuImgPath string, env []string, flag, snapName, diskPath string) error {
|
||||
if _, err := os.Stat(qemuImgPath); err != nil {
|
||||
return fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
|
||||
}
|
||||
snapName, err := ValidateSnapshotName(snapName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, qemuImgPath, "snapshot", flag, snapName, diskPath)
|
||||
configureCmd(cmd)
|
||||
cmd.Env = env
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
msg := strings.TrimSpace(stderr.String())
|
||||
if msg != "" {
|
||||
return fmt.Errorf("qemu-img snapshot %s %q: %s", flag, snapName, msg)
|
||||
}
|
||||
return fmt.Errorf("qemu-img snapshot %s %q: %w", flag, snapName, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -4,3 +4,6 @@ package host
|
||||
|
||||
// ForegroundPID is not implemented off Windows and always reports no owner.
|
||||
func ForegroundPID() uint32 { return 0 }
|
||||
|
||||
// FocusProcessWindow is not implemented off Windows.
|
||||
func FocusProcessWindow(uint32) bool { return false }
|
||||
@@ -2,7 +2,22 @@
|
||||
|
||||
package host
|
||||
|
||||
import "unsafe"
|
||||
import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var (
|
||||
procEnumWindows = user32.NewProc("EnumWindows")
|
||||
procIsWindowVisible = user32.NewProc("IsWindowVisible")
|
||||
procIsIconic = user32.NewProc("IsIconic")
|
||||
procShowWindow = user32.NewProc("ShowWindow")
|
||||
procSetForegroundWin = user32.NewProc("SetForegroundWindow")
|
||||
procBringWindowToTop = user32.NewProc("BringWindowToTop")
|
||||
procAttachThreadInput = user32.NewProc("AttachThreadInput")
|
||||
)
|
||||
|
||||
const swRestore = 9
|
||||
|
||||
// ForegroundPID returns the process that owns the foreground window, or 0
|
||||
// when there is none (locked screen, desktop focused).
|
||||
@@ -15,3 +30,61 @@ func ForegroundPID() uint32 {
|
||||
_, _, _ = procGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&pid)))
|
||||
return pid
|
||||
}
|
||||
|
||||
// FocusProcessWindow finds the primary visible top-level window belonging to
|
||||
// pid, restores it if minimized, and brings it to the foreground.
|
||||
func FocusProcessWindow(pid uint32) bool {
|
||||
if pid == 0 {
|
||||
return false
|
||||
}
|
||||
var found uintptr
|
||||
cb := syscall.NewCallback(func(hwnd uintptr, _ uintptr) uintptr {
|
||||
vis, _, _ := procIsWindowVisible.Call(hwnd)
|
||||
if vis == 0 {
|
||||
return 1
|
||||
}
|
||||
var winPID uint32
|
||||
_, _, _ = procGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&winPID)))
|
||||
if winPID == pid {
|
||||
found = hwnd
|
||||
return 0
|
||||
}
|
||||
return 1
|
||||
})
|
||||
_, _, _ = procEnumWindows.Call(cb, 0)
|
||||
if found == 0 {
|
||||
return false
|
||||
}
|
||||
iconic, _, _ := procIsIconic.Call(found)
|
||||
if iconic != 0 {
|
||||
_, _, _ = procShowWindow.Call(found, swRestore)
|
||||
}
|
||||
fgHwnd, _, _ := procGetForegroundWindow.Call()
|
||||
curTid, _, _ := procGetCurrentThreadId.Call()
|
||||
var fgTid uintptr
|
||||
if fgHwnd != 0 {
|
||||
fgTid, _, _ = procGetWindowThreadProcessId.Call(fgHwnd, 0)
|
||||
}
|
||||
targetTid, _, _ := procGetWindowThreadProcessId.Call(found, 0)
|
||||
attachedFg := false
|
||||
attachedTarget := false
|
||||
if fgTid != 0 && fgTid != curTid {
|
||||
if r, _, _ := procAttachThreadInput.Call(curTid, fgTid, 1); r != 0 {
|
||||
attachedFg = true
|
||||
}
|
||||
}
|
||||
if targetTid != 0 && targetTid != curTid && targetTid != fgTid {
|
||||
if r, _, _ := procAttachThreadInput.Call(curTid, targetTid, 1); r != 0 {
|
||||
attachedTarget = true
|
||||
}
|
||||
}
|
||||
_, _, _ = procBringWindowToTop.Call(found)
|
||||
_, _, _ = procSetForegroundWin.Call(found)
|
||||
if attachedTarget {
|
||||
_, _, _ = procAttachThreadInput.Call(curTid, targetTid, 0)
|
||||
}
|
||||
if attachedFg {
|
||||
_, _, _ = procAttachThreadInput.Call(curTid, fgTid, 0)
|
||||
}
|
||||
return true
|
||||
}
|
||||
+87
-15
@@ -34,22 +34,30 @@ type WHPXCapabilities struct {
|
||||
NestedVirtProbeError string `json:"nested_virt_probe_error,omitempty"`
|
||||
}
|
||||
|
||||
type LogicalCPUInfo struct {
|
||||
Index int `json:"index"`
|
||||
CoreIndex int `json:"core_index"`
|
||||
Tier string `json:"tier"` // "p" | "e" | "lpe" | "standard"
|
||||
SMT bool `json:"smt"`
|
||||
}
|
||||
|
||||
type Report struct {
|
||||
OS string `json:"os"`
|
||||
Arch string `json:"arch"`
|
||||
LogicalCPUs int `json:"logical_cpus"`
|
||||
PhysicalCores int `json:"physical_cores"`
|
||||
HasHybridCores bool `json:"has_hybrid_cores"`
|
||||
PCoreCount int `json:"p_core_count"`
|
||||
ECoreCount int `json:"e_core_count"`
|
||||
LPECoreCount int `json:"lpe_core_count,omitempty"`
|
||||
PCoreMask uint64 `json:"p_core_mask"`
|
||||
PCoreMaskHex string `json:"p_core_mask_hex"`
|
||||
PCoreLogicalCPUs []int `json:"p_core_logical_cpus,omitempty"`
|
||||
ECoreLogicalCPUs []int `json:"e_core_logical_cpus,omitempty"`
|
||||
NonLPEMask uint64 `json:"non_lpe_mask,omitempty"`
|
||||
NonLPEMaskHex string `json:"non_lpe_mask_hex,omitempty"`
|
||||
NonLPELogicalCPUs []int `json:"non_lpe_logical_cpus,omitempty"`
|
||||
OS string `json:"os"`
|
||||
Arch string `json:"arch"`
|
||||
LogicalCPUs int `json:"logical_cpus"`
|
||||
PhysicalCores int `json:"physical_cores"`
|
||||
HasHybridCores bool `json:"has_hybrid_cores"`
|
||||
PCoreCount int `json:"p_core_count"`
|
||||
ECoreCount int `json:"e_core_count"`
|
||||
LPECoreCount int `json:"lpe_core_count,omitempty"`
|
||||
PCoreMask uint64 `json:"p_core_mask"`
|
||||
PCoreMaskHex string `json:"p_core_mask_hex"`
|
||||
PCoreLogicalCPUs []int `json:"p_core_logical_cpus,omitempty"`
|
||||
ECoreLogicalCPUs []int `json:"e_core_logical_cpus,omitempty"`
|
||||
NonLPEMask uint64 `json:"non_lpe_mask,omitempty"`
|
||||
NonLPEMaskHex string `json:"non_lpe_mask_hex,omitempty"`
|
||||
NonLPELogicalCPUs []int `json:"non_lpe_logical_cpus,omitempty"`
|
||||
CPUTopology []LogicalCPUInfo `json:"cpu_topology,omitempty"`
|
||||
TotalRAMGB float64 `json:"total_ram_gb"`
|
||||
AvailRAMGB float64 `json:"avail_ram_gb"`
|
||||
MemoryLoadPct int `json:"memory_load_pct"`
|
||||
@@ -120,3 +128,67 @@ func PickRecommendedGPU(gpus []GPUInfo) *GPUInfo {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AllCPUsMask returns the 64-bit affinity mask covering logical CPUs 0..n-1
|
||||
// (capped at 64 bits, matching Win32 SetProcessAffinityMask group 0).
|
||||
func AllCPUsMask(logicalCPUs int) uint64 {
|
||||
if logicalCPUs <= 0 {
|
||||
return 0
|
||||
}
|
||||
if logicalCPUs >= 64 {
|
||||
return ^uint64(0)
|
||||
}
|
||||
return (uint64(1) << uint(logicalCPUs)) - 1
|
||||
}
|
||||
|
||||
// CPUsToMask encodes a list of logical CPU indices (0..maxCPUs-1, max 63) into
|
||||
// an affinity bitmask and returns the normalized sorted CPU list alongside it.
|
||||
func CPUsToMask(cpus []int, maxCPUs int) (uint64, []int) {
|
||||
limit := maxCPUs
|
||||
if limit <= 0 || limit > 64 {
|
||||
limit = 64
|
||||
}
|
||||
var mask uint64
|
||||
for _, idx := range cpus {
|
||||
if idx >= 0 && idx < limit {
|
||||
mask |= uint64(1) << uint(idx)
|
||||
}
|
||||
}
|
||||
return mask, MaskToCPUs(mask, limit)
|
||||
}
|
||||
|
||||
// MaskToCPUs decodes an affinity bitmask into sorted logical CPU indices.
|
||||
func MaskToCPUs(mask uint64, maxCPUs int) []int {
|
||||
limit := maxCPUs
|
||||
if limit <= 0 || limit > 64 {
|
||||
limit = 64
|
||||
}
|
||||
var out []int
|
||||
for i := 0; i < limit; i++ {
|
||||
if mask&(uint64(1)<<uint(i)) != 0 {
|
||||
out = append(out, i)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// DefaultCPUTopology constructs a homogeneous fallback topology when detailed
|
||||
// OS processor-core probing is unavailable.
|
||||
func DefaultCPUTopology(logicalCPUs int) []LogicalCPUInfo {
|
||||
limit := logicalCPUs
|
||||
if limit < 0 {
|
||||
limit = 0
|
||||
}
|
||||
if limit > 64 {
|
||||
limit = 64
|
||||
}
|
||||
out := make([]LogicalCPUInfo, limit)
|
||||
for i := 0; i < limit; i++ {
|
||||
out[i] = LogicalCPUInfo{
|
||||
Index: i,
|
||||
CoreIndex: i,
|
||||
Tier: "standard",
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -14,6 +14,7 @@ func Inspect(dataRoot string) Report {
|
||||
OS: runtime.GOOS,
|
||||
Arch: runtime.GOARCH,
|
||||
LogicalCPUs: runtime.NumCPU(),
|
||||
CPUTopology: DefaultCPUTopology(runtime.NumCPU()),
|
||||
DataRoot: dataRoot,
|
||||
WHPX: WHPXUnsupported,
|
||||
RecommendedResolution: rec,
|
||||
@@ -23,7 +24,19 @@ func Inspect(dataRoot string) Report {
|
||||
}
|
||||
|
||||
func PinProcessToPCores(pid uint32, mask uint64) error {
|
||||
return fmt.Errorf("P-core affinity pinning is only supported on Windows (current OS: %s)", runtime.GOOS)
|
||||
return SetProcessAffinityMask(pid, mask)
|
||||
}
|
||||
|
||||
func SetProcessAffinityMask(pid uint32, mask uint64) error {
|
||||
return fmt.Errorf("process CPU affinity is only supported on Windows (current OS: %s)", runtime.GOOS)
|
||||
}
|
||||
|
||||
func GetProcessAffinityMask(pid uint32) (uint64, uint64, error) {
|
||||
return 0, 0, fmt.Errorf("process CPU affinity is only supported on Windows (current OS: %s)", runtime.GOOS)
|
||||
}
|
||||
|
||||
func DisableProcessPowerThrottling(pid uint32) error {
|
||||
return fmt.Errorf("process power throttling control is only supported on Windows (current OS: %s)", runtime.GOOS)
|
||||
}
|
||||
|
||||
func EnableWHPXElevated() error {
|
||||
|
||||
@@ -22,3 +22,16 @@ func TestGPUClassificationAndRecommendation(t *testing.T) {
|
||||
t.Fatalf("expected NVIDIA discrete GPU to be recommended, got %#v", rec)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAffinityMaskHelpers(t *testing.T) {
|
||||
if got := AllCPUsMask(8); got != 0xFF {
|
||||
t.Fatalf("AllCPUsMask(8) = 0x%X, want 0xFF", got)
|
||||
}
|
||||
if got := AllCPUsMask(64); got != ^uint64(0) {
|
||||
t.Fatalf("AllCPUsMask(64) = 0x%X, want all-ones", got)
|
||||
}
|
||||
mask, cpus := CPUsToMask([]int{4, 1, 4, -1, 16}, 16)
|
||||
if mask != 0x12 || len(cpus) != 2 || cpus[0] != 1 || cpus[1] != 4 {
|
||||
t.Fatalf("CPUsToMask = (0x%X, %v), want (0x12, [1 4])", mask, cpus)
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,10 @@ package host
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"math/bits"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
@@ -20,6 +22,8 @@ var (
|
||||
procDeviceIoControl = kernel32.NewProc("DeviceIoControl")
|
||||
procOpenProcess = kernel32.NewProc("OpenProcess")
|
||||
procSetProcessAffinityMask = kernel32.NewProc("SetProcessAffinityMask")
|
||||
procGetProcessAffinityMask = kernel32.NewProc("GetProcessAffinityMask")
|
||||
procSetProcessInformation = kernel32.NewProc("SetProcessInformation")
|
||||
procCloseHandle = kernel32.NewProc("CloseHandle")
|
||||
|
||||
advapi32 = syscall.NewLazyDLL("advapi32.dll")
|
||||
@@ -37,8 +41,12 @@ const (
|
||||
regSZ = 1
|
||||
regExpandSZ = 2
|
||||
regMultiSZ = 7
|
||||
processSetInformation = 0x0200
|
||||
whvCapHypervisorPresent = 0x00000001
|
||||
processSetInformation = 0x0200
|
||||
processQueryLimitedInformation = 0x1000
|
||||
processPowerThrottlingClass = 4
|
||||
powerThrottlingCurrentVersion = 1
|
||||
powerThrottlingExecutionSpeed = 0x1
|
||||
whvCapHypervisorPresent = 0x00000001
|
||||
)
|
||||
|
||||
type memoryStatusEx struct {
|
||||
@@ -84,6 +92,10 @@ func Inspect(dataRoot string) Report {
|
||||
rep.NonLPEMaskHex = fmt.Sprintf("0x%X", topo.nonLPEMask)
|
||||
rep.NonLPELogicalCPUs = topo.nonLPELPs
|
||||
}
|
||||
rep.CPUTopology = topo.cpus
|
||||
}
|
||||
if len(rep.CPUTopology) == 0 {
|
||||
rep.CPUTopology = DefaultCPUTopology(rep.LogicalCPUs)
|
||||
}
|
||||
if totalGB, availGB, ok := probeMemoryGB(); ok {
|
||||
rep.TotalRAMGB = totalGB
|
||||
@@ -110,8 +122,13 @@ func Inspect(dataRoot string) Report {
|
||||
return rep
|
||||
}
|
||||
|
||||
// PinProcessToPCores restricts the given PID's affinity mask to P-cores.
|
||||
// PinProcessToPCores restricts the given PID's affinity mask to the given bitmask.
|
||||
func PinProcessToPCores(pid uint32, mask uint64) error {
|
||||
return SetProcessAffinityMask(pid, mask)
|
||||
}
|
||||
|
||||
// SetProcessAffinityMask sets the Win32 processor affinity mask for pid.
|
||||
func SetProcessAffinityMask(pid uint32, mask uint64) error {
|
||||
if mask == 0 {
|
||||
return fmt.Errorf("invalid affinity mask 0")
|
||||
}
|
||||
@@ -127,6 +144,60 @@ func PinProcessToPCores(pid uint32, mask uint64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetProcessAffinityMask reads the current process and system affinity masks for pid.
|
||||
func GetProcessAffinityMask(pid uint32) (uint64, uint64, error) {
|
||||
h, _, err := procOpenProcess.Call(uintptr(processQueryLimitedInformation), 0, uintptr(pid))
|
||||
if h == 0 {
|
||||
return 0, 0, fmt.Errorf("OpenProcess(%d): %w", pid, err)
|
||||
}
|
||||
defer procCloseHandle.Call(h)
|
||||
var procMask, sysMask uintptr
|
||||
r, _, err := procGetProcessAffinityMask.Call(
|
||||
h,
|
||||
uintptr(unsafe.Pointer(&procMask)),
|
||||
uintptr(unsafe.Pointer(&sysMask)),
|
||||
)
|
||||
if r == 0 {
|
||||
return 0, 0, fmt.Errorf("GetProcessAffinityMask(%d): %w", pid, err)
|
||||
}
|
||||
return uint64(procMask), uint64(sysMask), nil
|
||||
}
|
||||
|
||||
type processPowerThrottlingState struct {
|
||||
Version uint32
|
||||
ControlMask uint32
|
||||
StateMask uint32
|
||||
}
|
||||
|
||||
// DisableProcessPowerThrottling opts pid out of Windows EcoQoS execution-speed
|
||||
// power throttling so background / unfocused QEMU threads are not parked onto
|
||||
// efficiency or LP-E cores by the scheduler.
|
||||
func DisableProcessPowerThrottling(pid uint32) error {
|
||||
if err := procSetProcessInformation.Find(); err != nil {
|
||||
return err
|
||||
}
|
||||
h, _, err := procOpenProcess.Call(uintptr(processSetInformation), 0, uintptr(pid))
|
||||
if h == 0 {
|
||||
return fmt.Errorf("OpenProcess(%d): %w", pid, err)
|
||||
}
|
||||
defer procCloseHandle.Call(h)
|
||||
state := processPowerThrottlingState{
|
||||
Version: powerThrottlingCurrentVersion,
|
||||
ControlMask: powerThrottlingExecutionSpeed,
|
||||
StateMask: 0,
|
||||
}
|
||||
r, _, err := procSetProcessInformation.Call(
|
||||
h,
|
||||
uintptr(processPowerThrottlingClass),
|
||||
uintptr(unsafe.Pointer(&state)),
|
||||
uintptr(unsafe.Sizeof(state)),
|
||||
)
|
||||
if r == 0 {
|
||||
return fmt.Errorf("SetProcessInformation(ProcessPowerThrottling, %d): %w", pid, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnableWHPXElevated invokes a standard Windows UAC prompt to enable Windows Hypervisor Platform.
|
||||
func EnableWHPXElevated() error {
|
||||
verb, _ := syscall.UTF16PtrFromString("runas")
|
||||
@@ -194,6 +265,7 @@ type hybridTopology struct {
|
||||
pLPs []int
|
||||
eLPs []int
|
||||
nonLPELPs []int
|
||||
cpus []LogicalCPUInfo
|
||||
}
|
||||
|
||||
func probeHybridTopology() (topo hybridTopology, ok bool) {
|
||||
@@ -240,22 +312,43 @@ func probeHybridTopology() (topo hybridTopology, ok bool) {
|
||||
return
|
||||
}
|
||||
hasThreeTiers := len(effSet) >= 3
|
||||
isHybrid := len(effSet) >= 2
|
||||
topo.phys = len(cores)
|
||||
var eMask uint64
|
||||
for _, c := range cores {
|
||||
for coreIdx, c := range cores {
|
||||
tier := "standard"
|
||||
switch {
|
||||
case c.eff == maxEff:
|
||||
topo.pCount++
|
||||
topo.pMask |= c.mask
|
||||
topo.nonLPEMask |= c.mask
|
||||
if isHybrid {
|
||||
tier = "p"
|
||||
}
|
||||
case hasThreeTiers && c.eff == minEff:
|
||||
topo.lpeCount++
|
||||
tier = "lpe"
|
||||
default:
|
||||
topo.eCount++
|
||||
eMask |= c.mask
|
||||
topo.nonLPEMask |= c.mask
|
||||
tier = "e"
|
||||
}
|
||||
smt := bits.OnesCount64(c.mask) > 1
|
||||
for i := 0; i < 64; i++ {
|
||||
if c.mask&(uint64(1)<<uint(i)) != 0 {
|
||||
topo.cpus = append(topo.cpus, LogicalCPUInfo{
|
||||
Index: i,
|
||||
CoreIndex: coreIdx,
|
||||
Tier: tier,
|
||||
SMT: smt,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Slice(topo.cpus, func(i, j int) bool {
|
||||
return topo.cpus[i].Index < topo.cpus[j].Index
|
||||
})
|
||||
if !hasThreeTiers {
|
||||
topo.nonLPEMask = 0
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
//go:build windows
|
||||
|
||||
package host
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWindowsProcessAffinityAndTopology(t *testing.T) {
|
||||
pid := uint32(os.Getpid())
|
||||
procMask, sysMask, err := GetProcessAffinityMask(pid)
|
||||
if err != nil {
|
||||
t.Fatalf("GetProcessAffinityMask(self=%d): %v", pid, err)
|
||||
}
|
||||
if procMask == 0 || sysMask == 0 {
|
||||
t.Fatalf("unexpected zero masks: proc=0x%X sys=0x%X", procMask, sysMask)
|
||||
}
|
||||
if procMask&sysMask != procMask {
|
||||
t.Fatalf("procMask 0x%X is not subset of sysMask 0x%X", procMask, sysMask)
|
||||
}
|
||||
|
||||
rep := Inspect(t.TempDir())
|
||||
if len(rep.CPUTopology) == 0 {
|
||||
t.Fatalf("expected non-empty CPUTopology on Windows")
|
||||
}
|
||||
for i, c := range rep.CPUTopology {
|
||||
if i > 0 && c.Index <= rep.CPUTopology[i-1].Index {
|
||||
t.Fatalf("CPUTopology not strictly sorted at %d: %+v", i, rep.CPUTopology)
|
||||
}
|
||||
if c.Tier == "" {
|
||||
t.Fatalf("empty tier for CPU %d", c.Index)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
package vmstart
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/bits"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
)
|
||||
|
||||
const affinityConfigFile = ".reims-go-affinity.json"
|
||||
|
||||
// AffinityMode selects how a VM's QEMU process maps onto host logical CPUs.
|
||||
type AffinityMode string
|
||||
|
||||
const (
|
||||
AffinityAuto AffinityMode = "auto"
|
||||
AffinityAll AffinityMode = "all"
|
||||
AffinityPCores AffinityMode = "pcores"
|
||||
AffinityNonLPE AffinityMode = "non_lpe"
|
||||
AffinityCustom AffinityMode = "custom"
|
||||
)
|
||||
|
||||
// VMAffinityConfig is persisted per VM in <vmDir>/.reims-go-affinity.json
|
||||
// without modifying upstream vm.toml.
|
||||
type VMAffinityConfig struct {
|
||||
Mode AffinityMode `json:"mode"`
|
||||
CPUs []int `json:"cpus,omitempty"`
|
||||
DisableEcoQoS *bool `json:"disable_eco_qos,omitempty"`
|
||||
}
|
||||
|
||||
// ShouldDisableEcoQoS reports whether Windows EcoQoS power throttling should
|
||||
// be turned off for the VM's QEMU process. Defaults to true.
|
||||
func (c VMAffinityConfig) ShouldDisableEcoQoS() bool {
|
||||
if c.DisableEcoQoS == nil {
|
||||
return true
|
||||
}
|
||||
return *c.DisableEcoQoS
|
||||
}
|
||||
|
||||
// NormalizeAffinityMode maps empty or unknown mode values to AffinityAuto.
|
||||
func NormalizeAffinityMode(m AffinityMode) AffinityMode {
|
||||
switch AffinityMode(strings.ToLower(strings.TrimSpace(string(m)))) {
|
||||
case AffinityAll:
|
||||
return AffinityAll
|
||||
case AffinityPCores:
|
||||
return AffinityPCores
|
||||
case AffinityNonLPE:
|
||||
return AffinityNonLPE
|
||||
case AffinityCustom:
|
||||
return AffinityCustom
|
||||
default:
|
||||
return AffinityAuto
|
||||
}
|
||||
}
|
||||
|
||||
// DefaultVMAffinityConfig returns the default per-VM affinity preference.
|
||||
func DefaultVMAffinityConfig() VMAffinityConfig {
|
||||
eco := true
|
||||
return VMAffinityConfig{
|
||||
Mode: AffinityAuto,
|
||||
DisableEcoQoS: &eco,
|
||||
}
|
||||
}
|
||||
|
||||
// ReadVMAffinity loads <vmDir>/.reims-go-affinity.json, returning defaults when
|
||||
// absent or unreadable.
|
||||
func ReadVMAffinity(vmDir string) VMAffinityConfig {
|
||||
def := DefaultVMAffinityConfig()
|
||||
if strings.TrimSpace(vmDir) == "" {
|
||||
return def
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(vmDir, affinityConfigFile))
|
||||
if err != nil {
|
||||
return def
|
||||
}
|
||||
var cfg VMAffinityConfig
|
||||
if json.Unmarshal(raw, &cfg) != nil {
|
||||
return def
|
||||
}
|
||||
cfg.Mode = NormalizeAffinityMode(cfg.Mode)
|
||||
if cfg.Mode == AffinityCustom {
|
||||
_, cfg.CPUs = host.CPUsToMask(cfg.CPUs, 64)
|
||||
} else {
|
||||
cfg.CPUs = nil
|
||||
}
|
||||
if cfg.DisableEcoQoS == nil {
|
||||
eco := true
|
||||
cfg.DisableEcoQoS = &eco
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
// HasSavedVMAffinity reports whether <vmDir>/.reims-go-affinity.json exists.
|
||||
func HasSavedVMAffinity(vmDir string) bool {
|
||||
if strings.TrimSpace(vmDir) == "" {
|
||||
return false
|
||||
}
|
||||
_, err := os.Stat(filepath.Join(vmDir, affinityConfigFile))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// SaveVMAffinity validates and atomically writes <vmDir>/.reims-go-affinity.json.
|
||||
func SaveVMAffinity(vmDir string, cfg VMAffinityConfig, maxCPUs int) (VMAffinityConfig, error) {
|
||||
if strings.TrimSpace(vmDir) == "" {
|
||||
return VMAffinityConfig{}, errors.New("VM directory is empty")
|
||||
}
|
||||
cfg.Mode = NormalizeAffinityMode(cfg.Mode)
|
||||
if cfg.DisableEcoQoS == nil {
|
||||
eco := true
|
||||
cfg.DisableEcoQoS = &eco
|
||||
}
|
||||
if cfg.Mode == AffinityCustom {
|
||||
limit := maxCPUs
|
||||
if limit <= 0 || limit > 64 {
|
||||
limit = 64
|
||||
}
|
||||
mask, normalized := host.CPUsToMask(cfg.CPUs, limit)
|
||||
if mask == 0 {
|
||||
return VMAffinityConfig{}, errors.New("select at least one valid host CPU")
|
||||
}
|
||||
cfg.CPUs = normalized
|
||||
} else {
|
||||
cfg.CPUs = nil
|
||||
}
|
||||
data, err := json.MarshalIndent(cfg, "", " ")
|
||||
if err != nil {
|
||||
return VMAffinityConfig{}, err
|
||||
}
|
||||
dst := filepath.Join(vmDir, affinityConfigFile)
|
||||
tmp := dst + ".tmp"
|
||||
if err := os.WriteFile(tmp, data, 0o600); err != nil {
|
||||
return VMAffinityConfig{}, err
|
||||
}
|
||||
if err := os.Rename(tmp, dst); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return VMAffinityConfig{}, err
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// ResolvedAffinity is the concrete CPU mask computed for a VM on the current host.
|
||||
type ResolvedAffinity struct {
|
||||
ConfigMode AffinityMode
|
||||
EffectiveMode AffinityMode
|
||||
Mask uint64
|
||||
MaskHex string
|
||||
CPUs []int
|
||||
ShouldPin bool
|
||||
DisableEcoQoS bool
|
||||
AutoSkipped bool
|
||||
PThreads int
|
||||
}
|
||||
|
||||
// ResolveVMAffinity computes the effective host CPU mask for a VM given its
|
||||
// saved config, global auto-pin setting, current host report, and vCPU count.
|
||||
func ResolveVMAffinity(cfg VMAffinityConfig, globalAutoPin bool, rep host.Report, vcpus int) ResolvedAffinity {
|
||||
limit := rep.LogicalCPUs
|
||||
if limit <= 0 {
|
||||
limit = len(rep.CPUTopology)
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = 64
|
||||
}
|
||||
if limit > 64 {
|
||||
limit = 64
|
||||
}
|
||||
allMask := host.AllCPUsMask(limit)
|
||||
allCPUs := host.MaskToCPUs(allMask, limit)
|
||||
|
||||
mode := NormalizeAffinityMode(cfg.Mode)
|
||||
res := ResolvedAffinity{
|
||||
ConfigMode: mode,
|
||||
EffectiveMode: AffinityAll,
|
||||
Mask: allMask,
|
||||
MaskHex: fmt.Sprintf("0x%X", allMask),
|
||||
CPUs: allCPUs,
|
||||
DisableEcoQoS: cfg.ShouldDisableEcoQoS(),
|
||||
PThreads: len(rep.PCoreLogicalCPUs),
|
||||
}
|
||||
if res.PThreads == 0 {
|
||||
res.PThreads = rep.PCoreCount
|
||||
}
|
||||
|
||||
applyMask := func(eff AffinityMode, mask uint64) ResolvedAffinity {
|
||||
if mask == 0 {
|
||||
return res
|
||||
}
|
||||
cpus := host.MaskToCPUs(mask, limit)
|
||||
if len(cpus) == 0 {
|
||||
return res
|
||||
}
|
||||
res.EffectiveMode = eff
|
||||
res.Mask = mask
|
||||
res.MaskHex = fmt.Sprintf("0x%X", mask)
|
||||
res.CPUs = cpus
|
||||
res.ShouldPin = mask != allMask
|
||||
return res
|
||||
}
|
||||
|
||||
switch mode {
|
||||
case AffinityAll:
|
||||
return res
|
||||
case AffinityPCores:
|
||||
if rep.HasHybridCores && rep.PCoreMask > 0 {
|
||||
return applyMask(AffinityPCores, rep.PCoreMask)
|
||||
}
|
||||
return res
|
||||
case AffinityNonLPE:
|
||||
if rep.LPECoreCount > 0 && rep.NonLPEMask > 0 {
|
||||
return applyMask(AffinityNonLPE, rep.NonLPEMask)
|
||||
}
|
||||
return res
|
||||
case AffinityCustom:
|
||||
mask, _ := host.CPUsToMask(cfg.CPUs, limit)
|
||||
if mask != 0 {
|
||||
return applyMask(AffinityCustom, mask)
|
||||
}
|
||||
return res
|
||||
default: // AffinityAuto
|
||||
if !globalAutoPin || !rep.HasHybridCores || rep.PCoreMask == 0 {
|
||||
return res
|
||||
}
|
||||
plan := host.SelectSafeAffinity(rep, vcpus)
|
||||
res.PThreads = plan.PThreads
|
||||
switch plan.Mode {
|
||||
case "pcores":
|
||||
return applyMask(AffinityPCores, plan.Mask)
|
||||
case "non_lpe":
|
||||
return applyMask(AffinityNonLPE, plan.Mask)
|
||||
default:
|
||||
res.AutoSkipped = true
|
||||
return res
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ApplyVMAffinity applies the VM's persisted CPU affinity mask and EcoQoS
|
||||
// setting to a running QEMU PID. When forceApplyAll is true (e.g. a live user
|
||||
// edit switching back to "all"), SetProcessAffinityMask is called even for the
|
||||
// all-CPUs mask to clear any previous restriction.
|
||||
func ApplyVMAffinity(loc i18n.Locale, rep host.Report, vmDir string, globalAutoPin bool, pid, vcpus int, forceApplyAll bool) (string, error) {
|
||||
cfg := ReadVMAffinity(vmDir)
|
||||
res := ResolveVMAffinity(cfg, globalAutoPin, rep, vcpus)
|
||||
zh := loc == i18n.ZhCN
|
||||
|
||||
ecoDisabled := false
|
||||
if res.DisableEcoQoS {
|
||||
if err := host.DisableProcessPowerThrottling(uint32(pid)); err == nil {
|
||||
ecoDisabled = true
|
||||
}
|
||||
}
|
||||
|
||||
var ecoSuffix string
|
||||
if ecoDisabled {
|
||||
if zh {
|
||||
ecoSuffix = ",已禁用 EcoQoS 节流"
|
||||
} else {
|
||||
ecoSuffix = ", EcoQoS disabled"
|
||||
}
|
||||
}
|
||||
|
||||
if res.ShouldPin || forceApplyAll {
|
||||
targetMask := res.Mask
|
||||
if res.EffectiveMode == AffinityAll {
|
||||
if _, sysMask, err := host.GetProcessAffinityMask(uint32(pid)); err == nil && sysMask != 0 {
|
||||
targetMask = sysMask
|
||||
}
|
||||
}
|
||||
if targetMask == 0 {
|
||||
return "", errors.New("no valid CPU affinity mask available")
|
||||
}
|
||||
if err := host.SetProcessAffinityMask(uint32(pid), targetMask); err != nil {
|
||||
line := fmt.Sprintf("[CPU] Warning: CPU affinity update failed for PID %d (mask 0x%X): %v", pid, targetMask, err)
|
||||
return line, err
|
||||
}
|
||||
count := bits.OnesCount64(targetMask)
|
||||
maskHex := fmt.Sprintf("0x%X", targetMask)
|
||||
switch res.EffectiveMode {
|
||||
case AffinityPCores:
|
||||
if zh {
|
||||
return fmt.Sprintf("[CPU] 已将 QEMU (PID %d) 绑定到 P 核(%d 个逻辑处理器,掩码 %s%s)", pid, count, maskHex, ecoSuffix), nil
|
||||
}
|
||||
return fmt.Sprintf("[CPU] Pinned QEMU (PID %d) to P-cores (%d logical CPUs, mask %s%s)", pid, count, maskHex, ecoSuffix), nil
|
||||
case AffinityNonLPE:
|
||||
if zh {
|
||||
return fmt.Sprintf("[CPU] 已将 QEMU (PID %d) 绑定到 P+E 核(%d 个逻辑处理器,排除 LP-E 核,掩码 %s%s)", pid, count, maskHex, ecoSuffix), nil
|
||||
}
|
||||
return fmt.Sprintf("[CPU] Pinned QEMU (PID %d) to P+E cores (%d logical CPUs, LP-E excluded, mask %s%s)", pid, count, maskHex, ecoSuffix), nil
|
||||
case AffinityCustom:
|
||||
if zh {
|
||||
return fmt.Sprintf("[CPU] 已将 QEMU (PID %d) 映射到自定义核心(%d 个逻辑处理器,掩码 %s%s)", pid, count, maskHex, ecoSuffix), nil
|
||||
}
|
||||
return fmt.Sprintf("[CPU] Mapped QEMU (PID %d) to custom CPUs (%d logical CPUs, mask %s%s)", pid, count, maskHex, ecoSuffix), nil
|
||||
default:
|
||||
if zh {
|
||||
return fmt.Sprintf("[CPU] 已将 QEMU (PID %d) 设为所有处理器(%d 个逻辑处理器,掩码 %s%s)", pid, count, maskHex, ecoSuffix), nil
|
||||
}
|
||||
return fmt.Sprintf("[CPU] Set QEMU (PID %d) affinity to all CPUs (%d logical CPUs, mask %s%s)", pid, count, maskHex, ecoSuffix), nil
|
||||
}
|
||||
}
|
||||
|
||||
if res.AutoSkipped {
|
||||
if zh {
|
||||
return fmt.Sprintf("[CPU] 跳过自动绑核:虚拟机配置了 %d vCPU,超过可用安全绑定上限(P 核仅 %d 线程),使用全部核心%s", vcpus, res.PThreads, ecoSuffix), nil
|
||||
}
|
||||
return fmt.Sprintf("[CPU] Skipped auto pinning: VM has %d vCPUs, exceeding safe headroom (only %d P-core threads); using all CPUs%s", vcpus, res.PThreads, ecoSuffix), nil
|
||||
}
|
||||
if ecoDisabled {
|
||||
if zh {
|
||||
return fmt.Sprintf("[CPU] 已为 QEMU (PID %d) 禁用 Windows EcoQoS 效率节流(当前使用全部处理器)", pid), nil
|
||||
}
|
||||
return fmt.Sprintf("[CPU] Disabled Windows EcoQoS power throttling for QEMU (PID %d) (using all CPUs)", pid), nil
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// AffinitySummary formats a concise summary for startup logs.
|
||||
func AffinitySummary(loc i18n.Locale, rep host.Report, vmDir string, globalAutoPin bool, vcpus int) string {
|
||||
cfg := ReadVMAffinity(vmDir)
|
||||
res := ResolveVMAffinity(cfg, globalAutoPin, rep, vcpus)
|
||||
zh := loc == i18n.ZhCN
|
||||
switch res.EffectiveMode {
|
||||
case AffinityPCores:
|
||||
if zh {
|
||||
return fmt.Sprintf("P核(%d线程)", len(res.CPUs))
|
||||
}
|
||||
return fmt.Sprintf("P-cores(%dT)", len(res.CPUs))
|
||||
case AffinityNonLPE:
|
||||
if zh {
|
||||
return fmt.Sprintf("P+E(%d线程,避开LP-E)", len(res.CPUs))
|
||||
}
|
||||
return fmt.Sprintf("P+E(%dT,no-LPE)", len(res.CPUs))
|
||||
case AffinityCustom:
|
||||
if zh {
|
||||
return fmt.Sprintf("自定义(%d线程,%s)", len(res.CPUs), res.MaskHex)
|
||||
}
|
||||
return fmt.Sprintf("custom(%dT,%s)", len(res.CPUs), res.MaskHex)
|
||||
default:
|
||||
if res.AutoSkipped {
|
||||
if zh {
|
||||
return fmt.Sprintf("自动跳过(%d核≥%dP线程)", vcpus, res.PThreads)
|
||||
}
|
||||
return fmt.Sprintf("skipped(%dvCPU>=%dPT)", vcpus, res.PThreads)
|
||||
}
|
||||
if zh {
|
||||
return "全部核心"
|
||||
}
|
||||
return "all"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package vmstart
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
)
|
||||
|
||||
func TestVMAffinityRoundTripAndResolve(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
|
||||
// Default when sidecar does not exist.
|
||||
def := ReadVMAffinity(dir)
|
||||
if def.Mode != AffinityAuto || !def.ShouldDisableEcoQoS() {
|
||||
t.Fatalf("unexpected default: %+v", def)
|
||||
}
|
||||
|
||||
// Custom mode rejects empty selection.
|
||||
if _, err := SaveVMAffinity(dir, VMAffinityConfig{Mode: AffinityCustom}, 16); err == nil {
|
||||
t.Fatalf("expected error for empty custom CPU list")
|
||||
}
|
||||
|
||||
// Save custom deduplicated/sorted CPUs with EcoQoS disabled=false.
|
||||
eco := false
|
||||
saved, err := SaveVMAffinity(dir, VMAffinityConfig{
|
||||
Mode: AffinityCustom,
|
||||
CPUs: []int{5, 2, 2, 0, 99, -1},
|
||||
DisableEcoQoS: &eco,
|
||||
}, 16)
|
||||
if err != nil {
|
||||
t.Fatalf("SaveVMAffinity: %v", err)
|
||||
}
|
||||
wantCPUs := []int{0, 2, 5}
|
||||
if !reflect.DeepEqual(saved.CPUs, wantCPUs) || saved.ShouldDisableEcoQoS() {
|
||||
t.Fatalf("saved = %+v, want cpus %v eco=false", saved, wantCPUs)
|
||||
}
|
||||
|
||||
loaded := ReadVMAffinity(dir)
|
||||
if loaded.Mode != AffinityCustom || !reflect.DeepEqual(loaded.CPUs, wantCPUs) || loaded.ShouldDisableEcoQoS() {
|
||||
t.Fatalf("loaded = %+v", loaded)
|
||||
}
|
||||
|
||||
// Resolve on homogeneous 16-thread CPU.
|
||||
amd := host.Report{LogicalCPUs: 16}
|
||||
res := ResolveVMAffinity(loaded, true, amd, 4)
|
||||
if res.EffectiveMode != AffinityCustom || res.Mask != 0x25 || !res.ShouldPin {
|
||||
t.Fatalf("custom resolve = %+v, want mask 0x25", res)
|
||||
}
|
||||
|
||||
// Resolve auto on 3-tier Arrow Lake.
|
||||
arrowLake := host.Report{
|
||||
LogicalCPUs: 16,
|
||||
HasHybridCores: true,
|
||||
PCoreCount: 6,
|
||||
ECoreCount: 8,
|
||||
LPECoreCount: 2,
|
||||
PCoreMask: 0x3C03,
|
||||
PCoreLogicalCPUs: []int{0, 1, 10, 11, 12, 13},
|
||||
NonLPEMask: 0x3FFF,
|
||||
NonLPELogicalCPUs: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13},
|
||||
}
|
||||
r4 := ResolveVMAffinity(DefaultVMAffinityConfig(), true, arrowLake, 4)
|
||||
if r4.EffectiveMode != AffinityPCores || r4.Mask != 0x3C03 || !r4.ShouldPin {
|
||||
t.Fatalf("auto 4 vCPU = %+v", r4)
|
||||
}
|
||||
r8 := ResolveVMAffinity(DefaultVMAffinityConfig(), true, arrowLake, 8)
|
||||
if r8.EffectiveMode != AffinityNonLPE || r8.Mask != 0x3FFF || !r8.ShouldPin {
|
||||
t.Fatalf("auto 8 vCPU = %+v", r8)
|
||||
}
|
||||
r14 := ResolveVMAffinity(DefaultVMAffinityConfig(), true, arrowLake, 14)
|
||||
if r14.EffectiveMode != AffinityAll || !r14.AutoSkipped || r14.ShouldPin {
|
||||
t.Fatalf("auto 14 vCPU = %+v", r14)
|
||||
}
|
||||
// Explicit pcores overrides auto headroom limit when user explicitly asks for it.
|
||||
rExplicitP := ResolveVMAffinity(VMAffinityConfig{Mode: AffinityPCores}, false, arrowLake, 8)
|
||||
if rExplicitP.EffectiveMode != AffinityPCores || rExplicitP.Mask != 0x3C03 || !rExplicitP.ShouldPin {
|
||||
t.Fatalf("explicit pcores = %+v", rExplicitP)
|
||||
}
|
||||
// Explicit all returns full mask and ShouldPin=false (forceApplyAll handles live reset).
|
||||
rAll := ResolveVMAffinity(VMAffinityConfig{Mode: AffinityAll}, true, arrowLake, 4)
|
||||
if rAll.EffectiveMode != AffinityAll || rAll.Mask != 0xFFFF || rAll.ShouldPin {
|
||||
t.Fatalf("explicit all = %+v", rAll)
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,12 @@ func main() {
|
||||
MinWidth: 920,
|
||||
MinHeight: 600,
|
||||
Frameless: true,
|
||||
DragAndDrop: &options.DragAndDrop{
|
||||
EnableFileDrop: true,
|
||||
DisableWebViewDrop: true,
|
||||
CSSDropProperty: "--wails-drop-target",
|
||||
CSSDropValue: "drop",
|
||||
},
|
||||
AssetServer: &assetserver.Options{
|
||||
Assets: assets,
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user