From a962c52bcb651ad7b0c6e37fa5a97915fd2cc09e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Sat, 28 Nov 2026 06:31:54 -0700 Subject: [PATCH] feat: harden VM creation and expose host optimizations --- app.go | 93 +++--- cmd/reims-go/main.go | 24 +- create_flow.go | 77 +++++ frontend/src/App.tsx | 33 +- frontend/src/components/HostView.tsx | 87 ++++- frontend/src/components/LogPanel.tsx | 26 +- frontend/src/components/SettingsModal.tsx | 53 ++- frontend/src/i18n.ts | 62 ++++ frontend/src/lib/optimizations.ts | 62 ++++ frontend/src/styles/app.css | 1 + frontend/src/types.ts | 21 ++ frontend/wailsjs/go/models.ts | 44 +++ internal/driver/reims/compat.go | 134 ++++++++ internal/driver/reims/compat_test.go | 107 ++++++ internal/driver/reims/redact.go | 16 + internal/driver/reims/reims.go | 13 +- internal/host/host.go | 57 ++-- internal/host/host_windows.go | 35 +- internal/host/optimizations.go | 136 ++++++++ internal/host/optimizations_test.go | 74 +++++ internal/host/whpx_probe_other.go | 9 + internal/host/whpx_probe_windows.go | 124 +++++++ internal/installer/oc_cache.go | 195 +++++++++++ internal/installer/oc_cache_test.go | 106 ++++++ internal/qmp/watcher.go | 24 +- tasks.go | 33 +- vm_monitor.go | 383 ++++++++++++++++++++++ vm_monitor_test.go | 50 +++ 28 files changed, 1948 insertions(+), 131 deletions(-) create mode 100644 create_flow.go create mode 100644 frontend/src/lib/optimizations.ts create mode 100644 internal/driver/reims/compat.go create mode 100644 internal/driver/reims/compat_test.go create mode 100644 internal/driver/reims/redact.go create mode 100644 internal/host/optimizations.go create mode 100644 internal/host/optimizations_test.go create mode 100644 internal/host/whpx_probe_other.go create mode 100644 internal/host/whpx_probe_windows.go create mode 100644 internal/installer/oc_cache.go create mode 100644 internal/installer/oc_cache_test.go create mode 100644 vm_monitor.go create mode 100644 vm_monitor_test.go diff --git a/app.go b/app.go index 9b63b1d..51b9c86 100644 --- a/app.go +++ b/app.go @@ -27,6 +27,7 @@ type PendingChange struct { type AppState struct { Config *config.Config `json:"config"` Host host.Report `json:"host"` + Optimizations []host.Optimization `json:"optimizations"` Runtimes []rt.Installed `json:"runtimes"` ActiveRuntime *rt.Installed `json:"active_runtime,omitempty"` VMs []reims.VMListItem `json:"vms"` @@ -78,6 +79,8 @@ func (a *App) shutdown(ctx context.Context) { if a.stopPoll != nil { a.stopPoll() } + tasks.cancelAll() + stopAllVMMonitors() a.mu.Lock() for name, entry := range a.rebootWatchers { entry.cancel() @@ -122,6 +125,10 @@ func (a *App) pollVMs(ctx context.Context) { if cachedHost.HasHybridCores && cachedHost.PCoreMask > 0 { if err := host.PinProcessToPCores(uint32(*vm.PID), cachedHost.PCoreMask); err == nil { pinnedPIDs[*vm.PID] = true + a.emitLog(vm.Name, fmt.Sprintf("[CPU] Pinned QEMU (PID %d) to %d P-cores", *vm.PID, cachedHost.PCoreCount)) + } else { + pinnedPIDs[*vm.PID] = true + a.emitLog(vm.Name, fmt.Sprintf("[CPU] Warning: P-core pinning failed for PID %d: %v", *vm.PID, err)) } } } @@ -163,13 +170,13 @@ func (a *App) emitLog(source, line string) { wailsRuntime.EventsEmit(a.ctx, "reims:log", map[string]string{ "ts": time.Now().Format("15:04:05"), "source": source, - "line": line, + "line": reims.RedactLogLine(line), }) } type logWriter struct { - emit func(string) - buf strings.Builder + emit func(string) + buf strings.Builder } func (w *logWriter) Write(p []byte) (int, error) { @@ -202,9 +209,18 @@ func (a *App) GetState() AppState { active, _ := rt.ResolveActive(&cfgCopy) vms, _ := a.listVMsInternal(context.Background()) + var activePatches []string + if active != nil { + for _, p := range active.Manifest.Patches { + activePatches = append(activePatches, p.Name) + } + } + opts := host.EvaluateOptimizations(rep, activePatches) + return AppState{ Config: &cfgCopy, Host: rep, + Optimizations: opts, Runtimes: runtimes, ActiveRuntime: active, VMs: vms, @@ -320,32 +336,7 @@ func (a *App) PreviewCreate(opts reims.CreateOpts) (string, error) { } func (a *App) CreateVM(opts reims.CreateOpts) error { - if issues := a.ValidateCreate(opts); len(issues) > 0 { - return fmt.Errorf("%s", issues[0].Message) - } - c, err := a.client() - if err != nil { - return err - } - startAfterCreate := opts.Start - if startAfterCreate && a.needsColdRebootWorkaround() { - // Defer starting so StartVM can inject Win10 -no-reboot + QMP watcher first. - opts.Start = false - } - w, finishTask := a.ctlTaskWriter("vm-create", opts.Name) - a.emitLog(opts.Name, "Creating VM "+opts.Name+"...") - err = c.Create(context.Background(), opts, w, w) - finishTask(err) - if err != nil { - a.emitLog(opts.Name, "Create error: "+err.Error()) - return err - } - a.emitLog(opts.Name, "VM "+opts.Name+" ready.") - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - if startAfterCreate && !opts.Start { - return a.StartVM(opts.Name) - } - return nil + return a.createVMFlow(opts) } func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) { @@ -443,8 +434,17 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) { a.mu.Unlock() }() - guestReset, err := qmp.WatchForGuestReset(watchCtx, qmpAddr) - if err != nil || !guestReset { + reason, err := qmp.WatchShutdownReason(watchCtx, qmpAddr) + if err != nil { + if watchCtx.Err() == nil { + a.emitLog(name, "Win10 WHPX cold-reboot monitor disconnected: "+err.Error()) + } + return + } + if reason != "guest-reset" { + if reason != "" { + a.emitLog(name, "Win10 WHPX cold-reboot: VM exited ("+reason+"), not restarting") + } return } a.mu.Lock() @@ -454,7 +454,7 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) { return } - a.emitLog(name, "Win10 WHPX cold-reboot: guest requested reboot, restarting in a fresh Hyper-V partition...") + a.emitLog(name, "Win10 WHPX cold-reboot: guest requested reboot (guest-reset), restarting in a fresh Hyper-V partition...") c, err := a.client() if err != nil { a.emitLog(name, "Win10 WHPX cold-reboot aborted: "+err.Error()) @@ -501,19 +501,21 @@ func (a *App) StartVM(name string) error { } a.cancelRebootWatcher(name) + a.mu.Lock() + root := a.cfg.DataRoot + a.mu.Unlock() + rep := host.Inspect(root) + curDetail, _ := c.Show(context.Background(), name) + var qmpAddr string - if a.needsColdRebootWorkaround() { + if rep.NeedsColdRebootWorkaround { if port, perr := qmp.AllocateFreePort(); perr == nil { - cur, serr := c.Show(context.Background(), name) - existing := "" - if serr == nil { - existing = cur.ExtraArgs - } - merged := qmp.MergeWin10RebootArgs(existing, port) + merged := qmp.MergeWin10RebootArgs(curDetail.ExtraArgs, port) if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err != nil { a.emitLog(name, "Win10 cold-reboot extra-args setup skipped: "+err.Error()) } else { qmpAddr = fmt.Sprintf("127.0.0.1:%d", port) + curDetail.ExtraArgs = merged } } } @@ -524,9 +526,13 @@ func (a *App) StartVM(name string) error { a.mu.Unlock() wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + startAt := time.Now() + a.emitStartSummary(name, curDetail, rep, qmpAddr) w := &logWriter{emit: func(line string) { a.emitLog(name, line) }} a.emitLog(name, "Starting "+name+"...") - if err := c.Start(context.Background(), name, w, w); err != nil { + if err := c.StartWithCompat(context.Background(), name, w, w, func(msg string) { + a.emitLog(name, msg) + }); err != nil { a.mu.Lock() delete(a.transitions, name) a.mu.Unlock() @@ -537,6 +543,7 @@ func (a *App) StartVM(name string) error { if qmpAddr != "" { a.watchWin10ColdReboot(name, qmpAddr) } + a.startVMMonitor(name, curDetail, startAt) wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) return nil } @@ -547,6 +554,7 @@ func (a *App) StopVM(name string, force bool) error { return err } a.cancelRebootWatcher(name) + stopVMMonitor(name) a.mu.Lock() a.transitions[name] = "stopping" a.mu.Unlock() @@ -602,8 +610,11 @@ func (a *App) DeleteVM(name string, keepFiles bool) error { return err } a.cancelRebootWatcher(name) + stopVMMonitor(name) + w := &logWriter{emit: func(line string) { a.emitLog(name, line) }} a.emitLog(name, fmt.Sprintf("Deleting VM %s (keepFiles=%v)...", name, keepFiles)) - if err := c.Delete(context.Background(), name, keepFiles, io.Discard, io.Discard); err != nil { + if err := c.Delete(context.Background(), name, keepFiles, w, w); err != nil { + a.emitLog(name, "Delete error: "+err.Error()) return err } a.mu.Lock() diff --git a/cmd/reims-go/main.go b/cmd/reims-go/main.go index e0a1f68..55da87c 100644 --- a/cmd/reims-go/main.go +++ b/cmd/reims-go/main.go @@ -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/installer" rt "github.com/Nwflower/reims-go/internal/runtime" ) @@ -283,6 +284,7 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error { return fmt.Errorf("usage: reims-go vm create [flags] ") } name := fs.Arg(0) + startAfterCreate := *start opts := reims.CreateOpts{ Name: name, Dir: *dir, @@ -292,11 +294,27 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error { DiskSize: *diskSize, GPU: *gpu, Logs: logs, - Start: *start, + Start: false, + } + existingVMs, _ := client.List(ctx) + if removed, rerr := reims.CleanAbortedCreateDir(cfg.XDGDataDir(), opts, existingVMs); rerr == nil && removed != "" { + fmt.Fprintf(os.Stderr, "Removed unfinished directory from earlier interrupted create: %s\n", removed) + } + if installer.ShouldPrefetchOcBinaryData(active.Manifest.UtilCommit, active.Manifest.UtilVersion) { + if err := installer.EnsureCachedAsset(ctx, cfg.XDGCacheDir(), installer.OcBinaryDataAsset, nil, nil); err != nil { + fmt.Fprintf(os.Stderr, "OpenCore resource pre-fetch skipped (reims-ctl will retry): %v\n", err) + } } if err := client.Create(ctx, opts, os.Stdout, os.Stderr); err != nil { return err } + if startAfterCreate { + if err := client.StartWithCompat(ctx, name, os.Stdout, os.Stderr, func(msg string) { + fmt.Fprintln(os.Stderr, msg) + }); err != nil { + return err + } + } fmt.Println("\n" + i18n.T(loc, "vm.install_guide.title")) fmt.Println(i18n.T(loc, "vm.install_guide.step1")) fmt.Println(i18n.T(loc, "vm.install_guide.step2")) @@ -325,7 +343,9 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error { if len(args) < 2 { return fmt.Errorf("usage: reims-go vm start ") } - return client.Start(ctx, args[1], os.Stdout, os.Stderr) + return client.StartWithCompat(ctx, args[1], os.Stdout, os.Stderr, func(msg string) { + fmt.Fprintln(os.Stderr, msg) + }) case "stop": if len(args) < 2 { return fmt.Errorf("usage: reims-go vm stop ") diff --git a/create_flow.go b/create_flow.go new file mode 100644 index 0000000..59ef62b --- /dev/null +++ b/create_flow.go @@ -0,0 +1,77 @@ +package main + +import ( + "context" + "errors" + "fmt" + + "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/installer" + rt "github.com/Nwflower/reims-go/internal/runtime" + wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" +) + +func (a *App) createVMFlow(opts reims.CreateOpts) error { + if issues := a.ValidateCreate(opts); len(issues) > 0 { + return fmt.Errorf("%s", issues[0].Message) + } + a.mu.Lock() + cfgCopy := *a.cfg + a.mu.Unlock() + active, err := rt.ResolveActive(&cfgCopy) + if err != nil { + return err + } + c := reims.NewClient(&cfgCopy, *active) + + // Always defer starting to StartVM so commit-memory checks, Win10 cold-reboot + // QMP wiring, and Win11 WHPX nested-virt fallback apply uniformly. + startAfterCreate := opts.Start + opts.Start = false + + ctx, cancel := context.WithCancel(a.baseCtx()) + defer cancel() + taskID, w, finishTask := a.ctlTaskWriterWithCancel("vm-create", opts.Name, cancel) + a.emitLog(opts.Name, "Creating VM "+opts.Name+"...") + + existingVMs, _ := c.List(ctx) + if removed, rerr := reims.CleanAbortedCreateDir(cfgCopy.XDGDataDir(), opts, existingVMs); rerr != nil { + a.emitLog(opts.Name, "Warning: could not clean unfinished VM directory: "+rerr.Error()) + } else if removed != "" { + a.emitLog(opts.Name, "Removed unfinished directory from an earlier interrupted create: "+removed) + } + + // Pre-fetch OcBinaryData with an idle-read timeout so slow GitHub links do + // not trigger reims-util's 180s HTTP-200 truncate-and-restart loop. + if installer.ShouldPrefetchOcBinaryData(active.Manifest.UtilCommit, active.Manifest.UtilVersion) { + loggedPrefetch := false + perr := installer.EnsureCachedAsset(ctx, cfgCopy.XDGCacheDir(), installer.OcBinaryDataAsset, nil, func(u installer.Update) { + if !loggedPrefetch && u.Kind == installer.KindStep { + loggedPrefetch = true + a.emitLog(opts.Name, opts.Name+": "+u.Message) + } + tasks.update(taskID, u) + }) + if perr != nil { + if errors.Is(perr, context.Canceled) { + finishTask(perr) + a.emitLog(opts.Name, "Create canceled.") + return perr + } + a.emitLog(opts.Name, "Pre-fetch OpenCore resources skipped (reims-ctl will retry): "+perr.Error()) + } + } + + err = c.Create(ctx, opts, w, w) + finishTask(err) + if err != nil { + a.emitLog(opts.Name, "Create error: "+err.Error()) + return err + } + a.emitLog(opts.Name, "VM "+opts.Name+" ready.") + wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + if startAfterCreate { + return a.StartVM(opts.Name) + } + return nil +} diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 9107e32..0affedf 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -53,6 +53,7 @@ export const App: React.FC = () => { const [logTab, setLogTab] = useState('app') const [logLines, setLogLines] = useState([]) const [serialLog, setSerialLog] = useState('') + const [qemuLog, setQemuLog] = useState('') const [unseenErrors, setUnseenErrors] = useState(0) const logsOpenRef = useRef(logsOpen) logsOpenRef.current = logsOpen @@ -167,15 +168,21 @@ export const App: React.FC = () => { setUnseenErrors(0) } - const loadSerial = async (name = selectedVM?.name) => { + const loadVMLog = async (serial: boolean, name = selectedVM?.name) => { if (!name) return try { - setSerialLog(await backend.readVMLogs(name, true)) + const text = await backend.readVMLogs(name, serial) + if (serial) setSerialLog(text) + else setQemuLog(text) } catch (e) { - setSerialLog(errText(e)) + if (serial) setSerialLog(errText(e)) + else setQemuLog(errText(e)) } } + const loadSerial = (name?: string) => loadVMLog(true, name) + const loadQemu = (name?: string) => loadVMLog(false, name) + const fail = (title: string, e: unknown) => toasts.push({ kind: 'error', title, description: errText(e), action: { label: tr('viewLogs'), onClick: () => openLogs('app') } }) @@ -238,12 +245,15 @@ export const App: React.FC = () => { setSelected(name) return refresh() }) - .catch((e) => toasts.push({ - kind: 'error', - title: tr('failCreate', { name }), - description: errText(e), - action: { label: tr('backToEdit'), onClick: () => { setWizardDraft(draft); setShowWizard(true) } }, - })) + .catch((e) => { + void refresh() + toasts.push({ + kind: 'error', + title: tr('failCreate', { name }), + description: errText(e), + action: { label: tr('backToEdit'), onClick: () => { setWizardDraft(draft); setShowWizard(true) } }, + }) + }) } const copy = async (text: string) => { @@ -379,13 +389,15 @@ export const App: React.FC = () => { open={logsOpen} onToggle={toggleLogs} tab={selectedVM ? logTab : 'app'} - onTab={(tab) => { setLogTab(tab); if (tab === 'serial') loadSerial() }} + onTab={(tab) => { setLogTab(tab); if (tab === 'serial') loadSerial(); if (tab === 'qemu') loadQemu() }} lines={logLines} unseenErrors={unseenErrors} onClear={() => setLogLines([])} serialText={serialLog} + qemuText={qemuLog} showSerial={!!selectedVM} onRefreshSerial={() => loadSerial()} + onRefreshQemu={() => loadQemu()} task={activeTask} runningTasks={runningTasks} onCancelTask={cancelTask} @@ -409,6 +421,7 @@ export const App: React.FC = () => { locale={locale} detail={detail} host={state.host} + optimizations={state.optimizations} running={effectiveState === 'running'} onClose={() => setShowSettings(false)} onSaved={() => { diff --git a/frontend/src/components/HostView.tsx b/frontend/src/components/HostView.tsx index f2ce50b..1aabe23 100644 --- a/frontend/src/components/HostView.tsx +++ b/frontend/src/components/HostView.tsx @@ -1,6 +1,7 @@ import { Cpu, HardDrive, MemoryStick, RefreshCw, ShieldCheck } from 'lucide-react' import React, { useState } from 'react' import { I18nKey, t } from '../i18n' +import { findOptimization, kernelIrqchipHint, optBadgeClass, optStatusLabel } from '../lib/optimizations' import { AppState, Locale, Task } from '../types' import { Button, IconButton } from '../ui/controls' import { backend } from '../wails' @@ -21,8 +22,12 @@ interface Props { export const HostView: React.FC = ({ state, locale, onRefresh, onError, onSetLocale, runtimeTask, onChannel, onInstallRuntime, onCancelTask }) => { const [importing, setImporting] = useState(false) const [enabling, setEnabling] = useState(false) - const { host, config, runtimes } = state + const { host, config, runtimes, optimizations } = state const tr = (k: I18nKey, v?: Record) => t(locale, k, v) + const pcoreOpt = findOptimization(optimizations, 'pcore_pin') + const irqOpt = findOptimization(optimizations, 'kernel_irqchip') + const rebootOpt = findOptimization(optimizations, 'cold_reboot') + const gpuOpt = findOptimization(optimizations, 'discrete_gpu') const whpx = { ready: { short: tr('whpxReady'), hint: '', tone: 'ok' }, @@ -140,24 +145,33 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onError, o
- {host.has_hybrid_cores && ( -
-
-
{tr('autoPinPCores')}
+
+
+
+ {tr('autoPinPCores')} + + {optStatusLabel(locale, pcoreOpt?.status)} +
-
- +
+ {pcoreOpt?.supported + ? tr('optPCoreSub', { detail: pcoreOpt.detail ?? `${host.p_core_count}P+${host.e_core_count}E` }) + : tr('optPCoreUnavailable')}
- )} +
+ +
+
{tr('language')}
@@ -170,6 +184,47 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onError, o
+
+
{tr('hostOptimizations')}
+
+
+
+
+ {tr('optKernelIrqchipTitle')} + {optStatusLabel(locale, irqOpt?.status)} +
+
{kernelIrqchipHint(locale, irqOpt)}
+
+
+
+
+
+ {tr('optColdRebootTitle')} + {optStatusLabel(locale, rebootOpt?.status)} +
+
+ {tr(rebootOpt?.supported ? 'optColdRebootAuto' : 'optColdRebootUnavailable')} +
+
+
+
+
+
+ {tr('optDiscreteGpuTitle')} + {optStatusLabel(locale, gpuOpt?.status)} +
+
+ {gpuOpt?.status === 'recommended' + ? tr('optDiscreteGpuRec', { name: gpuOpt.detail ?? '' }) + : gpuOpt?.status === 'available' + ? tr('optDiscreteGpuIntegrated', { name: gpuOpt.detail ?? '' }) + : tr('optDiscreteGpuUnavailable')} +
+
+
+
+
+
{tr('hostGPUs')}
diff --git a/frontend/src/components/LogPanel.tsx b/frontend/src/components/LogPanel.tsx index 1127806..0f431e0 100644 --- a/frontend/src/components/LogPanel.tsx +++ b/frontend/src/components/LogPanel.tsx @@ -6,7 +6,7 @@ import { taskDetail, taskTitle } from '../lib/tasks' import { Locale, Task } from '../types' import { Button, IconButton, Tip } from '../ui/controls' -export type LogTab = 'app' | 'serial' +export type LogTab = 'app' | 'serial' | 'qemu' interface Props { locale: Locale @@ -18,8 +18,10 @@ interface Props { unseenErrors: number onClear: () => void serialText: string + qemuText: string showSerial: boolean onRefreshSerial: () => void + onRefreshQemu: () => void task: Task | null runningTasks: number onCancelTask: (id: string) => void @@ -49,11 +51,11 @@ function useStickToBottom(dep: unknown, active: boolean) { } export const LogPanel: React.FC = ({ - locale, open, onToggle, tab, onTab, lines, unseenErrors, onClear, serialText, showSerial, onRefreshSerial, + locale, open, onToggle, tab, onTab, lines, unseenErrors, onClear, serialText, qemuText, showSerial, onRefreshSerial, onRefreshQemu, task, runningTasks, onCancelTask, }) => { const tr = (k: Parameters[1]) => t(locale, k) - const content = tab === 'app' ? lines : serialText + const content = tab === 'app' ? lines : tab === 'serial' ? serialText : qemuText const { ref, stuck, onScroll, jump } = useStickToBottom(content, open) return ( @@ -87,9 +89,14 @@ export const LogPanel: React.FC = ({ {tr('logActivity')} {showSerial && ( - + <> + + + )}
)} @@ -99,6 +106,9 @@ export const LogPanel: React.FC = ({ {open && tab === 'serial' && ( } onClick={onRefreshSerial} /> )} + {open && tab === 'qemu' && ( + } onClick={onRefreshQemu} /> + )} {!open && unseenErrors > 0 && } = ({ {l.line}
))) - : (serialText || {tr('logsEmpty')})} + : tab === 'serial' + ? (serialText || {tr('logsEmpty')}) + : (qemuText || {tr('logsEmpty')})}
{!stuck && (
)} @@ -228,6 +240,7 @@ export const SettingsModal: React.FC = ({ locale, detail, host, running, {realGPUs.map((g) => )} + {realGPUs.length === 0 && {tr('gpuUnavailableHint')}}
@@ -258,6 +271,40 @@ export const SettingsModal: React.FC = ({ locale, detail, host, running, {cat === 'advanced' && ( <> +
+ +
+ + + +
+ + {kernelIrqchipHint(locale, irqOpt)} + +
set({ stop_timeout: Number(e.target.value) })} /> diff --git a/frontend/src/i18n.ts b/frontend/src/i18n.ts index df132be..c6c883f 100644 --- a/frontend/src/i18n.ts +++ b/frontend/src/i18n.ts @@ -94,6 +94,7 @@ const dict = { // Logs logActivity: '活动', logSerial: '串口', + logQemu: 'QEMU', logsEmpty: '暂无日志', // Tasks @@ -299,6 +300,36 @@ const dict = { stopTimeoutHint: '0 表示一直等待', extraArgs: '额外 QEMU 参数', logLevel: '日志级别(REIMS_VGPU_LOG)', + + // Host optimization probes & guidance + hostOptimizations: '优化能力', + optRecommended: '推荐', + optAvailable: '可用', + optExperimental: '实验性', + optAuto: '已自动开启', + optUnavailable: '不可用', + optPCoreSub: '仅调度到性能核({detail}),减少卡顿', + optPCoreUnavailable: '当前处理器无大小核架构,无需开启', + optKernelIrqchipTitle: 'WHPX 内核中断(kernel-irqchip)', + optKernelIrqchipRec: '当前 Windows 与硬件支持,可降低磁盘 I/O 与多核 CPU 开销', + optKernelIrqchipExp: '当前运行时含 Win10 多核启动补丁,可在虚拟机「高级」设置中手动开启验证', + optKernelIrqchipWin10NoPatch: 'Win10 默认关闭;需更新含 startup-ipis 补丁的运行时', + optKernelIrqchipNestedErr: '当前 Windows 拒绝嵌套虚拟化属性({code}),建议选「兼容模式」', + optKernelIrqchipUnavailable: '当前宿主 WHPX 环境不支持内核中断仿真', + optColdRebootTitle: 'Win10 无感冷重启补偿', + optColdRebootAuto: '检测到系统缺少 WHvResetPartition,启动时自动监控客体重启并冷拉起', + optColdRebootUnavailable: '当前 Windows 原生支持分区热重启,无需补偿', + optDiscreteGpuTitle: 'Vulkan 独显加速', + optDiscreteGpuRec: '已检测到独立显卡({name}),新建时默认优先使用', + optDiscreteGpuIntegrated: '仅检测到核显({name}),性能弱于独立显卡', + optDiscreteGpuUnavailable: '未检测到可用 Vulkan 显卡,可先切换 vmware-svga 排障', + kernelIrqchipLabel: 'WHPX 内核中断模式', + kernelIrqchipAuto: '自动', + kernelIrqchipOn: '开启(高性能)', + kernelIrqchipOff: '关闭(兼容)', + diskControllerNvmeHint: '安装盘已弹出,建议切换为 NVMe 以提升磁盘读写性能', + diskControllerInstallHint: '装机阶段建议保持 SATA,装完弹出安装盘后再切 NVMe', + gpuUnavailableHint: '未检测到可用 Vulkan 显卡,可先切换 vmware-svga 排障', }, 'en-US': { sidebarVMs: 'Virtual machines', @@ -386,6 +417,7 @@ const dict = { logActivity: 'Activity', logSerial: 'Serial', + logQemu: 'QEMU', logsEmpty: 'No logs yet', taskDownload: 'Downloading macOS {v}', @@ -584,6 +616,36 @@ const dict = { stopTimeoutHint: '0 waits indefinitely', extraArgs: 'Extra QEMU arguments', logLevel: 'Log level (REIMS_VGPU_LOG)', + + // Host optimization probes & guidance + hostOptimizations: 'Optimizations', + optRecommended: 'Recommended', + optAvailable: 'Available', + optExperimental: 'Experimental', + optAuto: 'Automatic', + optUnavailable: 'Unavailable', + optPCoreSub: 'Schedule QEMU on performance cores only ({detail})', + optPCoreUnavailable: 'CPU has no hybrid P/E cores', + optKernelIrqchipTitle: 'WHPX kernel irqchip', + optKernelIrqchipRec: 'Supported on this host; lowers disk I/O and multi-core CPU overhead', + optKernelIrqchipExp: 'Runtime includes Win10 startup-ipis patch; can be enabled in VM Advanced settings', + optKernelIrqchipWin10NoPatch: 'Off by default on Win10; needs a runtime with the startup-ipis patch', + optKernelIrqchipNestedErr: 'Host rejected nested virtualization property ({code}); use compatibility mode', + optKernelIrqchipUnavailable: 'Kernel APIC emulation is unavailable on this WHPX host', + optColdRebootTitle: 'Win10 cold-reboot workaround', + optColdRebootAuto: 'Host lacks WHvResetPartition; guest reboots are cold-restarted automatically', + optColdRebootUnavailable: 'Host supports native partition reset; workaround not needed', + optDiscreteGpuTitle: 'Vulkan discrete GPU acceleration', + optDiscreteGpuRec: 'Discrete GPU detected ({name}); preferred automatically', + optDiscreteGpuIntegrated: 'Integrated GPU only ({name})', + optDiscreteGpuUnavailable: 'No Vulkan GPU detected; use vmware-svga for troubleshooting', + kernelIrqchipLabel: 'WHPX kernel irqchip mode', + kernelIrqchipAuto: 'Auto', + kernelIrqchipOn: 'On (fast)', + kernelIrqchipOff: 'Off (compat)', + diskControllerNvmeHint: 'Installer ejected — switch to NVMe for faster disk I/O', + diskControllerInstallHint: 'Keep SATA while installing; switch to NVMe after ejecting the installer', + gpuUnavailableHint: 'No Vulkan GPU detected; switch to vmware-svga for troubleshooting', }, } as const diff --git a/frontend/src/lib/optimizations.ts b/frontend/src/lib/optimizations.ts new file mode 100644 index 0000000..ad8b998 --- /dev/null +++ b/frontend/src/lib/optimizations.ts @@ -0,0 +1,62 @@ +import { I18nKey, t } from '../i18n' +import { Locale, Optimization, OptimizationStatus } from '../types' + +export type KernelIrqchipMode = 'auto' | 'on' | 'off' + +export function findOptimization(list: Optimization[] | undefined, id: string): Optimization | undefined { + return (list ?? []).find((o) => o.id === id) +} + +export function optBadgeClass(status: OptimizationStatus | undefined): string { + switch (status) { + case 'recommended': + case 'auto': + return 'badge-ok' + case 'experimental': + return 'badge-warn' + case 'available': + return 'badge-accent' + default: + return '' + } +} + +export function optStatusLabel(locale: Locale, status: OptimizationStatus | undefined): string { + const keyMap: Record = { + recommended: 'optRecommended', + available: 'optAvailable', + experimental: 'optExperimental', + auto: 'optAuto', + unavailable: 'optUnavailable', + } + return t(locale, keyMap[status ?? 'unavailable']) +} + +export function kernelIrqchipHint(locale: Locale, opt: Optimization | undefined): string { + if (!opt) return t(locale, 'optKernelIrqchipUnavailable') + if (opt.status === 'recommended') return t(locale, 'optKernelIrqchipRec') + if (opt.status === 'experimental') return t(locale, 'optKernelIrqchipExp') + if (opt.detail === 'win10-needs-patch') return t(locale, 'optKernelIrqchipWin10NoPatch') + if (opt.detail && opt.detail.startsWith('0x')) return t(locale, 'optKernelIrqchipNestedErr', { code: opt.detail }) + return t(locale, 'optKernelIrqchipUnavailable') +} + +const IRQCHIP_RE = /(?:^|\s)-machine\s+kernel-irqchip=(on|off)(?=\s|$)/i +const INLINE_IRQCHIP_RE = /\bkernel-irqchip=(on|off)\b/i + +export function parseKernelIrqchip(extraArgs: string | undefined): KernelIrqchipMode { + const raw = (extraArgs ?? '').trim() + const m = raw.match(IRQCHIP_RE) ?? raw.match(INLINE_IRQCHIP_RE) + if (!m) return 'auto' + return m[1].toLowerCase() === 'on' ? 'on' : 'off' +} + +export function applyKernelIrqchip(extraArgs: string | undefined, mode: KernelIrqchipMode): string { + const cleaned = (extraArgs ?? '') + .replace(/(?:^|\s)-machine\s+kernel-irqchip=(?:on|off)(?=\s|$)/gi, ' ') + .replace(/\s+/g, ' ') + .trim() + if (mode === 'auto') return cleaned + const flag = `-machine kernel-irqchip=${mode}` + return cleaned ? `${cleaned} ${flag}` : flag +} diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 27e2cb4..c4936b6 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -312,6 +312,7 @@ h1, h2, h3, p { margin: 0; } .switch input:checked + .slider { background: var(--accent); } .switch input:checked + .slider::before { transform: translateX(16px); } .switch input:focus-visible + .slider { box-shadow: var(--focus-ring); } +.switch input:disabled + .slider { opacity: 0.45; cursor: not-allowed; } /* ── Log bar & panel ───────────────────────────────────── */ .logs { flex-shrink: 0; display: flex; flex-direction: column; border-top: 1px solid var(--border); background: var(--surface-chrome); } diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 14f6f02..dc63120 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -15,6 +15,24 @@ export interface GPUInfo { kind: 'discrete' | 'integrated' | 'virtual' | 'unknown' } +export interface WHPXCapabilities { + modern_os: boolean + apic_emulation: boolean + kernel_irqchip_available: boolean + nested_virt_property: boolean + nested_virt_probe_error?: string +} + +export type OptimizationStatus = 'recommended' | 'available' | 'experimental' | 'auto' | 'unavailable' + +export interface Optimization { + id: 'pcore_pin' | 'kernel_irqchip' | 'cold_reboot' | 'discrete_gpu' | string + status: OptimizationStatus + supported: boolean + recommended: boolean + detail?: string +} + export interface HostReport { os: string arch: string @@ -35,6 +53,8 @@ export interface HostReport { data_root: string free_disk_gb: number whpx: 'ready' | 'no_hypervisor' | 'missing' | 'unsupported' + whpx_caps?: WHPXCapabilities + needs_cold_reboot_workaround?: boolean gpus: GPUInfo[] recommended_gpu?: GPUInfo } @@ -73,6 +93,7 @@ export interface PendingChange { export interface AppState { config: Config host: HostReport + optimizations?: Optimization[] runtimes: InstalledRuntime[] | null active_runtime?: InstalledRuntime vms: VMListItem[] | null diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index f2c6dd0..0cfab5f 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -43,6 +43,46 @@ export namespace host { this.kind = source["kind"]; } } + export class Optimization { + id: string; + status: string; + supported: boolean; + recommended: boolean; + detail?: string; + + static createFrom(source: any = {}) { + return new Optimization(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.id = source["id"]; + this.status = source["status"]; + this.supported = source["supported"]; + this.recommended = source["recommended"]; + this.detail = source["detail"]; + } + } + export class WHPXCapabilities { + modern_os: boolean; + apic_emulation: boolean; + kernel_irqchip_available: boolean; + nested_virt_property: boolean; + nested_virt_probe_error?: string; + + static createFrom(source: any = {}) { + return new WHPXCapabilities(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.modern_os = source["modern_os"]; + this.apic_emulation = source["apic_emulation"]; + this.kernel_irqchip_available = source["kernel_irqchip_available"]; + this.nested_virt_property = source["nested_virt_property"]; + this.nested_virt_probe_error = source["nested_virt_probe_error"]; + } + } export class Report { os: string; arch: string; @@ -62,6 +102,7 @@ export namespace host { data_root: string; free_disk_gb: number; whpx: string; + whpx_caps: WHPXCapabilities; needs_cold_reboot_workaround: boolean; gpus: GPUInfo[]; recommended_gpu?: GPUInfo; @@ -90,6 +131,7 @@ export namespace host { this.data_root = source["data_root"]; this.free_disk_gb = source["free_disk_gb"]; this.whpx = source["whpx"]; + this.whpx_caps = this.convertValues(source["whpx_caps"], WHPXCapabilities); this.needs_cold_reboot_workaround = source["needs_cold_reboot_workaround"]; this.gpus = this.convertValues(source["gpus"], GPUInfo); this.recommended_gpu = this.convertValues(source["recommended_gpu"], GPUInfo); @@ -174,6 +216,7 @@ export namespace main { export class AppState { config?: config.Config; host: host.Report; + optimizations: host.Optimization[]; runtimes: runtime.Installed[]; active_runtime?: runtime.Installed; vms: reims.VMListItem[]; @@ -189,6 +232,7 @@ export namespace main { if ('string' === typeof source) source = JSON.parse(source); this.config = this.convertValues(source["config"], config.Config); this.host = this.convertValues(source["host"], host.Report); + this.optimizations = this.convertValues(source["optimizations"], host.Optimization); this.runtimes = this.convertValues(source["runtimes"], runtime.Installed); this.active_runtime = this.convertValues(source["active_runtime"], runtime.Installed); this.vms = this.convertValues(source["vms"], reims.VMListItem); diff --git a/internal/driver/reims/compat.go b/internal/driver/reims/compat.go new file mode 100644 index 0000000..d21f259 --- /dev/null +++ b/internal/driver/reims/compat.go @@ -0,0 +1,134 @@ +package reims + +import ( + "bytes" + "context" + "io" + "os" + "path/filepath" + "strings" + "sync" +) + +// creatingMarker is written by upstream `reims-ctl create` while building a VM +// directory and removed once vm.toml is saved (upstream 3731afd create.rs:451). +const creatingMarker = ".reims-ctl-creating" + +// CleanAbortedCreateDir removes an unregistered VM target directory left behind +// by a previously killed `reims-ctl create` run. It only removes a directory +// when all three safety conditions hold: +// 1. opts.Name is not present in registered VMs, +// 2. `.reims-ctl-creating` exists inside the directory, and +// 3. `vm.toml` does NOT exist inside the directory. +// +// Returns the removed path if cleaned, or "" if nothing was touched. +func CleanAbortedCreateDir(xdgDataDir string, opts CreateOpts, registered []VMListItem) (string, error) { + name := strings.TrimSpace(opts.Name) + if name == "" { + return "", nil + } + for _, vm := range registered { + if strings.EqualFold(vm.Name, name) { + return "", nil + } + } + target := strings.TrimSpace(opts.Dir) + if target == "" { + if strings.TrimSpace(xdgDataDir) == "" { + return "", nil + } + target = filepath.Join(xdgDataDir, "reims-ctl", "vms", name) + } + markerInfo, err := os.Stat(filepath.Join(target, creatingMarker)) + if err != nil || markerInfo.IsDir() { + return "", nil + } + if _, err := os.Stat(filepath.Join(target, "vm.toml")); err == nil { + return "", nil + } + if err := os.RemoveAll(target); err != nil { + return "", err + } + return target, nil +} + +// IsWHPXNestedVirtError reports whether QEMU exited because WHPX failed to +// enable nested virtualization (e.g. hr=80370302 WHV_E_UNKNOWN_PROPERTY on +// Windows 11 builds that advertise Bank1.NestedVirtSupport but reject +// WHvPartitionPropertyCodeNestedVirtualization; qemu-reims-vgpu 4571bc5 +// target/i386/whpx/whpx-all.c:3471-3484). +func IsWHPXNestedVirtError(output string) bool { + return strings.Contains(output, "WHPX: Failed to enable nested virtualization") +} + +// HasKernelIrqchipArg reports whether extra-args already specifies a +// kernel-irqchip setting. +func HasKernelIrqchipArg(extraArgs string) bool { + return strings.Contains(strings.ToLower(extraArgs), "kernel-irqchip=") +} + +// MergeKernelIrqchipOffArgs appends `-machine kernel-irqchip=off` to existing +// QEMU extra-args unless a kernel-irqchip setting is already present. +func MergeKernelIrqchipOffArgs(existing string) string { + trimmed := strings.TrimSpace(existing) + if HasKernelIrqchipArg(trimmed) { + return trimmed + } + const flag = "-machine kernel-irqchip=off" + if trimmed == "" { + return flag + } + return trimmed + " " + flag +} + +type captureWriter struct { + mu sync.Mutex + buf bytes.Buffer + dst io.Writer +} + +func (w *captureWriter) Write(p []byte) (int, error) { + w.mu.Lock() + if w.buf.Len() < 64*1024 { + w.buf.Write(p) + } + w.mu.Unlock() + if w.dst != nil { + return w.dst.Write(p) + } + return len(p), nil +} + +func (w *captureWriter) String() string { + w.mu.Lock() + defer w.mu.Unlock() + return w.buf.String() +} + +// StartWithCompat starts a VM and automatically recovers once if QEMU aborts +// with the WHPX nested-virtualization property error (hr=80370302) by writing +// `-machine kernel-irqchip=off` via `reims-ctl set` (D3) and retrying start. +func (c *Client) StartWithCompat(ctx context.Context, name string, stdout, stderr io.Writer, onNote func(string)) error { + outCap := &captureWriter{dst: stdout} + errCap := &captureWriter{dst: stderr} + err := c.Start(ctx, name, outCap, errCap) + if err == nil { + return nil + } + combined := outCap.String() + "\n" + errCap.String() + if !IsWHPXNestedVirtError(combined) { + return err + } + cur, serr := c.Show(ctx, name) + if serr != nil || HasKernelIrqchipArg(cur.ExtraArgs) { + return err + } + merged := MergeKernelIrqchipOffArgs(cur.ExtraArgs) + if setErr := c.Set(ctx, SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); setErr != nil { + return err + } + if onNote != nil { + onNote("WHPX host rejected nested virtualization property (hr=80370302); applied -machine kernel-irqchip=off and retrying start...") + } + return c.Start(ctx, name, stdout, stderr) +} diff --git a/internal/driver/reims/compat_test.go b/internal/driver/reims/compat_test.go new file mode 100644 index 0000000..ee5ee8d --- /dev/null +++ b/internal/driver/reims/compat_test.go @@ -0,0 +1,107 @@ +package reims + +import ( + "os" + "path/filepath" + "reflect" + "testing" +) + +func TestBuildDeleteArgs(t *testing.T) { + got := BuildDeleteArgs("macos-tahoe", false) + want := []string{"delete", "--yes", "macos-tahoe"} + if !reflect.DeepEqual(got, want) { + t.Fatalf("BuildDeleteArgs(keepFiles=false) = %v, want %v", got, want) + } + gotKeep := BuildDeleteArgs("macos-tahoe", true) + wantKeep := []string{"delete", "--yes", "macos-tahoe", "--keep-files"} + if !reflect.DeepEqual(gotKeep, wantKeep) { + t.Fatalf("BuildDeleteArgs(keepFiles=true) = %v, want %v", gotKeep, wantKeep) + } +} + +func TestRedactLogLine(t *testing.T) { + got := RedactLogLine("mac 52:54:00:12:34:56 serial C02ABCDEFGH") + if got != "mac [redacted] serial [redacted]" { + t.Fatalf("RedactLogLine = %q", got) + } +} + +func TestCleanAbortedCreateDir(t *testing.T) { + dataDir := t.TempDir() + vmDir := filepath.Join(dataDir, "reims-ctl", "vms", "macos-tahoe") + if err := os.MkdirAll(vmDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(vmDir, creatingMarker), nil, 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(vmDir, "disk.qcow2"), []byte("partial"), 0o644); err != nil { + t.Fatal(err) + } + + // Refuses if VM is registered. + removed, err := CleanAbortedCreateDir(dataDir, CreateOpts{Name: "macos-tahoe"}, []VMListItem{{Name: "macos-tahoe"}}) + if err != nil || removed != "" { + t.Fatalf("expected skip for registered VM, got removed=%q err=%v", removed, err) + } + + // Refuses if vm.toml exists. + tomlPath := filepath.Join(vmDir, "vm.toml") + if err := os.WriteFile(tomlPath, []byte("cpus = 8\n"), 0o644); err != nil { + t.Fatal(err) + } + removed, err = CleanAbortedCreateDir(dataDir, CreateOpts{Name: "macos-tahoe"}, nil) + if err != nil || removed != "" { + t.Fatalf("expected skip when vm.toml exists, got removed=%q err=%v", removed, err) + } + _ = os.Remove(tomlPath) + + // Cleans when unregistered, .reims-ctl-creating exists, and vm.toml is absent. + removed, err = CleanAbortedCreateDir(dataDir, CreateOpts{Name: "macos-tahoe"}, nil) + if err != nil || removed != vmDir { + t.Fatalf("expected removal of %q, got removed=%q err=%v", vmDir, removed, err) + } + if _, err := os.Stat(vmDir); !os.IsNotExist(err) { + t.Fatalf("expected %q to be deleted, stat err=%v", vmDir, err) + } + + // Refuses arbitrary non-empty directory without marker. + customDir := filepath.Join(t.TempDir(), "user-folder") + if err := os.MkdirAll(customDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(customDir, "notes.txt"), []byte("keep"), 0o644); err != nil { + t.Fatal(err) + } + removed, err = CleanAbortedCreateDir(dataDir, CreateOpts{Name: "other", Dir: customDir}, nil) + if err != nil || removed != "" { + t.Fatalf("expected skip without marker, got removed=%q err=%v", removed, err) + } +} + +func TestWHPXNestedVirtCompat(t *testing.T) { + sampleErr := "2026-11-28T13:04:47Z qemu: -accel whpx: WHPX: Failed to enable nested virtualization, hr=80370302\n" + if !IsWHPXNestedVirtError(sampleErr) { + t.Fatalf("expected IsWHPXNestedVirtError to match") + } + if IsWHPXNestedVirtError("some unrelated error") { + t.Fatalf("unexpected match on unrelated error") + } + + if got := MergeKernelIrqchipOffArgs(""); got != "-machine kernel-irqchip=off" { + t.Fatalf("MergeKernelIrqchipOffArgs(empty) = %q", got) + } + existing := "-no-reboot -qmp tcp:127.0.0.1:45555,server=on,wait=off" + want := existing + " -machine kernel-irqchip=off" + if got := MergeKernelIrqchipOffArgs(existing); got != want { + t.Fatalf("MergeKernelIrqchipOffArgs = %q, want %q", got, want) + } + // Idempotent when already set. + if got := MergeKernelIrqchipOffArgs(want); got != want { + t.Fatalf("expected idempotent merge, got %q", got) + } + if !HasKernelIrqchipArg("-accel whpx,kernel-irqchip=on") { + t.Fatalf("expected HasKernelIrqchipArg to detect accel form") + } +} diff --git a/internal/driver/reims/redact.go b/internal/driver/reims/redact.go new file mode 100644 index 0000000..87ce773 --- /dev/null +++ b/internal/driver/reims/redact.go @@ -0,0 +1,16 @@ +package reims + +import "regexp" + +var ( + reLogMac = regexp.MustCompile(`(?i)\bmac\s+[0-9a-f]{2}(?::[0-9a-f]{2}){5}\b`) + reLogSerial = regexp.MustCompile(`(?i)\bserial\s+[A-Z0-9]{8,}\b`) +) + +// RedactLogLine removes MAC addresses and SMBIOS serial numbers before lines +// are emitted to the activity log panel (docs/shell-design.md §3). +func RedactLogLine(line string) string { + line = reLogMac.ReplaceAllString(line, "mac [redacted]") + line = reLogSerial.ReplaceAllString(line, "serial [redacted]") + return line +} diff --git a/internal/driver/reims/reims.go b/internal/driver/reims/reims.go index 0cb6fd3..7c8b1e8 100644 --- a/internal/driver/reims/reims.go +++ b/internal/driver/reims/reims.go @@ -606,10 +606,17 @@ func (c *Client) Eject(ctx context.Context, name string, stdout, stderr io.Write return c.run(ctx, stdout, stderr, "eject", name) } -func (c *Client) Delete(ctx context.Context, name string, keepFiles bool, stdout, stderr io.Writer) error { - args := []string{"delete", name} +// BuildDeleteArgs builds `reims-ctl delete` arguments. Always passes --yes +// because reims-ctl prompts interactively on stdin when omitted and exits 0 +// with "nothing deleted" on EOF (upstream reims-vgpu 3731afd cli.rs:1089-1099). +func BuildDeleteArgs(name string, keepFiles bool) []string { + args := []string{"delete", "--yes", name} if keepFiles { args = append(args, "--keep-files") } - return c.run(ctx, stdout, stderr, args...) + return args +} + +func (c *Client) Delete(ctx context.Context, name string, keepFiles bool, stdout, stderr io.Writer) error { + return c.run(ctx, stdout, stderr, BuildDeleteArgs(name, keepFiles)...) } diff --git a/internal/host/host.go b/internal/host/host.go index 776596a..aa3b028 100644 --- a/internal/host/host.go +++ b/internal/host/host.go @@ -20,38 +20,47 @@ type GPUInfo struct { type WHPXState string const ( - WHPXReady WHPXState = "ready" + WHPXReady WHPXState = "ready" WHPXNoHypervisor WHPXState = "no_hypervisor" - WHPXMissing WHPXState = "missing" - WHPXUnsupported WHPXState = "unsupported" + WHPXMissing WHPXState = "missing" + WHPXUnsupported WHPXState = "unsupported" ) +type WHPXCapabilities struct { + ModernOS bool `json:"modern_os"` + APICEmulation bool `json:"apic_emulation"` + KernelIrqchipAvailable bool `json:"kernel_irqchip_available"` + NestedVirtProperty bool `json:"nested_virt_property"` + NestedVirtProbeError string `json:"nested_virt_probe_error,omitempty"` +} + 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"` - 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"` - TotalRAMGB float64 `json:"total_ram_gb"` - AvailRAMGB float64 `json:"avail_ram_gb"` + 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"` + 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"` + TotalRAMGB float64 `json:"total_ram_gb"` + AvailRAMGB float64 `json:"avail_ram_gb"` // Commit memory: QEMU commits all guest RAM at start (CreateFileMapping), so // a VM needs its memory free in the commit charge, not just in physical RAM. // Measured 2026-11-28: 14.7 GiB commit free with 17.3 GiB physical free, and a // 16G guest failed ("Cannot set up guest memory"). portable-runtime-spec.md §5.1. - CommitAvailGB float64 `json:"commit_avail_gb"` - CommitLimitGB float64 `json:"commit_limit_gb"` - DataRoot string `json:"data_root"` - FreeDiskGB float64 `json:"free_disk_gb"` - WHPX WHPXState `json:"whpx"` - NeedsColdRebootWorkaround bool `json:"needs_cold_reboot_workaround"` - GPUs []GPUInfo `json:"gpus"` - RecommendedGPU *GPUInfo `json:"recommended_gpu,omitempty"` + CommitAvailGB float64 `json:"commit_avail_gb"` + CommitLimitGB float64 `json:"commit_limit_gb"` + DataRoot string `json:"data_root"` + FreeDiskGB float64 `json:"free_disk_gb"` + WHPX WHPXState `json:"whpx"` + WHPXCaps WHPXCapabilities `json:"whpx_caps"` + NeedsColdRebootWorkaround bool `json:"needs_cold_reboot_workaround"` + GPUs []GPUInfo `json:"gpus"` + RecommendedGPU *GPUInfo `json:"recommended_gpu,omitempty"` } // ClassifyGPU distinguishes discrete, integrated, and virtual display adapters. diff --git a/internal/host/host_windows.go b/internal/host/host_windows.go index d0f0361..1f9a4fd 100644 --- a/internal/host/host_windows.go +++ b/internal/host/host_windows.go @@ -13,13 +13,13 @@ import ( ) var ( - kernel32 = syscall.NewLazyDLL("kernel32.dll") - procGetLogicalProcessorInformationEx = kernel32.NewProc("GetLogicalProcessorInformationEx") - procGlobalMemoryStatusEx = kernel32.NewProc("GlobalMemoryStatusEx") - procGetDiskFreeSpaceExW = kernel32.NewProc("GetDiskFreeSpaceExW") - procOpenProcess = kernel32.NewProc("OpenProcess") - procSetProcessAffinityMask = kernel32.NewProc("SetProcessAffinityMask") - procCloseHandle = kernel32.NewProc("CloseHandle") + kernel32 = syscall.NewLazyDLL("kernel32.dll") + procGetLogicalProcessorInformationEx = kernel32.NewProc("GetLogicalProcessorInformationEx") + procGlobalMemoryStatusEx = kernel32.NewProc("GlobalMemoryStatusEx") + procGetDiskFreeSpaceExW = kernel32.NewProc("GetDiskFreeSpaceExW") + procOpenProcess = kernel32.NewProc("OpenProcess") + procSetProcessAffinityMask = kernel32.NewProc("SetProcessAffinityMask") + procCloseHandle = kernel32.NewProc("CloseHandle") advapi32 = syscall.NewLazyDLL("advapi32.dll") procRegOpenKeyExW = advapi32.NewProc("RegOpenKeyExW") @@ -31,12 +31,12 @@ var ( ) const ( - hkeyLocalMachine = 0x80000002 - keyRead = 0x20019 - regSZ = 1 - regExpandSZ = 2 - regMultiSZ = 7 - processSetInformation = 0x0200 + hkeyLocalMachine = 0x80000002 + keyRead = 0x20019 + regSZ = 1 + regExpandSZ = 2 + regMultiSZ = 7 + processSetInformation = 0x0200 whvCapHypervisorPresent = 0x00000001 ) @@ -55,14 +55,17 @@ type memoryStatusEx struct { // Inspect collects Windows host capabilities without requiring administrator privileges. func Inspect(dataRoot string) Report { rep := Report{ - OS: "windows", - Arch: runtime.GOARCH, - LogicalCPUs: runtime.NumCPU(), + OS: "windows", + Arch: runtime.GOARCH, + LogicalCPUs: runtime.NumCPU(), DataRoot: dataRoot, WHPX: probeWHPX(), NeedsColdRebootWorkaround: probeNeedsColdRebootWorkaround(), GPUs: probeVulkanGPUs(), } + if rep.WHPX == WHPXReady { + rep.WHPXCaps = probeWHPXCapabilities() + } rep.RecommendedGPU = PickRecommendedGPU(rep.GPUs) if cores, pCount, eCount, pMask, pLPs, eLPs, ok := probeHybridTopology(); ok { diff --git a/internal/host/optimizations.go b/internal/host/optimizations.go new file mode 100644 index 0000000..94aa673 --- /dev/null +++ b/internal/host/optimizations.go @@ -0,0 +1,136 @@ +package host + +import ( + "fmt" + "strings" +) + +// Optimization summarizes the probed host availability and recommendation for +// one hardware/runtime optimization toggle. +type Optimization struct { + ID string `json:"id"` + Status string `json:"status"` // recommended | available | experimental | auto | unavailable + Supported bool `json:"supported"` + Recommended bool `json:"recommended"` + Detail string `json:"detail,omitempty"` +} + +// EvaluateOptimizations combines host capability probes with the active +// runtime's patch list so the UI can show accurate, self-explanatory guidance +// for every optimization toggle without guessing. +func EvaluateOptimizations(rep Report, runtimePatches []string) []Optimization { + hasPatch := func(substr string) bool { + for _, p := range runtimePatches { + if strings.Contains(strings.ToLower(p), strings.ToLower(substr)) { + return true + } + } + return false + } + + var out []Optimization + + // 1. P-Core affinity pinning (hybrid Intel CPUs) + if rep.HasHybridCores { + out = append(out, Optimization{ + ID: "pcore_pin", + Status: "recommended", + Supported: true, + Recommended: true, + Detail: fmt.Sprintf("%dP+%dE", rep.PCoreCount, rep.ECoreCount), + }) + } else { + out = append(out, Optimization{ + ID: "pcore_pin", + Status: "unavailable", + Supported: false, + }) + } + + // 2. WHPX kernel-irqchip (APIC emulation in Hyper-V) + switch { + case rep.WHPX != WHPXReady || !rep.WHPXCaps.KernelIrqchipAvailable: + out = append(out, Optimization{ + ID: "kernel_irqchip", + Status: "unavailable", + Supported: false, + }) + case !rep.NeedsColdRebootWorkaround: + // Windows 11 / Server 2022+: QEMU enables kernel-irqchip by default, + // unless NestedVirtualization property probe fails (e.g. hr=0x80370302). + if rep.WHPXCaps.NestedVirtProperty { + out = append(out, Optimization{ + ID: "kernel_irqchip", + Status: "recommended", + Supported: true, + Recommended: true, + }) + } else { + out = append(out, Optimization{ + ID: "kernel_irqchip", + Status: "unavailable", + Supported: false, + Detail: rep.WHPXCaps.NestedVirtProbeError, + }) + } + default: + // Windows 10: requires startup-ipis patch in runtime for multi-core boot. + if hasPatch("startup-ipis") { + out = append(out, Optimization{ + ID: "kernel_irqchip", + Status: "experimental", + Supported: true, + Detail: "win10-startup-ipis", + }) + } else { + out = append(out, Optimization{ + ID: "kernel_irqchip", + Status: "unavailable", + Supported: false, + Detail: "win10-needs-patch", + }) + } + } + + // 3. Win10 cold-reboot compensation + if rep.NeedsColdRebootWorkaround { + out = append(out, Optimization{ + ID: "cold_reboot", + Status: "auto", + Supported: true, + Recommended: true, + }) + } else { + out = append(out, Optimization{ + ID: "cold_reboot", + Status: "unavailable", + Supported: false, + }) + } + + // 4. Discrete Vulkan GPU acceleration + if rep.RecommendedGPU != nil && rep.RecommendedGPU.Kind == GPUDiscrete { + out = append(out, Optimization{ + ID: "discrete_gpu", + Status: "recommended", + Supported: true, + Recommended: true, + Detail: rep.RecommendedGPU.Name, + }) + } else if rep.RecommendedGPU != nil { + out = append(out, Optimization{ + ID: "discrete_gpu", + Status: "available", + Supported: true, + Detail: rep.RecommendedGPU.Name, + }) + } else { + out = append(out, Optimization{ + ID: "discrete_gpu", + Status: "unavailable", + Supported: false, + }) + } + + return out +} diff --git a/internal/host/optimizations_test.go b/internal/host/optimizations_test.go new file mode 100644 index 0000000..7bf94f2 --- /dev/null +++ b/internal/host/optimizations_test.go @@ -0,0 +1,74 @@ +package host + +import "testing" + +func findOpt(t *testing.T, opts []Optimization, id string) Optimization { + t.Helper() + for _, o := range opts { + if o.ID == id { + return o + } + } + t.Fatalf("optimization %q not found", id) + return Optimization{} +} + +func TestEvaluateOptimizationsWin10AndWin11(t *testing.T) { + // Win10 hybrid CPU without startup-ipis patch. + win10 := Report{ + WHPX: WHPXReady, + HasHybridCores: true, + PCoreCount: 8, + ECoreCount: 4, + NeedsColdRebootWorkaround: true, + WHPXCaps: WHPXCapabilities{ + APICEmulation: true, + KernelIrqchipAvailable: true, + }, + RecommendedGPU: &GPUInfo{Name: "NVIDIA GeForce RTX 4070 Ti", Kind: GPUDiscrete, VulkanICD: "nv-vk64.json"}, + } + opts := EvaluateOptimizations(win10, []string{"qemu-whpx-win10-compat.patch"}) + if o := findOpt(t, opts, "pcore_pin"); o.Status != "recommended" || !o.Supported { + t.Fatalf("pcore_pin = %+v", o) + } + if o := findOpt(t, opts, "kernel_irqchip"); o.Status != "unavailable" || o.Detail != "win10-needs-patch" { + t.Fatalf("kernel_irqchip without patch = %+v", o) + } + if o := findOpt(t, opts, "cold_reboot"); o.Status != "auto" { + t.Fatalf("cold_reboot = %+v", o) + } + + // Win10 with startup-ipis patch -> experimental. + optsPatched := EvaluateOptimizations(win10, []string{"qemu-whpx-win10-compat.patch", "qemu-whpx-win10-startup-ipis.patch"}) + if o := findOpt(t, optsPatched, "kernel_irqchip"); o.Status != "experimental" || !o.Supported { + t.Fatalf("kernel_irqchip with patch = %+v", o) + } + + // Win11 where NestedVirtualization probe fails with 0x80370302. + win11BrokenNested := Report{ + WHPX: WHPXReady, + NeedsColdRebootWorkaround: false, + WHPXCaps: WHPXCapabilities{ + ModernOS: true, + APICEmulation: true, + KernelIrqchipAvailable: true, + NestedVirtProperty: false, + NestedVirtProbeError: "0x80370302", + }, + } + opts11 := EvaluateOptimizations(win11BrokenNested, nil) + if o := findOpt(t, opts11, "kernel_irqchip"); o.Status != "unavailable" || o.Detail != "0x80370302" { + t.Fatalf("win11 broken nested = %+v", o) + } + if o := findOpt(t, opts11, "cold_reboot"); o.Status != "unavailable" { + t.Fatalf("win11 cold_reboot = %+v", o) + } + + // Win11 with full support. + win11BrokenNested.WHPXCaps.NestedVirtProperty = true + win11BrokenNested.WHPXCaps.NestedVirtProbeError = "" + opts11Ok := EvaluateOptimizations(win11BrokenNested, nil) + if o := findOpt(t, opts11Ok, "kernel_irqchip"); o.Status != "recommended" || !o.Supported { + t.Fatalf("win11 full support = %+v", o) + } +} diff --git a/internal/host/whpx_probe_other.go b/internal/host/whpx_probe_other.go new file mode 100644 index 0000000..54e64db --- /dev/null +++ b/internal/host/whpx_probe_other.go @@ -0,0 +1,9 @@ +//go:build !windows + +package host + +import "time" + +func ProcessCPUTime(pid uint32) (time.Duration, bool) { + return 0, false +} diff --git a/internal/host/whpx_probe_windows.go b/internal/host/whpx_probe_windows.go new file mode 100644 index 0000000..3528e00 --- /dev/null +++ b/internal/host/whpx_probe_windows.go @@ -0,0 +1,124 @@ +//go:build windows + +package host + +import ( + "fmt" + "syscall" + "time" + "unsafe" +) + +const ( + // WinHvPlatformDefs.h capability & partition property codes. + whvCapFeatures = 0x00000001 + whvCapProcessorPerfmon = 0x00001009 + whvPropNestedVirtualization = 0x00000004 + whvPropLocalApicEmulationMode = 0x00001005 + whvPropProcessorCount = 0x00001fff + whvLocalApicModeX2Apic = 2 + + processQueryLimitedInfo = 0x1000 +) + +var procGetProcessTimes = kernel32.NewProc("GetProcessTimes") + +// probeWHPXCapabilities checks WHPX kernel-irqchip and nested-virtualization +// partition property support on a throwaway WHP partition without starting any +// vCPU or requiring administrator privileges. +func probeWHPXCapabilities() WHPXCapabilities { + var caps WHPXCapabilities + mod := syscall.NewLazyDLL("WinHvPlatform.dll") + if err := mod.Load(); err != nil { + return caps + } + getCap := mod.NewProc("WHvGetCapability") + createPart := mod.NewProc("WHvCreatePartition") + deletePart := mod.NewProc("WHvDeletePartition") + setProp := mod.NewProc("WHvSetPartitionProperty") + if getCap.Find() != nil || createPart.Find() != nil || deletePart.Find() != nil || setProp.Find() != nil { + return caps + } + + var perfmon uint64 + var written uint32 + hr, _, _ := getCap.Call( + uintptr(whvCapProcessorPerfmon), + uintptr(unsafe.Pointer(&perfmon)), + uintptr(unsafe.Sizeof(perfmon)), + uintptr(unsafe.Pointer(&written)), + ) + caps.ModernOS = int32(hr) >= 0 + + var features uint64 + hr, _, _ = getCap.Call( + uintptr(whvCapFeatures), + uintptr(unsafe.Pointer(&features)), + uintptr(unsafe.Sizeof(features)), + uintptr(unsafe.Pointer(&written)), + ) + hasApicBit := int32(hr) >= 0 && (features&(1<<1)) != 0 + hasApicProcs := mod.NewProc("WHvSetVirtualProcessorInterruptControllerState2").Find() == nil && + mod.NewProc("WHvRequestInterrupt").Find() == nil + caps.APICEmulation = hasApicBit && hasApicProcs + + var part uintptr + hr, _, _ = createPart.Call(uintptr(unsafe.Pointer(&part))) + if int32(hr) < 0 || part == 0 { + return caps + } + defer deletePart.Call(part) + + var propBuf [24]byte + // ProcessorCount = 1 + propBuf[0] = 1 + hr, _, _ = setProp.Call(part, uintptr(whvPropProcessorCount), uintptr(unsafe.Pointer(&propBuf[0])), uintptr(len(propBuf))) + if int32(hr) < 0 { + return caps + } + + if caps.APICEmulation { + var mode uint32 = whvLocalApicModeX2Apic + hr, _, _ = setProp.Call(part, uintptr(whvPropLocalApicEmulationMode), uintptr(unsafe.Pointer(&mode)), uintptr(unsafe.Sizeof(mode))) + caps.KernelIrqchipAvailable = int32(hr) >= 0 + } + + // Probe WHvPartitionPropertyCodeNestedVirtualization (same property that + // fails with hr=0x80370302 WHV_E_UNKNOWN_PROPERTY on some Windows 11 builds). + var nestedBuf [24]byte + nestedBuf[0] = 1 + hr, _, _ = setProp.Call(part, uintptr(whvPropNestedVirtualization), uintptr(unsafe.Pointer(&nestedBuf[0])), uintptr(len(nestedBuf))) + if int32(hr) >= 0 { + caps.NestedVirtProperty = true + } else { + caps.NestedVirtProbeError = fmt.Sprintf("0x%08x", uint32(hr)) + } + return caps +} + +// ProcessCPUTime returns total kernel + user CPU time consumed by pid. +func ProcessCPUTime(pid uint32) (time.Duration, bool) { + if pid == 0 { + return 0, false + } + h, _, _ := procOpenProcess.Call(uintptr(processQueryLimitedInfo), 0, uintptr(pid)) + if h == 0 { + return 0, false + } + defer procCloseHandle.Call(h) + + var creation, exit, kernel, user syscall.Filetime + r, _, _ := procGetProcessTimes.Call( + h, + uintptr(unsafe.Pointer(&creation)), + uintptr(unsafe.Pointer(&exit)), + uintptr(unsafe.Pointer(&kernel)), + uintptr(unsafe.Pointer(&user)), + ) + if r == 0 { + return 0, false + } + total100ns := (uint64(kernel.HighDateTime)<<32 | uint64(kernel.LowDateTime)) + + (uint64(user.HighDateTime)<<32 | uint64(user.LowDateTime)) + return time.Duration(total100ns) * 100 * time.Nanosecond, true +} diff --git a/internal/installer/oc_cache.go b/internal/installer/oc_cache.go new file mode 100644 index 0000000..d806e22 --- /dev/null +++ b/internal/installer/oc_cache.go @@ -0,0 +1,195 @@ +package installer + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + "net" + "net/http" + "os" + "path/filepath" + "strings" + "time" +) + +// PinnedAsset describes a file that upstream `reims-util` caches under +// `$XDG_CACHE_HOME/reims-util/` and verifies by SHA-256 before +// downloading (reims-util 7867384 src/cache.rs:20-51). +type PinnedAsset struct { + Name string + URL string + SHA256 string + Step string +} + +// OcBinaryDataAsset matches upstream reims-util 7867384 +// (src/opencore/mod.rs:31-38). GitHub's `/archive/.zip` ignores Range +// requests (always answering HTTP 200 without Content-Length), which interacts +// with reims-util's 180s SEGMENT_BUDGET (src/http.rs:25, 291-297, 342-346) to +// silently truncate and restart from 0 every 3 minutes on slow connections. +// Pre-fetching it with an idle-read timeout avoids that loop while keeping +// exact SHA-256 verification. +var OcBinaryDataAsset = PinnedAsset{ + Name: "OcBinaryData-32500d5e3313f11cad00351ba1c6f9a4aa6cb0f7.zip", + URL: "https://github.com/acidanthera/OcBinaryData/archive/32500d5e3313f11cad00351ba1c6f9a4aa6cb0f7.zip", + SHA256: "1ced15b42352a3a6c1b76ca95951f337fa79899acfb4ed80f329191716623741", + Step: "downloading OpenCore's picker icons and boot chime", +} + +// ShouldPrefetchOcBinaryData returns true when the installed runtime uses the +// reims-util commit (7867384 / 0.1.0) whose pinned OcBinaryData matches +// OcBinaryDataAsset. +func ShouldPrefetchOcBinaryData(utilCommit, utilVersion string) bool { + c := strings.ToLower(strings.TrimSpace(utilCommit)) + if c != "" { + return strings.HasPrefix(c, "7867384") + } + return strings.Contains(utilVersion, "0.1.0") +} + +// EnsureCachedAsset verifies that `/reims-util/` +// exists with the expected SHA-256, downloading it via HTTP with a per-read +// idle timeout (instead of a total-body timeout) if missing or corrupt. +func EnsureCachedAsset(ctx context.Context, xdgCacheDir string, asset PinnedAsset, client *http.Client, onUpdate func(Update)) error { + if strings.TrimSpace(xdgCacheDir) == "" { + return nil + } + cacheDir := filepath.Join(xdgCacheDir, "reims-util") + dest := filepath.Join(cacheDir, asset.Name) + if ok, _ := fileMatchesSHA256(dest, asset.SHA256); ok { + return nil + } + if err := os.MkdirAll(cacheDir, 0o755); err != nil { + return err + } + if client == nil { + client = newIdleHTTPClient(60 * time.Second) + } + if onUpdate != nil { + onUpdate(Update{Kind: KindStep, Message: asset.Step, Percent: -1}) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, asset.URL, nil) + if err != nil { + return err + } + req.Header.Set("User-Agent", "reims-go") + + resp, err := client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("%s answered HTTP %d", asset.URL, resp.StatusCode) + } + + part := dest + ".part" + f, err := os.Create(part) + if err != nil { + return err + } + h := sha256.New() + total := resp.ContentLength + if total < 0 { + total = 0 + } + buf := make([]byte, 64*1024) + var done int64 + for { + if err := ctx.Err(); err != nil { + f.Close() + _ = os.Remove(part) + return err + } + n, rerr := resp.Body.Read(buf) + if n > 0 { + if _, werr := f.Write(buf[:n]); werr != nil { + f.Close() + _ = os.Remove(part) + return werr + } + _, _ = h.Write(buf[:n]) + done += int64(n) + if onUpdate != nil { + onUpdate(Update{ + Kind: KindProgress, + Step: asset.Step, + Done: done, + Total: total, + Percent: percentOf(done, total), + }) + } + } + if rerr == io.EOF { + break + } + if rerr != nil { + f.Close() + _ = os.Remove(part) + return rerr + } + } + if err := f.Close(); err != nil { + _ = os.Remove(part) + return err + } + + got := hex.EncodeToString(h.Sum(nil)) + if !strings.EqualFold(got, asset.SHA256) { + _ = os.Remove(part) + return fmt.Errorf("%s SHA-256 mismatch: got %s, want %s", asset.Name, got, asset.SHA256) + } + _ = os.Remove(dest) + if err := os.Rename(part, dest); err != nil { + _ = os.Remove(part) + return err + } + return nil +} + +func fileMatchesSHA256(path, want string) (bool, error) { + f, err := os.Open(path) + if err != nil { + return false, err + } + defer f.Close() + h := sha256.New() + if _, err := io.Copy(h, f); err != nil { + return false, err + } + return strings.EqualFold(hex.EncodeToString(h.Sum(nil)), want), nil +} + +// idleTimeoutConn resets the socket read deadline before every Read, so a slow +// but steadily progressing stream is never killed by a fixed total duration. +type idleTimeoutConn struct { + net.Conn + idle time.Duration +} + +func (c *idleTimeoutConn) Read(p []byte) (int, error) { + if c.idle > 0 { + _ = c.Conn.SetReadDeadline(time.Now().Add(c.idle)) + } + return c.Conn.Read(p) +} + +func newIdleHTTPClient(idle time.Duration) *http.Client { + dialer := &net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second} + tr := &http.Transport{ + Proxy: http.ProxyFromEnvironment, + DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { + conn, err := dialer.DialContext(ctx, network, addr) + if err != nil { + return nil, err + } + return &idleTimeoutConn{Conn: conn, idle: idle}, nil + }, + TLSHandshakeTimeout: 30 * time.Second, + ResponseHeaderTimeout: idle, + } + return &http.Client{Transport: tr} +} diff --git a/internal/installer/oc_cache_test.go b/internal/installer/oc_cache_test.go new file mode 100644 index 0000000..99faff2 --- /dev/null +++ b/internal/installer/oc_cache_test.go @@ -0,0 +1,106 @@ +package installer + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" +) + +func TestEnsureCachedAssetDownloadsChunkedAndSkipsWhenCached(t *testing.T) { + payload := []byte(strings.Repeat("opencore-binary-data-", 512)) + sum := sha256.Sum256(payload) + wantHash := hex.EncodeToString(sum[:]) + + var hits atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + // Mimic GitHub codeload: HTTP 200 without Content-Length (chunked). + flusher, _ := w.(http.Flusher) + w.WriteHeader(http.StatusOK) + mid := len(payload) / 2 + _, _ = w.Write(payload[:mid]) + if flusher != nil { + flusher.Flush() + } + _, _ = w.Write(payload[mid:]) + })) + defer srv.Close() + + cacheRoot := t.TempDir() + asset := PinnedAsset{ + Name: "OcBinaryData-test.zip", + URL: srv.URL + "/archive.zip", + SHA256: wantHash, + Step: "downloading OpenCore's picker icons and boot chime", + } + + var updates []Update + if err := EnsureCachedAsset(context.Background(), cacheRoot, asset, srv.Client(), func(u Update) { + updates = append(updates, u) + }); err != nil { + t.Fatalf("EnsureCachedAsset failed: %v", err) + } + if hits.Load() != 1 { + t.Fatalf("expected 1 HTTP hit, got %d", hits.Load()) + } + dest := filepath.Join(cacheRoot, "reims-util", asset.Name) + gotBytes, err := os.ReadFile(dest) + if err != nil || string(gotBytes) != string(payload) { + t.Fatalf("cached file mismatch: err=%v len=%d", err, len(gotBytes)) + } + if len(updates) < 2 { + t.Fatalf("expected step + progress updates, got %d", len(updates)) + } + + // Second call must hit cache without another HTTP request. + if err := EnsureCachedAsset(context.Background(), cacheRoot, asset, srv.Client(), nil); err != nil { + t.Fatalf("second EnsureCachedAsset failed: %v", err) + } + if hits.Load() != 1 { + t.Fatalf("expected cache hit with 0 extra requests, total hits=%d", hits.Load()) + } +} + +func TestEnsureCachedAssetRejectsWrongHash(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte("corrupted")) + })) + defer srv.Close() + + cacheRoot := t.TempDir() + asset := PinnedAsset{ + Name: "OcBinaryData-bad.zip", + URL: srv.URL, + SHA256: strings.Repeat("0", 64), + Step: "downloading", + } + if err := EnsureCachedAsset(context.Background(), cacheRoot, asset, srv.Client(), nil); err == nil { + t.Fatalf("expected hash mismatch error") + } + dest := filepath.Join(cacheRoot, "reims-util", asset.Name) + if _, err := os.Stat(dest); !os.IsNotExist(err) { + t.Fatalf("corrupted file should not exist at %s", dest) + } + if _, err := os.Stat(dest + ".part"); !os.IsNotExist(err) { + t.Fatalf("part file should be cleaned up on mismatch") + } +} + +func TestShouldPrefetchOcBinaryData(t *testing.T) { + if !ShouldPrefetchOcBinaryData("7867384abcdef", "reims-util 0.1.0") { + t.Fatalf("expected true for pinned commit 7867384") + } + if !ShouldPrefetchOcBinaryData("", "reims-util 0.1.0") { + t.Fatalf("expected true for schema-1 0.1.0") + } + if ShouldPrefetchOcBinaryData("deadbeef1234", "reims-util 0.2.0") { + t.Fatalf("expected false for newer util commit") + } +} diff --git a/internal/qmp/watcher.go b/internal/qmp/watcher.go index a2b6dd2..33f68d0 100644 --- a/internal/qmp/watcher.go +++ b/internal/qmp/watcher.go @@ -62,10 +62,20 @@ func isManagedQMPTarget(arg string) bool { // capabilities, and waits for a SHUTDOWN event. It returns true iff the VM exited // because the guest requested a reset (`reason == "guest-reset"` under `-no-reboot`). func WatchForGuestReset(ctx context.Context, addr string) (bool, error) { - conn, err := dialWithRetry(ctx, addr, 20*time.Second) + reason, err := WatchShutdownReason(ctx, addr) if err != nil { return false, err } + return reason == "guest-reset", nil +} + +// WatchShutdownReason waits for QEMU's SHUTDOWN event over QMP and returns its +// reason (e.g. "guest-reset", "guest-shutdown", "host-qmp-quit"), or "" on EOF. +func WatchShutdownReason(ctx context.Context, addr string) (string, error) { + conn, err := dialWithRetry(ctx, addr, 20*time.Second) + if err != nil { + return "", err + } defer conn.Close() go func() { @@ -80,13 +90,13 @@ func WatchForGuestReset(ctx context.Context, addr string) (bool, error) { // Read QMP greeting. if !reader.Scan() { if ctx.Err() != nil { - return false, ctx.Err() + return "", ctx.Err() } - return false, reader.Err() + return "", reader.Err() } if _, err := conn.Write([]byte("{\"execute\":\"qmp_capabilities\"}\n")); err != nil { - return false, err + return "", err } for reader.Scan() { @@ -99,13 +109,13 @@ func WatchForGuestReset(ctx context.Context, addr string) (bool, error) { continue } if ev.Event == "SHUTDOWN" { - return ev.Data.Reason == "guest-reset", nil + return ev.Data.Reason, nil } } if ctx.Err() != nil { - return false, ctx.Err() + return "", ctx.Err() } - return false, reader.Err() + return "", reader.Err() } func dialWithRetry(ctx context.Context, addr string, timeout time.Duration) (net.Conn, error) { diff --git a/tasks.go b/tasks.go index 6439bd5..0e4f51e 100644 --- a/tasks.go +++ b/tasks.go @@ -170,6 +170,20 @@ func (m *taskManager) cancel(id string) error { return nil } +func (m *taskManager) cancelAll() { + m.mu.Lock() + cancels := make([]context.CancelFunc, 0, len(m.tasks)) + for _, e := range m.tasks { + if e.cancel != nil { + cancels = append(cancels, e.cancel) + } + } + m.mu.Unlock() + for _, fn := range cancels { + fn() + } +} + func (m *taskManager) dismiss(id string) { m.mu.Lock() if e, ok := m.tasks[id]; ok && e.task.Status != TaskRunning { @@ -265,9 +279,15 @@ func (a *App) ensureTaskEmitter() { // once, so the log keeps the milestones without one line per percent. // finish closes the task with the command's error. func (a *App) ctlTaskWriter(kind, vm string) (w io.Writer, finish func(error)) { + _, w, finish = a.ctlTaskWriterWithCancel(kind, vm, nil) + return w, finish +} + +func (a *App) ctlTaskWriterWithCancel(kind, vm string, cancel context.CancelFunc) (id string, w io.Writer, finish func(error)) { a.ensureTaskEmitter() - id := tasks.start(kind, vm, vm, nil) + id = tasks.start(kind, vm, vm, cancel) lastStep := "" + lastLogAt := time.Now() trim := func(s string) string { return strings.TrimPrefix(s, vm+": ") } w = &logWriter{emit: func(line string) { u, ok := installer.ParseCtlLine(line) @@ -278,7 +298,15 @@ func (a *App) ctlTaskWriter(kind, vm string) (w io.Writer, finish func(error)) { u.Step = trim(u.Step) if u.Step != lastStep { lastStep = u.Step + lastLogAt = time.Now() a.emitLog(vm, u.Step) + } else if time.Since(lastLogAt) >= 30*time.Second { + lastLogAt = time.Now() + if u.Total > 0 { + a.emitLog(vm, fmt.Sprintf("%s: %.0f%% (%.1f / %.1f MB)", u.Step, u.Percent, float64(u.Done)/1e6, float64(u.Total)/1e6)) + } else if u.Done > 0 { + a.emitLog(vm, fmt.Sprintf("%s: %.1f MB", u.Step, float64(u.Done)/1e6)) + } } tasks.update(id, u) return @@ -286,7 +314,8 @@ func (a *App) ctlTaskWriter(kind, vm string) (w io.Writer, finish func(error)) { a.emitLog(vm, line) step := trim(u.Message) lastStep = step + lastLogAt = time.Now() tasks.update(id, installer.Update{Kind: installer.KindStep, Message: step, Percent: -1}) }} - return w, func(err error) { tasks.finish(id, "", err) } + return id, w, func(err error) { tasks.finish(id, "", err) } } diff --git a/vm_monitor.go b/vm_monitor.go new file mode 100644 index 0000000..fa67bcd --- /dev/null +++ b/vm_monitor.go @@ -0,0 +1,383 @@ +package main + +import ( + "context" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" +) + +// vmMonitors holds per-VM background log tailers & boot/install heartbeats. +var vmMonitors = struct { + mu sync.Mutex + seq uint64 + entries map[string]struct { + id uint64 + cancel context.CancelFunc + } +}{ + entries: map[string]struct { + id uint64 + cancel context.CancelFunc + }{}, +} + +func stopVMMonitor(name string) { + vmMonitors.mu.Lock() + if cur, ok := vmMonitors.entries[name]; ok { + cur.cancel() + delete(vmMonitors.entries, name) + } + vmMonitors.mu.Unlock() +} + +func stopAllVMMonitors() { + vmMonitors.mu.Lock() + for name, cur := range vmMonitors.entries { + cur.cancel() + delete(vmMonitors.entries, name) + } + vmMonitors.mu.Unlock() +} + +func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Time) { + stopVMMonitor(name) + if detail.Directory == "" { + return + } + ctx, cancel := context.WithCancel(a.baseCtx()) + vmMonitors.mu.Lock() + vmMonitors.seq++ + myID := vmMonitors.seq + vmMonitors.entries[name] = struct { + id uint64 + cancel context.CancelFunc + }{id: myID, cancel: cancel} + vmMonitors.mu.Unlock() + + a.mu.Lock() + loc := a.cfg.Locale + a.mu.Unlock() + + go func() { + defer func() { + cancel() + vmMonitors.mu.Lock() + if cur, ok := vmMonitors.entries[name]; ok && cur.id == myID { + delete(vmMonitors.entries, name) + } + vmMonitors.mu.Unlock() + }() + + serialPath := filepath.Join(detail.Directory, "logs", "serial.log") + qemuPath := filepath.Join(detail.Directory, "logs", "qemu.log") + diskPath := filepath.Join(detail.Directory, "disk.qcow2") + + // Only read logs belonging to this boot (ignore files last touched before StartVM). + serialOff := initialLogOffset(serialPath, startAt) + qemuOff := initialLogOffset(qemuPath, startAt) + var serialPartial, qemuPartial string + seenEvents := map[string]bool{} + + lastDiskSize := fileSizeBytes(diskPath) + var lastCPU time.Duration + var hasLastCPU bool + lastSampleAt := time.Now() + idleStreak := 0 + stallWarned := false + + logTicker := time.NewTicker(1500 * time.Millisecond) + hbTicker := time.NewTicker(30 * time.Second) + defer logTicker.Stop() + defer hbTicker.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-logTicker.C: + var newLines []string + serialOff, serialPartial, newLines = readNewLogLines(serialPath, serialOff, serialPartial) + for _, line := range newLines { + if key, msg := parseSerialMilestone(loc, line); msg != "" && !seenEvents[key] { + seenEvents[key] = true + a.emitLog(name, msg) + } + } + qemuOff, qemuPartial, newLines = readNewLogLines(qemuPath, qemuOff, qemuPartial) + for _, line := range newLines { + if key, msg := parseQemuMilestone(loc, line); msg != "" { + if key != "" && seenEvents[key] { + continue + } + if key != "" { + seenEvents[key] = true + } + a.emitLog(name, msg) + } + } + case <-hbTicker.C: + pid, running := a.currentVMPID(ctx, name) + if !running { + if loc == i18n.ZhCN { + a.emitLog(name, "[状态] 虚拟机进程已退出") + } else { + a.emitLog(name, "[state] VM process exited") + } + return + } + now := time.Now() + dt := now.Sub(lastSampleAt).Seconds() + if dt <= 0 { + dt = 30 + } + lastSampleAt = now + + diskNow := fileSizeBytes(diskPath) + diskDelta := diskNow - lastDiskSize + if diskDelta < 0 { + diskDelta = 0 + } + lastDiskSize = diskNow + + cpuPct := -1.0 + if cpuNow, ok := host.ProcessCPUTime(uint32(pid)); ok { + if hasLastCPU && cpuNow >= lastCPU { + cpuPct = (cpuNow - lastCPU).Seconds() / dt * 100 + } + lastCPU = cpuNow + hasLastCPU = true + } + + elapsed := time.Since(startAt) + inEarlyOrInstall := detail.HasInstaller || elapsed < 15*time.Minute + if !inEarlyOrInstall { + continue + } + + if diskDelta < 64*1024 && cpuPct >= 0 && cpuPct < 3.0 { + idleStreak++ + } else { + idleStreak = 0 + stallWarned = false + } + + if msg := formatBootHeartbeat(loc, elapsed, diskNow, diskDelta, cpuPct); msg != "" { + a.emitLog(name, msg) + } + if idleStreak >= 3 && !stallWarned { + stallWarned = true + if loc == i18n.ZhCN { + a.emitLog(name, "[警告] 连续 90 秒几乎无 CPU 与磁盘写入,虚拟机可能停在启动或重启阶段;可切到「QEMU」页签排查,或下次引导时按住 Win+V 查看内核输出") + } else { + a.emitLog(name, "[warn] Almost no CPU or disk activity for 90s; VM may be stalled during boot/reboot. Check the QEMU log tab or hold Win+V on next boot for verbose output") + } + } + } + } + }() +} + +func (a *App) currentVMPID(ctx context.Context, name string) (int, bool) { + vms, err := a.listVMsInternal(ctx) + if err != nil { + return 0, true // keep watching on transient error + } + for _, vm := range vms { + if vm.Name == name { + if vm.State == "running" && vm.PID != nil && *vm.PID > 0 { + return *vm.PID, true + } + return 0, false + } + } + return 0, false +} + +func initialLogOffset(path string, startAt time.Time) int64 { + info, err := os.Stat(path) + if err != nil { + return 0 + } + // If the log file has not been rotated/modified since before StartVM, start at its end. + if info.ModTime().Before(startAt.Add(-500 * time.Millisecond)) { + return info.Size() + } + return 0 +} + +func readNewLogLines(path string, offset int64, partial string) (int64, string, []string) { + info, err := os.Stat(path) + if err != nil { + return offset, partial, nil + } + // Log rotated or recreated (e.g., new boot overwrote serial.log / qemu.log). + if info.Size() < offset { + offset = 0 + partial = "" + } + if info.Size() == offset { + return offset, partial, nil + } + f, err := os.Open(path) + if err != nil { + return offset, partial, nil + } + defer f.Close() + if _, err := f.Seek(offset, io.SeekStart); err != nil { + return offset, partial, nil + } + const maxChunk = 256 * 1024 + data, err := io.ReadAll(io.LimitReader(f, maxChunk)) + if err != nil || len(data) == 0 { + return offset, partial, nil + } + offset += int64(len(data)) + combined := partial + string(data) + parts := strings.Split(combined, "\n") + partial = parts[len(parts)-1] + lines := make([]string, 0, len(parts)-1) + for _, p := range parts[:len(parts)-1] { + s := strings.TrimSpace(strings.TrimRight(p, "\r")) + if s != "" { + lines = append(lines, s) + } + } + return offset, partial, lines +} + +func parseSerialMilestone(loc i18n.Locale, line string) (key, msg string) { + switch { + case strings.Contains(line, "BdsDxe: starting Boot"): + if loc == i18n.ZhCN { + return "serial:boot", "[引导] UEFI 正在启动 OpenCore 引导程序" + } + return "serial:boot", "[boot] UEFI starting OpenCore bootloader" + case strings.Contains(line, "#[EB|LOG:HANDOFF TO XNU]"), strings.Contains(line, "End of efiboot serial output"): + if loc == i18n.ZhCN { + return "serial:xnu", "[引导] OpenCore 已交接 macOS 内核(XNU 正在加载系统与驱动)" + } + return "serial:xnu", "[boot] OpenCore handed off to macOS kernel (XNU loading)" + default: + return "", "" + } +} + +func parseQemuMilestone(loc i18n.Locale, line string) (key, msg string) { + // Skip verbose periodic rt-diag stat dumps. + if strings.Contains(line, "rt-diag") || strings.Contains(line, "rt-presents") { + return "", "" + } + if idx := strings.Index(line, "the rt platform's device: "); idx >= 0 { + rest := line[idx+len("the rt platform's device: "):] + if semi := strings.IndexByte(rest, ';'); semi >= 0 { + rest = rest[:semi] + } + if loc == i18n.ZhCN { + return "qemu:gpu", "[图形] vGPU 已初始化:" + strings.TrimSpace(rest) + } + return "qemu:gpu", "[gpu] vGPU initialized: " + strings.TrimSpace(rest) + } + if strings.Contains(line, "windows open through SDL") { + if loc == i18n.ZhCN { + return "qemu:window", "[窗口] 虚拟机显示窗口已打开" + } + return "qemu:window", "[window] VM display window opened" + } + if strings.Contains(line, "the device was reset") { + if loc == i18n.ZhCN { + return "qemu:reset", "[图形] vGPU 设备已重置" + } + return "qemu:reset", "[gpu] vGPU device reset" + } + // Known benign WHPX advisory: emit once as info/warn instead of repeating. + if strings.Contains(line, "no pre-fault of the pool") { + return "qemu:prefault", "" + } + low := strings.ToLower(line) + if strings.Contains(line, "WHPX:") || + strings.Contains(line, " ERROR ") || + strings.Contains(low, "error:") || + strings.Contains(low, "fatal:") || + strings.Contains(low, "failed to ") { + return "", "[QEMU] " + line + } + return "", "" +} + +func formatBootHeartbeat(loc i18n.Locale, elapsed time.Duration, diskBytes, diskDelta int64, cpuPct float64) string { + dur := fmt.Sprintf("%dm%02ds", int(elapsed.Minutes()), int(elapsed.Seconds())%60) + diskStr := fmt.Sprintf("%.2f GB", float64(diskBytes)/(1024*1024*1024)) + deltaStr := "" + if diskDelta >= 1024*1024 { + deltaStr = fmt.Sprintf(" (+%.1f MB)", float64(diskDelta)/(1024*1024)) + } + if loc == i18n.ZhCN { + if cpuPct >= 0 { + return fmt.Sprintf("[状态] 运行中(%s)· 磁盘占用 %s%s · QEMU CPU %.0f%%", dur, diskStr, deltaStr, cpuPct) + } + return fmt.Sprintf("[状态] 运行中(%s)· 磁盘占用 %s%s", dur, diskStr, deltaStr) + } + if cpuPct >= 0 { + return fmt.Sprintf("[state] Running (%s) · disk %s%s · QEMU CPU %.0f%%", dur, diskStr, deltaStr, cpuPct) + } + return fmt.Sprintf("[state] Running (%s) · disk %s%s", dur, diskStr, deltaStr) +} + +func fileSizeBytes(path string) int64 { + info, err := os.Stat(path) + if err != nil { + return 0 + } + return info.Size() +} + +func (a *App) emitStartSummary(name string, detail reims.VMDetail, rep host.Report, qmpAddr string) { + a.mu.Lock() + loc := a.cfg.Locale + rtCommit := a.cfg.ActiveRuntime + pinPCores := a.cfg.AutoPinPCores + a.mu.Unlock() + if rtCommit == "" { + rtCommit = "auto" + } + irqMode := "default" + lowExtra := strings.ToLower(detail.ExtraArgs) + switch { + case strings.Contains(lowExtra, "kernel-irqchip=off"): + irqMode = "off" + case strings.Contains(lowExtra, "kernel-irqchip=on"): + irqMode = "on" + } + if loc == i18n.ZhCN { + coldStr := "关闭" + if qmpAddr != "" { + coldStr = "开启" + } + pinStr := "关" + if pinPCores && rep.HasHybridCores { + pinStr = fmt.Sprintf("开(%dP)", rep.PCoreCount) + } + a.emitLog(name, fmt.Sprintf("[启动] 运行时 %s · %d 核 / %s(可用提交内存 %.1f GB)· 图形 %s · 磁盘 %s · irqchip=%s · 绑P核=%s · Win10冷重启=%s", + rtCommit, detail.CPUs, detail.Memory, rep.CommitAvailGB, detail.Graphics, strings.ToUpper(detail.DiskController), irqMode, pinStr, coldStr)) + return + } + coldStr := "off" + if qmpAddr != "" { + coldStr = "on" + } + pinStr := "off" + if pinPCores && rep.HasHybridCores { + pinStr = fmt.Sprintf("on(%dP)", rep.PCoreCount) + } + 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", + rtCommit, detail.CPUs, detail.Memory, rep.CommitAvailGB, detail.Graphics, strings.ToUpper(detail.DiskController), irqMode, pinStr, coldStr)) +} diff --git a/vm_monitor_test.go b/vm_monitor_test.go new file mode 100644 index 0000000..c76ed61 --- /dev/null +++ b/vm_monitor_test.go @@ -0,0 +1,50 @@ +package main + +import ( + "strings" + "testing" + "time" + + "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/i18n" +) + +func TestParseSerialAndQemuMilestones(t *testing.T) { + k, msg := parseSerialMilestone(i18n.ZhCN, `BdsDxe: starting Boot0002 "UEFI QEMU HARDDISK"`) + if k != "serial:boot" || !strings.Contains(msg, "OpenCore") { + t.Fatalf("serial boot = %q, %q", k, msg) + } + k, msg = parseSerialMilestone(i18n.EnUS, `#[EB|LOG:HANDOFF TO XNU] _`) + if k != "serial:xnu" || !strings.Contains(msg, "XNU") { + t.Fatalf("serial xnu = %q, %q", k, msg) + } + + k, msg = parseQemuMilestone(i18n.ZhCN, `reims-vgpu INFO reims_vgpu_vulkan::rt_platform: the rt platform's device: NVIDIA GeForce RTX 4070 Ti (10de:2782), driver NVIDIA 610.88; instance extensions`) + if k != "qemu:gpu" || !strings.Contains(msg, "RTX 4070 Ti") { + t.Fatalf("qemu gpu = %q, %q", k, msg) + } + k, msg = parseQemuMilestone(i18n.ZhCN, `reims-vgpu: rt-diag allocation sites, rt-presents 71011`) + if msg != "" { + t.Fatalf("expected rt-diag dump to be ignored, got %q", msg) + } + k, msg = parseQemuMilestone(i18n.ZhCN, `qemu: WHPX: Unexpected VP exit code 4`) + if k != "" || !strings.Contains(msg, "WHPX: Unexpected VP exit code 4") { + t.Fatalf("expected WHPX error to pass through, got k=%q msg=%q", k, msg) + } +} + +func TestFormatBootHeartbeatAndRedactLogLine(t *testing.T) { + hb := formatBootHeartbeat(i18n.ZhCN, 4*time.Minute+30*time.Second, 15*1024*1024*1024, 256*1024*1024, 142.4) + if !strings.Contains(hb, "4m30s") || !strings.Contains(hb, "15.00 GB") || !strings.Contains(hb, "+256.0 MB") || !strings.Contains(hb, "142%") { + t.Fatalf("unexpected heartbeat: %q", hb) + } + + redacted := reims.RedactLogLine("network user, mac 52:54:00:bc:bc:0d, ssh on 127.0.0.1:2222") + if strings.Contains(redacted, "bc:bc:0d") || !strings.Contains(redacted, "mac [redacted]") { + t.Fatalf("MAC not redacted: %q", redacted) + } + redactedSerial := reims.RedactLogLine("OpenCore presents the VM as an iMac20,1, serial C02FDGY9PN5T") + if strings.Contains(redactedSerial, "C02FDGY9PN5T") || !strings.Contains(redactedSerial, "serial [redacted]") { + t.Fatalf("serial not redacted: %q", redactedSerial) + } +}