Merge GitHub client updates into the Gitea mainline
Windows CI / verify (push) Successful in 6m28s

This commit was merged in pull request #3.
This commit is contained in:
YXC0915 committed 2026-12-07 03:33:06 +08:00
commit 577b2f73ed
271 files changed
+41085 -884

No files matched your search

@@ -0,0 +1,7 @@
{
"group": "new",
"order": 0,
"authors": ["Nwflower"],
"zh": "Apple 芯片 Mac 的实验性源码构建新增原生 macOS 虚拟机后端,可用本地 `.ipsw` 创建虚拟机并在独立窗口启动和关机。",
"en": "The experimental Apple silicon source build can create macOS VMs from local `.ipsw` restores, start them with a separate viewer, and shut them down."
}
@@ -0,0 +1,7 @@
{
"group": "new",
"order": 0,
"authors": ["icaruszezen"],
"zh": "新增默认启用的官方内置「macOS 自动装机助手」插件(`builtin.macos.autoinstall`)、AI 受控会话可视化、键鼠接管与画面防误触锁定、受保护阶段确认机制、macOS 离线首启预配置(跳过设置助理)以及自动装机宿主扩展能力。内置自动装机插件采用纯本地 Windows OCR(支持按需下载或离线校验导入 RapidOCR ONNX 备选模型)与声明式规则推进恢复终端安装、跨重启等待、退出恢复并重启与设置助理,截屏与密码均不离开本机,且可在「插件」页随时停用并立即结束会话、零残留隐藏入口。虚拟机处于安装或恢复阶段时,自动化截图与键鼠输入均需经主窗口弹窗授权(支持 10/30/60 分钟或直到离开阶段,仅存内存);拒绝授权或插件权限不足导致自动化脚本未运行时,自动中止会话、清理临时凭证并兜底展示原版手动安装引导;操作期间在侧栏、详情页、系统托盘与虚拟机窗口浮层显示受控状态并提供暂停与停止按钮,支持物理键鼠接管暂停(可在设置页调整恢复时长)与防误触输入锁定模式。内置 macOS 离线安装新增按虚拟机隔离的只读预配置卷(新建向导与 `vm provision` 命令行均可选启用,与自动恢复安装独立开关、无插件亦可独立使用),仅在内存中派生加盐 PBKDF2 密码哈希(不落盘明文、不启自动登录),经原生 OpenDirectory 接口或离线目录属性表创建管理员、跳过设置助理与键盘设置助理并按需预装 Guest Tools,退出恢复模式或删机时自动覆零清理。插件契约升级为 `pluginApi 1.3.0` 和 `uiApi 2.2.0`,新增 `contributes.autoInstallers` 通用自动装机扩展点、`vm autoinstall` 命令行、归一化区域无损 PNG 截图、`host/vm.finishInstall`、`host/vm.restart`、`host/vm.telemetry`、`host/ui.confirm`、`host/session.*`、`vm/phaseChanged` 以及 `host/download.start` 超时与自定义镜像二次确认([#103](https://github.com/Nwflower/Reims-Go/issues/103)、[#105](https://github.com/Nwflower/Reims-Go/issues/105)、[#129](https://github.com/Nwflower/Reims-Go/issues/129))。",
"en": "Add the default-enabled official built-in macOS Auto-Install Assistant plugin (`builtin.macos.autoinstall`), AI remote-control session visibility, physical input takeover and optional VM input lock, protected-phase confirmation, offline macOS first-boot provisioning (Setup Assistant skip), and generic auto-installer host foundations. The built-in auto-install plugin drives Recovery terminal installation, cross-reboot monitoring, exit recovery and restart, and Setup Assistant purely locally via Windows OCR (with optional user-confirmed RapidOCR ONNX fallback or SHA-256-verified offline bundle import) and declarative rules without sending screenshots or secrets off-device, and can be disabled in Plugins with immediate session teardown and zero UI residue. While a VM is in the installer or recovery phase, automated screenshots and input require an in-memory host confirmation grant (10/30/60 minutes or until phase exit); denying confirmation or plugin permissions when automation scripts cannot run aborts the session, wipes temporary credentials, and falls back to showing the original manual installation guide; active sessions appear in the sidebar, VM page, system tray, and a Win32 VM-window overlay with Pause and Stop controls, supporting physical takeover pause (with a configurable resume delay in Settings) and input-locked client shielding. Built-in offline macOS installation adds an opt-in per-VM read-only provisioning disk (independent of recovery auto-install in the Create Wizard and `vm provision` CLI, usable without plugins) that hashes passwords in memory via salted PBKDF2 (never writing plaintext passwords or auto-login), creates the local admin through native OpenDirectory or offline dslocal plists, skips Setup Assistant and Keyboard Setup Assistant, stages Guest Tools, and securely wipes the image on finish_install or VM deletion. The contracts move to `pluginApi 1.3.0` and `uiApi 2.2.0`, adding the generic `contributes.autoInstallers` extension point, `vm autoinstall` CLI subcommands, normalized-region PNG screenshots, `host/vm.finishInstall`, `host/vm.restart`, `host/vm.telemetry`, `host/ui.confirm`, `host/session.*`, `vm/phaseChanged`, and `host/download.start` connect/stall timeouts plus SHA-256-pinned custom mirror confirmation ([#103](https://github.com/Nwflower/Reims-Go/issues/103), [#105](https://github.com/Nwflower/Reims-Go/issues/105), [#129](https://github.com/Nwflower/Reims-Go/issues/129))."
}
@@ -0,0 +1,7 @@
{
"group": "improvements",
"order": 0,
"authors": ["reiasu2"],
"zh": "日志栏新增「导出排障包」入口,导出后弹出引导窗口展示自动检查结论与环境摘要,支持一键复制 `.zip` 压缩包文件或打开位置;框选多行「活动」日志时自动合并为单行格式,复制大段日志前提示导出排障包避免刷屏。",
"en": "Add an Export diagnostics button to the log bar and open a guidance dialog after export with automatic checks, an environment summary, Show in folder, and one-click `.zip` file copy; normalize multi-line Activity log selections into single lines and prompt before copying long log output."
}
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "Apple 芯片 Mac 的恢复镜像目录查询支持重试与 Apple 官方来源回退,原生红黄绿按钮与标题栏菜单纵向对齐。",
"en": "Retry Apple silicon restore catalog queries with an official Apple fallback, and vertically align the native window controls with the title bar menus."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "修复 macOS 上的开发构建,并防止关闭窗口时把应用隐藏到不存在的托盘。内置虚拟机运行时仍仅支持 Windows x64。",
"en": "Fix development builds on macOS and prevent the window from hiding to an unavailable tray. The built-in VM runtime still requires Windows x64."
}
@@ -0,0 +1,7 @@
{
"group": "new",
"order": 0,
"authors": ["Nwflower"],
"zh": "Apple 芯片 Mac 可在镜像页或新建向导内从 Apple 下载兼容恢复镜像,支持暂停续传,并使用系统原生的红黄绿窗口按钮。",
"en": "Download a compatible Apple restore image with pause and resume in Images or New VM on Apple silicon, and use the native macOS window controls."
}
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "Mac 客户端使用系统采样显示宿主机内存,不再误报内存满载,并修复无法显示的插件 SVG 图标。",
"en": "Show sampled host memory on macOS instead of reporting full memory use, and fix plugin SVG icons that failed to render."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "macOS 的应用、编辑和窗口菜单跟随当前界面语言,应用菜单统一显示 Reims-Go。",
"en": "Match the macOS application, Edit, and Window menus to the selected interface language and show Reims-Go as the application name."
}
@@ -0,0 +1,7 @@
{
"group": "improvements",
"order": 0,
"authors": ["Nwflower"],
"zh": "macOS 的「虚拟机」「视图」和「帮助」移至屏幕顶部的系统菜单栏,Windows 保留窗口内菜单。",
"en": "Move VM, View, and Help to the macOS system menu bar and keep them in the app window on Windows."
}
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "在 macOS 上使用本机 QQ 打开交流群邀请;不能直接打开时仍可打开邀请页。虚拟机的 SSH 入口也可在 Mac 的终端中打开。",
"en": "Open QQ group invites with the installed QQ app on macOS, with the invite page as a fallback. Open VM SSH sessions in the Mac terminal."
}
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "macOS 恢复镜像校验暂时失败后可继续重试,启动虚拟机时会等待读取状态,宿主机诊断会同时显示原生虚拟化和常规诊断信息。",
"en": "Retry temporary macOS restore image verification failures without redownloading, tolerate transient VM startup status errors, and show native virtualization alongside standard host diagnostics."
}
@@ -0,0 +1,7 @@
{
"group": "improvements",
"order": 0,
"authors": ["Nwflower"],
"zh": "Apple 芯片 Mac 的实验版改用独立的 Nivfold 运行器,支持安全取消安装,并在保存时检查宿主和客体的 CPU 与内存要求。",
"en": "The experimental Apple silicon build uses the standalone Nivfold runner, supports cooperative installation cancellation, and checks host and guest CPU and memory requirements before saving settings."
}
+2
View File
@@ -10,6 +10,8 @@ Reims-Go 是面向 Windows x86-64 的免编译 macOS 虚拟机桌面启动器与
Reims-Go 发布的便携运行时基于团队独立维护的 `reims-go/reims-vgpu` 和 `reims-go/qemu-reims-vgpu` 构建。运行时维护仓库通过 `vendor/qemu` 固定团队 QEMU 仓库的提交,并负责编译、依赖补丁、打包和预览发布。 [运行时维护仓库](https://github.com/reims-go/reims-vgpu) · [QEMU 维护仓库](https://github.com/reims-go/qemu-reims-vgpu) · [运行时构建流程](https://github.com/reims-go/reims-vgpu/blob/master/.github/workflows/runtime-preview.yml)
Apple 芯片 Mac 的实验性后端使用独立 `nivfold` 仓库中的原生运行器。虚拟设备、安装事务和运行器测试归 Nivfold;此仓库只维护客户端及兼容协议适配。
## 存储与调试目录纪律
1. 便携运行时、系统镜像、虚拟磁盘与快照只保存在用户本地指定的数据目录,不提交到仓库,也不放入 `.debug/`。
+15
View File
@@ -108,6 +108,21 @@ authorization of the copyright holder.
SPDX-License-Identifier: Unicode-3.0
## Optional local OCR fallback (built-in macOS Auto-Install Assistant)
When the Windows host lacks the required `Windows.Media.Ocr` language pack and
the user explicitly confirms fallback download or imports an offline archive
verified by SHA-256, the built-in macOS Auto-Install Assistant plugin may store
the following open-source components under its private plugin data directory
(`plugins/data/builtin.macos.autoinstall/ocr/`):
1. **RapidOCR / RapidOcrOnnx** (<https://github.com/RapidAI/RapidOcrOnnx>, <https://github.com/RapidAI/RapidOCR>) is licensed under the Apache License, Version 2.0.
2. **PP-OCRv4 mobile models** (PaddleOCR / RapidOCR ONNX weights) are licensed under the Apache License, Version 2.0.
3. **ONNX Runtime** (<https://github.com/microsoft/onnxruntime>) is licensed under the MIT License.
Reims-Go never bundles, downloads, or redistributes undocumented Windows OCR
libraries (`oneocr.dll`).
## Portable runtime
The portable runtime bundle (`reims-runtime-win-x64-<commit>.tar.zst`) contains
+20
View File
@@ -123,6 +123,26 @@ reims-go vm start macos-tahoe | Out-Host # Start the VM
With Go 1.26+, Node.js 22, pnpm 10 and the [Wails CLI](https://wails.io/docs/gettingstarted/installation) v2.17.1, run `wails build` in the repository root; the binary is written to `build\bin\reims-go.exe`. The runtime is built separately by the [Reims vGPU fork](https://github.com/reims-go/reims-vgpu).
On Apple silicon, the experimental client uses the standalone Nivfold runner instead of the Windows QEMU runtime. Run `sh build.sh` in a separate `nivfold` checkout first. Building the runner requires Xcode with Swift 6, and running it requires macOS 13 or later. The example assumes sibling checkouts; omit `--runtime` to build only the client.
```sh
node scripts/build-macos.mjs --runtime ../nivfold/.debug/runs/nivfold/nivfold
.debug/runs/macos-client/reims-go doctor
.debug/runs/macos-client/reims-go
```
In New VM, download the compatible macOS restore image offered by Apple for the current host, or choose an existing local `.ipsw`. The Images page can also download and manage cached images. Transfer only starts when you click Download, and downloaded images can be reused. Creation installs macOS onto a new virtual disk. When it finishes, start the VM and complete Setup Assistant manually in the separate guest window. CLI creation takes the absolute path to a local restore image:
```sh
client=.debug/runs/macos-client/reims-go
"$client" vm create --ipsw /absolute/path/to/Restore.ipsw mac-test
"$client" vm list
"$client" vm start mac-test
"$client" vm stop mac-test
```
The native backend cannot open Windows x86-64 VMs or their snapshots. This experimental build does not support snapshots, suspend, restore points, shared folders, or Reims vGPU.
</details>
## FAQ
+20
View File
@@ -119,6 +119,26 @@ reims-go vm start macos-tahoe | Out-Host # 启动虚拟机
需要 Go 1.26+、Node.js 22、pnpm 10 和 [Wails CLI](https://wails.io/docs/gettingstarted/installation) v2.17.1,在仓库根目录运行 `wails build`,产物在 `build\bin\reims-go.exe`。运行时由 [Reims vGPU fork](https://github.com/reims-go/reims-vgpu) 单独构建。
Apple 芯片 Mac 的实验版使用独立的 Nivfold 运行器,不安装 Windows 的 QEMU 运行时。先在单独检出的 `nivfold` 仓库运行 `sh build.sh`。运行器构建需要带 Swift 6 的 Xcode,运行需要 macOS 13 或更高版本。下例假设两个仓库位于同一个父目录;只构建客户端时可省略 `--runtime`。
```sh
node scripts/build-macos.mjs --runtime ../nivfold/.debug/runs/nivfold/nivfold
.debug/runs/macos-client/reims-go doctor
.debug/runs/macos-client/reims-go
```
在「新建虚拟机」中下载 Apple 为当前宿主提供的兼容恢复镜像,或选择已有的本地 `.ipsw`。「镜像」页也可下载和管理缓存。应用只在你点击下载后传输镜像,下载好的镜像可重复使用。创建会把系统安装到新虚拟磁盘;完成后点击「启动」,在独立窗口里手动完成客体的设置助理。命令行创建使用本地镜像的绝对路径:
```sh
client=.debug/runs/macos-client/reims-go
"$client" vm create --ipsw /absolute/path/to/Restore.ipsw mac-test
"$client" vm list
"$client" vm start mac-test
"$client" vm stop mac-test
```
Windows 上创建的 x86-64 虚拟机和快照不能在原生后端打开。实验版暂不支持快照、挂起、恢复点、共享文件夹或 Reims vGPU。
</details>
## 常见问题
+16 -4
View File
@@ -1,6 +1,6 @@
# 系统架构
桌面窗口与命令行共用同一份 Go 核心,面向 64 位 Windows 10 与 Windows 11。客户端只负责环境体检、资产下载、配置校验、生命周期编排与宿客协作,底层虚拟化与图形转换以受控子进程方式调用便携运行时完成。
桌面窗口与命令行共用同一份 Go 核心。Windows x64 使用 Reims vGPU 与 QEMU 运行时。Apple 芯片 Mac 可使用实验性原生驱动,通过独立运行器调用系统的虚拟化框架。客户端负责环境体检、配置校验与虚拟机生命周期编排。
## 总体分层
@@ -33,7 +33,7 @@ flowchart TB
Ctl --> QEMU
```
非 Windows 平台通过构建标签隔离系统原生调用并提供桩实现,保证全平台均可编译和运行单元测试。多语言词表在编译期同时生成前后端字典,默认跟随系统语言并支持通过声明式语言包扩展。
构建标签隔离系统原生调用,不支持的能力由对应平台拒绝。上图展示 Windows 的 Reims vGPU 路径。多语言词表在编译期同时生成前后端字典,默认跟随系统语言并支持通过声明式语言包扩展。
## 核心机制与安全边界
@@ -49,7 +49,7 @@ flowchart TB
便携运行时为每台运行中的虚拟机创建本地 Unix 域 QMP 套接字。宿主通过统一控制台路由串行处理每台虚拟机的截图、鼠标、键盘和文本输入,按驱动声明与虚拟机能力分派至内置虚拟机交互服务的 QMP 代理(每次操作后关闭连接,与生命周期操作共用同一把虚拟机锁)或驱动自带的控制台接口;缩略图、截屏、打字与代理控制共用该路由,桌面文本输入期间暂停后台缩略图捕获。
L3 插件经权限核验的 Host API 请求虚拟机状态、截图和输入操作,宿主不接受插件提供的 QMP 套接字或虚拟机目录。MCP 客户端通过 `reims-go plugin connect <plugin-id> <channel>` 与桌面进程通信;Windows 命名管道按可执行文件路径和用户 SID 摘要区分,ACL 限制当前用户并拒绝远程客户端。
L3 插件经权限核验的 Host API 请求虚拟机状态、截图和输入操作,宿主不接受插件提供的 QMP 套接字或虚拟机目录。虚拟机处于安装或恢复阶段时,外部插件的截图与键鼠输入必须先经主窗口弹窗确认,授权仅保留在内存中并在离开阶段、停机或点击停止后立即失效。外部插件操作期间,宿主通过独立的 Win32 虚拟机窗口浮层、详情页、侧栏和系统托盘展示受控状态并提供立即停止按钮,同时在虚拟机窗口内挂接物理键鼠监听,用户在窗口内操作键鼠时自动接管并暂停外部输入;受控会话激活期间自动抑制静态人工安装引导浮层。官方 macOS 自动装机助手以默认启用的内置插件接入同一套 `contributes.autoInstallers` 扩展点与宿主权限管道,连接新建向导、详情页与 `vm autoinstall` 命令行,停用后不展示任何入口且不阻碍第三方自动装机插件并存。MCP 客户端通过 `reims-go plugin connect <plugin-id> <channel>` 与桌面进程通信;Windows 命名管道按可执行文件路径和用户 SID 摘要区分,ACL 限制当前用户并拒绝远程客户端。
Windows 10 缺少虚拟化分区热重置能力,客体内部重启会导致虚拟化后端异常退出。在 Windows 10 宿主机上,客户端为虚拟机附加不自动重启标志,并额外挂载一条独立的本地 Unix 域控制套接字监听重启退出事件,进程干净退出后自动重新拉起。QMP 和插件控制通道均不使用 TCP 端口,防止虚拟机经用户态网络反向访问宿主机控制面。
@@ -57,6 +57,8 @@ Windows 10 缺少虚拟化分区热重置能力,客体内部重启会导致虚
宿客协作服务仅监听本机回环地址 `127.0.0.1`,为每台虚拟机分配独立的 256 位随机访问令牌,所有连接状态、剪贴板策略与文件路由均按驱动和实例隔离。
macOS 离线安装支持通过新建向导或 `reims-go vm provision` 按虚拟机生成只读首启预配置卷(`REIMSPROV`)。密码仅在内存中派生为加盐 SHA-512 PBKDF2 二进制属性表哈希,不向磁盘、配置或日志写入明文密码,且不写入自动登录凭据或免密 `sudo`。恢复辅助脚本检测到该卷时优先以 `startosinstall --installpackage` 注入自包含安装包,若安装器不支持则自动回退到标准安装并输出降级标记;预配置脚本在活体首启阶段经原生 OpenDirectory 接口(离线恢复阶段经本地目录属性表)创建本地管理员、跳过设置助理与键盘设置助理并按需预装 Guest Tools。退出恢复模式、非安装态冷启动与删除虚拟机均会剥离该盘参数并先覆零再删除镜像。
共享文件夹服务对每次读写强制约束在授权根目录之内,拦截目录穿越与越界符号链接。Windows 盘符只读共享默认全部关闭;启用后同时限制只读打开标志与写请求方法、核对持久化卷标识防止盘符漂移、限制目录遍历深度,并验证目录联接与符号链接目标仍位于已授权盘符内。
### 物理出口桥接
@@ -85,7 +87,7 @@ Npcap 桥接由可停用的内置扩展提供,通过逐台虚拟机的本地 U
### 托管型与进程型客体驱动
客体驱动按虚拟机进程的归属分为两类。进程型驱动让宿主拉起虚拟机进程,宿主据此判断运行状态、定位显示窗口并绑定处理器核心。托管型驱动在声明中带有 `hosted` 能力,虚拟机由驱动自己的管理层运行,宿主不探测其进程与窗口,也不提供全屏和绑核入口;仅当驱动同时声明控制台能力时才开放截屏与键入。
客体驱动按虚拟机进程的归属分为两类。进程型驱动让宿主拉起虚拟机进程,宿主据此判断运行状态、定位显示窗口并绑定处理器核心。托管型驱动在声明中带有 `hosted` 能力,虚拟机由驱动自己的管理层运行。宿主不探测托管型驱动的进程与窗口。声明查看窗口能力的驱动可自行唤出查看器。宿主不提供全屏和绑核入口;仅当驱动同时声明控制台能力时才开放截屏与键入。
托管型驱动通过宿主接口主动推送虚拟机的生命周期状态、就绪状态、所处阶段与客体系统信息。电源状态仍只取 `stopped`、`starting`、`running`、`stopping`、`suspended`、`broken` 与 `driver_unavailable`,就绪与阶段是独立字段,因此仍在启动中的客体显示为运行中但未就绪。推送缺失或过期时,宿主回退为向驱动查询。推送只对驱动自己名下的虚拟机生效。
@@ -111,6 +113,16 @@ macOS 专属逻辑集中在 `internal/macos/` 与 `frontend/src/macos/`,宿主
测试同时拒绝没有调用者的函数、前端导出、样式类与文案,拒绝前端模块循环引用,并限制单个 Go 函数的长度。
## Apple 芯片 Mac 原生后端
原生驱动只在 Darwin ARM64 上注册。独立 Nivfold 仓库维护运行器、签名和底层测试。Reims-Go 不包含它的源码,不在客户端构建中编译或下载运行器。客户端在自身可执行文件旁查找 Nivfold,不搜索工作目录或系统路径,并检查运行器标识和协议。开发构建可显式传入兼容的签名二进制。
Nivfold 按虚拟机独立启动。它使用本地恢复镜像安装系统,并一次发布虚拟硬件身份、辅助存储、磁盘和客体资源下限。只有完整安装的磁盘才可启动。旧版磁盘没有客体资源下限记录,保留兼容读取。原生磁盘与 Windows 的虚拟机、快照和挂起状态互不兼容。
运行器持有逐虚拟机的系统文件锁。管理命令使用当前用户限定的本地 Unix 套接字,不通过 PID 发送关机信号,也不开放 TCP 控制端口。虚拟机由运行器持有,独立于客户端窗口。系统启动后由用户在虚拟机窗口中完成客体设置。
Mac 与 Windows 共用镜像页和下载任务。Mac 通过 Nivfold 查询 Apple 为当前宿主提供的最新兼容恢复镜像。框架目录重试失败时,Nivfold 使用 Apple 设备目录中同时提供给当前 Mac 型号和虚拟 Mac 的恢复镜像。客户端只在用户触发后从 Apple 的 HTTPS 源下载。客户端根据强 ETag 续传,校验可用的官方摘要,并在框架确认镜像版本和兼容性后发布缓存。旧运行器或网络不可用时仍可选择本地镜像。
## 便携运行时与跨仓边界
便携运行时基于团队独立维护的 `reims-go/reims-vgpu` 和 `reims-go/qemu-reims-vgpu` 构建。运行时仓库固定 QEMU 子模块的提交,负责构建、依赖补丁、打包与 Alpha 发布。压缩包包含 `reims-ctl.exe`、`reims-util.exe`、QEMU、自包含运行库、实际应用的补丁和许可证全文。`manifest.json` 记录各组件的实际源码提交及补丁,调试符号单独打包分发。 [运行时维护仓库](https://github.com/reims-go/reims-vgpu) · [QEMU 维护仓库](https://github.com/reims-go/qemu-reims-vgpu)
+1 -1
View File
@@ -35,7 +35,7 @@
## 布局层级与视觉基线
窗口由左侧可折叠侧栏(`Ctrl+B`)、右侧主内容区、底部常驻状态栏与可收起日志抽屉(`Ctrl+L`)组成。侧栏上方列出虚拟机实例与新建入口(`Ctrl+N`),下方固定提供「镜像」「插件」「内核」「设置」(`Ctrl+,`)与「关于」入口。虚拟机操作按钮固定在详情页头而非全局标题栏,避免切换页面时顶栏跳动。
窗口由左侧可折叠侧栏(`Ctrl+B`)、右侧主内容区、底部常驻状态栏与可收起日志抽屉(`Ctrl+L`)组成。侧栏上方列出虚拟机实例与新建入口(`Ctrl+N`),下方固定提供「镜像」「插件」「内核」「设置」(`Ctrl+,`)与「关于」入口。虚拟机操作按钮固定在详情页头而非全局标题栏,避免切换页面时顶栏跳动。macOS 在系统菜单栏提供「虚拟机」「视图」和「帮助」菜单,应用及标准菜单均跟随界面语言,使用 `Command` 组合键;`Command+,` 打开应用设置,原有 `Ctrl` 快捷键仍可在窗口中使用。Windows 在窗口标题栏提供这三项菜单。
- 同一项硬件规格或运行状态在同一视图内只展示一次,相同动作不在同屏提供两个按钮出口。
- 页面只用单层分组容器或留白表达层级,禁止卡片嵌套卡片;下拉选择统一使用自绘弹出控件,不混用系统原生表单控件。
+10 -4
View File
@@ -20,7 +20,7 @@ flowchart TB
| 层级 | 运行形态 | 隔离与约束边界 |
| :--- | :--- | :--- |
| 编译期内置扩展 | 随主程序编译的模块,经同一注册表装载 | 核心默认主题始终启用;macOS 客体支持、宿客传输、剪贴板互通、输入服务、虚拟机交互与并行下载器可独立启停且停用零残留 |
| 编译期内置扩展 | 随主程序编译的模块,经同一注册表装载 | 核心默认主题始终启用;macOS 客体支持、macOS 镜像源、macOS 自动装机助手、宿客传输、剪贴板互通、输入服务、虚拟机交互与并行下载器可独立启停且停用零残留 |
| L1 声明式插件 | 纯 JSON 配置、词表、字体与静态样式资源 | 不含可执行代码,全部字段经宿主白名单与静态扫描校验 |
| 运行时包 | 原生虚拟化与工具二进制归档 | 自身不注册插件代码,仅由客体驱动以受控子进程调用 |
| L3 外部进程插件 | 每插件独立子进程,采用 `Content-Length` 分帧的双向 JSON-RPC 2.0 通信(日志走标准错误流) | 崩溃或死循环不拖垮主窗口;操作系统层面拥有当前用户完整账户权限,仅宿主接口受权限表约束 |
@@ -35,12 +35,16 @@ flowchart TB
内置 macOS 应用窗口插件默认关闭,依赖 Guest Tools 传输与虚拟机交互服务。用户启用后可在运行中的 macOS 虚拟机操作菜单中打开前台应用窗口。停用插件会移除操作入口并关闭独立窗口。
内置 macOS 自动装机助手插件默认启用,依赖虚拟机交互服务,在主进程内经同一套扩展点与宿主接口权限管道运行。它结合本机 Windows OCR(缺少语言包时可按需下载或离线导入 RapidOCR ONNX)与声明式规则推进恢复模式离线安装与设置助理,不向外部上传截屏或密文,停用后立即结束活动会话并移除新建向导、详情页与命令行的全部入口。
L3 插件可在清单 `contributes.channels` 中声明 `jsonl` 通道。桌面端的 `plugin connect` 经 Windows 当前用户限定的命名管道转发消息,不开放 TCP 或 HTTP MCP 监听。每条连接带一个会话标识,宿主随 `channel/<通道>/message` 一并转发,插件按会话区分请求 ID 和取消。连接结束后,宿主向正在运行的 Sidecar 发送 `channel/<通道>/closed` 通知,插件据此取消该连接的调用并释放按住的输入。官方 MCP 插件实现工具、虚拟机状态与桌面控制,以及通过 SSH/SFTP 的客体命令和文件传输。
Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 VM 目录。读取 VM 状态和恢复点列表要求 `vm:read`,截图要求 `vm:screen`,输入要求 `qmp:write`,VM 启停要求 `vm:control`。截图可指定一块区域,区域坐标默认按源分辨率计算,也可附带参考图像尺寸,由宿主换算到源分辨率;宿主在全分辨率帧上裁剪区域后再缩放,超出支持范围的宽度会被收进范围内而不是被拒绝。按键可单独按住和松开,按住时可同时带修饰键,宿主一并按住或抬起;释放接口一次抬起指定的按键和鼠标键;驱动控制台只支持按键单击。关机可指定强制停止。宿主记录每个插件在各台虚拟机上仍按住的键与鼠标键,包括驱动控制台上的鼠标键,在插件进程退出、插件停用、虚拟机停止或两分钟不再调用时替它抬起;按住状态只由输入事件维护,不依赖连接存活,虚拟机未运行时记录直接丢弃,不在开机后补发过期的释放。
Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 VM 目录。读取 VM 状态和恢复点列表要求 `vm:read`,截图要求 `vm:screen`,输入要求 `qmp:write`,VM 启停要求 `vm:control`。截图可指定一块区域,区域坐标默认按源分辨率计算,也可附带参考图像尺寸,由宿主换算到源分辨率;宿主在全分辨率帧上裁剪区域后再缩放,支持 JPEG 与无损 PNG 格式并可按宽度或最长边限制尺寸(`max_edge` 为 `0` 时返回原始分辨率),超出支持范围的宽度会被收进范围内而不是被拒绝。按键可单独按住和松开,按住时可同时带修饰键,宿主一并按住或抬起;释放接口一次抬起指定的按键和鼠标键;驱动控制台只支持按键单击。关机可指定强制停止。宿主记录每个插件在各台虚拟机上仍按住的键与鼠标键,包括驱动控制台上的鼠标键,在插件进程退出、插件停用、虚拟机停止或两分钟不再调用时替它抬起;按住状态只由输入事件维护,不依赖连接存活,虚拟机未运行时记录直接丢弃,不在开机后补发过期的释放。
键入敏感设置对所有持有 `qmp:write` 且用户已按虚拟机授权访问的插件开放,不再只对官方插件开放。宿主只键入该插件自己的设置,不向插件返回明文,审计日志只记录设置名与长度。恢复点还原对已授权访问的虚拟机开放;删除虚拟机仍只限插件自己创建的临时虚拟机,克隆名称由插件自定,宿主以自己写入的归属标记识别临时虚拟机。Host API 审核插件权限并记录方法名,不把输入文本写入审计日志。开机、登录和切换显示时画面可能是纯色,此时截图照常返回该帧并标记 `blank`,插件据此继续等待,而不是当作失败。登录密码由 Windows DPAPI 保护。插件自己的下载器敏感设置仅在下载请求中解密并传给该插件进程。
虚拟机处于 `installer` 或 `recovery` 阶段时,外部插件的截图与键鼠输入操作均须先经主窗口弹窗获得用户确认。授权仅驻留内存,默认有效期 30 分钟,可选 10 分钟、60 分钟或直到离开当前阶段,离开阶段、关机或点停止后立即撤销。外部插件操作虚拟机期间,宿主在侧栏、详情页、系统托盘和虚拟机窗口浮层显示受控状态与暂停/停止入口;普通接管模式下,用户在虚拟机窗口按下键盘、点击、滚轮或移动鼠标超过 24 像素即自动暂停外部输入,锁定模式下由宿主拦截对虚拟机客户区的误触键鼠输入(保留 `Alt+Tab`、`Alt+Esc` 与 `Win` 等系统逃生快捷键)并在点击浮层或主窗口「暂停」后立即解锁。
## 生命周期、参数账本与资源预算
每个启用中的插件拥有独立的作用域,注册的服务、事件订阅、界面槽位、后台监听与系统钩子均绑定释放函数;插件停用、卸载或激活失败时按逆序完整拆除。服务依赖变更时先停用失去依赖的插件,再按依赖拓扑激活就绪插件。
@@ -80,7 +84,7 @@ Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 V
每个公开的稳定契约项在发布时均具备宿主实现与契约测试;尚未实现的预留项在契约文件中标记为 `experimental`,清单校验予以放行但 `reims-go plugin doctor` 会给出实验性提示,正式版市场插件不得依赖实验项。主版本内只做向后兼容的可选扩展,插件在握手阶段根据宿主下发的 `features` 特性列表按需降级,未知清单字段忽略并提示。宿主接口目录中的每个方法同样以特性名宣告,测试保证目录中的稳定方法都有实现、宿主实现的方法都在目录内。
当前插件契约为 `pluginApi 1.3.0`,界面契约为 `uiApi 2.1.0`。客体驱动在清单中以 `runtimeKind` 为 `external` 声明自带运行环境,并可用 `consoleEndpoint`、`pasteCombo`、`keymap` 声明控制台接入方式、客体粘贴组合键与键位映射。`driver.console`、`host.secret.materialize`、`host.download` 与 `host.elevate.request` 均已进入稳定契约,并在 Sidecar 握手特性列表中宣告。声明 `pluginApi` 1.3 或更高范围的插件,其虚拟机与控制台方法的请求中未定义的字段会以 JSON-RPC `-32602` 拒绝;更早的插件继续忽略未知字段,以便已发布插件在宿主补齐字段前照常工作。
当前插件契约为 `pluginApi 1.3.0`,界面契约为 `uiApi 2.2.0`。客体驱动在清单中以 `runtimeKind` 为 `external` 声明自带运行环境,并可用 `consoleEndpoint`、`pasteCombo`、`keymap` 声明控制台接入方式、客体粘贴组合键与键位映射。`contributes.autoInstallers` 允许插件按客体家族声明自动装机提供方,供新建向导、虚拟机详情页与 `vm autoinstall` 子命令通用发现,宿主核心不硬编码具体插件标识。`driver.console`、`host.secret.materialize`、`host.download`、`host.download.timeouts`、`host.download.custom_mirror`、`host.elevate.request`、`host.ui.confirm`、`host.session`、`host.console.screenshot.region`、`host.vm.finishInstall`、`host.vm.restart`、`host.vm.telemetry` 与 `vm.phaseChanged` 均已进入稳定契约,并在 Sidecar 握手特性列表中宣告。声明 `pluginApi` 1.3 或更高范围的插件,其宿主接口请求中未定义的字段会以 JSON-RPC `-32602` 拒绝;更早的插件继续忽略未知字段,以便已发布插件在宿主补齐字段前照常工作。界面契约新增列表项与虚拟机页的 `data-remote-control` 受控状态属性及 `remote-control` 主题图标。
## 客体驱动的 Sidecar 协议
@@ -92,7 +96,9 @@ Sidecar 可通过宿主接口请求为指定虚拟机拉起进程,宿主以「
客体驱动可通过 `host/secret.materialize` 委托宿主把受 Windows DPAPI 保护的敏感设置按模板(支持原样、XML 转义与 Base64 UTF-16LE)写入虚拟机目录内的新文件,文件权限沿用该目录。插件本身不接触明文,审计日志只记录设置名与字节长度;宿主持久化记录已物化路径,在插件调用 `host/secret.discard` 或用户删除虚拟机时先覆写清零再删除文件。
插件可通过 `host/download.start` 与 `host/download.cancel` 委托宿主执行受 `net:<origin>` 权限约束的后台下载。宿主只放行已声明来源的 HTTPS 地址(测试用回环地址除外),要求提供并校验 SHA-256,检查重定向安全,禁止 HTTPS 降级为明文 HTTP 以及指向本机或私网地址的重定向,并限制落盘目录位于插件私有数据目录或该驱动声明的虚拟机根目录内。下载进度同步到桌面任务栏与 Sidecar 的 `download/progress` 通知;存在进行中的下载时,关闭主窗口会先弹出确认提示。
插件可通过 `host/download.start` 与 `host/download.cancel` 委托宿主执行受 `net:<origin>` 权限约束的后台下载。宿主只放行已声明来源的 HTTPS 地址(测试用回环地址除外),要求提供并校验 SHA-256,检查重定向安全,禁止 HTTPS 降级为明文 HTTP 以及指向本机或私网地址的重定向,并限制落盘目录位于插件私有数据目录或该驱动声明的虚拟机根目录内。调用方可为下载指定连接超时与卡死无进展超时;请求用户自定义镜像来源时必须提供固定 SHA-256 校验值,并经主窗口弹窗由用户确认来源后才放行。下载进度同步到桌面任务栏与 Sidecar 的 `download/progress` 通知;存在进行中的下载时,关闭主窗口会先弹出确认提示。
插件可通过 `host/vm.finishInstall`、`host/vm.restart` 与 `host/vm.telemetry` 分别完成移除安装介质、带重启计数触发重启以及读取虚拟机磁盘大小、串口启动里程碑(含离线首启预配置就绪信号)、最近日志与运行时状态摘要。宿主在虚拟机阶段变化时向运行中的 Sidecar 推送 `vm/phaseChanged` 通知,插件也可经 `host/ui.confirm` 发起受宿主渲染的确认弹窗。
客体驱动可通过 `host/elevate.request` 请求白名单内的 Windows 系统功能配置,当前仅支持启用 Hyper-V、将当前账户加入 Hyper-V Administrators 组与启用 Windows Sandbox。宿主先唤起主窗口并展示默认聚焦取消按钮的确认对话框,明确告知请求插件来源、操作内容、权限范围以及后续需要手动重启或重新登录,确认后才通过 Windows UAC 直接运行对应的系统工具。提权操作在无桌面窗口时直接拒绝,且绝不自动重启系统。
+1
View File
@@ -14,6 +14,7 @@
| QEMU 虚拟化层 | WHPX / TCG、客体机器与设备模型、`reims-graphics-pci` 的 PCI 设备侧、QMP 命令实现、`qcow2` 格式与迁移机制 | [`steelbrain/qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu)。核对构建提交中的 `vendor/qemu` gitlink 及其来源。 |
| 独立上游工具 | `reims-util` 内的引导资源生成、安装镜像处理和工具自身的参数语义 | [`steelbrain/reims-util`](https://github.com/steelbrain/reims-util)。按运行时锁定的提交定位。 |
| 独立图形依赖 | Metal 到 Vulkan 的命令、资源和着色器转换实现 | [`steelbrain/metal2vulkan`](https://github.com/steelbrain/metal2vulkan)。按运行时锁定的提交定位。 |
| Apple 芯片 Mac 原生运行器 | 虚拟机设备、安装事务、实例锁、查看器和关机协议 | 独立 `nivfold` 仓库。客户端的驱动注册、命令适配与任务界面仍归 `Reims-Go`。 |
| 其他独立引擎 | 引擎自身的执行、翻译和固件实现 | 对应引擎的源代码仓库。客户端的驱动注册、启动参数适配和状态展示仍归 `Reims-Go`。 |
| 运行时集成与分发 | 上游版本选取、依赖补丁、运行时编译、打包、能力清单及 Preview 发布 | [`reims-go/reims-vgpu`](https://github.com/reims-go/reims-vgpu) 的运行时流水线。构建及发布规则见[便携运行时与跨仓边界](architecture.md#便携运行时与跨仓边界)。 |
+3 -1
View File
@@ -12,6 +12,8 @@
| 跨模块改动或提 PR | `node scripts/test.mjs ci` | 前端测试和类型检查、`internal/`、`pkg/`、`scripts/` 下的 Go 测试与 vet、调试工具自测、GitHub 自动化脚本自测 |
| 核对发布候选 | `node scripts/test.mjs release` | 使用 `desktop,production` 构建标签运行同一套 Go 检查,禁用测试结果缓存并随机化用例顺序 |
| Windows 桌面冒烟 | `node scripts/test.mjs webview2 build/bin/reims-go.exe` | 启动已构建的客户端,在真实 WebView2 中完成首启数据目录设置 |
| Apple 芯片 Mac 构建 | `node scripts/build-macos.mjs` | 独立构建桌面端。`--runtime` 可接入已构建并签名的 Nivfold |
| Mac 客户端运行时契约检查 | `node scripts/test.mjs applevz .debug/runs/macos-client/nivfold` | 无系统镜像地检查 Nivfold 签名、协议、宿主能力和空实例状态。运行器内部套接字和安装取消测试在 Nivfold 仓库执行 |
GitHub CI 额外检查变更日志、工作区纪律、前端生产打包、Windows GUI 可执行文件的 `version` 输出与 WebView2 首启。滚动开发版检查推送到 `main` 的最新提交消息的第一行,包含 `#` 且不包含 `docs`(忽略大小写)时才复用该提交的 CI 测试自动构建。自动构建跳过有多个父提交的合并提交及纯文档推送。手动构建会跑 CI 测试并冒烟。带版本标签的发布与每日 Alpha 先跑发布候选测试,再对待发布的 EXE 运行桌面冒烟。两个发布流程都在上传前验证实际 EXE 的版本、ZIP 内的文件和 SHA-256 校验和。
@@ -28,4 +30,4 @@ Go 包并发默认为可用 CPU 数与 4 的较小值,每个包的运行上限
- 前端测试直接加载生产模块验证任务排序和过期事件。涉及界面交互时优先覆盖用户可观察的状态切换,不按源码行或正则截取组件源码执行。
- Go 单包测试验证领域规则,跨层测试保留桌面桥接、控制套接字、本地 HTTP、子进程与数据迁移等真实接口用例。异步用例通过完成信号控制时序,超时只用于报告卡死。
- 存储层测试使用真实临时目录验证配置、目录锁、版本升级、插件状态备份与损坏恢复。
- 依赖真实便携运行时、磁盘工具、引导镜像与安装包的集成用例仅在传入对应的 `REIMS_GO_TEST_*` 环境变量时运行,常规档位自动跳过。改动涉及虚拟机运行或磁盘操作时须在 Windows 宿主机实测验证。
- 依赖真实便携运行时、磁盘工具、引导镜像与安装包的集成用例仅在传入对应的 `REIMS_GO_TEST_*` 环境变量时运行,常规档位自动跳过。改动涉及虚拟机运行或磁盘操作时须在对应宿主实测。Mac 原生后端的完整冒烟需使用数据目录外的本地 Apple `.ipsw`,验证安装、首次启动、重新显示窗口和正常关机。执行客体图形安装向导前必须确认。
@@ -0,0 +1,78 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { loadTestModule } from './load-test-module.mjs'
const { buildNativeMenu, resolveMenuClick, buildTitleMenus, runMenuCommand, vmFeatures } = await loadTestModule(`
import './i18n/domains/core.gen'
import './i18n/domains/vm.gen'
export * from './macos/applicationMenuModel'
export * from './lib/titleMenu'
export { vmFeatures } from './lib/endpoints'
`)
const props = { locale: 'en-US', sidebarOpen: true, logsOpen: false, themeMode: 'system', canLight: true, canDark: true, vm: null }
const state = { workspaceReady: true, dialogOpen: false, vmSettingsReady: false }
const vm = { name: 'test', state: 'stopped', busy: false, canSuspend: false, features: vmFeatures() }
const find = (model, command) => model.groups.flatMap((group) => group.rows).find((row) => row.command === command)
test('the native bar localizes three menus and reflects view state and Command shortcuts', () => {
const { groups } = buildNativeMenu({ ...props, locale: 'zh-CN' }, state)
assert.deepEqual(groups.map(({ label }) => label), ['虚拟机', '视图', '帮助'])
const menu = buildNativeMenu({ ...props, canDark: false, themeMode: 'light', logsOpen: true, vm }, state)
assert.deepEqual(menu.groups.map(({ label }) => label), ['VM', 'View', 'Help'])
assert.equal(find(menu, 'sidebar').checked, true)
assert.equal(find(menu, 'logs').checked, true)
assert.equal(find(menu, 'theme:light').checked, true)
assert.equal(find(menu, 'theme:dark'), undefined)
assert.equal(find(menu, 'theme:system'), undefined)
assert.deepEqual(['new', 'sidebar', 'logs', 'settings', 'vm:start'].map((command) => find(menu, command).key), ['n', 'b', 'l', ',', '\r'])
assert.equal(buildTitleMenus(props).vm.rows[0].shortcut, 'Ctrl+N')
})
test('standard macOS menus use the same locale as the app-defined menus', () => {
const { standard: zh } = buildNativeMenu({ ...props, locale: 'zh-CN' }, state)
const { standard: en } = buildNativeMenu(props, state)
assert.deepEqual([zh.edit, zh.window, zh['hide:'], zh.Quit], ['编辑', '窗口', '隐藏 Reims-Go', '退出 Reims-Go'])
assert.deepEqual([en.edit, en.window, en['hide:'], en.Quit], ['Edit', 'Window', 'Hide Reims-Go', 'Quit Reims-Go'])
assert.deepEqual([zh['undo:'], zh['redo:'], zh['pasteAsRichText:'], zh['startSpeaking:']], ['撤销', '重做', '粘贴并匹配样式', '开始朗读'])
for (const key of Object.keys(en)) assert.notEqual(zh[key], en[key], key)
})
test('VM menu validates the current VM state and ignores stale targets', () => {
const selected = { ...state, selectedVMKey: 'driver:test', vmSettingsReady: true }
let menu = buildNativeMenu({ ...props, vm }, selected)
const click = (command, scope = selected.selectedVMKey) => resolveMenuClick({ command, scope }, menu.scope, menu.commands)
assert.equal(click('vm:start'), 'vm:start')
assert.equal(click('vm:start', 'another-driver:test'), undefined)
assert.equal(click('vmSettings'), 'vmSettings')
assert.equal(click('vm:stop'), undefined)
menu = buildNativeMenu({ ...props, vm: { ...vm, state: 'running' } }, selected)
assert.equal(click('vm:start'), undefined)
assert.equal(click('vm:focus'), 'vm:focus')
assert.equal(click('vm:stop'), 'vm:stop')
assert.equal(click('vm:delete'), undefined)
menu = buildNativeMenu({ ...props, vm: { ...vm, state: 'suspended' } }, selected)
assert.equal(click('vm:resume'), undefined)
assert.equal(click('vmSettings'), undefined)
assert.equal(click('vm:discardSuspend'), 'vm:discardSuspend')
})
test('setup only exposes external help, and modal dialogs block native menu commands', () => {
const setup = buildNativeMenu(props, { ...state, workspaceReady: false })
assert.deepEqual([...setup.commands], ['website', 'docs', 'project', 'report'])
assert.equal(buildNativeMenu(props, { ...state, dialogOpen: true }).commands.size, 0)
})
test('native menu commands reuse the renderer actions and URL localization', () => {
const calls = []
const actions = { ...props, locale: 'zh-CN',
onVMAction: (action) => calls.push(action),
onVMDelete: () => calls.push('confirm delete'),
onNavigate: (page) => calls.push(page),
onThemeMode: (mode) => calls.push(mode),
onOpenURL: (url) => calls.push(url),
}
for (const id of ['vm:stop', 'vm:delete', 'settings', 'update', 'theme:dark', 'docs']) runMenuCommand(actions, id)
assert.deepEqual(calls, ['stop', 'confirm delete', 'settings', 'about', 'dark', 'https://reims.dev/docs/quick-start'])
})
+33
View File
@@ -0,0 +1,33 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { loadTestModule } from './load-test-module.mjs'
const { defaultAutoInstallDraft, validateAutoInstallDraft } = await loadTestModule(
`export * from './lib/autoInstallDraft'`
)
test('recovery_only auto-install requires explicit Apple SLA confirmation', () => {
const draft = defaultAutoInstallDraft()
assert.equal(draft.enabled, false)
assert.equal(draft.autoInstall, true)
assert.equal(draft.slaAccepted, false)
// Without explicit SLA confirmation, starting recovery_only auto-install must be blocked.
assert.equal(validateAutoInstallDraft(draft, true), false)
// Once user explicitly confirms Apple SLA, recovery_only is valid without account credentials.
assert.equal(validateAutoInstallDraft({ ...draft, slaAccepted: true }, true), true)
})
test('full mode auto-install requires SLA confirmation and valid ASCII credentials', () => {
const base = {
...defaultAutoInstallDraft(),
enabled: true,
fullName: 'Reims User',
accountName: 'reims',
password: 'Password123',
slaAccepted: false,
}
assert.equal(validateAutoInstallDraft(base, true), false)
assert.equal(validateAutoInstallDraft({ ...base, slaAccepted: true }, true), true)
assert.equal(validateAutoInstallDraft({ ...base, slaAccepted: true, password: '123' }, true), false)
assert.equal(validateAutoInstallDraft({ ...base, slaAccepted: true, fullName: '中文' }, true), false)
})
+15 -1
View File
@@ -103,7 +103,7 @@ test('macOS VMs keep every action; other VMs follow their capabilities', () => {
assert.equal(withAffinity.screenshot, false)
})
test('hosted VMs never offer window, fullscreen, affinity, screenshot or typing', () => {
test('hosted VMs without a window or console do not offer process or display controls', () => {
const hosted = lib.vmFeatures({
driver_id: 'acme.wsl',
capabilities: ['hosted', 'affinity', 'qmp', 'snapshot'],
@@ -117,6 +117,20 @@ test('hosted VMs never offer window, fullscreen, affinity, screenshot or typing'
assert.equal(hosted.snapshot, true)
})
test('a hosted native window takes priority over ready endpoints', () => {
const windowed = lib.vmFeatures({ driver_id: 'example.native', capabilities: ['hosted', 'window', 'affinity'] })
const ssh = ep('ssh')
assert.equal(windowed.window, true)
assert.equal(windowed.fullscreen, false)
assert.equal(windowed.affinity, false)
assert.deepEqual(lib.primaryVMAccess(windowed, [ssh]), { kind: 'window' })
assert.deepEqual(lib.primaryVMAccess(windowed, []), { kind: 'window' })
const endpointOnly = lib.vmFeatures({ driver_id: 'example.wsl', capabilities: ['hosted'] })
assert.deepEqual(lib.primaryVMAccess(endpointOnly, [ssh]), { kind: 'endpoint', endpoint: ssh })
assert.equal(lib.primaryVMAccess(endpointOnly, [ep('ssh', false)]), undefined)
})
test('a hosted VM offers screenshots and typing only when its driver serves a console', () => {
const withConsole = lib.vmFeatures({ driver_id: 'acme.wsl', capabilities: ['hosted', 'console'] })
assert.equal(withConsole.screenshot, true)
+54
View File
@@ -0,0 +1,54 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { loadTestModule } from './load-test-module.mjs'
const { defaultGuestDriver, eligibleGuestDrivers, hasRestoreImagePicker, needsRuntimeSetup, restoreImageField } = await loadTestModule(`export * from './lib/guestDrivers'`)
const mac = { os: 'darwin', arch: 'arm64' }
const win = { os: 'windows', arch: 'amd64' }
const restore = { type: 'string', 'x-filePattern': '*.ipsw' }
const create_schema = { properties: { restore_path: restore } }
const native = { id: 'example.native', runtime_kind: 'external', builtin: true, create_schema }
const thirdParty = { id: 'example.additional', runtime_kind: 'external', create_schema }
const legacy = { id: 'builtin.driver.reims-macos', runtime_kind: 'reims-vgpu', builtin: true }
test('Apple Silicon skips portable runtime setup, but Windows still offers it when missing', () => {
assert.equal(needsRuntimeSetup(mac, false), false)
assert.equal(needsRuntimeSetup(win, false), true)
assert.equal(needsRuntimeSetup(win, true), false)
assert.equal(needsRuntimeSetup({ os: 'darwin', arch: 'amd64' }, false), true)
})
test('a host-provided external driver can create without a portable runtime', () => {
const eligible = eligibleGuestDrivers([legacy, native, thirdParty], false)
assert.deepEqual(eligible, [native, thirdParty])
assert.equal(defaultGuestDriver(eligible, mac), native)
assert.equal(defaultGuestDriver([thirdParty, native], mac), thirdParty)
assert.equal(defaultGuestDriver(eligible, mac, 'offline'), undefined)
assert.equal(defaultGuestDriver([thirdParty, legacy], win), legacy)
assert.equal(defaultGuestDriver([thirdParty, legacy], win, 'online'), legacy)
assert.deepEqual(eligibleGuestDrivers([legacy, native], true), [legacy, native])
})
test('Windows exposes only the managed drivers with their matching runtime', () => {
const arm = { id: 'builtin.driver.stambha', runtime_kind: 'stambha-hosted', builtin: true }
const drivers = [legacy, arm]
assert.deepEqual(eligibleGuestDrivers(drivers, false, true), [arm])
assert.equal(defaultGuestDriver([arm], win), arm)
assert.deepEqual(eligibleGuestDrivers(drivers, true, false), [legacy])
assert.deepEqual(eligibleGuestDrivers(drivers, true, true), drivers)
})
test('cached IPSW routes only to the trusted native restore driver', () => {
assert.equal(defaultGuestDriver([thirdParty, legacy, native], mac, 'ipsw'), native)
assert.equal(defaultGuestDriver([thirdParty, legacy], mac, 'ipsw'), undefined)
assert.equal(defaultGuestDriver([legacy, native], win, 'ipsw'), undefined)
assert.equal(restoreImageField(native, mac), 'restore_path')
})
test('only a host-trusted create schema can add the IPSW picker', () => {
assert.equal(hasRestoreImagePicker(native, restore), true)
assert.equal(hasRestoreImagePicker(thirdParty, restore), false)
assert.equal(hasRestoreImagePicker(native, { ...restore, 'x-filePattern': '*.ipsw;*' }), false)
assert.equal(hasRestoreImagePicker(native, { ...restore, type: 'integer' }), false)
})
+73 -1
View File
@@ -2,7 +2,16 @@ import assert from 'node:assert/strict'
import test from 'node:test'
import { loadTestModule } from './load-test-module.mjs'
const { createLogLine } = await loadTestModule(`export * from './lib/logs'`)
const {
LARGE_LOG_CHAR_THRESHOLD,
LARGE_LOG_LINE_THRESHOLD,
countLogLines,
createLogLine,
formatLogLine,
formatLogLines,
formatSelectedLogRows,
isLargeLogPayload,
} = await loadTestModule(`export * from './lib/logs'`)
const renderSelector = 'newRenderPipelineStateWithDescriptor:error:'
const computeSelector = 'newComputePipelineStateWithDescriptor:options:reflection:error:'
@@ -29,3 +38,66 @@ test('pipeline refusals and fatal errors retain their error level', () => {
assert.equal(createLogLine({ line }).level, 'error')
}
})
test('formatLogLine and formatLogLines emit single-line entries', () => {
const row = createLogLine({ ts: '12:34:56', source: 'qemu', line: 'booting kernel' })
assert.equal(formatLogLine(row), '12:34:56 [qemu] booting kernel')
assert.equal(
formatLogLines([
row,
createLogLine({ ts: '12:34:57', source: 'app', line: 'guest ready' }),
]),
'12:34:56 [qemu] booting kernel\n12:34:57 [app] guest ready',
)
})
test('countLogLines handles empty strings, CRLF, and trailing newlines', () => {
assert.equal(countLogLines(''), 0)
assert.equal(countLogLines('\n'), 0)
assert.equal(countLogLines('one line'), 1)
assert.equal(countLogLines('a\nb\n'), 2)
assert.equal(countLogLines('a\r\nb\r\nc'), 3)
})
test('isLargeLogPayload enforces line and character thresholds', () => {
assert.equal(LARGE_LOG_LINE_THRESHOLD, 20)
assert.equal(LARGE_LOG_CHAR_THRESHOLD, 2000)
const nineteenLines = Array.from({ length: 19 }, (_, i) => `line ${i + 1}`).join('\n')
const twentyLines = Array.from({ length: 20 }, (_, i) => `line ${i + 1}`).join('\n')
assert.equal(isLargeLogPayload(''), false)
assert.equal(isLargeLogPayload(nineteenLines), false)
assert.equal(isLargeLogPayload(`${nineteenLines}\n`), false)
assert.equal(isLargeLogPayload(twentyLines), true)
assert.equal(isLargeLogPayload('x'.repeat(1999)), false)
assert.equal(isLargeLogPayload('x'.repeat(2000)), true)
})
test('formatSelectedLogRows normalizes multi-row DOM selections into single lines', () => {
const normalized = formatSelectedLogRows([
{ ts: ' 09:00:01 ', source: ' host ', line: ' indented message' },
{ ts: '09:00:02', source: 'qemu', line: 'vgpu ready' },
])
assert.equal(
normalized,
'09:00:01 [host] indented message\n09:00:02 [qemu] vgpu ready',
)
})
test('formatSelectedLogRows flattens embedded LF, CRLF, and CR breaks within a log row', () => {
const normalized = formatSelectedLogRows([
{ ts: '00:00:00', source: 'app', line: 'first\ncontinued\n\ntrailing\n' },
{ ts: '00:00:01', source: 'qemu', line: 'win\r\nsecond line\r\n' },
{ ts: '00:00:02', source: 'host', line: '\rcr\rjoined' },
])
assert.equal(
normalized,
'00:00:00 [app] first continued trailing\n00:00:01 [qemu] win second line\n00:00:02 [host] cr joined',
)
assert.equal(countLogLines(normalized), 3)
assert.equal(
formatLogLine({ ts: '00:00:03', source: 'app', line: 'alpha\r\nbeta\ngamma' }),
'00:00:03 [app] alpha beta gamma',
)
})
+36
View File
@@ -0,0 +1,36 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { loadTestModule } from './load-test-module.mjs'
const { cachedRestoreImage, matchesRestoreImage, restoreImageChoiceKey, restoreImageChoices, restoreImagePathMissing } = await loadTestModule(`export * from './lib/restoreImages'`)
const latest = { version: '26.6.2', build: '25G83', title: 'macOS Tahoe' }
const olderBuild = { kind: 'ipsw', version: latest.version, build: '25G82', title: 'macOS Tahoe', path: '/saved/old.ipsw' }
const partial = { ...olderBuild, build: latest.build, path: '/saved/new.ipsw.part', partial: true }
const otherKind = { ...olderBuild, build: latest.build, kind: 'offline' }
test('a previous IPSW build stays selectable without masking the latest one', () => {
const cache = [olderBuild, partial, otherKind]
assert.deepEqual(restoreImageChoices(latest, cache).map((choice) => choice.key), [
restoreImageChoiceKey(latest.version, latest.build), restoreImageChoiceKey(olderBuild.version, olderBuild.build),
])
assert.equal(cachedRestoreImage(cache, latest.version, latest.build), undefined)
assert.equal(cachedRestoreImage(cache, olderBuild.version, olderBuild.build), olderBuild)
assert.equal(matchesRestoreImage(olderBuild, latest.version, latest.build), false)
assert.equal(matchesRestoreImage(partial, latest.version, latest.build), true)
})
test('a downloaded latest build is not repeated and is used by its exact matching row', () => {
const complete = { ...partial, partial: false, path: '/saved/new.ipsw' }
const cache = [otherKind, olderBuild, partial, complete]
assert.equal(restoreImageChoices(latest, cache).length, 2)
assert.equal(cachedRestoreImage(cache, latest.version, latest.build), complete)
assert.equal(restoreImageChoices(undefined, [otherKind, olderBuild, partial]).length, 1)
})
test('a completed IPSW missing a cache path is distinct from an absent or partial download', () => {
const missing = { ...partial, partial: false, path: '' }
assert.equal(restoreImagePathMissing([missing], latest.version, latest.build), true)
assert.equal(restoreImagePathMissing([olderBuild, otherKind, { ...partial, path: '' }], latest.version, latest.build), false)
assert.equal(restoreImagePathMissing([missing], latest.version, olderBuild.build), false)
})
+31 -2
View File
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict'
import test from 'node:test'
import { loadTestModule } from './load-test-module.mjs'
const { creatingVMTasks, currentTask, findActiveOfflineTask, pruneFinishedTasks, taskDetail, upsertTask } =
const { creatingVMTasks, currentTask, findActiveCachedTask, findActiveInstallerTask, findRunningRestoreTask, groupUnmatchedInstallerTasks, pruneFinishedTasks, taskDetail, taskStopAction, taskTitle, upsertTask } =
await loadTestModule(`export * from './lib/tasks'`)
const task = (id, overrides = {}) => ({
@@ -29,11 +29,23 @@ test('one installer download represents the VM creations waiting for it', () =>
const download = task('download', { kind: 'installer-download', started_at: 15 })
const vm = task('vm', { vm: 'vm one' })
const other = task('other', { installer_version: '15.8.3' })
assert.deepEqual(findActiveOfflineTask([vm, other, download], '26.7.3'), {
assert.deepEqual(findActiveInstallerTask([vm, other, download], 'offline', '26.7.3'), {
primary: download, waitingVMs: ['vm one'], matchedIDs: ['download', 'vm'],
})
})
test('native and Windows installers of the same version keep separate download state', () => {
const win = task('win', { kind: 'installer-download' })
const mac = task('mac', { kind: 'installer-download', installer_kind: 'ipsw' })
const other = task('other', { kind: 'installer-download', installer_kind: 'ipsw', installer_version: '27.0' })
const tasks = [win, mac, other]
assert.equal(findActiveInstallerTask(tasks, 'ipsw', '26.7.3')?.primary, mac)
assert.equal(findActiveInstallerTask(tasks, 'offline', '26.7.3')?.primary, win)
assert.equal(findActiveCachedTask(tasks, { kind: 'ipsw', version: '26.7.3', partial: true })?.primary, mac)
assert.deepEqual(groupUnmatchedInstallerTasks(tasks, new Set()).map((match) => match.primary.id), ['win', 'mac', 'other'])
assert.deepEqual(taskStopAction('en-US', mac), { kind: 'pause', label: 'Pause download' })
})
test('taskDetail formats download speeds under 1 MB/s in KB/s', () => {
assert.equal(taskDetail(task('slow', { done: 5e6, total: 50e6, rate: 512e3 })), '5 MB / 50 MB · 512 KB/s')
assert.equal(taskDetail(task('tiny', { done: 1e6, total: 10e6, rate: 200 })), '1 MB / 10 MB · 1 KB/s')
@@ -41,6 +53,23 @@ test('taskDetail formats download speeds under 1 MB/s in KB/s', () => {
assert.equal(taskDetail(task('gig', { done: 2e9, total: 10e9, rate: 1.2e9 })), '2.0 GB / 10.0 GB · 1.2 GB/s')
})
test('guest restore is labeled as installing and can be canceled, not paused', () => {
const restore = task('macOS', { kind: 'vm-restore', installer_kind: '', installer_phase: '' })
assert.equal(taskTitle('en-US', restore), 'Installing macOS on macOS')
assert.deepEqual(taskStopAction('en-US', restore), { kind: 'cancel', label: 'Cancel creation' })
})
test('restore progress and cancel target the matching driver and case-preserved VM name', () => {
const running = task('native', { kind: 'vm-restore', vm: 'builtin.driver.apple-vz:Test VM' })
const otherDriver = { ...running, id: 'other', vm: 'example.driver:Test VM' }
const finished = { ...running, id: 'finished', status: 'done' }
const tasks = [otherDriver, finished, running]
assert.equal(findRunningRestoreTask(tasks, 'builtin.driver.apple-vz', ' Test VM '), running)
assert.equal(findRunningRestoreTask(tasks, 'example.driver', 'Test VM'), otherDriver)
assert.equal(findRunningRestoreTask(tasks, 'builtin.driver.apple-vz', 'test vm'), undefined)
assert.equal(findRunningRestoreTask(tasks, '', 'Test VM'), undefined)
})
test('creatingVMTasks lists only running vm-create tasks not yet present in vms, oldest first', () => {
const first = task('t1', { subject: 'macos-a', started_at: 10 })
const second = task('t2', { subject: 'macos-b', started_at: 20 })
+265 -77
View File
@@ -2,9 +2,12 @@ import { Minus, Moon, Square, Sun, X } from 'lucide-react'
import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react'
import type { WizardDraft } from './components/CreateWizard'
import { AppDialogs } from './components/AppDialogs'
import { DiagnosticsExportDialog } from './components/DiagnosticsExportDialog'
import { OnlineRecoveryDialog } from './macos/OnlineRecoveryDialog'
import { LogPanel, LogTab } from './components/LogPanel'
import { TitleMenus } from './components/TitleMenus'
import { SidebarToggle, TitleMenus } from './components/TitleMenus'
import { ApplicationMenu } from './macos/ApplicationMenu'
import type { TitleMenuProps } from './lib/titleMenu'
import { UpdateCapsule } from './components/UpdateCapsule'
import { DataRootReadOnly } from './components/DataRootReadOnly'
import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar'
@@ -13,7 +16,8 @@ import { VMPage } from './components/VMPage'
import { buildFallbackChain, I18nKey, localeDir, locText, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
import { defaultGuestLang, recommendedMemoryGB } from './lib/format'
import { initialWizardResolution } from './lib/displayResolution'
import { hasStambhaRuntime, isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints'
import { hasStambhaRuntime, isMacOSDriver, liveVMInfo, primaryVMAccess, vmFeatures } from './lib/endpoints'
import { defaultGuestDriver, eligibleGuestDrivers, isAppleSilicon, needsRuntimeSetup } from './lib/guestDrivers'
import { resolveFullscreenHotkey } from './lib/fullscreenHotkey'
import { LogLine, appendLog, createLogLine } from './lib/logs'
import { macOSMajor } from './macos/macosRelease'
@@ -31,11 +35,11 @@ import { vmRefKey } from './lib/vmRef'
import { closePluginDialog, closePluginView, emptyPluginViewState, matchViewCondition, openPluginView, pluginViewKey, prunePluginViews, type PluginViewRoute, type PluginViewState } from './lib/pluginViewRouter'
import { publishPluginHostEvent } from './lib/pluginViewEvents'
import { buildSafePluginAssetURL } from './lib/pluginAssets'
import { ActiveThemePayload, AppState, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMAction, VMBusyAction, VMDetail, VMInfo, VMListItem, ViewContribution } from './types'
import { ActiveThemePayload, AppState, AutoInstallerProviderView, AutoInstallStartRequest, CachedInstaller, CreateOpts, DiagnosticsExportResult, DriverSummary, Locale, PluginUIContributions, ProvisionRequest, Task, VMAction, VMBusyAction, VMDetail, VMInfo, VMListItem, ViewContribution } from './types'
import { Tip, TooltipProvider } from './ui/controls'
import { errorToast, Toaster, type ToastInput, useToasts } from './ui/toast'
import { BrandMark, ThemeDecorations, ThemeVisualsProvider } from './ui/themeVisuals'
import { api, DROP_NETWORK_VOLUMES_DENIED, events, WindowMinimise, WindowToggleMaximise, type ElevationPrompt } from './wails'
import { api, DROP_NETWORK_VOLUMES_DENIED, events, WindowMinimise, WindowToggleMaximise, type ConfirmPrompt, type ConfirmResolvedEvent, type ElevationPrompt } from './wails'
// Opened on demand, so each is its own chunk and stays out of the startup
// bundle: first-run setup, and the Engine / Installers / Settings pages.
@@ -48,6 +52,10 @@ const PluginViewHost = lazy(() => import('./components/PluginViewHost').then((m)
const AppSettingsPage = lazy(() => import('./components/AppSettingsPage').then((m) => ({ default: m.AppSettingsPage })))
const AboutPage = lazy(() => import('./components/AboutPage').then((m) => ({ default: m.AboutPage })))
// Detect desktop chrome before GetState resolves, including the loading and setup screens.
const nativeTitlebar = navigator.platform.startsWith('Mac')
const titleMenuPages = { installers: INSTALLERS_ID, plugins: PLUGINS_ID, host: HOST_ID, settings: SETTINGS_ID, about: ABOUT_ID }
const errText = (e: unknown) => parseAppError(e).summary
type HostDropAck = { status: string; error?: string }
@@ -100,12 +108,15 @@ const failKey: Record<VMBusyAction, I18nKey> = {
export const App: React.FC = () => {
const [state, setState] = useState<AppState | null>(null)
const [nativeMenuReady, setNativeMenuReady] = useState(false)
const [selected, setSelectedPage] = useState<string>(HOST_ID)
const [detail, setDetail] = useState<VMDetail | null>(null)
// GetVMInfo for the selected non-macOS VM; macOS VMs use `detail` (GetVMDetail).
const [vmInfoLoaded, setVMInfoLoaded] = useState<VMInfo | null>(null)
const [detailRevision, setDetailRevision] = useState(0)
const [showWizard, setShowWizard] = useState(false)
const [wizardDrivers, setWizardDrivers] = useState<DriverSummary[]>([])
const loadingWizardDrivers = useRef(false)
const [wizardDraft, setWizardDraft] = useState<WizardDraft | null>(null)
const [pendingCreates, setPendingCreates] = useState<string[]>([])
const [showSettings, setShowSettings] = useState(false)
@@ -115,9 +126,17 @@ export const App: React.FC = () => {
const [discardSuspendTarget, setDiscardSuspendTarget] = useState<string | null>(null)
const [closeDownloadsOpen, setCloseDownloadsOpen] = useState(false)
const [elevationQueue, setElevationQueue] = useState<ElevationPrompt[]>([])
const [confirmQueue, setConfirmQueue] = useState<ConfirmPrompt[]>([])
const activeConfirmIDsRef = useRef(new Set<string>())
const [autoInstallers, setAutoInstallers] = useState<AutoInstallerProviderView[]>([])
const [cloneSource, setCloneSource] = useState<{ name: string; driverID: string } | null>(null)
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
const [sendTextTarget, setSendTextTarget] = useState<string | null>(null)
const [diagResult, setDiagResult] = useState<DiagnosticsExportResult | null>(null)
const [diagExporting, setDiagExporting] = useState(false)
const diagExportingRef = useRef(false)
const [diagCopyingFile, setDiagCopyingFile] = useState(false)
const [diagRevealingFile, setDiagRevealingFile] = useState(false)
const vmBusy = useVMBusy()
const [loadError, setLoadError] = useState('')
const [pluginUI, setPluginUI] = useState<PluginUIContributions | null>(null)
@@ -489,7 +508,8 @@ export const App: React.FC = () => {
const fixedModeSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'display-fixed-mode') ?? false
const diskCacheSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'win32-native-aio') ?? false
const stambhaAvailable = hasStambhaRuntime(state?.runtimes)
const hostReady = !!state && state.host.whpx === 'ready' && (!!state.active_runtime || stambhaAvailable)
const nativeHost = isAppleSilicon(state?.host)
const hostReady = !!state && (nativeHost ? !!state.host.apple_virtualization?.ready : state.host.whpx === 'ready' && (!!state.active_runtime || stambhaAvailable))
const canSuspend = state?.can_suspend ?? false
const fullscreenHotkey = state?.config.fullscreen_hotkey_enabled
? resolveFullscreenHotkey(state.config.fullscreen_hotkey)
@@ -596,14 +616,14 @@ export const App: React.FC = () => {
try {
const s = await api.GetState()
setState(s)
setSetupStage(s?.active_runtime || hasStambhaRuntime(s?.runtimes) ? null : 'runtime')
setSetupStage(needsRuntimeSetup(s.host, !!s.active_runtime || hasStambhaRuntime(s.runtimes)) ? 'runtime' : null)
} catch (e) {
console.warn('[app] GetState after setup failed:', e)
fail(tr('failGeneric'), e)
setSetupStage('runtime')
setSetupStage(!nativeHost ? 'runtime' : null)
}
}
const showSetup = !!state && (state.needs_setup || setupStage === 'runtime')
const showSetup = !!state && (state.needs_setup || (!nativeHost && setupStage === 'runtime'))
// The data folder opened read-only (internal/dataroot): nothing in it may be
// changed, so the workspace gives way to a screen that explains why.
const showReadOnly = !!state && !showSetup && !!state.data_root_status?.read_only
@@ -665,8 +685,14 @@ export const App: React.FC = () => {
console.warn('[app] GetPluginUIContributions failed:', e)
if (live) setPluginUI((previous) => previous ?? {} as PluginUIContributions)
})
api.ListAutoInstallers('').then((list) => {
if (live) setAutoInstallers(list ?? [])
}).catch((e) => {
console.warn('[app] ListAutoInstallers failed:', e)
if (live) setAutoInstallers([])
})
return () => { live = false }
}, [themeRevision, state?.safe_mode])
}, [themeRevision, state?.safe_mode, locale])
useEffect(() => {
void applyActiveTheme(
@@ -788,15 +814,6 @@ export const App: React.FC = () => {
}
}
// Hosted VMs have no window: the primary action is their best ready endpoint.
const openEndpoint = (vm: VMListItem, kind: string) => {
api.OpenVMEndpoint(vm.driver_id ?? '', vm.name, kind, '').catch((e) => fail(tr('failEndpointOpen'), e))
}
const openPrimaryEndpoint = (vm: VMListItem) => {
const { primary } = splitEndpoints(vm.endpoints)
if (primary) openEndpoint(vm, primary.kind)
}
// Actions that only the macOS driver implements (name-based or macOS guest features).
const MACOS_ONLY_ACTIONS: readonly VMAction[] = [
'finishInstall', 'enterRecovery', 'attachInstaller', 'attachGuestTools', 'detachGuestTools',
@@ -811,18 +828,16 @@ export const App: React.FC = () => {
const features = vmFeatures(actionVM)
if (!canSuspendVM(actionVM) && (action === 'suspend' || action === 'resume')) return
if (!features.macos && MACOS_ONLY_ACTIONS.includes(action)) return
if (action === 'focus' && !features.window) return
if (action === 'fullscreen' && !features.fullscreen) return
if (action === 'screenshot' && !features.screenshot) return
if ((action === 'type' || action === 'sendText') && !features.sendText) return
if (action === 'focus' && !features.window) {
if (actionVM) openPrimaryEndpoint(actionVM)
return
}
const activeBusy = vmBusy.current(key)
if (
activeBusy
&& action !== 'openFolder'
&& action !== 'openSharedFolder'
&& action !== 'exportDiagnostics'
&& (action !== 'forceStop' || activeBusy === 'forceStop')
) {
return
@@ -853,7 +868,7 @@ export const App: React.FC = () => {
case 'upgradeNVMe':
return runVMAction(key, action, () => api.UpgradeDiskToNVMe(name), tr(isRunning ? 'toastNVMeNextStart' : 'toastNVMeReady'))
case 'exportDiagnostics':
return runVMAction(key, action, async () => { await api.ExportDiagnostics(actionDriverID, name) }, tr('toastDiagExported'))
return void handleExportDiagnostics({ driverID: actionDriverID, name })
case 'cloneVM':
if (!features.clone) return
return setCloneSource({ name, driverID: actionDriverID })
@@ -884,9 +899,7 @@ export const App: React.FC = () => {
onVMActionFor(name, action, st === 'running')
}
// The state's own main action (Start, Resume while suspended, or Show Window while running), shared by
// Ctrl+Enter and a double-click in the sidebar. A running hosted VM has no window; its action is its
// best ready endpoint, and nothing when none is ready.
// Ctrl+Enter and sidebar double-click use the same primary action as the VM page.
const primaryAction = (name: string) => {
const vm = findVM(name)
if (!vm) return
@@ -895,7 +908,13 @@ export const App: React.FC = () => {
const st = state?.transitions[key] ?? vm.state
if (st === 'stopped') onVMActionFor(key, 'start', false)
else if (st === 'suspended') onVMActionFor(key, 'resume', false)
else if (st === 'running') onVMActionFor(key, 'focus', true)
else if (st === 'running') {
const access = primaryVMAccess(vmFeatures(vm), vm.endpoints)
if (access?.kind === 'window') onVMActionFor(key, 'focus', true)
else if (access?.kind === 'endpoint') {
api.OpenVMEndpoint(vm.driver_id ?? '', vm.name, access.endpoint.kind, '').catch((e) => fail(tr('failEndpointOpen'), e))
}
}
}
const confirmDelete = (keepFiles: boolean) => {
@@ -937,26 +956,44 @@ export const App: React.FC = () => {
}, tr('toastCloned', { name: cloneName }))
}
const openWizard = () => {
if (!state?.active_runtime && !stambhaAvailable) {
const loadWizardDrivers = async (kind?: 'offline' | 'online' | 'ipsw') => {
if (!state || loadingWizardDrivers.current) return false
loadingWizardDrivers.current = true
try {
const drivers = eligibleGuestDrivers(await api.ListDrivers() ?? [], !!state.active_runtime, stambhaAvailable)
if (defaultGuestDriver(drivers, state.host, kind)) {
setWizardDrivers(drivers)
return true
}
setSelected(HOST_ID)
toasts.push({ kind: 'error', title: tr('noRuntimeAlert') })
return
toasts.push({ kind: 'error', title: tr(needsRuntimeSetup(state.host, !!state.active_runtime || stambhaAvailable) ? 'noRuntimeAlert' : 'wizardNoDriver') })
return false
} catch (e) {
fail(tr('wizardDriverListFailed'), e)
return false
} finally {
loadingWizardDrivers.current = false
}
}
const openWizard = async () => {
if (!(await loadWizardDrivers())) return
setWizardDraft(null)
setShowWizard(true)
}
const openWizardWithInstaller = (item: CachedInstaller) => {
if (!state?.active_runtime) {
setSelected(HOST_ID)
toasts.push({ kind: 'error', title: tr('noRuntimeAlert') })
return
}
const openWizardWithInstaller = async (item: CachedInstaller) => {
if (!state || item.partial || item.kind === 'other' || !item.path || !(await loadWizardDrivers(item.kind))) return
const existing = new Set((state.vms ?? []).map((v) => v.name.toLowerCase()))
let defaultName = 'macos-tahoe'
const baseName = item.kind === 'ipsw' ? 'macos' : 'macos-tahoe'
let defaultName = baseName
for (let i = 2; existing.has(defaultName.toLowerCase()); i++) {
defaultName = `macos-tahoe-${i}`
defaultName = `${baseName}-${i}`
}
if (item.kind === 'ipsw') {
setWizardDraft({ step: 1, restoreImage: item, name: defaultName })
setShowWizard(true)
return
}
const isOffline = item.kind === 'offline' && !!item.version
const graphics = state.host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga'
@@ -994,17 +1031,53 @@ export const App: React.FC = () => {
// The wizard closes as soon as the create starts; progress shows in the sidebar,
// main view, and status bar. On failure or cancel the toast offers returning to the wizard.
const submitCreate = (payload: CreateOpts, draft: WizardDraft) => {
const submitCreate = (payload: CreateOpts, draft: WizardDraft, autoInstall?: AutoInstallStartRequest, provision?: ProvisionRequest) => {
setShowWizard(false)
setWizardDraft(null)
const name = payload.name
const hasDownload = payload.source_mode === 'offline' || payload.source_mode === 'apple'
const startAfterProvision = !!payload.start
const createPayload = (provision || autoInstall) ? { ...payload, start: false } : payload
setPendingCreates((prev) => (prev.includes(name) ? prev : [...prev, name]))
setSelected(name)
api.CreateVM(payload)
.then(() => {
api.CreateVM(createPayload)
.then(async () => {
toasts.push({ kind: 'ok', title: tr('toastCreated', { name }) })
setSelected(name)
if (provision) {
try {
await api.PrepareVMProvision(name, provision)
} catch (err) {
fail(tr('failProvision'), err)
return refresh()
}
}
if (autoInstall) {
try {
await api.StartAutoInstall({ ...autoInstall, vm_name: name, start_vm_if_stopped: true })
} catch (err) {
fail(tr('autoInstallStart'), err)
if (!/start VM for auto-install/i.test(errText(err))) {
try {
const latest = await api.GetState()
const created = latest?.vms?.find((v) => v.name === name && (!v.driver_id || v.driver_id === 'builtin.driver.reims-macos'))
if (!created || created.state === 'stopped') {
await api.StartVM('builtin.driver.reims-macos', name)
}
} catch (startErr) {
fail(tr('failGeneric'), startErr)
}
}
}
return refresh()
}
if (provision && startAfterProvision) {
try {
await api.StartVM('builtin.driver.reims-macos', name)
} catch (err) {
fail(tr('failGeneric'), err)
}
}
return refresh()
})
.catch((e) => {
@@ -1047,6 +1120,47 @@ export const App: React.FC = () => {
}
}
const handleExportDiagnostics = async (target?: { driverID: string; name: string }) => {
if (showReadOnly || diagExportingRef.current) return
const resolved = target ?? (selectedVM ? { driverID: selectedVM.driver_id ?? '', name: selectedVM.name } : { driverID: '', name: '' })
diagExportingRef.current = true
setDiagExporting(true)
try {
const result = await api.ExportDiagnostics(resolved.driverID, resolved.name)
setDiagResult(result)
} catch (e) {
fail(tr('failExportDiagnostics'), e)
} finally {
diagExportingRef.current = false
setDiagExporting(false)
}
}
const handleCopyDiagnosticsFile = async () => {
if (!diagResult || diagCopyingFile) return
setDiagCopyingFile(true)
try {
await api.CopyDiagnosticsFile(diagResult.path)
toasts.push({ kind: 'ok', title: tr('toastDiagFileCopied') })
} catch (e) {
fail(tr('failCopyDiagnosticsFile'), e)
} finally {
setDiagCopyingFile(false)
}
}
const handleRevealDiagnosticsFile = async () => {
if (!diagResult || diagRevealingFile) return
setDiagRevealingFile(true)
try {
await api.RevealDiagnosticsFile(diagResult.path)
} catch (e) {
fail(tr('failOpenFolder'), e)
} finally {
setDiagRevealingFile(false)
}
}
const setLang = async (l: Locale) => {
await api.SetLocale(l)
refresh()
@@ -1055,7 +1169,7 @@ export const App: React.FC = () => {
// Global shortcuts (see docs/design-guidelines.md). Dialogs own the keyboard while open.
const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {})
const appDialogOpen = showSetup || showReadOnly || showWizard || showSettings || affinityTarget || deleteTarget ||
discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || update.confirming || closeDownloadsOpen || elevationQueue.length > 0
discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || diagResult || update.confirming || closeDownloadsOpen || elevationQueue.length > 0 || confirmQueue.length > 0
shortcutRef.current = (e: KeyboardEvent) => {
if (!e.ctrlKey || e.altKey || e.metaKey) return
if (appDialogOpen) return
@@ -1097,6 +1211,26 @@ export const App: React.FC = () => {
)))
return () => { offRequest(); offResolved() }
}, [])
// #105 protected-phase authorization, host/ui.confirm, and custom mirror confirmation prompts.
const onConfirmResolvedRef = useRef<(ev: ConfirmResolvedEvent | string) => void>(() => {})
onConfirmResolvedRef.current = (ev) => {
const id = typeof ev === 'string' ? ev : ev?.id
const reason = typeof ev === 'string' ? '' : (ev?.reason ?? '')
if (!id) return
const wasPending = activeConfirmIDsRef.current.delete(id)
setConfirmQueue((q) => (q.some((item) => item.id === id) ? q.filter((item) => item.id !== id) : q))
if (wasPending && reason === 'timeout') {
toasts.push({ kind: 'error', title: tr('confirmTimedOut') })
}
}
useEffect(() => {
const offRequest = events.onConfirmRequest((req) => {
activeConfirmIDsRef.current.add(req.id)
setConfirmQueue((q) => (q.some((item) => item.id === req.id) ? q : [...q, req]))
})
const offResolved = events.onConfirmResolved((ev) => onConfirmResolvedRef.current(ev))
return () => { offRequest(); offResolved() }
}, [])
// Files dropped on the window go to the selected VM's shared folder.
const dropping = useFileDrop(!!selectedVM && !!detail && !detail.has_installer && !detail.recovery_mode, (paths) => {
@@ -1110,47 +1244,52 @@ export const App: React.FC = () => {
.catch((e) => fail(tr('failGuestTools'), e))
})
const workspaceReady = !!state && !showSetup && !showReadOnly
const titleMenuProps: TitleMenuProps = {
locale, sidebarOpen, logsOpen, themeMode, canLight, canDark, fullscreenHotkey,
vm: selectedVM ? {
name: selectedVM.name,
driver_id: selectedVM.driver_id,
state: effectiveState,
busy: vmRefKey(selectedVM) in vmBusy.busy,
graphics: detail?.name === selectedVM.name ? detail.graphics : undefined,
canSuspend: canSuspendVM(selectedVM),
features: selectedFeatures,
} : null,
appVersion: state?.app_version,
onToggleSidebar: toggleSidebar,
onToggleLogs: toggleLogs,
onThemeMode: setThemeMode,
onNewVM: openWizard,
onVMAction,
onVMSettings: () => { if (detail && effectiveState !== 'suspended') setShowSettings(true) },
onVMDelete: () => { if (selectedVM) setDeleteTarget(vmRefKey(selectedVM)) },
onNavigate: (page) => setSelected(titleMenuPages[page]),
onOpenURL: (url) => { api.OpenURL(url).catch((e) => fail(tr('failGeneric'), e)) },
}
return (
<ThemeVisualsProvider payload={activeThemePayload}>
<TooltipProvider>
{nativeTitlebar && <ApplicationMenu props={titleMenuProps} onReady={setNativeMenuReady} state={{
workspaceReady,
dialogOpen: workspaceReady && (!!appDialogOpen || pluginViewState.dialogs.length > 0),
selectedVMKey: selectedVM && vmRefKey(selectedVM),
vmSettingsReady: !!detail && detail.name === selectedVM?.name,
}} />}
<div className="app-shell rg-p-shell">
<div className="rg-layer rg-layer-background" data-rg-layer="layer.background" aria-hidden="true" />
<header className="titlebar rg-p-titlebar" onDoubleClick={() => WindowToggleMaximise()}>
{showSetup || showReadOnly || !state ? (
<header className="titlebar rg-p-titlebar" data-native-titlebar={nativeTitlebar || undefined} onDoubleClick={nativeTitlebar ? undefined : WindowToggleMaximise}>
{!workspaceReady ? (
<div className="brand rg-p-brand">
<BrandMark className="brand-mark" />
Reims-Go
</div>
) : (
<TitleMenus
locale={locale}
sidebarOpen={sidebarOpen}
onToggleSidebar={toggleSidebar}
logsOpen={logsOpen}
onToggleLogs={toggleLogs}
themeMode={themeMode}
canLight={canLight}
canDark={canDark}
onThemeMode={setThemeMode}
vm={selectedVM ? {
name: selectedVM.name,
driver_id: selectedVM.driver_id,
state: effectiveState,
busy: vmRefKey(selectedVM) in vmBusy.busy,
graphics: detail?.name === selectedVM.name ? detail.graphics : undefined,
canSuspend: canSuspendVM(selectedVM),
features: selectedFeatures,
} : null}
fullscreenHotkey={fullscreenHotkey}
onNewVM={openWizard}
onVMAction={onVMAction}
onVMSettings={() => { if (detail && effectiveState !== 'suspended') setShowSettings(true) }}
onVMDelete={() => { if (selectedVM) setDeleteTarget(vmRefKey(selectedVM)) }}
onNavigate={setSelected}
onOpenURL={(url) => { api.OpenURL(url).catch((e) => fail(tr('failGeneric'), e)) }}
appVersion={state.app_version}
/>
)}
) : nativeTitlebar && nativeMenuReady ? (
<div className="titlebar-left">
<SidebarToggle {...titleMenuProps} mac />
</div>
) : <TitleMenus {...titleMenuProps} />}
<div className="rg-slot-anchor titlebar-center" data-rg-slot="titlebar.center" />
<div className="titlebar-right" onDoubleClick={(e) => e.stopPropagation()}>
{canLight && canDark && (
@@ -1165,11 +1304,11 @@ export const App: React.FC = () => {
</button>
</Tip>
)}
<div className="win-controls">
{!nativeTitlebar && <div className="win-controls">
<button type="button" className="win-btn" aria-label={tr('minimize')} onClick={() => WindowMinimise()}><Minus size={14} aria-hidden="true" /></button>
<button type="button" className="win-btn" aria-label={tr('maximize')} onClick={() => WindowToggleMaximise()}><Square size={12} aria-hidden="true" /></button>
<button type="button" className="win-btn close" aria-label={tr('closeWindow')} onClick={() => api.RequestClose()}><X size={15} aria-hidden="true" /></button>
</div>
</div>}
</div>
</header>
@@ -1240,6 +1379,7 @@ export const App: React.FC = () => {
safeMode={state?.safe_mode}
updateDot={!!update.info?.has_update}
pluginViews={sidebarPluginViews}
agentSessions={state?.agent_sessions}
creatingVMs={creatingItems.map((item) => ({ name: item.name, percent: item.task?.percent ?? -1 }))}
updateCard={update.shown ? (
<UpdateCapsule
@@ -1333,6 +1473,7 @@ export const App: React.FC = () => {
host={state.host}
pending={pending}
busyAction={vmBusy.busy[vmRefKey(selectedVM)]}
exportingDiagnostics={diagExporting}
onAction={onVMAction}
onPluginCommand={(pluginID, command, title) => {
const name = selectedVM.name
@@ -1367,6 +1508,24 @@ export const App: React.FC = () => {
fullscreenHotkey={fullscreenHotkey}
dropping={dropping}
pluginUI={pluginUI}
agentSession={(state.agent_sessions ?? []).find((s) => s.vm_key === vmRefKey(selectedVM) || (!s.driver_id && s.vm_name === selectedVM.name)) ?? null}
provisionReady={selectedIsMacOS && (state.provision_ready_vms?.includes(vmRefKey(selectedVM)) ?? false)}
autoInstallers={autoInstallers}
onStopAgentSession={() => {
api.StopAgentSession(selectedVM.driver_id ?? '', selectedVM.name)
.then(() => refresh())
.catch((e) => fail(tr('remoteControlStop'), e))
}}
onPauseAgentSession={() => {
api.PauseAgentSession(selectedVM.driver_id ?? '', selectedVM.name)
.then(() => refresh())
.catch((e) => fail(tr('remoteControlPause'), e))
}}
onResumeAgentSession={() => {
api.ResumeAgentSession(selectedVM.driver_id ?? '', selectedVM.name)
.then(() => refresh())
.catch((e) => fail(tr('remoteControlResume'), e))
}}
/>
</>
) : selected === SETTINGS_ID ? (
@@ -1408,6 +1567,7 @@ export const App: React.FC = () => {
locale={locale}
onRefresh={refresh}
onNewVM={openWizard}
hostReady={hostReady}
onError={fail}
onToast={(title) => toasts.push({ kind: 'ok', title })}
runtimeTask={runtimeTask}
@@ -1444,6 +1604,8 @@ export const App: React.FC = () => {
host={state?.host}
runningVMs={runningVMCount}
onCopy={copy}
onExportDiagnostics={showReadOnly ? undefined : () => { void handleExportDiagnostics() }}
exportingDiagnostics={diagExporting}
hostReady={hostReady}
onOpenHost={() => setSelected(HOST_ID)}
/>
@@ -1463,7 +1625,13 @@ export const App: React.FC = () => {
displayNames={displayNames}
showWizard={showWizard}
wizardDraft={wizardDraft}
autoInstallers={autoInstallers}
wizardDrivers={wizardDrivers}
onCloseWizard={() => { setShowWizard(false); setWizardDraft(null) }}
onDriverCreated={(driverID, name) => {
toasts.push({ kind: 'ok', title: tr('toastCreated', { name }) })
void refresh().then(() => setSelected(vmRefKey({ driver_id: driverID, name })))
}}
onSubmitCreate={submitCreate}
showSettings={showSettings}
onCloseSettings={() => setShowSettings(false)}
@@ -1503,6 +1671,13 @@ export const App: React.FC = () => {
setElevationQueue((q) => q.filter((item) => item.id !== id))
api.ResolveElevationRequest(id, approved).catch((e) => console.warn('[app] ResolveElevationRequest failed:', e))
}}
confirmQueue={confirmQueue}
onResolveConfirm={(id, approved, durationMinutes, untilPhaseExit) => {
activeConfirmIDsRef.current.delete(id)
setConfirmQueue((q) => q.filter((item) => item.id !== id))
api.ResolveConfirmRequest(id, approved, durationMinutes, untilPhaseExit)
.catch((e) => fail(tr('confirmTimedOut'), e))
}}
discardSuspendTarget={discardSuspendTarget}
onCancelDiscardSuspend={() => setDiscardSuspendTarget(null)}
onConfirmDiscardSuspend={confirmDiscardSuspend}
@@ -1533,6 +1708,19 @@ export const App: React.FC = () => {
/>
)}
{diagResult && (
<DiagnosticsExportDialog
locale={locale}
result={diagResult}
copyingFile={diagCopyingFile}
revealingFile={diagRevealingFile}
onCopyFile={() => { void handleCopyDiagnosticsFile() }}
onRevealFile={() => { void handleRevealDiagnosticsFile() }}
onCopySummary={() => { if (diagResult.summary_text) void copy(diagResult.summary_text) }}
onClose={() => setDiagResult(null)}
/>
)}
<div className="rg-layer rg-layer-overlay" data-rg-layer="layer.overlay" aria-hidden="true" />
</div>
{/* Outside the isolated shell so toasts stay above dialogs and the overlay layer. */}
+18 -19
View File
@@ -8,12 +8,13 @@ import { Button, IconButton } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { Segmented } from '../ui/settings'
import { api } from '../wails'
import { REPO_URL, siteURL } from './TitleMenus'
import { REPO_URL, siteURL } from '../lib/titleMenu'
import type { UpdatePhase } from '../lib/useAppUpdate'
import { BrandMark } from '../ui/themeVisuals'
const DISCORD_INVITE_URL = 'https://discord.gg/Tj682rW5rS'
const QQ_GROUP_ID = '1136042744'
const QQ_GROUP_INVITE_URL = 'https://qm.qq.com/q/TBmRJlVbSo'
type AppUpdateChannel = 'stable' | 'alpha' | 'dev'
@@ -100,7 +101,7 @@ export const AboutPage: React.FC<Props> = ({
.then((ok) => { if (!cancelled) setQQInstalled(!!ok) })
.catch((e) => {
console.warn('[about] CanOpenQQGroup failed:', e)
if (!cancelled) setQQInstalled(false)
if (!cancelled) setQQLaunchErr(String(e))
})
return () => {
mountedRef.current = false
@@ -319,25 +320,23 @@ export const AboutPage: React.FC<Props> = ({
) : null}
</div>
<div className="row-right">
{onCopy && (
<IconButton
small
label={tr('aboutCopyQQGroup')}
icon={<Copy size={14} aria-hidden="true" />}
onClick={() => onCopy(QQ_GROUP_ID)}
/>
)}
{qqInstalled && !qqLaunchErr ? (
<>
{onCopy && (
<IconButton
small
label={tr('aboutCopyQQGroup')}
icon={<Copy size={14} aria-hidden="true" />}
onClick={() => onCopy(QQ_GROUP_ID)}
/>
)}
<Button busy={openingQQ} icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => void openQQGroup()}>
{tr('aboutJoinQQGroup')}
</Button>
</>
) : onCopy ? (
<Button icon={<Copy size={14} aria-hidden="true" />} onClick={() => onCopy(QQ_GROUP_ID)}>
{tr('aboutCopyQQGroup')}
<Button busy={openingQQ} icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => void openQQGroup()}>
{tr('aboutJoinQQGroup')}
</Button>
) : null}
) : (
<Button icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(QQ_GROUP_INVITE_URL)}>
{tr('aboutQQOpenInvite')}
</Button>
)}
</div>
</div>
</div>
+25 -4
View File
@@ -2,6 +2,7 @@ import React, { Suspense, lazy } from 'react'
import type { WizardDraft } from './CreateWizard'
import { DeleteDialog } from './DeleteDialog'
import { ElevationDialog } from './ElevationDialog'
import { HostConfirmDialog } from './HostConfirmDialog'
import { CloneDialog } from './CloneDialog'
import { SendTextDialog } from './SendTextDialog'
import { I18nKey, t } from '../i18n'
@@ -9,11 +10,11 @@ import { hasStambhaRuntime, STAMBHA_DRIVER_ID } from '../lib/endpoints'
import { latestVMStats } from '../lib/vmStats'
import { vmRefKey } from '../lib/vmRef'
import type { PluginViewRoute } from '../lib/pluginViewRouter'
import type { AppState, CreateOpts, Locale, Task, VMDetail, VMListItem, ViewContribution } from '../types'
import type { AppState, AutoInstallerProviderView, AutoInstallStartRequest, CreateOpts, DriverSummary, Locale, ProvisionRequest, Task, VMDetail, VMListItem, ViewContribution } from '../types'
import { Button } from '../ui/controls'
import { ConfirmDialog, Modal } from '../ui/dialog'
import type { ToastInput } from '../ui/toast'
import { api, type ElevationPrompt } from '../wails'
import { api, type ConfirmPrompt, type ElevationPrompt } from '../wails'
const CreateWizard = lazy(() => import('./CreateWizard').then((m) => ({ default: m.CreateWizard })))
const SettingsModal = lazy(() => import('./SettingsModal').then((m) => ({ default: m.SettingsModal })))
@@ -34,8 +35,11 @@ interface AppDialogsProps {
showWizard: boolean
wizardDraft: WizardDraft | null
autoInstallers?: AutoInstallerProviderView[]
wizardDrivers: DriverSummary[]
onCloseWizard: () => void
onSubmitCreate: (payload: CreateOpts, draft: WizardDraft) => void
onDriverCreated: (driverID: string, name: string) => void
onSubmitCreate: (payload: CreateOpts, draft: WizardDraft, autoInstall?: AutoInstallStartRequest, provision?: ProvisionRequest) => void
showSettings: boolean
onCloseSettings: () => void
@@ -62,6 +66,9 @@ interface AppDialogsProps {
elevationQueue: ElevationPrompt[]
onResolveElevation: (id: string, approved: boolean) => void
confirmQueue: ConfirmPrompt[]
onResolveConfirm: (id: string, approved: boolean, durationMinutes: number, untilPhaseExit: boolean) => void
discardSuspendTarget: string | null
onCancelDiscardSuspend: () => void
onConfirmDiscardSuspend: () => void
@@ -88,13 +95,14 @@ export const AppDialogs: React.FC<AppDialogsProps> = (props) => {
const {
locale, state, detail, selectedVM, selectedIsMacOS, effectiveState,
fixedModeSupported, diskCacheSupported, runningVMCount, tasks, displayNames,
showWizard, wizardDraft, onCloseWizard, onSubmitCreate,
showWizard, wizardDraft, autoInstallers, wizardDrivers, onCloseWizard, onDriverCreated, onSubmitCreate,
showSettings, onCloseSettings, onSavedSettings,
affinityTarget, affinityVersion, onOpenAffinity, onCloseAffinity, onAffinityApplied,
updateConfirming, updateLatest, onCancelInstallUpdate, onConfirmInstallUpdate,
deleteTarget, onCancelDelete, onConfirmDelete,
closeDownloadsOpen, onCancelCloseDownloads,
elevationQueue, onResolveElevation,
confirmQueue, onResolveConfirm,
discardSuspendTarget, onCancelDiscardSuspend, onConfirmDiscardSuspend,
cloneSource, onCancelClone, onConfirmClone,
sendTextTarget, onCancelSendText, onConfirmSendText,
@@ -110,12 +118,16 @@ export const AppDialogs: React.FC<AppDialogsProps> = (props) => {
<CreateWizard
locale={locale}
host={state.host}
drivers={wizardDrivers}
fixedModeSupported={fixedModeSupported}
captureSupported={state.runtime_capture_supported}
initialDriverID={!state.active_runtime && hasStambhaRuntime(state.runtimes) ? STAMBHA_DRIVER_ID : undefined}
tasks={tasks}
draft={wizardDraft}
autoInstallers={autoInstallers}
onCancelTask={api.CancelTask}
onClose={onCloseWizard}
onDriverCreated={onDriverCreated}
onSubmit={onSubmitCreate}
/>
</Suspense>
@@ -210,6 +222,15 @@ export const AppDialogs: React.FC<AppDialogsProps> = (props) => {
/>
)}
{confirmQueue.length > 0 && (
<HostConfirmDialog
key={confirmQueue[0].id}
locale={locale}
request={confirmQueue[0]}
onResolve={(approved, durationMinutes, untilPhaseExit) => onResolveConfirm(confirmQueue[0].id, approved, durationMinutes, untilPhaseExit)}
/>
)}
{discardSuspendTarget && (() => {
const targetVM = findVM(discardSuspendTarget)
const targetName = targetVM?.name ?? discardSuspendTarget
@@ -659,6 +659,26 @@ export const AppSettingsPage: React.FC<Props> = ({
</div>
)}
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('agentTakeoverPauseTitle')}</div>
<div className="row-sub">{tr('agentTakeoverPauseDesc')}</div>
</div>
<div className="row-right">
<PopupSelect<string>
label={tr('agentTakeoverPauseTitle')}
value={String(config.agent_takeover_pause_sec ?? 5)}
onChange={(v) => guard(() => api.SetAgentTakeoverPauseSec(Number(v)))()}
options={[
{ value: '0', label: tr('agentTakeoverPauseManual') },
{ value: '3', label: tr('agentTakeoverPauseSeconds', { seconds: 3 }) },
{ value: '5', label: tr('agentTakeoverPauseSeconds', { seconds: 5 }) },
{ value: '10', label: tr('agentTakeoverPauseSeconds', { seconds: 10 }) },
{ value: '30', label: tr('agentTakeoverPauseSeconds', { seconds: 30 }) },
]}
/>
</div>
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('hostDNSModeTitle')}</div>
@@ -0,0 +1,443 @@
import { Copy, Pause, Play, RotateCw, Square } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { I18nKey, t } from '../i18n'
import { AutoInstallDraftFields, defaultAutoInstallDraft, validateAutoInstallDraft } from '../lib/autoInstallDraft'
import { AutoInstallerProviderView, AutoInstallStartRequest, AutoInstallStatus, Locale } from '../types'
import { Button } from '../ui/controls'
import { Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
import { api } from '../wails'
interface OCRRowProps {
locale: Locale
provider?: AutoInstallerProviderView
guestLang: string
onError?: (title: string, err: unknown) => void
}
export const AutoInstallOCRStatusRow: React.FC<OCRRowProps> = ({
locale, provider, guestLang, onError,
}) => {
const tr = (k: I18nKey, vars?: Record<string, string | number>) => t(locale, k, vars)
const [ocrStatus, setOcrStatus] = useState<{ ready: boolean; backend: string; canDownload: boolean } | null>(null)
const [downloadingOCR, setDownloadingOCR] = useState(false)
useEffect(() => {
if (!provider) {
setOcrStatus(null)
return
}
let alive = true
api.PreflightAutoInstall(provider.plugin_id, '', '', guestLang || 'zh-Hans:0')
.then((res) => {
if (!alive) return
const ocr = (res?.ocr ?? {}) as { active_backend?: string; needs_rapidocr_download?: boolean; needs_rapidocr_import?: boolean }
const ready = typeof res?.ready === 'boolean'
? res.ready
: (ocr.active_backend !== 'missing' && !ocr.needs_rapidocr_download && !ocr.needs_rapidocr_import)
setOcrStatus({
ready,
backend: ocr.active_backend || 'winocr',
canDownload: res?.can_download_ocr === true,
})
})
.catch((err) => {
if (alive) console.warn('[autoinstall] preflight probe failed:', err)
})
return () => { alive = false }
}, [provider?.plugin_id, guestLang])
const downloadOCR = async () => {
if (!provider) return
setDownloadingOCR(true)
try {
await api.DownloadAutoInstallOCR(provider.plugin_id, '')
const res = await api.PreflightAutoInstall(provider.plugin_id, '', '', guestLang || 'zh-Hans:0')
const ocr = (res?.ocr ?? {}) as { active_backend?: string; needs_rapidocr_download?: boolean; needs_rapidocr_import?: boolean }
const ready = typeof res?.ready === 'boolean'
? res.ready
: (ocr.active_backend !== 'missing' && !ocr.needs_rapidocr_download && !ocr.needs_rapidocr_import)
setOcrStatus({
ready,
backend: ocr.active_backend || 'rapidocr',
canDownload: res?.can_download_ocr === true,
})
} catch (err) {
if (onError) onError(tr('autoInstallDownloadOCR'), err)
else console.warn('[autoinstall] download OCR failed:', err)
} finally {
setDownloadingOCR(false)
}
}
if (!provider || !ocrStatus) return null
return (
<SetRow
title={
ocrStatus.ready
? tr('autoInstallOCRReady', { backend: ocrStatus.backend })
: tr(ocrStatus.canDownload ? 'autoInstallOCRMissing' : 'autoInstallOCRMissingInstallPack')
}
control={!ocrStatus.ready && ocrStatus.canDownload ? (
<Button disabled={downloadingOCR} onClick={() => void downloadOCR()}>
{tr('autoInstallDownloadOCR')}
</Button>
) : undefined}
/>
)
}
interface FieldsProps {
locale: Locale
provider?: AutoInstallerProviderView
showPluginFields?: boolean
showOCRRow?: boolean
showGuestToolsOption?: boolean
showSLARow?: boolean
guestLang: string
draft: AutoInstallDraftFields
onChange: (next: AutoInstallDraftFields) => void
onError?: (title: string, err: unknown) => void
}
export const AutoInstallPreflightFields: React.FC<FieldsProps> = ({
locale, provider, showPluginFields = true, showOCRRow = true, showGuestToolsOption = false, showSLARow = true, guestLang, draft, onChange, onError,
}) => {
const tr = (k: I18nKey, vars?: Record<string, string | number>) => t(locale, k, vars)
const pluginActive = !!provider && showPluginFields
const set = (patch: Partial<AutoInstallDraftFields>) => onChange({ ...draft, ...patch })
return (
<>
{pluginActive && showOCRRow && (
<AutoInstallOCRStatusRow locale={locale} provider={provider} guestLang={guestLang} onError={onError} />
)}
<SetRow
title={tr('autoInstallFullName')}
control={
<input
className="input rg-p-input"
aria-label={tr('autoInstallFullName')}
value={draft.fullName}
onChange={(e) => set({ fullName: e.target.value })}
spellCheck={false}
/>
}
/>
<SetRow
title={tr('autoInstallAccountName')}
control={
<input
className="input rg-p-input"
aria-label={tr('autoInstallAccountName')}
value={draft.accountName}
onChange={(e) => set({ accountName: e.target.value.toLowerCase() })}
spellCheck={false}
/>
}
/>
<SetRow
title={tr('autoInstallPassword')}
control={
<input
type="password"
className="input rg-p-input"
aria-label={tr('autoInstallPassword')}
value={draft.password}
onChange={(e) => set({ password: e.target.value })}
autoComplete="new-password"
/>
}
/>
<SetRow
title={tr('autoInstallAppearance')}
control={
<Segmented
label={tr('autoInstallAppearance')}
value={draft.appearance}
onChange={(appearance) => set({ appearance })}
options={[
{ value: 'auto' as const, label: tr('autoInstallAppearanceAuto') },
{ value: 'light' as const, label: tr('autoInstallAppearanceLight') },
{ value: 'dark' as const, label: tr('autoInstallAppearanceDark') },
]}
/>
}
/>
{showGuestToolsOption && (
<SetRow
title={tr('provisionInstallGuestTools')}
control={
<Switch
label={tr('provisionInstallGuestTools')}
checked={draft.installGuestTools}
onChange={(installGuestTools) => set({ installGuestTools })}
/>
}
/>
)}
{pluginActive && (
<SetRow
title={tr('autoInstallSaveUnlock')}
desc={tr('autoInstallFileVaultNote')}
control={
<Switch
label={tr('autoInstallSaveUnlock')}
checked={draft.saveUnlockCredential}
onChange={(saveUnlockCredential) => set({ saveUnlockCredential })}
/>
}
/>
)}
{showSLARow && (
<SetRow
title={tr('autoInstallSLAConfirm')}
control={
<Switch
label={tr('autoInstallSLAConfirm')}
checked={draft.slaAccepted}
onChange={(slaAccepted) => set({ slaAccepted })}
/>
}
/>
)}
</>
)
}
interface VMCardProps {
locale: Locale
provider: AutoInstallerProviderView
driverID: string
vmName: string
guestLang: string
sessionRefreshKey?: string
onCopy: (text: string) => void
onError: (title: string, err: unknown) => void
onToast: (title: string) => void
}
export const VMAutoInstallPanel: React.FC<VMCardProps> = ({
locale, provider, driverID, vmName, guestLang, sessionRefreshKey = '', onCopy, onError, onToast,
}) => {
const tr = (k: I18nKey, vars?: Record<string, string | number>) => t(locale, k, vars)
const [status, setStatus] = useState<AutoInstallStatus | null>(null)
const [expanded, setExpanded] = useState(false)
const [busy, setBusy] = useState(false)
const [draft, setDraft] = useState<AutoInstallDraftFields>(() => defaultAutoInstallDraft())
const refreshStatus = async (isAlive?: () => boolean) => {
try {
const st = await api.GetAutoInstallStatus(provider.plugin_id, driverID, vmName)
if (isAlive && !isAlive()) return
setStatus(st)
} catch (err) {
if (!isAlive || isAlive()) console.warn('[autoinstall] status refresh failed:', err)
}
}
useEffect(() => {
setStatus(null)
}, [provider.plugin_id, driverID, vmName])
const active = status?.status === 'running' || status?.status === 'paused_for_user'
const paused = status?.status === 'paused_for_user'
useEffect(() => {
let alive = true
const check = () => alive
void refreshStatus(check)
return () => {
alive = false
}
}, [provider.plugin_id, driverID, vmName, sessionRefreshKey])
useEffect(() => {
if (!active) return
let alive = true
const check = () => alive
const id = window.setInterval(() => { void refreshStatus(check) }, 4000)
return () => {
alive = false
window.clearInterval(id)
}
}, [active, provider.plugin_id, driverID, vmName])
const canStart = validateAutoInstallDraft(draft, true)
const start = async () => {
if (!canStart) {
if (!expanded) setExpanded(true)
return
}
setBusy(true)
try {
const fullMode = draft.enabled
const req: AutoInstallStartRequest = {
plugin_id: provider.plugin_id,
driver_id: driverID,
vm_name: vmName,
mode: fullMode ? 'full' : 'recovery_only',
guest_lang: guestLang || 'zh-Hans:0',
full_name: fullMode ? draft.fullName.trim() : '',
account_name: fullMode ? draft.accountName.trim().toLowerCase() : '',
password: fullMode ? draft.password : '',
appearance: fullMode ? draft.appearance : undefined,
sla_accepted: draft.slaAccepted,
save_unlock_credential: fullMode && draft.saveUnlockCredential,
start_vm_if_stopped: true,
}
await api.StartAutoInstall(req)
setDraft((d) => ({ ...d, password: '' }))
setExpanded(false)
await refreshStatus()
} catch (err) {
onError(tr('autoInstallStart'), err)
} finally {
setBusy(false)
}
}
const pause = async () => {
setBusy(true)
try {
await api.PauseAgentSession(driverID, vmName)
await refreshStatus()
} catch (err) {
onError(tr('autoInstallPause'), err)
} finally {
setBusy(false)
}
}
const resume = async () => {
setBusy(true)
try {
await api.ResumeAutoInstall(provider.plugin_id, driverID, vmName)
await refreshStatus()
} catch (err) {
onError(tr('autoInstallResume'), err)
} finally {
setBusy(false)
}
}
const stop = async () => {
setBusy(true)
try {
await api.StopAutoInstall(provider.plugin_id, driverID, vmName)
await refreshStatus()
} catch (err) {
onError(tr('autoInstallStop'), err)
} finally {
setBusy(false)
}
}
const copySummary = async () => {
try {
const sum = await api.GetAutoInstallDiagnosticSummary(provider.plugin_id, driverID, vmName)
onCopy(JSON.stringify(sum, null, 2))
onToast(tr('autoInstallSummaryCopied'))
} catch (err) {
onError(tr('autoInstallCopySummary'), err)
}
}
const statusText =
status?.status === 'running' ? tr('autoInstallStatusRunning')
: status?.status === 'paused_for_user' ? tr('autoInstallStatusPaused')
: status?.status === 'completed' ? tr('autoInstallStatusCompleted')
: status?.status === 'failed' ? tr('autoInstallStatusFailed')
: tr('autoInstallDesc')
return (
<SetGroup title={provider.title || tr('autoInstallTitle')}>
<SetRow
title={status?.message || statusText}
desc={status?.stage_label || status?.stage || tr('autoInstallDesc')}
control={
<div className="hstack">
{active && !paused && (
<Button icon={<Pause size={14} />} disabled={busy} onClick={() => void pause()}>
{tr('autoInstallPause')}
</Button>
)}
{paused && (
<Button variant="primary" icon={<RotateCw size={14} />} disabled={busy} onClick={() => void resume()}>
{tr('autoInstallResume')}
</Button>
)}
{active && (
<Button variant="danger" icon={<Square size={14} />} disabled={busy} onClick={() => void stop()}>
{tr('autoInstallStop')}
</Button>
)}
{(paused || status?.unknown_page_summary) && (
<Button icon={<Copy size={14} />} onClick={() => void copySummary()}>
{tr('autoInstallCopySummary')}
</Button>
)}
{!active && (
<>
<Button variant="ghost" disabled={busy} onClick={() => setExpanded((v) => !v)}>
{tr(expanded ? 'autoInstallHideOptions' : 'autoInstallOptions')}
</Button>
{!expanded && (
<Button variant="primary" icon={<Play size={14} />} disabled={busy} onClick={() => void start()}>
{tr('autoInstallStart')}
</Button>
)}
</>
)}
</div>
}
/>
{!active && expanded && (
<>
<AutoInstallOCRStatusRow locale={locale} provider={provider} guestLang={guestLang} onError={onError} />
<SetRow
title={tr('autoInstallIncludeAccountToggle')}
desc={tr('autoInstallRecoveryOnlyHint')}
control={
<Switch
label={tr('autoInstallIncludeAccountToggle')}
checked={draft.enabled}
onChange={(enabled) => setDraft((d) => ({ ...d, enabled }))}
/>
}
/>
{draft.enabled && (
<AutoInstallPreflightFields
locale={locale}
provider={provider}
showOCRRow={false}
showSLARow={false}
guestLang={guestLang}
draft={draft}
onChange={setDraft}
onError={onError}
/>
)}
<SetRow
title={tr('autoInstallSLAConfirm')}
control={
<Switch
label={tr('autoInstallSLAConfirm')}
checked={draft.slaAccepted}
onChange={(slaAccepted) => setDraft((d) => ({ ...d, slaAccepted }))}
/>
}
/>
<SetRow
title=""
control={
<Button variant="primary" disabled={busy || !canStart} onClick={() => void start()}>
{tr('autoInstallStart')}
</Button>
}
/>
</>
)}
</SetGroup>
)
}
+213 -57
View File
@@ -1,7 +1,6 @@
import { Check, ChevronRight, CircleAlert, CircleCheck, CloudDownload, Copy, Disc3, HardDrive, LucideIcon, Package } from 'lucide-react'
import React, { Suspense, lazy, useEffect, useMemo, useState } from 'react'
import React, { Suspense, lazy, useCallback, useEffect, useMemo, useState } from 'react'
import { useNetworkPlan } from '../lib/useNetworkPlan'
import { STAMBHA_DRIVER_ID } from '../lib/endpoints'
import { NpcapDependency } from './NpcapDependency'
import { NetworkErrorNotice } from './NetworkErrorNotice'
import type { ParsedAppError } from '../i18n'
@@ -45,34 +44,40 @@ import {
switchWizardGraphics,
toggleWizardBorderless,
} from '../lib/displayResolution'
import { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, Task, ValidationIssue, VMNetworkSettings } from '../types'
import { findActiveOfflineTask, taskInstallerPhase } from '../lib/tasks'
import { AutoInstallerProviderView, AutoInstallStartRequest, CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, ProvisionRequest, Release, Task, ValidationIssue, VMNetworkSettings } from '../types'
import { findActiveInstallerTask, findRunningRestoreTask, taskInstallerPhase, taskStopAction, taskTitle } from '../lib/tasks'
import { isMacOSDriver, STAMBHA_DRIVER_ID } from '../lib/endpoints'
import { defaultGuestDriver, hasRestoreImagePicker, restoreImageField } from '../lib/guestDrivers'
import { RestoreImageSource } from './RestoreImageSource'
import { Button, IconButton } from '../ui/controls'
import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
import { Modal } from '../ui/dialog'
import { api } from '../wails'
import { AutoInstallDraftFields, defaultAutoInstallDraft, validateAutoInstallDraft } from '../lib/autoInstallDraft'
import { AutoInstallOCRStatusRow, AutoInstallPreflightFields } from './AutoInstallPanel'
const SchemaForm = lazy(() => import('./SchemaForm').then((m) => ({ default: m.SchemaForm })))
const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos'
/** Reopen the wizard where the user left it (e.g. after a failed create). */
export interface WizardDraft {
opts: CreateOpts
step: number
manualResolution?: boolean
}
export type WizardDraft =
| { opts: CreateOpts; step: number; manualResolution?: boolean; restoreImage?: never; name?: never }
| { step: number; restoreImage: CachedInstaller; name: string; opts?: never; manualResolution?: never }
interface Props {
locale: Locale
host: HostReport
drivers: DriverSummary[]
fixedModeSupported?: boolean
captureSupported?: boolean
initialDriverID?: string
tasks?: Task[]
draft?: WizardDraft | null
autoInstallers?: AutoInstallerProviderView[]
onCancelTask: (id: string) => Promise<void>
onClose: () => void
onDriverCreated: (driverID: string, name: string) => void
/** Called with the cleaned payload; the caller runs the create in the background. */
onSubmit: (payload: CreateOpts, draft: WizardDraft) => void
onSubmit: (payload: CreateOpts, draft: WizardDraft, autoInstall?: AutoInstallStartRequest, provision?: ProvisionRequest) => void
}
const REVIEW_STEP = 5
@@ -95,7 +100,7 @@ const SOURCES: { mode: 'offline' | 'apple' | 'installer' | 'disk'; icon: LucideI
{ mode: 'disk', icon: HardDrive, title: 'srcDiskTitle', sub: 'srcDiskSub' },
]
export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported = false, captureSupported = false, initialDriverID = BUILTIN_MACOS_DRIVER, tasks = [], draft, onClose, onSubmit }) => {
export const CreateWizard: React.FC<Props> = ({ locale, host, drivers, fixedModeSupported = false, captureSupported = false, initialDriverID, tasks = [], draft, autoInstallers = [], onCancelTask, onClose, onDriverCreated, onSubmit }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [step, setStep] = useState(draft?.step ?? 1)
// Once the user has reached the review step, keep validating so step markers stay current.
@@ -104,26 +109,29 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
const [err, setErr] = useState('')
const [issues, setIssues] = useState<ValidationIssue[]>([])
const [cmdPreview, setCmdPreview] = useState('')
const [drivers, setDrivers] = useState<DriverSummary[]>([])
const [driverID, setDriverID] = useState(initialDriverID)
const [driverID, setDriverID] = useState(() => {
if (!draft && initialDriverID && drivers.some((d) => d.id === initialDriverID)) return initialDriverID
const source = draft?.restoreImage ? 'ipsw' : draft?.opts ? 'offline' : undefined
return defaultGuestDriver(drivers, host, source)?.id ?? ''
})
const [driverOpts, setDriverOpts] = useState<Record<string, unknown>>({})
const [restorePath, setRestorePath] = useState('')
const [driverCreating, setDriverCreating] = useState(false)
const [canceling, setCanceling] = useState(false)
const [dependencyBusy, setDependencyBusy] = useState(false)
const [dependencyRefresh, setDependencyRefresh] = useState(0)
const [autoDraft, setAutoDraft] = useState<AutoInstallDraftFields>(() => defaultAutoInstallDraft())
const [validationRefresh, setValidationRefresh] = useState(0)
useEffect(() => {
let live = true
api.ListDrivers().then((list) => { if (live) setDrivers(list ?? []) }).catch((e) => console.warn('[wizard] ListDrivers failed:', e))
return () => { live = false }
}, [])
const armImageTask = [...tasks].reverse().find((task) => task.installer_kind === 'arm-ipsw')
const activeDriver = drivers.find((d) => d.id === driverID)
const isCustomDriver = driverID !== BUILTIN_MACOS_DRIVER && !!activeDriver
const legacyDriver = !!activeDriver && isMacOSDriver(activeDriver.id)
const restoreField = activeDriver && restoreImageField(activeDriver, host)
const updateRestorePath = useCallback((path: string) => setRestorePath(path), [])
const defaultGraphics = host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga'
const [opts, setOpts] = useState<CreateOpts>(draft?.opts ?? {
name: initialDriverID === STAMBHA_DRIVER_ID ? 'macos-arm64' : 'macos-tahoe',
name: draft?.name ?? (driverID === STAMBHA_DRIVER_ID ? 'macos-arm64' : 'macos-tahoe'),
dir: '',
// 离线安装默认关闭网络,减少恢复环境依赖;用户仍可在第 4 步改为 NAT 或桥接。
source_mode: 'offline',
@@ -153,17 +161,17 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
start: true,
})
const [manualResolutionPicked, setManualResolutionPicked] = useState(() =>
initialWizardManualResolution(draft),
initialWizardManualResolution(draft?.opts ? { ...draft, opts: draft.opts } : null),
)
const [networkTouched, setNetworkTouched] = useState(!!draft?.opts)
const set = (patch: Partial<CreateOpts>) => setOpts((o) => ({ ...o, ...patch }))
const networkMode = opts.network_mode ?? (opts.network ? 'nat' : 'off')
const [networkAdapters, setNetworkAdapters] = useState<VMNetworkSettings['adapters'] | null>(null)
const [networkError, setNetworkError] = useState<ParsedAppError | null>(null)
const { plan: networkPlan, planning: networkPlanning, planError: networkPlanError } = useNetworkPlan(opts.name.trim(), networkMode, opts.uplink_guid ?? '', step >= 4 && networkMode === 'bridge', `${dependencyRefresh}:${locale}`)
const { plan: networkPlan, planning: networkPlanning, planError: networkPlanError } = useNetworkPlan(opts.name.trim(), networkMode, opts.uplink_guid ?? '', legacyDriver && step >= 4 && networkMode === 'bridge', `${dependencyRefresh}:${locale}`)
const networkBlocked = networkMode === 'bridge' && (networkPlanning || !!networkPlanError || !networkPlan || !opts.uplink_guid)
useEffect(() => {
if (step !== 4 || networkMode !== 'bridge') return
if (!legacyDriver || step !== 4 || networkMode !== 'bridge') return
let active = true
setNetworkError(null)
api.ListNetworkAdapters().then((list) => {
@@ -173,7 +181,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
if (connected.length === 1) setOpts((current) => current.uplink_guid ? current : { ...current, uplink_guid: connected[0].guid })
}).catch((error) => { if (active) setNetworkError(parseAppError(error)) })
return () => { active = false }
}, [step, networkMode, locale])
}, [legacyDriver, step, networkMode, locale])
const windowPresets = windowDisplayPresets(host, fixedModeSupported)
const fullscreenPresets = fullscreenDisplayPresets(host)
const activePresets: FullscreenDisplayPreset[] = opts.borderless ? fullscreenPresets : windowPresets
@@ -221,7 +229,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
const [cached, setCached] = useState<CachedInstaller[]>([])
const [releasesErr, setReleasesErr] = useState('')
useEffect(() => {
if (opts.source_mode !== 'offline' || releases) return
if (!legacyDriver || opts.source_mode !== 'offline' || releases) return
let live = true
api.ListInstallers().then((l) => { if (live) setCached(l ?? []) }).catch((e) => console.warn('[wizard] ListInstallers failed:', e))
api.ListOfflineReleases()
@@ -232,9 +240,9 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
})
.catch((e) => { if (live) setReleasesErr(String(e).replace(/^Error:\s*/, '')) })
return () => { live = false }
}, [opts.source_mode])
}, [legacyDriver, opts.source_mode])
const isCached = (v: string) => cached.some((c) => c.kind === 'offline' && !c.partial && c.version === v)
const activeRelease = (v: string) => findActiveOfflineTask(tasks, v)
const activeRelease = (v: string) => findActiveInstallerTask(tasks, 'offline', 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) && !activeRelease(chosenRelease.version)
@@ -249,7 +257,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
}, [reviewed, issues.length])
useEffect(() => {
if (!reviewed && step !== REVIEW_STEP) return
if (!legacyDriver || (!reviewed && step !== REVIEW_STEP)) return
let live = true
setChecking(true)
const timer = setTimeout(() => {
@@ -265,7 +273,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
.finally(() => { if (live) setChecking(false) })
}, 200)
return () => { live = false; clearTimeout(timer) }
}, [step, reviewed, effectiveOpts, validationRefresh, captureSupported])
}, [legacyDriver, step, reviewed, effectiveOpts, validationRefresh, captureSupported])
const pickDir = async () => {
const dir = await api.PickDirectory(tr('vmDir'))
@@ -277,9 +285,47 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
if (f) set({ [field]: f })
}
const macAutoInstaller = autoInstallers.find((p) => !p.guest_families?.length || p.guest_families.includes('macos'))
const provisionSupported = legacyDriver && (opts.source_mode === 'offline' || opts.source_mode === 'installer')
const autoInstallSupported = provisionSupported && !!macAutoInstaller
const provisionActive = provisionSupported && autoDraft.enabled
const autoInstallActive = autoInstallSupported && autoDraft.autoInstall
const autoInstallValid = (!provisionActive && !autoInstallActive) || validateAutoInstallDraft(autoDraft, true)
const handleCreate = () => {
if (dependencyBusy || networkBlocked) return
onSubmit(buildPayload(), { opts: effectiveOpts, step: REVIEW_STEP, manualResolution: manualResolutionPicked })
if (dependencyBusy || networkBlocked || !autoInstallValid) return
const payload = buildPayload()
const savedDraft: WizardDraft = { opts: effectiveOpts, step: REVIEW_STEP, manualResolution: manualResolutionPicked }
const provisionReq: ProvisionRequest | undefined = provisionActive
? {
full_name: autoDraft.fullName.trim(),
account_name: autoDraft.accountName.trim().toLowerCase(),
password: autoDraft.password,
appearance: autoDraft.appearance,
sla_accepted: autoDraft.slaAccepted,
install_guest_tools: autoDraft.installGuestTools,
}
: undefined
if (autoInstallActive && macAutoInstaller) {
const autoReq: AutoInstallStartRequest = {
plugin_id: macAutoInstaller.plugin_id,
driver_id: activeDriver?.id || 'builtin.driver.reims-macos',
vm_name: payload.name,
mode: provisionActive ? 'full' : 'recovery_only',
guest_lang: payload.guest_lang || 'zh-Hans:0',
full_name: provisionActive ? autoDraft.fullName.trim() : '',
account_name: provisionActive ? autoDraft.accountName.trim().toLowerCase() : '',
password: provisionActive ? autoDraft.password : '',
appearance: provisionActive ? autoDraft.appearance : undefined,
sla_accepted: autoDraft.slaAccepted,
save_unlock_credential: provisionActive && autoDraft.saveUnlockCredential,
install_guest_tools: provisionActive ? autoDraft.installGuestTools : undefined,
start_vm_if_stopped: true,
}
onSubmit({ ...payload, start: false }, savedDraft, autoReq, provisionReq)
return
}
onSubmit(payload, savedDraft, undefined, provisionReq)
}
const issueSteps = new Set(reviewed ? issues.map(stepOfIssue) : [])
@@ -293,11 +339,11 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
const memMax = Math.max(Math.floor((host.total_ram_gb || 16) * 0.85), memRec, 4)
const memGB = Math.round(parseMemoryGB(opts.memory) ?? memRec)
const steps: I18nKey[] = ['step1', 'step2', 'step3', 'step4', 'step5']
const restoreTask = driverCreating ? findRunningRestoreTask(tasks, driverID, opts.name) : undefined
return (
<Modal className="wizard-dialog" title={tr('wizardTitle')} closeLabel={tr('close')} onClose={onClose}>
{driverID !== STAMBHA_DRIVER_ID && <nav className="wizard-steps" aria-label={tr('wizardTitle')}>
<Modal className="wizard-dialog" title={tr('wizardTitle')} closeLabel={tr('close')} dismissable={!driverCreating} onClose={onClose}>
{legacyDriver && <nav className="wizard-steps" aria-label={tr('wizardTitle')}>
{steps.map((key, idx) => {
const n = idx + 1
const bad = issueSteps.has(n) && n !== REVIEW_STEP
@@ -318,7 +364,13 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
</nav>}
<div className="dialog-body">
{err && <div className="notice notice-error">{err}</div>}
{err && <div className="notice notice-error" role="alert">{err}</div>}
{restoreTask && (
<div role="status" className="hstack">
<span>{taskTitle(locale, restoreTask)}</span>
<progress aria-label={taskTitle(locale, restoreTask)} max={100} value={restoreTask.percent >= 0 ? restoreTask.percent : undefined} />
</div>
)}
<div key={step} className="step-anim">
{step === 1 && (
@@ -327,6 +379,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
<SetGroup title={tr('wizardDriverGroup')}>
<SetRow
title={tr('wizardDriverType')}
disabled={driverCreating}
control={
<PopupSelect
label={tr('wizardDriverType')}
@@ -335,18 +388,30 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
value: d.id,
label: locText(d.name, locale, d.id),
}))}
onChange={(id) => { setDriverID(id); setDriverOpts({}); setErr('') }}
onChange={(id) => { setDriverID(id); setDriverOpts({}); setRestorePath(''); setErr('') }}
/>
}
/>
</SetGroup>
)}
{isCustomDriver ? (
{!activeDriver ? <div className="notice notice-error" role="alert">{tr('wizardNoDriver')}</div> : !legacyDriver ? (
<div className="stack-3">
{restoreField && <RestoreImageSource
key={activeDriver.id}
locale={locale}
host={host}
tasks={tasks}
initialImage={draft?.restoreImage}
disabled={driverCreating}
selectedPath={restorePath}
onPathChange={updateRestorePath}
onCancelTask={onCancelTask}
/>}
<SetGroup title={tr('wizardBasics')}>
<SetRow
title={tr('vmName')}
control={<input className="input rg-p-input" value={opts.name} onChange={(e) => set({ name: e.target.value })} />}
disabled={driverCreating}
control={<input aria-label={tr('vmName')} className="input rg-p-input" value={opts.name} onChange={(e) => set({ name: e.target.value })} />}
/>
</SetGroup>
{driverID === STAMBHA_DRIVER_ID && (
@@ -365,16 +430,22 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
{activeDriver.create_schema && (
<Suspense fallback={null}>
<SchemaForm
key={activeDriver.id}
locale={locale}
schema={activeDriver.create_schema}
values={driverOpts}
disabled={driverCreating}
hideFields={restoreField ? [restoreField] : undefined}
onChange={setDriverOpts}
pathFields={driverID === STAMBHA_DRIVER_ID ? {
boot_volume: true,
raw_disk: '*.qcow2;*.raw;*.img',
usb_image: '*.raw;*.img;*.bin',
} : undefined}
onPickError={(e) => setErr(parseAppError(e).summary)}
filePicker={activeDriver.builtin ? {
supports: (prop) => hasRestoreImagePicker(activeDriver, prop),
pick: (label) => api.PickFile(label, '*.ipsw'),
} : undefined}
/>
</Suspense>
)}
@@ -725,7 +796,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
{networkAdapters?.length === 0 && <span className="muted">{tr('bridgeNoAdapters')}</span>}
</div>} />}
{networkMode === 'bridge' && <>
<NpcapDependency plan={networkPlan} locale={locale} disabled={checking || driverCreating} onBusy={setDependencyBusy} onInstalled={() => setDependencyRefresh((value) => value + 1)} />
<NpcapDependency plan={networkPlan} locale={locale} disabled={checking} onBusy={setDependencyBusy} onInstalled={() => setDependencyRefresh((value) => value + 1)} />
{networkPlanning && <div className="srow-desc" role="status">{tr('bridgePlanPending')}</div>}
<NetworkErrorNotice error={networkPlanError} locale={locale} />
</>}
@@ -786,10 +857,14 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
host={host}
opts={effectiveOpts}
captureSupported={captureSupported}
networkUplink={networkAdapters?.find((adapter) => adapter.guid === opts.uplink_guid)?.name}
networkUplink={networkAdapters?.find((adapter) => adapter.guid === opts.uplink_guid)?.name}
issues={issues}
checking={checking}
command={cmdPreview}
provisionSupported={provisionSupported}
autoInstaller={autoInstallSupported ? macAutoInstaller : undefined}
autoDraft={autoDraft}
onAutoDraft={setAutoDraft}
onEdit={setStep}
onName={(name) => set({ name })}
onPickDir={pickDir}
@@ -801,26 +876,39 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
</div>
<div className="dialog-foot">
<Button variant="ghost" disabled={step === 1 || isCustomDriver} onClick={() => setStep(step - 1)}>{tr('back')}</Button>
{isCustomDriver ? (
{legacyDriver && <Button variant="ghost" disabled={step === 1} onClick={() => setStep(step - 1)}>{tr('back')}</Button>}
{restoreTask && (
<Button variant="ghost" busy={canceling} disabled={canceling} onClick={async () => {
setCanceling(true)
try {
await onCancelTask(restoreTask.id)
} catch (e) {
setErr(parseAppError(e).summary)
setCanceling(false)
}
}}>
{taskStopAction(locale, restoreTask).label}
</Button>
)}
{!legacyDriver ? (
<Button
variant="primary"
busy={driverCreating}
disabled={!opts.name.trim() || driverCreating}
disabled={!activeDriver || !opts.name.trim() || driverCreating || (!!restoreField && !restorePath.trim())}
onClick={async () => {
const name = opts.name.trim()
setDriverCreating(true)
setErr('')
try {
await api.CreateVMWithDriver({
driver_id: driverID,
name: opts.name.trim(),
dir: driverID === STAMBHA_DRIVER_ID ? '' : opts.dir,
options: driverOpts,
})
const options = restoreField ? { ...driverOpts, [restoreField]: restorePath.trim() } : driverOpts
await api.CreateVMWithDriver({ driver_id: driverID, name, dir: driverID === STAMBHA_DRIVER_ID ? '' : opts.dir, options })
onDriverCreated(driverID, name)
onClose()
} catch (e) {
setErr(parseAppError(e).summary)
const message = parseAppError(e).summary
setErr(/\bcontext canceled\b/i.test(message) ? tr('toastCreateCanceled', { name }) : message)
} finally {
setCanceling(false)
setDriverCreating(false)
}
}}
@@ -832,8 +920,8 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
) : (
<Button
variant="primary"
disabled={dependencyBusy || checking || !!err || issues.length > 0 || !cmdPreview || networkBlocked}
title={tr('createStartedHint')}
disabled={dependencyBusy || checking || !!err || issues.length > 0 || !cmdPreview || networkBlocked || !autoInstallValid}
title={!autoInstallValid ? tr('autoInstallSLAConfirm') : tr('createStartedHint')}
onClick={handleCreate}
>
{tr('createNow')}
@@ -845,7 +933,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
}
interface ReviewProps {
networkUplink?: string
networkUplink?: string
locale: Locale
host: HostReport
opts: CreateOpts
@@ -853,6 +941,10 @@ interface ReviewProps {
issues: ValidationIssue[]
checking: boolean
command: string
provisionSupported: boolean
autoInstaller?: AutoInstallerProviderView
autoDraft: AutoInstallDraftFields
onAutoDraft: (next: AutoInstallDraftFields) => void
onEdit: (step: number) => void
onName: (name: string) => void
onDir: (dir: string) => void
@@ -865,7 +957,7 @@ 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, captureSupported, issues, checking, command, onEdit, onName, onDir, onPickDir, onStartAfter, networkUplink }) => {
const Review: React.FC<ReviewProps> = ({ locale, host, opts, captureSupported, issues, checking, command, provisionSupported, autoInstaller, autoDraft, onAutoDraft, onEdit, onName, onDir, onPickDir, onStartAfter, networkUplink }) => {
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')
@@ -963,10 +1055,74 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, captureSupported, i
/>
<SetRow
title={tr('startAfterCreate')}
control={<Switch label={tr('startAfterCreate')} checked={!!opts.start} onChange={onStartAfter} />}
disabled={!!autoInstaller && autoDraft.autoInstall}
control={<Switch label={tr('startAfterCreate')} checked={!!opts.start || (!!autoInstaller && autoDraft.autoInstall)} disabled={!!autoInstaller && autoDraft.autoInstall} onChange={onStartAfter} />}
/>
</SetGroup>
{provisionSupported && (
<SetGroup title={tr(autoInstaller ? 'autoSetupGroupTitle' : 'provisionGroupTitle')}>
{autoInstaller && (
<>
<SetRow
title={tr('autoRecoveryToggle')}
desc={tr('autoRecoveryDesc')}
control={
<Switch
label={tr('autoRecoveryToggle')}
checked={autoDraft.autoInstall}
onChange={(autoInstall) => onAutoDraft({ ...autoDraft, autoInstall })}
/>
}
/>
{autoDraft.autoInstall && (
<AutoInstallOCRStatusRow
locale={locale}
provider={autoInstaller}
guestLang={opts.guest_lang || 'zh-Hans:0'}
/>
)}
</>
)}
<SetRow
title={tr('provisionToggle')}
desc={tr('provisionDesc')}
control={
<Switch
label={tr('provisionToggle')}
checked={autoDraft.enabled}
onChange={(enabled) => onAutoDraft({ ...autoDraft, enabled })}
/>
}
/>
{autoDraft.enabled ? (
<AutoInstallPreflightFields
locale={locale}
provider={autoInstaller}
showPluginFields={!!autoInstaller && autoDraft.autoInstall}
showOCRRow={false}
showGuestToolsOption={true}
guestLang={opts.guest_lang || 'zh-Hans:0'}
draft={autoDraft}
onChange={onAutoDraft}
/>
) : (
!!autoInstaller && autoDraft.autoInstall && (
<SetRow
title={tr('autoInstallSLAConfirm')}
control={
<Switch
label={tr('autoInstallSLAConfirm')}
checked={autoDraft.slaAccepted}
onChange={(slaAccepted) => onAutoDraft({ ...autoDraft, slaAccepted })}
/>
}
/>
)
)}
</SetGroup>
)}
{checking && issues.length === 0 ? (
<div className="review-status">{tr('validationChecking')}</div>
) : issues.length > 0 ? (
@@ -0,0 +1,172 @@
import { AlertCircle, AlertTriangle, Archive, Copy, FolderOpen, Info } from 'lucide-react'
import React from 'react'
import { I18nKey, t } from '../i18n'
import { formatBytes } from '../lib/format'
import { DiagnosticFinding, DiagnosticsExportResult, Locale } from '../types'
import { Button } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { HostIcon } from '../ui/themeVisuals'
interface Props {
locale: Locale
result: DiagnosticsExportResult
copyingFile?: boolean
revealingFile?: boolean
onCopyFile: () => void
onRevealFile: () => void
onCopySummary: () => void
onClose: () => void
}
const FINDING_COPY: Record<DiagnosticFinding['code'], { title: I18nKey; desc: I18nKey }> = {
gpu_device_lost: { title: 'diagFindingGpuDeviceLostTitle', desc: 'diagFindingGpuDeviceLostDesc' },
gpu_vulkan_floor: { title: 'diagFindingGpuVulkanFloorTitle', desc: 'diagFindingGpuVulkanFloorDesc' },
whpx_unavailable: { title: 'diagFindingWhpxUnavailableTitle', desc: 'diagFindingWhpxUnavailableDesc' },
low_memory: { title: 'diagFindingLowMemoryTitle', desc: 'diagFindingLowMemoryDesc' },
low_disk: { title: 'diagFindingLowDiskTitle', desc: 'diagFindingLowDiskDesc' },
}
export const DiagnosticsExportDialog: React.FC<Props> = ({
locale,
result,
copyingFile = false,
revealingFile = false,
onCopyFile,
onRevealFile,
onCopySummary,
onClose,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const findings = result.findings ?? []
const includedFiles = result.included_files ?? []
const sizeText = result.size_bytes > 0 ? formatBytes(result.size_bytes, locale) : ''
const subtitle = [result.file_name, sizeText].filter(Boolean).join(' · ')
const busy = copyingFile || revealingFile
return (
<Modal
className="md"
title={tr('diagDialogTitle')}
subtitle={subtitle}
closeLabel={tr('close')}
onClose={onClose}
>
<div className="dialog-body">
<div className="diag-findings">
{findings.length > 0 ? (
findings.map((finding, idx) => {
const isError = finding.severity === 'error'
const copyKeys = FINDING_COPY[finding.code]
const title = copyKeys ? tr(copyKeys.title) : finding.code
const desc = copyKeys ? tr(copyKeys.desc) : ''
return (
<div
key={`${finding.code}-${idx}`}
className={`notice ${isError ? 'notice-error' : 'notice-warn'} diag-finding`}
role={isError ? 'alert' : 'status'}
>
<div className="notice-main">
<span className="notice-icon" aria-hidden="true">
<HostIcon name={isError ? 'error' : 'warning'}>
{isError ? <AlertCircle size={15} /> : <AlertTriangle size={15} />}
</HostIcon>
</span>
<div className="notice-text">
<div className="notice-title">{title}</div>
{desc && <div className="notice-sub">{desc}</div>}
{finding.detail && (
<details className="network-error-details diag-finding-details">
<summary>{tr('errRawDetailsToggle')}</summary>
<pre className="selectable">{finding.detail}</pre>
</details>
)}
</div>
</div>
</div>
)
})
) : (
<div className="notice notice-info" role="status">
<div className="notice-main">
<span className="notice-icon" aria-hidden="true">
<HostIcon name="info"><Info size={15} /></HostIcon>
</span>
<div className="notice-text">
<div className="notice-title">{tr('diagNoFindingsTitle')}</div>
<div className="notice-sub">{tr('diagNoFindingsDesc')}</div>
</div>
</div>
</div>
)}
</div>
<section className="diag-card" aria-label={tr('diagChecklistTitle')}>
<div className="diag-card-title">{tr('diagChecklistTitle')}</div>
<ul className="diag-checklist">
<li>{tr('diagChecklistZip')}</li>
<li>{tr('diagChecklistSteps')}</li>
</ul>
{includedFiles.length > 0 && (
<div className="diag-files-section">
<div className="diag-files-label">{tr('diagIncludedFiles')}</div>
<div className="diag-files">
{includedFiles.map((file) => (
<span key={file} className="diag-file-pill selectable">{file}</span>
))}
</div>
</div>
)}
</section>
{result.summary_text && (
<details className="diag-summary-details">
<summary>{tr('diagSummaryToggle')}</summary>
<pre className="diag-summary-pre selectable">{result.summary_text}</pre>
</details>
)}
</div>
<div className="dialog-foot">
<div className="diag-foot-secondary">
<Button
icon={<Copy size={14} aria-hidden="true" />}
disabled={!result.summary_text || busy}
onClick={onCopySummary}
>
{tr('diagCopySummary')}
</Button>
{result.can_copy_file && (
<Button
icon={<FolderOpen size={14} aria-hidden="true" />}
busy={revealingFile}
disabled={copyingFile}
onClick={onRevealFile}
>
{tr('diagRevealFile')}
</Button>
)}
</div>
{result.can_copy_file ? (
<Button
variant="primary"
icon={<Archive size={14} aria-hidden="true" />}
busy={copyingFile}
disabled={revealingFile}
onClick={onCopyFile}
>
{tr('diagCopyArchive')}
</Button>
) : (
<Button
variant="primary"
icon={<FolderOpen size={14} aria-hidden="true" />}
busy={revealingFile}
onClick={onRevealFile}
>
{tr('diagRevealFile')}
</Button>
)}
</div>
</Modal>
)
}
@@ -0,0 +1,105 @@
import * as Alert from '@radix-ui/react-alert-dialog'
import React, { useRef, useState } from 'react'
import { t } from '../i18n'
import { Locale } from '../types'
import { Button } from '../ui/controls'
import { PopupSelect } from '../ui/settings'
import type { ConfirmPrompt } from '../wails'
type DurationChoice = '10' | '30' | '60' | 'until_phase_exit'
interface Props {
locale: Locale
request: ConfirmPrompt
onResolve: (approved: boolean, durationMinutes: number, untilPhaseExit: boolean) => void
}
export const HostConfirmDialog: React.FC<Props> = ({ locale, request, onResolve }) => {
const cancelRef = useRef<HTMLButtonElement | null>(null)
const resolvedRef = useRef(false)
const initialChoice: DurationChoice = request.prefer_until_phase_exit
? 'until_phase_exit'
: request.default_duration_minutes === 10
? '10'
: request.default_duration_minutes === 60
? '60'
: '30'
const [duration, setDuration] = useState<DurationChoice>(initialChoice)
const resolveOnce = (approved: boolean) => {
if (resolvedRef.current) return
resolvedRef.current = true
const untilExit = duration === 'until_phase_exit'
const mins = untilExit ? 0 : Number(duration) || 30
onResolve(approved, mins, untilExit)
}
const prevFocusRef = useRef<HTMLElement | null>(
typeof document !== 'undefined' && document.activeElement instanceof HTMLElement
? document.activeElement
: null,
)
const sourceDetail = [request.publisher, request.trust].filter(Boolean).join(' · ')
const allowLabel = request.confirm_label || t(locale, 'confirmAllow')
const denyLabel = request.cancel_label || t(locale, 'confirmDeny')
return (
<Alert.Root open onOpenChange={(open) => { if (!open) resolveOnce(false) }}>
<Alert.Portal>
<Alert.Overlay className="overlay" />
<Alert.Content
className="dialog rg-p-dialog sm"
data-tone={request.danger ? 'warn' : 'info'}
onOpenAutoFocus={(e) => {
e.preventDefault()
cancelRef.current?.focus({ preventScroll: true })
}}
onCloseAutoFocus={(e) => {
e.preventDefault()
const prev = prevFocusRef.current
if (prev?.isConnected) prev.focus({ preventScroll: true })
}}
>
<div className="dialog-body">
<Alert.Title className="dialog-title">{request.title}</Alert.Title>
<div className="stack-2" style={{ marginTop: 'var(--sp-2)', fontSize: 'var(--fs-13)' }}>
<div className="muted">
{t(locale, 'elevateSource', { name: request.plugin_name || request.plugin_id })}
{sourceDetail ? ` (${sourceDetail})` : ''}
</div>
<Alert.Description className="dialog-desc" style={{ marginTop: 0 }}>{request.message}</Alert.Description>
{request.kind === 'protected_phase' && (
<div className="muted">{t(locale, 'confirmPhaseScope')}</div>
)}
{request.allow_duration_choice && (
<div className="hstack" style={{ justifyContent: 'space-between', marginTop: 'var(--sp-2)' }}>
<span>{t(locale, 'confirmDurationLabel')}</span>
<PopupSelect<DurationChoice>
label={t(locale, 'confirmDurationLabel')}
value={duration}
onChange={setDuration}
options={[
{ value: '10', label: t(locale, 'confirmDuration10') },
{ value: '30', label: t(locale, 'confirmDuration30') },
{ value: '60', label: t(locale, 'confirmDuration60') },
{ value: 'until_phase_exit', label: t(locale, 'confirmDurationUntilExit') },
]}
/>
</div>
)}
</div>
</div>
<div className="dialog-foot">
<Alert.Cancel asChild>
<Button ref={cancelRef} autoFocus onClick={() => resolveOnce(false)}>{denyLabel}</Button>
</Alert.Cancel>
<Alert.Action asChild>
<Button variant={request.danger ? 'danger' : 'primary'} onClick={() => resolveOnce(true)}>{allowLabel}</Button>
</Alert.Action>
</div>
</Alert.Content>
</Alert.Portal>
</Alert.Root>
)
}
+29 -17
View File
@@ -5,7 +5,8 @@ import '../i18n/domains/wizard.gen'
import { I18nKey, t } from '../i18n'
import { formatBytes, gpuCompatHint, gpuKey, gpuMetaLine, sameGPU } from '../lib/format'
import { describeHostWHPX } from '../lib/hypervisor'
import { hasStambhaRuntime, STAMBHA_RUNTIME_KIND } from '../lib/endpoints'
import { STAMBHA_RUNTIME_KIND } from '../lib/endpoints'
import { isAppleSilicon } from '../lib/guestDrivers'
import { AppState, Locale, StorageBreakdown, Task } from '../types'
import { Button, IconButton } from '../ui/controls'
import { Switch } from '../ui/settings'
@@ -18,6 +19,7 @@ interface Props {
locale: Locale
onRefresh: () => Promise<void>
onNewVM?: () => void
hostReady: boolean
onError: (title: string, e: unknown) => void
onToast?: (title: string) => void
runtimeTask: Task | null
@@ -27,7 +29,7 @@ interface Props {
onCancelTask: (id: string) => void
}
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, onError, onToast, runtimeTask, onChannel, onInstallRuntime, onImportRuntime, onCancelTask }) => {
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, hostReady, onError, onToast, runtimeTask, onChannel, onInstallRuntime, onImportRuntime, onCancelTask }) => {
const [importing, setImporting] = useState(false)
const [enabling, setEnabling] = useState(false)
const [savingASLR, setSavingASLR] = useState(false)
@@ -44,7 +46,13 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
return () => { live = false }
}, [state.config.data_root, state.vms?.length, state.runtimes?.length])
const whpx = describeHostWHPX(locale, host)
const nativeHost = isAppleSilicon(host)
const virtualization = nativeHost ? {
short: tr(hostReady ? 'hostReady' : 'hostNeedsAction'),
hint: host.apple_virtualization?.detail,
tone: hostReady ? 'ok' : 'warn',
canEnable: false,
} : describeHostWHPX(locale, host)
const guard = (fn: () => Promise<unknown>) => async () => {
try {
@@ -112,7 +120,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
</div>
</header>
{(state.vms?.length ?? 0) === 0 && host.whpx === 'ready' && (!!state.active_runtime || hasStambhaRuntime(runtimes)) && onNewVM && (
{(state.vms?.length ?? 0) === 0 && hostReady && onNewVM && (
<section className="welcome-card">
<h1>{tr('welcomeTitle')}</h1>
<p>{tr('welcomeSub')}</p>
@@ -125,14 +133,14 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
<div className="tiles">
<div className="tile">
<div className="tile-head">
<span className={`tile-icon ${whpx.tone}`} aria-hidden="true"><ShieldCheck size={13} /></span>
{tr('whpxTitle')}
<span className={`tile-icon ${virtualization.tone}`} aria-hidden="true"><ShieldCheck size={13} /></span>
{tr(nativeHost ? 'appleVirtualizationTitle' : 'whpxTitle')}
</div>
<div className={`tile-value ${whpx.tone}`}>{whpx.short}</div>
{whpx.canEnable ? (
<div className={`tile-value ${virtualization.tone}`}>{virtualization.short}</div>
{virtualization.canEnable ? (
<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>
) : virtualization.hint ? (
<div className="tile-sub" title={virtualization.hint}>{virtualization.hint}</div>
) : null}
</div>
<div className="tile">
@@ -150,13 +158,17 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
<span className="tile-icon accent" aria-hidden="true"><MemoryStick size={13} /></span>
{tr('hostRAM')}
</div>
<div className="tile-value">{tr('hostRAMAvail', { n: host.avail_ram_gb.toFixed(1) })}</div>
<div className="tile-sub">
<div className="tile-value">
{host.memory_usage_known
? tr('hostRAMAvail', { n: host.avail_ram_gb.toFixed(1) })
: host.total_ram_gb > 0 ? tr('hostRAMTotal', { n: host.total_ram_gb.toFixed(1) }) : '—'}
</div>
{host.memory_usage_known && <div className="tile-sub">
{tr('hostRAMTotal', { n: host.total_ram_gb.toFixed(1) })}
{host.memory_spec?.speed_mhz
? ` · ${host.memory_spec.speed_mhz} MHz${host.memory_spec.type_name ? ` ${host.memory_spec.type_name}` : ''}`
: ''}
</div>
</div>}
</div>
<div className="tile">
<div className="tile-head">
@@ -202,7 +214,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
)
})()}
<section className="section">
{!nativeHost && <section className="section">
<div className="section-title">
{tr('hostRuntime')}
<Button variant="ghost" busy={importing} onClick={importRuntime}>
@@ -275,9 +287,9 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
)
})}
</div>
</section>
</section>}
<section className="section">
{!nativeHost && <section className="section">
<div className="section-title">{tr('hostGPUs')}</div>
<div className="list">
{realGPUs.length === 0 ? (
@@ -305,7 +317,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
})
)}
</div>
</section>
</section>}
{(host.displays?.length ?? 0) > 0 && (
<section className="section">
<div className="section-title">{tr('hostDisplays')}</div>
+104 -16
View File
@@ -1,10 +1,11 @@
import { AlertTriangle, ArrowDown, ChevronDown, ChevronUp, Copy, Eraser, LoaderCircle, Pause, RefreshCw, X } from 'lucide-react'
import { AlertTriangle, Archive, ArrowDown, ChevronDown, ChevronUp, Copy, Eraser, LoaderCircle, Pause, RefreshCw, X } from 'lucide-react'
import React, { useLayoutEffect, useMemo, useRef, useState } from 'react'
import { t } from '../i18n'
import { LogLine } from '../lib/logs'
import { LogLine, countLogLines, formatLogLines, formatSelectedLogRows, isLargeLogPayload } from '../lib/logs'
import { taskDetail, taskInstallerPhase, taskStopAction, taskTitle } from '../lib/tasks'
import { HostReport, Locale, Task } from '../types'
import { Button, IconButton, Tip } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { HostIcon } from '../ui/themeVisuals'
export type LogTab = 'app' | 'serial' | 'qemu'
@@ -29,6 +30,8 @@ interface Props {
host?: HostReport
runningVMs?: number
onCopy?: (text: string) => void
onExportDiagnostics?: () => void
exportingDiagnostics?: boolean
/** False when WHPX or the runtime needs attention; the bar then leads with a link to the host page. */
hostReady?: boolean
onOpenHost?: () => void
@@ -73,11 +76,12 @@ const MAX_LOG_HEIGHT = 520
export const LogPanel: React.FC<Props> = ({
locale, open, onToggle, tab, onTab, lines, unseenErrors, onClear, serialText, qemuText, showSerial, onRefreshSerial, onRefreshQemu,
task, runningTasks, onCancelTask, host, runningVMs = 0, onCopy, hostReady = true, onOpenHost,
task, runningTasks, onCancelTask, host, runningVMs = 0, onCopy, onExportDiagnostics, exportingDiagnostics = false, hostReady = true, onOpenHost,
}) => {
const tr = (k: Parameters<typeof t>[1], v?: Record<string, string | number>) => t(locale, k, v)
const [query, setQuery] = useState('')
const [errorsOnly, setErrorsOnly] = useState(false)
const [largeCopyPending, setLargeCopyPending] = useState<{ text: string; lines: number } | null>(null)
const q = query.trim().toLowerCase()
const filteredLines = useMemo(() => {
@@ -98,26 +102,66 @@ export const LogPanel: React.FC<Props> = ({
return raw.split('\n').filter((line) => line.toLowerCase().includes(q)).join('\n')
}, [tab, serialText, qemuText, q])
const requestCopy = (text: string) => {
if (!text || !onCopy) return
if (onExportDiagnostics && isLargeLogPayload(text)) {
setLargeCopyPending({ text, lines: countLogLines(text) })
return
}
onCopy(text)
}
const copyVisible = () => {
if (!onCopy) return
const txt = tab === 'app' ? formatLogLines(filteredLines) : filteredText
if (txt) requestCopy(txt)
}
const handleBodyCopy = (e: React.ClipboardEvent<HTMLDivElement>) => {
const sel = window.getSelection()
if (!sel || sel.isCollapsed || sel.rangeCount === 0) return
const range = sel.getRangeAt(0)
if (!e.currentTarget.contains(range.commonAncestorContainer)) return
if (tab === 'app') {
const txt = filteredLines.map((l) => `${l.ts} [${l.source}] ${l.line}`).join('\n')
if (txt) onCopy(txt)
} else if (filteredText) {
onCopy(filteredText)
const lineEls = Array.from(e.currentTarget.querySelectorAll<HTMLElement>('.log-line')).filter((el) => {
try {
return range.intersectsNode(el)
} catch (err) {
console.warn('[logPanel] selection intersectsNode failed:', err)
return false
}
})
if (lineEls.length >= 2) {
const normalized = formatSelectedLogRows(
lineEls.map((el) => ({
ts: el.querySelector('.log-ts')?.textContent ?? '',
source: el.querySelector('.log-src')?.textContent ?? '',
line: el.querySelector('.log-msg')?.textContent ?? '',
})),
)
if (onExportDiagnostics && isLargeLogPayload(normalized)) {
e.preventDefault()
setLargeCopyPending({ text: normalized, lines: countLogLines(normalized) })
return
}
e.preventDefault()
e.clipboardData.setData('text/plain', normalized)
return
}
}
const selectedText = sel.toString()
if (onExportDiagnostics && isLargeLogPayload(selectedText)) {
e.preventDefault()
setLargeCopyPending({ text: selectedText, lines: countLogLines(selectedText) })
}
}
const content = tab === 'app' ? filteredLines : filteredText
const { ref, stuck, onScroll, jump } = useStickToBottom(content, open)
const memPct = host
? Math.max(0, Math.min(100, host.memory_load_pct > 0
? host.memory_load_pct
: host.total_ram_gb > 0
? Math.round(((host.total_ram_gb - host.avail_ram_gb) / host.total_ram_gb) * 100)
: 0))
: 0
const memPct = Math.max(0, Math.min(100, host?.memory_load_pct ?? 0))
const usedMemGB = host && host.total_ram_gb > 0 ? Math.max(0, host.total_ram_gb - host.avail_ram_gb) : 0
const memTone = memPct >= 90 ? ' high' : memPct >= 80 ? ' warn' : ''
const lowDisk = !!host && host.free_disk_gb > 0 && host.free_disk_gb < 30
@@ -247,7 +291,7 @@ export const LogPanel: React.FC<Props> = ({
</button>
</Tip>
)}
{host.total_ram_gb > 0 && (
{host.memory_usage_known && host.total_ram_gb > 0 && (
<Tip
side="top"
label={tr('footerMemTip', {
@@ -338,6 +382,16 @@ export const LogPanel: React.FC<Props> = ({
{open && onCopy && (
<IconButton small tipSide="top" label={tr('logCopy')} icon={<Copy size={14} />} onClick={copyVisible} />
)}
{open && onExportDiagnostics && (
<Button
className="log-export-btn"
icon={<Archive size={13} aria-hidden="true" />}
busy={exportingDiagnostics}
onClick={onExportDiagnostics}
>
{tr('logExportDiagnostics')}
</Button>
)}
{open && tab === 'app' && lines.length > 0 && (
<IconButton small tipSide="top" label={tr('clear')} icon={<Eraser size={14} />} onClick={onClear} />
)}
@@ -365,7 +419,7 @@ export const LogPanel: React.FC<Props> = ({
{open && (
<div className="logs-body-wrap">
<div className="logs-body" style={{ height }} ref={ref} onScroll={onScroll} role="log" aria-live="off">
<div className="logs-body" style={{ height }} ref={ref} onScroll={onScroll} onCopy={handleBodyCopy} role="log" aria-live="off">
{tab === 'app'
? (filteredLines.length === 0
? <span className="muted">{tr('logsEmpty')}</span>
@@ -379,6 +433,40 @@ export const LogPanel: React.FC<Props> = ({
)}
</div>
)}
{largeCopyPending && onExportDiagnostics && (
<Modal
className="sm"
tone="neutral"
title={tr('logLargeCopyTitle')}
closeLabel={tr('close')}
onClose={() => setLargeCopyPending(null)}
>
<div className="dialog-body dialog-prose">
<p>{tr('logLargeCopyDesc', { n: largeCopyPending.lines })}</p>
</div>
<div className="dialog-foot">
<Button
onClick={() => {
const pending = largeCopyPending
setLargeCopyPending(null)
if (onCopy) onCopy(pending.text)
}}
>
{tr('logCopyAnyway')}
</Button>
<Button
variant="primary"
busy={exportingDiagnostics}
onClick={() => {
setLargeCopyPending(null)
onExportDiagnostics()
}}
>
{tr('logExportDiagnostics')}
</Button>
</div>
</Modal>
)}
</div>
)
}
@@ -0,0 +1,137 @@
import { CloudDownload, Disc3, Download, Pause, X } from 'lucide-react'
import { useEffect, useLayoutEffect, useState } from 'react'
import '../i18n/domains/settings.gen'
import '../i18n/domains/wizard.gen'
import { parseAppError, t } from '../i18n'
import { cachedRestoreImage, matchesRestoreImage, restoreImageChoiceKey, restoreImageChoices } from '../lib/restoreImages'
import { findActiveInstallerTask, taskDetail, taskInstallerKind, taskInstallerPhase, taskStopAction } from '../lib/tasks'
import type { CachedInstaller, HostReport, Locale, Release, Task } from '../types'
import { Button } from '../ui/controls'
import { PopupSelect, SetGroup, SetRow } from '../ui/settings'
import { api } from '../wails'
type Source = 'apple' | 'local'
interface Props {
locale: Locale
host: HostReport
tasks: Task[]
initialImage?: CachedInstaller
disabled: boolean
selectedPath: string
onPathChange: (path: string) => void
onCancelTask: (id: string) => Promise<void>
}
export function RestoreImageSource({ locale, host, tasks, initialImage, disabled, selectedPath, onPathChange, onCancelTask }: Props) {
const [source, setSource] = useState<Source>('apple')
const [localPath, setLocalPath] = useState('')
const [cached, setCached] = useState<CachedInstaller[]>(() => initialImage ? [initialImage] : [])
const [latest, setLatest] = useState<Release | null>()
const [selection, setSelection] = useState(() => initialImage?.version ? restoreImageChoiceKey(initialImage.version, initialImage.build ?? '') : '')
const [releaseErr, setReleaseErr] = useState('')
const [cacheErr, setCacheErr] = useState('')
const [actionErr, setActionErr] = useState('')
const [catalogRequest, setCatalogRequest] = useState(0)
const [pending, setPending] = useState<'download' | 'stop' | 'file' | ''>('')
const tr = (key: Parameters<typeof t>[1], vars?: Record<string, string | number>) => t(locale, key, vars)
const tasksSig = tasks.filter((task) => taskInstallerKind(task) === 'ipsw')
.map((task) => `${task.id}:${task.status}:${task.installer_phase}`).join('|')
useEffect(() => {
if (source !== 'apple') return
let live = true
api.ListInstallers().then((items) => {
if (!live) return
setCacheErr('')
setCached(items ?? [])
}).catch((error) => { if (live) setCacheErr(parseAppError(error).summary) })
return () => { live = false }
}, [source, tasksSig, catalogRequest])
useEffect(() => {
if (source !== 'apple') return
let live = true
setReleaseErr('')
setLatest(undefined)
api.ListOfflineReleases().then((items) => {
if (live) setLatest(items?.[0] ?? null)
}).catch((error) => {
if (!live) return
setLatest(null)
setReleaseErr(parseAppError(error).summary)
})
return () => { live = false }
}, [source, catalogRequest])
const choices = restoreImageChoices(latest ?? undefined, cached)
const selected = choices.find((choice) => choice.key === selection) ?? choices[0]
const complete = selected && cachedRestoreImage(cached, selected.version, selected.build)
const currentRelease = selected && latest?.version === selected.version && latest.build === selected.build ? latest : undefined
const active = currentRelease && findActiveInstallerTask(tasks, 'ipsw', currentRelease.version)?.primary
const partial = currentRelease && cached.find((item) => item.partial && matchesRestoreImage(item, currentRelease.version, currentRelease.build))
const needGB = currentRelease?.size ? Math.max(0, currentRelease.size - (partial?.bytes ?? 0)) / (2 ** 30) : 0
const lowSpace = needGB > 0 && !complete && !active && host.free_disk_gb > 0 && host.free_disk_gb < needGB
const local = source === 'local'
const path = local ? localPath : complete?.path ?? ''
// Update the parent submit control before the new selection is painted.
useLayoutEffect(() => { if (selectedPath !== path) onPathChange(path) }, [path, selectedPath, onPathChange])
const doAction = async (action: Exclude<typeof pending, ''>, fn: () => Promise<void>) => {
setPending(action)
setActionErr('')
try {
await fn()
} catch (error) {
setActionErr(parseAppError(error).summary)
} finally {
setPending('')
}
}
return (
<>
<div className="source-cards" role="radiogroup" aria-label={tr('step1')}>
{(['apple', 'local'] as const).map((mode) => {
const apple = mode === 'apple'
const Icon = apple ? CloudDownload : Disc3
return <label key={mode} className="source-card" data-selected={source === mode || undefined}>
<input type="radio" name="restore-source" checked={source === mode} disabled={disabled} onChange={() => { setActionErr(''); setSource(mode) }} />
<span className={`source-icon source-icon-${apple ? 'apple' : 'installer'}`} aria-hidden="true"><Icon size={20} /></span>
<span className="source-title">{tr(apple ? 'srcIPSWDownloadTitle' : 'srcIPSWLocalTitle')}</span>
<span className="source-sub">{tr(apple ? 'srcIPSWDownloadSub' : 'srcIPSWLocalSub')}</span>
</label>
})}
</div>
{actionErr && <div className="notice notice-error" role="alert">{actionErr}</div>}
{local ? <SetGroup>
<SetRow title={tr('srcIPSWLocalTitle')} disabled={disabled} control={
<div className="input-group">
<input className="input rg-p-input mono" value={localPath} aria-label={tr('srcIPSWLocalTitle')} onChange={(e) => setLocalPath(e.target.value)} />
<Button busy={pending === 'file'} disabled={!!pending} onClick={() => doAction('file', async () => {
const file = await api.PickFile(tr('srcIPSWLocalTitle'), '*.ipsw')
if (file) setLocalPath(file)
})}>{tr('wizChooseFile')}</Button>
</div>
} />
</SetGroup> : <SetGroup>
{choices.length > 0 && <SetRow title={tr('macosVersion')} disabled={disabled} control={
<PopupSelect label={tr('macosVersion')} value={selected?.key ?? ''} onChange={setSelection} options={choices.map((choice) => ({ value: choice.key, label: choice.label }))} />
} />}
{active ? <SetRow title={tr(taskInstallerPhase(active) === 'queued' ? 'offlineQueued' : 'offlineDownloading')} desc={taskDetail(active)} disabled={disabled} control={
<div className="hstack" role="status">
<progress aria-label={tr('offlineDownloading')} max={100} value={active.percent >= 0 ? active.percent : undefined} />
{active.cancelable && <Button icon={taskStopAction(locale, active).kind === 'pause' ? <Pause size={14} /> : <X size={14} />} busy={pending === 'stop'} disabled={!!pending} onClick={() => doAction('stop', () => onCancelTask(active.id))}>{taskStopAction(locale, active).label}</Button>}
</div>
} /> : complete ? <SetRow title={tr('offlineCached')} desc={selected?.label} /> : currentRelease && <SetRow title={tr('srcIPSWDownloadTitle')} disabled={disabled} desc={lowSpace ? tr('offlineSpaceWarn', { free: host.free_disk_gb.toFixed(0), need: Math.ceil(needGB) }) : undefined} control={
<Button icon={<Download size={14} />} busy={pending === 'download'} disabled={!!pending || lowSpace} onClick={() => doAction('download', async () => { await api.DownloadInstaller(currentRelease.version) })}>{tr(partial ? 'installersResume' : 'installersDownload')}</Button>
} />}
{(releaseErr || cacheErr) && <div className="notice notice-error hstack" role="alert">
<span>{releaseErr || cacheErr}</span>
<Button onClick={() => setCatalogRequest((id) => id + 1)}>{tr('installersRetry')}</Button>
</div>}
{!releaseErr && latest === undefined && !complete && <p className="hint" role="status">{tr('offlineLoading')}</p>}
{!releaseErr && latest === null && choices.length === 0 && <p className="hint">{tr('srcIPSWNone')}</p>}
</SetGroup>}
</>
)
}
+36 -29
View File
@@ -1,10 +1,11 @@
import React from 'react'
import React, { useState } from 'react'
import { FolderOpen } from 'lucide-react'
import '../i18n/domains/plugins.gen'
import '../i18n/domains/settings.gen'
import { locText, t } from '../i18n'
import { locText, parseAppError, t } from '../i18n'
import { Locale, SettingProperty, SettingsSchema } from '../types'
import { NumberField, PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
import { Button } from '../ui/controls'
import { NumberField, PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
import { api } from '../wails'
interface Props {
@@ -16,7 +17,10 @@ interface Props {
onChange: (next: Record<string, unknown>, patch: Record<string, unknown>) => void
hideGroupHeader?: boolean
pathFields?: Readonly<Record<string, string | true>>
onPickError?: (error: unknown) => void
hideFields?: readonly string[]
disabled?: boolean
/** Only the trusted driver's create form supplies a native file picker. */
filePicker?: { supports: (prop: SettingProperty) => boolean; pick: (label: string) => Promise<string> }
}
const SECRET_MASK = '••••••••'
@@ -24,13 +28,16 @@ const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
/** Lazy-loaded JSON Schema form renderer supporting x-secret, x-effect, and x-scope. */
export const SchemaForm: React.FC<Props> = ({
locale, schema, values, scopeFilter, groupFilter, onChange, hideGroupHeader, pathFields, onPickError,
locale, schema, values, scopeFilter, groupFilter, onChange, hideGroupHeader, hideFields, pathFields, disabled, filePicker,
}) => {
const [picking, setPicking] = useState('')
const [pickError, setPickError] = useState<{ key: string; text: string } | null>(null)
const propsMap = schema.properties ?? {}
const keys = (schema['x-order'] && schema['x-order'].length > 0
? schema['x-order'].filter((k) => !FORBIDDEN_KEYS.has(k) && Object.prototype.hasOwnProperty.call(propsMap, k))
: Object.keys(propsMap).filter((k) => !FORBIDDEN_KEYS.has(k))
).filter((k) => {
if (hideFields?.includes(k)) return false
const prop = propsMap[k]
const effScope = prop['x-scope'] || schema['x-scope'] || 'app'
const effGroup = prop['x-group'] || schema['x-group'] || ''
@@ -138,30 +145,7 @@ export const SchemaForm: React.FC<Props> = ({
)
}
const pathField = pathFields?.[k]
if (pathField !== undefined) {
return (
<div className="input-group">
<input
type="text"
className="input rg-p-input"
aria-label={label}
value={String(cur ?? '')}
onChange={(e) => setKey(k, e.target.value)}
/>
<Button onClick={async () => {
try {
const path = pathField === true ? await api.PickDirectory(label) : await api.PickFile(label, pathField)
if (path) setKey(k, path)
} catch (error) {
onPickError?.(error)
}
}}>{t(locale, 'choose')}</Button>
</div>
)
}
return (
const textInput = (
<input
type="text"
className="input rg-p-input"
@@ -170,6 +154,27 @@ export const SchemaForm: React.FC<Props> = ({
onChange={(e) => setKey(k, e.target.value)}
/>
)
const pathField = pathFields?.[k]
if (pathField === undefined && !filePicker?.supports(prop)) return textInput
return (
<div className="input-group">
{textInput}
<Button icon={<FolderOpen size={14} />} busy={picking === k} disabled={!!picking} onClick={async () => {
setPicking(k)
setPickError(null)
try {
const path = pathField === true ? await api.PickDirectory(label)
: typeof pathField === 'string' ? await api.PickFile(label, pathField)
: await filePicker!.pick(label)
if (path) setKey(k, path)
} catch (e) {
setPickError({ key: k, text: parseAppError(e).summary })
} finally {
setPicking('')
}
}}>{t(locale, 'choose')}</Button>
</div>
)
}
const rows = keys.map((k) => {
@@ -181,6 +186,8 @@ export const SchemaForm: React.FC<Props> = ({
<SetRow
key={k}
title={title}
disabled={disabled}
error={pickError?.key === k ? pickError.text : undefined}
desc={badge || desc ? <span className="hstack">{badge}{desc ? <span>{desc}</span> : null}</span> : undefined}
control={renderControl(k, prop)}
/>
+19 -5
View File
@@ -1,9 +1,9 @@
import * as Ctx from '@radix-ui/react-context-menu'
import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Maximize2, Pause, Play, Plus, Power, Puzzle, RotateCw, Settings, Square, Trash } from 'lucide-react'
import { AppWindow, Bot, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Maximize2, Pause, Play, Plus, Power, Puzzle, RotateCw, Settings, Square, Trash } from 'lucide-react'
import React, { useRef } from 'react'
import { I18nKey, localeDir, t } from '../i18n'
import { guestFamilyOf, vmFeatures } from '../lib/endpoints'
import { Locale, VMAction, VMBusyAction, VMListItem } from '../types'
import { AgentSessionView, Locale, VMAction, VMBusyAction, VMListItem } from '../types'
import { hasVisibleDialog } from '../lib/dialogState'
import { vmRefKey } from '../lib/vmRef'
import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
@@ -49,12 +49,14 @@ interface Props {
updateDot?: boolean
/** Declared plugin pages shown after the built-in Plugins entry. */
pluginViews?: { id: string; title: string; badge?: string; icon?: string }[]
/** Active remote-control / AI agent sessions across VMs. */
agentSessions?: AgentSessionView[]
/** VMs currently being created (not yet in `vms`). */
creatingVMs?: { name: string; percent: number }[]
}
export const Sidebar: React.FC<Props> = ({
locale, vms, transitions, busyActions = {}, selected, hostReady, canSuspend, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode, updateCard, updateDot, pluginViews = [], creatingVMs = [],
locale, vms, transitions, busyActions = {}, selected, hostReady, canSuspend, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode, updateCard, updateDot, pluginViews = [], agentSessions = [], creatingVMs = [],
}) => {
const tr = (k: I18nKey) => t(locale, k)
const listRef = useRef<HTMLDivElement>(null)
@@ -85,7 +87,7 @@ export const Sidebar: React.FC<Props> = ({
kind: ReturnType<typeof statusKind> | null,
onDoubleClick?: () => void,
dot?: boolean,
vm?: { state: string; driver: string; busy: boolean; family: string },
vm?: { state: string; driver: string; busy: boolean; family: string; remoteControlled?: boolean; remoteLabel?: string },
badgeText?: string,
) => (
<button
@@ -99,6 +101,7 @@ export const Sidebar: React.FC<Props> = ({
data-driver={vm?.driver}
data-guest-family={vm?.family}
data-busy={vm ? (vm.busy ? 'true' : 'false') : undefined}
data-remote-control={vm?.remoteControlled ? 'true' : undefined}
aria-selected={selected === id}
aria-label={stateLabel ? t(locale, 'sidebarItemAria', { label, state: stateLabel }) : label}
tabIndex={selected === id || (!hasSelectedInList && id === ids[0]) ? 0 : -1}
@@ -107,6 +110,13 @@ export const Sidebar: React.FC<Props> = ({
>
<span className={`nav-icon-badge ${badgeClass}`} aria-hidden="true">{icon}</span>
<span className="nav-label">{label}</span>
{vm?.remoteControlled && (
<Tip label={vm.remoteLabel || tr('remoteControlActive')} side="right">
<span className="hstack" aria-hidden="true">
<HostIcon name="remote-control"><Bot size={13} aria-hidden="true" /></HostIcon>
</span>
</Tip>
)}
{dot && <span className="nav-dot" aria-hidden="true" />}
{badgeText && <span className="badge rg-p-badge badge-idle">{badgeText}</span>}
{kind && (
@@ -148,6 +158,10 @@ export const Sidebar: React.FC<Props> = ({
const family = guestFamilyOf(vm)
const vmCanSuspend = features.macos ? canSuspend : features.suspend
const guestArt = hasGuestArt(family)
const session = agentSessions.find((s) => s.vm_key === key || (!s.driver_id && s.vm_name === vm.name))
const remoteLabel = session
? t(locale, 'remoteControlActive', { plugin: session.plugin_name || session.plugin_id })
: undefined
const trigger = navBtn(
key,
label,
@@ -157,7 +171,7 @@ export const Sidebar: React.FC<Props> = ({
statusKind(st),
onActivate ? () => onActivate(key) : undefined,
undefined,
{ state: st, driver: vm.driver_id ?? '', busy: vmBusy || transitioning, family },
{ state: st, driver: vm.driver_id ?? '', busy: vmBusy || transitioning, family, remoteControlled: !!session, remoteLabel },
)
if (!onVMContextAction) return trigger
return (
+60 -141
View File
@@ -1,49 +1,23 @@
import * as Menu from '@radix-ui/react-dropdown-menu'
import { Check, PanelLeft } from 'lucide-react'
import React, { useRef, useState } from 'react'
import { I18nKey, localeDir, t } from '../i18n'
import { localeDir, t } from '../i18n'
import { hasVisibleDialog } from '../lib/dialogState'
import { VMFeatures, vmFeatures } from '../lib/endpoints'
import { buildTitleMenus, MENU_IDS, runMenuCommand, type MenuId, type MenuRow, type TitleMenuProps } from '../lib/titleMenu'
import { useVMStats } from '../lib/vmStats'
import { Locale, VMAction } from '../types'
import { Tip } from '../ui/controls'
import type { ThemeMode } from '../lib/useAppearance'
import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PLUGINS_ID, SETTINGS_ID } from './Sidebar'
export const REPO_URL = 'https://github.com/Nwflower/Reims-Go'
/** A page on reims.dev in the UI language: Chinese at the root, every other locale under /en. */
export function siteURL(locale: Locale, path = ''): string {
const base = locale.toLowerCase().startsWith('zh') ? 'https://reims.dev' : 'https://reims.dev/en'
return path ? `${base}${path}` : `${base}/`
}
const MENU_IDS = ['vm', 'view', 'help'] as const
type MenuId = (typeof MENU_IDS)[number]
const HOVER_CLICK_GUARD_MS = 300
interface Props {
locale: Locale
sidebarOpen: boolean
onToggleSidebar: () => void
logsOpen: boolean
onToggleLogs: () => void
themeMode: ThemeMode
canLight?: boolean
canDark?: boolean
onThemeMode: (mode: ThemeMode) => void
/** The selected VM and its current state, or null on the system pages. `features` gates actions by driver capabilities (default: everything a macOS VM offers). */
vm: { name: string; driver_id?: string; state: string; busy: boolean; graphics?: string; canSuspend: boolean; features?: VMFeatures } | null
/** Active global fullscreen toggle shortcut when enabled, else undefined. */
fullscreenHotkey?: string
onNewVM: () => void
onVMAction: (action: VMAction) => void
onVMSettings: () => void
onVMDelete: () => void
onNavigate: (id: string) => void
onOpenURL: (url: string) => void
appVersion: string
export function SidebarToggle({ locale, sidebarOpen, onToggleSidebar, mac, disabled }: Pick<TitleMenuProps, 'locale' | 'sidebarOpen' | 'onToggleSidebar'> & { mac?: boolean; disabled?: boolean }) {
const label = t(locale, sidebarOpen ? 'hideSidebar' : 'showSidebar')
return (
<Tip label={label} shortcut={mac ? '⌘B' : 'Ctrl+B'} disabled={disabled}>
<button type="button" className="titlebar-icon" aria-label={label} aria-pressed={sidebarOpen} onClick={onToggleSidebar}>
<PanelLeft size={16} aria-hidden="true" />
</button>
</Tip>
)
}
/**
@@ -52,11 +26,8 @@ interface Props {
* discoverable and still reachable with the sidebar hidden. Once one menu is
* open, hovering the next title switches to it, as in a native menu bar.
*/
export const TitleMenus: React.FC<Props> = ({
locale, sidebarOpen, onToggleSidebar, logsOpen, onToggleLogs, themeMode, canLight = true, canDark = true, onThemeMode,
vm, fullscreenHotkey, onNewVM, onVMAction, onVMSettings, onVMDelete, onNavigate, onOpenURL, appVersion,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
export const TitleMenus: React.FC<TitleMenuProps> = (props) => {
const { locale, vm, themeMode } = props
const [menuState, setMenuState] = useState<{ id: MenuId | null; switched: boolean }>({ id: null, switched: false })
const openRef = useRef<MenuId | null>(null)
const navRef = useRef<HTMLElement>(null)
@@ -70,36 +41,55 @@ export const TitleMenus: React.FC<Props> = ({
}
const running = vm?.state === 'running'
const stopped = vm?.state === 'stopped'
const suspended = vm?.state === 'suspended'
const transitioning = vm?.state === 'starting' || vm?.state === 'stopping' || vm?.state === 'suspending' || vm?.state === 'resuming'
const vmBusy = !vm || vm.busy
const features = vm?.features ?? vmFeatures(null)
const canFullscreen = running && features.fullscreen && vm?.graphics !== 'vmware-svga'
const stats = useVMStats(vm?.driver_id ?? '', canFullscreen && vm ? vm.name : null, running)
const fullscreenLabel = !canFullscreen || !stats?.running
? tr('toggleFullscreen')
: stats.window_fullscreen
? tr('exitFullscreen')
: tr('enterFullscreen')
const stats = useVMStats(vm?.driver_id ?? '', running && vm.features.fullscreen && vm.graphics !== 'vmware-svga' ? vm.name : null, running)
const menus = buildTitleMenus(props, stats?.running ? stats.window_fullscreen : undefined)
const item = (label: string, onSelect: () => void, opts: { shortcut?: string; disabled?: boolean; danger?: boolean } = {}) => (
<Menu.Item className={`menu-item rg-p-menu-item${opts.danger ? ' danger' : ''}`} disabled={opts.disabled} onSelect={onSelect}>
<span className="menu-label">{label}</span>
{opts.shortcut && <kbd className="menu-shortcut">{opts.shortcut}</kbd>}
</Menu.Item>
)
const check = (label: string, checked: boolean, onSelect: () => void, shortcut?: string) => (
<Menu.CheckboxItem className="menu-item rg-p-menu-item menu-item-check" checked={checked} onSelect={onSelect}>
<Menu.ItemIndicator className="menu-check"><Check size={13} /></Menu.ItemIndicator>
<span className="menu-label">{label}</span>
{shortcut && <kbd className="menu-shortcut">{shortcut}</kbd>}
</Menu.CheckboxItem>
)
const renderRow = (row: MenuRow, index: number) => {
if (row.kind === 'separator') return <Menu.Separator key={index} className="menu-sep" />
if (row.kind === 'label') return <Menu.Label key={index} className="menu-group-label">{row.label}</Menu.Label>
const onSelect = () => runMenuCommand(props, row.command)
const label = <span className="menu-label">{row.label}</span>
const shortcut = row.shortcut && <kbd className="menu-shortcut">{row.shortcut}</kbd>
const indicator = <Menu.ItemIndicator className="menu-check"><Check size={13} /></Menu.ItemIndicator>
if (row.kind === 'radio') return (
<Menu.RadioItem key={row.command} className="menu-item rg-p-menu-item menu-item-check" value={row.command} disabled={row.disabled}>
{indicator}{label}
</Menu.RadioItem>
)
if (row.kind === 'check') return (
<Menu.CheckboxItem key={row.command} className="menu-item rg-p-menu-item menu-item-check" checked={row.checked} disabled={row.disabled} onSelect={onSelect}>
{indicator}{label}{shortcut}
</Menu.CheckboxItem>
)
return (
<Menu.Item key={row.command} className={`menu-item rg-p-menu-item${row.danger ? ' danger' : ''}`} disabled={row.disabled} onSelect={onSelect}>
{label}{shortcut}
</Menu.Item>
)
}
const renderRows = (rows: MenuRow[]) => {
const firstRadio = rows.findIndex((row) => row.kind === 'radio')
if (firstRadio === -1) return rows.map(renderRow)
const radioRows = rows.filter((row) => row.kind === 'radio')
return (
<>
{rows.slice(0, firstRadio).map(renderRow)}
<Menu.RadioGroup value={`theme:${themeMode}`} onValueChange={(value) => {
const row = radioRows.find((entry) => entry.kind === 'radio' && entry.command === value)
if (row?.kind === 'radio') runMenuCommand(props, row.command)
}}>
{radioRows.map(renderRow)}
</Menu.RadioGroup>
{rows.slice(firstRadio + radioRows.length).map((row, i) => renderRow(row, firstRadio + radioRows.length + i))}
</>
)
}
// `indented`: the menu has check marks, so every row shares their indent.
const menu = (id: MenuId, label: string, content: React.ReactNode, indented = false) => (
<Menu.Root
key={id}
dir={localeDir(locale)}
modal={false}
open={menuState.id === id}
@@ -214,80 +204,9 @@ export const TitleMenus: React.FC<Props> = ({
return (
<div className="titlebar-left" onDoubleClick={(e) => e.stopPropagation()}>
<Tip label={tr(sidebarOpen ? 'hideSidebar' : 'showSidebar')} shortcut="Ctrl+B" disabled={menuState.id !== null}>
<button
type="button"
className="titlebar-icon"
aria-label={tr(sidebarOpen ? 'hideSidebar' : 'showSidebar')}
aria-pressed={sidebarOpen}
onClick={onToggleSidebar}
>
<PanelLeft size={16} aria-hidden="true" />
</button>
</Tip>
<nav ref={navRef} className="titlebar-menus" aria-label={tr('menuBar')}>
{menu('vm', tr('menuVM'), (
<>
{item(tr('newVMEllipsis'), onNewVM, { shortcut: 'Ctrl+N' })}
<Menu.Separator className="menu-sep" />
{running
? (features.window && item(tr('showWindow'), () => onVMAction('focus'), { shortcut: 'Ctrl+Enter', disabled: vmBusy }))
: suspended
? item(tr('resume'), () => onVMAction('resume'), { shortcut: vm?.canSuspend ? 'Ctrl+Enter' : undefined, disabled: vmBusy || !vm?.canSuspend })
: item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })}
{suspended && !vm?.canSuspend && <Menu.Label className="menu-group-label">{tr('resumeUnavailable')}</Menu.Label>}
{features.fullscreen && item(fullscreenLabel, () => onVMAction('fullscreen'), { shortcut: fullscreenHotkey, disabled: vmBusy || !canFullscreen })}
{features.suspend && item(tr('suspend'), () => onVMAction('suspend'), { disabled: vmBusy || !running || !vm?.canSuspend })}
{item(tr('stop'), () => onVMAction('stop'), { disabled: vmBusy || !running })}
{item(tr('restart'), () => onVMAction('restart'), { disabled: vmBusy || !running })}
{features.screenshot && item(tr('copyScreenshot'), () => onVMAction('screenshot'), { disabled: vmBusy || !running })}
<Menu.Separator className="menu-sep" />
{features.macos && item(tr('settingsEllipsis'), onVMSettings, { shortcut: 'Ctrl+,', disabled: !vm || suspended || transitioning })}
{features.macos && item(tr('openFolder'), () => onVMAction('openFolder'), { disabled: !vm })}
<Menu.Separator className="menu-sep" />
{suspended && item(tr('discardSuspend'), () => onVMAction('discardSuspend'), { danger: true, disabled: vmBusy })}
{item(tr('forceStop'), () => onVMAction('forceStop'), { danger: true, disabled: !vm || !(running || transitioning) })}
{item(tr('deleteEllipsis'), onVMDelete, { danger: true, disabled: vmBusy || running || suspended || transitioning })}
</>
))}
{menu('view', tr('menuView'), (
<>
{check(tr('sidebarLabel'), sidebarOpen, onToggleSidebar, 'Ctrl+B')}
{check(tr('logButton'), logsOpen, onToggleLogs, 'Ctrl+L')}
<Menu.Separator className="menu-sep" />
<Menu.Label className="menu-group-label">{tr('appearance')}</Menu.Label>
<Menu.RadioGroup value={themeMode} onValueChange={(v) => onThemeMode(v as ThemeMode)}>
{(['light', 'dark', 'system'] as const).map((m) => (
<Menu.RadioItem
key={m}
className="menu-item rg-p-menu-item menu-item-check"
value={m}
disabled={(m === 'light' && !canLight) || (m === 'dark' && !canDark) || (m === 'system' && (!canLight || !canDark))}
>
<Menu.ItemIndicator className="menu-check"><Check size={13} /></Menu.ItemIndicator>
<span className="menu-label">{tr(m === 'light' ? 'themeLight' : m === 'dark' ? 'themeDark' : 'themeSystem')}</span>
</Menu.RadioItem>
))}
</Menu.RadioGroup>
<Menu.Separator className="menu-sep" />
{item(tr('sidebarInstallers'), () => onNavigate(INSTALLERS_ID))}
{item(tr('sidebarPlugins'), () => onNavigate(PLUGINS_ID))}
{item(tr('sidebarHost'), () => onNavigate(HOST_ID))}
{item(tr('sidebarSettings'), () => onNavigate(SETTINGS_ID))}
</>
), true)}
{menu('help', tr('menuHelp'), (
<>
{item(tr('helpWebsite'), () => onOpenURL(siteURL(locale)))}
{item(tr('helpDocs'), () => onOpenURL(siteURL(locale, '/docs/quick-start')))}
{item(tr('helpProjectPage'), () => onOpenURL(REPO_URL))}
{item(tr('helpReportIssue'), () => onOpenURL(`${REPO_URL}/issues`))}
{item(tr('helpCheckUpdate'), () => onNavigate(ABOUT_ID))}
{item(tr('helpAbout'), () => onNavigate(ABOUT_ID))}
<Menu.Separator className="menu-sep" />
<Menu.Label className="menu-group-label">Reims-Go {appVersion}</Menu.Label>
</>
))}
<SidebarToggle {...props} disabled={menuState.id !== null} />
<nav ref={navRef} className="titlebar-menus" aria-label={t(locale, 'menuBar')}>
{MENU_IDS.map((id) => menu(id, menus[id].label, renderRows(menus[id].rows), id === 'view'))}
</nav>
</div>
)
+117 -29
View File
@@ -2,6 +2,7 @@ import * as Menu from '@radix-ui/react-dropdown-menu'
import {
AppWindow,
Archive,
Bot,
Camera,
Check,
ChevronDown,
@@ -31,17 +32,18 @@ import {
endpointKey,
guestFamilyOf,
isMacOSDriver as isMacOSDriverID,
splitEndpoints,
primaryVMAccess,
vmFeatures,
} from '../lib/endpoints'
import { useVMStats } from '../lib/vmStats'
import { HostReport, Locale, PendingChange, PluginUIContributions, VMAction, VMBusyAction, VMDetail, VMInfo } from '../types'
import { AgentSessionView, AutoInstallerProviderView, HostReport, Locale, PendingChange, PluginUIContributions, VMAction, VMBusyAction, VMDetail, VMInfo } from '../types'
import { api } from '../wails'
import { Button, StatusShape, Tip, statusKind } from '../ui/controls'
import { ActionMenu } from '../ui/menu'
import { HostIcon } from '../ui/themeVisuals'
import { VersionArt } from '../macos/VersionArt'
import { GuestArt, hasGuestArt } from './GuestIcon'
import { VMAutoInstallPanel } from './AutoInstallPanel'
import { ConnectionSection } from './vmPage/connections'
import { endpointIcon, EndpointSection, useEndpointActions } from './vmPage/endpoints'
import { useHostDNS } from './vmPage/hostDNS'
@@ -80,6 +82,7 @@ interface Props {
host: HostReport
pending: PendingChange[]
busyAction?: VMBusyAction
exportingDiagnostics?: boolean
onAction: (action: VMAction) => void
onPluginCommand: (pluginID: string, command: string, title: string) => void
onSettings: () => void
@@ -96,6 +99,12 @@ interface Props {
fullscreenHotkey?: string
dropping?: boolean
pluginUI?: PluginUIContributions | null
agentSession?: AgentSessionView | null
provisionReady?: boolean
autoInstallers?: AutoInstallerProviderView[]
onStopAgentSession?: () => void
onPauseAgentSession?: () => void
onResumeAgentSession?: () => void
}
function ShutdownButton({ locale, busyAction, onAction }: Pick<Props, 'locale' | 'busyAction' | 'onAction'>) {
@@ -133,7 +142,7 @@ function ShutdownButton({ locale, busyAction, onAction }: Pick<Props, 'locale' |
}
export const VMPage: React.FC<Props> = ({
locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, currentAgentVersion, guideActive, installGuideEnabled, detail, vmInfo, host, pending, busyAction, onAction, onPluginCommand, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI, fullscreenHotkey,
locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, currentAgentVersion, guideActive, installGuideEnabled, detail, vmInfo, host, pending, busyAction, exportingDiagnostics = false, onAction, onPluginCommand, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI, fullscreenHotkey, agentSession, provisionReady, autoInstallers, onStopAgentSession, onPauseAgentSession, onResumeAgentSession,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const busy = busyAction !== undefined
@@ -163,9 +172,8 @@ export const VMPage: React.FC<Props> = ({
const guestArt = !isMacOSDriver && hasGuestArt(guestFamily)
const phase = vmInfo?.phase
const waitingForGuest = running && vmInfo?.ready === false
// A running hosted VM has no window: its best ready endpoint is the header action.
const { primary: bestEndpoint } = splitEndpoints(vmInfo?.endpoints)
const promotedEndpoint = features.hosted && running ? bestEndpoint : undefined
const access = running ? primaryVMAccess(features, vmInfo?.endpoints) : undefined
const promotedEndpoint = access?.kind === 'endpoint' ? access.endpoint : undefined
const endpoints = useEndpointActions({ locale, driverID, name, onCopy, onError })
const { endpointBusy, runEndpointAction, endpointActionLabel, endpointKindLabel } = endpoints
// Polled here rather than in App so each tick re-renders only this page.
@@ -242,27 +250,23 @@ export const VMPage: React.FC<Props> = ({
primary = <Button variant="primary" busy>{tr('state_resuming')}</Button>
} else if (running) {
const showLabel = tr(guideActive ? 'showInstallGuide' : 'showWindow')
if (features.hosted) {
// No window to show: the header action is the best ready endpoint, and with none ready there is no
// primary action at all (a disabled button never takes the primary slot).
if (promotedEndpoint) {
const action = defaultEndpointAction(promotedEndpoint.kind)
const label = action ? endpointActionLabel(promotedEndpoint.kind, action) : endpointKindLabel(promotedEndpoint.kind)
primary = (
<Tip label={label} shortcut={PRIMARY_SHORTCUT}>
<Button
variant="primary"
icon={endpointIcon(promotedEndpoint.kind, 14)}
busy={endpointBusy === `${endpointKey(promotedEndpoint)}:`}
disabled={busy}
onClick={() => runEndpointAction(promotedEndpoint, '')}
>
{label}
</Button>
</Tip>
)
}
} else {
if (promotedEndpoint) {
const action = defaultEndpointAction(promotedEndpoint.kind)
const label = action ? endpointActionLabel(promotedEndpoint.kind, action) : endpointKindLabel(promotedEndpoint.kind)
primary = (
<Tip label={label} shortcut={PRIMARY_SHORTCUT}>
<Button
variant="primary"
icon={endpointIcon(promotedEndpoint.kind, 14)}
busy={endpointBusy === `${endpointKey(promotedEndpoint)}:`}
disabled={busy}
onClick={() => runEndpointAction(promotedEndpoint, '')}
>
{label}
</Button>
</Tip>
)
} else if (access?.kind === 'window') {
primary = (
<Tip label={showLabel} shortcut={PRIMARY_SHORTCUT}>
<Button variant="primary" icon={<AppWindow size={14} aria-hidden="true" />} busy={busyAction === 'focus'} disabled={busy} onClick={() => onAction('focus')}>
@@ -374,7 +378,7 @@ export const VMPage: React.FC<Props> = ({
<Menu.Item className="menu-item rg-p-menu-item" onSelect={onViewLogs}>
<HostIcon name="logs"><Terminal size={14} /></HostIcon> {tr('viewLogs')}
</Menu.Item>
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy} onSelect={() => onAction('exportDiagnostics')}>
<Menu.Item className="menu-item rg-p-menu-item" disabled={exportingDiagnostics} onSelect={() => onAction('exportDiagnostics')}>
<Archive size={14} /> {tr('exportDiagnostics')}
</Menu.Item>
{toolbarMenus.map((m) => {
@@ -412,8 +416,19 @@ export const VMPage: React.FC<Props> = ({
? ({ '--wails-drop-target': 'drop' } as React.CSSProperties)
: undefined
const matchedAutoInstaller = (autoInstallers ?? []).find((p) => !p.guest_families?.length || p.guest_families.includes(guestFamily))
const showAutoInstaller = !!matchedAutoInstaller && (
installing || phase === 'installer' || phase === 'recovery' || agentSession?.plugin_id === matchedAutoInstaller.plugin_id
)
return (
<div className="page vm-page vm-page-drop rg-p-vm-page" data-vm-state={state} data-driver={driverID} data-guest-family={guestFamily} style={dropStyle}>
<div
className="page vm-page vm-page-drop rg-p-vm-page"
data-vm-state={state}
data-driver={driverID}
data-guest-family={guestFamily}
data-remote-control={agentSession ? 'true' : undefined}
style={dropStyle}
>
{dropping && (
<div className="drop-banner" role="status" aria-live="polite">
<Upload size={16} aria-hidden="true" />
@@ -497,11 +512,84 @@ export const VMPage: React.FC<Props> = ({
<VMSummary locale={locale} running={running} detail={detail} vmInfo={vmInfo} isMacOSDriver={isMacOSDriver} guestFamily={guestFamily} host={host} stats={stats} />
</div>
{agentSession && (() => {
const phaseLabel = agentSession.phase === 'installer'
? tr('phaseInstaller')
: agentSession.phase === 'recovery'
? tr('phaseRecovery')
: ''
const title = phaseLabel
? (!agentSession.auth_until_phase_exit && (agentSession.auth_remaining_sec ?? 0) > 0
? tr('remoteControlPhaseAuthTimer', {
phase: phaseLabel,
minutes: Math.max(1, Math.ceil((agentSession.auth_remaining_sec ?? 0) / 60)),
})
: tr('remoteControlPhaseAuth', { phase: phaseLabel }))
: tr('remoteControlActive', { plugin: agentSession.plugin_name || agentSession.plugin_id })
const paused = !!(agentSession.paused_for_user || agentSession.takeover_paused)
const sub = agentSession.takeover_paused && !agentSession.takeover_manual_wait && (agentSession.takeover_remaining_sec ?? 0) > 0
? tr('remoteControlTakeoverCountdown', { seconds: agentSession.takeover_remaining_sec ?? 1 })
: paused
? (agentSession.message || tr('remoteControlPaused'))
: [agentSession.input_locked ? tr('remoteControlInputLocked') : '', agentSession.stage_label || agentSession.stage, agentSession.message].filter(Boolean).join(' · ')
return (
<div className="notice notice-info" role="status" aria-live="polite">
<span className="notice-main">
<HostIcon name="remote-control"><Bot size={15} className="notice-icon" aria-hidden="true" /></HostIcon>
<span className="notice-text">
<span className="notice-title">{title}</span>
{sub && <span className="notice-sub">{sub}</span>}
</span>
</span>
<div className="hstack">
{!paused && onPauseAgentSession && (
<Button onClick={onPauseAgentSession}>{tr('remoteControlPause')}</Button>
)}
{paused && onResumeAgentSession && (
<Button variant="primary" onClick={onResumeAgentSession}>{tr('remoteControlResume')}</Button>
)}
{onStopAgentSession && (
<Button variant="danger" onClick={onStopAgentSession}>{tr('remoteControlStop')}</Button>
)}
</div>
</div>
)
})()}
{provisionReady && installing && !agentSession && (
<div className="notice notice-info" role="status" aria-live="polite">
<span className="notice-main">
<Check size={15} className="notice-icon" aria-hidden="true" />
<span className="notice-text">
<span className="notice-title">{tr('provisionReadyNoticeTitle')}</span>
<span className="notice-sub">{tr('provisionReadyNoticeDesc')}</span>
</span>
</span>
<Button variant="primary" busy={busyAction === 'finishInstall'} disabled={busy} onClick={() => onAction('finishInstall')}>
{tr('finishInstall')}
</Button>
</div>
)}
<VMNotices
locale={locale} state={state} canSuspend={canSuspend} resumeHintId={resumeHintId} detail={detail} stats={stats}
host={host} pending={pending} busyAction={busyAction} onAction={onAction}
/>
{showAutoInstaller && matchedAutoInstaller && (
<VMAutoInstallPanel
locale={locale}
provider={matchedAutoInstaller}
driverID={driverID}
vmName={name}
guestLang={detail?.guest_lang || 'zh-Hans:0'}
sessionRefreshKey={agentSession ? `${agentSession.plugin_id}:${agentSession.status ?? ''}:${agentSession.stage ?? ''}` : ''}
onCopy={onCopy}
onError={onError}
onToast={onToast}
/>
)}
{detail && installing && (!installGuideEnabled || state === 'stopped') && (
<InstallCard
key={name} locale={locale} name={name} detail={detail} running={running} installGuideEnabled={installGuideEnabled}
+98 -2
View File
@@ -12,7 +12,7 @@ export const coreZh: Record<string, string> = {
"clear": "清空",
"close": "关闭",
"closeDownloadsConfirm": "退出",
"closeDownloadsDesc": "仍有下载正在进行,退出会中断它们。",
"closeDownloadsDesc": "退出会中断正在进行的下载或 macOS 安装。",
"closeDownloadsTitle": "退出 Reims-Go?",
"closeWindow": "关闭",
"collapseLogs": "收起日志",
@@ -28,6 +28,27 @@ export const coreZh: Record<string, string> = {
"dataRootRetry": "重试",
"delete": "删除…",
"deleteEllipsis": "删除…",
"diagChecklistSteps": "一并说明问题现象、卡住的阶段或触发前的操作",
"diagChecklistTitle": "反馈清单",
"diagChecklistZip": "直接发送此 .zip 压缩包,内含已脱敏的环境信息、配置与日志,无需再贴大段文字或截图",
"diagCopyArchive": "复制压缩包",
"diagCopySummary": "复制摘要",
"diagDialogTitle": "排障包",
"diagFindingGpuDeviceLostDesc": "更新显卡驱动、改选其他独立显卡,或暂时改用 VMware SVGA(软件渲染)",
"diagFindingGpuDeviceLostTitle": "显卡设备丢失",
"diagFindingGpuVulkanFloorDesc": "更新显卡驱动以支持 Vulkan 1.3 与必需扩展,或改用 VMware SVGA(软件渲染)",
"diagFindingGpuVulkanFloorTitle": "Vulkan 版本或扩展不足",
"diagFindingLowDiskDesc": "清理数据盘空间,或将数据目录迁移到可用空间更大的磁盘",
"diagFindingLowDiskTitle": "数据盘可用空间偏低",
"diagFindingLowMemoryDesc": "关闭占用较高的宿主机程序,或调低虚拟机分配内存后重试",
"diagFindingLowMemoryTitle": "宿主机可用内存偏低",
"diagFindingWhpxUnavailableDesc": "打开「内核」页检查 Windows 虚拟机监控程序平台状态并按提示启用",
"diagFindingWhpxUnavailableTitle": "WHPX 虚拟化不可用",
"diagIncludedFiles": "包含文件",
"diagNoFindingsDesc": "日志与环境检查未发现常见故障,求助时补充具体现象(如黑屏、卡进度条)便于排查",
"diagNoFindingsTitle": "未发现已知异常",
"diagRevealFile": "打开位置",
"diagSummaryToggle": "环境摘要",
"displays": "显示器数量",
"eject": "弹出安装盘",
"elevateActionFallbackDesc": "随后将弹出系统 UAC 授权提示,本程序不会自动重启 Windows。",
@@ -47,6 +68,7 @@ export const coreZh: Record<string, string> = {
"errorBoundaryReload": "重新加载界面",
"errorBoundaryTitle": "界面遇到意外错误",
"expandLogs": "展开日志",
"failCopyDiagnosticsFile": "复制排障包失败",
"failCreate": "{name} 创建失败",
"failDownload": "下载失败",
"failGeneric": "操作失败",
@@ -101,7 +123,11 @@ export const coreZh: Record<string, string> = {
"logActivity": "活动",
"logButton": "日志",
"logCopy": "复制日志",
"logCopyAnyway": "仍然复制",
"logErrorsOnly": "仅错误/警告",
"logExportDiagnostics": "导出排障包",
"logLargeCopyDesc": "即将复制 {n} 行日志,直接粘贴容易刷屏且缺少环境信息,建议导出排障包",
"logLargeCopyTitle": "大段日志",
"logQemu": "QEMU",
"logSearchPlaceholder": "筛选日志…",
"logSerial": "串口",
@@ -121,6 +147,24 @@ export const coreZh: Record<string, string> = {
"maximize": "最大化",
"menuBar": "菜单栏",
"menuHelp": "帮助",
"menuMacCut": "剪切",
"menuMacDelete": "删除",
"menuMacEdit": "编辑",
"menuMacFullScreen": "进入全屏幕",
"menuMacHide": "隐藏 Reims-Go",
"menuMacHideOthers": "隐藏其他应用",
"menuMacPaste": "粘贴",
"menuMacPasteMatchStyle": "粘贴并匹配样式",
"menuMacQuit": "退出 Reims-Go",
"menuMacRedo": "重做",
"menuMacSelectAll": "全选",
"menuMacShowAll": "显示全部",
"menuMacSpeech": "朗读",
"menuMacStartSpeaking": "开始朗读",
"menuMacStopSpeaking": "停止朗读",
"menuMacUndo": "撤销",
"menuMacWindow": "窗口",
"menuMacZoom": "缩放",
"menuVM": "虚拟机",
"menuView": "视图",
"minimize": "最小化",
@@ -172,6 +216,7 @@ export const coreZh: Record<string, string> = {
"taskDownload": "下载 macOS {v}",
"taskPluginDownload": "下载 {name}",
"taskRecoveryDownload": "正在为 {name} 拉取并挂载在线恢复镜像",
"taskRestoreVM": "在 {name} 上安装 macOS",
"taskRuntime": "安装运行时 {v}",
"tasksRunning": "{n, plural, other {# 个任务进行中}}",
"themeDark": "深色",
@@ -185,6 +230,7 @@ export const coreZh: Record<string, string> = {
"toastCreateCanceled": "已取消创建 {name}",
"toastCreateCanceledPartial": "已下载部分已保留,可继续下载或返回修改",
"toastCreated": "{name} 已创建",
"toastDiagFileCopied": "已复制排障包文件,可直接粘贴发送",
"toastDownloadPaused": "已暂停,再次下载会从中断处继续",
"toastInstallerReady": "macOS {v} 安装包已就绪",
"toastQueueCanceled": "已取消排队",
@@ -213,6 +259,8 @@ export const coreZh: Record<string, string> = {
"uptimeMinutesSeconds": "{m} 分 {s} 秒",
"uptimeSeconds": "{s} 秒",
"viewLogs": "查看日志",
"wizardDriverListFailed": "无法加载客体驱动",
"wizardNoDriver": "没有可用的客体驱动",
}
export const coreEn: Record<string, string> = {
@@ -227,7 +275,7 @@ export const coreEn: Record<string, string> = {
"clear": "Clear",
"close": "Close",
"closeDownloadsConfirm": "Quit",
"closeDownloadsDesc": "Downloads are still running. Quitting stops them.",
"closeDownloadsDesc": "Quitting stops any downloads or macOS installations in progress.",
"closeDownloadsTitle": "Quit Reims-Go?",
"closeWindow": "Close",
"collapseLogs": "Hide logs",
@@ -243,6 +291,27 @@ export const coreEn: Record<string, string> = {
"dataRootRetry": "Try again",
"delete": "Delete…",
"deleteEllipsis": "Delete…",
"diagChecklistSteps": "Briefly describe what happened, where it stopped, and the steps leading up to it",
"diagChecklistTitle": "Sharing checklist",
"diagChecklistZip": "Send this .zip archive directly; it includes redacted host details, settings, and logs, with no need to paste long text",
"diagCopyArchive": "Copy archive",
"diagCopySummary": "Copy summary",
"diagDialogTitle": "Diagnostics archive",
"diagFindingGpuDeviceLostDesc": "Update the GPU driver, choose another discrete GPU, or switch to VMware SVGA (software rendering) for now",
"diagFindingGpuDeviceLostTitle": "GPU device lost",
"diagFindingGpuVulkanFloorDesc": "Update the GPU driver for Vulkan 1.3 and required extensions, or switch to VMware SVGA (software rendering)",
"diagFindingGpuVulkanFloorTitle": "Vulkan requirements not met",
"diagFindingLowDiskDesc": "Free up space on the data drive, or move the data folder to a drive with more space",
"diagFindingLowDiskTitle": "Low free space on data drive",
"diagFindingLowMemoryDesc": "Close memory-heavy apps on the host, or lower the VM’s memory allocation and try again",
"diagFindingLowMemoryTitle": "Low available host memory",
"diagFindingWhpxUnavailableDesc": "Open the Engine page to check Windows Hypervisor Platform status and enable virtualization",
"diagFindingWhpxUnavailableTitle": "WHPX virtualization unavailable",
"diagIncludedFiles": "Included files",
"diagNoFindingsDesc": "No common faults appeared in logs or host checks; note the symptom (such as a black screen or stalled boot) when asking for help",
"diagNoFindingsTitle": "No known issues found",
"diagRevealFile": "Show in folder",
"diagSummaryToggle": "Environment summary",
"displays": "Displays",
"eject": "Eject installer",
"elevateActionFallbackDesc": "A Windows UAC prompt will follow. Reims-Go will not reboot Windows automatically.",
@@ -262,6 +331,7 @@ export const coreEn: Record<string, string> = {
"errorBoundaryReload": "Reload window",
"errorBoundaryTitle": "Something went wrong in the window",
"expandLogs": "Show logs",
"failCopyDiagnosticsFile": "Couldn’t copy diagnostics archive",
"failCreate": "Couldn’t create {name}",
"failDownload": "Download failed",
"failGeneric": "Something went wrong",
@@ -316,7 +386,11 @@ export const coreEn: Record<string, string> = {
"logActivity": "Activity",
"logButton": "Logs",
"logCopy": "Copy logs",
"logCopyAnyway": "Copy anyway",
"logErrorsOnly": "Errors \u0026 warnings",
"logExportDiagnostics": "Export diagnostics",
"logLargeCopyDesc": "Pasting {n} lines of logs can flood chat and omits system details; export diagnostics instead",
"logLargeCopyTitle": "Long log output",
"logQemu": "QEMU",
"logSearchPlaceholder": "Filter logs…",
"logSerial": "Serial",
@@ -336,6 +410,24 @@ export const coreEn: Record<string, string> = {
"maximize": "Maximize",
"menuBar": "Menu bar",
"menuHelp": "Help",
"menuMacCut": "Cut",
"menuMacDelete": "Delete",
"menuMacEdit": "Edit",
"menuMacFullScreen": "Enter Full Screen",
"menuMacHide": "Hide Reims-Go",
"menuMacHideOthers": "Hide Others",
"menuMacPaste": "Paste",
"menuMacPasteMatchStyle": "Paste and Match Style",
"menuMacQuit": "Quit Reims-Go",
"menuMacRedo": "Redo",
"menuMacSelectAll": "Select All",
"menuMacShowAll": "Show All",
"menuMacSpeech": "Speech",
"menuMacStartSpeaking": "Start Speaking",
"menuMacStopSpeaking": "Stop Speaking",
"menuMacUndo": "Undo",
"menuMacWindow": "Window",
"menuMacZoom": "Zoom",
"menuVM": "VM",
"menuView": "View",
"minimize": "Minimize",
@@ -387,6 +479,7 @@ export const coreEn: Record<string, string> = {
"taskDownload": "Downloading macOS {v}",
"taskPluginDownload": "Downloading {name}",
"taskRecoveryDownload": "Downloading online recovery for {name}",
"taskRestoreVM": "Installing macOS on {name}",
"taskRuntime": "Installing runtime {v}",
"tasksRunning": "{n, plural, one {# task running} other {# tasks running}}",
"themeDark": "Dark",
@@ -400,6 +493,7 @@ export const coreEn: Record<string, string> = {
"toastCreateCanceled": "Canceled creating {name}",
"toastCreateCanceledPartial": "Downloaded progress is kept; resume anytime or edit and retry",
"toastCreated": "{name} created",
"toastDiagFileCopied": "Diagnostics archive copied — paste to send",
"toastDownloadPaused": "Paused — downloading again continues where it stopped",
"toastInstallerReady": "macOS {v} installer ready",
"toastQueueCanceled": "Removed from download queue",
@@ -428,4 +522,6 @@ export const coreEn: Record<string, string> = {
"uptimeMinutesSeconds": "{m}m {s}s",
"uptimeSeconds": "{s}s",
"viewLogs": "View logs",
"wizardDriverListFailed": "Could not load guest drivers",
"wizardNoDriver": "No eligible guest driver is available",
}
+20 -6
View File
@@ -15,9 +15,10 @@ export const settingsZh: Record<string, string> = {
"aboutLicensesTitle": "开源许可与声明",
"aboutLicensesView": "查看",
"aboutQQGroup": "QQ 交流群",
"aboutQQLaunchFailed": "未能拉起 QQ,可复制群号手动搜索加入",
"aboutQQNotInstalled": "未安装 QQ",
"aboutQQNotInstalledSub": "未检测到本地 QQ,可复制群号手动搜索加入",
"aboutQQLaunchFailed": "未能打开 QQ,可打开邀请页或复制群号",
"aboutQQNotInstalled": "无法直接打开 QQ",
"aboutQQNotInstalledSub": "未找到可处理加群链接的 QQ,可打开邀请页或复制群号",
"aboutQQOpenInvite": "打开邀请页",
"aboutTagline": "在 Windows 上开一台带 GPU 加速的 macOS 虚拟机——免编译,开箱即用。",
"activate": "使用",
"affinityApplyNow": "立即应用",
@@ -53,6 +54,10 @@ export const settingsZh: Record<string, string> = {
"affinitySummaryNonLPE": "P + E 核({count} 线程 · {mask})",
"affinitySummaryPCores": "仅 P 核({count} 线程 · {mask})",
"affinityTitle": "处理器核心",
"agentTakeoverPauseDesc": "在虚拟机窗口操作键鼠后暂停外部输入的时间,设为「手动恢复」则需点击继续",
"agentTakeoverPauseManual": "直到手动恢复",
"agentTakeoverPauseSeconds": "{seconds} 秒",
"agentTakeoverPauseTitle": "AI 操作接管暂停时长",
"appCheckUpdate": "检查更新",
"appUpToDate": "已是最新",
"appUpdateAvailable": "发现新版本 {v}(稳定版)",
@@ -66,6 +71,7 @@ export const settingsZh: Record<string, string> = {
"appUpdateChannelTitle": "更新通道",
"appUpdateLookupFailed": "暂时无法连接 GitHub 检查更新",
"appVersionTitle": "客户端版本",
"appleVirtualizationTitle": "Apple 虚拟化",
"appliesNextStart": "下次启动生效",
"audioBackendAuto": "自动",
"audioBackendDesc": "「静音」保留 macOS 的声卡但不出声,适合排查音频问题",
@@ -345,6 +351,7 @@ export const settingsZh: Record<string, string> = {
"imagesOpenPlugins": "前往插件",
"imagesSourcesLabel": "镜像来源",
"installersAvailable": "Apple 提供的版本",
"installersCacheUnavailable": "缓存镜像不可用",
"installersCreateVM": "新建虚拟机",
"installersDelete": "删除",
"installersDeleteConfirm": "确认删除",
@@ -531,9 +538,10 @@ export const settingsEn: Record<string, string> = {
"aboutLicensesTitle": "Open-source licenses",
"aboutLicensesView": "View",
"aboutQQGroup": "QQ Group",
"aboutQQLaunchFailed": "Couldn’t launch QQ — copy the group ID to join manually",
"aboutQQNotInstalled": "QQ not installed",
"aboutQQNotInstalledSub": "Local QQ wasn’t detected — copy the group ID to join manually",
"aboutQQLaunchFailed": "Couldn’t open QQ — open the invite page or copy the group ID",
"aboutQQNotInstalled": "Can’t open QQ directly",
"aboutQQNotInstalledSub": "No QQ app can handle the invite link — open the invite page or copy the group ID",
"aboutQQOpenInvite": "Open invite page",
"aboutTagline": "Run a GPU-accelerated macOS virtual machine on Windows — prebuilt, ready out of the box.",
"activate": "Use",
"affinityApplyNow": "Apply Now",
@@ -569,6 +577,10 @@ export const settingsEn: Record<string, string> = {
"affinitySummaryNonLPE": "P + E ({count}T · {mask})",
"affinitySummaryPCores": "P-Cores ({count}T · {mask})",
"affinityTitle": "CPU cores",
"agentTakeoverPauseDesc": "How long external control pauses after physical keyboard or mouse input in a VM window",
"agentTakeoverPauseManual": "Until manual resume",
"agentTakeoverPauseSeconds": "{seconds} seconds",
"agentTakeoverPauseTitle": "AI takeover pause duration",
"appCheckUpdate": "Check for updates",
"appUpToDate": "Up to date",
"appUpdateAvailable": "New stable release {v} available",
@@ -582,6 +594,7 @@ export const settingsEn: Record<string, string> = {
"appUpdateChannelTitle": "Update channel",
"appUpdateLookupFailed": "Couldn’t check GitHub for updates",
"appVersionTitle": "App version",
"appleVirtualizationTitle": "Apple Virtualization",
"appliesNextStart": "Applies on next start",
"audioBackendAuto": "Auto",
"audioBackendDesc": "Silent keeps the macOS sound card but plays nothing; useful for troubleshooting",
@@ -861,6 +874,7 @@ export const settingsEn: Record<string, string> = {
"imagesOpenPlugins": "Open Plugins",
"imagesSourcesLabel": "Image sources",
"installersAvailable": "Releases from Apple",
"installersCacheUnavailable": "Cached image unavailable",
"installersCreateVM": "Create VM",
"installersDelete": "Delete",
"installersDeleteConfirm": "Confirm delete",
+116 -2
View File
@@ -3,6 +3,39 @@
export const vmZh: Record<string, string> = {
"attachGuestTools": "挂载 Guest Tools",
"attachInstaller": "挂载离线镜像",
"autoInstallAccountName": "账户短名(小写 ASCII)",
"autoInstallAppearance": "系统外观",
"autoInstallAppearanceAuto": "自动",
"autoInstallAppearanceDark": "深色",
"autoInstallAppearanceLight": "浅色",
"autoInstallCopySummary": "复制脱敏摘要",
"autoInstallDesc": "纯本地视觉定位与状态机自动走完恢复终端、跨重启等待与设置助理,无需联网模型",
"autoInstallDownloadOCR": "下载 RapidOCR",
"autoInstallFileVaultNote": "自动装机默认关闭 FileVault 以免阻断无人值守重启,进入桌面后可按需开启",
"autoInstallFullName": "账户全名(ASCII)",
"autoInstallHideOptions": "收起选项",
"autoInstallIncludeAccountToggle": "同时预置本地账户并自动登录桌面(REIMSPROV)",
"autoInstallOCRMissing": "当前 Windows 缺少目标语种 OCR 包,可按需下载 RapidOCR 备选模型",
"autoInstallOCRMissingInstallPack": "当前 Windows 缺少目标语种 OCR 包,需在 Windows 设置安装对应语言包或离线导入 RapidOCR 包",
"autoInstallOCRReady": "本地 OCR 已就绪({backend})",
"autoInstallOptions": "选项…",
"autoInstallPassword": "账户密码(≥4 位可见 ASCII)",
"autoInstallPause": "暂停",
"autoInstallRecoveryOnlyHint": "仅自动完成恢复模式安装(无需账户密码;启动即同意 Apple 软件许可协议)",
"autoInstallResume": "继续自动安装",
"autoInstallSLAConfirm": "已阅读并同意 Apple 软件许可协议,允许自动确认许可与完成安装",
"autoInstallSaveUnlock": "安装完成后保留密码作解锁凭据(默认进桌面后自动清除)",
"autoInstallStart": "开始自动安装",
"autoInstallStatusCompleted": "已进入可用桌面",
"autoInstallStatusFailed": "自动安装已中止",
"autoInstallStatusPaused": "已暂停等待处理",
"autoInstallStatusRunning": "正在自动安装",
"autoInstallStop": "停止装机",
"autoInstallSummaryCopied": "已复制脱敏摘要",
"autoInstallTitle": "自动完成 macOS 安装",
"autoRecoveryDesc": "自动识别恢复界面、快捷键打开终端运行安装脚本并等待重启进入系统;运行期间锁定虚拟机画面防干扰(点右上角悬浮窗「暂停」可接管);开启即同意 Apple 软件许可协议(startosinstall --agreetolicense)",
"autoRecoveryToggle": "自动完成恢复模式安装",
"autoSetupGroupTitle": "自动安装与首启预配置",
"bridgeCreateCommandHint": "此命令创建基础配置;桥接由管理器随后应用,单独运行命令不会配置宿主出口",
"brokenHint": "这台虚拟机的配置无法读取",
"cloneConfirm": "立即派生",
@@ -10,6 +43,15 @@ export const vmZh: Record<string, string> = {
"cloneNameLabel": "新虚拟机名称",
"cloneTitle": "从「{name}」派生 CoW 副本",
"cloneVM": "秒级派生副本 (CoW)",
"confirmAllow": "允许",
"confirmDeny": "拒绝",
"confirmDuration10": "10 分钟",
"confirmDuration30": "30 分钟",
"confirmDuration60": "60 分钟",
"confirmDurationLabel": "授权时长",
"confirmDurationUntilExit": "直到离开此阶段",
"confirmPhaseScope": "授权范围:截屏与键鼠输入(仅存内存,退出或点停止立即撤销)",
"confirmTimedOut": "授权确认已超时关闭,对应操作已按拒绝处理",
"connGroup": "连接",
"copyScreenshot": "截屏并复制",
"cores": "{n, plural, other {# 核}}",
@@ -75,6 +117,7 @@ export const vmZh: Record<string, string> = {
"failFullscreen": "无法切换全屏",
"failGuestTools": "Guest Tools 操作失败",
"failOpenFolder": "无法打开文件夹",
"failProvision": "写入预配置卷失败",
"failRestart": "重启失败",
"failResume": "恢复失败",
"failScreenshot": "截屏失败",
@@ -158,6 +201,21 @@ export const vmZh: Record<string, string> = {
"phaseInstaller": "安装阶段",
"phaseRecovery": "恢复模式",
"pickRecoveryTitle": "选择离线镜像(.img / .dmg)",
"provisionDesc": "离线安装时通过 PBKDF2 哈希创建本地管理员、跳过设置助理与键盘向导,并预装 Guest Tools(明文密码不落盘)",
"provisionGroupTitle": "首启预配置(跳过设置助理)",
"provisionInstallGuestTools": "预装 Reims Guest Tools(启用网络后首次登录自动启动)",
"provisionReadyNoticeDesc": "点击「退出恢复模式」以弹出安装介质、覆零清理预配置卷并启用网络与 Guest Tools",
"provisionReadyNoticeTitle": "macOS 安装已完成并首次启动就绪",
"provisionToggle": "预置本地账户并跳过设置助理",
"remoteControlActive": "AI 正在操作 · {plugin}",
"remoteControlInputLocked": "画面已锁定防干扰",
"remoteControlPause": "暂停",
"remoteControlPaused": "已暂停,手动处理后点击继续",
"remoteControlPhaseAuth": "AI 正在操作({phase}已授权)",
"remoteControlPhaseAuthTimer": "AI 正在操作({phase}已授权 · 剩余 {minutes} 分钟)",
"remoteControlResume": "继续",
"remoteControlStop": "停止",
"remoteControlTakeoverCountdown": "检测到键鼠操作,{seconds} 秒后自动恢复",
"restartToApply": "重启以应用",
"resume": "恢复",
"resumeUnavailable": "切换到支持挂起的内核后可恢复",
@@ -222,7 +280,6 @@ export const vmZh: Record<string, string> = {
"techInfo": "技术信息",
"toastCloned": "已派生 CoW 副本「{name}」",
"toastDeleted": "已删除 {name}",
"toastDiagExported": "已导出脱敏排障日志包 (.zip)",
"toastDiscardSuspend": "已放弃 {name} 的挂起状态",
"toastEjected": "已弹出安装盘",
"toastEnterRecovery": "已进入恢复模式,启动后可在引导菜单选 Recovery",
@@ -263,6 +320,39 @@ export const vmZh: Record<string, string> = {
export const vmEn: Record<string, string> = {
"attachGuestTools": "Attach Guest Tools",
"attachInstaller": "Attach offline image",
"autoInstallAccountName": "Account name (lowercase ASCII)",
"autoInstallAppearance": "Appearance",
"autoInstallAppearanceAuto": "Auto",
"autoInstallAppearanceDark": "Dark",
"autoInstallAppearanceLight": "Light",
"autoInstallCopySummary": "Copy redacted summary",
"autoInstallDesc": "Local OCR and declarative state machine automate Recovery, reboots, and Setup Assistant without cloud APIs",
"autoInstallDownloadOCR": "Download RapidOCR",
"autoInstallFileVaultNote": "FileVault stays off during unattended setup so reboots never block; enable it after reaching Desktop",
"autoInstallFullName": "Full name (ASCII)",
"autoInstallHideOptions": "Hide options",
"autoInstallIncludeAccountToggle": "Also pre-configure local account and unlock desktop (REIMSPROV)",
"autoInstallOCRMissing": "Windows OCR language pack is missing; download the RapidOCR fallback bundle",
"autoInstallOCRMissingInstallPack": "Windows OCR language pack is missing; install the language pack in Windows Settings or import an offline RapidOCR bundle",
"autoInstallOCRReady": "Local OCR ready ({backend})",
"autoInstallOptions": "Options…",
"autoInstallPassword": "Password (4+ printable ASCII)",
"autoInstallPause": "Pause",
"autoInstallRecoveryOnlyHint": "Automate Recovery mode only (no account required; starting accepts the Apple Software License Agreement)",
"autoInstallResume": "Resume auto-install",
"autoInstallSLAConfirm": "I accept the Apple Software License Agreement and authorize unattended installation",
"autoInstallSaveUnlock": "Keep password as unlock credential after setup (cleared on desktop arrival by default)",
"autoInstallStart": "Start auto-install",
"autoInstallStatusCompleted": "Desktop ready",
"autoInstallStatusFailed": "Auto-install stopped",
"autoInstallStatusPaused": "Paused for user",
"autoInstallStatusRunning": "Auto-install running",
"autoInstallStop": "Stop install",
"autoInstallSummaryCopied": "Redacted summary copied",
"autoInstallTitle": "Automatic macOS installation",
"autoRecoveryDesc": "Detects macOS Recovery, opens Terminal via shortcut to run the installer script, and restarts into macOS automatically. VM screen input is locked while running (click Pause on the top-right HUD to take over). Enabling accepts the Apple Software License Agreement (startosinstall --agreetolicense)",
"autoRecoveryToggle": "Automate Recovery mode installation",
"autoSetupGroupTitle": "Automated setup and provisioning",
"bridgeCreateCommandHint": "This command creates the base configuration; the manager applies bridging afterward. Running this command alone does not configure the host uplink.",
"brokenHint": "This VM’s configuration can’t be read",
"cloneConfirm": "Create clone",
@@ -270,6 +360,15 @@ export const vmEn: Record<string, string> = {
"cloneNameLabel": "New VM name",
"cloneTitle": "Derive CoW clone from “{name}”",
"cloneVM": "Derive CoW clone",
"confirmAllow": "Allow",
"confirmDeny": "Deny",
"confirmDuration10": "10 minutes",
"confirmDuration30": "30 minutes",
"confirmDuration60": "60 minutes",
"confirmDurationLabel": "Authorization duration",
"confirmDurationUntilExit": "Until leaving this phase",
"confirmPhaseScope": "Scope: screenshots and keyboard/mouse input (memory only; revoked on exit or Stop)",
"confirmTimedOut": "Confirmation timed out and was treated as denied",
"connGroup": "Connection",
"copyScreenshot": "Copy screenshot",
"cores": "{n, plural, one {# core} other {# cores}}",
@@ -335,6 +434,7 @@ export const vmEn: Record<string, string> = {
"failFullscreen": "Couldn’t toggle full screen",
"failGuestTools": "Guest Tools operation failed",
"failOpenFolder": "Couldn’t open the folder",
"failProvision": "Failed to prepare provisioning disk",
"failRestart": "Couldn’t restart",
"failResume": "Couldn’t resume",
"failScreenshot": "Screenshot failed",
@@ -418,6 +518,21 @@ export const vmEn: Record<string, string> = {
"phaseInstaller": "Installer",
"phaseRecovery": "Recovery",
"pickRecoveryTitle": "Choose an offline image (.img / .dmg)",
"provisionDesc": "Creates a local admin using a PBKDF2 hash during offline install, skips Setup Assistant and Keyboard Assistant, and stages Guest Tools (no plaintext password on disk)",
"provisionGroupTitle": "First-boot provisioning (skip Setup Assistant)",
"provisionInstallGuestTools": "Pre-stage Reims Guest Tools (starts on first login once network is enabled)",
"provisionReadyNoticeDesc": "Click Exit recovery mode to eject the installer, wipe the provisioning disk, and enable network and Guest Tools",
"provisionReadyNoticeTitle": "macOS installation finished and reached first boot",
"provisionToggle": "Pre-configure local account and skip Setup Assistant",
"remoteControlActive": "AI controlling · {plugin}",
"remoteControlInputLocked": "Screen input locked",
"remoteControlPause": "Pause",
"remoteControlPaused": "Paused; finish this step and click Resume",
"remoteControlPhaseAuth": "AI controlling ({phase} authorized)",
"remoteControlPhaseAuthTimer": "AI controlling ({phase} authorized · {minutes}m left)",
"remoteControlResume": "Resume",
"remoteControlStop": "Stop",
"remoteControlTakeoverCountdown": "User input detected; resumes in {seconds}s",
"restartToApply": "Restart to apply",
"resume": "Resume",
"resumeUnavailable": "Switch to a runtime that supports suspend to resume this VM",
@@ -482,7 +597,6 @@ export const vmEn: Record<string, string> = {
"techInfo": "Technical details",
"toastCloned": "CoW clone “{name}” created",
"toastDeleted": "{name} deleted",
"toastDiagExported": "Redacted diagnostics archive exported (.zip)",
"toastDiscardSuspend": "Discarded saved state for {name}",
"toastEjected": "Installer ejected",
"toastEnterRecovery": "Recovery mode ready — pick Recovery in OpenCore on next start",
+10
View File
@@ -65,6 +65,11 @@ export const wizardZh: Record<string, string> = {
"srcAppleTitle": "从 Apple 下载",
"srcDiskSub": "已装好 macOS 的 .qcow2 等磁盘",
"srcDiskTitle": "已有磁盘",
"srcIPSWDownloadSub": "从 Apple 下载或使用已下载的镜像",
"srcIPSWDownloadTitle": "兼容恢复镜像",
"srcIPSWLocalSub": "选择这台 Mac 上的 .ipsw 文件",
"srcIPSWLocalTitle": "本地恢复镜像",
"srcIPSWNone": "没有兼容的恢复镜像",
"srcInstallerSub": "本机上的 .img 或 .dmg",
"srcInstallerTitle": "安装镜像",
"srcOfflineSub": "完整安装包,装机时不联网",
@@ -163,6 +168,11 @@ export const wizardEn: Record<string, string> = {
"srcAppleTitle": "Download from Apple",
"srcDiskSub": "A .qcow2 or other disk with macOS installed",
"srcDiskTitle": "Existing disk",
"srcIPSWDownloadSub": "Download from Apple or use a saved restore image",
"srcIPSWDownloadTitle": "Compatible restore image",
"srcIPSWLocalSub": "Choose an .ipsw file on this Mac",
"srcIPSWLocalTitle": "Local restore image",
"srcIPSWNone": "No compatible restore image is available",
"srcInstallerSub": "An .img or .dmg on this PC",
"srcInstallerTitle": "Installer image",
"srcOfflineSub": "The full installer; installs with no network",
+118 -1
View File
@@ -17,6 +17,7 @@ export type I18nKey =
| "aboutQQLaunchFailed"
| "aboutQQNotInstalled"
| "aboutQQNotInstalledSub"
| "aboutQQOpenInvite"
| "aboutTagline"
| "activate"
| "affinityApplyNow"
@@ -53,6 +54,10 @@ export type I18nKey =
| "affinitySummaryNonLPE"
| "affinitySummaryPCores"
| "affinityTitle"
| "agentTakeoverPauseDesc"
| "agentTakeoverPauseManual"
| "agentTakeoverPauseSeconds"
| "agentTakeoverPauseTitle"
| "appCheckUpdate"
| "appUpToDate"
| "appUpdateAvailable"
@@ -67,6 +72,7 @@ export type I18nKey =
| "appUpdateLookupFailed"
| "appVersionTitle"
| "appearance"
| "appleVirtualizationTitle"
| "appliesNextStart"
| "armRestoreDownload"
| "armRestoreDownloaded"
@@ -84,8 +90,41 @@ export type I18nKey =
| "audioDesc"
| "audioDisabledReason"
| "audioTroubleshootNote"
| "autoInstallAccountName"
| "autoInstallAppearance"
| "autoInstallAppearanceAuto"
| "autoInstallAppearanceDark"
| "autoInstallAppearanceLight"
| "autoInstallCopySummary"
| "autoInstallDesc"
| "autoInstallDownloadOCR"
| "autoInstallFileVaultNote"
| "autoInstallFullName"
| "autoInstallHideOptions"
| "autoInstallIncludeAccountToggle"
| "autoInstallOCRMissing"
| "autoInstallOCRMissingInstallPack"
| "autoInstallOCRReady"
| "autoInstallOptions"
| "autoInstallPassword"
| "autoInstallPause"
| "autoInstallRecoveryOnlyHint"
| "autoInstallResume"
| "autoInstallSLAConfirm"
| "autoInstallSaveUnlock"
| "autoInstallStart"
| "autoInstallStatusCompleted"
| "autoInstallStatusFailed"
| "autoInstallStatusPaused"
| "autoInstallStatusRunning"
| "autoInstallStop"
| "autoInstallSummaryCopied"
| "autoInstallTitle"
| "autoPinPCores"
| "autoRecoveryDesc"
| "autoRecoveryToggle"
| "autoResolution"
| "autoSetupGroupTitle"
| "back"
| "backToEdit"
| "borderless"
@@ -145,6 +184,15 @@ export type I18nKey =
| "commandToggleHint"
| "configured"
| "confirm"
| "confirmAllow"
| "confirmDeny"
| "confirmDuration10"
| "confirmDuration30"
| "confirmDuration60"
| "confirmDurationLabel"
| "confirmDurationUntilExit"
| "confirmPhaseScope"
| "confirmTimedOut"
| "connGroup"
| "copy"
| "copyScreenshot"
@@ -180,8 +228,29 @@ export type I18nKey =
| "diagAhciUpgradeHint"
| "diagBackingChainBroken"
| "diagBackingChainWarn"
| "diagChecklistSteps"
| "diagChecklistTitle"
| "diagChecklistZip"
| "diagCopyArchive"
| "diagCopySummary"
| "diagDialogTitle"
| "diagExternalDriveWarn"
| "diagFindingGpuDeviceLostDesc"
| "diagFindingGpuDeviceLostTitle"
| "diagFindingGpuVulkanFloorDesc"
| "diagFindingGpuVulkanFloorTitle"
| "diagFindingLowDiskDesc"
| "diagFindingLowDiskTitle"
| "diagFindingLowMemoryDesc"
| "diagFindingLowMemoryTitle"
| "diagFindingWhpxUnavailableDesc"
| "diagFindingWhpxUnavailableTitle"
| "diagHighMemWarn"
| "diagIncludedFiles"
| "diagNoFindingsDesc"
| "diagNoFindingsTitle"
| "diagRevealFile"
| "diagSummaryToggle"
| "discardSuspend"
| "discardSuspendConfirm"
| "discardSuspendDesc"
@@ -293,6 +362,7 @@ export type I18nKey =
| "factMemory"
| "failAttachInstaller"
| "failCloneVM"
| "failCopyDiagnosticsFile"
| "failCreate"
| "failDelete"
| "failDiscardSuspend"
@@ -309,6 +379,7 @@ export type I18nKey =
| "failGeneric"
| "failGuestTools"
| "failOpenFolder"
| "failProvision"
| "failRestart"
| "failResume"
| "failRuntime"
@@ -587,6 +658,7 @@ export type I18nKey =
| "imagesSourcesLabel"
| "importRuntime"
| "installersAvailable"
| "installersCacheUnavailable"
| "installersCreateVM"
| "installersDelete"
| "installersDeleteConfirm"
@@ -622,7 +694,11 @@ export type I18nKey =
| "logActivity"
| "logButton"
| "logCopy"
| "logCopyAnyway"
| "logErrorsOnly"
| "logExportDiagnostics"
| "logLargeCopyDesc"
| "logLargeCopyTitle"
| "logLevel"
| "logLevelCustom"
| "logLevelDesc"
@@ -651,6 +727,24 @@ export type I18nKey =
| "memRecHint"
| "menuBar"
| "menuHelp"
| "menuMacCut"
| "menuMacDelete"
| "menuMacEdit"
| "menuMacFullScreen"
| "menuMacHide"
| "menuMacHideOthers"
| "menuMacPaste"
| "menuMacPasteMatchStyle"
| "menuMacQuit"
| "menuMacRedo"
| "menuMacSelectAll"
| "menuMacShowAll"
| "menuMacSpeech"
| "menuMacStartSpeaking"
| "menuMacStopSpeaking"
| "menuMacUndo"
| "menuMacWindow"
| "menuMacZoom"
| "menuVM"
| "menuView"
| "minimize"
@@ -845,12 +939,27 @@ export type I18nKey =
| "pluginTrustDev"
| "pluginTrustOfficial"
| "pluginTrustVerified"
| "provisionDesc"
| "provisionGroupTitle"
| "provisionInstallGuestTools"
| "provisionReadyNoticeDesc"
| "provisionReadyNoticeTitle"
| "provisionToggle"
| "qemuASLR"
| "qemuASLRHint"
| "quitFailed"
| "quitInProgress"
| "recommendedBadge"
| "refresh"
| "remoteControlActive"
| "remoteControlInputLocked"
| "remoteControlPause"
| "remoteControlPaused"
| "remoteControlPhaseAuth"
| "remoteControlPhaseAuthTimer"
| "remoteControlResume"
| "remoteControlStop"
| "remoteControlTakeoverCountdown"
| "resAuto"
| "resAutoSub"
| "resAutoValue"
@@ -996,6 +1105,11 @@ export type I18nKey =
| "srcAppleTitle"
| "srcDiskSub"
| "srcDiskTitle"
| "srcIPSWDownloadSub"
| "srcIPSWDownloadTitle"
| "srcIPSWLocalSub"
| "srcIPSWLocalTitle"
| "srcIPSWNone"
| "srcInstallerSub"
| "srcInstallerTitle"
| "srcOfflineSub"
@@ -1075,6 +1189,7 @@ export type I18nKey =
| "taskDownload"
| "taskPluginDownload"
| "taskRecoveryDownload"
| "taskRestoreVM"
| "taskRuntime"
| "tasksRunning"
| "techInfo"
@@ -1094,7 +1209,7 @@ export type I18nKey =
| "toastCreateCanceledPartial"
| "toastCreated"
| "toastDeleted"
| "toastDiagExported"
| "toastDiagFileCopied"
| "toastDiscardSuspend"
| "toastDownloadPaused"
| "toastEjected"
@@ -1194,6 +1309,8 @@ export type I18nKey =
| "wizOptions"
| "wizardBasics"
| "wizardDriverGroup"
| "wizardDriverListFailed"
| "wizardDriverType"
| "wizardNoDriver"
| "wizardTitle"
| "x86RuntimeLabel";
+36
View File
@@ -0,0 +1,36 @@
export interface AutoInstallDraftFields {
enabled: boolean
autoInstall: boolean
installGuestTools: boolean
fullName: string
accountName: string
password: string
appearance: 'auto' | 'light' | 'dark'
slaAccepted: boolean
saveUnlockCredential: boolean
}
export const defaultAutoInstallDraft = (): AutoInstallDraftFields => ({
enabled: false,
autoInstall: true,
installGuestTools: true,
fullName: 'Reims User',
accountName: 'reims',
password: '',
appearance: 'auto',
slaAccepted: false,
saveUnlockCredential: false,
})
const ASCII_PRINTABLE = /^[\x20-\x7E]+$/
const ACCOUNT_NAME_RE = /^[a-z][a-z0-9_-]{0,31}$/
export function validateAutoInstallDraft(d: AutoInstallDraftFields, requireSLA = d.enabled): boolean {
if (requireSLA && !d.slaAccepted) return false
if (!d.enabled) return true
if (!d.slaAccepted) return false
if (!d.fullName.trim() || !ASCII_PRINTABLE.test(d.fullName.trim())) return false
if (!ACCOUNT_NAME_RE.test(d.accountName.trim().toLowerCase())) return false
if (d.password.length < 4 || d.password.length > 256 || !ASCII_PRINTABLE.test(d.password)) return false
return true
}
+11 -2
View File
@@ -40,7 +40,7 @@ export function hasCap(caps: readonly string[] | null | undefined, capability: s
return !!caps && caps.includes(capability)
}
/** Hosted VMs are run by their driver: no process, window, PID or QMP socket on the host side. */
/** Hosted VMs are managed by their driver rather than a host-owned VM process. */
export function isHosted(caps: readonly string[] | null | undefined): boolean {
return hasCap(caps, 'hosted')
}
@@ -84,7 +84,7 @@ export function vmFeatures(vm?: { driver_id?: string; capabilities?: readonly st
screenshot: hasCap(caps, 'console') || (hasCap(caps, 'qmp') && !hosted),
sendText: hasCap(caps, 'console') || (hasCap(caps, 'qmp') && !hosted),
suspend: hasCap(caps, 'suspend'),
window: !hosted,
window: !hosted || hasCap(caps, 'window'),
}
}
@@ -150,6 +150,15 @@ export function splitEndpoints(endpoints: readonly VMEndpoint[] | null | undefin
return primaryIdx < 0 ? { rest } : { primary: list[primaryIdx], rest }
}
/** A display window takes precedence over remote access; shell-only drivers keep their endpoint shortcut. */
export function primaryVMAccess(features: VMFeatures, endpoints?: readonly VMEndpoint[] | null):
{ kind: 'window' } | { kind: 'endpoint'; endpoint: VMEndpoint } | undefined {
if (features.window) return { kind: 'window' }
if (!features.hosted) return
const { primary } = splitEndpoints(endpoints)
if (primary) return { kind: 'endpoint', endpoint: primary }
}
/** A stable React key for an endpoint row. */
export function endpointKey(ep: VMEndpoint): string {
return [ep.kind, ep.host ?? '', ep.port ?? '', ep.distro ?? '', ep.vm ?? '', ep.serial ?? ''].join('|')
+36
View File
@@ -0,0 +1,36 @@
import type { DriverSummary, HostReport, InstallerKind, SettingProperty } from '../types'
import { isMacOSDriver, STAMBHA_RUNTIME_KIND } from './endpoints'
type HostPlatform = Pick<HostReport, 'os' | 'arch'>
export function isAppleSilicon(host?: HostPlatform): boolean {
return host?.os === 'darwin' && host.arch === 'arm64'
}
export function needsRuntimeSetup(host: HostPlatform, hasRuntime: boolean): boolean {
return !isAppleSilicon(host) && !hasRuntime
}
export function eligibleGuestDrivers(drivers: DriverSummary[], hasRuntime: boolean, hasStambha = false): DriverSummary[] {
return drivers.filter((driver) => {
if (driver.runtime_kind === STAMBHA_RUNTIME_KIND) return hasStambha
return driver.runtime_kind === 'external' || hasRuntime
})
}
export function defaultGuestDriver(drivers: DriverSummary[], host: HostPlatform, installerKind?: InstallerKind): DriverSummary | undefined {
const legacy = drivers.find((driver) => isMacOSDriver(driver.id))
if (installerKind === 'ipsw') return drivers.find((driver) => !!restoreImageField(driver, host))
if (installerKind) return legacy
return isAppleSilicon(host) ? drivers[0] : legacy ?? drivers[0]
}
export function restoreImageField(driver: DriverSummary, host: HostPlatform): string | undefined {
if (!isAppleSilicon(host)) return undefined
return Object.entries(driver.create_schema?.properties ?? {}).find(([, prop]) => hasRestoreImagePicker(driver, prop))?.[0]
}
/** Only create schemas supplied by the host's trusted built-ins may request a restore picker. */
export function hasRestoreImagePicker(driver: DriverSummary, prop: SettingProperty): boolean {
return driver.builtin === true && prop.type === 'string' && prop['x-filePattern'] === '*.ipsw'
}
+44
View File
@@ -28,6 +28,50 @@ export function createLogLine(entry: LogEntry): LogLine {
return { ts, source, line, id: nextId++, level }
}
export const LARGE_LOG_LINE_THRESHOLD = 20
export const LARGE_LOG_CHAR_THRESHOLD = 2000
interface FormattableLogRow {
ts: string
source: string
line: string
}
function flattenLogMessage(line: string): string {
return line.replace(/^[\r\n]+|[\r\n]+$/g, '').replace(/[\r\n]+/g, ' ')
}
export function formatLogLine(line: FormattableLogRow): string {
return `${line.ts} [${line.source}] ${flattenLogMessage(line.line)}`
}
export function formatLogLines(lines: readonly FormattableLogRow[]): string {
return lines.map(formatLogLine).join('\n')
}
export function countLogLines(text: string): number {
if (!text) return 0
const normalized = text.replace(/\r\n?/g, '\n')
const trimmed = normalized.endsWith('\n') ? normalized.slice(0, -1) : normalized
if (!trimmed) return 0
return trimmed.split('\n').length
}
export function isLargeLogPayload(text: string): boolean {
if (!text) return false
return countLogLines(text) >= LARGE_LOG_LINE_THRESHOLD || text.length >= LARGE_LOG_CHAR_THRESHOLD
}
export function formatSelectedLogRows(rows: ReadonlyArray<{ ts: string; source: string; line: string }>): string {
return formatLogLines(
rows.map((row) => ({
ts: row.ts.trim(),
source: row.source.trim(),
line: row.line,
})),
)
}
export function appendLog(prev: LogLine[], line: LogLine): LogLine[] {
const next = [...prev, line]
return next.length > MAX_LOG_LINES ? next.slice(next.length - MAX_LOG_LINES) : next
+41
View File
@@ -0,0 +1,41 @@
import type { CachedInstaller, Release } from '../types'
interface RestoreImageChoice {
version: string
build: string
label: string
key: string
}
/** Offer the catalog release and all finished restore images for local reuse. */
export function restoreImageChoices(release: Release | undefined, cached: CachedInstaller[]): RestoreImageChoice[] {
const choices = new Map<string, RestoreImageChoice>()
const add = (title: string, version: string, build: string) => {
const key = restoreImageChoiceKey(version, build)
if (choices.has(key)) return
const label = title.includes(version) ? title : `${title} ${version}`
choices.set(key, { key, version, build, label: build ? `${label} (${build})` : label })
}
if (release) add(release.title, release.version, release.build)
for (const image of cached) {
if (image.kind !== 'ipsw' || image.partial || !image.path || !image.version) continue
add(image.title || 'macOS', image.version, image.build ?? '')
}
return [...choices.values()]
}
export function restoreImageChoiceKey(version: string, build: string): string {
return `${version}|${build}`
}
export function matchesRestoreImage(image: CachedInstaller, version: string, build: string): boolean {
return image.kind === 'ipsw' && image.version === version && (image.build ?? '') === build
}
export function cachedRestoreImage(cached: CachedInstaller[], version: string, build: string): CachedInstaller | undefined {
return cached.find((image) => !image.partial && !!image.path && matchesRestoreImage(image, version, build))
}
export function restoreImagePathMissing(cached: CachedInstaller[], version: string, build: string): boolean {
return cached.some((image) => !image.partial && !image.path && matchesRestoreImage(image, version, build))
}
+15 -4
View File
@@ -1,5 +1,6 @@
import { t } from '../i18n'
import { CachedInstaller, InstallerKind, InstallerPhase, Locale, Task } from '../types'
import { vmRefKey } from './vmRef'
// Match the finished-task retention period in internal/app/tasks.go.
export const finishedTaskTTL = 10 * 60 * 1000
@@ -40,12 +41,21 @@ export function creatingVMTasks(all: Record<string, Task>, existingNames: Readon
.sort((a, b) => a.started_at - b.started_at || a.subject.localeCompare(b.subject))
}
/** Match the driver-scoped VM key sent by the restore task emitter. */
export function findRunningRestoreTask(tasks: Task[], driverID: string, name: string): Task | undefined {
const driver_id = driverID.trim()
if (!driver_id || !name.trim()) return undefined
const key = vmRefKey({ driver_id, name: name.trim() })
return tasks.find((task) => task.kind === 'vm-restore' && task.status === 'running' && task.vm === key)
}
/** Localized title; the upstream step (English) goes in the tooltip. */
export function taskTitle(locale: Locale, task: Task): string {
switch (task.kind) {
case 'installer-download': return t(locale, 'taskDownload', { v: task.subject })
case 'recovery-download': return t(locale, 'taskRecoveryDownload', { name: task.subject })
case 'vm-create': return t(locale, 'taskCreate', { name: task.subject })
case 'vm-restore': return t(locale, 'taskRestoreVM', { name: task.subject })
case 'runtime-install': return t(locale, 'taskRuntime', { v: task.subject })
case 'app-update': return t(locale, 'taskAppUpdate', { v: task.subject })
case 'plugin-download': return t(locale, 'taskPluginDownload', { name: task.subject })
@@ -67,7 +77,7 @@ export function isInstallerTask(task: Task): boolean {
}
export function taskInstallerKind(task: Task): InstallerKind | '' {
if (task.installer_kind === 'offline' || task.installer_kind === 'online' || task.installer_kind === 'arm-ipsw') return task.installer_kind
if (task.installer_kind === 'offline' || task.installer_kind === 'online' || task.installer_kind === 'arm-ipsw' || task.installer_kind === 'ipsw') return task.installer_kind
if (task.kind === 'installer-download') return 'offline'
if (task.kind === 'recovery-download') return 'online'
return ''
@@ -112,6 +122,7 @@ function matchesCachedInstaller(item: CachedInstaller, task: Task): boolean {
const kind = taskInstallerKind(task)
if (!kind || kind !== item.kind) return false
const v = taskInstallerVersion(task).toLowerCase()
if (kind === 'ipsw') return !!v && item.version?.toLowerCase() === v
if (kind === 'offline') {
if (item.version && item.version.toLowerCase() === v) return true
return item.partial && !!v && !/^\d/.test(v) && matchesOnlineInstallerTitle(item.title, v)
@@ -151,11 +162,11 @@ function pickPrimaryInstallerTask(matches: Task[]): ActiveInstallerMatch | null
return { primary, waitingVMs, matchedIDs: sorted.map((x) => x.id) }
}
export function findActiveOfflineTask(tasks: Task[], version: string): ActiveInstallerMatch | null {
export function findActiveInstallerTask(tasks: Task[], kind: InstallerKind, version: string): ActiveInstallerMatch | null {
const want = version.trim().toLowerCase()
if (!want) return null
const matches = tasks.filter(
(x) => isActiveInstallerTask(x) && taskInstallerKind(x) === 'offline' && taskInstallerVersion(x).toLowerCase() === want,
(x) => isActiveInstallerTask(x) && taskInstallerKind(x) === kind && taskInstallerVersion(x).toLowerCase() === want,
)
return pickPrimaryInstallerTask(matches)
}
@@ -184,7 +195,7 @@ export function groupUnmatchedInstallerTasks(activeTasks: Task[], matchedTaskIDs
}
export function taskStopAction(locale: Locale, task: Task): { kind: 'pause' | 'cancel'; label: string } {
if (task.kind === 'vm-create') return { kind: 'cancel', label: t(locale, 'cancelCreate') }
if (task.kind === 'vm-create' || task.kind === 'vm-restore') return { kind: 'cancel', label: t(locale, 'cancelCreate') }
if (task.kind === 'app-update') return { kind: 'cancel', label: t(locale, 'updateCancel') }
if (taskInstallerPhase(task) === 'queued') return { kind: 'cancel', label: t(locale, 'cancelQueue') }
return { kind: 'pause', label: t(locale, 'pauseDownload') }
+134
View File
@@ -0,0 +1,134 @@
import { t } from '../i18n'
import type { Locale, VMAction } from '../types'
import { vmFeatures, type VMFeatures } from './endpoints'
import type { ThemeMode } from './useAppearance'
export const REPO_URL = 'https://github.com/Nwflower/Reims-Go'
export function siteURL(locale: Locale, path = ''): string {
const base = locale.toLowerCase().startsWith('zh') ? 'https://reims.dev' : 'https://reims.dev/en'
return path ? `${base}${path}` : base
}
export const MENU_IDS = ['vm', 'view', 'help'] as const
export type MenuId = (typeof MENU_IDS)[number]
export type MenuCommand = 'new' | 'vmSettings' | 'sidebar' | 'logs' | 'installers' | 'plugins' | 'host' | 'settings' |
'website' | 'docs' | 'project' | 'report' | 'update' | 'about' | `vm:${VMAction}` | `theme:${ThemeMode}`
export type MenuRow =
| { kind: 'separator' }
| { kind: 'label'; label: string }
| { kind: 'action' | 'check' | 'radio'; command: MenuCommand; label: string; disabled?: boolean; checked?: boolean; danger?: boolean; shortcut?: string; macKey?: string }
export interface TitleMenuState {
locale: Locale
sidebarOpen: boolean
logsOpen: boolean
themeMode: ThemeMode
canLight: boolean
canDark: boolean
vm: { name: string; driver_id?: string; state: string; busy: boolean; graphics?: string; canSuspend: boolean; features: VMFeatures } | null
fullscreenHotkey?: string
appVersion?: string
}
export interface TitleMenuProps extends TitleMenuState {
onToggleSidebar: () => void
onToggleLogs: () => void
onThemeMode: (mode: ThemeMode) => void
onNewVM: () => void
onVMAction: (action: VMAction) => void
onVMSettings: () => void
onVMDelete: () => void
onNavigate: (page: 'installers' | 'plugins' | 'host' | 'settings' | 'about') => void
onOpenURL: (url: string) => void
}
export function buildTitleMenus(state: TitleMenuState, fullscreen: boolean | undefined = undefined) {
const { vm, locale, appVersion, fullscreenHotkey, sidebarOpen, logsOpen, canLight, canDark, themeMode } = state
const tr = (key: Parameters<typeof t>[1]) => t(locale, key)
const running = vm?.state === 'running'
const stopped = vm?.state === 'stopped'
const suspended = vm?.state === 'suspended'
const transitioning = vm?.state === 'starting' || vm?.state === 'stopping' || vm?.state === 'suspending' || vm?.state === 'resuming'
const busy = !vm || vm.busy
const features = vm?.features ?? vmFeatures(null)
const canFullscreen = running && features.fullscreen && vm?.graphics !== 'vmware-svga'
const fullscreenLabel = !canFullscreen || fullscreen === undefined ? tr('toggleFullscreen') : fullscreen ? tr('exitFullscreen') : tr('enterFullscreen')
const sep = { kind: 'separator' } as const
const vmRows: MenuRow[] = [{ kind: 'action', command: 'new', label: tr('newVMEllipsis'), shortcut: 'Ctrl+N', macKey: 'n' }, sep]
if (running) {
if (features.window) vmRows.push({ kind: 'action', command: 'vm:focus', label: tr('showWindow'), shortcut: 'Ctrl+Enter', macKey: '\r', disabled: busy })
} else if (suspended) {
vmRows.push({ kind: 'action', command: 'vm:resume', label: tr('resume'), shortcut: vm.canSuspend ? 'Ctrl+Enter' : undefined, macKey: vm.canSuspend ? '\r' : undefined, disabled: busy || !vm.canSuspend })
if (!vm.canSuspend) vmRows.push({ kind: 'label', label: tr('resumeUnavailable') })
} else {
vmRows.push({ kind: 'action', command: 'vm:start', label: tr('start'), shortcut: 'Ctrl+Enter', macKey: '\r', disabled: busy || !stopped })
}
if (features.fullscreen) vmRows.push({ kind: 'action', command: 'vm:fullscreen', label: fullscreenLabel, shortcut: fullscreenHotkey, disabled: busy || !canFullscreen })
if (features.suspend) vmRows.push({ kind: 'action', command: 'vm:suspend', label: tr('suspend'), disabled: busy || !running || !vm?.canSuspend })
vmRows.push(
{ kind: 'action', command: 'vm:stop', label: tr('stop'), disabled: busy || !running },
{ kind: 'action', command: 'vm:restart', label: tr('restart'), disabled: busy || !running },
)
if (features.screenshot) vmRows.push({ kind: 'action', command: 'vm:screenshot', label: tr('copyScreenshot'), disabled: busy || !running })
if (features.macos) vmRows.push(sep,
{ kind: 'action', command: 'vmSettings', label: tr('settingsEllipsis'), shortcut: 'Ctrl+,', disabled: !vm || suspended || transitioning },
{ kind: 'action', command: 'vm:openFolder', label: tr('openFolder'), disabled: !vm },
)
vmRows.push(sep)
if (suspended) vmRows.push({ kind: 'action', command: 'vm:discardSuspend', label: tr('discardSuspend'), danger: true, disabled: busy })
vmRows.push(
{ kind: 'action', command: 'vm:forceStop', label: tr('forceStop'), danger: true, disabled: !vm || !(running || transitioning) },
{ kind: 'action', command: 'vm:delete', label: tr('deleteEllipsis'), danger: true, disabled: busy || running || suspended || transitioning },
)
const viewRows: MenuRow[] = [
{ kind: 'check', command: 'sidebar', label: tr('sidebarLabel'), checked: sidebarOpen, shortcut: 'Ctrl+B', macKey: 'b' },
{ kind: 'check', command: 'logs', label: tr('logButton'), checked: logsOpen, shortcut: 'Ctrl+L', macKey: 'l' },
sep,
{ kind: 'label', label: tr('appearance') },
...(['light', 'dark', 'system'] as const).map((mode): MenuRow => ({
kind: 'radio', command: `theme:${mode}`, checked: themeMode === mode,
label: tr(mode === 'light' ? 'themeLight' : mode === 'dark' ? 'themeDark' : 'themeSystem'),
disabled: mode === 'light' ? !canLight : mode === 'dark' ? !canDark : !canLight || !canDark,
})),
sep,
{ kind: 'action', command: 'installers', label: tr('sidebarInstallers') },
{ kind: 'action', command: 'plugins', label: tr('sidebarPlugins') },
{ kind: 'action', command: 'host', label: tr('sidebarHost') },
{ kind: 'action', command: 'settings', label: tr('sidebarSettings'), macKey: ',' },
]
const helpRows: MenuRow[] = [
{ kind: 'action', command: 'website', label: tr('helpWebsite') },
{ kind: 'action', command: 'docs', label: tr('helpDocs') },
{ kind: 'action', command: 'project', label: tr('helpProjectPage') },
{ kind: 'action', command: 'report', label: tr('helpReportIssue') },
{ kind: 'action', command: 'update', label: tr('helpCheckUpdate') },
{ kind: 'action', command: 'about', label: tr('helpAbout') },
]
if (appVersion) helpRows.push(sep, { kind: 'label', label: `Reims-Go ${appVersion}` })
return {
vm: { label: tr('menuVM'), rows: vmRows },
view: { label: tr('menuView'), rows: viewRows },
help: { label: tr('menuHelp'), rows: helpRows },
}
}
export function runMenuCommand(props: TitleMenuProps, command: MenuCommand): void {
switch (command) {
case 'new': return props.onNewVM()
case 'vmSettings': return props.onVMSettings()
case 'vm:delete': return props.onVMDelete()
case 'sidebar': return props.onToggleSidebar()
case 'logs': return props.onToggleLogs()
case 'installers': case 'plugins': case 'host': case 'settings': case 'about': return props.onNavigate(command)
case 'update': return props.onNavigate('about')
case 'website': return props.onOpenURL(siteURL(props.locale))
case 'docs': return props.onOpenURL(siteURL(props.locale, '/docs/quick-start'))
case 'project': return props.onOpenURL(REPO_URL)
case 'report': return props.onOpenURL(`${REPO_URL}/issues`)
}
if (command.startsWith('vm:')) props.onVMAction(command.slice(3) as VMAction)
else if (command.startsWith('theme:')) props.onThemeMode(command.slice(6) as ThemeMode)
}
+70
View File
@@ -0,0 +1,70 @@
import { useEffect, useLayoutEffect, useRef } from 'react'
import { hasVisibleDialog } from '../lib/dialogState'
import { runMenuCommand, type TitleMenuProps } from '../lib/titleMenu'
import { useVMStats } from '../lib/vmStats'
import { api, events } from '../wails'
import { buildNativeMenu, resolveMenuClick, type MenuClick, type NativeMenuState } from './applicationMenuModel'
// Use distinct tokens across snapshots, also across renderer reloads while
// the old native menu is still installed. A click must never be retargeted.
let nextToken = 1 + Math.floor(Math.random() * 0x20000000)
export function ApplicationMenu({ props, state, onReady }: {
props: TitleMenuProps
state: NativeMenuState
onReady: (ready: boolean) => void
}) {
const { vm } = props
const running = vm?.state === 'running'
const stats = useVMStats(vm?.driver_id ?? '', running && vm.features.fullscreen && vm.graphics !== 'vmware-svga' ? vm.name : null, running)
const model = buildNativeMenu(props, state, stats?.running ? stats.window_fullscreen : undefined)
const key = JSON.stringify([model.scope, model.groups, model.standard])
const latest = useRef({ ...model, props })
const installed = useRef(new Map<number, MenuClick>())
useLayoutEffect(() => { latest.current = { ...model, props } })
useEffect(() => events.onApplicationMenuCommand((token) => {
const entry = installed.current.get(token)
const current = latest.current
if (!entry || hasVisibleDialog()) return
const command = resolveMenuClick(entry, current.scope, current.commands)
if (command) runMenuCommand(current.props, command)
}), [])
useEffect(() => {
let canceled = false
let retry: number | undefined
const publish = (attempt: number) => {
const { groups, scope, standard } = latest.current
const active = new Map<number, MenuClick>()
const appGroups = groups.map((group) => ({
label: group.label,
rows: group.rows.map(({ command, ...row }) => {
if (!command) return row
const token = nextToken++
active.set(token, { scope, command })
return { ...row, token }
}),
}))
installed.current = active
api.SyncApplicationMenu(JSON.stringify({ groups: appGroups, standard })).then(() => {
if (!canceled) onReady(true)
}).catch((error) => {
if (canceled) return
if (attempt < 2) {
retry = window.setTimeout(() => publish(attempt + 1), 250)
return
}
installed.current.clear()
onReady(false)
console.warn('[app] Could not update the macOS application menu:', error)
})
}
publish(0)
return () => {
canceled = true
window.clearTimeout(retry)
}
}, [key, onReady])
return null
}
+44 -26
View File
@@ -3,12 +3,14 @@ import React, { useEffect, useRef, useState } from 'react'
import '../i18n/domains/settings.gen'
import '../i18n/domains/wizard.gen'
import { WordmarkLoader } from '../components/WordmarkLoader'
import { I18nKey, t } from '../i18n'
import { I18nKey, parseAppError, t } from '../i18n'
import { macOSMajor } from './macosRelease'
import { isAppleSilicon } from '../lib/guestDrivers'
import { matchesRestoreImage, restoreImagePathMissing } from '../lib/restoreImages'
import {
ActiveInstallerMatch,
findActiveCachedTask,
findActiveOfflineTask,
findActiveInstallerTask,
groupUnmatchedInstallerTasks,
isActiveInstallerTask,
isInstallerTask,
@@ -82,6 +84,7 @@ export const InstallersPage: React.FC<Props> = ({
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [cached, setCached] = useState<CachedInstaller[] | null>(null)
const [cacheError, setCacheError] = useState(false)
const [releases, setReleases] = useState<Release[] | null>(null)
const [releasesErr, setReleasesErr] = useState('')
const [confirmDelete, setConfirmDelete] = useState('')
@@ -89,20 +92,23 @@ export const InstallersPage: React.FC<Props> = ({
const onBusyChangeRef = useRef(onBusyChange)
onBusyChangeRef.current = onBusyChange
const installerTasks = tasks.filter(isInstallerTask)
const releaseKind = isAppleSilicon(host) ? 'ipsw' : 'offline'
const installerTasks = tasks.filter((task) => isInstallerTask(task) && (releaseKind === 'ipsw') === (taskInstallerKind(task) === 'ipsw'))
const activeInstallerTasks = installerTasks.filter(isActiveInstallerTask)
const installerTasksSig = installerTasks
.map((x) => `${x.id}:${x.status}:${x.installer_phase ?? ''}`)
.sort()
.join('|')
const loadCached = () => api.ListInstallers().then((l) => setCached(l ?? [])).catch((e) => onError(tr('failGeneric'), e))
const loadCached = () => api.ListInstallers()
.then((l) => { setCached(l ?? []); setCacheError(false) })
.catch((e) => { setCacheError(true); onError(tr('failGeneric'), e) })
const loadReleases = () => {
setReleases(null)
setReleasesErr('')
api.ListOfflineReleases()
.then((l) => setReleases(l ?? []))
.catch((e) => setReleasesErr(String(e).replace(/^Error:\s*/, '')))
.catch((e) => setReleasesErr(parseAppError(e).summary))
}
useEffect(() => { loadReleases() }, [])
useEffect(() => {
@@ -127,9 +133,13 @@ export const InstallersPage: React.FC<Props> = ({
api.OpenURL(APPLE_SLA_URL).catch((e) => onError(tr('failGeneric'), e))
}
const downloaded = (version: string) => (cached ?? []).find((c) => c.kind === 'offline' && !c.partial && c.version === version)
const partial = (version: string) => (cached ?? []).some((c) => c.kind === 'offline' && c.partial && c.version === version)
const activeForRelease = (version: string) => findActiveOfflineTask(activeInstallerTasks, version)
const matchesRelease = (item: CachedInstaller, r: Release) => releaseKind === 'ipsw'
? matchesRestoreImage(item, r.version, r.build)
: item.kind === 'offline' && item.version === r.version
const downloaded = (r: Release) => (cached ?? []).find((c) => matchesRelease(c, r) && !!c.path && !c.partial)
const partial = (r: Release) => (cached ?? []).find((c) => matchesRelease(c, r) && c.partial)
const missingRestorePath = (r: Release) => releaseKind === 'ipsw' && restoreImagePathMissing(cached ?? [], r.version, r.build)
const activeForRelease = (version: string) => findActiveInstallerTask(activeInstallerTasks, releaseKind, version)
const download = (version: string) => {
api.DownloadInstaller(version).catch((e) => onError(tr('failDownload'), e))
@@ -173,7 +183,10 @@ export const InstallersPage: React.FC<Props> = ({
)
}
const spaceShort = (r: Release) => !downloaded(r.version) && !activeForRelease(r.version) && host.free_disk_gb > 0 && host.free_disk_gb * 1e9 < needBytes(r)
const remainingGB = (r: Release) => releaseKind === 'ipsw'
? Math.max(0, r.size - (partial(r)?.bytes ?? 0)) / (2 ** 30)
: needBytes(r) / 1e9
const spaceShort = (r: Release) => !downloaded(r) && !missingRestorePath(r) && !activeForRelease(r.version) && host.free_disk_gb > 0 && host.free_disk_gb < remainingGB(r)
const releaseAction = (r: Release) => {
const active = activeForRelease(r.version)
@@ -194,7 +207,7 @@ export const InstallersPage: React.FC<Props> = ({
</span>
)
}
const item = downloaded(r.version)
const item = downloaded(r)
if (item) {
return (
<Button variant="primary" icon={<Plus size={14} />} onClick={() => onCreateWithInstaller(item)}>
@@ -202,22 +215,26 @@ export const InstallersPage: React.FC<Props> = ({
</Button>
)
}
if (missingRestorePath(r)) return <span className="warn-text" role="status">{tr('installersCacheUnavailable')}</span>
if (releaseKind === 'ipsw' && cacheError) return <Button onClick={loadCached}>{tr('installersRetry')}</Button>
return (
<Button icon={<Download size={14} />} disabled={spaceShort(r)} onClick={() => download(r.version)}>
{partial(r.version) ? tr('installersResume') : tr('installersDownload')}
<Button icon={<Download size={14} />} disabled={spaceShort(r) || (releaseKind === 'ipsw' && cached === null)} onClick={() => download(r.version)}>
{partial(r) ? tr('installersResume') : tr('installersDownload')}
</Button>
)
}
const releaseMeta = (r: Release) => (
<div className="row-sub">
{r.posted} · {gb(r.size)}
{spaceShort(r) && <span className="warn-text"> · {tr('installersNoSpace', { need: Math.ceil(needBytes(r) / 1e9), free: host.free_disk_gb.toFixed(0) })}</span>}
const releaseMeta = (r: Release) => {
const details = [r.posted, r.size > 0 ? gb(r.size) : ''].filter(Boolean).join(' · ')
if (!details) return null
return <div className="row-sub">
{details}
{spaceShort(r) && <span className="warn-text"> · {tr('installersNoSpace', { need: Math.ceil(remainingGB(r)), free: host.free_disk_gb.toFixed(0) })}</span>}
</div>
)
}
const matchedTaskIDs = new Set<string>()
const cachedRows: DownloadedRow[] = (cached ?? []).map((c) => {
const cachedRows: DownloadedRow[] = (cached ?? []).filter((item) => releaseKind !== 'ipsw' || item.kind === 'ipsw').map((c) => {
const active = findActiveCachedTask(activeInstallerTasks, c)
if (active) {
for (const id of active.matchedIDs) matchedTaskIDs.add(id)
@@ -236,13 +253,13 @@ export const InstallersPage: React.FC<Props> = ({
const task = active.primary
const kind = taskInstallerKind(task) || 'offline'
const version = taskInstallerVersion(task)
if (kind === 'offline') {
if (kind === 'offline' || kind === 'ipsw') {
const rel = (releases ?? []).find((r) => r.version.toLowerCase() === version.toLowerCase())
return {
key: `active-${taskInstallerKey(task) || task.id}`,
title: rel?.title ?? 'macOS',
version: rel?.version ?? version,
kind: 'offline',
kind,
active,
}
}
@@ -305,6 +322,7 @@ export const InstallersPage: React.FC<Props> = ({
<div className="row-title">
<span>{row.title}{row.version ? ` ${row.version}` : ''}</span>
{!task && c?.kind === 'offline' && !c.partial && <span className="badge rg-p-badge badge-ok">{tr('installersKindOffline')}</span>}
{!task && c?.kind === 'ipsw' && !c.partial && <span className="badge rg-p-badge badge-ok">IPSW</span>}
{(!task && c?.kind === 'online' && !c.partial) || (task && row.kind === 'online')
? <span className="badge rg-p-badge">{tr('installersKindOnline')}</span>
: null}
@@ -336,12 +354,12 @@ export const InstallersPage: React.FC<Props> = ({
/>
) : c ? (
<>
{!c.partial && (c.kind === 'offline' || c.kind === 'online') && (
<Button variant={c.kind === 'offline' ? 'primary' : 'secondary'} icon={<Plus size={14} />} onClick={() => onCreateWithInstaller(c)}>
{!c.partial && !!c.path && c.kind !== 'other' && (c.kind !== 'ipsw' || releaseKind === 'ipsw') && (
<Button variant={c.kind === 'online' ? 'secondary' : 'primary'} icon={<Plus size={14} />} onClick={() => onCreateWithInstaller(c)}>
{tr('installersCreateVM')}
</Button>
)}
{c.partial && c.kind === 'offline' && c.version && (
{c.partial && c.version && (c.kind === 'offline' || (c.kind === 'ipsw' && (releases ?? []).some((r) => matchesRelease(c, r)))) && (
<Button icon={<Download size={14} />} onClick={() => download(c.version!)}>{tr('installersResume')}</Button>
)}
{confirmDelete === c.name ? (
@@ -365,7 +383,7 @@ export const InstallersPage: React.FC<Props> = ({
<div className="notice notice-error" role="alert">
<span className="notice-main">
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
<span>{tr('offlineListFailedDetail', { err: releasesErr })}</span>
<span>{releaseKind === 'ipsw' ? releasesErr : tr('offlineListFailedDetail', { err: releasesErr })}</span>
</span>
<Button onClick={loadReleases}>{tr('installersRetry')}</Button>
</div>
@@ -386,7 +404,7 @@ export const InstallersPage: React.FC<Props> = ({
<span>{latest.title}</span>
<strong>{latest.version}</strong>
{groupIndex === 0 && <span className="badge rg-p-badge badge-accent">{tr('installersLatest')}</span>}
{downloaded(latest.version) && <Check size={15} className="ok-text" aria-label={tr('offlineCached')} />}
{downloaded(latest) && <Check size={15} className="ok-text" aria-label={tr('offlineCached')} />}
</div>
{releaseMeta(latest)}
</div>
@@ -405,7 +423,7 @@ export const InstallersPage: React.FC<Props> = ({
<div className="row-title">
<span>{r.version}</span>
<span className="muted">{r.build}</span>
{downloaded(r.version) && <span className="badge rg-p-badge badge-ok">{tr('offlineCached')}</span>}
{downloaded(r) && <span className="badge rg-p-badge badge-ok">{tr('offlineCached')}</span>}
</div>
{releaseMeta(r)}
</div>
@@ -0,0 +1,49 @@
import { t, type I18nKey } from '../i18n'
import { buildTitleMenus, MENU_IDS, type MenuCommand, type TitleMenuState } from '../lib/titleMenu'
// Match Wails’ standard items by action, not by their original English title.
const standardMenuKeys = {
edit: 'menuMacEdit', window: 'menuMacWindow', speech: 'menuMacSpeech',
About: 'helpAbout', Quit: 'menuMacQuit',
'hide:': 'menuMacHide', 'hideOtherApplications:': 'menuMacHideOthers', 'unhideAllApplications:': 'menuMacShowAll',
'undo:': 'menuMacUndo', 'redo:': 'menuMacRedo',
'cut:': 'menuMacCut', 'copy:': 'copy', 'paste:': 'menuMacPaste', 'pasteAsRichText:': 'menuMacPasteMatchStyle',
'delete:': 'menuMacDelete', 'selectAll:': 'menuMacSelectAll',
'startSpeaking:': 'menuMacStartSpeaking', 'stopSpeaking:': 'menuMacStopSpeaking',
'performMiniaturize:': 'minimize', 'performZoom:': 'menuMacZoom', 'enterFullScreenMode:': 'menuMacFullScreen',
} satisfies Record<string, I18nKey>
type NativeRow = { label?: string; command?: MenuCommand; checked?: boolean; key?: string }
export type MenuClick = { scope: string; command: MenuCommand }
export interface NativeMenuState {
workspaceReady: boolean
dialogOpen: boolean
selectedVMKey?: string
vmSettingsReady: boolean
}
export function buildNativeMenu(props: TitleMenuState, state: NativeMenuState, fullscreen?: boolean) {
const menus = buildTitleMenus(props, fullscreen)
const commands = new Set<MenuCommand>()
const groups = MENU_IDS.map((id) => ({
label: menus[id].label,
rows: menus[id].rows.map((row): NativeRow => {
if (row.kind === 'separator') return {}
if (row.kind === 'label') return { label: row.label }
const alwaysAvailable = row.command === 'website' || row.command === 'docs' || row.command === 'project' || row.command === 'report'
const enabled = !state.dialogOpen && (state.workspaceReady || alwaysAvailable) && !row.disabled
&& (row.command !== 'vmSettings' || state.vmSettingsReady)
if (enabled) commands.add(row.command)
return { label: row.label, command: enabled ? row.command : undefined, checked: row.checked, key: row.macKey }
}),
}))
const standard = Object.fromEntries(Object.entries(standardMenuKeys).map(([item, key]) => [item, t(props.locale, key)]))
return { groups, standard, commands, scope: state.selectedVMKey ?? '' }
}
export function resolveMenuClick(entry: MenuClick, scope: string, commands: ReadonlySet<MenuCommand>): MenuCommand | undefined {
if (!commands.has(entry.command)) return undefined
if ((entry.command.startsWith('vm:') || entry.command === 'vmSettings') && entry.scope !== scope) return undefined
return entry.command
}
+59 -1
View File
@@ -1645,7 +1645,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
/* Log filter controls */
.log-filter-input {
width: 148px; height: 24px; padding: 0 8px; flex-shrink: 0;
width: clamp(104px, 15vw, 148px); height: 24px; padding: 0 8px; flex-shrink: 0;
border-radius: var(--r-sm); border: 1px solid var(--border-strong);
background: var(--surface-input); color: var(--text); font: inherit; font-size: var(--fs-12);
}
@@ -1658,6 +1658,57 @@ button.status-issue + .status-metric { margin-left: 6px; }
}
.log-filter-pill:hover { color: var(--text); background: var(--surface-hover); }
.log-filter-pill[aria-pressed="true"] { background: var(--warn-soft); border-color: transparent; color: var(--warn-text); font-weight: var(--fw-medium); }
.btn.log-export-btn {
height: 24px; padding: 0 8px; gap: 5px; flex-shrink: 0; white-space: nowrap;
font-size: var(--fs-12); border-radius: var(--r-sm);
}
/* Diagnostics export guidance dialog */
.diag-findings { display: flex; flex-direction: column; gap: var(--sp-2); }
.diag-finding { align-items: flex-start; }
.diag-finding-details { color: var(--text-2); font-size: var(--fs-12); }
.diag-finding-details > summary { cursor: pointer; user-select: none; color: var(--text-2); }
.diag-finding-details pre {
padding: var(--sp-2); border-radius: var(--r-sm);
background: var(--surface-0); border: 1px solid var(--border);
font-family: var(--font-mono); font-size: var(--fs-11); line-height: 1.5;
color: var(--text-code); max-height: 120px; overflow: auto;
}
.diag-card {
background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-md);
padding: var(--sp-3) var(--sp-4); display: flex; flex-direction: column; gap: var(--sp-2);
}
.diag-card-title { font-size: var(--fs-13); font-weight: var(--fw-strong); color: var(--text); }
.diag-checklist {
margin: 0; padding-inline-start: 18px;
display: flex; flex-direction: column; gap: 6px;
font-size: var(--fs-13); color: var(--text-2); line-height: 1.5;
}
.diag-files-section {
display: flex; flex-direction: column; gap: 6px;
padding-top: var(--sp-2); border-top: 1px solid var(--border);
}
.diag-files-label { font-size: var(--fs-12); color: var(--text-3); }
.diag-files { display: flex; flex-wrap: wrap; gap: 6px; }
.diag-file-pill {
display: inline-flex; align-items: center;
padding: 2px 8px; border-radius: var(--r-sm);
background: var(--surface-0); border: 1px solid var(--border);
font-family: var(--font-mono); font-size: var(--fs-11); color: var(--text-2);
overflow-wrap: anywhere;
}
.diag-summary-details { font-size: var(--fs-12); color: var(--text-2); }
.diag-summary-details > summary {
cursor: pointer; user-select: none; font-weight: var(--fw-medium); color: var(--text-2);
}
.diag-summary-pre {
margin: var(--sp-2) 0 0; padding: var(--sp-3);
border-radius: var(--r-md); background: var(--surface-1); border: 1px solid var(--border);
font-family: var(--font-mono); font-size: var(--fs-11); line-height: 1.5;
color: var(--text-code); white-space: pre-wrap; overflow-wrap: anywhere;
max-height: 180px; overflow: auto;
}
.diag-foot-secondary { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); }
/* Storage breakdown bar (Engine page) */
.storage-bar {
@@ -2069,6 +2120,13 @@ button.status-issue + .status-metric { margin-left: 6px; }
cannot override them even with !important. */
@layer host-guard {
.rg-p-titlebar { --wails-draggable: drag !important; }
/* Match the native titlebar's centerline. The top padding balances the bottom border.
AppKit's controls occupy the physical left edge, even when the app is RTL. */
.rg-p-titlebar[data-native-titlebar] {
height: 32px !important;
padding-top: 1px !important;
padding-left: 96px !important;
}
:focus-visible:not(.dialog):not(.menu) { box-shadow: var(--focus-ring) !important; }
.icon-btn, .win-btn { min-width: 28px !important; min-height: 28px !important; }
/* Layers and decorations never take input, whatever a theme says. */
+4 -1
View File
@@ -11,7 +11,7 @@
// options, icon names and view locations in internal/plugin/contract.go, and a
// Go test keeps both in step.
export const UI_API_VERSION = '2.1.0' as const
export const UI_API_VERSION = '2.2.0' as const
export const UI_CONTRACT_PARTS = [
'rg-p-shell',
@@ -81,9 +81,11 @@ export const UI_CONTRACT_ITEM_STATES = [
'rg-p-nav-item:data-selected',
'rg-p-nav-item:data-busy',
'rg-p-nav-item:data-guest-family',
'rg-p-nav-item:data-remote-control',
'rg-p-vm-page:data-vm-state',
'rg-p-vm-page:data-driver',
'rg-p-vm-page:data-guest-family',
'rg-p-vm-page:data-remote-control',
'rg-p-button:data-variant',
'rg-p-button:data-busy',
'rg-p-icon-button:data-busy',
@@ -182,6 +184,7 @@ export const UI_CONTRACT_ICONS = [
'guest-windows',
'guest-android',
'remote-desktop',
'remote-control',
'terminal',
] as const
+87 -1
View File
@@ -12,6 +12,7 @@ export type Locale = BuiltinLocale | (string & {})
export type Config = Model<config.Config> & {
locale: Locale
runtime_channel?: 'stable' | 'alpha' | ''
agent_takeover_pause_sec?: number
}
export type DisplayInfo = host.DisplayInfo
@@ -39,6 +40,15 @@ export type HostReport = Omit<Model<host.Report>, 'gpus' | 'recommended_gpu'> &
recommended_gpu?: GPUInfo
}
export type DiagnosticFinding = Model<host.DiagnosticFinding> & {
code: 'gpu_device_lost' | 'gpu_vulkan_floor' | 'whpx_unavailable' | 'low_memory' | 'low_disk'
severity: 'error' | 'warn'
}
export type DiagnosticsExportResult = Omit<Model<app.DiagnosticsExportResult>, 'findings'> & {
findings: DiagnosticFinding[]
}
export type InstalledRuntime = Model<runtime.Installed>
export type RemoteRuntime = Model<runtime.Remote> & {
@@ -69,6 +79,80 @@ export type VMInfo = Omit<Model<driver.VMInfo>, 'guest_os' | 'phase' | 'endpoint
export type PendingChange = app.PendingChange
export interface AgentSessionView {
vm_key: string
driver_id: string
vm_name: string
plugin_id: string
plugin_name: string
label?: string
stage?: string
stage_label?: string
status?: string
message?: string
phase?: string
auth_until_phase_exit?: boolean
auth_remaining_sec?: number
takeover_policy?: string
input_locked?: boolean
paused_for_user?: boolean
takeover_paused?: boolean
takeover_manual_wait?: boolean
takeover_remaining_sec?: number
started_at: string
}
export interface AutoInstallerProviderView {
plugin_id: string
id: string
title: string
description?: string
guest_families: string[]
requires_offline_installer?: boolean
secret_setting: string
}
export interface AutoInstallStartRequest {
plugin_id?: string
driver_id?: string
vm_name: string
mode?: 'recovery_only' | 'full'
guest_lang?: string
full_name?: string
account_name?: string
password?: string
region?: string
appearance?: 'auto' | 'light' | 'dark'
age_range?: string
sla_accepted: boolean
save_unlock_credential?: boolean
install_guest_tools?: boolean
ocr_backend?: string
custom_ocr_mirror?: string
start_vm_if_stopped?: boolean
}
export interface ProvisionRequest {
full_name: string
account_name: string
password: string
appearance?: 'auto' | 'light' | 'dark'
sla_accepted: boolean
install_guest_tools?: boolean
}
export interface AutoInstallStatus {
vm: string
stage?: string
stage_label?: string
status?: string
message?: string
pause_reason?: string
unknown_page_summary?: string
matched_rules?: string[]
finish_install_done?: boolean
}
export type AppState = Omit<Model<app.AppState>, 'config' | 'host' | 'optimizations' | 'runtimes' | 'active_runtime' | 'vms'> & {
config: Config
host: HostReport
@@ -77,6 +161,8 @@ export type AppState = Omit<Model<app.AppState>, 'config' | 'host' | 'optimizati
active_runtime?: InstalledRuntime
vms: VMListItem[] | null
vm_list_error?: string
agent_sessions?: AgentSessionView[]
provision_ready_vms?: string[]
}
export type AppUpdateInfo = version.UpdateInfo
@@ -126,7 +212,7 @@ export type CreateOpts = Model<reims.CreateOpts> & {
type TaskStatus = 'running' | 'done' | 'failed' | 'canceled'
export type InstallerKind = 'offline' | 'online' | 'arm-ipsw'
export type InstallerKind = 'offline' | 'online' | 'arm-ipsw' | 'ipsw'
export type InstallerPhase = 'queued' | 'downloading'
/** A tracked long-running job pushed as "reims:task" (internal/app/tasks.go). */
+47 -2
View File
@@ -15,8 +15,8 @@ import {
WindowToggleMaximise as RawWindowToggleMaximise,
} from '../wailsjs/runtime/runtime'
import type {
ActiveThemePayload, AppState, CachedInstaller, DataRootChoice, DriverSummary,
LogEntry, MarketBrowseResult, PluginInfo, PluginUIContributions, RemoteRuntime,
ActiveThemePayload, AppState, AutoInstallerProviderView, AutoInstallStartRequest, AutoInstallStatus, CachedInstaller, DataRootChoice, DiagnosticsExportResult, DriverSummary,
LogEntry, MarketBrowseResult, PluginInfo, PluginUIContributions, ProvisionRequest, RemoteRuntime,
ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMInfo, VMNetworkSettings, VMNetworkPlan,
} from './types'
@@ -148,6 +148,7 @@ function eventsEmit(eventName: string, ...args: unknown[]): void {
export const api = {
...boundGo,
ExportDiagnostics: boundGo.ExportDiagnostics as (driverID: string, name: string) => Promise<DiagnosticsExportResult>,
GetVMNetworkSettings: boundGo.GetVMNetworkSettings as (name: string) => Promise<VMNetworkSettings>,
GetVMNetworkPlan: boundGo.GetVMNetworkPlan as (name: string, mode: string, uplink: string) => Promise<VMNetworkPlan>,
ListNetworkAdapters: boundGo.ListNetworkAdapters as () => Promise<VMNetworkSettings['adapters']>,
@@ -171,6 +172,46 @@ export const api = {
GetPluginUIContributions: boundGo.GetPluginUIContributions as () => Promise<PluginUIContributions>,
GetActiveTheme: boundGo.GetActiveTheme as () => Promise<ActiveThemePayload>,
ListDrivers: boundGo.ListDrivers as () => Promise<DriverSummary[] | null>,
ResolveConfirmRequest: boundGo.ResolveConfirmRequest as (id: string, approved: boolean, durationMinutes: number, untilPhaseExit: boolean) => Promise<void>,
PauseAgentSession: boundGo.PauseAgentSession as (driverID: string, name: string) => Promise<void>,
ResumeAgentSession: boundGo.ResumeAgentSession as (driverID: string, name: string) => Promise<void>,
StopAgentSession: boundGo.StopAgentSession as (driverID: string, name: string) => Promise<void>,
SetAgentTakeoverPauseSec: boundGo.SetAgentTakeoverPauseSec as (seconds: number) => Promise<void>,
ListAutoInstallers: boundGo.ListAutoInstallers as (guestFamily: string) => Promise<AutoInstallerProviderView[] | null>,
PreflightAutoInstall: boundGo.PreflightAutoInstall as (pluginID: string, driverID: string, vmName: string, guestLang: string) => Promise<Record<string, unknown>>,
StartAutoInstall: boundGo.StartAutoInstall as (req: AutoInstallStartRequest) => Promise<Record<string, unknown>>,
GetAutoInstallStatus: boundGo.GetAutoInstallStatus as (pluginID: string, driverID: string, vmName: string) => Promise<AutoInstallStatus>,
ResumeAutoInstall: boundGo.ResumeAutoInstall as (pluginID: string, driverID: string, vmName: string) => Promise<AutoInstallStatus>,
StopAutoInstall: boundGo.StopAutoInstall as (pluginID: string, driverID: string, vmName: string) => Promise<void>,
GetAutoInstallDiagnosticSummary: boundGo.GetAutoInstallDiagnosticSummary as (pluginID: string, driverID: string, vmName: string) => Promise<Record<string, unknown>>,
DownloadAutoInstallOCR: boundGo.DownloadAutoInstallOCR as (pluginID: string, customMirror: string) => Promise<Record<string, unknown>>,
PrepareVMProvision: boundGo.PrepareVMProvision as (name: string, req: ProvisionRequest) => Promise<void>,
}
export interface ConfirmPrompt {
id: string
kind: 'generic' | 'protected_phase' | 'custom_mirror' | string
plugin_id: string
plugin_name: string
publisher?: string
trust?: string
vm?: string
vm_name?: string
phase?: string
title: string
message: string
confirm_label?: string
cancel_label?: string
danger?: boolean
allow_duration_choice?: boolean
default_duration_minutes?: number
prefer_until_phase_exit?: boolean
origin?: string
}
export interface ConfirmResolvedEvent {
id: string
reason?: string
}
export interface MarketInstallProgress {
@@ -198,6 +239,7 @@ export const events = {
onHostDropAck: (cb: (payload: { vm: string; drop_id: string; status: string; target_kind?: string; target_label?: string; placed_names?: string[]; error?: string }) => void) => eventsOn('reims:host-drop-ack', cb),
onTask: (cb: (task: Task) => void) => eventsOn('reims:task', cb),
onStateChanged: (cb: () => void) => eventsOn('reims:state-changed', cb),
onApplicationMenuCommand: (cb: (token: number) => void) => eventsOn('reims:application-menu-command', cb),
onLog: (cb: (entry: LogEntry) => void) => eventsOn('reims:log', cb),
onRuntimeWarning: (cb: (message: string) => void) => eventsOn('reims:runtime-warning', cb),
// Market install progress (internal/app/plugins_flow.go InstallMarketPlugin).
@@ -211,6 +253,9 @@ export const events = {
// Controlled elevation request from a guest driver plugin (internal/app/elevate_flow.go).
onElevateRequest: (cb: (req: ElevationPrompt) => void) => eventsOn('reims:elevate-request', cb),
onElevateResolved: (cb: (id: string) => void) => eventsOn('reims:elevate-resolved', cb),
// #105 protected-phase, host/ui.confirm, and custom mirror confirmation prompts.
onConfirmRequest: (cb: (req: ConfirmPrompt) => void) => eventsOn('reims:confirm-request', cb),
onConfirmResolved: (cb: (ev: ConfirmResolvedEvent | string) => void) => eventsOn('reims:confirm-resolved', cb),
// Renderer health watchdog & crash reporting (internal/app/ui_health.go).
onUIPing: (cb: () => void) => eventsOn('reims:ui-ping', cb),
emitUIPong: () => eventsEmit('reims:ui-pong'),
+4 -1
View File
@@ -1,5 +1,5 @@
{
"uiApi": "2.1.0",
"uiApi": "2.2.0",
"parts": [
"rg-p-shell",
"rg-p-titlebar",
@@ -57,9 +57,11 @@
"rg-p-nav-item:data-selected",
"rg-p-nav-item:data-busy",
"rg-p-nav-item:data-guest-family",
"rg-p-nav-item:data-remote-control",
"rg-p-vm-page:data-vm-state",
"rg-p-vm-page:data-driver",
"rg-p-vm-page:data-guest-family",
"rg-p-vm-page:data-remote-control",
"rg-p-button:data-variant",
"rg-p-button:data-busy",
"rg-p-icon-button:data-busy",
@@ -130,6 +132,7 @@
"guest-windows",
"guest-android",
"remote-desktop",
"remote-control",
"terminal"
],
"viewLocations": [
+35 -1
View File
@@ -40,6 +40,8 @@ export function CompactVMDisk(arg1:string,arg2:string):Promise<driver.DiskCompac
export function CompleteSetup(arg1:string):Promise<void>;
export function CopyDiagnosticsFile(arg1:string):Promise<void>;
export function CopyVMScreenshot(arg1:string,arg2:string):Promise<void>;
export function CreateSnapshot(arg1:string,arg2:string,arg3:string):Promise<void>;
@@ -80,7 +82,7 @@ export function EnablePlugin(arg1:string,arg2:boolean):Promise<void>;
export function EnterRecovery(arg1:string):Promise<void>;
export function ExportDiagnostics(arg1:string,arg2:string):Promise<string>;
export function ExportDiagnostics(arg1:string,arg2:string):Promise<app.DiagnosticsExportResult>;
export function FinishInstall(arg1:string):Promise<void>;
@@ -232,12 +234,42 @@ export function ResizeVMDisk(arg1:string,arg2:string,arg3:string):Promise<driver
export function ResolveElevationRequest(arg1:string,arg2:boolean):Promise<void>;
export function ResolveConfirmRequest(arg1:string,arg2:boolean,arg3:number,arg4:boolean):Promise<void>;
export function PauseAgentSession(arg1:string,arg2:string):Promise<void>;
export function ResumeAgentSession(arg1:string,arg2:string):Promise<void>;
export function StopAgentSession(arg1:string,arg2:string):Promise<void>;
export function SetAgentTakeoverPauseSec(arg1:number):Promise<void>;
export function ListAutoInstallers(arg1:string):Promise<Array<any>>;
export function PreflightAutoInstall(arg1:string,arg2:string,arg3:string,arg4:string):Promise<Record<string,any>>;
export function StartAutoInstall(arg1:Record<string,any>):Promise<Record<string,any>>;
export function GetAutoInstallStatus(arg1:string,arg2:string,arg3:string):Promise<Record<string,any>>;
export function ResumeAutoInstall(arg1:string,arg2:string,arg3:string):Promise<Record<string,any>>;
export function StopAutoInstall(arg1:string,arg2:string,arg3:string):Promise<void>;
export function GetAutoInstallDiagnosticSummary(arg1:string,arg2:string,arg3:string):Promise<Record<string,any>>;
export function DownloadAutoInstallOCR(arg1:string,arg2:string):Promise<Record<string,any>>;
export function PrepareVMProvision(arg1:string,arg2:any):Promise<void>;
export function RestartVM(arg1:string,arg2:string):Promise<void>;
export function RestoreSnapshot(arg1:string,arg2:string,arg3:string):Promise<void>;
export function ResumeVM(arg1:string,arg2:string):Promise<void>;
export function RevealDiagnosticsFile(arg1:string):Promise<void>;
export function SaveCustomThemeScheme(arg1:plugin.CustomThemeScheme):Promise<void>;
export function ScanInstalledPlugin(arg1:string):Promise<plugin.ScanReport>;
@@ -296,6 +328,8 @@ export function SuggestLanguagePack():Promise<plugin.MarketCatalogItem>;
export function SuspendVM(arg1:string,arg2:string):Promise<void>;
export function SyncApplicationMenu(arg1:string):Promise<void>;
export function TestHostDNS(arg1:guesttools.HostDNSConfig):Promise<guesttools.HostDNSTestResult>;
export function ToggleVMFullscreen(arg1:string,arg2:string):Promise<boolean>;
+68
View File
@@ -58,6 +58,10 @@ export function CompleteSetup(arg1) {
return window['go']['app']['App']['CompleteSetup'](arg1);
}
export function CopyDiagnosticsFile(arg1) {
return window['go']['app']['App']['CopyDiagnosticsFile'](arg1);
}
export function CopyVMScreenshot(arg1, arg2) {
return window['go']['app']['App']['CopyVMScreenshot'](arg1, arg2);
}
@@ -454,6 +458,10 @@ export function ResumeVM(arg1, arg2) {
return window['go']['app']['App']['ResumeVM'](arg1, arg2);
}
export function RevealDiagnosticsFile(arg1) {
return window['go']['app']['App']['RevealDiagnosticsFile'](arg1);
}
export function SaveCustomThemeScheme(arg1) {
return window['go']['app']['App']['SaveCustomThemeScheme'](arg1);
}
@@ -570,6 +578,10 @@ export function SuspendVM(arg1, arg2) {
return window['go']['app']['App']['SuspendVM'](arg1, arg2);
}
export function SyncApplicationMenu(arg1) {
return window['go']['app']['App']['SyncApplicationMenu'](arg1);
}
export function TestHostDNS(arg1) {
return window['go']['app']['App']['TestHostDNS'](arg1);
}
@@ -605,3 +617,59 @@ export function ValidateSet(arg1) {
export function WriteSSHConfig(arg1, arg2, arg3) {
return window['go']['app']['App']['WriteSSHConfig'](arg1, arg2, arg3);
}
export function ResolveConfirmRequest(arg1, arg2, arg3, arg4) {
return window['go']['app']['App']['ResolveConfirmRequest'](arg1, arg2, arg3, arg4);
}
export function PauseAgentSession(arg1, arg2) {
return window['go']['app']['App']['PauseAgentSession'](arg1, arg2);
}
export function ResumeAgentSession(arg1, arg2) {
return window['go']['app']['App']['ResumeAgentSession'](arg1, arg2);
}
export function StopAgentSession(arg1, arg2) {
return window['go']['app']['App']['StopAgentSession'](arg1, arg2);
}
export function SetAgentTakeoverPauseSec(arg1) {
return window['go']['app']['App']['SetAgentTakeoverPauseSec'](arg1);
}
export function ListAutoInstallers(arg1) {
return window['go']['app']['App']['ListAutoInstallers'](arg1);
}
export function PreflightAutoInstall(arg1, arg2, arg3, arg4) {
return window['go']['app']['App']['PreflightAutoInstall'](arg1, arg2, arg3, arg4);
}
export function StartAutoInstall(arg1) {
return window['go']['app']['App']['StartAutoInstall'](arg1);
}
export function GetAutoInstallStatus(arg1, arg2, arg3) {
return window['go']['app']['App']['GetAutoInstallStatus'](arg1, arg2, arg3);
}
export function ResumeAutoInstall(arg1, arg2, arg3) {
return window['go']['app']['App']['ResumeAutoInstall'](arg1, arg2, arg3);
}
export function StopAutoInstall(arg1, arg2, arg3) {
return window['go']['app']['App']['StopAutoInstall'](arg1, arg2, arg3);
}
export function GetAutoInstallDiagnosticSummary(arg1, arg2, arg3) {
return window['go']['app']['App']['GetAutoInstallDiagnosticSummary'](arg1, arg2, arg3);
}
export function DownloadAutoInstallOCR(arg1, arg2) {
return window['go']['app']['App']['DownloadAutoInstallOCR'](arg1, arg2);
}
export function PrepareVMProvision(arg1, arg2) {
return window['go']['app']['App']['PrepareVMProvision'](arg1, arg2);
}
+80
View File
@@ -118,6 +118,50 @@ export namespace app {
this.recommended = source["recommended"];
}
}
export class DiagnosticsExportResult {
path: string;
file_name: string;
size_bytes: number;
target_label: string;
included_files: string[];
summary_text: string;
findings: host.DiagnosticFinding[];
can_copy_file: boolean;
static createFrom(source: any = {}) {
return new DiagnosticsExportResult(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.path = source["path"];
this.file_name = source["file_name"];
this.size_bytes = source["size_bytes"];
this.target_label = source["target_label"];
this.included_files = source["included_files"];
this.summary_text = source["summary_text"];
this.findings = this.convertValues(source["findings"], host.DiagnosticFinding);
this.can_copy_file = source["can_copy_file"];
}
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 DriveShareInfo {
drive: string;
root: string;
@@ -1188,6 +1232,22 @@ export namespace host {
this.broken = source["broken"];
}
}
export class DiagnosticFinding {
code: string;
severity: string;
detail?: string;
static createFrom(source: any = {}) {
return new DiagnosticFinding(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.code = source["code"];
this.severity = source["severity"];
this.detail = source["detail"];
}
}
export class DisplayInfo {
name?: string;
friendly_name?: string;
@@ -1344,7 +1404,22 @@ export namespace host {
this.nested_virt_probe_error = source["nested_virt_probe_error"];
}
}
export class AppleVirtualizationStatus {
ready: boolean;
detail?: string;
static createFrom(source: any = {}) {
return new AppleVirtualizationStatus(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.ready = source["ready"];
this.detail = source["detail"];
}
}
export class Report {
apple_virtualization?: AppleVirtualizationStatus;
defender_realtime_active?: boolean;
os: string;
arch: string;
@@ -1366,6 +1441,7 @@ export namespace host {
total_ram_gb: number;
avail_ram_gb: number;
memory_load_pct: number;
memory_usage_known?: boolean;
memory_spec?: HostMemorySpec;
commit_avail_gb: number;
commit_limit_gb: number;
@@ -1399,6 +1475,7 @@ export namespace host {
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.apple_virtualization = this.convertValues(source["apple_virtualization"], AppleVirtualizationStatus);
this.defender_realtime_active = source["defender_realtime_active"];
this.os = source["os"];
this.arch = source["arch"];
@@ -1420,6 +1497,7 @@ export namespace host {
this.total_ram_gb = source["total_ram_gb"];
this.avail_ram_gb = source["avail_ram_gb"];
this.memory_load_pct = source["memory_load_pct"];
this.memory_usage_known = source["memory_usage_known"];
this.memory_spec = this.convertValues(source["memory_spec"], HostMemorySpec);
this.commit_avail_gb = source["commit_avail_gb"];
this.commit_limit_gb = source["commit_limit_gb"];
@@ -2341,6 +2419,7 @@ export namespace plugin {
}
export class SettingProperty {
type: string;
"x-filePattern"?: string;
title: LocalizedText;
description?: LocalizedText;
default?: any;
@@ -2361,6 +2440,7 @@ export namespace plugin {
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.type = source["type"];
this["x-filePattern"] = source["x-filePattern"];
this.title = this.convertValues(source["title"], LocalizedText);
this.description = this.convertValues(source["description"], LocalizedText);
this.default = source["default"];
File diff suppressed because it is too large. Load diff
+246
View File
@@ -0,0 +1,246 @@
package app
import (
"context"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
)
func TestFormatSessionStageAndOverlayStep(t *testing.T) {
cases := []struct {
loc i18n.Locale
raw string
want string
}{
{i18n.ZhCN, "stage0_preflight", "环境准备"},
{i18n.ZhCN, "stage1_boot_recovery", "步骤 1 · 进入恢复环境"},
{i18n.ZhCN, "stage2a_offline_terminal", "步骤 2 · 运行离线安装脚本"},
{i18n.ZhCN, "stage2_disk_utility", "步骤 2 · 磁盘工具抹盘"},
{i18n.ZhCN, "stage3_install_wait", "步骤 3 · 等待系统安装"},
{i18n.ZhCN, "stage3_reinstall_macos", "步骤 3 · 安装 macOS"},
{i18n.ZhCN, "stage3_wait_reboot", "步骤 3 · 等待系统重启"},
{i18n.ZhCN, "stage4_finish_install", "步骤 4 · 退出恢复并重启"},
{i18n.ZhCN, "stage4_setup_assistant", "步骤 4 · 完成设置助理"},
{i18n.ZhCN, "stage5_wait_reboot", "步骤 5 · 等待系统重启"},
{i18n.ZhCN, "stage5_guest_tools", "步骤 5 · 安装 Guest Tools"},
{i18n.ZhCN, "正在抹掉 APFS 磁盘", "正在抹掉 APFS 磁盘"},
{i18n.EnUS, "stage0_preflight", "Preflight check"},
{i18n.EnUS, "stage1_boot_recovery", "Step 1 · Boot into Recovery"},
{i18n.EnUS, "stage2a_offline_terminal", "Step 2 · Run offline installer"},
{i18n.EnUS, "stage3_install_wait", "Step 3 · Wait for macOS install"},
{i18n.EnUS, "stage3_wait_reboot", "Step 3 · Waiting for reboot"},
{i18n.EnUS, "stage4_finish_install", "Step 4 · Exit recovery and restart"},
{i18n.EnUS, "Step 2/5: Formatting volume", "Step 2/5: Formatting volume"},
}
for _, tc := range cases {
if got := formatSessionStage(tc.loc, tc.raw); got != tc.want {
t.Errorf("formatSessionStage(%s, %q) = %q, want %q", tc.loc, tc.raw, got, tc.want)
}
}
a := &App{}
view := AgentSessionView{
Stage: "stage2_disk_utility",
Message: "正在抹掉磁盘",
InputLocked: true,
}
step := a.sessionOverlayStep(i18n.ZhCN, view)
if step != "步骤 2 · 磁盘工具抹盘" {
t.Fatalf("sessionOverlayStep = %q, want 步骤 2 · 磁盘工具抹盘", step)
}
status := a.sessionOverlayStatusLine(i18n.ZhCN, view, step)
if status != "画面已锁定防干扰 · 正在抹掉磁盘" {
t.Fatalf("sessionOverlayStatusLine = %q, want 画面已锁定防干扰 · 正在抹掉磁盘", status)
}
// Syncing autoinstall/status progress updates session stage & message without clobbering user pause.
vm := driver.VMInfo{DriverID: driver.BuiltinReimsMacOSDriverID, Name: "tahoe-step-test"}
key := vm.Ref().Key()
a.beginAgentSession(nil, "reims.autoinstall", vm, "macOS Auto-Install", "stage0_preflight", "lock", true)
a.syncAutoInstallSessionProgress(key, "reims.autoinstall", "stage2_disk_utility", "点击抹掉")
views := a.activeAgentSessions()
if len(views) != 1 || views[0].Stage != "stage2_disk_utility" || views[0].Message != "点击抹掉" {
t.Fatalf("syncAutoInstallSessionProgress did not update session: %+v", views)
}
if err := a.PauseAgentSession(vm.DriverID, vm.Name); err != nil {
t.Fatal(err)
}
a.syncAutoInstallSessionProgress(key, "reims.autoinstall", "stage2_disk_utility", "should not overwrite pause msg")
views = a.activeAgentSessions()
if views[0].Message == "should not overwrite pause msg" {
t.Fatalf("syncAutoInstallSessionProgress overwrote paused user message: %+v", views[0])
}
}
func TestAgentSessionLockPauseResumeAndWriteGuard(t *testing.T) {
a := &App{}
vm := driver.VMInfo{
DriverID: driver.BuiltinReimsMacOSDriverID,
Name: "tahoe-lock-test",
}
vmKey := vm.Ref().Key()
a.beginAgentSession(nil, "reims.autoinstall", vm, "macOS Auto-Install", "stage1_boot_recovery", "lock", true)
views := a.activeAgentSessions()
if len(views) != 1 {
t.Fatalf("ActiveAgentSessions len = %d, want 1", len(views))
}
if views[0].TakeoverPolicy != "lock" || !views[0].InputLocked || views[0].PausedForUser {
t.Fatalf("expected active locked session, got %+v", views[0])
}
if err := a.checkUserTakeover(vmKey, vm.Name); err != nil {
t.Fatalf("running locked session should allow plugin QMP writes, got %v", err)
}
// Pausing from HUD/UI must unlock VM input and reject any in-flight plugin QMP writes.
if err := a.PauseAgentSession(vm.DriverID, vm.Name); err != nil {
t.Fatalf("PauseAgentSession: %v", err)
}
views = a.activeAgentSessions()
if len(views) != 1 || !views[0].PausedForUser || views[0].InputLocked {
t.Fatalf("expected paused & unlocked session, got %+v", views)
}
if err := a.checkUserTakeover(vmKey, vm.Name); err == nil {
t.Fatal("paused session must block in-flight plugin QMP writes")
}
// Resuming must re-lock VM input and allow plugin QMP writes again.
if err := a.ResumeAgentSession(vm.DriverID, vm.Name); err != nil {
t.Fatalf("ResumeAgentSession: %v", err)
}
views = a.activeAgentSessions()
if len(views) != 1 || views[0].PausedForUser || !views[0].InputLocked {
t.Fatalf("expected resumed & re-locked session, got %+v", views)
}
if err := a.checkUserTakeover(vmKey, vm.Name); err != nil {
t.Fatalf("resumed session should allow plugin QMP writes again, got %v", err)
}
a.endAgentSession(nil, "reims.autoinstall", vmKey, "completed")
if got := len(a.activeAgentSessions()); got != 0 {
t.Fatalf("expected 0 active sessions after end, got %d", got)
}
}
func TestAgentSessionUnboundDiscoveryAndImmediatePIDBind(t *testing.T) {
a := &App{}
vm := driver.VMInfo{
DriverID: driver.BuiltinReimsMacOSDriverID,
Name: "tahoe-bind-test",
}
vmKey := vm.Ref().Key()
if a.hasActiveAgentSessions() || a.hasUnboundAgentSession() {
t.Fatal("idle app should report no active or unbound agent sessions")
}
// Starting a session before the VM PID is known marks it unbound so pollVMs uses fast discovery.
a.beginAgentSession(nil, "reims.autoinstall", vm, "macOS Auto-Install", "stage0_preflight", "lock", true)
if !a.hasActiveAgentSessions() || !a.hasUnboundAgentSession() {
t.Fatal("new session without live PID must be tracked as active & unbound")
}
// Binding a freshly observed live PID (e.g., from first screenshot/write or VM start) resolves it immediately.
a.bindAgentSessionPID(vmKey, 42424)
if a.hasUnboundAgentSession() {
t.Fatal("bindAgentSessionPID should clear unbound state immediately")
}
if !a.hasActiveAgentSessions() {
t.Fatal("session should remain active after PID binding")
}
// A rate-limited concurrent refresh (stale cache + probe skipped within 300ms)
// must NOT wipe the already-bound PID back to 0.
a.mu.Lock()
a.ctx = context.Background()
a.lastVMs = nil
a.lastVMsAt = time.Now()
a.mu.Unlock()
a.sessionMu.Lock()
a.agentSessions[vmKey].lastPIDProbeAt = time.Now()
a.sessionMu.Unlock()
a.refreshAgentSessionVisuals(vmKey)
if a.hasUnboundAgentSession() {
t.Fatal("rate-limited refresh clobbered bound lastOverlayPID back to 0")
}
a.closeAgentSessions()
}
func TestComputerUseLocaleResolvesAuto(t *testing.T) {
a := &App{cfg: &config.Config{Locale: i18n.Auto}}
got := a.computerUseLocale()
if got == "" || got == i18n.Auto {
t.Fatalf("computerUseLocale() for Auto = %q, want concrete resolved locale", got)
}
if want := i18n.EffectiveLocale(i18n.Auto); got != want {
t.Fatalf("computerUseLocale() = %q, want %q", got, want)
}
a.cfg.Locale = i18n.EnUS
if got := a.computerUseLocale(); got != i18n.EnUS {
t.Fatalf("computerUseLocale() for en-US = %q, want en-US", got)
}
}
func TestCompletedSessionRetainsCompletedOverlayAndUnlocksInput(t *testing.T) {
a := &App{cfg: &config.Config{Locale: i18n.ZhCN}}
vm := driver.VMInfo{
DriverID: driver.BuiltinReimsMacOSDriverID,
Name: "tahoe-recovery-done",
}
vmKey := vm.Ref().Key()
const pluginID = "builtin.macos.autoinstall"
a.grantEphemeralVMAccess(pluginID, vmKey)
a.grantProtectedPhase(pluginID, vmKey, driver.PhaseInstaller, 0, true)
a.beginAgentSession(nil, pluginID, vm, "macOS Auto-Install", "stage3_install_wait", "lock", true)
a.bindAgentSessionPID(vmKey, 31337)
// Mark completed (as runner.completeRecoveryOnly does right before EndSession).
a.sessionMu.Lock()
sess := a.agentSessions[vmKey]
sess.stage = "stage6_desktop_ready"
sess.status = "completed"
sess.message = "已完成恢复模式安装并进入 macOS,画面输入已解锁"
a.sessionMu.Unlock()
if step := a.sessionOverlayStep(i18n.ZhCN, a.activeAgentSessions()[0]); step != "已完成" {
t.Fatalf("sessionOverlayStep for completed = %q, want 已完成", step)
}
st := a.completedSessionOverlayState(i18n.ZhCN, sess, 31337, true)
if !st.Completed || st.InputLocked || st.CanPause || st.CanResume {
t.Fatalf("completed overlay state must unlock input and hide pause/resume: %+v", st)
}
if st.StepText != "已完成" || st.CloseLabel != "关闭" {
t.Fatalf("unexpected completed overlay labels: StepText=%q CloseLabel=%q", st.StepText, st.CloseLabel)
}
// Ending the completed session exits active control, revokes grants, and retains completed overlay tracking.
a.endAgentSession(nil, pluginID, vmKey, "session_ended")
if len(a.activeAgentSessions()) != 0 {
t.Fatal("completed session must not remain in ActiveAgentSessions")
}
if a.hasEphemeralVMAccess(pluginID, vmKey) {
t.Fatal("completed session must revoke ephemeral VM access")
}
if _, ok := a.lookupProtectedPhaseGrant(pluginID, vmKey); ok {
t.Fatal("completed session must revoke protected-phase grant")
}
if !a.isCompletedOverlay(vmKey) {
t.Fatal("expected completed overlay marker to remain active until dismissed or VM stops")
}
// Polling while VM is stopped cleans up the completed overlay automatically.
a.mu.Lock()
a.lastVMs = []driver.VMListItem{{DriverID: vm.DriverID, Name: vm.Name, State: "stopped"}}
a.lastVMsAt = time.Now()
a.mu.Unlock()
a.cleanupStaleCompletedOverlays()
if a.isCompletedOverlay(vmKey) {
t.Fatal("completed overlay marker should be cleared when VM stops")
}
}
+83 -17
View File
@@ -17,6 +17,7 @@ import (
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/host/sessionoverlay"
"github.com/Nwflower/reims-go/internal/i18n"
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/packetbridge"
@@ -48,18 +49,20 @@ type PendingChange struct {
}
type AppState struct {
QuitMode string `json:"quit_mode,omitempty"`
Config *config.Config `json:"config"`
Host host.Report `json:"host"`
Optimizations []host.Optimization `json:"optimizations"`
Runtimes []rt.Installed `json:"runtimes"`
ActiveRuntime *rt.Installed `json:"active_runtime,omitempty"`
CanSuspend bool `json:"can_suspend"`
VMs []driver.VMListItem `json:"vms"`
VMListError string `json:"vm_list_error,omitempty"`
Transitions map[string]string `json:"transitions"`
PendingChanges map[string][]PendingChange `json:"pending_changes"`
ActiveGuides []string `json:"active_guides,omitempty"`
QuitMode string `json:"quit_mode,omitempty"`
Config *config.Config `json:"config"`
Host host.Report `json:"host"`
Optimizations []host.Optimization `json:"optimizations"`
Runtimes []rt.Installed `json:"runtimes"`
ActiveRuntime *rt.Installed `json:"active_runtime,omitempty"`
CanSuspend bool `json:"can_suspend"`
VMs []driver.VMListItem `json:"vms"`
VMListError string `json:"vm_list_error,omitempty"`
Transitions map[string]string `json:"transitions"`
PendingChanges map[string][]PendingChange `json:"pending_changes"`
ActiveGuides []string `json:"active_guides,omitempty"`
AgentSessions []AgentSessionView `json:"agent_sessions,omitempty"`
ProvisionReadyVMs []string `json:"provision_ready_vms,omitempty"`
// InstallGuideEnabled reports whether the VM-window install guide service is active.
InstallGuideEnabled bool `json:"install_guide_enabled,omitempty"`
// NeedsSetup is true on first launch, until a data folder is chosen (setup.go).
@@ -144,6 +147,8 @@ type App struct {
lifecycleSvc *vmlifecycle.Service
runtimeKinds *rt.KindRegistry
uiHealth uiHealthState
appleVZProbeOnce sync.Once
appleVZProbe host.AppleVirtualizationStatus
themeMode string
vmClosePrompts sync.Map
displayHost vmDisplayHost
@@ -157,6 +162,33 @@ type App struct {
// Host-side plugin API service (computer-use, secrets, downloads, elevation, file grants).
hostAPI HostAPIService
// #105 host confirmation & protected-phase grants (confirm_flow.go).
confirmMu sync.Mutex
confirmPending map[string]chan ConfirmResolution
confirmSeq uint64
confirmEmit func(ConfirmPrompt)
confirmDismiss func(id, reason string)
protectedPhaseGrants map[phaseGrantKey]protectedPhaseGrant
protectedPhaseInFlight map[phaseGrantKey]bool
lastVMPhases map[string]string
// #103 Agent sessions, physical input takeover, and Win32 overlay (agent_session_flow.go).
sessionMu sync.Mutex
agentSessions map[string]*agentSession
completedOverlays map[string]completedOverlayEntry
ephemeralVMAccess map[string]map[string]bool
takeoverMon *host.TakeoverMonitor
sessionOverlay *sessionoverlay.Manager
sessionShuttingDown bool
// Install guide recheck & post-install handoff state (install_guide.go, guarded by mu).
guideRecheckVMs map[string]bool
pendingGuideHandoffs map[string]string
// Read-only VM runtime telemetry snapshots (vm_monitor.go / computer_use_host.go).
telemetryMu sync.Mutex
vmTelemetry map[string]*vmTelemetryState
}
// Lifecycle exposes Wails lifecycle callbacks without exporting them as
@@ -278,8 +310,8 @@ func (a *App) beforeClose(ctx context.Context) bool {
wailsRuntime.WindowHide(ctx)
return true
}
if tasks.hasRunningDownload() {
// Closing now would abort a download: ask first. The window's
if tasks.hasRunningDownload() || tasks.hasRunningRestore() {
// Closing now would abort a download or restore: ask first. The window's
// confirmation calls QuitApp, which lets the next close through.
a.emit("reims:confirm-close-downloads", true)
return true
@@ -294,6 +326,8 @@ func (a *App) shutdown(ctx context.Context) {
}
tasks.cancelAll()
a.cancelPendingElevations()
a.cancelPendingConfirmations()
a.closeAgentSessions()
stopAllVMMonitors()
a.stopPluginControlServer()
a.mu.Lock()
@@ -374,12 +408,13 @@ func (a *App) GetState() AppState {
a.mu.Unlock()
rep := host.Inspect(cfgCopy.DataRoot)
rep.AppleVirtualization = a.nativeVirtualizationStatus()
if needsSetup || rootStatus.ReadOnly {
rep.PendingHypervisorBoot = host.ReadPendingHypervisorBoot("", rep.WHPX)
}
runtimes, _ := rt.List(&cfgCopy)
active, _ := rt.ResolveActive(&cfgCopy)
// The poller's list (≤ polledMaxAge old, and invalidated by wakePoll after
// The poller's list (鈮?polledMaxAge old, and invalidated by wakePoll after
// start/stop/delete) instead of another `reims-ctl list` per refresh.
var vms []driver.VMListItem
var listError string
@@ -426,6 +461,8 @@ func (a *App) GetState() AppState {
Transitions: trCopy,
PendingChanges: pcCopy,
ActiveGuides: activeGuides,
AgentSessions: a.activeAgentSessions(),
ProvisionReadyVMs: a.provisionReadyVMKeys(),
InstallGuideEnabled: installGuideEnabled,
NeedsSetup: needsSetup,
DataRoot: rootStatus,
@@ -465,6 +502,19 @@ func (a *App) SetMinimizeToTray(enabled bool) error {
return a.setPreference(func(cfg *config.Config) { cfg.MinimizeToTray = &enabled })
}
// SetAgentTakeoverPauseSec updates how long Agent input pauses after physical
// keyboard/mouse takeover on a VM window (0 = pause until manual Resume).
func (a *App) SetAgentTakeoverPauseSec(seconds int) error {
if seconds < 0 {
seconds = 0
}
if seconds > 300 {
seconds = 300
}
v := seconds
return a.setPreference(func(cfg *config.Config) { cfg.AgentTakeoverPauseSec = &v })
}
// showMainWindow restores and focuses the Wails window from the system tray.
func (a *App) showMainWindow() {
if a.ctx == nil {
@@ -514,10 +564,16 @@ func (a *App) startTray() {
cached = vms
}
}
effLoc := i18n.EffectiveLocale(loc)
activeSessions := map[string]AgentSessionView{}
for _, s := range a.activeAgentSessions() {
activeSessions[s.VMKey] = s
}
items := make([]tray.VMItem, 0, len(cached))
for _, vm := range cached {
key := vmKeyForDriver(vm.DriverID, vm.Name)
state := vm.State
if t := transitions[vmKeyForDriver(vm.DriverID, vm.Name)]; t != "" {
if t := transitions[key]; t != "" {
state = t
}
// The display name is the VM's note, read straight from its
@@ -528,7 +584,13 @@ func (a *App) startTray() {
label = sanitizeVMNote(string(b))
}
}
items = append(items, tray.VMItem{DriverID: vm.DriverID, Name: vm.Name, Label: label, State: state})
item := tray.VMItem{DriverID: vm.DriverID, Name: vm.Name, Label: label, State: state}
if sess, ok := activeSessions[key]; ok {
item.HasRemoteControl = true
title, _ := a.sessionBannerText(effLoc, sess)
item.RemoteControlLabel = title
}
items = append(items, item)
}
return tray.Snapshot{
Locale: i18n.EffectiveLocale(loc),
@@ -589,6 +651,8 @@ func (a *App) trayVMAction(driverID, name string, act tray.Action) {
case tray.ActOpenInApp:
a.showMainWindow()
a.emit("reims:tray-select-vm", name)
case tray.ActStopRemoteControl:
err = a.StopAgentSession(driverID, name)
}
if err != nil {
a.emitVMLog(name, failTitle+": "+err.Error())
@@ -605,6 +669,8 @@ func (a *App) resetDataRootCaches() {
a.lastVMListErr = nil
a.diskPaths = make(map[string]cachedDiskPath)
a.procSamples = make(map[string]host.ProcessSample)
a.guideRecheckVMs = nil
a.pendingGuideHandoffs = nil
a.mu.Unlock()
a.hostAPISvc().ResetPluginFiles()
cancelPluginTasks("")
+72
View File
@@ -0,0 +1,72 @@
package app
import (
"encoding/json"
"errors"
"strings"
)
type applicationMenuSnapshot struct {
Groups []applicationMenuGroup `json:"groups"`
Standard map[string]string `json:"standard"`
}
type applicationMenuGroup struct {
Label string `json:"label"`
Rows []applicationMenuRow `json:"rows"`
}
type applicationMenuRow struct {
Label string `json:"label,omitempty"`
Key string `json:"key,omitempty"`
Token int32 `json:"token,omitempty"`
Checked bool `json:"checked,omitempty"`
}
func parseApplicationMenu(raw string) (applicationMenuSnapshot, error) {
var snapshot applicationMenuSnapshot
if err := json.Unmarshal([]byte(raw), &snapshot); err != nil || len(snapshot.Groups) != 3 {
return snapshot, errors.New("invalid application menu groups")
}
for _, key := range []string{"edit", "window", "speech", "hide:", "Quit"} {
if strings.TrimSpace(snapshot.Standard[key]) == "" {
return snapshot, errors.New("missing standard application menu labels")
}
}
tokens := make(map[int32]bool)
for _, group := range snapshot.Groups {
if strings.TrimSpace(group.Label) == "" || len(group.Rows) == 0 || len(group.Rows) > 40 {
return snapshot, errors.New("invalid application menu group")
}
for _, row := range group.Rows {
switch row.Key {
case "", "n", "b", "l", ",", "\r":
default:
return snapshot, errors.New("invalid application menu shortcut")
}
if row.Token < 0 || (row.Token > 0 && (row.Label == "" || tokens[row.Token])) {
return snapshot, errors.New("invalid application menu action")
}
if row.Token > 0 {
tokens[row.Token] = true
}
}
}
return snapshot, nil
}
// SyncApplicationMenu publishes the renderer's localized menu and current
// action availability to the host's native menu bar.
func (a *App) SyncApplicationMenu(raw string) error {
if a.ctx == nil {
return errors.New("application menu is not ready")
}
if len(raw) > 32<<10 {
return errors.New("application menu snapshot is too large")
}
snapshot, err := parseApplicationMenu(raw)
if err != nil {
return err
}
return a.syncApplicationMenu(snapshot)
}
+42
View File
@@ -0,0 +1,42 @@
//go:build darwin && cgo
package app
/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework AppKit
#include <stdlib.h>
int reimsSyncApplicationMenu(const char *snapshot);
*/
import "C"
import (
"encoding/json"
"errors"
"sync/atomic"
"unsafe"
)
var nativeMenuOwner atomic.Pointer[App]
func (a *App) syncApplicationMenu(menu applicationMenuSnapshot) error {
snapshot, err := json.Marshal(menu)
if err != nil {
return err
}
data := C.CString(string(snapshot))
defer C.free(unsafe.Pointer(data))
nativeMenuOwner.Store(a)
if C.reimsSyncApplicationMenu(data) == 0 {
return errors.New("macOS application menu is not ready")
}
return nil
}
//export reimsApplicationMenuClicked
func reimsApplicationMenuClicked(token C.int) {
if a := nativeMenuOwner.Load(); a != nil {
// Let AppKit finish handling the input before emitting back to WebKit.
go a.emit("reims:application-menu-command", int(token))
}
}
+120
View File
@@ -0,0 +1,120 @@
//go:build darwin && cgo
#import <AppKit/AppKit.h>
extern void reimsApplicationMenuClicked(int token);
@interface ReimsMenuTarget : NSObject
- (void)invoke:(NSMenuItem *)sender;
@end
@implementation ReimsMenuTarget
- (void)invoke:(NSMenuItem *)sender {
reimsApplicationMenuClicked((int)sender.tag);
}
@end
static ReimsMenuTarget *menuTarget;
static NSArray<NSMenuItem *> *managedItems;
static NSArray<NSMenuItem *> *standardItems;
static void setMenuTitle(NSMenuItem *item, NSString *title) {
if (title.length == 0) return;
item.title = title;
item.submenu.title = title;
}
static void localizeStandardItems(NSMenu *menu, NSDictionary<NSString *, NSString *> *labels) {
for (NSMenuItem *item in menu.itemArray) {
if (item.isSeparatorItem) continue;
if (item.hasSubmenu) {
// AppKit can also inject its own submenus, such as AutoFill.
// Only relabel the speech submenu created by Wails.
for (NSMenuItem *child in item.submenu.itemArray) {
if (child.action == @selector(startSpeaking:)) {
setMenuTitle(item, labels[@"speech"]);
localizeStandardItems(item.submenu, labels);
break;
}
}
} else if (item.action) {
NSString *action = NSStringFromSelector(item.action);
// Wails sends both Undo and Redo to undo:, with Shift for Redo.
if (item.action == @selector(undo:) && (item.keyEquivalentModifierMask & NSEventModifierFlagShift)) {
action = @"redo:";
}
setMenuTitle(item, labels[action]);
}
}
}
static NSMenu *buildMenu(NSDictionary *group) {
NSMenu *menu = [[[NSMenu alloc] initWithTitle:group[@"label"]] autorelease];
menu.autoenablesItems = NO;
for (NSDictionary *row in group[@"rows"]) {
if (!row[@"label"]) {
[menu addItem:[NSMenuItem separatorItem]];
continue;
}
NSInteger token = [row[@"token"] integerValue];
NSMenuItem *item = [[[NSMenuItem alloc] initWithTitle:row[@"label"]
action:token ? @selector(invoke:) : NULL
keyEquivalent:row[@"key"] ?: @""] autorelease];
item.keyEquivalentModifierMask = NSEventModifierFlagCommand;
item.tag = token;
item.target = menuTarget;
item.enabled = token != 0;
item.state = [row[@"checked"] boolValue] ? NSControlStateValueOn : NSControlStateValueOff;
[menu addItem:item];
}
return menu;
}
static BOOL setMenuGroups(NSDictionary *snapshot) {
NSMenu *main = NSApp.mainMenu;
NSArray<NSDictionary *> *groups = snapshot[@"groups"];
if (!main || groups.count != 3) return NO;
if (!menuTarget) menuTarget = [ReimsMenuTarget new];
if (!managedItems || managedItems.firstObject.menu != main) {
// Wails initializes App, Edit and Window in this order. Keep the
// original items so localization does not change targets or shortcuts.
if (main.numberOfItems != 3) return NO;
[standardItems release];
standardItems = [main.itemArray copy];
NSMutableArray *items = [NSMutableArray arrayWithCapacity:3];
NSInteger index = 2;
for (NSDictionary *group in groups) {
[items addObject:[[[NSMenuItem alloc] initWithTitle:group[@"label"] action:NULL keyEquivalent:@""] autorelease]];
}
[main insertItem:items[0] atIndex:index];
[main insertItem:items[1] atIndex:index + 1];
[main addItem:items[2]];
[managedItems release];
managedItems = [items copy];
}
NSDictionary<NSString *, NSString *> *labels = snapshot[@"standard"];
setMenuTitle(standardItems[0], @"Reims-Go");
setMenuTitle(standardItems[1], labels[@"edit"]);
setMenuTitle(standardItems[2], labels[@"window"]);
for (NSMenuItem *item in standardItems) localizeStandardItems(item.submenu, labels);
for (NSUInteger i = 0; i < groups.count; i++) {
NSMenuItem *item = managedItems[i];
item.title = groups[i][@"label"];
item.submenu = buildMenu(groups[i]);
}
NSApp.helpMenu = managedItems.lastObject.submenu;
return YES;
}
int reimsSyncApplicationMenu(const char *snapshot) {
@autoreleasepool {
NSData *data = [NSData dataWithBytes:snapshot length:strlen(snapshot)];
NSDictionary *menu = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
if (NSThread.isMainThread) return setMenuGroups(menu);
__block BOOL updated = NO;
dispatch_sync(dispatch_get_main_queue(), ^{ updated = setMenuGroups(menu); });
return updated;
}
}
+9
View File
@@ -0,0 +1,9 @@
//go:build !darwin || !cgo
package app
import "errors"
func (a *App) syncApplicationMenu(applicationMenuSnapshot) error {
return errors.New("native application menu is unavailable")
}
+35
View File
@@ -0,0 +1,35 @@
package app
import "testing"
const standardMenuFixture = `,"standard":{"edit":"编辑","window":"窗口","speech":"朗读","hide:":"隐藏 Reims-Go","Quit":"退出 Reims-Go"}`
func TestParseApplicationMenu(t *testing.T) {
const groups = `[{"label":"虚拟机","rows":[{"label":"Start","token":1,"key":"\r"}]},{"label":"View","rows":[{}, {"label":"Sidebar","checked":true,"token":2}]},{"label":"Help","rows":[{"label":"Reims-Go"}]}]`
parsed, err := parseApplicationMenu(`{"groups":` + groups + standardMenuFixture + `}`)
if err != nil {
t.Fatal(err)
}
if parsed.Groups[0].Rows[0].Key != "\r" || !parsed.Groups[1].Rows[1].Checked || parsed.Groups[2].Rows[0].Token != 0 {
t.Fatalf("menu snapshot did not keep shortcut, checked state and disabled row: %+v", parsed)
}
if parsed.Standard["edit"] != "编辑" || parsed.Standard["Quit"] != "退出 Reims-Go" {
t.Fatalf("menu snapshot did not keep localized standard items: %+v", parsed.Standard)
}
}
func TestParseApplicationMenuRejectsInvalidSnapshots(t *testing.T) {
for _, groups := range []string{
`null`,
`[{"label":"VM","rows":[{}]}]`,
`[{"label":"VM","rows":[{"label":"Start","token":1}]},{"label":"View","rows":[{"label":"Sidebar","token":1}]},{"label":"Help","rows":[{}]}]`,
`[{"label":"VM","rows":[{"label":"Start","token":1,"key":"q"}]},{"label":"View","rows":[{}]},{"label":"Help","rows":[{}]}]`,
} {
if _, err := parseApplicationMenu(`{"groups":` + groups + standardMenuFixture + `}`); err == nil {
t.Errorf("accepted invalid groups: %s", groups)
}
}
if _, err := parseApplicationMenu(`{"groups":[{"label":"VM","rows":[{}]},{"label":"View","rows":[{}]},{"label":"Help","rows":[{}]}]}`); err == nil {
t.Error("accepted missing standard menu labels")
}
}
+636
View File
@@ -0,0 +1,636 @@
package app
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/plugin"
)
// AutoInstallerProviderView describes one enabled built-in or Sidecar plugin
// that provides unattended guest installation for a guest OS family.
type AutoInstallerProviderView struct {
PluginID string `json:"plugin_id"`
ID string `json:"id"`
Title string `json:"title"`
Description string `json:"description,omitempty"`
GuestFamilies []string `json:"guest_families"`
RequiresOfflineInstaller bool `json:"requires_offline_installer,omitempty"`
SecretSetting string `json:"secret_setting"`
}
// AutoInstallStartRequest carries Stage 0 preflight parameters submitted by the
// host Create Wizard or VM Detail Page. Password is encrypted directly into
// host DPAPI storage and never sent to the plugin or written to logs.
type AutoInstallStartRequest struct {
PluginID string `json:"plugin_id,omitempty"`
DriverID string `json:"driver_id,omitempty"`
VMName string `json:"vm_name"`
Mode string `json:"mode,omitempty"` // "recovery_only" | "full"
GuestLang string `json:"guest_lang,omitempty"`
FullName string `json:"full_name"`
AccountName string `json:"account_name"`
Password string `json:"password"`
Region string `json:"region,omitempty"`
Appearance string `json:"appearance,omitempty"`
AgeRange string `json:"age_range,omitempty"`
SLAAccepted bool `json:"sla_accepted"`
SaveUnlockCredential bool `json:"save_unlock_credential,omitempty"`
InstallGuestTools *bool `json:"install_guest_tools,omitempty"`
OCRBackend string `json:"ocr_backend,omitempty"`
CustomOCRMirror string `json:"custom_ocr_mirror,omitempty"`
StartVMIfStopped bool `json:"start_vm_if_stopped,omitempty"`
}
// ListAutoInstallers returns enabled auto-installer plugins matching guestFamily
// (or all enabled providers when guestFamily is empty). Disabling a plugin
// immediately removes it from this list so the UI leaves zero residue.
func (a *App) ListAutoInstallers(guestFamily string) []AutoInstallerProviderView {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil || mgr.Registry() == nil {
return nil
}
loc := string(a.computerUseLocale())
items := mgr.Registry().AutoInstallersForFamily(guestFamily)
out := make([]AutoInstallerProviderView, 0, len(items))
for _, item := range items {
secretKey := strings.TrimSpace(item.SecretSetting)
out = append(out, AutoInstallerProviderView{
PluginID: item.PluginID,
ID: item.ID,
Title: item.Title.Get(loc),
Description: item.Description.Get(loc),
GuestFamilies: append([]string(nil), item.GuestFamilies...),
RequiresOfflineInstaller: item.RequiresOfflineInstaller,
SecretSetting: secretKey,
})
}
return out
}
func (a *App) resolveAutoInstallerProvider(pluginID, guestFamily string) (*plugin.Manager, AutoInstallerProviderView, error) {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil || mgr.Registry() == nil {
return nil, AutoInstallerProviderView{}, errors.New("plugin manager is unavailable")
}
providers := a.ListAutoInstallers(guestFamily)
if len(providers) == 0 && guestFamily != "" {
providers = a.ListAutoInstallers("")
}
if len(providers) == 0 {
return nil, AutoInstallerProviderView{}, errors.New("no enabled auto-installer plugin is available")
}
pid := strings.TrimSpace(pluginID)
if pid == "" {
return mgr, providers[0], nil
}
for _, p := range providers {
if p.PluginID == pid {
return mgr, p, nil
}
}
return nil, AutoInstallerProviderView{}, fmt.Errorf("auto-installer plugin %q is not enabled", pid)
}
func validatePluginSecretSetting(mgr *plugin.Manager, pluginID, settingKey string) error {
settingKey = strings.TrimSpace(settingKey)
if settingKey == "" {
return fmt.Errorf("auto-installer plugin %q does not declare a secret_setting for password storage", pluginID)
}
if mgr == nil || mgr.Registry() == nil {
return errors.New("plugin manager is unavailable")
}
info, ok := mgr.Registry().Info(pluginID)
if !ok {
return fmt.Errorf("auto-installer plugin %q is not registered", pluginID)
}
if info.Settings == nil {
return fmt.Errorf("auto-installer plugin %q does not declare secret setting %q in its manifest", pluginID, settingKey)
}
prop, exists := info.Settings.Properties[settingKey]
if !exists || !prop.Secret {
return fmt.Errorf("auto-installer plugin %q setting %q is not declared as secret", pluginID, settingKey)
}
return nil
}
// Stambha can boot macOS, but cannot supply the guest console or installation phase.
func validateAutoInstallDriver(driverID string) error {
if driver.CanonicalDriverID(strings.TrimSpace(driverID)) == driver.BuiltinStambhaDriverID {
return errors.New("automatic installation is unavailable for Stambha VMs")
}
return nil
}
func isPrintableASCIIPassword(s string) bool {
if len(s) < 4 || len(s) > 256 {
return false
}
for _, r := range s {
if r < 0x20 || r > 0x7E {
return false
}
}
return true
}
// PreflightAutoInstall queries the enabled auto-installer plugin for local OCR
// readiness and resumable checkpoint status.
func (a *App) PreflightAutoInstall(pluginID, driverID, vmName, guestLang string) (map[string]any, error) {
if err := validateAutoInstallDriver(driverID); err != nil {
return nil, err
}
mgr, provider, err := a.resolveAutoInstallerProvider(pluginID, "macos")
if err != nil {
return nil, err
}
vmKeyStr := ""
if strings.TrimSpace(vmName) != "" {
vmKeyStr = vmKeyForDriver(driverID, vmName)
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
var resp map[string]any
err = mgr.CallSidecar(ctx, provider.PluginID, "autoinstall/preflight", map[string]any{
"vm": vmKeyStr,
"guest_lang": guestLang,
}, &resp)
if err != nil {
return nil, err
}
if resp == nil {
resp = map[string]any{}
}
resp["plugin_id"] = provider.PluginID
return resp, nil
}
// StartAutoInstall configures host session & authorization (plus optional DPAPI
// account credentials and REIMSPROV provisioning in "full" mode), starts the VM
// if requested, and launches the auto-installer's state machine with screen input lock.
func (a *App) StartAutoInstall(req AutoInstallStartRequest) (map[string]any, error) {
password := req.Password
req.Password = ""
defer func() { password = "" }()
mode := strings.ToLower(strings.TrimSpace(req.Mode))
if mode == "" {
if strings.TrimSpace(req.FullName) == "" && strings.TrimSpace(req.AccountName) == "" && password == "" {
mode = "recovery_only"
} else {
mode = "full"
}
}
if mode != "recovery_only" && mode != "full" {
return nil, fmt.Errorf("unsupported auto-install mode %q", mode)
}
if !req.SLAAccepted {
return nil, errors.New("explicit Apple SLA confirmation is required before starting auto-install")
}
if mode == "full" && !isPrintableASCIIPassword(password) {
return nil, errors.New("password must be 4–256 printable ASCII characters")
}
vm, err := a.resolveVMInfo(req.DriverID, req.VMName)
if err != nil {
return nil, err
}
if err := validateAutoInstallDriver(vm.DriverID); err != nil {
return nil, err
}
family := "macos"
if vm.GuestOS != nil && vm.GuestOS.Family != "" {
family = vm.GuestOS.Family
}
mgr, provider, err := a.resolveAutoInstallerProvider(req.PluginID, family)
if err != nil {
if vm.State == "running" {
a.restoreManualInstallGuideFallback(vm.DriverID, vm.Name)
}
return nil, err
}
if broker := mgr.Broker(); broker != nil {
for _, perm := range []string{"vm:read", "vm:screen", "qmp:write", "vm:control"} {
if perr := broker.Authorize(provider.PluginID, perm); perr != nil {
if vm.State == "running" {
a.restoreManualInstallGuideFallback(vm.DriverID, vm.Name)
}
return nil, perr
}
}
}
vmKeyStr := vm.Ref().Key()
secretSetting := ""
if mode == "full" {
secretSetting = strings.TrimSpace(provider.SecretSetting)
if err := validatePluginSecretSetting(mgr, provider.PluginID, secretSetting); err != nil {
return nil, err
}
// Encrypt password straight into host DPAPI storage (never passed in RPC payload).
if err := mgr.SetSettings(provider.PluginID, vmKeyStr, map[string]any{
secretSetting: password,
}); err != nil {
return nil, fmt.Errorf("store DPAPI password: %w", err)
}
}
// Grant ephemeral per-VM console access and #105 protected-phase authorization
// backed by the user's explicit host preflight confirmation, and lock VM input
// against accidental physical mouse/keyboard interference while running.
a.grantEphemeralVMAccess(provider.PluginID, vmKeyStr)
phase := a.effectiveVMPhase(vm)
if phase == driver.PhaseNormal {
phase = driver.PhaseInstaller
}
a.grantProtectedPhase(provider.PluginID, vmKeyStr, phase, 0, true)
a.beginAgentSession(mgr, provider.PluginID, vm, provider.Title, "stage0_preflight", "lock", true)
a.setAgentSessionAutoInstallConfig(vmKeyStr, provider.PluginID, mode, secretSetting, mode == "full" && req.SaveUnlockCredential)
// Stage (or rebuild) per-VM REIMSPROV (hash-only offline provisioning disk)
// before cold start in full mode so offline install always matches the latest
// requested credentials and skips Setup Assistant & Keyboard Setup Assistant.
if mode == "full" && family == "macos" && vm.Directory != "" && vm.State != "running" &&
strings.TrimSpace(req.FullName) != "" && strings.TrimSpace(req.AccountName) != "" {
if perr := a.prepareVMProvisionForDir(vm.Name, vm.Directory, ProvisionRequest{
FullName: strings.TrimSpace(req.FullName),
AccountName: strings.TrimSpace(req.AccountName),
Password: password,
Appearance: strings.TrimSpace(req.Appearance),
SLAAccepted: req.SLAAccepted,
InstallGuestTools: req.InstallGuestTools,
}); perr != nil {
a.emitVMLog(vm.Name, "Warning: REIMSPROV provisioning skipped (continuing with OCR fallback): "+perr.Error())
}
}
if req.StartVMIfStopped && vm.State != "running" {
if err := a.StartVM(vm.DriverID, vm.Name); err != nil {
if secretSetting != "" {
_ = mgr.SetSettings(provider.PluginID, vmKeyStr, map[string]any{secretSetting: ""})
}
_ = a.StopAgentSession(vm.DriverID, vm.Name)
return nil, fmt.Errorf("start VM for auto-install: %w", err)
}
// Ensure the protected-phase grant stays active after cold start even if
// an early poll tick observed the VM stopped before QEMU launched.
a.grantProtectedPhase(provider.PluginID, vmKeyStr, phase, 0, true)
// Immediately bind the newly launched VM PID to the floating island and input shield.
a.refreshActiveAgentSessionAfterStart(vmKeyStr)
}
guestLang := strings.TrimSpace(req.GuestLang)
if guestLang == "" {
guestLang = vmInfoString(vm, "guest_lang")
}
if guestLang == "" {
guestLang = "zh-Hans:0"
}
payload := map[string]any{
"vm": vmKeyStr,
"mode": mode,
"guest_lang": guestLang,
"full_name": strings.TrimSpace(req.FullName),
"account_name": strings.TrimSpace(req.AccountName),
"secret_setting": secretSetting,
"region": strings.TrimSpace(req.Region),
"appearance": strings.TrimSpace(req.Appearance),
"age_range": strings.TrimSpace(req.AgeRange),
"sla_accepted": req.SLAAccepted,
"save_unlock_credential": mode == "full" && req.SaveUnlockCredential,
"ocr_backend": strings.TrimSpace(req.OCRBackend),
"custom_ocr_mirror": strings.TrimSpace(req.CustomOCRMirror),
"has_provision_disk": mode == "full" && a.hasVMProvisionDir(vm.Directory),
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
var resp map[string]any
if err := mgr.CallSidecar(ctx, provider.PluginID, "autoinstall/start", payload, &resp); err != nil {
if secretSetting != "" {
_ = mgr.SetSettings(provider.PluginID, vmKeyStr, map[string]any{secretSetting: ""})
}
_ = a.StopAgentSession(vm.DriverID, vm.Name)
return nil, err
}
if watchCtx, watchGen, ok := a.startAutoInstallSessionWatch(vmKeyStr, provider.PluginID); ok {
go a.watchAutoInstallSession(watchCtx, watchGen, mgr, provider.PluginID, vmKeyStr, secretSetting, secretSetting != "" && !req.SaveUnlockCredential)
}
if resp == nil {
resp = map[string]any{}
}
resp["plugin_id"] = provider.PluginID
return resp, nil
}
var autoInstallWatchInterval = 3 * time.Second
// watchAutoInstallSession monitors an auto-install run so temporary DPAPI
// credentials are cleared and any lingering host session (for example if an
// external plugin exits or fails after permission denial without calling
// host/session.end) is ended cleanly to restore the manual installation guide.
func (a *App) watchAutoInstallSession(watchCtx context.Context, watchGen uint64, mgr *plugin.Manager, pluginID, vmKeyStr, secretSetting string, clearSecret bool) {
ticker := time.NewTicker(autoInstallWatchInterval)
defer ticker.Stop()
timeout := time.NewTimer(2 * time.Hour)
defer timeout.Stop()
var watchDone <-chan struct{}
if watchCtx != nil {
watchDone = watchCtx.Done()
}
cleanupSecret := func(completed bool) {
if secretSetting != "" && (clearSecret || !completed) {
_ = mgr.SetSettings(pluginID, vmKeyStr, map[string]any{secretSetting: ""})
}
}
consecutiveErrs := 0
for {
select {
case <-watchDone:
return
case <-timeout.C:
if !a.isCurrentAutoInstallSessionWatch(vmKeyStr, pluginID, watchGen) {
return
}
cleanupSecret(false)
a.revokeEphemeralVMAccess(pluginID, vmKeyStr)
if a.isCurrentAutoInstallSessionWatch(vmKeyStr, pluginID, watchGen) {
a.endAgentSession(mgr, pluginID, vmKeyStr, "timeout")
}
return
case <-ticker.C:
if !a.isCurrentAutoInstallSessionWatch(vmKeyStr, pluginID, watchGen) {
return
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
var st struct {
Status string `json:"status"`
Stage string `json:"stage"`
Message string `json:"message"`
}
err := mgr.CallSidecar(ctx, pluginID, "autoinstall/status", map[string]any{"vm": vmKeyStr}, &st)
cancel()
if !a.isCurrentAutoInstallSessionWatch(vmKeyStr, pluginID, watchGen) {
return
}
if err != nil {
consecutiveErrs++
if consecutiveErrs < 3 {
continue
}
} else {
consecutiveErrs = 0
if st.Stage != "" || st.Message != "" {
a.syncAutoInstallSessionProgress(vmKeyStr, pluginID, st.Stage, st.Message)
}
}
if err != nil || st.Status == "completed" || st.Status == "stopped" || st.Status == "failed" || st.Status == "idle" {
if !a.isCurrentAutoInstallSessionWatch(vmKeyStr, pluginID, watchGen) {
return
}
completed := err == nil && st.Status == "completed"
cleanupSecret(completed)
a.revokeEphemeralVMAccess(pluginID, vmKeyStr)
if a.isCurrentAutoInstallSessionWatch(vmKeyStr, pluginID, watchGen) {
status := strings.TrimSpace(st.Status)
if err != nil || status == "" || status == "idle" {
status = "failed"
}
a.sessionMu.Lock()
if sess := a.agentSessions[vmKeyStr]; sess != nil && sess.pluginID == pluginID && sess.watchGen == watchGen {
sess.status = status
if strings.TrimSpace(st.Message) != "" {
sess.message = strings.TrimSpace(st.Message)
}
}
a.sessionMu.Unlock()
a.endAgentSession(mgr, pluginID, vmKeyStr, "autoinstall_"+status)
}
return
}
}
}
}
// listAutoInstallStatuses returns all live and persisted auto-install runs for
// the selected provider (used by CLI control-pipe status queries without a VM).
func (a *App) listAutoInstallStatuses(pluginID string) (map[string]any, error) {
mgr, provider, err := a.resolveAutoInstallerProvider(pluginID, "macos")
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
var resp map[string]any
if err := mgr.CallSidecar(ctx, provider.PluginID, "autoinstall/status", map[string]any{"vm": ""}, &resp); err != nil {
return nil, err
}
if resp == nil {
resp = map[string]any{"runs": []any{}}
}
return resp, nil
}
// GetAutoInstallStatus queries the auto-installer plugin for one VM's progress.
func (a *App) GetAutoInstallStatus(pluginID, driverID, vmName string) (map[string]any, error) {
mgr, provider, err := a.resolveAutoInstallerProvider(pluginID, "macos")
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
vmKeyStr := vmKeyForDriver(driverID, vmName)
var resp map[string]any
err = mgr.CallSidecar(ctx, provider.PluginID, "autoinstall/status", map[string]any{
"vm": vmKeyStr,
}, &resp)
if err == nil && resp != nil {
stage, _ := resp["stage"].(string)
msg, _ := resp["message"].(string)
if stage != "" {
if existing, _ := resp["stage_label"].(string); existing == "" {
if label := stageKnownName(a.computerUseLocale(), stage); label != "" {
resp["stage_label"] = label
}
}
}
a.syncAutoInstallSessionProgress(vmKeyStr, provider.PluginID, stage, msg)
}
return resp, err
}
func (a *App) autoInstallResumeVM(driverID, vmName string) (driver.VMInfo, error) {
vm, err := a.resolveVMInfo(driverID, vmName)
if err != nil {
// An explicit driver can resume from its saved checkpoint. A bare
// name must resolve before granting access to any particular VM.
if strings.TrimSpace(driverID) == "" {
return driver.VMInfo{}, err
}
ref := driver.NewVMRef(driverID, vmName)
vm = driver.VMInfo{DriverID: ref.DriverID, Name: ref.Name}
}
return vm, validateAutoInstallDriver(vm.DriverID)
}
// resumeAutoInstallFromControl handles `resume` requests arriving over the
// local named-pipe control channel (e.g. `reims-go vm autoinstall resume`).
// Because any same-user process (including an L3 sidecar plugin) can connect to
// the named pipe, this path requires explicit desktop UI confirmation before
// granting ephemeral VM access, protected-phase authorization, or clearing
// host-initiated pauses.
func (a *App) resumeAutoInstallFromControl(ctx context.Context, pluginID, driverID, vmName string) (map[string]any, error) {
mgr, provider, err := a.resolveAutoInstallerProvider(pluginID, "macos")
if err != nil {
return nil, err
}
if broker := mgr.Broker(); broker != nil {
for _, perm := range []string{"vm:read", "vm:screen", "qmp:write", "vm:control"} {
if perr := broker.Authorize(provider.PluginID, perm); perr != nil {
return nil, perr
}
}
}
vmInfo, err := a.autoInstallResumeVM(driverID, vmName)
if err != nil {
return nil, err
}
phase := a.effectiveVMPhase(vmInfo)
if phase != driver.PhaseInstaller && phase != driver.PhaseRecovery {
phase = driver.PhaseInstaller
}
prompt := a.buildProtectedPhasePrompt(provider.PluginID, vmInfo, phase, true)
res, err := a.requestHostConfirm(ctx, mgr.Broker(), mgr.Registry(), provider.PluginID, prompt)
if err != nil {
return nil, err
}
if !res.Approved {
return nil, errors.New("confirmation_denied: user declined auto-install resume")
}
return a.ResumeAutoInstall(provider.PluginID, vmInfo.DriverID, vmInfo.Name)
}
// ResumeAutoInstall resumes a paused_for_user or takeover-paused installation.
func (a *App) ResumeAutoInstall(pluginID, driverID, vmName string) (map[string]any, error) {
mgr, provider, err := a.resolveAutoInstallerProvider(pluginID, "macos")
if err != nil {
a.restoreManualInstallGuideFallback(driverID, vmName)
return nil, err
}
resumeVM, err := a.autoInstallResumeVM(driverID, vmName)
if err != nil {
return nil, err
}
driverID, vmName = resumeVM.DriverID, resumeVM.Name
vmKeyStr := resumeVM.Ref().Key()
if broker := mgr.Broker(); broker != nil {
for _, perm := range []string{"vm:read", "vm:screen", "qmp:write", "vm:control"} {
if perr := broker.Authorize(provider.PluginID, perm); perr != nil {
a.handlePluginPermissionDeniedForVM(mgr, provider.PluginID, vmKeyStr, vmName, "permission_denied")
return nil, perr
}
}
}
hadSession := a.hasActiveAgentSessionOwnedBy(vmKeyStr, provider.PluginID)
a.grantEphemeralVMAccess(provider.PluginID, vmKeyStr)
if !hadSession {
phase := a.effectiveVMPhase(resumeVM)
if phase == driver.PhaseNormal {
phase = driver.PhaseInstaller
}
a.grantProtectedPhase(provider.PluginID, vmKeyStr, phase, 0, true)
}
_ = a.ResumeAgentSession(driverID, vmName)
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
var resp map[string]any
err = mgr.CallSidecar(ctx, provider.PluginID, "autoinstall/resume", map[string]any{
"vm": vmKeyStr,
}, &resp)
if err != nil {
if !hadSession {
a.revokeEphemeralVMAccess(provider.PluginID, vmKeyStr)
a.revokeProtectedPhaseForPluginVM(provider.PluginID, vmKeyStr, "resume_failed")
}
if !a.hasActiveAgentSession(vmKeyStr) {
a.restoreManualInstallGuideFallback(driverID, vmName)
}
return resp, err
}
// If resuming restarted a runner from a persisted checkpoint (no prior live
// session in memory), establish the host session with input-lock policy and
// start the session watcher so temporary credentials and grants are always
// cleaned up on completion.
if !hadSession {
saveUnlock, _ := resp["save_unlock_credential"].(bool)
stage, _ := resp["stage"].(string)
secretKey := strings.TrimSpace(provider.SecretSetting)
if validatePluginSecretSetting(mgr, provider.PluginID, secretKey) != nil {
secretKey = ""
}
if !a.hasActiveAgentSessionOwnedBy(vmKeyStr, provider.PluginID) {
a.beginAgentSession(mgr, provider.PluginID, resumeVM, provider.Title, stage, "lock", true)
}
a.setAgentSessionAutoInstallConfig(vmKeyStr, provider.PluginID, "", secretKey, saveUnlock)
if watchCtx, watchGen, ok := a.startAutoInstallSessionWatch(vmKeyStr, provider.PluginID); ok {
go a.watchAutoInstallSession(watchCtx, watchGen, mgr, provider.PluginID, vmKeyStr, secretKey, !saveUnlock)
}
}
return resp, nil
}
// StopAutoInstall aborts the active auto-install session, revokes authorization,
// and clears the temporary DPAPI password setting.
func (a *App) StopAutoInstall(pluginID, driverID, vmName string) error {
_ = a.StopAgentSession(driverID, vmName)
mgr, provider, err := a.resolveAutoInstallerProvider(pluginID, "macos")
if err != nil {
return nil
}
vmKeyStr := vmKeyForDriver(driverID, vmName)
secretSetting := strings.TrimSpace(provider.SecretSetting)
if validatePluginSecretSetting(mgr, provider.PluginID, secretSetting) == nil {
_ = mgr.SetSettings(provider.PluginID, vmKeyStr, map[string]any{secretSetting: ""})
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = mgr.CallSidecar(ctx, provider.PluginID, "autoinstall/stop", map[string]any{"vm": vmKeyStr}, nil)
return nil
}
// GetAutoInstallDiagnosticSummary returns a redacted unknown-page/error summary
// safe for the user to copy and share without exposing names, passwords, or images.
func (a *App) GetAutoInstallDiagnosticSummary(pluginID, driverID, vmName string) (map[string]any, error) {
mgr, provider, err := a.resolveAutoInstallerProvider(pluginID, "macos")
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
var resp map[string]any
err = mgr.CallSidecar(ctx, provider.PluginID, "autoinstall/diagnosticSummary", map[string]any{
"vm": vmKeyForDriver(driverID, vmName),
}, &resp)
return resp, err
}
// DownloadAutoInstallOCR asks the auto-installer plugin to download RapidOCR ONNX fallback assets.
func (a *App) DownloadAutoInstallOCR(pluginID, customMirror string) (map[string]any, error) {
mgr, provider, err := a.resolveAutoInstallerProvider(pluginID, "macos")
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
var resp map[string]any
err = mgr.CallSidecar(ctx, provider.PluginID, "autoinstall/downloadOCR", map[string]any{
"custom_mirror": strings.TrimSpace(customMirror),
}, &resp)
return resp, err
}
+198
View File
@@ -0,0 +1,198 @@
package app
import (
"context"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/macos/guest"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
)
func TestListAutoInstallersZeroResidueWhenDisabled(t *testing.T) {
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}}
mgr, err := plugin.NewManager(plugin.ManagerOptions{
DataRoot: a.cfg.DataRoot,
HostVersion: "0.3.0",
})
if err != nil {
t.Fatal(err)
}
defer mgr.Close()
a.pluginMgr = mgr
// Register a mock auto-installer plugin.
if err := mgr.Registry().Register(plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: "test.autoinstall",
Version: "1.0.0",
Name: plugin.LocalizedText{EnUS: "Test AutoInstall"},
Entry: plugin.Entry{Sidecar: "bin/auto.exe"},
Contributes: plugin.Contributes{
AutoInstallers: []plugin.AutoInstallerContribution{{
ID: "macos-local",
Title: plugin.LocalizedText{EnUS: "macOS Auto-Install"},
GuestFamilies: []string{"macos"},
RequiresOfflineInstaller: true,
}},
},
},
Source: plugin.SourceDevLink,
Trust: plugin.TrustDev,
Desired: true,
}); err != nil {
t.Fatal(err)
}
mgr.Registry().Reconcile(t.Context())
got := a.ListAutoInstallers("macos")
if len(got) != 1 || got[0].PluginID != "test.autoinstall" || got[0].SecretSetting != "account_password" {
t.Fatalf("expected 1 enabled macOS auto-installer, got %+v", got)
}
if len(a.ListAutoInstallers("linux")) != 0 {
t.Fatal("macOS-only auto-installer must not match linux family")
}
// Disabling the plugin removes the contribution with zero residue.
if err := mgr.Registry().SetDesired(t.Context(), "test.autoinstall", false); err != nil {
t.Fatal(err)
}
mgr.Registry().Reconcile(t.Context())
if len(a.ListAutoInstallers("macos")) != 0 {
t.Fatal("disabled auto-installer must leave zero providers")
}
}
func TestBuiltinAutoInstallDefaultEnabledAndDisableCleansSession(t *testing.T) {
dataRoot := t.TempDir()
cfg := config.Default()
cfg.DataRoot = dataRoot
a := &App{cfg: cfg, pollWake: make(chan struct{}, 1)}
var mgr *plugin.Manager
var err error
mgr, err = plugin.NewManager(plugin.ManagerOptions{
DataRoot: dataRoot,
HostVersion: "0.3.0",
HostHandlers: func(pluginID string) map[string]plugin.RPCRequestHandler {
return a.hostAPISvc().Handlers(mgr, pluginID)
},
})
if err != nil {
t.Fatal(err)
}
defer mgr.Close()
a.pluginMgr = mgr
cb := builtin.HostCallbacks{
GetConfig: func() config.Config { return *cfg },
GetSetting: func(pluginID, vmName, key string) (any, bool) {
v, ok := mgr.GetSettings(pluginID, vmName, false)[key]
return v, ok
},
PluginDataDir: mgr.Layout().DataDir,
PluginLogPath: mgr.Layout().LogPath,
CallHostAPI: mgr.CallHostAPI,
}
if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
t.Fatal(err)
}
if err := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
t.Fatal(err)
}
mgr.Registry().OnChange(func() {
a.stopAgentSessionsForInactivePlugins(mgr)
})
mgr.Registry().Reconcile(context.Background())
// Official built-in auto-installer must be enabled and discoverable by default.
providers := a.ListAutoInstallers("macos")
if len(providers) != 1 || providers[0].PluginID != guest.IDAutoInstall {
t.Fatalf("expected default-enabled %s, got %+v", guest.IDAutoInstall, providers)
}
if err := mgr.Broker().Authorize(guest.IDAutoInstall, "qmp:write"); err != nil {
t.Fatalf("official built-in auto-install plugin must hold qmp:write for DPAPI secret typing: %v", err)
}
// Preflight, status, diagnosticSummary, and DPAPI secret storage all work out of the box.
pf, err := a.PreflightAutoInstall("", driver.BuiltinReimsMacOSDriverID, "demo", "zh-Hans:0")
if err != nil {
t.Fatalf("PreflightAutoInstall: %v", err)
}
if pf["plugin_id"] != guest.IDAutoInstall {
t.Fatalf("unexpected preflight response: %+v", pf)
}
st, err := a.GetAutoInstallStatus("", driver.BuiltinReimsMacOSDriverID, "demo")
if err != nil {
t.Fatalf("GetAutoInstallStatus: %v", err)
}
if st["status"] != "idle" {
t.Fatalf("expected idle status, got %+v", st)
}
diag, err := a.GetAutoInstallDiagnosticSummary("", driver.BuiltinReimsMacOSDriverID, "demo")
if err != nil {
t.Fatalf("GetAutoInstallDiagnosticSummary: %v", err)
}
if diag["status"] != "idle" {
t.Fatalf("expected idle diagnostic summary, got %+v", diag)
}
vmKey := vmKeyForDriver(driver.BuiltinReimsMacOSDriverID, "demo")
if err := mgr.SetSettings(guest.IDAutoInstall, vmKey, map[string]any{"account_password": "TestPass123"}); err != nil {
t.Fatalf("SetSettings secret: %v", err)
}
secret, err := mgr.SecretSetting(guest.IDAutoInstall, vmKey, "account_password")
if err != nil || secret != "TestPass123" {
t.Fatalf("SecretSetting = %q, %v", secret, err)
}
// Simulate an active session owned by the built-in auto-install plugin and
// verify disabling the plugin stops the session and removes all providers.
a.grantEphemeralVMAccess(guest.IDAutoInstall, vmKey)
a.grantProtectedPhase(guest.IDAutoInstall, vmKey, driver.PhaseInstaller, 0, true)
a.beginAgentSession(mgr, guest.IDAutoInstall, driver.VMInfo{
DriverID: driver.BuiltinReimsMacOSDriverID,
Name: "demo",
}, "Auto-Install", "stage1_boot_recovery", "lock", true)
if !a.hasActiveAgentSession(vmKey) {
t.Fatal("expected active agent session before disable")
}
if err := mgr.Disable(context.Background(), guest.IDAutoInstall); err != nil {
t.Fatalf("Disable builtin auto-install: %v", err)
}
if len(a.ListAutoInstallers("macos")) != 0 {
t.Fatal("expected zero auto-installers after disabling builtin plugin")
}
if a.hasActiveAgentSession(vmKey) {
t.Fatal("expected active agent session to be torn down when plugin is disabled")
}
if _, ok := a.lookupProtectedPhaseGrant(guest.IDAutoInstall, vmKey); ok {
t.Fatal("expected protected-phase grant to be revoked when plugin is disabled")
}
// Re-enabling restores the built-in provider cleanly.
if err := mgr.Enable(context.Background(), guest.IDAutoInstall, false); err != nil {
t.Fatalf("Enable builtin auto-install: %v", err)
}
providers = a.ListAutoInstallers("macos")
if len(providers) != 1 || providers[0].PluginID != guest.IDAutoInstall {
t.Fatalf("expected %s restored after enable, got %+v", guest.IDAutoInstall, providers)
}
// Disabling the plugin must also clear any retained completed overlay (zero residue).
a.sessionMu.Lock()
a.completedOverlays = map[string]completedOverlayEntry{
vmKey: {pluginID: guest.IDAutoInstall, driverID: driver.BuiltinReimsMacOSDriverID, vmName: "demo", pid: 4242},
}
a.sessionMu.Unlock()
if err := mgr.Disable(context.Background(), guest.IDAutoInstall); err != nil {
t.Fatalf("Disable builtin auto-install (completed overlay cleanup): %v", err)
}
if a.isCompletedOverlay(vmKey) {
t.Fatal("expected completed overlay to be cleared when owning plugin is disabled")
}
}
+421
View File
@@ -0,0 +1,421 @@
package app
import (
"context"
"encoding/json"
"strings"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/control"
"github.com/Nwflower/reims-go/internal/driver"
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/plugin"
)
func newHardeningTestApp(t *testing.T, vms ...driver.VMInfo) (*App, *plugin.Manager, string) {
t.Helper()
dataRoot := t.TempDir()
mgr := newR3TestManager(t, dataRoot)
drvReg := plugin.NewRegistry(nil)
stubDrv := &stubMultiVMMacOSDriver{vms: vms}
if err := drvReg.Register(plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: "test.macos.driver.hardening",
Version: "1.0.0",
Name: plugin.LocalizedText{EnUS: "macOS Stub"},
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: true,
Activate: func(_ context.Context, sc *plugin.Scope) error {
sc.Registry().RegisterGuestDriver(sc, driver.BuiltinReimsMacOSDriverID, stubDrv)
return nil
},
}); err != nil {
t.Fatal(err)
}
drvReg.Reconcile(context.Background())
router := driver.NewRouter(drvReg, func() string { return dataRoot })
stateTable := driver.NewStateTable()
router.SetStateTable(stateTable)
a := &App{
cfg: &config.Config{DataRoot: dataRoot},
pluginMgr: mgr,
driverRouter: router,
vmStateTable: stateTable,
lifecycleSvc: vmlifecycle.New(drvReg, router, nil),
}
return a, mgr, dataRoot
}
func registerTestPluginWithPerms(t *testing.T, mgr *plugin.Manager, id string, perms []string, autoInstaller bool) {
t.Helper()
m := plugin.Manifest{
Schema: 1,
ID: id,
Version: "1.0.0",
Name: plugin.LocalizedText{EnUS: id},
Permissions: perms,
}
if autoInstaller {
m.Contributes.AutoInstallers = []plugin.AutoInstallerContribution{
{
ID: "auto",
Title: plugin.LocalizedText{EnUS: "Auto"},
GuestFamilies: []string{"macos"},
},
}
}
if err := mgr.Registry().Register(plugin.PluginDef{
Manifest: m,
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: true,
}); err != nil {
t.Fatal(err)
}
mgr.Registry().Reconcile(context.Background())
}
func TestHostUIConfirmCannotSpoofProtectedPhasePromptOrCrossPhase(t *testing.T) {
vm := driver.VMInfo{
DriverID: driver.BuiltinReimsMacOSDriverID,
Name: "tahoe-confirm",
State: "running",
Phase: driver.PhaseInstaller,
}
a, mgr, _ := newHardeningTestApp(t, vm)
const pid = "test.plugin.spoof"
registerTestPluginWithPerms(t, mgr, pid, []string{"ui:notify", "vm:read", "vm:screen"}, false)
var seen ConfirmPrompt
a.confirmEmit = func(p ConfirmPrompt) {
seen = p
go func() { _ = a.ResolveConfirmRequest(p.ID, true, 30, false) }()
}
rawReq, _ := json.Marshal(map[string]any{
"vm": vm.Ref().Key(),
"protected_phase": driver.PhaseInstaller,
"title": "Totally Harmless Update",
"message": "Click OK to continue",
"confirm_label": "OK",
"danger": false,
})
handlers := a.hostAPISvc().Handlers(mgr, pid)
if _, err := handlers["host/ui.confirm"](context.Background(), rawReq); err != nil {
t.Fatalf("host/ui.confirm returned error: %v", err)
}
if !seen.Danger {
t.Fatal("protected_phase confirmation must force Danger=true")
}
if seen.Title == "Totally Harmless Update" || seen.Message == "Click OK to continue" {
t.Fatalf("protected_phase confirmation allowed spoofed title/message: %+v", seen)
}
// An installer-phase grant must NOT authorize recovery phase.
if err := a.authorizeProtectedPhase(context.Background(), mgr, pid, vm, driver.PhaseInstaller, false, false); err != nil {
t.Fatalf("installer grant should be active for installer phase: %v", err)
}
a.confirmEmit = func(p ConfirmPrompt) {
go func() { _ = a.ResolveConfirmRequest(p.ID, false, 0, false) }()
}
if err := a.authorizeProtectedPhase(context.Background(), mgr, pid, vm, driver.PhaseRecovery, false, false); err == nil || !strings.Contains(err.Error(), "confirmation_required") {
t.Fatalf("installer grant must not authorize recovery phase; got err=%v", err)
}
}
func TestControlAutoInstallRejectsMissingDataRootAndRequiresConfirmForResume(t *testing.T) {
vm := driver.VMInfo{
DriverID: driver.BuiltinReimsMacOSDriverID,
Name: "tahoe-pipe",
State: "running",
Phase: driver.PhaseInstaller,
}
a, mgr, dataRoot := newHardeningTestApp(t, vm)
const pid = "test.plugin.autoinstall"
registerTestPluginWithPerms(t, mgr, pid, []string{"vm:read", "vm:screen", "qmp:write", "vm:control"}, true)
// 1. Missing data_root must be rejected when desktop app has a DataRoot configured.
rawNoRoot, _ := json.Marshal(control.AutoInstallRequest{
Action: "resume",
PluginID: pid,
DriverID: vm.DriverID,
VMName: vm.Name,
})
if _, err := a.handleControlAutoInstall(context.Background(), rawNoRoot); err == nil || !strings.Contains(err.Error(), "data_root_mismatch") {
t.Fatalf("expected data_root_mismatch when data_root omitted, got %v", err)
}
// 2. Named-pipe resume must require desktop confirmation and never silently
// grant ephemeral/protected-phase access or clear hostPaused when denied.
a.beginAgentSession(mgr, pid, vm, "Auto", "stage1", "lock", true)
if err := a.PauseAgentSession(vm.DriverID, vm.Name); err != nil {
t.Fatal(err)
}
prompted := false
a.confirmEmit = func(p ConfirmPrompt) {
prompted = true
go func() { _ = a.ResolveConfirmRequest(p.ID, false, 0, false) }()
}
rawResume, _ := json.Marshal(control.AutoInstallRequest{
Action: "resume",
DataRoot: dataRoot,
PluginID: pid,
DriverID: vm.DriverID,
VMName: vm.Name,
})
if _, err := a.handleControlAutoInstall(context.Background(), rawResume); err == nil || !strings.Contains(err.Error(), "confirmation_denied") {
t.Fatalf("expected confirmation_denied on denied control resume, got %v", err)
}
if !prompted {
t.Fatal("expected control resume to prompt user in desktop UI")
}
if _, ok := a.lookupProtectedPhaseGrant(pid, vm.Ref().Key()); ok {
t.Fatal("denied control resume must not mint protected-phase grant")
}
a.sessionMu.Lock()
sess := a.agentSessions[vm.Ref().Key()]
stillHostPaused := sess != nil && sess.hostPaused && sess.pausedForUser
a.sessionMu.Unlock()
if !stillHostPaused {
t.Fatal("denied control resume must preserve hostPaused state")
}
}
func TestDisablePluginRevokesProtectedPhaseGrantWithoutSession(t *testing.T) {
vm := driver.VMInfo{
DriverID: driver.BuiltinReimsMacOSDriverID,
Name: "tahoe-readonly-grant",
State: "running",
Phase: driver.PhaseInstaller,
}
a, mgr, _ := newHardeningTestApp(t, vm)
const pid = "test.plugin.readonly"
registerTestPluginWithPerms(t, mgr, pid, []string{"vm:read", "vm:screen"}, false)
a.grantProtectedPhase(pid, vm.Ref().Key(), driver.PhaseInstaller, 30, false)
if _, ok := a.lookupProtectedPhaseGrant(pid, vm.Ref().Key()); !ok {
t.Fatal("expected grant to be recorded")
}
// Disable plugin (no active agentSession exists) and reconcile.
if err := mgr.Registry().SetDesired(context.Background(), pid, false); err != nil {
t.Fatal(err)
}
mgr.Registry().Reconcile(context.Background())
a.stopAgentSessionsForInactivePlugins(mgr)
if _, ok := a.lookupProtectedPhaseGrant(pid, vm.Ref().Key()); ok {
t.Fatal("disabling plugin must revoke protected-phase grant even without an active agentSession")
}
}
func TestBeginAgentSessionReplacementCleansPreviousPluginState(t *testing.T) {
vm := driver.VMInfo{
DriverID: driver.BuiltinReimsMacOSDriverID,
Name: "tahoe-replace",
State: "running",
Phase: driver.PhaseInstaller,
}
a, mgr, _ := newHardeningTestApp(t, vm)
const pidA = "test.plugin.a"
const pidB = "test.plugin.b"
registerTestPluginWithPerms(t, mgr, pidA, []string{"vm:read", "qmp:write"}, false)
registerTestPluginWithPerms(t, mgr, pidB, []string{"vm:read", "qmp:write"}, false)
a.grantEphemeralVMAccess(pidA, vm.Ref().Key())
a.grantProtectedPhase(pidA, vm.Ref().Key(), driver.PhaseInstaller, 30, false)
a.beginAgentSession(mgr, pidA, vm, "Plugin A", "stage1", "lock", true)
a.beginAgentSession(mgr, pidB, vm, "Plugin B", "stage2", "auto", false)
if a.hasEphemeralVMAccess(pidA, vm.Ref().Key()) {
t.Fatal("replacing session must revoke previous plugin's ephemeral VM access")
}
if _, ok := a.lookupProtectedPhaseGrant(pidA, vm.Ref().Key()); ok {
t.Fatal("replacing session must revoke previous plugin's protected-phase grant")
}
}
func TestVMRestartAndFinishInstallEnforceTakeoverAndProtectedPhase(t *testing.T) {
vm := driver.VMInfo{
DriverID: driver.BuiltinReimsMacOSDriverID,
Name: "tahoe-restart-guard",
State: "running",
Phase: driver.PhaseInstaller,
}
a, mgr, _ := newHardeningTestApp(t, vm)
const pid = "test.plugin.restart"
registerTestPluginWithPerms(t, mgr, pid, []string{"vm:read", "vm:control"}, false)
a.grantEphemeralVMAccess(pid, vm.Ref().Key())
prompted := make(chan struct{}, 1)
a.confirmEmit = func(p ConfirmPrompt) {
select {
case prompted <- struct{}{}:
default:
}
go func() { _ = a.ResolveConfirmRequest(p.ID, false, 0, false) }()
}
rawVM, _ := json.Marshal(map[string]any{"vm": vm.Ref().Key()})
// 1. Without protected-phase grant, host/vm.restart must be blocked in installer phase.
if _, err := a.handleComputerUseVMRestart(context.Background(), rawVM, mgr, pid); err == nil || !strings.Contains(err.Error(), "confirmation_required") {
t.Fatalf("expected confirmation_required on host/vm.restart in installer phase, got %v", err)
}
<-prompted
// Wait for the async denial goroutine to settle before step 2.
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
a.confirmMu.Lock()
inFlight := a.protectedPhaseInFlight[phaseGrantKey{pluginID: pid, vmKey: vm.Ref().Key()}]
a.confirmMu.Unlock()
if !inFlight {
break
}
time.Sleep(10 * time.Millisecond)
}
// 2. While host-paused/taken over, both restart and finishInstall must be blocked.
a.grantEphemeralVMAccess(pid, vm.Ref().Key())
a.grantProtectedPhase(pid, vm.Ref().Key(), driver.PhaseInstaller, 30, false)
a.beginAgentSession(mgr, pid, vm, "Test", "stage1", "auto", false)
a.sessionMu.Lock()
a.agentSessions[vm.Ref().Key()].takeoverPaused = true
a.agentSessions[vm.Ref().Key()].takeoverUntil = time.Now().Add(30 * time.Second)
a.sessionMu.Unlock()
if _, err := a.handleComputerUseVMRestart(context.Background(), rawVM, mgr, pid); err == nil || !strings.Contains(err.Error(), "user_takeover") {
t.Fatalf("expected user_takeover on host/vm.restart during takeover, got %v", err)
}
if _, err := a.handleComputerUseVMFinishInstall(context.Background(), rawVM, mgr, pid); err == nil || !strings.Contains(err.Error(), "user_takeover") {
t.Fatalf("expected user_takeover on host/vm.finishInstall during takeover, got %v", err)
}
}
type phaseErrorDriver struct {
stubMultiVMMacOSDriver
phaseErr error
}
type stambhaAutomationTestDriver struct{ stubMultiVMMacOSDriver }
func (*stambhaAutomationTestDriver) ID() string { return driver.BuiltinStambhaDriverID }
func TestStambhaAutomationRequiresSupportedConsoleAndKnownPhase(t *testing.T) {
vm := driver.VMInfo{
DriverID: driver.BuiltinStambhaDriverID, Name: "arm-guest", State: "running",
Capabilities: []string{"guest.arm64"}, DriverData: map[string]any{"usb_image": "boot.raw"},
}
a, mgr, dataRoot := newHardeningTestApp(t)
drv := &stambhaAutomationTestDriver{stubMultiVMMacOSDriver{vms: []driver.VMInfo{vm}}}
reg := mgr.Registry()
if err := reg.Register(plugin.PluginDef{
Manifest: plugin.Manifest{Schema: 1, ID: "test.stambha", Version: "1.0.0", Name: plugin.LocalizedText{EnUS: "Stambha"}},
Source: plugin.SourceBuiltin, Trust: plugin.TrustOfficial, Desired: true,
Activate: func(_ context.Context, sc *plugin.Scope) error {
sc.Registry().RegisterGuestDriver(sc, drv.ID(), drv)
return nil
},
}); err != nil {
t.Fatal(err)
}
const pid = "test.plugin.stambha"
registerTestPluginWithPerms(t, mgr, pid, []string{"vm:read", "vm:screen", "qmp:write", "vm:control"}, true)
a.driverRouter = driver.NewRouter(reg, func() string { return dataRoot })
a.driverRouter.SetStateTable(a.vmStateTable)
a.lifecycleSvc = vmlifecycle.New(reg, a.driverRouter, nil)
a.confirmEmit = func(p ConfirmPrompt) {
t.Error("unsupported auto-install requested confirmation")
go func() { _ = a.ResolveConfirmRequest(p.ID, false, 0, false) }()
}
assertUnavailable := func(err error) {
t.Helper()
if err == nil || !strings.Contains(err.Error(), "unavailable for Stambha") {
t.Fatalf("want unsupported auto-install, got %v", err)
}
}
_, err := a.PreflightAutoInstall(pid, vm.DriverID, vm.Name, "")
assertUnavailable(err)
for _, id := range []string{vm.DriverID, ""} {
_, err = a.StartAutoInstall(AutoInstallStartRequest{
PluginID: pid, DriverID: id, VMName: vm.Name, Mode: "full", SLAAccepted: true, Password: "test-password",
})
assertUnavailable(err)
_, err = a.ResumeAutoInstall(pid, id, vm.Name)
assertUnavailable(err)
_, err = a.resumeAutoInstallFromControl(t.Context(), pid, id, vm.Name)
assertUnavailable(err)
}
key := vm.Ref().Key()
if a.hasEphemeralVMAccess(pid, key) || a.hasActiveAgentSession(key) {
t.Fatal("unsupported installation granted access or started a session")
}
if _, ok := a.lookupProtectedPhaseGrant(pid, key); ok {
t.Fatal("unsupported installation granted protected-phase access")
}
a.grantEphemeralVMAccess(pid, key)
raw, _ := json.Marshal(map[string]any{"vm": key})
for _, handler := range []computerUseVMHandler{a.handleComputerUseVMRestart, a.handleComputerUseVMFinishInstall} {
if _, err := handler(t.Context(), raw, mgr, pid); err == nil || !strings.Contains(err.Error(), "installation phase") {
t.Fatalf("want unknown installation phase, got %v", err)
}
}
}
func (d *phaseErrorDriver) Phase(_ context.Context, _ string) (string, error) {
return "", d.phaseErr
}
func TestEffectiveVMPhaseStrictAllowsMethodNotFoundAndFailsClosedOnOtherErrors(t *testing.T) {
vm := driver.VMInfo{
DriverID: driver.BuiltinReimsMacOSDriverID,
Name: "sidecar-vm",
State: "running",
}
makeApp := func(phaseErr error) *App {
dataRoot := t.TempDir()
drvReg := plugin.NewRegistry(nil)
stub := &phaseErrorDriver{
stubMultiVMMacOSDriver: stubMultiVMMacOSDriver{vms: []driver.VMInfo{vm}},
phaseErr: phaseErr,
}
if err := drvReg.Register(plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: "test.macos.driver.phaseerr",
Version: "1.0.0",
Name: plugin.LocalizedText{EnUS: "Phase Err Driver"},
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: true,
Activate: func(_ context.Context, sc *plugin.Scope) error {
sc.Registry().RegisterGuestDriver(sc, driver.BuiltinReimsMacOSDriverID, stub)
return nil
},
}); err != nil {
t.Fatal(err)
}
drvReg.Reconcile(context.Background())
return &App{driverRouter: driver.NewRouter(drvReg, func() string { return dataRoot })}
}
// Older sidecar without driver/phase (RPCMethodNotFound) must fall back to normal.
a1 := makeApp(&plugin.RPCError{Code: plugin.RPCMethodNotFound, Message: "method not found"})
phase, err := a1.effectiveVMPhaseStrict(vm)
if err != nil || phase != driver.PhaseNormal {
t.Fatalf("RPCMethodNotFound: got (%q, %v), want (%q, nil)", phase, err, driver.PhaseNormal)
}
// Real/transient error must fail closed.
a2 := makeApp(context.DeadlineExceeded)
if _, err := a2.effectiveVMPhaseStrict(vm); err == nil {
t.Fatal("expected effectiveVMPhaseStrict to fail closed on transient error")
}
}
+349 -35
View File
@@ -10,12 +10,14 @@ import (
"os"
"path/filepath"
"slices"
"sort"
"strings"
"time"
"unicode/utf8"
"github.com/Nwflower/reims-go/internal/console"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/thumb"
@@ -50,10 +52,13 @@ func (a *App) computerUseHostHandlers(mgr *plugin.Manager, pluginID string) map[
return map[string]plugin.RPCRequestHandler{
"host/vm.list": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.list", a.handleComputerUseVMList),
"host/vm.get": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.get", a.handleComputerUseVMGet),
"host/vm.telemetry": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.telemetry", a.handleComputerUseVMTelemetry),
"host/vm.start": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.start", a.handleComputerUseVMStart),
"host/vm.shutdown": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.shutdown", a.handleComputerUseVMShutdown),
"host/vm.suspend": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.suspend", a.handleComputerUseVMStateChange("host/vm.suspend", a.SuspendVM)),
"host/vm.resume": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.resume", a.handleComputerUseVMStateChange("host/vm.resume", a.ResumeVM)),
"host/vm.restart": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.restart", a.handleComputerUseVMRestart),
"host/vm.finishInstall": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.finishInstall", a.handleComputerUseVMFinishInstall),
"host/vm.clone": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.clone", a.handleComputerUseVMClone),
"host/vm.delete": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.delete", a.handleComputerUseVMDelete),
"host/vm.snapshot.list": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList),
@@ -81,17 +86,18 @@ func (a *App) handleComputerUseTypeSecret(ctx context.Context, raw json.RawMessa
if err != nil {
return nil, err
}
if strings.TrimSpace(req.Setting) == "" {
settingName := strings.TrimSpace(req.Setting)
if settingName == "" {
return nil, errors.New("secret setting name is required")
}
vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
vm, route, err := a.resolveComputerUseVM(ctx, mgr, pluginID, req.VM, true)
if err != nil {
return nil, err
}
if mgr == nil {
return nil, errors.New("plugin manager is unavailable")
}
secret, err := a.computerUseSecretSetting(mgr, pluginID, vm, req.Setting)
secret, err := a.computerUseSecretSetting(mgr, pluginID, vm, settingName)
if err != nil {
if errors.Is(err, plugin.ErrSecretEmpty) {
return nil, a.computerUseHostError("secret_missing", "err.computer_use.secret_missing", i18n.Vars{"name": vm.Name})
@@ -99,22 +105,28 @@ func (a *App) handleComputerUseTypeSecret(ctx context.Context, raw json.RawMessa
return nil, err
}
defer func() { secret = "" }()
if len(secret) == 0 || utf8.RuneCountInString(secret) > computerUseMaxTextRunes {
runeCount := utf8.RuneCountInString(secret)
if len(secret) == 0 || runeCount > computerUseMaxTextRunes {
return nil, errors.New("secret must contain between 1 and 4000 characters")
}
callCtx, cancelCall := a.withSessionContext(ctx, vm.Ref().Key())
defer cancelCall()
var count int
if route.kind == consoleRouteDriver {
count, err = route.console.ConsoleType(ctx, vm.Name, secret)
count, err = route.console.ConsoleType(callCtx, vm.Name, secret)
} else {
service, svcErr := a.computerUseService()
if svcErr != nil {
return nil, svcErr
}
count, err = service.TypeText(ctx, vm.Directory, secret, nil)
count, err = service.TypeText(callCtx, vm.Directory, secret, nil)
}
if err != nil {
return nil, err
}
if mgr.Broker() != nil {
mgr.Broker().Audit(pluginID, "TYPE_SECRET", fmt.Sprintf("setting=%s len=%d", settingName, runeCount))
}
return pluginproto.CharactersResult{Characters: count}, nil
}
@@ -230,6 +242,218 @@ func (a *App) handleComputerUseVMStateChange(method string, change func(driverID
}
}
func (a *App) handleComputerUseVMRestart(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.VMRestartParams](mgr, pluginID, "host/vm.restart", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
if err := a.checkUserTakeover(vm.Ref().Key(), vm.Name); err != nil {
return nil, err
}
phase, err := a.effectiveVMPhaseStrict(vm)
if err != nil {
return nil, err
}
if phase == driver.PhaseInstaller || phase == driver.PhaseRecovery {
if err := a.authorizeProtectedPhase(ctx, mgr, pluginID, vm, phase, false, true); err != nil {
return nil, err
}
}
callCtx, cancel := a.withSessionContext(ctx, vm.Ref().Key())
defer cancel()
if err := callCtx.Err(); err != nil {
return nil, err
}
// macOS Setup Assistant & Login Window ignore ACPI powerdown for the full
// 90s stop_timeout_secs; cap graceful shutdown for built-in macOS restarts
// triggered by automation so Stage 4 restarts in ~10s instead of stalling 90s.
if vm.DriverID == driver.BuiltinReimsMacOSDriverID {
grace := 10 * time.Second
if req.GracefulTimeoutSec > 0 && req.GracefulTimeoutSec <= 90 {
grace = time.Duration(req.GracefulTimeoutSec) * time.Second
}
if err := a.beginVMStart(); err != nil {
return nil, err
}
defer a.vmStarts.Done()
if _, err := a.restartMacOSVMWithGrace(callCtx, vm.Name, grace); err != nil {
return nil, err
}
} else if err := a.RestartVM(vm.DriverID, vm.Name); err != nil {
return nil, err
}
a.wakePoll()
pid := int(a.rebindAgentSessionAfterRestart(vm.Ref().Key()))
if pid == 0 {
if polled, ok := a.polledVMForDriver(vm.DriverID, vm.Name); ok && polled.PID != nil {
pid = *polled.PID
}
}
return map[string]any{"ok": true, "vm": vm.Ref().Key(), "pid": pid}, nil
}
func (a *App) handleComputerUseVMFinishInstall(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, "host/vm.finishInstall", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
if err := a.checkUserTakeover(vm.Ref().Key(), vm.Name); err != nil {
return nil, err
}
phase, err := a.effectiveVMPhaseStrict(vm)
if err != nil {
return nil, err
}
if phase == driver.PhaseInstaller || phase == driver.PhaseRecovery {
if err := a.authorizeProtectedPhase(ctx, mgr, pluginID, vm, phase, false, true); err != nil {
return nil, err
}
}
callCtx, cancel := a.withSessionContext(ctx, vm.Ref().Key())
defer cancel()
commitGuideHandoff := a.prepareInstallGuideFinishHandoff(vm)
livePID := 0
if polled, ok := a.polledVMForDriver(vm.DriverID, vm.Name); ok && polled.State == "running" && polled.PID != nil && *polled.PID > 0 {
livePID = *polled.PID
}
a.mu.Lock()
svc := a.lifecycleSvc
a.mu.Unlock()
if svc == nil {
if err := a.FinishInstall(vm.Name); err != nil {
return nil, err
}
commitGuideHandoff(livePID > 0, livePID)
a.markAgentSessionFinishInstallDone(vm.Ref().Key())
if !a.hasActiveAgentSession(vm.Ref().Key()) {
a.markInstallGuideRecheck(vm.Name)
}
return map[string]any{"ok": true, "vm": vm.Ref().Key()}, nil
}
var out any
err = a.withComputerUseVM(callCtx, vm.Directory, func(opCtx context.Context) error {
var invokeErr error
out, invokeErr = svc.InvokeAction(opCtx, vm.Ref(), "finish_install", nil)
return invokeErr
})
if err != nil {
return nil, err
}
result, _ := out.(map[string]any)
if result == nil {
result = map[string]any{}
}
running, hasRunning := result["running"].(bool)
if !hasRunning {
running = livePID > 0
}
a.applyFinishInstallResult(vm.DriverID, vm.Name, result)
commitGuideHandoff(running, livePID)
a.markAgentSessionFinishInstallDone(vm.Ref().Key())
result["ok"] = true
result["vm"] = vm.Ref().Key()
if !a.hasActiveAgentSession(vm.Ref().Key()) {
a.markInstallGuideRecheck(vm.Name)
}
a.wakePoll()
if a.hasActiveAgentSession(vm.Ref().Key()) {
go a.refreshActiveAgentSessionAfterStart(vm.Ref().Key())
}
a.emitStateChanged()
return result, nil
}
func (a *App) handleComputerUseVMTelemetry(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, "host/vm.telemetry", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
key := vm.Ref().Key()
pid := 0
state := vm.State
if polled, ok := a.polledVMForDriver(vm.DriverID, vm.Name); ok {
state = polled.State
if polled.PID != nil {
pid = *polled.PID
}
if vm.Directory == "" {
vm.Directory = polled.Dir
}
}
phase := a.effectiveVMPhase(vm)
var milestones []telemetryMilestone
var qemuErrors []string
var diskBytes, diskDelta int64
cpuPct := -1.0
coldReboots := 0
var updatedAt string
a.telemetryMu.Lock()
if st := a.vmTelemetry[key]; st != nil {
milestones = make([]telemetryMilestone, 0, len(st.milestones))
for _, m := range st.milestones {
milestones = append(milestones, m)
}
sort.Slice(milestones, func(i, j int) bool { return milestones[i].Key < milestones[j].Key })
qemuErrors = make([]string, 0, len(st.qemuErrors))
for _, line := range st.qemuErrors {
qemuErrors = append(qemuErrors, host.RedactText(line))
}
diskBytes = st.diskBytes
diskDelta = st.diskDeltaBytes
cpuPct = st.cpuPercent
coldReboots = st.coldRebootCount
if !st.updatedAt.IsZero() {
updatedAt = st.updatedAt.UTC().Format(time.RFC3339)
}
}
a.telemetryMu.Unlock()
if vm.Directory != "" && a.hasProvisionReadyMarker(vm.Directory) {
hasReady := false
for _, m := range milestones {
if m.Key == "serial:provision_ready" {
hasReady = true
break
}
}
if !hasReady {
milestones = append(milestones, telemetryMilestone{Key: "serial:provision_ready", Count: 1})
sort.Slice(milestones, func(i, j int) bool { return milestones[i].Key < milestones[j].Key })
}
}
if diskBytes == 0 && vm.Directory != "" {
diskBytes = fileSizeBytes(filepath.Join(vm.Directory, "disk.qcow2"))
}
return map[string]any{
"vm": key,
"state": state,
"phase": phase,
"pid": pid,
"boot_milestones": milestones,
"qemu_errors": qemuErrors,
"disk_bytes": diskBytes,
"disk_delta_bytes": diskDelta,
"cpu_percent": cpuPct,
"cold_reboot_count": coldReboots,
"updated_at": updatedAt,
}, nil
}
func (a *App) handleComputerUseVMClone(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.VMCloneParams](mgr, pluginID, "host/vm.clone", raw)
if err != nil {
@@ -362,14 +586,18 @@ func (a *App) handleComputerUseVMSnapshotRestore(_ context.Context, raw json.Raw
// resolveComputerUseVM returns the VM and the console route Agent calls use.
// A VM whose driver serves its own console needs no host process; every other
// VM must be a running QMP-reachable process.
func (a *App) resolveComputerUseVM(mgr *plugin.Manager, pluginID, ref string) (driver.VMInfo, consoleRoute, error) {
// VM must be a running QMP-reachable process. It enforces #105 protected-phase
// confirmation and, for write operations, #103 session visibility and user takeover.
func (a *App) resolveComputerUseVM(ctx context.Context, mgr *plugin.Manager, pluginID, ref string, isWrite bool) (driver.VMInfo, consoleRoute, error) {
ref = strings.TrimSpace(ref)
if ref == "" {
return driver.VMInfo{}, consoleRoute{}, errors.New("VM reference is required")
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, ref)
if err != nil {
if strings.Contains(err.Error(), "not_authorized") {
a.abortAgentSessionForVMRef(mgr, pluginID, ref, "permission_denied", false)
}
return driver.VMInfo{}, consoleRoute{}, err
}
// A plugin that stopped calling mid-hold must not leave a key down.
@@ -388,6 +616,11 @@ func (a *App) resolveComputerUseVM(mgr *plugin.Manager, pluginID, ref string) (d
a.forgetHeld(pluginID, vm.Ref().Key())
return driver.VMInfo{}, consoleRoute{}, a.computerUseHostError("vm_not_running", "err.computer_use.vm_not_running", i18n.Vars{"name": vm.Name})
}
livePID := uint32(0)
if current.PID != nil && *current.PID > 0 {
livePID = uint32(*current.PID)
a.bindAgentSessionPID(vm.Ref().Key(), livePID)
}
if vm.Phase == "" {
if pr, ok := a.driverFor(vm).(driver.PhaseReporter); ok {
pctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
@@ -402,9 +635,20 @@ func (a *App) resolveComputerUseVM(mgr *plugin.Manager, pluginID, ref string) (d
vm.Phase = phase
}
}
if phase := computerUseVMPhase(vm); phase != "normal" {
phaseLabel := i18n.M(a.computerUseLocale(), "err.computer_use.phase."+phase, nil)
return driver.VMInfo{}, consoleRoute{}, a.computerUseHostError("confirmation_required", "err.computer_use.phase_confirmation", i18n.Vars{"name": vm.Name, "phase": phaseLabel})
phase := computerUseVMPhase(vm)
if phase != driver.PhaseNormal {
if err := a.authorizeProtectedPhase(ctx, mgr, pluginID, vm, phase, false, false); err != nil {
return driver.VMInfo{}, consoleRoute{}, err
}
}
if isWrite {
a.ensureAgentSessionForWrite(mgr, pluginID, vm)
if livePID > 0 {
a.bindAgentSessionPID(vm.Ref().Key(), livePID)
}
if err := a.checkUserTakeover(vm.Ref().Key(), vm.Name); err != nil {
return driver.VMInfo{}, consoleRoute{}, err
}
}
if vm.Directory == "" {
vm.Directory = current.Dir
@@ -433,16 +677,16 @@ func (a *App) computerUseHostError(code, key string, params i18n.Vars) error {
func (a *App) computerUseLocale() i18n.Locale {
a.mu.Lock()
defer a.mu.Unlock()
loc := i18n.ZhCN
raw := i18n.ZhCN
if a.cfg != nil {
loc = a.cfg.Locale
raw = a.cfg.Locale
}
return loc
a.mu.Unlock()
return i18n.EffectiveLocale(raw)
}
func (a *App) computerUseVMAccessEnabled(mgr *plugin.Manager, pluginID, vmKey string) bool {
return computerUseVMAccessEnabled(mgr, pluginID, vmKey) || a.computerUseOwned(pluginID, vmKey)
return computerUseVMAccessEnabled(mgr, pluginID, vmKey) || a.computerUseOwned(pluginID, vmKey) || a.hasEphemeralVMAccess(pluginID, vmKey)
}
func (a *App) computerUseOwned(pluginID, vmKey string) bool {
@@ -814,45 +1058,101 @@ func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessa
if err != nil {
return nil, err
}
maxWidth := computerUseScreenshotWidth(req.MaxWidth)
outFormat := strings.ToLower(strings.TrimSpace(req.Format))
if outFormat == "" {
outFormat = "jpeg"
}
if outFormat != "jpeg" && outFormat != "png" {
return nil, fmt.Errorf("unsupported screenshot format %q (want jpeg or png)", req.Format)
}
if req.Region != nil && (req.Region.Width <= 0 || req.Region.Height <= 0) {
return nil, errors.New("region width and height must be positive")
}
_, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
if req.MaxEdge != nil && (*req.MaxEdge < 0 || *req.MaxEdge > 16384) {
return nil, fmt.Errorf("invalid max_edge %d", *req.MaxEdge)
}
maxWidth := computerUseScreenshotWidth(req.MaxWidth)
vm, route, err := a.resolveComputerUseVM(ctx, mgr, pluginID, req.VM, false)
if err != nil {
return nil, err
}
callCtx, cancelCall := a.withSessionContext(ctx, vm.Ref().Key())
defer cancelCall()
// A region is cut from the full-resolution frame, so the driver must not
// shrink it first.
captureEdge := maxWidth
if req.MaxEdge != nil {
captureEdge = *req.MaxEdge
}
if req.Region != nil {
captureEdge = 0
}
path, format, cleanup, err := a.consoleCapture(ctx, route, captureEdge)
path, frameFormat, cleanup, err := a.consoleCapture(callCtx, route, captureEdge)
if err != nil {
return nil, err
}
defer cleanup()
sourceSize, err := thumb.Size(path, format)
sourceSize, err := thumb.Size(path, frameFormat)
if err != nil {
return nil, err
}
var (
frame image.Image
blank bool
)
result := pluginproto.ScreenshotResult{
MIMEType: "image/jpeg", SourceWidth: sourceSize.X, SourceHeight: sourceSize.Y,
mimeType := "image/jpeg"
if outFormat == "png" {
mimeType = "image/png"
}
if req.Region == nil {
// A blank frame is a normal screen state during boot, login and display
// switches. Return it with a flag so pollers can keep waiting through it.
frame, blank, err = thumb.LoadPreviewFrame(path, format, maxWidth)
result := pluginproto.ScreenshotResult{
MIMEType: mimeType, SourceWidth: sourceSize.X, SourceHeight: sourceSize.Y,
}
if req.MaxEdge != nil {
var cropRect *image.Rectangle
if req.Region != nil {
mapped := computerUseRegionToSource(computerUseRegion{
X: req.Region.X, Y: req.Region.Y, Width: req.Region.Width, Height: req.Region.Height,
}, req.Width, req.Height, sourceSize)
r := image.Rect(mapped.X, mapped.Y, mapped.X+mapped.Width, mapped.Y+mapped.Height)
cropRect = &r
}
var actualCrop image.Rectangle
frame, actualCrop, blank, err = thumb.LoadRegionFrame(path, frameFormat, cropRect, *req.MaxEdge)
if err != nil {
return nil, err
}
if cropRect != nil {
result.Region = &pluginproto.Region{
X: actualCrop.Min.X, Y: actualCrop.Min.Y,
Width: actualCrop.Dx(), Height: actualCrop.Dy(),
}
}
} else if req.Region == nil {
// A blank frame is a normal screen state during boot, login and display
// switches. Return it with a flag so pollers can keep waiting through it.
frame, blank, err = thumb.LoadPreviewFrame(path, frameFormat, maxWidth)
if err != nil {
return nil, err
}
} else if req.MaxWidth == 0 && outFormat == "png" {
mapped := computerUseRegionToSource(computerUseRegion{
X: req.Region.X, Y: req.Region.Y, Width: req.Region.Width, Height: req.Region.Height,
}, req.Width, req.Height, sourceSize)
r := image.Rect(mapped.X, mapped.Y, mapped.X+mapped.Width, mapped.Y+mapped.Height)
var actualCrop image.Rectangle
frame, actualCrop, blank, err = thumb.LoadRegionFrame(path, frameFormat, &r, 0)
if err != nil {
return nil, err
}
result.Region = &pluginproto.Region{
X: actualCrop.Min.X, Y: actualCrop.Min.Y,
Width: actualCrop.Dx(), Height: actualCrop.Dy(),
}
} else {
full, err := thumb.Load(path, format)
full, err := thumb.Load(path, frameFormat)
if err != nil {
return nil, err
}
@@ -868,7 +1168,12 @@ func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessa
blank = thumb.Blank(full)
result.Region = &pluginproto.Region{X: applied.X, Y: applied.Y, Width: applied.Width, Height: applied.Height}
}
encoded, err := thumb.JPEG(frame, 84)
var encoded []byte
if outFormat == "png" {
encoded, err = thumb.PNG(frame)
} else {
encoded, err = thumb.JPEG(frame, 84)
}
if err != nil {
return nil, err
}
@@ -891,10 +1196,12 @@ func (a *App) handleComputerUsePointer(ctx context.Context, raw json.RawMessage,
if err != nil {
return nil, err
}
vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
vm, route, err := a.resolveComputerUseVM(ctx, mgr, pluginID, req.VM, true)
if err != nil {
return nil, err
}
callCtx, cancelCall := a.withSessionContext(ctx, vm.Ref().Key())
defer cancelCall()
// A button left down stays down in the guest until a release arrives, so
// the host records it on both console kinds and can lift it if the plugin
// goes away.
@@ -910,7 +1217,7 @@ func (a *App) handleComputerUsePointer(ctx context.Context, raw json.RawMessage,
a.noteHeldButton(pluginID, vm.Ref().Key(), button, true)
}
}
if err := a.consolePointer(ctx, route, driver.ConsolePointerRequest{
if err := a.consolePointer(callCtx, route, driver.ConsolePointerRequest{
Action: req.Action, X: req.X, Y: req.Y, Width: req.Width, Height: req.Height,
Button: req.Button, Down: req.Down, Delta: req.Delta, Horizontal: req.Horizontal,
}); err != nil {
@@ -930,12 +1237,14 @@ func (a *App) handleComputerUseKey(ctx context.Context, raw json.RawMessage, mgr
if strings.TrimSpace(req.Key) == "" {
return nil, errors.New("key is required")
}
vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
vm, route, err := a.resolveComputerUseVM(ctx, mgr, pluginID, req.VM, true)
if err != nil {
return nil, err
}
callCtx, cancelCall := a.withSessionContext(ctx, vm.Ref().Key())
defer cancelCall()
if req.Down == nil {
if err := a.consoleKey(ctx, route, req.Key, req.Modifiers); err != nil {
if err := a.consoleKey(callCtx, route, req.Key, req.Modifiers); err != nil {
return nil, err
}
return pluginproto.OKResult{OK: true}, nil
@@ -959,7 +1268,7 @@ func (a *App) handleComputerUseKey(ctx context.Context, raw json.RawMessage, mgr
}
}
for _, code := range codes {
if err := a.consoleKeyState(ctx, route, code, *req.Down); err != nil {
if err := a.consoleKeyState(callCtx, route, code, *req.Down); err != nil {
return nil, err
}
}
@@ -978,7 +1287,7 @@ func (a *App) handleComputerUseRelease(ctx context.Context, raw json.RawMessage,
if err != nil {
return nil, err
}
vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
vm, route, err := a.resolveComputerUseVM(ctx, mgr, pluginID, req.VM, false)
if err != nil {
return nil, err
}
@@ -1008,7 +1317,7 @@ func (a *App) handleComputerUseType(ctx context.Context, raw json.RawMessage, mg
if utf8.RuneCountInString(req.Text) > computerUseMaxTextRunes {
return nil, fmt.Errorf("text exceeds %d characters", computerUseMaxTextRunes)
}
vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
vm, route, err := a.resolveComputerUseVM(ctx, mgr, pluginID, req.VM, true)
if err != nil {
return nil, err
}
@@ -1018,6 +1327,11 @@ func (a *App) handleComputerUseType(ctx context.Context, raw json.RawMessage, mg
return nil, err
}
}
callCtx, cancelCall := a.withSessionContext(ctx, vm.Ref().Key())
defer cancelCall()
if err := callCtx.Err(); err != nil {
return nil, err
}
n, err := a.injectTextIntoVMForDriver(vm.DriverID, vm.Name, vm.Directory, req.Text, false, true)
if err != nil {
return nil, err
+744
View File
@@ -0,0 +1,744 @@
package app
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
var (
confirmPromptTimeout = 2 * time.Minute
protectedPhaseDenialCooldown = 30 * time.Second
)
// ConfirmResolvedEvent notifies the desktop window when a pending confirmation
// prompt closes (answered, timed out, or canceled) so stale modals never linger.
type ConfirmResolvedEvent struct {
ID string `json:"id"`
Reason string `json:"reason,omitempty"`
}
// ConfirmPrompt describes a host-native confirmation dialog shown for
// `host/ui.confirm`, #105 protected-phase authorization, or custom download mirrors.
type ConfirmPrompt struct {
ID string `json:"id"`
Kind string `json:"kind"` // "generic" | "protected_phase" | "custom_mirror"
PluginID string `json:"plugin_id"`
PluginName string `json:"plugin_name"`
Publisher string `json:"publisher,omitempty"`
Trust string `json:"trust,omitempty"`
VM string `json:"vm,omitempty"`
VMName string `json:"vm_name,omitempty"`
Phase string `json:"phase,omitempty"`
Title string `json:"title"`
Message string `json:"message"`
ConfirmLabel string `json:"confirm_label,omitempty"`
CancelLabel string `json:"cancel_label,omitempty"`
Danger bool `json:"danger,omitempty"`
AllowDurationChoice bool `json:"allow_duration_choice,omitempty"`
DefaultDurationMin int `json:"default_duration_minutes,omitempty"`
PreferUntilPhaseExit bool `json:"prefer_until_phase_exit,omitempty"`
Origin string `json:"origin,omitempty"`
}
// ConfirmResolution carries the user's answer from the desktop confirmation dialog.
type ConfirmResolution struct {
Approved bool `json:"approved"`
DurationMinutes int `json:"duration_minutes,omitempty"`
UntilPhaseExit bool `json:"until_phase_exit,omitempty"`
Reason string `json:"reason,omitempty"`
}
type phaseGrantKey struct {
pluginID string
vmKey string
}
type protectedPhaseGrant struct {
pluginID string
vmKey string
phase string
grantedAt time.Time
expiresAt time.Time
untilPhaseExit bool
denied bool
}
func (g protectedPhaseGrant) isActive(now time.Time) bool {
if g.denied {
return false
}
if g.untilPhaseExit {
return true
}
return !g.expiresAt.IsZero() && now.Before(g.expiresAt)
}
func (g protectedPhaseGrant) isDeniedActive(now time.Time) bool {
if !g.denied {
return false
}
return g.expiresAt.IsZero() || now.Before(g.expiresAt)
}
func (g protectedPhaseGrant) remainingSeconds(now time.Time) int {
if !g.isActive(now) || g.untilPhaseExit {
return 0
}
rem := int(time.Until(g.expiresAt).Seconds())
if rem < 0 {
return 0
}
return rem
}
func (a *App) confirmHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
if mgr == nil || mgr.Broker() == nil {
return nil
}
broker := mgr.Broker()
return map[string]plugin.RPCRequestHandler{
"host/ui.confirm": a.hostAPISvc().hostMethod(mgr, pluginID, "host/ui.confirm", func(ctx context.Context, raw json.RawMessage) (any, error) {
req, err := decodeHostParams[pluginproto.ConfirmParams](mgr, pluginID, "host/ui.confirm", raw)
if err != nil {
return nil, err
}
if strings.TrimSpace(req.Title) == "" && strings.TrimSpace(req.Message) == "" {
return nil, errors.New("title or message is required")
}
kind := "generic"
var vmKeyStr, vmName string
if strings.TrimSpace(req.VM) != "" {
if info, err := a.resolveComputerUseVMInfo(req.VM); err == nil {
vmKeyStr = info.Ref().Key()
vmName = info.Name
} else {
vmKeyStr = strings.TrimSpace(req.VM)
vmName = vmNameFromKey(vmKeyStr)
}
}
phase := strings.TrimSpace(req.ProtectedPhase)
var prompt ConfirmPrompt
if phase == driver.PhaseInstaller || phase == driver.PhaseRecovery {
if strings.TrimSpace(req.VM) == "" {
return nil, errors.New("vm is required for protected_phase confirmation")
}
vmInfo, err := a.resolveComputerUseVMInfo(req.VM)
if err != nil {
return nil, err
}
kind = "protected_phase"
vmKeyStr = vmInfo.Ref().Key()
vmName = vmInfo.Name
// Never allow plugins to spoof the #105 protected-phase dialog title,
// message, button labels, or danger flag; always render the host's
// canonical warning prompt.
prompt = a.buildProtectedPhasePrompt(pluginID, vmInfo, phase, req.PreferUntilPhaseExit)
if req.DefaultDurationMin > 0 {
prompt.DefaultDurationMin = req.DefaultDurationMin
}
} else {
prompt = ConfirmPrompt{
Kind: kind,
VM: vmKeyStr,
VMName: vmName,
Phase: phase,
Title: strings.TrimSpace(req.Title),
Message: strings.TrimSpace(req.Message),
ConfirmLabel: strings.TrimSpace(req.ConfirmLabel),
CancelLabel: strings.TrimSpace(req.CancelLabel),
Danger: req.Danger,
AllowDurationChoice: req.AllowDurationChoice,
DefaultDurationMin: req.DefaultDurationMin,
PreferUntilPhaseExit: req.PreferUntilPhaseExit,
}
}
res, err := a.requestHostConfirm(ctx, broker, mgr.Registry(), pluginID, prompt)
if err != nil {
if kind == "protected_phase" && vmKeyStr != "" {
a.handlePluginPermissionDeniedForVM(mgr, pluginID, vmKeyStr, vmName, "confirmation_denied")
}
return nil, err
}
if kind == "protected_phase" && vmKeyStr != "" {
if res.Approved {
a.recordProtectedPhaseGrant(broker, pluginID, vmKeyStr, phase, res.DurationMinutes, res.UntilPhaseExit)
} else {
a.recordProtectedPhaseDenial(mgr, broker, pluginID, vmKeyStr, vmName, phase)
}
}
return pluginproto.ConfirmResult{
Approved: res.Approved,
DurationMinutes: res.DurationMinutes,
UntilPhaseExit: res.UntilPhaseExit,
Reason: res.Reason,
}, nil
}),
}
}
func (a *App) requestHostConfirm(ctx context.Context, broker *plugin.Broker, reg *plugin.Registry, pluginID string, prompt ConfirmPrompt) (ConfirmResolution, error) {
a.mu.Lock()
emit := a.confirmEmit
dismiss := a.confirmDismiss
hasWindow := a.ctx != nil
locale := i18n.EffectiveLocale(i18n.Auto)
if a.cfg != nil {
locale = i18n.EffectiveLocale(a.cfg.Locale)
}
a.mu.Unlock()
if emit == nil && !hasWindow {
return ConfirmResolution{}, errors.New("confirmation_unavailable: the desktop window is required to confirm this action")
}
prompt.PluginID = pluginID
if prompt.PluginName == "" {
prompt.PluginName = pluginID
}
if reg != nil {
if info, found := reg.Info(pluginID); found {
if name := strings.TrimSpace(info.Name.Get(string(locale))); name != "" {
prompt.PluginName = name
}
prompt.Publisher = info.Publisher
prompt.Trust = string(info.Trust)
}
}
ch := make(chan ConfirmResolution, 1)
a.confirmMu.Lock()
if a.confirmPending == nil {
a.confirmPending = map[string]chan ConfirmResolution{}
}
a.confirmSeq++
prompt.ID = fmt.Sprintf("confirm-%d", a.confirmSeq)
a.confirmPending[prompt.ID] = ch
a.confirmMu.Unlock()
dismissed := false
clearPrompt := func(reason string) {
a.confirmMu.Lock()
delete(a.confirmPending, prompt.ID)
a.confirmMu.Unlock()
if dismissed {
return
}
dismissed = true
if dismiss != nil {
dismiss(prompt.ID, reason)
} else if emit == nil {
a.emit("reims:confirm-resolved", ConfirmResolvedEvent{ID: prompt.ID, Reason: reason})
}
}
defer clearPrompt("canceled")
if emit != nil {
emit(prompt)
} else {
a.showMainWindow()
a.emit("reims:confirm-request", prompt)
}
timer := time.NewTimer(confirmPromptTimeout)
defer timer.Stop()
select {
case res, open := <-ch:
if !open {
clearPrompt("canceled")
return ConfirmResolution{Approved: false, Reason: "canceled"}, nil
}
reason := res.Reason
if reason == "" {
if res.Approved {
reason = "approved"
} else {
reason = "denied"
}
}
clearPrompt(reason)
return res, nil
case <-ctx.Done():
clearPrompt("canceled")
return ConfirmResolution{Approved: false, Reason: "canceled"}, ctx.Err()
case <-timer.C:
clearPrompt("timeout")
if broker != nil {
broker.Audit(pluginID, "CONFIRM_TIMEOUT", prompt.Kind)
}
return ConfirmResolution{Approved: false, Reason: "timeout"}, nil
}
}
// ResolveConfirmRequest delivers the user's answer to a pending host confirmation dialog.
func (a *App) ResolveConfirmRequest(id string, approved bool, durationMinutes int, untilPhaseExit bool) error {
if approved && !untilPhaseExit && durationMinutes <= 0 {
durationMinutes = 30
}
a.confirmMu.Lock()
ch, ok := a.confirmPending[id]
if !ok {
a.confirmMu.Unlock()
return errors.New("confirmation request has expired or was already resolved")
}
delete(a.confirmPending, id)
select {
case ch <- ConfirmResolution{
Approved: approved,
DurationMinutes: durationMinutes,
UntilPhaseExit: untilPhaseExit,
}:
default:
}
a.confirmMu.Unlock()
return nil
}
func (a *App) cancelPendingConfirmations() {
a.confirmMu.Lock()
pending := a.confirmPending
a.confirmPending = nil
a.protectedPhaseGrants = nil
a.protectedPhaseInFlight = nil
a.confirmMu.Unlock()
a.mu.Lock()
emit := a.confirmEmit
dismiss := a.confirmDismiss
a.mu.Unlock()
for id, ch := range pending {
close(ch)
if dismiss != nil {
dismiss(id, "canceled")
} else if emit == nil {
a.emit("reims:confirm-resolved", ConfirmResolvedEvent{ID: id, Reason: "canceled"})
}
}
}
func normalizeGrantDuration(minutes int) time.Duration {
switch minutes {
case 10, 30, 60:
return time.Duration(minutes) * time.Minute
default:
if minutes <= 0 {
return 30 * time.Minute
}
if minutes > 120 {
return 120 * time.Minute
}
return time.Duration(minutes) * time.Minute
}
}
func (a *App) recordProtectedPhaseGrant(broker *plugin.Broker, pluginID, vmKey, phase string, durationMinutes int, untilPhaseExit bool) {
now := time.Now()
grant := protectedPhaseGrant{
pluginID: pluginID,
vmKey: vmKey,
phase: phase,
grantedAt: now,
untilPhaseExit: untilPhaseExit,
}
if !untilPhaseExit {
grant.expiresAt = now.Add(normalizeGrantDuration(durationMinutes))
}
a.confirmMu.Lock()
if a.protectedPhaseGrants == nil {
a.protectedPhaseGrants = map[phaseGrantKey]protectedPhaseGrant{}
}
a.protectedPhaseGrants[phaseGrantKey{pluginID: pluginID, vmKey: vmKey}] = grant
a.confirmMu.Unlock()
if broker != nil {
scope := fmt.Sprintf("%s:%dm", phase, durationMinutes)
if untilPhaseExit {
scope = phase + ":until_phase_exit"
}
broker.Audit(pluginID, "PHASE_AUTH_GRANTED", vmKey+" "+scope)
}
a.refreshAgentSessionVisuals(vmKey)
}
func (a *App) recordProtectedPhaseDenial(mgr *plugin.Manager, broker *plugin.Broker, pluginID, vmKey, vmName, phase string) {
now := time.Now()
a.confirmMu.Lock()
if a.protectedPhaseGrants == nil {
a.protectedPhaseGrants = map[phaseGrantKey]protectedPhaseGrant{}
}
a.protectedPhaseGrants[phaseGrantKey{pluginID: pluginID, vmKey: vmKey}] = protectedPhaseGrant{
pluginID: pluginID,
vmKey: vmKey,
phase: phase,
grantedAt: now,
expiresAt: now.Add(protectedPhaseDenialCooldown),
denied: true,
}
a.confirmMu.Unlock()
if broker != nil {
broker.Audit(pluginID, "PHASE_AUTH_DENIED", vmKey+" "+phase)
}
a.handlePluginPermissionDeniedForVM(mgr, pluginID, vmKey, vmName, "confirmation_denied")
}
// grantProtectedPhase records an in-memory #105 authorization directly from a
// host-owned confirmation UI (for example the auto-install preflight flow).
func (a *App) grantProtectedPhase(pluginID, vmKey, phase string, durationMinutes int, untilPhaseExit bool) {
var broker *plugin.Broker
a.mu.Lock()
if a.pluginMgr != nil {
broker = a.pluginMgr.Broker()
}
a.mu.Unlock()
if phase == "" {
phase = driver.PhaseInstaller
}
a.recordProtectedPhaseGrant(broker, pluginID, vmKey, phase, durationMinutes, untilPhaseExit)
}
func (a *App) lookupProtectedPhaseGrant(pluginID, vmKey string) (protectedPhaseGrant, bool) {
now := time.Now()
key := phaseGrantKey{pluginID: pluginID, vmKey: vmKey}
a.confirmMu.Lock()
defer a.confirmMu.Unlock()
g, ok := a.protectedPhaseGrants[key]
if !ok {
return protectedPhaseGrant{}, false
}
if g.denied && !g.isDeniedActive(now) {
delete(a.protectedPhaseGrants, key)
return protectedPhaseGrant{}, false
}
if !g.denied && !g.isActive(now) {
delete(a.protectedPhaseGrants, key)
return protectedPhaseGrant{pluginID: pluginID, vmKey: vmKey, phase: g.phase, expiresAt: g.expiresAt}, false
}
return g, true
}
func (a *App) revokeProtectedPhaseForPluginVM(pluginID, vmKey, reason string) {
a.confirmMu.Lock()
var revoked []protectedPhaseGrant
for k, g := range a.protectedPhaseGrants {
if k.vmKey == vmKey && (pluginID == "" || k.pluginID == pluginID) {
revoked = append(revoked, g)
delete(a.protectedPhaseGrants, k)
}
}
for k := range a.protectedPhaseInFlight {
if k.vmKey == vmKey && (pluginID == "" || k.pluginID == pluginID) {
delete(a.protectedPhaseInFlight, k)
}
}
a.confirmMu.Unlock()
var broker *plugin.Broker
a.mu.Lock()
if a.pluginMgr != nil {
broker = a.pluginMgr.Broker()
}
a.mu.Unlock()
if broker != nil {
for _, g := range revoked {
if !g.denied {
broker.Audit(g.pluginID, "PHASE_AUTH_REVOKED", vmKey+" "+reason)
}
}
}
}
func (a *App) revokeApprovedProtectedPhaseForPluginVM(pluginID, vmKey, reason string) {
a.confirmMu.Lock()
var revoked []protectedPhaseGrant
for k, g := range a.protectedPhaseGrants {
if k.vmKey == vmKey && (pluginID == "" || k.pluginID == pluginID) && !g.denied {
revoked = append(revoked, g)
delete(a.protectedPhaseGrants, k)
}
}
a.confirmMu.Unlock()
var broker *plugin.Broker
a.mu.Lock()
if a.pluginMgr != nil {
broker = a.pluginMgr.Broker()
}
a.mu.Unlock()
if broker != nil {
for _, g := range revoked {
broker.Audit(g.pluginID, "PHASE_AUTH_REVOKED", vmKey+" "+reason)
}
}
}
func (a *App) revokeProtectedPhaseForVM(vmKey, reason string) {
a.confirmMu.Lock()
var revoked []protectedPhaseGrant
for k, g := range a.protectedPhaseGrants {
if k.vmKey == vmKey {
revoked = append(revoked, g)
delete(a.protectedPhaseGrants, k)
}
}
for k := range a.protectedPhaseInFlight {
if k.vmKey == vmKey {
delete(a.protectedPhaseInFlight, k)
}
}
a.confirmMu.Unlock()
var broker *plugin.Broker
a.mu.Lock()
if a.pluginMgr != nil {
broker = a.pluginMgr.Broker()
}
a.mu.Unlock()
if broker != nil {
for _, g := range revoked {
if !g.denied {
broker.Audit(g.pluginID, "PHASE_AUTH_REVOKED", vmKey+" "+reason)
}
}
}
}
func (a *App) buildProtectedPhasePrompt(pluginID string, vm driver.VMInfo, phase string, preferUntilExit bool) ConfirmPrompt {
loc := a.computerUseLocale()
phaseLabel := i18n.M(loc, "err.computer_use.phase."+phase, nil)
return ConfirmPrompt{
Kind: "protected_phase",
PluginID: pluginID,
VM: vm.Ref().Key(),
VMName: vm.Name,
Phase: phase,
Title: i18n.M(loc, "confirm.phase.title", i18n.Vars{"phase": phaseLabel}),
Message: i18n.M(loc, "confirm.phase.message", i18n.Vars{"name": vm.Name, "phase": phaseLabel}),
ConfirmLabel: i18n.T(loc, "confirm.phase.allow"),
CancelLabel: i18n.T(loc, "confirm.phase.deny"),
Danger: true,
AllowDurationChoice: true,
DefaultDurationMin: 30,
PreferUntilPhaseExit: preferUntilExit,
}
}
// authorizeProtectedPhase enforces #105 for `installer` and `recovery` phases.
// When blocking is false (ordinary host/console.* calls), an unauthorized call
// triggers a native confirmation dialog asynchronously and returns
// `confirmation_required` immediately. When blocking is true (explicit
// host/session.begin requesting protected-phase auth), it waits for the user's
// decision and returns nil or `confirmation_denied`.
func (a *App) authorizeProtectedPhase(ctx context.Context, mgr *plugin.Manager, pluginID string, vm driver.VMInfo, phase string, blocking, preferUntilExit bool) error {
if phase != driver.PhaseInstaller && phase != driver.PhaseRecovery {
return nil
}
vmKeyStr := vm.Ref().Key()
var broker *plugin.Broker
var reg *plugin.Registry
if mgr != nil {
broker = mgr.Broker()
reg = mgr.Registry()
}
now := time.Now()
key := phaseGrantKey{pluginID: pluginID, vmKey: vmKeyStr}
a.confirmMu.Lock()
g, exists := a.protectedPhaseGrants[key]
if exists && g.denied && !g.isDeniedActive(now) {
delete(a.protectedPhaseGrants, key)
exists = false
} else if exists && !g.denied && !g.isActive(now) {
delete(a.protectedPhaseGrants, key)
exists = false
if broker != nil {
broker.Audit(pluginID, "PHASE_AUTH_EXPIRED", vmKeyStr+" "+g.phase)
}
}
a.confirmMu.Unlock()
if exists && g.isActive(now) && g.phase == phase {
return nil
}
if exists && g.denied && !blocking {
if a.hasActiveAgentSessionOwnedBy(vmKeyStr, pluginID) {
a.handlePluginPermissionDeniedForVM(mgr, pluginID, vmKeyStr, vm.Name, "confirmation_denied")
}
return a.computerUseHostError("confirmation_denied", "err.computer_use.phase_denied", i18n.Vars{"name": vm.Name})
}
prompt := a.buildProtectedPhasePrompt(pluginID, vm, phase, preferUntilExit)
if blocking {
res, err := a.requestHostConfirm(ctx, broker, reg, pluginID, prompt)
if err != nil {
a.handlePluginPermissionDeniedForVM(mgr, pluginID, vmKeyStr, vm.Name, "confirmation_denied")
return err
}
if res.Approved {
a.recordProtectedPhaseGrant(broker, pluginID, vmKeyStr, phase, res.DurationMinutes, res.UntilPhaseExit)
return nil
}
a.recordProtectedPhaseDenial(mgr, broker, pluginID, vmKeyStr, vm.Name, phase)
return a.computerUseHostError("confirmation_denied", "err.computer_use.phase_denied", i18n.Vars{"name": vm.Name})
}
// Non-blocking path: trigger at most one in-flight confirmation dialog per (plugin, VM).
a.confirmMu.Lock()
if a.protectedPhaseInFlight == nil {
a.protectedPhaseInFlight = map[phaseGrantKey]bool{}
}
alreadyInFlight := a.protectedPhaseInFlight[key]
if !alreadyInFlight {
a.protectedPhaseInFlight[key] = true
}
a.confirmMu.Unlock()
if !alreadyInFlight {
go func() {
defer func() {
a.confirmMu.Lock()
delete(a.protectedPhaseInFlight, key)
a.confirmMu.Unlock()
}()
res, err := a.requestHostConfirm(context.Background(), broker, reg, pluginID, prompt)
if err != nil {
a.handlePluginPermissionDeniedForVM(mgr, pluginID, vmKeyStr, vm.Name, "confirmation_denied")
return
}
if res.Approved {
a.recordProtectedPhaseGrant(broker, pluginID, vmKeyStr, phase, res.DurationMinutes, res.UntilPhaseExit)
} else {
a.recordProtectedPhaseDenial(mgr, broker, pluginID, vmKeyStr, vm.Name, phase)
}
}()
}
phaseLabel := i18n.M(a.computerUseLocale(), "err.computer_use.phase."+phase, nil)
return a.computerUseHostError("confirmation_required", "err.computer_use.phase_confirmation", i18n.Vars{"name": vm.Name, "phase": phaseLabel})
}
// trackVMPhaseTransitions compares current VM phases against the last observed
// values, broadcasts `vm/phaseChanged` to running Sidecars, and revokes
// protected-phase authorizations whenever a VM leaves installer/recovery or stops.
func (a *App) trackVMPhaseTransitions(vms []driver.VMListItem) {
a.mu.Lock()
var startingVMs map[string]bool
if len(a.transitions) > 0 {
startingVMs = make(map[string]bool, len(a.transitions))
for k, tr := range a.transitions {
if tr == "starting" || tr == "resuming" {
startingVMs[k] = true
}
}
}
a.mu.Unlock()
a.confirmMu.Lock()
if a.lastVMPhases == nil {
a.lastVMPhases = map[string]string{}
}
type transition struct {
vmKey, driverID, name, from, to string
stopped bool
}
var changes []transition
seen := map[string]bool{}
for _, vm := range vms {
key := vmKeyForDriver(vm.DriverID, vm.Name)
seen[key] = true
phase := strings.TrimSpace(vm.Phase)
if phase == "" {
phase = driver.PhaseNormal
}
prev, hadPrev := a.lastVMPhases[key]
if !hadPrev {
a.lastVMPhases[key] = phase
continue
}
if prev != phase {
a.lastVMPhases[key] = phase
changes = append(changes, transition{
vmKey: key, driverID: vm.DriverID, name: vm.Name,
from: prev, to: phase, stopped: vm.State != "running" && !startingVMs[key],
})
} else if vm.State == "stopped" || vm.State == "suspended" || vm.State == "broken" {
// Skip revoking grants while a VM is actively transitioning into start/resume
// (e.g. StartAutoInstall launching a stopped VM), otherwise ensure stopped VMs
// never keep stale in-memory phase grants alive.
if !(vm.State == "stopped" && startingVMs[key]) && a.hasProtectedPhaseGrantLocked(key) {
changes = append(changes, transition{
vmKey: key, driverID: vm.DriverID, name: vm.Name,
from: prev, to: phase, stopped: true,
})
}
}
}
var vanished []string
for key := range a.lastVMPhases {
if !seen[key] {
delete(a.lastVMPhases, key)
if a.hasProtectedPhaseGrantLocked(key) {
vanished = append(vanished, key)
}
}
}
a.confirmMu.Unlock()
for _, key := range vanished {
a.revokeProtectedPhaseForVM(key, "vm_removed")
}
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
for _, ch := range changes {
if ch.stopped {
a.revokeProtectedPhaseForVM(ch.vmKey, "vm_stopped")
} else if (ch.from == driver.PhaseInstaller || ch.from == driver.PhaseRecovery) && ch.to != ch.from {
a.revokeProtectedPhaseForVM(ch.vmKey, "left_protected_phase")
}
if ch.from != ch.to && mgr != nil {
mgr.NotifyRunningSidecars("vm/phaseChanged", map[string]any{
"vm": ch.vmKey,
"driver_id": ch.driverID,
"name": ch.name,
"from": ch.from,
"to": ch.to,
})
}
}
}
func (a *App) hasProtectedPhaseGrantLocked(vmKey string) bool {
for k, g := range a.protectedPhaseGrants {
if k.vmKey == vmKey && !g.denied {
return true
}
}
return false
}
// revokeProtectedPhaseForInactivePlugins removes any in-memory protected-phase
// grants held by plugins that are no longer active, even if they never opened
// an Agent session (e.g. read-only screenshot or host/ui.confirm grants).
func (a *App) revokeProtectedPhaseForInactivePlugins(reg *plugin.Registry, broker *plugin.Broker, reason string) {
if reg == nil {
return
}
var revoked []phaseGrantKey
a.confirmMu.Lock()
for k := range a.protectedPhaseGrants {
if !reg.IsActive(k.pluginID) {
delete(a.protectedPhaseGrants, k)
revoked = append(revoked, k)
}
}
a.confirmMu.Unlock()
if broker != nil {
for _, k := range revoked {
broker.Audit(k.pluginID, "PHASE_AUTH_REVOKED", k.vmKey+" "+reason)
}
}
}
+3 -3
View File
@@ -202,7 +202,7 @@ func TestAgentCallsOnADriverConsoleVMAskForConfirmationInProtectedPhases(t *test
const plugin = "reims.agent"
a.markComputerUseOwnedVM(plugin, ct.ref.Key(), true) // grants access without a plugin manager
vm, route, err := a.resolveComputerUseVM(nil, plugin, ct.ref.Key())
vm, route, err := a.resolveComputerUseVM(context.Background(), nil, plugin, ct.ref.Key(), false)
if err != nil || route.kind != consoleRouteDriver || vm.Name != "dev" {
t.Fatalf("a normal-phase driver console VM = %+v, %+v, %v", vm.Name, route.kind, err)
}
@@ -210,7 +210,7 @@ func TestAgentCallsOnADriverConsoleVMAskForConfirmationInProtectedPhases(t *test
if err := os.WriteFile(filepath.Join(ct.vmRoot, "dev", "phase"), []byte(phase), 0o644); err != nil {
t.Fatal(err)
}
if _, _, err := a.resolveComputerUseVM(nil, plugin, ct.ref.Key()); err == nil || !strings.Contains(err.Error(), "confirmation_required") {
if _, _, err := a.resolveComputerUseVM(context.Background(), nil, plugin, ct.ref.Key(), false); err == nil || !strings.Contains(err.Error(), "confirmation_required") {
t.Fatalf("phase %s: err = %v, want confirmation_required", phase, err)
}
}
@@ -218,7 +218,7 @@ func TestAgentCallsOnADriverConsoleVMAskForConfirmationInProtectedPhases(t *test
if err := os.WriteFile(filepath.Join(ct.vmRoot, "dev", "phase"), []byte("bogus"), 0o644); err != nil {
t.Fatal(err)
}
if _, _, err := a.resolveComputerUseVM(nil, plugin, ct.ref.Key()); err == nil {
if _, _, err := a.resolveComputerUseVM(context.Background(), nil, plugin, ct.ref.Key(), false); err == nil {
t.Fatal("a VM with an unreadable phase was treated as normal")
}
}
+107
View File
@@ -10,6 +10,7 @@ import (
"time"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/installer"
@@ -310,3 +311,109 @@ func (a *App) prepareCreateNetwork(ctx context.Context, c networkControlClient,
}
return ctx.Err()
}
// ProvisionRequest carries user-supplied first-boot macOS provisioning options.
// Password is only used in memory to derive SALTED-SHA512-PBKDF2 ShadowHashData
// and is never written to disk, vm.toml, or logs.
type ProvisionRequest struct {
FullName string `json:"full_name"`
AccountName string `json:"account_name"`
Password string `json:"password"`
Appearance string `json:"appearance,omitempty"`
SLAAccepted bool `json:"sla_accepted"`
InstallGuestTools *bool `json:"install_guest_tools,omitempty"`
}
// PrepareVMProvision builds the per-VM read-only REIMSPROV image inside the
// macOS VM directory so offline installation creates the local admin account
// (hash-only), skips Setup Assistant & Keyboard Setup Assistant, and optionally
// stages Guest Tools for first login.
func (a *App) PrepareVMProvision(name string, req ProvisionRequest) error {
password := req.Password
req.Password = ""
defer func() { password = "" }()
if err := a.requireMacOSEnabled(); err != nil {
return err
}
c, err := a.client()
if err != nil {
return err
}
det, err := c.Show(a.baseCtx(), name)
if err != nil {
return err
}
if strings.TrimSpace(det.Directory) == "" {
return fmt.Errorf("VM %q directory is unavailable", name)
}
if (det.State == "running" || det.State == "paused") && installer.HasProvisionImage(det.Directory) {
return fmt.Errorf("cannot overwrite existing REIMSPROV while VM %q is %s; stop the VM first", det.Name, det.State)
}
req.Password = password
return a.prepareVMProvisionForDir(det.Name, det.Directory, req)
}
func (a *App) hasVMProvisionDir(vmDir string) bool {
return installer.HasProvisionImage(vmDir)
}
func (a *App) hasProvisionReadyMarker(vmDir string) bool {
return installer.HasProvisionReadyMarker(vmDir)
}
func (a *App) writeProvisionReadyMarker(vmDir string) {
installer.WriteProvisionReadyMarker(vmDir)
}
func (a *App) prepareVMProvisionForDir(vmName, vmDir string, req ProvisionRequest) error {
password := req.Password
req.Password = ""
defer func() { password = "" }()
cfg := installer.ProvisionConfig{
FullName: req.FullName,
AccountName: req.AccountName,
Password: password,
Appearance: req.Appearance,
SLAAccepted: req.SLAAccepted,
}
if err := installer.ValidateProvisionConfig(&cfg); err != nil {
return err
}
installTools := req.InstallGuestTools == nil || *req.InstallGuestTools
if installTools {
if srv, port, gerr := a.ensureGuestToolsBridge(); gerr == nil && port > 0 {
unlock := a.lockGuestToolsVM(vmName)
gtCfg, cfgErr := guesttools.LoadOrCreateVMConfig(vmDir, vmName, a.vmSharedDir(vmName), port)
if cfgErr == nil && srv != nil {
validated, _ := a.validatedShareConfig(gtCfg)
srv.RegisterVM(validated)
}
unlock()
if cfgErr == nil {
for _, pf := range guesttools.ToolsProvisionFiles(gtCfg) {
cfg.GuestTools = append(cfg.GuestTools, installer.ProvisionGuestToolFile{
Name: pf.Name,
Mode: pf.Mode,
Data: pf.Data,
})
}
} else {
a.emitVMLog(vmName, "Warning: could not stage Guest Tools in REIMSPROV: "+cfgErr.Error())
}
} else if gerr != nil {
a.emitVMLog(vmName, "Warning: skipped Guest Tools in REIMSPROV because Guest Tools bridge is unavailable: "+gerr.Error())
} else {
a.emitVMLog(vmName, "Warning: skipped Guest Tools in REIMSPROV because Guest Tools bridge port is unavailable.")
}
}
if _, err := installer.BuildProvisionDiskImage(vmDir, cfg); err != nil {
return err
}
a.emitVMLog(vmName, "Prepared offline macOS provisioning disk (REIMSPROV) for "+vmName+".")
a.emitStateChanged()
return nil
}
+418 -55
View File
@@ -2,11 +2,17 @@ package app
import (
"archive/zip"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"maps"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"time"
@@ -14,8 +20,20 @@ import (
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/plugin"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/version"
)
type DiagnosticsExportResult struct {
Path string `json:"path"`
FileName string `json:"file_name"`
SizeBytes int64 `json:"size_bytes"`
TargetLabel string `json:"target_label"`
IncludedFiles []string `json:"included_files"`
SummaryText string `json:"summary_text"`
Findings []host.DiagnosticFinding `json:"findings"`
CanCopyFile bool `json:"can_copy_file"`
}
type diagnosticsBundle struct {
HostReport host.Report
Optimizations []host.Optimization
@@ -23,39 +41,101 @@ type diagnosticsBundle struct {
VMDetail any // legacy test/export payload; production uses VMInfo
VMInfo *driver.VMInfo
SerialLog string
SerialTruncated bool
QEMULog string
QEMUTruncated bool
AppLogs []string
PluginDiagnostics []plugin.DiagnosticsEntry
}
func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error {
if err := os.MkdirAll(filepath.Dir(zipPath), 0o755); err != nil {
return err
func writeDiagnosticsZip(reportsDir, label string, generatedAt time.Time, b diagnosticsBundle) (_ DiagnosticsExportResult, err error) {
if err := os.MkdirAll(reportsDir, 0o755); err != nil {
return DiagnosticsExportResult{}, err
}
f, err := os.Create(zipPath)
f, err := os.CreateTemp(reportsDir, fmt.Sprintf("reims-go-diag-%s-%s-*.zip", label, generatedAt.Local().Format("20060102-150405")))
if err != nil {
return err
return DiagnosticsExportResult{}, err
}
defer func() {
if err != nil {
err = errors.Join(err, os.Remove(f.Name()))
}
}()
zw := zip.NewWriter(f)
result, writeErr := writeDiagnosticsEntries(zw, label, generatedAt, b)
if err := errors.Join(writeErr, zw.Close(), f.Close()); err != nil {
return DiagnosticsExportResult{}, err
}
info, err := os.Stat(f.Name())
if err != nil {
return DiagnosticsExportResult{}, err
}
result.Path = f.Name()
result.FileName = info.Name()
result.SizeBytes = info.Size()
result.CanCopyFile = host.CanCopyFileToClipboard()
return result, nil
}
func writeDiagnosticsEntries(zw *zip.Writer, label string, generatedAt time.Time, b diagnosticsBundle) (DiagnosticsExportResult, error) {
appLogs := b.AppLogs
if b.VMInfo != nil {
appLogs = filterAppLogsForVM(appLogs, b.VMInfo.Ref())
}
result := DiagnosticsExportResult{
TargetLabel: label,
IncludedFiles: []string{},
Findings: host.AnalyzeDiagnostics(b.HostReport, b.QEMULog, b.SerialLog, appLogs),
}
redact := diagnosticsRedactor(b)
for i := range result.Findings {
result.Findings[i].Detail = redact(result.Findings[i].Detail)
}
addFile := func(name, content string) error {
w, err := zw.Create(name)
if err != nil {
return err
}
_, err = w.Write([]byte(host.RedactText(content)))
return err
if _, err := w.Write([]byte(content)); err != nil {
return err
}
result.IncludedFiles = append(result.IncludedFiles, name)
return nil
}
addJSON := func(name string, v any) error {
raw, err := json.MarshalIndent(v, "", " ")
raw, err := json.Marshal(v)
if err != nil {
return err
}
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.UseNumber()
var value any
if err := decoder.Decode(&value); err != nil {
return err
}
raw, err = json.MarshalIndent(redactDiagnosticsJSON(value, redact), "", " ")
if err != nil {
return err
}
return addFile(name, string(raw)+"\n")
}
rep := b.HostReport
rep.GPUs = slices.Clone(rep.GPUs)
for i := range rep.GPUs {
if rep.GPUs[i].VulkanICD != "" {
rep.GPUs[i].VulkanICD = "[redacted]"
}
}
if rep.RecommendedGPU != nil && rep.RecommendedGPU.VulkanICD != "" {
gpu := *rep.RecommendedGPU
gpu.VulkanICD = "[redacted]"
rep.RecommendedGPU = &gpu
}
hostSummary := map[string]any{
"generated_at": time.Now().UTC().Format(time.RFC3339),
"host": b.HostReport,
"generated_at": generatedAt.UTC().Format(time.RFC3339),
"host": rep,
"optimizations": b.Optimizations,
}
if code, detail := host.DiagnoseGPULog(b.QEMULog); code != "" {
@@ -65,74 +145,259 @@ func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error {
}
}
if err := addJSON("host-report.json", hostSummary); err != nil {
_ = zw.Close()
_ = f.Close()
return err
return DiagnosticsExportResult{}, err
}
if b.Runtime != nil {
if err := addJSON("runtime-manifest.json", b.Runtime.Manifest); err != nil {
_ = zw.Close()
_ = f.Close()
return err
return DiagnosticsExportResult{}, err
}
}
if b.VMDetail != nil {
if err := addJSON("vm-detail.json", b.VMDetail); err != nil {
_ = zw.Close()
_ = f.Close()
return err
return DiagnosticsExportResult{}, err
}
}
if b.VMInfo != nil {
if err := addJSON("vm-info.json", b.VMInfo); err != nil {
_ = zw.Close()
_ = f.Close()
return err
return DiagnosticsExportResult{}, err
}
}
if strings.TrimSpace(b.SerialLog) != "" {
if err := addFile("serial.log", b.SerialLog); err != nil {
_ = zw.Close()
_ = f.Close()
return err
if err := addFile("serial.log", redact(b.SerialLog)); err != nil {
return DiagnosticsExportResult{}, err
}
}
if strings.TrimSpace(b.QEMULog) != "" {
if err := addFile("qemu.log", b.QEMULog); err != nil {
_ = zw.Close()
_ = f.Close()
return err
if err := addFile("qemu.log", redact(b.QEMULog)); err != nil {
return DiagnosticsExportResult{}, err
}
}
if len(b.AppLogs) > 0 {
if err := addFile("app-logs.txt", strings.Join(b.AppLogs, "\n")+"\n"); err != nil {
_ = zw.Close()
_ = f.Close()
return err
if err := addFile("app-logs.txt", redact(strings.Join(b.AppLogs, "\n"))+"\n"); err != nil {
return DiagnosticsExportResult{}, err
}
}
if len(b.PluginDiagnostics) > 0 {
if err := addJSON("plugin-diagnostics.json", b.PluginDiagnostics); err != nil {
_ = zw.Close()
_ = f.Close()
return err
return DiagnosticsExportResult{}, err
}
}
if err := zw.Close(); err != nil {
_ = f.Close()
return err
result.SummaryText = redact(diagnosticsSummary(b, generatedAt, result, append(result.IncludedFiles, "summary.txt")))
if err := addFile("summary.txt", result.SummaryText); err != nil {
return DiagnosticsExportResult{}, err
}
return f.Close()
return result, nil
}
func redactDiagnosticsJSON(value any, redact func(string) string) any {
switch v := value.(type) {
case string:
return redact(v)
case []any:
for i, item := range v {
v[i] = redactDiagnosticsJSON(item, redact)
}
case map[string]any:
return redactJSONMap(v, redact)
}
return value
}
func redactJSONMap(data map[string]any, redact func(string) string) map[string]any {
redacted := make(map[string]any, len(data))
nextSuffix := make(map[string]int)
for _, key := range slices.Sorted(maps.Keys(data)) {
base := redact(key)
name := base
if _, exists := redacted[base]; exists {
suffix := max(2, nextSuffix[base])
for {
name = fmt.Sprintf("%s #%d", base, suffix)
suffix++
if _, exists := redacted[name]; !exists {
break
}
}
nextSuffix[base] = suffix
}
if item, ok := data[key].(string); ok && item != "" && isDiagnosticsSensitiveField(key) {
redacted[name] = "[redacted]"
continue
}
redacted[name] = redactDiagnosticsJSON(data[key], redact)
}
return redacted
}
func isDiagnosticsSensitiveField(key string) bool {
switch strings.ToLower(key) {
case "mac", "mac_address", "macaddress", "osk", "smc_osk", "serial", "serial_number", "serialnumber",
"system_serial", "system_serial_number", "systemserial", "systemserialnumber", "systemserial_number",
"mlb", "rom", "smuuid", "system_uuid", "systemuuid", "uuid",
"reims_token", "github_token", "token", "access_token", "refresh_token", "auth_token",
"api_key", "apikey", "password", "passwd", "secret", "authorization", "cookie":
return true
}
return false
}
var (
diagnosticsPathStart = regexp.MustCompile(`(?i)(?:^|[\s"'=(,\[])([a-z]:[/\\]|(?:\\\\|//)[^/\\\s"'=,;()\[\]]+[/\\]|\[redacted\][/\\])`)
diagnosticsPathEnd = regexp.MustCompile(`(?i)["'\r\n;,)\]]|:[ \t]|[ \t]+(?:-|Authorization:|[a-z][a-z0-9+.-]*://)`)
diagnosticsSingleQuotedPathEnd = regexp.MustCompile(`[\r\n]|'(?:$|[\s:;,)\]"])`)
)
func redactDiagnosticsWindowsPaths(content string) string {
matches := diagnosticsPathStart.FindAllStringSubmatchIndex(content, -1)
if len(matches) == 0 {
return content
}
var out strings.Builder
end := 0
for _, match := range matches {
start := match[2]
if start < end {
continue
}
out.WriteString(content[end:start])
out.WriteString("[redacted]")
end = diagnosticsWindowsPathEnd(content, start, match[3])
}
out.WriteString(content[end:])
return out.String()
}
func diagnosticsWindowsPathEnd(content string, start, prefixEnd int) int {
rest := content[prefixEnd:]
if start > 0 && content[start-1] == '\'' {
if stop := diagnosticsSingleQuotedPathEnd.FindStringIndex(rest); stop != nil {
return prefixEnd + stop[0]
}
return len(content)
}
if start > 0 && content[start-1] == '"' {
if close := strings.IndexByte(rest, '"'); close >= 0 && !strings.ContainsAny(rest[:close], "\r\n") {
return prefixEnd + close
}
}
if stop := diagnosticsPathEnd.FindStringIndex(rest); stop != nil {
rest = rest[:stop[0]]
}
return prefixEnd + len(strings.TrimRight(rest, " \t"))
}
func diagnosticsRedactor(b diagnosticsBundle) func(string) string {
home, _ := os.UserHomeDir()
paths := []string{b.HostReport.DataRoot, home}
if b.VMInfo != nil {
paths = append(paths, b.VMInfo.Directory, b.VMInfo.DiskPath)
}
if b.Runtime != nil {
paths = append(paths, b.Runtime.Dir)
}
var roots []*regexp.Regexp
// Match VM files and runtime directories before their enclosing data root.
slices.SortFunc(paths, func(a, b string) int { return len(b) - len(a) })
for _, path := range paths {
if !filepath.IsAbs(path) || filepath.Dir(path) == path {
continue
}
pattern := regexp.QuoteMeta(path)
if filepath.Separator == '\\' {
parts := strings.Split(filepath.ToSlash(path), "/")
for i, part := range parts {
parts[i] = regexp.QuoteMeta(part)
}
pattern = "(?i)" + strings.Join(parts, `[/\\]`)
}
roots = append(roots, regexp.MustCompile(pattern+`($|[/\\\r\n"'<>|:*?])`))
}
return func(content string) string {
// A known root may contain punctuation that terminates an unquoted path.
for _, root := range roots {
content = root.ReplaceAllString(content, "[redacted]${1}")
}
return host.RedactText(redactDiagnosticsWindowsPaths(content))
}
}
func filterAppLogsForVM(logs []string, ref driver.VMRef) []string {
target := ref.Key()
var filtered []string
for _, line := range logs {
_, entry, ok := strings.Cut(line, " [")
if !ok {
continue
}
if strings.HasPrefix(entry, target+"] ") {
filtered = append(filtered, line)
continue
}
source, _, _ := strings.Cut(entry, "] ")
switch source {
case "app", "host", "runtime", "installer", "network", "ui":
filtered = append(filtered, line)
}
}
return filtered
}
func diagnosticsSummary(b diagnosticsBundle, generatedAt time.Time, result DiagnosticsExportResult, files []string) string {
var summary strings.Builder
rep := b.HostReport
fmt.Fprintf(&summary, "Reims-Go diagnostics\nGenerated (UTC): %s\nApplication version: %s\nTarget: %s\n",
generatedAt.UTC().Format(time.RFC3339), version.Version, result.TargetLabel)
fmt.Fprintf(&summary, "\nHost\nSystem: %s %s\nCPU: %d logical, %d physical\nMemory: %.1f GB available / %.1f GB total\nData disk: %.1f GB free (%s)\nWHPX: %s\n",
rep.OS, rep.Arch, rep.LogicalCPUs, rep.PhysicalCores, rep.AvailRAMGB, rep.TotalRAMGB, rep.FreeDiskGB, rep.DataRootDriveType, rep.WHPX)
if len(rep.GPUs) == 0 {
summary.WriteString("GPU: unavailable\n")
}
for _, gpu := range rep.GPUs {
fmt.Fprintf(&summary, "GPU: %s (driver %s, Vulkan %s)\n", gpu.Name, gpu.DriverVersion, gpu.VulkanVersion)
}
summary.WriteString("\nActive runtime\n")
if b.Runtime == nil {
summary.WriteString("None\n")
} else {
m := b.Runtime.Manifest
fmt.Fprintf(&summary, "%s (commit %s, channel %s, QEMU %s)\n", m.Name, b.Runtime.Commit, m.Channel, m.QemuVersion)
}
if vm := b.VMInfo; vm != nil {
fmt.Fprintf(&summary, "\nVirtual machine\nName: %s\nDriver: %s\nState: %s\nCPU: %d vCPUs\nMemory: %s\nDisk: %s\n",
vm.Name, vm.DriverID, vm.State, vm.CPUs, vm.Memory, vm.DiskSummary)
}
summary.WriteString("\nAutomatic checks\n")
if len(result.Findings) == 0 {
summary.WriteString("No known issues found\n")
}
for _, finding := range result.Findings {
fmt.Fprintf(&summary, "- %s: %s", finding.Severity, finding.Code)
if finding.Detail != "" {
fmt.Fprintf(&summary, " (%s)", finding.Detail)
}
summary.WriteByte('\n')
}
fmt.Fprintf(&summary, "\nIncluded files\n- %s\n", strings.Join(files, "\n- "))
if b.SerialTruncated {
summary.WriteString("serial.log truncated: first 1 MiB and last 4 MiB retained\n")
}
if b.QEMUTruncated {
summary.WriteString("qemu.log truncated: first 1 MiB and last 4 MiB retained\n")
}
return summary.String()
}
// ExportDiagnostics collects a redacted troubleshooting zip bundle through the owning driver.
func (a *App) ExportDiagnostics(driverID, name string) (string, error) {
func (a *App) ExportDiagnostics(driverID, name string) (DiagnosticsExportResult, error) {
if err := a.requireWritableDataRoot(); err != nil {
return DiagnosticsExportResult{}, err
}
var vm driver.VMInfo
var err error
if strings.TrimSpace(name) != "" {
vm, err = a.resolveVMInfo(driverID, name)
if err != nil {
return "", err
return DiagnosticsExportResult{}, err
}
}
cfgCopy := a.runtimeConfig()
@@ -153,21 +418,119 @@ func (a *App) ExportDiagnostics(driverID, name string) (string, error) {
if ref.DriverID != driver.BuiltinReimsMacOSDriverID {
label = sshHostAlias(ref.DriverID, vm.Name)
}
if serial, err := a.ReadVMLogs(ref.DriverID, vm.Name, true); err == nil {
bundle.SerialLog = serial
}
if qemuLog, err := a.ReadVMLogs(ref.DriverID, vm.Name, false); err == nil {
bundle.QEMULog = qemuLog
}
bundle.SerialLog, bundle.SerialTruncated = a.readDiagnosticsLog(vm, true)
bundle.QEMULog, bundle.QEMUTruncated = a.readDiagnosticsLog(vm, false)
}
bundle.HostReport, bundle.Optimizations, bundle.Runtime, bundle.AppLogs = rep, a.evaluateOptimizations(rep), active, appLogs
bundle.VMInfo, bundle.PluginDiagnostics = info, a.collectPluginDiagnostics(context.Background(), pluginKey)
reportsDir := filepath.Join(cfgCopy.DataRoot, "reports")
zipPath := filepath.Join(reportsDir, fmt.Sprintf("reims-go-diag-%s-%s.zip", label, time.Now().Format("20060102-150405")))
if err := writeDiagnosticsZip(zipPath, bundle); err != nil {
reportsDir, err := filepath.Abs(filepath.Join(cfgCopy.DataRoot, "reports"))
if err != nil {
return DiagnosticsExportResult{}, err
}
result, err := writeDiagnosticsZip(reportsDir, label, time.Now(), bundle)
if err != nil {
return DiagnosticsExportResult{}, err
}
a.emitLog(label, "Diagnostics exported: "+result.Path)
return result, nil
}
func (a *App) readDiagnosticsLog(vm driver.VMInfo, serial bool) (string, bool) {
ref := vm.Ref()
if ref.DriverID != driver.BuiltinReimsMacOSDriverID || vm.Directory == "" {
log, err := a.ReadVMLogs(ref.DriverID, ref.Name, serial)
if err != nil {
return "", false
}
return log, false
}
name := "qemu.log"
if serial {
name = "serial.log"
}
f, err := host.OpenFileSharedRead(filepath.Join(vm.Directory, "logs", name))
if err != nil {
return "", false
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return "", false
}
const (
maxLogBytes = 16 << 20
headLogBytes = 1 << 20
tailLogBytes = 4 << 20
)
if info.Size() <= maxLogBytes {
log, _ := io.ReadAll(io.NewSectionReader(f, 0, info.Size()))
return string(log), false
}
head, _ := io.ReadAll(io.NewSectionReader(f, 0, headLogBytes))
head = head[:bytes.LastIndexByte(head, '\n')+1]
// Include the byte before the tail to detect an exact line boundary.
tail, _ := io.ReadAll(io.NewSectionReader(f, info.Size()-tailLogBytes-1, tailLogBytes+1))
_, tail, _ = bytes.Cut(tail, []byte("\n"))
return string(head) + "\n[log truncated: middle omitted]\n" + string(tail), true
}
func (a *App) RevealDiagnosticsFile(path string) error {
resolved, err := resolveDiagnosticsZipPath(a.currentDataRoot(), path)
if err != nil {
return err
}
return host.RevealFile(resolved)
}
func (a *App) CopyDiagnosticsFile(path string) error {
resolved, err := resolveDiagnosticsZipPath(a.currentDataRoot(), path)
if err != nil {
return err
}
return host.CopyFileToClipboard(resolved)
}
func resolveDiagnosticsZipPath(dataRoot, rawPath string) (string, error) {
if dataRoot == "" || !strings.EqualFold(filepath.Ext(rawPath), ".zip") {
return "", fmt.Errorf("expected a diagnostics .zip file in the reports directory")
}
reportsDir, err := filepath.Abs(filepath.Join(dataRoot, "reports"))
if err != nil {
return "", err
}
a.emitLog(label, "Diagnostics exported: "+zipPath)
_ = host.OpenFolder(reportsDir)
return zipPath, nil
path, err := filepath.Abs(rawPath)
if err != nil {
return "", err
}
rel, err := filepath.Rel(reportsDir, filepath.Dir(path))
if err != nil || rel != "." {
return "", fmt.Errorf("the diagnostics file is outside the reports directory")
}
reportsDir, err = filepath.EvalSymlinks(reportsDir)
if err != nil {
return "", err
}
path, err = filepath.EvalSymlinks(path)
if err != nil {
return "", err
}
reportsInfo, err := os.Stat(reportsDir)
if err != nil {
return "", err
}
parentInfo, err := os.Stat(filepath.Dir(path))
if err != nil {
return "", err
}
if !os.SameFile(reportsInfo, parentInfo) {
return "", fmt.Errorf("the diagnostics file is outside the reports directory")
}
info, err := os.Stat(path)
if err != nil {
return "", err
}
if !info.Mode().IsRegular() || !strings.EqualFold(filepath.Ext(path), ".zip") {
return "", fmt.Errorf("expected a regular diagnostics .zip file")
}
return path, nil
}
+642 -6
View File
@@ -2,47 +2,103 @@ package app
import (
"archive/zip"
"context"
"encoding/json"
"errors"
"io"
"io/fs"
"maps"
"math"
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"strings"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/dataroot"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/plugin"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/version"
)
func TestWriteDiagnosticsZipRedactsSensitiveData(t *testing.T) {
zipPath := filepath.Join(t.TempDir(), "reports", "diag.zip")
err := writeDiagnosticsZip(zipPath, diagnosticsBundle{
HostReport: host.Report{OS: "windows", LogicalCPUs: 16, DataRootDriveType: "fixed"},
dataRoot := t.TempDir()
generatedAt := time.Date(2026, 12, 5, 10, 0, 0, 0, time.UTC)
result, err := writeDiagnosticsZip(filepath.Join(dataRoot, "reports"), "macos-tahoe", generatedAt, diagnosticsBundle{
HostReport: host.Report{
OS: "windows", Arch: "amd64", LogicalCPUs: 16, TotalRAMGB: 32, AvailRAMGB: 12,
FreeDiskGB: 64, DataRoot: dataRoot, DataRootDriveType: "fixed",
GPUs: []host.GPUInfo{{Name: "Test GPU", VulkanVersion: "1.3"}},
},
Runtime: &rt.Installed{Commit: "test-commit", Manifest: rt.Manifest{Name: "Test runtime", QemuVersion: "10"}},
VMInfo: &driver.VMInfo{Name: "macos-tahoe", CPUs: 4, Memory: "8G", DiskSummary: "64 GB"},
VMDetail: &reims.VMDetail{
Name: "macos-tahoe",
NetworkSummary: "user, mac 52:54:00:ab:cd:ef, ssh on 127.0.0.1:2222",
ExtraArgs: "-device isa-applesmc,osk=ourhardworkbythesewordsguardedpleasedontsteal",
},
SerialLog: "OpenCore presents iMac20,1, serial C02FAKE123456\n",
QEMULog: "Authorization: Bearer 0123456789abcdef0123456789abcdef\n",
QEMULog: "ERROR_DEVICE_LOST " + filepath.Join(dataRoot, "vm.log") + " Authorization: Bearer 0123456789abcdef0123456789abcdef\n",
AppLogs: []string{`REIMS_TOKEN="abcdef0123456789abcdef0123456789"`},
})
if err != nil {
t.Fatalf("writeDiagnosticsZip: %v", err)
}
zr, err := zip.OpenReader(zipPath)
zr, err := zip.OpenReader(result.Path)
if err != nil {
t.Fatal(err)
}
defer zr.Close()
var all strings.Builder
var archivedFiles []string
for _, f := range zr.File {
rc, err := f.Open()
if err != nil {
t.Fatal(err)
}
b, _ := io.ReadAll(rc)
b, err := io.ReadAll(rc)
rc.Close()
if err != nil {
t.Fatal(err)
}
all.WriteString(f.Name + ":\n" + string(b) + "\n")
archivedFiles = append(archivedFiles, f.Name)
if f.Name == "summary.txt" && string(b) != result.SummaryText {
t.Fatalf("archive summary differs from returned summary")
}
}
wantFiles := []string{"host-report.json", "runtime-manifest.json", "vm-detail.json", "vm-info.json", "serial.log", "qemu.log", "app-logs.txt", "summary.txt"}
if !slices.Equal(result.IncludedFiles, archivedFiles) || !slices.Equal(archivedFiles, wantFiles) {
t.Fatalf("returned files = %v, archived files = %v, want %v", result.IncludedFiles, archivedFiles, wantFiles)
}
info, err := os.Stat(result.Path)
if err != nil {
t.Fatal(err)
}
if result.FileName != info.Name() || result.SizeBytes != info.Size() || result.SizeBytes == 0 ||
result.TargetLabel != "macos-tahoe" || result.CanCopyFile != host.CanCopyFileToClipboard() {
t.Fatalf("unexpected export result: %+v", result)
}
if len(result.Findings) != 1 || result.Findings[0].Code != "gpu_device_lost" ||
strings.Contains(result.Findings[0].Detail, dataRoot) || !strings.Contains(result.Findings[0].Detail, "Bearer [redacted]") {
t.Fatalf("unexpected findings: %+v", result.Findings)
}
for _, fragment := range []string{generatedAt.Format(time.RFC3339), version.Version, "windows amd64",
"16 logical", "12.0 GB available", "64.0 GB free", "Test GPU", "test-commit",
"4 vCPUs", "gpu_device_lost", "- summary.txt", "Bearer [redacted]"} {
if !strings.Contains(result.SummaryText, fragment) {
t.Errorf("summary is missing %q:\n%s", fragment, result.SummaryText)
}
}
text := all.String()
for _, secret := range []string{
@@ -51,6 +107,8 @@ func TestWriteDiagnosticsZipRedactsSensitiveData(t *testing.T) {
"ourhardworkbythesewordsguardedpleasedontsteal",
"0123456789abcdef0123456789abcdef",
"abcdef0123456789abcdef0123456789",
dataRoot,
strings.ReplaceAll(dataRoot, `\`, `\\`),
} {
if strings.Contains(text, secret) {
t.Fatalf("diagnostics zip leaked secret %q\n%s", secret, text)
@@ -60,3 +118,581 @@ func TestWriteDiagnosticsZipRedactsSensitiveData(t *testing.T) {
t.Fatalf("expected [redacted] markers in zip output")
}
}
func TestWriteDiagnosticsZipEmptyAndFailedExport(t *testing.T) {
reports := filepath.Join(t.TempDir(), "reports")
now := time.Now()
result, err := writeDiagnosticsZip(reports, "host", now, diagnosticsBundle{})
if err != nil {
t.Fatal(err)
}
if !slices.Equal(result.IncludedFiles, []string{"host-report.json", "summary.txt"}) ||
result.Findings == nil || len(result.Findings) != 0 || !strings.Contains(result.SummaryText, "No known issues found") {
t.Fatalf("unexpected empty export: %+v", result)
}
if _, err := writeDiagnosticsZip(reports, "host", now, diagnosticsBundle{HostReport: host.Report{TotalRAMGB: math.NaN()}}); err == nil {
t.Fatal("expected the host report encoding to fail")
}
second, err := writeDiagnosticsZip(reports, "host", now, diagnosticsBundle{})
if err != nil || second.Path == result.Path {
t.Fatalf("same-time export returned %q, %v after %q", second.Path, err, result.Path)
}
files, err := os.ReadDir(reports)
if err != nil || len(files) != 2 {
t.Fatalf("reports directory after two successful exports and one failure: %v, %v", files, err)
}
}
func TestWriteDiagnosticsZipRedactsWindowsPaths(t *testing.T) {
dataRoot := filepath.Join(t.TempDir(), "PrivateData")
home, err := os.UserHomeDir()
if err != nil {
t.Fatal(err)
}
vmDir := filepath.Join(dataRoot, "PrivateVM")
disk := filepath.Join(dataRoot, "PrivateDisks", "vm.qcow2")
runtimeDir := filepath.Join(dataRoot, "PrivateRuntime")
pathVariant := func(path string) string {
if runtime.GOOS == "windows" {
return strings.ToUpper(filepath.ToSlash(path))
}
return path
}
const driverStore = `C:\Windows\System32\DriverStore\FileRepository\private_gpu.inf\vulkan.json`
const recommendedICD = `D:\Private Drivers\preferred-vulkan.json`
const otherDisk = `E:\Private VM Backups\Disk Images\boot.qcow2`
const anotherLog = `F:/Private Launcher Logs/startup.log`
report := host.Report{
DataRoot: dataRoot,
GPUs: []host.GPUInfo{{VulkanICD: driverStore}},
RecommendedGPU: &host.GPUInfo{VulkanICD: recommendedICD},
}
qemuLog := "ERROR_DEVICE_LOST " + otherDisk
result, err := writeDiagnosticsZip(filepath.Join(t.TempDir(), "reports"), "vm", time.Now(), diagnosticsBundle{
HostReport: report,
Runtime: &rt.Installed{Dir: runtimeDir, Manifest: rt.Manifest{Name: pathVariant(runtimeDir)}},
VMInfo: &driver.VMInfo{Name: "vm", Directory: vmDir, DiskPath: disk, DiskSummary: pathVariant(disk)},
VMDetail: &reims.VMDetail{ExtraArgs: `-device isa-applesmc,osk="test quoted value"`},
QEMULog: qemuLog,
SerialLog: `opening "` + anotherLog + `" for diagnostics`,
AppLogs: []string{pathVariant(dataRoot), pathVariant(home), pathVariant(vmDir)},
PluginDiagnostics: []plugin.DiagnosticsEntry{{
Data: map[string]any{"paths": []string{otherDisk, pathVariant(runtimeDir)}},
}},
})
if err != nil {
t.Fatal(err)
}
if report.GPUs[0].VulkanICD != driverStore || report.RecommendedGPU.VulkanICD != recommendedICD {
t.Fatal("redaction modified the original host report")
}
checkRedacted := func(name, content string) {
t.Helper()
for _, secret := range []string{
dataRoot, pathVariant(dataRoot), home, pathVariant(home), vmDir, pathVariant(vmDir),
disk, pathVariant(disk), runtimeDir, pathVariant(runtimeDir), "private_gpu.inf",
"Private Drivers", "Private VM Backups", "Disk Images", "Private Launcher Logs", "test quoted value",
} {
if strings.Contains(content, secret) || strings.Contains(content, strings.ReplaceAll(secret, `\`, `\\`)) {
t.Errorf("%s leaked %q", name, secret)
}
}
}
zr, err := zip.OpenReader(result.Path)
if err != nil {
t.Fatal(err)
}
defer zr.Close()
for _, file := range zr.File {
data, err := readDiagnosticsTestEntry(file)
if err != nil {
t.Fatal(err)
}
checkRedacted(file.Name, string(data))
if filepath.Ext(file.Name) == ".json" {
var value json.RawMessage
if err := json.Unmarshal(data, &value); err != nil {
t.Errorf("%s contains invalid JSON: %v", file.Name, err)
}
}
if file.Name == "host-report.json" {
var entry struct {
Host host.Report `json:"host"`
}
if err := json.Unmarshal(data, &entry); err != nil || len(entry.Host.GPUs) != 1 ||
entry.Host.GPUs[0].VulkanICD != "[redacted]" || entry.Host.RecommendedGPU == nil ||
entry.Host.RecommendedGPU.VulkanICD != "[redacted]" {
t.Errorf("host-report.json did not redact both Vulkan ICDs: %s (%v)", data, err)
}
}
}
checkRedacted("SummaryText", result.SummaryText)
if len(result.Findings) != 1 || result.Findings[0].Detail != "ERROR_DEVICE_LOST [redacted]" {
t.Fatalf("unexpected findings: %+v", result.Findings)
}
for _, finding := range result.Findings {
checkRedacted(finding.Code, finding.Detail)
}
}
func TestRedactDiagnosticsWindowsPathBoundaries(t *testing.T) {
redact := diagnosticsRedactor(diagnosticsBundle{})
for _, tc := range []struct{ input, want string }{
{`open D:\VM Backups\boot.qcow2: access is denied (0x5)`, "open [redacted]: access is denied (0x5)"},
{`-L D:\Runtime Files -m 8G`, "-L [redacted] -m 8G"},
{"GET https://example.test/runtime.zip failed: 404", "GET https://example.test/runtime.zip failed: 404"},
{`GET file://example.test/runtime.zip`, `GET file://example.test/runtime.zip`},
{`saved D:\Private\download.zip https://example.test/runtime.zip`, "saved [redacted] https://example.test/runtime.zip"},
{`GET "http://example.test/runtime.zip" failed: 404`, `GET "http://example.test/runtime.zip" failed: 404`},
{`open \\server\private-share\boot.qcow2: access denied`, "open [redacted]: access denied"},
{`open //server/private-share/boot.qcow2: access denied`, "open [redacted]: access denied"},
{`//server/private-share/boot.qcow2`, "[redacted]"},
{`"\\server\private share\boot.qcow2"`, `"[redacted]"`},
{`'D:\Private, Backup\boot.qcow2' next`, "'[redacted]' next"},
{`Could not open 'D:\O'Brien\boot.qcow2': access denied`, `Could not open '[redacted]': access denied`},
{`file=D:/vm/backups,other=[E:\Private Backup]; (F:\Runtime)`, "file=[redacted],other=[[redacted]]; ([redacted])"},
{"D:\\first\r\nE:\\second", "[redacted]\r\n[redacted]"},
} {
if got := redact(tc.input); got != tc.want {
t.Errorf("redact(%q) = %q, want %q", tc.input, got, tc.want)
}
}
}
func TestRedactDiagnosticsKnownRootWithPunctuation(t *testing.T) {
root := filepath.Join(t.TempDir(), "Private, VM")
path := filepath.Join(root, "private disk.qcow2")
if runtime.GOOS == "windows" {
path = strings.ToUpper(filepath.ToSlash(path))
}
redact := diagnosticsRedactor(diagnosticsBundle{HostReport: host.Report{DataRoot: root}})
if got, want := redact("open "+path+": access denied"), "open [redacted]: access denied"; got != want {
t.Errorf("redacted known root = %q, want %q", got, want)
}
}
func TestWriteDiagnosticsZipRedactsUNCPaths(t *testing.T) {
const qemu = `ERROR_DEVICE_LOST open \\server\private-share\boot.qcow2: access denied`
const serial = `VK_ERROR_INCOMPATIBLE_DRIVER opening "\\server\private share\boot.qcow2"`
const wantQEMU = "ERROR_DEVICE_LOST open [redacted]: access denied"
const wantSerial = `VK_ERROR_INCOMPATIBLE_DRIVER opening "[redacted]"`
result, err := writeDiagnosticsZip(t.TempDir(), "vm", time.Now(), diagnosticsBundle{
QEMULog: qemu, SerialLog: serial, AppLogs: []string{qemu, serial},
})
if err != nil {
t.Fatal(err)
}
for _, finding := range []host.DiagnosticFinding{
{Code: "gpu_device_lost", Severity: "error", Detail: wantQEMU},
{Code: "gpu_vulkan_floor", Severity: "error", Detail: wantSerial},
} {
if !slices.Contains(result.Findings, finding) || !strings.Contains(result.SummaryText, finding.Detail) {
t.Fatalf("missing %+v from findings or summary:\n%+v\n%s", finding, result.Findings, result.SummaryText)
}
}
for name, want := range map[string]string{
"qemu.log": wantQEMU, "serial.log": wantSerial,
"app-logs.txt": wantQEMU + "\n" + wantSerial + "\n", "summary.txt": result.SummaryText,
} {
if got := readDiagnosticsArchiveEntry(t, result.Path, name); got != want {
t.Errorf("%s = %q, want %q", name, got, want)
}
}
report := readDiagnosticsArchiveEntry(t, result.Path, "host-report.json")
var hostReport struct {
Diagnosis host.DiagnosticFinding `json:"gpu_diagnosis"`
}
if err := json.Unmarshal([]byte(report), &hostReport); err != nil || hostReport.Diagnosis.Detail != wantQEMU {
t.Fatalf("host report diagnosis = %+v, err %v", hostReport.Diagnosis, err)
}
for _, secret := range []string{"server", "private-share", "private share", "boot.qcow2"} {
if strings.Contains(result.SummaryText, secret) || strings.Contains(report, secret) {
t.Errorf("summary or host report leaked %q", secret)
}
}
}
func TestWriteDiagnosticsZipRedactsStructuredJSON(t *testing.T) {
result, err := writeDiagnosticsZip(t.TempDir(), "vm", time.Now(), diagnosticsBundle{
PluginDiagnostics: []plugin.DiagnosticsEntry{{Data: map[string]any{
"disks": map[string]string{
`D:\test\disk-a`: "disk A", `D:\test\disk-b`: "disk B", `D:\test\disk-c`: "disk C", "[redacted] #2": "literal key",
},
"hardware": []map[string]string{{
"mac": "02:00:00:00:00:01", "MAC_Address": "another-mac", "OSK": "short",
"SMC_OSK": "test-osk", "serial": "short-serial", "Serial_Number": "another-serial",
"MLB": "test-mlb", "RoM": "test-rom", "System_UUID": "test-uuid",
"smuuid": "", "model": "test-model",
"uuid": "12345678-1234-1234-1234-123456789abc", "token": "syntheticToken0123456789",
"REIMS_TOKEN": "test-reims", "GITHUB_TOKEN": "test-github", "Access_Token": "test-access",
"refresh_token": "test-refresh", "auth_token": "test-auth", "api_key": "test-key", "apikey": "test-apikey",
"password": "test-password", "passwd": "test-passwd", "secret": "test-secret",
"authorization": "test-authorization", "cookie": "test-cookie",
}},
}}},
})
if err != nil {
t.Fatal(err)
}
report := readDiagnosticsArchiveEntry(t, result.Path, "plugin-diagnostics.json")
var entries []struct {
Data struct {
Disks map[string]string
Hardware []map[string]string
}
}
if err := json.Unmarshal([]byte(report), &entries); err != nil || len(entries) != 1 || len(entries[0].Data.Hardware) != 1 {
t.Fatalf("invalid plugin diagnostics: %s (%v)", report, err)
}
wantDisks := map[string]string{
"[redacted]": "disk A", "[redacted] #2": "disk B", "[redacted] #3": "disk C", "[redacted] #2 #2": "literal key",
}
wantHardware := map[string]string{
"mac": "[redacted]", "MAC_Address": "[redacted]", "OSK": "[redacted]", "SMC_OSK": "[redacted]",
"serial": "[redacted]", "Serial_Number": "[redacted]", "MLB": "[redacted]", "RoM": "[redacted]",
"System_UUID": "[redacted]", "smuuid": "", "model": "test-model",
"uuid": "[redacted]", "token": "[redacted]", "REIMS_TOKEN": "[redacted]", "GITHUB_TOKEN": "[redacted]",
"Access_Token": "[redacted]", "refresh_token": "[redacted]", "auth_token": "[redacted]",
"api_key": "[redacted]", "apikey": "[redacted]", "password": "[redacted]", "passwd": "[redacted]",
"secret": "[redacted]", "authorization": "[redacted]", "cookie": "[redacted]",
}
if !maps.Equal(entries[0].Data.Disks, wantDisks) || !maps.Equal(entries[0].Data.Hardware[0], wantHardware) {
t.Fatalf("unexpected redacted data: %s", report)
}
if strings.Contains(report, `D:\\test\\disk-`) || strings.Contains(report, "02:00:00:00:00:01") {
t.Fatalf("plugin diagnostics leaked a path or hardware identifier: %s", report)
}
}
func TestExportDiagnosticsRejectsReadOnlyDataRoot(t *testing.T) {
root := t.TempDir()
a := &App{
cfg: &config.Config{DataRoot: root},
root: dataroot.Status{Dir: root, ReadOnly: true, Reason: dataroot.ReasonNewer},
}
result, err := a.ExportDiagnostics("", "")
if err == nil || !strings.Contains(err.Error(), "E_DATAROOT_NEWER") || result.Path != "" {
t.Fatalf("ExportDiagnostics returned %+v, %v", result, err)
}
if _, err := os.Stat(filepath.Join(root, "reports")); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("reports directory stat: %v", err)
}
}
func newDiagnosticsTestApp(t *testing.T, drivers ...*appSecondDriver) *App {
t.Helper()
reg := plugin.NewRegistry(nil)
for _, d := range drivers {
err := reg.Register(plugin.PluginDef{
Manifest: plugin.Manifest{ID: "test." + d.id, Version: "1.0.0"},
Source: plugin.SourceBuiltin,
Desired: true,
Activate: func(_ context.Context, sc *plugin.Scope) error {
reg.RegisterGuestDriver(sc, d.id, d)
return nil
},
})
if err != nil {
t.Fatal(err)
}
}
reg.Reconcile(t.Context())
return &App{
cfg: &config.Config{DataRoot: t.TempDir()},
lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil),
}
}
func TestExportDiagnosticsVMChecksOnlyTargetAndHostLogs(t *testing.T) {
const dID = driver.BuiltinReimsMacOSDriverID
const otherID = "test.driver.other"
mac := &appSecondDriver{id: dID, vms: []driver.VMInfo{{Name: "vm-a"}, {Name: "vm-b"}}}
other := &appSecondDriver{id: otherID, vms: []driver.VMInfo{{Name: "vm-a"}}}
a := newDiagnosticsTestApp(t, mac, other)
a.emitVMLogForDriver(dID, "vm-b", "ERROR_DEVICE_LOST other instance")
a.emitVMLogForDriver(otherID, "vm-a", "ERROR_DEVICE_LOST other driver")
a.emitVMLogForDriver(dID, "vm-a", "VK_ERROR_INCOMPATIBLE_DRIVER target instance")
a.emitLog("host", "Hypervisor is disabled host detail")
a.emitLog("plugin:demo", "ERROR_DEVICE_LOST unscoped plugin stderr")
a.emitLog("plugin", "ERROR_DEVICE_LOST unscoped plugin error")
result, err := a.ExportDiagnostics(dID, "vm-a")
if err != nil {
t.Fatal(err)
}
if !slices.ContainsFunc(result.Findings, func(f host.DiagnosticFinding) bool {
return f.Code == "gpu_vulkan_floor" && strings.Contains(f.Detail, "target instance")
}) {
t.Fatalf("target VM's finding is missing: %+v", result.Findings)
}
for _, finding := range result.Findings {
if finding.Code == "gpu_device_lost" || strings.Contains(finding.Detail, "other instance") ||
strings.Contains(finding.Detail, "other driver") {
t.Errorf("another VM contributed a finding: %+v", finding)
}
}
for _, text := range []string{"ERROR_DEVICE_LOST", "gpu_device_lost", "other instance", "other driver", "unscoped plugin stderr", "unscoped plugin error"} {
if strings.Contains(result.SummaryText, text) {
t.Errorf("summary contains another VM's error: %s", result.SummaryText)
}
}
content := readDiagnosticsArchiveEntry(t, result.Path, "app-logs.txt")
for _, line := range []string{"[plugin:demo] ERROR_DEVICE_LOST unscoped plugin stderr", "[plugin] ERROR_DEVICE_LOST unscoped plugin error"} {
if !strings.Contains(content, line) {
t.Errorf("app-logs.txt is missing %q:\n%s", line, content)
}
}
a.emitLog("host", "ERROR_DEVICE_LOST shared host detail")
result, err = a.ExportDiagnostics(dID, "vm-a")
if err != nil {
t.Fatal(err)
}
if !slices.ContainsFunc(result.Findings, func(f host.DiagnosticFinding) bool {
return f.Code == "gpu_device_lost" && strings.Contains(f.Detail, "shared host detail")
}) {
t.Fatalf("host finding is missing: %+v", result.Findings)
}
}
func TestExportDiagnosticsReadsEarlierBuiltInVMLogs(t *testing.T) {
vm := driver.VMInfo{Name: "vm", DriverID: driver.BuiltinReimsMacOSDriverID, Directory: t.TempDir()}
a := newDiagnosticsTestApp(t, &appSecondDriver{id: vm.DriverID, vms: []driver.VMInfo{vm}})
logDir := filepath.Join(vm.Directory, "logs")
if err := os.Mkdir(logDir, 0o755); err != nil {
t.Fatal(err)
}
// Both errors precede the preview window. QEMU's error also precedes the last 2 MiB.
tail := strings.Repeat(strings.Repeat("a", 2047)+"\n", 48)
logs := map[string]string{
"qemu.log": "ERROR_DEVICE_LOST earlier QEMU error\n" + strings.Repeat(tail, 24),
"serial.log": "VK_ERROR_INCOMPATIBLE_DRIVER earlier serial error\n" + tail,
}
for name, content := range logs {
if err := os.WriteFile(filepath.Join(logDir, name), []byte(content), 0o600); err != nil {
t.Fatal(err)
}
}
result, err := a.ExportDiagnostics(vm.DriverID, vm.Name)
if err != nil {
t.Fatal(err)
}
for _, detail := range []string{"earlier QEMU error", "earlier serial error"} {
if !strings.Contains(result.SummaryText, detail) || !slices.ContainsFunc(result.Findings, func(f host.DiagnosticFinding) bool {
return strings.Contains(f.Detail, detail)
}) {
t.Errorf("earlier error %q is missing from findings or summary", detail)
}
}
if strings.Contains(result.SummaryText, "truncated:") {
t.Fatalf("summary reports truncation for complete logs:\n%s", result.SummaryText)
}
zr, err := zip.OpenReader(result.Path)
if err != nil {
t.Fatal(err)
}
defer zr.Close()
for _, file := range zr.File {
want, ok := logs[file.Name]
if !ok {
continue
}
content, err := readDiagnosticsTestEntry(file)
if err != nil || string(content) != want {
t.Fatalf("%s did not retain the full log: got %d bytes, want %d, err %v", file.Name, len(content), len(want), err)
}
delete(logs, file.Name)
}
if len(logs) != 0 {
t.Fatal("expected both VM logs in the archive")
}
}
func TestExportDiagnosticsTruncatesOversizedBuiltInVMLog(t *testing.T) {
vm := driver.VMInfo{Name: "vm", DriverID: driver.BuiltinReimsMacOSDriverID, Directory: t.TempDir()}
a := newDiagnosticsTestApp(t, &appSecondDriver{id: vm.DriverID, vms: []driver.VMInfo{vm}})
logDir := filepath.Join(vm.Directory, "logs")
if err := os.Mkdir(logDir, 0o755); err != nil {
t.Fatal(err)
}
const start = "ERROR_DEVICE_LOST first startup error\n"
const end = "VK_ERROR_INCOMPATIBLE_DRIVER last crash error\n"
head := start + strings.Repeat("a", (1<<20)-len(start)-1) + "\n"
tail := strings.Repeat("c", (4<<20)-len(end)-1) + "\n" + end
full := head + "middle omitted\n" + strings.Repeat("b", 11<<20) + "\n" + tail
if err := os.WriteFile(filepath.Join(logDir, "qemu.log"), []byte(full), 0o600); err != nil {
t.Fatal(err)
}
result, err := a.ExportDiagnostics(vm.DriverID, vm.Name)
if err != nil {
t.Fatal(err)
}
got := readDiagnosticsArchiveEntry(t, result.Path, "qemu.log")
want := head + "\n[log truncated: middle omitted]\n" + tail
if got != want {
t.Fatalf("truncated log differs from the expected head, marker and tail (%d vs %d bytes)", len(got), len(want))
}
for _, finding := range []host.DiagnosticFinding{
{Code: "gpu_device_lost", Severity: "error", Detail: strings.TrimSpace(start)},
{Code: "gpu_vulkan_floor", Severity: "error", Detail: strings.TrimSpace(end)},
} {
if !slices.Contains(result.Findings, finding) {
t.Errorf("missing %+v from findings: %+v", finding, result.Findings)
}
}
const note = "qemu.log truncated: first 1 MiB and last 4 MiB retained"
if !strings.Contains(result.SummaryText, note) || readDiagnosticsArchiveEntry(t, result.Path, "summary.txt") != result.SummaryText {
t.Fatalf("summary is missing the truncation note or differs from summary.txt:\n%s", result.SummaryText)
}
}
func TestExportDiagnosticsDropsPartialLinesAtLogCutoffs(t *testing.T) {
vm := driver.VMInfo{Name: "vm", DriverID: driver.BuiltinReimsMacOSDriverID, Directory: t.TempDir()}
a := newDiagnosticsTestApp(t, &appSecondDriver{id: vm.DriverID, vms: []driver.VMInfo{vm}})
logDir := filepath.Join(vm.Directory, "logs")
if err := os.Mkdir(logDir, 0o755); err != nil {
t.Fatal(err)
}
const start = "first complete line\n"
const end = "last complete line\n"
const partialTail = "Private Folder\\boot.qcow2: access denied\n"
head := start + "partial head line " + strings.Repeat("a", 1<<20) + "\n"
tail := partialTail + strings.Repeat("c", (4<<20)-len(partialTail)-len(end)-1) + "\n" + end
full := head + strings.Repeat("b", 12<<20) + "\nopen D:\\" + tail
if err := os.WriteFile(filepath.Join(logDir, "qemu.log"), []byte(full), 0o600); err != nil {
t.Fatal(err)
}
result, err := a.ExportDiagnostics(vm.DriverID, vm.Name)
if err != nil {
t.Fatal(err)
}
got := readDiagnosticsArchiveEntry(t, result.Path, "qemu.log")
for _, fragment := range []string{"partial head line", "Private Folder", "boot.qcow2"} {
if strings.Contains(got, fragment) {
t.Errorf("truncated log retained incomplete line fragment %q", fragment)
}
}
if !strings.HasPrefix(got, start+"\n[log truncated: middle omitted]\n") || !strings.HasSuffix(got, end) {
t.Fatal("truncated log lost a complete line or the truncation marker")
}
}
func readDiagnosticsArchiveEntry(t *testing.T, path, name string) string {
t.Helper()
zr, err := zip.OpenReader(path)
if err != nil {
t.Fatal(err)
}
defer zr.Close()
data, err := fs.ReadFile(zr, name)
if err != nil {
t.Fatalf("read %s: %v", name, err)
}
return string(data)
}
func readDiagnosticsTestEntry(file *zip.File) ([]byte, error) {
rc, err := file.Open()
if err != nil {
return nil, err
}
defer rc.Close()
return io.ReadAll(rc)
}
func TestResolveDiagnosticsZipPath(t *testing.T) {
root := t.TempDir()
reports := filepath.Join(root, "reports")
dir := filepath.Join(reports, "dir.zip")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
outside := filepath.Join(root, "reports-backup")
if err := os.Mkdir(outside, 0o755); err != nil {
t.Fatal(err)
}
valid := filepath.Join(reports, "export.ZIP")
wrongExt := filepath.Join(reports, "export.txt")
escaped := filepath.Join(outside, "export.zip")
nested := filepath.Join(dir, "nested.zip")
for _, path := range []string{valid, wrongExt, escaped, nested} {
if err := os.WriteFile(path, nil, 0o600); err != nil {
t.Fatal(err)
}
}
link := filepath.Join(reports, "link")
if runtime.GOOS == "windows" {
if out, err := exec.Command("cmd.exe", "/c", "mklink", "/J", link, outside).CombinedOutput(); err != nil {
t.Fatalf("make junction: %v\n%s", err, out)
}
} else if err := os.Symlink(outside, link); err != nil {
t.Fatal(err)
}
want, err := filepath.EvalSymlinks(valid)
if err != nil {
t.Fatal(err)
}
if got, err := resolveDiagnosticsZipPath(root, valid); err != nil || got != want {
t.Fatalf("resolveDiagnosticsZipPath(%q) = %q, %v, want %q", valid, got, err, want)
}
for name, path := range map[string]string{
"empty": "", "directory": dir, "missing": filepath.Join(reports, "missing.zip"),
"outside": escaped, "wrong extension": wrongExt, "link escape": filepath.Join(link, "export.zip"),
"nested file": nested,
"traversal": reports + string(os.PathSeparator) + "../reports-backup/export.zip",
} {
t.Run(name, func(t *testing.T) {
if got, err := resolveDiagnosticsZipPath(root, path); err == nil {
t.Errorf("accepted %q as %q", path, got)
}
})
}
}
func TestResolveDiagnosticsZipPathRejectsCaseSensitiveSibling(t *testing.T) {
root := t.TempDir()
var caseOutput []byte
if runtime.GOOS == "windows" {
output, err := exec.Command("fsutil.exe", "file", "setCaseSensitiveInfo", root, "enable").CombinedOutput()
if err != nil {
t.Skipf("cannot enable case sensitivity on the temporary directory: %v (%s)", err, output)
}
caseOutput = output
}
reports := filepath.Join(root, "reports")
sibling := filepath.Join(root, "REPORTS")
for _, dir := range []string{reports, sibling} {
if err := os.Mkdir(dir, 0o755); err != nil {
if dir == sibling && errors.Is(err, os.ErrExist) {
t.Skipf("temporary directory is case-insensitive: %v (%s)", err, strings.TrimSpace(string(caseOutput)))
}
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "export.zip"), nil, 0o600); err != nil {
t.Fatal(err)
}
}
if _, err := resolveDiagnosticsZipPath(root, filepath.Join(reports, "export.zip")); err != nil {
t.Fatalf("authorized reports directory rejected: %v", err)
}
if path, err := resolveDiagnosticsZipPath(root, filepath.Join(sibling, "export.zip")); err == nil {
t.Fatalf("accepted export from case-sensitive sibling: %s", path)
}
}
func TestResolveDiagnosticsZipPathRejectsDirectSymlinkEscape(t *testing.T) {
root := t.TempDir()
reports := filepath.Join(root, "reports")
if err := os.Mkdir(reports, 0o755); err != nil {
t.Fatal(err)
}
outside := filepath.Join(root, "outside.zip")
if err := os.WriteFile(outside, nil, 0o600); err != nil {
t.Fatal(err)
}
link := filepath.Join(reports, "link.zip")
if err := os.Symlink(outside, link); err != nil {
t.Skipf("cannot create a symbolic link: %v", err)
}
if path, err := resolveDiagnosticsZipPath(root, link); err == nil {
t.Fatalf("accepted symlink to outside of reports: %s", path)
}
}
+94 -15
View File
@@ -9,6 +9,7 @@ import (
"io"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
@@ -18,6 +19,7 @@ import (
"github.com/Nwflower/reims-go/internal/fetch"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/netproxy"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginproto"
@@ -51,7 +53,7 @@ func (a *App) downloadHostHandlers(mgr *plugin.Manager, pluginID string) map[str
}
broker := mgr.Broker()
return map[string]plugin.RPCRequestHandler{
"host/download.start": a.hostAPISvc().hostMethod(mgr, pluginID, "host/download.start", func(_ context.Context, raw json.RawMessage) (any, error) {
"host/download.start": a.hostAPISvc().hostMethod(mgr, pluginID, "host/download.start", func(ctx context.Context, raw json.RawMessage) (any, error) {
a.mu.Lock()
dataRoot := ""
if a.cfg != nil {
@@ -60,7 +62,7 @@ func (a *App) downloadHostHandlers(mgr *plugin.Manager, pluginID string) map[str
a.mu.Unlock()
roots := downloadRoots(mgr, pluginID, dataRoot)
notify := func(method string, params any) { mgr.NotifySidecar(pluginID, method, params) }
return a.startPluginDownload(mgr, broker, notify, pluginID, roots, raw)
return a.startPluginDownload(ctx, mgr, broker, mgr.Registry(), notify, pluginID, roots, raw)
}),
"host/download.cancel": a.hostAPISvc().hostMethod(mgr, pluginID, "host/download.cancel", func(_ context.Context, raw json.RawMessage) (any, error) {
return cancelPluginDownload(mgr, pluginID, raw)
@@ -127,13 +129,27 @@ func rejectInternalHost(host string) error {
}
// safeDownloadClient follows at most ten redirects, never from HTTPS to plain
// HTTP, and, unless the first URL was loopback itself, never to an internal
// address.
func safeDownloadClient(initial string) *http.Client {
client := netproxy.NewClient()
// HTTP, and, unless allowLoopbackInternal is true and the first URL was
// loopback, never to an internal address. connectTimeout > 0 tightens
// dial/TLS/header timeouts for fast mirror failover.
func safeDownloadClient(initial string, connectTimeout time.Duration, allowLoopbackInternal bool) *http.Client {
tr := netproxy.NewTransport()
if connectTimeout > 0 {
tr.DialContext = (&net.Dialer{
Timeout: connectTimeout,
KeepAlive: 30 * time.Second,
}).DialContext
tr.TLSHandshakeTimeout = connectTimeout
if connectTimeout < tr.ResponseHeaderTimeout {
tr.ResponseHeaderTimeout = connectTimeout * 2
}
}
client := &http.Client{Transport: tr}
allowInternal := false
if u, err := parseURLHost(initial); err == nil {
allowInternal = plugin.IsLoopbackHost(u)
if allowLoopbackInternal {
if u, err := parseURLHost(initial); err == nil {
allowInternal = plugin.IsLoopbackHost(u)
}
}
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
if len(via) >= downloadMaxRedirects {
@@ -212,22 +228,83 @@ type downloadEvent struct {
// startPluginDownload validates a download request and runs it in the
// background as a task. It returns the download ID at once.
func (a *App) startPluginDownload(kernel hostMethodHost, broker *plugin.Broker, notify downloadNotifier, pluginID string, roots []string, raw json.RawMessage) (any, error) {
func (a *App) startPluginDownload(reqCtx context.Context, kernel hostMethodHost, broker *plugin.Broker, reg *plugin.Registry, notify downloadNotifier, pluginID string, roots []string, raw json.RawMessage) (any, error) {
req, err := decodeHostParams[pluginproto.DownloadParams](kernel, pluginID, "host/download.start", raw)
if err != nil {
return nil, err
}
want := strings.ToLower(strings.TrimSpace(req.SHA256))
if want != "" && !isHex64(want) {
return nil, errors.New("sha256 must be 64 hex digits")
}
usedCustomMirror := false
if err := broker.AuthorizeNetOrigin(pluginID, req.URL); err != nil {
return nil, err
if !req.AllowCustomMirror || !errors.Is(err, plugin.ErrNetOriginNotDeclared) {
return nil, err
}
if want == "" {
return nil, errors.New("custom mirror downloads require a pinned sha256 digest")
}
parsed, parseErr := url.Parse(strings.TrimSpace(req.URL))
if parseErr != nil || parsed.Hostname() == "" || (parsed.Scheme != "https" && !plugin.IsLoopbackHost(parsed.Hostname())) {
return nil, errors.New("custom mirror URL must use HTTPS")
}
if parsed.User != nil {
broker.Audit(pluginID, "DENY", "custom mirror URL with user info")
return nil, errors.New("URLs with user info are not allowed")
}
if !plugin.IsLoopbackHost(parsed.Hostname()) {
if hostErr := rejectInternalHost(parsed.Hostname()); hostErr != nil {
return nil, hostErr
}
}
origin := parsed.Scheme + "://" + parsed.Host
loc := a.computerUseLocale()
confirmRes, confirmErr := a.requestHostConfirm(reqCtx, broker, reg, pluginID, ConfirmPrompt{
Kind: "custom_mirror",
Origin: origin,
Title: i18n.T(loc, "confirm.mirror.title"),
Message: i18n.M(loc, "confirm.mirror.message", i18n.Vars{"origin": origin}),
ConfirmLabel: i18n.T(loc, "confirm.mirror.allow"),
CancelLabel: i18n.T(loc, "confirm.phase.deny"),
Danger: true,
})
if confirmErr != nil {
return nil, confirmErr
}
if !confirmRes.Approved {
broker.Audit(pluginID, "DOWNLOAD_MIRROR_DENIED", origin)
return nil, errors.New("confirmation_denied: user declined the custom download mirror")
}
broker.Audit(pluginID, "DOWNLOAD_MIRROR_APPROVED", origin)
usedCustomMirror = true
}
if strings.TrimSpace(req.SHA256URL) != "" {
if err := broker.AuthorizeNetOrigin(pluginID, req.SHA256URL); err != nil {
return nil, err
}
}
want := strings.ToLower(strings.TrimSpace(req.SHA256))
if want != "" && !isHex64(want) {
return nil, errors.New("sha256 must be 64 hex digits")
connectTimeout := time.Duration(0)
if req.ConnectTimeoutMS > 0 {
ms := req.ConnectTimeoutMS
if ms < 2000 {
ms = 2000
}
if ms > 30000 {
ms = 30000
}
connectTimeout = time.Duration(ms) * time.Millisecond
}
stallTimeout := downloadStall
if req.StallTimeoutMS > 0 {
ms := req.StallTimeoutMS
if ms < 5000 {
ms = 5000
}
if ms > 120000 {
ms = 120000
}
stallTimeout = time.Duration(ms) * time.Millisecond
}
if want == "" && strings.TrimSpace(req.SHA256URL) == "" {
return nil, errors.New("sha256 or sha256_url is required")
@@ -270,7 +347,9 @@ func (a *App) startPluginDownload(kernel hostMethodHost, broker *plugin.Broker,
pluginDownloads.mu.Unlock()
go func() {
client := safeDownloadClient(req.URL)
// Undeclared custom mirrors must never gain internal/LAN redirect
// privileges even if the initial user-confirmed URL was loopback.
client := safeDownloadClient(req.URL, connectTimeout, !usedCustomMirror)
var lastNotify atomic.Int64
progress := func(done, total int64) {
percent := -1.0
@@ -289,7 +368,7 @@ func (a *App) startPluginDownload(kernel hostMethodHost, broker *plugin.Broker,
}
if err == nil {
_, err = fetch.ResumeDirect(ctx, client, req.URL, dest, req.Size, want, progress,
fetch.ResumeOptions{MaxBytes: downloadMaxBytes, StallTimeout: downloadStall})
fetch.ResumeOptions{MaxBytes: downloadMaxBytes, StallTimeout: stallTimeout})
}
pluginDownloads.mu.Lock()
delete(pluginDownloads.m, id)
+15 -3
View File
@@ -1,6 +1,7 @@
package app
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
@@ -61,7 +62,7 @@ func (e *downloadTestEnv) notify(method string, params any) {
func (e *downloadTestEnv) start(t *testing.T, pluginID string, req map[string]any) (string, error) {
t.Helper()
raw, _ := json.Marshal(req)
res, err := e.app.startPluginDownload(nil, e.h.Broker, e.notify, pluginID, e.roots, raw)
res, err := e.app.startPluginDownload(context.Background(), nil, e.h.Broker, e.h.Registry, e.notify, pluginID, e.roots, raw)
if err != nil {
return "", err
}
@@ -225,7 +226,7 @@ func TestHostDownloadCancelIsPerPlugin(t *testing.T) {
}
func TestDownloadRedirectsNeverDowngradeOrReachInternalHosts(t *testing.T) {
client := safeDownloadClient("https://downloads.example.com/file")
client := safeDownloadClient("https://downloads.example.com/file", 0, true)
req := func(raw string) *http.Request {
u, _ := url.Parse(raw)
return &http.Request{URL: u}
@@ -256,10 +257,21 @@ func TestDownloadRedirectsNeverDowngradeOrReachInternalHosts(t *testing.T) {
t.Error("an eleventh redirect was allowed")
}
// A loopback origin the plugin declared may redirect within loopback.
local := safeDownloadClient("http://127.0.0.1:1/f")
local := safeDownloadClient("http://127.0.0.1:1/f", 0, true)
if err := local.CheckRedirect(req("http://127.0.0.1:1/g"), []*http.Request{req("http://127.0.0.1:1/f")}); err != nil {
t.Errorf("a loopback redirect from a loopback origin was refused: %v", err)
}
// An undeclared custom mirror confirmed on loopback must NOT redirect to internal/private hosts.
customLocal := safeDownloadClient("http://127.0.0.1:1/f", 0, false)
for name, target := range map[string]string{
"private LAN": "http://192.168.1.1/secret",
"link local": "http://169.254.169.254/latest/meta-data",
"loopback": "http://127.0.0.1:9999/other",
} {
if err := customLocal.CheckRedirect(req(target), []*http.Request{req("http://127.0.0.1:1/f")}); err == nil {
t.Errorf("custom mirror loopback redirect to %s (%s) must be rejected", name, target)
}
}
}
func TestHasRunningDownloadFollowsPluginDownloads(t *testing.T) {
+18
View File
@@ -152,6 +152,24 @@ func TestSSHTargetPrefersTheEndpoint(t *testing.T) {
}
}
func TestMacSSHTerminalLaunch(t *testing.T) {
for _, tc := range []struct {
host, user, want string
}{
{"", "", "ssh://127.0.0.1:2222"},
{"guest.local", "dev", "ssh://dev@guest.local:2222"},
{"2001:db8::1", "dev", "ssh://dev@[2001:db8::1]:2222"},
} {
spec, err := macSSHTerminalLaunch(tc.host, 2222, tc.user)
if err != nil || spec.exe != "/usr/bin/open" || !slices.Equal(spec.args, []string{tc.want}) {
t.Errorf("launch = %+v, %v; want %q", spec, err, tc.want)
}
}
if _, err := macSSHTerminalLaunch("example.com", 22, "-oProxyCommand"); err == nil {
t.Error("accepted a user resembling an SSH option")
}
}
func TestSSHHostAliasSeparatesDrivers(t *testing.T) {
mac := sshHostAlias("", "dev")
other := sshHostAlias("vendor.driver.linux", "dev")
+4
View File
@@ -8,6 +8,7 @@ import (
"sort"
"strings"
"github.com/Nwflower/reims-go/internal/macos/guest"
"github.com/Nwflower/reims-go/internal/macos/installer"
)
@@ -91,6 +92,9 @@ func (a *App) GetStorageBreakdown() StorageBreakdown {
cfgCopy := *a.cfg
a.mu.Unlock()
vmsDir := filepath.Join(cfgCopy.XDGDataDir(), "reims-ctl", "vms")
if guest.UsesAppleVirtualization() {
return computeStorageBreakdown(cfgCopy.DataRoot, guest.AppleVMRoot(cfgCopy.DataRoot), installer.RestoreDir(&cfgCopy), "")
}
return computeStorageBreakdown(cfgCopy.DataRoot, vmsDir, installer.Dir(&cfgCopy), cfgCopy.ImagesDir())
}
+20 -4
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"strings"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginproto"
@@ -49,7 +50,7 @@ func authorizeHostMethod(host hostMethodHost, pluginID, method string) error {
// until it is updated, while a new plugin learns about a typo at once.
func strictHostParams(host hostMethodHost, pluginID, method string) bool {
spec, ok := pluginproto.Lookup(method)
if !ok || !spec.StrictParams || host == nil {
if !ok || !spec.StrictParams || host == nil || host.Registry() == nil {
return false
}
manifest, found := host.Registry().ManifestOf(pluginID)
@@ -94,8 +95,23 @@ func (h *HostAPIService) hostMethod(host hostMethodHost, pluginID, method string
}
// hostVMMethod wraps a handler that needs the manager and the calling plugin.
// When permission authorization fails (outside transient rate limits), active
// remote-control sessions for that plugin are aborted immediately.
func (h *HostAPIService) hostVMMethod(mgr *plugin.Manager, pluginID, method string, run computerUseVMHandler) plugin.RPCRequestHandler {
return h.hostMethod(mgr, pluginID, method, func(ctx context.Context, raw json.RawMessage) (any, error) {
return run(ctx, raw, mgr, pluginID)
})
return func(ctx context.Context, raw json.RawMessage) (any, error) {
if err := authorizeHostMethod(mgr, pluginID, method); err != nil {
if h.app != nil && !strings.Contains(strings.ToLower(err.Error()), "rate limit") {
h.app.abortAgentSessionsForPluginPermissionDenial(mgr, pluginID, parseVMRefFromRaw(raw), "permission_denied", method == "host/session.begin")
}
return nil, err
}
result, err := run(ctx, raw, mgr, pluginID)
broker := mgr.Broker()
if err != nil {
broker.Audit(pluginID, "HOST_API_ERROR", method)
return nil, err
}
broker.Audit(pluginID, "HOST_API", method)
return result, nil
}
}
+2
View File
@@ -8,6 +8,8 @@ func (h *HostAPIService) Handlers(mgr *plugin.Manager, pluginID string) map[stri
out := map[string]plugin.RPCRequestHandler{}
for _, set := range []map[string]plugin.RPCRequestHandler{
h.app.computerUseHostHandlers(mgr, pluginID),
h.app.confirmHostHandlers(mgr, pluginID),
h.app.sessionHostHandlers(mgr, pluginID),
h.app.secretHostHandlers(mgr, pluginID),
h.app.downloadHostHandlers(mgr, pluginID),
h.elevateHostHandlers(mgr, pluginID),
+45 -29
View File
@@ -26,8 +26,7 @@ func isRecoveryModeActive(d reims.VMDetail) bool {
}
func isRecoveryMarkerActive(vmDir string) bool {
m := startprep.ReadRecoveryMarker(vmDir)
return m == "on" || m == "want"
return startprep.IsRecoveryMarkerActive(vmDir)
}
func (a *App) pickCachedRecoveryInstaller() (string, error) {
@@ -260,6 +259,44 @@ func (a *App) DownloadAndAttachOnlineRecovery(name, version string) (string, err
return id, nil
}
// applyFinishInstallResult mirrors driver finish_install deferred changes into
// App.pendingChanges, clears any stale provision-ready milestone, and records
// recovery-exit and wipe-warning logs consistently for GUI, CLI, and Host API.
func (a *App) applyFinishInstallResult(driverID, name string, result map[string]any) {
running, _ := result["running"].(bool)
if running {
var diffs []PendingChange
if value, _ := result["installer_ejected"].(bool); value {
diffs = append(diffs, PendingChange{Field: "installer", From: "attached", To: "ejected"})
}
if value, _ := result["network_enabled"].(bool); value {
diffs = append(diffs, PendingChange{Field: "network", From: "off", To: "on"})
}
if value, _ := result["upgraded_nvme"].(bool); value {
from, _ := result["disk_controller_from"].(string)
if from == "" {
from = "ahci"
}
diffs = append(diffs, PendingChange{Field: "disk_controller", From: from, To: "nvme"})
}
if value, _ := result["recovery_pending"].(bool); value {
diffs = append(diffs, PendingChange{Field: "recovery", From: "on", To: "off"})
}
if len(diffs) > 0 {
a.mu.Lock()
a.pendingChanges[vmKeyForDriver(driverID, name)] = append(a.pendingChanges[vmKeyForDriver(driverID, name)], diffs...)
a.mu.Unlock()
}
}
if wiped, ok := result["provision_wiped"].(bool); ok && !wiped {
if detail, _ := result["provision_wipe_error"].(string); detail != "" {
a.emitVMLog(name, "Warning: could not remove offline provisioning disk (REIMSPROV) while running; scheduled wipe for next start: "+detail)
}
}
a.clearTelemetryMilestone(vmKeyForDriver(driverID, name), "serial:provision_ready")
a.emitVMLog(name, "Exited recovery mode")
}
// FinishInstall exits recovery through the owning driver and mirrors deferred
// changes into the existing App pending-change model.
func (a *App) FinishInstall(name string) error {
@@ -283,32 +320,7 @@ func (a *App) FinishInstall(name string) error {
return err
}
result, _ := raw.(map[string]any)
running, _ := result["running"].(bool)
if running {
var diffs []PendingChange
if value, _ := result["installer_ejected"].(bool); value {
diffs = append(diffs, PendingChange{Field: "installer", From: "attached", To: "ejected"})
}
if value, _ := result["network_enabled"].(bool); value {
diffs = append(diffs, PendingChange{Field: "network", From: "off", To: "on"})
}
if value, _ := result["upgraded_nvme"].(bool); value {
from, _ := result["disk_controller_from"].(string)
if from == "" {
from = "ahci"
}
diffs = append(diffs, PendingChange{Field: "disk_controller", From: from, To: "nvme"})
}
if value, _ := result["recovery_pending"].(bool); value {
diffs = append(diffs, PendingChange{Field: "recovery", From: "on", To: "off"})
}
if len(diffs) > 0 {
a.mu.Lock()
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], diffs...)
a.mu.Unlock()
}
}
a.emitVMLog(name, "Exited recovery mode")
a.applyFinishInstallResult(vm.DriverID, name, result)
a.wakePoll()
a.emitStateChanged()
return nil
@@ -338,7 +350,7 @@ func (a *App) finishMacOSInstall(name string) error {
return err
}
}
stripped := reims.StripOfflineHelperArgs(d.ExtraArgs)
stripped := reims.StripProvisionArgs(reims.StripOfflineHelperArgs(d.ExtraArgs))
setOpts := reims.SetOpts{Name: name}
needSet := false
upgradedNVMe := false
@@ -363,6 +375,10 @@ func (a *App) finishMacOSInstall(name string) error {
return err
}
}
if err := installer.SecureRemoveProvisionImage(d.Directory); err != nil {
a.emitVMLog(name, "Warning: could not remove offline provisioning disk (REIMSPROV) now; scheduled wipe for next start: "+err.Error())
}
a.clearTelemetryMilestone(vmKey(name), "serial:provision_ready")
running := c.IsRunning(ctx, d)
marker := startprep.ReadRecoveryMarker(d.Directory)
+262 -4
View File
@@ -2,6 +2,7 @@ package app
import (
"context"
"strings"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
@@ -75,6 +76,223 @@ func installGuideKind(d reims.VMDetail) (installguide.Kind, bool) {
return installguide.BuiltIn, startprep.ReadRecoveryMarker(d.Directory) == "on"
}
func (a *App) suppressInstallGuideForVM(name string) bool {
if gm := a.getInstallGuideManager(); gm != nil && name != "" {
return gm.Cancel(name)
}
return false
}
func (a *App) markInstallGuideRecheck(name string) {
name = strings.TrimSpace(name)
if name == "" {
return
}
a.mu.Lock()
if a.guideRecheckVMs == nil {
a.guideRecheckVMs = map[string]bool{}
}
a.guideRecheckVMs[name] = true
a.mu.Unlock()
}
func (a *App) consumeInstallGuideRecheck(name string) bool {
if name == "" {
return false
}
a.mu.Lock()
ok := a.guideRecheckVMs[name]
if ok {
delete(a.guideRecheckVMs, name)
}
a.mu.Unlock()
return ok
}
func (a *App) setPendingInstallGuideHandoff(name, step string) {
name = strings.TrimSpace(name)
if name == "" || step == "" {
return
}
a.mu.Lock()
if a.pendingGuideHandoffs == nil {
a.pendingGuideHandoffs = map[string]string{}
}
// Preserve a pending desktop handoff if already scheduled.
if cur := a.pendingGuideHandoffs[name]; cur != string(installguide.StepDesktop) || step == string(installguide.StepDesktop) {
a.pendingGuideHandoffs[name] = step
}
a.mu.Unlock()
}
func (a *App) hasPendingInstallGuideHandoff(name string) bool {
if name == "" {
return false
}
a.mu.Lock()
_, ok := a.pendingGuideHandoffs[name]
a.mu.Unlock()
return ok
}
func (a *App) applyPendingInstallGuideHandoff(name, dir string) {
if name == "" || dir == "" {
return
}
a.mu.Lock()
step, ok := a.pendingGuideHandoffs[name]
if ok {
delete(a.pendingGuideHandoffs, name)
}
a.mu.Unlock()
if ok && step != "" {
_ = installguide.AdvancePostInstallHandoff(dir, name, installguide.Offline, installguide.PostInstallStep(step))
}
}
func isMacOSDriverID(driverID string) bool {
id := driver.CanonicalDriverID(strings.TrimSpace(driverID))
return id == "" || id == driver.BuiltinReimsMacOSDriverID
}
func (a *App) cachedVMDir(driverID, name string) string {
driverID = driver.CanonicalDriverID(driverID)
if driverID == "" {
driverID = driver.BuiltinReimsMacOSDriverID
}
a.mu.Lock()
defer a.mu.Unlock()
for _, vm := range a.lastVMs {
if vm.Name == name && driver.CanonicalDriverID(vm.DriverID) == driverID && strings.TrimSpace(vm.Dir) != "" {
return strings.TrimSpace(vm.Dir)
}
}
return ""
}
func (a *App) cachedRunningVMPID(driverID, name string) int {
driverID = driver.CanonicalDriverID(driverID)
if driverID == "" {
driverID = driver.BuiltinReimsMacOSDriverID
}
a.mu.Lock()
defer a.mu.Unlock()
for _, vm := range a.lastVMs {
if vm.Name == name && driver.CanonicalDriverID(vm.DriverID) == driverID && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
return *vm.PID
}
}
return 0
}
// restoreManualInstallGuideFallback ensures the original manual installation
// guide is re-evaluated (or unfolded if already active in compact form) when a
// plugin cannot run — for example after the user denies protected-phase or
// plugin execution permission.
func (a *App) restoreManualInstallGuideFallback(driverID, vmName string) bool {
vmName = strings.TrimSpace(vmName)
if vmName == "" || !isMacOSDriverID(driverID) {
return false
}
vmKey := vmKeyForDriver(driverID, vmName)
a.dismissCompletedOverlay(vmKey)
a.markInstallGuideRecheck(vmName)
if gm := a.getInstallGuideManager(); gm != nil {
if pid := a.cachedRunningVMPID(driverID, vmName); pid > 0 && gm.HasActive(vmName, pid) {
gm.Unfold(vmName, pid)
}
}
a.wakePoll()
a.emitStateChanged()
return a.installGuideEnabled()
}
// prepareInstallGuideFinishHandoff snapshots a macOS VM's recovery state BEFORE
// `finish_install` modifies disk/recovery markers, returning a commit callback
// that persists the matching post-install manual guide checkpoint once
// `finish_install` succeeds.
func (a *App) prepareInstallGuideFinishHandoff(vm driver.VMInfo) func(running bool, pid int) bool {
if driver.CanonicalDriverID(vm.DriverID) != driver.BuiltinReimsMacOSDriverID {
return func(bool, int) bool { return false }
}
if vm.Directory == "" {
vm.Directory = a.cachedVMDir(vm.DriverID, vm.Name)
}
d, err := macOSDetailFromVMInfo(vm)
if err != nil || d.Directory == "" {
return func(bool, int) bool { return false }
}
kind, recovery := installGuideKind(d)
if !recovery {
return func(bool, int) bool { return false }
}
step := installguide.StepSetup
if kind == installguide.BuiltIn {
step = installguide.StepRestored
}
vmName, vmDir, media := vm.Name, d.Directory, d.InstallerPath
return func(running bool, pid int) bool {
var restartFrom uint32
if running && pid > 0 {
restartFrom = uint32(pid)
}
return installguide.SavePostInstallHandoff(vmDir, vmName, kind, media, step, restartFrom) == nil
}
}
// prepareInstallGuideRestoreAfterSession ensures the original manual install
// guide will reappear on the VM window after an auto-install or Agent session
// exits (whether stopped manually by the user, failed, plugin-disabled, or
// completed). It returns true when the native VM-window install guide is
// enabled and will take over the VM window so any colliding completed session
// island is dismissed cleanly.
func (a *App) prepareInstallGuideRestoreAfterSession(sess *agentSession, completed bool) bool {
if sess == nil || sess.vmName == "" {
return false
}
if !isMacOSDriverID(sess.driverID) {
return false
}
vmDir := strings.TrimSpace(sess.vmDir)
if vmDir == "" {
vmDir = a.cachedVMDir(sess.driverID, sess.vmName)
}
var targetStep installguide.PostInstallStep
if sess.isAutoInstall {
switch {
case completed && (strings.EqualFold(sess.autoInstallMode, "full") || (sess.autoInstallMode == "" && sess.sawSetupAssistant)):
targetStep = installguide.StepDesktop
case completed:
targetStep = installguide.StepSetup
case sess.stage == "stage6_desktop_ready":
targetStep = installguide.StepDesktop
case sess.finishInstallDone || sess.stage == "stage5_setup_assistant" || sess.stage == "stage5_wait_reboot":
targetStep = installguide.StepSetup
}
}
if targetStep != "" {
if vmDir != "" {
_ = installguide.AdvancePostInstallHandoff(vmDir, sess.vmName, installguide.Offline, targetStep)
} else {
a.setPendingInstallGuideHandoff(sess.vmName, string(targetStep))
}
}
a.markInstallGuideRecheck(sess.vmName)
if !a.installGuideEnabled() {
return false
}
if sess.isAutoInstall || sess.finishInstallDone || sess.suppressedInstallGuide {
return true
}
if vmDir != "" && installguide.HasPostInstallCheckpoint(vmDir, sess.vmName) {
return true
}
return a.hasPendingInstallGuideHandoff(sess.vmName)
}
// guideTracker follows the install guides of running VMs for the poll loop.
type guideTracker struct {
a *App
@@ -105,12 +323,33 @@ func (t *guideTracker) startMissing(ctx context.Context, vms []driver.VMListItem
}
started := false
for _, vm := range vms {
pid := vm.RunningPID()
// The install guide belongs to the macOS installer flow.
if pid == 0 || t.checked[pid] || !driver.SupportsCapability(vm.Capabilities, driver.CapOpenCore) {
if !driver.SupportsCapability(vm.Capabilities, driver.CapOpenCore) {
continue
}
det, ok := details[vmKeyForDriver(vm.DriverID, vm.Name)]
pid := vm.RunningPID()
if pid == 0 {
// Old PIDs were already pruned by prunePinnedPIDs; clear any stale recheck flag.
t.a.consumeInstallGuideRecheck(vm.Name)
continue
}
vmKey := vmKeyForDriver(vm.DriverID, vm.Name)
if t.a.hasActiveAgentSession(vmKey) {
// While an Agent/auto-install session owns the VM, never cache pid as
// checked so the original manual guide is re-evaluated as soon as it ends.
delete(t.checked, pid)
continue
}
if t.a.consumeInstallGuideRecheck(vm.Name) {
delete(t.checked, pid)
if t.mgr.HasActive(vm.Name, pid) {
t.mgr.Unfold(vm.Name, pid)
}
}
if t.checked[pid] {
continue
}
det, ok := details[vmKey]
if !ok {
var err error
if det, err = t.a.resolveVMInfo(vm.DriverID, vm.Name); err != nil {
@@ -120,9 +359,16 @@ func (t *guideTracker) startMissing(ctx context.Context, vms []driver.VMListItem
det.Directory = vm.Dir
}
}
t.a.applyPendingInstallGuideHandoff(vm.Name, det.Directory)
if t.a.hasActiveAgentSession(vmKey) {
delete(t.checked, pid)
continue
}
t.checked[pid] = true
if t.a.maybeStartInstallGuide(ctx, t.mgr, vm.Name, pid, det, loc) {
started = true
} else if t.a.hasActiveAgentSession(vmKey) {
delete(t.checked, pid)
}
}
return started
@@ -132,6 +378,10 @@ func (a *App) maybeStartInstallGuide(ctx context.Context, gm *installguide.Manag
if gm == nil || pid <= 0 || gm.HasActive(name, pid) {
return false
}
vmKey := vm.Ref().Key()
if a.hasActiveAgentSession(vmKey) {
return false
}
d, err := macOSDetailFromVMInfo(vm)
if err != nil {
return false
@@ -148,7 +398,15 @@ func (a *App) maybeStartInstallGuide(ctx context.Context, gm *installguide.Manag
if !g.Resume(d.Directory, d.InstallerPath, recovery) {
return false
}
return gm.Start(ctx, a.buildInstallGuide(ctx, g, d))
if !gm.Start(ctx, a.buildInstallGuide(ctx, g, d)) {
return false
}
if a.hasActiveAgentSession(vmKey) {
gm.Cancel(name)
return false
}
a.dismissCompletedOverlay(vmKey)
return true
}
func (a *App) buildInstallGuide(ctx context.Context, g installguide.Guide, d reims.VMDetail) installguide.Guide {
File diff suppressed because it is too large. Load diff
+82 -10
View File
@@ -8,6 +8,9 @@ import (
"fmt"
"strings"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/applevz"
"github.com/Nwflower/reims-go/internal/macos/guest"
"github.com/Nwflower/reims-go/internal/macos/installer"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
@@ -26,6 +29,14 @@ func (a *App) installerClient() (*installer.Client, error) {
// ListOfflineReleases lists the offline installers Apple offers, newest first.
// It reads Apple's catalog (a few seconds, needs the network).
func (a *App) ListOfflineReleases() ([]installer.Release, error) {
if guest.UsesAppleVirtualization() {
release, err := a.latestRestoreRelease(a.baseCtx())
if err != nil {
return nil, err
}
release.URL, release.Digest = "", "" // The UI selects a release, never a CDN URL or checksum.
return []installer.Release{release}, nil
}
c, err := a.installerClient()
if err != nil {
return nil, err
@@ -46,30 +57,72 @@ func (a *App) DownloadInstaller(version string) (string, error) {
if version == "" {
return "", fmt.Errorf("no version given")
}
if guest.UsesAppleVirtualization() {
return a.startRestoreImageDownload(version)
}
c, err := a.installerClient()
if err != nil {
return "", err
}
a.ensureTaskEmitter()
base := a.ctx
if base == nil {
base = context.Background()
return a.startInstallerDownload("offline", version, func(ctx context.Context, update func(installer.Update)) (*installer.Result, error) {
return c.DownloadOffline(ctx, version, update)
}), nil
}
func (a *App) startRestoreImageDownload(version string) (string, error) {
a.selectionMu.Lock()
defer a.selectionMu.Unlock()
if err := a.requireWritableDataRoot(); err != nil {
return "", err
}
cfg := a.runtimeConfig()
cache := installer.RestoreCache{Dir: installer.RestoreDir(&cfg)}
return a.startInstallerDownload(installer.RestoreKind, version, func(ctx context.Context, update func(installer.Update)) (*installer.Result, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
release, err := a.latestRestoreRelease(ctx)
if err != nil {
return nil, err
}
if release.Version != version {
return nil, errors.New("the compatible macOS restore image changed; refresh the catalog before downloading")
}
return cache.Download(ctx, release, update)
}), nil
}
func (a *App) latestRestoreRelease(ctx context.Context) (installer.Release, error) {
release, err := installer.LatestRestore(ctx)
if err == nil || errors.Is(err, context.Canceled) {
return release, err
}
key := "err.restore_catalog_unavailable"
if errors.Is(err, applevz.ErrRestoreCatalogUnsupported) {
key = "err.restore_catalog_unsupported"
}
a.emitLog("installer", "Apple restore catalog: "+err.Error())
return installer.Release{}, i18n.NewCodedError(a.locale(), "E_RESTORE_CATALOG", key, nil, err)
}
func (a *App) startInstallerDownload(kind, version string, download installerDownloadFunc) string {
a.ensureTaskEmitter()
base := a.baseCtx()
var (
ctx context.Context
cancel context.CancelFunc
)
run, id, owned := installerDownloads.reserveOrFind("offline", version, "installer-download", func(initialPhase string) string {
run, id, owned := installerDownloads.reserveOrFind(kind, version, "installer-download", func(initialPhase string) string {
ctx, cancel = context.WithCancel(base)
return tasks.startWithInstaller("installer-download", version, "", "offline", version, initialPhase, cancel)
return tasks.startWithInstaller("installer-download", version, "", kind, version, initialPhase, cancel)
})
if !owned {
return id, nil
return id
}
a.emitLog("installer", "Downloading macOS "+version+" offline installer")
a.emitLog("installer", "Downloading macOS "+version+" ("+kind+")")
go func() {
defer cancel()
res, err := c.DownloadOffline(ctx, version, func(u installer.Update) {
res, err := download(ctx, func(u installer.Update) {
switch u.Kind {
case installer.KindStep, installer.KindNote:
a.emitLog("installer", u.Message)
@@ -93,11 +146,18 @@ func (a *App) DownloadInstaller(version string) (string, error) {
tasks.finish(id, "", err)
}
}()
return id, nil
return id
}
// ListInstallers lists the downloaded installers kept for new VMs.
func (a *App) ListInstallers() ([]installer.Cached, error) {
if guest.UsesAppleVirtualization() {
if !a.dataRootUsable() {
return nil, nil
}
cfg := a.runtimeConfig()
return (installer.RestoreCache{Dir: installer.RestoreDir(&cfg)}).List()
}
c, err := a.installerClient()
if err != nil {
return nil, err
@@ -108,6 +168,18 @@ func (a *App) ListInstallers() ([]installer.Cached, error) {
// DeleteInstaller deletes a downloaded installer through reims-ctl, which
// refuses one a VM boots from or one being downloaded.
func (a *App) DeleteInstaller(name string) error {
if guest.UsesAppleVirtualization() {
a.selectionMu.Lock()
defer a.selectionMu.Unlock()
if err := a.requireWritableDataRoot(); err != nil {
return err
}
if tasks.hasRunningRestore() {
return errors.New("cannot delete a restore image while a macOS installation is running")
}
cfg := a.runtimeConfig()
return (installer.RestoreCache{Dir: installer.RestoreDir(&cfg)}).Delete(a.baseCtx(), name)
}
c, err := a.installerClient()
if err != nil {
return err
+1 -1
View File
@@ -17,7 +17,7 @@ type installerDownloadFunc func(ctx context.Context, onUpdate func(installer.Upd
// progress, deduplicate the same release, and surface queueing cleanly.
type installerDownloadRun struct {
key string
kind string // "offline" | "online"
kind string // "offline" | "online" | "ipsw"
version string
ownerID string
ownerKind string // "installer-download" | "vm-create" | "recovery-download"
+7
View File
@@ -162,6 +162,9 @@ func (a *App) startResolvedVMLocked(ctx context.Context, svc interface {
a.startVMMonitor(ref.Name, detail, startAt)
}
a.wakePoll()
if a.hasActiveAgentSession(key) {
go a.refreshActiveAgentSessionAfterStart(key)
}
a.emitStateChanged()
return nil
}
@@ -328,6 +331,10 @@ func (a *App) DeleteVM(driverID, name string, keepFiles bool) error {
stopVMMonitor(ref.Name)
a.stopPacketBridge(ref.Name)
}
_ = a.StopAgentSession(ref.DriverID, ref.Name)
a.telemetryMu.Lock()
delete(a.vmTelemetry, key)
a.telemetryMu.Unlock()
a.mu.Lock()
delete(a.pendingChanges, key)
delete(a.transitions, key)
+77
View File
@@ -117,6 +117,41 @@ func (d *appSecondDriver) InvokeAction(_ context.Context, _ string, action strin
return d.actionResults[action], nil
}
type nativeViewerDriver struct {
*appSecondDriver
shown string
}
func (d *nativeViewerDriver) ShowWindow(_ context.Context, name string) error {
d.shown = name
return nil
}
func TestHostedViewerIsOpenedThroughTheOwningDriver(t *testing.T) {
const id = "test.driver.viewer"
drv := &nativeViewerDriver{appSecondDriver: &appSecondDriver{id: id, vms: []driver.VMInfo{{
Name: "desktop", State: "running", Capabilities: []string{driver.CapHosted, driver.CapWindow},
}}}}
reg := plugin.NewRegistry(nil)
if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: id, Version: "1.0.0"},
Source: plugin.SourceBuiltin, Desired: true, Activate: func(_ context.Context, sc *plugin.Scope) error {
reg.RegisterGuestDriver(sc, id, drv)
return nil
}}); err != nil {
t.Fatal(err)
}
reg.Reconcile(t.Context())
router := driver.NewRouter(reg, nil)
a := &App{driverRouter: router, lifecycleSvc: vmlifecycle.New(reg, router, nil)}
if err := a.FocusVMWindow(id, "desktop"); err != nil || drv.shown != "desktop" {
t.Fatalf("focus hosted viewer: shown=%q, err=%v", drv.shown, err)
}
drv.shown, drv.vms[0].State = "", "stopped"
if err := a.FocusVMWindow(id, "desktop"); err == nil || drv.shown != "" {
t.Fatalf("focus stopped VM: shown=%q, err=%v", drv.shown, err)
}
}
func TestAppSecondDriverUserEntry(t *testing.T) {
const driverID = "test.driver.linux"
drv := &appSecondDriver{id: driverID, vms: []driver.VMInfo{{Name: "ubuntu", DriverID: driverID, Directory: t.TempDir(), State: "stopped"}}}
@@ -257,6 +292,48 @@ func TestSameNameVMsAcrossDriversStayIndependent(t *testing.T) {
}
}
func TestDeleteVMClearsTelemetryAndAgentSession(t *testing.T) {
const driverID = "test.driver.cleanup"
drv := &appSecondDriver{
id: driverID,
vms: []driver.VMInfo{{Name: "dev", DriverID: driverID, Directory: t.TempDir(), State: "stopped"}},
}
reg := plugin.NewRegistry(nil)
if err := reg.Register(plugin.PluginDef{
Manifest: plugin.Manifest{ID: "test.cleanup", Version: "1.0.0"},
Source: plugin.SourceBuiltin, Desired: true,
Activate: func(_ context.Context, sc *plugin.Scope) error {
reg.RegisterGuestDriver(sc, driverID, drv)
return nil
},
}); err != nil {
t.Fatal(err)
}
reg.Reconcile(context.Background())
a := &App{
cfg: &config.Config{DataRoot: t.TempDir()},
lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil),
transitions: map[string]string{},
pendingChanges: map[string][]PendingChange{},
}
key := drv.vms[0].Ref().Key()
a.recordTelemetryMilestone(key, "boot")
a.beginAgentSession(nil, "test.plugin", drv.vms[0], "Auto", "stage1", "manual", true)
if err := a.DeleteVM(driverID, "dev", false); err != nil {
t.Fatal(err)
}
if a.hasActiveAgentSession(key) {
t.Fatal("agent session remained active after deleting VM")
}
a.telemetryMu.Lock()
_, hasTelemetry := a.vmTelemetry[key]
a.telemetryMu.Unlock()
if hasTelemetry {
t.Fatal("telemetry state remained after deleting VM")
}
}
func TestStopVMMonitorWaitsForExitAndAllowsDirRemoval(t *testing.T) {
vmDir := t.TempDir()
logDir := filepath.Join(vmDir, "logs")
+40 -4
View File
@@ -101,6 +101,13 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) {
}
a.emitVMLog(name, "Win10 WHPX cold-reboot: guest requested reboot (guest-reset), restarting in a fresh Hyper-V partition...")
a.recordTelemetryColdReboot(vmKey(name))
restarted := false
defer func() {
if !restarted {
a.clearTelemetryColdRebootPreserve(vmKey(name))
}
}()
oldPID := a.cachedVMPID(name)
c, err := a.client()
if err != nil {
@@ -162,6 +169,8 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) {
}
if err := a.StartVM(driver.BuiltinReimsMacOSDriverID, name); err != nil {
a.emitVMLog(name, "Win10 WHPX cold-reboot start failed: "+err.Error())
} else {
restarted = true
}
}()
}
@@ -169,21 +178,48 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) {
// restartMacOSVM restarts a built-in macOS VM, waiting for the old QEMU
// process and its committed memory to go away before starting again.
func (a *App) restartMacOSVM(ctx context.Context, name string) (stopped bool, err error) {
return a.restartMacOSVMWithGrace(ctx, name, 0)
}
// restartMacOSVMWithGrace restarts a built-in macOS VM. When gracefulTimeout > 0
// and soft ACPI shutdown does not exit within gracefulTimeout (for example at
// macOS Setup Assistant or Login Window, which ignore ACPI power buttons), it
// falls back cleanly to a forced stop instead of stalling for stop_timeout_secs.
func (a *App) restartMacOSVMWithGrace(ctx context.Context, name string, gracefulTimeout time.Duration) (stopped bool, err error) {
vm, err := a.resolveVMInfo(driver.BuiltinReimsMacOSDriverID, name)
if err != nil {
return false, err
}
err = a.withComputerUseVM(ctx, vm.Directory, func(operationCtx context.Context) error {
stopped, err = a.restartMacOSVMLocked(operationCtx, name)
stopped, err = a.restartMacOSVMLocked(operationCtx, name, gracefulTimeout)
return err
})
return stopped, err
}
func (a *App) restartMacOSVMLocked(ctx context.Context, name string) (stopped bool, err error) {
func (a *App) restartMacOSVMLocked(ctx context.Context, name string, gracefulTimeout time.Duration) (stopped bool, err error) {
oldPID := a.cachedVMPID(name)
if err := a.stopVM(ctx, driver.BuiltinReimsMacOSDriverID, name, false); err != nil {
return false, err
if gracefulTimeout > 0 {
graceCtx, graceCancel := context.WithTimeout(ctx, gracefulTimeout)
stopErr := a.stopVM(graceCtx, driver.BuiltinReimsMacOSDriverID, name, false)
graceTimedOut := errors.Is(graceCtx.Err(), context.DeadlineExceeded) || errors.Is(stopErr, context.DeadlineExceeded)
graceCancel()
if stopErr != nil {
if ctx.Err() != nil {
return false, ctx.Err()
}
if !graceTimedOut {
return false, fmt.Errorf("graceful stop before restart: %w", stopErr)
}
a.emitVMLog(name, fmt.Sprintf("Graceful ACPI shutdown did not exit within %s; forcing restart...", gracefulTimeout))
if err := a.stopVM(ctx, driver.BuiltinReimsMacOSDriverID, name, true); err != nil {
return false, err
}
}
} else {
if err := a.stopVM(ctx, driver.BuiltinReimsMacOSDriverID, name, false); err != nil {
return false, err
}
}
a.waitForVMProcessExit(ctx, oldPID, vmExitWaitTimeout)
if c, err := a.client(); err == nil {
+73
View File
@@ -4,6 +4,10 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"path/filepath"
"runtime"
"strings"
"github.com/Nwflower/reims-go/internal/control"
"github.com/Nwflower/reims-go/internal/plugin"
@@ -23,6 +27,9 @@ func (a *App) startPluginControlServer() {
return a.pluginMgr
}
server, err := control.ListenWithOptions(control.PipeName(), func(ctx context.Context, pluginID, channel string, message json.RawMessage) (json.RawMessage, error) {
if pluginID == control.HostPluginID && channel == control.ChannelAutoInstall {
return a.handleControlAutoInstall(ctx, message)
}
mgr := currentManager()
if mgr == nil {
return nil, errors.New("plugin manager is not ready")
@@ -34,6 +41,9 @@ func (a *App) startPluginControlServer() {
return
}
for _, target := range targets {
if target.PluginID == control.HostPluginID {
continue
}
mgr.ChannelSessionClosed(target.PluginID, target.Channel, session)
}
}})
@@ -52,6 +62,69 @@ func (a *App) startPluginControlServer() {
a.mu.Unlock()
}
func sameDataRoot(aPath, bPath string) bool {
aClean := filepath.Clean(strings.TrimSpace(aPath))
bClean := filepath.Clean(strings.TrimSpace(bPath))
if runtime.GOOS == "windows" {
return strings.EqualFold(aClean, bClean)
}
return aClean == bClean
}
func (a *App) handleControlAutoInstall(ctx context.Context, message json.RawMessage) (json.RawMessage, error) {
var req control.AutoInstallRequest
if err := json.Unmarshal(message, &req); err != nil {
return nil, fmt.Errorf("invalid auto-install control request: %w", err)
}
action := strings.ToLower(strings.TrimSpace(req.Action))
a.mu.Lock()
appRoot := ""
if a.cfg != nil {
appRoot = a.cfg.DataRoot
}
a.mu.Unlock()
reqRoot := strings.TrimSpace(req.DataRoot)
mutating := action == "resume" || action == "stop"
if appRoot != "" && ((mutating && reqRoot == "") || (reqRoot != "" && !sameDataRoot(reqRoot, appRoot))) {
return nil, errors.New("data_root_mismatch: running desktop app uses a different data directory")
}
var (
res any
err error
)
switch action {
case "status":
if strings.TrimSpace(req.VMName) == "" {
res, err = a.listAutoInstallStatuses(req.PluginID)
} else {
res, err = a.GetAutoInstallStatus(req.PluginID, req.DriverID, req.VMName)
}
case "resume":
if strings.TrimSpace(req.VMName) == "" {
return nil, errors.New("vm name is required for auto-install resume")
}
res, err = a.resumeAutoInstallFromControl(ctx, req.PluginID, req.DriverID, req.VMName)
case "stop":
if strings.TrimSpace(req.VMName) == "" {
return nil, errors.New("vm name is required for auto-install stop")
}
if err = a.StopAutoInstall(req.PluginID, req.DriverID, req.VMName); err == nil {
res = map[string]any{"ok": true}
}
case "diagnostic":
if strings.TrimSpace(req.VMName) == "" {
return nil, errors.New("vm name is required for auto-install diagnostic")
}
res, err = a.GetAutoInstallDiagnosticSummary(req.PluginID, req.DriverID, req.VMName)
default:
return nil, fmt.Errorf("unknown auto-install control action %q", req.Action)
}
if err != nil {
return nil, err
}
return json.Marshal(res)
}
func (a *App) stopPluginControlServer() {
a.mu.Lock()
server := a.controlServer
+92 -9
View File
@@ -88,6 +88,9 @@ func (a *App) initPlugins() {
a.mu.Lock()
current := a.pluginMgr
a.mu.Unlock()
if current == nil {
current = mgr
}
return a.hostAPISvc().Handlers(current, pluginID)
},
OnSettingsChanged: func(pluginID, vmName string) {
@@ -98,7 +101,7 @@ func (a *App) initPlugins() {
// longer release it, so the host lifts what it left down.
a.releaseHeldForPlugin(pluginID)
},
VMInventory: guest.VMInventory(),
VMInventories: guest.VMInventories(),
Callbacks: builtin.HostCallbacks{
GetConfig: a.runtimeConfig,
Log: func(source, line string) {
@@ -170,7 +173,7 @@ func (a *App) initPlugins() {
a.wakePoll()
},
},
RegisterGuest: guest.Register,
RegisterGuest: guest.RegisterForHost,
})
if err != nil {
a.emitLog("plugin", "Could not initialize plugin manager: "+err.Error())
@@ -209,6 +212,7 @@ func (a *App) initPlugins() {
a.syncInputFilters()
a.syncClipboardPolicies()
a.syncLocales()
a.stopAgentSessionsForInactivePlugins(mgr)
a.wakePoll()
a.emitStateChanged()
})
@@ -472,11 +476,36 @@ func (a *App) syncClipboardPolicies() {
gt.SetGlobalClipboardPolicy(clipboardPolicyFromMap(globalVals))
}
func (a *App) normalizeVMKey(vmRef string) string {
vmRef = strings.TrimSpace(vmRef)
if vmRef == "" {
return ""
}
if vm, err := a.resolveComputerUseVMInfo(vmRef); err == nil {
return vm.Ref().Key()
}
if ref, ok := driver.ParseVMRef(vmRef); ok {
return ref.Key()
}
return vmKeyForDriver("", vmRef)
}
func (a *App) onPluginSettingsChanged(pluginID, vmName string) {
a.syncInputFilters()
if pluginID == builtin.IDClipboard {
a.syncClipboardPolicies()
}
if vmName != "" && pluginID != "" {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr != nil {
vmKey := a.normalizeVMKey(vmName)
if a.hasActiveAgentSessionOwnedBy(vmKey, pluginID) && !a.computerUseVMAccessEnabled(mgr, pluginID, vmKey) {
a.handlePluginPermissionDeniedForVM(mgr, pluginID, vmKey, "", "permission_denied")
}
}
}
if pluginID == guest.ID && vmName == "" {
a.mu.Lock()
mgr := a.pluginMgr
@@ -765,9 +794,7 @@ func (a *App) GetPluginUIContributions() PluginUIContributions {
if kr != nil {
out.RuntimeKinds = kr.List()
}
if dr != nil {
out.Drivers = dr.Summaries()
}
out.Drivers = desktopDriverSummaries(dr)
return out
}
@@ -829,10 +856,39 @@ func (a *App) ListDrivers() []driver.DriverSummary {
a.mu.Lock()
dr := a.driverRouter
a.mu.Unlock()
if dr == nil {
return desktopDriverSummaries(dr)
}
func desktopDriverSummaries(router *driver.Router) []driver.DriverSummary {
list := router.Summaries()
if !guest.UsesAppleVirtualization() {
return list
}
for i := range list {
if list[i].ID == guest.AppleDriverID() {
list[i].Builtin = true
list[0], list[i] = list[i], list[0]
break
}
}
return list
}
func (a *App) nativeVirtualizationStatus() *host.AppleVirtualizationStatus {
if !guest.UsesAppleVirtualization() {
return nil
}
return dr.Summaries()
a.appleVZProbeOnce.Do(func() {
ctx, cancel := context.WithTimeout(a.baseCtx(), 5*time.Second)
defer cancel()
if err := guest.ProbeAppleVirtualization(ctx); err != nil {
a.appleVZProbe.Detail = host.RedactText(err.Error())
return
}
a.appleVZProbe.Ready = true
})
status := a.appleVZProbe
return &status
}
func (a *App) CreateVMWithDriver(req driver.CreateRequest) error {
@@ -874,8 +930,12 @@ func (a *App) CreateVMWithDriver(req driver.CreateRequest) error {
if issues := drv.ValidateCreate(ctx, req); len(issues) > 0 {
return errors.New(issues[0].Message)
}
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(req.DriverID, req.Name, line) })
if err := drv.Create(ctx, req, w, w); err != nil {
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(drv.ID(), req.Name, line) })
if drv.ID() == guest.AppleDriverID() {
if err := a.restoreAppleVM(dr, drv, req, w); err != nil {
return err
}
} else if err := drv.Create(ctx, req, w, w); err != nil {
return err
}
if mgr != nil {
@@ -889,6 +949,29 @@ func (a *App) CreateVMWithDriver(req driver.CreateRequest) error {
return nil
}
func (a *App) restoreAppleVM(router *driver.Router, drv driver.Driver, req driver.CreateRequest, w vmstart.LineWriter) error {
ctx, cancel := context.WithCancel(a.baseCtx())
defer cancel()
a.selectionMu.Lock()
a.mu.Lock()
stillCurrent := a.driverRouter == router && !a.allowQuit && a.quitMode == ""
a.mu.Unlock()
if !stillCurrent {
a.selectionMu.Unlock()
return errors.New("virtual machine restore could not start because the workspace changed")
}
a.ensureTaskEmitter()
id := tasks.start("vm-restore", req.Name, driver.NewVMRef(drv.ID(), req.Name).Key(), cancel)
a.selectionMu.Unlock()
defer func() {
a.wakePoll()
a.emitStateChanged()
}()
err := drv.Create(ctx, req, w, w)
tasks.finish(id, req.Name, err)
return err
}
// InspectPluginArchive runs the unified static security scanner on a local .zip
// package before installing it so the UI can display hard blockers, capabilities,
// and L3 native execution notices.
+106
View File
@@ -0,0 +1,106 @@
package app
import (
"bytes"
"os"
"path/filepath"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/installer"
)
func TestPrepareVMProvisionForDir_HashOnlyAndCleanup(t *testing.T) {
dataRoot := t.TempDir()
vmDir := filepath.Join(dataRoot, "vms", "tahoe-prov")
if err := os.MkdirAll(vmDir, 0o755); err != nil {
t.Fatal(err)
}
a := &App{
cfg: &config.Config{DataRoot: dataRoot},
}
const secret = "ProvTestPass-2026!"
noTools := false
err := a.prepareVMProvisionForDir("tahoe-prov", vmDir, ProvisionRequest{
FullName: "Test User",
AccountName: "testuser",
Password: secret,
Appearance: "dark",
SLAAccepted: true,
InstallGuestTools: &noTools,
})
if err != nil {
t.Fatalf("prepareVMProvisionForDir: %v", err)
}
if !a.hasVMProvisionDir(vmDir) {
t.Fatalf("expected hasVMProvisionDir to report true")
}
imgPath := installer.ProvisionImagePath(vmDir)
raw, err := os.ReadFile(imgPath)
if err != nil {
t.Fatalf("read provision image: %v", err)
}
if bytes.Contains(raw, []byte(secret)) {
t.Fatalf("provision disk image must never contain plaintext password")
}
// Re-running prepareVMProvisionForDir with new credentials must rebuild the
// REIMSPROV image rather than silently keeping stale credentials on disk.
const newSecret = "UpdatedProvPass-2026!"
if err := a.prepareVMProvisionForDir("tahoe-prov", vmDir, ProvisionRequest{
FullName: "Second User",
AccountName: "seconduser",
Password: newSecret,
Appearance: "light",
SLAAccepted: true,
InstallGuestTools: &noTools,
}); err != nil {
t.Fatalf("rebuild prepareVMProvisionForDir: %v", err)
}
rebuilt, err := os.ReadFile(imgPath)
if err != nil {
t.Fatalf("read rebuilt provision image: %v", err)
}
if bytes.Contains(rebuilt, []byte(newSecret)) {
t.Fatal("rebuilt provision image must never contain plaintext password")
}
if !bytes.Contains(rebuilt, []byte("seconduser")) {
t.Fatal("rebuilt provision image must reflect updated account name")
}
if err := installer.SecureRemoveProvisionImage(vmDir); err != nil {
t.Fatalf("SecureRemoveProvisionImage: %v", err)
}
if a.hasVMProvisionDir(vmDir) {
t.Fatalf("expected hasVMProvisionDir to report false after removal")
}
}
func TestSerialProvisionReadyMilestone(t *testing.T) {
key, label := parseSerialMilestone(i18n.EnUS, "com.reimsgo.provision-ready: "+installer.ProvisionSerialReadyMarker)
if key != "serial:provision_ready" {
t.Fatalf("parseSerialMilestone key = %q, want serial:provision_ready", key)
}
if label == "" {
t.Fatalf("parseSerialMilestone label should not be empty")
}
a := &App{}
wantKey := vmKey("prov-ready-test-vm")
a.recordTelemetryMilestone(wantKey, key)
keys := a.provisionReadyVMKeys()
found := false
for _, k := range keys {
if k == wantKey {
found = true
break
}
}
if !found {
t.Fatalf("provisionReadyVMKeys() = %v, want %q", keys, wantKey)
}
}
Loaded 100 of 271 files, more files were not shown because too many files have changed in this diff. Show more