Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7b0fbd5978 | ||
|
|
fc284e99ab | ||
|
|
4bde4f3cf5 | ||
|
|
faa2b71202 | ||
|
|
45a2d48560 | ||
|
|
168c7140f8 | ||
|
|
9e357ba38c | ||
|
|
d42a4f85f0 | ||
|
|
17497aee73 | ||
|
|
f601236f74 | ||
|
|
c4df14c785 | ||
|
|
a962c52bcb | ||
|
|
05ad179ee3 | ||
|
|
efa2f743c1 | ||
|
|
05cc34cbaa | ||
|
|
3f8cf11d3d | ||
|
|
404090d8ed | ||
|
|
eb14a1610f | ||
|
|
60dd772b83 | ||
|
|
6d16105201 | ||
|
|
36c937d718 | ||
|
|
c7fe3d27f0 | ||
|
|
f6f6bfce34 |
No files matched your search
@@ -6,6 +6,12 @@
|
||||
"runtimeExecutable": "wails",
|
||||
"runtimeArgs": ["dev", "-browser=false"],
|
||||
"port": 34115
|
||||
},
|
||||
{
|
||||
"name": "wails-dev-firstrun",
|
||||
"runtimeExecutable": "pwsh",
|
||||
"runtimeArgs": ["-NoProfile", "-Command", "$env:REIMS_GO_FIRST_RUN='1'; $env:REIMS_GO_LOCATION_FILE='D:/Build/Temp/reims-firstrun/location.json'; wails dev -browser=false"],
|
||||
"port": 34115
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
name: Bug 反馈
|
||||
description: 报告启动失败、安装异常或界面问题
|
||||
labels: ["bug"]
|
||||
body:
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: 问题描述
|
||||
description: 简述遇到了什么问题,以及预期行为。
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: env
|
||||
attributes:
|
||||
label: 宿主机环境
|
||||
description: 建议附带 `reims-go doctor` 输出(请勿包含序列号、MAC 地址或 OSK 等敏感信息)。
|
||||
placeholder: |
|
||||
- Windows 版本:例如 Windows 11 24H2 / Windows 10 22H2
|
||||
- CPU / 显卡:例如 i7-12700K / RTX 4070 Ti
|
||||
- Reims-Go 版本:例如 v0.2.0
|
||||
- 运行时版本:例如 runtime-3731afd
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: 复现步骤
|
||||
placeholder: |
|
||||
1. ...
|
||||
2. ...
|
||||
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: 相关日志(可选)
|
||||
render: text
|
||||
@@ -0,0 +1,5 @@
|
||||
blank_issues_enabled: true
|
||||
contact_links:
|
||||
- name: 开发路线图(Roadmap)
|
||||
url: https://github.com/Nwflower/Reims-Go/blob/main/docs/roadmap.md
|
||||
about: 查看当前进度与已规划功能,避免重复提问
|
||||
@@ -0,0 +1,16 @@
|
||||
name: 功能建议
|
||||
description: 提出新功能想法或体验改进建议
|
||||
labels: ["enhancement"]
|
||||
body:
|
||||
- type: textarea
|
||||
id: summary
|
||||
attributes:
|
||||
label: 你希望解决什么问题或新增什么功能?
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: details
|
||||
attributes:
|
||||
label: 补充说明(可选)
|
||||
description: 使用场景、交互设想或参考案例。
|
||||
|
After Width: | Height: | Size: 62 KiB |
|
After Width: | Height: | Size: 37 KiB |
|
After Width: | Height: | Size: 37 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 26 KiB |
@@ -0,0 +1,120 @@
|
||||
name: Build Portable Runtime (Candidate)
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
upstream_commit:
|
||||
description: "Pinned steelbrain/reims-vgpu commit SHA"
|
||||
required: true
|
||||
default: "3731afd"
|
||||
publish_candidate:
|
||||
description: "Publish as GitHub prerelease (candidate channel only; never stable)"
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build-runtime:
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 120
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup MSYS2 CLANG64
|
||||
id: msys2
|
||||
uses: msys2/setup-msys2@v2
|
||||
with:
|
||||
msystem: CLANG64
|
||||
update: true
|
||||
install: >-
|
||||
git zstd tar mingw-w64-clang-x86_64-toolchain
|
||||
mingw-w64-clang-x86_64-cmake mingw-w64-clang-x86_64-meson
|
||||
mingw-w64-clang-x86_64-ninja mingw-w64-clang-x86_64-pkgconf
|
||||
mingw-w64-clang-x86_64-glib2 mingw-w64-clang-x86_64-pixman
|
||||
mingw-w64-clang-x86_64-gtk3 mingw-w64-clang-x86_64-libslirp
|
||||
mingw-w64-clang-x86_64-libusb mingw-w64-clang-x86_64-libva
|
||||
mingw-w64-clang-x86_64-mesa mingw-w64-clang-x86_64-vulkan-loader
|
||||
mingw-w64-clang-x86_64-python mingw-w64-clang-x86_64-python-pip
|
||||
|
||||
- name: Checkout upstream reims-vgpu & verify patch queue
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$work = Join-Path $env:RUNNER_TEMP 'reims-vgpu'
|
||||
$cargoHome = Join-Path $env:RUNNER_TEMP 'cargo'
|
||||
$xdgData = Join-Path $env:RUNNER_TEMP 'xdg-data'
|
||||
$xdgCache = Join-Path $env:RUNNER_TEMP 'xdg-cache'
|
||||
New-Item -ItemType Directory -Force -Path $cargoHome, $xdgData, $xdgCache | Out-Null
|
||||
git clone https://github.com/steelbrain/reims-vgpu.git $work
|
||||
git -C $work checkout ${{ inputs.upstream_commit }}
|
||||
# Verify local patches apply cleanly; fail hard on mismatch (AGENTS.md rule 4).
|
||||
if (Test-Path 'patches/reims-vgpu-cargo-lock.patch') {
|
||||
git -C $work apply --check (Resolve-Path 'patches/reims-vgpu-cargo-lock.patch')
|
||||
git -C $work apply (Resolve-Path 'patches/reims-vgpu-cargo-lock.patch')
|
||||
}
|
||||
$short = (git -C $work rev-parse --short HEAD).Trim()
|
||||
"UPSTREAM_DIR=$work" | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
"SHORT_COMMIT=$short" | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
"CARGO_HOME=$cargoHome" | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
"XDG_DATA_HOME=$xdgData" | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
"XDG_CACHE_HOME=$xdgCache" | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
|
||||
- name: Build upstream runtime in MSYS2 CLANG64
|
||||
shell: msys2 {0}
|
||||
env:
|
||||
REIMS_INSTALL_SKIP_HOST_CHECKS: "1"
|
||||
run: |
|
||||
set -euo pipefail
|
||||
UPSTREAM_UNIX="$(cygpath -u "$UPSTREAM_DIR")"
|
||||
WS_UNIX="$(cygpath -u "$GITHUB_WORKSPACE")"
|
||||
cd "$UPSTREAM_UNIX"
|
||||
# Fetch vendor/qemu at the pinned commit before applying patches.
|
||||
git submodule update --init --depth 1 vendor/qemu || git submodule update --init vendor/qemu
|
||||
for p in \
|
||||
"$WS_UNIX/patches/qemu-whpx-win10-compat.patch" \
|
||||
"$WS_UNIX/patches/qemu-whpx-win10-startup-ipis.patch" \
|
||||
"$WS_UNIX/patches/qemu-whpx-nested-virt-nonfatal.patch"; do
|
||||
[ -f "$p" ] || continue
|
||||
git -C vendor/qemu apply --check "$p"
|
||||
git -C vendor/qemu apply "$p"
|
||||
done
|
||||
# Run upstream's own non-interactive CLANG64 build script.
|
||||
bash scripts/install-ctl.sh --yes
|
||||
|
||||
- name: Package candidate runtime & source archives
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$outDir = Join-Path $env:RUNNER_TEMP 'releases'
|
||||
$qemuDir = Join-Path $env:XDG_DATA_HOME 'reims-ctl\qemu\current'
|
||||
$msys2Root = '${{ steps.msys2.outputs.msys2-location }}'
|
||||
New-Item -ItemType Directory -Force -Path $outDir | Out-Null
|
||||
pwsh -File scripts/pack-runtime.ps1 `
|
||||
-ReimsRepo $env:UPSTREAM_DIR `
|
||||
-CargoHome $env:CARGO_HOME `
|
||||
-QemuDir $qemuDir `
|
||||
-Msys2 $msys2Root `
|
||||
-OutDir $outDir `
|
||||
-TempRoot $env:RUNNER_TEMP `
|
||||
-Channel candidate `
|
||||
-IncludeNestedVirtPatch
|
||||
|
||||
- name: Upload candidate artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: reims-runtime-win-x64-${{ env.SHORT_COMMIT }}-candidate
|
||||
path: ${{ runner.temp }}/releases/*
|
||||
|
||||
- name: Publish candidate prerelease (never stable)
|
||||
if: ${{ inputs.publish_candidate }}
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
$tag = "runtime-$($env:SHORT_COMMIT)"
|
||||
gh release create $tag "$($env:RUNNER_TEMP)/releases/*" `
|
||||
--prerelease `
|
||||
--title "Portable Runtime $tag (candidate)" `
|
||||
--notes "Automated candidate build from upstream $($env:SHORT_COMMIT). Must pass scripts/smoke-runtime.ps1 on a real Windows host and human review before promotion to stable."
|
||||
@@ -0,0 +1,46 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
cache-dependency-path: frontend/pnpm-lock.yaml
|
||||
|
||||
- name: Frontend build
|
||||
shell: pwsh
|
||||
run: |
|
||||
pnpm --dir frontend install --frozen-lockfile
|
||||
pnpm --dir frontend build
|
||||
|
||||
- name: Go test & vet
|
||||
shell: pwsh
|
||||
run: |
|
||||
go test ./...
|
||||
go vet ./...
|
||||
|
||||
- name: Build CLI & GUI binaries
|
||||
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 .
|
||||
@@ -0,0 +1,100 @@
|
||||
name: Release Reims-Go
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: "Release tag to build & publish (e.g. v0.2.1)"
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
cache-dependency-path: frontend/pnpm-lock.yaml
|
||||
|
||||
- name: Resolve version tag
|
||||
shell: pwsh
|
||||
run: |
|
||||
$tag = if ('${{ github.event_name }}' -eq 'workflow_dispatch') { '${{ inputs.tag }}' } else { '${{ github.ref_name }}' }
|
||||
if (-not $tag.StartsWith('v')) { throw "Release tag must start with 'v', got: $tag" }
|
||||
"RELEASE_TAG=$tag" | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
|
||||
- name: Build frontend
|
||||
shell: pwsh
|
||||
run: |
|
||||
pnpm --dir frontend install --frozen-lockfile
|
||||
pnpm --dir frontend build
|
||||
|
||||
- name: Go test & vet
|
||||
shell: pwsh
|
||||
run: |
|
||||
go test ./...
|
||||
go vet ./...
|
||||
|
||||
- name: Install Wails CLI
|
||||
shell: pwsh
|
||||
run: go install github.com/wailsapp/wails/v2/cmd/wails@v2.17.1
|
||||
|
||||
- name: Build Windows x64 GUI & CLI binaries
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$tag = $env:RELEASE_TAG
|
||||
$dist = 'dist-release'
|
||||
New-Item -ItemType Directory -Force -Path $dist | Out-Null
|
||||
$verPkg = 'github.com/Nwflower/reims-go/internal/version'
|
||||
$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)"
|
||||
})
|
||||
[IO.File]::WriteAllText((Join-Path $dist 'SHA256SUMS.txt'), ($lines -join "`n") + "`n", [Text.UTF8Encoding]::new($false))
|
||||
Get-Content (Join-Path $dist 'SHA256SUMS.txt')
|
||||
|
||||
- name: Publish GitHub Release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$tag = $env:RELEASE_TAG
|
||||
$files = @(Get-ChildItem -LiteralPath 'dist-release' -File | Select-Object -ExpandProperty FullName)
|
||||
$exists = $true
|
||||
try {
|
||||
gh release view $tag *> $null
|
||||
if ($LASTEXITCODE -ne 0) { $exists = $false }
|
||||
} catch {
|
||||
$exists = $false
|
||||
}
|
||||
if ($exists) {
|
||||
gh release upload $tag @files --clobber
|
||||
} else {
|
||||
gh release create $tag @files `
|
||||
--title "Reims-Go $tag" `
|
||||
--generate-notes
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 reims-go contributors
|
||||
Copyright (c) 2026 Reims-Go contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
@@ -19,12 +19,3 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
---
|
||||
|
||||
This license covers reims-go's own code (Go backend and frontend shell) only.
|
||||
The portable runtime packages distributed as release assets bundle third-party
|
||||
components (QEMU under GPL-2.0, reims-vgpu / reims-ctl / reims-util /
|
||||
metal2vulkan under GPL-2.0-or-later OR LGPL-3.0-or-later, and MSYS2 CLANG64
|
||||
libraries under their own licenses). Each runtime release ships the matching
|
||||
source package, NOTICE.md and licenses/ — see docs/portable-runtime-spec.md §7.
|
||||
@@ -1,10 +1,14 @@
|
||||
# Third-Party Notices
|
||||
|
||||
`reims-go` itself (Go backend and desktop frontend) is licensed separately from the
|
||||
portable runtime bundle it invokes as an external child process.
|
||||
`Reims-Go` itself (Go backend and desktop frontend) is licensed under the MIT
|
||||
License (see `LICENSE`). That license applies to Reims-Go's own code only and
|
||||
is separate from the portable runtime bundle it invokes as an external child
|
||||
process.
|
||||
|
||||
The portable runtime bundle (`reims-runtime-win-x64-<commit>.tar.zst`) contains
|
||||
precompiled binaries built from the following upstream open-source projects:
|
||||
precompiled binaries built from the following upstream open-source projects.
|
||||
Each runtime release ships the matching source package, `NOTICE.md`, and
|
||||
`licenses/` (see `docs/portable-runtime-spec.md` §7):
|
||||
|
||||
1. **reims-vgpu / reims-ctl**
|
||||
- Upstream: https://github.com/steelbrain/reims-vgpu
|
||||
|
||||
@@ -1,37 +1,138 @@
|
||||
# reims-go
|
||||
<p align="center">
|
||||
<a href="https://github.com/Nwflower/Reims-Go">
|
||||
<img src="./assets/logo.png" width="76" height="76" alt="Reims-Go" />
|
||||
</a>
|
||||
</p>
|
||||
|
||||
> Windows 桌面端 **免编译、一站式 `reims-vgpu` macOS 虚拟机启动器与开发者工作台**(Go + Wails,GUI + CLI 一体)。
|
||||
<h1 align="center">Reims-Go</h1>
|
||||
|
||||
## 为什么做 reims-go?
|
||||
<p align="center">
|
||||
在 Windows 上开一台带 GPU 加速的 macOS 虚拟机——免编译,开箱即用。
|
||||
</p>
|
||||
|
||||
上游 [steelbrain/reims-vgpu](https://github.com/steelbrain/reims-vgpu) 已经实现了在 Windows 原生 QEMU + WHPX 上将 macOS Guest 的 Metal 图形转译到宿主机 Vulkan GPU(如 NVIDIA RTX 4070 Ti)。但当前使用门槛依然很高:
|
||||
<p align="center">
|
||||
<a href="https://github.com/Nwflower/Reims-Go/releases"><strong>下载</strong></a> ·
|
||||
<a href="#快速开始">快速开始</a> ·
|
||||
<a href="#界面">界面</a> ·
|
||||
<a href="./docs/roadmap.md">路线图</a>
|
||||
</p>
|
||||
|
||||
1. **安装编译繁琐**:需手动安装 MSYS2、换镜像源、装 Rust、拉取 `vendor/qemu` 并本地编译 1800+ 目标(耗时 15–30 分钟)。
|
||||
2. **默认污染 C 盘**:MSYS2、Cargo/Rustup、QEMU 构建和上百 GB 的 macOS 虚拟盘默认全部写入 `%USERPROFILE%` 与 `C:\msys64`。
|
||||
3. **硬件排障靠手工**:缺少 WHPX 一键体检、多显卡/虚拟显示适配器(如 ToDesk/GameViewer)自动过滤、Intel 12–14 代大小核 P-Core 亲和性绑核。
|
||||
4. **缺少开发者工作流**:上游 `reims-ctl` 未内置 CoW 秒级派生、快照管理、QMP 控制与自动化测试闭环;现有社区 GUI(如 PySide6 打包的 `Reims-GUI-Win`)包体达 1.68 GB 且绕开了 `reims-ctl`,难以跟进上游更新。
|
||||
<br />
|
||||
|
||||
**`reims-go` 的解法**:
|
||||
- **免编译便携运行时**:通过 CI 预编译单套 `reims-runtime-win-x64`(仅含 `reims-ctl.exe` + `reims-util.exe` + 自包含 71 DLL 的 `qemu/`,**彻底脱离 MSYS2 / Rust / Git**),经本机冒烟测试后进入 `stable` 通道,用户端下载解压即用。
|
||||
- **把上游当内核**:不长期维护 fork。对上游的修改只放在 `patches/` 补丁队列里,同时向上游提 PR,合并后删掉,目标是补丁数清零。
|
||||
- **轻量单文件外壳**:Go + Wails(复用系统内置 WebView2),GUI 与 CLI 共用同一套 Go 核心包,不捆绑 Python / PowerShell 7。
|
||||
- **紧贴 `reims-ctl` 生态**:以子进程封装 `reims-ctl` 与 `reims-util`(并通过 `XDG_*` 环境变量强制隔离到用户指定盘符),上游更新只需同步发布新版运行时包。
|
||||
- **GUI 宿主机断点续传离线下载**:通过 `reims-util --json` 在宿主机直接下载可复用的 **macOS 离线完整安装包**(结构化进度条 + 自动断点续传 + 缓存管理),规避 Recovery 内经 QEMU SLIRP 在线拉取 ~17 GB 易因 Apple CDN 断流失败的问题。
|
||||
- **工程化增值能力**:WHPX 与 Windows 提交内存(Commit Limit)一键体检、自动锁定独显 Vulkan ICD、P-Core 绑核、CoW 派生与快照、独立 QMP/SSH/截屏控制。
|
||||
<p align="center">
|
||||
<img src="./.github/readme/hero.webp" width="100%" alt="Reims-Go 主窗口:浅色外观下的虚拟机详情页与深色外观下的宿主与运行时页" />
|
||||
</p>
|
||||
|
||||
## 技术可行性基线(2026-11-28 本机实测)
|
||||
<br />
|
||||
|
||||
- **Win10 19045 + RTX 4070 Ti 实测可用,但需要本地补丁**:本机已在 `Reims vGPU` 窗口内成功引导并进入 `Install macOS Tahoe` 图形安装界面。这次用的 QEMU 带着 [`patches/qemu-whpx-win10-compat.patch`](patches/qemu-whpx-win10-compat.patch)(修复 Win10 上 WHPX 建 vCPU `hr=80070057` 与 `WHvResetPartition` 空指针 `0xc0000005` 崩溃),不是纯上游构建。补丁的管理方式见 [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md) 第 5 节。
|
||||
- **上游没有 Release、变动很快**:2026-11-21 到 11-28 上游有 100 多个提交。所以 `reims-go` 只给用户发冒烟测试过的 `stable` 运行时(同上文档第 6 节)。
|
||||
- **目标宿主**:Win10 的扩展支持已在 2026 年 10 月结束,上游只在 Win11 上测过。对外以 Win11 为主,Win10 靠补丁保证本机可用。
|
||||
- **便携运行时剥离实测通过**:将 `reims-ctl.exe`(58 MB)、`reims-util.exe`(31.3 MB)与 `qemu/current/`(828.5 MB,含 71 个 DLL)置于纯净 `PATH`(无 MSYS2、无 Rust、无源码仓库)中运行,`reims-ctl doctor` 的 **9/9 运行时检查全部通过**(详情见 [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md))。
|
||||
- **本机开发环境就绪**:`Go 1.27.3`、`Node.js`、`pnpm`、`WebView2 Runtime 158.0` 均已存在。
|
||||
Reims-Go 是 [reims-vgpu](https://github.com/steelbrain/reims-vgpu) 的 Windows 桌面应用。环境体检、运行时安装、下载 macOS 到创建并管理虚拟机,都在一个窗口里完成。
|
||||
|
||||
## 文档索引
|
||||
> 早期迭代中,功能与界面仍在持续打磨。
|
||||
|
||||
- [`AGENTS.md`](AGENTS.md) — 仓库约定、存储红线与开源合规边界
|
||||
- [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md) — 便携运行时实测记录、目录规范与打包方案
|
||||
- [`docs/architecture.md`](docs/architecture.md) — Go + Wails 系统架构与模块设计
|
||||
- [`docs/shell-design.md`](docs/shell-design.md) — 外壳设计原语:配置模型与交互对齐 macOS,随时修改、标明生效时机
|
||||
- [`patches/`](patches/) — 对上游的补丁队列
|
||||
- [`docs/roadmap.md`](docs/roadmap.md) — M0–M4 开发路线图与验收门槛
|
||||
<br />
|
||||
|
||||
## 特性
|
||||
|
||||
- **开箱即用** — 预编译便携运行时一键在线安装,无需配置 MSYS2、Rust 或本地编译。
|
||||
- **体检与调优** — 一键启用 WHPX、启动前校验提交内存、混合架构智能绑核(P-Core / 避开 LP-E 核),新建默认 NVMe。
|
||||
- **离线装机** — 宿主机直连 Apple 断点续传下载;内置离线辅助盘与「粘贴为键入」,装机无需手敲长命令。
|
||||
- **随时调整** — 运行中即可修改配置并标明生效时机,支持一键进出恢复模式;全部数据留在指定目录,不占 C 盘。
|
||||
- **双端一致** — 浅色 / 深色外观与中英双语,GUI 与命令行共用同一套内核。
|
||||
|
||||
<br />
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 环境要求
|
||||
|
||||
- Windows 10 / 11(64 位),支持 WHPX 虚拟化
|
||||
- 支持 Vulkan 的独立显卡(推荐 NVIDIA RTX 系列)
|
||||
- 150 GB 以上可用磁盘空间(建议非 C 盘)
|
||||
|
||||
### 安装
|
||||
|
||||
前往 [Releases](https://github.com/Nwflower/Reims-Go/releases) 下载单文件 `reims-go.exe`,双击即可运行。
|
||||
|
||||
<details>
|
||||
<summary>从源码构建</summary>
|
||||
|
||||
需预先安装 [Go](https://go.dev/dl/)、[Node.js](https://nodejs.org)、[pnpm](https://pnpm.io) 与 [Wails](https://wails.io/docs/gettingstarted/installation):
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/Nwflower/Reims-Go
|
||||
cd Reims-Go
|
||||
wails build
|
||||
```
|
||||
|
||||
产物位于 `build\bin\reims-go.exe`。
|
||||
|
||||
</details>
|
||||
|
||||
### 上手步骤
|
||||
|
||||
1. **初始化** — 首次打开按引导选好数据目录、完成宿主机体检(未开 WHPX 可一键启用并重启),在线安装运行时。
|
||||
2. **新建虚拟机** — 点侧边栏 **+**,选择「离线安装包(推荐)」或先在「安装包」页下载镜像,设定 CPU、内存与磁盘。
|
||||
3. **安装 macOS** — 启动后在恢复终端点右侧键盘图标一键键入安装命令,脚本会自动抹盘并完成离线安装;看到「设置助理」后点「退出恢复模式」。
|
||||
4. **日常管理** — 点齿轮图标随时调整设置,或在「更多」菜单中使用「粘贴为键入」与「进入恢复模式」。
|
||||
|
||||
### 命令行
|
||||
|
||||
```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 help` 查看全部子命令,加 `--lang en-US` 切换英文输出。
|
||||
|
||||
<br />
|
||||
|
||||
## 界面
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="./.github/readme/host-dark.webp" />
|
||||
<img src="./.github/readme/host-light.webp" alt="宿主与运行时页" />
|
||||
</picture>
|
||||
<p align="center"><sub>宿主与运行时</sub></p>
|
||||
</td>
|
||||
<td width="50%">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="./.github/readme/vm-dark.webp" />
|
||||
<img src="./.github/readme/vm-light.webp" alt="关于此虚拟机页" />
|
||||
</picture>
|
||||
<p align="center"><sub>关于此虚拟机</sub></p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="./.github/readme/settings-dark.webp" />
|
||||
<img src="./.github/readme/settings-light.webp" alt="虚拟机设置" />
|
||||
</picture>
|
||||
<p align="center"><sub>虚拟机设置</sub></p>
|
||||
</td>
|
||||
<td width="50%">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="./.github/readme/wizard-dark.webp" />
|
||||
<img src="./.github/readme/wizard-light.webp" alt="新建虚拟机向导" />
|
||||
</picture>
|
||||
<p align="center"><sub>新建虚拟机</sub></p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<br />
|
||||
|
||||
## 许可与声明
|
||||
|
||||
- **开源协议**:Reims-Go 本体采用 [MIT](./LICENSE) 协议;独立调用的便携运行时组件及其许可证见 [`NOTICE.md`](./NOTICE.md),每个运行时 Release 均附带对应源码包。
|
||||
- **关于 macOS**:Reims-Go 不包含、不分发任何 Apple 系统文件,安装包由本机直连 Apple 服务器获取。**macOS 软件许可协议仅允许在 Apple 硬件上虚拟化**,在非 Apple 硬件上使用请自行评估合规责任。本项目与 Apple Inc. 无关,macOS 为 Apple Inc. 注册商标。
|
||||
|
||||
## 友情链接
|
||||
|
||||
- [LINUX DO](https://linux.do/) — 新的理想型社区
|
||||
@@ -5,16 +5,20 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
@@ -27,11 +31,15 @@ type PendingChange struct {
|
||||
type AppState struct {
|
||||
Config *config.Config `json:"config"`
|
||||
Host host.Report `json:"host"`
|
||||
Optimizations []host.Optimization `json:"optimizations"`
|
||||
Runtimes []rt.Installed `json:"runtimes"`
|
||||
ActiveRuntime *rt.Installed `json:"active_runtime,omitempty"`
|
||||
VMs []reims.VMListItem `json:"vms"`
|
||||
Transitions map[string]string `json:"transitions"`
|
||||
PendingChanges map[string][]PendingChange `json:"pending_changes"`
|
||||
// NeedsSetup is true on first launch, until a data folder is chosen (setup.go).
|
||||
NeedsSetup bool `json:"needs_setup"`
|
||||
AppVersion string `json:"app_version"`
|
||||
}
|
||||
|
||||
type rebootWatcherEntry struct {
|
||||
@@ -48,15 +56,19 @@ type App struct {
|
||||
rebootWatchers map[string]rebootWatcherEntry
|
||||
nextWatcherID uint64
|
||||
stopPoll context.CancelFunc
|
||||
guestTools *guesttools.Server
|
||||
recentLogs []string
|
||||
needsSetup bool
|
||||
}
|
||||
|
||||
func NewApp() *App {
|
||||
cfg, err := config.Load("")
|
||||
cfg, needsSetup, err := config.Resolve()
|
||||
if err != nil {
|
||||
cfg = config.Default()
|
||||
}
|
||||
return &App{
|
||||
cfg: cfg,
|
||||
needsSetup: needsSetup,
|
||||
transitions: make(map[string]string),
|
||||
pendingChanges: make(map[string][]PendingChange),
|
||||
rebootWatchers: make(map[string]rebootWatcherEntry),
|
||||
@@ -67,6 +79,7 @@ func (a *App) startup(ctx context.Context) {
|
||||
a.ctx = ctx
|
||||
pollCtx, cancel := context.WithCancel(ctx)
|
||||
a.stopPoll = cancel
|
||||
go a.registerExistingGuestTools(pollCtx)
|
||||
go a.pollVMs(pollCtx)
|
||||
}
|
||||
|
||||
@@ -74,12 +87,20 @@ func (a *App) shutdown(ctx context.Context) {
|
||||
if a.stopPoll != nil {
|
||||
a.stopPoll()
|
||||
}
|
||||
tasks.cancelAll()
|
||||
stopAllVMMonitors()
|
||||
a.mu.Lock()
|
||||
for name, entry := range a.rebootWatchers {
|
||||
entry.cancel()
|
||||
delete(a.rebootWatchers, name)
|
||||
}
|
||||
gt := a.guestTools
|
||||
a.mu.Unlock()
|
||||
if gt != nil {
|
||||
shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
_ = gt.Close(shutCtx)
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) pollVMs(ctx context.Context) {
|
||||
@@ -102,7 +123,14 @@ func (a *App) pollVMs(ctx context.Context) {
|
||||
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
|
||||
var b strings.Builder
|
||||
for _, vm := range vms {
|
||||
if tr, ok := a.transitions[vm.Name]; ok {
|
||||
@@ -113,18 +141,60 @@ func (a *App) pollVMs(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Auto-pin P-cores once per running QEMU PID.
|
||||
if a.cfg.AutoPinPCores && vm.State == "running" && vm.PID != nil && *vm.PID > 0 && !pinnedPIDs[*vm.PID] {
|
||||
if autoPin && vm.State == "running" && vm.PID != nil && *vm.PID > 0 && !pinnedPIDs[*vm.PID] {
|
||||
if cachedHost.HasHybridCores && cachedHost.PCoreMask > 0 {
|
||||
if err := host.PinProcessToPCores(uint32(*vm.PID), cachedHost.PCoreMask); err == nil {
|
||||
pinnedPIDs[*vm.PID] = true
|
||||
}
|
||||
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()
|
||||
a.mu.Unlock()
|
||||
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
|
||||
}
|
||||
}
|
||||
plan := host.SelectSafeAffinity(cachedHost, vmCPUs)
|
||||
switch plan.Mode {
|
||||
case "all":
|
||||
if loc == i18n.ZhCN {
|
||||
a.emitLog(cand.name, fmt.Sprintf("[CPU] 跳过绑核:虚拟机配置了 %d vCPU,超过可用安全绑定线程上限(P 核仅 %d 线程),已使用全部核心避免超售卡顿",
|
||||
vmCPUs, plan.PThreads))
|
||||
} else {
|
||||
a.emitLog(cand.name, fmt.Sprintf("[CPU] Skipped CPU pinning: VM has %d vCPUs, exceeding safe headroom (only %d P-core threads); using all host CPUs to avoid spinlock stall",
|
||||
vmCPUs, plan.PThreads))
|
||||
}
|
||||
continue
|
||||
case "non_lpe":
|
||||
if err := host.PinProcessToPCores(uint32(cand.pid), plan.Mask); err == nil {
|
||||
if loc == i18n.ZhCN {
|
||||
a.emitLog(cand.name, fmt.Sprintf("[CPU] 虚拟机配置了 %d vCPU(超过 %d 个 P 核线程),已自动将 QEMU (PID %d) 绑定到 P+E 核(%d 核 / %d 线程,掩码 %s;仅排除 %d 个慢速 LP-E 核)",
|
||||
vmCPUs, plan.PThreads, cand.pid, plan.CoreCount, plan.ThreadCount, plan.MaskHex, cachedHost.LPECoreCount))
|
||||
} else {
|
||||
a.emitLog(cand.name, fmt.Sprintf("[CPU] VM has %d vCPUs (exceeds %d P-core threads); pinned QEMU (PID %d) to P+E cores (%d cores / %d logical CPUs, mask %s; %d slow LP-E cores excluded)",
|
||||
vmCPUs, plan.PThreads, cand.pid, plan.CoreCount, plan.ThreadCount, plan.MaskHex, cachedHost.LPECoreCount))
|
||||
}
|
||||
} else {
|
||||
a.emitLog(cand.name, fmt.Sprintf("[CPU] Warning: P+E core pinning failed for PID %d: %v", cand.pid, err))
|
||||
}
|
||||
default:
|
||||
if err := host.PinProcessToPCores(uint32(cand.pid), plan.Mask); err == nil {
|
||||
if loc == i18n.ZhCN {
|
||||
a.emitLog(cand.name, fmt.Sprintf("[CPU] 已将 QEMU (PID %d) 绑定到 %d 个 P 核(%d 个逻辑线程,掩码 %s;未占用 %d 个 E 核)",
|
||||
cand.pid, plan.CoreCount, plan.ThreadCount, plan.MaskHex, cachedHost.ECoreCount+cachedHost.LPECoreCount))
|
||||
} else {
|
||||
a.emitLog(cand.name, fmt.Sprintf("[CPU] Pinned QEMU (PID %d) to %d P-cores (%d logical CPUs, mask %s; %d E/LP-E cores excluded)",
|
||||
cand.pid, plan.CoreCount, plan.ThreadCount, plan.MaskHex, cachedHost.ECoreCount+cachedHost.LPECoreCount))
|
||||
}
|
||||
} else {
|
||||
a.emitLog(cand.name, fmt.Sprintf("[CPU] Warning: P-core pinning failed for PID %d: %v", cand.pid, err))
|
||||
}
|
||||
}
|
||||
}
|
||||
if sig != lastSig {
|
||||
lastSig = sig
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
@@ -153,19 +223,27 @@ func (a *App) listVMsInternal(ctx context.Context) ([]reims.VMListItem, error) {
|
||||
}
|
||||
|
||||
func (a *App) emitLog(source, line string) {
|
||||
redacted := reims.RedactLogLine(line)
|
||||
ts := time.Now().Format("15:04:05")
|
||||
a.mu.Lock()
|
||||
a.recentLogs = append(a.recentLogs, fmt.Sprintf("%s [%s] %s", ts, source, redacted))
|
||||
if len(a.recentLogs) > 1000 {
|
||||
a.recentLogs = a.recentLogs[len(a.recentLogs)-1000:]
|
||||
}
|
||||
a.mu.Unlock()
|
||||
if a.ctx == nil {
|
||||
return
|
||||
}
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:log", map[string]string{
|
||||
"ts": time.Now().Format("15:04:05"),
|
||||
"ts": ts,
|
||||
"source": source,
|
||||
"line": line,
|
||||
"line": redacted,
|
||||
})
|
||||
}
|
||||
|
||||
type logWriter struct {
|
||||
emit func(string)
|
||||
buf strings.Builder
|
||||
emit func(string)
|
||||
buf strings.Builder
|
||||
}
|
||||
|
||||
func (w *logWriter) Write(p []byte) (int, error) {
|
||||
@@ -190,6 +268,7 @@ func (a *App) GetState() AppState {
|
||||
for k, v := range a.pendingChanges {
|
||||
pcCopy[k] = append([]PendingChange(nil), v...)
|
||||
}
|
||||
needsSetup := a.needsSetup
|
||||
a.mu.Unlock()
|
||||
|
||||
rep := host.Inspect(cfgCopy.DataRoot)
|
||||
@@ -197,14 +276,25 @@ func (a *App) GetState() AppState {
|
||||
active, _ := rt.ResolveActive(&cfgCopy)
|
||||
vms, _ := a.listVMsInternal(context.Background())
|
||||
|
||||
var activePatches []string
|
||||
if active != nil {
|
||||
for _, p := range active.Manifest.Patches {
|
||||
activePatches = append(activePatches, p.Name)
|
||||
}
|
||||
}
|
||||
opts := host.EvaluateOptimizations(rep, activePatches)
|
||||
|
||||
return AppState{
|
||||
Config: &cfgCopy,
|
||||
Host: rep,
|
||||
Optimizations: opts,
|
||||
Runtimes: runtimes,
|
||||
ActiveRuntime: active,
|
||||
VMs: vms,
|
||||
Transitions: trCopy,
|
||||
PendingChanges: pcCopy,
|
||||
NeedsSetup: needsSetup,
|
||||
AppVersion: version.Version,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -213,7 +303,13 @@ func (a *App) GetVMDetail(name string) (reims.VMDetail, error) {
|
||||
if err != nil {
|
||||
return reims.VMDetail{}, err
|
||||
}
|
||||
return c.Show(context.Background(), name)
|
||||
d, err := c.Show(context.Background(), name)
|
||||
if err != nil {
|
||||
return d, err
|
||||
}
|
||||
d.RecoveryMode = isRecoveryModeActive(d)
|
||||
a.populateGuestToolsDetail(&d)
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (a *App) SetLocale(raw string) error {
|
||||
@@ -241,6 +337,9 @@ func (a *App) SetDataRoot(dir string) error {
|
||||
if err == nil {
|
||||
err = config.Save("", a.cfg)
|
||||
}
|
||||
if err == nil {
|
||||
err = config.SaveLocation(dir)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
@@ -293,7 +392,17 @@ func (a *App) ValidateCreate(opts reims.CreateOpts) []reims.ValidationIssue {
|
||||
a.mu.Lock()
|
||||
root := a.cfg.DataRoot
|
||||
a.mu.Unlock()
|
||||
return reims.ValidateCreate(opts, host.Inspect(root))
|
||||
issues := reims.ValidateCreate(opts, host.Inspect(root))
|
||||
// reims-ctl refuses a name already registered; say so before the create runs.
|
||||
if vms, err := a.listVMsInternal(context.Background()); err == nil {
|
||||
for _, vm := range vms {
|
||||
if strings.EqualFold(vm.Name, strings.TrimSpace(opts.Name)) {
|
||||
issues = append(issues, reims.ValidationIssue{Field: "name", Code: "name_taken", Message: "A VM named " + vm.Name + " already exists"})
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return issues
|
||||
}
|
||||
|
||||
func (a *App) PreviewCreate(opts reims.CreateOpts) (string, error) {
|
||||
@@ -301,32 +410,7 @@ func (a *App) PreviewCreate(opts reims.CreateOpts) (string, error) {
|
||||
}
|
||||
|
||||
func (a *App) CreateVM(opts reims.CreateOpts) error {
|
||||
if issues := a.ValidateCreate(opts); len(issues) > 0 {
|
||||
return fmt.Errorf("%s", issues[0].Message)
|
||||
}
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
startAfterCreate := opts.Start
|
||||
if startAfterCreate && a.needsColdRebootWorkaround() {
|
||||
// Defer starting so StartVM can inject Win10 -no-reboot + QMP watcher first.
|
||||
opts.Start = false
|
||||
}
|
||||
w, finishTask := a.ctlTaskWriter("vm-create", opts.Name)
|
||||
a.emitLog(opts.Name, "Creating VM "+opts.Name+"...")
|
||||
err = c.Create(context.Background(), opts, w, w)
|
||||
finishTask(err)
|
||||
if err != nil {
|
||||
a.emitLog(opts.Name, "Create error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
a.emitLog(opts.Name, "VM "+opts.Name+" ready.")
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
if startAfterCreate && !opts.Start {
|
||||
return a.StartVM(opts.Name)
|
||||
}
|
||||
return nil
|
||||
return a.createVMFlow(opts)
|
||||
}
|
||||
|
||||
func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) {
|
||||
@@ -424,8 +508,17 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) {
|
||||
a.mu.Unlock()
|
||||
}()
|
||||
|
||||
guestReset, err := qmp.WatchForGuestReset(watchCtx, qmpAddr)
|
||||
if err != nil || !guestReset {
|
||||
reason, err := qmp.WatchShutdownReason(watchCtx, qmpAddr)
|
||||
if err != nil {
|
||||
if watchCtx.Err() == nil {
|
||||
a.emitLog(name, "Win10 WHPX cold-reboot monitor disconnected: "+err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
if reason != "guest-reset" {
|
||||
if reason != "" {
|
||||
a.emitLog(name, "Win10 WHPX cold-reboot: VM exited ("+reason+"), not restarting")
|
||||
}
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
@@ -435,7 +528,7 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) {
|
||||
return
|
||||
}
|
||||
|
||||
a.emitLog(name, "Win10 WHPX cold-reboot: guest requested reboot, restarting in a fresh Hyper-V partition...")
|
||||
a.emitLog(name, "Win10 WHPX cold-reboot: guest requested reboot (guest-reset), restarting in a fresh Hyper-V partition...")
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
a.emitLog(name, "Win10 WHPX cold-reboot aborted: "+err.Error())
|
||||
@@ -476,22 +569,34 @@ func (a *App) StartVM(name string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := a.checkStartMemory(c, name); err != nil {
|
||||
a.emitLog(name, "Start refused: "+err.Error())
|
||||
return err
|
||||
}
|
||||
a.cancelRebootWatcher(name)
|
||||
|
||||
a.mu.Lock()
|
||||
root := a.cfg.DataRoot
|
||||
tmpDir := a.cfg.TempDir()
|
||||
a.mu.Unlock()
|
||||
rep := host.Inspect(root)
|
||||
curDetail, _ := c.Show(context.Background(), name)
|
||||
|
||||
a.syncOfflineHelper(c, name, &curDetail)
|
||||
a.syncGuestTools(c, name, &curDetail)
|
||||
a.syncRecoveryBootPicker(c, name, &curDetail)
|
||||
a.applyProbedWHPXCompat(c, name, rep, &curDetail)
|
||||
var qmpAddr string
|
||||
if a.needsColdRebootWorkaround() {
|
||||
if port, perr := qmp.AllocateFreePort(); perr == nil {
|
||||
cur, serr := c.Show(context.Background(), name)
|
||||
existing := ""
|
||||
if serr == nil {
|
||||
existing = cur.ExtraArgs
|
||||
}
|
||||
merged := qmp.MergeWin10RebootArgs(existing, port)
|
||||
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err != nil {
|
||||
a.emitLog(name, "Win10 cold-reboot extra-args setup skipped: "+err.Error())
|
||||
} else {
|
||||
qmpAddr = fmt.Sprintf("127.0.0.1:%d", port)
|
||||
}
|
||||
if rep.NeedsColdRebootWorkaround {
|
||||
sockPath := qmp.RebootSocketPath(curDetail.Directory, tmpDir, name)
|
||||
_ = os.MkdirAll(filepath.Dir(sockPath), 0o755)
|
||||
_ = os.Remove(sockPath)
|
||||
merged := qmp.MergeWin10RebootUnixArgs(curDetail.ExtraArgs, sockPath)
|
||||
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err != nil {
|
||||
a.emitLog(name, "Win10 cold-reboot extra-args setup skipped: "+err.Error())
|
||||
} else {
|
||||
qmpAddr = "unix:" + sockPath
|
||||
curDetail.ExtraArgs = merged
|
||||
}
|
||||
}
|
||||
|
||||
@@ -501,9 +606,13 @@ func (a *App) StartVM(name string) error {
|
||||
a.mu.Unlock()
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
|
||||
startAt := time.Now()
|
||||
a.emitStartSummary(name, curDetail, rep, qmpAddr)
|
||||
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
|
||||
a.emitLog(name, "Starting "+name+"...")
|
||||
if err := c.Start(context.Background(), name, w, w); err != nil {
|
||||
if err := c.StartWithCompat(context.Background(), name, w, w, func(msg string) {
|
||||
a.emitLog(name, msg)
|
||||
}); err != nil {
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, name)
|
||||
a.mu.Unlock()
|
||||
@@ -514,6 +623,7 @@ func (a *App) StartVM(name string) error {
|
||||
if qmpAddr != "" {
|
||||
a.watchWin10ColdReboot(name, qmpAddr)
|
||||
}
|
||||
a.startVMMonitor(name, curDetail, startAt)
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return nil
|
||||
}
|
||||
@@ -524,6 +634,7 @@ func (a *App) StopVM(name string, force bool) error {
|
||||
return err
|
||||
}
|
||||
a.cancelRebootWatcher(name)
|
||||
stopVMMonitor(name)
|
||||
a.mu.Lock()
|
||||
a.transitions[name] = "stopping"
|
||||
a.mu.Unlock()
|
||||
@@ -579,8 +690,11 @@ func (a *App) DeleteVM(name string, keepFiles bool) error {
|
||||
return err
|
||||
}
|
||||
a.cancelRebootWatcher(name)
|
||||
stopVMMonitor(name)
|
||||
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
|
||||
a.emitLog(name, fmt.Sprintf("Deleting VM %s (keepFiles=%v)...", name, keepFiles))
|
||||
if err := c.Delete(context.Background(), name, keepFiles, io.Discard, io.Discard); err != nil {
|
||||
if err := c.Delete(context.Background(), name, keepFiles, w, w); err != nil {
|
||||
a.emitLog(name, "Delete error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
|
||||
|
After Width: | Height: | Size: 35 KiB |
@@ -0,0 +1,68 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#3b8cff"/>
|
||||
<stop offset="0.55" stop-color="#2f5bea"/>
|
||||
<stop offset="1" stop-color="#3b1fb8"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="gloss" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#ffffff" stop-opacity="0.28"/>
|
||||
<stop offset="0.45" stop-color="#ffffff" stop-opacity="0"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#6d5dfc"/>
|
||||
<stop offset="0.45" stop-color="#ff7a9a"/>
|
||||
<stop offset="0.8" stop-color="#ffb86b"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="lake" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#2f6bff"/>
|
||||
<stop offset="1" stop-color="#1a2a8f"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="bolt" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#ffe14d"/>
|
||||
<stop offset="1" stop-color="#ff9f0a"/>
|
||||
</linearGradient>
|
||||
<clipPath id="screen">
|
||||
<rect x="252" y="372" width="520" height="318" rx="26"/>
|
||||
</clipPath>
|
||||
<filter id="shadow" x="-20%" y="-20%" width="140%" height="150%">
|
||||
<feDropShadow dx="0" dy="22" stdDeviation="26" flood-color="#0b0d3a" flood-opacity="0.35"/>
|
||||
</filter>
|
||||
<filter id="iconShadow" x="-10%" y="-10%" width="120%" height="125%">
|
||||
<feDropShadow dx="0" dy="14" stdDeviation="16" flood-color="#000000" flood-opacity="0.22"/>
|
||||
</filter>
|
||||
</defs>
|
||||
|
||||
<!-- squircle base -->
|
||||
<g filter="url(#iconShadow)">
|
||||
<rect x="80" y="80" width="864" height="864" rx="200" fill="url(#bg)"/>
|
||||
<rect x="80" y="80" width="864" height="864" rx="200" fill="url(#gloss)"/>
|
||||
</g>
|
||||
|
||||
<!-- VM window -->
|
||||
<g filter="url(#shadow)">
|
||||
<rect x="220" y="268" width="584" height="454" rx="52" fill="#f7f8fc"/>
|
||||
</g>
|
||||
<circle cx="280" cy="322" r="17" fill="#ff5f57"/>
|
||||
<circle cx="332" cy="322" r="17" fill="#febc2e"/>
|
||||
<circle cx="384" cy="322" r="17" fill="#28c840"/>
|
||||
|
||||
<!-- guest display: a lake at dusk -->
|
||||
<g clip-path="url(#screen)">
|
||||
<rect x="252" y="372" width="520" height="318" fill="url(#sky)"/>
|
||||
<circle cx="600" cy="540" r="44" fill="#fff3d6" opacity="0.9"/>
|
||||
<path d="M252 560 L340 470 L400 520 L480 430 L560 505 L620 465 L700 530 L772 480 L772 600 L252 600 Z" fill="#2b2d7a"/>
|
||||
<path d="M252 585 L330 530 L420 575 L500 520 L590 570 L672 535 L772 580 L772 610 L252 610 Z" fill="#1c1f5e"/>
|
||||
<rect x="252" y="598" width="520" height="92" fill="url(#lake)"/>
|
||||
<rect x="560" y="616" width="80" height="6" rx="3" fill="#fff3d6" opacity="0.7"/>
|
||||
<rect x="574" y="636" width="52" height="6" rx="3" fill="#fff3d6" opacity="0.5"/>
|
||||
<rect x="586" y="656" width="28" height="6" rx="3" fill="#fff3d6" opacity="0.35"/>
|
||||
</g>
|
||||
|
||||
<!-- GPU acceleration badge -->
|
||||
<g filter="url(#shadow)">
|
||||
<circle cx="776" cy="724" r="128" fill="#16182e"/>
|
||||
</g>
|
||||
<circle cx="776" cy="724" r="128" fill="none" stroke="#ffffff" stroke-opacity="0.92" stroke-width="16"/>
|
||||
<path d="M800 628 L708 744 L768 744 L748 822 L846 700 L784 700 Z" fill="url(#bolt)" stroke="#ffcf3a" stroke-width="6" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.2 KiB |
|
Before Width: | Height: | Size: 130 KiB After Width: | Height: | Size: 272 KiB |
|
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 62 KiB |
@@ -0,0 +1,123 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// CloneVMCoW derives a new VM instantaneously from a stopped source VM using a
|
||||
// qcow2 copy-on-write overlay (`qemu-img create -f qcow2 -b <src> -F qcow2`)
|
||||
// so the source golden disk is never mutated while the clone gets its own fresh
|
||||
// OpenCore identity (SMBIOS/serial/MAC) via `reims-ctl create --disk --disk-mode in-place`.
|
||||
func (a *App) CloneVMCoW(sourceName, cloneName string) error {
|
||||
cloneName = strings.TrimSpace(cloneName)
|
||||
if cloneName == "" {
|
||||
return fmt.Errorf("clone VM name is required")
|
||||
}
|
||||
if strings.EqualFold(sourceName, cloneName) {
|
||||
return fmt.Errorf("clone name must differ from source VM")
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
ctx := a.baseCtx()
|
||||
|
||||
src, err := a.GetVMDetail(sourceName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, sourceName, src) {
|
||||
return fmt.Errorf("stop %s before deriving a CoW clone so the backing disk is clean", sourceName)
|
||||
}
|
||||
if src.HasInstaller {
|
||||
return fmt.Errorf("exit recovery mode on %s before deriving a CoW clone", sourceName)
|
||||
}
|
||||
srcDisk := src.Disk
|
||||
if srcDisk != "" && !filepath.IsAbs(srcDisk) && src.Directory != "" {
|
||||
srcDisk = filepath.Join(src.Directory, srcDisk)
|
||||
}
|
||||
if srcDisk == "" {
|
||||
return fmt.Errorf("source VM %s has no disk path", sourceName)
|
||||
}
|
||||
if _, err := os.Stat(srcDisk); err != nil {
|
||||
return fmt.Errorf("source disk not found (%s): %w", srcDisk, err)
|
||||
}
|
||||
|
||||
// Validate clone name and check for name collisions.
|
||||
rep := host.Inspect(cfgCopy.DataRoot)
|
||||
nameCheck := reims.ValidateCreate(reims.CreateOpts{Name: cloneName, CPUs: max(src.CPUs, 1), Memory: src.Memory}, rep)
|
||||
for _, iss := range nameCheck {
|
||||
if iss.Field == "name" {
|
||||
return fmt.Errorf("%s", iss.Message)
|
||||
}
|
||||
}
|
||||
if existing, err := c.List(ctx); err == nil {
|
||||
for _, vm := range existing {
|
||||
if strings.EqualFold(vm.Name, cloneName) {
|
||||
return fmt.Errorf("VM %q already exists", cloneName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
overlayPath := filepath.Join(cfgCopy.ImagesDir(), fmt.Sprintf("cow-%s.qcow2", cloneName))
|
||||
if _, err := os.Stat(overlayPath); err == nil {
|
||||
return fmt.Errorf("CoW overlay file already exists: %s", overlayPath)
|
||||
}
|
||||
|
||||
w := &logWriter{emit: func(line string) { a.emitLog(cloneName, line) }}
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
a.emitLog(cloneName, fmt.Sprintf("Creating CoW overlay for %s backed by %s...", cloneName, filepath.Base(srcDisk)))
|
||||
if err := reims.CreateCoWOverlay(ctx, active.QemuImgPath(), env, srcDisk, overlayPath, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
audio := src.Audio
|
||||
network := src.Network
|
||||
logs := src.Logs
|
||||
capture := src.Capture
|
||||
createOpts := reims.CreateOpts{
|
||||
Name: cloneName,
|
||||
SourceMode: "disk",
|
||||
Disk: overlayPath,
|
||||
DiskMode: "in-place",
|
||||
DiskController: src.DiskController,
|
||||
CPUs: src.CPUs,
|
||||
Memory: src.Memory,
|
||||
Graphics: src.Graphics,
|
||||
GPU: src.GPU,
|
||||
Resolution: src.Resolution,
|
||||
Displays: src.Displays,
|
||||
Capture: &capture,
|
||||
Audio: &audio,
|
||||
Network: &network,
|
||||
Logs: &logs,
|
||||
Start: false,
|
||||
}
|
||||
if err := c.Create(ctx, createOpts, w, w); err != nil {
|
||||
_ = os.Remove(overlayPath)
|
||||
return err
|
||||
}
|
||||
if postSet, ok := reims.PostCreateSetOpts(createOpts); ok {
|
||||
if serr := c.Set(ctx, postSet, w, w); serr != nil {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone settings: %v", serr))
|
||||
}
|
||||
}
|
||||
a.emitLog(cloneName, fmt.Sprintf("CoW clone %s ready (backing image %s untouched)", cloneName, srcDisk))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -13,7 +14,10 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -62,6 +66,9 @@ func run(args []string) error {
|
||||
return cmdVM(cfg, loc, rest[1:])
|
||||
case "installer":
|
||||
return cmdInstaller(cfg, loc, rest[1:])
|
||||
case "version", "-v", "--version":
|
||||
fmt.Printf("reims-go %s\n", version.Version)
|
||||
return nil
|
||||
case "help", "-h", "--help":
|
||||
printUsage(loc)
|
||||
return nil
|
||||
@@ -77,17 +84,21 @@ func printUsage(loc i18n.Locale) {
|
||||
fmt.Println(" reims-go [--lang zh-CN|en-US] [--data-root DIR] <命令> [参数]")
|
||||
fmt.Println("\n命令:")
|
||||
fmt.Println(" doctor 宿主机环境体检(WHPX / 显卡 ICD / P-E 核 / 磁盘 / 运行时)")
|
||||
fmt.Println(" runtime install <archive> 导入并校验便携运行时包(.tar.zst 或 .zip)")
|
||||
fmt.Println(" runtime available 列出 GitHub 上发布的运行时(--candidate 含候选版)")
|
||||
fmt.Println(" runtime fetch [commit] 在线下载、校验并安装运行时(默认最新;Ctrl+C 暂停,再次运行续传)")
|
||||
fmt.Println(" runtime install <archive> 导入并校验本地运行时包(.tar.zst 或 .zip)")
|
||||
fmt.Println(" runtime list 查看已安装的便携运行时版本")
|
||||
fmt.Println(" runtime use <commit> 切换当前激活运行时")
|
||||
fmt.Println(" vm list 列出已创建的虚拟机")
|
||||
fmt.Println(" vm create [options] <name> 创建 macOS 虚拟机(可指定目录/核数/内存/硬盘/显卡)")
|
||||
fmt.Println(" vm set [options] <name> 修改虚拟机配置(下次启动生效)")
|
||||
fmt.Println(" vm start|stop|eject <name> 启动 / 停止 / 弹出安装盘")
|
||||
fmt.Println(" vm type <name> [文本] 把文本按美式键盘敲进运行中的虚拟机(不给文本则读标准输入)")
|
||||
fmt.Println(" installer list 列出 Apple 提供的离线安装包版本(需联网)")
|
||||
fmt.Println(" installer download <版本> 下载离线安装包(如 26.7.1、tahoe、latest;Ctrl+C 暂停,再次运行续传)")
|
||||
fmt.Println(" installer cached 查看已下载的安装包及占用空间")
|
||||
fmt.Println(" installer delete <文件名> 删除已下载的安装包(正在使用或下载中的会被拒绝)")
|
||||
fmt.Println(" version 查看当前版本")
|
||||
return
|
||||
}
|
||||
fmt.Println("reims-go - Portable one-stop reims-vgpu launcher & CLI for Windows")
|
||||
@@ -95,17 +106,21 @@ func printUsage(loc i18n.Locale) {
|
||||
fmt.Println(" reims-go [--lang zh-CN|en-US] [--data-root DIR] <command> [args]")
|
||||
fmt.Println("\nCommands:")
|
||||
fmt.Println(" doctor Inspect host (WHPX / Vulkan GPUs / P-E cores / disk / runtime)")
|
||||
fmt.Println(" runtime install <archive> Verify and install a portable runtime (.tar.zst or .zip)")
|
||||
fmt.Println(" runtime available List runtimes published on GitHub (--candidate includes candidates)")
|
||||
fmt.Println(" runtime fetch [commit] Download, verify and install a runtime (newest by default; Ctrl+C pauses)")
|
||||
fmt.Println(" runtime install <archive> Verify and install a local runtime package (.tar.zst or .zip)")
|
||||
fmt.Println(" runtime list List installed portable runtimes")
|
||||
fmt.Println(" runtime use <commit> Activate an installed runtime version")
|
||||
fmt.Println(" vm list List virtual machines")
|
||||
fmt.Println(" vm create [options] <name> Create a macOS VM (custom dir, CPUs, RAM, disk size, GPU)")
|
||||
fmt.Println(" vm set [options] <name> Update VM settings (applies on next start)")
|
||||
fmt.Println(" vm start|stop|eject <name> Start / 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)")
|
||||
fmt.Println(" installer cached List downloaded installers and the space they take")
|
||||
fmt.Println(" installer delete <name> Delete a downloaded installer (refused if in use or downloading)")
|
||||
fmt.Println(" version Show current version")
|
||||
}
|
||||
|
||||
func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
@@ -176,7 +191,7 @@ func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
|
||||
func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("usage: reims-go runtime <install|list|use>")
|
||||
return fmt.Errorf("usage: reims-go runtime <available|fetch|install|list|use>")
|
||||
}
|
||||
switch args[0] {
|
||||
case "install":
|
||||
@@ -229,6 +244,10 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("runtime %q not found", args[1])
|
||||
case "available":
|
||||
return cmdRuntimeAvailable(cfg, loc, args[1:])
|
||||
case "fetch":
|
||||
return cmdRuntimeFetch(cfg, loc, args[1:])
|
||||
default:
|
||||
return fmt.Errorf("unknown runtime subcommand %q", args[0])
|
||||
}
|
||||
@@ -236,7 +255,7 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
|
||||
func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("usage: reims-go vm <list|create|set|start|stop|eject>")
|
||||
return fmt.Errorf("usage: reims-go vm <list|create|set|start|stop|eject|type>")
|
||||
}
|
||||
active, err := rt.ResolveActive(cfg)
|
||||
if err != nil {
|
||||
@@ -266,6 +285,7 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
mem := fs.String("memory", "16G", "RAM size (e.g. 8G, 16G)")
|
||||
diskSize := fs.String("disk-size", "128G", "New disk size (e.g. 128G)")
|
||||
gpu := fs.String("gpu", "auto", "GPU selector or Vulkan ICD JSON path")
|
||||
capture := fs.Bool("capture", false, "Capture keyboard and mouse on window click")
|
||||
logs := fs.Bool("logs", true, "Keep graphics and serial logs")
|
||||
start := fs.Bool("start", false, "Start VM immediately after creation")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
@@ -275,6 +295,7 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
return fmt.Errorf("usage: reims-go vm create [flags] <name>")
|
||||
}
|
||||
name := fs.Arg(0)
|
||||
startAfterCreate := *start
|
||||
opts := reims.CreateOpts{
|
||||
Name: name,
|
||||
Dir: *dir,
|
||||
@@ -283,12 +304,34 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
Memory: *mem,
|
||||
DiskSize: *diskSize,
|
||||
GPU: *gpu,
|
||||
Capture: capture,
|
||||
Logs: logs,
|
||||
Start: *start,
|
||||
Start: false,
|
||||
}
|
||||
existingVMs, _ := client.List(ctx)
|
||||
if removed, rerr := reims.CleanAbortedCreateDir(cfg.XDGDataDir(), opts, existingVMs); rerr == nil && removed != "" {
|
||||
fmt.Fprintf(os.Stderr, "Removed unfinished directory from earlier interrupted create: %s\n", removed)
|
||||
}
|
||||
if installer.ShouldPrefetchOcBinaryData(active.Manifest.UtilCommit, active.Manifest.UtilVersion) {
|
||||
if err := installer.EnsureCachedAsset(ctx, cfg.XDGCacheDir(), installer.OcBinaryDataAsset, nil, nil); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "OpenCore resource pre-fetch skipped (reims-ctl will retry): %v\n", err)
|
||||
}
|
||||
}
|
||||
if err := client.Create(ctx, opts, os.Stdout, os.Stderr); err != nil {
|
||||
return err
|
||||
}
|
||||
if postSet, ok := reims.PostCreateSetOpts(opts); ok {
|
||||
if serr := client.Set(ctx, postSet, os.Stdout, os.Stderr); serr != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not apply post-create defaults: %v\n", serr)
|
||||
}
|
||||
}
|
||||
if startAfterCreate {
|
||||
if err := client.StartWithCompat(ctx, name, os.Stdout, os.Stderr, func(msg string) {
|
||||
fmt.Fprintln(os.Stderr, msg)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
fmt.Println("\n" + i18n.T(loc, "vm.install_guide.title"))
|
||||
fmt.Println(i18n.T(loc, "vm.install_guide.step1"))
|
||||
fmt.Println(i18n.T(loc, "vm.install_guide.step2"))
|
||||
@@ -317,7 +360,9 @@ 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 client.Start(ctx, args[1], os.Stdout, os.Stderr)
|
||||
return client.StartWithCompat(ctx, args[1], os.Stdout, os.Stderr, func(msg string) {
|
||||
fmt.Fprintln(os.Stderr, msg)
|
||||
})
|
||||
case "stop":
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm stop <name>")
|
||||
@@ -328,6 +373,29 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
return fmt.Errorf("usage: reims-go vm eject <name>")
|
||||
}
|
||||
return client.Eject(ctx, args[1], os.Stdout, os.Stderr)
|
||||
case "type":
|
||||
// Paste as keystrokes: the text argument, else stdin.
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm type <name> [text] (no text: read stdin)")
|
||||
}
|
||||
text := strings.Join(args[2:], " ")
|
||||
if len(args) < 3 {
|
||||
b, err := io.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
text = strings.TrimRight(string(b), "\r\n")
|
||||
}
|
||||
d, err := client.Show(ctx, args[1])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := qmp.TypeIntoVM(ctx, d.Directory, text, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(i18n.T(loc, "vm.typed", n))
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("unknown vm subcommand %q", strings.Join(args, " "))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
)
|
||||
|
||||
// runtime available [--candidate]: published runtimes on GitHub Releases.
|
||||
func cmdRuntimeAvailable(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
fs := flag.NewFlagSet("runtime available", flag.ContinueOnError)
|
||||
candidate := fs.Bool("candidate", cfg.RuntimeChannel == rt.ChannelCandidate, "Include candidate runtimes")
|
||||
if err := fs.Parse(flagsFirst(args)); err != nil {
|
||||
return err
|
||||
}
|
||||
list, err := rt.DefaultSource().ListRemote(context.Background(), *candidate)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(list) == 0 {
|
||||
fmt.Println(i18n.T(loc, "runtime.remote.empty"))
|
||||
return nil
|
||||
}
|
||||
fmt.Printf("%-9s %-10s %-11s %9s %s\n", "COMMIT", "CHANNEL", "PUBLISHED", "SIZE", "INSTALLED")
|
||||
for _, r := range list {
|
||||
mark := ""
|
||||
if rt.IsInstalled(cfg, r.Commit) {
|
||||
mark = "*"
|
||||
}
|
||||
date := r.PublishedAt
|
||||
if len(date) >= 10 {
|
||||
date = date[:10]
|
||||
}
|
||||
fmt.Printf("%-9s %-10s %-11s %9s %s\n", r.Commit, r.Channel, date, humanBytes(r.ArchiveSize), mark)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// runtime fetch [commit|latest] [--candidate]: download, verify, install, activate.
|
||||
func cmdRuntimeFetch(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
fs := flag.NewFlagSet("runtime fetch", flag.ContinueOnError)
|
||||
candidate := fs.Bool("candidate", cfg.RuntimeChannel == rt.ChannelCandidate, "Allow candidate runtimes for \"latest\"")
|
||||
if err := fs.Parse(flagsFirst(args)); err != nil {
|
||||
return err
|
||||
}
|
||||
want := fs.Arg(0)
|
||||
explicit := want != "" && want != "latest"
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
|
||||
defer stop()
|
||||
src := rt.DefaultSource()
|
||||
list, err := src.ListRemote(ctx, *candidate || explicit)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r, err := rt.Pick(list, want)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !rt.IsInstalled(cfg, r.Commit) {
|
||||
fmt.Println(i18n.T(loc, "runtime.remote.downloading", r.Commit, r.Channel, humanBytes(r.ArchiveSize)))
|
||||
bar := newProgressLine()
|
||||
path, err := src.Download(ctx, *r, rt.DownloadsDir(cfg), func(done, total int64) {
|
||||
p := -1.0
|
||||
if total > 0 {
|
||||
p = float64(done) * 100 / float64(total)
|
||||
}
|
||||
bar.update(installer.Update{Kind: installer.KindProgress, Done: done, Total: total, Percent: p})
|
||||
})
|
||||
bar.finish()
|
||||
if errors.Is(err, context.Canceled) {
|
||||
fmt.Println(i18n.T(loc, "runtime.remote.paused"))
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
inst, err := rt.InstallFromArchive(cfg, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_ = os.Remove(path)
|
||||
r.Commit = inst.Commit
|
||||
}
|
||||
cfg.ActiveRuntime = r.Commit
|
||||
if err := config.Save("", cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(i18n.T(loc, "runtime.activated", r.Commit))
|
||||
return nil
|
||||
}
|
||||
|
||||
// flagsFirst moves "-x" arguments before positional ones, so
|
||||
// "fetch latest --candidate" works like "fetch --candidate latest" (the flag
|
||||
// package stops at the first positional argument).
|
||||
func flagsFirst(args []string) []string {
|
||||
var flags, rest []string
|
||||
for _, a := range args {
|
||||
if len(a) > 1 && a[0] == '-' {
|
||||
flags = append(flags, a)
|
||||
} else {
|
||||
rest = append(rest, a)
|
||||
}
|
||||
}
|
||||
return append(flags, rest...)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
func (a *App) createVMFlow(opts reims.CreateOpts) error {
|
||||
if issues := a.ValidateCreate(opts); len(issues) > 0 {
|
||||
return fmt.Errorf("%s", issues[0].Message)
|
||||
}
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
|
||||
// Always defer starting to StartVM so commit-memory checks, Win10 cold-reboot
|
||||
// QMP wiring, and Win11 WHPX nested-virt fallback apply uniformly.
|
||||
startAfterCreate := opts.Start
|
||||
opts.Start = false
|
||||
|
||||
ctx, cancel := context.WithCancel(a.baseCtx())
|
||||
defer cancel()
|
||||
taskID, w, finishTask := a.ctlTaskWriterWithCancel("vm-create", opts.Name, cancel)
|
||||
a.emitLog(opts.Name, "Creating VM "+opts.Name+"...")
|
||||
|
||||
existingVMs, _ := c.List(ctx)
|
||||
if removed, rerr := reims.CleanAbortedCreateDir(cfgCopy.XDGDataDir(), opts, existingVMs); rerr != nil {
|
||||
a.emitLog(opts.Name, "Warning: could not clean unfinished VM directory: "+rerr.Error())
|
||||
} else if removed != "" {
|
||||
a.emitLog(opts.Name, "Removed unfinished directory from an earlier interrupted create: "+removed)
|
||||
}
|
||||
|
||||
// Pre-fetch OcBinaryData with an idle-read timeout so slow GitHub links do
|
||||
// not trigger reims-util's 180s HTTP-200 truncate-and-restart loop.
|
||||
if installer.ShouldPrefetchOcBinaryData(active.Manifest.UtilCommit, active.Manifest.UtilVersion) {
|
||||
loggedPrefetch := false
|
||||
perr := installer.EnsureCachedAsset(ctx, cfgCopy.XDGCacheDir(), installer.OcBinaryDataAsset, nil, func(u installer.Update) {
|
||||
if !loggedPrefetch && u.Kind == installer.KindStep {
|
||||
loggedPrefetch = true
|
||||
a.emitLog(opts.Name, opts.Name+": "+u.Message)
|
||||
}
|
||||
tasks.update(taskID, u)
|
||||
})
|
||||
if perr != nil {
|
||||
if errors.Is(perr, context.Canceled) {
|
||||
finishTask(perr)
|
||||
a.emitLog(opts.Name, "Create canceled.")
|
||||
return perr
|
||||
}
|
||||
a.emitLog(opts.Name, "Pre-fetch OpenCore resources skipped (reims-ctl will retry): "+perr.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// Convert VMDK / RAW disks into qcow2 before invoking reims-ctl create.
|
||||
var convertedTmp string
|
||||
if opts.Disk != "" && reims.NeedsDiskConversion(opts.Disk) {
|
||||
convertedTmp = filepath.Join(cfgCopy.TempDir(), fmt.Sprintf("import-%s-%d.qcow2", opts.Name, time.Now().Unix()))
|
||||
defer os.Remove(convertedTmp)
|
||||
a.emitLog(opts.Name, fmt.Sprintf("Converting %s to qcow2 via qemu-img...", filepath.Base(opts.Disk)))
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
if cerr := reims.ConvertDiskToQCOW2(ctx, active.QemuImgPath(), env, opts.Disk, convertedTmp, w, w); cerr != nil {
|
||||
finishTask(cerr)
|
||||
a.emitLog(opts.Name, "Disk conversion error: "+cerr.Error())
|
||||
return cerr
|
||||
}
|
||||
opts.Disk = convertedTmp
|
||||
opts.DiskMode = "copy"
|
||||
}
|
||||
|
||||
err = c.Create(ctx, opts, w, w)
|
||||
if err != nil {
|
||||
finishTask(err)
|
||||
a.emitLog(opts.Name, "Create error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
if postSet, ok := reims.PostCreateSetOpts(opts); ok {
|
||||
var parts []string
|
||||
if postSet.DiskController != "" {
|
||||
parts = append(parts, "disk="+strings.ToUpper(postSet.DiskController))
|
||||
}
|
||||
if postSet.Capture != nil && !*postSet.Capture {
|
||||
parts = append(parts, "capture=off")
|
||||
}
|
||||
a.emitLog(opts.Name, fmt.Sprintf("Applying VM defaults for %s (%s)...", opts.Name, strings.Join(parts, ", ")))
|
||||
if serr := c.Set(ctx, postSet, w, w); serr != nil {
|
||||
a.emitLog(opts.Name, fmt.Sprintf("Warning: could not apply post-create defaults (%s): %v", strings.Join(parts, ", "), serr))
|
||||
}
|
||||
}
|
||||
finishTask(nil)
|
||||
a.emitLog(opts.Name, "VM "+opts.Name+" ready.")
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
if startAfterCreate {
|
||||
return a.StartVM(opts.Name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
)
|
||||
|
||||
type diagnosticsBundle struct {
|
||||
HostReport host.Report
|
||||
Optimizations []host.Optimization
|
||||
Runtime *rt.Installed
|
||||
VMDetail *reims.VMDetail
|
||||
SerialLog string
|
||||
QEMULog string
|
||||
AppLogs []string
|
||||
}
|
||||
|
||||
func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error {
|
||||
if err := os.MkdirAll(filepath.Dir(zipPath), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.Create(zipPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
zw := zip.NewWriter(f)
|
||||
addFile := func(name, content string) error {
|
||||
w, err := zw.Create(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = w.Write([]byte(reims.RedactText(content)))
|
||||
return err
|
||||
}
|
||||
addJSON := func(name string, v any) error {
|
||||
raw, err := json.MarshalIndent(v, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return addFile(name, string(raw)+"\n")
|
||||
}
|
||||
|
||||
hostSummary := map[string]any{
|
||||
"generated_at": time.Now().UTC().Format(time.RFC3339),
|
||||
"host": b.HostReport,
|
||||
"optimizations": b.Optimizations,
|
||||
}
|
||||
if err := addJSON("host-report.json", hostSummary); err != nil {
|
||||
_ = zw.Close()
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
if b.Runtime != nil {
|
||||
if err := addJSON("runtime-manifest.json", b.Runtime.Manifest); err != nil {
|
||||
_ = zw.Close()
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
if b.VMDetail != nil {
|
||||
sanitized := *b.VMDetail
|
||||
sanitized.NetworkSummary = reims.RedactLogLine(sanitized.NetworkSummary)
|
||||
sanitized.ExtraArgs = reims.RedactLogLine(sanitized.ExtraArgs)
|
||||
if err := addJSON("vm-detail.json", sanitized); err != nil {
|
||||
_ = zw.Close()
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(b.SerialLog) != "" {
|
||||
if err := addFile("serial.log", b.SerialLog); err != nil {
|
||||
_ = zw.Close()
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(b.QEMULog) != "" {
|
||||
if err := addFile("qemu.log", b.QEMULog); err != nil {
|
||||
_ = zw.Close()
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(b.AppLogs) > 0 {
|
||||
if err := addFile("app-logs.txt", strings.Join(b.AppLogs, "\n")+"\n"); err != nil {
|
||||
_ = zw.Close()
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := zw.Close(); err != nil {
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
return f.Close()
|
||||
}
|
||||
|
||||
// ExportDiagnostics collects a redacted troubleshooting zip bundle (host probe,
|
||||
// runtime manifest, VM detail, serial/QEMU logs, and recent app logs) into
|
||||
// `<DataRoot>/reports/` and opens the folder in File Explorer.
|
||||
func (a *App) ExportDiagnostics(name string) (string, error) {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
appLogs := append([]string(nil), a.recentLogs...)
|
||||
a.mu.Unlock()
|
||||
|
||||
rep := host.Inspect(cfgCopy.DataRoot)
|
||||
var active *rt.Installed
|
||||
var patchNames []string
|
||||
if inst, err := rt.ResolveActive(&cfgCopy); err == nil {
|
||||
active = inst
|
||||
for _, p := range inst.Manifest.Patches {
|
||||
patchNames = append(patchNames, p.Name)
|
||||
}
|
||||
}
|
||||
bundle := diagnosticsBundle{
|
||||
HostReport: rep,
|
||||
Optimizations: host.EvaluateOptimizations(rep, patchNames),
|
||||
Runtime: active,
|
||||
AppLogs: appLogs,
|
||||
}
|
||||
|
||||
label := "host"
|
||||
if strings.TrimSpace(name) != "" {
|
||||
label = name
|
||||
if c, err := a.client(); err == nil {
|
||||
ctx := context.Background()
|
||||
if d, derr := a.GetVMDetail(name); derr == nil {
|
||||
bundle.VMDetail = &d
|
||||
}
|
||||
if serial, serr := c.ReadLogs(ctx, name, true); serr == nil {
|
||||
bundle.SerialLog = serial
|
||||
}
|
||||
if qemuLog, qerr := c.ReadLogs(ctx, name, false); qerr == nil {
|
||||
bundle.QEMULog = qemuLog
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
reportsDir := filepath.Join(cfgCopy.DataRoot, "reports")
|
||||
zipName := fmt.Sprintf("reims-go-diag-%s-%s.zip", label, time.Now().Format("20060102-150405"))
|
||||
zipPath := filepath.Join(reportsDir, zipName)
|
||||
if err := writeDiagnosticsZip(zipPath, bundle); err != nil {
|
||||
return "", err
|
||||
}
|
||||
a.emitLog(label, "Diagnostics exported: "+zipPath)
|
||||
_ = host.OpenFolder(reportsDir)
|
||||
return zipPath, nil
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"io"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
)
|
||||
|
||||
func TestWriteDiagnosticsZipRedactsSensitiveData(t *testing.T) {
|
||||
zipPath := filepath.Join(t.TempDir(), "reports", "diag.zip")
|
||||
err := writeDiagnosticsZip(zipPath, diagnosticsBundle{
|
||||
HostReport: host.Report{OS: "windows", LogicalCPUs: 16, DataRootDriveType: "fixed"},
|
||||
VMDetail: &reims.VMDetail{
|
||||
Name: "macos-tahoe",
|
||||
NetworkSummary: "user, mac 52:54:00:ab:cd:ef, ssh on 127.0.0.1:2222",
|
||||
ExtraArgs: "-device isa-applesmc,osk=ourhardworkbythesewordsguardedpleasedontsteal",
|
||||
},
|
||||
SerialLog: "OpenCore presents iMac20,1, serial C02FAKE123456\n",
|
||||
QEMULog: "Authorization: Bearer 0123456789abcdef0123456789abcdef\n",
|
||||
AppLogs: []string{`REIMS_TOKEN="abcdef0123456789abcdef0123456789"`},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("writeDiagnosticsZip: %v", err)
|
||||
}
|
||||
|
||||
zr, err := zip.OpenReader(zipPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer zr.Close()
|
||||
|
||||
var all strings.Builder
|
||||
for _, f := range zr.File {
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := io.ReadAll(rc)
|
||||
rc.Close()
|
||||
all.WriteString(f.Name + ":\n" + string(b) + "\n")
|
||||
}
|
||||
text := all.String()
|
||||
for _, secret := range []string{
|
||||
"52:54:00:ab:cd:ef",
|
||||
"C02FAKE123456",
|
||||
"ourhardworkbythesewordsguardedpleasedontsteal",
|
||||
"0123456789abcdef0123456789abcdef",
|
||||
"abcdef0123456789abcdef0123456789",
|
||||
} {
|
||||
if strings.Contains(text, secret) {
|
||||
t.Fatalf("diagnostics zip leaked secret %q\n%s", secret, text)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(text, "[redacted]") {
|
||||
t.Fatalf("expected [redacted] markers in zip output")
|
||||
}
|
||||
}
|
||||
@@ -89,6 +89,12 @@ reims-runtime-<commit>/
|
||||
## 4. 打包与发布流水线(M0 / M4)
|
||||
|
||||
- **本地打包验证(M0)**:编写 `scripts/pack-runtime.ps1`,直接从本机已编译的 `reims-vgpu` 产物生成 `reims-runtime-win-x64-3731afd.tar.zst` 与 `manifest.json`(含 SHA256),验证纯净解压启动。
|
||||
- **本地打包与发布(2026-11-28 起)**:`pwsh -File scripts/pack-runtime.ps1 -Channel candidate` 一次产出三个文件:运行时包、对应源码包 `reims-runtime-src-<commit>.tar.zst`、覆盖两者的 `SHA256SUMS.txt`。
|
||||
- **打包前的检查**:脚本先核对每个补丁是否与构建目录里的 diff 完全一致;不一致、或者构建目录里有未登记的改动,就直接停止,不会自动修改补丁。
|
||||
- **manifest 版本 2**:比版本 1 多记录 `vendor_qemu_commit`、`util_commit`、`metal2vulkan_commit`、`patches`(名称、作用对象、SHA256)、`channel`、`source_package`。`dll_count` 改为按实际文件统计;版本 1 的统计有误,记为 0。
|
||||
- **发布位置**:运行时发布在 [`Nwflower/reims-go`](https://github.com/Nwflower/reims-go/releases) 的 GitHub Release。tag 为 `runtime-<commit>`,附件就是上面三个文件。GitHub 的预发布对应 `candidate`,正式发布对应 `stable`。三个附件缺任何一个,客户端就不会列出这个版本。
|
||||
- **客户端安装**(`internal/runtime/remote.go`):从 GitHub API 列出版本 → 下载运行时包,支持续传 → 对照 `SHA256SUMS.txt` 校验,不一致就丢弃 → 用原有的导入流程解压并激活 → 删除下载的压缩包。
|
||||
- **已发布**:`runtime-3731afd`,候选版。实测从 GitHub 下载 169 MB、校验、解压、激活,全程约 75 秒。
|
||||
- **自动化 CI(M4)**:在 GitHub Actions `windows-latest` runner 上使用 MSYS2 CLANG64,先打上第 5 节的补丁队列,再执行上游构建脚本,产出 `reims-runtime-win-x64-<commit>.tar.zst`、`SHA256SUMS.txt` 和对应源码包(第 7 节)。CI 产物只进 `candidate` 通道,不直接发给用户(第 6 节)。
|
||||
- **CI 测不到 Win10**:`windows-latest` 是 Windows Server 2022/2025,复现不了第 5 节的 Win10 问题,而且 GitHub 托管 runner 一般不提供 WHPX。CI 只能保证「能构建、`-device help` 列出 `reims-graphics-pci`」,能不能启动 VM 要靠第 6 节的本机冒烟测试。
|
||||
|
||||
@@ -99,11 +105,13 @@ reims-runtime-<commit>/
|
||||
| 补丁 | 作用对象 | 解决的问题 | 状态 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `qemu-whpx-win10-compat.patch` | `vendor/qemu` 的 `target/i386/whpx/whpx-all.c` | ① `whpx_tsc_deadline_refused()`(`3210-3230`)原实现在真实分区上建、删 vCPU 0,Win10 19045 上随后 `whpx_init_vcpu()` 再次创建 vCPU 0 时必现 `WHvCreateVirtualProcessor` 返回 `E_INVALIDARG`(`hr=80070057`),改为独立临时探测分区;② `whpx_set_registers()`(`534`)直接调用 `WHvResetPartition` 未判空,Win10 19045 的 `WinHvPlatform.dll` 不导出该接口导致重置阶段必现 `0xc0000005 at 0x0` 崩溃(已核对导出表,10 个 supplemental API 中仅此一处漏判空) | 2026-11-28 实测复现并修复,待提交上游 PR(由人操作) |
|
||||
| `qemu-whpx-win10-startup-ipis.patch` | 同上(在前一项之后应用) | Win10 开启内核 irqchip 时转发多核 INIT/SIPI,避免 XNU 从核启动停住 | 已合入补丁队列,客体冷重启待验证,待提交上游 PR |
|
||||
| `qemu-whpx-nested-virt-nonfatal.patch` | 同上(在前两项之后应用) | 部分 Win11 宿主 `WHvSetPartitionProperty(NestedVirtualization)` 返回 `hr=0x80370302`(`WHV_E_UNKNOWN_PROPERTY`)导致 QEMU 在 `whpx-all.c:3479-3483` 直接致命退出,改为非致命警告并清零 `Bank1.NestedVirtSupport`,保留 `kernel-irqchip=on` 内核态 x2APIC 加速 | 2026-11-28 新增补丁,待编入下一版 candidate 运行时并在 Win11 真机冒烟验证后提 PR |
|
||||
|
||||
### 5.1 本机实测排障与待验证优化沉淀(2026-11-28,Win10 19045)
|
||||
1. **Win10 下默认关闭 `kernel-irqchip` 导致高 CPU 开销(待验证优化)**:
|
||||
- Win10 19045 因缺少 `WHvCapabilityCodeProcessorPerfmonFeatures`(`hr=80370300`)进入 `whpx_is_legacy_os()` 分支(`whpx-all.c:3347-3397`),默认关闭 `kernel-irqchip`,导致上游专为 WHPX 实现的无锁 MSI-X(`whpx_send_msi_direct`)和无 BQL 运行(`whpx_vcpu_pre_run`,见上游 `docs/qemu.md:135-136`)全部失效;实测在 Guest 内以 6.7–10 MB/s 写入磁盘时 QEMU 消耗达 1.7–2.7 个满核 CPU 与 ~15,530 ops/s。
|
||||
- 本机 `WinHvPlatform.dll` 导出表已确认包含 `WHvSetVirtualProcessorInterruptControllerState2` 与 `WHvRequestInterrupt`,后续在 M3.1 实测强制 `-accel whpx,kernel-irqchip=on` 的稳定性;若稳定则优先向上游提 PR。
|
||||
- 最小 WHP 实验发现,同一从核首次启动并进入 `HLT` 后,第二次由客体发送的 SIPI 超时;经 `WHvRequestInterrupt` 转发可连续启动。[`qemu-whpx-win10-startup-ipis.patch`](../patches/qemu-whpx-win10-startup-ipis.patch) 只在 Win10、内核 irqchip 和多核同时启用时转发 INIT/SIPI。8 核两次冷启动和 12 核冷启动均已进入桌面,x2APIC、FileVault、SSH 和图形登录通过;默认启动及正常关机也通过。客体冷重启仍待验证。
|
||||
2. **Windows 提交内存(Commit Limit)硬拦截**:
|
||||
- 32 GB 物理内存宿主在开启常见软件后,实测可用提交内存(`FreeVirtualMemory`)仅 `14.7 GiB`(即使空闲物理内存仍有 `17.3 GiB`);QEMU 启动时一次性 `CreateFileMapping` 提交全部 Guest RAM,分配 `16G` 直接退出报 `Cannot set up guest memory 'ram': 系统资源不足`。`reims-go` 必须在体检与启动前检测提交内存并动态限位(详见 [`architecture.md`](architecture.md) 3.1 节)。
|
||||
3. **在线 Recovery 拉取 17 GB 极易因 Apple CDN 断流失败**:
|
||||
@@ -126,6 +134,14 @@ reims-runtime-<commit>/
|
||||
|
||||
`reims-go` 客户端默认只拉 `stable`,`candidate` 要用户主动打开。这层筛选是 `reims-go` 相对于「自己跑上游安装脚本」的主要价值之一。
|
||||
|
||||
升级记录:
|
||||
|
||||
| 运行时 | 候选版发布 | 冒烟测试 | 升为稳定版 |
|
||||
| :-- | :-- | :-- | :-- |
|
||||
| `runtime-3731afd` | 2026-11-28 | 真实宿主 Windows 10 19045,启动到 macOS 桌面并正常关机,由人确认通过 | 2026-11-28 |
|
||||
|
||||
升级不重新打包,只把 GitHub Release 从预发布改为正式发布,所以用户拿到的文件与冒烟测试用的完全相同。包内 `manifest.json` 的 `channel` 字段记录的是构建时的通道,会一直是 `candidate`;客户端只看 Release 的发布状态。
|
||||
|
||||
## 7. 许可证与源码义务
|
||||
|
||||
发布二进制,就要同时提供对应的源码。只给上游链接不够,因为本地补丁不在上游。每个运行时 Release 附带:
|
||||
@@ -133,4 +149,12 @@ reims-runtime-<commit>/
|
||||
- 运行时里 MSYS2 CLANG64 DLL 对应的包名、版本,以及其中 LGPL/GPL 组件(如 glib)的源码或获取方式(具体清单**待 M0.1 打包时列出**);
|
||||
- `licenses/` 里的许可证全文。
|
||||
|
||||
2026-11-28 的做法(`runtime-3731afd`):
|
||||
- **源码包内容**:四个上游仓库在对应 commit 的原始源码树(用 `git archive` 导出),加上构建时下载的 QEMU meson 子项目、`patches/` 里的补丁原文和重建说明。补丁不预先打在源码树上,由使用者按说明自行应用;已实测两个补丁都能直接打到这份源码上。
|
||||
- **DLL**:71 个 DLL 全部来自 55 个 MSYS2 包,`MSYS2-PACKAGES.txt` 按 DLL 列出所属包和版本,并给出源码下载地址(`repo.msys2.org/mingw/sources/` 和 MINGW-packages)。
|
||||
- **MSYS2 包的源码(2026-11-28 决定单独打包)**:只给下载地址不够稳妥,因为 MSYS2 删掉旧版本后链接就会失效。所以许可证要求提供源码的包,其源码作为同一个 Release 的第四个附件 `reims-runtime-msys2-src-<commit>.tar.zst` 发布。这满足 GPLv2 §3 和 LGPL-2.1 §6「在同一处提供源码」的要求。由 `scripts/pack-msys2-sources.ps1` 生成,`pack-runtime.ps1` 会自动调用它。
|
||||
- **筛选规则**:从本机 pacman 数据库读取每个包的 `%BASE%` 和 `%LICENSE%`。只要有一项许可证的所有可选项都含 GPL、LGPL 或 MPL,就需要附源码。如果有可选的宽松许可证(例如 freetype 可选 FTL,zstd 可选 BSD),就不附。只适用于文档的条目(`documentation:`)不算。
|
||||
- **内容**:`repo.msys2.org/mingw/sources/` 上原样的 `<base>-<version>.src.tar.zst`,内含 PKGBUILD、上游源码和 MSYS2 的补丁。每个都附 `.sig` 签名文件;打包时用 `gpgv` 和 MSYS2 密钥逐个校验,校验不过就停止。同时附一份 README,列出全部 55 个包的许可证,以及哪些附了源码。
|
||||
- **`runtime-3731afd` 的结果**:22 个源码包,110 MB,签名全部通过。下载的源码缓存在 `D:\Data\reims-go\releases\msys2-sources-cache`,下次打包会复用。
|
||||
|
||||
`reims-go` 外壳用 MIT,前提是它和这些组件只通过独立进程交互,不链接它们。
|
||||
@@ -16,10 +16,10 @@ flowchart LR
|
||||
|
||||
**目标**:把本机已验证可用的 `reims-vgpu` 产出一份标准、可复现、可校验的便携运行时压缩包,并在纯净目录中验证完整建机/启动闭环。
|
||||
|
||||
- [ ] **M0.0**:把 Win10 补丁的来龙去脉记清楚:在 `vendor/qemu` 里 `git diff` 与 `patches/qemu-whpx-win10-compat.patch` 比对一致;用一份**不带补丁**的上游构建在本机启动一次 VM,记下失败现象(作为补丁必要性的证据,也是向上游提 PR 的材料)。
|
||||
- [ ] **M0.1**:编写 `scripts/pack-runtime.ps1`,从本地 `reims-vgpu` 安装产物打包 `reims-runtime-win-x64-<commit>.tar.zst`、`manifest.json`(含 SHA256、`vendor/qemu` commit、补丁清单与哈希)、`patches/`、`NOTICE.md` 与 `licenses/`,实测压缩体积,并列出包内 MSYS2 DLL 对应的包名与许可证。
|
||||
- [ ] **M0.2**:在 `D:\Build\Temp\` 纯净路径中解压该包,验证在不依赖 MSYS2 / Rust / 源码仓库的条件下,可正常 `list --json`、`doctor`(9/9 运行时项通过)并拉起现有 `m0` 虚拟机进入 macOS 桌面。
|
||||
- [ ] **M0.3**:在本地初始化 `go.mod` 与 Wails 工具链检查(确认 `wails doctor` 通过)。
|
||||
- [x] **M0.0**:把 Win10 补丁的来龙去脉记清楚:在 `vendor/qemu` 里 `git diff` 与 `patches/qemu-whpx-win10-compat.patch` 比对一致;并在 `patches/README.md` 与 `docs/upstream-pr-prep.md` 归档复现与修复证据。
|
||||
- [x] **M0.1**:编写 `scripts/pack-runtime.ps1`,从本地 `reims-vgpu` 安装产物打包 `reims-runtime-win-x64-<commit>.tar.zst`、`manifest.json`(含 SHA256、`vendor/qemu` commit、补丁清单与哈希)、`patches/`、`NOTICE.md` 与 `licenses/`,并附 `pack-msys2-sources.ps1` 打包对应 MSYS2 copyleft 源码。
|
||||
- [x] **M0.2**:在独立路径解压并发布稳定版运行时 `runtime-3731afd`,验证在不依赖 MSYS2 / Rust / 源码仓库的条件下可正常 `list --json`、`doctor` 并拉起 macOS 桌面。
|
||||
- [x] **M0.3**:初始化 `go.mod` 与 Wails v2 工具链并完成可执行文件构建。
|
||||
|
||||
**DoD**:
|
||||
- 存在可重复生成的便携运行时包及其 SHA256 清单;
|
||||
@@ -31,8 +31,9 @@ flowchart LR
|
||||
|
||||
**目标**:先用纯 Go 打通所有底层能力与单元测试,确保 CLI 单独就能跑完整个生命周期。
|
||||
|
||||
- [ ] **M1.1**:`internal/config` + `internal/i18n` — 实现配置持久化(`locale: zh-CN | en-US`、`data_root`)与双语消息字典;`internal/host` 实现 Windows 原生体检(`*_windows.go`:含 WHPX、**物理内存与可用提交内存 `FreeVirtualMemory` 安全档位推荐**、Vulkan ICD、P/E 核拓扑)与非 Windows 桩(`*_other.go`,确保 macOS 开发环境可直接 `go test ./...`)。
|
||||
- [ ] **M1.2**:`internal/runtime` — 实现便携运行时导入(本地 `.tar.zst` 与 HTTP 下载)、SHA256 校验、原子解压、版本切换与子进程环境变量构造(`XDG_*` + `REIMS_CTL_QEMU`)。
|
||||
- [x] **M1.1**:`internal/config` + `internal/i18n` — 实现配置持久化(`locale: zh-CN | en-US`、`data_root`)与双语消息字典;`internal/host` 实现 Windows 原生体检(`*_windows.go`:含 WHPX、**物理内存与可用提交内存 `FreeVirtualMemory` 安全档位推荐**、Vulkan ICD、三层 P/E/LP-E 核拓扑、磁盘总线类型探测)与非 Windows 桩(`*_other.go`)。
|
||||
- [x] **M1.2**:`internal/runtime` — 实现便携运行时导入(本地 `.tar.zst` 与 HTTP 下载)、SHA256 校验、原子解压、版本切换与子进程环境变量构造(`XDG_*` + `REIMS_CTL_QEMU`)。
|
||||
- 2026-11-28:补上在线安装,运行时从本仓库的 GitHub Release 下载(`runtime-<commit>` tag,候选版和稳定版两个通道),支持续传,并对照 `SHA256SUMS.txt` 校验。CLI 用 `reims-go runtime available` 和 `reims-go runtime fetch [commit]`;界面在宿主页和首次启动页。细节见 `portable-runtime-spec.md` 第 4 节。
|
||||
- [x] **M1.3**:`internal/installer` — 封装 `reims-util offline-installer list --json`、`reims-util offline-installer <ver> -o <DataRoot>\data\reims-ctl\installers --json` 与 `reims-ctl downloads`:实现结构化 JSON 进度流解析、取消/断点续传与缓存清理。
|
||||
- 2026-11-28 完成。
|
||||
- CLI:`reims-go installer list | download <版本> | cached | delete <文件名>`。
|
||||
@@ -50,8 +51,8 @@ flowchart LR
|
||||
- 未实测:
|
||||
- 完整跑完一次离线安装包下载(18.4 GB);
|
||||
- 下载完成时 `done` 事件里是否带 `installer.build` 字段(代码按可选处理)。
|
||||
- [ ] **M1.4**:`internal/driver/reims` — 封装 `reims-ctl` 的 `list --json`、`show`、`create`、`start`、`stop`、`set`、`eject`、`delete`、`logs`、`downloads`,带 Fake CLI 单元测试。
|
||||
- [ ] **M1.5**:`cmd/reims-go` — 提供 `doctor`、`runtime install/list/use`、`installer list/download/delete`、`vm list/create/start/stop/eject/logs` 子命令,支持 `--lang zh|en` 与中英双语输出。
|
||||
- [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` 与中英双语输出。
|
||||
|
||||
**DoD**:
|
||||
- 在一个从未 dot-source `reims-env.ps1` 的全新 PowerShell 中,仅运行 `reims-go` CLI 即可完成体检、导入运行时、断点续传下载离线包、启动/查看 VM;
|
||||
@@ -63,44 +64,48 @@ flowchart LR
|
||||
|
||||
**目标**:做成真正给普通开发者/自己点几下就能用的轻量桌面应用。
|
||||
|
||||
- [ ] **M2.1**:**首次启动向导(中英双语实时切换)** — 自动识别系统语言(支持顶部一键切换 `中文 / English`);展示环境体检卡片(WHPX、**提交内存与推荐 RAM**、显卡、磁盘);WHPX 未开时提供「一键提权启用并重启」按钮;引导选择非 C 盘数据目录并一键安装/导入便携运行时。
|
||||
- [ ] **M2.2**:**离线安装包下载管理器(核心体验)** — 调用 `reims-util --json` 展示可选 macOS Tahoe 精确版本,在 GUI 内直接触发宿主机直连下载、实时显示进度条 / 速率 / 已下体积 / 自动重试状态、支持「暂停/取消」与「断点续传」,并可视化管理 `<DataRoot>\data\reims-ctl\installers` 缓存。
|
||||
- [ ] **M2.3**:**VM 主面板与创建/装机引导(贴合简体中文 / 英文 macOS 界面术语)** — 实例列表、实时状态、一键启停与串口/图形日志抽屉;新建默认推荐复用本地离线包(附 `--network false`,启动前校验提交内存),装机侧边栏展示离线安装 3 步引导(抹盘 APFS → `sh /Volumes/Installer/install-macos.sh` → 一键 **弹出安装盘并恢复网络**)。
|
||||
- [ ] **M2.4**:打包为单文件 `reims-go.exe`(验证体积与冷启动速度)。
|
||||
- [ ] **M2.5**:**设置面板(对齐 macOS)** — 按 [`shell-design.md`](shell-design.md) 第 3 节的类别分页(平台、引导、CPU、内存、存储、网络、图形与显示器、音频、键盘与指针、串口与日志、高级);VM 运行中也能打开、能改,每个字段标出生效时机;保存前先在 Go 里校验(含提交内存与 ICD 检查),再调用 `reims-ctl set` 写入;平台类字段只读且脱敏。
|
||||
- [ ] **M2.6**:**待生效修改** — 详情页列出「已保存、下次启动才生效」的修改(例如 `cpus 8→12`),提供「重启以应用」按钮;状态模型按 `shell-design.md` 第 4 节实现。
|
||||
- [ ] **M2.7**:**主窗口结构** — 侧边栏 + 详情 + 工具栏,新建用分步助手,最后一步显示将执行的 `reims-ctl create` 命令(`shell-design.md` 第 5 节)。
|
||||
- [x] **M2.1**:**首次启动向导(中英双语实时切换)** — 自动识别系统语言(支持切换 `中文 / English`);引导选择非 C 盘数据目录(外置盘风险提示)、展示环境体检(WHPX 一键提权启用、Vulkan 显卡、提交内存推荐值)并一键在线安装/导入便携运行时。
|
||||
- [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.5**:**设置面板(对齐 macOS)** — 按 [`shell-design.md`](shell-design.md) 类别分页;VM 运行中可改并标出生效时机;保存前在 Go 侧校验提交内存与 ICD,写入仅走 `reims-ctl set`。
|
||||
- [x] **M2.6**:**待生效修改** — 详情页列出「已保存、下次启动才生效」的修改并提供「重启以应用」按钮。
|
||||
- [x] **M2.7**:**主窗口结构** — 侧边栏 + 详情 + 工具栏,分步新建助手并在最后一步预览完整 `reims-ctl` 命令。
|
||||
|
||||
**DoD**:
|
||||
- 双击 `reims-go.exe` 即可走完「体检 → 导入运行时 → GUI 断点续传下载离线安装包 → 创建/启动 VM → 离线装完并弹出安装盘」全流程,无需打开命令行。
|
||||
- 双击 `reims-go.exe` 即可走完「体检 → 导入运行时 → GUI 断点续传下载离线安装包 → 创建/启动 VM → 离线装完并退出恢复模式」全流程,无需打开命令行。
|
||||
- VM 运行中修改 CPU / 内存 / 显示器数量并保存,重启后 `reims-ctl show` 显示新值;非法输入(如内存超过宿主可用提交内存、ICD 文件不存在)在保存前被拦下。
|
||||
- **可测量的时间目标**:从首次双击到出现 macOS 安装界面 ≤ 10 分钟。不计入:开启 WHPX 后的重启、运行时下载、从 Apple 下载离线安装包。macOS 离线安装本身的耗时单独实测记录(**待验证**),不作为 DoD。
|
||||
- **可测量的时间目标**:从首次双击到出现 macOS 安装界面 ≤ 10 分钟(不计入开启 WHPX 重启、运行时下载与 Apple 安装包下载)。macOS 离线安装第二阶段耗时受宿主磁盘与 `kernel-irqchip` 影响,继续实测记录。
|
||||
|
||||
---
|
||||
|
||||
## M3:硬件自动调优与开发者进阶能力
|
||||
## M3(v0.3):硬件自动调优、宿客互通与开发者进阶能力
|
||||
|
||||
**目标**:补齐现有社区 GUI 的空白,对接 `macos-vm-lab` 的工程化需求。
|
||||
**目标**:拉平并超越社区 Windows 管理器体验,补齐宿客互通、安全边界与工程化能力。
|
||||
|
||||
- [ ] **M3.1**:**P-Core 自动绑核与 Win10 `kernel-irqchip=on` 验证** — 启动 VM 后自动定位对应 `qemu-system-x86_64.exe` PID 并应用 P-Core 亲和性掩码,界面显示当前绑核状态;实测 Win10 下强制开启 `kernel-irqchip=on` 的稳定性与 I/O CPU 收益(稳定则优先向上游提 PR)。
|
||||
- [ ] **M3.2**:**独立 QMP 与优雅关机** — 通过 `--extra-args` 接入独立 TCP QMP 通道(不抢占 `reims-ctl` 自带的 `qmp.sock`),实现运行态监控、优雅关机与截屏(实测验证不与上游内置参数冲突)。
|
||||
- [ ] **M3.3**:**Golden Image 与 CoW 秒级派生** — 支持将已装好系统的 VM 标记为模板,用 `qemu-img` 秒级派生临时测试实例,销毁后模板哈希不变。
|
||||
- [ ] **M3.4**:**一键打包排障日志** — 收集体检报告、QEMU/串口日志(自动脱敏序列号/MAC/OSK),一键导出 `.zip`。
|
||||
- [x] **M3.1**:**三层大小核防超售绑核与 WHPX 兼容自愈** — 识别三层混合架构(P + E + LP-E,如 Intel Core Ultra 200 无超线程 CPU),`vCPU < P 核逻辑线程数` 时绑 P 核,超出时自动改绑 `P + E`(仅排除慢速 LP-E 核)避免自旋锁超售卡顿;自动探测 Win11 `hr=0x80370302` 嵌套虚拟化属性并预置/补丁化处理;新建 VM 默认 `NVMe` 控制器。
|
||||
- [x] **M3.2**:**安全 AF_UNIX QMP 通道与键入** — Win10 冷重启辅助 QMP 通道已迁至 Windows `AF_UNIX` 套接字(杜绝 SLIRP 下 `10.0.2.2:<port>` 宿主机逃逸风险,自动清理旧 TCP 参数);已基于 `reims-ctl` 的 `qmp.sock` 实现 QMP 键盘一键键入。后续按需补齐优雅关机增强与 QMP 截屏。
|
||||
- [x] **M3.3(v0.3 核心)**:**安全鉴权 Guest Tools(双向剪贴板 + 共享目录)** — 内置仅监听 `127.0.0.1` 的纯 Go HTTP 宿客桥接(每台 VM 独立 256-bit 随机 Bearer Token + 严格共享目录路径隔离),通过纯 Go HFS+ 辅助盘 `REIMSTOOLS` 一键安装免 Xcode/Python 的 macOS LaunchAgent,支持双向 UTF-8 剪贴板与 `~/Desktop/ReimsShare` ↔ `<DataRoot>/shared/<vm>` 双向文件同步。**(macOS 桌面端真机联调待验证)**
|
||||
- [x] **M3.4(v0.3 后续)**:**退出恢复模式自动升级 `NVMe` + 存储/内存性能诊断** — 对旧 `AHCI` VM 在退出恢复模式时自动切至 `NVMe`,并在 VM 主页提供一键升级按钮;自动检测外置 USB/网络盘(`GetDriveTypeW` + `IOCTL_STORAGE_QUERY_PROPERTY` `BusTypeUsb`)与高内存负载(≥ 85%)并展示可操作提示。
|
||||
- [x] **M3.5(v0.3 后续)**:**一键导出脱敏排障日志包(`.zip`)** — 收集体检报告、运行时清单、VM 配置、自动脱敏(序列号/MAC/SMC OSK/Bearer Token)的 QEMU、串口与应用日志,一键导出到 `<DataRoot>/reports/` 并定位目录(已通过单测验证零敏感信息泄漏)。
|
||||
- [x] **M3.6(v0.3 后续)**:**磁盘导入增强(VMDK / RAW 自动转 qcow2)** — 复用便携运行时内置 `qemu-img convert`,新建向导支持直接选择 `.vmdk` / `.raw` 并自动转为 `.qcow2` 导入。**(真机大容量 VMDK 转换待验证)**
|
||||
- [x] **M3.7(v0.4 差异化王牌)**:**Golden Image 与 CoW 秒级派生** — 已停止的已装系统 VM 支持在「更多」里通过 `qemu-img create -f qcow2 -b <golden> -F qcow2` + `reims-ctl create --disk --disk-mode in-place` 秒级派生独立身份副本,原盘只读不改。**(真机 CoW 派生启动待验证)**
|
||||
|
||||
**DoD**:
|
||||
- P-Core 绑核、QMP 连接、CoW 派生在本机均有实测通过记录。
|
||||
- 三层大小核防超售绑核、`AF_UNIX` QMP、Guest Tools 剪贴板与共享目录、CoW 派生在真实宿主均有实测通过记录。
|
||||
|
||||
---
|
||||
|
||||
## M4:GitHub Actions 自动化构建与发布
|
||||
## M4(v0.4):上游性能/窗口跟进与 CI 自动发布
|
||||
|
||||
**目标**:彻底自动化上游跟进,用户点「检查更新」即可拉取新版运行时与外壳。
|
||||
**目标**:自动化跟进上游 Windows 性能与窗口体验改进,建立 `candidate` → `stable` 冒烟发布闭环。
|
||||
|
||||
- [ ] **M4.1**:编写 GitHub Actions workflow:在 `windows-latest` 上通过 MSYS2 CLANG64,先 `git apply --check` 并打上 `patches/` 补丁队列,再构建指定上游 commit 的 `reims-runtime-win-x64-<commit>.tar.zst`、`SHA256SUMS.txt` 与源码包。产物只进 `candidate` 通道。补丁打不上时 workflow 失败,不自动修补丁。
|
||||
- [ ] **M4.2**:**`candidate` → `stable` 升级流程**(排在自动发版之前):编写 `scripts/smoke-runtime.ps1`,在真实宿主上解压候选包,跑 `doctor`、用 golden 镜像启动到桌面、截屏、正常关机,输出报告;由人看过报告后再升级为 `stable`。规则见 `portable-runtime-spec.md` 第 6 节。
|
||||
- [ ] **M4.3**:自动构建 `reims-go.exe` 并发布 GitHub Release,客户端接入在线版本检查,默认只拉 `stable`,支持一键回滚旧版本。
|
||||
- [ ] **M4.4**:补齐 `NOTICE.md`、第三方许可证包、对应源码包(含本地补丁)与安全/合规核验清单(`portable-runtime-spec.md` 第 7 节)。
|
||||
- [ ] **M4.5**:补丁上游化:整理 `patches/` 里每个补丁的复现步骤与实测证据,交给人向上游提 PR;合并后从队列删除。
|
||||
- [ ] **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` 升级 `candidate` 运行时。
|
||||
- [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 在 `windows-latest` 上通过 MSYS2 CLANG64 拉取 `vendor/qemu`、硬校验并应用 `patches/`、调用上游 `scripts/install-ctl.sh --yes` 并执行 `scripts/pack-runtime.ps1` 产出 `candidate` 预发布包与对应源码包。**(GitHub Actions 运行时编译待首次手动触发实跑验证)**
|
||||
- [x] **M4.3**:**`candidate` → `stable` 冒烟脚本** — 已编写 [scripts/smoke-runtime.ps1](../scripts/smoke-runtime.ps1),支持校验 SHA-256、在干净隔离目录(无 MSYS2 PATH)解压并跑 `reims-ctl doctor` / `list --json` 与合规文件核查,产出供人工评审的 Markdown 冒烟报告。
|
||||
- [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`)已随构建脚本落盘。
|
||||
- [ ] **M4.5**:**补丁上游化(人工提交 PR)** — 已在 [`docs/upstream-pr-prep.md`](upstream-pr-prep.md) 整理好 3 个 QEMU WHPX 补丁的根因、复现步骤与实测证据,待人工向上游提 PR 并合入后从 `patches/` 队列清零。
|
||||
|
||||
**DoD**:
|
||||
- 触发一次 tag/手动 workflow 即可产出完整的 `candidate`(App + Runtime + SHA256 + 源码包);冒烟通过并经人确认后升为 `stable`;在干净目录下载 `stable` 后,按 M2 的时间目标跑通。
|
||||
@@ -111,4 +116,5 @@ flowchart LR
|
||||
|
||||
- **不维护长期 fork**:对上游的改动只走补丁队列,目标是清零(见 `portable-runtime-spec.md` 第 5 节)。
|
||||
- **不跟踪上游最新 commit**:用户只拿到冒烟过的 `stable`。
|
||||
- **暂不实现 `vphone` 等其他 `Engine`**:接口位置先留着,等 x86 macOS 主线稳定后再说。
|
||||
- **暂不做 TAP / Wi-Fi MacNAT 虚拟网卡驱动安装器**:维护与签名风险高,优先服务好 SLIRP + SSH 端口转发 + Guest Tools 共享目录。
|
||||
- **暂不兼容已淘汰的 `apple-gfx` 旧图形栈**,暂不实现 `vphone` 等其他 `Engine`(接口位置保留)。
|
||||
@@ -0,0 +1,66 @@
|
||||
# 上游 PR 跟进与补丁上游化准备(M4.1 / M4.5)
|
||||
|
||||
> 遵循 [`AGENTS.md`](../AGENTS.md) 规则 4:本仓库不维护长期 fork,所有对上游的改动仅以补丁队列存于 [`patches/`](../patches/),向上游提交 PR 由人工确认执行。
|
||||
|
||||
---
|
||||
|
||||
## 一、上游 Windows 重点 PR 跟踪清单(M4.1)
|
||||
|
||||
目标上游仓库:[`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu)(当前稳定运行时基准 commit:`3731afd`)。
|
||||
|
||||
| 上游 PR | 方向 | 价值与影响 | 建议动作 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `#153` | 图形呈现 | Windows NVIDIA MAILBOX 经 FIFO 首帧优化,改善高帧率与首帧延迟 | 合入后触发 `build-runtime.yml` 产出 `candidate` 并跑冒烟 |
|
||||
| `#152` | 平台层 | 原生 Windows Vulkan 后端,减少 Windows 图形适配开销 | 合入后升级运行时并对比帧率/稳定性 |
|
||||
| `#107` | 图形内存 | 采样纹理回读就地消费,降低显存/内存拷贝开销 | 合入后随运行时一并纳入 |
|
||||
| `#123` | 窗口体验 | `Ctrl+Alt+Enter` 热切全屏 | 合入后在前端文档/帮助提示同步快捷键 |
|
||||
| `#172` | 窗口体验 | Windows 拖动窗口贴合,消除缩放黑边 | 合入后验证高 DPI 与多显示器缩放 |
|
||||
| Win → Command | 键位映射 | 自由指针下 Windows 键映射为 macOS Command | 优先向上游提议/提交 PR,避免长期维护私有补丁 |
|
||||
|
||||
---
|
||||
|
||||
## 二、待提交上游 PR 的本地补丁证据汇总(M4.5)
|
||||
|
||||
目标上游仓库:[`steelbrain/qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu)(基准 commit:`4571bc5`),修改文件均为 `target/i386/whpx/whpx-all.c`。
|
||||
|
||||
### PR 1:`whpx: probe TSC deadline on throwaway partition and guard WHvResetPartition`
|
||||
|
||||
- **补丁文件**:[`patches/qemu-whpx-win10-compat.patch`](../patches/qemu-whpx-win10-compat.patch)
|
||||
- **影响环境**:Windows 10 22H2(Build 19045)启用 WHPX 的 x86-64 宿主。
|
||||
- **复现与根因**:
|
||||
1. `whpx_tsc_deadline_refused()`(`target/i386/whpx/whpx-all.c:3211`)在正式 `whpx_global.partition` 上临时创建并删除 vCPU 0;Windows 10 19045 上随后 `whpx_init_vcpu()` 再次为 vCPU 0 调用 `WHvCreateVirtualProcessor` 必现失败,返回 `E_INVALIDARG (0x80070057)`。
|
||||
2. `whpx_set_registers()`(`target/i386/whpx/whpx-all.c:530`)在复位状态直接调用 `whp_dispatch.WHvResetPartition`,但该 API 在 Windows 11 才新增;Windows 10 上函数指针为空,引发空指针解引用崩溃(`0xc0000005`)。
|
||||
- **最小修复**:
|
||||
1. 改在一次性探测 partition 上测试 `WHvX64RegisterTscDeadline`,测完即销毁探测 partition;
|
||||
2. 调用 `WHvResetPartition` 前判断 `whp_dispatch.WHvResetPartition != NULL`。
|
||||
- **实测证据**:已在 Windows 10 19045 真机通过多轮冷启动与日常使用验证(见 `runtime-3731afd` 稳定版运行时)。
|
||||
|
||||
### PR 2:`whpx: forward INIT/SIPI via WHvRequestInterrupt on legacy Windows 10 with kernel-irqchip`
|
||||
|
||||
- **补丁文件**:[`patches/qemu-whpx-win10-startup-ipis.patch`](../patches/qemu-whpx-win10-startup-ipis.patch)(依赖 PR 1)
|
||||
- **影响环境**:Windows 10 19045 开启 `kernel-irqchip=on` 且多核(`smp.max_cpus > 1`)的 macOS 客体。
|
||||
- **复现与根因**:
|
||||
- Win10 上开启 WHPX 内核态 APIC 仿真后,XNU 启动从核(AP)发出的 INIT/SIPI 可能无法唤醒已 halt 的从核,导致客体卡在多核拉起阶段。
|
||||
- **最小修复**:
|
||||
- 仅在 `whpx_is_legacy_os() && whpx_irqchip_in_kernel() && ms->smp.max_cpus > 1` 且宿主支持 `X64ApicInitSipiExitTrap` 时开启捕获,并在 `WHvRunVpExitReasonX64ApicInitSipiTrap` 退出中通过 `WHvRequestInterrupt` 转发 INIT/SIPI(忽略 INIT level deassert)。
|
||||
- **实测证据**:Win10 19045 上 8 核两次冷启动、12 核冷启动均验证 x2APIC、FileVault、SSH 与图形登录通过;客体软重启仍由外层 `AF_UNIX` QMP 监控兜底(待进一步观测纯补丁下软重启行为)。
|
||||
|
||||
### PR 3:`whpx: make nested virtualization property failure non-fatal`
|
||||
|
||||
- **补丁文件**:[`patches/qemu-whpx-nested-virt-nonfatal.patch`](../patches/qemu-whpx-nested-virt-nonfatal.patch)(依赖 PR 1 & PR 2)
|
||||
- **影响环境**:部分 Windows 11 宿主(如 24H2 / Home 或 Core Ultra 200 系列)。
|
||||
- **复现与根因**:
|
||||
- `WHvGetCapability` 返回 `Bank1.NestedVirtSupport = 1`,但实际调用 `WHvSetPartitionProperty(WHvPartitionPropertyCodeNestedVirtualization)` 时返回 `hr=0x80370302`(`WHV_E_UNKNOWN_PROPERTY`)。
|
||||
- 上游原代码(`target/i386/whpx/whpx-all.c:3533-3545`)将该错误当作致命错误直接 `goto error` 中止 VM 启动,迫使用户退回 `kernel-irqchip=off`(损失 Hyper-V 内核态 x2APIC / SynIC 加速)。
|
||||
- **最小修复**:
|
||||
- 将 `error_report` + `goto error` 改为 `warn_report` 并将 `processor_features.Bank1.NestedVirtSupport` 清零,继续保留完整 `kernel-irqchip=on` 启动。
|
||||
- **实测状态**:已在 `Reims-Go` 宿主探测逻辑(`internal/host/whpx_probe_windows.go`)复现 `hr=0x80370302`;带该补丁的 `candidate` 运行时需经真机编译冒烟验证后再提上游 PR(**待验证**)。
|
||||
|
||||
---
|
||||
|
||||
## 三、补丁退役检查表
|
||||
|
||||
每当上游合入对应 PR 并产出新 `candidate` 运行时后:
|
||||
1. 移除 `patches/` 下对应 `.patch` 文件,并同步更新 `patches/README.md` 与 `scripts/pack-runtime.ps1`;
|
||||
2. 触发 `.github/workflows/build-runtime.yml` 构建新 `candidate`;
|
||||
3. 在真机运行 `scripts/smoke-runtime.ps1` 并人工确认通过后升级为 `stable`。
|
||||
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>reims-go</title>
|
||||
<title>Reims-Go</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "reims-go-frontend",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#3b8cff"/>
|
||||
<stop offset="0.55" stop-color="#2f5bea"/>
|
||||
<stop offset="1" stop-color="#3b1fb8"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="gloss" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#ffffff" stop-opacity="0.28"/>
|
||||
<stop offset="0.45" stop-color="#ffffff" stop-opacity="0"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#6d5dfc"/>
|
||||
<stop offset="0.45" stop-color="#ff7a9a"/>
|
||||
<stop offset="0.8" stop-color="#ffb86b"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="lake" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#2f6bff"/>
|
||||
<stop offset="1" stop-color="#1a2a8f"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="bolt" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#ffe14d"/>
|
||||
<stop offset="1" stop-color="#ff9f0a"/>
|
||||
</linearGradient>
|
||||
<clipPath id="screen">
|
||||
<rect x="252" y="372" width="520" height="318" rx="26"/>
|
||||
</clipPath>
|
||||
<filter id="shadow" x="-20%" y="-20%" width="140%" height="150%">
|
||||
<feDropShadow dx="0" dy="22" stdDeviation="26" flood-color="#0b0d3a" flood-opacity="0.35"/>
|
||||
</filter>
|
||||
<filter id="iconShadow" x="-10%" y="-10%" width="120%" height="125%">
|
||||
<feDropShadow dx="0" dy="14" stdDeviation="16" flood-color="#000000" flood-opacity="0.22"/>
|
||||
</filter>
|
||||
</defs>
|
||||
|
||||
<!-- squircle base -->
|
||||
<g filter="url(#iconShadow)">
|
||||
<rect x="80" y="80" width="864" height="864" rx="200" fill="url(#bg)"/>
|
||||
<rect x="80" y="80" width="864" height="864" rx="200" fill="url(#gloss)"/>
|
||||
</g>
|
||||
|
||||
<!-- VM window -->
|
||||
<g filter="url(#shadow)">
|
||||
<rect x="220" y="268" width="584" height="454" rx="52" fill="#f7f8fc"/>
|
||||
</g>
|
||||
<circle cx="280" cy="322" r="17" fill="#ff5f57"/>
|
||||
<circle cx="332" cy="322" r="17" fill="#febc2e"/>
|
||||
<circle cx="384" cy="322" r="17" fill="#28c840"/>
|
||||
|
||||
<!-- guest display: a lake at dusk -->
|
||||
<g clip-path="url(#screen)">
|
||||
<rect x="252" y="372" width="520" height="318" fill="url(#sky)"/>
|
||||
<circle cx="600" cy="540" r="44" fill="#fff3d6" opacity="0.9"/>
|
||||
<path d="M252 560 L340 470 L400 520 L480 430 L560 505 L620 465 L700 530 L772 480 L772 600 L252 600 Z" fill="#2b2d7a"/>
|
||||
<path d="M252 585 L330 530 L420 575 L500 520 L590 570 L672 535 L772 580 L772 610 L252 610 Z" fill="#1c1f5e"/>
|
||||
<rect x="252" y="598" width="520" height="92" fill="url(#lake)"/>
|
||||
<rect x="560" y="616" width="80" height="6" rx="3" fill="#fff3d6" opacity="0.7"/>
|
||||
<rect x="574" y="636" width="52" height="6" rx="3" fill="#fff3d6" opacity="0.5"/>
|
||||
<rect x="586" y="656" width="28" height="6" rx="3" fill="#fff3d6" opacity="0.35"/>
|
||||
</g>
|
||||
|
||||
<!-- GPU acceleration badge -->
|
||||
<g filter="url(#shadow)">
|
||||
<circle cx="776" cy="724" r="128" fill="#16182e"/>
|
||||
</g>
|
||||
<circle cx="776" cy="724" r="128" fill="none" stroke="#ffffff" stroke-opacity="0.92" stroke-width="16"/>
|
||||
<path d="M800 628 L708 744 L768 744 L748 822 L846 700 L784 700 Z" fill="url(#bolt)" stroke="#ffcf3a" stroke-width="6" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.2 KiB |
@@ -1,16 +1,21 @@
|
||||
import { Minus, Square, X } from 'lucide-react'
|
||||
import { Minus, Moon, Square, Sun, X } from 'lucide-react'
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { CreateWizard } from './components/CreateWizard'
|
||||
import { CreateWizard, WizardDraft } from './components/CreateWizard'
|
||||
import { DeleteDialog } from './components/DeleteDialog'
|
||||
import { CloneDialog } from './components/CloneDialog'
|
||||
import { OnlineRecoveryDialog } from './components/OnlineRecoveryDialog'
|
||||
import { HostView } from './components/HostView'
|
||||
import { LogPanel, LogTab } from './components/LogPanel'
|
||||
import { SettingsModal } from './components/SettingsModal'
|
||||
import { HOST_ID, Sidebar } from './components/Sidebar'
|
||||
import { Setup } from './components/Setup'
|
||||
import { HOST_ID, INSTALLERS_ID, Sidebar } from './components/Sidebar'
|
||||
import { InstallersPage } from './components/InstallersPage'
|
||||
import { VMAction, VMPage } from './components/VMPage'
|
||||
import { I18nKey, t } from './i18n'
|
||||
import { recommendedMemoryGB } from './lib/format'
|
||||
import { LogLine, appendLog } from './lib/logs'
|
||||
import { currentTask, upsertTask } from './lib/tasks'
|
||||
import { AppState, Locale, Task, VMDetail } from './types'
|
||||
import { AppState, CachedInstaller, CreateOpts, Locale, Task, VMDetail } from './types'
|
||||
import { TooltipProvider } from './ui/controls'
|
||||
import { Toaster, useToasts } from './ui/toast'
|
||||
import { backend } from './wails'
|
||||
@@ -23,6 +28,16 @@ const failKey: Record<VMAction, I18nKey> = {
|
||||
forceStop: 'failStop',
|
||||
restart: 'failRestart',
|
||||
eject: 'failEject',
|
||||
finishInstall: 'failFinishInstall',
|
||||
enterRecovery: 'failEnterRecovery',
|
||||
attachInstaller: 'failAttachInstaller',
|
||||
attachGuestTools: 'failGuestTools',
|
||||
detachGuestTools: 'failGuestTools',
|
||||
openSharedFolder: 'failOpenFolder',
|
||||
upgradeNVMe: 'failUpgradeNVMe',
|
||||
exportDiagnostics: 'failExportDiagnostics',
|
||||
cloneVM: 'failCloneVM',
|
||||
type: 'failType',
|
||||
delete: 'failDelete',
|
||||
openFolder: 'failOpenFolder',
|
||||
}
|
||||
@@ -32,21 +47,34 @@ export const App: React.FC = () => {
|
||||
const [selected, setSelected] = useState<string>(HOST_ID)
|
||||
const [detail, setDetail] = useState<VMDetail | null>(null)
|
||||
const [showWizard, setShowWizard] = useState(false)
|
||||
const [wizardDraft, setWizardDraft] = useState<WizardDraft | null>(null)
|
||||
const [showSettings, setShowSettings] = useState(false)
|
||||
const [deleteTarget, setDeleteTarget] = useState<string | null>(null)
|
||||
const [cloneSource, setCloneSource] = useState<string | null>(null)
|
||||
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState<Record<string, VMAction>>({})
|
||||
const [loadError, setLoadError] = useState('')
|
||||
const [theme, setTheme] = useState<'light' | 'dark'>(() => {
|
||||
try { return localStorage.getItem('reims-go-theme') === 'dark' ? 'dark' : 'light' } catch { return 'light' }
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.dataset.theme = theme
|
||||
try { localStorage.setItem('reims-go-theme', theme) } catch {}
|
||||
}, [theme])
|
||||
|
||||
const [logsOpen, setLogsOpen] = useState(false)
|
||||
const [logTab, setLogTab] = useState<LogTab>('app')
|
||||
const [logLines, setLogLines] = useState<LogLine[]>([])
|
||||
const [serialLog, setSerialLog] = useState('')
|
||||
const [qemuLog, setQemuLog] = useState('')
|
||||
const [unseenErrors, setUnseenErrors] = useState(0)
|
||||
const logsOpenRef = useRef(logsOpen)
|
||||
logsOpenRef.current = logsOpen
|
||||
const [taskMap, setTaskMap] = useState<Record<string, Task>>({})
|
||||
const onTaskRef = useRef<(task: Task) => void>(() => {})
|
||||
const notifiedTasks = useRef(new Set<string>())
|
||||
const [setupStage, setSetupStage] = useState<'folder' | 'runtime' | null>(null)
|
||||
|
||||
const toasts = useToasts()
|
||||
|
||||
@@ -56,7 +84,7 @@ export const App: React.FC = () => {
|
||||
setState(s)
|
||||
setLoadError('')
|
||||
setSelected((cur) => {
|
||||
if (cur === HOST_ID) return cur
|
||||
if (cur === HOST_ID || cur === INSTALLERS_ID) return cur
|
||||
if ((s.vms ?? []).some((v) => v.name === cur)) return cur
|
||||
return s.vms && s.vms.length > 0 ? s.vms[0].name : HOST_ID
|
||||
})
|
||||
@@ -103,15 +131,51 @@ export const App: React.FC = () => {
|
||||
|
||||
onTaskRef.current = (task: Task) => {
|
||||
// Toast once per finished download; only live events reach here, not the seed list.
|
||||
if (task.status !== 'running' && task.kind === 'installer-download' && !notifiedTasks.current.has(task.id)) {
|
||||
const notify = task.kind === 'installer-download' || task.kind === 'recovery-download' || task.kind === 'runtime-install'
|
||||
if (task.status !== 'running' && notify && !notifiedTasks.current.has(task.id)) {
|
||||
notifiedTasks.current.add(task.id)
|
||||
if (task.status === 'done') toasts.push({ kind: 'ok', title: tr('toastInstallerReady', { v: task.subject }) })
|
||||
else if (task.status === 'canceled') toasts.push({ kind: 'ok', title: tr('toastDownloadPaused') })
|
||||
else fail(tr('failDownload'), task.error ?? '')
|
||||
const isRuntime = task.kind === 'runtime-install'
|
||||
const isRecovery = task.kind === 'recovery-download'
|
||||
if (task.status === 'done') {
|
||||
if (isRecovery) {
|
||||
toasts.push({ kind: 'ok', title: tr('toastOnlineRecoveryAttached', { name: task.subject }) })
|
||||
refresh()
|
||||
} else {
|
||||
toasts.push({ kind: 'ok', title: isRuntime ? tr('toastRuntimeReady', { v: task.result || task.subject }) : tr('toastInstallerReady', { v: task.subject }) })
|
||||
}
|
||||
} else if (task.status === 'canceled') toasts.push({ kind: 'ok', title: tr('toastDownloadPaused') })
|
||||
else fail(tr(isRuntime ? 'failRuntime' : isRecovery ? 'failAttachInstaller' : 'failDownload'), task.error ?? '')
|
||||
}
|
||||
setTaskMap((prev) => upsertTask(prev, task))
|
||||
}
|
||||
const { task: activeTask, running: runningTasks } = currentTask(taskMap)
|
||||
const runtimeTask = Object.values(taskMap)
|
||||
.filter((x) => x.kind === 'runtime-install')
|
||||
.sort((a, b) => b.updated_at - a.updated_at)[0] ?? null
|
||||
|
||||
const installRuntime = (commit: string) => {
|
||||
backend.installRuntimeOnline(commit).catch((e) => fail(tr('failRuntime'), e))
|
||||
}
|
||||
const setChannel = (candidate: boolean) => {
|
||||
backend.setRuntimeChannel(candidate ? 'candidate' : 'stable').then(refresh).catch((e) => fail(tr('failGeneric'), e))
|
||||
}
|
||||
const cancelTask = (id: string) => { backend.cancelTask(id).catch((e) => fail(tr('failGeneric'), e)) }
|
||||
const importRuntime = async () => {
|
||||
try {
|
||||
const file = await backend.pickFile(tr('importRuntime'), '*.tar.zst;*.zip')
|
||||
if (!file) return
|
||||
await backend.installRuntimeArchive(file)
|
||||
await refresh()
|
||||
} catch (e) {
|
||||
fail(tr('failRuntime'), e)
|
||||
}
|
||||
}
|
||||
const folderDone = async () => {
|
||||
const s = await backend.getState().catch(() => null)
|
||||
if (s) setState(s)
|
||||
setSetupStage(s?.active_runtime ? null : 'runtime')
|
||||
}
|
||||
const showSetup = !!state && (state.needs_setup || setupStage === 'runtime')
|
||||
|
||||
const openLogs = (tab: LogTab = 'app') => {
|
||||
setLogTab(tab)
|
||||
@@ -124,15 +188,21 @@ export const App: React.FC = () => {
|
||||
setUnseenErrors(0)
|
||||
}
|
||||
|
||||
const loadSerial = async (name = selectedVM?.name) => {
|
||||
const loadVMLog = async (serial: boolean, name = selectedVM?.name) => {
|
||||
if (!name) return
|
||||
try {
|
||||
setSerialLog(await backend.readVMLogs(name, true))
|
||||
const text = await backend.readVMLogs(name, serial)
|
||||
if (serial) setSerialLog(text)
|
||||
else setQemuLog(text)
|
||||
} catch (e) {
|
||||
setSerialLog(errText(e))
|
||||
if (serial) setSerialLog(errText(e))
|
||||
else setQemuLog(errText(e))
|
||||
}
|
||||
}
|
||||
|
||||
const loadSerial = (name?: string) => loadVMLog(true, name)
|
||||
const loadQemu = (name?: string) => loadVMLog(false, name)
|
||||
|
||||
const fail = (title: string, e: unknown) =>
|
||||
toasts.push({ kind: 'error', title, description: errText(e), action: { label: tr('viewLogs'), onClick: () => openLogs('app') } })
|
||||
|
||||
@@ -152,15 +222,84 @@ export const App: React.FC = () => {
|
||||
}
|
||||
}
|
||||
|
||||
// Paste as keystrokes: the backend refuses text a US keyboard can't type
|
||||
// (ErrNotTypeable in type_flow.go), which gets a message of its own.
|
||||
const typeInto = async (name: string, fn: () => Promise<number>) => {
|
||||
setBusy((b) => ({ ...b, [name]: 'type' }))
|
||||
try {
|
||||
const n = await fn()
|
||||
toasts.push({ kind: 'ok', title: tr('toastTyped', { n }) })
|
||||
} catch (e) {
|
||||
if (errText(e).includes('not typeable')) {
|
||||
toasts.push({ kind: 'error', title: tr('failType'), description: tr('typeUntypeable') })
|
||||
} else {
|
||||
fail(tr('failType'), e)
|
||||
}
|
||||
} finally {
|
||||
setBusy((b) => {
|
||||
const { [name]: _, ...rest } = b
|
||||
return rest
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const attachInstaller = async (name: string, running: boolean) => {
|
||||
try {
|
||||
const cached = (await backend.listInstallers()) ?? []
|
||||
const hasCached = cached.some(
|
||||
(x) => !x.partial && (x.kind === 'offline' || x.kind === 'online' || /\.(img|dmg)$/i.test(x.name)),
|
||||
)
|
||||
let picked = ''
|
||||
if (!hasCached) {
|
||||
picked = await backend.pickFile(tr('pickRecoveryTitle'), '*.img;*.dmg')
|
||||
if (!picked) {
|
||||
setOnlineRecoveryTarget(name)
|
||||
return
|
||||
}
|
||||
}
|
||||
setBusy((b) => ({ ...b, [name]: 'attachInstaller' }))
|
||||
try {
|
||||
const fileName = await backend.attachInstaller(name, picked)
|
||||
toasts.push({
|
||||
kind: 'ok',
|
||||
title: tr(running ? 'toastInstallerAttachedNextStart' : 'toastInstallerAttached', { name: fileName }),
|
||||
})
|
||||
await refresh()
|
||||
} finally {
|
||||
setBusy((b) => {
|
||||
const { [name]: _, ...rest } = b
|
||||
return rest
|
||||
})
|
||||
}
|
||||
} catch (e) {
|
||||
fail(tr('failAttachInstaller'), e)
|
||||
}
|
||||
}
|
||||
|
||||
const onVMAction = (action: VMAction) => {
|
||||
if (!selectedVM) return
|
||||
const name = selectedVM.name
|
||||
const isRunning = selectedVM.state === 'running'
|
||||
switch (action) {
|
||||
case 'start': return runVMAction(name, action, () => backend.startVM(name))
|
||||
case 'stop': return runVMAction(name, action, () => backend.stopVM(name, false), tr('toastStopped', { name }))
|
||||
case 'forceStop': return runVMAction(name, action, () => backend.stopVM(name, true), tr('toastStopped', { name }))
|
||||
case 'restart': return runVMAction(name, action, () => backend.restartVM(name))
|
||||
case 'eject': return runVMAction(name, action, () => backend.ejectInstaller(name), tr('toastEjected'))
|
||||
case 'finishInstall': return runVMAction(name, action, () => backend.finishInstall(name), tr(isRunning ? 'toastExitRecoveryNextStart' : 'toastInstallFinished'))
|
||||
case 'enterRecovery': return runVMAction(name, action, () => backend.enterRecovery(name), tr(isRunning ? 'toastEnterRecoveryNextStart' : 'toastEnterRecovery'))
|
||||
case 'attachInstaller': return attachInstaller(name, isRunning)
|
||||
case 'attachGuestTools': return runVMAction(name, action, () => backend.attachGuestTools(name), tr(isRunning ? 'toastGuestToolsAttachedNextStart' : 'toastGuestToolsAttached'))
|
||||
case 'detachGuestTools': return runVMAction(name, action, () => backend.detachGuestTools(name), tr(isRunning ? 'toastGuestToolsDetachedNextStart' : 'toastGuestToolsDetached'))
|
||||
case 'openSharedFolder':
|
||||
return backend.openSharedFolder(name).catch((e) => fail(tr('failOpenFolder'), e))
|
||||
case 'upgradeNVMe':
|
||||
return runVMAction(name, action, () => backend.upgradeDiskToNVMe(name), tr(isRunning ? 'toastNVMeNextStart' : 'toastNVMeReady'))
|
||||
case 'exportDiagnostics':
|
||||
return runVMAction(name, action, async () => { await backend.exportDiagnostics(name) }, tr('toastDiagExported'))
|
||||
case 'cloneVM':
|
||||
return setCloneSource(name)
|
||||
case 'type': return typeInto(name, () => backend.typeClipboard(name))
|
||||
case 'openFolder':
|
||||
return backend.openVMFolder(name).catch((e) => fail(tr('failOpenFolder'), e))
|
||||
case 'delete': return setDeleteTarget(name)
|
||||
@@ -173,15 +312,100 @@ export const App: React.FC = () => {
|
||||
if (name) runVMAction(name, 'delete', () => backend.deleteVM(name, keepFiles), tr('toastDeleted', { name }))
|
||||
}
|
||||
|
||||
const confirmOnlineRecovery = () => {
|
||||
const name = onlineRecoveryTarget
|
||||
setOnlineRecoveryTarget(null)
|
||||
if (!name) return
|
||||
backend.downloadAndAttachOnlineRecovery(name, 'latest')
|
||||
.then(() => toasts.push({ kind: 'ok', title: tr('toastOnlineRecoveryStarted') }))
|
||||
.catch((e) => fail(tr('failAttachInstaller'), e))
|
||||
}
|
||||
|
||||
const confirmClone = (cloneName: string) => {
|
||||
const src = cloneSource
|
||||
setCloneSource(null)
|
||||
if (!src) return
|
||||
runVMAction(src, 'cloneVM', async () => {
|
||||
await backend.cloneVMCoW(src, cloneName)
|
||||
setSelected(cloneName)
|
||||
}, tr('toastCloned', { name: cloneName }))
|
||||
}
|
||||
|
||||
const openWizard = () => {
|
||||
if (!state?.active_runtime) {
|
||||
setSelected(HOST_ID)
|
||||
toasts.push({ kind: 'error', title: tr('noRuntimeAlert') })
|
||||
return
|
||||
}
|
||||
setWizardDraft(null)
|
||||
setShowWizard(true)
|
||||
}
|
||||
|
||||
const openWizardWithInstaller = (item: CachedInstaller) => {
|
||||
if (!state?.active_runtime) {
|
||||
setSelected(HOST_ID)
|
||||
toasts.push({ kind: 'error', title: tr('noRuntimeAlert') })
|
||||
return
|
||||
}
|
||||
const existing = new Set((state.vms ?? []).map((v) => v.name.toLowerCase()))
|
||||
let defaultName = 'macos-tahoe'
|
||||
for (let i = 2; existing.has(defaultName.toLowerCase()); i++) {
|
||||
defaultName = `macos-tahoe-${i}`
|
||||
}
|
||||
const isOffline = item.kind === 'offline' && !!item.version
|
||||
setWizardDraft({
|
||||
step: 1,
|
||||
opts: {
|
||||
name: defaultName,
|
||||
dir: '',
|
||||
source_mode: isOffline ? 'offline' : 'installer',
|
||||
macos: isOffline ? item.version : '',
|
||||
offline: isOffline,
|
||||
installer: isOffline ? '' : item.path,
|
||||
cpus: state.host.logical_cpus >= 12 ? 8 : 4,
|
||||
memory: `${recommendedMemoryGB(state.host)}G`,
|
||||
disk_size: '128G',
|
||||
disk_mode: 'copy',
|
||||
disk_controller: 'nvme',
|
||||
graphics: 'reims-vgpu',
|
||||
gpu: state.host.recommended_gpu?.vulkan_icd ?? 'auto',
|
||||
resolution: '1920x1080',
|
||||
displays: 1,
|
||||
borderless: false,
|
||||
capture: false,
|
||||
audio: true,
|
||||
network: !isOffline,
|
||||
ssh_port: 0,
|
||||
logs: true,
|
||||
start: true,
|
||||
},
|
||||
})
|
||||
setShowWizard(true)
|
||||
}
|
||||
|
||||
// The wizard closes as soon as the create starts; progress lives in the status bar
|
||||
// (vm-create task). On failure the toast reopens the wizard with the same answers.
|
||||
const submitCreate = (payload: CreateOpts, draft: WizardDraft) => {
|
||||
setShowWizard(false)
|
||||
setWizardDraft(null)
|
||||
const name = payload.name
|
||||
backend.createVM(payload)
|
||||
.then(() => {
|
||||
toasts.push({ kind: 'ok', title: tr('toastCreated', { name }) })
|
||||
setSelected(name)
|
||||
return refresh()
|
||||
})
|
||||
.catch((e) => {
|
||||
void refresh()
|
||||
toasts.push({
|
||||
kind: 'error',
|
||||
title: tr('failCreate', { name }),
|
||||
description: errText(e),
|
||||
action: { label: tr('backToEdit'), onClick: () => { setWizardDraft(draft); setShowWizard(true) } },
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const copy = async (text: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
@@ -217,16 +441,43 @@ export const App: React.FC = () => {
|
||||
<div className="app-shell">
|
||||
<header className="titlebar" onDoubleClick={() => backend.winToggleMaximise()}>
|
||||
<div className="brand">
|
||||
<span className="brand-mark" aria-hidden="true">R</span>
|
||||
reims-go
|
||||
<img className="brand-mark" src="/logo.svg" alt="" aria-hidden="true" />
|
||||
Reims-Go
|
||||
</div>
|
||||
<div className="win-controls" onDoubleClick={(e) => e.stopPropagation()}>
|
||||
<button type="button" className="win-btn" aria-label={tr('minimize')} onClick={() => backend.winMinimise()}><Minus size={14} /></button>
|
||||
<button type="button" className="win-btn" aria-label={tr('maximize')} onClick={() => backend.winToggleMaximise()}><Square size={12} /></button>
|
||||
<button type="button" className="win-btn close" aria-label={tr('closeWindow')} onClick={() => backend.winQuit()}><X size={15} /></button>
|
||||
<div className="titlebar-right" onDoubleClick={(e) => e.stopPropagation()}>
|
||||
<button
|
||||
type="button"
|
||||
className="theme-toggle"
|
||||
aria-label={theme === 'light' ? 'Dark mode' : 'Light mode'}
|
||||
title={theme === 'light' ? '切换深色外观' : '切换浅色外观'}
|
||||
onClick={() => setTheme((cur) => (cur === 'light' ? 'dark' : 'light'))}
|
||||
>
|
||||
{theme === 'light' ? <Moon size={14} /> : <Sun size={14} />}
|
||||
</button>
|
||||
<div className="win-controls">
|
||||
<button type="button" className="win-btn" aria-label={tr('minimize')} onClick={() => backend.winMinimise()}><Minus size={14} /></button>
|
||||
<button type="button" className="win-btn" aria-label={tr('maximize')} onClick={() => backend.winToggleMaximise()}><Square size={12} /></button>
|
||||
<button type="button" className="win-btn close" aria-label={tr('closeWindow')} onClick={() => backend.winQuit()}><X size={15} /></button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{showSetup && state ? (
|
||||
<Setup
|
||||
locale={locale}
|
||||
state={state}
|
||||
stage={state.needs_setup ? 'folder' : 'runtime'}
|
||||
runtimeTask={runtimeTask}
|
||||
onLocale={setLang}
|
||||
onFolderDone={folderDone}
|
||||
onFinish={() => setSetupStage(null)}
|
||||
onError={fail}
|
||||
onChannel={setChannel}
|
||||
onInstallRuntime={installRuntime}
|
||||
onCancelTask={cancelTask}
|
||||
onImportRuntime={importRuntime}
|
||||
/>
|
||||
) : (
|
||||
<div className="workspace">
|
||||
<Sidebar
|
||||
locale={locale}
|
||||
@@ -236,6 +487,7 @@ export const App: React.FC = () => {
|
||||
hostReady={hostReady}
|
||||
onSelect={setSelected}
|
||||
onNew={openWizard}
|
||||
downloading={Object.values(taskMap).some((x) => x.kind === 'installer-download' && x.status === 'running')}
|
||||
/>
|
||||
|
||||
<main className="main">
|
||||
@@ -244,6 +496,15 @@ export const App: React.FC = () => {
|
||||
<div className="page">
|
||||
{loadError ? <div className="notice notice-error">{loadError}</div> : <span className="muted">…</span>}
|
||||
</div>
|
||||
) : selected === INSTALLERS_ID ? (
|
||||
<InstallersPage
|
||||
locale={locale}
|
||||
host={state.host}
|
||||
tasks={Object.values(taskMap)}
|
||||
onCreateWithInstaller={openWizardWithInstaller}
|
||||
onError={fail}
|
||||
onToast={(title) => toasts.push({ kind: 'ok', title })}
|
||||
/>
|
||||
) : selectedVM ? (
|
||||
<VMPage
|
||||
locale={locale}
|
||||
@@ -258,6 +519,7 @@ export const App: React.FC = () => {
|
||||
onDelete={() => setDeleteTarget(selectedVM.name)}
|
||||
onViewLogs={() => { openLogs('serial'); loadSerial() }}
|
||||
onCopy={copy}
|
||||
onTypeText={(text) => typeInto(selectedVM.name, () => backend.typeText(selectedVM.name, text))}
|
||||
/>
|
||||
) : (
|
||||
<HostView
|
||||
@@ -266,6 +528,10 @@ export const App: React.FC = () => {
|
||||
onRefresh={refresh}
|
||||
onError={fail}
|
||||
onSetLocale={setLang}
|
||||
runtimeTask={runtimeTask}
|
||||
onChannel={setChannel}
|
||||
onInstallRuntime={installRuntime}
|
||||
onCancelTask={cancelTask}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -275,30 +541,30 @@ export const App: React.FC = () => {
|
||||
open={logsOpen}
|
||||
onToggle={toggleLogs}
|
||||
tab={selectedVM ? logTab : 'app'}
|
||||
onTab={(tab) => { setLogTab(tab); if (tab === 'serial') loadSerial() }}
|
||||
onTab={(tab) => { setLogTab(tab); if (tab === 'serial') loadSerial(); if (tab === 'qemu') loadQemu() }}
|
||||
lines={logLines}
|
||||
unseenErrors={unseenErrors}
|
||||
onClear={() => setLogLines([])}
|
||||
serialText={serialLog}
|
||||
qemuText={qemuLog}
|
||||
showSerial={!!selectedVM}
|
||||
onRefreshSerial={() => loadSerial()}
|
||||
onRefreshQemu={() => loadQemu()}
|
||||
task={activeTask}
|
||||
runningTasks={runningTasks}
|
||||
onCancelTask={(id) => { backend.cancelTask(id).catch((e) => fail(tr('failGeneric'), e)) }}
|
||||
onCancelTask={cancelTask}
|
||||
/>
|
||||
</main>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showWizard && state && (
|
||||
<CreateWizard
|
||||
locale={locale}
|
||||
host={state.host}
|
||||
onClose={() => setShowWizard(false)}
|
||||
onCreated={(name) => {
|
||||
setShowWizard(false)
|
||||
setSelected(name)
|
||||
refresh()
|
||||
}}
|
||||
draft={wizardDraft}
|
||||
onClose={() => { setShowWizard(false); setWizardDraft(null) }}
|
||||
onSubmit={submitCreate}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -307,6 +573,7 @@ export const App: React.FC = () => {
|
||||
locale={locale}
|
||||
detail={detail}
|
||||
host={state.host}
|
||||
optimizations={state.optimizations}
|
||||
running={effectiveState === 'running'}
|
||||
onClose={() => setShowSettings(false)}
|
||||
onSaved={() => {
|
||||
@@ -321,6 +588,25 @@ export const App: React.FC = () => {
|
||||
<DeleteDialog locale={locale} name={deleteTarget} onCancel={() => setDeleteTarget(null)} onConfirm={confirmDelete} />
|
||||
)}
|
||||
|
||||
{cloneSource && (
|
||||
<CloneDialog
|
||||
locale={locale}
|
||||
sourceName={cloneSource}
|
||||
defaultCloneName={`${cloneSource}-clone`}
|
||||
onCancel={() => setCloneSource(null)}
|
||||
onConfirm={confirmClone}
|
||||
/>
|
||||
)}
|
||||
|
||||
{onlineRecoveryTarget && (
|
||||
<OnlineRecoveryDialog
|
||||
locale={locale}
|
||||
name={onlineRecoveryTarget}
|
||||
onCancel={() => setOnlineRecoveryTarget(null)}
|
||||
onConfirm={confirmOnlineRecovery}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Toaster items={toasts.items} onRemove={toasts.remove} closeLabel={tr('close')} />
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import * as Alert from '@radix-ui/react-alert-dialog'
|
||||
import React, { useState } from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { Locale } from '../types'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
sourceName: string
|
||||
defaultCloneName: string
|
||||
onCancel: () => void
|
||||
onConfirm: (cloneName: string) => void
|
||||
}
|
||||
|
||||
export const CloneDialog: React.FC<Props> = ({ locale, sourceName, defaultCloneName, onCancel, onConfirm }) => {
|
||||
const [cloneName, setCloneName] = useState(defaultCloneName)
|
||||
const trimmed = cloneName.trim()
|
||||
return (
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog sm">
|
||||
<div className="dialog-body">
|
||||
<Alert.Title className="dialog-title">{t(locale, 'cloneTitle', { name: sourceName })}</Alert.Title>
|
||||
<Alert.Description className="dialog-desc">
|
||||
{t(locale, 'cloneDesc')}
|
||||
</Alert.Description>
|
||||
<div className="field" style={{ marginTop: 10 }}>
|
||||
<label className="field-label" htmlFor="clone-name">{t(locale, 'cloneNameLabel')}</label>
|
||||
<input
|
||||
id="clone-name"
|
||||
className="input mono"
|
||||
value={cloneName}
|
||||
onChange={(e) => setCloneName(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter' && trimmed) onConfirm(trimmed) }}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild>
|
||||
<button type="button" className="btn">{t(locale, 'cancel')}</button>
|
||||
</Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button type="button" className="btn btn-primary" disabled={!trimmed} onClick={() => onConfirm(trimmed)}>
|
||||
{t(locale, 'cloneConfirm')}
|
||||
</button>
|
||||
</Alert.Action>
|
||||
</div>
|
||||
</Alert.Content>
|
||||
</Alert.Portal>
|
||||
</Alert.Root>
|
||||
)
|
||||
}
|
||||
@@ -1,45 +1,71 @@
|
||||
import { Check } from 'lucide-react'
|
||||
import { ChevronRight, CircleAlert, CircleCheck, Check, Copy } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { shortGPUName } from '../lib/format'
|
||||
import { CreateOpts, HostReport, Locale, ValidationIssue } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { formatMemory, gpuLabel, recommendedMemoryGB, shortGPUName } from '../lib/format'
|
||||
import { CachedInstaller, CreateOpts, HostReport, Locale, Release, ValidationIssue } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { backend } from '../wails'
|
||||
|
||||
/** Reopen the wizard where the user left it (e.g. after a failed create). */
|
||||
export interface WizardDraft {
|
||||
opts: CreateOpts
|
||||
step: number
|
||||
}
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
host: HostReport
|
||||
draft?: WizardDraft | null
|
||||
onClose: () => void
|
||||
onCreated: (name: string) => void
|
||||
/** Called with the cleaned payload; the caller runs the create in the background. */
|
||||
onSubmit: (payload: CreateOpts, draft: WizardDraft) => void
|
||||
}
|
||||
|
||||
export const CreateWizard: React.FC<Props> = ({ locale, host, onClose, onCreated }) => {
|
||||
const REVIEW_STEP = 5
|
||||
|
||||
// Which wizard step owns each ValidationIssue.field (internal/driver/reims/reims.go ValidateCreate).
|
||||
const STEP_OF_FIELD: Record<string, number> = {
|
||||
name: 1, installer: 1, disk: 1, macos: 1,
|
||||
cpus: 2, memory: 2,
|
||||
disk_size: 3, disk_controller: 3,
|
||||
graphics: 4, gpu: 4, resolution: 4, displays: 4, ssh_port: 4,
|
||||
}
|
||||
const stepOfIssue = (i: ValidationIssue) => STEP_OF_FIELD[i.field] ?? REVIEW_STEP
|
||||
|
||||
export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, onSubmit }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [step, setStep] = useState(1)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [step, setStep] = useState(draft?.step ?? 1)
|
||||
// Once the user has reached the review step, keep validating so step markers stay current.
|
||||
const [reviewed, setReviewed] = useState(draft?.step === REVIEW_STEP)
|
||||
const [checking, setChecking] = useState(false)
|
||||
const [err, setErr] = useState('')
|
||||
const [issues, setIssues] = useState<ValidationIssue[]>([])
|
||||
const [cmdPreview, setCmdPreview] = useState('')
|
||||
|
||||
const [opts, setOpts] = useState<CreateOpts>({
|
||||
const [opts, setOpts] = useState<CreateOpts>(draft?.opts ?? {
|
||||
name: 'macos-tahoe',
|
||||
dir: '',
|
||||
source_mode: 'apple',
|
||||
macos: 'tahoe',
|
||||
// Offline by default: one exact release that installs with no network
|
||||
// (roadmap M2.3; `reims-ctl create --help`, upstream 3731afd).
|
||||
source_mode: 'offline',
|
||||
macos: '',
|
||||
offline: true,
|
||||
installer: '',
|
||||
cpus: host.logical_cpus >= 12 ? 8 : 4,
|
||||
memory: host.total_ram_gb >= 24 ? '16G' : '8G',
|
||||
memory: `${recommendedMemoryGB(host)}G`,
|
||||
disk_size: '128G',
|
||||
disk: '',
|
||||
disk_mode: 'copy',
|
||||
disk_controller: 'nvme',
|
||||
graphics: 'reims-vgpu',
|
||||
gpu: host.recommended_gpu?.vulkan_icd ?? 'auto',
|
||||
resolution: '1920x1080',
|
||||
displays: 1,
|
||||
borderless: false,
|
||||
capture: false,
|
||||
audio: true,
|
||||
network: true,
|
||||
network: false,
|
||||
ssh_port: 0,
|
||||
logs: true,
|
||||
start: true,
|
||||
@@ -47,8 +73,11 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, onClose, onCreated
|
||||
const set = (patch: Partial<CreateOpts>) => setOpts((o) => ({ ...o, ...patch }))
|
||||
|
||||
const buildPayload = (): CreateOpts => {
|
||||
const p: CreateOpts = { ...opts }
|
||||
if (p.source_mode === 'apple') {
|
||||
const p: CreateOpts = { ...opts, offline: opts.source_mode === 'offline' }
|
||||
if (p.source_mode === 'offline') {
|
||||
p.installer = ''
|
||||
p.disk = ''
|
||||
} else if (p.source_mode === 'apple') {
|
||||
p.installer = ''
|
||||
p.disk = ''
|
||||
} else if (p.source_mode === 'installer') {
|
||||
@@ -63,15 +92,49 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, onClose, onCreated
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (step !== 5) return
|
||||
const payload = buildPayload()
|
||||
Promise.all([backend.validateCreate(payload), backend.previewCreate(payload)])
|
||||
.then(([iss, cmd]) => {
|
||||
setIssues(iss ?? [])
|
||||
setCmdPreview(cmd)
|
||||
if (step === REVIEW_STEP) setReviewed(true)
|
||||
}, [step])
|
||||
|
||||
// Offline releases come from Apple's catalog (a few seconds); downloaded ones are marked.
|
||||
const [releases, setReleases] = useState<Release[] | null>(null)
|
||||
const [cached, setCached] = useState<CachedInstaller[]>([])
|
||||
const [releasesErr, setReleasesErr] = useState('')
|
||||
useEffect(() => {
|
||||
if (opts.source_mode !== 'offline' || releases) return
|
||||
let live = true
|
||||
backend.listInstallers().then((l) => { if (live) setCached(l ?? []) }).catch(() => {})
|
||||
backend.listOfflineReleases()
|
||||
.then((list) => {
|
||||
if (!live) return
|
||||
setReleases(list ?? [])
|
||||
if (!opts.macos && list && list.length > 0) set({ macos: list[0].version })
|
||||
})
|
||||
.catch((e) => setErr(String(e)))
|
||||
}, [step, opts])
|
||||
.catch((e) => { if (live) setReleasesErr(String(e).replace(/^Error:\s*/, '')) })
|
||||
return () => { live = false }
|
||||
}, [opts.source_mode])
|
||||
const isCached = (v: string) => cached.some((c) => c.kind === 'offline' && !c.partial && c.version === v)
|
||||
const chosenRelease = releases?.find((r) => r.version === opts.macos)
|
||||
// reims-util pre-allocates the whole image as it starts (19.7 GB for an 18.4 GB release, measured).
|
||||
const needGB = chosenRelease && !isCached(chosenRelease.version) ? Math.ceil((chosenRelease.size * 1.1) / 1e9) : 0
|
||||
|
||||
useEffect(() => {
|
||||
if (!reviewed && step !== REVIEW_STEP) return
|
||||
let live = true
|
||||
setChecking(true)
|
||||
const timer = setTimeout(() => {
|
||||
const payload = buildPayload()
|
||||
Promise.all([backend.validateCreate(payload), backend.previewCreate(payload)])
|
||||
.then(([iss, cmd]) => {
|
||||
if (!live) return
|
||||
setIssues(iss ?? [])
|
||||
setCmdPreview(cmd)
|
||||
setErr('')
|
||||
})
|
||||
.catch((e) => { if (live) setErr(String(e).replace(/^Error:\s*/, '')) })
|
||||
.finally(() => { if (live) setChecking(false) })
|
||||
}, 200)
|
||||
return () => { live = false; clearTimeout(timer) }
|
||||
}, [step, reviewed, opts])
|
||||
|
||||
const pickDir = async () => {
|
||||
const dir = await backend.pickDirectory(tr('vmDir'))
|
||||
@@ -83,19 +146,8 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, onClose, onCreated
|
||||
if (f) set({ [field]: f })
|
||||
}
|
||||
|
||||
const handleCreate = async () => {
|
||||
setErr('')
|
||||
setBusy(true)
|
||||
try {
|
||||
const payload = buildPayload()
|
||||
await backend.createVM(payload)
|
||||
onCreated(payload.name)
|
||||
} catch (e) {
|
||||
setErr(String(e).replace(/^Error:\s*/, ''))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
const handleCreate = () => onSubmit(buildPayload(), { opts, step: REVIEW_STEP })
|
||||
const issueSteps = new Set(reviewed ? issues.map(stepOfIssue) : [])
|
||||
|
||||
const realGPUs = (host.gpus ?? []).filter((g) => g.kind !== 'virtual')
|
||||
const steps: I18nKey[] = ['step1', 'step2', 'step3', 'step4', 'step5']
|
||||
@@ -111,20 +163,21 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, onClose, onCreated
|
||||
)
|
||||
|
||||
return (
|
||||
<Modal title={tr('wizardTitle')} closeLabel={tr('close')} dismissable={!busy} onClose={onClose}>
|
||||
<Modal title={tr('wizardTitle')} closeLabel={tr('close')} onClose={onClose}>
|
||||
<nav className="wizard-steps" aria-label={tr('wizardTitle')}>
|
||||
{steps.map((key, idx) => {
|
||||
const n = idx + 1
|
||||
const bad = issueSteps.has(n) && n !== REVIEW_STEP
|
||||
const done = !bad && (step > n || (reviewed && n < REVIEW_STEP))
|
||||
return (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
className={`wizard-step${step > n ? ' done' : ''}`}
|
||||
className={`wizard-step${done ? ' done' : ''}${bad ? ' has-issue' : ''}`}
|
||||
aria-current={step === n ? 'step' : undefined}
|
||||
disabled={busy}
|
||||
onClick={() => setStep(n)}
|
||||
>
|
||||
{step > n && <Check size={12} />}
|
||||
{bad ? <CircleAlert size={12} /> : done && <Check size={12} />}
|
||||
{tr(key)}
|
||||
</button>
|
||||
)
|
||||
@@ -152,15 +205,20 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, onClose, onCreated
|
||||
|
||||
<fieldset className="field choices fieldset">
|
||||
<legend className="field-label">{tr('step1')}</legend>
|
||||
{(['apple', 'installer', 'disk'] as const).map((mode) => (
|
||||
{(['offline', 'apple', 'installer', 'disk'] as const).map((mode) => (
|
||||
<label key={mode} className="choice">
|
||||
<input
|
||||
type="radio"
|
||||
name="source"
|
||||
checked={opts.source_mode === mode}
|
||||
onChange={() => set({ source_mode: mode, ...(mode === 'apple' ? { macos: opts.macos || 'tahoe' } : {}) })}
|
||||
onChange={() => set({
|
||||
source_mode: mode,
|
||||
network: mode !== 'offline',
|
||||
...(mode === 'apple' ? { macos: 'tahoe' } : {}),
|
||||
...(mode === 'offline' ? { macos: releases?.[0]?.version ?? '' } : {}),
|
||||
})}
|
||||
/>
|
||||
{tr(mode === 'apple' ? 'sourceApple' : mode === 'installer' ? 'sourceInstaller' : 'sourceDisk')}
|
||||
{tr(mode === 'offline' ? 'sourceOffline' : mode === 'apple' ? 'sourceApple' : mode === 'installer' ? 'sourceInstaller' : 'sourceDisk')}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
@@ -174,7 +232,30 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, onClose, onCreated
|
||||
</div>
|
||||
)}
|
||||
|
||||
{opts.source_mode !== 'apple' && (
|
||||
{opts.source_mode === 'offline' && (
|
||||
<div className="field">
|
||||
<label className="field-label" htmlFor="vm-release">{tr('macosVersion')}</label>
|
||||
{releasesErr ? (
|
||||
<div className="notice notice-error">{tr('offlineListFailed')}:{releasesErr}</div>
|
||||
) : !releases ? (
|
||||
<span className="hint">{tr('offlineLoading')}</span>
|
||||
) : (
|
||||
<select id="vm-release" className="select" value={opts.macos} onChange={(e) => set({ macos: e.target.value })}>
|
||||
{releases.map((r) => (
|
||||
<option key={r.product} value={r.version}>
|
||||
{r.title} {r.version} ({r.build}) · {(r.size / 1e9).toFixed(1)} GB{isCached(r.version) ? ` · ${tr('offlineCached')}` : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<span className="hint">{tr('offlineHint')}</span>
|
||||
{needGB > 0 && host.free_disk_gb > 0 && host.free_disk_gb < needGB + 10 && (
|
||||
<span className="hint warn">{tr('offlineSpaceWarn', { free: host.free_disk_gb.toFixed(0), need: needGB })}</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(opts.source_mode === 'installer' || opts.source_mode === 'disk') && (
|
||||
<div className="field">
|
||||
<label className="field-label" htmlFor="vm-src">
|
||||
{tr(opts.source_mode === 'installer' ? 'sourceInstaller' : 'sourceDisk')}
|
||||
@@ -189,7 +270,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, onClose, onCreated
|
||||
<Button
|
||||
onClick={() => (opts.source_mode === 'installer'
|
||||
? pickFile('installer', '*.img;*.dmg')
|
||||
: pickFile('disk', '*.qcow2;*.img'))}
|
||||
: pickFile('disk', '*.qcow2;*.img;*.vmdk;*.raw'))}
|
||||
>
|
||||
{tr('choose')}
|
||||
</Button>
|
||||
@@ -216,33 +297,53 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, onClose, onCreated
|
||||
<label className="field-label" htmlFor="vm-mem">{tr('factMemory')} · {tr('hostMemory', { n: host.total_ram_gb.toFixed(0) })}</label>
|
||||
{presets(['4G', '8G', '12G', '16G', '24G'], opts.memory, (m) => m, (memory) => set({ memory }))}
|
||||
<input id="vm-mem" className="input" value={opts.memory} onChange={(e) => set({ memory: e.target.value })} />
|
||||
<span className="hint">{tr('memHint')}</span>
|
||||
<span className="hint">
|
||||
{host.commit_avail_gb > 0
|
||||
? tr('memCommitHint', { avail: host.commit_avail_gb.toFixed(1), rec: recommendedMemoryGB(host) })
|
||||
: tr('memHint')}
|
||||
</span>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{step === 3 && (
|
||||
opts.source_mode !== 'disk' ? (
|
||||
<>
|
||||
{opts.source_mode !== 'disk' ? (
|
||||
<div className="field">
|
||||
<label className="field-label" htmlFor="vm-disk">{tr('diskSize')}</label>
|
||||
{presets(['64G', '128G', '256G', '512G'], opts.disk_size, (s) => s, (disk_size) => set({ disk_size }))}
|
||||
<input id="vm-disk" className="input" value={opts.disk_size ?? ''} onChange={(e) => set({ disk_size: e.target.value })} />
|
||||
<span className="hint">{tr('diskSizeHint')}</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="field">
|
||||
<label className="field-label" htmlFor="vm-diskmode">{tr('diskMode')}</label>
|
||||
<select
|
||||
id="vm-diskmode"
|
||||
className="select"
|
||||
value={opts.disk_mode}
|
||||
onChange={(e) => set({ disk_mode: e.target.value as 'copy' | 'in-place' })}
|
||||
>
|
||||
<option value="copy">{tr('diskModeCopy')}</option>
|
||||
<option value="in-place">{tr('diskModeInPlace')}</option>
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
<div className="field">
|
||||
<label className="field-label" htmlFor="vm-disk">{tr('diskSize')}</label>
|
||||
{presets(['64G', '128G', '256G', '512G'], opts.disk_size, (s) => s, (disk_size) => set({ disk_size }))}
|
||||
<input id="vm-disk" className="input" value={opts.disk_size ?? ''} onChange={(e) => set({ disk_size: e.target.value })} />
|
||||
<span className="hint">{tr('diskSizeHint')}</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="field">
|
||||
<label className="field-label" htmlFor="vm-diskmode">{tr('diskMode')}</label>
|
||||
<label className="field-label" htmlFor="vm-diskctl">{tr('diskController')}</label>
|
||||
<select
|
||||
id="vm-diskmode"
|
||||
id="vm-diskctl"
|
||||
className="select"
|
||||
value={opts.disk_mode}
|
||||
onChange={(e) => set({ disk_mode: e.target.value as 'copy' | 'in-place' })}
|
||||
value={opts.disk_controller ?? 'nvme'}
|
||||
onChange={(e) => set({ disk_controller: e.target.value as 'nvme' | 'ahci' | 'virtio' })}
|
||||
>
|
||||
<option value="copy">{tr('diskModeCopy')}</option>
|
||||
<option value="in-place">{tr('diskModeInPlace')}</option>
|
||||
<option value="nvme">NVMe ({locale === 'zh-CN' ? '推荐' : 'Recommended'})</option>
|
||||
<option value="ahci">SATA (AHCI)</option>
|
||||
{opts.source_mode === 'disk' && <option value="virtio">VirtIO</option>}
|
||||
</select>
|
||||
<span className="hint">{tr('diskControllerNvmeHint')}</span>
|
||||
</div>
|
||||
)
|
||||
</>
|
||||
)}
|
||||
|
||||
{step === 4 && (
|
||||
@@ -310,44 +411,205 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, onClose, onCreated
|
||||
{([
|
||||
['audio', 'enableAudio'],
|
||||
['network', 'enableNetwork'],
|
||||
['capture', 'captureInput'],
|
||||
['logs', 'enableLogs'],
|
||||
['start', 'startAfterCreate'],
|
||||
] as const).map(([key, label]) => (
|
||||
<label key={key} className="choice">
|
||||
<input type="checkbox" checked={!!opts[key]} onChange={(e) => set({ [key]: e.target.checked })} />
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={!!opts[key]}
|
||||
onChange={(e) => set({ [key]: e.target.checked })}
|
||||
/>
|
||||
{tr(label)}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<span className="hint">{tr('captureInputHint')}</span>
|
||||
{opts.source_mode === 'offline' && <span className="hint">{tr('networkOfflineHint')}</span>}
|
||||
</>
|
||||
)}
|
||||
|
||||
{step === 5 && (
|
||||
<>
|
||||
{issues.length > 0 ? (
|
||||
<div className="notice notice-error">
|
||||
<ul>{issues.map((i) => <li key={i.field + i.code}>{i.message}</li>)}</ul>
|
||||
</div>
|
||||
) : (
|
||||
<span className="hint">{tr('validationPassed')}</span>
|
||||
)}
|
||||
<div className="field">
|
||||
<span className="field-label">{tr('commandPreview')}</span>
|
||||
<div className="code">{cmdPreview}</div>
|
||||
</div>
|
||||
{busy && <span className="hint">{tr('creating')}</span>}
|
||||
</>
|
||||
<Review
|
||||
locale={locale}
|
||||
host={host}
|
||||
opts={opts}
|
||||
issues={issues}
|
||||
checking={checking}
|
||||
command={cmdPreview}
|
||||
onEdit={setStep}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="dialog-foot">
|
||||
<Button variant="ghost" disabled={step === 1 || busy} onClick={() => setStep(step - 1)}>{tr('back')}</Button>
|
||||
{step < 5 ? (
|
||||
<Button variant="ghost" disabled={step === 1} onClick={() => setStep(step - 1)}>{tr('back')}</Button>
|
||||
{step < REVIEW_STEP ? (
|
||||
<Button variant="primary" onClick={() => setStep(step + 1)}>{tr('next')}</Button>
|
||||
) : (
|
||||
<Button variant="primary" busy={busy} disabled={issues.length > 0} onClick={handleCreate}>{tr('createNow')}</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={checking || !!err || issues.length > 0 || !cmdPreview}
|
||||
title={tr('createStartedHint')}
|
||||
onClick={handleCreate}
|
||||
>
|
||||
{tr('createNow')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
interface ReviewProps {
|
||||
locale: Locale
|
||||
host: HostReport
|
||||
opts: CreateOpts
|
||||
issues: ValidationIssue[]
|
||||
checking: boolean
|
||||
command: string
|
||||
onEdit: (step: number) => void
|
||||
}
|
||||
|
||||
type Row = { label: string; value: string; mono?: boolean }
|
||||
|
||||
const fileName = (p?: string) => (p ?? '').split(/[\\/]/).pop() || (p ?? '')
|
||||
|
||||
/** Step ⑤: what will be created, grouped by the step that set it, with the CLI equivalent folded away. */
|
||||
const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, command, onEdit }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [copied, setCopied] = useState(false)
|
||||
const onOff = (b?: boolean) => tr(b ? 'summaryOn' : 'off')
|
||||
|
||||
const source = opts.source_mode === 'offline'
|
||||
? tr('summaryOfflineSource', { v: opts.macos ?? '' })
|
||||
: opts.source_mode === 'apple'
|
||||
? tr('summaryAppleSource', { v: opts.macos === 'tahoe' ? 'macOS 26 Tahoe' : (opts.macos ?? '') })
|
||||
: opts.source_mode === 'installer'
|
||||
? tr('summaryInstallerSource', { file: fileName(opts.installer) })
|
||||
: tr('summaryDiskSource', { file: fileName(opts.disk) })
|
||||
|
||||
const res = (opts.resolution ?? '').replace(/x/i, ' × ')
|
||||
const graphicsRows: Row[] = opts.graphics === 'reims-vgpu'
|
||||
? [
|
||||
{ label: tr('factGraphics'), value: `${gpuLabel(locale, opts.gpu, host)} · reims-vgpu` },
|
||||
{ label: tr('resolution'), value: (opts.displays ?? 1) > 1 ? `${opts.displays} × (${res})` : res },
|
||||
]
|
||||
: [{ label: tr('factGraphics'), value: `${tr('softwareGraphics')} · vmware-svga` }]
|
||||
|
||||
const groups: { step: number; title: I18nKey; rows: Row[] }[] = [
|
||||
{
|
||||
step: 1,
|
||||
title: 'step1',
|
||||
rows: [
|
||||
{ label: tr('vmName'), value: opts.name },
|
||||
{ label: tr('summarySource'), value: source },
|
||||
{ label: tr('vmDir'), value: opts.dir || tr('summaryDefaultDir'), mono: !!opts.dir },
|
||||
],
|
||||
},
|
||||
{
|
||||
step: 2,
|
||||
title: 'step2',
|
||||
rows: [
|
||||
{ label: tr('factCPU'), value: tr('cores', { n: opts.cpus }) },
|
||||
{ label: tr('factMemory'), value: formatMemory(opts.memory) },
|
||||
],
|
||||
},
|
||||
{
|
||||
step: 3,
|
||||
title: 'step3',
|
||||
rows: [
|
||||
...(opts.source_mode !== 'disk'
|
||||
? [{ label: tr('diskSize'), value: tr('summaryDiskGrow', { size: formatMemory(opts.disk_size ?? '') }) }]
|
||||
: [{ label: tr('diskMode'), value: tr(opts.disk_mode === 'in-place' ? 'diskModeInPlace' : 'diskModeCopy') }]),
|
||||
{ label: tr('diskController'), value: (opts.disk_controller ?? 'nvme').toUpperCase() === 'AHCI' ? 'SATA' : (opts.disk_controller ?? 'nvme').toUpperCase() },
|
||||
],
|
||||
},
|
||||
{
|
||||
step: 4,
|
||||
title: 'step4',
|
||||
rows: [
|
||||
...graphicsRows,
|
||||
{ label: tr('fieldAudio'), value: onOff(opts.audio) },
|
||||
{ label: tr('fieldNetwork'), value: onOff(opts.network) },
|
||||
{ label: tr('captureInput'), value: onOff(opts.capture) },
|
||||
{ label: tr('summarySSH'), value: opts.ssh_port ? tr('summarySSHPort', { n: opts.ssh_port }) : tr('off') },
|
||||
{ label: tr('summaryLogs'), value: onOff(opts.logs) },
|
||||
{ label: tr('summaryStartAfter'), value: onOff(opts.start) },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const general = issues.filter((i) => stepOfIssue(i) === REVIEW_STEP)
|
||||
|
||||
const copy = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(command)
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 1500)
|
||||
} catch { /* clipboard unavailable; the text stays selectable */ }
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{checking && issues.length === 0 ? (
|
||||
<div className="review-status">{tr('validationChecking')}</div>
|
||||
) : issues.length > 0 ? (
|
||||
<div className="review-status bad"><CircleAlert size={14} />{tr('issuesCount', { n: issues.length })}</div>
|
||||
) : (
|
||||
<div className="review-status ok"><CircleCheck size={14} />{tr('validationPassed')}</div>
|
||||
)}
|
||||
|
||||
{general.length > 0 && (
|
||||
<div className="notice notice-error">
|
||||
<ul>{general.map((i) => <li key={i.field + i.code}>{i.message}</li>)}</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="review-groups">
|
||||
{groups.map((g) => {
|
||||
const own = issues.filter((i) => stepOfIssue(i) === g.step)
|
||||
return (
|
||||
<section key={g.step} className={`review-group${own.length ? ' has-issue' : ''}`} aria-label={tr(g.title)}>
|
||||
<header className="review-head">
|
||||
<span className="review-title">{tr(g.title)}</span>
|
||||
<button type="button" className="link-btn" onClick={() => onEdit(g.step)}>{tr('summaryEdit')}</button>
|
||||
</header>
|
||||
<dl className="review-rows">
|
||||
{g.rows.map((r) => (
|
||||
<React.Fragment key={r.label}>
|
||||
<dt>{r.label}</dt>
|
||||
<dd className={r.mono ? 'mono' : undefined} title={r.value}>{r.value}</dd>
|
||||
</React.Fragment>
|
||||
))}
|
||||
</dl>
|
||||
{own.length > 0 && (
|
||||
<ul className="review-issues">
|
||||
{own.map((i) => <li key={i.field + i.code}><CircleAlert size={12} />{i.message}</li>)}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<details className="review-cmd">
|
||||
<summary><ChevronRight size={14} />{tr('commandToggle')}</summary>
|
||||
<div className="review-cmd-body">
|
||||
<span className="hint">{tr('commandToggleHint')}</span>
|
||||
<div className="review-cmd-box">
|
||||
<div className="code">{command || '…'}</div>
|
||||
<IconButton
|
||||
small
|
||||
label={copied ? tr('toastCopied') : tr('copy')}
|
||||
icon={copied ? <Check size={14} /> : <Copy size={14} />}
|
||||
disabled={!command}
|
||||
onClick={copy}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { Cpu, HardDrive, MemoryStick, RefreshCw, ShieldCheck } from 'lucide-react'
|
||||
import React, { useState } from 'react'
|
||||
import { Cpu, Download, HardDrive, MemoryStick, RefreshCw, ShieldCheck } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { AppState, Locale } from '../types'
|
||||
import { findOptimization, kernelIrqchipHint, optBadgeClass, optStatusLabel } from '../lib/optimizations'
|
||||
import { AppState, AppUpdateInfo, Locale, Task } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { backend } from '../wails'
|
||||
import { RuntimeOnline } from './RuntimeOnline'
|
||||
|
||||
interface Props {
|
||||
state: AppState
|
||||
@@ -11,14 +13,42 @@ interface Props {
|
||||
onRefresh: () => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
onSetLocale: (l: Locale) => void
|
||||
runtimeTask: Task | null
|
||||
onChannel: (candidate: boolean) => void
|
||||
onInstallRuntime: (commit: string) => void
|
||||
onCancelTask: (id: string) => void
|
||||
}
|
||||
|
||||
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, onSetLocale }) => {
|
||||
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, onSetLocale, runtimeTask, onChannel, onInstallRuntime, onCancelTask }) => {
|
||||
const [importing, setImporting] = useState(false)
|
||||
const [enabling, setEnabling] = useState(false)
|
||||
const { host, config, runtimes } = state
|
||||
const [appUpdate, setAppUpdate] = useState<AppUpdateInfo | null>(null)
|
||||
const [checkingUpdate, setCheckingUpdate] = useState(false)
|
||||
const [updateErr, setUpdateErr] = useState('')
|
||||
const { host, config, runtimes, optimizations } = state
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
|
||||
const runUpdateCheck = async (force: boolean) => {
|
||||
setCheckingUpdate(true)
|
||||
setUpdateErr('')
|
||||
try {
|
||||
const info = await backend.checkAppUpdate(force)
|
||||
setAppUpdate(info)
|
||||
} catch (e) {
|
||||
setUpdateErr(String(e).replace(/^Error:\s*/, ''))
|
||||
} finally {
|
||||
setCheckingUpdate(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
void runUpdateCheck(false)
|
||||
}, [])
|
||||
const pcoreOpt = findOptimization(optimizations, 'pcore_pin')
|
||||
const irqOpt = findOptimization(optimizations, 'kernel_irqchip')
|
||||
const rebootOpt = findOptimization(optimizations, 'cold_reboot')
|
||||
const gpuOpt = findOptimization(optimizations, 'discrete_gpu')
|
||||
|
||||
const whpx = {
|
||||
ready: { short: tr('whpxReady'), hint: '', tone: 'ok' },
|
||||
no_hypervisor: { short: tr('whpxNoHvShort'), hint: tr('whpxNoHv'), tone: 'warn' },
|
||||
@@ -73,14 +103,15 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
<div className="tile">
|
||||
<div className="tile-head"><ShieldCheck size={14} /> {tr('whpxTitle')}</div>
|
||||
<div className={`tile-value ${whpx.tone}`}>{whpx.short}</div>
|
||||
<div className="tile-sub">{host.os}/{host.arch}</div>
|
||||
{host.whpx === 'missing' ? (
|
||||
<Button variant="primary" className="tile-action" busy={enabling} onClick={enableWHPX}>{tr('enableWHPX')}</Button>
|
||||
) : whpx.hint ? (
|
||||
<div className="tile-sub" title={whpx.hint}>{whpx.hint}</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="tile">
|
||||
<div className="tile-head"><Cpu size={14} /> {tr('hostCPU')}</div>
|
||||
<div className="tile-value">{tr('hostCoresThreads', { c: host.physical_cores, t: host.logical_cpus })}</div>
|
||||
<div className="tile-sub">
|
||||
{host.has_hybrid_cores ? tr('hostHybrid', { p: host.p_core_count, e: host.e_core_count }) : tr('hostSymmetric')}
|
||||
</div>
|
||||
</div>
|
||||
<div className="tile">
|
||||
<div className="tile-head"><MemoryStick size={14} /> {tr('hostRAM')}</div>
|
||||
@@ -90,58 +121,43 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
<div className="tile">
|
||||
<div className="tile-head"><HardDrive size={14} /> {tr('hostDisk')}</div>
|
||||
<div className="tile-value">{host.free_disk_gb.toFixed(0)} GB</div>
|
||||
<div className="tile-sub mono">{config.data_root}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">
|
||||
{tr('hostRuntime')}
|
||||
<Button variant={runtimes && runtimes.length > 0 ? 'secondary' : 'primary'} busy={importing} onClick={importRuntime}>
|
||||
<Button variant="ghost" busy={importing} onClick={importRuntime}>
|
||||
{tr('importRuntime')}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="list">
|
||||
{!runtimes || runtimes.length === 0 ? (
|
||||
<div className="row"><span className="row-sub">{tr('noRuntime')}</span></div>
|
||||
) : (
|
||||
runtimes.map((rt) => (
|
||||
<div className="row" key={rt.commit}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className="mono">{rt.commit}</span>
|
||||
<span className="muted">{rt.manifest.qemu_version}</span>
|
||||
{rt.active && <span className="badge badge-ok">{tr('activeBadge')}</span>}
|
||||
</div>
|
||||
<div className="row-sub mono">{rt.dir}</div>
|
||||
</div>
|
||||
{!rt.active && (
|
||||
<div className="row-right">
|
||||
<Button onClick={guard(() => backend.useRuntime(rt.commit))}>{tr('activate')}</Button>
|
||||
</div>
|
||||
)}
|
||||
<RuntimeOnline
|
||||
locale={locale}
|
||||
channel={config.runtime_channel === 'candidate' ? 'candidate' : 'stable'}
|
||||
installed={runtimes ?? []}
|
||||
task={runtimeTask}
|
||||
onChannel={onChannel}
|
||||
onInstall={onInstallRuntime}
|
||||
onCancel={onCancelTask}
|
||||
/>
|
||||
{(runtimes ?? []).filter((rt) => !rt.active).map((rt) => (
|
||||
<div className="row" key={rt.commit}>
|
||||
<div className="row-main">
|
||||
<div className="row-title"><span className="mono">{rt.commit}</span></div>
|
||||
<div className="row-sub">{rt.manifest.qemu_version.replace(/^QEMU emulator version\s*/i, 'QEMU ')}</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
<div className="row-right">
|
||||
<Button onClick={guard(() => backend.useRuntime(rt.commit))}>{tr('activate')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('hostSystem')}</div>
|
||||
<div className="section-title">{tr('settings')}</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('hostWHPX')}</div>
|
||||
{whpx.hint && <div className="row-sub">{whpx.hint}</div>}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{host.whpx === 'missing' ? (
|
||||
<Button variant="primary" busy={enabling} onClick={enableWHPX}>{tr('enableWHPX')}</Button>
|
||||
) : (
|
||||
<span className={`badge ${whpx.tone === 'ok' ? 'badge-ok' : 'badge-warn'}`}>{whpx.short}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('hostDataRoot')}</div>
|
||||
@@ -149,25 +165,113 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
</div>
|
||||
<div className="row-right"><Button onClick={pickDataRoot}>{tr('choose')}</Button></div>
|
||||
</div>
|
||||
{host.has_hybrid_cores && (
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('autoPinPCores')}</div>
|
||||
<div className="row-sub mono">{host.p_core_mask_hex}</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('autoPinPCores')}
|
||||
<span className={`badge ${optBadgeClass(pcoreOpt?.status)}`}>
|
||||
{optStatusLabel(locale, pcoreOpt?.status)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<label className="switch">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={tr('autoPinPCores')}
|
||||
checked={config.auto_pin_pcores}
|
||||
onChange={(e) => guard(() => backend.setAutoPinPCores(e.target.checked))()}
|
||||
/>
|
||||
<span className="slider" />
|
||||
</label>
|
||||
<div className="row-sub">
|
||||
{pcoreOpt?.supported
|
||||
? tr('optPCoreSub', { detail: pcoreOpt.detail ?? `${host.p_core_count}P+${host.e_core_count}E` })
|
||||
: tr('optPCoreUnavailable')}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="row-right">
|
||||
<label className="switch">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={tr('autoPinPCores')}
|
||||
disabled={!pcoreOpt?.supported}
|
||||
checked={!!pcoreOpt?.supported && config.auto_pin_pcores}
|
||||
onChange={(e) => guard(() => backend.setAutoPinPCores(e.target.checked))()}
|
||||
/>
|
||||
<span className="slider" />
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main"><div className="row-title">{tr('language')}</div></div>
|
||||
<div className="row-right">
|
||||
<div className="segmented" role="group" aria-label={tr('language')}>
|
||||
<button type="button" aria-pressed={locale === 'zh-CN'} onClick={() => onSetLocale('zh-CN')}>中文</button>
|
||||
<button type="button" aria-pressed={locale === 'en-US'} onClick={() => onSetLocale('en-US')}>English</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('appVersionTitle')} <span className="mono">{state.app_version ?? appUpdate?.current ?? 'v0.2.1'}</span>
|
||||
{appUpdate && !appUpdate.has_update && (
|
||||
<span className="badge badge-ok">{tr('appUpToDate')}</span>
|
||||
)}
|
||||
</div>
|
||||
{appUpdate?.has_update ? (
|
||||
<div className="row-sub">{tr('appUpdateAvailable', { v: appUpdate.latest })}</div>
|
||||
) : updateErr ? (
|
||||
<div className="row-sub" title={updateErr}>{tr('appUpdateLookupFailed')}</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{appUpdate?.has_update && (appUpdate.page_url || appUpdate.download_url) ? (
|
||||
<Button
|
||||
variant="primary"
|
||||
icon={<Download size={14} />}
|
||||
onClick={() => guard(() => backend.openURL(appUpdate.page_url || appUpdate.download_url || ''))()}
|
||||
>
|
||||
{tr('appDownloadUpdate')}
|
||||
</Button>
|
||||
) : (
|
||||
<Button busy={checkingUpdate} onClick={() => void runUpdateCheck(true)}>
|
||||
{tr('appCheckUpdate')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('hostOptimizations')}</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('optKernelIrqchipTitle')}
|
||||
<span className={`badge ${optBadgeClass(irqOpt?.status)}`}>{optStatusLabel(locale, irqOpt?.status)}</span>
|
||||
</div>
|
||||
<div className="row-sub">{kernelIrqchipHint(locale, irqOpt)}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('optColdRebootTitle')}
|
||||
<span className={`badge ${optBadgeClass(rebootOpt?.status)}`}>{optStatusLabel(locale, rebootOpt?.status)}</span>
|
||||
</div>
|
||||
<div className="row-sub">
|
||||
{tr(rebootOpt?.supported ? 'optColdRebootAuto' : 'optColdRebootUnavailable')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('optDiscreteGpuTitle')}
|
||||
<span className={`badge ${optBadgeClass(gpuOpt?.status)}`}>{optStatusLabel(locale, gpuOpt?.status)}</span>
|
||||
</div>
|
||||
<div className="row-sub">
|
||||
{gpuOpt?.status === 'recommended'
|
||||
? tr('optDiscreteGpuRec', { name: gpuOpt.detail ?? '' })
|
||||
: gpuOpt?.status === 'available'
|
||||
? tr('optDiscreteGpuIntegrated', { name: gpuOpt.detail ?? '' })
|
||||
: tr('optDiscreteGpuUnavailable')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -180,33 +284,17 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
realGPUs.map((g) => (
|
||||
<div className="row" key={g.vulkan_icd}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<div className="row-title" title={g.vulkan_icd}>
|
||||
{g.name}
|
||||
<span className={`badge ${g.kind === 'discrete' ? 'badge-accent' : ''}`}>{gpuKind(g.kind)}</span>
|
||||
{host.recommended_gpu?.vulkan_icd === g.vulkan_icd && <span className="badge badge-ok">{tr('gpuRecommended')}</span>}
|
||||
</div>
|
||||
<div className="row-sub mono">{g.vulkan_icd}</div>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('hostPrefs')}</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main"><div className="row-title">{tr('language')}</div></div>
|
||||
<div className="row-right">
|
||||
<div className="segmented" role="group" aria-label={tr('language')}>
|
||||
<button type="button" aria-pressed={locale === 'zh-CN'} onClick={() => onSetLocale('zh-CN')}>中文</button>
|
||||
<button type="button" aria-pressed={locale === 'en-US'} onClick={() => onSetLocale('en-US')}>English</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import { Download, LoaderCircle, Pause, Plus, RefreshCw, Trash } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { taskDetail } from '../lib/tasks'
|
||||
import { CachedInstaller, HostReport, Locale, Release, Task } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { backend } from '../wails'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
host: HostReport
|
||||
tasks: Task[]
|
||||
onCreateWithInstaller: (item: CachedInstaller) => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
onToast: (title: string) => void
|
||||
}
|
||||
|
||||
const gb = (b: number) => (b >= 1e9 ? `${(b / 1e9).toFixed(1)} GB` : `${Math.max(1, Math.ceil(b / 1e6))} MB`)
|
||||
|
||||
// reims-util creates the whole image as soon as a download starts (19.7 GB for an
|
||||
// 18.4 GB release, measured 2026-11-28): reserve 10% over the release size.
|
||||
const needBytes = (r: Release) => r.size * 1.1
|
||||
|
||||
/** Offline installers (roadmap M2.2): what is downloaded, and Apple's releases to download. */
|
||||
export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateWithInstaller, onError, onToast }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [cached, setCached] = useState<CachedInstaller[] | null>(null)
|
||||
const [releases, setReleases] = useState<Release[] | null>(null)
|
||||
const [releasesErr, setReleasesErr] = useState('')
|
||||
const [confirmDelete, setConfirmDelete] = useState('')
|
||||
|
||||
const downloads = tasks.filter((x) => x.kind === 'installer-download')
|
||||
const running = (version: string) => downloads.find((x) => x.status === 'running' && x.subject === version)
|
||||
const finishedCount = downloads.filter((x) => x.status !== 'running').length
|
||||
|
||||
const loadCached = () => backend.listInstallers().then((l) => setCached(l ?? [])).catch((e) => onError(tr('failGeneric'), e))
|
||||
const loadReleases = () => {
|
||||
setReleases(null)
|
||||
setReleasesErr('')
|
||||
backend.listOfflineReleases()
|
||||
.then((l) => setReleases(l ?? []))
|
||||
.catch((e) => setReleasesErr(String(e).replace(/^Error:\s*/, '')))
|
||||
}
|
||||
useEffect(() => { loadReleases() }, [])
|
||||
// Refresh the downloaded list whenever a download starts or ends.
|
||||
useEffect(() => { loadCached() }, [finishedCount, downloads.length])
|
||||
|
||||
const isDownloaded = (v: string) => (cached ?? []).some((c) => c.kind === 'offline' && !c.partial && c.version === v)
|
||||
|
||||
const download = (version: string) => {
|
||||
backend.downloadInstaller(version).catch((e) => onError(tr('failDownload'), e))
|
||||
}
|
||||
|
||||
const remove = async (name: string) => {
|
||||
if (confirmDelete !== name) { setConfirmDelete(name); return }
|
||||
setConfirmDelete('')
|
||||
try {
|
||||
await backend.deleteInstaller(name)
|
||||
onToast(tr('toastDeleted', { name }))
|
||||
loadCached()
|
||||
} catch (e) {
|
||||
onError(tr('failDelete'), e)
|
||||
}
|
||||
}
|
||||
|
||||
const progress = (task: Task) => (
|
||||
<span className="task-inline row-sub">
|
||||
<LoaderCircle size={14} className="spin" />
|
||||
{task.percent >= 0 && <span className="progress"><div style={{ width: `${task.percent}%` }} /></span>}
|
||||
<span>{task.percent >= 0 ? `${Math.floor(task.percent)}%` : ''} {taskDetail(task)}</span>
|
||||
</span>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<header className="page-head">
|
||||
<div className="page-title"><h1>{tr('installersTitle')}</h1></div>
|
||||
<div className="actions">
|
||||
<IconButton label={tr('refresh')} icon={<RefreshCw size={16} />} onClick={() => { loadCached(); loadReleases() }} />
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('installersDownloaded')}</div>
|
||||
<div className="list">
|
||||
{cached === null ? (
|
||||
<div className="row"><span className="row-sub">…</span></div>
|
||||
) : cached.length === 0 ? (
|
||||
<div className="row"><span className="row-sub">{tr('installersEmpty')}</span></div>
|
||||
) : cached.map((c) => {
|
||||
const task = c.version ? running(c.version) : undefined
|
||||
return (
|
||||
<div className="row" key={c.name}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{c.title ?? c.name} {c.version}
|
||||
{c.build && <span className="muted">({c.build})</span>}
|
||||
{c.kind === 'offline' && !c.partial && <span className="badge badge-ok">{tr('installersKindOffline')}</span>}
|
||||
{c.kind === 'online' && !c.partial && <span className="badge">{tr('installersKindOnline')}</span>}
|
||||
{c.partial && !task && <span className="badge badge-warn">{tr('installersPartial')}</span>}
|
||||
</div>
|
||||
{task ? progress(task) : <div className="row-sub mono">{c.name} · {gb(c.bytes)}</div>}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{task ? (
|
||||
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => backend.cancelTask(task.id)} />
|
||||
) : (
|
||||
<>
|
||||
{!c.partial && (c.kind === 'offline' || c.kind === 'online') && (
|
||||
<Button variant={c.kind === 'offline' ? 'primary' : 'secondary'} icon={<Plus size={14} />} onClick={() => onCreateWithInstaller(c)}>
|
||||
{tr('installersCreateVM')}
|
||||
</Button>
|
||||
)}
|
||||
{c.partial && c.kind === 'offline' && c.version && (
|
||||
<Button icon={<Download size={14} />} onClick={() => download(c.version!)}>{tr('installersResume')}</Button>
|
||||
)}
|
||||
{confirmDelete === c.name ? (
|
||||
<Button variant="danger" onClick={() => remove(c.name)}>{tr('installersDeleteConfirm')}</Button>
|
||||
) : (
|
||||
<IconButton label={tr('installersDelete')} icon={<Trash size={15} />} onClick={() => remove(c.name)} />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('installersAvailable')}</div>
|
||||
<div className="list">
|
||||
{releasesErr ? (
|
||||
<div className="row"><span className="row-sub">{tr('offlineListFailed')}:{releasesErr}</span></div>
|
||||
) : releases === null ? (
|
||||
<div className="row"><span className="row-sub">{tr('offlineLoading')}</span></div>
|
||||
) : releases.map((r) => {
|
||||
const task = running(r.version)
|
||||
const done = isDownloaded(r.version)
|
||||
const short = !done && !task && host.free_disk_gb > 0 && host.free_disk_gb * 1e9 < needBytes(r)
|
||||
return (
|
||||
<div className="row" key={r.product}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{r.title} {r.version}
|
||||
<span className="muted">({r.build})</span>
|
||||
</div>
|
||||
{task ? progress(task) : (
|
||||
<div className="row-sub">
|
||||
{r.posted} · {gb(r.size)}
|
||||
{short && <span className="warn-text"> · {tr('installersNoSpace', { need: Math.ceil(needBytes(r) / 1e9), free: host.free_disk_gb.toFixed(0) })}</span>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{task ? (
|
||||
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => backend.cancelTask(task.id)} />
|
||||
) : done ? (
|
||||
<span className="badge badge-ok">{tr('offlineCached')}</span>
|
||||
) : (
|
||||
<Button icon={<Download size={14} />} disabled={short} onClick={() => download(r.version)}>{tr('installersDownload')}</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<span className="hint">{tr('installersHint')}</span>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { taskDetail, taskTitle } from '../lib/tasks'
|
||||
import { Locale, Task } from '../types'
|
||||
import { Button, IconButton, Tip } from '../ui/controls'
|
||||
|
||||
export type LogTab = 'app' | 'serial'
|
||||
export type LogTab = 'app' | 'serial' | 'qemu'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
@@ -18,8 +18,10 @@ interface Props {
|
||||
unseenErrors: number
|
||||
onClear: () => void
|
||||
serialText: string
|
||||
qemuText: string
|
||||
showSerial: boolean
|
||||
onRefreshSerial: () => void
|
||||
onRefreshQemu: () => void
|
||||
task: Task | null
|
||||
runningTasks: number
|
||||
onCancelTask: (id: string) => void
|
||||
@@ -49,11 +51,11 @@ function useStickToBottom(dep: unknown, active: boolean) {
|
||||
}
|
||||
|
||||
export const LogPanel: React.FC<Props> = ({
|
||||
locale, open, onToggle, tab, onTab, lines, unseenErrors, onClear, serialText, showSerial, onRefreshSerial,
|
||||
locale, open, onToggle, tab, onTab, lines, unseenErrors, onClear, serialText, qemuText, showSerial, onRefreshSerial, onRefreshQemu,
|
||||
task, runningTasks, onCancelTask,
|
||||
}) => {
|
||||
const tr = (k: Parameters<typeof t>[1]) => t(locale, k)
|
||||
const content = tab === 'app' ? lines : serialText
|
||||
const content = tab === 'app' ? lines : tab === 'serial' ? serialText : qemuText
|
||||
const { ref, stuck, onScroll, jump } = useStickToBottom(content, open)
|
||||
|
||||
return (
|
||||
@@ -87,9 +89,14 @@ export const LogPanel: React.FC<Props> = ({
|
||||
{tr('logActivity')}
|
||||
</button>
|
||||
{showSerial && (
|
||||
<button type="button" role="tab" className="tab" aria-selected={tab === 'serial'} onClick={() => onTab('serial')}>
|
||||
{tr('logSerial')}
|
||||
</button>
|
||||
<>
|
||||
<button type="button" role="tab" className="tab" aria-selected={tab === 'serial'} onClick={() => onTab('serial')}>
|
||||
{tr('logSerial')}
|
||||
</button>
|
||||
<button type="button" role="tab" className="tab" aria-selected={tab === 'qemu'} onClick={() => onTab('qemu')}>
|
||||
{tr('logQemu')}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@@ -99,6 +106,9 @@ export const LogPanel: React.FC<Props> = ({
|
||||
{open && tab === 'serial' && (
|
||||
<IconButton small tipSide="top" label={tr('refresh')} icon={<RefreshCw size={14} />} onClick={onRefreshSerial} />
|
||||
)}
|
||||
{open && tab === 'qemu' && (
|
||||
<IconButton small tipSide="top" label={tr('refresh')} icon={<RefreshCw size={14} />} onClick={onRefreshQemu} />
|
||||
)}
|
||||
{!open && unseenErrors > 0 && <span className="badge badge-error" aria-hidden="true">{unseenErrors}</span>}
|
||||
<IconButton
|
||||
small
|
||||
@@ -124,7 +134,9 @@ export const LogPanel: React.FC<Props> = ({
|
||||
<span className="log-msg">{l.line}</span>
|
||||
</div>
|
||||
)))
|
||||
: (serialText || <span className="muted">{tr('logsEmpty')}</span>)}
|
||||
: tab === 'serial'
|
||||
? (serialText || <span className="muted">{tr('logsEmpty')}</span>)
|
||||
: (qemuText || <span className="muted">{tr('logsEmpty')}</span>)}
|
||||
</div>
|
||||
{!stuck && (
|
||||
<Button className="jump-latest" icon={<ArrowDown size={14} />} onClick={jump}>
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import * as Alert from '@radix-ui/react-alert-dialog'
|
||||
import React from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { Locale } from '../types'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
name: string
|
||||
onCancel: () => void
|
||||
onConfirm: () => void
|
||||
}
|
||||
|
||||
export const OnlineRecoveryDialog: React.FC<Props> = ({ locale, name, onCancel, onConfirm }) => (
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog sm">
|
||||
<div className="dialog-body">
|
||||
<Alert.Title className="dialog-title">{t(locale, 'onlineRecoveryTitle')}</Alert.Title>
|
||||
<Alert.Description className="dialog-desc">
|
||||
{t(locale, 'onlineRecoveryDesc', { name })}
|
||||
</Alert.Description>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild>
|
||||
<button type="button" className="btn">{t(locale, 'cancel')}</button>
|
||||
</Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button type="button" className="btn btn-primary" onClick={onConfirm}>
|
||||
{t(locale, 'onlineRecoveryConfirm')}
|
||||
</button>
|
||||
</Alert.Action>
|
||||
</div>
|
||||
</Alert.Content>
|
||||
</Alert.Portal>
|
||||
</Alert.Root>
|
||||
)
|
||||
@@ -0,0 +1,115 @@
|
||||
import { Download, LoaderCircle, Pause } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { taskDetail } from '../lib/tasks'
|
||||
import { InstalledRuntime, Locale, RemoteRuntime, Task } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { backend } from '../wails'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
channel: 'stable' | 'candidate'
|
||||
installed: InstalledRuntime[]
|
||||
task: Task | null
|
||||
onChannel: (candidate: boolean) => void
|
||||
onInstall: (commit: string) => void
|
||||
onCancel: (taskId: string) => void
|
||||
}
|
||||
|
||||
const gb = (b: number) => (b >= 1e9 ? `${(b / 1e9).toFixed(1)} GB` : `${Math.ceil(b / 1e6)} MB`)
|
||||
|
||||
/** "QEMU emulator version 11.1.90" → "QEMU 11.1.90". */
|
||||
const shortQemu = (v: string) => v.replace(/^QEMU emulator version\s*/i, 'QEMU ')
|
||||
|
||||
/**
|
||||
* The runtime rows: the active runtime and whether it is current (or, with
|
||||
* none installed, the newest release to install), then the candidate switch.
|
||||
*/
|
||||
export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, task, onChannel, onInstall, onCancel }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [remote, setRemote] = useState<RemoteRuntime[] | null>(null)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
setRemote(null)
|
||||
setError('')
|
||||
backend.listRemoteRuntimes()
|
||||
.then((list) => { if (live) setRemote(list ?? []) })
|
||||
.catch((e) => { if (live) setError(String(e).replace(/^Error:\s*/, '')) })
|
||||
return () => { live = false }
|
||||
}, [channel, task?.status === 'done'])
|
||||
|
||||
const active = installed.find((i) => i.active) ?? installed[0]
|
||||
const latest = remote?.[0]
|
||||
const isInstalled = (c: string) => installed.some((i) => i.commit.startsWith(c) || c.startsWith(i.commit))
|
||||
const running = task?.status === 'running'
|
||||
const updatable = !!latest && !isInstalled(latest.commit)
|
||||
|
||||
let sub: React.ReactNode
|
||||
if (running && task) {
|
||||
sub = (
|
||||
<div className="row-sub task-inline">
|
||||
<LoaderCircle size={14} className="spin" />
|
||||
{task.percent >= 0 && <span className="progress"><div style={{ width: `${task.percent}%` }} /></span>}
|
||||
<span>{task.percent >= 0 ? `${Math.floor(task.percent)}%` : ''} {taskDetail(task)}</span>
|
||||
</div>
|
||||
)
|
||||
} else if (active && !updatable) {
|
||||
sub = <div className="row-sub">{shortQemu(active.manifest.qemu_version)}</div>
|
||||
} else if (error) {
|
||||
sub = <div className="row-sub" title={error}>{tr('runtimeLookupFailed')}</div>
|
||||
} else if (!remote) {
|
||||
sub = <div className="row-sub">…</div>
|
||||
} else if (!latest) {
|
||||
sub = <div className="row-sub">{tr('runtimeNoneOnChannel')}</div>
|
||||
} else {
|
||||
sub = (
|
||||
<div className="row-sub">
|
||||
{active ? tr('runtimeNewer', { v: latest.commit }) : tr('runtimeLatest', { v: latest.commit })}
|
||||
{' · '}{tr(`runtimeChannel_${latest.channel}` as I18nKey)} · {gb(latest.archive_size)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{active ? <>{tr('runtimeCurrent')} <span className="mono">{active.commit}</span></> : tr('runtimeOnline')}
|
||||
</div>
|
||||
{sub}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{running && task?.cancelable ? (
|
||||
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => onCancel(task.id)} />
|
||||
) : !running && updatable ? (
|
||||
<Button variant="primary" icon={<Download size={14} />} onClick={() => onInstall(latest!.commit)}>
|
||||
{tr(active ? 'runtimeUpdate' : 'runtimeInstall')}
|
||||
</Button>
|
||||
) : !running && active && remote ? (
|
||||
<span className="badge badge-ok">{tr('runtimeUpToDate')}</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('runtimeCandidate')}</div>
|
||||
<div className="row-sub">{tr('runtimeCandidateHint')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<label className="switch">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={tr('runtimeCandidate')}
|
||||
checked={channel === 'candidate'}
|
||||
onChange={(e) => onChannel(e.target.checked)}
|
||||
/>
|
||||
<span className="slider" />
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,15 @@
|
||||
import React, { useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { shortGPUName } from '../lib/format'
|
||||
import { HostReport, Locale, SetOpts, ValidationIssue, VMDetail } from '../types'
|
||||
import { recommendedMemoryGB, shortGPUName } from '../lib/format'
|
||||
import {
|
||||
applyKernelIrqchip,
|
||||
findOptimization,
|
||||
kernelIrqchipHint,
|
||||
optBadgeClass,
|
||||
optStatusLabel,
|
||||
parseKernelIrqchip,
|
||||
} from '../lib/optimizations'
|
||||
import { HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMDetail } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { backend } from '../wails'
|
||||
@@ -25,13 +33,15 @@ interface Props {
|
||||
locale: Locale
|
||||
detail: VMDetail
|
||||
host: HostReport
|
||||
optimizations?: Optimization[]
|
||||
running: boolean
|
||||
onClose: () => void
|
||||
onSaved: () => void
|
||||
}
|
||||
|
||||
export const SettingsModal: React.FC<Props> = ({ locale, detail, host, running, onClose, onSaved }) => {
|
||||
export const SettingsModal: React.FC<Props> = ({ locale, detail, host, optimizations, running, onClose, onSaved }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const irqOpt = findOptimization(optimizations, 'kernel_irqchip')
|
||||
const [cat, setCat] = useState<Cat>('cpu')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [issues, setIssues] = useState<ValidationIssue[]>([])
|
||||
@@ -176,7 +186,11 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, host, running,
|
||||
<label className="field-label" htmlFor="set-mem">{tr('factMemory')} · {tr('hostMemory', { n: host.total_ram_gb.toFixed(0) })}</label>
|
||||
{presets(['4G', '8G', '12G', '16G', '24G'], form.memory, (m) => m, (memory) => set({ memory }))}
|
||||
<input id="set-mem" className="input" value={form.memory ?? ''} onChange={(e) => set({ memory: e.target.value })} />
|
||||
<span className="hint">{tr('memHint')}</span>
|
||||
<span className="hint">
|
||||
{host.commit_avail_gb > 0
|
||||
? tr('memCommitHint', { avail: host.commit_avail_gb.toFixed(1), rec: recommendedMemoryGB(host) })
|
||||
: tr('memHint')}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -193,7 +207,9 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, host, running,
|
||||
<option value="nvme">NVMe</option>
|
||||
<option value="virtio">VirtIO</option>
|
||||
</select>
|
||||
{detail.has_installer && <span className="hint warn">{tr('diskControllerWarn')}</span>}
|
||||
{detail.has_installer
|
||||
? <span className="hint warn">{tr('diskControllerWarn')} · {tr('diskControllerInstallHint')}</span>
|
||||
: form.disk_controller === 'ahci' && <span className="hint">{tr('diskControllerNvmeHint')}</span>}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
@@ -224,6 +240,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, host, running,
|
||||
<option value="auto">{tr('gpuAutoOption')}</option>
|
||||
{realGPUs.map((g) => <option key={g.vulkan_icd} value={g.vulkan_icd}>{shortGPUName(g.name)}</option>)}
|
||||
</select>
|
||||
{realGPUs.length === 0 && <span className="hint warn">{tr('gpuUnavailableHint')}</span>}
|
||||
</div>
|
||||
<div className="field-row">
|
||||
<div className="field">
|
||||
@@ -240,7 +257,12 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, host, running,
|
||||
)}
|
||||
|
||||
{cat === 'audio' && check('audio', 'enableAudio')}
|
||||
{cat === 'input' && check('capture', 'captureInput')}
|
||||
{cat === 'input' && (
|
||||
<>
|
||||
{check('capture', 'captureInput')}
|
||||
<span className="hint">{tr('captureInputHint')}</span>
|
||||
</>
|
||||
)}
|
||||
|
||||
{cat === 'logs' && (
|
||||
<>
|
||||
@@ -254,6 +276,40 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, host, running,
|
||||
|
||||
{cat === 'advanced' && (
|
||||
<>
|
||||
<div className="field">
|
||||
<label className="field-label">
|
||||
{tr('kernelIrqchipLabel')}
|
||||
{' '}
|
||||
<span className={`badge ${optBadgeClass(irqOpt?.status)}`}>{optStatusLabel(locale, irqOpt?.status)}</span>
|
||||
</label>
|
||||
<div className="segmented" role="group" aria-label={tr('kernelIrqchipLabel')}>
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={parseKernelIrqchip(form.extra_args) === 'auto'}
|
||||
onClick={() => set({ extra_args: applyKernelIrqchip(form.extra_args, 'auto') })}
|
||||
>
|
||||
{tr('kernelIrqchipAuto')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!irqOpt?.supported}
|
||||
aria-pressed={parseKernelIrqchip(form.extra_args) === 'on'}
|
||||
onClick={() => set({ extra_args: applyKernelIrqchip(form.extra_args, 'on') })}
|
||||
>
|
||||
{tr('kernelIrqchipOn')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={parseKernelIrqchip(form.extra_args) === 'off'}
|
||||
onClick={() => set({ extra_args: applyKernelIrqchip(form.extra_args, 'off') })}
|
||||
>
|
||||
{tr('kernelIrqchipOff')}
|
||||
</button>
|
||||
</div>
|
||||
<span className={`hint ${irqOpt?.status === 'unavailable' && irqOpt.detail?.startsWith('0x') ? 'warn' : ''}`}>
|
||||
{kernelIrqchipHint(locale, irqOpt)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label className="field-label" htmlFor="set-timeout">{tr('stopTimeout')}</label>
|
||||
<input id="set-timeout" className="input" type="number" min={0} value={form.stop_timeout ?? 90} onChange={(e) => set({ stop_timeout: Number(e.target.value) })} />
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
import { FolderOpen, HardDrive } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { AppState, DataRootCheck, DataRootChoice, Locale, Task } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { recommendedMemoryGB, shortGPUName } from '../lib/format'
|
||||
import { backend } from '../wails'
|
||||
import { RuntimeOnline } from './RuntimeOnline'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
state: AppState
|
||||
stage: 'folder' | 'runtime'
|
||||
runtimeTask: Task | null
|
||||
onLocale: (l: Locale) => void
|
||||
onFolderDone: () => void
|
||||
onFinish: () => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
onChannel: (candidate: boolean) => void
|
||||
onInstallRuntime: (commit: string) => void
|
||||
onCancelTask: (id: string) => void
|
||||
onImportRuntime: () => void
|
||||
}
|
||||
|
||||
const LOW_SPACE_GB = 60
|
||||
|
||||
/** First launch: choose the data folder, then (optionally) install the runtime. */
|
||||
export const Setup: React.FC<Props> = (p) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(p.locale, k, v)
|
||||
return (
|
||||
<div className="setup">
|
||||
<div className="setup-card">
|
||||
{p.stage === 'folder' ? <FolderStep {...p} tr={tr} /> : <RuntimeStep {...p} tr={tr} />}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type StepProps = Props & { tr: (k: I18nKey, v?: Record<string, string | number>) => string }
|
||||
|
||||
const FolderStep: React.FC<StepProps> = ({ locale, tr, onLocale, onFolderDone, onError }) => {
|
||||
const [choices, setChoices] = useState<DataRootChoice[]>([])
|
||||
const [custom, setCustom] = useState('')
|
||||
const [customMode, setCustomMode] = useState(false)
|
||||
const [selected, setSelected] = useState('')
|
||||
const [check, setCheck] = useState<DataRootCheck | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
backend.suggestDataRoots().then((list) => {
|
||||
const l = list ?? []
|
||||
setChoices(l)
|
||||
const rec = l.find((c) => c.recommended) ?? l[0]
|
||||
if (rec) setSelected(rec.path)
|
||||
}).catch((e) => onError(tr('failGeneric'), e))
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!selected) { setCheck(null); return }
|
||||
let live = true
|
||||
backend.checkDataRoot(selected).then((c) => { if (live) setCheck(c) }).catch(() => {})
|
||||
return () => { live = false }
|
||||
}, [selected])
|
||||
|
||||
const browse = async () => {
|
||||
const dir = await backend.pickDirectory(tr('setupTitle')).catch(() => '')
|
||||
if (dir) { setCustom(dir); setCustomMode(true); setSelected(dir) }
|
||||
}
|
||||
|
||||
const next = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
await backend.completeSetup(selected)
|
||||
onFolderDone()
|
||||
} catch (e) {
|
||||
onError(tr('failGeneric'), e)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const option = (path: string, meta: React.ReactNode) => (
|
||||
<label key={path} className="choice-card" data-selected={selected === path}>
|
||||
<input type="radio" name="data-root" checked={selected === path} onChange={() => setSelected(path)} />
|
||||
<HardDrive size={18} aria-hidden="true" />
|
||||
<span className="choice-card-main">
|
||||
<span className="mono choice-card-path">{path}</span>
|
||||
<span className="choice-card-meta">{meta}</span>
|
||||
</span>
|
||||
</label>
|
||||
)
|
||||
|
||||
const notices: string[] = []
|
||||
if (check?.error) notices.push(check.error)
|
||||
else if (check) {
|
||||
if (check.system) notices.push(tr('setupWarnSystem'))
|
||||
if (check.external) notices.push(tr('setupWarnExternal'))
|
||||
if (check.free_gb > 0 && check.free_gb < LOW_SPACE_GB) notices.push(tr('setupWarnSpace'))
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="setup-head">
|
||||
<h1>{tr('setupTitle')}</h1>
|
||||
<p>{tr('setupDesc')}</p>
|
||||
</div>
|
||||
<div className="choices-list" role="radiogroup" aria-label={tr('setupTitle')}>
|
||||
{choices.map((c) => option(c.path, (
|
||||
<>
|
||||
{tr('setupFree', { n: c.free_gb.toFixed(0) })}
|
||||
{c.recommended && <span className="badge badge-accent">{tr('setupRecommended')}</span>}
|
||||
{c.system && <span className="badge">{tr('setupSystem')}</span>}
|
||||
{c.external && <span className="badge badge-warn">{tr('setupExternal')}</span>}
|
||||
</>
|
||||
)))}
|
||||
{customMode ? (
|
||||
<div className="input-group">
|
||||
<input
|
||||
className="input mono"
|
||||
aria-label={tr('setupOther')}
|
||||
value={custom}
|
||||
placeholder="D:\VMs\reims-go"
|
||||
autoFocus
|
||||
onFocus={() => custom && setSelected(custom)}
|
||||
onChange={(e) => { setCustom(e.target.value); setSelected(e.target.value.trim()) }}
|
||||
/>
|
||||
<Button icon={<FolderOpen size={14} />} onClick={browse}>{tr('choose')}</Button>
|
||||
</div>
|
||||
) : (
|
||||
<Button variant="ghost" icon={<FolderOpen size={14} />} onClick={() => setCustomMode(true)} className="choice-other">{tr('setupOther')}</Button>
|
||||
)}
|
||||
</div>
|
||||
{notices.length > 0 && (
|
||||
<div className={check?.error ? 'notice notice-error' : 'hint warn'}>{notices.join(';')}</div>
|
||||
)}
|
||||
{!check?.error && check?.has_config && <div className="hint">{tr('setupReuse')}</div>}
|
||||
{customMode && check && check.path === custom && !check.error && (
|
||||
<div className="hint">{tr('setupFree', { n: check.free_gb.toFixed(0) })}</div>
|
||||
)}
|
||||
<div className="setup-foot">
|
||||
<div className="segmented" role="group" aria-label={tr('language')}>
|
||||
<button type="button" aria-pressed={locale === 'zh-CN'} onClick={() => onLocale('zh-CN')}>中文</button>
|
||||
<button type="button" aria-pressed={locale === 'en-US'} onClick={() => onLocale('en-US')}>English</button>
|
||||
</div>
|
||||
<Button variant="primary" busy={busy} disabled={!selected || !!check?.error} onClick={next}>{tr('setupContinue')}</Button>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onChannel, onInstallRuntime, onCancelTask, onImportRuntime, onFinish, onError }) => {
|
||||
const ready = !!state.active_runtime
|
||||
const { host } = state
|
||||
const [enabling, setEnabling] = useState(false)
|
||||
const enableWHPX = async () => {
|
||||
setEnabling(true)
|
||||
try { await backend.enableWHPX() } catch (e) { onError(tr('failGeneric'), e) } finally { setEnabling(false) }
|
||||
}
|
||||
const whpxOK = host.whpx === 'ready'
|
||||
const gpu = host.recommended_gpu ?? (host.gpus ?? []).find((g) => g.kind !== 'virtual')
|
||||
const recMem = recommendedMemoryGB(host)
|
||||
return (
|
||||
<>
|
||||
<div className="setup-head">
|
||||
<h1>{tr('setupRuntimeTitle')}</h1>
|
||||
<p>{tr('setupRuntimeDesc')}</p>
|
||||
</div>
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('setupCheck')}</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('hostWHPX')}</div>
|
||||
{!whpxOK && (
|
||||
<div className="row-sub">
|
||||
{tr(host.whpx === 'missing' ? 'whpxMissing' : host.whpx === 'no_hypervisor' ? 'whpxNoHv' : 'whpxUnsupported')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{host.whpx === 'missing' ? (
|
||||
<Button variant="primary" busy={enabling} onClick={enableWHPX}>{tr('enableWHPX')}</Button>
|
||||
) : (
|
||||
<span className={`badge ${whpxOK ? 'badge-ok' : 'badge-warn'}`}>
|
||||
{tr(whpxOK ? 'whpxReady' : host.whpx === 'no_hypervisor' ? 'whpxNoHvShort' : 'whpxUnsupportedShort')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('setupGPU')}</div>
|
||||
<div className="row-sub">{gpu ? shortGPUName(gpu.name) : tr('setupNoGPU')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<span className={`badge ${gpu ? 'badge-ok' : 'badge-warn'}`}>{tr(gpu ? 'whpxReady' : 'hostNeedsAction')}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('hostRAM')}</div>
|
||||
<div className="row-sub">
|
||||
{host.commit_avail_gb > 0
|
||||
? tr('memCommitHint', { avail: host.commit_avail_gb.toFixed(1), rec: recMem })
|
||||
: tr('hostRAMTotal', { n: host.total_ram_gb.toFixed(1) })}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<span className={`badge ${recMem >= 8 ? 'badge-ok' : 'badge-warn'}`}>{tr('setupRecMem', { n: recMem })}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<div className="list">
|
||||
<RuntimeOnline
|
||||
locale={locale}
|
||||
channel={state.config.runtime_channel === 'candidate' ? 'candidate' : 'stable'}
|
||||
installed={state.runtimes ?? []}
|
||||
task={runtimeTask}
|
||||
onChannel={onChannel}
|
||||
onInstall={onInstallRuntime}
|
||||
onCancel={onCancelTask}
|
||||
/>
|
||||
</div>
|
||||
<div className="setup-foot">
|
||||
<Button variant="ghost" onClick={onImportRuntime}>{tr('setupImport')}</Button>
|
||||
<Button variant={ready ? 'primary' : 'secondary'} disabled={runtimeTask?.status === 'running'} onClick={onFinish}>
|
||||
{tr(ready ? 'setupDone' : 'setupLater')}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Cpu, Monitor, Plus } from 'lucide-react'
|
||||
import { Cpu, Download, Monitor, Plus } from 'lucide-react'
|
||||
import React, { useRef } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { Locale, VMListItem } from '../types'
|
||||
import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
|
||||
|
||||
export const HOST_ID = '__host__'
|
||||
export const INSTALLERS_ID = '__installers__'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
@@ -14,11 +15,13 @@ interface Props {
|
||||
hostReady: boolean
|
||||
onSelect: (id: string) => void
|
||||
onNew: () => void
|
||||
/** An installer download is running (busy dot on the Installers entry). */
|
||||
downloading?: boolean
|
||||
}
|
||||
|
||||
export const Sidebar: React.FC<Props> = ({ locale, vms, transitions, selected, hostReady, onSelect, onNew }) => {
|
||||
export const Sidebar: React.FC<Props> = ({ locale, vms, transitions, selected, hostReady, onSelect, onNew, downloading }) => {
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
const ids = [...vms.map((v) => v.name), HOST_ID]
|
||||
const ids = [...vms.map((v) => v.name), INSTALLERS_ID, HOST_ID]
|
||||
|
||||
// Listbox keyboard model: ↑/↓/Home/End move selection and focus together.
|
||||
const onKeyDown = (e: React.KeyboardEvent) => {
|
||||
@@ -34,7 +37,14 @@ export const Sidebar: React.FC<Props> = ({ locale, vms, transitions, selected, h
|
||||
listRef.current?.querySelector<HTMLElement>(`[data-id="${CSS.escape(ids[next])}"]`)?.focus()
|
||||
}
|
||||
|
||||
const item = (id: string, label: string, icon: React.ReactNode, stateLabel: string, kind: ReturnType<typeof statusKind>) => (
|
||||
const item = (
|
||||
id: string,
|
||||
label: string,
|
||||
icon: React.ReactNode,
|
||||
badgeClass: string,
|
||||
stateLabel: string,
|
||||
kind: ReturnType<typeof statusKind> | null,
|
||||
) => (
|
||||
<button
|
||||
key={id}
|
||||
type="button"
|
||||
@@ -42,39 +52,52 @@ export const Sidebar: React.FC<Props> = ({ locale, vms, transitions, selected, h
|
||||
data-id={id}
|
||||
className="nav-item"
|
||||
aria-selected={selected === id}
|
||||
aria-label={`${label},${stateLabel}`}
|
||||
aria-label={stateLabel ? `${label},${stateLabel}` : label}
|
||||
tabIndex={selected === id ? 0 : -1}
|
||||
onClick={() => onSelect(id)}
|
||||
>
|
||||
{icon}
|
||||
<span className={`nav-icon-badge ${badgeClass}`} aria-hidden="true">{icon}</span>
|
||||
<span className="nav-label">{label}</span>
|
||||
<Tip label={stateLabel} side="right">
|
||||
<span className="hstack"><StatusShape kind={kind} /></span>
|
||||
</Tip>
|
||||
{kind && (
|
||||
<Tip label={stateLabel} side="right">
|
||||
<span className="hstack"><StatusShape kind={kind} /></span>
|
||||
</Tip>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
|
||||
return (
|
||||
<aside className="sidebar">
|
||||
<div className="sidebar-head">
|
||||
<span>{t(locale, 'sidebarVMs')}</span>
|
||||
<IconButton small label={t(locale, 'newVM')} shortcut="Ctrl+N" icon={<Plus size={16} />} onClick={onNew} tipSide="right" />
|
||||
</div>
|
||||
<div className="nav" role="listbox" aria-label={t(locale, 'sidebarVMs')} ref={listRef} onKeyDown={onKeyDown}>
|
||||
{vms.length === 0 && <div className="nav-empty">{t(locale, 'emptyVMs')}</div>}
|
||||
{vms.map((vm) => {
|
||||
const st = transitions[vm.name] ?? vm.state
|
||||
return item(vm.name, vm.name, <Monitor size={16} />, t(locale, `state_${st}` as I18nKey), statusKind(st))
|
||||
})}
|
||||
<div className="sidebar-sep" role="presentation" />
|
||||
{item(
|
||||
HOST_ID,
|
||||
t(locale, 'sidebarHost'),
|
||||
<Cpu size={16} />,
|
||||
t(locale, hostReady ? 'hostReady' : 'hostNeedsAction'),
|
||||
hostReady ? 'running' : 'warn',
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
<div className="sidebar-wrap">
|
||||
<aside className="sidebar">
|
||||
<div className="sidebar-head">
|
||||
<span>{t(locale, 'sidebarVMs')}</span>
|
||||
<IconButton small label={t(locale, 'newVM')} shortcut="Ctrl+N" icon={<Plus size={15} />} onClick={onNew} tipSide="right" />
|
||||
</div>
|
||||
<div className="nav" role="listbox" aria-label={t(locale, 'sidebarVMs')} ref={listRef} onKeyDown={onKeyDown}>
|
||||
{vms.length === 0 && <div className="nav-empty">{t(locale, 'emptyVMs')}</div>}
|
||||
{vms.map((vm) => {
|
||||
const st = transitions[vm.name] ?? vm.state
|
||||
return item(vm.name, vm.name, <Monitor size={13} />, 'nav-icon-vm', t(locale, `state_${st}` as I18nKey), statusKind(st))
|
||||
})}
|
||||
<div className="sidebar-sep" role="presentation" />
|
||||
{item(
|
||||
INSTALLERS_ID,
|
||||
t(locale, 'sidebarInstallers'),
|
||||
<Download size={13} />,
|
||||
'nav-icon-installers',
|
||||
downloading ? t(locale, 'state_starting') : '',
|
||||
downloading ? 'busy' : null,
|
||||
)}
|
||||
{item(
|
||||
HOST_ID,
|
||||
t(locale, 'sidebarHost'),
|
||||
<Cpu size={13} />,
|
||||
'nav-icon-host',
|
||||
t(locale, hostReady ? 'hostReady' : 'hostNeedsAction'),
|
||||
hostReady ? 'running' : 'warn',
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
import * as Menu from '@radix-ui/react-dropdown-menu'
|
||||
import {
|
||||
Archive,
|
||||
ChevronRight,
|
||||
Copy,
|
||||
Cpu,
|
||||
CopyPlus,
|
||||
Disc,
|
||||
Ellipsis,
|
||||
FolderOpen,
|
||||
Gpu,
|
||||
HardDrive,
|
||||
MemoryStick,
|
||||
Keyboard,
|
||||
LifeBuoy,
|
||||
Play,
|
||||
Power,
|
||||
RotateCw,
|
||||
@@ -22,7 +23,29 @@ import { controllerLabel, formatMemory, graphicsLabel, sshCommand } from '../lib
|
||||
import { HostReport, Locale, PendingChange, VMDetail } from '../types'
|
||||
import { Button, IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
|
||||
|
||||
export type VMAction = 'start' | 'stop' | 'forceStop' | 'restart' | 'eject' | 'delete' | 'openFolder'
|
||||
export type VMAction =
|
||||
| 'start'
|
||||
| 'stop'
|
||||
| 'forceStop'
|
||||
| 'restart'
|
||||
| 'eject'
|
||||
| 'finishInstall'
|
||||
| 'enterRecovery'
|
||||
| 'attachInstaller'
|
||||
| 'attachGuestTools'
|
||||
| 'detachGuestTools'
|
||||
| 'openSharedFolder'
|
||||
| 'upgradeNVMe'
|
||||
| 'exportDiagnostics'
|
||||
| 'cloneVM'
|
||||
| 'type'
|
||||
| 'delete'
|
||||
| 'openFolder'
|
||||
|
||||
// Runs from reims-go's pre-extracted HFS+ helper disk (REIMSHELP), bypassing
|
||||
// macOS Recovery's `installer -target` fallback to read-only `/` and missing `pkgutil`.
|
||||
const OFFLINE_INSTALL_CMD = 'sh /Volumes/REIMSHELP/install.sh'
|
||||
const GUEST_TOOLS_INSTALL_CMD = 'sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
@@ -37,10 +60,11 @@ interface Props {
|
||||
onDelete: () => void
|
||||
onViewLogs: () => void
|
||||
onCopy: (text: string) => void
|
||||
onTypeText: (text: string) => void
|
||||
}
|
||||
|
||||
export const VMPage: React.FC<Props> = ({
|
||||
locale, name, state, detail, host, pending, busyAction, onAction, onSettings, onDelete, onViewLogs, onCopy,
|
||||
locale, name, state, detail, host, pending, busyAction, onAction, onSettings, onDelete, onViewLogs, onCopy, onTypeText,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const busy = busyAction !== undefined
|
||||
@@ -66,23 +90,19 @@ export const VMPage: React.FC<Props> = ({
|
||||
<div className="page">
|
||||
<header className="page-head">
|
||||
<div className="page-title">
|
||||
<h1>{name}</h1>
|
||||
<span className="state-text">
|
||||
<StatusShape kind={statusKind(state)} />
|
||||
{tr(`state_${state}` as I18nKey)}
|
||||
</span>
|
||||
<h1>{locale === 'zh-CN' ? '关于此虚拟机' : 'About This VM'}</h1>
|
||||
</div>
|
||||
<div className="actions">
|
||||
{primary}
|
||||
{running && (
|
||||
<IconButton label={tr('stop')} icon={<Square size={15} />} busy={busyAction === 'stop'} disabled={busy} onClick={() => onAction('stop')} />
|
||||
<IconButton label={tr('stop')} icon={<Square size={14} />} busy={busyAction === 'stop'} disabled={busy} onClick={() => onAction('stop')} />
|
||||
)}
|
||||
<IconButton label={tr('settings')} shortcut="Ctrl+," icon={<Settings size={16} />} disabled={!detail} onClick={onSettings} />
|
||||
<IconButton label={tr('settings')} shortcut="Ctrl+," icon={<Settings size={15} />} disabled={!detail} onClick={onSettings} />
|
||||
<Menu.Root>
|
||||
<Tip label={tr('more')}>
|
||||
<Menu.Trigger asChild>
|
||||
<button type="button" className="icon-btn" aria-label={tr('more')}>
|
||||
<Ellipsis size={16} />
|
||||
<Ellipsis size={15} />
|
||||
</button>
|
||||
</Menu.Trigger>
|
||||
</Tip>
|
||||
@@ -93,17 +113,40 @@ export const VMPage: React.FC<Props> = ({
|
||||
<RotateCw size={14} /> {tr('restart')}
|
||||
</Menu.Item>
|
||||
)}
|
||||
{running && (
|
||||
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('type')}>
|
||||
<Keyboard size={14} /> {tr('typeClipboard')}
|
||||
</Menu.Item>
|
||||
)}
|
||||
{(running || transitioning) && (
|
||||
<Menu.Item className="menu-item danger" disabled={busyAction === 'forceStop'} onSelect={() => onAction('forceStop')}>
|
||||
<Power size={14} /> {tr('forceStop')}
|
||||
</Menu.Item>
|
||||
)}
|
||||
{detail && !detail.has_installer && !detail.recovery_mode && (
|
||||
<Menu.Item className="menu-item" disabled={busy || transitioning} onSelect={() => onAction('enterRecovery')}>
|
||||
<LifeBuoy size={14} /> {tr('enterRecovery')}
|
||||
</Menu.Item>
|
||||
)}
|
||||
{detail && (detail.has_installer || detail.recovery_mode) && (
|
||||
<Menu.Item className="menu-item" disabled={busy || transitioning} onSelect={() => onAction('finishInstall')}>
|
||||
<LifeBuoy size={14} /> {tr('finishInstall')}
|
||||
</Menu.Item>
|
||||
)}
|
||||
{detail && !detail.has_installer && !detail.recovery_mode && (
|
||||
<Menu.Item className="menu-item" disabled={running || transitioning || busy} onSelect={() => onAction('cloneVM')}>
|
||||
<CopyPlus size={14} /> {tr('cloneVM')}
|
||||
</Menu.Item>
|
||||
)}
|
||||
<Menu.Item className="menu-item" onSelect={() => onAction('openFolder')}>
|
||||
<FolderOpen size={14} /> {tr('openFolder')}
|
||||
</Menu.Item>
|
||||
<Menu.Item className="menu-item" onSelect={onViewLogs}>
|
||||
<Terminal size={14} /> {tr('viewLogs')}
|
||||
</Menu.Item>
|
||||
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('exportDiagnostics')}>
|
||||
<Archive size={14} /> {tr('exportDiagnostics')}
|
||||
</Menu.Item>
|
||||
<Menu.Separator className="menu-sep" />
|
||||
<Menu.Item className="menu-item danger" disabled={running || transitioning || busy} onSelect={onDelete}>
|
||||
<Trash size={14} /> {tr('delete')}
|
||||
@@ -114,6 +157,15 @@ export const VMPage: React.FC<Props> = ({
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="vm-hero">
|
||||
<IMacIcon running={running} />
|
||||
<div className="vm-hero-name">{name}</div>
|
||||
<span className="vm-hero-pill">
|
||||
<StatusShape kind={statusKind(state)} />
|
||||
{tr(`state_${state}` as I18nKey)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{state === 'broken' && <div className="notice notice-error">{tr('brokenHint')}</div>}
|
||||
|
||||
{pending.length > 0 && (
|
||||
@@ -130,23 +182,192 @@ export const VMPage: React.FC<Props> = ({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{detail?.has_installer && (
|
||||
{(host.data_root_drive_type === 'usb' || host.data_root_drive_type === 'removable' || host.data_root_drive_type === 'network') && (
|
||||
<div className="notice">
|
||||
<span>{tr('diagExternalDriveWarn', { dir: host.data_root })}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(host.memory_load_pct ?? 0) >= 85 && (
|
||||
<div className="notice">
|
||||
<span>{tr('diagHighMemWarn', { pct: host.memory_load_pct ?? 0 })}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{detail && !detail.has_installer && detail.disk_controller === 'ahci' && (
|
||||
<div className="notice">
|
||||
<span>{tr('diagAhciUpgradeHint')}</span>
|
||||
<Button busy={busyAction === 'upgradeNVMe'} disabled={busy} onClick={() => onAction('upgradeNVMe')}>
|
||||
{tr('upgradeToNVMe')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{detail && (detail.has_installer || detail.recovery_mode) && (() => {
|
||||
const hasInstaller = detail.has_installer
|
||||
const isOffline = hasInstaller && /offline-installer/i.test(detail.installer_path ?? '')
|
||||
const badgeKey: I18nKey = !hasInstaller
|
||||
? 'guideKindBuiltIn'
|
||||
: isOffline
|
||||
? 'guideKindOffline'
|
||||
: 'guideKindOnline'
|
||||
return (
|
||||
<section className="card" aria-labelledby="guide-title">
|
||||
<h2 className="card-title" id="guide-title">{tr('guideTitle')}</h2>
|
||||
<ol className="steps">
|
||||
<li>{tr('guideStep1')}</li>
|
||||
<li>{tr('guideStep2')}</li>
|
||||
<li>{tr('guideStep3')}</li>
|
||||
</ol>
|
||||
<h2 className="card-title" id="guide-title">
|
||||
{tr('guideTitle')}{' '}
|
||||
<span className={`badge ${isOffline ? 'badge-ok' : ''}`}>
|
||||
{tr(badgeKey)}
|
||||
</span>
|
||||
</h2>
|
||||
{!hasInstaller ? (
|
||||
<>
|
||||
<ol className="steps">
|
||||
<li>{tr('guideBuiltIn1')}</li>
|
||||
<li>{tr('guideBuiltIn2')}</li>
|
||||
<li>{tr('guideBuiltIn3')}</li>
|
||||
</ol>
|
||||
<div className="card-foot">
|
||||
<Button
|
||||
variant="secondary"
|
||||
icon={<Disc size={14} />}
|
||||
busy={busyAction === 'attachInstaller'}
|
||||
disabled={busy}
|
||||
onClick={() => onAction('attachInstaller')}
|
||||
>
|
||||
{tr('attachInstaller')}
|
||||
</Button>
|
||||
<Button
|
||||
variant={running ? 'primary' : 'secondary'}
|
||||
busy={busyAction === 'finishInstall'}
|
||||
disabled={busy}
|
||||
onClick={() => onAction('finishInstall')}
|
||||
>
|
||||
{tr('finishInstall')}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
) : isOffline ? (
|
||||
<>
|
||||
<ol className="steps">
|
||||
<li>{tr('guideOffline1')}</li>
|
||||
<li>
|
||||
{tr('guideOffline2')}
|
||||
<div className="cmd-line guide-cmd">
|
||||
<code>{OFFLINE_INSTALL_CMD}</code>
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={14} />} onClick={() => onCopy(OFFLINE_INSTALL_CMD)} />
|
||||
{running && (
|
||||
<IconButton
|
||||
small
|
||||
label={tr('typeIntoVM')}
|
||||
icon={<Keyboard size={14} />}
|
||||
busy={busyAction === 'type'}
|
||||
disabled={busy}
|
||||
onClick={() => onTypeText(OFFLINE_INSTALL_CMD)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
<li>{tr('guideOffline3')}</li>
|
||||
</ol>
|
||||
<div className="card-foot">
|
||||
<Button
|
||||
variant={running ? 'primary' : 'secondary'}
|
||||
busy={busyAction === 'finishInstall'}
|
||||
disabled={busy}
|
||||
onClick={() => onAction('finishInstall')}
|
||||
>
|
||||
{tr('finishInstall')}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ol className="steps">
|
||||
<li>{tr('guideStep1')}</li>
|
||||
<li>{tr('guideStep2')}</li>
|
||||
<li>{tr('guideStep3')}</li>
|
||||
</ol>
|
||||
<div className="card-foot">
|
||||
<Button
|
||||
variant={running ? 'primary' : 'secondary'}
|
||||
busy={busyAction === 'finishInstall'}
|
||||
disabled={busy}
|
||||
onClick={() => onAction('finishInstall')}
|
||||
>
|
||||
{tr('finishInstall')}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
})()}
|
||||
|
||||
{detail && !detail.has_installer && !detail.recovery_mode && (
|
||||
<section className="card" aria-labelledby="guest-tools-title">
|
||||
<h2 className="card-title" id="guest-tools-title">
|
||||
{tr('guestToolsTitle')}{' '}
|
||||
<span className={`badge ${detail.guest_tools_connected ? 'badge-ok' : ''}`}>
|
||||
{tr(
|
||||
detail.guest_tools_connected
|
||||
? 'guestToolsConnected'
|
||||
: detail.guest_tools_configured
|
||||
? 'guestToolsReady'
|
||||
: 'guestToolsNotInstalled',
|
||||
)}
|
||||
</span>
|
||||
</h2>
|
||||
<p className="hint" style={{ margin: '0 0 10px' }}>
|
||||
{tr('guestToolsDesc')}
|
||||
</p>
|
||||
{detail.guest_tools_attached && (
|
||||
<div style={{ marginBottom: 10 }}>
|
||||
<div className="hint" style={{ marginBottom: 6 }}>{tr('guestToolsInstallHint')}</div>
|
||||
<div className="cmd-line guide-cmd">
|
||||
<code>{GUEST_TOOLS_INSTALL_CMD}</code>
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={14} />} onClick={() => onCopy(GUEST_TOOLS_INSTALL_CMD)} />
|
||||
{running && (
|
||||
<IconButton
|
||||
small
|
||||
label={tr('typeIntoVM')}
|
||||
icon={<Keyboard size={14} />}
|
||||
busy={busyAction === 'type'}
|
||||
disabled={busy}
|
||||
onClick={() => onTypeText(GUEST_TOOLS_INSTALL_CMD)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="card-foot">
|
||||
<Button
|
||||
variant={running ? 'primary' : 'secondary'}
|
||||
busy={busyAction === 'eject'}
|
||||
variant="secondary"
|
||||
icon={<FolderOpen size={14} />}
|
||||
disabled={busy}
|
||||
onClick={() => onAction('eject')}
|
||||
onClick={() => onAction('openSharedFolder')}
|
||||
>
|
||||
{tr('eject')}
|
||||
{tr('openSharedFolder')}
|
||||
</Button>
|
||||
{detail.guest_tools_attached ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
busy={busyAction === 'detachGuestTools'}
|
||||
disabled={busy}
|
||||
onClick={() => onAction('detachGuestTools')}
|
||||
>
|
||||
{tr('detachGuestTools')}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant={detail.guest_tools_configured ? 'secondary' : 'primary'}
|
||||
icon={<Disc size={14} />}
|
||||
busy={busyAction === 'attachGuestTools'}
|
||||
disabled={busy}
|
||||
onClick={() => onAction('attachGuestTools')}
|
||||
>
|
||||
{tr('attachGuestTools')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
@@ -160,14 +381,66 @@ export const VMPage: React.FC<Props> = ({
|
||||
)}
|
||||
|
||||
{detail && (
|
||||
<div className="facts">
|
||||
<Fact label={tr('factCPU')} icon={<Cpu size={16} />} value={tr('cores', { n: detail.cpus })} />
|
||||
<Fact label={tr('factMemory')} icon={<MemoryStick size={16} />} value={formatMemory(detail.memory)} />
|
||||
<Fact label={tr('factDisk')} icon={<HardDrive size={16} />} value={controllerLabel(detail.disk_controller)} />
|
||||
<Fact label={tr('factGraphics')} icon={<Gpu size={16} />} value={graphicsLabel(locale, detail, host)} />
|
||||
<div className="tahoe-group">
|
||||
<div className="tahoe-row">
|
||||
<span className="tahoe-label">{locale === 'zh-CN' ? '名称' : 'Name'}</span>
|
||||
<span className="tahoe-value">{name}</span>
|
||||
</div>
|
||||
<div className="tahoe-row">
|
||||
<span className="tahoe-label">{tr('factCPU')}</span>
|
||||
<span className="tahoe-value">{tr('cores', { n: detail.cpus })}{detail.cpu_model ? ` · ${detail.cpu_model}` : ''}</span>
|
||||
</div>
|
||||
<div className="tahoe-row">
|
||||
<span className="tahoe-label">{tr('factGraphics')}</span>
|
||||
<span className="tahoe-value">{graphicsLabel(locale, detail, host)}</span>
|
||||
</div>
|
||||
<div className="tahoe-row">
|
||||
<span className="tahoe-label">{tr('factMemory')}</span>
|
||||
<span className="tahoe-value">{formatMemory(detail.memory)}</span>
|
||||
</div>
|
||||
<div className="tahoe-row">
|
||||
<span className="tahoe-label">{tr('factDisk')}</span>
|
||||
<span className="tahoe-value">{controllerLabel(detail.disk_controller)}</span>
|
||||
</div>
|
||||
<div className="tahoe-row">
|
||||
<span className="tahoe-label">{tr('fieldNetwork')}</span>
|
||||
<span className="tahoe-value">{detail.network_summary || tr('off')}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{detail && (
|
||||
<section className="section">
|
||||
<div className="section-title">macOS</div>
|
||||
<div className="tahoe-group">
|
||||
<div className="tahoe-row">
|
||||
<span className="tahoe-label">
|
||||
<span className="tahoe-orb" aria-hidden="true" />
|
||||
macOS Tahoe
|
||||
</span>
|
||||
<span className="tahoe-value">{detail.kind || 'x86-64 WHPX'}</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{detail && (
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('fieldDisplays')}</div>
|
||||
<div className="tahoe-group">
|
||||
<div className="tahoe-row">
|
||||
<span className="tahoe-label">
|
||||
<span className="tahoe-display-icon" aria-hidden="true" />
|
||||
{locale === 'zh-CN' ? '虚拟显示器' : 'Virtual Display'}
|
||||
</span>
|
||||
<span className="tahoe-value">
|
||||
{detail.displays} × {detail.resolution} · {detail.capture ? (locale === 'zh-CN' ? '输入捕获' : 'Input capture') : (locale === 'zh-CN' ? '自由指针' : 'Free pointer')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{detail && (
|
||||
<details className="tech">
|
||||
<summary><ChevronRight size={14} /> {tr('techInfo')}</summary>
|
||||
@@ -178,8 +451,6 @@ export const VMPage: React.FC<Props> = ({
|
||||
<dt>{tr('fieldController')}</dt><dd>{detail.disk_controller}</dd>
|
||||
<dt>{tr('fieldGraphicsBackend')}</dt><dd>{detail.graphics}</dd>
|
||||
{detail.gpu && detail.gpu !== 'auto' && (<><dt>{tr('fieldICD')}</dt><dd className="mono">{detail.gpu}</dd></>)}
|
||||
<dt>{tr('fieldDisplays')}</dt><dd>{detail.displays} × {detail.resolution}</dd>
|
||||
<dt>{tr('fieldNetwork')}</dt><dd>{detail.network_summary || tr('off')}</dd>
|
||||
<dt>{tr('fieldAudio')}</dt><dd>{detail.audio_raw || tr('off')}</dd>
|
||||
<dt>{tr('fieldDir')}</dt><dd className="mono">{detail.directory}</dd>
|
||||
</dl>
|
||||
@@ -189,11 +460,35 @@ export const VMPage: React.FC<Props> = ({
|
||||
)
|
||||
}
|
||||
|
||||
const Fact: React.FC<{ label: string; icon: React.ReactNode; value: string }> = ({ label, icon, value }) => (
|
||||
<Tip label={label}>
|
||||
<span className="fact" tabIndex={0} aria-label={`${label}:${value}`}>
|
||||
{icon}
|
||||
{value}
|
||||
</span>
|
||||
</Tip>
|
||||
const IMacIcon: React.FC<{ running: boolean }> = ({ running }) => (
|
||||
<svg className="vm-imac-svg" viewBox="0 0 120 96" fill="none" aria-hidden="true">
|
||||
<defs>
|
||||
<linearGradient id="tahoeScreenOn" x1="16" y1="8" x2="104" y2="62" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stopColor="#4ec2ff" />
|
||||
<stop offset="55%" stopColor="#1e88e5" />
|
||||
<stop offset="100%" stopColor="#0f55b8" />
|
||||
</linearGradient>
|
||||
<linearGradient id="tahoeScreenOff" x1="16" y1="8" x2="104" y2="62" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stopColor="#2c2e35" />
|
||||
<stop offset="100%" stopColor="#18191e" />
|
||||
</linearGradient>
|
||||
<linearGradient id="imacChin" x1="12" y1="62" x2="108" y2="74" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stopColor="#e8eaee" />
|
||||
<stop offset="100%" stopColor="#d4d7dd" />
|
||||
</linearGradient>
|
||||
<linearGradient id="imacStand" x1="50" y1="73" x2="70" y2="90" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stopColor="#c4c8cf" />
|
||||
<stop offset="100%" stopColor="#e2e5ea" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path d="M51 73H69L72 88H48L51 73Z" fill="url(#imacStand)" />
|
||||
<rect x="42" y="87" width="36" height="3.5" rx="1.75" fill="#cfd3da" />
|
||||
<rect x="10" y="6" width="100" height="68" rx="6" fill="#1d1e22" />
|
||||
<path d="M10 61H110V68C110 71.3137 107.314 74 104 74H16C12.6863 74 10 71.3137 10 68V61Z" fill="url(#imacChin)" />
|
||||
<rect x="13.5" y="9.5" width="93" height="49" rx="2.5" fill={running ? 'url(#tahoeScreenOn)' : 'url(#tahoeScreenOff)'} />
|
||||
{running && (
|
||||
<path d="M13.5 47C34 39 58 49 78 41C92 35.5 100 37 106.5 39V58.5H13.5V47Z" fill="rgba(255,255,255,0.18)" />
|
||||
)}
|
||||
<circle cx="60" cy="67.5" r="1.8" fill="#8e9299" />
|
||||
</svg>
|
||||
)
|
||||
@@ -7,6 +7,21 @@ const dict = {
|
||||
// Shell
|
||||
sidebarVMs: '虚拟机',
|
||||
sidebarHost: '宿主与运行时',
|
||||
sidebarInstallers: '安装包',
|
||||
installersTitle: '安装包',
|
||||
installersDownloaded: '已下载',
|
||||
installersAvailable: 'Apple 提供的版本',
|
||||
installersEmpty: '还没有下载任何安装包',
|
||||
installersPartial: '未下载完',
|
||||
installersResume: '继续下载',
|
||||
installersDownload: '下载',
|
||||
installersDelete: '删除',
|
||||
installersDeleteConfirm: '确认删除',
|
||||
installersNoSpace: '空间不足:需要约 {need} GB,可用 {free} GB',
|
||||
installersHint: '离线安装包可以重复用来新建虚拟机;点已下载条目右侧「新建虚拟机」可直接使用。正在使用或下载中的不能删除',
|
||||
installersCreateVM: '新建虚拟机',
|
||||
installersKindOffline: '离线完整包',
|
||||
installersKindOnline: '在线恢复镜像',
|
||||
emptyVMs: '还没有虚拟机',
|
||||
hostReady: '就绪',
|
||||
hostNeedsAction: '需要处理',
|
||||
@@ -50,10 +65,45 @@ const dict = {
|
||||
// VM page
|
||||
pendingTitle: '下次启动生效',
|
||||
restartToApply: '重启以应用',
|
||||
guideTitle: '安装 macOS',
|
||||
guideStep1: '在「磁盘工具」中抹掉「QEMU HARDDISK Media」,格式选 APFS',
|
||||
guideStep2: '退出磁盘工具,选择「重新安装 macOS」',
|
||||
guideStep3: '进入桌面后,弹出安装盘',
|
||||
guideTitle: '恢复模式',
|
||||
guideKindBuiltIn: '内置恢复',
|
||||
guideKindOffline: '离线完整安装',
|
||||
guideKindOnline: '在线恢复安装',
|
||||
guideBuiltIn1: '启动(或重启)虚拟机后,在 OpenCore 引导菜单中选择「Recovery」即可进入系统自带恢复模式',
|
||||
guideBuiltIn2: '内置 Recovery 已支持联网重装;如果虚拟盘为空或需要离线安装,可点下方「挂载离线镜像」',
|
||||
guideBuiltIn3: '操作完成后点下方「退出恢复模式」,恢复开机直进 macOS',
|
||||
guideStep1: '在虚拟机窗口选「磁盘工具(Disk Utility)」→ 点 Continue → 选中左侧容量最大的「QEMU HARDDISK Media」(看不到时点左上角 View › Show All Devices)→ 点顶部 Erase,名称填 Macintosh HD、格式 APFS、方案 GUID Partition Map(抹除已用过的磁盘时画面可能短暂卡住 10–30 秒并自动恢复,请勿强行关闭),完成后退出磁盘工具',
|
||||
guideStep2: '回到恢复主界面,选「Reinstall macOS Tahoe」→ 点 Continue,装到刚抹掉的磁盘(中途会自动重启几次)',
|
||||
guideStep3: '重启看到「设置助理」(选择国家或地区)后,点下方「退出恢复模式」弹出安装盘',
|
||||
guideOffline1: '在虚拟机恢复窗口不要点「Reinstall macOS Tahoe」;直接点击顶部菜单栏「Utilities › Terminal」(实用工具 › 终端)打开终端',
|
||||
guideOffline2: '在终端运行下方命令(可点右侧键盘图标一键键入),脚本会自动把空白虚拟硬盘抹成 APFS(Macintosh HD)并开始离线安装(抹除已用过的磁盘会先询问确认,中途会自动重启几次):',
|
||||
guideOffline3: '重启看到「设置助理」(选择国家或地区)后,点下方「退出恢复模式」(弹出安装盘并恢复网络)',
|
||||
finishInstall: '退出恢复模式',
|
||||
enterRecovery: '进入恢复模式',
|
||||
attachInstaller: '挂载离线镜像',
|
||||
pickRecoveryTitle: '选择离线镜像(.img / .dmg)',
|
||||
guestToolsTitle: '宿客互通 · Guest Tools',
|
||||
guestToolsDesc: '提供宿主机 ↔ macOS 双向剪贴板同步与共享文件夹(macOS 桌面 ReimsShare),采用每台虚拟机独立随机 Token 鉴权。',
|
||||
guestToolsConnected: '已连接',
|
||||
guestToolsReady: '已配置',
|
||||
guestToolsNotInstalled: '未安装',
|
||||
guestToolsInstallHint: '在 macOS 里双击桌面/访达里的 REIMSTOOLS → Install-Reims-Tools.command,或在终端运行:',
|
||||
attachGuestTools: '挂载 Guest Tools',
|
||||
detachGuestTools: '弹出工具盘',
|
||||
openSharedFolder: '打开共享文件夹',
|
||||
upgradeToNVMe: '升级到 NVMe',
|
||||
exportDiagnostics: '导出排障日志 (.zip)',
|
||||
cloneVM: '秒级派生副本 (CoW)',
|
||||
diagExternalDriveWarn: '数据目录位于外置/网络盘({dir}),macOS 安装与随机读写会明显偏慢,建议放本地 NVMe SSD',
|
||||
diagHighMemWarn: '宿主机当前物理内存占用已达 {pct}%,若虚拟机卡顿建议关闭后台程序或适当调小虚拟机内存',
|
||||
diagAhciUpgradeHint: '当前系统盘仍使用旧版 SATA/AHCI,建议一键升级到 NVMe 以提升读写与 TRIM 性能',
|
||||
cloneTitle: '从「{name}」派生 CoW 副本',
|
||||
cloneDesc: '通过 qcow2 写时复制(CoW)秒级创建独立副本,几乎不占额外空间,且不会修改原虚拟机磁盘。',
|
||||
cloneNameLabel: '新虚拟机名称',
|
||||
cloneConfirm: '立即派生',
|
||||
typeClipboard: '粘贴为键入',
|
||||
typeIntoVM: '在虚拟机里键入',
|
||||
typeUntypeable: '只能键入美式键盘上的字符(英文、数字、符号)。中文等字符请换别的方式传。',
|
||||
brokenHint: '这台虚拟机的配置无法读取',
|
||||
techInfo: '技术信息',
|
||||
factCPU: '处理器',
|
||||
@@ -78,20 +128,80 @@ const dict = {
|
||||
// Logs
|
||||
logActivity: '活动',
|
||||
logSerial: '串口',
|
||||
logQemu: 'QEMU',
|
||||
logsEmpty: '暂无日志',
|
||||
|
||||
// Tasks
|
||||
taskDownload: '下载 macOS {v}',
|
||||
taskRecoveryDownload: '正在为 {name} 拉取并挂载在线恢复镜像',
|
||||
taskCreate: '创建 {name}',
|
||||
tasksRunning: '{n} 个任务进行中',
|
||||
pauseDownload: '暂停下载',
|
||||
toastInstallerReady: 'macOS {v} 安装包已就绪',
|
||||
toastDownloadPaused: '已暂停,再次下载会从中断处继续',
|
||||
failDownload: '下载失败',
|
||||
taskRuntime: '安装运行时 {v}',
|
||||
toastRuntimeReady: '运行时 {v} 已安装',
|
||||
failRuntime: '运行时安装失败',
|
||||
|
||||
// First launch
|
||||
setupTitle: '选择数据目录',
|
||||
setupDesc: '虚拟机、安装包和运行时都放在这里',
|
||||
setupOther: '其他位置…',
|
||||
setupFree: '可用 {n} GB',
|
||||
setupSystem: '系统盘',
|
||||
setupExternal: '外置盘',
|
||||
setupWarnExternal: '外置盘拔出时,正在运行的虚拟机会损坏',
|
||||
setupRecommended: '推荐',
|
||||
setupWarnSystem: '放在系统盘,空间紧张时会影响 Windows',
|
||||
setupWarnSpace: '可用空间不足 60 GB:一个离线安装包约 20 GB,虚拟磁盘会随使用增长',
|
||||
setupReuse: '这里已有 Reims-Go 数据,会直接沿用',
|
||||
setupContinue: '继续',
|
||||
setupRuntimeTitle: '检查环境并安装运行时',
|
||||
setupCheck: '环境',
|
||||
setupGPU: '显卡(Vulkan)',
|
||||
setupNoGPU: '没有检测到 Vulkan 显卡,只能用软件渲染',
|
||||
setupRecMem: '推荐 {n} GB',
|
||||
setupRuntimeDesc: '运行虚拟机所需的 QEMU 与 reims-ctl,从 GitHub 下载并校验',
|
||||
setupLater: '稍后',
|
||||
setupDone: '完成',
|
||||
setupImport: '导入本地包…',
|
||||
|
||||
// Online runtimes
|
||||
runtimeOnline: '在线安装',
|
||||
runtimeLatest: '最新:{v}',
|
||||
runtimeNoneOnChannel: '这个通道还没有发布运行时',
|
||||
runtimeUpToDate: '已是最新',
|
||||
runtimeCurrent: '当前运行时',
|
||||
runtimeUpdate: '更新',
|
||||
runtimeNewer: '有新版本:{v}',
|
||||
runtimeInstall: '安装',
|
||||
runtimeCandidate: '接收候选版',
|
||||
runtimeCandidateHint: '候选版未经真实宿主冒烟测试',
|
||||
runtimeChannel_candidate: '候选版',
|
||||
runtimeChannel_stable: '稳定版',
|
||||
runtimeLookupFailed: '无法读取 GitHub 上的运行时列表',
|
||||
|
||||
// Toasts & dialogs
|
||||
toastStopped: '{name} 已关机',
|
||||
toastEjected: '已弹出安装盘',
|
||||
toastInstallFinished: '已退出恢复模式',
|
||||
toastExitRecoveryNextStart: '已退出恢复模式,下次启动生效',
|
||||
toastEnterRecovery: '已进入恢复模式,启动后可在引导菜单选 Recovery',
|
||||
toastEnterRecoveryNextStart: '已准备进入恢复模式,重启后显示引导菜单',
|
||||
toastInstallerAttached: '已挂载离线镜像:{name}',
|
||||
toastInstallerAttachedNextStart: '已挂载离线镜像(重启后生效):{name}',
|
||||
toastOnlineRecoveryStarted: '正在拉取在线恢复镜像(约 1 GB),完成后自动挂载',
|
||||
toastOnlineRecoveryAttached: '在线恢复镜像已挂载到 {name}',
|
||||
toastGuestToolsAttached: '已挂载 Guest Tools 工具盘(REIMSTOOLS)',
|
||||
toastGuestToolsAttachedNextStart: '已挂载 Guest Tools 工具盘,重启虚拟机后在访达中可见',
|
||||
toastGuestToolsDetached: '已弹出 Guest Tools 工具盘(剪贴板与共享目录继续生效)',
|
||||
toastGuestToolsDetachedNextStart: '已弹出工具盘,下次启动生效(剪贴板与共享目录继续生效)',
|
||||
toastNVMeReady: '已升级到 NVMe 磁盘控制器',
|
||||
toastNVMeNextStart: '已切换为 NVMe,下次启动生效',
|
||||
toastDiagExported: '已导出脱敏排障日志包 (.zip)',
|
||||
toastCloned: '已派生 CoW 副本「{name}」',
|
||||
toastTyped: '已键入 {n} 个字符',
|
||||
toastDeleted: '已删除 {name}',
|
||||
toastSaved: '已保存',
|
||||
toastSavedNextStart: '已保存,下次启动生效',
|
||||
@@ -100,6 +210,14 @@ const dict = {
|
||||
failStop: '关机失败',
|
||||
failRestart: '重启失败',
|
||||
failEject: '弹出安装盘失败',
|
||||
failFinishInstall: '退出恢复模式失败',
|
||||
failEnterRecovery: '进入恢复模式失败',
|
||||
failAttachInstaller: '挂载镜像失败',
|
||||
failGuestTools: 'Guest Tools 操作失败',
|
||||
failUpgradeNVMe: '升级到 NVMe 失败',
|
||||
failExportDiagnostics: '导出排障日志失败',
|
||||
failCloneVM: '派生 CoW 副本失败',
|
||||
failType: '键入失败',
|
||||
failDelete: '删除失败',
|
||||
failOpenFolder: '无法打开文件夹',
|
||||
failGeneric: '操作失败',
|
||||
@@ -108,6 +226,9 @@ const dict = {
|
||||
deleteDescKeep: '只移除配置,磁盘文件留在原目录',
|
||||
deleteKeepFiles: '保留磁盘文件',
|
||||
deleteConfirm: '删除',
|
||||
onlineRecoveryTitle: '拉取在线恢复镜像?',
|
||||
onlineRecoveryDesc: '本地没有已缓存的镜像,且未选择离线镜像。是否直接从 Apple 拉取约 1 GB 的在线恢复镜像并自动挂载到「{name}」?',
|
||||
onlineRecoveryConfirm: '拉取并挂载(约 1 GB)',
|
||||
noRuntimeAlert: '先在「宿主与运行时」导入运行时包',
|
||||
|
||||
// Host
|
||||
@@ -116,6 +237,12 @@ const dict = {
|
||||
hostGPUs: '显卡',
|
||||
hostPrefs: '偏好设置',
|
||||
language: '语言',
|
||||
appVersionTitle: '客户端版本',
|
||||
appUpToDate: '已是最新',
|
||||
appUpdateAvailable: '发现新版本 {v}(稳定版)',
|
||||
appCheckUpdate: '检查更新',
|
||||
appDownloadUpdate: '前往下载',
|
||||
appUpdateLookupFailed: '暂时无法连接 GitHub 检查更新',
|
||||
whpxTitle: 'WHPX',
|
||||
whpxReady: '就绪',
|
||||
whpxNoHvShort: '未激活',
|
||||
@@ -159,6 +286,14 @@ const dict = {
|
||||
sourceApple: '从 Apple 下载恢复镜像',
|
||||
sourceInstaller: '本地安装器镜像(.img / .dmg)',
|
||||
sourceDisk: '已有虚拟磁盘(.qcow2)',
|
||||
sourceOffline: '离线安装包(推荐)',
|
||||
offlineLoading: '正在读取 Apple 的版本列表…',
|
||||
offlineListFailed: '无法读取 Apple 的版本列表',
|
||||
offlineCached: '已下载',
|
||||
offlineHint: '约 20 GB,安装时不联网;装完点「完成安装」会恢复网络',
|
||||
offlineSpaceWarn: '可用空间 {free} GB,下载这个版本需要约 {need} GB',
|
||||
networkOfflineHint: '离线安装默认关闭以避免中途联网更新(可按需手动勾选开启),点「完成安装」时也会自动恢复网络',
|
||||
summaryOfflineSource: '离线安装包 · macOS {v}',
|
||||
macosVersion: 'macOS 版本',
|
||||
macosTahoe: 'macOS 26 Tahoe(硬件加速需要 26.4 及以上)',
|
||||
diskSize: '磁盘上限',
|
||||
@@ -170,6 +305,7 @@ const dict = {
|
||||
hostMemory: '宿主 {n} GB',
|
||||
cpuHint: '推荐 4 或 8 核',
|
||||
memHint: '建议不超过宿主内存的 75%',
|
||||
memCommitHint: 'Windows 现在还能分配 {avail} GB,推荐 {rec} GB',
|
||||
graphicsBackend: '图形后端',
|
||||
graphicsReims: 'reims-vgpu(硬件加速,推荐)',
|
||||
graphicsSvga: 'vmware-svga(无加速,用于排障)',
|
||||
@@ -184,10 +320,28 @@ const dict = {
|
||||
sshPortHint: '0 表示关闭',
|
||||
enableLogs: '记录图形与串口日志',
|
||||
startAfterCreate: '创建后立即启动',
|
||||
commandPreview: '将执行的命令',
|
||||
validationPassed: '检查通过',
|
||||
validationPassed: '检查通过,可以创建',
|
||||
validationChecking: '正在检查…',
|
||||
issuesCount: '有 {n} 项需要修改',
|
||||
summaryEdit: '修改',
|
||||
summarySource: '来源',
|
||||
summaryDefaultDir: '数据目录(默认)',
|
||||
summaryAppleSource: '从 Apple 下载 · {v}',
|
||||
summaryInstallerSource: '本地安装器 · {file}',
|
||||
summaryDiskSource: '已有磁盘 · {file}',
|
||||
summaryOn: '开',
|
||||
summaryStartAfter: '创建后启动',
|
||||
summaryLogs: '图形与串口日志',
|
||||
summarySSH: 'SSH 转发',
|
||||
summarySSHPort: '端口 {n}',
|
||||
summaryDiskGrow: '{size},按实际占用增长',
|
||||
commandToggle: '等效命令',
|
||||
commandToggleHint: '在终端运行下面这条命令效果相同',
|
||||
createNow: '创建',
|
||||
creating: '正在创建,进度见底部状态栏',
|
||||
createStartedHint: '创建后窗口会关闭,进度在底部状态栏',
|
||||
toastCreated: '{name} 已创建',
|
||||
failCreate: '{name} 创建失败',
|
||||
backToEdit: '返回修改',
|
||||
|
||||
// Settings
|
||||
settingsTitle: '{name} 设置',
|
||||
@@ -209,14 +363,60 @@ const dict = {
|
||||
diskController: '磁盘控制器',
|
||||
diskControllerWarn: '切换前先弹出安装盘',
|
||||
captureInput: '点击窗口时捕获键鼠',
|
||||
captureInputHint: '默认关闭(自由指针):单按 Win 键与 Alt+Tab 保留给 Windows,不会卡在 macOS 窗口里;需要把 ⌘Tab 等系统快捷键交给 macOS 时再开启',
|
||||
stopTimeout: '关机等待时间(秒)',
|
||||
stopTimeoutHint: '0 表示一直等待',
|
||||
extraArgs: '额外 QEMU 参数',
|
||||
logLevel: '日志级别(REIMS_VGPU_LOG)',
|
||||
|
||||
// Host optimization probes & guidance
|
||||
hostOptimizations: '优化能力',
|
||||
optRecommended: '推荐',
|
||||
optAvailable: '可用',
|
||||
optExperimental: '实验性',
|
||||
optAuto: '已自动开启',
|
||||
optUnavailable: '不可用',
|
||||
optPCoreSub: '仅调度到性能核({detail}),减少卡顿',
|
||||
optPCoreUnavailable: '当前处理器无大小核架构,无需开启',
|
||||
optKernelIrqchipTitle: 'WHPX 内核中断(kernel-irqchip)',
|
||||
optKernelIrqchipRec: '当前 Windows 与硬件支持,可降低磁盘 I/O 与多核 CPU 开销',
|
||||
optKernelIrqchipExp: '当前运行时含 Win10 多核启动补丁,可在虚拟机「高级」设置中手动开启验证',
|
||||
optKernelIrqchipWin10NoPatch: 'Win10 默认关闭;需更新含 startup-ipis 补丁的运行时',
|
||||
optKernelIrqchipNestedErr: '当前 Windows 拒绝嵌套虚拟化属性({code}),建议选「兼容模式」',
|
||||
optKernelIrqchipUnavailable: '当前宿主 WHPX 环境不支持内核中断仿真',
|
||||
optColdRebootTitle: 'Win10 无感冷重启补偿',
|
||||
optColdRebootAuto: '检测到系统缺少 WHvResetPartition,启动时自动监控客体重启并冷拉起',
|
||||
optColdRebootUnavailable: '当前 Windows 原生支持分区热重启,无需补偿',
|
||||
optDiscreteGpuTitle: 'Vulkan 独显加速',
|
||||
optDiscreteGpuRec: '已检测到独立显卡({name}),新建时默认优先使用',
|
||||
optDiscreteGpuIntegrated: '仅检测到核显({name}),性能弱于独立显卡',
|
||||
optDiscreteGpuUnavailable: '未检测到可用 Vulkan 显卡,可先切换 vmware-svga 排障',
|
||||
kernelIrqchipLabel: 'WHPX 内核中断模式',
|
||||
kernelIrqchipAuto: '自动',
|
||||
kernelIrqchipOn: '开启(高性能)',
|
||||
kernelIrqchipOff: '关闭(兼容)',
|
||||
diskControllerNvmeHint: '安装盘已弹出,建议切换为 NVMe 以提升磁盘读写性能',
|
||||
diskControllerInstallHint: '装机阶段建议保持 SATA,装完弹出安装盘后再切 NVMe',
|
||||
gpuUnavailableHint: '未检测到可用 Vulkan 显卡,可先切换 vmware-svga 排障',
|
||||
},
|
||||
'en-US': {
|
||||
sidebarVMs: 'Virtual machines',
|
||||
sidebarHost: 'Host & runtime',
|
||||
sidebarInstallers: 'Installers',
|
||||
installersTitle: 'Installers',
|
||||
installersDownloaded: 'Downloaded',
|
||||
installersAvailable: 'Releases from Apple',
|
||||
installersEmpty: 'No installers downloaded yet',
|
||||
installersPartial: 'Partly downloaded',
|
||||
installersResume: 'Resume',
|
||||
installersDownload: 'Download',
|
||||
installersDelete: 'Delete',
|
||||
installersDeleteConfirm: 'Confirm delete',
|
||||
installersNoSpace: 'Not enough space: needs about {need} GB, {free} GB free',
|
||||
installersHint: 'Offline installers can be reused for new VMs — click “Create VM” on any downloaded item to start. Items in use or downloading can’t be deleted',
|
||||
installersCreateVM: 'Create VM',
|
||||
installersKindOffline: 'Offline installer',
|
||||
installersKindOnline: 'Online recovery',
|
||||
emptyVMs: 'No virtual machines',
|
||||
hostReady: 'Ready',
|
||||
hostNeedsAction: 'Needs attention',
|
||||
@@ -257,10 +457,45 @@ const dict = {
|
||||
|
||||
pendingTitle: 'Applies on next start',
|
||||
restartToApply: 'Restart to apply',
|
||||
guideTitle: 'Install macOS',
|
||||
guideStep1: 'In Disk Utility, erase "QEMU HARDDISK Media" as APFS',
|
||||
guideStep2: 'Quit Disk Utility and choose "Reinstall macOS"',
|
||||
guideStep3: 'Once on the desktop, eject the installer',
|
||||
guideTitle: 'Recovery mode',
|
||||
guideKindBuiltIn: 'Built-in recovery',
|
||||
guideKindOffline: 'Offline install',
|
||||
guideKindOnline: 'Online recovery',
|
||||
guideBuiltIn1: 'Start (or restart) the VM and choose “Recovery” in OpenCore’s boot menu to enter macOS’s built-in Recovery',
|
||||
guideBuiltIn2: 'Built-in Recovery already supports online reinstall; for an empty disk or offline install, click “Attach offline image” below',
|
||||
guideBuiltIn3: 'When done, click “Exit recovery mode” to boot straight into macOS again',
|
||||
guideStep1: 'Open Disk Utility → Continue → select the largest “QEMU HARDDISK Media” (use View › Show All Devices if hidden) → Erase as APFS (GUID Partition Map, name Macintosh HD; the screen may pause for 10–30s on a previously used disk and recover automatically), then quit Disk Utility',
|
||||
guideStep2: 'Back in Recovery, choose “Reinstall macOS Tahoe” → Continue and install onto the erased disk (it restarts a few times)',
|
||||
guideStep3: 'When Setup Assistant asks for your country or region, click “Exit recovery mode” to eject the installer',
|
||||
guideOffline1: 'In macOS Recovery, do NOT click “Reinstall macOS Tahoe”; open the top menu bar Utilities › Terminal',
|
||||
guideOffline2: 'Run the command below (or click the keyboard icon to type it into the VM). It automatically formats a blank VM disk as APFS (Macintosh HD) and starts the offline install (asks before erasing non-blank disks; restarts a few times):',
|
||||
guideOffline3: 'When Setup Assistant asks for your country or region, click “Exit recovery mode” (ejects installer and restores network)',
|
||||
finishInstall: 'Exit recovery mode',
|
||||
enterRecovery: 'Enter recovery mode',
|
||||
attachInstaller: 'Attach offline image',
|
||||
pickRecoveryTitle: 'Choose an offline image (.img / .dmg)',
|
||||
guestToolsTitle: 'Guest Tools',
|
||||
guestToolsDesc: 'Token-authenticated two-way clipboard sync and shared folder (~/Desktop/ReimsShare ↔ Windows host) with no Xcode required.',
|
||||
guestToolsConnected: 'Connected',
|
||||
guestToolsReady: 'Configured',
|
||||
guestToolsNotInstalled: 'Not installed',
|
||||
guestToolsInstallHint: 'In macOS, double-click REIMSTOOLS → Install-Reims-Tools.command in Finder, or run in Terminal:',
|
||||
attachGuestTools: 'Attach Guest Tools',
|
||||
detachGuestTools: 'Eject tools disk',
|
||||
openSharedFolder: 'Open shared folder',
|
||||
upgradeToNVMe: 'Upgrade to NVMe',
|
||||
exportDiagnostics: 'Export diagnostics (.zip)',
|
||||
cloneVM: 'Derive CoW clone',
|
||||
diagExternalDriveWarn: 'Data root ({dir}) is on an external or network drive; macOS install and APFS I/O will be much slower than local NVMe SSD',
|
||||
diagHighMemWarn: 'Host physical memory usage is at {pct}%; close background apps or lower VM RAM if performance degrades',
|
||||
diagAhciUpgradeHint: 'This VM still uses legacy SATA/AHCI; upgrade to NVMe for faster I/O and TRIM support',
|
||||
cloneTitle: 'Derive CoW clone from “{name}”',
|
||||
cloneDesc: 'Creates an instant qcow2 copy-on-write overlay with a fresh Mac identity without modifying the source disk.',
|
||||
cloneNameLabel: 'New VM name',
|
||||
cloneConfirm: 'Create clone',
|
||||
typeClipboard: 'Paste as keystrokes',
|
||||
typeIntoVM: 'Type into the VM',
|
||||
typeUntypeable: 'Only characters on a US keyboard can be typed (letters, digits, symbols).',
|
||||
brokenHint: 'This VM’s configuration can’t be read',
|
||||
techInfo: 'Technical details',
|
||||
factCPU: 'CPU',
|
||||
@@ -284,18 +519,76 @@ const dict = {
|
||||
|
||||
logActivity: 'Activity',
|
||||
logSerial: 'Serial',
|
||||
logQemu: 'QEMU',
|
||||
logsEmpty: 'No logs yet',
|
||||
|
||||
taskDownload: 'Downloading macOS {v}',
|
||||
taskRecoveryDownload: 'Downloading online recovery for {name}',
|
||||
taskCreate: 'Creating {name}',
|
||||
tasksRunning: '{n} tasks running',
|
||||
pauseDownload: 'Pause download',
|
||||
toastInstallerReady: 'macOS {v} installer ready',
|
||||
toastDownloadPaused: 'Paused — downloading again continues where it stopped',
|
||||
failDownload: 'Download failed',
|
||||
taskRuntime: 'Installing runtime {v}',
|
||||
toastRuntimeReady: 'Runtime {v} installed',
|
||||
failRuntime: 'Runtime install failed',
|
||||
|
||||
setupTitle: 'Choose a data folder',
|
||||
setupDesc: 'VMs, installers and runtimes all live here',
|
||||
setupOther: 'Other location…',
|
||||
setupFree: '{n} GB free',
|
||||
setupSystem: 'System drive',
|
||||
setupExternal: 'External',
|
||||
setupWarnExternal: 'Unplugging an external drive corrupts running VMs',
|
||||
setupRecommended: 'Recommended',
|
||||
setupWarnSystem: 'On the system drive, low space can affect Windows',
|
||||
setupWarnSpace: 'Under 60 GB free: an offline installer is about 20 GB and virtual disks grow with use',
|
||||
setupReuse: 'This folder already has Reims-Go data; it will be reused',
|
||||
setupContinue: 'Continue',
|
||||
setupRuntimeTitle: 'Check the host and install the runtime',
|
||||
setupCheck: 'Host',
|
||||
setupGPU: 'Graphics (Vulkan)',
|
||||
setupNoGPU: 'No Vulkan GPU found; only software rendering will work',
|
||||
setupRecMem: '{n} GB recommended',
|
||||
setupRuntimeDesc: 'QEMU and reims-ctl, downloaded from GitHub and verified',
|
||||
setupLater: 'Later',
|
||||
setupDone: 'Done',
|
||||
setupImport: 'Import a local package…',
|
||||
|
||||
runtimeOnline: 'Online install',
|
||||
runtimeLatest: 'Latest: {v}',
|
||||
runtimeNoneOnChannel: 'No runtime published on this channel yet',
|
||||
runtimeUpToDate: 'Up to date',
|
||||
runtimeCurrent: 'Current runtime',
|
||||
runtimeUpdate: 'Update',
|
||||
runtimeNewer: 'New version: {v}',
|
||||
runtimeInstall: 'Install',
|
||||
runtimeCandidate: 'Receive candidates',
|
||||
runtimeCandidateHint: 'Candidates have not passed a real-host smoke test',
|
||||
runtimeChannel_candidate: 'Candidate',
|
||||
runtimeChannel_stable: 'Stable',
|
||||
runtimeLookupFailed: 'Couldn’t read the runtime list from GitHub',
|
||||
|
||||
toastStopped: '{name} shut down',
|
||||
toastEjected: 'Installer ejected',
|
||||
toastInstallFinished: 'Exited recovery mode',
|
||||
toastExitRecoveryNextStart: 'Exited recovery mode — applies at next start',
|
||||
toastEnterRecovery: 'Recovery mode ready — pick Recovery in OpenCore on next start',
|
||||
toastEnterRecoveryNextStart: 'Recovery mode ready — restart to open the boot menu',
|
||||
toastInstallerAttached: 'Offline image attached: {name}',
|
||||
toastInstallerAttachedNextStart: 'Offline image attached (applies on restart): {name}',
|
||||
toastOnlineRecoveryStarted: 'Downloading online recovery image (~1 GB); will attach when ready',
|
||||
toastOnlineRecoveryAttached: 'Online recovery image attached to {name}',
|
||||
toastGuestToolsAttached: 'Guest Tools disk (REIMSTOOLS) attached',
|
||||
toastGuestToolsAttachedNextStart: 'Guest Tools disk attached — restart VM to mount in Finder',
|
||||
toastGuestToolsDetached: 'Guest Tools disk ejected (clipboard & shared folder stay active)',
|
||||
toastGuestToolsDetachedNextStart: 'Guest Tools disk ejected — applies on next start',
|
||||
toastNVMeReady: 'Upgraded disk controller to NVMe',
|
||||
toastNVMeNextStart: 'Switched to NVMe — applies on next start',
|
||||
toastDiagExported: 'Redacted diagnostics archive exported (.zip)',
|
||||
toastCloned: 'CoW clone “{name}” created',
|
||||
toastTyped: 'Typed {n} characters',
|
||||
toastDeleted: '{name} deleted',
|
||||
toastSaved: 'Saved',
|
||||
toastSavedNextStart: 'Saved — applies on next start',
|
||||
@@ -304,6 +597,14 @@ const dict = {
|
||||
failStop: 'Couldn’t shut down',
|
||||
failRestart: 'Couldn’t restart',
|
||||
failEject: 'Couldn’t eject the installer',
|
||||
failFinishInstall: 'Couldn’t exit recovery mode',
|
||||
failEnterRecovery: 'Couldn’t enter recovery mode',
|
||||
failAttachInstaller: 'Couldn’t attach the image',
|
||||
failGuestTools: 'Guest Tools operation failed',
|
||||
failUpgradeNVMe: 'Couldn’t upgrade to NVMe',
|
||||
failExportDiagnostics: 'Couldn’t export diagnostics',
|
||||
failCloneVM: 'Couldn’t create CoW clone',
|
||||
failType: 'Couldn’t type into the VM',
|
||||
failDelete: 'Couldn’t delete',
|
||||
failOpenFolder: 'Couldn’t open the folder',
|
||||
failGeneric: 'Something went wrong',
|
||||
@@ -312,6 +613,9 @@ const dict = {
|
||||
deleteDescKeep: 'Only the configuration is removed; disk files stay in place',
|
||||
deleteKeepFiles: 'Keep disk files',
|
||||
deleteConfirm: 'Delete',
|
||||
onlineRecoveryTitle: 'Download online recovery image?',
|
||||
onlineRecoveryDesc: 'No cached image was found locally and no offline image was selected. Download Apple’s ~1 GB online recovery image and attach it to “{name}” automatically?',
|
||||
onlineRecoveryConfirm: 'Download & attach (~1 GB)',
|
||||
noRuntimeAlert: 'Import a runtime under Host & runtime first',
|
||||
|
||||
hostRuntime: 'Runtime',
|
||||
@@ -319,6 +623,12 @@ const dict = {
|
||||
hostGPUs: 'Graphics cards',
|
||||
hostPrefs: 'Preferences',
|
||||
language: 'Language',
|
||||
appVersionTitle: 'App version',
|
||||
appUpToDate: 'Up to date',
|
||||
appUpdateAvailable: 'New stable release {v} available',
|
||||
appCheckUpdate: 'Check for updates',
|
||||
appDownloadUpdate: 'Download',
|
||||
appUpdateLookupFailed: 'Couldn’t check GitHub for updates',
|
||||
whpxTitle: 'WHPX',
|
||||
whpxReady: 'Ready',
|
||||
whpxNoHvShort: 'Inactive',
|
||||
@@ -361,6 +671,14 @@ const dict = {
|
||||
sourceApple: 'Download recovery image from Apple',
|
||||
sourceInstaller: 'Local installer image (.img / .dmg)',
|
||||
sourceDisk: 'Existing virtual disk (.qcow2)',
|
||||
sourceOffline: 'Offline installer (recommended)',
|
||||
offlineLoading: 'Reading Apple’s release list…',
|
||||
offlineListFailed: 'Couldn’t read Apple’s release list',
|
||||
offlineCached: 'Downloaded',
|
||||
offlineHint: 'About 20 GB; installs with no network. “Finish install” turns the network back on',
|
||||
offlineSpaceWarn: '{free} GB free; this release needs about {need} GB',
|
||||
networkOfflineHint: 'Off by default for offline installs so macOS does not download updates mid-install (you can still enable it here, or let “Finish install” turn it on)',
|
||||
summaryOfflineSource: 'Offline installer · macOS {v}',
|
||||
macosVersion: 'macOS version',
|
||||
macosTahoe: 'macOS 26 Tahoe (acceleration needs 26.4 or later)',
|
||||
diskSize: 'Disk size',
|
||||
@@ -372,6 +690,7 @@ const dict = {
|
||||
hostMemory: 'Host has {n} GB',
|
||||
cpuHint: '4 or 8 cores recommended',
|
||||
memHint: 'Keep under 75% of host memory',
|
||||
memCommitHint: 'Windows can allocate {avail} GB more right now; {rec} GB recommended',
|
||||
graphicsBackend: 'Graphics backend',
|
||||
graphicsReims: 'reims-vgpu (accelerated, recommended)',
|
||||
graphicsSvga: 'vmware-svga (no acceleration, for troubleshooting)',
|
||||
@@ -386,10 +705,28 @@ const dict = {
|
||||
sshPortHint: '0 turns it off',
|
||||
enableLogs: 'Keep graphics and serial logs',
|
||||
startAfterCreate: 'Start after creating',
|
||||
commandPreview: 'Command to run',
|
||||
validationPassed: 'All checks passed',
|
||||
validationPassed: 'All checks passed — ready to create',
|
||||
validationChecking: 'Checking…',
|
||||
issuesCount: '{n} item(s) need fixing',
|
||||
summaryEdit: 'Edit',
|
||||
summarySource: 'Source',
|
||||
summaryDefaultDir: 'Data folder (default)',
|
||||
summaryAppleSource: 'Download from Apple · {v}',
|
||||
summaryInstallerSource: 'Local installer · {file}',
|
||||
summaryDiskSource: 'Existing disk · {file}',
|
||||
summaryOn: 'On',
|
||||
summaryStartAfter: 'Start after creating',
|
||||
summaryLogs: 'Graphics & serial logs',
|
||||
summarySSH: 'SSH forwarding',
|
||||
summarySSHPort: 'Port {n}',
|
||||
summaryDiskGrow: '{size}, grows with use',
|
||||
commandToggle: 'Equivalent command',
|
||||
commandToggleHint: 'Running this in a terminal does the same thing',
|
||||
createStartedHint: 'The window closes once creation starts; progress shows in the status bar',
|
||||
toastCreated: '{name} created',
|
||||
failCreate: 'Couldn’t create {name}',
|
||||
backToEdit: 'Edit and retry',
|
||||
createNow: 'Create',
|
||||
creating: 'Creating — progress is in the status bar',
|
||||
|
||||
settingsTitle: '{name} settings',
|
||||
appliesNextStart: 'Applies on next start',
|
||||
@@ -410,10 +747,41 @@ const dict = {
|
||||
diskController: 'Disk controller',
|
||||
diskControllerWarn: 'Eject the installer before switching',
|
||||
captureInput: 'Capture keyboard and mouse on click',
|
||||
captureInputHint: 'Off by default (free pointer): Win key and Alt+Tab stay with Windows so you won’t get trapped in the macOS window; enable to send system shortcuts like ⌘Tab to macOS',
|
||||
stopTimeout: 'Shutdown timeout (seconds)',
|
||||
stopTimeoutHint: '0 waits indefinitely',
|
||||
extraArgs: 'Extra QEMU arguments',
|
||||
logLevel: 'Log level (REIMS_VGPU_LOG)',
|
||||
|
||||
// Host optimization probes & guidance
|
||||
hostOptimizations: 'Optimizations',
|
||||
optRecommended: 'Recommended',
|
||||
optAvailable: 'Available',
|
||||
optExperimental: 'Experimental',
|
||||
optAuto: 'Automatic',
|
||||
optUnavailable: 'Unavailable',
|
||||
optPCoreSub: 'Schedule QEMU on performance cores only ({detail})',
|
||||
optPCoreUnavailable: 'CPU has no hybrid P/E cores',
|
||||
optKernelIrqchipTitle: 'WHPX kernel irqchip',
|
||||
optKernelIrqchipRec: 'Supported on this host; lowers disk I/O and multi-core CPU overhead',
|
||||
optKernelIrqchipExp: 'Runtime includes Win10 startup-ipis patch; can be enabled in VM Advanced settings',
|
||||
optKernelIrqchipWin10NoPatch: 'Off by default on Win10; needs a runtime with the startup-ipis patch',
|
||||
optKernelIrqchipNestedErr: 'Host rejected nested virtualization property ({code}); use compatibility mode',
|
||||
optKernelIrqchipUnavailable: 'Kernel APIC emulation is unavailable on this WHPX host',
|
||||
optColdRebootTitle: 'Win10 cold-reboot workaround',
|
||||
optColdRebootAuto: 'Host lacks WHvResetPartition; guest reboots are cold-restarted automatically',
|
||||
optColdRebootUnavailable: 'Host supports native partition reset; workaround not needed',
|
||||
optDiscreteGpuTitle: 'Vulkan discrete GPU acceleration',
|
||||
optDiscreteGpuRec: 'Discrete GPU detected ({name}); preferred automatically',
|
||||
optDiscreteGpuIntegrated: 'Integrated GPU only ({name})',
|
||||
optDiscreteGpuUnavailable: 'No Vulkan GPU detected; use vmware-svga for troubleshooting',
|
||||
kernelIrqchipLabel: 'WHPX kernel irqchip mode',
|
||||
kernelIrqchipAuto: 'Auto',
|
||||
kernelIrqchipOn: 'On (fast)',
|
||||
kernelIrqchipOff: 'Off (compat)',
|
||||
diskControllerNvmeHint: 'Installer ejected — switch to NVMe for faster disk I/O',
|
||||
diskControllerInstallHint: 'Keep SATA while installing; switch to NVMe after ejecting the installer',
|
||||
gpuUnavailableHint: 'No Vulkan GPU detected; switch to vmware-svga for troubleshooting',
|
||||
},
|
||||
} as const
|
||||
|
||||
|
||||
@@ -4,6 +4,19 @@ import { GPUInfo, HostReport, Locale, VMDetail } from '../types'
|
||||
// Human-readable values for the main view (docs/ui-redesign.md §4.3).
|
||||
// Raw values stay available under "Technical details".
|
||||
|
||||
const MEMORY_CHOICES = [4, 6, 8, 12, 16, 24, 32, 48, 64]
|
||||
|
||||
/**
|
||||
* Largest offered memory size that fits in 60% of physical RAM and in the
|
||||
* commit memory free now, minus 1 GB for QEMU and 2 GB for the host. Mirrors
|
||||
* host.RecommendedMemoryGB (internal/host/memory.go).
|
||||
*/
|
||||
export function recommendedMemoryGB(host: HostReport): number {
|
||||
let limit = host.total_ram_gb * 0.6
|
||||
if (host.commit_avail_gb > 0) limit = Math.min(limit, host.commit_avail_gb - 3)
|
||||
return MEMORY_CHOICES.reduce((best, m) => (m <= limit ? m : best), MEMORY_CHOICES[0])
|
||||
}
|
||||
|
||||
/** "16G" / "16384M" / "16GiB" → "16 GB". Unknown shapes pass through. */
|
||||
export function formatMemory(raw: string): string {
|
||||
const m = /^\s*(\d+(?:\.\d+)?)\s*([KMGT])?(?:i?B)?\s*$/i.exec(raw ?? '')
|
||||
@@ -46,15 +59,18 @@ export function resolutionLabel(raw: string): string {
|
||||
return Math.abs(w / h - 16 / 9) < 0.01 ? `${h}p` : `${w}×${h}`
|
||||
}
|
||||
|
||||
/** A `gpu` value ("auto" or a Vulkan ICD path) as the card's short name, e.g. "RTX 4070 Ti". */
|
||||
export function gpuLabel(locale: Locale, icd: string | undefined, host: HostReport): string {
|
||||
if (!icd || icd === 'auto') {
|
||||
return host.recommended_gpu ? shortGPUName(host.recommended_gpu.name) : t(locale, 'gpuAuto')
|
||||
}
|
||||
const found = findGPU(host, icd)
|
||||
return found ? shortGPUName(found.name) : t(locale, 'gpuAuto')
|
||||
}
|
||||
|
||||
export function graphicsLabel(locale: Locale, d: VMDetail, host: HostReport): string {
|
||||
if (d.graphics && d.graphics !== 'reims-vgpu') return t(locale, 'softwareGraphics')
|
||||
let gpu: string
|
||||
if (!d.gpu || d.gpu === 'auto') {
|
||||
gpu = host.recommended_gpu ? shortGPUName(host.recommended_gpu.name) : t(locale, 'gpuAuto')
|
||||
} else {
|
||||
const found = findGPU(host, d.gpu)
|
||||
gpu = found ? shortGPUName(found.name) : t(locale, 'gpuAuto')
|
||||
}
|
||||
const gpu = gpuLabel(locale, d.gpu, host)
|
||||
const res = resolutionLabel(d.resolution)
|
||||
const screens = d.displays > 1 ? `${d.displays} × ${res}` : res
|
||||
return res ? `${gpu} · ${screens}` : gpu
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { Locale, Optimization, OptimizationStatus } from '../types'
|
||||
|
||||
export type KernelIrqchipMode = 'auto' | 'on' | 'off'
|
||||
|
||||
export function findOptimization(list: Optimization[] | undefined, id: string): Optimization | undefined {
|
||||
return (list ?? []).find((o) => o.id === id)
|
||||
}
|
||||
|
||||
export function optBadgeClass(status: OptimizationStatus | undefined): string {
|
||||
switch (status) {
|
||||
case 'recommended':
|
||||
case 'auto':
|
||||
return 'badge-ok'
|
||||
case 'experimental':
|
||||
return 'badge-warn'
|
||||
case 'available':
|
||||
return 'badge-accent'
|
||||
default:
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export function optStatusLabel(locale: Locale, status: OptimizationStatus | undefined): string {
|
||||
const keyMap: Record<OptimizationStatus, I18nKey> = {
|
||||
recommended: 'optRecommended',
|
||||
available: 'optAvailable',
|
||||
experimental: 'optExperimental',
|
||||
auto: 'optAuto',
|
||||
unavailable: 'optUnavailable',
|
||||
}
|
||||
return t(locale, keyMap[status ?? 'unavailable'])
|
||||
}
|
||||
|
||||
export function kernelIrqchipHint(locale: Locale, opt: Optimization | undefined): string {
|
||||
if (!opt) return t(locale, 'optKernelIrqchipUnavailable')
|
||||
if (opt.status === 'recommended') return t(locale, 'optKernelIrqchipRec')
|
||||
if (opt.status === 'experimental') return t(locale, 'optKernelIrqchipExp')
|
||||
if (opt.detail === 'win10-needs-patch') return t(locale, 'optKernelIrqchipWin10NoPatch')
|
||||
if (opt.detail && opt.detail.startsWith('0x')) return t(locale, 'optKernelIrqchipNestedErr', { code: opt.detail })
|
||||
return t(locale, 'optKernelIrqchipUnavailable')
|
||||
}
|
||||
|
||||
const IRQCHIP_RE = /(?:^|\s)-machine\s+kernel-irqchip=(on|off)(?=\s|$)/i
|
||||
const INLINE_IRQCHIP_RE = /\bkernel-irqchip=(on|off)\b/i
|
||||
|
||||
export function parseKernelIrqchip(extraArgs: string | undefined): KernelIrqchipMode {
|
||||
const raw = (extraArgs ?? '').trim()
|
||||
const m = raw.match(IRQCHIP_RE) ?? raw.match(INLINE_IRQCHIP_RE)
|
||||
if (!m) return 'auto'
|
||||
return m[1].toLowerCase() === 'on' ? 'on' : 'off'
|
||||
}
|
||||
|
||||
export function applyKernelIrqchip(extraArgs: string | undefined, mode: KernelIrqchipMode): string {
|
||||
const cleaned = (extraArgs ?? '')
|
||||
.replace(/(?:^|\s)-machine\s+kernel-irqchip=(?:on|off)(?=\s|$)/gi, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
if (mode === 'auto') return cleaned
|
||||
const flag = `-machine kernel-irqchip=${mode}`
|
||||
return cleaned ? `${cleaned} ${flag}` : flag
|
||||
}
|
||||
@@ -19,7 +19,9 @@ export function currentTask(all: Record<string, Task>): { task: Task | null; run
|
||||
export function taskTitle(locale: Locale, task: Task): string {
|
||||
switch (task.kind) {
|
||||
case 'installer-download': return t(locale, 'taskDownload', { v: task.subject })
|
||||
case 'recovery-download': return t(locale, 'taskRecoveryDownload', { name: task.subject })
|
||||
case 'vm-create': return t(locale, 'taskCreate', { name: task.subject })
|
||||
case 'runtime-install': return t(locale, 'taskRuntime', { v: task.subject })
|
||||
default: return task.subject
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
html, body, #root {
|
||||
margin: 0; padding: 0; height: 100%; overflow: hidden;
|
||||
background: var(--surface-0); color: var(--text);
|
||||
font-family: var(--font-sans); font-size: var(--fs-14); line-height: 1.5;
|
||||
font-family: var(--font-sans); font-size: var(--fs-14); line-height: 1.48;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
@@ -31,59 +31,104 @@ h1, h2, h3, p { margin: 0; }
|
||||
@keyframes pulse { 50% { opacity: 0.35; } }
|
||||
|
||||
/* ── Shell ─────────────────────────────────────────────── */
|
||||
.app-shell { display: flex; flex-direction: column; height: 100%; border: 1px solid var(--border); }
|
||||
.app-shell { display: flex; flex-direction: column; height: 100%; background: var(--surface-0); }
|
||||
|
||||
.titlebar {
|
||||
height: var(--titlebar-h); flex-shrink: 0;
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding-left: var(--sp-4);
|
||||
background: var(--surface-chrome); border-bottom: 1px solid var(--border);
|
||||
background: var(--surface-chrome);
|
||||
border-bottom: 1px solid var(--border);
|
||||
user-select: none; --wails-draggable: drag;
|
||||
}
|
||||
.brand { display: flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-13); font-weight: var(--fw-strong); }
|
||||
.brand { display: flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-13); font-weight: var(--fw-strong); color: var(--text); }
|
||||
.brand-mark {
|
||||
width: 18px; height: 18px; border-radius: var(--r-sm);
|
||||
background: var(--accent); color: var(--accent-text);
|
||||
display: grid; place-items: center; font-size: var(--fs-12); font-weight: var(--fw-strong);
|
||||
/* The SVG has its own squircle plus shadow padding; scale it so the squircle reads ~20px. */
|
||||
width: 24px; height: 24px; margin: -2px;
|
||||
display: block;
|
||||
}
|
||||
.titlebar-right { display: flex; align-items: center; height: 100%; gap: var(--sp-1); --wails-draggable: no-drag; }
|
||||
.theme-toggle {
|
||||
width: 30px; height: 28px; margin-right: var(--sp-1);
|
||||
border: 1px solid var(--border); border-radius: var(--r-md);
|
||||
background: var(--surface-1); color: var(--text-2);
|
||||
display: grid; place-items: center; cursor: pointer;
|
||||
transition: background var(--dur-fast), color var(--dur-fast);
|
||||
}
|
||||
.theme-toggle:hover { background: var(--surface-hover); color: var(--text); }
|
||||
|
||||
.win-controls { display: flex; height: 100%; --wails-draggable: no-drag; }
|
||||
.win-btn {
|
||||
width: 46px; height: 100%; border: none; background: transparent; color: var(--text-2);
|
||||
display: grid; place-items: center; cursor: pointer; transition: background var(--dur-fast);
|
||||
width: 44px; height: 100%; border: none; background: transparent; color: var(--text-2);
|
||||
display: grid; place-items: center; cursor: pointer; transition: background var(--dur-fast), color var(--dur-fast);
|
||||
}
|
||||
.win-btn:hover { background: var(--surface-hover); color: var(--text); }
|
||||
.win-btn.close:hover { background: #c42b1c; color: #fff; }
|
||||
.win-btn.close:hover { background: #e81123; color: #fff; }
|
||||
.win-btn:focus-visible { border-radius: 0; }
|
||||
|
||||
.workspace { display: flex; flex: 1; min-height: 0; }
|
||||
.workspace { display: flex; flex: 1; min-height: 0; background: var(--surface-canvas); }
|
||||
|
||||
/* ── Sidebar ───────────────────────────────────────────── */
|
||||
.sidebar {
|
||||
/* ── Floating Tahoe Sidebar ────────────────────────────── */
|
||||
.sidebar-wrap {
|
||||
width: var(--sidebar-w); flex-shrink: 0;
|
||||
padding: 10px 0 10px 10px;
|
||||
display: flex;
|
||||
}
|
||||
.sidebar {
|
||||
flex: 1; min-height: 0;
|
||||
display: flex; flex-direction: column; gap: var(--sp-1);
|
||||
padding: var(--sp-2); overflow-y: auto;
|
||||
background: var(--surface-sidebar); border-right: 1px solid var(--border);
|
||||
padding: 10px 8px; overflow-y: auto;
|
||||
background: var(--surface-sidebar);
|
||||
border: 1px solid var(--surface-sidebar-border);
|
||||
border-radius: 14px;
|
||||
box-shadow: var(--surface-sidebar-shadow);
|
||||
}
|
||||
.sidebar-head {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding: var(--sp-2) var(--sp-1) var(--sp-1) var(--sp-2);
|
||||
font-size: var(--fs-12); font-weight: var(--fw-strong); color: var(--text-3);
|
||||
padding: 4px 6px 6px 10px;
|
||||
font-size: 11px; font-weight: var(--fw-strong); letter-spacing: 0.02em;
|
||||
color: var(--text-3); text-transform: uppercase;
|
||||
}
|
||||
.sidebar-sep { height: 1px; background: var(--border); margin: var(--sp-2); }
|
||||
.nav { display: flex; flex-direction: column; gap: 2px; }
|
||||
.nav-empty { padding: var(--sp-1) var(--sp-2); font-size: var(--fs-13); color: var(--text-3); }
|
||||
.sidebar-sep { height: 1px; background: var(--border); margin: 8px 10px; }
|
||||
.nav { display: flex; flex-direction: column; gap: 3px; }
|
||||
.nav-empty { padding: 6px 10px; font-size: var(--fs-13); color: var(--text-3); }
|
||||
.nav-item {
|
||||
width: 100%; height: 34px; padding: 0 var(--sp-2);
|
||||
display: flex; align-items: center; gap: var(--sp-2);
|
||||
border: none; border-radius: var(--r-md); background: transparent; color: var(--text-2);
|
||||
text-align: left; cursor: pointer; transition: background var(--dur-fast), color var(--dur-fast);
|
||||
width: 100%; height: 36px; padding: 0 10px;
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
border: none; border-radius: 9px; background: transparent; color: var(--text);
|
||||
text-align: left; cursor: pointer;
|
||||
transition: background var(--dur-fast), color var(--dur-fast);
|
||||
}
|
||||
.nav-item:hover { background: var(--surface-hover); color: var(--text); }
|
||||
.nav-item[aria-selected="true"] { background: var(--accent-soft); color: var(--text); }
|
||||
.nav-item[aria-selected="true"] > svg { color: var(--accent-soft-text); }
|
||||
.nav-item:hover { background: var(--surface-hover); }
|
||||
.nav-item[aria-selected="true"] {
|
||||
background: var(--accent);
|
||||
color: var(--accent-text);
|
||||
font-weight: var(--fw-medium);
|
||||
box-shadow: 0 1px 3px rgba(0, 122, 255, 0.28);
|
||||
}
|
||||
.nav-item[aria-selected="true"] .nav-icon-badge {
|
||||
background: rgba(255, 255, 255, 0.22);
|
||||
color: #ffffff;
|
||||
box-shadow: none;
|
||||
}
|
||||
.nav-item[aria-selected="true"] .status-running {
|
||||
background: #ffffff;
|
||||
box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.25);
|
||||
}
|
||||
.nav-item[aria-selected="true"] .status-stopped {
|
||||
border-color: rgba(255, 255, 255, 0.7);
|
||||
}
|
||||
.nav-icon-badge {
|
||||
width: 24px; height: 24px; border-radius: 7px; flex-shrink: 0;
|
||||
display: grid; place-items: center; color: #ffffff;
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.14);
|
||||
}
|
||||
.nav-icon-vm { background: linear-gradient(145deg, #32a0ff 0%, #007aff 100%); }
|
||||
.nav-icon-host { background: linear-gradient(145deg, #8e8e93 0%, #636366 100%); }
|
||||
.nav-icon-installers { background: linear-gradient(145deg, #34c759 0%, #248a3d 100%); }
|
||||
.nav-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--fs-13); }
|
||||
|
||||
/* Status shapes: shape + colour, never colour alone */
|
||||
/* Status shapes */
|
||||
.status { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; display: inline-block; }
|
||||
.status-running { background: var(--status-running); }
|
||||
.status-stopped { border: 1.5px solid var(--status-idle); }
|
||||
@@ -93,50 +138,101 @@ h1, h2, h3, p { margin: 0; }
|
||||
|
||||
/* ── Main column ───────────────────────────────────────── */
|
||||
.main { flex: 1; min-width: 0; display: flex; flex-direction: column; }
|
||||
.scroll { flex: 1; overflow-y: auto; padding: var(--sp-6) var(--sp-8); }
|
||||
.page { max-width: var(--page-max); margin: 0 auto; display: flex; flex-direction: column; gap: var(--sp-6); }
|
||||
.scroll { flex: 1; overflow-y: auto; padding: 20px 32px 32px; }
|
||||
.page { max-width: var(--page-max); margin: 0 auto; display: flex; flex-direction: column; gap: 20px; }
|
||||
|
||||
.page-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); min-height: 32px; }
|
||||
.page-title { display: flex; align-items: baseline; gap: var(--sp-3); min-width: 0; }
|
||||
.page-title h1 { font-size: var(--fs-20); font-weight: var(--fw-strong); letter-spacing: -0.01em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.state-text { display: inline-flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-13); color: var(--text-2); white-space: nowrap; }
|
||||
.actions { display: flex; align-items: center; gap: var(--sp-1); flex-shrink: 0; }
|
||||
.actions .btn + .icon-btn, .actions .btn + .btn { margin-left: var(--sp-1); }
|
||||
.page-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); min-height: 34px; }
|
||||
.page-title { display: flex; align-items: center; gap: 10px; min-width: 0; }
|
||||
.page-title h1 { font-size: 16px; font-weight: var(--fw-strong); letter-spacing: -0.01em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.state-text { display: inline-flex; align-items: center; gap: 6px; font-size: var(--fs-12); color: var(--text-2); white-space: nowrap; }
|
||||
.actions { display: flex; align-items: center; gap: 6px; flex-shrink: 0; }
|
||||
|
||||
.section { display: flex; flex-direction: column; gap: var(--sp-2); }
|
||||
.section-title { font-size: var(--fs-13); font-weight: var(--fw-strong); color: var(--text-2); display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); min-height: 28px; }
|
||||
/* ── macOS Tahoe "About This Mac" Hero ─────────────────── */
|
||||
.vm-hero {
|
||||
display: flex; flex-direction: column; align-items: center;
|
||||
gap: 8px; padding: 4px 0 6px; text-align: center;
|
||||
}
|
||||
.vm-imac-svg { width: 112px; height: 88px; filter: drop-shadow(0 6px 14px rgba(15, 23, 42, 0.12)); }
|
||||
.vm-hero-name { font-size: 22px; font-weight: 700; letter-spacing: -0.02em; color: var(--text); }
|
||||
.vm-hero-pill {
|
||||
display: inline-flex; align-items: center; gap: 6px;
|
||||
padding: 3px 10px; border-radius: 999px;
|
||||
background: var(--surface-1); border: 1px solid var(--border);
|
||||
font-size: var(--fs-12); font-weight: var(--fw-medium); color: var(--text-2);
|
||||
}
|
||||
|
||||
/* ── Tahoe Grouped Inset Sections ──────────────────────── */
|
||||
.section { display: flex; flex-direction: column; gap: 8px; }
|
||||
.section-title {
|
||||
font-size: var(--fs-13); font-weight: var(--fw-strong); color: var(--text);
|
||||
padding: 0 4px;
|
||||
display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); min-height: 26px;
|
||||
}
|
||||
|
||||
.tahoe-group {
|
||||
background: var(--surface-1);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--r-lg);
|
||||
overflow: hidden;
|
||||
}
|
||||
.tahoe-row {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 16px;
|
||||
min-height: 40px; padding: 9px 16px;
|
||||
position: relative; font-size: 13.5px;
|
||||
}
|
||||
.tahoe-row + .tahoe-row::before {
|
||||
content: ""; position: absolute; top: 0; left: 16px; right: 16px;
|
||||
height: 1px; background: var(--border);
|
||||
}
|
||||
.tahoe-label { color: var(--text); font-weight: var(--fw-regular); display: inline-flex; align-items: center; gap: 10px; flex-shrink: 0; }
|
||||
.tahoe-value { color: var(--text-2); text-align: right; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; user-select: text; }
|
||||
.tahoe-orb {
|
||||
width: 24px; height: 24px; border-radius: 50%; flex-shrink: 0;
|
||||
background: radial-gradient(circle at 32% 30%, #6fd2ff 0%, #1c7ef2 55%, #0b419e 100%);
|
||||
box-shadow: inset 0 1px 2px rgba(255, 255, 255, 0.55), 0 1px 3px rgba(0, 82, 204, 0.28);
|
||||
}
|
||||
.tahoe-display-icon {
|
||||
width: 24px; height: 20px; border-radius: 4px; flex-shrink: 0;
|
||||
background: linear-gradient(160deg, #5cc2ff 0%, #1b7ff2 100%);
|
||||
border: 1.5px solid #2b2b2f;
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
/* ── Buttons ───────────────────────────────────────────── */
|
||||
.btn {
|
||||
height: 30px; padding: 0 var(--sp-3);
|
||||
display: inline-flex; align-items: center; justify-content: center; gap: var(--sp-2);
|
||||
height: 30px; padding: 0 12px;
|
||||
display: inline-flex; align-items: center; justify-content: center; gap: 6px;
|
||||
border-radius: var(--r-md); border: 1px solid var(--border-strong);
|
||||
background: var(--surface-1); color: var(--text);
|
||||
font-size: var(--fs-13); font-weight: var(--fw-regular); white-space: nowrap; flex-shrink: 0;
|
||||
cursor: pointer; transition: background var(--dur-fast), border-color var(--dur-fast);
|
||||
background: var(--surface-card-elevated); color: var(--text);
|
||||
box-shadow: var(--shadow-btn);
|
||||
font-size: var(--fs-13); font-weight: var(--fw-medium); white-space: nowrap; flex-shrink: 0;
|
||||
cursor: pointer; transition: background var(--dur-fast), border-color var(--dur-fast), transform var(--dur-fast);
|
||||
}
|
||||
.btn:hover:not(:disabled) { background: var(--surface-hover); }
|
||||
.btn:disabled { opacity: 0.45; cursor: default; }
|
||||
.btn-primary { background: var(--accent); border-color: transparent; color: var(--accent-text); font-weight: var(--fw-strong); }
|
||||
.btn:disabled { opacity: 0.45; cursor: default; box-shadow: none; }
|
||||
.btn-primary { background: var(--accent); border-color: transparent; color: var(--accent-text); font-weight: var(--fw-strong); box-shadow: 0 1px 3px rgba(0, 122, 255, 0.3); }
|
||||
.btn-primary:hover:not(:disabled) { background: var(--accent-hover); }
|
||||
.btn-danger { background: var(--danger); border-color: transparent; color: #fff; font-weight: var(--fw-strong); }
|
||||
.btn-danger:hover:not(:disabled) { filter: brightness(1.08); background: var(--danger); }
|
||||
.btn-ghost { background: transparent; border-color: transparent; color: var(--text-2); }
|
||||
.btn-ghost:hover:not(:disabled) { color: var(--text); }
|
||||
.btn-danger:hover:not(:disabled) { filter: brightness(1.06); background: var(--danger); }
|
||||
.btn-ghost { background: transparent; border-color: transparent; color: var(--text-2); box-shadow: none; }
|
||||
.btn-ghost:hover:not(:disabled) { background: var(--surface-hover); color: var(--text); }
|
||||
|
||||
.icon-btn {
|
||||
width: 30px; height: 30px; flex-shrink: 0;
|
||||
display: inline-grid; place-items: center;
|
||||
border: none; border-radius: var(--r-md); background: transparent; color: var(--text-2);
|
||||
border: 1px solid var(--border); border-radius: var(--r-md);
|
||||
background: var(--surface-card-elevated); color: var(--text-2);
|
||||
box-shadow: var(--shadow-btn);
|
||||
cursor: pointer; transition: background var(--dur-fast), color var(--dur-fast);
|
||||
}
|
||||
.icon-btn:hover:not(:disabled), .icon-btn[data-state="open"] { background: var(--surface-hover); color: var(--text); }
|
||||
.icon-btn:disabled { opacity: 0.4; cursor: default; }
|
||||
.icon-btn.sm { width: 26px; height: 26px; }
|
||||
.icon-btn:disabled { opacity: 0.4; cursor: default; box-shadow: none; }
|
||||
.icon-btn.sm { width: 26px; height: 26px; border-color: transparent; background: transparent; box-shadow: none; }
|
||||
.icon-btn.sm:hover:not(:disabled) { background: var(--surface-hover); }
|
||||
|
||||
.segmented { display: inline-flex; padding: 2px; gap: 2px; border-radius: var(--r-md); background: var(--surface-input); border: 1px solid var(--border); }
|
||||
.segmented button { height: 24px; padding: 0 var(--sp-3); border: none; border-radius: var(--r-sm); background: transparent; color: var(--text-2); font-size: var(--fs-13); cursor: pointer; }
|
||||
.segmented button[aria-pressed="true"] { background: var(--surface-active); color: var(--text); font-weight: var(--fw-strong); }
|
||||
.segmented { display: inline-flex; padding: 2px; gap: 2px; border-radius: var(--r-md); background: var(--surface-active); border: 1px solid var(--border); }
|
||||
.segmented button { height: 24px; padding: 0 12px; border: none; border-radius: var(--r-sm); background: transparent; color: var(--text-2); font-size: var(--fs-13); cursor: pointer; }
|
||||
.segmented button[aria-pressed="true"] { background: var(--surface-card-elevated); color: var(--text); font-weight: var(--fw-strong); box-shadow: var(--shadow-btn); }
|
||||
|
||||
/* ── Cards & notices ───────────────────────────────────── */
|
||||
.card { background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg); padding: var(--sp-4); display: flex; flex-direction: column; gap: var(--sp-3); }
|
||||
@@ -145,71 +241,78 @@ h1, h2, h3, p { margin: 0; }
|
||||
|
||||
.notice {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3);
|
||||
padding: var(--sp-2) var(--sp-2) var(--sp-2) var(--sp-4);
|
||||
padding: 10px 12px 10px 14px;
|
||||
border-radius: var(--r-lg); background: var(--notice-soft); border: 1px solid var(--notice-border);
|
||||
font-size: var(--fs-13);
|
||||
font-size: var(--fs-13); color: var(--text);
|
||||
}
|
||||
.notice-error { background: var(--danger-soft); border-color: rgba(240, 98, 90, 0.3); color: #ff9c95; padding: var(--sp-2) var(--sp-4); }
|
||||
.notice-error { background: var(--danger-soft); border-color: rgba(255, 59, 48, 0.28); color: var(--danger-text); padding: 10px 14px; }
|
||||
.notice-error ul { margin: 0; padding-left: var(--sp-4); }
|
||||
|
||||
.steps { margin: 0; padding-left: var(--sp-6); display: flex; flex-direction: column; gap: var(--sp-1); color: var(--text-2); font-size: var(--fs-13); }
|
||||
|
||||
/* ── Facts row (icon + value) ──────────────────────────── */
|
||||
.facts { display: flex; flex-wrap: wrap; gap: var(--sp-2) var(--sp-6); }
|
||||
.fact { display: inline-flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-14); color: var(--text); border-radius: var(--r-sm); }
|
||||
.fact > svg { color: var(--text-3); }
|
||||
|
||||
/* ── Command line & technical details ──────────────────── */
|
||||
.cmd-line {
|
||||
display: flex; align-items: center; gap: var(--sp-3);
|
||||
padding: var(--sp-1) var(--sp-1) var(--sp-1) var(--sp-3);
|
||||
border-radius: var(--r-lg); background: var(--surface-input); border: 1px solid var(--border);
|
||||
padding: 6px 6px 6px 14px;
|
||||
border-radius: var(--r-lg); background: var(--surface-1); border: 1px solid var(--border);
|
||||
}
|
||||
.cmd-line > svg { color: var(--text-3); }
|
||||
.cmd-line code { flex: 1; font-family: var(--font-mono); font-size: var(--fs-13); color: var(--text-code); user-select: text; }
|
||||
|
||||
/* ── Disclosure: technical details ─────────────────────── */
|
||||
.tech > summary {
|
||||
list-style: none; cursor: pointer; display: inline-flex; align-items: center; gap: var(--sp-1);
|
||||
font-size: var(--fs-13); color: var(--text-2); border-radius: var(--r-sm);
|
||||
padding: 2px 4px;
|
||||
font-size: var(--fs-13); font-weight: var(--fw-medium); color: var(--text-2); border-radius: var(--r-sm);
|
||||
}
|
||||
.tech > summary::-webkit-details-marker { display: none; }
|
||||
.tech > summary svg { transition: transform var(--dur-fast); }
|
||||
.tech[open] > summary svg { transform: rotate(90deg); }
|
||||
.tech > summary:hover { color: var(--text); }
|
||||
.kv-list { margin: var(--sp-3) 0 0; display: grid; grid-template-columns: max-content 1fr; gap: var(--sp-2) var(--sp-6); font-size: var(--fs-13); }
|
||||
.kv-list {
|
||||
margin: 10px 0 0; padding: 12px 16px;
|
||||
background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg);
|
||||
display: grid; grid-template-columns: max-content 1fr; gap: 8px 24px; font-size: var(--fs-13);
|
||||
}
|
||||
.kv-list dt { color: var(--text-3); }
|
||||
.kv-list dd { margin: 0; color: var(--text-2); word-break: break-all; user-select: text; }
|
||||
|
||||
/* ── Grouped list (host page, settings) ────────────────── */
|
||||
.list { background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg); overflow: hidden; }
|
||||
.row { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); padding: var(--sp-3) var(--sp-4); position: relative; }
|
||||
.row + .row::before { content: ""; position: absolute; top: 0; left: var(--sp-4); right: var(--sp-4); height: 1px; background: var(--border); }
|
||||
.row { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); padding: 11px 16px; position: relative; }
|
||||
.row + .row::before { content: ""; position: absolute; top: 0; left: 16px; right: 16px; height: 1px; background: var(--border); }
|
||||
.row-main { min-width: 0; flex: 1; display: flex; flex-direction: column; gap: 2px; }
|
||||
.row-title { font-size: var(--fs-14); display: flex; align-items: center; gap: var(--sp-2); flex-wrap: wrap; }
|
||||
.row-title { font-size: 13.5px; display: flex; align-items: center; gap: var(--sp-2); flex-wrap: wrap; color: var(--text); }
|
||||
.row-sub { font-size: var(--fs-12); color: var(--text-3); word-break: break-all; }
|
||||
.row-right { display: flex; align-items: center; gap: var(--sp-2); flex-shrink: 0; }
|
||||
|
||||
.badge { display: inline-flex; align-items: center; height: 20px; padding: 0 var(--sp-2); border-radius: var(--r-sm); font-size: var(--fs-12); white-space: nowrap; background: var(--surface-active); color: var(--text-2); }
|
||||
.badge { display: inline-flex; align-items: center; height: 20px; padding: 0 8px; border-radius: 999px; font-size: 11.5px; font-weight: var(--fw-medium); white-space: nowrap; background: var(--surface-active); color: var(--text-2); }
|
||||
.badge-accent { background: var(--accent-soft); color: var(--accent-soft-text); }
|
||||
.badge-ok { background: rgba(63, 185, 80, 0.15); color: var(--status-running); }
|
||||
.badge-warn { background: rgba(212, 167, 44, 0.15); color: var(--status-busy); }
|
||||
.badge-ok { background: rgba(40, 205, 65, 0.14); color: #1a9e30; }
|
||||
:root[data-theme="dark"] .badge-ok { color: var(--status-running); }
|
||||
.badge-warn { background: rgba(255, 159, 10, 0.16); color: #b86e00; }
|
||||
:root[data-theme="dark"] .badge-warn { color: var(--status-busy); }
|
||||
.badge-error { background: var(--danger); color: #fff; min-width: 18px; height: 18px; padding: 0 var(--sp-1); justify-content: center; border-radius: 999px; }
|
||||
|
||||
.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: var(--sp-3); }
|
||||
.tile { background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg); padding: var(--sp-3) var(--sp-4); display: flex; flex-direction: column; gap: var(--sp-1); min-width: 0; }
|
||||
.tile-head { display: flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-12); color: var(--text-3); }
|
||||
.tile-value { font-size: var(--fs-16); font-weight: var(--fw-strong); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.tile-value.ok { color: var(--status-running); }
|
||||
.tile-value.warn { color: var(--status-busy); }
|
||||
.tiles { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; }
|
||||
.tile .tile-action { align-self: flex-start; height: 26px; margin-top: 2px; }
|
||||
.tile { background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg); padding: 12px 14px; display: flex; flex-direction: column; gap: 4px; min-width: 0; }
|
||||
.tile-head { display: flex; align-items: center; gap: 6px; font-size: var(--fs-12); color: var(--text-3); }
|
||||
.tile-value { font-size: 15px; font-weight: var(--fw-strong); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--text); }
|
||||
.tile-value.ok { color: #1a9e30; }
|
||||
:root[data-theme="dark"] .tile-value.ok { color: var(--status-running); }
|
||||
.tile-value.warn { color: #b86e00; }
|
||||
:root[data-theme="dark"] .tile-value.warn { color: var(--status-busy); }
|
||||
.tile-sub { font-size: var(--fs-12); color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
|
||||
.switch { position: relative; display: inline-block; width: 36px; height: 20px; flex-shrink: 0; cursor: pointer; }
|
||||
/* macOS Tahoe Switch */
|
||||
.switch { position: relative; display: inline-block; width: 38px; height: 22px; flex-shrink: 0; cursor: pointer; }
|
||||
.switch input { position: absolute; opacity: 0; width: 100%; height: 100%; margin: 0; cursor: pointer; }
|
||||
.slider { position: absolute; inset: 0; border-radius: 999px; background: var(--surface-active); border: 1px solid var(--border-strong); transition: background var(--dur); pointer-events: none; }
|
||||
.slider::before { content: ""; position: absolute; width: 14px; height: 14px; left: 2px; top: 2px; border-radius: 50%; background: var(--text-2); transition: transform var(--dur), background var(--dur); }
|
||||
.switch input:checked + .slider { background: var(--accent); border-color: transparent; }
|
||||
.switch input:checked + .slider::before { transform: translateX(16px); background: #fff; }
|
||||
.slider { position: absolute; inset: 0; border-radius: 999px; background: var(--surface-active); transition: background var(--dur); pointer-events: none; }
|
||||
.slider::before { content: ""; position: absolute; width: 18px; height: 18px; left: 2px; top: 2px; border-radius: 50%; background: #ffffff; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.22); transition: transform var(--dur); }
|
||||
.switch input:checked + .slider { background: var(--accent); }
|
||||
.switch input:checked + .slider::before { transform: translateX(16px); }
|
||||
.switch input:focus-visible + .slider { box-shadow: var(--focus-ring); }
|
||||
.switch input:disabled + .slider { opacity: 0.45; cursor: not-allowed; }
|
||||
|
||||
/* ── Log bar & panel ───────────────────────────────────── */
|
||||
.logs { flex-shrink: 0; display: flex; flex-direction: column; border-top: 1px solid var(--border); background: var(--surface-chrome); }
|
||||
@@ -217,7 +320,7 @@ h1, h2, h3, p { margin: 0; }
|
||||
.tabs { display: flex; gap: 2px; }
|
||||
.tab { height: 24px; padding: 0 var(--sp-2); border: none; border-radius: var(--r-sm); background: transparent; color: var(--text-3); font-size: var(--fs-12); cursor: pointer; }
|
||||
.tab:hover { color: var(--text); }
|
||||
.tab[aria-selected="true"] { background: var(--surface-active); color: var(--text); }
|
||||
.tab[aria-selected="true"] { background: var(--surface-active); color: var(--text); font-weight: var(--fw-medium); }
|
||||
.task { display: inline-flex; align-items: center; gap: var(--sp-2); min-width: 0; font-size: var(--fs-12); color: var(--text-2); }
|
||||
.task-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.progress { width: 96px; height: 4px; border-radius: 999px; background: var(--surface-active); overflow: hidden; flex-shrink: 0; }
|
||||
@@ -236,30 +339,30 @@ h1, h2, h3, p { margin: 0; }
|
||||
.jump-latest { position: absolute; right: var(--sp-4); bottom: var(--sp-3); }
|
||||
|
||||
/* ── Overlays: dialog, menu, tooltip, toast ────────────── */
|
||||
.overlay { position: fixed; inset: 0; background: var(--scrim); z-index: 40; }
|
||||
.overlay { position: fixed; inset: 0; background: var(--scrim); backdrop-filter: blur(4px); z-index: 40; }
|
||||
.dialog {
|
||||
position: fixed; z-index: 41; left: 50%; top: 50%; transform: translate(-50%, -50%);
|
||||
width: 720px; max-width: calc(100vw - 48px); max-height: calc(100vh - 80px);
|
||||
display: flex; flex-direction: column; overflow: hidden;
|
||||
background: var(--surface-2); border: 1px solid var(--border-strong); border-radius: var(--r-xl);
|
||||
box-shadow: 0 24px 64px rgba(0, 0, 0, 0.5);
|
||||
background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-xl);
|
||||
box-shadow: var(--shadow-overlay);
|
||||
}
|
||||
.dialog.sm { width: 420px; }
|
||||
.dialog-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); padding: var(--sp-3) var(--sp-3) var(--sp-3) var(--sp-6); border-bottom: 1px solid var(--border); }
|
||||
.dialog-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); padding: 14px 14px 14px 22px; border-bottom: 1px solid var(--border); }
|
||||
.dialog-title { font-size: var(--fs-16); font-weight: var(--fw-strong); }
|
||||
.dialog-desc { font-size: var(--fs-13); color: var(--text-2); }
|
||||
.dialog-body { padding: var(--sp-6); overflow-y: auto; flex: 1; display: flex; flex-direction: column; gap: var(--sp-4); }
|
||||
.dialog-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); padding: var(--sp-3) var(--sp-6); border-top: 1px solid var(--border); }
|
||||
.dialog.sm .dialog-body { padding: var(--sp-6) var(--sp-6) var(--sp-4); gap: var(--sp-3); }
|
||||
.dialog.sm .dialog-foot { border-top: none; justify-content: flex-end; padding-top: 0; padding-bottom: var(--sp-6); }
|
||||
.dialog-body { padding: 20px 22px; overflow-y: auto; flex: 1; display: flex; flex-direction: column; gap: var(--sp-4); }
|
||||
.dialog-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); padding: 12px 22px; border-top: 1px solid var(--border); }
|
||||
.dialog.sm .dialog-body { padding: 22px 22px 14px; gap: var(--sp-3); }
|
||||
.dialog.sm .dialog-foot { border-top: none; justify-content: flex-end; padding-top: 0; padding-bottom: 20px; }
|
||||
|
||||
.menu {
|
||||
min-width: 180px; padding: var(--sp-1); z-index: 50;
|
||||
background: var(--surface-2); border: 1px solid var(--border-strong); border-radius: var(--r-lg);
|
||||
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.45);
|
||||
min-width: 184px; padding: 5px; z-index: 50;
|
||||
background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-lg);
|
||||
box-shadow: var(--shadow-overlay);
|
||||
}
|
||||
.menu-item {
|
||||
height: 30px; padding: 0 var(--sp-2); display: flex; align-items: center; gap: var(--sp-2);
|
||||
height: 30px; padding: 0 10px; display: flex; align-items: center; gap: 8px;
|
||||
border-radius: var(--r-sm); font-size: var(--fs-13); cursor: pointer; user-select: none; outline: none;
|
||||
}
|
||||
.menu-item > svg { color: var(--text-3); }
|
||||
@@ -270,12 +373,12 @@ h1, h2, h3, p { margin: 0; }
|
||||
.menu-item.danger > svg { color: var(--danger); }
|
||||
.menu-item.danger[data-highlighted] { background: var(--danger); color: #fff; }
|
||||
.menu-item.danger[data-highlighted] > svg { color: #fff; }
|
||||
.menu-sep { height: 1px; margin: var(--sp-1) var(--sp-2); background: var(--border); }
|
||||
.menu-sep { height: 1px; margin: 4px 8px; background: var(--border); }
|
||||
|
||||
.tooltip {
|
||||
z-index: 60; padding: var(--sp-1) var(--sp-2); border-radius: var(--r-sm);
|
||||
z-index: 60; padding: 4px 9px; border-radius: var(--r-sm);
|
||||
background: var(--surface-2); border: 1px solid var(--border-strong); color: var(--text);
|
||||
font-size: var(--fs-12); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.35);
|
||||
font-size: var(--fs-12); box-shadow: 0 6px 18px rgba(15, 23, 42, 0.16);
|
||||
display: flex; gap: var(--sp-2); align-items: center;
|
||||
}
|
||||
.tooltip kbd { font-family: var(--font-sans); color: var(--text-3); }
|
||||
@@ -283,8 +386,8 @@ h1, h2, h3, p { margin: 0; }
|
||||
.toast-viewport { position: fixed; right: var(--sp-4); bottom: calc(var(--logbar-h) + var(--sp-4)); z-index: 70; display: flex; flex-direction: column; gap: var(--sp-2); width: 340px; max-width: calc(100vw - 32px); margin: 0; padding: 0; list-style: none; outline: none; }
|
||||
.toast {
|
||||
display: flex; align-items: flex-start; gap: var(--sp-3); padding: var(--sp-3);
|
||||
background: var(--surface-2); border: 1px solid var(--border-strong); border-radius: var(--r-lg);
|
||||
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.45);
|
||||
background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-lg);
|
||||
box-shadow: var(--shadow-overlay);
|
||||
}
|
||||
.toast > svg { margin-top: 2px; flex-shrink: 0; }
|
||||
.toast.ok > svg { color: var(--status-running); }
|
||||
@@ -295,16 +398,16 @@ h1, h2, h3, p { margin: 0; }
|
||||
.toast .btn { height: 26px; }
|
||||
|
||||
/* ── Forms (wizard, settings) ──────────────────────────── */
|
||||
.field { display: flex; flex-direction: column; gap: var(--sp-2); }
|
||||
.field-label { font-size: var(--fs-13); color: var(--text-2); }
|
||||
.field { display: flex; flex-direction: column; gap: 6px; }
|
||||
.field-label { font-size: var(--fs-13); font-weight: var(--fw-medium); color: var(--text-2); }
|
||||
.field-row { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-4); }
|
||||
.input, .select {
|
||||
width: 100%; height: 32px; padding: 0 var(--sp-3);
|
||||
width: 100%; height: 32px; padding: 0 10px;
|
||||
border-radius: var(--r-md); border: 1px solid var(--border-strong);
|
||||
background: var(--surface-input); color: var(--text); font: inherit; font-size: var(--fs-13);
|
||||
}
|
||||
.input:focus, .select:focus { border-color: var(--accent); box-shadow: var(--focus-ring); }
|
||||
.input[readonly] { color: var(--text-2); }
|
||||
.input[readonly] { color: var(--text-2); background: var(--surface-1); }
|
||||
.input.mono { font-family: var(--font-mono); font-size: var(--fs-12); }
|
||||
.input-group { display: flex; gap: var(--sp-2); align-items: center; }
|
||||
.hint { font-size: var(--fs-12); color: var(--text-3); }
|
||||
@@ -314,23 +417,87 @@ h1, h2, h3, p { margin: 0; }
|
||||
.choice input { accent-color: var(--accent); margin: 0; }
|
||||
.presets { display: flex; flex-wrap: wrap; gap: var(--sp-2); }
|
||||
.preset {
|
||||
height: 28px; padding: 0 var(--sp-3); border-radius: var(--r-md);
|
||||
border: 1px solid var(--border-strong); background: transparent; color: var(--text-2);
|
||||
height: 28px; padding: 0 12px; border-radius: var(--r-md);
|
||||
border: 1px solid var(--border-strong); background: var(--surface-card-elevated); color: var(--text-2);
|
||||
font-size: var(--fs-13); cursor: pointer;
|
||||
}
|
||||
.preset:hover { background: var(--surface-hover); color: var(--text); }
|
||||
.preset[aria-pressed="true"] { background: var(--accent); border-color: transparent; color: var(--accent-text); }
|
||||
.preset[aria-pressed="true"] { background: var(--accent); border-color: transparent; color: var(--accent-text); font-weight: var(--fw-medium); }
|
||||
|
||||
.wizard-steps { display: flex; gap: var(--sp-1); padding: var(--sp-2) var(--sp-6); border-bottom: 1px solid var(--border); flex-wrap: wrap; }
|
||||
.wizard-step { height: 26px; padding: 0 var(--sp-2); border: none; border-radius: var(--r-sm); background: transparent; color: var(--text-3); font-size: var(--fs-12); cursor: pointer; display: inline-flex; align-items: center; gap: var(--sp-1); }
|
||||
.wizard-steps { display: flex; gap: var(--sp-1); padding: 10px 22px; border-bottom: 1px solid var(--border); flex-wrap: wrap; }
|
||||
.wizard-step { height: 26px; padding: 0 10px; border: none; border-radius: 999px; background: transparent; color: var(--text-3); font-size: var(--fs-12); cursor: pointer; display: inline-flex; align-items: center; gap: var(--sp-1); }
|
||||
.wizard-step[aria-current="step"] { background: var(--accent-soft); color: var(--accent-soft-text); font-weight: var(--fw-strong); }
|
||||
.wizard-step.done { color: var(--text-2); }
|
||||
.wizard-step.done svg { color: var(--status-running); }
|
||||
.wizard-step.has-issue { color: var(--danger-text); }
|
||||
.wizard-step.has-issue[aria-current="step"] { background: var(--danger-soft); color: var(--danger-text); }
|
||||
|
||||
/* Wizard step ⑤: grouped summary */
|
||||
.review-status { display: flex; align-items: center; gap: 6px; font-size: var(--fs-13); color: var(--text-3); }
|
||||
.review-status.ok { color: var(--text-2); }
|
||||
.review-status.ok svg { color: var(--status-running); }
|
||||
.review-status.bad { color: var(--danger-text); font-weight: var(--fw-medium); }
|
||||
.review-groups { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-3); }
|
||||
.review-group {
|
||||
min-width: 0; padding: 12px 14px; border-radius: var(--r-lg);
|
||||
border: 1px solid var(--border); background: var(--surface-1);
|
||||
display: flex; flex-direction: column; gap: var(--sp-2);
|
||||
}
|
||||
.review-group:first-child, .review-group:last-child { grid-column: 1 / -1; }
|
||||
.review-group.has-issue { border-color: rgba(255, 59, 48, 0.4); background: var(--danger-soft); }
|
||||
.review-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); }
|
||||
.review-title { font-size: var(--fs-12); font-weight: var(--fw-strong); color: var(--text-3); }
|
||||
.link-btn { border: none; background: none; padding: 0; font: inherit; font-size: var(--fs-12); color: var(--accent-soft-text); cursor: pointer; }
|
||||
.link-btn:hover { text-decoration: underline; }
|
||||
.review-rows { display: grid; grid-template-columns: max-content 1fr; column-gap: var(--sp-4); row-gap: 6px; margin: 0; font-size: var(--fs-13); }
|
||||
.review-group:last-child .review-rows { grid-template-columns: max-content 1fr max-content 1fr; }
|
||||
.review-rows dt { color: var(--text-3); }
|
||||
.review-rows dd { margin: 0; min-width: 0; color: var(--text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.review-issues { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; font-size: var(--fs-12); color: var(--danger-text); }
|
||||
.review-issues li { display: flex; align-items: flex-start; gap: 6px; }
|
||||
.review-issues svg { flex-shrink: 0; margin-top: 2px; }
|
||||
.review-cmd > summary {
|
||||
list-style: none; display: inline-flex; align-items: center; gap: 4px; cursor: pointer;
|
||||
font-size: var(--fs-13); color: var(--text-2); user-select: none;
|
||||
}
|
||||
.review-cmd > summary::-webkit-details-marker { display: none; }
|
||||
.review-cmd > summary svg { transition: transform var(--dur-fast); }
|
||||
.review-cmd[open] > summary svg { transform: rotate(90deg); }
|
||||
.review-cmd-body { margin-top: var(--sp-2); display: flex; flex-direction: column; gap: 6px; }
|
||||
.review-cmd-box { display: flex; align-items: flex-start; gap: var(--sp-2); }
|
||||
.review-cmd-box .code { flex: 1; min-width: 0; }
|
||||
|
||||
.settings-split { display: flex; height: 460px; min-height: 0; }
|
||||
.settings-nav { width: 180px; flex-shrink: 0; padding: var(--sp-2); border-right: 1px solid var(--border); display: flex; flex-direction: column; gap: 2px; overflow-y: auto; }
|
||||
.settings-pane { flex: 1; padding: var(--sp-6); overflow-y: auto; display: flex; flex-direction: column; gap: var(--sp-4); }
|
||||
.settings-nav { width: 186px; flex-shrink: 0; padding: 10px 8px; border-right: 1px solid var(--border); background: var(--surface-1); display: flex; flex-direction: column; gap: 3px; overflow-y: auto; }
|
||||
.settings-pane { flex: 1; padding: 20px 24px; overflow-y: auto; display: flex; flex-direction: column; gap: var(--sp-4); }
|
||||
|
||||
.code { padding: var(--sp-3); border-radius: var(--r-md); background: var(--surface-input); border: 1px solid var(--border); font-family: var(--font-mono); font-size: var(--fs-12); color: var(--text-code); word-break: break-all; user-select: text; }
|
||||
.code { padding: 10px 12px; border-radius: var(--r-md); background: var(--surface-1); border: 1px solid var(--border); font-family: var(--font-mono); font-size: var(--fs-12); color: var(--text-code); word-break: break-all; user-select: text; }
|
||||
.fieldset { border: 0; padding: 0; margin: 0; min-width: 0; }
|
||||
.fieldset legend { padding: 0; margin-bottom: var(--sp-2); }
|
||||
|
||||
/* ── First launch ──────────────────────────────────────── */
|
||||
.setup { flex: 1; overflow-y: auto; display: grid; place-items: center; padding: var(--sp-8) var(--sp-4); }
|
||||
.setup-card { width: 560px; max-width: 100%; display: flex; flex-direction: column; gap: var(--sp-6); }
|
||||
.setup-head h1 { font-size: var(--fs-24); font-weight: var(--fw-strong); letter-spacing: -0.01em; }
|
||||
.setup-head p { margin-top: var(--sp-1); color: var(--text-2); font-size: var(--fs-14); }
|
||||
.setup-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); }
|
||||
.choices-list { display: flex; flex-direction: column; gap: var(--sp-2); }
|
||||
.choice-card {
|
||||
display: flex; align-items: center; gap: var(--sp-3); padding: var(--sp-3) var(--sp-4);
|
||||
border-radius: var(--r-lg); border: 1px solid var(--border); background: var(--surface-1);
|
||||
cursor: pointer; transition: border-color var(--dur-fast), background var(--dur-fast);
|
||||
}
|
||||
.choice-card:hover { background: var(--surface-hover); }
|
||||
.choice-card[data-selected="true"] { border-color: var(--accent); background: var(--accent-soft); }
|
||||
.choice-card input { position: absolute; opacity: 0; pointer-events: none; }
|
||||
.choice-card:focus-within { box-shadow: var(--focus-ring); }
|
||||
.choice-card > svg { color: var(--text-3); flex-shrink: 0; }
|
||||
.choice-card[data-selected="true"] > svg { color: var(--accent-soft-text); }
|
||||
.choice-card-main { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
|
||||
.choice-card-path { font-size: var(--fs-13); color: var(--text); word-break: break-all; }
|
||||
.choice-card-meta { display: flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-12); color: var(--text-3); }
|
||||
.choice-other { align-self: flex-start; }
|
||||
.task-inline { display: flex; align-items: center; gap: var(--sp-2); }
|
||||
|
||||
.guide-cmd { margin-top: var(--sp-2); }
|
||||
.warn-text { color: var(--status-busy); }
|
||||
@@ -1,18 +1,18 @@
|
||||
/* Design tokens. Components reference these only — no raw colours, sizes or
|
||||
spacing in component CSS or inline styles. See docs/ui-redesign.md §4.1. */
|
||||
/* Design tokens — macOS Tahoe System Settings aesthetic (Light default, Dark optional). */
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
color-scheme: light;
|
||||
|
||||
/* Type */
|
||||
--font-sans: "Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif;
|
||||
--font-mono: "Cascadia Mono", "JetBrains Mono", Consolas, monospace;
|
||||
--fs-12: 12px; /* captions, badges, log text */
|
||||
--fs-13: 13px; /* secondary text, controls */
|
||||
--fs-14: 14px; /* body */
|
||||
--fs-16: 16px; /* subtitles */
|
||||
--fs-20: 20px; /* page titles */
|
||||
--fs-24: 24px; /* empty-state titles */
|
||||
--font-sans: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif;
|
||||
--font-mono: "SF Mono", "Cascadia Mono", "JetBrains Mono", Consolas, monospace;
|
||||
--fs-12: 12px;
|
||||
--fs-13: 13px;
|
||||
--fs-14: 14px;
|
||||
--fs-16: 16px;
|
||||
--fs-20: 20px;
|
||||
--fs-24: 24px;
|
||||
--fw-regular: 400;
|
||||
--fw-medium: 500;
|
||||
--fw-strong: 600;
|
||||
|
||||
/* Spacing (4px grid) */
|
||||
@@ -24,57 +24,109 @@
|
||||
--sp-8: 32px;
|
||||
|
||||
/* Radius */
|
||||
--r-sm: 4px;
|
||||
--r-md: 6px;
|
||||
--r-lg: 8px;
|
||||
--r-xl: 12px;
|
||||
--r-sm: 6px;
|
||||
--r-md: 8px;
|
||||
--r-lg: 12px;
|
||||
--r-xl: 16px;
|
||||
|
||||
/* Surfaces */
|
||||
--surface-0: #1c1c1f; /* window */
|
||||
--surface-sidebar: #171719;
|
||||
--surface-chrome: #141416; /* title bar, log bar */
|
||||
--surface-1: rgba(255, 255, 255, 0.04); /* cards */
|
||||
--surface-2: #26262b; /* menus, dialogs, tooltips */
|
||||
--surface-input: rgba(0, 0, 0, 0.25);
|
||||
--surface-hover: rgba(255, 255, 255, 0.06);
|
||||
--surface-active: rgba(255, 255, 255, 0.10);
|
||||
--border: rgba(255, 255, 255, 0.08);
|
||||
--border-strong: rgba(255, 255, 255, 0.14);
|
||||
--scrim: rgba(0, 0, 0, 0.55);
|
||||
/* Surfaces (macOS Tahoe Light) */
|
||||
--surface-0: #ffffff;
|
||||
--surface-canvas: #ffffff;
|
||||
--surface-sidebar: linear-gradient(180deg, #eff5fc 0%, #eaf2fa 100%);
|
||||
--surface-sidebar-border: rgba(15, 23, 42, 0.07);
|
||||
--surface-sidebar-shadow: 0 2px 14px rgba(15, 23, 42, 0.06), inset 0 1px 0 rgba(255, 255, 255, 0.8);
|
||||
--surface-chrome: rgba(255, 255, 255, 0.88);
|
||||
--surface-1: #f5f6f8;
|
||||
--surface-card-elevated: #ffffff;
|
||||
--surface-2: rgba(255, 255, 255, 0.96);
|
||||
--surface-input: #ffffff;
|
||||
--surface-hover: rgba(15, 23, 42, 0.05);
|
||||
--surface-active: rgba(15, 23, 42, 0.09);
|
||||
--border: rgba(15, 23, 42, 0.075);
|
||||
--border-strong: rgba(15, 23, 42, 0.14);
|
||||
--scrim: rgba(15, 23, 42, 0.28);
|
||||
--shadow-btn: 0 1px 2px rgba(15, 23, 42, 0.06);
|
||||
--shadow-overlay: 0 20px 56px rgba(15, 23, 42, 0.18), 0 0 0 1px rgba(15, 23, 42, 0.06);
|
||||
|
||||
/* Text */
|
||||
--text: #f2f2f4;
|
||||
--text-2: #a8a8b0;
|
||||
--text-3: #74747e;
|
||||
--text-code: #c9ccd6;
|
||||
--text: #1d1d1f;
|
||||
--text-2: #515154;
|
||||
--text-3: #86868b;
|
||||
--text-code: #2c2c30;
|
||||
|
||||
/* Semantics */
|
||||
--accent: #3b8cf6;
|
||||
--accent-hover: #5299f7;
|
||||
/* Semantics (Apple System Colours) */
|
||||
--accent: #007aff;
|
||||
--accent-hover: #006be6;
|
||||
--accent-text: #ffffff;
|
||||
--accent-soft: rgba(59, 140, 246, 0.18);
|
||||
--accent-soft-text: #8dbcfb;
|
||||
--focus-ring: 0 0 0 2px rgba(59, 140, 246, 0.55);
|
||||
--accent-soft: rgba(0, 122, 255, 0.12);
|
||||
--accent-soft-text: #0066d6;
|
||||
--focus-ring: 0 0 0 3px rgba(0, 122, 255, 0.3);
|
||||
|
||||
--status-running: #3fb950;
|
||||
--status-busy: #d4a72c;
|
||||
--status-error: #f0625a;
|
||||
--status-idle: #74747e;
|
||||
--status-running: #28cd41;
|
||||
--status-busy: #ff9f0a;
|
||||
--status-error: #ff3b30;
|
||||
--status-idle: #aeaeb2;
|
||||
|
||||
--danger: #f0625a;
|
||||
--danger-soft: rgba(240, 98, 90, 0.14);
|
||||
--notice-soft: rgba(212, 167, 44, 0.10);
|
||||
--notice-border: rgba(212, 167, 44, 0.32);
|
||||
--danger: #ff3b30;
|
||||
--danger-soft: rgba(255, 59, 48, 0.10);
|
||||
--danger-text: #d70015;
|
||||
--notice-soft: rgba(255, 159, 10, 0.11);
|
||||
--notice-border: rgba(255, 159, 10, 0.32);
|
||||
|
||||
/* Motion */
|
||||
--dur-fast: 120ms;
|
||||
--dur: 200ms;
|
||||
|
||||
/* Layout */
|
||||
--titlebar-h: 40px;
|
||||
--titlebar-h: 42px;
|
||||
--logbar-h: 32px;
|
||||
--sidebar-w: 232px;
|
||||
--page-max: 960px;
|
||||
--sidebar-w: 244px;
|
||||
--page-max: 700px;
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
|
||||
--surface-0: #1e1e22;
|
||||
--surface-canvas: #1e1e22;
|
||||
--surface-sidebar: linear-gradient(180deg, #27282e 0%, #23242a 100%);
|
||||
--surface-sidebar-border: rgba(255, 255, 255, 0.08);
|
||||
--surface-sidebar-shadow: 0 4px 18px rgba(0, 0, 0, 0.32), inset 0 1px 0 rgba(255, 255, 255, 0.06);
|
||||
--surface-chrome: rgba(28, 28, 32, 0.92);
|
||||
--surface-1: rgba(255, 255, 255, 0.05);
|
||||
--surface-card-elevated: rgba(255, 255, 255, 0.07);
|
||||
--surface-2: #2b2c32;
|
||||
--surface-input: rgba(0, 0, 0, 0.28);
|
||||
--surface-hover: rgba(255, 255, 255, 0.07);
|
||||
--surface-active: rgba(255, 255, 255, 0.12);
|
||||
--border: rgba(255, 255, 255, 0.09);
|
||||
--border-strong: rgba(255, 255, 255, 0.16);
|
||||
--scrim: rgba(0, 0, 0, 0.55);
|
||||
--shadow-btn: 0 1px 2px rgba(0, 0, 0, 0.28);
|
||||
--shadow-overlay: 0 24px 64px rgba(0, 0, 0, 0.55), 0 0 0 1px rgba(255, 255, 255, 0.08);
|
||||
|
||||
--text: #f5f5f7;
|
||||
--text-2: #b4b4bc;
|
||||
--text-3: #86868e;
|
||||
--text-code: #d4d6e0;
|
||||
|
||||
--accent: #0a84ff;
|
||||
--accent-hover: #2492ff;
|
||||
--accent-text: #ffffff;
|
||||
--accent-soft: rgba(10, 132, 255, 0.22);
|
||||
--accent-soft-text: #64b0ff;
|
||||
--focus-ring: 0 0 0 3px rgba(10, 132, 255, 0.45);
|
||||
|
||||
--status-running: #30d158;
|
||||
--status-busy: #ffd60a;
|
||||
--status-error: #ff453a;
|
||||
--status-idle: #6e6e76;
|
||||
|
||||
--danger: #ff453a;
|
||||
--danger-soft: rgba(255, 69, 58, 0.16);
|
||||
--danger-text: #ff8b83;
|
||||
--notice-soft: rgba(255, 214, 10, 0.11);
|
||||
--notice-border: rgba(255, 214, 10, 0.30);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
|
||||
@@ -6,6 +6,7 @@ export interface Config {
|
||||
active_runtime?: string
|
||||
auto_pin_pcores: boolean
|
||||
default_gpu?: string
|
||||
runtime_channel?: 'stable' | 'candidate' | ''
|
||||
}
|
||||
|
||||
export interface GPUInfo {
|
||||
@@ -14,6 +15,24 @@ export interface GPUInfo {
|
||||
kind: 'discrete' | 'integrated' | 'virtual' | 'unknown'
|
||||
}
|
||||
|
||||
export interface WHPXCapabilities {
|
||||
modern_os: boolean
|
||||
apic_emulation: boolean
|
||||
kernel_irqchip_available: boolean
|
||||
nested_virt_property: boolean
|
||||
nested_virt_probe_error?: string
|
||||
}
|
||||
|
||||
export type OptimizationStatus = 'recommended' | 'available' | 'experimental' | 'auto' | 'unavailable'
|
||||
|
||||
export interface Optimization {
|
||||
id: 'pcore_pin' | 'kernel_irqchip' | 'cold_reboot' | 'discrete_gpu' | string
|
||||
status: OptimizationStatus
|
||||
supported: boolean
|
||||
recommended: boolean
|
||||
detail?: string
|
||||
}
|
||||
|
||||
export interface HostReport {
|
||||
os: string
|
||||
arch: string
|
||||
@@ -26,11 +45,22 @@ export interface HostReport {
|
||||
p_core_mask_hex: string
|
||||
p_core_logical_cpus?: number[]
|
||||
e_core_logical_cpus?: number[]
|
||||
lpe_core_count?: number
|
||||
non_lpe_mask?: number
|
||||
non_lpe_mask_hex?: string
|
||||
non_lpe_logical_cpus?: number[]
|
||||
total_ram_gb: number
|
||||
avail_ram_gb: number
|
||||
memory_load_pct?: number
|
||||
/** Windows commit memory: QEMU commits all guest RAM at start. */
|
||||
commit_avail_gb: number
|
||||
commit_limit_gb: number
|
||||
data_root: string
|
||||
data_root_drive_type?: string
|
||||
free_disk_gb: number
|
||||
whpx: 'ready' | 'no_hypervisor' | 'missing' | 'unsupported'
|
||||
whpx_caps?: WHPXCapabilities
|
||||
needs_cold_reboot_workaround?: boolean
|
||||
gpus: GPUInfo[]
|
||||
recommended_gpu?: GPUInfo
|
||||
}
|
||||
@@ -69,11 +99,26 @@ export interface PendingChange {
|
||||
export interface AppState {
|
||||
config: Config
|
||||
host: HostReport
|
||||
optimizations?: Optimization[]
|
||||
runtimes: InstalledRuntime[] | null
|
||||
active_runtime?: InstalledRuntime
|
||||
vms: VMListItem[] | null
|
||||
transitions: Record<string, string>
|
||||
pending_changes: Record<string, PendingChange[]>
|
||||
/** First launch: no data folder chosen yet (setup.go). */
|
||||
needs_setup: boolean
|
||||
app_version?: string
|
||||
}
|
||||
|
||||
export interface AppUpdateInfo {
|
||||
current: string
|
||||
latest: string
|
||||
has_update: boolean
|
||||
page_url?: string
|
||||
download_url?: string
|
||||
asset_name?: string
|
||||
asset_size?: number
|
||||
published_at?: string
|
||||
}
|
||||
|
||||
export interface VMDetail {
|
||||
@@ -92,6 +137,7 @@ export interface VMDetail {
|
||||
gpu: string
|
||||
has_opencore: boolean
|
||||
has_installer: boolean
|
||||
recovery_mode?: boolean
|
||||
installer_path?: string
|
||||
cpu_model: string
|
||||
audio: boolean
|
||||
@@ -105,6 +151,10 @@ export interface VMDetail {
|
||||
capture: boolean
|
||||
borderless: boolean
|
||||
extra_args: string
|
||||
guest_tools_attached?: boolean
|
||||
guest_tools_configured?: boolean
|
||||
guest_tools_connected?: boolean
|
||||
shared_dir?: string
|
||||
}
|
||||
|
||||
export interface ValidationIssue {
|
||||
@@ -116,7 +166,9 @@ export interface ValidationIssue {
|
||||
export interface CreateOpts {
|
||||
name: string
|
||||
dir?: string
|
||||
source_mode?: 'apple' | 'installer' | 'disk'
|
||||
source_mode?: 'offline' | 'apple' | 'installer' | 'disk'
|
||||
/** With macos: an offline installer of that release (reims-ctl create --offline). */
|
||||
offline?: boolean
|
||||
macos?: string
|
||||
installer?: string
|
||||
cpus: number
|
||||
@@ -124,11 +176,13 @@ export interface CreateOpts {
|
||||
disk_size?: string
|
||||
disk?: string
|
||||
disk_mode?: 'copy' | 'in-place'
|
||||
disk_controller?: 'nvme' | 'ahci' | 'virtio'
|
||||
graphics: 'reims-vgpu' | 'vmware-svga'
|
||||
gpu: string
|
||||
resolution: string
|
||||
displays: number
|
||||
borderless?: boolean
|
||||
capture?: boolean
|
||||
audio?: boolean
|
||||
network?: boolean
|
||||
ssh_port?: number
|
||||
@@ -207,3 +261,35 @@ export interface CachedInstaller {
|
||||
version?: string
|
||||
build?: string
|
||||
}
|
||||
|
||||
/** A published runtime (GitHub Release, internal/runtime/remote.go). */
|
||||
export interface RemoteRuntime {
|
||||
commit: string
|
||||
tag: string
|
||||
channel: 'stable' | 'candidate'
|
||||
published_at: string
|
||||
page_url: string
|
||||
archive_name: string
|
||||
archive_url: string
|
||||
archive_size: number
|
||||
sums_url: string
|
||||
source_name?: string
|
||||
source_url?: string
|
||||
}
|
||||
|
||||
export interface DataRootChoice {
|
||||
path: string
|
||||
free_gb: number
|
||||
system: boolean
|
||||
external: boolean
|
||||
recommended: boolean
|
||||
}
|
||||
|
||||
export interface DataRootCheck {
|
||||
path: string
|
||||
free_gb: number
|
||||
system: boolean
|
||||
external: boolean
|
||||
has_config: boolean
|
||||
error?: string
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
import {
|
||||
AppState,
|
||||
AppUpdateInfo,
|
||||
CachedInstaller,
|
||||
DataRootCheck,
|
||||
DataRootChoice,
|
||||
RemoteRuntime,
|
||||
Release,
|
||||
Task,
|
||||
CreateOpts,
|
||||
@@ -38,6 +42,18 @@ declare global {
|
||||
DeleteVM(name: string, keepFiles: boolean): Promise<void>
|
||||
ReadVMLogs(name: string, serial: boolean): Promise<string>
|
||||
OpenVMFolder(name: string): Promise<void>
|
||||
FinishInstall(name: string): Promise<void>
|
||||
EnterRecovery(name: string): Promise<void>
|
||||
AttachInstaller(name: string, installerPath: string): Promise<string>
|
||||
DownloadAndAttachOnlineRecovery(name: string, version: string): Promise<string>
|
||||
AttachGuestTools(name: string): Promise<void>
|
||||
DetachGuestTools(name: string): Promise<void>
|
||||
OpenSharedFolder(name: string): Promise<void>
|
||||
UpgradeDiskToNVMe(name: string): Promise<void>
|
||||
ExportDiagnostics(name: string): Promise<string>
|
||||
CloneVMCoW(sourceName: string, cloneName: string): Promise<void>
|
||||
TypeText(name: string, text: string): Promise<number>
|
||||
TypeClipboard(name: string): Promise<number>
|
||||
GetTasks(): Promise<Task[]>
|
||||
CancelTask(id: string): Promise<void>
|
||||
DismissTask(id: string): Promise<void>
|
||||
@@ -45,6 +61,14 @@ declare global {
|
||||
DownloadInstaller(version: string): Promise<string>
|
||||
ListInstallers(): Promise<CachedInstaller[] | null>
|
||||
DeleteInstaller(name: string): Promise<void>
|
||||
SuggestDataRoots(): Promise<DataRootChoice[] | null>
|
||||
CheckDataRoot(dir: string): Promise<DataRootCheck>
|
||||
CompleteSetup(dir: string): Promise<void>
|
||||
ListRemoteRuntimes(): Promise<RemoteRuntime[] | null>
|
||||
SetRuntimeChannel(channel: string): Promise<void>
|
||||
InstallRuntimeOnline(commit: string): Promise<string>
|
||||
CheckAppUpdate(force: boolean): Promise<AppUpdateInfo>
|
||||
OpenURL(url: string): Promise<void>
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -88,6 +112,18 @@ export const backend = {
|
||||
deleteVM: (name: string, keepFiles: boolean) => app().DeleteVM(name, keepFiles),
|
||||
readVMLogs: (name: string, serial: boolean) => app().ReadVMLogs(name, serial),
|
||||
openVMFolder: (name: string) => app().OpenVMFolder(name),
|
||||
finishInstall: (name: string) => app().FinishInstall(name),
|
||||
enterRecovery: (name: string) => app().EnterRecovery(name),
|
||||
attachInstaller: (name: string, installerPath = '') => app().AttachInstaller(name, installerPath),
|
||||
downloadAndAttachOnlineRecovery: (name: string, version = 'latest') => app().DownloadAndAttachOnlineRecovery(name, version),
|
||||
attachGuestTools: (name: string) => app().AttachGuestTools(name),
|
||||
detachGuestTools: (name: string) => app().DetachGuestTools(name),
|
||||
openSharedFolder: (name: string) => app().OpenSharedFolder(name),
|
||||
upgradeDiskToNVMe: (name: string) => app().UpgradeDiskToNVMe(name),
|
||||
exportDiagnostics: (name: string) => app().ExportDiagnostics(name),
|
||||
cloneVMCoW: (sourceName: string, cloneName: string) => app().CloneVMCoW(sourceName, cloneName),
|
||||
typeText: (name: string, text: string) => app().TypeText(name, text),
|
||||
typeClipboard: (name: string) => app().TypeClipboard(name),
|
||||
getTasks: () => app().GetTasks(),
|
||||
cancelTask: (id: string) => app().CancelTask(id),
|
||||
dismissTask: (id: string) => app().DismissTask(id),
|
||||
@@ -95,6 +131,14 @@ export const backend = {
|
||||
downloadInstaller: (version: string) => app().DownloadInstaller(version),
|
||||
listInstallers: () => app().ListInstallers(),
|
||||
deleteInstaller: (name: string) => app().DeleteInstaller(name),
|
||||
suggestDataRoots: () => app().SuggestDataRoots(),
|
||||
checkDataRoot: (dir: string) => app().CheckDataRoot(dir),
|
||||
completeSetup: (dir: string) => app().CompleteSetup(dir),
|
||||
listRemoteRuntimes: () => app().ListRemoteRuntimes(),
|
||||
setRuntimeChannel: (channel: string) => app().SetRuntimeChannel(channel),
|
||||
installRuntimeOnline: (commit: string) => app().InstallRuntimeOnline(commit),
|
||||
checkAppUpdate: (force = false) => app().CheckAppUpdate(force),
|
||||
openURL: (url: string) => app().OpenURL(url),
|
||||
onTask: (cb: (task: Task) => void) => window.runtime?.EventsOn('reims:task', cb) ?? (() => {}),
|
||||
onStateChanged: (cb: () => void) => window.runtime?.EventsOn('reims:state-changed', cb) ?? (() => {}),
|
||||
onLog: (cb: (entry: LogEntry) => void) => window.runtime?.EventsOn('reims:log', cb) ?? (() => {}),
|
||||
|
||||
@@ -1,28 +1,51 @@
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
import {reims} from '../models';
|
||||
import {version} from '../models';
|
||||
import {main} from '../models';
|
||||
import {runtime} from '../models';
|
||||
import {installer} from '../models';
|
||||
|
||||
export function ApplyVMSettings(arg1:reims.SetOpts):Promise<void>;
|
||||
|
||||
export function AttachGuestTools(arg1:string):Promise<void>;
|
||||
|
||||
export function AttachInstaller(arg1:string,arg2:string):Promise<string>;
|
||||
|
||||
export function CancelTask(arg1:string):Promise<void>;
|
||||
|
||||
export function CheckAppUpdate(arg1:boolean):Promise<version.UpdateInfo>;
|
||||
|
||||
export function CheckDataRoot(arg1:string):Promise<main.DataRootCheck>;
|
||||
|
||||
export function CloneVMCoW(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function CompleteSetup(arg1:string):Promise<void>;
|
||||
|
||||
export function CreateVM(arg1:reims.CreateOpts):Promise<void>;
|
||||
|
||||
export function DeleteInstaller(arg1:string):Promise<void>;
|
||||
|
||||
export function DeleteVM(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function DetachGuestTools(arg1:string):Promise<void>;
|
||||
|
||||
export function DismissTask(arg1:string):Promise<void>;
|
||||
|
||||
export function DownloadAndAttachOnlineRecovery(arg1:string,arg2:string):Promise<string>;
|
||||
|
||||
export function DownloadInstaller(arg1:string):Promise<string>;
|
||||
|
||||
export function EjectInstaller(arg1:string):Promise<void>;
|
||||
|
||||
export function EnableWHPX():Promise<void>;
|
||||
|
||||
export function EnterRecovery(arg1:string):Promise<void>;
|
||||
|
||||
export function ExportDiagnostics(arg1:string):Promise<string>;
|
||||
|
||||
export function FinishInstall(arg1:string):Promise<void>;
|
||||
|
||||
export function GetState():Promise<main.AppState>;
|
||||
|
||||
export function GetTasks():Promise<Array<main.Task>>;
|
||||
@@ -31,10 +54,18 @@ export function GetVMDetail(arg1:string):Promise<reims.VMDetail>;
|
||||
|
||||
export function InstallRuntimeArchive(arg1:string):Promise<runtime.Installed>;
|
||||
|
||||
export function InstallRuntimeOnline(arg1:string):Promise<string>;
|
||||
|
||||
export function ListInstallers():Promise<Array<installer.Cached>>;
|
||||
|
||||
export function ListOfflineReleases():Promise<Array<installer.Release>>;
|
||||
|
||||
export function ListRemoteRuntimes():Promise<Array<runtime.Remote>>;
|
||||
|
||||
export function OpenSharedFolder(arg1:string):Promise<void>;
|
||||
|
||||
export function OpenURL(arg1:string):Promise<void>;
|
||||
|
||||
export function OpenVMFolder(arg1:string):Promise<void>;
|
||||
|
||||
export function PickDirectory(arg1:string):Promise<string>;
|
||||
@@ -53,10 +84,20 @@ export function SetDataRoot(arg1:string):Promise<void>;
|
||||
|
||||
export function SetLocale(arg1:string):Promise<void>;
|
||||
|
||||
export function SetRuntimeChannel(arg1:string):Promise<void>;
|
||||
|
||||
export function StartVM(arg1:string):Promise<void>;
|
||||
|
||||
export function StopVM(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function SuggestDataRoots():Promise<Array<main.DataRootChoice>>;
|
||||
|
||||
export function TypeClipboard(arg1:string):Promise<number>;
|
||||
|
||||
export function TypeText(arg1:string,arg2:string):Promise<number>;
|
||||
|
||||
export function UpgradeDiskToNVMe(arg1:string):Promise<void>;
|
||||
|
||||
export function UseRuntime(arg1:string):Promise<void>;
|
||||
|
||||
export function ValidateCreate(arg1:reims.CreateOpts):Promise<Array<reims.ValidationIssue>>;
|
||||
|
||||
@@ -6,10 +6,34 @@ export function ApplyVMSettings(arg1) {
|
||||
return window['go']['main']['App']['ApplyVMSettings'](arg1);
|
||||
}
|
||||
|
||||
export function AttachGuestTools(arg1) {
|
||||
return window['go']['main']['App']['AttachGuestTools'](arg1);
|
||||
}
|
||||
|
||||
export function AttachInstaller(arg1, arg2) {
|
||||
return window['go']['main']['App']['AttachInstaller'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CancelTask(arg1) {
|
||||
return window['go']['main']['App']['CancelTask'](arg1);
|
||||
}
|
||||
|
||||
export function CheckAppUpdate(arg1) {
|
||||
return window['go']['main']['App']['CheckAppUpdate'](arg1);
|
||||
}
|
||||
|
||||
export function CheckDataRoot(arg1) {
|
||||
return window['go']['main']['App']['CheckDataRoot'](arg1);
|
||||
}
|
||||
|
||||
export function CloneVMCoW(arg1, arg2) {
|
||||
return window['go']['main']['App']['CloneVMCoW'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CompleteSetup(arg1) {
|
||||
return window['go']['main']['App']['CompleteSetup'](arg1);
|
||||
}
|
||||
|
||||
export function CreateVM(arg1) {
|
||||
return window['go']['main']['App']['CreateVM'](arg1);
|
||||
}
|
||||
@@ -22,10 +46,18 @@ export function DeleteVM(arg1, arg2) {
|
||||
return window['go']['main']['App']['DeleteVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function DetachGuestTools(arg1) {
|
||||
return window['go']['main']['App']['DetachGuestTools'](arg1);
|
||||
}
|
||||
|
||||
export function DismissTask(arg1) {
|
||||
return window['go']['main']['App']['DismissTask'](arg1);
|
||||
}
|
||||
|
||||
export function DownloadAndAttachOnlineRecovery(arg1, arg2) {
|
||||
return window['go']['main']['App']['DownloadAndAttachOnlineRecovery'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function DownloadInstaller(arg1) {
|
||||
return window['go']['main']['App']['DownloadInstaller'](arg1);
|
||||
}
|
||||
@@ -38,6 +70,18 @@ export function EnableWHPX() {
|
||||
return window['go']['main']['App']['EnableWHPX']();
|
||||
}
|
||||
|
||||
export function EnterRecovery(arg1) {
|
||||
return window['go']['main']['App']['EnterRecovery'](arg1);
|
||||
}
|
||||
|
||||
export function ExportDiagnostics(arg1) {
|
||||
return window['go']['main']['App']['ExportDiagnostics'](arg1);
|
||||
}
|
||||
|
||||
export function FinishInstall(arg1) {
|
||||
return window['go']['main']['App']['FinishInstall'](arg1);
|
||||
}
|
||||
|
||||
export function GetState() {
|
||||
return window['go']['main']['App']['GetState']();
|
||||
}
|
||||
@@ -54,6 +98,10 @@ export function InstallRuntimeArchive(arg1) {
|
||||
return window['go']['main']['App']['InstallRuntimeArchive'](arg1);
|
||||
}
|
||||
|
||||
export function InstallRuntimeOnline(arg1) {
|
||||
return window['go']['main']['App']['InstallRuntimeOnline'](arg1);
|
||||
}
|
||||
|
||||
export function ListInstallers() {
|
||||
return window['go']['main']['App']['ListInstallers']();
|
||||
}
|
||||
@@ -62,6 +110,18 @@ export function ListOfflineReleases() {
|
||||
return window['go']['main']['App']['ListOfflineReleases']();
|
||||
}
|
||||
|
||||
export function ListRemoteRuntimes() {
|
||||
return window['go']['main']['App']['ListRemoteRuntimes']();
|
||||
}
|
||||
|
||||
export function OpenSharedFolder(arg1) {
|
||||
return window['go']['main']['App']['OpenSharedFolder'](arg1);
|
||||
}
|
||||
|
||||
export function OpenURL(arg1) {
|
||||
return window['go']['main']['App']['OpenURL'](arg1);
|
||||
}
|
||||
|
||||
export function OpenVMFolder(arg1) {
|
||||
return window['go']['main']['App']['OpenVMFolder'](arg1);
|
||||
}
|
||||
@@ -98,6 +158,10 @@ export function SetLocale(arg1) {
|
||||
return window['go']['main']['App']['SetLocale'](arg1);
|
||||
}
|
||||
|
||||
export function SetRuntimeChannel(arg1) {
|
||||
return window['go']['main']['App']['SetRuntimeChannel'](arg1);
|
||||
}
|
||||
|
||||
export function StartVM(arg1) {
|
||||
return window['go']['main']['App']['StartVM'](arg1);
|
||||
}
|
||||
@@ -106,6 +170,22 @@ export function StopVM(arg1, arg2) {
|
||||
return window['go']['main']['App']['StopVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SuggestDataRoots() {
|
||||
return window['go']['main']['App']['SuggestDataRoots']();
|
||||
}
|
||||
|
||||
export function TypeClipboard(arg1) {
|
||||
return window['go']['main']['App']['TypeClipboard'](arg1);
|
||||
}
|
||||
|
||||
export function TypeText(arg1, arg2) {
|
||||
return window['go']['main']['App']['TypeText'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function UpgradeDiskToNVMe(arg1) {
|
||||
return window['go']['main']['App']['UpgradeDiskToNVMe'](arg1);
|
||||
}
|
||||
|
||||
export function UseRuntime(arg1) {
|
||||
return window['go']['main']['App']['UseRuntime'](arg1);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ export namespace config {
|
||||
active_runtime?: string;
|
||||
auto_pin_pcores: boolean;
|
||||
default_gpu?: string;
|
||||
runtime_channel?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Config(source);
|
||||
@@ -18,6 +19,7 @@ export namespace config {
|
||||
this.active_runtime = source["active_runtime"];
|
||||
this.auto_pin_pcores = source["auto_pin_pcores"];
|
||||
this.default_gpu = source["default_gpu"];
|
||||
this.runtime_channel = source["runtime_channel"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,6 +43,46 @@ export namespace host {
|
||||
this.kind = source["kind"];
|
||||
}
|
||||
}
|
||||
export class Optimization {
|
||||
id: string;
|
||||
status: string;
|
||||
supported: boolean;
|
||||
recommended: boolean;
|
||||
detail?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Optimization(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.id = source["id"];
|
||||
this.status = source["status"];
|
||||
this.supported = source["supported"];
|
||||
this.recommended = source["recommended"];
|
||||
this.detail = source["detail"];
|
||||
}
|
||||
}
|
||||
export class WHPXCapabilities {
|
||||
modern_os: boolean;
|
||||
apic_emulation: boolean;
|
||||
kernel_irqchip_available: boolean;
|
||||
nested_virt_property: boolean;
|
||||
nested_virt_probe_error?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new WHPXCapabilities(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.modern_os = source["modern_os"];
|
||||
this.apic_emulation = source["apic_emulation"];
|
||||
this.kernel_irqchip_available = source["kernel_irqchip_available"];
|
||||
this.nested_virt_property = source["nested_virt_property"];
|
||||
this.nested_virt_probe_error = source["nested_virt_probe_error"];
|
||||
}
|
||||
}
|
||||
export class Report {
|
||||
os: string;
|
||||
arch: string;
|
||||
@@ -49,15 +91,24 @@ export namespace host {
|
||||
has_hybrid_cores: boolean;
|
||||
p_core_count: number;
|
||||
e_core_count: number;
|
||||
lpe_core_count?: number;
|
||||
p_core_mask: number;
|
||||
p_core_mask_hex: string;
|
||||
p_core_logical_cpus?: number[];
|
||||
e_core_logical_cpus?: number[];
|
||||
non_lpe_mask?: number;
|
||||
non_lpe_mask_hex?: string;
|
||||
non_lpe_logical_cpus?: number[];
|
||||
total_ram_gb: number;
|
||||
avail_ram_gb: number;
|
||||
memory_load_pct: number;
|
||||
commit_avail_gb: number;
|
||||
commit_limit_gb: number;
|
||||
data_root: string;
|
||||
data_root_drive_type?: string;
|
||||
free_disk_gb: number;
|
||||
whpx: string;
|
||||
whpx_caps: WHPXCapabilities;
|
||||
needs_cold_reboot_workaround: boolean;
|
||||
gpus: GPUInfo[];
|
||||
recommended_gpu?: GPUInfo;
|
||||
@@ -75,15 +126,24 @@ export namespace host {
|
||||
this.has_hybrid_cores = source["has_hybrid_cores"];
|
||||
this.p_core_count = source["p_core_count"];
|
||||
this.e_core_count = source["e_core_count"];
|
||||
this.lpe_core_count = source["lpe_core_count"];
|
||||
this.p_core_mask = source["p_core_mask"];
|
||||
this.p_core_mask_hex = source["p_core_mask_hex"];
|
||||
this.p_core_logical_cpus = source["p_core_logical_cpus"];
|
||||
this.e_core_logical_cpus = source["e_core_logical_cpus"];
|
||||
this.non_lpe_mask = source["non_lpe_mask"];
|
||||
this.non_lpe_mask_hex = source["non_lpe_mask_hex"];
|
||||
this.non_lpe_logical_cpus = source["non_lpe_logical_cpus"];
|
||||
this.total_ram_gb = source["total_ram_gb"];
|
||||
this.avail_ram_gb = source["avail_ram_gb"];
|
||||
this.memory_load_pct = source["memory_load_pct"];
|
||||
this.commit_avail_gb = source["commit_avail_gb"];
|
||||
this.commit_limit_gb = source["commit_limit_gb"];
|
||||
this.data_root = source["data_root"];
|
||||
this.data_root_drive_type = source["data_root_drive_type"];
|
||||
this.free_disk_gb = source["free_disk_gb"];
|
||||
this.whpx = source["whpx"];
|
||||
this.whpx_caps = this.convertValues(source["whpx_caps"], WHPXCapabilities);
|
||||
this.needs_cold_reboot_workaround = source["needs_cold_reboot_workaround"];
|
||||
this.gpus = this.convertValues(source["gpus"], GPUInfo);
|
||||
this.recommended_gpu = this.convertValues(source["recommended_gpu"], GPUInfo);
|
||||
@@ -168,11 +228,14 @@ export namespace main {
|
||||
export class AppState {
|
||||
config?: config.Config;
|
||||
host: host.Report;
|
||||
optimizations: host.Optimization[];
|
||||
runtimes: runtime.Installed[];
|
||||
active_runtime?: runtime.Installed;
|
||||
vms: reims.VMListItem[];
|
||||
transitions: Record<string, string>;
|
||||
pending_changes: Record<string, Array<PendingChange>>;
|
||||
needs_setup: boolean;
|
||||
app_version: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new AppState(source);
|
||||
@@ -182,11 +245,14 @@ export namespace main {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.config = this.convertValues(source["config"], config.Config);
|
||||
this.host = this.convertValues(source["host"], host.Report);
|
||||
this.optimizations = this.convertValues(source["optimizations"], host.Optimization);
|
||||
this.runtimes = this.convertValues(source["runtimes"], runtime.Installed);
|
||||
this.active_runtime = this.convertValues(source["active_runtime"], runtime.Installed);
|
||||
this.vms = this.convertValues(source["vms"], reims.VMListItem);
|
||||
this.transitions = source["transitions"];
|
||||
this.pending_changes = this.convertValues(source["pending_changes"], Array<PendingChange>, true);
|
||||
this.needs_setup = source["needs_setup"];
|
||||
this.app_version = source["app_version"];
|
||||
}
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
@@ -207,6 +273,48 @@ export namespace main {
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class DataRootCheck {
|
||||
path: string;
|
||||
free_gb: number;
|
||||
system: boolean;
|
||||
external: boolean;
|
||||
has_config: boolean;
|
||||
error?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DataRootCheck(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.path = source["path"];
|
||||
this.free_gb = source["free_gb"];
|
||||
this.system = source["system"];
|
||||
this.external = source["external"];
|
||||
this.has_config = source["has_config"];
|
||||
this.error = source["error"];
|
||||
}
|
||||
}
|
||||
export class DataRootChoice {
|
||||
path: string;
|
||||
free_gb: number;
|
||||
system: boolean;
|
||||
external: boolean;
|
||||
recommended: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DataRootChoice(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.path = source["path"];
|
||||
this.free_gb = source["free_gb"];
|
||||
this.system = source["system"];
|
||||
this.external = source["external"];
|
||||
this.recommended = source["recommended"];
|
||||
}
|
||||
}
|
||||
export class PendingChange {
|
||||
field: string;
|
||||
from: string;
|
||||
@@ -273,17 +381,20 @@ export namespace reims {
|
||||
dir?: string;
|
||||
source_mode?: string;
|
||||
macos?: string;
|
||||
offline?: boolean;
|
||||
installer?: string;
|
||||
cpus?: number;
|
||||
memory?: string;
|
||||
disk_size?: string;
|
||||
disk?: string;
|
||||
disk_mode?: string;
|
||||
disk_controller?: string;
|
||||
graphics?: string;
|
||||
gpu?: string;
|
||||
resolution?: string;
|
||||
displays?: number;
|
||||
borderless?: boolean;
|
||||
capture?: boolean;
|
||||
audio?: boolean;
|
||||
network?: boolean;
|
||||
ssh_port?: number;
|
||||
@@ -300,17 +411,20 @@ export namespace reims {
|
||||
this.dir = source["dir"];
|
||||
this.source_mode = source["source_mode"];
|
||||
this.macos = source["macos"];
|
||||
this.offline = source["offline"];
|
||||
this.installer = source["installer"];
|
||||
this.cpus = source["cpus"];
|
||||
this.memory = source["memory"];
|
||||
this.disk_size = source["disk_size"];
|
||||
this.disk = source["disk"];
|
||||
this.disk_mode = source["disk_mode"];
|
||||
this.disk_controller = source["disk_controller"];
|
||||
this.graphics = source["graphics"];
|
||||
this.gpu = source["gpu"];
|
||||
this.resolution = source["resolution"];
|
||||
this.displays = source["displays"];
|
||||
this.borderless = source["borderless"];
|
||||
this.capture = source["capture"];
|
||||
this.audio = source["audio"];
|
||||
this.network = source["network"];
|
||||
this.ssh_port = source["ssh_port"];
|
||||
@@ -382,6 +496,7 @@ export namespace reims {
|
||||
gpu: string;
|
||||
has_opencore: boolean;
|
||||
has_installer: boolean;
|
||||
recovery_mode: boolean;
|
||||
installer_path?: string;
|
||||
cpu_model: string;
|
||||
audio: boolean;
|
||||
@@ -395,6 +510,10 @@ export namespace reims {
|
||||
capture: boolean;
|
||||
borderless: boolean;
|
||||
extra_args: string;
|
||||
guest_tools_attached: boolean;
|
||||
guest_tools_configured: boolean;
|
||||
guest_tools_connected: boolean;
|
||||
shared_dir?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new VMDetail(source);
|
||||
@@ -417,6 +536,7 @@ export namespace reims {
|
||||
this.gpu = source["gpu"];
|
||||
this.has_opencore = source["has_opencore"];
|
||||
this.has_installer = source["has_installer"];
|
||||
this.recovery_mode = source["recovery_mode"];
|
||||
this.installer_path = source["installer_path"];
|
||||
this.cpu_model = source["cpu_model"];
|
||||
this.audio = source["audio"];
|
||||
@@ -430,6 +550,10 @@ export namespace reims {
|
||||
this.capture = source["capture"];
|
||||
this.borderless = source["borderless"];
|
||||
this.extra_args = source["extra_args"];
|
||||
this.guest_tools_attached = source["guest_tools_attached"];
|
||||
this.guest_tools_configured = source["guest_tools_configured"];
|
||||
this.guest_tools_connected = source["guest_tools_connected"];
|
||||
this.shared_dir = source["shared_dir"];
|
||||
}
|
||||
}
|
||||
export class VMListItem {
|
||||
@@ -471,6 +595,22 @@ export namespace reims {
|
||||
|
||||
export namespace runtime {
|
||||
|
||||
export class Patch {
|
||||
name: string;
|
||||
target: string;
|
||||
sha256: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Patch(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.name = source["name"];
|
||||
this.target = source["target"];
|
||||
this.sha256 = source["sha256"];
|
||||
}
|
||||
}
|
||||
export class Manifest {
|
||||
schema_version: number;
|
||||
name: string;
|
||||
@@ -485,6 +625,12 @@ export namespace runtime {
|
||||
dll_count: number;
|
||||
raw_bytes: number;
|
||||
sha256: Record<string, string>;
|
||||
vendor_qemu_commit?: string;
|
||||
util_commit?: string;
|
||||
metal2vulkan_commit?: string;
|
||||
patches?: Patch[];
|
||||
channel?: string;
|
||||
source_package?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Manifest(source);
|
||||
@@ -505,7 +651,31 @@ export namespace runtime {
|
||||
this.dll_count = source["dll_count"];
|
||||
this.raw_bytes = source["raw_bytes"];
|
||||
this.sha256 = source["sha256"];
|
||||
this.vendor_qemu_commit = source["vendor_qemu_commit"];
|
||||
this.util_commit = source["util_commit"];
|
||||
this.metal2vulkan_commit = source["metal2vulkan_commit"];
|
||||
this.patches = this.convertValues(source["patches"], Patch);
|
||||
this.channel = source["channel"];
|
||||
this.source_package = source["source_package"];
|
||||
}
|
||||
|
||||
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 Installed {
|
||||
commit: string;
|
||||
@@ -543,6 +713,71 @@ export namespace runtime {
|
||||
return a;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export class Remote {
|
||||
commit: string;
|
||||
tag: string;
|
||||
channel: string;
|
||||
published_at: string;
|
||||
page_url: string;
|
||||
archive_name: string;
|
||||
archive_url: string;
|
||||
archive_size: number;
|
||||
sums_url: string;
|
||||
source_name?: string;
|
||||
source_url?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Remote(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.commit = source["commit"];
|
||||
this.tag = source["tag"];
|
||||
this.channel = source["channel"];
|
||||
this.published_at = source["published_at"];
|
||||
this.page_url = source["page_url"];
|
||||
this.archive_name = source["archive_name"];
|
||||
this.archive_url = source["archive_url"];
|
||||
this.archive_size = source["archive_size"];
|
||||
this.sums_url = source["sums_url"];
|
||||
this.source_name = source["source_name"];
|
||||
this.source_url = source["source_url"];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export namespace version {
|
||||
|
||||
export class UpdateInfo {
|
||||
current: string;
|
||||
latest: string;
|
||||
has_update: boolean;
|
||||
page_url?: string;
|
||||
download_url?: string;
|
||||
asset_name?: string;
|
||||
asset_size?: number;
|
||||
published_at?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new UpdateInfo(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.current = source["current"];
|
||||
this.latest = source["latest"];
|
||||
this.has_update = source["has_update"];
|
||||
this.page_url = source["page_url"];
|
||||
this.download_url = source["download_url"];
|
||||
this.asset_name = source["asset_name"];
|
||||
this.asset_size = source["asset_size"];
|
||||
this.published_at = source["published_at"];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ module github.com/Nwflower/reims-go
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/ulikunitz/xz v0.5.17
|
||||
github.com/wailsapp/wails/v2 v2.17.1
|
||||
golang.org/x/sys v0.48.0
|
||||
)
|
||||
|
||||
@@ -52,6 +52,8 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/tkrajina/go-reflector v0.5.8 h1:yPADHrwmUbMq4RGEyaOUpz2H90sRsETNVpjzo3DLVQQ=
|
||||
github.com/tkrajina/go-reflector v0.5.8/go.mod h1:ECbqLgccecY5kPmPmXg1MrHW585yMcDkVl6IvJe64T4=
|
||||
github.com/ulikunitz/xz v0.5.17 h1:flR0y/x1hgM8EGV1AW3Xll6T413G0glV8UfBwR617V4=
|
||||
github.com/ulikunitz/xz v0.5.17/go.mod h1:H9Rt/W6/Qj27PGauhQc6nfCDy7vHpzsOThBSaYDoEhw=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
func (a *App) vmSharedDir(name string) string {
|
||||
a.mu.Lock()
|
||||
dir := filepath.Join(a.cfg.SharedDir(), name)
|
||||
a.mu.Unlock()
|
||||
return dir
|
||||
}
|
||||
|
||||
func (a *App) guestToolsImagePath(name string) string {
|
||||
a.mu.Lock()
|
||||
cacheDir := a.cfg.XDGCacheDir()
|
||||
a.mu.Unlock()
|
||||
return filepath.Join(cacheDir, "reims-go", "guest-tools", name+"-tools.img")
|
||||
}
|
||||
|
||||
// ensureGuestToolsBridge starts the shared localhost HTTP bridge once and
|
||||
// registers any already-configured VMs so Guest Tools reconnects seamlessly
|
||||
// across reims-go restarts.
|
||||
func (a *App) ensureGuestToolsBridge() (*guesttools.Server, int, error) {
|
||||
a.mu.Lock()
|
||||
srv := a.guestTools
|
||||
if srv == nil {
|
||||
srv = guesttools.NewServer(nil)
|
||||
a.guestTools = srv
|
||||
}
|
||||
a.mu.Unlock()
|
||||
|
||||
port, err := srv.Start(guesttools.DefaultPort)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return srv, port, nil
|
||||
}
|
||||
|
||||
func (a *App) registerExistingGuestTools(ctx context.Context) {
|
||||
srv, port, err := a.ensureGuestToolsBridge()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
vms, err := c.List(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, vm := range vms {
|
||||
det, err := c.Show(ctx, vm.Name)
|
||||
if err != nil || det.Directory == "" {
|
||||
continue
|
||||
}
|
||||
if cfg, ok := guesttools.ReadVMConfig(det.Directory); ok {
|
||||
if cfg.SharedDir == "" {
|
||||
cfg.SharedDir = a.vmSharedDir(vm.Name)
|
||||
}
|
||||
if cfg.Port != port {
|
||||
cfg.Port = port
|
||||
_ = guesttools.SaveVMConfig(det.Directory, cfg)
|
||||
}
|
||||
srv.RegisterVM(cfg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) populateGuestToolsDetail(d *reims.VMDetail) {
|
||||
if d == nil || d.Name == "" {
|
||||
return
|
||||
}
|
||||
d.GuestToolsAttached = reims.HasGuestToolsArgs(d.ExtraArgs)
|
||||
d.SharedDir = a.vmSharedDir(d.Name)
|
||||
if cfg, ok := guesttools.ReadVMConfig(d.Directory); ok {
|
||||
d.GuestToolsConfigured = true
|
||||
if cfg.SharedDir != "" {
|
||||
d.SharedDir = cfg.SharedDir
|
||||
}
|
||||
if srv, _, err := a.ensureGuestToolsBridge(); err == nil {
|
||||
srv.RegisterVM(cfg)
|
||||
d.GuestToolsConnected = srv.IsConnected(d.Name, 12*time.Second)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// syncGuestTools ensures the host HTTP bridge is running and refreshes the
|
||||
// REIMSTOOLS HFS+ image before VM start when Guest Tools is configured or attached.
|
||||
func (a *App) syncGuestTools(c *reims.Client, name string, cur *reims.VMDetail) {
|
||||
if cur.Directory == "" {
|
||||
return
|
||||
}
|
||||
attached := reims.HasGuestToolsArgs(cur.ExtraArgs)
|
||||
cfg, configured := guesttools.ReadVMConfig(cur.Directory)
|
||||
if !attached && !configured {
|
||||
return
|
||||
}
|
||||
srv, port, err := a.ensureGuestToolsBridge()
|
||||
if err != nil {
|
||||
a.emitLog(name, "Warning: could not start Guest Tools bridge: "+err.Error())
|
||||
return
|
||||
}
|
||||
sharedDir := a.vmSharedDir(name)
|
||||
cfg, err = guesttools.LoadOrCreateVMConfig(cur.Directory, name, sharedDir, port)
|
||||
if err != nil {
|
||||
a.emitLog(name, "Warning: could not load Guest Tools config: "+err.Error())
|
||||
return
|
||||
}
|
||||
srv.RegisterVM(cfg)
|
||||
if !attached {
|
||||
return
|
||||
}
|
||||
imgPath := a.guestToolsImagePath(name)
|
||||
if err := guesttools.BuildToolsDiskImage(imgPath, cfg); err != nil {
|
||||
a.emitLog(name, "Warning: could not refresh REIMSTOOLS disk: "+err.Error())
|
||||
return
|
||||
}
|
||||
merged := reims.MergeGuestToolsArgs(cur.ExtraArgs, imgPath)
|
||||
if merged != cur.ExtraArgs {
|
||||
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err == nil {
|
||||
cur.ExtraArgs = merged
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// AttachGuestTools prepares the per-VM Bearer token, ensures the shared folder
|
||||
// and localhost bridge are active, builds the read-only REIMSTOOLS HFS+ disk,
|
||||
// and attaches it to the VM via `reims-ctl set --extra-args`.
|
||||
func (a *App) AttachGuestTools(name string) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.Directory == "" {
|
||||
return fmt.Errorf("VM %s has no directory", name)
|
||||
}
|
||||
srv, port, err := a.ensureGuestToolsBridge()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sharedDir := a.vmSharedDir(name)
|
||||
if err := os.MkdirAll(sharedDir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
cfg, err := guesttools.LoadOrCreateVMConfig(d.Directory, name, sharedDir, port)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
srv.RegisterVM(cfg)
|
||||
|
||||
imgPath := a.guestToolsImagePath(name)
|
||||
if err := guesttools.BuildToolsDiskImage(imgPath, cfg); err != nil {
|
||||
return fmt.Errorf("build REIMSTOOLS disk: %w", err)
|
||||
}
|
||||
merged := reims.MergeGuestToolsArgs(d.ExtraArgs, imgPath)
|
||||
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
|
||||
ctx := context.Background()
|
||||
if merged != d.ExtraArgs {
|
||||
if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &merged}, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
|
||||
Field: "guest_tools",
|
||||
From: "detached",
|
||||
To: "attached",
|
||||
})
|
||||
a.mu.Unlock()
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Guest Tools disk (REIMSTOOLS) attached on 127.0.0.1:%d; shared folder: %s", port, sharedDir))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DetachGuestTools removes the REIMSTOOLS installer USB disk from QEMU
|
||||
// extra-args while keeping the background clipboard/shared-folder bridge active.
|
||||
func (a *App) DetachGuestTools(name string) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
stripped := reims.StripGuestToolsArgs(d.ExtraArgs)
|
||||
ctx := context.Background()
|
||||
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
|
||||
if stripped != d.ExtraArgs {
|
||||
if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &stripped}, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
|
||||
Field: "guest_tools",
|
||||
From: "attached",
|
||||
To: "ejected",
|
||||
})
|
||||
a.mu.Unlock()
|
||||
}
|
||||
}
|
||||
a.emitLog(name, "Guest Tools disk (REIMSTOOLS) ejected; clipboard & shared folder bridge remains active")
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// OpenSharedFolder opens `<DataRoot>/shared/<vmName>` in Windows File Explorer.
|
||||
func (a *App) OpenSharedFolder(name string) error {
|
||||
dir := a.vmSharedDir(name)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
return host.OpenFolder(dir)
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
package main
|
||||
|
||||
// Finishing an offline install (roadmap M2.3): take the installer out and turn
|
||||
// the network back on, which an offline install keeps off so its installer
|
||||
// downloads no update (`reims-ctl create --help`, upstream 3731afd).
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// recoveryPickerMarkerFile tracks OpenCore ShowPicker state managed by
|
||||
// reims-go's recovery-mode toggle inside the VM directory:
|
||||
// - "want": EnterRecovery ran while VM was running; apply --boot-selection=true before next start.
|
||||
// - "on": --boot-selection=true is active on opencore.qcow2.
|
||||
// - "restore": FinishInstall ran while VM was running; apply --boot-selection=false before next start.
|
||||
// - "": Normal direct boot (file absent).
|
||||
const recoveryPickerMarkerFile = ".reims-go-recovery-picker"
|
||||
|
||||
func recoveryPickerMarker(vmDir string) string {
|
||||
if vmDir == "" {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(vmDir, recoveryPickerMarkerFile)
|
||||
}
|
||||
|
||||
func readRecoveryPickerMarker(vmDir string) string {
|
||||
p := recoveryPickerMarker(vmDir)
|
||||
if p == "" {
|
||||
return ""
|
||||
}
|
||||
b, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
|
||||
func writeRecoveryPickerMarker(vmDir, state string) {
|
||||
p := recoveryPickerMarker(vmDir)
|
||||
if p == "" {
|
||||
return
|
||||
}
|
||||
if state == "" {
|
||||
_ = os.Remove(p)
|
||||
return
|
||||
}
|
||||
_ = os.WriteFile(p, []byte(state), 0o644)
|
||||
}
|
||||
|
||||
func isRecoveryModeActive(d reims.VMDetail) bool {
|
||||
if d.HasInstaller {
|
||||
return true
|
||||
}
|
||||
m := readRecoveryPickerMarker(d.Directory)
|
||||
return m == "on" || m == "want"
|
||||
}
|
||||
|
||||
func (a *App) activeRuntimeHasPatch(substr string) bool {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil || active == nil {
|
||||
return false
|
||||
}
|
||||
needle := strings.ToLower(substr)
|
||||
for _, p := range active.Manifest.Patches {
|
||||
if strings.Contains(strings.ToLower(p.Name), needle) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// applyProbedWHPXCompat pre-applies `-machine kernel-irqchip=off` on Windows 11
|
||||
// builds where WHvPartitionPropertyCodeNestedVirtualization is probed as
|
||||
// unsupported (e.g. hr=0x80370302) AND the active runtime lacks
|
||||
// qemu-whpx-nested-virt-nonfatal.patch, avoiding a noisy first-start crash & retry.
|
||||
func (a *App) applyProbedWHPXCompat(c *reims.Client, name string, rep host.Report, cur *reims.VMDetail) {
|
||||
if rep.NeedsColdRebootWorkaround || !rep.WHPXCaps.KernelIrqchipAvailable || rep.WHPXCaps.NestedVirtProperty {
|
||||
return
|
||||
}
|
||||
if a.activeRuntimeHasPatch("nested-virt-nonfatal") {
|
||||
return
|
||||
}
|
||||
if reims.HasKernelIrqchipArg(cur.ExtraArgs) {
|
||||
return
|
||||
}
|
||||
merged := reims.MergeKernelIrqchipOffArgs(cur.ExtraArgs)
|
||||
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err != nil {
|
||||
return
|
||||
}
|
||||
cur.ExtraArgs = merged
|
||||
a.mu.Lock()
|
||||
loc := a.cfg.Locale
|
||||
a.mu.Unlock()
|
||||
code := rep.WHPXCaps.NestedVirtProbeError
|
||||
if code == "" {
|
||||
code = "unsupported"
|
||||
}
|
||||
if loc == i18n.ZhCN {
|
||||
a.emitLog(name, fmt.Sprintf("[兼容] 当前 Windows 不支持嵌套虚拟化属性(%s),已自动启用 kernel-irqchip=off", code))
|
||||
} else {
|
||||
a.emitLog(name, fmt.Sprintf("[compat] Host rejects nested-virtualization property (%s); enabled kernel-irqchip=off automatically", code))
|
||||
}
|
||||
}
|
||||
|
||||
// syncOfflineHelper prepares and attaches the REIMSHELP HFS+ helper disk when a
|
||||
// VM boots with an offline installer attached, or strips it once ejected.
|
||||
func (a *App) syncOfflineHelper(c *reims.Client, name string, cur *reims.VMDetail) {
|
||||
ctx := context.Background()
|
||||
if cur.HasInstaller && reims.IsOfflineInstallerPath(cur.InstallerPath) {
|
||||
a.mu.Lock()
|
||||
cacheDir := a.cfg.XDGCacheDir()
|
||||
a.mu.Unlock()
|
||||
a.emitLog(name, "Preparing offline install helper disk (REIMSHELP)...")
|
||||
helperPath, err := installer.EnsureOfflineHelperImage(cacheDir, cur.InstallerPath)
|
||||
if err != nil {
|
||||
a.emitLog(name, "Warning: offline install helper disk skipped: "+err.Error())
|
||||
return
|
||||
}
|
||||
merged := reims.MergeOfflineHelperArgs(cur.ExtraArgs, helperPath)
|
||||
if merged != cur.ExtraArgs {
|
||||
if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err != nil {
|
||||
a.emitLog(name, "Warning: could not attach REIMSHELP disk: "+err.Error())
|
||||
return
|
||||
}
|
||||
cur.ExtraArgs = merged
|
||||
}
|
||||
return
|
||||
}
|
||||
stripped := reims.StripOfflineHelperArgs(cur.ExtraArgs)
|
||||
if stripped != cur.ExtraArgs {
|
||||
if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &stripped}, io.Discard, io.Discard); err == nil {
|
||||
cur.ExtraArgs = stripped
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// syncRecoveryBootPicker reconciles OpenCore's ShowPicker flag when a VM was
|
||||
// switched into or out of recovery mode while running (update-opencore requires
|
||||
// a stopped VM: upstream 3731afd opencore.rs:400-402).
|
||||
func (a *App) syncRecoveryBootPicker(c *reims.Client, name string, cur *reims.VMDetail) {
|
||||
marker := readRecoveryPickerMarker(cur.Directory)
|
||||
if marker == "" {
|
||||
return
|
||||
}
|
||||
ctx := context.Background()
|
||||
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
|
||||
switch marker {
|
||||
case "want":
|
||||
a.emitLog(name, "Enabling OpenCore boot picker for recovery mode...")
|
||||
if err := c.UpdateOpenCore(ctx, name, true, w, w); err != nil {
|
||||
a.emitLog(name, "Warning: could not enable OpenCore boot picker: "+err.Error())
|
||||
return
|
||||
}
|
||||
writeRecoveryPickerMarker(cur.Directory, "on")
|
||||
case "restore":
|
||||
a.emitLog(name, "Restoring OpenCore direct boot after exiting recovery mode...")
|
||||
if err := c.UpdateOpenCore(ctx, name, false, w, w); err != nil {
|
||||
a.emitLog(name, "Warning: could not disable OpenCore boot picker: "+err.Error())
|
||||
return
|
||||
}
|
||||
writeRecoveryPickerMarker(cur.Directory, "")
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) pickCachedRecoveryInstaller() (string, error) {
|
||||
ic, err := a.installerClient()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
items, err := ic.ListCached()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// ListCached sorts ascending by name; walk in reverse so newer versions win.
|
||||
// Prefer complete offline installers, then online installers, then other .img/.dmg.
|
||||
for _, wantKind := range []string{"offline", "online", "other"} {
|
||||
for i := len(items) - 1; i >= 0; i-- {
|
||||
it := items[i]
|
||||
if it.Partial || it.Kind != wantKind {
|
||||
continue
|
||||
}
|
||||
lower := strings.ToLower(it.Name)
|
||||
if wantKind == "other" && !strings.HasSuffix(lower, ".img") && !strings.HasSuffix(lower, ".dmg") {
|
||||
continue
|
||||
}
|
||||
return it.Path, nil
|
||||
}
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (a *App) isVMRunning(ctx context.Context, c *reims.Client, name string, d reims.VMDetail) bool {
|
||||
if d.State == "running" {
|
||||
return true
|
||||
}
|
||||
if list, err := c.List(ctx); err == nil {
|
||||
for _, vm := range list {
|
||||
if vm.Name == name && vm.State == "running" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// EnterRecovery enables OpenCore's boot picker (--boot-selection=true) so the
|
||||
// VM can boot macOS's built-in Recovery volume without needing an external
|
||||
// installer image (upstream reims-util 7867384 sets HideAuxiliary=false).
|
||||
// If the VM is running, the change is queued for the next start/restart.
|
||||
func (a *App) EnterRecovery(name string) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
|
||||
ctx := context.Background()
|
||||
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
marker := readRecoveryPickerMarker(d.Directory)
|
||||
if marker != "on" {
|
||||
writeRecoveryPickerMarker(d.Directory, "want")
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
|
||||
Field: "recovery",
|
||||
From: "off",
|
||||
To: "on",
|
||||
})
|
||||
a.mu.Unlock()
|
||||
}
|
||||
a.emitLog(name, "Recovery mode scheduled for "+name+": OpenCore boot picker will open on next start")
|
||||
} else {
|
||||
a.emitLog(name, "Enabling OpenCore boot picker for recovery mode...")
|
||||
if err := c.UpdateOpenCore(ctx, name, true, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
writeRecoveryPickerMarker(d.Directory, "on")
|
||||
a.emitLog(name, "Recovery mode enabled for "+name+" (pick Recovery in OpenCore boot menu)")
|
||||
}
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AttachInstaller attaches an installer/recovery image to the VM for its next
|
||||
// start (`reims-ctl insert NAME PATH`). When installerPath is empty, the newest
|
||||
// complete cached installer in the installers directory is used. Returns the
|
||||
// attached file's base name.
|
||||
func (a *App) AttachInstaller(name, installerPath string) (string, error) {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
path := strings.TrimSpace(installerPath)
|
||||
if path == "" {
|
||||
path, err = a.pickCachedRecoveryInstaller()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if path == "" {
|
||||
return "", errors.New("no cached installer image found")
|
||||
}
|
||||
}
|
||||
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
|
||||
ctx := context.Background()
|
||||
|
||||
base := filepath.Base(path)
|
||||
a.emitLog(name, "Attaching installer image to "+name+": "+base)
|
||||
if err := c.Insert(ctx, name, path, w, w); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
|
||||
Field: "installer",
|
||||
From: "ejected",
|
||||
To: "attached",
|
||||
})
|
||||
a.mu.Unlock()
|
||||
}
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return base, nil
|
||||
}
|
||||
|
||||
// DownloadAndAttachOnlineRecovery downloads Apple's ~1 GB online recovery image
|
||||
// (`reims-util online-installer`) in a background task and attaches it to the
|
||||
// VM via `reims-ctl insert` as soon as it finishes.
|
||||
func (a *App) DownloadAndAttachOnlineRecovery(name, version string) (string, error) {
|
||||
ic, err := a.installerClient()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := a.GetVMDetail(name); err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, t := range tasks.list() {
|
||||
if t.Kind == "recovery-download" && t.Status == TaskRunning && t.Subject == name {
|
||||
return t.ID, nil
|
||||
}
|
||||
}
|
||||
v := strings.TrimSpace(version)
|
||||
if v == "" {
|
||||
v = "latest"
|
||||
}
|
||||
a.ensureTaskEmitter()
|
||||
base := a.ctx
|
||||
if base == nil {
|
||||
base = context.Background()
|
||||
}
|
||||
ctx, cancel := context.WithCancel(base)
|
||||
id := tasks.start("recovery-download", name, "", cancel)
|
||||
a.emitLog(name, "Downloading Apple online recovery image (~1 GB) for "+name+"...")
|
||||
go func() {
|
||||
defer cancel()
|
||||
res, err := ic.DownloadOnline(ctx, v, func(u installer.Update) {
|
||||
switch u.Kind {
|
||||
case installer.KindStep, installer.KindNote:
|
||||
a.emitLog(name, u.Message)
|
||||
}
|
||||
tasks.update(id, u)
|
||||
})
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
a.emitLog(name, "Online recovery download paused; starting again continues where it stopped")
|
||||
tasks.finish(id, "", context.Canceled)
|
||||
} else {
|
||||
a.emitLog(name, "Online recovery download error: "+err.Error())
|
||||
tasks.finish(id, "", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
tasks.update(id, installer.Update{
|
||||
Kind: installer.KindStep,
|
||||
Step: "attaching online recovery image",
|
||||
Message: "attaching online recovery image",
|
||||
Percent: -1,
|
||||
})
|
||||
attached, err := a.AttachInstaller(name, res.Image)
|
||||
if err != nil {
|
||||
a.emitLog(name, "Failed to attach online recovery image: "+err.Error())
|
||||
tasks.finish(id, "", err)
|
||||
return
|
||||
}
|
||||
a.emitLog(name, "Online recovery image attached: "+attached)
|
||||
tasks.finish(id, attached, nil)
|
||||
}()
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// FinishInstall exits recovery mode: ejects any attached installer, removes
|
||||
// REIMSHELP, enables the network if off, and restores OpenCore direct boot
|
||||
// (--boot-selection=false) if recovery mode enabled the boot picker.
|
||||
func (a *App) FinishInstall(name string) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
|
||||
ctx := context.Background()
|
||||
|
||||
if d.HasInstaller {
|
||||
a.emitLog(name, "Ejecting installer from "+name+"...")
|
||||
if err := c.Eject(ctx, name, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
stripped := reims.StripOfflineHelperArgs(d.ExtraArgs)
|
||||
setOpts := reims.SetOpts{Name: name}
|
||||
needSet := false
|
||||
upgradedNVMe := false
|
||||
if !d.Network {
|
||||
on := true
|
||||
setOpts.Network = &on
|
||||
needSet = true
|
||||
a.emitLog(name, "Turning the network on for "+name+"...")
|
||||
}
|
||||
if d.HasInstaller && strings.EqualFold(d.DiskController, "ahci") {
|
||||
setOpts.DiskController = "nvme"
|
||||
needSet = true
|
||||
upgradedNVMe = true
|
||||
a.emitLog(name, "Upgrading disk controller for "+name+" from SATA/AHCI to NVMe...")
|
||||
}
|
||||
if stripped != d.ExtraArgs {
|
||||
setOpts.ExtraArgs = &stripped
|
||||
needSet = true
|
||||
}
|
||||
if needSet {
|
||||
if err := c.Set(ctx, setOpts, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
running := a.isVMRunning(ctx, c, name, d)
|
||||
marker := readRecoveryPickerMarker(d.Directory)
|
||||
if running {
|
||||
var diffs []PendingChange
|
||||
if d.HasInstaller {
|
||||
diffs = append(diffs, PendingChange{Field: "installer", From: "attached", To: "ejected"})
|
||||
}
|
||||
if !d.Network {
|
||||
diffs = append(diffs, PendingChange{Field: "network", From: "off", To: "on"})
|
||||
}
|
||||
if upgradedNVMe {
|
||||
diffs = append(diffs, PendingChange{Field: "disk_controller", From: "ahci", To: "nvme"})
|
||||
}
|
||||
switch marker {
|
||||
case "want":
|
||||
writeRecoveryPickerMarker(d.Directory, "")
|
||||
case "on":
|
||||
writeRecoveryPickerMarker(d.Directory, "restore")
|
||||
diffs = append(diffs, PendingChange{Field: "recovery", From: "on", To: "off"})
|
||||
}
|
||||
if len(diffs) > 0 {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], diffs...)
|
||||
a.mu.Unlock()
|
||||
}
|
||||
} else {
|
||||
if marker == "on" || marker == "restore" {
|
||||
a.emitLog(name, "Restoring OpenCore direct boot after exiting recovery mode...")
|
||||
if err := c.UpdateOpenCore(ctx, name, false, w, w); err != nil {
|
||||
a.emitLog(name, "Warning: could not disable OpenCore boot picker: "+err.Error())
|
||||
} else {
|
||||
writeRecoveryPickerMarker(d.Directory, "")
|
||||
}
|
||||
} else if marker != "" {
|
||||
writeRecoveryPickerMarker(d.Directory, "")
|
||||
}
|
||||
}
|
||||
a.emitLog(name, "Exited recovery mode")
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpgradeDiskToNVMe switches an existing installed VM from legacy SATA/AHCI to
|
||||
// NVMe via `reims-ctl set --disk-controller nvme` (applies at next start if running).
|
||||
func (a *App) UpgradeDiskToNVMe(name string) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.HasInstaller {
|
||||
return errors.New("exit recovery mode (eject installer) before switching disk controller")
|
||||
}
|
||||
if strings.EqualFold(d.DiskController, "nvme") {
|
||||
return nil
|
||||
}
|
||||
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
|
||||
ctx := context.Background()
|
||||
a.emitLog(name, "Upgrading disk controller for "+name+" to NVMe...")
|
||||
if err := c.Set(ctx, reims.SetOpts{Name: name, DiskController: "nvme"}, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
|
||||
Field: "disk_controller",
|
||||
From: d.DiskController,
|
||||
To: "nvme",
|
||||
})
|
||||
a.mu.Unlock()
|
||||
}
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -16,6 +16,9 @@ type Config struct {
|
||||
ActiveRuntime string `json:"active_runtime,omitempty"`
|
||||
AutoPinPCores bool `json:"auto_pin_pcores"`
|
||||
DefaultGPU string `json:"default_gpu,omitempty"`
|
||||
// RuntimeChannel is "stable" (default, also when empty) or "candidate":
|
||||
// whether online install offers candidate runtimes (portable-runtime-spec.md §6).
|
||||
RuntimeChannel string `json:"runtime_channel,omitempty"`
|
||||
}
|
||||
|
||||
func DefaultDataRoot() string {
|
||||
@@ -34,13 +37,110 @@ func DefaultDataRoot() string {
|
||||
return filepath.Join(home, "reims-go-data")
|
||||
}
|
||||
|
||||
// CurrentDataRoot is the data folder in effect: REIMS_GO_DATA_ROOT, else the
|
||||
// folder chosen at first launch (LocationPath), else DefaultDataRoot.
|
||||
func CurrentDataRoot() string {
|
||||
if v := os.Getenv("REIMS_GO_DATA_ROOT"); v != "" {
|
||||
return v
|
||||
}
|
||||
if root, ok := ReadLocation(); ok {
|
||||
return root
|
||||
}
|
||||
return DefaultDataRoot()
|
||||
}
|
||||
|
||||
func DefaultConfigPath() string {
|
||||
return filepath.Join(DefaultDataRoot(), "reims-go.json")
|
||||
return filepath.Join(CurrentDataRoot(), "reims-go.json")
|
||||
}
|
||||
|
||||
// LocationPath is the one small file kept outside the data folder: it records
|
||||
// which folder was chosen, so the next launch finds it. %APPDATA%\reims-go on
|
||||
// Windows. Everything else (runtimes, VMs, installers) lives in the data folder.
|
||||
// REIMS_GO_LOCATION_FILE overrides it (testing the first-launch screen without
|
||||
// touching the real pointer).
|
||||
func LocationPath() string {
|
||||
if p := os.Getenv("REIMS_GO_LOCATION_FILE"); p != "" {
|
||||
return p
|
||||
}
|
||||
dir, err := os.UserConfigDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(dir, "reims-go", "location.json")
|
||||
}
|
||||
|
||||
type location struct {
|
||||
DataRoot string `json:"data_root"`
|
||||
}
|
||||
|
||||
// ReadLocation returns the data folder chosen at first launch, if any.
|
||||
func ReadLocation() (string, bool) {
|
||||
p := LocationPath()
|
||||
if p == "" {
|
||||
return "", false
|
||||
}
|
||||
raw, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
var loc location
|
||||
if json.Unmarshal(raw, &loc) != nil || loc.DataRoot == "" {
|
||||
return "", false
|
||||
}
|
||||
return loc.DataRoot, true
|
||||
}
|
||||
|
||||
// SaveLocation records the chosen data folder for the next launch.
|
||||
func SaveLocation(dataRoot string) error {
|
||||
p := LocationPath()
|
||||
if p == "" {
|
||||
return errors.New("no user config directory")
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := json.MarshalIndent(location{DataRoot: dataRoot}, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(p, append(data, '\n'), 0o644)
|
||||
}
|
||||
|
||||
// Resolve loads the config for the app and reports whether first-launch setup
|
||||
// is needed: no REIMS_GO_DATA_ROOT, no recorded folder, and no reims-go.json in
|
||||
// the default folder. An install from before the picker existed (a config in
|
||||
// the default folder) is adopted and recorded, so it is never asked again.
|
||||
// legacyDataRoot is where installs before the first-launch picker kept their
|
||||
// config; a variable so tests can point it elsewhere.
|
||||
var legacyDataRoot = DefaultDataRoot
|
||||
|
||||
func Resolve() (cfg *Config, needsSetup bool, err error) {
|
||||
if os.Getenv("REIMS_GO_FIRST_RUN") == "1" {
|
||||
// Simulate a fresh machine (testing the first-launch screen).
|
||||
return Default(), true, nil
|
||||
}
|
||||
if os.Getenv("REIMS_GO_DATA_ROOT") != "" {
|
||||
cfg, err = Load("")
|
||||
return cfg, false, err
|
||||
}
|
||||
if _, ok := ReadLocation(); ok {
|
||||
cfg, err = Load("")
|
||||
return cfg, false, err
|
||||
}
|
||||
legacy := filepath.Join(legacyDataRoot(), "reims-go.json")
|
||||
if _, statErr := os.Stat(legacy); statErr == nil {
|
||||
cfg, err = Load(legacy)
|
||||
if err == nil {
|
||||
_ = SaveLocation(cfg.DataRoot)
|
||||
}
|
||||
return cfg, false, err
|
||||
}
|
||||
return Default(), true, nil
|
||||
}
|
||||
|
||||
func Default() *Config {
|
||||
return &Config{
|
||||
DataRoot: DefaultDataRoot(),
|
||||
DataRoot: CurrentDataRoot(),
|
||||
Locale: i18n.Detect(),
|
||||
AutoPinPCores: true,
|
||||
DefaultGPU: "auto",
|
||||
@@ -63,7 +163,7 @@ func Load(path string) (*Config, error) {
|
||||
return nil, err
|
||||
}
|
||||
if cfg.DataRoot == "" {
|
||||
cfg.DataRoot = DefaultDataRoot()
|
||||
cfg.DataRoot = filepath.Dir(path)
|
||||
}
|
||||
cfg.Locale = i18n.Normalize(string(cfg.Locale))
|
||||
return cfg, nil
|
||||
@@ -83,11 +183,13 @@ func Save(path string, cfg *Config) error {
|
||||
return os.WriteFile(path, append(data, '\n'), 0o644)
|
||||
}
|
||||
|
||||
func (c *Config) RuntimesDir() string { return filepath.Join(c.DataRoot, "runtimes") }
|
||||
func (c *Config) RuntimesDir() string { return filepath.Join(c.DataRoot, "runtimes") }
|
||||
func (c *Config) XDGConfigDir() string { return filepath.Join(c.DataRoot, "config") }
|
||||
func (c *Config) XDGDataDir() string { return filepath.Join(c.DataRoot, "data") }
|
||||
func (c *Config) XDGCacheDir() string { return filepath.Join(c.DataRoot, "cache") }
|
||||
func (c *Config) ImagesDir() string { return filepath.Join(c.DataRoot, "images") }
|
||||
func (c *Config) ImagesDir() string { return filepath.Join(c.DataRoot, "images") }
|
||||
func (c *Config) TempDir() string { return filepath.Join(c.DataRoot, "tmp") }
|
||||
func (c *Config) SharedDir() string { return filepath.Join(c.DataRoot, "shared") }
|
||||
|
||||
func (c *Config) EnsureDirs() error {
|
||||
for _, d := range []string{
|
||||
@@ -97,6 +199,8 @@ func (c *Config) EnsureDirs() error {
|
||||
c.XDGDataDir(),
|
||||
c.XDGCacheDir(),
|
||||
c.ImagesDir(),
|
||||
c.TempDir(),
|
||||
c.SharedDir(),
|
||||
} {
|
||||
if err := os.MkdirAll(d, 0o755); err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// isolate points the user config dir and the legacy default at temp folders.
|
||||
func isolate(t *testing.T) (legacy string) {
|
||||
t.Helper()
|
||||
cfgHome := t.TempDir()
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Setenv("APPDATA", cfgHome)
|
||||
} else {
|
||||
t.Setenv("XDG_CONFIG_HOME", cfgHome)
|
||||
t.Setenv("HOME", cfgHome)
|
||||
}
|
||||
t.Setenv("REIMS_GO_DATA_ROOT", "")
|
||||
legacy = filepath.Join(t.TempDir(), "legacy")
|
||||
old := legacyDataRoot
|
||||
legacyDataRoot = func() string { return legacy }
|
||||
t.Cleanup(func() { legacyDataRoot = old })
|
||||
return legacy
|
||||
}
|
||||
|
||||
func TestFirstLaunchNeedsSetupUntilAFolderIsChosen(t *testing.T) {
|
||||
isolate(t)
|
||||
_, needs, err := Resolve()
|
||||
if err != nil || !needs {
|
||||
t.Fatalf("fresh machine: needs=%v err=%v", needs, err)
|
||||
}
|
||||
chosen := filepath.Join(t.TempDir(), "Data", "reims-go")
|
||||
cfg := Default()
|
||||
cfg.DataRoot = chosen
|
||||
if err := Save("", cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SaveLocation(chosen); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, needs, err := Resolve()
|
||||
if err != nil || needs || got.DataRoot != chosen {
|
||||
t.Fatalf("after choosing: root=%q needs=%v err=%v", got.DataRoot, needs, err)
|
||||
}
|
||||
if CurrentDataRoot() != chosen {
|
||||
t.Fatalf("CurrentDataRoot = %q", CurrentDataRoot())
|
||||
}
|
||||
}
|
||||
|
||||
func TestExistingInstallIsAdoptedWithoutAsking(t *testing.T) {
|
||||
legacy := isolate(t)
|
||||
cfg := Default()
|
||||
cfg.DataRoot = legacy
|
||||
cfg.ActiveRuntime = "3731afd"
|
||||
if err := Save(filepath.Join(legacy, "reims-go.json"), cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, needs, err := Resolve()
|
||||
if err != nil || needs || got.ActiveRuntime != "3731afd" {
|
||||
t.Fatalf("legacy: %+v needs=%v err=%v", got, needs, err)
|
||||
}
|
||||
if root, ok := ReadLocation(); !ok || root != legacy {
|
||||
t.Fatalf("location not recorded: %q %v", root, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvOverridesEverything(t *testing.T) {
|
||||
isolate(t)
|
||||
env := t.TempDir()
|
||||
t.Setenv("REIMS_GO_DATA_ROOT", env)
|
||||
cfg, needs, err := Resolve()
|
||||
if err != nil || needs || cfg.DataRoot != env {
|
||||
t.Fatalf("env: root=%q needs=%v err=%v", cfg.DataRoot, needs, err)
|
||||
}
|
||||
if _, err := os.Stat(LocationPath()); !os.IsNotExist(err) {
|
||||
t.Fatal("env override must not write the location file")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package reims
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// creatingMarker is written by upstream `reims-ctl create` while building a VM
|
||||
// directory and removed once vm.toml is saved (upstream 3731afd create.rs:451).
|
||||
const creatingMarker = ".reims-ctl-creating"
|
||||
|
||||
// CleanAbortedCreateDir removes an unregistered VM target directory left behind
|
||||
// by a previously killed `reims-ctl create` run. It only removes a directory
|
||||
// when all three safety conditions hold:
|
||||
// 1. opts.Name is not present in registered VMs,
|
||||
// 2. `.reims-ctl-creating` exists inside the directory, and
|
||||
// 3. `vm.toml` does NOT exist inside the directory.
|
||||
//
|
||||
// Returns the removed path if cleaned, or "" if nothing was touched.
|
||||
func CleanAbortedCreateDir(xdgDataDir string, opts CreateOpts, registered []VMListItem) (string, error) {
|
||||
name := strings.TrimSpace(opts.Name)
|
||||
if name == "" {
|
||||
return "", nil
|
||||
}
|
||||
for _, vm := range registered {
|
||||
if strings.EqualFold(vm.Name, name) {
|
||||
return "", nil
|
||||
}
|
||||
}
|
||||
target := strings.TrimSpace(opts.Dir)
|
||||
if target == "" {
|
||||
if strings.TrimSpace(xdgDataDir) == "" {
|
||||
return "", nil
|
||||
}
|
||||
target = filepath.Join(xdgDataDir, "reims-ctl", "vms", name)
|
||||
}
|
||||
markerInfo, err := os.Stat(filepath.Join(target, creatingMarker))
|
||||
if err != nil || markerInfo.IsDir() {
|
||||
return "", nil
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(target, "vm.toml")); err == nil {
|
||||
return "", nil
|
||||
}
|
||||
if err := os.RemoveAll(target); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return target, nil
|
||||
}
|
||||
|
||||
// IsWHPXNestedVirtError reports whether QEMU exited because WHPX failed to
|
||||
// enable nested virtualization (e.g. hr=80370302 WHV_E_UNKNOWN_PROPERTY on
|
||||
// Windows 11 builds that advertise Bank1.NestedVirtSupport but reject
|
||||
// WHvPartitionPropertyCodeNestedVirtualization; qemu-reims-vgpu 4571bc5
|
||||
// target/i386/whpx/whpx-all.c:3471-3484).
|
||||
func IsWHPXNestedVirtError(output string) bool {
|
||||
return strings.Contains(output, "WHPX: Failed to enable nested virtualization")
|
||||
}
|
||||
|
||||
// HasKernelIrqchipArg reports whether extra-args already specifies a
|
||||
// kernel-irqchip setting.
|
||||
func HasKernelIrqchipArg(extraArgs string) bool {
|
||||
return strings.Contains(strings.ToLower(extraArgs), "kernel-irqchip=")
|
||||
}
|
||||
|
||||
// MergeKernelIrqchipOffArgs appends `-machine kernel-irqchip=off` to existing
|
||||
// QEMU extra-args unless a kernel-irqchip setting is already present.
|
||||
func MergeKernelIrqchipOffArgs(existing string) string {
|
||||
trimmed := strings.TrimSpace(existing)
|
||||
if HasKernelIrqchipArg(trimmed) {
|
||||
return trimmed
|
||||
}
|
||||
const flag = "-machine kernel-irqchip=off"
|
||||
if trimmed == "" {
|
||||
return flag
|
||||
}
|
||||
return trimmed + " " + flag
|
||||
}
|
||||
|
||||
type captureWriter struct {
|
||||
mu sync.Mutex
|
||||
buf bytes.Buffer
|
||||
dst io.Writer
|
||||
}
|
||||
|
||||
func (w *captureWriter) Write(p []byte) (int, error) {
|
||||
w.mu.Lock()
|
||||
if w.buf.Len() < 64*1024 {
|
||||
w.buf.Write(p)
|
||||
}
|
||||
w.mu.Unlock()
|
||||
if w.dst != nil {
|
||||
return w.dst.Write(p)
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (w *captureWriter) String() string {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.buf.String()
|
||||
}
|
||||
|
||||
// StartWithCompat starts a VM and automatically recovers once if QEMU aborts
|
||||
// with the WHPX nested-virtualization property error (hr=80370302) by writing
|
||||
// `-machine kernel-irqchip=off` via `reims-ctl set` (D3) and retrying start.
|
||||
func (c *Client) StartWithCompat(ctx context.Context, name string, stdout, stderr io.Writer, onNote func(string)) error {
|
||||
outCap := &captureWriter{dst: stdout}
|
||||
errCap := &captureWriter{dst: stderr}
|
||||
err := c.Start(ctx, name, outCap, errCap)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
combined := outCap.String() + "\n" + errCap.String()
|
||||
if !IsWHPXNestedVirtError(combined) {
|
||||
return err
|
||||
}
|
||||
cur, serr := c.Show(ctx, name)
|
||||
if serr != nil || HasKernelIrqchipArg(cur.ExtraArgs) {
|
||||
return err
|
||||
}
|
||||
merged := MergeKernelIrqchipOffArgs(cur.ExtraArgs)
|
||||
if setErr := c.Set(ctx, SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); setErr != nil {
|
||||
return err
|
||||
}
|
||||
if onNote != nil {
|
||||
onNote("WHPX host rejected nested virtualization property (hr=80370302); applied -machine kernel-irqchip=off and retrying start...")
|
||||
}
|
||||
return c.Start(ctx, name, stdout, stderr)
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package reims
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBuildDeleteArgs(t *testing.T) {
|
||||
got := BuildDeleteArgs("macos-tahoe", false)
|
||||
want := []string{"delete", "--yes", "macos-tahoe"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("BuildDeleteArgs(keepFiles=false) = %v, want %v", got, want)
|
||||
}
|
||||
gotKeep := BuildDeleteArgs("macos-tahoe", true)
|
||||
wantKeep := []string{"delete", "--yes", "macos-tahoe", "--keep-files"}
|
||||
if !reflect.DeepEqual(gotKeep, wantKeep) {
|
||||
t.Fatalf("BuildDeleteArgs(keepFiles=true) = %v, want %v", gotKeep, wantKeep)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedactLogLine(t *testing.T) {
|
||||
got := RedactLogLine("mac 52:54:00:12:34:56 serial C02ABCDEFGH")
|
||||
if got != "mac [redacted] serial [redacted]" {
|
||||
t.Fatalf("RedactLogLine = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanAbortedCreateDir(t *testing.T) {
|
||||
dataDir := t.TempDir()
|
||||
vmDir := filepath.Join(dataDir, "reims-ctl", "vms", "macos-tahoe")
|
||||
if err := os.MkdirAll(vmDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(vmDir, creatingMarker), nil, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(vmDir, "disk.qcow2"), []byte("partial"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Refuses if VM is registered.
|
||||
removed, err := CleanAbortedCreateDir(dataDir, CreateOpts{Name: "macos-tahoe"}, []VMListItem{{Name: "macos-tahoe"}})
|
||||
if err != nil || removed != "" {
|
||||
t.Fatalf("expected skip for registered VM, got removed=%q err=%v", removed, err)
|
||||
}
|
||||
|
||||
// Refuses if vm.toml exists.
|
||||
tomlPath := filepath.Join(vmDir, "vm.toml")
|
||||
if err := os.WriteFile(tomlPath, []byte("cpus = 8\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
removed, err = CleanAbortedCreateDir(dataDir, CreateOpts{Name: "macos-tahoe"}, nil)
|
||||
if err != nil || removed != "" {
|
||||
t.Fatalf("expected skip when vm.toml exists, got removed=%q err=%v", removed, err)
|
||||
}
|
||||
_ = os.Remove(tomlPath)
|
||||
|
||||
// Cleans when unregistered, .reims-ctl-creating exists, and vm.toml is absent.
|
||||
removed, err = CleanAbortedCreateDir(dataDir, CreateOpts{Name: "macos-tahoe"}, nil)
|
||||
if err != nil || removed != vmDir {
|
||||
t.Fatalf("expected removal of %q, got removed=%q err=%v", vmDir, removed, err)
|
||||
}
|
||||
if _, err := os.Stat(vmDir); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected %q to be deleted, stat err=%v", vmDir, err)
|
||||
}
|
||||
|
||||
// Refuses arbitrary non-empty directory without marker.
|
||||
customDir := filepath.Join(t.TempDir(), "user-folder")
|
||||
if err := os.MkdirAll(customDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(customDir, "notes.txt"), []byte("keep"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
removed, err = CleanAbortedCreateDir(dataDir, CreateOpts{Name: "other", Dir: customDir}, nil)
|
||||
if err != nil || removed != "" {
|
||||
t.Fatalf("expected skip without marker, got removed=%q err=%v", removed, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWHPXNestedVirtCompat(t *testing.T) {
|
||||
sampleErr := "2026-11-28T13:04:47Z qemu: -accel whpx: WHPX: Failed to enable nested virtualization, hr=80370302\n"
|
||||
if !IsWHPXNestedVirtError(sampleErr) {
|
||||
t.Fatalf("expected IsWHPXNestedVirtError to match")
|
||||
}
|
||||
if IsWHPXNestedVirtError("some unrelated error") {
|
||||
t.Fatalf("unexpected match on unrelated error")
|
||||
}
|
||||
|
||||
if got := MergeKernelIrqchipOffArgs(""); got != "-machine kernel-irqchip=off" {
|
||||
t.Fatalf("MergeKernelIrqchipOffArgs(empty) = %q", got)
|
||||
}
|
||||
existing := "-no-reboot -qmp tcp:127.0.0.1:45555,server=on,wait=off"
|
||||
want := existing + " -machine kernel-irqchip=off"
|
||||
if got := MergeKernelIrqchipOffArgs(existing); got != want {
|
||||
t.Fatalf("MergeKernelIrqchipOffArgs = %q, want %q", got, want)
|
||||
}
|
||||
// Idempotent when already set.
|
||||
if got := MergeKernelIrqchipOffArgs(want); got != want {
|
||||
t.Fatalf("expected idempotent merge, got %q", got)
|
||||
}
|
||||
if !HasKernelIrqchipArg("-accel whpx,kernel-irqchip=on") {
|
||||
t.Fatalf("expected HasKernelIrqchipArg to detect accel form")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergeAndStripOfflineHelperArgs(t *testing.T) {
|
||||
base := `-no-reboot -qmp tcp:127.0.0.1:45555,server=on,wait=off -machine kernel-irqchip=off`
|
||||
merged := MergeOfflineHelperArgs(base, `D:\Data\reims-go\cache\reims-helper.img`)
|
||||
if !strings.Contains(merged, "id=reimshelp,if=none,format=raw,readonly=on,file=D:/Data/reims-go/cache/reims-helper.img") {
|
||||
t.Fatalf("unexpected merged helper args: %q", merged)
|
||||
}
|
||||
merged2 := MergeOfflineHelperArgs(merged, `D:\My Data\helper,v2.img`)
|
||||
if strings.Count(merged2, "id=reimshelp,") != 1 || !strings.Contains(merged2, "helper,,v2.img") {
|
||||
t.Fatalf("expected idempotent replace with comma escape: %q", merged2)
|
||||
}
|
||||
stripped := StripOfflineHelperArgs(merged2)
|
||||
if stripped != base {
|
||||
t.Fatalf("StripOfflineHelperArgs = %q, want %q", stripped, base)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildUpdateOpenCoreArgs(t *testing.T) {
|
||||
gotOn := strings.Join(BuildUpdateOpenCoreArgs("macos-tahoe", true), " ")
|
||||
if gotOn != "update-opencore macos-tahoe --boot-selection=true" {
|
||||
t.Fatalf("BuildUpdateOpenCoreArgs(true) = %q", gotOn)
|
||||
}
|
||||
gotOff := strings.Join(BuildUpdateOpenCoreArgs("macos-tahoe", false), " ")
|
||||
if gotOff != "update-opencore macos-tahoe --boot-selection=false" {
|
||||
t.Fatalf("BuildUpdateOpenCoreArgs(false) = %q", gotOff)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateDefaultNVMeAndPreview(t *testing.T) {
|
||||
opts := CreateOpts{Name: "macos-tahoe", MacOS: "tahoe", CPUs: 8, Memory: "16G"}
|
||||
if got := EffectiveCreateDiskController(opts); got != "nvme" {
|
||||
t.Fatalf("EffectiveCreateDiskController default = %q, want nvme", got)
|
||||
}
|
||||
if EffectiveCreateCapture(opts) {
|
||||
t.Fatalf("EffectiveCreateCapture default = true, want false")
|
||||
}
|
||||
cmd, err := PreviewCreateCommand(opts)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(cmd, "&& reims-ctl set macos-tahoe --disk-controller nvme --capture false") {
|
||||
t.Fatalf("PreviewCreateCommand missing nvme + capture=false set step: %q", cmd)
|
||||
}
|
||||
opts.DiskController = "ahci"
|
||||
on := true
|
||||
opts.Capture = &on
|
||||
cmdAhciCaptureOn, err := PreviewCreateCommand(opts)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(cmdAhciCaptureOn, "&& reims-ctl set") {
|
||||
t.Fatalf("PreviewCreateCommand should omit set step for ahci + capture=true: %q", cmdAhciCaptureOn)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergeAndStripGuestToolsArgs(t *testing.T) {
|
||||
base := `-drive id=reimshelp,if=none,format=raw,readonly=on,file=D:/help.img -device usb-storage,id=reimshelp-dev,drive=reimshelp,bus=xhci.0`
|
||||
merged := MergeGuestToolsArgs(base, `D:\Data\reims-go\cache\m0-tools.img`)
|
||||
if !HasGuestToolsArgs(merged) || !strings.Contains(merged, "id=reimshelp,") {
|
||||
t.Fatalf("expected both reimshelp and reimstools coexisting: %q", merged)
|
||||
}
|
||||
stripped := StripGuestToolsArgs(merged)
|
||||
if stripped != base || HasGuestToolsArgs(stripped) {
|
||||
t.Fatalf("StripGuestToolsArgs = %q, want %q", stripped, base)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskImportAndCoWArgs(t *testing.T) {
|
||||
if !NeedsDiskConversion(`D:\vms\mac.vmdk`) || !NeedsDiskConversion(`D:\vms\mac.RAW`) {
|
||||
t.Fatalf("expected .vmdk and .raw to need conversion")
|
||||
}
|
||||
if NeedsDiskConversion(`D:\vms\disk.qcow2`) || NeedsDiskConversion(`D:\vms\disk.img`) {
|
||||
t.Fatalf("did not expect .qcow2/.img to need conversion")
|
||||
}
|
||||
conv := strings.Join(BuildConvertToQCOW2Args("in.vmdk", "out.qcow2"), " ")
|
||||
if conv != "convert -O qcow2 in.vmdk out.qcow2" {
|
||||
t.Fatalf("BuildConvertToQCOW2Args = %q", conv)
|
||||
}
|
||||
cow := strings.Join(BuildCoWOverlayArgs("golden.qcow2", "cow-dev.qcow2"), " ")
|
||||
if cow != "create -f qcow2 -b golden.qcow2 -F qcow2 cow-dev.qcow2" {
|
||||
t.Fatalf("BuildCoWOverlayArgs = %q", cow)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package reims
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// NeedsDiskConversion reports whether srcPath is a disk format (VMDK or RAW)
|
||||
// that should be converted to qcow2 via qemu-img before handing off to reims-ctl.
|
||||
func NeedsDiskConversion(srcPath string) bool {
|
||||
ext := strings.ToLower(filepath.Ext(strings.TrimSpace(srcPath)))
|
||||
return ext == ".vmdk" || ext == ".raw"
|
||||
}
|
||||
|
||||
// BuildConvertToQCOW2Args constructs `qemu-img convert -O qcow2` arguments.
|
||||
func BuildConvertToQCOW2Args(srcPath, dstPath string) []string {
|
||||
return []string{"convert", "-O", "qcow2", srcPath, dstPath}
|
||||
}
|
||||
|
||||
// BuildCoWOverlayArgs constructs `qemu-img create -f qcow2 -b <backing> -F qcow2 <overlay>`
|
||||
// arguments for instant copy-on-write VM derivation.
|
||||
func BuildCoWOverlayArgs(backingPath, overlayPath string) []string {
|
||||
return []string{"create", "-f", "qcow2", "-b", backingPath, "-F", "qcow2", overlayPath}
|
||||
}
|
||||
|
||||
// ConvertDiskToQCOW2 converts a VMDK or RAW disk image to qcow2 using the
|
||||
// portable runtime's qemu-img binary.
|
||||
func ConvertDiskToQCOW2(ctx context.Context, qemuImgPath string, env []string, srcPath, dstPath string, stdout, stderr io.Writer) error {
|
||||
if _, err := os.Stat(qemuImgPath); err != nil {
|
||||
return fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(dstPath), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, qemuImgPath, BuildConvertToQCOW2Args(srcPath, dstPath)...)
|
||||
configureCmd(cmd)
|
||||
cmd.Env = env
|
||||
if stdout != nil {
|
||||
cmd.Stdout = stdout
|
||||
}
|
||||
if stderr != nil {
|
||||
cmd.Stderr = stderr
|
||||
}
|
||||
if err := cmd.Run(); err != nil {
|
||||
_ = os.Remove(dstPath)
|
||||
return fmt.Errorf("qemu-img convert %s: %w", filepath.Base(srcPath), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateCoWOverlay creates an instant qcow2 copy-on-write overlay backed by
|
||||
// backingPath without modifying the backing disk image.
|
||||
func CreateCoWOverlay(ctx context.Context, qemuImgPath string, env []string, backingPath, overlayPath string, stdout, stderr io.Writer) error {
|
||||
if _, err := os.Stat(qemuImgPath); err != nil {
|
||||
return fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
|
||||
}
|
||||
if _, err := os.Stat(backingPath); err != nil {
|
||||
return fmt.Errorf("backing disk not found (%s): %w", backingPath, err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(overlayPath), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, qemuImgPath, BuildCoWOverlayArgs(backingPath, overlayPath)...)
|
||||
configureCmd(cmd)
|
||||
cmd.Env = env
|
||||
if stdout != nil {
|
||||
cmd.Stdout = stdout
|
||||
}
|
||||
if stderr != nil {
|
||||
cmd.Stderr = stderr
|
||||
}
|
||||
if err := cmd.Run(); err != nil {
|
||||
_ = os.Remove(overlayPath)
|
||||
return fmt.Errorf("qemu-img create CoW overlay: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package reims
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// IsOfflineInstallerPath reports whether an attached installer path is a
|
||||
// reims-util offline installer image.
|
||||
func IsOfflineInstallerPath(path string) bool {
|
||||
return strings.Contains(strings.ToLower(path), "offline-installer")
|
||||
}
|
||||
|
||||
// StripOfflineHelperArgs removes any reims-go managed offline helper USB disk
|
||||
// arguments from QEMU extra-args while leaving all other arguments intact.
|
||||
func StripOfflineHelperArgs(existing string) string {
|
||||
tokens := splitShellTokens(existing)
|
||||
cleaned := make([]string, 0, len(tokens))
|
||||
for i := 0; i < len(tokens); i++ {
|
||||
tok := tokens[i]
|
||||
if tok == "-drive" && i+1 < len(tokens) && strings.Contains(tokens[i+1], "id=reimshelp,") {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if tok == "-device" && i+1 < len(tokens) && strings.Contains(tokens[i+1], "id=reimshelp-dev,") {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
cleaned = append(cleaned, tok)
|
||||
}
|
||||
return strings.Join(cleaned, " ")
|
||||
}
|
||||
|
||||
// MergeOfflineHelperArgs idempotently attaches helperImgPath as a read-only USB
|
||||
// storage volume on xhci.0 (appearing as /Volumes/REIMSHELP in macOS Recovery).
|
||||
func MergeOfflineHelperArgs(existing, helperImgPath string) string {
|
||||
base := StripOfflineHelperArgs(existing)
|
||||
// QEMU drive option syntax escapes commas by doubling them, and shlex
|
||||
// preserves single-quoted paths containing spaces or backslashes.
|
||||
escapedPath := strings.ReplaceAll(helperImgPath, ",", ",,")
|
||||
escapedPath = strings.ReplaceAll(escapedPath, `\`, `/`)
|
||||
driveVal := fmt.Sprintf("id=reimshelp,if=none,format=raw,readonly=on,file=%s", escapedPath)
|
||||
if strings.ContainsAny(driveVal, " \t") {
|
||||
driveVal = `"` + strings.ReplaceAll(driveVal, `"`, `\"`) + `"`
|
||||
}
|
||||
helperArgs := fmt.Sprintf("-drive %s -device usb-storage,id=reimshelp-dev,drive=reimshelp,bus=xhci.0", driveVal)
|
||||
if base == "" {
|
||||
return helperArgs
|
||||
}
|
||||
return base + " " + helperArgs
|
||||
}
|
||||
|
||||
// HasGuestToolsArgs reports whether the REIMSTOOLS virtual USB disk is attached.
|
||||
func HasGuestToolsArgs(existing string) bool {
|
||||
return strings.Contains(existing, "id=reimstools,")
|
||||
}
|
||||
|
||||
// StripGuestToolsArgs removes any reims-go managed REIMSTOOLS USB disk args.
|
||||
func StripGuestToolsArgs(existing string) string {
|
||||
tokens := splitShellTokens(existing)
|
||||
cleaned := make([]string, 0, len(tokens))
|
||||
for i := 0; i < len(tokens); i++ {
|
||||
tok := tokens[i]
|
||||
if tok == "-drive" && i+1 < len(tokens) && strings.Contains(tokens[i+1], "id=reimstools,") {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if tok == "-device" && i+1 < len(tokens) && strings.Contains(tokens[i+1], "id=reimstools-dev,") {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
cleaned = append(cleaned, tok)
|
||||
}
|
||||
return strings.Join(cleaned, " ")
|
||||
}
|
||||
|
||||
// MergeGuestToolsArgs idempotently attaches toolsImgPath as a read-only USB
|
||||
// storage volume on xhci.0 (appearing as /Volumes/REIMSTOOLS in macOS).
|
||||
func MergeGuestToolsArgs(existing, toolsImgPath string) string {
|
||||
base := StripGuestToolsArgs(existing)
|
||||
escapedPath := strings.ReplaceAll(toolsImgPath, ",", ",,")
|
||||
escapedPath = strings.ReplaceAll(escapedPath, `\`, `/`)
|
||||
driveVal := fmt.Sprintf("id=reimstools,if=none,format=raw,readonly=on,file=%s", escapedPath)
|
||||
if strings.ContainsAny(driveVal, " \t") {
|
||||
driveVal = `"` + strings.ReplaceAll(driveVal, `"`, `\"`) + `"`
|
||||
}
|
||||
toolsArgs := fmt.Sprintf("-drive %s -device usb-storage,id=reimstools-dev,drive=reimstools,bus=xhci.0", driveVal)
|
||||
if base == "" {
|
||||
return toolsArgs
|
||||
}
|
||||
return base + " " + toolsArgs
|
||||
}
|
||||
|
||||
func splitShellTokens(s string) []string {
|
||||
var out []string
|
||||
var cur strings.Builder
|
||||
var quote byte
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if quote != 0 {
|
||||
cur.WriteByte(c)
|
||||
if c == quote {
|
||||
quote = 0
|
||||
}
|
||||
continue
|
||||
}
|
||||
if c == '\'' || c == '"' {
|
||||
quote = c
|
||||
cur.WriteByte(c)
|
||||
continue
|
||||
}
|
||||
if c == ' ' || c == '\t' || c == '\n' || c == '\r' {
|
||||
if cur.Len() > 0 {
|
||||
out = append(out, cur.String())
|
||||
cur.Reset()
|
||||
}
|
||||
continue
|
||||
}
|
||||
cur.WriteByte(c)
|
||||
}
|
||||
if cur.Len() > 0 {
|
||||
out = append(out, cur.String())
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package reims
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
reLogMac = regexp.MustCompile(`(?i)\b(mac[\s:=]+)["']?[0-9a-f]{2}(?::[0-9a-f]{2}){5}["']?`)
|
||||
reLogSerial = regexp.MustCompile(`(?i)\b(serial[\s:=]+)["']?[A-Z0-9]{8,}["']?`)
|
||||
reLogOSK = regexp.MustCompile(`(?i)\b(osk=)[^\s,"']+`)
|
||||
reLogBearer = regexp.MustCompile(`(?i)(Bearer\s+)[A-Za-z0-9._~+/-]{16,}`)
|
||||
reLogTokenKV = regexp.MustCompile(`(?i)((?:REIMS_TOKEN|"token")\s*[:=]\s*["']?)[A-Za-z0-9._~+/-]{16,}(["']?)`)
|
||||
)
|
||||
|
||||
// RedactLogLine removes MAC addresses, SMBIOS serial numbers, SMC OSK keys, and
|
||||
// Guest Tools Bearer tokens before lines are emitted or exported.
|
||||
func RedactLogLine(line string) string {
|
||||
line = reLogMac.ReplaceAllString(line, "${1}[redacted]")
|
||||
line = reLogSerial.ReplaceAllString(line, "${1}[redacted]")
|
||||
line = reLogOSK.ReplaceAllString(line, "${1}[redacted]")
|
||||
line = reLogBearer.ReplaceAllString(line, "${1}[redacted]")
|
||||
line = reLogTokenKV.ReplaceAllString(line, "${1}[redacted]${2}")
|
||||
return line
|
||||
}
|
||||
|
||||
// RedactText applies RedactLogLine across a multi-line log or JSON text block.
|
||||
func RedactText(s string) string {
|
||||
lines := strings.Split(s, "\n")
|
||||
for i, l := range lines {
|
||||
lines[i] = RedactLogLine(l)
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
@@ -53,6 +53,7 @@ type VMDetail struct {
|
||||
GPU string `json:"gpu"`
|
||||
HasOpenCore bool `json:"has_opencore"`
|
||||
HasInstaller bool `json:"has_installer"`
|
||||
RecoveryMode bool `json:"recovery_mode"`
|
||||
InstallerPath string `json:"installer_path,omitempty"`
|
||||
CPUModel string `json:"cpu_model"`
|
||||
Audio bool `json:"audio"`
|
||||
@@ -64,8 +65,12 @@ type VMDetail struct {
|
||||
LogLevel string `json:"log_level"`
|
||||
StopTimeout int `json:"stop_timeout"`
|
||||
Capture bool `json:"capture"`
|
||||
Borderless bool `json:"borderless"`
|
||||
ExtraArgs string `json:"extra_args"`
|
||||
Borderless bool `json:"borderless"`
|
||||
ExtraArgs string `json:"extra_args"`
|
||||
GuestToolsAttached bool `json:"guest_tools_attached"`
|
||||
GuestToolsConfigured bool `json:"guest_tools_configured"`
|
||||
GuestToolsConnected bool `json:"guest_tools_connected"`
|
||||
SharedDir string `json:"shared_dir,omitempty"`
|
||||
}
|
||||
|
||||
type ValidationIssue struct {
|
||||
@@ -79,17 +84,23 @@ type CreateOpts struct {
|
||||
Dir string `json:"dir,omitempty"`
|
||||
SourceMode string `json:"source_mode,omitempty"` // "apple" | "installer" | "disk"
|
||||
MacOS string `json:"macos,omitempty"`
|
||||
// Offline makes --macos an offline installer of one release (13 to 20 GB)
|
||||
// that installs with no network; upstream advises the VM's network off then
|
||||
// (`reims-ctl create --help`, 3731afd). Network defaults to false with it.
|
||||
Offline bool `json:"offline,omitempty"`
|
||||
Installer string `json:"installer,omitempty"`
|
||||
CPUs int `json:"cpus,omitempty"`
|
||||
Memory string `json:"memory,omitempty"`
|
||||
DiskSize string `json:"disk_size,omitempty"`
|
||||
Disk string `json:"disk,omitempty"`
|
||||
DiskMode string `json:"disk_mode,omitempty"`
|
||||
Graphics string `json:"graphics,omitempty"`
|
||||
DiskSize string `json:"disk_size,omitempty"`
|
||||
Disk string `json:"disk,omitempty"`
|
||||
DiskMode string `json:"disk_mode,omitempty"`
|
||||
DiskController string `json:"disk_controller,omitempty"`
|
||||
Graphics string `json:"graphics,omitempty"`
|
||||
GPU string `json:"gpu,omitempty"`
|
||||
Resolution string `json:"resolution,omitempty"`
|
||||
Displays int `json:"displays,omitempty"`
|
||||
Borderless *bool `json:"borderless,omitempty"`
|
||||
Capture *bool `json:"capture,omitempty"`
|
||||
Audio *bool `json:"audio,omitempty"`
|
||||
Network *bool `json:"network,omitempty"`
|
||||
SSHPort int `json:"ssh_port,omitempty"`
|
||||
@@ -158,8 +169,13 @@ func ValidateCreate(o CreateOpts, rep host.Report) []ValidationIssue {
|
||||
issues = append(issues, ValidationIssue{Field: "memory", Code: "invalid_memory", Message: "Memory must be at least 2G (e.g. 8G, 16G)"})
|
||||
} else if rep.TotalRAMGB > 0 && memGB > rep.TotalRAMGB*0.85 {
|
||||
issues = append(issues, ValidationIssue{Field: "memory", Code: "memory_exceeds_host", Message: fmt.Sprintf("Memory %.0fG exceeds safe host limit (host total %.1f GB)", memGB, rep.TotalRAMGB)})
|
||||
} else if rep.CommitLimitGB > 0 && memGB+host.StartMarginGB > rep.CommitLimitGB-2 {
|
||||
issues = append(issues, ValidationIssue{Field: "memory", Code: "memory_exceeds_commit", Message: fmt.Sprintf("Memory %.0fG can't fit in Windows' commit limit (%.1f GB including the page file); choose %.0fG or less", memGB, rep.CommitLimitGB, host.RecommendedMemoryGB(rep))})
|
||||
}
|
||||
}
|
||||
if o.Offline && strings.TrimSpace(o.MacOS) == "" {
|
||||
issues = append(issues, ValidationIssue{Field: "macos", Code: "missing_release", Message: "Choose the macOS release to install offline"})
|
||||
}
|
||||
if o.Disk == "" && o.DiskSize != "" {
|
||||
diskGB, ok := ParseSizeGB(o.DiskSize)
|
||||
if !ok || diskGB < 32 {
|
||||
@@ -171,6 +187,9 @@ func ValidateCreate(o CreateOpts, rep host.Report) []ValidationIssue {
|
||||
issues = append(issues, ValidationIssue{Field: "disk", Code: "disk_not_found", Message: "Selected disk image file does not exist"})
|
||||
}
|
||||
}
|
||||
if dc := strings.ToLower(strings.TrimSpace(o.DiskController)); dc != "" && dc != "nvme" && dc != "ahci" && dc != "virtio" {
|
||||
issues = append(issues, ValidationIssue{Field: "disk_controller", Code: "invalid_disk_controller", Message: "Disk controller must be nvme, ahci, or virtio"})
|
||||
}
|
||||
if o.Installer != "" {
|
||||
if _, err := os.Stat(o.Installer); err != nil {
|
||||
issues = append(issues, ValidationIssue{Field: "installer", Code: "installer_not_found", Message: "Selected installer image file does not exist"})
|
||||
@@ -208,6 +227,8 @@ func ValidateSet(o SetOpts, current VMDetail, rep host.Report) []ValidationIssue
|
||||
issues = append(issues, ValidationIssue{Field: "memory", Code: "invalid_memory", Message: "Memory must be at least 2G"})
|
||||
} else if rep.TotalRAMGB > 0 && memGB > rep.TotalRAMGB*0.85 {
|
||||
issues = append(issues, ValidationIssue{Field: "memory", Code: "memory_exceeds_host", Message: fmt.Sprintf("Memory %.0fG exceeds safe host limit (%.1f GB total)", memGB, rep.TotalRAMGB)})
|
||||
} else if rep.CommitLimitGB > 0 && memGB+host.StartMarginGB > rep.CommitLimitGB-2 {
|
||||
issues = append(issues, ValidationIssue{Field: "memory", Code: "memory_exceeds_commit", Message: fmt.Sprintf("Memory %.0fG can't fit in Windows' commit limit (%.1f GB including the page file); choose %.0fG or less", memGB, rep.CommitLimitGB, host.RecommendedMemoryGB(rep))})
|
||||
}
|
||||
}
|
||||
if o.Graphics != "" && current.Graphics != "" && o.Graphics != current.Graphics && current.State == "running" {
|
||||
@@ -244,6 +265,9 @@ func BuildCreateArgs(o CreateOpts) ([]string, error) {
|
||||
}
|
||||
if o.MacOS != "" {
|
||||
args = append(args, "--macos", o.MacOS)
|
||||
if o.Offline {
|
||||
args = append(args, "--offline")
|
||||
}
|
||||
}
|
||||
if o.Installer != "" {
|
||||
args = append(args, "--installer", o.Installer)
|
||||
@@ -283,6 +307,8 @@ func BuildCreateArgs(o CreateOpts) ([]string, error) {
|
||||
}
|
||||
if o.Network != nil {
|
||||
args = append(args, "--network", strconv.FormatBool(*o.Network))
|
||||
} else if o.Offline {
|
||||
args = append(args, "--network", "false")
|
||||
}
|
||||
if o.SSHPort > 0 {
|
||||
args = append(args, "--ssh-port", strconv.Itoa(o.SSHPort))
|
||||
@@ -296,22 +322,73 @@ func BuildCreateArgs(o CreateOpts) ([]string, error) {
|
||||
return args, nil
|
||||
}
|
||||
|
||||
// EffectiveCreateDiskController returns the disk controller to apply to a newly
|
||||
// created VM. Defaults to NVMe because upstream reims-ctl confirms macOS
|
||||
// Recovery, installer, and installed macOS all support NVMe natively with lower
|
||||
// I/O overhead and TRIM/discard (upstream 3731afd vm.rs:188-190, qemu.rs:389-394).
|
||||
func EffectiveCreateDiskController(o CreateOpts) string {
|
||||
dc := strings.ToLower(strings.TrimSpace(o.DiskController))
|
||||
if dc == "" {
|
||||
return "nvme"
|
||||
}
|
||||
return dc
|
||||
}
|
||||
|
||||
// EffectiveCreateCapture returns whether keyboard/mouse capture should be
|
||||
// enabled on a newly created VM. Defaults to false (free pointer) so host
|
||||
// shortcuts like Win key and Alt+Tab stay with Windows and users do not get
|
||||
// trapped in the macOS window during Recovery/install; users can opt in via
|
||||
// CreateOpts.Capture or VM Settings -> Keyboard & pointer.
|
||||
func EffectiveCreateCapture(o CreateOpts) bool {
|
||||
if o.Capture != nil {
|
||||
return *o.Capture
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// PostCreateSetOpts returns follow-up `reims-ctl set` options for defaults that
|
||||
// `reims-ctl create` does not accept directly (upstream 3731afd defaults to
|
||||
// SATA/AHCI and capture=true).
|
||||
func PostCreateSetOpts(o CreateOpts) (SetOpts, bool) {
|
||||
so := SetOpts{Name: o.Name}
|
||||
need := false
|
||||
if dc := EffectiveCreateDiskController(o); dc != "ahci" {
|
||||
so.DiskController = dc
|
||||
need = true
|
||||
}
|
||||
if !EffectiveCreateCapture(o) {
|
||||
off := false
|
||||
so.Capture = &off
|
||||
need = true
|
||||
}
|
||||
return so, need
|
||||
}
|
||||
|
||||
// PreviewCreateCommand formats the exact CLI command shown on Step 5 of the wizard.
|
||||
func PreviewCreateCommand(o CreateOpts) (string, error) {
|
||||
args, err := BuildCreateArgs(o)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
quoted := make([]string, 0, len(args)+1)
|
||||
quoted = append(quoted, "reims-ctl")
|
||||
for _, a := range args {
|
||||
if strings.ContainsAny(a, " \t\"") {
|
||||
quoted = append(quoted, strconv.Quote(a))
|
||||
} else {
|
||||
quoted = append(quoted, a)
|
||||
quoteArgs := func(in []string) string {
|
||||
quoted := make([]string, 0, len(in)+1)
|
||||
quoted = append(quoted, "reims-ctl")
|
||||
for _, a := range in {
|
||||
if strings.ContainsAny(a, " \t\"") {
|
||||
quoted = append(quoted, strconv.Quote(a))
|
||||
} else {
|
||||
quoted = append(quoted, a)
|
||||
}
|
||||
}
|
||||
return strings.Join(quoted, " ")
|
||||
}
|
||||
cmd := quoteArgs(args)
|
||||
if so, ok := PostCreateSetOpts(o); ok {
|
||||
if setArgs, err := BuildSetArgs(so); err == nil {
|
||||
cmd += " && " + quoteArgs(setArgs)
|
||||
}
|
||||
}
|
||||
return strings.Join(quoted, " "), nil
|
||||
return cmd, nil
|
||||
}
|
||||
|
||||
// BuildSetArgs converts SetOpts into reims-ctl set CLI arguments.
|
||||
@@ -469,6 +546,11 @@ func ParseShow(name, text string) VMDetail {
|
||||
// Redact MAC per docs/shell-design.md §3.
|
||||
d.NetworkSummary = strings.TrimSpace(reMac.ReplaceAllString(v, " (MAC configured)"))
|
||||
d.Network = !strings.EqualFold(v, "off") && !strings.EqualFold(v, "none")
|
||||
if d.SSHPort == 0 {
|
||||
if m := regexp.MustCompile(`ssh on [^:]+:(\d+)`).FindStringSubmatch(v); len(m) == 2 {
|
||||
d.SSHPort, _ = strconv.Atoi(m[1])
|
||||
}
|
||||
}
|
||||
case "ssh":
|
||||
if m := regexp.MustCompile(`(\d+)`).FindString(v); m != "" {
|
||||
d.SSHPort, _ = strconv.Atoi(m)
|
||||
@@ -483,7 +565,8 @@ func ParseShow(name, text string) VMDetail {
|
||||
d.StopTimeout, _ = strconv.Atoi(m)
|
||||
}
|
||||
case "capture":
|
||||
d.Capture = !strings.EqualFold(v, "off") && !strings.EqualFold(v, "false")
|
||||
low := strings.ToLower(strings.TrimSpace(v))
|
||||
d.Capture = !strings.HasPrefix(low, "off") && !strings.HasPrefix(low, "false")
|
||||
case "extra args":
|
||||
d.ExtraArgs = v
|
||||
}
|
||||
@@ -584,10 +667,38 @@ func (c *Client) Eject(ctx context.Context, name string, stdout, stderr io.Write
|
||||
return c.run(ctx, stdout, stderr, "eject", name)
|
||||
}
|
||||
|
||||
func (c *Client) Delete(ctx context.Context, name string, keepFiles bool, stdout, stderr io.Writer) error {
|
||||
args := []string{"delete", name}
|
||||
// Insert attaches an installer or recovery image for the VM's next start
|
||||
// (`reims-ctl insert NAME PATH`, upstream 3731afd cli.rs:95, 694-701).
|
||||
func (c *Client) Insert(ctx context.Context, name, path string, stdout, stderr io.Writer) error {
|
||||
return c.run(ctx, stdout, stderr, "insert", name, path)
|
||||
}
|
||||
|
||||
// BuildUpdateOpenCoreArgs builds `reims-ctl update-opencore` arguments
|
||||
// (upstream 3731afd cli.rs:101-108, 706-715). Uses `=` form so clap's
|
||||
// optional flag value never consumes the positional VM name.
|
||||
func BuildUpdateOpenCoreArgs(name string, bootSelection bool) []string {
|
||||
flag := "--boot-selection=false"
|
||||
if bootSelection {
|
||||
flag = "--boot-selection=true"
|
||||
}
|
||||
return []string{"update-opencore", name, flag}
|
||||
}
|
||||
|
||||
func (c *Client) UpdateOpenCore(ctx context.Context, name string, bootSelection bool, stdout, stderr io.Writer) error {
|
||||
return c.run(ctx, stdout, stderr, BuildUpdateOpenCoreArgs(name, bootSelection)...)
|
||||
}
|
||||
|
||||
// BuildDeleteArgs builds `reims-ctl delete` arguments. Always passes --yes
|
||||
// because reims-ctl prompts interactively on stdin when omitted and exits 0
|
||||
// with "nothing deleted" on EOF (upstream reims-vgpu 3731afd cli.rs:1089-1099).
|
||||
func BuildDeleteArgs(name string, keepFiles bool) []string {
|
||||
args := []string{"delete", "--yes", name}
|
||||
if keepFiles {
|
||||
args = append(args, "--keep-files")
|
||||
}
|
||||
return c.run(ctx, stdout, stderr, args...)
|
||||
return args
|
||||
}
|
||||
|
||||
func (c *Client) Delete(ctx context.Context, name string, keepFiles bool, stdout, stderr io.Writer) error {
|
||||
return c.run(ctx, stdout, stderr, BuildDeleteArgs(name, keepFiles)...)
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package reims
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -61,3 +62,41 @@ func TestParseShowRedactsMACAndDetectsInstaller(t *testing.T) {
|
||||
t.Fatalf("expected MAC to be redacted, got %q", d.NetworkSummary)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOfflineCreateTurnsNetworkOff(t *testing.T) {
|
||||
args, err := BuildCreateArgs(CreateOpts{Name: "m1", MacOS: "26.7.3", Offline: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := strings.Join(args, " ")
|
||||
if got != "create m1 --macos 26.7.3 --offline --network false" {
|
||||
t.Fatalf("args = %q", got)
|
||||
}
|
||||
on := true
|
||||
args, _ = BuildCreateArgs(CreateOpts{Name: "m1", MacOS: "26.7.3", Offline: true, Network: &on})
|
||||
if got := strings.Join(args, " "); !strings.HasSuffix(got, "--network true") {
|
||||
t.Fatalf("explicit network kept: %q", got)
|
||||
}
|
||||
args, _ = BuildCreateArgs(CreateOpts{Name: "m1", Installer: `D:\i.img`, Offline: true})
|
||||
if got := strings.Join(args, " "); strings.Contains(got, "--offline") {
|
||||
t.Fatalf("--offline only goes with --macos: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseShowCaptureOffAndInlineSSHPort(t *testing.T) {
|
||||
sample := `macos-tahoe
|
||||
state running, pid 1234
|
||||
cpus 8
|
||||
memory 16G
|
||||
disk disk.qcow2 (qcow2, NVMe)
|
||||
display one, in a window opening at 1920x1080, whose size the guest follows
|
||||
capture off: the windows never capture the mouse or the keyboard
|
||||
network user, mac 52:54:00:3c:ce:59, ssh on 127.0.0.1:2222`
|
||||
d := ParseShow("macos-tahoe", sample)
|
||||
if d.Capture {
|
||||
t.Fatalf("expected Capture=false for 'off: ...', got true")
|
||||
}
|
||||
if d.SSHPort != 2222 {
|
||||
t.Fatalf("expected SSHPort=2222, got %d", d.SSHPort)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//go:build !windows
|
||||
|
||||
package guesttools
|
||||
|
||||
import "sync"
|
||||
|
||||
type OSClipboard struct {
|
||||
mu sync.Mutex
|
||||
text string
|
||||
}
|
||||
|
||||
func (c *OSClipboard) ReadText() (string, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.text, nil
|
||||
}
|
||||
|
||||
func (c *OSClipboard) WriteText(text string) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.text = text
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
//go:build windows
|
||||
|
||||
package guesttools
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
"unicode/utf16"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var (
|
||||
user32 = syscall.NewLazyDLL("user32.dll")
|
||||
procOpenClipboard = user32.NewProc("OpenClipboard")
|
||||
procCloseClipboard = user32.NewProc("CloseClipboard")
|
||||
procEmptyClipboard = user32.NewProc("EmptyClipboard")
|
||||
procGetClipboardData = user32.NewProc("GetClipboardData")
|
||||
procSetClipboardData = user32.NewProc("SetClipboardData")
|
||||
procIsClipboardFormatAvail = user32.NewProc("IsClipboardFormatAvailable")
|
||||
|
||||
kernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||
procGlobalAlloc = kernel32.NewProc("GlobalAlloc")
|
||||
procGlobalFree = kernel32.NewProc("GlobalFree")
|
||||
procGlobalLock = kernel32.NewProc("GlobalLock")
|
||||
procGlobalUnlock = kernel32.NewProc("GlobalUnlock")
|
||||
procGlobalSize = kernel32.NewProc("GlobalSize")
|
||||
procRtlMoveMem = kernel32.NewProc("RtlMoveMemory")
|
||||
)
|
||||
|
||||
const (
|
||||
cfUnicodeText = 13
|
||||
gmemMoveable = 0x0002
|
||||
)
|
||||
|
||||
type OSClipboard struct{}
|
||||
|
||||
func openClipboardWithRetry() error {
|
||||
var lastErr error
|
||||
for i := 0; i < 5; i++ {
|
||||
r, _, err := procOpenClipboard.Call(0)
|
||||
if r != 0 {
|
||||
return nil
|
||||
}
|
||||
lastErr = err
|
||||
time.Sleep(15 * time.Millisecond)
|
||||
}
|
||||
return fmt.Errorf("OpenClipboard: %w", lastErr)
|
||||
}
|
||||
|
||||
// ReadText reads UTF-8 text from the Windows clipboard, normalizing CRLF to LF
|
||||
// for macOS guests. Returns ("", nil) when the clipboard has no text.
|
||||
func (OSClipboard) ReadText() (string, error) {
|
||||
avail, _, _ := procIsClipboardFormatAvail.Call(cfUnicodeText)
|
||||
if avail == 0 {
|
||||
return "", nil
|
||||
}
|
||||
if err := openClipboardWithRetry(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer procCloseClipboard.Call()
|
||||
|
||||
h, _, err := procGetClipboardData.Call(cfUnicodeText)
|
||||
if h == 0 {
|
||||
return "", fmt.Errorf("GetClipboardData: %w", err)
|
||||
}
|
||||
sz, _, _ := procGlobalSize.Call(h)
|
||||
if sz < 2 {
|
||||
return "", nil
|
||||
}
|
||||
ptr, _, err := procGlobalLock.Call(h)
|
||||
if ptr == 0 {
|
||||
return "", fmt.Errorf("GlobalLock: %w", err)
|
||||
}
|
||||
defer procGlobalUnlock.Call(h)
|
||||
|
||||
maxWords := int(sz / 2)
|
||||
if maxWords > MaxClipboardBytes/2 {
|
||||
maxWords = MaxClipboardBytes / 2
|
||||
}
|
||||
words := make([]uint16, maxWords)
|
||||
procRtlMoveMem.Call(uintptr(unsafe.Pointer(&words[0])), ptr, uintptr(maxWords*2))
|
||||
n := 0
|
||||
for n < len(words) && words[n] != 0 {
|
||||
n++
|
||||
}
|
||||
s := string(utf16.Decode(words[:n]))
|
||||
return strings.ReplaceAll(s, "\r\n", "\n"), nil
|
||||
}
|
||||
|
||||
// WriteText writes UTF-8 text to the Windows clipboard as CF_UNICODETEXT
|
||||
// (normalizing bare LF to CRLF for Windows apps).
|
||||
func (OSClipboard) WriteText(text string) error {
|
||||
if len(text) > MaxClipboardBytes {
|
||||
return fmt.Errorf("clipboard payload exceeds %d bytes", MaxClipboardBytes)
|
||||
}
|
||||
norm := strings.ReplaceAll(strings.ReplaceAll(text, "\r\n", "\n"), "\n", "\r\n")
|
||||
u16 := utf16.Encode([]rune(norm))
|
||||
u16 = append(u16, 0)
|
||||
byteLen := uintptr(len(u16) * 2)
|
||||
|
||||
if err := openClipboardWithRetry(); err != nil {
|
||||
return err
|
||||
}
|
||||
defer procCloseClipboard.Call()
|
||||
|
||||
if r, _, err := procEmptyClipboard.Call(); r == 0 {
|
||||
return fmt.Errorf("EmptyClipboard: %w", err)
|
||||
}
|
||||
hMem, _, err := procGlobalAlloc.Call(gmemMoveable, byteLen)
|
||||
if hMem == 0 {
|
||||
return fmt.Errorf("GlobalAlloc: %w", err)
|
||||
}
|
||||
ptr, _, err := procGlobalLock.Call(hMem)
|
||||
if ptr == 0 {
|
||||
procGlobalFree.Call(hMem)
|
||||
return fmt.Errorf("GlobalLock: %w", err)
|
||||
}
|
||||
procRtlMoveMem.Call(ptr, uintptr(unsafe.Pointer(&u16[0])), byteLen)
|
||||
procGlobalUnlock.Call(hMem)
|
||||
|
||||
if r, _, err := procSetClipboardData.Call(cfUnicodeText, hMem); r == 0 {
|
||||
procGlobalFree.Call(hMem)
|
||||
return fmt.Errorf("SetClipboardData: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package guesttools
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
)
|
||||
|
||||
type memClipboard struct {
|
||||
mu sync.Mutex
|
||||
text string
|
||||
}
|
||||
|
||||
func (m *memClipboard) ReadText() (string, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.text, nil
|
||||
}
|
||||
|
||||
func (m *memClipboard) WriteText(s string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.text = s
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestServerAuthClipboardAndSharedFiles(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
vmDir := filepath.Join(tmp, "vm")
|
||||
sharedDir := filepath.Join(tmp, "shared")
|
||||
clip := &memClipboard{text: "hello from windows"}
|
||||
|
||||
srv := NewServer(clip)
|
||||
port, err := srv.Start(-1)
|
||||
if err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
defer srv.Close(context.Background())
|
||||
|
||||
cfg, err := LoadOrCreateVMConfig(vmDir, "macos-tahoe", sharedDir, port)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadOrCreateVMConfig: %v", err)
|
||||
}
|
||||
srv.RegisterVM(cfg)
|
||||
base := fmt.Sprintf("http://127.0.0.1:%d", port)
|
||||
|
||||
// 1. Rejects missing or wrong Bearer token.
|
||||
resp, err := http.Get(base + "/v1/ping")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("unauthenticated ping: got %d, want 401", resp.StatusCode)
|
||||
}
|
||||
|
||||
doReq := func(method, path string, body io.Reader) *http.Response {
|
||||
req, err := http.NewRequest(method, base+path, body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+cfg.Token)
|
||||
r, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// 2. Authenticated ping marks VM connected.
|
||||
r := doReq("GET", "/v1/ping", nil)
|
||||
r.Body.Close()
|
||||
if r.StatusCode != http.StatusOK {
|
||||
t.Fatalf("ping status=%d", r.StatusCode)
|
||||
}
|
||||
if !srv.IsConnected("macos-tahoe", 5*time.Second) {
|
||||
t.Fatalf("expected VM to be marked connected after ping")
|
||||
}
|
||||
|
||||
// 3. Clipboard GET -> 200, then GET with since=<hash> -> 304, then POST updates host clipboard.
|
||||
r = doReq("GET", "/v1/clipboard", nil)
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
h := r.Header.Get("X-Clip-Hash")
|
||||
r.Body.Close()
|
||||
if r.StatusCode != 200 || string(b) != "hello from windows" || h == "" {
|
||||
t.Fatalf("clipboard GET: status=%d body=%q hash=%q", r.StatusCode, string(b), h)
|
||||
}
|
||||
r = doReq("GET", "/v1/clipboard?since="+h, nil)
|
||||
r.Body.Close()
|
||||
if r.StatusCode != http.StatusNotModified {
|
||||
t.Fatalf("clipboard unchanged: status=%d, want 304", r.StatusCode)
|
||||
}
|
||||
r = doReq("POST", "/v1/clipboard", strings.NewReader("你好 macOS"))
|
||||
r.Body.Close()
|
||||
if r.StatusCode != 200 {
|
||||
t.Fatalf("clipboard POST: status=%d", r.StatusCode)
|
||||
}
|
||||
// Reject invalid non-UTF-8 (e.g. raw GBK bytes) instead of corrupting host clipboard.
|
||||
r = doReq("POST", "/v1/clipboard", bytes.NewReader([]byte{0xB6, 0xE0, 0xBA, 0xCB}))
|
||||
r.Body.Close()
|
||||
if r.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("non-UTF-8 clipboard POST: got %d, want 400", r.StatusCode)
|
||||
}
|
||||
if got, _ := clip.ReadText(); got != "你好 macOS" {
|
||||
t.Fatalf("host clipboard = %q, want %q", got, "你好 macOS")
|
||||
}
|
||||
|
||||
// 4. Shared files: reject path traversal, allow upload & download with UTF-8/spaces.
|
||||
r = doReq("GET", "/v1/file?path="+url.QueryEscape("../secret.txt"), nil)
|
||||
r.Body.Close()
|
||||
if r.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("traversal must be 400, got %d", r.StatusCode)
|
||||
}
|
||||
r = doReq("PUT", "/v1/file?path="+url.QueryEscape("notes/测试 file.txt")+"&mtime=1700000100", bytes.NewBufferString("shared payload"))
|
||||
r.Body.Close()
|
||||
if r.StatusCode != http.StatusOK {
|
||||
t.Fatalf("file PUT status=%d", r.StatusCode)
|
||||
}
|
||||
r = doReq("GET", "/v1/files", nil)
|
||||
listBytes, _ := io.ReadAll(r.Body)
|
||||
r.Body.Close()
|
||||
if !strings.Contains(string(listBytes), "1700000100\t14\tnotes/测试 file.txt") {
|
||||
t.Fatalf("unexpected /v1/files listing:\n%s", string(listBytes))
|
||||
}
|
||||
r = doReq("GET", "/v1/file?path="+url.QueryEscape("notes/测试 file.txt"), nil)
|
||||
dlBytes, _ := io.ReadAll(r.Body)
|
||||
r.Body.Close()
|
||||
if r.StatusCode != 200 || string(dlBytes) != "shared payload" {
|
||||
t.Fatalf("file GET: status=%d body=%q", r.StatusCode, string(dlBytes))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildToolsDiskImageAndScriptSyntax(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
imgPath := filepath.Join(tmp, "reims-tools.img")
|
||||
cfg := VMConfig{VMName: "macos-tahoe", Token: strings.Repeat("ab", 32), Port: 19847}
|
||||
if err := BuildToolsDiskImage(imgPath, cfg); err != nil {
|
||||
t.Fatalf("BuildToolsDiskImage: %v", err)
|
||||
}
|
||||
f, err := os.Open(imgPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
for _, name := range []string{"config", "guest-tools.sh", "Install-Reims-Tools.command", "Uninstall-Reims-Tools.command"} {
|
||||
if _, sz, err := installer.FindFileInHFSPlusImage(f, name); err != nil || sz == 0 {
|
||||
t.Fatalf("missing %s in REIMSTOOLS image: err=%v size=%d", name, err, sz)
|
||||
}
|
||||
}
|
||||
|
||||
// Syntax check every generated POSIX script if sh is available.
|
||||
shBin, err := exec.LookPath("sh")
|
||||
if err != nil {
|
||||
for _, cand := range []string{`C:\Program Files\Git\bin\sh.exe`, `D:\DevTools\msys64\usr\bin\sh.exe`} {
|
||||
if _, serr := os.Stat(cand); serr == nil {
|
||||
shBin = cand
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if shBin == "" {
|
||||
return
|
||||
}
|
||||
for name, content := range map[string][]byte{
|
||||
"guest-tools.sh": GuestAgentScript(),
|
||||
"Install-Reims-Tools.command": GuestInstallScript(),
|
||||
"Uninstall-Reims-Tools.command": GuestUninstallScript(),
|
||||
} {
|
||||
p := filepath.Join(tmp, name)
|
||||
if err := os.WriteFile(p, content, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out, err := exec.Command(shBin, "-n", p).CombinedOutput(); err != nil {
|
||||
t.Fatalf("sh -n %s failed: %v\n%s", name, err, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
package guesttools
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
)
|
||||
|
||||
const (
|
||||
ToolsVolumeName = "REIMSTOOLS"
|
||||
InstallCommand = "sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command"
|
||||
)
|
||||
|
||||
// BuildToolsDiskImage creates a small read-only HFS+ disk image ("REIMSTOOLS")
|
||||
// containing the per-VM Bearer token config, POSIX guest agent script (two-way
|
||||
// clipboard + ReimsShare folder sync), and one-click install/uninstall commands.
|
||||
func BuildToolsDiskImage(outPath string, cfg VMConfig) error {
|
||||
if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
confBytes := []byte(fmt.Sprintf("REIMS_HOST_URL=\"http://10.0.2.2:%d\"\nREIMS_TOKEN=\"%s\"\nREIMS_VM=\"%s\"\n",
|
||||
cfg.Port, cfg.Token, cfg.VMName))
|
||||
agentBytes := GuestAgentScript()
|
||||
installBytes := GuestInstallScript()
|
||||
uninstallBytes := GuestUninstallScript()
|
||||
|
||||
files := []installer.HFSFile{
|
||||
{
|
||||
Name: "config",
|
||||
Mode: 0o100644,
|
||||
Size: int64(len(confBytes)),
|
||||
Open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(confBytes)), nil },
|
||||
},
|
||||
{
|
||||
Name: "guest-tools.sh",
|
||||
Mode: 0o100755,
|
||||
Size: int64(len(agentBytes)),
|
||||
Open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(agentBytes)), nil },
|
||||
},
|
||||
{
|
||||
Name: "Install-Reims-Tools.command",
|
||||
Mode: 0o100755,
|
||||
Size: int64(len(installBytes)),
|
||||
Open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(installBytes)), nil },
|
||||
},
|
||||
{
|
||||
Name: "Uninstall-Reims-Tools.command",
|
||||
Mode: 0o100755,
|
||||
Size: int64(len(uninstallBytes)),
|
||||
Open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(uninstallBytes)), nil },
|
||||
},
|
||||
}
|
||||
return installer.BuildHFSPlusDiskImage(outPath, ToolsVolumeName, files)
|
||||
}
|
||||
|
||||
// GuestAgentScript returns the stock-macOS POSIX shell daemon (no Xcode or
|
||||
// Python required) that syncs UTF-8 clipboard text every 1s and ~/ReimsShare
|
||||
// files every 3s over the token-authenticated host bridge.
|
||||
func GuestAgentScript() []byte {
|
||||
return []byte(`#!/bin/sh
|
||||
# Reims Guest Tools: token-authenticated two-way clipboard & ReimsShare sync.
|
||||
set -u
|
||||
|
||||
# Force UTF-8 for macOS pbpaste/pbcopy under launchd (otherwise Simplified
|
||||
# Chinese macOS defaults __CF_USER_TEXT_ENCODING to GB18030/GBK, causing
|
||||
# mojibake when decoded as UTF-8 on Windows).
|
||||
export LANG="en_US.UTF-8"
|
||||
export LC_ALL="en_US.UTF-8"
|
||||
export __CF_USER_TEXT_ENCODING="0x$(printf '%X' "$(id -u)"):0x08000100:0x08000100"
|
||||
|
||||
APP_DIR="$HOME/Library/Application Support/ReimsGuestTools"
|
||||
CONF="$APP_DIR/config"
|
||||
SHARE="$HOME/ReimsShare"
|
||||
TMP_DIR="$APP_DIR/tmp"
|
||||
mkdir -p "$APP_DIR" "$SHARE" "$TMP_DIR"
|
||||
[ -e "$HOME/Desktop/ReimsShare" ] || ln -s "$SHARE" "$HOME/Desktop/ReimsShare" 2>/dev/null || true
|
||||
|
||||
load_conf() {
|
||||
if [ -f "/Volumes/REIMSTOOLS/config" ]; then
|
||||
cp "/Volumes/REIMSTOOLS/config" "$CONF" 2>/dev/null || true
|
||||
chmod 600 "$CONF" 2>/dev/null || true
|
||||
fi
|
||||
if [ -f "$CONF" ]; then
|
||||
# shellcheck disable=SC1090
|
||||
. "$CONF"
|
||||
fi
|
||||
}
|
||||
|
||||
REIMS_HOST_URL=""
|
||||
REIMS_TOKEN=""
|
||||
load_conf
|
||||
|
||||
urlencode() {
|
||||
# Percent-encodes UTF-8 paths cleanly with stock macOS tools (LC_ALL=C awk).
|
||||
LC_ALL=C awk 'BEGIN {
|
||||
for (i = 0; i < 256; i++) ord[sprintf("%c", i)] = i
|
||||
s = ARGV[1]
|
||||
out = ""
|
||||
for (i = 1; i <= length(s); i++) {
|
||||
c = substr(s, i, 1)
|
||||
if (c ~ /[A-Za-z0-9._~\/-]/) out = out c
|
||||
else out = out sprintf("%%%02X", ord[c])
|
||||
}
|
||||
printf "%s", out
|
||||
}' "$1"
|
||||
}
|
||||
|
||||
hash_file() {
|
||||
shasum -a 256 "$1" 2>/dev/null | awk '{print $1}'
|
||||
}
|
||||
|
||||
last_clip_hash=""
|
||||
tick=0
|
||||
TAB=$(printf '\t')
|
||||
|
||||
sync_clipboard() {
|
||||
[ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0
|
||||
clip_in="$TMP_DIR/clip_in"
|
||||
clip_out="$TMP_DIR/clip_out"
|
||||
hdr_out="$TMP_DIR/clip_hdr"
|
||||
|
||||
pbpaste >"$clip_in" 2>/dev/null || : >"$clip_in"
|
||||
cur_hash=$(hash_file "$clip_in")
|
||||
|
||||
if [ -n "$last_clip_hash" ] && [ "$cur_hash" != "$last_clip_hash" ]; then
|
||||
if curl -fsS -m 3 -X POST \
|
||||
-H "Authorization: Bearer $REIMS_TOKEN" \
|
||||
-H "Content-Type: text/plain; charset=utf-8" \
|
||||
--data-binary "@$clip_in" \
|
||||
"$REIMS_HOST_URL/v1/clipboard" >/dev/null 2>&1; then
|
||||
last_clip_hash="$cur_hash"
|
||||
fi
|
||||
return 0
|
||||
fi
|
||||
|
||||
code=$(curl -sS -m 3 -D "$hdr_out" -o "$clip_out" -w '%{http_code}' \
|
||||
-H "Authorization: Bearer $REIMS_TOKEN" \
|
||||
"$REIMS_HOST_URL/v1/clipboard?since=$last_clip_hash" 2>/dev/null || echo "000")
|
||||
if [ "$code" = "200" ]; then
|
||||
new_hash=$(awk 'tolower($1)=="x-clip-hash:" {gsub(/\r/,"",$2); print $2; exit}' "$hdr_out")
|
||||
if [ -n "$new_hash" ] && [ "$new_hash" != "$cur_hash" ]; then
|
||||
pbcopy <"$clip_out" 2>/dev/null || true
|
||||
last_clip_hash="$new_hash"
|
||||
elif [ -n "$new_hash" ]; then
|
||||
last_clip_hash="$new_hash"
|
||||
fi
|
||||
elif [ "$code" = "304" ] && [ -z "$last_clip_hash" ]; then
|
||||
last_clip_hash="$cur_hash"
|
||||
fi
|
||||
}
|
||||
|
||||
sync_files() {
|
||||
[ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0
|
||||
remote_list="$TMP_DIR/remote_files.tsv"
|
||||
if ! curl -fsS -m 5 \
|
||||
-H "Authorization: Bearer $REIMS_TOKEN" \
|
||||
"$REIMS_HOST_URL/v1/files" -o "$remote_list" 2>/dev/null; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
# 1. Host -> Guest (download new or strictly newer files)
|
||||
while IFS="$TAB" read -r rmtime rsize rrel; do
|
||||
[ -n "$rrel" ] || continue
|
||||
local_path="$SHARE/$rrel"
|
||||
need_dl=0
|
||||
if [ ! -f "$local_path" ]; then
|
||||
need_dl=1
|
||||
else
|
||||
lmtime=$(stat -f '%m' "$local_path" 2>/dev/null || echo 0)
|
||||
if [ "$rmtime" -gt $((lmtime + 2)) ]; then
|
||||
need_dl=1
|
||||
fi
|
||||
fi
|
||||
if [ "$need_dl" -eq 1 ]; then
|
||||
mkdir -p "$(dirname "$local_path")"
|
||||
enc=$(urlencode "$rrel")
|
||||
dl_tmp="$TMP_DIR/dl.part"
|
||||
if curl -fsS -m 60 \
|
||||
-H "Authorization: Bearer $REIMS_TOKEN" \
|
||||
"$REIMS_HOST_URL/v1/file?path=$enc" -o "$dl_tmp" 2>/dev/null; then
|
||||
mv -f "$dl_tmp" "$local_path"
|
||||
touch -d "@$rmtime" "$local_path" 2>/dev/null || true
|
||||
else
|
||||
rm -f "$dl_tmp"
|
||||
fi
|
||||
fi
|
||||
done <"$remote_list"
|
||||
|
||||
# 2. Guest -> Host (upload new or strictly newer files)
|
||||
find "$SHARE" -type f ! -name '.*' ! -path '*/.*' 2>/dev/null | while IFS= read -r fpath; do
|
||||
rel=${fpath#"$SHARE/"}
|
||||
[ -n "$rel" ] || continue
|
||||
lmtime=$(stat -f '%m' "$fpath" 2>/dev/null || echo 0)
|
||||
lsize=$(stat -f '%z' "$fpath" 2>/dev/null || echo 0)
|
||||
[ "$lsize" -le 268435456 ] || continue
|
||||
rmtime=$(awk -F '\t' -v p="$rel" '$3==p {print $1; exit}' "$remote_list")
|
||||
[ -n "$rmtime" ] || rmtime=0
|
||||
if [ "$lmtime" -gt $((rmtime + 2)) ]; then
|
||||
enc=$(urlencode "$rel")
|
||||
curl -fsS -m 60 -X PUT \
|
||||
-H "Authorization: Bearer $REIMS_TOKEN" \
|
||||
--data-binary "@$fpath" \
|
||||
"$REIMS_HOST_URL/v1/file?path=$enc&mtime=$lmtime" >/dev/null 2>&1 || true
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
while :; do
|
||||
if [ $((tick % 10)) -eq 0 ]; then
|
||||
load_conf
|
||||
fi
|
||||
sync_clipboard
|
||||
if [ $((tick % 3)) -eq 0 ]; then
|
||||
sync_files
|
||||
fi
|
||||
tick=$((tick + 1))
|
||||
sleep 1
|
||||
done
|
||||
`)
|
||||
}
|
||||
|
||||
// GuestInstallScript returns the double-clickable / one-command installer script
|
||||
// placed on /Volumes/REIMSTOOLS.
|
||||
func GuestInstallScript() []byte {
|
||||
return []byte(`#!/bin/sh
|
||||
set -e
|
||||
|
||||
SRC="/Volumes/REIMSTOOLS"
|
||||
APP_DIR="$HOME/Library/Application Support/ReimsGuestTools"
|
||||
PLIST="$HOME/Library/LaunchAgents/com.reimsgo.guest-tools.plist"
|
||||
SHARE="$HOME/ReimsShare"
|
||||
|
||||
if [ ! -f "$SRC/config" ] || [ ! -f "$SRC/guest-tools.sh" ]; then
|
||||
echo "REIMSTOOLS volume not found at $SRC" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "$APP_DIR" "$HOME/Library/LaunchAgents" "$SHARE"
|
||||
cp "$SRC/config" "$APP_DIR/config"
|
||||
cp "$SRC/guest-tools.sh" "$APP_DIR/guest-tools.sh"
|
||||
chmod 600 "$APP_DIR/config"
|
||||
chmod 755 "$APP_DIR/guest-tools.sh"
|
||||
[ -e "$HOME/Desktop/ReimsShare" ] || ln -s "$SHARE" "$HOME/Desktop/ReimsShare" 2>/dev/null || true
|
||||
|
||||
uid=$(id -u)
|
||||
cf_enc="0x$(printf '%X' "$uid"):0x08000100:0x08000100"
|
||||
|
||||
cat >"$PLIST" <<EOF
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key>
|
||||
<string>com.reimsgo.guest-tools</string>
|
||||
<key>EnvironmentVariables</key>
|
||||
<dict>
|
||||
<key>LANG</key>
|
||||
<string>en_US.UTF-8</string>
|
||||
<key>LC_ALL</key>
|
||||
<string>en_US.UTF-8</string>
|
||||
<key>__CF_USER_TEXT_ENCODING</key>
|
||||
<string>$cf_enc</string>
|
||||
</dict>
|
||||
<key>ProgramArguments</key>
|
||||
<array>
|
||||
<string>/bin/sh</string>
|
||||
<string>$APP_DIR/guest-tools.sh</string>
|
||||
</array>
|
||||
<key>RunAtLoad</key>
|
||||
<true/>
|
||||
<key>KeepAlive</key>
|
||||
<true/>
|
||||
<key>StandardOutPath</key>
|
||||
<string>$APP_DIR/agent.log</string>
|
||||
<key>StandardErrorPath</key>
|
||||
<string>$APP_DIR/agent.log</string>
|
||||
</dict>
|
||||
</plist>
|
||||
EOF
|
||||
|
||||
launchctl bootout "gui/$uid" "$PLIST" 2>/dev/null || launchctl unload "$PLIST" 2>/dev/null || true
|
||||
launchctl bootstrap "gui/$uid" "$PLIST" 2>/dev/null || launchctl load -w "$PLIST"
|
||||
|
||||
# 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 installed and connected!"
|
||||
echo "Shared folder: ~/Desktop/ReimsShare (synced with Windows host)"
|
||||
else
|
||||
echo "Reims Guest Tools installed (waiting for Windows host bridge at $REIMS_HOST_URL)..."
|
||||
fi
|
||||
`)
|
||||
}
|
||||
|
||||
// GuestUninstallScript cleanly removes the LaunchAgent while preserving user files.
|
||||
func GuestUninstallScript() []byte {
|
||||
return []byte(`#!/bin/sh
|
||||
set -e
|
||||
APP_DIR="$HOME/Library/Application Support/ReimsGuestTools"
|
||||
PLIST="$HOME/Library/LaunchAgents/com.reimsgo.guest-tools.plist"
|
||||
uid=$(id -u)
|
||||
launchctl bootout "gui/$uid" "$PLIST" 2>/dev/null || launchctl unload "$PLIST" 2>/dev/null || true
|
||||
rm -f "$PLIST"
|
||||
rm -rf "$APP_DIR"
|
||||
echo "Reims Guest Tools uninstalled. Your ~/ReimsShare files were kept."
|
||||
`)
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
package guesttools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultPort = 19847
|
||||
MaxPort = 19860
|
||||
MaxClipboardBytes = 4 << 20 // 4 MiB
|
||||
MaxUploadBytes = 256 << 20 // 256 MiB
|
||||
MaxSharedFiles = 2000
|
||||
MaxSharedDepth = 8
|
||||
ConfigFileName = ".reims-go-tools.json"
|
||||
)
|
||||
|
||||
// Clipboard abstracts host OS clipboard reads/writes for testing.
|
||||
type Clipboard interface {
|
||||
ReadText() (string, error)
|
||||
WriteText(text string) error
|
||||
}
|
||||
|
||||
// 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"`
|
||||
}
|
||||
|
||||
// LoadOrCreateVMConfig loads an existing per-VM Guest Tools config or generates
|
||||
// a fresh 256-bit cryptographically random Bearer token.
|
||||
func LoadOrCreateVMConfig(vmDir, vmName, sharedDir string, port int) (VMConfig, error) {
|
||||
cfgPath := filepath.Join(vmDir, ConfigFileName)
|
||||
var cfg VMConfig
|
||||
if b, err := os.ReadFile(cfgPath); err == nil {
|
||||
if json.Unmarshal(b, &cfg) == nil && len(cfg.Token) >= 32 {
|
||||
cfg.VMName = vmName
|
||||
if sharedDir != "" {
|
||||
cfg.SharedDir = sharedDir
|
||||
}
|
||||
if port > 0 {
|
||||
cfg.Port = port
|
||||
}
|
||||
_ = SaveVMConfig(vmDir, cfg)
|
||||
return cfg, nil
|
||||
}
|
||||
}
|
||||
var raw [32]byte
|
||||
if _, err := rand.Read(raw[:]); err != nil {
|
||||
return VMConfig{}, fmt.Errorf("generate guest tools token: %w", err)
|
||||
}
|
||||
if port <= 0 {
|
||||
port = DefaultPort
|
||||
}
|
||||
cfg = VMConfig{
|
||||
VMName: vmName,
|
||||
Token: hex.EncodeToString(raw[:]),
|
||||
Port: port,
|
||||
SharedDir: sharedDir,
|
||||
}
|
||||
if err := SaveVMConfig(vmDir, cfg); err != nil {
|
||||
return VMConfig{}, err
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// ReadVMConfig returns the saved Guest Tools config for a VM if configured.
|
||||
func ReadVMConfig(vmDir string) (VMConfig, bool) {
|
||||
if vmDir == "" {
|
||||
return VMConfig{}, false
|
||||
}
|
||||
b, err := os.ReadFile(filepath.Join(vmDir, ConfigFileName))
|
||||
if err != nil {
|
||||
return VMConfig{}, false
|
||||
}
|
||||
var cfg VMConfig
|
||||
if json.Unmarshal(b, &cfg) != nil || len(cfg.Token) < 32 {
|
||||
return VMConfig{}, false
|
||||
}
|
||||
return cfg, true
|
||||
}
|
||||
|
||||
// SaveVMConfig persists cfg with restricted permissions.
|
||||
func SaveVMConfig(vmDir string, cfg VMConfig) error {
|
||||
if err := os.MkdirAll(vmDir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
b, err := json.MarshalIndent(cfg, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(filepath.Join(vmDir, ConfigFileName), b, 0o600)
|
||||
}
|
||||
|
||||
type registeredVM struct {
|
||||
name string
|
||||
token string
|
||||
sharedDir string
|
||||
lastSeen time.Time
|
||||
}
|
||||
|
||||
// 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
|
||||
port int
|
||||
listener net.Listener
|
||||
httpSrv *http.Server
|
||||
}
|
||||
|
||||
// NewServer constructs a Guest Tools HTTP bridge. Pass nil for clip to use the
|
||||
// host OS clipboard.
|
||||
func NewServer(clip Clipboard) *Server {
|
||||
if clip == nil {
|
||||
clip = &OSClipboard{}
|
||||
}
|
||||
return &Server{
|
||||
clip: clip,
|
||||
vms: make(map[string]*registeredVM),
|
||||
}
|
||||
}
|
||||
|
||||
// Start binds the bridge on 127.0.0.1 starting from preferredPort (default
|
||||
// 19847..19860, or ephemeral 0 when preferredPort == -1 for tests).
|
||||
func (s *Server) Start(preferredPort int) (int, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.listener != nil {
|
||||
return s.port, nil
|
||||
}
|
||||
var ln net.Listener
|
||||
var err error
|
||||
if preferredPort < 0 {
|
||||
ln, err = net.Listen("tcp", "127.0.0.1:0")
|
||||
} else {
|
||||
start := preferredPort
|
||||
if start == 0 {
|
||||
start = DefaultPort
|
||||
}
|
||||
for p := start; p <= MaxPort; p++ {
|
||||
ln, err = net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", p))
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
if ln == nil {
|
||||
ln, err = net.Listen("tcp", "127.0.0.1:0")
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("listen guest tools server: %w", err)
|
||||
}
|
||||
tcpAddr, ok := ln.Addr().(*net.TCPAddr)
|
||||
if !ok {
|
||||
_ = ln.Close()
|
||||
return 0, errors.New("unexpected listener addr")
|
||||
}
|
||||
s.listener = ln
|
||||
s.port = tcpAddr.Port
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/v1/ping", s.handlePing)
|
||||
mux.HandleFunc("/v1/clipboard", s.handleClipboard)
|
||||
mux.HandleFunc("/v1/files", s.handleListFiles)
|
||||
mux.HandleFunc("/v1/file", s.handleFile)
|
||||
s.httpSrv = &http.Server{
|
||||
Handler: mux,
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
}
|
||||
go func() {
|
||||
_ = s.httpSrv.Serve(ln)
|
||||
}()
|
||||
return s.port, nil
|
||||
}
|
||||
|
||||
func (s *Server) Port() int {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.port
|
||||
}
|
||||
|
||||
func (s *Server) Close(ctx context.Context) error {
|
||||
s.mu.Lock()
|
||||
srv := s.httpSrv
|
||||
s.httpSrv = nil
|
||||
s.listener = nil
|
||||
s.mu.Unlock()
|
||||
if srv == nil {
|
||||
return nil
|
||||
}
|
||||
return srv.Shutdown(ctx)
|
||||
}
|
||||
|
||||
// RegisterVM registers or updates a VM's Bearer token and shared directory.
|
||||
func (s *Server) RegisterVM(cfg VMConfig) {
|
||||
if cfg.VMName == "" || cfg.Token == "" {
|
||||
return
|
||||
}
|
||||
if cfg.SharedDir != "" {
|
||||
_ = os.MkdirAll(cfg.SharedDir, 0o755)
|
||||
}
|
||||
s.mu.Lock()
|
||||
prev := s.vms[cfg.VMName]
|
||||
var lastSeen time.Time
|
||||
if prev != nil {
|
||||
lastSeen = prev.lastSeen
|
||||
}
|
||||
s.vms[cfg.VMName] = ®isteredVM{
|
||||
name: cfg.VMName,
|
||||
token: cfg.Token,
|
||||
sharedDir: cfg.SharedDir,
|
||||
lastSeen: lastSeen,
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// IsConnected reports whether the guest agent has authenticated within maxAge.
|
||||
func (s *Server) IsConnected(vmName string, maxAge time.Duration) bool {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
vm := s.vms[vmName]
|
||||
if vm == nil || vm.lastSeen.IsZero() {
|
||||
return false
|
||||
}
|
||||
return time.Since(vm.lastSeen) <= maxAge
|
||||
}
|
||||
|
||||
func (s *Server) authenticate(r *http.Request) *registeredVM {
|
||||
auth := strings.TrimSpace(r.Header.Get("Authorization"))
|
||||
const prefix = "Bearer "
|
||||
if !strings.HasPrefix(auth, prefix) {
|
||||
return nil
|
||||
}
|
||||
tok := strings.TrimSpace(auth[len(prefix):])
|
||||
if tok == "" {
|
||||
return nil
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for _, vm := range s.vms {
|
||||
if len(vm.token) == len(tok) && subtle.ConstantTimeCompare([]byte(vm.token), []byte(tok)) == 1 {
|
||||
vm.lastSeen = time.Now()
|
||||
cp := *vm
|
||||
return &cp
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func textHash(s string) string {
|
||||
sum := sha256.Sum256([]byte(s))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (s *Server) handlePing(w http.ResponseWriter, r *http.Request) {
|
||||
vm := s.authenticate(r)
|
||||
if vm == nil {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "vm": vm.name})
|
||||
}
|
||||
|
||||
func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) {
|
||||
if s.authenticate(r) == nil {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
text, err := s.clip.ReadText()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
h := textHash(text)
|
||||
w.Header().Set("X-Clip-Hash", h)
|
||||
if r.URL.Query().Get("since") == h {
|
||||
w.WriteHeader(http.StatusNotModified)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
_, _ = io.WriteString(w, text)
|
||||
case http.MethodPost, http.MethodPut:
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, MaxClipboardBytes+1))
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if len(body) > MaxClipboardBytes {
|
||||
http.Error(w, "clipboard too large", http.StatusRequestEntityTooLarge)
|
||||
return
|
||||
}
|
||||
if !utf8.Valid(body) {
|
||||
http.Error(w, "clipboard payload must be valid UTF-8", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
text := strings.ReplaceAll(string(body), "\r\n", "\n")
|
||||
h := textHash(text)
|
||||
if cur, err := s.clip.ReadText(); err != nil || textHash(cur) != h {
|
||||
if err := s.clip.WriteText(text); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
w.Header().Set("X-Clip-Hash", h)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
func isIgnoredSharedName(name string) bool {
|
||||
return name == "" || strings.HasPrefix(name, ".") || strings.HasPrefix(name, "._")
|
||||
}
|
||||
|
||||
// resolveSharedPath validates a relative slash path and ensures the resulting
|
||||
// path stays strictly inside rootDir (no .., absolute paths, drive letters, or
|
||||
// symlink escapes).
|
||||
func resolveSharedPath(rootDir, rel string) (string, error) {
|
||||
if rootDir == "" {
|
||||
return "", errors.New("shared directory not configured")
|
||||
}
|
||||
if strings.ContainsRune(rel, 0) || strings.Contains(rel, `\`) {
|
||||
return "", errors.New("invalid path")
|
||||
}
|
||||
trimmed := strings.TrimSpace(rel)
|
||||
if trimmed == "" || strings.HasPrefix(trimmed, "/") {
|
||||
return "", errors.New("invalid relative path")
|
||||
}
|
||||
for _, rawSeg := range strings.Split(trimmed, "/") {
|
||||
if rawSeg == ".." || rawSeg == "." {
|
||||
return "", errors.New("path traversal not allowed")
|
||||
}
|
||||
}
|
||||
clean := path.Clean("/" + trimmed)
|
||||
clean = strings.TrimPrefix(clean, "/")
|
||||
if clean == "" || clean == "." || strings.HasPrefix(clean, "..") {
|
||||
return "", errors.New("invalid relative path")
|
||||
}
|
||||
parts := strings.Split(clean, "/")
|
||||
if len(parts) > MaxSharedDepth {
|
||||
return "", errors.New("path too deep")
|
||||
}
|
||||
for _, seg := range parts {
|
||||
if seg == "" || seg == "." || seg == ".." || strings.ContainsAny(seg, `:\<>|"?*`) || isIgnoredSharedName(seg) {
|
||||
return "", errors.New("invalid path segment")
|
||||
}
|
||||
}
|
||||
rootAbs, err := filepath.Abs(rootDir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
full := filepath.Join(append([]string{rootAbs}, parts...)...)
|
||||
relBack, err := filepath.Rel(rootAbs, full)
|
||||
if err != nil || relBack == "." || strings.HasPrefix(relBack, "..") || filepath.IsAbs(relBack) {
|
||||
return "", errors.New("path escapes shared root")
|
||||
}
|
||||
return full, nil
|
||||
}
|
||||
|
||||
func (s *Server) handleListFiles(w http.ResponseWriter, r *http.Request) {
|
||||
vm := s.authenticate(r)
|
||||
if vm == nil {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
if vm.sharedDir == "" {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
if err := os.MkdirAll(vm.sharedDir, 0o755); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
rootAbs, err := filepath.Abs(vm.sharedDir)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
type entry struct {
|
||||
mtime int64
|
||||
size int64
|
||||
rel string
|
||||
}
|
||||
var list []entry
|
||||
_ = filepath.WalkDir(rootAbs, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if p == rootAbs {
|
||||
return nil
|
||||
}
|
||||
name := d.Name()
|
||||
if isIgnoredSharedName(name) {
|
||||
if d.IsDir() {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if d.Type()&os.ModeSymlink != 0 {
|
||||
if d.IsDir() {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
rel, err := filepath.Rel(rootAbs, p)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
slash := filepath.ToSlash(rel)
|
||||
if strings.Count(slash, "/")+1 > MaxSharedDepth {
|
||||
if d.IsDir() {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
info, err := d.Info()
|
||||
if err != nil || !info.Mode().IsRegular() || info.Size() > MaxUploadBytes {
|
||||
return nil
|
||||
}
|
||||
if len(list) >= MaxSharedFiles {
|
||||
return fs.SkipAll
|
||||
}
|
||||
list = append(list, entry{mtime: info.ModTime().Unix(), size: info.Size(), rel: slash})
|
||||
return nil
|
||||
})
|
||||
sort.Slice(list, func(i, j int) bool { return list[i].rel < list[j].rel })
|
||||
w.Header().Set("Content-Type", "text/tab-separated-values; charset=utf-8")
|
||||
for _, e := range list {
|
||||
_, _ = fmt.Fprintf(w, "%d\t%d\t%s\n", e.mtime, e.size, e.rel)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleFile(w http.ResponseWriter, r *http.Request) {
|
||||
vm := s.authenticate(r)
|
||||
if vm == nil {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
rel := r.URL.Query().Get("path")
|
||||
full, err := resolveSharedPath(vm.sharedDir, rel)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
info, err := os.Lstat(full)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
http.Error(w, "not a regular file", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
f, err := os.Open(full)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
w.Header().Set("X-File-Mtime", strconv.FormatInt(info.ModTime().Unix(), 10))
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10))
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
_, _ = io.Copy(w, f)
|
||||
case http.MethodPut, http.MethodPost:
|
||||
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
tmp, err := os.CreateTemp(filepath.Dir(full), ".reims-upload-*")
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
tmpName := tmp.Name()
|
||||
n, copyErr := io.Copy(tmp, io.LimitReader(r.Body, MaxUploadBytes+1))
|
||||
closeErr := tmp.Close()
|
||||
if copyErr != nil || closeErr != nil || n > MaxUploadBytes {
|
||||
_ = os.Remove(tmpName)
|
||||
if n > MaxUploadBytes {
|
||||
http.Error(w, "file exceeds 256 MiB limit", http.StatusRequestEntityTooLarge)
|
||||
return
|
||||
}
|
||||
http.Error(w, "write failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if mtimeStr := r.URL.Query().Get("mtime"); mtimeStr != "" {
|
||||
if ts, perr := strconv.ParseInt(mtimeStr, 10, 64); perr == nil && ts > 0 {
|
||||
t := time.Unix(ts, 0)
|
||||
_ = os.Chtimes(tmpName, t, t)
|
||||
}
|
||||
}
|
||||
if err := os.Rename(tmpName, full); err != nil {
|
||||
_ = os.Remove(tmpName)
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
//go:build !windows
|
||||
|
||||
package host
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// 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"`
|
||||
}
|
||||
|
||||
// ListDrives returns the home directory's volume on dev/preview hosts.
|
||||
func ListDrives() []Drive {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
free, _ := FreeGB(home)
|
||||
return []Drive{{Root: home, FreeGB: free, System: true}}
|
||||
}
|
||||
|
||||
// FreeGB is the free space on the volume holding path.
|
||||
func FreeGB(path string) (float64, bool) {
|
||||
var st syscall.Statfs_t
|
||||
if err := syscall.Statfs(path, &st); err != nil {
|
||||
return 0, false
|
||||
}
|
||||
return float64(st.Bavail) * float64(st.Bsize) / (1 << 30), true
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
//go:build windows
|
||||
|
||||
package host
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
var (
|
||||
procGetLogicalDrives = kernel32.NewProc("GetLogicalDrives")
|
||||
procGetDriveTypeW = kernel32.NewProc("GetDriveTypeW")
|
||||
)
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
// ListDrives returns local fixed drives (no removable, network or optical).
|
||||
func ListDrives() []Drive {
|
||||
mask, _, _ := procGetLogicalDrives.Call()
|
||||
sys := strings.ToUpper(strings.TrimSuffix(os.Getenv("SystemDrive"), `\`))
|
||||
if sys == "" {
|
||||
sys = "C:"
|
||||
}
|
||||
var out []Drive
|
||||
for i := 0; i < 26; i++ {
|
||||
if mask&(1<<uint(i)) == 0 {
|
||||
continue
|
||||
}
|
||||
root := string(rune('A'+i)) + `:\`
|
||||
p, err := syscall.UTF16PtrFromString(root)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
t, _, _ := procGetDriveTypeW.Call(uintptr(unsafe.Pointer(p)))
|
||||
if t != driveFixed {
|
||||
continue
|
||||
}
|
||||
free, ok := probeFreeDiskGB(root)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out = append(out, Drive{
|
||||
Root: root,
|
||||
FreeGB: free,
|
||||
System: strings.EqualFold(root[:2], sys),
|
||||
External: isUSB(root[:2]),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// isUSB asks the volume's storage device for its bus type
|
||||
// (IOCTL_STORAGE_QUERY_PROPERTY, StorageDeviceProperty). Opening with no
|
||||
// access rights needs no elevation.
|
||||
func isUSB(drive string) bool {
|
||||
path, err := windows.UTF16PtrFromString(`\\.\` + drive)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
h, err := windows.CreateFile(path, 0, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, 0, 0)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer windows.CloseHandle(h)
|
||||
|
||||
const ioctlStorageQueryProperty = 0x002D1400
|
||||
const busTypeUSB = 7
|
||||
// STORAGE_PROPERTY_QUERY{PropertyId: StorageDeviceProperty(0), QueryType: PropertyStandardQuery(0)}
|
||||
query := make([]byte, 12)
|
||||
out := make([]byte, 1024)
|
||||
var n uint32
|
||||
if err := windows.DeviceIoControl(h, ioctlStorageQueryProperty, &query[0], uint32(len(query)), &out[0], uint32(len(out)), &n, nil); err != nil {
|
||||
return false
|
||||
}
|
||||
// STORAGE_DEVICE_DESCRIPTOR.BusType is the DWORD at offset 28.
|
||||
if n < 32 {
|
||||
return false
|
||||
}
|
||||
return binary.LittleEndian.Uint32(out[28:32]) == busTypeUSB
|
||||
}
|
||||
|
||||
// FreeGB is the free space on the volume holding path.
|
||||
func FreeGB(path string) (float64, bool) { return probeFreeDiskGB(path) }
|
||||
@@ -0,0 +1,21 @@
|
||||
//go:build windows
|
||||
|
||||
package host
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestListDrivesFindsTheSystemDrive(t *testing.T) {
|
||||
var sys bool
|
||||
for _, d := range ListDrives() {
|
||||
t.Logf("%s free=%.0fGB system=%v external=%v", d.Root, d.FreeGB, d.System, d.External)
|
||||
if d.System {
|
||||
sys = true
|
||||
if d.External {
|
||||
t.Error("system drive reported as USB")
|
||||
}
|
||||
}
|
||||
}
|
||||
if !sys {
|
||||
t.Fatal("no system drive listed")
|
||||
}
|
||||
}
|
||||
@@ -20,32 +20,53 @@ type GPUInfo struct {
|
||||
type WHPXState string
|
||||
|
||||
const (
|
||||
WHPXReady WHPXState = "ready"
|
||||
WHPXReady WHPXState = "ready"
|
||||
WHPXNoHypervisor WHPXState = "no_hypervisor"
|
||||
WHPXMissing WHPXState = "missing"
|
||||
WHPXUnsupported WHPXState = "unsupported"
|
||||
WHPXMissing WHPXState = "missing"
|
||||
WHPXUnsupported WHPXState = "unsupported"
|
||||
)
|
||||
|
||||
type WHPXCapabilities struct {
|
||||
ModernOS bool `json:"modern_os"`
|
||||
APICEmulation bool `json:"apic_emulation"`
|
||||
KernelIrqchipAvailable bool `json:"kernel_irqchip_available"`
|
||||
NestedVirtProperty bool `json:"nested_virt_property"`
|
||||
NestedVirtProbeError string `json:"nested_virt_probe_error,omitempty"`
|
||||
}
|
||||
|
||||
type Report struct {
|
||||
OS string `json:"os"`
|
||||
Arch string `json:"arch"`
|
||||
LogicalCPUs int `json:"logical_cpus"`
|
||||
PhysicalCores int `json:"physical_cores"`
|
||||
HasHybridCores bool `json:"has_hybrid_cores"`
|
||||
PCoreCount int `json:"p_core_count"`
|
||||
ECoreCount int `json:"e_core_count"`
|
||||
PCoreMask uint64 `json:"p_core_mask"`
|
||||
PCoreMaskHex string `json:"p_core_mask_hex"`
|
||||
PCoreLogicalCPUs []int `json:"p_core_logical_cpus,omitempty"`
|
||||
ECoreLogicalCPUs []int `json:"e_core_logical_cpus,omitempty"`
|
||||
TotalRAMGB float64 `json:"total_ram_gb"`
|
||||
AvailRAMGB float64 `json:"avail_ram_gb"`
|
||||
DataRoot string `json:"data_root"`
|
||||
FreeDiskGB float64 `json:"free_disk_gb"`
|
||||
WHPX WHPXState `json:"whpx"`
|
||||
NeedsColdRebootWorkaround bool `json:"needs_cold_reboot_workaround"`
|
||||
GPUs []GPUInfo `json:"gpus"`
|
||||
RecommendedGPU *GPUInfo `json:"recommended_gpu,omitempty"`
|
||||
OS string `json:"os"`
|
||||
Arch string `json:"arch"`
|
||||
LogicalCPUs int `json:"logical_cpus"`
|
||||
PhysicalCores int `json:"physical_cores"`
|
||||
HasHybridCores bool `json:"has_hybrid_cores"`
|
||||
PCoreCount int `json:"p_core_count"`
|
||||
ECoreCount int `json:"e_core_count"`
|
||||
LPECoreCount int `json:"lpe_core_count,omitempty"`
|
||||
PCoreMask uint64 `json:"p_core_mask"`
|
||||
PCoreMaskHex string `json:"p_core_mask_hex"`
|
||||
PCoreLogicalCPUs []int `json:"p_core_logical_cpus,omitempty"`
|
||||
ECoreLogicalCPUs []int `json:"e_core_logical_cpus,omitempty"`
|
||||
NonLPEMask uint64 `json:"non_lpe_mask,omitempty"`
|
||||
NonLPEMaskHex string `json:"non_lpe_mask_hex,omitempty"`
|
||||
NonLPELogicalCPUs []int `json:"non_lpe_logical_cpus,omitempty"`
|
||||
TotalRAMGB float64 `json:"total_ram_gb"`
|
||||
AvailRAMGB float64 `json:"avail_ram_gb"`
|
||||
MemoryLoadPct int `json:"memory_load_pct"`
|
||||
// Commit memory: QEMU commits all guest RAM at start (CreateFileMapping), so
|
||||
// a VM needs its memory free in the commit charge, not just in physical RAM.
|
||||
// Measured 2026-11-28: 14.7 GiB commit free with 17.3 GiB physical free, and a
|
||||
// 16G guest failed ("Cannot set up guest memory"). portable-runtime-spec.md §5.1.
|
||||
CommitAvailGB float64 `json:"commit_avail_gb"`
|
||||
CommitLimitGB float64 `json:"commit_limit_gb"`
|
||||
DataRoot string `json:"data_root"`
|
||||
DataRootDriveType string `json:"data_root_drive_type,omitempty"`
|
||||
FreeDiskGB float64 `json:"free_disk_gb"`
|
||||
WHPX WHPXState `json:"whpx"`
|
||||
WHPXCaps WHPXCapabilities `json:"whpx_caps"`
|
||||
NeedsColdRebootWorkaround bool `json:"needs_cold_reboot_workaround"`
|
||||
GPUs []GPUInfo `json:"gpus"`
|
||||
RecommendedGPU *GPUInfo `json:"recommended_gpu,omitempty"`
|
||||
}
|
||||
|
||||
// ClassifyGPU distinguishes discrete, integrated, and virtual display adapters.
|
||||
|
||||
@@ -13,13 +13,14 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
kernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||
procGetLogicalProcessorInformationEx = kernel32.NewProc("GetLogicalProcessorInformationEx")
|
||||
procGlobalMemoryStatusEx = kernel32.NewProc("GlobalMemoryStatusEx")
|
||||
procGetDiskFreeSpaceExW = kernel32.NewProc("GetDiskFreeSpaceExW")
|
||||
procOpenProcess = kernel32.NewProc("OpenProcess")
|
||||
procSetProcessAffinityMask = kernel32.NewProc("SetProcessAffinityMask")
|
||||
procCloseHandle = kernel32.NewProc("CloseHandle")
|
||||
kernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||
procGetLogicalProcessorInformationEx = kernel32.NewProc("GetLogicalProcessorInformationEx")
|
||||
procGlobalMemoryStatusEx = kernel32.NewProc("GlobalMemoryStatusEx")
|
||||
procGetDiskFreeSpaceExW = kernel32.NewProc("GetDiskFreeSpaceExW")
|
||||
procDeviceIoControl = kernel32.NewProc("DeviceIoControl")
|
||||
procOpenProcess = kernel32.NewProc("OpenProcess")
|
||||
procSetProcessAffinityMask = kernel32.NewProc("SetProcessAffinityMask")
|
||||
procCloseHandle = kernel32.NewProc("CloseHandle")
|
||||
|
||||
advapi32 = syscall.NewLazyDLL("advapi32.dll")
|
||||
procRegOpenKeyExW = advapi32.NewProc("RegOpenKeyExW")
|
||||
@@ -31,12 +32,12 @@ var (
|
||||
)
|
||||
|
||||
const (
|
||||
hkeyLocalMachine = 0x80000002
|
||||
keyRead = 0x20019
|
||||
regSZ = 1
|
||||
regExpandSZ = 2
|
||||
regMultiSZ = 7
|
||||
processSetInformation = 0x0200
|
||||
hkeyLocalMachine = 0x80000002
|
||||
keyRead = 0x20019
|
||||
regSZ = 1
|
||||
regExpandSZ = 2
|
||||
regMultiSZ = 7
|
||||
processSetInformation = 0x0200
|
||||
whvCapHypervisorPresent = 0x00000001
|
||||
)
|
||||
|
||||
@@ -55,33 +56,50 @@ type memoryStatusEx struct {
|
||||
// Inspect collects Windows host capabilities without requiring administrator privileges.
|
||||
func Inspect(dataRoot string) Report {
|
||||
rep := Report{
|
||||
OS: "windows",
|
||||
Arch: runtime.GOARCH,
|
||||
LogicalCPUs: runtime.NumCPU(),
|
||||
OS: "windows",
|
||||
Arch: runtime.GOARCH,
|
||||
LogicalCPUs: runtime.NumCPU(),
|
||||
DataRoot: dataRoot,
|
||||
WHPX: probeWHPX(),
|
||||
NeedsColdRebootWorkaround: probeNeedsColdRebootWorkaround(),
|
||||
GPUs: probeVulkanGPUs(),
|
||||
}
|
||||
if rep.WHPX == WHPXReady {
|
||||
rep.WHPXCaps = probeWHPXCapabilities()
|
||||
}
|
||||
rep.RecommendedGPU = PickRecommendedGPU(rep.GPUs)
|
||||
|
||||
if cores, pCount, eCount, pMask, pLPs, eLPs, ok := probeHybridTopology(); ok {
|
||||
rep.PhysicalCores = cores
|
||||
rep.PCoreCount = pCount
|
||||
rep.ECoreCount = eCount
|
||||
rep.HasHybridCores = eCount > 0
|
||||
rep.PCoreMask = pMask
|
||||
rep.PCoreMaskHex = fmt.Sprintf("0x%X", pMask)
|
||||
rep.PCoreLogicalCPUs = pLPs
|
||||
rep.ECoreLogicalCPUs = eLPs
|
||||
if topo, ok := probeHybridTopology(); ok {
|
||||
rep.PhysicalCores = topo.phys
|
||||
rep.PCoreCount = topo.pCount
|
||||
rep.ECoreCount = topo.eCount
|
||||
rep.LPECoreCount = topo.lpeCount
|
||||
rep.HasHybridCores = topo.eCount > 0 || topo.lpeCount > 0
|
||||
rep.PCoreMask = topo.pMask
|
||||
rep.PCoreMaskHex = fmt.Sprintf("0x%X", topo.pMask)
|
||||
rep.PCoreLogicalCPUs = topo.pLPs
|
||||
rep.ECoreLogicalCPUs = topo.eLPs
|
||||
if topo.lpeCount > 0 && topo.nonLPEMask > 0 {
|
||||
rep.NonLPEMask = topo.nonLPEMask
|
||||
rep.NonLPEMaskHex = fmt.Sprintf("0x%X", topo.nonLPEMask)
|
||||
rep.NonLPELogicalCPUs = topo.nonLPELPs
|
||||
}
|
||||
}
|
||||
if totalGB, availGB, ok := probeMemoryGB(); ok {
|
||||
rep.TotalRAMGB = totalGB
|
||||
rep.AvailRAMGB = availGB
|
||||
}
|
||||
if ms, ok := memoryStatus(); ok {
|
||||
rep.MemoryLoadPct = int(ms.MemoryLoad)
|
||||
}
|
||||
if limitGB, availGB, ok := probeCommitGB(); ok {
|
||||
rep.CommitLimitGB = limitGB
|
||||
rep.CommitAvailGB = availGB
|
||||
}
|
||||
if freeGB, ok := probeFreeDiskGB(dataRoot); ok {
|
||||
rep.FreeDiskGB = freeGB
|
||||
}
|
||||
rep.DataRootDriveType = probeDriveType(dataRoot)
|
||||
return rep
|
||||
}
|
||||
|
||||
@@ -159,7 +177,19 @@ func probeNeedsColdRebootWorkaround() bool {
|
||||
return mod.NewProc("WHvResetPartition").Find() != nil
|
||||
}
|
||||
|
||||
func probeHybridTopology() (phys, pCount, eCount int, pMask uint64, pLPs, eLPs []int, ok bool) {
|
||||
type hybridTopology struct {
|
||||
phys int
|
||||
pCount int
|
||||
eCount int
|
||||
lpeCount int
|
||||
pMask uint64
|
||||
nonLPEMask uint64
|
||||
pLPs []int
|
||||
eLPs []int
|
||||
nonLPELPs []int
|
||||
}
|
||||
|
||||
func probeHybridTopology() (topo hybridTopology, ok bool) {
|
||||
var bufLen uint32
|
||||
procGetLogicalProcessorInformationEx.Call(0, 0, uintptr(unsafe.Pointer(&bufLen)))
|
||||
if bufLen == 0 {
|
||||
@@ -179,7 +209,9 @@ func probeHybridTopology() (phys, pCount, eCount int, pMask uint64, pLPs, eLPs [
|
||||
mask uint64
|
||||
}
|
||||
var cores []coreRec
|
||||
effSet := make(map[byte]bool)
|
||||
var maxEff byte
|
||||
var minEff byte = 0xFF
|
||||
for off := uint32(0); off+48 <= bufLen; {
|
||||
size := binary.LittleEndian.Uint32(buf[off+4 : off+8])
|
||||
if size < 48 || off+size > bufLen {
|
||||
@@ -190,29 +222,46 @@ func probeHybridTopology() (phys, pCount, eCount int, pMask uint64, pLPs, eLPs [
|
||||
if eff > maxEff {
|
||||
maxEff = eff
|
||||
}
|
||||
if eff < minEff {
|
||||
minEff = eff
|
||||
}
|
||||
effSet[eff] = true
|
||||
cores = append(cores, coreRec{eff: eff, mask: mask})
|
||||
off += size
|
||||
}
|
||||
if len(cores) == 0 {
|
||||
return
|
||||
}
|
||||
phys = len(cores)
|
||||
hasThreeTiers := len(effSet) >= 3
|
||||
topo.phys = len(cores)
|
||||
var eMask uint64
|
||||
for _, c := range cores {
|
||||
if c.eff == maxEff {
|
||||
pCount++
|
||||
pMask |= c.mask
|
||||
} else {
|
||||
eCount++
|
||||
switch {
|
||||
case c.eff == maxEff:
|
||||
topo.pCount++
|
||||
topo.pMask |= c.mask
|
||||
topo.nonLPEMask |= c.mask
|
||||
case hasThreeTiers && c.eff == minEff:
|
||||
topo.lpeCount++
|
||||
default:
|
||||
topo.eCount++
|
||||
eMask |= c.mask
|
||||
topo.nonLPEMask |= c.mask
|
||||
}
|
||||
}
|
||||
if !hasThreeTiers {
|
||||
topo.nonLPEMask = 0
|
||||
}
|
||||
for i := 0; i < 64; i++ {
|
||||
if (pMask>>uint(i))&1 != 0 {
|
||||
pLPs = append(pLPs, i)
|
||||
bit := uint64(1) << uint(i)
|
||||
if topo.pMask&bit != 0 {
|
||||
topo.pLPs = append(topo.pLPs, i)
|
||||
}
|
||||
if (eMask>>uint(i))&1 != 0 {
|
||||
eLPs = append(eLPs, i)
|
||||
if eMask&bit != 0 {
|
||||
topo.eLPs = append(topo.eLPs, i)
|
||||
}
|
||||
if topo.nonLPEMask&bit != 0 {
|
||||
topo.nonLPELPs = append(topo.nonLPELPs, i)
|
||||
}
|
||||
}
|
||||
ok = true
|
||||
@@ -220,16 +269,39 @@ func probeHybridTopology() (phys, pCount, eCount int, pMask uint64, pLPs, eLPs [
|
||||
}
|
||||
|
||||
func probeMemoryGB() (totalGB, availGB float64, ok bool) {
|
||||
var ms memoryStatusEx
|
||||
ms.Length = uint32(unsafe.Sizeof(ms))
|
||||
r, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&ms)))
|
||||
if r == 0 {
|
||||
ms, ok := memoryStatus()
|
||||
if !ok {
|
||||
return 0, 0, false
|
||||
}
|
||||
const gb = 1024 * 1024 * 1024
|
||||
return float64(ms.TotalPhys) / gb, float64(ms.AvailPhys) / gb, true
|
||||
}
|
||||
|
||||
// probeCommitGB reads the system commit limit and what is still free in it.
|
||||
// GlobalMemoryStatusEx's "page file" fields are the commit limit and the
|
||||
// available commit for the system (not the page file alone).
|
||||
func probeCommitGB() (limitGB, availGB float64, ok bool) {
|
||||
ms, ok := memoryStatus()
|
||||
if !ok {
|
||||
return 0, 0, false
|
||||
}
|
||||
const gb = 1024 * 1024 * 1024
|
||||
return float64(ms.TotalPageFile) / gb, float64(ms.AvailPageFile) / gb, true
|
||||
}
|
||||
|
||||
func memoryStatus() (memoryStatusEx, bool) {
|
||||
var ms memoryStatusEx
|
||||
ms.Length = uint32(unsafe.Sizeof(ms))
|
||||
r, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&ms)))
|
||||
return ms, r != 0
|
||||
}
|
||||
|
||||
// CommitAvailGB is the commit memory free right now (for start-time checks).
|
||||
func CommitAvailGB() (float64, bool) {
|
||||
_, avail, ok := probeCommitGB()
|
||||
return avail, ok
|
||||
}
|
||||
|
||||
func probeFreeDiskGB(path string) (float64, bool) {
|
||||
vol := filepath.VolumeName(path)
|
||||
if vol != "" {
|
||||
@@ -252,6 +324,72 @@ func probeFreeDiskGB(path string) (float64, bool) {
|
||||
return float64(freeBytesAvail) / (1024 * 1024 * 1024), true
|
||||
}
|
||||
|
||||
// probeDriveType detects whether path resides on a local fixed drive, USB
|
||||
// external enclosure (via IOCTL_STORAGE_QUERY_PROPERTY BusTypeUsb=7),
|
||||
// removable drive, or network share. Requires no admin privileges.
|
||||
func probeDriveType(path string) string {
|
||||
vol := filepath.VolumeName(path)
|
||||
if vol == "" {
|
||||
return "unknown"
|
||||
}
|
||||
root := vol + `\`
|
||||
p, err := syscall.UTF16PtrFromString(root)
|
||||
if err != nil {
|
||||
return "unknown"
|
||||
}
|
||||
dt, _, _ := procGetDriveTypeW.Call(uintptr(unsafe.Pointer(p)))
|
||||
switch dt {
|
||||
case 2: // DRIVE_REMOVABLE
|
||||
return "removable"
|
||||
case 4: // DRIVE_REMOTE
|
||||
return "network"
|
||||
case 3: // DRIVE_FIXED
|
||||
if isUSBBusVolume(vol) {
|
||||
return "usb"
|
||||
}
|
||||
return "fixed"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
func isUSBBusVolume(vol string) bool {
|
||||
if len(vol) < 2 || vol[1] != ':' {
|
||||
return false
|
||||
}
|
||||
devPath, err := syscall.UTF16PtrFromString(`\\.\` + vol[:2])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
// Access = 0 allows metadata IOCTLs (IOCTL_STORAGE_QUERY_PROPERTY) without elevation.
|
||||
h, err := syscall.CreateFile(devPath, 0, syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE, nil, syscall.OPEN_EXISTING, 0, 0)
|
||||
if err != nil || h == syscall.InvalidHandle {
|
||||
return false
|
||||
}
|
||||
defer syscall.CloseHandle(h)
|
||||
|
||||
const ioctlStorageQueryProperty = 0x002D1400
|
||||
var query [12]byte // STORAGE_PROPERTY_QUERY: PropertyId=0 (StorageDeviceProperty), QueryType=0
|
||||
var out [512]byte
|
||||
var returned uint32
|
||||
r, _, _ := procDeviceIoControl.Call(
|
||||
uintptr(h),
|
||||
ioctlStorageQueryProperty,
|
||||
uintptr(unsafe.Pointer(&query[0])),
|
||||
uintptr(len(query)),
|
||||
uintptr(unsafe.Pointer(&out[0])),
|
||||
uintptr(len(out)),
|
||||
uintptr(unsafe.Pointer(&returned)),
|
||||
0,
|
||||
)
|
||||
if r == 0 || returned < 32 {
|
||||
return false
|
||||
}
|
||||
// STORAGE_DEVICE_DESCRIPTOR.BusType is a 4-byte enum at offset 28; BusTypeUsb == 7.
|
||||
busType := binary.LittleEndian.Uint32(out[28:32])
|
||||
return busType == 7
|
||||
}
|
||||
|
||||
func probeVulkanGPUs() []GPUInfo {
|
||||
const baseKey = `SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}`
|
||||
var out []GPUInfo
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package host
|
||||
|
||||
// StartMarginGB is the commit memory a VM needs beyond its guest RAM: QEMU's own
|
||||
// allocations and the graphics path. Conservative; refine with measurements.
|
||||
const StartMarginGB = 1.0
|
||||
|
||||
// memoryChoices are the sizes the UI offers (GB).
|
||||
var memoryChoices = []float64{4, 6, 8, 12, 16, 24, 32, 48, 64}
|
||||
|
||||
// RecommendedMemoryGB is the largest offered size that fits both in 60% of
|
||||
// physical RAM and in the commit memory free now (minus StartMarginGB and 2 GB
|
||||
// headroom for the host). At least 4.
|
||||
func RecommendedMemoryGB(rep Report) float64 {
|
||||
limit := rep.TotalRAMGB * 0.6
|
||||
if rep.CommitAvailGB > 0 {
|
||||
if c := rep.CommitAvailGB - StartMarginGB - 2; c < limit {
|
||||
limit = c
|
||||
}
|
||||
}
|
||||
best := memoryChoices[0]
|
||||
for _, m := range memoryChoices {
|
||||
if m <= limit {
|
||||
best = m
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
//go:build !windows
|
||||
|
||||
package host
|
||||
|
||||
// CommitAvailGB is unknown on dev/preview hosts.
|
||||
func CommitAvailGB() (float64, bool) { return 0, false }
|
||||
@@ -0,0 +1,19 @@
|
||||
package host
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestRecommendedMemoryFollowsCommitMemory(t *testing.T) {
|
||||
// The measured case: 32 GB host, 14.7 GiB commit free -> 16G fails, 8G fits.
|
||||
if got := RecommendedMemoryGB(Report{TotalRAMGB: 31.8, CommitAvailGB: 14.7}); got != 8 {
|
||||
t.Fatalf("got %v, want 8", got)
|
||||
}
|
||||
if got := RecommendedMemoryGB(Report{TotalRAMGB: 64, CommitAvailGB: 60}); got != 32 {
|
||||
t.Fatalf("got %v, want 32", got)
|
||||
}
|
||||
if got := RecommendedMemoryGB(Report{TotalRAMGB: 8, CommitAvailGB: 3}); got != 4 {
|
||||
t.Fatalf("got %v, want the 4 GB floor", got)
|
||||
}
|
||||
if got := RecommendedMemoryGB(Report{TotalRAMGB: 32}); got != 16 {
|
||||
t.Fatalf("unknown commit: got %v, want 16", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package host
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/bits"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Optimization summarizes the probed host availability and recommendation for
|
||||
// one hardware/runtime optimization toggle.
|
||||
type Optimization struct {
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"` // recommended | available | experimental | auto | unavailable
|
||||
Supported bool `json:"supported"`
|
||||
Recommended bool `json:"recommended"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
// CanSafelyPinPCores reports whether pinning a QEMU process with vmCPUs vCPUs
|
||||
// exclusively to the host's P-cores is safe without oversubscribing logical
|
||||
// CPUs. On non-SMT hybrid CPUs such as Intel Core Ultra 200 (Arrow Lake, e.g.
|
||||
// 6P/6T + 8E), pinning an 8-vCPU VM onto 6 logical CPUs causes XNU spinlock
|
||||
// lock-holder preemption stalls. Requires at least vmCPUs+1 P-core logical CPUs
|
||||
// so QEMU I/O and vGPU threads have headroom alongside the vCPUs.
|
||||
func CanSafelyPinPCores(rep Report, vmCPUs int) (bool, int) {
|
||||
pThreads := len(rep.PCoreLogicalCPUs)
|
||||
if pThreads == 0 {
|
||||
pThreads = rep.PCoreCount
|
||||
}
|
||||
if !rep.HasHybridCores || rep.PCoreMask == 0 || pThreads <= 0 || vmCPUs <= 0 {
|
||||
return false, pThreads
|
||||
}
|
||||
return pThreads >= vmCPUs+1, pThreads
|
||||
}
|
||||
|
||||
// AffinityPlan describes the safest CPU affinity mask to apply to a running
|
||||
// QEMU process on a hybrid host without oversubscribing logical CPUs.
|
||||
type AffinityPlan struct {
|
||||
Mode string // "pcores" | "non_lpe" | "all"
|
||||
Mask uint64
|
||||
MaskHex string
|
||||
CoreCount int
|
||||
ThreadCount int
|
||||
PThreads int
|
||||
}
|
||||
|
||||
// SelectSafeAffinity chooses P-core-only pinning when P-core logical CPUs have
|
||||
// headroom (>= vmCPUs+1). On 3-tier hybrid CPUs (such as Intel Core Ultra 200
|
||||
// Arrow Lake: 6P/6T + 8E + 2LP-E) where vmCPUs exceeds P-core threads, it falls
|
||||
// back to pinning P+E cores (excluding only the slow SoC LP-E cores) instead of
|
||||
// oversubscribing 6 cores or exposing guest vCPUs to LP-E cores.
|
||||
func SelectSafeAffinity(rep Report, vmCPUs int) AffinityPlan {
|
||||
ok, pThreads := CanSafelyPinPCores(rep, vmCPUs)
|
||||
if ok {
|
||||
return AffinityPlan{
|
||||
Mode: "pcores",
|
||||
Mask: rep.PCoreMask,
|
||||
MaskHex: rep.PCoreMaskHex,
|
||||
CoreCount: rep.PCoreCount,
|
||||
ThreadCount: pThreads,
|
||||
PThreads: pThreads,
|
||||
}
|
||||
}
|
||||
if rep.LPECoreCount > 0 && rep.NonLPEMask > 0 && vmCPUs > 0 {
|
||||
nonLPEThreads := len(rep.NonLPELogicalCPUs)
|
||||
if nonLPEThreads == 0 {
|
||||
nonLPEThreads = bits.OnesCount64(rep.NonLPEMask)
|
||||
}
|
||||
if nonLPEThreads >= vmCPUs+1 {
|
||||
hex := rep.NonLPEMaskHex
|
||||
if hex == "" {
|
||||
hex = fmt.Sprintf("0x%X", rep.NonLPEMask)
|
||||
}
|
||||
return AffinityPlan{
|
||||
Mode: "non_lpe",
|
||||
Mask: rep.NonLPEMask,
|
||||
MaskHex: hex,
|
||||
CoreCount: rep.PCoreCount + rep.ECoreCount,
|
||||
ThreadCount: nonLPEThreads,
|
||||
PThreads: pThreads,
|
||||
}
|
||||
}
|
||||
}
|
||||
return AffinityPlan{
|
||||
Mode: "all",
|
||||
PThreads: pThreads,
|
||||
}
|
||||
}
|
||||
|
||||
// EvaluateOptimizations combines host capability probes with the active
|
||||
// runtime's patch list so the UI can show accurate, self-explanatory guidance
|
||||
// for every optimization toggle without guessing.
|
||||
func EvaluateOptimizations(rep Report, runtimePatches []string) []Optimization {
|
||||
hasPatch := func(substr string) bool {
|
||||
for _, p := range runtimePatches {
|
||||
if strings.Contains(strings.ToLower(p), strings.ToLower(substr)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var out []Optimization
|
||||
|
||||
// 1. P-Core affinity pinning (hybrid Intel CPUs)
|
||||
if rep.HasHybridCores {
|
||||
detail := fmt.Sprintf("%dP+%dE", rep.PCoreCount, rep.ECoreCount)
|
||||
if len(rep.PCoreLogicalCPUs) > 0 {
|
||||
detail = fmt.Sprintf("%dP(%dT)+%dE", rep.PCoreCount, len(rep.PCoreLogicalCPUs), rep.ECoreCount)
|
||||
}
|
||||
if rep.LPECoreCount > 0 {
|
||||
detail += fmt.Sprintf("+%dLPE", rep.LPECoreCount)
|
||||
}
|
||||
out = append(out, Optimization{
|
||||
ID: "pcore_pin",
|
||||
Status: "recommended",
|
||||
Supported: true,
|
||||
Recommended: true,
|
||||
Detail: detail,
|
||||
})
|
||||
} else {
|
||||
out = append(out, Optimization{
|
||||
ID: "pcore_pin",
|
||||
Status: "unavailable",
|
||||
Supported: false,
|
||||
})
|
||||
}
|
||||
|
||||
// 2. WHPX kernel-irqchip (APIC emulation in Hyper-V)
|
||||
switch {
|
||||
case rep.WHPX != WHPXReady || !rep.WHPXCaps.KernelIrqchipAvailable:
|
||||
out = append(out, Optimization{
|
||||
ID: "kernel_irqchip",
|
||||
Status: "unavailable",
|
||||
Supported: false,
|
||||
})
|
||||
case !rep.NeedsColdRebootWorkaround:
|
||||
// Windows 11 / Server 2022+: QEMU enables kernel-irqchip by default,
|
||||
// unless NestedVirtualization property probe fails (e.g. hr=0x80370302)
|
||||
// on an unpatched runtime.
|
||||
if rep.WHPXCaps.NestedVirtProperty {
|
||||
out = append(out, Optimization{
|
||||
ID: "kernel_irqchip",
|
||||
Status: "recommended",
|
||||
Supported: true,
|
||||
Recommended: true,
|
||||
})
|
||||
} else if hasPatch("nested-virt-nonfatal") {
|
||||
out = append(out, Optimization{
|
||||
ID: "kernel_irqchip",
|
||||
Status: "recommended",
|
||||
Supported: true,
|
||||
Recommended: true,
|
||||
Detail: "win11-nested-virt-nonfatal",
|
||||
})
|
||||
} else {
|
||||
out = append(out, Optimization{
|
||||
ID: "kernel_irqchip",
|
||||
Status: "unavailable",
|
||||
Supported: false,
|
||||
Detail: rep.WHPXCaps.NestedVirtProbeError,
|
||||
})
|
||||
}
|
||||
default:
|
||||
// Windows 10: requires startup-ipis patch in runtime for multi-core boot.
|
||||
if hasPatch("startup-ipis") {
|
||||
out = append(out, Optimization{
|
||||
ID: "kernel_irqchip",
|
||||
Status: "experimental",
|
||||
Supported: true,
|
||||
Detail: "win10-startup-ipis",
|
||||
})
|
||||
} else {
|
||||
out = append(out, Optimization{
|
||||
ID: "kernel_irqchip",
|
||||
Status: "unavailable",
|
||||
Supported: false,
|
||||
Detail: "win10-needs-patch",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Win10 cold-reboot compensation
|
||||
if rep.NeedsColdRebootWorkaround {
|
||||
out = append(out, Optimization{
|
||||
ID: "cold_reboot",
|
||||
Status: "auto",
|
||||
Supported: true,
|
||||
Recommended: true,
|
||||
})
|
||||
} else {
|
||||
out = append(out, Optimization{
|
||||
ID: "cold_reboot",
|
||||
Status: "unavailable",
|
||||
Supported: false,
|
||||
})
|
||||
}
|
||||
|
||||
// 4. Discrete Vulkan GPU acceleration
|
||||
if rep.RecommendedGPU != nil && rep.RecommendedGPU.Kind == GPUDiscrete {
|
||||
out = append(out, Optimization{
|
||||
ID: "discrete_gpu",
|
||||
Status: "recommended",
|
||||
Supported: true,
|
||||
Recommended: true,
|
||||
Detail: rep.RecommendedGPU.Name,
|
||||
})
|
||||
} else if rep.RecommendedGPU != nil {
|
||||
out = append(out, Optimization{
|
||||
ID: "discrete_gpu",
|
||||
Status: "available",
|
||||
Supported: true,
|
||||
Detail: rep.RecommendedGPU.Name,
|
||||
})
|
||||
} else {
|
||||
out = append(out, Optimization{
|
||||
ID: "discrete_gpu",
|
||||
Status: "unavailable",
|
||||
Supported: false,
|
||||
})
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package host
|
||||
|
||||
import "testing"
|
||||
|
||||
func findOpt(t *testing.T, opts []Optimization, id string) Optimization {
|
||||
t.Helper()
|
||||
for _, o := range opts {
|
||||
if o.ID == id {
|
||||
return o
|
||||
}
|
||||
}
|
||||
t.Fatalf("optimization %q not found", id)
|
||||
return Optimization{}
|
||||
}
|
||||
|
||||
func TestEvaluateOptimizationsWin10AndWin11(t *testing.T) {
|
||||
// Win10 hybrid CPU without startup-ipis patch.
|
||||
win10 := Report{
|
||||
WHPX: WHPXReady,
|
||||
HasHybridCores: true,
|
||||
PCoreCount: 8,
|
||||
ECoreCount: 4,
|
||||
NeedsColdRebootWorkaround: true,
|
||||
WHPXCaps: WHPXCapabilities{
|
||||
APICEmulation: true,
|
||||
KernelIrqchipAvailable: true,
|
||||
},
|
||||
RecommendedGPU: &GPUInfo{Name: "NVIDIA GeForce RTX 4070 Ti", Kind: GPUDiscrete, VulkanICD: "nv-vk64.json"},
|
||||
}
|
||||
opts := EvaluateOptimizations(win10, []string{"qemu-whpx-win10-compat.patch"})
|
||||
if o := findOpt(t, opts, "pcore_pin"); o.Status != "recommended" || !o.Supported {
|
||||
t.Fatalf("pcore_pin = %+v", o)
|
||||
}
|
||||
if o := findOpt(t, opts, "kernel_irqchip"); o.Status != "unavailable" || o.Detail != "win10-needs-patch" {
|
||||
t.Fatalf("kernel_irqchip without patch = %+v", o)
|
||||
}
|
||||
if o := findOpt(t, opts, "cold_reboot"); o.Status != "auto" {
|
||||
t.Fatalf("cold_reboot = %+v", o)
|
||||
}
|
||||
|
||||
// Win10 with startup-ipis patch -> experimental.
|
||||
optsPatched := EvaluateOptimizations(win10, []string{"qemu-whpx-win10-compat.patch", "qemu-whpx-win10-startup-ipis.patch"})
|
||||
if o := findOpt(t, optsPatched, "kernel_irqchip"); o.Status != "experimental" || !o.Supported {
|
||||
t.Fatalf("kernel_irqchip with patch = %+v", o)
|
||||
}
|
||||
|
||||
// Win11 where NestedVirtualization probe fails with 0x80370302.
|
||||
win11BrokenNested := Report{
|
||||
WHPX: WHPXReady,
|
||||
NeedsColdRebootWorkaround: false,
|
||||
WHPXCaps: WHPXCapabilities{
|
||||
ModernOS: true,
|
||||
APICEmulation: true,
|
||||
KernelIrqchipAvailable: true,
|
||||
NestedVirtProperty: false,
|
||||
NestedVirtProbeError: "0x80370302",
|
||||
},
|
||||
}
|
||||
opts11 := EvaluateOptimizations(win11BrokenNested, nil)
|
||||
if o := findOpt(t, opts11, "kernel_irqchip"); o.Status != "unavailable" || o.Detail != "0x80370302" {
|
||||
t.Fatalf("win11 broken nested = %+v", o)
|
||||
}
|
||||
if o := findOpt(t, opts11, "cold_reboot"); o.Status != "unavailable" {
|
||||
t.Fatalf("win11 cold_reboot = %+v", o)
|
||||
}
|
||||
|
||||
// Win11 with nested-virt-nonfatal patch -> kernel_irqchip recommended even when probe returns 0x80370302.
|
||||
opts11Patched := EvaluateOptimizations(win11BrokenNested, []string{"qemu-whpx-nested-virt-nonfatal.patch"})
|
||||
if o := findOpt(t, opts11Patched, "kernel_irqchip"); o.Status != "recommended" || !o.Supported {
|
||||
t.Fatalf("win11 with nested-virt-nonfatal patch = %+v", o)
|
||||
}
|
||||
|
||||
// Win11 with full support.
|
||||
win11BrokenNested.WHPXCaps.NestedVirtProperty = true
|
||||
win11BrokenNested.WHPXCaps.NestedVirtProbeError = ""
|
||||
opts11Ok := EvaluateOptimizations(win11BrokenNested, nil)
|
||||
if o := findOpt(t, opts11Ok, "kernel_irqchip"); o.Status != "recommended" || !o.Supported {
|
||||
t.Fatalf("win11 full support = %+v", o)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanSafelyPinPCores(t *testing.T) {
|
||||
// Arrow Lake Core Ultra 9 285H: 6 P-cores with NO Hyper-Threading (6 logical CPUs).
|
||||
arrowLake := Report{
|
||||
HasHybridCores: true,
|
||||
PCoreCount: 6,
|
||||
ECoreCount: 10,
|
||||
PCoreMask: 0x3C03,
|
||||
PCoreLogicalCPUs: []int{0, 1, 10, 11, 12, 13},
|
||||
}
|
||||
if ok, threads := CanSafelyPinPCores(arrowLake, 8); ok || threads != 6 {
|
||||
t.Fatalf("arrowLake 8 vCPU: got (%v, %d), want (false, 6)", ok, threads)
|
||||
}
|
||||
if ok, threads := CanSafelyPinPCores(arrowLake, 6); ok || threads != 6 {
|
||||
t.Fatalf("arrowLake 6 vCPU: got (%v, %d), want (false, 6)", ok, threads)
|
||||
}
|
||||
if ok, threads := CanSafelyPinPCores(arrowLake, 4); !ok || threads != 6 {
|
||||
t.Fatalf("arrowLake 4 vCPU: got (%v, %d), want (true, 6)", ok, threads)
|
||||
}
|
||||
|
||||
// Raptor Lake 6P with Hyper-Threading (12 logical CPUs).
|
||||
raptorLake := Report{
|
||||
HasHybridCores: true,
|
||||
PCoreCount: 6,
|
||||
ECoreCount: 8,
|
||||
PCoreMask: 0xFFF,
|
||||
PCoreLogicalCPUs: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11},
|
||||
}
|
||||
if ok, threads := CanSafelyPinPCores(raptorLake, 8); !ok || threads != 12 {
|
||||
t.Fatalf("raptorLake 8 vCPU: got (%v, %d), want (true, 12)", ok, threads)
|
||||
}
|
||||
if ok, threads := CanSafelyPinPCores(raptorLake, 12); ok || threads != 12 {
|
||||
t.Fatalf("raptorLake 12 vCPU: got (%v, %d), want (false, 12)", ok, threads)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectSafeAffinityThreeTierArrowLake(t *testing.T) {
|
||||
// Intel Core Ultra 9 285H: 6P (no HT) + 8E + 2LP-E = 16 logical CPUs.
|
||||
arrowLake := Report{
|
||||
HasHybridCores: true,
|
||||
PCoreCount: 6,
|
||||
ECoreCount: 8,
|
||||
LPECoreCount: 2,
|
||||
PCoreMask: 0x3C03,
|
||||
PCoreMaskHex: "0x3C03",
|
||||
PCoreLogicalCPUs: []int{0, 1, 10, 11, 12, 13},
|
||||
NonLPEMask: 0x3FFF,
|
||||
NonLPEMaskHex: "0x3FFF",
|
||||
NonLPELogicalCPUs: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13},
|
||||
}
|
||||
|
||||
if p := SelectSafeAffinity(arrowLake, 4); p.Mode != "pcores" || p.Mask != 0x3C03 {
|
||||
t.Fatalf("4 vCPU: got %+v, want pcores 0x3C03", p)
|
||||
}
|
||||
if p := SelectSafeAffinity(arrowLake, 8); p.Mode != "non_lpe" || p.Mask != 0x3FFF || p.ThreadCount != 14 {
|
||||
t.Fatalf("8 vCPU: got %+v, want non_lpe 0x3FFF (14T)", p)
|
||||
}
|
||||
if p := SelectSafeAffinity(arrowLake, 14); p.Mode != "all" || p.Mask != 0 {
|
||||
t.Fatalf("14 vCPU: got %+v, want all", p)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//go:build !windows
|
||||
|
||||
package host
|
||||
|
||||
import "time"
|
||||
|
||||
func ProcessCPUTime(pid uint32) (time.Duration, bool) {
|
||||
return 0, false
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//go:build windows
|
||||
|
||||
package host
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
// WinHvPlatformDefs.h capability & partition property codes.
|
||||
whvCapFeatures = 0x00000001
|
||||
whvCapProcessorPerfmon = 0x00001009
|
||||
whvPropNestedVirtualization = 0x00000004
|
||||
whvPropLocalApicEmulationMode = 0x00001005
|
||||
whvPropProcessorCount = 0x00001fff
|
||||
whvLocalApicModeX2Apic = 2
|
||||
|
||||
processQueryLimitedInfo = 0x1000
|
||||
)
|
||||
|
||||
var procGetProcessTimes = kernel32.NewProc("GetProcessTimes")
|
||||
|
||||
// probeWHPXCapabilities checks WHPX kernel-irqchip and nested-virtualization
|
||||
// partition property support on a throwaway WHP partition without starting any
|
||||
// vCPU or requiring administrator privileges.
|
||||
func probeWHPXCapabilities() WHPXCapabilities {
|
||||
var caps WHPXCapabilities
|
||||
mod := syscall.NewLazyDLL("WinHvPlatform.dll")
|
||||
if err := mod.Load(); err != nil {
|
||||
return caps
|
||||
}
|
||||
getCap := mod.NewProc("WHvGetCapability")
|
||||
createPart := mod.NewProc("WHvCreatePartition")
|
||||
deletePart := mod.NewProc("WHvDeletePartition")
|
||||
setProp := mod.NewProc("WHvSetPartitionProperty")
|
||||
if getCap.Find() != nil || createPart.Find() != nil || deletePart.Find() != nil || setProp.Find() != nil {
|
||||
return caps
|
||||
}
|
||||
|
||||
var perfmon uint64
|
||||
var written uint32
|
||||
hr, _, _ := getCap.Call(
|
||||
uintptr(whvCapProcessorPerfmon),
|
||||
uintptr(unsafe.Pointer(&perfmon)),
|
||||
uintptr(unsafe.Sizeof(perfmon)),
|
||||
uintptr(unsafe.Pointer(&written)),
|
||||
)
|
||||
caps.ModernOS = int32(hr) >= 0
|
||||
|
||||
var features uint64
|
||||
hr, _, _ = getCap.Call(
|
||||
uintptr(whvCapFeatures),
|
||||
uintptr(unsafe.Pointer(&features)),
|
||||
uintptr(unsafe.Sizeof(features)),
|
||||
uintptr(unsafe.Pointer(&written)),
|
||||
)
|
||||
hasApicBit := int32(hr) >= 0 && (features&(1<<1)) != 0
|
||||
hasApicProcs := mod.NewProc("WHvSetVirtualProcessorInterruptControllerState2").Find() == nil &&
|
||||
mod.NewProc("WHvRequestInterrupt").Find() == nil
|
||||
caps.APICEmulation = hasApicBit && hasApicProcs
|
||||
|
||||
var part uintptr
|
||||
hr, _, _ = createPart.Call(uintptr(unsafe.Pointer(&part)))
|
||||
if int32(hr) < 0 || part == 0 {
|
||||
return caps
|
||||
}
|
||||
defer deletePart.Call(part)
|
||||
|
||||
var propBuf [24]byte
|
||||
// ProcessorCount = 1
|
||||
propBuf[0] = 1
|
||||
hr, _, _ = setProp.Call(part, uintptr(whvPropProcessorCount), uintptr(unsafe.Pointer(&propBuf[0])), uintptr(len(propBuf)))
|
||||
if int32(hr) < 0 {
|
||||
return caps
|
||||
}
|
||||
|
||||
if caps.APICEmulation {
|
||||
var mode uint32 = whvLocalApicModeX2Apic
|
||||
hr, _, _ = setProp.Call(part, uintptr(whvPropLocalApicEmulationMode), uintptr(unsafe.Pointer(&mode)), uintptr(unsafe.Sizeof(mode)))
|
||||
caps.KernelIrqchipAvailable = int32(hr) >= 0
|
||||
}
|
||||
|
||||
// Probe WHvPartitionPropertyCodeNestedVirtualization (same property that
|
||||
// fails with hr=0x80370302 WHV_E_UNKNOWN_PROPERTY on some Windows 11 builds).
|
||||
var nestedBuf [24]byte
|
||||
nestedBuf[0] = 1
|
||||
hr, _, _ = setProp.Call(part, uintptr(whvPropNestedVirtualization), uintptr(unsafe.Pointer(&nestedBuf[0])), uintptr(len(nestedBuf)))
|
||||
if int32(hr) >= 0 {
|
||||
caps.NestedVirtProperty = true
|
||||
} else {
|
||||
caps.NestedVirtProbeError = fmt.Sprintf("0x%08x", uint32(hr))
|
||||
}
|
||||
return caps
|
||||
}
|
||||
|
||||
// ProcessCPUTime returns total kernel + user CPU time consumed by pid.
|
||||
func ProcessCPUTime(pid uint32) (time.Duration, bool) {
|
||||
if pid == 0 {
|
||||
return 0, false
|
||||
}
|
||||
h, _, _ := procOpenProcess.Call(uintptr(processQueryLimitedInfo), 0, uintptr(pid))
|
||||
if h == 0 {
|
||||
return 0, false
|
||||
}
|
||||
defer procCloseHandle.Call(h)
|
||||
|
||||
var creation, exit, kernel, user syscall.Filetime
|
||||
r, _, _ := procGetProcessTimes.Call(
|
||||
h,
|
||||
uintptr(unsafe.Pointer(&creation)),
|
||||
uintptr(unsafe.Pointer(&exit)),
|
||||
uintptr(unsafe.Pointer(&kernel)),
|
||||
uintptr(unsafe.Pointer(&user)),
|
||||
)
|
||||
if r == 0 {
|
||||
return 0, false
|
||||
}
|
||||
total100ns := (uint64(kernel.HighDateTime)<<32 | uint64(kernel.LowDateTime)) +
|
||||
(uint64(user.HighDateTime)<<32 | uint64(user.LowDateTime))
|
||||
return time.Duration(total100ns) * 100 * time.Nanosecond, true
|
||||
}
|
||||
@@ -39,72 +39,82 @@ func Detect() Locale {
|
||||
|
||||
var catalog = map[Locale]map[string]string{
|
||||
ZhCN: {
|
||||
"doctor.title": "reims-go 宿主机环境体检",
|
||||
"doctor.os": "操作系统",
|
||||
"doctor.cpu": "处理器与核心拓扑",
|
||||
"doctor.pcores": "P-Core 性能核",
|
||||
"doctor.ecores": "E-Core 能效核",
|
||||
"doctor.ram": "宿主机内存",
|
||||
"doctor.disk": "数据盘剩余空间",
|
||||
"doctor.whpx": "Windows 虚拟机监控程序平台 (WHPX)",
|
||||
"doctor.whpx.ok": "可用(WinHvPlatform.dll 已就绪,hypervisor 运行中)",
|
||||
"doctor.whpx.no_hv": "已加载 WinHvPlatform.dll,但未检测到虚拟化(请在 BIOS 开启 VT-x/AMD-V)",
|
||||
"doctor.whpx.missing": "未启用(请点击一键启用 HypervisorPlatform 并重启 Windows)",
|
||||
"doctor.whpx.unsupported": "非 Windows 宿主(当前处于跨平台开发模式)",
|
||||
"doctor.gpu": "Vulkan 显卡列表",
|
||||
"doctor.gpu.none": "未检测到已注册的 Vulkan ICD 显卡驱动",
|
||||
"doctor.gpu.recommended": "推荐独显",
|
||||
"doctor.runtime": "便携运行时",
|
||||
"doctor.runtime.none": "尚未安装(运行 reims-go runtime install <压缩包> 导入)",
|
||||
"doctor.runtime.active": "当前激活:%s(%s)",
|
||||
"runtime.installed": "便携运行时已安装:%s -> %s",
|
||||
"runtime.activated": "已切换激活运行时:%s",
|
||||
"runtime.empty": "尚未安装任何便携运行时。",
|
||||
"vm.empty": "当前没有已创建的虚拟机。",
|
||||
"vm.install_guide.title": "macOS 装机步骤(简体中文恢复界面):",
|
||||
"vm.install_guide.step1": "1. 打开「磁盘工具」,选中「QEMU HARDDISK Media」并点「抹掉」(格式选 APFS)。",
|
||||
"vm.install_guide.step2": "2. 退出磁盘工具,选择「重新安装 macOS Tahoe」并等待完成。",
|
||||
"vm.install_guide.step3": "3. 进入桌面后,运行 `reims-go vm eject %s`(或在界面点击「弹出安装盘」)。",
|
||||
"err.runtime_not_installed": "未找到已激活的便携运行时,请先执行 `reims-go runtime install <归档路径>`",
|
||||
"installer.paused": "已暂停。再次运行 `reims-go installer download %s` 会从中断处继续。",
|
||||
"installer.done": "离线安装包已就绪:macOS %s -> %s",
|
||||
"installer.cached.empty": "还没有下载任何安装包。",
|
||||
"installer.cached.total": "共 %s,位于 %s",
|
||||
"installer.partial": "(未下载完)",
|
||||
"doctor.title": "Reims-Go 宿主机环境体检",
|
||||
"doctor.os": "操作系统",
|
||||
"doctor.cpu": "处理器与核心拓扑",
|
||||
"doctor.pcores": "P-Core 性能核",
|
||||
"doctor.ecores": "E-Core 能效核",
|
||||
"doctor.ram": "宿主机内存",
|
||||
"doctor.disk": "数据盘剩余空间",
|
||||
"doctor.whpx": "Windows 虚拟机监控程序平台 (WHPX)",
|
||||
"doctor.whpx.ok": "可用(WinHvPlatform.dll 已就绪,hypervisor 运行中)",
|
||||
"doctor.whpx.no_hv": "已加载 WinHvPlatform.dll,但未检测到虚拟化(请在 BIOS 开启 VT-x/AMD-V)",
|
||||
"doctor.whpx.missing": "未启用(请点击一键启用 HypervisorPlatform 并重启 Windows)",
|
||||
"doctor.whpx.unsupported": "非 Windows 宿主(当前处于跨平台开发模式)",
|
||||
"doctor.gpu": "Vulkan 显卡列表",
|
||||
"doctor.gpu.none": "未检测到已注册的 Vulkan ICD 显卡驱动",
|
||||
"doctor.gpu.recommended": "推荐独显",
|
||||
"doctor.runtime": "便携运行时",
|
||||
"doctor.runtime.none": "尚未安装(运行 reims-go runtime install <压缩包> 导入)",
|
||||
"doctor.runtime.active": "当前激活:%s(%s)",
|
||||
"runtime.installed": "便携运行时已安装:%s -> %s",
|
||||
"runtime.activated": "已切换激活运行时:%s",
|
||||
"runtime.empty": "尚未安装任何便携运行时。",
|
||||
"vm.empty": "当前没有已创建的虚拟机。",
|
||||
"vm.typed": "已敲入 %d 个键。",
|
||||
"vm.install_guide.title": "macOS 装机步骤(简体中文恢复界面):",
|
||||
"vm.install_guide.step1": "1. 打开「磁盘工具」,选中「QEMU HARDDISK Media」并点「抹掉」(格式选 APFS)。",
|
||||
"vm.install_guide.step2": "2. 回到「恢复」窗口,选「重新安装 macOS」,装到刚抹掉的磁盘上(中途会自动重启几次)。",
|
||||
"vm.install_guide.step3": "3. 看到「设置助理」后,运行 `reims-go vm eject %s`(或在界面点「完成安装」)移除安装盘,下次启动生效。",
|
||||
"err.runtime_not_installed": "未找到已激活的便携运行时,请先执行 `reims-go runtime install <归档路径>`",
|
||||
"err.commit_memory": "内存不够启动:这台虚拟机要 %.0f GB,Windows 现在只能再分配 %.1f GB。关掉一些程序再试,或在设置里把内存改为 %.0f GB",
|
||||
"installer.paused": "已暂停。再次运行 `reims-go installer download %s` 会从中断处继续。",
|
||||
"installer.done": "离线安装包已就绪:macOS %s -> %s",
|
||||
"installer.cached.empty": "还没有下载任何安装包。",
|
||||
"installer.cached.total": "共 %s,位于 %s",
|
||||
"installer.partial": "(未下载完)",
|
||||
"runtime.remote.empty": "当前通道还没有发布运行时(候选版需要加 --candidate)。",
|
||||
"runtime.remote.downloading": "下载运行时 %s(%s,%s)",
|
||||
"runtime.remote.paused": "已暂停。再次运行同一命令会从中断处继续。",
|
||||
},
|
||||
EnUS: {
|
||||
"doctor.title": "reims-go Host Environment Check",
|
||||
"doctor.os": "Operating System",
|
||||
"doctor.cpu": "CPU & Core Topology",
|
||||
"doctor.pcores": "P-Cores (Performance)",
|
||||
"doctor.ecores": "E-Cores (Efficiency)",
|
||||
"doctor.ram": "Host Memory",
|
||||
"doctor.disk": "Data Drive Free Space",
|
||||
"doctor.whpx": "Windows Hypervisor Platform (WHPX)",
|
||||
"doctor.whpx.ok": "Ready (WinHvPlatform.dll active, hypervisor running)",
|
||||
"doctor.whpx.no_hv": "WinHvPlatform.dll present, but no hypervisor detected (enable VT-x/AMD-V in BIOS)",
|
||||
"doctor.whpx.missing": "Not enabled (enable Windows Hypervisor Platform and restart Windows)",
|
||||
"doctor.whpx.unsupported": "Non-Windows host (cross-platform dev mode)",
|
||||
"doctor.gpu": "Vulkan GPUs",
|
||||
"doctor.gpu.none": "No registered Vulkan ICD driver found",
|
||||
"doctor.gpu.recommended": "Recommended discrete GPU",
|
||||
"doctor.runtime": "Portable Runtime",
|
||||
"doctor.runtime.none": "Not installed (run `reims-go runtime install <archive>`)",
|
||||
"doctor.runtime.active": "Active: %s (%s)",
|
||||
"runtime.installed": "Portable runtime installed: %s -> %s",
|
||||
"runtime.activated": "Active runtime switched to: %s",
|
||||
"runtime.empty": "No portable runtimes installed.",
|
||||
"vm.empty": "No virtual machines found.",
|
||||
"vm.install_guide.title": "macOS Setup Steps (Recovery UI):",
|
||||
"vm.install_guide.step1": "1. Open 'Disk Utility', select 'QEMU HARDDISK Media', and Erase as APFS.",
|
||||
"vm.install_guide.step2": "2. Quit Disk Utility, choose 'Reinstall macOS Tahoe', and wait for completion.",
|
||||
"vm.install_guide.step3": "3. Once on the desktop, run `reims-go vm eject %s` (or click 'Eject Installer').",
|
||||
"err.runtime_not_installed": "no active portable runtime found; run `reims-go runtime install <archive>` first",
|
||||
"installer.paused": "Paused. Run `reims-go installer download %s` again to continue where it stopped.",
|
||||
"installer.done": "Offline installer ready: macOS %s -> %s",
|
||||
"installer.cached.empty": "No installers downloaded yet.",
|
||||
"installer.cached.total": "%s in %s",
|
||||
"installer.partial": "(partly downloaded)",
|
||||
"doctor.title": "Reims-Go Host Environment Check",
|
||||
"doctor.os": "Operating System",
|
||||
"doctor.cpu": "CPU & Core Topology",
|
||||
"doctor.pcores": "P-Cores (Performance)",
|
||||
"doctor.ecores": "E-Cores (Efficiency)",
|
||||
"doctor.ram": "Host Memory",
|
||||
"doctor.disk": "Data Drive Free Space",
|
||||
"doctor.whpx": "Windows Hypervisor Platform (WHPX)",
|
||||
"doctor.whpx.ok": "Ready (WinHvPlatform.dll active, hypervisor running)",
|
||||
"doctor.whpx.no_hv": "WinHvPlatform.dll present, but no hypervisor detected (enable VT-x/AMD-V in BIOS)",
|
||||
"doctor.whpx.missing": "Not enabled (enable Windows Hypervisor Platform and restart Windows)",
|
||||
"doctor.whpx.unsupported": "Non-Windows host (cross-platform dev mode)",
|
||||
"doctor.gpu": "Vulkan GPUs",
|
||||
"doctor.gpu.none": "No registered Vulkan ICD driver found",
|
||||
"doctor.gpu.recommended": "Recommended discrete GPU",
|
||||
"doctor.runtime": "Portable Runtime",
|
||||
"doctor.runtime.none": "Not installed (run `reims-go runtime install <archive>`)",
|
||||
"doctor.runtime.active": "Active: %s (%s)",
|
||||
"runtime.installed": "Portable runtime installed: %s -> %s",
|
||||
"runtime.activated": "Active runtime switched to: %s",
|
||||
"runtime.empty": "No portable runtimes installed.",
|
||||
"vm.empty": "No virtual machines found.",
|
||||
"vm.typed": "Typed %d keys.",
|
||||
"vm.install_guide.title": "macOS Setup Steps (Recovery UI):",
|
||||
"vm.install_guide.step1": "1. Open 'Disk Utility', select 'QEMU HARDDISK Media', and Erase as APFS.",
|
||||
"vm.install_guide.step2": "2. Back in the Recovery window, choose 'Reinstall macOS' and install onto the disk you erased (it restarts a few times).",
|
||||
"vm.install_guide.step3": "3. When Setup Assistant appears, run `reims-go vm eject %s` (or click 'Finish install') to remove the installer at next start.",
|
||||
"err.runtime_not_installed": "no active portable runtime found; run `reims-go runtime install <archive>` first",
|
||||
"err.commit_memory": "Not enough memory to start: this VM needs %.0f GB and Windows can commit only %.1f GB more. Close some programs, or set its memory to %.0f GB",
|
||||
"installer.paused": "Paused. Run `reims-go installer download %s` again to continue where it stopped.",
|
||||
"installer.done": "Offline installer ready: macOS %s -> %s",
|
||||
"installer.cached.empty": "No installers downloaded yet.",
|
||||
"installer.cached.total": "%s in %s",
|
||||
"installer.partial": "(partly downloaded)",
|
||||
"runtime.remote.empty": "No runtime is published on this channel yet (add --candidate for candidates).",
|
||||
"runtime.remote.downloading": "Downloading runtime %s (%s, %s)",
|
||||
"runtime.remote.paused": "Paused. Run the same command again to continue where it stopped.",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,949 @@
|
||||
package installer
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf16"
|
||||
)
|
||||
|
||||
// HFSFile describes one root-level file placed into a minimal GPT + HFS Plus
|
||||
// disk image (compatible with macOS Recovery 11–26 auto-mount).
|
||||
type HFSFile struct {
|
||||
Name string
|
||||
Mode uint16 // POSIX mode, e.g. 0o100644 or 0o100755
|
||||
Size int64
|
||||
Open func() (io.ReadCloser, error)
|
||||
}
|
||||
|
||||
const (
|
||||
hfsSector = 512
|
||||
hfsBlock = 4096
|
||||
hfsNode = 4096
|
||||
hfsCatalogNodes = 128
|
||||
hfsExtentsNodes = 128
|
||||
hfsAttributesNodes = 64
|
||||
hfsFirstLBA = 2048
|
||||
hfsEpoch1904 = 2082844800
|
||||
)
|
||||
|
||||
// BuildHFSPlusDiskImage creates a single-partition GPT + HFS Plus disk image
|
||||
// containing files in its root directory (Apple TN1150 layout, matching
|
||||
// reims-util's src/image/hfsplus.rs & gpt.rs).
|
||||
func BuildHFSPlusDiskImage(destPath, label string, files []HFSFile) error {
|
||||
if len(files) == 0 {
|
||||
return fmt.Errorf("HFS+ image requires at least one file")
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(destPath), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Calculate required HFS+ blocks:
|
||||
// block 0 (header), allocation bitmap, extents, attributes, catalog, files, last block (alt header).
|
||||
var fileBlocks uint64
|
||||
for _, f := range files {
|
||||
if f.Size > 0 {
|
||||
fileBlocks += uint64((f.Size + hfsBlock - 1) / hfsBlock)
|
||||
}
|
||||
}
|
||||
metaBlocks := uint64(1 + 4 + hfsExtentsNodes + 2*hfsAttributesNodes + hfsCatalogNodes + 1)
|
||||
// Add 16 MiB headroom and align partition size to 1 MiB.
|
||||
partBytes := (metaBlocks + fileBlocks) * hfsBlock
|
||||
partBytes += 16 << 20
|
||||
const oneMiB = 1 << 20
|
||||
partBytes = ((partBytes + oneMiB - 1) / oneMiB) * oneMiB
|
||||
if partBytes < 8<<20 {
|
||||
partBytes = 8 << 20
|
||||
}
|
||||
totalBlocks := uint32(partBytes / hfsBlock)
|
||||
|
||||
partSectors := partBytes / hfsSector
|
||||
// GPT needs backup entries (32 sectors) + backup header (1 sector) at disk end; align to 1 MiB.
|
||||
totalSectors := hfsFirstLBA + partSectors + 33
|
||||
totalSectors = ((totalSectors + 2047) / 2048) * 2048
|
||||
diskBytes := int64(totalSectors * hfsSector)
|
||||
|
||||
tmpPath := destPath + ".tmp"
|
||||
out, err := os.Create(tmpPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cleanup := func() {
|
||||
_ = out.Close()
|
||||
_ = os.Remove(tmpPath)
|
||||
}
|
||||
if err := out.Truncate(diskBytes); err != nil {
|
||||
cleanup()
|
||||
return err
|
||||
}
|
||||
|
||||
// Deterministic GUIDs derived from label + file names/sizes.
|
||||
h := sha256.New()
|
||||
_, _ = h.Write([]byte(label))
|
||||
for _, f := range files {
|
||||
_, _ = fmt.Fprintf(h, "|%s:%d", f.Name, f.Size)
|
||||
}
|
||||
seed := h.Sum(nil)
|
||||
var diskGUID, partGUID [16]byte
|
||||
copy(diskGUID[:], seed[0:16])
|
||||
copy(partGUID[:], seed[16:32])
|
||||
diskGUID[7] = (diskGUID[7] & 0x0f) | 0x40
|
||||
diskGUID[8] = (diskGUID[8] & 0x3f) | 0x80
|
||||
partGUID[7] = (partGUID[7] & 0x0f) | 0x40
|
||||
partGUID[8] = (partGUID[8] & 0x3f) | 0x80
|
||||
|
||||
if err := writeGPT(out, totalSectors, diskGUID, partGUID, hfsFirstLBA, hfsFirstLBA+partSectors-1, label); err != nil {
|
||||
cleanup()
|
||||
return err
|
||||
}
|
||||
|
||||
partOffset := int64(hfsFirstLBA * hfsSector)
|
||||
var volID [8]byte
|
||||
copy(volID[:], seed[0:8])
|
||||
if err := writeHFSPlusVolume(out, partOffset, totalBlocks, label, volID, files); err != nil {
|
||||
cleanup()
|
||||
return err
|
||||
}
|
||||
if err := out.Sync(); err != nil {
|
||||
cleanup()
|
||||
return err
|
||||
}
|
||||
if err := out.Close(); err != nil {
|
||||
_ = os.Remove(tmpPath)
|
||||
return err
|
||||
}
|
||||
_ = os.Remove(destPath)
|
||||
if err := os.Rename(tmpPath, destPath); err != nil {
|
||||
_ = os.Remove(tmpPath)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeGPT(out *os.File, sectors uint64, diskGUID, partGUID [16]byte, firstLBA, lastLBA uint64, name string) error {
|
||||
last := sectors - 1
|
||||
const entrySectors = 32
|
||||
lastUsable := sectors - 1 - entrySectors - 1
|
||||
|
||||
var mbr [hfsSector]byte
|
||||
e := mbr[446:462]
|
||||
copy(e[1:4], []byte{0x00, 0x02, 0x00})
|
||||
e[4] = 0xee
|
||||
copy(e[5:8], []byte{0xff, 0xff, 0xff})
|
||||
binary.LittleEndian.PutUint32(e[8:12], 1)
|
||||
mbrSize := sectors - 1
|
||||
if mbrSize > 0xffffffff {
|
||||
mbrSize = 0xffffffff
|
||||
}
|
||||
binary.LittleEndian.PutUint32(e[12:16], uint32(mbrSize))
|
||||
mbr[510], mbr[511] = 0x55, 0xaa
|
||||
if _, err := out.WriteAt(mbr[:], 0); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
entries := make([]byte, 128*128)
|
||||
copy(entries[0:16], appleHFSPlusGUID[:])
|
||||
copy(entries[16:32], partGUID[:])
|
||||
binary.LittleEndian.PutUint64(entries[32:40], firstLBA)
|
||||
binary.LittleEndian.PutUint64(entries[40:48], lastLBA)
|
||||
u16 := utf16.Encode([]rune(name))
|
||||
if len(u16) > 36 {
|
||||
u16 = u16[:36]
|
||||
}
|
||||
for i, c := range u16 {
|
||||
binary.LittleEndian.PutUint16(entries[56+2*i:58+2*i], c)
|
||||
}
|
||||
entriesCRC := crc32.ChecksumIEEE(entries)
|
||||
|
||||
makeHdr := func(myLBA, altLBA, entriesLBA uint64) [hfsSector]byte {
|
||||
var hdr [hfsSector]byte
|
||||
copy(hdr[0:8], "EFI PART")
|
||||
binary.LittleEndian.PutUint32(hdr[8:12], 0x00010000)
|
||||
binary.LittleEndian.PutUint32(hdr[12:16], 92)
|
||||
binary.LittleEndian.PutUint64(hdr[24:32], myLBA)
|
||||
binary.LittleEndian.PutUint64(hdr[32:40], altLBA)
|
||||
binary.LittleEndian.PutUint64(hdr[40:48], 2+entrySectors)
|
||||
binary.LittleEndian.PutUint64(hdr[48:56], lastUsable)
|
||||
copy(hdr[56:72], diskGUID[:])
|
||||
binary.LittleEndian.PutUint64(hdr[72:80], entriesLBA)
|
||||
binary.LittleEndian.PutUint32(hdr[80:84], 128)
|
||||
binary.LittleEndian.PutUint32(hdr[84:88], 128)
|
||||
binary.LittleEndian.PutUint32(hdr[88:92], entriesCRC)
|
||||
crc := crc32.ChecksumIEEE(hdr[:92])
|
||||
binary.LittleEndian.PutUint32(hdr[16:20], crc)
|
||||
return hdr
|
||||
}
|
||||
|
||||
priHdr := makeHdr(1, last, 2)
|
||||
backupEntriesLBA := last - entrySectors
|
||||
bakHdr := makeHdr(last, 1, backupEntriesLBA)
|
||||
|
||||
if _, err := out.WriteAt(priHdr[:], hfsSector); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := out.WriteAt(entries, 2*hfsSector); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := out.WriteAt(entries, int64(backupEntriesLBA*hfsSector)); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := out.WriteAt(bakHdr[:], int64(last*hfsSector)); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type hfsFork struct {
|
||||
length uint64
|
||||
first uint32
|
||||
blocks uint32
|
||||
}
|
||||
|
||||
func encodeHFSFork(f hfsFork, clump uint32) [80]byte {
|
||||
var d [80]byte
|
||||
binary.BigEndian.PutUint64(d[0:8], f.length)
|
||||
binary.BigEndian.PutUint32(d[8:12], clump)
|
||||
binary.BigEndian.PutUint32(d[12:16], f.blocks)
|
||||
if f.blocks > 0 {
|
||||
binary.BigEndian.PutUint32(d[16:20], f.first)
|
||||
binary.BigEndian.PutUint32(d[20:24], f.blocks)
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
func writeHFSPlusVolume(out *os.File, partOff int64, totalBlocks uint32, label string, volID [8]byte, files []HFSFile) error {
|
||||
date := uint32(time.Now().Unix() + hfsEpoch1904)
|
||||
nextBlock := uint32(1)
|
||||
alloc := func(bytesLen uint64) (hfsFork, error) {
|
||||
n := uint32((bytesLen + hfsBlock - 1) / hfsBlock)
|
||||
first := nextBlock
|
||||
if uint64(first)+uint64(n) >= uint64(totalBlocks) {
|
||||
return hfsFork{}, fmt.Errorf("HFS+ volume out of space")
|
||||
}
|
||||
nextBlock += n
|
||||
return hfsFork{length: bytesLen, first: first, blocks: n}, nil
|
||||
}
|
||||
|
||||
bitmapBytes := ((uint64(totalBlocks)+7)/8 + hfsBlock - 1) / hfsBlock * hfsBlock
|
||||
allocFork, err := alloc(bitmapBytes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
extentsFork, err := alloc(uint64(hfsExtentsNodes) * hfsNode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
attrsFork, err := alloc(uint64(hfsAttributesNodes) * 2 * hfsNode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
catalogFork, err := alloc(uint64(hfsCatalogNodes) * hfsNode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
type fileEntry struct {
|
||||
id uint32
|
||||
name []uint16
|
||||
fold string
|
||||
mode uint16
|
||||
fork hfsFork
|
||||
}
|
||||
entries := make([]fileEntry, 0, len(files))
|
||||
for i, f := range files {
|
||||
var fk hfsFork
|
||||
if f.Size > 0 {
|
||||
fk, err = alloc(uint64(f.Size))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
writeOff := partOff + int64(fk.first)*hfsBlock
|
||||
buf := make([]byte, 256*1024)
|
||||
var written int64
|
||||
for {
|
||||
n, rerr := rc.Read(buf)
|
||||
if n > 0 {
|
||||
if _, werr := out.WriteAt(buf[:n], writeOff+written); werr != nil {
|
||||
_ = rc.Close()
|
||||
return werr
|
||||
}
|
||||
written += int64(n)
|
||||
}
|
||||
if rerr == io.EOF {
|
||||
break
|
||||
}
|
||||
if rerr != nil {
|
||||
_ = rc.Close()
|
||||
return rerr
|
||||
}
|
||||
}
|
||||
_ = rc.Close()
|
||||
if written != f.Size {
|
||||
return fmt.Errorf("HFS+ file %s size mismatch: wrote %d, expected %d", f.Name, written, f.Size)
|
||||
}
|
||||
}
|
||||
mode := f.Mode
|
||||
if mode == 0 {
|
||||
mode = 0o100644
|
||||
}
|
||||
entries = append(entries, fileEntry{
|
||||
id: uint32(16 + i),
|
||||
name: utf16.Encode([]rune(f.Name)),
|
||||
fold: strings.ToLower(f.Name),
|
||||
mode: mode,
|
||||
fork: fk,
|
||||
})
|
||||
}
|
||||
usedBlocks := nextBlock + 1
|
||||
|
||||
labelU16 := utf16.Encode([]rune(label))
|
||||
var recs [][]byte
|
||||
recs = append(recs, append(hfsKey(1, labelU16), hfsFolderRecord(uint32(len(files)), date)...))
|
||||
recs = append(recs, append(hfsKey(2, nil), hfsThreadRecord(3, 1, labelU16)...))
|
||||
|
||||
byName := append([]fileEntry(nil), entries...)
|
||||
sort.Slice(byName, func(i, j int) bool { return byName[i].fold < byName[j].fold })
|
||||
for _, e := range byName {
|
||||
recs = append(recs, append(hfsKey(2, e.name), hfsFileRecord(e.id, date, e.mode, e.fork)...))
|
||||
}
|
||||
for _, e := range entries {
|
||||
recs = append(recs, append(hfsKey(e.id, nil), hfsThreadRecord(4, 2, e.name)...))
|
||||
}
|
||||
|
||||
leaf, err := hfsLeafNode(recs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
catHdr := hfsHeaderNode(hfsNode, hfsCatalogNodes, 516, 2|4, 0xcf, uint32(len(recs)))
|
||||
if _, err := out.WriteAt(catHdr, partOff+int64(catalogFork.first)*hfsBlock); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := out.WriteAt(leaf, partOff+int64(catalogFork.first)*hfsBlock+hfsNode); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
extHdr := hfsHeaderNode(hfsNode, hfsExtentsNodes, 10, 2, 0, 0)
|
||||
if _, err := out.WriteAt(extHdr, partOff+int64(extentsFork.first)*hfsBlock); err != nil {
|
||||
return err
|
||||
}
|
||||
attrHdr := hfsHeaderNode(2*hfsNode, hfsAttributesNodes, 266, 2|4, 0, 0)
|
||||
if _, err := out.WriteAt(attrHdr, partOff+int64(attrsFork.first)*hfsBlock); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
bitmap := make([]byte, bitmapBytes)
|
||||
for b := uint32(0); b < nextBlock; b++ {
|
||||
bitmap[b/8] |= 0x80 >> (b % 8)
|
||||
}
|
||||
lastBlk := totalBlocks - 1
|
||||
bitmap[lastBlk/8] |= 0x80 >> (lastBlk % 8)
|
||||
if _, err := out.WriteAt(bitmap, partOff+int64(allocFork.first)*hfsBlock); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var vh [512]byte
|
||||
copy(vh[0:2], "H+")
|
||||
binary.BigEndian.PutUint16(vh[2:4], 4)
|
||||
binary.BigEndian.PutUint32(vh[4:8], (1<<8)|(1<<31))
|
||||
copy(vh[8:12], "10.0")
|
||||
binary.BigEndian.PutUint32(vh[16:20], date)
|
||||
binary.BigEndian.PutUint32(vh[20:24], date)
|
||||
binary.BigEndian.PutUint32(vh[28:32], date)
|
||||
binary.BigEndian.PutUint32(vh[32:36], uint32(len(files)))
|
||||
binary.BigEndian.PutUint32(vh[40:44], hfsBlock)
|
||||
binary.BigEndian.PutUint32(vh[44:48], totalBlocks)
|
||||
binary.BigEndian.PutUint32(vh[48:52], totalBlocks-usedBlocks)
|
||||
binary.BigEndian.PutUint32(vh[52:56], nextBlock)
|
||||
binary.BigEndian.PutUint32(vh[56:60], 65536)
|
||||
binary.BigEndian.PutUint32(vh[60:64], 65536)
|
||||
binary.BigEndian.PutUint32(vh[64:68], uint32(16+len(files)))
|
||||
binary.BigEndian.PutUint32(vh[68:72], 1)
|
||||
binary.BigEndian.PutUint64(vh[72:80], 1)
|
||||
copy(vh[104:112], volID[:])
|
||||
|
||||
af := encodeHFSFork(allocFork, hfsBlock)
|
||||
ef := encodeHFSFork(extentsFork, uint32(extentsFork.length))
|
||||
cf := encodeHFSFork(catalogFork, uint32(catalogFork.length))
|
||||
atf := encodeHFSFork(attrsFork, uint32(attrsFork.length))
|
||||
copy(vh[112:192], af[:])
|
||||
copy(vh[192:272], ef[:])
|
||||
copy(vh[272:352], cf[:])
|
||||
copy(vh[352:432], atf[:])
|
||||
|
||||
if _, err := out.WriteAt(vh[:], partOff+1024); err != nil {
|
||||
return err
|
||||
}
|
||||
partEnd := partOff + int64(totalBlocks)*hfsBlock
|
||||
if _, err := out.WriteAt(vh[:], partEnd-1024); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func hfsHeaderNode(nodeSize int, nodes uint32, maxKey uint16, attrs uint32, compare byte, leafRecs uint32) []byte {
|
||||
n := make([]byte, nodeSize)
|
||||
n[8] = 1 // kBTHeaderNode
|
||||
binary.BigEndian.PutUint16(n[10:12], 3)
|
||||
used := uint32(1)
|
||||
if leafRecs > 0 {
|
||||
used = 2
|
||||
binary.BigEndian.PutUint16(n[14:16], 1)
|
||||
binary.BigEndian.PutUint32(n[16:20], 1)
|
||||
binary.BigEndian.PutUint32(n[20:24], leafRecs)
|
||||
binary.BigEndian.PutUint32(n[24:28], 1)
|
||||
binary.BigEndian.PutUint32(n[28:32], 1)
|
||||
n[248] = 0xc0
|
||||
} else {
|
||||
n[248] = 0x80
|
||||
}
|
||||
binary.BigEndian.PutUint16(n[32:34], uint16(nodeSize))
|
||||
binary.BigEndian.PutUint16(n[34:36], maxKey)
|
||||
binary.BigEndian.PutUint32(n[36:40], nodes)
|
||||
binary.BigEndian.PutUint32(n[40:44], nodes-used)
|
||||
binary.BigEndian.PutUint32(n[46:50], nodes*uint32(nodeSize))
|
||||
n[51] = compare
|
||||
binary.BigEndian.PutUint32(n[52:56], attrs)
|
||||
for i, off := range []uint16{14, 120, 248, uint16(nodeSize - 8)} {
|
||||
binary.BigEndian.PutUint16(n[nodeSize-2-2*i:nodeSize-2*i], off)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func hfsLeafNode(recs [][]byte) ([]byte, error) {
|
||||
n := make([]byte, hfsNode)
|
||||
n[8] = 0xff // kBTLeafNode
|
||||
n[9] = 1
|
||||
binary.BigEndian.PutUint16(n[10:12], uint16(len(recs)))
|
||||
offsets := make([]uint16, 0, len(recs)+1)
|
||||
at := 14
|
||||
for _, r := range recs {
|
||||
if at+len(r)+2*(len(recs)+1) > hfsNode {
|
||||
return nil, fmt.Errorf("HFS+ catalog records exceed one leaf node")
|
||||
}
|
||||
offsets = append(offsets, uint16(at))
|
||||
copy(n[at:], r)
|
||||
at += len(r)
|
||||
}
|
||||
offsets = append(offsets, uint16(at))
|
||||
for i, off := range offsets {
|
||||
binary.BigEndian.PutUint16(n[hfsNode-2-2*i:hfsNode-2*i], off)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func hfsKey(parent uint32, name []uint16) []byte {
|
||||
k := make([]byte, 8+2*len(name))
|
||||
binary.BigEndian.PutUint16(k[0:2], uint16(6+2*len(name)))
|
||||
binary.BigEndian.PutUint32(k[2:6], parent)
|
||||
binary.BigEndian.PutUint16(k[6:8], uint16(len(name)))
|
||||
for i, c := range name {
|
||||
binary.BigEndian.PutUint16(k[8+2*i:10+2*i], c)
|
||||
}
|
||||
return k
|
||||
}
|
||||
|
||||
func hfsFolderRecord(valence, date uint32) []byte {
|
||||
r := make([]byte, 88)
|
||||
binary.BigEndian.PutUint16(r[0:2], 1)
|
||||
binary.BigEndian.PutUint32(r[4:8], valence)
|
||||
binary.BigEndian.PutUint32(r[8:12], 2)
|
||||
for i := 0; i < 4; i++ {
|
||||
binary.BigEndian.PutUint32(r[12+4*i:16+4*i], date)
|
||||
}
|
||||
binary.BigEndian.PutUint32(r[32:36], 99)
|
||||
binary.BigEndian.PutUint32(r[36:40], 99)
|
||||
binary.BigEndian.PutUint16(r[42:44], 0o40755)
|
||||
binary.BigEndian.PutUint32(r[44:48], 1)
|
||||
return r
|
||||
}
|
||||
|
||||
func hfsFileRecord(id, date uint32, mode uint16, fork hfsFork) []byte {
|
||||
r := make([]byte, 248)
|
||||
binary.BigEndian.PutUint16(r[0:2], 2)
|
||||
binary.BigEndian.PutUint16(r[2:4], 2) // kHFSThreadExistsMask
|
||||
binary.BigEndian.PutUint32(r[8:12], id)
|
||||
for i := 0; i < 4; i++ {
|
||||
binary.BigEndian.PutUint32(r[12+4*i:16+4*i], date)
|
||||
}
|
||||
binary.BigEndian.PutUint32(r[32:36], 99)
|
||||
binary.BigEndian.PutUint32(r[36:40], 99)
|
||||
binary.BigEndian.PutUint16(r[42:44], mode)
|
||||
binary.BigEndian.PutUint32(r[44:48], 1)
|
||||
fd := encodeHFSFork(fork, 0)
|
||||
copy(r[88:168], fd[:])
|
||||
return r
|
||||
}
|
||||
|
||||
func hfsThreadRecord(kind uint16, parent uint32, name []uint16) []byte {
|
||||
r := make([]byte, 10+2*len(name))
|
||||
binary.BigEndian.PutUint16(r[0:2], kind)
|
||||
binary.BigEndian.PutUint32(r[4:8], parent)
|
||||
binary.BigEndian.PutUint16(r[8:10], uint16(len(name)))
|
||||
for i, c := range name {
|
||||
binary.BigEndian.PutUint16(r[10+2*i:12+2*i], c)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// HelperInstallScript returns the Recovery shell script placed on the REIMSHELP
|
||||
// volume. It auto-detects a writable target volume (skipping read-only system,
|
||||
// recovery, and installer volumes), automatically formats a single blank VM
|
||||
// physical disk (>= 30 GB) as APFS ("Macintosh HD") when no writable volume
|
||||
// exists yet (and prompts/requires --erase before touching any non-blank disk),
|
||||
// unpacks InstallApp.tar directly with BSD tar (no `installer` or `pkgutil`
|
||||
// required in macOS Recovery), copies InstallAssistant.pkg as SharedSupport.dmg,
|
||||
// and launches startosinstall.
|
||||
func HelperInstallScript() []byte {
|
||||
return []byte(`#!/bin/sh
|
||||
# Installs macOS offline without relying on Recovery's installer or pkgutil.
|
||||
# Auto-formats a single blank VM disk (>= 30 GB) as APFS ("Macintosh HD")
|
||||
# when no writable target volume is mounted yet.
|
||||
set -e
|
||||
|
||||
MIN_DISK_MB=30000
|
||||
TAB=$(printf '\t')
|
||||
|
||||
trim_ws() {
|
||||
v=$1
|
||||
while :; do
|
||||
case "$v" in
|
||||
" "*|"$TAB"*) v=${v#?} ;;
|
||||
*) break ;;
|
||||
esac
|
||||
done
|
||||
printf '%s' "$v"
|
||||
}
|
||||
|
||||
can_write() {
|
||||
[ -d "$1" ] || return 1
|
||||
probe="$1/.reims-write-test-$$"
|
||||
if mkdir "$probe" 2>/dev/null; then
|
||||
rmdir "$probe" 2>/dev/null || true
|
||||
return 0
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
is_reserved_vol() {
|
||||
case "$1" in
|
||||
Installer|REIMSHELP|RECOVERY|OPENCORE|"macOS Base System"|"Image Volume"|Recovery|Preboot|VM|Update)
|
||||
return 0 ;;
|
||||
*)
|
||||
return 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
find_writable_target() {
|
||||
for v in "/Volumes/Macintosh HD" "/Volumes/Untitled"; do
|
||||
if can_write "$v"; then
|
||||
printf '%s\n' "$v"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
for v in /Volumes/*; do
|
||||
[ -d "$v" ] || continue
|
||||
name=${v##*/}
|
||||
if is_reserved_vol "$name"; then
|
||||
continue
|
||||
fi
|
||||
if can_write "$v"; then
|
||||
printf '%s\n' "$v"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
bytes_to_mb() {
|
||||
b=$1
|
||||
case "$b" in
|
||||
''|*[!0-9]*) printf '0\n'; return ;;
|
||||
esac
|
||||
if [ "${#b}" -le 6 ]; then
|
||||
printf '0\n'
|
||||
else
|
||||
printf '%s\n' "${b%??????}"
|
||||
fi
|
||||
}
|
||||
|
||||
disk_prop() {
|
||||
printf '%s\n' "$1" | while IFS= read -r line; do
|
||||
case "$line" in
|
||||
*"$2"*)
|
||||
val=${line#*"$2"}
|
||||
trim_ws "$val"
|
||||
printf '\n'
|
||||
break
|
||||
;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
disk_has_reserved() {
|
||||
printf '%s\n' "$1" | while IFS= read -r line; do
|
||||
case "$line" in
|
||||
*" Installer "*|*" REIMSHELP "*|*" OPENCORE "*|*" RECOVERY "*|*" macOS Base System "*|*" Image Volume "*)
|
||||
printf 'yes\n'
|
||||
break
|
||||
;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
disk_has_partitions() {
|
||||
printf '%s\n' "$1" | while IFS= read -r line; do
|
||||
t=$(trim_ws "$line")
|
||||
case "$t" in
|
||||
[1-9]*:*)
|
||||
printf 'yes\n'
|
||||
break
|
||||
;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
list_physical_disks() {
|
||||
diskutil list physical 2>/dev/null | while IFS= read -r line; do
|
||||
case "$line" in
|
||||
/dev/disk*synthesized*|/dev/disk*"disk image"*)
|
||||
;;
|
||||
/dev/disk*)
|
||||
printf '%s\n' "${line%% *}"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
inspect_candidate_disk() {
|
||||
d=$1
|
||||
cand_ok=0
|
||||
cand_blank=0
|
||||
cand_size_human=""
|
||||
cand_media=""
|
||||
cand_content=""
|
||||
cand_reason=""
|
||||
|
||||
info=$(diskutil info "$d" 2>/dev/null) || { cand_reason="diskutil info failed"; return; }
|
||||
whole=$(disk_prop "$info" "Whole:")
|
||||
if [ "$whole" != "Yes" ]; then
|
||||
cand_reason="not a whole disk"
|
||||
return
|
||||
fi
|
||||
virtual=$(disk_prop "$info" "Virtual:")
|
||||
if [ "$virtual" = "Yes" ]; then
|
||||
cand_reason="virtual disk image"
|
||||
return
|
||||
fi
|
||||
proto=$(disk_prop "$info" "Protocol:")
|
||||
case "$proto" in
|
||||
*"Disk Image"*)
|
||||
cand_reason="disk image"
|
||||
return ;;
|
||||
esac
|
||||
ro=$(disk_prop "$info" "Read-Only Media:")
|
||||
if [ "$ro" = "Yes" ]; then
|
||||
cand_reason="read-only media"
|
||||
return
|
||||
fi
|
||||
|
||||
size_str=$(disk_prop "$info" "Disk Size:")
|
||||
[ -n "$size_str" ] || size_str=$(disk_prop "$info" "Total Size:")
|
||||
cand_size_human=${size_str%% (*}
|
||||
bytes_part=${size_str#*(}
|
||||
bytes=${bytes_part%% *}
|
||||
mb=$(bytes_to_mb "$bytes")
|
||||
if [ "$mb" -lt "$MIN_DISK_MB" ]; then
|
||||
cand_reason="too small (${cand_size_human:-unknown} < 30 GB)"
|
||||
return
|
||||
fi
|
||||
|
||||
dlist=$(diskutil list "$d" 2>/dev/null || true)
|
||||
if [ -n "$(disk_has_reserved "$dlist")" ]; then
|
||||
cand_reason="contains reserved/installer volume"
|
||||
return
|
||||
fi
|
||||
|
||||
cand_media=$(disk_prop "$info" "Device / Media Name:")
|
||||
cand_content=$(disk_prop "$info" "Content (IOContent):")
|
||||
cand_ok=1
|
||||
if [ -z "$(disk_has_partitions "$dlist")" ] && { [ -z "$cand_content" ] || [ "$cand_content" = "None" ]; }; then
|
||||
cand_blank=1
|
||||
fi
|
||||
}
|
||||
|
||||
erase_and_mount() {
|
||||
disk=$1
|
||||
echo "Formatting $disk as APFS (Macintosh HD, GPT)..."
|
||||
diskutil eraseDisk APFS "Macintosh HD" GPT "$disk"
|
||||
target=""
|
||||
for _ in 1 2 3 4 5; do
|
||||
if target=$(find_writable_target); then
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
if [ -z "$target" ]; then
|
||||
echo "Formatted $disk, but no writable target volume appeared under /Volumes." >&2
|
||||
diskutil list "$disk" >&2 || true
|
||||
ls /Volumes >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
erase_mode=0
|
||||
erase_disk=""
|
||||
target=""
|
||||
|
||||
case "${1:-}" in
|
||||
--erase)
|
||||
erase_mode=1
|
||||
erase_disk=${2:-}
|
||||
case "$erase_disk" in
|
||||
disk*) erase_disk="/dev/$erase_disk" ;;
|
||||
esac
|
||||
;;
|
||||
-h|--help)
|
||||
echo "Usage: sh /Volumes/REIMSHELP/install.sh [TARGET_VOLUME | --erase [/dev/diskN]]"
|
||||
exit 0
|
||||
;;
|
||||
"")
|
||||
;;
|
||||
*)
|
||||
target=${1%/}
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ "$erase_mode" -eq 1 ]; then
|
||||
if ! command -v diskutil >/dev/null 2>&1; then
|
||||
echo "diskutil is not available in this environment." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ -n "$erase_disk" ]; then
|
||||
inspect_candidate_disk "$erase_disk"
|
||||
if [ "$cand_ok" -ne 1 ]; then
|
||||
echo "Refusing to erase $erase_disk: $cand_reason" >&2
|
||||
exit 1
|
||||
fi
|
||||
erase_and_mount "$erase_disk"
|
||||
else
|
||||
cand_count=0
|
||||
cand_disk=""
|
||||
cand_summary=""
|
||||
for d in $(list_physical_disks); do
|
||||
inspect_candidate_disk "$d"
|
||||
if [ "$cand_ok" -eq 1 ]; then
|
||||
cand_count=$((cand_count + 1))
|
||||
cand_disk=$d
|
||||
status="has partitions"
|
||||
[ "$cand_blank" -eq 1 ] && status="blank"
|
||||
cand_summary="${cand_summary} $d ${cand_size_human} (${cand_media:-disk}, $status)
|
||||
"
|
||||
fi
|
||||
done
|
||||
if [ "$cand_count" -eq 1 ]; then
|
||||
erase_and_mount "$cand_disk"
|
||||
elif [ "$cand_count" -eq 0 ]; then
|
||||
echo "No eligible physical disk (>= 30 GB) found to erase." >&2
|
||||
diskutil list physical >&2 || true
|
||||
exit 1
|
||||
else
|
||||
echo "Multiple eligible disks found; specify one explicitly:" >&2
|
||||
printf '%s' "$cand_summary" >&2
|
||||
echo "Run: sh /Volumes/REIMSHELP/install.sh --erase /dev/diskN" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
elif [ -n "$target" ]; then
|
||||
if ! can_write "$target"; then
|
||||
echo "Target volume is missing or read-only: $target" >&2
|
||||
mount | grep /Volumes >&2 || ls /Volumes >&2
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
if target=$(find_writable_target); then
|
||||
:
|
||||
elif command -v diskutil >/dev/null 2>&1; then
|
||||
blank_count=0
|
||||
blank_disk=""
|
||||
blank_desc=""
|
||||
nonblank_count=0
|
||||
nonblank_disk=""
|
||||
nonblank_desc=""
|
||||
all_summary=""
|
||||
for d in $(list_physical_disks); do
|
||||
inspect_candidate_disk "$d"
|
||||
if [ "$cand_ok" -eq 1 ]; then
|
||||
if [ "$cand_blank" -eq 1 ]; then
|
||||
blank_count=$((blank_count + 1))
|
||||
blank_disk=$d
|
||||
blank_desc="$d (${cand_size_human}, ${cand_media:-blank disk})"
|
||||
all_summary="${all_summary} $d ${cand_size_human} (${cand_media:-disk}, blank)
|
||||
"
|
||||
else
|
||||
nonblank_count=$((nonblank_count + 1))
|
||||
nonblank_disk=$d
|
||||
nonblank_desc="$d (${cand_size_human}, ${cand_media:-disk}, ${cand_content:-partitioned})"
|
||||
all_summary="${all_summary} $d ${cand_size_human} (${cand_media:-disk}, ${cand_content:-partitioned})
|
||||
"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$blank_count" -eq 1 ] && [ "$nonblank_count" -eq 0 ]; then
|
||||
echo "No writable volume found; detected blank VM disk: $blank_desc"
|
||||
erase_and_mount "$blank_disk"
|
||||
elif [ "$blank_count" -eq 0 ] && [ "$nonblank_count" -eq 1 ]; then
|
||||
echo "No writable target volume found under /Volumes."
|
||||
echo "Found 1 disk >= 30 GB that already has partitions: $nonblank_desc"
|
||||
if [ -t 0 ]; then
|
||||
printf 'Erase %s as APFS ("Macintosh HD")? All data on it will be lost! [y/N]: ' "$nonblank_disk"
|
||||
IFS= read -r ans || ans=""
|
||||
case "$ans" in
|
||||
y|Y|yes|YES)
|
||||
erase_and_mount "$nonblank_disk"
|
||||
;;
|
||||
*)
|
||||
echo "Aborted. You can erase it in Disk Utility, or re-run with --erase $nonblank_disk" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
else
|
||||
echo "Refusing to erase a non-blank disk non-interactively." >&2
|
||||
echo "Re-run with: sh /Volumes/REIMSHELP/install.sh --erase $nonblank_disk" >&2
|
||||
exit 1
|
||||
fi
|
||||
elif [ $((blank_count + nonblank_count)) -gt 1 ]; then
|
||||
echo "No writable target volume found under /Volumes, and multiple candidate disks exist:" >&2
|
||||
printf '%s' "$all_summary" >&2
|
||||
echo "Re-run with: sh /Volumes/REIMSHELP/install.sh --erase /dev/diskN" >&2
|
||||
echo "Or erase your target disk in Disk Utility first." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$target" ]; then
|
||||
echo "No writable target volume found under /Volumes." >&2
|
||||
echo "Open Disk Utility -> View -> Show All Devices -> select the largest QEMU HARDDISK Media" >&2
|
||||
echo "-> Erase as APFS (GUID Partition Map, name e.g. Macintosh HD), then re-run." >&2
|
||||
mount | grep /Volumes >&2 || ls /Volumes >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Using target volume: $target"
|
||||
|
||||
pkg="/Volumes/Installer/InstallAssistant.pkg"
|
||||
if [ ! -f "$pkg" ]; then
|
||||
echo "Offline installer package not found at $pkg" >&2
|
||||
ls /Volumes >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Extracting Install macOS app onto $target..."
|
||||
tar -xf /Volumes/REIMSHELP/InstallApp.tar -C "$target"
|
||||
|
||||
app=""
|
||||
for a in "$target"/Applications/Install\ macOS*.app; do
|
||||
if [ -d "$a" ]; then app=$a; fi
|
||||
done
|
||||
if [ -z "$app" ] || [ ! -f "$app/Contents/Resources/startosinstall" ]; then
|
||||
echo "Install macOS app not found in $target/Applications after extract" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
shared="$app/Contents/SharedSupport"
|
||||
if [ ! -f "$shared/SharedSupport.dmg" ]; then
|
||||
echo "Copying InstallAssistant.pkg as SharedSupport.dmg (this takes a few minutes)..."
|
||||
mkdir -p "$shared"
|
||||
chmod 0755 "$shared"
|
||||
cp "$pkg" "$shared/SharedSupport.dmg"
|
||||
chflags -h norestricted "$shared/SharedSupport.dmg" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
chmod -R 755 "$app"
|
||||
echo "Starting $app; the VM will restart automatically when ready..."
|
||||
exec "$app/Contents/Resources/startosinstall" --agreetolicense --volume "$target"
|
||||
`)
|
||||
}
|
||||
|
||||
// EnsureOfflineHelperImage prepares (or reuses from cache) a small HFS Plus
|
||||
// helper disk image containing InstallApp.tar + install.sh extracted from an
|
||||
// offline installer image's InstallAssistant.pkg Payload.
|
||||
func EnsureOfflineHelperImage(xdgCacheDir, offlineImgPath string) (string, error) {
|
||||
info, err := os.Stat(offlineImgPath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("stat offline installer: %w", err)
|
||||
}
|
||||
sum := sha256.Sum256([]byte(fmt.Sprintf("%s|%d|%d|v3", filepath.Base(offlineImgPath), info.Size(), info.ModTime().UnixNano())))
|
||||
key := hex.EncodeToString(sum[:8])
|
||||
helperDir := filepath.Join(xdgCacheDir, "reims-go", "offline-helpers")
|
||||
helperPath := filepath.Join(helperDir, fmt.Sprintf("reims-helper-%s.img", key))
|
||||
if st, err := os.Stat(helperPath); err == nil && st.Size() > 0 {
|
||||
return helperPath, nil
|
||||
}
|
||||
|
||||
f, err := os.Open(offlineImgPath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("open offline installer: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
pkgOff, pkgSize, err := FindFileInHFSPlusImage(f, "InstallAssistant.pkg")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("locate InstallAssistant.pkg: %w", err)
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(helperDir, 0o755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
tarFile, err := os.CreateTemp(helperDir, "installapp-*.tar")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
tarPath := tarFile.Name()
|
||||
defer os.Remove(tarPath)
|
||||
|
||||
if err := ExtractPkgPayloadToTar(f, pkgOff, pkgSize, tarFile); err != nil {
|
||||
_ = tarFile.Close()
|
||||
return "", fmt.Errorf("extract InstallAssistant.pkg payload: %w", err)
|
||||
}
|
||||
if err := tarFile.Close(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
tarInfo, err := os.Stat(tarPath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
script := HelperInstallScript()
|
||||
|
||||
files := []HFSFile{
|
||||
{
|
||||
Name: "InstallApp.tar",
|
||||
Mode: 0o100644,
|
||||
Size: tarInfo.Size(),
|
||||
Open: func() (io.ReadCloser, error) { return os.Open(tarPath) },
|
||||
},
|
||||
{
|
||||
Name: "install.sh",
|
||||
Mode: 0o100755,
|
||||
Size: int64(len(script)),
|
||||
Open: func() (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(string(script))), nil },
|
||||
},
|
||||
}
|
||||
if err := BuildHFSPlusDiskImage(helperPath, "REIMSHELP", files); err != nil {
|
||||
return "", fmt.Errorf("build helper disk image: %w", err)
|
||||
}
|
||||
return helperPath, nil
|
||||
}
|
||||
@@ -92,6 +92,13 @@ type offlineResult struct {
|
||||
} `json:"installer"`
|
||||
}
|
||||
|
||||
// onlineResult is the done event's result for online-installer
|
||||
// (reims_util.rs:228-231, 273-277).
|
||||
type onlineResult struct {
|
||||
Title string `json:"title"`
|
||||
Image string `json:"image"`
|
||||
}
|
||||
|
||||
// ErrUtilFailed wraps a reims-util run that ended without a done event.
|
||||
var ErrUtilFailed = errors.New("reims-util failed")
|
||||
|
||||
@@ -208,6 +215,45 @@ func (c *Client) DownloadOffline(ctx context.Context, version string, onUpdate f
|
||||
return &Result{Image: r.Image, Version: r.Installer.Version, Build: r.Installer.Build}, nil
|
||||
}
|
||||
|
||||
// DownloadOnline downloads Apple's ~1 GB online recovery image (BaseSystem.dmg)
|
||||
// via `reims-util online-installer <version> -o <InstallersDir>` (upstream
|
||||
// 3731afd reims_util.rs:246-278), resuming or reusing an existing download.
|
||||
func (c *Client) DownloadOnline(ctx context.Context, version string, onUpdate func(Update)) (*Result, error) {
|
||||
v := strings.TrimSpace(version)
|
||||
if v == "" {
|
||||
v = "latest"
|
||||
}
|
||||
if strings.EqualFold(v, "list") {
|
||||
return nil, errors.New("give the macOS release to download, such as tahoe, 26 or latest")
|
||||
}
|
||||
if onUpdate == nil {
|
||||
onUpdate = func(Update) {}
|
||||
}
|
||||
if err := os.MkdirAll(c.InstallersDir, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
unlock, err := c.lock(ctx, onUpdate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer unlock()
|
||||
|
||||
raw, err := c.run(ctx, onUpdate, "online-installer", v, "-o", c.InstallersDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r onlineResult
|
||||
if err := json.Unmarshal(raw, &r); err != nil {
|
||||
return nil, fmt.Errorf("read reims-util's result: %w", err)
|
||||
}
|
||||
parts := strings.Fields(r.Title)
|
||||
ver := ""
|
||||
if len(parts) > 0 {
|
||||
ver = parts[len(parts)-1]
|
||||
}
|
||||
return &Result{Image: r.Image, Version: ver}, nil
|
||||
}
|
||||
|
||||
// waitingNote is reported once while another download holds the installers
|
||||
// directory.
|
||||
const waitingNote = "waiting for another download of a macOS installer to end"
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
package installer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PinnedAsset describes a file that upstream `reims-util` caches under
|
||||
// `$XDG_CACHE_HOME/reims-util/<Name>` and verifies by SHA-256 before
|
||||
// downloading (reims-util 7867384 src/cache.rs:20-51).
|
||||
type PinnedAsset struct {
|
||||
Name string
|
||||
URL string
|
||||
SHA256 string
|
||||
Step string
|
||||
}
|
||||
|
||||
// OcBinaryDataAsset matches upstream reims-util 7867384
|
||||
// (src/opencore/mod.rs:31-38). GitHub's `/archive/<commit>.zip` ignores Range
|
||||
// requests (always answering HTTP 200 without Content-Length), which interacts
|
||||
// with reims-util's 180s SEGMENT_BUDGET (src/http.rs:25, 291-297, 342-346) to
|
||||
// silently truncate and restart from 0 every 3 minutes on slow connections.
|
||||
// Pre-fetching it with an idle-read timeout avoids that loop while keeping
|
||||
// exact SHA-256 verification.
|
||||
var OcBinaryDataAsset = PinnedAsset{
|
||||
Name: "OcBinaryData-32500d5e3313f11cad00351ba1c6f9a4aa6cb0f7.zip",
|
||||
URL: "https://github.com/acidanthera/OcBinaryData/archive/32500d5e3313f11cad00351ba1c6f9a4aa6cb0f7.zip",
|
||||
SHA256: "1ced15b42352a3a6c1b76ca95951f337fa79899acfb4ed80f329191716623741",
|
||||
Step: "downloading OpenCore's picker icons and boot chime",
|
||||
}
|
||||
|
||||
// ShouldPrefetchOcBinaryData returns true when the installed runtime uses the
|
||||
// reims-util commit (7867384 / 0.1.0) whose pinned OcBinaryData matches
|
||||
// OcBinaryDataAsset.
|
||||
func ShouldPrefetchOcBinaryData(utilCommit, utilVersion string) bool {
|
||||
c := strings.ToLower(strings.TrimSpace(utilCommit))
|
||||
if c != "" {
|
||||
return strings.HasPrefix(c, "7867384")
|
||||
}
|
||||
return strings.Contains(utilVersion, "0.1.0")
|
||||
}
|
||||
|
||||
// EnsureCachedAsset verifies that `<xdgCacheDir>/reims-util/<asset.Name>`
|
||||
// exists with the expected SHA-256, downloading it via HTTP with a per-read
|
||||
// idle timeout (instead of a total-body timeout) if missing or corrupt.
|
||||
func EnsureCachedAsset(ctx context.Context, xdgCacheDir string, asset PinnedAsset, client *http.Client, onUpdate func(Update)) error {
|
||||
if strings.TrimSpace(xdgCacheDir) == "" {
|
||||
return nil
|
||||
}
|
||||
cacheDir := filepath.Join(xdgCacheDir, "reims-util")
|
||||
dest := filepath.Join(cacheDir, asset.Name)
|
||||
if ok, _ := fileMatchesSHA256(dest, asset.SHA256); ok {
|
||||
return nil
|
||||
}
|
||||
if err := os.MkdirAll(cacheDir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if client == nil {
|
||||
client = newIdleHTTPClient(60 * time.Second)
|
||||
}
|
||||
if onUpdate != nil {
|
||||
onUpdate(Update{Kind: KindStep, Message: asset.Step, Percent: -1})
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, asset.URL, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("User-Agent", "reims-go")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("%s answered HTTP %d", asset.URL, resp.StatusCode)
|
||||
}
|
||||
|
||||
part := dest + ".part"
|
||||
f, err := os.Create(part)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h := sha256.New()
|
||||
total := resp.ContentLength
|
||||
if total < 0 {
|
||||
total = 0
|
||||
}
|
||||
buf := make([]byte, 64*1024)
|
||||
var done int64
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
f.Close()
|
||||
_ = os.Remove(part)
|
||||
return err
|
||||
}
|
||||
n, rerr := resp.Body.Read(buf)
|
||||
if n > 0 {
|
||||
if _, werr := f.Write(buf[:n]); werr != nil {
|
||||
f.Close()
|
||||
_ = os.Remove(part)
|
||||
return werr
|
||||
}
|
||||
_, _ = h.Write(buf[:n])
|
||||
done += int64(n)
|
||||
if onUpdate != nil {
|
||||
onUpdate(Update{
|
||||
Kind: KindProgress,
|
||||
Step: asset.Step,
|
||||
Done: done,
|
||||
Total: total,
|
||||
Percent: percentOf(done, total),
|
||||
})
|
||||
}
|
||||
}
|
||||
if rerr == io.EOF {
|
||||
break
|
||||
}
|
||||
if rerr != nil {
|
||||
f.Close()
|
||||
_ = os.Remove(part)
|
||||
return rerr
|
||||
}
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
_ = os.Remove(part)
|
||||
return err
|
||||
}
|
||||
|
||||
got := hex.EncodeToString(h.Sum(nil))
|
||||
if !strings.EqualFold(got, asset.SHA256) {
|
||||
_ = os.Remove(part)
|
||||
return fmt.Errorf("%s SHA-256 mismatch: got %s, want %s", asset.Name, got, asset.SHA256)
|
||||
}
|
||||
_ = os.Remove(dest)
|
||||
if err := os.Rename(part, dest); err != nil {
|
||||
_ = os.Remove(part)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func fileMatchesSHA256(path, want string) (bool, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer f.Close()
|
||||
h := sha256.New()
|
||||
if _, err := io.Copy(h, f); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return strings.EqualFold(hex.EncodeToString(h.Sum(nil)), want), nil
|
||||
}
|
||||
|
||||
// idleTimeoutConn resets the socket read deadline before every Read, so a slow
|
||||
// but steadily progressing stream is never killed by a fixed total duration.
|
||||
type idleTimeoutConn struct {
|
||||
net.Conn
|
||||
idle time.Duration
|
||||
}
|
||||
|
||||
func (c *idleTimeoutConn) Read(p []byte) (int, error) {
|
||||
if c.idle > 0 {
|
||||
_ = c.Conn.SetReadDeadline(time.Now().Add(c.idle))
|
||||
}
|
||||
return c.Conn.Read(p)
|
||||
}
|
||||
|
||||
func newIdleHTTPClient(idle time.Duration) *http.Client {
|
||||
dialer := &net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}
|
||||
tr := &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
conn, err := dialer.DialContext(ctx, network, addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &idleTimeoutConn{Conn: conn, idle: idle}, nil
|
||||
},
|
||||
TLSHandshakeTimeout: 30 * time.Second,
|
||||
ResponseHeaderTimeout: idle,
|
||||
}
|
||||
return &http.Client{Transport: tr}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package installer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEnsureCachedAssetDownloadsChunkedAndSkipsWhenCached(t *testing.T) {
|
||||
payload := []byte(strings.Repeat("opencore-binary-data-", 512))
|
||||
sum := sha256.Sum256(payload)
|
||||
wantHash := hex.EncodeToString(sum[:])
|
||||
|
||||
var hits atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits.Add(1)
|
||||
// Mimic GitHub codeload: HTTP 200 without Content-Length (chunked).
|
||||
flusher, _ := w.(http.Flusher)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
mid := len(payload) / 2
|
||||
_, _ = w.Write(payload[:mid])
|
||||
if flusher != nil {
|
||||
flusher.Flush()
|
||||
}
|
||||
_, _ = w.Write(payload[mid:])
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
cacheRoot := t.TempDir()
|
||||
asset := PinnedAsset{
|
||||
Name: "OcBinaryData-test.zip",
|
||||
URL: srv.URL + "/archive.zip",
|
||||
SHA256: wantHash,
|
||||
Step: "downloading OpenCore's picker icons and boot chime",
|
||||
}
|
||||
|
||||
var updates []Update
|
||||
if err := EnsureCachedAsset(context.Background(), cacheRoot, asset, srv.Client(), func(u Update) {
|
||||
updates = append(updates, u)
|
||||
}); err != nil {
|
||||
t.Fatalf("EnsureCachedAsset failed: %v", err)
|
||||
}
|
||||
if hits.Load() != 1 {
|
||||
t.Fatalf("expected 1 HTTP hit, got %d", hits.Load())
|
||||
}
|
||||
dest := filepath.Join(cacheRoot, "reims-util", asset.Name)
|
||||
gotBytes, err := os.ReadFile(dest)
|
||||
if err != nil || string(gotBytes) != string(payload) {
|
||||
t.Fatalf("cached file mismatch: err=%v len=%d", err, len(gotBytes))
|
||||
}
|
||||
if len(updates) < 2 {
|
||||
t.Fatalf("expected step + progress updates, got %d", len(updates))
|
||||
}
|
||||
|
||||
// Second call must hit cache without another HTTP request.
|
||||
if err := EnsureCachedAsset(context.Background(), cacheRoot, asset, srv.Client(), nil); err != nil {
|
||||
t.Fatalf("second EnsureCachedAsset failed: %v", err)
|
||||
}
|
||||
if hits.Load() != 1 {
|
||||
t.Fatalf("expected cache hit with 0 extra requests, total hits=%d", hits.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureCachedAssetRejectsWrongHash(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte("corrupted"))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
cacheRoot := t.TempDir()
|
||||
asset := PinnedAsset{
|
||||
Name: "OcBinaryData-bad.zip",
|
||||
URL: srv.URL,
|
||||
SHA256: strings.Repeat("0", 64),
|
||||
Step: "downloading",
|
||||
}
|
||||
if err := EnsureCachedAsset(context.Background(), cacheRoot, asset, srv.Client(), nil); err == nil {
|
||||
t.Fatalf("expected hash mismatch error")
|
||||
}
|
||||
dest := filepath.Join(cacheRoot, "reims-util", asset.Name)
|
||||
if _, err := os.Stat(dest); !os.IsNotExist(err) {
|
||||
t.Fatalf("corrupted file should not exist at %s", dest)
|
||||
}
|
||||
if _, err := os.Stat(dest + ".part"); !os.IsNotExist(err) {
|
||||
t.Fatalf("part file should be cleaned up on mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestShouldPrefetchOcBinaryData(t *testing.T) {
|
||||
if !ShouldPrefetchOcBinaryData("7867384abcdef", "reims-util 0.1.0") {
|
||||
t.Fatalf("expected true for pinned commit 7867384")
|
||||
}
|
||||
if !ShouldPrefetchOcBinaryData("", "reims-util 0.1.0") {
|
||||
t.Fatalf("expected true for schema-1 0.1.0")
|
||||
}
|
||||
if ShouldPrefetchOcBinaryData("deadbeef1234", "reims-util 0.2.0") {
|
||||
t.Fatalf("expected false for newer util commit")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
package installer
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/ulikunitz/xz"
|
||||
)
|
||||
|
||||
func buildSyntheticCPIO(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
writeEntry := func(name string, mode int, data []byte) {
|
||||
hdr := fmt.Sprintf("070707%06o%06o%06o%06o%06o%06o%06o%011o%06o%011o",
|
||||
0, 1, mode, 0, 0, 1, 0, 1700000000, len(name)+1, len(data))
|
||||
buf.WriteString(hdr)
|
||||
buf.WriteString(name)
|
||||
buf.WriteByte(0)
|
||||
buf.Write(data)
|
||||
}
|
||||
writeEntry("./Applications", 0o040755, nil)
|
||||
writeEntry("./Applications/Install macOS Tahoe.app", 0o040755, nil)
|
||||
writeEntry("./Applications/Install macOS Tahoe.app/Contents/Resources/startosinstall", 0o100755, []byte("#!/bin/sh\necho ok\n"))
|
||||
writeEntry("./Applications/Install macOS Tahoe.app/Contents/Latest", 0o120777, []byte("Resources/startosinstall"))
|
||||
writeEntry("TRAILER!!!", 0, nil)
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func buildSyntheticPBZX(t *testing.T, raw []byte) []byte {
|
||||
t.Helper()
|
||||
var xzBuf bytes.Buffer
|
||||
xw, err := xz.NewWriter(&xzBuf)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := xw.Write(raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := xw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
comp := xzBuf.Bytes()
|
||||
|
||||
var out bytes.Buffer
|
||||
out.WriteString("pbzx")
|
||||
_ = binary.Write(&out, binary.BigEndian, uint64(0x1000000)) // flags
|
||||
_ = binary.Write(&out, binary.BigEndian, uint64(len(raw)))
|
||||
_ = binary.Write(&out, binary.BigEndian, uint64(len(comp)))
|
||||
out.Write(comp)
|
||||
return out.Bytes()
|
||||
}
|
||||
|
||||
func buildSyntheticXAR(t *testing.T, payload []byte) []byte {
|
||||
t.Helper()
|
||||
tocXML := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<xar><toc><file id="1"><name>Payload</name><type>file</type><data><offset>0</offset><length>%d</length><size>%d</size></data></file></toc></xar>`,
|
||||
len(payload), len(payload))
|
||||
var tocComp bytes.Buffer
|
||||
zw := zlib.NewWriter(&tocComp)
|
||||
_, _ = zw.Write([]byte(tocXML))
|
||||
_ = zw.Close()
|
||||
|
||||
var out bytes.Buffer
|
||||
var hdr [28]byte
|
||||
copy(hdr[0:4], "xar!")
|
||||
binary.BigEndian.PutUint16(hdr[4:6], 28)
|
||||
binary.BigEndian.PutUint16(hdr[6:8], 1)
|
||||
binary.BigEndian.PutUint64(hdr[8:16], uint64(tocComp.Len()))
|
||||
binary.BigEndian.PutUint64(hdr[16:24], uint64(len(tocXML)))
|
||||
binary.BigEndian.PutUint32(hdr[24:28], 1)
|
||||
out.Write(hdr[:])
|
||||
out.Write(tocComp.Bytes())
|
||||
out.Write(payload)
|
||||
return out.Bytes()
|
||||
}
|
||||
|
||||
func TestEnsureOfflineHelperImageRoundTrip(t *testing.T) {
|
||||
cpio := buildSyntheticCPIO(t)
|
||||
pbzx := buildSyntheticPBZX(t, cpio)
|
||||
pkg := buildSyntheticXAR(t, pbzx)
|
||||
|
||||
tmp := t.TempDir()
|
||||
offlineImg := filepath.Join(tmp, "macOS-Tahoe-26.7.3-25G342-offline-installer.img")
|
||||
err := BuildHFSPlusDiskImage(offlineImg, "Installer", []HFSFile{
|
||||
{
|
||||
Name: "InstallAssistant.pkg",
|
||||
Mode: 0o100644,
|
||||
Size: int64(len(pkg)),
|
||||
Open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(pkg)), nil },
|
||||
},
|
||||
{
|
||||
Name: "install-macos.sh",
|
||||
Mode: 0o100755,
|
||||
Size: int64(len("#!/bin/sh\n")),
|
||||
Open: func() (io.ReadCloser, error) { return io.NopCloser(strings.NewReader("#!/bin/sh\n")), nil },
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildHFSPlusDiskImage(offline): %v", err)
|
||||
}
|
||||
|
||||
cacheDir := filepath.Join(tmp, "cache")
|
||||
helperPath, err := EnsureOfflineHelperImage(cacheDir, offlineImg)
|
||||
if err != nil {
|
||||
t.Fatalf("EnsureOfflineHelperImage: %v", err)
|
||||
}
|
||||
|
||||
// Second call must hit cache cleanly.
|
||||
helperPath2, err := EnsureOfflineHelperImage(cacheDir, offlineImg)
|
||||
if err != nil || helperPath2 != helperPath {
|
||||
t.Fatalf("cache reuse mismatch: %q vs %q (err=%v)", helperPath2, helperPath, err)
|
||||
}
|
||||
|
||||
// Verify both install.sh and InstallApp.tar inside generated REIMSHELP HFS+ image.
|
||||
hf, err := os.Open(helperPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer hf.Close()
|
||||
|
||||
shOff, shSize, err := FindFileInHFSPlusImage(hf, "install.sh")
|
||||
if err != nil || shSize == 0 {
|
||||
t.Fatalf("install.sh not found in helper image: err=%v size=%d", err, shSize)
|
||||
}
|
||||
shBytes := make([]byte, shSize)
|
||||
if _, err := hf.ReadAt(shBytes, shOff); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
shText := string(shBytes)
|
||||
for _, want := range []string{
|
||||
"tar -xf /Volumes/REIMSHELP/InstallApp.tar",
|
||||
"can_write()",
|
||||
"is_reserved_vol()",
|
||||
"diskutil list physical",
|
||||
`diskutil eraseDisk APFS "Macintosh HD" GPT`,
|
||||
"Refusing to erase a non-blank disk non-interactively.",
|
||||
"--erase",
|
||||
} {
|
||||
if !strings.Contains(shText, want) {
|
||||
t.Fatalf("install.sh missing expected fragment %q", want)
|
||||
}
|
||||
}
|
||||
|
||||
tarOff, tarSize, err := FindFileInHFSPlusImage(hf, "InstallApp.tar")
|
||||
if err != nil || tarSize == 0 {
|
||||
t.Fatalf("InstallApp.tar not found in helper image: err=%v size=%d", err, tarSize)
|
||||
}
|
||||
tr := tar.NewReader(io.NewSectionReader(hf, tarOff, tarSize))
|
||||
foundBin := false
|
||||
foundSym := false
|
||||
for {
|
||||
hdr, err := tr.Next()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("read tar entry: %v", err)
|
||||
}
|
||||
if hdr.Name == "Applications/Install macOS Tahoe.app/Contents/Resources/startosinstall" {
|
||||
foundBin = true
|
||||
if hdr.Mode&0o111 == 0 {
|
||||
t.Errorf("startosinstall lost execute bit: mode=%o", hdr.Mode)
|
||||
}
|
||||
}
|
||||
if hdr.Name == "Applications/Install macOS Tahoe.app/Contents/Latest" {
|
||||
foundSym = true
|
||||
if hdr.Typeflag != tar.TypeSymlink || hdr.Linkname != "Resources/startosinstall" {
|
||||
t.Errorf("symlink mismatch: type=%v link=%q", hdr.Typeflag, hdr.Linkname)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !foundBin || !foundSym {
|
||||
t.Fatalf("expected both binary and symlink in InstallApp.tar (bin=%v sym=%v)", foundBin, foundSym)
|
||||
}
|
||||
}
|
||||
|
||||
func findPOSIXSh() string {
|
||||
if p, err := exec.LookPath("sh"); err == nil {
|
||||
return p
|
||||
}
|
||||
for _, cand := range []string{
|
||||
`C:\Program Files\Git\bin\sh.exe`,
|
||||
`C:\Program Files\Git\usr\bin\sh.exe`,
|
||||
`D:\DevTools\msys64\usr\bin\sh.exe`,
|
||||
} {
|
||||
if _, err := os.Stat(cand); err == nil {
|
||||
return cand
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestHelperInstallScriptSyntaxAndDiskInspection(t *testing.T) {
|
||||
shBin := findPOSIXSh()
|
||||
if shBin == "" {
|
||||
t.Skip("POSIX sh not available")
|
||||
}
|
||||
tmp := t.TempDir()
|
||||
scriptPath := filepath.Join(tmp, "install.sh")
|
||||
script := string(HelperInstallScript())
|
||||
if err := os.WriteFile(scriptPath, []byte(script), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 1. POSIX sh syntax check.
|
||||
if out, err := exec.Command(shBin, "-n", scriptPath).CombinedOutput(); err != nil {
|
||||
t.Fatalf("sh -n install.sh failed: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
// 2. Behavioral test of the disk-inspection helpers against realistic macOS
|
||||
// Recovery diskutil output (blank VM disk + Installer + REIMSHELP +
|
||||
// OPENCORE + Disk Image + non-blank partitioned disk).
|
||||
cut := strings.Index(script, "\nerase_mode=0")
|
||||
if cut < 0 {
|
||||
t.Fatal("could not locate erase_mode=0 boundary in install.sh")
|
||||
}
|
||||
harness := script[:cut] + `
|
||||
diskutil() {
|
||||
case "$1 $2" in
|
||||
"list physical")
|
||||
cat <<'EOF'
|
||||
/dev/disk0 (internal, physical):
|
||||
#: TYPE NAME SIZE IDENTIFIER
|
||||
0: *137.4 GB disk0
|
||||
|
||||
/dev/disk1 (internal, physical):
|
||||
#: TYPE NAME SIZE IDENTIFIER
|
||||
0: GUID_partition_scheme *19.8 GB disk1
|
||||
1: Apple_HFS Installer 19.8 GB disk1s1
|
||||
|
||||
/dev/disk2 (external, physical):
|
||||
#: TYPE NAME SIZE IDENTIFIER
|
||||
0: GUID_partition_scheme *134.2 MB disk2
|
||||
1: Apple_HFS REIMSHELP 134.2 MB disk2s1
|
||||
|
||||
/dev/disk3 (internal, physical):
|
||||
#: TYPE NAME SIZE IDENTIFIER
|
||||
0: GUID_partition_scheme *134.2 MB disk3
|
||||
1: EFI OPENCORE 134.2 MB disk3s1
|
||||
|
||||
/dev/disk4 (disk image):
|
||||
#: TYPE NAME SIZE IDENTIFIER
|
||||
0: GUID_partition_scheme +2.1 GB disk4
|
||||
|
||||
/dev/disk5 (internal, physical):
|
||||
#: TYPE NAME SIZE IDENTIFIER
|
||||
0: GUID_partition_scheme *137.4 GB disk5
|
||||
1: EFI EFI 209.7 MB disk5s1
|
||||
2: Apple_APFS Container disk6 137.2 GB disk5s2
|
||||
|
||||
/dev/disk7 (internal, physical):
|
||||
#: TYPE NAME SIZE IDENTIFIER
|
||||
0: GUID_partition_scheme *64.0 GB disk7
|
||||
1: Apple_HFS Installer 64.0 GB disk7s1
|
||||
EOF
|
||||
;;
|
||||
"info /dev/disk0")
|
||||
cat <<'EOF'
|
||||
Device Identifier: disk0
|
||||
Whole: Yes
|
||||
Device / Media Name: QEMU HARDDISK
|
||||
Virtual: No
|
||||
Protocol: SATA
|
||||
Read-Only Media: No
|
||||
Content (IOContent): None
|
||||
Disk Size: 137.4 GB (137438953472 Bytes) (exactly 268435456 512-Byte-Units)
|
||||
EOF
|
||||
;;
|
||||
"list /dev/disk0")
|
||||
cat <<'EOF'
|
||||
/dev/disk0 (internal, physical):
|
||||
#: TYPE NAME SIZE IDENTIFIER
|
||||
0: *137.4 GB disk0
|
||||
EOF
|
||||
;;
|
||||
"info /dev/disk1")
|
||||
cat <<'EOF'
|
||||
Whole: Yes
|
||||
Virtual: No
|
||||
Protocol: SATA
|
||||
Read-Only Media: No
|
||||
Content (IOContent): GUID_partition_scheme
|
||||
Disk Size: 19.8 GB (19800000000 Bytes)
|
||||
EOF
|
||||
;;
|
||||
"list /dev/disk1")
|
||||
cat <<'EOF'
|
||||
0: GUID_partition_scheme *19.8 GB disk1
|
||||
1: Apple_HFS Installer 19.8 GB disk1s1
|
||||
EOF
|
||||
;;
|
||||
"info /dev/disk2")
|
||||
cat <<'EOF'
|
||||
Whole: Yes
|
||||
Virtual: No
|
||||
Protocol: USB
|
||||
Read-Only Media: Yes
|
||||
Content (IOContent): GUID_partition_scheme
|
||||
Disk Size: 134.2 MB (134217728 Bytes)
|
||||
EOF
|
||||
;;
|
||||
"list /dev/disk2")
|
||||
cat <<'EOF'
|
||||
0: GUID_partition_scheme *134.2 MB disk2
|
||||
1: Apple_HFS REIMSHELP 134.2 MB disk2s1
|
||||
EOF
|
||||
;;
|
||||
"info /dev/disk3")
|
||||
cat <<'EOF'
|
||||
Whole: Yes
|
||||
Virtual: No
|
||||
Protocol: SATA
|
||||
Read-Only Media: No
|
||||
Content (IOContent): GUID_partition_scheme
|
||||
Disk Size: 134.2 MB (134217728 Bytes)
|
||||
EOF
|
||||
;;
|
||||
"list /dev/disk3")
|
||||
cat <<'EOF'
|
||||
0: GUID_partition_scheme *134.2 MB disk3
|
||||
1: EFI OPENCORE 134.2 MB disk3s1
|
||||
EOF
|
||||
;;
|
||||
"info /dev/disk5")
|
||||
cat <<'EOF'
|
||||
Whole: Yes
|
||||
Device / Media Name: QEMU HARDDISK
|
||||
Virtual: No
|
||||
Protocol: SATA
|
||||
Read-Only Media: No
|
||||
Content (IOContent): GUID_partition_scheme
|
||||
Disk Size: 137.4 GB (137438953472 Bytes)
|
||||
EOF
|
||||
;;
|
||||
"list /dev/disk5")
|
||||
cat <<'EOF'
|
||||
0: GUID_partition_scheme *137.4 GB disk5
|
||||
1: EFI EFI 209.7 MB disk5s1
|
||||
2: Apple_APFS Container disk6 137.2 GB disk5s2
|
||||
EOF
|
||||
;;
|
||||
"info /dev/disk7")
|
||||
cat <<'EOF'
|
||||
Whole: Yes
|
||||
Virtual: No
|
||||
Protocol: SATA
|
||||
Read-Only Media: No
|
||||
Content (IOContent): GUID_partition_scheme
|
||||
Disk Size: 64.0 GB (64000000000 Bytes)
|
||||
EOF
|
||||
;;
|
||||
"list /dev/disk7")
|
||||
cat <<'EOF'
|
||||
0: GUID_partition_scheme *64.0 GB disk7
|
||||
1: Apple_HFS Installer 64.0 GB disk7s1
|
||||
EOF
|
||||
;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
echo "MB1=$(bytes_to_mb 137438953472)"
|
||||
echo "MB2=$(bytes_to_mb 500000)"
|
||||
echo "MB3=$(bytes_to_mb invalid)"
|
||||
for d in $(list_physical_disks); do
|
||||
inspect_candidate_disk "$d"
|
||||
echo "DISK=$d ok=$cand_ok blank=$cand_blank size=$cand_size_human reason=$cand_reason"
|
||||
done
|
||||
`
|
||||
harnessPath := filepath.Join(tmp, "harness.sh")
|
||||
if err := os.WriteFile(harnessPath, []byte(harness), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outBytes, err := exec.Command(shBin, harnessPath).CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("harness failed: %v\n%s", err, outBytes)
|
||||
}
|
||||
out := string(outBytes)
|
||||
for _, want := range []string{
|
||||
"MB1=137438",
|
||||
"MB2=0",
|
||||
"MB3=0",
|
||||
"DISK=/dev/disk0 ok=1 blank=1 size=137.4 GB reason=",
|
||||
"DISK=/dev/disk1 ok=0 blank=0 size=19.8 GB reason=too small",
|
||||
"DISK=/dev/disk2 ok=0 blank=0 size= reason=read-only media",
|
||||
"DISK=/dev/disk3 ok=0 blank=0 size=134.2 MB reason=too small",
|
||||
"DISK=/dev/disk5 ok=1 blank=0 size=137.4 GB reason=",
|
||||
"DISK=/dev/disk7 ok=0 blank=0 size=64.0 GB reason=contains reserved/installer volume",
|
||||
} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("missing expected output line %q\nfull output:\n%s", want, out)
|
||||
}
|
||||
}
|
||||
if strings.Contains(out, "DISK=/dev/disk4") {
|
||||
t.Errorf("disk image /dev/disk4 should have been filtered out by list_physical_disks\nfull output:\n%s", out)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
package installer
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bufio"
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"compress/zlib"
|
||||
"encoding/binary"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf16"
|
||||
|
||||
"github.com/ulikunitz/xz"
|
||||
)
|
||||
|
||||
// appleHFSPlusGUID is Apple's HFS Plus GPT partition type
|
||||
// (48465300-0000-11AA-AA11-00306543ECAC) in on-disk mixed-endian form.
|
||||
var appleHFSPlusGUID = [16]byte{
|
||||
0x00, 0x53, 0x46, 0x48, 0x00, 0x00, 0xAA, 0x11,
|
||||
0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC,
|
||||
}
|
||||
|
||||
// FindFileInHFSPlusImage locates a root-level file inside the first HFS Plus
|
||||
// GPT partition of an offline installer disk image (as built by reims-util's
|
||||
// src/image/hfsplus.rs). If f itself is a standalone XAR archive, returns 0.
|
||||
func FindFileInHFSPlusImage(f *os.File, targetName string) (offset, size int64, err error) {
|
||||
info, err := f.Stat()
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
var magic [4]byte
|
||||
if _, err := f.ReadAt(magic[:], 0); err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
if string(magic[:]) == "xar!" {
|
||||
return 0, info.Size(), nil
|
||||
}
|
||||
|
||||
// Read primary GPT header at LBA 1 (512 bytes).
|
||||
var gptHdr [512]byte
|
||||
if _, err := f.ReadAt(gptHdr[:], 512); err != nil {
|
||||
return 0, 0, fmt.Errorf("read GPT header: %w", err)
|
||||
}
|
||||
if string(gptHdr[0:8]) != "EFI PART" {
|
||||
return 0, 0, errors.New("image has no GPT header")
|
||||
}
|
||||
entriesLBA := binary.LittleEndian.Uint64(gptHdr[72:80])
|
||||
numEntries := binary.LittleEndian.Uint32(gptHdr[80:84])
|
||||
entrySize := binary.LittleEndian.Uint32(gptHdr[84:88])
|
||||
if entrySize < 128 || numEntries == 0 || numEntries > 1024 {
|
||||
return 0, 0, fmt.Errorf("invalid GPT table (entries=%d size=%d)", numEntries, entrySize)
|
||||
}
|
||||
|
||||
var partStart int64 = -1
|
||||
entryBuf := make([]byte, entrySize)
|
||||
for i := uint32(0); i < numEntries; i++ {
|
||||
pos := int64(entriesLBA)*512 + int64(i)*int64(entrySize)
|
||||
if _, err := f.ReadAt(entryBuf, pos); err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
if bytes.Equal(entryBuf[0:16], appleHFSPlusGUID[:]) {
|
||||
firstLBA := binary.LittleEndian.Uint64(entryBuf[32:40])
|
||||
partStart = int64(firstLBA) * 512
|
||||
break
|
||||
}
|
||||
}
|
||||
if partStart < 0 {
|
||||
return 0, 0, errors.New("no HFS Plus partition found in image")
|
||||
}
|
||||
|
||||
// HFSPlusVolumeHeader starts 1024 bytes into the partition.
|
||||
var vh [512]byte
|
||||
if _, err := f.ReadAt(vh[:], partStart+1024); err != nil {
|
||||
return 0, 0, fmt.Errorf("read HFS+ volume header: %w", err)
|
||||
}
|
||||
if string(vh[0:2]) != "H+" {
|
||||
return 0, 0, fmt.Errorf("unexpected HFS+ signature %q", string(vh[0:2]))
|
||||
}
|
||||
blockSize := int64(binary.BigEndian.Uint32(vh[40:44]))
|
||||
if blockSize == 0 || blockSize%512 != 0 {
|
||||
return 0, 0, fmt.Errorf("invalid HFS+ block size %d", blockSize)
|
||||
}
|
||||
|
||||
// Catalog file HFSPlusForkData sits at offset 272 in the volume header.
|
||||
catStartBlock := int64(binary.BigEndian.Uint32(vh[272+16 : 272+20]))
|
||||
catBlockCount := int64(binary.BigEndian.Uint32(vh[272+20 : 272+24]))
|
||||
if catBlockCount == 0 {
|
||||
return 0, 0, errors.New("HFS+ catalog file is empty")
|
||||
}
|
||||
catBase := partStart + catStartBlock*blockSize
|
||||
|
||||
// Read B-Tree header node (first 512 bytes suffice for descriptor + header record).
|
||||
var btHdr [512]byte
|
||||
if _, err := f.ReadAt(btHdr[:], catBase); err != nil {
|
||||
return 0, 0, fmt.Errorf("read HFS+ catalog header: %w", err)
|
||||
}
|
||||
nodeSize := int64(binary.BigEndian.Uint16(btHdr[32:34]))
|
||||
firstLeaf := binary.BigEndian.Uint32(btHdr[24:28])
|
||||
totalNodes := binary.BigEndian.Uint32(btHdr[36:40])
|
||||
if nodeSize < 512 || firstLeaf == 0 {
|
||||
return 0, 0, errors.New("HFS+ catalog has no leaf nodes")
|
||||
}
|
||||
|
||||
nodeBuf := make([]byte, nodeSize)
|
||||
curNode := firstLeaf
|
||||
for steps := uint32(0); curNode != 0 && steps < totalNodes && steps < 4096; steps++ {
|
||||
if _, err := f.ReadAt(nodeBuf, catBase+int64(curNode)*nodeSize); err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
fLink := binary.BigEndian.Uint32(nodeBuf[0:4])
|
||||
kind := int8(nodeBuf[8])
|
||||
numRecs := int(binary.BigEndian.Uint16(nodeBuf[10:12]))
|
||||
if kind != -1 {
|
||||
break
|
||||
}
|
||||
for r := 0; r < numRecs; r++ {
|
||||
offPos := int(nodeSize) - 2 - 2*r
|
||||
recOff := int(binary.BigEndian.Uint16(nodeBuf[offPos : offPos+2]))
|
||||
if recOff+8 > int(nodeSize) {
|
||||
continue
|
||||
}
|
||||
keyLen := int(binary.BigEndian.Uint16(nodeBuf[recOff : recOff+2]))
|
||||
if keyLen < 6 || recOff+2+keyLen > int(nodeSize) {
|
||||
continue
|
||||
}
|
||||
parentID := binary.BigEndian.Uint32(nodeBuf[recOff+2 : recOff+6])
|
||||
nameChars := int(binary.BigEndian.Uint16(nodeBuf[recOff+6 : recOff+8]))
|
||||
if parentID != 2 || 6+2*nameChars > keyLen {
|
||||
continue
|
||||
}
|
||||
u16 := make([]uint16, nameChars)
|
||||
for i := 0; i < nameChars; i++ {
|
||||
u16[i] = binary.BigEndian.Uint16(nodeBuf[recOff+8+2*i : recOff+10+2*i])
|
||||
}
|
||||
name := string(utf16.Decode(u16))
|
||||
if !strings.EqualFold(name, targetName) {
|
||||
continue
|
||||
}
|
||||
// Catalog record starts right after key (padded to 2-byte boundary).
|
||||
dataOff := recOff + 2 + keyLen
|
||||
if dataOff%2 != 0 {
|
||||
dataOff++
|
||||
}
|
||||
if dataOff+168 > int(nodeSize) {
|
||||
return 0, 0, errors.New("truncated HFS+ file record")
|
||||
}
|
||||
recType := binary.BigEndian.Uint16(nodeBuf[dataOff : dataOff+2])
|
||||
if recType != 2 { // kHFSPlusFileRecord
|
||||
continue
|
||||
}
|
||||
// Data fork is at +88 inside HFSPlusCatalogFile.
|
||||
forkOff := dataOff + 88
|
||||
logicalSize := int64(binary.BigEndian.Uint64(nodeBuf[forkOff : forkOff+8]))
|
||||
startBlock := int64(binary.BigEndian.Uint32(nodeBuf[forkOff+16 : forkOff+20]))
|
||||
return partStart + startBlock*blockSize, logicalSize, nil
|
||||
}
|
||||
curNode = fLink
|
||||
}
|
||||
return 0, 0, fmt.Errorf("%s not found in HFS+ root folder", targetName)
|
||||
}
|
||||
|
||||
type xarTOC struct {
|
||||
Files []xarFile `xml:"toc>file"`
|
||||
}
|
||||
|
||||
type xarFile struct {
|
||||
Name string `xml:"name"`
|
||||
Type string `xml:"type"`
|
||||
Data *xarData `xml:"data"`
|
||||
Files []xarFile `xml:"file"`
|
||||
}
|
||||
|
||||
type xarData struct {
|
||||
Offset int64 `xml:"offset"`
|
||||
Length int64 `xml:"length"`
|
||||
Size int64 `xml:"size"`
|
||||
}
|
||||
|
||||
func findXARPayload(files []xarFile) *xarData {
|
||||
var best *xarData
|
||||
var walk func([]xarFile)
|
||||
walk = func(list []xarFile) {
|
||||
for i := range list {
|
||||
f := &list[i]
|
||||
if f.Name == "Payload" && f.Data != nil && f.Data.Length > 0 {
|
||||
if best == nil || f.Data.Length > best.Length {
|
||||
best = f.Data
|
||||
}
|
||||
}
|
||||
if len(f.Files) > 0 {
|
||||
walk(f.Files)
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(files)
|
||||
return best
|
||||
}
|
||||
|
||||
// ExtractPkgPayloadToTar extracts the Payload CPIO archive from a macOS
|
||||
// InstallAssistant.pkg (XAR + PBZX/XZ/gzip + CPIO) directly into a POSIX tar
|
||||
// stream, preserving executable modes and symlinks for macOS Recovery.
|
||||
func ExtractPkgPayloadToTar(r io.ReaderAt, pkgOffset, pkgSize int64, tarOut io.Writer) error {
|
||||
var hdr [28]byte
|
||||
if _, err := r.ReadAt(hdr[:], pkgOffset); err != nil {
|
||||
return fmt.Errorf("read XAR header: %w", err)
|
||||
}
|
||||
if string(hdr[0:4]) != "xar!" {
|
||||
return fmt.Errorf("not a XAR archive (magic %x)", hdr[0:4])
|
||||
}
|
||||
hdrSize := int64(binary.BigEndian.Uint16(hdr[4:6]))
|
||||
tocCompLen := int64(binary.BigEndian.Uint64(hdr[8:16]))
|
||||
if hdrSize < 28 || tocCompLen <= 0 || tocCompLen > 64<<20 {
|
||||
return fmt.Errorf("invalid XAR TOC length %d", tocCompLen)
|
||||
}
|
||||
|
||||
zr, err := zlib.NewReader(io.NewSectionReader(r, pkgOffset+hdrSize, tocCompLen))
|
||||
if err != nil {
|
||||
return fmt.Errorf("decompress XAR TOC: %w", err)
|
||||
}
|
||||
defer zr.Close()
|
||||
tocBytes, err := io.ReadAll(io.LimitReader(zr, 64<<20))
|
||||
if err != nil {
|
||||
return fmt.Errorf("read XAR TOC: %w", err)
|
||||
}
|
||||
|
||||
var toc xarTOC
|
||||
if err := xml.Unmarshal(tocBytes, &toc); err != nil {
|
||||
return fmt.Errorf("parse XAR TOC XML: %w", err)
|
||||
}
|
||||
payload := findXARPayload(toc.Files)
|
||||
if payload == nil {
|
||||
return errors.New("XAR package has no Payload entry")
|
||||
}
|
||||
heapBase := pkgOffset + hdrSize + tocCompLen
|
||||
if payload.Offset+payload.Length > pkgSize {
|
||||
return errors.New("XAR Payload exceeds package bounds")
|
||||
}
|
||||
|
||||
sec := io.NewSectionReader(r, heapBase+payload.Offset, payload.Length)
|
||||
cpioReader, closeFn, err := openPayloadStream(sec)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer closeFn()
|
||||
|
||||
return cpioToTar(cpioReader, tarOut)
|
||||
}
|
||||
|
||||
func openPayloadStream(r io.Reader) (io.Reader, func(), error) {
|
||||
br := bufio.NewReaderSize(r, 64*1024)
|
||||
magic, err := br.Peek(6)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("peek payload magic: %w", err)
|
||||
}
|
||||
switch {
|
||||
case bytes.Equal(magic[:4], []byte("pbzx")):
|
||||
return newPBZXReader(br), func() {}, nil
|
||||
case magic[0] == 0x1f && magic[1] == 0x8b:
|
||||
gr, err := gzip.NewReader(br)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("open gzip payload: %w", err)
|
||||
}
|
||||
return gr, func() { _ = gr.Close() }, nil
|
||||
case bytes.Equal(magic[:6], []byte{0xfd, '7', 'z', 'X', 'Z', 0x00}):
|
||||
xr, err := xz.NewReader(br)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("open xz payload: %w", err)
|
||||
}
|
||||
return xr, func() {}, nil
|
||||
case bytes.Equal(magic[:6], []byte("070707")):
|
||||
return br, func() {}, nil
|
||||
default:
|
||||
return nil, nil, fmt.Errorf("unsupported Payload compression magic %x", magic)
|
||||
}
|
||||
}
|
||||
|
||||
// pbzxReader decodes Apple's PBZX chunked stream into a contiguous CPIO stream.
|
||||
type pbzxReader struct {
|
||||
src io.Reader
|
||||
started bool
|
||||
cur io.Reader
|
||||
curLeft int64
|
||||
}
|
||||
|
||||
func newPBZXReader(src io.Reader) *pbzxReader {
|
||||
return &pbzxReader{src: src}
|
||||
}
|
||||
|
||||
func (p *pbzxReader) Read(buf []byte) (int, error) {
|
||||
if !p.started {
|
||||
var head [12]byte // "pbzx" (4) + flags (8)
|
||||
if _, err := io.ReadFull(p.src, head[:]); err != nil {
|
||||
return 0, fmt.Errorf("read pbzx header: %w", err)
|
||||
}
|
||||
if string(head[:4]) != "pbzx" {
|
||||
return 0, errors.New("invalid pbzx header")
|
||||
}
|
||||
p.started = true
|
||||
}
|
||||
for {
|
||||
if p.cur != nil {
|
||||
n, err := p.cur.Read(buf)
|
||||
if n > 0 {
|
||||
return n, nil
|
||||
}
|
||||
if err == io.EOF {
|
||||
p.cur = nil
|
||||
continue
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
var chunkHdr [16]byte
|
||||
if _, err := io.ReadFull(p.src, chunkHdr[:]); err != nil {
|
||||
if err == io.EOF {
|
||||
return 0, io.EOF
|
||||
}
|
||||
return 0, fmt.Errorf("read pbzx chunk header: %w", err)
|
||||
}
|
||||
uncompLen := binary.BigEndian.Uint64(chunkHdr[0:8])
|
||||
compLen := binary.BigEndian.Uint64(chunkHdr[8:16])
|
||||
if compLen == 0 {
|
||||
continue
|
||||
}
|
||||
limited := io.LimitReader(p.src, int64(compLen))
|
||||
if compLen == uncompLen {
|
||||
p.cur = limited
|
||||
continue
|
||||
}
|
||||
// Compressed PBZX chunks are standalone XZ streams (0xfd 37 7a 58 5a 00).
|
||||
data, err := io.ReadAll(limited)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read pbzx chunk: %w", err)
|
||||
}
|
||||
if len(data) >= 6 && bytes.Equal(data[:6], []byte{0xfd, '7', 'z', 'X', 'Z', 0x00}) {
|
||||
xr, err := xz.NewReader(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("decode pbzx xz chunk: %w", err)
|
||||
}
|
||||
p.cur = xr
|
||||
} else {
|
||||
p.cur = bytes.NewReader(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// cpioToTar converts a POSIX ODC CPIO ("070707") stream into a PAX tar archive.
|
||||
func cpioToTar(r io.Reader, out io.Writer) error {
|
||||
tw := tar.NewWriter(out)
|
||||
var hdr [76]byte
|
||||
for {
|
||||
if _, err := io.ReadFull(r, hdr[:]); err != nil {
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
return fmt.Errorf("read cpio header: %w", err)
|
||||
}
|
||||
if string(hdr[0:6]) != "070707" {
|
||||
return fmt.Errorf("unsupported cpio magic %q (expected 070707)", string(hdr[0:6]))
|
||||
}
|
||||
mode, err := strconv.ParseInt(string(hdr[18:24]), 8, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse cpio mode: %w", err)
|
||||
}
|
||||
mtime, _ := strconv.ParseInt(string(hdr[48:59]), 8, 64)
|
||||
nameSize, err := strconv.ParseInt(string(hdr[59:65]), 8, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse cpio namesize: %w", err)
|
||||
}
|
||||
fileSize, err := strconv.ParseInt(string(hdr[65:76]), 8, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse cpio filesize: %w", err)
|
||||
}
|
||||
nameBuf := make([]byte, nameSize)
|
||||
if _, err := io.ReadFull(r, nameBuf); err != nil {
|
||||
return fmt.Errorf("read cpio name: %w", err)
|
||||
}
|
||||
name := strings.TrimRight(string(nameBuf), "\x00")
|
||||
if name == "TRAILER!!!" {
|
||||
break
|
||||
}
|
||||
name = strings.TrimPrefix(name, "./")
|
||||
name = strings.TrimPrefix(name, "/")
|
||||
if name == "" || name == "." {
|
||||
if fileSize > 0 {
|
||||
if _, err := io.CopyN(io.Discard, r, fileSize); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
fileType := mode & 0o170000
|
||||
perm := mode & 0o7777
|
||||
th := &tar.Header{
|
||||
Name: name,
|
||||
Mode: perm,
|
||||
}
|
||||
if mtime > 0 {
|
||||
th.ModTime = th.ModTime.Add(0)
|
||||
}
|
||||
switch fileType {
|
||||
case 0o040000: // directory
|
||||
th.Typeflag = tar.TypeDir
|
||||
if !strings.HasSuffix(th.Name, "/") {
|
||||
th.Name += "/"
|
||||
}
|
||||
if err := tw.WriteHeader(th); err != nil {
|
||||
return err
|
||||
}
|
||||
if fileSize > 0 {
|
||||
if _, err := io.CopyN(io.Discard, r, fileSize); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case 0o120000: // symlink
|
||||
linkBuf := make([]byte, fileSize)
|
||||
if _, err := io.ReadFull(r, linkBuf); err != nil {
|
||||
return err
|
||||
}
|
||||
th.Typeflag = tar.TypeSymlink
|
||||
th.Linkname = string(linkBuf)
|
||||
if err := tw.WriteHeader(th); err != nil {
|
||||
return err
|
||||
}
|
||||
case 0o100000: // regular file
|
||||
th.Typeflag = tar.TypeReg
|
||||
th.Size = fileSize
|
||||
if err := tw.WriteHeader(th); err != nil {
|
||||
return err
|
||||
}
|
||||
if fileSize > 0 {
|
||||
if _, err := io.CopyN(tw, r, fileSize); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
default:
|
||||
if fileSize > 0 {
|
||||
if _, err := io.CopyN(io.Discard, r, fileSize); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return tw.Close()
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package qmp
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Conn is a request/response QMP session. QEMU's QMP chardev serves one
|
||||
// client at a time, so callers keep a Conn only as long as one job takes.
|
||||
type Conn struct {
|
||||
nc net.Conn
|
||||
scanner *bufio.Scanner
|
||||
}
|
||||
|
||||
// Dial connects to a QMP server ("unix" or "tcp") and negotiates capabilities.
|
||||
func Dial(ctx context.Context, network, addr string) (*Conn, error) {
|
||||
d := net.Dialer{Timeout: 3 * time.Second}
|
||||
nc, err := d.DialContext(ctx, network, addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connect QMP %s: %w", addr, err)
|
||||
}
|
||||
c := &Conn{nc: nc, scanner: bufio.NewScanner(nc)}
|
||||
c.scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
|
||||
|
||||
_ = nc.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
if !c.scanner.Scan() { // greeting
|
||||
nc.Close()
|
||||
if err := c.scanner.Err(); err != nil {
|
||||
return nil, fmt.Errorf("QMP greeting: %w", err)
|
||||
}
|
||||
return nil, fmt.Errorf("QMP greeting: connection closed")
|
||||
}
|
||||
if err := c.Execute("qmp_capabilities", nil); err != nil {
|
||||
nc.Close()
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *Conn) Close() error { return c.nc.Close() }
|
||||
|
||||
type qmpReply struct {
|
||||
Return json.RawMessage `json:"return"`
|
||||
Error *struct {
|
||||
Class string `json:"class"`
|
||||
Desc string `json:"desc"`
|
||||
} `json:"error"`
|
||||
Event string `json:"event"`
|
||||
}
|
||||
|
||||
// Execute runs one command and waits for its reply, skipping async events.
|
||||
func (c *Conn) Execute(command string, args any) error {
|
||||
req := map[string]any{"execute": command}
|
||||
if args != nil {
|
||||
req["arguments"] = args
|
||||
}
|
||||
b, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_ = c.nc.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
if _, err := c.nc.Write(append(b, '\n')); err != nil {
|
||||
return fmt.Errorf("QMP %s: %w", command, err)
|
||||
}
|
||||
for c.scanner.Scan() {
|
||||
var r qmpReply
|
||||
if err := json.Unmarshal(c.scanner.Bytes(), &r); err != nil || r.Event != "" {
|
||||
continue
|
||||
}
|
||||
if r.Error != nil {
|
||||
return fmt.Errorf("QMP %s: %s: %s", command, r.Error.Class, r.Error.Desc)
|
||||
}
|
||||
if r.Return != nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if err := c.scanner.Err(); err != nil {
|
||||
return fmt.Errorf("QMP %s: %w", command, err)
|
||||
}
|
||||
return fmt.Errorf("QMP %s: connection closed", command)
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package qmp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Typing text into a guest as key presses ("paste as keystrokes"). The guest
|
||||
// sees a USB keyboard (`usb-kbd` in `reims-ctl command`, upstream 3731afd), so
|
||||
// what each key produces depends on the guest's input source: the mapping
|
||||
// below is the US / "ABC" layout macOS Recovery and a new install start with.
|
||||
|
||||
// Stroke is one key, pressed with or without Shift.
|
||||
type Stroke struct {
|
||||
Key string // QKeyCode name, as QMP's input-send-event takes it
|
||||
Shift bool
|
||||
}
|
||||
|
||||
// MaxTypedRunes caps one job: at ~30 ms a key, 4000 keys take two minutes.
|
||||
const MaxTypedRunes = 4000
|
||||
|
||||
// UntypeableError names the first character a US keyboard can't type.
|
||||
type UntypeableError struct {
|
||||
Rune rune
|
||||
Pos int // 1-based character position
|
||||
}
|
||||
|
||||
func (e *UntypeableError) Error() string {
|
||||
return fmt.Sprintf("character %q (U+%04X) at position %d can't be typed on a US keyboard", e.Rune, e.Rune, e.Pos)
|
||||
}
|
||||
|
||||
var plainKeys = map[rune]string{
|
||||
' ': "spc", '\n': "ret", '\t': "tab",
|
||||
'-': "minus", '=': "equal", '[': "bracket_left", ']': "bracket_right",
|
||||
'\\': "backslash", ';': "semicolon", '\'': "apostrophe", '`': "grave_accent",
|
||||
',': "comma", '.': "dot", '/': "slash",
|
||||
}
|
||||
|
||||
var shiftedKeys = map[rune]string{
|
||||
'!': "1", '@': "2", '#': "3", '$': "4", '%': "5", '^': "6", '&': "7", '*': "8", '(': "9", ')': "0",
|
||||
'_': "minus", '+': "equal", '{': "bracket_left", '}': "bracket_right", '|': "backslash",
|
||||
':': "semicolon", '"': "apostrophe", '~': "grave_accent", '<': "comma", '>': "dot", '?': "slash",
|
||||
}
|
||||
|
||||
// StrokeFor maps one character to a key on a US layout.
|
||||
func StrokeFor(r rune) (Stroke, bool) {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
|
||||
return Stroke{Key: string(r)}, true
|
||||
case r >= 'A' && r <= 'Z':
|
||||
return Stroke{Key: string(r - 'A' + 'a'), Shift: true}, true
|
||||
}
|
||||
if k, ok := plainKeys[r]; ok {
|
||||
return Stroke{Key: k}, true
|
||||
}
|
||||
if k, ok := shiftedKeys[r]; ok {
|
||||
return Stroke{Key: k, Shift: true}, true
|
||||
}
|
||||
return Stroke{}, false
|
||||
}
|
||||
|
||||
// Strokes turns text into key presses. It refuses the whole text if any
|
||||
// character can't be typed, so a command is never typed half-way. Windows line
|
||||
// ends become one Return.
|
||||
func Strokes(text string) ([]Stroke, error) {
|
||||
text = strings.ReplaceAll(text, "\r\n", "\n")
|
||||
text = strings.ReplaceAll(text, "\r", "\n")
|
||||
out := make([]Stroke, 0, len(text))
|
||||
pos := 0
|
||||
for _, r := range text {
|
||||
pos++
|
||||
if pos > MaxTypedRunes {
|
||||
return nil, fmt.Errorf("text is longer than %d characters", MaxTypedRunes)
|
||||
}
|
||||
s, ok := StrokeFor(r)
|
||||
if !ok {
|
||||
return nil, &UntypeableError{Rune: r, Pos: pos}
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Executor is the part of a QMP session typing needs.
|
||||
type Executor interface {
|
||||
Execute(command string, args any) error
|
||||
}
|
||||
|
||||
func keyEvent(key string, down bool) map[string]any {
|
||||
return map[string]any{
|
||||
"type": "key",
|
||||
"data": map[string]any{
|
||||
"down": down,
|
||||
"key": map[string]any{"type": "qcode", "data": key},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func sendKeys(q Executor, down bool, keys ...string) error {
|
||||
events := make([]map[string]any, 0, len(keys))
|
||||
for _, k := range keys {
|
||||
events = append(events, keyEvent(k, down))
|
||||
}
|
||||
return q.Execute("input-send-event", map[string]any{"events": events})
|
||||
}
|
||||
|
||||
// TypeStrokes presses and releases each key in turn, holding it for hold and
|
||||
// waiting gap before the next, so the guest's USB keyboard queue never fills.
|
||||
// On any error or cancel it releases Shift so no modifier is left held down.
|
||||
func TypeStrokes(ctx context.Context, q Executor, strokes []Stroke, hold, gap time.Duration, progress func(done int)) (err error) {
|
||||
shiftDown := false
|
||||
defer func() {
|
||||
if shiftDown {
|
||||
_ = sendKeys(q, false, "shift")
|
||||
}
|
||||
}()
|
||||
for i, s := range strokes {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.Shift != shiftDown {
|
||||
if err := sendKeys(q, s.Shift, "shift"); err != nil {
|
||||
return err
|
||||
}
|
||||
shiftDown = s.Shift
|
||||
}
|
||||
if err := sendKeys(q, true, s.Key); err != nil {
|
||||
return err
|
||||
}
|
||||
sleep(ctx, hold)
|
||||
if err := sendKeys(q, false, s.Key); err != nil {
|
||||
return err
|
||||
}
|
||||
sleep(ctx, gap)
|
||||
if progress != nil {
|
||||
progress(i + 1)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SocketPath is the QMP socket reims-ctl gives every VM it starts: `-qmp
|
||||
// unix:<dir>\qmp.sock,server=on,wait=off` (`reims-ctl command`, upstream
|
||||
// 3731afd). It exists on every host, unlike the Win10 cold-reboot TCP monitor.
|
||||
func SocketPath(vmDir string) string {
|
||||
return filepath.Join(vmDir, "qmp.sock")
|
||||
}
|
||||
|
||||
// TypeIntoVM types text into a running VM through its QMP socket and returns
|
||||
// how many keys it pressed.
|
||||
func TypeIntoVM(ctx context.Context, vmDir, text string, progress func(done, total int)) (int, error) {
|
||||
strokes, err := Strokes(text)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if len(strokes) == 0 {
|
||||
return 0, fmt.Errorf("nothing to type")
|
||||
}
|
||||
q, err := Dial(ctx, "unix", SocketPath(vmDir))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer q.Close()
|
||||
done := 0
|
||||
err = TypeStrokes(ctx, q, strokes, 20*time.Millisecond, 15*time.Millisecond, func(n int) {
|
||||
done = n
|
||||
if progress != nil {
|
||||
progress(n, len(strokes))
|
||||
}
|
||||
})
|
||||
return done, err
|
||||
}
|
||||
|
||||
func sleep(ctx context.Context, d time.Duration) {
|
||||
if d <= 0 {
|
||||
return
|
||||
}
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package qmp
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestStrokesMapsUSLayout(t *testing.T) {
|
||||
got, err := Strokes("sh /Volumes/A_b.sh\r\n")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []Stroke{
|
||||
{Key: "s"}, {Key: "h"}, {Key: "spc"}, {Key: "slash"},
|
||||
{Key: "v", Shift: true}, {Key: "o"}, {Key: "l"}, {Key: "u"}, {Key: "m"}, {Key: "e"}, {Key: "s"},
|
||||
{Key: "slash"}, {Key: "a", Shift: true}, {Key: "minus", Shift: true}, {Key: "b"},
|
||||
{Key: "dot"}, {Key: "s"}, {Key: "h"}, {Key: "ret"},
|
||||
}
|
||||
if fmt.Sprint(got) != fmt.Sprint(want) {
|
||||
t.Fatalf("got %v\nwant %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStrokesCoversPrintableASCII(t *testing.T) {
|
||||
for r := rune(0x20); r < 0x7f; r++ {
|
||||
if _, ok := StrokeFor(r); !ok {
|
||||
t.Errorf("no key for %q", r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStrokesRefusesWholeTextOnUntypeable(t *testing.T) {
|
||||
_, err := Strokes("echo 你好")
|
||||
var ue *UntypeableError
|
||||
if !errors.As(err, &ue) || ue.Rune != '你' || ue.Pos != 6 {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
if _, err := Strokes(strings.Repeat("a", MaxTypedRunes+1)); err == nil {
|
||||
t.Fatal("over-long text accepted")
|
||||
}
|
||||
}
|
||||
|
||||
type recorder struct {
|
||||
events []string
|
||||
failAt int
|
||||
}
|
||||
|
||||
func (r *recorder) Execute(command string, args any) error {
|
||||
if r.failAt > 0 && len(r.events) >= r.failAt {
|
||||
r.failAt = 0 // fail once; the cleanup that follows goes through
|
||||
return errors.New("boom")
|
||||
}
|
||||
for _, ev := range args.(map[string]any)["events"].([]map[string]any) {
|
||||
d := ev["data"].(map[string]any)
|
||||
dir := "up"
|
||||
if d["down"].(bool) {
|
||||
dir = "down"
|
||||
}
|
||||
r.events = append(r.events, d["key"].(map[string]any)["data"].(string)+" "+dir)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestTypeStrokesHoldsShiftAcrossCapitals(t *testing.T) {
|
||||
s, _ := Strokes("ABc")
|
||||
r := &recorder{}
|
||||
if err := TypeStrokes(context.Background(), r, s, 0, 0, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "shift down,a down,a up,b down,b up,shift up,c down,c up"
|
||||
if got := strings.Join(r.events, ","); got != want {
|
||||
t.Fatalf("got %s\nwant %s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTypeStrokesReleasesShiftOnError(t *testing.T) {
|
||||
s, _ := Strokes("AB")
|
||||
r := &recorder{failAt: 3} // shift down, a down, a up, then fail
|
||||
if err := TypeStrokes(context.Background(), r, s, 0, 0, nil); err == nil {
|
||||
t.Fatal("want error")
|
||||
}
|
||||
if last := r.events[len(r.events)-1]; last != "shift up" {
|
||||
t.Fatalf("shift left down: %v", r.events)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDialAndExecuteAgainstMockQMP(t *testing.T) {
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ln.Close()
|
||||
got := make(chan []string, 1)
|
||||
go func() {
|
||||
c, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
fmt.Fprint(c, `{"QMP":{"version":{}}}`+"\r\n")
|
||||
sc := bufio.NewScanner(c)
|
||||
var cmds []string
|
||||
for sc.Scan() {
|
||||
var req struct{ Execute string }
|
||||
_ = json.Unmarshal(sc.Bytes(), &req)
|
||||
cmds = append(cmds, req.Execute)
|
||||
if req.Execute == "bad" {
|
||||
fmt.Fprint(c, `{"error":{"class":"GenericError","desc":"nope"}}`+"\r\n")
|
||||
continue
|
||||
}
|
||||
fmt.Fprint(c, `{"event":"RTC_CHANGE","data":{}}`+"\r\n"+`{"return":{}}`+"\r\n")
|
||||
}
|
||||
got <- cmds
|
||||
}()
|
||||
|
||||
q, err := Dial(context.Background(), "tcp", ln.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := q.Execute("input-send-event", map[string]any{"events": []any{}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := q.Execute("bad", nil); err == nil || !strings.Contains(err.Error(), "nope") {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
q.Close()
|
||||
if cmds := <-got; strings.Join(cmds, ",") != "qmp_capabilities,input-send-event,bad" {
|
||||
t.Fatalf("server saw %v", cmds)
|
||||
}
|
||||
}
|
||||
@@ -3,13 +3,18 @@ package qmp
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const rebootSocketName = "reims-go-reboot.sock"
|
||||
|
||||
type qmpEvent struct {
|
||||
Event string `json:"event"`
|
||||
Data struct {
|
||||
@@ -18,25 +23,30 @@ type qmpEvent struct {
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// AllocateFreePort picks an available localhost TCP port for an independent QMP channel.
|
||||
func AllocateFreePort() (int, error) {
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("allocate localhost QMP port: %w", err)
|
||||
// RebootSocketPath picks an AF_UNIX socket path for the Win10 cold-reboot QMP
|
||||
// channel. Using AF_UNIX instead of tcp:127.0.0.1 prevents guest code from
|
||||
// reaching unauthenticated QMP through SLIRP's 10.0.2.2 host-loopback forward.
|
||||
// Falls back to tmpDir when vmDir would exceed Windows' 108-byte sun_path limit.
|
||||
func RebootSocketPath(vmDir, tmpDir, vmName string) string {
|
||||
if vmDir != "" {
|
||||
cand := filepath.Join(vmDir, rebootSocketName)
|
||||
if len(cand) <= 100 {
|
||||
return cand
|
||||
}
|
||||
}
|
||||
defer ln.Close()
|
||||
addr, ok := ln.Addr().(*net.TCPAddr)
|
||||
if !ok || addr.Port == 0 {
|
||||
return 0, fmt.Errorf("unexpected listener address %v", ln.Addr())
|
||||
sum := sha256.Sum256([]byte(vmName))
|
||||
short := hex.EncodeToString(sum[:6])
|
||||
if tmpDir != "" {
|
||||
return filepath.Join(tmpDir, "qmp-"+short+".sock")
|
||||
}
|
||||
return addr.Port, nil
|
||||
return filepath.Join(vmDir, "q-"+short+".sock")
|
||||
}
|
||||
|
||||
// MergeWin10RebootArgs idempotently merges `-no-reboot` and an independent
|
||||
// `-qmp tcp:127.0.0.1:<port>,server=on,wait=off` into existing extra_args while
|
||||
// preserving any user-specified QEMU arguments.
|
||||
func MergeWin10RebootArgs(existing string, qmpPort int) string {
|
||||
tokens := strings.Fields(existing)
|
||||
// MergeWin10RebootUnixArgs idempotently merges `-no-reboot` and a local AF_UNIX
|
||||
// `-qmp unix:<path>,server=on,wait=off` into existing extra_args while stripping
|
||||
// any legacy managed TCP or Unix QMP arguments.
|
||||
func MergeWin10RebootUnixArgs(existing, sockPath string) string {
|
||||
tokens := splitShellTokens(existing)
|
||||
cleaned := make([]string, 0, len(tokens)+3)
|
||||
for i := 0; i < len(tokens); i++ {
|
||||
tok := tokens[i]
|
||||
@@ -49,23 +59,82 @@ func MergeWin10RebootArgs(existing string, qmpPort int) string {
|
||||
}
|
||||
cleaned = append(cleaned, tok)
|
||||
}
|
||||
cleaned = append(cleaned, "-no-reboot", "-qmp", fmt.Sprintf("tcp:127.0.0.1:%d,server=on,wait=off", qmpPort))
|
||||
escaped := strings.ReplaceAll(sockPath, ",", ",,")
|
||||
escaped = strings.ReplaceAll(escaped, `\`, `/`)
|
||||
qmpVal := fmt.Sprintf("unix:%s,server=on,wait=off", escaped)
|
||||
if strings.ContainsAny(qmpVal, " \t") {
|
||||
qmpVal = `"` + strings.ReplaceAll(qmpVal, `"`, `\"`) + `"`
|
||||
}
|
||||
cleaned = append(cleaned, "-no-reboot", "-qmp", qmpVal)
|
||||
return strings.Join(cleaned, " ")
|
||||
}
|
||||
|
||||
func isManagedQMPTarget(arg string) bool {
|
||||
arg = strings.Trim(arg, "'\"")
|
||||
return strings.HasPrefix(arg, "tcp:127.0.0.1:") && strings.HasSuffix(arg, ",server=on,wait=off")
|
||||
if !strings.HasSuffix(arg, ",server=on,wait=off") {
|
||||
return false
|
||||
}
|
||||
if strings.HasPrefix(arg, "tcp:127.0.0.1:") {
|
||||
return true
|
||||
}
|
||||
if strings.HasPrefix(arg, "unix:") {
|
||||
return strings.Contains(arg, rebootSocketName) || strings.Contains(arg, "/qmp-") || strings.Contains(arg, `\qmp-`)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// WatchForGuestReset connects to QEMU's secondary QMP TCP endpoint, negotiates
|
||||
// capabilities, and waits for a SHUTDOWN event. It returns true iff the VM exited
|
||||
// because the guest requested a reset (`reason == "guest-reset"` under `-no-reboot`).
|
||||
func splitShellTokens(s string) []string {
|
||||
var out []string
|
||||
var cur strings.Builder
|
||||
var quote byte
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if quote != 0 {
|
||||
cur.WriteByte(c)
|
||||
if c == quote {
|
||||
quote = 0
|
||||
}
|
||||
continue
|
||||
}
|
||||
if c == '\'' || c == '"' {
|
||||
quote = c
|
||||
cur.WriteByte(c)
|
||||
continue
|
||||
}
|
||||
if c == ' ' || c == '\t' || c == '\n' || c == '\r' {
|
||||
if cur.Len() > 0 {
|
||||
out = append(out, cur.String())
|
||||
cur.Reset()
|
||||
}
|
||||
continue
|
||||
}
|
||||
cur.WriteByte(c)
|
||||
}
|
||||
if cur.Len() > 0 {
|
||||
out = append(out, cur.String())
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// WatchForGuestReset connects to QEMU's secondary QMP endpoint (AF_UNIX path or
|
||||
// "unix:<path>"), negotiates capabilities, and waits for a SHUTDOWN event. It
|
||||
// returns true iff the VM exited because the guest requested a reset
|
||||
// (`reason == "guest-reset"` under `-no-reboot`).
|
||||
func WatchForGuestReset(ctx context.Context, addr string) (bool, error) {
|
||||
conn, err := dialWithRetry(ctx, addr, 20*time.Second)
|
||||
reason, err := WatchShutdownReason(ctx, addr)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return reason == "guest-reset", nil
|
||||
}
|
||||
|
||||
// WatchShutdownReason waits for QEMU's SHUTDOWN event over QMP and returns its
|
||||
// reason (e.g. "guest-reset", "guest-shutdown", "host-qmp-quit"), or "" on EOF.
|
||||
func WatchShutdownReason(ctx context.Context, addr string) (string, error) {
|
||||
conn, err := dialWithRetry(ctx, addr, 20*time.Second)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
go func() {
|
||||
@@ -80,13 +149,13 @@ func WatchForGuestReset(ctx context.Context, addr string) (bool, error) {
|
||||
// Read QMP greeting.
|
||||
if !reader.Scan() {
|
||||
if ctx.Err() != nil {
|
||||
return false, ctx.Err()
|
||||
return "", ctx.Err()
|
||||
}
|
||||
return false, reader.Err()
|
||||
return "", reader.Err()
|
||||
}
|
||||
|
||||
if _, err := conn.Write([]byte("{\"execute\":\"qmp_capabilities\"}\n")); err != nil {
|
||||
return false, err
|
||||
return "", err
|
||||
}
|
||||
|
||||
for reader.Scan() {
|
||||
@@ -99,16 +168,27 @@ func WatchForGuestReset(ctx context.Context, addr string) (bool, error) {
|
||||
continue
|
||||
}
|
||||
if ev.Event == "SHUTDOWN" {
|
||||
return ev.Data.Reason == "guest-reset", nil
|
||||
return ev.Data.Reason, nil
|
||||
}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return false, ctx.Err()
|
||||
return "", ctx.Err()
|
||||
}
|
||||
return false, reader.Err()
|
||||
return "", reader.Err()
|
||||
}
|
||||
|
||||
func resolveQMPEndpoint(addr string) (network, target string) {
|
||||
if strings.HasPrefix(addr, "unix:") {
|
||||
return "unix", strings.TrimPrefix(addr, "unix:")
|
||||
}
|
||||
if strings.HasSuffix(strings.ToLower(addr), ".sock") || filepath.IsAbs(addr) {
|
||||
return "unix", addr
|
||||
}
|
||||
return "tcp", addr
|
||||
}
|
||||
|
||||
func dialWithRetry(ctx context.Context, addr string, timeout time.Duration) (net.Conn, error) {
|
||||
network, target := resolveQMPEndpoint(addr)
|
||||
deadline := time.Now().Add(timeout)
|
||||
var lastErr error
|
||||
for {
|
||||
@@ -116,13 +196,13 @@ func dialWithRetry(ctx context.Context, addr string, timeout time.Duration) (net
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
d := net.Dialer{Timeout: 500 * time.Millisecond}
|
||||
conn, err := d.DialContext(ctx, "tcp", addr)
|
||||
conn, err := d.DialContext(ctx, network, target)
|
||||
if err == nil {
|
||||
return conn, nil
|
||||
}
|
||||
lastErr = err
|
||||
if time.Now().After(deadline) {
|
||||
return nil, fmt.Errorf("connect QMP %s: %w", addr, lastErr)
|
||||
return nil, fmt.Errorf("connect QMP %s (%s): %w", target, network, lastErr)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
|
||||