Merge branch 'feat/vmref-driver-start' into main
This commit is contained in:
commit
563b5a45bb
232 files changed
+10126
-4164
No files matched your search
@@ -72,4 +72,5 @@
|
||||
- [`docs/pr-review-guidelines.md`](docs/pr-review-guidelines.md) — PR 变更归属、跨仓交付与客户端独立性审查
|
||||
- [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md) — 便携运行时打包、发布通道与合规规范
|
||||
- [`docs/plugin-architecture.md`](docs/plugin-architecture.md) — 插件系统架构与扩展接口规范
|
||||
- [`docs/guest-plugin-migration.md`](docs/guest-plugin-migration.md) — 客体插件化与 macOS 剥离的迁移路径
|
||||
- [运行时补丁与上游跟踪](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md) — 运行时源码入口与依赖补丁
|
||||
+23
-12
@@ -54,22 +54,26 @@ flowchart TB
|
||||
| :--- | :--- |
|
||||
| `main.go`、`console_*.go` | 统一入口:无参数启动 Wails GUI,带子命令进入 `internal/cli`;处理 GUI 子系统下的父控制台句柄接管 |
|
||||
| `internal/app` | Wails 绑定与桌面编排(启停、安装、快照、CoW 派生、磁盘扩容/回收、SSH、脱敏排障包、任务状态、运行监视) |
|
||||
| `internal/vmstart` | GUI 与 CLI 共用的启动前准备:提交内存预检、离线辅助盘、恢复模式引导、客体语言重放、WHPX 兼容处理、启动后 CPU 绑核 |
|
||||
| `internal/vmstart` | 通用启动辅助:提交内存等待、启动后 CPU 绑核、亲和性配置与命令行日志 |
|
||||
| `internal/macos/startprep` | macOS 启动前准备:WHPX/内存检查、离线辅助盘、恢复模式引导、客体语言重放与兼容处理 |
|
||||
| `internal/cli` | 命令行子命令实现、单实例参数解析与向界面进程交接 `vm start` |
|
||||
| `internal/host` | 宿主机体检与硬件调优:WHPX 检测与 UAC 启用、提交内存预检、Vulkan ICD 扫描、三层大小核拓扑与实时绑核、显示器 HiDPI 推荐、音频与磁盘总线探测、窗口置前、IME 文本钩子 |
|
||||
| `internal/runtime` | 便携运行时拉取(GitHub Releases)、原子解压、多版本切换与子进程环境变量构造 |
|
||||
| `internal/fetch` | 发布附件下载:HTTP `Range` 续传与按发布页 `SHA256SUMS.txt` 强制校验,运行时安装与应用内更新共用 |
|
||||
| `internal/selfupdate` | 应用内更新:把已校验的新版 `reims-go.exe` 换入运行中程序的位置、重新拉起与残留清理 |
|
||||
| `internal/installer` | 包装 `reims-util --json` 实现 macOS 离线安装包查询、宿主机直连下载、断点续传、互斥锁保护与缓存清理 |
|
||||
| `internal/driver/reims` | `reims-ctl` 与 `qemu-img` 受控子进程包装、输出解析、快照/派生/导入操作、日志与配置脱敏 |
|
||||
| `internal/macos/installer` | 包装 `reims-util --json` 实现 macOS 离线安装包查询、宿主机直连下载、断点续传、互斥锁保护与缓存清理 |
|
||||
| `internal/macos/reims` | `reims-ctl` 与 `qemu-img` 受控子进程包装、输出解析、快照/派生/导入操作、日志与配置脱敏 |
|
||||
| `internal/macos/macosdriver` | 把 `internal/macos/reims` 适配为通用 `driver.Driver`(内置驱动 `builtin.driver.reims-macos`) |
|
||||
| `internal/macos/guest` | 内置可选插件 `builtin.guest.macos`:静态驱动声明、宿主体检、启动与兼容 Hook、安装引导服务,以及数据布局 v2 的状态与参数账本迁移 |
|
||||
| `internal/macos/installguide` | 虚拟机窗口旁的 macOS 安装与恢复分步引导(Win32 浮层) |
|
||||
| `internal/qmp` | QMP 客户端:键盘键入、截屏与 Win10 冷重启监视 |
|
||||
| `internal/guesttools` | 本地回环鉴权 HTTP/WebDAV 服务:图文双向剪贴板、共享目录、Windows 盘符只读共享、防休眠开关与 `REIMSTOOLS` 辅助盘生成 |
|
||||
| `internal/opencore` | 改写 OpenCore 镜像中的 `prev-lang:kbd`,实现系统外预设 macOS 语言 |
|
||||
| `internal/macos/opencore` | 改写 OpenCore 镜像中的 `prev-lang:kbd`,实现系统外预设 macOS 语言 |
|
||||
| `internal/netproxy` | 统一 HTTP Transport:优先环境变量代理,回退读取 Windows 系统代理配置 |
|
||||
| `locales/`、`cmd/i18ngen` | 单一事实源分域 JSON 词表(含译者上下文 `$comment` 与 Apple macOS 官方多语种词汇表)及编译期前后端字典代码生成器 |
|
||||
| `internal/config`、`internal/i18n` | 应用配置持久化(`reims-go.json`)、轻量 ICU 格式化引擎、多跳语言回退链与带稳定排障码的结构化错误(`CodedError`) |
|
||||
| `internal/thumb`、`internal/tray`、`internal/version` | 4K 截屏行级缩放预览、Windows 系统托盘常驻、版本信息与新版本检查 |
|
||||
| `frontend/src` | 桌面界面:`components/`(页面与对话框)、`ui/`(Radix 基件封装)、`lib/`(格式化、日志与任务)、`styles/`(设计令牌) |
|
||||
| `frontend/src` | 桌面界面:`components/`(页面与对话框)、`macos/`(macOS 专属页面与组件)、`ui/`(Radix 基件封装)、`lib/`(格式化、日志与任务)、`styles/`(设计令牌) |
|
||||
| `scripts/` | 便携运行时打包、二进制裁剪与符号分离、MSYS2 源码归档、`alpha` 准入与冒烟脚本,以及 `scripts/debug/` 本地调试目录管理与卫生校验脚本 |
|
||||
|
||||
---
|
||||
@@ -77,8 +81,8 @@ flowchart TB
|
||||
## 4. 关键机制与安全边界
|
||||
|
||||
### 4.1 启动编排与单实例交接
|
||||
- `internal/vmstart` 承载 GUI 与 CLI 共用的启动步骤;只有常驻进程才能维持的能力(Guest Tools 桥接、Win10 冷重启监视)由界面进程托管。
|
||||
- CLI 执行 `vm start` 时,默认交由桌面进程启动:界面已在运行时通过 Wails 单实例锁(`WM_COPYDATA`)发消息不弹窗拉起;未运行时以 `--background` 启动隐藏到托盘的后台界面进程,结果经 `<DataRoot>\tmp\cli-start-*.json` 回传并带退出码返回。
|
||||
- `internal/lifecycle` 统一 GUI、CLI 与窗口交接的 VM 列表、详情、设置、启动、停止、重启、删除、介质动作和日志读取:按 `VMRef` 解析所属驱动,先收集第三方 Hook,否决时不调用驱动,成功后再发事件。macOS 的启动前检查、参数账本与磁盘准备由 `internal/macos/macosdriver` 自己完成,准备失败即中止;`internal/vmstart` 保留共享检查与旧回退。只有常驻进程才能维持的能力(Guest Tools 桥接、Win10 冷重启监视)由界面进程托管。
|
||||
- CLI 执行 `vm start` 时,默认交由桌面进程启动:界面已在运行时通过 Wails 单实例锁(`WM_COPYDATA`)发消息不弹窗拉起;未运行时以 `--background` 启动隐藏到托盘的后台界面进程,结果经 `<DataRoot>\tmp\cli-start-*.json` 回传并带退出码返回。交接同时携带 `--start-driver=`,裸名称不再作为跨驱动的完整身份。
|
||||
- 仅在 CLI 显式指定 `--data-root` 时由命令进程直接启动,此时不包含 Guest Tools 桥接与 Win10 冷重启监视。
|
||||
- `reims-go.exe` 编译为 Windows GUI 子系统程序,命令行模式下保留调用方管道/文件句柄,缺失时通过 `AttachConsole` 挂载父控制台;在交互式 PowerShell/cmd 中加 `| Out-Host` 可等待命令执行完毕。
|
||||
|
||||
@@ -87,13 +91,13 @@ flowchart TB
|
||||
- **Win10 冷重启监视通道**:Windows 10 19045 缺少 `WHvResetPartition`,客体热重启会导致 WHPX 退出异常。在 Win10 宿主上,启动时附加 `-no-reboot` 并另开一条独立的 `AF_UNIX` QMP 通道监听重启退出事件,干净退出后自动重新拉起。使用 `AF_UNIX` 而非 TCP,避免客体经 SLIRP 的 `10.0.2.2` 访问宿主机监控接口。
|
||||
|
||||
### 4.3 Guest Tools 与宿客安全边界
|
||||
- Guest Tools 服务仅监听 `127.0.0.1`,每台虚拟机分配独立的 256-bit 随机 Token(Bearer / Basic 鉴权)。
|
||||
- Guest Tools 服务仅监听 `127.0.0.1`,每台虚拟机分配独立的 256-bit 随机 Token(Bearer / Basic 鉴权)。注册表、连接状态、剪贴板策略、文本输入与 WebDAV handler 按 `driver.VMRef.Key()` 隔离;token 认证同时识别驱动与名称,既有客体 URL 不变。
|
||||
- WebDAV 共享目录(`/dav/<vm>/`)严格校验路径防目录穿越;Windows 盘符只读共享(`/dav/<vm>/drives/<盘符>/`)默认全部关闭,服务端同时限制 HTTP 写方法与只读打开标志、校验持久化 Volume GUID 防盘符漂移、限制 `PROPFIND Depth` 并校验 Junction/符号链接解析目标仍在授权盘符内。
|
||||
|
||||
### 4.4 宿主机体检与硬件调优
|
||||
- **免提权 WHPX 检测**:通过 `WinHvPlatform.dll`(`WHvGetCapability`)与系统功能查询判断状态,仅在缺失且用户确认时通过 `ShellExecuteW(..., "runas", ...)` 触发 UAC 启用。
|
||||
- **提交内存预检**:通过 `GlobalMemoryStatusEx` 检查可用提交内存(`AvailPageFile`),因为 QEMU 在 Windows 上会一次性提交整块客体内存;建机时推荐安全档位,启动前余量不足时提前拦截。
|
||||
- **GPU 与大小核**:扫描注册表 Vulkan ICD 并过滤虚拟显示适配器;解析 `GetLogicalProcessorInformationEx` 识别 P / E / LP-E 三层混合核心,支持按 VM 实时调整进程亲和性,避免超售卡顿。
|
||||
- **GPU 与大小核**:扫描注册表 Vulkan ICD 并过滤虚拟显示适配器;解析 `GetLogicalProcessorInformationEx` 识别 P / E / LP-E 三层混合核心,支持按 VM 实时调整进程亲和性,避免超售卡顿。宿主只评估通用硬件事实;`kernel_irqchip`、冷重启等 macOS/WHPX 建议由所属驱动的 `driver.OptimizationAdvisor` 提供,与启动准备共用运行时判定。
|
||||
|
||||
### 4.5 应用内更新
|
||||
- 界面启动后检查一次新版本,之后每 6 小时检查一次(后端缓存 10 分钟),只看 `vX.Y.Z` 正式版,忽略草稿与预发布。有新版本时侧栏顶部显示更新胶囊卡片,关于页提供同样的操作。
|
||||
@@ -103,16 +107,23 @@ flowchart TB
|
||||
- 开发构建(`wails dev`,`dev` 标签)与非 Windows 平台不支持应用内更新;程序所在目录不可写(如未提权的 `Program Files`)时提示改为手动更新。
|
||||
|
||||
### 4.6 资源回收与内存约束
|
||||
- 按 VM 生命周期分配的状态(缩略图锁、Guest Tools 注册与 WebDAV handler、进程采样、绑核记录、文本队列与 worker)在删除 VM 或轮询发现外部删除时立即回收。
|
||||
- 按 VM 生命周期分配的状态(过渡态、待生效设置、冷重启监视、磁盘路径缓存、进程采样、缩略图与键入锁、文本队列与 worker)以 `driver.VMRef.Key()` 隔离,并在删除 VM 或轮询发现外部删除时立即回收;VM 日志来源也使用规范键。
|
||||
- 日志监视器对单行无换行输出设 **64 KiB** 内存上限(原始日志文件完整保留);已结束任务在 10 分钟后从前后端状态中清理。
|
||||
- 4K 屏幕预览采用按行流式缩放降低单帧分配;手动复制截图仍保留全分辨率。不在热路径中人为调用 `debug.FreeOSMemory`。
|
||||
|
||||
### 4.7 数据目录版本与迁移
|
||||
- `<DataRoot>\.reims-go-data.json` 记录数据布局版本 `data_version`,以及最后一次提升它的应用版本 `written_by`。它不放进 `reims-go.json`,因为配置每次保存都会按结构体整体重写,旧版本会丢掉不认识的字段。
|
||||
- 每个版本都带着从旧布局升到自身布局的全部迁移步骤(`internal/datamigrate`),GUI 与 CLI 启动时、读取数据之前按版本号依次执行。步骤必须可重复执行;某步失败时,版本号停在最后一个成功的步骤,下次启动从那里继续。用户可以从任意旧版本直接升到新版本。
|
||||
- 数据目录的版本高于本程序所知时(降级运行),不做任何改动,只记一条日志。
|
||||
- GUI 启动、首次设置、切换数据目录与 CLI 都经 `internal/dataroot` 打开数据目录:先不加锁读取版本戳,需要迁移时才取 `<DataRoot>.reims-go.lock` 并在锁内重读版本戳,两个进程同时打开同一目录时迁移只执行一次。
|
||||
- 数据目录由更新版本写入、版本戳无法解析、迁移失败或另一进程长时间持锁时,以只读模式打开,不创建或修改任何文件(包括锁文件):GUI 不启动插件、不轮询虚拟机,以只读界面代替工作台;CLI 只放行 `version`、`help` 与 `doctor`。版本戳损坏时可由用户显式修复,从 v0 重新执行全部步骤。
|
||||
- 首次设置选定目录之前,宿主不写入默认建议目录:不迁移、不启动插件、不轮询,界面中的选择只保存在内存里,由 `CompleteSetup` 写入选定的目录。
|
||||
- 只有删除很老的迁移步骤之后,才需要「最低迁移版本」:新版本根据 `data_version` 判断,并提示先安装某个中间版本。这个判断看的是数据本身,所以直接下载新版本运行也会生效。
|
||||
- 现有步骤:v1 为 reims-ctl 管理的每台 VM(目录含 `vm.toml`)补写驱动归属标记,见 [plugin-architecture.md](plugin-architecture.md) 的「VM 归属」。
|
||||
- 现有步骤:v1 为 reims-ctl 管理的每台 VM(目录含 `vm.toml`)补写驱动归属标记,见 [plugin-architecture.md](plugin-architecture.md) 的「VM 归属」;v3 一次性把正式版 `builtin.core` 的设置、`builtin.install-guide` 的启停和已知参数账本条目迁入 `builtin.guest.macos`,把按裸 VM 名的插件设置键改为 `driverID:vmName`,并补扫无归属标记的 VM。`state.json` 只加载、保存一次,原始 `.bak` 不被中间布局覆盖;功能分支上的 v2 仍可直升,未公开发布过的旧插件 ID 不做长期迁移。
|
||||
|
||||
### 4.8 macOS 代码边界
|
||||
- macOS 专属代码集中在 `internal/macos/` 与 `frontend/src/macos/`,最终作为独立插件移出本仓库;宿主只应经驱动层(`driver.Router`)与宿主服务使用它。
|
||||
- 三个棘轮测试守住边界:`internal/archtest` 分别检查宿主到 macOS、macOS 到宿主私有 Go 包的依赖,`frontend/scripts/test-macos-boundary.mjs` 检查前端文件。只有列入清单的包或文件可以跨界;新增引用、或清单中的条目已不再引用时,测试都会失败,所以清单只能缩短。
|
||||
- 宿主到 macOS 的例外包括 GUI 与 CLI 的组装入口、数据布局 v2 的迁移,以及仍混有宿主与 macOS 逻辑、待拆分的 `internal/guesttools`。反向清单记录 macOS 对宿主私有包的现有依赖,随公开接口建设逐步清零。
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
# 客体插件化与 macOS 剥离方案
|
||||
|
||||
> 状态:待评审。本文描述从现有代码走到"与客体无关的主程序 + macOS 外部插件"的路径。[plugin-architecture.md](plugin-architecture.md) 记录的是插件系统当前的权威设计;本文的每一步合入时,同步修改该文对应章节(§3.2、§5.3、§5.4、§12 等),两份文档不得长期并存矛盾。
|
||||
|
||||
## 1. 目标与边界
|
||||
|
||||
- **终态**:主程序是与客体无关的本地虚拟机工作台。macOS 能力作为外部插件(独立仓库、独立发布)提供;主程序的源码、文档、语言词表、发布物与运行时流水线不含 macOS 专属内容。
|
||||
- **过渡态**:macOS 先成为内置插件 `builtin.guest.macos`,仍随 `reims-go.exe` 编译。过渡期只保证两件事,以免外置时再做一次迁移:
|
||||
- **职责与数据按终态划分**:设置、参数账本、VM 归属、启动准备从一开始就归 macOS 插件与它的驱动所有。
|
||||
- **调用面按终态收敛**:macOS 代码只经驱动接口、Hook 与宿主服务使用宿主;它对宿主 Go 包的依赖逐步收敛到可公开的 `pkg/` 包(第 6 节的反向棘轮)。
|
||||
- 界面是唯一允许的例外:过渡期可挂载原生页面,步骤 5 替换。
|
||||
- **特权按角色而不是按 ID 前缀**:宿主内置插件(留在主程序的部分)保留现有特权;拥有某台 VM 的驱动,对该 VM 的启动参数拥有完整控制(含 `-drive`、`-chardev`、`-qmp` 等),无论它是内置还是外部。外部驱动本身是 L3 原生程序,拥有完整账户权限,这不构成提权;第三方 Hook 仍受现有脱敏、超时与参数族限制。
|
||||
- **Linux 驱动**用于验证接口通用性,按 plugin-architecture.md Phase 4 以独立仓库的 L3 插件实现。Android 只预留接口。
|
||||
- **不在本方案内**:常驻后台服务、OCI 分发、运行态热迁移、整盘导出导入、稳定 VM ID(第 8 节)。
|
||||
- 哪些内容构成法律风险、需剥离到什么程度,不由本文判断,见第 9 节。
|
||||
|
||||
## 2. 现状
|
||||
|
||||
macOS 代码已集中到 `internal/macos/`(`installer`、`opencore`、`installguide`、`reims`、`macosdriver`)与 `frontend/src/macos/`,宿主到 macOS 的 import 由两处棘轮测试守住([architecture.md](architecture.md) §4.8)。仍需解决的问题:
|
||||
|
||||
### 2.1 身份与数据
|
||||
|
||||
| 问题 | 现状 |
|
||||
| :--- | :--- |
|
||||
| 驱动 ID 与旧插件 ID 混用 | `builtin.driver.reims-macos` 同时列在 `builtin.RetiredIDs` 中,不能直接拿来做新插件 ID |
|
||||
| 设置迁移不原子 | `MigrateRetired` 先落盘删除旧记录,再单独落盘新设置;两次写盘之间退出会丢失用户关闭过的选项 |
|
||||
| 安装引导独立成插件 | `builtin.install-guide` 是独立可选插件,内容是纯 macOS 的安装与恢复引导 |
|
||||
| 使用中保护依赖静态声明 | 使用中检查经 `DeclaredDriverIDs` 读取清单的 `guestDrivers`;`builtin.core` 在激活时动态注册驱动,未静态声明。核心插件不可停用所以目前无害,macOS 插件可停用后会失效 |
|
||||
| VM 以裸名称索引 | `PluginRecord.VMSettings` 以 VM 名为键;宿主内存态(`transitions`、`pendingChanges`、`rebootWatchers`、`diskPaths`、`procSamples`)、Guest Tools 注册表、缩略图与键入锁、日志来源同样以名称索引;界面进程交接参数 `--start-vm=` 不带驱动 |
|
||||
| VM 目录只有一个根 | 路由与"驱动不可用"扫描只看 `<DataRoot>/data/reims-ctl/vms` |
|
||||
| 运行时只能选一个 | `config.ActiveRuntime` 是单个字符串;非默认种类直接取已安装列表第一项;已装多个 reims-vgpu 运行时且未选定时,所有依赖运行时的功能失败 |
|
||||
|
||||
### 2.2 数据目录写入
|
||||
|
||||
GUI 启动、首次设置、`SetDataRoot`、CLI 各自打开数据目录;迁移失败时 GUI 只记日志、CLI 只打印警告;`SetDataRoot` 先保存配置再迁移;首次设置完成前,宿主已把默认建议目录当作数据目录读写;版本戳损坏时按 v0 重跑;没有跨进程写锁。
|
||||
|
||||
### 2.3 启动链路
|
||||
|
||||
| 问题 | 现状 |
|
||||
| :--- | :--- |
|
||||
| 启动入口 | GUI 的 `App.StartVM` 直接取 reims 客户端、自做 WHPX 检查,启动事件写死 macOS 驱动 ID 与能力;CLI 有直接启动(`startVM`)与交给界面进程(`startInWindow`)两条路径 |
|
||||
| 启动准备放在公共 Hook | `builtin.core` 的 `vm.beforeStart` 依次执行离线辅助盘、恢复启动、引导语言、WHPX 兼容降级、Win10 冷重启五步;恢复与语言两步在回调里直接写恢复标记、改写 OpenCore 镜像,后续插件否决时磁盘已被改动 |
|
||||
| 特权按前缀 | `BuiltinOnlyQEMUOptionFamilies`(`-drive`、`-chardev`、`-qmp`、`-fw_cfg`、`-global`、`-object`)、宿主环境变量白名单与 `PostStart` 动作都按 `builtin.` 前缀放行;外部插件的 `vm.beforeStart` 拿不到 `VMDir`、`ExtraArgs`、`InstallerPath`,单个回调限时 2 秒 |
|
||||
| 驱动接口缺参数 | `Driver.Start` 只收 VM 名,不接收合并后的参数、环境变量与启动后动作;参数账本的合并结果在 `StartVM` 中经 `reims-ctl set --extra-args` 写入;`stripLegacyManagedExtraArgs` 在 `internal/app` 中直接调用 macOS 代码 |
|
||||
| 调优不分驱动 | `host.EvaluateOptimizations` 一次算出绑核、irqchip、冷重启、独显与 CoW 建议 |
|
||||
|
||||
### 2.4 路由与界面
|
||||
|
||||
列表、详情、设置、停止、删除、日志等十余处直接调用 reims 客户端;`Router.ListAllVMs` 没有调用方且按名称去重;`Router.ResolveVM` 返回第一个同名结果;CLI 只有 `vm create --driver` 走驱动层;前端类型直接使用 `reims.VMDetail`,`CreateWizard`、`SettingsModal`、`lib/tasks.ts` 含 OpenCore、恢复、引导语言、无边框、安装包等字段与交互(不经 import,棘轮看不到)。
|
||||
|
||||
### 2.5 外置障碍
|
||||
|
||||
| 问题 | 现状 |
|
||||
| :--- | :--- |
|
||||
| Go 可见性 | `internal/macos/*` 导入宿主的 `internal/config`、`host`、`i18n`、`driver`、`plugin`、`runtime`、`vmstart`;外部仓库不能导入别的模块的 `internal/` 包 |
|
||||
| SDK | `pkg/pluginsdk` 只有 JSON-RPC 骨架 |
|
||||
| 反向宿主接口 | Sidecar 只能调用 `notify`、`audit`、`vm.spawn`、`vm.stop`、`vm.isRunning`;没有运行时查询、内存预检、绑核、日志与任务、进程退出、窗口信息等服务 |
|
||||
| 外部界面 | 外部插件不能贡献整页界面;沙箱 iframe 没有文件选择、流式任务进度、弹窗与尺寸协调等桥接 |
|
||||
| 非 import 耦合 | 全局脱敏器(`i18n.SetDetailRedactor`、插件管理器 `RedactFn`、排障包、界面错误上报)都直接用 `reims.RedactText`;`internal/runtime` 内置 `DefaultKind = "reims-vgpu"`、`reims-ctl` / `reims-util` 路径、reims 专用环境变量、按补丁推断能力与发布源;`locales/*/macos-glossary.json` 与 `internal/i18n/glossary.go`,以及 `vm`、`wizard`、`settings` 等词表中的 macOS 文案;`internal/app/macos_release.go`(`.reims-go-macos`);数据目录禁止逗号源于 `reims-util`;`internal/host` 中面向 reims-vgpu / metal2vulkan 的显卡兼容判断;CLI 顶层 `installer` 子命令 |
|
||||
| 外围文件 | `patches/`、`.github/workflows/build-runtime.yml`、`scripts/` 中的运行时打包与补丁脚本、`docs/portable-runtime-spec.md` |
|
||||
|
||||
## 3. 身份模型
|
||||
|
||||
| 身份 | 作用 | 规则 |
|
||||
| :--- | :--- | :--- |
|
||||
| 插件 ID | 启停、设置、贡献、参数账本归属 | 过渡期 `builtin.guest.macos`;外部插件不可使用 `builtin.` 前缀,换新 ID,经声明式承接接收旧 ID 的数据(见下) |
|
||||
| 驱动 ID | 一台 VM 由谁管理,写在 VM 目录的 `.reims-go-driver` | 过渡期保留 `builtin.driver.reims-macos`;外部驱动换新 ID,并把旧 ID 声明为别名,已有标记不改写 |
|
||||
| 运行时种类 | 安装哪套可执行程序、驱动要求的接口版本 | 每种类单独选定活跃运行时(步骤 3.5) |
|
||||
| VM 引用 `VMRef` | 一次操作、一份设置或一项内存状态针对哪台 VM | `{驱动 ID, 驱动内名称}`,自步骤 2 起贯穿宿主;稳定 VM ID 见第 8 节 |
|
||||
| VM 目录根 | 驱动的 VM 放在哪里 | 驱动在清单中静态声明自己的 VM 根目录(相对 DataRoot);macOS 驱动声明现有的 `data/reims-ctl/vms`。停用的驱动清单仍可读,宿主据此扫描"驱动不可用"的 VM,两个驱动的同名 VM 不会在磁盘上冲突 |
|
||||
|
||||
**声明式承接**:外部插件在清单中声明 `replaces`(它承接的旧插件 ID)与驱动 `aliases`(它承接的旧驱动 ID)。宿主在**安装或首次激活该插件时**把旧 ID 名下的设置、参数账本条目与按 VM 设置转给它,并让带旧驱动 ID 标记的 VM 归它管理。约束:
|
||||
|
||||
- 宿主在旧插件消失后保留其 `state.json` 记录与账本条目,直到有插件承接,期间这些 VM 显示"驱动不可用"。
|
||||
- 承接 `builtin.*` ID 只允许信任等级为 `official` 的包,或经用户逐项确认,防止任意插件接管已有 VM。
|
||||
- 主程序不硬编码任何 macOS 新旧 ID 映射。数据迁移带入的 `driver.RenamedDriverIDs` 只用于主程序内部的内置驱动改名,外部插件改名一律走 `aliases`。
|
||||
|
||||
驱动 ID 从此与插件 ID 分开:步骤 1 将 `builtin.driver.reims-macos` 移出 `RetiredIDs`,只有正式发布过的旧记录进入迁移清单:`builtin.core` 的设置与账本,以及 `builtin.install-guide` 的启停。未公开发布过的独立 theme/driver、compat/prep 插件记录不迁移、不删除。
|
||||
|
||||
## 4. 分步方案
|
||||
|
||||
每一步单独合入、单独发布,完成后对应的棘轮例外缩短(第 6 节)。
|
||||
|
||||
### 步骤 0:数据目录写入保护
|
||||
|
||||
后续每一步的数据迁移都依赖它;不依赖第 3 节的任何决定,可以立即开始。
|
||||
|
||||
- **统一打开入口**:新增宿主包(暂名 `internal/dataroot`),GUI 启动(`config.Resolve`)、首次设置(`CompleteSetup`)、切换目录(`SetDataRoot`)与 CLI 都经它进入。顺序为:
|
||||
1. 不加锁读取版本戳。版本高于本程序、或版本戳无法解析时,以只读模式返回,**不创建锁文件、不写任何文件**。
|
||||
2. 需要迁移或即将写入时,才创建并获取写锁,**拿锁后重新读取版本戳**,再决定是否迁移。另一个进程已完成迁移时直接返回。
|
||||
3. 迁移完成、版本戳写入后释放写锁。
|
||||
- **写锁**:把 `internal/macos/installer` 中基于 `LockFileEx` 的文件锁上提为宿主公共实现(`internal/filelock`),锁文件放在数据目录内,只在迁移时持有。配置与 `state.json` 都以临时文件加改名的方式原子写入,单次写入不会留下残缺文件,因此不为单次写入加锁;GUI 与 CLI 同时修改同一份配置时的相互覆盖不在本步解决。
|
||||
- **只读诊断模式**:GUI 不启动插件、不轮询虚拟机,以只读界面代替工作台,说明原因与详细信息,可选择其他目录;版本记录损坏时提供显式"修复(从 v0 重新迁移)",另一进程升级中或升级失败时提供"重试"。CLI 只放行 `version`、`help` 与 `doctor`,其他命令以非零退出码拒绝。
|
||||
- **写入点清单**(只读模式与首次设置前全部拦截):`reims-go.json`、`plugins/state.json` 与其备份、市场索引缓存、版本戳、启动哨兵 `.startup-sentinel`、`cli-start-*.json`、界面健康日志 `logs/ui-health.log`、应用更新后对更新下载目录的清理、VM 目录内的参数账本与归属标记。`CompleteSetup` 对候选目录的可写性探测(`.write-test-*`)只针对用户已选定的目录,保留。
|
||||
- **首次设置前零写入**:`needsSetup` 期间不把默认建议目录当作数据目录,数据迁移、插件状态与配置保存都要等目录选定。`REIMS_GO_FIRST_RUN` 测试模式必须同时指定隔离的数据目录,否则拒绝启动。
|
||||
- **CLI 交给界面进程**:`location.json` 位于数据目录之外。CLI 未指定数据目录、经单实例交给界面进程时,以界面进程当前打开的目录为准;该目录处于只读模式时,写命令被拒绝并说明原因。
|
||||
- **`MigrateRetired` 一次落盘**:删除旧记录与写入新设置合并为一次 `state.json` 原子替换。
|
||||
|
||||
**验收**
|
||||
- 高版本或版本戳损坏的数据目录:GUI 进入只读模式、CLI 写命令被拒,目录内无任何文件(含锁文件)被创建或修改。
|
||||
- 首次设置测试模式与设置完成前,默认建议目录内无任何文件被创建或修改。
|
||||
- 在 `MigrateRetired` 两步之间模拟退出,重启后用户关闭的选项仍为关闭。
|
||||
- GUI 与 CLI 同时启动并触发迁移,迁移只执行一次,结果一致。
|
||||
|
||||
### 步骤 1:macOS 插件身份与元数据迁移(已落地,合并至 v3)
|
||||
|
||||
- 新增内置插件 `builtin.guest.macos`,注册代码放在 `internal/macos/guest` 内,由 GUI 与 CLI 组装入口注册。`builtin.core` 只保留客体无关的默认主题。过渡期 macOS 插件默认启用,以保留存量 VM 的升级行为。
|
||||
- **安装引导并入**:`builtin.install-guide` 并入 `builtin.guest.macos`,成为它的一个可开关功能;旧 ID 退役,用户原来的启用状态转为新插件的对应设置。外部 macOS 插件因此只是一个包。
|
||||
- **静态声明驱动**:新插件在清单 `guestDrivers` 中静态声明 `builtin.driver.reims-macos`,运行中检查才能阻止在 macOS VM 运行时停用它,使用中检查才能阻止在仍有 macOS VM 时卸载它。
|
||||
- **设置迁移**:`whpx_fallback`、`win10_cold_reboot` 从 `builtin.core` 转给新插件,合并顺序为"新插件显式值 → 旧插件显式值 → 默认值"。
|
||||
- **参数账本迁移**:每台 VM 的账本中,只把已知由 macOS 启动步骤写入的条目转给新插件;用户手动参数与其他插件的条目保持原所有者。无账本的旧 VM(老版本或 CLI 直接启动过)由 `stripLegacyManagedExtraArgs` 兜底,该函数随之迁入 macOS 代码。
|
||||
- **迁移方式**:在写锁下先备份受影响的小文件,一次替换 `state.json`,各步可重复执行,全部校验通过后才写版本戳 v3;与步骤 2a 的 VMRef 设置键转换共用一次 `state.json` 读取和写入,保留升级前原始备份。VM 目录、磁盘、快照、CoW 父盘与 `vm.toml` 不移动。
|
||||
- **反向棘轮**:新增"`internal/macos/` 只能导入列入清单的宿主包"的测试,清单从现状开始,只减不增。
|
||||
|
||||
**验收**
|
||||
- 从 v0.2.x 直升:用户关闭过的兼容选项与安装引导开关保持原值,手动设置的 `kernel-irqchip` 仍优先。
|
||||
- 迁移中途退出后重启,迁移可继续,结果与一次完成相同。
|
||||
- 同一台 VM 连续启动两次,参数不重复追加,辅助盘不重复挂载。
|
||||
|
||||
### 步骤 2:VM 引用与启动链路
|
||||
|
||||
**2a. `VMRef` 身份、内部索引与 list/start/stop 用户入口已落地**(原计划在步骤 3,提前是因为统一启动入口就要按归属解析 VM)
|
||||
|
||||
- 引入 `VMRef{DriverID, Name}`;`Router.ResolveVM` 遇到多个同名结果时返回歧义错误;`ListAllVMs` 不再按名称去重。
|
||||
- 驱动在清单中声明 VM 根目录(第 3 节),路由与"驱动不可用"扫描遍历所有已声明的根。
|
||||
- 宿主内存态、Guest Tools 注册表、缩略图与键入锁、日志来源改为按 `VMRef` 索引;对客体已经暴露的访问路径保留兼容。
|
||||
- `PluginRecord.VMSettings` 的键改为 `VMRef` 的规范字符串,与步骤 1 共用版本 v3 的一次写入:已有键全部归属 `builtin.driver.reims-macos`。
|
||||
- 界面进程交接参数增加驱动;只给名称且不重名时仍可用。
|
||||
|
||||
**2b. 驱动自有准备与第三方意图分开(已落地)**
|
||||
|
||||
- `Driver.Start` 改为接收启动请求:`VMRef`、第三方插件经 `vm.beforeStart` 给出的意图(参数片段、环境变量、启动后动作),以及日志输出。
|
||||
- 启动前检查(WHPX、运行时兼容)与启动准备由驱动自己完成。macOS 的离线辅助盘、恢复启动、引导语言、WHPX 兼容降级、Win10 冷重启、Guest Tools 辅助盘从 `vm.beforeStart` 移入 macOS 驱动的 `Start`,"先准备恢复环境,再写引导语言"的顺序由驱动保证。
|
||||
- 参数账本的合并与写入(对 reims 即 `reims-ctl set --extra-args`)由驱动执行,宿主以公共函数提供账本合并逻辑。
|
||||
- `vm.beforeStart` 只留给第三方插件,继续脱敏、限时、限参数族。驱动在完成全部第三方 Hook、无人否决之后才改动磁盘,因此不需要通用回滚:准备步骤保持可重复执行,任一步失败即中止启动并明确报错;用户选择恢复启动而准备失败时,不悄悄转为普通启动。
|
||||
- 特权按第 1 节的角色规则判定:驱动对自己的 VM 拥有完整参数控制;宿主内置插件保留现有白名单;其他插件按现有限制。
|
||||
|
||||
**2c. 统一入口与职责拆分(已落地)**
|
||||
|
||||
- 新增生命周期模块(暂名 `internal/lifecycle`),GUI 的 `StartVM` 与 CLI 的 `startVM` 都调用它,`startInWindow` 交给界面进程后同样进入它。宿主负责按 `VMRef` 解析驱动、串行化同一台 VM 的操作、派发事件(驱动 ID、运行时与能力取自该 VM)、任务与日志、进程退出监视。
|
||||
- **拆分 `vmstart`**:提交内存检查、P 核绑核、亲和性配置留在宿主;离线辅助盘、恢复标记与 OpenCore 相关步骤迁入 `internal/macos/`。
|
||||
- **拆分 Guest Tools**:传输、剪贴板与共享目录留在宿主(`guest-tools.transport` 服务),macOS 客体代理与辅助盘镜像(`BuildToolsDiskImage` 等)迁入 `internal/macos/`;镜像构建由 macOS 驱动在全部启动 Hook 通过后执行。
|
||||
- **拆分调优判定**:宿主只报告探测事实;驱动针对选中的 VM 结合运行时能力给出建议,设置页与实际启动共用同一份判定。`kernel-irqchip`、WHPX 兼容降级与冷重启补偿的策略归 macOS 驱动。
|
||||
|
||||
**验收**
|
||||
- 升级后用原有 macOS VM 验证:恢复引导、离线辅助盘、引导语言、冷重启监视、Guest Tools 与升级前行为一致;按 VM 的插件设置不丢失。
|
||||
- 第三方插件否决启动时,VM 目录与 OpenCore 镜像未被修改。
|
||||
- 测试驱动在相同宿主探测结果下,不会收到 OpenCore、辅助盘或冷重启参数。
|
||||
|
||||
### 步骤 3:其余入口统一路由(通用 App/CLI 已去 reims 直调,原生 macOS 流程按文件例外隔离)
|
||||
|
||||
- **后端**:VM 列表与轮询、详情、创建、设置、停止、重启、删除、日志、弹出安装介质,以及快照、克隆、磁盘、缩略图、统计、排障采集、亲和性等流程,全部经生命周期模块按 `VMRef` 路由。
|
||||
- **CLI**:`vm` 子命令全部走驱动层,重名时要求 `--driver`。顶层 `installer` 子命令改由 macOS 插件经 `commands` 扩展点贡献,宿主 CLI 提供插件命令转发。
|
||||
- **前端**:改用通用 VM 模型(名称、驱动、状态、CPU、内存、磁盘摘要、可用操作),按驱动能力位显示入口,后端执行时同样校验能力。`CreateWizard`、`SettingsModal` 中的 macOS 字段改为驱动的 `CreateSchema` / `SettingsSchema` 或插件页面。
|
||||
- **macOS 界面**:安装包页、在线恢复、版本图、OpenCore 设置由 macOS 插件贡献;过渡期经同一处注册表挂载 `frontend/src/macos/` 内的原生页面。
|
||||
|
||||
**验收**
|
||||
- 在测试装配中不注册 macOS 插件:工作台仍可用测试驱动完成"创建 → 启动 → 停止 → 删除"。
|
||||
- 两个驱动各有一台名为 `dev` 的 VM:两台都出现在列表、各自的按 VM 设置互不覆盖;停止其中一台只调用其所属驱动。
|
||||
- 恢复 macOS 插件后,原有 macOS VM 沿原路径启动,无需转换磁盘或重建配置。
|
||||
|
||||
### 步骤 3.5:宿主服务与按种类的运行时
|
||||
|
||||
Linux 驱动(步骤 4)与 macOS 外置(步骤 5)共同的前置条件,可在步骤 2 之后与步骤 3 并行开发。
|
||||
|
||||
- **按种类选定运行时**:配置改为每个运行时种类各记一个活跃运行时,随数据版本迁移现有的单值;只读操作在未选定时临时使用该种类最新安装的运行时、不写回配置,启动与创建前要求选定(待决,见第 9 节)。
|
||||
- **运行时与 reims 解耦**:`internal/runtime` 只保留按种类的通用安装、校验、切换与环境构造;reims-vgpu 的默认种类、`reims-ctl` / `reims-util` 路径、专用环境变量、按补丁推断能力与发布源,改由运行时种类声明提供(过渡期由 macOS 插件声明)。
|
||||
- **反向宿主接口扩充**(同时进入 `pkg/pluginsdk` 的公开类型):运行时查询(按种类返回路径与能力)、提交内存预检、绑核、日志与任务进度、进程退出通知、QMP 访问、VM 窗口信息与宿主明暗主题事件(安装引导浮层需要)。每项按权限校验。
|
||||
- **脱敏注册**:宿主提供通用脱敏层,插件可注册自己的脱敏规则;全局脱敏器、插件管理器、排障包与界面错误上报改用它。macOS 的规则由 macOS 插件注册。
|
||||
|
||||
### 步骤 4:Linux 最小驱动与驱动契约测试
|
||||
|
||||
- 新增与具体驱动无关的契约测试集(暂名 `internal/driver/drivertest`),对每个驱动运行同一组用例:生命周期调用的幂等与可重试边界、错误分类,以及"进程已启动 / 控制通道可用 / 客体已就绪"三种状态的区分。
|
||||
- Linux 驱动以独立仓库的 L3 插件实现,只依赖 `pkg/pluginsdk` 与反向宿主接口;先跑通一种镜像的创建、启动、停止与删除,再按 plugin-architecture.md Phase 4 的验收标准补齐。
|
||||
- 只有出现两份以上重复实现时,才从中提取磁盘或 QEMU 公共模块。
|
||||
|
||||
**验收**:契约测试同时覆盖 macOS 内置驱动与 Linux 驱动;Linux 驱动不修改主程序源码即可接入。
|
||||
|
||||
### 步骤 5:macOS 外置
|
||||
|
||||
前置条件:
|
||||
|
||||
- **外部插件页面**:整页插件页面(iframe,插件自带前端包,宿主提供主题令牌与到插件自身 Sidecar 的桥接)、创建向导步骤槽位、VM 详情分区槽位。桥接至少提供:宿主文件与目录选择(返回宿主路径交给插件 Sidecar,iframe 内不可见)、长任务的注册与流式进度(下载、取消、退出前拦截活跃任务)、由宿主绘制的对话框、iframe 高度自适应与焦点和快捷键传递。
|
||||
- **运行时需求声明**:插件在清单中声明需要的运行时种类与版本范围;缺少时宿主引导用户安装。运行时包不随插件安装事务自动拉取,插件之间的安装期依赖等出现真实用例再设计。
|
||||
- **语言与文案**:`macos-glossary.json`、`internal/i18n/glossary.go` 与各词表中的 macOS 文案迁入 macOS 插件的 `l10n`;第三方语言包对 macOS 文案的翻译改为针对该插件的 `pluginOverrides`。
|
||||
- **反向棘轮清零**:`internal/macos/` 不再导入任何宿主 `internal/` 包,只依赖 `pkg/`。
|
||||
- **声明式承接可用**:`replaces` 与 `aliases`(第 3 节)已实现并有测试。
|
||||
|
||||
外置本身:
|
||||
|
||||
- 迁出清单:`internal/macos/`、`frontend/src/macos/`、macOS 词表、`patches/`、`.github/workflows/build-runtime.yml`、`scripts/` 中的运行时打包与补丁脚本、`docs/portable-runtime-spec.md` 中 reims-vgpu 专属部分。用 `git filter-repo` 按清单生成 macOS 插件仓库,保留这部分历史;主仓库一次提交删除,并改写 README 与 AGENTS 中的产品定位。若历史本身也需剥离,改为反向拆分(第 9 节)。
|
||||
- 发布不含 macOS 的主程序:已有 macOS VM 因归属标记与 macOS 驱动声明的 VM 根仍在列表中,显示"需要安装对应驱动插件",由用户自行安装;主程序不自动安装、不默认推荐。用户安装外部 macOS 插件后,经声明式承接取回设置、账本与 VM 归属。
|
||||
|
||||
**验收**
|
||||
- 主仓库删除迁出清单后,构建、测试与两处棘轮全部通过;对 `macOS`、`OpenCore`、`reims`、`Apple` 等词的全仓检索只剩明确列出的例外(如"驱动不可用"提示中的通用说法)。
|
||||
- 安装外部 macOS 插件后,原有 macOS VM 无需转换即可启动,用户关闭过的选项保持关闭。
|
||||
|
||||
## 5. 顺序与并行
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
S0["步骤 0\n数据目录写入保护"] --> S1["步骤 1\nmacOS 插件身份\n与 v3 迁移"]
|
||||
S1 --> S2["步骤 2\nVMRef 与启动链路"]
|
||||
S2 --> S3["步骤 3\n其余入口统一路由"]
|
||||
S2 --> S35["步骤 3.5\n宿主服务与\n按种类的运行时"]
|
||||
S3 --> S4["步骤 4\nLinux 最小驱动"]
|
||||
S35 --> S4
|
||||
S3 --> S5["步骤 5\nmacOS 外置"]
|
||||
S35 --> S5
|
||||
P5["外部插件页面 · 承接机制\n语言迁出 · 反向棘轮清零"] --> S5
|
||||
```
|
||||
|
||||
- 步骤 0 不依赖其他决定,可以立即开始;步骤 1、2 开始前需定下第 3 节的身份模型与第 1 节的特权规则。
|
||||
- 步骤 3 与 3.5 可并行;外部插件页面、承接机制与语言迁出可在步骤 2 之后并行开发。
|
||||
- 以法律目标为准时,最快路径仍要经过步骤 1–3.5;跳过它们会让外置时再做一次数据与职责迁移。
|
||||
|
||||
## 6. 棘轮与检查
|
||||
|
||||
**宿主 → macOS**(现有,`internal/archtest` 与 `frontend/scripts/test-macos-boundary.mjs`):
|
||||
|
||||
| 例外 | 移除时机 |
|
||||
| :--- | :--- |
|
||||
| `internal/plugin/builtin`(仅源码的 Guest Tools 参数辅助) | 步骤 2:客体代理与辅助盘镜像迁出后移除;注册与测试例外已在步骤 1 移除 |
|
||||
| `internal/datamigrate` | 步骤 5:历史 v3 迁移改为不依赖 macOS 实现的通用数据迁移后移除 |
|
||||
| `internal/guesttools`(源码与测试) | 步骤 2:客体代理与辅助盘镜像迁出 |
|
||||
| `internal/plugin`(仅测试) | 步骤 3:Sidecar 测试改用通用测试替身 |
|
||||
| `internal/app`、`internal/cli` | 步骤 3:只剩一个组装文件注册 macOS 插件,例外细化到该文件 |
|
||||
| 前端 `App.tsx`、`Sidebar.tsx`、`VMPage.tsx` | 步骤 3:改为插件贡献 |
|
||||
| 组装文件 | 步骤 5:macOS 外置后删除 |
|
||||
|
||||
**macOS → 宿主 `internal/`**(步骤 1 新增):清单从现状开始,随步骤 2 与 3.5 把依赖改到 `pkg/`,步骤 5 前清零。
|
||||
|
||||
**非 import 耦合**:import 棘轮看不到第 2.5 节所列的词表、脱敏、运行时、前端字段等耦合。不为它们另建常驻检查;各自在所属步骤内迁移,步骤 5 以一次全仓检索作为验收。
|
||||
|
||||
## 7. 风险
|
||||
|
||||
| 风险 | 应对 |
|
||||
| :--- | :--- |
|
||||
| 迁移改坏用户数据 | 步骤 0 的写锁、只读模式与一次落盘;迁移前备份小文件;只动元数据,不动磁盘 |
|
||||
| 升级后 macOS VM 行为变化 | 每步以原有 macOS VM 做回归:恢复引导、辅助盘、引导语言、冷重启监视、Guest Tools、绑核 |
|
||||
| 特权模型改变引入越权 | "驱动对自己的 VM 拥有完整参数控制"只授予 VM 的所属驱动;`builtin.*` 的承接只允许 `official` 包或用户逐项确认;改动单独评审 |
|
||||
| `VMRef` 迁移遗漏某处按名索引的状态 | 步骤 2a 以"两台同名 VM"作为贯穿测试用例,覆盖设置、内存态、Guest Tools 与交接参数 |
|
||||
| 新旧版本混用 | 只读模式只保护新版本;降级支持的最低版本需明确公布(第 9 节) |
|
||||
| 步骤之间长期停留在半迁移状态 | 每步自成闭环、可单独发布;棘轮清单只减不增 |
|
||||
| 外部插件界面体验不及原生 | 过渡期保留原生页面;外置前以安装包页与恢复向导做可用性验收 |
|
||||
|
||||
## 8. 后续(不在本方案内)
|
||||
|
||||
触发条件出现时再立项:
|
||||
|
||||
- **稳定 VM ID**:VM 改名需要保持设置与历史、PID 复用或 CLI 超时重试出现实际问题时,引入 VM ID、一次开机的运行 ID 与一次长操作的操作 ID(参考 libvirt 的 UUID 与 containerd 将对象与运行分离的做法)。`VMRef` 届时作为人读入口保留。
|
||||
- **重新接管**:管理进程重启后重新连接正在运行的 VM,GUI 退出后 CLI 能找回同一次运行。
|
||||
- **常驻服务**:需要"GUI 退出后任务继续""多客户端订阅同一状态"或第三方程序调用时,再把生命周期模块放到用户级后台进程后,经 Windows 命名管道提供带版本的接口。
|
||||
- **整盘迁移**:换盘、换电脑做成停机导出与导入;验收为原数据目录完全不可访问时,目标机仍能从带 CoW 子盘的副本启动。
|
||||
- **升级交接**:进行中的创建、克隆、快照绑定发起时的驱动版本,运行中 VM 的控制权在重连验证后移交(参考 Magpie 插件宿主升级时的处理)。
|
||||
- **插件间安装期依赖**:出现"插件 A 必须与插件 B 一起安装"的真实用例后再设计,届时优先考虑只提示、不自动求解。
|
||||
|
||||
## 9. 待决事项
|
||||
|
||||
步骤 1 开始前需要定下:
|
||||
|
||||
1. **特权规则**:是否接受第 1 节"按角色授予特权"的规则,替代现有按 `builtin.` 前缀放行。
|
||||
2. **承接的信任要求**:承接 `builtin.*` ID 是只允许 `official` 包,还是也允许用户逐项确认。
|
||||
3. **过渡期 macOS 插件是否默认启用**:步骤 1 暂取默认启用,保证升级无感;默认关闭更贴近剥离方向,但存量用户升级后会看到"驱动不可用"。最终实现仍待评审。
|
||||
|
||||
可在后续步骤前决定:
|
||||
|
||||
4. **多运行时未选定时的行为**(步骤 3.5):建议只读操作临时使用最新安装的运行时、不写回配置,启动与创建前要求选定。
|
||||
5. **降级支持**(步骤 0 发布前):可安全退回的最低版本,以及只读模式的提示文案。
|
||||
6. **剥离范围**(步骤 5):法律风险具体涉及哪些内容(OpenCore 与 SMBIOS 处理、Apple 安装包下载、产品定位中的 macOS 字样、reims-vgpu 运行时),决定迁出清单的范围。
|
||||
7. **官方市场是否上架 macOS 插件**(步骤 5):上架方便用户,但官方索引仍与 macOS 产生关联。
|
||||
8. **代码历史**(步骤 5):只删除当前代码,还是让主程序以新仓库重新开始历史、本仓库保留为 macOS 插件仓库。
|
||||
@@ -60,7 +60,7 @@
|
||||
flowchart TB
|
||||
subgraph Exe["reims-go.exe(可信核心)"]
|
||||
Reg["扩展点注册表\n依赖解析 · 可逆副作用 · Reconcile"]
|
||||
Builtin["内置扩展(编译期注册)\n核心:reims 驱动 · 默认主题 · 启动准备 · 兼容补偿\n可选:宿客桥接 · 剪贴板 · 输入服务 · 窗口安装引导 · reims-vgpu 运行时种类"]
|
||||
Builtin["内置扩展(编译期注册)\n核心:默认主题\n可选:macOS 客体驱动 · 宿客桥接 · 剪贴板 · 输入服务 · reims-vgpu 运行时种类"]
|
||||
Mgr["插件管理器\n清单校验 · 事务安装 · 状态 · 安全模式"]
|
||||
Broker["Host API 代理\n权限校验 · 脱敏 · 限流 · 审计"]
|
||||
Sup["进程监管器\nJob Object · 重启退避 · 健康检查"]
|
||||
@@ -106,10 +106,11 @@ flowchart TB
|
||||
|
||||
扩展点先由内置功能使用一遍再对外开放。内置功能分两类,判断标准是用户关掉它之后,是「少了一项功能」还是「已有功能坏掉」:
|
||||
|
||||
- **核心** `builtin.core`:Reims-Go 离开它就无法运行 macOS 虚拟机的部分,包括 reims 驱动(驱动 id 仍为 `builtin.driver.reims-macos`)、默认主题(主题 id 仍为 `builtin.theme.default`)、启动准备(离线辅助盘、恢复模式引导切换、引导语言重放)与宿主兼容补偿(WHPX 降级、Win10 冷重启)。它是**系统插件**:始终启用,不能停用或卸载,插件页显示为一行「始终启用」,不参与「使用中」检查。两项兼容补偿作为核心的应用级设置保留开关,仅供排障。启动准备在同一个 `vm.beforeStart` 处理器里按固定顺序执行,引导语言重放必须在恢复模式切换(可能重建 OpenCore)之后。
|
||||
- **核心** `builtin.core`:只保留客体无关的默认主题(主题 id 为 `builtin.theme.default`)。它是**系统插件**:始终启用,不能停用或卸载,不出现在插件页与 `plugin list` 中(按 ID 查询仍可见),不参与「使用中」检查。
|
||||
- **macOS 客体插件** `builtin.guest.macos`:注册代码位于 `internal/macos/guest`,静态声明 reims 驱动(驱动 id 仍为 `builtin.driver.reims-macos`)、宿主体检、启动准备、WHPX 降级、Win10 冷重启和安装引导。它是可停用插件,过渡期默认启用以保留升级行为;有 VM 运行时不能停用,停用后宿主内的 macOS 原生页面与流程(创建、设置、Guest Tools 挂载、安装与恢复等)一并拒绝执行,直到重新启用。安装引导保留独立应用级开关。启动准备暂经 `vm.beforeStart`,下一步改由驱动自己执行,见 [guest-plugin-migration.md](guest-plugin-migration.md) 步骤 2。
|
||||
- **可选内置扩展**:Guest Tools 传输服务、剪贴板互通、宿主输入服务、虚拟机窗口安装引导。经同一注册表注册、可独立启停、停用后零残留,停用即真正停止(不被其他调用方重新拉起)。首批示例为默认开启的剪贴板互通(见 §5.4)。
|
||||
|
||||
核心由曾经拆开的七个内置插件合并而来(`builtin.RetiredIDs`)。启动时删除 `state.json` 中这些旧 ID 的记录,关闭过的兼容补偿转为对应的核心设置;启动 VM 时,参数归属账本中旧 ID 名下的片段移交给核心,继续沿用而不是被当作已卸载插件的残留剥离。
|
||||
旧版曾把 macOS 驱动、兼容补偿、安装引导与准备步骤拆成多个内置插件。数据布局 v2 的迁移删除这些旧 ID 的记录:显式设置与旧安装引导启停状态转入 `builtin.guest.macos`,参数账本中已知 macOS 条目也转给该插件;无关插件与宿主参数保持原所有者。
|
||||
|
||||
---
|
||||
|
||||
@@ -119,7 +120,8 @@ flowchart TB
|
||||
|
||||
- 每个已启用插件(含内置)拥有一个作用域,所有注册行为(提供服务、贡献扩展点、订阅事件、后台服务、Win32 钩子、QMP 监视)都登记一个释放函数;停用、卸载或升级时**逆序释放**,激活中途失败则回滚已登记项。
|
||||
- 插件声明 `requires` / `provides`(服务名 + 版本范围)。Reconcile 先关后开:先释放不再需要的插件及依赖其服务的插件,再按依赖求不动点激活。状态为 `off / pending / active / degraded / failed`。
|
||||
- **使用中不可移除**:仍有 VM 归属的驱动、仍被 VM 使用的运行时,不可停用或卸载;使用情况查询失败按「使用中」处理。
|
||||
- **使用中不可移除**:仍有 VM 归属的驱动不可卸载,仍被 VM 使用的运行时不可删除;使用情况查询失败按「使用中」处理。
|
||||
- **运行中不可停用**:驱动的 VM 只要有一台不是停止(或损坏)状态,就不能停用其插件;状态查询失败同样拒绝。只有已停止的 VM 时可以停用:VM 文件保留,显示为「驱动不可用」,不能启动或修改,重新启用后恢复。插件页停用这类插件前先弹窗说明。
|
||||
- 内置扩展通过 `pluginApi` 版本做兼容检查;激活 panic 转为 `failed` 并回滚。
|
||||
|
||||
### 4.2 扩展点目录
|
||||
@@ -228,16 +230,17 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
|
||||
### 5.3 非 macOS 虚拟机(客体驱动,L3)
|
||||
|
||||
**驱动抽象**:当前 `internal/app`、`internal/vmstart`、`internal/cli` 直接依赖 `internal/driver/reims` 的具体类型。抽象后:
|
||||
**驱动抽象**:当前 `internal/app`、`internal/vmstart`、`internal/cli` 直接依赖 `internal/macos/reims` 的具体类型。抽象后:
|
||||
|
||||
| 层 | 内容 |
|
||||
| :--- | :--- |
|
||||
| 通用 VM 模型 | 驱动 id + 名称、状态(`stopped / running / broken` 与过渡态)、CPU / 内存 / 磁盘摘要、目录、能力位 |
|
||||
| 驱动专有数据 | 不透明扩展字段 + 驱动提供的创建/设置 JSON Schema(宿主原生渲染,标注生效时机) |
|
||||
| 能力位 | `snapshot`、`cow_clone`、`resize`、`qmp`、`ssh`、`guest_tools`、`affinity`、`opencore`、`recovery`、`cloud_init`、`uefi_iso` 等;UI 与 CLI 按能力位显隐操作 |
|
||||
| 驱动动作 | `List / Show / ValidateCreate / Create / ValidateSet / Set / Start / Stop / Delete`,可选快照、派生、扩容与通用 `InvokeAction` |
|
||||
| 驱动动作 | `List / Show / ValidateCreate / Create / ValidateSet / Set / Start / Stop / Delete`,可选 `SnapshotDriver`、`CloneDriver`、`DiskDriver` 与通用 `InvokeAction`;存储调用由生命周期先解析 `VMRef`,结果使用 `driver.DiskSnapshot / DiskResizeResult / DiskCompactResult` |
|
||||
|
||||
- **VM 归属**:VM 目录内的标记文件 `.reims-go-driver` 记录驱动 id;无标记的存量 VM 归属 `builtin.driver.reims-macos`,并由数据迁移补写标记([architecture.md](architecture.md) §4.7)。有标记的 VM 在其驱动缺席时仍以「驱动不可用」列出。驱动迁到另一个插件、id 随之改变时(市场插件不能使用 `builtin.` 前缀),在 `driver.RenamedDriverIDs` 登记旧 id 到新 id 的映射;标记文件不改写,降级后旧版本仍能识别。CLI 增加 `vm create --driver <id>`,其余 `vm` 子命令按归属自动路由。
|
||||
- **VM 引用与根目录**:`driver.VMRef{DriverID, Name}` 的规范键为 `driverID:vmName`;`Router.ListAllVMs` 按完整引用去重,裸名称解析遇到跨驱动同名时返回歧义错误,调用方须显式指定驱动。每个 `guestDrivers` 条目用 `vmRoots` 声明相对 `<DataRoot>` 的斜杠路径,绝对路径、反斜杠与 `..` 均被拒绝;路由遍历所有已声明根(包括停用驱动)以保留「驱动不可用」条目。按 VM 的插件设置也以规范键持久化。
|
||||
- **宿主共享服务**(驱动经反向调用复用):体检报告、提交内存预检、大小核绑核、QMP 截屏与键入、缩略图、Guest Tools 注册、进程退出监视、任务进度、日志通道、托盘菜单。
|
||||
- **VM 进程归宿主托管**:驱动不直接派生 QEMU,而是请求宿主代为启动并返回 PID。这样 VM 进程不随驱动进程的 Job Object 被回收(驱动崩溃或重启不误杀 VM),绑核、退出监视与冷重启补偿也只在宿主实现一份。
|
||||
- **配置写入**:`reims-ctl set` 铁律约束 reims 管理的 VM;Linux 驱动自管配置文件,同样不允许 UI 拼接原始命令行。
|
||||
@@ -269,8 +272,10 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
| :--- | :--- | :--- |
|
||||
| `builtin.bridge.guest-tools` | `internal/guesttools`、`guesttools_flow.go` | 提供传输服务 + `vm.beforeStart`(注入桥接参数与环境变量)+ `vm.afterStart` + `vm.card`;共享文件夹、盘符共享、防休眠逐步拆为功能扩展 |
|
||||
| `builtin.input` | `host/ime_hook_windows.go` | 提供输入服务与 `inputFilters`;IME 桥成为其上的功能,停用时卸载钩子线程 |
|
||||
| `builtin.install-guide` | `internal/installguide`、`internal/app/install_guide.go` | 提供 `ui.install-guide` 服务 + `vm.afterStop` / `vm.deleted` 观察钩子;在虚拟机窗口悬浮展示安装与恢复引导,停用时立即关闭全部浮层并回退主界面恢复卡片 |
|
||||
| `builtin.core`(系统插件) | `driver/reims_adapter.go`、`vmstart.Prepare` 各步骤、`app.go` 冷重启监视 | `guestDrivers` + `themes` + `host.preflight` + 一个按序执行全部启动准备的 `vm.beforeStart`(离线辅助盘 → 恢复模式引导 → 引导语言 → WHPX 降级 → Win10 冷重启)+ `vm.afterStart` / `vm.afterStop`(冷重启监视);设置 `whpx_fallback`、`win10_cold_reboot` |
|
||||
| `builtin.guest.macos` | `internal/macos/guest`、`internal/macos/installguide`、`macosdriver`、`vmstart.Prepare` 各步骤 | 静态 `guestDrivers` + `host.preflight` + 驱动内启动准备与冷重启意图 + 条件提供的 `ui.install-guide` 服务;设置 `install_guide`、`whpx_fallback`、`win10_cold_reboot` |
|
||||
| `builtin.core`(系统插件) | `internal/plugin/builtin/core.go` | `themes`:默认主题 |
|
||||
|
||||
> 下一步:Guest Tools 的 macOS 客体代理与辅助盘镜像迁入 macOS 插件,传输服务留在宿主;启动准备改由驱动自己执行。见 [guest-plugin-migration.md](guest-plugin-migration.md) 步骤 2。
|
||||
|
||||
### 5.5 与上游补丁队列的边界
|
||||
|
||||
@@ -392,7 +397,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
| 入口 | 内容 |
|
||||
| :--- | :--- |
|
||||
| CLI | `reims-go plugin list / search / install <zip\|id> / update [id] / pack <dir> / link <dir> / enable [--approve-high-risk] / disable / remove [--purge] / info / doctor [--json] [dir\|zip\|id] / locale <init\|check> / run <id> <command>`;`vm create --driver <id>` |
|
||||
| 应用设置 → 插件 | 提供「已安装 / 插件市场」双视图(市场索引惰性加载):核心置顶、显示「始终启用」且无开关;其余显示来源与信任标签、权限摘要、安全扫描报告入口、启用开关、故障状态与日志入口;本地包导入前先展示三段式静态安全报告并执行硬门禁拦截 |
|
||||
| 应用设置 → 插件 | 提供「已安装 / 插件市场」双视图(市场索引惰性加载):系统插件(核心)不列出;其余显示来源与信任标签、权限摘要、安全扫描报告入口、启用开关、故障状态与日志入口;本地包导入前先展示三段式静态安全报告并执行硬门禁拦截 |
|
||||
| 插件设置页 | 由 `settings` Schema 渲染,复用现有设置控件,标注生效时机 |
|
||||
| VM 页面 | 按能力位显隐操作;`vm.toolbar` 菜单项支持 `when` 条件;`vm.card` 展示驱动或插件提供的键值信息 |
|
||||
| 创建向导 | 先选驱动,再按驱动 `CreateSchema` 渲染专属表单 |
|
||||
@@ -420,6 +425,8 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
|
||||
## 12. 分阶段演进与验收标准
|
||||
|
||||
从现有代码走到这里所述的客体驱动形态、并将 macOS 外置为插件的具体路径,见 [guest-plugin-migration.md](guest-plugin-migration.md)。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
P0["Phase 0\n内部抽象\n(不对外)"] --> P1["Phase 1\n插件底座 + L1\n(主题/模板/运行时源/规则 Hook)"]
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"test": "node --test scripts/test-i18n.mjs",
|
||||
"test": "node --test scripts/test-i18n.mjs scripts/test-macos-boundary.mjs",
|
||||
"build": "tsc --noEmit && vite build && node scripts/check-ui-contract.mjs",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// macOS UI lives under src/macos so it can leave the app as a plugin. Host
|
||||
// files may import from it only while listed below; the test fails when a new
|
||||
// file starts importing it and when a listed file stops, so the list only
|
||||
// shrinks (same ratchet as internal/archtest on the Go side).
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import ts from 'typescript'
|
||||
|
||||
const srcDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'src')
|
||||
const macosDir = path.join(srcDir, 'macos')
|
||||
|
||||
const MACOS_IMPORTERS = {
|
||||
'App.tsx': 'mounts the installers page and online-recovery dialog; macOS release names in the VM list',
|
||||
'components/Sidebar.tsx': 'macOS version art next to each VM',
|
||||
'components/VMPage.tsx': 'macOS version art in the VM header',
|
||||
}
|
||||
|
||||
function walk(dir) {
|
||||
const out = []
|
||||
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, e.name)
|
||||
if (e.isDirectory()) {
|
||||
if (p !== macosDir) out.push(...walk(p))
|
||||
} else if (/\.(?:[cm]?[jt]s|[jt]sx)$/.test(e.name)) {
|
||||
out.push(p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
test('host frontend reaches src/macos only from listed files', () => {
|
||||
const importers = new Set()
|
||||
for (const file of walk(srcDir)) {
|
||||
const text = fs.readFileSync(file, 'utf8')
|
||||
for (const { fileName } of ts.preProcessFile(text, true, true).importedFiles) {
|
||||
let target
|
||||
if (fileName.startsWith('.')) target = path.resolve(path.dirname(file), fileName)
|
||||
else if (fileName.startsWith('/src/')) target = path.resolve(srcDir, fileName.slice(5))
|
||||
else continue
|
||||
if (target === macosDir || target.startsWith(macosDir + path.sep)) {
|
||||
importers.add(path.relative(srcDir, file).split(path.sep).join('/'))
|
||||
}
|
||||
}
|
||||
}
|
||||
const unexpected = [...importers].filter((f) => !(f in MACOS_IMPORTERS)).sort()
|
||||
const stale = Object.keys(MACOS_IMPORTERS).filter((f) => !importers.has(f)).sort()
|
||||
assert.deepEqual(unexpected, [], `host files import src/macos without being listed in MACOS_IMPORTERS: ${unexpected.join(', ')}`)
|
||||
assert.deepEqual(stale, [], `listed files no longer import src/macos; remove them from MACOS_IMPORTERS: ${stale.join(', ')}`)
|
||||
})
|
||||
+101
-69
@@ -3,21 +3,23 @@ import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from
|
||||
import type { WizardDraft } from './components/CreateWizard'
|
||||
import { DeleteDialog } from './components/DeleteDialog'
|
||||
import { CloneDialog } from './components/CloneDialog'
|
||||
import { OnlineRecoveryDialog } from './components/OnlineRecoveryDialog'
|
||||
import { OnlineRecoveryDialog } from './macos/OnlineRecoveryDialog'
|
||||
import { SendTextDialog } from './components/SendTextDialog'
|
||||
import type { ThemeMode } from './components/AppSettingsPage'
|
||||
import { LogPanel, LogTab } from './components/LogPanel'
|
||||
import { TitleMenus } from './components/TitleMenus'
|
||||
import { UpdateCapsule, UpdatePhase } 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'
|
||||
import { VMAction, VMPage } from './components/VMPage'
|
||||
import { buildFallbackChain, I18nKey, localeDir, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
|
||||
import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format'
|
||||
import { LogLine, appendLog } from './lib/logs'
|
||||
import { macOSMajor } from './lib/macosRelease'
|
||||
import { macOSMajor } from './macos/macosRelease'
|
||||
import { currentTask, finishedTaskTTL, isActiveInstallerTask, pruneFinishedTasks, upsertTask } from './lib/tasks'
|
||||
import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, notifyInteractiveThemeState, type UIStateSnapshot } from './lib/themeEngine'
|
||||
import { latestVMStats, refreshSubscribedVMStats, refreshVMStats } from './lib/vmStats'
|
||||
import { latestVMStatsWithDriver, refreshSubscribedVMStats, refreshVMStatsWithDriver } from './lib/vmStats'
|
||||
import { vmRefKey } from './lib/vmRef'
|
||||
import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail } from './types'
|
||||
import { Button, Tip, TooltipProvider } from './ui/controls'
|
||||
import { ConfirmDialog, Modal } from './ui/dialog'
|
||||
@@ -32,7 +34,7 @@ const SettingsModal = lazy(() => import('./components/SettingsModal').then((m) =
|
||||
const AffinityDialog = lazy(() => import('./components/AffinityDialog').then((m) => ({ default: m.AffinityDialog })))
|
||||
const Setup = lazy(() => import('./components/Setup').then((m) => ({ default: m.Setup })))
|
||||
const HostView = lazy(() => import('./components/HostView').then((m) => ({ default: m.HostView })))
|
||||
const InstallersPage = lazy(() => import('./components/InstallersPage').then((m) => ({ default: m.InstallersPage })))
|
||||
const InstallersPage = lazy(() => import('./macos/InstallersPage').then((m) => ({ default: m.InstallersPage })))
|
||||
const PluginsPage = lazy(() => import('./components/PluginsPage').then((m) => ({ default: m.PluginsPage })))
|
||||
const AppSettingsPage = lazy(() => import('./components/AppSettingsPage').then((m) => ({ default: m.AppSettingsPage })))
|
||||
const AboutPage = lazy(() => import('./components/AboutPage').then((m) => ({ default: m.AboutPage })))
|
||||
@@ -85,11 +87,11 @@ export const App: React.FC = () => {
|
||||
const [showWizard, setShowWizard] = useState(false)
|
||||
const [wizardDraft, setWizardDraft] = useState<WizardDraft | null>(null)
|
||||
const [showSettings, setShowSettings] = useState(false)
|
||||
const [affinityTarget, setAffinityTarget] = useState<string | null>(null)
|
||||
const [affinityTarget, setAffinityTarget] = useState<{ name: string; driverID: string } | null>(null)
|
||||
const [affinityVersion, setAffinityVersion] = useState(0)
|
||||
const [deleteTarget, setDeleteTarget] = useState<string | null>(null)
|
||||
const [discardSuspendTarget, setDiscardSuspendTarget] = useState<string | null>(null)
|
||||
const [cloneSource, setCloneSource] = useState<string | null>(null)
|
||||
const [cloneSource, setCloneSource] = useState<{ name: string; driverID: string } | null>(null)
|
||||
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
|
||||
const [sendTextTarget, setSendTextTarget] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState<Record<string, VMAction>>({})
|
||||
@@ -197,8 +199,8 @@ export const App: React.FC = () => {
|
||||
setLoadError('')
|
||||
setSelected((cur) => {
|
||||
if (PAGE_IDS.includes(cur)) return cur
|
||||
if ((s.vms ?? []).some((v) => v.name === cur)) return cur
|
||||
return s.vms && s.vms.length > 0 ? s.vms[0].name : HOST_ID
|
||||
if ((s.vms ?? []).some((v) => vmRefKey(v) === cur || v.name === cur)) return cur
|
||||
return s.vms && s.vms.length > 0 ? vmRefKey(s.vms[0]) : HOST_ID
|
||||
})
|
||||
if (reloadDetail) setDetailRevision((revision) => revision + 1)
|
||||
} catch (e) {
|
||||
@@ -267,15 +269,15 @@ export const App: React.FC = () => {
|
||||
}, [refresh])
|
||||
|
||||
const vms = state?.vms ?? []
|
||||
const runningVMCount = vms.filter((v) => (state?.transitions[v.name] ?? v.state) === 'running').length
|
||||
const runningVMCount = vms.filter((v) => (state?.transitions[vmRefKey(v)] ?? v.state) === 'running').length
|
||||
const selectedVM = !PAGE_IDS.includes(selected)
|
||||
? vms.find((v) => v.name === selected)
|
||||
? vms.find((v) => vmRefKey(v) === selected) ?? vms.find((v) => v.name === selected)
|
||||
: undefined
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedVM) { setDetail(null); return }
|
||||
api.GetVMDetail(selectedVM.name).then(setDetail).catch(() => setDetail(null))
|
||||
}, [selectedVM?.name, selectedVM?.state, state?.transitions[selectedVM?.name ?? ''], detailRevision])
|
||||
}, [selectedVM?.name, selectedVM?.driver_id, selectedVM?.state, state?.transitions[selectedVM ? vmRefKey(selectedVM) : ''], detailRevision])
|
||||
|
||||
// Display names (the VM's note, .reims-go-note): shown in place of the VM's
|
||||
// name in the sidebar and page title; the name itself stays the identifier.
|
||||
@@ -332,8 +334,8 @@ export const App: React.FC = () => {
|
||||
|
||||
useEffect(() => () => { disposeActiveThemeAndLocaleFonts() }, [])
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const effectiveState = selectedVM ? (state?.transitions[selectedVM.name] ?? selectedVM.state) : ''
|
||||
const pending = selectedVM ? (state?.pending_changes[selectedVM.name] ?? []) : []
|
||||
const effectiveState = selectedVM ? (state?.transitions[vmRefKey(selectedVM)] ?? selectedVM.state) : ''
|
||||
const pending = selectedVM ? (state?.pending_changes[vmRefKey(selectedVM)] ?? []) : []
|
||||
const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime
|
||||
const canSuspend = state?.can_suspend ?? false
|
||||
|
||||
@@ -451,6 +453,9 @@ export const App: React.FC = () => {
|
||||
setSetupStage(s?.active_runtime ? null : 'runtime')
|
||||
}
|
||||
const showSetup = !!state && (state.needs_setup || 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
|
||||
|
||||
// UI Contract v1 read-only document state attributes (§5.1).
|
||||
const currentView = showSetup ? 'setup' : selected === HOST_ID ? 'host' : selected === INSTALLERS_ID ? 'installers' : selected === PLUGINS_ID ? 'plugins' : selected === SETTINGS_ID ? 'settings' : selected === ABOUT_ID ? 'about' : 'vm'
|
||||
@@ -468,7 +473,7 @@ export const App: React.FC = () => {
|
||||
hasError: hasAnyError,
|
||||
sidebarCollapsed: !sidebarOpen,
|
||||
safeMode: !!state?.safe_mode,
|
||||
vms: vms.map((v) => ({ name: v.name, state: state?.transitions[v.name] ?? v.state })),
|
||||
vms: vms.map((v) => ({ name: v.name, state: state?.transitions[vmRefKey(v)] ?? v.state })),
|
||||
})
|
||||
uiStateRef.current = {
|
||||
appearance: theme,
|
||||
@@ -482,7 +487,7 @@ export const App: React.FC = () => {
|
||||
hasError: hasAnyError,
|
||||
sidebarCollapsed: !sidebarOpen,
|
||||
safeMode: !!state?.safe_mode,
|
||||
vms: vms.map((v) => ({ name: v.name, state: state?.transitions[v.name] ?? v.state })),
|
||||
vms: vms.map((v) => ({ name: v.name, state: state?.transitions[vmRefKey(v)] ?? v.state })),
|
||||
}
|
||||
useEffect(() => {
|
||||
const el = document.documentElement
|
||||
@@ -529,7 +534,8 @@ export const App: React.FC = () => {
|
||||
const loadVMLog = async (serial: boolean, name = selectedVM?.name) => {
|
||||
if (!name) return
|
||||
try {
|
||||
const text = await api.ReadVMLogs(name, serial)
|
||||
const logDriverID = vms.find((v) => v.name === name)?.driver_id ?? ''
|
||||
const text = await api.ReadVMLogsWithDriver(logDriverID, name, serial)
|
||||
if (serial) setSerialLog(text)
|
||||
else setQemuLog(text)
|
||||
} catch (e) {
|
||||
@@ -661,6 +667,9 @@ export const App: React.FC = () => {
|
||||
}
|
||||
|
||||
const onVMActionFor = (name: string, action: VMAction, isRunning: boolean) => {
|
||||
const actionVM = vms.find((v) => vmRefKey(v) === name) ?? vms.find((v) => v.name === name)
|
||||
const actionDriverID = actionVM?.driver_id ?? ''
|
||||
name = actionVM?.name ?? name
|
||||
if (!canSuspend && (action === 'suspend' || action === 'resume')) return
|
||||
const activeBusy = activeVMBusy(name)
|
||||
if (
|
||||
@@ -672,21 +681,21 @@ export const App: React.FC = () => {
|
||||
return
|
||||
}
|
||||
switch (action) {
|
||||
case 'start': return runVMAction(name, action, () => api.StartVM(name))
|
||||
case 'suspend': return runVMAction(name, action, () => api.SuspendVM(name), tr('toastSuspended', { name }))
|
||||
case 'resume': return runVMAction(name, action, () => api.ResumeVM(name), tr('toastResumed', { name }))
|
||||
case 'discardSuspend': return setDiscardSuspendTarget(name)
|
||||
case 'focus': return api.FocusVMWindow(name).catch((e) => fail(tr('failFocus'), e))
|
||||
case 'start': return runVMAction(name, action, () => api.StartVMWithDriver(actionDriverID, name))
|
||||
case 'suspend': return runVMAction(name, action, () => api.SuspendVMWithDriver(actionDriverID, name), tr('toastSuspended', { name }))
|
||||
case 'resume': return runVMAction(name, action, () => api.ResumeVMWithDriver(actionDriverID, name), tr('toastResumed', { name }))
|
||||
case 'discardSuspend': return setDiscardSuspendTarget(actionVM ? vmRefKey(actionVM) : name)
|
||||
case 'focus': return api.FocusVMWindowWithDriver(actionDriverID, name).catch((e) => fail(tr('failFocus'), e))
|
||||
case 'fullscreen':
|
||||
return runVMAction(name, action, async () => {
|
||||
const isFullscreen = await api.ToggleVMFullscreen(name)
|
||||
refreshVMStats(name, { window_fullscreen: isFullscreen })
|
||||
const isFullscreen = await api.ToggleVMFullscreenWithDriver(actionDriverID, name)
|
||||
refreshVMStatsWithDriver(actionDriverID, name, { window_fullscreen: isFullscreen })
|
||||
})
|
||||
case 'screenshot': return runVMAction(name, action, () => api.CopyVMScreenshot(name), tr('toastScreenshotCopied'))
|
||||
case 'stop': return runVMAction(name, action, () => api.StopVM(name, false), tr('toastStopped', { name }))
|
||||
case 'forceStop': return runVMAction(name, action, () => api.StopVM(name, true), tr('toastStopped', { name }))
|
||||
case 'restart': return runVMAction(name, action, () => api.RestartVM(name))
|
||||
case 'eject': return runVMAction(name, action, () => api.EjectInstaller(name), tr('toastEjected'))
|
||||
case 'screenshot': return runVMAction(name, action, () => api.CopyVMScreenshotWithDriver(actionDriverID, name), tr('toastScreenshotCopied'))
|
||||
case 'stop': return runVMAction(name, action, () => api.StopVMWithDriver(actionDriverID, name, false), tr('toastStopped', { name }))
|
||||
case 'forceStop': return runVMAction(name, action, () => api.StopVMWithDriver(actionDriverID, name, true), tr('toastStopped', { name }))
|
||||
case 'restart': return runVMAction(name, action, () => api.RestartVMWithDriver(actionDriverID, name))
|
||||
case 'eject': return runVMAction(name, action, () => api.EjectInstallerWithDriver(actionDriverID, name), tr('toastEjected'))
|
||||
case 'finishInstall': return runVMAction(name, action, () => api.FinishInstall(name), tr(isRunning ? 'toastExitRecoveryNextStart' : 'toastInstallFinished'))
|
||||
case 'enterRecovery': return runVMAction(name, action, () => api.EnterRecovery(name), tr(isRunning ? 'toastEnterRecoveryNextStart' : 'toastEnterRecovery'))
|
||||
case 'attachInstaller': return attachInstaller(name, isRunning)
|
||||
@@ -697,29 +706,29 @@ export const App: React.FC = () => {
|
||||
case 'upgradeNVMe':
|
||||
return runVMAction(name, action, () => api.UpgradeDiskToNVMe(name), tr(isRunning ? 'toastNVMeNextStart' : 'toastNVMeReady'))
|
||||
case 'exportDiagnostics':
|
||||
return runVMAction(name, action, async () => { await api.ExportDiagnostics(name) }, tr('toastDiagExported'))
|
||||
return runVMAction(name, action, async () => { await api.ExportDiagnosticsWithDriver(actionDriverID, name) }, tr('toastDiagExported'))
|
||||
case 'cloneVM':
|
||||
return setCloneSource(name)
|
||||
return setCloneSource({ name, driverID: actionDriverID })
|
||||
case 'type': return typeInto(name, () => api.TypeClipboard(name))
|
||||
case 'sendText': return setSendTextTarget(name)
|
||||
case 'openFolder':
|
||||
return api.OpenVMFolder(name).catch((e) => fail(tr('failOpenFolder'), e))
|
||||
case 'delete': return setDeleteTarget(name)
|
||||
case 'delete': return setDeleteTarget(actionVM ? vmRefKey(actionVM) : name)
|
||||
}
|
||||
}
|
||||
|
||||
const onVMAction = (action: VMAction) => {
|
||||
if (!selectedVM) return
|
||||
return onVMActionFor(selectedVM.name, action, selectedVM.state === 'running')
|
||||
return onVMActionFor(vmRefKey(selectedVM), action, selectedVM.state === 'running')
|
||||
}
|
||||
|
||||
const onSidebarContextAction = (name: string, action: VMAction | 'settings') => {
|
||||
const vm = vms.find((v) => v.name === name)
|
||||
const st = state?.transitions[name] ?? vm?.state ?? 'stopped'
|
||||
const vm = vms.find((v) => vmRefKey(v) === name) ?? vms.find((v) => v.name === name)
|
||||
const st = state?.transitions[vm ? vmRefKey(vm) : name] ?? vm?.state ?? 'stopped'
|
||||
if (action === 'settings') {
|
||||
if (st === 'suspended' || st === 'suspending' || st === 'resuming') return
|
||||
setSelected(name)
|
||||
api.GetVMDetail(name).then((d) => { setDetail(d); setShowSettings(true) }).catch((e) => fail(tr('failGeneric'), e))
|
||||
api.GetVMDetail(vm?.name ?? name).then((d) => { setDetail(d); setShowSettings(true) }).catch((e) => fail(tr('failGeneric'), e))
|
||||
return
|
||||
}
|
||||
onVMActionFor(name, action, st === 'running')
|
||||
@@ -728,24 +737,31 @@ export const App: React.FC = () => {
|
||||
// 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.
|
||||
const primaryAction = (name: string) => {
|
||||
const vm = vms.find((v) => v.name === name)
|
||||
if (!vm || activeVMBusy(name)) return
|
||||
const st = state?.transitions[name] ?? vm.state
|
||||
if (st === 'stopped') onVMActionFor(name, 'start', false)
|
||||
else if (st === 'suspended') onVMActionFor(name, 'resume', false)
|
||||
else if (st === 'running') onVMActionFor(name, 'focus', true)
|
||||
const vm = vms.find((v) => vmRefKey(v) === name) ?? vms.find((v) => v.name === name)
|
||||
if (!vm || activeVMBusy(vm.name)) return
|
||||
const key = vmRefKey(vm)
|
||||
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)
|
||||
}
|
||||
|
||||
const confirmDelete = (keepFiles: boolean) => {
|
||||
const name = deleteTarget
|
||||
const target = deleteTarget
|
||||
setDeleteTarget(null)
|
||||
if (name) runVMAction(name, 'delete', () => api.DeleteVM(name, keepFiles), tr('toastDeleted', { name }))
|
||||
const targetVM = vms.find((v) => vmRefKey(v) === target) ?? vms.find((v) => v.name === target)
|
||||
const name = targetVM?.name ?? target
|
||||
const driverID = targetVM?.driver_id ?? ''
|
||||
if (name) runVMAction(name, 'delete', () => api.DeleteVMWithDriver(driverID, name, keepFiles), tr('toastDeleted', { name }))
|
||||
}
|
||||
|
||||
const confirmDiscardSuspend = () => {
|
||||
const name = discardSuspendTarget
|
||||
const target = discardSuspendTarget
|
||||
setDiscardSuspendTarget(null)
|
||||
if (name) runVMAction(name, 'discardSuspend', () => api.DiscardSuspend(name), tr('toastDiscardSuspend', { name }))
|
||||
const targetVM = vms.find((v) => vmRefKey(v) === target) ?? vms.find((v) => v.name === target)
|
||||
const name = targetVM?.name ?? target
|
||||
const driverID = targetVM?.driver_id ?? ''
|
||||
if (name) runVMAction(name, 'discardSuspend', () => api.DiscardSuspendWithDriver(driverID, name), tr('toastDiscardSuspend', { name }))
|
||||
}
|
||||
|
||||
const confirmOnlineRecovery = () => {
|
||||
@@ -761,9 +777,9 @@ export const App: React.FC = () => {
|
||||
const src = cloneSource
|
||||
setCloneSource(null)
|
||||
if (!src) return
|
||||
runVMAction(src, 'cloneVM', async () => {
|
||||
await api.CloneVMCoW(src, cloneName)
|
||||
setSelected(cloneName)
|
||||
runVMAction(src.name, 'cloneVM', async () => {
|
||||
await api.CloneVMCoWWithDriver(src.driverID, src.name, cloneName)
|
||||
setSelected(vmRefKey({ name: cloneName, driver_id: src.driverID }))
|
||||
}, tr('toastCloned', { name: cloneName }))
|
||||
}
|
||||
|
||||
@@ -874,7 +890,7 @@ export const App: React.FC = () => {
|
||||
|
||||
// Global shortcuts (docs/design-guidelines.md §6). Dialogs own the keyboard while open.
|
||||
const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {})
|
||||
const appDialogOpen = showSetup || showWizard || showSettings || affinityTarget || deleteTarget ||
|
||||
const appDialogOpen = showSetup || showReadOnly || showWizard || showSettings || affinityTarget || deleteTarget ||
|
||||
discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate
|
||||
shortcutRef.current = (e: KeyboardEvent) => {
|
||||
if (!e.ctrlKey || e.altKey || e.metaKey) return
|
||||
@@ -885,7 +901,7 @@ export const App: React.FC = () => {
|
||||
else if (k === ',' && detail && effectiveState !== 'suspended' && effectiveState !== 'suspending' && effectiveState !== 'resuming') { e.preventDefault(); setShowSettings(true) }
|
||||
else if (k === 'l') { e.preventDefault(); toggleLogs() }
|
||||
else if (k === 'b' && !showSetup) { e.preventDefault(); toggleSidebar() }
|
||||
else if (k === 'enter' && selectedVM && !e.shiftKey) { e.preventDefault(); primaryAction(selectedVM.name) }
|
||||
else if (k === 'enter' && selectedVM && !e.shiftKey) { e.preventDefault(); primaryAction(vmRefKey(selectedVM)) }
|
||||
}
|
||||
useEffect(() => {
|
||||
const h = (e: KeyboardEvent) => shortcutRef.current(e)
|
||||
@@ -952,7 +968,7 @@ export const App: React.FC = () => {
|
||||
<TooltipProvider>
|
||||
<div className="app-shell rg-p-shell">
|
||||
<header className="titlebar rg-p-titlebar" onDoubleClick={() => WindowToggleMaximise()}>
|
||||
{showSetup || !state ? (
|
||||
{showSetup || showReadOnly || !state ? (
|
||||
<div className="brand rg-p-brand">
|
||||
<img className="brand-mark" src="/logo.svg" alt="" aria-hidden="true" />
|
||||
Reims-Go
|
||||
@@ -970,6 +986,7 @@ export const App: React.FC = () => {
|
||||
onThemeMode={setThemeMode}
|
||||
vm={selectedVM ? {
|
||||
name: selectedVM.name,
|
||||
driver_id: selectedVM.driver_id,
|
||||
state: effectiveState,
|
||||
busy: Object.prototype.hasOwnProperty.call(busy, selectedVM.name),
|
||||
graphics: detail?.name === selectedVM.name ? detail.graphics : undefined,
|
||||
@@ -1033,6 +1050,14 @@ export const App: React.FC = () => {
|
||||
onImportRuntime={importRuntime}
|
||||
/>
|
||||
</Suspense>
|
||||
) : showReadOnly && state ? (
|
||||
<DataRootReadOnly
|
||||
locale={locale}
|
||||
status={state.data_root_status}
|
||||
message={state.data_root_message ?? ''}
|
||||
onChanged={() => { void refresh() }}
|
||||
onError={fail}
|
||||
/>
|
||||
) : (
|
||||
<div className={`workspace rg-p-workspace${sidebarOpen ? '' : ' sidebar-hidden'}`}>
|
||||
{sidebarOpen && <div className="sidebar-backdrop" aria-hidden="true" onClick={toggleSidebar} />}
|
||||
@@ -1098,6 +1123,7 @@ export const App: React.FC = () => {
|
||||
<VMPage
|
||||
locale={locale}
|
||||
name={selectedVM.name}
|
||||
driverID={selectedVM.driver_id ?? ''}
|
||||
displayName={displayNames[selectedVM.name] ?? ''}
|
||||
onDisplayNameSaved={(n) => setDisplayNames((m) => ({ ...m, [selectedVM.name]: n }))}
|
||||
macosMajor={macosMajors[selectedVM.name] ?? null}
|
||||
@@ -1111,7 +1137,7 @@ export const App: React.FC = () => {
|
||||
busyAction={Object.prototype.hasOwnProperty.call(busy, selectedVM.name) ? busy[selectedVM.name] : undefined}
|
||||
onAction={onVMAction}
|
||||
onSettings={() => setShowSettings(true)}
|
||||
onOpenAffinity={() => setAffinityTarget(selectedVM.name)}
|
||||
onOpenAffinity={() => setAffinityTarget({ name: selectedVM.name, driverID: selectedVM.driver_id ?? '' })}
|
||||
onDelete={() => setDeleteTarget(selectedVM.name)}
|
||||
onViewLogs={() => { openLogs('serial'); loadSerial() }}
|
||||
onCopy={copy}
|
||||
@@ -1238,13 +1264,14 @@ export const App: React.FC = () => {
|
||||
<SettingsModal
|
||||
locale={locale}
|
||||
detail={detail}
|
||||
stats={latestVMStats(detail.name)}
|
||||
driverID={selectedVM?.driver_id ?? ''}
|
||||
stats={latestVMStatsWithDriver(selectedVM?.driver_id ?? '', detail.name)}
|
||||
host={state.host}
|
||||
optimizations={state.optimizations}
|
||||
running={effectiveState === 'running'}
|
||||
onCopy={copy}
|
||||
onDiskChanged={refresh}
|
||||
onOpenAffinity={() => setAffinityTarget(detail.name)}
|
||||
onOpenAffinity={() => setAffinityTarget({ name: detail.name, driverID: selectedVM?.driver_id ?? '' })}
|
||||
affinityVersion={affinityVersion}
|
||||
onHostChanged={refresh}
|
||||
onClose={() => setShowSettings(false)}
|
||||
@@ -1261,8 +1288,9 @@ export const App: React.FC = () => {
|
||||
<Suspense fallback={null}>
|
||||
<AffinityDialog
|
||||
locale={locale}
|
||||
vmName={affinityTarget}
|
||||
vcpus={detail?.name === affinityTarget ? detail.cpus : 4}
|
||||
vmName={affinityTarget.name}
|
||||
driverID={affinityTarget.driverID}
|
||||
vcpus={detail?.name === affinityTarget.name ? detail.cpus : 4}
|
||||
host={state.host}
|
||||
globalAutoPin={state.config.auto_pin_pcores}
|
||||
onClose={() => setAffinityTarget(null)}
|
||||
@@ -1307,22 +1335,26 @@ export const App: React.FC = () => {
|
||||
<DeleteDialog locale={locale} name={deleteTarget} onCancel={() => setDeleteTarget(null)} onConfirm={confirmDelete} />
|
||||
)}
|
||||
|
||||
{discardSuspendTarget && (
|
||||
<ConfirmDialog
|
||||
title={tr('discardSuspendTitle', { name: displayNames[discardSuspendTarget] || discardSuspendTarget })}
|
||||
description={tr('discardSuspendDesc')}
|
||||
cancelLabel={tr('cancel')}
|
||||
confirmLabel={tr('discardSuspendConfirm')}
|
||||
onCancel={() => setDiscardSuspendTarget(null)}
|
||||
onConfirm={confirmDiscardSuspend}
|
||||
/>
|
||||
)}
|
||||
{discardSuspendTarget && (() => {
|
||||
const targetVM = vms.find((v) => vmRefKey(v) === discardSuspendTarget) ?? vms.find((v) => v.name === discardSuspendTarget)
|
||||
const targetName = targetVM?.name ?? discardSuspendTarget
|
||||
return (
|
||||
<ConfirmDialog
|
||||
title={tr('discardSuspendTitle', { name: displayNames[targetName] || targetName })}
|
||||
description={tr('discardSuspendDesc')}
|
||||
cancelLabel={tr('cancel')}
|
||||
confirmLabel={tr('discardSuspendConfirm')}
|
||||
onCancel={() => setDiscardSuspendTarget(null)}
|
||||
onConfirm={confirmDiscardSuspend}
|
||||
/>
|
||||
)
|
||||
})()}
|
||||
|
||||
{cloneSource && (
|
||||
<CloneDialog
|
||||
locale={locale}
|
||||
sourceName={cloneSource}
|
||||
defaultCloneName={`${cloneSource}-clone`}
|
||||
sourceName={cloneSource.name}
|
||||
defaultCloneName={`${cloneSource.name}-clone`}
|
||||
onCancel={() => setCloneSource(null)}
|
||||
onConfirm={confirmClone}
|
||||
/>
|
||||
@@ -1341,7 +1373,7 @@ export const App: React.FC = () => {
|
||||
<SendTextDialog
|
||||
locale={locale}
|
||||
vmName={sendTextTarget}
|
||||
guestToolsConnected={Boolean(latestVMStats(sendTextTarget)?.guest_tools_connected ?? detail?.guest_tools_connected)}
|
||||
guestToolsConnected={Boolean(latestVMStatsWithDriver(selectedVM?.driver_id ?? '', sendTextTarget)?.guest_tools_connected ?? detail?.guest_tools_connected)}
|
||||
onCancel={() => setSendTextTarget(null)}
|
||||
onConfirm={(text) => {
|
||||
const target = sendTextTarget
|
||||
|
||||
@@ -11,6 +11,7 @@ import { api } from '../wails'
|
||||
interface Props {
|
||||
locale: Locale
|
||||
vmName: string
|
||||
driverID: string
|
||||
vcpus: number
|
||||
host: HostReport
|
||||
globalAutoPin: boolean
|
||||
@@ -79,7 +80,7 @@ export function formatAffinitySummary(locale: Locale, status: VMAffinityStatus |
|
||||
}
|
||||
|
||||
export const AffinityDialog: React.FC<Props> = ({
|
||||
locale, vmName, vcpus, host, globalAutoPin, onClose, onApplied,
|
||||
locale, vmName, driverID, vcpus, host, globalAutoPin, onClose, onApplied,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const topology = useMemo(() => buildTopology(host), [host])
|
||||
@@ -99,7 +100,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
let live = true
|
||||
setLoading(true)
|
||||
setErr('')
|
||||
api.GetVMAffinity(vmName)
|
||||
api.GetVMAffinityWithDriver(driverID, vmName)
|
||||
.then((st) => {
|
||||
if (!live) return
|
||||
setStatus(st)
|
||||
@@ -205,7 +206,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
setSaving(true)
|
||||
setErr('')
|
||||
try {
|
||||
const updated = await api.SetVMAffinity(vmName, {
|
||||
const updated = await api.SetVMAffinityWithDriver(driverID, vmName, {
|
||||
mode,
|
||||
cpus: mode === 'custom' ? selected : [],
|
||||
disable_eco_qos: disableEcoQoS,
|
||||
|
||||
@@ -58,7 +58,7 @@ interface Props {
|
||||
|
||||
const REVIEW_STEP = 5
|
||||
|
||||
// Which wizard step owns each ValidationIssue.field (internal/driver/reims/reims.go ValidateCreate).
|
||||
// Which wizard step owns each ValidationIssue.field (internal/macos/reims/reims.go ValidateCreate).
|
||||
const STEP_OF_FIELD: Record<string, number> = {
|
||||
installer: 1, disk: 1, macos: 1, guest_lang: 1,
|
||||
cpus: 2, memory: 2,
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { FolderOpen } from 'lucide-react'
|
||||
import React, { useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { AppState, Locale } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { api } from '../wails'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
status: AppState['data_root_status']
|
||||
/** Localized reason from the backend (dataroot.Error). */
|
||||
message: string
|
||||
/** The folder changed or reopened; the app reloads its state. */
|
||||
onChanged: () => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Shown instead of the workspace while the data folder is open read-only
|
||||
* (written by a newer release, damaged version record, failed or concurrent
|
||||
* upgrade). Nothing in the folder has been changed; the user can repair it,
|
||||
* try again, or pick another folder.
|
||||
*/
|
||||
export const DataRootReadOnly: React.FC<Props> = ({ locale, status, message, onChanged, onError }) => {
|
||||
const tr = (k: I18nKey) => t(locale, k)
|
||||
const [busy, setBusy] = useState<'' | 'repair' | 'retry' | 'choose'>('')
|
||||
|
||||
const run = async (kind: 'repair' | 'retry' | 'choose', fn: () => Promise<unknown>) => {
|
||||
setBusy(kind)
|
||||
try {
|
||||
await fn()
|
||||
onChanged()
|
||||
} catch (e) {
|
||||
onError(tr('failGeneric'), e)
|
||||
} finally {
|
||||
setBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
const choose = () => run('choose', async () => {
|
||||
const dir = await api.PickDirectory(tr('dataRootChooseTitle'))
|
||||
if (dir) await api.SetDataRoot(dir)
|
||||
})
|
||||
|
||||
const canRepair = status.reason === 'damaged'
|
||||
const canRetry = status.reason === 'busy' || status.reason === 'migration_failed'
|
||||
|
||||
return (
|
||||
<div className="setup">
|
||||
<div className="setup-card">
|
||||
<div className="setup-head">
|
||||
<h1>{tr('dataRootReadOnlyTitle')}</h1>
|
||||
<p>{message}</p>
|
||||
</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('dataRootReadOnlyFolder')}</div>
|
||||
<div className="row-sub mono selectable">{status.dir}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{status.detail && (
|
||||
<details className="dataroot-detail">
|
||||
<summary>{tr('dataRootReadOnlyDetail')}</summary>
|
||||
<pre className="mono selectable">{status.detail}</pre>
|
||||
</details>
|
||||
)}
|
||||
<div className="setup-foot">
|
||||
<span className="hstack">
|
||||
{canRepair && (
|
||||
<Button busy={busy === 'repair'} disabled={!!busy} onClick={() => void run('repair', () => api.ReopenDataRoot(true))}>
|
||||
{tr('dataRootRepair')}
|
||||
</Button>
|
||||
)}
|
||||
{canRetry && (
|
||||
<Button busy={busy === 'retry'} disabled={!!busy} onClick={() => void run('retry', () => api.ReopenDataRoot(false))}>
|
||||
{tr('dataRootRetry')}
|
||||
</Button>
|
||||
)}
|
||||
</span>
|
||||
<Button variant="primary" icon={<FolderOpen size={14} aria-hidden="true" />} busy={busy === 'choose'} disabled={!!busy} onClick={() => void choose()}>
|
||||
{tr('dataRootChooseOther')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -103,6 +103,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
const [settingsValues, setSettingsValues] = useState<Record<string, unknown>>({})
|
||||
const [logTarget, setLogTarget] = useState<{ id: string; text: string } | null>(null)
|
||||
const [removeTarget, setRemoveTarget] = useState<PluginInfo | null>(null)
|
||||
const [disableTarget, setDisableTarget] = useState<PluginInfo | null>(null)
|
||||
const [deleteSchemeTarget, setDeleteSchemeTarget] = useState<CustomThemeScheme | null>(null)
|
||||
|
||||
// Static risk scan modal state (pre-install .zip preview or installed plugin scan)
|
||||
@@ -171,7 +172,12 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
|
||||
useEffect(() => { if (activeTab === 'market') setMarketOpened(true) }, [activeTab])
|
||||
|
||||
const togglePlugin = async (p: PluginInfo, enable: boolean) => {
|
||||
const togglePlugin = async (p: PluginInfo, enable: boolean, confirmed = false) => {
|
||||
// Disabling a plugin that still owns VMs leaves them "driver unavailable": say so first.
|
||||
if (!enable && p.in_use && !confirmed) {
|
||||
setDisableTarget(p)
|
||||
return
|
||||
}
|
||||
if (enable && p.needs_approval) {
|
||||
setApproveChecked(false)
|
||||
setApproveReport(null)
|
||||
@@ -365,11 +371,8 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
return name.includes(q) || desc.includes(q) || p.id.toLowerCase().includes(q)
|
||||
}
|
||||
|
||||
// The always-on core goes first; the optional builtins keep backend order.
|
||||
const builtins = useMemo(
|
||||
() => plugins.filter((p) => p.source === 'builtin').sort((a, b) => Number(!!b.system) - Number(!!a.system)),
|
||||
[plugins],
|
||||
)
|
||||
// System plugins are part of the host and never listed; builtins keep backend order.
|
||||
const builtins = useMemo(() => plugins.filter((p) => p.source === 'builtin'), [plugins])
|
||||
const external = useMemo(() => plugins.filter((p) => p.source !== 'builtin'), [plugins])
|
||||
const filteredBuiltins = useMemo(() => builtins.filter(matchesFilter), [builtins, q, locale])
|
||||
const filteredExternal = useMemo(() => external.filter(matchesFilter), [external, q, locale])
|
||||
@@ -472,7 +475,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
) : (
|
||||
<Switch
|
||||
label={locText(p.name, locale, p.id)}
|
||||
disabled={busyID === p.id || (p.enabled && p.in_use) || (!!safeMode && !isBuiltin)}
|
||||
disabled={busyID === p.id || (!!safeMode && !isBuiltin)}
|
||||
checked={p.enabled}
|
||||
onChange={(checked) => void togglePlugin(p, checked)}
|
||||
/>
|
||||
@@ -922,6 +925,35 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{disableTarget && (
|
||||
<Modal
|
||||
title={tr('pluginDisableInUseTitle')}
|
||||
subtitle={locText(disableTarget.name, locale, disableTarget.id)}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setDisableTarget(null)}
|
||||
>
|
||||
<div style={{ padding: 'var(--sp-4)', fontSize: 'var(--fs-13)', color: 'var(--text-2)' }}>
|
||||
{tr('pluginDisableInUseBody')}
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<span className="hstack">
|
||||
<Button variant="ghost" onClick={() => setDisableTarget(null)}>{tr('cancel')}</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
onClick={() => {
|
||||
const target = disableTarget
|
||||
setDisableTarget(null)
|
||||
void togglePlugin(target, false, true)
|
||||
}}
|
||||
>
|
||||
{tr('pluginDisable')}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{removeTarget && (
|
||||
<Modal
|
||||
title={tr('pluginRemove')}
|
||||
|
||||
@@ -124,6 +124,7 @@ function baseline(detail: VMDetail, host: HostReport): SetOpts {
|
||||
interface Props {
|
||||
locale: Locale
|
||||
detail: VMDetail
|
||||
driverID: string
|
||||
stats?: VMStats | null
|
||||
host: HostReport
|
||||
optimizations?: Optimization[]
|
||||
@@ -138,7 +139,7 @@ interface Props {
|
||||
onSaved: () => void
|
||||
}
|
||||
|
||||
export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onHostChanged, onClose, onSaved }) => {
|
||||
export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats, host, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onHostChanged, onClose, onSaved }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const irqOpt = findOptimization(optimizations, 'kernel_irqchip')
|
||||
const base = useMemo(() => baseline(detail, host), [detail, host])
|
||||
@@ -161,11 +162,12 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
const [affinityStatus, setAffinityStatus] = useState<VMAffinityStatus | null>(null)
|
||||
const [vmPlugins, setVmPlugins] = useState<PluginInfo[]>([])
|
||||
const [vmPluginVals, setVmPluginVals] = useState<Record<string, Record<string, unknown>>>({})
|
||||
const vmSettingsKey = `${driverID}:${detail.name}`
|
||||
const pane = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
Promise.all([api.ListPlugins(), api.GetVMPluginSettings(detail.name)])
|
||||
Promise.all([api.ListPlugins(), api.GetVMPluginSettings(vmSettingsKey)])
|
||||
.then(([list, vals]) => {
|
||||
if (!live) return
|
||||
const activeWithVM = (list ?? []).filter((p) => (p.state === 'active' || p.state === 'degraded') && !!p.settings)
|
||||
@@ -174,11 +176,11 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
})
|
||||
.catch(() => {})
|
||||
return () => { live = false }
|
||||
}, [detail.name])
|
||||
}, [driverID, detail.name])
|
||||
|
||||
const updateVMPluginSetting = (pluginID: string, next: Record<string, unknown>) => {
|
||||
setVmPluginVals((prev) => ({ ...prev, [pluginID]: next }))
|
||||
void api.SetPluginSettings(pluginID, detail.name, next).catch((e) => setErr(parseAppError(e).summary))
|
||||
void api.SetPluginSettings(pluginID, vmSettingsKey, next).catch((e) => setErr(parseAppError(e).summary))
|
||||
}
|
||||
|
||||
const renderVMPluginGroup = (group: string) => {
|
||||
@@ -275,7 +277,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
api.GetVMAffinity(detail.name)
|
||||
api.GetVMAffinityWithDriver(driverID, detail.name)
|
||||
.then((st) => { if (active) setAffinityStatus(st) })
|
||||
.catch(() => {})
|
||||
return () => { active = false }
|
||||
@@ -659,7 +661,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
setErr('')
|
||||
setDiskOpBusy('resize')
|
||||
try {
|
||||
const res = await api.ResizeVMDisk(detail.name, resizeInput.trim())
|
||||
const res = await api.ResizeVMDiskWithDriver(driverID, detail.name, resizeInput.trim())
|
||||
setResizeResult(res)
|
||||
onDiskChanged?.()
|
||||
} catch (e) {
|
||||
@@ -674,7 +676,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
setErr('')
|
||||
setDiskOpBusy('compact')
|
||||
try {
|
||||
const res = await api.CompactVMDisk(detail.name)
|
||||
const res = await api.CompactVMDiskWithDriver(driverID, detail.name)
|
||||
setCompactResult(res)
|
||||
onDiskChanged?.()
|
||||
} catch (e) {
|
||||
|
||||
@@ -3,8 +3,9 @@ import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Maximize2
|
||||
import React, { useRef } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { Locale, VMListItem } from '../types'
|
||||
import { vmRefKey } from '../lib/vmRef'
|
||||
import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
|
||||
import { VersionArt } from './VersionArt'
|
||||
import { VersionArt } from '../macos/VersionArt'
|
||||
import { VMAction } from './VMPage'
|
||||
|
||||
export const HOST_ID = '__host__'
|
||||
@@ -51,7 +52,7 @@ export const Sidebar: React.FC<Props> = ({
|
||||
const tr = (k: I18nKey) => t(locale, k)
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
const ctxOpenedByPointerRef = useRef(false)
|
||||
const ids = [...vms.map((v) => v.name), INSTALLERS_ID, PLUGINS_ID, HOST_ID, SETTINGS_ID, ABOUT_ID]
|
||||
const ids = [...vms.map((v) => vmRefKey(v)), INSTALLERS_ID, PLUGINS_ID, HOST_ID, SETTINGS_ID, ABOUT_ID]
|
||||
|
||||
// Listbox keyboard model: ↑/↓/Home/End move selection and focus together.
|
||||
const onKeyDown = (e: React.KeyboardEvent) => {
|
||||
@@ -117,7 +118,7 @@ export const Sidebar: React.FC<Props> = ({
|
||||
<div className="nav-group nav-vms" role="group" aria-label={tr('sidebarVMs')}>
|
||||
{vms.length === 0 && <div className="nav-empty rg-p-empty" data-rg-slot="empty.state">{tr('emptyVMs')}</div>}
|
||||
{vms.map((vm) => {
|
||||
const st = transitions[vm.name] ?? vm.state
|
||||
const st = transitions[vmRefKey(vm)] ?? vm.state
|
||||
const running = st === 'running'
|
||||
const stopped = st === 'stopped'
|
||||
const suspended = st === 'suspended'
|
||||
@@ -126,17 +127,17 @@ export const Sidebar: React.FC<Props> = ({
|
||||
const vmBusy = !!busyAction
|
||||
const label = displayNames[vm.name] || vm.name
|
||||
const trigger = navBtn(
|
||||
vm.name,
|
||||
vmRefKey(vm),
|
||||
label,
|
||||
<VersionArt shape="tile" major={macosMajors[vm.name] ?? null} name={label} />,
|
||||
'nav-icon-art',
|
||||
t(locale, `state_${st}` as I18nKey),
|
||||
statusKind(st),
|
||||
onActivate ? () => onActivate(vm.name) : undefined,
|
||||
onActivate ? () => onActivate(vmRefKey(vm)) : undefined,
|
||||
)
|
||||
if (!onVMContextAction) return trigger
|
||||
return (
|
||||
<Ctx.Root key={vm.name}>
|
||||
<Ctx.Root key={vmRefKey(vm)}>
|
||||
<Ctx.Trigger
|
||||
asChild
|
||||
onContextMenu={(e) => {
|
||||
@@ -158,67 +159,67 @@ export const Sidebar: React.FC<Props> = ({
|
||||
}}
|
||||
>
|
||||
{stopped && (
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'start')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'start')}>
|
||||
<Play size={14} /> {tr('start')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
{suspended && (
|
||||
<>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy || !canSuspend} onSelect={() => onVMContextAction(vm.name, 'resume')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy || !canSuspend} onSelect={() => onVMContextAction(vmRefKey(vm), 'resume')}>
|
||||
<Play size={14} /> {tr('resume')}
|
||||
</Ctx.Item>
|
||||
{!canSuspend && <Ctx.Label className="menu-group-label">{tr('resumeUnavailable')}</Ctx.Label>}
|
||||
<Ctx.Item className="menu-item danger" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'discardSuspend')}>
|
||||
<Ctx.Item className="menu-item danger" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'discardSuspend')}>
|
||||
<Power size={14} /> {tr('discardSuspend')}
|
||||
</Ctx.Item>
|
||||
</>
|
||||
)}
|
||||
{running && (
|
||||
<>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'focus')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'focus')}>
|
||||
<AppWindow size={14} /> {tr('showWindow')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'fullscreen')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'fullscreen')}>
|
||||
<Maximize2 size={14} /> {tr('toggleFullscreen')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'screenshot')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'screenshot')}>
|
||||
<Camera size={14} /> {tr('copyScreenshot')}
|
||||
</Ctx.Item>
|
||||
{canSuspend && (
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'suspend')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'suspend')}>
|
||||
<Pause size={14} /> {tr('suspend')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'stop')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'stop')}>
|
||||
<Square size={14} /> {tr('stop')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'restart')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'restart')}>
|
||||
<RotateCw size={14} /> {tr('restart')}
|
||||
</Ctx.Item>
|
||||
</>
|
||||
)}
|
||||
{(running || transitioning) && (
|
||||
<Ctx.Item className="menu-item danger" disabled={busyAction === 'forceStop'} onSelect={() => onVMContextAction(vm.name, 'forceStop')}>
|
||||
<Ctx.Item className="menu-item danger" disabled={busyAction === 'forceStop'} onSelect={() => onVMContextAction(vmRefKey(vm), 'forceStop')}>
|
||||
<Power size={14} /> {tr('forceStop')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
<Ctx.Separator className="menu-sep" />
|
||||
<Ctx.Item className="menu-item" disabled={suspended || transitioning} onSelect={() => onVMContextAction(vm.name, 'settings')}>
|
||||
<Ctx.Item className="menu-item" disabled={suspended || transitioning} onSelect={() => onVMContextAction(vmRefKey(vm), 'settings')}>
|
||||
<Settings size={14} /> {tr('settingsEllipsis')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'openSharedFolder')}>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vmRefKey(vm), 'openSharedFolder')}>
|
||||
<FolderOpen size={14} /> {tr('openSharedFolder')}
|
||||
</Ctx.Item>
|
||||
{stopped && (
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'cloneVM')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'cloneVM')}>
|
||||
<CopyPlus size={14} /> {tr('cloneVM')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'openFolder')}>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vmRefKey(vm), 'openFolder')}>
|
||||
<FolderOpen size={14} /> {tr('openFolder')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Separator className="menu-sep" />
|
||||
<Ctx.Item className="menu-item danger" disabled={vmBusy || running || suspended || transitioning} onSelect={() => onVMContextAction(vm.name, 'delete')}>
|
||||
<Ctx.Item className="menu-item danger" disabled={vmBusy || running || suspended || transitioning} onSelect={() => onVMContextAction(vmRefKey(vm), 'delete')}>
|
||||
<Trash size={14} /> {tr('delete')}
|
||||
</Ctx.Item>
|
||||
</Ctx.Content>
|
||||
|
||||
@@ -27,7 +27,7 @@ interface Props {
|
||||
canDark?: boolean
|
||||
onThemeMode: (mode: ThemeMode) => void
|
||||
/** The selected VM and its current state, or null on the system pages. */
|
||||
vm: { name: string; state: string; busy: boolean; graphics?: string; canSuspend: boolean } | null
|
||||
vm: { name: string; driver_id?: string; state: string; busy: boolean; graphics?: string; canSuspend: boolean } | null
|
||||
onNewVM: () => void
|
||||
onVMAction: (action: VMAction) => void
|
||||
onVMSettings: () => void
|
||||
@@ -66,7 +66,7 @@ export const TitleMenus: React.FC<Props> = ({
|
||||
const transitioning = vm?.state === 'starting' || vm?.state === 'stopping' || vm?.state === 'suspending' || vm?.state === 'resuming'
|
||||
const vmBusy = !vm || vm.busy
|
||||
const canFullscreen = running && vm?.graphics !== 'vmware-svga'
|
||||
const stats = useVMStats(canFullscreen && vm ? vm.name : null, running)
|
||||
const stats = useVMStats(vm?.driver_id ?? '', canFullscreen && vm ? vm.name : null, running)
|
||||
const fullscreenLabel = !canFullscreen || !stats?.running
|
||||
? tr('toggleFullscreen')
|
||||
: stats.window_fullscreen
|
||||
|
||||
@@ -52,7 +52,7 @@ import { DiskSnapshot, HostReport, Locale, PendingChange, PluginUIContributions,
|
||||
import { api } from '../wails'
|
||||
import { Button, IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
|
||||
import { Switch } from '../ui/settings'
|
||||
import { VersionArt } from './VersionArt'
|
||||
import { VersionArt } from '../macos/VersionArt'
|
||||
|
||||
export type VMAction =
|
||||
| 'start'
|
||||
@@ -90,6 +90,7 @@ interface Props {
|
||||
locale: Locale
|
||||
/** The VM's identifier (folder, CLI, reims-ctl). */
|
||||
name: string
|
||||
driverID: string
|
||||
/** What the user calls it (its note); empty shows `name`. */
|
||||
displayName: string
|
||||
onDisplayNameSaved: (displayName: string) => void
|
||||
@@ -138,7 +139,7 @@ interface Spec {
|
||||
}
|
||||
|
||||
export const VMPage: React.FC<Props> = ({
|
||||
locale, name, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI,
|
||||
locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const busy = busyAction !== undefined
|
||||
@@ -150,23 +151,23 @@ export const VMPage: React.FC<Props> = ({
|
||||
const installing = !!detail && (detail.has_installer || detail.recovery_mode)
|
||||
const transitioning = state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming'
|
||||
// Polled here rather than in App so each tick re-renders only this page.
|
||||
const stats = useVMStats(name, running)
|
||||
const stats = useVMStats(driverID, name, running)
|
||||
|
||||
// Screen thumbnail (thumbnail_flow.go): a fresh frame every 15 s while the VM
|
||||
// runs, otherwise the last frame saved. Skipped while this window is hidden;
|
||||
// the backend also skips it while the VM's own window is in front.
|
||||
const [thumb, setThumb] = useState<VMThumbnail | null>(null)
|
||||
useEffect(() => { setThumb(null) }, [name])
|
||||
useEffect(() => { setThumb(null) }, [driverID, name])
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
const pull = () => {
|
||||
if (document.hidden) return
|
||||
api.GetVMThumbnail(name).then((t) => { if (live && t?.data_url) setThumb(t) }).catch(() => {})
|
||||
api.GetVMThumbnailWithDriver(driverID, name).then((t) => { if (live && t?.data_url) setThumb(t) }).catch(() => {})
|
||||
}
|
||||
pull()
|
||||
const timer = running ? window.setInterval(pull, 15000) : undefined
|
||||
return () => { live = false; if (timer) window.clearInterval(timer) }
|
||||
}, [name, running])
|
||||
}, [driverID, name, running])
|
||||
|
||||
// Display name, stored as the VM's note (.reims-go-note). Clicking the title
|
||||
// edits it in place; clearing it (or typing the name) falls back to the name.
|
||||
@@ -206,29 +207,29 @@ export const VMPage: React.FC<Props> = ({
|
||||
setMoreMenuOpen(false)
|
||||
setSshMenuOpen(false)
|
||||
setSshUserDialog(false)
|
||||
}, [name])
|
||||
}, [driverID, name])
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
api.GetVMSSHUser(name).then((u) => { if (live) setSshUser(u ?? '') }).catch(() => { if (live) setSshUser('') })
|
||||
api.GetVMSSHUserWithDriver(driverID, name).then((u) => { if (live) setSshUser(u ?? '') }).catch(() => { if (live) setSshUser('') })
|
||||
return () => { live = false }
|
||||
}, [name])
|
||||
}, [driverID, name])
|
||||
|
||||
const openSSHTerminal = () => {
|
||||
api.OpenSSHTerminal(name, sshUser).catch((e) => onError(tr('failSSH'), e))
|
||||
api.OpenSSHTerminalWithDriver(driverID, name, sshUser).catch((e) => onError(tr('failSSH'), e))
|
||||
}
|
||||
const writeSSHConfig = () => {
|
||||
api.WriteSSHConfig(name, sshUser)
|
||||
api.WriteSSHConfigWithDriver(driverID, name, sshUser)
|
||||
.then((alias) => onToast(tr('toastSSHConfigWritten', { alias })))
|
||||
.catch((e) => onError(tr('failSSH'), e))
|
||||
}
|
||||
const openVSCodeSSH = () => {
|
||||
api.OpenVSCodeSSH(name, sshUser).catch((e) => onError(tr('failSSH'), e))
|
||||
api.OpenVSCodeSSHWithDriver(driverID, name, sshUser).catch((e) => onError(tr('failSSH'), e))
|
||||
}
|
||||
const saveSSHUser = async () => {
|
||||
const next = sshUserDraft.trim()
|
||||
setSshUserDialog(false)
|
||||
try {
|
||||
await api.SetVMSSHUser(name, next)
|
||||
await api.SetVMSSHUserWithDriver(driverID, name, next)
|
||||
setSshUser(next)
|
||||
onToast(tr('toastSSHUserSaved'))
|
||||
} catch (e) {
|
||||
@@ -266,7 +267,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
|
||||
const loadSnapshots = () => {
|
||||
if (!showSnapshots) { setSnapshots([]); return }
|
||||
api.ListSnapshots(name).then((list) => setSnapshots(list ?? [])).catch(() => setSnapshots([]))
|
||||
api.ListSnapshotsWithDriver(driverID, name).then((list) => setSnapshots(list ?? [])).catch(() => setSnapshots([]))
|
||||
}
|
||||
useEffect(() => {
|
||||
setCreatingSnap(false)
|
||||
@@ -274,14 +275,14 @@ export const VMPage: React.FC<Props> = ({
|
||||
setRestoreTarget(null)
|
||||
loadSnapshots()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [name, showSnapshots, state])
|
||||
}, [driverID, name, showSnapshots, state])
|
||||
|
||||
const handleCreateSnapshot = async () => {
|
||||
const label = snapDraft.trim()
|
||||
if (!label) return
|
||||
setSnapBusy('create')
|
||||
try {
|
||||
await api.CreateSnapshot(name, label)
|
||||
await api.CreateSnapshotWithDriver(driverID, name, label)
|
||||
setSnapDraft('')
|
||||
setCreatingSnap(false)
|
||||
onToast(tr('toastSnapshotCreated', { name: label }))
|
||||
@@ -296,7 +297,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
setRestoreTarget(null)
|
||||
setSnapBusy(`restore:${snapName}`)
|
||||
try {
|
||||
await api.RestoreSnapshot(name, snapName)
|
||||
await api.RestoreSnapshotWithDriver(driverID, name, snapName)
|
||||
onToast(tr('toastSnapshotRestored', { name: snapName }))
|
||||
loadSnapshots()
|
||||
} catch (e) {
|
||||
@@ -308,7 +309,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
const handleDeleteSnapshot = async (snapName: string) => {
|
||||
setSnapBusy(`delete:${snapName}`)
|
||||
try {
|
||||
await api.DeleteSnapshot(name, snapName)
|
||||
await api.DeleteSnapshotWithDriver(driverID, name, snapName)
|
||||
onToast(tr('toastSnapshotDeleted', { name: snapName }))
|
||||
loadSnapshots()
|
||||
} catch (e) {
|
||||
|
||||
@@ -14,6 +14,13 @@ export const coreZh: Record<string, string> = {
|
||||
"collapseLogs": "收起日志",
|
||||
"copy": "复制",
|
||||
"copyTechInfo": "复制技术信息",
|
||||
"dataRootChooseOther": "选择其他数据目录",
|
||||
"dataRootChooseTitle": "选择数据目录",
|
||||
"dataRootReadOnlyDetail": "详细信息",
|
||||
"dataRootReadOnlyFolder": "数据目录",
|
||||
"dataRootReadOnlyTitle": "数据目录暂时无法使用",
|
||||
"dataRootRepair": "修复版本记录",
|
||||
"dataRootRetry": "重试",
|
||||
"delete": "删除…",
|
||||
"deleteEllipsis": "删除…",
|
||||
"displays": "显示器数量",
|
||||
@@ -196,6 +203,13 @@ export const coreEn: Record<string, string> = {
|
||||
"collapseLogs": "Hide logs",
|
||||
"copy": "Copy",
|
||||
"copyTechInfo": "Copy technical details",
|
||||
"dataRootChooseOther": "Choose another data folder",
|
||||
"dataRootChooseTitle": "Choose data folder",
|
||||
"dataRootReadOnlyDetail": "Details",
|
||||
"dataRootReadOnlyFolder": "Data folder",
|
||||
"dataRootReadOnlyTitle": "This data folder can’t be used right now",
|
||||
"dataRootRepair": "Repair version record",
|
||||
"dataRootRetry": "Try again",
|
||||
"delete": "Delete…",
|
||||
"deleteEllipsis": "Delete…",
|
||||
"displays": "Displays",
|
||||
|
||||
@@ -14,6 +14,9 @@ export const pluginsZh: Record<string, string> = {
|
||||
"pluginColorSchemes": "配色方案",
|
||||
"pluginColorSchemesHint": "修改种子色派生整套界面色阶",
|
||||
"pluginDeleteScheme": "删除方案",
|
||||
"pluginDisable": "停用",
|
||||
"pluginDisableInUseBody": "停用后,这个插件管理的虚拟机会显示为「驱动不可用」,不能启动或修改。虚拟机文件不会删除,重新启用即可恢复。运行中的虚拟机需要先停止。",
|
||||
"pluginDisableInUseTitle": "停用仍有虚拟机的插件",
|
||||
"pluginDone": "完成",
|
||||
"pluginEnableLater": "暂不启用",
|
||||
"pluginEnableNow": "启用",
|
||||
@@ -134,6 +137,9 @@ export const pluginsEn: Record<string, string> = {
|
||||
"pluginColorSchemes": "Color schemes",
|
||||
"pluginColorSchemesHint": "Seed colors derive the full surface, text, and accent ramp",
|
||||
"pluginDeleteScheme": "Delete scheme",
|
||||
"pluginDisable": "Disable",
|
||||
"pluginDisableInUseBody": "Its VMs will show as “Driver unavailable” and can’t be started or changed. Their files are kept; turning the plugin back on restores them. Stop any running VM first.",
|
||||
"pluginDisableInUseTitle": "Disable a plugin that still has VMs",
|
||||
"pluginDone": "Done",
|
||||
"pluginEnableLater": "Not now",
|
||||
"pluginEnableNow": "Enable",
|
||||
|
||||
@@ -123,6 +123,13 @@ export type I18nKey =
|
||||
| "cpuRecHint"
|
||||
| "createNow"
|
||||
| "createStartedHint"
|
||||
| "dataRootChooseOther"
|
||||
| "dataRootChooseTitle"
|
||||
| "dataRootReadOnlyDetail"
|
||||
| "dataRootReadOnlyFolder"
|
||||
| "dataRootReadOnlyTitle"
|
||||
| "dataRootRepair"
|
||||
| "dataRootRetry"
|
||||
| "delete"
|
||||
| "deleteConfirm"
|
||||
| "deleteDesc"
|
||||
@@ -504,6 +511,9 @@ export type I18nKey =
|
||||
| "pluginColorSchemes"
|
||||
| "pluginColorSchemesHint"
|
||||
| "pluginDeleteScheme"
|
||||
| "pluginDisable"
|
||||
| "pluginDisableInUseBody"
|
||||
| "pluginDisableInUseTitle"
|
||||
| "pluginDone"
|
||||
| "pluginEnableLater"
|
||||
| "pluginEnableNow"
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
export interface VMRefLike {
|
||||
name: string
|
||||
driver_id?: string
|
||||
}
|
||||
|
||||
/** Matches driver.VMRef.Key while tolerating pre-VMRef test/host snapshots. */
|
||||
export function vmRefKey(vm: VMRefLike): string {
|
||||
return vm.driver_id ? `${vm.driver_id}:${vm.name}` : vm.name
|
||||
}
|
||||
+37
-39
@@ -2,13 +2,8 @@ import { useEffect, useState } from 'react'
|
||||
import { VMStats } from '../types'
|
||||
import { api } from '../wails'
|
||||
|
||||
// Shared VM stats poller (stats_flow.go). Components that show stats
|
||||
// subscribe with useVMStats, so a tick re-renders only them, not the whole
|
||||
// App. One timer per VM however many subscribe; it pauses while the window
|
||||
// is hidden and samples once on return.
|
||||
|
||||
// Shared VM stats poller, keyed by VMRef so same-name VMs never share samples.
|
||||
const RUNNING_MS = 3000
|
||||
// A stopped VM only changes disk usage, so it is sampled rarely.
|
||||
const STOPPED_MS = 30000
|
||||
|
||||
interface Entry {
|
||||
@@ -21,14 +16,14 @@ interface Entry {
|
||||
}
|
||||
|
||||
const entries = new Map<string, Entry>()
|
||||
const statsKey = (driverID: string, name: string) => `${driverID}:${name}`
|
||||
|
||||
function sample(name: string, entryRef: Entry) {
|
||||
if (entries.get(name) !== entryRef) return
|
||||
function sample(key: string, driverID: string, name: string, entryRef: Entry) {
|
||||
if (entries.get(key) !== entryRef) return
|
||||
const reqSeq = ++entryRef.seq
|
||||
api.GetVMStats(name)
|
||||
api.GetVMStatsWithDriver(driverID, name)
|
||||
.then((s) => {
|
||||
if (entries.get(name) !== entryRef) return
|
||||
if (reqSeq <= entryRef.appliedSeq) return
|
||||
if (entries.get(key) !== entryRef || reqSeq <= entryRef.appliedSeq) return
|
||||
entryRef.appliedSeq = reqSeq
|
||||
entryRef.last = s
|
||||
entryRef.subs.forEach((f) => f(s))
|
||||
@@ -36,81 +31,84 @@ function sample(name: string, entryRef: Entry) {
|
||||
.catch(() => {})
|
||||
}
|
||||
|
||||
function schedule(name: string, e: Entry) {
|
||||
function schedule(key: string, driverID: string, name: string, e: Entry) {
|
||||
if (e.timer) window.clearInterval(e.timer)
|
||||
e.timer = undefined
|
||||
if (document.hidden || e.subs.size === 0) return
|
||||
e.timer = window.setInterval(() => sample(name, e), e.running ? RUNNING_MS : STOPPED_MS)
|
||||
e.timer = window.setInterval(() => sample(key, driverID, name, e), e.running ? RUNNING_MS : STOPPED_MS)
|
||||
}
|
||||
|
||||
if (typeof document !== 'undefined') {
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
entries.forEach((e, name) => {
|
||||
if (!document.hidden && e.subs.size > 0) sample(name, e)
|
||||
schedule(name, e)
|
||||
entries.forEach((e, key) => {
|
||||
const split = key.indexOf(':')
|
||||
const driverID = key.slice(0, split)
|
||||
const name = key.slice(split + 1)
|
||||
if (!document.hidden && e.subs.size > 0) sample(key, driverID, name, e)
|
||||
schedule(key, driverID, name, e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** Latest stats seen for a VM, without subscribing (e.g. when a dialog opens). */
|
||||
export function latestVMStats(name: string | undefined | null): VMStats | null {
|
||||
return name ? entries.get(name)?.last ?? null : null
|
||||
export function latestVMStatsWithDriver(driverID: string, name: string | undefined | null): VMStats | null {
|
||||
return name ? entries.get(statsKey(driverID, name))?.last ?? null : null
|
||||
}
|
||||
export function latestVMStats(name: string | undefined | null): VMStats | null { return latestVMStatsWithDriver('', name) }
|
||||
|
||||
/** Immediately patch cached stats (if any) and re-sample a VM's stats. */
|
||||
export function refreshVMStats(name: string, patch?: Partial<VMStats>) {
|
||||
const e = entries.get(name)
|
||||
export function refreshVMStatsWithDriver(driverID: string, name: string, patch?: Partial<VMStats>) {
|
||||
const key = statsKey(driverID, name)
|
||||
const e = entries.get(key)
|
||||
if (!e) return
|
||||
// Invalidate any in-flight samples started before this refresh/patch.
|
||||
e.appliedSeq = ++e.seq
|
||||
if (patch && e.last) {
|
||||
e.last = { ...e.last, ...patch }
|
||||
e.subs.forEach((f) => f(e.last!))
|
||||
}
|
||||
sample(name, e)
|
||||
sample(key, driverID, name, e)
|
||||
}
|
||||
export function refreshVMStats(name: string, patch?: Partial<VMStats>) { refreshVMStatsWithDriver('', name, patch) }
|
||||
|
||||
/** Re-sample all currently subscribed VMs (e.g. after a tray-triggered state change). */
|
||||
export function refreshSubscribedVMStats() {
|
||||
entries.forEach((e, name) => {
|
||||
if (e.subs.size > 0) {
|
||||
e.appliedSeq = ++e.seq
|
||||
sample(name, e)
|
||||
}
|
||||
entries.forEach((e, key) => {
|
||||
if (e.subs.size === 0) return
|
||||
const split = key.indexOf(':')
|
||||
e.appliedSeq = ++e.seq
|
||||
sample(key, key.slice(0, split), key.slice(split + 1), e)
|
||||
})
|
||||
}
|
||||
|
||||
/** Live stats for one VM; `running` picks the sampling rate. Null name: none. */
|
||||
export function useVMStats(name: string | null, running: boolean): VMStats | null {
|
||||
const [stats, setStats] = useState<VMStats | null>(() => latestVMStats(name))
|
||||
|
||||
export function useVMStats(driverID: string, name: string | null, running: boolean): VMStats | null {
|
||||
const [stats, setStats] = useState<VMStats | null>(() => latestVMStatsWithDriver(driverID, name))
|
||||
useEffect(() => {
|
||||
if (!name) { setStats(null); return }
|
||||
let e = entries.get(name)
|
||||
const key = statsKey(driverID, name)
|
||||
let e = entries.get(key)
|
||||
if (!e) {
|
||||
e = { subs: new Set(), running, last: null, seq: 0, appliedSeq: 0 }
|
||||
entries.set(name, e)
|
||||
entries.set(key, e)
|
||||
}
|
||||
setStats(e.last)
|
||||
const sub = (s: VMStats) => setStats(s)
|
||||
e.subs.add(sub)
|
||||
// A state change (start/stop) samples at once and re-paces the timer.
|
||||
if (e.running !== running) {
|
||||
e.running = running
|
||||
e.appliedSeq = ++e.seq
|
||||
}
|
||||
sample(name, e)
|
||||
schedule(name, e)
|
||||
sample(key, driverID, name, e)
|
||||
schedule(key, driverID, name, e)
|
||||
return () => {
|
||||
const cur = entries.get(name)
|
||||
const cur = entries.get(key)
|
||||
if (!cur || cur !== e) return
|
||||
cur.subs.delete(sub)
|
||||
if (cur.subs.size === 0) {
|
||||
if (cur.timer) window.clearInterval(cur.timer)
|
||||
entries.delete(name)
|
||||
entries.delete(key)
|
||||
}
|
||||
}
|
||||
}, [name, running])
|
||||
|
||||
}, [driverID, name, running])
|
||||
return stats
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import React, { useEffect, useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import '../i18n/domains/wizard.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { macOSMajor } from '../lib/macosRelease'
|
||||
import { macOSMajor } from './macosRelease'
|
||||
import {
|
||||
ActiveInstallerMatch,
|
||||
findActiveCachedTask,
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1263,6 +1263,14 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.setup-head h1 { font-size: var(--fs-24); font-weight: var(--fw-strong); letter-spacing: -0.02em; text-wrap: balance; }
|
||||
.setup-head p { margin-top: var(--sp-1); color: var(--text-2); font-size: var(--fs-14); }
|
||||
.setup-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); }
|
||||
/* Read-only data folder screen (DataRootReadOnly) */
|
||||
.dataroot-detail { font-size: var(--fs-12); color: var(--text-2); }
|
||||
.dataroot-detail summary { cursor: pointer; }
|
||||
.dataroot-detail pre {
|
||||
margin: var(--sp-2) 0 0; padding: var(--sp-3); border-radius: var(--r-md);
|
||||
background: var(--surface-1); border: 1px solid var(--border);
|
||||
white-space: pre-wrap; word-break: break-word; max-height: 160px; overflow: auto;
|
||||
}
|
||||
/* First-run offer of a market language pack for the OS language */
|
||||
.setup-langpack {
|
||||
display: flex; align-items: center; gap: var(--sp-3); padding: var(--sp-3) var(--sp-4);
|
||||
|
||||
@@ -47,7 +47,8 @@ export type RemoteRuntime = Model<runtime.Remote> & {
|
||||
channel: 'stable' | 'alpha'
|
||||
}
|
||||
|
||||
export type VMListItem = Model<reims.VMListItem> & {
|
||||
export type VMListItem = Model<driver.VMListItem> & {
|
||||
driver_id?: string
|
||||
state: 'running' | 'stopped' | 'suspended' | 'broken'
|
||||
}
|
||||
|
||||
@@ -80,9 +81,9 @@ export type VMAffinityStatus = Omit<Model<app.VMAffinityStatus>, 'mode' | 'effec
|
||||
/** One frame of a VM's screen (internal/app/thumbnail_flow.go). Empty data_url: none yet. */
|
||||
export type VMThumbnail = app.VMThumbnail
|
||||
export type ValidationIssue = reims.ValidationIssue
|
||||
export type DiskResizeResult = reims.DiskResizeResult
|
||||
export type DiskCompactResult = reims.DiskCompactResult
|
||||
export type DiskSnapshot = reims.DiskSnapshot
|
||||
export type DiskResizeResult = driver.DiskResizeResult
|
||||
export type DiskCompactResult = driver.DiskCompactResult
|
||||
export type DiskSnapshot = driver.DiskSnapshot
|
||||
export type StorageBreakdown = Model<app.StorageBreakdown>
|
||||
export type SetOpts = reims.SetOpts
|
||||
|
||||
|
||||
@@ -149,6 +149,8 @@ export const api = {
|
||||
GetTasks: boundGo.GetTasks as () => Promise<Task[]>,
|
||||
GetVMAffinity: boundGo.GetVMAffinity as (name: string) => Promise<VMAffinityStatus>,
|
||||
SetVMAffinity: boundGo.SetVMAffinity as (name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
|
||||
GetVMAffinityWithDriver: boundGo.GetVMAffinityWithDriver as (driverID: string, name: string) => Promise<VMAffinityStatus>,
|
||||
SetVMAffinityWithDriver: boundGo.SetVMAffinityWithDriver as (driverID: string, name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
|
||||
ListInstallers: boundGo.ListInstallers as () => Promise<CachedInstaller[] | null>,
|
||||
ListRemoteRuntimes: boundGo.ListRemoteRuntimes as () => Promise<RemoteRuntime[] | null>,
|
||||
SuggestDataRoots: boundGo.SuggestDataRoots as () => Promise<DataRootChoice[] | null>,
|
||||
|
||||
Vendored
+68
-5
@@ -8,6 +8,7 @@ import {driver} from '../models';
|
||||
import {runtime} from '../models';
|
||||
import {installer} from '../models';
|
||||
import {http} from '../models';
|
||||
import {dataroot} from '../models';
|
||||
|
||||
export function ApplyVMSettings(arg1:reims.SetOpts):Promise<void>;
|
||||
|
||||
@@ -27,14 +28,22 @@ export function CheckDataRoot(arg1:string):Promise<app.DataRootCheck>;
|
||||
|
||||
export function CloneVMCoW(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function CompactVMDisk(arg1:string):Promise<reims.DiskCompactResult>;
|
||||
export function CloneVMCoWWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function CompactVMDisk(arg1:string):Promise<driver.DiskCompactResult>;
|
||||
|
||||
export function CompactVMDiskWithDriver(arg1:string,arg2:string):Promise<driver.DiskCompactResult>;
|
||||
|
||||
export function CompleteSetup(arg1:string):Promise<void>;
|
||||
|
||||
export function CopyVMScreenshot(arg1:string):Promise<void>;
|
||||
|
||||
export function CopyVMScreenshotWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function CreateSnapshot(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function CreateSnapshotWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function CreateVM(arg1:reims.CreateOpts):Promise<void>;
|
||||
|
||||
export function CreateVMWithDriver(arg1:driver.CreateRequest):Promise<void>;
|
||||
@@ -45,9 +54,11 @@ export function DeleteInstaller(arg1:string):Promise<void>;
|
||||
|
||||
export function DeleteSnapshot(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function DeleteSnapshotWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function DeleteVM(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function DiscardSuspend(arg1:string):Promise<void>;
|
||||
export function DeleteVMWithDriver(arg1:string,arg2:string,arg3:boolean):Promise<void>;
|
||||
|
||||
export function DeliverFileToGuest(arg1:string):Promise<string>;
|
||||
|
||||
@@ -57,6 +68,10 @@ export function DetachGuestTools(arg1:string):Promise<void>;
|
||||
|
||||
export function DisablePlugin(arg1:string):Promise<void>;
|
||||
|
||||
export function DiscardSuspend(arg1:string):Promise<void>;
|
||||
|
||||
export function DiscardSuspendWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function DismissTask(arg1:string):Promise<void>;
|
||||
|
||||
export function DoctorPlugin(arg1:string):Promise<Array<plugin.DoctorFinding>>;
|
||||
@@ -69,6 +84,8 @@ export function DownloadInstaller(arg1:string):Promise<string>;
|
||||
|
||||
export function EjectInstaller(arg1:string):Promise<void>;
|
||||
|
||||
export function EjectInstallerWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function EnablePlugin(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function EnableWHPX():Promise<void>;
|
||||
@@ -77,10 +94,14 @@ export function EnterRecovery(arg1:string):Promise<void>;
|
||||
|
||||
export function ExportDiagnostics(arg1:string):Promise<string>;
|
||||
|
||||
export function ExportDiagnosticsWithDriver(arg1:string,arg2:string):Promise<string>;
|
||||
|
||||
export function FinishInstall(arg1:string):Promise<void>;
|
||||
|
||||
export function FocusVMWindow(arg1:string):Promise<void>;
|
||||
|
||||
export function FocusVMWindowWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function GetActiveTheme():Promise<plugin.ActiveThemePayload>;
|
||||
|
||||
export function GetLicenseTexts():Promise<app.LicenseTexts>;
|
||||
@@ -97,10 +118,14 @@ export function GetTasks():Promise<Array<app.Task>>;
|
||||
|
||||
export function GetVMAffinity(arg1:string):Promise<app.VMAffinityStatus>;
|
||||
|
||||
export function GetVMAffinityWithDriver(arg1:string,arg2:string):Promise<app.VMAffinityStatus>;
|
||||
|
||||
export function GetVMDetail(arg1:string):Promise<reims.VMDetail>;
|
||||
|
||||
export function GetVMDriveShareSettings(arg1:string):Promise<app.DriveShareSettings>;
|
||||
|
||||
export function GetVMInfo(arg1:string,arg2:string):Promise<driver.VMInfo>;
|
||||
|
||||
export function GetVMMacOS(arg1:string):Promise<string>;
|
||||
|
||||
export function GetVMNote(arg1:string):Promise<string>;
|
||||
@@ -109,10 +134,16 @@ export function GetVMPluginSettings(arg1:string):Promise<Record<string, Record<s
|
||||
|
||||
export function GetVMSSHUser(arg1:string):Promise<string>;
|
||||
|
||||
export function GetVMSSHUserWithDriver(arg1:string,arg2:string):Promise<string>;
|
||||
|
||||
export function GetVMStats(arg1:string):Promise<app.VMStats>;
|
||||
|
||||
export function GetVMStatsWithDriver(arg1:string,arg2:string):Promise<app.VMStats>;
|
||||
|
||||
export function GetVMThumbnail(arg1:string):Promise<app.VMThumbnail>;
|
||||
|
||||
export function GetVMThumbnailWithDriver(arg1:string,arg2:string):Promise<app.VMThumbnail>;
|
||||
|
||||
export function InspectPluginArchive(arg1:string):Promise<plugin.ScanReport>;
|
||||
|
||||
export function InstallAppUpdate():Promise<void>;
|
||||
@@ -141,7 +172,9 @@ export function ListRemoteRuntimes():Promise<Array<runtime.Remote>>;
|
||||
|
||||
export function ListRuntimeKinds():Promise<Array<runtime.KindSpec>>;
|
||||
|
||||
export function ListSnapshots(arg1:string):Promise<Array<reims.DiskSnapshot>>;
|
||||
export function ListSnapshots(arg1:string):Promise<Array<driver.DiskSnapshot>>;
|
||||
|
||||
export function ListSnapshotsWithDriver(arg1:string,arg2:string):Promise<Array<driver.DiskSnapshot>>;
|
||||
|
||||
export function OpenProcessorScheduling():Promise<void>;
|
||||
|
||||
@@ -149,6 +182,8 @@ export function OpenQQGroup():Promise<void>;
|
||||
|
||||
export function OpenSSHTerminal(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function OpenSSHTerminalWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function OpenSharedFolder(arg1:string):Promise<void>;
|
||||
|
||||
export function OpenURL(arg1:string):Promise<void>;
|
||||
@@ -157,6 +192,8 @@ export function OpenVMFolder(arg1:string):Promise<void>;
|
||||
|
||||
export function OpenVSCodeSSH(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function OpenVSCodeSSHWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function PanelBridgeCall(arg1:string,arg2:string,arg3:Record<string, any>):Promise<any>;
|
||||
|
||||
export function PeekPluginMarket(arg1:string,arg2:string):Promise<plugin.MarketBrowseResult>;
|
||||
@@ -175,20 +212,32 @@ export function ReadPluginLog(arg1:string):Promise<string>;
|
||||
|
||||
export function ReadVMLogs(arg1:string,arg2:boolean):Promise<string>;
|
||||
|
||||
export function ReadVMLogsWithDriver(arg1:string,arg2:string,arg3:boolean):Promise<string>;
|
||||
|
||||
export function RemovePlugin(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function RemoveRuntime(arg1:string):Promise<void>;
|
||||
|
||||
export function ReopenDataRoot(arg1:boolean):Promise<dataroot.Status>;
|
||||
|
||||
export function RequestClose():Promise<void>;
|
||||
|
||||
export function ResizeVMDisk(arg1:string,arg2:string):Promise<reims.DiskResizeResult>;
|
||||
export function ResizeVMDisk(arg1:string,arg2:string):Promise<driver.DiskResizeResult>;
|
||||
|
||||
export function ResizeVMDiskWithDriver(arg1:string,arg2:string,arg3:string):Promise<driver.DiskResizeResult>;
|
||||
|
||||
export function RestartVM(arg1:string):Promise<void>;
|
||||
|
||||
export function ResumeVM(arg1:string):Promise<void>;
|
||||
export function RestartVMWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function RestoreSnapshot(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function RestoreSnapshotWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function ResumeVM(arg1:string):Promise<void>;
|
||||
|
||||
export function ResumeVMWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function SaveCustomThemeScheme(arg1:plugin.CustomThemeScheme):Promise<void>;
|
||||
|
||||
export function ScanInstalledPlugin(arg1:string):Promise<plugin.ScanReport>;
|
||||
@@ -213,28 +262,40 @@ export function SetRuntimeChannel(arg1:string):Promise<void>;
|
||||
|
||||
export function SetVMAffinity(arg1:string,arg2:app.VMAffinityUpdate):Promise<app.VMAffinityStatus>;
|
||||
|
||||
export function SetVMAffinityWithDriver(arg1:string,arg2:string,arg3:app.VMAffinityUpdate):Promise<app.VMAffinityStatus>;
|
||||
|
||||
export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array<string>):Promise<app.DriveShareSettings>;
|
||||
|
||||
export function SetVMNote(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function SetVMSSHUser(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function SetVMSSHUserWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function ShowMainWindow():Promise<void>;
|
||||
|
||||
export function StartVM(arg1:string):Promise<void>;
|
||||
|
||||
export function StartVMWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function StopVM(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function StopVMWithDriver(arg1:string,arg2:string,arg3:boolean):Promise<void>;
|
||||
|
||||
export function SuggestDataRoots():Promise<Array<app.DataRootChoice>>;
|
||||
|
||||
export function SuggestLanguagePack():Promise<plugin.MarketCatalogItem>;
|
||||
|
||||
export function SuspendVM(arg1:string):Promise<void>;
|
||||
|
||||
export function SuspendVMWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function ToggleBorderless(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function ToggleVMFullscreen(arg1:string):Promise<boolean>;
|
||||
|
||||
export function ToggleVMFullscreenWithDriver(arg1:string,arg2:string):Promise<boolean>;
|
||||
|
||||
export function TypeClipboard(arg1:string):Promise<number>;
|
||||
|
||||
export function TypeText(arg1:string,arg2:string):Promise<number>;
|
||||
@@ -248,3 +309,5 @@ export function ValidateCreate(arg1:reims.CreateOpts):Promise<Array<reims.Valida
|
||||
export function ValidateSet(arg1:reims.SetOpts):Promise<Array<reims.ValidationIssue>>;
|
||||
|
||||
export function WriteSSHConfig(arg1:string,arg2:string):Promise<string>;
|
||||
|
||||
export function WriteSSHConfigWithDriver(arg1:string,arg2:string,arg3:string):Promise<string>;
|
||||
@@ -38,10 +38,18 @@ export function CloneVMCoW(arg1, arg2) {
|
||||
return window['go']['app']['App']['CloneVMCoW'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CloneVMCoWWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['CloneVMCoWWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function CompactVMDisk(arg1) {
|
||||
return window['go']['app']['App']['CompactVMDisk'](arg1);
|
||||
}
|
||||
|
||||
export function CompactVMDiskWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['CompactVMDiskWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CompleteSetup(arg1) {
|
||||
return window['go']['app']['App']['CompleteSetup'](arg1);
|
||||
}
|
||||
@@ -50,10 +58,18 @@ export function CopyVMScreenshot(arg1) {
|
||||
return window['go']['app']['App']['CopyVMScreenshot'](arg1);
|
||||
}
|
||||
|
||||
export function CopyVMScreenshotWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['CopyVMScreenshotWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CreateSnapshot(arg1, arg2) {
|
||||
return window['go']['app']['App']['CreateSnapshot'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CreateSnapshotWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['CreateSnapshotWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function CreateVM(arg1) {
|
||||
return window['go']['app']['App']['CreateVM'](arg1);
|
||||
}
|
||||
@@ -74,12 +90,16 @@ export function DeleteSnapshot(arg1, arg2) {
|
||||
return window['go']['app']['App']['DeleteSnapshot'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function DeleteSnapshotWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['DeleteSnapshotWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function DeleteVM(arg1, arg2) {
|
||||
return window['go']['app']['App']['DeleteVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function DiscardSuspend(arg1) {
|
||||
return window['go']['app']['App']['DiscardSuspend'](arg1);
|
||||
export function DeleteVMWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['DeleteVMWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function DeliverFileToGuest(arg1) {
|
||||
@@ -98,6 +118,14 @@ export function DisablePlugin(arg1) {
|
||||
return window['go']['app']['App']['DisablePlugin'](arg1);
|
||||
}
|
||||
|
||||
export function DiscardSuspend(arg1) {
|
||||
return window['go']['app']['App']['DiscardSuspend'](arg1);
|
||||
}
|
||||
|
||||
export function DiscardSuspendWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['DiscardSuspendWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function DismissTask(arg1) {
|
||||
return window['go']['app']['App']['DismissTask'](arg1);
|
||||
}
|
||||
@@ -122,6 +150,10 @@ export function EjectInstaller(arg1) {
|
||||
return window['go']['app']['App']['EjectInstaller'](arg1);
|
||||
}
|
||||
|
||||
export function EjectInstallerWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['EjectInstallerWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function EnablePlugin(arg1, arg2) {
|
||||
return window['go']['app']['App']['EnablePlugin'](arg1, arg2);
|
||||
}
|
||||
@@ -138,6 +170,10 @@ export function ExportDiagnostics(arg1) {
|
||||
return window['go']['app']['App']['ExportDiagnostics'](arg1);
|
||||
}
|
||||
|
||||
export function ExportDiagnosticsWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['ExportDiagnosticsWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function FinishInstall(arg1) {
|
||||
return window['go']['app']['App']['FinishInstall'](arg1);
|
||||
}
|
||||
@@ -146,6 +182,10 @@ export function FocusVMWindow(arg1) {
|
||||
return window['go']['app']['App']['FocusVMWindow'](arg1);
|
||||
}
|
||||
|
||||
export function FocusVMWindowWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['FocusVMWindowWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function GetActiveTheme() {
|
||||
return window['go']['app']['App']['GetActiveTheme']();
|
||||
}
|
||||
@@ -178,6 +218,10 @@ export function GetVMAffinity(arg1) {
|
||||
return window['go']['app']['App']['GetVMAffinity'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMAffinityWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMAffinityWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function GetVMDetail(arg1) {
|
||||
return window['go']['app']['App']['GetVMDetail'](arg1);
|
||||
}
|
||||
@@ -186,6 +230,10 @@ export function GetVMDriveShareSettings(arg1) {
|
||||
return window['go']['app']['App']['GetVMDriveShareSettings'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMInfo(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMInfo'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function GetVMMacOS(arg1) {
|
||||
return window['go']['app']['App']['GetVMMacOS'](arg1);
|
||||
}
|
||||
@@ -202,14 +250,26 @@ export function GetVMSSHUser(arg1) {
|
||||
return window['go']['app']['App']['GetVMSSHUser'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMSSHUserWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMSSHUserWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function GetVMStats(arg1) {
|
||||
return window['go']['app']['App']['GetVMStats'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMStatsWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMStatsWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function GetVMThumbnail(arg1) {
|
||||
return window['go']['app']['App']['GetVMThumbnail'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMThumbnailWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMThumbnailWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function InspectPluginArchive(arg1) {
|
||||
return window['go']['app']['App']['InspectPluginArchive'](arg1);
|
||||
}
|
||||
@@ -270,6 +330,10 @@ export function ListSnapshots(arg1) {
|
||||
return window['go']['app']['App']['ListSnapshots'](arg1);
|
||||
}
|
||||
|
||||
export function ListSnapshotsWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['ListSnapshotsWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function OpenProcessorScheduling() {
|
||||
return window['go']['app']['App']['OpenProcessorScheduling']();
|
||||
}
|
||||
@@ -282,6 +346,10 @@ export function OpenSSHTerminal(arg1, arg2) {
|
||||
return window['go']['app']['App']['OpenSSHTerminal'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function OpenSSHTerminalWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['OpenSSHTerminalWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function OpenSharedFolder(arg1) {
|
||||
return window['go']['app']['App']['OpenSharedFolder'](arg1);
|
||||
}
|
||||
@@ -298,6 +366,10 @@ export function OpenVSCodeSSH(arg1, arg2) {
|
||||
return window['go']['app']['App']['OpenVSCodeSSH'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function OpenVSCodeSSHWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['OpenVSCodeSSHWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function PanelBridgeCall(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['PanelBridgeCall'](arg1, arg2, arg3);
|
||||
}
|
||||
@@ -334,6 +406,10 @@ export function ReadVMLogs(arg1, arg2) {
|
||||
return window['go']['app']['App']['ReadVMLogs'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function ReadVMLogsWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['ReadVMLogsWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function RemovePlugin(arg1, arg2) {
|
||||
return window['go']['app']['App']['RemovePlugin'](arg1, arg2);
|
||||
}
|
||||
@@ -342,6 +418,10 @@ export function RemoveRuntime(arg1) {
|
||||
return window['go']['app']['App']['RemoveRuntime'](arg1);
|
||||
}
|
||||
|
||||
export function ReopenDataRoot(arg1) {
|
||||
return window['go']['app']['App']['ReopenDataRoot'](arg1);
|
||||
}
|
||||
|
||||
export function RequestClose() {
|
||||
return window['go']['app']['App']['RequestClose']();
|
||||
}
|
||||
@@ -350,16 +430,32 @@ export function ResizeVMDisk(arg1, arg2) {
|
||||
return window['go']['app']['App']['ResizeVMDisk'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function ResizeVMDiskWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['ResizeVMDiskWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function RestartVM(arg1) {
|
||||
return window['go']['app']['App']['RestartVM'](arg1);
|
||||
}
|
||||
|
||||
export function RestartVMWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['RestartVMWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function RestoreSnapshot(arg1, arg2) {
|
||||
return window['go']['app']['App']['RestoreSnapshot'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function RestoreSnapshotWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['RestoreSnapshotWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function ResumeVM(arg1) {
|
||||
return window['go']['app']['App']['ResumeVM'](arg1);
|
||||
}
|
||||
|
||||
export function RestoreSnapshot(arg1, arg2) {
|
||||
return window['go']['app']['App']['RestoreSnapshot'](arg1, arg2);
|
||||
export function ResumeVMWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['ResumeVMWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SaveCustomThemeScheme(arg1) {
|
||||
@@ -410,6 +506,10 @@ export function SetVMAffinity(arg1, arg2) {
|
||||
return window['go']['app']['App']['SetVMAffinity'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SetVMAffinityWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMAffinityWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function SetVMDriveShareSettings(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMDriveShareSettings'](arg1, arg2, arg3);
|
||||
}
|
||||
@@ -422,6 +522,10 @@ export function SetVMSSHUser(arg1, arg2) {
|
||||
return window['go']['app']['App']['SetVMSSHUser'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SetVMSSHUserWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMSSHUserWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function ShowMainWindow() {
|
||||
return window['go']['app']['App']['ShowMainWindow']();
|
||||
}
|
||||
@@ -430,10 +534,18 @@ export function StartVM(arg1) {
|
||||
return window['go']['app']['App']['StartVM'](arg1);
|
||||
}
|
||||
|
||||
export function StartVMWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['StartVMWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function StopVM(arg1, arg2) {
|
||||
return window['go']['app']['App']['StopVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function StopVMWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['StopVMWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function SuggestDataRoots() {
|
||||
return window['go']['app']['App']['SuggestDataRoots']();
|
||||
}
|
||||
@@ -446,6 +558,10 @@ export function SuspendVM(arg1) {
|
||||
return window['go']['app']['App']['SuspendVM'](arg1);
|
||||
}
|
||||
|
||||
export function SuspendVMWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['SuspendVMWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function ToggleBorderless(arg1, arg2) {
|
||||
return window['go']['app']['App']['ToggleBorderless'](arg1, arg2);
|
||||
}
|
||||
@@ -454,6 +570,10 @@ export function ToggleVMFullscreen(arg1) {
|
||||
return window['go']['app']['App']['ToggleVMFullscreen'](arg1);
|
||||
}
|
||||
|
||||
export function ToggleVMFullscreenWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['ToggleVMFullscreenWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function TypeClipboard(arg1) {
|
||||
return window['go']['app']['App']['TypeClipboard'](arg1);
|
||||
}
|
||||
@@ -481,3 +601,7 @@ export function ValidateSet(arg1) {
|
||||
export function WriteSSHConfig(arg1, arg2) {
|
||||
return window['go']['app']['App']['WriteSSHConfig'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function WriteSSHConfigWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['WriteSSHConfigWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
+156
-75
@@ -7,12 +7,14 @@ export namespace app {
|
||||
runtimes: runtime.Installed[];
|
||||
active_runtime?: runtime.Installed;
|
||||
can_suspend: boolean;
|
||||
vms: reims.VMListItem[];
|
||||
vms: driver.VMListItem[];
|
||||
transitions: Record<string, string>;
|
||||
pending_changes: Record<string, Array<PendingChange>>;
|
||||
active_guides?: string[];
|
||||
install_guide_enabled?: boolean;
|
||||
needs_setup: boolean;
|
||||
data_root_status: dataroot.Status;
|
||||
data_root_message?: string;
|
||||
app_version: string;
|
||||
safe_mode?: boolean;
|
||||
plugin_crash_detected?: boolean;
|
||||
@@ -32,12 +34,14 @@ export namespace app {
|
||||
this.runtimes = this.convertValues(source["runtimes"], runtime.Installed);
|
||||
this.active_runtime = this.convertValues(source["active_runtime"], runtime.Installed);
|
||||
this.can_suspend = source["can_suspend"];
|
||||
this.vms = this.convertValues(source["vms"], reims.VMListItem);
|
||||
this.vms = this.convertValues(source["vms"], driver.VMListItem);
|
||||
this.transitions = source["transitions"];
|
||||
this.pending_changes = this.convertValues(source["pending_changes"], Array<PendingChange>, true);
|
||||
this.active_guides = source["active_guides"];
|
||||
this.install_guide_enabled = source["install_guide_enabled"];
|
||||
this.needs_setup = source["needs_setup"];
|
||||
this.data_root_status = this.convertValues(source["data_root_status"], dataroot.Status);
|
||||
this.data_root_message = source["data_root_message"];
|
||||
this.app_version = source["app_version"];
|
||||
this.safe_mode = source["safe_mode"];
|
||||
this.plugin_crash_detected = source["plugin_crash_detected"];
|
||||
@@ -493,6 +497,35 @@ export namespace config {
|
||||
|
||||
}
|
||||
|
||||
export namespace dataroot {
|
||||
|
||||
export class Status {
|
||||
dir: string;
|
||||
read_only: boolean;
|
||||
reason?: string;
|
||||
detail?: string;
|
||||
version: number;
|
||||
known: number;
|
||||
migrated?: string[];
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Status(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.dir = source["dir"];
|
||||
this.read_only = source["read_only"];
|
||||
this.reason = source["reason"];
|
||||
this.detail = source["detail"];
|
||||
this.version = source["version"];
|
||||
this.known = source["known"];
|
||||
this.migrated = source["migrated"];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export namespace driver {
|
||||
|
||||
export class CreateRequest {
|
||||
@@ -513,6 +546,60 @@ export namespace driver {
|
||||
this.options = source["options"];
|
||||
}
|
||||
}
|
||||
export class DiskCompactResult {
|
||||
path: string;
|
||||
before_bytes: number;
|
||||
after_bytes: number;
|
||||
reclaimed_bytes: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DiskCompactResult(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.path = source["path"];
|
||||
this.before_bytes = source["before_bytes"];
|
||||
this.after_bytes = source["after_bytes"];
|
||||
this.reclaimed_bytes = source["reclaimed_bytes"];
|
||||
}
|
||||
}
|
||||
export class DiskResizeResult {
|
||||
path: string;
|
||||
old_virtual_bytes: number;
|
||||
new_virtual_bytes: number;
|
||||
guest_expand_cmd: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DiskResizeResult(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.path = source["path"];
|
||||
this.old_virtual_bytes = source["old_virtual_bytes"];
|
||||
this.new_virtual_bytes = source["new_virtual_bytes"];
|
||||
this.guest_expand_cmd = source["guest_expand_cmd"];
|
||||
}
|
||||
}
|
||||
export class DiskSnapshot {
|
||||
id: string;
|
||||
name: string;
|
||||
created_at: number;
|
||||
vm_state_bytes: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DiskSnapshot(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.id = source["id"];
|
||||
this.name = source["name"];
|
||||
this.created_at = source["created_at"];
|
||||
this.vm_state_bytes = source["vm_state_bytes"];
|
||||
}
|
||||
}
|
||||
export class DriverSummary {
|
||||
id: string;
|
||||
name: plugin.LocalizedText;
|
||||
@@ -557,6 +644,66 @@ export namespace driver {
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class VMInfo {
|
||||
name: string;
|
||||
driver_id: string;
|
||||
driver_name?: string;
|
||||
state: string;
|
||||
pid?: number;
|
||||
cpus?: number;
|
||||
memory?: string;
|
||||
disk_summary?: string;
|
||||
disk_path?: string;
|
||||
directory?: string;
|
||||
network?: boolean;
|
||||
ssh_port?: number;
|
||||
capabilities?: string[];
|
||||
driver_data?: Record<string, any>;
|
||||
driver_unavailable?: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new VMInfo(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.name = source["name"];
|
||||
this.driver_id = source["driver_id"];
|
||||
this.driver_name = source["driver_name"];
|
||||
this.state = source["state"];
|
||||
this.pid = source["pid"];
|
||||
this.cpus = source["cpus"];
|
||||
this.memory = source["memory"];
|
||||
this.disk_summary = source["disk_summary"];
|
||||
this.disk_path = source["disk_path"];
|
||||
this.directory = source["directory"];
|
||||
this.network = source["network"];
|
||||
this.ssh_port = source["ssh_port"];
|
||||
this.capabilities = source["capabilities"];
|
||||
this.driver_data = source["driver_data"];
|
||||
this.driver_unavailable = source["driver_unavailable"];
|
||||
}
|
||||
}
|
||||
export class VMListItem {
|
||||
name: string;
|
||||
driver_id?: string;
|
||||
dir: string;
|
||||
pid?: number;
|
||||
state: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new VMListItem(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.name = source["name"];
|
||||
this.driver_id = source["driver_id"];
|
||||
this.dir = source["dir"];
|
||||
this.pid = source["pid"];
|
||||
this.state = source["state"];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -2196,60 +2343,6 @@ export namespace reims {
|
||||
this.start = source["start"];
|
||||
}
|
||||
}
|
||||
export class DiskCompactResult {
|
||||
path: string;
|
||||
before_bytes: number;
|
||||
after_bytes: number;
|
||||
reclaimed_bytes: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DiskCompactResult(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.path = source["path"];
|
||||
this.before_bytes = source["before_bytes"];
|
||||
this.after_bytes = source["after_bytes"];
|
||||
this.reclaimed_bytes = source["reclaimed_bytes"];
|
||||
}
|
||||
}
|
||||
export class DiskResizeResult {
|
||||
path: string;
|
||||
old_virtual_bytes: number;
|
||||
new_virtual_bytes: number;
|
||||
guest_expand_cmd: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DiskResizeResult(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.path = source["path"];
|
||||
this.old_virtual_bytes = source["old_virtual_bytes"];
|
||||
this.new_virtual_bytes = source["new_virtual_bytes"];
|
||||
this.guest_expand_cmd = source["guest_expand_cmd"];
|
||||
}
|
||||
}
|
||||
export class DiskSnapshot {
|
||||
id: string;
|
||||
name: string;
|
||||
created_at: number;
|
||||
vm_state_bytes: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DiskSnapshot(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.id = source["id"];
|
||||
this.name = source["name"];
|
||||
this.created_at = source["created_at"];
|
||||
this.vm_state_bytes = source["vm_state_bytes"];
|
||||
}
|
||||
}
|
||||
export class SetOpts {
|
||||
name: string;
|
||||
cpus?: number;
|
||||
@@ -2437,7 +2530,7 @@ export namespace reims {
|
||||
this.guest_lang = source["guest_lang"];
|
||||
this.suspend_info = this.convertValues(source["suspend_info"], SuspendInfo);
|
||||
}
|
||||
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
@@ -2456,24 +2549,6 @@ export namespace reims {
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class VMListItem {
|
||||
name: string;
|
||||
dir: string;
|
||||
pid?: number;
|
||||
state: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new VMListItem(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.name = source["name"];
|
||||
this.dir = source["dir"];
|
||||
this.pid = source["pid"];
|
||||
this.state = source["state"];
|
||||
}
|
||||
}
|
||||
export class ValidationIssue {
|
||||
field: string;
|
||||
code?: string;
|
||||
@@ -2636,6 +2711,9 @@ export namespace runtime {
|
||||
name_en: string;
|
||||
required_files?: string[];
|
||||
default_api_version?: string;
|
||||
control_executable?: string;
|
||||
utility_executable?: string;
|
||||
control_qemu_env?: string;
|
||||
builtin?: boolean;
|
||||
plugin_id?: string;
|
||||
|
||||
@@ -2651,6 +2729,9 @@ export namespace runtime {
|
||||
this.name_en = source["name_en"];
|
||||
this.required_files = source["required_files"];
|
||||
this.default_api_version = source["default_api_version"];
|
||||
this.control_executable = source["control_executable"];
|
||||
this.utility_executable = source["utility_executable"];
|
||||
this.control_qemu_env = source["control_qemu_env"];
|
||||
this.builtin = source["builtin"];
|
||||
this.plugin_id = source["plugin_id"];
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
@@ -57,7 +57,7 @@ func (a *App) findRunningVMPID(ctx context.Context, name string) int {
|
||||
return 0
|
||||
}
|
||||
|
||||
func buildVMAffinityStatus(detail reims.VMDetail, rep host.Report, globalAutoPin bool, pid int) VMAffinityStatus {
|
||||
func buildVMAffinityStatus(detail driver.VMInfo, rep host.Report, globalAutoPin bool, pid int) VMAffinityStatus {
|
||||
cfg := vmstart.ReadVMAffinity(detail.Directory)
|
||||
res := vmstart.ResolveVMAffinity(cfg, globalAutoPin, rep, detail.CPUs)
|
||||
savedCPUs := cfg.CPUs
|
||||
@@ -98,7 +98,14 @@ func buildVMAffinityStatus(detail reims.VMDetail, rep host.Report, globalAutoPin
|
||||
// GetVMAffinity returns the per-VM processor affinity configuration, resolved
|
||||
// effective CPU set, and live QEMU process affinity mask when running.
|
||||
func (a *App) GetVMAffinity(name string) (VMAffinityStatus, error) {
|
||||
detail, err := a.GetVMDetail(name)
|
||||
return a.GetVMAffinityWithDriver("", name)
|
||||
}
|
||||
func (a *App) GetVMAffinityWithDriver(driverID, name string) (VMAffinityStatus, error) {
|
||||
vm, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return VMAffinityStatus{}, err
|
||||
}
|
||||
detail := vm
|
||||
if err != nil {
|
||||
return VMAffinityStatus{}, err
|
||||
}
|
||||
@@ -109,7 +116,12 @@ func (a *App) GetVMAffinity(name string) (VMAffinityStatus, error) {
|
||||
rep := host.Inspect(root)
|
||||
pid := 0
|
||||
if detail.State == "running" {
|
||||
pid = a.findRunningVMPID(a.baseCtx(), name)
|
||||
if listed, ok := a.polledVMForDriver(vm.DriverID, name); ok && listed.PID != nil {
|
||||
pid = *listed.PID
|
||||
}
|
||||
if vm.PID != nil {
|
||||
pid = *vm.PID
|
||||
}
|
||||
}
|
||||
return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), nil
|
||||
}
|
||||
@@ -117,7 +129,14 @@ func (a *App) GetVMAffinity(name string) (VMAffinityStatus, error) {
|
||||
// SetVMAffinity saves a VM's processor affinity mapping and immediately applies
|
||||
// it (plus EcoQoS power-throttling control) to the running QEMU process if active.
|
||||
func (a *App) SetVMAffinity(name string, req VMAffinityUpdate) (VMAffinityStatus, error) {
|
||||
detail, err := a.GetVMDetail(name)
|
||||
return a.SetVMAffinityWithDriver("", name, req)
|
||||
}
|
||||
func (a *App) SetVMAffinityWithDriver(driverID, name string, req VMAffinityUpdate) (VMAffinityStatus, error) {
|
||||
vm, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return VMAffinityStatus{}, err
|
||||
}
|
||||
detail := vm
|
||||
if err != nil {
|
||||
return VMAffinityStatus{}, err
|
||||
}
|
||||
@@ -142,12 +161,17 @@ func (a *App) SetVMAffinity(name string, req VMAffinityUpdate) (VMAffinityStatus
|
||||
|
||||
pid := 0
|
||||
if detail.State == "running" {
|
||||
pid = a.findRunningVMPID(a.baseCtx(), name)
|
||||
if listed, ok := a.polledVMForDriver(vm.DriverID, name); ok && listed.PID != nil {
|
||||
pid = *listed.PID
|
||||
}
|
||||
if vm.PID != nil {
|
||||
pid = *vm.PID
|
||||
}
|
||||
}
|
||||
if pid > 0 {
|
||||
line, applyErr := vmstart.ApplyVMAffinity(loc, rep, detail.Directory, globalAutoPin, pid, detail.CPUs, true)
|
||||
if line != "" {
|
||||
a.emitLog(name, line)
|
||||
a.emitVMLogForDriver(driverID, name, line)
|
||||
}
|
||||
if applyErr != nil {
|
||||
return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), applyErr
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
@@ -21,7 +21,7 @@ func TestBuildVMAffinityStatus(t *testing.T) {
|
||||
}
|
||||
|
||||
rep := host.Report{LogicalCPUs: 16}
|
||||
st := buildVMAffinityStatus(reims.VMDetail{
|
||||
st := buildVMAffinityStatus(driver.VMInfo{
|
||||
Name: "test-vm",
|
||||
Directory: dir,
|
||||
CPUs: 6,
|
||||
|
||||
+139
-735
File diff suppressed because it is too large.
Load diff
@@ -6,7 +6,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
)
|
||||
|
||||
func TestPolledVMsReusesFreshPoll(t *testing.T) {
|
||||
@@ -82,11 +82,11 @@ func TestReleaseVMTypingDrainsAndRemovesQueue(t *testing.T) {
|
||||
a := &App{}
|
||||
typing.mu.Lock()
|
||||
ch := make(chan remoteTextItem)
|
||||
typing.remoteQueues[name] = ch
|
||||
typing.lastHintAt[name] = time.Now()
|
||||
typing.remoteQueues[vmKey(name)] = ch
|
||||
typing.lastHintAt[vmKey(name)] = time.Now()
|
||||
typing.mu.Unlock()
|
||||
go func() {
|
||||
a.runRemoteTextQueue(name, ch)
|
||||
a.runRemoteTextQueue(vmKey(name), name, ch)
|
||||
close(done)
|
||||
}()
|
||||
releaseVMTyping(name)
|
||||
|
||||
@@ -17,14 +17,14 @@ import (
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/cli"
|
||||
"github.com/Nwflower/reims-go/internal/fetch"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/netproxy"
|
||||
"github.com/Nwflower/reims-go/internal/selfupdate"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
)
|
||||
|
||||
// appUpdateTaskKind is the task kind the frontend watches for update progress.
|
||||
// appUpdateTaskKind is the task kind the frontend watches for update host.
|
||||
const appUpdateTaskKind = "app-update"
|
||||
|
||||
// appUpdateReady is the verified download InstallAppUpdate swaps in.
|
||||
@@ -68,11 +68,10 @@ func (a *App) DownloadAppUpdate() (string, error) {
|
||||
if err := a.updateSupported(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
a.mu.Lock()
|
||||
if a.needsSetup {
|
||||
a.mu.Unlock()
|
||||
return "", errors.New("choose a data folder first")
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
a.mu.Lock()
|
||||
dataRoot := a.cfg.DataRoot
|
||||
a.mu.Unlock()
|
||||
|
||||
@@ -100,8 +99,8 @@ func (a *App) DownloadAppUpdate() (string, error) {
|
||||
go func() {
|
||||
defer cancel()
|
||||
path, sum, err := downloadAppUpdate(ctx, info, appUpdateDir(dataRoot), func(done, total int64) {
|
||||
tasks.update(id, installer.Update{
|
||||
Kind: installer.KindProgress, Step: "downloading " + info.AssetName,
|
||||
tasks.update(id, host.Update{
|
||||
Kind: host.KindProgress, Step: "downloading " + info.AssetName,
|
||||
Done: done, Total: total, Percent: percent(done, total),
|
||||
})
|
||||
})
|
||||
@@ -228,7 +227,7 @@ func (a *App) finishAppUpdateWithExe(exe string) {
|
||||
if a.launch.WaitPID == 0 {
|
||||
return
|
||||
}
|
||||
if !keepOld && dataRoot != "" {
|
||||
if !keepOld && dataRoot != "" && a.dataRootUsable() {
|
||||
_ = os.RemoveAll(appUpdateDir(dataRoot))
|
||||
}
|
||||
if keepOld {
|
||||
|
||||
+15
-138
@@ -1,153 +1,30 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"errors"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// CloneVMCoW derives a new VM instantaneously from a stopped source VM using a
|
||||
// qcow2 copy-on-write overlay (`qemu-img create -f qcow2 -b <src> -F qcow2`)
|
||||
// so the source golden disk is never mutated while the clone gets its own fresh
|
||||
// OpenCore identity (SMBIOS/serial/MAC) via `reims-ctl create --disk --disk-mode in-place`.
|
||||
// CloneVMCoW derives a VM through the source VM's owning driver.
|
||||
func (a *App) CloneVMCoW(sourceName, cloneName string) error {
|
||||
loc := a.locale()
|
||||
cloneName = strings.TrimSpace(cloneName)
|
||||
if cloneName == "" {
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_EMPTY_NAME", "err.clone.missing_name", nil, nil)
|
||||
}
|
||||
if strings.EqualFold(sourceName, cloneName) {
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_SAME_NAME", "err.clone.same_name", nil, nil)
|
||||
}
|
||||
return a.CloneVMCoWWithDriver("", sourceName, cloneName)
|
||||
}
|
||||
|
||||
func (a *App) CloneVMCoWWithDriver(driverID, sourceName, cloneName string) error {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
cfgCopy.Locale = loc
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
if svc == nil {
|
||||
return errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
ref := driver.VMRef{DriverID: driverID, Name: sourceName}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(driverID, cloneName, line) })
|
||||
if err := svc.CloneCoW(a.baseCtx(), ref, cloneName, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
ctx := a.baseCtx()
|
||||
|
||||
src, release, err := vmstart.LockVM(ctx, c, sourceName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
a.populateVMDetail(&src)
|
||||
if a.isVMRunning(ctx, c, sourceName, src) {
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_RUNNING", "err.clone.source_running", i18n.Vars{"name": sourceName}, nil)
|
||||
}
|
||||
if a.isVMSuspended(src) {
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": sourceName}, nil)
|
||||
}
|
||||
if src.HasInstaller {
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_RECOVERY", "err.clone.in_recovery", i18n.Vars{"name": sourceName}, nil)
|
||||
}
|
||||
srcDisk := src.Disk
|
||||
if srcDisk != "" && !filepath.IsAbs(srcDisk) && src.Directory != "" {
|
||||
srcDisk = filepath.Join(src.Directory, srcDisk)
|
||||
}
|
||||
if srcDisk == "" {
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_NO_DISK", "err.clone.no_disk", i18n.Vars{"name": sourceName}, nil)
|
||||
}
|
||||
if _, err := os.Stat(srcDisk); err != nil {
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_DISK_MISSING", "err.clone.disk_missing", i18n.Vars{"path": srcDisk}, err)
|
||||
}
|
||||
|
||||
// Validate clone name and check for name collisions.
|
||||
rep := host.Inspect(cfgCopy.DataRoot)
|
||||
nameCheck := reims.ValidateCreateLocalized(reims.CreateOpts{Name: cloneName, CPUs: max(src.CPUs, 1), Memory: src.Memory}, rep, loc)
|
||||
for _, iss := range nameCheck {
|
||||
if iss.Field == "name" {
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_INVALID_NAME", "validate."+iss.Code, i18n.Vars{"name": cloneName}, nil)
|
||||
}
|
||||
}
|
||||
if existing, err := c.List(ctx); err == nil {
|
||||
for _, vm := range existing {
|
||||
if strings.EqualFold(vm.Name, cloneName) {
|
||||
return i18n.NewCodedError(loc, "E_VM_NAME_TAKEN", "validate.name_taken", i18n.Vars{"name": cloneName}, nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
overlayPath := filepath.Join(cfgCopy.ImagesDir(), fmt.Sprintf("cow-%s.qcow2", cloneName))
|
||||
if _, err := os.Stat(overlayPath); err == nil {
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_OVERLAY_EXISTS", "err.clone.overlay_exists", i18n.Vars{"path": overlayPath}, nil)
|
||||
}
|
||||
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(cloneName, line) })
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
a.emitLog(cloneName, fmt.Sprintf("Creating CoW overlay for %s backed by %s...", cloneName, filepath.Base(srcDisk)))
|
||||
if err := reims.CreateCoWOverlay(ctx, active.QemuImgPath(), env, srcDisk, overlayPath, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
audio := src.Audio
|
||||
network := src.Network
|
||||
logs := src.Logs
|
||||
capture := src.Capture
|
||||
createOpts := reims.CreateOpts{
|
||||
Name: cloneName,
|
||||
SourceMode: "disk",
|
||||
Disk: overlayPath,
|
||||
DiskMode: "in-place",
|
||||
DiskController: src.DiskController,
|
||||
CPUs: src.CPUs,
|
||||
Memory: src.Memory,
|
||||
Graphics: src.Graphics,
|
||||
GPU: src.GPU,
|
||||
Resolution: src.Resolution,
|
||||
Displays: src.Displays,
|
||||
Capture: &capture,
|
||||
Audio: &audio,
|
||||
Network: &network,
|
||||
Logs: &logs,
|
||||
Start: false,
|
||||
}
|
||||
if err := c.Create(ctx, createOpts, w, w); err != nil {
|
||||
_ = os.Remove(overlayPath)
|
||||
return err
|
||||
}
|
||||
if postSet, ok := reims.PostCreateSetOpts(createOpts); ok {
|
||||
if serr := c.Set(ctx, postSet, w, w); serr != nil {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone settings: %v", serr))
|
||||
}
|
||||
}
|
||||
if src.GuestLang != "" || vmstart.HasSavedVMAffinity(src.Directory) {
|
||||
if cloned, serr := c.Show(ctx, cloneName); serr == nil && cloned.Directory != "" {
|
||||
if src.GuestLang != "" {
|
||||
prep, lerr := a.prep(cloneName)
|
||||
if lerr == nil {
|
||||
lerr = prep.ApplyGuestLang(ctx, cloned.Directory, src.GuestLang, false)
|
||||
}
|
||||
if lerr != nil {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone language (%s): %v", src.GuestLang, lerr))
|
||||
}
|
||||
}
|
||||
if werr := writeVMMacOS(cloned.Directory, readVMMacOS(src.Directory)); werr != nil {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not copy macOS release: %v", werr))
|
||||
}
|
||||
if vmstart.HasSavedVMAffinity(src.Directory) {
|
||||
if _, aerr := vmstart.SaveVMAffinity(cloned.Directory, vmstart.ReadVMAffinity(src.Directory), rep.LogicalCPUs); aerr != nil {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not copy CPU affinity setting: %v", aerr))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
a.emitLog(cloneName, fmt.Sprintf("CoW clone %s ready (backing image %s untouched)", cloneName, srcDisk))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return nil
|
||||
}
|
||||
+38
-23
@@ -9,14 +9,18 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/opencore"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/opencore"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
func (a *App) createVMFlow(opts reims.CreateOpts) error {
|
||||
if err := a.requireMacOSEnabled(); err != nil {
|
||||
return err
|
||||
}
|
||||
if issues := a.ValidateCreate(opts); len(issues) > 0 {
|
||||
return fmt.Errorf("%s", issues[0].Message)
|
||||
}
|
||||
@@ -37,13 +41,13 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
|
||||
ctx, cancel := context.WithCancel(a.baseCtx())
|
||||
defer cancel()
|
||||
taskID, w, finishTask := a.ctlTaskWriterWithCancel("vm-create", opts.Name, cancel)
|
||||
a.emitLog(opts.Name, "Creating VM "+opts.Name+"...")
|
||||
a.emitVMLog(opts.Name, "Creating VM "+opts.Name+"...")
|
||||
|
||||
existingVMs, _ := c.List(ctx)
|
||||
if removed, rerr := reims.CleanAbortedCreateDir(cfgCopy.XDGDataDir(), opts, existingVMs); rerr != nil {
|
||||
a.emitLog(opts.Name, "Warning: could not clean unfinished VM directory: "+rerr.Error())
|
||||
a.emitVMLog(opts.Name, "Warning: could not clean unfinished VM directory: "+rerr.Error())
|
||||
} else if removed != "" {
|
||||
a.emitLog(opts.Name, "Removed unfinished directory from an earlier interrupted create: "+removed)
|
||||
a.emitVMLog(opts.Name, "Removed unfinished directory from an earlier interrupted create: "+removed)
|
||||
}
|
||||
|
||||
// Ensure any requested macOS installer is downloaded via installer.Client
|
||||
@@ -64,15 +68,15 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
|
||||
if derr != nil {
|
||||
if errors.Is(derr, context.Canceled) || ctx.Err() != nil {
|
||||
finishTask(context.Canceled)
|
||||
a.emitLog(opts.Name, "Create canceled.")
|
||||
a.emitVMLog(opts.Name, "Create canceled.")
|
||||
return context.Canceled
|
||||
}
|
||||
finishTask(derr)
|
||||
a.emitLog(opts.Name, "Create error: "+derr.Error())
|
||||
a.emitVMLog(opts.Name, "Create error: "+derr.Error())
|
||||
return derr
|
||||
}
|
||||
if res != nil && res.Image != "" {
|
||||
a.emitLog(opts.Name, "Installer ready: "+res.Image)
|
||||
a.emitVMLog(opts.Name, "Installer ready: "+res.Image)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -84,17 +88,17 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
|
||||
perr := installer.EnsureCachedAsset(ctx, cfgCopy.XDGCacheDir(), installer.OcBinaryDataAsset, nil, func(u installer.Update) {
|
||||
if !loggedPrefetch && u.Kind == installer.KindStep {
|
||||
loggedPrefetch = true
|
||||
a.emitLog(opts.Name, opts.Name+": "+u.Message)
|
||||
a.emitVMLog(opts.Name, opts.Name+": "+u.Message)
|
||||
}
|
||||
tasks.update(taskID, u)
|
||||
})
|
||||
if perr != nil {
|
||||
if errors.Is(perr, context.Canceled) || ctx.Err() != nil {
|
||||
finishTask(context.Canceled)
|
||||
a.emitLog(opts.Name, "Create canceled.")
|
||||
a.emitVMLog(opts.Name, "Create canceled.")
|
||||
return context.Canceled
|
||||
}
|
||||
a.emitLog(opts.Name, "Pre-fetch OpenCore resources skipped (reims-ctl will retry): "+perr.Error())
|
||||
a.emitVMLog(opts.Name, "Pre-fetch OpenCore resources skipped (reims-ctl will retry): "+perr.Error())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,7 +107,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
|
||||
if opts.Disk != "" && reims.NeedsDiskConversion(opts.Disk) {
|
||||
convertedTmp = filepath.Join(cfgCopy.TempDir(), fmt.Sprintf("import-%s-%d.qcow2", opts.Name, time.Now().Unix()))
|
||||
defer os.Remove(convertedTmp)
|
||||
a.emitLog(opts.Name, fmt.Sprintf("Converting %s to qcow2 via qemu-img...", filepath.Base(opts.Disk)))
|
||||
a.emitVMLog(opts.Name, fmt.Sprintf("Converting %s to qcow2 via qemu-img...", filepath.Base(opts.Disk)))
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
if cerr := reims.ConvertDiskToQCOW2(ctx, active.QemuImgPath(), env, opts.Disk, convertedTmp, w, w); cerr != nil {
|
||||
if ctx.Err() != nil {
|
||||
@@ -111,9 +115,9 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
|
||||
}
|
||||
finishTask(cerr)
|
||||
if errors.Is(cerr, context.Canceled) {
|
||||
a.emitLog(opts.Name, "Create canceled.")
|
||||
a.emitVMLog(opts.Name, "Create canceled.")
|
||||
} else {
|
||||
a.emitLog(opts.Name, "Disk conversion error: "+cerr.Error())
|
||||
a.emitVMLog(opts.Name, "Disk conversion error: "+cerr.Error())
|
||||
}
|
||||
return cerr
|
||||
}
|
||||
@@ -128,12 +132,23 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
|
||||
}
|
||||
finishTask(err)
|
||||
if errors.Is(err, context.Canceled) {
|
||||
a.emitLog(opts.Name, "Create canceled.")
|
||||
a.emitVMLog(opts.Name, "Create canceled.")
|
||||
} else {
|
||||
a.emitLog(opts.Name, "Create error: "+err.Error())
|
||||
a.emitVMLog(opts.Name, "Create error: "+err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
createdDir := strings.TrimSpace(opts.Dir)
|
||||
if det, serr := c.Show(ctx, opts.Name); serr == nil && det.Directory != "" {
|
||||
createdDir = det.Directory
|
||||
}
|
||||
if createdDir == "" {
|
||||
createdDir = filepath.Join(cfgCopy.XDGDataDir(), "reims-ctl", "vms", opts.Name)
|
||||
}
|
||||
if err := driver.WriteOwnerDriver(createdDir, driver.BuiltinReimsMacOSDriverID); err != nil {
|
||||
finishTask(err)
|
||||
return fmt.Errorf("record VM driver ownership: %w", err)
|
||||
}
|
||||
if postSet, ok := reims.PostCreateSetOpts(opts); ok {
|
||||
var parts []string
|
||||
if postSet.DiskController != "" {
|
||||
@@ -142,9 +157,9 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
|
||||
if postSet.Capture != nil && !*postSet.Capture {
|
||||
parts = append(parts, "capture=off")
|
||||
}
|
||||
a.emitLog(opts.Name, fmt.Sprintf("Applying VM defaults for %s (%s)...", opts.Name, strings.Join(parts, ", ")))
|
||||
a.emitVMLog(opts.Name, fmt.Sprintf("Applying VM defaults for %s (%s)...", opts.Name, strings.Join(parts, ", ")))
|
||||
if serr := c.Set(ctx, postSet, w, w); serr != nil {
|
||||
a.emitLog(opts.Name, fmt.Sprintf("Warning: could not apply post-create defaults (%s): %v", strings.Join(parts, ", "), serr))
|
||||
a.emitVMLog(opts.Name, fmt.Sprintf("Warning: could not apply post-create defaults (%s): %v", strings.Join(parts, ", "), serr))
|
||||
}
|
||||
}
|
||||
guestLang := strings.TrimSpace(opts.GuestLang)
|
||||
@@ -165,7 +180,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
|
||||
}
|
||||
}
|
||||
if werr := writeVMMacOS(vmDir, release); werr != nil {
|
||||
a.emitLog(opts.Name, fmt.Sprintf("Warning: could not record macOS release (%s): %v", release, werr))
|
||||
a.emitVMLog(opts.Name, fmt.Sprintf("Warning: could not record macOS release (%s): %v", release, werr))
|
||||
}
|
||||
if guestLang != "" {
|
||||
prep, lerr := a.prep(opts.Name)
|
||||
@@ -173,14 +188,14 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
|
||||
lerr = prep.ApplyGuestLang(ctx, vmDir, guestLang, false)
|
||||
}
|
||||
if lerr != nil {
|
||||
a.emitLog(opts.Name, fmt.Sprintf("Warning: could not apply macOS language (%s): %v", guestLang, lerr))
|
||||
a.emitVMLog(opts.Name, fmt.Sprintf("Warning: could not apply macOS language (%s): %v", guestLang, lerr))
|
||||
}
|
||||
}
|
||||
finishTask(nil)
|
||||
a.emitLog(opts.Name, "VM "+opts.Name+" ready.")
|
||||
a.emitVMLog(opts.Name, "VM "+opts.Name+" ready.")
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
if startAfterCreate {
|
||||
return a.StartVM(opts.Name)
|
||||
return a.StartVMWithDriver(driver.BuiltinReimsMacOSDriverID, opts.Name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/dataroot"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// openDataRoot opens the current data folder (dataroot.Open: version check,
|
||||
// migration under the folder lock) and records whether it may be written.
|
||||
func (a *App) openDataRoot() dataroot.Status {
|
||||
a.mu.Lock()
|
||||
dir := a.cfg.DataRoot
|
||||
a.mu.Unlock()
|
||||
st := dataroot.Open(dir, version.Version)
|
||||
a.mu.Lock()
|
||||
a.root = st
|
||||
a.mu.Unlock()
|
||||
a.logDataRoot(st)
|
||||
return st
|
||||
}
|
||||
|
||||
func (a *App) logDataRoot(st dataroot.Status) {
|
||||
switch {
|
||||
case st.ReadOnly:
|
||||
msg := fmt.Sprintf("Data folder %s opened read-only (%s)", st.Dir, st.Reason)
|
||||
if st.Detail != "" {
|
||||
msg += ": " + st.Detail
|
||||
}
|
||||
a.emitLog("app", msg)
|
||||
case len(st.Migrated) > 0:
|
||||
a.emitLog("app", fmt.Sprintf("Data folder upgraded to layout v%d (%s)", st.Version, strings.Join(st.Migrated, ", ")))
|
||||
}
|
||||
}
|
||||
|
||||
// dataRootUsable reports whether anything may read the data folder through
|
||||
// reims-ctl or write to it: not before first-run setup has chosen a folder,
|
||||
// and not while the folder is open read-only.
|
||||
func (a *App) dataRootUsable() bool {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return !a.needsSetup && !a.root.ReadOnly
|
||||
}
|
||||
|
||||
// requireWritableDataRoot is the guard for bindings that change the data
|
||||
// folder and can be reached without the main window, such as a VM start
|
||||
// handed over from the CLI.
|
||||
func (a *App) requireWritableDataRoot() error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.needsSetup {
|
||||
return i18n.NewCodedError(i18n.EffectiveLocale(a.cfg.Locale), "E_DATAROOT_SETUP", "err.dataroot.needs_setup", nil, nil)
|
||||
}
|
||||
return dataroot.Error(i18n.EffectiveLocale(a.cfg.Locale), a.root)
|
||||
}
|
||||
|
||||
// saveConfigLocked persists a.cfg; a.mu must be held. Before first-run setup
|
||||
// a.cfg points at a suggested folder the user has not chosen, so changes stay
|
||||
// in memory until CompleteSetup writes them into the chosen folder. A folder
|
||||
// open read-only refuses the write.
|
||||
func (a *App) saveConfigLocked() error {
|
||||
if a.needsSetup {
|
||||
return nil
|
||||
}
|
||||
if err := dataroot.Error(i18n.EffectiveLocale(a.cfg.Locale), a.root); err != nil {
|
||||
return err
|
||||
}
|
||||
return config.Save("", a.cfg)
|
||||
}
|
||||
|
||||
// ReopenDataRoot opens the current data folder again: after another process
|
||||
// finished upgrading it, after a failed upgrade, or with repair set, to rebuild
|
||||
// a damaged version record on the user's request. When the folder becomes
|
||||
// writable, the parts that were held back start.
|
||||
func (a *App) ReopenDataRoot(repair bool) (dataroot.Status, error) {
|
||||
a.mu.Lock()
|
||||
if a.needsSetup {
|
||||
st := a.root
|
||||
a.mu.Unlock()
|
||||
return st, nil
|
||||
}
|
||||
dir := a.cfg.DataRoot
|
||||
wasReadOnly := a.root.ReadOnly
|
||||
a.mu.Unlock()
|
||||
|
||||
var st dataroot.Status
|
||||
if repair {
|
||||
st = dataroot.Repair(dir, version.Version)
|
||||
} else {
|
||||
st = dataroot.Open(dir, version.Version)
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.root = st
|
||||
a.mu.Unlock()
|
||||
a.logDataRoot(st)
|
||||
|
||||
if wasReadOnly && st.Writable() {
|
||||
a.resetDataRootCaches()
|
||||
a.reloadPlugins()
|
||||
a.wakePoll()
|
||||
}
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return st, nil
|
||||
}
|
||||
|
||||
// dataRootMessage is the localized explanation the read-only screen shows,
|
||||
// without the error code and raw detail (shown separately).
|
||||
func dataRootMessage(loc i18n.Locale, st dataroot.Status) string {
|
||||
var ce *i18n.CodedError
|
||||
if errors.As(dataroot.Error(loc, st), &ce) {
|
||||
return ce.Summary(loc)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/datamigrate"
|
||||
"github.com/Nwflower/reims-go/internal/dataroot"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
)
|
||||
|
||||
func dirEntries(t *testing.T, dir string) []string {
|
||||
t.Helper()
|
||||
var out []string
|
||||
_ = filepath.Walk(dir, func(p string, _ os.FileInfo, err error) error {
|
||||
if err == nil && p != dir {
|
||||
out = append(out, p)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// Before first-run setup a.cfg only suggests a folder. Picking a language on
|
||||
// the setup screen or starting plugins must not write anything into it.
|
||||
func TestNothingWrittenBeforeSetup(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default()
|
||||
cfg.DataRoot = dir
|
||||
a := &App{cfg: cfg, needsSetup: true}
|
||||
|
||||
if err := a.SetLocale("en-US"); err != nil {
|
||||
t.Fatalf("SetLocale before setup: %v", err)
|
||||
}
|
||||
if a.cfg.Locale != "en-US" {
|
||||
t.Fatalf("locale not kept in memory: %q", a.cfg.Locale)
|
||||
}
|
||||
a.initPlugins()
|
||||
if a.pluginMgr != nil {
|
||||
t.Fatal("plugins started before setup")
|
||||
}
|
||||
a.appendUICrashLog("renderer unresponsive")
|
||||
if got := dirEntries(t, dir); len(got) != 0 {
|
||||
t.Fatalf("suggested folder written before setup: %v", got)
|
||||
}
|
||||
if err := a.StartVM("mac"); err == nil {
|
||||
t.Fatal("StartVM before setup must be refused")
|
||||
}
|
||||
}
|
||||
|
||||
// A folder written by a newer release opens read-only: settings, VM starts
|
||||
// and plugins are all refused, and the folder is left as it was.
|
||||
func TestReadOnlyFolderRefusesWrites(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfgPath := filepath.Join(dir, "reims-go.json")
|
||||
if err := os.WriteFile(cfgPath, []byte(`{"data_root": "x", "locale": "zh-CN"}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, datamigrate.StampFile), []byte(`{"data_version": 999}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := dirEntries(t, dir)
|
||||
|
||||
cfg := config.Default()
|
||||
cfg.DataRoot = dir
|
||||
a := &App{cfg: cfg, root: dataroot.Open(dir, version.Version)}
|
||||
if !a.root.ReadOnly {
|
||||
t.Fatalf("root = %+v, want read-only", a.root)
|
||||
}
|
||||
|
||||
if err := a.SetLocale("en-US"); err == nil {
|
||||
t.Fatal("SetLocale on a read-only folder must fail")
|
||||
}
|
||||
if raw, _ := os.ReadFile(cfgPath); string(raw) != `{"data_root": "x", "locale": "zh-CN"}` {
|
||||
t.Fatalf("config rewritten: %s", raw)
|
||||
}
|
||||
if err := a.StartVM("mac"); err == nil {
|
||||
t.Fatal("StartVM on a read-only folder must be refused")
|
||||
}
|
||||
a.initPlugins()
|
||||
if a.pluginMgr != nil {
|
||||
t.Fatal("plugins started on a read-only folder")
|
||||
}
|
||||
a.appendUICrashLog("renderer unresponsive")
|
||||
if got := dirEntries(t, dir); len(got) != len(before) {
|
||||
t.Fatalf("read-only folder changed: before %v, after %v", before, got)
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
@@ -20,7 +20,8 @@ type diagnosticsBundle struct {
|
||||
HostReport host.Report
|
||||
Optimizations []host.Optimization
|
||||
Runtime *rt.Installed
|
||||
VMDetail *reims.VMDetail
|
||||
VMDetail any // legacy test/export payload; production uses VMInfo
|
||||
VMInfo *driver.VMInfo
|
||||
SerialLog string
|
||||
QEMULog string
|
||||
AppLogs []string
|
||||
@@ -41,7 +42,7 @@ func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = w.Write([]byte(reims.RedactText(content)))
|
||||
_, err = w.Write([]byte(host.RedactText(content)))
|
||||
return err
|
||||
}
|
||||
addJSON := func(name string, v any) error {
|
||||
@@ -57,7 +58,7 @@ func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error {
|
||||
"host": b.HostReport,
|
||||
"optimizations": b.Optimizations,
|
||||
}
|
||||
if code, detail := reims.DiagnoseGPULog(b.QEMULog); code != "" {
|
||||
if code, detail := host.DiagnoseGPULog(b.QEMULog); code != "" {
|
||||
hostSummary["gpu_diagnosis"] = map[string]string{
|
||||
"code": code,
|
||||
"detail": detail,
|
||||
@@ -76,10 +77,14 @@ func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error {
|
||||
}
|
||||
}
|
||||
if b.VMDetail != nil {
|
||||
sanitized := *b.VMDetail
|
||||
sanitized.NetworkSummary = reims.RedactLogLine(sanitized.NetworkSummary)
|
||||
sanitized.ExtraArgs = reims.RedactLogLine(sanitized.ExtraArgs)
|
||||
if err := addJSON("vm-detail.json", sanitized); err != nil {
|
||||
if err := addJSON("vm-detail.json", b.VMDetail); err != nil {
|
||||
_ = zw.Close()
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
if b.VMInfo != nil {
|
||||
if err := addJSON("vm-info.json", b.VMInfo); err != nil {
|
||||
_ = zw.Close()
|
||||
_ = f.Close()
|
||||
return err
|
||||
@@ -120,52 +125,48 @@ func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error {
|
||||
return f.Close()
|
||||
}
|
||||
|
||||
// ExportDiagnostics collects a redacted troubleshooting zip bundle (host probe,
|
||||
// runtime manifest, VM detail, serial/QEMU logs, and recent app logs) into
|
||||
// `<DataRoot>/reports/` and opens the folder in File Explorer.
|
||||
// ExportDiagnostics collects a redacted troubleshooting zip bundle through the owning driver.
|
||||
func (a *App) ExportDiagnostics(name string) (string, error) {
|
||||
return a.ExportDiagnosticsWithDriver("", name)
|
||||
}
|
||||
func (a *App) ExportDiagnosticsWithDriver(driverID, name string) (string, error) {
|
||||
var vm driver.VMInfo
|
||||
var err error
|
||||
if strings.TrimSpace(name) != "" {
|
||||
vm, err = a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
appLogs := append([]string(nil), a.recentLogs...)
|
||||
a.mu.Unlock()
|
||||
|
||||
rep := host.Inspect(cfgCopy.DataRoot)
|
||||
var active *rt.Installed
|
||||
var patchNames []string
|
||||
if inst, err := rt.ResolveActive(&cfgCopy); err == nil {
|
||||
active = inst
|
||||
for _, p := range inst.Manifest.Patches {
|
||||
patchNames = append(patchNames, p.Name)
|
||||
}
|
||||
}
|
||||
bundle := diagnosticsBundle{
|
||||
HostReport: rep,
|
||||
Optimizations: host.EvaluateOptimizations(rep, patchNames),
|
||||
Runtime: active,
|
||||
AppLogs: appLogs,
|
||||
PluginDiagnostics: a.collectPluginDiagnostics(context.Background(), name),
|
||||
}
|
||||
|
||||
active, _ := rt.ResolveActive(&cfgCopy)
|
||||
bundle := diagnosticsBundle{}
|
||||
label := "host"
|
||||
if strings.TrimSpace(name) != "" {
|
||||
label = name
|
||||
if c, err := a.client(); err == nil {
|
||||
ctx := context.Background()
|
||||
if d, derr := a.GetVMDetail(name); derr == nil {
|
||||
bundle.VMDetail = &d
|
||||
}
|
||||
if serial, serr := c.ReadLogs(ctx, name, true); serr == nil {
|
||||
bundle.SerialLog = serial
|
||||
}
|
||||
if qemuLog, qerr := c.ReadLogs(ctx, name, false); qerr == nil {
|
||||
bundle.QEMULog = qemuLog
|
||||
}
|
||||
pluginKey := ""
|
||||
var info *driver.VMInfo
|
||||
if vm.Name != "" {
|
||||
info = &vm
|
||||
label = vm.Name
|
||||
ref := vm.Ref()
|
||||
pluginKey = ref.Key()
|
||||
if ref.DriverID != driver.BuiltinReimsMacOSDriverID {
|
||||
label = sshHostAliasForDriver(ref.DriverID, vm.Name)
|
||||
}
|
||||
if serial, err := a.ReadVMLogsWithDriver(ref.DriverID, vm.Name, true); err == nil {
|
||||
bundle.SerialLog = serial
|
||||
}
|
||||
if qemuLog, err := a.ReadVMLogsWithDriver(ref.DriverID, vm.Name, false); err == nil {
|
||||
bundle.QEMULog = qemuLog
|
||||
}
|
||||
}
|
||||
|
||||
bundle.HostReport, bundle.Optimizations, bundle.Runtime, bundle.AppLogs = rep, a.evaluateOptimizations(rep), active, appLogs
|
||||
bundle.VMInfo, bundle.PluginDiagnostics = info, a.collectPluginDiagnostics(context.Background(), pluginKey)
|
||||
reportsDir := filepath.Join(cfgCopy.DataRoot, "reports")
|
||||
zipName := fmt.Sprintf("reims-go-diag-%s-%s.zip", label, time.Now().Format("20060102-150405"))
|
||||
zipPath := filepath.Join(reportsDir, zipName)
|
||||
zipPath := filepath.Join(reportsDir, fmt.Sprintf("reims-go-diag-%s-%s.zip", label, time.Now().Format("20060102-150405")))
|
||||
if err := writeDiagnosticsZip(zipPath, bundle); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
@@ -7,8 +7,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
)
|
||||
|
||||
func TestWriteDiagnosticsZipRedactsSensitiveData(t *testing.T) {
|
||||
|
||||
+38
-86
@@ -2,115 +2,67 @@ package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
)
|
||||
|
||||
// ResizeVMDisk expands a stopped VM's virtual disk via `qemu-img resize` and
|
||||
// returns the macOS `diskutil` command needed to grow the APFS container inside
|
||||
// the guest.
|
||||
func (a *App) ResizeVMDisk(name, newSize string) (reims.DiskResizeResult, error) {
|
||||
// ResizeVMDisk expands a stopped VM's virtual disk through its owning driver.
|
||||
func (a *App) ResizeVMDisk(name, newSize string) (driver.DiskResizeResult, error) {
|
||||
return a.ResizeVMDiskWithDriver("", name, newSize)
|
||||
}
|
||||
func (a *App) ResizeVMDiskWithDriver(driverID, name, newSize string) (driver.DiskResizeResult, error) {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return reims.DiskResizeResult{}, err
|
||||
if svc == nil {
|
||||
return driver.DiskResizeResult{}, errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
ctx := a.baseCtx()
|
||||
|
||||
d, release, err := vmstart.LockVM(ctx, c, name)
|
||||
if err != nil {
|
||||
return reims.DiskResizeResult{}, err
|
||||
}
|
||||
defer release()
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
return reims.DiskResizeResult{}, fmt.Errorf("stop %s before resizing its disk", name)
|
||||
}
|
||||
if a.isVMSuspended(d) {
|
||||
return reims.DiskResizeResult{}, fmt.Errorf("resume or discard suspend state for %s before resizing its disk", name)
|
||||
}
|
||||
diskPath := resolveVMDiskPath(d)
|
||||
if diskPath == "" {
|
||||
return reims.DiskResizeResult{}, fmt.Errorf("VM %s has no disk path", name)
|
||||
}
|
||||
|
||||
taskCtx, cancel := context.WithCancel(ctx)
|
||||
ref := driver.VMRef{DriverID: driverID, Name: name}
|
||||
taskCtx, cancel := context.WithCancel(a.baseCtx())
|
||||
defer cancel()
|
||||
_, w, finishTask := a.ctlTaskWriterWithCancel("vm-disk-resize", name, cancel)
|
||||
a.emitLog(name, fmt.Sprintf("Resizing disk for %s (%s)...", name, strings.TrimSpace(newSize)))
|
||||
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
res, err := reims.ResizeDisk(taskCtx, active.QemuImgPath(), env, diskPath, newSize, w, w)
|
||||
_, w, finishTask := a.ctlTaskWriterWithCancel("vm-disk-resize", ref.Key(), cancel)
|
||||
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Resizing disk for %s (%s)...", name, strings.TrimSpace(newSize)))
|
||||
res, err := svc.ResizeDisk(taskCtx, ref, newSize, w, w)
|
||||
if err != nil {
|
||||
finishTask(err)
|
||||
a.emitLog(name, "Disk resize error: "+err.Error())
|
||||
return reims.DiskResizeResult{}, err
|
||||
a.emitVMLogForDriver(driverID, name, "Disk resize error: "+err.Error())
|
||||
return driver.DiskResizeResult{}, err
|
||||
}
|
||||
finishTask(nil)
|
||||
a.emitLog(name, fmt.Sprintf("Expanded disk for %s: %.0f GB -> %.0f GB (run diskutil inside macOS to expand APFS)",
|
||||
name, float64(res.OldVirtualBytes)/float64(1<<30), float64(res.NewVirtualBytes)/float64(1<<30)))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Expanded disk for %s: %.0f GB -> %.0f GB", name, float64(res.OldVirtualBytes)/float64(1<<30), float64(res.NewVirtualBytes)/float64(1<<30)))
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// CompactVMDisk rewrites a stopped VM's standalone qcow2 image into a freshly
|
||||
// compacted sparse qcow2 file to reclaim unused/TRIMmed host disk space.
|
||||
func (a *App) CompactVMDisk(name string) (reims.DiskCompactResult, error) {
|
||||
// CompactVMDisk reclaims unused host space through the owning driver.
|
||||
func (a *App) CompactVMDisk(name string) (driver.DiskCompactResult, error) {
|
||||
return a.CompactVMDiskWithDriver("", name)
|
||||
}
|
||||
func (a *App) CompactVMDiskWithDriver(driverID, name string) (driver.DiskCompactResult, error) {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return reims.DiskCompactResult{}, err
|
||||
if svc == nil {
|
||||
return driver.DiskCompactResult{}, errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
ctx := a.baseCtx()
|
||||
|
||||
d, release, err := vmstart.LockVM(ctx, c, name)
|
||||
if err != nil {
|
||||
return reims.DiskCompactResult{}, err
|
||||
}
|
||||
defer release()
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
return reims.DiskCompactResult{}, fmt.Errorf("stop %s before reclaiming disk space", name)
|
||||
}
|
||||
if a.isVMSuspended(d) {
|
||||
return reims.DiskCompactResult{}, fmt.Errorf("resume or discard suspend state for %s before reclaiming disk space", name)
|
||||
}
|
||||
diskPath := resolveVMDiskPath(d)
|
||||
if diskPath == "" {
|
||||
return reims.DiskCompactResult{}, fmt.Errorf("VM %s has no disk path", name)
|
||||
}
|
||||
|
||||
taskCtx, cancel := context.WithCancel(ctx)
|
||||
ref := driver.VMRef{DriverID: driverID, Name: name}
|
||||
taskCtx, cancel := context.WithCancel(a.baseCtx())
|
||||
defer cancel()
|
||||
_, w, finishTask := a.ctlTaskWriterWithCancel("vm-disk-compact", name, cancel)
|
||||
a.emitLog(name, fmt.Sprintf("Compacting qcow2 disk for %s to reclaim unused space...", name))
|
||||
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
res, err := reims.CompactDisk(taskCtx, active.QemuImgPath(), env, diskPath, w, w)
|
||||
_, w, finishTask := a.ctlTaskWriterWithCancel("vm-disk-compact", ref.Key(), cancel)
|
||||
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Compacting disk for %s to reclaim unused space...", name))
|
||||
res, err := svc.CompactDisk(taskCtx, ref, w, w)
|
||||
if err != nil {
|
||||
finishTask(err)
|
||||
a.emitLog(name, "Disk compact error: "+err.Error())
|
||||
return reims.DiskCompactResult{}, err
|
||||
a.emitVMLogForDriver(driverID, name, "Disk compact error: "+err.Error())
|
||||
return driver.DiskCompactResult{}, err
|
||||
}
|
||||
finishTask(nil)
|
||||
a.emitLog(name, fmt.Sprintf("Compacted disk for %s: %.2f GB -> %.2f GB (reclaimed %.2f GB)",
|
||||
name,
|
||||
float64(res.BeforeBytes)/float64(1<<30),
|
||||
float64(res.AfterBytes)/float64(1<<30),
|
||||
float64(res.ReclaimedBytes)/float64(1<<30)))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Compacted disk for %s: %.2f GB -> %.2f GB (reclaimed %.2f GB)", name, float64(res.BeforeBytes)/float64(1<<30), float64(res.AfterBytes)/float64(1<<30), float64(res.ReclaimedBytes)/float64(1<<30)))
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return res, nil
|
||||
}
|
||||
@@ -179,7 +179,7 @@ func (a *App) SetVMDriveShareSettings(name string, enabled bool, drives []string
|
||||
return DriveShareSettings{}, err
|
||||
}
|
||||
srv.RegisterVM(validatedDriveConfig(cfg))
|
||||
a.emitLog(name, fmt.Sprintf("Read-only Windows drive sharing enabled=%v drives=%v", enabled, normalized))
|
||||
a.emitVMLog(name, fmt.Sprintf("Read-only Windows drive sharing enabled=%v drives=%v", enabled, normalized))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
)
|
||||
|
||||
const vmNoteFileName = ".reims-go-note"
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
)
|
||||
|
||||
func TestParseDiskSnapshotsJSON(t *testing.T) {
|
||||
|
||||
@@ -10,10 +10,11 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
@@ -33,6 +34,20 @@ func (a *App) guestToolsImagePath(name string) string {
|
||||
return filepath.Join(cacheDir, "reims-go", "guest-tools", name+"-tools.img")
|
||||
}
|
||||
|
||||
// buildGuestToolsImage runs in the macOS driver after all start hooks pass.
|
||||
func (a *App) buildGuestToolsImage(vmName, vmDir string) error {
|
||||
_, port, _, err := a.startGuestToolsServer()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg, err := guesttools.LoadOrCreateVMConfig(vmDir, vmName, a.vmSharedDir(vmName), port)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg = validatedDriveConfig(cfg)
|
||||
return guesttools.BuildToolsDiskImage(a.guestToolsImagePath(vmName), cfg)
|
||||
}
|
||||
|
||||
// startGuestToolsServer starts the shared localhost HTTP bridge once. Only the
|
||||
// Guest Tools plugin and the no-plugin-manager fallback may call it; created
|
||||
// reports whether this call made a new server.
|
||||
@@ -45,14 +60,14 @@ func (a *App) startGuestToolsServer() (srv *guesttools.Server, port int, created
|
||||
} else {
|
||||
srv = guesttools.NewServer(nil)
|
||||
}
|
||||
srv.SetHostTextHandler(func(vmName, text string) {
|
||||
srv.SetHostTextHandler(func(vmKey, vmName, text string) {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
if mgr != nil && !mgr.Registry().IsActive(builtin.IDInput) {
|
||||
return
|
||||
}
|
||||
a.injectRemoteText(vmName, "", text)
|
||||
a.injectRemoteTextRef(vmKey, vmName, "", text)
|
||||
})
|
||||
a.guestTools = srv
|
||||
created = true
|
||||
@@ -191,13 +206,13 @@ func (a *App) syncGuestTools(c *reims.Client, name string, cur *reims.VMDetail)
|
||||
}
|
||||
srv, port, err := a.ensureGuestToolsBridge()
|
||||
if err != nil {
|
||||
a.emitLog(name, "Warning: could not start Guest Tools bridge: "+err.Error())
|
||||
a.emitVMLog(name, "Warning: could not start Guest Tools bridge: "+err.Error())
|
||||
return
|
||||
}
|
||||
sharedDir := a.vmSharedDir(name)
|
||||
cfg, err = guesttools.LoadOrCreateVMConfig(cur.Directory, name, sharedDir, port)
|
||||
if err != nil {
|
||||
a.emitLog(name, "Warning: could not load Guest Tools config: "+err.Error())
|
||||
a.emitVMLog(name, "Warning: could not load Guest Tools config: "+err.Error())
|
||||
return
|
||||
}
|
||||
srv.RegisterVM(validatedDriveConfig(cfg))
|
||||
@@ -206,7 +221,7 @@ func (a *App) syncGuestTools(c *reims.Client, name string, cur *reims.VMDetail)
|
||||
}
|
||||
imgPath := a.guestToolsImagePath(name)
|
||||
if err := guesttools.BuildToolsDiskImage(imgPath, cfg); err != nil {
|
||||
a.emitLog(name, "Warning: could not refresh REIMSTOOLS disk: "+err.Error())
|
||||
a.emitVMLog(name, "Warning: could not refresh REIMSTOOLS disk: "+err.Error())
|
||||
return
|
||||
}
|
||||
merged := reims.MergeGuestToolsArgs(cur.ExtraArgs, imgPath)
|
||||
@@ -225,7 +240,7 @@ func (a *App) AttachGuestTools(name string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
|
||||
d, release, err := startprep.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -249,7 +264,7 @@ func (a *App) AttachGuestTools(name string) error {
|
||||
return fmt.Errorf("build REIMSTOOLS disk: %w", err)
|
||||
}
|
||||
merged := reims.MergeGuestToolsArgs(d.ExtraArgs, imgPath)
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
ctx := context.Background()
|
||||
if merged != d.ExtraArgs {
|
||||
if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &merged}, w, w); err != nil {
|
||||
@@ -258,14 +273,14 @@ func (a *App) AttachGuestTools(name string) error {
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
|
||||
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
|
||||
Field: "guest_tools",
|
||||
From: "detached",
|
||||
To: "attached",
|
||||
})
|
||||
a.mu.Unlock()
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Guest Tools disk (REIMSTOOLS) attached on 127.0.0.1:%d; shared folder: %s", port, sharedDir))
|
||||
a.emitVMLog(name, fmt.Sprintf("Guest Tools disk (REIMSTOOLS) attached on 127.0.0.1:%d; shared folder: %s", port, sharedDir))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
@@ -279,21 +294,21 @@ func (a *App) DetachGuestTools(name string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
|
||||
d, release, err := startprep.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
stripped := reims.StripGuestToolsArgs(d.ExtraArgs)
|
||||
ctx := context.Background()
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
if stripped != d.ExtraArgs {
|
||||
if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &stripped}, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
|
||||
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
|
||||
Field: "guest_tools",
|
||||
From: "attached",
|
||||
To: "ejected",
|
||||
@@ -301,7 +316,7 @@ func (a *App) DetachGuestTools(name string) error {
|
||||
a.mu.Unlock()
|
||||
}
|
||||
}
|
||||
a.emitLog(name, "Guest Tools disk (REIMSTOOLS) ejected; clipboard & shared folder bridge remains active")
|
||||
a.emitVMLog(name, "Guest Tools disk (REIMSTOOLS) ejected; clipboard & shared folder bridge remains active")
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
@@ -342,7 +357,7 @@ func (a *App) SetGuestPreventSleep(name string, enabled bool) error {
|
||||
}
|
||||
srv.RegisterVM(validatedDriveConfig(cfg))
|
||||
srv.SetPreventSleep(name, enabled)
|
||||
a.emitLog(name, fmt.Sprintf("Guest Tools prevent-sleep guard set to %v", enabled))
|
||||
a.emitVMLog(name, fmt.Sprintf("Guest Tools prevent-sleep guard set to %v", enabled))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
@@ -428,6 +443,6 @@ func (a *App) deliverHostFile(name, picked string) (string, error) {
|
||||
_ = os.Remove(tmpName)
|
||||
return "", err
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Delivered %s to shared folder (%s)", base, sharedDir))
|
||||
a.emitVMLog(name, fmt.Sprintf("Delivered %s to shared folder (%s)", base, sharedDir))
|
||||
return base, nil
|
||||
}
|
||||
+161
-49
@@ -10,8 +10,10 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
@@ -26,7 +28,7 @@ func isRecoveryModeActive(d reims.VMDetail) bool {
|
||||
if d.HasInstaller {
|
||||
return true
|
||||
}
|
||||
m := vmstart.ReadRecoveryMarker(d.Directory)
|
||||
m := startprep.ReadRecoveryMarker(d.Directory)
|
||||
return m == "on" || m == "want"
|
||||
}
|
||||
|
||||
@@ -71,46 +73,77 @@ func (a *App) isVMRunning(ctx context.Context, c *reims.Client, name string, d r
|
||||
return false
|
||||
}
|
||||
|
||||
// EnterRecovery routes the macOS recovery action through the lifecycle service.
|
||||
// The legacy path remains available for minimal embedding without a plugin manager.
|
||||
func (a *App) EnterRecovery(name string) error {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
return a.enterRecoveryLegacy(name)
|
||||
}
|
||||
raw, err := svc.InvokeAction(context.Background(), driver.NewVMRef("", name), "enter_recovery", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, _ := raw.(map[string]any)
|
||||
running, _ := result["running"].(bool)
|
||||
if running {
|
||||
scheduled, _ := result["scheduled"].(bool)
|
||||
if scheduled {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{Field: "recovery", From: "off", To: "on"})
|
||||
a.mu.Unlock()
|
||||
}
|
||||
a.emitVMLog(name, "Recovery mode scheduled for "+name+": OpenCore boot picker will open on next start")
|
||||
} else {
|
||||
a.emitVMLog(name, "Recovery mode enabled for "+name+" (pick Recovery in OpenCore boot menu)")
|
||||
}
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnterRecovery enables OpenCore's boot picker (--boot-selection=true) so the
|
||||
// VM can boot macOS's built-in Recovery volume without needing an external
|
||||
// installer image (upstream reims-util 7867384 sets HideAuxiliary=false).
|
||||
// If the VM is running, the change is queued for the next start/restart.
|
||||
func (a *App) EnterRecovery(name string) error {
|
||||
func (a *App) enterRecoveryLegacy(name string) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
|
||||
d, release, err := startprep.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
ctx := context.Background()
|
||||
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
marker := vmstart.ReadRecoveryMarker(d.Directory)
|
||||
marker := startprep.ReadRecoveryMarker(d.Directory)
|
||||
if marker != "on" {
|
||||
vmstart.WriteRecoveryMarker(d.Directory, "want")
|
||||
startprep.WriteRecoveryMarker(d.Directory, "want")
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
|
||||
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
|
||||
Field: "recovery",
|
||||
From: "off",
|
||||
To: "on",
|
||||
})
|
||||
a.mu.Unlock()
|
||||
}
|
||||
a.emitLog(name, "Recovery mode scheduled for "+name+": OpenCore boot picker will open on next start")
|
||||
a.emitVMLog(name, "Recovery mode scheduled for "+name+": OpenCore boot picker will open on next start")
|
||||
} else {
|
||||
a.emitLog(name, "Enabling OpenCore boot picker for recovery mode...")
|
||||
a.emitVMLog(name, "Enabling OpenCore boot picker for recovery mode...")
|
||||
if err := c.UpdateOpenCore(ctx, name, true, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
vmstart.WriteRecoveryMarker(d.Directory, "on")
|
||||
startprep.WriteRecoveryMarker(d.Directory, "on")
|
||||
if prep, err := a.prep(name); err == nil {
|
||||
prep.ReplayGuestLang(ctx, d.Directory)
|
||||
}
|
||||
a.emitLog(name, "Recovery mode enabled for "+name+" (pick Recovery in OpenCore boot menu)")
|
||||
a.emitVMLog(name, "Recovery mode enabled for "+name+" (pick Recovery in OpenCore boot menu)")
|
||||
}
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
@@ -127,11 +160,23 @@ func (a *App) AttachInstaller(name, installerPath string) (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
var d reims.VMDetail
|
||||
if svc == nil {
|
||||
var release func()
|
||||
d, release, err = startprep.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer release()
|
||||
} else {
|
||||
d, err = c.Show(a.baseCtx(), name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
defer release()
|
||||
path := strings.TrimSpace(installerPath)
|
||||
if path == "" {
|
||||
path, err = a.pickCachedRecoveryInstaller()
|
||||
@@ -142,17 +187,22 @@ func (a *App) AttachInstaller(name, installerPath string) (string, error) {
|
||||
return "", errors.New("no cached installer image found")
|
||||
}
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
ctx := context.Background()
|
||||
|
||||
base := filepath.Base(path)
|
||||
a.emitLog(name, "Attaching installer image to "+name+": "+base)
|
||||
if err := c.Insert(ctx, name, path, w, w); err != nil {
|
||||
a.emitVMLog(name, "Attaching installer image to "+name+": "+base)
|
||||
if svc != nil {
|
||||
_, err = svc.InvokeAction(ctx, driver.NewVMRef("", name), "insert", map[string]any{"path": path})
|
||||
} else {
|
||||
err = c.Insert(ctx, name, path, w, w)
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
|
||||
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
|
||||
Field: "installer",
|
||||
From: "ejected",
|
||||
To: "attached",
|
||||
@@ -192,7 +242,7 @@ func (a *App) DownloadAndAttachOnlineRecovery(name, version string) (string, err
|
||||
}
|
||||
ctx, cancel := context.WithCancel(base)
|
||||
id := tasks.start("recovery-download", name, name, cancel)
|
||||
a.emitLog(name, "Downloading Apple online recovery image (~1 GB) for "+name+"...")
|
||||
a.emitVMLog(name, "Downloading Apple online recovery image (~1 GB) for "+name+"...")
|
||||
go func() {
|
||||
defer cancel()
|
||||
res, err := a.ensureInstallerForTask(ctx, id, "recovery-download", name, "online", v, func(dlCtx context.Context, onUpdate func(installer.Update)) (*installer.Result, error) {
|
||||
@@ -200,10 +250,10 @@ func (a *App) DownloadAndAttachOnlineRecovery(name, version string) (string, err
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, context.Canceled) || ctx.Err() != nil {
|
||||
a.emitLog(name, "Online recovery download paused; starting again continues where it stopped")
|
||||
a.emitVMLog(name, "Online recovery download paused; starting again continues where it stopped")
|
||||
tasks.finish(id, "", context.Canceled)
|
||||
} else {
|
||||
a.emitLog(name, "Online recovery download error: "+err.Error())
|
||||
a.emitVMLog(name, "Online recovery download error: "+err.Error())
|
||||
tasks.finish(id, "", err)
|
||||
}
|
||||
return
|
||||
@@ -216,34 +266,79 @@ func (a *App) DownloadAndAttachOnlineRecovery(name, version string) (string, err
|
||||
})
|
||||
attached, err := a.AttachInstaller(name, res.Image)
|
||||
if err != nil {
|
||||
a.emitLog(name, "Failed to attach online recovery image: "+err.Error())
|
||||
a.emitVMLog(name, "Failed to attach online recovery image: "+err.Error())
|
||||
tasks.finish(id, "", err)
|
||||
return
|
||||
}
|
||||
a.emitLog(name, "Online recovery image attached: "+attached)
|
||||
a.emitVMLog(name, "Online recovery image attached: "+attached)
|
||||
tasks.finish(id, attached, nil)
|
||||
}()
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// FinishInstall exits recovery through the owning driver and mirrors deferred
|
||||
// changes into the existing App pending-change model.
|
||||
func (a *App) FinishInstall(name string) error {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
return a.finishInstallLegacy(name)
|
||||
}
|
||||
raw, err := svc.InvokeAction(context.Background(), driver.NewVMRef("", name), "finish_install", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, _ := raw.(map[string]any)
|
||||
running, _ := result["running"].(bool)
|
||||
if running {
|
||||
var diffs []PendingChange
|
||||
if value, _ := result["installer_ejected"].(bool); value {
|
||||
diffs = append(diffs, PendingChange{Field: "installer", From: "attached", To: "ejected"})
|
||||
}
|
||||
if value, _ := result["network_enabled"].(bool); value {
|
||||
diffs = append(diffs, PendingChange{Field: "network", From: "off", To: "on"})
|
||||
}
|
||||
if value, _ := result["upgraded_nvme"].(bool); value {
|
||||
from, _ := result["disk_controller_from"].(string)
|
||||
if from == "" {
|
||||
from = "ahci"
|
||||
}
|
||||
diffs = append(diffs, PendingChange{Field: "disk_controller", From: from, To: "nvme"})
|
||||
}
|
||||
if value, _ := result["recovery_pending"].(bool); value {
|
||||
diffs = append(diffs, PendingChange{Field: "recovery", From: "on", To: "off"})
|
||||
}
|
||||
if len(diffs) > 0 {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], diffs...)
|
||||
a.mu.Unlock()
|
||||
}
|
||||
}
|
||||
a.emitVMLog(name, "Exited recovery mode")
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return nil
|
||||
}
|
||||
|
||||
// FinishInstall exits recovery mode: ejects any attached installer, removes
|
||||
// REIMSHELP, enables the network if off, and restores OpenCore direct boot
|
||||
// (--boot-selection=false) if recovery mode enabled the boot picker.
|
||||
func (a *App) FinishInstall(name string) error {
|
||||
func (a *App) finishInstallLegacy(name string) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
|
||||
d, release, err := startprep.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
ctx := context.Background()
|
||||
|
||||
if d.HasInstaller {
|
||||
a.emitLog(name, "Ejecting installer from "+name+"...")
|
||||
a.emitVMLog(name, "Ejecting installer from "+name+"...")
|
||||
if err := c.Eject(ctx, name, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -256,13 +351,13 @@ func (a *App) FinishInstall(name string) error {
|
||||
on := true
|
||||
setOpts.Network = &on
|
||||
needSet = true
|
||||
a.emitLog(name, "Turning the network on for "+name+"...")
|
||||
a.emitVMLog(name, "Turning the network on for "+name+"...")
|
||||
}
|
||||
if d.HasInstaller && strings.EqualFold(d.DiskController, "ahci") {
|
||||
setOpts.DiskController = "nvme"
|
||||
needSet = true
|
||||
upgradedNVMe = true
|
||||
a.emitLog(name, "Upgrading disk controller for "+name+" from SATA/AHCI to NVMe...")
|
||||
a.emitVMLog(name, "Upgrading disk controller for "+name+" from SATA/AHCI to NVMe...")
|
||||
}
|
||||
if stripped != d.ExtraArgs {
|
||||
setOpts.ExtraArgs = &stripped
|
||||
@@ -275,7 +370,7 @@ func (a *App) FinishInstall(name string) error {
|
||||
}
|
||||
|
||||
running := a.isVMRunning(ctx, c, name, d)
|
||||
marker := vmstart.ReadRecoveryMarker(d.Directory)
|
||||
marker := startprep.ReadRecoveryMarker(d.Directory)
|
||||
if running {
|
||||
var diffs []PendingChange
|
||||
if d.HasInstaller {
|
||||
@@ -289,32 +384,32 @@ func (a *App) FinishInstall(name string) error {
|
||||
}
|
||||
switch marker {
|
||||
case "want":
|
||||
vmstart.WriteRecoveryMarker(d.Directory, "")
|
||||
startprep.WriteRecoveryMarker(d.Directory, "")
|
||||
case "on":
|
||||
vmstart.WriteRecoveryMarker(d.Directory, "restore")
|
||||
startprep.WriteRecoveryMarker(d.Directory, "restore")
|
||||
diffs = append(diffs, PendingChange{Field: "recovery", From: "on", To: "off"})
|
||||
}
|
||||
if len(diffs) > 0 {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], diffs...)
|
||||
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], diffs...)
|
||||
a.mu.Unlock()
|
||||
}
|
||||
} else {
|
||||
if marker == "on" || marker == "restore" {
|
||||
a.emitLog(name, "Restoring OpenCore direct boot after exiting recovery mode...")
|
||||
a.emitVMLog(name, "Restoring OpenCore direct boot after exiting recovery mode...")
|
||||
if err := c.UpdateOpenCore(ctx, name, false, w, w); err != nil {
|
||||
a.emitLog(name, "Warning: could not disable OpenCore boot picker: "+err.Error())
|
||||
a.emitVMLog(name, "Warning: could not disable OpenCore boot picker: "+err.Error())
|
||||
} else {
|
||||
vmstart.WriteRecoveryMarker(d.Directory, "")
|
||||
startprep.WriteRecoveryMarker(d.Directory, "")
|
||||
if prep, err := a.prep(name); err == nil {
|
||||
prep.ReplayGuestLang(ctx, d.Directory)
|
||||
}
|
||||
}
|
||||
} else if marker != "" {
|
||||
vmstart.WriteRecoveryMarker(d.Directory, "")
|
||||
startprep.WriteRecoveryMarker(d.Directory, "")
|
||||
}
|
||||
}
|
||||
a.emitLog(name, "Exited recovery mode")
|
||||
a.emitVMLog(name, "Exited recovery mode")
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
@@ -328,26 +423,43 @@ func (a *App) UpgradeDiskToNVMe(name string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
var d reims.VMDetail
|
||||
if svc == nil {
|
||||
var release func()
|
||||
d, release, err = startprep.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
} else {
|
||||
d, err = c.Show(a.baseCtx(), name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
defer release()
|
||||
if d.HasInstaller {
|
||||
return errors.New("exit recovery mode (eject installer) before switching disk controller")
|
||||
}
|
||||
if strings.EqualFold(d.DiskController, "nvme") {
|
||||
return nil
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
ctx := context.Background()
|
||||
a.emitLog(name, "Upgrading disk controller for "+name+" to NVMe...")
|
||||
if err := c.Set(ctx, reims.SetOpts{Name: name, DiskController: "nvme"}, w, w); err != nil {
|
||||
a.emitVMLog(name, "Upgrading disk controller for "+name+" to NVMe...")
|
||||
if svc != nil {
|
||||
_, err = svc.InvokeAction(ctx, driver.NewVMRef("", name), "upgrade_nvme", nil)
|
||||
} else {
|
||||
err = c.Set(ctx, reims.SetOpts{Name: name, DiskController: "nvme"}, w, w)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
|
||||
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
|
||||
Field: "disk_controller",
|
||||
From: d.DiskController,
|
||||
To: "nvme",
|
||||
|
||||
@@ -3,11 +3,12 @@ package app
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/installguide"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installguide"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
@@ -20,7 +21,7 @@ func (a *App) getInstallGuideManager() *installguide.Manager {
|
||||
if mgr == nil {
|
||||
return nil
|
||||
}
|
||||
raw, ok := mgr.Registry().LookupService(builtin.ServiceInstallGuide)
|
||||
raw, ok := mgr.Registry().LookupService(guest.ServiceInstallGuide)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
@@ -39,7 +40,7 @@ func (a *App) guidePreferences() (i18n.Locale, installguide.Theme) {
|
||||
rawLoc := a.cfg.Locale
|
||||
th := a.themeMode
|
||||
a.mu.Unlock()
|
||||
return i18n.EffectiveLocale(rawLoc), th
|
||||
return i18n.EffectiveLocale(rawLoc), installguide.Theme(th)
|
||||
}
|
||||
|
||||
func (a *App) bindGuideEvents(ctx context.Context) {
|
||||
@@ -51,7 +52,7 @@ func (a *App) bindGuideEvents(ctx context.Context) {
|
||||
theme := installguide.Theme(raw)
|
||||
if theme == installguide.ThemeLight || theme == installguide.ThemeDark {
|
||||
a.mu.Lock()
|
||||
a.themeMode = theme
|
||||
a.themeMode = string(theme)
|
||||
a.mu.Unlock()
|
||||
}
|
||||
})
|
||||
@@ -72,13 +73,17 @@ func installGuideKind(d reims.VMDetail) (installguide.Kind, bool) {
|
||||
}
|
||||
return installguide.Online, true
|
||||
}
|
||||
return installguide.BuiltIn, vmstart.ReadRecoveryMarker(d.Directory) == "on"
|
||||
return installguide.BuiltIn, startprep.ReadRecoveryMarker(d.Directory) == "on"
|
||||
}
|
||||
|
||||
func (a *App) maybeStartInstallGuide(ctx context.Context, gm *installguide.Manager, name string, pid int, d reims.VMDetail, loc i18n.Locale) bool {
|
||||
func (a *App) maybeStartInstallGuide(ctx context.Context, gm *installguide.Manager, name string, pid int, vm driver.VMInfo, loc i18n.Locale) bool {
|
||||
if gm == nil || pid <= 0 || gm.HasActive(name, pid) {
|
||||
return false
|
||||
}
|
||||
d, err := macOSDetailFromVMInfo(vm)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
kind, recovery := installGuideKind(d)
|
||||
g := installguide.Guide{
|
||||
Name: name,
|
||||
@@ -137,7 +142,7 @@ func (a *App) buildInstallGuide(ctx context.Context, g installguide.Guide, d rei
|
||||
_, err := a.AttachInstaller(name, path)
|
||||
return err
|
||||
}
|
||||
g.LogError = func(err error) { a.emitLog(name, "Installation guide: "+err.Error()) }
|
||||
g.LogError = func(err error) { a.emitVMLog(name, "Installation guide: "+err.Error()) }
|
||||
g.AttachTools = func() error {
|
||||
if err := checkBoot(); err != nil {
|
||||
return err
|
||||
@@ -148,12 +153,12 @@ func (a *App) buildInstallGuide(ctx context.Context, g installguide.Guide, d rei
|
||||
if err := checkBoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
stopped, err := a.restartVM(name)
|
||||
stopped, err := a.restartMacOSVM(name)
|
||||
if stopped && err != nil {
|
||||
// The guest window has closed, so report start failures via the tray.
|
||||
loc, _ := a.guidePreferences()
|
||||
title := i18n.M(loc, "guide.err.restart_failed", i18n.Vars{"name": name})
|
||||
a.emitLog(name, title+": "+err.Error())
|
||||
a.emitVMLog(name, title+": "+err.Error())
|
||||
a.mu.Lock()
|
||||
tm := a.trayMgr
|
||||
a.mu.Unlock()
|
||||
|
||||
@@ -5,12 +5,13 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/installguide"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installguide"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
func TestInstallGuideFollowsBootMedia(t *testing.T) {
|
||||
@@ -24,7 +25,7 @@ func TestInstallGuideFollowsBootMedia(t *testing.T) {
|
||||
{"on", "", installguide.BuiltIn, true}, {"restore", "", installguide.BuiltIn, false},
|
||||
{"", "BaseSystem.img", installguide.Online, true}, {"", "offline-installer-tahoe.img", installguide.Offline, true},
|
||||
} {
|
||||
vmstart.WriteRecoveryMarker(d.Directory, test.marker)
|
||||
startprep.WriteRecoveryMarker(d.Directory, test.marker)
|
||||
d.HasInstaller, d.InstallerPath = test.path != "", test.path
|
||||
if kind, show := installGuideKind(d); kind != test.want || show != test.show {
|
||||
t.Errorf("%+v: got (%d,%t)", test, kind, show)
|
||||
@@ -46,7 +47,7 @@ func TestInstallGuideFollowsPluginSwitch(t *testing.T) {
|
||||
a := &App{
|
||||
cfg: cfg,
|
||||
pluginMgr: mgr,
|
||||
themeMode: installguide.ThemeDark,
|
||||
themeMode: "dark",
|
||||
pollWake: make(chan struct{}, 1),
|
||||
}
|
||||
|
||||
@@ -58,9 +59,10 @@ func TestInstallGuideFollowsPluginSwitch(t *testing.T) {
|
||||
GetConfig: func() config.Config { return *cfg },
|
||||
SyncInstallGuides: a.wakePoll,
|
||||
}
|
||||
if err := builtin.RegisterAll(mgr.Registry(), cb, func(id string, def bool) bool {
|
||||
return id == builtin.IDInstallGuide && def
|
||||
}); err != nil {
|
||||
if err := builtin.RegisterAll(mgr.Registry(), cb, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr.Registry().Reconcile(context.Background())
|
||||
@@ -77,7 +79,7 @@ func TestInstallGuideFollowsPluginSwitch(t *testing.T) {
|
||||
}
|
||||
|
||||
// Disabling the plugin removes the service and closes the guide manager.
|
||||
if err := mgr.Registry().SetDesired(context.Background(), builtin.IDInstallGuide, false); err != nil {
|
||||
if err := mgr.Registry().SetDesired(context.Background(), guest.ID, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a.installGuideEnabled() || a.getInstallGuideManager() != nil {
|
||||
@@ -85,7 +87,7 @@ func TestInstallGuideFollowsPluginSwitch(t *testing.T) {
|
||||
}
|
||||
|
||||
// Re-enabling restores the service and wakes pollVMs to attach running VMs.
|
||||
if err := mgr.Registry().SetDesired(context.Background(), builtin.IDInstallGuide, true); err != nil {
|
||||
if err := mgr.Registry().SetDesired(context.Background(), guest.ID, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !a.installGuideEnabled() {
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
)
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
)
|
||||
|
||||
type installerDownloadFunc func(ctx context.Context, onUpdate func(installer.Update)) (*installer.Result, error)
|
||||
|
||||
@@ -7,8 +7,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
)
|
||||
|
||||
func newTestCoordinator(t *testing.T) {
|
||||
|
||||
@@ -4,7 +4,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"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/qmp"
|
||||
@@ -21,7 +22,7 @@ func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) {
|
||||
ledger := &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{}}
|
||||
active := map[string]bool{
|
||||
builtin.IDGuestTools: true,
|
||||
builtin.IDCore: true,
|
||||
guest.ID: true,
|
||||
}
|
||||
intents := []plugin.StartIntent{
|
||||
{
|
||||
@@ -32,12 +33,12 @@ func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) {
|
||||
}},
|
||||
},
|
||||
{
|
||||
PluginID: builtin.IDCore,
|
||||
PluginID: guest.ID,
|
||||
Args: []plugin.ArgFragment{{
|
||||
PluginID: builtin.IDCore, Key: "reimshelp", Builtin: true, Priority: 85,
|
||||
PluginID: guest.ID, Key: "reimshelp", Builtin: true, Priority: 85,
|
||||
Tokens: plugin.SplitShellTokens(reims.MergeOfflineHelperArgs("", `D:\Data\cache\reimshelp.img`)),
|
||||
}, {
|
||||
PluginID: builtin.IDCore, Key: "win10-cold-reboot", Builtin: true, Priority: 95,
|
||||
PluginID: guest.ID, Key: "win10-cold-reboot", Builtin: true, Priority: 95,
|
||||
Tokens: plugin.SplitShellTokens(qmp.MergeWin10RebootUnixArgs("", `D:\Data\vms\mac\reims-go-reboot.sock`)),
|
||||
}},
|
||||
},
|
||||
@@ -58,7 +59,7 @@ func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) {
|
||||
// Simulate detaching Guest Tools & ejecting offline installer on next start.
|
||||
nextIntents := []plugin.StartIntent{
|
||||
{PluginID: builtin.IDGuestTools, ClearKeys: []string{"reimstools"}},
|
||||
{PluginID: builtin.IDCore, ClearKeys: []string{"reimshelp", "win10-cold-reboot"}},
|
||||
{PluginID: guest.ID, ClearKeys: []string{"reimshelp", "win10-cold-reboot"}},
|
||||
}
|
||||
base2 := stripLegacyManagedExtraArgs(res.ExtraArgs)
|
||||
res2 := plugin.ReconcileStartIntents(base2, ledger, active, nextIntents)
|
||||
@@ -81,15 +82,15 @@ func TestStripLegacyPreservesUserNoReboot(t *testing.T) {
|
||||
// stripped as belonging to a gone plugin and the next start could crash.
|
||||
func TestPreMergeLedgerFragmentsCarriedIntoCore(t *testing.T) {
|
||||
irq := plugin.ArgFragment{
|
||||
PluginID: "builtin.compat.whpx-fallback", Key: "kernel-irqchip", Builtin: true, Priority: 90,
|
||||
PluginID: builtin.IDCore, Key: "kernel-irqchip", Builtin: true, Priority: 90,
|
||||
Tokens: []string{"-machine", "kernel-irqchip=off"},
|
||||
}
|
||||
extra := "-cpu host -machine kernel-irqchip=off"
|
||||
active := map[string]bool{builtin.IDCore: true}
|
||||
intents := []plugin.StartIntent{{PluginID: builtin.IDCore}}
|
||||
active := map[string]bool{guest.ID: true}
|
||||
intents := []plugin.StartIntent{{PluginID: guest.ID}}
|
||||
newLedger := func() *plugin.ArgLedger {
|
||||
return &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{
|
||||
"builtin.compat.whpx-fallback": {irq},
|
||||
builtin.IDCore: {irq},
|
||||
}}
|
||||
}
|
||||
|
||||
@@ -99,7 +100,7 @@ func TestPreMergeLedgerFragmentsCarriedIntoCore(t *testing.T) {
|
||||
}
|
||||
|
||||
ledger := newLedger()
|
||||
if !builtin.MigrateLedger(ledger) {
|
||||
if !guest.MigrateLedger(ledger) {
|
||||
t.Fatal("MigrateLedger reported no change for a retired owner")
|
||||
}
|
||||
res := plugin.ReconcileStartIntents(extra, ledger, active, intents)
|
||||
@@ -109,7 +110,7 @@ func TestPreMergeLedgerFragmentsCarriedIntoCore(t *testing.T) {
|
||||
if !strings.Contains(res.ExtraArgs, "-cpu host") {
|
||||
t.Fatalf("user arg lost: %q", res.ExtraArgs)
|
||||
}
|
||||
if builtin.MigrateLedger(ledger) {
|
||||
if guest.MigrateLedger(ledger) {
|
||||
t.Fatal("MigrateLedger should be a no-op once migrated")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
func (a *App) emitLifecycleStateChanged() {
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) emitVMLogForDriver(driverID, name, line string) {
|
||||
a.emitLog(vmKeyForDriver(driverID, name), line)
|
||||
}
|
||||
|
||||
func (a *App) startHookPayload(_ context.Context, d driver.Driver, vm driver.VMInfo, base plugin.BeforeStartPayload) (plugin.BeforeStartPayload, error) {
|
||||
if d.ID() != builtin.IDDriverReimsMacOS {
|
||||
return base, nil
|
||||
}
|
||||
prep, err := a.prep(vm.Name)
|
||||
if err != nil {
|
||||
return base, err
|
||||
}
|
||||
caps := prep.Runtime.Manifest.EffectiveCapabilities()
|
||||
rep := host.Inspect(a.currentDataRoot())
|
||||
base.RuntimeKind = prep.Runtime.Manifest.EffectiveKind()
|
||||
base.RuntimeCaps = caps
|
||||
base.HostFacts = buildHostFacts(rep, caps)
|
||||
return base, nil
|
||||
}
|
||||
|
||||
func (a *App) currentDataRoot() string {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.cfg.DataRoot
|
||||
}
|
||||
|
||||
func (a *App) evaluateOptimizations(rep host.Report) []host.Optimization {
|
||||
core := host.EvaluateCoreOptimizations(rep)
|
||||
a.mu.Lock()
|
||||
router := a.driverRouter
|
||||
a.mu.Unlock()
|
||||
var extra []host.Optimization
|
||||
if router != nil {
|
||||
for _, drv := range router.Drivers() {
|
||||
if advisor, ok := drv.(driver.OptimizationAdvisor); ok {
|
||||
extra = append(extra, advisor.EvaluateOptimizations(context.Background(), rep)...)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(core) == 0 {
|
||||
return extra
|
||||
}
|
||||
out := append([]host.Optimization{core[0]}, extra...)
|
||||
return append(out, core[1:]...)
|
||||
}
|
||||
|
||||
func (a *App) resolveVMInfo(driverID, name string) (driver.VMInfo, error) {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc != nil {
|
||||
_, vm, err := svc.Resolve(context.Background(), driverID, name)
|
||||
return vm, err
|
||||
}
|
||||
detail, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return driver.VMInfo{}, err
|
||||
}
|
||||
return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: resolveVMDiskPath(detail), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort}, nil
|
||||
}
|
||||
|
||||
func (a *App) GetVMInfo(driverID, name string) (driver.VMInfo, error) {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
return driver.VMInfo{}, errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
_, vm, err := svc.Resolve(context.Background(), driverID, name)
|
||||
return vm, err
|
||||
}
|
||||
|
||||
func (a *App) StartVM(name string) error { return a.StartVMWithDriver("", name) }
|
||||
|
||||
func (a *App) StartVMWithDriver(driverID, name string) error {
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
|
||||
return fmt.Errorf("driver %q is unavailable without the plugin manager", driverID)
|
||||
}
|
||||
return a.startVMLegacy(name)
|
||||
}
|
||||
_, vm, err := svc.Resolve(context.Background(), driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ref := vm.Ref()
|
||||
if vm.State == "suspended" {
|
||||
return a.ResumeVMWithDriver(ref.DriverID, ref.Name)
|
||||
}
|
||||
key := ref.Key()
|
||||
detail := vm
|
||||
a.mu.Lock()
|
||||
a.transitions[key] = "starting"
|
||||
delete(a.pendingChanges, key)
|
||||
a.mu.Unlock()
|
||||
a.emitLifecycleStateChanged()
|
||||
startAt := time.Now()
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
rep := host.Inspect(a.currentDataRoot())
|
||||
a.emitStartSummary(ref.Name, detail, rep, "")
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Starting "+ref.Name+"...")
|
||||
result, err := svc.Start(context.Background(), ref, w, w)
|
||||
if err != nil {
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, key)
|
||||
a.mu.Unlock()
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Start error: "+err.Error())
|
||||
a.emitLifecycleStateChanged()
|
||||
return err
|
||||
}
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
for _, action := range result.PostStart {
|
||||
if action.Kind != "qmp.watch_cold_reboot" {
|
||||
continue
|
||||
}
|
||||
if addr, _ := action.Params["qmp_addr"].(string); addr != "" {
|
||||
a.watchWin10ColdReboot(ref.Name, addr)
|
||||
}
|
||||
}
|
||||
a.startVMMonitor(ref.Name, detail, startAt)
|
||||
}
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) StopVM(name string, force bool) error { return a.StopVMWithDriver("", name, force) }
|
||||
|
||||
func (a *App) StopVMWithDriver(driverID, name string, force bool) error {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
|
||||
return errors.New("driver is unavailable without the plugin manager")
|
||||
}
|
||||
return a.stopVMLegacy(name, force)
|
||||
}
|
||||
_, vm, err := svc.Resolve(context.Background(), driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ref := vm.Ref()
|
||||
key := ref.Key()
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.cancelRebootWatcher(ref.Name)
|
||||
stopVMMonitor(ref.Name)
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.transitions[key] = "stopping"
|
||||
a.mu.Unlock()
|
||||
a.emitLifecycleStateChanged()
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
||||
if err := svc.Stop(context.Background(), ref, force, w, w); err != nil {
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, key)
|
||||
a.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
delete(a.pendingChanges, key)
|
||||
a.mu.Unlock()
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) EjectInstaller(name string) error { return a.EjectInstallerWithDriver("", name) }
|
||||
|
||||
func (a *App) EjectInstallerWithDriver(driverID, name string) error {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
|
||||
return errors.New("driver is unavailable without the plugin manager")
|
||||
}
|
||||
return a.ejectInstallerLegacy(name)
|
||||
}
|
||||
_, err := svc.InvokeAction(context.Background(), driver.VMRef{DriverID: driverID, Name: name}, "eject", nil)
|
||||
if err == nil {
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *App) ReadVMLogsWithDriver(driverID, name string, serial bool) (string, error) {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
return a.readVMLogsLegacy(name, serial)
|
||||
}
|
||||
return svc.ReadLogs(context.Background(), driver.VMRef{DriverID: driverID, Name: name}, serial)
|
||||
}
|
||||
|
||||
func (a *App) RestartVMWithDriver(driverID, name string) error {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
var ref driver.VMRef
|
||||
if svc != nil {
|
||||
_, vm, err := svc.Resolve(context.Background(), driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ref = vm.Ref()
|
||||
} else {
|
||||
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
|
||||
return fmt.Errorf("driver %q is unavailable without the plugin manager", driverID)
|
||||
}
|
||||
ref = driver.NewVMRef(driver.BuiltinReimsMacOSDriverID, name)
|
||||
}
|
||||
if ref.DriverID != driver.BuiltinReimsMacOSDriverID {
|
||||
if err := a.StopVMWithDriver(ref.DriverID, ref.Name, false); err != nil {
|
||||
return err
|
||||
}
|
||||
return a.StartVMWithDriver(ref.DriverID, ref.Name)
|
||||
}
|
||||
_, err := a.restartMacOSVM(ref.Name)
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *App) DeleteVM(name string, keepFiles bool) error {
|
||||
return a.DeleteVMWithDriver("", name, keepFiles)
|
||||
}
|
||||
|
||||
func (a *App) DeleteVMWithDriver(driverID, name string, keepFiles bool) error {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
|
||||
return errors.New("driver is unavailable without the plugin manager")
|
||||
}
|
||||
return a.deleteVMLegacy(name, keepFiles)
|
||||
}
|
||||
_, vm, err := svc.Resolve(context.Background(), driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ref := vm.Ref()
|
||||
key := ref.Key()
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.cancelRebootWatcher(ref.Name)
|
||||
stopVMMonitor(ref.Name)
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
||||
if err := svc.Delete(context.Background(), ref, keepFiles, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
delete(a.pendingChanges, key)
|
||||
delete(a.transitions, key)
|
||||
delete(a.diskPaths, key)
|
||||
delete(a.procSamples, key)
|
||||
gt := a.guestTools
|
||||
a.mu.Unlock()
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
releaseVMTyping(ref.Name)
|
||||
releaseVMThumbnail(ref.Name)
|
||||
}
|
||||
if gt != nil {
|
||||
gt.UnregisterVM(key)
|
||||
}
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/tray"
|
||||
)
|
||||
|
||||
type appSecondDriver struct {
|
||||
id string
|
||||
vms []driver.VMInfo
|
||||
starts, stops, deletes, sets int
|
||||
actions []string
|
||||
actionResults map[string]any
|
||||
}
|
||||
|
||||
func (d *appSecondDriver) ID() string { return d.id }
|
||||
func (d *appSecondDriver) DisplayName() plugin.LocalizedText { return plugin.LocalizedText{EnUS: d.id} }
|
||||
func (d *appSecondDriver) RuntimeKind() string { return "test-runtime" }
|
||||
func (d *appSecondDriver) RuntimeAPIRange() string { return "^1.0.0" }
|
||||
func (d *appSecondDriver) Capabilities() []string { return nil }
|
||||
func (d *appSecondDriver) CreateSchema() *plugin.SettingsSchema { return nil }
|
||||
func (d *appSecondDriver) SettingsSchema() *plugin.SettingsSchema { return nil }
|
||||
func (d *appSecondDriver) List(context.Context) ([]driver.VMInfo, error) { return d.vms, nil }
|
||||
func (d *appSecondDriver) Show(_ context.Context, name string) (driver.VMInfo, error) {
|
||||
for _, vm := range d.vms {
|
||||
if vm.Name == name {
|
||||
return vm, nil
|
||||
}
|
||||
}
|
||||
return driver.VMInfo{}, os.ErrNotExist
|
||||
}
|
||||
func (d *appSecondDriver) ValidateCreate(context.Context, driver.CreateRequest) []driver.ValidationIssue {
|
||||
return nil
|
||||
}
|
||||
func (d *appSecondDriver) Create(context.Context, driver.CreateRequest, io.Writer, io.Writer) error {
|
||||
return nil
|
||||
}
|
||||
func (d *appSecondDriver) ValidateSet(context.Context, driver.SetRequest) []driver.ValidationIssue {
|
||||
return nil
|
||||
}
|
||||
func (d *appSecondDriver) Set(context.Context, driver.SetRequest, io.Writer, io.Writer) error {
|
||||
d.sets++
|
||||
return nil
|
||||
}
|
||||
func (d *appSecondDriver) Start(context.Context, driver.StartRequest) (driver.StartResult, error) {
|
||||
d.starts++
|
||||
return driver.StartResult{}, nil
|
||||
}
|
||||
func (d *appSecondDriver) Stop(context.Context, string, bool, io.Writer, io.Writer) error {
|
||||
d.stops++
|
||||
return nil
|
||||
}
|
||||
func (d *appSecondDriver) Delete(context.Context, string, bool, io.Writer, io.Writer) error {
|
||||
d.deletes++
|
||||
return nil
|
||||
}
|
||||
func (d *appSecondDriver) InvokeAction(_ context.Context, _ string, action string, _ map[string]any) (any, error) {
|
||||
d.actions = append(d.actions, action)
|
||||
return d.actionResults[action], nil
|
||||
}
|
||||
|
||||
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"}}}
|
||||
reg := plugin.NewRegistry(nil)
|
||||
if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: "test.linux", Version: "1.0.0"},
|
||||
Source: plugin.SourceBuiltin, Desired: true, Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
reg.RegisterGuestDriver(sc, driverID, drv)
|
||||
return nil
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.Reconcile(context.Background())
|
||||
router := driver.NewRouter(reg, nil)
|
||||
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}, lifecycleSvc: vmlifecycle.New(reg, router, nil),
|
||||
transitions: map[string]string{}, pendingChanges: map[string][]PendingChange{}}
|
||||
info, err := a.GetVMInfo(driverID, "ubuntu")
|
||||
if err != nil || info.DriverID != driverID {
|
||||
t.Fatalf("GetVMInfo = %+v, %v", info, err)
|
||||
}
|
||||
vms, err := a.listVMsInternal(context.Background())
|
||||
if err != nil || len(vms) != 1 || vms[0].DriverID != driverID {
|
||||
t.Fatalf("list = %+v, %v", vms, err)
|
||||
}
|
||||
if err := a.StartVMWithDriver(driverID, "ubuntu"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.StopVMWithDriver(driverID, "ubuntu", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.startHandedVM(driverID, "ubuntu"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.lifecycleSvc.Set(context.Background(), driver.NewVMRef(driverID, "ubuntu"), map[string]any{"memory": "8G"}, io.Discard, io.Discard); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.RestartVMWithDriver(driverID, "ubuntu"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.DeleteVMWithDriver(driverID, "ubuntu", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if drv.starts != 3 || drv.stops != 2 || drv.deletes != 1 || drv.sets != 1 {
|
||||
t.Fatalf("starts=%d stops=%d deletes=%d", drv.starts, drv.stops, drv.deletes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppRecoveryActionsUseLifecycle(t *testing.T) {
|
||||
const driverID = driver.BuiltinReimsMacOSDriverID
|
||||
drv := &appSecondDriver{id: driverID, vms: []driver.VMInfo{{Name: "ubuntu", DriverID: driverID, Directory: t.TempDir(), State: "running"}}, actionResults: map[string]any{
|
||||
"enter_recovery": map[string]any{"running": true, "scheduled": true},
|
||||
"finish_install": map[string]any{"running": true, "installer_ejected": true, "network_enabled": true, "upgraded_nvme": true, "disk_controller_from": "ahci", "recovery_pending": true},
|
||||
}}
|
||||
reg := plugin.NewRegistry(nil)
|
||||
if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: "test.recovery", Version: "1.0.0"}, Source: plugin.SourceBuiltin, Desired: true, Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
reg.RegisterGuestDriver(sc, driverID, drv)
|
||||
return nil
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.Reconcile(context.Background())
|
||||
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}, lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil), transitions: map[string]string{}, pendingChanges: map[string][]PendingChange{}}
|
||||
if err := a.EnterRecovery("ubuntu"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := a.pendingChanges[vmKey("ubuntu")]; len(got) != 1 || got[0].Field != "recovery" {
|
||||
t.Fatalf("enter pending = %+v", got)
|
||||
}
|
||||
a.pendingChanges = map[string][]PendingChange{}
|
||||
if err := a.FinishInstall("ubuntu"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := a.pendingChanges[vmKey("ubuntu")]; len(got) != 4 {
|
||||
t.Fatalf("finish pending = %+v", got)
|
||||
}
|
||||
if len(drv.actions) != 2 || drv.actions[0] != "enter_recovery" || drv.actions[1] != "finish_install" {
|
||||
t.Fatalf("actions = %v", drv.actions)
|
||||
}
|
||||
}
|
||||
|
||||
// A same-named VM in another driver must not make macOS-native flows or tray
|
||||
// actions ambiguous once the owning driver is known.
|
||||
func TestSameNameVMsAcrossDriversStayIndependent(t *testing.T) {
|
||||
mac := &appSecondDriver{id: driver.BuiltinReimsMacOSDriverID, vms: []driver.VMInfo{{Name: "dup", DriverID: driver.BuiltinReimsMacOSDriverID, Directory: t.TempDir(), State: "running"}}}
|
||||
lin := &appSecondDriver{id: "test.driver.linux", vms: []driver.VMInfo{{Name: "dup", DriverID: "test.driver.linux", Directory: t.TempDir(), State: "running"}}}
|
||||
reg := plugin.NewRegistry(nil)
|
||||
for _, d := range []*appSecondDriver{mac, lin} {
|
||||
d := d
|
||||
if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: "test." + d.id, Version: "1.0.0"}, Source: plugin.SourceBuiltin, Desired: true,
|
||||
Activate: func(_ context.Context, sc *plugin.Scope) error { reg.RegisterGuestDriver(sc, d.id, d); return nil }}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
reg.Reconcile(context.Background())
|
||||
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}, lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil),
|
||||
transitions: map[string]string{}, pendingChanges: map[string][]PendingChange{}}
|
||||
|
||||
if err := a.StopVM("dup", false); err == nil {
|
||||
t.Fatal("bare-name stop must stay ambiguous")
|
||||
}
|
||||
d, err := a.GetVMDetail("dup")
|
||||
if err != nil || d.Directory != mac.vms[0].Directory {
|
||||
t.Fatalf("GetVMDetail = %+v, %v", d, err)
|
||||
}
|
||||
if err := a.RestartVMWithDriver(driver.BuiltinReimsMacOSDriverID, "dup"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if mac.stops != 1 || mac.starts != 1 || lin.stops != 0 || lin.starts != 0 {
|
||||
t.Fatalf("macOS restart: mac stops=%d starts=%d, linux stops=%d starts=%d", mac.stops, mac.starts, lin.stops, lin.starts)
|
||||
}
|
||||
a.trayVMAction(lin.id, "dup", tray.ActRestart)
|
||||
if lin.stops != 1 || lin.starts != 1 || mac.stops != 1 || mac.starts != 1 {
|
||||
t.Fatalf("tray restart: mac stops=%d starts=%d, linux stops=%d starts=%d", mac.stops, mac.starts, lin.stops, lin.starts)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
)
|
||||
|
||||
// requireMacOSEnabled refuses native macOS flows while the user has disabled
|
||||
// macOS VM Support: its VMs then show as driver_unavailable, and the native
|
||||
// pages must not act on them behind the plugin's back. It reads the persisted
|
||||
// choice rather than the live driver so startup work racing plugin activation
|
||||
// is not refused.
|
||||
func (a *App) requireMacOSEnabled() error {
|
||||
a.mu.Lock()
|
||||
mgr, loc := a.pluginMgr, a.cfg.Locale
|
||||
a.mu.Unlock()
|
||||
if mgr == nil || mgr.DesiredFor(guest.ID, true) {
|
||||
return nil
|
||||
}
|
||||
return errors.New(i18n.T(i18n.EffectiveLocale(loc), "err.macos.disabled"))
|
||||
}
|
||||
|
||||
func (a *App) client() (*reims.Client, error) {
|
||||
if err := a.requireMacOSEnabled(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
cfg := a.cfg
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s", i18n.T(cfg.Locale, "err.runtime_not_installed"))
|
||||
}
|
||||
return reims.NewClient(cfg, *active), nil
|
||||
}
|
||||
|
||||
func enrichMacOSVMListStates(vms []driver.VMListItem) {
|
||||
for i := range vms {
|
||||
if vms[i].State == "stopped" && reims.HasSuspendState(vms[i].Dir) {
|
||||
vms[i].State = "suspended"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
)
|
||||
|
||||
func resolveVMDiskPath(d reims.VMDetail) string {
|
||||
raw := strings.TrimSpace(d.Disk)
|
||||
if idx := strings.Index(raw, " ("); idx > 0 {
|
||||
raw = strings.TrimSpace(raw[:idx])
|
||||
}
|
||||
if raw != "" {
|
||||
if filepath.IsAbs(raw) {
|
||||
return raw
|
||||
}
|
||||
if d.Directory != "" {
|
||||
return filepath.Join(d.Directory, raw)
|
||||
}
|
||||
}
|
||||
if d.Directory != "" {
|
||||
return filepath.Join(d.Directory, "disk.qcow2")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// macOSDetailFromVMInfo is the native UI adapter for the built-in macOS driver.
|
||||
func macOSDetailFromVMInfo(vm driver.VMInfo) (reims.VMDetail, error) {
|
||||
raw, err := json.Marshal(vm.DriverData)
|
||||
if err != nil {
|
||||
return reims.VMDetail{}, err
|
||||
}
|
||||
var detail reims.VMDetail
|
||||
if err := json.Unmarshal(raw, &detail); err != nil {
|
||||
return reims.VMDetail{}, err
|
||||
}
|
||||
detail.Name, detail.Directory, detail.State = vm.Name, vm.Directory, vm.State
|
||||
return detail, nil
|
||||
}
|
||||
|
||||
func vmInfoFromMacOSDetail(detail reims.VMDetail) driver.VMInfo {
|
||||
raw, _ := json.Marshal(detail)
|
||||
var data map[string]any
|
||||
_ = json.Unmarshal(raw, &data)
|
||||
return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: resolveVMDiskPath(detail), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort, DriverData: data}
|
||||
}
|
||||
|
||||
func (a *App) getVMDetailLegacy(name string) (reims.VMDetail, error) {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return reims.VMDetail{}, err
|
||||
}
|
||||
d, err := c.Show(context.Background(), name)
|
||||
if err != nil {
|
||||
return d, err
|
||||
}
|
||||
d.RecoveryMode = isRecoveryModeActive(d)
|
||||
a.populateGuestToolsDetail(&d)
|
||||
a.populateGuestLangDetail(&d)
|
||||
populateSuspendDetail(&d)
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (a *App) GetVMDetail(name string) (reims.VMDetail, error) {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
return a.getVMDetailLegacy(name)
|
||||
}
|
||||
// This adapter only serves the built-in macOS driver, so resolve within it:
|
||||
// a same-named VM in another driver must not make the lookup ambiguous.
|
||||
vm, err := a.GetVMInfo(driver.BuiltinReimsMacOSDriverID, name)
|
||||
if err != nil {
|
||||
return reims.VMDetail{}, err
|
||||
}
|
||||
raw, err := json.Marshal(vm.DriverData)
|
||||
if err != nil {
|
||||
return reims.VMDetail{}, err
|
||||
}
|
||||
var d reims.VMDetail
|
||||
if err := json.Unmarshal(raw, &d); err != nil {
|
||||
return reims.VMDetail{}, err
|
||||
}
|
||||
d.Name, d.Directory, d.State = vm.Name, vm.Directory, vm.State
|
||||
d.RecoveryMode = isRecoveryModeActive(d)
|
||||
a.populateGuestToolsDetail(&d)
|
||||
a.populateGuestLangDetail(&d)
|
||||
populateSuspendDetail(&d)
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func populateSuspendDetail(d *reims.VMDetail) {
|
||||
if d != nil && d.State == "stopped" && reims.HasSuspendState(d.Directory) {
|
||||
d.State = "suspended"
|
||||
if info, err := reims.ReadSuspendInfo(d.Directory); err == nil {
|
||||
d.SuspendInfo = info
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
)
|
||||
|
||||
// Disabling macOS VM Support must also stop the native macOS pages from
|
||||
// driving reims-ctl behind the plugin's back.
|
||||
func TestNativeMacOSFlowsRefuseWhilePluginDisabled(t *testing.T) {
|
||||
dataRoot := t.TempDir()
|
||||
mgr, err := plugin.NewManager(plugin.ManagerOptions{DataRoot: dataRoot, HostVersion: "0.0.0"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer mgr.Close()
|
||||
cfg := config.Default()
|
||||
cfg.DataRoot = dataRoot
|
||||
cfg.Locale = i18n.ZhCN
|
||||
a := &App{cfg: cfg, pluginMgr: mgr, pollWake: make(chan struct{}, 1)}
|
||||
cb := builtin.HostCallbacks{GetConfig: func() config.Config { return *cfg }}
|
||||
if err := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr.Registry().Reconcile(context.Background())
|
||||
|
||||
if err := a.requireMacOSEnabled(); err != nil {
|
||||
t.Fatalf("enabled plugin refused: %v", err)
|
||||
}
|
||||
if err := mgr.Disable(context.Background(), guest.ID); err != nil {
|
||||
t.Fatalf("disable: %v", err)
|
||||
}
|
||||
want := i18n.T(i18n.ZhCN, "err.macos.disabled")
|
||||
for name, call := range map[string]func() error{
|
||||
"client": func() error { _, err := a.client(); return err },
|
||||
"prep": func() error { _, err := a.prep("vm"); return err },
|
||||
"createVM": func() error { return a.CreateVM(reims.CreateOpts{Name: "vm"}) },
|
||||
} {
|
||||
if err := call(); err == nil || !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("%s while disabled: err = %v, want %q", name, err, want)
|
||||
}
|
||||
}
|
||||
if err := mgr.Enable(context.Background(), guest.ID, false); err != nil {
|
||||
t.Fatalf("enable: %v", err)
|
||||
}
|
||||
if err := a.requireMacOSEnabled(); err != nil {
|
||||
t.Fatalf("re-enabled plugin refused: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,493 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/macos/macosdriver"
|
||||
"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/qmp"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
const (
|
||||
vmExitWaitTimeout = 12 * time.Second
|
||||
vmMemoryReclaimWaitTimeout = 15 * time.Second
|
||||
)
|
||||
|
||||
func (a *App) cachedVMPID(name string) int {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for _, vm := range a.lastVMs {
|
||||
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
|
||||
return *vm.PID
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (a *App) waitForVMProcessExit(ctx context.Context, pid int, timeout time.Duration) {
|
||||
if pid <= 0 || timeout <= 0 {
|
||||
return
|
||||
}
|
||||
waitCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
_ = host.WaitProcessExit(waitCtx, uint32(pid), qemuImage)
|
||||
}
|
||||
|
||||
func (a *App) waitForCommitMemoryReclaim(ctx context.Context, c *reims.Client, name, logPrefix string) {
|
||||
if ctx.Err() != nil || c == nil {
|
||||
return
|
||||
}
|
||||
detail, err := c.Show(ctx, name)
|
||||
if err != nil || detail.Memory == "" {
|
||||
return
|
||||
}
|
||||
vmstart.WaitForCommitMemory(ctx, detail.Memory, vmMemoryReclaimWaitTimeout, func(availGB, neededGB float64) {
|
||||
a.emitVMLog(name, fmt.Sprintf("%s: waiting for Windows to release VM memory (available %.1f GB, need %.1f GB)...", logPrefix, availGB, neededGB))
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) cancelRebootWatcher(name string) { a.cancelRebootWatcherKey(vmKey(name)) }
|
||||
|
||||
func (a *App) cancelRebootWatcherKey(key string) {
|
||||
a.mu.Lock()
|
||||
if entry, ok := a.rebootWatchers[key]; ok {
|
||||
entry.cancel()
|
||||
delete(a.rebootWatchers, key)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
func (a *App) watchWin10ColdReboot(name, qmpAddr string) {
|
||||
a.cancelRebootWatcher(name)
|
||||
baseCtx := a.ctx
|
||||
if baseCtx == nil {
|
||||
baseCtx = context.Background()
|
||||
}
|
||||
watchCtx, cancel := context.WithCancel(baseCtx)
|
||||
a.mu.Lock()
|
||||
a.nextWatcherID++
|
||||
myID := a.nextWatcherID
|
||||
a.rebootWatchers[vmKey(name)] = rebootWatcherEntry{id: myID, cancel: cancel}
|
||||
a.mu.Unlock()
|
||||
|
||||
go func() {
|
||||
defer func() {
|
||||
cancel()
|
||||
a.mu.Lock()
|
||||
if cur, ok := a.rebootWatchers[vmKey(name)]; ok && cur.id == myID {
|
||||
delete(a.rebootWatchers, vmKey(name))
|
||||
}
|
||||
a.mu.Unlock()
|
||||
}()
|
||||
|
||||
reason, err := qmp.WatchShutdownReason(watchCtx, qmpAddr)
|
||||
if err != nil {
|
||||
if watchCtx.Err() == nil {
|
||||
a.emitVMLog(name, "Win10 WHPX cold-reboot monitor disconnected: "+err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
if reason != "guest-reset" {
|
||||
if reason != "" {
|
||||
a.emitVMLog(name, "Win10 WHPX cold-reboot: VM exited ("+reason+"), not restarting")
|
||||
}
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
tr := a.transitions[vmKey(name)]
|
||||
a.mu.Unlock()
|
||||
if tr == "stopping" || tr == "suspending" {
|
||||
return
|
||||
}
|
||||
|
||||
a.emitVMLog(name, "Win10 WHPX cold-reboot: guest requested reboot (guest-reset), restarting in a fresh Hyper-V partition...")
|
||||
oldPID := a.cachedVMPID(name)
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
a.emitVMLog(name, "Win10 WHPX cold-reboot aborted: "+err.Error())
|
||||
return
|
||||
}
|
||||
// Wait for QEMU to finish exiting cleanly under -no-reboot. Wait on the
|
||||
// OS process handle when known so we don't race against QEMU teardown
|
||||
// even if `reims-ctl list` reports stopped early.
|
||||
deadline := time.Now().Add(vmExitWaitTimeout)
|
||||
waitedPID := 0
|
||||
if oldPID > 0 {
|
||||
a.waitForVMProcessExit(watchCtx, oldPID, time.Until(deadline))
|
||||
waitedPID = oldPID
|
||||
}
|
||||
for time.Now().Before(deadline) {
|
||||
if watchCtx.Err() != nil {
|
||||
return
|
||||
}
|
||||
vms, err := c.List(watchCtx)
|
||||
if err == nil {
|
||||
stopped := false
|
||||
for _, vm := range vms {
|
||||
if vm.Name != name {
|
||||
continue
|
||||
}
|
||||
if vm.PID != nil && *vm.PID > 0 && oldPID == 0 {
|
||||
oldPID = *vm.PID
|
||||
}
|
||||
if vm.State == "stopped" {
|
||||
stopped = true
|
||||
}
|
||||
break
|
||||
}
|
||||
if stopped {
|
||||
break
|
||||
}
|
||||
if oldPID > 0 && oldPID != waitedPID {
|
||||
a.waitForVMProcessExit(watchCtx, oldPID, time.Until(deadline))
|
||||
waitedPID = oldPID
|
||||
continue
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-watchCtx.Done():
|
||||
return
|
||||
case <-time.After(300 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
if oldPID > 0 && oldPID != waitedPID {
|
||||
a.waitForVMProcessExit(watchCtx, oldPID, time.Until(deadline))
|
||||
}
|
||||
if watchCtx.Err() != nil {
|
||||
return
|
||||
}
|
||||
a.waitForCommitMemoryReclaim(watchCtx, c, name, "Win10 WHPX cold-reboot")
|
||||
if watchCtx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if err := a.StartVMWithDriver(driver.BuiltinReimsMacOSDriverID, name); err != nil {
|
||||
a.emitVMLog(name, "Win10 WHPX cold-reboot start failed: "+err.Error())
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// stripLegacyManagedExtraArgs removes reims-go internally managed QEMU arg
|
||||
// fragments (reimstools, reimshelp, and legacy managed Win10 QMP targets)
|
||||
// before ledger reconciliation so pre-plugin VMs and out-of-band helpers never
|
||||
// produce duplicate QEMU device IDs on upgrade.
|
||||
func stripLegacyManagedExtraArgs(extraArgs string) string {
|
||||
s := reims.StripGuestToolsArgs(extraArgs)
|
||||
s = reims.StripOfflineHelperArgs(s)
|
||||
s = qmp.StripLegacyWin10RebootArgs(s)
|
||||
s = reims.StripIncomingDeferArgs(s)
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
func (a *App) startVMLegacy(name string) error {
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
prep, err := a.prep(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c := prep.Client
|
||||
a.mu.Lock()
|
||||
root := a.cfg.DataRoot
|
||||
tmpDir := a.cfg.TempDir()
|
||||
a.mu.Unlock()
|
||||
rep := host.Inspect(root)
|
||||
if err := prep.CheckWHPX(rep); err != nil {
|
||||
a.emitVMLog(name, "Start refused: "+err.Error())
|
||||
return err
|
||||
}
|
||||
curDetail, _ := c.Show(context.Background(), name)
|
||||
if err := prep.CheckMemory(curDetail.Memory, rep); err != nil {
|
||||
a.emitVMLog(name, "Start refused: "+err.Error())
|
||||
return err
|
||||
}
|
||||
a.cancelRebootWatcher(name)
|
||||
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
var qmpAddr string
|
||||
if mgr != nil {
|
||||
// Unified plugin-kernel start pipeline (§4.4): collect all vm.beforeStart
|
||||
// intents (builtin + L1 rule hooks + L3 code hooks) and write merged
|
||||
// extra-args via AT MOST ONE `reims-ctl set --extra-args` call.
|
||||
rtCaps := prep.Runtime.Manifest.EffectiveCapabilities()
|
||||
intents, blockErr := mgr.Registry().Hooks().DispatchBeforeStart(context.Background(), plugin.BeforeStartPayload{
|
||||
VMName: name,
|
||||
VMDir: curDetail.Directory,
|
||||
DriverID: builtin.IDDriverReimsMacOS,
|
||||
ExtraArgs: curDetail.ExtraArgs,
|
||||
HasInstaller: curDetail.HasInstaller,
|
||||
InstallerPath: curDetail.InstallerPath,
|
||||
RuntimeKind: prep.Runtime.Manifest.EffectiveKind(),
|
||||
RuntimeCaps: rtCaps,
|
||||
HostFacts: buildHostFacts(rep, rtCaps),
|
||||
VMCaps: macosdriver.ReimsMacOSCapabilities,
|
||||
State: curDetail.State,
|
||||
})
|
||||
if blockErr != nil {
|
||||
a.emitVMLog(name, "Start blocked: "+blockErr.Error())
|
||||
return blockErr
|
||||
}
|
||||
ledger, ledgerErr := plugin.LoadArgLedger(curDetail.Directory)
|
||||
if ledgerErr != nil {
|
||||
a.emitVMLog(name, "Warning: could not read arg ledger: "+ledgerErr.Error())
|
||||
ledger = &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{}}
|
||||
}
|
||||
// Fragments written before the builtins were merged into the core
|
||||
// belong to the core now; carry them instead of re-adding them.
|
||||
guest.MigrateLedger(ledger)
|
||||
// Adopt/strip pre-ledger or out-of-band managed fragments before reconciling
|
||||
// so upgrading existing VMs never duplicates QEMU device IDs (B1).
|
||||
// BeforeStartPayload above already saw the original curDetail.ExtraArgs.
|
||||
baseExtraArgs := stripLegacyManagedExtraArgs(curDetail.ExtraArgs)
|
||||
reconciled := plugin.ReconcileStartIntents(baseExtraArgs, ledger, mgr.Registry().ActivePluginIDs(), intents)
|
||||
reconciled.Changed = strings.TrimSpace(curDetail.ExtraArgs) != reconciled.ExtraArgs
|
||||
for _, warn := range reconciled.Warnings {
|
||||
a.emitVMLog(name, "[plugin] "+warn)
|
||||
}
|
||||
if len(reconciled.Env) > 0 {
|
||||
c.Env = append(c.Env, reconciled.Env...)
|
||||
}
|
||||
if reconciled.Changed {
|
||||
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &reconciled.ExtraArgs}, io.Discard, io.Discard); err != nil {
|
||||
a.emitVMLog(name, "Warning: could not apply reconciled start extra-args: "+err.Error())
|
||||
} else {
|
||||
curDetail.ExtraArgs = reconciled.ExtraArgs
|
||||
_ = plugin.SaveArgLedger(curDetail.Directory, ledger)
|
||||
}
|
||||
} else {
|
||||
_ = plugin.SaveArgLedger(curDetail.Directory, ledger)
|
||||
}
|
||||
for _, act := range reconciled.PostStart {
|
||||
if act.Kind == "qmp.watch_cold_reboot" {
|
||||
if addr, ok := act.Params["qmp_addr"].(string); ok && addr != "" {
|
||||
qmpAddr = addr
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
a.syncGuestTools(c, name, &curDetail)
|
||||
if prep.Runtime.Manifest.HasCapability("win32-unicode-input") {
|
||||
if env := a.inputBridgeEnv(name, curDetail.Directory); len(env) > 0 {
|
||||
c.Env = append(c.Env, env...)
|
||||
}
|
||||
}
|
||||
prep.Prepare(context.Background(), name, rep, &curDetail)
|
||||
if rep.NeedsColdRebootWorkaround {
|
||||
sockPath := qmp.RebootSocketPath(curDetail.Directory, tmpDir, name)
|
||||
_ = os.MkdirAll(filepath.Dir(sockPath), 0o755)
|
||||
_ = os.Remove(sockPath)
|
||||
merged := qmp.MergeWin10RebootUnixArgs(curDetail.ExtraArgs, sockPath)
|
||||
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err != nil {
|
||||
a.emitVMLog(name, "Win10 cold-reboot extra-args setup skipped: "+err.Error())
|
||||
} else {
|
||||
qmpAddr = "unix:" + sockPath
|
||||
curDetail.ExtraArgs = merged
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if prep.Runtime.Manifest.HasCapability("display-fixed-mode") &&
|
||||
host.ShouldUseFixedGuestMode(curDetail.Borderless, curDetail.Resolution, rep.PrimaryDisplay) {
|
||||
c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
|
||||
}
|
||||
if prep.Runtime.Manifest.HasCapability("client-window-close") {
|
||||
c.Env = append(c.Env, vmstart.CloseRequestEnv(name)...)
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
a.transitions[vmKey(name)] = "starting"
|
||||
delete(a.pendingChanges, vmKey(name))
|
||||
a.mu.Unlock()
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
|
||||
startAt := time.Now()
|
||||
a.emitStartSummary(name, vmInfoFromMacOSDetail(curDetail), rep, qmpAddr)
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
a.emitVMLog(name, "Starting "+name+"...")
|
||||
if err := c.StartWithCompat(context.Background(), name, w, w, func(msg string) {
|
||||
a.emitVMLog(name, msg)
|
||||
}); err != nil {
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, vmKey(name))
|
||||
a.mu.Unlock()
|
||||
a.emitVMLog(name, "Start error: "+err.Error())
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return err
|
||||
}
|
||||
if qmpAddr != "" && mgr == nil {
|
||||
a.watchWin10ColdReboot(name, qmpAddr)
|
||||
}
|
||||
if mgr != nil {
|
||||
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStart, plugin.VMEventPayload{
|
||||
VMName: name,
|
||||
VMDir: curDetail.Directory,
|
||||
DriverID: builtin.IDDriverReimsMacOS,
|
||||
QMPAddr: qmpAddr,
|
||||
})
|
||||
}
|
||||
a.startVMMonitor(name, vmInfoFromMacOSDetail(curDetail), startAt)
|
||||
a.wakePoll()
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) stopVMLegacy(name string, force bool) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
a.cancelRebootWatcher(name)
|
||||
stopVMMonitor(name)
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.transitions[vmKey(name)] = "stopping"
|
||||
a.mu.Unlock()
|
||||
if mgr != nil {
|
||||
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMBeforeStop, plugin.VMEventPayload{
|
||||
VMName: name,
|
||||
DriverID: builtin.IDDriverReimsMacOS,
|
||||
})
|
||||
}
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
a.emitVMLog(name, fmt.Sprintf("Stopping %s (force=%v)...", name, force))
|
||||
if force {
|
||||
err = c.StopForce(context.Background(), name, w, w)
|
||||
} else {
|
||||
err = c.Stop(context.Background(), name, w, w)
|
||||
}
|
||||
if err != nil {
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, vmKey(name))
|
||||
a.mu.Unlock()
|
||||
a.emitVMLog(name, "Stop error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
delete(a.pendingChanges, vmKey(name))
|
||||
a.mu.Unlock()
|
||||
if mgr != nil {
|
||||
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStop, plugin.VMEventPayload{
|
||||
VMName: name,
|
||||
DriverID: builtin.IDDriverReimsMacOS,
|
||||
})
|
||||
}
|
||||
a.wakePoll()
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) RestartVM(name string) error { return a.RestartVMWithDriver("", name) }
|
||||
|
||||
// restartMacOSVM restarts a built-in macOS VM, waiting for the old QEMU
|
||||
// process and its committed memory to go away before starting again.
|
||||
func (a *App) restartMacOSVM(name string) (stopped bool, err error) {
|
||||
oldPID := a.cachedVMPID(name)
|
||||
if err := a.StopVMWithDriver(driver.BuiltinReimsMacOSDriverID, name, false); err != nil {
|
||||
return false, err
|
||||
}
|
||||
ctx := a.baseCtx()
|
||||
a.waitForVMProcessExit(ctx, oldPID, vmExitWaitTimeout)
|
||||
if c, err := a.client(); err == nil {
|
||||
a.waitForCommitMemoryReclaim(ctx, c, name, "Restart")
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return true, err
|
||||
}
|
||||
return true, a.StartVMWithDriver(driver.BuiltinReimsMacOSDriverID, name)
|
||||
}
|
||||
|
||||
func (a *App) ejectInstallerLegacy(name string) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
a.emitVMLog(name, "Ejecting installer from "+name+"...")
|
||||
if err := c.Eject(context.Background(), name, w, w); err != nil {
|
||||
a.emitVMLog(name, "Eject error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
a.emitVMLog(name, "Installer ejected.")
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) deleteVMLegacy(name string, keepFiles bool) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
a.cancelRebootWatcher(name)
|
||||
stopVMMonitor(name)
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
a.emitVMLog(name, fmt.Sprintf("Deleting VM %s (keepFiles=%v)...", name, keepFiles))
|
||||
if err := c.Delete(context.Background(), name, keepFiles, w, w); err != nil {
|
||||
a.emitVMLog(name, "Delete error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
delete(a.pendingChanges, vmKey(name))
|
||||
delete(a.transitions, vmKey(name))
|
||||
delete(a.diskPaths, vmKey(name))
|
||||
delete(a.procSamples, vmKey(name))
|
||||
gt := a.guestTools
|
||||
a.mu.Unlock()
|
||||
releaseVMTyping(name)
|
||||
releaseVMThumbnail(name)
|
||||
if gt != nil {
|
||||
gt.UnregisterVM(name)
|
||||
}
|
||||
a.mu.Lock()
|
||||
delMgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
if delMgr != nil {
|
||||
delMgr.Registry().Hooks().DispatchObserve(plugin.EventVMDeleted, plugin.VMEventPayload{
|
||||
VMName: name,
|
||||
DriverID: builtin.IDDriverReimsMacOS,
|
||||
})
|
||||
}
|
||||
a.wakePoll()
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return nil
|
||||
}
|
||||
|
||||
// OpenVMFolder shows the VM's directory in File Explorer.
|
||||
func (a *App) OpenVMFolder(name string) error {
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.Directory == "" {
|
||||
return fmt.Errorf("VM %s has no directory", name)
|
||||
}
|
||||
return host.OpenFolder(d.Directory)
|
||||
}
|
||||
|
||||
func (a *App) ReadVMLogs(name string, serial bool) (string, error) {
|
||||
return a.ReadVMLogsWithDriver("", name, serial)
|
||||
}
|
||||
|
||||
func (a *App) readVMLogsLegacy(name string, serial bool) (string, error) {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return c.ReadLogs(context.Background(), name, serial)
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"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/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// ToggleBorderless switches borderless fullscreen startup through the native macOS settings flow.
|
||||
func (a *App) ToggleBorderless(name string, enabled bool) error {
|
||||
v := enabled
|
||||
return a.ApplyVMSettings(reims.SetOpts{Name: name, Borderless: &v})
|
||||
}
|
||||
|
||||
func (a *App) ValidateCreate(opts reims.CreateOpts) []reims.ValidationIssue {
|
||||
a.mu.Lock()
|
||||
root := a.cfg.DataRoot
|
||||
loc := i18n.EffectiveLocale(a.cfg.Locale)
|
||||
a.mu.Unlock()
|
||||
issues := reims.ValidateCreateLocalized(opts, host.Inspect(root), loc)
|
||||
// reims-ctl refuses a name already registered; say so before the create runs.
|
||||
if vms, err := a.listVMsInternal(context.Background()); err == nil {
|
||||
for _, vm := range vms {
|
||||
if strings.EqualFold(vm.Name, strings.TrimSpace(opts.Name)) {
|
||||
issues = append(issues, reims.ValidationIssue{Field: "name", Code: "name_taken", Message: i18n.T(loc, "validate.name_taken", vm.Name)})
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return issues
|
||||
}
|
||||
|
||||
func (a *App) PreviewCreate(opts reims.CreateOpts) (string, error) {
|
||||
return reims.PreviewCreateCommand(opts)
|
||||
}
|
||||
|
||||
func (a *App) CreateVM(opts reims.CreateOpts) error {
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
return a.createVMFlow(opts)
|
||||
}
|
||||
|
||||
func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) {
|
||||
cur, err := a.GetVMDetail(opts.Name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
root := a.cfg.DataRoot
|
||||
loc := a.cfg.Locale
|
||||
a.mu.Unlock()
|
||||
return reims.ValidateSetLocalized(opts, cur, host.Inspect(root), loc), nil
|
||||
}
|
||||
|
||||
func (a *App) ApplyVMSettings(opts reims.SetOpts) error {
|
||||
cur, err := a.GetVMDetail(opts.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
root := a.cfg.DataRoot
|
||||
loc := a.cfg.Locale
|
||||
a.mu.Unlock()
|
||||
if issues := reims.ValidateSetLocalized(opts, cur, host.Inspect(root), loc); len(issues) > 0 {
|
||||
return fmt.Errorf("%s", issues[0].Message)
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(opts.Name, line) })
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
guestLangChanged := strings.TrimSpace(opts.GuestLang) != "" && strings.TrimSpace(opts.GuestLang) != cur.GuestLang
|
||||
if svc != nil {
|
||||
raw, _ := json.Marshal(opts)
|
||||
var changes map[string]any
|
||||
_ = json.Unmarshal(raw, &changes)
|
||||
if err := svc.Set(context.Background(), driver.NewVMRef("", opts.Name), changes, w, w); err != nil {
|
||||
a.emitVMLog(opts.Name, "Set error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, release, err := startprep.LockMutableVM(a.baseCtx(), c, opts.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
if reims.HasCtlSetChanges(opts) {
|
||||
if err := c.Set(context.Background(), opts, w, w); err != nil {
|
||||
a.emitVMLog(opts.Name, "Set error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
}
|
||||
if guestLangChanged {
|
||||
prep, err := a.prep(opts.Name)
|
||||
if err == nil {
|
||||
err = prep.ApplyGuestLang(context.Background(), cur.Directory, opts.GuestLang, cur.State == "running")
|
||||
}
|
||||
if err != nil {
|
||||
a.emitVMLog(opts.Name, "Guest language error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
} else if cur.State != "running" && opts.Graphics != "" && opts.Graphics != cur.Graphics {
|
||||
if prep, err := a.prep(opts.Name); err == nil {
|
||||
prep.ReplayGuestLang(context.Background(), cur.Directory)
|
||||
}
|
||||
}
|
||||
}
|
||||
if cur.State == "running" {
|
||||
var diffs []PendingChange
|
||||
if opts.CPUs > 0 && opts.CPUs != cur.CPUs {
|
||||
diffs = append(diffs, PendingChange{Field: "cpus", From: fmt.Sprintf("%d", cur.CPUs), To: fmt.Sprintf("%d", opts.CPUs)})
|
||||
}
|
||||
if opts.Memory != "" && !strings.EqualFold(opts.Memory, cur.Memory) {
|
||||
diffs = append(diffs, PendingChange{Field: "memory", From: cur.Memory, To: opts.Memory})
|
||||
}
|
||||
if opts.Resolution != "" && opts.Resolution != cur.Resolution {
|
||||
diffs = append(diffs, PendingChange{Field: "resolution", From: cur.Resolution, To: opts.Resolution})
|
||||
}
|
||||
if opts.GPU != "" && opts.GPU != cur.GPU {
|
||||
diffs = append(diffs, PendingChange{Field: "gpu", From: cur.GPU, To: opts.GPU})
|
||||
}
|
||||
if opts.Displays > 0 && opts.Displays != cur.Displays {
|
||||
diffs = append(diffs, PendingChange{Field: "displays", From: fmt.Sprintf("%d", cur.Displays), To: fmt.Sprintf("%d", opts.Displays)})
|
||||
}
|
||||
if opts.Borderless != nil && *opts.Borderless != cur.Borderless {
|
||||
diffs = append(diffs, PendingChange{Field: "borderless", From: fmt.Sprintf("%v", cur.Borderless), To: fmt.Sprintf("%v", *opts.Borderless)})
|
||||
}
|
||||
if opts.Audio != nil && *opts.Audio != cur.Audio {
|
||||
diffs = append(diffs, PendingChange{Field: "audio", From: fmt.Sprintf("%v", cur.Audio), To: fmt.Sprintf("%v", *opts.Audio)})
|
||||
}
|
||||
if opts.AudioBackend != "" && opts.AudioBackend != cur.AudioBackend {
|
||||
from := cur.AudioBackend
|
||||
if from == "" {
|
||||
from = "auto"
|
||||
}
|
||||
diffs = append(diffs, PendingChange{Field: "audio_backend", From: from, To: opts.AudioBackend})
|
||||
}
|
||||
if guestLangChanged {
|
||||
from := cur.GuestLang
|
||||
if from == "" {
|
||||
from = "en-US:0"
|
||||
}
|
||||
diffs = append(diffs, PendingChange{Field: "guest_lang", From: from, To: strings.TrimSpace(opts.GuestLang)})
|
||||
}
|
||||
if len(diffs) > 0 {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[vmKey(opts.Name)] = append(a.pendingChanges[vmKey(opts.Name)], diffs...)
|
||||
a.mu.Unlock()
|
||||
}
|
||||
}
|
||||
a.emitVMLog(opts.Name, "Updated VM settings for "+opts.Name)
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"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/macos/reims"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// ToggleVMFullscreen switches the running VM's display between full screen and windowed mode.
|
||||
func (a *App) toggleVMFullscreenLegacy(name string) (bool, error) {
|
||||
a.mu.Lock()
|
||||
preference := a.cfg.Locale
|
||||
a.mu.Unlock()
|
||||
loc := i18n.EffectiveLocale(preference)
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", i18n.Vars{"name": name}, err)
|
||||
}
|
||||
fullscreen, err := toggleVMFullscreen(context.Background(), name, loc, c, host.ToggleProcessWindowFullscreen)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
a.emitVMLog(name, fmt.Sprintf("VM window full screen: %t", fullscreen))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return fullscreen, nil
|
||||
}
|
||||
|
||||
type fullscreenVMClient interface {
|
||||
Show(context.Context, string) (reims.VMDetail, error)
|
||||
List(context.Context) ([]driver.VMListItem, error)
|
||||
}
|
||||
|
||||
func findRunningVMPID(vms []driver.VMListItem, name string) (uint32, bool) {
|
||||
for _, vm := range vms {
|
||||
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
|
||||
return uint32(*vm.PID), true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func toggleVMFullscreen(ctx context.Context, name string, loc i18n.Locale, c fullscreenVMClient, toggleWindow func(uint32) (bool, error)) (bool, error) {
|
||||
vars := i18n.Vars{"name": name}
|
||||
beforeVMs, err := c.List(ctx)
|
||||
if err != nil {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
|
||||
}
|
||||
pidBefore, ok := findRunningVMPID(beforeVMs, name)
|
||||
if !ok {
|
||||
return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil)
|
||||
}
|
||||
detail, err := c.Show(ctx, name)
|
||||
if err != nil {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
|
||||
}
|
||||
if detail.State != "running" {
|
||||
return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil)
|
||||
}
|
||||
if detail.Graphics == "vmware-svga" {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_VMWARE_SVGA", "err.fullscreen_vmware_svga", vars, nil)
|
||||
}
|
||||
afterVMs, err := c.List(ctx)
|
||||
if err != nil {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
|
||||
}
|
||||
pidAfter, ok := findRunningVMPID(afterVMs, name)
|
||||
if !ok || pidAfter != pidBefore {
|
||||
return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil)
|
||||
}
|
||||
fullscreen, err := toggleWindow(pidAfter)
|
||||
if errors.Is(err, host.ErrDisplayWindowNotFound) {
|
||||
return false, i18n.NewCodedError(loc, "E_VM_WINDOW_NOT_FOUND", "err.vm_window_not_found", vars, err)
|
||||
}
|
||||
if err != nil {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
|
||||
}
|
||||
return fullscreen, nil
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/opencore"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
"github.com/Nwflower/reims-go/internal/macos/opencore"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||
)
|
||||
|
||||
// populateGuestLangDetail fills VMDetail.GuestLang from the VM's persisted
|
||||
@@ -26,9 +26,12 @@ func (a *App) populateGuestLangDetail(d *reims.VMDetail) {
|
||||
|
||||
// prep returns the shared start/OpenCore helpers (internal/vmstart) for one VM,
|
||||
// logging to that VM's log panel.
|
||||
func (a *App) prep(name string) (*vmstart.Prep, error) {
|
||||
func (a *App) prep(name string) (*startprep.Prep, error) {
|
||||
if err := a.requireMacOSEnabled(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
cfg := *a.cfg
|
||||
a.mu.Unlock()
|
||||
return vmstart.New(cfg, func(line string) { a.emitLog(name, line) })
|
||||
return startprep.New(cfg, func(line string) { a.emitVMLog(name, line) })
|
||||
}
|
||||
@@ -14,12 +14,12 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/datamigrate"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
@@ -31,42 +31,45 @@ import (
|
||||
// PluginUIContributions aggregates all active declarative plugin UI contributions
|
||||
// for the frontend in a single round-trip (§4.2, §10).
|
||||
type PluginUIContributions struct {
|
||||
SafeMode bool `json:"safe_mode"`
|
||||
CrashDetected bool `json:"crash_detected"`
|
||||
Menus []plugin.MenuContribution `json:"menus,omitempty"`
|
||||
VMCards []plugin.VMCardContribution `json:"vm_cards,omitempty"`
|
||||
SettingsPages []plugin.SettingsPageContribution `json:"settings_pages,omitempty"`
|
||||
StatusItems []plugin.StatusItemContribution `json:"status_items,omitempty"`
|
||||
Panels []plugin.PanelContribution `json:"panels,omitempty"`
|
||||
SafeMode bool `json:"safe_mode"`
|
||||
CrashDetected bool `json:"crash_detected"`
|
||||
Menus []plugin.MenuContribution `json:"menus,omitempty"`
|
||||
VMCards []plugin.VMCardContribution `json:"vm_cards,omitempty"`
|
||||
SettingsPages []plugin.SettingsPageContribution `json:"settings_pages,omitempty"`
|
||||
StatusItems []plugin.StatusItemContribution `json:"status_items,omitempty"`
|
||||
Panels []plugin.PanelContribution `json:"panels,omitempty"`
|
||||
VMTemplates []plugin.VMTemplateContribution `json:"vm_templates,omitempty"`
|
||||
Themes []plugin.ThemeContribution `json:"themes,omitempty"`
|
||||
Locales []plugin.ResolvedLocalePack `json:"locales,omitempty"`
|
||||
RuntimeSources []plugin.RuntimeSourceContribution `json:"runtime_sources,omitempty"`
|
||||
RuntimeKinds []rt.KindSpec `json:"runtime_kinds,omitempty"`
|
||||
Drivers []driver.DriverSummary `json:"drivers,omitempty"`
|
||||
AssetToken string `json:"asset_token,omitempty"`
|
||||
RuntimeKinds []rt.KindSpec `json:"runtime_kinds,omitempty"`
|
||||
Drivers []driver.DriverSummary `json:"drivers,omitempty"`
|
||||
AssetToken string `json:"asset_token,omitempty"`
|
||||
}
|
||||
|
||||
func (a *App) initPlugins() {
|
||||
// Plugins keep their state in the data folder. Before setup there is no
|
||||
// chosen folder, and a read-only folder must not be written; the app runs
|
||||
// without a plugin manager then (see startup).
|
||||
if !a.dataRootUsable() {
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
dataRoot := a.cfg.DataRoot
|
||||
safeMode := a.launch.SafeMode
|
||||
a.mu.Unlock()
|
||||
|
||||
// Bring the data folder to this build's layout before anything reads it.
|
||||
if res, err := datamigrate.Run(dataRoot, version.Version); err != nil {
|
||||
a.emitLog("app", "Data migration failed: "+err.Error())
|
||||
} else if res.Newer {
|
||||
a.emitLog("app", fmt.Sprintf("Data folder uses layout v%d from a newer Reims-Go (this build knows v%d); leaving it unchanged", res.From, datamigrate.CurrentVersion))
|
||||
} else if len(res.Applied) > 0 {
|
||||
a.emitLog("app", fmt.Sprintf("Data folder upgraded from layout v%d to v%d (%s)", res.From, res.To, strings.Join(res.Applied, ", ")))
|
||||
// Idempotent fallback for embedders that construct a Manager directly;
|
||||
// normal startup already ran this as data layout v2 in dataroot.Open.
|
||||
if err := guest.MigrateFiles(dataRoot); err != nil {
|
||||
a.emitLog("plugin", "Could not migrate macOS guest state: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
mgr, err := plugin.NewManager(plugin.ManagerOptions{
|
||||
DataRoot: dataRoot,
|
||||
HostVersion: version.Version,
|
||||
SafeMode: safeMode,
|
||||
RedactFn: reims.RedactText,
|
||||
RedactFn: host.RedactText,
|
||||
LocaleFn: a.locale,
|
||||
Logger: func(source, line string) {
|
||||
a.emitLog(source, line)
|
||||
@@ -86,30 +89,14 @@ func (a *App) initPlugins() {
|
||||
}
|
||||
|
||||
kindReg := rt.NewKindRegistry()
|
||||
drvRouter := driver.NewRouter(mgr.Registry(), func() string {
|
||||
drvRouter := driver.NewRouterWithDataRoot(mgr.Registry(), func() string {
|
||||
a.mu.Lock()
|
||||
dir := filepath.Join(a.cfg.XDGDataDir(), "reims-ctl", "vms")
|
||||
a.mu.Unlock()
|
||||
return dir
|
||||
defer a.mu.Unlock()
|
||||
return a.cfg.DataRoot
|
||||
})
|
||||
|
||||
mgr.Registry().SetInUseChecker(func(pluginID string) (bool, string, error) {
|
||||
// Must not call Registry.Info/List here: both invoke this checker,
|
||||
// which recursed until the goroutine stack overflowed at startup.
|
||||
// Check all guest driver IDs declared by this plugin (even when disabled) plus pluginID itself.
|
||||
seen := map[string]bool{}
|
||||
candidates := append([]string{pluginID}, mgr.Registry().DeclaredDriverIDs(pluginID)...)
|
||||
for _, did := range candidates {
|
||||
if did == "" || seen[did] {
|
||||
continue
|
||||
}
|
||||
seen[did] = true
|
||||
if inUse, reason, err := drvRouter.CheckDriverInUse(context.Background(), did); err != nil || inUse {
|
||||
return inUse, reason, err
|
||||
}
|
||||
}
|
||||
return false, "", nil
|
||||
})
|
||||
mgr.Registry().SetInUseChecker(drvRouter.PluginInUseChecker())
|
||||
mgr.Registry().SetBusyChecker(drvRouter.PluginBusyChecker())
|
||||
|
||||
mgr.Broker().SetNotifier(func(pluginID, title, body string) {
|
||||
a.emitLog("plugin:"+pluginID, title+": "+body)
|
||||
@@ -161,6 +148,7 @@ func (a *App) initPlugins() {
|
||||
GuestToolsImg: func(vmName string) string {
|
||||
return a.guestToolsImagePath(vmName)
|
||||
},
|
||||
BuildGuestToolsImage: a.buildGuestToolsImage,
|
||||
OnInstallGuidesChanged: func() {
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
@@ -178,8 +166,8 @@ func (a *App) initPlugins() {
|
||||
if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
||||
a.emitLog("plugin", "Builtin extension register error: "+err.Error())
|
||||
}
|
||||
if err := builtin.MigrateRetired(mgr); err != nil {
|
||||
a.emitLog("plugin", "Could not migrate merged core plugin state: "+err.Error())
|
||||
if err := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
||||
a.emitLog("plugin", "macOS guest plugin register error: "+err.Error())
|
||||
}
|
||||
if err := mgr.LoadExternal(); err != nil {
|
||||
a.emitLog("plugin", "External plugin load warning: "+err.Error())
|
||||
@@ -199,6 +187,7 @@ func (a *App) initPlugins() {
|
||||
a.mu.Lock()
|
||||
a.pluginMgr = mgr
|
||||
a.driverRouter = drvRouter
|
||||
a.lifecycleSvc = vmlifecycle.New(mgr.Registry(), drvRouter, a.startHookPayload)
|
||||
a.runtimeKinds = kindReg
|
||||
a.mu.Unlock()
|
||||
|
||||
@@ -214,6 +203,8 @@ func (a *App) shutdownPlugins() {
|
||||
mgr := a.pluginMgr
|
||||
a.pluginMgr = nil
|
||||
a.pluginMarket = nil
|
||||
a.lifecycleSvc = nil
|
||||
a.driverRouter = nil
|
||||
a.mu.Unlock()
|
||||
i18n.SetPluginCatalogs(nil)
|
||||
if mgr != nil {
|
||||
@@ -371,8 +362,13 @@ func (a *App) syncInputFilters() {
|
||||
if len(vmNames) == 0 {
|
||||
continue
|
||||
}
|
||||
for _, vmName := range vmNames {
|
||||
vals := mgr.GetSettings(flt.PluginID, vmName, false)
|
||||
for _, vmKey := range vmNames {
|
||||
ref, ok := driver.ParseVMRef(vmKey)
|
||||
if !ok {
|
||||
ref = driver.NewVMRef("", vmKey)
|
||||
}
|
||||
vmName := ref.Name
|
||||
vals := mgr.GetSettings(flt.PluginID, vmKey, false)
|
||||
vert := true
|
||||
if flt.VertKey != "" {
|
||||
if v, ok := vals[flt.VertKey].(bool); ok {
|
||||
@@ -394,7 +390,7 @@ func (a *App) syncInputFilters() {
|
||||
axis = ""
|
||||
}
|
||||
rules = append(rules, host.InputFilterRule{
|
||||
ID: flt.ID + ":" + vmName,
|
||||
ID: flt.ID + ":" + ref.Key(),
|
||||
PluginID: flt.PluginID,
|
||||
Event: flt.Event,
|
||||
Axis: axis,
|
||||
@@ -422,9 +418,13 @@ func (a *App) syncClipboardPolicies() {
|
||||
}
|
||||
globalVals := mgr.GetSettings(builtin.IDClipboard, "", false)
|
||||
gt.SetGlobalClipboardPolicy(clipboardPolicyFromMap(globalVals))
|
||||
for vmName, vmVals := range mgr.SavedVMSettingsForPlugin(builtin.IDClipboard) {
|
||||
for vmKey, vmVals := range mgr.SavedVMSettingsForPlugin(builtin.IDClipboard) {
|
||||
ref, ok := driver.ParseVMRef(vmKey)
|
||||
if !ok {
|
||||
ref = driver.NewVMRef("", vmKey)
|
||||
}
|
||||
pol := clipboardPolicyFromMap(vmVals)
|
||||
gt.SetVMClipboardPolicy(vmName, &pol)
|
||||
gt.SetVMClipboardPolicy(ref.Key(), &pol)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -441,7 +441,22 @@ func (a *App) onPluginSettingsChanged(pluginID, vmName string) {
|
||||
if vmName == "" {
|
||||
gt.SetGlobalClipboardPolicy(pol)
|
||||
} else {
|
||||
gt.SetVMClipboardPolicy(vmName, &pol)
|
||||
ref, ok := driver.ParseVMRef(vmName)
|
||||
if !ok {
|
||||
ref = driver.NewVMRef("", vmName)
|
||||
}
|
||||
gt.SetVMClipboardPolicy(ref.Key(), &pol)
|
||||
}
|
||||
}
|
||||
}
|
||||
if pluginID == guest.ID && vmName == "" {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
if mgr != nil {
|
||||
wantGuide := guest.SettingOn(mgr.GetSettings(guest.ID, "", false), guest.SettingInstallGuide)
|
||||
if wantGuide != a.installGuideEnabled() {
|
||||
a.reloadPlugins()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -519,7 +534,7 @@ func (a *App) collectPluginDiagnostics(ctx context.Context, vmName string) []plu
|
||||
if mgr == nil {
|
||||
return nil
|
||||
}
|
||||
return mgr.Registry().CollectDiagnostics(ctx, vmName, reims.RedactText)
|
||||
return mgr.Registry().CollectDiagnostics(ctx, vmName, host.RedactText)
|
||||
}
|
||||
|
||||
func buildHostFacts(rep host.Report, rtCaps []string) map[string]any {
|
||||
@@ -548,7 +563,7 @@ func (a *App) ListPlugins() []plugin.PluginInfo {
|
||||
if mgr == nil {
|
||||
return nil
|
||||
}
|
||||
return mgr.LocalizePluginInfos(mgr.Registry().List())
|
||||
return mgr.LocalizePluginInfos(mgr.Registry().ListVisible())
|
||||
}
|
||||
|
||||
func (a *App) InstallPluginArchive(archivePath string) (*plugin.PluginInfo, error) {
|
||||
@@ -609,34 +624,34 @@ func (a *App) RemovePlugin(id string, purgeData bool) error {
|
||||
return mgr.Remove(context.Background(), id, purgeData)
|
||||
}
|
||||
|
||||
func (a *App) GetPluginSettings(pluginID, vmName string) map[string]any {
|
||||
func (a *App) GetPluginSettings(pluginID, vmKey string) map[string]any {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
if mgr == nil {
|
||||
return map[string]any{}
|
||||
}
|
||||
return mgr.GetSettings(pluginID, vmName, true)
|
||||
return mgr.GetSettings(pluginID, vmKey, true)
|
||||
}
|
||||
|
||||
func (a *App) SetPluginSettings(pluginID, vmName string, values map[string]any) error {
|
||||
func (a *App) SetPluginSettings(pluginID, vmKey string, values map[string]any) error {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
if mgr == nil {
|
||||
return errors.New("plugin manager not initialized")
|
||||
}
|
||||
return mgr.SetSettings(pluginID, vmName, values)
|
||||
return mgr.SetSettings(pluginID, vmKey, values)
|
||||
}
|
||||
|
||||
func (a *App) GetVMPluginSettings(vmName string) map[string]map[string]any {
|
||||
func (a *App) GetVMPluginSettings(vmKey string) map[string]map[string]any {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
if mgr == nil {
|
||||
return map[string]map[string]any{}
|
||||
}
|
||||
return mgr.GetAllVMSettings(vmName)
|
||||
return mgr.GetAllVMSettings(vmKey)
|
||||
}
|
||||
|
||||
func (a *App) GetPluginUIContributions() PluginUIContributions {
|
||||
@@ -748,6 +763,9 @@ func (a *App) ListRuntimeKinds() []rt.KindSpec {
|
||||
}
|
||||
|
||||
func (a *App) CreateVMWithDriver(req driver.CreateRequest) error {
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
dr := a.driverRouter
|
||||
mgr := a.pluginMgr
|
||||
@@ -834,7 +852,7 @@ func (a *App) ReadPluginLog(pluginID string) (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return reims.RedactText(string(raw)), nil
|
||||
return host.RedactText(string(raw)), nil
|
||||
}
|
||||
|
||||
func (a *App) DoctorPlugin(pluginID string) []plugin.DoctorFinding {
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
@@ -80,7 +80,7 @@ func (a *App) SetRuntimeChannel(channel string) error {
|
||||
defer a.mu.Unlock()
|
||||
a.cfg.RuntimeChannel = channel
|
||||
forgetRemoteRuntimes()
|
||||
return config.Save("", a.cfg)
|
||||
return a.saveConfigLocked()
|
||||
}
|
||||
|
||||
// InstallRuntimeOnline downloads, verifies and installs a published runtime
|
||||
@@ -132,7 +132,7 @@ func (a *App) installRuntime(ctx context.Context, cfg *config.Config, commit, ta
|
||||
src := rt.DefaultSource()
|
||||
step := func(msg string) {
|
||||
a.emitLog("runtime", msg)
|
||||
tasks.update(taskID, installer.Update{Kind: installer.KindStep, Message: msg, Percent: -1})
|
||||
tasks.update(taskID, host.Update{Kind: host.KindStep, Message: msg, Percent: -1})
|
||||
}
|
||||
step("Looking up runtime releases")
|
||||
// An explicit commit may be an alpha even on the stable channel: the
|
||||
@@ -149,8 +149,8 @@ func (a *App) installRuntime(ctx context.Context, cfg *config.Config, commit, ta
|
||||
if !rt.IsInstalled(cfg, r.Commit) {
|
||||
step("Downloading runtime " + r.Commit)
|
||||
path, err := src.Download(ctx, *r, rt.DownloadsDir(cfg), func(done, total int64) {
|
||||
tasks.update(taskID, installer.Update{
|
||||
Kind: installer.KindProgress, Step: "downloading runtime " + r.Commit,
|
||||
tasks.update(taskID, host.Update{
|
||||
Kind: host.KindProgress, Step: "downloading runtime " + r.Commit,
|
||||
Done: done, Total: total, Percent: percent(done, total),
|
||||
})
|
||||
})
|
||||
@@ -168,7 +168,7 @@ func (a *App) installRuntime(ctx context.Context, cfg *config.Config, commit, ta
|
||||
|
||||
a.mu.Lock()
|
||||
a.cfg.ActiveRuntime = r.Commit
|
||||
err = config.Save("", a.cfg)
|
||||
err = a.saveConfigLocked()
|
||||
a.mu.Unlock()
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -203,7 +203,7 @@ func (a *App) SetAppUpdateChannel(channel string) error {
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.cfg.AppUpdateChannel = channel
|
||||
err := config.Save("", a.cfg)
|
||||
err := a.saveConfigLocked()
|
||||
a.mu.Unlock()
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
+15
-8
@@ -12,8 +12,10 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/dataroot"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
@@ -107,6 +109,11 @@ func (a *App) CompleteSetup(dir string) error {
|
||||
if err := validateDataRoot(dir, locale); err != nil {
|
||||
return err
|
||||
}
|
||||
// Check the folder before writing anything into it: one written by a
|
||||
// newer release, or with a damaged version record, is refused untouched.
|
||||
if st := dataroot.Open(dir, version.Version); st.ReadOnly {
|
||||
return dataroot.Error(i18n.EffectiveLocale(locale), st)
|
||||
}
|
||||
|
||||
cfgPath := filepath.Join(dir, "reims-go.json")
|
||||
cfg, err := config.Load(cfgPath)
|
||||
@@ -129,18 +136,18 @@ func (a *App) CompleteSetup(dir string) error {
|
||||
if err := config.SaveLocation(dir); err != nil {
|
||||
return err
|
||||
}
|
||||
// A folder created just now gets its version stamp here.
|
||||
st := dataroot.Open(dir, version.Version)
|
||||
a.mu.Lock()
|
||||
prevRoot := ""
|
||||
if a.cfg != nil {
|
||||
prevRoot = a.cfg.DataRoot
|
||||
}
|
||||
a.cfg = cfg
|
||||
a.needsSetup = false
|
||||
a.root = st
|
||||
a.mu.Unlock()
|
||||
if filepath.Clean(prevRoot) != filepath.Clean(dir) {
|
||||
a.resetDataRootCaches()
|
||||
a.reloadPlugins()
|
||||
}
|
||||
a.logDataRoot(st)
|
||||
// Nothing touching the data folder ran before setup (startup), so plugins
|
||||
// start now whichever folder was chosen.
|
||||
a.resetDataRootCaches()
|
||||
a.reloadPlugins()
|
||||
a.wakePoll()
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
|
||||
@@ -1,62 +1,49 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// ListSnapshots returns all internal qcow2 restore points for a VM, newest first.
|
||||
func (a *App) ListSnapshots(name string) ([]reims.DiskSnapshot, error) {
|
||||
// ListSnapshots returns all driver-owned restore points for a VM, newest first.
|
||||
func (a *App) ListSnapshots(name string) ([]driver.DiskSnapshot, error) {
|
||||
return a.ListSnapshotsWithDriver("", name)
|
||||
}
|
||||
func (a *App) ListSnapshotsWithDriver(driverID, name string) ([]driver.DiskSnapshot, error) {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if svc == nil {
|
||||
return nil, errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
diskPath := resolveVMDiskPath(d)
|
||||
if diskPath == "" || !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") {
|
||||
return nil, nil
|
||||
}
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
snaps, err := reims.ListDiskSnapshots(a.baseCtx(), active.QemuImgPath(), env, diskPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sort.SliceStable(snaps, func(i, j int) bool {
|
||||
return snaps[i].CreatedAt > snaps[j].CreatedAt
|
||||
})
|
||||
return snaps, nil
|
||||
return svc.ListSnapshots(a.baseCtx(), driver.VMRef{DriverID: driverID, Name: name})
|
||||
}
|
||||
|
||||
// CreateSnapshot creates a named offline restore point inside a stopped VM's qcow2 disk.
|
||||
func (a *App) CreateSnapshot(name, snapName string) error {
|
||||
return a.runSnapshotOp(name, "-c", snapName, "Created restore point")
|
||||
return a.CreateSnapshotWithDriver("", name, snapName)
|
||||
}
|
||||
func (a *App) CreateSnapshotWithDriver(driverID, name, snapName string) error {
|
||||
return a.runSnapshotOpWithDriver(driverID, name, "create", snapName, "Created restore point")
|
||||
}
|
||||
|
||||
// RestoreSnapshot rolls back a stopped VM's qcow2 disk to the named restore point.
|
||||
func (a *App) RestoreSnapshot(name, snapName string) error {
|
||||
return a.runSnapshotOp(name, "-a", snapName, "Restored restore point")
|
||||
return a.RestoreSnapshotWithDriver("", name, snapName)
|
||||
}
|
||||
func (a *App) RestoreSnapshotWithDriver(driverID, name, snapName string) error {
|
||||
return a.runSnapshotOpWithDriver(driverID, name, "restore", snapName, "Restored restore point")
|
||||
}
|
||||
|
||||
// DeleteSnapshot removes a named restore point from a stopped VM's qcow2 disk.
|
||||
func (a *App) DeleteSnapshot(name, snapName string) error {
|
||||
return a.runSnapshotOp(name, "-d", snapName, "Deleted restore point")
|
||||
return a.DeleteSnapshotWithDriver("", name, snapName)
|
||||
}
|
||||
func (a *App) DeleteSnapshotWithDriver(driverID, name, snapName string) error {
|
||||
return a.runSnapshotOpWithDriver(driverID, name, "delete", snapName, "Deleted restore point")
|
||||
}
|
||||
|
||||
func (a *App) runSnapshotOp(name, flag, snapName, verb string) error {
|
||||
func (a *App) runSnapshotOpWithDriver(driverID, name, operation, snapName, verb string) error {
|
||||
loc := a.locale()
|
||||
cleanSnap := strings.TrimSpace(snapName)
|
||||
if cleanSnap == "" {
|
||||
@@ -65,45 +52,22 @@ func (a *App) runSnapshotOp(name, flag, snapName, verb string) error {
|
||||
if len([]rune(cleanSnap)) > 64 {
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_NAME_TOO_LONG", "err.snapshot.name_too_long", nil, nil)
|
||||
}
|
||||
if _, err := reims.ValidateSnapshotName(cleanSnap); err != nil {
|
||||
if _, err := driver.ValidateSnapshotName(cleanSnap); err != nil {
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_NAME_INVALID", "err.snapshot.name_invalid", nil, err)
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
if svc == nil {
|
||||
return errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
ref := driver.VMRef{DriverID: driverID, Name: name}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(driverID, name, line) })
|
||||
if err := svc.RunSnapshot(a.baseCtx(), ref, operation, cleanSnap, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
ctx := a.baseCtx()
|
||||
|
||||
d, release, err := vmstart.LockVM(ctx, c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_VM_RUNNING", "err.snapshot.vm_running", i18n.Vars{"name": name}, nil)
|
||||
}
|
||||
if a.isVMSuspended(d) {
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil)
|
||||
}
|
||||
diskPath := resolveVMDiskPath(d)
|
||||
if diskPath == "" {
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_NO_DISK", "err.clone.no_disk", i18n.Vars{"name": name}, nil)
|
||||
}
|
||||
if !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") {
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_QCOW2_ONLY", "err.snapshot.qcow2_only", nil, nil)
|
||||
}
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
if err := reims.RunDiskSnapshot(ctx, active.QemuImgPath(), env, flag, cleanSnap, diskPath); err != nil {
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_QEMU_IMG", "err.snapshot.qemu_img_failed", i18n.Vars{"snap": cleanSnap}, err)
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("%s %q", verb, cleanSnap))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("%s %q", verb, cleanSnap))
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return nil
|
||||
}
|
||||
+49
-17
@@ -7,6 +7,8 @@ import (
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
)
|
||||
|
||||
const sshUserFileName = ".reims-go-ssh-user"
|
||||
@@ -14,9 +16,21 @@ const sshUserFileName = ".reims-go-ssh-user"
|
||||
var safeSSHUserRe = regexp.MustCompile(`^[A-Za-z0-9._-]+$`)
|
||||
|
||||
// sshHostAlias returns a stable ~/.ssh/config Host alias for a VM.
|
||||
func sshHostAlias(vmName string) string {
|
||||
func sshHostAlias(vmName string) string { return sshHostAliasForDriver("", vmName) }
|
||||
|
||||
func sshHostAliasForDriver(driverID, vmName string) string {
|
||||
var b strings.Builder
|
||||
b.WriteString("reims-")
|
||||
if id := driver.CanonicalDriverID(driverID); id != "" && id != driver.BuiltinReimsMacOSDriverID {
|
||||
for _, r := range strings.ToLower(id) {
|
||||
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
|
||||
b.WriteRune(r)
|
||||
} else {
|
||||
b.WriteByte('-')
|
||||
}
|
||||
}
|
||||
b.WriteByte('-')
|
||||
}
|
||||
for _, r := range strings.ToLower(strings.TrimSpace(vmName)) {
|
||||
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
|
||||
b.WriteRune(r)
|
||||
@@ -27,9 +41,17 @@ func sshHostAlias(vmName string) string {
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func sshConfigKey(driverID, name string) string {
|
||||
if id := driver.CanonicalDriverID(driverID); id == "" || id == driver.BuiltinReimsMacOSDriverID {
|
||||
return name
|
||||
}
|
||||
return driver.NewVMRef(driverID, name).Key()
|
||||
}
|
||||
|
||||
// GetVMSSHUser returns the remembered SSH login user for a VM (empty if unset).
|
||||
func (a *App) GetVMSSHUser(name string) string {
|
||||
d, err := a.GetVMDetail(name)
|
||||
func (a *App) GetVMSSHUser(name string) string { return a.GetVMSSHUserWithDriver("", name) }
|
||||
func (a *App) GetVMSSHUserWithDriver(driverID, name string) string {
|
||||
d, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil || d.Directory == "" {
|
||||
return ""
|
||||
}
|
||||
@@ -41,12 +63,13 @@ func (a *App) GetVMSSHUser(name string) string {
|
||||
}
|
||||
|
||||
// SetVMSSHUser persists the preferred SSH login user for a VM.
|
||||
func (a *App) SetVMSSHUser(name, user string) error {
|
||||
func (a *App) SetVMSSHUser(name, user string) error { return a.SetVMSSHUserWithDriver("", name, user) }
|
||||
func (a *App) SetVMSSHUserWithDriver(driverID, name, user string) error {
|
||||
user = strings.TrimSpace(user)
|
||||
if user != "" && !safeSSHUserRe.MatchString(user) {
|
||||
return fmt.Errorf("invalid SSH username %q", user)
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
d, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -64,7 +87,10 @@ func (a *App) SetVMSSHUser(name, user string) error {
|
||||
// OpenSSHTerminal launches an interactive Windows Terminal (falling back to
|
||||
// PowerShell) connected to the VM's forwarded SSH port.
|
||||
func (a *App) OpenSSHTerminal(name, user string) error {
|
||||
d, err := a.GetVMDetail(name)
|
||||
return a.OpenSSHTerminalWithDriver("", name, user)
|
||||
}
|
||||
func (a *App) OpenSSHTerminalWithDriver(driverID, name, user string) error {
|
||||
d, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -73,11 +99,11 @@ func (a *App) OpenSSHTerminal(name, user string) error {
|
||||
}
|
||||
user = strings.TrimSpace(user)
|
||||
if user == "" {
|
||||
user = a.GetVMSSHUser(name)
|
||||
user = a.GetVMSSHUserWithDriver(driverID, name)
|
||||
} else if !safeSSHUserRe.MatchString(user) {
|
||||
return fmt.Errorf("invalid SSH username %q", user)
|
||||
} else {
|
||||
_ = a.SetVMSSHUser(name, user)
|
||||
_ = a.SetVMSSHUserWithDriver(driverID, name, user)
|
||||
}
|
||||
target := "127.0.0.1"
|
||||
if user != "" {
|
||||
@@ -95,14 +121,17 @@ func (a *App) OpenSSHTerminal(name, user string) error {
|
||||
if err := cmd.Start(); err != nil {
|
||||
return fmt.Errorf("open SSH terminal: %w", err)
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Opened SSH terminal (%s -p %s)", target, portStr))
|
||||
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Opened SSH terminal (%s -p %s)", target, portStr))
|
||||
return 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(name, user string) (string, error) {
|
||||
d, err := a.GetVMDetail(name)
|
||||
return a.WriteSSHConfigWithDriver("", name, user)
|
||||
}
|
||||
func (a *App) WriteSSHConfigWithDriver(driverID, name, user string) (string, error) {
|
||||
d, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -111,11 +140,11 @@ func (a *App) WriteSSHConfig(name, user string) (string, error) {
|
||||
}
|
||||
user = strings.TrimSpace(user)
|
||||
if user == "" {
|
||||
user = a.GetVMSSHUser(name)
|
||||
user = a.GetVMSSHUserWithDriver(driverID, name)
|
||||
} else if !safeSSHUserRe.MatchString(user) {
|
||||
return "", fmt.Errorf("invalid SSH username %q", user)
|
||||
} else {
|
||||
_ = a.SetVMSSHUser(name, user)
|
||||
_ = a.SetVMSSHUserWithDriver(driverID, name, user)
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
@@ -126,18 +155,21 @@ func (a *App) WriteSSHConfig(name, user string) (string, error) {
|
||||
return "", fmt.Errorf("create ~/.ssh: %w", err)
|
||||
}
|
||||
cfgPath := filepath.Join(sshDir, "config")
|
||||
alias := sshHostAlias(name)
|
||||
if err := upsertSSHConfigBlock(cfgPath, name, alias, d.SSHPort, user); err != nil {
|
||||
alias := sshHostAliasForDriver(driverID, name)
|
||||
if err := upsertSSHConfigBlock(cfgPath, sshConfigKey(driverID, name), alias, d.SSHPort, user); err != nil {
|
||||
return "", err
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Updated ~/.ssh/config with Host %s (127.0.0.1:%d)", alias, d.SSHPort))
|
||||
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Updated ~/.ssh/config with Host %s (127.0.0.1:%d)", alias, d.SSHPort))
|
||||
return alias, nil
|
||||
}
|
||||
|
||||
// OpenVSCodeSSH ensures the VM's Host block is present in ~/.ssh/config and
|
||||
// launches VS Code (falling back to Cursor) in Remote-SSH mode.
|
||||
func (a *App) OpenVSCodeSSH(name, user string) error {
|
||||
alias, err := a.WriteSSHConfig(name, user)
|
||||
return a.OpenVSCodeSSHWithDriver("", name, user)
|
||||
}
|
||||
func (a *App) OpenVSCodeSSHWithDriver(driverID, name, user string) error {
|
||||
alias, err := a.WriteSSHConfigWithDriver(driverID, name, user)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -155,7 +187,7 @@ func (a *App) OpenVSCodeSSH(name, user string) error {
|
||||
if err := cmd.Start(); err != nil {
|
||||
return fmt.Errorf("launch editor Remote-SSH: %w", err)
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Launched %s Remote-SSH for %s", filepath.Base(bin), alias))
|
||||
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Launched %s Remote-SSH for %s", filepath.Base(bin), alias))
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,9 @@ import (
|
||||
)
|
||||
|
||||
func TestSSHHostAlias(t *testing.T) {
|
||||
if sshHostAliasForDriver("test.driver.linux", "dev") == sshHostAliasForDriver("", "dev") {
|
||||
t.Fatal("same-name drivers share an SSH alias")
|
||||
}
|
||||
if got := sshHostAlias("macos-tahoe"); got != "reims-macos-tahoe" {
|
||||
t.Fatalf("alias = %q", got)
|
||||
}
|
||||
|
||||
+32
-66
@@ -1,13 +1,10 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
)
|
||||
|
||||
@@ -34,50 +31,28 @@ type VMStats struct {
|
||||
GuestToolsSleepGuard bool `json:"guest_tools_sleep_guard"`
|
||||
}
|
||||
|
||||
func resolveVMDiskPath(d reims.VMDetail) string {
|
||||
raw := strings.TrimSpace(d.Disk)
|
||||
// `reims-ctl show` formats disk like "disk.qcow2 (nvme, 128G)" or an absolute path.
|
||||
if idx := strings.Index(raw, " ("); idx > 0 {
|
||||
raw = strings.TrimSpace(raw[:idx])
|
||||
}
|
||||
if raw != "" {
|
||||
if filepath.IsAbs(raw) {
|
||||
return raw
|
||||
}
|
||||
if d.Directory != "" {
|
||||
return filepath.Join(d.Directory, raw)
|
||||
}
|
||||
}
|
||||
if d.Directory != "" {
|
||||
return filepath.Join(d.Directory, "disk.qcow2")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// GetVMStats samples QEMU CPU/memory usage (when running), disk actual vs
|
||||
// virtual capacity, and live Guest Tools status.
|
||||
func (a *App) GetVMStats(name string) (VMStats, error) {
|
||||
stats := VMStats{Name: name}
|
||||
c, err := a.client()
|
||||
// GetVMStats samples host-side process and disk telemetry through the owning driver.
|
||||
func (a *App) GetVMStats(name string) (VMStats, error) { return a.GetVMStatsWithDriver("", name) }
|
||||
func (a *App) GetVMStatsWithDriver(driverID, name string) (VMStats, error) {
|
||||
vm, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return stats, err
|
||||
return VMStats{Name: name}, err
|
||||
}
|
||||
ctx := context.Background()
|
||||
vms, _ := a.polledVMs(ctx)
|
||||
var pid int
|
||||
for _, vm := range vms {
|
||||
if vm.Name == name {
|
||||
stats.Running = vm.State == "running"
|
||||
if vm.PID != nil {
|
||||
pid = *vm.PID
|
||||
}
|
||||
break
|
||||
ref := vm.Ref()
|
||||
stats := VMStats{Name: vm.Name, Running: vm.State == "running"}
|
||||
pid := 0
|
||||
if vm.PID != nil {
|
||||
pid = *vm.PID
|
||||
}
|
||||
if listed, ok := a.polledVMForDriver(ref.DriverID, vm.Name); ok {
|
||||
stats.Running = stats.Running || listed.State == "running"
|
||||
if listed.PID != nil {
|
||||
pid = *listed.PID
|
||||
}
|
||||
}
|
||||
stats.PID = pid
|
||||
|
||||
if diskPath := a.vmDiskPath(ctx, c, name); diskPath != "" {
|
||||
if du, err := host.InspectDiskUsage(diskPath); err == nil {
|
||||
if vm.DiskPath != "" {
|
||||
if du, err := host.InspectDiskUsage(vm.DiskPath); err == nil {
|
||||
stats.DiskActualBytes = du.ActualBytes
|
||||
stats.DiskVirtualBytes = du.VirtualBytes
|
||||
stats.DiskFormat = du.Format
|
||||
@@ -86,13 +61,12 @@ func (a *App) GetVMStats(name string) (VMStats, error) {
|
||||
stats.DiskBackingDepthWarn = du.BackingDepth >= host.BackingChainWarnDepth || du.BackingBroken
|
||||
}
|
||||
}
|
||||
|
||||
if stats.Running && pid > 0 {
|
||||
stats.WindowFullscreen = host.IsProcessWindowFullscreen(uint32(pid))
|
||||
if sample, err := host.SampleProcessStats(pid); err == nil {
|
||||
a.mu.Lock()
|
||||
prev := a.procSamples[name]
|
||||
a.procSamples[name] = sample
|
||||
prev := a.procSamples[ref.Key()]
|
||||
a.procSamples[ref.Key()] = sample
|
||||
a.mu.Unlock()
|
||||
stats.CPUPercent = host.ComputeCPUPercent(prev, sample, runtime.NumCPU())
|
||||
stats.MemoryRSSBytes = sample.WorkingSet
|
||||
@@ -105,28 +79,20 @@ func (a *App) GetVMStats(name string) (VMStats, error) {
|
||||
}
|
||||
} else {
|
||||
a.mu.Lock()
|
||||
delete(a.procSamples, name)
|
||||
delete(a.procSamples, ref.Key())
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
srv := a.guestTools
|
||||
a.mu.Unlock()
|
||||
if srv != nil {
|
||||
st := srv.Status(name, 15*time.Second)
|
||||
stats.GuestToolsConnected = st.Connected
|
||||
stats.GuestToolsMountMode = st.MountMode
|
||||
stats.GuestToolsAgentVersion = st.AgentVersion
|
||||
stats.GuestToolsSleepGuard = st.SleepActive
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.mu.Lock()
|
||||
srv := a.guestTools
|
||||
a.mu.Unlock()
|
||||
if srv != nil {
|
||||
st := srv.Status(vm.Name, 15*time.Second)
|
||||
stats.GuestToolsConnected = st.Connected
|
||||
stats.GuestToolsMountMode = st.MountMode
|
||||
stats.GuestToolsAgentVersion = st.AgentVersion
|
||||
stats.GuestToolsSleepGuard = st.SleepActive
|
||||
}
|
||||
}
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
// ToggleBorderless switches borderless fullscreen startup via `reims-ctl set --borderless`.
|
||||
func (a *App) ToggleBorderless(name string, enabled bool) error {
|
||||
v := enabled
|
||||
return a.ApplyVMSettings(reims.SetOpts{
|
||||
Name: name,
|
||||
Borderless: &v,
|
||||
})
|
||||
}
|
||||
+97
-111
@@ -1,197 +1,180 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
func enrichVMListStates(vms []reims.VMListItem) {
|
||||
for i := range vms {
|
||||
if vms[i].State == "stopped" && reims.HasSuspendState(vms[i].Dir) {
|
||||
vms[i].State = "suspended"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) populateSuspendDetail(d *reims.VMDetail) {
|
||||
if d != nil && d.State == "stopped" && reims.HasSuspendState(d.Directory) {
|
||||
d.State = "suspended"
|
||||
if info, err := reims.ReadSuspendInfo(d.Directory); err == nil {
|
||||
d.SuspendInfo = info
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) isVMSuspended(d reims.VMDetail) bool {
|
||||
return d.State == "suspended" || (d.State == "stopped" && reims.HasSuspendState(d.Directory))
|
||||
}
|
||||
|
||||
// SuspendVM saves a VM's running state and closes its QEMU process.
|
||||
func (a *App) SuspendVM(name string) error {
|
||||
prep, err := a.prep(name)
|
||||
if err != nil {
|
||||
return a.SuspendVMWithDriver("", name)
|
||||
}
|
||||
|
||||
func (a *App) SuspendVMWithDriver(driverID, name string) error {
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
svc, gt := a.lifecycleSvc, a.guestTools
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
return errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
ctx := a.baseCtx()
|
||||
d, release, err := vmstart.LockVM(ctx, prep.Client, name)
|
||||
_, vm, err := svc.Resolve(ctx, driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
end, err := a.beginSuspendTransition(name, "suspending")
|
||||
ref := vm.Ref()
|
||||
key := ref.Key()
|
||||
end, err := a.beginSuspendTransition(key, ref.Name, "suspending")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer end()
|
||||
|
||||
a.mu.Lock()
|
||||
mgr, gt := a.pluginMgr, a.guestTools
|
||||
a.mu.Unlock()
|
||||
event := plugin.VMEventPayload{VMName: name, VMDir: d.Directory, DriverID: builtin.IDDriverReimsMacOS}
|
||||
if mgr != nil {
|
||||
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMBeforeStop, event)
|
||||
}
|
||||
lastPct := -1
|
||||
info, err := prep.SuspendSnapshot(ctx, d, func(p qmp.MigrateProgress) {
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
||||
res, err := svc.Suspend(ctx, ref, func(p driver.SuspendProgress) {
|
||||
if pct, ok := suspendProgressPercent(p); ok {
|
||||
if pct >= lastPct+25 || p.Status == "completed" {
|
||||
lastPct = pct
|
||||
a.emitLog(name, fmt.Sprintf("Suspend progress: %s (%d%%)", p.Status, pct))
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, fmt.Sprintf("Suspend progress: %s (%d%%)", p.Status, pct))
|
||||
}
|
||||
}
|
||||
})
|
||||
}, w, w)
|
||||
if err != nil {
|
||||
a.emitLog(name, "Suspend error: "+err.Error())
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Suspend error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
a.cancelRebootWatcher(name)
|
||||
stopVMMonitor(name)
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.cancelRebootWatcherKey(key)
|
||||
stopVMMonitor(ref.Name)
|
||||
}
|
||||
if gt != nil {
|
||||
gt.UnregisterVM(name)
|
||||
gt.UnregisterVM(key)
|
||||
}
|
||||
if mgr != nil {
|
||||
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStop, event)
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Suspended %s (%.2f GiB saved)", name, float64(info.VMStateSize)/float64(1<<30)))
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, fmt.Sprintf("Suspended %s (%.2f GiB saved)", ref.Name, float64(res.VMStateSize)/float64(1<<30)))
|
||||
return nil
|
||||
}
|
||||
|
||||
// ResumeVM restores a suspended VM with its original media and devices.
|
||||
func (a *App) ResumeVM(name string) error {
|
||||
prep, err := a.prep(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, release, err := vmstart.LockVM(a.baseCtx(), prep.Client, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
return a.resumeLocked(prep, d)
|
||||
return a.ResumeVMWithDriver("", name)
|
||||
}
|
||||
|
||||
func (a *App) resumeLocked(prep *vmstart.Prep, d reims.VMDetail) error {
|
||||
name := d.Name
|
||||
end, err := a.beginSuspendTransition(name, "resuming")
|
||||
func (a *App) ResumeVMWithDriver(driverID, name string) error {
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
return errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
ctx := a.baseCtx()
|
||||
_, vm, err := svc.Resolve(ctx, driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ref := vm.Ref()
|
||||
key := ref.Key()
|
||||
end, err := a.beginSuspendTransition(key, ref.Name, "resuming")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer end()
|
||||
|
||||
a.mu.Lock()
|
||||
root, tmpDir, mgr := a.cfg.DataRoot, a.cfg.TempDir(), a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
rep := host.Inspect(root)
|
||||
var qmpAddr string
|
||||
if d.State == "stopped" && reims.HasSuspendState(d.Directory) && rep.NeedsColdRebootWorkaround {
|
||||
sockPath := qmp.RebootSocketPath(d.Directory, tmpDir, name)
|
||||
if qmp.HasWin10RebootUnixArgs(d.ExtraArgs, sockPath) {
|
||||
a.cancelRebootWatcher(name)
|
||||
if err := os.Remove(sockPath); err != nil && !os.IsNotExist(err) {
|
||||
return fmt.Errorf("remove stale reboot socket: %w", err)
|
||||
}
|
||||
qmpAddr = "unix:" + sockPath
|
||||
var extraEnv []string
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.cancelRebootWatcherKey(key)
|
||||
if active, rerr := rt.ResolveActive(&cfgCopy); rerr == nil && active != nil && active.Manifest.HasCapability("win32-unicode-input") {
|
||||
extraEnv = append(extraEnv, a.inputBridgeEnv(ref.Name, vm.Directory)...)
|
||||
}
|
||||
}
|
||||
if prep.Runtime.Manifest.HasCapability("win32-unicode-input") {
|
||||
prep.Client.Env = append(prep.Client.Env, a.inputBridgeEnv(name, d.Directory)...)
|
||||
}
|
||||
if prep.Runtime.Manifest.HasCapability("display-fixed-mode") &&
|
||||
host.ShouldUseFixedGuestMode(d.Borderless, d.Resolution, rep.PrimaryDisplay) {
|
||||
prep.Client.Env = append(prep.Client.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
|
||||
}
|
||||
if prep.Runtime.Manifest.HasCapability("client-window-close") {
|
||||
prep.Client.Env = append(prep.Client.Env, vmCloseRequestEnv(name)...)
|
||||
}
|
||||
|
||||
startAt := time.Now()
|
||||
out := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
if err := prep.ResumeSnapshot(a.baseCtx(), d, rep, out, out); err != nil {
|
||||
a.emitLog(name, "Resume error: "+err.Error())
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
||||
result, err := svc.Resume(ctx, ref, extraEnv, w, w)
|
||||
if err != nil {
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Resume error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
if mgr != nil {
|
||||
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStart, plugin.VMEventPayload{
|
||||
VMName: name, VMDir: d.Directory, DriverID: builtin.IDDriverReimsMacOS, QMPAddr: qmpAddr,
|
||||
})
|
||||
} else if qmpAddr != "" {
|
||||
a.watchWin10ColdReboot(name, qmpAddr)
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
for _, action := range result.PostStart {
|
||||
if action.Kind != "qmp.watch_cold_reboot" {
|
||||
continue
|
||||
}
|
||||
if addr, _ := action.Params["qmp_addr"].(string); addr != "" {
|
||||
a.watchWin10ColdReboot(ref.Name, addr)
|
||||
}
|
||||
}
|
||||
a.startVMMonitor(ref.Name, vm, startAt)
|
||||
}
|
||||
a.startVMMonitor(name, d, startAt)
|
||||
a.emitLog(name, fmt.Sprintf("Resumed %s in %.1fs", name, time.Since(startAt).Seconds()))
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, fmt.Sprintf("Resumed %s in %.1fs", ref.Name, time.Since(startAt).Seconds()))
|
||||
return nil
|
||||
}
|
||||
|
||||
// DiscardSuspend deletes a stopped VM's saved execution state.
|
||||
func (a *App) DiscardSuspend(name string) error {
|
||||
c, err := a.client()
|
||||
return a.DiscardSuspendWithDriver("", name)
|
||||
}
|
||||
|
||||
func (a *App) DiscardSuspendWithDriver(driverID, name string) error {
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
return errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
ctx := a.baseCtx()
|
||||
_, vm, err := svc.Resolve(ctx, driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, release, err := vmstart.LockVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
ref := vm.Ref()
|
||||
if err := svc.DiscardSuspend(ctx, ref); err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
if err := vmstart.DiscardSnapshot(a.locale(), d); err != nil {
|
||||
return err
|
||||
}
|
||||
a.emitLog(name, "Discarded suspend state for "+name)
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Discarded suspend state for "+ref.Name)
|
||||
a.wakePoll()
|
||||
a.emitStateChanged()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) beginSuspendTransition(name, state string) (func(), error) {
|
||||
func (a *App) beginSuspendTransition(key, displayName, state string) (func(), error) {
|
||||
a.mu.Lock()
|
||||
loc := a.cfg.Locale
|
||||
if a.transitions[name] != "" {
|
||||
if a.transitions[key] != "" {
|
||||
a.mu.Unlock()
|
||||
return nil, i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil)
|
||||
return nil, i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": displayName}, nil)
|
||||
}
|
||||
a.transitions[name] = state
|
||||
a.transitions[key] = state
|
||||
a.mu.Unlock()
|
||||
a.emitStateChanged()
|
||||
return func() {
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, name)
|
||||
delete(a.transitions, key)
|
||||
a.mu.Unlock()
|
||||
a.wakePoll()
|
||||
a.emitStateChanged()
|
||||
}, nil
|
||||
}
|
||||
|
||||
func suspendProgressPercent(p qmp.MigrateProgress) (int, bool) {
|
||||
func suspendProgressPercent(p driver.SuspendProgress) (int, bool) {
|
||||
if p.Status == "completed" {
|
||||
return 100, true
|
||||
}
|
||||
@@ -219,3 +202,6 @@ func (a *App) emitStateChanged() {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
}
|
||||
|
||||
// Keep context import used cleanly for future cancellation hooks.
|
||||
var _ context.Context
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
)
|
||||
|
||||
@@ -31,12 +31,12 @@ func TestEnrichVMListStatesAndPopulateSuspendDetail(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
vms := []reims.VMListItem{
|
||||
vms := []driver.VMListItem{
|
||||
{Name: "mac-a", Dir: suspendedDir, State: "stopped"},
|
||||
{Name: "mac-b", Dir: stoppedDir, State: "stopped"},
|
||||
{Name: "mac-c", Dir: suspendedDir, State: "running"},
|
||||
}
|
||||
enrichVMListStates(vms)
|
||||
enrichMacOSVMListStates(vms)
|
||||
if vms[0].State != "suspended" {
|
||||
t.Fatalf("mac-a state = %q, want suspended", vms[0].State)
|
||||
}
|
||||
@@ -47,15 +47,11 @@ func TestEnrichVMListStatesAndPopulateSuspendDetail(t *testing.T) {
|
||||
t.Fatalf("running VM must stay running, got %q", vms[2].State)
|
||||
}
|
||||
|
||||
a := &App{}
|
||||
det := reims.VMDetail{Name: "mac-a", Directory: suspendedDir, State: "stopped"}
|
||||
a.populateSuspendDetail(&det)
|
||||
populateSuspendDetail(&det)
|
||||
if det.State != "suspended" || det.SuspendInfo == nil || det.SuspendInfo.VMStateSize != 10 {
|
||||
t.Fatalf("populateSuspendDetail failed: %+v", det)
|
||||
}
|
||||
if !a.isVMSuspended(det) {
|
||||
t.Fatal("expected isVMSuspended=true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripLegacyManagedExtraArgsStripsIncomingDefer(t *testing.T) {
|
||||
@@ -68,14 +64,14 @@ func TestStripLegacyManagedExtraArgsStripsIncomingDefer(t *testing.T) {
|
||||
func TestSuspendProgressPercentTracksRemainingAcrossSparseRAM(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
prog qmp.MigrateProgress
|
||||
prog driver.SuspendProgress
|
||||
pct int
|
||||
ok bool
|
||||
}{
|
||||
{"setup", qmp.MigrateProgress{Status: "setup"}, 0, false},
|
||||
{"active sparse", qmp.MigrateProgress{Status: "active", Transferred: 400, Remaining: 1000, Total: 2000}, 50, true},
|
||||
{"device stage caps below 100", qmp.MigrateProgress{Status: "device", Transferred: 1080, Remaining: 0, Total: 2000}, 99, true},
|
||||
{"completed always 100", qmp.MigrateProgress{Status: "completed", Transferred: 1080, Remaining: 0, Total: 2000}, 100, true},
|
||||
{"setup", driver.SuspendProgress{Status: "setup"}, 0, false},
|
||||
{"active sparse", driver.SuspendProgress{Status: "active", Transferred: 400, Remaining: 1000, Total: 2000}, 50, true},
|
||||
{"device stage caps below 100", driver.SuspendProgress{Status: "device", Transferred: 1080, Remaining: 0, Total: 2000}, 99, true},
|
||||
{"completed always 100", driver.SuspendProgress{Status: "completed", Transferred: 1080, Remaining: 0, Total: 2000}, 100, true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
|
||||
+12
-12
@@ -14,7 +14,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
@@ -86,7 +86,7 @@ func (m *taskManager) startWithInstaller(kind, subject, vm, installerKind, insta
|
||||
now := time.Now().UnixMilli()
|
||||
step := ""
|
||||
if installerPhase == TaskPhaseQueued {
|
||||
step = installer.WaitingNote
|
||||
step = host.WaitingNote
|
||||
}
|
||||
e := &taskEntry{
|
||||
task: Task{
|
||||
@@ -117,7 +117,7 @@ func (m *taskManager) setInstaller(id, kind, version, phase string) {
|
||||
e.task.InstallerVersion = version
|
||||
e.task.InstallerPhase = phase
|
||||
if phase == TaskPhaseQueued {
|
||||
e.task.Step = installer.WaitingNote
|
||||
e.task.Step = host.WaitingNote
|
||||
e.task.Done, e.task.Total, e.task.Percent, e.task.Rate = 0, 0, -1, 0
|
||||
e.rate = rateMeter{}
|
||||
}
|
||||
@@ -150,7 +150,7 @@ func (m *taskManager) clearInstallerPhase(id string) {
|
||||
}
|
||||
|
||||
// update applies an upstream progress report to the task.
|
||||
func (m *taskManager) update(id string, u installer.Update) {
|
||||
func (m *taskManager) update(id string, u host.Update) {
|
||||
m.mu.Lock()
|
||||
e, ok := m.tasks[id]
|
||||
if !ok || e.task.Status != TaskRunning {
|
||||
@@ -159,8 +159,8 @@ func (m *taskManager) update(id string, u installer.Update) {
|
||||
}
|
||||
force := false
|
||||
switch u.Kind {
|
||||
case installer.KindNote:
|
||||
if u.Message != installer.WaitingNote || e.task.InstallerKind == "" {
|
||||
case host.KindNote:
|
||||
if u.Message != host.WaitingNote || e.task.InstallerKind == "" {
|
||||
m.mu.Unlock()
|
||||
return
|
||||
}
|
||||
@@ -173,7 +173,7 @@ func (m *taskManager) update(id string, u installer.Update) {
|
||||
e.task.Done, e.task.Total, e.task.Percent, e.task.Rate = 0, 0, -1, 0
|
||||
e.rate = rateMeter{}
|
||||
force = true
|
||||
case installer.KindStep:
|
||||
case host.KindStep:
|
||||
if e.task.InstallerPhase == TaskPhaseQueued {
|
||||
e.task.InstallerPhase = TaskPhaseDownloading
|
||||
force = true
|
||||
@@ -182,7 +182,7 @@ func (m *taskManager) update(id string, u installer.Update) {
|
||||
e.task.Step = u.Message
|
||||
e.task.Done, e.task.Total, e.task.Percent, e.task.Rate = 0, 0, -1, 0
|
||||
e.rate = rateMeter{}
|
||||
case installer.KindProgress:
|
||||
case host.KindProgress:
|
||||
if e.task.InstallerPhase == TaskPhaseQueued {
|
||||
e.task.InstallerPhase = TaskPhaseDownloading
|
||||
force = true
|
||||
@@ -358,7 +358,7 @@ func (a *App) ensureTaskEmitter() {
|
||||
|
||||
// ctlTaskWriter returns a writer for reims-ctl output that routes progress
|
||||
// lines into a task and everything else to the log. reims-ctl prints its
|
||||
// progress as "<step>: N% of <size>" (installer.ParseCtlLine), sometimes behind
|
||||
// progress as "<step>: N% of <size>" (host.ParseCtlLine), sometimes behind
|
||||
// a "<vm>: " prefix, which is dropped from the step. Each new step is logged
|
||||
// once, so the log keeps the milestones without one line per percent.
|
||||
// finish closes the task with the command's error.
|
||||
@@ -374,11 +374,11 @@ func (a *App) ctlTaskWriterWithCancel(kind, vm string, cancel context.CancelFunc
|
||||
lastLogAt := time.Now()
|
||||
trim := func(s string) string { return strings.TrimPrefix(s, vm+": ") }
|
||||
w = vmstart.LineWriter(func(line string) {
|
||||
u, ok := installer.ParseCtlLine(line)
|
||||
u, ok := host.ParseCtlLine(line)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if u.Kind == installer.KindProgress {
|
||||
if u.Kind == host.KindProgress {
|
||||
u.Step = trim(u.Step)
|
||||
if u.Step != lastStep {
|
||||
lastStep = u.Step
|
||||
@@ -399,7 +399,7 @@ func (a *App) ctlTaskWriterWithCancel(kind, vm string, cancel context.CancelFunc
|
||||
step := trim(u.Message)
|
||||
lastStep = step
|
||||
lastLogAt = time.Now()
|
||||
tasks.update(id, installer.Update{Kind: installer.KindStep, Message: step, Percent: -1})
|
||||
tasks.update(id, host.Update{Kind: host.KindStep, Message: step, Percent: -1})
|
||||
})
|
||||
return id, w, func(err error) { tasks.finish(id, "", err) }
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
)
|
||||
|
||||
func newTestTasks(t *testing.T) *[]Task {
|
||||
|
||||
@@ -14,16 +14,16 @@ import (
|
||||
"image/png"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
"github.com/Nwflower/reims-go/internal/thumb"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// VMThumbnail is one frame of a VM's screen as a data URL.
|
||||
@@ -42,20 +42,32 @@ var thumbLocks = struct {
|
||||
locks map[string]*sync.Mutex
|
||||
}{locks: make(map[string]*sync.Mutex)}
|
||||
|
||||
func (a *App) thumbPath(name string) string {
|
||||
func (a *App) thumbPath(name string) string { return a.thumbPathForDriver("", name) }
|
||||
func (a *App) thumbPathForDriver(driverID, name string) string {
|
||||
a.mu.Lock()
|
||||
dir := a.cfg.XDGCacheDir()
|
||||
a.mu.Unlock()
|
||||
return filepath.Join(dir, "thumbs", name+".jpg")
|
||||
prefix := ""
|
||||
if id := driver.CanonicalDriverID(driverID); id != "" && id != driver.BuiltinReimsMacOSDriverID {
|
||||
prefix = strings.Map(func(r rune) rune {
|
||||
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
|
||||
return r
|
||||
}
|
||||
return '_'
|
||||
}, id) + "__"
|
||||
}
|
||||
return filepath.Join(dir, "thumbs", prefix+name+".jpg")
|
||||
}
|
||||
|
||||
func vmThumbLock(name string) *sync.Mutex {
|
||||
func vmThumbLock(name string) *sync.Mutex { return vmThumbLockForDriver("", name) }
|
||||
func vmThumbLockForDriver(driverID, name string) *sync.Mutex {
|
||||
key := vmKeyForDriver(driverID, name)
|
||||
thumbLocks.mu.Lock()
|
||||
defer thumbLocks.mu.Unlock()
|
||||
mu := thumbLocks.locks[name]
|
||||
mu := thumbLocks.locks[key]
|
||||
if mu == nil {
|
||||
mu = &sync.Mutex{}
|
||||
thumbLocks.locks[name] = mu
|
||||
thumbLocks.locks[key] = mu
|
||||
}
|
||||
return mu
|
||||
}
|
||||
@@ -63,11 +75,12 @@ func vmThumbLock(name string) *sync.Mutex {
|
||||
// releaseVMThumbnail waits for an in-flight capture before releasing its lock,
|
||||
// so an old request cannot install a new lock after the VM has been deleted.
|
||||
func releaseVMThumbnail(name string) {
|
||||
key := vmKey(name)
|
||||
mu := vmThumbLock(name)
|
||||
mu.Lock()
|
||||
thumbLocks.mu.Lock()
|
||||
if thumbLocks.locks[name] == mu {
|
||||
delete(thumbLocks.locks, name)
|
||||
if thumbLocks.locks[key] == mu {
|
||||
delete(thumbLocks.locks, key)
|
||||
}
|
||||
thumbLocks.mu.Unlock()
|
||||
mu.Unlock()
|
||||
@@ -76,11 +89,14 @@ func releaseVMThumbnail(name string) {
|
||||
// GetVMThumbnail returns the VM's screen: a fresh frame while it runs, else
|
||||
// the last one saved. An empty DataURL means there is no frame to show.
|
||||
func (a *App) GetVMThumbnail(name string) (VMThumbnail, error) {
|
||||
path := a.thumbPath(name)
|
||||
mu := vmThumbLock(name)
|
||||
return a.GetVMThumbnailWithDriver("", name)
|
||||
}
|
||||
func (a *App) GetVMThumbnailWithDriver(driverID, name string) (VMThumbnail, error) {
|
||||
path := a.thumbPathForDriver(driverID, name)
|
||||
mu := vmThumbLockForDriver(driverID, name)
|
||||
if mu.TryLock() {
|
||||
defer mu.Unlock()
|
||||
if t, ok := a.captureThumb(name, path); ok {
|
||||
if t, ok := a.captureThumbWithDriver(driverID, name, path); ok {
|
||||
return t, nil
|
||||
}
|
||||
}
|
||||
@@ -89,8 +105,13 @@ func (a *App) GetVMThumbnail(name string) (VMThumbnail, error) {
|
||||
|
||||
// FocusVMWindow brings a running VM's QEMU display window to the foreground,
|
||||
// restoring it first if minimized.
|
||||
func (a *App) FocusVMWindow(name string) error {
|
||||
vm, ok := a.polledVM(name)
|
||||
func (a *App) FocusVMWindow(name string) error { return a.FocusVMWindowWithDriver("", name) }
|
||||
func (a *App) FocusVMWindowWithDriver(driverID, name string) error {
|
||||
info, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
vm, ok := a.polledVMForDriver(info.DriverID, name)
|
||||
if !ok || vm.State != "running" || vm.PID == nil || *vm.PID <= 0 {
|
||||
return fmt.Errorf("VM %s is not running", name)
|
||||
}
|
||||
@@ -101,87 +122,55 @@ func (a *App) FocusVMWindow(name string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ToggleVMFullscreen switches the running VM's display between full screen and windowed mode.
|
||||
// ToggleVMFullscreen switches the running VM's display through its owning driver.
|
||||
func (a *App) ToggleVMFullscreen(name string) (bool, error) {
|
||||
return a.ToggleVMFullscreenWithDriver("", name)
|
||||
}
|
||||
func (a *App) ToggleVMFullscreenWithDriver(driverID, name string) (bool, error) {
|
||||
a.mu.Lock()
|
||||
preference := a.cfg.Locale
|
||||
a.mu.Unlock()
|
||||
loc := i18n.EffectiveLocale(preference)
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", i18n.Vars{"name": name}, err)
|
||||
}
|
||||
fullscreen, err := toggleVMFullscreen(context.Background(), name, loc, c, host.ToggleProcessWindowFullscreen)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("VM window full screen: %t", fullscreen))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return fullscreen, nil
|
||||
}
|
||||
|
||||
type fullscreenVMClient interface {
|
||||
Show(context.Context, string) (reims.VMDetail, error)
|
||||
List(context.Context) ([]reims.VMListItem, error)
|
||||
}
|
||||
|
||||
func findRunningVMPID(vms []reims.VMListItem, name string) (uint32, bool) {
|
||||
for _, vm := range vms {
|
||||
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
|
||||
return uint32(*vm.PID), true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func toggleVMFullscreen(ctx context.Context, name string, loc i18n.Locale, c fullscreenVMClient, toggleWindow func(uint32) (bool, error)) (bool, error) {
|
||||
vars := i18n.Vars{"name": name}
|
||||
beforeVMs, err := c.List(ctx)
|
||||
vm, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
|
||||
}
|
||||
pidBefore, ok := findRunningVMPID(beforeVMs, name)
|
||||
if !ok {
|
||||
if vm.State != "running" {
|
||||
return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil)
|
||||
}
|
||||
detail, err := c.Show(ctx, name)
|
||||
if err != nil {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
|
||||
}
|
||||
if detail.State != "running" {
|
||||
return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil)
|
||||
}
|
||||
if detail.Graphics == "vmware-svga" {
|
||||
if graphics, _ := vm.DriverData["graphics"].(string); graphics == "vmware-svga" {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_VMWARE_SVGA", "err.fullscreen_vmware_svga", vars, nil)
|
||||
}
|
||||
afterVMs, err := c.List(ctx)
|
||||
if err != nil {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
|
||||
}
|
||||
pidAfter, ok := findRunningVMPID(afterVMs, name)
|
||||
if !ok || pidAfter != pidBefore {
|
||||
listed, ok := a.polledVMForDriver(vm.DriverID, name)
|
||||
if !ok || listed.PID == nil || *listed.PID <= 0 {
|
||||
return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil)
|
||||
}
|
||||
fullscreen, err := toggleWindow(pidAfter)
|
||||
fullscreen, err := host.ToggleProcessWindowFullscreen(uint32(*listed.PID))
|
||||
if errors.Is(err, host.ErrDisplayWindowNotFound) {
|
||||
return false, i18n.NewCodedError(loc, "E_VM_WINDOW_NOT_FOUND", "err.vm_window_not_found", vars, err)
|
||||
}
|
||||
if err != nil {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
|
||||
}
|
||||
a.emitVMLogForDriver(vm.DriverID, name, fmt.Sprintf("VM window full screen: %t", fullscreen))
|
||||
a.emitLifecycleStateChanged()
|
||||
return fullscreen, nil
|
||||
}
|
||||
|
||||
// CopyVMScreenshot captures a full-resolution frame from a running VM over QMP
|
||||
// and writes it as a PNG/DIB image to the Windows clipboard.
|
||||
func (a *App) CopyVMScreenshot(name string) error {
|
||||
vm, ok := a.polledVM(name)
|
||||
func (a *App) CopyVMScreenshot(name string) error { return a.CopyVMScreenshotWithDriver("", name) }
|
||||
func (a *App) CopyVMScreenshotWithDriver(driverID, name string) error {
|
||||
info, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
vm, ok := a.polledVMForDriver(info.DriverID, name)
|
||||
if !ok || vm.State != "running" || vm.Dir == "" {
|
||||
return fmt.Errorf("VM %s is not running", name)
|
||||
}
|
||||
mu := vmThumbLock(name)
|
||||
mu := vmThumbLockForDriver(driverID, name)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
@@ -191,7 +180,7 @@ func (a *App) CopyVMScreenshot(name string) error {
|
||||
if err := os.MkdirAll(tmp, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
raw := filepath.Join(tmp, "screenshot-"+name)
|
||||
raw := filepath.Join(tmp, "screenshot-"+strings.TrimSuffix(filepath.Base(a.thumbPathForDriver(driverID, name)), ".jpg"))
|
||||
defer os.Remove(raw)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
@@ -211,18 +200,25 @@ func (a *App) CopyVMScreenshot(name string) error {
|
||||
if err := (&guesttools.OSClipboard{}).WritePNG(buf.Bytes()); err != nil {
|
||||
return fmt.Errorf("copy image to clipboard: %w", err)
|
||||
}
|
||||
a.emitLog(name, "Copied VM screenshot to clipboard")
|
||||
a.emitVMLogForDriver(driverID, name, "Copied VM screenshot to clipboard")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) captureThumb(name, path string) (VMThumbnail, bool) {
|
||||
return a.captureThumbWithDriver("", name, path)
|
||||
}
|
||||
func (a *App) captureThumbWithDriver(driverID, name, path string) (VMThumbnail, bool) {
|
||||
typing.mu.Lock()
|
||||
busy := typing.busy[name]
|
||||
busy := typing.busy[vmKeyForDriver(driverID, name)]
|
||||
typing.mu.Unlock()
|
||||
if busy {
|
||||
return VMThumbnail{}, false
|
||||
}
|
||||
vm, ok := a.polledVM(name)
|
||||
info, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return VMThumbnail{}, false
|
||||
}
|
||||
vm, ok := a.polledVMForDriver(info.DriverID, name)
|
||||
if !ok || vm.State != "running" || vm.Dir == "" {
|
||||
return VMThumbnail{}, false
|
||||
}
|
||||
@@ -238,7 +234,7 @@ func (a *App) captureThumb(name, path string) (VMThumbnail, bool) {
|
||||
if err := os.MkdirAll(tmp, 0o755); err != nil {
|
||||
return VMThumbnail{}, false
|
||||
}
|
||||
raw := filepath.Join(tmp, "screendump-"+name)
|
||||
raw := filepath.Join(tmp, "screendump-"+strings.TrimSuffix(filepath.Base(path), ".jpg"))
|
||||
defer os.Remove(raw)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
||||
|
||||
@@ -6,9 +6,9 @@ import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
)
|
||||
|
||||
func TestReleaseVMThumbnailRemovesLock(t *testing.T) {
|
||||
|
||||
+25
-20
@@ -82,16 +82,17 @@ func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool)
|
||||
return 0, errors.New("nothing to type")
|
||||
}
|
||||
|
||||
key := vmKey(name)
|
||||
typing.mu.Lock()
|
||||
if typing.busy[name] {
|
||||
if typing.busy[key] {
|
||||
typing.mu.Unlock()
|
||||
return 0, fmt.Errorf("%s is already being typed into", name)
|
||||
}
|
||||
typing.busy[name] = true
|
||||
typing.busy[key] = true
|
||||
typing.mu.Unlock()
|
||||
defer func() {
|
||||
typing.mu.Lock()
|
||||
delete(typing.busy, name)
|
||||
delete(typing.busy, key)
|
||||
typing.mu.Unlock()
|
||||
}()
|
||||
|
||||
@@ -132,12 +133,12 @@ func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool)
|
||||
if err == nil {
|
||||
n := utf8.RuneCountInString(text)
|
||||
if !fromRemoteIME {
|
||||
a.emitLog(name, fmt.Sprintf("Injected %d character(s) into %s via Guest Tools (%s) + Cmd+V.", n, name, mode))
|
||||
a.emitVMLog(name, fmt.Sprintf("Injected %d character(s) into %s via Guest Tools (%s) + Cmd+V.", n, name, mode))
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
if !errors.Is(err, guesttools.ErrGuestToolsNotConnected) {
|
||||
a.emitLog(name, fmt.Sprintf("Guest Tools text injection (%s) failed: %v", mode, err))
|
||||
a.emitVMLog(name, fmt.Sprintf("Guest Tools text injection (%s) failed: %v", mode, err))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -148,26 +149,26 @@ func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool)
|
||||
if errors.As(err, &ue) {
|
||||
if fromRemoteIME {
|
||||
typing.mu.Lock()
|
||||
last := typing.lastHintAt[name]
|
||||
last := typing.lastHintAt[key]
|
||||
shouldLog := time.Since(last) > 15*time.Second
|
||||
if shouldLog {
|
||||
typing.lastHintAt[name] = time.Now()
|
||||
typing.lastHintAt[key] = time.Now()
|
||||
}
|
||||
typing.mu.Unlock()
|
||||
if shouldLog {
|
||||
a.emitLog(name, "Remote IME Unicode text received, but Guest Tools is not connected in macOS yet (install Guest Tools to enable Chinese/Unicode remote input).")
|
||||
a.emitVMLog(name, "Remote IME Unicode text received, but Guest Tools is not connected in macOS yet (install Guest Tools to enable Chinese/Unicode remote input).")
|
||||
}
|
||||
} else {
|
||||
a.emitLog(name, "Paste as keystrokes refused: "+ue.Error())
|
||||
a.emitVMLog(name, "Paste as keystrokes refused: "+ue.Error())
|
||||
}
|
||||
return 0, fmt.Errorf("%w: %s", ErrNotTypeable, ue.Error())
|
||||
}
|
||||
if err != nil {
|
||||
a.emitLog(name, fmt.Sprintf("Paste as keystrokes stopped after %d keys: %v", n, err))
|
||||
a.emitVMLog(name, fmt.Sprintf("Paste as keystrokes stopped after %d keys: %v", n, err))
|
||||
return n, err
|
||||
}
|
||||
if !fromRemoteIME {
|
||||
a.emitLog(name, fmt.Sprintf("Typed %d keys into %s.", n, name))
|
||||
a.emitVMLog(name, fmt.Sprintf("Typed %d keys into %s.", n, name))
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
@@ -176,17 +177,21 @@ func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool)
|
||||
// or the reims-vgpu-window WM_CHAR bridge (/v1/host-text) onto a per-VM FIFO
|
||||
// worker so rapid IME bursts are delivered strictly in order without drops.
|
||||
func (a *App) injectRemoteText(vmName, vmDir, text string) {
|
||||
a.injectRemoteTextRef(vmKey(vmName), vmName, vmDir, text)
|
||||
}
|
||||
|
||||
func (a *App) injectRemoteTextRef(key, vmName, vmDir, text string) {
|
||||
if vmName == "" || text == "" {
|
||||
return
|
||||
}
|
||||
typing.mu.Lock()
|
||||
ch, ok := typing.remoteQueues[vmName]
|
||||
ch, ok := typing.remoteQueues[key]
|
||||
if !ok {
|
||||
ch = make(chan remoteTextItem, 32)
|
||||
typing.remoteQueues[vmName] = ch
|
||||
go a.runRemoteTextQueue(vmName, ch)
|
||||
typing.remoteQueues[key] = ch
|
||||
go a.runRemoteTextQueue(key, vmName, ch)
|
||||
}
|
||||
if typing.closing[vmName] {
|
||||
if typing.closing[key] {
|
||||
typing.mu.Unlock()
|
||||
return
|
||||
}
|
||||
@@ -201,7 +206,7 @@ func (a *App) injectRemoteText(vmName, vmDir, text string) {
|
||||
|
||||
func releaseVMTyping(vmName string) {
|
||||
typing.mu.Lock()
|
||||
names := []string{vmName}
|
||||
names := []string{vmKey(vmName)}
|
||||
if vmName == "" {
|
||||
names = make([]string, 0, len(typing.remoteQueues))
|
||||
for name := range typing.remoteQueues {
|
||||
@@ -220,12 +225,12 @@ func releaseVMTyping(vmName string) {
|
||||
typing.mu.Unlock()
|
||||
}
|
||||
|
||||
func (a *App) runRemoteTextQueue(vmName string, ch <-chan remoteTextItem) {
|
||||
func (a *App) runRemoteTextQueue(key, vmName string, ch <-chan remoteTextItem) {
|
||||
defer func() {
|
||||
typing.mu.Lock()
|
||||
delete(typing.remoteQueues, vmName)
|
||||
delete(typing.lastHintAt, vmName)
|
||||
delete(typing.closing, vmName)
|
||||
delete(typing.remoteQueues, key)
|
||||
delete(typing.lastHintAt, key)
|
||||
delete(typing.closing, key)
|
||||
typing.mu.Unlock()
|
||||
}()
|
||||
for item := range ch {
|
||||
|
||||
@@ -12,7 +12,7 @@ func TestRemoteTextWorkerExitsWithPendingTextOnClosedQueue(t *testing.T) {
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
new(App).runRemoteTextQueue("removed-test-vm", queue)
|
||||
new(App).runRemoteTextQueue(vmKey("removed-test-vm"), "removed-test-vm", queue)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
@@ -82,7 +82,7 @@ func (a *App) startUIHealthWatchdog(ctx context.Context) {
|
||||
if len(parts) == 0 {
|
||||
return
|
||||
}
|
||||
msg := reims.RedactText(strings.Join(parts, " | "))
|
||||
msg := host.RedactText(strings.Join(parts, " | "))
|
||||
a.emitLog("ui", "Frontend error: "+msg)
|
||||
a.appendUICrashLog(msg)
|
||||
})
|
||||
@@ -177,6 +177,11 @@ func (a *App) probeUIHealth(ctx context.Context, reason string) {
|
||||
}
|
||||
|
||||
func (a *App) appendUICrashLog(msg string) {
|
||||
// The message already went to the log panel; the file copy waits until a
|
||||
// data folder is chosen and writable (internal/dataroot).
|
||||
if !a.dataRootUsable() {
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
root := ""
|
||||
if a.cfg != nil {
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
//go:build windows
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/installguide"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/tray"
|
||||
)
|
||||
|
||||
@@ -24,32 +28,40 @@ func (a *App) confirmVMWindowClose(name string) {
|
||||
a.emitLog(name, "Could not locate the VM display window for close confirmation")
|
||||
return
|
||||
}
|
||||
loc, theme := a.guidePreferences()
|
||||
label := strings.TrimSpace(a.GetVMNote(name))
|
||||
if label == "" {
|
||||
label = name
|
||||
a.mu.Lock()
|
||||
loc := i18n.EffectiveLocale(a.cfg.Locale)
|
||||
theme := a.themeMode
|
||||
a.mu.Unlock()
|
||||
|
||||
ref := driver.NewVMRef("", name)
|
||||
canSuspend := false
|
||||
if vm, err := a.resolveVMInfo("", name); err == nil {
|
||||
ref = vm.Ref()
|
||||
canSuspend = slices.Contains(vm.Capabilities, driver.CapSuspend)
|
||||
}
|
||||
prep, err := a.prep(name)
|
||||
canSuspend := err == nil && prep.Runtime.Manifest.HasCapability("vm-suspend")
|
||||
choice, err := installguide.ConfirmVMClose(ctx, owner, label, loc, theme, canSuspend)
|
||||
label := strings.TrimSpace(a.GetVMNote(ref.Name))
|
||||
if label == "" {
|
||||
label = ref.Name
|
||||
}
|
||||
choice, err := host.ConfirmVMClose(ctx, owner, label, loc, theme, canSuspend)
|
||||
if err != nil {
|
||||
a.emitLog(name, err.Error())
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, err.Error())
|
||||
return
|
||||
}
|
||||
if choice == installguide.VMCloseCancel {
|
||||
if choice == host.VMCloseCancel {
|
||||
return
|
||||
}
|
||||
vms, err := a.listVMsInternal(ctx)
|
||||
if err != nil {
|
||||
a.emitLog(name, err.Error())
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, err.Error())
|
||||
return
|
||||
}
|
||||
if current, running := findRunningVMPID(vms, name); !running || current != uint32(pid) {
|
||||
if current, running := findRunningVMPID(vms, ref.Name); !running || current != uint32(pid) {
|
||||
return
|
||||
}
|
||||
if choice == installguide.VMCloseSuspend {
|
||||
a.trayVMAction(name, tray.ActSuspend)
|
||||
if choice == host.VMCloseSuspend {
|
||||
a.trayVMAction(ref.DriverID, ref.Name, tray.ActSuspend)
|
||||
} else {
|
||||
a.trayVMAction(name, tray.ActStop)
|
||||
a.trayVMAction(ref.DriverID, ref.Name, tray.ActStop)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package app
|
||||
|
||||
import "github.com/Nwflower/reims-go/internal/driver"
|
||||
|
||||
func vmInfoString(vm driver.VMInfo, key string) string {
|
||||
if vm.DriverData == nil {
|
||||
return ""
|
||||
}
|
||||
value, _ := vm.DriverData[key].(string)
|
||||
return value
|
||||
}
|
||||
|
||||
func vmInfoBool(vm driver.VMInfo, key string) bool {
|
||||
if vm.DriverData == nil {
|
||||
return false
|
||||
}
|
||||
value, _ := vm.DriverData[key].(bool)
|
||||
return value
|
||||
}
|
||||
+13
-13
@@ -10,7 +10,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"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/vmstart"
|
||||
@@ -49,7 +49,7 @@ func stopAllVMMonitors() {
|
||||
vmMonitors.mu.Unlock()
|
||||
}
|
||||
|
||||
func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Time) {
|
||||
func (a *App) startVMMonitor(name string, detail driver.VMInfo, startAt time.Time) {
|
||||
if detail.Directory == "" {
|
||||
stopVMMonitor(name)
|
||||
return
|
||||
@@ -108,7 +108,7 @@ func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Ti
|
||||
a.emitPluginLogLine(name, "serial", line)
|
||||
if key, msg := parseSerialMilestone(loc, line); msg != "" && !seenEvents[key] {
|
||||
seenEvents[key] = true
|
||||
a.emitLog(name, msg)
|
||||
a.emitVMLog(name, msg)
|
||||
}
|
||||
}
|
||||
for _, line := range qemu.read(qemuPath) {
|
||||
@@ -120,14 +120,14 @@ func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Ti
|
||||
if key != "" {
|
||||
seenEvents[key] = true
|
||||
}
|
||||
a.emitLog(name, msg)
|
||||
a.emitVMLog(name, msg)
|
||||
}
|
||||
}
|
||||
case <-hbTicker.C:
|
||||
loc := a.locale()
|
||||
pid, running := a.currentVMPID(ctx, name)
|
||||
if !running {
|
||||
a.emitLog(name, i18n.T(loc, "monitor.exited"))
|
||||
a.emitVMLog(name, i18n.T(loc, "monitor.exited"))
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
@@ -154,7 +154,7 @@ func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Ti
|
||||
}
|
||||
|
||||
elapsed := time.Since(startAt)
|
||||
inEarlyOrInstall := detail.HasInstaller || elapsed < 15*time.Minute
|
||||
inEarlyOrInstall := vmInfoBool(detail, "has_installer") || elapsed < 15*time.Minute
|
||||
if !inEarlyOrInstall {
|
||||
continue
|
||||
}
|
||||
@@ -167,11 +167,11 @@ func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Ti
|
||||
}
|
||||
|
||||
if msg := formatBootHeartbeat(loc, elapsed, diskNow, diskDelta, cpuPct); msg != "" {
|
||||
a.emitLog(name, msg)
|
||||
a.emitVMLog(name, msg)
|
||||
}
|
||||
if idleStreak >= 3 && !stallWarned {
|
||||
stallWarned = true
|
||||
a.emitLog(name, i18n.T(loc, "monitor.stall_warn"))
|
||||
a.emitVMLog(name, i18n.T(loc, "monitor.stall_warn"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -337,7 +337,7 @@ func fileSizeBytes(path string) int64 {
|
||||
return info.Size()
|
||||
}
|
||||
|
||||
func (a *App) emitStartSummary(name string, detail reims.VMDetail, rep host.Report, qmpAddr string) {
|
||||
func (a *App) emitStartSummary(name string, detail driver.VMInfo, rep host.Report, qmpAddr string) {
|
||||
a.mu.Lock()
|
||||
rawLoc := a.cfg.Locale
|
||||
rtCommit := a.cfg.ActiveRuntime
|
||||
@@ -348,7 +348,7 @@ func (a *App) emitStartSummary(name string, detail reims.VMDetail, rep host.Repo
|
||||
rtCommit = "auto"
|
||||
}
|
||||
irqMode := "default"
|
||||
lowExtra := strings.ToLower(detail.ExtraArgs)
|
||||
lowExtra := strings.ToLower(vmInfoString(detail, "extra_args"))
|
||||
switch {
|
||||
case strings.Contains(lowExtra, "kernel-irqchip=off"):
|
||||
irqMode = "off"
|
||||
@@ -360,13 +360,13 @@ func (a *App) emitStartSummary(name string, detail reims.VMDetail, rep host.Repo
|
||||
if qmpAddr != "" {
|
||||
coldStr = i18n.T(loc, "monitor.start.on")
|
||||
}
|
||||
a.emitLog(name, i18n.M(loc, "monitor.start.summary", i18n.Vars{
|
||||
a.emitVMLog(name, i18n.M(loc, "monitor.start.summary", i18n.Vars{
|
||||
"rt": rtCommit,
|
||||
"cpus": detail.CPUs,
|
||||
"mem": detail.Memory,
|
||||
"avail": rep.CommitAvailGB,
|
||||
"gfx": detail.Graphics,
|
||||
"disk": strings.ToUpper(detail.DiskController),
|
||||
"gfx": vmInfoString(detail, "graphics"),
|
||||
"disk": strings.ToUpper(vmInfoString(detail, "disk_controller")),
|
||||
"irq": irqMode,
|
||||
"pin": pinStr,
|
||||
"cold": coldStr,
|
||||
|
||||
@@ -8,8 +8,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
)
|
||||
|
||||
func TestLogTailDiscardsOversizeLinesAndResumes(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
)
|
||||
|
||||
func TestSameNamedVMMemoryStatesUseDriverQualifiedKeys(t *testing.T) {
|
||||
a := &App{
|
||||
transitions: map[string]string{}, pendingChanges: map[string][]PendingChange{},
|
||||
diskPaths: map[string]cachedDiskPath{}, procSamples: map[string]host.ProcessSample{},
|
||||
}
|
||||
aKey := vmKeyForDriver("test.driver.a", "shared")
|
||||
bKey := vmKeyForDriver("test.driver.b", "shared")
|
||||
if aKey == bKey {
|
||||
t.Fatal("same-named VMs share a key")
|
||||
}
|
||||
a.transitions[aKey] = "starting"
|
||||
a.pendingChanges[bKey] = []PendingChange{{Field: "memory"}}
|
||||
a.diskPaths[aKey] = cachedDiskPath{path: "a", at: time.Now()}
|
||||
a.procSamples[bKey] = host.ProcessSample{}
|
||||
if len(a.transitions) != 1 || a.transitions[bKey] != "" {
|
||||
t.Fatalf("transitions = %+v", a.transitions)
|
||||
}
|
||||
if len(a.pendingChanges[aKey]) != 0 || len(a.pendingChanges[bKey]) != 1 {
|
||||
t.Fatalf("pending = %+v", a.pendingChanges)
|
||||
}
|
||||
if len(a.diskPaths) != 1 || len(a.procSamples) != 1 {
|
||||
t.Fatal("driver-qualified cache keys collided")
|
||||
}
|
||||
a.cfg = &config.Config{DataRoot: t.TempDir()}
|
||||
if a.thumbPathForDriver("test.driver.a", "shared") == a.thumbPathForDriver("test.driver.b", "shared") {
|
||||
t.Fatal("same-named VMs share a thumbnail path")
|
||||
}
|
||||
if got := a.thumbPath("shared"); got != a.thumbPathForDriver("", "shared") {
|
||||
t.Fatal("default thumbnail path changed")
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
@@ -55,13 +54,13 @@ func (a *App) handleWindowArgs(w cli.WindowArgs, secondLaunch bool) {
|
||||
name := w.StartVM
|
||||
result := a.startResultPath(w.StartResult)
|
||||
if w.StartResult != "" && result == "" {
|
||||
a.emitLog(name, "Ignored a start result path outside the Reims-Go temp folder: "+w.StartResult)
|
||||
a.emitVMLog(name, "Ignored a start result path outside the Reims-Go temp folder: "+w.StartResult)
|
||||
}
|
||||
a.emitLog(name, "Start requested from the command line")
|
||||
a.emitVMLog(name, "Start requested from the command line")
|
||||
go func() {
|
||||
capture := a.captureLogs(name)
|
||||
err := a.StartVM(name)
|
||||
lines := a.releaseLogs(name, capture)
|
||||
capture := a.captureLogs(vmKey(name))
|
||||
err := a.startHandedVM(w.StartDriver, name)
|
||||
lines := a.releaseLogs(vmKey(name), capture)
|
||||
if err != nil && len(lines) > 0 {
|
||||
// StartVM's own error is often just "exit status 1"; the reason is
|
||||
// in what it logged. The command line has no log panel to look at.
|
||||
@@ -69,21 +68,14 @@ func (a *App) handleWindowArgs(w cli.WindowArgs, secondLaunch bool) {
|
||||
}
|
||||
if result != "" {
|
||||
if werr := cli.WriteStartResult(result, err); werr != nil {
|
||||
a.emitLog(name, "Could not report the start result to the command line: "+werr.Error())
|
||||
a.emitVMLog(name, "Could not report the start result to the command line: "+werr.Error())
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func vmCloseRequestEnv(name string) []string {
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return []string{
|
||||
"REIMS_GO_VM_CLOSE_EXE=" + executable,
|
||||
"REIMS_GO_VM_CLOSE_NAME=" + name,
|
||||
}
|
||||
func (a *App) startHandedVM(driverID, name string) error {
|
||||
return a.StartVMWithDriver(driverID, name)
|
||||
}
|
||||
|
||||
// logCapture keeps the last few log lines one source emits while it is
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
// Package archtest holds repository-wide architecture checks. It has no
|
||||
// runtime code; see the tests.
|
||||
package archtest
|
||||
@@ -0,0 +1,236 @@
|
||||
package archtest
|
||||
|
||||
import (
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const macosImportPrefix = "github.com/Nwflower/reims-go/internal/macos"
|
||||
|
||||
// macosImporter is a package outside internal/macos that may still import
|
||||
// macOS code: debt to pay down before macOS leaves this repository.
|
||||
type macosImporter struct {
|
||||
src, test bool // which of its files may import internal/macos
|
||||
why string
|
||||
}
|
||||
|
||||
// macosImporters is the ratchet. The test fails when a package not listed
|
||||
// here starts importing internal/macos, and when a listed package (or its
|
||||
// source or test files) stops, so the list can only shrink.
|
||||
var macosImporters = map[string]macosImporter{
|
||||
"internal/app": {test: true, why: "GUI composition root tests may exercise native macOS flows"},
|
||||
"internal/datamigrate": {src: true, test: true, why: "data layout v2 invokes and verifies the macOS-owned state and ledger migration"},
|
||||
"internal/plugin/builtin": {src: true, why: "host Guest Tools bridge still uses reims argument helpers; guest registration moved to internal/macos/guest"},
|
||||
"internal/guesttools": {src: true, test: true, why: "mixed: host transport and clipboard next to the macOS guest agent image"},
|
||||
"internal/plugin": {test: true, why: "sidecar manager test builds a reims-ctl stand-in"},
|
||||
}
|
||||
|
||||
// macosSourceFiles is the file-scoped native macOS boundary. plugins_flow.go
|
||||
// and cli/plugin.go are the composition files; every other entry is a native
|
||||
// macOS page or flow mounted through that registration. New files may not be added.
|
||||
var macosSourceFiles = map[string][]string{
|
||||
"internal/app": {
|
||||
"internal/app/create_flow.go",
|
||||
"internal/app/extras_flow.go",
|
||||
"internal/app/guesttools_flow.go",
|
||||
"internal/app/install_flow.go",
|
||||
"internal/app/install_guide.go",
|
||||
"internal/app/installer_bindings.go",
|
||||
"internal/app/installer_coordinator.go",
|
||||
"internal/app/macos_client.go",
|
||||
"internal/app/macos_detail.go",
|
||||
"internal/app/macos_lifecycle_native.go",
|
||||
"internal/app/macos_settings.go",
|
||||
"internal/app/macos_window.go",
|
||||
"internal/app/opencore_flow.go",
|
||||
"internal/app/plugins_flow.go",
|
||||
},
|
||||
"internal/cli": {
|
||||
"internal/cli/installer.go",
|
||||
"internal/cli/macos_native.go",
|
||||
"internal/cli/plugin.go",
|
||||
},
|
||||
}
|
||||
|
||||
func TestMacOSBoundary(t *testing.T) {
|
||||
root, err := filepath.Abs(filepath.Join("..", ".."))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
type use struct{ src, test []string }
|
||||
found := map[string]*use{}
|
||||
|
||||
skipDirs := map[string]bool{".git": true, ".debug": true, "build": true, "frontend": true, "node_modules": true}
|
||||
err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rel, _ := filepath.Rel(root, path)
|
||||
rel = filepath.ToSlash(rel)
|
||||
if d.IsDir() {
|
||||
if skipDirs[d.Name()] || rel == "internal/macos" {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !strings.HasSuffix(path, ".go") {
|
||||
return nil
|
||||
}
|
||||
f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, imp := range f.Imports {
|
||||
p, _ := strconv.Unquote(imp.Path.Value)
|
||||
if p != macosImportPrefix && !strings.HasPrefix(p, macosImportPrefix+"/") {
|
||||
continue
|
||||
}
|
||||
dir := filepath.ToSlash(filepath.Dir(rel))
|
||||
u := found[dir]
|
||||
if u == nil {
|
||||
u = &use{}
|
||||
found[dir] = u
|
||||
}
|
||||
if strings.HasSuffix(path, "_test.go") {
|
||||
u.test = append(u.test, rel)
|
||||
} else {
|
||||
u.src = append(u.src, rel)
|
||||
}
|
||||
break
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var problems []string
|
||||
for dir, u := range found {
|
||||
if files, scoped := macosSourceFiles[dir]; scoped {
|
||||
allowed := make(map[string]bool, len(files))
|
||||
for _, file := range files {
|
||||
allowed[file] = true
|
||||
}
|
||||
for _, file := range u.src {
|
||||
if !allowed[file] {
|
||||
problems = append(problems, "host code imports internal/macos outside the native file list: "+file)
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
allowed := macosImporters[dir]
|
||||
if len(u.src) > 0 && !allowed.src {
|
||||
problems = append(problems, "host code imports internal/macos (go through the driver layer or a host service instead): "+strings.Join(u.src, ", "))
|
||||
}
|
||||
if len(u.test) > 0 && !allowed.test {
|
||||
problems = append(problems, "host tests import internal/macos: "+strings.Join(u.test, ", "))
|
||||
}
|
||||
}
|
||||
for dir, files := range macosSourceFiles {
|
||||
u := found[dir]
|
||||
present := map[string]bool{}
|
||||
if u != nil {
|
||||
for _, file := range u.src {
|
||||
present[file] = true
|
||||
}
|
||||
}
|
||||
for _, file := range files {
|
||||
if !present[file] {
|
||||
problems = append(problems, file+" no longer imports internal/macos: remove it from macosSourceFiles")
|
||||
}
|
||||
}
|
||||
}
|
||||
for dir, allowed := range macosImporters {
|
||||
u := found[dir]
|
||||
if allowed.src && (u == nil || len(u.src) == 0) {
|
||||
problems = append(problems, dir+" no longer imports internal/macos from source files: set src to false (or drop the entry) in macosImporters")
|
||||
}
|
||||
if allowed.test && (u == nil || len(u.test) == 0) {
|
||||
problems = append(problems, dir+" no longer imports internal/macos from tests: set test to false (or drop the entry) in macosImporters")
|
||||
}
|
||||
}
|
||||
sort.Strings(problems)
|
||||
for _, p := range problems {
|
||||
t.Error(p)
|
||||
}
|
||||
}
|
||||
|
||||
// The ratchet only means something if internal/macos exists where the test
|
||||
// looks; guard against the walk silently finding nothing after a move.
|
||||
func TestMacOSBoundaryRootExists(t *testing.T) {
|
||||
if st, err := os.Stat(filepath.Join("..", "macos")); err != nil || !st.IsDir() {
|
||||
t.Fatalf("internal/macos not found next to internal/archtest: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// macosHostImports is the reverse ratchet: dependencies of internal/macos on
|
||||
// private host packages. External repositories cannot import these, so the
|
||||
// list must shrink to zero before macOS becomes a separate Go module.
|
||||
var macosHostImports = map[string]string{
|
||||
"config": "configuration paths and persisted host settings",
|
||||
"driver": "public driver contracts not yet moved to pkg",
|
||||
"filelock": "shared host file locking",
|
||||
"host": "host inspection and process services",
|
||||
"i18n": "host localization and coded errors",
|
||||
"netproxy": "host HTTP proxy resolution",
|
||||
"plugin": "plugin manifests, hooks and ledger contracts",
|
||||
"plugin/builtin": "built-in callback wiring during the transition",
|
||||
"qmp": "host QMP helpers",
|
||||
"runtime": "host runtime kinds and child process environment",
|
||||
"version": "host application version",
|
||||
"vmstart": "mixed host/macOS start preparation pending step 2",
|
||||
}
|
||||
|
||||
func TestMacOSDoesNotGainPrivateHostDependencies(t *testing.T) {
|
||||
root, err := filepath.Abs(filepath.Join("..", "macos"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := map[string][]string{}
|
||||
err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.IsDir() || !strings.HasSuffix(path, ".go") {
|
||||
return nil
|
||||
}
|
||||
f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, imp := range f.Imports {
|
||||
p, _ := strconv.Unquote(imp.Path.Value)
|
||||
const prefix = "github.com/Nwflower/reims-go/internal/"
|
||||
if !strings.HasPrefix(p, prefix) {
|
||||
continue
|
||||
}
|
||||
name := strings.TrimPrefix(p, prefix)
|
||||
if strings.HasPrefix(name, "macos") {
|
||||
continue
|
||||
}
|
||||
rel, _ := filepath.Rel(root, path)
|
||||
found[name] = append(found[name], filepath.ToSlash(rel))
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for name, files := range found {
|
||||
if _, ok := macosHostImports[name]; !ok {
|
||||
t.Errorf("internal/macos gained private host dependency internal/%s (%v)", name, files)
|
||||
}
|
||||
}
|
||||
for name := range macosHostImports {
|
||||
if len(found[name]) == 0 {
|
||||
t.Errorf("internal/macos no longer imports internal/%s; remove it from macosHostImports", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
+122
-207
@@ -12,18 +12,14 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/datamigrate"
|
||||
"github.com/Nwflower/reims-go/internal/dataroot"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/opencore"
|
||||
"github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
// Package cli is reims-go's command-line mode. The single reims-go.exe opens
|
||||
@@ -32,7 +28,7 @@ import (
|
||||
|
||||
// Main runs one command and returns the process exit code.
|
||||
func Main(args []string) int {
|
||||
i18n.SetDetailRedactor(reims.RedactText)
|
||||
i18n.SetDetailRedactor(host.RedactText)
|
||||
loc, err := run(args)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error: %s\n", i18n.FormatCLIError(loc, err))
|
||||
@@ -70,10 +66,8 @@ func run(args []string) (i18n.Locale, error) {
|
||||
if *dataRootFlag != "" {
|
||||
cfg.DataRoot = *dataRootFlag
|
||||
}
|
||||
// Same data-folder upgrade the GUI runs on startup.
|
||||
if _, err := datamigrate.Run(cfg.DataRoot, version.Version); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "warning:", err)
|
||||
}
|
||||
// Same check and upgrade the GUI runs on startup (internal/dataroot).
|
||||
root := dataroot.Open(cfg.DataRoot, version.Version)
|
||||
// Load enabled static language packs from <DataRoot>/plugins before resolving
|
||||
// effective locale so "auto" and custom --lang tags (e.g. ja-JP, zh-TW) work in CLI.
|
||||
plugin.LoadStaticLocalePacks(cfg.DataRoot)
|
||||
@@ -89,6 +83,11 @@ func run(args []string) (i18n.Locale, error) {
|
||||
printUsage(loc)
|
||||
return loc, nil
|
||||
}
|
||||
// A folder open read-only (written by a newer release, damaged version
|
||||
// record, failed upgrade) only serves commands that never write to it.
|
||||
if root.ReadOnly && !readOnlySafeCommand(rest[0]) {
|
||||
return loc, dataroot.Error(loc, root)
|
||||
}
|
||||
|
||||
switch rest[0] {
|
||||
case "doctor":
|
||||
@@ -375,16 +374,17 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("usage: reims-go vm <list|create|set|start|stop|suspend|resume|discard-suspend|eject|type>")
|
||||
}
|
||||
prep, err := vmstart.New(*cfg, func(line string) { fmt.Fprintln(os.Stderr, line) })
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client, active := prep.Client, &prep.Runtime
|
||||
ctx := context.Background()
|
||||
|
||||
switch args[0] {
|
||||
case "list":
|
||||
vms, err := client.ListRaw(ctx)
|
||||
mgr, router, err := openCLIPluginManager(cfg, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer mgr.Close()
|
||||
svc := lifecycle.New(mgr.Registry(), router, nil)
|
||||
vms, err := svc.List(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -392,13 +392,6 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
|
||||
fmt.Println(i18n.T(loc, "vm.empty"))
|
||||
return nil
|
||||
}
|
||||
for i := range vms {
|
||||
if st, _ := vms[i]["state"].(string); st == "stopped" {
|
||||
if dir, _ := vms[i]["dir"].(string); reims.HasSuspendState(dir) {
|
||||
vms[i]["state"] = "suspended"
|
||||
}
|
||||
}
|
||||
}
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
return enc.Encode(vms)
|
||||
@@ -413,7 +406,7 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
|
||||
gpu := fs.String("gpu", "auto", "GPU selector or Vulkan ICD JSON path")
|
||||
capture := fs.Bool("capture", false, "Capture keyboard and mouse on window click")
|
||||
logs := fs.Bool("logs", true, "Keep graphics and serial logs")
|
||||
guestLang := fs.String("guest-lang", opencore.DefaultGuestLang(loc), "macOS boot/recovery language prev-lang:kbd (e.g. zh-Hans:0, en-US:0)")
|
||||
guestLang := fs.String("guest-lang", defaultMacOSGuestLang(loc), "macOS boot/recovery language prev-lang:kbd (e.g. zh-Hans:0, en-US:0)")
|
||||
start := fs.Bool("start", false, "Start VM immediately after creation")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return err
|
||||
@@ -450,240 +443,162 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
|
||||
return err
|
||||
}
|
||||
if *start {
|
||||
return drv.Start(ctx, name, os.Stdout, os.Stderr)
|
||||
svc := lifecycle.New(mgr.Registry(), router, nil)
|
||||
_, err := svc.Start(ctx, driver.NewVMRef(drv.ID(), name), os.Stdout, os.Stderr)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
startAfterCreate := *start
|
||||
opts := reims.CreateOpts{
|
||||
Name: name,
|
||||
Dir: *dir,
|
||||
MacOS: *macos,
|
||||
CPUs: *cpus,
|
||||
Memory: *mem,
|
||||
DiskSize: *diskSize,
|
||||
GPU: *gpu,
|
||||
Capture: capture,
|
||||
Logs: logs,
|
||||
GuestLang: strings.TrimSpace(*guestLang),
|
||||
Start: false,
|
||||
}
|
||||
existingVMs, _ := client.List(ctx)
|
||||
if removed, rerr := reims.CleanAbortedCreateDir(cfg.XDGDataDir(), opts, existingVMs); rerr == nil && removed != "" {
|
||||
fmt.Fprintf(os.Stderr, "Removed unfinished directory from earlier interrupted create: %s\n", removed)
|
||||
}
|
||||
if installer.ShouldPrefetchOcBinaryData(active.Manifest.UtilCommit, active.Manifest.UtilVersion) {
|
||||
if err := installer.EnsureCachedAsset(ctx, cfg.XDGCacheDir(), installer.OcBinaryDataAsset, nil, nil); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "OpenCore resource pre-fetch skipped (reims-ctl will retry): %v\n", err)
|
||||
}
|
||||
}
|
||||
if err := client.Create(ctx, opts, os.Stdout, os.Stderr); err != nil {
|
||||
return err
|
||||
}
|
||||
if postSet, ok := reims.PostCreateSetOpts(opts); ok {
|
||||
if serr := client.Set(ctx, postSet, os.Stdout, os.Stderr); serr != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not apply post-create defaults: %v\n", serr)
|
||||
}
|
||||
}
|
||||
if opts.GuestLang != "" {
|
||||
vmDir := opts.Dir
|
||||
if d, serr := client.Show(ctx, name); serr == nil && d.Directory != "" {
|
||||
vmDir = d.Directory
|
||||
} else if vmDir == "" {
|
||||
vmDir = filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms", name)
|
||||
}
|
||||
if lerr := prep.ApplyGuestLang(ctx, vmDir, opts.GuestLang, false); lerr != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not apply macOS language (%s): %v\n", opts.GuestLang, lerr)
|
||||
}
|
||||
}
|
||||
if startAfterCreate {
|
||||
if err := startVM(ctx, cfg, prep, name, viaWindow); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
fmt.Println("\n" + i18n.T(loc, "vm.install_guide.title"))
|
||||
fmt.Println(i18n.T(loc, "vm.install_guide.step1"))
|
||||
fmt.Println(i18n.T(loc, "vm.install_guide.step2"))
|
||||
fmt.Println(i18n.T(loc, "vm.install_guide.step3", name))
|
||||
return nil
|
||||
return createMacOSVM(ctx, cfg, loc, macOSCreateOptions{Name: name, Dir: *dir, MacOS: *macos, CPUs: *cpus, Memory: *mem, DiskSize: *diskSize, GPU: *gpu, Capture: *capture, Logs: *logs, GuestLang: *guestLang}, *start, viaWindow)
|
||||
case "set":
|
||||
fs := flag.NewFlagSet("vm set", flag.ContinueOnError)
|
||||
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
|
||||
cpus := fs.Int("cpus", 0, "vCPU count")
|
||||
mem := fs.String("memory", "", "RAM size")
|
||||
gpu := fs.String("gpu", "", "GPU selector or Vulkan ICD JSON")
|
||||
res := fs.String("resolution", "", "Window resolution WIDTHxHEIGHT")
|
||||
audioBackend := fs.String("audio-backend", "", "Audio backend (auto, dsound, none, wav)")
|
||||
guestLang := fs.String("guest-lang", "", "macOS boot/recovery language prev-lang:kbd (e.g. zh-Hans:0, en-US:0)")
|
||||
guestLang := fs.String("guest-lang", "", "macOS boot/recovery language prev-lang:kbd")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
if fs.NArg() < 1 {
|
||||
return fmt.Errorf("usage: reims-go vm set [flags] <name>")
|
||||
return fmt.Errorf("usage: reims-go vm set [--driver <id>] [flags] <name>")
|
||||
}
|
||||
setOpts := reims.SetOpts{
|
||||
Name: fs.Arg(0),
|
||||
CPUs: *cpus,
|
||||
Memory: *mem,
|
||||
GPU: *gpu,
|
||||
Resolution: *res,
|
||||
AudioBackend: strings.TrimSpace(*audioBackend),
|
||||
GuestLang: strings.TrimSpace(*guestLang),
|
||||
changes := map[string]any{}
|
||||
if *cpus != 0 {
|
||||
changes["cpus"] = *cpus
|
||||
}
|
||||
d, release, err := vmstart.LockVM(ctx, client, setOpts.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
if *mem != "" {
|
||||
changes["memory"] = *mem
|
||||
}
|
||||
defer release()
|
||||
if d.State == "stopped" && reims.HasSuspendState(d.Directory) {
|
||||
return i18n.NewCodedError(loc, "E_SET_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": setOpts.Name}, nil)
|
||||
if *gpu != "" {
|
||||
changes["gpu"] = *gpu
|
||||
}
|
||||
if reims.HasCtlSetChanges(setOpts) {
|
||||
if err := client.Set(ctx, setOpts, os.Stdout, os.Stderr); err != nil {
|
||||
return err
|
||||
}
|
||||
if *res != "" {
|
||||
changes["resolution"] = *res
|
||||
}
|
||||
if setOpts.GuestLang != "" {
|
||||
d, err := client.Show(ctx, setOpts.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := prep.ApplyGuestLang(ctx, d.Directory, setOpts.GuestLang, d.State == "running"); err != nil {
|
||||
return err
|
||||
}
|
||||
if *audioBackend != "" {
|
||||
changes["audio_backend"] = *audioBackend
|
||||
}
|
||||
return nil
|
||||
if *guestLang != "" {
|
||||
changes["guest_lang"] = *guestLang
|
||||
}
|
||||
return setVM(ctx, cfg, *driverID, fs.Arg(0), changes)
|
||||
case "start":
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm start <name>")
|
||||
fs := flag.NewFlagSet("vm start", flag.ContinueOnError)
|
||||
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
return startVM(ctx, cfg, prep, args[1], viaWindow)
|
||||
if fs.NArg() < 1 {
|
||||
return fmt.Errorf("usage: reims-go vm start [--driver <id>] <name>")
|
||||
}
|
||||
return startVMWithDriver(ctx, cfg, *driverID, fs.Arg(0), viaWindow)
|
||||
case "stop":
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm stop <name>")
|
||||
}
|
||||
release, err := vmstart.LockVMForStop(ctx, client, args[1], false)
|
||||
if err != nil {
|
||||
fs := flag.NewFlagSet("vm stop", flag.ContinueOnError)
|
||||
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
return client.Stop(ctx, args[1], os.Stdout, os.Stderr)
|
||||
if fs.NArg() < 1 {
|
||||
return fmt.Errorf("usage: reims-go vm stop [--driver <id>] <name>")
|
||||
}
|
||||
return stopVM(ctx, cfg, *driverID, fs.Arg(0), false)
|
||||
case "suspend":
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm suspend <name>")
|
||||
fs := flag.NewFlagSet("vm suspend", flag.ContinueOnError)
|
||||
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
return suspendVM(ctx, cfg, prep, args[1])
|
||||
if fs.NArg() < 1 {
|
||||
return fmt.Errorf("usage: reims-go vm suspend [--driver <id>] <name>")
|
||||
}
|
||||
return suspendVM(ctx, cfg, *driverID, fs.Arg(0))
|
||||
case "resume":
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm resume <name>")
|
||||
fs := flag.NewFlagSet("vm resume", flag.ContinueOnError)
|
||||
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
return resumeVM(ctx, cfg, prep, args[1])
|
||||
if fs.NArg() < 1 {
|
||||
return fmt.Errorf("usage: reims-go vm resume [--driver <id>] <name>")
|
||||
}
|
||||
return resumeVM(ctx, cfg, *driverID, fs.Arg(0))
|
||||
case "discard-suspend":
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm discard-suspend <name>")
|
||||
fs := flag.NewFlagSet("vm discard-suspend", flag.ContinueOnError)
|
||||
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
return discardSuspendVM(ctx, cfg, prep, args[1])
|
||||
if fs.NArg() < 1 {
|
||||
return fmt.Errorf("usage: reims-go vm discard-suspend [--driver <id>] <name>")
|
||||
}
|
||||
return discardSuspendVM(ctx, cfg, *driverID, fs.Arg(0))
|
||||
case "delete":
|
||||
fs := flag.NewFlagSet("vm delete", flag.ContinueOnError)
|
||||
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
|
||||
keepFiles := fs.Bool("keep-files", false, "Delete registration but keep VM files")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
if fs.NArg() < 1 {
|
||||
return fmt.Errorf("usage: reims-go vm delete [--driver <id>] [--keep-files] <name>")
|
||||
}
|
||||
return deleteVM(ctx, cfg, *driverID, fs.Arg(0), *keepFiles)
|
||||
case "eject":
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm eject <name>")
|
||||
}
|
||||
d, release, err := vmstart.LockVM(ctx, client, args[1])
|
||||
if err != nil {
|
||||
fs := flag.NewFlagSet("vm eject", flag.ContinueOnError)
|
||||
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
if d.State == "stopped" && reims.HasSuspendState(d.Directory) {
|
||||
return i18n.NewCodedError(loc, "E_VM_EJECT_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": args[1]}, nil)
|
||||
if fs.NArg() < 1 {
|
||||
return fmt.Errorf("usage: reims-go vm eject [--driver <id>] <name>")
|
||||
}
|
||||
return client.Eject(ctx, args[1], os.Stdout, os.Stderr)
|
||||
return actionVM(ctx, cfg, *driverID, fs.Arg(0), "eject", nil)
|
||||
case "type":
|
||||
// Paste as keystrokes: the text argument, else stdin.
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm type <name> [text] (no text: read stdin)")
|
||||
}
|
||||
text := strings.Join(args[2:], " ")
|
||||
if len(args) < 3 {
|
||||
b, err := io.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
text = strings.TrimRight(string(b), "\r\n")
|
||||
}
|
||||
d, err := client.Show(ctx, args[1])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := qmp.TypeIntoVM(ctx, d.Directory, text, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(i18n.T(loc, "vm.typed", n))
|
||||
return nil
|
||||
return typeMacOSVM(ctx, cfg, loc, args)
|
||||
case "resize":
|
||||
if len(args) < 3 {
|
||||
return fmt.Errorf("usage: reims-go vm resize <name> <size> (e.g. 256G or +64G)")
|
||||
fs := flag.NewFlagSet("vm resize", flag.ContinueOnError)
|
||||
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
d, release, err := vmstart.LockVM(ctx, client, args[1])
|
||||
if fs.NArg() < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm resize [--driver <id>] <name> <size> (e.g. 256G or +64G)")
|
||||
}
|
||||
res, err := resizeVM(ctx, cfg, *driverID, fs.Arg(0), fs.Arg(1))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
if d.State == "running" {
|
||||
return fmt.Errorf("%s", i18n.T(loc, "vm.resize.stop_first", args[1]))
|
||||
}
|
||||
if reims.HasSuspendState(d.Directory) {
|
||||
return i18n.NewCodedError(loc, "E_RESIZE_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": args[1]}, nil)
|
||||
}
|
||||
diskPath := resolveCLIDiskPath(d)
|
||||
res, err := reims.ResizeDisk(ctx, active.QemuImgPath(), client.Env, diskPath, args[2], os.Stdout, os.Stderr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(i18n.T(loc, "vm.resize.done",
|
||||
args[1], float64(res.OldVirtualBytes)/float64(1<<30), float64(res.NewVirtualBytes)/float64(1<<30), res.GuestExpandCmd))
|
||||
fmt.Println(i18n.T(loc, "vm.resize.done", fs.Arg(0), float64(res.OldVirtualBytes)/float64(1<<30), float64(res.NewVirtualBytes)/float64(1<<30), res.GuestExpandCmd))
|
||||
return nil
|
||||
case "compact":
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm compact <name>")
|
||||
fs := flag.NewFlagSet("vm compact", flag.ContinueOnError)
|
||||
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
d, release, err := vmstart.LockVM(ctx, client, args[1])
|
||||
if fs.NArg() < 1 {
|
||||
return fmt.Errorf("usage: reims-go vm compact [--driver <id>] <name>")
|
||||
}
|
||||
res, err := compactVM(ctx, cfg, *driverID, fs.Arg(0))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
if d.State == "running" {
|
||||
return fmt.Errorf("%s", i18n.T(loc, "vm.compact.stop_first", args[1]))
|
||||
}
|
||||
if reims.HasSuspendState(d.Directory) {
|
||||
return i18n.NewCodedError(loc, "E_COMPACT_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": args[1]}, nil)
|
||||
}
|
||||
diskPath := resolveCLIDiskPath(d)
|
||||
res, err := reims.CompactDisk(ctx, active.QemuImgPath(), client.Env, diskPath, os.Stdout, os.Stderr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(i18n.T(loc, "vm.compact.done",
|
||||
args[1], float64(res.BeforeBytes)/float64(1<<30), float64(res.AfterBytes)/float64(1<<30), float64(res.ReclaimedBytes)/float64(1<<30)))
|
||||
fmt.Println(i18n.T(loc, "vm.compact.done", fs.Arg(0), float64(res.BeforeBytes)/float64(1<<30), float64(res.AfterBytes)/float64(1<<30), float64(res.ReclaimedBytes)/float64(1<<30)))
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("unknown vm subcommand %q", strings.Join(args, " "))
|
||||
}
|
||||
}
|
||||
|
||||
func resolveCLIDiskPath(d reims.VMDetail) string {
|
||||
raw := strings.TrimSpace(d.Disk)
|
||||
if idx := strings.Index(raw, " ("); idx > 0 {
|
||||
raw = strings.TrimSpace(raw[:idx])
|
||||
// readOnlySafeCommand reports whether cmd runs without writing to the data
|
||||
// folder, so it may run while the folder is open read-only.
|
||||
func readOnlySafeCommand(cmd string) bool {
|
||||
switch cmd {
|
||||
case "version", "-v", "--version", "help", "-h", "--help", "doctor":
|
||||
return true
|
||||
}
|
||||
if raw != "" {
|
||||
if filepath.IsAbs(raw) {
|
||||
return raw
|
||||
}
|
||||
if d.Directory != "" {
|
||||
return filepath.Join(d.Directory, raw)
|
||||
}
|
||||
}
|
||||
if d.Directory != "" {
|
||||
return filepath.Join(d.Directory, "disk.qcow2")
|
||||
}
|
||||
return ""
|
||||
return false
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/opencore"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
)
|
||||
|
||||
func defaultMacOSGuestLang(loc i18n.Locale) string { return opencore.DefaultGuestLang(loc) }
|
||||
|
||||
// macOSCreateOptions is the CLI-neutral input to the native macOS create flow.
|
||||
type macOSCreateOptions struct {
|
||||
Name, Dir, MacOS, Memory, DiskSize, GPU, GuestLang string
|
||||
CPUs int
|
||||
Capture, Logs bool
|
||||
}
|
||||
|
||||
func createMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, in macOSCreateOptions, startAfterCreate, viaWindow bool) error {
|
||||
prep, err := startprep.New(*cfg, func(line string) { fmt.Fprintln(os.Stderr, line) })
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client := prep.Client
|
||||
opts := reims.CreateOpts{Name: in.Name, Dir: in.Dir, MacOS: in.MacOS, CPUs: in.CPUs, Memory: in.Memory, DiskSize: in.DiskSize, GPU: in.GPU, Capture: &in.Capture, Logs: &in.Logs, GuestLang: strings.TrimSpace(in.GuestLang), Start: false}
|
||||
existingVMs, _ := client.List(ctx)
|
||||
if removed, rerr := reims.CleanAbortedCreateDir(cfg.XDGDataDir(), opts, existingVMs); rerr == nil && removed != "" {
|
||||
fmt.Fprintf(os.Stderr, "Removed unfinished directory from earlier interrupted create: %s\n", removed)
|
||||
}
|
||||
if installer.ShouldPrefetchOcBinaryData(prep.Runtime.Manifest.UtilCommit, prep.Runtime.Manifest.UtilVersion) {
|
||||
if err := installer.EnsureCachedAsset(ctx, cfg.XDGCacheDir(), installer.OcBinaryDataAsset, nil, nil); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "OpenCore resource pre-fetch skipped (reims-ctl will retry): %v\n", err)
|
||||
}
|
||||
}
|
||||
if err := client.Create(ctx, opts, os.Stdout, os.Stderr); err != nil {
|
||||
return err
|
||||
}
|
||||
createdDir := strings.TrimSpace(opts.Dir)
|
||||
if det, err := client.Show(ctx, opts.Name); err == nil && det.Directory != "" {
|
||||
createdDir = det.Directory
|
||||
}
|
||||
if createdDir == "" {
|
||||
createdDir = filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms", opts.Name)
|
||||
}
|
||||
if err := driver.WriteOwnerDriver(createdDir, driver.BuiltinReimsMacOSDriverID); err != nil {
|
||||
return err
|
||||
}
|
||||
if postSet, ok := reims.PostCreateSetOpts(opts); ok {
|
||||
if err := client.Set(ctx, postSet, os.Stdout, os.Stderr); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not apply post-create defaults: %v\n", err)
|
||||
}
|
||||
}
|
||||
if opts.GuestLang != "" {
|
||||
vmDir := opts.Dir
|
||||
if det, err := client.Show(ctx, in.Name); err == nil && det.Directory != "" {
|
||||
vmDir = det.Directory
|
||||
} else if vmDir == "" {
|
||||
vmDir = filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms", in.Name)
|
||||
}
|
||||
if err := prep.ApplyGuestLang(ctx, vmDir, opts.GuestLang, false); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not apply macOS language (%s): %v\n", opts.GuestLang, err)
|
||||
}
|
||||
}
|
||||
if startAfterCreate {
|
||||
if err := startVM(ctx, cfg, in.Name, viaWindow); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
fmt.Println("\n" + i18n.T(loc, "vm.install_guide.title"))
|
||||
fmt.Println(i18n.T(loc, "vm.install_guide.step1"))
|
||||
fmt.Println(i18n.T(loc, "vm.install_guide.step2"))
|
||||
fmt.Println(i18n.T(loc, "vm.install_guide.step3", in.Name))
|
||||
return nil
|
||||
}
|
||||
|
||||
func typeMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm type <name> [text] (no text: read stdin)")
|
||||
}
|
||||
prep, err := startprep.New(*cfg, func(line string) { fmt.Fprintln(os.Stderr, line) })
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
text := strings.Join(args[2:], " ")
|
||||
if len(args) < 3 {
|
||||
raw, err := io.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
text = strings.TrimRight(string(raw), "\r\n")
|
||||
}
|
||||
detail, err := prep.Client.Show(ctx, args[1])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := qmp.TypeIntoVM(ctx, detail.Directory, text, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(i18n.T(loc, "vm.typed", n))
|
||||
return nil
|
||||
}
|
||||
+14
-24
@@ -6,24 +6,27 @@ import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
)
|
||||
|
||||
func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, *driver.Router, error) {
|
||||
if err := guest.MigrateFiles(cfg.DataRoot); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
mgr, err := plugin.NewManager(plugin.ManagerOptions{
|
||||
DataRoot: cfg.DataRoot,
|
||||
HostVersion: version.Version,
|
||||
SafeMode: safeMode,
|
||||
RedactFn: reims.RedactText,
|
||||
RedactFn: host.RedactText,
|
||||
LocaleFn: func() i18n.Locale {
|
||||
return i18n.EffectiveLocale(cfg.Locale)
|
||||
},
|
||||
@@ -43,29 +46,16 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, *
|
||||
fmt.Fprintf(os.Stderr, "[%s] %s\n", source, line)
|
||||
},
|
||||
}
|
||||
router := driver.NewRouter(mgr.Registry(), func() string {
|
||||
return filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms")
|
||||
})
|
||||
mgr.Registry().SetInUseChecker(func(pluginID string) (bool, string, error) {
|
||||
seen := map[string]bool{}
|
||||
candidates := append([]string{pluginID}, mgr.Registry().DeclaredDriverIDs(pluginID)...)
|
||||
for _, did := range candidates {
|
||||
if did == "" || seen[did] {
|
||||
continue
|
||||
}
|
||||
seen[did] = true
|
||||
if inUse, reason, err := router.CheckDriverInUse(context.Background(), did); err != nil || inUse {
|
||||
return inUse, reason, err
|
||||
}
|
||||
}
|
||||
return false, "", nil
|
||||
})
|
||||
router := driver.NewRouterWithDataRoot(mgr.Registry(), func() string { return cfg.DataRoot })
|
||||
mgr.Registry().SetInUseChecker(router.PluginInUseChecker())
|
||||
mgr.Registry().SetBusyChecker(router.PluginBusyChecker())
|
||||
if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
||||
mgr.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
if err := builtin.MigrateRetired(mgr); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "[plugin] could not migrate merged core plugin state: %v\n", err)
|
||||
if err := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
||||
mgr.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
_ = mgr.LoadExternal()
|
||||
mgr.Registry().Reconcile(context.Background())
|
||||
@@ -163,7 +153,7 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
return err
|
||||
}
|
||||
defer mgr.Close()
|
||||
list := mgr.LocalizePluginInfos(mgr.Registry().List())
|
||||
list := mgr.LocalizePluginInfos(mgr.Registry().ListVisible())
|
||||
if *asJSON {
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
@@ -507,7 +497,7 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
fmt.Println("[]")
|
||||
return nil
|
||||
}
|
||||
for _, info := range mgr.Registry().List() {
|
||||
for _, info := range mgr.Registry().ListVisible() {
|
||||
fmt.Printf("[ok] %s@%s (%s, state=%s)\n", info.ID, info.Version, info.Source, info.State)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -9,8 +9,8 @@ import (
|
||||
"os/signal"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
)
|
||||
|
||||
@@ -73,7 +73,7 @@ func cmdRuntimeFetch(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
if total > 0 {
|
||||
p = float64(done) * 100 / float64(total)
|
||||
}
|
||||
bar.update(installer.Update{Kind: installer.KindProgress, Done: done, Total: total, Percent: p})
|
||||
bar.update(host.Update{Kind: host.KindProgress, Done: done, Total: total, Percent: p})
|
||||
})
|
||||
bar.finish()
|
||||
if errors.Is(err, context.Canceled) {
|
||||
|
||||
+74
-56
@@ -11,12 +11,9 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
"github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
)
|
||||
|
||||
// startHandoffTimeout bounds how long `vm start` waits for the window to
|
||||
@@ -31,70 +28,91 @@ const startHandoffTimeout = 5 * time.Minute
|
||||
//
|
||||
// viaWindow is false when --data-root points elsewhere than the window's
|
||||
// data root could; the VM then starts here, without those two.
|
||||
func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string, viaWindow bool) error {
|
||||
rep := host.Inspect(cfg.DataRoot)
|
||||
d, err := prep.Client.Show(ctx, name)
|
||||
func startVM(ctx context.Context, cfg *config.Config, name string, viaWindow bool) error {
|
||||
return startVMWithDriver(ctx, cfg, "", name, viaWindow)
|
||||
}
|
||||
|
||||
func startVMWithDriver(ctx context.Context, cfg *config.Config, driverID, name string, viaWindow bool) error {
|
||||
mgr, router, err := openCLIPluginManager(cfg, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.State == "running" {
|
||||
// Preparation rewrites extra-args and the OpenCore image; never under a live VM.
|
||||
return fmt.Errorf("%s", i18n.T(cfg.Locale, "vm.already_running", name))
|
||||
}
|
||||
if err := prep.CheckWHPX(rep); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := prep.CheckMemory(d.Memory, rep); err != nil {
|
||||
defer mgr.Close()
|
||||
svc := lifecycle.New(mgr.Registry(), router, nil)
|
||||
_, vm, err := svc.Resolve(ctx, driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if viaWindow && windowHandoffWorks {
|
||||
return startInWindow(ctx, cfg, name)
|
||||
return startInWindow(ctx, cfg, vm.DriverID, vm.Name)
|
||||
}
|
||||
d, release, err := vmstart.LockVM(ctx, prep.Client, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
if d.State == "running" {
|
||||
return fmt.Errorf("%s", i18n.T(cfg.Locale, "vm.already_running", name))
|
||||
}
|
||||
if d.State == "stopped" && reims.HasSuspendState(d.Directory) {
|
||||
return resumeLocked(ctx, cfg, prep, d, rep)
|
||||
}
|
||||
|
||||
// Honour the core plugin's WHPX setting, as the window does.
|
||||
st := plugin.ReadState(cfg.DataRoot)
|
||||
prep.SkipWHPXFallback = !builtin.CoreSettingOnInState(st, builtin.SettingWHPXFallback)
|
||||
prep.Prepare(ctx, name, rep, &d)
|
||||
if err := prep.Client.StartWithCompat(ctx, name, os.Stdout, os.Stderr, func(msg string) {
|
||||
fmt.Fprintln(os.Stderr, msg)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
vms, err := prep.Client.List(ctx)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
for _, vm := range vms {
|
||||
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
|
||||
vmDir := vm.Dir
|
||||
if vmDir == "" {
|
||||
vmDir = d.Directory
|
||||
}
|
||||
if line, _ := vmstart.ApplyVMAffinity(cfg.Locale, rep, vmDir, cfg.AutoPinPCores, *vm.PID, d.CPUs, false); line != "" {
|
||||
fmt.Fprintln(os.Stderr, line)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
_, err = svc.Start(ctx, vm.Ref(), os.Stdout, os.Stderr)
|
||||
return err
|
||||
}
|
||||
|
||||
func startInWindow(ctx context.Context, cfg *config.Config, name string) error {
|
||||
func actionVM(ctx context.Context, cfg *config.Config, driverID, name, action string, params map[string]any) error {
|
||||
mgr, router, err := openCLIPluginManager(cfg, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer mgr.Close()
|
||||
svc := lifecycle.New(mgr.Registry(), router, nil)
|
||||
_, err = svc.InvokeAction(ctx, driver.VMRef{DriverID: driverID, Name: name}, action, params)
|
||||
return err
|
||||
}
|
||||
|
||||
func setVM(ctx context.Context, cfg *config.Config, driverID, name string, changes map[string]any) error {
|
||||
mgr, router, err := openCLIPluginManager(cfg, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer mgr.Close()
|
||||
svc := lifecycle.New(mgr.Registry(), router, nil)
|
||||
return svc.Set(ctx, driver.VMRef{DriverID: driverID, Name: name}, changes, os.Stdout, os.Stderr)
|
||||
}
|
||||
|
||||
func deleteVM(ctx context.Context, cfg *config.Config, driverID, name string, keepFiles bool) error {
|
||||
mgr, router, err := openCLIPluginManager(cfg, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer mgr.Close()
|
||||
svc := lifecycle.New(mgr.Registry(), router, nil)
|
||||
return svc.Delete(ctx, driver.VMRef{DriverID: driverID, Name: name}, keepFiles, os.Stdout, os.Stderr)
|
||||
}
|
||||
|
||||
func resizeVM(ctx context.Context, cfg *config.Config, driverID, name, newSize string) (driver.DiskResizeResult, error) {
|
||||
mgr, router, err := openCLIPluginManager(cfg, false)
|
||||
if err != nil { return driver.DiskResizeResult{}, err }
|
||||
defer mgr.Close()
|
||||
svc := lifecycle.New(mgr.Registry(), router, nil)
|
||||
return svc.ResizeDisk(ctx, driver.VMRef{DriverID: driverID, Name: name}, newSize, os.Stdout, os.Stderr)
|
||||
}
|
||||
|
||||
func compactVM(ctx context.Context, cfg *config.Config, driverID, name string) (driver.DiskCompactResult, error) {
|
||||
mgr, router, err := openCLIPluginManager(cfg, false)
|
||||
if err != nil { return driver.DiskCompactResult{}, err }
|
||||
defer mgr.Close()
|
||||
svc := lifecycle.New(mgr.Registry(), router, nil)
|
||||
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, force bool) error {
|
||||
mgr, router, err := openCLIPluginManager(cfg, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer mgr.Close()
|
||||
svc := lifecycle.New(mgr.Registry(), router, nil)
|
||||
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 {
|
||||
if err := os.MkdirAll(cfg.TempDir(), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
result := filepath.Join(cfg.TempDir(), fmt.Sprintf("cli-start-%d.json", time.Now().UnixNano()))
|
||||
w := WindowArgs{StartVM: name, StartResult: result}
|
||||
w := WindowArgs{StartVM: name, StartDriver: driverID, StartResult: result}
|
||||
if hwnd := findWindow(); hwnd != 0 {
|
||||
fmt.Fprintln(os.Stderr, i18n.M(cfg.Locale, "cli.start.handing_to_window", i18n.Vars{"name": name}))
|
||||
if err := sendToWindow(hwnd, w.Args(), 0); err != nil {
|
||||
|
||||
+40
-27
@@ -7,63 +7,76 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
func suspendVM(ctx context.Context, _ *config.Config, prep *vmstart.Prep, name string) error {
|
||||
d, release, err := vmstart.LockVM(ctx, prep.Client, name)
|
||||
func suspendVM(ctx context.Context, cfg *config.Config, driverID, name string) error {
|
||||
mgr, router, err := openCLIPluginManager(cfg, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
|
||||
fmt.Fprintf(os.Stderr, "Suspending %s to %s...\n", name, reims.SuspendStateFileName)
|
||||
info, err := prep.SuspendSnapshot(ctx, d, nil)
|
||||
defer mgr.Close()
|
||||
svc := lifecycle.New(mgr.Registry(), router, nil)
|
||||
_, vm, err := svc.Resolve(ctx, driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("Suspended %s (%.2f GiB saved)\n", name, float64(info.VMStateSize)/float64(1<<30))
|
||||
fmt.Fprintf(os.Stderr, "Suspending %s...\n", vm.Name)
|
||||
res, err := svc.Suspend(ctx, vm.Ref(), nil, os.Stdout, os.Stderr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("Suspended %s (%.2f GiB saved)\n", vm.Name, float64(res.VMStateSize)/float64(1<<30))
|
||||
return nil
|
||||
}
|
||||
|
||||
func resumeVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error {
|
||||
d, release, err := vmstart.LockVM(ctx, prep.Client, name)
|
||||
func resumeVM(ctx context.Context, cfg *config.Config, driverID, name string) error {
|
||||
mgr, router, err := openCLIPluginManager(cfg, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
return resumeLocked(ctx, cfg, prep, d, host.Inspect(cfg.DataRoot))
|
||||
}
|
||||
|
||||
func resumeLocked(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, d reims.VMDetail, rep host.Report) error {
|
||||
fmt.Fprintf(os.Stderr, "Resuming %s from %s...\n", d.Name, reims.SuspendStateFileName)
|
||||
startAt := time.Now()
|
||||
if err := prep.ResumeSnapshot(ctx, d, rep, os.Stdout, os.Stderr); err != nil {
|
||||
defer mgr.Close()
|
||||
svc := lifecycle.New(mgr.Registry(), router, nil)
|
||||
_, vm, err := svc.Resolve(ctx, driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if vms, err := prep.Client.List(ctx); err == nil {
|
||||
for _, vm := range vms {
|
||||
if vm.Name != d.Name || vm.State != "running" || vm.PID == nil || *vm.PID <= 0 {
|
||||
ref := vm.Ref()
|
||||
fmt.Fprintf(os.Stderr, "Resuming %s...\n", ref.Name)
|
||||
startAt := time.Now()
|
||||
if _, err := svc.Resume(ctx, ref, nil, os.Stdout, os.Stderr); err != nil {
|
||||
return err
|
||||
}
|
||||
rep := host.Inspect(cfg.DataRoot)
|
||||
if list, err := svc.List(ctx); err == nil {
|
||||
for _, item := range list {
|
||||
if item.Ref() != ref || item.State != "running" || item.PID == nil || *item.PID <= 0 {
|
||||
continue
|
||||
}
|
||||
if line, _ := vmstart.ApplyVMAffinity(cfg.Locale, rep, d.Directory, cfg.AutoPinPCores, *vm.PID, d.CPUs, false); line != "" {
|
||||
vmDir := item.Directory
|
||||
if vmDir == "" {
|
||||
vmDir = vm.Directory
|
||||
}
|
||||
if line, _ := vmstart.ApplyVMAffinity(cfg.Locale, rep, vmDir, cfg.AutoPinPCores, *item.PID, vm.CPUs, false); line != "" {
|
||||
fmt.Fprintln(os.Stderr, line)
|
||||
}
|
||||
}
|
||||
}
|
||||
fmt.Printf("Resumed %s in %.1fs\n", d.Name, time.Since(startAt).Seconds())
|
||||
fmt.Printf("Resumed %s in %.1fs\n", ref.Name, time.Since(startAt).Seconds())
|
||||
return nil
|
||||
}
|
||||
|
||||
func discardSuspendVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error {
|
||||
d, release, err := vmstart.LockVM(ctx, prep.Client, name)
|
||||
func discardSuspendVM(ctx context.Context, cfg *config.Config, driverID, name string) error {
|
||||
mgr, router, err := openCLIPluginManager(cfg, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
if err := vmstart.DiscardSnapshot(cfg.Locale, d); err != nil {
|
||||
defer mgr.Close()
|
||||
svc := lifecycle.New(mgr.Registry(), router, nil)
|
||||
if err := svc.DiscardSuspend(ctx, driver.VMRef{DriverID: driverID, Name: name}); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("Discarded suspend state for %s\n", name)
|
||||
|
||||
@@ -13,6 +13,7 @@ const (
|
||||
flagBackground = "--background"
|
||||
flagSafeMode = "--safe-mode"
|
||||
flagStartVM = "--start-vm="
|
||||
flagStartDriver = "--start-driver="
|
||||
flagStartResult = "--start-result="
|
||||
flagCloseVM = "--close-vm="
|
||||
flagWaitPID = "--wait-pid="
|
||||
@@ -28,6 +29,8 @@ type WindowArgs struct {
|
||||
// StartVM is a VM to start as the GUI's StartVM would (Guest Tools and
|
||||
// the Win10 cold-reboot watcher included).
|
||||
StartVM string
|
||||
// StartDriver identifies the VM's owning driver when names are ambiguous.
|
||||
StartDriver string
|
||||
// StartResult is a file the window writes a StartResult to once StartVM
|
||||
// has returned, so the command that asked can report it.
|
||||
StartResult string
|
||||
@@ -51,6 +54,8 @@ func ParseWindowArgs(args []string) (w WindowArgs, ok bool) {
|
||||
w.SafeMode = true
|
||||
case strings.HasPrefix(a, flagStartVM):
|
||||
w.StartVM = strings.TrimPrefix(a, flagStartVM)
|
||||
case strings.HasPrefix(a, flagStartDriver):
|
||||
w.StartDriver = strings.TrimPrefix(a, flagStartDriver)
|
||||
case strings.HasPrefix(a, flagStartResult):
|
||||
w.StartResult = strings.TrimPrefix(a, flagStartResult)
|
||||
case strings.HasPrefix(a, flagCloseVM):
|
||||
@@ -83,6 +88,9 @@ func (w WindowArgs) Args() []string {
|
||||
if w.StartVM != "" {
|
||||
out = append(out, flagStartVM+w.StartVM)
|
||||
}
|
||||
if w.StartDriver != "" {
|
||||
out = append(out, flagStartDriver+w.StartDriver)
|
||||
}
|
||||
if w.StartResult != "" {
|
||||
out = append(out, flagStartResult+w.StartResult)
|
||||
}
|
||||
|
||||
@@ -18,8 +18,8 @@ func TestParseWindowArgs(t *testing.T) {
|
||||
}{
|
||||
{nil, WindowArgs{}, true},
|
||||
{[]string{"--background"}, WindowArgs{Background: true}, true},
|
||||
{[]string{"--background", "--start-vm=m0", `--start-result=D:\tmp\cli-start-1.json`},
|
||||
WindowArgs{Background: true, StartVM: "m0", StartResult: `D:\tmp\cli-start-1.json`}, true},
|
||||
{[]string{"--background", "--start-vm=m0", "--start-driver=test.driver.linux", `--start-result=D:\tmp\cli-start-1.json`},
|
||||
WindowArgs{Background: true, StartVM: "m0", StartDriver: "test.driver.linux", StartResult: `D:\tmp\cli-start-1.json`}, true},
|
||||
{[]string{"vm", "start", "m0"}, WindowArgs{}, false},
|
||||
{[]string{"--background", "vm", "list"}, WindowArgs{}, false},
|
||||
{[]string{"--help"}, WindowArgs{}, false},
|
||||
@@ -50,7 +50,7 @@ func TestCloseWindowArgsRoundTrip(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestWindowArgsRoundTrip(t *testing.T) {
|
||||
w := WindowArgs{Background: true, StartVM: "mac os", StartResult: `D:\Data\tmp\cli-start-9.json`, WaitPID: 31337}
|
||||
w := WindowArgs{Background: true, StartVM: "mac os", StartDriver: "test.driver.linux", StartResult: `D:\Data\tmp\cli-start-9.json`, WaitPID: 31337}
|
||||
got, ok := ParseWindowArgs(w.Args())
|
||||
if !ok || got != w {
|
||||
t.Fatalf("round trip = %+v, %v", got, ok)
|
||||
|
||||
@@ -146,6 +146,20 @@ func SaveLocation(dataRoot string) error {
|
||||
// config; a variable so tests can point it elsewhere.
|
||||
var legacyDataRoot = DefaultDataRoot
|
||||
|
||||
// ErrFirstRunNotIsolated refuses REIMS_GO_FIRST_RUN without its own
|
||||
// REIMS_GO_LOCATION_FILE: finishing the simulated setup would otherwise
|
||||
// repoint the user's real data folder record.
|
||||
var ErrFirstRunNotIsolated = errors.New("REIMS_GO_FIRST_RUN=1 also needs REIMS_GO_LOCATION_FILE pointing at a test location file")
|
||||
|
||||
// CheckFirstRunIsolation reports ErrFirstRunNotIsolated when the first-run
|
||||
// test mode is on without a test location file.
|
||||
func CheckFirstRunIsolation() error {
|
||||
if os.Getenv("REIMS_GO_FIRST_RUN") == "1" && os.Getenv("REIMS_GO_LOCATION_FILE") == "" {
|
||||
return ErrFirstRunNotIsolated
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Resolve() (cfg *Config, needsSetup bool, err error) {
|
||||
if os.Getenv("REIMS_GO_FIRST_RUN") == "1" {
|
||||
// Simulate a fresh machine (testing the first-launch screen).
|
||||
@@ -222,7 +236,13 @@ func Save(path string, cfg *Config) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(path, append(data, '\n'), 0o644)
|
||||
// Temp file + rename: a crash mid-write leaves the old file, not a
|
||||
// truncated one.
|
||||
tmp := path + ".tmp"
|
||||
if err := os.WriteFile(tmp, append(data, '\n'), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, path)
|
||||
}
|
||||
|
||||
func (c *Config) RuntimesDir() string { return filepath.Join(c.DataRoot, "runtimes") }
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
@@ -92,3 +93,22 @@ func TestLegacyCandidateChannelReadsAsAlpha(t *testing.T) {
|
||||
t.Fatalf("runtime_channel = %q, want alpha", cfg.RuntimeChannel)
|
||||
}
|
||||
}
|
||||
|
||||
// The first-run test mode must not be able to repoint the real data folder
|
||||
// record, so it needs its own location file.
|
||||
func TestFirstRunNeedsItsOwnLocationFile(t *testing.T) {
|
||||
t.Setenv("REIMS_GO_FIRST_RUN", "1")
|
||||
t.Setenv("REIMS_GO_LOCATION_FILE", "")
|
||||
if err := CheckFirstRunIsolation(); !errors.Is(err, ErrFirstRunNotIsolated) {
|
||||
t.Fatalf("FIRST_RUN without location file: err = %v", err)
|
||||
}
|
||||
t.Setenv("REIMS_GO_LOCATION_FILE", filepath.Join(t.TempDir(), "location.json"))
|
||||
if err := CheckFirstRunIsolation(); err != nil {
|
||||
t.Fatalf("FIRST_RUN with location file: %v", err)
|
||||
}
|
||||
t.Setenv("REIMS_GO_FIRST_RUN", "")
|
||||
t.Setenv("REIMS_GO_LOCATION_FILE", "")
|
||||
if err := CheckFirstRunIsolation(); err != nil {
|
||||
t.Fatalf("normal launch: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ const StampFile = ".reims-go-data.json"
|
||||
|
||||
// CurrentVersion is the data layout this build writes. Bump it together
|
||||
// with a new Step.
|
||||
const CurrentVersion = 1
|
||||
const CurrentVersion = 3
|
||||
|
||||
// Stamp is the content of StampFile.
|
||||
type Stamp struct {
|
||||
@@ -45,6 +45,7 @@ type Step struct {
|
||||
// steps lists every upgrade in ascending To order.
|
||||
var steps = []Step{
|
||||
{To: 1, Name: "vm-owner-markers", Run: backfillOwnerMarkers},
|
||||
{To: 3, Name: "guest-vmref-metadata", Run: migrateGuestAndVMRef},
|
||||
}
|
||||
|
||||
// Result reports what Run did.
|
||||
@@ -60,10 +61,22 @@ type Result struct {
|
||||
// Run brings the data folder at dataRoot up to CurrentVersion. A missing or
|
||||
// empty dataRoot is not an error: there is nothing to migrate yet.
|
||||
func Run(dataRoot, appVersion string) (Result, error) {
|
||||
return run(dataRoot, appVersion, steps, CurrentVersion, time.Now)
|
||||
return run(dataRoot, appVersion, steps, CurrentVersion, time.Now, false)
|
||||
}
|
||||
|
||||
func run(dataRoot, appVersion string, steps []Step, current int, now func() time.Time) (Result, error) {
|
||||
// ErrDamagedStamp reports a StampFile that cannot be read. Run then changes
|
||||
// nothing: the folder may belong to a newer release whose stamp this build
|
||||
// cannot parse. Repair rebuilds it on the user's explicit request.
|
||||
var ErrDamagedStamp = errors.New("data version stamp is damaged")
|
||||
|
||||
// Repair is Run for a folder whose stamp is damaged: it treats the folder as
|
||||
// unstamped and runs every step from version 0. Steps are idempotent, so this
|
||||
// is safe on a folder that was already partly or fully migrated.
|
||||
func Repair(dataRoot, appVersion string) (Result, error) {
|
||||
return run(dataRoot, appVersion, steps, CurrentVersion, time.Now, true)
|
||||
}
|
||||
|
||||
func run(dataRoot, appVersion string, steps []Step, current int, now func() time.Time, repair bool) (Result, error) {
|
||||
if dataRoot == "" {
|
||||
return Result{}, nil
|
||||
}
|
||||
@@ -73,7 +86,9 @@ func run(dataRoot, appVersion string, steps []Step, current int, now func() time
|
||||
|
||||
stamp, readErr := ReadStamp(dataRoot)
|
||||
if readErr != nil {
|
||||
// Steps are idempotent, so a damaged stamp is safe to rebuild from 0.
|
||||
if !repair {
|
||||
return Result{}, fmt.Errorf("%w: %v", ErrDamagedStamp, readErr)
|
||||
}
|
||||
stamp = Stamp{}
|
||||
}
|
||||
res := Result{From: stamp.DataVersion, To: stamp.DataVersion}
|
||||
|
||||
@@ -48,7 +48,7 @@ func TestRunStampsAndMarksLegacyVMs(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if res.From != 0 || res.To != CurrentVersion || !reflect.DeepEqual(res.Applied, []string{"vm-owner-markers"}) {
|
||||
if res.From != 0 || res.To != CurrentVersion || !reflect.DeepEqual(res.Applied, []string{"vm-owner-markers", "guest-vmref-metadata"}) {
|
||||
t.Fatalf("result = %+v", res)
|
||||
}
|
||||
if got := marker(t, legacy); got != driver.BuiltinReimsMacOSDriverID {
|
||||
@@ -95,16 +95,25 @@ func TestRunLeavesNewerLayoutAlone(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRebuildsDamagedStamp(t *testing.T) {
|
||||
// A damaged stamp may come from a newer release, so Run leaves the folder
|
||||
// alone; Repair, on the user's request, rebuilds it from version 0.
|
||||
func TestDamagedStampNeedsExplicitRepair(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(root, StampFile), []byte("{not json"), 0o644); err != nil {
|
||||
stampPath := filepath.Join(root, StampFile)
|
||||
if err := os.WriteFile(stampPath, []byte("{not json"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Run(root, "0.2.12"); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
if _, err := Run(root, "0.2.12"); !errors.Is(err, ErrDamagedStamp) {
|
||||
t.Fatalf("Run on a damaged stamp: err = %v, want ErrDamagedStamp", err)
|
||||
}
|
||||
if raw, _ := os.ReadFile(stampPath); string(raw) != "{not json" {
|
||||
t.Fatalf("Run rewrote a damaged stamp: %q", raw)
|
||||
}
|
||||
if _, err := Repair(root, "0.2.12"); err != nil {
|
||||
t.Fatalf("Repair: %v", err)
|
||||
}
|
||||
if st, err := ReadStamp(root); err != nil || st.DataVersion != CurrentVersion {
|
||||
t.Fatalf("stamp after rebuild = %+v, %v", st, err)
|
||||
t.Fatalf("stamp after repair = %+v, %v", st, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,7 +129,7 @@ func TestRunStopsAtFailedStep(t *testing.T) {
|
||||
{To: 3, Name: "three", Run: ok("three")},
|
||||
}
|
||||
now := func() time.Time { return time.Unix(0, 0) }
|
||||
res, err := run(root, "1.0.0", steps, 3, now)
|
||||
res, err := run(root, "1.0.0", steps, 3, now, false)
|
||||
if err == nil || !strings.Contains(err.Error(), `"two"`) {
|
||||
t.Fatalf("expected failure in step two, got %v", err)
|
||||
}
|
||||
@@ -134,7 +143,7 @@ func TestRunStopsAtFailedStep(t *testing.T) {
|
||||
// Next start resumes from layout 1 once the problem is gone.
|
||||
steps[1].Run = ok("two")
|
||||
ran = nil
|
||||
res, err = run(root, "1.0.0", steps, 3, now)
|
||||
res, err = run(root, "1.0.0", steps, 3, now, false)
|
||||
if err != nil || res.From != 1 || res.To != 3 || !reflect.DeepEqual(ran, []string{"two", "three"}) {
|
||||
t.Fatalf("resume = %+v, ran %v, err %v", res, ran, err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package datamigrate
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
)
|
||||
|
||||
func TestV1ToV3GuestPluginMigration(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
vmDir := mkVM(t, root, "mac", map[string]string{"vm.toml": "name = 'mac'"})
|
||||
ledger := &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{
|
||||
builtin.IDCore: {
|
||||
{PluginID: builtin.IDCore, Key: "kernel-irqchip", Tokens: []string{"-machine", "kernel-irqchip=off"}},
|
||||
{PluginID: builtin.IDCore, Key: "host-owned", Tokens: []string{"-rtc", "base=utc"}},
|
||||
},
|
||||
}}
|
||||
if err := plugin.SaveArgLedger(vmDir, ledger); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := plugin.NewStateStore(plugin.NewPluginsLayout(root).Root)
|
||||
if err := store.Save(&plugin.StateFile{Plugins: map[string]*plugin.PluginRecord{
|
||||
builtin.IDCore: {ID: builtin.IDCore, Enabled: true, AppSettings: map[string]any{guest.SettingWHPXFallback: false}},
|
||||
guest.LegacyInstallGuideID: {ID: guest.LegacyInstallGuideID, Enabled: false},
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(root, StampFile), []byte(`{"data_version":1}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
original, err := os.ReadFile(store.Path())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res, err := Run(root, "0.2.12")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.From != 1 || res.To != CurrentVersion {
|
||||
t.Fatalf("result = %+v", res)
|
||||
}
|
||||
backup, err := os.ReadFile(store.Path() + ".bak")
|
||||
if err != nil || string(backup) != string(original) {
|
||||
t.Fatalf("v1 original backup changed: %v", err)
|
||||
}
|
||||
if got := marker(t, vmDir); got != driver.BuiltinReimsMacOSDriverID {
|
||||
t.Fatalf("late v1 VM marker = %q", got)
|
||||
}
|
||||
st := plugin.ReadState(root)
|
||||
rec := st.Plugins[guest.ID]
|
||||
if rec == nil || !rec.Enabled {
|
||||
t.Fatalf("guest record = %+v", rec)
|
||||
}
|
||||
if guest.SettingOn(rec.AppSettings, guest.SettingWHPXFallback) || guest.SettingOn(rec.AppSettings, guest.SettingInstallGuide) {
|
||||
t.Fatalf("settings = %+v", rec.AppSettings)
|
||||
}
|
||||
if _, ok := st.Plugins[guest.LegacyInstallGuideID]; ok {
|
||||
t.Fatal("old install-guide record remains")
|
||||
}
|
||||
got, err := plugin.LoadArgLedger(vmDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.Owners[guest.ID]) != 1 || got.Owners[guest.ID][0].Key != "kernel-irqchip" {
|
||||
t.Fatalf("guest ledger = %+v", got.Owners)
|
||||
}
|
||||
if len(got.Owners[builtin.IDCore]) != 1 || got.Owners[builtin.IDCore][0].Key != "host-owned" {
|
||||
t.Fatalf("unrelated ledger moved: %+v", got.Owners)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(vmDir, plugin.ArgLedgerFileName+".bak")); err != nil {
|
||||
t.Fatalf("ledger backup: %v", err)
|
||||
}
|
||||
res, err = Run(root, "0.2.12")
|
||||
if err != nil || len(res.Applied) != 0 {
|
||||
t.Fatalf("second run = %+v, %v", res, err)
|
||||
}
|
||||
}
|
||||
Loaded 100 of 232 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user