diff --git a/.github/changes/apple-virtualization.json b/.github/changes/apple-virtualization.json new file mode 100644 index 0000000..7be3cfa --- /dev/null +++ b/.github/changes/apple-virtualization.json @@ -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." +} diff --git a/.github/changes/macos-catalog-and-titlebar-polish.json b/.github/changes/macos-catalog-and-titlebar-polish.json new file mode 100644 index 0000000..6f02203 --- /dev/null +++ b/.github/changes/macos-catalog-and-titlebar-polish.json @@ -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." +} diff --git a/.github/changes/macos-client-build.json b/.github/changes/macos-client-build.json new file mode 100644 index 0000000..1d60ed8 --- /dev/null +++ b/.github/changes/macos-client-build.json @@ -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." +} diff --git a/.github/changes/macos-download-and-titlebar.json b/.github/changes/macos-download-and-titlebar.json new file mode 100644 index 0000000..f288ec5 --- /dev/null +++ b/.github/changes/macos-download-and-titlebar.json @@ -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." +} diff --git a/.github/changes/macos-memory-and-plugin-icons.json b/.github/changes/macos-memory-and-plugin-icons.json new file mode 100644 index 0000000..9af7f51 --- /dev/null +++ b/.github/changes/macos-memory-and-plugin-icons.json @@ -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." +} diff --git a/.github/changes/macos-menu-language.json b/.github/changes/macos-menu-language.json new file mode 100644 index 0000000..b043dff --- /dev/null +++ b/.github/changes/macos-menu-language.json @@ -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." +} diff --git a/.github/changes/macos-native-application-menu.json b/.github/changes/macos-native-application-menu.json new file mode 100644 index 0000000..f146e76 --- /dev/null +++ b/.github/changes/macos-native-application-menu.json @@ -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." +} diff --git a/.github/changes/macos-qq-group-and-ssh.json b/.github/changes/macos-qq-group-and-ssh.json new file mode 100644 index 0000000..fe7e09c --- /dev/null +++ b/.github/changes/macos-qq-group-and-ssh.json @@ -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." +} diff --git a/.github/changes/macos-review-reliability.json b/.github/changes/macos-review-reliability.json new file mode 100644 index 0000000..f3eb5dc --- /dev/null +++ b/.github/changes/macos-review-reliability.json @@ -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." +} diff --git a/.github/changes/nivfold-native-runtime.json b/.github/changes/nivfold-native-runtime.json new file mode 100644 index 0000000..805e9cc --- /dev/null +++ b/.github/changes/nivfold-native-runtime.json @@ -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." +} diff --git a/AGENTS.md b/AGENTS.md index 7de0e7f..029478b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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/`。 diff --git a/README.md b/README.md index 83da74e..a14d655 100644 --- a/README.md +++ b/README.md @@ -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. + ## FAQ diff --git a/README.zh-CN.md b/README.zh-CN.md index 93b42d0..dd96804 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -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。 + ## 常见问题 diff --git a/docs/architecture.md b/docs/architecture.md index 4caff99..c514f4c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -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 路径。多语言词表在编译期同时生成前后端字典,默认跟随系统语言并支持通过声明式语言包扩展。 ## 核心机制与安全边界 @@ -85,7 +85,7 @@ Npcap 桥接由可停用的内置扩展提供,通过逐台虚拟机的本地 U ### 托管型与进程型客体驱动 -客体驱动按虚拟机进程的归属分为两类。进程型驱动让宿主拉起虚拟机进程,宿主据此判断运行状态、定位显示窗口并绑定处理器核心。托管型驱动在声明中带有 `hosted` 能力,虚拟机由驱动自己的管理层运行,宿主不探测其进程与窗口,也不提供全屏和绑核入口;仅当驱动同时声明控制台能力时才开放截屏与键入。 +客体驱动按虚拟机进程的归属分为两类。进程型驱动让宿主拉起虚拟机进程,宿主据此判断运行状态、定位显示窗口并绑定处理器核心。托管型驱动在声明中带有 `hosted` 能力,虚拟机由驱动自己的管理层运行。宿主不探测托管型驱动的进程与窗口。声明查看窗口能力的驱动可自行唤出查看器。宿主不提供全屏和绑核入口;仅当驱动同时声明控制台能力时才开放截屏与键入。 托管型驱动通过宿主接口主动推送虚拟机的生命周期状态、就绪状态、所处阶段与客体系统信息。电源状态仍只取 `stopped`、`starting`、`running`、`stopping`、`suspended`、`broken` 与 `driver_unavailable`,就绪与阶段是独立字段,因此仍在启动中的客体显示为运行中但未就绪。推送缺失或过期时,宿主回退为向驱动查询。推送只对驱动自己名下的虚拟机生效。 @@ -111,6 +111,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) diff --git a/docs/design-guidelines.md b/docs/design-guidelines.md index bc5ac85..7294a05 100644 --- a/docs/design-guidelines.md +++ b/docs/design-guidelines.md @@ -35,7 +35,7 @@ ## 布局层级与视觉基线 -窗口由左侧可折叠侧栏(`Ctrl+B`)、右侧主内容区、底部常驻状态栏与可收起日志抽屉(`Ctrl+L`)组成。侧栏上方列出虚拟机实例与新建入口(`Ctrl+N`),下方固定提供「镜像」「插件」「内核」「设置」(`Ctrl+,`)与「关于」入口。虚拟机操作按钮固定在详情页头而非全局标题栏,避免切换页面时顶栏跳动。 +窗口由左侧可折叠侧栏(`Ctrl+B`)、右侧主内容区、底部常驻状态栏与可收起日志抽屉(`Ctrl+L`)组成。侧栏上方列出虚拟机实例与新建入口(`Ctrl+N`),下方固定提供「镜像」「插件」「内核」「设置」(`Ctrl+,`)与「关于」入口。虚拟机操作按钮固定在详情页头而非全局标题栏,避免切换页面时顶栏跳动。macOS 在系统菜单栏提供「虚拟机」「视图」和「帮助」菜单,应用及标准菜单均跟随界面语言,使用 `Command` 组合键;`Command+,` 打开应用设置,原有 `Ctrl` 快捷键仍可在窗口中使用。Windows 在窗口标题栏提供这三项菜单。 - 同一项硬件规格或运行状态在同一视图内只展示一次,相同动作不在同屏提供两个按钮出口。 - 页面只用单层分组容器或留白表达层级,禁止卡片嵌套卡片;下拉选择统一使用自绘弹出控件,不混用系统原生表单控件。 diff --git a/docs/pr-review-guidelines.md b/docs/pr-review-guidelines.md index 656b665..453671f 100644 --- a/docs/pr-review-guidelines.md +++ b/docs/pr-review-guidelines.md @@ -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#便携运行时与跨仓边界)。 | diff --git a/docs/testing.md b/docs/testing.md index f1a3dc2..5ed4c13 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -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`,验证安装、首次启动、重新显示窗口和正常关机。执行客体图形安装向导前必须确认。 diff --git a/frontend/scripts/test-application-menu.mjs b/frontend/scripts/test-application-menu.mjs new file mode 100644 index 0000000..26e2e95 --- /dev/null +++ b/frontend/scripts/test-application-menu.mjs @@ -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']) +}) diff --git a/frontend/scripts/test-endpoints.mjs b/frontend/scripts/test-endpoints.mjs index 076db6d..a6af764 100644 --- a/frontend/scripts/test-endpoints.mjs +++ b/frontend/scripts/test-endpoints.mjs @@ -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) diff --git a/frontend/scripts/test-guest-drivers.mjs b/frontend/scripts/test-guest-drivers.mjs new file mode 100644 index 0000000..5d8cfec --- /dev/null +++ b/frontend/scripts/test-guest-drivers.mjs @@ -0,0 +1,45 @@ +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('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) +}) diff --git a/frontend/scripts/test-restore-images.mjs b/frontend/scripts/test-restore-images.mjs new file mode 100644 index 0000000..e0d1be3 --- /dev/null +++ b/frontend/scripts/test-restore-images.mjs @@ -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) +}) diff --git a/frontend/scripts/test-tasks.mjs b/frontend/scripts/test-tasks.mjs index 7629b25..720e0ff 100644 --- a/frontend/scripts/test-tasks.mjs +++ b/frontend/scripts/test-tasks.mjs @@ -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 }) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 69c7496..373a78f 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -4,7 +4,9 @@ import type { WizardDraft } from './components/CreateWizard' import { AppDialogs } from './components/AppDialogs' 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 +15,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 { isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints' +import { 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,7 +34,7 @@ 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, CachedInstaller, CreateOpts, DriverSummary, Locale, PluginUIContributions, 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' @@ -48,6 +51,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 +107,15 @@ const failKey: Record = { export const App: React.FC = () => { const [state, setState] = useState(null) + const [nativeMenuReady, setNativeMenuReady] = useState(false) const [selected, setSelectedPage] = useState(HOST_ID) const [detail, setDetail] = useState(null) // GetVMInfo for the selected non-macOS VM; macOS VMs use `detail` (GetVMDetail). const [vmInfoLoaded, setVMInfoLoaded] = useState(null) const [detailRevision, setDetailRevision] = useState(0) const [showWizard, setShowWizard] = useState(false) + const [wizardDrivers, setWizardDrivers] = useState([]) + const loadingWizardDrivers = useRef(false) const [wizardDraft, setWizardDraft] = useState(null) const [pendingCreates, setPendingCreates] = useState([]) const [showSettings, setShowSettings] = useState(false) @@ -488,7 +498,8 @@ export const App: React.FC = () => { const pending = selectedVM ? (state?.pending_changes[vmRefKey(selectedVM)] ?? []) : [] 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 hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime + const nativeHost = isAppleSilicon(state?.host) + const hostReady = !!state && (nativeHost ? !!state.host.apple_virtualization?.ready : state.host.whpx === 'ready' && !!state.active_runtime) const canSuspend = state?.can_suspend ?? false const fullscreenHotkey = state?.config.fullscreen_hotkey_enabled ? resolveFullscreenHotkey(state.config.fullscreen_hotkey) @@ -595,14 +606,14 @@ export const App: React.FC = () => { try { const s = await api.GetState() setState(s) - setSetupStage(s?.active_runtime ? null : 'runtime') + setSetupStage(needsRuntimeSetup(s.host, !!s.active_runtime) ? '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 @@ -787,15 +798,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', @@ -810,13 +812,10 @@ 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 @@ -883,9 +882,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 @@ -894,7 +891,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) => { @@ -936,26 +939,44 @@ export const App: React.FC = () => { }, tr('toastCloned', { name: cloneName })) } - const openWizard = () => { - if (!state?.active_runtime) { + 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) + 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) ? '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' @@ -1109,47 +1130,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 ( + {nativeTitlebar && 0), + selectedVMKey: selectedVM && vmRefKey(selectedVM), + vmSettingsReady: !!detail && detail.name === selectedVM?.name, + }} />}
+ {onCopy && ( +
diff --git a/frontend/src/components/AppDialogs.tsx b/frontend/src/components/AppDialogs.tsx index ac13144..c736f3f 100644 --- a/frontend/src/components/AppDialogs.tsx +++ b/frontend/src/components/AppDialogs.tsx @@ -8,7 +8,7 @@ import { I18nKey, t } from '../i18n' 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, CreateOpts, DriverSummary, Locale, Task, VMDetail, VMListItem, ViewContribution } from '../types' import { Button } from '../ui/controls' import { ConfirmDialog, Modal } from '../ui/dialog' import type { ToastInput } from '../ui/toast' @@ -33,7 +33,9 @@ interface AppDialogsProps { showWizard: boolean wizardDraft: WizardDraft | null + wizardDrivers: DriverSummary[] onCloseWizard: () => void + onDriverCreated: (driverID: string, name: string) => void onSubmitCreate: (payload: CreateOpts, draft: WizardDraft) => void showSettings: boolean @@ -87,7 +89,7 @@ export const AppDialogs: React.FC = (props) => { const { locale, state, detail, selectedVM, selectedIsMacOS, effectiveState, fixedModeSupported, diskCacheSupported, runningVMCount, tasks, displayNames, - showWizard, wizardDraft, onCloseWizard, onSubmitCreate, + showWizard, wizardDraft, wizardDrivers, onCloseWizard, onDriverCreated, onSubmitCreate, showSettings, onCloseSettings, onSavedSettings, affinityTarget, affinityVersion, onOpenAffinity, onCloseAffinity, onAffinityApplied, updateConfirming, updateLatest, onCancelInstallUpdate, onConfirmInstallUpdate, @@ -109,11 +111,14 @@ export const AppDialogs: React.FC = (props) => { diff --git a/frontend/src/components/CreateWizard.tsx b/frontend/src/components/CreateWizard.tsx index 483eb90..bc05f04 100644 --- a/frontend/src/components/CreateWizard.tsx +++ b/frontend/src/components/CreateWizard.tsx @@ -1,5 +1,5 @@ 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 { NpcapDependency } from './NpcapDependency' import { NetworkErrorNotice } from './NetworkErrorNotice' @@ -45,30 +45,33 @@ import { toggleWizardBorderless, } from '../lib/displayResolution' import { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, Task, ValidationIssue, VMNetworkSettings } from '../types' -import { findActiveOfflineTask, taskInstallerPhase } from '../lib/tasks' +import { findActiveInstallerTask, findRunningRestoreTask, taskInstallerPhase, taskStopAction, taskTitle } from '../lib/tasks' +import { isMacOSDriver } 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' 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 tasks?: Task[] draft?: WizardDraft | null + onCancelTask: (id: string) => Promise 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 } @@ -93,7 +96,7 @@ const SOURCES: { mode: 'offline' | 'apple' | 'installer' | 'disk'; icon: LucideI { mode: 'disk', icon: HardDrive, title: 'srcDiskTitle', sub: 'srcDiskSub' }, ] -export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported = false, captureSupported = false, tasks = [], draft, onClose, onSubmit }) => { +export const CreateWizard: React.FC = ({ locale, host, drivers, fixedModeSupported = false, captureSupported = false, tasks = [], draft, onCancelTask, onClose, onDriverCreated, onSubmit }) => { const tr = (k: I18nKey, v?: Record) => 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. @@ -102,25 +105,23 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported const [err, setErr] = useState('') const [issues, setIssues] = useState([]) const [cmdPreview, setCmdPreview] = useState('') - const [drivers, setDrivers] = useState([]) - const [driverID, setDriverID] = useState(BUILTIN_MACOS_DRIVER) + const [driverID, setDriverID] = useState(() => defaultGuestDriver(drivers, host, draft?.restoreImage ? 'ipsw' : draft?.opts ? 'offline' : undefined)?.id ?? '') const [driverOpts, setDriverOpts] = useState>({}) + 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 [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 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(draft?.opts ?? { - name: 'macos-tahoe', + name: draft?.name ?? 'macos-tahoe', dir: '', // 离线安装默认关闭网络,减少恢复环境依赖;用户仍可在第 4 步改为 NAT 或桥接。 source_mode: 'offline', @@ -150,17 +151,17 @@ export const CreateWizard: React.FC = ({ 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) => setOpts((o) => ({ ...o, ...patch })) const networkMode = opts.network_mode ?? (opts.network ? 'nat' : 'off') const [networkAdapters, setNetworkAdapters] = useState(null) const [networkError, setNetworkError] = useState(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) => { @@ -170,7 +171,7 @@ export const CreateWizard: React.FC = ({ 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 @@ -218,7 +219,7 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported const [cached, setCached] = useState([]) 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() @@ -229,9 +230,9 @@ export const CreateWizard: React.FC = ({ 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) @@ -246,7 +247,7 @@ export const CreateWizard: React.FC = ({ 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(() => { @@ -262,7 +263,7 @@ export const CreateWizard: React.FC = ({ 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')) @@ -290,11 +291,11 @@ export const CreateWizard: React.FC = ({ 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 ( - - }
- {err &&
{err}
} + {err &&
{err}
} + {restoreTask && ( +
+ {taskTitle(locale, restoreTask)} + = 0 ? restoreTask.percent : undefined} /> +
+ )}
{step === 1 && ( @@ -324,6 +331,7 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported = ({ locale, host, fixedModeSupported value: d.id, label: locText(d.name, locale, d.id), }))} - onChange={(id) => { setDriverID(id); setErr('') }} + onChange={(id) => { setDriverID(id); setDriverOpts({}); setRestorePath(''); setErr('') }} /> } /> )} - {isCustomDriver ? ( + {!activeDriver ?
{tr('wizardNoDriver')}
: !legacyDriver ? (
+ {restoreField && } set({ name: e.target.value })} />} + disabled={driverCreating} + control={ set({ name: e.target.value })} />} /> {activeDriver.create_schema && ( hasRestoreImagePicker(activeDriver, prop), + pick: (label) => api.PickFile(label, '*.ipsw'), + } : undefined} /> )} @@ -703,7 +730,7 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported {networkAdapters?.length === 0 && {tr('bridgeNoAdapters')}}
} />} {networkMode === 'bridge' && <> - setDependencyRefresh((value) => value + 1)} /> + setDependencyRefresh((value) => value + 1)} /> {networkPlanning &&
{tr('bridgePlanPending')}
} } @@ -779,26 +806,39 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported
- - {isCustomDriver ? ( + {legacyDriver && } + {restoreTask && ( + + )} + {!legacyDriver ? (
- {(state.vms?.length ?? 0) === 0 && host.whpx === 'ready' && !!state.active_runtime && onNewVM && ( + {(state.vms?.length ?? 0) === 0 && hostReady && onNewVM && (

{tr('welcomeTitle')}

{tr('welcomeSub')}

@@ -124,14 +132,14 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onNewVM, o
- - {tr('whpxTitle')} + + {tr(nativeHost ? 'appleVirtualizationTitle' : 'whpxTitle')}
-
{whpx.short}
- {whpx.canEnable ? ( +
{virtualization.short}
+ {virtualization.canEnable ? ( - ) : whpx.hint ? ( -
{whpx.hint}
+ ) : virtualization.hint ? ( +
{virtualization.hint}
) : null}
@@ -149,13 +157,17 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onNewVM, o {tr('hostRAM')}
-
{tr('hostRAMAvail', { n: host.avail_ram_gb.toFixed(1) })}
-
+
+ {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) }) : '—'} +
+ {host.memory_usage_known &&
{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}` : ''}` : ''} -
+
}
@@ -201,7 +213,7 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onNewVM, o ) })()} -
+ {!nativeHost &&
{tr('hostRuntime')}
))}
-
+ } -
+ {!nativeHost &&
{tr('hostGPUs')}
{realGPUs.length === 0 ? ( @@ -296,7 +308,7 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onNewVM, o }) )}
-
+
} {(host.displays?.length ?? 0) > 0 && (
{tr('hostDisplays')}
diff --git a/frontend/src/components/LogPanel.tsx b/frontend/src/components/LogPanel.tsx index f25c456..6257a11 100644 --- a/frontend/src/components/LogPanel.tsx +++ b/frontend/src/components/LogPanel.tsx @@ -111,13 +111,7 @@ export const LogPanel: React.FC = ({ 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 +241,7 @@ export const LogPanel: React.FC = ({ )} - {host.total_ram_gb > 0 && ( + {host.memory_usage_known && host.total_ram_gb > 0 && ( void + onCancelTask: (id: string) => Promise +} + +export function RestoreImageSource({ locale, host, tasks, initialImage, disabled, selectedPath, onPathChange, onCancelTask }: Props) { + const [source, setSource] = useState('apple') + const [localPath, setLocalPath] = useState('') + const [cached, setCached] = useState(() => initialImage ? [initialImage] : []) + const [latest, setLatest] = useState() + 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[1], vars?: Record) => 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, fn: () => Promise) => { + setPending(action) + setActionErr('') + try { + await fn() + } catch (error) { + setActionErr(parseAppError(error).summary) + } finally { + setPending('') + } + } + + return ( + <> +
+ {(['apple', 'local'] as const).map((mode) => { + const apple = mode === 'apple' + const Icon = apple ? CloudDownload : Disc3 + return + })} +
+ {actionErr &&
{actionErr}
} + {local ? + + setLocalPath(e.target.value)} /> + +
+ } /> + : + {choices.length > 0 && ({ value: choice.key, label: choice.label }))} /> + } />} + {active ? + = 0 ? active.percent : undefined} /> + {active.cancelable && } + + } /> : complete ? : currentRelease && } busy={pending === 'download'} disabled={!!pending || lowSpace} onClick={() => doAction('download', async () => { await api.DownloadInstaller(currentRelease.version) })}>{tr(partial ? 'installersResume' : 'installersDownload')} + } />} + {(releaseErr || cacheErr) &&
+ {releaseErr || cacheErr} + +
} + {!releaseErr && latest === undefined && !complete &&

{tr('offlineLoading')}

} + {!releaseErr && latest === null && choices.length === 0 &&

{tr('srcIPSWNone')}

} +
} + + ) +} diff --git a/frontend/src/components/SchemaForm.tsx b/frontend/src/components/SchemaForm.tsx index 6e9c73f..3ed711f 100644 --- a/frontend/src/components/SchemaForm.tsx +++ b/frontend/src/components/SchemaForm.tsx @@ -1,8 +1,10 @@ -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 { Button } from '../ui/controls' import { NumberField, PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../ui/settings' interface Props { @@ -13,6 +15,10 @@ interface Props { groupFilter?: string onChange: (next: Record, patch: Record) => void hideGroupHeader?: boolean + 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 } } const SECRET_MASK = '••••••••' @@ -20,13 +26,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 = ({ - locale, schema, values, scopeFilter, groupFilter, onChange, hideGroupHeader, + locale, schema, values, scopeFilter, groupFilter, onChange, hideGroupHeader, hideFields, 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'] || '' @@ -134,7 +143,7 @@ export const SchemaForm: React.FC = ({ ) } - return ( + const textInput = ( = ({ onChange={(e) => setKey(k, e.target.value)} /> ) + if (!filePicker?.supports(prop)) return textInput + return ( +
+ {textInput} + +
+ ) } const rows = keys.map((k) => { @@ -154,6 +181,8 @@ export const SchemaForm: React.FC = ({ {badge}{desc ? {desc} : null} : undefined} control={renderControl(k, prop)} /> diff --git a/frontend/src/components/TitleMenus.tsx b/frontend/src/components/TitleMenus.tsx index e1c7907..1dee076 100644 --- a/frontend/src/components/TitleMenus.tsx +++ b/frontend/src/components/TitleMenus.tsx @@ -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 & { mac?: boolean; disabled?: boolean }) { + const label = t(locale, sidebarOpen ? 'hideSidebar' : 'showSidebar') + return ( + + + + ) } /** @@ -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 = ({ - 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) => t(locale, k, v) +export const TitleMenus: React.FC = (props) => { + const { locale, vm, themeMode } = props const [menuState, setMenuState] = useState<{ id: MenuId | null; switched: boolean }>({ id: null, switched: false }) const openRef = useRef(null) const navRef = useRef(null) @@ -70,36 +41,55 @@ export const TitleMenus: React.FC = ({ } 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 } = {}) => ( - - {label} - {opts.shortcut && {opts.shortcut}} - - ) - const check = (label: string, checked: boolean, onSelect: () => void, shortcut?: string) => ( - - - {label} - {shortcut && {shortcut}} - - ) + const renderRow = (row: MenuRow, index: number) => { + if (row.kind === 'separator') return + if (row.kind === 'label') return {row.label} + const onSelect = () => runMenuCommand(props, row.command) + const label = {row.label} + const shortcut = row.shortcut && {row.shortcut} + const indicator = + if (row.kind === 'radio') return ( + + {indicator}{label} + + ) + if (row.kind === 'check') return ( + + {indicator}{label}{shortcut} + + ) + return ( + + {label}{shortcut} + + ) + } + + 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)} + { + const row = radioRows.find((entry) => entry.kind === 'radio' && entry.command === value) + if (row?.kind === 'radio') runMenuCommand(props, row.command) + }}> + {radioRows.map(renderRow)} + + {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) => ( = ({ return (
e.stopPropagation()}> - - - -
) diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index e37a515..03ba5d2 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -31,7 +31,7 @@ import { endpointKey, guestFamilyOf, isMacOSDriver as isMacOSDriverID, - splitEndpoints, + primaryVMAccess, vmFeatures, } from '../lib/endpoints' import { useVMStats } from '../lib/vmStats' @@ -163,9 +163,8 @@ export const VMPage: React.FC = ({ 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 +241,23 @@ export const VMPage: React.FC = ({ primary = } 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 = ( - - - - ) - } - } else { + if (promotedEndpoint) { + const action = defaultEndpointAction(promotedEndpoint.kind) + const label = action ? endpointActionLabel(promotedEndpoint.kind, action) : endpointKindLabel(promotedEndpoint.kind) + primary = ( + + + + ) + } else if (access?.kind === 'window') { primary = ( ) } + if (missingRestorePath(r)) return {tr('installersCacheUnavailable')} + if (releaseKind === 'ipsw' && cacheError) return return ( - ) } - const releaseMeta = (r: Release) => ( -
- {r.posted} · {gb(r.size)} - {spaceShort(r) && · {tr('installersNoSpace', { need: Math.ceil(needBytes(r) / 1e9), free: host.free_disk_gb.toFixed(0) })}} + const releaseMeta = (r: Release) => { + const details = [r.posted, r.size > 0 ? gb(r.size) : ''].filter(Boolean).join(' · ') + if (!details) return null + return
+ {details} + {spaceShort(r) && · {tr('installersNoSpace', { need: Math.ceil(remainingGB(r)), free: host.free_disk_gb.toFixed(0) })}}
- ) + } const matchedTaskIDs = new Set() - 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 = ({ 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, } } @@ -302,6 +319,7 @@ export const InstallersPage: React.FC = ({
{row.title}{row.version ? ` ${row.version}` : ''} {!task && c?.kind === 'offline' && !c.partial && {tr('installersKindOffline')}} + {!task && c?.kind === 'ipsw' && !c.partial && IPSW} {(!task && c?.kind === 'online' && !c.partial) || (task && row.kind === 'online') ? {tr('installersKindOnline')} : null} @@ -333,12 +351,12 @@ export const InstallersPage: React.FC = ({ /> ) : c ? ( <> - {!c.partial && (c.kind === 'offline' || c.kind === 'online') && ( - )} - {c.partial && c.kind === 'offline' && c.version && ( + {c.partial && c.version && (c.kind === 'offline' || (c.kind === 'ipsw' && (releases ?? []).some((r) => matchesRelease(c, r)))) && ( )} {confirmDelete === c.name ? ( @@ -362,7 +380,7 @@ export const InstallersPage: React.FC = ({
@@ -383,7 +401,7 @@ export const InstallersPage: React.FC = ({ {latest.title} {latest.version} {groupIndex === 0 && {tr('installersLatest')}} - {downloaded(latest.version) && } + {downloaded(latest) && }
{releaseMeta(latest)}
@@ -402,7 +420,7 @@ export const InstallersPage: React.FC = ({
{r.version} {r.build} - {downloaded(r.version) && {tr('offlineCached')}} + {downloaded(r) && {tr('offlineCached')}}
{releaseMeta(r)} diff --git a/frontend/src/macos/applicationMenuModel.ts b/frontend/src/macos/applicationMenuModel.ts new file mode 100644 index 0000000..7780636 --- /dev/null +++ b/frontend/src/macos/applicationMenuModel.ts @@ -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 + +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() + 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 | undefined { + if (!commands.has(entry.command)) return undefined + if ((entry.command.startsWith('vm:') || entry.command === 'vmSettings') && entry.scope !== scope) return undefined + return entry.command +} diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 9e87479..6ec6278 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -2069,6 +2069,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. */ diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 43d6106..303181d 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -126,7 +126,7 @@ export type CreateOpts = Model & { type TaskStatus = 'running' | 'done' | 'failed' | 'canceled' -export type InstallerKind = 'offline' | 'online' +export type InstallerKind = 'offline' | 'online' | 'ipsw' export type InstallerPhase = 'queued' | 'downloading' /** A tracked long-running job pushed as "reims:task" (internal/app/tasks.go). */ diff --git a/frontend/src/wails.ts b/frontend/src/wails.ts index a4e1ddb..ebd8942 100644 --- a/frontend/src/wails.ts +++ b/frontend/src/wails.ts @@ -198,6 +198,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). diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index e066de7..f9e3c1a 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -294,6 +294,8 @@ export function SuggestLanguagePack():Promise; export function SuspendVM(arg1:string,arg2:string):Promise; +export function SyncApplicationMenu(arg1:string):Promise; + export function TestHostDNS(arg1:guesttools.HostDNSConfig):Promise; export function ToggleVMFullscreen(arg1:string,arg2:string):Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index eeef3a9..681aa2c 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -566,6 +566,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); } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 0186a20..f25b5ae 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -1344,7 +1344,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 +1381,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 +1415,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 +1437,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 +2359,7 @@ export namespace plugin { } export class SettingProperty { type: string; + "x-filePattern"?: string; title: LocalizedText; description?: LocalizedText; default?: any; @@ -2361,6 +2380,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"]; diff --git a/internal/app/app.go b/internal/app/app.go index 57c101c..d907f57 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -122,31 +122,33 @@ type App struct { trayMgr *tray.Manager allowQuit bool launchPrevDataRoot string - quitMode string - vmStarts sync.WaitGroup - lastVMs []driver.VMListItem - lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale - lastVMListErr error - pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick - diskPaths map[string]cachedDiskPath - procSamples map[string]host.ProcessSample - recentLogs []string - needsSetup bool - root dataroot.Status // how the current data folder opened (dataroot_flow.go) - launch cli.WindowArgs // flags this window was started with (window_launch.go) - trayIcon []byte // embedded PNG passed in from package main - logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go) - pluginMgr *plugin.Manager - pluginMarket *market.MarketClient - controlServer *control.Server - driverRouter *driver.Router - vmStateTable *driver.StateTable - lifecycleSvc *vmlifecycle.Service - runtimeKinds *rt.KindRegistry - uiHealth uiHealthState - themeMode string - vmClosePrompts sync.Map - displayHost vmDisplayHost + quitMode string + vmStarts sync.WaitGroup + lastVMs []driver.VMListItem + lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale + lastVMListErr error + pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick + diskPaths map[string]cachedDiskPath + procSamples map[string]host.ProcessSample + recentLogs []string + needsSetup bool + root dataroot.Status // how the current data folder opened (dataroot_flow.go) + launch cli.WindowArgs // flags this window was started with (window_launch.go) + trayIcon []byte // embedded PNG passed in from package main + logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go) + pluginMgr *plugin.Manager + pluginMarket *market.MarketClient + controlServer *control.Server + driverRouter *driver.Router + vmStateTable *driver.StateTable + lifecycleSvc *vmlifecycle.Service + runtimeKinds *rt.KindRegistry + uiHealth uiHealthState + appleVZProbeOnce sync.Once + appleVZProbe host.AppleVirtualizationStatus + themeMode string + vmClosePrompts sync.Map + displayHost vmDisplayHost displayPlacements sync.Map @@ -191,15 +193,15 @@ func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) { needsSetup: needsSetup, launch: launch, launchPrevDataRoot: launchPrevDataRoot, - trayIcon: trayIcon, - transitions: make(map[string]string), - pendingChanges: make(map[string][]PendingChange), - rebootWatchers: make(map[string]rebootWatcherEntry), - pollWake: make(chan struct{}, 1), - diskPaths: make(map[string]cachedDiskPath), - procSamples: make(map[string]host.ProcessSample), - uiHealth: uiHealthState{windowHidden: launch.Background}, - displayHost: vmDisplayHost{displays: host.ConnectedDisplays, move: host.MoveProcessWindowToDisplay}, + trayIcon: trayIcon, + transitions: make(map[string]string), + pendingChanges: make(map[string][]PendingChange), + rebootWatchers: make(map[string]rebootWatcherEntry), + pollWake: make(chan struct{}, 1), + diskPaths: make(map[string]cachedDiskPath), + procSamples: make(map[string]host.ProcessSample), + uiHealth: uiHealthState{windowHidden: launch.Background}, + displayHost: vmDisplayHost{displays: host.ConnectedDisplays, move: host.MoveProcessWindowToDisplay}, } a.hostAPI.app = a a.hostAPI.pluginFiles = make(map[string]pluginFileGrant) @@ -278,8 +280,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 @@ -374,6 +376,7 @@ 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) } diff --git a/internal/app/application_menu.go b/internal/app/application_menu.go new file mode 100644 index 0000000..4d5fc5f --- /dev/null +++ b/internal/app/application_menu.go @@ -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) +} diff --git a/internal/app/application_menu_darwin.go b/internal/app/application_menu_darwin.go new file mode 100644 index 0000000..75dbc97 --- /dev/null +++ b/internal/app/application_menu_darwin.go @@ -0,0 +1,42 @@ +//go:build darwin && cgo + +package app + +/* +#cgo CFLAGS: -x objective-c +#cgo LDFLAGS: -framework AppKit +#include +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)) + } +} diff --git a/internal/app/application_menu_darwin.m b/internal/app/application_menu_darwin.m new file mode 100644 index 0000000..ae1fd79 --- /dev/null +++ b/internal/app/application_menu_darwin.m @@ -0,0 +1,120 @@ +//go:build darwin && cgo + +#import + +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 *managedItems; +static NSArray *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 *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 *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 *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; + } +} diff --git a/internal/app/application_menu_other.go b/internal/app/application_menu_other.go new file mode 100644 index 0000000..21bc5f0 --- /dev/null +++ b/internal/app/application_menu_other.go @@ -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") +} diff --git a/internal/app/application_menu_test.go b/internal/app/application_menu_test.go new file mode 100644 index 0000000..9f142db --- /dev/null +++ b/internal/app/application_menu_test.go @@ -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") + } +} diff --git a/internal/app/endpoints_flow_test.go b/internal/app/endpoints_flow_test.go index 190cdf1..7f4011f 100644 --- a/internal/app/endpoints_flow_test.go +++ b/internal/app/endpoints_flow_test.go @@ -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") diff --git a/internal/app/extras_flow.go b/internal/app/extras_flow.go index 1630a88..bfa6dde 100644 --- a/internal/app/extras_flow.go +++ b/internal/app/extras_flow.go @@ -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()) } diff --git a/internal/app/installer_bindings.go b/internal/app/installer_bindings.go index 73af8ae..c556c10 100644 --- a/internal/app/installer_bindings.go +++ b/internal/app/installer_bindings.go @@ -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 diff --git a/internal/app/installer_coordinator.go b/internal/app/installer_coordinator.go index c476dba..ca172d6 100644 --- a/internal/app/installer_coordinator.go +++ b/internal/app/installer_coordinator.go @@ -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" diff --git a/internal/app/lifecycle_flow_test.go b/internal/app/lifecycle_flow_test.go index 57e33e6..d00d0b4 100644 --- a/internal/app/lifecycle_flow_test.go +++ b/internal/app/lifecycle_flow_test.go @@ -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"}}} diff --git a/internal/app/plugins_flow.go b/internal/app/plugins_flow.go index 6b4ad11..1fca199 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -98,7 +98,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 +170,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()) @@ -765,9 +765,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 +827,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 +901,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 +920,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. diff --git a/internal/app/qqgroup.go b/internal/app/qqgroup.go index 59e71d5..b4bd744 100644 --- a/internal/app/qqgroup.go +++ b/internal/app/qqgroup.go @@ -19,6 +19,7 @@ import ( const ( qqGroupID = "1136042744" qqGroupShortURL = "https://qm.qq.com/q/TBmRJlVbSo" + qqGroupProtocolURL = "tencent://groupwpa/" qqGroupAuthCacheTTL = 10 * time.Minute qqGroupLookupTimeout = 5 * time.Second ) @@ -151,7 +152,15 @@ func buildQQGroupSchemeURL(groupUin, authKey string, now time.Time) string { AuthKey: authKey, Auth: "", }) - return "tencent://groupwpa/?subcmd=all¶m=" + strings.ToUpper(hex.EncodeToString(raw)) + "&jump_from=" + return qqGroupProtocolURL + "?subcmd=all¶m=" + strings.ToUpper(hex.EncodeToString(raw)) + "&jump_from=" +} + +func validateQQGroupProtocolURL(uri string) (string, error) { + uri = strings.TrimSpace(uri) + if !strings.HasPrefix(uri, qqGroupProtocolURL+"?") || strings.ContainsAny(uri, "\x00\r\n") { + return "", errors.New("refusing to open non-QQ-group protocol URL") + } + return uri, nil } func decodeBase64Flexible(s string) ([]byte, bool) { diff --git a/internal/app/qqgroup_darwin.go b/internal/app/qqgroup_darwin.go new file mode 100644 index 0000000..96a36de --- /dev/null +++ b/internal/app/qqgroup_darwin.go @@ -0,0 +1,53 @@ +//go:build darwin && cgo + +package app + +/* +#cgo CFLAGS: -x objective-c +#cgo LDFLAGS: -framework AppKit +#include +#include + +static int reimsHasQQProtocolHandler(const char *uri) { + @autoreleasepool { + NSURL *url = [NSURL URLWithString:[NSString stringWithUTF8String:uri]]; + NSURL *appURL = [[NSWorkspace sharedWorkspace] URLForApplicationToOpenURL:url]; + return appURL && [[[NSBundle bundleWithURL:appURL] bundleIdentifier] isEqualToString:@"com.tencent.qq"]; + } +} + +static int reimsOpenQQProtocol(const char *uri) { + @autoreleasepool { + NSURL *url = [NSURL URLWithString:[NSString stringWithUTF8String:uri]]; + return url && [[NSWorkspace sharedWorkspace] openURL:url]; + } +} +*/ +import "C" + +import ( + "errors" + "unsafe" +) + +func hasQQProtocolHandler() bool { + uri := C.CString(qqGroupProtocolURL) + defer C.free(unsafe.Pointer(uri)) + return C.reimsHasQQProtocolHandler(uri) != 0 +} + +func launchQQProtocol(uri string) error { + clean, err := validateQQGroupProtocolURL(uri) + if err != nil { + return err + } + if !hasQQProtocolHandler() { + return errQQNotInstalled + } + target := C.CString(clean) + defer C.free(unsafe.Pointer(target)) + if C.reimsOpenQQProtocol(target) == 0 { + return errors.New("macOS refused to open the QQ group invite") + } + return nil +} diff --git a/internal/app/qqgroup_darwin_test.go b/internal/app/qqgroup_darwin_test.go new file mode 100644 index 0000000..ecf17fe --- /dev/null +++ b/internal/app/qqgroup_darwin_test.go @@ -0,0 +1,24 @@ +//go:build darwin && cgo + +package app + +import ( + "os" + "testing" +) + +func TestMacQQProtocolHandler(t *testing.T) { + mode := os.Getenv("REIMS_TEST_MAC_QQ") + if mode != "1" && mode != "launch" { + t.Skip("requires QQ registered as the tencent URL handler in a macOS desktop session") + } + a := new(App) + if !a.CanOpenQQGroup() { + t.Fatal("Launch Services did not resolve the QQ group link to the QQ app") + } + if mode == "launch" { + if err := a.OpenQQGroup(); err != nil { + t.Fatal(err) + } + } +} diff --git a/internal/app/qqgroup_other.go b/internal/app/qqgroup_other.go index ebc57e8..b77942b 100644 --- a/internal/app/qqgroup_other.go +++ b/internal/app/qqgroup_other.go @@ -1,4 +1,4 @@ -//go:build !windows +//go:build !windows && (!darwin || !cgo) package app diff --git a/internal/app/qqgroup_test.go b/internal/app/qqgroup_test.go index f64dc25..f029ef5 100644 --- a/internal/app/qqgroup_test.go +++ b/internal/app/qqgroup_test.go @@ -54,6 +54,18 @@ func TestBuildQQGroupSchemeURL(t *testing.T) { } } +func TestValidateQQGroupProtocolURL(t *testing.T) { + invite := buildQQGroupSchemeURL(qqGroupID, "test-key", time.UnixMilli(1)) + if got, err := validateQQGroupProtocolURL(" " + invite + " "); err != nil || got != invite { + t.Fatalf("validate invite = %q, %v", got, err) + } + for _, raw := range []string{qqGroupShortURL, "tencent://message/?uin=123", "tencent://groupwpa/other?param=123", invite + "\x00extra"} { + if _, err := validateQQGroupProtocolURL(raw); err == nil { + t.Errorf("accepted %q", raw) + } + } +} + func TestExtractCommandExecutable(t *testing.T) { cases := []struct { in string diff --git a/internal/app/qqgroup_windows.go b/internal/app/qqgroup_windows.go index 0ae0120..7049dcb 100644 --- a/internal/app/qqgroup_windows.go +++ b/internal/app/qqgroup_windows.go @@ -3,10 +3,8 @@ package app import ( - "errors" "fmt" "os" - "strings" "syscall" "unsafe" @@ -14,8 +12,8 @@ import ( ) var ( - qqShell32 = syscall.NewLazyDLL("shell32.dll") - qqProcShellExecW = qqShell32.NewProc("ShellExecuteW") + qqShell32 = syscall.NewLazyDLL("shell32.dll") + qqProcShellExecW = qqShell32.NewProc("ShellExecuteW") ) func hasQQProtocolHandler() bool { @@ -52,9 +50,9 @@ func hasQQProtocolHandler() bool { } func launchQQProtocol(uri string) error { - trimmed := strings.TrimSpace(uri) - if !strings.HasPrefix(trimmed, "tencent://groupwpa/") { - return errors.New("refusing to open non-QQ-group protocol URL") + trimmed, err := validateQQGroupProtocolURL(uri) + if err != nil { + return err } verb, err := syscall.UTF16PtrFromString("open") if err != nil { diff --git a/internal/app/quit_no_tray_test.go b/internal/app/quit_no_tray_test.go new file mode 100644 index 0000000..41b06b5 --- /dev/null +++ b/internal/app/quit_no_tray_test.go @@ -0,0 +1,21 @@ +//go:build !windows + +package app + +import ( + "context" + "testing" + + "github.com/Nwflower/reims-go/internal/config" +) + +func TestClosingDesktopWithoutSystemTray(t *testing.T) { + a := &App{cfg: config.Default()} + a.startTray() + if a.trayMgr != nil { + t.Fatal("host without a system tray must not register a tray manager") + } + if a.beforeClose(context.Background()) { + t.Fatal("closing the window must not hide it to an unavailable tray") + } +} diff --git a/internal/app/ssh_flow.go b/internal/app/ssh_flow.go index 6002564..1c9b1bb 100644 --- a/internal/app/ssh_flow.go +++ b/internal/app/ssh_flow.go @@ -2,10 +2,14 @@ package app import ( "fmt" + "net" + "net/url" "os" "os/exec" "path/filepath" "regexp" + "runtime" + "strconv" "strings" "github.com/Nwflower/reims-go/internal/driver" @@ -97,8 +101,7 @@ func sshTarget(vm driver.VMInfo) (host string, port int, user string, ok bool) { return "", 0, "", false } -// OpenSSHTerminal launches an interactive Windows Terminal (falling back to -// PowerShell) connected to the VM's forwarded SSH port. +// OpenSSHTerminal opens an interactive SSH session in the host's terminal. func (a *App) OpenSSHTerminal(driverID, name, user string) error { d, err := a.resolveVMInfo(driverID, name) if err != nil { @@ -119,6 +122,17 @@ func (a *App) OpenSSHTerminal(driverID, name, user string) error { if user == "" { user = endpointUser } + if runtime.GOOS == "darwin" { + spec, err := macSSHTerminalLaunch(sshHost, sshPort, user) + if err != nil { + return err + } + if err := exec.Command(spec.exe, spec.args...).Run(); err != nil { + return fmt.Errorf("open SSH terminal: %w", err) + } + a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Opened SSH terminal (%s:%d)", sshHost, sshPort)) + return nil + } target := sshHost if user != "" { target = user + "@" + sshHost @@ -139,6 +153,22 @@ func (a *App) OpenSSHTerminal(driverID, name, user string) error { return nil } +// macSSHTerminalLaunch passes a validated SSH URL to Launch Services, not a shell command. +func macSSHTerminalLaunch(host string, port int, user string) (launchSpec, error) { + ep := driver.VMEndpoint{Kind: driver.EndpointSSH, Host: host, Port: port, User: user} + if err := driver.ValidateEndpoint(ep); err != nil { + return launchSpec{}, err + } + if host == "" { + host = "127.0.0.1" + } + target := url.URL{Scheme: "ssh", Host: net.JoinHostPort(host, strconv.Itoa(port))} + if user != "" { + target.User = url.User(user) + } + return launchSpec{exe: "/usr/bin/open", args: []string{target.String()}}, nil +} + // WriteSSHConfig idempotently writes or updates a Host block for the VM in // ~/.ssh/config and returns the configured Host alias (e.g. "reims-macos-tahoe"). func (a *App) WriteSSHConfig(driverID, name, user string) (string, error) { diff --git a/internal/app/tasks.go b/internal/app/tasks.go index 57aa758..81b6f8e 100644 --- a/internal/app/tasks.go +++ b/internal/app/tasks.go @@ -34,7 +34,7 @@ type Task struct { Kind string `json:"kind"` // installer/recovery/VM/runtime/app tasks or "plugin:" Subject string `json:"subject"` // release ("26.7.3") or VM name VM string `json:"vm,omitempty"` - InstallerKind string `json:"installer_kind,omitempty"` // "offline" | "online" while an installer download is attached + InstallerKind string `json:"installer_kind,omitempty"` // "offline" | "online" | "ipsw" while an installer download is attached InstallerVersion string `json:"installer_version,omitempty"` // release ("26.7.3") or online target ("tahoe" / "latest") InstallerPhase string `json:"installer_phase,omitempty"` // "queued" | "downloading" while active Step string `json:"step"` // upstream wording, e.g. "downloading OpenCore 1.0.8" @@ -280,6 +280,17 @@ func (m *taskManager) hasRunningDownload() bool { return false } +func (m *taskManager) hasRunningRestore() bool { + m.mu.Lock() + defer m.mu.Unlock() + for _, e := range m.tasks { + if e.task.Kind == "vm-restore" && e.task.Status == TaskRunning { + return true + } + } + return false +} + func (m *taskManager) cancelAll() { m.mu.Lock() cancels := make([]context.CancelFunc, 0, len(m.tasks)) diff --git a/internal/app/thumbnail_flow.go b/internal/app/thumbnail_flow.go index fcc5ed2..8122ebf 100644 --- a/internal/app/thumbnail_flow.go +++ b/internal/app/thumbnail_flow.go @@ -101,15 +101,16 @@ func (a *App) GetVMThumbnail(driverID, name string) (VMThumbnail, error) { return readThumb(path, false), nil } -// FocusVMWindow brings a running VM's QEMU display window to the foreground, -// restoring it first if minimized. +// FocusVMWindow brings a running VM's display or primary endpoint to the foreground. func (a *App) FocusVMWindow(driverID, name string) error { info, err := a.resolveVMInfo(driverID, name) if err != nil { return err } if driver.IsHosted(info.Capabilities) { - // A hosted VM has no window of its own: bring up its best endpoint. + if driver.HasCapability(info.Capabilities, driver.CapWindow) { + return a.showHostedVMWindow(info) + } ep, ok := driver.PrimaryHostedEndpoint(info.Endpoints) if !ok { return fmt.Errorf("%s has no ready endpoint to open", name) @@ -137,6 +138,26 @@ func (a *App) FocusVMWindow(driverID, name string) error { return nil } +func (a *App) showHostedVMWindow(info driver.VMInfo) error { + if info.State != "running" { + return fmt.Errorf("VM %s is not running", info.Name) + } + a.mu.Lock() + router := a.driverRouter + a.mu.Unlock() + drv, err := router.DriverByID(info.DriverID) + if err != nil { + return err + } + window, ok := drv.(driver.WindowDriver) + if !ok { + return fmt.Errorf("driver %q does not provide a viewer", info.DriverID) + } + ctx, cancel := context.WithTimeout(a.baseCtx(), 10*time.Second) + defer cancel() + return window.ShowWindow(ctx, info.Name) +} + // ToggleVMFullscreen switches the running VM's display through its owning driver. func (a *App) ToggleVMFullscreen(driverID, name string) (bool, error) { a.mu.Lock() diff --git a/internal/archtest/file_replace_test.go b/internal/archtest/file_replace_test.go index 1772ade..8e5cd35 100644 --- a/internal/archtest/file_replace_test.go +++ b/internal/archtest/file_replace_test.go @@ -13,6 +13,7 @@ var renameOwners = map[string]bool{ "internal/app/ui_health.go": true, // log rotation "internal/atomicfile/atomicfile.go": true, "internal/fetch/fetch.go": true, // download + "internal/fetch/validated.go": true, // validated restore image download "internal/macos/installer/accelerated.go": true, // download "internal/macos/installer/hfs_image.go": true, // disk image "internal/macos/installer/oc_cache.go": true, // download diff --git a/internal/archtest/macos_boundary_test.go b/internal/archtest/macos_boundary_test.go index 12e7c8d..9f1e5d3 100644 --- a/internal/archtest/macos_boundary_test.go +++ b/internal/archtest/macos_boundary_test.go @@ -151,6 +151,14 @@ func TestMacOSDoesNotGainPrivateHostDependencies(t *testing.T) { } for _, dir := range s.imports() { if name, ok := strings.CutPrefix(dir, "internal/"); ok && !isMacOSDir(dir) { + if s.rel == "internal/macos/installer/restore_image.go" && name == "fetch" { + // Native restore transfer shares the client's validated HTTP cache path. + continue + } + if s.dir() == "internal/macos/applevz" && name == "atomicfile" { + // The native backend owns its settings and uses the common safe replacement primitive. + continue + } found[name] = append(found[name], s.rel) } } diff --git a/internal/archtest/sources_test.go b/internal/archtest/sources_test.go index 296cf2b..d20f068 100644 --- a/internal/archtest/sources_test.go +++ b/internal/archtest/sources_test.go @@ -71,7 +71,7 @@ var loadSources = sync.OnceValues(func() ([]source, error) { if err != nil { return err } - f, err := parser.ParseFile(fileSet, p, raw, parser.SkipObjectResolution) + f, err := parser.ParseFile(fileSet, p, raw, parser.SkipObjectResolution|parser.ParseComments) if err != nil { return err } diff --git a/internal/archtest/unused_test.go b/internal/archtest/unused_test.go index 38dd5a0..3e0ab8c 100644 --- a/internal/archtest/unused_test.go +++ b/internal/archtest/unused_test.go @@ -30,6 +30,12 @@ func TestProductCodeHasNoUncalledFunctions(t *testing.T) { self = s.dir() + "." + fn.Name.Name checked := strings.HasPrefix(s.rel, "internal/") && !strings.HasPrefix(s.rel, "internal/testutil/") || strings.HasPrefix(s.rel, "scripts/i18ngen/") entry := fn.Name.Name == "main" || fn.Name.Name == "init" || fn.Name.Name == "_" + if fn.Doc != nil { + for _, comment := range fn.Doc.List { + // cgo callbacks are called from native code, not the Go AST. + entry = entry || comment.Text == "//export "+fn.Name.Name + } + } if checked && !entry && (fn.Recv == nil || !fn.Name.IsExported()) { decls[self] = decl{s, fn} } diff --git a/internal/cli/apple_vz_test.go b/internal/cli/apple_vz_test.go new file mode 100644 index 0000000..66ec20d --- /dev/null +++ b/internal/cli/apple_vz_test.go @@ -0,0 +1,55 @@ +package cli + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver" +) + +func TestAppleNativeCLIUsesItsOwnDriverWithoutWindowsRuntime(t *testing.T) { + root := t.TempDir() + t.Setenv("REIMS_CTL_CONFIG_DIR", "") + cfg := &config.Config{DataRoot: root} + mgr, router, err := openCLIPluginManager(cfg, true) + if err != nil { + t.Fatal(err) + } + defer mgr.Close() + wantApple := runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" + if isAppleCreateDriver(defaultCreateDriver()) != wantApple { + t.Fatalf("unexpected default %q on %s/%s", defaultCreateDriver(), runtime.GOOS, runtime.GOARCH) + } + if !wantApple { + return + } + apple, err := router.DriverByID(defaultCreateDriver()) + if err != nil { + t.Fatal(err) + } + if apple.RuntimeKind() != "external" || !driver.HasCapability(apple.Capabilities(), driver.CapWindow) { + t.Fatalf("unexpected native driver metadata: %v", apple) + } + if _, err := router.DriverByID(driver.BuiltinReimsMacOSDriverID); err == nil { + t.Fatal("the Apple host must not load the Windows runtime driver") + } + registry := filepath.Join(cfg.XDGConfigDir(), "reims-ctl", "vms.toml") + if err := os.MkdirAll(filepath.Dir(registry), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(registry, []byte("[[vm]]\nname = \"legacy\"\ndir = \"/not-used\"\n"), 0o600); err != nil { + t.Fatal(err) + } + vms, err := router.ListAllVMs(t.Context()) + if err != nil || len(vms) != 1 || !vms[0].DriverUnavailable || vms[0].DriverID != driver.BuiltinReimsMacOSDriverID { + t.Fatalf("legacy entries should be listed without loading the Windows runtime: %+v, %v", vms, err) + } + err = vmCreate(t.Context(), cfg, "en-US", []string{"--gpu", "auto", "mac"}, false) + if err == nil || !strings.Contains(err.Error(), "--gpu") { + t.Fatalf("native create silently accepted a Windows graphics option: %v", err) + } +} diff --git a/internal/cli/cli.go b/internal/cli/cli.go index b65e672..7a634c8 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -91,7 +91,7 @@ func run(args []string) (i18n.Locale, error) { switch rest[0] { case "doctor": - return loc, cmdDoctor(cfg, loc, rest[1:]) + return loc, cmdDoctor(cfg, loc, root, rest[1:]) case "runtime": return loc, cmdRuntime(cfg, loc, rest[1:]) case "vm": @@ -114,6 +114,10 @@ func run(args []string) (i18n.Locale, error) { } func printUsage(loc i18n.Locale) { + if isAppleCreateDriver(defaultCreateDriver()) { + printAppleUsage(loc) + return + } fmt.Println(i18n.T(loc, "cli.usage.header")) fmt.Println("\n" + i18n.T(loc, "cli.usage.section_usage")) fmt.Println(i18n.T(loc, "cli.usage.line_gui")) @@ -150,20 +154,27 @@ func printUsage(loc i18n.Locale) { } } -func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error { +func cmdDoctor(cfg *config.Config, loc i18n.Locale, root dataroot.Status, args []string) error { fs := flag.NewFlagSet("doctor", flag.ContinueOnError) asJSON := fs.Bool("json", false, "Output JSON") if err := fs.Parse(args); err != nil { return err } rep := host.Inspect(cfg.DataRoot) + if native, err := nativeVirtualizationStatus(context.Background()); native { + rep.AppleVirtualization = &host.AppleVirtualizationStatus{Ready: err == nil} + if err != nil { + rep.AppleVirtualization.Detail = i18n.FormatCLIError(loc, err) + } + } active, _ := rt.ResolveActive(cfg) if *asJSON { payload := map[string]any{ - "host": rep, - "config": cfg, - "runtime": active, + "host": rep, + "config": cfg, + "runtime": active, + "data_root": root, } return printJSON(payload) } @@ -176,25 +187,60 @@ func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error { fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.ecores"), i18n.T(loc, "doctor.ecores.detail", rep.ECoreCount, rep.ECoreLogicalCPUs)) } if rep.TotalRAMGB > 0 { - fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.ram"), i18n.T(loc, "doctor.ram.detail", rep.TotalRAMGB, rep.AvailRAMGB)) + memory := i18n.M(loc, "doctor.ram.total_only", i18n.Vars{"total": rep.TotalRAMGB}) + if rep.MemoryUsageKnown { + memory = i18n.T(loc, "doctor.ram.detail", rep.TotalRAMGB, rep.AvailRAMGB) + } + fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.ram"), memory) + } + if rep.AppleVirtualization != nil { + printAppleVirtualizationStatus(loc, rep.AppleVirtualization) } if rep.FreeDiskGB > 0 { fmt.Printf("%-36s: %.1f GB (%s)\n", i18n.T(loc, "doctor.disk"), rep.FreeDiskGB, rep.DataRoot) } - - whpxKey := "doctor.whpx.unsupported" - switch rep.WHPX { - case host.WHPXReady: - whpxKey = "doctor.whpx.ok" - case host.WHPXHypervisorOff: - whpxKey = "doctor.whpx.hypervisor_off" - case host.WHPXNoHypervisor: - whpxKey = "doctor.whpx.no_hv" - case host.WHPXMissing: - whpxKey = "doctor.whpx.missing" + if err := dataroot.Error(loc, root); err != nil { + fmt.Fprintln(os.Stderr, i18n.FormatCLIError(loc, err)) } - fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.whpx"), i18n.T(loc, whpxKey)) + if rep.AppleVirtualization == nil { + whpxKey := "doctor.whpx.unsupported" + switch rep.WHPX { + case host.WHPXReady: + whpxKey = "doctor.whpx.ok" + case host.WHPXHypervisorOff: + whpxKey = "doctor.whpx.hypervisor_off" + case host.WHPXNoHypervisor: + whpxKey = "doctor.whpx.no_hv" + case host.WHPXMissing: + whpxKey = "doctor.whpx.missing" + } + fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.whpx"), i18n.T(loc, whpxKey)) + } + + printDoctorVulkan(loc, rep) + if active == nil { + fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.none")) + } else { + fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.active", active.Commit, active.Dir)) + } + if len(rep.DeepBackingChains) > 0 { + fmt.Printf("%s:\n", i18n.T(loc, "doctor.cow_chain")) + for _, c := range rep.DeepBackingChains { + if c.Broken { + fmt.Printf(" ! %s\n", i18n.T(loc, "doctor.cow_chain.broken", c.VMName, c.Depth, c.Path)) + } else { + fmt.Printf(" ! %s\n", i18n.T(loc, "doctor.cow_chain.item", c.VMName, c.Depth, host.BackingChainWarnDepth)) + } + } + } + return nil +} + +func printDoctorVulkan(loc i18n.Locale, rep host.Report) { + if rep.AppleVirtualization != nil && rep.VulkanProbeError == "" && len(rep.GPUs) == 0 { + return // The native host does not use or probe Vulkan. + } if rep.VulkanProbeError != "" { fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.gpu"), i18n.M(loc, "doctor.gpu.probe_failed", i18n.Vars{"detail": rep.VulkanProbeError})) } @@ -237,23 +283,6 @@ func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error { } } } - - if active == nil { - fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.none")) - } else { - fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.active", active.Commit, active.Dir)) - } - if len(rep.DeepBackingChains) > 0 { - fmt.Printf("%s:\n", i18n.T(loc, "doctor.cow_chain")) - for _, c := range rep.DeepBackingChains { - if c.Broken { - fmt.Printf(" ! %s\n", i18n.T(loc, "doctor.cow_chain.broken", c.VMName, c.Depth, c.Path)) - } else { - fmt.Printf(" ! %s\n", i18n.T(loc, "doctor.cow_chain.item", c.VMName, c.Depth, host.BackingChainWarnDepth)) - } - } - } - return nil } func sameGPU(a, b *host.GPUInfo) bool { @@ -409,11 +438,16 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e } return startVM(ctx, cfg, driverID, name, viaWindow) case "stop": - driverID, name, err := parseVMTarget(args) - if err != nil { + fs := flag.NewFlagSet("vm stop", flag.ContinueOnError) + driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") + force := fs.Bool("force", false, "Force power off if the guest cannot shut down normally") + if err := fs.Parse(args[1:]); err != nil { return err } - return stopVM(ctx, cfg, driverID, name) + if fs.NArg() != 1 { + return fmt.Errorf("usage: reims-go vm stop [--driver ] [--force] ") + } + return stopVM(ctx, cfg, *driverID, fs.Arg(0), *force) case "suspend": driverID, name, err := parseVMTarget(args) if err != nil { @@ -497,7 +531,8 @@ func parseVMTarget(args []string) (driverID, name string, err error) { func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) error { fs := flag.NewFlagSet("vm create", flag.ContinueOnError) - driverID := fs.String("driver", driver.BuiltinReimsMacOSDriverID, "Guest VM driver ID (default: builtin.driver.reims-macos)") + driverID := fs.String("driver", defaultCreateDriver(), "Guest VM driver ID") + ipsw := fs.String("ipsw", "", "Local Apple macOS restore image (Apple Virtualization only)") dir := fs.String("dir", "", "Custom VM directory") macos := fs.String("macos", "tahoe", "macOS version (e.g. tahoe)") cpus := fs.Int("cpus", 8, "vCPU count") @@ -518,6 +553,12 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s return fmt.Errorf("usage: reims-go vm create [flags] ") } name := fs.Arg(0) + if *ipsw != "" && !isAppleCreateDriver(*driverID) { + return fmt.Errorf("--ipsw is only supported by the Apple Virtualization driver") + } + if isAppleCreateDriver(*driverID) { + return createAppleVM(ctx, cfg, *driverID, name, *dir, *ipsw, *cpus, *mem, *diskSize, *start, fs) + } // Route non-reims guest drivers through the plugin Driver Router (§5.3, §10). if strings.TrimSpace(*driverID) != "" && *driverID != driver.BuiltinReimsMacOSDriverID { mgr, router, err := openCLIPluginManager(cfg, false) diff --git a/internal/cli/macos_native.go b/internal/cli/macos_native.go index bf22ffd..a03c997 100644 --- a/internal/cli/macos_native.go +++ b/internal/cli/macos_native.go @@ -3,16 +3,21 @@ package cli import ( "context" "errors" + "flag" "fmt" "io" "os" + "os/signal" "path/filepath" "strings" + "time" "github.com/Nwflower/reims-go/internal/config" "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/lifecycle" "github.com/Nwflower/reims-go/internal/macos/guest" "github.com/Nwflower/reims-go/internal/macos/installer" "github.com/Nwflower/reims-go/internal/macos/opencore" @@ -24,6 +29,48 @@ import ( func defaultMacOSGuestLang(loc i18n.Locale) string { return opencore.DefaultGuestLang(loc) } +func defaultCreateDriver() string { + if guest.UsesAppleVirtualization() { + return guest.AppleDriverID() + } + return driver.BuiltinReimsMacOSDriverID +} + +func isAppleCreateDriver(id string) bool { return id == guest.AppleDriverID() } + +func nativeVirtualizationStatus(ctx context.Context) (bool, error) { + if !guest.UsesAppleVirtualization() { + return false, nil + } + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + return true, guest.ProbeAppleVirtualization(ctx) +} + +func printAppleUsage(loc i18n.Locale) { + fmt.Println(i18n.T(loc, "cli.usage.apple.header")) + fmt.Println(i18n.T(loc, "cli.usage.line_cmd")) + fmt.Println() + for _, k := range []string{ + "cli.usage.apple.doctor", "cli.usage.apple.create", "cli.usage.cmd_vm_list", + "cli.usage.apple.start", "cli.usage.apple.stop", "cli.usage.apple.delete", + "cli.usage.cmd_vm_set", "cli.usage.cmd_plugin", "cli.usage.cmd_version", + } { + fmt.Println(i18n.T(loc, k)) + } +} + +func printAppleVirtualizationStatus(loc i18n.Locale, status *host.AppleVirtualizationStatus) { + key := "doctor.apple_virtualization.ready" + if !status.Ready { + key = "doctor.apple_virtualization.unavailable" + } + fmt.Printf("%-36s: %s\n", "Apple Virtualization", i18n.T(loc, key)) + if status.Detail != "" { + fmt.Fprintln(os.Stderr, status.Detail) + } +} + func requireDirectNetwork(vm driver.VMInfo) error { if vm.Ref().DriverID != driver.BuiltinReimsMacOSDriverID { return nil @@ -63,6 +110,47 @@ func requireCLIMacOSEnabled(cfg *config.Config, loc i18n.Locale) error { return nil } +func createAppleVM(ctx context.Context, cfg *config.Config, id, name, dir, ipsw string, cpus int, mem, disk string, start bool, flags *flag.FlagSet) error { + options := map[string]any{"restore_path": ipsw} + var unsupported error + flags.Visit(func(f *flag.Flag) { + switch f.Name { + case "driver", "ipsw", "start": + case "cpus": + options["cpus"] = cpus + case "memory": + options["memory"] = mem + case "disk-size": + options["disk_size"] = disk + default: + unsupported = fmt.Errorf("--%s is not supported by the Apple Virtualization driver", f.Name) + } + }) + if unsupported != nil { + return unsupported + } + if dir != "" { + return errors.New("the Apple Virtualization driver manages its VM directories under the data folder") + } + mgr, router, err := openCLIPluginManager(cfg, false) + if err != nil { + return err + } + defer mgr.Close() + drv, err := router.DriverByID(id) + if err != nil { + return err + } + ctx, cancel := signal.NotifyContext(ctx, os.Interrupt) + defer cancel() + req := driver.CreateRequest{DriverID: drv.ID(), Name: name, Options: options} + if err := drv.Create(ctx, req, os.Stdout, os.Stderr); err != nil || !start { + return err + } + _, err = lifecycle.New(mgr.Registry(), router, nil).Start(ctx, driver.NewVMRef(drv.ID(), name), os.Stdout, os.Stderr) + return err +} + // macOSCreateOptions is the CLI-neutral input to the native macOS create flow. type macOSCreateOptions struct { Name, Dir, MacOS, Memory, DiskSize, Disk, DiskMode, DiskCache, GPU, GuestLang string diff --git a/internal/cli/plugin.go b/internal/cli/plugin.go index c241d85..f683898 100644 --- a/internal/cli/plugin.go +++ b/internal/cli/plugin.go @@ -31,8 +31,8 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, * LocaleFn: func() i18n.Locale { return i18n.EffectiveLocale(cfg.Locale) }, - Logger: logf, - VMInventory: guest.VMInventory(), + Logger: logf, + VMInventories: guest.VMInventories(), Callbacks: builtin.HostCallbacks{ GetConfig: func() config.Config { return *cfg }, PrepareVMNetwork: func(ctx context.Context, name string, _ bool) (func(), error) { @@ -40,7 +40,7 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, * }, Log: logf, }, - RegisterGuest: guest.Register, + RegisterGuest: guest.RegisterForHost, StrictRegister: true, }) if err != nil { diff --git a/internal/cli/plugin_test.go b/internal/cli/plugin_test.go index 1e4407b..c9892e5 100644 --- a/internal/cli/plugin_test.go +++ b/internal/cli/plugin_test.go @@ -21,11 +21,14 @@ func TestMacOSPluginDisableAndVMInventory(t *testing.T) { _, err := run(append(args, command...)) return err } + if isAppleCreateDriver(defaultCreateDriver()) { + t.Skip("this test exercises registration and toggling of the Reims vGPU driver") + } t.Setenv("REIMS_CTL_CONFIG_DIR", filepath.Join(root, "config", "reims-ctl")) if err := runCLI("plugin", "disable", "builtin.guest.macos"); err != nil { t.Fatalf("disable without a runtime or VMs: %v", err) } - for _, cmd := range [][]string{{"vm", "create", "--start", "mac"}, {"vm", "type", "mac", "test"}} { + for _, cmd := range [][]string{{"vm", "create", "--driver", driver.BuiltinReimsMacOSDriverID, "--start", "mac"}, {"vm", "type", "mac", "test"}} { if err := runCLI(cmd...); err == nil || err.Error() != i18n.T(i18n.EnUS, "err.macos.disabled") { t.Fatalf("%v while disabled: %v", cmd, err) } diff --git a/internal/cli/start.go b/internal/cli/start.go index fd05db8..2a14cb0 100644 --- a/internal/cli/start.go +++ b/internal/cli/start.go @@ -103,13 +103,13 @@ func compactVM(ctx context.Context, cfg *config.Config, driverID, name string) ( return svc.CompactDisk(ctx, driver.VMRef{DriverID: driverID, Name: name}, os.Stdout, os.Stderr) } -func stopVM(ctx context.Context, cfg *config.Config, driverID, name string) error { +func stopVM(ctx context.Context, cfg *config.Config, driverID, name string, force bool) error { svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } defer closeService() - return svc.Stop(ctx, driver.VMRef{DriverID: driverID, Name: name}, false, os.Stdout, os.Stderr) + return svc.Stop(ctx, driver.VMRef{DriverID: driverID, Name: name}, force, os.Stdout, os.Stderr) } func startInWindow(ctx context.Context, cfg *config.Config, driverID, name string) error { diff --git a/internal/driver/driver.go b/internal/driver/driver.go index 4418435..b3af391 100644 --- a/internal/driver/driver.go +++ b/internal/driver/driver.go @@ -41,6 +41,7 @@ const ( // CapHosted marks VMs the driver runs itself: the host does not spawn, // watch, pin or window-manage a process for them. CapHosted = "hosted" + CapWindow = "window" // a hosted driver can bring its own viewer forward CapConsole = "console" CapTPM = "tpm" CapRDP = "rdp" @@ -237,6 +238,11 @@ type ActionDriver interface { InvokeAction(ctx context.Context, vmName, action string, params map[string]any) (any, error) } +// WindowDriver lets a hosted driver bring its own guest viewer forward. +type WindowDriver interface { + ShowWindow(context.Context, string) error +} + // LogDriver exposes driver-owned serial and QEMU logs. type LogDriver interface { ReadLogs(context.Context, string, bool) (string, error) diff --git a/internal/fetch/validated.go b/internal/fetch/validated.go new file mode 100644 index 0000000..cb95e1a --- /dev/null +++ b/internal/fetch/validated.go @@ -0,0 +1,264 @@ +package fetch + +import ( + "context" + "errors" + "fmt" + "net/http" + "os" + "strconv" + "strings" + "time" + + "github.com/Nwflower/reims-go/internal/atomicfile" +) + +// InvalidDownloadError marks a validation failure that proves the bytes are bad. +// Other validation failures leave the staged bytes and ETag available for retry. +type InvalidDownloadError struct{ Err error } + +func (e *InvalidDownloadError) Error() string { return e.Err.Error() } +func (e *InvalidDownloadError) Unwrap() error { return e.Err } + +// ResumeValidated downloads directly from the supplied client. A strong ETag +// binds a partial to the same representation; only a complete, consumer-validated +// file is published. The validator checks any consumer-specific integrity data. +func ResumeValidated(ctx context.Context, client *http.Client, url, final, part string, maxBytes int64, + onProgress Progress, validate func(context.Context, string) error) error { + if onProgress == nil { + onProgress = func(int64, int64) {} + } + for _, path := range []string{part, part + ".etag"} { + if _, err := plainDownloadFile(path); err != nil { + return err + } + } + info, err := plainDownloadFile(final) + if err != nil { + return err + } + if info != nil { + if info.Size() <= 0 || info.Size() > maxBytes { + return errors.New("cached download has an invalid size; delete it before retrying") + } + onProgress(info.Size(), info.Size()) + return validate(ctx, final) + } + if err := streamValidated(ctx, client, url, part, maxBytes, onProgress); err != nil { + return err + } + if err := validate(ctx, part); err != nil { + if ctx.Err() != nil { + return ctx.Err() // Keep the partial so validation can be retried. + } + var invalid *InvalidDownloadError + if errors.As(err, &invalid) { + return errors.Join(err, removeDownloadPart(part+".etag"), removeDownloadPart(part)) + } + return err + } + if err := ctx.Err(); err != nil { + return err + } + if err := removeDownloadPart(part + ".etag"); err != nil { + return err + } + return os.Rename(part, final) +} + +func plainDownloadFile(path string) (os.FileInfo, error) { + info, err := os.Lstat(path) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + if !info.Mode().IsRegular() { + return nil, fmt.Errorf("download path is not a regular file: %s", path) + } + return info, nil +} + +func removeDownloadPart(path string) error { + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + return nil +} + +func streamValidated(ctx context.Context, client *http.Client, url, part string, maxBytes int64, progress Progress) error { + info, err := plainDownloadFile(part) + if err != nil { + return err + } + var have int64 + var validator string + if info != nil && info.Size() > 0 && info.Size() <= maxBytes { + if tag, err := plainDownloadFile(part + ".etag"); err != nil { + return err + } else if tag != nil && tag.Size() <= 1024 { + data, err := os.ReadFile(part + ".etag") + if err != nil { + return err + } + if strongETag(string(data)) { + validator, have = string(data), info.Size() + } + } + } + retry, err := transferValidated(ctx, client, url, part, validator, have, maxBytes, progress) + if retry && err == nil { + _, err = transferValidated(ctx, client, url, part, "", 0, maxBytes, progress) + } + return err +} + +func transferValidated(ctx context.Context, client *http.Client, url, part, validator string, have, maxBytes int64, progress Progress) (bool, error) { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + req, err := NewRequest(ctx, url) + if err != nil { + return false, err + } + req.Header.Set("Accept-Encoding", "identity") + if have > 0 { + req.Header.Set("Range", fmt.Sprintf("bytes=%d-", have)) + req.Header.Set("If-Range", validator) + } + resp, err := client.Do(req) + if err != nil { + return false, err + } + if resp.StatusCode == http.StatusRequestedRangeNotSatisfiable && have > 0 { + // A 416 body is not image data; close it before any follow-up request. + resp.Body.Close() + if !confirmedCompleteRange(client, req, resp, validator, have) { + return true, nil + } + if err := checkValidatedSize(part, have); err != nil { + return false, err + } + progress(have, have) + return false, nil + } + defer resp.Body.Close() + tag := singleHeader(resp.Header, "ETag") + contentRange := singleHeader(resp.Header, "Content-Range") + flags, total := os.O_CREATE|os.O_WRONLY, resp.ContentLength + switch resp.StatusCode { + case http.StatusPartialContent: + if have == 0 || tag != validator || !validTailRange(contentRange, have, resp.ContentLength) { + if have > 0 { + return true, nil + } + return false, errors.New("download returned an unsolicited partial response") + } + flags, total = flags|os.O_APPEND, have+resp.ContentLength + case http.StatusOK: + have, flags = 0, flags|os.O_TRUNC + default: + return false, fmt.Errorf("download: HTTP %d", resp.StatusCode) + } + if !identityEncoding(resp) { + return false, errors.New("download returned an unexpected content encoding") + } + if total <= 0 || total > maxBytes { + return false, fmt.Errorf("download has an invalid content length: %d", total) + } + if have == 0 { + if err := resetDownloadValidator(part, tag); err != nil { + return false, err + } + } + if err := copyBody(resp.Body, cancel, part, flags, have, total, total, 45*time.Second, "restore image", progress); err != nil { + return false, err + } + return false, checkValidatedSize(part, total) +} + +func confirmedCompleteRange(client *http.Client, req *http.Request, resp *http.Response, validator string, have int64) bool { + if !completeRange(singleHeader(resp.Header, "Content-Range"), have) { + return false + } + if tags := resp.Header.Values("ETag"); len(tags) != 0 { + return len(tags) == 1 && tags[0] == validator + } + + // Some servers do not send ETag on 416. Confirm the same unencoded + // representation via a bounded conditional HEAD, never from length alone. + ctx, cancel := context.WithTimeout(req.Context(), 5*time.Second) + defer cancel() + head := req.Clone(ctx) + head.Method = http.MethodHead + head.Header.Del("Range") + head.Header.Del("If-Range") + head.Header.Set("If-Match", validator) + meta, err := client.Do(head) + if err != nil { + return false + } + defer meta.Body.Close() + return meta.StatusCode == http.StatusOK && meta.Request != nil && resp.Request != nil && + meta.Request.URL.String() == resp.Request.URL.String() && + singleHeader(meta.Header, "ETag") == validator && meta.ContentLength == have && identityEncoding(meta) +} + +func identityEncoding(resp *http.Response) bool { + encodings := resp.Header.Values("Content-Encoding") + return !resp.Uncompressed && (len(encodings) == 0 || len(encodings) == 1 && strings.EqualFold(encodings[0], "identity")) +} + +func checkValidatedSize(part string, total int64) error { + if info, err := plainDownloadFile(part); err != nil || info == nil || info.Size() != total { + return errors.Join(errors.New("restore image download is incomplete"), err) + } + return nil +} + +func resetDownloadValidator(part, tag string) error { + if err := removeDownloadPart(part + ".etag"); err != nil { + return err + } + if err := removeDownloadPart(part); err != nil { + return err + } + if !strongETag(tag) { + return nil + } + return atomicfile.Write(part+".etag", []byte(tag), 0o600) +} + +func singleHeader(header http.Header, name string) string { + if values := header.Values(name); len(values) == 1 { + return values[0] + } + return "" +} + +func strongETag(tag string) bool { + if len(tag) < 2 || len(tag) > 1024 || tag[0] != '"' || tag[len(tag)-1] != '"' { + return false + } + for i := 1; i < len(tag)-1; i++ { + if b := tag[i]; b <= ' ' || b == '"' || b == '\x7f' { + return false + } + } + return true +} + +func completeRange(header string, have int64) bool { + length, ok := strings.CutPrefix(header, "bytes */") + return ok && strings.TrimLeft(length, "0") == strconv.FormatInt(have, 10) +} + +func validTailRange(header string, have, length int64) bool { + span, totalRaw, ok := strings.Cut(strings.TrimPrefix(header, "bytes "), "/") + firstRaw, lastRaw, found := strings.Cut(span, "-") + first, e1 := strconv.ParseInt(firstRaw, 10, 64) + last, e2 := strconv.ParseInt(lastRaw, 10, 64) + total, e3 := strconv.ParseInt(totalRaw, 10, 64) + return strings.HasPrefix(header, "bytes ") && ok && found && e1 == nil && e2 == nil && e3 == nil && + length > 0 && first == have && last >= first && last < total && total-last == 1 && last-first+1 == length +} diff --git a/internal/fetch/validated_test.go b/internal/fetch/validated_test.go new file mode 100644 index 0000000..fa02bff --- /dev/null +++ b/internal/fetch/validated_test.go @@ -0,0 +1,288 @@ +package fetch + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "testing" +) + +func TestValidatedTransferUsesBoundPartialAndPublishesAfterValidation(t *testing.T) { + const payload = "fake IPSW body used only in a local test" + for _, tc := range []struct{ name, reply string }{{"resume", "matched"}, {"restart when file changes", "changed"}, {"restart on incorrect content range", "wrong-range"}} { + t.Run(tc.name, func(t *testing.T) { + var requests []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + rangeHeader := r.Header.Get("Range") + requests = append(requests, rangeHeader) + w.Header().Set("ETag", `"stable"`) + if rangeHeader != "" { + if rangeHeader != "bytes=5-" || r.Header.Get("If-Range") != `"stable"` { + t.Errorf("unsafe resume request: %s, %s", rangeHeader, r.Header.Get("If-Range")) + } + switch tc.reply { + case "changed": + w.Header().Set("ETag", `"changed"`) + case "wrong-range", "matched": + first := 5 + if tc.reply == "wrong-range" { + first = 4 + } + w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", first, len(payload)-1, len(payload))) + w.WriteHeader(http.StatusPartialContent) + fmt.Fprint(w, payload[first:]) + return + } + } + fmt.Fprint(w, payload) + })) + defer server.Close() + dir := t.TempDir() + final, part := filepath.Join(dir, "restore.ipsw"), filepath.Join(dir, "restore.part.ipsw") + for p, body := range map[string]string{part: payload[:5], part + ".etag": `"stable"`} { + if err := os.WriteFile(p, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + } + validate := func(_ context.Context, name string) error { + if name != part { + t.Errorf("validation path = %s", name) + } + if _, err := os.Stat(final); !os.IsNotExist(err) { + t.Error("download published before validation") + } + body, err := os.ReadFile(name) + if string(body) != payload { + t.Errorf("unexpected body: %q", body) + } + return err + } + if err := ResumeValidated(t.Context(), server.Client(), server.URL, final, part, 1024, nil, validate); err != nil { + t.Fatal(err) + } + if len(requests) != 1 && tc.reply != "wrong-range" || len(requests) != 2 && tc.reply == "wrong-range" { + t.Fatalf("requests: %v", requests) + } + if body, err := os.ReadFile(final); err != nil || string(body) != payload { + t.Fatalf("final = %q, %v", body, err) + } + if _, err := os.Stat(part + ".etag"); !os.IsNotExist(err) { + t.Fatalf("validator remains: %v", err) + } + }) + } +} + +func TestValidatedTransferReusesOnlyBoundComplete416(t *testing.T) { + const payload = "bound fixture" + const replacement = "changed bytes" // Same size, distinct bytes. + exact := fmt.Sprintf("bytes */%d", len(payload)) + for _, tc := range []struct { + name, savedTag string + tags, ranges []string + wantRange, wantFresh bool + }{ + {"complete", `"stable"`, []string{`"stable"`}, []string{exact}, true, false}, + {"changed", `"stable"`, []string{`"changed"`}, []string{exact}, true, true}, + {"weak response ETag", `"stable"`, []string{`W/"stable"`}, []string{exact}, true, true}, + {"ambiguous response ETag", `"stable"`, []string{`"stable"`, `"changed"`}, []string{exact}, true, true}, + {"wrong size", `"stable"`, []string{`"stable"`}, []string{fmt.Sprintf("bytes */%d", len(payload)-1)}, true, true}, + {"missing size", `"stable"`, []string{`"stable"`}, nil, true, true}, + {"malformed size", `"stable"`, []string{`"stable"`}, []string{fmt.Sprintf("bytes */+%d", len(payload))}, true, true}, + {"ambiguous size", `"stable"`, []string{`"stable"`}, []string{exact, "bytes */1"}, true, true}, + {"missing saved ETag", "", []string{`"stable"`}, []string{exact}, false, true}, + {"weak saved ETag", `W/"stable"`, []string{`"stable"`}, []string{exact}, false, true}, + {"malformed saved ETag", `"not valid"`, []string{`"stable"`}, []string{exact}, false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + var requests []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + rangeHeader := r.Header.Get("Range") + requests = append(requests, rangeHeader) + if rangeHeader == "" { + w.Header().Set("ETag", `"changed"`) + fmt.Fprint(w, replacement) + return + } + if r.Header.Get("If-Range") != tc.savedTag || r.Header.Get("Accept-Encoding") != "identity" { + t.Errorf("unexpected resume headers: %v", r.Header) + } + for _, tag := range tc.tags { + w.Header().Add("ETag", tag) + } + for _, value := range tc.ranges { + w.Header().Add("Content-Range", value) + } + w.Header().Set("Content-Encoding", "gzip") // The 416 error body is ignored. + w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) + fmt.Fprint(w, "not image data") + })) + defer server.Close() + dir := t.TempDir() + final, part := filepath.Join(dir, "restore.ipsw"), filepath.Join(dir, "restore.part.ipsw") + if err := os.WriteFile(part, []byte(payload), 0o600); err != nil { + t.Fatal(err) + } + if tc.savedTag != "" { + if err := os.WriteFile(part+".etag", []byte(tc.savedTag), 0o600); err != nil { + t.Fatal(err) + } + } + var wantRequests []string + wantBody := payload + if tc.wantRange { + wantRequests = append(wantRequests, fmt.Sprintf("bytes=%d-", len(payload))) + } + if tc.wantFresh { + wantRequests = append(wantRequests, "") + wantBody = replacement + } + var done, total int64 + err := ResumeValidated(t.Context(), server.Client(), server.URL, final, part, 1024, func(d, n int64) { + done, total = d, n + }, func(_ context.Context, file string) error { + if file != part { + t.Errorf("validation path = %s", file) + } + if _, err := os.Stat(final); !os.IsNotExist(err) { + t.Errorf("download published before validation: %v", err) + } + if body, err := os.ReadFile(file); err != nil || string(body) != wantBody { + t.Errorf("staged body = %q, %v; want %q", body, err, wantBody) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(requests, wantRequests) { + t.Fatalf("requests = %q, want %q", requests, wantRequests) + } + if want := int64(len(wantBody)); done != want || total != want { + t.Fatalf("progress = %d/%d, want %d/%d", done, total, want, want) + } + if body, err := os.ReadFile(final); err != nil || string(body) != wantBody { + t.Fatalf("final = %q, %v; want %q", body, err, wantBody) + } + }) + } +} + +func TestValidatedTransferConfirmsUntaggedComplete416WithHead(t *testing.T) { + const staged = "staged bytes" + const fresh = "fresh bytes" + const tag = `"stable"` + for _, tc := range []struct { + name, headTag, encoding string + headSize, headStatus int + redirect, wantFresh bool + }{ + {"match", tag, "", len(staged), http.StatusOK, false, false}, + {"changed", `"changed"`, "", len(staged), http.StatusOK, false, true}, + {"weak", `W/"stable"`, "", len(staged), http.StatusOK, false, true}, + {"missing", "", "", len(staged), http.StatusOK, false, true}, + {"wrong size", tag, "", len(staged) + 1, http.StatusOK, false, true}, + {"encoded", tag, "gzip", len(staged), http.StatusOK, false, true}, + {"precondition failed", tag, "", len(staged), http.StatusPreconditionFailed, false, true}, + {"different target", tag, "", len(staged), http.StatusOK, true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + var requests []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests = append(requests, r.Method+" "+r.URL.Path+" "+r.Header.Get("Range")) + if r.Method == http.MethodHead { + if r.Header.Get("If-Match") != tag || r.Header.Get("Range") != "" || r.Header.Get("If-Range") != "" || r.Header.Get("Accept-Encoding") != "identity" { + t.Errorf("unexpected confirmation headers: %v", r.Header) + } + if tc.redirect && r.URL.Path == "/" { + http.Redirect(w, r, "/other", http.StatusTemporaryRedirect) + return + } + if tc.headTag != "" { + w.Header().Set("ETag", tc.headTag) + } + if tc.encoding != "" { + w.Header().Set("Content-Encoding", tc.encoding) + } + w.Header().Set("Content-Length", fmt.Sprint(tc.headSize)) + w.WriteHeader(tc.headStatus) + return + } + if r.Header.Get("Range") != "" { + w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", len(staged))) + w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) + return + } + fmt.Fprint(w, fresh) + })) + defer server.Close() + dir := t.TempDir() + final, part := filepath.Join(dir, "restore.ipsw"), filepath.Join(dir, "restore.part.ipsw") + for path, bytes := range map[string]string{part: staged, part + ".etag": tag} { + if err := os.WriteFile(path, []byte(bytes), 0o600); err != nil { + t.Fatal(err) + } + } + wantRequests := []string{fmt.Sprintf("GET / bytes=%d-", len(staged)), "HEAD / "} + if tc.redirect { + wantRequests = append(wantRequests, "HEAD /other ") + } + wantBody := staged + if tc.wantFresh { + wantRequests = append(wantRequests, "GET / ") + wantBody = fresh + } + if err := ResumeValidated(t.Context(), server.Client(), server.URL, final, part, 1024, nil, func(_ context.Context, file string) error { + body, err := os.ReadFile(file) + if err == nil && string(body) != wantBody { + return fmt.Errorf("staged body = %q, want %q", body, wantBody) + } + return err + }); err != nil { + t.Fatal(err) + } + if !slices.Equal(requests, wantRequests) { + t.Fatalf("requests = %q, want %q", requests, wantRequests) + } + }) + } +} + +func TestValidatedTransferKeepsPartialOnPauseButRejectsInvalidImage(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("ETag", `"first"`) + fmt.Fprint(w, "fake body") + })) + defer server.Close() + dir := t.TempDir() + final, part := filepath.Join(dir, "restore.ipsw"), filepath.Join(dir, "restore.part.ipsw") + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + err := ResumeValidated(ctx, server.Client(), server.URL, final, part, 1024, nil, func(ctx context.Context, _ string) error { + cancel() + return ctx.Err() + }) + if !errors.Is(err, context.Canceled) { + t.Fatalf("pause: %v", err) + } + if _, err := os.Stat(part); err != nil { + t.Fatalf("pause did not keep partial: %v", err) + } + badImage := errors.New("not a restore image") + err = ResumeValidated(t.Context(), server.Client(), server.URL, final, part, 1024, nil, func(context.Context, string) error { + return &InvalidDownloadError{Err: badImage} + }) + if !errors.Is(err, badImage) { + t.Fatalf("validate: %v", err) + } + for _, file := range []string{part, part + ".etag", final} { + if _, err := os.Stat(file); !os.IsNotExist(err) { + t.Fatalf("invalid image left %s: %v", file, err) + } + } +} diff --git a/internal/host/host.go b/internal/host/host.go index 4cf511e..8203172 100644 --- a/internal/host/host.go +++ b/internal/host/host.go @@ -61,29 +61,36 @@ type LogicalCPUInfo struct { SMT bool `json:"smt"` } +type AppleVirtualizationStatus struct { + Ready bool `json:"ready"` + Detail string `json:"detail,omitempty"` +} + type Report struct { - DefenderRealtimeActive bool `json:"defender_realtime_active,omitempty"` - OS string `json:"os"` - Arch string `json:"arch"` - Timezone string `json:"timezone,omitempty"` - LogicalCPUs int `json:"logical_cpus"` - PhysicalCores int `json:"physical_cores"` - HasHybridCores bool `json:"has_hybrid_cores"` - PCoreCount int `json:"p_core_count"` - ECoreCount int `json:"e_core_count"` - LPECoreCount int `json:"lpe_core_count,omitempty"` - PCoreMask uint64 `json:"p_core_mask"` - PCoreMaskHex string `json:"p_core_mask_hex"` - PCoreLogicalCPUs []int `json:"p_core_logical_cpus,omitempty"` - ECoreLogicalCPUs []int `json:"e_core_logical_cpus,omitempty"` - NonLPEMask uint64 `json:"non_lpe_mask,omitempty"` - NonLPEMaskHex string `json:"non_lpe_mask_hex,omitempty"` - NonLPELogicalCPUs []int `json:"non_lpe_logical_cpus,omitempty"` - CPUTopology []LogicalCPUInfo `json:"cpu_topology,omitempty"` - TotalRAMGB float64 `json:"total_ram_gb"` - AvailRAMGB float64 `json:"avail_ram_gb"` - MemoryLoadPct int `json:"memory_load_pct"` - MemorySpec *HostMemorySpec `json:"memory_spec,omitempty"` + AppleVirtualization *AppleVirtualizationStatus `json:"apple_virtualization,omitempty"` + DefenderRealtimeActive bool `json:"defender_realtime_active,omitempty"` + OS string `json:"os"` + Arch string `json:"arch"` + Timezone string `json:"timezone,omitempty"` + LogicalCPUs int `json:"logical_cpus"` + PhysicalCores int `json:"physical_cores"` + HasHybridCores bool `json:"has_hybrid_cores"` + PCoreCount int `json:"p_core_count"` + ECoreCount int `json:"e_core_count"` + LPECoreCount int `json:"lpe_core_count,omitempty"` + PCoreMask uint64 `json:"p_core_mask"` + PCoreMaskHex string `json:"p_core_mask_hex"` + PCoreLogicalCPUs []int `json:"p_core_logical_cpus,omitempty"` + ECoreLogicalCPUs []int `json:"e_core_logical_cpus,omitempty"` + NonLPEMask uint64 `json:"non_lpe_mask,omitempty"` + NonLPEMaskHex string `json:"non_lpe_mask_hex,omitempty"` + NonLPELogicalCPUs []int `json:"non_lpe_logical_cpus,omitempty"` + CPUTopology []LogicalCPUInfo `json:"cpu_topology,omitempty"` + TotalRAMGB float64 `json:"total_ram_gb"` + AvailRAMGB float64 `json:"avail_ram_gb"` + MemoryLoadPct int `json:"memory_load_pct"` + MemoryUsageKnown bool `json:"memory_usage_known,omitempty"` + MemorySpec *HostMemorySpec `json:"memory_spec,omitempty"` // QEMU commits all guest RAM at start (CreateFileMapping), so a VM requires // available Windows commit charge rather than physical free RAM alone. Both // values include expandable paging-file headroom (CommitHeadroom). diff --git a/internal/host/host_windows.go b/internal/host/host_windows.go index a7d790b..196780f 100644 --- a/internal/host/host_windows.go +++ b/internal/host/host_windows.go @@ -172,6 +172,7 @@ func Inspect(dataRoot string) Report { if totalGB, availGB, ok := probeMemoryGB(); ok { rep.TotalRAMGB = totalGB rep.AvailRAMGB = availGB + rep.MemoryUsageKnown = true } if ms, ok := memoryStatus(); ok { rep.MemoryLoadPct = int(ms.MemoryLoad) diff --git a/internal/host/memory_darwin.go b/internal/host/memory_darwin.go new file mode 100644 index 0000000..48f2b4c --- /dev/null +++ b/internal/host/memory_darwin.go @@ -0,0 +1,22 @@ +package host + +import "math/bits" + +// Non-cache usage is anonymous memory less purgeable pages, plus wired +// memory and the physical pages occupied by the compressor. File-backed +// cache is not counted as used here; this is an estimate, not memory pressure. +func darwinMemoryBytes(total, pageSize, anonymous, purgeable, wired, compressed uint64) (uint64, bool) { + if total == 0 || pageSize == 0 { + return 0, false + } + anonymous -= min(anonymous, purgeable) + pages, carry := bits.Add64(anonymous, wired, 0) + if carry != 0 { + return 0, false + } + pages, carry = bits.Add64(pages, compressed, 0) + if carry != 0 || pages > total/pageSize { + return 0, false + } + return pages * pageSize, true +} diff --git a/internal/host/memory_darwin_cgo.go b/internal/host/memory_darwin_cgo.go new file mode 100644 index 0000000..93547ad --- /dev/null +++ b/internal/host/memory_darwin_cgo.go @@ -0,0 +1,27 @@ +//go:build darwin && cgo + +package host + +/* +#include +#include +#include + +static int reims_memory_stats(vm_statistics64_data_t *stats) { + mach_port_t host = mach_host_self(); + mach_msg_type_number_t count = HOST_VM_INFO64_COUNT; + kern_return_t result = host_statistics64(host, HOST_VM_INFO64, (host_info64_t)stats, &count); + mach_port_deallocate(mach_task_self(), host); + return result == KERN_SUCCESS && count >= HOST_VM_INFO64_REV1_COUNT; +} +*/ +import "C" + +func darwinUsedMemory(total uint64) (uint64, bool) { + var stats C.vm_statistics64_data_t + if C.reims_memory_stats(&stats) == 0 { + return 0, false + } + return darwinMemoryBytes(total, uint64(C.getpagesize()), uint64(stats.internal_page_count), + uint64(stats.purgeable_count), uint64(stats.wire_count), uint64(stats.compressor_page_count)) +} diff --git a/internal/host/memory_darwin_nocgo.go b/internal/host/memory_darwin_nocgo.go new file mode 100644 index 0000000..00ba306 --- /dev/null +++ b/internal/host/memory_darwin_nocgo.go @@ -0,0 +1,5 @@ +//go:build darwin && !cgo + +package host + +func darwinUsedMemory(_ uint64) (uint64, bool) { return 0, false } diff --git a/internal/host/memory_darwin_test.go b/internal/host/memory_darwin_test.go new file mode 100644 index 0000000..e593cbe --- /dev/null +++ b/internal/host/memory_darwin_test.go @@ -0,0 +1,28 @@ +package host + +import ( + "math" + "testing" +) + +func TestDarwinMemoryUsageExcludesReclaimablePages(t *testing.T) { + const page = 16384 + for _, tc := range []struct { + name string + total, anon, purge, wired, compressed uint64 + want uint64 + ok bool + }{ + {"cache is excluded", 100 * page, 40, 5, 15, 10, 60 * page, true}, + {"purgeable cannot underflow", 100 * page, 10, 15, 3, 2, 5 * page, true}, + {"usage exceeds physical RAM", 100 * page, 80, 0, 40, 0, 0, false}, + {"counter overflow", 100 * page, math.MaxUint64, 0, 2, 0, 0, false}, + } { + t.Run(tc.name, func(t *testing.T) { + got, ok := darwinMemoryBytes(tc.total, page, tc.anon, tc.purge, tc.wired, tc.compressed) + if got != tc.want || ok != tc.ok { + t.Fatalf("usage = (%d, %v), want (%d, %v)", got, ok, tc.want, tc.ok) + } + }) + } +} diff --git a/internal/host/resources_darwin.go b/internal/host/resources_darwin.go new file mode 100644 index 0000000..f583db0 --- /dev/null +++ b/internal/host/resources_darwin.go @@ -0,0 +1,35 @@ +package host + +import ( + "math" + "path/filepath" + + "golang.org/x/sys/unix" +) + +func inspectPlatformResources(report *Report) { + if cores, err := unix.SysctlUint32("hw.physicalcpu"); err == nil { + report.PhysicalCores = int(cores) + } + if memory, err := unix.SysctlUint64("hw.memsize"); err == nil && memory > 0 { + const gib = 1 << 30 + report.TotalRAMGB = float64(memory) / gib + if used, ok := darwinUsedMemory(memory); ok { + report.AvailRAMGB = float64(memory-used) / gib + report.MemoryLoadPct = int(math.Round(float64(used) / float64(memory) * 100)) + report.MemoryUsageKnown = true + } + } + report.FreeDiskGB = darwinDataFreeGB(report.DataRoot, FreeGB) +} + +func darwinDataFreeGB(path string, probe func(string) (float64, bool)) float64 { + for dir := filepath.Clean(path); ; dir = filepath.Dir(dir) { + if free, ok := probe(dir); ok { + return free + } + if filepath.Dir(dir) == dir { + return 0 + } + } +} diff --git a/internal/host/resources_darwin_test.go b/internal/host/resources_darwin_test.go new file mode 100644 index 0000000..5de4bf8 --- /dev/null +++ b/internal/host/resources_darwin_test.go @@ -0,0 +1,30 @@ +package host + +import ( + "reflect" + "testing" +) + +func TestDarwinDataFreeGBFallsBackToNearestProbeableParent(t *testing.T) { + var paths []string + got := darwinDataFreeGB("/data/private/vms", func(path string) (float64, bool) { + paths = append(paths, path) + return 20, path == "/data" + }) + if want := []string{"/data/private/vms", "/data/private", "/data"}; got != 20 || !reflect.DeepEqual(paths, want) { + t.Fatalf("got %g GiB and probed %v; want 20 GiB and %v", got, paths, want) + } +} + +func TestDarwinDataFreeGBStopsOnKnownZeroOrRoot(t *testing.T) { + for _, path := range []string{"/full", "/"} { + count := 0 + got := darwinDataFreeGB(path, func(string) (float64, bool) { + count++ + return 0, path == "/full" + }) + if got != 0 || count != 1 { + t.Fatalf("%s: got %g GiB and %d probes; want 0 GiB and one probe", path, got, count) + } + } +} diff --git a/internal/host/resources_other.go b/internal/host/resources_other.go new file mode 100644 index 0000000..e5686a3 --- /dev/null +++ b/internal/host/resources_other.go @@ -0,0 +1,5 @@ +//go:build !windows && !darwin + +package host + +func inspectPlatformResources(_ *Report) {} diff --git a/internal/host/stubs_hardware_other.go b/internal/host/stubs_hardware_other.go index 4c6d0f8..6114120 100644 --- a/internal/host/stubs_hardware_other.go +++ b/internal/host/stubs_hardware_other.go @@ -17,7 +17,7 @@ func Inspect(dataRoot string) Report { displays := probeDisplays() primary := PrimaryDisplayOf(displays) presets, rec := RecommendDisplayPresets(primary) - return Report{ + report := Report{ OS: runtime.GOOS, Arch: runtime.GOARCH, LogicalCPUs: runtime.NumCPU(), @@ -33,6 +33,8 @@ func Inspect(dataRoot string) Report { ProcessorScheduling: probeProcessorScheduling(), Audio: ProbeAudio(), } + inspectPlatformResources(&report) + return report } func ConfigureVulkanDrivers() {} diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 92a092f..2f53337 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -36,6 +36,12 @@ var catalog = map[Locale]map[string]string{ "cli.start.running_in_tray": "{name} 已在启动中(Reims-Go 在托盘运行)。", "cli.start.spawning_tray": "在后台拉起 Reims-Go(托盘)来启动 {name}…", "cli.start.timeout": "Reims-Go 在 {timeout} 内没有回报 {name} 的启动结果;请看界面的日志面板(若正在运行的是旧版 Reims-Go,请先退出它)", + "cli.usage.apple.create": " vm create --ipsw 从本地 Apple 恢复镜像创建虚拟机", + "cli.usage.apple.delete": " vm delete [--keep-files] 删除已关机的虚拟机", + "cli.usage.apple.doctor": " doctor 检查 Apple 虚拟化环境", + "cli.usage.apple.header": "reims-go - Apple 芯片 Mac 实验性虚拟机管理器", + "cli.usage.apple.start": " vm start 启动虚拟机并打开窗口", + "cli.usage.apple.stop": " vm stop [--force] 关闭虚拟机", "cli.usage.cmd_doctor": " doctor 宿主机环境体检(WHPX / 显卡 ICD / P-E 核 / 磁盘 / 运行时)", "cli.usage.cmd_inst_cached": " installer cached 查看已下载的安装包及占用空间", "cli.usage.cmd_inst_del": " installer delete <文件名> 删除已下载的安装包(正在使用或下载中的会被拒绝)", @@ -68,7 +74,7 @@ var catalog = map[Locale]map[string]string{ "cli.usage.section_usage": "用法:", "close": "关闭", "closeDownloadsConfirm": "退出", - "closeDownloadsDesc": "仍有下载正在进行,退出会中断它们。", + "closeDownloadsDesc": "退出会中断正在进行的下载或 macOS 安装。", "closeDownloadsTitle": "退出 Reims-Go?", "closeWindow": "关闭", "collapseLogs": "收起日志", @@ -88,6 +94,8 @@ var catalog = map[Locale]map[string]string{ "delete": "删除…", "deleteEllipsis": "删除…", "displays": "显示器数量", + "doctor.apple_virtualization.ready": "可用", + "doctor.apple_virtualization.unavailable": "不可用", "doctor.cow_chain": "CoW 磁盘派生链体检", "doctor.cow_chain.broken": "虚拟机 {vm} 的系统盘 CoW 链存在缺失父镜像(深度 {depth} 层,{path})", "doctor.cow_chain.item": "虚拟机 {vm} 的系统盘 CoW 链深度为 {depth} 层(≥ {warn}),未分配簇读穿透会拖慢小文件 I/O,建议合并或基于基础镜像重新派生", @@ -113,6 +121,7 @@ var catalog = map[Locale]map[string]string{ "doctor.pcores.detail": "{count} 核,掩码 {mask}(CPU {cpus})", "doctor.ram": "宿主机内存", "doctor.ram.detail": "共 {total, number, .1} GB / 可用 {avail, number, .1} GB", + "doctor.ram.total_only": "共 {total, number, .1} GB(可用内存未知)", "doctor.runtime": "便携运行时", "doctor.runtime.active": "当前激活:{commit}({dir})", "doctor.runtime.none": "尚未安装(运行 reims-go runtime install <压缩包> 导入)", @@ -193,6 +202,8 @@ var catalog = map[Locale]map[string]string{ "err.qemu_aslr.image_policy": "Windows 已按程序名为 qemu-system-x86_64.exe 配置防护,已跳过此运行时的 ASLR 规则。可在 Windows 安全中心的「漏洞保护 → 程序设置」中管理 QEMU 的 ASLR", "err.quit.stop_failed": "无法关闭虚拟机「{name}」,已取消退出。", "err.quit.timeout": "虚拟机「{name}」关机超时,已取消退出。", + "err.restore_catalog_unavailable": "暂时无法读取 Apple 的恢复镜像目录,可重试或选择本地 IPSW。", + "err.restore_catalog_unsupported": "当前 Nivfold 版本不支持查询恢复镜像,可更新 Nivfold 或选择本地 IPSW。", "err.runtime_changed": "操作期间运行时已切换,请重试以使用当前选定的版本。", "err.runtime_not_installed": "未找到已激活的便携运行时,请先执行 `reims-go runtime install <归档路径>`", "err.snapshot.name_empty": "请输入恢复点名称", @@ -402,6 +413,24 @@ var catalog = map[Locale]map[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": "最小化", @@ -586,6 +615,7 @@ var catalog = map[Locale]map[string]string{ "taskDownload": "下载 macOS {v}", "taskPluginDownload": "下载 {name}", "taskRecoveryDownload": "正在为 {name} 拉取并挂载在线恢复镜像", + "taskRestoreVM": "在 {name} 上安装 macOS", "taskRuntime": "安装运行时 {v}", "tasksRunning": "{n, plural, other {# 个任务进行中}}", "themeDark": "深色", @@ -712,6 +742,8 @@ var catalog = map[Locale]map[string]string{ "window.close.description_no_suspend": "当前运行时不支持挂起。关机将请求系统关闭。", "window.close.suspend": "挂起", "window.close.title": "关闭「{name}」?", + "wizardDriverListFailed": "无法加载客体驱动", + "wizardNoDriver": "没有可用的客体驱动", }, EnUS: { "affinity.applied.all": "[CPU] Set QEMU (PID {pid}) affinity to all CPUs ({count} logical CPUs, mask {mask}{eco})", @@ -746,6 +778,12 @@ var catalog = map[Locale]map[string]string{ "cli.start.running_in_tray": "{name} is starting (Reims-Go is running in the tray).", "cli.start.spawning_tray": "Starting Reims-Go in the tray to run {name}...", "cli.start.timeout": "Reims-Go did not report starting {name} within {timeout}; check its log panel (quit it first if it is an older version)", + "cli.usage.apple.create": " vm create --ipsw Create from a local Apple restore image", + "cli.usage.apple.delete": " vm delete [--keep-files] Remove a stopped VM", + "cli.usage.apple.doctor": " doctor Check Apple Virtualization support", + "cli.usage.apple.header": "reims-go - Experimental Apple silicon VM manager", + "cli.usage.apple.start": " vm start Start a VM and open its viewer", + "cli.usage.apple.stop": " vm stop [--force] Shut down a VM", "cli.usage.cmd_doctor": " doctor Inspect host (WHPX / Vulkan GPUs / P-E cores / disk / runtime)", "cli.usage.cmd_inst_cached": " installer cached List downloaded installers and the space they take", "cli.usage.cmd_inst_del": " installer delete Delete a downloaded installer (refused if in use or downloading)", @@ -778,7 +816,7 @@ var catalog = map[Locale]map[string]string{ "cli.usage.section_usage": "Usage:", "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", @@ -798,6 +836,8 @@ var catalog = map[Locale]map[string]string{ "delete": "Delete…", "deleteEllipsis": "Delete…", "displays": "Displays", + "doctor.apple_virtualization.ready": "Ready", + "doctor.apple_virtualization.unavailable": "Unavailable", "doctor.cow_chain": "CoW Disk Backing Chain Check", "doctor.cow_chain.broken": "VM {vm} system disk CoW backing chain has a missing parent image (depth {depth}, {path})", "doctor.cow_chain.item": "VM {vm} system disk has a {depth}-layer CoW backing chain (>= {warn}); read-through slows small-file I/O — consider flattening or re-deriving from the base image", @@ -823,6 +863,7 @@ var catalog = map[Locale]map[string]string{ "doctor.pcores.detail": "{count, plural, one {# core} other {# cores}}, mask {mask} (CPUs {cpus})", "doctor.ram": "Host Memory", "doctor.ram.detail": "{total, number, .1} GB total / {avail, number, .1} GB avail", + "doctor.ram.total_only": "{total, number, .1} GB total (available memory unknown)", "doctor.runtime": "Portable Runtime", "doctor.runtime.active": "Active: {commit} ({dir})", "doctor.runtime.none": "Not installed (run `reims-go runtime install `)", @@ -903,6 +944,8 @@ var catalog = map[Locale]map[string]string{ "err.qemu_aslr.image_policy": "Windows already has a program-wide rule for qemu-system-x86_64.exe, so this runtime’s ASLR rule was skipped. Manage QEMU’s ASLR in Windows Security under Exploit protection → Program settings.", "err.quit.stop_failed": "Could not shut down “{name}”. Quit canceled.", "err.quit.timeout": "Shutdown timed out for “{name}”. Quit canceled.", + "err.restore_catalog_unavailable": "Apple’s restore image catalog is unavailable. Retry or choose a local IPSW.", + "err.restore_catalog_unsupported": "This Nivfold version cannot query restore images. Update Nivfold or choose a local IPSW.", "err.runtime_changed": "The selected runtime changed during this operation. Retry to use the current selection.", "err.runtime_not_installed": "no active portable runtime found; run `reims-go runtime install ` first", "err.snapshot.name_empty": "Enter a restore point name", @@ -1112,6 +1155,24 @@ var catalog = map[Locale]map[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", @@ -1296,6 +1357,7 @@ var catalog = map[Locale]map[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", @@ -1422,6 +1484,8 @@ var catalog = map[Locale]map[string]string{ "window.close.description_no_suspend": "The current runtime does not support suspend. Shut down asks macOS to shut down.", "window.close.suspend": "Suspend", "window.close.title": "Close “{name}”?", + "wizardDriverListFailed": "Could not load guest drivers", + "wizardNoDriver": "No eligible guest driver is available", }, } @@ -1459,6 +1523,7 @@ var paramOrder = map[string][]string{ "doctor.gpu.warn.amd_rdna2": {"ref"}, "doctor.pcores.detail": {"count", "mask", "cpus"}, "doctor.ram.detail": {"total", "avail"}, + "doctor.ram.total_only": {"total"}, "doctor.runtime.active": {"commit", "dir"}, "elevateActionFallbackTitle": {"action"}, "elevateSource": {"name"}, @@ -1576,6 +1641,7 @@ var paramOrder = map[string][]string{ "taskDownload": {"v"}, "taskPluginDownload": {"name"}, "taskRecoveryDownload": {"name"}, + "taskRestoreVM": {"name"}, "taskRuntime": {"v"}, "tasksRunning": {"n"}, "toastAffinityApplied": {"count", "mask"}, diff --git a/internal/macos/applevz/config.go b/internal/macos/applevz/config.go new file mode 100644 index 0000000..b1138f2 --- /dev/null +++ b/internal/macos/applevz/config.go @@ -0,0 +1,216 @@ +package applevz + +import ( + "context" + "encoding/json" + "fmt" + "maps" + "os" + "path/filepath" + "regexp" + "slices" + "strconv" + "strings" + + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/plugin" +) + +const ( + minCPUs = 2 + maxCPUs = 64 + minMemoryMiB = 4096 + maxMemoryMiB = 1024 * 1024 + minDiskGiB = 64 + maxDiskGiB = 16 * 1024 +) + +var vmNamePattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,62}$`) + +func validName(name string) bool { return vmNamePattern.MatchString(name) } + +// vmConfig is the on-disk contract with the native runner. The restore path is +// passed to the installer only and is not saved once provisioning begins. +type vmConfig struct { + Name string `json:"name"` + CPUs int `json:"cpu_count"` + MemoryMiB int `json:"memory_mib"` + DiskGiB int `json:"disk_gib"` +} + +func defaultConfig(name string) vmConfig { + return vmConfig{Name: name, CPUs: 4, MemoryMiB: 8192, DiskGiB: 64} +} + +func (*Driver) CreateSchema() *plugin.SettingsSchema { + defaults := defaultConfig("") + return &plugin.SettingsSchema{ + Order: []string{"restore_path", "cpus", "memory", "disk_size"}, + Properties: map[string]plugin.SettingProperty{ + "restore_path": { + Type: "string", Title: plugin.LocalizedText{ZhCN: "macOS 恢复映像", EnUS: "macOS restore image"}, + Description: plugin.LocalizedText{ZhCN: "选择本机上的 .ipsw 文件", EnUS: "Choose a local .ipsw file"}, + Required: true, FilePattern: "*.ipsw", + }, + "cpus": cpuProperty(defaults.CPUs), + "memory": memoryProperty(formatMemory(defaults.MemoryMiB)), + "disk_size": { + Type: "string", Title: plugin.LocalizedText{ZhCN: "磁盘容量", EnUS: "Disk size"}, + Description: plugin.LocalizedText{ZhCN: "至少 64 GiB,例如 128G", EnUS: "At least 64 GiB, for example 128G"}, + Default: fmt.Sprintf("%dG", defaults.DiskGiB), + }, + }, + } +} + +func (*Driver) SettingsSchema() *plugin.SettingsSchema { + return &plugin.SettingsSchema{ + Scope: "vm", Order: []string{"cpus", "memory"}, + Properties: map[string]plugin.SettingProperty{ + "cpus": cpuProperty(nil), "memory": memoryProperty(nil), + }, + } +} + +func cpuProperty(value any) plugin.SettingProperty { + lo, hi := float64(minCPUs), float64(maxCPUs) + return plugin.SettingProperty{ + Type: "integer", Title: plugin.LocalizedText{ZhCN: "虚拟处理器", EnUS: "Virtual CPUs"}, + Default: value, Minimum: &lo, Maximum: &hi, Effect: "next_start", + } +} + +func memoryProperty(value any) plugin.SettingProperty { + return plugin.SettingProperty{ + Type: "string", Title: plugin.LocalizedText{ZhCN: "内存", EnUS: "Memory"}, + Description: plugin.LocalizedText{ZhCN: "使用 G 或 M,例如 8G 或 8192M", EnUS: "Use G or M, for example 8G or 8192M"}, + Default: value, Effect: "next_start", + } +} + +func (d *Driver) ValidateCreate(ctx context.Context, req driver.CreateRequest) []driver.ValidationIssue { + _, _, issues := d.createConfig(ctx, req) + return issues +} + +func (d *Driver) createConfig(ctx context.Context, req driver.CreateRequest) (vmConfig, string, []driver.ValidationIssue) { + cfg := defaultConfig(req.Name) + if err := ctx.Err(); err != nil { + return cfg, "", []driver.ValidationIssue{issue("", err)} + } + var issues []driver.ValidationIssue + if req.DriverID != "" && req.DriverID != ID { + issues = append(issues, issue("driver_id", fmt.Errorf("incorrect driver %q", req.DriverID))) + } + if !validName(cfg.Name) { + issues = append(issues, issue("name", fmt.Errorf("the VM name must contain 1–63 letters, digits, dots, underscores or hyphens and start with a letter or digit"))) + } + if req.Dir != "" { + issues = append(issues, issue("dir", fmt.Errorf("Apple virtual machines must be created in the driver data folder"))) + } + issues = append(issues, cfg.apply(req.Options, true)...) + restore, err := restorePath(req.Options["restore_path"]) + if err != nil { + issues = append(issues, issue("restore_path", err)) + } + return cfg, restore, issues +} + +func (cfg *vmConfig) apply(changes map[string]any, creating bool) []driver.ValidationIssue { + var issues []driver.ValidationIssue + for _, field := range slices.Sorted(maps.Keys(changes)) { + value := changes[field] + var err error + switch field { + case "cpus": + cfg.CPUs, err = parseQuantity(value, "", minCPUs, maxCPUs) + case "memory": + cfg.MemoryMiB, err = parseQuantity(value, "MiB", minMemoryMiB, maxMemoryMiB) + case "disk_size": + if creating { + cfg.DiskGiB, err = parseQuantity(value, "GiB", minDiskGiB, maxDiskGiB) + } else { + err = fmt.Errorf("disk size cannot be changed after installation") + } + case "restore_path": + if !creating { + err = fmt.Errorf("restore image cannot be changed after installation") + } + default: + err = fmt.Errorf("setting %q is not supported by the Apple virtualization driver", field) + } + if err != nil { + issues = append(issues, issue(field, err)) + } + } + return issues +} + +func parseQuantity(value any, unit string, minimum, maximum int) (int, error) { + factor := 1 + var n int64 + var err error + switch typed := value.(type) { + case int: + n = int64(typed) + case float64: + if typed >= 0 && typed <= float64(maximum) && typed == float64(int64(typed)) { + n = int64(typed) + } + case json.Number: + n, err = typed.Int64() + case string: + text := strings.ToUpper(strings.TrimSpace(typed)) + if unit == "MiB" { + switch { + case strings.HasSuffix(text, "GIB"): + text, factor = strings.TrimSuffix(text, "GIB"), 1024 + case strings.HasSuffix(text, "G"): + text, factor = strings.TrimSuffix(text, "G"), 1024 + default: + text = strings.TrimSuffix(strings.TrimSuffix(text, "MIB"), "M") + } + } else if unit == "GiB" { + text = strings.TrimSuffix(strings.TrimSuffix(text, "GIB"), "G") + } + n, err = strconv.ParseInt(strings.TrimSpace(text), 10, 64) + } + if err != nil || n < 1 || n > int64(maximum/factor) || n*int64(factor) < int64(minimum) { + message := fmt.Sprintf("enter a whole number from %d to %d", minimum, maximum) + if unit != "" { + message += " " + unit + } + return 0, fmt.Errorf("%s", message) + } + return int(n) * factor, nil +} + +func restorePath(value any) (string, error) { + path, _ := value.(string) + if !filepath.IsAbs(path) || !strings.EqualFold(filepath.Ext(path), ".ipsw") { + return "", fmt.Errorf("choose a local .ipsw file using its absolute path") + } + path, err := filepath.EvalSymlinks(path) + if err != nil { + return "", fmt.Errorf("open macOS restore image: %w", err) + } + info, err := os.Stat(path) + if err != nil { + return "", fmt.Errorf("open macOS restore image: %w", err) + } + if !info.Mode().IsRegular() || info.Size() == 0 { + return "", fmt.Errorf("the macOS restore image must be a non-empty regular file") + } + return path, nil +} + +func formatMemory(mib int) string { + if mib%1024 == 0 { + return fmt.Sprintf("%dG", mib/1024) + } + return fmt.Sprintf("%dM", mib) +} + +func issue(field string, err error) driver.ValidationIssue { + return driver.ValidationIssue{Field: field, Message: err.Error()} +} diff --git a/internal/macos/applevz/driver.go b/internal/macos/applevz/driver.go new file mode 100644 index 0000000..ab6b938 --- /dev/null +++ b/internal/macos/applevz/driver.go @@ -0,0 +1,147 @@ +// Package applevz adapts the native Apple virtualization runner as a hosted driver. +package applevz + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "path/filepath" + + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/plugin" +) + +const ( + ID = "builtin.driver.apple-vz" + VMRoot = "apple-vz" +) + +// Options selects the current application data root and a trusted runner. An +// empty RunnerPath looks only alongside the current executable, never in PATH. +type Options struct { + DataRoot func() string + RunnerPath string +} + +// Driver is independent of the Windows runtime and owns no host-side VM process API. +type Driver struct{ opts Options } + +var ( + _ driver.Driver = (*Driver)(nil) + _ driver.LogDriver = (*Driver)(nil) + _ driver.WindowDriver = (*Driver)(nil) +) + +func New(opts Options) *Driver { return &Driver{opts: opts} } + +func (*Driver) ID() string { return ID } + +func (*Driver) DisplayName() plugin.LocalizedText { + return plugin.LocalizedText{ZhCN: "macOS(Apple 虚拟化)", EnUS: "macOS (Apple virtualization)"} +} + +func (*Driver) RuntimeKind() string { return "external" } +func (*Driver) RuntimeAPIRange() string { return "" } +func (*Driver) Capabilities() []string { return []string{driver.CapHosted, driver.CapWindow} } + +// Inventory lists registered instances even when the native driver is inactive. +func Inventory(dataRoot string) ([]driver.VMInfo, error) { + d := New(Options{DataRoot: func() string { return dataRoot }}) + return d.List(context.Background()) +} + +func (d *Driver) List(ctx context.Context) ([]driver.VMInfo, error) { + root, err := d.root(false) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + entries, err := os.ReadDir(root) + if err != nil { + return nil, err + } + out := make([]driver.VMInfo, 0, len(entries)) + for _, entry := range entries { + if err := ctx.Err(); err != nil { + return nil, err + } + if !entry.IsDir() || !validName(entry.Name()) { + continue + } + vm := instance{dir: filepath.Join(root, entry.Name()), name: entry.Name()} + if !vm.owned() { + continue + } + out = append(out, d.info(vm)) + } + return out, nil +} + +func (d *Driver) Show(ctx context.Context, name string) (driver.VMInfo, error) { + if err := ctx.Err(); err != nil { + return driver.VMInfo{}, err + } + vm, err := d.find(name) + if err != nil { + return driver.VMInfo{}, err + } + return d.info(vm), nil +} + +func (d *Driver) info(vm instance) driver.VMInfo { + info := driver.VMInfo{ + Name: vm.name, DriverID: ID, DriverName: d.DisplayName().EnUS, + Directory: vm.dir, Capabilities: d.Capabilities(), Network: true, + GuestOS: &driver.GuestOSInfo{Family: driver.GuestFamilyMacOS, Arch: "arm64"}, + State: "broken", Phase: driver.PhaseNormal, + } + cfg, err := vm.config() + if err != nil { + return info + } + info.Name, info.CPUs, info.Memory = cfg.Name, cfg.CPUs, formatMemory(cfg.MemoryMiB) + info.DiskSummary = fmt.Sprintf("%d GiB", cfg.DiskGiB) + info.DriverData = map[string]any{"cpus": cfg.CPUs, "memory": info.Memory} + if vm.installed() == nil { + info.DiskPath = vm.path(machineDirectory, "disk.img") + info.State = "stopped" + } + if status, err := vm.status(); err == nil { + switch status.State { + case "installing": + info.State, info.Phase = "starting", driver.PhaseInstaller + case "starting", "running", "stopping": + info.State = status.State + } + } else { + info.State = "broken" + } + return info +} + +func (d *Driver) ReadLogs(ctx context.Context, name string, serial bool) (string, error) { + if serial { + return "", errors.ErrUnsupported + } + if err := ctx.Err(); err != nil { + return "", err + } + vm, err := d.find(name) + if err != nil { + return "", err + } + return vm.logTail(128 << 10) +} + +// ShowWindow reopens or brings forward the runner's native viewer. +func (d *Driver) ShowWindow(ctx context.Context, name string) error { + return d.control(ctx, name, "show", false, nil, nil) +} + +func (d *Driver) Stop(ctx context.Context, name string, force bool, stdout, stderr io.Writer) error { + return d.control(ctx, name, "stop", force, stdout, stderr) +} diff --git a/internal/macos/applevz/lifecycle.go b/internal/macos/applevz/lifecycle.go new file mode 100644 index 0000000..212603f --- /dev/null +++ b/internal/macos/applevz/lifecycle.go @@ -0,0 +1,176 @@ +package applevz + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "path/filepath" + + "github.com/Nwflower/reims-go/internal/atomicfile" + "github.com/Nwflower/reims-go/internal/driver" +) + +func (d *Driver) Create(ctx context.Context, req driver.CreateRequest, stdout, stderr io.Writer) error { + cfg, restore, issues := d.createConfig(ctx, req) + if len(issues) > 0 { + return errors.New(issues[0].Message) + } + bounds, err := d.probe(ctx) + if err != nil { + return err + } + if err := bounds.validate(cfg); err != nil { + return err + } + root, err := d.root(true) + if err != nil { + return err + } + op, err := lockOperations(root, cfg.Name) + if err != nil { + return err + } + defer op.Close() + vm, err := createInstance(root, cfg) + if err != nil { + return err + } + if err := d.invoke(ctx, vm, stdout, stderr, "install", "--ipsw", restore); err != nil { + return fmt.Errorf("install macOS into %q (see the VM logs): %w", vm.name, err) + } + return vm.installed() +} + +func createInstance(root string, cfg vmConfig) (instance, error) { + if existing, err := namedInstance(root, cfg.Name); err == nil { + return retryUnpublished(existing, cfg) + } else if !errors.Is(err, os.ErrNotExist) { + return instance{}, err + } + vm := instance{dir: filepath.Join(root, cfg.Name), name: cfg.Name} + if err := os.Mkdir(vm.dir, 0o700); err != nil { + return instance{}, err + } + if err := atomicfile.WriteJSON(vm.path(configFile), cfg, 0o600); err != nil { + return instance{}, errors.Join(err, os.Remove(vm.dir)) + } + if err := atomicfile.Write(vm.path(driver.OwnerMarkerFile), []byte(ID+"\n"), 0o600); err != nil { + return instance{}, errors.Join(err, os.Remove(vm.path(configFile)), os.Remove(vm.dir)) + } + return vm, nil +} + +func retryUnpublished(vm instance, cfg vmConfig) (instance, error) { + if err := requireDirectory(vm.dir); err != nil || !vm.owned() { + return instance{}, fmt.Errorf("an unmanaged directory already exists for %q", cfg.Name) + } + lock, err := acquireLock(vm.path(runnerLock), true) + if err != nil { + return instance{}, err + } + if lock == nil { + return instance{}, fmt.Errorf("VM %q is already in use", cfg.Name) + } + defer lock.Close() + for _, name := range []string{machineDirectory, ".applevz-installing"} { + if _, err := os.Lstat(vm.path(name)); err == nil { + if name == machineDirectory { + return instance{}, fmt.Errorf("VM %q already has a published machine", cfg.Name) + } + return instance{}, fmt.Errorf("VM %q has interrupted staging data; delete the incomplete VM before retrying", cfg.Name) + } else if !errors.Is(err, os.ErrNotExist) { + return instance{}, err + } + } + if _, err := vm.config(); err != nil { + return instance{}, err + } + cfg.Name = vm.name + return vm, atomicfile.WriteJSON(vm.path(configFile), cfg, 0o600) +} + +func (d *Driver) ValidateSet(ctx context.Context, req driver.SetRequest) []driver.ValidationIssue { + if err := ctx.Err(); err != nil { + return []driver.ValidationIssue{issue("", err)} + } + vm, err := d.find(req.Name) + if err == nil { + var cfg vmConfig + cfg, err = vm.config() + if err == nil { + return cfg.apply(req.Changes, false) + } + } + return []driver.ValidationIssue{issue("name", err)} +} + +func (d *Driver) Set(ctx context.Context, req driver.SetRequest, _, _ io.Writer) error { + vm, release, err := d.lockStopped(ctx, req.Name) + if err != nil { + return err + } + defer release() + if err := vm.installed(); err != nil { + return err + } + cfg, err := vm.config() + if err != nil { + return err + } + if issues := cfg.apply(req.Changes, false); len(issues) > 0 { + return errors.New(issues[0].Message) + } + bounds, err := d.probe(ctx) + if err != nil { + return err + } + bounds, err = vm.applyGuestMinimum(bounds) + if err != nil { + return err + } + if err := bounds.validate(cfg); err != nil { + return err + } + return atomicfile.WriteJSON(vm.path(configFile), cfg, 0o600) +} + +func (d *Driver) Delete(ctx context.Context, name string, keepFiles bool, _, _ io.Writer) error { + vm, release, err := d.lockStopped(ctx, name) + if err != nil { + return err + } + defer release() + if keepFiles { + return os.Remove(vm.path(driver.OwnerMarkerFile)) + } + // lockStopped re-resolved the owned, non-symlink child of the driver root. + return os.RemoveAll(vm.dir) +} + +func (d *Driver) lockStopped(ctx context.Context, name string) (instance, func(), error) { + if err := ctx.Err(); err != nil { + return instance{}, nil, err + } + root, err := d.root(false) + if err != nil { + return instance{}, nil, err + } + op, err := lockOperations(root, name) + if err != nil { + return instance{}, nil, err + } + vm, err := ownedInstance(root, name) + if err == nil { + var runtime *os.File + runtime, err = acquireLock(vm.path(runnerLock), true) + if runtime != nil { + return vm, func() { runtime.Close(); op.Close() }, nil + } + if err == nil { + err = fmt.Errorf("shut down VM %q before changing or deleting it", name) + } + } + return instance{}, nil, errors.Join(err, op.Close()) +} diff --git a/internal/macos/applevz/platform_darwin.go b/internal/macos/applevz/platform_darwin.go new file mode 100644 index 0000000..a5677cd --- /dev/null +++ b/internal/macos/applevz/platform_darwin.go @@ -0,0 +1,35 @@ +package applevz + +import ( + "os" + "os/exec" + "syscall" +) + +const safeOpenFlags = syscall.O_NOFOLLOW | syscall.O_NONBLOCK + +func sharedFile(info os.FileInfo) bool { + st, ok := info.Sys().(*syscall.Stat_t) + return !ok || st.Nlink != 1 +} + +func tryStatusLock(file *os.File) (bool, error) { + err := syscall.Flock(int(file.Fd()), syscall.LOCK_SH|syscall.LOCK_NB) + if err == syscall.EWOULDBLOCK { + return false, nil + } + return err == nil, err +} + +func detachRunner(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} +} + +func interruptInstaller(process *os.Process) error { + if err := process.Signal(syscall.SIGTERM); err != nil { + return err + } + // A successful atomic publication wins over a racing cancellation. A + // cancelled installer still exits nonzero and its context error is retained. + return os.ErrProcessDone +} diff --git a/internal/macos/applevz/platform_other.go b/internal/macos/applevz/platform_other.go new file mode 100644 index 0000000..af0f211 --- /dev/null +++ b/internal/macos/applevz/platform_other.go @@ -0,0 +1,22 @@ +//go:build !darwin + +package applevz + +import ( + "os" + "os/exec" + + "github.com/Nwflower/reims-go/internal/filelock" +) + +// The shared schema and inventory compile on other platforms. Probe never +// permits runner operations there, so process and open flags are Darwin-only. +const safeOpenFlags = 0 + +func tryStatusLock(file *os.File) (bool, error) { return filelock.TryLock(file) } + +func detachRunner(*exec.Cmd) {} + +func interruptInstaller(process *os.Process) error { return process.Kill() } + +func sharedFile(os.FileInfo) bool { return false } diff --git a/internal/macos/applevz/resources.go b/internal/macos/applevz/resources.go new file mode 100644 index 0000000..87d819d --- /dev/null +++ b/internal/macos/applevz/resources.go @@ -0,0 +1,42 @@ +package applevz + +import ( + "encoding/json" + "errors" + "fmt" + "os" +) + +func (b resourceBounds) validate(cfg vmConfig) error { + if cfg.CPUs < b.MinCPU || cfg.CPUs > b.MaxCPU { + return fmt.Errorf("this guest and host require %d–%d vCPUs", b.MinCPU, b.MaxCPU) + } + if uint64(cfg.MemoryMiB) < b.MinRAM || uint64(cfg.MemoryMiB) > b.MaxRAM { + return fmt.Errorf("this guest and host require %d–%d MiB RAM", b.MinRAM, b.MaxRAM) + } + return nil +} + +func (vm instance) applyGuestMinimum(bounds resourceBounds) (resourceBounds, error) { + raw, err := readSmallFile(vm.path(machineDirectory, "requirements.json")) + if errors.Is(err, os.ErrNotExist) { + return bounds, nil // VMs installed before Nivfold may not have these metadata. + } + if err != nil { + return bounds, err + } + var minimum struct { + Version int `json:"version"` + CPU int `json:"minimum_cpu_count"` + RAM uint64 `json:"minimum_memory_mib"` + } + if err := json.Unmarshal(raw, &minimum); err != nil || minimum.Version != 1 || minimum.CPU < 1 || minimum.RAM < 1 { + return bounds, errors.New("invalid or incompatible Nivfold guest requirements") + } + bounds.MinCPU = max(bounds.MinCPU, minimum.CPU) + bounds.MinRAM = max(bounds.MinRAM, minimum.RAM) + if bounds.MinCPU > bounds.MaxCPU || bounds.MinRAM > bounds.MaxRAM { + return bounds, errors.New("the guest's minimum CPU or memory exceeds this host's limit") + } + return bounds, nil +} diff --git a/internal/macos/applevz/restore.go b/internal/macos/applevz/restore.go new file mode 100644 index 0000000..ef7085a --- /dev/null +++ b/internal/macos/applevz/restore.go @@ -0,0 +1,59 @@ +package applevz + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os/exec" + "slices" + "time" +) + +// RestoreImage is metadata from the framework, not an installer or a user URL. +type RestoreImage struct { + Version string `json:"version"` + Build string `json:"build"` + URL string `json:"url,omitempty"` +} + +// ErrRestoreCatalogUnsupported distinguishes old runners from network failure. +var ErrRestoreCatalogUnsupported = errors.New("this Nivfold build does not support restore image downloads") + +// LatestRestoreImage queries Apple via Nivfold without transferring the image. +func (d *Driver) LatestRestoreImage(ctx context.Context) (RestoreImage, error) { + probe, err := d.runProbe(ctx) + if err != nil { + return RestoreImage{}, err + } + if !slices.Contains(probe.Capabilities, "restore-image") || !slices.Contains(probe.Capabilities, "inspect-restore-image") { + return RestoreImage{}, ErrRestoreCatalogUnsupported + } + return d.queryRestoreImage(ctx, 40*time.Second, "restore-image") +} + +// InspectRestoreImage uses the framework to read a local image and check host compatibility. +func (d *Driver) InspectRestoreImage(ctx context.Context, path string) (RestoreImage, error) { + return d.queryRestoreImage(ctx, 2*time.Minute, "inspect-restore-image", "--ipsw", path) +} + +func (d *Driver) queryRestoreImage(ctx context.Context, limit time.Duration, command string, args ...string) (RestoreImage, error) { + var result RestoreImage + path, err := d.runnerPath() + if err != nil { + return result, err + } + ctx, cancel := context.WithTimeout(ctx, limit) + defer cancel() + cmd := exec.CommandContext(ctx, path, append([]string{command}, args...)...) + var stdout, stderr outputTail + cmd.Stdout, cmd.Stderr = &stdout, &stderr + cmd.WaitDelay = 2 * time.Second + if err := cmd.Run(); err != nil { + return result, fmt.Errorf("Nivfold %s: %w", command, commandError(ctx, err, &stderr)) + } + if err := json.Unmarshal(stdout.Bytes(), &result); err != nil { + return result, fmt.Errorf("decode Nivfold restore image metadata: %w", err) + } + return result, nil +} diff --git a/internal/macos/applevz/runner.go b/internal/macos/applevz/runner.go new file mode 100644 index 0000000..09e315f --- /dev/null +++ b/internal/macos/applevz/runner.go @@ -0,0 +1,370 @@ +package applevz + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync" + "time" + + "github.com/Nwflower/reims-go/internal/driver" +) + +const runnerName = "nivfold" + +func (d *Driver) runnerPath() (string, error) { + if runtime.GOOS != "darwin" || runtime.GOARCH != "arm64" { + return "", errors.New("Apple virtualization requires Apple silicon macOS") + } + path := d.opts.RunnerPath + if path == "" { + executable, err := os.Executable() + if err != nil { + return "", err + } + path = filepath.Join(filepath.Dir(executable), runnerName) + } + if !filepath.IsAbs(path) { + return "", errors.New("the Apple virtualization helper path must be absolute") + } + info, err := os.Stat(path) + if err != nil { + return "", fmt.Errorf("find Apple virtualization helper %q: %w", path, err) + } + if !info.Mode().IsRegular() || info.Mode().Perm()&0o111 == 0 { + return "", fmt.Errorf("the Apple virtualization helper is not executable: %q", path) + } + return path, nil +} + +type resourceBounds struct { + MinCPU int `json:"minimum_cpu_count"` + MaxCPU int `json:"maximum_cpu_count"` + MinRAM uint64 `json:"minimum_memory_mib"` + MaxRAM uint64 `json:"maximum_memory_mib"` +} + +type runnerProbe struct { + Runtime string `json:"runtime"` + Version int `json:"protocol_version"` + Supported bool `json:"supported"` + Resources resourceBounds `json:"resources"` + Capabilities []string `json:"capabilities"` +} + +// Probe checks both local platform support and the runner's protocol version. +func (d *Driver) Probe(ctx context.Context) error { + _, err := d.runProbe(ctx) + return err +} + +func (d *Driver) probe(ctx context.Context) (resourceBounds, error) { + probe, err := d.runProbe(ctx) + return probe.Resources, err +} + +func (d *Driver) runProbe(ctx context.Context) (runnerProbe, error) { + var empty runnerProbe + path, err := d.runnerPath() + if err != nil { + return empty, err + } + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, path, "probe") + var stdout, stderr outputTail + cmd.Stdout, cmd.Stderr = &stdout, &stderr + cmd.WaitDelay = 2 * time.Second + if err := cmd.Run(); err != nil { + return empty, fmt.Errorf("check Nivfold: %w", commandError(ctx, err, &stderr)) + } + var probe runnerProbe + if err := json.Unmarshal(stdout.Bytes(), &probe); err != nil || probe.Runtime != runnerName || probe.Version != 1 { + return empty, errors.New("expected a compatible Nivfold runtime (protocol 1)") + } + if !probe.Supported { + return empty, errors.New("Nivfold reports this Mac is unsupported") + } + b := probe.Resources + if b.MinCPU < 1 || b.MaxCPU < b.MinCPU || b.MinRAM < 1 || b.MaxRAM < b.MinRAM { + return empty, errors.New("Nivfold did not report valid CPU and memory limits") + } + return probe, nil +} + +func (d *Driver) invoke(ctx context.Context, vm instance, stdout, stderr io.Writer, action string, tail ...string) error { + path, err := d.runnerPath() + if err != nil { + return err + } + args := append([]string{action, "--vm-dir", vm.dir}, tail...) + cmd := exec.CommandContext(ctx, path, args...) + cmd.WaitDelay = 2 * time.Second + if action == "install" { + cmd.WaitDelay = 15 * time.Second + cmd.Cancel = func() error { return signalInstallOwner(vm, cmd.Process) } + } + log, err := openRegular(vm.path(logFile), os.O_CREATE|os.O_WRONLY|os.O_APPEND) + if err != nil { + return err + } + defer log.Close() + var diagnostics outputTail + cmd.Stdout = io.MultiWriter(log, orDiscard(stdout)) + // A caller may provide the same writer twice (the GUI does). Go may copy + // stdout and stderr concurrently; route through one Go writer in that case + // by always serializing writes through a shared mutex-bearing writer. + cmd.Stderr = io.MultiWriter(log, &diagnostics, orDiscard(stderr)) + cmd.Stdout, cmd.Stderr = serializedWriters(cmd.Stdout, cmd.Stderr) + if err := cmd.Run(); err != nil { + if action == "install" && ctx.Err() != nil { + var exit *exec.ExitError + if errors.As(err, &exit) && exit.ExitCode() == 1 { + // Cleanup or a non-cancellation error must not look like a clean cancellation. + return commandError(context.WithoutCancel(ctx), err, &diagnostics) + } + } + return commandError(ctx, err, &diagnostics) + } + return nil +} + +func signalInstallOwner(vm instance, process *os.Process) error { + // Installing is published only after the runner's signal handler is armed. + // Wait briefly for it so early cancellation can use the same cleanup path. + deadline := time.Now().Add(250 * time.Millisecond) + for time.Now().Before(deadline) { + if status, err := vm.activeStatus(); err == nil && status.State == "installing" && status.PID == process.Pid { + break + } + time.Sleep(10 * time.Millisecond) + } + return interruptInstaller(process) +} + +func (d *Driver) control(ctx context.Context, name, action string, force bool, stdout, stderr io.Writer) error { + vm, err := d.find(name) + if err != nil { + return err + } + var flags []string + timeout := 5 * time.Second + if action == "stop" { + timeout = 70 * time.Second + if force { + timeout = 20 * time.Second + flags = append(flags, "--force") + } + } + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + return d.invoke(ctx, vm, stdout, stderr, action, flags...) +} + +func (d *Driver) Start(ctx context.Context, req driver.StartRequest) (driver.StartResult, error) { + if req.Ref.DriverID != "" && req.Ref.DriverID != ID { + return driver.StartResult{}, fmt.Errorf("incorrect driver %q", req.Ref.DriverID) + } + if err := startIntents(req); err != nil { + return driver.StartResult{}, err + } + if err := d.Probe(ctx); err != nil { + return driver.StartResult{}, err + } + return driver.StartResult{}, d.start(ctx, req.Ref.Name) +} + +func startIntents(req driver.StartRequest) error { + for _, intent := range req.Intents { + if intent.BlockReason != "" { + return errors.New(intent.BlockReason) + } + if len(intent.Args)+len(intent.Env)+len(intent.ClearKeys)+len(intent.PostStart) != 0 { + return fmt.Errorf("plugin %q requested startup changes unsupported by Apple virtualization", intent.PluginID) + } + for _, warning := range intent.Warnings { + if _, err := fmt.Fprintln(orDiscard(req.Stderr), warning); err != nil { + return err + } + } + } + return nil +} + +func (d *Driver) start(ctx context.Context, name string) error { + root, err := d.root(false) + if err != nil { + return err + } + op, err := lockOperations(root, name) + if err != nil { + return err + } + defer op.Close() + vm, err := ownedInstance(root, name) + if err != nil { + return err + } + if _, err := vm.config(); err != nil { + return err + } + if err := vm.installed(); err != nil { + return err + } + // The native owner takes the runtime lock. Probing it here would race + // read-only status requests and would not reserve it for this launch. + return d.launch(ctx, vm) +} + +func (d *Driver) launch(ctx context.Context, vm instance) error { + if err := ctx.Err(); err != nil { + return err + } + path, err := d.runnerPath() + if err != nil { + return err + } + log, err := openRegular(vm.path(logFile), os.O_CREATE|os.O_WRONLY|os.O_APPEND) + if err != nil { + return err + } + defer log.Close() + // The native runner, VM and viewer outlive this command and the desktop. + // File-backed output avoids blocking on a pipe or app writer after return. + cmd := exec.Command(path, "run", "--vm-dir", vm.dir) + cmd.Stdout, cmd.Stderr = log, log + detachRunner(cmd) + if err := cmd.Start(); err != nil { + return err + } + exited := make(chan error, 1) + go func() { exited <- cmd.Wait() }() + ctx, cancel := context.WithTimeout(ctx, 45*time.Second) + defer cancel() + if err := waitForStart(ctx, vm, cmd.Process.Pid, exited); err != nil { + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + err = errors.Join(err, d.cancelStart(vm, cmd.Process.Pid, exited)) + } + return fmt.Errorf("start VM %q (see the VM logs): %w", vm.name, err) + } + return nil +} + +func waitForStart(ctx context.Context, vm instance, pid int, exited <-chan error) error { + ticker := time.NewTicker(50 * time.Millisecond) + defer ticker.Stop() + var lastStatusErr error + for { + select { + case err := <-exited: + if err == nil { + err = errors.New("runner exited before the VM started") + } + return errors.Join(err, lastStatusErr) + case <-ctx.Done(): + return errors.Join(ctx.Err(), lastStatusErr) + case <-ticker.C: + status, err := vm.status() + if err != nil { + // A status check can race with the runner publishing its state. + lastStatusErr = fmt.Errorf("last startup status check: %w", err) + continue + } + if status.PID == pid && status.State == "running" { + return nil + } + } + } +} + +func (d *Driver) cancelStart(vm instance, pid int, exited <-chan error) error { + ctx, cancel := context.WithTimeout(context.Background(), 21*time.Second) + defer cancel() + // At cancellation the spawned helper may not have published a PID yet. + // Wait briefly, but never send a stop command for an unrelated owner. + for i := 0; i < 10; i++ { + status, err := vm.status() + if err != nil { + return fmt.Errorf("cannot confirm VM state after cancellation: %w", err) + } + if status.PID == pid { + err = d.invoke(ctx, vm, nil, nil, "stop", "--force", "--expect-pid", strconv.Itoa(pid)) + if err == nil { + return nil + } + // The runner publishes its starting state before opening its socket. + if i == 9 || ctx.Err() != nil { + return fmt.Errorf("could not cancel the native startup; check VM state: %w", err) + } + } else if status.PID > 0 { + return nil + } + select { + case <-exited: + return nil + case <-time.After(100 * time.Millisecond): + } + } + return errors.New("cannot confirm the startup owner; check VM state before retrying") +} + +type serialWriter struct { + mu *sync.Mutex + w io.Writer +} + +func (w serialWriter) Write(data []byte) (int, error) { + w.mu.Lock() + defer w.mu.Unlock() + return w.w.Write(data) +} + +func serializedWriters(stdout, stderr io.Writer) (io.Writer, io.Writer) { + mu := new(sync.Mutex) + return serialWriter{mu: mu, w: stdout}, serialWriter{mu: mu, w: stderr} +} + +func orDiscard(w io.Writer) io.Writer { + if w == nil { + return io.Discard + } + return w +} + +func commandError(ctx context.Context, err error, stderr *outputTail) error { + if ctx.Err() != nil { + return ctx.Err() + } + if detail := strings.TrimSpace(stderr.String()); detail != "" { + return fmt.Errorf("%w: %s", err, detail) + } + return err +} + +// outputTail bounds short protocol responses and diagnostic output in memory. +type outputTail struct{ bytes.Buffer } + +func (w *outputTail) Write(b []byte) (int, error) { + const limit = 8 << 10 + if len(b) >= limit { + w.Reset() + _, err := w.Buffer.Write(b[len(b)-limit:]) + return len(b), err + } + if drop := w.Len() + len(b) - limit; drop > 0 { + // Release consumed space instead of keeping a buffer that grows with + // consecutive writes. + copy(w.Bytes(), w.Bytes()[drop:]) + w.Truncate(w.Len() - drop) + } + return w.Buffer.Write(b) +} diff --git a/internal/macos/applevz/runner_test.go b/internal/macos/applevz/runner_test.go new file mode 100644 index 0000000..4a1154f --- /dev/null +++ b/internal/macos/applevz/runner_test.go @@ -0,0 +1,499 @@ +//go:build darwin && arm64 + +package applevz + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/signal" + "path/filepath" + "slices" + "strings" + "syscall" + "testing" + "testing/synctest" + "time" + + "github.com/Nwflower/reims-go/internal/atomicfile" + "github.com/Nwflower/reims-go/internal/driver" +) + +func TestNativeDriverLifecycle(t *testing.T) { + d, localRestore := newTestDriver(t) + ctx := t.Context() + if err := d.Probe(ctx); err != nil { + t.Fatal(err) + } + if list, err := d.List(ctx); err != nil || len(list) != 0 { + t.Fatalf("initial inventory = %v, %v", list, err) + } + req := driver.CreateRequest{DriverID: ID, Name: "Tahoe", Options: map[string]any{ + "cpus": float64(6), "memory": "12GiB", "disk_size": "128G", "restore_path": localRestore, + }} + var output bytes.Buffer + if err := d.Create(ctx, req, &output, &output); err != nil { + t.Fatal(err) + } + if !strings.Contains(output.String(), "installed from fixture.ipsw") { + t.Fatalf("unexpected installer output: %q", output.String()) + } + info, err := d.Show(ctx, "tahoe") + if err != nil || info.Name != "Tahoe" || info.CPUs != 6 || info.Memory != "12G" || info.State != "stopped" || + info.DiskSummary != "128 GiB" || info.GuestOS == nil || info.GuestOS.Arch != "arm64" || info.PID != nil || + !driver.HasCapability(info.Capabilities, driver.CapWindow) || !driver.IsHosted(info.Capabilities) { + t.Fatalf("installed VM: %+v, %v", info, err) + } + list, err := d.List(ctx) + if err != nil || len(list) != 1 || list[0].Name != "Tahoe" { + t.Fatalf("inventory = %v, %v", list, err) + } + if err := d.Create(ctx, driver.CreateRequest{Name: "tahoe", Options: req.Options}, nil, nil); err == nil { + t.Fatal("case-insensitive duplicate was accepted") + } + vm, err := d.find("Tahoe") + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(vm.path(machineDirectory, "requirements.json"), []byte(`{"version":1,"minimum_cpu_count":4,"minimum_memory_mib":8192}`), 0o600); err != nil { + t.Fatal(err) + } + before, err := os.ReadFile(vm.path(configFile)) + if err != nil { + t.Fatal(err) + } + for _, options := range []map[string]any{{"cpus": 2}, {"cpus": 11}, {"memory": "6G"}, {"memory": "32G"}} { + if err := d.Set(ctx, driver.SetRequest{Name: "Tahoe", Changes: options}, nil, nil); err == nil { + t.Fatalf("accepted invalid configuration: %v", options) + } + } + if after, err := os.ReadFile(vm.path(configFile)); err != nil || !bytes.Equal(before, after) { + t.Fatalf("rejected settings changed disk configuration: %v", err) + } + if err := d.Set(ctx, driver.SetRequest{Name: "Tahoe", Changes: map[string]any{"memory": "10240M"}}, nil, nil); err != nil { + t.Fatal(err) + } + start := driver.StartRequest{Ref: driver.NewVMRef(ID, "Tahoe")} + defer func() { _ = d.Stop(context.Background(), "Tahoe", true, nil, nil) }() + startCtx, cancel := context.WithCancel(ctx) + defer cancel() + if _, err := d.Start(startCtx, start); err != nil { + t.Fatal(err) + } + cancel() // A successful VM launch must outlive its caller's context. + other := New(d.opts) + if info, err := other.Show(ctx, "Tahoe"); err != nil || info.State != "running" || info.Memory != "10G" || info.PID != nil { + t.Fatalf("detached VM: %+v, %v", info, err) + } + if err := other.ShowWindow(ctx, "Tahoe"); err != nil { + t.Fatal(err) + } + if _, err := other.Start(ctx, start); err == nil { + t.Fatal("started the same VM twice") + } + if err := other.Delete(ctx, "Tahoe", false, nil, nil); err == nil { + t.Fatal("deleted a live VM") + } + if err := other.Set(ctx, driver.SetRequest{Name: "Tahoe", Changes: map[string]any{"cpus": 2}}, nil, nil); err == nil { + t.Fatal("changed the settings of a live VM") + } + if err := other.Stop(ctx, "Tahoe", false, nil, nil); err != nil { + t.Fatal(err) + } + if info, err := other.Show(ctx, "Tahoe"); err != nil || info.State != "stopped" { + t.Fatalf("stopped VM: %+v, %v", info, err) + } + logs, err := other.ReadLogs(ctx, "Tahoe", false) + if err != nil || !strings.Contains(logs, "installed") || !strings.Contains(logs, "READY") || !strings.Contains(logs, "viewer shown") { + t.Fatalf("runner logs = %q, %v", logs, err) + } + if err := other.Delete(ctx, "Tahoe", true, nil, nil); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(info.DiskPath); err != nil { + t.Fatalf("keep-files removed disk: %v", err) + } + if list, err := other.List(ctx); err != nil || len(list) != 0 { + t.Fatalf("unregistered VM in list: %v, %v", list, err) + } +} + +func TestInstallCancellationKeepsInstanceRecoverable(t *testing.T) { + d, restore := newTestDriver(t) + t.Setenv("APPLE_VZ_TEST_INSTALL_WAIT", "1") + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + done := make(chan error, 1) + go func() { + done <- d.Create(ctx, driver.CreateRequest{Name: "cancelled", Options: map[string]any{"restore_path": restore}}, nil, nil) + }() + until(t, func() bool { + info, err := d.Show(t.Context(), "cancelled") + return err == nil && info.Phase == driver.PhaseInstaller + }) + if err := d.Delete(t.Context(), "cancelled", false, nil, nil); err == nil { + t.Fatal("deleted a VM while native install was active") + } + cancel() + select { + case err := <-done: + if !errors.Is(err, context.Canceled) { + t.Fatalf("install cancellation: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("cancelled installer did not exit") + } + if info, err := d.Show(t.Context(), "cancelled"); err != nil || info.State != "broken" { + t.Fatalf("interrupted VM not recoverable: %+v, %v", info, err) + } + if _, err := d.Start(t.Context(), driver.StartRequest{Ref: driver.NewVMRef(ID, "cancelled")}); err == nil { + t.Fatal("ran an uninstalled VM") + } + t.Setenv("APPLE_VZ_TEST_INSTALL_WAIT", "0") + if err := d.Create(t.Context(), driver.CreateRequest{Name: "Cancelled", Options: map[string]any{"restore_path": restore}}, nil, nil); err != nil { + t.Fatalf("could not retry cleanly cancelled installation: %v", err) + } + if info, err := d.Show(t.Context(), "cancelled"); err != nil || info.State != "stopped" || info.Name != "cancelled" { + t.Fatalf("retry did not preserve registration: %+v, %v", info, err) + } +} + +func TestPublishedInstallWinsRacingCancellation(t *testing.T) { + d, restore := newTestDriver(t) + t.Setenv("APPLE_VZ_TEST_INSTALL_WAIT", "1") + t.Setenv("APPLE_VZ_TEST_COMMIT_ON_CANCEL", "1") + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + done := make(chan error, 1) + go func() { + done <- d.Create(ctx, driver.CreateRequest{Name: "commit", Options: map[string]any{"restore_path": restore}}, nil, nil) + }() + until(t, func() bool { + info, err := d.Show(t.Context(), "commit") + return err == nil && info.Phase == driver.PhaseInstaller + }) + cancel() + select { + case err := <-done: + if err != nil { + t.Fatalf("published VM was reported as canceled: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("test installer did not exit") + } + if info, err := d.Show(t.Context(), "commit"); err != nil || info.State != "stopped" { + t.Fatalf("missing published VM: %+v %v", info, err) + } +} + +func TestCancelledStartStopsOnlyItsRunner(t *testing.T) { + d, restore := newTestDriver(t) + if err := d.Create(t.Context(), driver.CreateRequest{Name: "slow", Options: map[string]any{"restore_path": restore}}, nil, nil); err != nil { + t.Fatal(err) + } + t.Setenv("APPLE_VZ_TEST_RUN_WAIT", "1") + defer func() { _ = d.Stop(context.Background(), "slow", true, nil, nil) }() + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + done := make(chan error, 1) + go func() { + _, err := d.Start(ctx, driver.StartRequest{Ref: driver.NewVMRef(ID, "slow")}) + done <- err + }() + until(t, func() bool { + vm, err := d.find("slow") + if err != nil { + return false + } + status, err := vm.status() + return err == nil && status.PID > 0 && status.State == "starting" + }) + cancel() + select { + case err := <-done: + if !errors.Is(err, context.Canceled) { + t.Fatalf("start cancellation: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("cancelled startup did not exit") + } + if vm, err := d.Show(t.Context(), "slow"); err != nil || vm.State != "stopped" { + t.Fatalf("cancelled start left running VM: %+v, %v", vm, err) + } + if text, err := d.ReadLogs(t.Context(), "slow", false); err != nil || !strings.Contains(text, "stopped expected owner") { + t.Fatalf("runner did not verify owner: %q, %v", text, err) + } +} + +func TestWaitForStartRecoversFromTransientStatusErrors(t *testing.T) { + vm := newStartStatusFixture(t) + const pid = 123 + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), time.Second) + defer cancel() + done := make(chan error, 1) + go func() { done <- waitForStart(ctx, vm, pid, make(chan error)) }() + + for _, data := range []string{ + `{"state":`, + `{"state":"ready","pid":123}`, + `{"state":"running","pid":456}`, + `{"state":"starting","pid":123}`, + } { + writeStartStatus(t, vm, data) + time.Sleep(100 * time.Millisecond) + synctest.Wait() + select { + case err := <-done: + t.Fatalf("startup ended after status %s: %v", data, err) + default: + } + } + writeStartStatus(t, vm, `{"state":"running","pid":123}`) + if err := <-done; err != nil { + t.Fatalf("startup did not recover: %v", err) + } + }) +} + +func TestWaitForStartReportsLastStatusError(t *testing.T) { + for _, exitEarly := range []bool{false, true} { + name := "deadline" + if exitEarly { + name = "runner exit" + } + t.Run(name, func(t *testing.T) { + vm := newStartStatusFixture(t) + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), time.Second) + defer cancel() + exited, done := make(chan error, 1), make(chan error, 1) + go func() { done <- waitForStart(ctx, vm, 123, exited) }() + + writeStartStatus(t, vm, `{"state":`) + time.Sleep(100 * time.Millisecond) + synctest.Wait() + writeStartStatus(t, vm, `{"state":"ready","pid":123}`) + time.Sleep(100 * time.Millisecond) + synctest.Wait() + writeStartStatus(t, vm, `{"state":"running","pid":456}`) + time.Sleep(100 * time.Millisecond) + synctest.Wait() + + want := context.DeadlineExceeded + if exitEarly { + want = errors.New("test runner exited") + exited <- want + } + err := <-done + if !errors.Is(err, want) || !strings.Contains(err.Error(), "invalid runner status") || strings.Contains(err.Error(), "read runner status") { + t.Fatalf("want %v and only the most recent status error, got %v", want, err) + } + }) + }) + } +} + +func newStartStatusFixture(t *testing.T) instance { + t.Helper() + vm := instance{dir: t.TempDir()} + lock, err := acquireLock(vm.path(runnerLock), true) + if err != nil || lock == nil { + t.Fatalf("acquire test runner lock: %v", err) + } + t.Cleanup(func() { + if err := lock.Close(); err != nil { + t.Error(err) + } + }) + return vm +} + +func writeStartStatus(t *testing.T, vm instance, status string) { + t.Helper() + if err := atomicfile.Write(vm.path(statusFile), []byte(status), 0o600); err != nil { + t.Fatal(err) + } +} + +func newTestDriver(t *testing.T) (*Driver, string) { + t.Helper() + dir := t.TempDir() + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + t.Setenv("APPLE_VZ_TEST_BIN", exe) + path := filepath.Join(dir, runnerName) + wrapper := "#!/bin/sh\nexec \"$APPLE_VZ_TEST_BIN\" -test.run '^TestRunnerProcess$' -- \"$@\"\n" + if err := os.WriteFile(path, []byte(wrapper), 0o700); err != nil { + t.Fatal(err) + } + restore := filepath.Join(dir, "fixture.ipsw") + if err := os.WriteFile(restore, []byte("not an Apple image"), 0o600); err != nil { + t.Fatal(err) + } + return New(Options{DataRoot: func() string { return filepath.Join(dir, "data") }, RunnerPath: path}), restore +} + +func until(t *testing.T, ready func() bool) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for !ready() { + if time.Now().After(deadline) { + t.Fatal("timed out waiting for fake runner") + } + time.Sleep(10 * time.Millisecond) + } +} + +// TestRunnerProcess is invoked as a standalone process by the fake helper. No +// Virtualization.framework, guest assets, signing or graphical setup is used. +func TestRunnerProcess(t *testing.T) { + idx := slices.Index(os.Args, "--") + if idx < 0 { + return + } + if err := runnerFixture(os.Args[idx+1:]); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + os.Exit(0) +} + +func runnerFixture(args []string) error { + if slices.Equal(args, []string{"probe"}) { + _, err := io.WriteString(os.Stdout, `{"runtime":"nivfold","protocol_version":1,"supported":true,"resources":{"minimum_cpu_count":2,"maximum_cpu_count":10,"minimum_memory_mib":4096,"maximum_memory_mib":24576}}`) + return err + } + if len(args) < 3 || args[1] != "--vm-dir" || !filepath.IsAbs(args[2]) { + return fmt.Errorf("invalid runner args %q", args) + } + vm := instance{dir: args[2], name: filepath.Base(args[2])} + switch args[0] { + case "install", "run": + return runnerOwner(vm, args[0], args[3:]) + case "show": + status, err := vm.status() + if err != nil || status.State != "running" { + return errors.Join(err, errors.New("VM not running")) + } + fmt.Println("viewer shown") + return nil + case "stop": + return runnerStop(vm, args[3:]) + default: + return fmt.Errorf("unknown command %q", args[0]) + } +} + +func runnerOwner(vm instance, command string, args []string) error { + lock, err := acquireLock(vm.path(runnerLock), true) + if err != nil || lock == nil { + return errors.Join(err, errors.New("runtime lock unavailable")) + } + defer lock.Close() + defer os.Remove(vm.path(statusFile)) + if _, err := vm.config(); err != nil { + return err + } + var cfg map[string]json.RawMessage + data, err := os.ReadFile(vm.path(configFile)) + if err != nil { + return err + } + if err := json.Unmarshal(data, &cfg); err != nil || cfg["cpu_count"] == nil || cfg["memory_mib"] == nil || cfg["disk_gib"] == nil { + return errors.Join(err, errors.New("config is missing runner fields")) + } + status := runnerStatus{PID: os.Getpid(), State: "starting"} + var cancelSignals chan os.Signal + if command == "install" { + cancelSignals = make(chan os.Signal, 1) + signal.Notify(cancelSignals, syscall.SIGTERM) + defer signal.Stop(cancelSignals) + status.State = "installing" + } else if os.Getenv("APPLE_VZ_TEST_RUN_WAIT") != "1" { + status.State = "running" + fmt.Println("READY") + } + if err := atomicfile.WriteJSON(vm.path(statusFile), status, 0o600); err != nil { + return err + } + if command == "install" { + return runnerInstall(vm, args, cancelSignals) + } + return waitMarker(vm.path("stop.request"), true) +} + +func runnerInstall(vm instance, args []string, cancelSignals <-chan os.Signal) error { + if len(args) != 2 || args[0] != "--ipsw" || !filepath.IsAbs(args[1]) || filepath.Ext(args[1]) != ".ipsw" { + return fmt.Errorf("invalid install args %q", args) + } + if os.Getenv("APPLE_VZ_TEST_INSTALL_WAIT") == "1" { + select { + case <-cancelSignals: + if os.Getenv("APPLE_VZ_TEST_COMMIT_ON_CANCEL") != "1" { + // Match Nivfold's cooperative SIGTERM exit status. + if err := os.Remove(vm.path(statusFile)); err != nil { + return err + } + os.Exit(143) + } + case <-time.After(5 * time.Second): + return errors.New("test installer timed out waiting for cancellation") + } + } + if err := os.Mkdir(vm.path(machineDirectory), 0o700); err != nil { + return err + } + for _, name := range []string{"hardware-model", "machine-id", "auxiliary-storage", "disk.img"} { + if err := os.WriteFile(vm.path(machineDirectory, name), []byte("mock artifact"), 0o600); err != nil { + return err + } + } + fmt.Printf("installed from %s\n", filepath.Base(args[1])) + return nil +} + +func runnerStop(vm instance, args []string) error { + status, err := vm.status() + if err != nil || status.State == "stopped" { + return err + } + if len(args) == 3 && args[0] == "--force" && args[1] == "--expect-pid" && args[2] == fmt.Sprint(status.PID) { + fmt.Println("stopped expected owner") + } else if !(len(args) == 0 || slices.Equal(args, []string{"--force"})) { + return fmt.Errorf("invalid stop args %q for owner %d", args, status.PID) + } + if err := os.WriteFile(vm.path("stop.request"), []byte("stop"), 0o600); err != nil { + return err + } + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + current, err := vm.status() + if err != nil || current.State == "stopped" { + return err + } + time.Sleep(10 * time.Millisecond) + } + return errors.New("VM did not release its runtime lock") +} + +func waitMarker(path string, present bool) error { + deadline := time.Now().Add(10 * time.Second) + for time.Now().Before(deadline) { + _, err := os.Stat(path) + if present && err == nil { + return os.Remove(path) + } + if !present && errors.Is(err, os.ErrNotExist) { + return nil + } + time.Sleep(10 * time.Millisecond) + } + return fmt.Errorf("timed out waiting for %s", path) +} diff --git a/internal/macos/applevz/storage.go b/internal/macos/applevz/storage.go new file mode 100644 index 0000000..37a5c34 --- /dev/null +++ b/internal/macos/applevz/storage.go @@ -0,0 +1,318 @@ +package applevz + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "strings" + + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/filelock" +) + +const ( + configFile = "config.json" + runnerLock = ".applevz.lock" + statusFile = ".applevz-status.json" + machineDirectory = "machine" + logFile = "runner.log" +) + +type instance struct{ dir, name string } + +type runnerStatus struct { + State string `json:"state"` + PID int `json:"pid"` +} + +func (vm instance) path(parts ...string) string { + return filepath.Join(append([]string{vm.dir}, parts...)...) +} + +func (d *Driver) root(create bool) (string, error) { + if d.opts.DataRoot == nil { + return "", errors.New("Apple virtualization has no configured data folder") + } + data := d.opts.DataRoot() + if !filepath.IsAbs(data) { + return "", errors.New("Apple virtualization needs an absolute data folder") + } + if create { + if err := os.MkdirAll(data, 0o700); err != nil { + return "", err + } + } + data, err := filepath.EvalSymlinks(data) + if err != nil { + return "", err + } + root := filepath.Join(data, VMRoot) + if create { + if err := os.Mkdir(root, 0o700); err != nil && !errors.Is(err, os.ErrExist) { + return "", err + } + } + return root, requireDirectory(root) +} + +func requireDirectory(path string) error { + info, err := os.Lstat(path) + if err != nil { + return err + } + if !info.IsDir() { + return fmt.Errorf("not a plain directory: %s", path) + } + return nil +} + +// Operations addressing an existing instance match names independently of the +// filesystem's case sensitivity. New names may not collide under that rule. +func namedInstance(root, name string) (instance, error) { + if !validName(name) { + return instance{}, fmt.Errorf("invalid Apple VM name %q", name) + } + entries, err := os.ReadDir(root) + if err != nil { + return instance{}, err + } + var actual string + for _, entry := range entries { + if strings.EqualFold(entry.Name(), name) { + if actual != "" { + return instance{}, fmt.Errorf("multiple directory entries match VM %q", name) + } + actual = entry.Name() + } + } + if actual == "" { + return instance{}, fmt.Errorf("Apple VM %q: %w", name, os.ErrNotExist) + } + return instance{dir: filepath.Join(root, actual), name: actual}, nil +} + +func (d *Driver) find(name string) (instance, error) { + root, err := d.root(false) + if err != nil { + return instance{}, err + } + return ownedInstance(root, name) +} + +func ownedInstance(root, name string) (instance, error) { + vm, err := namedInstance(root, name) + if err != nil { + return instance{}, err + } + if err := requireDirectory(vm.dir); err != nil { + return instance{}, err + } + if !vm.owned() { + return instance{}, fmt.Errorf("Apple VM %q is not registered: %w", name, os.ErrNotExist) + } + return vm, nil +} + +func (vm instance) owned() bool { + b, err := readSmallFile(vm.path(driver.OwnerMarkerFile)) + return err == nil && strings.TrimSpace(string(b)) == ID +} + +func (vm instance) config() (vmConfig, error) { + var cfg vmConfig + b, err := readSmallFile(vm.path(configFile)) + if err != nil { + return cfg, err + } + if err := json.Unmarshal(b, &cfg); err != nil { + return cfg, fmt.Errorf("read VM configuration: %w", err) + } + if cfg.Name != vm.name || cfg.CPUs < minCPUs || cfg.CPUs > maxCPUs || cfg.MemoryMiB < minMemoryMiB || + cfg.MemoryMiB > maxMemoryMiB || cfg.DiskGiB < minDiskGiB || cfg.DiskGiB > maxDiskGiB { + return cfg, errors.New("invalid VM configuration") + } + return cfg, nil +} + +func (vm instance) installed() error { + if err := requireDirectory(vm.path(machineDirectory)); err != nil { + return fmt.Errorf("Apple VM is not installed: %w", err) + } + for _, artifact := range []string{"hardware-model", "machine-id", "auxiliary-storage", "disk.img"} { + info, err := os.Lstat(vm.path(machineDirectory, artifact)) + if err != nil { + return fmt.Errorf("missing VM installation artifact %s: %w", artifact, err) + } + if !info.Mode().IsRegular() || info.Size() == 0 || sharedFile(info) { + return fmt.Errorf("invalid VM installation artifact %s", artifact) + } + } + return nil +} + +func (vm instance) status() (runnerStatus, error) { + path := vm.path(runnerLock) + file, err := openRegular(path, os.O_RDONLY) + if errors.Is(err, os.ErrNotExist) { + return runnerStatus{State: "stopped"}, nil + } + if err != nil { + return runnerStatus{}, err + } + defer file.Close() + idle, err := tryStatusLock(file) + if err != nil { + return runnerStatus{}, err + } + if err := validateOpened(path, file); err != nil { + return runnerStatus{}, err + } + if idle { + return runnerStatus{State: "stopped"}, nil + } + return vm.activeStatus() +} + +func (vm instance) activeStatus() (runnerStatus, error) { + b, err := readSmallFile(vm.path(statusFile)) + if errors.Is(err, os.ErrNotExist) { + return runnerStatus{State: "starting"}, nil + } + if err != nil { + return runnerStatus{}, err + } + var status runnerStatus + if err := json.Unmarshal(b, &status); err != nil { + return runnerStatus{}, fmt.Errorf("read runner status: %w", err) + } + switch status.State { + case "installing", "starting", "running", "stopping": + if status.PID > 0 { + return status, nil + } + } + return runnerStatus{}, errors.New("invalid runner status") +} + +func lockOperations(root, name string) (*os.File, error) { + if !validName(name) { + return nil, fmt.Errorf("invalid Apple VM name %q", name) + } + dir := filepath.Join(root, ".operations") + if err := os.Mkdir(dir, 0o700); err != nil && !errors.Is(err, os.ErrExist) { + return nil, err + } + if err := requireDirectory(dir); err != nil { + return nil, err + } + lock, err := acquireLock(filepath.Join(dir, strings.ToLower(name)), true) + if err == nil && lock == nil { + err = fmt.Errorf("another operation is in progress for VM %q", name) + } + return lock, err +} + +func acquireLock(path string, create bool) (*os.File, error) { + flags := os.O_RDWR + if create { + flags |= os.O_CREATE + } + file, err := openRegular(path, flags) + if err != nil { + return nil, err + } + locked, err := filelock.TryLock(file) + if err != nil { + return nil, errors.Join(err, file.Close()) + } + if err := validateOpened(path, file); err != nil { + return nil, errors.Join(err, file.Close()) + } + if !locked { + return nil, file.Close() + } + return file, nil +} + +func openRegular(path string, flags int) (*os.File, error) { + if info, err := os.Lstat(path); err == nil && (!info.Mode().IsRegular() || sharedFile(info)) { + return nil, fmt.Errorf("not a plain file: %s", path) + } else if err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, err + } + f, err := openFile(path, flags) + if err != nil { + return nil, err + } + if err := validateOpened(path, f); err != nil { + return nil, errors.Join(err, f.Close()) + } + return f, nil +} + +func openFile(path string, flags int) (*os.File, error) { + if runtime.GOOS != "windows" || filepath.Base(path) != runnerLock { + return os.OpenFile(path, flags|safeOpenFlags, 0o600) + } + // Windows requires delete sharing to unlink the held runtime lock during + // Delete. Root.OpenFile enables it without releasing the owner's lock. + root, err := os.OpenRoot(filepath.Dir(path)) + if err != nil { + return nil, err + } + defer root.Close() + return root.OpenFile(runnerLock, flags, 0o600) +} + +func validateOpened(path string, f *os.File) error { + fromFile, err := f.Stat() + if err != nil { + return err + } + fromPath, err := os.Lstat(path) + if err != nil { + return err + } + if !fromPath.Mode().IsRegular() || sharedFile(fromPath) || !os.SameFile(fromFile, fromPath) { + return fmt.Errorf("not a plain file: %s", path) + } + return nil +} + +func readSmallFile(path string) ([]byte, error) { + f, err := openRegular(path, os.O_RDONLY) + if err != nil { + return nil, err + } + defer f.Close() + const limit = 64 << 10 + b, err := io.ReadAll(io.LimitReader(f, limit+1)) + if len(b) > limit { + return nil, fmt.Errorf("metadata file exceeds %d bytes: %s", limit, filepath.Base(path)) + } + return b, err +} + +func (vm instance) logTail(limit int64) (string, error) { + f, err := openRegular(vm.path(logFile), os.O_RDONLY) + if errors.Is(err, os.ErrNotExist) { + return "", nil + } + if err != nil { + return "", err + } + defer f.Close() + info, err := f.Stat() + if err != nil { + return "", err + } + if _, err := f.Seek(max(info.Size()-limit, 0), io.SeekStart); err != nil { + return "", err + } + data, err := io.ReadAll(io.LimitReader(f, limit)) + return string(data), err +} diff --git a/internal/macos/applevz/storage_test.go b/internal/macos/applevz/storage_test.go new file mode 100644 index 0000000..66d6f45 --- /dev/null +++ b/internal/macos/applevz/storage_test.go @@ -0,0 +1,110 @@ +package applevz + +import ( + "errors" + "os" + "path/filepath" + "slices" + "testing" + + "github.com/Nwflower/reims-go/internal/atomicfile" + "github.com/Nwflower/reims-go/internal/driver" +) + +func TestCreateValidationRejectsExternalAndUnsafeInputs(t *testing.T) { + d := New(Options{}) + for _, tc := range []struct { + name, field string + req driver.CreateRequest + }{ + {"traversal", "name", driver.CreateRequest{Name: "../outside"}}, + {"custom directory", "dir", driver.CreateRequest{Name: "tahoe", Dir: t.TempDir()}}, + {"remote source", "restore_path", driver.CreateRequest{Name: "tahoe", Options: map[string]any{"restore_path": "https://example.invalid/image.ipsw"}}}, + {"file URI", "restore_path", driver.CreateRequest{Name: "tahoe", Options: map[string]any{"restore_path": "file:///tmp/image.ipsw"}}}, + {"small memory", "memory", driver.CreateRequest{Name: "tahoe", Options: map[string]any{"memory": "2G"}}}, + {"fractional CPU", "cpus", driver.CreateRequest{Name: "tahoe", Options: map[string]any{"cpus": 2.5}}}, + {"unknown option", "graphics", driver.CreateRequest{Name: "tahoe", Options: map[string]any{"graphics": "wgpu"}}}, + } { + t.Run(tc.name, func(t *testing.T) { + issues := d.ValidateCreate(t.Context(), tc.req) + if !slices.ContainsFunc(issues, func(issue driver.ValidationIssue) bool { return issue.Field == tc.field }) { + t.Fatalf("got %v, expected field %q", issues, tc.field) + } + }) + } +} + +func TestInventoryIgnoresUnknownAndDamagedInstances(t *testing.T) { + data := t.TempDir() + d := New(Options{DataRoot: func() string { return data }}) + root, err := d.root(true) + if err != nil { + t.Fatal(err) + } + vm, err := createInstance(root, defaultConfig("unfinished")) + if err != nil { + t.Fatal(err) + } + if err := atomicfile.WriteJSON(vm.path(statusFile), runnerStatus{State: "running", PID: os.Getpid()}, 0o600); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(filepath.Join(root, "unknown"), 0o700); err != nil { + t.Fatal(err) + } + linkErr := os.Symlink(vm.dir, filepath.Join(root, "link")) + if err := os.WriteFile(vm.path(configFile), []byte("not JSON"), 0o600); err != nil { + t.Fatal(err) + } + list, err := d.List(t.Context()) + if err != nil || len(list) != 1 || list[0].State != "broken" || list[0].Name != vm.name || list[0].PID != nil { + t.Fatalf("inventory = %v, %v", list, err) + } + t.Run("linked directory", func(t *testing.T) { + if linkErr != nil { + t.Skipf("cannot create a symlink: %v", linkErr) + } + if err := d.Delete(t.Context(), "link", false, nil, nil); err == nil { + t.Fatal("deleted through a linked directory") + } + }) + t.Run("held runner lock", func(t *testing.T) { + lock, err := acquireLock(vm.path(runnerLock), true) + if err != nil || lock == nil { + t.Fatalf("acquire test runner lock: %v", err) + } + // This cleanup runs before the parent deletes the instance or its TempDir. + t.Cleanup(func() { + if err := lock.Close(); err != nil { + t.Error(err) + } + }) + if err := d.Delete(t.Context(), vm.name, false, nil, nil); err == nil { + t.Fatal("deleted an instance whose runner lock was held") + } + }) + if err := d.Delete(t.Context(), vm.name, false, nil, nil); err != nil { + t.Fatalf("delete broken VM: %v", err) + } + if _, err := os.Stat(vm.dir); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("broken VM not cleaned up: %v", err) + } +} + +func TestInventoryIgnoresStatusWithoutRunnerLock(t *testing.T) { + data := t.TempDir() + d := New(Options{DataRoot: func() string { return data }}) + root, err := d.root(true) + if err != nil { + t.Fatal(err) + } + vm, err := createInstance(root, defaultConfig("interrupted")) + if err != nil { + t.Fatal(err) + } + if err := atomicfile.WriteJSON(vm.path(statusFile), runnerStatus{State: "running", PID: os.Getpid()}, 0o600); err != nil { + t.Fatal(err) + } + if info, err := d.Show(t.Context(), vm.name); err != nil || info.State != "broken" { + t.Fatalf("stale process record mattered: %+v, %v", info, err) + } +} diff --git a/internal/macos/guest/apple_vz.go b/internal/macos/guest/apple_vz.go new file mode 100644 index 0000000..a149588 --- /dev/null +++ b/internal/macos/guest/apple_vz.go @@ -0,0 +1,54 @@ +package guest + +import ( + "context" + "path/filepath" + "runtime" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/macos/applevz" + "github.com/Nwflower/reims-go/internal/plugin" +) + +// UsesAppleVirtualization identifies hosts for the native Apple Silicon driver. +func UsesAppleVirtualization() bool { return runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" } + +// AppleDriverID identifies the native driver in CLI creation requests. +func AppleDriverID() string { return applevz.ID } + +// AppleVMRoot is the directory used by the native driver's VM inventory. +func AppleVMRoot(dataRoot string) string { return filepath.Join(dataRoot, applevz.VMRoot) } + +// ProbeAppleVirtualization checks the installed native helper without opening a VM. +func ProbeAppleVirtualization(ctx context.Context) error { + return applevz.New(applevz.Options{}).Probe(ctx) +} + +func appleDefinition(ver string, getConfig func() config.Config, desired bool) plugin.PluginDef { + drv := applevz.New(applevz.Options{DataRoot: func() string { + if getConfig == nil { + return "" + } + return getConfig().DataRoot + }}) + return plugin.PluginDef{ + Manifest: plugin.Manifest{ + Schema: 1, ID: applevz.ID, Version: ver, Name: drv.DisplayName(), + Description: plugin.LocalizedText{ + ZhCN: "在 Apple 芯片 Mac 上运行 ARM64 macOS 虚拟机", + EnUS: "Runs ARM64 macOS VMs on Apple silicon", + }, + Publisher: "Reims-Go", License: "Apache-2.0", DefaultEnabled: true, + Permissions: []string{"driver:vm", "vm:control"}, + Contributes: plugin.Contributes{GuestDrivers: []plugin.GuestDriverContribution{{ + ID: drv.ID(), Name: drv.DisplayName(), RuntimeKind: drv.RuntimeKind(), + Capabilities: drv.Capabilities(), VMRoots: []string{applevz.VMRoot}, + }}}, + }, + Source: plugin.SourceBuiltin, Trust: plugin.TrustOfficial, Desired: desired, + Activate: func(_ context.Context, scope *plugin.Scope) error { + scope.Registry().RegisterGuestDriver(scope, drv.ID(), drv) + return nil + }, + } +} diff --git a/internal/macos/guest/register.go b/internal/macos/guest/register.go index adfdee7..fe7c7a0 100644 --- a/internal/macos/guest/register.go +++ b/internal/macos/guest/register.go @@ -4,18 +4,22 @@ import ( "strings" "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/macos/applevz" "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/internal/plugin/builtin" "github.com/Nwflower/reims-go/internal/version" ) -// VMInventory keeps registered VMs discoverable while macOS support is disabled. -func VMInventory() driver.VMInventory { - return driver.VMInventory{DriverID: IDDriver, List: reims.ListRegisteredVMs} +// VMInventories keep registered VMs discoverable when their driver is unavailable. +func VMInventories() []driver.VMInventory { + return []driver.VMInventory{ + {DriverID: IDDriver, List: reims.ListRegisteredVMs}, + {DriverID: applevz.ID, List: applevz.Inventory}, + } } -// Register adds the optional built-in macOS plugins (guest driver + image source) to reg. +// Register adds the built-in Reims vGPU guest driver and image source. func Register(reg *plugin.Registry, cb builtin.HostCallbacks, desiredFn func(string, bool) bool) error { if desiredFn == nil { desiredFn = func(_ string, def bool) bool { return def } @@ -26,3 +30,16 @@ func Register(reg *plugin.Registry, cb builtin.HostCallbacks, desiredFn func(str } return reg.Register(ImagesDefinition(ver, desiredFn(IDImages, true))) } + +// RegisterForHost selects the local backend without losing the other backend's +// registered VMs: the router's read-only inventories still expose those entries. +func RegisterForHost(reg *plugin.Registry, cb builtin.HostCallbacks, desiredFn func(string, bool) bool) error { + if !UsesAppleVirtualization() { + return Register(reg, cb, desiredFn) + } + ver := strings.TrimPrefix(strings.TrimSpace(version.Version), "v") + if err := reg.Register(appleDefinition(ver, cb.GetConfig, desiredFn == nil || desiredFn(AppleDriverID(), true))); err != nil { + return err + } + return reg.Register(ImagesDefinition(ver, desiredFn == nil || desiredFn(IDImages, true))) +} diff --git a/internal/macos/installer/restore_image.go b/internal/macos/installer/restore_image.go new file mode 100644 index 0000000..3f463e2 --- /dev/null +++ b/internal/macos/installer/restore_image.go @@ -0,0 +1,314 @@ +package installer + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path" + "path/filepath" + "regexp" + "strings" + "time" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/fetch" + "github.com/Nwflower/reims-go/internal/filelock" + "github.com/Nwflower/reims-go/internal/macos/applevz" +) + +// RestoreKind is the installer task/cache kind for Apple Silicon guests. +const RestoreKind = "ipsw" +const maxRestoreBytes int64 = 64 << 30 + +var restoreNamePattern = regexp.MustCompile(`^UniversalMac_([0-9]{1,3}\.[0-9]{1,3}(?:\.[0-9]{1,3})?)_([0-9]{1,4}[A-Z][0-9]{1,8}[a-z]?)_Restore\.ipsw$`) + +// RestoreDir keeps native images separate from reims-ctl installers. +func RestoreDir(cfg *config.Config) string { return filepath.Join(cfg.ImagesDir(), "apple-restore") } + +func LatestRestore(ctx context.Context) (Release, error) { + image, err := applevz.New(applevz.Options{}).LatestRestoreImage(ctx) + if err != nil { + return Release{}, err + } + r := Release{Title: "macOS " + image.Version, Version: image.Version, Build: image.Build, URL: image.URL} + if _, err := restoreFilename(r); err != nil { + return Release{}, err + } + // Metadata only: the CDN may omit Content-Length or decline HEAD. + if meta, err := restoreHeader(ctx, restoreHTTPClient(), r.URL); err == nil { + r.Size = meta.size + } + return r, nil +} + +func restoreImageName(version, build string) string { + return "UniversalMac_" + version + "_" + build + "_Restore.ipsw" +} + +func restoreFilename(r Release) (string, error) { + u, err := url.Parse(r.URL) + name := restoreImageName(r.Version, r.Build) + if err != nil || !appleRestoreURL(u) || !restoreNamePattern.MatchString(name) || path.Base(u.Path) != name { + return "", errors.New("Apple restore catalog returned an invalid image") + } + return name, nil +} + +func appleRestoreURL(u *url.URL) bool { + if u == nil || u.Scheme != "https" || u.User != nil || u.Fragment != "" || + (u.Port() != "" && u.Port() != "443") { + return false + } + return strings.EqualFold(u.Hostname(), "updates.cdn-apple.com") || strings.EqualFold(u.Hostname(), "updates.apple.com") +} + +type RestoreCache struct{ Dir string } + +func (c RestoreCache) List() ([]Cached, error) { + cacheDir, err := c.cacheDir(false) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + entries, err := os.ReadDir(cacheDir) + if err != nil { + return nil, err + } + var out []Cached + for _, e := range entries { + if !e.Type().IsRegular() { + continue + } + name := e.Name() + base, partial := strings.CutSuffix(name, ".part.ipsw") + if partial { + base += ".ipsw" + } + parts := restoreNamePattern.FindStringSubmatch(base) + if parts == nil { + continue + } + info, err := e.Info() + if err != nil || info.Size() <= 0 { + continue + } + item := Cached{Name: name, Kind: RestoreKind, Partial: partial, Title: "macOS " + parts[1], Version: parts[1], Build: parts[2], Bytes: info.Size()} + if !partial { + item.Path = filepath.Join(cacheDir, name) + } + out = append(out, item) + } + return out, nil +} + +func (c RestoreCache) Delete(ctx context.Context, name string) error { + base, partial := strings.CutSuffix(name, ".part.ipsw") + if partial { + base += ".ipsw" + } + if !restoreNamePattern.MatchString(base) { + return errors.New("not a cached restore image name") + } + dir, err := c.cacheDir(false) + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond) + defer cancel() + release, err := lockRestoreCache(ctx, dir) + if err != nil { + return fmt.Errorf("restore image cache is busy: %w", err) + } + defer release() + file := filepath.Join(dir, name) + info, err := os.Lstat(file) + if err != nil { + return err + } + if !info.Mode().IsRegular() { + return errors.New("restore image cache entry is not a regular file") + } + if err := os.Remove(file); err != nil { + return err + } + if partial { + if err := os.Remove(file + ".etag"); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + } + return nil +} + +func (c RestoreCache) Download(ctx context.Context, r Release, onUpdate func(Update)) (*Result, error) { + name, err := restoreFilename(r) + if err != nil { + return nil, err + } + client := restoreHTTPClient() + if meta, err := restoreHeader(ctx, client, r.URL); err == nil { + r.Size, r.Digest = meta.size, meta.digest + } + if r.Size > maxRestoreBytes { + return nil, errors.New("Apple restore image exceeds the download size limit") + } + inspect := applevz.New(applevz.Options{}).InspectRestoreImage + return c.download(ctx, r, name, client, inspect, onUpdate) +} + +func (c RestoreCache) download(ctx context.Context, r Release, name string, client *http.Client, + inspect func(context.Context, string) (applevz.RestoreImage, error), onUpdate func(Update)) (*Result, error) { + dir, err := c.cacheDir(true) + if err != nil { + return nil, err + } + if onUpdate == nil { + onUpdate = func(Update) {} + } + onUpdate(Update{Kind: KindNote, Message: WaitingNote}) + release, err := lockRestoreCache(ctx, dir) + if err != nil { + return nil, err + } + defer release() + onUpdate(Update{Kind: KindStep, Message: "Downloading macOS " + r.Version + " restore image", Percent: -1}) + final := filepath.Join(dir, name) + part := filepath.Join(dir, strings.TrimSuffix(name, ".ipsw")+".part.ipsw") + err = fetch.ResumeValidated(ctx, client, r.URL, final, part, maxRestoreBytes, func(done, total int64) { + onUpdate(Update{Kind: KindProgress, Done: done, Total: total, Percent: float64(done) * 100 / float64(total)}) + }, func(ctx context.Context, file string) error { + onUpdate(Update{Kind: KindStep, Message: "Checking macOS restore image", Percent: -1}) + if err := verifyRestoreFile(ctx, file, r.Size, r.Digest); err != nil { + return err + } + image, err := inspect(ctx, file) + if err != nil { + return err + } + if !restoreNamePattern.MatchString(restoreImageName(image.Version, image.Build)) { + return errors.New("Nivfold returned invalid or incomplete restore image metadata") + } + if image.Version != r.Version || image.Build != r.Build { + return &fetch.InvalidDownloadError{Err: errors.New("downloaded restore image does not match the Apple catalog")} + } + return nil + }) + if err != nil { + return nil, err + } + return &Result{Image: final, Version: r.Version, Build: r.Build}, nil +} + +type restoreHeaders struct { + size int64 + digest string +} + +func restoreHeader(ctx context.Context, client *http.Client, rawURL string) (restoreHeaders, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodHead, rawURL, nil) + if err != nil { + return restoreHeaders{}, err + } + resp, err := client.Do(req) + if err != nil { + return restoreHeaders{}, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return restoreHeaders{}, fmt.Errorf("Apple restore metadata: HTTP %d", resp.StatusCode) + } + meta := restoreHeaders{size: max(0, resp.ContentLength)} + if digest := resp.Header.Get("x-amz-meta-digest-sha256"); digest != "" { + if decoded, err := hex.DecodeString(digest); err == nil && len(decoded) == sha256.Size { + meta.digest = strings.ToLower(digest) + } + } + return meta, nil +} + +func verifyRestoreFile(ctx context.Context, path string, size int64, digest string) error { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + info, err := file.Stat() + if err != nil { + return err + } + if size > 0 && info.Size() != size { + return &fetch.InvalidDownloadError{Err: errors.New("restore image size does not match Apple's download metadata")} + } + if digest == "" { + return nil + } + h := sha256.New() + buf := make([]byte, 1<<20) + for { + if err := ctx.Err(); err != nil { + return err + } + n, err := file.Read(buf) + h.Write(buf[:n]) + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return err + } + } + if hex.EncodeToString(h.Sum(nil)) != digest { + return &fetch.InvalidDownloadError{Err: errors.New("restore image SHA-256 does not match Apple's download metadata")} + } + return nil +} + +func restoreHTTPClient() *http.Client { + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.DisableCompression = true + transport.ResponseHeaderTimeout = 30 * time.Second + return &http.Client{Transport: transport, CheckRedirect: func(req *http.Request, via []*http.Request) error { + if len(via) >= 5 || !appleRestoreURL(req.URL) || path.Base(req.URL.Path) != path.Base(via[0].URL.Path) { + return errors.New("unexpected redirect while downloading Apple restore image") + } + return nil + }} +} + +func (c RestoreCache) cacheDir(create bool) (string, error) { + if !filepath.IsAbs(c.Dir) { + return "", errors.New("restore images need an absolute data directory") + } + if create { + if err := os.MkdirAll(c.Dir, 0o700); err != nil { + return "", err + } + } + info, err := os.Lstat(c.Dir) + if err != nil { + return "", err + } + if !info.IsDir() { + return "", errors.New("restore image cache is not a directory") + } + return c.Dir, nil +} + +func lockRestoreCache(ctx context.Context, dir string) (func(), error) { + lock := filepath.Join(dir, ".restore.lock") + if info, err := os.Lstat(lock); err == nil && !info.Mode().IsRegular() { + return nil, errors.New("restore image cache lock is not a regular file") + } else if err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, err + } + return filelock.Acquire(ctx, lock, 200*time.Millisecond) +} diff --git a/internal/macos/installer/restore_image_test.go b/internal/macos/installer/restore_image_test.go new file mode 100644 index 0000000..151b033 --- /dev/null +++ b/internal/macos/installer/restore_image_test.go @@ -0,0 +1,223 @@ +package installer + +import ( + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/Nwflower/reims-go/internal/macos/applevz" +) + +func TestRestoreCacheDownloadValidatesBeforePublishing(t *testing.T) { + const name = "UniversalMac_27.2.1_26B131_Restore.ipsw" + const body = "local test fixture, not an Apple image" + sum := fmt.Sprintf("%x", sha256.Sum256([]byte(body))) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", fmt.Sprint(len(body))) + w.Header().Set("x-amz-meta-digest-sha256", sum) + w.Header().Set("ETag", `"mock"`) + if r.Method != http.MethodHead { + fmt.Fprint(w, body) + } + })) + defer server.Close() + meta, err := restoreHeader(t.Context(), server.Client(), server.URL) + if err != nil || meta.digest != sum || meta.size != int64(len(body)) { + t.Fatalf("HEAD metadata: %+v, %v", meta, err) + } + cache := RestoreCache{Dir: filepath.Join(t.TempDir(), "restore")} + for _, valid := range []bool{false, true} { + r := Release{Build: "26B131", Version: "27.2.1", URL: server.URL, Size: meta.size, Digest: meta.digest} + if !valid { + r.Digest = fmt.Sprintf("%064d", 0) + } + var inspected bool + _, err := cache.download(t.Context(), r, name, server.Client(), func(_ context.Context, path string) (applevz.RestoreImage, error) { + inspected = true + if filepath.Ext(path) != ".ipsw" { + t.Errorf("staged image must end in .ipsw: %s", path) + } + return applevz.RestoreImage{Version: r.Version, Build: r.Build}, nil + }, nil) + if (err == nil) != valid || inspected != valid { + t.Fatalf("download valid=%t, inspected=%t: %v", valid, inspected, err) + } + list, err := cache.List() + if err != nil || len(list) != map[bool]int{true: 1, false: 0}[valid] { + t.Fatalf("cache valid=%t: %+v %v", valid, list, err) + } + if valid && (list[0].Kind != RestoreKind || list[0].Path != filepath.Join(cache.Dir, name) || list[0].Partial) { + t.Fatalf("cached image: %+v", list[0]) + } + } + if err := cache.Delete(t.Context(), "../"+name); err == nil { + t.Fatal("allowed deletion outside cache") + } + if err := cache.Delete(t.Context(), name); err != nil { + t.Fatal(err) + } + part := filepath.Join(cache.Dir, "UniversalMac_27.2.1_26B131_Restore.part.ipsw") + if err := os.WriteFile(part, []byte("partial"), 0o600); err != nil { + t.Fatal(err) + } + list, err := cache.List() + if err != nil || len(list) != 1 || !list[0].Partial || list[0].Path != "" || list[0].Version != "27.2.1" { + t.Fatalf("unsafe partial exposed: %+v %v", list, err) + } +} + +func TestRestoreCacheRetriesInspectionAgainstCompletePart(t *testing.T) { + const name = "UniversalMac_27.2.1_26B131_Restore.ipsw" + const body = "local fixture, not an Apple image" + const tag = `"stable"` + exact := fmt.Sprintf("bytes=%d-", len(body)) + for _, tc := range []struct { + name string + inspectErr error + image applevz.RestoreImage + }{ + {name: "nested timeout", inspectErr: fmt.Errorf("Nivfold inspect: %w", context.DeadlineExceeded)}, + {name: "process error", inspectErr: errors.New("Nivfold inspect: exit status 1")}, + {name: "decode error", inspectErr: fmt.Errorf("decode Nivfold restore image metadata: %w", &json.SyntaxError{})}, + {name: "incompatible response", inspectErr: errors.New("Nivfold inspect: no supported configuration on this host")}, + {name: "incomplete metadata", image: applevz.RestoreImage{Version: "27.2.1"}}, + {name: "malformed metadata", image: applevz.RestoreImage{Version: "unknown", Build: "26B131"}}, + } { + t.Run(tc.name, func(t *testing.T) { + var requests []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("ETag", tag) + requested := r.Header.Get("Range") + requests = append(requests, requested) + if requested != "" { + if r.Header.Get("If-Range") != tag { + t.Errorf("If-Range = %q, want %q", r.Header.Get("If-Range"), tag) + } + w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", len(body))) + w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) + return + } + fmt.Fprint(w, body) + })) + defer server.Close() + cache := RestoreCache{Dir: filepath.Join(t.TempDir(), "restore")} + r := Release{Build: "26B131", Version: "27.2.1", URL: server.URL, Size: int64(len(body)), Digest: fmt.Sprintf("%x", sha256.Sum256([]byte(body)))} + part := filepath.Join(cache.Dir, strings.TrimSuffix(name, ".ipsw")+".part.ipsw") + final := filepath.Join(cache.Dir, name) + result, err := cache.download(t.Context(), r, name, server.Client(), func(context.Context, string) (applevz.RestoreImage, error) { + return tc.image, tc.inspectErr + }, nil) + if result != nil || err == nil || tc.inspectErr != nil && !errors.Is(err, tc.inspectErr) { + t.Fatalf("failed inspect result = %+v, error = %v (wanted failure %v)", result, err, tc.inspectErr) + } + for file, want := range map[string]string{part: body, part + ".etag": tag} { + if got, err := os.ReadFile(file); err != nil || string(got) != want { + t.Fatalf("resumable file %s = %q, %v; want %q", file, got, err, want) + } + } + if _, err := os.Stat(final); !os.IsNotExist(err) { + t.Fatalf("published after failed inspection: %v", err) + } + inspected := false + result, err = cache.download(t.Context(), r, name, server.Client(), func(_ context.Context, path string) (applevz.RestoreImage, error) { + inspected = true + if path != part { + t.Errorf("inspection path = %q, want %q", path, part) + } + return applevz.RestoreImage{Version: r.Version, Build: r.Build}, nil + }, nil) + if err != nil || result == nil || result.Image != final || !inspected { + t.Fatalf("retry result = %+v, inspected = %t, error = %v", result, inspected, err) + } + if want := []string{"", exact}; !slices.Equal(requests, want) { + t.Fatalf("requests = %q, want %q", requests, want) + } + if got, err := os.ReadFile(final); err != nil || string(got) != body { + t.Fatalf("final = %q, %v", got, err) + } + }) + } +} + +func TestRestoreCacheDiscardsConfirmedBadCompletePart(t *testing.T) { + const name = "UniversalMac_27.2.1_26B131_Restore.ipsw" + const body = "local fixture, not an Apple image" + const tag = `"stable"` + goodDigest := fmt.Sprintf("%x", sha256.Sum256([]byte(body))) + for _, tc := range []struct { + name, digest string + size int64 + image applevz.RestoreImage + wantInspected bool + }{ + {"size", goodDigest, int64(len(body) + 1), applevz.RestoreImage{}, false}, + {"digest", strings.Repeat("0", 64), int64(len(body)), applevz.RestoreImage{}, false}, + {"version", goodDigest, int64(len(body)), applevz.RestoreImage{Version: "27.2.2", Build: "26B131"}, true}, + {"build", goodDigest, int64(len(body)), applevz.RestoreImage{Version: "27.2.1", Build: "26B132"}, true}, + } { + t.Run(tc.name, func(t *testing.T) { + var requests []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests = append(requests, r.Header.Get("Range")) + w.Header().Set("ETag", tag) + w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", len(body))) + w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) + })) + defer server.Close() + cache := RestoreCache{Dir: t.TempDir()} + part := filepath.Join(cache.Dir, strings.TrimSuffix(name, ".ipsw")+".part.ipsw") + for file, data := range map[string]string{part: body, part + ".etag": tag} { + if err := os.WriteFile(file, []byte(data), 0o600); err != nil { + t.Fatal(err) + } + } + r := Release{Build: "26B131", Version: "27.2.1", URL: server.URL, Size: tc.size, Digest: tc.digest} + inspected := false + result, err := cache.download(t.Context(), r, name, server.Client(), func(context.Context, string) (applevz.RestoreImage, error) { + inspected = true + return tc.image, nil + }, nil) + if result != nil || err == nil || inspected != tc.wantInspected { + t.Fatalf("result = %+v, inspected = %t, error = %v", result, inspected, err) + } + if want := []string{fmt.Sprintf("bytes=%d-", len(body))}; !slices.Equal(requests, want) { + t.Fatalf("requests = %q, want %q", requests, want) + } + for _, file := range []string{part, part + ".etag", filepath.Join(cache.Dir, name)} { + if _, err := os.Stat(file); !os.IsNotExist(err) { + t.Fatalf("invalid download left %s: %v", file, err) + } + } + }) + } +} + +func TestRestoreCatalogRejectsUntrustedURLs(t *testing.T) { + const name = "UniversalMac_27.2.1_26B131_Restore.ipsw" + for _, tc := range []struct { + base string + valid bool + }{ + {"https://updates.cdn-apple.com/catalog/", true}, {"https://updates.apple.com/", true}, + {"http://updates.apple.com/", false}, {"https://updates.apple.com.evil.example/", false}, + {"https://other.example@updates.apple.com/", false}, {"https://updates.apple.com:9443/", false}, + } { + r := Release{Version: "27.2.1", Build: "26B131", URL: tc.base + name} + if _, err := restoreFilename(r); (err == nil) != tc.valid { + t.Errorf("catalog source %s: %v", tc.base, err) + } + r.Build = "26B132" + if _, err := restoreFilename(r); err == nil { + t.Fatalf("catalog source accepted a mismatching build: %+v", r) + } + } +} diff --git a/internal/plugin/builtin/bootstrap.go b/internal/plugin/builtin/bootstrap.go index a716de9..54e48fd 100644 --- a/internal/plugin/builtin/bootstrap.go +++ b/internal/plugin/builtin/bootstrap.go @@ -21,7 +21,7 @@ type KernelBootstrapOptions struct { HostHandlers func(pluginID string) map[string]plugin.RPCRequestHandler OnSettingsChanged func(pluginID, vmName string) OnSidecarStopped func(pluginID string) - VMInventory driver.VMInventory + VMInventories []driver.VMInventory Callbacks HostCallbacks RegisterGuest func(reg *plugin.Registry, cb HostCallbacks, desired func(id string, defaultEnabled bool) bool) error // StrictRegister causes builtin/guest registration errors to abort bootstrap @@ -66,7 +66,7 @@ func BootstrapKernel(opts KernelBootstrapOptions) (*plugin.Manager, *driver.Rout root := opts.DataRoot dataRootFn = func() string { return root } } - router := driver.NewRouter(mgr.Registry(), dataRootFn, opts.VMInventory) + router := driver.NewRouter(mgr.Registry(), dataRootFn, opts.VMInventories...) mgr.Registry().SetInUseChecker(router.PluginInUseChecker()) mgr.Registry().SetBusyChecker(router.PluginBusyChecker()) diff --git a/internal/plugin/icon_test.go b/internal/plugin/icon_test.go index 6cf64e7..70698b6 100644 --- a/internal/plugin/icon_test.go +++ b/internal/plugin/icon_test.go @@ -50,6 +50,26 @@ func TestResolvePluginIconFromPackageDir(t *testing.T) { if !strings.HasPrefix(got.SVG, "` + got := ResolvePluginIcon(&PluginIcon{Tone: "sky", SVG: svg}, "", true) + if got == nil || !strings.Contains(got.SVG, `stroke="currentColor"`) { + t.Fatalf("unexpected resolved builtin icon: %+v", got) + } + assertPluginIconNamespace(t, got.SVG) +} + +func assertPluginIconNamespace(t *testing.T, svg string) { + t.Helper() + root, _, _ := strings.Cut(svg, ">") + if strings.Count(root, `xmlns="`) != 1 || !strings.Contains(root, `xmlns="http://www.w3.org/2000/svg"`) { + t.Fatalf("standalone SVG must declare the root namespace exactly once: %s", root) + } } func TestScanBlocksOversizedAndMalformedIconSVG(t *testing.T) { diff --git a/internal/plugin/types.go b/internal/plugin/types.go index c66d978..2ad3a1a 100644 --- a/internal/plugin/types.go +++ b/internal/plugin/types.go @@ -689,7 +689,8 @@ type SettingsSchema struct { // SettingProperty describes one configurable field. type SettingProperty struct { - Type string `json:"type"` // "boolean" | "string" | "number" | "integer" + Type string `json:"type"` // "boolean" | "string" | "number" | "integer" + FilePattern string `json:"x-filePattern,omitempty"` // native picker for built-in create forms only Title LocalizedText `json:"title"` Description LocalizedText `json:"description,omitempty"` Default any `json:"default,omitempty"` diff --git a/internal/plugin/uiassets/assets.go b/internal/plugin/uiassets/assets.go index 0d837c5..8e7cf22 100644 --- a/internal/plugin/uiassets/assets.go +++ b/internal/plugin/uiassets/assets.go @@ -158,6 +158,7 @@ func SanitizeSVG(raw []byte) []byte { var out bytes.Buffer enc := xml.NewEncoder(&out) skipDepth := 0 + var namespaces []string for { tok, err := dec.Token() if err == io.EOF { @@ -175,7 +176,16 @@ func SanitizeSVG(raw []byte) []byte { continue } filtered := make([]xml.Attr, 0, len(t.Attr)) + // The decoder resolves namespace URIs and the encoder emits their + // declarations. Forwarding the original xmlns would duplicate it. + if n := len(namespaces); n > 0 && namespaces[n-1] != "" && t.Name.Space == "" { + filtered = append(filtered, xml.Attr{Name: xml.Name{Local: "xmlns"}}) + } + namespaces = append(namespaces, t.Name.Space) for _, attr := range t.Attr { + if attr.Name.Space == "xmlns" || (attr.Name.Space == "" && attr.Name.Local == "xmlns") { + continue + } name := strings.ToLower(attr.Name.Local) if strings.HasPrefix(name, "on") { continue @@ -197,6 +207,7 @@ func SanitizeSVG(raw []byte) []byte { skipDepth-- continue } + namespaces = namespaces[:len(namespaces)-1] if err := enc.EncodeToken(t); err != nil { return nil } diff --git a/internal/plugin/uiassets/assets_test.go b/internal/plugin/uiassets/assets_test.go new file mode 100644 index 0000000..389b67d --- /dev/null +++ b/internal/plugin/uiassets/assets_test.go @@ -0,0 +1,61 @@ +package uiassets + +import ( + "bytes" + "encoding/xml" + "io" + "testing" +) + +func TestSanitizeSVGPreservesNamespacesWithoutDuplicateDeclarations(t *testing.T) { + const svg = "http://www.w3.org/2000/svg" + const xlink = "http://www.w3.org/1999/xlink" + raw := []byte(`` + + `` + + ``) + cleaned := SanitizeSVG(raw) + dec := xml.NewDecoder(bytes.NewReader(cleaned)) + want := []xml.Name{ + {Space: svg, Local: "svg"}, + {Space: svg, Local: "use"}, + {Space: svg, Local: "use"}, + {Space: svg, Local: "metadata"}, + {Local: "note"}, + {Local: "entry"}, + {Space: svg, Local: "g"}, + } + i := 0 + for { + tok, err := dec.Token() + if err == io.EOF { + break + } + if err != nil { + t.Fatalf("invalid sanitized SVG: %v\n%s", err, cleaned) + } + start, ok := tok.(xml.StartElement) + if !ok { + continue + } + if i >= len(want) || start.Name != want[i] { + t.Fatalf("unexpected element %d: %+v\n%s", i, start.Name, cleaned) + } + seen := map[xml.Name]bool{} + for _, attr := range start.Attr { + if seen[attr.Name] { + t.Fatalf("duplicate %s attribute on <%s>\n%s", attr.Name.Local, start.Name.Local, cleaned) + } + seen[attr.Name] = true + if attr.Name.Local == "onload" || (attr.Name.Local == "href" && (i != 1 || attr.Name.Space != xlink || attr.Value != "#shape")) { + t.Fatalf("unexpected attribute on <%s>: %+v", start.Name.Local, attr) + } + } + if i == 1 && !seen[xml.Name{Space: xlink, Local: "href"}] { + t.Fatal("lost local namespaced reference") + } + i++ + } + if i != len(want) { + t.Fatalf("found %d elements, want %d: %s", i, len(want), cleaned) + } +} diff --git a/internal/tray/tray_other.go b/internal/tray/tray_other.go index e852710..b24b4cf 100644 --- a/internal/tray/tray_other.go +++ b/internal/tray/tray_other.go @@ -5,8 +5,9 @@ package tray // Manager is a no-op stub on non-Windows platforms. type Manager struct{} +// Start returns no manager on hosts without a system tray implementation. func Start(_ []byte, _ string, _ Callbacks) (*Manager, error) { - return &Manager{}, nil + return nil, nil } func (m *Manager) UpdateTooltip(_ string) {} diff --git a/link_darwin.go b/link_darwin.go new file mode 100644 index 0000000..be9751c --- /dev/null +++ b/link_darwin.go @@ -0,0 +1,9 @@ +//go:build darwin && cgo + +package main + +// Wails' macOS file dialogs use UTType. Link the framework explicitly while +// the pinned Wails version does not include it in its cgo linker flags. + +// #cgo LDFLAGS: -framework UniformTypeIdentifiers +import "C" diff --git a/locales/en-US/core.json b/locales/en-US/core.json index eb8ce95..5fa1047 100644 --- a/locales/en-US/core.json +++ b/locales/en-US/core.json @@ -35,6 +35,24 @@ "menuVM": "VM", "menuView": "View", "menuHelp": "Help", + "menuMacEdit": "Edit", + "menuMacWindow": "Window", + "menuMacHide": "Hide Reims-Go", + "menuMacHideOthers": "Hide Others", + "menuMacShowAll": "Show All", + "menuMacQuit": "Quit Reims-Go", + "menuMacUndo": "Undo", + "menuMacRedo": "Redo", + "menuMacCut": "Cut", + "menuMacPaste": "Paste", + "menuMacPasteMatchStyle": "Paste and Match Style", + "menuMacDelete": "Delete", + "menuMacSelectAll": "Select All", + "menuMacSpeech": "Speech", + "menuMacStartSpeaking": "Start Speaking", + "menuMacStopSpeaking": "Stop Speaking", + "menuMacZoom": "Zoom", + "menuMacFullScreen": "Enter Full Screen", "newVMEllipsis": "New Virtual Machine…", "deleteEllipsis": "Delete…", "sidebarLabel": "Sidebar", @@ -69,7 +87,7 @@ "taskAppUpdate": "Downloading Reims-Go {v}", "taskPluginDownload": "Downloading {name}", "closeDownloadsTitle": "Quit Reims-Go?", - "closeDownloadsDesc": "Downloads are still running. Quitting stops them.", + "closeDownloadsDesc": "Quitting stops any downloads or macOS installations in progress.", "closeDownloadsConfirm": "Quit", "settingsAbout": "About", "themeLight": "Light", @@ -131,6 +149,7 @@ "taskDownload": "Downloading macOS {v}", "taskRecoveryDownload": "Downloading online recovery for {name}", "taskCreate": "Creating {name}", + "taskRestoreVM": "Installing macOS on {name}", "tasksRunning": { "message": "{n, plural, one {# task running} other {# tasks running}}", "$comment": "底部后台任务队列汇总" @@ -155,6 +174,8 @@ "toastCopied": "Copied", "failGeneric": "Something went wrong", "noRuntimeAlert": "Import a runtime under Engine first", + "wizardNoDriver": "No eligible guest driver is available", + "wizardDriverListFailed": "Could not load guest drivers", "importRuntime": "Import runtime", "gpuWarnAmdLegacy": "AMD Vega/Polaris on Windows hits known upstream black-screen/device-loss issues ({ref}); prefer another discrete GPU or use VMware SVGA for now", "gpuWarnAmdRdna2": "This AMD GPU hits known Windows device-loss issues upstream ({ref}); update drivers or use VMware SVGA if it freezes", diff --git a/locales/en-US/native.json b/locales/en-US/native.json index db8f51c..3d90999 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -128,7 +128,10 @@ "avail" ] }, + "doctor.ram.total_only": "{total, number, .1} GB total (available memory unknown)", "doctor.disk": "Data Drive Free Space", + "doctor.apple_virtualization.ready": "Ready", + "doctor.apple_virtualization.unavailable": "Unavailable", "doctor.whpx": "Windows Hypervisor Platform (WHPX)", "doctor.whpx.ok": "Ready (WinHvPlatform.dll active, hypervisor running)", "doctor.whpx.no_hv": "WinHvPlatform.dll present, but no hypervisor detected (enable VT-x/AMD-V in BIOS)", @@ -293,6 +296,8 @@ "name" ] }, + "err.restore_catalog_unavailable": "Apple’s restore image catalog is unavailable. Retry or choose a local IPSW.", + "err.restore_catalog_unsupported": "This Nivfold version cannot query restore images. Update Nivfold or choose a local IPSW.", "err.runtime_not_installed": "no active portable runtime found; run `reims-go runtime install ` first", "err.qemu_aslr.cancelled": "Windows authorization was canceled before the QEMU ASLR changes were applied", "err.qemu_aslr.image_policy": "Windows already has a program-wide rule for qemu-system-x86_64.exe, so this runtime’s ASLR rule was skipped. Manage QEMU’s ASLR in Windows Security under Exploit protection → Program settings.", @@ -936,6 +941,12 @@ }, "affinity.summary.all": "all", "cli.usage.header": "reims-go - Portable one-stop reims-vgpu launcher for Windows", + "cli.usage.apple.header": "reims-go - Experimental Apple silicon VM manager", + "cli.usage.apple.doctor": " doctor Check Apple Virtualization support", + "cli.usage.apple.create": " vm create --ipsw Create from a local Apple restore image", + "cli.usage.apple.start": " vm start Start a VM and open its viewer", + "cli.usage.apple.stop": " vm stop [--force] Shut down a VM", + "cli.usage.apple.delete": " vm delete [--keep-files] Remove a stopped VM", "cli.usage.section_usage": "Usage:", "cli.usage.line_gui": " reims-go Open the window (--background: tray only, no window)", "cli.usage.line_cmd": " reims-go [--lang ] [--data-root DIR] [args]", diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index 58957e2..99ee690 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -29,6 +29,7 @@ "bridgeApplyHint": "Network changes apply separately. Shut down this VM to change mode; bridged uplinks can change while running without reconfiguring other VMs. Host adapter IP, DNS, and bindings remain unchanged", "installersTitle": "Images", "installersDownloaded": "Downloaded", + "installersCacheUnavailable": "Cached image unavailable", "installersAvailable": "Releases from Apple", "installersLatest": "Latest", "installersOlder": { @@ -104,12 +105,14 @@ "aboutCopyDiscord": "Copy invite link", "aboutJoinDiscord": "Join server", "aboutQQGroup": "QQ Group", - "aboutQQNotInstalled": "QQ not installed", - "aboutQQNotInstalledSub": "Local QQ wasn’t detected — copy the group ID to join manually", - "aboutQQLaunchFailed": "Couldn’t launch QQ — copy the group ID to join manually", + "aboutQQNotInstalled": "Can’t open QQ directly", + "aboutQQNotInstalledSub": "No QQ app can handle the invite link — open the invite page or copy the group ID", + "aboutQQLaunchFailed": "Couldn’t open QQ — open the invite page or copy the group ID", + "aboutQQOpenInvite": "Open invite page", "aboutCopyQQGroup": "Copy group ID", "aboutJoinQQGroup": "Join group", "whpxTitle": "WHPX", + "appleVirtualizationTitle": "Apple Virtualization", "whpxReady": "Ready", "whpxNoHvShort": "Inactive", "whpxMissingShort": "Off", diff --git a/locales/en-US/wizard.json b/locales/en-US/wizard.json index 0303153..d9bb52d 100644 --- a/locales/en-US/wizard.json +++ b/locales/en-US/wizard.json @@ -44,6 +44,11 @@ "srcOfflineSub": "The full installer; installs with no network", "srcAppleTitle": "Download from Apple", "srcAppleSub": "A recovery image; macOS downloads during install", + "srcIPSWDownloadTitle": "Compatible restore image", + "srcIPSWDownloadSub": "Download from Apple or use a saved restore image", + "srcIPSWLocalTitle": "Local restore image", + "srcIPSWLocalSub": "Choose an .ipsw file on this Mac", + "srcIPSWNone": "No compatible restore image is available", "srcInstallerTitle": "Installer image", "srcInstallerSub": "An .img or .dmg on this PC", "srcDiskTitle": "Existing disk", diff --git a/locales/zh-CN/core.json b/locales/zh-CN/core.json index 50beef1..11dc186 100644 --- a/locales/zh-CN/core.json +++ b/locales/zh-CN/core.json @@ -35,6 +35,24 @@ "menuVM": "虚拟机", "menuView": "视图", "menuHelp": "帮助", + "menuMacEdit": "编辑", + "menuMacWindow": "窗口", + "menuMacHide": "隐藏 Reims-Go", + "menuMacHideOthers": "隐藏其他应用", + "menuMacShowAll": "显示全部", + "menuMacQuit": "退出 Reims-Go", + "menuMacUndo": "撤销", + "menuMacRedo": "重做", + "menuMacCut": "剪切", + "menuMacPaste": "粘贴", + "menuMacPasteMatchStyle": "粘贴并匹配样式", + "menuMacDelete": "删除", + "menuMacSelectAll": "全选", + "menuMacSpeech": "朗读", + "menuMacStartSpeaking": "开始朗读", + "menuMacStopSpeaking": "停止朗读", + "menuMacZoom": "缩放", + "menuMacFullScreen": "进入全屏幕", "newVMEllipsis": "新建虚拟机…", "deleteEllipsis": "删除…", "sidebarLabel": "侧边栏", @@ -69,7 +87,7 @@ "taskAppUpdate": "下载 Reims-Go {v}", "taskPluginDownload": "下载 {name}", "closeDownloadsTitle": "退出 Reims-Go?", - "closeDownloadsDesc": "仍有下载正在进行,退出会中断它们。", + "closeDownloadsDesc": "退出会中断正在进行的下载或 macOS 安装。", "closeDownloadsConfirm": "退出", "settingsAbout": "关于", "themeLight": "浅色", @@ -131,6 +149,7 @@ "taskDownload": "下载 macOS {v}", "taskRecoveryDownload": "正在为 {name} 拉取并挂载在线恢复镜像", "taskCreate": "创建 {name}", + "taskRestoreVM": "在 {name} 上安装 macOS", "tasksRunning": { "message": "{n, plural, other {# 个任务进行中}}", "$comment": "底部后台任务队列汇总" @@ -155,6 +174,8 @@ "toastCopied": "已复制", "failGeneric": "操作失败", "noRuntimeAlert": "先在「内核」导入运行时包", + "wizardNoDriver": "没有可用的客体驱动", + "wizardDriverListFailed": "无法加载客体驱动", "importRuntime": "导入运行时包", "gpuWarnAmdLegacy": "AMD Vega/Polaris 在 Windows 闭源驱动下存在上游已知黑屏/设备丢失问题({ref});若有其他独显请改选独显,否则建议暂用 VMware SVGA", "gpuWarnAmdRdna2": "该 AMD 显卡在 Windows 下存在上游已知设备丢失风险({ref});若卡死黑屏请升级驱动或暂用 VMware SVGA", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index 19ca56c..40cdbaa 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -128,7 +128,10 @@ "avail" ] }, + "doctor.ram.total_only": "共 {total, number, .1} GB(可用内存未知)", "doctor.disk": "数据盘剩余空间", + "doctor.apple_virtualization.ready": "可用", + "doctor.apple_virtualization.unavailable": "不可用", "doctor.whpx": "Windows 虚拟机监控程序平台 (WHPX)", "doctor.whpx.ok": "可用(WinHvPlatform.dll 已就绪,hypervisor 运行中)", "doctor.whpx.no_hv": "已加载 WinHvPlatform.dll,但未检测到虚拟化(请在 BIOS 开启 VT-x/AMD-V)", @@ -293,6 +296,8 @@ "name" ] }, + "err.restore_catalog_unavailable": "暂时无法读取 Apple 的恢复镜像目录,可重试或选择本地 IPSW。", + "err.restore_catalog_unsupported": "当前 Nivfold 版本不支持查询恢复镜像,可更新 Nivfold 或选择本地 IPSW。", "err.runtime_not_installed": "未找到已激活的便携运行时,请先执行 `reims-go runtime install <归档路径>`", "err.qemu_aslr.cancelled": "已取消 Windows 管理员授权,QEMU ASLR 设置保持原样", "err.qemu_aslr.image_policy": "Windows 已按程序名为 qemu-system-x86_64.exe 配置防护,已跳过此运行时的 ASLR 规则。可在 Windows 安全中心的「漏洞保护 → 程序设置」中管理 QEMU 的 ASLR", @@ -936,6 +941,12 @@ }, "affinity.summary.all": "全部核心", "cli.usage.header": "reims-go - Windows 一站式免编译 reims-vgpu 启动器", + "cli.usage.apple.header": "reims-go - Apple 芯片 Mac 实验性虚拟机管理器", + "cli.usage.apple.doctor": " doctor 检查 Apple 虚拟化环境", + "cli.usage.apple.create": " vm create --ipsw 从本地 Apple 恢复镜像创建虚拟机", + "cli.usage.apple.start": " vm start 启动虚拟机并打开窗口", + "cli.usage.apple.stop": " vm stop [--force] 关闭虚拟机", + "cli.usage.apple.delete": " vm delete [--keep-files] 删除已关机的虚拟机", "cli.usage.section_usage": "用法:", "cli.usage.line_gui": " reims-go 打开界面(--background:只在托盘运行,不显示窗口)", "cli.usage.line_cmd": " reims-go [--lang ] [--data-root DIR] <命令> [参数]", diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index c74d6e9..e0642d6 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -29,6 +29,7 @@ "bridgeApplyHint": "网络设置单独应用。切换模式需关闭此虚拟机,更换桥接出口支持运行中应用,不影响其他虚拟机。宿主网卡的 IP、DNS 和绑定保持不变", "installersTitle": "镜像", "installersDownloaded": "已下载", + "installersCacheUnavailable": "缓存镜像不可用", "installersAvailable": "Apple 提供的版本", "installersLatest": "最新", "installersOlder": { @@ -104,12 +105,14 @@ "aboutCopyDiscord": "复制邀请链接", "aboutJoinDiscord": "加入服务器", "aboutQQGroup": "QQ 交流群", - "aboutQQNotInstalled": "未安装 QQ", - "aboutQQNotInstalledSub": "未检测到本地 QQ,可复制群号手动搜索加入", - "aboutQQLaunchFailed": "未能拉起 QQ,可复制群号手动搜索加入", + "aboutQQNotInstalled": "无法直接打开 QQ", + "aboutQQNotInstalledSub": "未找到可处理加群链接的 QQ,可打开邀请页或复制群号", + "aboutQQLaunchFailed": "未能打开 QQ,可打开邀请页或复制群号", + "aboutQQOpenInvite": "打开邀请页", "aboutCopyQQGroup": "复制群号", "aboutJoinQQGroup": "加入群聊", "whpxTitle": "WHPX", + "appleVirtualizationTitle": "Apple 虚拟化", "whpxReady": "就绪", "whpxNoHvShort": "未激活", "whpxMissingShort": "未启用", diff --git a/locales/zh-CN/wizard.json b/locales/zh-CN/wizard.json index abea692..6b4c472 100644 --- a/locales/zh-CN/wizard.json +++ b/locales/zh-CN/wizard.json @@ -44,6 +44,11 @@ "srcOfflineSub": "完整安装包,装机时不联网", "srcAppleTitle": "从 Apple 下载", "srcAppleSub": "恢复镜像,系统在装机时在线下载", + "srcIPSWDownloadTitle": "兼容恢复镜像", + "srcIPSWDownloadSub": "从 Apple 下载或使用已下载的镜像", + "srcIPSWLocalTitle": "本地恢复镜像", + "srcIPSWLocalSub": "选择这台 Mac 上的 .ipsw 文件", + "srcIPSWNone": "没有兼容的恢复镜像", "srcInstallerTitle": "安装镜像", "srcInstallerSub": "本机上的 .img 或 .dmg", "srcDiskTitle": "已有磁盘", diff --git a/main.go b/main.go index 7f90345..956d940 100644 --- a/main.go +++ b/main.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "os" + "runtime" "time" "github.com/Nwflower/reims-go/internal/app" @@ -17,6 +18,7 @@ import ( "github.com/wailsapp/wails/v2" "github.com/wailsapp/wails/v2/pkg/options" "github.com/wailsapp/wails/v2/pkg/options/assetserver" + "github.com/wailsapp/wails/v2/pkg/options/mac" "github.com/wailsapp/wails/v2/pkg/options/windows" ) @@ -110,7 +112,12 @@ func main() { Height: 740, MinWidth: 920, MinHeight: 600, - Frameless: true, + // macOS extends content behind a titled native window; a frameless + // window would also remove the system traffic-light controls. + Frameless: runtime.GOOS != "darwin", + Mac: &mac.Options{ + TitleBar: mac.TitleBarHidden(), + }, DragAndDrop: &options.DragAndDrop{ EnableFileDrop: true, DisableWebViewDrop: true, diff --git a/scripts/build-macos.mjs b/scripts/build-macos.mjs new file mode 100644 index 0000000..17f87d6 --- /dev/null +++ b/scripts/build-macos.mjs @@ -0,0 +1,54 @@ +#!/usr/bin/env node +import { execFileSync } from 'node:child_process' +import fs from 'node:fs' +import path from 'node:path' +import { cachePath, REPO_ROOT, resolveStorageRoot, runsPath } from './debug/paths.mjs' +import { createTemporaryFiles } from './debug/temporary-files.mjs' + +if (process.platform !== 'darwin' || process.arch !== 'arm64') { + console.error('This build requires an Apple silicon Mac and the Xcode toolchain.') + process.exit(1) +} + +const root = resolveStorageRoot() +const temps = createTemporaryFiles(root) +const output = runsPath(root, 'macos-client') +const goCache = cachePath(root, 'go-build') +const input = process.argv.slice(2) +if (input.length !== 0 && (input.length !== 2 || input[0] !== '--runtime')) { + console.error('Usage: node scripts/build-macos.mjs [--runtime ]') + process.exit(1) +} +const external = input.length ? path.resolve(input[1]) : null +const directory = temps.create('build-macos', process.pid) +const env = { ...process.env, TMPDIR: directory, GOTMPDIR: directory, GOCACHE: goCache, CGO_ENABLED: '1' } +const run = (command, args) => execFileSync(command, args, { cwd: REPO_ROOT, env, stdio: 'inherit' }) + +function stageRuntime(source) { + const staged = path.join(directory, 'nivfold') + fs.copyFileSync(source, staged, fs.constants.COPYFILE_EXCL) + fs.accessSync(staged, fs.constants.X_OK) + run('codesign', ['--verify', '--strict', staged]) + const report = JSON.parse(execFileSync(staged, ['probe'], { cwd: REPO_ROOT, env, timeout: 5000, encoding: 'utf8' })) + if (report.runtime !== 'nivfold' || report.protocol_version !== 1 || report.supported !== true) { + throw new Error('expected a compatible Nivfold runtime (protocol 1)') + } + return staged +} + +try { + for (const dir of [output, goCache]) fs.mkdirSync(dir, { recursive: true }) + const helper = external ? stageRuntime(external) : null + run('pnpm', ['--dir', 'frontend', '--store-dir', cachePath(root, 'pnpm-store'), 'install', '--frozen-lockfile']) + run('pnpm', ['--dir', 'frontend', 'run', 'build']) + const client = path.join(directory, 'reims-go') + run('go', ['build', '-trimpath', '-tags', 'desktop,production', '-o', client, '.']) + if (helper) fs.renameSync(helper, path.join(output, 'nivfold')) + fs.renameSync(client, path.join(output, 'reims-go')) + temps.close(directory) + console.log(`Native macOS client: ${path.join(output, 'reims-go')}`) + if (!helper) console.log('The client build does not install a VM runtime. Pass --runtime with a trusted Nivfold build to install it beside the client.') +} catch (error) { + console.error(`macOS build failed: ${error.message}\nBuild directory retained: ${directory}`) + process.exitCode = 1 +} diff --git a/scripts/check-nivfold.mjs b/scripts/check-nivfold.mjs new file mode 100644 index 0000000..d8dfa8a --- /dev/null +++ b/scripts/check-nivfold.mjs @@ -0,0 +1,17 @@ +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import fs from 'node:fs' +import path from 'node:path' + +const [runner] = process.argv.slice(2) +const vm = path.join(process.env.REIMS_TMP_DIR, 'native-vm') +fs.mkdirSync(vm, { mode: 0o700 }) +const query = (...args) => JSON.parse(execFileSync(runner, args, { encoding: 'utf8', timeout: 5000 })) +const probe = query('probe') +assert.equal(probe.runtime, 'nivfold') +assert.equal(probe.protocol_version, 1) +assert.equal(probe.entitled, true) +assert.equal(probe.supported, true) +assert.ok(probe.resources.recommended_cpu_count > 0) +assert.ok(probe.resources.maximum_memory_mib >= probe.resources.minimum_memory_mib) +assert.deepEqual(query('status', '--vm-dir', vm), { installed: false, pid: 0, state: 'stopped' }) diff --git a/scripts/test.mjs b/scripts/test.mjs index da9187e..ff89586 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -21,6 +21,7 @@ const usage = `Usage: node scripts/test.mjs ci release webview2 + applevz Set REIMS_TEST_JOBS to cap Go package concurrency (default: at most 4).` @@ -39,7 +40,7 @@ function run(label, command, args, env, cwd = REPO_ROOT) { function select(args) { const [profile, area, ...packages] = args if ((profile === 'ci' || profile === 'release') && args.length === 1) return { profile } - if (profile === 'webview2' && args.length === 2) return { profile, executable: path.resolve(area) } + if ((profile === 'webview2' || profile === 'applevz') && args.length === 2) return { profile, executable: path.resolve(area) } if (profile !== 'quick') throw new Error(usage) if (area === 'go' && packages.length > 0) { for (const pkg of packages) { @@ -96,6 +97,10 @@ async function main(args) { await run('WebView2 first launch', 'powershell.exe', [ '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', 'scripts/smoke-webview2.ps1', executable, ], env) + } else if (profile === 'applevz') { + if (process.platform !== 'darwin' || process.arch !== 'arm64') throw new Error('Apple Virtualization smoke requires Apple silicon') + await run('Apple Virtualization signature', 'codesign', ['--verify', '--strict', executable], env) + await run('Nivfold runtime protocol', process.execPath, ['scripts/check-nivfold.mjs', executable], env) } else if (profile === 'quick') { if (area === 'go') await go(packages) if (area === 'storage') {