Compare commits

..
Author SHA1 Message Date
NwflowerandClaude Opus 5.5 05cc34cbaa feat(ui): declutter the host page; cache the runtime release list
- Four stat tiles always on one row; drop the P/E-core line, os/arch and
  the data-folder path from the tiles. The WHPX tile carries "Enable" when
  WHPX is off, replacing the duplicate WHPX row.
- Runtime: one list with the current runtime (QEMU version, "Up to date" or
  "Update") and the candidate switch; no install path, no separate
  online-install row once a runtime is installed.
- "System" and "Preferences" merge into one "Settings" section: data folder
  (shown once), P-core pinning (no hex mask), language.
- Graphics cards show name and badges; the Vulkan ICD path moves to a tooltip.
- ListRemoteRuntimes caches for 10 minutes (GitHub allows 60 anonymous API
  requests an hour); a channel change clears it.
- Roadmap: M2.2 done; M2.1 and M2.3 progress for v0.2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 05:12:48 -07:00
NwflowerandClaude Opus 5.5 3f8cf11d3d feat: offline install flow, installer page, commit-memory checks (v0.2)
- New VMs default to an offline installer of one exact release
  (`reims-ctl create --macos <ver> --offline --network false`); the wizard
  lists Apple's releases, marks downloaded ones and warns when space is short.
- Offline VMs get an install guide with the install-macos.sh command and a
  "Finish install" action that ejects the installer and turns the network on
  (FinishInstall; pending until the next start on a running VM).
- Installers page (roadmap M2.2): downloaded installers with resume/delete,
  Apple's releases with download, progress and pause, space check first.
- Commit memory: the host report carries Windows' commit limit and available
  commit; create/settings refuse memory over the limit, start refuses memory
  that can't be committed now with a clear message, and the wizard, settings
  and first launch show a recommended size (16G failed with 14.7 GiB free).
- First launch shows a host check (WHPX with enable, Vulkan GPU, memory)
  before the runtime install.
- Create validation rejects a VM name that already exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 05:09:50 -07:00
NwflowerandClaude Opus 5.5 404090d8ed feat: graphical review step in the new-VM wizard
Step 5 used to show only a pass/fail line and the raw reims-ctl
command. It now shows a summary grouped by wizard step, each with an
Edit link back to that step. Validation issues are mapped to their
step: the group is highlighted, the step tab gets a marker, and
re-validation keeps running while the user edits. The equivalent
command is folded away with a copy button.

Create now closes the wizard right away and runs in the background;
progress stays in the status bar. A failure toast offers "Edit and
retry", which reopens the wizard with the same answers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 04:57:55 -07:00
NwflowerandClaude Opus 5.5 eb14a1610f docs: promote runtime-3731afd to stable; regenerate Wails bindings
- portable-runtime-spec.md §6 records the promotion: smoke test on a real
  Windows 10 19045 host, confirmed by a person; the release flag changes,
  the files don't.
- roadmap M2.4: single-file reims-go.exe (12.7 MB) released as v0.1.0.
- frontend/wailsjs: bindings regenerated for the setup and online-runtime
  methods (SuggestDataRoots, CompleteSetup, InstallRuntimeOnline, ...).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 04:51:33 -07:00
NwflowerandClaude Opus 5.5 60dd772b83 feat: ship sources of copyleft MSYS2 packages as a release asset
scripts/pack-msys2-sources.ps1 reads the bundled DLLs' MSYS2 packages, keeps
those whose licence requires source (GPL / LGPL / MPL with no permissive
alternative), downloads their .src.tar.zst and .sig from repo.msys2.org,
checks each signature with gpgv against the MSYS2 keyring, and packs them
as reims-runtime-msys2-src-<commit>.tar.zst, adding it to SHA256SUMS.txt.
pack-runtime.ps1 now calls it, so every runtime release has four assets.

runtime-3731afd: 22 source packages (110 MB), all signatures good, uploaded
beside the runtime; release notes and SHA256SUMS.txt updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 04:46:28 -07:00
NwflowerandClaude Opus 5.5 6d16105201 fix: restore LF line endings and the location.json path in roadmap
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 04:29:16 -07:00
NwflowerandClaude Opus 5.5 36c937d718 fix: runtime install deadlock, manifest raw_bytes, CLI flag order
- extractTarZst uses Windows' System32 tar.exe (reads .tar.zst and D:\
  paths); a bare "tar" could resolve to GNU tar, whose failure left the
  zstd | tar pipe deadlocked. The fallback now decompresses to a temp file.
- pack-runtime.ps1 casts raw_bytes to an integer (PowerShell 7 summed to a
  double, "962466926.0", which the Go reader rejected); the reader now also
  accepts whole-number floats.
- `runtime fetch latest --candidate` honours flags after the positional arg.
- Docs: release layout, source package contents and the open MSYS2 source
  question (portable-runtime-spec.md §4, §7); roadmap M1.2 and M2.1 progress.

Verified: a fresh `reims-go runtime fetch latest --candidate` downloads the
published runtime-3731afd from GitHub, checks SHA256SUMS.txt, unpacks and
activates it (75 s for 169 MB); reims-ctl and QEMU run from the result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 04:28:30 -07:00
NwflowerandClaude Opus 5.5 c7fe3d27f0 docs: rewrite README, add app icon and screenshots
- README follows a feature / install / usage layout with a hero image and
  light/dark screenshots that follow the reader's GitHub theme.
- New app icon (assets/logo.svg) replaces the default Wails icon in
  build/appicon.png and build/windows/icon.ico, and the "R" mark in the
  title bar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 04:11:46 -07:00
NwflowerandClaude Opus 5.5 f6f6bfce34 feat: online runtime install, first-launch data folder picker, source packages
- Runtime: list and fetch runtimes from this repo's GitHub Releases
  (stable by default, candidate on request), with SHA256 check and resume.
  CLI gains `runtime available` and `runtime fetch`; the host page gets an
  online install row and a "receive candidates" switch.
- First launch: pick a data folder (non-system drives first, USB never
  recommended); the choice is recorded in %APPDATA%\reims-go\location.json.
  Existing installs in the default folder are adopted without asking.
- pack-runtime.ps1: also builds the matching source package, records every
  patch with its SHA256 and the channel, and refuses undeclared changes in
  the build trees.
- patches: declare reims-vgpu-cargo-lock.patch (Cargo.lock source lines).
- UI: sidebar and VM page restyle, new design tokens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 04:11:37 -07:00
65 changed files with 4491 additions and 629 deletions

No files matched your search

+6
View File
@@ -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
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

+116 -28
View File
@@ -1,37 +1,125 @@
# reims-go
<p align="center">
<a href="https://github.com/Nwflower/reims-go">
<img src="./assets/logo.png" width="80" height="80" 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`,难以跟进上游更新。
<p align="center">
<img src="./.github/readme/hero.webp" width="100%" alt="reims-go 主窗口:前面是浅色外观下正在运行的 macos-tahoe 虚拟机详情页,后面是深色外观下的宿主与运行时页" />
</p>
**`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/截屏控制。
reims-go 是 [reims-vgpu](https://github.com/steelbrain/reims-vgpu) 的 Windows 桌面应用。装好之后,检查电脑、下载 macOS、创建和启动虚拟机都在一个窗口里完成,不需要自己配环境或敲命令。
## 技术可行性基线(2026-11-28 本机实测)
> 早期开发中,功能和界面还会变。
- **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` 均已存在。
## 功能
## 文档索引
- **开箱即用。** 运行时已经预先编译好,在应用里点一下就能安装,不用装任何开发工具。
- **电脑体检。** 一屏看清虚拟化是否开启、CPU、内存、显卡和剩余空间。虚拟化没开的话可以一键开启。
- **下载 macOS。** 在 Windows 上直接下载 macOS 完整安装包,带进度条,可以暂停,断了能接着下。
- **新建向导。** 五步建好一台虚拟机:选系统来源、CPU 与内存、存储、图形,最后确认。
- **随时调整。** 设置按 macOS 系统设置的方式分类。虚拟机开着也能改,每一项都会告诉你什么时候生效。
- **不占 C 盘。** 虚拟机、安装包和运行时都放在你选的数据目录里。
- **浅色和深色外观**,界面支持中文和英文。
- [`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 开发路线图与验收门槛
## 安装
### 环境要求
- Windows 11 64 位
- 一块支持 Vulkan 的独立显卡,推荐 NVIDIA RTX 系列
- 建议留出 150 GB 以上的可用空间,用来放 macOS 安装包和虚拟磁盘
### 下载
打包好的安装程序还没有发布,目前需要从源码构建。先装好 [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` 启动。
## 使用
1. **选择数据目录。** 第一次打开时,应用会推荐一个空间充足、不在 C 盘的位置。
2. **检查电脑并安装运行时。** 进入「宿主与运行时」页,确认各项都是「就绪」。虚拟化没开的话点「启用」,按提示重启一次电脑。然后在「运行时」里点「在线安装」。
3. **新建虚拟机。** 点侧边栏的 **+**,按向导选好 macOS 版本、CPU、内存和磁盘大小。
4. **启动并安装 macOS。** 点「启动」,会弹出虚拟机窗口。照着虚拟机页上的提示操作:先在「磁盘工具」里把磁盘抹掉成 APFS,再选「重新安装 macOS」。进入 macOS 桌面后,点「弹出安装盘」。
5. **调整配置。** 点齿轮图标打开设置。
> 在线安装目前还没有正式版运行时可选。在这之前,可以在「宿主与运行时」页打开「接收候选版」,或者用「导入运行时包」导入本地的运行时。
### 命令行
不想用图形界面的话,同样的功能也可以用命令行完成:
```powershell
reims-go doctor # 检查电脑
reims-go runtime fetch # 安装运行时
reims-go installer download tahoe # 下载 macOS 安装包
reims-go vm create macos-tahoe # 新建虚拟机
reims-go vm start macos-tahoe # 启动
```
运行 `reims-go help` 查看全部命令,加 `--lang en-US` 切换成英文输出。
## 截图
<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="虚拟机设置:左侧是分类,右侧是 CPU 核数选择" />
</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="新建虚拟机向导:系统来源、CPU 与内存、存储、图形与外设、确认五步" />
</picture>
<p align="center"><sub>新建虚拟机</sub></p>
</td>
</tr>
</table>
## 许可证
reims-go 使用 [MIT](./LICENSE) 许可证。它调用的运行时组件有各自的开源许可证,见 [`NOTICE.md`](./NOTICE.md)。
## 关于 macOS
reims-go 不包含、也不分发任何 Apple 系统文件,macOS 安装包由你的电脑直接从 Apple 服务器下载。
**macOS 的软件许可协议只允许在 Apple 硬件上运行虚拟机。** 在其他硬件上使用是否合规,需要你自己判断并承担责任。reims-go 与 Apple Inc. 没有关联,macOS 是 Apple Inc. 的商标。
+25 -2
View File
@@ -32,6 +32,8 @@ type AppState struct {
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"`
}
type rebootWatcherEntry struct {
@@ -48,15 +50,17 @@ type App struct {
rebootWatchers map[string]rebootWatcherEntry
nextWatcherID uint64
stopPoll context.CancelFunc
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),
@@ -190,6 +194,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)
@@ -205,6 +210,7 @@ func (a *App) GetState() AppState {
VMs: vms,
Transitions: trCopy,
PendingChanges: pcCopy,
NeedsSetup: needsSetup,
}
}
@@ -241,6 +247,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 +302,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) {
@@ -476,6 +495,10 @@ 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)
var qmpAddr string
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

+68
View File
@@ -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

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 130 KiB

After

Width:  |  Height:  |  Size: 272 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 62 KiB

+11 -3
View File
@@ -77,7 +77,9 @@ 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 列出已创建的虚拟机")
@@ -95,7 +97,9 @@ 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")
@@ -176,7 +180,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 +233,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])
}
+114
View File
@@ -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...)
}
+22
View File
@@ -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 节的本机冒烟测试。
@@ -126,6 +132,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 +147,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,前提是它和这些组件只通过独立进程交互,不链接它们。
+9 -2
View File
@@ -32,7 +32,8 @@ 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.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 <文件名>`。
@@ -64,9 +65,15 @@ flowchart LR
**目标**:做成真正给普通开发者/自己点几下就能用的轻量桌面应用。
- [ ] **M2.1**:**首次启动向导(中英双语实时切换)** — 自动识别系统语言(支持顶部一键切换 `中文 / English`);展示环境体检卡片(WHPX、**提交内存与推荐 RAM**、显卡、磁盘);WHPX 未开时提供「一键提权启用并重启」按钮;引导选择非 C 盘数据目录并一键安装/导入便携运行时。
- [ ] **M2.2**:**离线安装包下载管理器(核心体验)** — 调用 `reims-util --json` 展示可选 macOS Tahoe 精确版本,在 GUI 内直接触发宿主机直连下载、实时显示进度条 / 速率 / 已下体积 / 自动重试状态、支持「暂停/取消」与「断点续传」,并可视化管理 `<DataRoot>\data\reims-ctl\installers` 缓存。
- 2026-11-28 已完成一部分。首次启动先选数据目录:推荐有空间的非系统盘,USB 外置盘排在最后并标出风险,也可以手填路径;选好后进入运行时在线安装,这一步可以跳过。已有安装会被直接沿用,不再询问。选择结果记在 `%APPDATA%\reims-go\location.json`(只有这一个小文件放在数据目录之外)。环境体检卡片和一键启用 WHPX 还没并进这个流程。
- 2026-11-28(v0.2):选好目录后的那一步加了环境检查,包括 WHPX(未启用时可以一键启用,会弹 UAC)、Vulkan 显卡、内存(按 Windows 可分配内存推荐大小),之后再在线安装运行时。
- [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% 计,因为一开始就会占满整个镜像的空间)。速率显示在进度的悬停提示里。暂停后再次下载会接着下。
- [ ] **M2.3**:**VM 主面板与创建/装机引导(贴合简体中文 / 英文 macOS 界面术语)** — 实例列表、实时状态、一键启停与串口/图形日志抽屉;新建默认推荐复用本地离线包(附 `--network false`,启动前校验提交内存),装机侧边栏展示离线安装 3 步引导(抹盘 APFS → `sh /Volumes/Installer/install-macos.sh` → 一键 **弹出安装盘并恢复网络**)。
- 2026-11-28(v0.2):新建助手默认改为「离线安装包(推荐)」,执行 `reims-ctl create --macos <版本> --offline --network false`。版本列表来自 Apple,已下载的会标出来。这样建的 VM,装机引导改为三步:抹盘、在终端运行 `sh /Volumes/Installer/install-macos.sh`(命令可以一键复制)、点「完成安装」(弹出安装盘并打开网络,下次启动生效)。
- 可分配内存检查:体检会读取 Windows 的可分配内存(commit)上限和当前剩余。新建和修改设置时超过上限的会被拦下;启动前如果「内存 + 1 GB」超过当前剩余,就拒绝启动,并说明原因和推荐的大小。新建助手、设置面板、首次启动页都会显示推荐值。M1.1 和 M2.5 里要求的提交内存检查也是这一项。
- [ ] **M2.4**:打包为单文件 `reims-go.exe`(验证体积与冷启动速度)。
- 2026-11-28:`wails build -trimpath` 产出 12.7 MB 的单文件,命令行版 7.7 MB,作为 [v0.1.0](https://github.com/Nwflower/reims-go/releases/tag/v0.1.0) 发布。没有代码签名,首次运行会被 SmartScreen 拦截一次。冷启动时间还没测。
- [ ] **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 节)。
+68
View File
@@ -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

+123 -21
View File
@@ -1,16 +1,18 @@
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 { 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 { LogLine, appendLog } from './lib/logs'
import { currentTask, upsertTask } from './lib/tasks'
import { AppState, Locale, Task, VMDetail } from './types'
import { AppState, CreateOpts, Locale, Task, VMDetail } from './types'
import { TooltipProvider } from './ui/controls'
import { Toaster, useToasts } from './ui/toast'
import { backend } from './wails'
@@ -23,6 +25,7 @@ const failKey: Record<VMAction, I18nKey> = {
forceStop: 'failStop',
restart: 'failRestart',
eject: 'failEject',
finishInstall: 'failFinishInstall',
delete: 'failDelete',
openFolder: 'failOpenFolder',
}
@@ -32,10 +35,19 @@ 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 [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')
@@ -47,6 +59,7 @@ export const App: React.FC = () => {
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 +69,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 +116,45 @@ 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 === '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'
if (task.status === 'done') {
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' : '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)
@@ -161,6 +204,7 @@ export const App: React.FC = () => {
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('toastInstallFinished'))
case 'openFolder':
return backend.openVMFolder(name).catch((e) => fail(tr('failOpenFolder'), e))
case 'delete': return setDeleteTarget(name)
@@ -182,6 +226,26 @@ export const App: React.FC = () => {
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) => 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 +281,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>
<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 +327,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 +336,14 @@ 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)}
onError={fail}
onToast={(title) => toasts.push({ kind: 'ok', title })}
/>
) : selectedVM ? (
<VMPage
locale={locale}
@@ -266,6 +366,10 @@ export const App: React.FC = () => {
onRefresh={refresh}
onError={fail}
onSetLocale={setLang}
runtimeTask={runtimeTask}
onChannel={setChannel}
onInstallRuntime={installRuntime}
onCancelTask={cancelTask}
/>
)}
</div>
@@ -284,21 +388,19 @@ export const App: React.FC = () => {
onRefreshSerial={() => loadSerial()}
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}
/>
)}
+302 -63
View File
@@ -1,35 +1,59 @@
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',
@@ -39,7 +63,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, onClose, onCreated
displays: 1,
borderless: false,
audio: true,
network: true,
network: false,
ssh_port: 0,
logs: true,
start: true,
@@ -47,8 +71,12 @@ 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 = ''
p.network = false
} else if (p.source_mode === 'apple') {
p.installer = ''
p.disk = ''
} else if (p.source_mode === 'installer') {
@@ -63,15 +91,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 +145,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 +162,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 +204,19 @@ 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,
...(mode === 'apple' ? { macos: 'tahoe', network: true } : {}),
...(mode === 'offline' ? { macos: releases?.[0]?.version ?? '', network: false } : {}),
})}
/>
{tr(mode === 'apple' ? 'sourceApple' : mode === 'installer' ? 'sourceInstaller' : 'sourceDisk')}
{tr(mode === 'offline' ? 'sourceOffline' : mode === 'apple' ? 'sourceApple' : mode === 'installer' ? 'sourceInstaller' : 'sourceDisk')}
</label>
))}
</fieldset>
@@ -174,7 +230,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')}
@@ -216,7 +295,11 @@ 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>
</>
)}
@@ -314,40 +397,196 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, onClose, onCreated
['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]}
disabled={key === 'network' && opts.source_mode === 'offline'}
onChange={(e) => set({ [key]: e.target.checked })}
/>
{tr(label)}
</label>
))}
</div>
{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') }],
},
{
step: 4,
title: 'step4',
rows: [
...graphicsRows,
{ label: tr('fieldAudio'), value: onOff(opts.audio) },
{ label: tr('fieldNetwork'), value: onOff(opts.network) },
{ 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>
</>
)
}
+43 -60
View File
@@ -1,9 +1,10 @@
import { Cpu, HardDrive, MemoryStick, RefreshCw, ShieldCheck } from 'lucide-react'
import React, { useState } from 'react'
import { I18nKey, t } from '../i18n'
import { AppState, Locale } from '../types'
import { AppState, Locale, Task } from '../types'
import { Button, IconButton } from '../ui/controls'
import { backend } from '../wails'
import { RuntimeOnline } from './RuntimeOnline'
interface Props {
state: AppState
@@ -11,9 +12,13 @@ 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
@@ -73,14 +78,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 +96,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>
@@ -153,7 +144,6 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
<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>
<div className="row-right">
<label className="switch">
@@ -168,6 +158,15 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
</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>
</section>
@@ -180,33 +179,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>
)
}
+165
View File
@@ -0,0 +1,165 @@
import { Download, LoaderCircle, Pause, 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[]
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, 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.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.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>
)
}
+115
View File
@@ -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>
</>
)
}
+6 -2
View File
@@ -1,6 +1,6 @@
import React, { useState } from 'react'
import { I18nKey, t } from '../i18n'
import { shortGPUName } from '../lib/format'
import { recommendedMemoryGB, shortGPUName } from '../lib/format'
import { HostReport, Locale, SetOpts, ValidationIssue, VMDetail } from '../types'
import { Button } from '../ui/controls'
import { Modal } from '../ui/dialog'
@@ -176,7 +176,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>
)}
+233
View File
@@ -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>
</>
)
}
+53 -30
View File
@@ -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>
)
}
+148 -42
View File
@@ -2,12 +2,8 @@ import * as Menu from '@radix-ui/react-dropdown-menu'
import {
ChevronRight,
Copy,
Cpu,
Ellipsis,
FolderOpen,
Gpu,
HardDrive,
MemoryStick,
Play,
Power,
RotateCw,
@@ -22,7 +18,10 @@ 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' | 'delete' | 'openFolder'
// What an offline installer's Recovery runs to install (`reims-util offline-installer --help`).
const OFFLINE_INSTALL_CMD = 'sh /Volumes/Installer/install-macos.sh'
interface Props {
locale: Locale
@@ -66,23 +65,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>
@@ -114,6 +109,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 && (
@@ -133,21 +137,49 @@ export const VMPage: React.FC<Props> = ({
{detail?.has_installer && (
<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>
<div className="card-foot">
<Button
variant={running ? 'primary' : 'secondary'}
busy={busyAction === 'eject'}
disabled={busy}
onClick={() => onAction('eject')}
>
{tr('eject')}
</Button>
</div>
{/offline-installer/i.test(detail.installer_path ?? '') ? (
<>
<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)} />
</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 === 'eject'}
disabled={busy}
onClick={() => onAction('eject')}
>
{tr('eject')}
</Button>
</div>
</>
)}
</section>
)}
@@ -160,14 +192,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 +262,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 +271,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>
)
+176 -6
View File
@@ -7,6 +7,18 @@ const dict = {
// Shell
sidebarVMs: '虚拟机',
sidebarHost: '宿主与运行时',
sidebarInstallers: '安装包',
installersTitle: '安装包',
installersDownloaded: '已下载',
installersAvailable: 'Apple 提供的版本',
installersEmpty: '还没有下载任何安装包',
installersPartial: '未下载完',
installersResume: '继续下载',
installersDownload: '下载',
installersDelete: '删除',
installersDeleteConfirm: '确认删除',
installersNoSpace: '空间不足:需要约 {need} GB,可用 {free} GB',
installersHint: '离线安装包可以重复用来新建虚拟机;正在使用或正在下载的不能删除',
emptyVMs: '还没有虚拟机',
hostReady: '就绪',
hostNeedsAction: '需要处理',
@@ -54,6 +66,10 @@ const dict = {
guideStep1: '在「磁盘工具」中抹掉「QEMU HARDDISK Media」,格式选 APFS',
guideStep2: '退出磁盘工具,选择「重新安装 macOS」',
guideStep3: '进入桌面后,弹出安装盘',
guideOffline1: '在「磁盘工具」中抹掉「QEMU HARDDISK Media」,格式选 APFS',
guideOffline2: '退出磁盘工具,打开「实用工具 › 终端」,运行:',
guideOffline3: '进入桌面后,点「完成安装」',
finishInstall: '完成安装',
brokenHint: '这台虚拟机的配置无法读取',
techInfo: '技术信息',
factCPU: '处理器',
@@ -88,10 +104,52 @@ const dict = {
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: '已弹出安装盘并打开网络,下次启动生效',
toastDeleted: '已删除 {name}',
toastSaved: '已保存',
toastSavedNextStart: '已保存,下次启动生效',
@@ -100,6 +158,7 @@ const dict = {
failStop: '关机失败',
failRestart: '重启失败',
failEject: '弹出安装盘失败',
failFinishInstall: '完成安装失败',
failDelete: '删除失败',
failOpenFolder: '无法打开文件夹',
failGeneric: '操作失败',
@@ -159,6 +218,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 +237,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 +252,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} 设置',
@@ -217,6 +303,18 @@ const dict = {
'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: 'An offline installer can be reused for new VMs; one in use or downloading can’t be deleted',
emptyVMs: 'No virtual machines',
hostReady: 'Ready',
hostNeedsAction: 'Needs attention',
@@ -261,6 +359,10 @@ const dict = {
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',
guideOffline1: 'In Disk Utility, erase "QEMU HARDDISK Media" as APFS',
guideOffline2: 'Quit Disk Utility, open Utilities › Terminal and run:',
guideOffline3: 'Once on the desktop, click “Finish install”',
finishInstall: 'Finish install',
brokenHint: 'This VM’s configuration can’t be read',
techInfo: 'Technical details',
factCPU: 'CPU',
@@ -293,9 +395,49 @@ const dict = {
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: 'Installer ejected and network on — applies at next start',
toastDeleted: '{name} deleted',
toastSaved: 'Saved',
toastSavedNextStart: 'Saved — applies on next start',
@@ -304,6 +446,7 @@ const dict = {
failStop: 'Couldn’t shut down',
failRestart: 'Couldn’t restart',
failEject: 'Couldn’t eject the installer',
failFinishInstall: 'Couldn’t finish the install',
failDelete: 'Couldn’t delete',
failOpenFolder: 'Couldn’t open the folder',
failGeneric: 'Something went wrong',
@@ -361,6 +504,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 while installing offline; turned on when you finish the install',
summaryOfflineSource: 'Offline installer · macOS {v}',
macosVersion: 'macOS version',
macosTahoe: 'macOS 26 Tahoe (acceleration needs 26.4 or later)',
diskSize: 'Disk size',
@@ -372,6 +523,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 +538,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',
+23 -7
View File
@@ -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
+1
View File
@@ -20,6 +20,7 @@ export function taskTitle(locale: Locale, task: Task): string {
switch (task.kind) {
case 'installer-download': return t(locale, 'taskDownload', { v: 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
}
}
+280 -114
View File
@@ -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,70 +241,76 @@ 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); }
/* ── Log bar & panel ───────────────────────────────────── */
@@ -217,7 +319,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 +338,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 +372,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 +385,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 +397,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 +416,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); }
+100 -48
View File
@@ -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) {
+41 -1
View File
@@ -6,6 +6,7 @@ export interface Config {
active_runtime?: string
auto_pin_pcores: boolean
default_gpu?: string
runtime_channel?: 'stable' | 'candidate' | ''
}
export interface GPUInfo {
@@ -28,6 +29,9 @@ export interface HostReport {
e_core_logical_cpus?: number[]
total_ram_gb: number
avail_ram_gb: number
/** Windows commit memory: QEMU commits all guest RAM at start. */
commit_avail_gb: number
commit_limit_gb: number
data_root: string
free_disk_gb: number
whpx: 'ready' | 'no_hypervisor' | 'missing' | 'unsupported'
@@ -74,6 +78,8 @@ export interface AppState {
vms: VMListItem[] | null
transitions: Record<string, string>
pending_changes: Record<string, PendingChange[]>
/** First launch: no data folder chosen yet (setup.go). */
needs_setup: boolean
}
export interface VMDetail {
@@ -116,7 +122,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
@@ -207,3 +215,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
}
+17
View File
@@ -1,6 +1,9 @@
import {
AppState,
CachedInstaller,
DataRootCheck,
DataRootChoice,
RemoteRuntime,
Release,
Task,
CreateOpts,
@@ -38,6 +41,7 @@ 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>
GetTasks(): Promise<Task[]>
CancelTask(id: string): Promise<void>
DismissTask(id: string): Promise<void>
@@ -45,6 +49,12 @@ 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>
}
}
}
@@ -88,6 +98,7 @@ 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),
getTasks: () => app().GetTasks(),
cancelTask: (id: string) => app().CancelTask(id),
dismissTask: (id: string) => app().DismissTask(id),
@@ -95,6 +106,12 @@ 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),
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) ?? (() => {}),
+14
View File
@@ -9,6 +9,10 @@ export function ApplyVMSettings(arg1:reims.SetOpts):Promise<void>;
export function CancelTask(arg1:string):Promise<void>;
export function CheckDataRoot(arg1:string):Promise<main.DataRootCheck>;
export function CompleteSetup(arg1:string):Promise<void>;
export function CreateVM(arg1:reims.CreateOpts):Promise<void>;
export function DeleteInstaller(arg1:string):Promise<void>;
@@ -23,6 +27,8 @@ export function EjectInstaller(arg1:string):Promise<void>;
export function EnableWHPX():Promise<void>;
export function FinishInstall(arg1:string):Promise<void>;
export function GetState():Promise<main.AppState>;
export function GetTasks():Promise<Array<main.Task>>;
@@ -31,10 +37,14 @@ 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 OpenVMFolder(arg1:string):Promise<void>;
export function PickDirectory(arg1:string):Promise<string>;
@@ -53,10 +63,14 @@ 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 UseRuntime(arg1:string):Promise<void>;
export function ValidateCreate(arg1:reims.CreateOpts):Promise<Array<reims.ValidationIssue>>;
+28
View File
@@ -10,6 +10,14 @@ export function CancelTask(arg1) {
return window['go']['main']['App']['CancelTask'](arg1);
}
export function CheckDataRoot(arg1) {
return window['go']['main']['App']['CheckDataRoot'](arg1);
}
export function CompleteSetup(arg1) {
return window['go']['main']['App']['CompleteSetup'](arg1);
}
export function CreateVM(arg1) {
return window['go']['main']['App']['CreateVM'](arg1);
}
@@ -38,6 +46,10 @@ export function EnableWHPX() {
return window['go']['main']['App']['EnableWHPX']();
}
export function FinishInstall(arg1) {
return window['go']['main']['App']['FinishInstall'](arg1);
}
export function GetState() {
return window['go']['main']['App']['GetState']();
}
@@ -54,6 +66,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 +78,10 @@ export function ListOfflineReleases() {
return window['go']['main']['App']['ListOfflineReleases']();
}
export function ListRemoteRuntimes() {
return window['go']['main']['App']['ListRemoteRuntimes']();
}
export function OpenVMFolder(arg1) {
return window['go']['main']['App']['OpenVMFolder'](arg1);
}
@@ -98,6 +118,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 +130,10 @@ export function StopVM(arg1, arg2) {
return window['go']['main']['App']['StopVM'](arg1, arg2);
}
export function SuggestDataRoots() {
return window['go']['main']['App']['SuggestDataRoots']();
}
export function UseRuntime(arg1) {
return window['go']['main']['App']['UseRuntime'](arg1);
}
+132
View File
@@ -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"];
}
}
@@ -55,6 +57,8 @@ export namespace host {
e_core_logical_cpus?: number[];
total_ram_gb: number;
avail_ram_gb: number;
commit_avail_gb: number;
commit_limit_gb: number;
data_root: string;
free_disk_gb: number;
whpx: string;
@@ -81,6 +85,8 @@ export namespace host {
this.e_core_logical_cpus = source["e_core_logical_cpus"];
this.total_ram_gb = source["total_ram_gb"];
this.avail_ram_gb = source["avail_ram_gb"];
this.commit_avail_gb = source["commit_avail_gb"];
this.commit_limit_gb = source["commit_limit_gb"];
this.data_root = source["data_root"];
this.free_disk_gb = source["free_disk_gb"];
this.whpx = source["whpx"];
@@ -173,6 +179,7 @@ export namespace main {
vms: reims.VMListItem[];
transitions: Record<string, string>;
pending_changes: Record<string, Array<PendingChange>>;
needs_setup: boolean;
static createFrom(source: any = {}) {
return new AppState(source);
@@ -187,6 +194,7 @@ export namespace main {
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"];
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
@@ -207,6 +215,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,6 +323,7 @@ export namespace reims {
dir?: string;
source_mode?: string;
macos?: string;
offline?: boolean;
installer?: string;
cpus?: number;
memory?: string;
@@ -300,6 +351,7 @@ 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"];
@@ -471,6 +523,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 +553,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 +579,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 +641,40 @@ 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"];
}
}
}
+70
View File
@@ -0,0 +1,70 @@
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"
"github.com/Nwflower/reims-go/internal/driver/reims"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// FinishInstall ejects the installer and enables the network. Both changes
// apply at the VM's next start (a running VM keeps its installer until then:
// `reims-ctl eject --help`), so on a running VM they are listed as pending.
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
}
}
if !d.Network {
on := true
a.emitLog(name, "Turning the network on for "+name+"...")
if err := c.Set(ctx, reims.SetOpts{Name: name, Network: &on}, w, w); err != nil {
return err
}
}
running := d.State == "running"
if !running {
if list, err := c.List(ctx); err == nil {
for _, vm := range list {
if vm.Name == name {
running = vm.State == "running"
}
}
}
}
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"})
}
a.mu.Lock()
a.pendingChanges[name] = append(a.pendingChanges[name], diffs...)
a.mu.Unlock()
}
a.emitLog(name, "Install finished: installer out, network on")
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return nil
}
+104 -4
View File
@@ -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,7 +183,7 @@ 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") }
+80
View File
@@ -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")
}
}
+23 -1
View File
@@ -79,6 +79,10 @@ 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"`
@@ -158,8 +162,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 {
@@ -208,6 +217,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 +255,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 +297,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))
@@ -469,6 +485,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 +504,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
}
+39
View File
@@ -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)
}
}
+35
View File
@@ -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
}
+96
View File
@@ -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) }
+21
View File
@@ -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")
}
}
+6
View File
@@ -40,6 +40,12 @@ type Report struct {
ECoreLogicalCPUs []int `json:"e_core_logical_cpus,omitempty"`
TotalRAMGB float64 `json:"total_ram_gb"`
AvailRAMGB float64 `json:"avail_ram_gb"`
// Commit memory: QEMU commits all guest RAM at start (CreateFileMapping), so
// a VM needs its memory free in the commit charge, not just in physical RAM.
// Measured 2026-11-28: 14.7 GiB commit free with 17.3 GiB physical free, and a
// 16G guest failed ("Cannot set up guest memory"). portable-runtime-spec.md §5.1.
CommitAvailGB float64 `json:"commit_avail_gb"`
CommitLimitGB float64 `json:"commit_limit_gb"`
DataRoot string `json:"data_root"`
FreeDiskGB float64 `json:"free_disk_gb"`
WHPX WHPXState `json:"whpx"`
+31 -4
View File
@@ -79,6 +79,10 @@ func Inspect(dataRoot string) Report {
rep.TotalRAMGB = totalGB
rep.AvailRAMGB = availGB
}
if limitGB, availGB, ok := probeCommitGB(); ok {
rep.CommitLimitGB = limitGB
rep.CommitAvailGB = availGB
}
if freeGB, ok := probeFreeDiskGB(dataRoot); ok {
rep.FreeDiskGB = freeGB
}
@@ -220,16 +224,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 != "" {
+27
View File
@@ -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
}
+6
View File
@@ -0,0 +1,6 @@
//go:build !windows
package host
// CommitAvailGB is unknown on dev/preview hosts.
func CommitAvailGB() (float64, bool) { return 0, false }
+19
View File
@@ -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)
}
}
+72 -64
View File
@@ -39,72 +39,80 @@ 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.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 <归档路径>`",
"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.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",
"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.",
},
}
+19
View File
@@ -0,0 +1,19 @@
package runtime
import (
"os"
"path/filepath"
"testing"
)
func TestManifestAcceptsWholeNumberFloats(t *testing.T) {
p := filepath.Join(t.TempDir(), "manifest.json")
os.WriteFile(p, []byte("\ufeff"+`{"schema_version":2,"commit":"3731afd","raw_bytes":962466926.0,"patches":[{"name":"a.patch","target":"vendor/qemu","sha256":"ab"}],"channel":"candidate"}`), 0o644)
m, err := readManifest(p)
if err != nil {
t.Fatal(err)
}
if m.RawBytes != 962466926 || m.Channel != "candidate" || len(m.Patches) != 1 {
t.Fatalf("manifest = %+v", m)
}
}
+329
View File
@@ -0,0 +1,329 @@
package runtime
// Online install: runtime packages are GitHub Release assets of the reims-go
// repository (decided 2026-11-28, AGENTS.md). A runtime release is tagged
// "runtime-<commit>" and carries:
//
// reims-runtime-win-x64-<commit>.tar.zst
// reims-runtime-src-<commit>.tar.zst (matching sources, spec §7)
// SHA256SUMS.txt
//
// A GitHub prerelease is the candidate channel; a full release is stable
// (spec §6). The client lists stable only unless candidate is asked for.
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/config"
)
const (
DefaultReleasesRepo = "Nwflower/reims-go"
DefaultAPIBase = "https://api.github.com"
runtimeTagPrefix = "runtime-"
sumsAsset = "SHA256SUMS.txt"
)
const (
ChannelStable = "stable"
ChannelCandidate = "candidate"
)
// Source is where runtime releases are listed. REIMS_GO_RELEASES_REPO
// overrides the repository (for forks and testing).
type Source struct {
APIBase string
Repo string
Client *http.Client
}
func DefaultSource() Source {
repo := os.Getenv("REIMS_GO_RELEASES_REPO")
if repo == "" {
repo = DefaultReleasesRepo
}
return Source{APIBase: DefaultAPIBase, Repo: repo, Client: &http.Client{Timeout: 0}}
}
// Remote is a runtime package published as a release.
type Remote struct {
Commit string `json:"commit"`
Tag string `json:"tag"`
Channel string `json:"channel"`
PublishedAt string `json:"published_at"`
PageURL string `json:"page_url"`
ArchiveName string `json:"archive_name"`
ArchiveURL string `json:"archive_url"`
ArchiveSize int64 `json:"archive_size"`
SumsURL string `json:"sums_url"`
SourceName string `json:"source_name,omitempty"`
SourceURL string `json:"source_url,omitempty"`
}
type ghRelease struct {
TagName string `json:"tag_name"`
Draft bool `json:"draft"`
Prerelease bool `json:"prerelease"`
PublishedAt string `json:"published_at"`
HTMLURL string `json:"html_url"`
Assets []ghAsset `json:"assets"`
}
type ghAsset struct {
Name string `json:"name"`
Size int64 `json:"size"`
URL string `json:"browser_download_url"`
}
func (s Source) client() *http.Client {
if s.Client != nil {
return s.Client
}
return http.DefaultClient
}
func newRequest(ctx context.Context, url string) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
// A generic client name; nothing about the user (GitHub requires a User-Agent).
req.Header.Set("User-Agent", "reims-go")
return req, nil
}
// ListRemote lists published runtime packages, newest first. Candidates are
// included only when includeCandidate is set.
func (s Source) ListRemote(ctx context.Context, includeCandidate bool) ([]Remote, error) {
url := fmt.Sprintf("%s/repos/%s/releases?per_page=100", strings.TrimRight(s.APIBase, "/"), s.Repo)
req, err := newRequest(ctx, url)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/vnd.github+json")
resp, err := s.client().Do(req)
if err != nil {
return nil, fmt.Errorf("list runtime releases: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusTooManyRequests {
return nil, fmt.Errorf("GitHub API rate limit reached; try again later (HTTP %d)", resp.StatusCode)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("list runtime releases: HTTP %d", resp.StatusCode)
}
var rels []ghRelease
if err := json.NewDecoder(resp.Body).Decode(&rels); err != nil {
return nil, fmt.Errorf("read runtime releases: %w", err)
}
var out []Remote
for _, r := range rels {
if r.Draft || !strings.HasPrefix(r.TagName, runtimeTagPrefix) {
continue
}
commit := strings.TrimPrefix(r.TagName, runtimeTagPrefix)
rem := Remote{Commit: commit, Tag: r.TagName, PublishedAt: r.PublishedAt, PageURL: r.HTMLURL, Channel: ChannelStable}
if r.Prerelease {
rem.Channel = ChannelCandidate
}
for _, a := range r.Assets {
switch {
case a.Name == "reims-runtime-win-x64-"+commit+".tar.zst":
rem.ArchiveName, rem.ArchiveURL, rem.ArchiveSize = a.Name, a.URL, a.Size
case a.Name == sumsAsset:
rem.SumsURL = a.URL
case strings.HasPrefix(a.Name, "reims-runtime-src-"):
rem.SourceName, rem.SourceURL = a.Name, a.URL
}
}
// A release without its sums or sources is incomplete: never offer it.
if rem.ArchiveURL == "" || rem.SumsURL == "" || rem.SourceURL == "" {
continue
}
if rem.Channel == ChannelCandidate && !includeCandidate {
continue
}
out = append(out, rem)
}
sort.SliceStable(out, func(i, j int) bool { return out[i].PublishedAt > out[j].PublishedAt })
return out, nil
}
// Pick finds a release by commit prefix, or the newest for "" / "latest".
func Pick(list []Remote, want string) (*Remote, error) {
want = strings.TrimSpace(want)
if len(list) == 0 {
return nil, errors.New("no runtime release is published for this channel")
}
if want == "" || strings.EqualFold(want, "latest") {
return &list[0], nil
}
for i := range list {
if strings.HasPrefix(list[i].Commit, want) || strings.HasPrefix(want, list[i].Commit) {
return &list[i], nil
}
}
return nil, fmt.Errorf("no runtime release for %q", want)
}
// Progress reports bytes of the archive download.
type Progress func(done, total int64)
// Download fetches r's archive into dir, continuing a partial download, and
// checks it against the release's SHA256SUMS.txt. It returns the archive path.
func (s Source) Download(ctx context.Context, r Remote, dir string, onProgress Progress) (string, error) {
if onProgress == nil {
onProgress = func(int64, int64) {}
}
want, err := s.expectedSum(ctx, r)
if err != nil {
return "", err
}
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", err
}
final := filepath.Join(dir, r.ArchiveName)
if got, err := fileSHA256(final); err == nil && strings.EqualFold(got, want) {
onProgress(r.ArchiveSize, r.ArchiveSize)
return final, nil
}
part := final + ".part"
var have int64
if st, err := os.Stat(part); err == nil {
have = st.Size()
}
req, err := newRequest(ctx, r.ArchiveURL)
if err != nil {
return "", err
}
if have > 0 {
req.Header.Set("Range", "bytes="+strconv.FormatInt(have, 10)+"-")
}
resp, err := s.client().Do(req)
if err != nil {
return "", fmt.Errorf("download %s: %w", r.ArchiveName, err)
}
defer resp.Body.Close()
flags := os.O_CREATE | os.O_WRONLY
switch resp.StatusCode {
case http.StatusPartialContent:
flags |= os.O_APPEND
case http.StatusOK:
have = 0 // server ignored the range: start over
flags |= os.O_TRUNC
case http.StatusRequestedRangeNotSatisfiable:
os.Remove(part)
return s.Download(ctx, r, dir, onProgress)
default:
return "", fmt.Errorf("download %s: HTTP %d", r.ArchiveName, resp.StatusCode)
}
total := r.ArchiveSize
if total <= 0 && resp.ContentLength > 0 {
total = have + resp.ContentLength
}
f, err := os.OpenFile(part, flags, 0o644)
if err != nil {
return "", err
}
done := have
onProgress(done, total)
buf := make([]byte, 256*1024)
last := time.Now()
for {
n, rerr := resp.Body.Read(buf)
if n > 0 {
if _, werr := f.Write(buf[:n]); werr != nil {
f.Close()
return "", werr
}
done += int64(n)
if time.Since(last) > 100*time.Millisecond {
onProgress(done, total)
last = time.Now()
}
}
if rerr == io.EOF {
break
}
if rerr != nil {
f.Close()
return "", fmt.Errorf("download %s: %w", r.ArchiveName, rerr) // .part kept for resume
}
}
if err := f.Close(); err != nil {
return "", err
}
onProgress(done, total)
got, err := fileSHA256(part)
if err != nil {
return "", err
}
if !strings.EqualFold(got, want) {
os.Remove(part)
return "", fmt.Errorf("%s: SHA256 mismatch (expected %s, got %s); the download was discarded", r.ArchiveName, want, got)
}
if err := os.Rename(part, final); err != nil {
return "", err
}
return final, nil
}
// expectedSum reads r's archive hash from the release's SHA256SUMS.txt
// ("<hex> <name>" lines, as sha256sum writes them).
func (s Source) expectedSum(ctx context.Context, r Remote) (string, error) {
req, err := newRequest(ctx, r.SumsURL)
if err != nil {
return "", err
}
resp, err := s.client().Do(req)
if err != nil {
return "", fmt.Errorf("download %s: %w", sumsAsset, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("download %s: HTTP %d", sumsAsset, resp.StatusCode)
}
sc := bufio.NewScanner(io.LimitReader(resp.Body, 1<<20))
for sc.Scan() {
fields := strings.Fields(sc.Text())
if len(fields) == 2 && strings.TrimPrefix(fields[1], "*") == r.ArchiveName && len(fields[0]) == 64 {
return strings.ToLower(fields[0]), nil
}
}
return "", fmt.Errorf("%s has no entry for %s", sumsAsset, r.ArchiveName)
}
// DownloadsDir is where runtime archives are downloaded before install.
func DownloadsDir(cfg *config.Config) string {
return filepath.Join(cfg.DataRoot, "downloads")
}
// IsInstalled reports whether commit is already unpacked under runtimes/.
func IsInstalled(cfg *config.Config, commit string) bool {
list, err := List(cfg)
if err != nil {
return false
}
for _, it := range list {
if strings.HasPrefix(it.Commit, commit) || strings.HasPrefix(commit, it.Commit) {
return true
}
}
return false
}
+154
View File
@@ -0,0 +1,154 @@
package runtime
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
type fakeGitHub struct {
srv *httptest.Server
archive []byte
sums string
hits map[string]int
}
func newFakeGitHub(t *testing.T) *fakeGitHub {
t.Helper()
g := &fakeGitHub{archive: bytes.Repeat([]byte("reims-runtime-"), 50_000), hits: map[string]int{}}
sum := sha256.Sum256(g.archive)
g.sums = hex.EncodeToString(sum[:]) + " reims-runtime-win-x64-abc1234.tar.zst\n"
mux := http.NewServeMux()
mux.HandleFunc("/repos/o/r/releases", func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-Agent") != "reims-go" {
t.Errorf("User-Agent = %q", r.Header.Get("User-Agent"))
}
base := g.srv.URL
fmt.Fprintf(w, `[
{"tag_name":"runtime-abc1234","prerelease":true,"published_at":"2026-11-28T10:00:00Z","assets":[
{"name":"reims-runtime-win-x64-abc1234.tar.zst","size":%d,"browser_download_url":"%s/a/archive"},
{"name":"reims-runtime-src-abc1234.tar.zst","size":5,"browser_download_url":"%s/a/src"},
{"name":"SHA256SUMS.txt","size":90,"browser_download_url":"%s/a/sums"}]},
{"tag_name":"runtime-0000old","prerelease":false,"published_at":"2026-10-01T00:00:00Z","assets":[
{"name":"reims-runtime-win-x64-0000old.tar.zst","size":1,"browser_download_url":"%s/a/x"},
{"name":"reims-runtime-src-0000old.tar.zst","size":1,"browser_download_url":"%s/a/x"},
{"name":"SHA256SUMS.txt","size":1,"browser_download_url":"%s/a/x"}]},
{"tag_name":"runtime-nosrc00","prerelease":false,"published_at":"2026-11-01T00:00:00Z","assets":[
{"name":"reims-runtime-win-x64-nosrc00.tar.zst","size":1,"browser_download_url":"%s/a/x"},
{"name":"SHA256SUMS.txt","size":1,"browser_download_url":"%s/a/x"}]},
{"tag_name":"runtime-draft00","draft":true,"assets":[]},
{"tag_name":"v0.1.0","prerelease":false,"assets":[]}
]`, len(g.archive), base, base, base, base, base, base, base, base)
})
mux.HandleFunc("/a/archive", func(w http.ResponseWriter, r *http.Request) {
g.hits["archive"]++
if r.Header.Get("Range") != "" {
g.hits["range"]++
}
http.ServeContent(w, r, "a.tar.zst", time.Time{}, bytes.NewReader(g.archive))
})
mux.HandleFunc("/a/sums", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, g.sums) })
g.srv = httptest.NewServer(mux)
t.Cleanup(g.srv.Close)
return g
}
func (g *fakeGitHub) source() Source {
return Source{APIBase: g.srv.URL, Repo: "o/r", Client: g.srv.Client()}
}
func TestListRemoteFiltersChannelsAndIncompleteReleases(t *testing.T) {
g := newFakeGitHub(t)
stable, err := g.source().ListRemote(context.Background(), false)
if err != nil {
t.Fatal(err)
}
if len(stable) != 1 || stable[0].Commit != "0000old" || stable[0].Channel != ChannelStable {
t.Fatalf("stable only = %+v", stable)
}
all, err := g.source().ListRemote(context.Background(), true)
if err != nil {
t.Fatal(err)
}
if len(all) != 2 || all[0].Commit != "abc1234" || all[0].Channel != ChannelCandidate || all[0].SourceName == "" {
t.Fatalf("with candidate = %+v", all)
}
if r, err := Pick(all, "abc"); err != nil || r.Commit != "abc1234" {
t.Fatalf("pick prefix: %v %v", r, err)
}
if r, _ := Pick(all, "latest"); r.Commit != "abc1234" {
t.Fatalf("latest = %v", r)
}
if _, err := Pick(nil, ""); err == nil {
t.Fatal("empty list")
}
}
func TestDownloadResumesAndVerifies(t *testing.T) {
g := newFakeGitHub(t)
src := g.source()
list, _ := src.ListRemote(context.Background(), true)
r := list[0]
dir := t.TempDir()
// A previous run left the first 100 KB.
part := filepath.Join(dir, r.ArchiveName+".part")
os.WriteFile(part, g.archive[:100_000], 0o644)
var last int64
path, err := src.Download(context.Background(), r, dir, func(done, total int64) {
if total != int64(len(g.archive)) {
t.Errorf("total = %d", total)
}
last = done
})
if err != nil {
t.Fatal(err)
}
if g.hits["range"] != 1 {
t.Fatalf("expected a ranged request, hits=%v", g.hits)
}
if last != int64(len(g.archive)) {
t.Fatalf("last progress = %d", last)
}
got, _ := os.ReadFile(path)
if !bytes.Equal(got, g.archive) {
t.Fatal("archive content differs")
}
if _, err := os.Stat(part); !os.IsNotExist(err) {
t.Fatal(".part left behind")
}
// Already there and valid: no new request.
before := g.hits["archive"]
if _, err := src.Download(context.Background(), r, dir, nil); err != nil {
t.Fatal(err)
}
if g.hits["archive"] != before {
t.Fatal("re-downloaded a verified archive")
}
}
func TestDownloadRejectsAWrongChecksum(t *testing.T) {
g := newFakeGitHub(t)
g.sums = strings.Repeat("0", 64) + " reims-runtime-win-x64-abc1234.tar.zst\n"
list, _ := g.source().ListRemote(context.Background(), true)
dir := t.TempDir()
_, err := g.source().Download(context.Background(), list[0], dir, nil)
if err == nil || !strings.Contains(err.Error(), "SHA256 mismatch") {
t.Fatalf("err = %v", err)
}
entries, _ := os.ReadDir(dir)
if len(entries) != 0 {
t.Fatalf("bad download kept: %v", entries)
}
}
+71 -30
View File
@@ -30,8 +30,37 @@ type Manifest struct {
BuiltAt string `json:"built_at"`
FileCount int `json:"file_count"`
DLLCount int `json:"dll_count"`
RawBytes int64 `json:"raw_bytes"`
RawBytes ByteCount `json:"raw_bytes"`
SHA256 map[string]string `json:"sha256"`
// Schema 2 (docs/portable-runtime-spec.md §3.1, §5, §7): what the package
// was really built from. A package with patches is not "pure upstream".
VendorQemuCommit string `json:"vendor_qemu_commit,omitempty"`
UtilCommit string `json:"util_commit,omitempty"`
MetalCommit string `json:"metal2vulkan_commit,omitempty"`
Patches []Patch `json:"patches,omitempty"`
Channel string `json:"channel,omitempty"` // candidate | stable
SourcePackage string `json:"source_package,omitempty"` // file name of the matching source archive
}
// ByteCount is an integer that also accepts a whole-number float ("962466926.0"),
// which PowerShell 7 wrote into manifests before pack-runtime.ps1 cast it.
type ByteCount int64
func (b *ByteCount) UnmarshalJSON(data []byte) error {
var f float64
if err := json.Unmarshal(data, &f); err != nil {
return err
}
*b = ByteCount(f)
return nil
}
// Patch is one local patch applied on top of upstream.
type Patch struct {
Name string `json:"name"`
Target string `json:"target"` // e.g. "vendor/qemu"
SHA256 string `json:"sha256"`
}
type Installed struct {
@@ -301,37 +330,49 @@ func fileSHA256(path string) (string, error) {
return hex.EncodeToString(h.Sum(nil)), nil
}
func extractTarZst(archivePath, destDir string) error {
// Windows 10/11 built-in bsdtar supports .tar.zst natively on modern builds;
// fall back to zstd -dc | tar -xf if needed.
cmd := exec.Command("tar", "-xf", archivePath, "-C", destDir)
configureCmd(cmd)
if out, err := cmd.CombinedOutput(); err == nil {
return nil
} else {
zstdBin := findZstd()
if zstdBin == "" {
return fmt.Errorf("tar -xf failed (%v: %s) and zstd was not found", err, strings.TrimSpace(string(out)))
// tarCommand is Windows' own bsdtar (System32/tar.exe, Windows 10 1803+),
// which reads .tar.zst directly and takes "D:\..." paths. A bare "tar" can
// resolve to GNU tar from Git or MSYS2, which does neither.
func tarCommand() string {
if runtime.GOOS == "windows" {
if root := os.Getenv("SystemRoot"); root != "" {
p := filepath.Join(root, "System32", "tar.exe")
if _, err := os.Stat(p); err == nil {
return p
}
}
z := exec.Command(zstdBin, "-dc", archivePath)
t := exec.Command("tar", "-xf", "-", "-C", destDir)
configureCmd(z)
configureCmd(t)
pipe, err := z.StdoutPipe()
if err != nil {
return err
}
t.Stdin = pipe
if err := z.Start(); err != nil {
return err
}
tOut, tErr := t.CombinedOutput()
zErr := z.Wait()
if tErr != nil {
return fmt.Errorf("tar extract failed: %v (%s)", tErr, strings.TrimSpace(string(tOut)))
}
return zErr
}
return "tar"
}
func extractTarZst(archivePath, destDir string) error {
tarBin := tarCommand()
cmd := exec.Command(tarBin, "-xf", archivePath, "-C", destDir)
configureCmd(cmd)
out, err := cmd.CombinedOutput()
if err == nil {
return nil
}
// Fallback for a tar without zstd: decompress to a temporary .tar first.
// (Piping zstd into tar deadlocked when tar exited early: zstd blocked on a
// full pipe nobody read.)
zstdBin := findZstd()
if zstdBin == "" {
return fmt.Errorf("tar -xf failed (%v: %s) and zstd was not found", err, strings.TrimSpace(string(out)))
}
tmpTar := filepath.Join(destDir, ".extract.tar")
defer os.Remove(tmpTar)
z := exec.Command(zstdBin, "-d", "-q", "-f", archivePath, "-o", tmpTar)
configureCmd(z)
if zOut, zErr := z.CombinedOutput(); zErr != nil {
return fmt.Errorf("zstd -d failed: %v (%s)", zErr, strings.TrimSpace(string(zOut)))
}
t := exec.Command(tarBin, "-xf", tmpTar, "-C", destDir)
configureCmd(t)
if tOut, tErr := t.CombinedOutput(); tErr != nil {
return fmt.Errorf("tar extract failed: %v (%s)", tErr, strings.TrimSpace(string(tOut)))
}
return nil
}
func findZstd() string {
+37
View File
@@ -0,0 +1,37 @@
package main
import (
"fmt"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
)
// checkStartMemory refuses to start a VM whose guest RAM can't be committed
// right now. Without it QEMU exits with "Cannot set up guest memory 'ram'"
// (measured 2026-11-28, portable-runtime-spec.md §5.1), which says nothing
// about what to do.
func (a *App) checkStartMemory(c *reims.Client, name string) error {
avail, ok := host.CommitAvailGB()
if !ok {
return nil
}
d, err := a.GetVMDetail(name)
if err != nil {
return nil // can't tell; let reims-ctl report its own error
}
memGB, ok := reims.ParseSizeGB(d.Memory)
if !ok {
return nil
}
if memGB+host.StartMarginGB <= avail {
return nil
}
a.mu.Lock()
loc := a.cfg.Locale
root := a.cfg.DataRoot
a.mu.Unlock()
rec := host.RecommendedMemoryGB(host.Inspect(root))
return fmt.Errorf("%s", i18n.T(loc, "err.commit_memory", memGB, avail, rec))
}
+1
View File
@@ -10,4 +10,5 @@
| 文件 | 目标仓库 / 基准 commit | 解决的问题 | 上游状态 |
| :--- | :--- | :--- | :--- |
| `reims-vgpu-cargo-lock.patch` | `steelbrain/reims-vgpu` (`3731afd`) 的 `Cargo.lock` | 不改代码:cargo 构建时给 `metal2vulkan`、`metal2vulkan-air`、`metal2vulkan-runtime` 三个包补上了 `source = "git+…metal2vulkan?rev=0b0ac58…"`。为了让源码包和实际构建逐字节一致,照实声明(2026-11-28 从本机构建目录 `git diff` 取得) | 不需要上游修复;上游 `Cargo.lock` 补齐后即可删除 |
| `qemu-whpx-win10-compat.patch` | `steelbrain/qemu-reims-vgpu` (`4571bc5`) | 修复 Windows 10 19045 上 WHPX 两处必现崩溃:① `whpx_tsc_deadline_refused()` 在正式 partition 上删建 vCPU 0 导致 `WHvCreateVirtualProcessor` 返回 `0x80070057`;② `whpx_set_registers()` 调用 Win11 新增的 `WHvResetPartition` 未判空导致 `0xc0000005` 崩溃 | 待提交上游 PR |
+28
View File
@@ -0,0 +1,28 @@
diff --git a/Cargo.lock b/Cargo.lock
index 106e75e..01bf052 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -213,6 +213,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "metal2vulkan"
version = "0.2.0"
+source = "git+https://github.com/steelbrain/metal2vulkan?rev=0b0ac58eb0f69ed3b37007fbdf3b135a46f90699#0b0ac58eb0f69ed3b37007fbdf3b135a46f90699"
dependencies = [
"ash",
"metal2vulkan-air",
@@ -223,6 +224,7 @@ dependencies = [
[[package]]
name = "metal2vulkan-air"
version = "0.2.0"
+source = "git+https://github.com/steelbrain/metal2vulkan?rev=0b0ac58eb0f69ed3b37007fbdf3b135a46f90699#0b0ac58eb0f69ed3b37007fbdf3b135a46f90699"
dependencies = [
"sha2 0.11.1",
]
@@ -230,6 +232,7 @@ dependencies = [
[[package]]
name = "metal2vulkan-runtime"
version = "0.2.0"
+source = "git+https://github.com/steelbrain/metal2vulkan?rev=0b0ac58eb0f69ed3b37007fbdf3b135a46f90699#0b0ac58eb0f69ed3b37007fbdf3b135a46f90699"
dependencies = [
"ash",
"libc",
+180
View File
@@ -0,0 +1,180 @@
package main
// Online runtime install from GitHub Releases (internal/runtime/remote.go).
// Downloads run as "runtime-install" tasks, so progress shows in the status bar.
import (
"context"
"errors"
"fmt"
"os"
"strings"
"sync"
"time"
"github.com/Nwflower/reims-go/internal/config"
"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) baseCtx() context.Context {
if a.ctx != nil {
return a.ctx
}
return context.Background()
}
func (a *App) includeCandidate() bool {
a.mu.Lock()
defer a.mu.Unlock()
return a.cfg.RuntimeChannel == rt.ChannelCandidate
}
// remoteCache keeps the release list for a while: GitHub allows 60
// unauthenticated API requests an hour, and the host page, first launch and
// the CLI all ask for it.
var remoteCache struct {
sync.Mutex
at time.Time
candidate bool
list []rt.Remote
}
const remoteCacheTTL = 10 * time.Minute
// ListRemoteRuntimes lists published runtimes for the configured channel.
func (a *App) ListRemoteRuntimes() ([]rt.Remote, error) {
cand := a.includeCandidate()
remoteCache.Lock()
defer remoteCache.Unlock()
if remoteCache.list != nil && remoteCache.candidate == cand && time.Since(remoteCache.at) < remoteCacheTTL {
return remoteCache.list, nil
}
list, err := rt.DefaultSource().ListRemote(a.baseCtx(), cand)
if err != nil {
return nil, err
}
remoteCache.at, remoteCache.candidate, remoteCache.list = time.Now(), cand, list
return list, nil
}
// forgetRemoteRuntimes drops the cached list (after an install or a channel change).
func forgetRemoteRuntimes() {
remoteCache.Lock()
remoteCache.list = nil
remoteCache.Unlock()
}
// SetRuntimeChannel picks "stable" or "candidate" for online installs.
func (a *App) SetRuntimeChannel(channel string) error {
if channel != rt.ChannelStable && channel != rt.ChannelCandidate {
return fmt.Errorf("unknown channel %q", channel)
}
a.mu.Lock()
defer a.mu.Unlock()
a.cfg.RuntimeChannel = channel
forgetRemoteRuntimes()
return config.Save("", a.cfg)
}
// InstallRuntimeOnline downloads, verifies and installs a published runtime
// ("" or "latest" for the newest on the channel) and makes it active. It runs
// in the background and returns the task ID; CancelTask pauses the download,
// which resumes on the next install.
func (a *App) InstallRuntimeOnline(commit string) (string, error) {
a.mu.Lock()
if a.needsSetup {
a.mu.Unlock()
return "", errors.New("choose a data folder first")
}
cfg := *a.cfg
a.mu.Unlock()
subject := strings.TrimSpace(commit)
if subject == "" {
subject = "latest"
}
for _, t := range tasks.list() {
if t.Kind == "runtime-install" && t.Status == TaskRunning {
return t.ID, nil
}
}
a.ensureTaskEmitter()
ctx, cancel := context.WithCancel(a.baseCtx())
id := tasks.start("runtime-install", subject, "", cancel)
go func() {
defer cancel()
res, err := a.installRuntime(ctx, &cfg, commit, id)
switch {
case err == nil:
tasks.finish(id, res, nil)
case ctx.Err() != nil:
a.emitLog("runtime", "Runtime download paused; installing again continues where it stopped")
tasks.finish(id, "", context.Canceled)
default:
a.emitLog("runtime", "Runtime install error: "+err.Error())
tasks.finish(id, "", err)
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
}()
return id, nil
}
func (a *App) installRuntime(ctx context.Context, cfg *config.Config, commit, taskID string) (string, error) {
src := rt.DefaultSource()
step := func(msg string) {
a.emitLog("runtime", msg)
tasks.update(taskID, installer.Update{Kind: installer.KindStep, Message: msg, Percent: -1})
}
step("Looking up runtime releases on GitHub")
// An explicit commit may be a candidate even on the stable channel: the
// user asked for it by name.
list, err := src.ListRemote(ctx, cfg.RuntimeChannel == rt.ChannelCandidate || (commit != "" && commit != "latest"))
if err != nil {
return "", err
}
r, err := rt.Pick(list, commit)
if err != nil {
return "", err
}
if !rt.IsInstalled(cfg, r.Commit) {
step("Downloading runtime " + r.Commit)
path, err := src.Download(ctx, *r, rt.DownloadsDir(cfg), func(done, total int64) {
tasks.update(taskID, installer.Update{
Kind: installer.KindProgress, Step: "downloading runtime " + r.Commit,
Done: done, Total: total, Percent: percent(done, total),
})
})
if err != nil {
return "", err
}
step("Installing runtime " + r.Commit)
inst, err := rt.InstallFromArchive(cfg, path)
if err != nil {
return "", err
}
_ = os.Remove(path) // the unpacked runtime is what's kept
r.Commit = inst.Commit
}
a.mu.Lock()
a.cfg.ActiveRuntime = r.Commit
err = config.Save("", a.cfg)
a.mu.Unlock()
if err != nil {
return "", err
}
a.emitLog("runtime", fmt.Sprintf("Runtime %s (%s) installed and active", r.Commit, r.Channel))
return r.Commit, nil
}
func percent(done, total int64) float64 {
if total <= 0 {
return -1
}
return float64(done) * 100 / float64(total)
}
+171
View File
@@ -0,0 +1,171 @@
<#
.SYNOPSIS
Pack the sources of the copyleft MSYS2 packages whose DLLs a runtime bundles,
as a separate release asset.
.DESCRIPTION
Reads the "# Packages" list from a runtime's MSYS2-PACKAGES.txt, looks up each
package's source name (%BASE%) and licenses in the local pacman database, and
keeps the packages whose license requires source (GPL / LGPL / MPL) unless an
alternative licence without those can be chosen (for example "GPL OR FTL").
For each kept package it downloads <base>-<version>.src.tar.zst and its .sig
from repo.msys2.org (cached in -CacheDir), checks the signature against the
MSYS2 keyring with gpgv, and packs them into
reims-runtime-msys2-src-<commit>.tar.zst in -OutDir. The archive's hash is
added to -OutDir\SHA256SUMS.txt (an existing line for it is replaced).
Published in the same GitHub Release as the runtime, so the sources are
offered from the same place as the binaries (GPLv2 §3, LGPL-2.1 §6).
.EXAMPLE
pwsh -File scripts/pack-msys2-sources.ps1 -PackagesFile MSYS2-PACKAGES.txt -Commit 3731afd -OutDir D:\Data\reims-go\releases\3731afd-candidate
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)] [string]$PackagesFile,
[Parameter(Mandatory)] [string]$Commit,
[Parameter(Mandatory)] [string]$OutDir,
[string]$Msys2 = 'D:\DevTools\msys64',
[string]$CacheDir = 'D:\Data\reims-go\releases\msys2-sources-cache',
[string]$TempRoot = 'D:\Build\Temp',
[string]$Mirror = 'https://repo.msys2.org/mingw/sources'
)
$ErrorActionPreference = 'Stop'
$localDb = Join-Path $Msys2 'var\lib\pacman\local'
$bash = Join-Path $Msys2 'usr\bin\bash.exe'
$zstd = Join-Path $Msys2 'usr\bin\zstd.exe'
function Write-Utf8([string]$path, [string]$text) {
[IO.File]::WriteAllText($path, $text.Replace("`r`n", "`n"), [Text.UTF8Encoding]::new($false))
}
function Read-Desc([string]$name, [string]$version) {
$file = Join-Path $localDb "$name-$version\desc"
if (-not (Test-Path -LiteralPath $file)) {
throw "$name $version is not in the local pacman database ($file): was MSYS2 updated after the runtime was built?"
}
$fields = @{}
$key = $null
foreach ($line in Get-Content -LiteralPath $file) {
if ($line -match '^%(\w+)%$') { $key = $Matches[1]; $fields[$key] = @(); continue }
if ($key -and $line -ne '') { $fields[$key] += $line }
}
return $fields
}
# A licence entry needs source unless one OR-alternative is free of copyleft.
# Entries prefixed "documentation:" cover only docs, which aren't shipped.
function Test-NeedsSource([string[]]$licenses) {
foreach ($entry in $licenses) {
if ($entry -like 'documentation:*') { continue }
$expr = $entry -replace '^spdx:', ''
$alternatives = $expr -split '\s+OR\s+'
$allCopyleft = $true
foreach ($alt in $alternatives) {
if ($alt -notmatch 'GPL|MPL') { $allCopyleft = $false }
}
if ($allCopyleft) { return $true }
}
return $false
}
function To-MsysPath([string]$winPath) {
$p = $winPath -replace '\\', '/'
if ($p -match '^([A-Za-z]):(.*)$') { return '/' + $Matches[1].ToLower() + $Matches[2] }
return $p
}
# ── 1. Which packages need source ────────────────────────────
$text = Get-Content -Raw -LiteralPath $PackagesFile
$section = ($text -split '# Packages[^\n]*\n', 2)[1]
if (-not $section) { throw "No '# Packages' section in $PackagesFile" }
$packages = $section -split "`n" | Where-Object { $_ -match '^\S+ \S+$' } | ForEach-Object {
$n, $v = $_ -split ' '
$d = Read-Desc $n $v
[pscustomobject]@{
Name = $n
Version = $v
Base = $d['BASE'][0]
Licenses = $d['LICENSE']
Needs = (Test-NeedsSource $d['LICENSE'])
}
}
$needed = @($packages | Where-Object Needs | Sort-Object Base, Version -Unique)
Write-Host ("==> {0} of {1} packages need source; {2} source archives" -f @($packages | Where-Object Needs).Count, $packages.Count, $needed.Count)
# ── 2. Download and verify ───────────────────────────────────
New-Item -ItemType Directory -Force -Path $CacheDir, $OutDir | Out-Null
foreach ($p in $needed) {
$file = "$($p.Base)-$($p.Version).src.tar.zst"
foreach ($f in @($file, "$file.sig")) {
$dest = Join-Path $CacheDir $f
if (-not (Test-Path -LiteralPath $dest)) {
Write-Host " downloading $f"
Invoke-WebRequest -Uri "$Mirror/$f" -OutFile "$dest.part" -UserAgent 'reims-go-packager'
Move-Item -LiteralPath "$dest.part" -Destination $dest -Force
}
}
$cache = To-MsysPath $CacheDir
$out = & $bash -lc "LC_ALL=C gpgv --keyring /etc/pacman.d/gnupg/pubring.gpg '$cache/$file.sig' '$cache/$file' 2>&1"
if ($LASTEXITCODE -ne 0) { throw "Signature check failed for ${file}:`n$out" }
$signer = ($out | Select-String 'Good signature from "([^"]+)"').Matches.Groups[1].Value
$p | Add-Member -NotePropertyName File -NotePropertyValue $file
$p | Add-Member -NotePropertyName Signer -NotePropertyValue $signer
}
# ── 3. Pack ──────────────────────────────────────────────────
$name = "reims-runtime-msys2-src-$Commit"
$stage = Join-Path $TempRoot "pack-$name"
if (Test-Path -LiteralPath $stage) { Remove-Item -Recurse -Force -LiteralPath $stage }
$dir = Join-Path $stage $name
New-Item -ItemType Directory -Force -Path (Join-Path $dir 'sources') | Out-Null
foreach ($p in $needed) {
Copy-Item -LiteralPath (Join-Path $CacheDir $p.File) -Destination (Join-Path $dir 'sources')
Copy-Item -LiteralPath (Join-Path $CacheDir "$($p.File).sig") -Destination (Join-Path $dir 'sources')
}
$rows = foreach ($p in ($packages | Sort-Object Name)) {
$lic = ($p.Licenses -join '; ') -replace '\|', '/'
$src = if ($p.Needs) { "``sources/$("$($p.Base)-$($p.Version).src.tar.zst")``" } else { '— (permissive licence; text in the runtime''s licenses/)' }
"| ``$($p.Name -replace '^mingw-w64-clang-x86_64-', '')`` | $($p.Version) | $lic | $src |"
}
Write-Utf8 (Join-Path $dir 'README.md') @"
# MSYS2 package sources for reims-runtime-win-x64-$Commit
The runtime's ``qemu/bin`` bundles DLLs from MSYS2 CLANG64 packages. This archive
holds, unmodified, the source packages of every one whose licence requires source
(GPL, LGPL or MPL with no permissive alternative), exactly as MSYS2 publishes them
at $Mirror, each with its detached signature (``.sig``), checked with gpgv
against the MSYS2 keyring when this archive was made.
A ``.src.tar.zst`` contains the PKGBUILD, the upstream source tarball and MSYS2's
patches: ``makepkg-mingw`` in an MSYS2 shell rebuilds the package.
| Package | Version | Licence | Source |
| :-- | :-- | :-- | :-- |
$($rows -join "`n")
"@
$tar = Join-Path $TempRoot "$name.tar"
& tar.exe -cf $tar -C $stage $name
if ($LASTEXITCODE -ne 0) { throw 'tar failed' }
$archive = Join-Path $OutDir "$name.tar.zst"
& $zstd -T0 -3 -q -f $tar -o $archive # contents are already compressed
if ($LASTEXITCODE -ne 0) { throw 'zstd failed' }
Remove-Item -LiteralPath $tar -Force
Remove-Item -Recurse -Force -LiteralPath $stage
# ── 4. SHA256SUMS.txt ────────────────────────────────────────
$hash = (Get-FileHash -Algorithm SHA256 -LiteralPath $archive).Hash.ToLowerInvariant()
$sums = Join-Path $OutDir 'SHA256SUMS.txt'
$lines = @()
if (Test-Path -LiteralPath $sums) {
$lines = @(Get-Content -LiteralPath $sums | Where-Object { $_ -and $_ -notmatch " $([regex]::Escape("$name.tar.zst"))$" })
}
$lines += "$hash $name.tar.zst"
Write-Utf8 $sums (($lines -join "`n") + "`n")
Write-Host '==> Done' -ForegroundColor Green
'{0} {1:N1} MB ({2} source archives, all signatures good)' -f $archive, ((Get-Item $archive).Length / 1MB), $needed.Count
+247 -97
View File
@@ -1,147 +1,297 @@
<#
.SYNOPSIS
Pack a standalone, MSYS2-free portable reims-vgpu runtime bundle for Windows x64.
Pack a portable reims-vgpu runtime for Windows x64, its matching source
package, and SHA256SUMS.txt, ready to publish as a GitHub Release.
.DESCRIPTION
Collects reims-ctl.exe, reims-util.exe, and the self-contained QEMU directory
(with its bundled CLANG64/libva DLLs and share/ data), generates manifest.json
with SHA-256 hashes, copies NOTICE.md and upstream LICENSE files, and compresses
the bundle into a .tar.zst archive (falling back to .zip if zstd is unavailable).
Outputs, in -OutDir (all four are assets of one GitHub Release):
reims-runtime-win-x64-<commit>.tar.zst runtime (bin/, qemu/, manifest.json,
NOTICE.md, licenses/, patches/,
MSYS2-PACKAGES.txt)
reims-runtime-src-<commit>.tar.zst corresponding source: pristine upstream
trees at the built commits + patches/
reims-runtime-msys2-src-<commit>.tar.zst sources of the copyleft MSYS2 packages
whose DLLs are bundled (pack-msys2-sources.ps1)
SHA256SUMS.txt all three archives
manifest.json (schema 2) states what the package was really built from:
upstream commit, vendor/qemu commit, reims-util and metal2vulkan commits,
every local patch with its SHA256, and the channel. A package built with
patches is never described as pure upstream (AGENTS.md rule 5).
Before packing, each patch in -Patches is checked against the build tree:
the tree's diff must equal the patch, so the source package matches the
binaries. A mismatch stops the script.
.EXAMPLE
.\scripts\pack-runtime.ps1
.\scripts\pack-runtime.ps1 -OutDir D:\Data\reims-go\releases -ZstdLevel 15
pwsh -File scripts/pack-runtime.ps1 -Channel candidate
#>
[CmdletBinding()]
param(
[string]$ReimsRepo = 'D:\DevTools\reims-vgpu',
[string]$CargoBin = 'D:\DevTools\cargo\bin',
[string]$QemuDir = 'D:\Data\macos-vm-lab\reims\data\reims-ctl\qemu\current',
[string]$OutDir = 'D:\Data\reims-go\releases',
[string]$TempRoot = 'D:\Build\Temp',
[int]$ZstdLevel = 15
[string]$ReimsRepo = 'D:\DevTools\reims-vgpu',
[string]$CargoHome = 'D:\DevTools\cargo',
[string]$QemuDir = 'D:\Data\macos-vm-lab\reims\data\reims-ctl\qemu\current',
[string]$Msys2 = 'D:\DevTools\msys64',
[string]$OutDir = 'D:\Data\reims-go\releases',
[string]$TempRoot = 'D:\Build\Temp',
[ValidateSet('candidate', 'stable')]
[string]$Channel = 'candidate',
[int]$ZstdLevel = 15
)
$ErrorActionPreference = 'Stop'
$repoRoot = Split-Path -Parent $PSScriptRoot
$patchesDir = Join-Path $repoRoot 'patches'
$CargoBin = Join-Path $CargoHome 'bin'
function Resolve-Zstd {
$candidates = @(
(Get-Command zstd.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source),
'D:\DevTools\msys64\usr\bin\zstd.exe',
'D:\DevTools\msys64\clang64\bin\zstd.exe'
) | Where-Object { $_ -and (Test-Path -LiteralPath $_) }
return ($candidates | Select-Object -First 1)
function Invoke-Native([string]$exe, [string[]]$argv) {
& $exe @argv
if ($LASTEXITCODE -ne 0) { throw "$exe $($argv -join ' ') failed ($LASTEXITCODE)" }
}
# 1. Verify inputs
function Get-Sha256([string]$path) {
(Get-FileHash -Algorithm SHA256 -LiteralPath $path).Hash.ToLowerInvariant()
}
function Write-Utf8([string]$path, [string]$text) {
[IO.File]::WriteAllText($path, $text.Replace("`r`n", "`n"), [Text.UTF8Encoding]::new($false))
}
function Resolve-Zstd {
@(
(Get-Command zstd.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source),
(Join-Path $Msys2 'usr\bin\zstd.exe'),
(Join-Path $Msys2 'clang64\bin\zstd.exe')
) | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Select-Object -First 1
}
function New-TarZst([string]$parent, [string]$name, [string]$archive) {
$zstd = Resolve-Zstd
if (-not $zstd) { throw 'zstd not found (install MSYS2 zstd or put zstd.exe on PATH)' }
$tar = Join-Path $TempRoot "$name.tar"
Invoke-Native 'tar.exe' @('-cf', $tar, '-C', $parent, $name)
Invoke-Native $zstd @('-T0', "-$ZstdLevel", '-q', '-f', $tar, '-o', $archive)
Remove-Item -LiteralPath $tar -Force
}
# ── 1. Inputs and provenance ─────────────────────────────────
$ctlExe = Join-Path $CargoBin 'reims-ctl.exe'
$utilExe = Join-Path $CargoBin 'reims-util.exe'
$qemuExe = Join-Path $QemuDir 'bin\qemu-system-x86_64.exe'
foreach ($p in @($ctlExe, $utilExe, $qemuExe)) {
if (-not (Test-Path -LiteralPath $p)) {
throw "Required runtime binary not found: $p"
}
if (-not (Test-Path -LiteralPath $p)) { throw "Required runtime binary not found: $p" }
}
$commit = (git -C $ReimsRepo rev-parse --short HEAD).Trim()
$fullCommit = (git -C $ReimsRepo rev-parse HEAD).Trim()
$commit = (git -C $ReimsRepo rev-parse --short HEAD).Trim()
$fullCommit = (git -C $ReimsRepo rev-parse HEAD).Trim()
$qemuRepo = Join-Path $ReimsRepo 'vendor\qemu'
$qemuCommit = (git -C $qemuRepo rev-parse HEAD).Trim()
# reims-util's pinned commit is a constant in reims-ctl (crates/reims-ctl/src/reims_util.rs, REV).
$utilSrc = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'crates\reims-ctl\src\reims_util.rs')
if ($utilSrc -notmatch 'pub const REV: &str = "([0-9a-f]{40})"') { throw 'reims-util REV not found in reims_util.rs' }
$utilCommit = $Matches[1]
# metal2vulkan's git rev as built (Cargo.lock in the build tree).
$lock = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'Cargo.lock')
if ($lock -notmatch 'metal2vulkan\?rev=([0-9a-f]{40})') { throw 'metal2vulkan rev not found in Cargo.lock' }
$m2vCommit = $Matches[1]
$qemuVersionLine = (& $qemuExe --version | Select-Object -First 1).Trim()
$utilVersionLine = (& $utilExe --version | Select-Object -First 1).Trim()
# ── 2. Patches must equal the build tree's diffs ─────────────
$patchSpecs = @(
@{ Name = 'reims-vgpu-cargo-lock.patch'; Target = 'reims-vgpu'; Repo = $ReimsRepo; Paths = @('Cargo.lock') },
@{ Name = 'qemu-whpx-win10-compat.patch'; Target = 'vendor/qemu'; Repo = $qemuRepo; Paths = @() }
)
$patches = @()
foreach ($ps in $patchSpecs) {
$file = Join-Path $patchesDir $ps.Name
if (-not (Test-Path -LiteralPath $file)) { throw "Patch missing: $file" }
$argv = @('-C', $ps.Repo, '-c', 'core.autocrlf=false', 'diff') + $ps.Paths
$treeDiff = (& git @argv | Out-String).Replace("`r`n", "`n")
$patchText = [IO.File]::ReadAllText($file).Replace("`r`n", "`n")
if ($treeDiff.TrimEnd() -ne $patchText.TrimEnd()) {
throw "$($ps.Name) does not match the build tree's diff in $($ps.Repo). Stop: don't edit patches automatically (AGENTS.md rule 4)."
}
$patches += [ordered]@{ name = $ps.Name; target = $ps.Target; sha256 = (Get-Sha256 $file) }
}
# Anything else changed in the build trees is undeclared: refuse.
$otherCtl = @(git -C $ReimsRepo status --porcelain --ignore-submodules=all | Where-Object { $_ -notmatch 'Cargo\.lock$' })
$otherQemu = @(git -C $qemuRepo status --porcelain --untracked-files=no | Where-Object { $_ -notmatch 'target/i386/whpx/whpx-all\.c$' })
if ($otherCtl.Count -or $otherQemu.Count) {
throw "Undeclared changes in the build trees:`n$($otherCtl + $otherQemu -join "`n")"
}
$bundleName = "reims-runtime-win-x64-$commit"
$stageRoot = Join-Path $TempRoot "pack-$bundleName"
$srcName = "reims-runtime-src-$commit"
$stageRoot = Join-Path $TempRoot "pack-$commit"
$bundleDir = Join-Path $stageRoot $bundleName
$srcDir = Join-Path $stageRoot $srcName
if (Test-Path -LiteralPath $stageRoot) { Remove-Item -Recurse -Force -LiteralPath $stageRoot }
New-Item -ItemType Directory -Force -Path "$bundleDir\bin", "$bundleDir\qemu", "$bundleDir\licenses", $OutDir | Out-Null
New-Item -ItemType Directory -Force -Path "$bundleDir\bin", "$bundleDir\qemu", "$bundleDir\licenses", "$bundleDir\patches", $srcDir, $OutDir | Out-Null
Write-Host "==> Staging $bundleName ..."
# ── 3. Runtime bundle ────────────────────────────────────────
Write-Host "==> Staging $bundleName ($Channel)"
Copy-Item -LiteralPath $ctlExe -Destination "$bundleDir\bin\reims-ctl.exe"
Copy-Item -LiteralPath $utilExe -Destination "$bundleDir\bin\reims-util.exe"
# Resolve junction target so robocopy/copy gets real files cleanly
$resolvedQemu = (Get-Item -LiteralPath $QemuDir).Target
if (-not $resolvedQemu) { $resolvedQemu = $QemuDir }
Copy-Item -Path "$resolvedQemu\*" -Destination "$bundleDir\qemu" -Recurse -Force
# Copy NOTICE.md and upstream license(s)
$repoRoot = Split-Path -Parent $PSScriptRoot
Copy-Item -LiteralPath (Join-Path $repoRoot 'NOTICE.md') -Destination "$bundleDir\NOTICE.md"
$upstreamLicense = Join-Path $ReimsRepo 'LICENSE'
if (Test-Path -LiteralPath $upstreamLicense) {
Copy-Item -LiteralPath $upstreamLicense -Destination "$bundleDir\licenses\reims-vgpu-LICENSE.txt"
foreach ($ps in $patchSpecs) { Copy-Item -LiteralPath (Join-Path $patchesDir $ps.Name) -Destination "$bundleDir\patches\" }
Copy-Item -LiteralPath (Join-Path $patchesDir 'README.md') -Destination "$bundleDir\patches\README.md"
$licenses = @{
'reims-vgpu-LICENSE.txt' = (Join-Path $ReimsRepo 'LICENSE')
'qemu-COPYING.txt' = (Join-Path $qemuRepo 'COPYING')
'qemu-COPYING.LIB.txt' = (Join-Path $qemuRepo 'COPYING.LIB')
}
$qemuLicense = Join-Path $ReimsRepo 'vendor\qemu\COPYING'
if (Test-Path -LiteralPath $qemuLicense) {
Copy-Item -LiteralPath $qemuLicense -Destination "$bundleDir\licenses\qemu-COPYING.txt"
foreach ($k in $licenses.Keys) {
if (Test-Path -LiteralPath $licenses[$k]) { Copy-Item -LiteralPath $licenses[$k] -Destination (Join-Path "$bundleDir\licenses" $k) }
}
if (Test-Path -LiteralPath (Join-Path $ReimsRepo 'LICENSES')) {
Copy-Item -Path (Join-Path $ReimsRepo 'LICENSES\*') -Destination "$bundleDir\licenses\" -Recurse -Force
}
# 2. Compute file inventory & key hashes
# MSYS2 CLANG64 DLLs: owning package and version, and where its source is.
Write-Host '==> Listing MSYS2 packages of bundled DLLs'
$bash = Join-Path $Msys2 'usr\bin\bash.exe'
$dlls = @(Get-ChildItem -LiteralPath "$bundleDir\qemu\bin" -Filter '*.dll' -File | Sort-Object Name)
$pkgLines = [Collections.Generic.List[string]]::new()
$pkgSet = [ordered]@{}
foreach ($d in $dlls) {
$owner = (& $bash -lc "LC_ALL=C pacman -Qqo /clang64/bin/$($d.Name) 2>/dev/null" | Select-Object -First 1)
if ($owner) {
$ver = (& $bash -lc "LC_ALL=C pacman -Q $owner" | Select-Object -First 1).Split(' ')[1]
$pkgLines.Add("$($d.Name)`t$owner`t$ver")
$pkgSet["$owner $ver"] = $true
} else {
$pkgLines.Add("$($d.Name)`t(not from an MSYS2 package: built with qemu, source in the source package)`t-")
}
}
$msysText = @"
# DLLs bundled in qemu/bin and the MSYS2 CLANG64 packages they come from
# (pacman -Qo on the build machine, $(Get-Date -Format 'yyyy-MM-dd')).
#
# Sources: every package whose licence requires source (GPL / LGPL / MPL) is in
# reims-runtime-msys2-src-$commit.tar.zst, published beside this runtime.
# The same files are also at:
# https://repo.msys2.org/mingw/sources/ (<package>-<version>.src.tar.zst, by pkgbase)
# https://github.com/msys2/MINGW-packages (build recipes)
# Licenses: see each package's /clang64/share/licenses/<package>/ in MSYS2.
DLL`tPACKAGE`tVERSION
$($pkgLines -join "`n")
# Packages ($($pkgSet.Count))
$($pkgSet.Keys -join "`n")
"@
Write-Utf8 "$bundleDir\MSYS2-PACKAGES.txt" $msysText
# ── 4. Source bundle ─────────────────────────────────────────
Write-Host "==> Staging $srcName"
function Export-GitTree([string]$repo, [string]$rev, [string]$dest) {
New-Item -ItemType Directory -Force -Path $dest | Out-Null
$tar = Join-Path $TempRoot ("git-export-" + [guid]::NewGuid() + '.tar')
Invoke-Native 'git' @('-C', $repo, 'archive', '--format=tar', '-o', $tar, $rev)
Invoke-Native 'tar.exe' @('-xf', $tar, '-C', $dest)
Remove-Item -LiteralPath $tar -Force
}
Export-GitTree $ReimsRepo $fullCommit (Join-Path $srcDir "reims-vgpu-$commit")
Export-GitTree $qemuRepo $qemuCommit (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu")
# QEMU's meson wraps downloaded for this build (dtc, keycodemapdb, ...): part of what was built.
Get-ChildItem -LiteralPath (Join-Path $qemuRepo 'subprojects') -Directory |
Where-Object { $_.Name -ne 'packagecache' -and -not (Test-Path -LiteralPath (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu\subprojects\$($_.Name)")) } |
ForEach-Object { Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu\subprojects\") -Recurse -Force }
$checkouts = Join-Path $CargoHome 'git\checkouts'
$utilTree = Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'reims-util-*' | ForEach-Object { Join-Path $_.FullName $utilCommit.Substring(0, 7) } | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1
$m2vTree = Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'metal2vulkan-*' | ForEach-Object { Join-Path $_.FullName $m2vCommit.Substring(0, 7) } | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1
if (-not $utilTree) { throw "reims-util source at $utilCommit not found under $checkouts" }
if (-not $m2vTree) { throw "metal2vulkan source at $m2vCommit not found under $checkouts" }
Export-GitTree $utilTree $utilCommit (Join-Path $srcDir "reims-util-$($utilCommit.Substring(0, 7))")
Export-GitTree $m2vTree $m2vCommit (Join-Path $srcDir "metal2vulkan-$($m2vCommit.Substring(0, 7))")
New-Item -ItemType Directory -Force -Path "$srcDir\patches" | Out-Null
Copy-Item -Path "$bundleDir\patches\*" -Destination "$srcDir\patches\"
Copy-Item -LiteralPath "$bundleDir\MSYS2-PACKAGES.txt" -Destination "$srcDir\MSYS2-PACKAGES.txt"
Copy-Item -LiteralPath "$bundleDir\NOTICE.md" -Destination "$srcDir\NOTICE.md"
Write-Utf8 "$srcDir\README.md" @"
# Source for $bundleName
Corresponding source for the binaries in ``$bundleName.tar.zst``.
| Directory | Upstream | Commit |
| :-- | :-- | :-- |
| ``reims-vgpu-$commit/`` | https://github.com/steelbrain/reims-vgpu | ``$fullCommit`` |
| ``reims-vgpu-$commit/vendor/qemu/`` | https://github.com/steelbrain/qemu-reims-vgpu | ``$qemuCommit`` |
| ``reims-util-$($utilCommit.Substring(0, 7))/`` | https://github.com/steelbrain/reims-util | ``$utilCommit`` |
| ``metal2vulkan-$($m2vCommit.Substring(0, 7))/`` | https://github.com/steelbrain/metal2vulkan | ``$m2vCommit`` |
The trees are pristine upstream. The binaries were built after applying the
patches in ``patches/``:
cd reims-vgpu-$commit && git apply ../patches/reims-vgpu-cargo-lock.patch
cd vendor/qemu && git apply ../../../patches/qemu-whpx-win10-compat.patch
(``patch -p1`` works too.) Then build as upstream documents (``scripts/install-ctl.sh``
in an MSYS2 CLANG64 shell). The DLLs in ``qemu/bin`` come from the MSYS2
packages listed in ``MSYS2-PACKAGES.txt``, with links to their sources.
"@
# ── 5. Manifest (schema 2) ───────────────────────────────────
$allFiles = Get-ChildItem -LiteralPath $bundleDir -Recurse -File
$rawBytes = ($allFiles | Measure-Object Length -Sum).Sum
$dllCount = @(Get-ChildItem -Path "$bundleDir\qemu\bin\*.dll" -ErrorAction SilentlyContinue).Count
$keyFiles = @(
'bin/reims-ctl.exe',
'bin/reims-util.exe',
'qemu/bin/qemu-system-x86_64.exe',
'qemu/bin/qemu-img.exe',
'qemu/bin/reims-vgpu-compile.exe'
)
$keyFiles = @('bin/reims-ctl.exe', 'bin/reims-util.exe', 'qemu/bin/qemu-system-x86_64.exe', 'qemu/bin/qemu-img.exe', 'qemu/bin/reims-vgpu-compile.exe')
$hashes = [ordered]@{}
foreach ($rel in $keyFiles) {
$fp = Join-Path $bundleDir ($rel -replace '/', '\')
if (Test-Path -LiteralPath $fp) {
$hashes[$rel] = (Get-FileHash -Algorithm SHA256 -LiteralPath $fp).Hash.ToLowerInvariant()
}
if (Test-Path -LiteralPath $fp) { $hashes[$rel] = Get-Sha256 $fp }
}
$manifest = [ordered]@{
schema_version = 1
name = $bundleName
platform = 'windows-x86_64'
upstream_repo = 'https://github.com/steelbrain/reims-vgpu'
commit = $commit
full_commit = $fullCommit
qemu_version = $qemuVersionLine
util_version = $utilVersionLine
built_at = (Get-Date).ToString('o')
file_count = $allFiles.Count
dll_count = $dllCount
raw_bytes = $rawBytes
sha256 = $hashes
schema_version = 2
name = $bundleName
platform = 'windows-x86_64'
upstream_repo = 'https://github.com/steelbrain/reims-vgpu'
commit = $commit
full_commit = $fullCommit
vendor_qemu_commit = $qemuCommit
util_commit = $utilCommit
metal2vulkan_commit = $m2vCommit
patches = $patches
channel = $Channel
source_package = "$srcName.tar.zst"
qemu_version = $qemuVersionLine
util_version = $utilVersionLine
built_at = (Get-Date).ToString('o')
file_count = $allFiles.Count + 1
dll_count = $dlls.Count
raw_bytes = [int64](($allFiles | Measure-Object Length -Sum).Sum) # PowerShell 7 sums to a double; JSON must stay an integer
sha256 = $hashes
}
$manifest | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath "$bundleDir\manifest.json" -Encoding utf8
Write-Utf8 "$bundleDir\manifest.json" ($manifest | ConvertTo-Json -Depth 5)
# 3. Compress
$zstd = Resolve-Zstd
$archivePath = $null
if ($zstd) {
$tarPath = Join-Path $stageRoot "$bundleName.tar"
$archivePath = Join-Path $OutDir "$bundleName.tar.zst"
Write-Host "==> Creating tar archive..."
& tar.exe -cf $tarPath -C $stageRoot $bundleName
if ($LASTEXITCODE -ne 0) { throw "tar.exe failed with exit code $LASTEXITCODE" }
Write-Host "==> Compressing with zstd (level $ZstdLevel, multi-threaded)..."
& $zstd -T0 -$ZstdLevel -f $tarPath -o $archivePath
if ($LASTEXITCODE -ne 0) { throw "zstd failed with exit code $LASTEXITCODE" }
} else {
$archivePath = Join-Path $OutDir "$bundleName.zip"
Write-Host "==> zstd not found; compressing with Compress-Archive (.zip)..."
Compress-Archive -Path $bundleDir -DestinationPath $archivePath -Force
}
# ── 6. Archives and sums ─────────────────────────────────────
Write-Host '==> Compressing runtime'
$runtimeArchive = Join-Path $OutDir "$bundleName.tar.zst"
New-TarZst $stageRoot $bundleName $runtimeArchive
Write-Host '==> Compressing sources'
$srcArchive = Join-Path $OutDir "$srcName.tar.zst"
New-TarZst $stageRoot $srcName $srcArchive
$archiveSizeMB = [math]::Round((Get-Item -LiteralPath $archivePath).Length / 1MB, 1)
$rawSizeMB = [math]::Round($rawBytes / 1MB, 1)
$archiveHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $archivePath).Hash.ToLowerInvariant()
"$archiveHash $(Split-Path -Leaf $archivePath)" | Set-Content -LiteralPath "$archivePath.sha256" -Encoding ascii
$rtHash = Get-Sha256 $runtimeArchive
$srcHash = Get-Sha256 $srcArchive
Write-Utf8 "$runtimeArchive.sha256" "$rtHash $bundleName.tar.zst`n"
Write-Utf8 (Join-Path $OutDir 'SHA256SUMS.txt') "$rtHash $bundleName.tar.zst`n$srcHash $srcName.tar.zst`n"
# Sources of the copyleft MSYS2 packages, as their own asset (adds a line to SHA256SUMS.txt).
& (Join-Path $PSScriptRoot 'pack-msys2-sources.ps1') -PackagesFile (Join-Path $bundleDir 'MSYS2-PACKAGES.txt') -Commit $commit -OutDir $OutDir -Msys2 $Msys2 -TempRoot $TempRoot
# 4. Clean staging dir
Remove-Item -Recurse -Force -LiteralPath $stageRoot
Write-Host ""
Write-Host "==> Done!" -ForegroundColor Green
Write-Host " Archive : $archivePath"
Write-Host " Raw : $rawSizeMB MB ($($allFiles.Count) files, $dllCount DLLs)"
Write-Host " Packed : $archiveSizeMB MB (ratio $([math]::Round($archiveSizeMB / $rawSizeMB * 100, 1))%)"
Write-Host " SHA256 : $archiveHash"
Write-Host ''
Write-Host '==> Done' -ForegroundColor Green
'{0,-10} {1} {2:N1} MB' -f 'runtime', $runtimeArchive, ((Get-Item $runtimeArchive).Length / 1MB)
'{0,-10} {1} {2:N1} MB' -f 'source', $srcArchive, ((Get-Item $srcArchive).Length / 1MB)
"channel $Channel; patches: $(($patches | ForEach-Object { $_.name }) -join ', '); DLLs: $($dlls.Count)"
+186
View File
@@ -0,0 +1,186 @@
package main
// First launch: the user picks the data folder before anything else is written
// (runtimes, VMs, installers and caches all live under it).
import (
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// DataRootChoice is a suggested data folder on one drive.
type DataRootChoice struct {
Path string `json:"path"`
FreeGB float64 `json:"free_gb"`
System bool `json:"system"`
External bool `json:"external"` // USB disk: may be unplugged while a VM runs
Recommended bool `json:"recommended"`
}
// DataRootCheck describes a folder the user is about to choose.
type DataRootCheck struct {
Path string `json:"path"`
FreeGB float64 `json:"free_gb"`
System bool `json:"system"`
External bool `json:"external"`
HasConfig bool `json:"has_config"` // an earlier reims-go data folder: its VMs are kept
Error string `json:"error,omitempty"`
}
// SuggestDataRoots offers <drive>\Data\reims-go on each fixed drive, the
// non-system drive with the most free space first.
func (a *App) SuggestDataRoots() []DataRootChoice {
var out []DataRootChoice
for _, d := range host.ListDrives() {
out = append(out, DataRootChoice{
Path: filepath.Join(d.Root, "Data", "reims-go"),
FreeGB: d.FreeGB,
System: d.System,
External: d.External,
})
}
// Internal non-system drives first, then the system drive, USB disks last;
// most free space first within each. A USB disk is never recommended.
rank := func(c DataRootChoice) int {
switch {
case c.External:
return 2
case c.System:
return 1
}
return 0
}
sort.SliceStable(out, func(i, j int) bool {
if rank(out[i]) != rank(out[j]) {
return rank(out[i]) < rank(out[j])
}
return out[i].FreeGB > out[j].FreeGB
})
if len(out) > 0 && !out[0].External {
out[0].Recommended = true
}
return out
}
// CheckDataRoot reports free space and whether dir already holds reims-go data.
func (a *App) CheckDataRoot(dir string) DataRootCheck {
dir = strings.TrimSpace(dir)
c := DataRootCheck{Path: dir}
if err := validateDataRoot(dir); err != nil {
c.Error = err.Error()
return c
}
c.FreeGB, _ = host.FreeGB(existingAncestor(dir))
c.System = isSystemVolume(dir)
vol := strings.ToUpper(filepath.VolumeName(dir))
for _, d := range host.ListDrives() {
if strings.EqualFold(d.Root[:2], vol) {
c.External = d.External
}
}
if _, err := os.Stat(filepath.Join(dir, "reims-go.json")); err == nil {
c.HasConfig = true
}
return c
}
// CompleteSetup makes dir the data folder: creates its layout, keeps an
// existing reims-go config there (its runtimes and VMs), records the choice for
// the next launch and leaves first-launch setup.
func (a *App) CompleteSetup(dir string) error {
dir = filepath.Clean(strings.TrimSpace(dir))
if err := validateDataRoot(dir); err != nil {
return err
}
a.mu.Lock()
locale := a.cfg.Locale
a.mu.Unlock()
cfgPath := filepath.Join(dir, "reims-go.json")
cfg, err := config.Load(cfgPath)
if err != nil {
return fmt.Errorf("read %s: %w", cfgPath, err)
}
cfg.DataRoot = dir
if _, statErr := os.Stat(cfgPath); statErr != nil {
cfg.Locale = locale // a new folder keeps the language picked on this screen
}
if err := cfg.EnsureDirs(); err != nil {
return err
}
if err := writable(dir); err != nil {
return err
}
if err := config.Save(cfgPath, cfg); err != nil {
return err
}
if err := config.SaveLocation(dir); err != nil {
return err
}
a.mu.Lock()
a.cfg = cfg
a.needsSetup = false
a.mu.Unlock()
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return nil
}
func validateDataRoot(dir string) error {
if dir == "" {
return errors.New("choose a folder")
}
if !filepath.IsAbs(dir) {
return fmt.Errorf("%s is not a full path", dir)
}
if filepath.Clean(dir) == filepath.VolumeName(dir)+string(filepath.Separator) || filepath.Dir(dir) == dir {
return errors.New("choose a folder, not a whole drive")
}
if strings.ContainsAny(dir, ",") {
// reims-ctl passes kext paths to reims-util as "PATH,MIN,MAX" and refuses ','
// (upstream 3731afd reims_util.rs:308-317); the data folder holds them.
return errors.New("the folder path can't contain ','")
}
if info, err := os.Stat(dir); err == nil && !info.IsDir() {
return fmt.Errorf("%s is a file", dir)
}
return nil
}
// existingAncestor is dir or its nearest existing parent (for free-space checks
// before the folder exists).
func existingAncestor(dir string) string {
for d := dir; ; d = filepath.Dir(d) {
if _, err := os.Stat(d); err == nil {
return d
}
if filepath.Dir(d) == d {
return d
}
}
}
func isSystemVolume(dir string) bool {
sys := os.Getenv("SystemDrive")
vol := filepath.VolumeName(dir)
return sys != "" && vol != "" && strings.EqualFold(sys, vol)
}
func writable(dir string) error {
f, err := os.CreateTemp(dir, ".write-test-*")
if err != nil {
return fmt.Errorf("can't write to %s: %w", dir, err)
}
name := f.Name()
f.Close()
return os.Remove(name)
}