Files
Reims-Go/internal/host/host_windows.go
T
千川白浪andClaude Opus 5.5 4bea654736 feat: add Wails desktop GUI and stage-0 UI redesign
Wails shell over the existing Go core (app.go, main.go, wails.json,
build/), with a React frontend for the VM list, VM detail, host page,
create wizard and settings, plus process helpers for the driver and
runtime packages.

UI redesign stage 0 (docs/ui-redesign.md):
- VM actions live in the page header: one primary action per state,
  icon-only secondary actions with tooltips, the rest in a "..." menu
- install guide is a single card with the only "eject installer" button
- summary is an icon + value row; paths, ICD, CPU model and runtime hash
  moved to a collapsed "technical details" section
- logs no longer auto-open; a status bar shows merged download progress
  and an error count; the log view sticks to the bottom
- busy states on actions, toasts for results, custom delete dialog with
  "keep disk files"
- design tokens, Windows font stack, integer type scale, no inline styles
- keyboard: sidebar listbox navigation, focus rings, Ctrl+N / Ctrl+, / Ctrl+L
- copy rewritten per the restraint rules in §4.5
- Radix primitives and lucide icons replace hand-rolled widgets

Backend: OpenVMFolder binding to show a VM's directory in Explorer.
Docs: shell-design.md revised for decisions D1 and D4.
Vite dev server pinned to 127.0.0.1 so `wails dev` can reach it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 03:09:39 -07:00

296 lines
8.0 KiB
Go

//go:build windows
package host
import (
"encoding/binary"
"fmt"
"path/filepath"
"runtime"
"strings"
"syscall"
"unsafe"
)
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")
advapi32 = syscall.NewLazyDLL("advapi32.dll")
procRegOpenKeyExW = advapi32.NewProc("RegOpenKeyExW")
procRegQueryValueExW = advapi32.NewProc("RegQueryValueExW")
procRegCloseKey = advapi32.NewProc("RegCloseKey")
shell32 = syscall.NewLazyDLL("shell32.dll")
procShellExecuteW = shell32.NewProc("ShellExecuteW")
)
const (
hkeyLocalMachine = 0x80000002
keyRead = 0x20019
regSZ = 1
regExpandSZ = 2
regMultiSZ = 7
processSetInformation = 0x0200
whvCapHypervisorPresent = 0x00000001
)
type memoryStatusEx struct {
Length uint32
MemoryLoad uint32
TotalPhys uint64
AvailPhys uint64
TotalPageFile uint64
AvailPageFile uint64
TotalVirtual uint64
AvailVirtual uint64
AvailExtendedVirtual uint64
}
// Inspect collects Windows host capabilities without requiring administrator privileges.
func Inspect(dataRoot string) Report {
rep := Report{
OS: "windows",
Arch: runtime.GOARCH,
LogicalCPUs: runtime.NumCPU(),
DataRoot: dataRoot,
WHPX: probeWHPX(),
GPUs: probeVulkanGPUs(),
}
rep.RecommendedGPU = PickRecommendedGPU(rep.GPUs)
if cores, pCount, eCount, pMask, pLPs, eLPs, ok := probeHybridTopology(); ok {
rep.PhysicalCores = cores
rep.PCoreCount = pCount
rep.ECoreCount = eCount
rep.HasHybridCores = eCount > 0
rep.PCoreMask = pMask
rep.PCoreMaskHex = fmt.Sprintf("0x%X", pMask)
rep.PCoreLogicalCPUs = pLPs
rep.ECoreLogicalCPUs = eLPs
}
if totalGB, availGB, ok := probeMemoryGB(); ok {
rep.TotalRAMGB = totalGB
rep.AvailRAMGB = availGB
}
if freeGB, ok := probeFreeDiskGB(dataRoot); ok {
rep.FreeDiskGB = freeGB
}
return rep
}
// PinProcessToPCores restricts the given PID's affinity mask to P-cores.
func PinProcessToPCores(pid uint32, mask uint64) error {
if mask == 0 {
return fmt.Errorf("invalid affinity mask 0")
}
h, _, err := procOpenProcess.Call(uintptr(processSetInformation), 0, uintptr(pid))
if h == 0 {
return fmt.Errorf("OpenProcess(%d): %w", pid, err)
}
defer procCloseHandle.Call(h)
r, _, err := procSetProcessAffinityMask.Call(h, uintptr(mask))
if r == 0 {
return fmt.Errorf("SetProcessAffinityMask(%d, 0x%X): %w", pid, mask, err)
}
return nil
}
// EnableWHPXElevated invokes a standard Windows UAC prompt to enable Windows Hypervisor Platform.
func EnableWHPXElevated() error {
verb, _ := syscall.UTF16PtrFromString("runas")
file, _ := syscall.UTF16PtrFromString("powershell.exe")
params, _ := syscall.UTF16PtrFromString(`-NoProfile -Command "Enable-WindowsOptionalFeature -Online -FeatureName HypervisorPlatform -All -NoRestart; Write-Host 'Done. Please restart Windows.'; Start-Sleep -Seconds 3"`)
r, _, err := procShellExecuteW.Call(
0,
uintptr(unsafe.Pointer(verb)),
uintptr(unsafe.Pointer(file)),
uintptr(unsafe.Pointer(params)),
0,
1, // SW_SHOWNORMAL
)
if r <= 32 {
return fmt.Errorf("ShellExecuteW runas failed (code %d): %w", r, err)
}
return nil
}
func probeWHPX() WHPXState {
mod := syscall.NewLazyDLL("WinHvPlatform.dll")
if err := mod.Load(); err != nil {
return WHPXMissing
}
proc := mod.NewProc("WHvGetCapability")
if err := proc.Find(); err != nil {
return WHPXMissing
}
var capVal uint64
var written uint32
hr, _, _ := proc.Call(
uintptr(whvCapHypervisorPresent),
uintptr(unsafe.Pointer(&capVal)),
uintptr(unsafe.Sizeof(capVal)),
uintptr(unsafe.Pointer(&written)),
)
if int32(hr) < 0 {
return WHPXNoHypervisor
}
if capVal&1 != 0 {
return WHPXReady
}
return WHPXNoHypervisor
}
func probeHybridTopology() (phys, pCount, eCount int, pMask uint64, pLPs, eLPs []int, ok bool) {
var bufLen uint32
procGetLogicalProcessorInformationEx.Call(0, 0, uintptr(unsafe.Pointer(&bufLen)))
if bufLen == 0 {
return
}
buf := make([]byte, bufLen)
r, _, _ := procGetLogicalProcessorInformationEx.Call(
0, // RelationProcessorCore
uintptr(unsafe.Pointer(&buf[0])),
uintptr(unsafe.Pointer(&bufLen)),
)
if r == 0 {
return
}
type coreRec struct {
eff byte
mask uint64
}
var cores []coreRec
var maxEff byte
for off := uint32(0); off+48 <= bufLen; {
size := binary.LittleEndian.Uint32(buf[off+4 : off+8])
if size < 48 || off+size > bufLen {
break
}
eff := buf[off+9]
mask := binary.LittleEndian.Uint64(buf[off+32 : off+40])
if eff > maxEff {
maxEff = eff
}
cores = append(cores, coreRec{eff: eff, mask: mask})
off += size
}
if len(cores) == 0 {
return
}
phys = len(cores)
var eMask uint64
for _, c := range cores {
if c.eff == maxEff {
pCount++
pMask |= c.mask
} else {
eCount++
eMask |= c.mask
}
}
for i := 0; i < 64; i++ {
if (pMask>>uint(i))&1 != 0 {
pLPs = append(pLPs, i)
}
if (eMask>>uint(i))&1 != 0 {
eLPs = append(eLPs, i)
}
}
ok = true
return
}
func probeMemoryGB() (totalGB, availGB float64, ok bool) {
var ms memoryStatusEx
ms.Length = uint32(unsafe.Sizeof(ms))
r, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&ms)))
if r == 0 {
return 0, 0, false
}
const gb = 1024 * 1024 * 1024
return float64(ms.TotalPhys) / gb, float64(ms.AvailPhys) / gb, true
}
func probeFreeDiskGB(path string) (float64, bool) {
vol := filepath.VolumeName(path)
if vol != "" {
path = vol + `\`
}
p, err := syscall.UTF16PtrFromString(path)
if err != nil {
return 0, false
}
var freeBytesAvail, totalBytes, totalFree uint64
r, _, _ := procGetDiskFreeSpaceExW.Call(
uintptr(unsafe.Pointer(p)),
uintptr(unsafe.Pointer(&freeBytesAvail)),
uintptr(unsafe.Pointer(&totalBytes)),
uintptr(unsafe.Pointer(&totalFree)),
)
if r == 0 {
return 0, false
}
return float64(freeBytesAvail) / (1024 * 1024 * 1024), true
}
func probeVulkanGPUs() []GPUInfo {
const baseKey = `SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}`
var out []GPUInfo
for i := 0; i < 32; i++ {
sub := fmt.Sprintf(`%s\%04d`, baseKey, i)
desc, okDesc := regReadString(hkeyLocalMachine, sub, "DriverDesc")
if !okDesc || desc == "" {
continue
}
icd, _ := regReadString(hkeyLocalMachine, sub, "VulkanDriverName")
if icd == "" {
continue
}
out = append(out, GPUInfo{
Name: desc,
VulkanICD: icd,
Kind: ClassifyGPU(desc),
})
}
return out
}
func regReadString(root uintptr, subKey, valueName string) (string, bool) {
sk, err := syscall.UTF16PtrFromString(subKey)
if err != nil {
return "", false
}
var hKey uintptr
r, _, _ := procRegOpenKeyExW.Call(root, uintptr(unsafe.Pointer(sk)), 0, keyRead, uintptr(unsafe.Pointer(&hKey)))
if r != 0 {
return "", false
}
defer procRegCloseKey.Call(hKey)
vn, err := syscall.UTF16PtrFromString(valueName)
if err != nil {
return "", false
}
var typ, size uint32
r, _, _ = procRegQueryValueExW.Call(hKey, uintptr(unsafe.Pointer(vn)), 0, uintptr(unsafe.Pointer(&typ)), 0, uintptr(unsafe.Pointer(&size)))
if r != 0 || size == 0 {
return "", false
}
buf := make([]uint16, (size+1)/2)
r, _, _ = procRegQueryValueExW.Call(hKey, uintptr(unsafe.Pointer(vn)), 0, uintptr(unsafe.Pointer(&typ)), uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&size)))
if r != 0 {
return "", false
}
if typ != regSZ && typ != regExpandSZ && typ != regMultiSZ {
return "", false
}
// For REG_MULTI_SZ, take the first NUL-terminated entry (64-bit Vulkan ICD JSON).
return strings.TrimSpace(syscall.UTF16ToString(buf)), true
}