Compare commits

..
4 Commits
Author SHA1 Message Date
NwflowerandClaude Opus 5.5 470ed2d30a release: v0.2.3
Release Reims-Go / release (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 22:52:29 -07:00
NwflowerandClaude Opus 5.5 2f1e0bb0e4 feat(cli): fold the command line into reims-go.exe
Only reims-go.exe ships now; reims-go-cli.exe is gone. Without
arguments it opens the window, with a command it runs command-line mode
(cmd/reims-go moved to internal/cli). Missing standard handles are
attached to the parent console; handles the caller passes in (pipes,
files) are kept, so scripts and agents get output and exit codes.

`vm start` hands the VM to the window process so it gets Guest Tools
and the Win10 cold-reboot watcher, which a command that exits could not
run:
- a running window gets the request through Wails' single-instance
  protocol and stays hidden;
- otherwise the command launches the window tray-only (--background),
  detached from the caller's console and handles;
- the window writes the outcome, with the VM's last log lines on
  failure, to <DataRoot>\tmp\cli-start-*.json (it accepts no other
  path) and the command reports it.
With --data-root the VM still starts in the command itself.

The window now takes a single-instance lock: a second double-click
brings the running window forward. `wails dev` builds use their own
lock name.

Tested on Win10 19045 with macos-tahoe: start from the command line
with no window running (4 s, exit 0) and with one running (3 s, exit 0,
same process); the cold-reboot monitor was held by the window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 22:52:07 -07:00
NwflowerandClaude Opus 5.5 69803355bf perf(shell): cut thumbnail cost and reims-ctl polling
The VM page made the shell spawn about 84 reims-ctl processes a minute
and pull a full 4K screendump every 5 s while a VM ran.

- Scale reads *image.RGBA Pix directly: a 4K frame drops from ~80 ms
  and 8.3M allocations to ~10 ms and 2.
- Thumbnails refresh every 15 s and skip the screendump while the VM's
  own window is in the foreground.
- pollVMs polls every 2 s only while a VM starts or stops, else every
  5 s; start, stop and delete wake it at once.
- Stats, thumbnails and the heartbeat reuse the polled list instead of
  running their own `reims-ctl list`; the disk path from `show` is kept
  for a minute.

Measured with two windows on the VM page: 67 -> 13 reims-ctl spawns a
minute.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 22:51:40 -07:00
Nwflower d30c694e2f feat(guesttools): add read-only Windows drive sharing 2026-11-28 20:27:35 -07:00
53 changed files with 2229 additions and 248 deletions

No files matched your search

+4 -2
View File
@@ -38,9 +38,11 @@ jobs:
go test ./...
go vet ./...
- name: Build CLI & GUI binaries
- name: Build reims-go.exe (window + command-line mode)
shell: pwsh
run: |
New-Item -ItemType Directory -Force -Path build/bin | Out-Null
go build -trimpath -o build/bin/reims-go-cli.exe ./cmd/reims-go
go build -trimpath -tags desktop,production -ldflags "-H windowsgui" -o build/bin/reims-go.exe .
# Command-line mode must still answer through a pipe from the GUI-subsystem build.
$out = & build/bin/reims-go.exe version | Out-String
if ($LASTEXITCODE -ne 0 -or $out -notmatch '^reims-go ') { throw "reims-go.exe version failed: $out" }
+2 -3
View File
@@ -56,7 +56,7 @@ jobs:
shell: pwsh
run: go install github.com/wailsapp/wails/v2/cmd/wails@v2.17.1
- name: Build Windows x64 GUI & CLI binaries
- name: Build Windows x64 binary
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
@@ -64,11 +64,10 @@ jobs:
$dist = 'dist-release'
New-Item -ItemType Directory -Force -Path $dist | Out-Null
$verPkg = 'github.com/Nwflower/reims-go/internal/version'
# One executable: the window without arguments, command-line mode with a command.
$guiOut = Join-Path $dist "reims-go-$tag-windows-amd64.exe"
$cliOut = Join-Path $dist "reims-go-cli-$tag-windows-amd64.exe"
wails build -s -trimpath -ldflags "-s -w -X $verPkg.Version=$tag" -o "reims-go-$tag-windows-amd64.exe"
Copy-Item (Join-Path 'build\bin' "reims-go-$tag-windows-amd64.exe") $guiOut
go build -trimpath -ldflags "-s -w -X $verPkg.Version=$tag" -o $cliOut ./cmd/reims-go
$lines = @(Get-ChildItem -LiteralPath $dist -File | Sort-Object Name | ForEach-Object {
$h = (Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash.ToLowerInvariant()
"$h $($_.Name)"
+8 -6
View File
@@ -77,15 +77,17 @@ wails build
### 命令行
命令行模式就在同一个 `reims-go.exe` 里:不带参数打开窗口,带子命令就在终端里执行。
```powershell
reims-go doctor # 环境体检
reims-go runtime fetch # 在线安装运行时
reims-go installer download tahoe # 下载离线安装包(支持续传)
reims-go vm create macos-tahoe # 新建虚拟机
reims-go vm start macos-tahoe # 启动虚拟机
reims-go doctor | Out-Host # 环境体检
reims-go runtime fetch | Out-Host # 在线安装运行时
reims-go installer download tahoe | Out-Host # 下载离线安装包(支持续传)
reims-go vm create macos-tahoe | Out-Host # 新建虚拟机
reims-go vm start macos-tahoe | Out-Host # 启动虚拟机(交给托盘里的 Reims-Go,带剪贴板与共享目录)
```
运行 `reims-go help` 查看全部子命令,加 `--lang en-US` 切换英文输出。
`reims-go.exe` 是窗口程序,交互式 PowerShell / cmd 不会等它结束;加 `| Out-Host`(或任何管道、重定向)就会等命令执行完并给出退出码。脚本和 Agent 通过管道调用,不受影响。运行 `reims-go help` 查看全部子命令,加 `--lang en-US` 切换英文输出。
<br />
+175 -69
View File
@@ -10,6 +10,7 @@ import (
"sync"
"time"
"github.com/Nwflower/reims-go/internal/cli"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/guesttools"
@@ -62,9 +63,14 @@ type App struct {
trayMgr *tray.Manager
allowQuit bool
lastVMs []reims.VMListItem
lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale
pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick
diskPaths map[string]cachedDiskPath
procSamples map[string]host.ProcessSample
recentLogs []string
needsSetup bool
launch cli.WindowArgs // flags this window was started with (window_launch.go)
logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go)
}
func NewApp() *App {
@@ -78,6 +84,8 @@ func NewApp() *App {
transitions: make(map[string]string),
pendingChanges: make(map[string][]PendingChange),
rebootWatchers: make(map[string]rebootWatcherEntry),
pollWake: make(chan struct{}, 1),
diskPaths: make(map[string]cachedDiskPath),
procSamples: make(map[string]host.ProcessSample),
}
}
@@ -90,6 +98,7 @@ func (a *App) startup(ctx context.Context) {
a.startIMEBridge()
go a.registerExistingGuestTools(pollCtx)
go a.pollVMs(pollCtx)
a.afterStartup()
}
func (a *App) startIMEBridge() {
@@ -148,9 +157,20 @@ func (a *App) shutdown(ctx context.Context) {
}
}
// pollVMs refreshes the VM list every pollBusy while a VM is starting or
// stopping and every pollSteady otherwise; each tick runs one `reims-ctl list`.
// Start, stop and delete call wakePoll so their result shows up at once.
const (
pollBusy = 2 * time.Second
pollSteady = 5 * time.Second
// polledMaxAge is how old lastVMs may be for polledVMs to reuse it. It sits
// above pollSteady so a poll that runs a little late still counts.
polledMaxAge = pollSteady + 3*time.Second
)
func (a *App) pollVMs(ctx context.Context) {
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
timer := time.NewTimer(pollBusy)
defer timer.Stop()
// Cache static hybrid P-core mask once instead of querying host every tick.
a.mu.Lock()
initRoot := a.cfg.DataRoot
@@ -163,81 +183,90 @@ func (a *App) pollVMs(ctx context.Context) {
select {
case <-ctx.Done():
return
case <-ticker.C:
vms, err := a.listVMsInternal(ctx)
if err != nil {
continue
case <-timer.C:
case <-a.pollWake:
}
a.mu.Lock()
next := pollSteady
if len(a.transitions) > 0 {
next = pollBusy
}
a.mu.Unlock()
timer.Reset(next)
vms, err := a.listVMsInternal(ctx)
if err != nil {
continue
}
type pinCandidate struct {
name string
pid int
}
var toPin []pinCandidate
a.mu.Lock()
loc := a.cfg.Locale
autoPin := a.cfg.AutoPinPCores
a.lastVMs = append([]reims.VMListItem(nil), vms...)
a.lastVMsAt = time.Now()
tm := a.trayMgr
runningCount := 0
var b strings.Builder
var imeTargets []host.IMETarget
for _, vm := range vms {
if vm.State == "running" {
runningCount++
if vm.PID != nil && *vm.PID > 0 {
imeTargets = append(imeTargets, host.IMETarget{
VMName: vm.Name,
VMDir: vm.Dir,
PID: uint32(*vm.PID),
})
}
}
type pinCandidate struct {
name string
pid int
}
var toPin []pinCandidate
a.mu.Lock()
loc := a.cfg.Locale
autoPin := a.cfg.AutoPinPCores
a.lastVMs = append([]reims.VMListItem(nil), vms...)
tm := a.trayMgr
runningCount := 0
var b strings.Builder
var imeTargets []host.IMETarget
for _, vm := range vms {
if vm.State == "running" {
runningCount++
if vm.PID != nil && *vm.PID > 0 {
imeTargets = append(imeTargets, host.IMETarget{
VMName: vm.Name,
VMDir: vm.Dir,
PID: uint32(*vm.PID),
})
if tr, ok := a.transitions[vm.Name]; ok {
if (tr == "starting" && vm.State == "running") || (tr == "stopping" && vm.State == "stopped") {
delete(a.transitions, vm.Name)
if vm.State == "stopped" {
delete(a.pendingChanges, vm.Name)
}
}
if tr, ok := a.transitions[vm.Name]; ok {
if (tr == "starting" && vm.State == "running") || (tr == "stopping" && vm.State == "stopped") {
delete(a.transitions, vm.Name)
if vm.State == "stopped" {
delete(a.pendingChanges, vm.Name)
}
}
}
if autoPin && vm.State == "running" && vm.PID != nil && *vm.PID > 0 && !pinnedPIDs[*vm.PID] {
if cachedHost.HasHybridCores && cachedHost.PCoreMask > 0 {
pinnedPIDs[*vm.PID] = true
toPin = append(toPin, pinCandidate{name: vm.Name, pid: *vm.PID})
}
}
fmt.Fprintf(&b, "%s:%s:%s;", vm.Name, vm.State, a.transitions[vm.Name])
}
sig := b.String()
ib := a.imeBridge
a.mu.Unlock()
if ib != nil {
ib.SetTargets(imeTargets)
if autoPin && vm.State == "running" && vm.PID != nil && *vm.PID > 0 && !pinnedPIDs[*vm.PID] {
if cachedHost.HasHybridCores && cachedHost.PCoreMask > 0 {
pinnedPIDs[*vm.PID] = true
toPin = append(toPin, pinCandidate{name: vm.Name, pid: *vm.PID})
}
}
if tm != nil {
if runningCount > 0 {
if loc == i18n.ZhCN {
tm.UpdateTooltip(fmt.Sprintf("Reims-Go — %d 台虚拟机运行中", runningCount))
} else {
tm.UpdateTooltip(fmt.Sprintf("Reims-Go — %d VM(s) running", runningCount))
}
fmt.Fprintf(&b, "%s:%s:%s;", vm.Name, vm.State, a.transitions[vm.Name])
}
sig := b.String()
ib := a.imeBridge
a.mu.Unlock()
if ib != nil {
ib.SetTargets(imeTargets)
}
if tm != nil {
if runningCount > 0 {
if loc == i18n.ZhCN {
tm.UpdateTooltip(fmt.Sprintf("Reims-Go — %d 台虚拟机运行中", runningCount))
} else {
tm.UpdateTooltip("Reims-Go")
tm.UpdateTooltip(fmt.Sprintf("Reims-Go — %d VM(s) running", runningCount))
}
} else {
tm.UpdateTooltip("Reims-Go")
}
}
for _, cand := range toPin {
vmCPUs := 0
if c, cerr := a.client(); cerr == nil {
if det, derr := c.Show(ctx, cand.name); derr == nil {
vmCPUs = det.CPUs
}
}
for _, cand := range toPin {
vmCPUs := 0
if c, cerr := a.client(); cerr == nil {
if det, derr := c.Show(ctx, cand.name); derr == nil {
vmCPUs = det.CPUs
}
}
a.emitLog(cand.name, vmstart.PinQEMU(loc, cachedHost, cand.pid, vmCPUs))
}
if sig != lastSig {
lastSig = sig
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitLog(cand.name, vmstart.PinQEMU(loc, cachedHost, cand.pid, vmCPUs))
}
if sig != lastSig {
lastSig = sig
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
}
}
@@ -261,6 +290,76 @@ func (a *App) listVMsInternal(ctx context.Context) ([]reims.VMListItem, error) {
return c.List(ctx)
}
// polledVMs returns the list pollVMs saw last if it is at most polledMaxAge
// old, so per-VM samplers (stats, thumbnails, heartbeats) don't each spawn
// their own `reims-ctl list`. A stale or missing poll falls back to one.
func (a *App) polledVMs(ctx context.Context) ([]reims.VMListItem, error) {
a.mu.Lock()
if !a.lastVMsAt.IsZero() && time.Since(a.lastVMsAt) <= polledMaxAge {
vms := append([]reims.VMListItem(nil), a.lastVMs...)
a.mu.Unlock()
return vms, nil
}
a.mu.Unlock()
return a.listVMsInternal(ctx)
}
// polledVM looks name up in polledVMs.
func (a *App) polledVM(name string) (reims.VMListItem, bool) {
vms, err := a.polledVMs(context.Background())
if err != nil {
return reims.VMListItem{}, false
}
for _, vm := range vms {
if vm.Name == name {
return vm, true
}
}
return reims.VMListItem{}, false
}
// wakePoll marks the polled list stale and runs pollVMs now. Call it after
// anything that changes which VMs exist or run.
func (a *App) wakePoll() {
a.mu.Lock()
a.lastVMsAt = time.Time{}
a.mu.Unlock()
select {
case a.pollWake <- struct{}{}:
default:
}
}
// cachedDiskPath is one VM's disk path from `reims-ctl show`, kept for
// diskPathTTL so GetVMStats doesn't run `show` every few seconds.
type cachedDiskPath struct {
path string
at time.Time
}
const diskPathTTL = time.Minute
// vmDiskPath resolves name's disk image path, reusing a recent answer. The
// path only changes through `reims-ctl set`, so at worst the disk-usage
// figure follows such a change a minute late.
func (a *App) vmDiskPath(ctx context.Context, c *reims.Client, name string) string {
a.mu.Lock()
cur, ok := a.diskPaths[name]
a.mu.Unlock()
if ok && time.Since(cur.at) < diskPathTTL {
return cur.path
}
d, err := c.Show(ctx, name)
if err != nil {
return ""
}
path := resolveVMDiskPath(d)
a.mu.Lock()
a.diskPaths[name] = cachedDiskPath{path: path, at: time.Now()}
a.mu.Unlock()
return path
}
func (a *App) emitLog(source, line string) {
redacted := reims.RedactLogLine(line)
ts := time.Now().Format("15:04:05")
@@ -269,6 +368,9 @@ func (a *App) emitLog(source, line string) {
if len(a.recentLogs) > 1000 {
a.recentLogs = a.recentLogs[len(a.recentLogs)-1000:]
}
for _, c := range a.logCaptures[source] {
c.add(redacted)
}
a.mu.Unlock()
if a.ctx == nil {
return
@@ -777,6 +879,7 @@ func (a *App) StartVM(name string) error {
a.watchWin10ColdReboot(name, qmpAddr)
}
a.startVMMonitor(name, curDetail, startAt)
a.wakePoll()
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
return nil
}
@@ -810,6 +913,7 @@ func (a *App) StopVM(name string, force bool) error {
a.mu.Lock()
delete(a.pendingChanges, name)
a.mu.Unlock()
a.wakePoll()
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
return nil
}
@@ -853,7 +957,9 @@ func (a *App) DeleteVM(name string, keepFiles bool) error {
a.mu.Lock()
delete(a.pendingChanges, name)
delete(a.transitions, name)
delete(a.diskPaths, name)
a.mu.Unlock()
a.wakePoll()
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
return nil
}
+50
View File
@@ -0,0 +1,50 @@
package main
import (
"context"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/driver/reims"
)
func TestPolledVMsReusesFreshPoll(t *testing.T) {
pid := 42
a := &App{pollWake: make(chan struct{}, 1)}
a.lastVMs = []reims.VMListItem{{Name: "m0", Dir: `D:\vms\m0`, PID: &pid, State: "running"}}
a.lastVMsAt = time.Now()
vm, ok := a.polledVM("m0")
if !ok || vm.State != "running" || vm.Dir != `D:\vms\m0` || *vm.PID != 42 {
t.Fatalf("polledVM = %+v, %v", vm, ok)
}
if _, ok := a.polledVM("missing"); ok {
t.Fatal("unknown VM should not be found")
}
vms, _ := a.polledVMs(context.Background())
vms[0].State = "stopped"
if a.lastVMs[0].State != "running" {
t.Fatal("polledVMs must return a copy, not the cached slice")
}
}
func TestWakePollMarksStaleAndWakesOnce(t *testing.T) {
a := &App{pollWake: make(chan struct{}, 1)}
a.lastVMsAt = time.Now()
a.wakePoll()
a.wakePoll() // a second wake while one is pending must not block
if !a.lastVMsAt.IsZero() {
t.Fatal("wakePoll should mark the polled list stale")
}
select {
case <-a.pollWake:
default:
t.Fatal("wakePoll should signal pollVMs")
}
select {
case <-a.pollWake:
t.Fatal("pending wakes should coalesce into one")
default:
}
}
-49
View File
@@ -1,49 +0,0 @@
package main
import (
"context"
"fmt"
"os"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/vmstart"
)
// startVM runs the same checks and preparation as the GUI's StartVM
// (internal/vmstart), then pins QEMU to P-cores once it runs. Guest Tools and
// the Win10 cold-reboot watcher are left out: both need the GUI process to
// keep running after the VM starts.
func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error {
rep := host.Inspect(cfg.DataRoot)
d, err := prep.Client.Show(ctx, name)
if err != nil {
return err
}
if d.State == "running" {
// Preparation rewrites extra-args and the OpenCore image; never under a live VM.
return fmt.Errorf("%s is already running", name)
}
if err := prep.CheckMemory(d.Memory, rep); err != nil {
return err
}
prep.Prepare(ctx, name, rep, &d)
if err := prep.Client.StartWithCompat(ctx, name, os.Stdout, os.Stderr, func(msg string) {
fmt.Fprintln(os.Stderr, msg)
}); err != nil {
return err
}
if !cfg.AutoPinPCores || !rep.HasHybridCores || rep.PCoreMask == 0 {
return nil
}
vms, err := prep.Client.List(ctx)
if err != nil {
return nil
}
for _, vm := range vms {
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
fmt.Fprintln(os.Stderr, vmstart.PinQEMU(cfg.Locale, rep, *vm.PID, d.CPUs))
}
}
return nil
}
+6
View File
@@ -0,0 +1,6 @@
//go:build !windows
package main
// attachConsole is only needed for Windows GUI-subsystem builds.
func attachConsole() {}
+58
View File
@@ -0,0 +1,58 @@
//go:build windows
package main
import (
"os"
"syscall"
)
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
procAttachConsole = kernel32.NewProc("AttachConsole")
)
const attachParentProcess = ^uintptr(0) // ATTACH_PARENT_PROCESS, (DWORD)-1
// attachConsole gives command-line mode somewhere to write. reims-go.exe is
// a GUI-subsystem program, so Windows starts it without a console. Handles
// the caller passed in (a pipe, a file: how agents and scripts run it) are
// kept; only missing ones are pointed at the console of the terminal that
// launched it.
func attachConsole() {
out, errOut, in := usable(os.Stdout), usable(os.Stderr), usable(os.Stdin)
if out && errOut && in {
return
}
if r, _, _ := procAttachConsole.Call(attachParentProcess); r == 0 {
return // started from Explorer or a shortcut: nowhere to write
}
if !out || !errOut {
if f, err := os.OpenFile("CONOUT$", os.O_RDWR, 0); err == nil {
if !out {
os.Stdout = f
}
if !errOut {
os.Stderr = f
}
}
}
if !in {
if f, err := os.OpenFile("CONIN$", os.O_RDWR, 0); err == nil {
os.Stdin = f
}
}
}
// usable reports whether f wraps a real handle the caller passed in.
func usable(f *os.File) bool {
if f == nil {
return false
}
h := syscall.Handle(f.Fd())
if h == 0 || h == syscall.InvalidHandle {
return false
}
t, err := syscall.GetFileType(h)
return err == nil && t != syscall.FILE_TYPE_UNKNOWN
}
+13 -6
View File
@@ -6,7 +6,7 @@
1. **零编译上手**:用户拿到单个 `reims-go.exe`(或便携压缩包),首次启动向导自动检测环境 → 下载/导入便携运行时 → 创建并启动 macOS Tahoe。
2. **不重复造 `reims-ctl` 的轮子**:`reims-go` 通过受控子进程包装 `reims-ctl`(及 `qemu-img`),避免像手写 PowerShell 启动脚本那样在每次上游变更参数时失效。
3. **GUI 与 CLI 同源**:所有核心能力落在 `internal/` Go 包中;既可双击启动 Wails 桌面界面,也可通过 `reims-go <subcommand>` 在终端或 CI 中自动化调用。
3. **GUI 与 CLI 同源、同一个 exe**:所有核心能力落在 `internal/` Go 包中。只发布一个 `reims-go.exe`:双击(无参数)打开 Wails 桌面界面,带子命令(`reims-go <subcommand>`)走命令行模式,供终端、脚本、CI 和 Agent 调用。2026-11-28 起不再单独发布 `reims-go-cli.exe`。
4. **C 盘零污染**:所有运行时、下载缓存、VM 磁盘与快照严格留在用户选定的 `<DataRoot>` 下。
5. **Day-1 中英双语(`zh-CN` / `en-US`)**:前端界面、装机引导文案(默认贴合简体中文 macOS 恢复与安装界面术语,如「磁盘工具 → 抹掉为 APFS → 重新安装 macOS」)与 CLI 输出从第一天即内置双语字典,自动跟随系统语言并支持在界面顶部实时切换(持久化到 `reims-go.json`)。
6. **跨平台开发友好**:虽然宿主机运行目标优先面向 Windows x86-64(WHPX),但所有 Windows 原生 API(`WinHvPlatform.dll`、注册表 Vulkan ICD、`GetLogicalProcessorInformationEx`、进程亲和性)严格隔离在 `*_windows.go` 构建标签中,提供 `*_other.go` 桩实现,确保在中文 macOS 开发环境上也能直接进行前端开发、`go build` 与 `go test ./...`。
@@ -17,7 +17,7 @@
flowchart TB
subgraph UI["交互层"]
GUI["Wails 桌面界面\n(React / Vite + WebView2)"]
CLI["CLI 子命令\n(reims-go doctor/runtime/installer/vm)"]
CLI["命令行模式(同一个 exe)\n(reims-go doctor/runtime/installer/vm)"]
end
subgraph Core["Go 核心服务层 (internal/)"]
@@ -83,8 +83,14 @@ flowchart TB
- **配置写入只用 `set`**:`reims-ctl set` 的修改在**下次启动**时生效(`cli.rs:73`);改图形会在 VM 停止时重建 OpenCore 镜像(`cli.rs:242`)。可改字段见 `cli.rs:551-616`,外壳如何呈现见 [`shell-design.md`](shell-design.md)。
### 3.5 启动编排:`internal/vmstart` 与 GUI 编排层
- `internal/vmstart` 是 GUI 和 CLI 共用的启动步骤:提交内存预检、离线辅助盘、恢复模式引导菜单、客体语言重放、WHPX 嵌套虚拟化兼容,以及启动后的 P 核绑定。GUI 的 `StartVM`(`app.go`)和 CLI 的 `vm start`(`cmd/reims-go/start.go`)都调用它。
- 只有 GUI 做的两步:Guest Tools 桥接(`guesttools_flow.go`)和 Win10 冷重启监视(`app.go`)。这两步都需要启动后仍在运行的进程,CLI 命令执行完就退出了,所以做不了。用 CLI 启动的 VM 没有剪贴板和共享目录;在 Win10 上,客体重启后 VM 会停下来,不会自动重新拉起。
- `internal/vmstart` 是 GUI 和 CLI 共用的启动步骤:提交内存预检、离线辅助盘、恢复模式引导菜单、客体语言重放、WHPX 嵌套虚拟化兼容,以及启动后的 P 核绑定。GUI 的 `StartVM`(`app.go`)调用它;CLI 的 `vm start`(`internal/cli/start.go`)通常把启动交给界面进程,只在指定了 `--data-root` 时自己调用它。
- 只有界面进程做的两步:Guest Tools 桥接(`guesttools_flow.go`)和 Win10 冷重启监视(`app.go`)。这两步都需要启动后仍在运行的进程,而命令执行完就退出,所以 `vm start` 会把启动交给界面进程:
- 界面已在运行:按 Wails 单实例协议(`options.SingleInstanceLock`,WM_COPYDATA)把 `--start-vm=<名称>` 发给它,不弹窗;
- 界面没在运行:以 `--background` 拉起一个只在托盘里运行的界面进程(`StartHidden`)。拉起时与调用方的控制台和句柄分离,Agent 读的管道会随命令结束而关闭;
- 两种情况都由界面调用 `StartVM`,再把结果写到 `<DataRoot>\tmp\cli-start-*.json`(只接受这个目录下的这类文件名),命令读到后带退出码返回。
- 指定了 `--data-root` 的 `vm start` 仍在命令进程里启动,没有剪贴板和共享目录,Win10 上客体重启后不会自动拉起。
- 单实例:同一用户只运行一个界面进程。再次双击会把已有窗口调到前台。`wails dev` 构建用另一个锁名(`internal/cli/instance_id_dev.go`),不会和已安装的 Reims-Go 互相抢。
- 命令行模式与 Windows 子系统:`reims-go.exe` 是 GUI 子系统程序。命令行模式会保留调用方传入的句柄(管道、文件),缺失的才用 `AttachConsole` 接回父进程控制台(`console_windows.go`)。所以 Agent、脚本、管道调用都能正常拿到输出和退出码;在交互式 PowerShell / cmd 里,提示符会先返回,要等命令结束需加 `| Out-Host`。
- GUI 的其余编排仍在根目录的 `App`(`app.go`)和各个 `*_flow.go` 里:CoW 派生(`clone_flow.go`)、磁盘扩容与回收(`disk_flow.go`)、运行监视与里程碑日志(`vm_monitor.go`)。
- **CoW 派生**:先 `qemu-img create -f qcow2 -F qcow2 -b <golden> <overlay>`,再 `reims-ctl create --disk <overlay> --disk-mode in-place`,原盘不改。真机上从派生盘启动**待验证**。
- **SSH**:只展示 `reims-ctl` 的 `--ssh-port` 转发端口,没有命令执行通道。
@@ -93,9 +99,10 @@ flowchart TB
```text
reims-go/
├── cmd/
│ └── reims-go/ # 主入口(无参启动 Wails GUI,带子命令走 CLI 模式)
├── main.go # 唯一入口:无参数启动 Wails 界面,带子命令走 internal/cli
├── window_launch.go # 界面处理 --background / --start-vm 与第二次启动
├── internal/
│ ├── cli/ # 命令行模式:子命令、把 vm start 交给界面进程
│ ├── config/ # reims-go.json(含 locale: zh-CN|en-US、DataRoot、P-Core 开关)
│ ├── i18n/ # Go 端中英双语消息字典与结构化错误码
│ ├── host/ # WHPX、提交内存预检、Vulkan ICD、P/E 核拓扑、进程亲和性(*_windows.go + *_other.go)
+5 -3
View File
@@ -62,7 +62,7 @@ flowchart LR
- 完整跑完一次离线安装包下载(18.4 GB);
- 下载完成时 `done` 事件里是否带 `installer.build` 字段(代码按可选处理)。
- [x] **M1.4**:`internal/driver/reims` — 封装 `reims-ctl` 的 `list --json`、`show`、`create`、`start`、`stop`、`set`、`insert`、`eject`、`update-opencore`、`delete`、`logs`、`downloads` 与 `qemu-img` 转换/CoW 派生,带单元测试。
- [x] **M1.5**:`cmd/reims-go` — 提供 `doctor`、`runtime available/fetch/install/list/use`、`installer list/download/cached/delete`、`vm list/create/set/start/stop/eject/type`、`version` 子命令,支持 `--lang zh-CN|en-US` 与中英双语输出。
- [x] **M1.5**:命令行模式(2026-11-28 起从 `cmd/reims-go` 移到 `internal/cli`,并入 `reims-go.exe`)— 提供 `doctor`、`runtime available/fetch/install/list/use`、`installer list/download/cached/delete`、`vm list/create/set/start/stop/eject/type`、`version` 子命令,支持 `--lang zh-CN|en-US` 与中英双语输出。
**DoD**:
- 在一个从未 dot-source `reims-env.ps1` 的全新 PowerShell 中,仅运行 `reims-go` CLI 即可完成体检、导入运行时、断点续传下载离线包、启动/查看 VM;
@@ -78,7 +78,8 @@ flowchart LR
- [x] **M2.2**:**离线安装包下载管理器(核心体验)** — 调用 `reims-util --json` 展示可选 macOS Tahoe 精确版本,在 GUI 内直接触发宿主机直连下载、实时显示进度条 / 速率 / 已下体积 / 自动重试状态、支持「暂停/取消」与「断点续传」,并可视化管理 `<DataRoot>\data\reims-ctl\installers` 缓存。
- 2026-11-28(v0.2):侧边栏新增「安装包」页。上半部分是已下载的安装包:可以继续未下载完的、删除(两步确认,删除走 `reims-ctl downloads delete`)。下半部分是 Apple 提供的版本:下载、进度、暂停。下载前检查剩余空间(按安装包大小加 10% 计,因为一开始就会占满整个镜像的空间)。速率显示在进度的悬停提示里。暂停后再次下载会接着下。
- [x] **M2.3**:**VM 主面板与创建/装机引导(贴合简体中文 / 英文 macOS 界面术语)** — 实例列表、实时状态、一键启停与串口/图形日志抽屉;新建默认推荐复用本地离线包 + 默认 `NVMe` 磁盘控制器,启动前校验提交内存;离线安装通过纯 Go HFS+ 辅助盘 `REIMSHELP` 自动绕过 macOS 26.7.3 缺 `pkgutil` / `installer -target` 失效,支持空白盘自动 APFS 抹盘 + QMP 一键键入;提供对称的「进入/退出恢复模式」切换与约 1 GB 在线恢复镜像兜底拉取。
- [x] **M2.4**:打包为单文件 `reims-go.exe`(~13.3 MB)与命令行版 `reims-go-cli.exe`(~11.5 MB)。无代码签名,冷启动时间待量化实测。
- [x] **M2.4**:打包为单文件 `reims-go.exe`(~13.3 MB)。无代码签名,冷启动时间待量化实测。
- 2026-11-28:不再单独发布命令行版 `reims-go-cli.exe`,命令行模式并入同一个 exe:带子命令即走命令行;`vm start` 把启动交给界面进程(没在运行就以 `--background` 拉起到托盘),因此命令行启动的 VM 也有剪贴板、共享目录和 Win10 冷重启。细节见 [`architecture.md`](architecture.md) 3.5 节。
- [x] **M2.5**:**设置面板(对齐 macOS)** — 按 [`shell-design.md`](shell-design.md) 类别分页;VM 运行中可改并标出生效时机;保存前在 Go 侧校验提交内存与 ICD,写入仅走 `reims-ctl set`。
- [x] **M2.6**:**待生效修改** — 详情页列出「已保存、下次启动才生效」的修改并提供「重启以应用」按钮。
- [x] **M2.7**:**主窗口结构** — 侧边栏 + 详情 + 工具栏,分步新建助手并在最后一步预览完整 `reims-ctl` 命令。
@@ -116,7 +117,7 @@ flowchart LR
- [ ] **M4.1**:**上游窗口与性能 PR 跟进(运行时升级,持续跟踪)** — 已建立跟踪清单 [`docs/upstream-pr-prep.md`](upstream-pr-prep.md),跟踪上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 关键 Windows PR(`#153`、`#152`、`#107`、`#123`、`#172` 与 Win→Command)合入后由 `build-runtime.yml` 的每日构建自动产出 `alpha` 运行时。
- [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 与 GUI;运行时构建 workflow 每天从上游最新 commit 自动构建(2026-11-28 起;已发布过的 commit 跳过),在 `windows-latest` 上通过 MSYS2 CLANG64 拉取 `vendor/qemu`、按 `patches/series.txt` 应用补丁(已被上游合并的跳过并开 issue 提醒,冲突就停止)、调用上游 `scripts/install-ctl.sh --yes`、执行 `scripts/pack-runtime.ps1`,经 `scripts/check-runtime-alpha.ps1` 准入检查后发布 `alpha` 预发布包与对应源码包,并只保留最近 7 个 alpha。**(GitHub Actions 运行时编译待首次手动触发实跑验证)**
- [x] **M4.3**:**`alpha` → `stable` 冒烟脚本** — 已编写 [scripts/smoke-runtime.ps1](../scripts/smoke-runtime.ps1),支持校验 SHA-256、在干净隔离目录(无 MSYS2 PATH)解压并跑 `reims-ctl doctor` / `list --json` 与合规文件核查,产出供人工评审的 Markdown 冒烟报告。
- [x] **M4.4**:**客户端自动发布与在线更新检查** — 已新增 [.github/workflows/release.yml](../.github/workflows/release.yml)(打 `v*` tag 自动跑测、构建 `reims-go-<tag>-windows-amd64.exe` / `reims-go-cli-<tag>-windows-amd64.exe` + `SHA256SUMS.txt` 并发布 GitHub Release);客户端与 CLI 接入 `internal/version` 版本号与稳定版在线更新检查(`HostView` 一键检查/跳转下载,运行时支持多版本回滚切换);合规文件(`NOTICE.md`、`LICENSE`、运行时源码包与 `MSYS2-PACKAGES.txt`)已随构建脚本落盘。
- [x] **M4.4**:**客户端自动发布与在线更新检查** — 已新增 [.github/workflows/release.yml](../.github/workflows/release.yml)(打 `v*` tag 自动跑测、构建 `reims-go-<tag>-windows-amd64.exe` + `SHA256SUMS.txt`(2026-11-28 前还附带 `reims-go-cli-<tag>-windows-amd64.exe`) 并发布 GitHub Release);客户端与 CLI 接入 `internal/version` 版本号与稳定版在线更新检查(`HostView` 一键检查/跳转下载,运行时支持多版本回滚切换);合规文件(`NOTICE.md`、`LICENSE`、运行时源码包与 `MSYS2-PACKAGES.txt`)已随构建脚本落盘。
- [ ] **M4.5**:**补丁上游化(人工提交 PR)** — 已在 [`docs/upstream-pr-prep.md`](upstream-pr-prep.md) 整理好 4 个 QEMU 补丁的根因、复现步骤与实测证据,待人工向上游提 PR 并合入后从 `patches/` 队列清零。
**DoD**:
@@ -141,6 +142,7 @@ flowchart LR
- [x] **M5.3(本仓)**:**Guest Tools 2.0(图片剪贴板 + 真挂载式共享目录)**
- 剪贴板 2.0:Windows 端支持原生 `"PNG"` 与 32-bit `CF_DIB` 双向图片剪贴板编解码(纯 Go,零外部依赖),服务端基于 `GetClipboardSequenceNumber()` 实现低延迟长轮询事件唤醒(`?since=&wait=&accept=image`),Guest POSIX 脚本使用 macOS 原生 `osascript` + `sips` 实现零 Xcode/Python 的文本 + PNG 截图双向剪贴板;
- 共享目录 2.0:在 `reims-go` 内置仅监听 `127.0.0.1`、带 per-VM 256-bit Basic/Bearer Token 鉴权与严格目录防穿越的纯 Go **WebDAV 服务**(`/dav/<vm>/`),Guest 侧优先 `mount_webdav` 实时零双份挂载到 `~/Desktop/ReimsShare` 并在不可用时自动回退同步模式;
- Windows 盘符只读共享:每台 VM 在「存储与网络」设置中独立开启内部固定盘符,默认全部关闭,系统盘显示敏感信息提示;新增 `/dav/<vm>/drives/<盘符>/`,由服务端同时限制 HTTP 写方法和文件打开标志,持久化并复核 Volume GUID 防止盘符重绑定,限制 `PROPFIND Depth` 避免整盘递归,并验证 Junction / 符号链接解析后的目标仍在授权盘符内。Guest Tools 4 根据 `/v1/config` 自动挂载/卸载 `Windows C` 等 Finder 卷,关闭开关立即拒绝新请求。**(macOS Finder 真机挂载、只读兼容与重连待验证)**
- UI 升级:主界面实时显示 Guest Tools 连接状态、`WebDAV 挂载` / `文件同步` 模式徽章、旧版工具升级提示与「投递文件到 macOS」快捷入口。**(macOS 桌面端真机 WebDAV 挂载与图片剪贴板联调待验证)**
- [x] **M5.4(本仓)**:**防休眠守护、系统托盘驻留与资源状态条**
- 防休眠守护:Guest Tools 2.0 支持由宿主机 UI 一键实时开关 `caffeinate -dims`(免 sudo,通过 `/v1/config` 实时下发),并在 `REIMSTOOLS` 附带可选 `Apply-Prevent-Sleep-pmset.command`;
+1 -1
View File
@@ -43,7 +43,7 @@
| 键盘与指针 | 点击窗口时捕获键鼠 | `--capture` | 下次启动 | — |
| 串口与日志 | 日志开关、日志级别 | `--logs`、`--log-level` | 下次启动 | 日志在详情页抽屉里实时查看 |
| 高级 | 关机等待时间、额外 QEMU 参数、环境变量 | `--stop-timeout`、`--extra-args`、`--env` | 下次启动 | `reims-go` 自己注入的 QMP 参数要和用户填的分开存放、合并写入,不能互相覆盖 |
| (VZ 有,上游没有) | 共享目录、剪贴板、vsock | 无 | — | 先不做,界面上也不放占位 |
| 宿客协作(Reims-Go 扩展) | ReimsShare、Windows 盘符只读共享、剪贴板 | Guest Tools HTTP/WebDAV,无对应 `reims-ctl` 参数 | 立即生效 | 每台 VM 独立配置;盘符共享默认全部关闭,仅枚举内部固定磁盘,系统盘提示敏感信息风险 |
## 4. 状态模型
+187
View File
@@ -0,0 +1,187 @@
package main
import (
"fmt"
"strings"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// DriveShareInfo describes one currently available internal fixed drive.
type DriveShareInfo struct {
Drive string `json:"drive"`
Root string `json:"root"`
Selected bool `json:"selected"`
System bool `json:"system"`
}
// DriveShareSettings is the live, per-VM read-only drive sharing configuration.
type DriveShareSettings struct {
Enabled bool `json:"enabled"`
ReadOnly bool `json:"read_only"`
RequiredAgentVersion int `json:"required_agent_version"`
Drives []DriveShareInfo `json:"drives"`
}
func shareableFixedDrives() []host.Drive {
all := host.ListDrives()
out := make([]host.Drive, 0, len(all))
for _, drive := range all {
if drive.External {
continue
}
if _, ok := guesttools.NormalizeDriveLetter(drive.Root); ok && drive.VolumeGUID != "" {
out = append(out, drive)
}
}
return out
}
func normalizeDriveSelection(available []host.Drive, selected []string) ([]string, error) {
allowed := make(map[string]bool, len(available))
for _, drive := range available {
if letter, ok := guesttools.NormalizeDriveLetter(drive.Root); ok && !drive.External {
allowed[letter] = true
}
}
requested := make(map[string]bool, len(selected))
for _, raw := range selected {
letter, ok := guesttools.NormalizeDriveLetter(raw)
if !ok {
return nil, fmt.Errorf("invalid drive %q", raw)
}
if !allowed[letter] {
return nil, fmt.Errorf("drive %s is not an available internal fixed drive", letter)
}
requested[letter] = true
}
out := []string{}
for _, drive := range available {
letter, _ := guesttools.NormalizeDriveLetter(drive.Root)
if requested[letter] {
out = append(out, letter)
}
}
return out, nil
}
// validatedDriveConfig derives runtime roots only from currently present fixed volumes
// whose stable GUID matches the user's persisted selection. It never saves filtered state.
func validatedDriveConfig(cfg guesttools.VMConfig) guesttools.VMConfig {
return validatedDriveConfigForVolumes(cfg, shareableFixedDrives())
}
func validatedDriveConfigForVolumes(cfg guesttools.VMConfig, available []host.Drive) guesttools.VMConfig {
selected := make(map[string]bool, len(cfg.SharedDrives))
for _, raw := range cfg.SharedDrives {
if letter, ok := guesttools.NormalizeDriveLetter(raw); ok {
selected[letter] = true
}
}
cfg.SharedDrives = []string{}
cfg.DriveRoots = make(map[string]string)
for _, drive := range available {
if drive.External || drive.VolumeGUID == "" {
continue
}
letter, _ := guesttools.NormalizeDriveLetter(drive.Root)
expected := cfg.DriveVolumes[letter]
if !selected[letter] || expected == "" || !strings.EqualFold(expected, drive.VolumeGUID) {
continue
}
cfg.SharedDrives = append(cfg.SharedDrives, letter)
cfg.DriveRoots[letter] = drive.Root
}
return cfg
}
func selectedVolumeIdentities(available []host.Drive, selected []string) map[string]string {
wanted := make(map[string]bool, len(selected))
for _, letter := range selected {
wanted[letter] = true
}
out := make(map[string]string)
for _, drive := range available {
letter, ok := guesttools.NormalizeDriveLetter(drive.Root)
if ok && wanted[letter] && drive.VolumeGUID != "" {
out[letter] = drive.VolumeGUID
}
}
return out
}
func makeDriveShareSettings(cfg guesttools.VMConfig, available []host.Drive) DriveShareSettings {
selected := make(map[string]bool, len(cfg.SharedDrives))
for _, raw := range cfg.SharedDrives {
if letter, ok := guesttools.NormalizeDriveLetter(raw); ok {
selected[letter] = true
}
}
settings := DriveShareSettings{
Enabled: cfg.DriveSharingEnabled, ReadOnly: true,
RequiredAgentVersion: guesttools.DriveShareAgentVersion, Drives: []DriveShareInfo{},
}
for _, drive := range available {
if drive.External {
continue
}
letter, ok := guesttools.NormalizeDriveLetter(drive.Root)
if !ok {
continue
}
expected := cfg.DriveVolumes[letter]
identityMatches := expected != "" && strings.EqualFold(expected, drive.VolumeGUID)
settings.Drives = append(settings.Drives, DriveShareInfo{
Drive: letter, Root: drive.Root, Selected: selected[letter] && identityMatches, System: drive.System,
})
}
return settings
}
// GetVMDriveShareSettings returns per-VM switches without creating Guest Tools config.
func (a *App) GetVMDriveShareSettings(name string) (DriveShareSettings, error) {
detail, err := a.GetVMDetail(name)
if err != nil {
return DriveShareSettings{}, err
}
cfg, _ := guesttools.ReadVMConfig(detail.Directory)
return makeDriveShareSettings(cfg, shareableFixedDrives()), nil
}
// SetVMDriveShareSettings persists selected drive letters and applies access control immediately.
func (a *App) SetVMDriveShareSettings(name string, enabled bool, drives []string) (DriveShareSettings, error) {
detail, err := a.GetVMDetail(name)
if err != nil {
return DriveShareSettings{}, err
}
if detail.Directory == "" {
return DriveShareSettings{}, fmt.Errorf("VM %s has no directory", name)
}
available := shareableFixedDrives()
normalized, err := normalizeDriveSelection(available, drives)
if err != nil {
return DriveShareSettings{}, err
}
srv, port, err := a.ensureGuestToolsBridge()
if err != nil {
return DriveShareSettings{}, err
}
cfg, err := guesttools.LoadOrCreateVMConfig(detail.Directory, name, a.vmSharedDir(name), port)
if err != nil {
return DriveShareSettings{}, err
}
cfg.DriveSharingEnabled = enabled
cfg.SharedDrives = normalized
cfg.DriveVolumes = selectedVolumeIdentities(available, normalized)
if err := guesttools.SaveVMConfig(detail.Directory, cfg); err != nil {
return DriveShareSettings{}, err
}
srv.RegisterVM(validatedDriveConfig(cfg))
a.emitLog(name, fmt.Sprintf("Read-only Windows drive sharing enabled=%v drives=%v", enabled, normalized))
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return makeDriveShareSettings(cfg, available), nil
}
+62
View File
@@ -0,0 +1,62 @@
package main
import (
"testing"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
)
func TestNormalizeDriveSelectionRejectsUnavailableAndExternalDrives(t *testing.T) {
available := []host.Drive{{Root: `C:\`, System: true}, {Root: `D:\`}, {Root: `E:\`, External: true}}
got, err := normalizeDriveSelection(available, []string{"d", "D:", `C:\`})
if err != nil {
t.Fatal(err)
}
if len(got) != 2 || got[0] != "C" || got[1] != "D" {
t.Fatalf("normalized selection = %#v, want [C D]", got)
}
for _, selected := range [][]string{{"E"}, {"Z"}, {"../C"}, {"C:/"}} {
if _, err := normalizeDriveSelection(available, selected); err == nil {
t.Fatalf("selection %#v unexpectedly accepted", selected)
}
}
}
func TestValidatedDriveConfigRejectsMissingAndReboundVolumes(t *testing.T) {
cfg := guesttools.VMConfig{
DriveSharingEnabled: true, SharedDrives: []string{"C", "D", "E"},
DriveVolumes: map[string]string{"C": "vol-c", "D": "old-volume-d"},
}
available := []host.Drive{
{Root: `C:\`, VolumeGUID: "vol-c"},
{Root: `D:\`, VolumeGUID: "new-volume-d"},
{Root: `E:\`, VolumeGUID: "vol-e", External: true},
}
got := validatedDriveConfigForVolumes(cfg, available)
if len(got.SharedDrives) != 1 || got.SharedDrives[0] != "C" || got.DriveRoots["C"] != `C:\` {
t.Fatalf("validated config = %#v, want only original C volume", got)
}
if len(got.DriveVolumes) != 2 {
t.Fatalf("runtime validation mutated persisted identities: %#v", got.DriveVolumes)
}
cfg.SharedDrives = []string{"C"}
cfg.DriveVolumes = nil
if got := validatedDriveConfigForVolumes(cfg, available); len(got.SharedDrives) != 0 {
t.Fatalf("legacy config without volume identity was trusted: %#v", got)
}
}
func TestMakeDriveShareSettingsDefaultsToReadOnlyAndPerDriveSelection(t *testing.T) {
available := []host.Drive{{Root: `C:\`, System: true, VolumeGUID: "vol-c"}, {Root: `D:\`, VolumeGUID: "vol-d"}}
settings := makeDriveShareSettings(guesttools.VMConfig{}, available)
if settings.Enabled || !settings.ReadOnly || settings.RequiredAgentVersion != guesttools.DriveShareAgentVersion {
t.Fatalf("unexpected defaults: %#v", settings)
}
if settings.Drives == nil || len(settings.Drives) != 2 {
t.Fatalf("drives = %#v, want two entries", settings.Drives)
}
settings = makeDriveShareSettings(guesttools.VMConfig{DriveSharingEnabled: true, SharedDrives: []string{"D"}, DriveVolumes: map[string]string{"D": "vol-d"}}, available)
if !settings.Enabled || settings.Drives[0].Selected || !settings.Drives[1].Selected || !settings.Drives[0].System {
t.Fatalf("unexpected settings: %#v", settings)
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "reims-go-frontend",
"private": true,
"version": "0.2.2",
"version": "0.2.3",
"type": "module",
"scripts": {
"dev": "vite",
+1 -1
View File
@@ -1 +1 @@
7782101f68324d7c033ce75c59399d77
f71dbd21d10dd124677343ad731d7f59
+82 -1
View File
@@ -22,7 +22,7 @@ import {
optStatusLabel,
parseKernelIrqchip,
} from '../lib/optimizations'
import { DiskCompactResult, DiskResizeResult, HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMDetail, VMStats } from '../types'
import { DiskCompactResult, DiskResizeResult, DriveShareSettings, HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMDetail, VMStats } from '../types'
import { Button, IconButton } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, SetValue, Switch } from '../ui/settings'
@@ -142,6 +142,12 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
const [diskOpBusy, setDiskOpBusy] = useState<'resize' | 'compact' | ''>('')
const [resizeResult, setResizeResult] = useState<DiskResizeResult | null>(null)
const [compactResult, setCompactResult] = useState<DiskCompactResult | null>(null)
const [driveSettings, setDriveSettings] = useState<DriveShareSettings | null>(null)
const [driveBusy, setDriveBusy] = useState(false)
const driveBusyRef = useRef(false)
const activeVMNameRef = useRef(detail.name)
activeVMNameRef.current = detail.name
const [driveErr, setDriveErr] = useState('')
const pane = useRef<HTMLDivElement>(null)
const presets = recommendedDisplayPresets(host)
@@ -186,6 +192,35 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
el?.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
}, [issues, cat])
useEffect(() => {
let active = true
setDriveSettings(null)
setDriveErr('')
api.GetVMDriveShareSettings(detail.name)
.then((settings) => { if (active) setDriveSettings(settings) })
.catch((e) => { if (active) setDriveErr(String(e).replace(/^Error:\s*/, '')) })
return () => { active = false }
}, [detail.name])
const updateDriveShares = async (enabled: boolean, selected: string[]) => {
if (driveBusyRef.current || !driveSettings) return
driveBusyRef.current = true
const vmName = detail.name
setDriveBusy(true)
setDriveErr('')
try {
const next = await api.SetVMDriveShareSettings(vmName, enabled, selected)
if (activeVMNameRef.current === vmName) setDriveSettings(next)
} catch (e) {
if (activeVMNameRef.current === vmName) setDriveErr(String(e).replace(/^Error:\s*/, ''))
} finally {
driveBusyRef.current = false
setDriveBusy(false)
}
}
const selectedDrives = () => (driveSettings?.drives ?? []).filter((d) => d.selected).map((d) => d.drive)
const handleSave = async () => {
if (busy || changed.length === 0 || localBlock) return
setErr('')
@@ -593,6 +628,52 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
}
/>
</SetGroup>
<SetGroup title={tr('driveShareTitle')} note={tr('driveShareReadOnly')}>
<SetRow
title={tr('driveShareMaster')}
desc={tr('driveShareMasterDesc')}
control={
<Switch
label={tr('driveShareMaster')}
checked={!!driveSettings?.enabled}
disabled={!driveSettings || driveBusy}
onChange={(enabled) => void updateDriveShares(enabled, selectedDrives())}
/>
}
/>
{driveErr && <div className="notice" role="alert">{driveErr}</div>}
{driveSettings?.enabled && selectedDrives().length > 0 &&
(detail.guest_tools_agent_version ?? 0) < driveSettings.required_agent_version && (
<div className="notice">{tr('driveShareNeedsTools', { version: driveSettings.required_agent_version })}</div>
)}
{(driveSettings?.drives ?? []).map((drive) => {
const title = `Windows (${drive.drive}:)`
return (
<SetRow
key={drive.drive}
title={title}
desc={drive.system ? tr('driveShareSystem', { root: drive.root }) : tr('driveShareDrive', { root: drive.root })}
disabled={!driveSettings?.enabled || driveBusy}
reason={!driveSettings?.enabled ? tr('driveShareMasterOff') : undefined}
control={
<Switch
label={title}
checked={drive.selected}
disabled={driveBusy}
onChange={(enabled) => {
const next = selectedDrives().filter((letter) => letter !== drive.drive)
if (enabled) next.push(drive.drive)
void updateDriveShares(driveSettings?.enabled ?? false, next)
}}
/>
}
/>
)
})}
{driveSettings && driveSettings.drives.length === 0 && (
<SetValue title={tr('driveShareTitle')} value={tr('driveShareNoDrives')} />
)}
</SetGroup>
<SetGroup title={tr('catNetwork')}>
<SetRow
{...rowProps('network')}
+4 -3
View File
@@ -83,8 +83,9 @@ export const VMPage: React.FC<Props> = ({
const running = state === 'running'
const transitioning = state === 'starting' || state === 'stopping'
// Screen thumbnail (thumbnail_flow.go): a fresh frame every 5 s while the VM
// runs, otherwise the last frame saved. Skipped while the window is hidden.
// Screen thumbnail (thumbnail_flow.go): a fresh frame every 15 s while the VM
// runs, otherwise the last frame saved. Skipped while this window is hidden;
// the backend also skips it while the VM's own window is in front.
const [thumb, setThumb] = useState<VMThumbnail | null>(null)
useEffect(() => { setThumb(null) }, [name])
useEffect(() => {
@@ -94,7 +95,7 @@ export const VMPage: React.FC<Props> = ({
api.GetVMThumbnail(name).then((t) => { if (live && t.data_url) setThumb(t) }).catch(() => {})
}
pull()
const timer = running ? window.setInterval(pull, 5000) : undefined
const timer = running ? window.setInterval(pull, 15000) : undefined
return () => { live = false; if (timer) window.clearInterval(timer) }
}, [name, running])
+18
View File
@@ -391,6 +391,15 @@ const dict = {
resCustom: '自定义',
resCustomSub: '宽 × 高',
resInvalid: '格式为 宽x高,例如 2560x1600',
driveShareTitle: 'Windows 盘符共享',
driveShareMaster: '共享 Windows 盘符',
driveShareMasterDesc: '将所选内部固定磁盘挂载到 macOS Finder,立即生效',
driveShareReadOnly: '只读 · macOS 可以打开和复制文件,不能修改 Windows 文件',
driveShareSystem: '{root} · 系统盘包含个人文件和凭据,请谨慎共享',
driveShareDrive: '{root} · 只读挂载为 Windows 盘符',
driveShareNeedsTools: '需要 Guest Tools {version} 或更新版本。运行中的 VM 要先重启以更新 REIMSTOOLS,然后在 macOS 中重新运行安装命令',
driveShareMasterOff: '先开启 Windows 盘符共享',
driveShareNoDrives: '没有可共享的内部固定磁盘',
networkDesc: '通过 NAT 共享宿主的网络连接',
sshForward: 'SSH 端口转发',
sshOffDesc: '把宿主的一个端口转发到 macOS 的 22 端口',
@@ -881,6 +890,15 @@ const dict = {
resCustom: 'Custom',
resCustomSub: 'Width × height',
resInvalid: 'Use WIDTHxHEIGHT, e.g. 2560x1600',
driveShareTitle: 'Windows drive sharing',
driveShareMaster: 'Share Windows drives',
driveShareMasterDesc: 'Mounts selected internal fixed disks in macOS Finder; applies immediately',
driveShareReadOnly: 'Read-only · macOS can open and copy files, but cannot change Windows files',
driveShareSystem: '{root} · The system disk contains personal files and credentials; share with care',
driveShareDrive: '{root} · Mounted read-only as a Windows drive',
driveShareNeedsTools: 'Requires Guest Tools {version} or newer. Restart a running VM to update REIMSTOOLS, then run the install command in macOS again',
driveShareMasterOff: 'Turn on Windows drive sharing first',
driveShareNoDrives: 'No internal fixed disks are available to share',
networkDesc: 'Shares the host connection through NAT',
sshForward: 'SSH port forwarding',
sshOffDesc: 'Forwards a host port to port 22 in macOS',
+1
View File
@@ -60,6 +60,7 @@ export type AppState = Omit<Model<main.AppState>, 'config' | 'host' | 'optimizat
export type AppUpdateInfo = version.UpdateInfo
export type VMDetail = reims.VMDetail
export type VMStats = main.VMStats
export type DriveShareSettings = Model<main.DriveShareSettings>
/** One frame of a VM's screen (thumbnail_flow.go). Empty data_url: none yet. */
export type VMThumbnail = main.VMThumbnail
export type ValidationIssue = reims.ValidationIssue
+4
View File
@@ -56,6 +56,8 @@ export function GetTasks():Promise<Array<main.Task>>;
export function GetVMDetail(arg1:string):Promise<reims.VMDetail>;
export function GetVMDriveShareSettings(arg1:string):Promise<main.DriveShareSettings>;
export function GetVMStats(arg1:string):Promise<main.VMStats>;
export function GetVMThumbnail(arg1:string):Promise<main.VMThumbnail>;
@@ -104,6 +106,8 @@ export function SetMinimizeToTray(arg1:boolean):Promise<void>;
export function SetRuntimeChannel(arg1:string):Promise<void>;
export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array<string>):Promise<main.DriveShareSettings>;
export function ShowMainWindow():Promise<void>;
export function StartVM(arg1:string):Promise<void>;
+8
View File
@@ -102,6 +102,10 @@ export function GetVMDetail(arg1) {
return window['go']['main']['App']['GetVMDetail'](arg1);
}
export function GetVMDriveShareSettings(arg1) {
return window['go']['main']['App']['GetVMDriveShareSettings'](arg1);
}
export function GetVMStats(arg1) {
return window['go']['main']['App']['GetVMStats'](arg1);
}
@@ -198,6 +202,10 @@ export function SetRuntimeChannel(arg1) {
return window['go']['main']['App']['SetRuntimeChannel'](arg1);
}
export function SetVMDriveShareSettings(arg1, arg2, arg3) {
return window['go']['main']['App']['SetVMDriveShareSettings'](arg1, arg2, arg3);
}
export function ShowMainWindow() {
return window['go']['main']['App']['ShowMainWindow']();
}
+54
View File
@@ -387,6 +387,60 @@ export namespace main {
this.recommended = source["recommended"];
}
}
export class DriveShareInfo {
drive: string;
root: string;
selected: boolean;
system: boolean;
static createFrom(source: any = {}) {
return new DriveShareInfo(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.drive = source["drive"];
this.root = source["root"];
this.selected = source["selected"];
this.system = source["system"];
}
}
export class DriveShareSettings {
enabled: boolean;
read_only: boolean;
required_agent_version: number;
drives: DriveShareInfo[];
static createFrom(source: any = {}) {
return new DriveShareSettings(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.enabled = source["enabled"];
this.read_only = source["read_only"];
this.required_agent_version = source["required_agent_version"];
this.drives = this.convertValues(source["drives"], DriveShareInfo);
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
if (!a) {
return a;
}
if (a.slice && a.map) {
return (a as any[]).map(elem => this.convertValues(elem, classs));
} else if ("object" === typeof a) {
if (asMap) {
for (const key of Object.keys(a)) {
a[key] = new classs(a[key]);
}
return a;
}
return new classs(a);
}
return a;
}
}
export class PendingChange {
field: string;
from: string;
+6 -6
View File
@@ -66,7 +66,7 @@ func (a *App) inputBridgeEnv(name, vmDir string) []string {
if err != nil || cfg.Token == "" {
return nil
}
srv.RegisterVM(cfg)
srv.RegisterVM(validatedDriveConfig(cfg))
return []string{
fmt.Sprintf("REIMS_GO_INPUT_URL=http://127.0.0.1:%d/v1/host-text", port),
"REIMS_GO_INPUT_TOKEN=" + cfg.Token,
@@ -99,7 +99,7 @@ func (a *App) registerExistingGuestTools(ctx context.Context) {
cfg.Port = port
_ = guesttools.SaveVMConfig(det.Directory, cfg)
}
srv.RegisterVM(cfg)
srv.RegisterVM(validatedDriveConfig(cfg))
}
}
}
@@ -117,7 +117,7 @@ func (a *App) populateGuestToolsDetail(d *reims.VMDetail) {
d.SharedDir = cfg.SharedDir
}
if srv, _, err := a.ensureGuestToolsBridge(); err == nil {
srv.RegisterVM(cfg)
srv.RegisterVM(validatedDriveConfig(cfg))
st := srv.Status(d.Name, 15*time.Second)
d.GuestToolsConnected = st.Connected
d.GuestToolsMountMode = st.MountMode
@@ -149,7 +149,7 @@ func (a *App) syncGuestTools(c *reims.Client, name string, cur *reims.VMDetail)
a.emitLog(name, "Warning: could not load Guest Tools config: "+err.Error())
return
}
srv.RegisterVM(cfg)
srv.RegisterVM(validatedDriveConfig(cfg))
if !attached {
return
}
@@ -193,7 +193,7 @@ func (a *App) AttachGuestTools(name string) error {
if err != nil {
return err
}
srv.RegisterVM(cfg)
srv.RegisterVM(validatedDriveConfig(cfg))
imgPath := a.guestToolsImagePath(name)
if err := guesttools.BuildToolsDiskImage(imgPath, cfg); err != nil {
@@ -290,7 +290,7 @@ func (a *App) SetGuestPreventSleep(name string, enabled bool) error {
if err := guesttools.SaveVMConfig(d.Directory, cfg); err != nil {
return err
}
srv.RegisterVM(cfg)
srv.RegisterVM(validatedDriveConfig(cfg))
srv.SetPreventSleep(name, enabled)
a.emitLog(name, fmt.Sprintf("Guest Tools prevent-sleep guard set to %v", enabled))
if a.ctx != nil {
+33 -12
View File
@@ -1,4 +1,4 @@
package main
package cli
import (
"context"
@@ -22,11 +22,24 @@ import (
"github.com/Nwflower/reims-go/internal/vmstart"
)
func main() {
if err := run(os.Args[1:]); err != nil {
// Package cli is reims-go's command-line mode. The single reims-go.exe opens
// the desktop window when started without a command and runs this package
// when given one (see main.go); both share the internal/ packages.
// Main runs one command and returns the process exit code.
func Main(args []string) int {
if err := run(args); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
return 1
}
return 0
}
// IsCommand reports whether args ask for command-line mode rather than the
// desktop window: anything except no arguments or the window's own flags.
func IsCommand(args []string) bool {
_, isWindow := ParseWindowArgs(args)
return !isWindow
}
func run(args []string) error {
@@ -65,7 +78,7 @@ func run(args []string) error {
case "runtime":
return cmdRuntime(cfg, loc, rest[1:])
case "vm":
return cmdVM(cfg, loc, rest[1:])
return cmdVM(cfg, loc, rest[1:], *dataRootFlag == "")
case "installer":
return cmdInstaller(cfg, loc, rest[1:])
case "version", "-v", "--version":
@@ -81,9 +94,11 @@ func run(args []string) error {
func printUsage(loc i18n.Locale) {
if loc == i18n.ZhCN {
fmt.Println("reims-go - Windows 一站式免编译 reims-vgpu 启动器与 CLI")
fmt.Println("reims-go - Windows 一站式免编译 reims-vgpu 启动器")
fmt.Println("\n用法:")
fmt.Println(" reims-go 打开界面(--background:只在托盘运行,不显示窗口)")
fmt.Println(" reims-go [--lang zh-CN|en-US] [--data-root DIR] <命令> [参数]")
fmt.Println("\n 在交互式 PowerShell / cmd 中提示符会先返回;要等命令结束并拿到退出码,请加 | Out-Host 或用管道。")
fmt.Println("\n命令:")
fmt.Println(" doctor 宿主机环境体检(WHPX / 显卡 ICD / P-E 核 / 磁盘 / 运行时)")
fmt.Println(" runtime available 列出 GitHub 上发布的运行时(--alpha 含 alpha 版)")
@@ -96,7 +111,8 @@ func printUsage(loc i18n.Locale) {
fmt.Println(" vm set [options] <name> 修改虚拟机配置(下次启动生效)")
fmt.Println(" vm resize <name> <大小> 停机扩容虚拟磁盘(如 256G 或 +64G)")
fmt.Println(" vm compact <name> 停机回收 .qcow2 磁盘未用空间")
fmt.Println(" vm start|stop|eject <name> 启动 / 停止 / 弹出安装盘")
fmt.Println(" vm start <name> 启动虚拟机:交给界面进程(未运行则在托盘拉起),带剪贴板与共享目录;指定 --data-root 时在本进程内启动")
fmt.Println(" vm stop|eject <name> 停止 / 弹出安装盘")
fmt.Println(" vm type <name> [文本] 把文本按美式键盘敲进运行中的虚拟机(不给文本则读标准输入)")
fmt.Println(" installer list 列出 Apple 提供的离线安装包版本(需联网)")
fmt.Println(" installer download <版本> 下载离线安装包(如 26.7.1、tahoe、latest;Ctrl+C 暂停,再次运行续传)")
@@ -105,9 +121,12 @@ func printUsage(loc i18n.Locale) {
fmt.Println(" version 查看当前版本")
return
}
fmt.Println("reims-go - Portable one-stop reims-vgpu launcher & CLI for Windows")
fmt.Println("reims-go - Portable one-stop reims-vgpu launcher for Windows")
fmt.Println("\nUsage:")
fmt.Println(" reims-go Open the window (--background: tray only, no window)")
fmt.Println(" reims-go [--lang zh-CN|en-US] [--data-root DIR] <command> [args]")
fmt.Println("\n Interactive PowerShell / cmd return to the prompt early; pipe the output (e.g. | Out-Host)")
fmt.Println(" to wait for the command and get its exit code.")
fmt.Println("\nCommands:")
fmt.Println(" doctor Inspect host (WHPX / Vulkan GPUs / P-E cores / disk / runtime)")
fmt.Println(" runtime available List runtimes published on GitHub (--alpha includes alpha builds)")
@@ -120,7 +139,9 @@ func printUsage(loc i18n.Locale) {
fmt.Println(" vm set [options] <name> Update VM settings (applies on next start)")
fmt.Println(" vm resize <name> <size> Expand stopped VM disk (e.g. 256G or +64G)")
fmt.Println(" vm compact <name> Compact stopped .qcow2 disk to reclaim unused space")
fmt.Println(" vm start|stop|eject <name> Start / stop / eject installer")
fmt.Println(" vm start <name> Start a VM in the Reims-Go window process (launched in the tray if needed),")
fmt.Println(" with clipboard and shared folders; with --data-root it starts in this process")
fmt.Println(" vm stop|eject <name> Stop / eject installer")
fmt.Println(" vm type <name> [text] Type text into a running VM as US-keyboard keys (stdin if no text)")
fmt.Println(" installer list List offline macOS installers Apple offers (needs network)")
fmt.Println(" installer download <ver> Download an offline installer (26.7.1, tahoe, latest; Ctrl+C pauses, rerun resumes)")
@@ -259,7 +280,7 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
}
}
func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error {
func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) error {
if len(args) == 0 {
return fmt.Errorf("usage: reims-go vm <list|create|set|start|stop|eject|type>")
}
@@ -345,7 +366,7 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error {
}
}
if startAfterCreate {
if err := startVM(ctx, cfg, prep, name); err != nil {
if err := startVM(ctx, cfg, prep, name, viaWindow); err != nil {
return err
}
}
@@ -396,7 +417,7 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error {
if len(args) < 2 {
return fmt.Errorf("usage: reims-go vm start <name>")
}
return startVM(ctx, cfg, prep, args[1])
return startVM(ctx, cfg, prep, args[1], viaWindow)
case "stop":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go vm stop <name>")
+14
View File
@@ -0,0 +1,14 @@
//go:build !windows
package cli
import "errors"
// Off Windows `vm start` always runs in the command itself.
const windowHandoffWorks = false
func findWindow() uintptr { return 0 }
func sendToWindow(uintptr, []string) error { return errors.ErrUnsupported }
func spawnWindow([]string) error { return errors.ErrUnsupported }
+97
View File
@@ -0,0 +1,97 @@
//go:build windows
package cli
import (
"encoding/json"
"errors"
"os"
"os/exec"
"runtime"
"syscall"
"unsafe"
"github.com/wailsapp/wails/v2/pkg/options"
)
// Handing work to the desktop window speaks Wails v2's own single-instance
// protocol (internal/frontend/desktop/windows/single_instance.go, v2.17.1):
// the first instance owns a message-only window named
// "wails-app-<id>-sic" / "wails-app-<id>-siw" and reads a JSON
// options.SecondInstanceData from WM_COPYDATA with dwData 1542. Recheck
// these names when upgrading Wails.
const (
wmCopyData = 0x004A
wailsCopyDataID = 1542
hwndMessage = ^uintptr(2) // HWND_MESSAGE, (HWND)-3
detachedProcess = 0x00000008
windowHandoffWorks = true
)
var (
user32 = syscall.NewLazyDLL("user32.dll")
procFindWindowExW = user32.NewProc("FindWindowExW")
procSendMessageW = user32.NewProc("SendMessageW")
)
type copyDataStruct struct {
dwData uintptr
cbData uint32
lpData uintptr
}
// findWindow returns the running Reims-Go window's message window, or 0.
func findWindow() uintptr {
id := "wails-app-" + InstanceID
class, err := syscall.UTF16PtrFromString(id + "-sic")
if err != nil {
return 0
}
name, err := syscall.UTF16PtrFromString(id + "-siw")
if err != nil {
return 0
}
h, _, _ := procFindWindowExW.Call(hwndMessage, 0, uintptr(unsafe.Pointer(class)), uintptr(unsafe.Pointer(name)))
return h
}
// sendToWindow delivers args to the running window as if a second
// `reims-go.exe <args>` had been launched.
func sendToWindow(hwnd uintptr, args []string) error {
wd, _ := os.Getwd()
payload, err := json.Marshal(options.SecondInstanceData{Args: args, WorkingDirectory: wd})
if err != nil {
return err
}
buf, err := syscall.UTF16FromString(string(payload)) // NUL-terminated
if err != nil {
return err
}
cds := copyDataStruct{
dwData: wailsCopyDataID,
cbData: uint32(len(buf) * 2),
lpData: uintptr(unsafe.Pointer(&buf[0])),
}
procSendMessageW.Call(hwnd, wmCopyData, 0, uintptr(unsafe.Pointer(&cds)))
runtime.KeepAlive(buf)
return nil
}
// spawnWindow launches this executable as the desktop window, detached from
// the caller's console and Ctrl+C, with no handles of the caller's: a pipe an
// agent reads from must close when this command exits, not when Reims-Go does.
func spawnWindow(args []string) error {
exe, err := os.Executable()
if err != nil {
return err
}
cmd := exec.Command(exe, args...)
cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: detachedProcess | syscall.CREATE_NEW_PROCESS_GROUP}
if err := cmd.Start(); err != nil {
return err
}
if cmd.Process == nil {
return errors.New("reims-go window did not start")
}
return cmd.Process.Release()
}
@@ -1,4 +1,4 @@
package main
package cli
import (
"context"
+8
View File
@@ -0,0 +1,8 @@
//go:build !dev
package cli
// InstanceID names the desktop window's single-instance lock (Wails
// options.SingleInstanceLock). Command-line mode finds a running window by
// the same name to hand `vm start` to it.
const InstanceID = "reims-go-9d3f6c1e"
+7
View File
@@ -0,0 +1,7 @@
//go:build dev
package cli
// InstanceID for `wails dev` builds: separate from release builds so a dev
// window neither hands itself to nor blocks an installed Reims-Go.
const InstanceID = "reims-go-9d3f6c1e-dev"
@@ -1,4 +1,4 @@
package main
package cli
import (
"context"
+166
View File
@@ -0,0 +1,166 @@
package cli
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"os/signal"
"path/filepath"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/vmstart"
)
// startHandoffTimeout bounds how long `vm start` waits for the window to
// report back. Preparation can rebuild the OpenCore image before QEMU starts.
const startHandoffTimeout = 5 * time.Minute
// startVM checks the VM can start, then hands it to the desktop window: the
// one already running, or a new one in the tray (`--background`). The window
// runs the GUI's StartVM, so a VM started from the command line gets Guest
// Tools and the Win10 cold-reboot watcher too; both need a process that stays
// up after this command exits.
//
// viaWindow is false when --data-root points elsewhere than the window's
// data root could; the VM then starts here, without those two.
func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string, viaWindow bool) error {
rep := host.Inspect(cfg.DataRoot)
d, err := prep.Client.Show(ctx, name)
if err != nil {
return err
}
if d.State == "running" {
// Preparation rewrites extra-args and the OpenCore image; never under a live VM.
return fmt.Errorf("%s is already running", name)
}
if err := prep.CheckMemory(d.Memory, rep); err != nil {
return err
}
if viaWindow && windowHandoffWorks {
return startInWindow(ctx, cfg, name)
}
prep.Prepare(ctx, name, rep, &d)
if err := prep.Client.StartWithCompat(ctx, name, os.Stdout, os.Stderr, func(msg string) {
fmt.Fprintln(os.Stderr, msg)
}); err != nil {
return err
}
if !cfg.AutoPinPCores || !rep.HasHybridCores || rep.PCoreMask == 0 {
return nil
}
vms, err := prep.Client.List(ctx)
if err != nil {
return nil
}
for _, vm := range vms {
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
fmt.Fprintln(os.Stderr, vmstart.PinQEMU(cfg.Locale, rep, *vm.PID, d.CPUs))
}
}
return nil
}
func startInWindow(ctx context.Context, cfg *config.Config, name string) error {
zh := cfg.Locale == i18n.ZhCN
if err := os.MkdirAll(cfg.TempDir(), 0o755); err != nil {
return err
}
result := filepath.Join(cfg.TempDir(), fmt.Sprintf("cli-start-%d.json", time.Now().UnixNano()))
w := WindowArgs{StartVM: name, StartResult: result}
if hwnd := findWindow(); hwnd != 0 {
if zh {
fmt.Fprintf(os.Stderr, "交给正在运行的 Reims-Go 启动 %s…\n", name)
} else {
fmt.Fprintf(os.Stderr, "Handing %s to the running Reims-Go...\n", name)
}
if err := sendToWindow(hwnd, w.Args()); err != nil {
return err
}
} else {
w.Background = true
if zh {
fmt.Fprintf(os.Stderr, "在后台拉起 Reims-Go(托盘)来启动 %s…\n", name)
} else {
fmt.Fprintf(os.Stderr, "Starting Reims-Go in the tray to run %s...\n", name)
}
if err := spawnWindow(w.Args()); err != nil {
return err
}
}
ctx, stop := signal.NotifyContext(ctx, os.Interrupt)
defer stop()
res, err := waitStartResult(ctx, result, startHandoffTimeout)
switch {
case errors.Is(err, context.Canceled):
if zh {
return fmt.Errorf("已停止等待;%s 仍由 Reims-Go 继续启动", name)
}
return fmt.Errorf("stopped waiting; Reims-Go keeps starting %s", name)
case errors.Is(err, context.DeadlineExceeded):
if zh {
return fmt.Errorf("Reims-Go 在 %v 内没有回报 %s 的启动结果;请看界面的日志面板(若正在运行的是旧版 Reims-Go,请先退出它)", startHandoffTimeout, name)
}
return fmt.Errorf("Reims-Go did not report starting %s within %v; check its log panel (quit it first if it is an older version)", name, startHandoffTimeout)
case err != nil:
return err
}
if !res.OK {
return errors.New(res.Error)
}
// Guest Tools only connects once macOS is up and its agent runs, so say
// what this process can know: who now looks after the VM.
if zh {
fmt.Printf("%s 已启动,由 Reims-Go 界面进程管理;macOS 启动后,已安装 Guest Tools 的客体会接入剪贴板与共享目录\n", name)
} else {
fmt.Printf("%s is running, looked after by the Reims-Go window process; once macOS is up, a guest with Guest Tools installed gets clipboard and shared folders\n", name)
}
return nil
}
// waitStartResult polls for the window's StartResult file and removes it.
// The window writes it with a rename, so any file seen is complete.
func waitStartResult(ctx context.Context, path string, timeout time.Duration) (StartResult, error) {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
tick := time.NewTicker(250 * time.Millisecond)
defer tick.Stop()
for {
if b, err := os.ReadFile(path); err == nil {
_ = os.Remove(path)
var res StartResult
if err := json.Unmarshal(b, &res); err != nil {
return StartResult{}, fmt.Errorf("unreadable start result %s: %w", path, err)
}
return res, nil
}
select {
case <-ctx.Done():
return StartResult{}, ctx.Err()
case <-tick.C:
}
}
}
// WriteStartResult is the window's side of waitStartResult.
func WriteStartResult(path string, startErr error) error {
res := StartResult{OK: startErr == nil}
if startErr != nil {
res.Error = startErr.Error()
}
b, err := json.Marshal(res)
if err != nil {
return err
}
part := path + ".part"
if err := os.WriteFile(part, b, 0o644); err != nil {
return err
}
return os.Rename(part, path)
}
+66
View File
@@ -0,0 +1,66 @@
package cli
import "strings"
// The desktop window's own flags. `vm start` launches the window with them
// (or sends them to a window already running), so they are the whole
// protocol between command-line mode and the window. Each flag is one
// argument (`--name=value`) so a stray value is never taken for a command.
const (
flagBackground = "--background"
flagStartVM = "--start-vm="
flagStartResult = "--start-result="
)
// WindowArgs is what the desktop window was asked to do at launch, or by a
// later `reims-go` run handing work to it.
type WindowArgs struct {
// Background keeps the window hidden; Reims-Go lives in the tray.
Background bool
// StartVM is a VM to start as the GUI's StartVM would (Guest Tools and
// the Win10 cold-reboot watcher included).
StartVM string
// StartResult is a file the window writes a StartResult to once StartVM
// has returned, so the command that asked can report it.
StartResult string
}
// ParseWindowArgs reads the window flags. ok is false when args hold
// anything else, which means command-line mode. No arguments is a plain
// window launch.
func ParseWindowArgs(args []string) (w WindowArgs, ok bool) {
for _, a := range args {
switch {
case a == flagBackground:
w.Background = true
case strings.HasPrefix(a, flagStartVM):
w.StartVM = strings.TrimPrefix(a, flagStartVM)
case strings.HasPrefix(a, flagStartResult):
w.StartResult = strings.TrimPrefix(a, flagStartResult)
default:
return WindowArgs{}, false
}
}
return w, true
}
// Args is the inverse of ParseWindowArgs.
func (w WindowArgs) Args() []string {
var out []string
if w.Background {
out = append(out, flagBackground)
}
if w.StartVM != "" {
out = append(out, flagStartVM+w.StartVM)
}
if w.StartResult != "" {
out = append(out, flagStartResult+w.StartResult)
}
return out
}
// StartResult is the JSON the window writes to WindowArgs.StartResult.
type StartResult struct {
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
}
+75
View File
@@ -0,0 +1,75 @@
package cli
import (
"context"
"errors"
"os"
"path/filepath"
"reflect"
"testing"
"time"
)
func TestParseWindowArgs(t *testing.T) {
cases := []struct {
args []string
want WindowArgs
isPlain bool // window launch, not a command
}{
{nil, WindowArgs{}, true},
{[]string{"--background"}, WindowArgs{Background: true}, true},
{[]string{"--background", "--start-vm=m0", `--start-result=D:\tmp\cli-start-1.json`},
WindowArgs{Background: true, StartVM: "m0", StartResult: `D:\tmp\cli-start-1.json`}, true},
{[]string{"vm", "start", "m0"}, WindowArgs{}, false},
{[]string{"--background", "vm", "list"}, WindowArgs{}, false},
{[]string{"--help"}, WindowArgs{}, false},
{[]string{"--start-vm", "m0"}, WindowArgs{}, false}, // value must be joined with =
}
for _, c := range cases {
got, ok := ParseWindowArgs(c.args)
if ok != c.isPlain || !reflect.DeepEqual(got, c.want) {
t.Errorf("ParseWindowArgs(%q) = %+v, %v; want %+v, %v", c.args, got, ok, c.want, c.isPlain)
}
if IsCommand(c.args) == c.isPlain {
t.Errorf("IsCommand(%q) = %v", c.args, !c.isPlain)
}
}
}
func TestWindowArgsRoundTrip(t *testing.T) {
w := WindowArgs{Background: true, StartVM: "mac os", StartResult: `D:\Data\tmp\cli-start-9.json`}
got, ok := ParseWindowArgs(w.Args())
if !ok || got != w {
t.Fatalf("round trip = %+v, %v", got, ok)
}
}
func TestStartResultRoundTrip(t *testing.T) {
dir := t.TempDir()
okPath := filepath.Join(dir, "cli-start-1.json")
if err := WriteStartResult(okPath, nil); err != nil {
t.Fatal(err)
}
res, err := waitStartResult(context.Background(), okPath, time.Second)
if err != nil || !res.OK {
t.Fatalf("ok result = %+v, %v", res, err)
}
if _, err := os.Stat(okPath); !os.IsNotExist(err) {
t.Fatal("result file should be removed once read")
}
failPath := filepath.Join(dir, "cli-start-2.json")
go func() {
time.Sleep(300 * time.Millisecond)
_ = WriteStartResult(failPath, errors.New("not enough memory"))
}()
res, err = waitStartResult(context.Background(), failPath, 5*time.Second)
if err != nil || res.OK || res.Error != "not enough memory" {
t.Fatalf("failed result = %+v, %v", res, err)
}
_, err = waitStartResult(context.Background(), filepath.Join(dir, "never.json"), 300*time.Millisecond)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("missing result err = %v", err)
}
}
+161
View File
@@ -0,0 +1,161 @@
package guesttools
import (
"context"
"net/http"
"os"
"path"
"path/filepath"
"sort"
"strings"
"golang.org/x/net/webdav"
)
// DriveShareAgentVersion is the first macOS agent that applies dynamic drive mounts.
const DriveShareAgentVersion = 4
// NormalizeDriveLetter accepts C, C:, or C:\ and returns the canonical letter C.
func NormalizeDriveLetter(raw string) (string, bool) {
s := strings.ToUpper(strings.TrimSpace(raw))
s = strings.TrimSuffix(s, `\`)
s = strings.TrimSuffix(s, ":")
if len(s) != 1 || s[0] < 'A' || s[0] > 'Z' {
return "", false
}
return s, true
}
func configuredDriveRoots(cfg VMConfig) map[string]string {
roots := make(map[string]string)
for _, raw := range cfg.SharedDrives {
drive, ok := NormalizeDriveLetter(raw)
if !ok {
continue
}
root := cfg.DriveRoots[drive]
if root == "" {
continue
}
roots[drive] = root
}
return roots
}
func cloneStringMap(src map[string]string) map[string]string {
if src == nil {
return nil
}
dst := make(map[string]string, len(src))
for k, v := range src {
dst[k] = v
}
return dst
}
func enabledDriveLetters(vm *registeredVM) []string {
out := []string{}
if vm == nil || !vm.driveSharingEnabled {
return out
}
for drive := range vm.sharedDriveRoots {
out = append(out, drive)
}
sort.Strings(out)
return out
}
// readOnlyDriveFS exposes an existing fixed-drive root without ever creating it.
// Every read resolves junctions/symlinks and verifies that the final target stays
// inside the authorized root. All mutating filesystem operations are denied.
type readOnlyDriveFS struct {
rootAbs string
inner webdav.Dir
}
func newReadOnlyDriveFS(root string) (*readOnlyDriveFS, error) {
abs, err := filepath.Abs(root)
if err != nil {
return nil, err
}
info, err := os.Stat(abs)
if err != nil {
return nil, err
}
if !info.IsDir() {
return nil, os.ErrInvalid
}
resolved, err := filepath.EvalSymlinks(abs)
if err != nil {
return nil, err
}
return &readOnlyDriveFS{rootAbs: resolved, inner: webdav.Dir(resolved)}, nil
}
func pathWithinRoot(root, target string) bool {
rel, err := filepath.Rel(root, target)
if err != nil {
return false
}
return rel == "." || (rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator)) && !filepath.IsAbs(rel))
}
func (f *readOnlyDriveFS) validate(name string) error {
if strings.ContainsRune(name, 0) || strings.Contains(name, `\`) {
return os.ErrInvalid
}
clean := path.Clean("/" + name)
full := filepath.Join(f.rootAbs, filepath.FromSlash(strings.TrimPrefix(clean, "/")))
if !pathWithinRoot(f.rootAbs, full) {
return os.ErrPermission
}
resolved, err := filepath.EvalSymlinks(full)
if err != nil {
return err
}
if !pathWithinRoot(f.rootAbs, resolved) {
return os.ErrPermission
}
return nil
}
func (f *readOnlyDriveFS) Mkdir(context.Context, string, os.FileMode) error {
return os.ErrPermission
}
func (f *readOnlyDriveFS) OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (webdav.File, error) {
const writeFlags = os.O_WRONLY | os.O_RDWR | os.O_APPEND | os.O_CREATE | os.O_EXCL | os.O_TRUNC
if flag&writeFlags != 0 {
return nil, os.ErrPermission
}
if err := f.validate(name); err != nil {
return nil, err
}
return f.inner.OpenFile(ctx, name, os.O_RDONLY, perm)
}
func (f *readOnlyDriveFS) RemoveAll(context.Context, string) error {
return os.ErrPermission
}
func (f *readOnlyDriveFS) Rename(context.Context, string, string) error {
return os.ErrPermission
}
func (f *readOnlyDriveFS) Stat(ctx context.Context, name string) (os.FileInfo, error) {
if err := f.validate(name); err != nil {
return nil, err
}
return f.inner.Stat(ctx, name)
}
func allowReadOnlyDAV(w http.ResponseWriter, r *http.Request) bool {
switch r.Method {
case http.MethodGet, http.MethodHead, http.MethodOptions, "PROPFIND":
return true
default:
w.Header().Set("Allow", "OPTIONS, GET, HEAD, PROPFIND")
http.Error(w, "read-only drive share", http.StatusMethodNotAllowed)
return false
}
}
+248
View File
@@ -0,0 +1,248 @@
package guesttools
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
)
func TestNormalizeDriveLetter(t *testing.T) {
for _, tc := range []struct{ in, want string }{{"c", "C"}, {"C:", "C"}, {"d:\\", "D"}, {" e: ", "E"}} {
got, ok := NormalizeDriveLetter(tc.in)
if !ok || got != tc.want {
t.Fatalf("NormalizeDriveLetter(%q) = %q, %v; want %q", tc.in, got, ok, tc.want)
}
}
for _, raw := range []string{"", "CC", "1", "C:/", "../C", `\\server\share`} {
if got, ok := NormalizeDriveLetter(raw); ok {
t.Fatalf("NormalizeDriveLetter(%q) unexpectedly accepted as %q", raw, got)
}
}
}
func TestReadOnlyDriveSharesEnforceSelectionAndIsolation(t *testing.T) {
tmp := t.TempDir()
rootC := filepath.Join(tmp, "drive-c")
rootD := filepath.Join(tmp, "drive-d")
if err := os.MkdirAll(rootC, 0o755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(rootD, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(rootC, "hello.txt"), []byte("from-c"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(rootD, "hello.txt"), []byte("from-d"), 0o600); err != nil {
t.Fatal(err)
}
srv := NewServer(&memClipboard{})
port, err := srv.Start(-1)
if err != nil {
t.Fatal(err)
}
defer srv.Close(context.Background())
base := fmt.Sprintf("http://127.0.0.1:%d", port)
cfg := VMConfig{
VMName: "mac", Token: strings.Repeat("ab", 32), Port: port,
SharedDir: filepath.Join(tmp, "shared"), DriveSharingEnabled: true,
SharedDrives: []string{"C"}, DriveRoots: map[string]string{"C": rootC, "D": rootD},
}
srv.RegisterVM(cfg)
other := VMConfig{
VMName: "other", Token: strings.Repeat("cd", 32), Port: port,
DriveSharingEnabled: true, SharedDrives: []string{"C"},
DriveRoots: map[string]string{"C": rootD},
}
srv.RegisterVM(other)
do := func(method, reqPath, token string, body io.Reader) (int, string, http.Header) {
t.Helper()
req, err := http.NewRequest(method, base+reqPath, body)
if err != nil {
t.Fatal(err)
}
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
if method == "PROPFIND" {
req.Header.Set("Depth", "1")
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
return resp.StatusCode, string(b), resp.Header
}
readC := "/dav/mac/drives/C/hello.txt"
if code, body, _ := do(http.MethodGet, readC, cfg.Token, nil); code != http.StatusOK || body != "from-c" {
t.Fatalf("read shared C: code=%d body=%q", code, body)
}
if code, body, _ := do("PROPFIND", "/dav/mac/drives/C/", cfg.Token, nil); code != http.StatusMultiStatus || !strings.Contains(body, "hello.txt") {
t.Fatalf("PROPFIND shared C: code=%d body=%s", code, body)
}
reqMissing, err := http.NewRequest("PROPFIND", base+"/dav/mac/drives/C/", nil)
if err != nil {
t.Fatal(err)
}
reqMissing.Header.Set("Authorization", "Bearer "+cfg.Token)
respMissing, err := http.DefaultClient.Do(reqMissing)
if err != nil {
t.Fatal(err)
}
respMissing.Body.Close()
if respMissing.StatusCode != http.StatusMultiStatus {
t.Fatalf("PROPFIND without Depth: code=%d, want 207", respMissing.StatusCode)
}
for _, depth := range []string{"infinity", "2"} {
req, err := http.NewRequest("PROPFIND", base+"/dav/mac/drives/C/", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+cfg.Token)
if depth != "" {
req.Header.Set("Depth", depth)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("PROPFIND Depth %q: code=%d, want 400", depth, resp.StatusCode)
}
}
if code, _, _ := do(http.MethodPut, "/dav/mac/drives/C/new.txt", cfg.Token, strings.NewReader("bad")); code != http.StatusMethodNotAllowed {
t.Fatalf("PUT read-only C: code=%d, want 405", code)
}
if _, err := os.Stat(filepath.Join(rootC, "new.txt")); !os.IsNotExist(err) {
t.Fatalf("read-only PUT created a host file: %v", err)
}
for _, method := range []string{http.MethodDelete, "MKCOL", "MOVE", "COPY", "PROPPATCH", "LOCK"} {
if code, _, _ := do(method, readC, cfg.Token, nil); code != http.StatusMethodNotAllowed {
t.Fatalf("%s read-only C: code=%d, want 405", method, code)
}
}
if body, err := os.ReadFile(filepath.Join(rootC, "hello.txt")); err != nil || string(body) != "from-c" {
t.Fatalf("read-only DELETE changed host file: %q, %v", body, err)
}
if code, _, _ := do(http.MethodGet, "/dav/mac/drives/D/hello.txt", cfg.Token, nil); code != http.StatusForbidden {
t.Fatalf("unselected D: code=%d, want 403", code)
}
if code, _, _ := do(http.MethodGet, readC, "", nil); code != http.StatusUnauthorized {
t.Fatalf("unauthenticated drive read: code=%d, want 401", code)
}
if code, body, _ := do(http.MethodGet, "/dav/other/drives/C/hello.txt", other.Token, nil); code != http.StatusOK || body != "from-d" {
t.Fatalf("per-VM drive root isolation: code=%d body=%q", code, body)
}
if code, _, _ := do(http.MethodGet, "/dav/other/drives/C/hello.txt", cfg.Token, nil); code != http.StatusForbidden {
t.Fatalf("cross-VM drive read: code=%d, want 403", code)
}
if _, body, _ := do(http.MethodGet, "/v1/config", cfg.Token, nil); !strings.Contains(body, `"shared_drives":["C"]`) {
t.Fatalf("enabled config shared_drives missing C: %s", body)
}
cfg.SharedDrives = []string{"C", "D"}
srv.RegisterVM(cfg)
if code, body, _ := do(http.MethodGet, "/dav/mac/drives/D/hello.txt", cfg.Token, nil); code != http.StatusOK || body != "from-d" {
t.Fatalf("newly selected D: code=%d body=%q", code, body)
}
cfg.DriveSharingEnabled = false
srv.RegisterVM(cfg)
if code, _, _ := do(http.MethodGet, readC, cfg.Token, nil); code != http.StatusForbidden {
t.Fatalf("disabled master switch: code=%d, want 403", code)
}
req, _ := http.NewRequest(http.MethodGet, base+"/v1/config", nil)
req.Header.Set("Authorization", "Bearer "+cfg.Token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
var live struct {
SharedDrives []string `json:"shared_drives"`
}
if err := json.NewDecoder(resp.Body).Decode(&live); err != nil {
t.Fatal(err)
}
resp.Body.Close()
if live.SharedDrives == nil || len(live.SharedDrives) != 0 {
t.Fatalf("disabled config shared_drives = %#v, want empty JSON array", live.SharedDrives)
}
}
func TestDriveShareConfigPersistsLettersButNotRuntimeRoots(t *testing.T) {
vmDir := filepath.Join(t.TempDir(), "vm")
cfg := VMConfig{VMName: "mac", Token: strings.Repeat("ab", 32), DriveSharingEnabled: true, SharedDrives: []string{"C"}, DriveVolumes: map[string]string{"C": "vol-c"}, DriveRoots: map[string]string{"C": `C:\secret-root`}}
if err := SaveVMConfig(vmDir, cfg); err != nil {
t.Fatal(err)
}
raw, err := os.ReadFile(filepath.Join(vmDir, ConfigFileName))
if err != nil {
t.Fatal(err)
}
text := string(raw)
if !strings.Contains(text, `"shared_drives": [`) || !strings.Contains(text, `"C"`) || strings.Contains(text, "secret-root") || strings.Contains(text, "DriveRoots") {
t.Fatalf("persisted drive config leaks runtime roots or omits letters: %s", text)
}
loaded, ok := ReadVMConfig(vmDir)
if !ok || !loaded.DriveSharingEnabled || len(loaded.SharedDrives) != 1 || loaded.SharedDrives[0] != "C" || loaded.DriveVolumes["C"] != "vol-c" || loaded.DriveRoots != nil {
t.Fatalf("loaded drive config = %#v", loaded)
}
}
func TestReadOnlyDriveFSRejectsWritesAndEscapingSymlink(t *testing.T) {
tmp := t.TempDir()
root := filepath.Join(tmp, "root")
outside := filepath.Join(tmp, "outside")
if err := os.MkdirAll(root, 0o755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(outside, 0o755); err != nil {
t.Fatal(err)
}
victim := filepath.Join(root, "victim.txt")
if err := os.WriteFile(victim, []byte("safe"), 0o600); err != nil {
t.Fatal(err)
}
fsys, err := newReadOnlyDriveFS(root)
if err != nil {
t.Fatal(err)
}
for _, flag := range []int{os.O_WRONLY, os.O_RDWR, os.O_APPEND, os.O_CREATE, os.O_EXCL, os.O_TRUNC} {
if _, err := fsys.OpenFile(context.Background(), "victim.txt", flag, 0); err == nil {
t.Fatalf("write OpenFile flag %d unexpectedly succeeded", flag)
}
}
if err := fsys.Mkdir(context.Background(), "new-dir", 0o755); err == nil {
t.Fatal("Mkdir unexpectedly succeeded")
}
if err := fsys.RemoveAll(context.Background(), "victim.txt"); err == nil {
t.Fatal("RemoveAll unexpectedly succeeded")
}
if err := fsys.Rename(context.Background(), "victim.txt", "renamed.txt"); err == nil {
t.Fatal("Rename unexpectedly succeeded")
}
if body, err := os.ReadFile(victim); err != nil || string(body) != "safe" {
t.Fatalf("write attempt changed file: %q, %v", body, err)
}
if err := os.Symlink(outside, filepath.Join(root, "escape")); err != nil {
t.Skipf("symlink creation unavailable on this host: %v", err)
}
if err := os.WriteFile(filepath.Join(outside, "secret.txt"), []byte("secret"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := fsys.OpenFile(context.Background(), "escape/secret.txt", os.O_RDONLY, 0); err == nil {
t.Fatal("directory symlink escape unexpectedly succeeded")
}
}
@@ -0,0 +1,41 @@
//go:build windows
package guesttools
import (
"context"
"os"
"os/exec"
"path/filepath"
"testing"
)
func TestReadOnlyDriveFSRejectsWindowsJunctionEscape(t *testing.T) {
tmp := t.TempDir()
root := filepath.Join(tmp, "root")
outside := filepath.Join(tmp, "outside")
if err := os.MkdirAll(root, 0o755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(outside, 0o755); err != nil {
t.Fatal(err)
}
secret := filepath.Join(outside, "secret.txt")
if err := os.WriteFile(secret, []byte("outside"), 0o600); err != nil {
t.Fatal(err)
}
link := filepath.Join(root, "junction")
if output, err := exec.Command("cmd.exe", "/c", "mklink", "/J", link, outside).CombinedOutput(); err != nil {
t.Fatalf("create test junction: %v: %s", err, output)
}
if body, err := os.ReadFile(filepath.Join(link, "secret.txt")); err != nil || string(body) != "outside" {
t.Fatalf("test junction is not usable: %q, %v", body, err)
}
fsys, err := newReadOnlyDriveFS(root)
if err != nil {
t.Fatal(err)
}
if _, err := fsys.OpenFile(context.Background(), "junction/secret.txt", os.O_RDONLY, 0); err == nil {
t.Fatal("junction escape unexpectedly succeeded")
}
}
+98 -9
View File
@@ -16,7 +16,7 @@ const (
)
// BuildToolsDiskImage creates a small read-only HFS+ disk image ("REIMSTOOLS")
// containing the per-VM Bearer token config, Guest Tools 2.0 POSIX agent script
// containing the per-VM Bearer token config, Guest Tools 4 POSIX agent script
// (text + PNG image clipboard with long-poll, WebDAV live mount with fallback
// sync, and caffeinate prevent-sleep daemon), plus install/uninstall/pmset scripts.
func BuildToolsDiskImage(outPath string, cfg VMConfig) error {
@@ -65,14 +65,15 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error {
return installer.BuildHFSPlusDiskImage(outPath, ToolsVolumeName, files)
}
// GuestAgentScript returns the Guest Tools 2.0 stock-macOS POSIX shell daemon
// GuestAgentScript returns the Guest Tools 4 stock-macOS POSIX shell daemon
// (no Xcode or Python required):
// - Two-way UTF-8 text + PNG screenshot clipboard with server long-polling
// - Zero-duplication WebDAV shared folder mount (~/Desktop/ReimsShare) with automatic sync fallback
// - Host-controlled read-only Windows fixed-drive mounts with automatic unmount
// - Live host-controlled prevent-sleep guard via `caffeinate -dims` (no sudo required)
func GuestAgentScript() []byte {
return []byte(`#!/bin/sh
# Reims Guest Tools 2.0: text+PNG clipboard (long-poll), WebDAV shared folder, prevent-sleep.
# Reims Guest Tools 4: clipboard, WebDAV share, read-only Windows drives, prevent-sleep.
set -u
# Force UTF-8 for macOS pbpaste/pbcopy under launchd (otherwise Simplified
@@ -86,10 +87,11 @@ APP_DIR="$HOME/Library/Application Support/ReimsGuestTools"
CONF="$APP_DIR/config"
SHARE_SYNC="$HOME/ReimsShare"
SHARE_MOUNT="$HOME/ReimsShareMount"
DRIVE_MOUNT_ROOT="$HOME/ReimsWindowsDrives"
DESKTOP_LINK="$HOME/Desktop/ReimsShare"
TMP_DIR="$APP_DIR/tmp"
INJECT_LOCK="$TMP_DIR/injecting"
mkdir -p "$APP_DIR" "$SHARE_SYNC" "$SHARE_MOUNT" "$TMP_DIR"
mkdir -p "$APP_DIR" "$SHARE_SYNC" "$SHARE_MOUNT" "$DRIVE_MOUNT_ROOT" "$TMP_DIR"
rm -f "$INJECT_LOCK" 2>/dev/null || true
CAFFEINATE_PID=""
@@ -193,10 +195,89 @@ ensure_webdav_mount() {
sleep_active="false"
apply_prevent_sleep() {
is_drive_mounted() {
mount 2>/dev/null | grep -F "on $1 (" >/dev/null 2>&1
}
update_drive_link() {
letter="$1"
mount_point="$DRIVE_MOUNT_ROOT/$letter"
link="$HOME/Desktop/Windows $letter"
if [ -L "$link" ]; then
[ "$(readlink "$link" 2>/dev/null || true)" = "$mount_point" ] && return 0
rm -f "$link" 2>/dev/null || true
elif [ -e "$link" ]; then
return 0
fi
ln -s "$mount_point" "$link" 2>/dev/null || true
}
remove_drive_link() {
letter="$1"
mount_point="$DRIVE_MOUNT_ROOT/$letter"
link="$HOME/Desktop/Windows $letter"
if [ -L "$link" ] && [ "$(readlink "$link" 2>/dev/null || true)" = "$mount_point" ]; then
rm -f "$link" 2>/dev/null || true
fi
}
unmount_drive() {
letter="$1"
mount_point="$DRIVE_MOUNT_ROOT/$letter"
if is_drive_mounted "$mount_point"; then
umount "$mount_point" >/dev/null 2>&1 || true
fi
remove_drive_link "$letter"
if ! is_drive_mounted "$mount_point"; then
rmdir "$mount_point" 2>/dev/null || true
fi
}
mount_drive() {
letter="$1"
mount_point="$DRIVE_MOUNT_ROOT/$letter"
if is_drive_mounted "$mount_point"; then
update_drive_link "$letter"
return 0
fi
command -v mount_webdav >/dev/null 2>&1 || return 0
host_addr=${REIMS_HOST_URL#http://}
host_addr=${host_addr#https://}
host_addr=${host_addr%/}
dav_url="http://reims:${REIMS_TOKEN}@${host_addr}/dav/${REIMS_VM}/drives/${letter}/"
mkdir -p "$mount_point"
# Prefer a client read-only mount where supported; the host remains the authority.
if mount_webdav -o ro -v "Windows $letter" "$dav_url" "$mount_point" >/dev/null 2>&1 || \
mount_webdav -o ro "$dav_url" "$mount_point" >/dev/null 2>&1 || \
mount_webdav -v "Windows $letter" "$dav_url" "$mount_point" >/dev/null 2>&1 || \
mount_webdav "$dav_url" "$mount_point" >/dev/null 2>&1; then
update_drive_link "$letter"
fi
}
sync_drive_mounts() {
cfg_json="$1"
desired=$(printf '%s\n' "$cfg_json" | \
sed -n 's/.*"shared_drives"[[:space:]]*:[[:space:]]*\[\([^]]*\)\].*/\1/p' | \
tr ',' '\n' | sed -n 's/^[[:space:]]*"\([A-Z]\)"[[:space:]]*$/\1/p' | tr '\n' ' ')
for mount_point in "$DRIVE_MOUNT_ROOT"/*; do
[ -d "$mount_point" ] || continue
letter=${mount_point##*/}
case " $desired " in
*" $letter "*) ;;
*) unmount_drive "$letter" ;;
esac
done
for letter in $desired; do
mount_drive "$letter"
done
}
apply_host_config() {
[ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0
cfg_json=$(curl -fsS -m 3 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/config" 2>/dev/null || true)
[ -n "$cfg_json" ] || return 0
sync_drive_mounts "$cfg_json"
if printf '%s' "$cfg_json" | grep -q '"prevent_sleep"[[:space:]]*:[[:space:]]*true'; then
if [ -z "$CAFFEINATE_PID" ] || ! kill -0 "$CAFFEINATE_PID" 2>/dev/null; then
if command -v caffeinate >/dev/null 2>&1; then
@@ -223,7 +304,7 @@ report_status() {
curl -fsS -m 3 -X POST \
-H "Authorization: Bearer $REIMS_TOKEN" \
-H "Content-Type: application/json" \
-d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":3}" \
-d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":4}" \
"$REIMS_HOST_URL/v1/status" >/dev/null 2>&1 || true
}
@@ -431,7 +512,7 @@ while :; do
if [ $((tick % 5)) -eq 0 ]; then
load_conf
ensure_webdav_mount
apply_prevent_sleep
apply_host_config
report_status
fi
sync_clipboard
@@ -509,12 +590,12 @@ launchctl bootstrap "gui/$uid" "$PLIST" 2>/dev/null || launchctl load -w "$PLIST
# Verify host bridge connectivity immediately.
. "$APP_DIR/config"
if curl -fsS -m 5 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/ping" >/dev/null 2>&1; then
echo "Reims Guest Tools 2.0 installed and connected!"
echo "Reims Guest Tools 4 installed and connected!"
echo "Clipboard: UTF-8 text + PNG screenshots (two-way)"
echo "Shared folder: ~/Desktop/ReimsShare (WebDAV live mount, auto-fallback to sync)"
echo "Prevent-sleep: controlled live from Reims-Go host UI"
else
echo "Reims Guest Tools 2.0 installed (waiting for Windows host bridge at $REIMS_HOST_URL)..."
echo "Reims Guest Tools 4 installed (waiting for Windows host bridge at $REIMS_HOST_URL)..."
fi
`)
}
@@ -526,9 +607,17 @@ set -e
APP_DIR="$HOME/Library/Application Support/ReimsGuestTools"
PLIST="$HOME/Library/LaunchAgents/com.reimsgo.guest-tools.plist"
SHARE_MOUNT="$HOME/ReimsShareMount"
DRIVE_MOUNT_ROOT="$HOME/ReimsWindowsDrives"
uid=$(id -u)
launchctl bootout "gui/$uid" "$PLIST" 2>/dev/null || launchctl unload "$PLIST" 2>/dev/null || true
umount "$SHARE_MOUNT" 2>/dev/null || true
for mount_point in "$DRIVE_MOUNT_ROOT"/*; do
[ -d "$mount_point" ] || continue
letter=${mount_point##*/}
umount "$mount_point" 2>/dev/null || true
link="$HOME/Desktop/Windows $letter"
[ -L "$link" ] && rm -f "$link" 2>/dev/null || true
done
rm -f "$PLIST"
rm -rf "$APP_DIR"
echo "Reims Guest Tools uninstalled. Your ~/ReimsShare files were kept."
+58 -42
View File
@@ -69,14 +69,20 @@ type Clipboard interface {
// VMConfig is persisted per VM in <vmDir>/.reims-go-tools.json (0600) so the
// guest's Bearer token survives reims-go restarts without reinstalling Guest Tools.
type VMConfig struct {
VMName string `json:"vm_name"`
Token string `json:"token"`
Port int `json:"port"`
SharedDir string `json:"shared_dir"`
PreventSleep bool `json:"prevent_sleep"`
VMName string `json:"vm_name"`
Token string `json:"token"`
Port int `json:"port"`
SharedDir string `json:"shared_dir"`
PreventSleep bool `json:"prevent_sleep"`
DriveSharingEnabled bool `json:"drive_sharing_enabled"`
SharedDrives []string `json:"shared_drives,omitempty"`
DriveVolumes map[string]string `json:"drive_volumes,omitempty"`
// DriveRoots is a runtime-only test/platform override keyed by NormalizeDriveLetter.
// Persisted configuration stores drive letters only, never arbitrary host roots.
DriveRoots map[string]string `json:"-"`
}
// GuestStatus summarizes live Guest Tools 2.0 connection and capability state.
// GuestStatus summarizes live Guest Tools connection and capability state.
type GuestStatus struct {
Connected bool `json:"connected"`
MountMode string `json:"mount_mode,omitempty"` // "webdav" | "sync"
@@ -166,14 +172,16 @@ type pendingClipOverride struct {
}
type registeredVM struct {
name string
token string
sharedDir string
preventSleep bool
mountMode string
sleepActive bool
agentVersion int
lastSeen time.Time
name string
token string
sharedDir string
preventSleep bool
driveSharingEnabled bool
sharedDriveRoots map[string]string
mountMode string
sleepActive bool
agentVersion int
lastSeen time.Time
injectMu sync.Mutex
textSeq uint64
@@ -188,17 +196,17 @@ type registeredVM struct {
// Server serves the token-authenticated host ↔ guest bridge over 127.0.0.1
// (reachable from QEMU SLIRP guests as http://10.0.2.2:<port>).
type Server struct {
mu sync.RWMutex
clip Clipboard
vms map[string]*registeredVM // keyed by VM name
davHandlers map[string]*webdav.Handler
davRoots map[string]string
port int
listener net.Listener
httpSrv *http.Server
watchCancel context.CancelFunc
clipNotify chan struct{}
onHostText func(vmName, text string)
mu sync.RWMutex
clip Clipboard
vms map[string]*registeredVM // keyed by VM name
davHandlers map[string]*webdav.Handler
davRoots map[string]string
port int
listener net.Listener
httpSrv *http.Server
watchCancel context.CancelFunc
clipNotify chan struct{}
onHostText func(vmName, text string)
}
// NewServer constructs a Guest Tools HTTP bridge. Pass nil for clip to use the
@@ -341,7 +349,7 @@ func (s *Server) Close(ctx context.Context) error {
return srv.Shutdown(ctx)
}
// RegisterVM registers or updates a VM's Bearer token and shared directory.
// RegisterVM registers or updates a VM's token, shared directory, and read-only drive selection.
func (s *Server) RegisterVM(cfg VMConfig) {
if cfg.VMName == "" || cfg.Token == "" {
return
@@ -349,21 +357,26 @@ func (s *Server) RegisterVM(cfg VMConfig) {
if cfg.SharedDir != "" {
_ = os.MkdirAll(cfg.SharedDir, 0o755)
}
driveRoots := configuredDriveRoots(cfg)
s.mu.Lock()
if cur := s.vms[cfg.VMName]; cur != nil {
cur.token = cfg.Token
cur.sharedDir = cfg.SharedDir
cur.preventSleep = cfg.PreventSleep
cur.driveSharingEnabled = cfg.DriveSharingEnabled
cur.sharedDriveRoots = driveRoots
s.mu.Unlock()
return
}
s.vms[cfg.VMName] = &registeredVM{
name: cfg.VMName,
token: cfg.Token,
sharedDir: cfg.SharedDir,
preventSleep: cfg.PreventSleep,
textActive: make(map[string]*pendingTextInput),
textNotify: make(chan struct{}),
name: cfg.VMName,
token: cfg.Token,
sharedDir: cfg.SharedDir,
preventSleep: cfg.PreventSleep,
driveSharingEnabled: cfg.DriveSharingEnabled,
sharedDriveRoots: driveRoots,
textActive: make(map[string]*pendingTextInput),
textNotify: make(chan struct{}),
}
s.mu.Unlock()
}
@@ -575,14 +588,16 @@ func (s *Server) authenticate(r *http.Request) *registeredVM {
// injectMu and alias the text queues. Handlers that need the
// queues look the live VM up again by name under s.mu.
cp := registeredVM{
name: vm.name,
token: vm.token,
sharedDir: vm.sharedDir,
preventSleep: vm.preventSleep,
mountMode: vm.mountMode,
sleepActive: vm.sleepActive,
agentVersion: vm.agentVersion,
lastSeen: vm.lastSeen,
name: vm.name,
token: vm.token,
sharedDir: vm.sharedDir,
preventSleep: vm.preventSleep,
driveSharingEnabled: vm.driveSharingEnabled,
sharedDriveRoots: cloneStringMap(vm.sharedDriveRoots),
mountMode: vm.mountMode,
sleepActive: vm.sleepActive,
agentVersion: vm.agentVersion,
lastSeen: vm.lastSeen,
}
return &cp
}
@@ -619,8 +634,8 @@ func (s *Server) handlePing(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]any{
"ok": true,
"vm": vm.name,
"version": 3,
"capabilities": []string{"clipboard-text", "clipboard-png", "clipboard-longpoll", "webdav", "prevent-sleep", "text-input"},
"version": DriveShareAgentVersion,
"capabilities": []string{"clipboard-text", "clipboard-png", "clipboard-longpoll", "webdav", "prevent-sleep", "text-input", "drive-shares-readonly"},
})
}
@@ -639,6 +654,7 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
"vm": vm.name,
"prevent_sleep": vm.preventSleep,
"webdav_path": "/dav/" + vm.name + "/",
"shared_drives": enabledDriveLetters(vm),
})
}
+67
View File
@@ -112,6 +112,11 @@ func (s *Server) handleWebDAV(w http.ResponseWriter, r *http.Request) {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
drivePrefix := vm.name + "/drives/"
if strings.HasPrefix(trimmed, drivePrefix) {
s.handleDriveWebDAV(w, r, vm, strings.TrimPrefix(trimmed, drivePrefix))
return
}
if vm.sharedDir == "" {
http.Error(w, "shared directory not configured", http.StatusNotFound)
return
@@ -125,6 +130,68 @@ func (s *Server) handleWebDAV(w http.ResponseWriter, r *http.Request) {
handler.ServeHTTP(w, r)
}
func (s *Server) handleDriveWebDAV(w http.ResponseWriter, r *http.Request, vm *registeredVM, drivePath string) {
if !vm.driveSharingEnabled {
http.Error(w, "drive sharing disabled", http.StatusForbidden)
return
}
if r.Method == "PROPFIND" {
depth := strings.TrimSpace(r.Header.Get("Depth"))
if depth == "" {
depth = "1"
r.Header.Set("Depth", depth)
}
if depth != "0" && depth != "1" {
http.Error(w, "drive PROPFIND requires Depth: 0 or 1", http.StatusBadRequest)
return
}
}
if !allowReadOnlyDAV(w, r) {
return
}
driveSegment := drivePath
if idx := strings.IndexByte(driveSegment, '/'); idx >= 0 {
driveSegment = driveSegment[:idx]
}
drive, ok := NormalizeDriveLetter(driveSegment)
if !ok || driveSegment != drive {
http.Error(w, "invalid drive", http.StatusBadRequest)
return
}
root, ok := vm.sharedDriveRoots[drive]
if !ok {
http.Error(w, "drive not shared", http.StatusForbidden)
return
}
handler, err := s.getOrCreateDriveDAVHandler(vm.name, drive, root)
if err != nil {
http.Error(w, "drive unavailable", http.StatusNotFound)
return
}
handler.ServeHTTP(w, r)
}
func (s *Server) getOrCreateDriveDAVHandler(vmName, drive, root string) (*webdav.Handler, error) {
key := vmName + "/drives/" + drive
s.mu.Lock()
defer s.mu.Unlock()
if cur := s.davHandlers[key]; cur != nil && s.davRoots[key] == root {
return cur, nil
}
fsys, err := newReadOnlyDriveFS(root)
if err != nil {
return nil, err
}
h := &webdav.Handler{
Prefix: "/dav/" + vmName + "/drives/" + drive,
FileSystem: fsys,
LockSystem: webdav.NewMemLS(),
}
s.davHandlers[key] = h
s.davRoots[key] = root
return h, nil
}
func (s *Server) getOrCreateDAVHandler(vmName, sharedDir string) (*webdav.Handler, error) {
s.mu.Lock()
defer s.mu.Unlock()
+5 -4
View File
@@ -9,10 +9,11 @@ import (
// Drive is a disk a data folder could go on.
type Drive struct {
Root string `json:"root"`
FreeGB float64 `json:"free_gb"`
System bool `json:"system"`
External bool `json:"external"`
Root string `json:"root"`
FreeGB float64 `json:"free_gb"`
System bool `json:"system"`
External bool `json:"external"`
VolumeGUID string `json:"volume_guid,omitempty"`
}
// ListDrives returns the home directory's volume on dev/preview hosts.
+28 -10
View File
@@ -13,18 +13,20 @@ import (
)
var (
procGetLogicalDrives = kernel32.NewProc("GetLogicalDrives")
procGetDriveTypeW = kernel32.NewProc("GetDriveTypeW")
procGetLogicalDrives = kernel32.NewProc("GetLogicalDrives")
procGetDriveTypeW = kernel32.NewProc("GetDriveTypeW")
procGetVolumeNameForVolumeMountPointW = kernel32.NewProc("GetVolumeNameForVolumeMountPointW")
)
const driveFixed = 3 // DRIVE_FIXED
// Drive is a local fixed disk a data folder could go on.
type Drive struct {
Root string `json:"root"` // `D:\`
FreeGB float64 `json:"free_gb"` // bytes available to this user
System bool `json:"system"` // holds Windows
External bool `json:"external"` // on a USB bus (Windows still calls USB disks "fixed")
Root string `json:"root"` // `D:\`
FreeGB float64 `json:"free_gb"` // bytes available to this user
System bool `json:"system"` // holds Windows
External bool `json:"external"` // on a USB bus (Windows still calls USB disks "fixed")
VolumeGUID string `json:"volume_guid,omitempty"` // stable volume identity; letters can be reassigned
}
// ListDrives returns local fixed drives (no removable, network or optical).
@@ -53,15 +55,31 @@ func ListDrives() []Drive {
continue
}
out = append(out, Drive{
Root: root,
FreeGB: free,
System: strings.EqualFold(root[:2], sys),
External: isUSB(root[:2]),
Root: root,
FreeGB: free,
System: strings.EqualFold(root[:2], sys),
External: isUSB(root[:2]),
VolumeGUID: volumeGUID(root),
})
}
return out
}
func volumeGUID(root string) string {
p, err := syscall.UTF16PtrFromString(root)
if err != nil {
return ""
}
buf := make([]uint16, 50)
r, _, _ := procGetVolumeNameForVolumeMountPointW.Call(
uintptr(unsafe.Pointer(p)), uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)),
)
if r == 0 {
return ""
}
return syscall.UTF16ToString(buf)
}
// isUSB asks the volume's storage device for its bus type
// (IOCTL_STORAGE_QUERY_PROPERTY, StorageDeviceProperty). Opening with no
// access rights needs no elevation.
+3
View File
@@ -13,6 +13,9 @@ func TestListDrivesFindsTheSystemDrive(t *testing.T) {
if d.External {
t.Error("system drive reported as USB")
}
if d.VolumeGUID == "" {
t.Error("system drive has no volume GUID")
}
}
}
if !sys {
+6
View File
@@ -0,0 +1,6 @@
//go:build !windows
package host
// ForegroundPID is not implemented off Windows and always reports no owner.
func ForegroundPID() uint32 { return 0 }
+17
View File
@@ -0,0 +1,17 @@
//go:build windows
package host
import "unsafe"
// ForegroundPID returns the process that owns the foreground window, or 0
// when there is none (locked screen, desktop focused).
func ForegroundPID() uint32 {
hwnd, _, _ := procGetForegroundWindow.Call()
if hwnd == 0 {
return 0
}
var pid uint32
_, _, _ = procGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&pid)))
return pid
}
+30
View File
@@ -98,6 +98,10 @@ func Scale(img image.Image, maxW int) image.Image {
dh = 1
}
dst := image.NewRGBA(image.Rect(0, 0, dw, dh))
if src, ok := img.(*image.RGBA); ok {
scaleRGBA(dst, src, sw, sh, dw, dh)
return dst
}
for y := 0; y < dh; y++ {
y0, y1 := y*sh/dh, (y+1)*sh/dh
for x := 0; x < dw; x++ {
@@ -118,6 +122,32 @@ func Scale(img image.Image, maxW int) image.Image {
return dst
}
// scaleRGBA is Scale's box filter for *image.RGBA, the type decodePPM
// returns. It reads Pix directly: going through img.At boxes every pixel
// in an interface, which for a 4K frame is about 8 million allocations.
func scaleRGBA(dst, src *image.RGBA, sw, sh, dw, dh int) {
for y := 0; y < dh; y++ {
y0, y1 := y*sh/dh, (y+1)*sh/dh
drow := dst.Pix[y*dst.Stride:]
for x := 0; x < dw; x++ {
x0, x1 := x*sw/dw, (x+1)*sw/dw
var r, g, bl, n uint32
for sy := y0; sy < y1; sy++ {
row := src.Pix[sy*src.Stride+x0*4 : sy*src.Stride+x1*4]
for i := 0; i < len(row); i += 4 {
r, g, bl = r+uint32(row[i]), g+uint32(row[i+1]), bl+uint32(row[i+2])
}
n += uint32(x1 - x0)
}
if n == 0 {
n = 1
}
d := drow[x*4 : x*4+4]
d[0], d[1], d[2], d[3] = uint8(r/n), uint8(g/n), uint8(bl/n), 255
}
}
}
// Blank reports whether a frame is (almost) one flat colour — a powered-off
// or not-yet-drawn console — so the UI can keep its placeholder instead.
func Blank(img image.Image) bool {
+26
View File
@@ -53,6 +53,32 @@ func TestScaleKeepsAspect(t *testing.T) {
}
}
// opaqueImage hides the *image.RGBA type so Scale takes its generic path.
type opaqueImage struct{ image.Image }
func TestScaleRGBAMatchesGenericPath(t *testing.T) {
img := image.NewRGBA(image.Rect(0, 0, 1931, 1087)) // odd sizes: uneven boxes
for i := range img.Pix {
img.Pix[i] = byte(i*7 + i/4)
if i%4 == 3 {
img.Pix[i] = 255
}
}
fast := Scale(img, 640).(*image.RGBA)
slow := Scale(opaqueImage{img}, 640).(*image.RGBA)
if !bytes.Equal(fast.Pix, slow.Pix) {
t.Fatal("RGBA fast path differs from the generic box filter")
}
}
func BenchmarkScale4K(b *testing.B) {
img := image.NewRGBA(image.Rect(0, 0, 3840, 2160))
b.ReportAllocs()
for i := 0; i < b.N; i++ {
Scale(img, 640)
}
}
func TestBlank(t *testing.T) {
flat := image.NewRGBA(image.Rect(0, 0, 200, 100))
if !Blank(flat) {
+2 -2
View File
@@ -13,8 +13,8 @@ import (
// Version is the current Reims-Go release version. Release builds may override
// it at link time with:
//
// -ldflags "-X github.com/Nwflower/reims-go/internal/version.Version=v0.2.2"
var Version = "v0.2.2"
// -ldflags "-X github.com/Nwflower/reims-go/internal/version.Version=v0.2.3"
var Version = "v0.2.3"
const (
DefaultReleasesRepo = "Nwflower/Reims-Go"
+22 -4
View File
@@ -2,6 +2,9 @@ package main
import (
"embed"
"os"
"github.com/Nwflower/reims-go/internal/cli"
"github.com/wailsapp/wails/v2"
"github.com/wailsapp/wails/v2/pkg/options"
@@ -16,9 +19,24 @@ var assets embed.FS
var trayIconPNG []byte
func main() {
args := os.Args[1:]
if cli.IsCommand(args) {
attachConsole()
os.Exit(cli.Main(args))
}
launch, _ := cli.ParseWindowArgs(args)
app := NewApp()
app.launch = launch
err := wails.Run(&options.App{
Title: "Reims-Go",
Title: "Reims-Go",
StartHidden: launch.Background,
// One window per user. A second launch — double-click, or `reims-go vm
// start` handing a VM over — goes to the running one instead.
SingleInstanceLock: &options.SingleInstanceLock{
UniqueId: cli.InstanceID,
OnSecondInstanceLaunch: app.onSecondInstance,
},
Width: 1120,
Height: 740,
MinWidth: 920,
@@ -33,9 +51,9 @@ func main() {
WebviewIsTransparent: false,
WindowIsTranslucent: false,
CustomTheme: &windows.ThemeSettings{
DarkModeTitleBar: windows.RGB(28, 28, 30),
DarkModeTitleText: windows.RGB(245, 245, 247),
DarkModeBorder: windows.RGB(58, 58, 62),
DarkModeTitleBar: windows.RGB(28, 28, 30),
DarkModeTitleText: windows.RGB(245, 245, 247),
DarkModeBorder: windows.RGB(58, 58, 62),
},
},
OnStartup: app.startup,
+6 -8
View File
@@ -57,7 +57,7 @@ func (a *App) GetVMStats(name string) (VMStats, error) {
return stats, err
}
ctx := context.Background()
vms, _ := c.List(ctx)
vms, _ := a.polledVMs(ctx)
var pid int
for _, vm := range vms {
if vm.Name == name {
@@ -70,13 +70,11 @@ func (a *App) GetVMStats(name string) (VMStats, error) {
}
stats.PID = pid
if d, err := c.Show(ctx, name); err == nil {
if diskPath := resolveVMDiskPath(d); diskPath != "" {
if du, err := host.InspectDiskUsage(diskPath); err == nil {
stats.DiskActualBytes = du.ActualBytes
stats.DiskVirtualBytes = du.VirtualBytes
stats.DiskFormat = du.Format
}
if diskPath := a.vmDiskPath(ctx, c, name); diskPath != "" {
if du, err := host.InspectDiskUsage(diskPath); err == nil {
stats.DiskActualBytes = du.ActualBytes
stats.DiskVirtualBytes = du.VirtualBytes
stats.DiskFormat = du.Format
}
}
+10 -3
View File
@@ -13,6 +13,7 @@ import (
"sync"
"time"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/qmp"
"github.com/Nwflower/reims-go/internal/thumb"
)
@@ -59,8 +60,14 @@ func (a *App) captureThumb(name, path string) (VMThumbnail, bool) {
if busy {
return VMThumbnail{}, false
}
d, err := a.GetVMDetail(name)
if err != nil || d.State != "running" || d.Directory == "" {
vm, ok := a.polledVM(name)
if !ok || vm.State != "running" || vm.Dir == "" {
return VMThumbnail{}, false
}
// The user is looking at the VM window itself, not this page: skip the
// screendump, which runs on QEMU's main loop and writes a full-size frame
// (about 25 MB at 4K) to disk.
if vm.PID != nil && *vm.PID > 0 && host.ForegroundPID() == uint32(*vm.PID) {
return VMThumbnail{}, false
}
a.mu.Lock()
@@ -74,7 +81,7 @@ func (a *App) captureThumb(name, path string) (VMThumbnail, bool) {
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
defer cancel()
format, err := qmp.ScreendumpVM(ctx, d.Directory, raw)
format, err := qmp.ScreendumpVM(ctx, vm.Dir, raw)
if err != nil {
return VMThumbnail{}, false
}
+1 -1
View File
@@ -187,7 +187,7 @@ func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Ti
}
func (a *App) currentVMPID(ctx context.Context, name string) (int, bool) {
vms, err := a.listVMsInternal(ctx)
vms, err := a.polledVMs(ctx)
if err != nil {
return 0, true // keep watching on transient error
}
+134
View File
@@ -0,0 +1,134 @@
package main
// What the desktop window does with cli.WindowArgs: from its own launch
// (`reims-go --background --start-vm=…`) or from a later `reims-go` run
// (Wails OnSecondInstanceLaunch). See internal/cli/window_args.go.
import (
"fmt"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/cli"
"github.com/wailsapp/wails/v2/pkg/options"
)
// afterStartup runs the launch request once the window's context exists. A
// hidden launch with no tray to reopen it from shows the window after all.
func (a *App) afterStartup() {
a.mu.Lock()
launch := a.launch
noTray := a.trayMgr == nil
a.mu.Unlock()
if launch.Background && noTray {
a.ShowMainWindow()
}
a.handleWindowArgs(launch, false)
}
// onSecondInstance handles another `reims-go.exe` started while this one runs.
func (a *App) onSecondInstance(data options.SecondInstanceData) {
w, ok := cli.ParseWindowArgs(data.Args)
if !ok {
// Command-line mode never gets here (it does not take the lock), so
// this is an argument we don't know: treat it as a plain launch.
w = cli.WindowArgs{}
}
a.handleWindowArgs(w, true)
}
// handleWindowArgs starts the requested VM, or for a plain second launch
// (double-click while running in the tray) brings the window forward. A
// `vm start` handed over from the command line leaves the window as it is.
func (a *App) handleWindowArgs(w cli.WindowArgs, secondLaunch bool) {
if w.StartVM == "" {
if secondLaunch && !w.Background {
a.ShowMainWindow()
}
return
}
name := w.StartVM
result := a.startResultPath(w.StartResult)
if w.StartResult != "" && result == "" {
a.emitLog(name, "Ignored a start result path outside the Reims-Go temp folder: "+w.StartResult)
}
a.emitLog(name, "Start requested from the command line")
go func() {
capture := a.captureLogs(name)
err := a.StartVM(name)
lines := a.releaseLogs(name, capture)
if err != nil && len(lines) > 0 {
// StartVM's own error is often just "exit status 1"; the reason is
// in what it logged. The command line has no log panel to look at.
err = fmt.Errorf("%w\n%s", err, strings.Join(lines, "\n"))
}
if result != "" {
if werr := cli.WriteStartResult(result, err); werr != nil {
a.emitLog(name, "Could not report the start result to the command line: "+werr.Error())
}
}
}()
}
// logCapture keeps the last few log lines one source emits while it is
// registered, for reporting a failed start back to the command line.
type logCapture struct{ lines []string }
const logCaptureMax = 8
func (c *logCapture) add(line string) {
c.lines = append(c.lines, line)
if len(c.lines) > logCaptureMax {
c.lines = c.lines[len(c.lines)-logCaptureMax:]
}
}
// captureLogs starts collecting emitLog lines for source.
func (a *App) captureLogs(source string) *logCapture {
c := &logCapture{}
a.mu.Lock()
if a.logCaptures == nil {
a.logCaptures = make(map[string][]*logCapture)
}
a.logCaptures[source] = append(a.logCaptures[source], c)
a.mu.Unlock()
return c
}
// releaseLogs stops c and returns what it collected.
func (a *App) releaseLogs(source string, c *logCapture) []string {
a.mu.Lock()
defer a.mu.Unlock()
list := a.logCaptures[source]
for i, cur := range list {
if cur == c {
list = append(list[:i], list[i+1:]...)
break
}
}
if len(list) == 0 {
delete(a.logCaptures, source)
} else {
a.logCaptures[source] = list
}
return c.lines
}
// startResultPath accepts only a result file directly in this data root's
// temp folder named like the ones `vm start` makes, so a launch argument
// can't make Reims-Go overwrite an arbitrary file.
func (a *App) startResultPath(p string) string {
if p == "" {
return ""
}
a.mu.Lock()
tmp := a.cfg.TempDir()
a.mu.Unlock()
clean := filepath.Clean(p)
base := filepath.Base(clean)
if !strings.EqualFold(filepath.Dir(clean), filepath.Clean(tmp)) ||
!strings.HasPrefix(base, "cli-start-") || !strings.HasSuffix(base, ".json") {
return ""
}
return clean
}
+48
View File
@@ -0,0 +1,48 @@
package main
import (
"fmt"
"path/filepath"
"testing"
"github.com/Nwflower/reims-go/internal/config"
)
func TestLogCaptureKeepsLastLinesOfItsSource(t *testing.T) {
a := &App{cfg: config.Default()}
c := a.captureLogs("m0")
for i := 0; i < logCaptureMax+3; i++ {
a.emitLog("m0", fmt.Sprintf("line %d", i))
}
a.emitLog("other", "not mine")
lines := a.releaseLogs("m0", c)
if len(lines) != logCaptureMax || lines[0] != "line 3" || lines[len(lines)-1] != fmt.Sprintf("line %d", logCaptureMax+2) {
t.Fatalf("captured %q", lines)
}
a.emitLog("m0", "after release")
if len(c.lines) != logCaptureMax || len(a.logCaptures) != 0 {
t.Fatal("a released capture must stop collecting")
}
}
func TestStartResultPathStaysInTempDir(t *testing.T) {
cfg := config.Default()
cfg.DataRoot = `D:\Data\reims-go`
a := &App{cfg: cfg}
tmp := cfg.TempDir()
good := filepath.Join(tmp, "cli-start-123.json")
if got := a.startResultPath(good); got != good {
t.Fatalf("own result file rejected: %q", got)
}
for _, bad := range []string{
filepath.Join(tmp, "..", "reims-go.json"),
filepath.Join(tmp, "sub", "cli-start-1.json"),
filepath.Join(tmp, "notes.json"),
`C:\Windows\cli-start-1.json`,
} {
if got := a.startResultPath(bad); got != "" {
t.Errorf("startResultPath(%q) = %q, want rejected", bad, got)
}
}
}