From 5e39b11566bbd3e0cb4e5e1d472587b1eeef701a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Mon, 30 Nov 2026 05:47:14 -0700 Subject: [PATCH 01/42] refactor(macos): isolate guest-specific code and guard host imports --- docs/architecture.md | 15 ++- docs/plugin-architecture.md | 6 +- frontend/package.json | 2 +- frontend/scripts/test-macos-boundary.mjs | 52 ++++++++ frontend/src/App.tsx | 6 +- frontend/src/components/CreateWizard.tsx | 2 +- frontend/src/components/Sidebar.tsx | 2 +- frontend/src/components/VMPage.tsx | 2 +- .../{components => macos}/InstallersPage.tsx | 2 +- .../OnlineRecoveryDialog.tsx | 0 .../src/{components => macos}/VersionArt.tsx | 0 frontend/src/{lib => macos}/macosRelease.ts | 0 internal/app/affinity_flow.go | 2 +- internal/app/affinity_flow_test.go | 2 +- internal/app/app.go | 7 +- internal/app/app_poll_test.go | 2 +- internal/app/appupdate_flow.go | 2 +- internal/app/clone_flow.go | 2 +- internal/app/create_flow.go | 6 +- internal/app/diagnostics_flow.go | 2 +- internal/app/diagnostics_test.go | 2 +- internal/app/disk_flow.go | 2 +- internal/app/extras_flow.go | 2 +- internal/app/extras_snapshot_test.go | 2 +- internal/app/guesttools_flow.go | 2 +- internal/app/install_flow.go | 4 +- internal/app/install_guide.go | 4 +- internal/app/install_guide_test.go | 4 +- internal/app/installer_bindings.go | 2 +- internal/app/installer_coordinator.go | 2 +- internal/app/installer_coordinator_test.go | 4 +- internal/app/legacy_ledger_test.go | 2 +- internal/app/opencore_flow.go | 4 +- internal/app/plugins_flow.go | 2 +- internal/app/runtime_bindings.go | 2 +- internal/app/snapshot_flow.go | 2 +- internal/app/stats_flow.go | 2 +- internal/app/tasks.go | 2 +- internal/app/tasks_test.go | 2 +- internal/app/thumbnail_flow.go | 2 +- internal/app/thumbnail_flow_test.go | 2 +- internal/app/ui_health.go | 2 +- internal/app/vm_monitor.go | 2 +- internal/app/vm_monitor_test.go | 2 +- internal/archtest/doc.go | 3 + internal/archtest/macos_boundary_test.go | 119 ++++++++++++++++++ internal/cli/cli.go | 6 +- internal/cli/installer.go | 2 +- internal/cli/plugin.go | 2 +- internal/cli/runtime_fetch.go | 2 +- internal/guesttools/guesttools_test.go | 2 +- internal/guesttools/image.go | 2 +- internal/{ => macos}/installer/events.go | 0 internal/{ => macos}/installer/hfs_image.go | 0 internal/{ => macos}/installer/installer.go | 0 .../{ => macos}/installer/installer_test.go | 0 internal/{ => macos}/installer/oc_cache.go | 0 .../{ => macos}/installer/oc_cache_test.go | 0 .../installer/offline_helper_test.go | 0 internal/{ => macos}/installer/pkg_extract.go | 0 internal/{ => macos}/installer/proc_other.go | 0 .../{ => macos}/installer/proc_windows.go | 0 .../installguide/appearance_windows.go | 0 .../installguide/dialog_windows.go | 0 internal/{ => macos}/installguide/guide.go | 0 internal/{ => macos}/installguide/manager.go | 0 .../{ => macos}/installguide/manager_test.go | 0 .../{ => macos}/installguide/overlay_other.go | 0 .../installguide/overlay_windows.go | 0 .../installguide/overlay_windows_test.go | 4 +- .../installguide/picker_windows.go | 0 internal/{ => macos}/installguide/progress.go | 0 .../installguide/session_windows.go | 0 .../installguide/session_windows_test.go | 0 .../macosdriver/driver.go} | 61 ++++----- internal/{ => macos}/opencore/image.go | 0 internal/{ => macos}/opencore/lang.go | 0 .../{ => macos}/opencore/opencore_test.go | 0 internal/{ => macos}/opencore/plist.go | 0 internal/{ => macos}/opencore/proc_other.go | 0 internal/{ => macos}/opencore/proc_windows.go | 0 internal/{driver => macos}/reims/compat.go | 0 .../{driver => macos}/reims/compat_test.go | 0 .../{driver => macos}/reims/disk_import.go | 0 .../{driver => macos}/reims/disk_ops_test.go | 0 .../{driver => macos}/reims/helper_args.go | 0 .../{driver => macos}/reims/proc_other.go | 0 .../{driver => macos}/reims/proc_windows.go | 0 internal/{driver => macos}/reims/redact.go | 0 internal/{driver => macos}/reims/reims.go | 2 +- .../{driver => macos}/reims/reims_test.go | 0 internal/{driver => macos}/reims/snapshot.go | 0 internal/plugin/builtin/builtin.go | 2 +- internal/plugin/builtin/builtin_test.go | 2 +- internal/plugin/builtin/core.go | 9 +- internal/plugin/builtin/install_guide.go | 2 +- internal/plugin/manager_sidecar_test.go | 2 +- internal/vmstart/vmstart.go | 6 +- patches/README.md | 2 +- 99 files changed, 293 insertions(+), 109 deletions(-) create mode 100644 frontend/scripts/test-macos-boundary.mjs rename frontend/src/{components => macos}/InstallersPage.tsx (99%) rename frontend/src/{components => macos}/OnlineRecoveryDialog.tsx (100%) rename frontend/src/{components => macos}/VersionArt.tsx (100%) rename frontend/src/{lib => macos}/macosRelease.ts (100%) create mode 100644 internal/archtest/doc.go create mode 100644 internal/archtest/macos_boundary_test.go rename internal/{ => macos}/installer/events.go (100%) rename internal/{ => macos}/installer/hfs_image.go (100%) rename internal/{ => macos}/installer/installer.go (100%) rename internal/{ => macos}/installer/installer_test.go (100%) rename internal/{ => macos}/installer/oc_cache.go (100%) rename internal/{ => macos}/installer/oc_cache_test.go (100%) rename internal/{ => macos}/installer/offline_helper_test.go (100%) rename internal/{ => macos}/installer/pkg_extract.go (100%) rename internal/{ => macos}/installer/proc_other.go (100%) rename internal/{ => macos}/installer/proc_windows.go (100%) rename internal/{ => macos}/installguide/appearance_windows.go (100%) rename internal/{ => macos}/installguide/dialog_windows.go (100%) rename internal/{ => macos}/installguide/guide.go (100%) rename internal/{ => macos}/installguide/manager.go (100%) rename internal/{ => macos}/installguide/manager_test.go (100%) rename internal/{ => macos}/installguide/overlay_other.go (100%) rename internal/{ => macos}/installguide/overlay_windows.go (100%) rename internal/{ => macos}/installguide/overlay_windows_test.go (99%) rename internal/{ => macos}/installguide/picker_windows.go (100%) rename internal/{ => macos}/installguide/progress.go (100%) rename internal/{ => macos}/installguide/session_windows.go (100%) rename internal/{ => macos}/installguide/session_windows_test.go (100%) rename internal/{driver/reims_adapter.go => macos/macosdriver/driver.go} (76%) rename internal/{ => macos}/opencore/image.go (100%) rename internal/{ => macos}/opencore/lang.go (100%) rename internal/{ => macos}/opencore/opencore_test.go (100%) rename internal/{ => macos}/opencore/plist.go (100%) rename internal/{ => macos}/opencore/proc_other.go (100%) rename internal/{ => macos}/opencore/proc_windows.go (100%) rename internal/{driver => macos}/reims/compat.go (100%) rename internal/{driver => macos}/reims/compat_test.go (100%) rename internal/{driver => macos}/reims/disk_import.go (100%) rename internal/{driver => macos}/reims/disk_ops_test.go (100%) rename internal/{driver => macos}/reims/helper_args.go (100%) rename internal/{driver => macos}/reims/proc_other.go (100%) rename internal/{driver => macos}/reims/proc_windows.go (100%) rename internal/{driver => macos}/reims/redact.go (100%) rename internal/{driver => macos}/reims/reims.go (99%) rename internal/{driver => macos}/reims/reims_test.go (100%) rename internal/{driver => macos}/reims/snapshot.go (100%) diff --git a/docs/architecture.md b/docs/architecture.md index 7e472b6..a31641c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -60,16 +60,18 @@ flowchart TB | `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/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/`(设计令牌) | | `patches/` | 上游临时补丁队列与 PR 跟踪,见 [`patches/README.md`](../patches/README.md) | | `scripts/` | 便携运行时打包、二进制裁剪与符号分离、MSYS2 源码归档、`alpha` 准入与冒烟脚本,以及 `scripts/debug/` 本地调试目录管理与卫生校验脚本 | @@ -115,6 +117,11 @@ flowchart TB - 只有删除很老的迁移步骤之后,才需要「最低迁移版本」:新版本根据 `data_version` 判断,并提示先安装某个中间版本。这个判断看的是数据本身,所以直接下载新版本运行也会生效。 - 现有步骤:v1 为 reims-ctl 管理的每台 VM(目录含 `vm.toml`)补写驱动归属标记,见 [plugin-architecture.md](plugin-architecture.md) 的「VM 归属」。 +### 4.8 macOS 代码边界 +- macOS 专属代码集中在 `internal/macos/` 与 `frontend/src/macos/`,最终作为独立插件移出本仓库;宿主只应经驱动层(`driver.Router`)与宿主服务使用它。 +- 两处棘轮测试守住边界:`internal/archtest` 检查 Go 包,`frontend/scripts/test-macos-boundary.mjs` 检查前端文件。宿主代码只有列入例外清单的包或文件可以引用 macOS 代码;新增引用、或清单中的条目已不再引用时,测试都会失败,所以清单只能缩短。 +- 清单中每一项都注明原因,现阶段包括 GUI 与 CLI 的组装入口、注册内置 macOS 插件的 `internal/plugin/builtin`,以及仍混有宿主与 macOS 逻辑、待拆分的 `internal/vmstart` 与 `internal/guesttools`。 + --- ## 5. 与上游 `reims-vgpu` 的边界 diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 511d846..b951b39 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -228,7 +228,7 @@ 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` 的具体类型。抽象后: | 层 | 内容 | | :--- | :--- | @@ -269,8 +269,8 @@ 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.install-guide` | `internal/macos/installguide`、`internal/app/install_guide.go` | 提供 `ui.install-guide` 服务 + `vm.afterStop` / `vm.deleted` 观察钩子;在虚拟机窗口悬浮展示安装与恢复引导,停用时立即关闭全部浮层并回退主界面恢复卡片 | +| `builtin.core`(系统插件) | `macos/macosdriver`、`vmstart.Prepare` 各步骤、`app.go` 冷重启监视 | `guestDrivers` + `themes` + `host.preflight` + 一个按序执行全部启动准备的 `vm.beforeStart`(离线辅助盘 → 恢复模式引导 → 引导语言 → WHPX 降级 → Win10 冷重启)+ `vm.afterStart` / `vm.afterStop`(冷重启监视);设置 `whpx_fallback`、`win10_cold_reboot` | ### 5.5 与上游补丁队列的边界 diff --git a/frontend/package.json b/frontend/package.json index a8ca3f0..66ecaa2 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -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" }, diff --git a/frontend/scripts/test-macos-boundary.mjs b/frontend/scripts/test-macos-boundary.mjs new file mode 100644 index 0000000..1d64867 --- /dev/null +++ b/frontend/scripts/test-macos-boundary.mjs @@ -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(', ')}`) +}) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 2f43c0b..7404660 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -3,7 +3,7 @@ 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' @@ -14,7 +14,7 @@ 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' @@ -32,7 +32,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 }))) diff --git a/frontend/src/components/CreateWizard.tsx b/frontend/src/components/CreateWizard.tsx index 7a210c6..d872e5e 100644 --- a/frontend/src/components/CreateWizard.tsx +++ b/frontend/src/components/CreateWizard.tsx @@ -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 = { installer: 1, disk: 1, macos: 1, guest_lang: 1, cpus: 2, memory: 2, diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index 45c7a88..5ac6026 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -4,7 +4,7 @@ import React, { useRef } from 'react' import { I18nKey, t } from '../i18n' import { Locale, VMListItem } from '../types' 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__' diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index e8b60ea..05179a1 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -51,7 +51,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' diff --git a/frontend/src/components/InstallersPage.tsx b/frontend/src/macos/InstallersPage.tsx similarity index 99% rename from frontend/src/components/InstallersPage.tsx rename to frontend/src/macos/InstallersPage.tsx index 52a8758..c8c701e 100644 --- a/frontend/src/components/InstallersPage.tsx +++ b/frontend/src/macos/InstallersPage.tsx @@ -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, diff --git a/frontend/src/components/OnlineRecoveryDialog.tsx b/frontend/src/macos/OnlineRecoveryDialog.tsx similarity index 100% rename from frontend/src/components/OnlineRecoveryDialog.tsx rename to frontend/src/macos/OnlineRecoveryDialog.tsx diff --git a/frontend/src/components/VersionArt.tsx b/frontend/src/macos/VersionArt.tsx similarity index 100% rename from frontend/src/components/VersionArt.tsx rename to frontend/src/macos/VersionArt.tsx diff --git a/frontend/src/lib/macosRelease.ts b/frontend/src/macos/macosRelease.ts similarity index 100% rename from frontend/src/lib/macosRelease.ts rename to frontend/src/macos/macosRelease.ts diff --git a/internal/app/affinity_flow.go b/internal/app/affinity_flow.go index d4e64b8..f745996 100644 --- a/internal/app/affinity_flow.go +++ b/internal/app/affinity_flow.go @@ -4,8 +4,8 @@ import ( "context" "fmt" - "github.com/Nwflower/reims-go/internal/driver/reims" "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/vmstart" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) diff --git a/internal/app/affinity_flow_test.go b/internal/app/affinity_flow_test.go index 821911b..88e9c48 100644 --- a/internal/app/affinity_flow_test.go +++ b/internal/app/affinity_flow_test.go @@ -4,8 +4,8 @@ import ( "reflect" "testing" - "github.com/Nwflower/reims-go/internal/driver/reims" "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/vmstart" ) diff --git a/internal/app/app.go b/internal/app/app.go index 061e539..90fcddd 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -15,11 +15,12 @@ import ( "github.com/Nwflower/reims-go/internal/cli" "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/guesttools" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" - "github.com/Nwflower/reims-go/internal/installguide" + "github.com/Nwflower/reims-go/internal/macos/installguide" + "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" @@ -1357,7 +1358,7 @@ func (a *App) StartVM(name string) error { RuntimeKind: prep.Runtime.Manifest.EffectiveKind(), RuntimeCaps: rtCaps, HostFacts: buildHostFacts(rep, rtCaps), - VMCaps: driver.ReimsMacOSCapabilities, + VMCaps: macosdriver.ReimsMacOSCapabilities, State: curDetail.State, }) if blockErr != nil { diff --git a/internal/app/app_poll_test.go b/internal/app/app_poll_test.go index 7192c16..7c40bac 100644 --- a/internal/app/app_poll_test.go +++ b/internal/app/app_poll_test.go @@ -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) { diff --git a/internal/app/appupdate_flow.go b/internal/app/appupdate_flow.go index c446af5..829138a 100644 --- a/internal/app/appupdate_flow.go +++ b/internal/app/appupdate_flow.go @@ -18,7 +18,7 @@ import ( "github.com/Nwflower/reims-go/internal/cli" "github.com/Nwflower/reims-go/internal/fetch" "github.com/Nwflower/reims-go/internal/i18n" - "github.com/Nwflower/reims-go/internal/installer" + "github.com/Nwflower/reims-go/internal/macos/installer" "github.com/Nwflower/reims-go/internal/netproxy" "github.com/Nwflower/reims-go/internal/selfupdate" "github.com/Nwflower/reims-go/internal/version" diff --git a/internal/app/clone_flow.go b/internal/app/clone_flow.go index 42ca1d1..98b62f6 100644 --- a/internal/app/clone_flow.go +++ b/internal/app/clone_flow.go @@ -6,9 +6,9 @@ import ( "path/filepath" "strings" - "github.com/Nwflower/reims-go/internal/driver/reims" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/macos/reims" rt "github.com/Nwflower/reims-go/internal/runtime" "github.com/Nwflower/reims-go/internal/vmstart" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" diff --git a/internal/app/create_flow.go b/internal/app/create_flow.go index 4172b1d..bbfbede 100644 --- a/internal/app/create_flow.go +++ b/internal/app/create_flow.go @@ -9,9 +9,9 @@ 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/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" ) diff --git a/internal/app/diagnostics_flow.go b/internal/app/diagnostics_flow.go index 00993d6..0419c77 100644 --- a/internal/app/diagnostics_flow.go +++ b/internal/app/diagnostics_flow.go @@ -10,8 +10,8 @@ import ( "strings" "time" - "github.com/Nwflower/reims-go/internal/driver/reims" "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/plugin" rt "github.com/Nwflower/reims-go/internal/runtime" ) diff --git a/internal/app/diagnostics_test.go b/internal/app/diagnostics_test.go index 1f360ec..b85d107 100644 --- a/internal/app/diagnostics_test.go +++ b/internal/app/diagnostics_test.go @@ -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) { diff --git a/internal/app/disk_flow.go b/internal/app/disk_flow.go index f1bf3cf..008444b 100644 --- a/internal/app/disk_flow.go +++ b/internal/app/disk_flow.go @@ -5,7 +5,7 @@ import ( "fmt" "strings" - "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/macos/reims" rt "github.com/Nwflower/reims-go/internal/runtime" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) diff --git a/internal/app/extras_flow.go b/internal/app/extras_flow.go index 6732fc9..1673159 100644 --- a/internal/app/extras_flow.go +++ b/internal/app/extras_flow.go @@ -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" diff --git a/internal/app/extras_snapshot_test.go b/internal/app/extras_snapshot_test.go index 70e22c2..c3ae4de 100644 --- a/internal/app/extras_snapshot_test.go +++ b/internal/app/extras_snapshot_test.go @@ -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) { diff --git a/internal/app/guesttools_flow.go b/internal/app/guesttools_flow.go index 6cfe72b..e61bdce 100644 --- a/internal/app/guesttools_flow.go +++ b/internal/app/guesttools_flow.go @@ -10,10 +10,10 @@ 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/plugin/builtin" "github.com/Nwflower/reims-go/internal/vmstart" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" diff --git a/internal/app/install_flow.go b/internal/app/install_flow.go index 10f979a..29bbaff 100644 --- a/internal/app/install_flow.go +++ b/internal/app/install_flow.go @@ -10,8 +10,8 @@ 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/macos/installer" + "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/vmstart" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) diff --git a/internal/app/install_guide.go b/internal/app/install_guide.go index 102a54b..0aa9308 100644 --- a/internal/app/install_guide.go +++ b/internal/app/install_guide.go @@ -3,9 +3,9 @@ package app import ( "context" - "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/installguide" + "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/plugin/builtin" "github.com/Nwflower/reims-go/internal/vmstart" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" diff --git a/internal/app/install_guide_test.go b/internal/app/install_guide_test.go index 82c77f4..9477042 100644 --- a/internal/app/install_guide_test.go +++ b/internal/app/install_guide_test.go @@ -5,9 +5,9 @@ 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/installguide" + "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/vmstart" diff --git a/internal/app/installer_bindings.go b/internal/app/installer_bindings.go index 573a051..2319c5e 100644 --- a/internal/app/installer_bindings.go +++ b/internal/app/installer_bindings.go @@ -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" ) diff --git a/internal/app/installer_coordinator.go b/internal/app/installer_coordinator.go index 0f26811..c476dba 100644 --- a/internal/app/installer_coordinator.go +++ b/internal/app/installer_coordinator.go @@ -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) diff --git a/internal/app/installer_coordinator_test.go b/internal/app/installer_coordinator_test.go index a50ac87..b4b90f6 100644 --- a/internal/app/installer_coordinator_test.go +++ b/internal/app/installer_coordinator_test.go @@ -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) { diff --git a/internal/app/legacy_ledger_test.go b/internal/app/legacy_ledger_test.go index 2e212d3..f61088e 100644 --- a/internal/app/legacy_ledger_test.go +++ b/internal/app/legacy_ledger_test.go @@ -4,7 +4,7 @@ import ( "strings" "testing" - "github.com/Nwflower/reims-go/internal/driver/reims" + "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" diff --git a/internal/app/opencore_flow.go b/internal/app/opencore_flow.go index 862d4e6..159daa9 100644 --- a/internal/app/opencore_flow.go +++ b/internal/app/opencore_flow.go @@ -1,8 +1,8 @@ package app import ( - "github.com/Nwflower/reims-go/internal/driver/reims" - "github.com/Nwflower/reims-go/internal/opencore" + "github.com/Nwflower/reims-go/internal/macos/opencore" + "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/vmstart" ) diff --git a/internal/app/plugins_flow.go b/internal/app/plugins_flow.go index ec50073..3205b14 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -16,10 +16,10 @@ import ( "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" + "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/internal/plugin/builtin" rt "github.com/Nwflower/reims-go/internal/runtime" diff --git a/internal/app/runtime_bindings.go b/internal/app/runtime_bindings.go index da5c5ab..db8f262 100644 --- a/internal/app/runtime_bindings.go +++ b/internal/app/runtime_bindings.go @@ -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/macos/installer" rt "github.com/Nwflower/reims-go/internal/runtime" "github.com/Nwflower/reims-go/internal/version" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" diff --git a/internal/app/snapshot_flow.go b/internal/app/snapshot_flow.go index 306aa7b..2f04251 100644 --- a/internal/app/snapshot_flow.go +++ b/internal/app/snapshot_flow.go @@ -6,8 +6,8 @@ import ( "sort" "strings" - "github.com/Nwflower/reims-go/internal/driver/reims" "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/macos/reims" rt "github.com/Nwflower/reims-go/internal/runtime" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) diff --git a/internal/app/stats_flow.go b/internal/app/stats_flow.go index 66be5f5..cd8c3e5 100644 --- a/internal/app/stats_flow.go +++ b/internal/app/stats_flow.go @@ -7,8 +7,8 @@ import ( "strings" "time" - "github.com/Nwflower/reims-go/internal/driver/reims" "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/macos/reims" ) // VMStats provides lightweight real-time resource telemetry for the VM detail header. diff --git a/internal/app/tasks.go b/internal/app/tasks.go index 50fb366..1be1ab6 100644 --- a/internal/app/tasks.go +++ b/internal/app/tasks.go @@ -14,7 +14,7 @@ import ( "sync" "time" - "github.com/Nwflower/reims-go/internal/installer" + "github.com/Nwflower/reims-go/internal/macos/installer" "github.com/Nwflower/reims-go/internal/vmstart" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) diff --git a/internal/app/tasks_test.go b/internal/app/tasks_test.go index eacf9d4..c7fb7e3 100644 --- a/internal/app/tasks_test.go +++ b/internal/app/tasks_test.go @@ -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 { diff --git a/internal/app/thumbnail_flow.go b/internal/app/thumbnail_flow.go index 3a13dc0..6f99f5b 100644 --- a/internal/app/thumbnail_flow.go +++ b/internal/app/thumbnail_flow.go @@ -17,10 +17,10 @@ import ( "sync" "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/qmp" "github.com/Nwflower/reims-go/internal/thumb" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" diff --git a/internal/app/thumbnail_flow_test.go b/internal/app/thumbnail_flow_test.go index ce51b1b..0fbadb9 100644 --- a/internal/app/thumbnail_flow_test.go +++ b/internal/app/thumbnail_flow_test.go @@ -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) { diff --git a/internal/app/ui_health.go b/internal/app/ui_health.go index 87bca97..3e81ba7 100644 --- a/internal/app/ui_health.go +++ b/internal/app/ui_health.go @@ -9,7 +9,7 @@ import ( "sync" "time" - "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/macos/reims" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) diff --git a/internal/app/vm_monitor.go b/internal/app/vm_monitor.go index 79756f4..a12d144 100644 --- a/internal/app/vm_monitor.go +++ b/internal/app/vm_monitor.go @@ -10,9 +10,9 @@ import ( "sync" "time" - "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" "github.com/Nwflower/reims-go/internal/vmstart" ) diff --git a/internal/app/vm_monitor_test.go b/internal/app/vm_monitor_test.go index b7ca8a6..529befd 100644 --- a/internal/app/vm_monitor_test.go +++ b/internal/app/vm_monitor_test.go @@ -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) { diff --git a/internal/archtest/doc.go b/internal/archtest/doc.go new file mode 100644 index 0000000..ee0c70b --- /dev/null +++ b/internal/archtest/doc.go @@ -0,0 +1,3 @@ +// Package archtest holds repository-wide architecture checks. It has no +// runtime code; see the tests. +package archtest diff --git a/internal/archtest/macos_boundary_test.go b/internal/archtest/macos_boundary_test.go new file mode 100644 index 0000000..522e454 --- /dev/null +++ b/internal/archtest/macos_boundary_test.go @@ -0,0 +1,119 @@ +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": {src: true, test: true, why: "GUI composition root; VM flows still call the reims client directly instead of driver.Router"}, + "internal/cli": {src: true, why: "CLI composition root; vm subcommands call the reims client directly"}, + "internal/plugin/builtin": {src: true, test: true, why: "registers the macOS driver, install guide and start hooks as builtin plugins"}, + "internal/vmstart": {src: true, why: "mixed: host CPU pinning and memory checks next to reims start preparation"}, + "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"}, +} + +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 { + 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, 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) + } +} diff --git a/internal/cli/cli.go b/internal/cli/cli.go index cc733c6..e6e726f 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -14,11 +14,11 @@ import ( "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/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/macos/installer" + "github.com/Nwflower/reims-go/internal/macos/opencore" + "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/internal/qmp" rt "github.com/Nwflower/reims-go/internal/runtime" diff --git a/internal/cli/installer.go b/internal/cli/installer.go index 3c7c235..95e2611 100644 --- a/internal/cli/installer.go +++ b/internal/cli/installer.go @@ -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" ) diff --git a/internal/cli/plugin.go b/internal/cli/plugin.go index ebac529..2ba272e 100644 --- a/internal/cli/plugin.go +++ b/internal/cli/plugin.go @@ -11,8 +11,8 @@ import ( "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/i18n" + "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/internal/plugin/builtin" "github.com/Nwflower/reims-go/internal/version" diff --git a/internal/cli/runtime_fetch.go b/internal/cli/runtime_fetch.go index e6634a9..0ea3dc8 100644 --- a/internal/cli/runtime_fetch.go +++ b/internal/cli/runtime_fetch.go @@ -10,7 +10,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" ) diff --git a/internal/guesttools/guesttools_test.go b/internal/guesttools/guesttools_test.go index 2adcee9..17461c1 100644 --- a/internal/guesttools/guesttools_test.go +++ b/internal/guesttools/guesttools_test.go @@ -19,7 +19,7 @@ import ( "testing" "time" - "github.com/Nwflower/reims-go/internal/installer" + "github.com/Nwflower/reims-go/internal/macos/installer" ) type memClipboard struct { diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index bb9fc8e..bacca3d 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -7,7 +7,7 @@ import ( "os" "path/filepath" - "github.com/Nwflower/reims-go/internal/installer" + "github.com/Nwflower/reims-go/internal/macos/installer" ) const ( diff --git a/internal/installer/events.go b/internal/macos/installer/events.go similarity index 100% rename from internal/installer/events.go rename to internal/macos/installer/events.go diff --git a/internal/installer/hfs_image.go b/internal/macos/installer/hfs_image.go similarity index 100% rename from internal/installer/hfs_image.go rename to internal/macos/installer/hfs_image.go diff --git a/internal/installer/installer.go b/internal/macos/installer/installer.go similarity index 100% rename from internal/installer/installer.go rename to internal/macos/installer/installer.go diff --git a/internal/installer/installer_test.go b/internal/macos/installer/installer_test.go similarity index 100% rename from internal/installer/installer_test.go rename to internal/macos/installer/installer_test.go diff --git a/internal/installer/oc_cache.go b/internal/macos/installer/oc_cache.go similarity index 100% rename from internal/installer/oc_cache.go rename to internal/macos/installer/oc_cache.go diff --git a/internal/installer/oc_cache_test.go b/internal/macos/installer/oc_cache_test.go similarity index 100% rename from internal/installer/oc_cache_test.go rename to internal/macos/installer/oc_cache_test.go diff --git a/internal/installer/offline_helper_test.go b/internal/macos/installer/offline_helper_test.go similarity index 100% rename from internal/installer/offline_helper_test.go rename to internal/macos/installer/offline_helper_test.go diff --git a/internal/installer/pkg_extract.go b/internal/macos/installer/pkg_extract.go similarity index 100% rename from internal/installer/pkg_extract.go rename to internal/macos/installer/pkg_extract.go diff --git a/internal/installer/proc_other.go b/internal/macos/installer/proc_other.go similarity index 100% rename from internal/installer/proc_other.go rename to internal/macos/installer/proc_other.go diff --git a/internal/installer/proc_windows.go b/internal/macos/installer/proc_windows.go similarity index 100% rename from internal/installer/proc_windows.go rename to internal/macos/installer/proc_windows.go diff --git a/internal/installguide/appearance_windows.go b/internal/macos/installguide/appearance_windows.go similarity index 100% rename from internal/installguide/appearance_windows.go rename to internal/macos/installguide/appearance_windows.go diff --git a/internal/installguide/dialog_windows.go b/internal/macos/installguide/dialog_windows.go similarity index 100% rename from internal/installguide/dialog_windows.go rename to internal/macos/installguide/dialog_windows.go diff --git a/internal/installguide/guide.go b/internal/macos/installguide/guide.go similarity index 100% rename from internal/installguide/guide.go rename to internal/macos/installguide/guide.go diff --git a/internal/installguide/manager.go b/internal/macos/installguide/manager.go similarity index 100% rename from internal/installguide/manager.go rename to internal/macos/installguide/manager.go diff --git a/internal/installguide/manager_test.go b/internal/macos/installguide/manager_test.go similarity index 100% rename from internal/installguide/manager_test.go rename to internal/macos/installguide/manager_test.go diff --git a/internal/installguide/overlay_other.go b/internal/macos/installguide/overlay_other.go similarity index 100% rename from internal/installguide/overlay_other.go rename to internal/macos/installguide/overlay_other.go diff --git a/internal/installguide/overlay_windows.go b/internal/macos/installguide/overlay_windows.go similarity index 100% rename from internal/installguide/overlay_windows.go rename to internal/macos/installguide/overlay_windows.go diff --git a/internal/installguide/overlay_windows_test.go b/internal/macos/installguide/overlay_windows_test.go similarity index 99% rename from internal/installguide/overlay_windows_test.go rename to internal/macos/installguide/overlay_windows_test.go index 6477dc2..48bc31b 100644 --- a/internal/installguide/overlay_windows_test.go +++ b/internal/macos/installguide/overlay_windows_test.go @@ -245,8 +245,8 @@ func TestOverlayOfficialZhTWAndJaJPLanguagePacksFit(t *testing.T) { return m } - twDir := filepath.Join("..", "plugin", "testdata", "official.lang.zh-tw", "locales") - jaDir := filepath.Join("..", "plugin", "testdata", "official.lang.ja-jp", "locales") + twDir := filepath.Join("..", "..", "plugin", "testdata", "official.lang.zh-tw", "locales") + jaDir := filepath.Join("..", "..", "plugin", "testdata", "official.lang.ja-jp", "locales") i18n.SetPluginCatalogs(map[i18n.Locale]i18n.PluginCatalog{ "zh-TW": { Fallback: i18n.ZhCN, diff --git a/internal/installguide/picker_windows.go b/internal/macos/installguide/picker_windows.go similarity index 100% rename from internal/installguide/picker_windows.go rename to internal/macos/installguide/picker_windows.go diff --git a/internal/installguide/progress.go b/internal/macos/installguide/progress.go similarity index 100% rename from internal/installguide/progress.go rename to internal/macos/installguide/progress.go diff --git a/internal/installguide/session_windows.go b/internal/macos/installguide/session_windows.go similarity index 100% rename from internal/installguide/session_windows.go rename to internal/macos/installguide/session_windows.go diff --git a/internal/installguide/session_windows_test.go b/internal/macos/installguide/session_windows_test.go similarity index 100% rename from internal/installguide/session_windows_test.go rename to internal/macos/installguide/session_windows_test.go diff --git a/internal/driver/reims_adapter.go b/internal/macos/macosdriver/driver.go similarity index 76% rename from internal/driver/reims_adapter.go rename to internal/macos/macosdriver/driver.go index 066e58e..f3f15a4 100644 --- a/internal/driver/reims_adapter.go +++ b/internal/macos/macosdriver/driver.go @@ -1,4 +1,4 @@ -package driver +package macosdriver import ( "context" @@ -7,26 +7,27 @@ import ( "io" "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/macos/reims" "github.com/Nwflower/reims-go/internal/plugin" rt "github.com/Nwflower/reims-go/internal/runtime" ) // ReimsMacOSCapabilities lists all capabilities supported by builtin.driver.reims-macos. var ReimsMacOSCapabilities = []string{ - CapSnapshot, - CapCowClone, - CapResize, - CapQMP, - CapSSH, - CapGuestTools, - CapAffinity, - CapOpenCore, - CapRecovery, + driver.CapSnapshot, + driver.CapCowClone, + driver.CapResize, + driver.CapQMP, + driver.CapSSH, + driver.CapGuestTools, + driver.CapAffinity, + driver.CapOpenCore, + driver.CapRecovery, } -// ReimsMacOSDriver adapts internal/driver/reims into the generic Driver interface +// ReimsMacOSDriver adapts internal/macos/reims into the generic driver.Driver interface // as the compiled-in `builtin.driver.reims-macos` extension (§3.2, §5.3). type ReimsMacOSDriver struct { getConfig func() config.Config @@ -37,7 +38,7 @@ func NewReimsMacOSDriver(getConfig func() config.Config) *ReimsMacOSDriver { return &ReimsMacOSDriver{getConfig: getConfig} } -func (d *ReimsMacOSDriver) ID() string { return BuiltinReimsMacOSDriverID } +func (d *ReimsMacOSDriver) ID() string { return driver.BuiltinReimsMacOSDriverID } func (d *ReimsMacOSDriver) DisplayName() plugin.LocalizedText { return plugin.LocalizedText{ZhCN: "macOS (Reims vGPU)", EnUS: "macOS (Reims vGPU)"} @@ -67,7 +68,7 @@ func (d *ReimsMacOSDriver) client() (*reims.Client, error) { return reims.NewClient(&cfg, *active), nil } -func (d *ReimsMacOSDriver) List(ctx context.Context) ([]VMInfo, error) { +func (d *ReimsMacOSDriver) List(ctx context.Context) ([]driver.VMInfo, error) { c, err := d.client() if err != nil { return nil, err @@ -76,9 +77,9 @@ func (d *ReimsMacOSDriver) List(ctx context.Context) ([]VMInfo, error) { if err != nil { return nil, err } - out := make([]VMInfo, 0, len(items)) + out := make([]driver.VMInfo, 0, len(items)) for _, it := range items { - out = append(out, VMInfo{ + out = append(out, driver.VMInfo{ Name: it.Name, DriverID: d.ID(), DriverName: "macOS (Reims vGPU)", @@ -90,19 +91,19 @@ func (d *ReimsMacOSDriver) List(ctx context.Context) ([]VMInfo, error) { return out, nil } -func (d *ReimsMacOSDriver) Show(ctx context.Context, name string) (VMInfo, error) { +func (d *ReimsMacOSDriver) Show(ctx context.Context, name string) (driver.VMInfo, error) { c, err := d.client() if err != nil { - return VMInfo{}, err + return driver.VMInfo{}, err } det, err := c.Show(ctx, name) if err != nil { - return VMInfo{}, err + return driver.VMInfo{}, err } rawBytes, _ := json.Marshal(det) var data map[string]any _ = json.Unmarshal(rawBytes, &data) - return VMInfo{ + return driver.VMInfo{ Name: det.Name, DriverID: d.ID(), DriverName: "macOS (Reims vGPU)", @@ -116,10 +117,10 @@ func (d *ReimsMacOSDriver) Show(ctx context.Context, name string) (VMInfo, error }, nil } -func (d *ReimsMacOSDriver) ValidateCreate(_ context.Context, req CreateRequest) []ValidationIssue { +func (d *ReimsMacOSDriver) ValidateCreate(_ context.Context, req driver.CreateRequest) []driver.ValidationIssue { var opts reims.CreateOpts if err := decodeMap(req.Options, &opts); err != nil { - return []ValidationIssue{{Field: "options", Message: err.Error()}} + return []driver.ValidationIssue{{Field: "options", Message: err.Error()}} } if opts.Name == "" { opts.Name = req.Name @@ -130,14 +131,14 @@ func (d *ReimsMacOSDriver) ValidateCreate(_ context.Context, req CreateRequest) cfg := d.getConfig() rep := host.Inspect(cfg.DataRoot) issues := reims.ValidateCreateLocalized(opts, rep, cfg.Locale) - out := make([]ValidationIssue, 0, len(issues)) + out := make([]driver.ValidationIssue, 0, len(issues)) for _, is := range issues { - out = append(out, ValidationIssue{Field: is.Field, Message: is.Message}) + out = append(out, driver.ValidationIssue{Field: is.Field, Message: is.Message}) } return out } -func (d *ReimsMacOSDriver) Create(ctx context.Context, req CreateRequest, stdout, stderr io.Writer) error { +func (d *ReimsMacOSDriver) Create(ctx context.Context, req driver.CreateRequest, stdout, stderr io.Writer) error { c, err := d.client() if err != nil { return err @@ -155,10 +156,10 @@ func (d *ReimsMacOSDriver) Create(ctx context.Context, req CreateRequest, stdout return c.Create(ctx, opts, stdout, stderr) } -func (d *ReimsMacOSDriver) ValidateSet(ctx context.Context, req SetRequest) []ValidationIssue { +func (d *ReimsMacOSDriver) ValidateSet(ctx context.Context, req driver.SetRequest) []driver.ValidationIssue { var opts reims.SetOpts if err := decodeMap(req.Changes, &opts); err != nil { - return []ValidationIssue{{Field: "changes", Message: err.Error()}} + return []driver.ValidationIssue{{Field: "changes", Message: err.Error()}} } opts.Name = req.Name var cur reims.VMDetail @@ -170,14 +171,14 @@ func (d *ReimsMacOSDriver) ValidateSet(ctx context.Context, req SetRequest) []Va cfg := d.getConfig() rep := host.Inspect(cfg.DataRoot) issues := reims.ValidateSetLocalized(opts, cur, rep, cfg.Locale) - out := make([]ValidationIssue, 0, len(issues)) + out := make([]driver.ValidationIssue, 0, len(issues)) for _, is := range issues { - out = append(out, ValidationIssue{Field: is.Field, Message: is.Message}) + out = append(out, driver.ValidationIssue{Field: is.Field, Message: is.Message}) } return out } -func (d *ReimsMacOSDriver) Set(ctx context.Context, req SetRequest, stdout, stderr io.Writer) error { +func (d *ReimsMacOSDriver) Set(ctx context.Context, req driver.SetRequest, stdout, stderr io.Writer) error { c, err := d.client() if err != nil { return err diff --git a/internal/opencore/image.go b/internal/macos/opencore/image.go similarity index 100% rename from internal/opencore/image.go rename to internal/macos/opencore/image.go diff --git a/internal/opencore/lang.go b/internal/macos/opencore/lang.go similarity index 100% rename from internal/opencore/lang.go rename to internal/macos/opencore/lang.go diff --git a/internal/opencore/opencore_test.go b/internal/macos/opencore/opencore_test.go similarity index 100% rename from internal/opencore/opencore_test.go rename to internal/macos/opencore/opencore_test.go diff --git a/internal/opencore/plist.go b/internal/macos/opencore/plist.go similarity index 100% rename from internal/opencore/plist.go rename to internal/macos/opencore/plist.go diff --git a/internal/opencore/proc_other.go b/internal/macos/opencore/proc_other.go similarity index 100% rename from internal/opencore/proc_other.go rename to internal/macos/opencore/proc_other.go diff --git a/internal/opencore/proc_windows.go b/internal/macos/opencore/proc_windows.go similarity index 100% rename from internal/opencore/proc_windows.go rename to internal/macos/opencore/proc_windows.go diff --git a/internal/driver/reims/compat.go b/internal/macos/reims/compat.go similarity index 100% rename from internal/driver/reims/compat.go rename to internal/macos/reims/compat.go diff --git a/internal/driver/reims/compat_test.go b/internal/macos/reims/compat_test.go similarity index 100% rename from internal/driver/reims/compat_test.go rename to internal/macos/reims/compat_test.go diff --git a/internal/driver/reims/disk_import.go b/internal/macos/reims/disk_import.go similarity index 100% rename from internal/driver/reims/disk_import.go rename to internal/macos/reims/disk_import.go diff --git a/internal/driver/reims/disk_ops_test.go b/internal/macos/reims/disk_ops_test.go similarity index 100% rename from internal/driver/reims/disk_ops_test.go rename to internal/macos/reims/disk_ops_test.go diff --git a/internal/driver/reims/helper_args.go b/internal/macos/reims/helper_args.go similarity index 100% rename from internal/driver/reims/helper_args.go rename to internal/macos/reims/helper_args.go diff --git a/internal/driver/reims/proc_other.go b/internal/macos/reims/proc_other.go similarity index 100% rename from internal/driver/reims/proc_other.go rename to internal/macos/reims/proc_other.go diff --git a/internal/driver/reims/proc_windows.go b/internal/macos/reims/proc_windows.go similarity index 100% rename from internal/driver/reims/proc_windows.go rename to internal/macos/reims/proc_windows.go diff --git a/internal/driver/reims/redact.go b/internal/macos/reims/redact.go similarity index 100% rename from internal/driver/reims/redact.go rename to internal/macos/reims/redact.go diff --git a/internal/driver/reims/reims.go b/internal/macos/reims/reims.go similarity index 99% rename from internal/driver/reims/reims.go rename to internal/macos/reims/reims.go index 17dcc5d..79ca515 100644 --- a/internal/driver/reims/reims.go +++ b/internal/macos/reims/reims.go @@ -15,7 +15,7 @@ import ( "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/opencore" + "github.com/Nwflower/reims-go/internal/macos/opencore" rt "github.com/Nwflower/reims-go/internal/runtime" ) diff --git a/internal/driver/reims/reims_test.go b/internal/macos/reims/reims_test.go similarity index 100% rename from internal/driver/reims/reims_test.go rename to internal/macos/reims/reims_test.go diff --git a/internal/driver/reims/snapshot.go b/internal/macos/reims/snapshot.go similarity index 100% rename from internal/driver/reims/snapshot.go rename to internal/macos/reims/snapshot.go diff --git a/internal/plugin/builtin/builtin.go b/internal/plugin/builtin/builtin.go index 86e3cf0..7770590 100644 --- a/internal/plugin/builtin/builtin.go +++ b/internal/plugin/builtin/builtin.go @@ -12,9 +12,9 @@ import ( "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/guesttools" "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/internal/version" ) diff --git a/internal/plugin/builtin/builtin_test.go b/internal/plugin/builtin/builtin_test.go index dafe8c8..e99ad11 100644 --- a/internal/plugin/builtin/builtin_test.go +++ b/internal/plugin/builtin/builtin_test.go @@ -8,7 +8,7 @@ import ( "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/guesttools" "github.com/Nwflower/reims-go/internal/host" - "github.com/Nwflower/reims-go/internal/installguide" + "github.com/Nwflower/reims-go/internal/macos/installguide" "github.com/Nwflower/reims-go/internal/plugin" ) diff --git a/internal/plugin/builtin/core.go b/internal/plugin/builtin/core.go index f7bceb0..64df4d8 100644 --- a/internal/plugin/builtin/core.go +++ b/internal/plugin/builtin/core.go @@ -7,10 +7,11 @@ import ( "strings" "github.com/Nwflower/reims-go/internal/driver" - "github.com/Nwflower/reims-go/internal/driver/reims" "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/macos/installer" + "github.com/Nwflower/reims-go/internal/macos/macosdriver" + "github.com/Nwflower/reims-go/internal/macos/opencore" + "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/internal/qmp" rt "github.com/Nwflower/reims-go/internal/runtime" @@ -177,7 +178,7 @@ func defCore(ver string, cb HostCallbacks) plugin.PluginDef { Trust: plugin.TrustOfficial, System: true, Activate: func(_ context.Context, sc *plugin.Scope) error { - drv := driver.NewReimsMacOSDriver(cb.GetConfig) + drv := macosdriver.NewReimsMacOSDriver(cb.GetConfig) sc.Registry().RegisterGuestDriver(sc, IDDriverReimsMacOS, drv) hooks := sc.Registry().Hooks() diff --git a/internal/plugin/builtin/install_guide.go b/internal/plugin/builtin/install_guide.go index f617213..cd19eca 100644 --- a/internal/plugin/builtin/install_guide.go +++ b/internal/plugin/builtin/install_guide.go @@ -3,7 +3,7 @@ package builtin import ( "context" - "github.com/Nwflower/reims-go/internal/installguide" + "github.com/Nwflower/reims-go/internal/macos/installguide" "github.com/Nwflower/reims-go/internal/plugin" ) diff --git a/internal/plugin/manager_sidecar_test.go b/internal/plugin/manager_sidecar_test.go index 345c8d6..f91aa4d 100644 --- a/internal/plugin/manager_sidecar_test.go +++ b/internal/plugin/manager_sidecar_test.go @@ -19,7 +19,7 @@ import ( "time" "github.com/Nwflower/reims-go/internal/driver" - "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/pkg/pluginsdk" ) diff --git a/internal/vmstart/vmstart.go b/internal/vmstart/vmstart.go index 6f85da2..7efc27a 100644 --- a/internal/vmstart/vmstart.go +++ b/internal/vmstart/vmstart.go @@ -19,11 +19,11 @@ 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/i18n" - "github.com/Nwflower/reims-go/internal/installer" - "github.com/Nwflower/reims-go/internal/opencore" + "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" ) diff --git a/patches/README.md b/patches/README.md index 67677b0..ac6decd 100644 --- a/patches/README.md +++ b/patches/README.md @@ -114,7 +114,7 @@ | `#123` 窗口体验 | `Ctrl+Alt+Enter` 运行中热切全屏 | 同步界面快捷键提示 | | `#172` 窗口体验 | Windows 拖动窗口动态贴合,消除缩放黑边 | 验证多显示器与高 DPI 缩放 | | `Win → Command` | 自由指针模式下 Windows 键映射 macOS Command | 合入后移除前端相关提示 | -| `reims-util` 语言参数 | 支持 `opencore --lang` 并在重建 OpenCore 时保留 `prev-lang:kbd` | 合入后可逐步简化本仓 `internal/opencore` 补丁重写 | +| `reims-util` 语言参数 | 支持 `opencore --lang` 并在重建 OpenCore 时保留 `prev-lang:kbd` | 合入后可逐步简化本仓 `internal/macos/opencore` 补丁重写 | --- From 2ffddf94b4c2e40bc53b66499728496009ff1bda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Mon, 30 Nov 2026 06:58:32 -0700 Subject: [PATCH 02/42] docs(plugins): plan guest migration and macOS extraction --- AGENTS.md | 1 + docs/guest-plugin-migration.md | 272 +++++++++++++++++++++++++++++++++ docs/plugin-architecture.md | 6 + 3 files changed, 279 insertions(+) create mode 100644 docs/guest-plugin-migration.md diff --git a/AGENTS.md b/AGENTS.md index 266b695..4b2eb8f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,4 +71,5 @@ - [`docs/design-guidelines.md`](docs/design-guidelines.md) — 产品与界面设计规范(配置原语、状态模型、视觉与文案) - [`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 剥离的迁移路径 - [`patches/README.md`](patches/README.md) — 上游临时补丁队列与 PR 跟踪 diff --git a/docs/guest-plugin-migration.md b/docs/guest-plugin-migration.md new file mode 100644 index 0000000..91284e3 --- /dev/null +++ b/docs/guest-plugin-migration.md @@ -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 目录只有一个根 | 路由与"驱动不可用"扫描只看 `/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`,旧版本以该 ID 记下的插件状态由 v2 迁移按旧插件记录处理。 + +## 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 插件身份与 v2 元数据迁移 + +- 新增内置插件 `builtin.guest.macos`,注册代码放在 `internal/macos/` 内,由组装入口注册。`builtin.core` 只保留与客体无关的部分(默认主题、宿主体检等)。 +- **安装引导并入**:`builtin.install-guide` 并入 `builtin.guest.macos`,成为它的一个可开关功能;旧 ID 退役,用户原来的启用状态转为新插件的对应设置。外部 macOS 插件因此只是一个包。 +- **静态声明驱动**:新插件在清单 `guestDrivers` 中静态声明 `builtin.driver.reims-macos`,使用中检查才能阻止在仍有 macOS VM 运行时停用它。 +- **设置迁移**:`whpx_fallback`、`win10_cold_reboot` 从 `builtin.core` 转给新插件,合并顺序为"新插件显式值 → 旧插件显式值 → 默认值"。 +- **参数账本迁移**:每台 VM 的账本中,只把已知由 macOS 启动步骤写入的条目转给新插件;用户手动参数与其他插件的条目保持原所有者。无账本的旧 VM(老版本或 CLI 直接启动过)由 `stripLegacyManagedExtraArgs` 兜底,该函数随之迁入 macOS 代码。 +- **迁移方式**:在写锁下先备份受影响的小文件,一次替换 `state.json`,各步可重复执行,全部校验通过后才写版本戳 v2。VM 目录、磁盘、快照、CoW 父盘与 `vm.toml` 不移动。 +- **反向棘轮**:新增"`internal/macos/` 只能导入列入清单的宿主包"的测试,清单从现状开始,只减不增。 + +**验收** +- 从 v0.2.x 直升:用户关闭过的兼容选项与安装引导开关保持原值,手动设置的 `kernel-irqchip` 仍优先。 +- 迁移中途退出后重启,迁移可继续,结果与一次完成相同。 +- 同一台 VM 连续启动两次,参数不重复追加,辅助盘不重复挂载。 + +### 步骤 2:VM 引用与启动链路 + +**2a. `VMRef` 贯穿宿主**(原计划在步骤 3,提前是因为统一启动入口就要按归属解析 VM) + +- 引入 `VMRef{DriverID, Name}`;`Router.ResolveVM` 遇到多个同名结果时返回歧义错误;`ListAllVMs` 不再按名称去重。 +- 驱动在清单中声明 VM 根目录(第 3 节),路由与"驱动不可用"扫描遍历所有已声明的根。 +- 宿主内存态、Guest Tools 注册表、缩略图与键入锁、日志来源改为按 `VMRef` 索引;对客体已经暴露的访问路径保留兼容。 +- `PluginRecord.VMSettings` 的键改为 `VMRef` 的规范字符串,随版本 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/`。 +- **拆分调优判定**:宿主只报告探测事实;驱动针对选中的 VM 结合运行时能力给出建议,设置页与实际启动共用同一份判定。`kernel-irqchip`、WHPX 兼容降级与冷重启补偿的策略归 macOS 驱动。 + +**验收** +- 升级后用原有 macOS VM 验证:恢复引导、离线辅助盘、引导语言、冷重启监视、Guest Tools 与升级前行为一致;按 VM 的插件设置不丢失。 +- 第三方插件否决启动时,VM 目录与 OpenCore 镜像未被修改。 +- 测试驱动在相同宿主探测结果下,不会收到 OpenCore、辅助盘或冷重启参数。 + +### 步骤 3:其余入口统一路由 + +- **后端**: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与 v2 迁移"] + 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`(源码与测试) | 步骤 1:macOS 注册迁入 `internal/macos/` | +| `internal/vmstart` | 步骤 2:宿主部分与 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 插件是否默认启用**:默认启用可保证升级无感;默认关闭更贴近剥离方向,但存量用户升级后会看到"驱动不可用"。 + +可在后续步骤前决定: + +4. **多运行时未选定时的行为**(步骤 3.5):建议只读操作临时使用最新安装的运行时、不写回配置,启动与创建前要求选定。 +5. **降级支持**(步骤 0 发布前):可安全退回的最低版本,以及只读模式的提示文案。 +6. **剥离范围**(步骤 5):法律风险具体涉及哪些内容(OpenCore 与 SMBIOS 处理、Apple 安装包下载、产品定位中的 macOS 字样、reims-vgpu 运行时),决定迁出清单的范围。 +7. **官方市场是否上架 macOS 插件**(步骤 5):上架方便用户,但官方索引仍与 macOS 产生关联。 +8. **代码历史**(步骤 5):只删除当前代码,还是让主程序以新仓库重新开始历史、本仓库保留为 macOS 插件仓库。 diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index b951b39..89167e5 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -107,6 +107,8 @@ flowchart TB 扩展点先由内置功能使用一遍再对外开放。内置功能分两类,判断标准是用户关掉它之后,是「少了一项功能」还是「已有功能坏掉」: - **核心** `builtin.core`:Reims-Go 离开它就无法运行 macOS 虚拟机的部分,包括 reims 驱动(驱动 id 仍为 `builtin.driver.reims-macos`)、默认主题(主题 id 仍为 `builtin.theme.default`)、启动准备(离线辅助盘、恢复模式引导切换、引导语言重放)与宿主兼容补偿(WHPX 降级、Win10 冷重启)。它是**系统插件**:始终启用,不能停用或卸载,插件页显示为一行「始终启用」,不参与「使用中」检查。两项兼容补偿作为核心的应用级设置保留开关,仅供排障。启动准备在同一个 `vm.beforeStart` 处理器里按固定顺序执行,引导语言重放必须在恢复模式切换(可能重建 OpenCore)之后。 + +> 迁移中:macOS 相关部分(reims 驱动、两项兼容补偿与启动准备)将迁出核心,成为内置插件 `builtin.guest.macos` 并最终外置;启动准备改由驱动自己执行,不再经 `vm.beforeStart`。见 [guest-plugin-migration.md](guest-plugin-migration.md) 步骤 1–2。 - **可选内置扩展**:Guest Tools 传输服务、剪贴板互通、宿主输入服务、虚拟机窗口安装引导。经同一注册表注册、可独立启停、停用后零残留,停用即真正停止(不被其他调用方重新拉起)。首批示例为默认开启的剪贴板互通(见 §5.4)。 核心由曾经拆开的七个内置插件合并而来(`builtin.RetiredIDs`)。启动时删除 `state.json` 中这些旧 ID 的记录,关闭过的兼容补偿转为对应的核心设置;启动 VM 时,参数归属账本中旧 ID 名下的片段移交给核心,继续沿用而不是被当作已卸载插件的残留剥离。 @@ -272,6 +274,8 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card` | `builtin.install-guide` | `internal/macos/installguide`、`internal/app/install_guide.go` | 提供 `ui.install-guide` 服务 + `vm.afterStop` / `vm.deleted` 观察钩子;在虚拟机窗口悬浮展示安装与恢复引导,停用时立即关闭全部浮层并回退主界面恢复卡片 | | `builtin.core`(系统插件) | `macos/macosdriver`、`vmstart.Prepare` 各步骤、`app.go` 冷重启监视 | `guestDrivers` + `themes` + `host.preflight` + 一个按序执行全部启动准备的 `vm.beforeStart`(离线辅助盘 → 恢复模式引导 → 引导语言 → WHPX 降级 → Win10 冷重启)+ `vm.afterStart` / `vm.afterStop`(冷重启监视);设置 `whpx_fallback`、`win10_cold_reboot` | +> 迁移中:`builtin.install-guide` 将并入 `builtin.guest.macos`,`builtin.core` 中的 macOS 驱动与启动准备随之迁出;Guest Tools 的 macOS 客体代理与辅助盘镜像迁入 macOS 插件,传输服务留在宿主。见 [guest-plugin-migration.md](guest-plugin-migration.md) 步骤 1–2。 + ### 5.5 与上游补丁队列的边界 | 类别 | 归属 | 原则 | @@ -420,6 +424,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)"] From 6dcf33f71b6d25cd2f8d23afd383e3d59ceb7fd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Mon, 30 Nov 2026 06:58:32 -0700 Subject: [PATCH 03/42] feat(dataroot): guard data folder writes and migrations --- docs/architecture.md | 4 +- frontend/src/App.tsx | 16 +- frontend/src/components/DataRootReadOnly.tsx | 89 ++++++++++ frontend/src/i18n/domains/core.gen.ts | 14 ++ frontend/src/i18n/keys.gen.ts | 7 + frontend/src/styles/app.css | 8 + frontend/wailsjs/go/app/App.d.ts | 3 + frontend/wailsjs/go/app/App.js | 4 + frontend/wailsjs/go/models.ts | 33 ++++ internal/app/app.go | 59 +++++-- internal/app/appupdate_flow.go | 9 +- internal/app/dataroot_flow.go | 122 ++++++++++++++ internal/app/dataroot_flow_test.go | 90 +++++++++++ internal/app/plugins_flow.go | 19 ++- internal/app/runtime_bindings.go | 6 +- internal/app/setup.go | 23 ++- internal/app/ui_health.go | 5 + internal/cli/cli.go | 23 ++- internal/config/config.go | 22 ++- internal/config/config_test.go | 20 +++ internal/datamigrate/datamigrate.go | 20 ++- internal/datamigrate/datamigrate_test.go | 23 ++- internal/dataroot/dataroot.go | 157 ++++++++++++++++++ internal/dataroot/dataroot_test.go | 162 +++++++++++++++++++ internal/filelock/filelock.go | 48 ++++++ internal/filelock/lock_other.go | 25 +++ internal/filelock/lock_windows.go | 33 ++++ internal/i18n/catalog_gen.go | 28 ++++ internal/macos/installer/installer.go | 9 +- internal/macos/installer/proc_other.go | 23 +-- internal/macos/installer/proc_windows.go | 29 ---- internal/plugin/builtin/core.go | 24 ++- internal/plugin/manager.go | 37 ++++- locales/en-US/core.json | 9 +- locales/en-US/native.json | 7 +- locales/zh-CN/core.json | 9 +- locales/zh-CN/native.json | 7 +- main.go | 6 + 38 files changed, 1104 insertions(+), 128 deletions(-) create mode 100644 frontend/src/components/DataRootReadOnly.tsx create mode 100644 internal/app/dataroot_flow.go create mode 100644 internal/app/dataroot_flow_test.go create mode 100644 internal/dataroot/dataroot.go create mode 100644 internal/dataroot/dataroot_test.go create mode 100644 internal/filelock/filelock.go create mode 100644 internal/filelock/lock_other.go create mode 100644 internal/filelock/lock_windows.go diff --git a/docs/architecture.md b/docs/architecture.md index a31641c..8b2f383 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -113,7 +113,9 @@ flowchart TB ### 4.7 数据目录版本与迁移 - `\.reims-go-data.json` 记录数据布局版本 `data_version`,以及最后一次提升它的应用版本 `written_by`。它不放进 `reims-go.json`,因为配置每次保存都会按结构体整体重写,旧版本会丢掉不认识的字段。 - 每个版本都带着从旧布局升到自身布局的全部迁移步骤(`internal/datamigrate`),GUI 与 CLI 启动时、读取数据之前按版本号依次执行。步骤必须可重复执行;某步失败时,版本号停在最后一个成功的步骤,下次启动从那里继续。用户可以从任意旧版本直接升到新版本。 -- 数据目录的版本高于本程序所知时(降级运行),不做任何改动,只记一条日志。 +- GUI 启动、首次设置、切换数据目录与 CLI 都经 `internal/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 归属」。 diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 7404660..3342ddc 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -9,6 +9,7 @@ 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' @@ -446,6 +447,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' @@ -859,7 +863,7 @@ export const App: React.FC = () => { const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {}) shortcutRef.current = (e: KeyboardEvent) => { if (!e.ctrlKey || e.altKey || e.metaKey) return - if (showSetup || showWizard || showSettings || affinityTarget || deleteTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate) return + if (showSetup || showReadOnly || showWizard || showSettings || affinityTarget || deleteTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate) return if (document.querySelector('[role="dialog"], [role="alertdialog"]')) return const k = e.key.toLowerCase() if (k === 'n') { e.preventDefault(); openWizard() } @@ -929,7 +933,7 @@ export const App: React.FC = () => {
WindowToggleMaximise()}> - {showSetup || !state ? ( + {showSetup || showReadOnly || !state ? (
Reims-Go @@ -1009,6 +1013,14 @@ export const App: React.FC = () => { onImportRuntime={importRuntime} /> + ) : showReadOnly && state ? ( + { void refresh() }} + onError={fail} + /> ) : (
{sidebarOpen && +
+
+
{tr('syncHostMemorySMBIOS')}
+
+ {memSpecLabel + ? tr('syncHostMemorySMBIOSSub', { spec: memSpecLabel }) + : tr('syncHostMemorySMBIOSUnavailable')} +
+
+
+ guard(() => api.SetSyncHostMemorySMBIOS(checked))()} + /> +
+
{tr('minimizeToTray')}
diff --git a/frontend/src/components/HostView.tsx b/frontend/src/components/HostView.tsx index 50d780f..6b0fef0 100644 --- a/frontend/src/components/HostView.tsx +++ b/frontend/src/components/HostView.tsx @@ -135,7 +135,12 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onNewVM, o {tr('hostRAM')}
{tr('hostRAMAvail', { n: host.avail_ram_gb.toFixed(1) })}
-
{tr('hostRAMTotal', { n: host.total_ram_gb.toFixed(1) })}
+
+ {tr('hostRAMTotal', { n: host.total_ram_gb.toFixed(1) })} + {host.memory_spec?.speed_mhz + ? ` · ${host.memory_spec.speed_mhz} MHz${host.memory_spec.type_name ? ` ${host.memory_spec.type_name}` : ''}` + : ''} +
diff --git a/frontend/src/i18n/domains/settings.gen.ts b/frontend/src/i18n/domains/settings.gen.ts index 3a65bcd..effba80 100644 --- a/frontend/src/i18n/domains/settings.gen.ts +++ b/frontend/src/i18n/domains/settings.gen.ts @@ -293,6 +293,9 @@ export const settingsZh: Record = { "storageInstallers": "安装包", "storageRuntimes": "Reims-Go", "storageVMs": "虚拟机文件", + "syncHostMemorySMBIOS": "同步宿主机内存规格", + "syncHostMemorySMBIOSSub": "在 macOS「关于本机」中显示宿主机真实内存频率与代数(当前:{spec}),下次启动生效", + "syncHostMemorySMBIOSUnavailable": "未能从宿主机 SMBIOS 读取物理内存频率,虚拟机将保持默认的 2666 MHz DDR4", "themeLabel": "外观", "themePluginDarkDisabled": "默认主题插件已停用,深色与跟随系统外观不可用", "themePluginLightDisabled": "当前主题仅支持深色外观", @@ -610,6 +613,9 @@ export const settingsEn: Record = { "storageInstallers": "Installers", "storageRuntimes": "Reims-Go", "storageVMs": "VM files", + "syncHostMemorySMBIOS": "Sync host memory specs", + "syncHostMemorySMBIOSSub": "Show the host's actual memory speed and generation ({spec}) in macOS About This Mac; applies on next start", + "syncHostMemorySMBIOSUnavailable": "Could not read host SMBIOS memory speed; VMs keep the default 2666 MHz DDR4", "themeLabel": "Appearance", "themePluginDarkDisabled": "Default theme plugin is disabled; dark and system appearances are unavailable", "themePluginLightDisabled": "The active theme supports dark appearance only", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 9ee8854..07d8a92 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -792,6 +792,9 @@ export type I18nKey = | "suspendedNoticeDescWithTime" | "suspendedNoticeTitle" | "suspendedSettingsHint" + | "syncHostMemorySMBIOS" + | "syncHostMemorySMBIOSSub" + | "syncHostMemorySMBIOSUnavailable" | "taskAppUpdate" | "taskCreate" | "taskDownload" diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index ded8dce..f9f863d 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -47,8 +47,6 @@ export function DeleteSnapshot(arg1:string,arg2:string):Promise; export function DeleteVM(arg1:string,arg2:boolean):Promise; -export function DiscardSuspend(arg1:string):Promise; - export function DeliverFileToGuest(arg1:string):Promise; export function DeliverPathsToGuest(arg1:string,arg2:Array):Promise>; @@ -57,6 +55,8 @@ export function DetachGuestTools(arg1:string):Promise; export function DisablePlugin(arg1:string):Promise; +export function DiscardSuspend(arg1:string):Promise; + export function DismissTask(arg1:string):Promise; export function DoctorPlugin(arg1:string):Promise>; @@ -185,10 +185,10 @@ export function ResizeVMDisk(arg1:string,arg2:string):Promise; -export function ResumeVM(arg1:string):Promise; - export function RestoreSnapshot(arg1:string,arg2:string):Promise; +export function ResumeVM(arg1:string):Promise; + export function SaveCustomThemeScheme(arg1:plugin.CustomThemeScheme):Promise; export function ScanInstalledPlugin(arg1:string):Promise; @@ -211,6 +211,8 @@ export function SetPluginSettings(arg1:string,arg2:string,arg3:Record; +export function SetSyncHostMemorySMBIOS(arg1:boolean):Promise; + export function SetVMAffinity(arg1:string,arg2:app.VMAffinityUpdate):Promise; export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array):Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index da78976..b257eb9 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -78,10 +78,6 @@ 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 DeliverFileToGuest(arg1) { return window['go']['app']['App']['DeliverFileToGuest'](arg1); } @@ -98,6 +94,10 @@ export function DisablePlugin(arg1) { return window['go']['app']['App']['DisablePlugin'](arg1); } +export function DiscardSuspend(arg1) { + return window['go']['app']['App']['DiscardSuspend'](arg1); +} + export function DismissTask(arg1) { return window['go']['app']['App']['DismissTask'](arg1); } @@ -354,14 +354,14 @@ export function RestartVM(arg1) { return window['go']['app']['App']['RestartVM'](arg1); } -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 ResumeVM(arg1) { + return window['go']['app']['App']['ResumeVM'](arg1); +} + export function SaveCustomThemeScheme(arg1) { return window['go']['app']['App']['SaveCustomThemeScheme'](arg1); } @@ -406,6 +406,10 @@ export function SetRuntimeChannel(arg1) { return window['go']['app']['App']['SetRuntimeChannel'](arg1); } +export function SetSyncHostMemorySMBIOS(arg1) { + return window['go']['app']['App']['SetSyncHostMemorySMBIOS'](arg1); +} + export function SetVMAffinity(arg1, arg2) { return window['go']['app']['App']['SetVMAffinity'](arg1, arg2); } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 7d181bf..779b257 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -473,6 +473,7 @@ export namespace config { runtime_channel?: string; app_update_channel?: string; minimize_to_tray?: boolean; + sync_host_memory_smbios?: boolean; static createFrom(source: any = {}) { return new Config(source); @@ -488,6 +489,7 @@ export namespace config { this.runtime_channel = source["runtime_channel"]; this.app_update_channel = source["app_update_channel"]; this.minimize_to_tray = source["minimize_to_tray"]; + this.sync_host_memory_smbios = source["sync_host_memory_smbios"]; } } @@ -674,6 +676,22 @@ export namespace host { this.compat_detail = source["compat_detail"]; } } + export class HostMemorySpec { + speed_mhz?: number; + memory_type?: number; + type_name?: string; + + static createFrom(source: any = {}) { + return new HostMemorySpec(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.speed_mhz = source["speed_mhz"]; + this.memory_type = source["memory_type"]; + this.type_name = source["type_name"]; + } + } export class LogicalCPUInfo { index: number; core_index: number; @@ -752,6 +770,7 @@ export namespace host { total_ram_gb: number; avail_ram_gb: number; memory_load_pct: number; + memory_spec?: HostMemorySpec; commit_avail_gb: number; commit_limit_gb: number; data_root: string; @@ -797,6 +816,7 @@ export namespace host { this.total_ram_gb = source["total_ram_gb"]; this.avail_ram_gb = source["avail_ram_gb"]; this.memory_load_pct = source["memory_load_pct"]; + this.memory_spec = this.convertValues(source["memory_spec"], HostMemorySpec); this.commit_avail_gb = source["commit_avail_gb"]; this.commit_limit_gb = source["commit_limit_gb"]; this.data_root = source["data_root"]; @@ -2437,7 +2457,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; diff --git a/internal/app/app.go b/internal/app/app.go index 9c035eb..6fed07f 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -727,6 +727,13 @@ func (a *App) SetMinimizeToTray(enabled bool) error { return err } +func (a *App) SetSyncHostMemorySMBIOS(enabled bool) error { + a.mu.Lock() + defer a.mu.Unlock() + a.cfg.SyncHostMemorySMBIOS = enabled + return config.Save("", a.cfg) +} + // ShowMainWindow restores and focuses the Wails window from the system tray. func (a *App) ShowMainWindow() { if a.ctx == nil { @@ -908,6 +915,7 @@ func (a *App) SetDataRoot(dir string) error { curRuntimeChannel := a.cfg.RuntimeChannel curAppUpdateChannel := a.cfg.AppUpdateChannel curMinToTray := a.cfg.MinimizeToTray + curSyncHostMemSMBIOS := a.cfg.SyncHostMemorySMBIOS for _, v := range a.lastVMs { if v.State == "running" || v.State == "starting" || v.State == "stopping" || v.State == "suspending" || v.State == "resuming" { a.mu.Unlock() @@ -948,6 +956,7 @@ func (a *App) SetDataRoot(dir string) error { nextCfg.RuntimeChannel = curRuntimeChannel nextCfg.AppUpdateChannel = curAppUpdateChannel nextCfg.MinimizeToTray = curMinToTray + nextCfg.SyncHostMemorySMBIOS = curSyncHostMemSMBIOS } if err := nextCfg.EnsureDirs(); err != nil { return err @@ -1393,24 +1402,6 @@ func (a *App) StartVM(name string) error { // 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: driver.ReimsMacOSCapabilities, - State: curDetail.State, - }) - if blockErr != nil { - a.emitLog(name, "Start blocked: "+blockErr.Error()) - return blockErr - } ledger, ledgerErr := plugin.LoadArgLedger(curDetail.Directory) if ledgerErr != nil { a.emitLog(name, "Warning: could not read arg ledger: "+ledgerErr.Error()) @@ -1421,8 +1412,35 @@ func (a *App) StartVM(name string) error { builtin.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. + // BeforeStartPayload below still sees the original curDetail.ExtraArgs. baseExtraArgs := stripLegacyManagedExtraArgs(curDetail.ExtraArgs) + + rtCaps := prep.Runtime.Manifest.EffectiveCapabilities() + hostFacts := buildHostFacts(rep, rtCaps) + a.mu.Lock() + syncHostMem := a.cfg.SyncHostMemorySMBIOS + a.mu.Unlock() + if syncHostMem && rep.MemorySpec != nil && rep.MemorySpec.SpeedMHz > 0 { + hostFacts["runtime.smbios_memory_type"] = reims.ProbeQEMUSupportsSMBIOSMemoryType(prep.Runtime.QemuPath(), c.Env) + hostFacts["vm.user_has_smbios_type17"] = reims.HasSMBIOSType17Arg(plugin.UserExtraArgs(baseExtraArgs, ledger)) + } + 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: hostFacts, + VMCaps: driver.ReimsMacOSCapabilities, + State: curDetail.State, + }) + if blockErr != nil { + a.emitLog(name, "Start blocked: "+blockErr.Error()) + return blockErr + } reconciled := plugin.ReconcileStartIntents(baseExtraArgs, ledger, mgr.Registry().ActivePluginIDs(), intents) reconciled.Changed = strings.TrimSpace(curDetail.ExtraArgs) != reconciled.ExtraArgs for _, warn := range reconciled.Warnings { diff --git a/internal/app/plugins_flow.go b/internal/app/plugins_flow.go index ec50073..6762905 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -527,7 +527,7 @@ func buildHostFacts(rep host.Report, rtCaps []string) map[string]any { if rep.RecommendedGPU != nil { gpuKind = string(rep.RecommendedGPU.Kind) } - return map[string]any{ + facts := map[string]any{ "host.os": rep.OS, "host.arch": rep.Arch, "host.whpx": string(rep.WHPX), @@ -537,6 +537,13 @@ func buildHostFacts(rep host.Report, rtCaps []string) map[string]any { "host.gpu_kind": gpuKind, "runtime.capabilities": rtCaps, } + if rep.MemorySpec != nil && rep.MemorySpec.SpeedMHz > 0 { + facts["host.memory_speed_mhz"] = rep.MemorySpec.SpeedMHz + if rep.MemorySpec.MemoryType > 0 { + facts["host.memory_type"] = rep.MemorySpec.MemoryType + } + } + return facts } // --- Wails-bound Plugin & Driver APIs (§10) --- diff --git a/internal/config/config.go b/internal/config/config.go index fbaae72..6992638 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -28,6 +28,10 @@ type Config struct { // MinimizeToTray keeps Reims-Go running in the Windows system tray when the // main window is closed so Guest Tools bridges stay alive. Defaults to true. MinimizeToTray *bool `json:"minimize_to_tray,omitempty"` + // SyncHostMemorySMBIOS overrides QEMU's default SMBIOS Type 17 memory spec + // (2666 MHz DDR4) with the host's physical memory speed and generation so + // macOS About This Mac reports the host's real RAM frequency. Defaults to false. + SyncHostMemorySMBIOS bool `json:"sync_host_memory_smbios,omitempty"` } // ShouldMinimizeToTray returns true when closing the main window should hide to tray. diff --git a/internal/driver/reims/smbios_compat.go b/internal/driver/reims/smbios_compat.go new file mode 100644 index 0000000..9da4345 --- /dev/null +++ b/internal/driver/reims/smbios_compat.go @@ -0,0 +1,117 @@ +package reims + +import ( + "context" + "fmt" + "io" + "os" + "os/exec" + "strings" + "sync" + "time" +) + +// BuildSMBIOSType17Value formats the value token for `-smbios ` carrying +// SMBIOS Type 17 memory speed (and optionally memory_type). Returns "" when +// speedMHz is out of QEMU's uint16 range. +func BuildSMBIOSType17Value(speedMHz, memoryType int, includeMemoryType bool) string { + if speedMHz <= 0 || speedMHz > 65535 { + return "" + } + if includeMemoryType && memoryType > 0 && memoryType <= 255 { + return fmt.Sprintf("type=17,speed=%d,memory_type=%d", speedMHz, memoryType) + } + return fmt.Sprintf("type=17,speed=%d", speedMHz) +} + +// HasSMBIOSType17Arg reports whether extraArgs already contains a `-smbios` +// option targeting SMBIOS Type 17. +func HasSMBIOSType17Arg(extraArgs string) bool { + tokens := splitShellTokens(extraArgs) + for i := 0; i < len(tokens); i++ { + tok := tokens[i] + var val string + if tok == "-smbios" && i+1 < len(tokens) { + val = tokens[i+1] + i++ + } else if rest, ok := strings.CutPrefix(tok, "-smbios="); ok { + val = rest + } else { + continue + } + val = strings.Trim(val, `"'`) + for _, part := range strings.Split(val, ",") { + if strings.EqualFold(strings.TrimSpace(part), "type=17") { + return true + } + } + } + return false +} + +// MergeSMBIOSType17Args appends `-smbios type=17,...` to existing extra-args +// unless a Type 17 SMBIOS override is already present. +func MergeSMBIOSType17Args(existing string, speedMHz, memoryType int, includeMemoryType bool) string { + trimmed := strings.TrimSpace(existing) + if HasSMBIOSType17Arg(trimmed) { + return trimmed + } + val := BuildSMBIOSType17Value(speedMHz, memoryType, includeMemoryType) + if val == "" { + return trimmed + } + flag := "-smbios " + val + if trimmed == "" { + return flag + } + return trimmed + " " + flag +} + +type smbiosProbeKey struct { + path string + mtime int64 +} + +var ( + smbiosProbeMu sync.Mutex + smbiosProbeCache = map[smbiosProbeKey]bool{} +) + +// ProbeQEMUSupportsSMBIOSMemoryType checks whether qemuPath accepts +// `-smbios type=17,memory_type=26` (supported by reims-vgpu's QEMU fork). +// Results are cached per (binary path, modification time). +func ProbeQEMUSupportsSMBIOSMemoryType(qemuPath string, env []string) bool { + qemuPath = strings.TrimSpace(qemuPath) + if qemuPath == "" { + return false + } + var mtime int64 + if st, err := os.Stat(qemuPath); err == nil { + mtime = st.ModTime().UnixNano() + } else { + return false + } + key := smbiosProbeKey{path: qemuPath, mtime: mtime} + smbiosProbeMu.Lock() + if cached, ok := smbiosProbeCache[key]; ok { + smbiosProbeMu.Unlock() + return cached + } + smbiosProbeMu.Unlock() + + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, qemuPath, "-smbios", "type=17,memory_type=26", "-version") + configureCmd(cmd) + if len(env) > 0 { + cmd.Env = env + } + cmd.Stdout = io.Discard + cmd.Stderr = io.Discard + ok := cmd.Run() == nil + + smbiosProbeMu.Lock() + smbiosProbeCache[key] = ok + smbiosProbeMu.Unlock() + return ok +} diff --git a/internal/driver/reims/smbios_compat_test.go b/internal/driver/reims/smbios_compat_test.go new file mode 100644 index 0000000..93224aa --- /dev/null +++ b/internal/driver/reims/smbios_compat_test.go @@ -0,0 +1,62 @@ +package reims + +import ( + "os" + "testing" +) + +func TestBuildSMBIOSType17Value(t *testing.T) { + if got := BuildSMBIOSType17Value(6400, 34, true); got != "type=17,speed=6400,memory_type=34" { + t.Fatalf("with memory_type: got %q", got) + } + if got := BuildSMBIOSType17Value(6400, 34, false); got != "type=17,speed=6400" { + t.Fatalf("without memory_type: got %q", got) + } + if got := BuildSMBIOSType17Value(3200, 0, true); got != "type=17,speed=3200" { + t.Fatalf("zero memory_type: got %q", got) + } + if got := BuildSMBIOSType17Value(0, 34, true); got != "" { + t.Fatalf("zero speed: got %q", got) + } + if got := BuildSMBIOSType17Value(70000, 34, true); got != "" { + t.Fatalf("overflow speed: got %q", got) + } +} + +func TestHasAndMergeSMBIOSType17Arg(t *testing.T) { + if HasSMBIOSType17Arg("-machine kernel-irqchip=off") { + t.Fatal("unexpected true for unrelated args") + } + if !HasSMBIOSType17Arg("-smbios type=17,speed=6400,memory_type=34") { + t.Fatal("expected true for -smbios type=17") + } + if !HasSMBIOSType17Arg("-smbios=type=17,speed=3200") { + t.Fatal("expected true for -smbios=type=17") + } + if HasSMBIOSType17Arg("-smbios type=2") { + t.Fatal("unexpected true for type=2") + } + + merged := MergeSMBIOSType17Args("-machine kernel-irqchip=off", 6400, 34, true) + if merged != "-machine kernel-irqchip=off -smbios type=17,speed=6400,memory_type=34" { + t.Fatalf("merged = %q", merged) + } + // Existing manual type=17 must not be duplicated. + keep := MergeSMBIOSType17Args("-smbios type=17,speed=5200", 6400, 34, true) + if keep != "-smbios type=17,speed=5200" { + t.Fatalf("existing type=17 altered: %q", keep) + } +} + +func TestProbeQEMUSupportsSMBIOSMemoryTypeMissingBinary(t *testing.T) { + if ProbeQEMUSupportsSMBIOSMemoryType("", nil) { + t.Fatal("empty path should return false") + } + if ProbeQEMUSupportsSMBIOSMemoryType("nonexistent-qemu-binary-12345", nil) { + t.Fatal("missing binary should return false") + } + exe, err := os.Executable() + if err == nil && ProbeQEMUSupportsSMBIOSMemoryType(exe, nil) { + t.Fatal("test binary should refuse -smbios and return false") + } +} diff --git a/internal/host/host.go b/internal/host/host.go index 84e1203..881c279 100644 --- a/internal/host/host.go +++ b/internal/host/host.go @@ -74,9 +74,10 @@ type Report struct { NonLPEMaskHex string `json:"non_lpe_mask_hex,omitempty"` NonLPELogicalCPUs []int `json:"non_lpe_logical_cpus,omitempty"` CPUTopology []LogicalCPUInfo `json:"cpu_topology,omitempty"` - TotalRAMGB float64 `json:"total_ram_gb"` - AvailRAMGB float64 `json:"avail_ram_gb"` - MemoryLoadPct int `json:"memory_load_pct"` + TotalRAMGB float64 `json:"total_ram_gb"` + AvailRAMGB float64 `json:"avail_ram_gb"` + MemoryLoadPct int `json:"memory_load_pct"` + MemorySpec *HostMemorySpec `json:"memory_spec,omitempty"` // Commit memory: QEMU commits all guest RAM at start (CreateFileMapping), so // a VM needs its memory free in the commit charge, not just in physical RAM. // Measured 2026-11-28: 14.7 GiB commit free with 17.3 GiB physical free, and a diff --git a/internal/host/host_windows.go b/internal/host/host_windows.go index 11da2fe..c82ae80 100644 --- a/internal/host/host_windows.go +++ b/internal/host/host_windows.go @@ -69,6 +69,7 @@ type staticHostSnapshot struct { recGPU *GPUInfo topo hybridTopology topoOK bool + memSpec *HostMemorySpec } var ( @@ -90,6 +91,7 @@ func getStaticHostSnapshot() staticHostSnapshot { recGPU: PickRecommendedGPU(gpus), topo: topo, topoOK: ok, + memSpec: probeHostMemorySpec(), } }) return staticHostData @@ -114,6 +116,11 @@ func Inspect(dataRoot string) Report { cp := *st.recGPU recGPUCopy = &cp } + var memSpecCopy *HostMemorySpec + if st.memSpec != nil { + cp := *st.memSpec + memSpecCopy = &cp + } rep := Report{ OS: "windows", Arch: runtime.GOARCH, @@ -123,6 +130,7 @@ func Inspect(dataRoot string) Report { NeedsColdRebootWorkaround: st.needsColdReboot, GPUs: gpusCopy, RecommendedGPU: recGPUCopy, + MemorySpec: memSpecCopy, } if rep.WHPX == WHPXReady { rep.WHPXCaps = getCachedWHPXCapabilities() diff --git a/internal/host/smbios_memory.go b/internal/host/smbios_memory.go new file mode 100644 index 0000000..172d5d6 --- /dev/null +++ b/internal/host/smbios_memory.go @@ -0,0 +1,180 @@ +package host + +import ( + "encoding/binary" + "fmt" +) + +// HostMemorySpec describes the host's physical memory speed and generation +// parsed from SMBIOS Type 17 (Memory Device) tables. +type HostMemorySpec struct { + SpeedMHz int `json:"speed_mhz,omitempty"` + MemoryType int `json:"memory_type,omitempty"` + TypeName string `json:"type_name,omitempty"` +} + +// FormatMemorySpec returns a concise human-readable label such as +// "6400 MHz DDR5" or "3200 MHz", or "" when speed is unknown. +func FormatMemorySpec(spec *HostMemorySpec) string { + if spec == nil || spec.SpeedMHz <= 0 { + return "" + } + name := spec.TypeName + if name == "" && spec.MemoryType > 0 { + name = SMBIOSMemoryTypeName(spec.MemoryType) + } + if name != "" { + return fmt.Sprintf("%d MHz %s", spec.SpeedMHz, name) + } + return fmt.Sprintf("%d MHz", spec.SpeedMHz) +} + +// SMBIOSMemoryTypeName maps DMTF SMBIOS Type 17 Memory Type codes to short +// display names. Returns "" for unknown/unspecified codes. +func SMBIOSMemoryTypeName(code int) string { + switch code { + case 18: + return "DDR" + case 19: + return "DDR2" + case 20: + return "DDR2 FB-DIMM" + case 24: + return "DDR3" + case 26: + return "DDR4" + case 27: + return "LPDDR" + case 28: + return "LPDDR2" + case 29: + return "LPDDR3" + case 30: + return "LPDDR4" + case 34: + return "DDR5" + case 35: + return "LPDDR5" + default: + return "" + } +} + +// ParseWindowsRawSMBIOS parses the RawSMBIOSData buffer returned by Win32 +// GetSystemFirmwareTable('RSMB', 0, ...) and extracts the host physical memory +// speed and SMBIOS memory type from populated Type 17 entries. +func ParseWindowsRawSMBIOS(buf []byte) *HostMemorySpec { + // RawSMBIOSData header: + // BYTE Used20CallingMethod; + // BYTE SMBIOSMajorVersion; + // BYTE SMBIOSMinorVersion; + // BYTE DmiRevision; + // DWORD Length; + // BYTE SMBIOSTableData[]; + if len(buf) < 8 { + return nil + } + tableLen := int(binary.LittleEndian.Uint32(buf[4:8])) + table := buf[8:] + if tableLen > 0 && tableLen < len(table) { + table = table[:tableLen] + } + return ParseSMBIOSType17Table(table) +} + +// ParseSMBIOSType17Table walks a raw SMBIOS structure stream and extracts the +// configured speed (falling back to rated speed) and SMBIOS Memory Type from +// populated Type 17 (Memory Device) structures. +// +// Only non-empty DIMM slots are considered. When multiple populated DIMMs +// report differing speeds, the lowest valid speed is selected. Speeds are +// bounded to uint16 (1..65535) because QEMU's `-smbios type=17,speed=...` +// stores a 16-bit value. +func ParseSMBIOSType17Table(table []byte) *HostMemorySpec { + var bestSpeed int + var bestType int + + i := 0 + for i+4 <= len(table) { + typ := table[i] + length := int(table[i+1]) + if length < 4 || i+length > len(table) { + break + } + if typ == 127 { + // End-of-Table structure. + break + } + + if typ == 17 && length >= 0x15 { + structData := table[i : i+length] + size := binary.LittleEndian.Uint16(structData[0x0C:0x0E]) + populated := size != 0 && size != 0xFFFF + if size == 0x7FFF && length >= 0x20 { + extSize := binary.LittleEndian.Uint32(structData[0x1C:0x20]) + populated = extSize != 0 + } + if populated { + memType := int(structData[0x12]) + if memType <= 2 { + // 0 = reserved, 1 = Other, 2 = Unknown + memType = 0 + } + + var speed int + // Prefer ConfiguredMemorySpeed (offset 0x20, SMBIOS 2.7+) so + // XMP/EXPO/actual running clock is reported instead of JEDEC base. + if length >= 0x22 { + cfg := int(binary.LittleEndian.Uint16(structData[0x20:0x22])) + if cfg > 0 && cfg < 0xFFFF { + speed = cfg + } else if cfg == 0xFFFF && length >= 0x5C { + ext := int(binary.LittleEndian.Uint32(structData[0x58:0x5C])) + if ext > 0 && ext <= 0xFFFF { + speed = ext + } + } + } + if speed == 0 && length >= 0x17 { + rated := int(binary.LittleEndian.Uint16(structData[0x15:0x17])) + if rated > 0 && rated < 0xFFFF { + speed = rated + } else if rated == 0xFFFF && length >= 0x58 { + ext := int(binary.LittleEndian.Uint32(structData[0x54:0x58])) + if ext > 0 && ext <= 0xFFFF { + speed = ext + } + } + } + + if speed >= 200 && speed <= 65535 { + if bestSpeed == 0 || speed < bestSpeed { + bestSpeed = speed + } + } + if bestType == 0 && memType > 0 { + bestType = memType + } + } + } + + // Advance past formatted structure and its double-NUL terminated string set. + next := i + length + for next+1 < len(table) && !(table[next] == 0 && table[next+1] == 0) { + next++ + } + if next+1 >= len(table) { + break + } + i = next + 2 + } + + if bestSpeed == 0 { + return nil + } + return &HostMemorySpec{ + SpeedMHz: bestSpeed, + MemoryType: bestType, + TypeName: SMBIOSMemoryTypeName(bestType), + } +} diff --git a/internal/host/smbios_memory_other.go b/internal/host/smbios_memory_other.go new file mode 100644 index 0000000..2a796a9 --- /dev/null +++ b/internal/host/smbios_memory_other.go @@ -0,0 +1,7 @@ +//go:build !windows + +package host + +func probeHostMemorySpec() *HostMemorySpec { + return nil +} diff --git a/internal/host/smbios_memory_test.go b/internal/host/smbios_memory_test.go new file mode 100644 index 0000000..de0c837 --- /dev/null +++ b/internal/host/smbios_memory_test.go @@ -0,0 +1,93 @@ +package host + +import ( + "encoding/binary" + "runtime" + "testing" +) + +func buildSMBIOSType17Entry(size uint16, memType byte, speed, cfgSpeed uint16) []byte { + b := make([]byte, 0x22) + b[0] = 17 + b[1] = byte(len(b)) + binary.LittleEndian.PutUint16(b[2:4], 0x0011) + binary.LittleEndian.PutUint16(b[0x0C:0x0E], size) + b[0x12] = memType + binary.LittleEndian.PutUint16(b[0x15:0x17], speed) + binary.LittleEndian.PutUint16(b[0x20:0x22], cfgSpeed) + // Double-NUL string terminator. + return append(b, 0, 0) +} + +func wrapWindowsRawSMBIOS(table []byte) []byte { + hdr := make([]byte, 8) + hdr[1] = 3 + hdr[2] = 6 + binary.LittleEndian.PutUint32(hdr[4:8], uint32(len(table))) + return append(hdr, table...) +} + +func TestParseSMBIOSType17DDR5ConfiguredSpeed(t *testing.T) { + var table []byte + // Empty DIMM slot should be ignored even if firmware left bogus fields. + table = append(table, buildSMBIOSType17Entry(0, 26, 2666, 2666)...) + // Populated DDR5-6400 EXPO DIMM (rated 4800, configured 6400). + table = append(table, buildSMBIOSType17Entry(16384, 34, 4800, 6400)...) + table = append(table, buildSMBIOSType17Entry(16384, 34, 4800, 6400)...) + // End-of-table marker. + table = append(table, 127, 4, 0, 0, 0, 0) + + spec := ParseWindowsRawSMBIOS(wrapWindowsRawSMBIOS(table)) + if spec == nil { + t.Fatal("expected non-nil HostMemorySpec") + } + if spec.SpeedMHz != 6400 || spec.MemoryType != 34 || spec.TypeName != "DDR5" { + t.Fatalf("got %+v, want 6400 MHz DDR5 (type 34)", spec) + } + if got := FormatMemorySpec(spec); got != "6400 MHz DDR5" { + t.Fatalf("FormatMemorySpec = %q, want %q", got, "6400 MHz DDR5") + } +} + +func TestParseSMBIOSType17FallsBackToRatedSpeed(t *testing.T) { + // Older SMBIOS 2.3 entry without ConfiguredMemorySpeed (length 0x1B). + entry := make([]byte, 0x1B) + entry[0] = 17 + entry[1] = byte(len(entry)) + binary.LittleEndian.PutUint16(entry[0x0C:0x0E], 8192) + entry[0x12] = 26 // DDR4 + binary.LittleEndian.PutUint16(entry[0x15:0x17], 3200) + entry = append(entry, 'D', 'I', 'M', 'M', '0', 0, 0) + + spec := ParseSMBIOSType17Table(entry) + if spec == nil { + t.Fatal("expected non-nil HostMemorySpec") + } + if spec.SpeedMHz != 3200 || spec.MemoryType != 26 || spec.TypeName != "DDR4" { + t.Fatalf("got %+v, want 3200 MHz DDR4", spec) + } +} + +func TestParseSMBIOSType17EmptyAndMalformed(t *testing.T) { + if got := ParseWindowsRawSMBIOS(nil); got != nil { + t.Fatalf("nil input: got %+v", got) + } + if got := ParseWindowsRawSMBIOS([]byte{1, 2, 3}); got != nil { + t.Fatalf("short input: got %+v", got) + } + emptySlot := buildSMBIOSType17Entry(0, 26, 3200, 3200) + if got := ParseSMBIOSType17Table(emptySlot); got != nil { + t.Fatalf("empty slot only: got %+v", got) + } +} + +func TestProbeHostMemorySpecLiveWindows(t *testing.T) { + if runtime.GOOS != "windows" { + t.Skip("Windows live SMBIOS probe test") + } + spec := probeHostMemorySpec() + t.Logf("live Windows host memory spec: %+v (%q)", spec, FormatMemorySpec(spec)) + if spec != nil && (spec.SpeedMHz < 200 || spec.SpeedMHz > 65535) { + t.Fatalf("out-of-range live SpeedMHz: %+v", spec) + } +} diff --git a/internal/host/smbios_memory_windows.go b/internal/host/smbios_memory_windows.go new file mode 100644 index 0000000..d94b343 --- /dev/null +++ b/internal/host/smbios_memory_windows.go @@ -0,0 +1,39 @@ +//go:build windows + +package host + +import "unsafe" + +var procGetSystemFirmwareTable = kernel32.NewProc("GetSystemFirmwareTable") + +// firmwareTableProviderRSMB is the Win32 'RSMB' (Raw SMBIOS) table signature. +const firmwareTableProviderRSMB = 0x52534D42 + +// probeHostMemorySpec reads the host's raw SMBIOS firmware table via +// GetSystemFirmwareTable('RSMB') without administrator privileges and extracts +// the populated physical memory speed and generation. +func probeHostMemorySpec() *HostMemorySpec { + if err := procGetSystemFirmwareTable.Find(); err != nil { + return nil + } + size, _, _ := procGetSystemFirmwareTable.Call( + uintptr(firmwareTableProviderRSMB), + 0, + 0, + 0, + ) + if size < 8 || size > 4*1024*1024 { + return nil + } + buf := make([]byte, size) + written, _, _ := procGetSystemFirmwareTable.Call( + uintptr(firmwareTableProviderRSMB), + 0, + uintptr(unsafe.Pointer(&buf[0])), + size, + ) + if written < 8 || written > size { + return nil + } + return ParseWindowsRawSMBIOS(buf[:written]) +} diff --git a/internal/plugin/blockers_test.go b/internal/plugin/blockers_test.go index 4f9330a..813963f 100644 --- a/internal/plugin/blockers_test.go +++ b/internal/plugin/blockers_test.go @@ -100,6 +100,31 @@ func TestValidateArgFragmentBlocksInjection(t *testing.T) { if err := ValidateArgFragment(ArgFragment{Tokens: []string{"-drive", "file=secret.img"}}); err == nil { t.Error("expected external -drive to be rejected") } + // External plugin must ALWAYS be rejected from -smbios, even type=17. + if err := ValidateArgFragment(ArgFragment{Tokens: []string{"-smbios", "type=17,speed=6400,memory_type=34"}}); err == nil { + t.Error("expected external -smbios type=17 to be rejected") + } + // Builtin -smbios must allow ONLY type=17 with speed and optional memory_type. + for _, goodBuiltin := range [][]string{ + {"-smbios", "type=17,speed=6400,memory_type=34"}, + {"-smbios", "type=17,speed=3200"}, + } { + if err := ValidateArgFragment(ArgFragment{Builtin: true, Tokens: goodBuiltin}); err != nil { + t.Errorf("expected builtin %q to be allowed, got %v", goodBuiltin, err) + } + } + for _, badBuiltin := range [][]string{ + {"-smbios", "type=1,serial=SECRET"}, + {"-smbios", "type=17,speed=6400,serial=SECRET"}, + {"-smbios", "type=17"}, + {"-smbios", "type=17,speed=0"}, + {"-smbios", "type=17,speed=70000"}, + {"-smbios", "type=17,speed=6400,memory_type=300"}, + } { + if err := ValidateArgFragment(ArgFragment{Builtin: true, Tokens: badBuiltin}); err == nil { + t.Errorf("expected builtin %q to be rejected, got nil", badBuiltin) + } + } } func TestBuiltinBeforeStartExemptFromExternalTimeout(t *testing.T) { diff --git a/internal/plugin/builtin/core.go b/internal/plugin/builtin/core.go index f7bceb0..82264c2 100644 --- a/internal/plugin/builtin/core.go +++ b/internal/plugin/builtin/core.go @@ -214,6 +214,7 @@ func defCore(ver string, cb HostCallbacks) plugin.PluginDef { stepGuestLang(ctx, cb, p, &in) stepWHPXFallback(cb, p, &in) stepWin10ColdReboot(cb, p, &in) + stepHostMemorySMBIOS(cb, p, &in) return in, nil }, }) @@ -247,9 +248,10 @@ func defCore(ver string, cb HostCallbacks) plugin.PluginDef { // Arg-ledger keys owned by the core. const ( - keyOfflineHelper = "reimshelp" - keyKernelIrqchip = "kernel-irqchip" - keyWin10ColdReboot = "win10-cold-reboot" + keyOfflineHelper = "reimshelp" + keyKernelIrqchip = "kernel-irqchip" + keyWin10ColdReboot = "win10-cold-reboot" + keyHostMemorySMBIOS = "host-memory-smbios" ) // stepOfflineHelper attaches the REIMSHELP helper disk while an offline @@ -398,3 +400,52 @@ func stepWin10ColdReboot(cb HostCallbacks, p plugin.BeforeStartPayload, in *plug Params: map[string]any{"qmp_addr": "unix:" + sockPath}, }) } + +// stepHostMemorySMBIOS appends `-smbios type=17,speed=...,memory_type=...` +// when SyncHostMemorySMBIOS is enabled in app config, overriding reims-ctl's +// hardcoded 2666 MHz DDR4 default with the host's probed RAM spec. +func stepHostMemorySMBIOS(cb HostCallbacks, p plugin.BeforeStartPayload, in *plugin.StartIntent) { + if cb.GetConfig == nil || !cb.GetConfig().SyncHostMemorySMBIOS { + in.ClearKeys = append(in.ClearKeys, keyHostMemorySMBIOS) + return + } + if userHas, _ := p.HostFacts["vm.user_has_smbios_type17"].(bool); userHas { + in.ClearKeys = append(in.ClearKeys, keyHostMemorySMBIOS) + return + } + speedMHz := hostFactInt(p.HostFacts, "host.memory_speed_mhz") + if speedMHz <= 0 { + in.ClearKeys = append(in.ClearKeys, keyHostMemorySMBIOS) + return + } + memType := hostFactInt(p.HostFacts, "host.memory_type") + supportsMemType, _ := p.HostFacts["runtime.smbios_memory_type"].(bool) + val := reims.BuildSMBIOSType17Value(speedMHz, memType, supportsMemType) + if val == "" { + in.ClearKeys = append(in.ClearKeys, keyHostMemorySMBIOS) + return + } + in.Args = append(in.Args, plugin.ArgFragment{ + PluginID: IDCore, + Key: keyHostMemorySMBIOS, + Tokens: []string{"-smbios", val}, + Builtin: true, + Priority: 75, + }) +} + +func hostFactInt(facts map[string]any, key string) int { + if facts == nil { + return 0 + } + switch v := facts[key].(type) { + case int: + return v + case int64: + return int(v) + case float64: + return int(v) + default: + return 0 + } +} diff --git a/internal/plugin/builtin/core_test.go b/internal/plugin/builtin/core_test.go index 63b69ac..0c0c61e 100644 --- a/internal/plugin/builtin/core_test.go +++ b/internal/plugin/builtin/core_test.go @@ -192,3 +192,96 @@ func TestMigrateRetiredCarriesWorkaroundChoices(t *testing.T) { t.Fatalf("second migration: %v", err) } } + +func TestCoreHostMemorySMBIOS(t *testing.T) { + facts := map[string]any{ + "host.memory_speed_mhz": 6400, + "host.memory_type": 34, + "runtime.smbios_memory_type": true, + } + // Disabled by default: clears keyHostMemorySMBIOS. + in := dispatchCoreStart(t, nil, facts, nil) + if slices.Contains(argKeys(in), keyHostMemorySMBIOS) || !slices.Contains(in.ClearKeys, keyHostMemorySMBIOS) { + t.Fatalf("default off: want host-memory-smbios cleared, got args %v clear %v", argKeys(in), in.ClearKeys) + } + + runWithSync := func(f map[string]any) plugin.StartIntent { + t.Helper() + reg := plugin.NewRegistry(nil) + cb := coreTestCallbacks(t, nil) + origCfg := cb.GetConfig + cb.GetConfig = func() config.Config { + c := origCfg() + c.SyncHostMemorySMBIOS = true + return c + } + if err := RegisterAll(reg, cb, nil); err != nil { + t.Fatal(err) + } + reg.Reconcile(context.Background()) + intents, err := reg.Hooks().DispatchBeforeStart(context.Background(), plugin.BeforeStartPayload{ + VMName: "mac1", + VMDir: t.TempDir(), + DriverID: IDDriverReimsMacOS, + HostFacts: f, + }) + if err != nil { + t.Fatal(err) + } + for _, intent := range intents { + if intent.PluginID == IDCore { + return intent + } + } + t.Fatal("missing core intent") + return plugin.StartIntent{} + } + + // Enabled with QEMU memory_type support: emits speed + memory_type. + inOn := runWithSync(facts) + var memFrag *plugin.ArgFragment + for i := range inOn.Args { + if inOn.Args[i].Key == keyHostMemorySMBIOS { + memFrag = &inOn.Args[i] + } + } + if memFrag == nil || !slices.Equal(memFrag.Tokens, []string{"-smbios", "type=17,speed=6400,memory_type=34"}) { + t.Fatalf("enabled with memory_type: got %+v", memFrag) + } + if err := plugin.ValidateArgFragment(*memFrag); err != nil { + t.Fatalf("ValidateArgFragment rejected core memory fragment: %v", err) + } + + // Enabled without QEMU memory_type support: emits speed only. + inNoType := runWithSync(map[string]any{ + "host.memory_speed_mhz": 6400, + "host.memory_type": 34, + "runtime.smbios_memory_type": false, + }) + memFrag = nil + for i := range inNoType.Args { + if inNoType.Args[i].Key == keyHostMemorySMBIOS { + memFrag = &inNoType.Args[i] + } + } + if memFrag == nil || !slices.Equal(memFrag.Tokens, []string{"-smbios", "type=17,speed=6400"}) { + t.Fatalf("enabled without memory_type: got %+v", memFrag) + } + + // Enabled when host speed unavailable: clears key. + inUnknown := runWithSync(map[string]any{}) + if slices.Contains(argKeys(inUnknown), keyHostMemorySMBIOS) || !slices.Contains(inUnknown.ClearKeys, keyHostMemorySMBIOS) { + t.Fatalf("unknown speed: want cleared, got args %v clear %v", argKeys(inUnknown), inUnknown.ClearKeys) + } + + // User already supplied a manual -smbios type=17 in extra_args: respect it and clear ours. + inManual := runWithSync(map[string]any{ + "host.memory_speed_mhz": 6400, + "host.memory_type": 34, + "runtime.smbios_memory_type": true, + "vm.user_has_smbios_type17": true, + }) + if slices.Contains(argKeys(inManual), keyHostMemorySMBIOS) || !slices.Contains(inManual.ClearKeys, keyHostMemorySMBIOS) { + t.Fatalf("user manual type=17: want cleared, got args %v clear %v", argKeys(inManual), inManual.ClearKeys) + } +} diff --git a/internal/plugin/ledger.go b/internal/plugin/ledger.go index ab61ac0..555eb9a 100644 --- a/internal/plugin/ledger.go +++ b/internal/plugin/ledger.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "sort" + "strconv" "strings" ) @@ -259,15 +260,36 @@ func ValidateArgFragment(frag ArgFragment) error { return fmt.Errorf("unexpected positional QEMU argument %q", tok) } flagName := tok + hasEq := false + var inlineVal string if eq := strings.IndexByte(flagName, '='); eq > 0 { + inlineVal = flagName[eq+1:] flagName = flagName[:eq] + hasEq = true + } + if flagName == "-smbios" { + if !frag.Builtin { + return fmt.Errorf("QEMU option %q is not in plugin allowlist", flagName) + } + val := inlineVal + if !hasEq { + if i+1 >= len(frag.Tokens) || strings.HasPrefix(frag.Tokens[i+1], "-") { + return fmt.Errorf("QEMU option %q requires a value token", flagName) + } + val = frag.Tokens[i+1] + i++ + } + if err := validateBuiltinSMBIOSType17(val); err != nil { + return err + } + continue } allowed, exists := AllowedQEMUOptionFamilies[flagName] if (!exists || !allowed) && !(frag.Builtin && BuiltinOnlyQEMUOptionFamilies[flagName]) { return fmt.Errorf("QEMU option %q is not in plugin allowlist", flagName) } // Value-taking flags without '=' must carry their argument value in this fragment. - if flagName != "-no-reboot" && flagName != "-usb" && !strings.Contains(tok, "=") { + if flagName != "-no-reboot" && flagName != "-usb" && !hasEq { if i+1 >= len(frag.Tokens) || strings.HasPrefix(frag.Tokens[i+1], "-") { return fmt.Errorf("QEMU option %q requires a value token", flagName) } @@ -277,6 +299,48 @@ func ValidateArgFragment(frag ArgFragment) error { return nil } +// validateBuiltinSMBIOSType17 enforces that compiled-in builtins may only pass +// `-smbios type=17,speed=<1..65535>[,memory_type=<1..255>]` — never Type 1/2/3 +// or sensitive identity fields such as serial/uuid/manufacturer. +func validateBuiltinSMBIOSType17(val string) error { + if val == "" || strings.ContainsAny(val, " \t\"'\r\n\x00") { + return fmt.Errorf("disallowed -smbios value %q", val) + } + var sawType17, sawSpeed bool + seen := map[string]bool{} + for _, part := range strings.Split(val, ",") { + k, v, ok := strings.Cut(part, "=") + if !ok || k == "" || v == "" || seen[k] { + return fmt.Errorf("invalid -smbios type=17 option %q", part) + } + seen[k] = true + switch k { + case "type": + if v != "17" { + return fmt.Errorf("builtin -smbios only allows type=17, got %q", part) + } + sawType17 = true + case "speed": + n, err := strconv.Atoi(v) + if err != nil || n <= 0 || n > 65535 { + return fmt.Errorf("invalid -smbios speed %q", v) + } + sawSpeed = true + case "memory_type": + n, err := strconv.Atoi(v) + if err != nil || n <= 0 || n > 255 { + return fmt.Errorf("invalid -smbios memory_type %q", v) + } + default: + return fmt.Errorf("disallowed -smbios field %q", k) + } + } + if !sawType17 || !sawSpeed { + return fmt.Errorf("builtin -smbios requires type=17 and speed, got %q", val) + } + return nil +} + // ValidateEnvKey checks whether pluginID is allowed to set envKey (§4.4). // Shared host env vars (e.g. VK_ICD_FILENAMES, REIMS_GO_INPUT_*) are restricted // to built-in plugins; external plugins may only set their own REIMS_PLUGIN__* namespace. @@ -303,6 +367,12 @@ func sanitizeEnvPrefix(pluginID string) string { return b.String() } +// UserExtraArgs returns the portion of currentExtraArgs that is NOT owned by +// any fragment currently recorded in ledger. +func UserExtraArgs(currentExtraArgs string, ledger *ArgLedger) string { + return strings.Join(stripOwnedTokens(SplitShellTokens(currentExtraArgs), ledger), " ") +} + // ReconcileStartIntents strips previously owned fragments from currentExtraArgs // (preserving ALL unowned user args), arbitrates conflicts across new intents, // validates option allowlists & env prefixes, updates the ledger, and returns diff --git a/internal/vmstart/vmstart.go b/internal/vmstart/vmstart.go index 6250d60..13f3aa4 100644 --- a/internal/vmstart/vmstart.go +++ b/internal/vmstart/vmstart.go @@ -158,6 +158,25 @@ func (p *Prep) Prepare(ctx context.Context, name string, rep host.Report, cur *r if !p.SkipWHPXFallback { p.applyProbedWHPXCompat(ctx, name, rep, cur) } + p.syncHostMemorySMBIOS(ctx, name, rep, cur) +} + +func (p *Prep) syncHostMemorySMBIOS(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) { + if !p.cfg.SyncHostMemorySMBIOS || rep.MemorySpec == nil || rep.MemorySpec.SpeedMHz <= 0 { + return + } + if reims.HasSMBIOSType17Arg(cur.ExtraArgs) { + return + } + supportsType := reims.ProbeQEMUSupportsSMBIOSMemoryType(p.Runtime.QemuPath(), p.Client.Env) + merged := reims.MergeSMBIOSType17Args(cur.ExtraArgs, rep.MemorySpec.SpeedMHz, rep.MemorySpec.MemoryType, supportsType) + if merged == cur.ExtraArgs { + return + } + if err := p.setExtraArgs(ctx, name, merged); err != nil { + return + } + cur.ExtraArgs = merged } func (p *Prep) setExtraArgs(ctx context.Context, name, args string) error { diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index cf32f40..d909719 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -325,5 +325,8 @@ "effectImmediate": "Immediate", "effectNextStart": "Next start", "themePluginDarkDisabled": "Default theme plugin is disabled; dark and system appearances are unavailable", - "themePluginLightDisabled": "The active theme supports dark appearance only" + "themePluginLightDisabled": "The active theme supports dark appearance only", + "syncHostMemorySMBIOS": "Sync host memory specs", + "syncHostMemorySMBIOSSub": "Show the host's actual memory speed and generation ({spec}) in macOS About This Mac; applies on next start", + "syncHostMemorySMBIOSUnavailable": "Could not read host SMBIOS memory speed; VMs keep the default 2666 MHz DDR4" } diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index e46c6aa..d6347f4 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -325,5 +325,8 @@ "effectImmediate": "立即生效", "effectNextStart": "下次启动生效", "themePluginDarkDisabled": "默认主题插件已停用,深色与跟随系统外观不可用", - "themePluginLightDisabled": "当前主题仅支持深色外观" + "themePluginLightDisabled": "当前主题仅支持深色外观", + "syncHostMemorySMBIOS": "同步宿主机内存规格", + "syncHostMemorySMBIOSSub": "在 macOS「关于本机」中显示宿主机真实内存频率与代数(当前:{spec}),下次启动生效", + "syncHostMemorySMBIOSUnavailable": "未能从宿主机 SMBIOS 读取物理内存频率,虚拟机将保持默认的 2666 MHz DDR4" } From e62742f65dfd271a8503447caa3ec168fec87720 Mon Sep 17 00:00:00 2001 From: ChenRuoT Date: Tue, 1 Dec 2026 13:01:37 +0800 Subject: [PATCH 22/42] fix(host): surface Vulkan probe failures in setup and doctor --- frontend/src/components/Setup.tsx | 7 +++-- frontend/src/i18n/domains/wizard.gen.ts | 2 ++ frontend/src/i18n/keys.gen.ts | 1 + frontend/wailsjs/go/models.ts | 2 ++ internal/cli/cli.go | 7 +++-- internal/host/host.go | 1 + internal/host/host_windows.go | 26 +++++++++------- internal/host/vulkan_windows.go | 40 +++++++++++++++++-------- internal/i18n/catalog_gen.go | 3 ++ locales/en-US/native.json | 1 + locales/en-US/wizard.json | 1 + locales/zh-CN/native.json | 1 + locales/zh-CN/wizard.json | 1 + 13 files changed, 66 insertions(+), 27 deletions(-) diff --git a/frontend/src/components/Setup.tsx b/frontend/src/components/Setup.tsx index 0c24142..19eb844 100644 --- a/frontend/src/components/Setup.tsx +++ b/frontend/src/components/Setup.tsx @@ -203,7 +203,7 @@ const RuntimeStep: React.FC = ({ locale, tr, state, runtimeTask, onCh const whpxOK = host.whpx === 'ready' const gpu = host.recommended_gpu ?? (host.gpus ?? []).find((g) => g.kind !== 'virtual') const gpuHint = gpuCompatHint(locale, gpu) - const gpuOK = !!gpu && gpu.compat !== 'warn' && gpu.compat !== 'unsupported' + const gpuOK = !host.vulkan_probe_error && !!gpu && gpu.compat !== 'warn' && gpu.compat !== 'unsupported' const recMem = recommendedMemoryGB(host) return ( <> @@ -236,7 +236,10 @@ const RuntimeStep: React.FC = ({ locale, tr, state, runtimeTask, onCh
{tr('setupGPU')}
-
{gpu ? shortGPUName(gpu.name) : tr('setupNoGPU')}
+ {gpu &&
{shortGPUName(gpu.name)}
} + {host.vulkan_probe_error ? ( +
{tr('vulkanProbeFailed', { detail: host.vulkan_probe_error })}
+ ) : !gpu &&
{tr('setupNoGPU')}
} {gpuHint &&
{gpuHint}
}
diff --git a/frontend/src/i18n/domains/wizard.gen.ts b/frontend/src/i18n/domains/wizard.gen.ts index 2dfc62a..93b1c61 100644 --- a/frontend/src/i18n/domains/wizard.gen.ts +++ b/frontend/src/i18n/domains/wizard.gen.ts @@ -79,6 +79,7 @@ export const wizardZh: Record = { "summarySource": "来源", "validationChecking": "正在检查…", "validationPassed": "可以创建", + "vulkanProbeFailed": "Vulkan 探测失败({detail})。请运行 vulkaninfo --summary 检查驱动。", "wizChooseFile": "选择…", "wizNoFile": "还没有选择文件", "wizOptions": "选项", @@ -166,6 +167,7 @@ export const wizardEn: Record = { "summarySource": "Source", "validationChecking": "Checking…", "validationPassed": "Ready to create", + "vulkanProbeFailed": "Vulkan probe failed ({detail}). Run vulkaninfo --summary to check the driver.", "wizChooseFile": "Choose…", "wizNoFile": "No file chosen", "wizOptions": "Options", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 9ee8854..97a6a15 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -890,6 +890,7 @@ export type I18nKey = | "viewLogs" | "vmDir" | "vmName" + | "vulkanProbeFailed" | "welcomeCheckHost" | "welcomeSub" | "welcomeTitle" diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 7d181bf..1c69716 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -762,6 +762,7 @@ export namespace host { whpx_caps: WHPXCapabilities; needs_cold_reboot_workaround: boolean; gpus: GPUInfo[]; + vulkan_probe_error?: string; recommended_gpu?: GPUInfo; displays?: DisplayInfo[]; primary_display?: DisplayInfo; @@ -807,6 +808,7 @@ export namespace host { this.whpx_caps = this.convertValues(source["whpx_caps"], WHPXCapabilities); this.needs_cold_reboot_workaround = source["needs_cold_reboot_workaround"]; this.gpus = this.convertValues(source["gpus"], GPUInfo); + this.vulkan_probe_error = source["vulkan_probe_error"]; this.recommended_gpu = this.convertValues(source["recommended_gpu"], GPUInfo); this.displays = this.convertValues(source["displays"], DisplayInfo); this.primary_display = this.convertValues(source["primary_display"], DisplayInfo); diff --git a/internal/cli/cli.go b/internal/cli/cli.go index aa74164..1d40ef8 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -194,9 +194,12 @@ func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error { } fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.whpx"), i18n.T(loc, whpxKey)) - if len(rep.GPUs) == 0 { + if rep.VulkanProbeError != "" { + fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.gpu"), i18n.M(loc, "doctor.gpu.probe_failed", i18n.Vars{"detail": rep.VulkanProbeError})) + } + if len(rep.GPUs) == 0 && rep.VulkanProbeError == "" { fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.gpu"), i18n.T(loc, "doctor.gpu.none")) - } else { + } else if len(rep.GPUs) > 0 { fmt.Printf("%s:\n", i18n.T(loc, "doctor.gpu")) for _, g := range rep.GPUs { tags := []string{} diff --git a/internal/host/host.go b/internal/host/host.go index 84e1203..e6cfe37 100644 --- a/internal/host/host.go +++ b/internal/host/host.go @@ -91,6 +91,7 @@ type Report struct { WHPXCaps WHPXCapabilities `json:"whpx_caps"` NeedsColdRebootWorkaround bool `json:"needs_cold_reboot_workaround"` GPUs []GPUInfo `json:"gpus"` + VulkanProbeError string `json:"vulkan_probe_error,omitempty"` RecommendedGPU *GPUInfo `json:"recommended_gpu,omitempty"` Displays []DisplayInfo `json:"displays,omitempty"` PrimaryDisplay *DisplayInfo `json:"primary_display,omitempty"` diff --git a/internal/host/host_windows.go b/internal/host/host_windows.go index 11da2fe..4e00778 100644 --- a/internal/host/host_windows.go +++ b/internal/host/host_windows.go @@ -64,11 +64,12 @@ type memoryStatusEx struct { } type staticHostSnapshot struct { - needsColdReboot bool - gpus []GPUInfo - recGPU *GPUInfo - topo hybridTopology - topoOK bool + needsColdReboot bool + gpus []GPUInfo + vulkanProbeError string + recGPU *GPUInfo + topo hybridTopology + topoOK bool } var ( @@ -82,7 +83,7 @@ var ( func getStaticHostSnapshot() staticHostSnapshot { staticHostOnce.Do(func() { - gpus := probeVulkanGPUs() + gpus, err := probeVulkanGPUs() topo, ok := probeHybridTopology() staticHostData = staticHostSnapshot{ needsColdReboot: probeNeedsColdRebootWorkaround(), @@ -91,6 +92,9 @@ func getStaticHostSnapshot() staticHostSnapshot { topo: topo, topoOK: ok, } + if err != nil { + staticHostData.vulkanProbeError = err.Error() + } }) return staticHostData } @@ -122,6 +126,7 @@ func Inspect(dataRoot string) Report { WHPX: probeWHPX(), NeedsColdRebootWorkaround: st.needsColdReboot, GPUs: gpusCopy, + VulkanProbeError: st.vulkanProbeError, RecommendedGPU: recGPUCopy, } if rep.WHPX == WHPXReady { @@ -545,10 +550,11 @@ func isUSBBusVolume(vol string) bool { // ProbeVulkanGPUs returns the current Vulkan adapters without using Inspect's cache. func ProbeVulkanGPUs() []GPUInfo { - return probeVulkanGPUs() + gpus, _ := probeVulkanGPUs() + return gpus } -func probeVulkanGPUs() []GPUInfo { +func probeVulkanGPUs() ([]GPUInfo, error) { const baseKey = `SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}` var regGPUs []GPUInfo for i := 0; i < 32; i++ { @@ -578,8 +584,8 @@ func probeVulkanGPUs() []GPUInfo { DriverVersion: drvVer, }) } - vkProbes := probeVulkanDevices() - return MergeRegistryAndVulkanGPUs(regGPUs, vkProbes) + vkProbes, err := probeVulkanDevices() + return MergeRegistryAndVulkanGPUs(regGPUs, vkProbes), err } func regReadString(root uintptr, subKey, valueName string) (string, bool) { diff --git a/internal/host/vulkan_windows.go b/internal/host/vulkan_windows.go index f9c1cab..01815fb 100644 --- a/internal/host/vulkan_windows.go +++ b/internal/host/vulkan_windows.go @@ -5,6 +5,7 @@ package host import ( "bytes" "encoding/binary" + "fmt" "syscall" "unsafe" ) @@ -50,21 +51,21 @@ type vkExtensionProperties struct { // probeVulkanDevices loads vulkan-1.dll and enumerates all visible Vulkan // physical devices along with their API version, PCI IDs, device type, and -// advertised device extensions. Returns nil cleanly if the Vulkan loader is -// absent or refuses instance creation. -func probeVulkanDevices() []VulkanDeviceProbe { +// advertised device extensions. An empty list with no error means enumeration succeeded. +func probeVulkanDevices() ([]VulkanDeviceProbe, error) { dll := syscall.NewLazyDLL("vulkan-1.dll") if err := dll.Load(); err != nil { - return nil + return nil, err } pCreateInst := dll.NewProc("vkCreateInstance") pDestroyInst := dll.NewProc("vkDestroyInstance") pEnumPhys := dll.NewProc("vkEnumeratePhysicalDevices") pGetProps := dll.NewProc("vkGetPhysicalDeviceProperties") pEnumExts := dll.NewProc("vkEnumerateDeviceExtensionProperties") - if pCreateInst.Find() != nil || pDestroyInst.Find() != nil || - pEnumPhys.Find() != nil || pGetProps.Find() != nil || pEnumExts.Find() != nil { - return nil + for _, proc := range []*syscall.LazyProc{pCreateInst, pDestroyInst, pEnumPhys, pGetProps, pEnumExts} { + if err := proc.Find(); err != nil { + return nil, err + } } appName := append([]byte("reims-go"), 0) @@ -92,15 +93,21 @@ func probeVulkanDevices() []VulkanDeviceProbe { uintptr(unsafe.Pointer(&instance)), ) } - if int32(res) != vkSuccess || instance == 0 { - return nil + if int32(res) != vkSuccess { + return nil, vulkanResultError("vkCreateInstance", int32(res)) + } + if instance == 0 { + return nil, fmt.Errorf("vkCreateInstance: VK_NULL_HANDLE") } defer pDestroyInst.Call(instance, 0) var count uint32 res, _, _ = pEnumPhys.Call(instance, uintptr(unsafe.Pointer(&count)), 0) - if (int32(res) != vkSuccess && int32(res) != vkIncomplete) || count == 0 { - return nil + if int32(res) != vkSuccess && int32(res) != vkIncomplete { + return nil, vulkanResultError("vkEnumeratePhysicalDevices", int32(res)) + } + if count == 0 { + return nil, nil } if count > 32 { count = 32 @@ -112,7 +119,7 @@ func probeVulkanDevices() []VulkanDeviceProbe { uintptr(unsafe.Pointer(&devices[0])), ) if int32(res) != vkSuccess && int32(res) != vkIncomplete { - return nil + return nil, vulkanResultError("vkEnumeratePhysicalDevices", int32(res)) } out := make([]VulkanDeviceProbe, 0, count) @@ -136,7 +143,14 @@ func probeVulkanDevices() []VulkanDeviceProbe { } out = append(out, probe) } - return out + return out, nil +} + +func vulkanResultError(call string, result int32) error { + if result == vkErrorIncompatibleDriver { + return fmt.Errorf("%s: VK_ERROR_INCOMPATIBLE_DRIVER (%d)", call, result) + } + return fmt.Errorf("%s: VkResult %d", call, result) } func probeVulkanDeviceExtensions(pEnumExts *syscall.LazyProc, pd uintptr) map[string]bool { diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 61dcba3..9c9ce59 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -90,6 +90,7 @@ var catalog = map[Locale]map[string]string{ "doctor.gpu.err.vulkan_cpu": "软件渲染 Vulkan 实现不满足 vGPU 硬件加速要求,请改用 VMware SVGA", "doctor.gpu.err.vulkan_too_old": "Vulkan 版本 {ver} 低于 1.3 最低要求,请更新显卡驱动或改用 VMware SVGA", "doctor.gpu.none": "未检测到已注册的 Vulkan ICD 显卡驱动", + "doctor.gpu.probe_failed": "Vulkan 探测失败({detail})。请运行 vulkaninfo --summary 检查驱动。", "doctor.gpu.recommended": "推荐", "doctor.gpu.warn.amd_legacy": "AMD Vega/Polaris 在 Windows 闭源驱动下存在上游已知黑屏/设备丢失问题({ref}),建议使用其他独显或在虚拟机设置改用 VMware SVGA", "doctor.gpu.warn.amd_rdna2": "该 AMD 显卡在 Windows 下存在上游已知设备丢失风险({ref}),若黑屏/卡死请升级驱动或临时改用 VMware SVGA", @@ -624,6 +625,7 @@ var catalog = map[Locale]map[string]string{ "doctor.gpu.err.vulkan_cpu": "Software Vulkan implementation does not meet the vGPU floor; use VMware SVGA instead", "doctor.gpu.err.vulkan_too_old": "Vulkan {ver} is below the required 1.3 floor; update your GPU driver or use VMware SVGA", "doctor.gpu.none": "No registered Vulkan ICD driver found", + "doctor.gpu.probe_failed": "Vulkan probe failed ({detail}). Run vulkaninfo --summary to check the driver.", "doctor.gpu.recommended": "Recommended", "doctor.gpu.warn.amd_legacy": "AMD Vega/Polaris on Windows hits known upstream black-screen/device-loss issues ({ref}); prefer another discrete GPU or switch the VM to VMware SVGA", "doctor.gpu.warn.amd_rdna2": "This AMD GPU hits known Windows device-loss issues upstream ({ref}); update drivers or switch temporarily to VMware SVGA if it freezes", @@ -1099,6 +1101,7 @@ var paramOrder = map[string][]string{ "doctor.ecores.detail": {"count", "cpus"}, "doctor.gpu.err.missing_ext": {"ext"}, "doctor.gpu.err.vulkan_too_old": {"ver"}, + "doctor.gpu.probe_failed": {"detail"}, "doctor.gpu.warn.amd_legacy": {"ref"}, "doctor.gpu.warn.amd_rdna2": {"ref"}, "doctor.pcores.detail": {"count", "mask", "cpus"}, diff --git a/locales/en-US/native.json b/locales/en-US/native.json index 0fdcee5..bffddc7 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -1,4 +1,5 @@ { + "doctor.gpu.probe_failed": "Vulkan probe failed ({detail}). Run vulkaninfo --summary to check the driver.", "doctor.title": "Reims-Go Host Environment Check", "doctor.os": "Operating System", "doctor.cpu": "CPU & Core Topology", diff --git a/locales/en-US/wizard.json b/locales/en-US/wizard.json index 6f0f83c..4491ef1 100644 --- a/locales/en-US/wizard.json +++ b/locales/en-US/wizard.json @@ -1,4 +1,5 @@ { + "vulkanProbeFailed": "Vulkan probe failed ({detail}). Run vulkaninfo --summary to check the driver.", "setupTitle": "Choose a data folder", "setupDesc": "VMs, installers and runtimes all live here", "setupOther": "Other location…", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index 91ce361..06c638b 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -1,4 +1,5 @@ { + "doctor.gpu.probe_failed": "Vulkan 探测失败({detail})。请运行 vulkaninfo --summary 检查驱动。", "doctor.title": "Reims-Go 宿主机环境体检", "doctor.os": "操作系统", "doctor.cpu": "处理器与核心拓扑", diff --git a/locales/zh-CN/wizard.json b/locales/zh-CN/wizard.json index 93fca8c..56708ca 100644 --- a/locales/zh-CN/wizard.json +++ b/locales/zh-CN/wizard.json @@ -1,4 +1,5 @@ { + "vulkanProbeFailed": "Vulkan 探测失败({detail})。请运行 vulkaninfo --summary 检查驱动。", "setupTitle": "选择数据目录", "setupDesc": "虚拟机、安装包和运行时都放在这里", "setupOther": "其他位置…", From 6628da21ffcdd7153beeada99be434b55a61507e Mon Sep 17 00:00:00 2001 From: ChenRuoT Date: Tue, 1 Dec 2026 13:17:18 +0800 Subject: [PATCH 23/42] fix(host): discover missing Vulkan ICDs in active display driver packages --- internal/host/host_other.go | 2 + internal/host/host_windows.go | 10 +- internal/host/host_windows_test.go | 17 +++ internal/host/vulkan_driverstore_windows.go | 153 ++++++++++++++++++++ internal/runtime/runtime.go | 2 + 5 files changed, 183 insertions(+), 1 deletion(-) create mode 100644 internal/host/vulkan_driverstore_windows.go diff --git a/internal/host/host_other.go b/internal/host/host_other.go index 9cfb949..3958091 100644 --- a/internal/host/host_other.go +++ b/internal/host/host_other.go @@ -29,6 +29,8 @@ func Inspect(dataRoot string) Report { } } +func ConfigureVulkanDrivers() {} + // ProbeVulkanGPUs returns no adapters on hosts without Windows Vulkan probing. func ProbeVulkanGPUs() []GPUInfo { return nil diff --git a/internal/host/host_windows.go b/internal/host/host_windows.go index 4e00778..9c4ff47 100644 --- a/internal/host/host_windows.go +++ b/internal/host/host_windows.go @@ -584,8 +584,16 @@ func probeVulkanGPUs() ([]GPUInfo, error) { DriverVersion: drvVer, }) } + recovered := recoveredManifests() vkProbes, err := probeVulkanDevices() - return MergeRegistryAndVulkanGPUs(regGPUs, vkProbes), err + gpus := MergeRegistryAndVulkanGPUs(regGPUs, vkProbes) + for i, gpu := range gpus { + if gpu.VulkanICD != "" || gpu.VulkanVersion == "" { + continue + } + gpus[i].VulkanICD = recovered[gpu.VendorID+":"+gpu.DeviceID] + } + return gpus, err } func regReadString(root uintptr, subKey, valueName string) (string, bool) { diff --git a/internal/host/host_windows_test.go b/internal/host/host_windows_test.go index 8d85fa2..5984dd8 100644 --- a/internal/host/host_windows_test.go +++ b/internal/host/host_windows_test.go @@ -3,10 +3,27 @@ package host import ( + "maps" "os" "testing" ) +func TestMissingDriverPackages(t *testing.T) { + candidates := []adapterManifest{ + {"10de:28e0", "nvidia.json"}, + {"10de:28e0", "nvidia.json"}, + {"8086:1234", "intel.json"}, + {"1002:5678", "amd-a.json"}, + {"1002:5678", "amd-b.json"}, + {"1002:5678", "amd-a.json"}, + } + visible := []VulkanDeviceProbe{{VendorID: 0x8086, DeviceID: 0x1234}} + got := missingDriverPackages(candidates, visible) + if !maps.Equal(got, map[string]string{"10de:28e0": "nvidia.json"}) { + t.Fatalf("expected only the missing unambiguous device, got %v", got) + } +} + func TestWindowsProcessAffinityAndTopology(t *testing.T) { pid := uint32(os.Getpid()) procMask, sysMask, err := GetProcessAffinityMask(pid) diff --git a/internal/host/vulkan_driverstore_windows.go b/internal/host/vulkan_driverstore_windows.go new file mode 100644 index 0000000..7eef430 --- /dev/null +++ b/internal/host/vulkan_driverstore_windows.go @@ -0,0 +1,153 @@ +package host + +import ( + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "unsafe" + + "golang.org/x/sys/windows" +) + +const displayClass = "{4d36e968-e325-11ce-bfc1-08002be10318}" + +var infStoreLocation = windows.NewLazySystemDLL("setupapi.dll").NewProc("SetupGetInfDriverStoreLocationW") + +// Look only in the installed INF's package. DriverStore can also contain +// older versions of the same vendor's driver. +func driverStoreManifest(inf, vendor string) string { + if !filepath.IsLocal(inf) || filepath.Base(inf) != inf || !strings.EqualFold(filepath.Ext(inf), ".inf") { + return "" + } + var names []string + switch vendor { + case "10de": + names = []string{"nv-vk64.json"} + case "8086": + names = []string{"igvk64.json"} + case "1002": + names = []string{"amd-vulkan64.json", "amdvlk64.json"} + default: + return "" + } + input, err := windows.UTF16PtrFromString(inf) + if err != nil { + return "" + } + var size uint32 + infStoreLocation.Call(uintptr(unsafe.Pointer(input)), 0, 0, 0, 0, uintptr(unsafe.Pointer(&size))) + if size == 0 { + return "" + } + buf := make([]uint16, size) + ok, _, _ := infStoreLocation.Call(uintptr(unsafe.Pointer(input)), 0, 0, uintptr(unsafe.Pointer(&buf[0])), uintptr(size), 0) + if ok == 0 { + return "" + } + dir := filepath.Dir(windows.UTF16ToString(buf)) + var manifest string + for _, name := range names { + path := filepath.Join(dir, name) + if info, err := os.Stat(path); err == nil && info.Mode().IsRegular() { + if manifest != "" { + return "" // Multiple driver implementations in this package. + } + manifest = path + } + } + return manifest +} + +type adapterManifest struct { + id, path string +} + +func unregisteredDriverManifests() []adapterManifest { + guid, _ := windows.GUIDFromString(displayClass) + devs, err := windows.SetupDiGetClassDevsEx(&guid, "", 0, windows.DIGCF_PRESENT, 0, "") + if err != nil { + return nil + } + defer devs.Close() + var candidates []adapterManifest + for i := 0; ; i++ { + dev, err := devs.EnumDeviceInfo(i) + if err != nil { + break + } + id, _ := devs.DeviceInstanceID(dev) + vendor, device := ParsePCIIDs(id) + if device == "" || !strings.HasPrefix(strings.ToUpper(id), `PCI\`) { + continue + } + value, _ := devs.DeviceRegistryProperty(dev, windows.SPDRP_DRIVER) + driverKey, ok := value.(string) + if !ok || driverKey == "" { + continue + } + sub := `SYSTEM\CurrentControlSet\Control\Class\` + driverKey + if path, _ := regReadString(hkeyLocalMachine, sub, "VulkanDriverName"); path != "" { + if info, err := os.Stat(path); err == nil && info.Mode().IsRegular() { + continue + } + } + inf, _ := regReadString(hkeyLocalMachine, sub, "InfPath") + if path := driverStoreManifest(inf, vendor); path != "" { + candidates = append(candidates, adapterManifest{vendor + ":" + device, path}) + } + } + return candidates +} + +// Only bind a PCI ID to a manifest when its active driver package is unambiguous +// and the loader has not already enumerated that GPU through another source. +func missingDriverPackages(candidates []adapterManifest, probes []VulkanDeviceProbe) map[string]string { + packages := make(map[string]string) + for _, c := range candidates { + if previous, seen := packages[c.id]; seen && previous != c.path { + packages[c.id] = "" + } else { + packages[c.id] = c.path + } + } + for _, p := range probes { + delete(packages, fmt.Sprintf("%04x:%04x", p.VendorID, p.DeviceID)) + } + for id, path := range packages { + if path == "" { + delete(packages, id) + } + } + return packages +} + +var recoveredManifests = sync.OnceValue(func() map[string]string { + for _, key := range []string{"VK_DRIVER_FILES", "VK_ICD_FILENAMES", "VK_ADD_DRIVER_FILES"} { + if _, set := os.LookupEnv(key); set { + return nil + } + } + candidates := unregisteredDriverManifests() + if len(candidates) == 0 { + return nil + } + probes, _ := probeVulkanDevices() + missing := missingDriverPackages(candidates, probes) + var paths []string + for _, path := range missing { + if !slices.Contains(paths, path) { + paths = append(paths, path) + } + } + slices.Sort(paths) + if len(paths) == 0 || os.Setenv("VK_ADD_DRIVER_FILES", strings.Join(paths, ";")) != nil { + return nil + } + return missing +}) + +// ConfigureVulkanDrivers prepares process-local discovery for runtime children. +func ConfigureVulkanDrivers() { recoveredManifests() } diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index bc470cf..5ba7999 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -17,6 +17,7 @@ import ( "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/fetch" + "github.com/Nwflower/reims-go/internal/host" "github.com/klauspost/compress/zstd" ) @@ -278,6 +279,7 @@ func BuildChildEnv(cfg *config.Config, rt Installed) []string { "TMP": tmpDir, "TMPDIR": tmpDir, } + host.ConfigureVulkanDrivers() env := os.Environ() out := make([]string, 0, len(env)+len(overrides)) seenPath := false From cbcbec7f836ec306137236f3d25312498be5f625 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BA=8B=E4=BA=8B=E4=BC=91?= <70455176+yfl520@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:36:40 +0800 Subject: [PATCH 24/42] feat(opencore,ui): add one-click OpenCore SMBIOS identity rotation --- frontend/src/components/SettingsModal.tsx | 251 +++++++++++- frontend/src/i18n/domains/settings.gen.ts | 40 ++ frontend/src/i18n/keys.gen.ts | 20 + frontend/src/types.ts | 3 +- frontend/wailsjs/go/app/App.d.ts | 15 +- frontend/wailsjs/go/app/App.js | 28 +- frontend/wailsjs/go/models.ts | 27 +- internal/app/opencore_flow.go | 91 +++++ internal/opencore/image.go | 50 ++- internal/opencore/plist.go | 6 +- internal/opencore/smbios.go | 447 ++++++++++++++++++++++ internal/opencore/smbios_test.go | 158 ++++++++ locales/en-US/settings.json | 22 +- locales/zh-CN/settings.json | 22 +- 14 files changed, 1141 insertions(+), 39 deletions(-) create mode 100644 internal/opencore/smbios.go create mode 100644 internal/opencore/smbios_test.go diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index 7eaee4d..197f7b8 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -1,4 +1,4 @@ -import { CircleAlert, Copy, Cpu, HardDrive, Info, Keyboard, LucideIcon, Monitor, Wrench } from 'lucide-react' +import { CircleAlert, Copy, Cpu, Eye, EyeOff, HardDrive, Info, Keyboard, LucideIcon, Monitor, Shuffle, Wrench } from 'lucide-react' import React, { Suspense, lazy, useEffect, useMemo, useRef, useState } from 'react' import '../i18n/domains/settings.gen' import { I18nKey, parseAppError, t } from '../i18n' @@ -25,7 +25,7 @@ import { sshCommand, } from '../lib/format' import { applyKernelIrqchip, findOptimization, kernelIrqchipHint, parseKernelIrqchip } from '../lib/optimizations' -import { DiskCompactResult, DiskResizeResult, DriveShareSettings, HostReport, Locale, Optimization, PluginInfo, SetOpts, ValidationIssue, VMAffinityStatus, VMDetail, VMStats } from '../types' +import { DiskCompactResult, DiskResizeResult, DriveShareSettings, HostReport, Locale, Optimization, PluginInfo, SetOpts, SMBIOSIdentity, ValidationIssue, VMAffinityStatus, VMDetail, VMStats } from '../types' import { Button, IconButton } from '../ui/controls' import { Modal } from '../ui/dialog' import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, SetValue, Switch } from '../ui/settings' @@ -81,6 +81,13 @@ const RES_RE = /^\s*\d{3,5}\s*[x×]\s*\d{3,5}\s*$/i const normPath = (s: string | undefined) => (s ?? '').replace(/\//g, '\\').toLowerCase() const normRes = (s: string | undefined) => (s ?? '').replace(/\s/g, '').replace(/×/g, 'x').toLowerCase() +function maskIdentity(v: string | undefined, head = 4, tail = 4): string { + const s = (v ?? '').trim() + if (!s) return '—' + if (s.length <= head + tail) return '•'.repeat(s.length) + return `${s.slice(0, head)}••••${s.slice(-tail)}` +} + /** Whether two values of a field mean the same thing to reims-ctl. */ function same(field: Field, a: SetOpts[Field], b: SetOpts[Field]): boolean { switch (field) { @@ -161,6 +168,14 @@ export const SettingsModal: React.FC = ({ locale, detail, stats, host, op const [affinityStatus, setAffinityStatus] = useState(null) const [vmPlugins, setVmPlugins] = useState([]) const [vmPluginVals, setVmPluginVals] = useState>>({}) + const [smbios, setSmbios] = useState(null) + const [smbiosErr, setSmbiosErr] = useState('') + const [smbiosReveal, setSmbiosReveal] = useState(false) + const [smbiosOpen, setSmbiosOpen] = useState(false) + const [smbiosDraft, setSmbiosDraft] = useState(null) + const [smbiosBusy, setSmbiosBusy] = useState<'' | 'generate' | 'apply'>('') + const [smbiosModalErr, setSmbiosModalErr] = useState('') + const [smbiosApplied, setSmbiosApplied] = useState(false) const pane = useRef(null) useEffect(() => { @@ -281,6 +296,70 @@ export const SettingsModal: React.FC = ({ locale, detail, stats, host, op return () => { active = false } }, [detail.name, running, affinityVersion]) + useEffect(() => { + let active = true + setSmbios(null) + setSmbiosErr('') + setSmbiosReveal(false) + setSmbiosApplied(false) + if (!detail.has_opencore) return () => { active = false } + api.GetVMSMBIOS(detail.name) + .then((id) => { if (active) setSmbios(id) }) + .catch((e) => { if (active) setSmbiosErr(parseAppError(e).summary) }) + return () => { active = false } + }, [detail.name, detail.has_opencore]) + + const smbiosLocked = running || detail.state === 'suspended' || !!detail.suspend_info + + const handleGenerateSmbios = async (modelOverride?: string) => { + setSmbiosModalErr('') + setSmbiosBusy('generate') + try { + const generated = await api.GenerateVMSMBIOS(modelOverride ?? smbios?.model ?? '') + setSmbiosDraft({ + model: smbios?.model || generated.model, + serial: generated.serial, + mlb: generated.mlb, + uuid: generated.uuid, + rom: smbios?.rom || '', + }) + } catch (e) { + setSmbiosModalErr(parseAppError(e).summary) + } finally { + setSmbiosBusy('') + } + } + + const openSmbiosRotate = () => { + if (smbiosLocked) return + setSmbiosModalErr('') + setSmbiosApplied(false) + setSmbiosOpen(true) + void handleGenerateSmbios(smbios?.model ?? '') + } + + const handleApplySmbios = async () => { + if (smbiosLocked || smbiosBusy || !smbiosDraft) return + setSmbiosModalErr('') + setSmbiosBusy('apply') + try { + const updated = await api.ApplyVMSMBIOS(detail.name, { + model: smbios?.model || smbiosDraft.model || '', + serial: smbiosDraft.serial, + mlb: smbiosDraft.mlb, + uuid: smbiosDraft.uuid, + rom: smbios?.rom || '', + }) + setSmbios(updated) + setSmbiosOpen(false) + setSmbiosApplied(true) + } catch (e) { + setSmbiosModalErr(parseAppError(e).summary) + } finally { + setSmbiosBusy('') + } + } + const updateDriveShares = async (enabled: boolean, selected: string[]) => { if (driveBusyRef.current || !driveSettings) return driveBusyRef.current = true @@ -386,13 +465,66 @@ export const SettingsModal: React.FC = ({ locale, detail, stats, host, op } /> - + + {detail.has_opencore && ( + + + )} {renderVMPluginGroup('collaboration')} ) @@ -1072,6 +1204,119 @@ export const SettingsModal: React.FC = ({ locale, detail, stats, host, op
+ {smbiosOpen && ( + setSmbiosOpen(false)} + > +
+
+ {tr('smbiosWarning')} +
+
+ + {onCopy && smbiosDraft?.serial && ( + + )} +
+ + + + {smbios?.rom && ( +
+ {tr('smbiosROM')}: {smbios.rom} +
+ )} +
{tr('smbiosCheckHint')}
+ {smbiosModalErr &&
{smbiosModalErr}
} +
+
+ + + + + +
+
+ )} ) } diff --git a/frontend/src/i18n/domains/settings.gen.ts b/frontend/src/i18n/domains/settings.gen.ts index 3a65bcd..bcc3f4b 100644 --- a/frontend/src/i18n/domains/settings.gen.ts +++ b/frontend/src/i18n/domains/settings.gen.ts @@ -274,6 +274,26 @@ export const settingsZh: Record = { "settingsAppearance": "外观与语言", "settingsGeneral": "常规", "settingsTitle": "{name}", + "smbiosApplied": "已写入新的 OpenCore 设备码,下次启动虚拟机生效", + "smbiosApply": "写入新设备码", + "smbiosCheckHint": "建议将序列号复制到 checkcoverage.apple.com 确认显示「无效序列号」(未被真机占用)后再写入。", + "smbiosCopySerial": "复制序列号", + "smbiosDesc": "写入 OpenCore 的序列号、主板号 (MLB) 与 UUID,用于 Apple 服务识别。ROM 与虚拟网卡 MAC 保持同步,换码时不会修改。", + "smbiosDialogSub": "只修改序列号、MLB 与 SystemUUID,保留原 ROM(网卡 MAC)与 NVRAM", + "smbiosDialogTitle": "更换 OpenCore 设备码", + "smbiosGenerate": "随机生成一组", + "smbiosHide": "隐藏", + "smbiosLoadFailed": "无法读取 OpenCore 设备码", + "smbiosMLB": "主板号 (MLB)", + "smbiosModel": "机型", + "smbiosROM": "网卡 ROM", + "smbiosRotateBtn": "一键换码…", + "smbiosSerial": "序列号", + "smbiosShow": "显示完整码", + "smbiosStopRequired": "请先彻底关机(不能处于运行或休眠状态)", + "smbiosTitle": "设备身份 (SMBIOS)", + "smbiosUUID": "系统 UUID", + "smbiosWarning": "换码前请先在 macOS 中退出 Apple 账户并彻底关机;换码后首次开机可能弹出「设置助理」,iCloud / App Store 需重新登录。", "sourceDisk": "已有虚拟磁盘(.qcow2)", "sourceInstaller": "本地安装器镜像(.img / .dmg)", "sshForward": "SSH 端口转发", @@ -591,6 +611,26 @@ export const settingsEn: Record = { "settingsAppearance": "Appearance \u0026 language", "settingsGeneral": "General", "settingsTitle": "{name}", + "smbiosApplied": "Updated OpenCore SMBIOS identity. Applies on next start", + "smbiosApply": "Write new codes", + "smbiosCheckHint": "Tip: check the serial at checkcoverage.apple.com and verify it reports invalid (not registered to a real Mac) before writing.", + "smbiosCopySerial": "Copy serial", + "smbiosDesc": "Serial, MLB and UUID written to OpenCore for Apple services. ROM stays synced with the virtual NIC MAC and is left unchanged.", + "smbiosDialogSub": "Updates Serial, MLB and SystemUUID only; keeps ROM (NIC MAC) and NVRAM intact", + "smbiosDialogTitle": "Rotate OpenCore SMBIOS", + "smbiosGenerate": "Generate random", + "smbiosHide": "Hide", + "smbiosLoadFailed": "Could not read OpenCore SMBIOS", + "smbiosMLB": "MLB", + "smbiosModel": "Model", + "smbiosROM": "NIC ROM", + "smbiosRotateBtn": "Rotate codes…", + "smbiosSerial": "Serial", + "smbiosShow": "Reveal", + "smbiosStopRequired": "Shut down the VM completely first (not running or suspended)", + "smbiosTitle": "Device identity (SMBIOS)", + "smbiosUUID": "System UUID", + "smbiosWarning": "Sign out of Apple Account in macOS and shut down completely before rotating. First boot may show Setup Assistant and require signing in to iCloud / App Store again.", "sourceDisk": "Existing virtual disk (.qcow2)", "sourceInstaller": "Local installer image (.img / .dmg)", "sshForward": "SSH port forwarding", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 9ee8854..dd00da6 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -697,6 +697,26 @@ export type I18nKey = | "sidebarSettings" | "sidebarSystem" | "sidebarVMs" + | "smbiosApplied" + | "smbiosApply" + | "smbiosCheckHint" + | "smbiosCopySerial" + | "smbiosDesc" + | "smbiosDialogSub" + | "smbiosDialogTitle" + | "smbiosGenerate" + | "smbiosHide" + | "smbiosLoadFailed" + | "smbiosMLB" + | "smbiosModel" + | "smbiosROM" + | "smbiosRotateBtn" + | "smbiosSerial" + | "smbiosShow" + | "smbiosStopRequired" + | "smbiosTitle" + | "smbiosUUID" + | "smbiosWarning" | "snapshotCreate" | "snapshotDelete" | "snapshotEmpty" diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 92b48b5..05f9d8a 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -1,7 +1,7 @@ // Backend types come from the Wails-generated models (wailsjs/go/models.ts, // regenerated by `wails dev` / `wails build`). This file only adds what Go // cannot say: string unions, and `| null` for slices Go may send as nil. -import { app, config, driver, host, installer, plugin, reims, runtime, version } from '../wailsjs/go/models' +import { app, config, driver, host, installer, opencore, plugin, reims, runtime, version } from '../wailsjs/go/models' /** A generated class as a plain data shape (no convertValues helper). */ type Model = Omit @@ -65,6 +65,7 @@ export type AppState = Omit, 'config' | 'host' | 'optimizati export type AppUpdateInfo = version.UpdateInfo export type SuspendInfo = reims.SuspendInfo export type VMDetail = reims.VMDetail +export type SMBIOSIdentity = opencore.SMBIOSIdentity export type VMStats = app.VMStats export type DriveShareSettings = Model export type VMAffinityMode = 'auto' | 'all' | 'pcores' | 'non_lpe' | 'custom' diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index ded8dce..37c71b7 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -1,5 +1,6 @@ // Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL // This file is automatically generated. DO NOT EDIT +import {opencore} from '../models'; import {reims} from '../models'; import {plugin} from '../models'; import {version} from '../models'; @@ -9,6 +10,8 @@ import {runtime} from '../models'; import {installer} from '../models'; import {http} from '../models'; +export function ApplyVMSMBIOS(arg1:string,arg2:opencore.SMBIOSIdentity):Promise; + export function ApplyVMSettings(arg1:reims.SetOpts):Promise; export function AttachGuestTools(arg1:string):Promise; @@ -47,8 +50,6 @@ export function DeleteSnapshot(arg1:string,arg2:string):Promise; export function DeleteVM(arg1:string,arg2:boolean):Promise; -export function DiscardSuspend(arg1:string):Promise; - export function DeliverFileToGuest(arg1:string):Promise; export function DeliverPathsToGuest(arg1:string,arg2:Array):Promise>; @@ -57,6 +58,8 @@ export function DetachGuestTools(arg1:string):Promise; export function DisablePlugin(arg1:string):Promise; +export function DiscardSuspend(arg1:string):Promise; + export function DismissTask(arg1:string):Promise; export function DoctorPlugin(arg1:string):Promise>; @@ -81,6 +84,8 @@ export function FinishInstall(arg1:string):Promise; export function FocusVMWindow(arg1:string):Promise; +export function GenerateVMSMBIOS(arg1:string):Promise; + export function GetActiveTheme():Promise; export function GetLicenseTexts():Promise; @@ -107,6 +112,8 @@ export function GetVMNote(arg1:string):Promise; export function GetVMPluginSettings(arg1:string):Promise>>; +export function GetVMSMBIOS(arg1:string):Promise; + export function GetVMSSHUser(arg1:string):Promise; export function GetVMStats(arg1:string):Promise; @@ -185,10 +192,10 @@ export function ResizeVMDisk(arg1:string,arg2:string):Promise; -export function ResumeVM(arg1:string):Promise; - export function RestoreSnapshot(arg1:string,arg2:string):Promise; +export function ResumeVM(arg1:string):Promise; + export function SaveCustomThemeScheme(arg1:plugin.CustomThemeScheme):Promise; export function ScanInstalledPlugin(arg1:string):Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index da78976..85cf3c9 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -2,6 +2,10 @@ // Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL // This file is automatically generated. DO NOT EDIT +export function ApplyVMSMBIOS(arg1, arg2) { + return window['go']['app']['App']['ApplyVMSMBIOS'](arg1, arg2); +} + export function ApplyVMSettings(arg1) { return window['go']['app']['App']['ApplyVMSettings'](arg1); } @@ -78,10 +82,6 @@ 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 DeliverFileToGuest(arg1) { return window['go']['app']['App']['DeliverFileToGuest'](arg1); } @@ -98,6 +98,10 @@ export function DisablePlugin(arg1) { return window['go']['app']['App']['DisablePlugin'](arg1); } +export function DiscardSuspend(arg1) { + return window['go']['app']['App']['DiscardSuspend'](arg1); +} + export function DismissTask(arg1) { return window['go']['app']['App']['DismissTask'](arg1); } @@ -146,6 +150,10 @@ export function FocusVMWindow(arg1) { return window['go']['app']['App']['FocusVMWindow'](arg1); } +export function GenerateVMSMBIOS(arg1) { + return window['go']['app']['App']['GenerateVMSMBIOS'](arg1); +} + export function GetActiveTheme() { return window['go']['app']['App']['GetActiveTheme'](); } @@ -198,6 +206,10 @@ export function GetVMPluginSettings(arg1) { return window['go']['app']['App']['GetVMPluginSettings'](arg1); } +export function GetVMSMBIOS(arg1) { + return window['go']['app']['App']['GetVMSMBIOS'](arg1); +} + export function GetVMSSHUser(arg1) { return window['go']['app']['App']['GetVMSSHUser'](arg1); } @@ -354,14 +366,14 @@ export function RestartVM(arg1) { return window['go']['app']['App']['RestartVM'](arg1); } -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 ResumeVM(arg1) { + return window['go']['app']['App']['ResumeVM'](arg1); +} + export function SaveCustomThemeScheme(arg1) { return window['go']['app']['App']['SaveCustomThemeScheme'](arg1); } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 7d181bf..302b5b4 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -892,6 +892,31 @@ export namespace installer { } +export namespace opencore { + + export class SMBIOSIdentity { + model: string; + serial: string; + mlb: string; + uuid: string; + rom?: string; + + static createFrom(source: any = {}) { + return new SMBIOSIdentity(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.model = source["model"]; + this.serial = source["serial"]; + this.mlb = source["mlb"]; + this.uuid = source["uuid"]; + this.rom = source["rom"]; + } + } + +} + export namespace plugin { export class CustomThemeScheme { @@ -2437,7 +2462,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; diff --git a/internal/app/opencore_flow.go b/internal/app/opencore_flow.go index 862d4e6..9092e2a 100644 --- a/internal/app/opencore_flow.go +++ b/internal/app/opencore_flow.go @@ -1,9 +1,13 @@ package app import ( + "fmt" + "github.com/Nwflower/reims-go/internal/driver/reims" "github.com/Nwflower/reims-go/internal/opencore" + rt "github.com/Nwflower/reims-go/internal/runtime" "github.com/Nwflower/reims-go/internal/vmstart" + wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) // populateGuestLangDetail fills VMDetail.GuestLang from the VM's persisted @@ -32,3 +36,90 @@ func (a *App) prep(name string) (*vmstart.Prep, error) { a.mu.Unlock() return vmstart.New(cfg, func(line string) { a.emitLog(name, line) }) } + +// GetVMSMBIOS reads the VM's OpenCore PlatformInfo > Generic identity +// (SystemProductName, SystemSerialNumber, MLB, SystemUUID, and read-only ROM). +// Values are returned directly to the UI and never written to app or VM logs. +func (a *App) GetVMSMBIOS(name string) (opencore.SMBIOSIdentity, error) { + a.mu.Lock() + cfgCopy := *a.cfg + a.mu.Unlock() + active, err := rt.ResolveActive(&cfgCopy) + if err != nil { + return opencore.SMBIOSIdentity{}, err + } + c := reims.NewClient(&cfgCopy, *active) + d, err := c.Show(a.baseCtx(), name) + if err != nil { + return opencore.SMBIOSIdentity{}, err + } + ocPath := opencore.ResolveOpenCorePath(d.Directory) + if ocPath == "" { + return opencore.SMBIOSIdentity{}, fmt.Errorf("VM %s has no OpenCore image", name) + } + return opencore.ReadImageSMBIOS(ocPath) +} + +// GenerateVMSMBIOS creates a cryptographically random, format-valid Mac SMBIOS +// candidate (Serial, Base-34 checksummed MLB, and UUID v4) for the given model +// (defaulting to iMac20,1) without modifying disk state. +func (a *App) GenerateVMSMBIOS(model string) (opencore.SMBIOSIdentity, error) { + return opencore.GenerateSMBIOS(model) +} + +// ApplyVMSMBIOS writes new SystemSerialNumber, MLB, and SystemUUID values into +// a stopped VM's OpenCore image while keeping ROM untouched so it stays synced +// with the VM's network MAC address. +func (a *App) ApplyVMSMBIOS(name string, id opencore.SMBIOSIdentity) (opencore.SMBIOSIdentity, error) { + norm, err := opencore.NormalizeAndValidateSMBIOS(id) + if err != nil { + return opencore.SMBIOSIdentity{}, err + } + a.mu.Lock() + cfgCopy := *a.cfg + a.mu.Unlock() + active, err := rt.ResolveActive(&cfgCopy) + if err != nil { + return opencore.SMBIOSIdentity{}, err + } + c := reims.NewClient(&cfgCopy, *active) + ctx := a.baseCtx() + + d, release, err := vmstart.LockVM(ctx, c, name) + if err != nil { + return opencore.SMBIOSIdentity{}, err + } + defer release() + if a.isVMRunning(ctx, c, name, d) { + return opencore.SMBIOSIdentity{}, fmt.Errorf("stop %s before updating its SMBIOS identity", name) + } + if a.isVMSuspended(d) { + return opencore.SMBIOSIdentity{}, fmt.Errorf("resume or discard suspend state for %s before updating its SMBIOS identity", name) + } + ocPath := opencore.ResolveOpenCorePath(d.Directory) + if ocPath == "" { + return opencore.SMBIOSIdentity{}, fmt.Errorf("VM %s has no OpenCore image", name) + } + + env := rt.BuildChildEnv(&cfgCopy, *active) + changed, err := opencore.PatchImageSMBIOS(ctx, ocPath, norm, active.QemuImgPath(), env) + if err != nil { + return opencore.SMBIOSIdentity{}, err + } + updated, err := opencore.ReadImageSMBIOS(ocPath) + if err != nil { + return opencore.SMBIOSIdentity{}, err + } + if changed { + modelLabel := updated.Model + if modelLabel == "" { + modelLabel = "default" + } + // Never log Serial, MLB, UUID, or ROM into VM/app logs. + a.emitLog(name, fmt.Sprintf("Updated OpenCore SMBIOS identity (%s)", modelLabel)) + if a.ctx != nil { + wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + } + } + return updated, nil +} diff --git a/internal/opencore/image.go b/internal/opencore/image.go index ecc034e..a5e9d67 100644 --- a/internal/opencore/image.go +++ b/internal/opencore/image.go @@ -640,7 +640,9 @@ func ReadImagePrevLang(imagePath string) (string, error) { return lang, nil } -func patchImageDirect(imagePath, lang string) (changed bool, err error) { +type plistPatcher func(orig []byte) (patched []byte, changed bool, err error) + +func patchImageDirectWith(imagePath string, fn plistPatcher) (changed bool, err error) { d, isQcow2, err := openDisk(imagePath, true) if err != nil { return false, err @@ -659,11 +661,8 @@ func patchImageDirect(imagePath, lang string) (changed bool, err error) { if err != nil { return false, err } - if cur, ok := ReadPrevLang(orig); ok && cur == lang { - return false, nil - } - patched, err := PatchPrevLang(orig, lang) - if err != nil { + patched, changed, err := fn(orig) + if err != nil || !changed { return false, err } if err := fs.writeFile(entry, patched, !isQcow2); err != nil { @@ -672,6 +671,17 @@ func patchImageDirect(imagePath, lang string) (changed bool, err error) { return true, nil } +func patchImageConfigPlist(ctx context.Context, imagePath, qemuImgPath string, env []string, fn plistPatcher) (bool, error) { + changed, err := patchImageDirectWith(imagePath, fn) + if err == nil { + return changed, nil + } + if !errors.Is(err, errNeedsConvertFallback) || strings.TrimSpace(qemuImgPath) == "" { + return false, err + } + return patchQcow2ViaRawWith(ctx, imagePath, qemuImgPath, env, fn) +} + // PatchImagePrevLang updates NVRAM > Add > 7C436110-... > prev-lang:kbd inside // imagePath (opencore.qcow2 or opencore.img). Fast in-place pure-Go patching is // used whenever clusters are directly writable; if a qcow2 image needs cluster @@ -685,27 +695,29 @@ func PatchImagePrevLang(ctx context.Context, imagePath, lang, qemuImgPath string if norm == "" { return false, nil } - changed, err := patchImageDirect(imagePath, norm) - if err == nil { - return changed, nil - } - if !errors.Is(err, errNeedsConvertFallback) || strings.TrimSpace(qemuImgPath) == "" { - return false, err - } - return patchQcow2ViaRaw(ctx, imagePath, norm, qemuImgPath, env) + return patchImageConfigPlist(ctx, imagePath, qemuImgPath, env, func(orig []byte) ([]byte, bool, error) { + if cur, ok := ReadPrevLang(orig); ok && cur == norm { + return nil, false, nil + } + patched, err := PatchPrevLang(orig, norm) + if err != nil { + return nil, false, err + } + return patched, true, nil + }) } -func patchQcow2ViaRaw(ctx context.Context, qcow2Path, lang, qemuImgPath string, env []string) (bool, error) { +func patchQcow2ViaRawWith(ctx context.Context, qcow2Path, qemuImgPath string, env []string, fn plistPatcher) (bool, error) { dir := filepath.Dir(qcow2Path) - rawTmp := filepath.Join(dir, ".opencore-lang-patch.raw.tmp") - qcowTmp := filepath.Join(dir, ".opencore-lang-patch.qcow2.tmp") + rawTmp := filepath.Join(dir, ".opencore-patch.raw.tmp") + qcowTmp := filepath.Join(dir, ".opencore-patch.qcow2.tmp") defer os.Remove(rawTmp) defer os.Remove(qcowTmp) if err := runQemuImg(ctx, qemuImgPath, env, "convert", "-f", "qcow2", "-O", "raw", qcow2Path, rawTmp); err != nil { return false, fmt.Errorf("convert opencore to raw: %w", err) } - changed, err := patchImageDirect(rawTmp, lang) + changed, err := patchImageDirectWith(rawTmp, fn) if err != nil { return false, err } @@ -717,7 +729,7 @@ func patchQcow2ViaRaw(ctx context.Context, qcow2Path, lang, qemuImgPath string, } if err := os.Rename(qcowTmp, qcow2Path); err != nil { // On Windows os.Rename fails if destination already exists; swap via backup. - bak := qcow2Path + ".lang.bak" + bak := qcow2Path + ".patch.bak" _ = os.Remove(bak) if berr := os.Rename(qcow2Path, bak); berr != nil { return false, fmt.Errorf("replace opencore image: %w", berr) diff --git a/internal/opencore/plist.go b/internal/opencore/plist.go index c0e595d..e77a21b 100644 --- a/internal/opencore/plist.go +++ b/internal/opencore/plist.go @@ -286,6 +286,10 @@ func PatchPrevLang(src []byte, lang string) ([]byte, error) { } // Apply patches in reverse byte-offset order so earlier offsets stay valid. + return applyBytePatches(src, patches), nil +} + +func applyBytePatches(src []byte, patches []bytePatch) []byte { out := append([]byte(nil), src...) for i := 0; i < len(patches); i++ { for j := i + 1; j < len(patches); j++ { @@ -301,5 +305,5 @@ func PatchPrevLang(src []byte, lang string) ([]byte, error) { buf = append(buf, out[p.end:]...) out = buf } - return out, nil + return out } diff --git a/internal/opencore/smbios.go b/internal/opencore/smbios.go new file mode 100644 index 0000000..c6848fd --- /dev/null +++ b/internal/opencore/smbios.go @@ -0,0 +1,447 @@ +package opencore + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "math/big" + "strings" +) + +// SMBIOSIdentity holds the Mac identity fields stored in OpenCore's +// PlatformInfo > Generic dictionary. ROM is populated on read for reference and +// preserved untouched when patching so it stays aligned with the VM's NIC MAC. +type SMBIOSIdentity struct { + Model string `json:"model"` + Serial string `json:"serial"` + MLB string `json:"mlb"` + UUID string `json:"uuid"` + ROM string `json:"rom,omitempty"` +} + +type smbiosModelSpec struct { + name string + location string + years []int + modelCode string + boardCode string +} + +var smbiosModels = []smbiosModelSpec{ + { + name: "iMac20,1", + location: "C02", + years: []int{2020, 2021, 2022}, + modelCode: "PN5T", + boardCode: "PHC1", + }, + { + name: "iMacPro1,1", + location: "C02", + years: []int{2017, 2018, 2019, 2020, 2021}, + modelCode: "HX87", + boardCode: "JG36", + }, +} + +const ( + smbiosBase34 = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ" + smbiosYearCodes = "CDFGHJKLMNPQRSTVWXYZ" + smbiosWeekCodes = "0123456789CDFGHJKLMNPQRTVWX123456789CDFGHJKLMNPQRTVWXY" + smbiosWeekLookup = "123456789CDFGHJKLMNPQRSTVWXYZ" + smbiosSecondHalf = "DGJLNQSVXZ" + smbiosLineReprMx = 1155 + smbiosLineMax = 3399 +) + +var ( + mlbBlock1 = []string{ + "200", "600", "403", "404", "405", "303", "108", "207", "609", "501", "306", "102", "701", + "301", "501", "101", "300", "130", "100", "270", "310", "902", "104", "401", "902", "500", + "700", "802", + } + mlbBlock2 = []string{"GU", "4N", "J9", "QX", "OP", "CD", "GU"} + mlbBlock3 = []string{"1H", "1M", "AD", "1F", "A8", "UE", "JA", "JC", "8C", "CB", "FB"} +) + +func lookupSMBIOSModel(name string) smbiosModelSpec { + trimmed := strings.TrimSpace(name) + for _, m := range smbiosModels { + if strings.EqualFold(m.name, trimmed) { + return m + } + } + return smbiosModels[0] +} + +func cryptoRandInt(max int) (int, error) { + if max <= 1 { + return 0, nil + } + n, err := rand.Int(rand.Reader, big.NewInt(int64(max))) + if err != nil { + return 0, err + } + return int(n.Int64()), nil +} + +func formatAppleSerial(m smbiosModelSpec, year, week, line int) (string, error) { + if year < 2010 || year > 2030 { + return "", fmt.Errorf("year %d out of range", year) + } + if week < 1 || week > 53 { + return "", fmt.Errorf("week %d out of range", week) + } + if line < 0 || line > smbiosLineMax { + return "", fmt.Errorf("line %d out of range", line) + } + base := 2010 + if year >= 2020 { + base = 2020 + } + half := 0 + if week >= 27 { + half = 1 + } + yearCode := smbiosYearCodes[(year-base)*2+half] + weekCode := smbiosWeekCodes[week] + + rmin := 0 + if line > smbiosLineReprMx { + rmin = (line - smbiosLineReprMx + 67) / 68 + } + rest := line - rmin*68 + var b strings.Builder + b.Grow(12) + b.WriteString(m.location) + b.WriteByte(yearCode) + b.WriteByte(weekCode) + b.WriteByte(smbiosBase34[rmin]) + b.WriteByte(smbiosBase34[rest/34]) + b.WriteByte(smbiosBase34[rest%34]) + b.WriteString(m.modelCode) + return b.String(), nil +} + +// MLBChecksumOK verifies the 17-character Apple MLB base-34 weighted checksum. +func MLBChecksumOK(mlb string) bool { + if len(mlb) == 0 { + return false + } + n := len(mlb) + sum := 0 + for i := 0; i < n; i++ { + v := strings.IndexByte(smbiosBase34, mlb[i]) + if v < 0 { + return false + } + weight := 1 + if (i & 1) == (n & 1) { + weight = 3 + } + sum += weight * v + } + return sum%34 == 0 +} + +func generateMLBForSerial(m smbiosModelSpec, serial string) (string, error) { + if len(serial) != 12 { + return "", fmt.Errorf("12-character serial required for MLB") + } + yearCode := serial[3] + weekCode := serial[4] + year := 0 + if idx := strings.IndexByte(smbiosYearCodes, yearCode); idx >= 0 { + year = idx / 2 + } + week := 0 + if strings.IndexByte(smbiosSecondHalf, yearCode) >= 0 { + week = 27 + } + if idx := strings.IndexByte(smbiosWeekLookup, weekCode); idx >= 0 { + week += idx + 1 + } + if week < 1 { + return "", fmt.Errorf("serial has no valid week") + } + week-- + if week == 0 { + week = 53 + if year == 0 { + year = 9 + } else { + year-- + } + } + + for attempt := 0; attempt < 100000; attempt++ { + i1, err := cryptoRandInt(len(mlbBlock1)) + if err != nil { + return "", err + } + i2, err := cryptoRandInt(len(mlbBlock2)) + if err != nil { + return "", err + } + i3, err := cryptoRandInt(len(mlbBlock3)) + if err != nil { + return "", err + } + cand := fmt.Sprintf("%s%d%02d%s%s%s%s", + m.location, year, week, mlbBlock1[i1], mlbBlock2[i2], m.boardCode, mlbBlock3[i3], + ) + if MLBChecksumOK(cand) { + return cand, nil + } + } + return "", errors.New("could not generate MLB with valid checksum") +} + +func generateUUIDv4() (string, error) { + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + return "", err + } + b[6] = (b[6] & 0x0f) | 0x40 + b[8] = (b[8] & 0x3f) | 0x80 + h := strings.ToUpper(hex.EncodeToString(b[:])) + return fmt.Sprintf("%s-%s-%s-%s-%s", h[0:8], h[8:12], h[12:16], h[16:20], h[20:32]), nil +} + +// GenerateSMBIOS produces a fresh, cryptographically random SMBIOS identity +// (SystemSerialNumber, matching checksummed MLB, and UUID v4) for model +// ("iMac20,1" or "iMacPro1,1"; defaults to "iMac20,1"). +func GenerateSMBIOS(model string) (SMBIOSIdentity, error) { + m := lookupSMBIOSModel(model) + yi, err := cryptoRandInt(len(m.years)) + if err != nil { + return SMBIOSIdentity{}, err + } + wi, err := cryptoRandInt(52) + if err != nil { + return SMBIOSIdentity{}, err + } + li, err := cryptoRandInt(smbiosLineMax + 1) + if err != nil { + return SMBIOSIdentity{}, err + } + serial, err := formatAppleSerial(m, m.years[yi], 1+wi, li) + if err != nil { + return SMBIOSIdentity{}, err + } + mlb, err := generateMLBForSerial(m, serial) + if err != nil { + return SMBIOSIdentity{}, err + } + uuid, err := generateUUIDv4() + if err != nil { + return SMBIOSIdentity{}, err + } + return SMBIOSIdentity{ + Model: m.name, + Serial: serial, + MLB: mlb, + UUID: uuid, + }, nil +} + +// NormalizeAndValidateSMBIOS trims, uppercases, and validates user-supplied +// SMBIOS fields before writing them into OpenCore's config.plist. +func NormalizeAndValidateSMBIOS(in SMBIOSIdentity) (SMBIOSIdentity, error) { + out := SMBIOSIdentity{ + Model: strings.TrimSpace(in.Model), + Serial: strings.ToUpper(strings.TrimSpace(in.Serial)), + MLB: strings.ToUpper(strings.TrimSpace(in.MLB)), + } + if len(out.Serial) != 12 || !isASCIIAlphaNum(out.Serial) { + return SMBIOSIdentity{}, fmt.Errorf("serial number must be 12 alphanumeric characters") + } + if (len(out.MLB) != 17 && len(out.MLB) != 13) || !isASCIIAlphaNum(out.MLB) { + return SMBIOSIdentity{}, fmt.Errorf("MLB must be 13 or 17 alphanumeric characters") + } + rawUUID := strings.ReplaceAll(strings.TrimSpace(in.UUID), "-", "") + if len(rawUUID) != 32 || !isASCIIHex(rawUUID) { + return SMBIOSIdentity{}, fmt.Errorf("SystemUUID must be a valid 32-hex UUID") + } + h := strings.ToUpper(rawUUID) + out.UUID = fmt.Sprintf("%s-%s-%s-%s-%s", h[0:8], h[8:12], h[12:16], h[16:20], h[20:32]) + if out.Model != "" && strings.ContainsAny(out.Model, "<>&\"'\r\n\t ") { + return SMBIOSIdentity{}, fmt.Errorf("invalid Mac model %q", out.Model) + } + return out, nil +} + +func isASCIIAlphaNum(s string) bool { + for i := 0; i < len(s); i++ { + c := s[i] + if !((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) { + return false + } + } + return true +} + +func isASCIIHex(s string) bool { + for i := 0; i < len(s); i++ { + c := s[i] + if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) { + return false + } + } + return true +} + +func findPlatformGenericDict(root *xmlElem) *xmlElem { + top := findRootDict(root) + _, pi := dictLookup(top, "PlatformInfo") + _, gen := dictLookup(pi, "Generic") + if gen != nil && gen.name == "dict" { + return gen + } + return nil +} + +// ReadSMBIOS reads PlatformInfo > Generic identity fields from an OpenCore +// XML config.plist. +func ReadSMBIOS(src []byte) (SMBIOSIdentity, bool) { + root, err := parsePlistTree(src) + if err != nil { + return SMBIOSIdentity{}, false + } + gen := findPlatformGenericDict(root) + if gen == nil { + return SMBIOSIdentity{}, false + } + var id SMBIOSIdentity + if _, v := dictLookup(gen, "SystemProductName"); v != nil && v.name == "string" { + id.Model = strings.TrimSpace(v.text) + } + if _, v := dictLookup(gen, "SystemSerialNumber"); v != nil && v.name == "string" { + id.Serial = strings.TrimSpace(v.text) + } + if _, v := dictLookup(gen, "MLB"); v != nil && v.name == "string" { + id.MLB = strings.TrimSpace(v.text) + } + if _, v := dictLookup(gen, "SystemUUID"); v != nil && v.name == "string" { + id.UUID = strings.TrimSpace(v.text) + } + if _, v := dictLookup(gen, "ROM"); v != nil && v.name == "data" { + cleaned := strings.Join(strings.Fields(v.text), "") + if raw, decErr := base64.StdEncoding.DecodeString(cleaned); decErr == nil && len(raw) == 6 { + id.ROM = fmt.Sprintf("%02X:%02X:%02X:%02X:%02X:%02X", + raw[0], raw[1], raw[2], raw[3], raw[4], raw[5]) + } + } + ok := id.Serial != "" || id.MLB != "" || id.UUID != "" || id.Model != "" + return id, ok +} + +// PatchSMBIOS returns a modified copy of an OpenCore XML config.plist with +// PlatformInfo > Generic > SystemSerialNumber, MLB, SystemUUID (and optionally +// SystemProductName if non-empty) replaced in place. ROM and all other keys +// are preserved byte-for-byte. +func PatchSMBIOS(src []byte, in SMBIOSIdentity) ([]byte, error) { + id, err := NormalizeAndValidateSMBIOS(in) + if err != nil { + return nil, err + } + root, err := parsePlistTree(src) + if err != nil { + return nil, err + } + gen := findPlatformGenericDict(root) + if gen == nil { + return nil, errors.New("config.plist missing PlatformInfo > Generic") + } + + updates := []struct { + key string + val string + }{ + {"SystemSerialNumber", id.Serial}, + {"MLB", id.MLB}, + {"SystemUUID", id.UUID}, + } + if id.Model != "" { + updates = append(updates, struct { + key string + val string + }{"SystemProductName", id.Model}) + } + + var patches []bytePatch + nl := "\n" + if bytes.Contains(src, []byte("\r\n")) { + nl = "\r\n" + } + var inserts strings.Builder + closeIndent := lineIndent(src, gen.contentEnd) + entryIndent := closeIndent + "\t" + if len(gen.children) > 0 { + entryIndent = lineIndent(src, gen.children[0].start) + } + + for _, u := range updates { + if keyEl, valEl := dictLookup(gen, u.key); keyEl != nil && valEl != nil { + repl := fmt.Sprintf("%s", u.val) + patches = append(patches, bytePatch{start: valEl.start, end: valEl.end, repl: []byte(repl)}) + } else { + fmt.Fprintf(&inserts, "%s%s%s%s%s%s", + entryIndent, u.key, nl, entryIndent, u.val, nl) + } + } + if inserts.Len() > 0 { + insertPos := gen.contentEnd + for insertPos > gen.contentStart && (src[insertPos-1] == ' ' || src[insertPos-1] == '\t') { + insertPos-- + } + patches = append(patches, bytePatch{ + start: insertPos, + end: gen.contentEnd, + repl: []byte(inserts.String() + closeIndent), + }) + } + + return applyBytePatches(src, patches), nil +} + +// ReadImageSMBIOS reads PlatformInfo > Generic SMBIOS identity from an OpenCore +// disk image (opencore.qcow2 or raw). +func ReadImageSMBIOS(imagePath string) (SMBIOSIdentity, error) { + cfg, err := ReadConfigPlist(imagePath) + if err != nil { + return SMBIOSIdentity{}, err + } + id, ok := ReadSMBIOS(cfg) + if !ok { + return SMBIOSIdentity{}, errors.New("config.plist does not contain PlatformInfo > Generic SMBIOS") + } + return id, nil +} + +// PatchImageSMBIOS updates PlatformInfo > Generic (SystemSerialNumber, MLB, +// SystemUUID, and optional SystemProductName) inside imagePath while keeping +// ROM, kexts, and NVRAM intact. +func PatchImageSMBIOS(ctx context.Context, imagePath string, id SMBIOSIdentity, qemuImgPath string, env []string) (bool, error) { + norm, err := NormalizeAndValidateSMBIOS(id) + if err != nil { + return false, err + } + return patchImageConfigPlist(ctx, imagePath, qemuImgPath, env, func(orig []byte) ([]byte, bool, error) { + if cur, ok := ReadSMBIOS(orig); ok { + sameModel := norm.Model == "" || cur.Model == norm.Model + if sameModel && cur.Serial == norm.Serial && cur.MLB == norm.MLB && cur.UUID == norm.UUID { + return nil, false, nil + } + } + patched, err := PatchSMBIOS(orig, norm) + if err != nil { + return nil, false, err + } + return patched, true, nil + }) +} diff --git a/internal/opencore/smbios_test.go b/internal/opencore/smbios_test.go new file mode 100644 index 0000000..c959397 --- /dev/null +++ b/internal/opencore/smbios_test.go @@ -0,0 +1,158 @@ +package opencore + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestFormatAppleSerialVectors(t *testing.T) { + imac := lookupSMBIOSModel("iMac20,1") + got, err := formatAppleSerial(imac, 2020, 30, 1000) + if err != nil || got != "C02D40VEPN5T" { + t.Fatalf("iMac20,1 vector: got (%q, %v), want C02D40VEPN5T", got, err) + } + pro := lookupSMBIOSModel("imacpro1,1") + got, err = formatAppleSerial(pro, 2017, 5, 3399) + if err != nil || got != "C02T5ZZZHX87" { + t.Fatalf("iMacPro1,1 vector: got (%q, %v), want C02T5ZZZHX87", got, err) + } +} + +func TestGenerateAndValidateSMBIOS(t *testing.T) { + for _, model := range []string{"iMac20,1", "iMacPro1,1", ""} { + id, err := GenerateSMBIOS(model) + if err != nil { + t.Fatalf("GenerateSMBIOS(%q): %v", model, err) + } + if len(id.Serial) != 12 { + t.Fatalf("serial len = %d (%q)", len(id.Serial), id.Serial) + } + if len(id.MLB) != 17 || !MLBChecksumOK(id.MLB) { + t.Fatalf("invalid MLB %q", id.MLB) + } + if _, err := NormalizeAndValidateSMBIOS(id); err != nil { + t.Fatalf("NormalizeAndValidateSMBIOS failed on generated identity: %v", err) + } + } +} + +func TestReadAndPatchSMBIOSPlist(t *testing.T) { + sample := []byte(` + + + PlatformInfo + + Automatic + + Generic + + MLB + C02029200GUPHC11H + ROM + + UlQAEljq + + SystemProductName + iMac20,1 + SystemSerialNumber + C02D40VEPN5T + SystemUUID + 11111111-2222-4333-8444-555555555555 + + + + +`) + cur, ok := ReadSMBIOS(sample) + if !ok { + t.Fatal("ReadSMBIOS returned ok=false") + } + if cur.Model != "iMac20,1" || cur.Serial != "C02D40VEPN5T" || cur.ROM != "52:54:00:12:58:EA" { + t.Fatalf("ReadSMBIOS = %+v", cur) + } + + next, err := GenerateSMBIOS("iMac20,1") + if err != nil { + t.Fatal(err) + } + patched, err := PatchSMBIOS(sample, next) + if err != nil { + t.Fatalf("PatchSMBIOS: %v", err) + } + after, ok := ReadSMBIOS(patched) + if !ok { + t.Fatal("ReadSMBIOS after patch failed") + } + if after.Serial != next.Serial || after.MLB != next.MLB || after.UUID != next.UUID { + t.Fatalf("patched identity mismatch: got %+v, want %+v", after, next) + } + // ROM must be preserved untouched. + if after.ROM != "52:54:00:12:58:EA" || !strings.Contains(string(patched), "UlQAEljq") { + t.Fatalf("ROM was not preserved: %+v", after) + } +} + +func TestPatchImageSMBIOSRoundTrip(t *testing.T) { + sample := []byte(` + + + PlatformInfo + + Automatic + + Generic + + MLB + C02029200GUPHC11H + ROM + UlQAEljq + SystemProductName + iMac20,1 + SystemSerialNumber + C02D40VEPN5T + SystemUUID + 11111111-2222-4333-8444-555555555555 + + + + +`) + dir := t.TempDir() + rawBytes := buildSyntheticRawOpenCore(t, sample) + qcowPath := filepath.Join(dir, "opencore.qcow2") + if err := os.WriteFile(qcowPath, wrapRawAsQcow2(rawBytes), 0o644); err != nil { + t.Fatalf("write qcow2: %v", err) + } + + orig, err := ReadImageSMBIOS(qcowPath) + if err != nil { + t.Fatalf("ReadImageSMBIOS(orig): %v", err) + } + if orig.Serial != "C02D40VEPN5T" || orig.ROM != "52:54:00:12:58:EA" { + t.Fatalf("unexpected orig SMBIOS: %+v", orig) + } + + next, err := GenerateSMBIOS("iMac20,1") + if err != nil { + t.Fatalf("GenerateSMBIOS: %v", err) + } + changed, err := PatchImageSMBIOS(context.Background(), qcowPath, next, "", nil) + if err != nil || !changed { + t.Fatalf("PatchImageSMBIOS = (%v, %v), want (true, nil)", changed, err) + } + after, err := ReadImageSMBIOS(qcowPath) + if err != nil { + t.Fatalf("ReadImageSMBIOS(after): %v", err) + } + if after.Serial != next.Serial || after.MLB != next.MLB || after.UUID != next.UUID || after.ROM != orig.ROM { + t.Fatalf("after patch = %+v, want serial/mlb/uuid=%+v and rom=%s", after, next, orig.ROM) + } + // Repeating the same SMBIOS should be a no-op. + changed2, err := PatchImageSMBIOS(context.Background(), qcowPath, next, "", nil) + if err != nil || changed2 { + t.Fatalf("repeat PatchImageSMBIOS = (%v, %v), want (false, nil)", changed2, err) + } +} diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index cf32f40..2d82624 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -325,5 +325,25 @@ "effectImmediate": "Immediate", "effectNextStart": "Next start", "themePluginDarkDisabled": "Default theme plugin is disabled; dark and system appearances are unavailable", - "themePluginLightDisabled": "The active theme supports dark appearance only" + "themePluginLightDisabled": "The active theme supports dark appearance only", + "smbiosTitle": "Device identity (SMBIOS)", + "smbiosDesc": "Serial, MLB and UUID written to OpenCore for Apple services. ROM stays synced with the virtual NIC MAC and is left unchanged.", + "smbiosModel": "Model", + "smbiosSerial": "Serial", + "smbiosMLB": "MLB", + "smbiosUUID": "System UUID", + "smbiosROM": "NIC ROM", + "smbiosShow": "Reveal", + "smbiosHide": "Hide", + "smbiosCopySerial": "Copy serial", + "smbiosRotateBtn": "Rotate codes…", + "smbiosDialogTitle": "Rotate OpenCore SMBIOS", + "smbiosDialogSub": "Updates Serial, MLB and SystemUUID only; keeps ROM (NIC MAC) and NVRAM intact", + "smbiosGenerate": "Generate random", + "smbiosApply": "Write new codes", + "smbiosApplied": "Updated OpenCore SMBIOS identity. Applies on next start", + "smbiosWarning": "Sign out of Apple Account in macOS and shut down completely before rotating. First boot may show Setup Assistant and require signing in to iCloud / App Store again.", + "smbiosCheckHint": "Tip: check the serial at checkcoverage.apple.com and verify it reports invalid (not registered to a real Mac) before writing.", + "smbiosStopRequired": "Shut down the VM completely first (not running or suspended)", + "smbiosLoadFailed": "Could not read OpenCore SMBIOS" } diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index e46c6aa..69a0f73 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -325,5 +325,25 @@ "effectImmediate": "立即生效", "effectNextStart": "下次启动生效", "themePluginDarkDisabled": "默认主题插件已停用,深色与跟随系统外观不可用", - "themePluginLightDisabled": "当前主题仅支持深色外观" + "themePluginLightDisabled": "当前主题仅支持深色外观", + "smbiosTitle": "设备身份 (SMBIOS)", + "smbiosDesc": "写入 OpenCore 的序列号、主板号 (MLB) 与 UUID,用于 Apple 服务识别。ROM 与虚拟网卡 MAC 保持同步,换码时不会修改。", + "smbiosModel": "机型", + "smbiosSerial": "序列号", + "smbiosMLB": "主板号 (MLB)", + "smbiosUUID": "系统 UUID", + "smbiosROM": "网卡 ROM", + "smbiosShow": "显示完整码", + "smbiosHide": "隐藏", + "smbiosCopySerial": "复制序列号", + "smbiosRotateBtn": "一键换码…", + "smbiosDialogTitle": "更换 OpenCore 设备码", + "smbiosDialogSub": "只修改序列号、MLB 与 SystemUUID,保留原 ROM(网卡 MAC)与 NVRAM", + "smbiosGenerate": "随机生成一组", + "smbiosApply": "写入新设备码", + "smbiosApplied": "已写入新的 OpenCore 设备码,下次启动虚拟机生效", + "smbiosWarning": "换码前请先在 macOS 中退出 Apple 账户并彻底关机;换码后首次开机可能弹出「设置助理」,iCloud / App Store 需重新登录。", + "smbiosCheckHint": "建议将序列号复制到 checkcoverage.apple.com 确认显示「无效序列号」(未被真机占用)后再写入。", + "smbiosStopRequired": "请先彻底关机(不能处于运行或休眠状态)", + "smbiosLoadFailed": "无法读取 OpenCore 设备码" } From 0bb1e1a8a611ee38bfd7ad1904822f90aed30207 Mon Sep 17 00:00:00 2001 From: ELDment Date: Tue, 1 Dec 2026 15:29:13 +0800 Subject: [PATCH 25/42] feat(app): add VM shutdown mode selection and one-click force quit --- frontend/src/components/AppSettingsPage.tsx | 21 +++ frontend/src/components/VMPage.tsx | 37 ++++- frontend/src/i18n/domains/core.gen.ts | 8 +- frontend/src/i18n/domains/settings.gen.ts | 8 + frontend/src/i18n/keys.gen.ts | 7 + frontend/src/styles/app.css | 5 + frontend/wailsjs/go/app/App.d.ts | 2 + frontend/wailsjs/go/app/App.js | 4 + frontend/wailsjs/go/models.ts | 2 + internal/app/app.go | 63 ++++---- internal/app/quit_flow.go | 119 +++++++++++++++ internal/app/quit_flow_test.go | 153 ++++++++++++++++++++ internal/app/suspend_flow.go | 4 + internal/driver/reims/reims.go | 7 +- internal/i18n/catalog_gen.go | 14 +- locales/en-US/core.json | 3 + locales/en-US/native.json | 2 + locales/en-US/settings.json | 4 + locales/zh-CN/core.json | 5 +- locales/zh-CN/native.json | 2 + locales/zh-CN/settings.json | 4 + 21 files changed, 436 insertions(+), 38 deletions(-) create mode 100644 internal/app/quit_flow.go create mode 100644 internal/app/quit_flow_test.go diff --git a/frontend/src/components/AppSettingsPage.tsx b/frontend/src/components/AppSettingsPage.tsx index 0d99a93..b6d93a8 100644 --- a/frontend/src/components/AppSettingsPage.tsx +++ b/frontend/src/components/AppSettingsPage.tsx @@ -1,4 +1,5 @@ import React from 'react' +import { PowerOff } from 'lucide-react' import '../i18n/domains/settings.gen' import { getLocaleOptions, I18nKey, t } from '../i18n' import { findOptimization, optBadgeClass, optStatusLabel } from '../lib/optimizations' @@ -27,6 +28,7 @@ export const AppSettingsPage: React.FC = ({ }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const { host, config, optimizations } = state + const quitMode = state.quit_mode const pcoreOpt = findOptimization(optimizations, 'pcore_pin') const missingFontScript = state.missing_font_hint || '' @@ -45,6 +47,14 @@ export const AppSettingsPage: React.FC = ({ if (dir) await api.SetDataRoot(dir) }) + const forceQuit = async () => { + try { + await api.ForceQuitApp() + } catch (e) { + onError(tr('quitFailed'), e) + } + } + return (
@@ -97,6 +107,17 @@ export const AppSettingsPage: React.FC = ({ />
+
+
+
{tr('forceQuitAppTitle')}
+
{tr('forceQuitAppSub')}
+
+
+ +
+
diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index 01f16df..0ed8400 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -7,6 +7,7 @@ import { Archive, Camera, Check, + ChevronDown, ChevronRight, Code2, Copy, @@ -126,6 +127,40 @@ type Tone = '' | ' warn' | ' high' const meterTone = (pct: number, warn = 75, high = 90): Tone => (pct >= high ? ' high' : pct >= warn ? ' warn' : '') const clampPct = (v: number) => Math.min(100, Math.max(0, v)) +function ShutdownButton({ locale, busyAction, onAction }: Pick) { + const [mode, setMode] = useState<'stop' | 'forceStop'>('stop') + const forced = mode === 'forceStop' + const variant = forced ? 'danger' : 'secondary' + const label = t(locale, 'shutdownMode') + const Icon = forced ? Power : Square + + return ( +
+ + + + + + + + setMode(v === 'forceStop' ? 'forceStop' : 'stop')}> + {(['stop', 'forceStop'] as const).map((action) => ( + + + {t(locale, action)} + + ))} + + + + +
+ ) +} + interface Spec { key: string /** Shown only in the wide, single-column layout. */ @@ -378,7 +413,7 @@ export const VMPage: React.FC = ({ {tr('suspend')} )} - + ) } else if (state === 'broken') { diff --git a/frontend/src/i18n/domains/core.gen.ts b/frontend/src/i18n/domains/core.gen.ts index 591503e..12e093a 100644 --- a/frontend/src/i18n/domains/core.gen.ts +++ b/frontend/src/i18n/domains/core.gen.ts @@ -39,7 +39,7 @@ export const coreZh: Record = { "footerMemTip": "系统内存:已用 {used} GB / 共 {total} GB(可用 {avail} GB)", "footerMemValue": "{used} / {total} GB", "footerRunningVMs": "{n, plural, other {# 台运行中}}", - "forceStop": "强制关机", + "forceStop": "硬关机", "gpuErrMissingExt": "缺少必需 Vulkan 扩展({ext}),请更新显卡驱动或改用 VMware SVGA", "gpuErrVulkanCpu": "软件 Vulkan 实现不满足 vGPU 加速要求,请改用 VMware SVGA", "gpuErrVulkanTooOld": "Vulkan {ver} 低于 1.3 最低要求,请更新显卡驱动或改用 VMware SVGA", @@ -108,6 +108,8 @@ export const coreZh: Record = { "panelLoadFailed": "面板加载失败", "pauseDownload": "暂停下载", "pluginSafeModeShort": "安全模式", + "quitFailed": "已取消退出", + "quitInProgress": "正在退出…", "refresh": "刷新", "resLooksLike": "看起来像 {w} × {h}", "resizeLogPanel": "拖动调整日志高度", @@ -122,6 +124,7 @@ export const coreZh: Record = { "shortcutBarFullscreen": "切换全屏", "shortcutBarRelease": "释放键盘和鼠标", "showSidebar": "显示侧边栏", + "shutdownMode": "关机方式", "sidebarHost": "内核", "sidebarInstallers": "安装包", "sidebarItemAria": "{label},{state}", @@ -290,6 +293,8 @@ export const coreEn: Record = { "panelLoadFailed": "Panel failed to load", "pauseDownload": "Pause download", "pluginSafeModeShort": "Safe mode", + "quitFailed": "Quit canceled", + "quitInProgress": "Quitting…", "refresh": "Refresh", "resLooksLike": "Looks like {w} × {h}", "resizeLogPanel": "Drag to resize log panel", @@ -304,6 +309,7 @@ export const coreEn: Record = { "shortcutBarFullscreen": "Toggle full screen", "shortcutBarRelease": "Release keyboard and mouse", "showSidebar": "Show sidebar", + "shutdownMode": "Shutdown mode", "sidebarHost": "Engine", "sidebarInstallers": "Installers", "sidebarItemAria": "{label}, {state}", diff --git a/frontend/src/i18n/domains/settings.gen.ts b/frontend/src/i18n/domains/settings.gen.ts index 3a65bcd..0840d2d 100644 --- a/frontend/src/i18n/domains/settings.gen.ts +++ b/frontend/src/i18n/domains/settings.gen.ts @@ -138,6 +138,10 @@ export const settingsZh: Record = { "footerDisk": "磁盘可用 {gb} GB", "footerMem": "内存 {pct}%", "footerMemAvail": "可用 {avail} GB", + "forceQuitAppButton": "强制退出", + "forceQuitAppSub": "对所有运行中的虚拟机执行硬关机,未保存的数据可能丢失。", + "forceQuitAppTitle": "强制退出 Reims-Go", + "forceQuitInProgress": "正在强制退出…", "fullscreenDecoupledHint": "窗口铺满屏幕;下方分辨率可独立设为原生或超采样 HiDPI(如 4K 1.5× = 5120×2880),由 GPU 自动缩放", "fullscreenLaunch": "无边框全屏启动", "fullscreenLaunchHint": "启动后直接进入无边框全屏", @@ -455,6 +459,10 @@ export const settingsEn: Record = { "footerDisk": "Disk {gb} GB free", "footerMem": "Memory {pct}%", "footerMemAvail": "{avail} GB free", + "forceQuitAppButton": "Force quit", + "forceQuitAppSub": "Cuts power to running virtual machines. Unsaved data may be lost.", + "forceQuitAppTitle": "Force quit Reims-Go", + "forceQuitInProgress": "Force quitting…", "fullscreenDecoupledHint": "Fills the monitor; pick native or supersampled HiDPI (e.g. 5120×2880 for 4K 1.5×) below, scaled on the GPU", "fullscreenLaunch": "Launch borderless fullscreen", "fullscreenLaunchHint": "Opens macOS in borderless full screen", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 9ee8854..1ccb0df 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -252,6 +252,10 @@ export type I18nKey = | "footerMemTip" | "footerMemValue" | "footerRunningVMs" + | "forceQuitAppButton" + | "forceQuitAppSub" + | "forceQuitAppTitle" + | "forceQuitInProgress" | "forceStop" | "fullscreenDecoupledHint" | "fullscreenLaunch" @@ -610,6 +614,8 @@ export type I18nKey = | "pluginTrustOfficial" | "pluginTrustVerified" | "pluginViewLog" + | "quitFailed" + | "quitInProgress" | "recommendedBadge" | "refresh" | "resCustom" @@ -689,6 +695,7 @@ export type I18nKey = | "showInstallGuide" | "showSidebar" | "showWindow" + | "shutdownMode" | "sidebarHost" | "sidebarInstallers" | "sidebarItemAria" diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 6710013..ba2f518 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -529,6 +529,11 @@ h1, h2, h3, p { margin: 0; } box-shadow: 0 1px 3px rgba(255, 59, 48, 0.28), inset 0 1px 0 rgba(255, 255, 255, 0.18); } .btn-danger:hover:not(:disabled) { filter: brightness(1.06); background: var(--danger); } +.shutdown-button { display: inline-flex; } +.shutdown-button > .btn:first-child { border-start-end-radius: 0; border-end-end-radius: 0; } +.shutdown-button > .btn:last-child { + padding-inline: 6px; border-start-start-radius: 0; border-end-start-radius: 0; border-inline-start: 0; +} .btn-ghost { background: transparent; border-color: transparent; color: var(--text-2); box-shadow: none; } .btn-ghost:hover:not(:disabled) { background: var(--surface-hover); color: var(--text); } diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index ded8dce..2391278 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -81,6 +81,8 @@ export function FinishInstall(arg1:string):Promise; export function FocusVMWindow(arg1:string):Promise; +export function ForceQuitApp():Promise; + export function GetActiveTheme():Promise; export function GetLicenseTexts():Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index da78976..982ef0c 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -146,6 +146,10 @@ export function FocusVMWindow(arg1) { return window['go']['app']['App']['FocusVMWindow'](arg1); } +export function ForceQuitApp() { + return window['go']['app']['App']['ForceQuitApp'](); +} + export function GetActiveTheme() { return window['go']['app']['App']['GetActiveTheme'](); } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 7d181bf..703f2b5 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -1,6 +1,7 @@ export namespace app { export class AppState { + quit_mode?: string; config?: config.Config; host: host.Report; optimizations: host.Optimization[]; @@ -26,6 +27,7 @@ export namespace app { constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); + this.quit_mode = source["quit_mode"]; this.config = this.convertValues(source["config"], config.Config); this.host = this.convertValues(source["host"], host.Report); this.optimizations = this.convertValues(source["optimizations"], host.Optimization); diff --git a/internal/app/app.go b/internal/app/app.go index 9c035eb..a65a0f5 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -8,6 +8,7 @@ import ( "maps" "os" "path/filepath" + "slices" "strings" "sync" "time" @@ -38,6 +39,7 @@ type PendingChange struct { } type AppState struct { + QuitMode string `json:"quit_mode,omitempty"` Config *config.Config `json:"config"` Host host.Report `json:"host"` Optimizations []host.Optimization `json:"optimizations"` @@ -78,6 +80,8 @@ type App struct { imeBridge *host.IMEBridge trayMgr *tray.Manager allowQuit bool + quitMode string + vmStarts sync.WaitGroup lastVMs []reims.VMListItem lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick @@ -174,10 +178,17 @@ func (a *App) startIMEBridge() { func (a *App) beforeClose(ctx context.Context) bool { a.mu.Lock() allow := a.allowQuit + quitting := a.quitMode != "" toTray := a.cfg.ShouldMinimizeToTray() hasTray := a.trayMgr != nil a.mu.Unlock() - if !allow && toTray && hasTray { + if allow { + return false + } + if quitting { + return true + } + if toTray && hasTray { a.setWindowHidden(true) wailsRuntime.WindowHide(ctx) return true @@ -653,7 +664,11 @@ func (a *App) GetState() AppState { activeGuides = guideMgr.ActiveNames() } + a.mu.Lock() + quitMode := a.quitMode + a.mu.Unlock() return AppState{ + QuitMode: quitMode, Config: &cfgCopy, Host: rep, Optimizations: opts, @@ -741,28 +756,8 @@ func (a *App) ShowMainWindow() { // RequestClose handles the custom titlebar close button: hides to system tray // when MinimizeToTray is enabled, or quits the application otherwise. func (a *App) RequestClose() { - if a.ctx == nil { - return - } - a.mu.Lock() - toTray := a.cfg.ShouldMinimizeToTray() - hasTray := a.trayMgr != nil - a.mu.Unlock() - if toTray && hasTray { - a.setWindowHidden(true) - wailsRuntime.WindowHide(a.ctx) - return - } - a.QuitApp() -} - -// QuitApp exits Reims-Go completely (bypassing minimize-to-tray). -func (a *App) QuitApp() { - a.mu.Lock() - a.allowQuit = true - a.mu.Unlock() if a.ctx != nil { - wailsRuntime.Quit(a.ctx) + wailsRuntime.Quit(a.ctx) // beforeClose applies the window-close preference. } } @@ -778,9 +773,7 @@ func (a *App) startTray() { } }, OnVMAction: a.trayVMAction, - OnQuit: func() { - a.QuitApp() - }, + OnQuit: a.QuitApp, GetSnapshot: func() tray.Snapshot { a.mu.Lock() cfgCopy := *a.cfg @@ -1357,6 +1350,10 @@ func stripLegacyManagedExtraArgs(extraArgs string) string { } func (a *App) StartVM(name string) error { + if err := a.beginVMStart(); err != nil { + return err + } + defer a.vmStarts.Done() prep, err := a.prep(name) if err != nil { return err @@ -1517,7 +1514,15 @@ func (a *App) StopVM(name string, force bool) error { if err != nil { return err } - release, err := vmstart.LockVMForStop(a.baseCtx(), c, name, force) + if force { + return a.stopVM(a.baseCtx(), c, name, "--force") + } + return a.stopVM(a.baseCtx(), c, name) +} + +func (a *App) stopVM(ctx context.Context, c *reims.Client, name string, flags ...string) error { + force := slices.Contains(flags, "--force") + release, err := vmstart.LockVMForStop(ctx, c, name, force) if err != nil { return err } @@ -1538,11 +1543,7 @@ func (a *App) StopVM(name string, force bool) error { w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) }) a.emitLog(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) - } + err = c.Stop(ctx, name, w, w, flags...) if err != nil { a.mu.Lock() delete(a.transitions, name) diff --git a/internal/app/quit_flow.go b/internal/app/quit_flow.go new file mode 100644 index 0000000..9a792c0 --- /dev/null +++ b/internal/app/quit_flow.go @@ -0,0 +1,119 @@ +package app + +import ( + "context" + "errors" + "os" + "path/filepath" + "time" + + "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/i18n" + wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" +) + +func (a *App) beginVMStart() error { + a.mu.Lock() + defer a.mu.Unlock() + if a.quitMode != "" || a.allowQuit { + return errors.New(i18n.T(a.cfg.Locale, "quitInProgress")) + } + a.vmStarts.Add(1) + return nil +} + +// QuitApp exits the desktop app and leaves its guests running. +func (a *App) QuitApp() { + _ = a.quitApp(false) +} + +// ForceQuitApp powers off all running guests before exiting. +func (a *App) ForceQuitApp() error { + return a.quitApp(true) +} + +func (a *App) quitApp(force bool) error { + a.mu.Lock() + if a.allowQuit || a.quitMode != "" { + a.mu.Unlock() + return nil + } + if force { + a.quitMode = "force" + a.mu.Unlock() + a.emitStateChanged() + a.vmStarts.Wait() + err := a.forceStopRunningVMs(a.baseCtx()) + a.mu.Lock() + if err != nil { + a.quitMode = "" + a.mu.Unlock() + a.emitStateChanged() + return err + } + } + a.allowQuit = true + a.mu.Unlock() + if a.ctx != nil { + wailsRuntime.Quit(a.ctx) + } + return nil +} + +func (a *App) forceStopRunningVMs(ctx context.Context) error { + c, err := a.client() + if err != nil { + // A fresh installation can quit before its first runtime is installed. + a.mu.Lock() + cfg := *a.cfg + a.mu.Unlock() + _, registryErr := os.Stat(filepath.Join(cfg.XDGConfigDir(), "reims-ctl", "vms.toml")) + dirs, dirErr := os.ReadDir(filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms")) + if os.IsNotExist(registryErr) && (os.IsNotExist(dirErr) || (dirErr == nil && len(dirs) == 0)) { + return nil + } + return err + } + return stopListedVMs(ctx, c.Locale, c.List, func(ctx context.Context, name string) error { + return a.stopVM(ctx, c, name, "--force") + }) +} + +const quitVMTimeout = 10 * time.Second + +func stopListedVMs(ctx context.Context, loc i18n.Locale, list func(context.Context) ([]reims.VMListItem, error), stop func(context.Context, string) error) error { + stopped := make(map[string]bool) + for { + listCtx, cancel := context.WithTimeout(ctx, quitVMTimeout) + vms, err := list(listCtx) + cancel() + if err != nil { + return err + } + var next string + for _, vm := range vms { + if vm.State == "running" { + if stopped[vm.Name] { + return errors.New(i18n.M(loc, "err.quit.stop_failed", i18n.Vars{"name": vm.Name})) + } + if next == "" { + next = vm.Name + } + } + } + if next == "" { + return nil + } + stopCtx, cancel := context.WithTimeout(ctx, quitVMTimeout) + err = stop(stopCtx, next) + ctxErr := stopCtx.Err() + cancel() + if errors.Is(ctxErr, context.DeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) { + return errors.New(i18n.M(loc, "err.quit.timeout", i18n.Vars{"name": next})) + } + if err != nil { + return errors.New(i18n.M(loc, "err.quit.stop_failed", i18n.Vars{"name": next})) + } + stopped[next] = true + } +} diff --git a/internal/app/quit_flow_test.go b/internal/app/quit_flow_test.go new file mode 100644 index 0000000..71d0968 --- /dev/null +++ b/internal/app/quit_flow_test.go @@ -0,0 +1,153 @@ +package app + +import ( + "context" + "errors" + "os" + "path/filepath" + "slices" + "testing" + "testing/synctest" + "time" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/i18n" +) + +func TestStopListedVMs(t *testing.T) { + for _, tc := range []struct { + name, wantErr string + }{ + {name: "all stopped"}, + {name: "failure", wantErr: "无法关闭虚拟机「two」,已取消退出。"}, + {name: "still running", wantErr: "无法关闭虚拟机「two」,已取消退出。"}, + {name: "timeout", wantErr: "虚拟机「two」关机超时,已取消退出。"}, + } { + t.Run(tc.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + vms := []reims.VMListItem{ + {Name: "one", State: "running"}, {Name: "off", State: "stopped"}, + {Name: "two", State: "running"}, {Name: "saved", State: "suspended"}, {Name: "three", State: "running"}, + } + var calls []string + err := stopListedVMs(t.Context(), i18n.ZhCN, func(context.Context) ([]reims.VMListItem, error) { + return vms, nil + }, func(ctx context.Context, name string) error { + calls = append(calls, name) + if name == "two" { + switch tc.name { + case "failure": + return errors.New("stop failed") + case "still running": + return nil + case "timeout": + started := time.Now() + <-ctx.Done() + if elapsed := time.Since(started); elapsed != 10*time.Second { + t.Errorf("shutdown timed out after %v, want 10s", elapsed) + } + return errors.New("exit status 1") + } + } + for i := range vms { + if vms[i].Name == name { + vms[i].State = "stopped" + } + } + return nil + }) + want := []string{"one", "two", "three"} + if tc.wantErr != "" { + want = want[:2] + if err == nil || err.Error() != tc.wantErr { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + } else if err != nil { + t.Fatal(err) + } + if !slices.Equal(calls, want) { + t.Fatalf("stop calls = %v, want %v", calls, want) + } + }) + }) + } +} + +func TestQuitAppLeavesVMsRunning(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + a := &App{lastVMs: []reims.VMListItem{{Name: "one", State: "running"}}} + if err := a.beginVMStart(); err != nil { + t.Fatal(err) + } + defer a.vmStarts.Done() + done := make(chan struct{}) + go func() { + a.QuitApp() + close(done) + }() + synctest.Wait() + select { + case <-done: + if !a.allowQuit || a.quitMode != "" { + t.Fatalf("tray exit: allowQuit=%v mode=%q", a.allowQuit, a.quitMode) + } + default: + t.Fatal("tray exit waited for VM operations") + } + }) +} + +func TestForceQuitAppWaitsForStartsAndCanRetry(t *testing.T) { + a := &App{cfg: &config.Config{DataRoot: t.TempDir(), Locale: i18n.EnUS}} + if err := a.beginVMStart(); err != nil { + t.Fatal(err) + } + quit := make(chan error, 1) + go func() { quit <- a.ForceQuitApp() }() + deadline := time.Now().Add(3 * time.Second) + for { + a.mu.Lock() + quitting := a.quitMode != "" + a.mu.Unlock() + if quitting { + break + } + if time.Now().After(deadline) { + t.Fatal("quit did not start") + } + time.Sleep(time.Millisecond) + } + for _, launch := range []func(string) error{a.StartVM, a.ResumeVM} { + if err := launch("new"); err == nil || err.Error() != i18n.T(i18n.EnUS, "quitInProgress") { + t.Fatalf("launch during shutdown: %v", err) + } + } + a.QuitApp() + if !a.beforeClose(context.Background()) { + t.Fatal("another close bypassed the pending shutdown") + } + if err := a.ForceQuitApp(); err != nil { + t.Fatal(err) + } + if a.quitMode != "force" || a.allowQuit { + t.Fatalf("duplicate quit: mode=%q allowQuit=%v", a.quitMode, a.allowQuit) + } + + // The in-flight start creates a VM entry after the quit request. Without + // a runtime, shutdown must now fail instead of assuming an empty library. + dir := filepath.Join(a.cfg.XDGDataDir(), "reims-ctl", "vms", "starting") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + a.vmStarts.Done() + if err := <-quit; err == nil || a.allowQuit || a.quitMode != "" { + t.Fatalf("failed shutdown: err=%v allowQuit=%v mode=%q", err, a.allowQuit, a.quitMode) + } + if err := os.Remove(dir); err != nil { + t.Fatal(err) + } + if err := a.ForceQuitApp(); err != nil || !a.allowQuit || a.beforeClose(context.Background()) { + t.Fatalf("retry with empty library: err=%v allowQuit=%v", err, a.allowQuit) + } +} diff --git a/internal/app/suspend_flow.go b/internal/app/suspend_flow.go index 8cfd783..f4b60cd 100644 --- a/internal/app/suspend_flow.go +++ b/internal/app/suspend_flow.go @@ -89,6 +89,10 @@ func (a *App) SuspendVM(name string) error { // ResumeVM restores a suspended VM with its original media and devices. func (a *App) ResumeVM(name string) error { + if err := a.beginVMStart(); err != nil { + return err + } + defer a.vmStarts.Done() prep, err := a.prep(name) if err != nil { return err diff --git a/internal/driver/reims/reims.go b/internal/driver/reims/reims.go index 6a2702c..171b488 100644 --- a/internal/driver/reims/reims.go +++ b/internal/driver/reims/reims.go @@ -756,12 +756,13 @@ func (c *Client) Start(ctx context.Context, name string, stdout, stderr io.Write return c.run(ctx, stdout, stderr, "start", name) } -func (c *Client) Stop(ctx context.Context, name string, stdout, stderr io.Writer) error { - return c.run(ctx, stdout, stderr, "stop", name) +func (c *Client) Stop(ctx context.Context, name string, stdout, stderr io.Writer, flags ...string) error { + args := append([]string{"stop"}, flags...) + return c.run(ctx, stdout, stderr, append(args, name)...) } func (c *Client) StopForce(ctx context.Context, name string, stdout, stderr io.Writer) error { - return c.run(ctx, stdout, stderr, "stop", "--force", name) + return c.Stop(ctx, name, stdout, stderr, "--force") } func (c *Client) Eject(ctx context.Context, name string, stdout, stderr io.Writer) error { diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 61dcba3..2285863 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -130,6 +130,8 @@ var catalog = map[Locale]map[string]string{ "err.plugin.in_use": "插件「{id}」正在被虚拟机使用,无法停用或卸载:{reason}", "err.plugin.safe_mode": "当前处于安全模式,已暂停加载和变更第三方插件", "err.plugin.system_locked": "系统核心组件「{id}」不可停用或卸载", + "err.quit.stop_failed": "无法关闭虚拟机「{name}」,已取消退出。", + "err.quit.timeout": "虚拟机「{name}」关机超时,已取消退出。", "err.runtime_not_installed": "未找到已激活的便携运行时,请先执行 `reims-go runtime install <归档路径>`", "err.snapshot.name_empty": "请输入恢复点名称", "err.snapshot.name_invalid": "恢复点名称包含不支持的控制字符或引号", @@ -182,7 +184,7 @@ var catalog = map[Locale]map[string]string{ "footerMemTip": "系统内存:已用 {used} GB / 共 {total} GB(可用 {avail} GB)", "footerMemValue": "{used} / {total} GB", "footerRunningVMs": "{n, plural, other {# 台运行中}}", - "forceStop": "强制关机", + "forceStop": "硬关机", "gpuErrMissingExt": "缺少必需 Vulkan 扩展({ext}),请更新显卡驱动或改用 VMware SVGA", "gpuErrVulkanCpu": "软件 Vulkan 实现不满足 vGPU 加速要求,请改用 VMware SVGA", "gpuErrVulkanTooOld": "Vulkan {ver} 低于 1.3 最低要求,请更新显卡驱动或改用 VMware SVGA", @@ -373,6 +375,8 @@ var catalog = map[Locale]map[string]string{ "plugin.removed": "已卸载 {id}(purge={purge})", "plugin.target_not_found": "未找到插件或目录 \"{target}\"", "pluginSafeModeShort": "安全模式", + "quitFailed": "已取消退出", + "quitInProgress": "正在退出…", "refresh": "刷新", "resLooksLike": "看起来像 {w} × {h}", "resizeLogPanel": "拖动调整日志高度", @@ -402,6 +406,7 @@ var catalog = map[Locale]map[string]string{ "shortcutBarFullscreen": "切换全屏", "shortcutBarRelease": "释放键盘和鼠标", "showSidebar": "显示侧边栏", + "shutdownMode": "关机方式", "sidebarHost": "内核", "sidebarInstallers": "安装包", "sidebarItemAria": "{label},{state}", @@ -664,6 +669,8 @@ var catalog = map[Locale]map[string]string{ "err.plugin.in_use": "Plugin “{id}” is currently in use and cannot be disabled or removed: {reason}", "err.plugin.safe_mode": "Safe mode is active; third-party plugin changes are paused", "err.plugin.system_locked": "Core system component “{id}” cannot be disabled or removed", + "err.quit.stop_failed": "Could not shut down “{name}”. Quit canceled.", + "err.quit.timeout": "Shutdown timed out for “{name}”. Quit canceled.", "err.runtime_not_installed": "no active portable runtime found; run `reims-go runtime install ` first", "err.snapshot.name_empty": "Enter a restore point name", "err.snapshot.name_invalid": "Restore point name contains unsupported characters or quotes", @@ -907,6 +914,8 @@ var catalog = map[Locale]map[string]string{ "plugin.removed": "Removed {id} (purge={purge})", "plugin.target_not_found": "plugin or directory \"{target}\" not found", "pluginSafeModeShort": "Safe mode", + "quitFailed": "Quit canceled", + "quitInProgress": "Quitting…", "refresh": "Refresh", "resLooksLike": "Looks like {w} × {h}", "resizeLogPanel": "Drag to resize log panel", @@ -936,6 +945,7 @@ var catalog = map[Locale]map[string]string{ "shortcutBarFullscreen": "Toggle full screen", "shortcutBarRelease": "Release keyboard and mouse", "showSidebar": "Show sidebar", + "shutdownMode": "Shutdown mode", "sidebarHost": "Engine", "sidebarInstallers": "Installers", "sidebarItemAria": "{label}, {state}", @@ -1116,6 +1126,8 @@ var paramOrder = map[string][]string{ "err.plugin.high_risk_unapproved": {"id"}, "err.plugin.in_use": {"id", "reason"}, "err.plugin.system_locked": {"id"}, + "err.quit.stop_failed": {"name"}, + "err.quit.timeout": {"name"}, "err.snapshot.qemu_img_failed": {"snap"}, "err.snapshot.vm_running": {"name"}, "err.suspend.action_blocked": {"name"}, diff --git a/locales/en-US/core.json b/locales/en-US/core.json index 35dd497..c384854 100644 --- a/locales/en-US/core.json +++ b/locales/en-US/core.json @@ -4,6 +4,8 @@ "sidebarHost": "Engine", "sidebarPlugins": "Plugins", "sidebarSettings": "Settings", + "quitInProgress": "Quitting…", + "quitFailed": "Quit canceled", "sidebarInstallers": "Installers", "installersRetry": "Retry", "emptyVMs": "No virtual machines", @@ -87,6 +89,7 @@ }, "restart": "Restart", "forceStop": "Force shut down", + "shutdownMode": "Shutdown mode", "eject": "Eject installer", "settings": "Settings", "more": { diff --git a/locales/en-US/native.json b/locales/en-US/native.json index 0fdcee5..eccfd0f 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -1028,6 +1028,8 @@ ] }, "err.dataroot.busy_vms": "Stop all running virtual machines before switching the data folder", + "err.quit.stop_failed": "Could not shut down “{name}”. Quit canceled.", + "err.quit.timeout": "Shutdown timed out for “{name}”. Quit canceled.", "err.dataroot.busy_tasks": "Wait for active download or creation tasks to finish before switching the data folder", "font.script.zh_hant": "Traditional Chinese (繁體中文)", "font.script.zh_hans": "Simplified Chinese (简体中文)", diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index cf32f40..8b6bfd4 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -278,6 +278,10 @@ "gpuUnavailableHint": "No GPU available for acceleration; try VMware SVGA", "minimizeToTray": "Minimize to system tray on close", "minimizeToTraySub": "Clipboard and shared folders keep working; start and stop VMs from the tray", + "forceQuitAppTitle": "Force quit Reims-Go", + "forceQuitAppSub": "Cuts power to running virtual machines. Unsaved data may be lost.", + "forceQuitAppButton": "Force quit", + "forceQuitInProgress": "Force quitting…", "hostDisplays": "Physical displays", "hostDisplayPrimary": "Primary", "multiDisplayHint": { diff --git a/locales/zh-CN/core.json b/locales/zh-CN/core.json index 9bfbc42..0b43fdd 100644 --- a/locales/zh-CN/core.json +++ b/locales/zh-CN/core.json @@ -4,6 +4,8 @@ "sidebarHost": "内核", "sidebarPlugins": "插件", "sidebarSettings": "设置", + "quitInProgress": "正在退出…", + "quitFailed": "已取消退出", "sidebarInstallers": "安装包", "installersRetry": "重试", "emptyVMs": "还没有虚拟机", @@ -86,7 +88,8 @@ "$maxLength": 16 }, "restart": "重启", - "forceStop": "强制关机", + "forceStop": "硬关机", + "shutdownMode": "关机方式", "eject": "弹出安装盘", "settings": "设置", "more": { diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index 91ce361..87fb606 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -1028,6 +1028,8 @@ ] }, "err.dataroot.busy_vms": "仍有虚拟机正在运行,请先全部关机后再切换数据目录", + "err.quit.stop_failed": "无法关闭虚拟机「{name}」,已取消退出。", + "err.quit.timeout": "虚拟机「{name}」关机超时,已取消退出。", "err.dataroot.busy_tasks": "仍有后台下载或创建任务进行中,请等待任务结束或取消后再切换数据目录", "font.script.zh_hant": "繁体中文(繁體中文)", "font.script.zh_hans": "简体中文", diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index e46c6aa..935acba 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -278,6 +278,10 @@ "gpuUnavailableHint": "没有找到能加速的显卡,可改用 VMware SVGA", "minimizeToTray": "关闭窗口时最小化到系统托盘", "minimizeToTraySub": "关闭窗口后剪贴板和共享文件夹继续工作,可从托盘启停虚拟机", + "forceQuitAppTitle": "强制退出 Reims-Go", + "forceQuitAppSub": "对所有运行中的虚拟机执行硬关机,未保存的数据可能丢失。", + "forceQuitAppButton": "强制退出", + "forceQuitInProgress": "正在强制退出…", "hostDisplays": "物理显示器", "hostDisplayPrimary": "主屏", "multiDisplayHint": { From b1eec6050bd4c6672bf8289b48e075759d4bfa1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Tue, 1 Dec 2026 03:05:54 -0700 Subject: [PATCH 26/42] fix(runtime): keep capabilities of manifests without the field Packages published before manifest.json carried "capabilities" (up to runtime-3731afd-p4) lost every capability once inference was removed, so Win10 hosts got kernel-irqchip=off and rule hooks saw no runtime caps. When a built-in reims-vgpu manifest has no "capabilities" key, declare the patch-derived set at load time with the same mapping as pack-runtime.ps1. A declared list, including an empty one, still wins; other kinds must declare their own. Co-Authored-By: Claude Opus 5.5 --- internal/runtime/kinds.go | 42 ++++++++++++++++++++++ internal/runtime/manifest_test.go | 59 +++++++++++++++++++++++++++++++ internal/runtime/runtime.go | 13 +++++-- 3 files changed, 112 insertions(+), 2 deletions(-) diff --git a/internal/runtime/kinds.go b/internal/runtime/kinds.go index 40d67d6..7da0b23 100644 --- a/internal/runtime/kinds.go +++ b/internal/runtime/kinds.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "regexp" + "slices" "sort" "strings" "sync" @@ -154,6 +155,47 @@ func (m Manifest) EffectiveCapabilities() []string { return out } +// buggyWin32UnicodeInputPatchSHA256 is the SHA-256 of the initial +// reims-vgpu-win32-unicode-input.patch shipped in runtime-3731afd-p2/p3, which +// duplicated physical keystrokes (issue #14). Packages built with it must not +// get the "win32-unicode-input" capability. +const buggyWin32UnicodeInputPatchSHA256 = "0b34f7c0ebdf3ca537c7f4523af97967a06924aedba7058dbc978870f561b366" + +// legacyCapabilities declares capabilities for built-in packages whose +// manifest.json predates the "capabilities" field. It mirrors the mapping in +// scripts/pack-runtime.ps1 and runs once when the manifest is read, so callers +// only ever see declared capabilities. Other kinds must declare their own. +func legacyCapabilities(m Manifest) []string { + if m.EffectiveKind() != DefaultKind { + return nil + } + var out []string + for _, p := range m.Patches { + low := strings.ToLower(p.Name) + var c string + switch { + case strings.Contains(low, "nested-virt-nonfatal"): + c = "nested-virt-nonfatal" + case strings.Contains(low, "startup-ipis"): + c = "win10-startup-ipis" + case strings.Contains(low, "win10-compat"): + c = "win10-compat" + case strings.Contains(low, "coroutine-fiber"): + c = "win32-coroutine-fiber" + case strings.Contains(low, "win32-unicode-input"): + if sha := strings.TrimSpace(p.SHA256); sha != "" && !strings.EqualFold(sha, buggyWin32UnicodeInputPatchSHA256) { + c = "win32-unicode-input" + } + case strings.Contains(low, "display-fixed-mode"): + c = "display-fixed-mode" + } + if c != "" && !slices.Contains(out, c) { + out = append(out, c) + } + } + return out +} + // HasCapability reports whether manifest.json declares capability capName. func (m Manifest) HasCapability(capName string) bool { for _, c := range m.EffectiveCapabilities() { diff --git a/internal/runtime/manifest_test.go b/internal/runtime/manifest_test.go index 85219f0..d56d32d 100644 --- a/internal/runtime/manifest_test.go +++ b/internal/runtime/manifest_test.go @@ -3,6 +3,7 @@ package runtime import ( "os" "path/filepath" + "slices" "testing" ) @@ -17,3 +18,61 @@ func TestManifestAcceptsWholeNumberFloats(t *testing.T) { t.Fatalf("manifest = %+v", m) } } + +// Packages published before manifest.json carried "capabilities" (up to +// runtime-3731afd-p4) must keep the capabilities their patches provide. +func TestManifestWithoutCapabilitiesKeepsLegacyCapabilities(t *testing.T) { + const fixedSHA = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + for _, tc := range []struct { + name, body string + want []string + }{ + { + name: "published-p3", + body: `{"commit":"3731afd-p3","patches":[` + + `{"name":"reims-vgpu-win32-unicode-input.patch","sha256":"` + buggyWin32UnicodeInputPatchSHA256 + `"},` + + `{"name":"qemu-whpx-win10-compat.patch","sha256":"x"},` + + `{"name":"qemu-whpx-win10-startup-ipis.patch","sha256":"x"},` + + `{"name":"qemu-whpx-nested-virt-nonfatal.patch","sha256":"x"},` + + `{"name":"qemu-win32-coroutine-fiber-commit.patch","sha256":"x"}]}`, + want: []string{"win10-compat", "win10-startup-ipis", "nested-virt-nonfatal", "win32-coroutine-fiber"}, + }, + { + name: "fixed-unicode-input-and-fixed-mode", + body: `{"commit":"c","patches":[{"name":"reims-vgpu-win32-unicode-input.patch","sha256":"` + fixedSHA + `"},` + + `{"name":"reims-vgpu-display-fixed-mode.patch","sha256":"x"}]}`, + want: []string{"win32-unicode-input", "display-fixed-mode"}, + }, + { + name: "unicode-input-without-hash", + body: `{"commit":"c","patches":[{"name":"reims-vgpu-win32-unicode-input.patch"}]}`, + }, + { + name: "declared-empty-wins", + body: `{"commit":"c","capabilities":[],"patches":[{"name":"qemu-whpx-nested-virt-nonfatal.patch"}]}`, + }, + { + name: "declared-list-wins", + body: `{"commit":"c","capabilities":["display-fixed-mode"],"patches":[{"name":"qemu-whpx-nested-virt-nonfatal.patch"}]}`, + want: []string{"display-fixed-mode"}, + }, + { + name: "other-kind-must-declare", + body: `{"commit":"c","kind":"qemu-ovmf","patches":[{"name":"qemu-whpx-nested-virt-nonfatal.patch"}]}`, + }, + } { + t.Run(tc.name, func(t *testing.T) { + p := filepath.Join(t.TempDir(), "manifest.json") + if err := os.WriteFile(p, []byte(tc.body), 0o644); err != nil { + t.Fatal(err) + } + m, err := readManifest(p) + if err != nil { + t.Fatal(err) + } + if got := m.EffectiveCapabilities(); !slices.Equal(got, tc.want) { + t.Fatalf("capabilities = %v, want %v", got, tc.want) + } + }) + } +} diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index 5968957..dfcd993 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -451,8 +451,17 @@ func readManifest(path string) (Manifest, error) { } // Strip UTF-8 BOM if written by Windows PowerShell Set-Content -Encoding utf8. raw = []byte(strings.TrimPrefix(string(raw), "\uFEFF")) - err = json.Unmarshal(raw, &m) - return m, err + if err = json.Unmarshal(raw, &m); err != nil { + return m, err + } + var keys map[string]json.RawMessage + if err = json.Unmarshal(raw, &keys); err != nil { + return m, err + } + if _, declared := keys["capabilities"]; !declared { + m.Capabilities = legacyCapabilities(m) + } + return m, nil } func findBundleRoot(dir string) (string, error) { From 974389f56bf23c401a1ab61ff5fa1d971f4385a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Tue, 1 Dec 2026 03:05:54 -0700 Subject: [PATCH 27/42] fix(app): resolve macOS-native flows within the macOS driver A same-named VM in another driver made macOS restart, GetVMDetail and the flows built on it fail as ambiguous even when the driver was known. Restart now resolves the owner first and sends macOS VMs through restartMacOSVM, which also restores the commit-memory wait that a bare-name restart had skipped. Create-then-start and the Win10 cold-reboot start name the macOS driver explicitly. Tray items carry their driver ID, and the tray reads transitions by VMRef key so starting/stopping shows again. Co-Authored-By: Claude Opus 5.5 --- internal/app/app.go | 14 +++++----- internal/app/create_flow.go | 2 +- internal/app/install_guide.go | 2 +- internal/app/lifecycle_flow.go | 29 +++++++++++--------- internal/app/lifecycle_flow_test.go | 37 ++++++++++++++++++++++++++ internal/app/macos_detail.go | 8 +++--- internal/app/macos_lifecycle_native.go | 11 +++++--- internal/tray/tray.go | 9 ++++--- internal/tray/tray_windows.go | 2 +- 9 files changed, 79 insertions(+), 35 deletions(-) diff --git a/internal/app/app.go b/internal/app/app.go index 10ad872..7d87442 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -792,7 +792,7 @@ func (a *App) startTray() { items := make([]tray.VMItem, 0, len(cached)) for _, vm := range cached { state := vm.State - if t := transitions[vm.Name]; t != "" { + if t := transitions[vmKeyForDriver(vm.DriverID, vm.Name)]; t != "" { state = t } // The display name is the VM's note, read straight from its @@ -803,7 +803,7 @@ func (a *App) startTray() { label = sanitizeVMNote(string(b)) } } - items = append(items, tray.VMItem{Name: vm.Name, Label: label, State: state}) + items = append(items, tray.VMItem{DriverID: vm.DriverID, Name: vm.Name, Label: label, State: state}) } effLoc := i18n.EffectiveLocale(loc) return tray.Snapshot{ @@ -825,7 +825,7 @@ func (a *App) startTray() { // trayVMAction runs a command picked from the tray menu. The main window may // be hidden, so failures (and a copied screenshot, which has no other visible // result) are reported as a Windows notification from the tray icon. -func (a *App) trayVMAction(name string, act tray.Action) { +func (a *App) trayVMAction(driverID, name string, act tray.Action) { a.mu.Lock() rawLoc := a.cfg.Locale tm := a.trayMgr @@ -836,13 +836,13 @@ func (a *App) trayVMAction(name string, act tray.Action) { var failTitle string switch act { case tray.ActStart: - err, failTitle = a.StartVM(name), i18n.M(loc, "tray.notify.start_fail", vars) + err, failTitle = a.StartVMWithDriver(driverID, name), i18n.M(loc, "tray.notify.start_fail", vars) case tray.ActStop: - err, failTitle = a.StopVM(name, false), i18n.M(loc, "tray.notify.stop_fail", vars) + err, failTitle = a.StopVMWithDriver(driverID, name, false), i18n.M(loc, "tray.notify.stop_fail", vars) case tray.ActForceStop: - err, failTitle = a.StopVM(name, true), i18n.M(loc, "tray.notify.force_stop_fail", vars) + err, failTitle = a.StopVMWithDriver(driverID, name, true), i18n.M(loc, "tray.notify.force_stop_fail", vars) case tray.ActRestart: - err, failTitle = a.RestartVM(name), i18n.M(loc, "tray.notify.restart_fail", vars) + err, failTitle = a.RestartVMWithDriver(driverID, name), i18n.M(loc, "tray.notify.restart_fail", vars) case tray.ActShowWindow: err, failTitle = a.FocusVMWindow(name), i18n.M(loc, "tray.notify.focus_fail", vars) case tray.ActToggleFullscreen: diff --git a/internal/app/create_flow.go b/internal/app/create_flow.go index cc16bf1..fcacccd 100644 --- a/internal/app/create_flow.go +++ b/internal/app/create_flow.go @@ -192,7 +192,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error { 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 } diff --git a/internal/app/install_guide.go b/internal/app/install_guide.go index 99e345a..56a1cea 100644 --- a/internal/app/install_guide.go +++ b/internal/app/install_guide.go @@ -153,7 +153,7 @@ func (a *App) buildInstallGuide(ctx context.Context, g installguide.Guide, d rei if err := checkBoot(); err != nil { return err } - stopped, err := a.restartVMLegacy(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() diff --git a/internal/app/lifecycle_flow.go b/internal/app/lifecycle_flow.go index 4dfb35d..712abfb 100644 --- a/internal/app/lifecycle_flow.go +++ b/internal/app/lifecycle_flow.go @@ -226,21 +226,26 @@ func (a *App) RestartVMWithDriver(driverID, name string) error { a.mu.Lock() svc := a.lifecycleSvc a.mu.Unlock() - if svc != nil && driverID == "" { - if _, vm, err := svc.Resolve(context.Background(), driverID, name); err == nil && vm.DriverID != driver.BuiltinReimsMacOSDriverID { - if err := a.StopVMWithDriver(driverID, name, false); err != nil { - return err - } - return a.StartVMWithDriver(driverID, name) - } - } - if driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID { - if err := a.StopVMWithDriver(driverID, name, false); err != nil { + var ref driver.VMRef + if svc != nil { + _, vm, err := svc.Resolve(context.Background(), driverID, name) + if err != nil { return err } - return a.StartVMWithDriver(driverID, name) + 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) } - _, err := a.restartVMLegacy(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 } diff --git a/internal/app/lifecycle_flow_test.go b/internal/app/lifecycle_flow_test.go index ef79f42..ecbdacb 100644 --- a/internal/app/lifecycle_flow_test.go +++ b/internal/app/lifecycle_flow_test.go @@ -10,6 +10,7 @@ import ( "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 { @@ -144,3 +145,39 @@ func TestAppRecoveryActionsUseLifecycle(t *testing.T) { 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) + } +} diff --git a/internal/app/macos_detail.go b/internal/app/macos_detail.go index 6ba2056..3ac517b 100644 --- a/internal/app/macos_detail.go +++ b/internal/app/macos_detail.go @@ -3,7 +3,6 @@ package app import ( "context" "encoding/json" - "fmt" "path/filepath" "strings" @@ -73,13 +72,12 @@ func (a *App) GetVMDetail(name string) (reims.VMDetail, error) { if svc == nil { return a.getVMDetailLegacy(name) } - vm, err := a.GetVMInfo("", 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 } - if vm.DriverID != driver.BuiltinReimsMacOSDriverID { - return reims.VMDetail{}, fmt.Errorf("VM %q belongs to driver %q, not the macOS detail adapter", name, vm.DriverID) - } raw, err := json.Marshal(vm.DriverData) if err != nil { return reims.VMDetail{}, err diff --git a/internal/app/macos_lifecycle_native.go b/internal/app/macos_lifecycle_native.go index c152e4b..062f9c5 100644 --- a/internal/app/macos_lifecycle_native.go +++ b/internal/app/macos_lifecycle_native.go @@ -9,6 +9,7 @@ import ( "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" @@ -172,7 +173,7 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) { if watchCtx.Err() != nil { return } - if err := a.StartVM(name); err != nil { + if err := a.StartVMWithDriver(driver.BuiltinReimsMacOSDriverID, name); err != nil { a.emitVMLog(name, "Win10 WHPX cold-reboot start failed: "+err.Error()) } }() @@ -390,9 +391,11 @@ func (a *App) stopVMLegacy(name string, force bool) error { func (a *App) RestartVM(name string) error { return a.RestartVMWithDriver("", name) } -func (a *App) restartVMLegacy(name string) (stopped bool, err error) { +// 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.StopVM(name, false); err != nil { + if err := a.StopVMWithDriver(driver.BuiltinReimsMacOSDriverID, name, false); err != nil { return false, err } ctx := a.baseCtx() @@ -403,7 +406,7 @@ func (a *App) restartVMLegacy(name string) (stopped bool, err error) { if err := ctx.Err(); err != nil { return true, err } - return true, a.StartVM(name) + return true, a.StartVMWithDriver(driver.BuiltinReimsMacOSDriverID, name) } func (a *App) ejectInstallerLegacy(name string) error { diff --git a/internal/tray/tray.go b/internal/tray/tray.go index a13a046..54bf0e5 100644 --- a/internal/tray/tray.go +++ b/internal/tray/tray.go @@ -11,9 +11,10 @@ import ( // VMItem is a lightweight summary shown inside the system tray menu. type VMItem struct { - Name string // identifier passed back to callbacks - Label string // display name (the VM's note); empty shows Name - State string // running | stopped | starting | stopping | broken + DriverID string // owning guest driver, passed back to callbacks with Name + Name string // VM name within DriverID, passed back to callbacks + Label string // display name (the VM's note); empty shows Name + State string // running | stopped | starting | stopping | broken } func (v VMItem) title() string { @@ -50,7 +51,7 @@ const ( type Callbacks struct { OnShow func() OnNewVM func() - OnVMAction func(name string, act Action) + OnVMAction func(driverID, name string, act Action) OnQuit func() GetSnapshot func() Snapshot } diff --git a/internal/tray/tray_windows.go b/internal/tray/tray_windows.go index 26167bd..5e5c134 100644 --- a/internal/tray/tray_windows.go +++ b/internal/tray/tray_windows.go @@ -565,7 +565,7 @@ func (m *Manager) dispatchCommand(cmd int) { } m.mu.Unlock() if valid && m.cb.OnVMAction != nil { - go m.cb.OnVMAction(item.Name, act) + go m.cb.OnVMAction(item.DriverID, item.Name, act) } } } From aabe0cf29fc01c6060ce025943d4ec2b00645962 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Tue, 1 Dec 2026 03:05:54 -0700 Subject: [PATCH 28/42] feat(plugin): hide the core system plugin from plugin lists builtin.core only contributes the default theme and cannot be turned off, so listing it as a plugin was noise. The plugins page, plugin list and the plugin doctor fallback now use Registry.ListVisible; Info and market comparisons still see every plugin. Co-Authored-By: Claude Opus 5.5 --- docs/plugin-architecture.md | 4 ++-- frontend/src/components/PluginsPage.tsx | 7 ++----- internal/app/plugins_flow.go | 2 +- internal/cli/plugin.go | 4 ++-- internal/plugin/builtin/builtin_test.go | 28 +++++++++++++++++++++++++ internal/plugin/registry.go | 14 +++++++++++++ 6 files changed, 49 insertions(+), 10 deletions(-) diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 6e9b16a..67427a9 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -106,7 +106,7 @@ flowchart TB 扩展点先由内置功能使用一遍再对外开放。内置功能分两类,判断标准是用户关掉它之后,是「少了一项功能」还是「已有功能坏掉」: -- **核心** `builtin.core`:只保留客体无关的默认主题(主题 id 为 `builtin.theme.default`)。它是**系统插件**:始终启用,不能停用或卸载,插件页显示为一行「始终启用」,不参与「使用中」检查。 +- **核心** `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 时由「使用中」检查阻止停用。安装引导保留独立应用级开关。启动准备暂经 `vm.beforeStart`,下一步改由驱动自己执行,见 [guest-plugin-migration.md](guest-plugin-migration.md) 步骤 2。 - **可选内置扩展**:Guest Tools 传输服务、剪贴板互通、宿主输入服务、虚拟机窗口安装引导。经同一注册表注册、可独立启停、停用后零残留,停用即真正停止(不被其他调用方重新拉起)。首批示例为默认开启的剪贴板互通(见 §5.4)。 @@ -396,7 +396,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card` | 入口 | 内容 | | :--- | :--- | | CLI | `reims-go plugin list / search / install / update [id] / pack / link / enable [--approve-high-risk] / disable / remove [--purge] / info / doctor [--json] [dir\|zip\|id] / locale / run `;`vm create --driver ` | -| 应用设置 → 插件 | 提供「已安装 / 插件市场」双视图(市场索引惰性加载):核心置顶、显示「始终启用」且无开关;其余显示来源与信任标签、权限摘要、安全扫描报告入口、启用开关、故障状态与日志入口;本地包导入前先展示三段式静态安全报告并执行硬门禁拦截 | +| 应用设置 → 插件 | 提供「已安装 / 插件市场」双视图(市场索引惰性加载):系统插件(核心)不列出;其余显示来源与信任标签、权限摘要、安全扫描报告入口、启用开关、故障状态与日志入口;本地包导入前先展示三段式静态安全报告并执行硬门禁拦截 | | 插件设置页 | 由 `settings` Schema 渲染,复用现有设置控件,标注生效时机 | | VM 页面 | 按能力位显隐操作;`vm.toolbar` 菜单项支持 `when` 条件;`vm.card` 展示驱动或插件提供的键值信息 | | 创建向导 | 先选驱动,再按驱动 `CreateSchema` 渲染专属表单 | diff --git a/frontend/src/components/PluginsPage.tsx b/frontend/src/components/PluginsPage.tsx index 7cba893..6f63d34 100644 --- a/frontend/src/components/PluginsPage.tsx +++ b/frontend/src/components/PluginsPage.tsx @@ -365,11 +365,8 @@ export const PluginsPage: React.FC = ({ 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]) diff --git a/internal/app/plugins_flow.go b/internal/app/plugins_flow.go index e3960c1..cf0446f 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -578,7 +578,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) { diff --git a/internal/cli/plugin.go b/internal/cli/plugin.go index 809ed0e..de4fd16 100644 --- a/internal/cli/plugin.go +++ b/internal/cli/plugin.go @@ -165,7 +165,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("", " ") @@ -509,7 +509,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 diff --git a/internal/plugin/builtin/builtin_test.go b/internal/plugin/builtin/builtin_test.go index ab4c5c7..c5120c0 100644 --- a/internal/plugin/builtin/builtin_test.go +++ b/internal/plugin/builtin/builtin_test.go @@ -143,3 +143,31 @@ func TestGuestToolsInputBridgeEnvGating(t *testing.T) { t.Fatalf("with input plugin disabled: unexpected input bridge env %v", env) } } + +// The core plugin is the host itself: user-facing lists leave it out, while +// lookups by ID and the full registry listing still see it. +func TestCorePluginHiddenFromVisibleList(t *testing.T) { + reg := plugin.NewRegistry(nil) + if err := RegisterAll(reg, HostCallbacks{}, nil); err != nil { + t.Fatalf("RegisterAll: %v", err) + } + reg.Reconcile(context.Background()) + has := func(list []plugin.PluginInfo, id string) bool { + for _, p := range list { + if p.ID == id { + return true + } + } + return false + } + visible := reg.ListVisible() + if has(visible, IDCore) { + t.Fatal("ListVisible must not include the core plugin") + } + if !has(visible, IDGuestTools) || len(visible) != len(reg.List())-1 { + t.Fatalf("ListVisible = %d plugins, List = %d", len(visible), len(reg.List())) + } + if info, ok := reg.Info(IDCore); !ok || !info.System { + t.Fatalf("Info(core) = %+v, %v", info, ok) + } +} diff --git a/internal/plugin/registry.go b/internal/plugin/registry.go index 81bff1d..459b076 100644 --- a/internal/plugin/registry.go +++ b/internal/plugin/registry.go @@ -1431,6 +1431,20 @@ func (r *Registry) List() []PluginInfo { return out } +// ListVisible is List without system plugins. A system plugin is part of the +// host itself (always on, nothing to configure), so plugin lists shown to +// users leave it out; Info still returns it by ID. +func (r *Registry) ListVisible() []PluginInfo { + all := r.List() + out := all[:0] + for _, p := range all { + if !p.System { + out = append(out, p) + } + } + return out +} + func (r *Registry) entryToInfoLocked(e *pluginEntry) PluginInfo { m := e.def.Manifest perms := make([]PermissionSpec, 0, len(m.Permissions)) From f8943ea78c93cc55faae2f683cacd51e8f2f9e6e Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 18:06:40 +0800 Subject: [PATCH 29/42] docs: define PR ownership and client boundaries --- AGENTS.md | 1 + docs/pr-review-guidelines.md | 53 ++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 docs/pr-review-guidelines.md diff --git a/AGENTS.md b/AGENTS.md index ad9c2c8..a7fd824 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,6 +69,7 @@ - [`docs/roadmap.md`](docs/roadmap.md) — 公开路线图与近期重点 - [`docs/architecture.md`](docs/architecture.md) — 系统架构、模块职责与安全边界 - [`docs/design-guidelines.md`](docs/design-guidelines.md) — 产品与界面设计规范(配置原语、状态模型、视觉与文案) +- [`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) — 插件系统架构与扩展接口规范 - [运行时补丁与上游跟踪](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md) — 运行时源码入口与依赖补丁 diff --git a/docs/pr-review-guidelines.md b/docs/pr-review-guidelines.md new file mode 100644 index 0000000..43ba194 --- /dev/null +++ b/docs/pr-review-guidelines.md @@ -0,0 +1,53 @@ +# PR 变更归属审查 + +> 以产生行为的实现为准。先定位改动发生在哪个组件,再决定提交仓库和验证范围。桌面或 CLI 是否有入口,只决定客户端是否也需要改动。 + +## 1. 确认归属 + +以 PR 实际目标分支与提交的差异为准。使用 GitHub 的「Files changed」或本地 `git diff ...`,同时检查生成文件对应的源文件、补丁目标、依赖锁定和 CI 变更。先从用户入口沿调用链找到行为的实现,再按下表归属。 + +| 类别 | 行为或改动 | 实现归属 | +| :--- | :--- | :--- | +| 客户端 | GUI、CLI、虚拟机流程编排、宿主机体检及窗口集成、Guest Tools、运行时下载和安装 | `Reims-Go`。主要入口和模块见[系统架构](architecture.md)。 | +| 客户端运行时适配 | 构造命令和环境、调用已发布的 CLI / QMP 接口、解析结果以及处理版本、能力或错误 | `Reims-Go`。生效行为仍由被调用的组件实现。 | +| Reims vGPU 内核及控制工具 | `reims-ctl` 的配置、启动与参数语义,`reims-restore` 的恢复流程,Reims 的宿主图形、原生 VM 窗口及输入实现 | [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu)。运行时所用改动以 [Reims vGPU fork](https://github.com/yxc0915/reims-vgpu) 的实际构建提交为准。 | +| QEMU 虚拟化层 | WHPX / TCG、客体机器与设备模型、`reims-graphics-pci` 的 PCI 设备侧、QMP 命令实现、`qcow2` 格式与迁移机制 | [`steelbrain/qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu)。核对构建提交中的 `vendor/qemu` gitlink 及其来源。 | +| 独立上游工具 | `reims-util` 内的引导资源生成、安装镜像处理和工具自身的参数语义 | [`steelbrain/reims-util`](https://github.com/steelbrain/reims-util)。按运行时锁定的提交定位。 | +| 独立图形依赖 | Metal 到 Vulkan 的命令、资源和着色器转换实现 | [`steelbrain/metal2vulkan`](https://github.com/steelbrain/metal2vulkan)。按运行时锁定的提交定位。 | +| 其他独立引擎 | 引擎自身的执行、翻译和固件实现 | 对应引擎的源代码仓库。客户端的驱动注册、启动参数适配和状态展示仍归 `Reims-Go`。 | +| 运行时集成与分发 | 上游版本选取、依赖补丁、运行时编译、打包、能力清单及 Preview 发布 | [`yxc0915/reims-vgpu`](https://github.com/yxc0915/reims-vgpu) 的运行时流水线。构建及发布规则见[便携运行时规范](portable-runtime-spec.md)。 | + +同一项功能可以涉及多个仓库。窗口安装引导调用已有运行时能力时,浮层、进度和流程编排属于客户端。若同时调整 Reims 原生窗口的事件语义,窗口实现属于 `reims-vgpu`,调用和交互留在客户端。挂起功能同理,GUI / CLI 和任务状态属于客户端,QEMU 的迁移或设备状态实现属于 QEMU;运行时再负责选取具备该能力的版本。 + +## 2. 审查客户端独立性 + +- **构建与发布**:客户端 CI 仅从 `Reims-Go` 源码检出完成前端构建、Go 检查和应用产物构建。运行时源码、编译工具链和运行时发布产物由运行时仓库管理。客户端自行发布应用,并在虚拟机运行前下载、校验或导入兼容的独立运行时。 +- **接口边界**:客户端通过约定的子进程接口和协议调用运行时。配置写入沿用 [`reims-ctl set`](design-guidelines.md#2-配置原语)。需要新增命令、参数、字段或能力时,在负责组件实现,并在客户端附上对应接口证据。 +- **运行时兼容**:客户端 PR 写明验证使用的运行时与最低要求。若依赖新能力,优先使用运行时明确声明的能力或版本,在旧版、缺失运行时和不支持该能力的场景下明确禁用、提示或保留既有流程。客户端合入与运行时发布各自按其流程验收,用户默认仍走受支持的 `stable` 通道。 +- **跨仓交付**:按归属拆分 PR。客户端 PR 链接底层 PR、提交或运行时版本,列出合并顺序和兼容路径。临时依赖补丁由运行时仓库记录,注明目标仓库、适用提交和退役条件。跨仓定位以源码、依赖锁定和产物清单为证据。 + +## 3. PR 描述与合并检查 + +提交者在 PR 描述中附上以下信息。纯文档或纯客户端改动可将无关字段写为「不适用」。 + +```markdown +## 变更归属 + +- 用户可见行为 +- 变更位置与责任仓库 +- 上游证据(仓库、commit、文件及行号) +- 跨仓依赖(关联 PR、合并顺序、运行时要求) +- 旧版或缺失运行时的表现 + +## 验证 + +- 已通过的检查及运行时版本 +- 待验证场景及其影响 +``` + +审查者在合并前核对以下各项。 + +- [ ] 差异中的客户端、内核、独立依赖和分发变更均已注明归属。跨仓实现已拆分并可追溯。 +- [ ] 客户端能独立通过其 CI。行为变更已按影响验证 GUI、CLI 或两者的正常入口。 +- [ ] 底层或打包改动有负责仓库的验证证据。涉及运行时发布时,核对 `manifest.json` 中的来源提交、补丁与能力声明,以及相应的 [`alpha` 准入与 `stable` 冒烟要求](portable-runtime-spec.md#5-发布通道alpha--stable)。 +- [ ] 上游行为已定位到对应提交和源码行号。真机或兼容性覆盖不足的场景标明「待验证」,合并前明确其对客户端发布和能力开放的影响。 From 8887771beccb782fa1648a74294cb587125d1aa7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Tue, 1 Dec 2026 03:29:03 -0700 Subject: [PATCH 30/42] feat(plugin): allow disabling macOS guest plugin and guard native flows --- docs/guest-plugin-migration.md | 2 +- docs/plugin-architecture.md | 5 +- frontend/src/components/PluginsPage.tsx | 39 +++++++++++++- frontend/src/i18n/domains/plugins.gen.ts | 6 +++ frontend/src/i18n/keys.gen.ts | 3 ++ internal/app/create_flow.go | 3 ++ internal/app/macos_client.go | 20 +++++++ internal/app/macos_disable_test.go | 57 ++++++++++++++++++++ internal/app/opencore_flow.go | 3 ++ internal/app/plugins_flow.go | 19 +------ internal/cli/plugin.go | 16 +----- internal/driver/driver.go | 67 ++++++++++++++++++++++++ internal/driver/driver_test.go | 38 ++++++++++++++ internal/i18n/catalog_gen.go | 2 + internal/plugin/kernel_test.go | 26 ++++++++- internal/plugin/registry.go | 38 ++++++++++++-- locales/en-US/native.json | 1 + locales/en-US/plugins.json | 3 ++ locales/zh-CN/native.json | 1 + locales/zh-CN/plugins.json | 3 ++ 20 files changed, 311 insertions(+), 41 deletions(-) create mode 100644 internal/app/macos_disable_test.go diff --git a/docs/guest-plugin-migration.md b/docs/guest-plugin-migration.md index 8913b06..4106e3c 100644 --- a/docs/guest-plugin-migration.md +++ b/docs/guest-plugin-migration.md @@ -106,7 +106,7 @@ GUI 启动、首次设置、`SetDataRoot`、CLI 各自打开数据目录;迁 - 新增内置插件 `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 运行时停用它。 +- **静态声明驱动**:新插件在清单 `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` 不移动。 diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 67427a9..2284d17 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -107,7 +107,7 @@ flowchart TB 扩展点先由内置功能使用一遍再对外开放。内置功能分两类,判断标准是用户关掉它之后,是「少了一项功能」还是「已有功能坏掉」: - **核心** `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 时由「使用中」检查阻止停用。安装引导保留独立应用级开关。启动准备暂经 `vm.beforeStart`,下一步改由驱动自己执行,见 [guest-plugin-migration.md](guest-plugin-migration.md) 步骤 2。 +- **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)。 旧版曾把 macOS 驱动、兼容补偿、安装引导与准备步骤拆成多个内置插件。数据布局 v2 的迁移删除这些旧 ID 的记录:显式设置与旧安装引导启停状态转入 `builtin.guest.macos`,参数账本中已知 macOS 条目也转给该插件;无关插件与宿主参数保持原所有者。 @@ -120,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 扩展点目录 diff --git a/frontend/src/components/PluginsPage.tsx b/frontend/src/components/PluginsPage.tsx index 6f63d34..1b0779c 100644 --- a/frontend/src/components/PluginsPage.tsx +++ b/frontend/src/components/PluginsPage.tsx @@ -103,6 +103,7 @@ export const PluginsPage: React.FC = ({ const [settingsValues, setSettingsValues] = useState>({}) const [logTarget, setLogTarget] = useState<{ id: string; text: string } | null>(null) const [removeTarget, setRemoveTarget] = useState(null) + const [disableTarget, setDisableTarget] = useState(null) const [deleteSchemeTarget, setDeleteSchemeTarget] = useState(null) // Static risk scan modal state (pre-install .zip preview or installed plugin scan) @@ -171,7 +172,12 @@ export const PluginsPage: React.FC = ({ 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) @@ -469,7 +475,7 @@ export const PluginsPage: React.FC = ({ ) : ( void togglePlugin(p, checked)} /> @@ -919,6 +925,35 @@ export const PluginsPage: React.FC = ({ )} + {disableTarget && ( + setDisableTarget(null)} + > +
+ {tr('pluginDisableInUseBody')} +
+
+ + + + + +
+
+ )} + {removeTarget && ( = { "pluginColorSchemes": "配色方案", "pluginColorSchemesHint": "修改种子色派生整套界面色阶", "pluginDeleteScheme": "删除方案", + "pluginDisable": "停用", + "pluginDisableInUseBody": "停用后,这个插件管理的虚拟机会显示为「驱动不可用」,不能启动或修改。虚拟机文件不会删除,重新启用即可恢复。运行中的虚拟机需要先停止。", + "pluginDisableInUseTitle": "停用仍有虚拟机的插件", "pluginDone": "完成", "pluginEnableLater": "暂不启用", "pluginEnableNow": "启用", @@ -134,6 +137,9 @@ export const pluginsEn: Record = { "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", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index aa2a8bf..11bfe79 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -504,6 +504,9 @@ export type I18nKey = | "pluginColorSchemes" | "pluginColorSchemesHint" | "pluginDeleteScheme" + | "pluginDisable" + | "pluginDisableInUseBody" + | "pluginDisableInUseTitle" | "pluginDone" | "pluginEnableLater" | "pluginEnableNow" diff --git a/internal/app/create_flow.go b/internal/app/create_flow.go index fcacccd..11cc2b5 100644 --- a/internal/app/create_flow.go +++ b/internal/app/create_flow.go @@ -18,6 +18,9 @@ import ( ) 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) } diff --git a/internal/app/macos_client.go b/internal/app/macos_client.go index 77b87bd..19894d2 100644 --- a/internal/app/macos_client.go +++ b/internal/app/macos_client.go @@ -1,14 +1,34 @@ package app import ( + "errors" "fmt" "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() diff --git a/internal/app/macos_disable_test.go b/internal/app/macos_disable_test.go new file mode 100644 index 0000000..cf2975d --- /dev/null +++ b/internal/app/macos_disable_test.go @@ -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) + } +} diff --git a/internal/app/opencore_flow.go b/internal/app/opencore_flow.go index ba6cfe8..0f5d0f9 100644 --- a/internal/app/opencore_flow.go +++ b/internal/app/opencore_flow.go @@ -27,6 +27,9 @@ 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) (*startprep.Prep, error) { + if err := a.requireMacOSEnabled(); err != nil { + return nil, err + } a.mu.Lock() cfg := *a.cfg a.mu.Unlock() diff --git a/internal/app/plugins_flow.go b/internal/app/plugins_flow.go index cf0446f..e7ab99c 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -95,23 +95,8 @@ func (a *App) initPlugins() { 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) diff --git a/internal/cli/plugin.go b/internal/cli/plugin.go index de4fd16..1cd4d41 100644 --- a/internal/cli/plugin.go +++ b/internal/cli/plugin.go @@ -47,20 +47,8 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, * }, } router := driver.NewRouterWithDataRoot(mgr.Registry(), func() string { return cfg.DataRoot }) - 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 - }) + 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 diff --git a/internal/driver/driver.go b/internal/driver/driver.go index 9ff486f..4170e21 100644 --- a/internal/driver/driver.go +++ b/internal/driver/driver.go @@ -458,6 +458,73 @@ func (rt *Router) ResolveRef(ctx context.Context, ref VMRef) (Driver, VMInfo, er return nil, VMInfo{}, err } +// PluginInUseChecker reports a plugin as in use while a guest driver it +// declares (or registers under its own ID) owns any VM. It blocks removal. +func (rt *Router) PluginInUseChecker() plugin.InUseChecker { + return rt.pluginChecker(rt.CheckDriverInUse) +} + +// PluginBusyChecker reports a plugin as busy while a VM of one of its guest +// drivers is not stopped. It blocks disabling. +func (rt *Router) PluginBusyChecker() plugin.InUseChecker { + return rt.pluginChecker(rt.CheckDriverRunning) +} + +// pluginChecker must not call Registry.Info/List: both invoke the in-use +// checker, which recursed until the goroutine stack overflowed. +func (rt *Router) pluginChecker(check func(context.Context, string) (bool, string, error)) plugin.InUseChecker { + return func(pluginID string) (bool, string, error) { + seen := map[string]bool{} + for _, did := range append([]string{pluginID}, rt.reg.DeclaredDriverIDs(pluginID)...) { + if did == "" || seen[did] { + continue + } + seen[did] = true + if hit, reason, err := check(context.Background(), did); err != nil || hit { + return hit, reason, err + } + } + return false, "", nil + } +} + +// vmIdle reports states in which a driver can go away without orphaning a +// live VM process. Anything else (running, starting, stopping, paused or an +// unknown state) counts as live. +func vmIdle(state string) bool { + switch strings.ToLower(strings.TrimSpace(state)) { + case "stopped", "broken", "driver_unavailable": + return true + } + return false +} + +// CheckDriverRunning returns true if a VM of driverID is not stopped +// (fail-closed on list error). A driver that is not active runs nothing. +func (rt *Router) CheckDriverRunning(ctx context.Context, driverID string) (bool, string, error) { + if rt == nil || rt.reg == nil { + return false, "", errors.New("driver router not initialized") + } + raw, ok := rt.reg.GuestDriver(driverID) + if !ok { + return false, "", nil + } + d, ok := raw.(Driver) + if !ok || d == nil { + return false, "", nil + } + vms, err := d.List(ctx) + if err != nil { + return true, "", err + } + for _, vm := range vms { + if !vmIdle(vm.State) { + return true, fmt.Sprintf("VM %s is %s", vm.Name, vm.State), nil + } + } + return false, "", nil +} + // CheckDriverInUse returns true if any VM belongs to driverID (fail-closed on list error, §4.1). func (rt *Router) CheckDriverInUse(ctx context.Context, driverID string) (bool, string, error) { if rt == nil || rt.reg == nil { diff --git a/internal/driver/driver_test.go b/internal/driver/driver_test.go index 1ee95d6..7afbd46 100644 --- a/internal/driver/driver_test.go +++ b/internal/driver/driver_test.go @@ -121,3 +121,41 @@ func TestRenamedDriverKeepsMarkedVMsVisible(t *testing.T) { t.Fatalf("DriverByID(old ID) should look up %s, got %v", newID, err) } } + +// A plugin whose driver owns only stopped VMs may be disabled (busy=false) +// but not removed (inUse=true); a VM in any other state makes it busy. +func TestPluginBusyAndInUseCheckers(t *testing.T) { + const pluginID, driverID = "test.guest", "test.driver" + drv := &fakeDriver{id: driverID, vms: []VMInfo{{Name: "a", State: "stopped"}, {Name: "b", State: "broken"}}} + reg := plugin.NewRegistry(nil) + if err := reg.Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ID: pluginID, Version: "1.0.0", + Contributes: plugin.Contributes{GuestDrivers: []plugin.GuestDriverContribution{{ID: driverID}}}}, + 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 := NewRouter(reg, nil) + busy, inUse := router.PluginBusyChecker(), router.PluginInUseChecker() + + if hit, _, err := busy(pluginID); err != nil || hit { + t.Fatalf("stopped/broken VMs: busy=%v err=%v", hit, err) + } + if hit, _, err := inUse(pluginID); err != nil || !hit { + t.Fatalf("owned VMs: inUse=%v err=%v", hit, err) + } + for _, state := range []string{"running", "starting", "stopping", "paused", ""} { + drv.vms[0].State = state + if hit, reason, err := busy(pluginID); err != nil || !hit || !strings.Contains(reason, "a") { + t.Fatalf("state %q: busy=%v reason=%q err=%v", state, hit, reason, err) + } + } + if hit, _, _ := busy("other.plugin"); hit { + t.Fatal("a plugin without drivers must never be busy") + } +} diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 37876da..43a7aa7 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -135,6 +135,7 @@ var catalog = map[Locale]map[string]string{ "err.gpu_icd_stale": "原显卡的 Vulkan ICD 文件已不存在({path})。在设置 → 图形与显示器中重新选择显卡,或选择自动", "err.gpu_vulkan_floor": "宿主显卡不满足 Reims vGPU 的 Vulkan 1.3 硬件要求。请更新显卡驱动,或在设置中将虚拟显卡切为 VMware SVGA(软件渲染)", "err.guest_tools_disabled": "Guest Tools 传输服务已在插件页停用,启用后才能使用剪贴板、共享文件夹与防休眠", + "err.macos.disabled": "「macOS 虚拟机支持」插件已停用,请先在插件页启用", "err.plugin.high_risk_unapproved": "插件「{id}」包含高危权限,需要先确认授权后才能启用", "err.plugin.in_use": "插件「{id}」正在被虚拟机使用,无法停用或卸载:{reason}", "err.plugin.safe_mode": "当前处于安全模式,已暂停加载和变更第三方插件", @@ -659,6 +660,7 @@ var catalog = map[Locale]map[string]string{ "err.gpu_icd_stale": "The selected GPU's Vulkan ICD file no longer exists ({path}). In Settings → Graphics & displays, reselect the GPU or choose Automatic", "err.gpu_vulkan_floor": "Host GPU does not meet Reims vGPU's Vulkan 1.3 requirements. Update GPU drivers or switch graphics to VMware SVGA (software rendering) in VM Settings", "err.guest_tools_disabled": "Guest Tools Transport is turned off on the Plugins page; turn it on to use clipboard, shared folders and keep-awake", + "err.macos.disabled": "macOS VM Support is disabled; enable it on the Plugins page first", "err.plugin.high_risk_unapproved": "Plugin “{id}” requests high-risk permissions and requires confirmation before enabling", "err.plugin.in_use": "Plugin “{id}” is currently in use and cannot be disabled or removed: {reason}", "err.plugin.safe_mode": "Safe mode is active; third-party plugin changes are paused", diff --git a/internal/plugin/kernel_test.go b/internal/plugin/kernel_test.go index 42c3d4d..696c4da 100644 --- a/internal/plugin/kernel_test.go +++ b/internal/plugin/kernel_test.go @@ -164,14 +164,36 @@ func TestRegistryPanicRollbackAndInUseFailClosed(t *testing.T) { Desired: true, }) reg.Reconcile(context.Background()) - reg.SetInUseChecker(func(id string) (bool, string, error) { + reg.SetBusyChecker(func(id string) (bool, string, error) { if id == "drv.test" { return false, "", errors.New("probe error") } return false, "", nil }) if err := reg.SetDesired(context.Background(), "drv.test", false); err == nil { - t.Fatal("expected fail-closed error when InUseChecker fails") + t.Fatal("expected fail-closed error when BusyChecker fails") + } + reg.SetBusyChecker(func(string) (bool, string, error) { return true, "VM a is running", nil }) + if err := reg.SetDesired(context.Background(), "drv.test", false); err == nil { + t.Fatal("expected disabling to be refused while a VM runs") + } + + // Owning stopped VMs blocks removal, not disabling: the VMs stay on disk + // as driver_unavailable until the plugin is enabled again. + reg.SetBusyChecker(func(string) (bool, string, error) { return false, "", nil }) + reg.SetInUseChecker(func(id string) (bool, string, error) { return id == "drv.test", "VM a owned by drv.test", nil }) + if err := reg.SetDesired(context.Background(), "drv.test", false); err != nil { + t.Fatalf("disabling a plugin with stopped VMs: %v", err) + } + if reg.StateOf("drv.test") == StateActive { + t.Fatal("drv.test still active after disabling") + } + if err := reg.Unregister(context.Background(), "drv.test"); err == nil { + t.Fatal("expected removal to be refused while the plugin owns VMs") + } + reg.SetInUseChecker(func(string) (bool, string, error) { return false, "", errors.New("probe error") }) + if err := reg.Unregister(context.Background(), "drv.test"); err == nil { + t.Fatal("expected fail-closed removal when InUseChecker fails") } } diff --git a/internal/plugin/registry.go b/internal/plugin/registry.go index 459b076..0f425df 100644 --- a/internal/plugin/registry.go +++ b/internal/plugin/registry.go @@ -87,6 +87,7 @@ type Registry struct { entries map[string]*pluginEntry services map[string]serviceRecord // serviceName -> record inUseChecker InUseChecker + busyChecker InUseChecker onChange []func() logger func(source, line string) localeFn func() i18n.Locale @@ -133,13 +134,23 @@ func (r *Registry) Hooks() *HookBus { return r.hooks } -// SetInUseChecker installs the guard that prevents disabling/removing plugins in use. +// SetInUseChecker installs the guard that prevents removing plugins whose +// drivers still own VMs. Disabling is guarded by SetBusyChecker instead: +// a disabled plugin keeps its VMs on disk, shown as driver_unavailable. func (r *Registry) SetInUseChecker(fn InUseChecker) { r.mu.Lock() r.inUseChecker = fn r.mu.Unlock() } +// SetBusyChecker installs the guard that prevents disabling a plugin while +// work it owns is live (for guest drivers: a VM that is not stopped). +func (r *Registry) SetBusyChecker(fn InUseChecker) { + r.mu.Lock() + r.busyChecker = fn + r.mu.Unlock() +} + // OnChange subscribes to registry state or extension-point changes. func (r *Registry) OnChange(fn func()) func() { if fn == nil { @@ -262,7 +273,7 @@ func (r *Registry) SetDesired(ctx context.Context, id string, enabled bool) erro if system { return fmt.Errorf("plugin %q is part of Reims-Go core and cannot be disabled", id) } - if err := r.checkNotInUse(id); err != nil { + if err := r.checkNotBusy(id); err != nil { return err } } @@ -308,7 +319,28 @@ func (r *Registry) checkNotInUse(id string) error { if reason == "" { reason = "referenced by existing VMs" } - return fmt.Errorf("plugin %q is in use and cannot be disabled or removed: %s", id, reason) + return fmt.Errorf("plugin %q is in use and cannot be removed: %s", id, reason) + } + return nil +} + +func (r *Registry) checkNotBusy(id string) error { + r.mu.RLock() + checker := r.busyChecker + r.mu.RUnlock() + if checker == nil { + return nil + } + busy, reason, err := checker(id) + if err != nil { + // Fail-closed like checkNotInUse: an unknown VM state blocks disabling. + return fmt.Errorf("cannot verify whether plugin %q has running VMs (treated as running): %w", id, err) + } + if busy { + if reason == "" { + reason = "a VM is running" + } + return fmt.Errorf("plugin %q cannot be disabled while its VMs run; stop them first: %s", id, reason) } return nil } diff --git a/locales/en-US/native.json b/locales/en-US/native.json index 6e15f22..c9c09b4 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -198,6 +198,7 @@ ] }, "err.runtime_not_installed": "no active portable runtime found; run `reims-go runtime install ` first", + "err.macos.disabled": "macOS VM Support is disabled; enable it on the Plugins page first", "err.vm_not_running": "VM {name} is not running", "err.fullscreen_vmware_svga": "Press Ctrl+Alt+F in the QEMU window for {name} to toggle full screen", "err.vm_window_not_found": "Couldn’t find the display window for {name}", diff --git a/locales/en-US/plugins.json b/locales/en-US/plugins.json index ef1f210..4604d79 100644 --- a/locales/en-US/plugins.json +++ b/locales/en-US/plugins.json @@ -27,6 +27,9 @@ "pluginHighRiskNotice": "Contains high-risk permissions; approval required before enabling", "pluginViewLog": "View log", "pluginInUse": "In use", + "pluginDisable": "Disable", + "pluginDisableInUseTitle": "Disable a plugin that still has VMs", + "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.", "pluginRemove": "Remove", "pluginThemeSection": "Theme extensions", "pluginActiveTheme": "Active theme pack", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index 483c53d..757c900 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -198,6 +198,7 @@ ] }, "err.runtime_not_installed": "未找到已激活的便携运行时,请先执行 `reims-go runtime install <归档路径>`", + "err.macos.disabled": "「macOS 虚拟机支持」插件已停用,请先在插件页启用", "err.vm_not_running": "虚拟机 {name} 未运行", "err.fullscreen_vmware_svga": "在 {name} 的 QEMU 窗口中按 Ctrl+Alt+F 切换全屏", "err.vm_window_not_found": "找不到 {name} 的显示窗口", diff --git a/locales/zh-CN/plugins.json b/locales/zh-CN/plugins.json index 06d539c..aecdd52 100644 --- a/locales/zh-CN/plugins.json +++ b/locales/zh-CN/plugins.json @@ -27,6 +27,9 @@ "pluginHighRiskNotice": "包含高危权限,启用前需确认", "pluginViewLog": "查看日志", "pluginInUse": "使用中不可卸载", + "pluginDisable": "停用", + "pluginDisableInUseTitle": "停用仍有虚拟机的插件", + "pluginDisableInUseBody": "停用后,这个插件管理的虚拟机会显示为「驱动不可用」,不能启动或修改。虚拟机文件不会删除,重新启用即可恢复。运行中的虚拟机需要先停止。", "pluginRemove": "卸载", "pluginThemeSection": "主题扩展", "pluginActiveTheme": "当前主题包", From c8b792b3161a2c7ac4b958380bd16722dfe2c208 Mon Sep 17 00:00:00 2001 From: Dnyo666 Date: Tue, 1 Dec 2026 17:26:11 +0800 Subject: [PATCH 31/42] feat(ui,docs): add Discord community link to About page and READMEs - Add a Discord community entry with open-in-browser and copy-invite actions to AboutPage - Add zh-CN and en-US i18n strings for the Discord entry and regenerate settings/key catalogs - Add Discord and QQ group badges, nav anchors, and community sections to README.md and README.en.md --- README.en.md | 10 +++++++++- README.md | 10 +++++++++- frontend/src/components/AboutPage.tsx | 22 +++++++++++++++++++++- frontend/src/i18n/domains/settings.gen.ts | 8 ++++++++ frontend/src/i18n/keys.gen.ts | 4 ++++ locales/en-US/settings.json | 4 ++++ locales/zh-CN/settings.json | 4 ++++ 7 files changed, 59 insertions(+), 3 deletions(-) diff --git a/README.en.md b/README.en.md index 34753d6..5d09de3 100644 --- a/README.en.md +++ b/README.en.md @@ -17,6 +17,8 @@ release GitHub stars license Apache-2.0 + Discord + QQ Group 1136042744 @@ -32,7 +34,8 @@ Download · Quick Start · Screenshots · - Roadmap + Roadmap · + Community

@@ -155,6 +158,11 @@ The binary is written to `build\bin\reims-go.exe`. +## Community + +- **Discord**: [Join the Discord server](https://discord.gg/Tj682rW5rS) — Bilingual chat, troubleshooting, hardware compatibility reports, alpha testing and plugin development +- **QQ Group**: [1136042744](https://qm.qq.com/q/TBmRJlVbSo) — Chinese community chat and feedback + ## License & Notice - Reims-Go is licensed under [Apache-2.0](./LICENSE). Runtime components such as QEMU ship as separate programs; their licenses are in [`NOTICE.md`](./NOTICE.md), and every runtime release includes the matching source. diff --git a/README.md b/README.md index 907b9d7..fa559cc 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,8 @@ release GitHub stars license Apache-2.0 + Discord + QQ 交流群 1136042744 @@ -32,7 +34,8 @@ 下载 · 快速开始 · 界面 · - 路线图 + 路线图 · + 社区交流

@@ -155,6 +158,11 @@ wails build +## 社区交流 + +- **Discord 社区**:[加入 Discord 服务器](https://discord.gg/Tj682rW5rS) — 中英双语交流、排障求助、硬件兼容性实测、Alpha 测试与插件开发 +- **QQ 交流群**:[1136042744](https://qm.qq.com/q/TBmRJlVbSo) — 中文日常交流与使用反馈 + ## 许可与声明 - Reims-Go 采用 [Apache-2.0](./LICENSE) 协议。运行时里的 QEMU 等组件作为独立程序随附,许可证见 [`NOTICE.md`](./NOTICE.md),每个运行时 Release 都附带对应源码。 diff --git a/frontend/src/components/AboutPage.tsx b/frontend/src/components/AboutPage.tsx index e37a683..3f06d55 100644 --- a/frontend/src/components/AboutPage.tsx +++ b/frontend/src/components/AboutPage.tsx @@ -11,6 +11,7 @@ import { api } from '../wails' import { REPO_URL } from './TitleMenus' import type { UpdatePhase } from './UpdateCapsule' +const DISCORD_INVITE_URL = 'https://discord.gg/Tj682rW5rS' const QQ_GROUP_ID = '1136042744' export type AppUpdateChannel = 'stable' | 'alpha' | 'dev' @@ -34,7 +35,7 @@ interface Props { onError: (title: string, e: unknown) => void } -/** About page: version and updates, project links and the community group. */ +/** About page: version and updates, project links and community channels. */ export const AboutPage: React.FC = ({ locale, appVersion, appUpdateChannel, onAppUpdateChannel, appUpdate, onAppUpdate, updatePhase, updateTask, installing, onDownloadUpdate, onCancelUpdate, onInstallUpdate, onCopy, onError, @@ -252,6 +253,25 @@ export const AboutPage: React.FC = ({

+
+
+
{tr('aboutDiscord')}
+
{tr('aboutDiscordSub')}
+
+
+ {onCopy && ( +
+
diff --git a/frontend/src/i18n/domains/settings.gen.ts b/frontend/src/i18n/domains/settings.gen.ts index 3a65bcd..f6ce213 100644 --- a/frontend/src/i18n/domains/settings.gen.ts +++ b/frontend/src/i18n/domains/settings.gen.ts @@ -3,8 +3,12 @@ import { registerBuiltinDomain } from '../runtime' export const settingsZh: Record = { "aboutCommunity": "社区与支持", + "aboutCopyDiscord": "复制邀请链接", "aboutCopyQQGroup": "复制群号", + "aboutDiscord": "Discord 社区", + "aboutDiscordSub": "交流使用体验、硬件兼容反馈、Alpha 测试与插件开发", "aboutIssueSub": "遇到问题或有功能建议,在 GitHub 提交 Issue", + "aboutJoinDiscord": "加入服务器", "aboutJoinQQGroup": "加入群聊", "aboutLicensesOpenGitHub": "在 GitHub 查看", "aboutLicensesSub": "Apache-2.0 协议与第三方开源组件声明(离线可查)", @@ -320,8 +324,12 @@ export const settingsZh: Record = { export const settingsEn: Record = { "aboutCommunity": "Community \u0026 support", + "aboutCopyDiscord": "Copy invite link", "aboutCopyQQGroup": "Copy group ID", + "aboutDiscord": "Discord community", + "aboutDiscordSub": "Chat with users, share hardware compatibility, test alphas and build plugins", "aboutIssueSub": "Report a problem or suggest a feature on GitHub", + "aboutJoinDiscord": "Join server", "aboutJoinQQGroup": "Join group", "aboutLicensesOpenGitHub": "View on GitHub", "aboutLicensesSub": "Apache-2.0 license and third-party notices (available offline)", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 9ee8854..ba75466 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -2,8 +2,12 @@ export type I18nKey = | "aboutCommunity" + | "aboutCopyDiscord" | "aboutCopyQQGroup" + | "aboutDiscord" + | "aboutDiscordSub" | "aboutIssueSub" + | "aboutJoinDiscord" | "aboutJoinQQGroup" | "aboutLicensesOpenGitHub" | "aboutLicensesSub" diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index cf32f40..011201c 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -74,6 +74,10 @@ "appCheckUpdate": "Check for updates", "appDownloadUpdate": "Download", "appUpdateLookupFailed": "Couldn’t check GitHub for updates", + "aboutDiscord": "Discord community", + "aboutDiscordSub": "Chat with users, share hardware compatibility, test alphas and build plugins", + "aboutCopyDiscord": "Copy invite link", + "aboutJoinDiscord": "Join server", "aboutQQGroup": "QQ Group", "aboutQQGroupSub": "Launch QQ directly to join for community support and feedback", "aboutQQNotInstalled": "QQ not installed", diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index e46c6aa..209270e 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -74,6 +74,10 @@ "appCheckUpdate": "检查更新", "appDownloadUpdate": "前往下载", "appUpdateLookupFailed": "暂时无法连接 GitHub 检查更新", + "aboutDiscord": "Discord 社区", + "aboutDiscordSub": "交流使用体验、硬件兼容反馈、Alpha 测试与插件开发", + "aboutCopyDiscord": "复制邀请链接", + "aboutJoinDiscord": "加入服务器", "aboutQQGroup": "QQ 交流群", "aboutQQGroupSub": "点击直接拉起 QQ 加群,交流使用与问题反馈", "aboutQQNotInstalled": "未安装 QQ", From 6bac79b34682c3e8b9cbc0cdedf78b61d9628054 Mon Sep 17 00:00:00 2001 From: Dnyo666 Date: Tue, 1 Dec 2026 17:54:02 +0800 Subject: [PATCH 32/42] fix(ui): prevent previous titlebar menu from flashing on switch Scope `.menu` and `.tooltip` enter animations to their open data-state selectors and explicitly set `animation: none` on `[data-state="closed"]` so Radix Presence unmounts closing menus immediately instead of replaying `menu-in` for 160ms when `data-menubar-switch` is removed during a sibling switch. Also keep `data-menubar-switch` active across the switch frame, narrow `onPointerDownOutside` to sibling menu buttons so clicks in the gap still dismiss, fix `prefers-reduced-motion` close animations (adding `fade-out` for closing toasts), and add a static guard in `test-i18n.mjs`. --- frontend/scripts/test-i18n.mjs | 39 ++++++++++++++++++++++++++ frontend/src/components/TitleMenus.tsx | 7 +++-- frontend/src/styles/app.css | 18 ++++++++---- 3 files changed, 56 insertions(+), 8 deletions(-) diff --git a/frontend/scripts/test-i18n.mjs b/frontend/scripts/test-i18n.mjs index 6539187..fea549e 100644 --- a/frontend/scripts/test-i18n.mjs +++ b/frontend/scripts/test-i18n.mjs @@ -137,6 +137,45 @@ test('Static Guard (CRITICAL-2): every stack-*, notice-*, error-boundary*, and t } }) +test('Static Guard (CRITICAL-3): Radix Presence .menu/.tooltip animations never replay on close', () => { + const css = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8') + const titleMenus = fs.readFileSync(path.join(srcDir, 'components', 'TitleMenus.tsx'), 'utf8') + + // Unconditional `.menu { ... animation: ... }` causes Radix Presence to detect an + // animationName change (`none` -> `menu-in`) when `data-menubar-switch` is removed on close, + // suspending unmount and flashing the previous menu for 160ms. + assert.doesNotMatch( + css, + /\.menu\s*\{[^}]*animation\s*:/, + 'Enter animation on .menu must be scoped to .menu[data-state="open"]', + ) + assert.match( + css, + /\.menu\[data-state="open"\]\s*\{[^}]*animation\s*:/, + '.menu[data-state="open"] must define the menu enter animation', + ) + assert.match( + css, + /\.menu\[data-state="closed"\]\s*\{[^}]*animation\s*:\s*none/, + '.menu[data-state="closed"] must explicitly disable animation so Radix Presence unmounts immediately', + ) + assert.doesNotMatch( + css, + /\.tooltip\s*\{[^}]*animation\s*:/, + 'Enter animation on .tooltip must be scoped to .tooltip[data-state="delayed-open"]', + ) + assert.match( + css, + /\.tooltip\[data-state="closed"\]\s*\{[^}]*animation\s*:\s*none/, + '.tooltip[data-state="closed"] must explicitly disable animation', + ) + assert.doesNotMatch( + titleMenus, + /data-menubar-switch=\{\s*menuState\.id\s*===\s*id\s*&&\s*menuState\.switched/, + 'TitleMenus must not strip data-menubar-switch from the outgoing sibling menu on switch', + ) +}) + test('Runtime i18n v2: ICU formatting, ghost-locale isolation (H-3), parseAppError (HIGH-2), RTL (L-2), and en-XA', async () => { const mod = await loadBundledTS(` import './i18n/domains/wizard.gen' diff --git a/frontend/src/components/TitleMenus.tsx b/frontend/src/components/TitleMenus.tsx index 477d11b..58f0f6b 100644 --- a/frontend/src/components/TitleMenus.tsx +++ b/frontend/src/components/TitleMenus.tsx @@ -146,7 +146,7 @@ export const TitleMenus: React.FC = ({ = ({ pointerClosedRef.current = false }} onPointerDownOutside={(e) => { - const target = e.target as Node | null - if (target && navRef.current?.contains(target)) { + const target = e.target instanceof Element ? e.target : (e.target as Node | null)?.parentElement ?? null + const trigger = target?.closest('button.titlebar-menu') ?? null + if (trigger && navRef.current?.contains(trigger)) { e.preventDefault() return } diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 6710013..08c14fd 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -1323,6 +1323,7 @@ button.status-issue + .status-metric { margin-left: 6px; } /* ── Motion (emil-design-eng & apple-design) ───────────── */ @keyframes rise-in { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } } @keyframes fade-in { from { opacity: 0; } to { opacity: 1; } } +@keyframes fade-out { from { opacity: 1; } to { opacity: 0; } } @keyframes pop-in { from { opacity: 0; transform: translate(-50%, -49%) scale(0.96); } to { opacity: 1; transform: translate(-50%, -50%) scale(1); } } @keyframes menu-in { from { opacity: 0; transform: scale(0.96); } to { opacity: 1; transform: scale(1); } } @keyframes tip-in { from { opacity: 0; transform: scale(0.96); } to { opacity: 1; transform: scale(1); } } @@ -1334,10 +1335,13 @@ button.status-issue + .status-metric { margin-left: 6px; } .page { animation: rise-in var(--dur) var(--ease-out) both; } .overlay { animation: fade-in var(--dur) var(--ease-out) both; } .dialog { animation: pop-in var(--dur-modal) var(--ease-out) both; } -.menu { transform-origin: var(--radix-dropdown-menu-content-transform-origin, top); animation: menu-in 160ms var(--ease-out) both; } -.menu[data-menubar-switch="true"] { animation: none; } -.tooltip { animation: tip-in 125ms var(--ease-out) both; } -.tooltip[data-state="instant-open"] { animation-duration: 0ms; } +.menu { transform-origin: var(--radix-dropdown-menu-content-transform-origin, top); } +.menu[data-state="open"] { animation: menu-in 160ms var(--ease-out) both; } +.menu[data-state="open"][data-menubar-switch="true"], +.menu[data-state="closed"] { animation: none; } +.tooltip[data-state="delayed-open"] { animation: tip-in 125ms var(--ease-out) both; } +.tooltip[data-state="instant-open"], +.tooltip[data-state="closed"] { animation: none; } .pane-anim { display: flex; flex-direction: column; gap: 20px; animation: rise-in var(--dur) var(--ease-out) both; } .step-anim { display: flex; flex-direction: column; gap: var(--sp-4); animation: rise-in var(--dur) var(--ease-out) both; } @@ -1488,10 +1492,14 @@ button.status-issue + .status-metric { margin-left: 6px; } .status-busy, .vm-screen-live, .skeleton-bar { animation: none; } .vm-display-unit, .vm-display-unit.is-actionable:hover, .vm-display-unit.is-actionable:active { transform: none; } .vm-screen-img, .vm-spec-meter .meter-fill { transition: none; } - .page, .dialog, .menu, .tooltip, .pane-anim, .step-anim, .toast[data-state="open"], .toast[data-state="closed"] { + .page, .dialog, .menu[data-state="open"]:not([data-menubar-switch="true"]), .tooltip[data-state="delayed-open"], .pane-anim, .step-anim, .toast[data-state="open"] { animation-name: fade-in; animation-duration: 140ms; } + .toast[data-state="closed"] { + animation-name: fade-out; + animation-duration: 140ms; + } } /* ── v0.2.6 Enhancements: Screenshot, Note, Dropzone, Snapshots, Log Filter, Welcome ── */ From 8721f3de703c6281eb28fe747698659302ec9389 Mon Sep 17 00:00:00 2001 From: Dnyo666 Date: Tue, 1 Dec 2026 18:47:22 +0800 Subject: [PATCH 33/42] perf(ui): eliminate software-compositing modal lag and harden UI responsiveness Remove backdrop-filter from software-composited overlays/dialogs under WebviewGpuIsDisabled: true, preload license text before mounting the modal, fix short-viewport double scrollbars and narrow-screen row wrapping, restore keyboard focus on modal close, wire RTL direction to Radix menus, add ArrowUp/ArrowDown support and signature-based layout measurement in Segmented, and harden CRITICAL-3/CRITICAL-4 static guards. --- frontend/scripts/test-i18n.mjs | 75 +++++++++++--- frontend/src/App.tsx | 7 +- frontend/src/components/AboutPage.tsx | 55 +++++++--- frontend/src/components/Sidebar.tsx | 4 +- frontend/src/components/TitleMenus.tsx | 6 +- frontend/src/components/VMPage.tsx | 4 +- frontend/src/styles/app.css | 81 +++++++++------ frontend/src/styles/tokens.css | 14 +-- frontend/src/ui/dialog.tsx | 138 +++++++++++++++---------- frontend/src/ui/settings.tsx | 13 ++- 10 files changed, 264 insertions(+), 133 deletions(-) diff --git a/frontend/scripts/test-i18n.mjs b/frontend/scripts/test-i18n.mjs index fea549e..953d47d 100644 --- a/frontend/scripts/test-i18n.mjs +++ b/frontend/scripts/test-i18n.mjs @@ -138,17 +138,30 @@ test('Static Guard (CRITICAL-2): every stack-*, notice-*, error-boundary*, and t }) test('Static Guard (CRITICAL-3): Radix Presence .menu/.tooltip animations never replay on close', () => { - const css = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8') + const rawCss = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8') + const css = rawCss.replace(/\/\*[\s\S]*?\*\//g, '') const titleMenus = fs.readFileSync(path.join(srcDir, 'components', 'TitleMenus.tsx'), 'utf8') - // Unconditional `.menu { ... animation: ... }` causes Radix Presence to detect an - // animationName change (`none` -> `menu-in`) when `data-menubar-switch` is removed on close, - // suspending unmount and flashing the previous menu for 160ms. - assert.doesNotMatch( - css, - /\.menu\s*\{[^}]*animation\s*:/, - 'Enter animation on .menu must be scoped to .menu[data-state="open"]', - ) + // Unconditional `.menu` / `.tooltip` animation (including animation-name inside + // comma-separated selector lists or reduced-motion media queries) causes Radix + // Presence to detect an animationName change on close and flash for 160ms. + for (const m of css.matchAll(/([^{}@]+)\{([^{}]+)\}/g)) { + const selectors = m[1].split(',').map((s) => s.trim()).filter(Boolean) + const decls = m[2] + if (!/\banimation(?:-name)?\s*:(?!\s*none\b)/.test(decls)) continue + for (const sel of selectors) { + assert.doesNotMatch( + sel, + /\.menu(?![a-zA-Z0-9_-])(?!\[data-state="open"\])/, + `Non-open .menu selector "${sel}" must not apply an active animation`, + ) + assert.doesNotMatch( + sel, + /\.tooltip(?![a-zA-Z0-9_-])(?!\[data-state="delayed-open"\])/, + `Non-delayed-open .tooltip selector "${sel}" must not apply an active animation`, + ) + } + } assert.match( css, /\.menu\[data-state="open"\]\s*\{[^}]*animation\s*:/, @@ -156,19 +169,24 @@ test('Static Guard (CRITICAL-3): Radix Presence .menu/.tooltip animations never ) assert.match( css, - /\.menu\[data-state="closed"\]\s*\{[^}]*animation\s*:\s*none/, - '.menu[data-state="closed"] must explicitly disable animation so Radix Presence unmounts immediately', - ) - assert.doesNotMatch( - css, - /\.tooltip\s*\{[^}]*animation\s*:/, - 'Enter animation on .tooltip must be scoped to .tooltip[data-state="delayed-open"]', + /\.menu\[data-state="open"\]\[data-menubar-switch="true"\][^\{]*\{[^}]*animation\s*:\s*none/, + '.menu[data-state="open"][data-menubar-switch="true"] must disable enter animation', ) assert.match( css, - /\.tooltip\[data-state="closed"\]\s*\{[^}]*animation\s*:\s*none/, + /\.menu\[data-state="closed"\][^\{]*\{[^}]*animation\s*:\s*none/, + '.menu[data-state="closed"] must explicitly disable animation so Radix Presence unmounts immediately', + ) + assert.match( + css, + /\.tooltip\[data-state="closed"\][^\{]*\{[^}]*animation\s*:\s*none/, '.tooltip[data-state="closed"] must explicitly disable animation', ) + assert.match( + css, + /@media\s*\(\s*prefers-reduced-motion\s*:\s*reduce\s*\)\s*\{[\s\S]*?\.toast\[data-state="closed"\][^{]*\{[^}]*animation-name\s*:\s*fade-out/, + 'Reduced-motion .toast[data-state="closed"] must use fade-out', + ) assert.doesNotMatch( titleMenus, /data-menubar-switch=\{\s*menuState\.id\s*===\s*id\s*&&\s*menuState\.switched/, @@ -176,6 +194,29 @@ test('Static Guard (CRITICAL-3): Radix Presence .menu/.tooltip animations never ) }) +test('Static Guard (CRITICAL-4): software-composited UI avoids backdrop-filter and slow pre shaping', () => { + const rawCss = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8') + const css = rawCss.replace(/\/\*[\s\S]*?\*\//g, '') + + // main.go sets WebviewGpuIsDisabled: true (software compositing), where + // backdrop-filter blurs stall CPU rasterization on animations and scrolling. + assert.doesNotMatch( + css, + /(?:-webkit-)?backdrop-filter\s*:/i, + 'app.css must not apply backdrop-filter under software compositing', + ) + assert.match( + css, + /\.license-pre\s*\{[^}]*contain\s*:\s*content/, + '.license-pre should isolate scroll/layout repaints with contain: content', + ) + assert.match( + css, + /\.license-pre\s*\{[^}]*text-rendering\s*:\s*auto/, + '.license-pre should opt out of global optimizeLegibility for long monospace texts', + ) +}) + test('Runtime i18n v2: ICU formatting, ghost-locale isolation (H-3), parseAppError (HIGH-2), RTL (L-2), and en-XA', async () => { const mod = await loadBundledTS(` import './i18n/domains/wizard.gen' diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index b3e9a8a..6090715 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1044,7 +1044,12 @@ export const App: React.FC = () => { selected={selected} hostReady={hostReady} canSuspend={canSuspend} - onSelect={setSelected} + onSelect={(id) => { + setSelected(id) + if (sidebarOpen && window.matchMedia('(max-width: 768px)').matches) { + toggleSidebar() + } + }} displayNames={displayNames} macosMajors={macosMajors} onActivate={primaryAction} diff --git a/frontend/src/components/AboutPage.tsx b/frontend/src/components/AboutPage.tsx index 3f06d55..2b919ee 100644 --- a/frontend/src/components/AboutPage.tsx +++ b/frontend/src/components/AboutPage.tsx @@ -1,5 +1,5 @@ import { Copy, Download, ExternalLink, RotateCw, Scale } from 'lucide-react' -import React, { useEffect, useState } from 'react' +import React, { useEffect, useRef, useState } from 'react' import '../i18n/domains/settings.gen' import { I18nKey, t } from '../i18n' import { taskDetail } from '../lib/tasks' @@ -50,14 +50,34 @@ export const AboutPage: React.FC = ({ const [licenseOpen, setLicenseOpen] = useState(false) const [licenseTab, setLicenseTab] = useState<'notice' | 'license'>('notice') const [licenses, setLicenses] = useState<{ license: string; notice: string } | null>(null) + const mountedRef = useRef(true) + const loadingLicensesRef = useRef(false) + const licensePreRef = useRef(null) - const openLicenses = () => { - setLicenseOpen(true) - if (!licenses) { - api.GetLicenseTexts() - .then((res) => setLicenses({ license: res?.license ?? '', notice: res?.notice ?? '' })) - .catch((e) => onError(tr('failGeneric'), e)) + const openLicenses = async () => { + if (licenses) { + setLicenseOpen(true) + return } + if (loadingLicensesRef.current) return + loadingLicensesRef.current = true + try { + // Load embedded license text before mounting the modal so the dialog opens + // with its final content on frame 1 instead of reflowing mid-animation. + const res = await api.GetLicenseTexts() + if (!mountedRef.current) return + setLicenses({ license: res?.license ?? '', notice: res?.notice ?? '' }) + setLicenseOpen(true) + } catch (e) { + if (mountedRef.current) onError(tr('failGeneric'), e) + } finally { + loadingLicensesRef.current = false + } + } + + const handleLicenseTabChange = (next: 'notice' | 'license') => { + setLicenseTab(next) + if (licensePreRef.current) licensePreRef.current.scrollTop = 0 } const runUpdateCheck = async (force: boolean) => { @@ -73,12 +93,16 @@ export const AboutPage: React.FC = ({ } useEffect(() => { + mountedRef.current = true if (!appUpdate) void runUpdateCheck(false) let cancelled = false api.CanOpenQQGroup() .then((ok) => { if (!cancelled) setQQInstalled(!!ok) }) .catch(() => { if (!cancelled) setQQInstalled(false) }) - return () => { cancelled = true } + return () => { + mountedRef.current = false + cancelled = true + } }, []) const openURL = (url: string) => { @@ -245,7 +269,7 @@ export const AboutPage: React.FC = ({
{tr('aboutLicensesSub')}
-
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index 850dc2e..f71bf72 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -1,7 +1,7 @@ import * as Ctx from '@radix-ui/react-context-menu' import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Maximize2, Pause, Play, Plus, Power, Puzzle, RotateCw, Settings, Square, Trash } from 'lucide-react' import React, { useRef } from 'react' -import { I18nKey, t } from '../i18n' +import { I18nKey, localeDir, t } from '../i18n' import { Locale, VMListItem } from '../types' import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls' import { VersionArt } from './VersionArt' @@ -136,7 +136,7 @@ export const Sidebar: React.FC = ({ ) if (!onVMContextAction) return trigger return ( - + { diff --git a/frontend/src/components/TitleMenus.tsx b/frontend/src/components/TitleMenus.tsx index 58f0f6b..4136358 100644 --- a/frontend/src/components/TitleMenus.tsx +++ b/frontend/src/components/TitleMenus.tsx @@ -1,7 +1,7 @@ import * as Menu from '@radix-ui/react-dropdown-menu' import { Check, PanelLeft } from 'lucide-react' import React, { useRef, useState } from 'react' -import { I18nKey, t } from '../i18n' +import { I18nKey, localeDir, t } from '../i18n' import { useVMStats } from '../lib/vmStats' import { Locale } from '../types' import { Tip } from '../ui/controls' @@ -90,6 +90,7 @@ export const TitleMenus: React.FC = ({ // `indented`: the menu has check marks, so every row shares their indent. const menu = (id: MenuId, label: string, content: React.ReactNode, indented = false) => ( { @@ -159,9 +160,10 @@ export const TitleMenus: React.FC = ({ pointerClosedRef.current = false }} onPointerDownOutside={(e) => { + const orig = e.detail.originalEvent const target = e.target instanceof Element ? e.target : (e.target as Node | null)?.parentElement ?? null const trigger = target?.closest('button.titlebar-menu') ?? null - if (trigger && navRef.current?.contains(trigger)) { + if (orig.button === 0 && !orig.ctrlKey && trigger && navRef.current?.contains(trigger)) { e.preventDefault() return } diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index 01f16df..c24604b 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -42,7 +42,7 @@ import { UserRound, } from 'lucide-react' import React, { useEffect, useId, useRef, useState } from 'react' -import { I18nKey, locText, t } from '../i18n' +import { I18nKey, localeDir, locText, t } from '../i18n' import { controllerLabel, formatBytes, formatDiskUsage, formatMemory, formatUptime, graphicsLabel, parseMemoryGB, pendingChangeText, resolveGuestLang, sshCommand, @@ -388,6 +388,7 @@ export const VMPage: React.FC = ({ // "More" menu, grouped by purpose; destructive items last (docs/design-guidelines.md §5.2). const menu = ( { if (o) morePointerClosed.current = false @@ -979,6 +980,7 @@ export const VMPage: React.FC = ({ {tr('sshOpenTerminal')} { if (o) sshPointerClosed.current = false diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 08c14fd..5467901 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -82,15 +82,15 @@ h1, h2, h3, p { margin: 0; } /* Left of the title bar: sidebar toggle + a small menu bar. Controls and the menu bar group opt out of window dragging so sweeping across menus stays smooth. */ -.titlebar-left { display: flex; align-items: center; gap: 2px; height: 100%; margin-left: calc(var(--sp-2) * -1); } +.titlebar-left { display: flex; align-items: center; gap: 2px; height: 100%; min-width: 0; margin-inline-start: calc(var(--sp-2) * -1); } .titlebar-icon, .titlebar-menu { --wails-draggable: no-drag; height: 28px; border: none; border-radius: var(--r-sm); background: transparent; color: var(--text-2); cursor: pointer; transition: background var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), transform var(--dur-press) var(--ease-out); } -.titlebar-icon { width: 32px; display: grid; place-items: center; margin-right: 4px; } -.titlebar-menu { padding: 0 10px; font-size: var(--fs-13); font-weight: var(--fw-medium); } +.titlebar-icon { width: 32px; display: grid; place-items: center; margin-inline-end: 4px; flex-shrink: 0; } +.titlebar-menu { padding: 0 10px; font-size: var(--fs-13); font-weight: var(--fw-medium); white-space: nowrap; flex-shrink: 0; } .titlebar-icon:hover, .titlebar-menu:hover { background: var(--surface-hover); color: var(--text); } .titlebar-menu[data-state="open"] { background: var(--surface-active); color: var(--text); } .titlebar-icon:active, .titlebar-menu:active { transform: scale(0.96); } @@ -100,7 +100,7 @@ h1, h2, h3, p { margin: 0; } /* Menu rows with a trailing shortcut, check marks and group labels. */ .menu-label { flex: 1; min-width: 0; white-space: nowrap; } .menu-shortcut { - margin-left: 24px; font-family: var(--font-sans); font-size: var(--fs-12); + margin-inline-start: 24px; font-family: var(--font-sans); font-size: var(--fs-12); color: var(--text-3); font-variant-numeric: tabular-nums; } .menu-item[data-highlighted] .menu-shortcut { color: rgba(255, 255, 255, 0.78); } @@ -109,7 +109,7 @@ h1, h2, h3, p { margin: 0; } .menu-check { position: absolute; inset-inline-start: 9px; top: 50%; transform: translateY(-50%); display: grid; place-items: center; } .menu-group-label { padding: 6px 10px 2px; font-size: 11.5px; font-weight: var(--fw-medium); color: var(--text-3); user-select: none; } .theme-toggle { - width: 30px; height: 28px; margin-right: var(--sp-1); + width: 30px; height: 28px; margin-inline-end: var(--sp-1); border: 1px solid var(--border); border-radius: var(--r-md); background: var(--surface-1); color: var(--text-2); display: grid; place-items: center; cursor: pointer; @@ -138,11 +138,16 @@ h1, h2, h3, p { margin: 0; } display: flex; overflow: hidden; background: var(--surface-sidebar-rail); border-inline-end: 1px solid var(--border); - transition: width var(--dur-modal) var(--ease-out), padding var(--dur-modal) var(--ease-out), opacity var(--dur) var(--ease-out), border-color var(--dur) var(--ease-out); + transition: width var(--dur-modal) var(--ease-out), padding var(--dur-modal) var(--ease-out), opacity var(--dur) var(--ease-out), border-color var(--dur) var(--ease-out), visibility 0s linear 0s; } /* Hidden sidebar (Ctrl+B): slides shut; the card keeps its width so its - contents don't reflow while the rail narrows. */ -.workspace.sidebar-hidden .sidebar-wrap { width: 0; padding-inline: 0; opacity: 0; border-inline-end-color: transparent; } + contents don't reflow while the rail narrows, and visibility: hidden removes + off-screen buttons from the keyboard Tab order. */ +.workspace.sidebar-hidden .sidebar-wrap { + width: 0; padding-inline: 0; opacity: 0; border-inline-end-color: transparent; + visibility: hidden; pointer-events: none; + transition: width var(--dur-modal) var(--ease-out), padding var(--dur-modal) var(--ease-out), opacity var(--dur) var(--ease-out), border-color var(--dur) var(--ease-out), visibility 0s linear var(--dur-modal); +} .sidebar-wrap > .sidebar { min-width: calc(var(--sidebar-w) - 20px); } .sidebar { flex: 1; min-height: 0; @@ -716,11 +721,14 @@ h1, h2, h3, p { margin: 0; } .about-hero-text h1 { font-size: 22px; font-weight: var(--fw-strong); letter-spacing: -0.02em; color: var(--text); } .about-hero-text p { margin: 0; font-size: var(--fs-13); color: var(--text-2); line-height: 1.5; } .license-modal-body { gap: var(--sp-3); } +.license-modal-body > .seg { align-self: flex-start; flex-shrink: 0; } .license-pre { - margin: 0; padding: 14px 16px; min-height: 260px; max-height: 52vh; overflow: auto; + margin: 0; padding: 14px 16px; flex: 0 1 auto; height: min(440px, 50vh); min-height: 120px; overflow: auto; + overscroll-behavior: contain; contain: content; border-radius: var(--r-md); border: 1px solid var(--border); background: var(--surface-1); font-family: var(--font-mono); font-size: var(--fs-12); line-height: 1.55; color: var(--text-2); white-space: pre-wrap; word-break: break-word; user-select: text; + text-rendering: auto; text-autospace: no-autospace; } .section-count { min-width: 20px; padding: 1px 7px; border-radius: 999px; background: var(--surface-active); color: var(--text-3); font-size: 11px; font-weight: var(--fw-medium); text-align: center; } .installer-row { min-height: 62px; } @@ -886,6 +894,7 @@ button.status-issue + .status-metric { margin-left: 6px; } overflow-y: auto; overscroll-behavior: contain; padding: var(--sp-2) var(--sp-4); font-family: var(--font-mono); font-size: var(--fs-12); line-height: 1.6; color: var(--text-code); white-space: pre-wrap; word-break: break-word; user-select: text; + text-rendering: auto; text-autospace: no-autospace; } .log-line { display: flex; gap: var(--sp-3); } .log-ts { color: var(--text-3); flex-shrink: 0; font-variant-numeric: tabular-nums; } @@ -895,27 +904,30 @@ button.status-issue + .status-metric { margin-left: 6px; } .jump-latest { position: absolute; inset-inline-end: var(--sp-4); bottom: var(--sp-3); } /* ── Overlays: dialog, menu, tooltip, toast ────────────── */ -.overlay { position: fixed; inset: 0; background: var(--scrim); backdrop-filter: blur(5px); z-index: 40; } +/* No backdrop-filter: main.go sets WebviewGpuIsDisabled: true (software + compositing), where per-frame CPU Gaussian blur over modals/overlays stutters + badly during enter animations and inner scrolling. */ +.overlay { position: fixed; inset: 0; background: var(--scrim); z-index: 40; } .dialog { position: fixed; z-index: 41; left: 50%; top: 50%; transform: translate(-50%, -50%); width: 720px; max-width: calc(100vw - 48px); max-height: calc(100vh - 80px); display: flex; flex-direction: column; overflow: hidden; - background: var(--surface-2); backdrop-filter: var(--blur-overlay); + background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-xl); box-shadow: var(--shadow-overlay), var(--highlight-top); } .dialog.sm { width: 420px; } -.dialog-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); padding: 14px 14px 14px 22px; border-bottom: 1px solid var(--border); } +.dialog-head { flex-shrink: 0; display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); padding-block: 14px; padding-inline: 22px 14px; border-bottom: 1px solid var(--border); } .dialog-title { font-size: var(--fs-16); font-weight: var(--fw-strong); letter-spacing: -0.01em; text-wrap: balance; } .dialog-desc { font-size: var(--fs-13); color: var(--text-2); margin-top: 2px; } .dialog-body { padding: 20px 22px; overflow-y: auto; overscroll-behavior: contain; flex: 1; display: flex; flex-direction: column; gap: var(--sp-4); } -.dialog-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); padding: 12px 22px; border-top: 1px solid var(--border); } +.dialog-foot { flex-shrink: 0; display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--sp-2); padding: 12px 22px; border-top: 1px solid var(--border); } .dialog.sm .dialog-body { padding: 22px 22px 14px; gap: var(--sp-3); } .dialog.sm .dialog-foot { border-top: none; justify-content: flex-end; padding-top: 0; padding-bottom: 20px; } .menu { min-width: 188px; padding: 5px; z-index: 50; - background: var(--surface-2); backdrop-filter: var(--blur-overlay); + background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-lg); box-shadow: var(--shadow-overlay), var(--highlight-top); } @@ -936,7 +948,7 @@ button.status-issue + .status-metric { margin-left: 6px; } .tooltip { z-index: 60; padding: 5px 9px; border-radius: var(--r-sm); - background: var(--surface-2); backdrop-filter: var(--blur-overlay); + background: var(--surface-2); border: 1px solid var(--border-strong); color: var(--text); font-size: var(--fs-12); box-shadow: 0 8px 22px rgba(15, 23, 42, 0.16); display: flex; gap: var(--sp-2); align-items: center; @@ -947,7 +959,7 @@ button.status-issue + .status-metric { margin-left: 6px; } .toast-viewport { position: fixed; inset-inline-end: var(--sp-4); bottom: calc(var(--logbar-h) + var(--sp-4)); z-index: 70; display: flex; flex-direction: column; gap: var(--sp-2); width: 380px; max-width: calc(100vw - 32px); margin: 0; padding: 0; list-style: none; outline: none; } .toast { display: flex; flex-direction: column; gap: var(--sp-2); padding: var(--sp-3); - background: var(--surface-2); backdrop-filter: var(--blur-overlay); + background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-lg); box-shadow: var(--shadow-overlay), var(--highlight-top); } @@ -968,7 +980,7 @@ button.status-issue + .status-metric { margin-left: 6px; } .toast-title { font-size: var(--fs-13); font-weight: var(--fw-strong); } .toast-code { font-family: var(--font-mono); font-size: var(--fs-11); padding: 1px 5px; - border-radius: 4px; background: var(--surface-active); color: var(--text-3); + border-radius: 4px; background: var(--surface-active); color: var(--text-2); } .toast-desc { font-size: var(--fs-12); color: var(--text-2); overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical; overflow: hidden; } .toast-footer { display: flex; flex-direction: column; gap: var(--sp-2); padding-inline-start: 28px; width: 100%; min-width: 0; } @@ -1389,7 +1401,7 @@ button.status-issue + .status-metric { margin-left: 6px; } width: max-content; max-width: calc(100% - 20px); padding: 0 12px; display: inline-flex; align-items: center; justify-content: center; gap: 5px; height: 26px; border-radius: 999px; pointer-events: none; - background: rgba(20, 21, 26, 0.72); color: #fff; backdrop-filter: blur(10px); + background: rgba(20, 21, 26, 0.84); color: #fff; font-size: var(--fs-12); font-weight: var(--fw-medium); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; opacity: 0; transform: translateX(-50%) translateY(4px); @@ -1489,14 +1501,16 @@ button.status-issue + .status-metric { margin-left: 6px; } /* Reduced motion: stop decorative loops & positional motion */ @media (prefers-reduced-motion: reduce) { - .status-busy, .vm-screen-live, .skeleton-bar { animation: none; } + .status-busy, .vm-screen-live, .skeleton-bar, .market-progress.is-indeterminate .market-progress-fill { animation: none; } .vm-display-unit, .vm-display-unit.is-actionable:hover, .vm-display-unit.is-actionable:active { transform: none; } .vm-screen-img, .vm-spec-meter .meter-fill { transition: none; } .page, .dialog, .menu[data-state="open"]:not([data-menubar-switch="true"]), .tooltip[data-state="delayed-open"], .pane-anim, .step-anim, .toast[data-state="open"] { animation-name: fade-in; animation-duration: 140ms; } - .toast[data-state="closed"] { + .toast[data-state="closed"], + .toast[data-swipe="end"], + :root[dir="rtl"] .toast[data-swipe="end"] { animation-name: fade-out; animation-duration: 140ms; } @@ -1508,14 +1522,13 @@ button.status-issue + .status-metric { margin-left: 6px; } position: absolute; right: 8px; bottom: 8px; z-index: 3; width: 30px; height: 30px; border: 1px solid rgba(255, 255, 255, 0.22); border-radius: 8px; display: grid; place-items: center; cursor: pointer; - background: rgba(20, 22, 28, 0.68); color: #ffffff; - backdrop-filter: blur(10px); + background: rgba(20, 22, 28, 0.82); color: #ffffff; opacity: 0; transform: translateY(3px); transition: opacity var(--dur-fast) var(--ease-out), transform var(--dur-fast) var(--ease-out), background var(--dur-fast) var(--ease-out); } .vm-screen:hover .vm-screen-shot, .vm-screen-shot:focus-visible { opacity: 1; transform: translateY(0); } -.vm-screen-shot:hover { background: rgba(20, 22, 28, 0.88); } +.vm-screen-shot:hover { background: rgba(20, 22, 28, 0.94); } .vm-screen-shot:active { transform: scale(0.94); } /* The title is the display name; click to rename in place. The pencil hangs @@ -1569,9 +1582,8 @@ button.status-issue + .status-metric { margin-left: 6px; } position: sticky; top: 0; z-index: 20; display: flex; align-items: center; justify-content: center; gap: 8px; padding: 12px 16px; border-radius: var(--r-lg); - background: var(--accent-soft); border: 1.5px dashed var(--accent); + background: color-mix(in srgb, var(--surface-canvas) 89%, var(--accent)); border: 1.5px dashed var(--accent); color: var(--accent-soft-text); font-size: var(--fs-13); font-weight: var(--fw-medium); - backdrop-filter: var(--blur-overlay); } /* Interactive install stepper */ @@ -1839,7 +1851,7 @@ button.status-issue + .status-metric { margin-left: 6px; } } .plugin-risk.is-high .plugin-risk-icon { background: var(--warn-soft); color: var(--warn-text); } .plugin-scan-section { display: flex; flex-direction: column; gap: 6px; } -.plugin-scan-section-title { font-size: var(--fs-12); font-weight: var(--fw-semibold); color: var(--text-2); } +.plugin-scan-section-title { font-size: var(--fs-12); font-weight: var(--fw-strong); color: var(--text-2); } .plugin-scan-section-title.is-danger { color: var(--danger-text); } .plugin-scan-examples { margin-top: 4px; font-size: var(--fs-11); color: var(--text-2); display: flex; flex-direction: column; gap: 2px; } @@ -1905,6 +1917,7 @@ button.status-issue + .status-metric { margin-left: 6px; } max-height: 180px; overflow: auto; background: var(--surface-0); border: 1px solid var(--border); white-space: pre-wrap; word-break: break-word; + text-rendering: auto; text-autospace: no-autospace; } .error-boundary-actions { display: flex; gap: var(--sp-2); justify-content: flex-end; } @@ -1919,7 +1932,7 @@ button.status-issue + .status-metric { margin-left: 6px; } .sidebar-backdrop { display: block; position: absolute; inset: 0; - background: var(--scrim); backdrop-filter: blur(3px); z-index: 31; + background: var(--scrim); z-index: 31; } .sidebar-wrap { position: absolute; z-index: 32; @@ -1941,18 +1954,22 @@ button.status-issue + .status-metric { margin-left: 6px; } .settings-pane { padding: 16px; } } +@container (max-width: 520px) { + .row, .srow-head { flex-wrap: wrap; gap: var(--sp-2) var(--sp-4); } + .row-main, .srow-text { flex: 1 1 220px; } + .row-right, .srow-ctrl { flex-wrap: wrap; max-width: 100%; min-width: 0; } +} + @media (max-width: 640px) { .source-cards, .field-row, .review-groups { grid-template-columns: 1fr; } .review-group:last-child .review-rows { grid-template-columns: max-content 1fr; } .vm-spec-card { grid-template-columns: repeat(2, minmax(0, 1fr)); padding: 12px 14px; } .affinity-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } - .conn-row, .srow-head, .row, .page-head { flex-wrap: wrap; } - .conn-ctrl { flex-wrap: wrap; max-width: 100%; } + .conn-row, .srow-head, .row, .page-head { flex-wrap: wrap; gap: var(--sp-2) var(--sp-4); } + .row-main, .srow-text { flex: 1 1 220px; } + .conn-ctrl, .row-right, .srow-ctrl { flex-wrap: wrap; max-width: 100%; min-width: 0; } .plugins-search { width: 100%; } } -@container (max-width: 560px) { - .review-group:last-child .review-rows { grid-template-columns: max-content 1fr; } -} } diff --git a/frontend/src/styles/tokens.css b/frontend/src/styles/tokens.css index 7d588e2..b821444 100644 --- a/frontend/src/styles/tokens.css +++ b/frontend/src/styles/tokens.css @@ -90,17 +90,19 @@ --surface-statusbar: #eef3fa; --surface-1: #f5f6f8; --surface-card-elevated: #ffffff; - --surface-2: rgba(255, 255, 255, 0.94); + --surface-2: rgba(255, 255, 255, 0.98); --surface-input: #ffffff; --surface-hover: rgba(15, 23, 42, 0.048); --surface-active: rgba(15, 23, 42, 0.085); --border: rgba(15, 23, 42, 0.08); --border-strong: rgba(15, 23, 42, 0.14); --highlight-top: inset 0 1px 0 rgba(255, 255, 255, 0.85); - --scrim: rgba(15, 23, 42, 0.28); + --scrim: rgba(15, 23, 42, 0.34); --shadow-btn: 0 1px 2px rgba(15, 23, 42, 0.06), inset 0 1px 0 rgba(255, 255, 255, 0.7); --shadow-card: 0 1px 2px rgba(15, 23, 42, 0.025); - --shadow-overlay: 0 22px 58px rgba(15, 23, 42, 0.18), 0 4px 14px rgba(15, 23, 42, 0.06), 0 0 0 1px rgba(15, 23, 42, 0.06); + --shadow-overlay: 0 16px 36px rgba(15, 23, 42, 0.16), 0 3px 10px rgba(15, 23, 42, 0.06), 0 0 0 1px rgba(15, 23, 42, 0.06); + /* Retained for UI Contract v1 (uiApi 1.0.0) theme compatibility; unused by default + base styles while main.go runs WebView2 in software compositing mode. */ --blur-chrome: blur(20px) saturate(180%); --blur-overlay: blur(18px) saturate(165%); @@ -167,17 +169,17 @@ --surface-statusbar: #18191e; --surface-1: rgba(255, 255, 255, 0.048); --surface-card-elevated: rgba(255, 255, 255, 0.075); - --surface-2: rgba(42, 43, 50, 0.94); + --surface-2: rgba(42, 43, 50, 0.98); --surface-input: rgba(0, 0, 0, 0.28); --surface-hover: rgba(255, 255, 255, 0.075); --surface-active: rgba(255, 255, 255, 0.12); --border: rgba(255, 255, 255, 0.085); --border-strong: rgba(255, 255, 255, 0.16); --highlight-top: inset 0 1px 0 rgba(255, 255, 255, 0.08); - --scrim: rgba(0, 0, 0, 0.56); + --scrim: rgba(0, 0, 0, 0.58); --shadow-btn: 0 1px 2px rgba(0, 0, 0, 0.30), inset 0 1px 0 rgba(255, 255, 255, 0.06); --shadow-card: 0 1px 3px rgba(0, 0, 0, 0.18); - --shadow-overlay: 0 26px 68px rgba(0, 0, 0, 0.58), 0 0 0 1px rgba(255, 255, 255, 0.09); + --shadow-overlay: 0 18px 40px rgba(0, 0, 0, 0.52), 0 0 0 1px rgba(255, 255, 255, 0.09); --text: #f5f5f7; --text-2: #c2c2ca; diff --git a/frontend/src/ui/dialog.tsx b/frontend/src/ui/dialog.tsx index 16ddcdc..d8b6101 100644 --- a/frontend/src/ui/dialog.tsx +++ b/frontend/src/ui/dialog.tsx @@ -14,30 +14,44 @@ interface ConfirmDialogProps { children?: React.ReactNode } -export const ConfirmDialog: React.FC = ({ title, description, cancelLabel, confirmLabel, onCancel, onConfirm, children }) => ( - { if (!open) onCancel() }}> - - - -
- {title} - {description} - {children} -
-
- - -
-
-
-
-) +export const ConfirmDialog: React.FC = ({ title, description, cancelLabel, confirmLabel, onCancel, onConfirm, children }) => { + const prevFocusRef = React.useRef( + typeof document !== 'undefined' && document.activeElement instanceof HTMLElement + ? document.activeElement + : null, + ) + return ( + { if (!open) onCancel() }}> + + + { + e.preventDefault() + const prev = prevFocusRef.current + if (prev?.isConnected) prev.focus({ preventScroll: true }) + }} + > +
+ {title} + {description} + {children} +
+
+ + +
+
+
+
+ ) +} interface Props { title: string subtitle?: string closeLabel: string - /** While false, Esc / outside click / ✕ are ignored (e.g. during a create). */ + /** While false, Esc / ✕ are ignored (e.g. during a create). */ dismissable?: boolean onClose: () => void /** Extra class on the dialog box, e.g. a wider variant. */ @@ -46,41 +60,53 @@ interface Props { } /** Modal frame: head with title and ✕; children supply body/steps/foot sections. */ -export const Modal: React.FC = ({ title, subtitle, closeLabel, dismissable = true, onClose, className, children }) => ( - { if (!open && dismissable) onClose() }}> - - - e.preventDefault()} - // Focus the first enabled form field, or the dialog container itself when there is - // none, so the top-right ✕ close button's tooltip never pops on open. - onOpenAutoFocus={(e) => { - const root = e.currentTarget as HTMLElement | null - if (!root) return - e.preventDefault() - const first = root.querySelector( - 'input:not(:disabled):not([type="hidden"]):not([type="radio"]:not(:checked)), select:not(:disabled), textarea:not(:disabled)', - ) - if (first) { - first.focus({ preventScroll: true }) - } - if (!root.contains(document.activeElement)) { - root.focus({ preventScroll: true }) - } - }} - > -
-
- {title} - {subtitle ? {subtitle} : } +export const Modal: React.FC = ({ title, subtitle, closeLabel, dismissable = true, onClose, className, children }) => { + const prevFocusRef = React.useRef( + typeof document !== 'undefined' && document.activeElement instanceof HTMLElement + ? document.activeElement + : null, + ) + return ( + { if (!open && dismissable) onClose() }}> + + + e.preventDefault()} + // Focus the first enabled form field, or the dialog container itself when there is + // none, so the top-right ✕ close button's tooltip never pops on open. + onOpenAutoFocus={(e) => { + const root = e.currentTarget as HTMLElement | null + if (!root) return + e.preventDefault() + const first = root.querySelector( + 'input:not(:disabled):not([type="hidden"]):not([type="radio"]:not(:checked)), select:not(:disabled), textarea:not(:disabled)', + ) + if (first) { + first.focus({ preventScroll: true }) + } + if (!root.contains(document.activeElement)) { + root.focus({ preventScroll: true }) + } + }} + onCloseAutoFocus={(e) => { + e.preventDefault() + const prev = prevFocusRef.current + if (prev?.isConnected) prev.focus({ preventScroll: true }) + }} + > +
+
+ {title} + {subtitle ? {subtitle} : } +
+ + } disabled={!dismissable} /> +
- - } disabled={!dismissable} /> - -
- {children} - - - -) + {children} + + + + ) +} diff --git a/frontend/src/ui/settings.tsx b/frontend/src/ui/settings.tsx index b487340..2e2b3b0 100644 --- a/frontend/src/ui/settings.tsx +++ b/frontend/src/ui/settings.tsx @@ -122,7 +122,10 @@ export function Segmented({ options, value, onChange, return next }) } - useLayoutEffect(measure, [value, options]) + const optionsSig = options.map((o) => `${String(o.value)}\x1f${o.label}`).join('\x1e') + const docDir = typeof document !== 'undefined' ? document.documentElement.dir : '' + // eslint-disable-next-line react-hooks/exhaustive-deps + useLayoutEffect(measure, [value, optionsSig, wide, docDir]) useEffect(() => { if (!box.current || typeof ResizeObserver === 'undefined') return let raf = 0 @@ -142,12 +145,13 @@ export function Segmented({ options, value, onChange, }, []) const onKey = (e: React.KeyboardEvent) => { - if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return + if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft' && e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return e.preventDefault() const enabled = options.filter((o) => !o.disabled) const i = enabled.findIndex((o) => o.value === value) const isRTL = box.current ? getComputedStyle(box.current).direction === 'rtl' : false - const delta = (e.key === 'ArrowRight') !== isRTL ? 1 : -1 + const forward = e.key === 'ArrowDown' || (e.key === 'ArrowRight' && !isRTL) || (e.key === 'ArrowLeft' && isRTL) + const delta = forward ? 1 : -1 const next = enabled[(i + delta + enabled.length) % enabled.length] if (next) { onChange(next.value) @@ -384,8 +388,9 @@ export function PopupSelect({ value, options, onChange, label, id?: string }) { const cur = options.find((o) => o.value === value) + const dir: 'ltr' | 'rtl' = typeof document !== 'undefined' && document.documentElement.dir === 'rtl' ? 'rtl' : 'ltr' return ( - +
+
+
+
{tr('aboutDiscord')}
+
{tr('aboutDiscordSub')}
+
+
+ {onCopy && ( +
+
diff --git a/frontend/src/i18n/domains/settings.gen.ts b/frontend/src/i18n/domains/settings.gen.ts index 3a65bcd..f6ce213 100644 --- a/frontend/src/i18n/domains/settings.gen.ts +++ b/frontend/src/i18n/domains/settings.gen.ts @@ -3,8 +3,12 @@ import { registerBuiltinDomain } from '../runtime' export const settingsZh: Record = { "aboutCommunity": "社区与支持", + "aboutCopyDiscord": "复制邀请链接", "aboutCopyQQGroup": "复制群号", + "aboutDiscord": "Discord 社区", + "aboutDiscordSub": "交流使用体验、硬件兼容反馈、Alpha 测试与插件开发", "aboutIssueSub": "遇到问题或有功能建议,在 GitHub 提交 Issue", + "aboutJoinDiscord": "加入服务器", "aboutJoinQQGroup": "加入群聊", "aboutLicensesOpenGitHub": "在 GitHub 查看", "aboutLicensesSub": "Apache-2.0 协议与第三方开源组件声明(离线可查)", @@ -320,8 +324,12 @@ export const settingsZh: Record = { export const settingsEn: Record = { "aboutCommunity": "Community \u0026 support", + "aboutCopyDiscord": "Copy invite link", "aboutCopyQQGroup": "Copy group ID", + "aboutDiscord": "Discord community", + "aboutDiscordSub": "Chat with users, share hardware compatibility, test alphas and build plugins", "aboutIssueSub": "Report a problem or suggest a feature on GitHub", + "aboutJoinDiscord": "Join server", "aboutJoinQQGroup": "Join group", "aboutLicensesOpenGitHub": "View on GitHub", "aboutLicensesSub": "Apache-2.0 license and third-party notices (available offline)", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index eef4c99..2714283 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -2,8 +2,12 @@ export type I18nKey = | "aboutCommunity" + | "aboutCopyDiscord" | "aboutCopyQQGroup" + | "aboutDiscord" + | "aboutDiscordSub" | "aboutIssueSub" + | "aboutJoinDiscord" | "aboutJoinQQGroup" | "aboutLicensesOpenGitHub" | "aboutLicensesSub" diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index cf32f40..011201c 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -74,6 +74,10 @@ "appCheckUpdate": "Check for updates", "appDownloadUpdate": "Download", "appUpdateLookupFailed": "Couldn’t check GitHub for updates", + "aboutDiscord": "Discord community", + "aboutDiscordSub": "Chat with users, share hardware compatibility, test alphas and build plugins", + "aboutCopyDiscord": "Copy invite link", + "aboutJoinDiscord": "Join server", "aboutQQGroup": "QQ Group", "aboutQQGroupSub": "Launch QQ directly to join for community support and feedback", "aboutQQNotInstalled": "QQ not installed", diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index e46c6aa..209270e 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -74,6 +74,10 @@ "appCheckUpdate": "检查更新", "appDownloadUpdate": "前往下载", "appUpdateLookupFailed": "暂时无法连接 GitHub 检查更新", + "aboutDiscord": "Discord 社区", + "aboutDiscordSub": "交流使用体验、硬件兼容反馈、Alpha 测试与插件开发", + "aboutCopyDiscord": "复制邀请链接", + "aboutJoinDiscord": "加入服务器", "aboutQQGroup": "QQ 交流群", "aboutQQGroupSub": "点击直接拉起 QQ 加群,交流使用与问题反馈", "aboutQQNotInstalled": "未安装 QQ", From 6fbcd6422e9cda7f30a42a1ffb3cc1bdd7115795 Mon Sep 17 00:00:00 2001 From: Dnyo666 Date: Tue, 1 Dec 2026 17:54:02 +0800 Subject: [PATCH 39/42] fix(ui): prevent previous titlebar menu from flashing on switch Scope `.menu` and `.tooltip` enter animations to their open data-state selectors and explicitly set `animation: none` on `[data-state="closed"]` so Radix Presence unmounts closing menus immediately instead of replaying `menu-in` for 160ms when `data-menubar-switch` is removed during a sibling switch. Also keep `data-menubar-switch` active across the switch frame, narrow `onPointerDownOutside` to sibling menu buttons so clicks in the gap still dismiss, fix `prefers-reduced-motion` close animations (adding `fade-out` for closing toasts), and add a static guard in `test-i18n.mjs`. --- frontend/scripts/test-i18n.mjs | 39 ++++++++++++++++++++++++++ frontend/src/components/TitleMenus.tsx | 7 +++-- frontend/src/styles/app.css | 18 ++++++++---- 3 files changed, 56 insertions(+), 8 deletions(-) diff --git a/frontend/scripts/test-i18n.mjs b/frontend/scripts/test-i18n.mjs index 6539187..fea549e 100644 --- a/frontend/scripts/test-i18n.mjs +++ b/frontend/scripts/test-i18n.mjs @@ -137,6 +137,45 @@ test('Static Guard (CRITICAL-2): every stack-*, notice-*, error-boundary*, and t } }) +test('Static Guard (CRITICAL-3): Radix Presence .menu/.tooltip animations never replay on close', () => { + const css = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8') + const titleMenus = fs.readFileSync(path.join(srcDir, 'components', 'TitleMenus.tsx'), 'utf8') + + // Unconditional `.menu { ... animation: ... }` causes Radix Presence to detect an + // animationName change (`none` -> `menu-in`) when `data-menubar-switch` is removed on close, + // suspending unmount and flashing the previous menu for 160ms. + assert.doesNotMatch( + css, + /\.menu\s*\{[^}]*animation\s*:/, + 'Enter animation on .menu must be scoped to .menu[data-state="open"]', + ) + assert.match( + css, + /\.menu\[data-state="open"\]\s*\{[^}]*animation\s*:/, + '.menu[data-state="open"] must define the menu enter animation', + ) + assert.match( + css, + /\.menu\[data-state="closed"\]\s*\{[^}]*animation\s*:\s*none/, + '.menu[data-state="closed"] must explicitly disable animation so Radix Presence unmounts immediately', + ) + assert.doesNotMatch( + css, + /\.tooltip\s*\{[^}]*animation\s*:/, + 'Enter animation on .tooltip must be scoped to .tooltip[data-state="delayed-open"]', + ) + assert.match( + css, + /\.tooltip\[data-state="closed"\]\s*\{[^}]*animation\s*:\s*none/, + '.tooltip[data-state="closed"] must explicitly disable animation', + ) + assert.doesNotMatch( + titleMenus, + /data-menubar-switch=\{\s*menuState\.id\s*===\s*id\s*&&\s*menuState\.switched/, + 'TitleMenus must not strip data-menubar-switch from the outgoing sibling menu on switch', + ) +}) + test('Runtime i18n v2: ICU formatting, ghost-locale isolation (H-3), parseAppError (HIGH-2), RTL (L-2), and en-XA', async () => { const mod = await loadBundledTS(` import './i18n/domains/wizard.gen' diff --git a/frontend/src/components/TitleMenus.tsx b/frontend/src/components/TitleMenus.tsx index 81b489d..a53f02a 100644 --- a/frontend/src/components/TitleMenus.tsx +++ b/frontend/src/components/TitleMenus.tsx @@ -146,7 +146,7 @@ export const TitleMenus: React.FC = ({ = ({ pointerClosedRef.current = false }} onPointerDownOutside={(e) => { - const target = e.target as Node | null - if (target && navRef.current?.contains(target)) { + const target = e.target instanceof Element ? e.target : (e.target as Node | null)?.parentElement ?? null + const trigger = target?.closest('button.titlebar-menu') ?? null + if (trigger && navRef.current?.contains(trigger)) { e.preventDefault() return } diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index cc859a8..4c96f69 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -1331,6 +1331,7 @@ button.status-issue + .status-metric { margin-left: 6px; } /* ── Motion (emil-design-eng & apple-design) ───────────── */ @keyframes rise-in { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } } @keyframes fade-in { from { opacity: 0; } to { opacity: 1; } } +@keyframes fade-out { from { opacity: 1; } to { opacity: 0; } } @keyframes pop-in { from { opacity: 0; transform: translate(-50%, -49%) scale(0.96); } to { opacity: 1; transform: translate(-50%, -50%) scale(1); } } @keyframes menu-in { from { opacity: 0; transform: scale(0.96); } to { opacity: 1; transform: scale(1); } } @keyframes tip-in { from { opacity: 0; transform: scale(0.96); } to { opacity: 1; transform: scale(1); } } @@ -1342,10 +1343,13 @@ button.status-issue + .status-metric { margin-left: 6px; } .page { animation: rise-in var(--dur) var(--ease-out) both; } .overlay { animation: fade-in var(--dur) var(--ease-out) both; } .dialog { animation: pop-in var(--dur-modal) var(--ease-out) both; } -.menu { transform-origin: var(--radix-dropdown-menu-content-transform-origin, top); animation: menu-in 160ms var(--ease-out) both; } -.menu[data-menubar-switch="true"] { animation: none; } -.tooltip { animation: tip-in 125ms var(--ease-out) both; } -.tooltip[data-state="instant-open"] { animation-duration: 0ms; } +.menu { transform-origin: var(--radix-dropdown-menu-content-transform-origin, top); } +.menu[data-state="open"] { animation: menu-in 160ms var(--ease-out) both; } +.menu[data-state="open"][data-menubar-switch="true"], +.menu[data-state="closed"] { animation: none; } +.tooltip[data-state="delayed-open"] { animation: tip-in 125ms var(--ease-out) both; } +.tooltip[data-state="instant-open"], +.tooltip[data-state="closed"] { animation: none; } .pane-anim { display: flex; flex-direction: column; gap: 20px; animation: rise-in var(--dur) var(--ease-out) both; } .step-anim { display: flex; flex-direction: column; gap: var(--sp-4); animation: rise-in var(--dur) var(--ease-out) both; } @@ -1496,10 +1500,14 @@ button.status-issue + .status-metric { margin-left: 6px; } .status-busy, .vm-screen-live, .skeleton-bar { animation: none; } .vm-display-unit, .vm-display-unit.is-actionable:hover, .vm-display-unit.is-actionable:active { transform: none; } .vm-screen-img, .vm-spec-meter .meter-fill { transition: none; } - .page, .dialog, .menu, .tooltip, .pane-anim, .step-anim, .toast[data-state="open"], .toast[data-state="closed"] { + .page, .dialog, .menu[data-state="open"]:not([data-menubar-switch="true"]), .tooltip[data-state="delayed-open"], .pane-anim, .step-anim, .toast[data-state="open"] { animation-name: fade-in; animation-duration: 140ms; } + .toast[data-state="closed"] { + animation-name: fade-out; + animation-duration: 140ms; + } } /* ── v0.2.6 Enhancements: Screenshot, Note, Dropzone, Snapshots, Log Filter, Welcome ── */ From ee5c02f54f0549c2f21e8914aaee29604d530d7a Mon Sep 17 00:00:00 2001 From: Dnyo666 Date: Tue, 1 Dec 2026 18:47:22 +0800 Subject: [PATCH 40/42] perf(ui): eliminate software-compositing modal lag and harden UI responsiveness Remove backdrop-filter from software-composited overlays/dialogs under WebviewGpuIsDisabled: true, preload license text before mounting the modal, fix short-viewport double scrollbars and narrow-screen row wrapping, restore keyboard focus on modal close, wire RTL direction to Radix menus, add ArrowUp/ArrowDown support and signature-based layout measurement in Segmented, and harden CRITICAL-3/CRITICAL-4 static guards. --- frontend/scripts/test-i18n.mjs | 75 +++++++++++--- frontend/src/App.tsx | 7 +- frontend/src/components/AboutPage.tsx | 55 +++++++--- frontend/src/components/Sidebar.tsx | 4 +- frontend/src/components/TitleMenus.tsx | 6 +- frontend/src/components/VMPage.tsx | 4 +- frontend/src/styles/app.css | 81 +++++++++------ frontend/src/styles/tokens.css | 14 +-- frontend/src/ui/dialog.tsx | 138 +++++++++++++++---------- frontend/src/ui/settings.tsx | 13 ++- 10 files changed, 264 insertions(+), 133 deletions(-) diff --git a/frontend/scripts/test-i18n.mjs b/frontend/scripts/test-i18n.mjs index fea549e..953d47d 100644 --- a/frontend/scripts/test-i18n.mjs +++ b/frontend/scripts/test-i18n.mjs @@ -138,17 +138,30 @@ test('Static Guard (CRITICAL-2): every stack-*, notice-*, error-boundary*, and t }) test('Static Guard (CRITICAL-3): Radix Presence .menu/.tooltip animations never replay on close', () => { - const css = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8') + const rawCss = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8') + const css = rawCss.replace(/\/\*[\s\S]*?\*\//g, '') const titleMenus = fs.readFileSync(path.join(srcDir, 'components', 'TitleMenus.tsx'), 'utf8') - // Unconditional `.menu { ... animation: ... }` causes Radix Presence to detect an - // animationName change (`none` -> `menu-in`) when `data-menubar-switch` is removed on close, - // suspending unmount and flashing the previous menu for 160ms. - assert.doesNotMatch( - css, - /\.menu\s*\{[^}]*animation\s*:/, - 'Enter animation on .menu must be scoped to .menu[data-state="open"]', - ) + // Unconditional `.menu` / `.tooltip` animation (including animation-name inside + // comma-separated selector lists or reduced-motion media queries) causes Radix + // Presence to detect an animationName change on close and flash for 160ms. + for (const m of css.matchAll(/([^{}@]+)\{([^{}]+)\}/g)) { + const selectors = m[1].split(',').map((s) => s.trim()).filter(Boolean) + const decls = m[2] + if (!/\banimation(?:-name)?\s*:(?!\s*none\b)/.test(decls)) continue + for (const sel of selectors) { + assert.doesNotMatch( + sel, + /\.menu(?![a-zA-Z0-9_-])(?!\[data-state="open"\])/, + `Non-open .menu selector "${sel}" must not apply an active animation`, + ) + assert.doesNotMatch( + sel, + /\.tooltip(?![a-zA-Z0-9_-])(?!\[data-state="delayed-open"\])/, + `Non-delayed-open .tooltip selector "${sel}" must not apply an active animation`, + ) + } + } assert.match( css, /\.menu\[data-state="open"\]\s*\{[^}]*animation\s*:/, @@ -156,19 +169,24 @@ test('Static Guard (CRITICAL-3): Radix Presence .menu/.tooltip animations never ) assert.match( css, - /\.menu\[data-state="closed"\]\s*\{[^}]*animation\s*:\s*none/, - '.menu[data-state="closed"] must explicitly disable animation so Radix Presence unmounts immediately', - ) - assert.doesNotMatch( - css, - /\.tooltip\s*\{[^}]*animation\s*:/, - 'Enter animation on .tooltip must be scoped to .tooltip[data-state="delayed-open"]', + /\.menu\[data-state="open"\]\[data-menubar-switch="true"\][^\{]*\{[^}]*animation\s*:\s*none/, + '.menu[data-state="open"][data-menubar-switch="true"] must disable enter animation', ) assert.match( css, - /\.tooltip\[data-state="closed"\]\s*\{[^}]*animation\s*:\s*none/, + /\.menu\[data-state="closed"\][^\{]*\{[^}]*animation\s*:\s*none/, + '.menu[data-state="closed"] must explicitly disable animation so Radix Presence unmounts immediately', + ) + assert.match( + css, + /\.tooltip\[data-state="closed"\][^\{]*\{[^}]*animation\s*:\s*none/, '.tooltip[data-state="closed"] must explicitly disable animation', ) + assert.match( + css, + /@media\s*\(\s*prefers-reduced-motion\s*:\s*reduce\s*\)\s*\{[\s\S]*?\.toast\[data-state="closed"\][^{]*\{[^}]*animation-name\s*:\s*fade-out/, + 'Reduced-motion .toast[data-state="closed"] must use fade-out', + ) assert.doesNotMatch( titleMenus, /data-menubar-switch=\{\s*menuState\.id\s*===\s*id\s*&&\s*menuState\.switched/, @@ -176,6 +194,29 @@ test('Static Guard (CRITICAL-3): Radix Presence .menu/.tooltip animations never ) }) +test('Static Guard (CRITICAL-4): software-composited UI avoids backdrop-filter and slow pre shaping', () => { + const rawCss = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8') + const css = rawCss.replace(/\/\*[\s\S]*?\*\//g, '') + + // main.go sets WebviewGpuIsDisabled: true (software compositing), where + // backdrop-filter blurs stall CPU rasterization on animations and scrolling. + assert.doesNotMatch( + css, + /(?:-webkit-)?backdrop-filter\s*:/i, + 'app.css must not apply backdrop-filter under software compositing', + ) + assert.match( + css, + /\.license-pre\s*\{[^}]*contain\s*:\s*content/, + '.license-pre should isolate scroll/layout repaints with contain: content', + ) + assert.match( + css, + /\.license-pre\s*\{[^}]*text-rendering\s*:\s*auto/, + '.license-pre should opt out of global optimizeLegibility for long monospace texts', + ) +}) + test('Runtime i18n v2: ICU formatting, ghost-locale isolation (H-3), parseAppError (HIGH-2), RTL (L-2), and en-XA', async () => { const mod = await loadBundledTS(` import './i18n/domains/wizard.gen' diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 8368fac..2709c1e 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1069,7 +1069,12 @@ export const App: React.FC = () => { selected={selected} hostReady={hostReady} canSuspend={canSuspend} - onSelect={setSelected} + onSelect={(id) => { + setSelected(id) + if (sidebarOpen && window.matchMedia('(max-width: 768px)').matches) { + toggleSidebar() + } + }} displayNames={displayNames} macosMajors={macosMajors} onActivate={primaryAction} diff --git a/frontend/src/components/AboutPage.tsx b/frontend/src/components/AboutPage.tsx index 3f06d55..2b919ee 100644 --- a/frontend/src/components/AboutPage.tsx +++ b/frontend/src/components/AboutPage.tsx @@ -1,5 +1,5 @@ import { Copy, Download, ExternalLink, RotateCw, Scale } from 'lucide-react' -import React, { useEffect, useState } from 'react' +import React, { useEffect, useRef, useState } from 'react' import '../i18n/domains/settings.gen' import { I18nKey, t } from '../i18n' import { taskDetail } from '../lib/tasks' @@ -50,14 +50,34 @@ export const AboutPage: React.FC = ({ const [licenseOpen, setLicenseOpen] = useState(false) const [licenseTab, setLicenseTab] = useState<'notice' | 'license'>('notice') const [licenses, setLicenses] = useState<{ license: string; notice: string } | null>(null) + const mountedRef = useRef(true) + const loadingLicensesRef = useRef(false) + const licensePreRef = useRef(null) - const openLicenses = () => { - setLicenseOpen(true) - if (!licenses) { - api.GetLicenseTexts() - .then((res) => setLicenses({ license: res?.license ?? '', notice: res?.notice ?? '' })) - .catch((e) => onError(tr('failGeneric'), e)) + const openLicenses = async () => { + if (licenses) { + setLicenseOpen(true) + return } + if (loadingLicensesRef.current) return + loadingLicensesRef.current = true + try { + // Load embedded license text before mounting the modal so the dialog opens + // with its final content on frame 1 instead of reflowing mid-animation. + const res = await api.GetLicenseTexts() + if (!mountedRef.current) return + setLicenses({ license: res?.license ?? '', notice: res?.notice ?? '' }) + setLicenseOpen(true) + } catch (e) { + if (mountedRef.current) onError(tr('failGeneric'), e) + } finally { + loadingLicensesRef.current = false + } + } + + const handleLicenseTabChange = (next: 'notice' | 'license') => { + setLicenseTab(next) + if (licensePreRef.current) licensePreRef.current.scrollTop = 0 } const runUpdateCheck = async (force: boolean) => { @@ -73,12 +93,16 @@ export const AboutPage: React.FC = ({ } useEffect(() => { + mountedRef.current = true if (!appUpdate) void runUpdateCheck(false) let cancelled = false api.CanOpenQQGroup() .then((ok) => { if (!cancelled) setQQInstalled(!!ok) }) .catch(() => { if (!cancelled) setQQInstalled(false) }) - return () => { cancelled = true } + return () => { + mountedRef.current = false + cancelled = true + } }, []) const openURL = (url: string) => { @@ -245,7 +269,7 @@ export const AboutPage: React.FC = ({
{tr('aboutLicensesSub')}
-
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index 87d25c1..3bcaae5 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -1,7 +1,7 @@ import * as Ctx from '@radix-ui/react-context-menu' import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Maximize2, Pause, Play, Plus, Power, Puzzle, RotateCw, Settings, Square, Trash } from 'lucide-react' import React, { useRef } from 'react' -import { I18nKey, t } from '../i18n' +import { I18nKey, localeDir, t } from '../i18n' import { Locale, VMListItem } from '../types' import { vmRefKey } from '../lib/vmRef' import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls' @@ -137,7 +137,7 @@ export const Sidebar: React.FC = ({ ) if (!onVMContextAction) return trigger return ( - + { diff --git a/frontend/src/components/TitleMenus.tsx b/frontend/src/components/TitleMenus.tsx index a53f02a..cc5165c 100644 --- a/frontend/src/components/TitleMenus.tsx +++ b/frontend/src/components/TitleMenus.tsx @@ -1,7 +1,7 @@ import * as Menu from '@radix-ui/react-dropdown-menu' import { Check, PanelLeft } from 'lucide-react' import React, { useRef, useState } from 'react' -import { I18nKey, t } from '../i18n' +import { I18nKey, localeDir, t } from '../i18n' import { useVMStats } from '../lib/vmStats' import { Locale } from '../types' import { Tip } from '../ui/controls' @@ -90,6 +90,7 @@ export const TitleMenus: React.FC = ({ // `indented`: the menu has check marks, so every row shares their indent. const menu = (id: MenuId, label: string, content: React.ReactNode, indented = false) => ( { @@ -159,9 +160,10 @@ export const TitleMenus: React.FC = ({ pointerClosedRef.current = false }} onPointerDownOutside={(e) => { + const orig = e.detail.originalEvent const target = e.target instanceof Element ? e.target : (e.target as Node | null)?.parentElement ?? null const trigger = target?.closest('button.titlebar-menu') ?? null - if (trigger && navRef.current?.contains(trigger)) { + if (orig.button === 0 && !orig.ctrlKey && trigger && navRef.current?.contains(trigger)) { e.preventDefault() return } diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index d01f93e..c397152 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -42,7 +42,7 @@ import { UserRound, } from 'lucide-react' import React, { useEffect, useId, useRef, useState } from 'react' -import { I18nKey, locText, t } from '../i18n' +import { I18nKey, localeDir, locText, t } from '../i18n' import { controllerLabel, formatBytes, formatDiskUsage, formatMemory, formatUptime, graphicsLabel, parseMemoryGB, pendingChangeText, resolveGuestLang, sshCommand, @@ -389,6 +389,7 @@ export const VMPage: React.FC = ({ // "More" menu, grouped by purpose; destructive items last (docs/design-guidelines.md §5.2). const menu = ( { if (o) morePointerClosed.current = false @@ -980,6 +981,7 @@ export const VMPage: React.FC = ({ {tr('sshOpenTerminal')} { if (o) sshPointerClosed.current = false diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 4c96f69..5bc1d2f 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -82,15 +82,15 @@ h1, h2, h3, p { margin: 0; } /* Left of the title bar: sidebar toggle + a small menu bar. Controls and the menu bar group opt out of window dragging so sweeping across menus stays smooth. */ -.titlebar-left { display: flex; align-items: center; gap: 2px; height: 100%; margin-left: calc(var(--sp-2) * -1); } +.titlebar-left { display: flex; align-items: center; gap: 2px; height: 100%; min-width: 0; margin-inline-start: calc(var(--sp-2) * -1); } .titlebar-icon, .titlebar-menu { --wails-draggable: no-drag; height: 28px; border: none; border-radius: var(--r-sm); background: transparent; color: var(--text-2); cursor: pointer; transition: background var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), transform var(--dur-press) var(--ease-out); } -.titlebar-icon { width: 32px; display: grid; place-items: center; margin-right: 4px; } -.titlebar-menu { padding: 0 10px; font-size: var(--fs-13); font-weight: var(--fw-medium); } +.titlebar-icon { width: 32px; display: grid; place-items: center; margin-inline-end: 4px; flex-shrink: 0; } +.titlebar-menu { padding: 0 10px; font-size: var(--fs-13); font-weight: var(--fw-medium); white-space: nowrap; flex-shrink: 0; } .titlebar-icon:hover, .titlebar-menu:hover { background: var(--surface-hover); color: var(--text); } .titlebar-menu[data-state="open"] { background: var(--surface-active); color: var(--text); } .titlebar-icon:active, .titlebar-menu:active { transform: scale(0.96); } @@ -100,7 +100,7 @@ h1, h2, h3, p { margin: 0; } /* Menu rows with a trailing shortcut, check marks and group labels. */ .menu-label { flex: 1; min-width: 0; white-space: nowrap; } .menu-shortcut { - margin-left: 24px; font-family: var(--font-sans); font-size: var(--fs-12); + margin-inline-start: 24px; font-family: var(--font-sans); font-size: var(--fs-12); color: var(--text-3); font-variant-numeric: tabular-nums; } .menu-item[data-highlighted] .menu-shortcut { color: rgba(255, 255, 255, 0.78); } @@ -109,7 +109,7 @@ h1, h2, h3, p { margin: 0; } .menu-check { position: absolute; inset-inline-start: 9px; top: 50%; transform: translateY(-50%); display: grid; place-items: center; } .menu-group-label { padding: 6px 10px 2px; font-size: 11.5px; font-weight: var(--fw-medium); color: var(--text-3); user-select: none; } .theme-toggle { - width: 30px; height: 28px; margin-right: var(--sp-1); + width: 30px; height: 28px; margin-inline-end: var(--sp-1); border: 1px solid var(--border); border-radius: var(--r-md); background: var(--surface-1); color: var(--text-2); display: grid; place-items: center; cursor: pointer; @@ -138,11 +138,16 @@ h1, h2, h3, p { margin: 0; } display: flex; overflow: hidden; background: var(--surface-sidebar-rail); border-inline-end: 1px solid var(--border); - transition: width var(--dur-modal) var(--ease-out), padding var(--dur-modal) var(--ease-out), opacity var(--dur) var(--ease-out), border-color var(--dur) var(--ease-out); + transition: width var(--dur-modal) var(--ease-out), padding var(--dur-modal) var(--ease-out), opacity var(--dur) var(--ease-out), border-color var(--dur) var(--ease-out), visibility 0s linear 0s; } /* Hidden sidebar (Ctrl+B): slides shut; the card keeps its width so its - contents don't reflow while the rail narrows. */ -.workspace.sidebar-hidden .sidebar-wrap { width: 0; padding-inline: 0; opacity: 0; border-inline-end-color: transparent; } + contents don't reflow while the rail narrows, and visibility: hidden removes + off-screen buttons from the keyboard Tab order. */ +.workspace.sidebar-hidden .sidebar-wrap { + width: 0; padding-inline: 0; opacity: 0; border-inline-end-color: transparent; + visibility: hidden; pointer-events: none; + transition: width var(--dur-modal) var(--ease-out), padding var(--dur-modal) var(--ease-out), opacity var(--dur) var(--ease-out), border-color var(--dur) var(--ease-out), visibility 0s linear var(--dur-modal); +} .sidebar-wrap > .sidebar { min-width: calc(var(--sidebar-w) - 20px); } .sidebar { flex: 1; min-height: 0; @@ -716,11 +721,14 @@ h1, h2, h3, p { margin: 0; } .about-hero-text h1 { font-size: 22px; font-weight: var(--fw-strong); letter-spacing: -0.02em; color: var(--text); } .about-hero-text p { margin: 0; font-size: var(--fs-13); color: var(--text-2); line-height: 1.5; } .license-modal-body { gap: var(--sp-3); } +.license-modal-body > .seg { align-self: flex-start; flex-shrink: 0; } .license-pre { - margin: 0; padding: 14px 16px; min-height: 260px; max-height: 52vh; overflow: auto; + margin: 0; padding: 14px 16px; flex: 0 1 auto; height: min(440px, 50vh); min-height: 120px; overflow: auto; + overscroll-behavior: contain; contain: content; border-radius: var(--r-md); border: 1px solid var(--border); background: var(--surface-1); font-family: var(--font-mono); font-size: var(--fs-12); line-height: 1.55; color: var(--text-2); white-space: pre-wrap; word-break: break-word; user-select: text; + text-rendering: auto; text-autospace: no-autospace; } .section-count { min-width: 20px; padding: 1px 7px; border-radius: 999px; background: var(--surface-active); color: var(--text-3); font-size: 11px; font-weight: var(--fw-medium); text-align: center; } .installer-row { min-height: 62px; } @@ -886,6 +894,7 @@ button.status-issue + .status-metric { margin-left: 6px; } overflow-y: auto; overscroll-behavior: contain; padding: var(--sp-2) var(--sp-4); font-family: var(--font-mono); font-size: var(--fs-12); line-height: 1.6; color: var(--text-code); white-space: pre-wrap; word-break: break-word; user-select: text; + text-rendering: auto; text-autospace: no-autospace; } .log-line { display: flex; gap: var(--sp-3); } .log-ts { color: var(--text-3); flex-shrink: 0; font-variant-numeric: tabular-nums; } @@ -895,27 +904,30 @@ button.status-issue + .status-metric { margin-left: 6px; } .jump-latest { position: absolute; inset-inline-end: var(--sp-4); bottom: var(--sp-3); } /* ── Overlays: dialog, menu, tooltip, toast ────────────── */ -.overlay { position: fixed; inset: 0; background: var(--scrim); backdrop-filter: blur(5px); z-index: 40; } +/* No backdrop-filter: main.go sets WebviewGpuIsDisabled: true (software + compositing), where per-frame CPU Gaussian blur over modals/overlays stutters + badly during enter animations and inner scrolling. */ +.overlay { position: fixed; inset: 0; background: var(--scrim); z-index: 40; } .dialog { position: fixed; z-index: 41; left: 50%; top: 50%; transform: translate(-50%, -50%); width: 720px; max-width: calc(100vw - 48px); max-height: calc(100vh - 80px); display: flex; flex-direction: column; overflow: hidden; - background: var(--surface-2); backdrop-filter: var(--blur-overlay); + background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-xl); box-shadow: var(--shadow-overlay), var(--highlight-top); } .dialog.sm { width: 420px; } -.dialog-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); padding: 14px 14px 14px 22px; border-bottom: 1px solid var(--border); } +.dialog-head { flex-shrink: 0; display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); padding-block: 14px; padding-inline: 22px 14px; border-bottom: 1px solid var(--border); } .dialog-title { font-size: var(--fs-16); font-weight: var(--fw-strong); letter-spacing: -0.01em; text-wrap: balance; } .dialog-desc { font-size: var(--fs-13); color: var(--text-2); margin-top: 2px; } .dialog-body { padding: 20px 22px; overflow-y: auto; overscroll-behavior: contain; flex: 1; display: flex; flex-direction: column; gap: var(--sp-4); } -.dialog-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); padding: 12px 22px; border-top: 1px solid var(--border); } +.dialog-foot { flex-shrink: 0; display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--sp-2); padding: 12px 22px; border-top: 1px solid var(--border); } .dialog.sm .dialog-body { padding: 22px 22px 14px; gap: var(--sp-3); } .dialog.sm .dialog-foot { border-top: none; justify-content: flex-end; padding-top: 0; padding-bottom: 20px; } .menu { min-width: 188px; padding: 5px; z-index: 50; - background: var(--surface-2); backdrop-filter: var(--blur-overlay); + background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-lg); box-shadow: var(--shadow-overlay), var(--highlight-top); } @@ -936,7 +948,7 @@ button.status-issue + .status-metric { margin-left: 6px; } .tooltip { z-index: 60; padding: 5px 9px; border-radius: var(--r-sm); - background: var(--surface-2); backdrop-filter: var(--blur-overlay); + background: var(--surface-2); border: 1px solid var(--border-strong); color: var(--text); font-size: var(--fs-12); box-shadow: 0 8px 22px rgba(15, 23, 42, 0.16); display: flex; gap: var(--sp-2); align-items: center; @@ -947,7 +959,7 @@ button.status-issue + .status-metric { margin-left: 6px; } .toast-viewport { position: fixed; inset-inline-end: var(--sp-4); bottom: calc(var(--logbar-h) + var(--sp-4)); z-index: 70; display: flex; flex-direction: column; gap: var(--sp-2); width: 380px; max-width: calc(100vw - 32px); margin: 0; padding: 0; list-style: none; outline: none; } .toast { display: flex; flex-direction: column; gap: var(--sp-2); padding: var(--sp-3); - background: var(--surface-2); backdrop-filter: var(--blur-overlay); + background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-lg); box-shadow: var(--shadow-overlay), var(--highlight-top); } @@ -968,7 +980,7 @@ button.status-issue + .status-metric { margin-left: 6px; } .toast-title { font-size: var(--fs-13); font-weight: var(--fw-strong); } .toast-code { font-family: var(--font-mono); font-size: var(--fs-11); padding: 1px 5px; - border-radius: 4px; background: var(--surface-active); color: var(--text-3); + border-radius: 4px; background: var(--surface-active); color: var(--text-2); } .toast-desc { font-size: var(--fs-12); color: var(--text-2); overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical; overflow: hidden; } .toast-footer { display: flex; flex-direction: column; gap: var(--sp-2); padding-inline-start: 28px; width: 100%; min-width: 0; } @@ -1397,7 +1409,7 @@ button.status-issue + .status-metric { margin-left: 6px; } width: max-content; max-width: calc(100% - 20px); padding: 0 12px; display: inline-flex; align-items: center; justify-content: center; gap: 5px; height: 26px; border-radius: 999px; pointer-events: none; - background: rgba(20, 21, 26, 0.72); color: #fff; backdrop-filter: blur(10px); + background: rgba(20, 21, 26, 0.84); color: #fff; font-size: var(--fs-12); font-weight: var(--fw-medium); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; opacity: 0; transform: translateX(-50%) translateY(4px); @@ -1497,14 +1509,16 @@ button.status-issue + .status-metric { margin-left: 6px; } /* Reduced motion: stop decorative loops & positional motion */ @media (prefers-reduced-motion: reduce) { - .status-busy, .vm-screen-live, .skeleton-bar { animation: none; } + .status-busy, .vm-screen-live, .skeleton-bar, .market-progress.is-indeterminate .market-progress-fill { animation: none; } .vm-display-unit, .vm-display-unit.is-actionable:hover, .vm-display-unit.is-actionable:active { transform: none; } .vm-screen-img, .vm-spec-meter .meter-fill { transition: none; } .page, .dialog, .menu[data-state="open"]:not([data-menubar-switch="true"]), .tooltip[data-state="delayed-open"], .pane-anim, .step-anim, .toast[data-state="open"] { animation-name: fade-in; animation-duration: 140ms; } - .toast[data-state="closed"] { + .toast[data-state="closed"], + .toast[data-swipe="end"], + :root[dir="rtl"] .toast[data-swipe="end"] { animation-name: fade-out; animation-duration: 140ms; } @@ -1516,14 +1530,13 @@ button.status-issue + .status-metric { margin-left: 6px; } position: absolute; right: 8px; bottom: 8px; z-index: 3; width: 30px; height: 30px; border: 1px solid rgba(255, 255, 255, 0.22); border-radius: 8px; display: grid; place-items: center; cursor: pointer; - background: rgba(20, 22, 28, 0.68); color: #ffffff; - backdrop-filter: blur(10px); + background: rgba(20, 22, 28, 0.82); color: #ffffff; opacity: 0; transform: translateY(3px); transition: opacity var(--dur-fast) var(--ease-out), transform var(--dur-fast) var(--ease-out), background var(--dur-fast) var(--ease-out); } .vm-screen:hover .vm-screen-shot, .vm-screen-shot:focus-visible { opacity: 1; transform: translateY(0); } -.vm-screen-shot:hover { background: rgba(20, 22, 28, 0.88); } +.vm-screen-shot:hover { background: rgba(20, 22, 28, 0.94); } .vm-screen-shot:active { transform: scale(0.94); } /* The title is the display name; click to rename in place. The pencil hangs @@ -1577,9 +1590,8 @@ button.status-issue + .status-metric { margin-left: 6px; } position: sticky; top: 0; z-index: 20; display: flex; align-items: center; justify-content: center; gap: 8px; padding: 12px 16px; border-radius: var(--r-lg); - background: var(--accent-soft); border: 1.5px dashed var(--accent); + background: color-mix(in srgb, var(--surface-canvas) 89%, var(--accent)); border: 1.5px dashed var(--accent); color: var(--accent-soft-text); font-size: var(--fs-13); font-weight: var(--fw-medium); - backdrop-filter: var(--blur-overlay); } /* Interactive install stepper */ @@ -1847,7 +1859,7 @@ button.status-issue + .status-metric { margin-left: 6px; } } .plugin-risk.is-high .plugin-risk-icon { background: var(--warn-soft); color: var(--warn-text); } .plugin-scan-section { display: flex; flex-direction: column; gap: 6px; } -.plugin-scan-section-title { font-size: var(--fs-12); font-weight: var(--fw-semibold); color: var(--text-2); } +.plugin-scan-section-title { font-size: var(--fs-12); font-weight: var(--fw-strong); color: var(--text-2); } .plugin-scan-section-title.is-danger { color: var(--danger-text); } .plugin-scan-examples { margin-top: 4px; font-size: var(--fs-11); color: var(--text-2); display: flex; flex-direction: column; gap: 2px; } @@ -1913,6 +1925,7 @@ button.status-issue + .status-metric { margin-left: 6px; } max-height: 180px; overflow: auto; background: var(--surface-0); border: 1px solid var(--border); white-space: pre-wrap; word-break: break-word; + text-rendering: auto; text-autospace: no-autospace; } .error-boundary-actions { display: flex; gap: var(--sp-2); justify-content: flex-end; } @@ -1927,7 +1940,7 @@ button.status-issue + .status-metric { margin-left: 6px; } .sidebar-backdrop { display: block; position: absolute; inset: 0; - background: var(--scrim); backdrop-filter: blur(3px); z-index: 31; + background: var(--scrim); z-index: 31; } .sidebar-wrap { position: absolute; z-index: 32; @@ -1949,18 +1962,22 @@ button.status-issue + .status-metric { margin-left: 6px; } .settings-pane { padding: 16px; } } +@container (max-width: 520px) { + .row, .srow-head { flex-wrap: wrap; gap: var(--sp-2) var(--sp-4); } + .row-main, .srow-text { flex: 1 1 220px; } + .row-right, .srow-ctrl { flex-wrap: wrap; max-width: 100%; min-width: 0; } +} + @media (max-width: 640px) { .source-cards, .field-row, .review-groups { grid-template-columns: 1fr; } .review-group:last-child .review-rows { grid-template-columns: max-content 1fr; } .vm-spec-card { grid-template-columns: repeat(2, minmax(0, 1fr)); padding: 12px 14px; } .affinity-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } - .conn-row, .srow-head, .row, .page-head { flex-wrap: wrap; } - .conn-ctrl { flex-wrap: wrap; max-width: 100%; } + .conn-row, .srow-head, .row, .page-head { flex-wrap: wrap; gap: var(--sp-2) var(--sp-4); } + .row-main, .srow-text { flex: 1 1 220px; } + .conn-ctrl, .row-right, .srow-ctrl { flex-wrap: wrap; max-width: 100%; min-width: 0; } .plugins-search { width: 100%; } } -@container (max-width: 560px) { - .review-group:last-child .review-rows { grid-template-columns: max-content 1fr; } -} } diff --git a/frontend/src/styles/tokens.css b/frontend/src/styles/tokens.css index 7d588e2..b821444 100644 --- a/frontend/src/styles/tokens.css +++ b/frontend/src/styles/tokens.css @@ -90,17 +90,19 @@ --surface-statusbar: #eef3fa; --surface-1: #f5f6f8; --surface-card-elevated: #ffffff; - --surface-2: rgba(255, 255, 255, 0.94); + --surface-2: rgba(255, 255, 255, 0.98); --surface-input: #ffffff; --surface-hover: rgba(15, 23, 42, 0.048); --surface-active: rgba(15, 23, 42, 0.085); --border: rgba(15, 23, 42, 0.08); --border-strong: rgba(15, 23, 42, 0.14); --highlight-top: inset 0 1px 0 rgba(255, 255, 255, 0.85); - --scrim: rgba(15, 23, 42, 0.28); + --scrim: rgba(15, 23, 42, 0.34); --shadow-btn: 0 1px 2px rgba(15, 23, 42, 0.06), inset 0 1px 0 rgba(255, 255, 255, 0.7); --shadow-card: 0 1px 2px rgba(15, 23, 42, 0.025); - --shadow-overlay: 0 22px 58px rgba(15, 23, 42, 0.18), 0 4px 14px rgba(15, 23, 42, 0.06), 0 0 0 1px rgba(15, 23, 42, 0.06); + --shadow-overlay: 0 16px 36px rgba(15, 23, 42, 0.16), 0 3px 10px rgba(15, 23, 42, 0.06), 0 0 0 1px rgba(15, 23, 42, 0.06); + /* Retained for UI Contract v1 (uiApi 1.0.0) theme compatibility; unused by default + base styles while main.go runs WebView2 in software compositing mode. */ --blur-chrome: blur(20px) saturate(180%); --blur-overlay: blur(18px) saturate(165%); @@ -167,17 +169,17 @@ --surface-statusbar: #18191e; --surface-1: rgba(255, 255, 255, 0.048); --surface-card-elevated: rgba(255, 255, 255, 0.075); - --surface-2: rgba(42, 43, 50, 0.94); + --surface-2: rgba(42, 43, 50, 0.98); --surface-input: rgba(0, 0, 0, 0.28); --surface-hover: rgba(255, 255, 255, 0.075); --surface-active: rgba(255, 255, 255, 0.12); --border: rgba(255, 255, 255, 0.085); --border-strong: rgba(255, 255, 255, 0.16); --highlight-top: inset 0 1px 0 rgba(255, 255, 255, 0.08); - --scrim: rgba(0, 0, 0, 0.56); + --scrim: rgba(0, 0, 0, 0.58); --shadow-btn: 0 1px 2px rgba(0, 0, 0, 0.30), inset 0 1px 0 rgba(255, 255, 255, 0.06); --shadow-card: 0 1px 3px rgba(0, 0, 0, 0.18); - --shadow-overlay: 0 26px 68px rgba(0, 0, 0, 0.58), 0 0 0 1px rgba(255, 255, 255, 0.09); + --shadow-overlay: 0 18px 40px rgba(0, 0, 0, 0.52), 0 0 0 1px rgba(255, 255, 255, 0.09); --text: #f5f5f7; --text-2: #c2c2ca; diff --git a/frontend/src/ui/dialog.tsx b/frontend/src/ui/dialog.tsx index 16ddcdc..d8b6101 100644 --- a/frontend/src/ui/dialog.tsx +++ b/frontend/src/ui/dialog.tsx @@ -14,30 +14,44 @@ interface ConfirmDialogProps { children?: React.ReactNode } -export const ConfirmDialog: React.FC = ({ title, description, cancelLabel, confirmLabel, onCancel, onConfirm, children }) => ( - { if (!open) onCancel() }}> - - - -
- {title} - {description} - {children} -
-
- - -
-
-
-
-) +export const ConfirmDialog: React.FC = ({ title, description, cancelLabel, confirmLabel, onCancel, onConfirm, children }) => { + const prevFocusRef = React.useRef( + typeof document !== 'undefined' && document.activeElement instanceof HTMLElement + ? document.activeElement + : null, + ) + return ( + { if (!open) onCancel() }}> + + + { + e.preventDefault() + const prev = prevFocusRef.current + if (prev?.isConnected) prev.focus({ preventScroll: true }) + }} + > +
+ {title} + {description} + {children} +
+
+ + +
+
+
+
+ ) +} interface Props { title: string subtitle?: string closeLabel: string - /** While false, Esc / outside click / ✕ are ignored (e.g. during a create). */ + /** While false, Esc / ✕ are ignored (e.g. during a create). */ dismissable?: boolean onClose: () => void /** Extra class on the dialog box, e.g. a wider variant. */ @@ -46,41 +60,53 @@ interface Props { } /** Modal frame: head with title and ✕; children supply body/steps/foot sections. */ -export const Modal: React.FC = ({ title, subtitle, closeLabel, dismissable = true, onClose, className, children }) => ( - { if (!open && dismissable) onClose() }}> - - - e.preventDefault()} - // Focus the first enabled form field, or the dialog container itself when there is - // none, so the top-right ✕ close button's tooltip never pops on open. - onOpenAutoFocus={(e) => { - const root = e.currentTarget as HTMLElement | null - if (!root) return - e.preventDefault() - const first = root.querySelector( - 'input:not(:disabled):not([type="hidden"]):not([type="radio"]:not(:checked)), select:not(:disabled), textarea:not(:disabled)', - ) - if (first) { - first.focus({ preventScroll: true }) - } - if (!root.contains(document.activeElement)) { - root.focus({ preventScroll: true }) - } - }} - > -
-
- {title} - {subtitle ? {subtitle} : } +export const Modal: React.FC = ({ title, subtitle, closeLabel, dismissable = true, onClose, className, children }) => { + const prevFocusRef = React.useRef( + typeof document !== 'undefined' && document.activeElement instanceof HTMLElement + ? document.activeElement + : null, + ) + return ( + { if (!open && dismissable) onClose() }}> + + + e.preventDefault()} + // Focus the first enabled form field, or the dialog container itself when there is + // none, so the top-right ✕ close button's tooltip never pops on open. + onOpenAutoFocus={(e) => { + const root = e.currentTarget as HTMLElement | null + if (!root) return + e.preventDefault() + const first = root.querySelector( + 'input:not(:disabled):not([type="hidden"]):not([type="radio"]:not(:checked)), select:not(:disabled), textarea:not(:disabled)', + ) + if (first) { + first.focus({ preventScroll: true }) + } + if (!root.contains(document.activeElement)) { + root.focus({ preventScroll: true }) + } + }} + onCloseAutoFocus={(e) => { + e.preventDefault() + const prev = prevFocusRef.current + if (prev?.isConnected) prev.focus({ preventScroll: true }) + }} + > +
+
+ {title} + {subtitle ? {subtitle} : } +
+ + } disabled={!dismissable} /> +
- - } disabled={!dismissable} /> - -
- {children} - - - -) + {children} + + + + ) +} diff --git a/frontend/src/ui/settings.tsx b/frontend/src/ui/settings.tsx index b487340..2e2b3b0 100644 --- a/frontend/src/ui/settings.tsx +++ b/frontend/src/ui/settings.tsx @@ -122,7 +122,10 @@ export function Segmented({ options, value, onChange, return next }) } - useLayoutEffect(measure, [value, options]) + const optionsSig = options.map((o) => `${String(o.value)}\x1f${o.label}`).join('\x1e') + const docDir = typeof document !== 'undefined' ? document.documentElement.dir : '' + // eslint-disable-next-line react-hooks/exhaustive-deps + useLayoutEffect(measure, [value, optionsSig, wide, docDir]) useEffect(() => { if (!box.current || typeof ResizeObserver === 'undefined') return let raf = 0 @@ -142,12 +145,13 @@ export function Segmented({ options, value, onChange, }, []) const onKey = (e: React.KeyboardEvent) => { - if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return + if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft' && e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return e.preventDefault() const enabled = options.filter((o) => !o.disabled) const i = enabled.findIndex((o) => o.value === value) const isRTL = box.current ? getComputedStyle(box.current).direction === 'rtl' : false - const delta = (e.key === 'ArrowRight') !== isRTL ? 1 : -1 + const forward = e.key === 'ArrowDown' || (e.key === 'ArrowRight' && !isRTL) || (e.key === 'ArrowLeft' && isRTL) + const delta = forward ? 1 : -1 const next = enabled[(i + delta + enabled.length) % enabled.length] if (next) { onChange(next.value) @@ -384,8 +388,9 @@ export function PopupSelect({ value, options, onChange, label, id?: string }) { const cur = options.find((o) => o.value === value) + const dir: 'ltr' | 'rtl' = typeof document !== 'undefined' && document.documentElement.dir === 'rtl' ? 'rtl' : 'ltr' return ( - +