diff --git a/.github/workflows/build-runtime.yml b/.github/workflows/build-runtime.yml new file mode 100644 index 0000000..8666332 --- /dev/null +++ b/.github/workflows/build-runtime.yml @@ -0,0 +1,103 @@ +name: Build Portable Runtime (Candidate) + +on: + workflow_dispatch: + inputs: + upstream_commit: + description: "Pinned steelbrain/reims-vgpu commit SHA" + required: true + default: "3731afd" + publish_candidate: + description: "Publish as GitHub prerelease (candidate channel only; never stable)" + type: boolean + default: false + +permissions: + contents: write + +jobs: + build-runtime: + runs-on: windows-latest + timeout-minutes: 120 + steps: + - uses: actions/checkout@v4 + + - name: Setup MSYS2 CLANG64 + uses: msys2/setup-msys2@v2 + with: + msystem: CLANG64 + update: true + install: >- + git zstd tar mingw-w64-clang-x86_64-toolchain + mingw-w64-clang-x86_64-meson mingw-w64-clang-x86_64-ninja + mingw-w64-clang-x86_64-pkgconf mingw-w64-clang-x86_64-glib2 + mingw-w64-clang-x86_64-pixman mingw-w64-clang-x86_64-SDL2 + mingw-w64-clang-x86_64-vulkan-loader mingw-w64-clang-x86_64-python + + - name: Checkout upstream reims-vgpu & verify patch queue + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + $work = Join-Path $env:RUNNER_TEMP 'reims-vgpu' + git clone https://github.com/steelbrain/reims-vgpu.git $work + git -C $work checkout ${{ inputs.upstream_commit }} + # Verify local patches apply cleanly; fail hard on mismatch (AGENTS.md rule 4). + if (Test-Path 'patches/reims-vgpu-cargo-lock.patch') { + git -C $work apply --check (Resolve-Path 'patches/reims-vgpu-cargo-lock.patch') + git -C $work apply (Resolve-Path 'patches/reims-vgpu-cargo-lock.patch') + } + $short = (git -C $work rev-parse --short HEAD).Trim() + "UPSTREAM_DIR=$work" | Out-File -FilePath $env:GITHUB_ENV -Append + "SHORT_COMMIT=$short" | Out-File -FilePath $env:GITHUB_ENV -Append + + - name: Build upstream runtime in MSYS2 CLANG64 + shell: msys2 {0} + run: | + set -euo pipefail + cd "$UPSTREAM_DIR" + # Fetch vendor/qemu at pinned commit and verify QEMU patches before building. + if [ -f scripts/install.ps1 ]; then + echo "Upstream checkout ready at $(git rev-parse HEAD)" + fi + if [ -d vendor/qemu/.git ]; then + for p in "$GITHUB_WORKSPACE"/patches/qemu-*.patch; do + [ -f "$p" ] || continue + git -C vendor/qemu apply --check "$p" + git -C vendor/qemu apply "$p" + done + fi + + - name: Package candidate runtime & source archives + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + $outDir = Join-Path $env:RUNNER_TEMP 'releases' + New-Item -ItemType Directory -Force -Path $outDir | Out-Null + if (Test-Path (Join-Path $env:CARGO_HOME 'bin\reims-ctl.exe')) { + pwsh -File scripts/pack-runtime.ps1 ` + -ReimsRepo $env:UPSTREAM_DIR ` + -OutDir $outDir ` + -TempRoot $env:RUNNER_TEMP ` + -Channel candidate + } else { + Write-Host "Build step must populate CARGO_HOME/bin/reims-ctl.exe and QEMU dir before pack-runtime.ps1" + exit 1 + } + + - name: Upload candidate artifacts + uses: actions/upload-artifact@v4 + with: + name: reims-runtime-win-x64-${{ env.SHORT_COMMIT }}-candidate + path: ${{ runner.temp }}/releases/* + + - name: Publish candidate prerelease (never stable) + if: ${{ inputs.publish_candidate }} + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + shell: pwsh + run: | + $tag = "runtime-$($env:SHORT_COMMIT)" + gh release create $tag "$($env:RUNNER_TEMP)/releases/*" ` + --prerelease ` + --title "Portable Runtime $tag (candidate)" ` + --notes "Automated candidate build from upstream $($env:SHORT_COMMIT). Must pass scripts/smoke-runtime.ps1 on a real Windows host and human review before promotion to stable." diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ff81b8d --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,43 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + verify: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + - uses: pnpm/action-setup@v4 + with: + version: 10 + + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: pnpm + cache-dependency-path: frontend/pnpm-lock.yaml + + - name: Go test & vet + shell: pwsh + run: | + go test ./... + go vet ./... + + - name: Frontend build + shell: pwsh + run: | + pnpm --dir frontend install --frozen-lockfile + pnpm --dir frontend build + + - name: Build CLI binary + shell: pwsh + run: go build -trimpath -o build/bin/reims-go-cli.exe ./cmd/reims-go diff --git a/app.go b/app.go index 833fa30..31d1b96 100644 --- a/app.go +++ b/app.go @@ -55,6 +55,7 @@ type App struct { nextWatcherID uint64 stopPoll context.CancelFunc guestTools *guesttools.Server + recentLogs []string needsSetup bool } @@ -220,13 +221,21 @@ func (a *App) listVMsInternal(ctx context.Context) ([]reims.VMListItem, error) { } func (a *App) emitLog(source, line string) { + redacted := reims.RedactLogLine(line) + ts := time.Now().Format("15:04:05") + a.mu.Lock() + a.recentLogs = append(a.recentLogs, fmt.Sprintf("%s [%s] %s", ts, source, redacted)) + if len(a.recentLogs) > 1000 { + a.recentLogs = a.recentLogs[len(a.recentLogs)-1000:] + } + a.mu.Unlock() if a.ctx == nil { return } wailsRuntime.EventsEmit(a.ctx, "reims:log", map[string]string{ - "ts": time.Now().Format("15:04:05"), + "ts": ts, "source": source, - "line": reims.RedactLogLine(line), + "line": redacted, }) } diff --git a/clone_flow.go b/clone_flow.go new file mode 100644 index 0000000..41707c5 --- /dev/null +++ b/clone_flow.go @@ -0,0 +1,123 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/host" + rt "github.com/Nwflower/reims-go/internal/runtime" + wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" +) + +// CloneVMCoW derives a new VM instantaneously from a stopped source VM using a +// qcow2 copy-on-write overlay (`qemu-img create -f qcow2 -b -F qcow2`) +// so the source golden disk is never mutated while the clone gets its own fresh +// OpenCore identity (SMBIOS/serial/MAC) via `reims-ctl create --disk --disk-mode in-place`. +func (a *App) CloneVMCoW(sourceName, cloneName string) error { + cloneName = strings.TrimSpace(cloneName) + if cloneName == "" { + return fmt.Errorf("clone VM name is required") + } + if strings.EqualFold(sourceName, cloneName) { + return fmt.Errorf("clone name must differ from source VM") + } + + a.mu.Lock() + cfgCopy := *a.cfg + a.mu.Unlock() + active, err := rt.ResolveActive(&cfgCopy) + if err != nil { + return err + } + c := reims.NewClient(&cfgCopy, *active) + ctx := a.baseCtx() + + src, err := a.GetVMDetail(sourceName) + if err != nil { + return err + } + if a.isVMRunning(ctx, c, sourceName, src) { + return fmt.Errorf("stop %s before deriving a CoW clone so the backing disk is clean", sourceName) + } + if src.HasInstaller { + return fmt.Errorf("exit recovery mode on %s before deriving a CoW clone", sourceName) + } + srcDisk := src.Disk + if srcDisk != "" && !filepath.IsAbs(srcDisk) && src.Directory != "" { + srcDisk = filepath.Join(src.Directory, srcDisk) + } + if srcDisk == "" { + return fmt.Errorf("source VM %s has no disk path", sourceName) + } + if _, err := os.Stat(srcDisk); err != nil { + return fmt.Errorf("source disk not found (%s): %w", srcDisk, err) + } + + // Validate clone name and check for name collisions. + rep := host.Inspect(cfgCopy.DataRoot) + nameCheck := reims.ValidateCreate(reims.CreateOpts{Name: cloneName, CPUs: max(src.CPUs, 1), Memory: src.Memory}, rep) + for _, iss := range nameCheck { + if iss.Field == "name" { + return fmt.Errorf("%s", iss.Message) + } + } + if existing, err := c.List(ctx); err == nil { + for _, vm := range existing { + if strings.EqualFold(vm.Name, cloneName) { + return fmt.Errorf("VM %q already exists", cloneName) + } + } + } + + overlayPath := filepath.Join(cfgCopy.ImagesDir(), fmt.Sprintf("cow-%s.qcow2", cloneName)) + if _, err := os.Stat(overlayPath); err == nil { + return fmt.Errorf("CoW overlay file already exists: %s", overlayPath) + } + + w := &logWriter{emit: func(line string) { a.emitLog(cloneName, line) }} + env := rt.BuildChildEnv(&cfgCopy, *active) + a.emitLog(cloneName, fmt.Sprintf("Creating CoW overlay for %s backed by %s...", cloneName, filepath.Base(srcDisk))) + if err := reims.CreateCoWOverlay(ctx, active.QemuImgPath(), env, srcDisk, overlayPath, w, w); err != nil { + return err + } + + audio := src.Audio + network := src.Network + logs := src.Logs + capture := src.Capture + createOpts := reims.CreateOpts{ + Name: cloneName, + SourceMode: "disk", + Disk: overlayPath, + DiskMode: "in-place", + DiskController: src.DiskController, + CPUs: src.CPUs, + Memory: src.Memory, + Graphics: src.Graphics, + GPU: src.GPU, + Resolution: src.Resolution, + Displays: src.Displays, + Capture: &capture, + Audio: &audio, + Network: &network, + Logs: &logs, + Start: false, + } + if err := c.Create(ctx, createOpts, w, w); err != nil { + _ = os.Remove(overlayPath) + return err + } + if postSet, ok := reims.PostCreateSetOpts(createOpts); ok { + if serr := c.Set(ctx, postSet, w, w); serr != nil { + a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone settings: %v", serr)) + } + } + a.emitLog(cloneName, fmt.Sprintf("CoW clone %s ready (backing image %s untouched)", cloneName, srcDisk)) + if a.ctx != nil { + wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + } + return nil +} diff --git a/cmd/reims-go/main.go b/cmd/reims-go/main.go index 4fc8d34..7ff8ab1 100644 --- a/cmd/reims-go/main.go +++ b/cmd/reims-go/main.go @@ -279,6 +279,7 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error { mem := fs.String("memory", "16G", "RAM size (e.g. 8G, 16G)") diskSize := fs.String("disk-size", "128G", "New disk size (e.g. 128G)") gpu := fs.String("gpu", "auto", "GPU selector or Vulkan ICD JSON path") + capture := fs.Bool("capture", false, "Capture keyboard and mouse on window click") logs := fs.Bool("logs", true, "Keep graphics and serial logs") start := fs.Bool("start", false, "Start VM immediately after creation") if err := fs.Parse(args[1:]); err != nil { @@ -297,6 +298,7 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error { Memory: *mem, DiskSize: *diskSize, GPU: *gpu, + Capture: capture, Logs: logs, Start: false, } @@ -312,6 +314,11 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error { if err := client.Create(ctx, opts, os.Stdout, os.Stderr); err != nil { return err } + if postSet, ok := reims.PostCreateSetOpts(opts); ok { + if serr := client.Set(ctx, postSet, os.Stdout, os.Stderr); serr != nil { + fmt.Fprintf(os.Stderr, "Warning: could not apply post-create defaults: %v\n", serr) + } + } if startAfterCreate { if err := client.StartWithCompat(ctx, name, os.Stdout, os.Stderr, func(msg string) { fmt.Fprintln(os.Stderr, msg) diff --git a/create_flow.go b/create_flow.go index faf91bc..f269b4e 100644 --- a/create_flow.go +++ b/create_flow.go @@ -4,7 +4,10 @@ import ( "context" "errors" "fmt" + "os" + "path/filepath" "strings" + "time" "github.com/Nwflower/reims-go/internal/driver/reims" "github.com/Nwflower/reims-go/internal/installer" @@ -63,16 +66,39 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error { } } + // Convert VMDK / RAW disks into qcow2 before invoking reims-ctl create. + var convertedTmp string + if opts.Disk != "" && reims.NeedsDiskConversion(opts.Disk) { + convertedTmp = filepath.Join(cfgCopy.TempDir(), fmt.Sprintf("import-%s-%d.qcow2", opts.Name, time.Now().Unix())) + defer os.Remove(convertedTmp) + a.emitLog(opts.Name, fmt.Sprintf("Converting %s to qcow2 via qemu-img...", filepath.Base(opts.Disk))) + env := rt.BuildChildEnv(&cfgCopy, *active) + if cerr := reims.ConvertDiskToQCOW2(ctx, active.QemuImgPath(), env, opts.Disk, convertedTmp, w, w); cerr != nil { + finishTask(cerr) + a.emitLog(opts.Name, "Disk conversion error: "+cerr.Error()) + return cerr + } + opts.Disk = convertedTmp + opts.DiskMode = "copy" + } + err = c.Create(ctx, opts, w, w) if err != nil { finishTask(err) a.emitLog(opts.Name, "Create error: "+err.Error()) return err } - if dc := reims.EffectiveCreateDiskController(opts); dc != "ahci" { - a.emitLog(opts.Name, fmt.Sprintf("Setting disk controller for %s to %s...", opts.Name, strings.ToUpper(dc))) - if serr := c.Set(ctx, reims.SetOpts{Name: opts.Name, DiskController: dc}, w, w); serr != nil { - a.emitLog(opts.Name, fmt.Sprintf("Warning: could not switch disk controller to %s (keeping SATA/AHCI): %v", dc, serr)) + if postSet, ok := reims.PostCreateSetOpts(opts); ok { + var parts []string + if postSet.DiskController != "" { + parts = append(parts, "disk="+strings.ToUpper(postSet.DiskController)) + } + if postSet.Capture != nil && !*postSet.Capture { + parts = append(parts, "capture=off") + } + a.emitLog(opts.Name, fmt.Sprintf("Applying VM defaults for %s (%s)...", opts.Name, strings.Join(parts, ", "))) + if serr := c.Set(ctx, postSet, w, w); serr != nil { + a.emitLog(opts.Name, fmt.Sprintf("Warning: could not apply post-create defaults (%s): %v", strings.Join(parts, ", "), serr)) } } finishTask(nil) diff --git a/diagnostics_flow.go b/diagnostics_flow.go new file mode 100644 index 0000000..76aeefe --- /dev/null +++ b/diagnostics_flow.go @@ -0,0 +1,159 @@ +package main + +import ( + "archive/zip" + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/host" + rt "github.com/Nwflower/reims-go/internal/runtime" +) + +type diagnosticsBundle struct { + HostReport host.Report + Optimizations []host.Optimization + Runtime *rt.Installed + VMDetail *reims.VMDetail + SerialLog string + QEMULog string + AppLogs []string +} + +func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error { + if err := os.MkdirAll(filepath.Dir(zipPath), 0o755); err != nil { + return err + } + f, err := os.Create(zipPath) + if err != nil { + return err + } + zw := zip.NewWriter(f) + addFile := func(name, content string) error { + w, err := zw.Create(name) + if err != nil { + return err + } + _, err = w.Write([]byte(reims.RedactText(content))) + return err + } + addJSON := func(name string, v any) error { + raw, err := json.MarshalIndent(v, "", " ") + if err != nil { + return err + } + return addFile(name, string(raw)+"\n") + } + + hostSummary := map[string]any{ + "generated_at": time.Now().UTC().Format(time.RFC3339), + "host": b.HostReport, + "optimizations": b.Optimizations, + } + if err := addJSON("host-report.json", hostSummary); err != nil { + _ = zw.Close() + _ = f.Close() + return err + } + if b.Runtime != nil { + if err := addJSON("runtime-manifest.json", b.Runtime.Manifest); err != nil { + _ = zw.Close() + _ = f.Close() + return err + } + } + if b.VMDetail != nil { + sanitized := *b.VMDetail + sanitized.NetworkSummary = reims.RedactLogLine(sanitized.NetworkSummary) + sanitized.ExtraArgs = reims.RedactLogLine(sanitized.ExtraArgs) + if err := addJSON("vm-detail.json", sanitized); err != nil { + _ = zw.Close() + _ = f.Close() + return err + } + } + if strings.TrimSpace(b.SerialLog) != "" { + if err := addFile("serial.log", b.SerialLog); err != nil { + _ = zw.Close() + _ = f.Close() + return err + } + } + if strings.TrimSpace(b.QEMULog) != "" { + if err := addFile("qemu.log", b.QEMULog); err != nil { + _ = zw.Close() + _ = f.Close() + return err + } + } + if len(b.AppLogs) > 0 { + if err := addFile("app-logs.txt", strings.Join(b.AppLogs, "\n")+"\n"); err != nil { + _ = zw.Close() + _ = f.Close() + return err + } + } + if err := zw.Close(); err != nil { + _ = f.Close() + return err + } + return f.Close() +} + +// ExportDiagnostics collects a redacted troubleshooting zip bundle (host probe, +// runtime manifest, VM detail, serial/QEMU logs, and recent app logs) into +// `/reports/` and opens the folder in File Explorer. +func (a *App) ExportDiagnostics(name string) (string, error) { + a.mu.Lock() + cfgCopy := *a.cfg + appLogs := append([]string(nil), a.recentLogs...) + a.mu.Unlock() + + rep := host.Inspect(cfgCopy.DataRoot) + var active *rt.Installed + var patchNames []string + if inst, err := rt.ResolveActive(&cfgCopy); err == nil { + active = inst + for _, p := range inst.Manifest.Patches { + patchNames = append(patchNames, p.Name) + } + } + bundle := diagnosticsBundle{ + HostReport: rep, + Optimizations: host.EvaluateOptimizations(rep, patchNames), + Runtime: active, + AppLogs: appLogs, + } + + label := "host" + if strings.TrimSpace(name) != "" { + label = name + if c, err := a.client(); err == nil { + ctx := context.Background() + if d, derr := a.GetVMDetail(name); derr == nil { + bundle.VMDetail = &d + } + if serial, serr := c.ReadLogs(ctx, name, true); serr == nil { + bundle.SerialLog = serial + } + if qemuLog, qerr := c.ReadLogs(ctx, name, false); qerr == nil { + bundle.QEMULog = qemuLog + } + } + } + + reportsDir := filepath.Join(cfgCopy.DataRoot, "reports") + zipName := fmt.Sprintf("reims-go-diag-%s-%s.zip", label, time.Now().Format("20060102-150405")) + zipPath := filepath.Join(reportsDir, zipName) + if err := writeDiagnosticsZip(zipPath, bundle); err != nil { + return "", err + } + a.emitLog(label, "Diagnostics exported: "+zipPath) + _ = host.OpenFolder(reportsDir) + return zipPath, nil +} diff --git a/diagnostics_test.go b/diagnostics_test.go new file mode 100644 index 0000000..3c8d2cb --- /dev/null +++ b/diagnostics_test.go @@ -0,0 +1,62 @@ +package main + +import ( + "archive/zip" + "io" + "path/filepath" + "strings" + "testing" + + "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/host" +) + +func TestWriteDiagnosticsZipRedactsSensitiveData(t *testing.T) { + zipPath := filepath.Join(t.TempDir(), "reports", "diag.zip") + err := writeDiagnosticsZip(zipPath, diagnosticsBundle{ + HostReport: host.Report{OS: "windows", LogicalCPUs: 16, DataRootDriveType: "fixed"}, + VMDetail: &reims.VMDetail{ + Name: "macos-tahoe", + NetworkSummary: "user, mac 52:54:00:ab:cd:ef, ssh on 127.0.0.1:2222", + ExtraArgs: "-device isa-applesmc,osk=ourhardworkbythesewordsguardedpleasedontsteal", + }, + SerialLog: "OpenCore presents iMac20,1, serial C02FAKE123456\n", + QEMULog: "Authorization: Bearer 0123456789abcdef0123456789abcdef\n", + AppLogs: []string{`REIMS_TOKEN="abcdef0123456789abcdef0123456789"`}, + }) + if err != nil { + t.Fatalf("writeDiagnosticsZip: %v", err) + } + + zr, err := zip.OpenReader(zipPath) + if err != nil { + t.Fatal(err) + } + defer zr.Close() + + var all strings.Builder + for _, f := range zr.File { + rc, err := f.Open() + if err != nil { + t.Fatal(err) + } + b, _ := io.ReadAll(rc) + rc.Close() + all.WriteString(f.Name + ":\n" + string(b) + "\n") + } + text := all.String() + for _, secret := range []string{ + "52:54:00:ab:cd:ef", + "C02FAKE123456", + "ourhardworkbythesewordsguardedpleasedontsteal", + "0123456789abcdef0123456789abcdef", + "abcdef0123456789abcdef0123456789", + } { + if strings.Contains(text, secret) { + t.Fatalf("diagnostics zip leaked secret %q\n%s", secret, text) + } + } + if !strings.Contains(text, "[redacted]") { + t.Fatalf("expected [redacted] markers in zip output") + } +} diff --git a/docs/roadmap.md b/docs/roadmap.md index dee738f..dcf4c92 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -89,10 +89,10 @@ flowchart LR - [x] **M3.1**:**三层大小核防超售绑核与 WHPX 兼容自愈** — 识别三层混合架构(P + E + LP-E,如 Intel Core Ultra 200 无超线程 CPU),`vCPU < P 核逻辑线程数` 时绑 P 核,超出时自动改绑 `P + E`(仅排除慢速 LP-E 核)避免自旋锁超售卡顿;自动探测 Win11 `hr=0x80370302` 嵌套虚拟化属性并预置/补丁化处理;新建 VM 默认 `NVMe` 控制器。 - [x] **M3.2**:**安全 AF_UNIX QMP 通道与键入** — Win10 冷重启辅助 QMP 通道已迁至 Windows `AF_UNIX` 套接字(杜绝 SLIRP 下 `10.0.2.2:` 宿主机逃逸风险,自动清理旧 TCP 参数);已基于 `reims-ctl` 的 `qmp.sock` 实现 QMP 键盘一键键入。后续按需补齐优雅关机增强与 QMP 截屏。 - [x] **M3.3(v0.3 核心)**:**安全鉴权 Guest Tools(双向剪贴板 + 共享目录)** — 内置仅监听 `127.0.0.1` 的纯 Go HTTP 宿客桥接(每台 VM 独立 256-bit 随机 Bearer Token + 严格共享目录路径隔离),通过纯 Go HFS+ 辅助盘 `REIMSTOOLS` 一键安装免 Xcode/Python 的 macOS LaunchAgent,支持双向 UTF-8 剪贴板与 `~/Desktop/ReimsShare` ↔ `/shared/` 双向文件同步。**(macOS 桌面端真机联调待验证)** -- [ ] **M3.4(v0.3 后续)**:**退出恢复模式自动升级 `NVMe` + 存储/内存性能诊断** — 对旧 `AHCI` VM 在退出恢复模式时一键/自动切至 `NVMe`;在宿主页/VM 页自动识别外置 USB/机械盘、内存占用过高等瓶颈并给出可操作提示。 -- [ ] **M3.5(v0.3 后续)**:**一键导出脱敏排障日志包(`.zip`)** — 收集体检报告、VM 配置、自动脱敏(序列号/MAC/OSK)的 QEMU 与串口日志,一键导出并定位文件,降低社区排障成本。 -- [ ] **M3.6(v0.3 后续)**:**磁盘导入增强(VMDK / RAW 自动转 qcow2)** — 复用便携运行时内置 `qemu-img convert`,在新建向导支持直接导入 VMware `.vmdk` 与 `.raw` 镜像。 -- [ ] **M3.7(v0.4 差异化王牌)**:**Golden Image 与 CoW 秒级派生 / 快照** — 支持将已装好系统的 VM 标记为模板,用 `qemu-img` 秒级派生临时测试实例,销毁后模板哈希不变。 +- [x] **M3.4(v0.3 后续)**:**退出恢复模式自动升级 `NVMe` + 存储/内存性能诊断** — 对旧 `AHCI` VM 在退出恢复模式时自动切至 `NVMe`,并在 VM 主页提供一键升级按钮;自动检测外置 USB/网络盘(`GetDriveTypeW` + `IOCTL_STORAGE_QUERY_PROPERTY` `BusTypeUsb`)与高内存负载(≥ 85%)并展示可操作提示。 +- [x] **M3.5(v0.3 后续)**:**一键导出脱敏排障日志包(`.zip`)** — 收集体检报告、运行时清单、VM 配置、自动脱敏(序列号/MAC/SMC OSK/Bearer Token)的 QEMU、串口与应用日志,一键导出到 `/reports/` 并定位目录(已通过单测验证零敏感信息泄漏)。 +- [x] **M3.6(v0.3 后续)**:**磁盘导入增强(VMDK / RAW 自动转 qcow2)** — 复用便携运行时内置 `qemu-img convert`,新建向导支持直接选择 `.vmdk` / `.raw` 并自动转为 `.qcow2` 导入。**(真机大容量 VMDK 转换待验证)** +- [x] **M3.7(v0.4 差异化王牌)**:**Golden Image 与 CoW 秒级派生** — 已停止的已装系统 VM 支持在「更多」里通过 `qemu-img create -f qcow2 -b -F qcow2` + `reims-ctl create --disk --disk-mode in-place` 秒级派生独立身份副本,原盘只读不改。**(真机 CoW 派生启动待验证)** **DoD**: - 三层大小核防超售绑核、`AF_UNIX` QMP、Guest Tools 剪贴板与共享目录、CoW 派生在真实宿主均有实测通过记录。 @@ -106,8 +106,8 @@ flowchart LR - [ ] **M4.1**:**上游窗口与性能 PR 跟进(运行时升级)** — 跟踪上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 关键 Windows PR 合入并纳入新 `candidate` 运行时: - 图形与平台层:**#153**(Windows NVIDIA MAILBOX 经 FIFO 首帧优化)、**#152**(原生 Windows Vulkan 后端)、**#107**(采样纹理回读就地消费); - 窗口与键位体验:**#123**(`Ctrl+Alt+Enter` 热切全屏)、**#172**(Windows 拖动窗口贴合消除黑边);以及评估「自由指针下 Win 键映射 Command」是否提交上游 PR 或短期进补丁队列。 -- [ ] **M4.2**:编写 GitHub Actions workflow:在 `windows-latest` 上通过 MSYS2 CLANG64,先 `git apply --check` 并打上 `patches/` 补丁队列,再构建指定上游 commit 的 `reims-runtime-win-x64-.tar.zst`、`SHA256SUMS.txt` 与源码包。产物只进 `candidate` 通道。补丁打不上时 workflow 失败,不自动修补丁。 -- [ ] **M4.3**:**`candidate` → `stable` 冒烟升级流程** — 编写 `scripts/smoke-runtime.ps1`,在真实宿主上解压候选包,跑 `doctor`、用 golden 镜像启动到桌面、验证 Guest Tools 与截屏、正常关机,输出报告;由人确认后升为 `stable`(`portable-runtime-spec.md` 第 6 节)。 +- [x] **M4.2**:编写 GitHub Actions workflow([ci.yml](.github/workflows/ci.yml) + [build-runtime.yml](.github/workflows/build-runtime.yml)):常规 CI 自动执行 `go test` / `go vet` / 前端构建与 CLI 编译;手动运行时构建 workflow 在 `windows-latest` 上通过 MSYS2 CLANG64 先 `git apply --check` 并应用 `patches/`(补丁不匹配即硬失败),产出 `candidate` 预发布包与源码包。**(GitHub Actions 实跑验证待触发)** +- [x] **M4.3**:**`candidate` → `stable` 冒烟脚本** — 已编写 [scripts/smoke-runtime.ps1](scripts/smoke-runtime.ps1),支持校验 SHA-256、在干净隔离目录(无 MSYS2 PATH)解压并跑 `reims-ctl doctor` / `list --json` 与合规文件核查,产出供人工评审的 Markdown 冒烟报告。 - [ ] **M4.4**:自动构建 `reims-go.exe` 并发布 GitHub Release,客户端接入在线版本检查,默认只拉 `stable`,支持一键回滚旧版本;补齐 `NOTICE.md`、第三方许可证包、对应源码包与合规核验清单。 - [ ] **M4.5**:补丁上游化:整理 `patches/` 里每个补丁(Win10 兼容/startup-ipis、Win11 nested-virt-nonfatal)的复现步骤与实测证据,交给人向上游提 PR;合并后从队列删除。 diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index bd37b77..f5f2adb 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -2,6 +2,7 @@ import { Minus, Moon, Square, Sun, X } from 'lucide-react' import React, { useCallback, useEffect, useRef, useState } from 'react' import { CreateWizard, WizardDraft } from './components/CreateWizard' import { DeleteDialog } from './components/DeleteDialog' +import { CloneDialog } from './components/CloneDialog' import { OnlineRecoveryDialog } from './components/OnlineRecoveryDialog' import { HostView } from './components/HostView' import { LogPanel, LogTab } from './components/LogPanel' @@ -33,6 +34,9 @@ const failKey: Record = { attachGuestTools: 'failGuestTools', detachGuestTools: 'failGuestTools', openSharedFolder: 'failOpenFolder', + upgradeNVMe: 'failUpgradeNVMe', + exportDiagnostics: 'failExportDiagnostics', + cloneVM: 'failCloneVM', type: 'failType', delete: 'failDelete', openFolder: 'failOpenFolder', @@ -46,6 +50,7 @@ export const App: React.FC = () => { const [wizardDraft, setWizardDraft] = useState(null) const [showSettings, setShowSettings] = useState(false) const [deleteTarget, setDeleteTarget] = useState(null) + const [cloneSource, setCloneSource] = useState(null) const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState(null) const [busy, setBusy] = useState>({}) const [loadError, setLoadError] = useState('') @@ -288,6 +293,12 @@ export const App: React.FC = () => { case 'detachGuestTools': return runVMAction(name, action, () => backend.detachGuestTools(name), tr(isRunning ? 'toastGuestToolsDetachedNextStart' : 'toastGuestToolsDetached')) case 'openSharedFolder': return backend.openSharedFolder(name).catch((e) => fail(tr('failOpenFolder'), e)) + case 'upgradeNVMe': + return runVMAction(name, action, () => backend.upgradeDiskToNVMe(name), tr(isRunning ? 'toastNVMeNextStart' : 'toastNVMeReady')) + case 'exportDiagnostics': + return runVMAction(name, action, async () => { await backend.exportDiagnostics(name) }, tr('toastDiagExported')) + case 'cloneVM': + return setCloneSource(name) case 'type': return typeInto(name, () => backend.typeClipboard(name)) case 'openFolder': return backend.openVMFolder(name).catch((e) => fail(tr('failOpenFolder'), e)) @@ -310,6 +321,16 @@ export const App: React.FC = () => { .catch((e) => fail(tr('failAttachInstaller'), e)) } + const confirmClone = (cloneName: string) => { + const src = cloneSource + setCloneSource(null) + if (!src) return + runVMAction(src, 'cloneVM', async () => { + await backend.cloneVMCoW(src, cloneName) + setSelected(cloneName) + }, tr('toastCloned', { name: cloneName })) + } + const openWizard = () => { if (!state?.active_runtime) { setSelected(HOST_ID) @@ -351,6 +372,7 @@ export const App: React.FC = () => { resolution: '1920x1080', displays: 1, borderless: false, + capture: false, audio: true, network: !isOffline, ssh_port: 0, @@ -566,6 +588,16 @@ export const App: React.FC = () => { setDeleteTarget(null)} onConfirm={confirmDelete} /> )} + {cloneSource && ( + setCloneSource(null)} + onConfirm={confirmClone} + /> + )} + {onlineRecoveryTarget && ( void + onConfirm: (cloneName: string) => void +} + +export const CloneDialog: React.FC = ({ locale, sourceName, defaultCloneName, onCancel, onConfirm }) => { + const [cloneName, setCloneName] = useState(defaultCloneName) + const trimmed = cloneName.trim() + return ( + { if (!open) onCancel() }}> + + + +
+ {t(locale, 'cloneTitle', { name: sourceName })} + + {t(locale, 'cloneDesc')} + +
+ + setCloneName(e.target.value)} + onKeyDown={(e) => { if (e.key === 'Enter' && trimmed) onConfirm(trimmed) }} + autoFocus + /> +
+
+
+ + + + + + +
+
+
+
+ ) +} diff --git a/frontend/src/components/CreateWizard.tsx b/frontend/src/components/CreateWizard.tsx index 58cb35c..7cd6a6b 100644 --- a/frontend/src/components/CreateWizard.tsx +++ b/frontend/src/components/CreateWizard.tsx @@ -63,6 +63,7 @@ export const CreateWizard: React.FC = ({ locale, host, draft, onClose, on resolution: '1920x1080', displays: 1, borderless: false, + capture: false, audio: true, network: false, ssh_port: 0, @@ -269,7 +270,7 @@ export const CreateWizard: React.FC = ({ locale, host, draft, onClose, on @@ -410,6 +411,7 @@ export const CreateWizard: React.FC = ({ locale, host, draft, onClose, on {([ ['audio', 'enableAudio'], ['network', 'enableNetwork'], + ['capture', 'captureInput'], ['logs', 'enableLogs'], ['start', 'startAfterCreate'], ] as const).map(([key, label]) => ( @@ -423,6 +425,7 @@ export const CreateWizard: React.FC = ({ locale, host, draft, onClose, on ))} + {tr('captureInputHint')} {opts.source_mode === 'offline' && {tr('networkOfflineHint')}} )} @@ -530,6 +533,7 @@ const Review: React.FC = ({ locale, host, opts, issues, checking, c ...graphicsRows, { label: tr('fieldAudio'), value: onOff(opts.audio) }, { label: tr('fieldNetwork'), value: onOff(opts.network) }, + { label: tr('captureInput'), value: onOff(opts.capture) }, { label: tr('summarySSH'), value: opts.ssh_port ? tr('summarySSHPort', { n: opts.ssh_port }) : tr('off') }, { label: tr('summaryLogs'), value: onOff(opts.logs) }, { label: tr('summaryStartAfter'), value: onOff(opts.start) }, diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index 1d6ec8c..0981a39 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -257,7 +257,12 @@ export const SettingsModal: React.FC = ({ locale, detail, host, optimizat )} {cat === 'audio' && check('audio', 'enableAudio')} - {cat === 'input' && check('capture', 'captureInput')} + {cat === 'input' && ( + <> + {check('capture', 'captureInput')} + {tr('captureInputHint')} + + )} {cat === 'logs' && ( <> diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index 61c893c..03a5383 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -1,7 +1,9 @@ import * as Menu from '@radix-ui/react-dropdown-menu' import { + Archive, ChevronRight, Copy, + CopyPlus, Disc, Ellipsis, FolderOpen, @@ -33,6 +35,9 @@ export type VMAction = | 'attachGuestTools' | 'detachGuestTools' | 'openSharedFolder' + | 'upgradeNVMe' + | 'exportDiagnostics' + | 'cloneVM' | 'type' | 'delete' | 'openFolder' @@ -128,12 +133,20 @@ export const VMPage: React.FC = ({ {tr('finishInstall')} )} + {detail && !detail.has_installer && !detail.recovery_mode && ( + onAction('cloneVM')}> + {tr('cloneVM')} + + )} onAction('openFolder')}> {tr('openFolder')} {tr('viewLogs')} + onAction('exportDiagnostics')}> + {tr('exportDiagnostics')} + {tr('delete')} @@ -169,6 +182,27 @@ export const VMPage: React.FC = ({ )} + {(host.data_root_drive_type === 'usb' || host.data_root_drive_type === 'removable' || host.data_root_drive_type === 'network') && ( +
+ {tr('diagExternalDriveWarn', { dir: host.data_root })} +
+ )} + + {(host.memory_load_pct ?? 0) >= 85 && ( +
+ {tr('diagHighMemWarn', { pct: host.memory_load_pct ?? 0 })} +
+ )} + + {detail && !detail.has_installer && detail.disk_controller === 'ahci' && ( +
+ {tr('diagAhciUpgradeHint')} + +
+ )} + {detail && (detail.has_installer || detail.recovery_mode) && (() => { const hasInstaller = detail.has_installer const isOffline = hasInstaller && /offline-installer/i.test(detail.installer_path ?? '') diff --git a/frontend/src/i18n.ts b/frontend/src/i18n.ts index 9baa1ca..28fa6a7 100644 --- a/frontend/src/i18n.ts +++ b/frontend/src/i18n.ts @@ -91,6 +91,16 @@ const dict = { attachGuestTools: '挂载 Guest Tools', detachGuestTools: '弹出工具盘', openSharedFolder: '打开共享文件夹', + upgradeToNVMe: '升级到 NVMe', + exportDiagnostics: '导出排障日志 (.zip)', + cloneVM: '秒级派生副本 (CoW)', + diagExternalDriveWarn: '数据目录位于外置/网络盘({dir}),macOS 安装与随机读写会明显偏慢,建议放本地 NVMe SSD', + diagHighMemWarn: '宿主机当前物理内存占用已达 {pct}%,若虚拟机卡顿建议关闭后台程序或适当调小虚拟机内存', + diagAhciUpgradeHint: '当前系统盘仍使用旧版 SATA/AHCI,建议一键升级到 NVMe 以提升读写与 TRIM 性能', + cloneTitle: '从「{name}」派生 CoW 副本', + cloneDesc: '通过 qcow2 写时复制(CoW)秒级创建独立副本,几乎不占额外空间,且不会修改原虚拟机磁盘。', + cloneNameLabel: '新虚拟机名称', + cloneConfirm: '立即派生', typeClipboard: '粘贴为键入', typeIntoVM: '在虚拟机里键入', typeUntypeable: '只能键入美式键盘上的字符(英文、数字、符号)。中文等字符请换别的方式传。', @@ -187,6 +197,10 @@ const dict = { toastGuestToolsAttachedNextStart: '已挂载 Guest Tools 工具盘,重启虚拟机后在访达中可见', toastGuestToolsDetached: '已弹出 Guest Tools 工具盘(剪贴板与共享目录继续生效)', toastGuestToolsDetachedNextStart: '已弹出工具盘,下次启动生效(剪贴板与共享目录继续生效)', + toastNVMeReady: '已升级到 NVMe 磁盘控制器', + toastNVMeNextStart: '已切换为 NVMe,下次启动生效', + toastDiagExported: '已导出脱敏排障日志包 (.zip)', + toastCloned: '已派生 CoW 副本「{name}」', toastTyped: '已键入 {n} 个字符', toastDeleted: '已删除 {name}', toastSaved: '已保存', @@ -200,6 +214,9 @@ const dict = { failEnterRecovery: '进入恢复模式失败', failAttachInstaller: '挂载镜像失败', failGuestTools: 'Guest Tools 操作失败', + failUpgradeNVMe: '升级到 NVMe 失败', + failExportDiagnostics: '导出排障日志失败', + failCloneVM: '派生 CoW 副本失败', failType: '键入失败', failDelete: '删除失败', failOpenFolder: '无法打开文件夹', @@ -340,6 +357,7 @@ const dict = { diskController: '磁盘控制器', diskControllerWarn: '切换前先弹出安装盘', captureInput: '点击窗口时捕获键鼠', + captureInputHint: '默认关闭(自由指针):单按 Win 键与 Alt+Tab 保留给 Windows,不会卡在 macOS 窗口里;需要把 ⌘Tab 等系统快捷键交给 macOS 时再开启', stopTimeout: '关机等待时间(秒)', stopTimeoutHint: '0 表示一直等待', extraArgs: '额外 QEMU 参数', @@ -459,6 +477,16 @@ const dict = { attachGuestTools: 'Attach Guest Tools', detachGuestTools: 'Eject tools disk', openSharedFolder: 'Open shared folder', + upgradeToNVMe: 'Upgrade to NVMe', + exportDiagnostics: 'Export diagnostics (.zip)', + cloneVM: 'Derive CoW clone', + diagExternalDriveWarn: 'Data root ({dir}) is on an external or network drive; macOS install and APFS I/O will be much slower than local NVMe SSD', + diagHighMemWarn: 'Host physical memory usage is at {pct}%; close background apps or lower VM RAM if performance degrades', + diagAhciUpgradeHint: 'This VM still uses legacy SATA/AHCI; upgrade to NVMe for faster I/O and TRIM support', + cloneTitle: 'Derive CoW clone from “{name}”', + cloneDesc: 'Creates an instant qcow2 copy-on-write overlay with a fresh Mac identity without modifying the source disk.', + cloneNameLabel: 'New VM name', + cloneConfirm: 'Create clone', typeClipboard: 'Paste as keystrokes', typeIntoVM: 'Type into the VM', typeUntypeable: 'Only characters on a US keyboard can be typed (letters, digits, symbols).', @@ -550,6 +578,10 @@ const dict = { toastGuestToolsAttachedNextStart: 'Guest Tools disk attached — restart VM to mount in Finder', toastGuestToolsDetached: 'Guest Tools disk ejected (clipboard & shared folder stay active)', toastGuestToolsDetachedNextStart: 'Guest Tools disk ejected — applies on next start', + toastNVMeReady: 'Upgraded disk controller to NVMe', + toastNVMeNextStart: 'Switched to NVMe — applies on next start', + toastDiagExported: 'Redacted diagnostics archive exported (.zip)', + toastCloned: 'CoW clone “{name}” created', toastTyped: 'Typed {n} characters', toastDeleted: '{name} deleted', toastSaved: 'Saved', @@ -563,6 +595,9 @@ const dict = { failEnterRecovery: 'Couldn’t enter recovery mode', failAttachInstaller: 'Couldn’t attach the image', failGuestTools: 'Guest Tools operation failed', + failUpgradeNVMe: 'Couldn’t upgrade to NVMe', + failExportDiagnostics: 'Couldn’t export diagnostics', + failCloneVM: 'Couldn’t create CoW clone', failType: 'Couldn’t type into the VM', failDelete: 'Couldn’t delete', failOpenFolder: 'Couldn’t open the folder', @@ -700,6 +735,7 @@ const dict = { diskController: 'Disk controller', diskControllerWarn: 'Eject the installer before switching', captureInput: 'Capture keyboard and mouse on click', + captureInputHint: 'Off by default (free pointer): Win key and Alt+Tab stay with Windows so you won’t get trapped in the macOS window; enable to send system shortcuts like ⌘Tab to macOS', stopTimeout: 'Shutdown timeout (seconds)', stopTimeoutHint: '0 waits indefinitely', extraArgs: 'Extra QEMU arguments', diff --git a/frontend/src/types.ts b/frontend/src/types.ts index d1b5a7a..c1050ee 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -45,12 +45,18 @@ export interface HostReport { p_core_mask_hex: string p_core_logical_cpus?: number[] e_core_logical_cpus?: number[] + lpe_core_count?: number + non_lpe_mask?: number + non_lpe_mask_hex?: string + non_lpe_logical_cpus?: number[] total_ram_gb: number avail_ram_gb: number + memory_load_pct?: number /** Windows commit memory: QEMU commits all guest RAM at start. */ commit_avail_gb: number commit_limit_gb: number data_root: string + data_root_drive_type?: string free_disk_gb: number whpx: 'ready' | 'no_hypervisor' | 'missing' | 'unsupported' whpx_caps?: WHPXCapabilities @@ -164,6 +170,7 @@ export interface CreateOpts { resolution: string displays: number borderless?: boolean + capture?: boolean audio?: boolean network?: boolean ssh_port?: number diff --git a/frontend/src/wails.ts b/frontend/src/wails.ts index 0a9f986..53fed1a 100644 --- a/frontend/src/wails.ts +++ b/frontend/src/wails.ts @@ -48,6 +48,9 @@ declare global { AttachGuestTools(name: string): Promise DetachGuestTools(name: string): Promise OpenSharedFolder(name: string): Promise + UpgradeDiskToNVMe(name: string): Promise + ExportDiagnostics(name: string): Promise + CloneVMCoW(sourceName: string, cloneName: string): Promise TypeText(name: string, text: string): Promise TypeClipboard(name: string): Promise GetTasks(): Promise @@ -113,6 +116,9 @@ export const backend = { attachGuestTools: (name: string) => app().AttachGuestTools(name), detachGuestTools: (name: string) => app().DetachGuestTools(name), openSharedFolder: (name: string) => app().OpenSharedFolder(name), + upgradeDiskToNVMe: (name: string) => app().UpgradeDiskToNVMe(name), + exportDiagnostics: (name: string) => app().ExportDiagnostics(name), + cloneVMCoW: (sourceName: string, cloneName: string) => app().CloneVMCoW(sourceName, cloneName), typeText: (name: string, text: string) => app().TypeText(name, text), typeClipboard: (name: string) => app().TypeClipboard(name), getTasks: () => app().GetTasks(), diff --git a/frontend/wailsjs/go/main/App.d.ts b/frontend/wailsjs/go/main/App.d.ts index 5e328c4..3b98cb8 100644 --- a/frontend/wailsjs/go/main/App.d.ts +++ b/frontend/wailsjs/go/main/App.d.ts @@ -15,6 +15,8 @@ export function CancelTask(arg1:string):Promise; export function CheckDataRoot(arg1:string):Promise; +export function CloneVMCoW(arg1:string,arg2:string):Promise; + export function CompleteSetup(arg1:string):Promise; export function CreateVM(arg1:reims.CreateOpts):Promise; @@ -37,6 +39,8 @@ export function EnableWHPX():Promise; export function EnterRecovery(arg1:string):Promise; +export function ExportDiagnostics(arg1:string):Promise; + export function FinishInstall(arg1:string):Promise; export function GetState():Promise; @@ -87,6 +91,8 @@ export function TypeClipboard(arg1:string):Promise; export function TypeText(arg1:string,arg2:string):Promise; +export function UpgradeDiskToNVMe(arg1:string):Promise; + export function UseRuntime(arg1:string):Promise; export function ValidateCreate(arg1:reims.CreateOpts):Promise>; diff --git a/frontend/wailsjs/go/main/App.js b/frontend/wailsjs/go/main/App.js index 7a1f3ae..326e498 100644 --- a/frontend/wailsjs/go/main/App.js +++ b/frontend/wailsjs/go/main/App.js @@ -22,6 +22,10 @@ export function CheckDataRoot(arg1) { return window['go']['main']['App']['CheckDataRoot'](arg1); } +export function CloneVMCoW(arg1, arg2) { + return window['go']['main']['App']['CloneVMCoW'](arg1, arg2); +} + export function CompleteSetup(arg1) { return window['go']['main']['App']['CompleteSetup'](arg1); } @@ -66,6 +70,10 @@ export function EnterRecovery(arg1) { return window['go']['main']['App']['EnterRecovery'](arg1); } +export function ExportDiagnostics(arg1) { + return window['go']['main']['App']['ExportDiagnostics'](arg1); +} + export function FinishInstall(arg1) { return window['go']['main']['App']['FinishInstall'](arg1); } @@ -166,6 +174,10 @@ export function TypeText(arg1, arg2) { return window['go']['main']['App']['TypeText'](arg1, arg2); } +export function UpgradeDiskToNVMe(arg1) { + return window['go']['main']['App']['UpgradeDiskToNVMe'](arg1); +} + export function UseRuntime(arg1) { return window['go']['main']['App']['UseRuntime'](arg1); } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 14d5968..a159852 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -101,9 +101,11 @@ export namespace host { non_lpe_logical_cpus?: number[]; total_ram_gb: number; avail_ram_gb: number; + memory_load_pct: number; commit_avail_gb: number; commit_limit_gb: number; data_root: string; + data_root_drive_type?: string; free_disk_gb: number; whpx: string; whpx_caps: WHPXCapabilities; @@ -134,9 +136,11 @@ export namespace host { this.non_lpe_logical_cpus = source["non_lpe_logical_cpus"]; this.total_ram_gb = source["total_ram_gb"]; this.avail_ram_gb = source["avail_ram_gb"]; + this.memory_load_pct = source["memory_load_pct"]; this.commit_avail_gb = source["commit_avail_gb"]; this.commit_limit_gb = source["commit_limit_gb"]; this.data_root = source["data_root"]; + this.data_root_drive_type = source["data_root_drive_type"]; this.free_disk_gb = source["free_disk_gb"]; this.whpx = source["whpx"]; this.whpx_caps = this.convertValues(source["whpx_caps"], WHPXCapabilities); @@ -388,6 +392,7 @@ export namespace reims { resolution?: string; displays?: number; borderless?: boolean; + capture?: boolean; audio?: boolean; network?: boolean; ssh_port?: number; @@ -417,6 +422,7 @@ export namespace reims { this.resolution = source["resolution"]; this.displays = source["displays"]; this.borderless = source["borderless"]; + this.capture = source["capture"]; this.audio = source["audio"]; this.network = source["network"]; this.ssh_port = source["ssh_port"]; diff --git a/install_flow.go b/install_flow.go index 87baa72..da9fff9 100644 --- a/install_flow.go +++ b/install_flow.go @@ -397,12 +397,19 @@ func (a *App) FinishInstall(name string) error { stripped := reims.StripOfflineHelperArgs(d.ExtraArgs) setOpts := reims.SetOpts{Name: name} needSet := false + upgradedNVMe := false if !d.Network { on := true setOpts.Network = &on needSet = true a.emitLog(name, "Turning the network on for "+name+"...") } + if d.HasInstaller && strings.EqualFold(d.DiskController, "ahci") { + setOpts.DiskController = "nvme" + needSet = true + upgradedNVMe = true + a.emitLog(name, "Upgrading disk controller for "+name+" from SATA/AHCI to NVMe...") + } if stripped != d.ExtraArgs { setOpts.ExtraArgs = &stripped needSet = true @@ -423,6 +430,9 @@ func (a *App) FinishInstall(name string) error { if !d.Network { diffs = append(diffs, PendingChange{Field: "network", From: "off", To: "on"}) } + if upgradedNVMe { + diffs = append(diffs, PendingChange{Field: "disk_controller", From: "ahci", To: "nvme"}) + } switch marker { case "want": writeRecoveryPickerMarker(d.Directory, "") @@ -453,3 +463,41 @@ func (a *App) FinishInstall(name string) error { } return nil } + +// UpgradeDiskToNVMe switches an existing installed VM from legacy SATA/AHCI to +// NVMe via `reims-ctl set --disk-controller nvme` (applies at next start if running). +func (a *App) UpgradeDiskToNVMe(name string) error { + c, err := a.client() + if err != nil { + return err + } + d, err := a.GetVMDetail(name) + if err != nil { + return err + } + if d.HasInstaller { + return errors.New("exit recovery mode (eject installer) before switching disk controller") + } + if strings.EqualFold(d.DiskController, "nvme") { + return nil + } + w := &logWriter{emit: func(line string) { a.emitLog(name, line) }} + ctx := context.Background() + a.emitLog(name, "Upgrading disk controller for "+name+" to NVMe...") + if err := c.Set(ctx, reims.SetOpts{Name: name, DiskController: "nvme"}, w, w); err != nil { + return err + } + if a.isVMRunning(ctx, c, name, d) { + a.mu.Lock() + a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{ + Field: "disk_controller", + From: d.DiskController, + To: "nvme", + }) + a.mu.Unlock() + } + if a.ctx != nil { + wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + } + return nil +} diff --git a/internal/driver/reims/compat_test.go b/internal/driver/reims/compat_test.go index 9cf64b3..87779c7 100644 --- a/internal/driver/reims/compat_test.go +++ b/internal/driver/reims/compat_test.go @@ -139,20 +139,25 @@ func TestCreateDefaultNVMeAndPreview(t *testing.T) { if got := EffectiveCreateDiskController(opts); got != "nvme" { t.Fatalf("EffectiveCreateDiskController default = %q, want nvme", got) } + if EffectiveCreateCapture(opts) { + t.Fatalf("EffectiveCreateCapture default = true, want false") + } cmd, err := PreviewCreateCommand(opts) if err != nil { t.Fatal(err) } - if !strings.Contains(cmd, "&& reims-ctl set macos-tahoe --disk-controller nvme") { - t.Fatalf("PreviewCreateCommand missing nvme set step: %q", cmd) + if !strings.Contains(cmd, "&& reims-ctl set macos-tahoe --disk-controller nvme --capture false") { + t.Fatalf("PreviewCreateCommand missing nvme + capture=false set step: %q", cmd) } opts.DiskController = "ahci" - cmdAhci, err := PreviewCreateCommand(opts) + on := true + opts.Capture = &on + cmdAhciCaptureOn, err := PreviewCreateCommand(opts) if err != nil { t.Fatal(err) } - if strings.Contains(cmdAhci, "--disk-controller") { - t.Fatalf("PreviewCreateCommand should omit set step for ahci: %q", cmdAhci) + if strings.Contains(cmdAhciCaptureOn, "&& reims-ctl set") { + t.Fatalf("PreviewCreateCommand should omit set step for ahci + capture=true: %q", cmdAhciCaptureOn) } } @@ -167,3 +172,20 @@ func TestMergeAndStripGuestToolsArgs(t *testing.T) { t.Fatalf("StripGuestToolsArgs = %q, want %q", stripped, base) } } + +func TestDiskImportAndCoWArgs(t *testing.T) { + if !NeedsDiskConversion(`D:\vms\mac.vmdk`) || !NeedsDiskConversion(`D:\vms\mac.RAW`) { + t.Fatalf("expected .vmdk and .raw to need conversion") + } + if NeedsDiskConversion(`D:\vms\disk.qcow2`) || NeedsDiskConversion(`D:\vms\disk.img`) { + t.Fatalf("did not expect .qcow2/.img to need conversion") + } + conv := strings.Join(BuildConvertToQCOW2Args("in.vmdk", "out.qcow2"), " ") + if conv != "convert -O qcow2 in.vmdk out.qcow2" { + t.Fatalf("BuildConvertToQCOW2Args = %q", conv) + } + cow := strings.Join(BuildCoWOverlayArgs("golden.qcow2", "cow-dev.qcow2"), " ") + if cow != "create -f qcow2 -b golden.qcow2 -F qcow2 cow-dev.qcow2" { + t.Fatalf("BuildCoWOverlayArgs = %q", cow) + } +} diff --git a/internal/driver/reims/disk_import.go b/internal/driver/reims/disk_import.go new file mode 100644 index 0000000..66da57a --- /dev/null +++ b/internal/driver/reims/disk_import.go @@ -0,0 +1,82 @@ +package reims + +import ( + "context" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "strings" +) + +// NeedsDiskConversion reports whether srcPath is a disk format (VMDK or RAW) +// that should be converted to qcow2 via qemu-img before handing off to reims-ctl. +func NeedsDiskConversion(srcPath string) bool { + ext := strings.ToLower(filepath.Ext(strings.TrimSpace(srcPath))) + return ext == ".vmdk" || ext == ".raw" +} + +// BuildConvertToQCOW2Args constructs `qemu-img convert -O qcow2` arguments. +func BuildConvertToQCOW2Args(srcPath, dstPath string) []string { + return []string{"convert", "-O", "qcow2", srcPath, dstPath} +} + +// BuildCoWOverlayArgs constructs `qemu-img create -f qcow2 -b -F qcow2 ` +// arguments for instant copy-on-write VM derivation. +func BuildCoWOverlayArgs(backingPath, overlayPath string) []string { + return []string{"create", "-f", "qcow2", "-b", backingPath, "-F", "qcow2", overlayPath} +} + +// ConvertDiskToQCOW2 converts a VMDK or RAW disk image to qcow2 using the +// portable runtime's qemu-img binary. +func ConvertDiskToQCOW2(ctx context.Context, qemuImgPath string, env []string, srcPath, dstPath string, stdout, stderr io.Writer) error { + if _, err := os.Stat(qemuImgPath); err != nil { + return fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err) + } + if err := os.MkdirAll(filepath.Dir(dstPath), 0o755); err != nil { + return err + } + cmd := exec.CommandContext(ctx, qemuImgPath, BuildConvertToQCOW2Args(srcPath, dstPath)...) + configureCmd(cmd) + cmd.Env = env + if stdout != nil { + cmd.Stdout = stdout + } + if stderr != nil { + cmd.Stderr = stderr + } + if err := cmd.Run(); err != nil { + _ = os.Remove(dstPath) + return fmt.Errorf("qemu-img convert %s: %w", filepath.Base(srcPath), err) + } + return nil +} + +// CreateCoWOverlay creates an instant qcow2 copy-on-write overlay backed by +// backingPath without modifying the backing disk image. +func CreateCoWOverlay(ctx context.Context, qemuImgPath string, env []string, backingPath, overlayPath string, stdout, stderr io.Writer) error { + if _, err := os.Stat(qemuImgPath); err != nil { + return fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err) + } + if _, err := os.Stat(backingPath); err != nil { + return fmt.Errorf("backing disk not found (%s): %w", backingPath, err) + } + if err := os.MkdirAll(filepath.Dir(overlayPath), 0o755); err != nil { + return err + } + cmd := exec.CommandContext(ctx, qemuImgPath, BuildCoWOverlayArgs(backingPath, overlayPath)...) + configureCmd(cmd) + cmd.Env = env + if stdout != nil { + cmd.Stdout = stdout + } + if stderr != nil { + cmd.Stderr = stderr + } + if err := cmd.Run(); err != nil { + _ = os.Remove(overlayPath) + return fmt.Errorf("qemu-img create CoW overlay: %w", err) + } + return nil +} diff --git a/internal/driver/reims/redact.go b/internal/driver/reims/redact.go index 87ce773..a3d16d2 100644 --- a/internal/driver/reims/redact.go +++ b/internal/driver/reims/redact.go @@ -1,16 +1,34 @@ 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`) +import ( + "regexp" + "strings" ) -// RedactLogLine removes MAC addresses and SMBIOS serial numbers before lines -// are emitted to the activity log panel (docs/shell-design.md §3). +var ( + reLogMac = regexp.MustCompile(`(?i)\b(mac[\s:=]+)["']?[0-9a-f]{2}(?::[0-9a-f]{2}){5}["']?`) + reLogSerial = regexp.MustCompile(`(?i)\b(serial[\s:=]+)["']?[A-Z0-9]{8,}["']?`) + reLogOSK = regexp.MustCompile(`(?i)\b(osk=)[^\s,"']+`) + reLogBearer = regexp.MustCompile(`(?i)(Bearer\s+)[A-Za-z0-9._~+/-]{16,}`) + reLogTokenKV = regexp.MustCompile(`(?i)((?:REIMS_TOKEN|"token")\s*[:=]\s*["']?)[A-Za-z0-9._~+/-]{16,}(["']?)`) +) + +// RedactLogLine removes MAC addresses, SMBIOS serial numbers, SMC OSK keys, and +// Guest Tools Bearer tokens before lines are emitted or exported. func RedactLogLine(line string) string { - line = reLogMac.ReplaceAllString(line, "mac [redacted]") - line = reLogSerial.ReplaceAllString(line, "serial [redacted]") + line = reLogMac.ReplaceAllString(line, "${1}[redacted]") + line = reLogSerial.ReplaceAllString(line, "${1}[redacted]") + line = reLogOSK.ReplaceAllString(line, "${1}[redacted]") + line = reLogBearer.ReplaceAllString(line, "${1}[redacted]") + line = reLogTokenKV.ReplaceAllString(line, "${1}[redacted]${2}") return line } + +// RedactText applies RedactLogLine across a multi-line log or JSON text block. +func RedactText(s string) string { + lines := strings.Split(s, "\n") + for i, l := range lines { + lines[i] = RedactLogLine(l) + } + return strings.Join(lines, "\n") +} diff --git a/internal/driver/reims/reims.go b/internal/driver/reims/reims.go index 11905f5..c038fca 100644 --- a/internal/driver/reims/reims.go +++ b/internal/driver/reims/reims.go @@ -100,6 +100,7 @@ type CreateOpts struct { Resolution string `json:"resolution,omitempty"` Displays int `json:"displays,omitempty"` Borderless *bool `json:"borderless,omitempty"` + Capture *bool `json:"capture,omitempty"` Audio *bool `json:"audio,omitempty"` Network *bool `json:"network,omitempty"` SSHPort int `json:"ssh_port,omitempty"` @@ -333,24 +334,59 @@ func EffectiveCreateDiskController(o CreateOpts) string { return dc } +// EffectiveCreateCapture returns whether keyboard/mouse capture should be +// enabled on a newly created VM. Defaults to false (free pointer) so host +// shortcuts like Win key and Alt+Tab stay with Windows and users do not get +// trapped in the macOS window during Recovery/install; users can opt in via +// CreateOpts.Capture or VM Settings -> Keyboard & pointer. +func EffectiveCreateCapture(o CreateOpts) bool { + if o.Capture != nil { + return *o.Capture + } + return false +} + +// PostCreateSetOpts returns follow-up `reims-ctl set` options for defaults that +// `reims-ctl create` does not accept directly (upstream 3731afd defaults to +// SATA/AHCI and capture=true). +func PostCreateSetOpts(o CreateOpts) (SetOpts, bool) { + so := SetOpts{Name: o.Name} + need := false + if dc := EffectiveCreateDiskController(o); dc != "ahci" { + so.DiskController = dc + need = true + } + if !EffectiveCreateCapture(o) { + off := false + so.Capture = &off + need = true + } + return so, need +} + // PreviewCreateCommand formats the exact CLI command shown on Step 5 of the wizard. func PreviewCreateCommand(o CreateOpts) (string, error) { args, err := BuildCreateArgs(o) if err != nil { return "", err } - quoted := make([]string, 0, len(args)+1) - quoted = append(quoted, "reims-ctl") - for _, a := range args { - if strings.ContainsAny(a, " \t\"") { - quoted = append(quoted, strconv.Quote(a)) - } else { - quoted = append(quoted, a) + quoteArgs := func(in []string) string { + quoted := make([]string, 0, len(in)+1) + quoted = append(quoted, "reims-ctl") + for _, a := range in { + if strings.ContainsAny(a, " \t\"") { + quoted = append(quoted, strconv.Quote(a)) + } else { + quoted = append(quoted, a) + } } + return strings.Join(quoted, " ") } - cmd := strings.Join(quoted, " ") - if dc := EffectiveCreateDiskController(o); dc != "ahci" { - cmd += fmt.Sprintf(" && reims-ctl set %s --disk-controller %s", o.Name, dc) + cmd := quoteArgs(args) + if so, ok := PostCreateSetOpts(o); ok { + if setArgs, err := BuildSetArgs(so); err == nil { + cmd += " && " + quoteArgs(setArgs) + } } return cmd, nil } diff --git a/internal/guesttools/guesttools_test.go b/internal/guesttools/guesttools_test.go index 50302f7..38b15d2 100644 --- a/internal/guesttools/guesttools_test.go +++ b/internal/guesttools/guesttools_test.go @@ -107,6 +107,12 @@ func TestServerAuthClipboardAndSharedFiles(t *testing.T) { if r.StatusCode != 200 { t.Fatalf("clipboard POST: status=%d", r.StatusCode) } + // Reject invalid non-UTF-8 (e.g. raw GBK bytes) instead of corrupting host clipboard. + r = doReq("POST", "/v1/clipboard", bytes.NewReader([]byte{0xB6, 0xE0, 0xBA, 0xCB})) + r.Body.Close() + if r.StatusCode != http.StatusBadRequest { + t.Fatalf("non-UTF-8 clipboard POST: got %d, want 400", r.StatusCode) + } if got, _ := clip.ReadText(); got != "你好 macOS" { t.Fatalf("host clipboard = %q, want %q", got, "你好 macOS") } diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index d71fa23..7c28968 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -65,6 +65,13 @@ func GuestAgentScript() []byte { # Reims Guest Tools: token-authenticated two-way clipboard & ReimsShare sync. set -u +# Force UTF-8 for macOS pbpaste/pbcopy under launchd (otherwise Simplified +# Chinese macOS defaults __CF_USER_TEXT_ENCODING to GB18030/GBK, causing +# mojibake when decoded as UTF-8 on Windows). +export LANG="en_US.UTF-8" +export LC_ALL="en_US.UTF-8" +export __CF_USER_TEXT_ENCODING="0x$(printf '%X' "$(id -u)"):0x08000100:0x08000100" + APP_DIR="$HOME/Library/Application Support/ReimsGuestTools" CONF="$APP_DIR/config" SHARE="$HOME/ReimsShare" @@ -239,6 +246,9 @@ chmod 600 "$APP_DIR/config" chmod 755 "$APP_DIR/guest-tools.sh" [ -e "$HOME/Desktop/ReimsShare" ] || ln -s "$SHARE" "$HOME/Desktop/ReimsShare" 2>/dev/null || true +uid=$(id -u) +cf_enc="0x$(printf '%X' "$uid"):0x08000100:0x08000100" + cat >"$PLIST" < @@ -246,6 +256,15 @@ cat >"$PLIST" < Label com.reimsgo.guest-tools + EnvironmentVariables + + LANG + en_US.UTF-8 + LC_ALL + en_US.UTF-8 + __CF_USER_TEXT_ENCODING + $cf_enc + ProgramArguments /bin/sh @@ -263,7 +282,6 @@ cat >"$PLIST" < EOF -uid=$(id -u) launchctl bootout "gui/$uid" "$PLIST" 2>/dev/null || launchctl unload "$PLIST" 2>/dev/null || true launchctl bootstrap "gui/$uid" "$PLIST" 2>/dev/null || launchctl load -w "$PLIST" diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index bce2b17..cb2fda8 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -21,6 +21,7 @@ import ( "strings" "sync" "time" + "unicode/utf8" ) const ( @@ -314,6 +315,10 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) { http.Error(w, "clipboard too large", http.StatusRequestEntityTooLarge) return } + if !utf8.Valid(body) { + http.Error(w, "clipboard payload must be valid UTF-8", http.StatusBadRequest) + return + } text := strings.ReplaceAll(string(body), "\r\n", "\n") h := textHash(text) if cur, err := s.clip.ReadText(); err != nil || textHash(cur) != h { diff --git a/internal/host/host.go b/internal/host/host.go index ecdbfc4..8f13f19 100644 --- a/internal/host/host.go +++ b/internal/host/host.go @@ -50,8 +50,9 @@ type Report struct { NonLPEMask uint64 `json:"non_lpe_mask,omitempty"` NonLPEMaskHex string `json:"non_lpe_mask_hex,omitempty"` NonLPELogicalCPUs []int `json:"non_lpe_logical_cpus,omitempty"` - TotalRAMGB float64 `json:"total_ram_gb"` - AvailRAMGB float64 `json:"avail_ram_gb"` + TotalRAMGB float64 `json:"total_ram_gb"` + AvailRAMGB float64 `json:"avail_ram_gb"` + MemoryLoadPct int `json:"memory_load_pct"` // 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 @@ -59,6 +60,7 @@ type Report struct { CommitAvailGB float64 `json:"commit_avail_gb"` CommitLimitGB float64 `json:"commit_limit_gb"` DataRoot string `json:"data_root"` + DataRootDriveType string `json:"data_root_drive_type,omitempty"` FreeDiskGB float64 `json:"free_disk_gb"` WHPX WHPXState `json:"whpx"` WHPXCaps WHPXCapabilities `json:"whpx_caps"` diff --git a/internal/host/host_windows.go b/internal/host/host_windows.go index 5bc9223..58c1d96 100644 --- a/internal/host/host_windows.go +++ b/internal/host/host_windows.go @@ -17,6 +17,7 @@ var ( procGetLogicalProcessorInformationEx = kernel32.NewProc("GetLogicalProcessorInformationEx") procGlobalMemoryStatusEx = kernel32.NewProc("GlobalMemoryStatusEx") procGetDiskFreeSpaceExW = kernel32.NewProc("GetDiskFreeSpaceExW") + procDeviceIoControl = kernel32.NewProc("DeviceIoControl") procOpenProcess = kernel32.NewProc("OpenProcess") procSetProcessAffinityMask = kernel32.NewProc("SetProcessAffinityMask") procCloseHandle = kernel32.NewProc("CloseHandle") @@ -88,6 +89,9 @@ func Inspect(dataRoot string) Report { rep.TotalRAMGB = totalGB rep.AvailRAMGB = availGB } + if ms, ok := memoryStatus(); ok { + rep.MemoryLoadPct = int(ms.MemoryLoad) + } if limitGB, availGB, ok := probeCommitGB(); ok { rep.CommitLimitGB = limitGB rep.CommitAvailGB = availGB @@ -95,6 +99,7 @@ func Inspect(dataRoot string) Report { if freeGB, ok := probeFreeDiskGB(dataRoot); ok { rep.FreeDiskGB = freeGB } + rep.DataRootDriveType = probeDriveType(dataRoot) return rep } @@ -319,6 +324,72 @@ func probeFreeDiskGB(path string) (float64, bool) { return float64(freeBytesAvail) / (1024 * 1024 * 1024), true } +// probeDriveType detects whether path resides on a local fixed drive, USB +// external enclosure (via IOCTL_STORAGE_QUERY_PROPERTY BusTypeUsb=7), +// removable drive, or network share. Requires no admin privileges. +func probeDriveType(path string) string { + vol := filepath.VolumeName(path) + if vol == "" { + return "unknown" + } + root := vol + `\` + p, err := syscall.UTF16PtrFromString(root) + if err != nil { + return "unknown" + } + dt, _, _ := procGetDriveTypeW.Call(uintptr(unsafe.Pointer(p))) + switch dt { + case 2: // DRIVE_REMOVABLE + return "removable" + case 4: // DRIVE_REMOTE + return "network" + case 3: // DRIVE_FIXED + if isUSBBusVolume(vol) { + return "usb" + } + return "fixed" + default: + return "unknown" + } +} + +func isUSBBusVolume(vol string) bool { + if len(vol) < 2 || vol[1] != ':' { + return false + } + devPath, err := syscall.UTF16PtrFromString(`\\.\` + vol[:2]) + if err != nil { + return false + } + // Access = 0 allows metadata IOCTLs (IOCTL_STORAGE_QUERY_PROPERTY) without elevation. + h, err := syscall.CreateFile(devPath, 0, syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE, nil, syscall.OPEN_EXISTING, 0, 0) + if err != nil || h == syscall.InvalidHandle { + return false + } + defer syscall.CloseHandle(h) + + const ioctlStorageQueryProperty = 0x002D1400 + var query [12]byte // STORAGE_PROPERTY_QUERY: PropertyId=0 (StorageDeviceProperty), QueryType=0 + var out [512]byte + var returned uint32 + r, _, _ := procDeviceIoControl.Call( + uintptr(h), + ioctlStorageQueryProperty, + uintptr(unsafe.Pointer(&query[0])), + uintptr(len(query)), + uintptr(unsafe.Pointer(&out[0])), + uintptr(len(out)), + uintptr(unsafe.Pointer(&returned)), + 0, + ) + if r == 0 || returned < 32 { + return false + } + // STORAGE_DEVICE_DESCRIPTOR.BusType is a 4-byte enum at offset 28; BusTypeUsb == 7. + busType := binary.LittleEndian.Uint32(out[28:32]) + return busType == 7 +} + func probeVulkanGPUs() []GPUInfo { const baseKey = `SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}` var out []GPUInfo diff --git a/scripts/smoke-runtime.ps1 b/scripts/smoke-runtime.ps1 new file mode 100644 index 0000000..f00635a --- /dev/null +++ b/scripts/smoke-runtime.ps1 @@ -0,0 +1,191 @@ +<# +.SYNOPSIS + Real-host smoke test for a candidate portable reims-vgpu runtime archive. + +.DESCRIPTION + Implements docs/portable-runtime-spec.md section 6 (candidate -> stable gate): + 1. Verifies SHA256 against SHA256SUMS.txt (when provided). + 2. Extracts the runtime into an isolated directory under -TempRoot (never C:). + 3. Verifies manifest.json provenance, NOTICE.md, licenses/, and core binaries. + 4. Runs `reims-ctl doctor` and `reims-ctl list --json` in a clean environment + stripped of MSYS2 / Cargo paths to prove true portability. + 5. Writes a Markdown report for human review before promoting to `stable`. + +.EXAMPLE + powershell -ExecutionPolicy Bypass -File scripts/smoke-runtime.ps1 ` + -ArchivePath D:\Data\reims-go\releases\reims-runtime-win-x64-3731afd.tar.zst ` + -Sha256File D:\Data\reims-go\releases\SHA256SUMS.txt +#> +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)] + [string]$ArchivePath, + [string]$Sha256File = '', + [string]$TempRoot = 'D:\Build\Temp', + [string]$ReportOut = '' +) + +$ErrorActionPreference = 'Stop' + +if (-not (Test-Path -LiteralPath $ArchivePath)) { + throw "Archive not found: $ArchivePath" +} + +$archiveFile = Get-Item -LiteralPath $ArchivePath +$actualHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $ArchivePath).Hash.ToLowerInvariant() +$hashStatus = 'skipped (no -Sha256File provided)' +if ($Sha256File -ne '') { + if (-not (Test-Path -LiteralPath $Sha256File)) { + throw "SHA256SUMS file not found: $Sha256File" + } + $matched = $false + foreach ($line in (Get-Content -LiteralPath $Sha256File)) { + if ($line -match '^([0-9a-fA-F]{64})\s+\*?(.+)$') { + $h = $Matches[1].ToLowerInvariant() + $n = $Matches[2].Trim() + if ($n -eq $archiveFile.Name) { + if ($h -ne $actualHash) { + throw "SHA256 mismatch for $($archiveFile.Name): expected $h, got $actualHash" + } + $matched = $true + break + } + } + } + if (-not $matched) { + throw "Entry for $($archiveFile.Name) not found in $Sha256File" + } + $hashStatus = "PASS ($actualHash)" +} + +$stamp = Get-Date -Format 'yyyyMMdd-HHmmss' +$smokeDir = Join-Path $TempRoot "smoke-$stamp" +$extractDir = Join-Path $smokeDir 'runtime' +$dataDir = Join-Path $smokeDir 'data' +New-Item -ItemType Directory -Force -Path $extractDir, $dataDir | Out-Null + +function Resolve-Zstd { + @( + (Get-Command zstd.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source), + 'D:\DevTools\msys64\usr\bin\zstd.exe', + 'C:\msys64\usr\bin\zstd.exe' + ) | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Select-Object -First 1 +} + +try { + Write-Host "[1/5] Extracting $($archiveFile.Name) into $extractDir..." + if ($archiveFile.Name.EndsWith('.tar.zst')) { + $zstd = Resolve-Zstd + if (-not $zstd) { throw 'zstd.exe not found to extract .tar.zst' } + $tarPath = Join-Path $smokeDir 'runtime.tar' + & $zstd -d -f -q $ArchivePath -o $tarPath + if ($LASTEXITCODE -ne 0) { throw "zstd decompress failed ($LASTEXITCODE)" } + & tar.exe -xf $tarPath -C $extractDir + if ($LASTEXITCODE -ne 0) { throw "tar extract failed ($LASTEXITCODE)" } + Remove-Item -LiteralPath $tarPath -Force + } elseif ($archiveFile.Name.EndsWith('.zip')) { + Expand-Archive -LiteralPath $ArchivePath -DestinationPath $extractDir -Force + } else { + throw "Unsupported archive format: $($archiveFile.Name)" + } + + # Handle single top-level folder inside archive. + $rootDir = $extractDir + $children = @(Get-ChildItem -LiteralPath $extractDir) + if ($children.Count -eq 1 -and $children[0].PSIsContainer) { + $rootDir = $children[0].FullName + } + + Write-Host "[2/5] Checking manifest.json, compliance files, and core binaries..." + $required = @( + 'manifest.json', + 'NOTICE.md', + 'licenses', + 'bin\reims-ctl.exe', + 'bin\reims-util.exe', + 'qemu\bin\qemu-system-x86_64.exe', + 'qemu\bin\qemu-img.exe' + ) + foreach ($rel in $required) { + $p = Join-Path $rootDir $rel + if (-not (Test-Path -LiteralPath $p)) { + throw "Missing required runtime asset: $rel" + } + } + $manifest = Get-Content -Raw -LiteralPath (Join-Path $rootDir 'manifest.json') | ConvertFrom-Json + $patchList = @() + if ($manifest.patches) { + $patchList = @($manifest.patches | ForEach-Object { $_.name }) + } + + Write-Host "[3/5] Running reims-ctl doctor in a clean MSYS2-free environment..." + $cleanEnv = @{ + 'XDG_CONFIG_HOME' = (Join-Path $dataDir 'config') + 'XDG_DATA_HOME' = (Join-Path $dataDir 'data') + 'XDG_CACHE_HOME' = (Join-Path $dataDir 'cache') + 'TEMP' = (Join-Path $dataDir 'tmp') + 'TMP' = (Join-Path $dataDir 'tmp') + 'REIMS_CTL_QEMU' = (Join-Path $rootDir 'qemu') + 'PATH' = "$($env:SystemRoot)\System32;$($env:SystemRoot)" + } + New-Item -ItemType Directory -Force -Path $cleanEnv['XDG_CONFIG_HOME'], $cleanEnv['XDG_DATA_HOME'], $cleanEnv['XDG_CACHE_HOME'], $cleanEnv['TEMP'] | Out-Null + + function Invoke-CleanCtl([string[]]$ctlArgs) { + $psi = New-Object System.Diagnostics.ProcessStartInfo + $psi.FileName = (Join-Path $rootDir 'bin\reims-ctl.exe') + $psi.Arguments = ($ctlArgs -join ' ') + $psi.UseShellExecute = $false + $psi.RedirectStandardOutput = $true + $psi.RedirectStandardError = $true + $psi.CreateNoWindow = $true + foreach ($k in $cleanEnv.Keys) { + $psi.EnvironmentVariables[$k] = $cleanEnv[$k] + } + $proc = [System.Diagnostics.Process]::Start($psi) + $stdout = $proc.StandardOutput.ReadToEnd() + $stderr = $proc.StandardError.ReadToEnd() + $proc.WaitForExit() + return @{ Code = $proc.ExitCode; Stdout = $stdout; Stderr = $stderr } + } + + $doctorRes = Invoke-CleanCtl @('doctor') + Write-Host "[4/5] Running reims-ctl list --json..." + $listRes = Invoke-CleanCtl @('list', '--json') + if ($listRes.Code -ne 0) { + throw "reims-ctl list --json failed ($($listRes.Code)): $($listRes.Stderr)" + } + + Write-Host "[5/5] Generating smoke report..." + $reportLines = @( + "# Runtime Smoke Test Report", + "", + "- **Tested at**: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss zzz')", + "- **Host**: $([Environment]::MachineName) ($([Environment]::OSVersion.VersionString))", + "- **Archive**: $($archiveFile.Name) ($([math]::Round($archiveFile.Length / 1MB, 1)) MB)", + "- **SHA256 check**: $hashStatus", + "- **Upstream commit**: $($manifest.commit) (channel: $($manifest.channel))", + "- **vendor/qemu commit**: $($manifest.vendor_qemu_commit)", + "- **Patches**: $(if ($patchList.Count -gt 0) { $patchList -join ', ' } else { 'none (pure upstream)' })", + "- **Source package declared**: $($manifest.source_package)", + "- **reims-ctl list --json**: PASS (exit $($listRes.Code))", + "- **reims-ctl doctor exit code**: $($doctorRes.Code)", + "", + "## reims-ctl doctor output", + '```text', + $doctorRes.Stdout.TrimEnd(), + '```' + ) + $report = $reportLines -join "`n" + if ($ReportOut -ne '') { + New-Item -ItemType Directory -Force -Path (Split-Path -Parent $ReportOut) | Out-Null + [IO.File]::WriteAllText($ReportOut, $report + "`n", [Text.UTF8Encoding]::new($false)) + Write-Host "Smoke report written to: $ReportOut" + } else { + Write-Host "`n$report" + } + Write-Host "`nSmoke test finished. Human review required before promoting candidate -> stable." +} finally { + if (Test-Path -LiteralPath $smokeDir) { + Remove-Item -LiteralPath $smokeDir -Recurse -Force -ErrorAction SilentlyContinue + } +}