From c639682a8873b0c2af918c78704075c56bb1059c 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: Thu, 3 Dec 2026 20:55:03 -0700 Subject: [PATCH 01/22] refactor: remove unused functions and keep the codebase free of them Delete functions that no product code calls, and fold "simple plus WithOptions" pairs into the one signature callers actually use. Rename the live macOS lifecycle functions that were labelled Legacy. The architecture tests now share one source loader and reject functions without a product caller and catalog messages nobody reads. Co-Authored-By: Claude Opus 5.5 --- frontend/src/i18n/domains/plugins.gen.ts | 6 - frontend/src/i18n/domains/settings.gen.ts | 44 ----- frontend/src/i18n/keys.gen.ts | 25 --- internal/app/appupdate_flow.go | 2 +- internal/app/create_flow.go | 2 +- internal/app/disk_flow.go | 4 +- internal/app/host_drop.go | 11 +- internal/app/install_flow.go | 12 +- internal/app/lifecycle_flow.go | 12 +- internal/app/macos_detail.go | 4 +- internal/app/macos_lifecycle_native.go | 22 +-- internal/app/macos_settings.go | 29 +--- internal/app/macos_window.go | 86 ---------- internal/app/plugins_flow.go | 2 +- internal/app/runtime_bindings.go | 2 +- internal/app/ssh_flow.go | 11 +- internal/app/ssh_flow_test.go | 8 +- internal/app/tasks.go | 7 +- internal/app/tasks_test.go | 2 +- internal/app/thumbnail_flow.go | 5 - internal/app/thumbnail_flow_test.go | 159 ++++++------------ internal/app/vm_close_windows.go | 12 +- internal/app/vm_monitor_test.go | 6 +- internal/app/vm_processes.go | 10 -- internal/app/vmref_test.go | 3 - internal/archtest/driver_isolation_test.go | 43 +---- internal/archtest/locales_test.go | 75 +++++++++ internal/archtest/macos_boundary_test.go | 104 +++--------- internal/archtest/sources_test.go | 98 +++++++++++ internal/archtest/unused_test.go | 61 +++++++ internal/cli/plugin.go | 16 +- internal/console/manager.go | 2 +- internal/console/manager_test.go | 8 + internal/datamigrate/guest_migration_test.go | 5 +- internal/datamigrate/release_upgrade_test.go | 5 +- internal/datamigrate/vmref_settings.go | 14 -- internal/datamigrate/vmref_settings_test.go | 5 +- internal/driver/driver.go | 21 +-- internal/driver/driver_test.go | 62 ++++--- internal/driver/vmref_test.go | 2 +- internal/host/fonts_other.go | 4 - internal/host/fonts_windows.go | 8 - internal/host/foreground_other.go | 3 - internal/host/foreground_windows.go | 6 - internal/host/fullscreen_other.go | 8 - internal/host/fullscreen_windows.go | 11 -- internal/host/host_other.go | 8 - internal/host/host_windows.go | 27 +-- internal/host/hypervisor.go | 8 - internal/host/hypervisor_test.go | 10 +- internal/host/hypervisor_windows.go | 4 - internal/host/progress_parse_test.go | 26 +++ internal/host/smbios_memory.go | 17 -- internal/host/smbios_memory_test.go | 5 +- internal/host/stats.go | 16 -- internal/i18n/catalog_gen.go | 34 ---- internal/i18n/i18n.go | 8 - internal/macos/guest/guest.go | 21 --- internal/macos/guest/guest_test.go | 8 +- internal/macos/installer/events.go | 3 - internal/macos/installer/installer_test.go | 23 --- internal/macos/macosdriver/clone.go | 2 +- internal/macos/macosdriver/driver.go | 4 +- internal/macos/macosdriver/optimizations.go | 11 -- .../macos/macosdriver/optimizations_test.go | 12 +- internal/macos/macosdriver/storage.go | 2 +- internal/macos/opencore/lang.go | 15 -- internal/macos/reims/compat_test.go | 11 +- internal/macos/reims/disk_import.go | 45 +---- internal/macos/reims/disk_ops_test.go | 8 +- internal/macos/reims/network.go | 35 ---- internal/macos/reims/network_test.go | 6 +- internal/macos/reims/redact.go | 9 - internal/macos/reims/reims.go | 18 +- internal/macos/reims/suspend.go | 15 -- internal/macos/reims/suspend_test.go | 7 +- internal/packetbridge/start_guard_other.go | 1 - internal/packetbridge/start_guard_windows.go | 5 - internal/plugin/assets.go | 2 +- internal/plugin/blockers_test.go | 6 +- internal/plugin/kernel_test.go | 6 +- internal/plugin/ledger.go | 13 -- internal/plugin/manager.go | 2 +- internal/plugin/manager_sidecar_test.go | 10 +- internal/plugin/scanner.go | 14 +- internal/plugin/state.go | 12 -- internal/plugin/theme_css.go | 28 ++- internal/qmp/blockstats.go | 23 --- internal/qmp/combo_test.go | 8 - internal/qmp/keys.go | 71 +------- internal/qmp/keys_test.go | 8 +- internal/qmp/pointer.go | 15 -- internal/qmp/screendump.go | 11 -- internal/qmp/watcher.go | 12 -- internal/qmp/watcher_test.go | 24 +-- internal/selfupdate/selfupdate.go | 15 +- internal/selfupdate/selfupdate_test.go | 8 +- internal/testutil/fakedriver/harness.go | 2 +- internal/version/version.go | 16 +- internal/version/version_test.go | 16 +- internal/vmstart/core.go | 21 --- locales/en-US/native.json | 73 -------- locales/en-US/plugins.json | 3 - locales/en-US/settings.json | 22 --- locales/zh-CN/native.json | 73 -------- locales/zh-CN/plugins.json | 3 - locales/zh-CN/settings.json | 22 --- 107 files changed, 575 insertions(+), 1435 deletions(-) delete mode 100644 internal/app/macos_window.go create mode 100644 internal/archtest/locales_test.go create mode 100644 internal/archtest/sources_test.go create mode 100644 internal/archtest/unused_test.go create mode 100644 internal/host/progress_parse_test.go delete mode 100644 internal/macos/reims/redact.go diff --git a/frontend/src/i18n/domains/plugins.gen.ts b/frontend/src/i18n/domains/plugins.gen.ts index 0bec700..4cd5847 100644 --- a/frontend/src/i18n/domains/plugins.gen.ts +++ b/frontend/src/i18n/domains/plugins.gen.ts @@ -14,7 +14,6 @@ export const pluginsZh: Record = { "pluginBuiltinSection": "内置插件", "pluginClearSecret": "清除", "pluginColorSchemes": "配色方案", - "pluginColorSchemesHint": "修改种子色派生整套界面色阶", "pluginDeleteScheme": "删除方案", "pluginDisable": "停用", "pluginDisableInUseBody": "停用后,这个插件管理的虚拟机会显示为「驱动不可用」,不能启动或修改。虚拟机文件和挂起状态都会保留,重新启用即可恢复。运行中的虚拟机需要先停止或挂起。", @@ -70,7 +69,6 @@ export const pluginsZh: Record = { "pluginMarketSearchPlaceholder": "搜索市场插件、作者或标签", "pluginMarketStaleBanner": "远程插件市场暂不可达,当前显示本地缓存或内置回退索引", "pluginMarketSyncing": "正在同步插件市场", - "pluginMarketUpdate": "更新至 v{version}", "pluginMarketUpdateShort": "更新", "pluginMarketVersionTip": "已安装 v{installed},可更新至 v{version}", "pluginMarketWithdrawn": "已撤回", @@ -98,7 +96,6 @@ export const pluginsZh: Record = { "pluginScanHardSection": "硬性拦截项(禁止安装)", "pluginScanInspect": "安全扫描", "pluginScanInstallConfirm": "确认导入安装", - "pluginScanLoading": "正在扫描插件包…", "pluginScanModalTitle": "插件静态安全报告", "pluginScanMoreItems": "另有 {count} 项已折叠", "pluginSchemeDefault": "默认", @@ -139,7 +136,6 @@ export const pluginsEn: Record = { "pluginBuiltinSection": "Built-in plugins", "pluginClearSecret": "Clear", "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 and any suspended state are kept; turning the plugin back on restores them. Stop or suspend any running VM first.", @@ -195,7 +191,6 @@ export const pluginsEn: Record = { "pluginMarketSearchPlaceholder": "Search market plugins, publishers, or tags", "pluginMarketStaleBanner": "Remote market index is unreachable; showing cached or offline fallback data", "pluginMarketSyncing": "Syncing the plugin market", - "pluginMarketUpdate": "Update to v{version}", "pluginMarketUpdateShort": "Update", "pluginMarketVersionTip": "v{installed} installed, v{version} available", "pluginMarketWithdrawn": "Withdrawn", @@ -223,7 +218,6 @@ export const pluginsEn: Record = { "pluginScanHardSection": "Hard blockers (install refused)", "pluginScanInspect": "Security scan", "pluginScanInstallConfirm": "Proceed with install", - "pluginScanLoading": "Scanning plugin package…", "pluginScanModalTitle": "Plugin security report", "pluginScanMoreItems": "...and {count} more", "pluginSchemeDefault": "Default", diff --git a/frontend/src/i18n/domains/settings.gen.ts b/frontend/src/i18n/domains/settings.gen.ts index 02e3482..aca3c0a 100644 --- a/frontend/src/i18n/domains/settings.gen.ts +++ b/frontend/src/i18n/domains/settings.gen.ts @@ -59,7 +59,6 @@ export const settingsZh: Record = { "affinitySummaryPCores": "仅 P 核({count} 线程 · {mask})", "affinityTitle": "处理器核心", "appCheckUpdate": "检查更新", - "appDownloadUpdate": "前往下载", "appUpToDate": "已是最新", "appUpdateAvailable": "发现新版本 {v}(稳定版)", "appUpdateAvailableAlpha": "发现新版本 {v}(Alpha 测试版)", @@ -169,11 +168,9 @@ export const settingsZh: Record = { "effectNextStart": "下次启动生效", "enableAudio": "音频", "enableLogs": "记录图形与串口日志", - "enableNetwork": "网络(NAT)", "enableWHPX": "启用", "extraArgs": "额外 QEMU 参数", "extraArgsDesc": "原样追加到 QEMU 命令行", - "failAffinity": "设置处理器相关性失败", "folderShareAdd": "添加目录…", "folderShareAddTitle": "宿主机目录", "folderShareConfirmRWAction": "改为读写", @@ -199,9 +196,6 @@ export const settingsZh: Record = { "folderShareRemove": "移除目录", "folderShareTitle": "自定义共享目录", "folderShareWritableWarn": "读写模式:macOS 中的修改和删除会直接作用于宿主机原目录", - "footerDisk": "磁盘可用 {gb} GB", - "footerMem": "内存 {pct}%", - "footerMemAvail": "可用 {avail} GB", "forceQuitAppButton": "强制退出", "forceQuitAppSub": "对所有运行中的虚拟机执行硬关机,未保存的数据可能丢失。", "forceQuitAppTitle": "强制退出 Reims-Go", @@ -247,7 +241,6 @@ export const settingsZh: Record = { "groupMacOS": "macOS", "groupPerformance": "性能", "groupQemu": "QEMU", - "gtInstallCmd": "安装命令", "guestLangHint": "恢复模式、设置助理和登录界面使用的语言;选美式键盘,在终端输命令不易出错", "guestLangSettingsHint": "恢复模式、设置助理和登录界面使用的语言", "guestLangShort": "系统语言", @@ -279,9 +272,6 @@ export const settingsZh: Record = { "guestTimezoneUTC": "UTC(协调世界时)", "guestTimezoneUpgradeAttachHint": "先在虚拟机详情页挂载 Guest Tools 镜像,即可查看升级到版本 {version} 的命令", "guestTimezoneUpgradeHint": "在 macOS 终端运行以下命令,将 Guest Tools 升级到版本 {version}", - "guestToolsConnected": "已连接", - "guestToolsPreventSleepSub": "闲置时让 macOS 保持唤醒,立即生效", - "guestToolsReady": "已配置", "hidpiPresetBadge": "HiDPI", "hostAudioInput": "Windows 麦克风", "hostAudioMissingIn": "没有检测到麦克风,macOS 录不到声音", @@ -356,7 +346,6 @@ export const settingsZh: Record = { "installersDownloaded": "已下载", "installersDownloadingForVM": "为 {vm} 下载中", "installersDownloadingPct": "下载中 {p}%", - "installersEmpty": "还没有下载任何镜像", "installersHint": "下载好的镜像可以重复用来新建虚拟机", "installersKindOffline": "离线完整包", "installersKindOnline": "在线恢复镜像", @@ -425,7 +414,6 @@ export const settingsZh: Record = { "nestedVirtLabel": "嵌套虚拟化", "nestedVirtUnavailable": "当前 Windows 宿主机无法通过 WHPX 提供 VMX。", "networkBridge": "桥接", - "networkDesc": "通过 Windows 的网络连接上网", "networkNAT": "NAT", "networkOfflineHint": "离线安装默认关闭;看到「设置助理」后退出恢复模式并重启即可联网", "networkTitle": "网络", @@ -436,7 +424,6 @@ export const settingsZh: Record = { "npcapInstalling": "正在准备 Npcap,在弹出的官方安装向导中完成安装后将自动重新检查", "npcapMissing": "未检测到完整安装;应用网络时自动从官网下载,也可提前安装。许可与 UAC 在官方向导确认", "npcapStopFirst": "安装驱动前需先关闭全部虚拟机", - "offlineListFailed": "无法读取 Apple 的版本列表", "opencore": "OpenCore", "optAuto": "已自动开启", "optAvailable": "可用", @@ -449,11 +436,9 @@ export const settingsZh: Record = { "optPCoreSub": "仅调度到性能核({detail}),减少卡顿", "optPCoreUnavailable": "当前处理器无大小核架构,无需开启", "optRecommended": "推荐", - "optSchedBackground": "后台服务", "optSchedNowBackground": "当前为「后台服务」,适合虚拟机在后台运行(影响整个 Windows)", "optSchedNowPrograms": "当前为「程序优先」,虚拟机在后台时可能变慢,建议改为「后台服务」(影响整个 Windows)", "optSchedOpen": "更改…", - "optSchedPrograms": "程序优先", "optSchedSub": "选「后台服务」,虚拟机在后台时更稳定(影响整个 Windows)", "optSchedTitle": "Windows 处理器调度", "optUnavailable": "不可用", @@ -462,7 +447,6 @@ export const settingsZh: Record = { "recommendedBadge": "推荐", "resCustom": "自定义", "resCustomSub": "宽 × 高", - "resFullscreen": "全屏", "resInvalid": "格式为 宽x高,例如 2560x1600", "resNativeBadge": "原生", "resScaleToFitWindow": "缩放以适应窗口", @@ -504,11 +488,6 @@ export const settingsZh: Record = { "sshOffDesc": "从 Windows 用 SSH 登录 macOS", "sshPort": "SSH 转发端口", "startAfterCreate": "创建后立即启动", - "statsCPU": "QEMU CPU", - "statsDisk": "磁盘占用", - "statsDiskSub": "实际 {actual} / 上限 {virtual}", - "statsMemory": "宿主机内存", - "statsUptime": "运行时长", "stopBeforeDiskOp": "关机后才能操作", "stopTimeout": "关机等待时间", "stopTimeoutHint": "0 表示一直等待", @@ -547,7 +526,6 @@ export const settingsZh: Record = { "vcpus": "虚拟处理器", "vmDir": "存放目录", "vmName": "名称", - "welcomeCheckHost": "先完成内核环境配置 →", "welcomeSub": "选择系统来源、分配核数与显卡,几步完成配置", "welcomeTitle": "创建第一台 macOS 虚拟机", "whpxHvOff": "Hypervisor 启动已关闭,启用后重启 Windows", @@ -624,7 +602,6 @@ export const settingsEn: Record = { "affinitySummaryPCores": "P-Cores ({count}T · {mask})", "affinityTitle": "CPU cores", "appCheckUpdate": "Check for updates", - "appDownloadUpdate": "Download", "appUpToDate": "Up to date", "appUpdateAvailable": "New stable release {v} available", "appUpdateAvailableAlpha": "New alpha release {v} available", @@ -734,11 +711,9 @@ export const settingsEn: Record = { "effectNextStart": "Next start", "enableAudio": "Audio", "enableLogs": "Keep graphics and serial logs", - "enableNetwork": "Network (NAT)", "enableWHPX": "Enable", "extraArgs": "Extra QEMU arguments", "extraArgsDesc": "Appended to the QEMU command line as is", - "failAffinity": "Could not update processor affinity", "folderShareAdd": "Add folder…", "folderShareAddTitle": "Host folders", "folderShareConfirmRWAction": "Enable read-write", @@ -764,9 +739,6 @@ export const settingsEn: Record = { "folderShareRemove": "Remove folder", "folderShareTitle": "Custom shared folders", "folderShareWritableWarn": "Read-write: changes and deletions in macOS modify the host folder directly", - "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", @@ -812,7 +784,6 @@ export const settingsEn: Record = { "groupMacOS": "macOS", "groupPerformance": "Performance", "groupQemu": "QEMU", - "gtInstallCmd": "Install command", "guestLangHint": "Used by Recovery, Setup Assistant and the login window; a US keyboard layout keeps Terminal input reliable", "guestLangSettingsHint": "Used by Recovery, Setup Assistant and the login window", "guestLangShort": "System language", @@ -844,9 +815,6 @@ export const settingsEn: Record = { "guestTimezoneUTC": "UTC", "guestTimezoneUpgradeAttachHint": "Attach the Guest Tools image on the VM details page to see the command for updating to version {version}", "guestTimezoneUpgradeHint": "Run the command below in macOS Terminal to update Guest Tools to version {version}", - "guestToolsConnected": "Connected", - "guestToolsPreventSleepSub": "Keeps macOS awake while idle; applies immediately", - "guestToolsReady": "Configured", "hidpiPresetBadge": "HiDPI", "hostAudioInput": "Windows microphone", "hostAudioMissingIn": "No microphone found; macOS will record silence", @@ -921,7 +889,6 @@ export const settingsEn: Record = { "installersDownloaded": "Downloaded", "installersDownloadingForVM": "Downloading for {vm}", "installersDownloadingPct": "Downloading {p}%", - "installersEmpty": "No images downloaded yet", "installersHint": "Downloaded images can be reused for new VMs", "installersKindOffline": "Offline installer", "installersKindOnline": "Online recovery", @@ -990,7 +957,6 @@ export const settingsEn: Record = { "nestedVirtLabel": "Nested virtualization", "nestedVirtUnavailable": "The Windows host does not provide VMX through WHPX.", "networkBridge": "Bridged", - "networkDesc": "Uses the Windows network connection", "networkNAT": "NAT", "networkOfflineHint": "Off by default for offline installs. Exit recovery and restart when Setup Assistant appears to enable networking", "networkTitle": "Network", @@ -1001,7 +967,6 @@ export const settingsEn: Record = { "npcapInstalling": "Preparing Npcap. Complete the official installer; availability will be checked afterwards", "npcapMissing": "A complete installation was not detected. Downloaded from the official website when applying, or install now. Confirm the license and UAC in the official wizard", "npcapStopFirst": "Shut down all VMs before installing the driver", - "offlineListFailed": "Couldn’t read Apple’s release list", "opencore": "OpenCore", "optAuto": "Automatic", "optAvailable": "Available", @@ -1014,11 +979,9 @@ export const settingsEn: Record = { "optPCoreSub": "Schedule QEMU on performance cores only ({detail})", "optPCoreUnavailable": "CPU has no hybrid P/E cores", "optRecommended": "Recommended", - "optSchedBackground": "Background services", "optSchedNowBackground": "Set to Background services, which suits a VM running in the background (affects all of Windows)", "optSchedNowPrograms": "Set to Programs, so the VM may slow down in the background. Background services is recommended (affects all of Windows)", "optSchedOpen": "Change…", - "optSchedPrograms": "Programs", "optSchedSub": "Background services keeps the VM steady in the background (affects all of Windows)", "optSchedTitle": "Windows processor scheduling", "optUnavailable": "Unavailable", @@ -1027,7 +990,6 @@ export const settingsEn: Record = { "recommendedBadge": "Recommended", "resCustom": "Custom", "resCustomSub": "Width × height", - "resFullscreen": "Full screen", "resInvalid": "Use WIDTHxHEIGHT, e.g. 2560x1600", "resNativeBadge": "Native", "resScaleToFitWindow": "Scale to fit window", @@ -1069,11 +1031,6 @@ export const settingsEn: Record = { "sshOffDesc": "Log in to macOS over SSH from Windows", "sshPort": "SSH forward port", "startAfterCreate": "Start after creating", - "statsCPU": "QEMU CPU", - "statsDisk": "Disk usage", - "statsDiskSub": "{actual} actual / {virtual} max", - "statsMemory": "Host RAM", - "statsUptime": "Uptime", "stopBeforeDiskOp": "Shut down the VM first", "stopTimeout": "Shutdown timeout", "stopTimeoutHint": "0 waits indefinitely", @@ -1112,7 +1069,6 @@ export const settingsEn: Record = { "vcpus": "Virtual CPUs", "vmDir": "Folder", "vmName": "Name", - "welcomeCheckHost": "Set up Engine first →", "welcomeSub": "Pick an installer, assign cores and GPU, and launch in minutes", "welcomeTitle": "Create your first macOS VM", "whpxHvOff": "Hypervisor launch is off — enable and restart Windows", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 5bc845f..1159fac 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -59,7 +59,6 @@ export type I18nKey = | "affinitySummaryPCores" | "affinityTitle" | "appCheckUpdate" - | "appDownloadUpdate" | "appUpToDate" | "appUpdateAvailable" | "appUpdateAvailableAlpha" @@ -245,7 +244,6 @@ export type I18nKey = | "emptyVMs" | "enableAudio" | "enableLogs" - | "enableNetwork" | "enableWHPX" | "endpointCopyADB" | "endpointEditConnection" @@ -278,7 +276,6 @@ export type I18nKey = | "factGraphics" | "factGuestOS" | "factMemory" - | "failAffinity" | "failAttachInstaller" | "failCloneVM" | "failCreate" @@ -346,14 +343,11 @@ export type I18nKey = | "folderShareTitle" | "folderShareWritableWarn" | "fontMissingFoDHint" - | "footerDisk" | "footerDiskLabel" | "footerDiskTip" | "footerDiskValue" | "footerHostIssue" | "footerHostIssueTip" - | "footerMem" - | "footerMemAvail" | "footerMemLabel" | "footerMemTip" | "footerMemValue" @@ -412,7 +406,6 @@ export type I18nKey = | "groupPerformance" | "groupQemu" | "gtInstall" - | "gtInstallCmd" | "gtInstallSub" | "gtNotInstalledDesc" | "gtStatusConnected" @@ -464,13 +457,10 @@ export type I18nKey = | "guestTimezoneUTC" | "guestTimezoneUpgradeAttachHint" | "guestTimezoneUpgradeHint" - | "guestToolsConnected" | "guestToolsHostDNS" | "guestToolsModeSync" | "guestToolsModeWebDAV" | "guestToolsPreventSleep" - | "guestToolsPreventSleepSub" - | "guestToolsReady" | "guestToolsSleepActive" | "guestToolsTitle" | "guestToolsUpgradeHint" @@ -588,7 +578,6 @@ export type I18nKey = | "installersDownloading" | "installersDownloadingForVM" | "installersDownloadingPct" - | "installersEmpty" | "installersHint" | "installersKindOffline" | "installersKindOnline" @@ -694,7 +683,6 @@ export type I18nKey = | "netOff" | "netShared" | "networkBridge" - | "networkDesc" | "networkNAT" | "networkOfflineHint" | "networkTitle" @@ -712,7 +700,6 @@ export type I18nKey = | "offlineCached" | "offlineDownloading" | "offlineHint" - | "offlineListFailed" | "offlineListFailedDetail" | "offlineLoading" | "offlineQueued" @@ -737,11 +724,9 @@ export type I18nKey = | "optPCoreSub" | "optPCoreUnavailable" | "optRecommended" - | "optSchedBackground" | "optSchedNowBackground" | "optSchedNowPrograms" | "optSchedOpen" - | "optSchedPrograms" | "optSchedSub" | "optSchedTitle" | "optUnavailable" @@ -767,7 +752,6 @@ export type I18nKey = | "pluginBuiltinSection" | "pluginClearSecret" | "pluginColorSchemes" - | "pluginColorSchemesHint" | "pluginDeleteScheme" | "pluginDisable" | "pluginDisableInUseBody" @@ -823,7 +807,6 @@ export type I18nKey = | "pluginMarketSearchPlaceholder" | "pluginMarketStaleBanner" | "pluginMarketSyncing" - | "pluginMarketUpdate" | "pluginMarketUpdateShort" | "pluginMarketVersionTip" | "pluginMarketWithdrawn" @@ -852,7 +835,6 @@ export type I18nKey = | "pluginScanHardSection" | "pluginScanInspect" | "pluginScanInstallConfirm" - | "pluginScanLoading" | "pluginScanModalTitle" | "pluginScanMoreItems" | "pluginSchemeDefault" @@ -884,7 +866,6 @@ export type I18nKey = | "refresh" | "resCustom" | "resCustomSub" - | "resFullscreen" | "resInvalid" | "resLooksLike" | "resNativeBadge" @@ -1051,11 +1032,6 @@ export type I18nKey = | "state_stopping" | "state_suspended" | "state_suspending" - | "statsCPU" - | "statsDisk" - | "statsDiskSub" - | "statsMemory" - | "statsUptime" | "step1" | "step2" | "step3" @@ -1208,7 +1184,6 @@ export type I18nKey = | "vmDir" | "vmName" | "vulkanProbeFailed" - | "welcomeCheckHost" | "welcomeSub" | "welcomeTitle" | "whpxHvOff" diff --git a/internal/app/appupdate_flow.go b/internal/app/appupdate_flow.go index abc0a09..e31d3d0 100644 --- a/internal/app/appupdate_flow.go +++ b/internal/app/appupdate_flow.go @@ -175,7 +175,7 @@ func (a *App) InstallAppUpdate() error { } a.mu.Unlock() target := selfupdate.Target(exe, filepath.Base(path)) - if err := selfupdate.SwapWithOptions(exe, target, path, version.KeepsPreviousInstall(channel)); err != nil { + if err := selfupdate.Swap(exe, target, path, version.KeepsPreviousInstall(channel)); err != nil { return err } a.emitLog("app", fmt.Sprintf("Installed update %s at %s; restarting", ver, target)) diff --git a/internal/app/create_flow.go b/internal/app/create_flow.go index ddcaca1..8bcda84 100644 --- a/internal/app/create_flow.go +++ b/internal/app/create_flow.go @@ -56,7 +56,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) { ctx, cancel := context.WithCancel(a.baseCtx()) defer cancel() - taskID, w, finishTask := a.ctlTaskWriterWithCancel("vm-create", opts.Name, cancel) + taskID, w, finishTask := a.ctlTaskWriter("vm-create", opts.Name, cancel) if opts.NetworkMode == "bridge" { tasks.update(taskID, installer.Update{Kind: installer.KindStep, Message: networkmsg.Text(a.locale(), "log.create_network_prepare"), Percent: -1}) } diff --git a/internal/app/disk_flow.go b/internal/app/disk_flow.go index f917484..cec64cd 100644 --- a/internal/app/disk_flow.go +++ b/internal/app/disk_flow.go @@ -23,7 +23,7 @@ func (a *App) ResizeVMDiskWithDriver(driverID, name, newSize string) (driver.Dis ref := driver.VMRef{DriverID: driverID, Name: name} taskCtx, cancel := context.WithCancel(a.baseCtx()) defer cancel() - _, w, finishTask := a.ctlTaskWriterWithCancel("vm-disk-resize", ref.Key(), cancel) + _, w, finishTask := a.ctlTaskWriter("vm-disk-resize", ref.Key(), cancel) a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Resizing disk for %s (%s)...", name, strings.TrimSpace(newSize))) res, err := svc.ResizeDisk(taskCtx, ref, newSize, w, w) if err != nil { @@ -70,7 +70,7 @@ func (a *App) runCompactVMDisk(driverID, name string, optimize bool) (driver.Dis taskKind = "vm-disk-optimize" message = fmt.Sprintf("Optimizing qcow2 disk for %s with extended L2 subclusters...", name) } - _, w, finishTask := a.ctlTaskWriterWithCancel(taskKind, ref.Key(), cancel) + _, w, finishTask := a.ctlTaskWriter(taskKind, ref.Key(), cancel) a.emitVMLogForDriver(driverID, name, message) var ( res driver.DiskCompactResult diff --git a/internal/app/host_drop.go b/internal/app/host_drop.go index 94f8711..6d43552 100644 --- a/internal/app/host_drop.go +++ b/internal/app/host_drop.go @@ -14,7 +14,6 @@ import ( "time" "github.com/Nwflower/reims-go/internal/guesttools" - "github.com/Nwflower/reims-go/internal/qmp" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) @@ -199,9 +198,6 @@ func (a *App) currentGuestToolsServer() *guesttools.Server { return a.guestTools } -var sendDropClickAndPaste = qmp.SendAbsoluteClickAndPaste -var defaultDropClickAndPaste = true - func (a *App) handleHostDropPaste(ctx context.Context, vmKey, name, dropID string, displayIndex int, normX, normY float64, activateClick bool, commandKey string, focusWait time.Duration) error { if _, running := a.currentVMPID(ctx, name); !running { return fmt.Errorf("%s is not running", name) @@ -210,12 +206,7 @@ func (a *App) handleHostDropPaste(ctx context.Context, vmKey, name, dropID strin if err != nil { return err } - if defaultDropClickAndPaste && fmt.Sprintf("%p", sendDropClickAndPaste) == fmt.Sprintf("%p", qmp.SendAbsoluteClickAndPaste) { - if svc, svcErr := a.computerUseService(); svcErr == nil && svc != nil { - return svc.SendAbsoluteClickAndPaste(ctx, d.Directory, normX, normY, activateClick, commandKey, focusWait) - } - } - return sendDropClickAndPaste(ctx, d.Directory, normX, normY, activateClick, commandKey, focusWait) + return a.computerUseInternalService().SendAbsoluteClickAndPaste(ctx, d.Directory, normX, normY, activateClick, commandKey, focusWait) } func (a *App) handleHostDropAck(vmKey, name string, ack guesttools.DropEventAck) { diff --git a/internal/app/install_flow.go b/internal/app/install_flow.go index 5d6ac62..4b5fe6c 100644 --- a/internal/app/install_flow.go +++ b/internal/app/install_flow.go @@ -79,7 +79,7 @@ func (a *App) EnterRecovery(name string) error { svc := a.lifecycleSvc a.mu.Unlock() if svc == nil { - return a.enterRecoveryLegacy(name) + return a.enterMacOSRecovery(name) } raw, err := svc.InvokeAction(context.Background(), driver.NewVMRef("", name), "enter_recovery", nil) if err != nil { @@ -103,10 +103,10 @@ func (a *App) EnterRecovery(name string) error { return nil } -// enterRecoveryLegacy is the direct reims-ctl fallback when the lifecycle +// enterMacOSRecovery is the direct reims-ctl fallback when the lifecycle // router is unconfigured; it enables OpenCore's boot picker (--boot-selection=true) // immediately when stopped or queues a "want" marker when running. -func (a *App) enterRecoveryLegacy(name string) error { +func (a *App) enterMacOSRecovery(name string) error { c, err := a.client() if err != nil { return err @@ -286,7 +286,7 @@ func (a *App) FinishInstall(name string) error { svc := a.lifecycleSvc a.mu.Unlock() if svc == nil { - return a.finishInstallLegacy(name) + return a.finishMacOSInstall(name) } vm, err := a.resolveVMInfo("", name) if err != nil { @@ -333,10 +333,10 @@ func (a *App) FinishInstall(name string) error { return nil } -// FinishInstall exits recovery mode: ejects any attached installer, removes +// finishMacOSInstall exits recovery mode: ejects any attached installer, removes // REIMSHELP, enables the network if off, and restores OpenCore direct boot // (--boot-selection=false) if recovery mode enabled the boot picker. -func (a *App) finishInstallLegacy(name string) error { +func (a *App) finishMacOSInstall(name string) error { c, err := a.client() if err != nil { return err diff --git a/internal/app/lifecycle_flow.go b/internal/app/lifecycle_flow.go index b3c0ea3..5a343c2 100644 --- a/internal/app/lifecycle_flow.go +++ b/internal/app/lifecycle_flow.go @@ -118,7 +118,7 @@ func (a *App) StartVMWithDriver(driverID, name string) error { return err } return a.withComputerUseVM(context.Background(), vm.Directory, func(context.Context) error { - return a.startVMLegacy(vm.Name) + return a.startMacOSVM(vm.Name) }) } _, vm, err := svc.Resolve(context.Background(), driverID, name) @@ -137,7 +137,7 @@ func (a *App) startResolvedVMLocked(ctx context.Context, svc interface { Start(context.Context, driver.VMRef, io.Writer, io.Writer) (driver.StartResult, error) }, vm driver.VMInfo) error { if svc == nil { - return a.startVMLegacy(vm.Name) + return a.startMacOSVM(vm.Name) } ref := vm.Ref() key := ref.Key() @@ -193,7 +193,7 @@ func (a *App) stopVMWithDriverCtx(ctx context.Context, driverID, name string, fo if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID { return errors.New("driver is unavailable without the plugin manager") } - return a.stopVMLegacyCtx(ctx, name, force) + return a.stopMacOSVM(ctx, name, force) } _, vm, err := svc.Resolve(ctx, driverID, name) if err != nil { @@ -238,7 +238,7 @@ func (a *App) EjectInstallerWithDriver(driverID, name string) error { if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID { return errors.New("driver is unavailable without the plugin manager") } - return a.ejectInstallerLegacy(name) + return a.ejectMacOSInstaller(name) } vm, err := a.resolveVMInfo(driverID, name) if err != nil { @@ -260,7 +260,7 @@ func (a *App) ReadVMLogsWithDriver(driverID, name string, serial bool) (string, svc := a.lifecycleSvc a.mu.Unlock() if svc == nil { - return a.readVMLogsLegacy(name, serial) + return a.readMacOSVMLogs(name, serial) } return svc.ReadLogs(context.Background(), driver.VMRef{DriverID: driverID, Name: name}, serial) } @@ -318,7 +318,7 @@ func (a *App) DeleteVMWithDriver(driverID, name string, keepFiles bool) error { if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID { return errors.New("driver is unavailable without the plugin manager") } - return a.deleteVMLegacy(name, keepFiles) + return a.deleteMacOSVM(name, keepFiles) } d, vm, err := svc.ResolveForDelete(context.Background(), driverID, name) if err != nil { diff --git a/internal/app/macos_detail.go b/internal/app/macos_detail.go index 8830f67..6d4e713 100644 --- a/internal/app/macos_detail.go +++ b/internal/app/macos_detail.go @@ -30,7 +30,7 @@ func vmInfoFromMacOSDetail(detail reims.VMDetail) driver.VMInfo { return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: detail.DiskPath(), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort, DriverData: data} } -func (a *App) getVMDetailLegacy(name string, epoch uint64) (reims.VMDetail, error) { +func (a *App) loadMacOSVMDetail(name string, epoch uint64) (reims.VMDetail, error) { c, err := a.client() if err != nil { return reims.VMDetail{}, err @@ -56,7 +56,7 @@ func (a *App) getVMDetail(name string, epoch uint64) (reims.VMDetail, error) { svc := a.lifecycleSvc a.mu.Unlock() if svc == nil { - return a.getVMDetailLegacy(name, epoch) + return a.loadMacOSVMDetail(name, epoch) } // 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. diff --git a/internal/app/macos_lifecycle_native.go b/internal/app/macos_lifecycle_native.go index ec5cf4d..bf02ef3 100644 --- a/internal/app/macos_lifecycle_native.go +++ b/internal/app/macos_lifecycle_native.go @@ -194,7 +194,7 @@ func stripLegacyManagedExtraArgs(extraArgs string) string { return strings.TrimSpace(s) } -func (a *App) startVMLegacy(name string) error { +func (a *App) startMacOSVM(name string) error { if err := a.requireWritableDataRoot(); err != nil { return err } @@ -433,11 +433,7 @@ func (a *App) reconcileLegacyBridgeArgs(ctx context.Context, c networkControlCli return nil } -func (a *App) stopVMLegacy(name string, force bool) error { - return a.stopVMLegacyCtx(context.Background(), name, force) -} - -func (a *App) stopVMLegacyCtx(ctx context.Context, name string, force bool) error { +func (a *App) stopMacOSVM(ctx context.Context, name string, force bool) error { c, err := a.client() if err != nil { return err @@ -447,11 +443,11 @@ func (a *App) stopVMLegacyCtx(ctx context.Context, name string, force bool) erro return err } return a.withComputerUseVM(ctx, detail.Directory, func(operationCtx context.Context) error { - return a.stopVMLegacyLocked(operationCtx, name, force, c) + return a.stopMacOSVMLocked(operationCtx, name, force, c) }) } -func (a *App) stopVMLegacyLocked(ctx context.Context, name string, force bool, c *reims.Client) error { +func (a *App) stopMacOSVMLocked(ctx context.Context, name string, force bool, c *reims.Client) error { a.cancelRebootWatcher(name) stopVMMonitor(name) a.mu.Lock() @@ -541,7 +537,7 @@ func (a *App) restartMacOSVMLocked(ctx context.Context, name string) (stopped bo return true, a.startResolvedVMLocked(ctx, svc, vm) } -func (a *App) ejectInstallerLegacy(name string) error { +func (a *App) ejectMacOSInstaller(name string) error { c, err := a.client() if err != nil { return err @@ -563,7 +559,7 @@ func (a *App) ejectInstallerLegacy(name string) error { return nil } -func (a *App) deleteVMLegacy(name string, keepFiles bool) error { +func (a *App) deleteMacOSVM(name string, keepFiles bool) error { c, err := a.client() if err != nil { return err @@ -573,11 +569,11 @@ func (a *App) deleteVMLegacy(name string, keepFiles bool) error { return err } return a.withComputerUseVM(context.Background(), detail.Directory, func(ctx context.Context) error { - return a.deleteVMLegacyLocked(ctx, name, keepFiles, c) + return a.deleteMacOSVMLocked(ctx, name, keepFiles, c) }) } -func (a *App) deleteVMLegacyLocked(ctx context.Context, name string, keepFiles bool, c *reims.Client) error { +func (a *App) deleteMacOSVMLocked(ctx context.Context, name string, keepFiles bool, c *reims.Client) error { a.cancelRebootWatcher(name) stopVMMonitor(name) w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) }) @@ -628,7 +624,7 @@ func (a *App) ReadVMLogs(name string, serial bool) (string, error) { return a.ReadVMLogsWithDriver("", name, serial) } -func (a *App) readVMLogsLegacy(name string, serial bool) (string, error) { +func (a *App) readMacOSVMLogs(name string, serial bool) (string, error) { c, err := a.client() if err != nil { return "", err diff --git a/internal/app/macos_settings.go b/internal/app/macos_settings.go index 365b564..db906d7 100644 --- a/internal/app/macos_settings.go +++ b/internal/app/macos_settings.go @@ -36,7 +36,7 @@ func (a *App) ValidateCreate(opts reims.CreateOpts) []reims.ValidationIssue { root := a.cfg.DataRoot loc := i18n.EffectiveLocale(a.cfg.Locale) a.mu.Unlock() - issues := reims.ValidateCreateLocalized(opts, host.Inspect(root), loc) + issues := reims.ValidateCreate(opts, host.Inspect(root), loc) // reims-ctl refuses a name already registered; say so before the create runs. if vms, err := a.listVMsInternal(context.Background()); err == nil { for _, vm := range vms { @@ -69,7 +69,7 @@ func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) { root := a.cfg.DataRoot loc := a.cfg.Locale a.mu.Unlock() - return reims.ValidateSetLocalized(opts, cur, host.Inspect(root), loc), nil + return reims.ValidateSet(opts, cur, host.Inspect(root), loc), nil } func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) { @@ -107,7 +107,7 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) { root := a.cfg.DataRoot loc := a.cfg.Locale a.mu.Unlock() - if issues := reims.ValidateSetLocalized(opts, cur, host.Inspect(root), loc); len(issues) > 0 { + if issues := reims.ValidateSet(opts, cur, host.Inspect(root), loc); len(issues) > 0 { return fmt.Errorf("%s", issues[0].Message) } w := vmstart.LineWriter(func(line string) { a.emitVMLog(opts.Name, line) }) @@ -526,29 +526,6 @@ func (a *App) recoverPacketNetwork(ctx context.Context, c networkControlClient, })() } -// 启动和恢复只重开 Npcap 通道,不改写封存的设备参数。 -func (a *App) prepareVMNetwork(c *reims.Client, d reims.VMDetail) (err error) { - defer a.localizeNetworkError(&err) - record, err := reims.ReadNetworkRecord(d.Directory) - if err != nil { - return err - } - if record.Corrupt { - return networkmsg.Error("record_invalid", nil) - } - if record.Pending { - return networkmsg.Error("packet_pending", nil) - } - if d.NetworkMode != "bridge" { - a.stopPacketBridge(d.Name) - return nil - } - if !a.npcapPluginEnabled() { - return networkmsg.Error("plugin_disabled", nil) - } - return a.preparePacketNetwork(a.baseCtx(), c, d, record, false) -} - func selectPacketUplink(adapters []packetbridge.Adapter, guid string) (packetbridge.Adapter, error) { for _, adapter := range adapters { if guid != "" && adapterGUIDKey(adapter.GUID) == adapterGUIDKey(guid) && adapter.Status == "Up" { diff --git a/internal/app/macos_window.go b/internal/app/macos_window.go deleted file mode 100644 index 3cae6d1..0000000 --- a/internal/app/macos_window.go +++ /dev/null @@ -1,86 +0,0 @@ -package app - -import ( - "context" - "errors" - "fmt" - - "github.com/Nwflower/reims-go/internal/driver" - "github.com/Nwflower/reims-go/internal/host" - "github.com/Nwflower/reims-go/internal/i18n" - "github.com/Nwflower/reims-go/internal/macos/reims" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" -) - -// ToggleVMFullscreen switches the running VM's display between full screen and windowed mode. -func (a *App) toggleVMFullscreenLegacy(name string) (bool, error) { - a.mu.Lock() - preference := a.cfg.Locale - a.mu.Unlock() - loc := i18n.EffectiveLocale(preference) - c, err := a.client() - if err != nil { - return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", i18n.Vars{"name": name}, err) - } - fullscreen, err := toggleVMFullscreen(context.Background(), name, loc, c, host.ToggleProcessWindowFullscreen) - if err != nil { - return false, err - } - a.emitVMLog(name, fmt.Sprintf("VM window full screen: %t", fullscreen)) - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } - return fullscreen, nil -} - -type fullscreenVMClient interface { - Show(context.Context, string) (reims.VMDetail, error) - List(context.Context) ([]driver.VMListItem, error) -} - -func findRunningVMPID(vms []driver.VMListItem, name string) (uint32, bool) { - for _, vm := range vms { - if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 { - return uint32(*vm.PID), true - } - } - return 0, false -} - -func toggleVMFullscreen(ctx context.Context, name string, loc i18n.Locale, c fullscreenVMClient, toggleWindow func(uint32) (bool, error)) (bool, error) { - vars := i18n.Vars{"name": name} - beforeVMs, err := c.List(ctx) - if err != nil { - return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err) - } - pidBefore, ok := findRunningVMPID(beforeVMs, name) - if !ok { - return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil) - } - detail, err := c.Show(ctx, name) - if err != nil { - return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err) - } - if detail.State != "running" { - return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil) - } - if detail.Graphics == "vmware-svga" { - return false, i18n.NewCodedError(loc, "E_FULLSCREEN_VMWARE_SVGA", "err.fullscreen_vmware_svga", vars, nil) - } - afterVMs, err := c.List(ctx) - if err != nil { - return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err) - } - pidAfter, ok := findRunningVMPID(afterVMs, name) - if !ok || pidAfter != pidBefore { - return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil) - } - fullscreen, err := toggleWindow(pidAfter) - if errors.Is(err, host.ErrDisplayWindowNotFound) { - return false, i18n.NewCodedError(loc, "E_VM_WINDOW_NOT_FOUND", "err.vm_window_not_found", vars, err) - } - if err != nil { - return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err) - } - return fullscreen, nil -} diff --git a/internal/app/plugins_flow.go b/internal/app/plugins_flow.go index 5e84a4d..c622ea8 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -103,7 +103,7 @@ func (a *App) initPlugins() { } kindReg := rt.NewKindRegistry() - drvRouter := driver.NewRouterWithDataRoot(mgr.Registry(), func() string { + drvRouter := driver.NewRouter(mgr.Registry(), func() string { a.mu.Lock() defer a.mu.Unlock() return a.cfg.DataRoot diff --git a/internal/app/runtime_bindings.go b/internal/app/runtime_bindings.go index 2e336d5..8380f6d 100644 --- a/internal/app/runtime_bindings.go +++ b/internal/app/runtime_bindings.go @@ -234,7 +234,7 @@ func (a *App) CheckAppUpdate(force bool) (version.UpdateInfo, error) { if !force && appUpdateCache.info != nil && appUpdateCache.channel == ch && time.Since(appUpdateCache.at) < remoteCacheTTL { return *appUpdateCache.info, nil } - info, err := version.DefaultSource().CheckUpdateChannel(a.baseCtx(), version.Version, ch) + info, err := version.DefaultSource().CheckUpdate(a.baseCtx(), version.Version, ch) if err != nil { return info, err } diff --git a/internal/app/ssh_flow.go b/internal/app/ssh_flow.go index d099549..b89215f 100644 --- a/internal/app/ssh_flow.go +++ b/internal/app/ssh_flow.go @@ -15,9 +15,6 @@ const sshUserFileName = ".reims-go-ssh-user" var safeSSHUserRe = regexp.MustCompile(`^[A-Za-z0-9._-]+$`) -// sshHostAlias returns a stable ~/.ssh/config Host alias for a VM. -func sshHostAlias(vmName string) string { return sshHostAliasForDriver("", vmName) } - func sshHostAliasForDriver(driverID, vmName string) string { var b strings.Builder b.WriteString("reims-") @@ -183,7 +180,7 @@ func (a *App) WriteSSHConfigWithDriver(driverID, name, user string) (string, err } cfgPath := filepath.Join(sshDir, "config") alias := sshHostAliasForDriver(driverID, name) - if err := upsertSSHConfigBlockHost(cfgPath, sshConfigKey(driverID, name), alias, sshHost, sshPort, user); err != nil { + if err := upsertSSHConfigBlock(cfgPath, sshConfigKey(driverID, name), alias, sshHost, sshPort, user); err != nil { return "", err } a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Updated ~/.ssh/config with Host %s (%s:%d)", alias, sshHost, sshPort)) @@ -218,11 +215,7 @@ func (a *App) OpenVSCodeSSHWithDriver(driverID, name, user string) error { return nil } -func upsertSSHConfigBlock(cfgPath, vmName, alias string, port int, user string) error { - return upsertSSHConfigBlockHost(cfgPath, vmName, alias, "127.0.0.1", port, user) -} - -func upsertSSHConfigBlockHost(cfgPath, vmName, alias, host string, port int, user string) error { +func upsertSSHConfigBlock(cfgPath, vmName, alias, host string, port int, user string) error { startMark := fmt.Sprintf("# >>> reims-go:%s >>>", vmName) endMark := fmt.Sprintf("# <<< reims-go:%s <<<", vmName) diff --git a/internal/app/ssh_flow_test.go b/internal/app/ssh_flow_test.go index 2481cb9..a0099c6 100644 --- a/internal/app/ssh_flow_test.go +++ b/internal/app/ssh_flow_test.go @@ -11,10 +11,10 @@ func TestSSHHostAlias(t *testing.T) { if sshHostAliasForDriver("test.driver.linux", "dev") == sshHostAliasForDriver("", "dev") { t.Fatal("same-name drivers share an SSH alias") } - if got := sshHostAlias("macos-tahoe"); got != "reims-macos-tahoe" { + if got := sshHostAliasForDriver("", "macos-tahoe"); got != "reims-macos-tahoe" { t.Fatalf("alias = %q", got) } - if got := sshHostAlias("My Mac 26"); got != "reims-my-mac-26" { + if got := sshHostAliasForDriver("", "My Mac 26"); got != "reims-my-mac-26" { t.Fatalf("alias = %q", got) } } @@ -26,7 +26,7 @@ func TestUpsertSSHConfigBlockIdempotent(t *testing.T) { t.Fatal(err) } - if err := upsertSSHConfigBlock(cfg, "macos-tahoe", "reims-macos-tahoe", 2222, "alice"); err != nil { + if err := upsertSSHConfigBlock(cfg, "macos-tahoe", "reims-macos-tahoe", "127.0.0.1", 2222, "alice"); err != nil { t.Fatal(err) } b1, _ := os.ReadFile(cfg) @@ -36,7 +36,7 @@ func TestUpsertSSHConfigBlockIdempotent(t *testing.T) { } // Updating port and user must replace the block in place without duplicating it. - if err := upsertSSHConfigBlock(cfg, "macos-tahoe", "reims-macos-tahoe", 2223, "bob"); err != nil { + if err := upsertSSHConfigBlock(cfg, "macos-tahoe", "reims-macos-tahoe", "127.0.0.1", 2223, "bob"); err != nil { t.Fatal(err) } b2, _ := os.ReadFile(cfg) diff --git a/internal/app/tasks.go b/internal/app/tasks.go index 25c10ff..7acb892 100644 --- a/internal/app/tasks.go +++ b/internal/app/tasks.go @@ -399,12 +399,7 @@ func (a *App) ensureTaskEmitter() { // a ": " prefix, which is dropped from the step. Each new step is logged // once, so the log keeps the milestones without one line per percent. // finish closes the task with the command's error. -func (a *App) ctlTaskWriter(kind, vm string) (w io.Writer, finish func(error)) { - _, w, finish = a.ctlTaskWriterWithCancel(kind, vm, nil) - return w, finish -} - -func (a *App) ctlTaskWriterWithCancel(kind, vm string, cancel context.CancelFunc) (id string, w io.Writer, finish func(error)) { +func (a *App) ctlTaskWriter(kind, vm string, cancel context.CancelFunc) (id string, w io.Writer, finish func(error)) { a.ensureTaskEmitter() id = tasks.start(kind, vm, vm, cancel) lastStep := "" diff --git a/internal/app/tasks_test.go b/internal/app/tasks_test.go index c7fb7e3..aa3c24b 100644 --- a/internal/app/tasks_test.go +++ b/internal/app/tasks_test.go @@ -75,7 +75,7 @@ func TestTaskCancelAndFailure(t *testing.T) { func TestCtlTaskWriterRoutesProgressToTheTask(t *testing.T) { sent := newTestTasks(t) a := &App{} // no Wails context: emitLog is a no-op - w, finish := a.ctlTaskWriter("vm-create", "macos-tahoe") + _, w, finish := a.ctlTaskWriter("vm-create", "macos-tahoe", nil) fmt.Fprintln(w, "macos-tahoe: creating the disk") for p := 0; p <= 100; p += 5 { fmt.Fprintf(w, "macos-tahoe: downloading OpenCore 1.0.8: %d%% of 11 MB\n", p) diff --git a/internal/app/thumbnail_flow.go b/internal/app/thumbnail_flow.go index 29c4830..20bc9d9 100644 --- a/internal/app/thumbnail_flow.go +++ b/internal/app/thumbnail_flow.go @@ -41,7 +41,6 @@ var thumbLocks = struct { locks map[string]*sync.Mutex }{locks: make(map[string]*sync.Mutex)} -func (a *App) thumbPath(name string) string { return a.thumbPathForDriver("", name) } func (a *App) thumbPathForDriver(driverID, name string) string { a.mu.Lock() dir := a.cfg.XDGCacheDir() @@ -58,7 +57,6 @@ func (a *App) thumbPathForDriver(driverID, name string) string { return filepath.Join(dir, "thumbs", prefix+name+".jpg") } -func vmThumbLock(name string) *sync.Mutex { return vmThumbLockForDriver("", name) } func vmThumbLockForDriver(driverID, name string) *sync.Mutex { key := vmKeyForDriver(driverID, name) thumbLocks.mu.Lock() @@ -237,9 +235,6 @@ func (a *App) CopyVMScreenshotWithDriver(driverID, name string) error { return nil } -func (a *App) captureThumb(name, path string) (VMThumbnail, bool) { - return a.captureThumbWithDriver("", name, path) -} func (a *App) captureThumbWithDriver(driverID, name, path string) (VMThumbnail, bool) { typing.mu.Lock() busy := typing.busy[vmKeyForDriver(driverID, name)] diff --git a/internal/app/thumbnail_flow_test.go b/internal/app/thumbnail_flow_test.go index 0fbadb9..44e6fd6 100644 --- a/internal/app/thumbnail_flow_test.go +++ b/internal/app/thumbnail_flow_test.go @@ -2,20 +2,23 @@ package app import ( "context" - "errors" - "slices" + "os" + "runtime" + "strings" "testing" - "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/i18n" - "github.com/Nwflower/reims-go/internal/macos/reims" + vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle" + "github.com/Nwflower/reims-go/internal/plugin" ) func TestReleaseVMThumbnailRemovesLock(t *testing.T) { const name = "thumbnail-release-test" t.Cleanup(func() { releaseVMThumbnail(name) }) - first := vmThumbLock(name) - if got := vmThumbLock(name); got != first { + first := vmThumbLockForDriver("", name) + if got := vmThumbLockForDriver("", name); got != first { t.Fatal("same VM should share a thumbnail lock") } releaseVMThumbnail(name) @@ -25,124 +28,58 @@ func TestReleaseVMThumbnailRemovesLock(t *testing.T) { if remaining != 0 { t.Fatalf("thumbnail locks remain after release: %d", remaining) } - if got := vmThumbLock(name); got == first { + if got := vmThumbLockForDriver("", name); got == first { t.Fatal("released lock was reused") } } -type testFullscreenClient struct { - detail reims.VMDetail - vms []reims.VMListItem - listCalls [][]reims.VMListItem - calls []string -} - -func (c *testFullscreenClient) Show(_ context.Context, name string) (reims.VMDetail, error) { - c.calls = append(c.calls, "show "+name) - return c.detail, nil -} - -func (c *testFullscreenClient) List(context.Context) ([]reims.VMListItem, error) { - idx := 0 - for _, call := range c.calls { - if call == "list" { - idx++ - } - } - c.calls = append(c.calls, "list") - if len(c.listCalls) > 0 { - if idx < len(c.listCalls) { - return c.listCalls[idx], nil - } - return c.listCalls[len(c.listCalls)-1], nil - } - return c.vms, nil -} - -func TestToggleVMFullscreenUsesLiveVMState(t *testing.T) { - const name = "Tahoe" - oldPID, livePID, zeroPID, invalidPID := 301, 542, 0, -1 - for _, tt := range []struct { - name string - state string - vms []reims.VMListItem - listCalls [][]reims.VMListItem - wantCalls []string - target uint32 - }{ - {"stopped at show", "stopped", []reims.VMListItem{{Name: name, State: "running", PID: &oldPID}}, nil, []string{"list", "show Tahoe"}, 0}, - {"stopped before first list", "running", []reims.VMListItem{{Name: name, State: "stopped", PID: &oldPID}}, nil, []string{"list"}, 0}, - {"missing from list", "running", []reims.VMListItem{{Name: "Other", State: "running", PID: &oldPID}}, nil, []string{"list"}, 0}, - {"missing PID", "running", []reims.VMListItem{{Name: name, State: "running"}}, nil, []string{"list"}, 0}, - {"zero PID", "running", []reims.VMListItem{{Name: name, State: "running", PID: &zeroPID}}, nil, []string{"list"}, 0}, - {"negative PID", "running", []reims.VMListItem{{Name: name, State: "running", PID: &invalidPID}}, nil, []string{"list"}, 0}, - {"restarted with different PID between show and list (e.g. switched to SVGA)", "running", nil, [][]reims.VMListItem{ - {{Name: name, State: "running", PID: &oldPID}}, - {{Name: name, State: "running", PID: &livePID}}, - }, []string{"list", "show Tahoe", "list"}, 0}, - {"live running VM with stable PID", "running", []reims.VMListItem{ - {Name: "Other", State: "running", PID: &oldPID}, {Name: name, State: "running", PID: &livePID}, - }, nil, []string{"list", "show Tahoe", "list"}, uint32(livePID)}, - } { - t.Run(tt.name, func(t *testing.T) { - c := &testFullscreenClient{detail: reims.VMDetail{State: tt.state, Graphics: "reims-vgpu"}, vms: tt.vms, listCalls: tt.listCalls} - got, err := toggleVMFullscreen(context.Background(), name, i18n.EnUS, c, func(pid uint32) (bool, error) { - if pid != tt.target || tt.target == 0 { - t.Fatalf("toggled PID %d, want %d", pid, tt.target) - } - return true, nil - }) - if !slices.Equal(c.calls, tt.wantCalls) { - t.Fatalf("client calls = %v, want %v", c.calls, tt.wantCalls) - } - if tt.target == 0 { - if got || err == nil || err.Error() != "VM Tahoe is not running [E_VM_NOT_RUNNING]" { - t.Fatalf("toggle = (%v, %v), want a not-running error", got, err) - } - } else if !got || err != nil { - t.Fatalf("toggle = (%v, %v), want (true, nil)", got, err) - } - }) - } -} - +// Every refusal carries a localized summary and a stable code. func TestToggleVMFullscreenLocalizesErrors(t *testing.T) { - win32Error := errors.New("SetWindowPos: access denied") - pid := 542 + windowless := os.Getpid() for _, tt := range []struct { - name string - detail reims.VMDetail - hostError error - en, zh string + name, state, graphics string + pid *int + en, zh string }{ - {"stopped", reims.VMDetail{State: "stopped"}, nil, + {"stopped", "stopped", "", nil, "VM Tahoe is not running [E_VM_NOT_RUNNING]", "虚拟机 Tahoe 未运行 [E_VM_NOT_RUNNING]"}, - {"SVGA", reims.VMDetail{State: "running", Graphics: "vmware-svga"}, nil, + {"no process", "running", "reims-vgpu", nil, + "VM Tahoe is not running [E_VM_NOT_RUNNING]", "虚拟机 Tahoe 未运行 [E_VM_NOT_RUNNING]"}, + {"SVGA", "running", "vmware-svga", &windowless, "Press Ctrl+Alt+F in the QEMU window for Tahoe to toggle full screen [E_FULLSCREEN_VMWARE_SVGA]", "在 Tahoe 的 QEMU 窗口中按 Ctrl+Alt+F 切换全屏 [E_FULLSCREEN_VMWARE_SVGA]"}, - {"missing window", reims.VMDetail{State: "running", Graphics: "reims-vgpu"}, host.ErrDisplayWindowNotFound, + {"missing window", "running", "reims-vgpu", &windowless, "Couldn’t find the display window for Tahoe [E_VM_WINDOW_NOT_FOUND]", "找不到 Tahoe 的显示窗口 [E_VM_WINDOW_NOT_FOUND]"}, - {"Win32 failure", reims.VMDetail{State: "running", Graphics: "reims-vgpu"}, win32Error, - "Couldn’t toggle full screen for Tahoe [E_FULLSCREEN_FAILED]", "无法切换 Tahoe 的全屏状态 [E_FULLSCREEN_FAILED]"}, } { - for loc, summary := range map[i18n.Locale]string{i18n.EnUS: tt.en, i18n.ZhCN: tt.zh} { - t.Run(tt.name+"/"+string(loc), func(t *testing.T) { - c := &testFullscreenClient{detail: tt.detail, vms: []reims.VMListItem{{Name: "Tahoe", State: "running", PID: &pid}}} - got, err := toggleVMFullscreen(context.Background(), "Tahoe", loc, c, func(uint32) (bool, error) { - if tt.hostError == nil { - t.Fatal("toggled a stopped or SVGA VM") - } - return false, tt.hostError - }) - want := summary - if tt.hostError != nil { - want += "\n[detail] " + tt.hostError.Error() - if !errors.Is(err, tt.hostError) { - t.Errorf("error lost original cause: %v", err) - } + if tt.name == "missing window" && runtime.GOOS != "windows" { + continue // only the Windows host looks for windows + } + for locale, want := range map[string]string{"en-US": tt.en, "zh-CN": tt.zh} { + t.Run(tt.name+"/"+locale, func(t *testing.T) { + drv := &appSecondDriver{id: driver.BuiltinReimsMacOSDriverID, vms: []driver.VMInfo{{ + Name: "Tahoe", DriverID: driver.BuiltinReimsMacOSDriverID, Directory: t.TempDir(), + State: tt.state, PID: tt.pid, DriverData: map[string]any{"graphics": tt.graphics}, + }}} + reg := plugin.NewRegistry(nil) + if err := reg.Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ID: "test.macos", Version: "1.0.0"}, Source: plugin.SourceBuiltin, Desired: true, + Activate: func(_ context.Context, sc *plugin.Scope) error { + reg.RegisterGuestDriver(sc, drv.id, drv) + return nil + }, + }); err != nil { + t.Fatal(err) } - if got || err == nil || err.Error() != want { - t.Fatalf("toggle = (%v, %v), want (false, %q)", got, err, want) + reg.Reconcile(t.Context()) + a := &App{cfg: &config.Config{DataRoot: t.TempDir(), Locale: i18n.Locale(locale)}, + lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil), + transitions: map[string]string{}, pendingChanges: map[string][]PendingChange{}} + got, err := a.ToggleVMFullscreen("Tahoe") + if got || err == nil { + t.Fatalf("toggle = (%v, %v), want an error", got, err) + } + if summary, _, _ := strings.Cut(err.Error(), "\n"); summary != want { + t.Fatalf("summary = %q, want %q", summary, want) } }) } diff --git a/internal/app/vm_close_windows.go b/internal/app/vm_close_windows.go index 8d7b789..71e2068 100644 --- a/internal/app/vm_close_windows.go +++ b/internal/app/vm_close_windows.go @@ -12,6 +12,16 @@ import ( "github.com/Nwflower/reims-go/internal/tray" ) +// runningVMPID returns the process ID of the named VM when it is running. +func runningVMPID(vms []driver.VMListItem, name string) (uint32, bool) { + for _, vm := range vms { + if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 { + return uint32(*vm.PID), true + } + } + return 0, false +} + func (a *App) confirmVMWindowClose(name string) { if _, pending := a.vmClosePrompts.LoadOrStore(name, struct{}{}); pending { return @@ -56,7 +66,7 @@ func (a *App) confirmVMWindowClose(name string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, err.Error()) return } - if current, running := findRunningVMPID(vms, ref.Name); !running || current != uint32(pid) { + if current, running := runningVMPID(vms, ref.Name); !running || current != uint32(pid) { return } if choice == host.VMCloseSuspend { diff --git a/internal/app/vm_monitor_test.go b/internal/app/vm_monitor_test.go index 529befd..4127693 100644 --- a/internal/app/vm_monitor_test.go +++ b/internal/app/vm_monitor_test.go @@ -9,7 +9,7 @@ import ( "time" "github.com/Nwflower/reims-go/internal/i18n" - "github.com/Nwflower/reims-go/internal/macos/reims" + "github.com/Nwflower/reims-go/internal/host" ) func TestLogTailDiscardsOversizeLinesAndResumes(t *testing.T) { @@ -96,11 +96,11 @@ func TestFormatBootHeartbeatAndRedactLogLine(t *testing.T) { t.Fatalf("unexpected heartbeat: %q", hb) } - redacted := reims.RedactLogLine("network user, mac 52:54:00:bc:bc:0d, ssh on 127.0.0.1:2222") + redacted := host.RedactLine("network user, mac 52:54:00:bc:bc:0d, ssh on 127.0.0.1:2222") if strings.Contains(redacted, "bc:bc:0d") || !strings.Contains(redacted, "mac [redacted]") { t.Fatalf("MAC not redacted: %q", redacted) } - redactedSerial := reims.RedactLogLine("OpenCore presents the VM as an iMac20,1, serial C02FDGY9PN5T") + redactedSerial := host.RedactLine("OpenCore presents the VM as an iMac20,1, serial C02FDGY9PN5T") if strings.Contains(redactedSerial, "C02FDGY9PN5T") || !strings.Contains(redactedSerial, "serial [redacted]") { t.Fatalf("serial not redacted: %q", redactedSerial) } diff --git a/internal/app/vm_processes.go b/internal/app/vm_processes.go index ad19b9c..3972113 100644 --- a/internal/app/vm_processes.go +++ b/internal/app/vm_processes.go @@ -11,16 +11,6 @@ import ( "github.com/Nwflower/reims-go/internal/vmstart" ) -// canScreendump reports whether the host can read a VM's screen over its QMP -// socket: the VM must declare `qmp` and must not be hosted. A VM with no -// declared capabilities is a legacy macOS VM. -func canScreendump(caps []string) bool { - if driver.IsHosted(caps) { - return false - } - return len(caps) == 0 || driver.HasCapability(caps, driver.CapQMP) -} - // readyToken and endpointSignature fold a VM's readiness and endpoints into // the poll signature, so the UI refreshes when a driver flips them. func readyToken(ready *bool) string { diff --git a/internal/app/vmref_test.go b/internal/app/vmref_test.go index 5ec2b30..e9c4d7f 100644 --- a/internal/app/vmref_test.go +++ b/internal/app/vmref_test.go @@ -35,7 +35,4 @@ func TestSameNamedVMMemoryStatesUseDriverQualifiedKeys(t *testing.T) { if a.thumbPathForDriver("test.driver.a", "shared") == a.thumbPathForDriver("test.driver.b", "shared") { t.Fatal("same-named VMs share a thumbnail path") } - if got := a.thumbPath("shared"); got != a.thumbPathForDriver("", "shared") { - t.Fatal("default thumbnail path changed") - } } diff --git a/internal/archtest/driver_isolation_test.go b/internal/archtest/driver_isolation_test.go index 9ab5df7..339b797 100644 --- a/internal/archtest/driver_isolation_test.go +++ b/internal/archtest/driver_isolation_test.go @@ -1,9 +1,6 @@ package archtest import ( - "io/fs" - "os" - "path/filepath" "strings" "testing" ) @@ -20,44 +17,14 @@ var externalDriverIDs = []string{ } func TestHostCodeNamesNoExternalDriver(t *testing.T) { - root, err := filepath.Abs(filepath.Join("..", "..")) - if err != nil { - t.Fatal(err) - } - skipDirs := map[string]bool{".git": true, ".debug": true, "build": true, "frontend": true, "node_modules": true} - scanned := 0 - err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { - if err != nil { - return err + for _, s := range sources(t) { + if s.isTest() { + continue } - rel, _ := filepath.Rel(root, path) - rel = filepath.ToSlash(rel) - if d.IsDir() { - if skipDirs[d.Name()] || rel == "internal/archtest" { - return filepath.SkipDir - } - return nil - } - if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { - return nil - } - raw, err := os.ReadFile(path) - if err != nil { - return err - } - scanned++ - text := string(raw) for _, id := range externalDriverIDs { - if strings.Contains(text, id) { - t.Errorf("%s names the external driver %q: host code must stay driver-agnostic", rel, id) + if strings.Contains(s.raw, id) { + t.Errorf("%s names the external driver %q: host code must stay driver-agnostic", s.rel, id) } } - return nil - }) - if err != nil { - t.Fatal(err) - } - if scanned < 50 { - t.Fatalf("scanned only %d Go files: the walk no longer finds the host sources", scanned) } } diff --git a/internal/archtest/locales_test.go b/internal/archtest/locales_test.go new file mode 100644 index 0000000..2f12691 --- /dev/null +++ b/internal/archtest/locales_test.go @@ -0,0 +1,75 @@ +package archtest + +import ( + "encoding/json" + "io/fs" + "os" + "path/filepath" + "regexp" + "strings" + "testing" +) + +var stringLiteral = regexp.MustCompile("[\"'`]([A-Za-z0-9_.-]+)(?:[\"'`]|[$]{|%s)") + +// Every message costs a translation in every language pack, so one that no +// code shows must go. A key also counts as used when code builds it from a +// literal prefix, such as "cli.start." + step. +func TestCatalogHasNoUnusedMessages(t *testing.T) { + literals := map[string]bool{} + collect := func(text string) { + for _, m := range stringLiteral.FindAllStringSubmatch(text, -1) { + literals[m[1]] = true + } + } + for _, s := range sources(t) { + if !strings.HasSuffix(s.rel, "_gen.go") && !s.isTest() { + collect(s.raw) + } + } + err := filepath.WalkDir(filepath.Join("..", "..", "frontend", "src"), func(p string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() || strings.Contains(p, ".gen.") { + return err + } + raw, err := os.ReadFile(p) + collect(string(raw)) + return err + }) + if err != nil { + t.Fatal(err) + } + + used := func(key string) bool { + if literals[key] { + return true + } + for i := range key { + if (key[i] == '.' || key[i] == '_') && literals[key[:i+1]] { + return true + } + } + return false + } + catalogs, err := filepath.Glob(filepath.Join("..", "..", "locales", "en-US", "*.json")) + if err != nil || len(catalogs) == 0 { + t.Fatalf("no message catalogs: %v", err) + } + for _, path := range catalogs { + if filepath.Base(path) == "macos-glossary.json" { + continue // Apple's wording, looked up by the text it translates + } + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var messages map[string]json.RawMessage + if err := json.Unmarshal(raw, &messages); err != nil { + t.Fatalf("%s: %v", path, err) + } + for key := range messages { + if !strings.HasPrefix(key, "$") && !used(key) { + t.Errorf("%s: no code shows message %q", filepath.Base(path), key) + } + } + } +} diff --git a/internal/archtest/macos_boundary_test.go b/internal/archtest/macos_boundary_test.go index ba93700..7804269 100644 --- a/internal/archtest/macos_boundary_test.go +++ b/internal/archtest/macos_boundary_test.go @@ -1,19 +1,11 @@ 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 { @@ -29,7 +21,6 @@ var macosImporters = map[string]macosImporter{ "internal/datamigrate": {src: true, test: true, why: "data layout v3 invokes and verifies the macOS-owned state and ledger migration"}, "internal/plugin/builtin": {src: true, why: "host Guest Tools bridge still uses reims argument helpers; guest registration moved to internal/macos/guest"}, "internal/guesttools": {src: true, test: true, why: "mixed: host transport and clipboard next to the macOS guest agent image"}, - "internal/plugin": {test: true, why: "sidecar manager test builds a reims-ctl stand-in"}, } // macosSourceFiles is the file-scoped native macOS boundary. plugins_flow.go @@ -48,7 +39,6 @@ var macosSourceFiles = map[string][]string{ "internal/app/macos_detail.go", "internal/app/macos_lifecycle_native.go", "internal/app/macos_settings.go", - "internal/app/macos_window.go", "internal/app/opencore_flow.go", "internal/app/plugins_flow.go", }, @@ -60,55 +50,28 @@ var macosSourceFiles = map[string][]string{ } 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 + for _, s := range sources(t) { + if isMacOSDir(s.dir()) { + continue } - 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+"/") { + for _, dir := range s.imports() { + if !isMacOSDir(dir) { continue } - dir := filepath.ToSlash(filepath.Dir(rel)) - u := found[dir] + u := found[s.dir()] if u == nil { u = &use{} - found[dir] = u + found[s.dir()] = u } - if strings.HasSuffix(path, "_test.go") { - u.test = append(u.test, rel) + if s.isTest() { + u.test = append(u.test, s.rel) } else { - u.src = append(u.src, rel) + u.src = append(u.src, s.rel) } break } - return nil - }) - if err != nil { - t.Fatal(err) } var problems []string @@ -162,14 +125,6 @@ func TestMacOSBoundary(t *testing.T) { } } -// The ratchet only means something if internal/macos exists where the test -// looks; guard against the walk silently finding nothing after a move. -func TestMacOSBoundaryRootExists(t *testing.T) { - if st, err := os.Stat(filepath.Join("..", "macos")); err != nil || !st.IsDir() { - t.Fatalf("internal/macos not found next to internal/archtest: %v", err) - } -} - // macosHostImports is the reverse ratchet: dependencies of internal/macos on // private host packages. External repositories cannot import these, so the // list must shrink to zero before macOS becomes a separate Go module. @@ -190,39 +145,16 @@ var macosHostImports = map[string]string{ } func TestMacOSDoesNotGainPrivateHostDependencies(t *testing.T) { - root, err := filepath.Abs(filepath.Join("..", "macos")) - if err != nil { - t.Fatal(err) - } found := map[string][]string{} - err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { - if err != nil { - return err + for _, s := range sources(t) { + if !isMacOSDir(s.dir()) { + continue } - if d.IsDir() || !strings.HasSuffix(path, ".go") { - return nil - } - f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly) - if err != nil { - return err - } - for _, imp := range f.Imports { - p, _ := strconv.Unquote(imp.Path.Value) - const prefix = "github.com/Nwflower/reims-go/internal/" - if !strings.HasPrefix(p, prefix) { - continue + for _, dir := range s.imports() { + if name, ok := strings.CutPrefix(dir, "internal/"); ok && !isMacOSDir(dir) { + found[name] = append(found[name], s.rel) } - name := strings.TrimPrefix(p, prefix) - if strings.HasPrefix(name, "macos") { - continue - } - rel, _ := filepath.Rel(root, path) - found[name] = append(found[name], filepath.ToSlash(rel)) } - return nil - }) - if err != nil { - t.Fatal(err) } for name, files := range found { if _, ok := macosHostImports[name]; !ok { @@ -235,3 +167,7 @@ func TestMacOSDoesNotGainPrivateHostDependencies(t *testing.T) { } } } + +func isMacOSDir(dir string) bool { + return dir == "internal/macos" || strings.HasPrefix(dir, "internal/macos/") +} diff --git a/internal/archtest/sources_test.go b/internal/archtest/sources_test.go new file mode 100644 index 0000000..296cf2b --- /dev/null +++ b/internal/archtest/sources_test.go @@ -0,0 +1,98 @@ +package archtest + +import ( + "go/ast" + "go/parser" + "go/token" + "io/fs" + "os" + "path" + "path/filepath" + "strconv" + "strings" + "sync" + "testing" +) + +const modulePath = "github.com/Nwflower/reims-go" + +// source is one Go file of the repository. All build constraints are covered: +// the checks read every file, not one platform's selection. +type source struct { + rel string // slash-separated path from the repository root + raw string + file *ast.File +} + +func (s source) dir() string { return path.Dir(s.rel) } +func (s source) isTest() bool { return strings.HasSuffix(s.rel, "_test.go") } + +// imports maps the local name of every module-internal import to its +// repository directory. +func (s source) imports() map[string]string { + out := map[string]string{} + for _, imp := range s.file.Imports { + p, err := strconv.Unquote(imp.Path.Value) + if err != nil || !strings.HasPrefix(p, modulePath+"/") { + continue + } + name := path.Base(p) + if imp.Name != nil { + name = imp.Name.Name + } + out[name] = strings.TrimPrefix(p, modulePath+"/") + } + return out +} + +var fileSet = token.NewFileSet() + +var loadSources = sync.OnceValues(func() ([]source, error) { + root, err := filepath.Abs(filepath.Join("..", "..")) + if err != nil { + return nil, err + } + skip := map[string]bool{".git": true, ".debug": true, ".local": true, "build": true, "frontend": true, "node_modules": true, "archtest": true} + var out []source + err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + if skip[d.Name()] { + return filepath.SkipDir + } + return nil + } + if !strings.HasSuffix(p, ".go") { + return nil + } + raw, err := os.ReadFile(p) + if err != nil { + return err + } + f, err := parser.ParseFile(fileSet, p, raw, parser.SkipObjectResolution) + if err != nil { + return err + } + rel, err := filepath.Rel(root, p) + if err != nil { + return err + } + out = append(out, source{rel: filepath.ToSlash(rel), raw: string(raw), file: f}) + return nil + }) + return out, err +}) + +func sources(t *testing.T) []source { + t.Helper() + all, err := loadSources() + if err != nil { + t.Fatal(err) + } + if len(all) < 300 { + t.Fatalf("found only %d Go files: the walk no longer sees the repository", len(all)) + } + return all +} diff --git a/internal/archtest/unused_test.go b/internal/archtest/unused_test.go new file mode 100644 index 0000000..0e5c966 --- /dev/null +++ b/internal/archtest/unused_test.go @@ -0,0 +1,61 @@ +package archtest + +import ( + "go/ast" + "strings" + "testing" +) + +// A function that only tests call is a second implementation the product does +// not run: delete it and test the one it does run. pkg/ is public API and +// internal/testutil exists for tests, so both are exempt. Exported methods are +// too, since interfaces and the Wails bindings call them. +func TestProductCodeHasNoUncalledFunctions(t *testing.T) { + type decl struct { + src source + fn *ast.FuncDecl + } + decls := map[string]decl{} // "." + used := map[string]bool{} + + for _, s := range sources(t) { + if s.isTest() { + continue + } + imports := s.imports() + for _, d := range s.file.Decls { + fn, _ := d.(*ast.FuncDecl) + self := "" + if fn != nil { + self = s.dir() + "." + fn.Name.Name + checked := strings.HasPrefix(s.rel, "internal/") && !strings.HasPrefix(s.rel, "internal/testutil/") || strings.HasPrefix(s.rel, "cmd/") + entry := fn.Name.Name == "main" || fn.Name.Name == "init" || fn.Name.Name == "_" + if checked && !entry && (fn.Recv == nil || !fn.Name.IsExported()) { + decls[self] = decl{s, fn} + } + } + ast.Inspect(d, func(n ast.Node) bool { + switch n := n.(type) { + case *ast.SelectorExpr: + if x, ok := n.X.(*ast.Ident); ok { + if dir, ok := imports[x.Name]; ok { + used[dir+"."+n.Sel.Name] = true + return false + } + } + case *ast.Ident: + // The declaration's own name and recursion are not callers. + if key := s.dir() + "." + n.Name; key != self { + used[key] = true + } + } + return true + }) + } + } + for key, d := range decls { + if !used[key] { + t.Errorf("%s: no product code calls %s", fileSet.Position(d.fn.Pos()), d.fn.Name.Name) + } + } +} diff --git a/internal/cli/plugin.go b/internal/cli/plugin.go index c4eddc2..5966720 100644 --- a/internal/cli/plugin.go +++ b/internal/cli/plugin.go @@ -53,7 +53,7 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, * return value, ok }, } - router := driver.NewRouterWithDataRoot(mgr.Registry(), func() string { return cfg.DataRoot }, guest.VMInventory()) + router := driver.NewRouter(mgr.Registry(), func() string { return cfg.DataRoot }, guest.VMInventory()) mgr.Registry().SetInUseChecker(router.PluginInUseChecker()) mgr.Registry().SetBusyChecker(router.PluginBusyChecker()) if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil { @@ -582,20 +582,6 @@ func printScanReports(loc i18n.Locale, reports []plugin.ScanReport, asJSON bool) return nil } -func printDoctorFindings(loc i18n.Locale, findings []plugin.DoctorFinding) error { - hasErr := false - for _, f := range findings { - fmt.Printf("[%s] (%s) %s\n", f.Severity, f.Check, f.Message) - if f.Severity == "error" { - hasErr = true - } - } - if hasErr { - return fmt.Errorf("%s", i18n.T(loc, "plugin.doctor.errors")) - } - return nil -} - func cmdPluginLocale(loc i18n.Locale, args []string) error { if len(args) == 0 { return fmt.Errorf("usage: reims-go plugin locale ...") diff --git a/internal/console/manager.go b/internal/console/manager.go index 4375f73..e692929 100644 --- a/internal/console/manager.go +++ b/internal/console/manager.go @@ -122,7 +122,7 @@ func (m *Manager) SendAbsoluteClickAndPaste(ctx context.Context, vmDir string, n focusWait = 120 * time.Millisecond } return m.withConn(ctx, vmDir, func(conn qmpSession) error { - return qmp.ClickAndPasteWithActivate(ctx, conn, normX, normY, activateClick, 550*time.Millisecond, 25*time.Millisecond, focusWait, 25*time.Millisecond, commandKey) + return qmp.ClickAndPaste(ctx, conn, normX, normY, activateClick, 550*time.Millisecond, 25*time.Millisecond, focusWait, 25*time.Millisecond, commandKey) }) } diff --git a/internal/console/manager_test.go b/internal/console/manager_test.go index 64a7458..e341eb2 100644 --- a/internal/console/manager_test.go +++ b/internal/console/manager_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "os" "path/filepath" + "strings" "sync" "sync/atomic" "testing" @@ -159,3 +160,10 @@ func TestManagerQMPOperationHoldsLifecycleFileLock(t *testing.T) { } filelock.Unlock(lockFile) } + +func TestSendPasteShortcutComboRejectsBadComboBeforeDialing(t *testing.T) { + err := NewManager().SendPasteShortcutCombo(t.Context(), t.TempDir(), "ctrl+") + if err == nil || !strings.Contains(err.Error(), "empty key") { + t.Fatalf("err = %v", err) + } +} diff --git a/internal/datamigrate/guest_migration_test.go b/internal/datamigrate/guest_migration_test.go index a03d717..55698f5 100644 --- a/internal/datamigrate/guest_migration_test.go +++ b/internal/datamigrate/guest_migration_test.go @@ -51,7 +51,10 @@ func TestV1ToV3GuestPluginMigration(t *testing.T) { if got := marker(t, vmDir); got != driver.BuiltinReimsMacOSDriverID { t.Fatalf("late v1 VM marker = %q", got) } - st := plugin.ReadState(root) + st, err := store.Load() + if err != nil { + t.Fatal(err) + } rec := st.Plugins[guest.ID] if rec == nil || !rec.Enabled { t.Fatalf("guest record = %+v", rec) diff --git a/internal/datamigrate/release_upgrade_test.go b/internal/datamigrate/release_upgrade_test.go index 5854070..47e4371 100644 --- a/internal/datamigrate/release_upgrade_test.go +++ b/internal/datamigrate/release_upgrade_test.go @@ -37,7 +37,10 @@ func TestUnstampedReleaseUpgradeRestoresOriginalBackup(t *testing.T) { if got := marker(t, vmDir); got != driver.BuiltinReimsMacOSDriverID { t.Fatalf("owner marker = %q", got) } - st := plugin.ReadState(root) + st, err := store.Load() + if err != nil { + t.Fatal(err) + } rec := st.Plugins[guest.ID] if rec == nil || guest.SettingOn(rec.AppSettings, guest.SettingWHPXFallback) || guest.SettingOn(rec.AppSettings, guest.SettingInstallGuide) { t.Fatalf("guest settings = %+v", rec) diff --git a/internal/datamigrate/vmref_settings.go b/internal/datamigrate/vmref_settings.go index 3ea346c..a4fe325 100644 --- a/internal/datamigrate/vmref_settings.go +++ b/internal/datamigrate/vmref_settings.go @@ -5,20 +5,6 @@ import ( "github.com/Nwflower/reims-go/internal/plugin" ) -// migrateVMRefSettings qualifies legacy per-VM plugin settings with the only -// driver that existed before VMRef. Existing qualified keys win field by field. -func migrateVMRefSettings(dataRoot string) error { - store := plugin.NewStateStore(plugin.NewPluginsLayout(dataRoot).Root) - st, err := store.Load() - if err != nil { - return err - } - if migrateVMRefSettingsState(st) { - return store.Save(st) - } - return nil -} - func migrateVMRefSettingsState(st *plugin.StateFile) bool { changed := false for _, rec := range st.Plugins { diff --git a/internal/datamigrate/vmref_settings_test.go b/internal/datamigrate/vmref_settings_test.go index 1a90425..ab26737 100644 --- a/internal/datamigrate/vmref_settings_test.go +++ b/internal/datamigrate/vmref_settings_test.go @@ -28,7 +28,10 @@ func TestV3MigratesVMSettingsToVMRefKeys(t *testing.T) { if err != nil || res.From != 2 || res.To != 3 { t.Fatalf("Run = %+v, %v", res, err) } - st := plugin.ReadState(root) + st, err := store.Load() + if err != nil { + t.Fatal(err) + } vals := st.Plugins["test.plugin"].VMSettings[key] if vals["legacy"] != true || vals["priority"] != "new" { t.Fatalf("merged settings = %+v", vals) diff --git a/internal/driver/driver.go b/internal/driver/driver.go index 51d637c..cc33f87 100644 --- a/internal/driver/driver.go +++ b/internal/driver/driver.go @@ -316,11 +316,10 @@ const HostedReportMaxAge = 15 * time.Second // Router aggregates active guest drivers from the plugin Registry and routes // VM operations by ownership (§5.3). type Router struct { - reg *plugin.Registry - dataRootDir func() string // DataRoot for statically declared guest VM roots - legacyVMRoot func() string // compatibility root for tests and older embedders - inventories []VMInventory - states *StateTable + reg *plugin.Registry + dataRootDir func() string // DataRoot for statically declared guest VM roots + inventories []VMInventory + states *StateTable } // SetStateTable attaches the table of driver-reported VM states that @@ -345,14 +344,9 @@ type VMInventory struct { List func(dataRoot string) ([]VMInfo, error) } -// NewRouter creates a driver Router backed by reg. -func NewRouter(reg *plugin.Registry, vmRootDir func() string) *Router { - return &Router{reg: reg, legacyVMRoot: vmRootDir} -} - -// NewRouterWithDataRoot discovers unavailable VMs through driver inventories +// NewRouter discovers unavailable VMs through driver inventories // or through ownership markers in declared roots. -func NewRouterWithDataRoot(reg *plugin.Registry, dataRootDir func() string, inventories ...VMInventory) *Router { +func NewRouter(reg *plugin.Registry, dataRootDir func() string, inventories ...VMInventory) *Router { return &Router{reg: reg, dataRootDir: dataRootDir, inventories: inventories} } @@ -379,9 +373,6 @@ func (rt *Router) vmRoots() []string { } } } - if rt != nil && rt.legacyVMRoot != nil { - add(rt.legacyVMRoot()) - } return roots } diff --git a/internal/driver/driver_test.go b/internal/driver/driver_test.go index ec7b799..c6eb75a 100644 --- a/internal/driver/driver_test.go +++ b/internal/driver/driver_test.go @@ -16,25 +16,43 @@ type fakeDriver struct { vms []VMInfo } -func (f *fakeDriver) ID() string { return f.id } -func (f *fakeDriver) DisplayName() plugin.LocalizedText { return plugin.LocalizedText{EnUS: f.id} } -func (f *fakeDriver) RuntimeKind() string { return "qemu-ovmf" } -func (f *fakeDriver) RuntimeAPIRange() string { return "^1.0.0" } -func (f *fakeDriver) Capabilities() []string { return []string{CapCloudInit, CapSSH} } -func (f *fakeDriver) CreateSchema() *plugin.SettingsSchema { return nil } -func (f *fakeDriver) SettingsSchema() *plugin.SettingsSchema { return nil } -func (f *fakeDriver) List(context.Context) ([]VMInfo, error) { return f.vms, nil } -func (f *fakeDriver) Show(_ context.Context, n string) (VMInfo, error) { return VMInfo{Name: n, DriverID: f.id}, nil } -func (f *fakeDriver) ValidateCreate(context.Context, CreateRequest) []ValidationIssue { return nil } -func (f *fakeDriver) Create(context.Context, CreateRequest, io.Writer, io.Writer) error { return nil } -func (f *fakeDriver) ValidateSet(context.Context, SetRequest) []ValidationIssue { return nil } -func (f *fakeDriver) Set(context.Context, SetRequest, io.Writer, io.Writer) error { return nil } -func (f *fakeDriver) Start(context.Context, StartRequest) (StartResult, error) { return StartResult{}, nil } -func (f *fakeDriver) Stop(context.Context, string, bool, io.Writer, io.Writer) error { return nil } -func (f *fakeDriver) Delete(context.Context, string, bool, io.Writer, io.Writer) error { return nil } +func (f *fakeDriver) ID() string { return f.id } +func (f *fakeDriver) DisplayName() plugin.LocalizedText { return plugin.LocalizedText{EnUS: f.id} } +func (f *fakeDriver) RuntimeKind() string { return "qemu-ovmf" } +func (f *fakeDriver) RuntimeAPIRange() string { return "^1.0.0" } +func (f *fakeDriver) Capabilities() []string { return []string{CapCloudInit, CapSSH} } +func (f *fakeDriver) CreateSchema() *plugin.SettingsSchema { return nil } +func (f *fakeDriver) SettingsSchema() *plugin.SettingsSchema { return nil } +func (f *fakeDriver) List(context.Context) ([]VMInfo, error) { return f.vms, nil } +func (f *fakeDriver) Show(_ context.Context, n string) (VMInfo, error) { + return VMInfo{Name: n, DriverID: f.id}, nil +} +func (f *fakeDriver) ValidateCreate(context.Context, CreateRequest) []ValidationIssue { return nil } +func (f *fakeDriver) Create(context.Context, CreateRequest, io.Writer, io.Writer) error { return nil } +func (f *fakeDriver) ValidateSet(context.Context, SetRequest) []ValidationIssue { return nil } +func (f *fakeDriver) Set(context.Context, SetRequest, io.Writer, io.Writer) error { return nil } +func (f *fakeDriver) Start(context.Context, StartRequest) (StartResult, error) { + return StartResult{}, nil +} +func (f *fakeDriver) Stop(context.Context, string, bool, io.Writer, io.Writer) error { return nil } +func (f *fakeDriver) Delete(context.Context, string, bool, io.Writer, io.Writer) error { return nil } + +// declareVMRoot registers an installed but disabled driver plugin that keeps +// its VMs in /vms. +func declareVMRoot(t *testing.T, reg *plugin.Registry, driverID string) { + t.Helper() + if err := reg.Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ID: "test.disabled-driver", Version: "1.0.0", + Contributes: plugin.Contributes{GuestDrivers: []plugin.GuestDriverContribution{{ID: driverID, VMRoots: []string{"vms"}}}}}, + Source: plugin.SourceBuiltin, + }); err != nil { + t.Fatal(err) + } +} func TestOwnerMarkerZeroMigrationAndRouterUnavailable(t *testing.T) { - vmRoot := t.TempDir() + dataRoot := t.TempDir() + vmRoot := filepath.Join(dataRoot, "vms") legacyVM := filepath.Join(vmRoot, "macos-tahoe") _ = os.MkdirAll(legacyVM, 0o755) if got := ReadOwnerDriver(legacyVM); got != BuiltinReimsMacOSDriverID { @@ -63,8 +81,9 @@ func TestOwnerMarkerZeroMigrationAndRouterUnavailable(t *testing.T) { }, }) reg.Reconcile(context.Background()) + declareVMRoot(t, reg, "reims.driver.linux") - router := NewRouter(reg, func() string { return vmRoot }) + router := NewRouter(reg, func() string { return dataRoot }) all, err := router.ListAllVMs(context.Background()) if err != nil { t.Fatal(err) @@ -97,7 +116,8 @@ func TestRenamedDriverKeepsMarkedVMsVisible(t *testing.T) { RenamedDriverIDs[BuiltinReimsMacOSDriverID] = newID t.Cleanup(func() { delete(RenamedDriverIDs, BuiltinReimsMacOSDriverID) }) - vmRoot := t.TempDir() + dataRoot := t.TempDir() + vmRoot := filepath.Join(dataRoot, "vms") vmDir := filepath.Join(vmRoot, "macos-tahoe") if err := WriteOwnerDriver(vmDir, BuiltinReimsMacOSDriverID); err != nil { t.Fatal(err) @@ -106,7 +126,9 @@ func TestRenamedDriverKeepsMarkedVMsVisible(t *testing.T) { t.Fatalf("renamed owner = %q, want %q", got, newID) } - router := NewRouter(plugin.NewRegistry(nil), func() string { return vmRoot }) + reg := plugin.NewRegistry(nil) + declareVMRoot(t, reg, newID) + router := NewRouter(reg, func() string { return dataRoot }) all, err := router.ListAllVMs(context.Background()) if err != nil { t.Fatal(err) diff --git a/internal/driver/vmref_test.go b/internal/driver/vmref_test.go index 558ce1a..6c9fdae 100644 --- a/internal/driver/vmref_test.go +++ b/internal/driver/vmref_test.go @@ -57,7 +57,7 @@ func TestRouterScansDeclaredVMRoots(t *testing.T) { }, Source: plugin.SourceBuiltin}); err != nil { t.Fatal(err) } - router := NewRouterWithDataRoot(reg, func() string { return dataRoot }) + router := NewRouter(reg, func() string { return dataRoot }) vms, err := router.ListAllVMs(context.Background()) if err != nil || len(vms) != 1 || !vms[0].DriverUnavailable { t.Fatalf("ListAllVMs = %+v, %v", vms, err) diff --git a/internal/host/fonts_other.go b/internal/host/fonts_other.go index b14b0a7..080b58b 100644 --- a/internal/host/fonts_other.go +++ b/internal/host/fonts_other.go @@ -4,10 +4,6 @@ package host import "github.com/Nwflower/reims-go/internal/i18n" -func CheckMissingLocaleFonts(locale string) string { - return "" -} - func CheckMissingLocaleFontsForUI(targetLocale string, uiLocale i18n.Locale) string { return "" } diff --git a/internal/host/fonts_windows.go b/internal/host/fonts_windows.go index 3a4bf14..15409ef 100644 --- a/internal/host/fonts_windows.go +++ b/internal/host/fonts_windows.go @@ -65,14 +65,6 @@ func hasInstalledFontFamily(name string) bool { return fontDetectHit } -// CheckMissingLocaleFonts checks whether Windows has at least one modern UI -// font installed for the East Asian script required by locale (detecting missing -// Windows Features-on-Demand supplemental font packages on non-CJK Windows installs). -// Returns "" when fonts are present or not needed, or a localized script label. -func CheckMissingLocaleFonts(locale string) string { - return CheckMissingLocaleFontsForUI(locale, i18n.ResolveLocale(locale)) -} - // CheckMissingLocaleFontsForUI checks whether Windows has fonts for targetLocale // and returns the localized script name in uiLocale when missing. func CheckMissingLocaleFontsForUI(targetLocale string, uiLocale i18n.Locale) string { diff --git a/internal/host/foreground_other.go b/internal/host/foreground_other.go index dc62b0a..106bb85 100644 --- a/internal/host/foreground_other.go +++ b/internal/host/foreground_other.go @@ -5,9 +5,6 @@ package host // ForegroundPID is not implemented off Windows and always reports no owner. func ForegroundPID() uint32 { return 0 } -// FocusProcessWindow is not implemented off Windows. -func FocusProcessWindow(uint32) bool { return false } - // FocusProcessTreeWindow is not implemented off Windows. func FocusProcessTreeWindow([]uint32) bool { return false } diff --git a/internal/host/foreground_windows.go b/internal/host/foreground_windows.go index f9d252d..355e691 100644 --- a/internal/host/foreground_windows.go +++ b/internal/host/foreground_windows.go @@ -73,12 +73,6 @@ func enumFocusWindowProc(hwnd uintptr, _ uintptr) uintptr { return 1 } -// FocusProcessWindow finds the primary visible top-level window belonging to -// pid, restores it if minimized, and brings it to the foreground. -func FocusProcessWindow(pid uint32) bool { - return FocusProcessTreeWindow([]uint32{pid}) -} - // FocusProcessTreeWindow does the same for a launcher and the child processes // it started: the first visible top-level window of any of pids is focused. func FocusProcessTreeWindow(pids []uint32) bool { diff --git a/internal/host/fullscreen_other.go b/internal/host/fullscreen_other.go index 8eef1c9..004cd73 100644 --- a/internal/host/fullscreen_other.go +++ b/internal/host/fullscreen_other.go @@ -4,17 +4,9 @@ package host import "errors" -// IsProcessWindowFullscreen is not implemented off Windows. -func IsProcessWindowFullscreen(uint32) bool { return false } - // IsProcessTreeWindowFullscreen is not implemented off Windows. func IsProcessTreeWindowFullscreen([]uint32) bool { return false } -// ToggleProcessWindowFullscreen is not implemented off Windows. -func ToggleProcessWindowFullscreen(uint32) (bool, error) { - return false, errors.New("toggling a VM window's full screen mode is only supported on Windows") -} - // ToggleProcessTreeWindowFullscreen is not implemented off Windows. func ToggleProcessTreeWindowFullscreen([]uint32) (bool, error) { return false, errors.New("toggling a VM window's full screen mode is only supported on Windows") diff --git a/internal/host/fullscreen_windows.go b/internal/host/fullscreen_windows.go index a7d4b5f..8d24899 100644 --- a/internal/host/fullscreen_windows.go +++ b/internal/host/fullscreen_windows.go @@ -168,11 +168,6 @@ func liveWindowPID(hwnd uintptr) uint32 { return windowPID(hwnd) } -// IsProcessWindowFullscreen reports whether the selected display window fills its monitor without a frame. -func IsProcessWindowFullscreen(pid uint32) bool { - return IsProcessTreeWindowFullscreen([]uint32{pid}) -} - // IsProcessTreeWindowFullscreen is IsProcessWindowFullscreen for a process tree. func IsProcessTreeWindowFullscreen(pids []uint32) bool { fullscreenState.prune(liveWindowPID) @@ -200,12 +195,6 @@ func IsProcessTreeWindowFullscreen(pids []uint32) bool { return err == nil && isBorderlessFullscreenRect(style, rect, WindowRect(monitor.Monitor)) } -// ToggleProcessWindowFullscreen switches the selected display window between -// borderless fullscreen and windowed mode. -func ToggleProcessWindowFullscreen(pid uint32) (bool, error) { - return ToggleProcessTreeWindowFullscreen([]uint32{pid}) -} - // ToggleProcessTreeWindowFullscreen is ToggleProcessWindowFullscreen for a // process tree: the display window may belong to any of pids. func ToggleProcessTreeWindowFullscreen(pids []uint32) (bool, error) { diff --git a/internal/host/host_other.go b/internal/host/host_other.go index f9673dd..3a51243 100644 --- a/internal/host/host_other.go +++ b/internal/host/host_other.go @@ -37,10 +37,6 @@ func ProbeVulkanGPUs() []GPUInfo { return nil } -func PinProcessToPCores(pid uint32, mask uint64) error { - return SetProcessAffinityMask(pid, mask) -} - func SetProcessAffinityMask(pid uint32, mask uint64) error { return fmt.Errorf("process CPU affinity is only supported on Windows (current OS: %s)", runtime.GOOS) } @@ -52,7 +48,3 @@ func GetProcessAffinityMask(pid uint32) (uint64, uint64, error) { func DisableProcessPowerThrottling(pid uint32) error { return fmt.Errorf("process power throttling control is only supported on Windows (current OS: %s)", runtime.GOOS) } - -func EnableWHPXElevated() error { - return fmt.Errorf("WHPX elevation is only supported on Windows (current OS: %s)", runtime.GOOS) -} diff --git a/internal/host/host_windows.go b/internal/host/host_windows.go index 6c42092..a7d790b 100644 --- a/internal/host/host_windows.go +++ b/internal/host/host_windows.go @@ -3,7 +3,6 @@ package host import ( - "context" "encoding/binary" "fmt" "math/bits" @@ -38,11 +37,11 @@ var ( ) const ( - hkeyLocalMachine = 0x80000002 - keyRead = 0x20019 - regSZ = 1 - regExpandSZ = 2 - regMultiSZ = 7 + hkeyLocalMachine = 0x80000002 + keyRead = 0x20019 + regSZ = 1 + regExpandSZ = 2 + regMultiSZ = 7 processSetInformation = 0x0200 processQueryLimitedInformation = 0x1000 processPowerThrottlingClass = 4 @@ -197,11 +196,6 @@ func Inspect(dataRoot string) Report { return rep } -// PinProcessToPCores restricts the given PID's affinity mask to the given bitmask. -func PinProcessToPCores(pid uint32, mask uint64) error { - return SetProcessAffinityMask(pid, mask) -} - // SetProcessAffinityMask sets the Win32 processor affinity mask for pid. func SetProcessAffinityMask(pid uint32, mask uint64) error { if mask == 0 { @@ -273,17 +267,6 @@ func DisableProcessPowerThrottling(pid uint32) error { return nil } -// EnableWHPXElevated invokes a standard Windows UAC prompt to enable Windows -// Hypervisor Platform (if missing) and set hypervisorlaunchtype to auto. -func EnableWHPXElevated() error { - return SetHypervisorBootElevated(context.Background(), true) -} - -func probeWHPX() WHPXState { - st, _ := probeWHPXAndFirmware() - return st -} - func probeWHPXAndFirmware() (WHPXState, bool) { firmwareVirt := probeFirmwareVirtEnabled() mod := syscall.NewLazyDLL("WinHvPlatform.dll") diff --git a/internal/host/hypervisor.go b/internal/host/hypervisor.go index b074105..61b0c73 100644 --- a/internal/host/hypervisor.go +++ b/internal/host/hypervisor.go @@ -157,10 +157,6 @@ func RecordPendingHypervisorBoot(dataRoot string, liveState WHPXState, enable bo return recordPendingHypervisorBootSession(dataRoot, liveState, enable, currentBootSession()) } -func recordPendingHypervisorBootAt(dataRoot string, liveState WHPXState, enable bool, bootEpoch int64) string { - return recordPendingHypervisorBootSession(dataRoot, liveState, enable, bootSession{EpochSec: bootEpoch}) -} - func recordPendingHypervisorBootSession(dataRoot string, liveState WHPXState, enable bool, sess bootSession) string { target := ResolvePendingHypervisorTarget(liveState, enable) pendingBootMu.Lock() @@ -208,10 +204,6 @@ func ReadPendingHypervisorBoot(dataRoot string, liveState WHPXState) string { return readPendingHypervisorBootSession(dataRoot, liveState, currentBootSession()) } -func readPendingHypervisorBootAt(dataRoot string, liveState WHPXState, bootEpoch int64) string { - return readPendingHypervisorBootSession(dataRoot, liveState, bootSession{EpochSec: bootEpoch}) -} - func readPendingHypervisorBootSession(dataRoot string, liveState WHPXState, sess bootSession) string { if !sess.valid() { return "" diff --git a/internal/host/hypervisor_test.go b/internal/host/hypervisor_test.go index 5d53262..9a9b19e 100644 --- a/internal/host/hypervisor_test.go +++ b/internal/host/hypervisor_test.go @@ -104,6 +104,15 @@ func TestPendingHypervisorBootLifecycle(t *testing.T) { } } +// The epoch-only helpers stand in for a boot session without a volatile marker. +func recordPendingHypervisorBootAt(dataRoot string, liveState WHPXState, enable bool, bootEpoch int64) string { + return recordPendingHypervisorBootSession(dataRoot, liveState, enable, bootSession{EpochSec: bootEpoch}) +} + +func readPendingHypervisorBootAt(dataRoot string, liveState WHPXState, bootEpoch int64) string { + return readPendingHypervisorBootSession(dataRoot, liveState, bootSession{EpochSec: bootEpoch}) +} + func TestPendingHypervisorBootUndoAcrossDataRoots(t *testing.T) { defer func() { pendingBootMu.Lock() @@ -185,4 +194,3 @@ func TestPendingHypervisorBootFastRebootAndSleepResilience(t *testing.T) { t.Fatalf("fallback fast reboot with reset TickMs must expire pending state, got %q", got) } } - diff --git a/internal/host/hypervisor_windows.go b/internal/host/hypervisor_windows.go index 7974aed..5b52ad5 100644 --- a/internal/host/hypervisor_windows.go +++ b/internal/host/hypervisor_windows.go @@ -68,10 +68,6 @@ func currentBootSession() bootSession { } } -func currentBootEpochSec() int64 { - return currentBootSession().EpochSec -} - // probeVolatileBootMarker reads the LastWriteTime of HKLM\HARDWARE\DESCRIPTION\System, // an in-memory REG_OPTION_VOLATILE hive recreated by the Windows kernel on every OS // boot. Unlike wall-clock minus GetTickCount64, it stays constant across S3 sleep, diff --git a/internal/host/progress_parse_test.go b/internal/host/progress_parse_test.go new file mode 100644 index 0000000..69bad39 --- /dev/null +++ b/internal/host/progress_parse_test.go @@ -0,0 +1,26 @@ +package host + +import "testing" + +func TestParseCtlLine(t *testing.T) { + // Formats from reims_util.rs:480-488 and its test at :777-786. + u, _ := ParseCtlLine("downloading the macOS Tahoe 26 recovery image: 45% of 2.0 GB") + if u.Kind != KindProgress || u.Step != "downloading the macOS Tahoe 26 recovery image" || u.Percent != 45 || u.Total != 2_000_000_000 { + t.Fatalf("percent line = %+v", u) + } + u, _ = ParseCtlLine("macos-tahoe: downloading OpenCore 1.0.8: 5% of 11 MB") + if u.Step != "macos-tahoe: downloading OpenCore 1.0.8" || u.Total != 11_000_000 { + t.Fatalf("ctl-prefixed line = %+v", u) + } + u, _ = ParseCtlLine("downloading the installer: 300 MB") + if u.Kind != KindProgress || u.Percent != -1 || u.Done != 300_000_000 { + t.Fatalf("size line = %+v", u) + } + u, _ = ParseCtlLine("creating the disk") + if u.Kind != KindNote || u.Message != "creating the disk" { + t.Fatalf("note = %+v", u) + } + if _, ok := ParseCtlLine(" "); ok { + t.Fatal("blank line") + } +} diff --git a/internal/host/smbios_memory.go b/internal/host/smbios_memory.go index 172d5d6..6e322f8 100644 --- a/internal/host/smbios_memory.go +++ b/internal/host/smbios_memory.go @@ -2,7 +2,6 @@ package host import ( "encoding/binary" - "fmt" ) // HostMemorySpec describes the host's physical memory speed and generation @@ -13,22 +12,6 @@ type HostMemorySpec struct { 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 { diff --git a/internal/host/smbios_memory_test.go b/internal/host/smbios_memory_test.go index de0c837..5fb9ced 100644 --- a/internal/host/smbios_memory_test.go +++ b/internal/host/smbios_memory_test.go @@ -44,9 +44,6 @@ func TestParseSMBIOSType17DDR5ConfiguredSpeed(t *testing.T) { 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) { @@ -86,7 +83,7 @@ func TestProbeHostMemorySpecLiveWindows(t *testing.T) { t.Skip("Windows live SMBIOS probe test") } spec := probeHostMemorySpec() - t.Logf("live Windows host memory spec: %+v (%q)", spec, FormatMemorySpec(spec)) + t.Logf("live Windows host memory spec: %+v", spec) if spec != nil && (spec.SpeedMHz < 200 || spec.SpeedMHz > 65535) { t.Fatalf("out-of-range live SpeedMHz: %+v", spec) } diff --git a/internal/host/stats.go b/internal/host/stats.go index 0ecd556..7615319 100644 --- a/internal/host/stats.go +++ b/internal/host/stats.go @@ -251,22 +251,6 @@ func resolveDiskPathFromVMToml(vmDir string) string { return filepath.Join(vmDir, "disk.qcow2") } -// readQCOW2VirtualSize reads the 8-byte big-endian virtual size from a QCOW2 -// header (magic "QFI\xfb", version 2 or 3, size at byte offset 24). -func readQCOW2VirtualSize(path string) (uint64, bool) { - size, _, _, ok := readQCOW2HeaderMeta(path) - return size, ok -} - -func readQCOW2HeaderMeta(path string) (virtualSize uint64, extendedL2 bool, snapshotCount uint32, ok bool) { - f, err := os.Open(path) - if err != nil { - return 0, false, 0, false - } - defer f.Close() - return decodeQCOW2HeaderMeta(f) -} - func decodeQCOW2HeaderMeta(f io.ReaderAt) (virtualSize uint64, extendedL2 bool, snapshotCount uint32, ok bool) { var hdr [104]byte n, err := f.ReadAt(hdr[:], 0) diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 8374445..485799c 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -76,10 +76,6 @@ var catalog = map[Locale]map[string]string{ "copy": "复制", "copyTechInfo": "复制技术信息", "core.preflight.whpx_irqchip_advice": "宿主不支持 nested-virt 属性且当前运行时未包含非致命降级补丁,启动虚拟机时将自动附加 kernel-irqchip=off", - "core.start.warn.offline_helper_skipped": "已跳过离线装机辅助盘挂载:{err}", - "core.start.warn.opencore_lang_failed": "未能向 OpenCore 写入客户机语言设置:{err}", - "core.start.warn.opencore_picker_failed": "未能更新 OpenCore 启动选择器配置:{err}", - "core.start.warn.whpx_irqchip_applied": "宿主拒绝了嵌套虚拟化属性,已自动启用 kernel-irqchip=off 兼容参数", "dataRootChooseOther": "选择其他数据目录", "dataRootChooseTitle": "选择数据目录", "dataRootReadOnlyDetail": "详细信息", @@ -619,7 +615,6 @@ var catalog = map[Locale]map[string]string{ "tray.menu.suspend": "挂起(&P)", "tray.menu.toggle_fullscreen": "切换全屏", "tray.notify.app_window_paste_retry": "剪贴板尚未同步,再试一次", - "tray.notify.discard_suspend_fail": "无法放弃 {name} 的挂起状态", "tray.notify.focus_fail": "找不到 {name} 的窗口", "tray.notify.force_stop_fail": "无法强制关机 {name}", "tray.notify.fullscreen_fail": "无法切换 {name} 全屏", @@ -632,8 +627,6 @@ var catalog = map[Locale]map[string]string{ "tray.notify.stop_fail": "无法关机 {name}", "tray.notify.suspend_fail": "无法挂起 {name}", "tray.running": "{count, plural, =1 {Reims-Go — 1 台虚拟机运行中} other {Reims-Go — # 台虚拟机运行中}}", - "tray.running.many": "Reims-Go — {count} 台虚拟机运行中", - "tray.running.one": "Reims-Go — 1 台虚拟机运行中", "tray.state.broken": "配置损坏", "tray.state.resuming": "正在恢复…", "tray.state.running": "运行中", @@ -688,21 +681,16 @@ var catalog = map[Locale]map[string]string{ "viewLogs": "查看日志", "vm.already_running": "{name} 已在运行中", "vm.compact.done": "{name}:磁盘已瘦身 {before, number, .2} GB -> {after, number, .2} GB(回收 {saved, number, .2} GB)", - "vm.compact.stop_first": "请先停止 {name} 再回收磁盘空间", "vm.empty": "当前没有已创建的虚拟机。", "vm.install_guide.step1": "1. 打开「磁盘工具」,选中「QEMU HARDDISK Media」并点「抹掉」(格式选 APFS)。", "vm.install_guide.step2": "2. 回到「恢复」窗口,选「重新安装 macOS」,装到刚抹掉的磁盘上(中途会自动重启几次)。", "vm.install_guide.step3": "3. 看到「设置助理」后,运行 `reims-go vm eject {name}`(或在界面点「退出恢复模式」)移除安装盘,下次启动生效。", "vm.install_guide.title": "macOS 装机步骤(简体中文恢复界面):", "vm.resize.done": "{name}:虚拟磁盘已扩容 {before, number, .0} GB -> {after, number, .0} GB\n请在 macOS 终端执行以下命令扩展 APFS 容器:\n {cmd}", - "vm.resize.stop_first": "请先停止 {name} 再扩容虚拟磁盘", "vm.typed": "{count, plural, other {已敲入 # 个键。}}", "vmstart.compat.nested_virt": "[兼容] 当前 Windows 不支持嵌套虚拟化属性({code}),已自动启用 kernel-irqchip=off", "vmstart.nested_vmx.invalid": "无法读取嵌套虚拟化设置。虚拟机将按默认 CPU 设置启动。", "vmstart.nested_vmx.unavailable": "当前 Windows 宿主机和中断控制器设置无法启用嵌套虚拟化。", - "vmstart.pin.non_lpe": "[CPU] 虚拟机配置了 {vcpus} vCPU(超过 {pthreads} 个 P 核线程),已自动将 QEMU (PID {pid}) 绑定到 P+E 核({cores} 核 / {threads} 线程,掩码 {mask};仅排除 {lpe} 个慢速 LP-E 核)", - "vmstart.pin.pcores": "[CPU] 已将 QEMU (PID {pid}) 绑定到 {cores} 个 P 核({threads} 个逻辑线程,掩码 {mask};未占用 {excluded} 个 E 核)", - "vmstart.pin.skipped": "[CPU] 跳过绑核:虚拟机配置了 {vcpus} vCPU,超过可用安全绑定线程上限(P 核仅 {pthreads} 线程),已使用全部核心避免超售卡顿", "window.close.description": "关机将请求系统关闭。挂起会保存当前会话。", "window.close.description_no_suspend": "当前运行时不支持挂起。关机将请求系统关闭。", "window.close.suspend": "挂起", @@ -781,10 +769,6 @@ var catalog = map[Locale]map[string]string{ "copy": "Copy", "copyTechInfo": "Copy technical details", "core.preflight.whpx_irqchip_advice": "Host lacks nested-virt property and runtime lacks nested-virt-nonfatal capability; kernel-irqchip=off will be auto-applied", - "core.start.warn.offline_helper_skipped": "Offline install helper disk skipped: {err}", - "core.start.warn.opencore_lang_failed": "Could not apply macOS language to OpenCore: {err}", - "core.start.warn.opencore_picker_failed": "Could not update OpenCore boot picker: {err}", - "core.start.warn.whpx_irqchip_applied": "Host rejects nested-virtualization property; enabled kernel-irqchip=off automatically", "dataRootChooseOther": "Choose another data folder", "dataRootChooseTitle": "Choose data folder", "dataRootReadOnlyDetail": "Details", @@ -1324,7 +1308,6 @@ var catalog = map[Locale]map[string]string{ "tray.menu.suspend": "Sus&pend", "tray.menu.toggle_fullscreen": "Toggle full screen", "tray.notify.app_window_paste_retry": "Clipboard is still syncing. Try pasting again", - "tray.notify.discard_suspend_fail": "Couldn't discard saved state for {name}", "tray.notify.focus_fail": "Couldn't find the window of {name}", "tray.notify.force_stop_fail": "Couldn't force shut down {name}", "tray.notify.fullscreen_fail": "Couldn’t toggle full screen for {name}", @@ -1337,8 +1320,6 @@ var catalog = map[Locale]map[string]string{ "tray.notify.stop_fail": "Couldn't shut down {name}", "tray.notify.suspend_fail": "Couldn't suspend {name}", "tray.running": "{count, plural, one {Reims-Go — # VM running} other {Reims-Go — # VMs running}}", - "tray.running.many": "Reims-Go — {count} VMs running", - "tray.running.one": "Reims-Go — 1 VM running", "tray.state.broken": "Broken", "tray.state.resuming": "Resuming…", "tray.state.running": "Running", @@ -1393,21 +1374,16 @@ var catalog = map[Locale]map[string]string{ "viewLogs": "View logs", "vm.already_running": "{name} is already running", "vm.compact.done": "{name}: compacted disk {before, number, .2} GB -> {after, number, .2} GB (reclaimed {saved, number, .2} GB)", - "vm.compact.stop_first": "stop {name} before compacting its disk", "vm.empty": "No virtual machines found.", "vm.install_guide.step1": "1. Open 'Disk Utility', select 'QEMU HARDDISK Media', and Erase as APFS.", "vm.install_guide.step2": "2. Back in the Recovery window, choose 'Reinstall macOS' and install onto the disk you erased (it restarts a few times).", "vm.install_guide.step3": "3. When Setup Assistant appears, run `reims-go vm eject {name}` (or click 'Exit recovery mode') to remove the installer at next start.", "vm.install_guide.title": "macOS Setup Steps (Recovery UI):", "vm.resize.done": "{name}: expanded disk {before, number, .0} GB -> {after, number, .0} GB\nRun inside macOS Terminal to expand APFS:\n {cmd}", - "vm.resize.stop_first": "stop {name} before resizing its disk", "vm.typed": "{count, plural, one {Typed # key.} other {Typed # keys.}}", "vmstart.compat.nested_virt": "[compat] Host rejects nested-virtualization property ({code}); enabled kernel-irqchip=off automatically", "vmstart.nested_vmx.invalid": "The nested virtualization setting could not be read. Starting with the default CPU settings.", "vmstart.nested_vmx.unavailable": "Nested virtualization is unavailable with the current Windows host and interrupt controller settings.", - "vmstart.pin.non_lpe": "[CPU] VM has {vcpus} vCPUs (exceeds {pthreads} P-core threads); pinned QEMU (PID {pid}) to P+E cores ({cores} cores / {threads} logical CPUs, mask {mask}; {lpe} slow LP-E cores excluded)", - "vmstart.pin.pcores": "[CPU] Pinned QEMU (PID {pid}) to {cores} P-cores ({threads} logical CPUs, mask {mask}; {excluded} E/LP-E cores excluded)", - "vmstart.pin.skipped": "[CPU] Skipped CPU pinning: VM has {vcpus} vCPUs, exceeding safe headroom (only {pthreads} P-core threads); using all host CPUs to avoid spinlock stall", "window.close.description": "Shut down asks macOS to shut down. Suspend saves the session.", "window.close.description_no_suspend": "The current runtime does not support suspend. Shut down asks macOS to shut down.", "window.close.suspend": "Suspend", @@ -1438,9 +1414,6 @@ var paramOrder = map[string][]string{ "cli.start.spawning_tray": {"name"}, "cli.start.timeout": {"name", "timeout"}, "compat.gpu_icd_rebound": {"old", "new"}, - "core.start.warn.offline_helper_skipped": {"err"}, - "core.start.warn.opencore_lang_failed": {"err"}, - "core.start.warn.opencore_picker_failed": {"err"}, "doctor.cow_chain.broken": {"vm", "depth", "path"}, "doctor.cow_chain.item": {"vm", "depth", "warn"}, "doctor.ecores.detail": {"count", "cpus"}, @@ -1574,7 +1547,6 @@ var paramOrder = map[string][]string{ "toastInstallerReady": {"v"}, "toastRuntimeReady": {"v"}, "toastSSHConfigWritten": {"alias"}, - "tray.notify.discard_suspend_fail": {"name"}, "tray.notify.focus_fail": {"name"}, "tray.notify.force_stop_fail": {"name"}, "tray.notify.fullscreen_fail": {"name"}, @@ -1585,7 +1557,6 @@ var paramOrder = map[string][]string{ "tray.notify.stop_fail": {"name"}, "tray.notify.suspend_fail": {"name"}, "tray.running": {"count"}, - "tray.running.many": {"count"}, "updateCapsuleAvailable": {"v"}, "updateCapsuleDownloadingPct": {"p"}, "updateCapsuleReady": {"v"}, @@ -1602,14 +1573,9 @@ var paramOrder = map[string][]string{ "validate.name_taken": {"name"}, "vm.already_running": {"name"}, "vm.compact.done": {"name", "before", "after", "saved"}, - "vm.compact.stop_first": {"name"}, "vm.install_guide.step3": {"name"}, "vm.resize.done": {"name", "before", "after", "cmd"}, - "vm.resize.stop_first": {"name"}, "vm.typed": {"count"}, "vmstart.compat.nested_virt": {"code"}, - "vmstart.pin.non_lpe": {"vcpus", "pthreads", "pid", "cores", "threads", "mask", "lpe"}, - "vmstart.pin.pcores": {"pid", "cores", "threads", "mask", "excluded"}, - "vmstart.pin.skipped": {"vcpus", "pthreads"}, "window.close.title": {"name"}, } diff --git a/internal/i18n/i18n.go b/internal/i18n/i18n.go index c12ab7b..112977c 100644 --- a/internal/i18n/i18n.go +++ b/internal/i18n/i18n.go @@ -95,14 +95,6 @@ func rewriteLegacyPositionalVerbs(s string) string { return b.String() } -// HasPluginLocale reports whether an active plugin pack provides translations for loc. -func HasPluginLocale(loc Locale) bool { - pluginCatalogMu.RLock() - _, ok := pluginCatalogs[loc] - pluginCatalogMu.RUnlock() - return ok -} - func primarySubtag(tag string) string { s := strings.ToLower(strings.TrimSpace(tag)) if idx := strings.IndexAny(s, "-_"); idx >= 0 { diff --git a/internal/macos/guest/guest.go b/internal/macos/guest/guest.go index 485fcfb..5d3f497 100644 --- a/internal/macos/guest/guest.go +++ b/internal/macos/guest/guest.go @@ -42,27 +42,6 @@ func SettingOn(vals map[string]any, key string) bool { return true } -// SettingOnInState reads a setting without starting a Manager. Explicit -// values on the new plugin win over the released former core record. -func SettingOnInState(st *plugin.StateFile, key string) bool { - if st == nil { - return true - } - for _, id := range []string{ID, builtin.IDCore} { - if rec := st.Plugins[id]; rec != nil { - if _, ok := rec.AppSettings[key]; ok { - return SettingOn(rec.AppSettings, key) - } - } - } - if key == SettingInstallGuide { - if rec := st.Plugins[LegacyInstallGuideID]; rec != nil { - return rec.Enabled - } - } - return true -} - func settingOn(cb builtin.HostCallbacks, key string) bool { if cb.GetSetting == nil { return true diff --git a/internal/macos/guest/guest_test.go b/internal/macos/guest/guest_test.go index 3a643e0..6b3e9f9 100644 --- a/internal/macos/guest/guest_test.go +++ b/internal/macos/guest/guest_test.go @@ -79,9 +79,6 @@ func TestMigrateFilesPreservesChoicesBeforeRegistration(t *testing.T) { }}); err != nil { t.Fatal(err) } - if SettingOnInState(plugin.ReadState(root), SettingWHPXFallback) { - t.Fatal("old off switch not honoured") - } if err := MigrateFiles(root); err != nil { t.Fatal(err) } @@ -94,7 +91,10 @@ func TestMigrateFilesPreservesChoicesBeforeRegistration(t *testing.T) { if string(first) != string(second) { t.Fatal("second migration rewrote state") } - st := plugin.ReadState(root) + st, err := store.Load() + if err != nil { + t.Fatal(err) + } rec := st.Plugins[ID] if rec == nil || !rec.Enabled { t.Fatalf("guest record = %+v", rec) diff --git a/internal/macos/installer/events.go b/internal/macos/installer/events.go index 8d03f96..a4fbc0a 100644 --- a/internal/macos/installer/events.go +++ b/internal/macos/installer/events.go @@ -59,6 +59,3 @@ func percentOf(done, total int64) float64 { } return float64(done) * 100 / float64(total) } - -// ParseCtlLine delegates engine progress parsing to the host progress package. -func ParseCtlLine(line string) (Update, bool) { return host.ParseCtlLine(line) } diff --git a/internal/macos/installer/installer_test.go b/internal/macos/installer/installer_test.go index 9f51fc5..426781c 100644 --- a/internal/macos/installer/installer_test.go +++ b/internal/macos/installer/installer_test.go @@ -227,29 +227,6 @@ func TestListCachedSkipsHiddenFiles(t *testing.T) { } } -func TestParseCtlLine(t *testing.T) { - // Formats from reims_util.rs:480-488 and its test at :777-786. - u, _ := ParseCtlLine("downloading the macOS Tahoe 26 recovery image: 45% of 2.0 GB") - if u.Kind != KindProgress || u.Step != "downloading the macOS Tahoe 26 recovery image" || u.Percent != 45 || u.Total != 2_000_000_000 { - t.Fatalf("percent line = %+v", u) - } - u, _ = ParseCtlLine("macos-tahoe: downloading OpenCore 1.0.8: 5% of 11 MB") - if u.Step != "macos-tahoe: downloading OpenCore 1.0.8" || u.Total != 11_000_000 { - t.Fatalf("ctl-prefixed line = %+v", u) - } - u, _ = ParseCtlLine("downloading the installer: 300 MB") - if u.Kind != KindProgress || u.Percent != -1 || u.Done != 300_000_000 { - t.Fatalf("size line = %+v", u) - } - u, _ = ParseCtlLine("creating the disk") - if u.Kind != KindNote || u.Message != "creating the disk" { - t.Fatalf("note = %+v", u) - } - if _, ok := ParseCtlLine(" "); ok { - t.Fatal("blank line") - } -} - // TestLockExcludesReimsCtl checks the lock against the real reims-ctl: while we // hold installers/.lock, `reims-ctl downloads delete` must refuse a file as // "being downloaded" (downloads.rs:139-159). Runs only with REIMS_GO_TEST_CTL diff --git a/internal/macos/macosdriver/clone.go b/internal/macos/macosdriver/clone.go index bead74d..90c289b 100644 --- a/internal/macos/macosdriver/clone.go +++ b/internal/macos/macosdriver/clone.go @@ -91,7 +91,7 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s return fmt.Errorf("source disk %s: %w", srcDisk, err) } rep := host.Inspect(cfg.DataRoot) - for _, issue := range reims.ValidateCreateLocalized(reims.CreateOpts{Name: cloneName, CPUs: max(src.CPUs, 1), Memory: src.Memory}, rep, cfg.Locale) { + for _, issue := range reims.ValidateCreate(reims.CreateOpts{Name: cloneName, CPUs: max(src.CPUs, 1), Memory: src.Memory}, rep, cfg.Locale) { if issue.Field == "name" { return fmt.Errorf("invalid clone name %q: %s", cloneName, issue.Message) } diff --git a/internal/macos/macosdriver/driver.go b/internal/macos/macosdriver/driver.go index 20bec16..0405319 100644 --- a/internal/macos/macosdriver/driver.go +++ b/internal/macos/macosdriver/driver.go @@ -225,7 +225,7 @@ func (d *ReimsMacOSDriver) ValidateCreate(_ context.Context, req driver.CreateRe } cfg := d.getConfig() rep := host.Inspect(cfg.DataRoot) - issues := reims.ValidateCreateLocalized(opts, rep, cfg.Locale) + issues := reims.ValidateCreate(opts, rep, cfg.Locale) out := make([]driver.ValidationIssue, 0, len(issues)) for _, is := range issues { out = append(out, driver.ValidationIssue{Field: is.Field, Message: is.Message}) @@ -276,7 +276,7 @@ func (d *ReimsMacOSDriver) ValidateSet(ctx context.Context, req driver.SetReques } cfg := d.getConfig() rep := host.Inspect(cfg.DataRoot) - issues := reims.ValidateSetLocalized(opts, cur, rep, cfg.Locale) + issues := reims.ValidateSet(opts, cur, rep, cfg.Locale) out := make([]driver.ValidationIssue, 0, len(issues)) for _, is := range issues { out = append(out, driver.ValidationIssue{Field: is.Field, Message: is.Message}) diff --git a/internal/macos/macosdriver/optimizations.go b/internal/macos/macosdriver/optimizations.go index 0078556..08e3e94 100644 --- a/internal/macos/macosdriver/optimizations.go +++ b/internal/macos/macosdriver/optimizations.go @@ -47,17 +47,6 @@ func DriverOptimizations(rep host.Report, runtimePatches []string) []host.Optimi return out } -// EvaluateOptimizations preserves the existing host-page ordering. -func EvaluateOptimizations(rep host.Report, runtimePatches []string) []host.Optimization { - core := host.EvaluateCoreOptimizations(rep) - extra := DriverOptimizations(rep, runtimePatches) - if len(core) == 0 { - return extra - } - out := append([]host.Optimization{core[0]}, extra...) - return append(out, core[1:]...) -} - func (d *ReimsMacOSDriver) EvaluateOptimizations(_ context.Context, rep host.Report) []host.Optimization { var patches []string if _, active, err := d.startClient(); err == nil { diff --git a/internal/macos/macosdriver/optimizations_test.go b/internal/macos/macosdriver/optimizations_test.go index fbd6928..5687fcb 100644 --- a/internal/macos/macosdriver/optimizations_test.go +++ b/internal/macos/macosdriver/optimizations_test.go @@ -20,8 +20,8 @@ func TestEvaluateOptimizationsWin10AndWin11(t *testing.T) { win10 := host.Report{WHPX: host.WHPXReady, HasHybridCores: true, PCoreCount: 8, ECoreCount: 4, NeedsColdRebootWorkaround: true, WHPXCaps: host.WHPXCapabilities{APICEmulation: true, KernelIrqchipAvailable: true}, RecommendedGPU: &host.GPUInfo{Name: "NVIDIA GeForce RTX 4070 Ti", Kind: host.GPUDiscrete, VulkanICD: "nv-vk64.json"}} - opts := EvaluateOptimizations(win10, []string{"qemu-whpx-win10-compat.patch"}) - if o := findOpt(t, opts, "pcore_pin"); o.Status != "recommended" || !o.Supported { + opts := DriverOptimizations(win10, []string{"qemu-whpx-win10-compat.patch"}) + if o := findOpt(t, host.EvaluateCoreOptimizations(win10), "pcore_pin"); o.Status != "recommended" || !o.Supported { t.Fatalf("pcore_pin = %+v", o) } if o := findOpt(t, opts, "kernel_irqchip"); o.Status != "unavailable" || o.Detail != "win10-needs-patch" { @@ -30,26 +30,26 @@ func TestEvaluateOptimizationsWin10AndWin11(t *testing.T) { if o := findOpt(t, opts, "cold_reboot"); o.Status != "auto" { t.Fatalf("cold_reboot = %+v", o) } - opts = EvaluateOptimizations(win10, []string{"qemu-whpx-win10-compat.patch", "qemu-whpx-win10-startup-ipis.patch"}) + opts = DriverOptimizations(win10, []string{"qemu-whpx-win10-compat.patch", "qemu-whpx-win10-startup-ipis.patch"}) if o := findOpt(t, opts, "kernel_irqchip"); o.Status != "experimental" || !o.Supported { t.Fatalf("patched kernel_irqchip = %+v", o) } win11 := host.Report{WHPX: host.WHPXReady, WHPXCaps: host.WHPXCapabilities{ModernOS: true, APICEmulation: true, KernelIrqchipAvailable: true, NestedVirtProperty: false, NestedVirtProbeError: "0x80370302"}} - opts = EvaluateOptimizations(win11, nil) + opts = DriverOptimizations(win11, nil) if o := findOpt(t, opts, "kernel_irqchip"); o.Status != "unavailable" || o.Detail != "0x80370302" { t.Fatalf("win11 broken nested = %+v", o) } if o := findOpt(t, opts, "cold_reboot"); o.Status != "unavailable" { t.Fatalf("win11 cold_reboot = %+v", o) } - opts = EvaluateOptimizations(win11, []string{"qemu-whpx-nested-virt-nonfatal.patch"}) + opts = DriverOptimizations(win11, []string{"qemu-whpx-nested-virt-nonfatal.patch"}) if o := findOpt(t, opts, "kernel_irqchip"); o.Status != "recommended" || !o.Supported { t.Fatalf("win11 patched = %+v", o) } win11.WHPXCaps.NestedVirtProperty = true win11.WHPXCaps.NestedVirtProbeError = "" - opts = EvaluateOptimizations(win11, nil) + opts = DriverOptimizations(win11, nil) if o := findOpt(t, opts, "kernel_irqchip"); o.Status != "recommended" || !o.Supported { t.Fatalf("win11 full support = %+v", o) } diff --git a/internal/macos/macosdriver/storage.go b/internal/macos/macosdriver/storage.go index a142dbc..6007925 100644 --- a/internal/macos/macosdriver/storage.go +++ b/internal/macos/macosdriver/storage.go @@ -165,7 +165,7 @@ func (d *ReimsMacOSDriver) compactDiskWithOptions(ctx context.Context, name stri } defer releaseDisk() cfg := d.getConfig() - res, err := reims.CompactDiskWithOptions(ctx, active.QemuImgPath(), rt.BuildChildEnv(&cfg, active), diskPath, opts, stdout, stderr) + res, err := reims.CompactDisk(ctx, active.QemuImgPath(), rt.BuildChildEnv(&cfg, active), diskPath, opts, stdout, stderr) if err != nil { return driver.DiskCompactResult{}, err } diff --git a/internal/macos/opencore/lang.go b/internal/macos/opencore/lang.go index c0bcfd4..28336c4 100644 --- a/internal/macos/opencore/lang.go +++ b/internal/macos/opencore/lang.go @@ -23,21 +23,6 @@ type Preset struct { LabelEN string `json:"label_en"` } -// Presets returns the built-in macOS prev-lang:kbd choices. -// `:0` pairs the locale with the standard US keyboard layout so terminal -// commands in macOS Recovery / Setup Assistant stay predictable; `:252` uses -// OpenCore's Pinyin layout ID. -func Presets() []Preset { - return []Preset{ - {Value: "zh-Hans:0", LabelZH: "简体中文(美式键盘,推荐)", LabelEN: "Simplified Chinese (US Keyboard)"}, - {Value: "zh-Hans:252", LabelZH: "简体中文(拼音键盘)", LabelEN: "Simplified Chinese (Pinyin)"}, - {Value: "zh-Hant:0", LabelZH: "繁體中文(美式键盘)", LabelEN: "Traditional Chinese (US Keyboard)"}, - {Value: "en-US:0", LabelZH: "English (US)", LabelEN: "English (US)"}, - {Value: "ja-JP:0", LabelZH: "日本語(美式键盘)", LabelEN: "Japanese (US Keyboard)"}, - {Value: "ko-KR:0", LabelZH: "한국어(美式键盘)", LabelEN: "Korean (US Keyboard)"}, - } -} - // DefaultGuestLang chooses the default macOS prev-lang:kbd matching the app UI locale. func DefaultGuestLang(locale i18n.Locale) string { resolved := strings.ToLower(string(i18n.ResolveLocale(string(locale)))) diff --git a/internal/macos/reims/compat_test.go b/internal/macos/reims/compat_test.go index 6fc9c3b..fdc8ef2 100644 --- a/internal/macos/reims/compat_test.go +++ b/internal/macos/reims/compat_test.go @@ -282,13 +282,6 @@ func TestBuildDeleteArgs(t *testing.T) { } } -func TestRedactLogLine(t *testing.T) { - got := RedactLogLine("mac 52:54:00:12:34:56 serial C02ABCDEFGH") - if got != "mac [redacted] serial [redacted]" { - t.Fatalf("RedactLogLine = %q", got) - } -} - func TestCleanAbortedCreateDir(t *testing.T) { dataDir := t.TempDir() vmDir := filepath.Join(dataDir, "reims-ctl", "vms", "macos-tahoe") @@ -474,11 +467,11 @@ func TestDiskImportAndCoWArgs(t *testing.T) { if conv != "convert -O qcow2 -o "+wantOpts+" in.vmdk out.qcow2" { t.Fatalf("BuildConvertToQCOW2Args = %q", conv) } - cow := strings.Join(BuildCoWOverlayArgs("golden.qcow2", "cow-dev.qcow2"), " ") + cow := strings.Join(BuildCoWOverlayArgs("golden.qcow2", "cow-dev.qcow2", DefaultQCOW2CreateOptions()), " ") if cow != "create -f qcow2 -b golden.qcow2 -F qcow2 -o "+wantOpts+" cow-dev.qcow2" { t.Fatalf("BuildCoWOverlayArgs = %q", cow) } - cmp := strings.Join(BuildCompactDiskArgs("disk.qcow2", "disk.compact.tmp"), " ") + cmp := strings.Join(BuildCompactDiskArgs("disk.qcow2", "disk.compact.tmp", DefaultQCOW2CreateOptions()), " ") if cmp != "convert -p -f qcow2 -O qcow2 -o "+wantOpts+" disk.qcow2 disk.compact.tmp" { t.Fatalf("BuildCompactDiskArgs = %q", cmp) } diff --git a/internal/macos/reims/disk_import.go b/internal/macos/reims/disk_import.go index 44ba8bf..6344717 100644 --- a/internal/macos/reims/disk_import.go +++ b/internal/macos/reims/disk_import.go @@ -223,15 +223,9 @@ func BuildResizeDiskArgs(diskPath, sizeArg string) []string { return []string{"resize", diskPath, sizeArg} } -// BuildCompactDiskArgs builds `qemu-img convert -p -f qcow2 -O qcow2` arguments -// using the default qcow2 creation options. -func BuildCompactDiskArgs(srcPath, dstPath string) []string { - return BuildCompactDiskArgsWithOptions(srcPath, dstPath, DefaultQCOW2CreateOptions()) -} - -// BuildCompactDiskArgsWithOptions builds `qemu-img convert -p -f qcow2 -O qcow2` +// BuildCompactDiskArgs builds `qemu-img convert -p -f qcow2 -O qcow2` // arguments preserving explicit qcow2 creation options. -func BuildCompactDiskArgsWithOptions(srcPath, dstPath string, opts QCOW2CreateOptions) []string { +func BuildCompactDiskArgs(srcPath, dstPath string, opts QCOW2CreateOptions) []string { args := []string{"convert", "-p", "-f", "qcow2", "-O", "qcow2"} if optStr := opts.OptionString(); optStr != "" { args = append(args, "-o", optStr) @@ -247,30 +241,14 @@ func NeedsDiskConversion(srcPath string) bool { } // BuildConvertToQCOW2Args constructs `qemu-img convert -O qcow2` arguments -// using the canonical default qcow2 creation options. +// using the default qcow2 creation options. func BuildConvertToQCOW2Args(srcPath, dstPath string) []string { - return BuildConvertToQCOW2ArgsWithOptions(srcPath, dstPath, DefaultQCOW2CreateOptions()) -} - -// BuildConvertToQCOW2ArgsWithOptions constructs `qemu-img convert -O qcow2` -// arguments with explicit qcow2 creation options. -func BuildConvertToQCOW2ArgsWithOptions(srcPath, dstPath string, opts QCOW2CreateOptions) []string { - args := []string{"convert", "-O", "qcow2"} - if optStr := opts.OptionString(); optStr != "" { - args = append(args, "-o", optStr) - } - return append(args, srcPath, dstPath) + return []string{"convert", "-O", "qcow2", "-o", DefaultQCOW2CreateOptions().OptionString(), srcPath, dstPath} } // BuildCoWOverlayArgs constructs `qemu-img create -f qcow2 -b -F qcow2` -// arguments using the default qcow2 creation options. -func BuildCoWOverlayArgs(backingPath, overlayPath string) []string { - return BuildCoWOverlayArgsWithOptions(backingPath, overlayPath, DefaultQCOW2CreateOptions()) -} - -// BuildCoWOverlayArgsWithOptions constructs `qemu-img create -f qcow2 -b -F qcow2` // arguments with explicit qcow2 creation options inherited from the backing image. -func BuildCoWOverlayArgsWithOptions(backingPath, overlayPath string, opts QCOW2CreateOptions) []string { +func BuildCoWOverlayArgs(backingPath, overlayPath string, opts QCOW2CreateOptions) []string { args := []string{"create", "-f", "qcow2", "-b", backingPath, "-F", "qcow2"} if optStr := opts.OptionString(); optStr != "" { args = append(args, "-o", optStr) @@ -319,7 +297,7 @@ func CreateCoWOverlay(ctx context.Context, qemuImgPath string, env []string, bac if err != nil { return fmt.Errorf("inspect backing qcow2 options: %w", err) } - cmd := exec.CommandContext(ctx, qemuImgPath, BuildCoWOverlayArgsWithOptions(backingPath, overlayPath, opts)...) + cmd := exec.CommandContext(ctx, qemuImgPath, BuildCoWOverlayArgs(backingPath, overlayPath, opts)...) configureCmd(cmd) cmd.Env = env if stdout != nil { @@ -372,14 +350,7 @@ func ResizeDisk(ctx context.Context, qemuImgPath string, env []string, diskPath, }, nil } -// CompactDisk rewrites a stopped VM's standalone qcow2 image into a freshly -// compacted sparse qcow2 file, verifies it with `qemu-img check`, and atomically -// swaps it into place to reclaim deleted/TRIMmed host disk space. -func CompactDisk(ctx context.Context, qemuImgPath string, env []string, diskPath string, stdout, stderr io.Writer) (DiskCompactResult, error) { - return CompactDiskWithOptions(ctx, qemuImgPath, env, diskPath, CompactDiskOptions{}, stdout, stderr) -} - -func CompactDiskWithOptions(ctx context.Context, qemuImgPath string, env []string, diskPath string, compactOpts CompactDiskOptions, stdout, stderr io.Writer) (DiskCompactResult, error) { +func CompactDisk(ctx context.Context, qemuImgPath string, env []string, diskPath string, compactOpts CompactDiskOptions, stdout, stderr io.Writer) (DiskCompactResult, error) { before, err := host.InspectDiskUsage(diskPath) if err != nil { return DiskCompactResult{}, fmt.Errorf("inspect disk %s: %w", diskPath, err) @@ -420,7 +391,7 @@ func CompactDiskWithOptions(ctx context.Context, qemuImgPath string, env []strin _ = os.Remove(tmpPath) defer os.Remove(tmpPath) - cmd := exec.CommandContext(ctx, qemuImgPath, BuildCompactDiskArgsWithOptions(diskPath, tmpPath, opts)...) + cmd := exec.CommandContext(ctx, qemuImgPath, BuildCompactDiskArgs(diskPath, tmpPath, opts)...) configureCmd(cmd) cmd.Env = env if stdout != nil { diff --git a/internal/macos/reims/disk_ops_test.go b/internal/macos/reims/disk_ops_test.go index 295e52b..c990fe3 100644 --- a/internal/macos/reims/disk_ops_test.go +++ b/internal/macos/reims/disk_ops_test.go @@ -62,8 +62,8 @@ func TestDiskRewriteRefusesSnapshotsAndBackingFiles(t *testing.T) { if err := os.WriteFile(disk, hdr, 0o644); err != nil { t.Fatal(err) } - _, compactErr := CompactDisk(context.Background(), missingQemuImg, nil, disk, nil, nil) - _, optimizeErr := CompactDiskWithOptions(context.Background(), missingQemuImg, nil, disk, CompactDiskOptions{EnableExtendedL2: true}, nil, nil) + _, compactErr := CompactDisk(context.Background(), missingQemuImg, nil, disk, CompactDiskOptions{}, nil, nil) + _, optimizeErr := CompactDisk(context.Background(), missingQemuImg, nil, disk, CompactDiskOptions{EnableExtendedL2: true}, nil, nil) for _, err := range []error{compactErr, optimizeErr} { if err == nil || !strings.Contains(err.Error(), want) { t.Fatalf("rewrite error = %v, want %q", err, want) @@ -331,7 +331,7 @@ func TestResizeAndCompactRealQemuImg(t *testing.T) { if res.NewVirtualBytes != 128<<20 { t.Fatalf("NewVirtualBytes = %d, want %d", res.NewVirtualBytes, 128<<20) } - cmp, err := CompactDisk(context.Background(), qemuImg, nil, disk, nil, nil) + cmp, err := CompactDisk(context.Background(), qemuImg, nil, disk, CompactDiskOptions{}, nil, nil) if err != nil { t.Fatalf("CompactDisk: %v", err) } @@ -355,7 +355,7 @@ func TestResizeAndCompactRealQemuImg(t *testing.T) { t.Fatalf("unexpected beforeOpts: %+v", beforeOpts) } - if _, err := CompactDisk(context.Background(), qemuImg, nil, customDisk, nil, nil); err != nil { + if _, err := CompactDisk(context.Background(), qemuImg, nil, customDisk, CompactDiskOptions{}, nil, nil); err != nil { t.Fatalf("CompactDisk(custom): %v", err) } afterCompactOpts, err := InspectQCOW2CreateOptions(context.Background(), qemuImg, nil, customDisk) diff --git a/internal/macos/reims/network.go b/internal/macos/reims/network.go index 33b0437..2b96c9e 100644 --- a/internal/macos/reims/network.go +++ b/internal/macos/reims/network.go @@ -127,17 +127,6 @@ type mainNetwork struct { func isMainNetworkID(id string) bool { return id == "net0" || id == PacketBridgeID } -func setQEMUField(value, key, replacement string) string { - parts := qemuFields(value) - for i, part := range parts { - if strings.HasPrefix(part, key+"=") { - parts[i] = key + "=" + replacement - } - parts[i] = strings.ReplaceAll(parts[i], "\x00", ",,") - } - return strings.Join(parts, ",") -} - func findMainNetwork(args []string) (mainNetwork, error) { var n mainNetwork for i := 0; i < len(args); i++ { @@ -435,27 +424,3 @@ func PacketBridgeUnixTokens(mac, socketPath string) ([]string, error) { "-device", fmt.Sprintf("virtio-net-pci,netdev=%s,id=net0,mac=%s,addr=0x3", PacketBridgeID, strings.ToLower(hw.String())), }, nil } - -// BuildPacketBridgeExtra 保留用于兼容旧版调用与回归测试。 -func BuildPacketBridgeExtra(extra, generated string, port int) (string, error) { - if port < 1 || port > 65535 { - return "", networkError("packet_port", nil) - } - args, err := cleanMainNetwork(extra) - if err != nil { - return "", err - } - all, err := ShellArgs(generated) - if err != nil { - return "", err - } - actual, err := findMainNetwork(all) - if err != nil { - return "", err - } - if actual.backends != 1 || actual.devices != 1 { - return "", networkError("args_main_unknown", nil) - } - args = append(args, "-netdev", fmt.Sprintf("stream,id=%s,server=off,addr.type=inet,addr.host=127.0.0.1,addr.port=%d,reconnect-ms=1000", PacketBridgeID, port), "-device", setQEMUField(actual.device, "netdev", PacketBridgeID)) - return JoinShellArgs(args), nil -} diff --git a/internal/macos/reims/network_test.go b/internal/macos/reims/network_test.go index 707b0f1..da93140 100644 --- a/internal/macos/reims/network_test.go +++ b/internal/macos/reims/network_test.go @@ -66,10 +66,8 @@ func TestNetworkModesAndUnixTokens(t *testing.T) { } // Legacy TCP bridge detection still works for pre-upgrade running/suspended VMs. - legacy, err := BuildPacketBridgeExtra("-cpu host", "qemu -netdev user,id=net0 -device virtio-net-pci,netdev=net0,id=net0,mac="+mac+",addr=0x3", 12363) - if err != nil { - t.Fatalf("BuildPacketBridgeExtra: %v", err) - } + legacy := "-cpu host -netdev stream,id=" + PacketBridgeID + ",server=off,addr.type=inet,addr.host=127.0.0.1,addr.port=12363,reconnect-ms=1000" + + " -device virtio-net-pci,netdev=" + PacketBridgeID + ",id=net0,mac=" + mac + ",addr=0x3" if got := NetworkMode(false, legacy); got != "bridge" { t.Fatalf("NetworkMode(legacy tcp) = %q, want bridge", got) } diff --git a/internal/macos/reims/redact.go b/internal/macos/reims/redact.go deleted file mode 100644 index 306d33b..0000000 --- a/internal/macos/reims/redact.go +++ /dev/null @@ -1,9 +0,0 @@ -package reims - -import "github.com/Nwflower/reims-go/internal/host" - -// RedactLogLine preserves the engine package API while sharing the host redactor. -func RedactLogLine(line string) string { return host.RedactLine(line) } - -// RedactText applies RedactLogLine across a multi-line text block. -func RedactText(s string) string { return host.RedactText(s) } diff --git a/internal/macos/reims/reims.go b/internal/macos/reims/reims.go index 66a28f7..0cdaa5f 100644 --- a/internal/macos/reims/reims.go +++ b/internal/macos/reims/reims.go @@ -215,13 +215,8 @@ func ParseSizeGB(raw string) (float64, bool) { return v, true } -// ValidateCreate performs pre-save validation aligned with VZVirtualMachineConfiguration.validate(). -func ValidateCreate(o CreateOpts, rep host.Report) []ValidationIssue { - return ValidateCreateLocalized(o, rep, i18n.EnUS) -} - -// ValidateCreateLocalized performs pre-save validation with localized issue messages. -func ValidateCreateLocalized(o CreateOpts, rep host.Report, loc i18n.Locale) []ValidationIssue { +// ValidateCreate performs pre-save validation with localized issue messages. +func ValidateCreate(o CreateOpts, rep host.Report, loc i18n.Locale) []ValidationIssue { var issues []ValidationIssue if o.NetworkMode != "" && o.NetworkMode != "off" && o.NetworkMode != "nat" && o.NetworkMode != "bridge" { issues = append(issues, ValidationIssue{Field: "network_mode", Code: "invalid_network_mode", Message: i18n.T(loc, "validate.invalid_network_mode")}) @@ -290,13 +285,8 @@ func ValidateCreateLocalized(o CreateOpts, rep host.Report, loc i18n.Locale) []V return issues } -// ValidateSet validates configuration edits before invoking `reims-ctl set`. -func ValidateSet(o SetOpts, current VMDetail, rep host.Report) []ValidationIssue { - return ValidateSetLocalized(o, current, rep, i18n.EnUS) -} - -// ValidateSetLocalized validates configuration edits with localized issue messages. -func ValidateSetLocalized(o SetOpts, current VMDetail, rep host.Report, loc i18n.Locale) []ValidationIssue { +// ValidateSet validates configuration edits with localized issue messages. +func ValidateSet(o SetOpts, current VMDetail, rep host.Report, loc i18n.Locale) []ValidationIssue { var issues []ValidationIssue if strings.TrimSpace(o.Name) == "" { issues = append(issues, ValidationIssue{Field: "name", Code: "missing_name", Message: i18n.T(loc, "validate.missing_name")}) diff --git a/internal/macos/reims/suspend.go b/internal/macos/reims/suspend.go index 26c9f20..c74210c 100644 --- a/internal/macos/reims/suspend.go +++ b/internal/macos/reims/suspend.go @@ -206,21 +206,6 @@ func shortRev(rev string) string { return rev } -// HasIncomingDeferArg reports whether extraArgs contains `-incoming defer`. -func HasIncomingDeferArg(extraArgs string) bool { - tokens := splitShellTokens(extraArgs) - for i := 0; i < len(tokens); i++ { - tok := tokens[i] - if tok == "-incoming" && i+1 < len(tokens) && tokens[i+1] == "defer" { - return true - } - if tok == "-incoming=defer" { - return true - } - } - return false -} - // StripIncomingDeferArgs removes any `-incoming defer` / `-incoming=defer` // arguments from QEMU extra-args while leaving all other arguments intact. func StripIncomingDeferArgs(existing string) string { diff --git a/internal/macos/reims/suspend_test.go b/internal/macos/reims/suspend_test.go index 0549c80..ee28d48 100644 --- a/internal/macos/reims/suspend_test.go +++ b/internal/macos/reims/suspend_test.go @@ -90,11 +90,8 @@ func TestSuspendStateLifecycle(t *testing.T) { } func TestIncomingDeferArgsIdempotent(t *testing.T) { - if HasIncomingDeferArg("") || HasIncomingDeferArg("-machine q35") { - t.Fatal("unexpected HasIncomingDeferArg=true") - } m := MergeIncomingDeferArgs(`-drive "id=x,file=C:/a b/c.img"`) - if !HasIncomingDeferArg(m) { + if !strings.HasSuffix(m, " -incoming defer") { t.Fatalf("expected -incoming defer in %q", m) } if m2 := MergeIncomingDeferArgs(m); m2 != m { @@ -126,7 +123,7 @@ func TestSuspendLegacyRuntimeStillRequiresExactVersion(t *testing.T) { } func TestValidateSetRejectsSuspendedVM(t *testing.T) { - issues := ValidateSetLocalized( + issues := ValidateSet( SetOpts{Name: "tahoe", CPUs: 6}, VMDetail{Name: "tahoe", State: "suspended", CPUs: 8, Memory: "8G"}, host.Report{LogicalCPUs: 16, TotalRAMGB: 32}, diff --git a/internal/packetbridge/start_guard_other.go b/internal/packetbridge/start_guard_other.go index c01191b..b49b548 100644 --- a/internal/packetbridge/start_guard_other.go +++ b/internal/packetbridge/start_guard_other.go @@ -4,4 +4,3 @@ package packetbridge func AcquireBridgeStart() (func(), error) { return func() {}, nil } func AcquireNpcapInstall() (func(), error) { return func() {}, nil } -func AcquireVMStart() (func(), error) { return func() {}, nil } diff --git a/internal/packetbridge/start_guard_windows.go b/internal/packetbridge/start_guard_windows.go index 13d8e62..a15107c 100644 --- a/internal/packetbridge/start_guard_windows.go +++ b/internal/packetbridge/start_guard_windows.go @@ -61,11 +61,6 @@ func AcquireNpcapInstall() (func(), error) { return acquireGuard(lockPath, statePath, true) } -// AcquireVMStart 保留向后兼容别名,语义已收敛为共享读锁(供桥接 VM 启动使用)。 -func AcquireVMStart() (func(), error) { - return AcquireBridgeStart() -} - func acquireGuard(lockPath, statePath string, exclusive bool) (func(), error) { if err := checkTrackedInstaller(statePath); err != nil { return nil, err diff --git a/internal/plugin/assets.go b/internal/plugin/assets.go index 6adc38f..d4b4393 100644 --- a/internal/plugin/assets.go +++ b/internal/plugin/assets.go @@ -125,7 +125,7 @@ func (a *AssetServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { ct = "image/svg+xml; charset=utf-8" data = SanitizeSVG(data) } else { - if err := ValidateThemeCSSSafetyInDir(string(data), filepath.Dir(fullPath)); err != nil { + if err := ValidateThemeCSSSafety(string(data), filepath.Dir(fullPath)); err != nil { http.Error(w, "unsafe stylesheet blocked", http.StatusForbidden) return } diff --git a/internal/plugin/blockers_test.go b/internal/plugin/blockers_test.go index e15682b..51c561c 100644 --- a/internal/plugin/blockers_test.go +++ b/internal/plugin/blockers_test.go @@ -191,7 +191,7 @@ func TestValidateThemeCSSAndContributionBlocksBypasses(t *testing.T) { {"traversal-url", `.rg-p-shell { background: url("../../secret.png"); }`}, } for _, tc := range badCSS { - if err := ValidateThemeCSSSafety(tc.css); err == nil { + if err := ValidateThemeCSSSafety(tc.css, ""); err == nil { t.Errorf("ValidateThemeCSSSafety(%s) expected error, got nil", tc.name) } } @@ -204,10 +204,10 @@ func TestValidateThemeCSSAndContributionBlocksBypasses(t *testing.T) { if err := os.WriteFile(filepath.Join(dir, "assets", "bg.png"), []byte("png"), 0o644); err != nil { t.Fatal(err) } - if err := ValidateThemeCSSSafetyInDir(`.rg-p-shell { background: url("assets/bg.png"); }`, dir); err != nil { + if err := ValidateThemeCSSSafety(`.rg-p-shell { background: url("assets/bg.png"); }`, dir); err != nil { t.Errorf("valid local asset rejected: %v", err) } - if err := ValidateThemeCSSSafetyInDir(`.rg-p-shell { background: url("assets/missing.png"); }`, dir); err == nil { + if err := ValidateThemeCSSSafety(`.rg-p-shell { background: url("assets/missing.png"); }`, dir); err == nil { t.Error("missing local asset should be rejected") } diff --git a/internal/plugin/kernel_test.go b/internal/plugin/kernel_test.go index 99f6bbe..38c7d49 100644 --- a/internal/plugin/kernel_test.go +++ b/internal/plugin/kernel_test.go @@ -445,10 +445,12 @@ func TestArgLedgerReconcilePreserveUserArgsAndStripOnDisable(t *testing.T) { } // Disable thirdparty.tweak -> its fragment is stripped cleanly, user + builtin remain. - stripped, changed := StripPluginFromArgs(res.ExtraArgs, reloaded, "thirdparty.tweak") - if !changed { + delete(active, "thirdparty.tweak") + after := ReconcileStartIntents(res.ExtraArgs, reloaded, active, intents[:1]) + if !after.Changed { t.Fatal("expected change on strip") } + stripped := after.ExtraArgs if strings.Contains(stripped, "usb-tablet") { t.Fatalf("plugin fragment not stripped: %q", stripped) } diff --git a/internal/plugin/ledger.go b/internal/plugin/ledger.go index 13bbff5..e54dfa5 100644 --- a/internal/plugin/ledger.go +++ b/internal/plugin/ledger.go @@ -596,19 +596,6 @@ func reconcileStartIntents(currentExtraArgs string, ledger *ArgLedger, activePlu return res } -// StripPluginFromArgs removes all fragments owned by pluginID from currentExtraArgs -// and updates ledger, leaving user args and other plugins' args intact. -func StripPluginFromArgs(currentExtraArgs string, ledger *ArgLedger, pluginID string) (string, bool) { - if ledger == nil || len(ledger.Owners[pluginID]) == 0 { - return strings.TrimSpace(currentExtraArgs), false - } - sub := &ArgLedger{Owners: map[string][]ArgFragment{pluginID: ledger.Owners[pluginID]}} - tokens := stripOwnedTokens(SplitShellTokens(currentExtraArgs), sub) - delete(ledger.Owners, pluginID) - next := strings.TrimSpace(strings.Join(tokens, " ")) - return next, next != strings.TrimSpace(currentExtraArgs) -} - func fragWins(candidate, existing ArgFragment) bool { if candidate.Builtin != existing.Builtin { return candidate.Builtin diff --git a/internal/plugin/manager.go b/internal/plugin/manager.go index ade6d7a..5612917 100644 --- a/internal/plugin/manager.go +++ b/internal/plugin/manager.go @@ -1326,7 +1326,7 @@ func (m *Manager) ActiveThemePayload() ActiveThemePayload { if installDir != "" && th.Stylesheet != "" { if full, err := safeJoin(installDir, th.Stylesheet); err == nil { if raw, err := os.ReadFile(full); err == nil { - if ValidateThemeCSSSafetyInDir(string(raw), filepath.Dir(full)) == nil { + if ValidateThemeCSSSafety(string(raw), filepath.Dir(full)) == nil { payload.CSS = string(raw) } } diff --git a/internal/plugin/manager_sidecar_test.go b/internal/plugin/manager_sidecar_test.go index 1024549..2bd296e 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/macos/reims" + "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/pkg/pluginsdk" ) @@ -148,7 +148,7 @@ func TestTransactionalInstallSigningRedlinesAndThemeDoctor(t *testing.T) { Trust: plugin.TrustOfficial, PublicKey: pub, }}, - RedactFn: reims.RedactText, + RedactFn: host.RedactText, }) if err != nil { t.Fatal(err) @@ -268,7 +268,7 @@ func TestTransactionalInstallSigningRedlinesAndThemeDoctor(t *testing.T) { // 4. Market redline: reject Apple .ipsw inside zip. redlineZip := makePluginZip(t, map[string][]byte{ - "plugin.json": manifestJSON, + "plugin.json": manifestJSON, "Universal.ipsw": []byte("nope"), }, nil, false) if _, err := mgr.InstallLocalArchive(context.Background(), redlineZip, plugin.PackageInstallOptions{}); err == nil { @@ -289,7 +289,7 @@ func TestSidecarSupervisionReverseHostAPIDriverAndCrashIsolation(t *testing.T) { dataRoot := t.TempDir() layout := plugin.NewPluginsLayout(dataRoot) reg := plugin.NewRegistry(nil) - broker := plugin.NewBroker(layout, reg, reims.RedactText) + broker := plugin.NewBroker(layout, reg, host.RedactText) notified := make(chan string, 1) broker.SetNotifier(func(pid, title, body string) { @@ -361,7 +361,7 @@ func TestSidecarSupervisionReverseHostAPIDriverAndCrashIsolation(t *testing.T) { } // 3. Diagnostics collection enforces host redaction of MAC & serial (§4.2, §7.1). - diags := reg.CollectDiagnostics(context.Background(), "ubuntu-24", reims.RedactText) + diags := reg.CollectDiagnostics(context.Background(), "ubuntu-24", host.RedactText) if len(diags) != 1 { t.Fatalf("expected 1 diag entry, got %d", len(diags)) } diff --git a/internal/plugin/scanner.go b/internal/plugin/scanner.go index be55b18..e02596b 100644 --- a/internal/plugin/scanner.go +++ b/internal/plugin/scanner.go @@ -403,7 +403,7 @@ func ScanDirectory(dir, hostVersion string, opts ScanOptions) ScanReport { if ext == ".css" && !declaredThemeCSS[rel] && !inRelDir(rel, declaredPanelDir) && info.Size() <= maxScanTextBytes { if b, rErr := os.ReadFile(full); rErr == nil { - if err := ValidateThemeCSSSafetyInDir(string(b), filepath.Dir(full)); err != nil { + if err := ValidateThemeCSSSafety(string(b), filepath.Dir(full)); err != nil { addHard("theme-css", rel, fmt.Sprintf("unsafe CSS %s: %v", rel, err), fmt.Sprintf("样式文件 %s 未通过安全校验:%v", rel, err), fmt.Sprintf("Stylesheet %s failed safety check: %v", rel, err)) @@ -843,12 +843,12 @@ func describePermission(perm string) (LocalizedText, LocalizedText) { if strings.HasPrefix(perm, "net:") { host := strings.TrimPrefix(perm, "net:") return LocalizedText{ - ZhCN: "访问指定网络主机", - EnUS: "Access declared network host", - }, LocalizedText{ - ZhCN: fmt.Sprintf("允许向 %s 发起网络请求。", host), - EnUS: fmt.Sprintf("Allows outbound network requests to %s.", host), - } + ZhCN: "访问指定网络主机", + EnUS: "Access declared network host", + }, LocalizedText{ + ZhCN: fmt.Sprintf("允许向 %s 发起网络请求。", host), + EnUS: fmt.Sprintf("Allows outbound network requests to %s.", host), + } } switch perm { case "ui:script": diff --git a/internal/plugin/state.go b/internal/plugin/state.go index 1cff3c1..f3de906 100644 --- a/internal/plugin/state.go +++ b/internal/plugin/state.go @@ -145,18 +145,6 @@ func (s *StateStore) Save(st *StateFile) error { return nil } -// ReadState reads `/plugins/state.json` without starting a Manager, -// for processes such as `vm start` that only need a setting or two. It returns -// nil when the file is unreadable; callers then use their defaults, as the -// GUI's Manager does. -func ReadState(dataRoot string) *StateFile { - st, err := NewStateStore(NewPluginsLayout(dataRoot).Root).Load() - if err != nil { - return nil - } - return st -} - // --- Safe-mode startup sentinel (§9) --- // SentinelPath returns `/plugins/.startup-sentinel`. diff --git a/internal/plugin/theme_css.go b/internal/plugin/theme_css.go index 3ab5029..b50f1a8 100644 --- a/internal/plugin/theme_css.go +++ b/internal/plugin/theme_css.go @@ -12,26 +12,20 @@ import ( ) var ( - reTokenKey = regexp.MustCompile(`^--[a-z0-9][a-z0-9-]*$`) - reSafeFontFamily = regexp.MustCompile(`^[\p{L}\p{N} _-]{1,80}$`) - reFontWeight = regexp.MustCompile(`^[0-9a-zA-Z\s-]+$`) - reFontStyle = regexp.MustCompile(`^(normal|italic|oblique(\s+-?[0-9]+(\.[0-9]+)?deg)?)$`) - reUnicodeRange = regexp.MustCompile(`^[U+0-9a-fA-F?,\s-]+$`) - reSafeAssetRel = regexp.MustCompile(`^[a-zA-Z0-9._/@ -]+$`) - reSchemePrefix = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9+.-]*:`) + reTokenKey = regexp.MustCompile(`^--[a-z0-9][a-z0-9-]*$`) + reSafeFontFamily = regexp.MustCompile(`^[\p{L}\p{N} _-]{1,80}$`) + reFontWeight = regexp.MustCompile(`^[0-9a-zA-Z\s-]+$`) + reFontStyle = regexp.MustCompile(`^(normal|italic|oblique(\s+-?[0-9]+(\.[0-9]+)?deg)?)$`) + reUnicodeRange = regexp.MustCompile(`^[U+0-9a-fA-F?,\s-]+$`) + reSafeAssetRel = regexp.MustCompile(`^[a-zA-Z0-9._/@ -]+$`) + reSchemePrefix = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9+.-]*:`) ) // ValidateThemeCSSSafety rejects unbalanced braces, unclosed strings/comments, // CSS-escaped url()/image-set()/expression() bypasses, remote @import, and -// external or unsafe data: URLs. -func ValidateThemeCSSSafety(css string) error { - return ValidateThemeCSSSafetyInDir(css, "") -} - -// ValidateThemeCSSSafetyInDir performs ValidateThemeCSSSafety and, when rootDir -// is non-empty, also verifies that every relative url()/@import resolves to an -// existing file inside rootDir. -func ValidateThemeCSSSafetyInDir(css, rootDir string) error { +// external or unsafe data: URLs. When rootDir is non-empty, every relative +// url()/@import must also resolve to an existing file inside rootDir. +func ValidateThemeCSSSafety(css, rootDir string) error { if strings.Contains(strings.ToLower(css), ""), negotiates capabilities, and waits for a SHUTDOWN event. It -// returns true iff the VM exited because the guest requested a reset -// (`reason == "guest-reset"` under `-no-reboot`). -func WatchForGuestReset(ctx context.Context, addr string) (bool, error) { - reason, err := WatchShutdownReason(ctx, addr) - if err != nil { - return false, err - } - return reason == "guest-reset", nil -} - // WatchShutdownReason waits for QEMU's SHUTDOWN event over QMP and returns its // reason (e.g. "guest-reset", "guest-shutdown", "host-qmp-quit"), or "" on EOF. func WatchShutdownReason(ctx context.Context, addr string) (string, error) { diff --git a/internal/qmp/watcher_test.go b/internal/qmp/watcher_test.go index 011b9ff..943ae27 100644 --- a/internal/qmp/watcher_test.go +++ b/internal/qmp/watcher_test.go @@ -66,7 +66,7 @@ func TestRebootSocketPathFallback(t *testing.T) { } } -func runMockQMPUnix(t *testing.T, eventJSON string) (bool, error) { +func runMockQMPUnix(t *testing.T, eventJSON string) (string, error) { t.Helper() const sockPath = "reims-go-reboot.sock" ln, err := net.Listen("unix", sockPath) @@ -91,25 +91,17 @@ func runMockQMPUnix(t *testing.T, eventJSON string) (bool, error) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() - return WatchForGuestReset(ctx, "unix:"+sockPath) + return WatchShutdownReason(ctx, "unix:"+sockPath) } -func TestWatchForGuestReset(t *testing.T) { +func TestWatchShutdownReason(t *testing.T) { // Unix socket addresses have a small byte limit. The isolated working // directory lets the mock and watcher use the same short relative address. t.Chdir(t.TempDir()) - reset, err := runMockQMPUnix(t, `{"event":"SHUTDOWN","data":{"guest":true,"reason":"guest-reset"}}`) - if err != nil || !reset { - t.Fatalf("guest-reset: got reset=%v err=%v, want true nil", reset, err) - } - - reset, err = runMockQMPUnix(t, `{"event":"SHUTDOWN","data":{"guest":true,"reason":"guest-shutdown"}}`) - if err != nil || reset { - t.Fatalf("guest-shutdown: got reset=%v err=%v, want false nil", reset, err) - } - - reset, err = runMockQMPUnix(t, `{"event":"SHUTDOWN","data":{"guest":false,"reason":"host-ui"}}`) - if err != nil || reset { - t.Fatalf("host-ui: got reset=%v err=%v, want false nil", reset, err) + for _, want := range []string{"guest-reset", "guest-shutdown", "host-ui"} { + got, err := runMockQMPUnix(t, `{"event":"SHUTDOWN","data":{"guest":true,"reason":"`+want+`"}}`) + if err != nil || got != want { + t.Fatalf("reason = %q, %v, want %q", got, err, want) + } } } diff --git a/internal/selfupdate/selfupdate.go b/internal/selfupdate/selfupdate.go index 07652a5..6ada3d1 100644 --- a/internal/selfupdate/selfupdate.go +++ b/internal/selfupdate/selfupdate.go @@ -71,17 +71,10 @@ func Writable(dir string) error { } // Swap installs newExe at target (see Target; usually exe itself) and moves -// the running exe aside to ".old" (or a timestamped name when an earlier -// one is still locked). A file already at target is replaced. On any failure -// the original executable is left in place. -func Swap(exe, target, newExe string) error { - return SwapWithOptions(exe, target, newExe, false) -} - -// SwapWithOptions behaves like Swap, except when keepOld is true it never -// deletes an existing ".old" backup (falling back to a timestamped -// ".old-" name instead). -func SwapWithOptions(exe, target, newExe string, keepOld bool) error { +// the running exe aside to ".old", or to a timestamped name when an +// earlier backup is still locked or keepOld asks to preserve it. A file already +// at target is replaced. On any failure the original executable stays in place. +func Swap(exe, target, newExe string, keepOld bool) error { staged := target + ".new" if err := copyFile(newExe, staged); err != nil { os.Remove(staged) diff --git a/internal/selfupdate/selfupdate_test.go b/internal/selfupdate/selfupdate_test.go index 10ade82..d2f10cd 100644 --- a/internal/selfupdate/selfupdate_test.go +++ b/internal/selfupdate/selfupdate_test.go @@ -30,7 +30,7 @@ func TestSwapAndCleanup(t *testing.T) { write(t, newExe, "new build") write(t, exe+".old", "left over from an earlier update") - if err := Swap(exe, exe, newExe); err != nil { + if err := Swap(exe, exe, newExe, false); err != nil { t.Fatal(err) } if got := read(t, exe); got != "new build" { @@ -56,7 +56,7 @@ func TestSwapLeavesExeOnFailure(t *testing.T) { dir := t.TempDir() exe := filepath.Join(dir, "reims-go.exe") write(t, exe, "old build") - if err := Swap(exe, exe, filepath.Join(dir, "missing.exe")); err == nil { + if err := Swap(exe, exe, filepath.Join(dir, "missing.exe"), false); err == nil { t.Fatal("a missing download must fail") } if got := read(t, exe); got != "old build" { @@ -107,7 +107,7 @@ func TestSwapRenamesReleaseFile(t *testing.T) { write(t, newExe, "v0.2.6") target := Target(exe, filepath.Base(newExe)) - if err := Swap(exe, target, newExe); err != nil { + if err := Swap(exe, target, newExe, false); err != nil { t.Fatal(err) } if got := read(t, target); got != "v0.2.6" { @@ -138,7 +138,7 @@ func TestSwapKeepOldAndCleanupStaging(t *testing.T) { write(t, exe+".old", "stable backup") write(t, newExe, "new dev-2") - if err := SwapWithOptions(exe, exe, newExe, true); err != nil { + if err := Swap(exe, exe, newExe, true); err != nil { t.Fatal(err) } if got := read(t, exe); got != "new dev-2" { diff --git a/internal/testutil/fakedriver/harness.go b/internal/testutil/fakedriver/harness.go index 9ad20d8..d5efe87 100644 --- a/internal/testutil/fakedriver/harness.go +++ b/internal/testutil/fakedriver/harness.go @@ -34,7 +34,7 @@ func NewHarness(t *testing.T) *Harness { broker.SetVMStateHandler(func(_ string, rep plugin.ReportedVMState) error { return states.Report(driver.ReportedStateFromPlugin(rep)) }) - router := driver.NewRouterWithDataRoot(reg, func() string { return root }) + router := driver.NewRouter(reg, func() string { return root }) router.SetStateTable(states) h := &Harness{Registry: reg, Broker: broker, Router: router, States: states, DataRoot: root, StopFile: filepath.Join(t.TempDir(), "stop"), t: t} diff --git a/internal/version/version.go b/internal/version/version.go index fec814c..c17239f 100644 --- a/internal/version/version.go +++ b/internal/version/version.go @@ -109,12 +109,6 @@ type ghAsset struct { URL string `json:"browser_download_url"` } -// ParseSemver parses a tag like "v0.2.1" or "0.2.1-rc1" into major/minor/patch. -func ParseSemver(v string) (major, minor, patch int, ok bool) { - major, minor, patch, _, ok = parseSemverFull(v) - return major, minor, patch, ok -} - func parseSemverFull(v string) (major, minor, patch int, pre string, ok bool) { s := strings.TrimSpace(v) s = strings.TrimPrefix(s, "v") @@ -242,12 +236,6 @@ func Compare(a, b string) int { return comparePrerelease(aPre, bPre) } -// CheckUpdate queries GitHub Releases for the newest stable (non-draft, -// non-prerelease) application release tagged "vX.Y.Z". -func (s Source) CheckUpdate(ctx context.Context, current string) (UpdateInfo, error) { - return s.CheckUpdateChannel(ctx, current, ChannelStable) -} - type releaseCandidate struct { rel *ghRelease ver string @@ -322,9 +310,9 @@ func isSameBaseDevBuild(a, b string) bool { strings.HasPrefix(strings.ToLower(bPre), "dev-") } -// CheckUpdateChannel queries GitHub Releases for the newest eligible Reims-Go +// CheckUpdate queries GitHub Releases for the newest eligible Reims-Go // release on the requested channel ("stable", "alpha", or "dev"). -func (s Source) CheckUpdateChannel(ctx context.Context, current, channel string) (UpdateInfo, error) { +func (s Source) CheckUpdate(ctx context.Context, current, channel string) (UpdateInfo, error) { if current == "" { current = Version } diff --git a/internal/version/version_test.go b/internal/version/version_test.go index e031034..056d9d7 100644 --- a/internal/version/version_test.go +++ b/internal/version/version_test.go @@ -61,7 +61,7 @@ func TestCheckUpdateFindsNewerStableOnly(t *testing.T) { defer srv.Close() src := Source{APIBase: srv.URL, Repo: "Nwflower/Reims-Go", Client: srv.Client()} - info, err := src.CheckUpdate(context.Background(), "v0.2.1") + info, err := src.CheckUpdate(context.Background(), "v0.2.1", ChannelStable) if err != nil { t.Fatalf("CheckUpdate: %v", err) } @@ -79,7 +79,7 @@ func TestCheckUpdateFindsNewerStableOnly(t *testing.T) { } // Same version reports up to date. - upToDate, err := src.CheckUpdate(context.Background(), "v0.2.2") + upToDate, err := src.CheckUpdate(context.Background(), "v0.2.2", ChannelStable) if err != nil { t.Fatalf("CheckUpdate(same): %v", err) } @@ -89,7 +89,7 @@ func TestCheckUpdateFindsNewerStableOnly(t *testing.T) { // Prerelease of the released stable version upgrades to stable. for _, pre := range []string{"v0.2.2-alpha.1", "v0.2.2-dev-66da194"} { - preInfo, err := src.CheckUpdate(context.Background(), pre) + preInfo, err := src.CheckUpdate(context.Background(), pre, ChannelStable) if err != nil { t.Fatalf("CheckUpdate(%s): %v", pre, err) } @@ -99,7 +99,7 @@ func TestCheckUpdateFindsNewerStableOnly(t *testing.T) { } // Prerelease of a newer version does not downgrade to an older stable release. - ahead, err := src.CheckUpdate(context.Background(), "v0.2.3-dev-66da194") + ahead, err := src.CheckUpdate(context.Background(), "v0.2.3-dev-66da194", ChannelStable) if err != nil { t.Fatalf("CheckUpdate(ahead): %v", err) } @@ -155,7 +155,7 @@ func TestCheckUpdateChannels(t *testing.T) { src := Source{APIBase: srv.URL, Repo: "Nwflower/Reims-Go", Client: srv.Client()} // Stable channel ignores alpha and dev. - st, err := src.CheckUpdateChannel(context.Background(), "v0.2.8", ChannelStable) + st, err := src.CheckUpdate(context.Background(), "v0.2.8", ChannelStable) if err != nil { t.Fatalf("stable: %v", err) } @@ -164,7 +164,7 @@ func TestCheckUpdateChannels(t *testing.T) { } // Alpha channel picks v0.2.9-alpha.1 (ignoring dev). - al, err := src.CheckUpdateChannel(context.Background(), "v0.2.8", ChannelAlpha) + al, err := src.CheckUpdate(context.Background(), "v0.2.8", ChannelAlpha) if err != nil { t.Fatalf("alpha: %v", err) } @@ -173,7 +173,7 @@ func TestCheckUpdateChannels(t *testing.T) { } // Dev channel extracts version from rolling dev asset and detects update across non-monotonic SHAs. - dv, err := src.CheckUpdateChannel(context.Background(), "v0.2.9-dev-fffffff", ChannelDev) + dv, err := src.CheckUpdate(context.Background(), "v0.2.9-dev-fffffff", ChannelDev) if err != nil { t.Fatalf("dev: %v", err) } @@ -182,7 +182,7 @@ func TestCheckUpdateChannels(t *testing.T) { } // Dev channel reports up to date when SHA matches. - dvSame, err := src.CheckUpdateChannel(context.Background(), "v0.2.9-dev-0123456", ChannelDev) + dvSame, err := src.CheckUpdate(context.Background(), "v0.2.9-dev-0123456", ChannelDev) if err != nil { t.Fatalf("dev same: %v", err) } diff --git a/internal/vmstart/core.go b/internal/vmstart/core.go index 4880972..b8fa272 100644 --- a/internal/vmstart/core.go +++ b/internal/vmstart/core.go @@ -5,14 +5,12 @@ package vmstart import ( "bufio" "context" - "fmt" "os" "strconv" "strings" "time" "github.com/Nwflower/reims-go/internal/host" - "github.com/Nwflower/reims-go/internal/i18n" ) func parseSizeGB(raw string) (float64, bool) { @@ -78,25 +76,6 @@ func waitForCommitMemory(ctx context.Context, memory string, timeout, pollInterv } } -// PinQEMU applies the safe host affinity plan and returns a human log line. -func PinQEMU(loc i18n.Locale, rep host.Report, pid, vcpus int) string { - plan := host.SelectSafeAffinity(rep, vcpus) - if plan.Mode == "all" { - return i18n.M(loc, "vmstart.pin.skipped", i18n.Vars{"vcpus": vcpus, "pthreads": plan.PThreads}) - } - err := host.PinProcessToPCores(uint32(pid), plan.Mask) - if plan.Mode == "non_lpe" { - if err != nil { - return fmt.Sprintf("[CPU] Warning: P+E core pinning failed for PID %d: %v", pid, err) - } - return i18n.M(loc, "vmstart.pin.non_lpe", i18n.Vars{"vcpus": vcpus, "pthreads": plan.PThreads, "pid": pid, "cores": plan.CoreCount, "threads": plan.ThreadCount, "mask": plan.MaskHex, "lpe": rep.LPECoreCount}) - } - if err != nil { - return fmt.Sprintf("[CPU] Warning: P-core pinning failed for PID %d: %v", pid, err) - } - return i18n.M(loc, "vmstart.pin.pcores", i18n.Vars{"pid": pid, "cores": plan.CoreCount, "threads": plan.ThreadCount, "mask": plan.MaskHex, "excluded": rep.ECoreCount + rep.LPECoreCount}) -} - // LineWriter turns command output into one log call per non-empty line. type LineWriter func(string) diff --git a/locales/en-US/native.json b/locales/en-US/native.json index a0100fb..124aa75 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -259,12 +259,6 @@ "name" ] }, - "vm.resize.stop_first": { - "message": "stop {name} before resizing its disk", - "$params": [ - "name" - ] - }, "vm.resize.done": { "message": "{name}: expanded disk {before, number, .0} GB -> {after, number, .0} GB\nRun inside macOS Terminal to expand APFS:\n {cmd}", "$params": [ @@ -274,12 +268,6 @@ "cmd" ] }, - "vm.compact.stop_first": { - "message": "stop {name} before compacting its disk", - "$params": [ - "name" - ] - }, "vm.compact.done": { "message": "{name}: compacted disk {before, number, .2} GB -> {after, number, .2} GB (reclaimed {saved, number, .2} GB)", "$params": [ @@ -511,13 +499,6 @@ "backend" ] }, - "tray.running.one": "Reims-Go — 1 VM running", - "tray.running.many": { - "message": "Reims-Go — {count} VMs running", - "$params": [ - "count" - ] - }, "tray.running": { "message": "{count, plural, one {Reims-Go — # VM running} other {Reims-Go — # VMs running}}", "$params": [ @@ -570,12 +551,6 @@ "name" ] }, - "tray.notify.discard_suspend_fail": { - "message": "Couldn't discard saved state for {name}", - "$params": [ - "name" - ] - }, "tray.notify.stop_fail": { "message": "Couldn't shut down {name}", "$params": [ @@ -842,35 +817,6 @@ "code" ] }, - "vmstart.pin.skipped": { - "message": "[CPU] Skipped CPU pinning: VM has {vcpus} vCPUs, exceeding safe headroom (only {pthreads} P-core threads); using all host CPUs to avoid spinlock stall", - "$params": [ - "vcpus", - "pthreads" - ] - }, - "vmstart.pin.non_lpe": { - "message": "[CPU] VM has {vcpus} vCPUs (exceeds {pthreads} P-core threads); pinned QEMU (PID {pid}) to P+E cores ({cores} cores / {threads} logical CPUs, mask {mask}; {lpe} slow LP-E cores excluded)", - "$params": [ - "vcpus", - "pthreads", - "pid", - "cores", - "threads", - "mask", - "lpe" - ] - }, - "vmstart.pin.pcores": { - "message": "[CPU] Pinned QEMU (PID {pid}) to {cores} P-cores ({threads} logical CPUs, mask {mask}; {excluded} E/LP-E cores excluded)", - "$params": [ - "pid", - "cores", - "threads", - "mask", - "excluded" - ] - }, "affinity.eco_suffix": ", EcoQoS disabled", "affinity.applied.pcores": { "message": "[CPU] Pinned QEMU (PID {pid}) to P-cores ({count} logical CPUs, mask {mask}{eco})", @@ -1098,25 +1044,6 @@ }, "err.affinity.empty_mask": "Select at least 1 logical processor", "core.preflight.whpx_irqchip_advice": "Host lacks nested-virt property and runtime lacks nested-virt-nonfatal capability; kernel-irqchip=off will be auto-applied", - "core.start.warn.offline_helper_skipped": { - "message": "Offline install helper disk skipped: {err}", - "$params": [ - "err" - ] - }, - "core.start.warn.opencore_picker_failed": { - "message": "Could not update OpenCore boot picker: {err}", - "$params": [ - "err" - ] - }, - "core.start.warn.opencore_lang_failed": { - "message": "Could not apply macOS language to OpenCore: {err}", - "$params": [ - "err" - ] - }, - "core.start.warn.whpx_irqchip_applied": "Host rejects nested-virtualization property; enabled kernel-irqchip=off automatically", "validate.invalid_guest_lang": "Invalid guest language code (expected format like zh-Hans:0 or en-US:0)", "validate.vm_suspended": "Resume or discard the VM's suspended state before changing its settings", "err.suspend.unsupported_runtime": "The active portable runtime does not support VM suspend/resume; update to a runtime built with suspend support", diff --git a/locales/en-US/plugins.json b/locales/en-US/plugins.json index d3219bb..363b1fe 100644 --- a/locales/en-US/plugins.json +++ b/locales/en-US/plugins.json @@ -39,7 +39,6 @@ "pluginThemePackLabel": "Theme pack", "pluginNewScheme": "New scheme", "pluginColorSchemes": "Color schemes", - "pluginColorSchemesHint": "Seed colors derive the full surface, text, and accent ramp", "pluginDeleteScheme": "Delete scheme", "pluginExternalSection": "Installed plugins", "pluginLinkDevBtn": "Link plugin dev folder", @@ -74,7 +73,6 @@ "pluginMarketEmpty": "No plugins available in the market index yet. You can still import local .zip packages or configure a custom index URL.", "pluginMarketStaleBanner": "Remote market index is unreachable; showing cached or offline fallback data", "pluginMarketInstall": "Install", - "pluginMarketUpdate": "Update to v{version}", "pluginMarketInstalled": "Installed", "pluginMarketIncompatible": "Incompatible", "pluginMarketWithdrawn": "Withdrawn", @@ -96,7 +94,6 @@ "pluginScanMoreItems": "...and {count} more", "pluginScanInstallConfirm": "Proceed with install", "pluginScanBlockedBtn": "Blocked — cannot install", - "pluginScanLoading": "Scanning plugin package…", "pluginFailScan": "Couldn’t scan plugin", "pluginPermCount": { "message": "{count, plural, one {# permission} other {# permissions}}", diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index 65cba79..c9f06ae 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -67,7 +67,6 @@ "message": "{count, plural, one {# older version} other {# older versions}}", "$comment": "镜像页面折叠的旧点版本计数按钮" }, - "installersEmpty": "No images downloaded yet", "installersPartial": "Partly downloaded", "installersResume": "Resume", "installersDownload": "Download", @@ -89,9 +88,6 @@ "installersQueued": "Queued", "installersQueuedForVM": "Queued for {vm}", "installersWaitingVM": "{vm} waiting", - "footerMem": "Memory {pct}%", - "footerMemAvail": "{avail} GB free", - "footerDisk": "Disk {gb} GB free", "updateDownloadInstall": "Download and install", "updateReleaseNotes": "Release notes", "updateDownloadingSub": "Downloading {v}", @@ -117,12 +113,9 @@ "storageRuntimes": "Reims-Go", "welcomeTitle": "Create your first macOS VM", "welcomeSub": "Pick an installer, assign cores and GPU, and launch in minutes", - "welcomeCheckHost": "Set up Engine first →", "back": "Back", "next": "Next", "choose": "Browse…", - "guestToolsConnected": "Connected", - "guestToolsReady": "Configured", "hostRuntime": "Runtime", "hostGPUs": "Graphics cards", "language": "Language", @@ -139,7 +132,6 @@ "appUpdateChannelAlpha": "Alpha", "appUpdateChannelDev": "Dev", "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", @@ -191,7 +183,6 @@ "vmDir": "Folder", "sourceInstaller": "Local installer image (.img / .dmg)", "sourceDisk": "Existing virtual disk (.qcow2)", - "offlineListFailed": "Couldn’t read Apple’s release list", "networkOfflineHint": "Off by default for offline installs. Exit recovery and restart when Setup Assistant appears to enable networking", "macosVersion": "macOS version", "diskSize": "Disk size", @@ -204,12 +195,10 @@ "gpuSelect": "GPU", "gpuAutoOption": "Automatic (prefers discrete)", "enableAudio": "Audio", - "enableNetwork": "Network (NAT)", "sshPort": "SSH forward port", "enableLogs": "Keep graphics and serial logs", "startAfterCreate": "Start after creating", "settingsTitle": "{name}", - "gtInstallCmd": "Install command", "networkTitle": "Network", "logLevelDesc": "Raise only when troubleshooting", "secondsUnit": "s", @@ -250,7 +239,6 @@ "displayGroup": "Displays", "resCustom": "Custom", "resCustomSub": "Width × height", - "resFullscreen": "Full screen", "resNativeBadge": "Native", "resScaleToFitWindow": "Scale to fit window", "resInvalid": "Use WIDTHxHEIGHT, e.g. 2560x1600", @@ -319,8 +307,6 @@ "affinitySummaryPCores": "P-Cores ({count}T · {mask})", "affinitySummaryNonLPE": "P + E ({count}T · {mask})", "affinitySummaryCustom": "Custom ({count}T · {mask})", - "failAffinity": "Could not update processor affinity", - "networkDesc": "Uses the Windows network connection", "sshForward": "SSH port forwarding", "sshOffDesc": "Log in to macOS over SSH from Windows", "sshNeedsNetwork": "Turn on the network first", @@ -361,8 +347,6 @@ "optKernelIrqchipNestedErr": "Not supported by this Windows ({code}); Auto keeps it off", "optKernelIrqchipUnavailable": "Not supported on this PC", "optSchedTitle": "Windows processor scheduling", - "optSchedPrograms": "Programs", - "optSchedBackground": "Background services", "optSchedSub": "Background services keeps the VM steady in the background (affects all of Windows)", "optSchedNowPrograms": "Set to Programs, so the VM may slow down in the background. Background services is recommended (affects all of Windows)", "optSchedNowBackground": "Set to Background services, which suits a VM running in the background (affects all of Windows)", @@ -395,7 +379,6 @@ "fullscreenLaunch": "Launch borderless fullscreen", "fullscreenLaunchHint": "Opens macOS in borderless full screen", "fullscreenDecoupledHint": "Fills the monitor; pick native or supersampled HiDPI (e.g. 5120×2880 for 4K 1.5×) below, scaled on the GPU", - "guestToolsPreventSleepSub": "Keeps macOS awake while idle; applies immediately", "guestLangHint": "Used by Recovery, Setup Assistant and the login window; a US keyboard layout keeps Terminal input reliable", "guestLangSettingsHint": "Used by Recovery, Setup Assistant and the login window", "diskControllerVirtioHint": "Lower overhead but experimental; switch back to NVMe if you hit problems", @@ -436,11 +419,6 @@ "hostAudioMissingOut": "No speakers or headphones found; the VM will be silent", "hostAudioMissingIn": "No microphone found; macOS will record silence", "audioTroubleshootNote": "If audio crackles, set the Windows sound format to 48000 Hz. If the mic is silent, check Windows Privacy › Microphone", - "statsCPU": "QEMU CPU", - "statsMemory": "Host RAM", - "statsDisk": "Disk usage", - "statsUptime": "Uptime", - "statsDiskSub": "{actual} actual / {virtual} max", "effectImmediate": "Immediate", "effectNextStart": "Next start", "themePluginDarkDisabled": "Default theme plugin is disabled; dark and system appearances are unavailable", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index 6132c64..664be53 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -259,12 +259,6 @@ "name" ] }, - "vm.resize.stop_first": { - "message": "请先停止 {name} 再扩容虚拟磁盘", - "$params": [ - "name" - ] - }, "vm.resize.done": { "message": "{name}:虚拟磁盘已扩容 {before, number, .0} GB -> {after, number, .0} GB\n请在 macOS 终端执行以下命令扩展 APFS 容器:\n {cmd}", "$params": [ @@ -274,12 +268,6 @@ "cmd" ] }, - "vm.compact.stop_first": { - "message": "请先停止 {name} 再回收磁盘空间", - "$params": [ - "name" - ] - }, "vm.compact.done": { "message": "{name}:磁盘已瘦身 {before, number, .2} GB -> {after, number, .2} GB(回收 {saved, number, .2} GB)", "$params": [ @@ -511,13 +499,6 @@ "backend" ] }, - "tray.running.one": "Reims-Go — 1 台虚拟机运行中", - "tray.running.many": { - "message": "Reims-Go — {count} 台虚拟机运行中", - "$params": [ - "count" - ] - }, "tray.running": { "message": "{count, plural, =1 {Reims-Go — 1 台虚拟机运行中} other {Reims-Go — # 台虚拟机运行中}}", "$params": [ @@ -570,12 +551,6 @@ "name" ] }, - "tray.notify.discard_suspend_fail": { - "message": "无法放弃 {name} 的挂起状态", - "$params": [ - "name" - ] - }, "tray.notify.stop_fail": { "message": "无法关机 {name}", "$params": [ @@ -842,35 +817,6 @@ "code" ] }, - "vmstart.pin.skipped": { - "message": "[CPU] 跳过绑核:虚拟机配置了 {vcpus} vCPU,超过可用安全绑定线程上限(P 核仅 {pthreads} 线程),已使用全部核心避免超售卡顿", - "$params": [ - "vcpus", - "pthreads" - ] - }, - "vmstart.pin.non_lpe": { - "message": "[CPU] 虚拟机配置了 {vcpus} vCPU(超过 {pthreads} 个 P 核线程),已自动将 QEMU (PID {pid}) 绑定到 P+E 核({cores} 核 / {threads} 线程,掩码 {mask};仅排除 {lpe} 个慢速 LP-E 核)", - "$params": [ - "vcpus", - "pthreads", - "pid", - "cores", - "threads", - "mask", - "lpe" - ] - }, - "vmstart.pin.pcores": { - "message": "[CPU] 已将 QEMU (PID {pid}) 绑定到 {cores} 个 P 核({threads} 个逻辑线程,掩码 {mask};未占用 {excluded} 个 E 核)", - "$params": [ - "pid", - "cores", - "threads", - "mask", - "excluded" - ] - }, "affinity.eco_suffix": ",已禁用 EcoQoS 节流", "affinity.applied.pcores": { "message": "[CPU] 已将 QEMU (PID {pid}) 绑定到 P 核({count} 个逻辑处理器,掩码 {mask}{eco})", @@ -1098,25 +1044,6 @@ }, "err.affinity.empty_mask": "请至少选择 1 个可用的逻辑处理器", "core.preflight.whpx_irqchip_advice": "宿主不支持 nested-virt 属性且当前运行时未包含非致命降级补丁,启动虚拟机时将自动附加 kernel-irqchip=off", - "core.start.warn.offline_helper_skipped": { - "message": "已跳过离线装机辅助盘挂载:{err}", - "$params": [ - "err" - ] - }, - "core.start.warn.opencore_picker_failed": { - "message": "未能更新 OpenCore 启动选择器配置:{err}", - "$params": [ - "err" - ] - }, - "core.start.warn.opencore_lang_failed": { - "message": "未能向 OpenCore 写入客户机语言设置:{err}", - "$params": [ - "err" - ] - }, - "core.start.warn.whpx_irqchip_applied": "宿主拒绝了嵌套虚拟化属性,已自动启用 kernel-irqchip=off 兼容参数", "validate.invalid_guest_lang": "客户机系统语言标识格式无效(如 zh-Hans:0、en-US:0)", "validate.vm_suspended": "虚拟机当前处于挂起状态,请先恢复或放弃挂起状态后再修改配置", "err.suspend.unsupported_runtime": "当前激活的便携运行时尚未包含虚拟机挂起/恢复支持,请更新至包含挂起补丁的运行时版本", diff --git a/locales/zh-CN/plugins.json b/locales/zh-CN/plugins.json index 5954c67..b3aa6db 100644 --- a/locales/zh-CN/plugins.json +++ b/locales/zh-CN/plugins.json @@ -39,7 +39,6 @@ "pluginThemePackLabel": "主题包", "pluginNewScheme": "新建配色方案", "pluginColorSchemes": "配色方案", - "pluginColorSchemesHint": "修改种子色派生整套界面色阶", "pluginDeleteScheme": "删除方案", "pluginExternalSection": "已安装插件", "pluginLinkDevBtn": "链接插件开发目录", @@ -74,7 +73,6 @@ "pluginMarketEmpty": "当前插件市场暂无可用条目,你仍可导入本地 .zip 插件包或配置自定义市场索引地址", "pluginMarketStaleBanner": "远程插件市场暂不可达,当前显示本地缓存或内置回退索引", "pluginMarketInstall": "安装", - "pluginMarketUpdate": "更新至 v{version}", "pluginMarketInstalled": "已安装", "pluginMarketIncompatible": "不兼容", "pluginMarketWithdrawn": "已撤回", @@ -96,7 +94,6 @@ "pluginScanMoreItems": "另有 {count} 项已折叠", "pluginScanInstallConfirm": "确认导入安装", "pluginScanBlockedBtn": "已拦截,无法安装", - "pluginScanLoading": "正在扫描插件包…", "pluginFailScan": "插件安全扫描失败", "pluginPermCount": { "message": "{count, plural, other {# 项权限}}", diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index 96a4453..6a1e680 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -67,7 +67,6 @@ "message": "{count, plural, other {# 个旧版本}}", "$comment": "镜像页面折叠的旧点版本计数按钮" }, - "installersEmpty": "还没有下载任何镜像", "installersPartial": "未下载完", "installersResume": "继续下载", "installersDownload": "下载", @@ -89,9 +88,6 @@ "installersQueued": "排队中", "installersQueuedForVM": "为 {vm} 排队中", "installersWaitingVM": "{vm} 等待使用", - "footerMem": "内存 {pct}%", - "footerMemAvail": "可用 {avail} GB", - "footerDisk": "磁盘可用 {gb} GB", "updateDownloadInstall": "下载并安装", "updateReleaseNotes": "发行说明", "updateDownloadingSub": "正在下载 {v}", @@ -117,12 +113,9 @@ "storageRuntimes": "Reims-Go", "welcomeTitle": "创建第一台 macOS 虚拟机", "welcomeSub": "选择系统来源、分配核数与显卡,几步完成配置", - "welcomeCheckHost": "先完成内核环境配置 →", "back": "上一步", "next": "下一步", "choose": "浏览…", - "guestToolsConnected": "已连接", - "guestToolsReady": "已配置", "hostRuntime": "运行时", "hostGPUs": "显卡", "language": "语言", @@ -139,7 +132,6 @@ "appUpdateChannelAlpha": "Alpha", "appUpdateChannelDev": "Dev", "appCheckUpdate": "检查更新", - "appDownloadUpdate": "前往下载", "appUpdateLookupFailed": "暂时无法连接 GitHub 检查更新", "aboutDiscord": "Discord 社区", "aboutDiscordSub": "交流使用体验、硬件兼容反馈、Alpha 测试与插件开发", @@ -191,7 +183,6 @@ "vmDir": "存放目录", "sourceInstaller": "本地安装器镜像(.img / .dmg)", "sourceDisk": "已有虚拟磁盘(.qcow2)", - "offlineListFailed": "无法读取 Apple 的版本列表", "networkOfflineHint": "离线安装默认关闭;看到「设置助理」后退出恢复模式并重启即可联网", "macosVersion": "macOS 版本", "diskSize": "磁盘上限", @@ -204,12 +195,10 @@ "gpuSelect": "显卡", "gpuAutoOption": "自动(优先独显)", "enableAudio": "音频", - "enableNetwork": "网络(NAT)", "sshPort": "SSH 转发端口", "enableLogs": "记录图形与串口日志", "startAfterCreate": "创建后立即启动", "settingsTitle": "{name}", - "gtInstallCmd": "安装命令", "networkTitle": "网络", "logLevelDesc": "排查问题时再调高", "secondsUnit": "秒", @@ -250,7 +239,6 @@ "displayGroup": "显示器", "resCustom": "自定义", "resCustomSub": "宽 × 高", - "resFullscreen": "全屏", "resNativeBadge": "原生", "resScaleToFitWindow": "缩放以适应窗口", "resInvalid": "格式为 宽x高,例如 2560x1600", @@ -319,8 +307,6 @@ "affinitySummaryPCores": "仅 P 核({count} 线程 · {mask})", "affinitySummaryNonLPE": "P + E 核({count} 线程 · {mask})", "affinitySummaryCustom": "自定义({count} 线程 · {mask})", - "failAffinity": "设置处理器相关性失败", - "networkDesc": "通过 Windows 的网络连接上网", "sshForward": "SSH 端口转发", "sshOffDesc": "从 Windows 用 SSH 登录 macOS", "sshNeedsNetwork": "需要先开启网络", @@ -361,8 +347,6 @@ "optKernelIrqchipNestedErr": "当前 Windows 不支持({code}),「自动」会保持关闭", "optKernelIrqchipUnavailable": "当前电脑不支持", "optSchedTitle": "Windows 处理器调度", - "optSchedPrograms": "程序优先", - "optSchedBackground": "后台服务", "optSchedSub": "选「后台服务」,虚拟机在后台时更稳定(影响整个 Windows)", "optSchedNowPrograms": "当前为「程序优先」,虚拟机在后台时可能变慢,建议改为「后台服务」(影响整个 Windows)", "optSchedNowBackground": "当前为「后台服务」,适合虚拟机在后台运行(影响整个 Windows)", @@ -395,7 +379,6 @@ "fullscreenLaunch": "无边框全屏启动", "fullscreenLaunchHint": "启动后直接进入无边框全屏", "fullscreenDecoupledHint": "窗口铺满屏幕;下方分辨率可独立设为原生或超采样 HiDPI(如 4K 1.5× = 5120×2880),由 GPU 自动缩放", - "guestToolsPreventSleepSub": "闲置时让 macOS 保持唤醒,立即生效", "guestLangHint": "恢复模式、设置助理和登录界面使用的语言;选美式键盘,在终端输命令不易出错", "guestLangSettingsHint": "恢复模式、设置助理和登录界面使用的语言", "diskControllerVirtioHint": "VirtIO 开销更低,仍属实验性;遇到问题请改回 NVMe", @@ -436,11 +419,6 @@ "hostAudioMissingOut": "没有检测到扬声器或耳机,虚拟机将没有声音", "hostAudioMissingIn": "没有检测到麦克风,macOS 录不到声音", "audioTroubleshootNote": "有爆音时,把 Windows 声音格式设为 48000 Hz;麦克风没声音时,检查 Windows「隐私 › 麦克风」权限", - "statsCPU": "QEMU CPU", - "statsMemory": "宿主机内存", - "statsDisk": "磁盘占用", - "statsUptime": "运行时长", - "statsDiskSub": "实际 {actual} / 上限 {virtual}", "effectImmediate": "立即生效", "effectNextStart": "下次启动生效", "themePluginDarkDisabled": "默认主题插件已停用,深色与跟随系统外观不可用", From 90fbce8b47cf5e99fd3571d36681fbd33f777244 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: Thu, 3 Dec 2026 20:59:56 -0700 Subject: [PATCH 02/22] refactor: write small files through one atomic writer Fifteen call sites each had their own temp-file-and-rename code. Some used a fixed temporary name, so two writers could mix their content, and most did not flush before the rename. They now share atomicfile.Write. An architecture test keeps new os.Rename calls out of other packages. Co-Authored-By: Claude Opus 5.5 --- internal/app/plugin_bridge_files.go | 8 +-- internal/app/secret_materialize_flow.go | 42 ++--------- internal/app/thumbnail_flow.go | 6 +- internal/archtest/file_replace_test.go | 58 ++++++++++++++++ internal/atomicfile/atomicfile.go | 43 ++++++++++++ internal/atomicfile/atomicfile_test.go | 92 +++++++++++++++++++++++++ internal/cli/start.go | 7 +- internal/config/config.go | 19 ++--- internal/datamigrate/datamigrate.go | 13 +--- internal/downloader/parallel.go | 6 +- internal/guesttools/server.go | 16 +---- internal/host/hypervisor.go | 27 +------- internal/plugin/ledger.go | 32 +-------- internal/plugin/market.go | 28 +------- internal/plugin/state.go | 18 ++--- internal/plugin/view_storage.go | 13 +--- internal/vmstart/affinity.go | 13 +--- internal/vmstart/display.go | 16 +---- internal/vmstart/keymap.go | 17 +---- internal/vmstart/nestedvirt.go | 17 +---- 20 files changed, 241 insertions(+), 250 deletions(-) create mode 100644 internal/archtest/file_replace_test.go create mode 100644 internal/atomicfile/atomicfile.go create mode 100644 internal/atomicfile/atomicfile_test.go diff --git a/internal/app/plugin_bridge_files.go b/internal/app/plugin_bridge_files.go index 9437c02..dda63c3 100644 --- a/internal/app/plugin_bridge_files.go +++ b/internal/app/plugin_bridge_files.go @@ -13,6 +13,7 @@ import ( "time" "unicode/utf8" + "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/plugin" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) @@ -226,12 +227,7 @@ func (a *App) panelFileCall(mgr *plugin.Manager, pluginID, method string, params if len(data) > maxPanelFileBytes { return nil, fmt.Errorf("data exceeds %d bytes", maxPanelFileBytes) } - tmp := path + "." + id + ".reims-plugin-tmp" - if err := os.WriteFile(tmp, data, 0o600); err != nil { - return nil, err - } - if err := os.Rename(tmp, path); err != nil { - _ = os.Remove(tmp) + if err := atomicfile.Write(path, data, 0o600); err != nil { return nil, err } return map[string]any{"ok": true, "name": filepath.Base(path), "size": len(data)}, nil diff --git a/internal/app/secret_materialize_flow.go b/internal/app/secret_materialize_flow.go index 2a35131..6edc5e8 100644 --- a/internal/app/secret_materialize_flow.go +++ b/internal/app/secret_materialize_flow.go @@ -14,6 +14,7 @@ import ( "sync" "unicode/utf16" + "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/plugin" ) @@ -170,37 +171,10 @@ func (a *App) materializeSecret(broker *plugin.Broker, source secretSource, plug } func writeSecretFile(dest string, content []byte) error { - dir := filepath.Dir(dest) - if err := os.MkdirAll(dir, 0o755); err != nil { + if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil { return err } - tmp, err := os.CreateTemp(dir, ".secret-*") - if err != nil { - return err - } - tmpName := tmp.Name() - ok := false - defer func() { - if !ok { - _ = os.Remove(tmpName) - } - }() - if err := tmp.Chmod(0o600); err != nil { - _ = tmp.Close() - return err - } - if _, err := tmp.Write(content); err != nil { - _ = tmp.Close() - return err - } - if err := tmp.Close(); err != nil { - return err - } - if err := os.Rename(tmpName, dest); err != nil { - return err - } - ok = true - return nil + return atomicfile.Write(dest, content, 0o600) } func (a *App) materializedSecretsPath() string { @@ -234,18 +208,10 @@ func saveMaterializedSecrets(path string, doc materializedSecretsFile) error { } return nil } - raw, err := json.MarshalIndent(doc, "", " ") - if err != nil { - return err - } if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return err } - tmp := path + ".tmp" - if err := os.WriteFile(tmp, raw, 0o600); err != nil { - return err - } - return os.Rename(tmp, path) + return atomicfile.WriteJSON(path, doc, 0o600) } func samePath(a, b string) bool { return strings.EqualFold(filepath.Clean(a), filepath.Clean(b)) } diff --git a/internal/app/thumbnail_flow.go b/internal/app/thumbnail_flow.go index 20bc9d9..6ee9665 100644 --- a/internal/app/thumbnail_flow.go +++ b/internal/app/thumbnail_flow.go @@ -18,6 +18,7 @@ import ( "sync" "time" + "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/guesttools" "github.com/Nwflower/reims-go/internal/host" @@ -289,10 +290,7 @@ func (a *App) captureThumbWithDriver(driverID, name, path string) (VMThumbnail, return VMThumbnail{}, false } if err := os.MkdirAll(filepath.Dir(path), 0o755); err == nil { - part := path + ".part" - if os.WriteFile(part, jpg, 0o644) == nil { - _ = os.Rename(part, path) - } + _ = atomicfile.Write(path, jpg, 0o644) } return VMThumbnail{ DataURL: "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(jpg), diff --git a/internal/archtest/file_replace_test.go b/internal/archtest/file_replace_test.go new file mode 100644 index 0000000..e6d1056 --- /dev/null +++ b/internal/archtest/file_replace_test.go @@ -0,0 +1,58 @@ +package archtest + +import ( + "go/ast" + "testing" +) + +// renameOwners move something atomicfile cannot write: a directory, an image or +// download too large for memory, a rotated log, the running executable, or +// several files that must change together. +var renameOwners = map[string]bool{ + "internal/app/guesttools_flow.go": true, // file copied into the shared folder + "internal/app/ui_health.go": true, // log rotation + "internal/atomicfile/atomicfile.go": true, + "internal/fetch/fetch.go": true, // download + "internal/macos/installer/accelerated.go": true, // download + "internal/macos/installer/hfs_image.go": true, // disk image + "internal/macos/installer/oc_cache.go": true, // download + "internal/macos/installer/recovery.go": true, // download + "internal/macos/installguide/progress.go": true, // macOS may not import atomicfile, see macosHostImports + "internal/macos/reims/network_record.go": true, // same + "internal/macos/opencore/image.go": true, // disk image with rollback + "internal/macos/reims/disk_import.go": true, // disk image with rollback + "internal/macos/reims/suspend_transaction.go": true, // state and metadata commit together + "internal/plugin/broker.go": true, // log rotation + "internal/plugin/pack.go": true, // archive + "internal/plugin/package.go": true, // plugin directory + "internal/runtime/runtime.go": true, // runtime directory + "internal/selfupdate/selfupdate.go": true, // running executable +} + +func TestSmallFilesAreReplacedThroughAtomicfile(t *testing.T) { + seen := map[string]bool{} + for _, s := range sources(t) { + if s.isTest() { + continue + } + ast.Inspect(s.file, func(n ast.Node) bool { + sel, ok := n.(*ast.SelectorExpr) + if !ok || sel.Sel.Name != "Rename" { + return true + } + if pkg, ok := sel.X.(*ast.Ident); !ok || pkg.Name != "os" { + return true + } + seen[s.rel] = true + if !renameOwners[s.rel] { + t.Errorf("%s calls os.Rename: write small files with atomicfile.Write or atomicfile.WriteJSON", s.rel) + } + return true + }) + } + for rel := range renameOwners { + if !seen[rel] { + t.Errorf("%s no longer calls os.Rename: remove it from renameOwners", rel) + } + } +} diff --git a/internal/atomicfile/atomicfile.go b/internal/atomicfile/atomicfile.go new file mode 100644 index 0000000..9020b92 --- /dev/null +++ b/internal/atomicfile/atomicfile.go @@ -0,0 +1,43 @@ +// Package atomicfile replaces small files so that a reader, a concurrent +// writer or a crash never leaves a partly written file behind. +package atomicfile + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" +) + +// Write replaces path with data. The directory must exist. On failure the +// previous file stays as it was and no temporary file is left. +func Write(path string, data []byte, perm os.FileMode) error { + f, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*.tmp") + if err != nil { + return err + } + _, err = f.Write(data) + if err == nil { + err = f.Chmod(perm) + } + if err == nil { + err = f.Sync() + } + err = errors.Join(err, f.Close()) + if err == nil { + err = os.Rename(f.Name(), path) + } + if err != nil { + return errors.Join(err, os.Remove(f.Name())) + } + return nil +} + +// WriteJSON replaces path with v as indented JSON. +func WriteJSON(path string, v any, perm os.FileMode) error { + data, err := json.MarshalIndent(v, "", " ") + if err != nil { + return err + } + return Write(path, append(data, '\n'), perm) +} diff --git a/internal/atomicfile/atomicfile_test.go b/internal/atomicfile/atomicfile_test.go new file mode 100644 index 0000000..12dbdaf --- /dev/null +++ b/internal/atomicfile/atomicfile_test.go @@ -0,0 +1,92 @@ +package atomicfile + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "testing" +) + +func entries(t *testing.T, dir string) []string { + t.Helper() + list, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + var names []string + for _, e := range list { + names = append(names, e.Name()) + } + return names +} + +func TestWriteReplacesAndLeavesNoTemporaryFile(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "state.json") + for _, want := range []string{"first, longer content", "second"} { + if err := Write(path, []byte(want), 0o600); err != nil { + t.Fatal(err) + } + if got, err := os.ReadFile(path); err != nil || string(got) != want { + t.Fatalf("content = %q, %v; want %q", got, err, want) + } + } + if got := entries(t, dir); len(got) != 1 { + t.Fatalf("directory holds %v", got) + } +} + +func TestWriteFailureKeepsTargetAndCleansUp(t *testing.T) { + dir := t.TempDir() + target := filepath.Join(dir, "taken") + if err := os.MkdirAll(filepath.Join(target, "child"), 0o755); err != nil { + t.Fatal(err) + } + if err := Write(target, []byte("x"), 0o600); err == nil { + t.Fatal("replacing a directory succeeded") + } + if got := entries(t, dir); len(got) != 1 { + t.Fatalf("directory holds %v", got) + } + if err := Write(filepath.Join(dir, "missing", "f"), nil, 0o600); err == nil { + t.Fatal("writing into a missing directory succeeded") + } +} + +func TestConcurrentWritersNeverMixContent(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "state") + var wg sync.WaitGroup + for i := range 8 { + wg.Go(func() { + // Windows may refuse a rename that races with another one; the file + // must still hold one writer's whole content. + if err := Write(path, []byte(strings.Repeat(fmt.Sprint(i), 4096)), 0o600); err != nil { + t.Logf("writer %d: %v", i, err) + } + }) + } + wg.Wait() + got, err := os.ReadFile(path) + if err != nil || len(got) != 4096 || strings.Trim(string(got), string(got[0])) != "" { + t.Fatalf("mixed content of %d bytes, %v", len(got), err) + } + if left := entries(t, dir); len(left) != 1 { + t.Fatalf("directory holds %v", left) + } +} + +func TestWriteJSONIndentsAndEndsWithNewline(t *testing.T) { + path := filepath.Join(t.TempDir(), "v.json") + if err := WriteJSON(path, map[string]int{"a": 1}, 0o644); err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(path); string(got) != "{\n \"a\": 1\n}\n" { + t.Fatalf("content = %q", got) + } + if err := WriteJSON(path, func() {}, 0o644); err == nil { + t.Fatal("encoded a function") + } +} diff --git a/internal/cli/start.go b/internal/cli/start.go index 8297ada..50c2334 100644 --- a/internal/cli/start.go +++ b/internal/cli/start.go @@ -10,6 +10,7 @@ import ( "path/filepath" "time" + "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/i18n" @@ -199,9 +200,5 @@ func WriteStartResult(path string, startErr error) error { if err != nil { return err } - part := path + ".part" - if err := os.WriteFile(part, b, 0o644); err != nil { - return err - } - return os.Rename(part, path) + return atomicfile.Write(path, b, 0o644) } diff --git a/internal/config/config.go b/internal/config/config.go index 5625c4c..bc1c05f 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -8,6 +8,7 @@ import ( "runtime" "strings" + "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/i18n" ) @@ -256,26 +257,16 @@ func Save(path string, cfg *Config) error { if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return err } - data, err := json.MarshalIndent(cfg, "", " ") - if err != nil { - return err - } - // Temp file + rename: a crash mid-write leaves the old file, not a - // truncated one. - tmp := path + ".tmp" - if err := os.WriteFile(tmp, append(data, '\n'), 0o644); err != nil { - return err - } - return os.Rename(tmp, path) + return atomicfile.WriteJSON(path, cfg, 0o644) } func (c *Config) RuntimesDir() string { return filepath.Join(c.DataRoot, "runtimes") } func (c *Config) XDGConfigDir() string { return filepath.Join(c.DataRoot, "config") } func (c *Config) XDGDataDir() string { return filepath.Join(c.DataRoot, "data") } func (c *Config) XDGCacheDir() string { return filepath.Join(c.DataRoot, "cache") } -func (c *Config) ImagesDir() string { return filepath.Join(c.DataRoot, "images") } -func (c *Config) TempDir() string { return filepath.Join(c.DataRoot, "tmp") } -func (c *Config) SharedDir() string { return filepath.Join(c.DataRoot, "shared") } +func (c *Config) ImagesDir() string { return filepath.Join(c.DataRoot, "images") } +func (c *Config) TempDir() string { return filepath.Join(c.DataRoot, "tmp") } +func (c *Config) SharedDir() string { return filepath.Join(c.DataRoot, "shared") } func (c *Config) EnsureDirs() error { for _, d := range []string{ diff --git a/internal/datamigrate/datamigrate.go b/internal/datamigrate/datamigrate.go index 2e70f52..956633e 100644 --- a/internal/datamigrate/datamigrate.go +++ b/internal/datamigrate/datamigrate.go @@ -11,6 +11,8 @@ import ( "os" "path/filepath" "time" + + "github.com/Nwflower/reims-go/internal/atomicfile" ) // StampFile sits at the root of the data folder. @@ -141,14 +143,5 @@ func stampExists(dataRoot string) bool { } func writeStamp(dataRoot string, s Stamp) error { - raw, err := json.MarshalIndent(s, "", " ") - if err != nil { - return err - } - path := filepath.Join(dataRoot, StampFile) - tmp := path + ".tmp" - if err := os.WriteFile(tmp, append(raw, '\n'), 0o644); err != nil { - return err - } - return os.Rename(tmp, path) + return atomicfile.WriteJSON(filepath.Join(dataRoot, StampFile), s, 0o644) } diff --git a/internal/downloader/parallel.go b/internal/downloader/parallel.go index fe01ec3..f62b7f2 100644 --- a/internal/downloader/parallel.go +++ b/internal/downloader/parallel.go @@ -19,6 +19,7 @@ import ( "sync/atomic" "time" + "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/netproxy" ) @@ -167,10 +168,7 @@ func saveResumeState(destPath, rawURL string, destOffset, totalSize int64, done if err != nil { return } - tmp := statePath(destPath) + ".tmp" - if os.WriteFile(tmp, raw, 0o644) == nil { - _ = os.Rename(tmp, statePath(destPath)) - } + _ = atomicfile.Write(statePath(destPath), raw, 0o644) } // Download fetches req.URL into req.DestPath (at req.DestOffset) using concurrent diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index a56974c..5a00e18 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -25,6 +25,7 @@ import ( "unicode" "unicode/utf8" + "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/host" "golang.org/x/net/webdav" @@ -218,20 +219,7 @@ func SaveVMConfig(vmDir string, cfg VMConfig) error { if _, err := os.Stat(vmDir); err != nil { return err } - b, err := json.MarshalIndent(cfg, "", " ") - if err != nil { - return err - } - f, err := os.CreateTemp(vmDir, ConfigFileName+"-*") - if err != nil { - return err - } - defer os.Remove(f.Name()) - _, writeErr := f.Write(b) - if err := errors.Join(writeErr, f.Close()); err != nil { - return err - } - return os.Rename(f.Name(), filepath.Join(vmDir, ConfigFileName)) + return atomicfile.WriteJSON(filepath.Join(vmDir, ConfigFileName), cfg, 0o600) } type pendingTextInput struct { diff --git a/internal/host/hypervisor.go b/internal/host/hypervisor.go index 61b0c73..2fe2f1d 100644 --- a/internal/host/hypervisor.go +++ b/internal/host/hypervisor.go @@ -6,6 +6,8 @@ import ( "os" "path/filepath" "sync" + + "github.com/Nwflower/reims-go/internal/atomicfile" ) const ( @@ -126,29 +128,6 @@ func pendingBootFilePath(dataRoot string) string { return filepath.Join(dataRoot, "tmp", pendingBootFileName) } -func writePendingFileAtomic(path string, data []byte) error { - dir := filepath.Dir(path) - f, err := os.CreateTemp(dir, ".hypervisor-pending-*") - if err != nil { - return err - } - tmpName := f.Name() - if _, err := f.Write(data); err != nil { - _ = f.Close() - _ = os.Remove(tmpName) - return err - } - if err := f.Close(); err != nil { - _ = os.Remove(tmpName) - return err - } - if err := os.Rename(tmpName, path); err != nil { - _ = os.Remove(tmpName) - return err - } - return nil -} - // RecordPendingHypervisorBoot records (or clears) the pending hypervisor boot // mode for the current OS boot session. If /tmp already exists, it is // also persisted atomically there so reopening Reims-Go before restarting @@ -186,7 +165,7 @@ func recordPendingHypervisorBootSession(dataRoot string, liveState WHPXState, en tmpDir := filepath.Dir(p) if st, err := os.Stat(tmpDir); err == nil && st.IsDir() { if raw, merr := json.Marshal(rec); merr == nil { - if writePendingFileAtomic(p, append(raw, '\n')) == nil { + if atomicfile.Write(p, append(raw, '\n'), 0o600) == nil { if pendingBootPath != "" && pendingBootPath != p { _ = os.Remove(pendingBootPath) } diff --git a/internal/plugin/ledger.go b/internal/plugin/ledger.go index e54dfa5..afa1ace 100644 --- a/internal/plugin/ledger.go +++ b/internal/plugin/ledger.go @@ -9,6 +9,8 @@ import ( "sort" "strconv" "strings" + + "github.com/Nwflower/reims-go/internal/atomicfile" ) const ArgLedgerFileName = ".reims-go-arg-ledger.json" @@ -195,35 +197,7 @@ func SaveArgLedger(vmDir string, ledger *ArgLedger) error { return err } ledger.Version = 1 - raw, err := json.MarshalIndent(ledger, "", " ") - if err != nil { - return err - } - target := filepath.Join(vmDir, ArgLedgerFileName) - f, err := os.CreateTemp(vmDir, ArgLedgerFileName+".*.tmp") - if err != nil { - return err - } - tmp := f.Name() - if _, err := f.Write(append(raw, '\n')); err != nil { - _ = f.Close() - _ = os.Remove(tmp) - return err - } - if err := f.Sync(); err != nil { - _ = f.Close() - _ = os.Remove(tmp) - return err - } - if err := f.Close(); err != nil { - _ = os.Remove(tmp) - return err - } - if err := os.Rename(tmp, target); err != nil { - _ = os.Remove(tmp) - return err - } - return nil + return atomicfile.WriteJSON(filepath.Join(vmDir, ArgLedgerFileName), ledger, 0o600) } // ReconcileResult holds the merged extra-args, env vars, warnings, and post-start actions. diff --git a/internal/plugin/market.go b/internal/plugin/market.go index cc95dc1..436bf96 100644 --- a/internal/plugin/market.go +++ b/internal/plugin/market.go @@ -17,6 +17,7 @@ import ( "sync" "time" + "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/fetch" "github.com/Nwflower/reims-go/internal/netproxy" ) @@ -699,33 +700,10 @@ func (c *MarketClient) writeDiskCache(idx MarketIndex) error { c.diskCacheMu.Lock() defer c.diskCacheMu.Unlock() cachePath := c.layout.IndexCachePath() - dir := filepath.Dir(cachePath) - if err := os.MkdirAll(dir, 0o755); err != nil { + if err := os.MkdirAll(filepath.Dir(cachePath), 0o755); err != nil { return err } - raw, err := json.MarshalIndent(idx, "", " ") - if err != nil { - return err - } - tmpFile, err := os.CreateTemp(dir, "index-cache-*.tmp") - if err != nil { - return err - } - tmpPath := tmpFile.Name() - if _, err := tmpFile.Write(raw); err != nil { - _ = tmpFile.Close() - _ = os.Remove(tmpPath) - return err - } - if err := tmpFile.Close(); err != nil { - _ = os.Remove(tmpPath) - return err - } - if err := os.Rename(tmpPath, cachePath); err != nil { - _ = os.Remove(tmpPath) - return err - } - return nil + return atomicfile.WriteJSON(cachePath, idx, 0o600) } func selectChannelEntries(entries []MarketEntry, includeAlpha bool) map[string]MarketEntry { diff --git a/internal/plugin/state.go b/internal/plugin/state.go index f3de906..91b3b59 100644 --- a/internal/plugin/state.go +++ b/internal/plugin/state.go @@ -9,6 +9,8 @@ import ( "strings" "sync" "time" + + "github.com/Nwflower/reims-go/internal/atomicfile" ) const ( @@ -116,29 +118,17 @@ func (s *StateStore) Save(st *StateFile) error { if err := os.MkdirAll(s.dir, 0o755); err != nil { return err } - raw, err := json.MarshalIndent(st, "", " ") - if err != nil { - return err - } - raw = append(raw, '\n') target := s.Path() - tmp := target + ".tmp" - if err := os.WriteFile(tmp, raw, 0o644); err != nil { - return err - } - // Preserve previous valid file as .bak before atomic swap. A failed backup + // Preserve the previous valid file as .bak before the swap. A failed backup // aborts the migration/save instead of silently destroying the only fallback. if prev, err := os.ReadFile(target); err == nil { if err := os.WriteFile(target+".bak", prev, 0o644); err != nil { - _ = os.Remove(tmp) return fmt.Errorf("backup plugin state: %w", err) } } else if !errors.Is(err, os.ErrNotExist) { - _ = os.Remove(tmp) return fmt.Errorf("read plugin state before backup: %w", err) } - if err := os.Rename(tmp, target); err != nil { - _ = os.Remove(tmp) + if err := atomicfile.WriteJSON(target, st, 0o644); err != nil { return err } s.data = st diff --git a/internal/plugin/view_storage.go b/internal/plugin/view_storage.go index 83ff4d0..b17bf7c 100644 --- a/internal/plugin/view_storage.go +++ b/internal/plugin/view_storage.go @@ -10,6 +10,8 @@ import ( "strings" "unicode" "unicode/utf8" + + "github.com/Nwflower/reims-go/internal/atomicfile" ) const ( @@ -79,16 +81,7 @@ func (m *Manager) saveViewStorage(pluginID string, st *viewStorageFile) error { if err := os.MkdirAll(dir, 0o700); err != nil { return err } - target := m.viewStoragePath(pluginID) - tmp := target + ".tmp" - if err := os.WriteFile(tmp, raw, 0o600); err != nil { - return err - } - if err := os.Rename(tmp, target); err != nil { - _ = os.Remove(tmp) - return err - } - return nil + return atomicfile.Write(m.viewStoragePath(pluginID), raw, 0o600) } // ViewStorageGet returns one value from a plugin's persistent private view store. diff --git a/internal/vmstart/affinity.go b/internal/vmstart/affinity.go index d2c52b0..720d24f 100644 --- a/internal/vmstart/affinity.go +++ b/internal/vmstart/affinity.go @@ -9,6 +9,7 @@ import ( "path/filepath" "strings" + "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" ) @@ -128,17 +129,7 @@ func SaveVMAffinity(vmDir string, cfg VMAffinityConfig, maxCPUs int) (VMAffinity } else { cfg.CPUs = nil } - data, err := json.MarshalIndent(cfg, "", " ") - if err != nil { - return VMAffinityConfig{}, err - } - dst := filepath.Join(vmDir, affinityConfigFile) - tmp := dst + ".tmp" - if err := os.WriteFile(tmp, data, 0o600); err != nil { - return VMAffinityConfig{}, err - } - if err := os.Rename(tmp, dst); err != nil { - _ = os.Remove(tmp) + if err := atomicfile.WriteJSON(filepath.Join(vmDir, affinityConfigFile), cfg, 0o600); err != nil { return VMAffinityConfig{}, err } return cfg, nil diff --git a/internal/vmstart/display.go b/internal/vmstart/display.go index 8a1f48a..f309fbf 100644 --- a/internal/vmstart/display.go +++ b/internal/vmstart/display.go @@ -7,6 +7,7 @@ import ( "path/filepath" "strings" + "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/host" ) @@ -50,20 +51,7 @@ func SaveVMDisplay(vmDir string, cfg VMDisplayConfig) (VMDisplayConfig, error) { return cfg, nil } - data, err := json.MarshalIndent(cfg, "", " ") - if err != nil { - return VMDisplayConfig{}, err - } - tmp, err := os.CreateTemp(vmDir, vmDisplayConfigFile+".*") - if err != nil { - return VMDisplayConfig{}, err - } - defer os.Remove(tmp.Name()) - _, writeErr := tmp.Write(data) - if err := errors.Join(writeErr, tmp.Close()); err != nil { - return VMDisplayConfig{}, err - } - if err := os.Rename(tmp.Name(), dst); err != nil { + if err := atomicfile.WriteJSON(dst, cfg, 0o600); err != nil { return VMDisplayConfig{}, err } return cfg, nil diff --git a/internal/vmstart/keymap.go b/internal/vmstart/keymap.go index a74fd2a..af3952d 100644 --- a/internal/vmstart/keymap.go +++ b/internal/vmstart/keymap.go @@ -7,6 +7,8 @@ import ( "os" "path/filepath" "strings" + + "github.com/Nwflower/reims-go/internal/atomicfile" ) type KeymapPreset string @@ -155,20 +157,7 @@ func SaveVMKeymap(vmDir string, cfg VMKeymapConfig) (VMKeymapConfig, error) { } else { cfg.Bindings = nil } - data, err := json.MarshalIndent(cfg, "", " ") - if err != nil { - return VMKeymapConfig{}, err - } - tmp, err := os.CreateTemp(vmDir, keymapConfigFile+".*") - if err != nil { - return VMKeymapConfig{}, err - } - defer os.Remove(tmp.Name()) - _, writeErr := tmp.Write(data) - if err := errors.Join(writeErr, tmp.Close()); err != nil { - return VMKeymapConfig{}, err - } - if err := os.Rename(tmp.Name(), dst); err != nil { + if err := atomicfile.WriteJSON(dst, cfg, 0o600); err != nil { return VMKeymapConfig{}, err } return cfg, nil diff --git a/internal/vmstart/nestedvirt.go b/internal/vmstart/nestedvirt.go index f00c381..1775ca0 100644 --- a/internal/vmstart/nestedvirt.go +++ b/internal/vmstart/nestedvirt.go @@ -7,6 +7,8 @@ import ( "os" "path/filepath" "strings" + + "github.com/Nwflower/reims-go/internal/atomicfile" ) const vmNestedVirtConfigFile = ".reims-go-nested-virt.json" @@ -52,18 +54,5 @@ func SaveVMNestedVirt(vmDir string, cfg VMNestedVirtConfig) error { return nil } - data, err := json.MarshalIndent(cfg, "", " ") - if err != nil { - return err - } - tmp, err := os.CreateTemp(vmDir, vmNestedVirtConfigFile+".*") - if err != nil { - return err - } - defer os.Remove(tmp.Name()) - _, writeErr := tmp.Write(data) - if err := errors.Join(writeErr, tmp.Close()); err != nil { - return err - } - return os.Rename(tmp.Name(), dst) + return atomicfile.WriteJSON(dst, cfg, 0o600) } From b203bde6502ce320698b17b9fd0866c3fa4cde6b 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: Thu, 3 Dec 2026 21:09:19 -0700 Subject: [PATCH 03/22] refactor: merge duplicated helpers and the window event contract Events to the frontend go through App.emit, and a test keeps their names in step with wails.ts. QEMU argument splitting, hidden console processes, the macOS release record, the running check and a few smaller helpers now exist once. Co-Authored-By: Claude Opus 5.5 --- internal/app/affinity_flow.go | 5 +- internal/app/app.go | 33 ++++-------- internal/app/clone_flow.go | 2 +- internal/app/create_flow.go | 11 ++-- internal/app/dataroot_flow.go | 5 +- internal/app/disk_flow.go | 4 +- internal/app/display_flow.go | 2 +- internal/app/drive_share_flow.go | 5 +- internal/app/elevate_flow.go | 7 ++- internal/app/events.go | 14 ++++++ internal/app/extras_snapshot_test.go | 12 ----- internal/app/folder_share_flow.go | 5 +- internal/app/fullscreen_hotkey_flow.go | 2 +- internal/app/guesttools_flow.go | 16 ++---- internal/app/host_dns_flow.go | 5 +- internal/app/host_drop.go | 9 ++-- internal/app/hypervisor_flow.go | 11 ++-- internal/app/install_flow.go | 43 ++++------------ internal/app/legacy_ledger_test.go | 6 +-- internal/app/lifecycle_flow.go | 21 +++----- internal/app/macos_detail.go | 11 ++++ internal/app/macos_lifecycle_native.go | 15 +++--- internal/app/macos_release.go | 40 --------------- internal/app/macos_release_test.go | 25 --------- internal/app/macos_settings.go | 7 +-- internal/app/opencore_flow.go | 7 +-- internal/app/plugins_flow.go | 39 ++++++-------- internal/app/runtime_bindings.go | 4 +- internal/app/setup.go | 5 +- internal/app/snapshot_flow.go | 2 +- internal/app/suspend_flow.go | 7 --- internal/app/tasks.go | 5 +- internal/app/thumbnail_flow.go | 2 +- internal/app/ui_health.go | 2 +- internal/archtest/events_test.go | 56 +++++++++++++++++++++ internal/datamigrate/datamigrate.go | 5 +- internal/dataroot/dataroot.go | 7 +-- internal/driver/storage_test.go | 15 ++++++ internal/host/console_other.go | 8 +++ internal/host/console_windows.go | 13 +++++ internal/host/log_diagnose_test.go | 17 +++++++ internal/macos/guest/guest.go | 12 +---- internal/macos/installer/accelerated.go | 3 +- internal/macos/installer/installer.go | 4 +- internal/macos/installer/proc_other.go | 7 --- internal/macos/installer/proc_windows.go | 17 ------- internal/macos/macosdriver/clone.go | 18 +------ internal/macos/macosdriver/prepare.go | 4 +- internal/macos/macosdriver/storage.go | 22 ++------ internal/macos/opencore/image.go | 12 +++-- internal/macos/opencore/proc_other.go | 7 --- internal/macos/opencore/proc_windows.go | 12 ----- internal/macos/reims/compat.go | 7 +-- internal/macos/reims/compat_test.go | 14 ------ internal/macos/reims/disk_import.go | 12 ++--- internal/macos/reims/helper_args.go | 39 ++------------ internal/macos/reims/proc_other.go | 7 --- internal/macos/reims/proc_windows.go | 17 ------- internal/macos/reims/reims.go | 15 +++++- internal/macos/reims/release_record.go | 31 ++++++++++++ internal/macos/reims/release_record_test.go | 25 +++++++++ internal/macos/reims/smbios_compat.go | 7 ++- internal/macos/reims/snapshot.go | 12 ++--- internal/macos/reims/suspend.go | 3 +- internal/plugin/builtin/builtin.go | 16 ++---- internal/plugin/hooks.go | 7 +++ internal/plugin/ledger.go | 41 ++------------- internal/qmp/args.go | 37 ++++++++++++++ internal/qmp/keys.go | 10 ++-- internal/qmp/watcher.go | 39 ++------------ 70 files changed, 396 insertions(+), 571 deletions(-) create mode 100644 internal/app/events.go delete mode 100644 internal/app/macos_release.go delete mode 100644 internal/app/macos_release_test.go create mode 100644 internal/archtest/events_test.go create mode 100644 internal/driver/storage_test.go create mode 100644 internal/host/console_other.go create mode 100644 internal/host/console_windows.go create mode 100644 internal/host/log_diagnose_test.go delete mode 100644 internal/macos/installer/proc_other.go delete mode 100644 internal/macos/installer/proc_windows.go delete mode 100644 internal/macos/opencore/proc_other.go delete mode 100644 internal/macos/opencore/proc_windows.go delete mode 100644 internal/macos/reims/proc_other.go delete mode 100644 internal/macos/reims/proc_windows.go create mode 100644 internal/macos/reims/release_record.go create mode 100644 internal/macos/reims/release_record_test.go create mode 100644 internal/qmp/args.go diff --git a/internal/app/affinity_flow.go b/internal/app/affinity_flow.go index eb00d5a..c934073 100644 --- a/internal/app/affinity_flow.go +++ b/internal/app/affinity_flow.go @@ -7,7 +7,6 @@ import ( "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/vmstart" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) // VMAffinityUpdate is the payload passed from the UI to save and live-apply a @@ -180,8 +179,6 @@ func (a *App) SetVMAffinityWithDriver(driverID, name string, req VMAffinityUpdat return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), applyErr } } - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), nil } diff --git a/internal/app/app.go b/internal/app/app.go index 9ba0c17..09db2c4 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -284,7 +284,7 @@ func (a *App) beforeClose(ctx context.Context) bool { if tasks.hasRunningDownload() { // Closing now would abort a download: ask first. The window's // confirmation calls QuitApp, which lets the next close through. - wailsRuntime.EventsEmit(ctx, "reims:confirm-close-downloads", true) + a.emit("reims:confirm-close-downloads", true) return true } return false @@ -390,7 +390,7 @@ func (a *App) pollVMs(ctx context.Context) { a.lastVMsAt = time.Now() a.mu.Unlock() if changed { - a.emitLifecycleStateChanged() + a.emitStateChanged() } continue } @@ -633,7 +633,7 @@ func (a *App) pollVMs(ctx context.Context) { } if sig != lastSig || guidesChanged || listRecovered { lastSig = sig - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + a.emitStateChanged() } } } @@ -797,7 +797,7 @@ func (a *App) emitLog(source, line string) { if a.ctx == nil { return } - wailsRuntime.EventsEmit(a.ctx, "reims:log", map[string]string{ + a.emit("reims:log", map[string]string{ "ts": ts, "source": source, "line": redacted, @@ -897,9 +897,7 @@ func (a *App) SetLocale(raw string) error { if mgr != nil { mgr.NotifyLocaleChanged(eff) } - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() return err } @@ -952,9 +950,7 @@ func (a *App) startTray() { }, OnNewVM: func() { a.ShowMainWindow() - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:tray-new-vm") - } + a.emit("reims:tray-new-vm") }, OnVMAction: a.trayVMAction, OnQuit: a.QuitApp, @@ -1032,9 +1028,7 @@ func (a *App) trayVMAction(driverID, name string, act tray.Action) { err, failTitle = a.ResumeVMWithDriver(driverID, name), i18n.M(loc, "tray.notify.resume_fail", vars) case tray.ActDiscardSuspend: a.ShowMainWindow() - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:tray-discard-suspend", name) - } + a.emit("reims:tray-discard-suspend", name) case tray.ActStop: err, failTitle = a.StopVMWithDriver(driverID, name, false), i18n.M(loc, "tray.notify.stop_fail", vars) case tray.ActForceStop: @@ -1055,9 +1049,7 @@ func (a *App) trayVMAction(driverID, name string, act tray.Action) { err, failTitle = a.OpenSharedFolder(name), i18n.T(loc, "tray.notify.shared_fail") case tray.ActOpenInApp: a.ShowMainWindow() - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:tray-select-vm", name) - } + a.emit("reims:tray-select-vm", name) } if err != nil { a.emitVMLog(name, failTitle+": "+err.Error()) @@ -1178,9 +1170,7 @@ func (a *App) SetDataRoot(dir string) error { if rootChanged { a.reloadPlugins() a.wakePoll() - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() } return nil } @@ -1245,7 +1235,6 @@ func (a *App) RemoveRuntime(commit string) error { a.mu.Lock() cfg := a.cfg loc := i18n.EffectiveLocale(a.cfg.Locale) - ctx := a.ctx a.mu.Unlock() inst, err := rt.Remove(cfg, commit) @@ -1262,9 +1251,7 @@ func (a *App) RemoveRuntime(commit string) error { } } a.emitLog("runtime", fmt.Sprintf("Removed runtime %s (%s)", inst.Commit, inst.Dir)) - if ctx != nil { - wailsRuntime.EventsEmit(ctx, "reims:state-changed", true) - } + a.emitStateChanged() return nil } diff --git a/internal/app/clone_flow.go b/internal/app/clone_flow.go index e7e3972..e2d2337 100644 --- a/internal/app/clone_flow.go +++ b/internal/app/clone_flow.go @@ -31,6 +31,6 @@ func (a *App) cloneVMCoWWithDriverInfo(driverID, sourceName, cloneName string) ( return driver.VMInfo{}, err } a.wakePoll() - a.emitLifecycleStateChanged() + a.emitStateChanged() return cloned, nil } diff --git a/internal/app/create_flow.go b/internal/app/create_flow.go index 8bcda84..c8b7e89 100644 --- a/internal/app/create_flow.go +++ b/internal/app/create_flow.go @@ -17,7 +17,6 @@ import ( "github.com/Nwflower/reims-go/internal/networkmsg" "github.com/Nwflower/reims-go/internal/packetbridge" rt "github.com/Nwflower/reims-go/internal/runtime" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) func (a *App) createVMFlow(opts reims.CreateOpts) (err error) { @@ -203,7 +202,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) { vmDir = filepath.Join(cfgCopy.XDGDataDir(), "reims-ctl", "vms", opts.Name) } } - if werr := writeVMMacOS(vmDir, release); werr != nil { + if werr := reims.WriteReleaseRecord(vmDir, release); werr != nil { a.emitVMLog(opts.Name, fmt.Sprintf("Warning: could not record macOS release (%s): %v", release, werr)) } if guestLang != "" { @@ -220,17 +219,13 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) { err = networkmsg.Error("create_bridge_pending", networkErr, "name", opts.Name) finishTask(err) a.emitLog(opts.Name, networkmsg.Text(a.locale(), "log.create_bridge_failed")+" "+networkmsg.Localize(networkErr, a.locale()).Error()) - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() return err } } finishTask(nil) a.emitVMLog(opts.Name, "VM "+opts.Name+" ready.") - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() if startAfterCreate && ctx.Err() == nil { return a.StartVMWithDriver(driver.BuiltinReimsMacOSDriverID, opts.Name) } diff --git a/internal/app/dataroot_flow.go b/internal/app/dataroot_flow.go index 39db36b..96be933 100644 --- a/internal/app/dataroot_flow.go +++ b/internal/app/dataroot_flow.go @@ -9,7 +9,6 @@ import ( "github.com/Nwflower/reims-go/internal/dataroot" "github.com/Nwflower/reims-go/internal/i18n" "github.com/Nwflower/reims-go/internal/version" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) // openDataRoot opens the current data folder (dataroot.Open: version check, @@ -107,9 +106,7 @@ func (a *App) ReopenDataRoot(repair bool) (dataroot.Status, error) { a.reloadPlugins() a.wakePoll() } - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() return st, nil } diff --git a/internal/app/disk_flow.go b/internal/app/disk_flow.go index cec64cd..1d139f6 100644 --- a/internal/app/disk_flow.go +++ b/internal/app/disk_flow.go @@ -34,7 +34,7 @@ func (a *App) ResizeVMDiskWithDriver(driverID, name, newSize string) (driver.Dis finishTask(nil) a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Expanded disk for %s: %.0f GB -> %.0f GB", name, float64(res.OldVirtualBytes)/float64(1<<30), float64(res.NewVirtualBytes)/float64(1<<30))) a.wakePoll() - a.emitLifecycleStateChanged() + a.emitStateChanged() return res, nil } @@ -89,6 +89,6 @@ func (a *App) runCompactVMDisk(driverID, name string, optimize bool) (driver.Dis finishTask(nil) a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Rewrote disk for %s: %.2f GB -> %.2f GB (reclaimed %.2f GB, extended L2: %t)", name, float64(res.BeforeBytes)/float64(1<<30), float64(res.AfterBytes)/float64(1<<30), float64(res.ReclaimedBytes)/float64(1<<30), res.ExtendedL2Enabled)) a.wakePoll() - a.emitLifecycleStateChanged() + a.emitStateChanged() return res, nil } diff --git a/internal/app/display_flow.go b/internal/app/display_flow.go index af49475..0aaf702 100644 --- a/internal/app/display_flow.go +++ b/internal/app/display_flow.go @@ -103,7 +103,7 @@ func (a *App) SetVMDisplayWithDriver(driverID, name, targetDisplay string) (VMDi if _, err := vmstart.SaveVMDisplay(vm.Directory, cfg); err != nil { return VMDisplayStatus{}, err } - defer a.emitLifecycleStateChanged() + defer a.emitStateChanged() if !status.Running || len(displays) == 0 { return status, nil } diff --git a/internal/app/drive_share_flow.go b/internal/app/drive_share_flow.go index 09522d0..4bcccd2 100644 --- a/internal/app/drive_share_flow.go +++ b/internal/app/drive_share_flow.go @@ -7,7 +7,6 @@ import ( "github.com/Nwflower/reims-go/internal/guesttools" "github.com/Nwflower/reims-go/internal/host" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) // DriveShareInfo describes one currently available internal fixed drive. @@ -208,8 +207,6 @@ func (a *App) SetVMDriveShareSettings(name string, enabled bool, drives []string return DriveShareSettings{}, err } a.emitVMLog(name, fmt.Sprintf("Read-only Windows drive sharing enabled=%v drives=%v", enabled, normalized)) - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() return makeDriveShareSettings(cfg, available), nil } diff --git a/internal/app/elevate_flow.go b/internal/app/elevate_flow.go index 5e0dc9f..980be9d 100644 --- a/internal/app/elevate_flow.go +++ b/internal/app/elevate_flow.go @@ -12,7 +12,6 @@ import ( "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" "github.com/Nwflower/reims-go/internal/plugin" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) // elevatePromptTimeout is how long a confirmation waits for the person. @@ -122,8 +121,8 @@ func (a *App) requestElevation(ctx context.Context, broker *plugin.Broker, reg * dismissed = true if dismiss != nil { dismiss(prompt.ID) - } else if emit == nil && winCtx != nil { - wailsRuntime.EventsEmit(winCtx, "reims:elevate-resolved", prompt.ID) + } else if emit == nil { + a.emit("reims:elevate-resolved", prompt.ID) } } defer clearPrompt() @@ -132,7 +131,7 @@ func (a *App) requestElevation(ctx context.Context, broker *plugin.Broker, reg * emit(prompt) } else { a.ShowMainWindow() - wailsRuntime.EventsEmit(winCtx, "reims:elevate-request", prompt) + a.emit("reims:elevate-request", prompt) } timer := time.NewTimer(elevatePromptTimeout) diff --git a/internal/app/events.go b/internal/app/events.go new file mode 100644 index 0000000..1045931 --- /dev/null +++ b/internal/app/events.go @@ -0,0 +1,14 @@ +package app + +import wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" + +// emit sends an event to the frontend, which subscribes in frontend/src/wails.ts. +// Without a window it does nothing. +func (a *App) emit(name string, data ...any) { + if a.ctx != nil { + wailsRuntime.EventsEmit(a.ctx, name, data...) + } +} + +// emitStateChanged asks the frontend to read the application state again. +func (a *App) emitStateChanged() { a.emit("reims:state-changed", true) } diff --git a/internal/app/extras_snapshot_test.go b/internal/app/extras_snapshot_test.go index c3ae4de..e11f4c5 100644 --- a/internal/app/extras_snapshot_test.go +++ b/internal/app/extras_snapshot_test.go @@ -25,18 +25,6 @@ func TestParseDiskSnapshotsJSON(t *testing.T) { } } -func TestValidateSnapshotName(t *testing.T) { - if got, err := reims.ValidateSnapshotName(" before-ota-26.2 "); err != nil || got != "before-ota-26.2" { - t.Fatalf("valid name failed: %q %v", got, err) - } - if _, err := reims.ValidateSnapshotName(" "); err == nil { - t.Fatal("expected error for empty snapshot name") - } - if _, err := reims.ValidateSnapshotName(`bad"quote`); err == nil { - t.Fatal("expected error for quote in snapshot name") - } -} - func TestSanitizeVMNoteAndStorageBreakdown(t *testing.T) { if got := sanitizeVMNote(" Xcode 26\nBuilder "); got != "Xcode 26 Builder" { t.Fatalf("sanitizeVMNote = %q", got) diff --git a/internal/app/folder_share_flow.go b/internal/app/folder_share_flow.go index 28f2f75..f0f8862 100644 --- a/internal/app/folder_share_flow.go +++ b/internal/app/folder_share_flow.go @@ -13,7 +13,6 @@ import ( "github.com/Nwflower/reims-go/internal/guesttools" "github.com/Nwflower/reims-go/internal/host" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) type SharedFolderInfo struct { @@ -382,8 +381,6 @@ func (a *App) changeVMSharedFolder(vmName, vmDir, folderID, action, hostPath str } srv.RegisterVM(validated) a.emitVMLog(vmName, fmt.Sprintf("Shared folder id=%s mode=%s count=%d", id, logMode, len(cfg.SharedFolders))) - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() return settings, nil } diff --git a/internal/app/fullscreen_hotkey_flow.go b/internal/app/fullscreen_hotkey_flow.go index f0413fb..32e376e 100644 --- a/internal/app/fullscreen_hotkey_flow.go +++ b/internal/app/fullscreen_hotkey_flow.go @@ -65,7 +65,7 @@ func (a *App) SetFullscreenHotkey(req FullscreenHotkeyConfig) (FullscreenHotkeyS a.mu.Unlock() a.syncFullscreenHotkeyTargets() - a.emitLifecycleStateChanged() + a.emitStateChanged() return a.GetFullscreenHotkey(), nil } diff --git a/internal/app/guesttools_flow.go b/internal/app/guesttools_flow.go index fec43b1..bbc9aaf 100644 --- a/internal/app/guesttools_flow.go +++ b/internal/app/guesttools_flow.go @@ -478,7 +478,7 @@ func (a *App) AttachGuestTools(name string) error { return err } } - if a.isVMRunning(ctx, c, name, d) { + if c.IsRunning(ctx, d) { a.mu.Lock() a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{ Field: "guest_tools", @@ -488,9 +488,7 @@ func (a *App) AttachGuestTools(name string) error { a.mu.Unlock() } a.emitVMLog(name, fmt.Sprintf("Guest Tools disk (REIMSTOOLS) attached on 127.0.0.1:%d; shared folder: %s", port, sharedDir)) - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() return nil } @@ -513,7 +511,7 @@ func (a *App) DetachGuestTools(name string) error { if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &stripped}, w, w); err != nil { return err } - if a.isVMRunning(ctx, c, name, d) { + if c.IsRunning(ctx, d) { a.mu.Lock() a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{ Field: "guest_tools", @@ -524,9 +522,7 @@ func (a *App) DetachGuestTools(name string) error { } } a.emitVMLog(name, "Guest Tools disk (REIMSTOOLS) ejected; clipboard & shared folder bridge remains active") - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() return nil } @@ -575,9 +571,7 @@ func (a *App) SetGuestPreventSleep(name string, enabled bool) error { return err } a.emitVMLog(name, fmt.Sprintf("Guest Tools prevent-sleep guard set to %v", enabled)) - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() return nil } diff --git a/internal/app/host_dns_flow.go b/internal/app/host_dns_flow.go index 7f32a95..f65084b 100644 --- a/internal/app/host_dns_flow.go +++ b/internal/app/host_dns_flow.go @@ -6,7 +6,6 @@ import ( "time" "github.com/Nwflower/reims-go/internal/guesttools" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) func (a *App) hostDNSConfigLocked() guesttools.HostDNSConfig { @@ -119,8 +118,6 @@ func (a *App) SetGuestToolsHostDNS(name string, enabled bool) error { if err := a.registerGuestToolsConfig(srv, d.Directory, cfg); err != nil { return err } - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() return nil } diff --git a/internal/app/host_drop.go b/internal/app/host_drop.go index 6d43552..eb7610b 100644 --- a/internal/app/host_drop.go +++ b/internal/app/host_drop.go @@ -14,7 +14,6 @@ import ( "time" "github.com/Nwflower/reims-go/internal/guesttools" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) const MaxHostDropFileBytes int64 = 2 << 30 @@ -184,8 +183,8 @@ func (a *App) handleHostDrop(vmKey, name string, req guesttools.HostDropRequest) result.Delivered = append(result.Delivered, delivered) } a.emitVMLog(name, fmt.Sprintf("Host drop %s: delivered %d, skipped %d", result.DropID, len(result.Delivered), len(result.Skipped))) - if a.ctx != nil && len(result.Delivered) > 0 { - wailsRuntime.EventsEmit(a.ctx, "reims:host-drop", map[string]any{ + if len(result.Delivered) > 0 { + a.emit("reims:host-drop", map[string]any{ "vm": name, "drop_id": result.DropID, "delivered": result.Delivered, "skipped": result.Skipped, "mode": result.Mode, }) } @@ -215,8 +214,8 @@ func (a *App) handleHostDropAck(vmKey, name string, ack guesttools.DropEventAck) srv.RevokeDropShare(vmKey, ack.DropID) } a.emitVMLog(name, fmt.Sprintf("Host drop %s: %s (%s)", ack.DropID, ack.Status, ack.TargetKind)) - if ack.Status != "cancelled" && a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:host-drop-ack", map[string]any{ + if ack.Status != "cancelled" { + a.emit("reims:host-drop-ack", map[string]any{ "vm": name, "drop_id": ack.DropID, "status": ack.Status, "target_kind": ack.TargetKind, "target_label": ack.TargetLabel, "placed_names": ack.PlacedNames, "error": ack.Error, }) diff --git a/internal/app/hypervisor_flow.go b/internal/app/hypervisor_flow.go index b4681df..791f2dd 100644 --- a/internal/app/hypervisor_flow.go +++ b/internal/app/hypervisor_flow.go @@ -7,7 +7,6 @@ import ( "github.com/Nwflower/reims-go/internal/dataroot" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) var ( @@ -28,10 +27,9 @@ func (a *App) SetEnableHypervisorSwitch(enabled bool) error { if err != nil { a.cfg.EnableHypervisorSwitch = prev } - ctx := a.ctx a.mu.Unlock() - if err == nil && ctx != nil { - wailsRuntime.EventsEmit(ctx, "reims:state-changed", true) + if err == nil { + a.emitStateChanged() } return err } @@ -56,7 +54,6 @@ func (a *App) setHypervisorBootInternal(enable bool) (bool, error) { dataRoot := a.cfg.DataRoot needsSetup := a.needsSetup rootStatus := a.root - ctx := a.ctx if rootStatus.ReadOnly { a.mu.Unlock() return false, dataroot.Error(loc, rootStatus) @@ -124,9 +121,7 @@ func (a *App) setHypervisorBootInternal(enable bool) (bool, error) { } else { a.emitLog("host", "Updated Windows hypervisor boot configuration (next boot: "+pending+"); restart Windows manually to apply") } - if ctx != nil { - wailsRuntime.EventsEmit(ctx, "reims:state-changed", true) - } + a.emitStateChanged() return true, nil } diff --git a/internal/app/install_flow.go b/internal/app/install_flow.go index 4b5fe6c..1eaafda 100644 --- a/internal/app/install_flow.go +++ b/internal/app/install_flow.go @@ -14,7 +14,6 @@ import ( "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/macos/startprep" "github.com/Nwflower/reims-go/internal/vmstart" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) // isRecoveryModeActive reports whether d has an installer attached or an @@ -58,20 +57,6 @@ func (a *App) pickCachedRecoveryInstaller() (string, error) { return "", nil } -func (a *App) isVMRunning(ctx context.Context, c *reims.Client, name string, d reims.VMDetail) bool { - if d.State == "running" { - return true - } - if list, err := c.List(ctx); err == nil { - for _, vm := range list { - if vm.Name == name && vm.State == "running" { - return true - } - } - } - return false -} - // EnterRecovery routes the macOS recovery action through the lifecycle service. // The legacy path remains available for minimal embedding without a plugin manager. func (a *App) EnterRecovery(name string) error { @@ -99,7 +84,7 @@ func (a *App) EnterRecovery(name string) error { a.emitVMLog(name, "Recovery mode enabled for "+name+" (pick Recovery in OpenCore boot menu)") } a.wakePoll() - a.emitLifecycleStateChanged() + a.emitStateChanged() return nil } @@ -119,7 +104,7 @@ func (a *App) enterMacOSRecovery(name string) error { w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) }) ctx := context.Background() - if a.isVMRunning(ctx, c, name, d) { + if c.IsRunning(ctx, d) { marker := startprep.ReadRecoveryMarker(d.Directory) if marker != "on" { startprep.WriteRecoveryMarker(d.Directory, "want") @@ -143,9 +128,7 @@ func (a *App) enterMacOSRecovery(name string) error { } a.emitVMLog(name, "Recovery mode enabled for "+name+" (pick Recovery in OpenCore boot menu)") } - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() return nil } @@ -203,7 +186,7 @@ func (a *App) AttachInstaller(name, installerPath string) (string, error) { if err != nil { return "", err } - if a.isVMRunning(ctx, c, name, d) { + if c.IsRunning(ctx, d) { a.mu.Lock() a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{ Field: "installer", @@ -212,9 +195,7 @@ func (a *App) AttachInstaller(name, installerPath string) (string, error) { }) a.mu.Unlock() } - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() return base, nil } @@ -329,7 +310,7 @@ func (a *App) FinishInstall(name string) error { } a.emitVMLog(name, "Exited recovery mode") a.wakePoll() - a.emitLifecycleStateChanged() + a.emitStateChanged() return nil } @@ -383,7 +364,7 @@ func (a *App) finishMacOSInstall(name string) error { } } - running := a.isVMRunning(ctx, c, name, d) + running := c.IsRunning(ctx, d) marker := startprep.ReadRecoveryMarker(d.Directory) if running { var diffs []PendingChange @@ -424,9 +405,7 @@ func (a *App) finishMacOSInstall(name string) error { } } a.emitVMLog(name, "Exited recovery mode") - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() return nil } @@ -471,7 +450,7 @@ func (a *App) UpgradeDiskToNVMe(name string) error { if err != nil { return err } - if a.isVMRunning(ctx, c, name, d) { + if c.IsRunning(ctx, d) { a.mu.Lock() a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{ Field: "disk_controller", @@ -480,8 +459,6 @@ func (a *App) UpgradeDiskToNVMe(name string) error { }) a.mu.Unlock() } - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() return nil } diff --git a/internal/app/legacy_ledger_test.go b/internal/app/legacy_ledger_test.go index 32fa83f..ec81419 100644 --- a/internal/app/legacy_ledger_test.go +++ b/internal/app/legacy_ledger_test.go @@ -29,17 +29,17 @@ func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) { PluginID: builtin.IDGuestTools, Args: []plugin.ArgFragment{{ PluginID: builtin.IDGuestTools, Key: "reimstools", Builtin: true, Priority: 80, - Tokens: plugin.SplitShellTokens(reims.MergeGuestToolsArgs("", `D:\Data\cache\tools.img`)), + Tokens: qmp.SplitArgs(reims.MergeGuestToolsArgs("", `D:\Data\cache\tools.img`)), }}, }, { PluginID: guest.ID, Args: []plugin.ArgFragment{{ PluginID: guest.ID, Key: "reimshelp", Builtin: true, Priority: 85, - Tokens: plugin.SplitShellTokens(reims.MergeOfflineHelperArgs("", `D:\Data\cache\reimshelp.img`)), + Tokens: qmp.SplitArgs(reims.MergeOfflineHelperArgs("", `D:\Data\cache\reimshelp.img`)), }, { PluginID: guest.ID, Key: "win10-cold-reboot", Builtin: true, Priority: 95, - Tokens: plugin.SplitShellTokens(qmp.MergeWin10RebootUnixArgs("", `D:\Data\vms\mac\reims-go-reboot.sock`)), + Tokens: qmp.SplitArgs(qmp.MergeWin10RebootUnixArgs("", `D:\Data\vms\mac\reims-go-reboot.sock`)), }}, }, } diff --git a/internal/app/lifecycle_flow.go b/internal/app/lifecycle_flow.go index 5a343c2..fb38694 100644 --- a/internal/app/lifecycle_flow.go +++ b/internal/app/lifecycle_flow.go @@ -12,15 +12,8 @@ import ( "github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/internal/plugin/builtin" "github.com/Nwflower/reims-go/internal/vmstart" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) -func (a *App) emitLifecycleStateChanged() { - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } -} - func (a *App) emitVMLogForDriver(driverID, name, line string) { a.emitLog(vmKeyForDriver(driverID, name), line) } @@ -146,7 +139,7 @@ func (a *App) startResolvedVMLocked(ctx context.Context, svc interface { a.transitions[key] = "starting" delete(a.pendingChanges, key) a.mu.Unlock() - a.emitLifecycleStateChanged() + a.emitStateChanged() startAt := time.Now() if ref.DriverID == driver.BuiltinReimsMacOSDriverID { rep := host.Inspect(a.currentDataRoot()) @@ -160,7 +153,7 @@ func (a *App) startResolvedVMLocked(ctx context.Context, svc interface { delete(a.transitions, key) a.mu.Unlock() a.emitVMLogForDriver(ref.DriverID, ref.Name, "Start error: "+err.Error()) - a.emitLifecycleStateChanged() + a.emitStateChanged() return err } if ref.DriverID == driver.BuiltinReimsMacOSDriverID { @@ -175,7 +168,7 @@ func (a *App) startResolvedVMLocked(ctx context.Context, svc interface { a.startVMMonitor(ref.Name, detail, startAt) } a.wakePoll() - a.emitLifecycleStateChanged() + a.emitStateChanged() return nil } @@ -209,7 +202,7 @@ func (a *App) stopVMWithDriverCtx(ctx context.Context, driverID, name string, fo a.mu.Lock() a.transitions[key] = "stopping" a.mu.Unlock() - a.emitLifecycleStateChanged() + a.emitStateChanged() w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) }) if err := svc.Stop(operationCtx, ref, force, w, w); err != nil { a.mu.Lock() @@ -224,7 +217,7 @@ func (a *App) stopVMWithDriverCtx(ctx context.Context, driverID, name string, fo delete(a.pendingChanges, key) a.mu.Unlock() a.wakePoll() - a.emitLifecycleStateChanged() + a.emitStateChanged() return nil }) } @@ -250,7 +243,7 @@ func (a *App) EjectInstallerWithDriver(driverID, name string) error { }) if err == nil { a.wakePoll() - a.emitLifecycleStateChanged() + a.emitStateChanged() } return err } @@ -378,7 +371,7 @@ func (a *App) DeleteVMWithDriver(driverID, name string, keepFiles bool) error { gt.UnregisterVM(key) } a.wakePoll() - a.emitLifecycleStateChanged() + a.emitStateChanged() return deleteErr }) } diff --git a/internal/app/macos_detail.go b/internal/app/macos_detail.go index 6d4e713..8a6a639 100644 --- a/internal/app/macos_detail.go +++ b/internal/app/macos_detail.go @@ -97,3 +97,14 @@ func populateSuspendDetail(d *reims.VMDetail) { } } } + +// GetVMMacOS returns the macOS release recorded when the VM was created. It is +// "" for VMs made from an existing disk or before this was recorded; the UI +// then guesses from the VM's name. +func (a *App) GetVMMacOS(name string) string { + dir := a.vmDirectory(name) + if dir == "" { + return "" + } + return reims.ReadReleaseRecord(dir) +} diff --git a/internal/app/macos_lifecycle_native.go b/internal/app/macos_lifecycle_native.go index bf02ef3..29902e6 100644 --- a/internal/app/macos_lifecycle_native.go +++ b/internal/app/macos_lifecycle_native.go @@ -19,7 +19,6 @@ import ( "github.com/Nwflower/reims-go/internal/plugin/builtin" "github.com/Nwflower/reims-go/internal/qmp" "github.com/Nwflower/reims-go/internal/vmstart" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) const ( @@ -350,7 +349,7 @@ func (a *App) startMacOSVM(name string) error { a.transitions[vmKey(name)] = "starting" delete(a.pendingChanges, vmKey(name)) a.mu.Unlock() - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + a.emitStateChanged() startAt := time.Now() a.emitStartSummary(name, vmInfoFromMacOSDetail(curDetail), rep, qmpAddr) @@ -363,7 +362,7 @@ func (a *App) startMacOSVM(name string) error { delete(a.transitions, vmKey(name)) a.mu.Unlock() a.emitVMLog(name, "Start error: "+err.Error()) - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + a.emitStateChanged() return err } if qmpAddr != "" && mgr == nil { @@ -379,7 +378,7 @@ func (a *App) startMacOSVM(name string) error { } a.startVMMonitor(name, vmInfoFromMacOSDetail(curDetail), startAt) a.wakePoll() - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + a.emitStateChanged() return nil } @@ -460,7 +459,7 @@ func (a *App) stopMacOSVMLocked(ctx context.Context, name string, force bool, c DriverID: builtin.IDDriverReimsMacOS, }) } - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + a.emitStateChanged() w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) }) a.emitVMLog(name, fmt.Sprintf("Stopping %s (force=%v)...", name, force)) @@ -488,7 +487,7 @@ func (a *App) stopMacOSVMLocked(ctx context.Context, name string, force bool, c }) } a.wakePoll() - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + a.emitStateChanged() return nil } @@ -555,7 +554,7 @@ func (a *App) ejectMacOSInstaller(name string) error { return err } a.emitVMLog(name, "Installer ejected.") - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + a.emitStateChanged() return nil } @@ -604,7 +603,7 @@ func (a *App) deleteMacOSVMLocked(ctx context.Context, name string, keepFiles bo }) } a.wakePoll() - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + a.emitStateChanged() return nil } diff --git a/internal/app/macos_release.go b/internal/app/macos_release.go deleted file mode 100644 index 394f39d..0000000 --- a/internal/app/macos_release.go +++ /dev/null @@ -1,40 +0,0 @@ -package app - -import ( - "os" - "path/filepath" - "strings" -) - -// vmMacOSFileName records which macOS release a VM was created with, for its -// icon. reims-ctl keeps no such field in vm.toml. -const vmMacOSFileName = ".reims-go-macos" - -// GetVMMacOS returns the macOS release recorded when the VM was created: an -// installer version such as "26.7.3", or a codename such as "tahoe" for an -// online-recovery install. It is "" for VMs made from an existing disk or -// before this was recorded; the UI then guesses from the VM's name. -func (a *App) GetVMMacOS(name string) string { - dir := a.vmDirectory(name) - if dir == "" { - return "" - } - return readVMMacOS(dir) -} - -func readVMMacOS(dir string) string { - b, err := os.ReadFile(filepath.Join(dir, vmMacOSFileName)) - if err != nil { - return "" - } - return strings.TrimSpace(string(b)) -} - -// writeVMMacOS stores release next to vm.toml; an empty release writes nothing. -func writeVMMacOS(dir, release string) error { - release = strings.TrimSpace(strings.ReplaceAll(strings.ReplaceAll(release, "\r", ""), "\n", "")) - if dir == "" || release == "" { - return nil - } - return os.WriteFile(filepath.Join(dir, vmMacOSFileName), []byte(release+"\n"), 0o644) -} diff --git a/internal/app/macos_release_test.go b/internal/app/macos_release_test.go deleted file mode 100644 index 17f83aa..0000000 --- a/internal/app/macos_release_test.go +++ /dev/null @@ -1,25 +0,0 @@ -package app - -import "testing" - -func TestVMMacOSRoundTrip(t *testing.T) { - dir := t.TempDir() - if got := readVMMacOS(dir); got != "" { - t.Fatalf("empty dir: got %q", got) - } - if err := writeVMMacOS(dir, ""); err != nil { - t.Fatal(err) - } - if got := readVMMacOS(dir); got != "" { - t.Fatalf("empty release wrote %q", got) - } - if err := writeVMMacOS(dir, " 26.7.3\r\n"); err != nil { - t.Fatal(err) - } - if got := readVMMacOS(dir); got != "26.7.3" { - t.Fatalf("got %q, want 26.7.3", got) - } - if err := writeVMMacOS("", "tahoe"); err != nil { - t.Fatalf("no dir should be a no-op, got %v", err) - } -} diff --git a/internal/app/macos_settings.go b/internal/app/macos_settings.go index db906d7..4ae82c0 100644 --- a/internal/app/macos_settings.go +++ b/internal/app/macos_settings.go @@ -22,7 +22,6 @@ import ( "github.com/Nwflower/reims-go/internal/qmp" rt "github.com/Nwflower/reims-go/internal/runtime" "github.com/Nwflower/reims-go/internal/vmstart" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) // ToggleBorderless switches borderless fullscreen startup through the native macOS settings flow. @@ -206,7 +205,7 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) { } } a.emitVMLog(opts.Name, "Updated VM settings for "+opts.Name) - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + a.emitStateChanged() return nil } @@ -480,9 +479,7 @@ func (a *App) applyVMNetwork(parent context.Context, name, mode, uplink string) } else if err := a.applyPacketNetwork(ctx, c, d, mode, selected, record); err != nil { return VMNetworkSettings{}, err } - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() settings, err := a.GetVMNetworkSettings(name) if err != nil { a.emitLog(name, networkmsg.Text(a.locale(), "log.refresh_failed")) diff --git a/internal/app/opencore_flow.go b/internal/app/opencore_flow.go index 14891c7..18ed855 100644 --- a/internal/app/opencore_flow.go +++ b/internal/app/opencore_flow.go @@ -7,7 +7,6 @@ import ( "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/macos/startprep" rt "github.com/Nwflower/reims-go/internal/runtime" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) // populateGuestLangDetail fills VMDetail.GuestLang from the VM's persisted @@ -102,7 +101,7 @@ func (a *App) ApplyVMSMBIOS(name string, id opencore.SMBIOSIdentity) (opencore.S return opencore.SMBIOSIdentity{}, err } defer release() - if a.isVMRunning(ctx, c, name, d) { + if c.IsRunning(ctx, d) { return opencore.SMBIOSIdentity{}, fmt.Errorf("stop %s before updating its SMBIOS identity", name) } if d.State == "suspended" { @@ -132,9 +131,7 @@ func (a *App) ApplyVMSMBIOS(name string, id opencore.SMBIOSIdentity) (opencore.S } // Never log Serial, MLB, UUID, or ROM into VM/app logs. a.emitVMLog(name, fmt.Sprintf("Updated OpenCore SMBIOS identity (%s)", modelLabel)) - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() } return updated, nil } diff --git a/internal/app/plugins_flow.go b/internal/app/plugins_flow.go index c622ea8..babf561 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -30,7 +30,6 @@ import ( rt "github.com/Nwflower/reims-go/internal/runtime" "github.com/Nwflower/reims-go/internal/version" "github.com/Nwflower/reims-go/internal/vmstart" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) // PluginUIContributions aggregates all active declarative plugin UI contributions @@ -121,7 +120,7 @@ func (a *App) initPlugins() { return err } a.wakePoll() - a.emitLifecycleStateChanged() + a.emitStateChanged() return nil }) mgr.Broker().SetVMExitHandler(func(string, string) { a.wakePoll() }) @@ -200,9 +199,7 @@ func (a *App) initPlugins() { }, StopPacketBridges: a.closePacketBridges, OnInstallGuidesChanged: func() { - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() }, SyncInstallGuides: func() { a.wakePoll() @@ -236,9 +233,7 @@ func (a *App) initPlugins() { a.syncClipboardPolicies() a.syncLocales() a.wakePoll() - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() }) a.keymapMu.Lock() @@ -537,9 +532,7 @@ func (a *App) onPluginSettingsChanged(pluginID, vmName string) { } } } - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() } func clipboardPolicyFromMap(vals map[string]any) guesttools.ClipboardPolicy { @@ -671,8 +664,8 @@ func (a *App) InstallPluginArchive(archivePath string) (*plugin.PluginInfo, erro return nil, errors.New("plugin manager not initialized") } info, err := mgr.InstallLocalArchive(context.Background(), archivePath, plugin.PackageInstallOptions{}) - if err == nil && a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + if err == nil { + a.emitStateChanged() } return info, err } @@ -685,8 +678,8 @@ func (a *App) LinkPluginDev(dir string) (*plugin.PluginInfo, error) { return nil, errors.New("plugin manager not initialized") } info, err := mgr.LinkDev(context.Background(), dir) - if err == nil && a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + if err == nil { + a.emitStateChanged() } return info, err } @@ -825,8 +818,8 @@ func (a *App) SetActiveTheme(themeID, schemeID string) error { return errors.New("plugin manager not initialized") } err := mgr.SetActiveTheme(themeID, schemeID) - if err == nil && a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + if err == nil { + a.emitStateChanged() } return err } @@ -921,9 +914,7 @@ func (a *App) CreateVMWithDriver(req driver.CreateRequest) error { }) } a.wakePoll() - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() return nil } @@ -1139,9 +1130,7 @@ func (a *App) InstallMarketPlugin(pluginID string, includeAlpha bool) (*plugin.P lastEmit time.Time ) emit := func(p MarketInstallProgress) { - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:plugin-install", p) - } + a.emit("reims:plugin-install", p) } info, err := a.getPluginMarket().InstallFromMarket(context.Background(), mgr, pluginID, plugin.MarketInstallOptions{ IncludeAlpha: includeAlpha, @@ -1165,8 +1154,8 @@ func (a *App) InstallMarketPlugin(pluginID string, includeAlpha bool) (*plugin.P emit(MarketInstallProgress{ID: pluginID, Phase: ph, Done: done, Total: total}) }, }) - if err == nil && a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + if err == nil { + a.emitStateChanged() } return info, err } diff --git a/internal/app/runtime_bindings.go b/internal/app/runtime_bindings.go index 8380f6d..86ca124 100644 --- a/internal/app/runtime_bindings.go +++ b/internal/app/runtime_bindings.go @@ -122,9 +122,7 @@ func (a *App) InstallRuntimeOnline(commit string) (string, error) { a.emitLog("runtime", "Runtime install error: "+err.Error()) tasks.finish(id, "", err) } - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() }() return id, nil } diff --git a/internal/app/setup.go b/internal/app/setup.go index 720d995..8aa4e3e 100644 --- a/internal/app/setup.go +++ b/internal/app/setup.go @@ -16,7 +16,6 @@ import ( "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" "github.com/Nwflower/reims-go/internal/version" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) // DataRootChoice is a suggested data folder on one drive. @@ -150,9 +149,7 @@ func (a *App) CompleteSetup(dir string) error { a.resetDataRootCaches() a.reloadPlugins() a.wakePoll() - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitStateChanged() return nil } diff --git a/internal/app/snapshot_flow.go b/internal/app/snapshot_flow.go index b1df7ed..a1b85b8 100644 --- a/internal/app/snapshot_flow.go +++ b/internal/app/snapshot_flow.go @@ -68,6 +68,6 @@ func (a *App) runSnapshotOpWithDriver(driverID, name, operation, snapName, verb } a.emitVMLogForDriver(driverID, name, fmt.Sprintf("%s %q", verb, cleanSnap)) a.wakePoll() - a.emitLifecycleStateChanged() + a.emitStateChanged() return nil } diff --git a/internal/app/suspend_flow.go b/internal/app/suspend_flow.go index c2a3f24..157b874 100644 --- a/internal/app/suspend_flow.go +++ b/internal/app/suspend_flow.go @@ -11,7 +11,6 @@ import ( "github.com/Nwflower/reims-go/internal/i18n" rt "github.com/Nwflower/reims-go/internal/runtime" "github.com/Nwflower/reims-go/internal/vmstart" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) // SuspendVM saves a VM's running state and closes its QEMU process. @@ -297,11 +296,5 @@ func suspendProgressPercent(p driver.SuspendProgress) (int, bool) { return pct, true } -func (a *App) emitStateChanged() { - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } -} - // Keep context import used cleanly for future cancellation hooks. var _ context.Context diff --git a/internal/app/tasks.go b/internal/app/tasks.go index 7acb892..da604a8 100644 --- a/internal/app/tasks.go +++ b/internal/app/tasks.go @@ -16,7 +16,6 @@ import ( "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/vmstart" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) const ( @@ -367,9 +366,7 @@ func (r *rateMeter) add(done int64) float64 { func (a *App) taskEmitter() func(Task) { return func(t Task) { - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:task", t) - } + a.emit("reims:task", t) } } diff --git a/internal/app/thumbnail_flow.go b/internal/app/thumbnail_flow.go index 6ee9665..1919c77 100644 --- a/internal/app/thumbnail_flow.go +++ b/internal/app/thumbnail_flow.go @@ -184,7 +184,7 @@ func (a *App) ToggleVMFullscreenWithDriver(driverID, name string) (bool, error) return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err) } a.emitVMLogForDriver(vm.DriverID, name, fmt.Sprintf("VM window full screen: %t", fullscreen)) - a.emitLifecycleStateChanged() + a.emitStateChanged() return fullscreen, nil } diff --git a/internal/app/ui_health.go b/internal/app/ui_health.go index d589f19..5b3264b 100644 --- a/internal/app/ui_health.go +++ b/internal/app/ui_health.go @@ -147,7 +147,7 @@ func (a *App) probeUIHealth(ctx context.Context, reason string) { if wailsRuntime.WindowIsMinimised(a.ctx) { return } - wailsRuntime.EventsEmit(a.ctx, "reims:ui-ping", pingSentAt.UnixMilli()) + a.emit("reims:ui-ping", pingSentAt.UnixMilli()) timer := time.NewTimer(uiHealthPingTimeout) defer timer.Stop() diff --git a/internal/archtest/events_test.go b/internal/archtest/events_test.go new file mode 100644 index 0000000..023a939 --- /dev/null +++ b/internal/archtest/events_test.go @@ -0,0 +1,56 @@ +package archtest + +import ( + "go/ast" + "os" + "regexp" + "strings" + "testing" +) + +// TestFrontendEventsMatch keeps both ends of the window event contract in step: +// Go emits only through App.emit, and every event name used in Go is also used +// in the frontend's wails.ts, and the other way round. +func TestFrontendEventsMatch(t *testing.T) { + raw, err := os.ReadFile("../../frontend/src/wails.ts") + if err != nil { + t.Fatal(err) + } + frontend := map[string]bool{} + for _, m := range regexp.MustCompile(`'(reims:[a-z-]+)'`).FindAllStringSubmatch(string(raw), -1) { + frontend[m[1]] = true + } + if len(frontend) < 10 { + t.Fatalf("found only %d event names in wails.ts", len(frontend)) + } + + backend := map[string]bool{} + for _, s := range sources(t) { + if s.isTest() || !strings.HasPrefix(s.rel, "internal/") { + continue + } + ast.Inspect(s.file, func(n ast.Node) bool { + switch n := n.(type) { + case *ast.SelectorExpr: + if n.Sel.Name == "EventsEmit" && s.rel != "internal/app/events.go" { + t.Errorf("%s calls EventsEmit: use App.emit", s.rel) + } + case *ast.BasicLit: + if name := strings.Trim(n.Value, `"`); strings.HasPrefix(name, "reims:") { + backend[name] = true + } + } + return true + }) + } + for name := range backend { + if !frontend[name] { + t.Errorf("event %q exists in Go but not in frontend/src/wails.ts", name) + } + } + for name := range frontend { + if !backend[name] { + t.Errorf("event %q exists in frontend/src/wails.ts but not in Go", name) + } + } +} diff --git a/internal/datamigrate/datamigrate.go b/internal/datamigrate/datamigrate.go index 956633e..828d97a 100644 --- a/internal/datamigrate/datamigrate.go +++ b/internal/datamigrate/datamigrate.go @@ -108,7 +108,7 @@ func run(dataRoot, appVersion string, steps []Step, current int, now func() time // A folder already stamped at this layout is left untouched; anything // else (steps ran, no stamp yet, damaged stamp) gets a fresh stamp. - if stamp.DataVersion == current && readErr == nil && stampExists(dataRoot) { + if stamp.DataVersion == current && readErr == nil && HasStamp(dataRoot) { return res, nil } res.To = current @@ -137,7 +137,8 @@ func ReadStamp(dataRoot string) (Stamp, error) { return s, nil } -func stampExists(dataRoot string) bool { +// HasStamp reports whether dataRoot records its data version. +func HasStamp(dataRoot string) bool { _, err := os.Stat(filepath.Join(dataRoot, StampFile)) return err == nil } diff --git a/internal/dataroot/dataroot.go b/internal/dataroot/dataroot.go index 4fb2d31..28f44a8 100644 --- a/internal/dataroot/dataroot.go +++ b/internal/dataroot/dataroot.go @@ -87,7 +87,7 @@ func open(dir, appVersion string, repair bool) Status { case err == nil && stamp.DataVersion > datamigrate.CurrentVersion: st.Version = stamp.DataVersion return readOnly(st, ReasonNewer, "") - case err == nil && stamp.DataVersion == datamigrate.CurrentVersion && stampExists(dir): + case err == nil && stamp.DataVersion == datamigrate.CurrentVersion && datamigrate.HasStamp(dir): st.Version = stamp.DataVersion return st } @@ -128,11 +128,6 @@ func readOnly(st Status, reason Reason, detail string) Status { return st } -func stampExists(dir string) bool { - _, err := os.Stat(filepath.Join(dir, datamigrate.StampFile)) - return err == nil -} - // Error explains why st cannot be written, for the GUI and the CLI alike. It // is nil for a writable folder. func Error(loc i18n.Locale, st Status) error { diff --git a/internal/driver/storage_test.go b/internal/driver/storage_test.go new file mode 100644 index 0000000..cbeddb7 --- /dev/null +++ b/internal/driver/storage_test.go @@ -0,0 +1,15 @@ +package driver + +import "testing" + +func TestValidateSnapshotName(t *testing.T) { + if got, err := ValidateSnapshotName(" before-ota-26.2 "); err != nil || got != "before-ota-26.2" { + t.Fatalf("valid name failed: %q %v", got, err) + } + if _, err := ValidateSnapshotName(" "); err == nil { + t.Fatal("expected error for empty snapshot name") + } + if _, err := ValidateSnapshotName(`bad"quote`); err == nil { + t.Fatal("expected error for quote in snapshot name") + } +} diff --git a/internal/host/console_other.go b/internal/host/console_other.go new file mode 100644 index 0000000..4d8d337 --- /dev/null +++ b/internal/host/console_other.go @@ -0,0 +1,8 @@ +//go:build !windows + +package host + +import "os/exec" + +// HideConsole does nothing: only Windows opens console windows. +func HideConsole(*exec.Cmd) {} diff --git a/internal/host/console_windows.go b/internal/host/console_windows.go new file mode 100644 index 0000000..5187479 --- /dev/null +++ b/internal/host/console_windows.go @@ -0,0 +1,13 @@ +package host + +import ( + "os/exec" + "syscall" + + "golang.org/x/sys/windows" +) + +// HideConsole keeps a console program started by the GUI from opening a window. +func HideConsole(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NO_WINDOW} +} diff --git a/internal/host/log_diagnose_test.go b/internal/host/log_diagnose_test.go new file mode 100644 index 0000000..d301e7b --- /dev/null +++ b/internal/host/log_diagnose_test.go @@ -0,0 +1,17 @@ +package host + +import "testing" + +func TestDiagnoseGPULog(t *testing.T) { + lost := "reims-vgpu: the rt platform's device on AMD Radeon (TM) Graphics (1002:15e7) was lost at vkQueueSubmit2 (ERROR_DEVICE_LOST)" + if code, detail := DiagnoseGPULog(lost); code != "gpu_device_lost" || detail == "" { + t.Fatalf("DiagnoseGPULog(lost) = (%q, %q), want gpu_device_lost", code, detail) + } + floor := "reims-vgpu: no physical device meets the floor (VK_ERROR_INCOMPATIBLE_DRIVER)" + if code, detail := DiagnoseGPULog(floor); code != "gpu_vulkan_floor" || detail == "" { + t.Fatalf("DiagnoseGPULog(floor) = (%q, %q), want gpu_vulkan_floor", code, detail) + } + if code, _ := DiagnoseGPULog("normal boot log line"); code != "" { + t.Fatalf("expected empty code for normal log, got %q", code) + } +} diff --git a/internal/macos/guest/guest.go b/internal/macos/guest/guest.go index 5d3f497..a67d3f7 100644 --- a/internal/macos/guest/guest.go +++ b/internal/macos/guest/guest.go @@ -2,7 +2,6 @@ package guest import ( "context" - "strings" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/i18n" @@ -140,7 +139,7 @@ func Definition(ver string, cb builtin.HostCallbacks, desired bool) plugin.Plugi return nil, nil } caps, _ := p.HostFacts["runtime.capabilities"].([]string) - if whpxFallbackNeeded(p.HostFacts) && !hasCap(caps, "nested-virt-nonfatal") { + if whpxFallbackNeeded(p.HostFacts) && !plugin.HasCap(caps, "nested-virt-nonfatal") { return plugin.PreflightResult{ Advices: []string{i18n.T(guestLocale(cb), "core.preflight.whpx_irqchip_advice")}, }, nil @@ -182,12 +181,3 @@ func whpxFallbackNeeded(facts map[string]any) bool { nestedOK, _ := facts["host.whpx_nested_virt"].(bool) return !needsCold && irqAvail && !nestedOK } - -func hasCap(caps []string, want string) bool { - for _, c := range caps { - if strings.EqualFold(c, want) { - return true - } - } - return false -} diff --git a/internal/macos/installer/accelerated.go b/internal/macos/installer/accelerated.go index a40dc9b..e372e9f 100644 --- a/internal/macos/installer/accelerated.go +++ b/internal/macos/installer/accelerated.go @@ -15,6 +15,7 @@ import ( "strings" "github.com/Nwflower/reims-go/internal/downloader" + "github.com/Nwflower/reims-go/internal/host" ) func resolveOfflineRelease(releases []Release, version string) (Release, bool) { @@ -77,7 +78,7 @@ func (c *Client) prepareOfflinePartWithUtil(ctx context.Context, version, partPa defer cancel() cmd := exec.CommandContext(prepCtx, c.Util, "--json", "offline-installer", version, "-o", c.InstallersDir) - configureCmd(cmd) + host.HideConsole(cmd) cmd.Env = c.Env cmd.Stdin = nil var stderr bytes.Buffer diff --git a/internal/macos/installer/installer.go b/internal/macos/installer/installer.go index d0ebbfc..2375e55 100644 --- a/internal/macos/installer/installer.go +++ b/internal/macos/installer/installer.go @@ -118,7 +118,7 @@ func (c *Client) run(ctx context.Context, onUpdate func(Update), args ...string) onUpdate = func(Update) {} } cmd := exec.CommandContext(ctx, c.Util, append([]string{"--json"}, args...)...) - configureCmd(cmd) + host.HideConsole(cmd) cmd.Env = c.Env cmd.Stdin = nil var stderr bytes.Buffer @@ -428,7 +428,7 @@ func (c *Client) DeleteCached(ctx context.Context, name string, stdout io.Writer return fmt.Errorf("not a download name: %q", name) } cmd := exec.CommandContext(ctx, c.Ctl, "downloads", "delete", name, "--yes") - configureCmd(cmd) + host.HideConsole(cmd) cmd.Env = c.Env var out, errBuf bytes.Buffer cmd.Stdout = &out diff --git a/internal/macos/installer/proc_other.go b/internal/macos/installer/proc_other.go deleted file mode 100644 index 3aa7f86..0000000 --- a/internal/macos/installer/proc_other.go +++ /dev/null @@ -1,7 +0,0 @@ -//go:build !windows - -package installer - -import "os/exec" - -func configureCmd(*exec.Cmd) {} diff --git a/internal/macos/installer/proc_windows.go b/internal/macos/installer/proc_windows.go deleted file mode 100644 index 2f26bd0..0000000 --- a/internal/macos/installer/proc_windows.go +++ /dev/null @@ -1,17 +0,0 @@ -//go:build windows - -package installer - -import ( - "os/exec" - "syscall" -) - -const createNoWindow = 0x08000000 - -func configureCmd(cmd *exec.Cmd) { - cmd.SysProcAttr = &syscall.SysProcAttr{ - HideWindow: true, - CreationFlags: createNoWindow, - } -} diff --git a/internal/macos/macosdriver/clone.go b/internal/macos/macosdriver/clone.go index 90c289b..dd594a6 100644 --- a/internal/macos/macosdriver/clone.go +++ b/internal/macos/macosdriver/clone.go @@ -22,22 +22,6 @@ import ( var _ driver.CloneDriver = (*ReimsMacOSDriver)(nil) var _ driver.CloneResultDriver = (*ReimsMacOSDriver)(nil) -func readVMMacOS(dir string) string { - raw, err := os.ReadFile(filepath.Join(dir, ".reims-go-macos")) - if err != nil { - return "" - } - return strings.TrimSpace(string(raw)) -} - -func writeVMMacOS(dir, release string) error { - release = strings.TrimSpace(strings.NewReplacer("\r", "", "\n", "").Replace(release)) - if dir == "" || release == "" { - return nil - } - return os.WriteFile(filepath.Join(dir, ".reims-go-macos"), []byte(release+"\n"), 0o644) -} - func (d *ReimsMacOSDriver) CloneCoWWithInfo(ctx context.Context, sourceName, cloneName string, stdout, stderr io.Writer) (driver.VMInfo, error) { cloneName = strings.TrimSpace(cloneName) if err := d.CloneCoW(ctx, sourceName, cloneName, stdout, stderr); err != nil { @@ -155,7 +139,7 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s _, _ = fmt.Fprintf(stdout, "Warning: could not apply clone language (%s): %v\n", src.GuestLang, prepErr) } } - if err := writeVMMacOS(cloned.Directory, readVMMacOS(src.Directory)); err != nil { + if err := reims.WriteReleaseRecord(cloned.Directory, reims.ReadReleaseRecord(src.Directory)); err != nil { _, _ = fmt.Fprintf(stdout, "Warning: could not copy macOS release: %v\n", err) } if vmstart.HasSavedVMAffinity(src.Directory) { diff --git a/internal/macos/macosdriver/prepare.go b/internal/macos/macosdriver/prepare.go index 4b0085b..7320b86 100644 --- a/internal/macos/macosdriver/prepare.go +++ b/internal/macos/macosdriver/prepare.go @@ -174,7 +174,7 @@ func (d *ReimsMacOSDriver) prepareOfflineHelper(cfg config.Config, cur reims.VMD return fmt.Errorf("prepare offline install helper disk: %w", err) } in.Args = append(in.Args, plugin.ArgFragment{PluginID: d.opts.OwnerID, Key: keyOfflineHelper, - Tokens: plugin.SplitShellTokens(reims.MergeOfflineHelperArgs("", helperPath)), Builtin: true, Priority: 85}) + Tokens: qmp.SplitArgs(reims.MergeOfflineHelperArgs("", helperPath)), Builtin: true, Priority: 85}) return nil } @@ -242,7 +242,7 @@ func (d *ReimsMacOSDriver) prepareColdReboot(cfg config.Config, name, vmDir stri return fmt.Errorf("replace cold-reboot socket: %w", err) } in.Args = append(in.Args, plugin.ArgFragment{PluginID: d.opts.OwnerID, Key: keyWin10ColdReboot, - Tokens: plugin.SplitShellTokens(qmp.MergeWin10RebootUnixArgs("", sockPath)), Builtin: true, Priority: 95}) + Tokens: qmp.SplitArgs(qmp.MergeWin10RebootUnixArgs("", sockPath)), Builtin: true, Priority: 95}) in.PostStart = append(in.PostStart, plugin.PostStartAction{PluginID: d.opts.OwnerID, Kind: "qmp.watch_cold_reboot", Params: map[string]any{"qmp_addr": "unix:" + sockPath}}) return nil diff --git a/internal/macos/macosdriver/storage.go b/internal/macos/macosdriver/storage.go index 6007925..adbdda1 100644 --- a/internal/macos/macosdriver/storage.go +++ b/internal/macos/macosdriver/storage.go @@ -18,20 +18,6 @@ import ( var _ driver.SnapshotDriver = (*ReimsMacOSDriver)(nil) var _ driver.DiskDriver = (*ReimsMacOSDriver)(nil) -func vmRunning(ctx context.Context, c *reims.Client, name string, d reims.VMDetail) bool { - if d.State == "running" { - return true - } - if list, err := c.List(ctx); err == nil { - for _, vm := range list { - if vm.Name == name && vm.State == "running" { - return true - } - } - } - return false -} - func (d *ReimsMacOSDriver) ListSnapshots(ctx context.Context, name string) ([]driver.DiskSnapshot, error) { c, active, err := d.startClient() if err != nil { @@ -59,7 +45,7 @@ func (d *ReimsMacOSDriver) ListSnapshots(ctx context.Context, name string) ([]dr } func (d *ReimsMacOSDriver) RunSnapshot(ctx context.Context, name, operation, snapName string, stdout, stderr io.Writer) error { - clean, err := reims.ValidateSnapshotName(snapName) + clean, err := driver.ValidateSnapshotName(snapName) if err != nil { return err } @@ -76,7 +62,7 @@ func (d *ReimsMacOSDriver) RunSnapshot(ctx context.Context, name, operation, sna return err } defer release() - if vmRunning(ctx, c, name, det) { + if c.IsRunning(ctx, det) { return fmt.Errorf("stop %s before changing restore points", name) } if reims.HasSuspendState(det.Directory) { @@ -108,7 +94,7 @@ func (d *ReimsMacOSDriver) ResizeDisk(ctx context.Context, name, newSize string, return driver.DiskResizeResult{}, err } defer release() - if vmRunning(ctx, c, name, det) { + if c.IsRunning(ctx, det) { return driver.DiskResizeResult{}, fmt.Errorf("stop %s before resizing its disk", name) } if reims.HasSuspendState(det.Directory) { @@ -149,7 +135,7 @@ func (d *ReimsMacOSDriver) compactDiskWithOptions(ctx context.Context, name stri return driver.DiskCompactResult{}, err } defer release() - if vmRunning(ctx, c, name, det) { + if c.IsRunning(ctx, det) { return driver.DiskCompactResult{}, fmt.Errorf("stop %s before rewriting its disk", name) } if reims.HasSuspendState(det.Directory) { diff --git a/internal/macos/opencore/image.go b/internal/macos/opencore/image.go index a5e9d67..7f408ee 100644 --- a/internal/macos/opencore/image.go +++ b/internal/macos/opencore/image.go @@ -11,6 +11,8 @@ import ( "path/filepath" "strings" "unicode/utf16" + + "github.com/Nwflower/reims-go/internal/host" ) const ( @@ -286,10 +288,10 @@ type fat32FS struct { } type fatEntry struct { - name string - firstCluster uint32 - size uint32 - dirEntryOff uint64 // byte offset on disk of this 32-byte short directory entry + name string + firstCluster uint32 + size uint32 + dirEntryOff uint64 // byte offset on disk of this 32-byte short directory entry } func openFAT32(d diskIO, espStart uint64) (*fat32FS, error) { @@ -745,7 +747,7 @@ func patchQcow2ViaRawWith(ctx context.Context, qcow2Path, qemuImgPath string, en func runQemuImg(ctx context.Context, qemuImgPath string, env []string, args ...string) error { cmd := exec.CommandContext(ctx, qemuImgPath, args...) - configureCmd(cmd) + host.HideConsole(cmd) if len(env) > 0 { cmd.Env = env } diff --git a/internal/macos/opencore/proc_other.go b/internal/macos/opencore/proc_other.go deleted file mode 100644 index 547b52c..0000000 --- a/internal/macos/opencore/proc_other.go +++ /dev/null @@ -1,7 +0,0 @@ -//go:build !windows - -package opencore - -import "os/exec" - -func configureCmd(_ *exec.Cmd) {} diff --git a/internal/macos/opencore/proc_windows.go b/internal/macos/opencore/proc_windows.go deleted file mode 100644 index 8417232..0000000 --- a/internal/macos/opencore/proc_windows.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build windows - -package opencore - -import ( - "os/exec" - "syscall" -) - -func configureCmd(cmd *exec.Cmd) { - cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} -} diff --git a/internal/macos/reims/compat.go b/internal/macos/reims/compat.go index 451411b..1ed5e06 100644 --- a/internal/macos/reims/compat.go +++ b/internal/macos/reims/compat.go @@ -78,11 +78,6 @@ func IsWHPXNestedVirtError(output string) bool { return strings.Contains(output, "WHPX: Failed to enable nested virtualization") } -// DiagnoseGPULog inspects QEMU / reims-vgpu output for known Vulkan GPU -// compatibility or device-loss failures and returns a machine-readable code -// ("gpu_device_lost" | "gpu_vulkan_floor") and matching line excerpt. -func DiagnoseGPULog(output string) (code, detail string) { return host.DiagnoseGPULog(output) } - // HasKernelIrqchipArg reports whether extra-args already specifies a // kernel-irqchip setting. func HasKernelIrqchipArg(extraArgs string) bool { @@ -230,7 +225,7 @@ func (c *Client) StartWithCompat(ctx context.Context, name string, stdout, stder } return fmt.Errorf("%s (%w)", msg, err) } - if gpuCode, _ := DiagnoseGPULog(combined); gpuCode != "" { + if gpuCode, _ := host.DiagnoseGPULog(combined); gpuCode != "" { msg := i18n.T(c.Locale, "err."+gpuCode) if onNote != nil { onNote(msg) diff --git a/internal/macos/reims/compat_test.go b/internal/macos/reims/compat_test.go index fdc8ef2..56a5fa3 100644 --- a/internal/macos/reims/compat_test.go +++ b/internal/macos/reims/compat_test.go @@ -375,20 +375,6 @@ func TestIsWHPXNoAcceleratorError(t *testing.T) { } } -func TestDiagnoseGPULog(t *testing.T) { - lost := "reims-vgpu: the rt platform's device on AMD Radeon (TM) Graphics (1002:15e7) was lost at vkQueueSubmit2 (ERROR_DEVICE_LOST)" - if code, detail := DiagnoseGPULog(lost); code != "gpu_device_lost" || detail == "" { - t.Fatalf("DiagnoseGPULog(lost) = (%q, %q), want gpu_device_lost", code, detail) - } - floor := "reims-vgpu: no physical device meets the floor (VK_ERROR_INCOMPATIBLE_DRIVER)" - if code, detail := DiagnoseGPULog(floor); code != "gpu_vulkan_floor" || detail == "" { - t.Fatalf("DiagnoseGPULog(floor) = (%q, %q), want gpu_vulkan_floor", code, detail) - } - if code, _ := DiagnoseGPULog("normal boot log line"); code != "" { - t.Fatalf("expected empty code for normal log, got %q", code) - } -} - func TestMergeAndStripOfflineHelperArgs(t *testing.T) { base := `-no-reboot -qmp tcp:127.0.0.1:45555,server=on,wait=off -machine kernel-irqchip=off` merged := MergeOfflineHelperArgs(base, `D:\Data\reims-go\cache\reims-helper.img`) diff --git a/internal/macos/reims/disk_import.go b/internal/macos/reims/disk_import.go index 6344717..f0f85c6 100644 --- a/internal/macos/reims/disk_import.go +++ b/internal/macos/reims/disk_import.go @@ -209,7 +209,7 @@ func ParseQCOW2CreateOptionsFromInfoJSON(raw []byte) (QCOW2CreateOptions, error) // on diskPath and returns its qcow2 creation options. func InspectQCOW2CreateOptions(ctx context.Context, qemuImgPath string, env []string, diskPath string) (QCOW2CreateOptions, error) { cmd := exec.CommandContext(ctx, qemuImgPath, "info", "--force-share", "--output=json", diskPath) - configureCmd(cmd) + host.HideConsole(cmd) cmd.Env = env out, err := cmd.CombinedOutput() if err != nil { @@ -266,7 +266,7 @@ func ConvertDiskToQCOW2(ctx context.Context, qemuImgPath string, env []string, s return err } cmd := exec.CommandContext(ctx, qemuImgPath, BuildConvertToQCOW2Args(srcPath, dstPath)...) - configureCmd(cmd) + host.HideConsole(cmd) cmd.Env = env if stdout != nil { cmd.Stdout = stdout @@ -298,7 +298,7 @@ func CreateCoWOverlay(ctx context.Context, qemuImgPath string, env []string, bac return fmt.Errorf("inspect backing qcow2 options: %w", err) } cmd := exec.CommandContext(ctx, qemuImgPath, BuildCoWOverlayArgs(backingPath, overlayPath, opts)...) - configureCmd(cmd) + host.HideConsole(cmd) cmd.Env = env if stdout != nil { cmd.Stdout = stdout @@ -327,7 +327,7 @@ func ResizeDisk(ctx context.Context, qemuImgPath string, env []string, diskPath, return DiskResizeResult{}, err } cmd := exec.CommandContext(ctx, qemuImgPath, BuildResizeDiskArgs(diskPath, arg)...) - configureCmd(cmd) + host.HideConsole(cmd) cmd.Env = env if stdout != nil { cmd.Stdout = stdout @@ -392,7 +392,7 @@ func CompactDisk(ctx context.Context, qemuImgPath string, env []string, diskPath defer os.Remove(tmpPath) cmd := exec.CommandContext(ctx, qemuImgPath, BuildCompactDiskArgs(diskPath, tmpPath, opts)...) - configureCmd(cmd) + host.HideConsole(cmd) cmd.Env = env if stdout != nil { cmd.Stdout = stdout @@ -406,7 +406,7 @@ func CompactDisk(ctx context.Context, qemuImgPath string, env []string, diskPath // Verify integrity of the compacted image before touching the original. chk := exec.CommandContext(ctx, qemuImgPath, "check", "-q", tmpPath) - configureCmd(chk) + host.HideConsole(chk) chk.Env = env if out, err := chk.CombinedOutput(); err != nil { return DiskCompactResult{}, fmt.Errorf("compacted qcow2 integrity check failed: %w (%s)", err, strings.TrimSpace(string(out))) diff --git a/internal/macos/reims/helper_args.go b/internal/macos/reims/helper_args.go index 15b2ed2..6fdd12f 100644 --- a/internal/macos/reims/helper_args.go +++ b/internal/macos/reims/helper_args.go @@ -3,6 +3,8 @@ package reims import ( "fmt" "strings" + + "github.com/Nwflower/reims-go/internal/qmp" ) // IsOfflineInstallerPath reports whether an attached installer path is a @@ -14,7 +16,7 @@ func IsOfflineInstallerPath(path string) bool { // StripOfflineHelperArgs removes any reims-go managed offline helper USB disk // arguments from QEMU extra-args while leaving all other arguments intact. func StripOfflineHelperArgs(existing string) string { - tokens := splitShellTokens(existing) + tokens := qmp.SplitArgs(existing) cleaned := make([]string, 0, len(tokens)) for i := 0; i < len(tokens); i++ { tok := tokens[i] @@ -57,7 +59,7 @@ func HasGuestToolsArgs(existing string) bool { // StripGuestToolsArgs removes any reims-go managed REIMSTOOLS USB disk args. func StripGuestToolsArgs(existing string) string { - tokens := splitShellTokens(existing) + tokens := qmp.SplitArgs(existing) cleaned := make([]string, 0, len(tokens)) for i := 0; i < len(tokens); i++ { tok := tokens[i] @@ -90,36 +92,3 @@ func MergeGuestToolsArgs(existing, toolsImgPath string) string { } return base + " " + toolsArgs } - -func splitShellTokens(s string) []string { - var out []string - var cur strings.Builder - var quote byte - for i := 0; i < len(s); i++ { - c := s[i] - if quote != 0 { - cur.WriteByte(c) - if c == quote { - quote = 0 - } - continue - } - if c == '\'' || c == '"' { - quote = c - cur.WriteByte(c) - continue - } - if c == ' ' || c == '\t' || c == '\n' || c == '\r' { - if cur.Len() > 0 { - out = append(out, cur.String()) - cur.Reset() - } - continue - } - cur.WriteByte(c) - } - if cur.Len() > 0 { - out = append(out, cur.String()) - } - return out -} diff --git a/internal/macos/reims/proc_other.go b/internal/macos/reims/proc_other.go deleted file mode 100644 index 1045666..0000000 --- a/internal/macos/reims/proc_other.go +++ /dev/null @@ -1,7 +0,0 @@ -//go:build !windows - -package reims - -import "os/exec" - -func configureCmd(cmd *exec.Cmd) {} diff --git a/internal/macos/reims/proc_windows.go b/internal/macos/reims/proc_windows.go deleted file mode 100644 index 435192e..0000000 --- a/internal/macos/reims/proc_windows.go +++ /dev/null @@ -1,17 +0,0 @@ -//go:build windows - -package reims - -import ( - "os/exec" - "syscall" -) - -const createNoWindow = 0x08000000 - -func configureCmd(cmd *exec.Cmd) { - cmd.SysProcAttr = &syscall.SysProcAttr{ - HideWindow: true, - CreationFlags: createNoWindow, - } -} diff --git a/internal/macos/reims/reims.go b/internal/macos/reims/reims.go index 0cdaa5f..0a0e7cf 100644 --- a/internal/macos/reims/reims.go +++ b/internal/macos/reims/reims.go @@ -10,6 +10,7 @@ import ( "os/exec" "path/filepath" "regexp" + "slices" "strconv" "strings" @@ -714,7 +715,7 @@ func ParseShow(name, text string) VMDetail { func (c *Client) run(ctx context.Context, stdout, stderr io.Writer, args ...string) error { cmd := exec.CommandContext(ctx, c.Binary, args...) - configureCmd(cmd) + host.HideConsole(cmd) cmd.Env = c.Env if stdout != nil { cmd.Stdout = stdout @@ -886,3 +887,15 @@ func (c *Client) Delete(ctx context.Context, name string, keepFiles bool, stdout } return c.deleteWithCoW(ctx, name, keepFiles, removeVM) } + +// IsRunning reports whether the VM runs, either in d or in a fresh list. +func (c *Client) IsRunning(ctx context.Context, d VMDetail) bool { + if d.State == "running" { + return true + } + list, err := c.List(ctx) + if err != nil { + return false + } + return slices.ContainsFunc(list, func(vm VMListItem) bool { return vm.Name == d.Name && vm.State == "running" }) +} diff --git a/internal/macos/reims/release_record.go b/internal/macos/reims/release_record.go new file mode 100644 index 0000000..14c5829 --- /dev/null +++ b/internal/macos/reims/release_record.go @@ -0,0 +1,31 @@ +package reims + +import ( + "os" + "path/filepath" + "strings" +) + +// releaseRecordFile records which macOS release a VM was created with, for its +// icon. reims-ctl keeps no such field in vm.toml. +const releaseRecordFile = ".reims-go-macos" + +// ReadReleaseRecord returns the macOS release recorded in dir: an installer +// version such as "26.7.3", or a codename such as "tahoe" for an +// online-recovery install. It is "" when none was recorded. +func ReadReleaseRecord(dir string) string { + b, err := os.ReadFile(filepath.Join(dir, releaseRecordFile)) + if err != nil { + return "" + } + return strings.TrimSpace(string(b)) +} + +// WriteReleaseRecord stores release next to vm.toml; an empty release writes nothing. +func WriteReleaseRecord(dir, release string) error { + release = strings.TrimSpace(strings.NewReplacer("\r", "", "\n", "").Replace(release)) + if dir == "" || release == "" { + return nil + } + return os.WriteFile(filepath.Join(dir, releaseRecordFile), []byte(release+"\n"), 0o644) +} diff --git a/internal/macos/reims/release_record_test.go b/internal/macos/reims/release_record_test.go new file mode 100644 index 0000000..1abcc91 --- /dev/null +++ b/internal/macos/reims/release_record_test.go @@ -0,0 +1,25 @@ +package reims + +import "testing" + +func TestReleaseRecordRoundTrip(t *testing.T) { + dir := t.TempDir() + if got := ReadReleaseRecord(dir); got != "" { + t.Fatalf("empty dir: got %q", got) + } + if err := WriteReleaseRecord(dir, ""); err != nil { + t.Fatal(err) + } + if got := ReadReleaseRecord(dir); got != "" { + t.Fatalf("empty release wrote %q", got) + } + if err := WriteReleaseRecord(dir, " 26.7.3\r\n"); err != nil { + t.Fatal(err) + } + if got := ReadReleaseRecord(dir); got != "26.7.3" { + t.Fatalf("got %q, want 26.7.3", got) + } + if err := WriteReleaseRecord("", "tahoe"); err != nil { + t.Fatalf("no dir should be a no-op, got %v", err) + } +} diff --git a/internal/macos/reims/smbios_compat.go b/internal/macos/reims/smbios_compat.go index 9da4345..2650f65 100644 --- a/internal/macos/reims/smbios_compat.go +++ b/internal/macos/reims/smbios_compat.go @@ -9,6 +9,9 @@ import ( "strings" "sync" "time" + + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/qmp" ) // BuildSMBIOSType17Value formats the value token for `-smbios ` carrying @@ -27,7 +30,7 @@ func BuildSMBIOSType17Value(speedMHz, memoryType int, includeMemoryType bool) st // HasSMBIOSType17Arg reports whether extraArgs already contains a `-smbios` // option targeting SMBIOS Type 17. func HasSMBIOSType17Arg(extraArgs string) bool { - tokens := splitShellTokens(extraArgs) + tokens := qmp.SplitArgs(extraArgs) for i := 0; i < len(tokens); i++ { tok := tokens[i] var val string @@ -102,7 +105,7 @@ func ProbeQEMUSupportsSMBIOSMemoryType(qemuPath string, env []string) bool { 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) + host.HideConsole(cmd) if len(env) > 0 { cmd.Env = env } diff --git a/internal/macos/reims/snapshot.go b/internal/macos/reims/snapshot.go index 5838671..626a303 100644 --- a/internal/macos/reims/snapshot.go +++ b/internal/macos/reims/snapshot.go @@ -11,6 +11,7 @@ import ( "strings" "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/host" ) // DiskSnapshot describes one internal qcow2 snapshot returned by `qemu-img info --output=json`. @@ -55,7 +56,7 @@ func ListDiskSnapshots(ctx context.Context, qemuImgPath string, env []string, di return nil, fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err) } cmd := exec.CommandContext(ctx, qemuImgPath, "info", "--output=json", diskPath) - configureCmd(cmd) + host.HideConsole(cmd) cmd.Env = env var stdout, stderr bytes.Buffer cmd.Stdout = &stdout @@ -77,23 +78,18 @@ func ListDiskSnapshots(ctx context.Context, qemuImgPath string, env []string, di return snaps, nil } -// ValidateSnapshotName checks that a snapshot tag is safe for `qemu-img snapshot`. -func ValidateSnapshotName(snapName string) (string, error) { - return driver.ValidateSnapshotName(snapName) -} - // RunDiskSnapshot executes `qemu-img snapshot ` // where flag is "-c" (create), "-a" (apply/restore), or "-d" (delete). func RunDiskSnapshot(ctx context.Context, qemuImgPath string, env []string, flag, snapName, diskPath string) error { if _, err := os.Stat(qemuImgPath); err != nil { return fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err) } - snapName, err := ValidateSnapshotName(snapName) + snapName, err := driver.ValidateSnapshotName(snapName) if err != nil { return err } cmd := exec.CommandContext(ctx, qemuImgPath, "snapshot", flag, snapName, diskPath) - configureCmd(cmd) + host.HideConsole(cmd) cmd.Env = env var stderr bytes.Buffer cmd.Stderr = &stderr diff --git a/internal/macos/reims/suspend.go b/internal/macos/reims/suspend.go index c74210c..440f1d3 100644 --- a/internal/macos/reims/suspend.go +++ b/internal/macos/reims/suspend.go @@ -8,6 +8,7 @@ import ( "strings" "time" + "github.com/Nwflower/reims-go/internal/qmp" rt "github.com/Nwflower/reims-go/internal/runtime" ) @@ -209,7 +210,7 @@ func shortRev(rev string) string { // StripIncomingDeferArgs removes any `-incoming defer` / `-incoming=defer` // arguments from QEMU extra-args while leaving all other arguments intact. func StripIncomingDeferArgs(existing string) string { - tokens := splitShellTokens(existing) + tokens := qmp.SplitArgs(existing) cleaned := make([]string, 0, len(tokens)) for i := 0; i < len(tokens); i++ { tok := tokens[i] diff --git a/internal/plugin/builtin/builtin.go b/internal/plugin/builtin/builtin.go index c1102ab..0bfc7a5 100644 --- a/internal/plugin/builtin/builtin.go +++ b/internal/plugin/builtin/builtin.go @@ -19,6 +19,7 @@ import ( "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/networkmsg" "github.com/Nwflower/reims-go/internal/plugin" + "github.com/Nwflower/reims-go/internal/qmp" "github.com/Nwflower/reims-go/internal/version" ) @@ -69,15 +70,6 @@ type HostCallbacks struct { GetSetting func(pluginID, vmName, key string) (any, bool) } -func hasCap(caps []string, want string) bool { - for _, cap := range caps { - if strings.EqualFold(cap, want) { - return true - } - } - return false -} - func appVersion() string { v := strings.TrimPrefix(strings.TrimSpace(version.Version), "v") if v == "" || v == "dev" { @@ -195,20 +187,20 @@ func defGuestTools(ver string, cb HostCallbacks, desiredFn func(string, bool) bo s.StopManagementNetwork(p.VMName) intent.ClearKeys = append(intent.ClearKeys, "guest-tools-network") } - if hasCap(p.RuntimeCaps, "window-file-drop") { + if plugin.HasCap(p.RuntimeCaps, "window-file-drop") { if token := s.HostDropToken(gtCfg.DriverID, p.VMName); token != "" { intent.Env["REIMS_GO_DROP_URL"] = fmt.Sprintf("http://127.0.0.1:%d/v1/host-drop", port) intent.Env["REIMS_GO_DROP_TOKEN"] = token } } - if sc.Registry().IsActive(IDInput) && hasCap(p.RuntimeCaps, "win32-unicode-input") { + if sc.Registry().IsActive(IDInput) && plugin.HasCap(p.RuntimeCaps, "win32-unicode-input") { intent.Env["REIMS_GO_INPUT_URL"] = fmt.Sprintf("http://127.0.0.1:%d/v1/host-text", port) intent.Env["REIMS_GO_INPUT_TOKEN"] = gtCfg.Token } } if reims.HasGuestToolsArgs(p.ExtraArgs) && cb.GuestToolsImg != nil && err == nil { imgPath := cb.GuestToolsImg(p.VMName) - tokens := plugin.SplitShellTokens(reims.MergeGuestToolsArgs("", imgPath)) + tokens := qmp.SplitArgs(reims.MergeGuestToolsArgs("", imgPath)) intent.Args = append(intent.Args, plugin.ArgFragment{ PluginID: IDGuestTools, Key: "reimstools", diff --git a/internal/plugin/hooks.go b/internal/plugin/hooks.go index 7899963..5e24753 100644 --- a/internal/plugin/hooks.go +++ b/internal/plugin/hooks.go @@ -3,7 +3,9 @@ package plugin import ( "context" "fmt" + "slices" "sort" + "strings" "sync" "sync/atomic" "time" @@ -61,6 +63,11 @@ type BeforeCreateResult struct { Patches map[string]any `json:"patches,omitempty"` } +// HasCap reports whether a runtime declares the capability want. +func HasCap(caps []string, want string) bool { + return slices.ContainsFunc(caps, func(c string) bool { return strings.EqualFold(c, want) }) +} + // BeforeStartPayload is passed to vm.beforeStart handlers. type BeforeStartPayload struct { VMName string `json:"vm_name"` diff --git a/internal/plugin/ledger.go b/internal/plugin/ledger.go index afa1ace..49d86c4 100644 --- a/internal/plugin/ledger.go +++ b/internal/plugin/ledger.go @@ -11,6 +11,7 @@ import ( "strings" "github.com/Nwflower/reims-go/internal/atomicfile" + "github.com/Nwflower/reims-go/internal/qmp" ) const ArgLedgerFileName = ".reims-go-arg-ledger.json" @@ -252,7 +253,7 @@ func validateSingleShellToken(tok string) error { return fmt.Errorf("QEMU argument token %q contains unquoted whitespace or quotes", tok) } } - resplit := SplitShellTokens(tok) + resplit := qmp.SplitArgs(tok) if len(resplit) != 1 || resplit[0] != tok { return fmt.Errorf("QEMU argument token %q does not round-trip as a single token", tok) } @@ -386,7 +387,7 @@ func sanitizeEnvPrefix(pluginID string) 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), " ") + return strings.Join(stripOwnedTokens(qmp.SplitArgs(currentExtraArgs), ledger), " ") } // ReconcileStartIntents strips previously owned fragments from currentExtraArgs @@ -411,7 +412,7 @@ func reconcileStartIntents(currentExtraArgs string, ledger *ArgLedger, activePlu ledger.Owners = map[string][]ArgFragment{} } - userTokens := stripOwnedTokens(SplitShellTokens(currentExtraArgs), ledger) + userTokens := stripOwnedTokens(qmp.SplitArgs(currentExtraArgs), ledger) if activePlugins != nil { for pid := range ledger.Owners { @@ -656,37 +657,3 @@ func unquoteShellToken(token string) string { } return token } - -// SplitShellTokens splits a QEMU extra-args string preserving quoted tokens. -func SplitShellTokens(s string) []string { - var out []string - var cur strings.Builder - var quote byte - for i := 0; i < len(s); i++ { - c := s[i] - if quote != 0 { - cur.WriteByte(c) - if c == quote { - quote = 0 - } - continue - } - if c == '\'' || c == '"' { - quote = c - cur.WriteByte(c) - continue - } - if c == ' ' || c == '\t' || c == '\n' || c == '\r' { - if cur.Len() > 0 { - out = append(out, cur.String()) - cur.Reset() - } - continue - } - cur.WriteByte(c) - } - if cur.Len() > 0 { - out = append(out, cur.String()) - } - return out -} diff --git a/internal/qmp/args.go b/internal/qmp/args.go new file mode 100644 index 0000000..cced01d --- /dev/null +++ b/internal/qmp/args.go @@ -0,0 +1,37 @@ +package qmp + +import "strings" + +// SplitArgs splits a QEMU extra-args string and keeps quoted tokens whole. +func SplitArgs(s string) []string { + var out []string + var cur strings.Builder + var quote byte + for i := 0; i < len(s); i++ { + c := s[i] + if quote != 0 { + cur.WriteByte(c) + if c == quote { + quote = 0 + } + continue + } + if c == '\'' || c == '"' { + quote = c + cur.WriteByte(c) + continue + } + if c == ' ' || c == '\t' || c == '\n' || c == '\r' { + if cur.Len() > 0 { + out = append(out, cur.String()) + cur.Reset() + } + continue + } + cur.WriteByte(c) + } + if cur.Len() > 0 { + out = append(out, cur.String()) + } + return out +} diff --git a/internal/qmp/keys.go b/internal/qmp/keys.go index 8137d27..34be13f 100644 --- a/internal/qmp/keys.go +++ b/internal/qmp/keys.go @@ -257,10 +257,6 @@ func absEvent(axis string, value int) map[string]any { return map[string]any{"type": "abs", "data": map[string]any{"axis": axis, "value": value}} } -func btnEvent(button string, down bool) map[string]any { - return map[string]any{"type": "btn", "data": map[string]any{"down": down, "button": button}} -} - func clampAbsCoord(norm float64) int { switch { case math.IsNaN(norm), math.IsInf(norm, 0), norm <= 0: @@ -306,20 +302,20 @@ func leftClick(ctx context.Context, q Executor, clickHold time.Duration) error { if err := ctx.Err(); err != nil { return err } - if err := send(btnEvent("left", true)); err != nil { + if err := send(mouseButtonEvent("left", true)); err != nil { return err } btnDown := true defer func() { if btnDown { - _ = send(btnEvent("left", false)) + _ = send(mouseButtonEvent("left", false)) } }() sleep(ctx, clickHold) if err := ctx.Err(); err != nil { return err } - if err := send(btnEvent("left", false)); err != nil { + if err := send(mouseButtonEvent("left", false)); err != nil { return err } btnDown = false diff --git a/internal/qmp/watcher.go b/internal/qmp/watcher.go index 3fdc4a5..270be15 100644 --- a/internal/qmp/watcher.go +++ b/internal/qmp/watcher.go @@ -46,7 +46,7 @@ func RebootSocketPath(vmDir, tmpDir, vmName string) string { // (`-no-reboot` + `-qmp `) ONLY when a managed QMP target is present, // preserving any user hand-written `-no-reboot` on hosts without managed QMP. func StripLegacyWin10RebootArgs(existing string) string { - tokens := splitShellTokens(existing) + tokens := SplitArgs(existing) hasManagedQMP := false for i := 0; i < len(tokens); i++ { if tokens[i] == "-qmp" && i+1 < len(tokens) && isManagedQMPTarget(tokens[i+1]) { @@ -76,7 +76,7 @@ func StripLegacyWin10RebootArgs(existing string) string { // `-qmp unix:,server=on,wait=off` into existing extra_args while stripping // any legacy managed TCP or Unix QMP arguments. func MergeWin10RebootUnixArgs(existing, sockPath string) string { - tokens := splitShellTokens(existing) + tokens := SplitArgs(existing) cleaned := make([]string, 0, len(tokens)+3) for i := 0; i < len(tokens); i++ { tok := tokens[i] @@ -106,7 +106,7 @@ func win10RebootUnixTarget(sockPath string) string { // HasWin10RebootUnixArgs checks for the private socket Reims-Go configured, // without accepting other monitors declared in extra-args. func HasWin10RebootUnixArgs(extraArgs, sockPath string) bool { - tokens := splitShellTokens(extraArgs) + tokens := SplitArgs(extraArgs) want := win10RebootUnixTarget(sockPath) var noReboot, socket bool for i, token := range tokens { @@ -134,39 +134,6 @@ func isManagedQMPTarget(arg string) bool { return false } -func splitShellTokens(s string) []string { - var out []string - var cur strings.Builder - var quote byte - for i := 0; i < len(s); i++ { - c := s[i] - if quote != 0 { - cur.WriteByte(c) - if c == quote { - quote = 0 - } - continue - } - if c == '\'' || c == '"' { - quote = c - cur.WriteByte(c) - continue - } - if c == ' ' || c == '\t' || c == '\n' || c == '\r' { - if cur.Len() > 0 { - out = append(out, cur.String()) - cur.Reset() - } - continue - } - cur.WriteByte(c) - } - if cur.Len() > 0 { - out = append(out, cur.String()) - } - return out -} - // WatchShutdownReason waits for QEMU's SHUTDOWN event over QMP and returns its // reason (e.g. "guest-reset", "guest-shutdown", "host-qmp-quit"), or "" on EOF. func WatchShutdownReason(ctx context.Context, addr string) (string, error) { From 565577589a6c163a6a08847b9a32151363ad0e5a 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: Thu, 3 Dec 2026 21:16:28 -0700 Subject: [PATCH 04/22] refactor: give each VM action one window binding Every VM action had two bindings: one by name and one by driver and name. The window used only the second, so the first is gone and the WithDriver suffix with it. Unused bindings and frontend exports are removed too. Tests now reject bindings the window never calls, stale generated bindings and unused frontend exports. TypeScript rejects unused locals. Co-Authored-By: Claude Opus 5.5 --- frontend/package.json | 2 +- frontend/scripts/test-unused-exports.mjs | 55 +++ frontend/src/App.tsx | 52 +-- frontend/src/components/AboutPage.tsx | 2 +- frontend/src/components/AffinityDialog.tsx | 4 +- frontend/src/components/CreateWizard.tsx | 2 - frontend/src/components/GuestIcon.tsx | 2 +- frontend/src/components/ImagesPage.tsx | 2 +- .../src/components/NetworkErrorNotice.tsx | 1 - frontend/src/components/NpcapDependency.tsx | 2 +- frontend/src/components/SettingsModal.tsx | 20 +- frontend/src/components/VMNetworkSettings.tsx | 2 +- frontend/src/components/VMPage.tsx | 30 +- frontend/src/i18n.ts | 8 +- frontend/src/i18n/icu.ts | 2 +- frontend/src/lib/dialogState.ts | 4 +- frontend/src/lib/endpoints.ts | 8 +- frontend/src/lib/format.ts | 17 +- frontend/src/lib/fullscreenHotkey.ts | 16 +- frontend/src/lib/hypervisor.ts | 4 +- frontend/src/lib/logs.ts | 6 +- frontend/src/lib/optimizations.ts | 2 +- frontend/src/lib/pluginViewActions.ts | 2 +- frontend/src/lib/pluginViewEvents.ts | 4 +- frontend/src/lib/pluginViewRouter.ts | 2 +- frontend/src/lib/tasks.ts | 4 +- frontend/src/lib/themeEngine.ts | 21 +- frontend/src/lib/uiSdk.ts | 2 +- frontend/src/lib/vmRef.ts | 2 +- frontend/src/lib/vmStats.ts | 12 +- frontend/src/styles/ui-contract.ts | 25 -- frontend/src/types.ts | 28 +- frontend/src/ui/controls.tsx | 2 +- frontend/src/ui/settings.tsx | 8 +- frontend/src/ui/themeVisuals.tsx | 6 +- frontend/src/ui/toast.tsx | 2 +- frontend/src/wails.ts | 6 +- frontend/tsconfig.json | 4 +- frontend/wailsjs/go/app/App.d.ts | 160 +++------ frontend/wailsjs/go/app/App.js | 320 +++++------------- internal/app/affinity_flow.go | 10 +- internal/app/app.go | 30 +- internal/app/clone_flow.go | 10 +- internal/app/computer_use_host.go | 32 +- internal/app/console_router_test.go | 6 +- internal/app/create_flow.go | 2 +- internal/app/dataroot_flow_test.go | 4 +- internal/app/diagnostics_flow.go | 11 +- internal/app/disk_flow.go | 15 +- internal/app/disk_flow_test.go | 2 +- internal/app/display_flow.go | 4 +- internal/app/display_flow_test.go | 36 +- internal/app/elevate_flow.go | 2 +- internal/app/endpoints_flow.go | 14 +- internal/app/endpoints_flow_test.go | 6 +- internal/app/extras_flow.go | 10 +- internal/app/fullscreen_hotkey_flow.go | 2 +- internal/app/hosted_driver_test.go | 44 +-- internal/app/hypervisor_flow.go | 11 - internal/app/hypervisor_flow_test.go | 23 +- internal/app/install_guide.go | 2 +- internal/app/lifecycle_flow.go | 30 +- internal/app/lifecycle_flow_test.go | 12 +- internal/app/macos_lifecycle_native.go | 10 +- internal/app/plugins_flow.go | 25 -- internal/app/quit_flow.go | 2 +- internal/app/quit_flow_test.go | 4 +- internal/app/snapshot_flow.go | 28 +- internal/app/ssh_flow.go | 40 +-- internal/app/ssh_flow_test.go | 6 +- internal/app/stats_flow.go | 3 +- internal/app/stats_flow_test.go | 2 +- internal/app/suspend_flow.go | 18 +- internal/app/suspend_flow_test.go | 2 +- internal/app/tasks.go | 11 - internal/app/tasks_test.go | 9 + internal/app/thumbnail_flow.go | 34 +- internal/app/thumbnail_flow_test.go | 8 +- internal/app/timezone_flow.go | 12 +- internal/app/timezone_flow_test.go | 12 +- internal/app/type_flow.go | 18 +- internal/app/vm_close_windows.go | 2 +- internal/app/vmref_test.go | 2 +- internal/app/window_launch.go | 8 +- internal/archtest/bindings_test.go | 86 +++++ internal/cli/cli.go | 2 +- internal/cli/macos_native.go | 2 +- internal/cli/start.go | 4 +- internal/plugin/manager_sidecar_test.go | 2 +- internal/plugin/package.go | 10 - internal/plugin/scanner.go | 3 +- 91 files changed, 606 insertions(+), 930 deletions(-) create mode 100644 frontend/scripts/test-unused-exports.mjs create mode 100644 internal/archtest/bindings_test.go diff --git a/frontend/package.json b/frontend/package.json index 3fbcfb8..8a74cc6 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -5,7 +5,7 @@ "type": "module", "scripts": { "dev": "vite", - "test": "node --test --test-concurrency=2 scripts/test-i18n.mjs scripts/test-keymap.mjs scripts/test-plugins.mjs scripts/test-tasks.mjs scripts/test-display-presets.mjs scripts/test-endpoints.mjs scripts/test-guest-tools.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs scripts/test-hypervisor.mjs", + "test": "node --test --test-concurrency=2 scripts/test-i18n.mjs scripts/test-keymap.mjs scripts/test-plugins.mjs scripts/test-tasks.mjs scripts/test-display-presets.mjs scripts/test-endpoints.mjs scripts/test-guest-tools.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs scripts/test-unused-exports.mjs scripts/test-hypervisor.mjs", "typecheck": "tsc --noEmit", "bundle": "vite build && node scripts/check-ui-contract.mjs", "build": "tsc --noEmit && pnpm run bundle", diff --git a/frontend/scripts/test-unused-exports.mjs b/frontend/scripts/test-unused-exports.mjs new file mode 100644 index 0000000..7c4db7e --- /dev/null +++ b/frontend/scripts/test-unused-exports.mjs @@ -0,0 +1,55 @@ +// Rejects exports in src/ that no other file uses: dead code, or an export +// keyword that only widens a module's interface. +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import ts from 'typescript' + +const root = path.resolve(import.meta.dirname, '..') + +function findUnusedExports() { + const { config } = ts.readConfigFile(path.join(root, 'tsconfig.json'), ts.sys.readFile) + const { fileNames, options } = ts.parseJsonConfigFileContent(config, ts.sys, root) + const service = ts.createLanguageService({ + ...ts.sys, + getCompilationSettings: () => options, + getScriptFileNames: () => fileNames, + getScriptVersion: () => '1', + getScriptSnapshot: (file) => (fs.existsSync(file) ? ts.ScriptSnapshot.fromString(fs.readFileSync(file, 'utf8')) : undefined), + getCurrentDirectory: () => root, + getDefaultLibFileName: ts.getDefaultLibFilePath, + }) + // The test and contract scripts import src modules or read them as text. + const scripts = fs.readdirSync(import.meta.dirname) + .filter((name) => name !== path.basename(import.meta.filename)) + .map((name) => fs.readFileSync(path.join(import.meta.dirname, name), 'utf8')) + .join('\n') + + const unused = [] + for (const file of fileNames) { + // bridgeContract.ts also documents the message types for plugin authors. + if (file.endsWith('.gen.ts') || file.endsWith('/bridgeContract.ts')) continue + const source = service.getProgram().getSourceFile(file) + for (const statement of source.statements) { + if (!ts.canHaveModifiers(statement) || !ts.getModifiers(statement)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) continue + const names = ts.isVariableStatement(statement) + ? statement.declarationList.declarations.map((d) => d.name).filter(ts.isIdentifier) + : [statement.name].filter(Boolean) + for (const name of names) { + if (new RegExp(`\\b${name.text}\\b`).test(scripts)) continue + const references = (service.findReferences(file, name.getStart(source)) ?? []).flatMap((r) => r.references) + if (references.every((r) => r.fileName === file)) { + unused.push(`${path.relative(root, file)}: ${name.text}`) + } + } + } + } + return { unused, files: fileNames.length } +} + +test('every export in src/ has a user outside its own file', () => { + const { unused, files } = findUnusedExports() + assert.ok(files > 50, `expected to scan src/, found ${files} files`) + assert.deepEqual(unused, []) +}) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 1ed836b..087bf2d 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -24,7 +24,7 @@ import { macOSMajor } from './macos/macosRelease' import { currentTask, finishedTaskTTL, isActiveInstallerTask, pruneFinishedTasks, upsertTask } from './lib/tasks' import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, emitThemeEvent, notifyInteractiveThemeState, type UIStateSnapshot } from './lib/themeEngine' import { hasVisibleDialog } from './lib/dialogState' -import { latestVMStatsWithDriver, refreshSubscribedVMStats, refreshVMStatsWithDriver } from './lib/vmStats' +import { latestVMStats, refreshSubscribedVMStats, refreshVMStats } from './lib/vmStats' import { vmRefKey } from './lib/vmRef' import { closePluginDialog, closePluginView, emptyPluginViewState, matchViewCondition, openPluginView, pluginViewKey, prunePluginViews, type PluginViewRoute, type PluginViewState } from './lib/pluginViewRouter' import { publishPluginHostEvent } from './lib/pluginViewEvents' @@ -434,9 +434,9 @@ export const App: React.FC = () => { let live = true for (const vm of vms) { const key = vmRefKey(vm) - api.GetVMNoteWithDriver(vm.driver_id ?? '', vm.name) + api.GetVMNote(vm.driver_id ?? '', vm.name) .then((n) => { if (live) setDisplayNames((m) => ({ ...m, [key]: (n ?? '').trim() })) }) - .catch((e) => console.warn('[app] GetVMNoteWithDriver failed:', key, e)) + .catch((e) => console.warn('[app] GetVMNote failed:', key, e)) } return () => { live = false } // eslint-disable-next-line react-hooks/exhaustive-deps @@ -742,7 +742,7 @@ export const App: React.FC = () => { openSettings: () => setSelected(SETTINGS_ID), focusVMWindow: (vmName) => { const vm = vmsRef.current.find((v) => vmRefKey(v) === vmName) ?? vmsRef.current.find((v) => v.name === vmName) - void api.FocusVMWindowWithDriver(vm?.driver_id ?? '', vm?.name ?? vmName).catch((e) => console.warn('[theme] FocusVMWindowWithDriver failed:', vmName, e)) + void api.FocusVMWindow(vm?.driver_id ?? '', vm?.name ?? vmName).catch((e) => console.warn('[theme] FocusVMWindow failed:', vmName, e)) }, }, ) @@ -765,7 +765,7 @@ export const App: React.FC = () => { try { const logVM = name === selectedVM?.name ? selectedVM : vms.find((v) => v.name === name) const logDriverID = logVM?.driver_id ?? '' - const text = await api.ReadVMLogsWithDriver(logDriverID, name, serial) + const text = await api.ReadVMLogs(logDriverID, name, serial) if (serial) setSerialLog(text) else setQemuLog(text) } catch (e) { @@ -903,7 +903,7 @@ export const App: React.FC = () => { // Hosted VMs have no window: the primary action is their best ready endpoint. const openEndpoint = (vm: VMListItem, kind: string) => { - api.OpenVMEndpointWithDriver(vm.driver_id ?? '', vm.name, kind, '').catch((e) => fail(tr('failEndpointOpen'), e)) + api.OpenVMEndpoint(vm.driver_id ?? '', vm.name, kind, '').catch((e) => fail(tr('failEndpointOpen'), e)) } const openPrimaryEndpoint = (vm: VMListItem) => { const { primary } = splitEndpoints(vm.endpoints) @@ -941,21 +941,21 @@ export const App: React.FC = () => { return } switch (action) { - case 'start': return runVMAction(key, action, () => api.StartVMWithDriver(actionDriverID, name)) - case 'suspend': return runVMAction(key, action, () => api.SuspendVMWithDriver(actionDriverID, name), tr('toastSuspended', { name })) - case 'resume': return runVMAction(key, action, () => api.ResumeVMWithDriver(actionDriverID, name), tr('toastResumed', { name })) + case 'start': return runVMAction(key, action, () => api.StartVM(actionDriverID, name)) + case 'suspend': return runVMAction(key, action, () => api.SuspendVM(actionDriverID, name), tr('toastSuspended', { name })) + case 'resume': return runVMAction(key, action, () => api.ResumeVM(actionDriverID, name), tr('toastResumed', { name })) case 'discardSuspend': return setDiscardSuspendTarget(key) - case 'focus': return api.FocusVMWindowWithDriver(actionDriverID, name).catch((e) => fail(tr('failFocus'), e)) + case 'focus': return api.FocusVMWindow(actionDriverID, name).catch((e) => fail(tr('failFocus'), e)) case 'fullscreen': return runVMAction(key, action, async () => { - const isFullscreen = await api.ToggleVMFullscreenWithDriver(actionDriverID, name) - refreshVMStatsWithDriver(actionDriverID, name, { window_fullscreen: isFullscreen }) + const isFullscreen = await api.ToggleVMFullscreen(actionDriverID, name) + refreshVMStats(actionDriverID, name, { window_fullscreen: isFullscreen }) }) - case 'screenshot': return runVMAction(key, action, () => api.CopyVMScreenshotWithDriver(actionDriverID, name), tr('toastScreenshotCopied')) - case 'stop': return runVMAction(key, action, () => api.StopVMWithDriver(actionDriverID, name, false), tr('toastStopped', { name })) - case 'forceStop': return runVMAction(key, action, () => api.StopVMWithDriver(actionDriverID, name, true), tr('toastStopped', { name })) - case 'restart': return runVMAction(key, action, () => api.RestartVMWithDriver(actionDriverID, name)) - case 'eject': return runVMAction(key, action, () => api.EjectInstallerWithDriver(actionDriverID, name), tr('toastEjected')) + case 'screenshot': return runVMAction(key, action, () => api.CopyVMScreenshot(actionDriverID, name), tr('toastScreenshotCopied')) + case 'stop': return runVMAction(key, action, () => api.StopVM(actionDriverID, name, false), tr('toastStopped', { name })) + case 'forceStop': return runVMAction(key, action, () => api.StopVM(actionDriverID, name, true), tr('toastStopped', { name })) + case 'restart': return runVMAction(key, action, () => api.RestartVM(actionDriverID, name)) + case 'eject': return runVMAction(key, action, () => api.EjectInstaller(actionDriverID, name), tr('toastEjected')) case 'finishInstall': return runVMAction(key, action, () => api.FinishInstall(name), tr(isRunning ? 'toastExitRecoveryNextStart' : 'toastInstallFinished')) case 'enterRecovery': return runVMAction(key, action, () => api.EnterRecovery(name), tr(isRunning ? 'toastEnterRecoveryNextStart' : 'toastEnterRecovery')) case 'attachInstaller': return attachInstaller(key, name, isRunning) @@ -966,11 +966,11 @@ export const App: React.FC = () => { case 'upgradeNVMe': return runVMAction(key, action, () => api.UpgradeDiskToNVMe(name), tr(isRunning ? 'toastNVMeNextStart' : 'toastNVMeReady')) case 'exportDiagnostics': - return runVMAction(key, action, async () => { await api.ExportDiagnosticsWithDriver(actionDriverID, name) }, tr('toastDiagExported')) + return runVMAction(key, action, async () => { await api.ExportDiagnostics(actionDriverID, name) }, tr('toastDiagExported')) case 'cloneVM': if (!features.clone) return return setCloneSource({ name, driverID: actionDriverID }) - case 'type': return typeInto(key, () => api.TypeClipboardWithDriver(actionDriverID, name)) + case 'type': return typeInto(key, () => api.TypeClipboard(actionDriverID, name)) case 'sendText': return setSendTextTarget(key) case 'openFolder': return api.OpenVMFolder(name).catch((e) => fail(tr('failOpenFolder'), e)) @@ -1018,7 +1018,7 @@ export const App: React.FC = () => { const name = targetVM?.name ?? target const driverID = targetVM?.driver_id ?? '' const key = targetVM ? vmRefKey(targetVM) : (name ?? '') - if (name) runVMAction(key, 'delete', () => api.DeleteVMWithDriver(driverID, name, keepFiles), tr('toastDeleted', { name })) + if (name) runVMAction(key, 'delete', () => api.DeleteVM(driverID, name, keepFiles), tr('toastDeleted', { name })) } const confirmDiscardSuspend = () => { @@ -1028,7 +1028,7 @@ export const App: React.FC = () => { const name = targetVM?.name ?? target const driverID = targetVM?.driver_id ?? '' const key = targetVM ? vmRefKey(targetVM) : (name ?? '') - if (name) runVMAction(key, 'discardSuspend', () => api.DiscardSuspendWithDriver(driverID, name), tr('toastDiscardSuspend', { name })) + if (name) runVMAction(key, 'discardSuspend', () => api.DiscardSuspend(driverID, name), tr('toastDiscardSuspend', { name })) } const confirmOnlineRecovery = () => { @@ -1045,7 +1045,7 @@ export const App: React.FC = () => { setCloneSource(null) if (!src) return runVMAction(vmRefKey({ name: src.name, driver_id: src.driverID }), 'cloneVM', async () => { - await api.CloneVMCoWWithDriver(src.driverID, src.name, cloneName) + await api.CloneVMCoW(src.driverID, src.name, cloneName) setSelected(vmRefKey({ name: cloneName, driver_id: src.driverID })) }, tr('toastCloned', { name: cloneName })) } @@ -1485,7 +1485,7 @@ export const App: React.FC = () => { onDelete={() => setDeleteTarget(vmRefKey(selectedVM))} onViewLogs={() => { openLogs('serial'); loadSerial() }} onCopy={copy} - onTypeText={(text) => typeInto(vmRefKey(selectedVM), () => api.TypeTextWithDriver(selectedVM.driver_id ?? '', selectedVM.name, text))} + onTypeText={(text) => typeInto(vmRefKey(selectedVM), () => api.TypeText(selectedVM.driver_id ?? '', selectedVM.name, text))} onToggleBorderless={(enabled) => { api.ToggleBorderless(selectedVM.name, enabled) .then(() => { @@ -1615,7 +1615,7 @@ export const App: React.FC = () => { locale={locale} detail={detail} driverID={selectedVM?.driver_id ?? ''} - stats={latestVMStatsWithDriver(selectedVM?.driver_id ?? '', detail.name)} + stats={latestVMStats(selectedVM?.driver_id ?? '', detail.name)} host={state.host} fixedModeSupported={fixedModeSupported} optimizations={state.optimizations} @@ -1752,12 +1752,12 @@ export const App: React.FC = () => { setSendTextTarget(null)} onConfirm={(text) => { const target = sendTextTarget setSendTextTarget(null) - typeInto(sendVM ? vmRefKey(sendVM) : target, () => api.TypeTextWithDriver(sendVM?.driver_id ?? '', sendName, text)) + typeInto(sendVM ? vmRefKey(sendVM) : target, () => api.TypeText(sendVM?.driver_id ?? '', sendName, text)) }} /> ) diff --git a/frontend/src/components/AboutPage.tsx b/frontend/src/components/AboutPage.tsx index 9462663..947d41a 100644 --- a/frontend/src/components/AboutPage.tsx +++ b/frontend/src/components/AboutPage.tsx @@ -15,7 +15,7 @@ import { BrandMark } from '../ui/themeVisuals' const DISCORD_INVITE_URL = 'https://discord.gg/Tj682rW5rS' const QQ_GROUP_ID = '1136042744' -export type AppUpdateChannel = 'stable' | 'alpha' | 'dev' +type AppUpdateChannel = 'stable' | 'alpha' | 'dev' interface Props { locale: Locale diff --git a/frontend/src/components/AffinityDialog.tsx b/frontend/src/components/AffinityDialog.tsx index e8858b1..3ad63a7 100644 --- a/frontend/src/components/AffinityDialog.tsx +++ b/frontend/src/components/AffinityDialog.tsx @@ -100,7 +100,7 @@ export const AffinityDialog: React.FC = ({ let live = true setLoading(true) setErr('') - api.GetVMAffinityWithDriver(driverID, vmName) + api.GetVMAffinity(driverID, vmName) .then((st) => { if (!live) return setStatus(st) @@ -206,7 +206,7 @@ export const AffinityDialog: React.FC = ({ setSaving(true) setErr('') try { - const updated = await api.SetVMAffinityWithDriver(driverID, vmName, { + const updated = await api.SetVMAffinity(driverID, vmName, { mode, cpus: mode === 'custom' ? selected : [], disable_eco_qos: disableEcoQoS, diff --git a/frontend/src/components/CreateWizard.tsx b/frontend/src/components/CreateWizard.tsx index c79faba..5e86a05 100644 --- a/frontend/src/components/CreateWizard.tsx +++ b/frontend/src/components/CreateWizard.tsx @@ -8,7 +8,6 @@ import '../i18n/domains/wizard.gen' import '../i18n/domains/settings.gen' import { I18nKey, locText, parseAppError, t } from '../i18n' import { - GUEST_LANG_PRESETS, guestLangOptions, MEMORY_MARKS, controllerLabel, @@ -32,7 +31,6 @@ import { recommendedMemoryGB, recommendedResolution, shortGPUName, - splitLangLabel, sshCommand, } from '../lib/format' import { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, Task, ValidationIssue, VMNetworkSettings } from '../types' diff --git a/frontend/src/components/GuestIcon.tsx b/frontend/src/components/GuestIcon.tsx index e9278ed..4eeb1c2 100644 --- a/frontend/src/components/GuestIcon.tsx +++ b/frontend/src/components/GuestIcon.tsx @@ -13,7 +13,7 @@ export const hasGuestArt = (family: GuestFamily): boolean => ART_FAMILIES.includ * names. macOS keeps its version artwork (VersionArt), so this returns null * for it and for an unknown family and the caller falls back to that artwork. */ -export const GuestIcon: React.FC<{ family: GuestFamily; size?: number }> = ({ family, size = 15 }) => { +const GuestIcon: React.FC<{ family: GuestFamily; size?: number }> = ({ family, size = 15 }) => { switch (family) { case 'linux': return diff --git a/frontend/src/components/ImagesPage.tsx b/frontend/src/components/ImagesPage.tsx index 3a5bcc5..35982c4 100644 --- a/frontend/src/components/ImagesPage.tsx +++ b/frontend/src/components/ImagesPage.tsx @@ -9,7 +9,7 @@ import { PluginPanelFrame } from './PluginPanelFrame' import { locText } from './SchemaForm' import { WordmarkLoader } from './WordmarkLoader' -export interface NativeImageSourceRenderOpts { +interface NativeImageSourceRenderOpts { refreshSignal: number onBusyChange: (busy: boolean) => void } diff --git a/frontend/src/components/NetworkErrorNotice.tsx b/frontend/src/components/NetworkErrorNotice.tsx index 2d569e8..a841f7c 100644 --- a/frontend/src/components/NetworkErrorNotice.tsx +++ b/frontend/src/components/NetworkErrorNotice.tsx @@ -1,4 +1,3 @@ -import React from 'react' import { t } from '../i18n' import type { ParsedAppError } from '../i18n' import type { Locale } from '../types' diff --git a/frontend/src/components/NpcapDependency.tsx b/frontend/src/components/NpcapDependency.tsx index b5dd547..5c39f50 100644 --- a/frontend/src/components/NpcapDependency.tsx +++ b/frontend/src/components/NpcapDependency.tsx @@ -1,4 +1,4 @@ -import React, { useState } from 'react' +import { useState } from 'react' import '../i18n/domains/settings.gen' import { parseAppError, t } from '../i18n' import type { ParsedAppError } from '../i18n' diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index a485f22..0a6b9de 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -93,7 +93,7 @@ const CUSTOM = '__custom' const PRIMARY_DISPLAY_OPT = '__primary' const RES_RE = /^\s*\d{3,5}\s*[x×]\s*\d{3,5}\s*$/i -type VMTimezoneStatus = Awaited> +type VMTimezoneStatus = Awaited> const GUEST_TOOLS_INSTALL_CMD = 'sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command' const GUEST_TIMEZONE_APPLY_CMD = 'sh /Volumes/REIMSTOOLS/Apply-Timezone.command' @@ -387,9 +387,9 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats useEffect(() => { let active = true - api.GetVMAffinityWithDriver(driverID, detail.name) + api.GetVMAffinity(driverID, detail.name) .then((st) => { if (active) setAffinityStatus(st) }) - .catch((e) => console.warn('[settings] GetVMAffinityWithDriver failed:', e)) + .catch((e) => console.warn('[settings] GetVMAffinity failed:', e)) return () => { active = false } }, [detail.name, running, affinityVersion]) @@ -409,7 +409,7 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats let active = true const reqSeq = displayReqSeqRef.current if (displayBusyRef.current) return () => { active = false } - api.GetVMDisplayWithDriver(driverID, detail.name) + api.GetVMDisplay(driverID, detail.name) .then((st) => { if (active && displayReqSeqRef.current === reqSeq) { setDisplayStatus(st) @@ -430,7 +430,7 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats useEffect(() => { if (cat !== 'general') return - const { refresh, stop } = tzRequests.watch(vmSettingsKey, () => api.GetVMTimezoneWithDriver(driverID, detail.name)) + const { refresh, stop } = tzRequests.watch(vmSettingsKey, () => api.GetVMTimezone(driverID, detail.name)) void refresh() const timer = window.setInterval(refresh, 3000) return () => { stop(); window.clearInterval(timer) } @@ -440,7 +440,7 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats if (busy || displayBusyRef.current || !tzStatus) return const currentSetting = tzStatus.mode === 'off' ? 'off' : tzStatus.mode === 'custom' ? tzStatus.timezone : 'host' if (nextSetting === currentSetting) return - if (await tzRequests.write(vmSettingsKey, () => api.SetVMTimezoneWithDriver(driverID, detail.name, nextSetting))) { + if (await tzRequests.write(vmSettingsKey, () => api.SetVMTimezone(driverID, detail.name, nextSetting))) { onToast({ kind: 'ok', title: tr('guestTimezoneSaved') }) } } @@ -624,7 +624,7 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats setDisplayBusy(true) setDisplayErr('') try { - const next = await api.SetVMDisplayWithDriver(driverID, vmName, nextTarget) + const next = await api.SetVMDisplay(driverID, vmName, nextTarget) if (activeVMNameRef.current !== vmName || displayReqSeqRef.current !== opSeq) return setDisplayStatus(next) const chosenLabel = displayOptions.find((o) => o.value === nextValue)?.label @@ -1213,7 +1213,7 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats setErr('') setDiskOpBusy('resize') try { - const res = await api.ResizeVMDiskWithDriver(driverID, vmName, resizeInput.trim()) + const res = await api.ResizeVMDisk(driverID, vmName, resizeInput.trim()) if (activeVMNameRef.current === vmName) { setResizeResult(res) } @@ -1243,13 +1243,13 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats setDiskOpBusy(optimize ? 'optimize' : 'compact') try { if (optimize) { - const res = await api.OptimizeVMDiskWithDriver(driverID, vmName) + const res = await api.OptimizeVMDisk(driverID, vmName) if (activeVMNameRef.current === vmName) { setOptimizeResult(res) setCompactResult(null) } } else { - const res = await api.CompactVMDiskWithDriver(driverID, vmName) + const res = await api.CompactVMDisk(driverID, vmName) if (activeVMNameRef.current === vmName) { setCompactResult(res) } diff --git a/frontend/src/components/VMNetworkSettings.tsx b/frontend/src/components/VMNetworkSettings.tsx index 43d5386..5fcbe57 100644 --- a/frontend/src/components/VMNetworkSettings.tsx +++ b/frontend/src/components/VMNetworkSettings.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useState } from 'react' +import { useEffect, useState } from 'react' import '../i18n/domains/settings.gen' import { parseAppError, t } from '../i18n' import type { I18nKey, ParsedAppError } from '../i18n' diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index a4df2d2..5c8583c 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -97,7 +97,7 @@ const OFFLINE_INSTALL_CMD = 'sh /Volumes/REIMSHELP/install.sh' const GUEST_TOOLS_INSTALL_CMD = 'sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command' const HOST_DNS_APPLY_CMD = 'sh /Volumes/REIMSTOOLS/Apply-Host-DNS.command' const HOST_DNS_DISABLE_CMD = 'sh /Volumes/REIMSTOOLS/Disable-Host-DNS.command' -export const PRIMARY_SHORTCUT = 'Ctrl+Enter' +const PRIMARY_SHORTCUT = 'Ctrl+Enter' const GUEST_FAMILY_LABEL: Record = { macos: 'macOS', linux: 'Linux', windows: 'Windows', android: 'Android' } @@ -346,9 +346,9 @@ export const VMPage: React.FC = ({ let live = true const pull = () => { if (document.hidden) return - api.GetVMThumbnailWithDriver(driverID, name) + api.GetVMThumbnail(driverID, name) .then((t) => { if (live && t?.data_url) setThumb(t) }) - .catch((e) => console.warn('[vm] GetVMThumbnailWithDriver failed:', e)) + .catch((e) => console.warn('[vm] GetVMThumbnail failed:', e)) } pull() const timer = running ? window.setInterval(pull, 15000) : undefined @@ -377,7 +377,7 @@ export const VMPage: React.FC = ({ if (next === name) next = '' if (next === displayName) return try { - await api.SetVMNoteWithDriver(driverID, name, next) + await api.SetVMNote(driverID, name, next) onDisplayNameSaved(next) } catch (e) { onError(tr('failGeneric'), e) @@ -399,7 +399,7 @@ export const VMPage: React.FC = ({ // The remembered SSH user belongs to the macOS connection row; other drivers keep theirs in their endpoints. if (!isMacOSDriver) { setSshUser(''); return } let live = true - api.GetVMSSHUserWithDriver(driverID, name).then((u) => { if (live) setSshUser(u ?? '') }).catch(() => { if (live) setSshUser('') }) + api.GetVMSSHUser(driverID, name).then((u) => { if (live) setSshUser(u ?? '') }).catch(() => { if (live) setSshUser('') }) return () => { live = false } }, [driverID, name, isMacOSDriver]) @@ -408,13 +408,13 @@ export const VMPage: React.FC = ({ setEndpointBusy(busyKey) const done = () => setEndpointBusy((cur) => (cur === busyKey ? '' : cur)) if (action === 'copy') { - api.GetVMEndpointCommandWithDriver(driverID, name, ep.kind) + api.GetVMEndpointCommand(driverID, name, ep.kind) .then((cmd) => onCopy(cmd)) .catch((e) => onError(tr('failEndpointCommand'), e)) .finally(done) return } - api.OpenVMEndpointWithDriver(driverID, name, ep.kind, action) + api.OpenVMEndpoint(driverID, name, ep.kind, action) .catch((e) => onError(tr('failEndpointOpen'), e)) .finally(done) } @@ -441,21 +441,21 @@ export const VMPage: React.FC = ({ } const openSSHTerminal = () => { - api.OpenSSHTerminalWithDriver(driverID, name, sshUser).catch((e) => onError(tr('failSSH'), e)) + api.OpenSSHTerminal(driverID, name, sshUser).catch((e) => onError(tr('failSSH'), e)) } const writeSSHConfig = () => { - api.WriteSSHConfigWithDriver(driverID, name, sshUser) + api.WriteSSHConfig(driverID, name, sshUser) .then((alias) => onToast(tr('toastSSHConfigWritten', { alias }))) .catch((e) => onError(tr('failSSH'), e)) } const openVSCodeSSH = () => { - api.OpenVSCodeSSHWithDriver(driverID, name, sshUser).catch((e) => onError(tr('failSSH'), e)) + api.OpenVSCodeSSH(driverID, name, sshUser).catch((e) => onError(tr('failSSH'), e)) } const saveSSHUser = async () => { const next = sshUserDraft.trim() setSshUserDialog(false) try { - await api.SetVMSSHUserWithDriver(driverID, name, next) + await api.SetVMSSHUser(driverID, name, next) setSshUser(next) onToast(tr('toastSSHUserSaved')) } catch (e) { @@ -495,7 +495,7 @@ export const VMPage: React.FC = ({ const loadSnapshots = () => { if (!showSnapshots) { setSnapshots([]); return } - api.ListSnapshotsWithDriver(driverID, name).then((list) => setSnapshots(list ?? [])).catch(() => setSnapshots([])) + api.ListSnapshots(driverID, name).then((list) => setSnapshots(list ?? [])).catch(() => setSnapshots([])) } useEffect(() => { setCreatingSnap(false) @@ -510,7 +510,7 @@ export const VMPage: React.FC = ({ if (!label) return setSnapBusy('create') try { - await api.CreateSnapshotWithDriver(driverID, name, label) + await api.CreateSnapshot(driverID, name, label) setSnapDraft('') setCreatingSnap(false) onToast(tr('toastSnapshotCreated', { name: label })) @@ -525,7 +525,7 @@ export const VMPage: React.FC = ({ setRestoreTarget(null) setSnapBusy(`restore:${snapName}`) try { - await api.RestoreSnapshotWithDriver(driverID, name, snapName) + await api.RestoreSnapshot(driverID, name, snapName) onToast(tr('toastSnapshotRestored', { name: snapName })) loadSnapshots() } catch (e) { @@ -537,7 +537,7 @@ export const VMPage: React.FC = ({ const handleDeleteSnapshot = async (snapName: string) => { setSnapBusy(`delete:${snapName}`) try { - await api.DeleteSnapshotWithDriver(driverID, name, snapName) + await api.DeleteSnapshot(driverID, name, snapName) onToast(tr('toastSnapshotDeleted', { name: snapName })) loadSnapshots() } catch (e) { diff --git a/frontend/src/i18n.ts b/frontend/src/i18n.ts index db69f35..f4456cc 100644 --- a/frontend/src/i18n.ts +++ b/frontend/src/i18n.ts @@ -6,7 +6,7 @@ import { builtinDict, registerBuiltinDomain } from './i18n/runtime' export type { I18nKey } export { registerBuiltinDomain } -export interface LocaleOption { +interface LocaleOption { value: Locale label: string detail?: string @@ -65,11 +65,11 @@ function primarySubtag(tag: string): string { return idx >= 0 ? s.slice(0, idx) : s } -export function isZhLocale(locale: Locale): boolean { +function isZhLocale(locale: Locale): boolean { return primarySubtag(locale) === 'zh' } -export function isCJKLocale(locale: Locale): boolean { +function isCJKLocale(locale: Locale): boolean { const p = primarySubtag(locale) return p === 'zh' || p === 'ja' || p === 'ko' } @@ -87,7 +87,7 @@ function isBuiltinLocale(locale: string): locale is BuiltinLocale { return locale === 'zh-CN' || locale === 'en-US' } -export function canonicalizeTag(raw: string | undefined): string { +function canonicalizeTag(raw: string | undefined): string { if (!raw) return '' const clean = raw.trim().split(/[.@]/)[0].replaceAll('_', '-') const low = clean.toLowerCase() diff --git a/frontend/src/i18n/icu.ts b/frontend/src/i18n/icu.ts index 773ced8..de3e147 100644 --- a/frontend/src/i18n/icu.ts +++ b/frontend/src/i18n/icu.ts @@ -51,7 +51,7 @@ export function formatLocaleNumber(locale: string, value: number, precision = -1 const MAX_ICU_DEPTH = 16 const MAX_ICU_TEMPLATE_LEN = 16384 -export function parseICU(tmpl: string): ICUNode[] | null { +function parseICU(tmpl: string): ICUNode[] | null { if (tmpl.length > MAX_ICU_TEMPLATE_LEN) return null if (astCache.has(tmpl)) { return astCache.get(tmpl) ?? null diff --git a/frontend/src/lib/dialogState.ts b/frontend/src/lib/dialogState.ts index 6780e77..5272a80 100644 --- a/frontend/src/lib/dialogState.ts +++ b/frontend/src/lib/dialogState.ts @@ -3,13 +3,13 @@ // visibility:hidden/collapse, [hidden], [inert], aria-hidden="true", // data-state="closed") must not block global shortcuts or menu focus return. -export interface DialogLikeElement { +interface DialogLikeElement { getAttribute(name: string): string | null closest?(selector: string): unknown parentElement?: DialogLikeElement | null } -export interface ComputedVisibility { +interface ComputedVisibility { display: string visibility: string } diff --git a/frontend/src/lib/endpoints.ts b/frontend/src/lib/endpoints.ts index d485ef3..d14ae4c 100644 --- a/frontend/src/lib/endpoints.ts +++ b/frontend/src/lib/endpoints.ts @@ -3,7 +3,7 @@ import type { VMEndpoint, VMInfo, VMListItem } from '../types' // Guest family, driver capabilities and endpoint ordering for non-macOS guests. // Everything here is pure so node:test can load it (scripts/test-endpoints.mjs). -export const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos' +const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos' export type GuestFamily = 'macos' | 'linux' | 'windows' | 'android' | '' @@ -85,7 +85,7 @@ export function vmFeatures(vm?: { driver_id?: string; capabilities?: readonly st /** Highest priority first: the first ready endpoint in this order is the primary hosted action. */ export const ENDPOINT_PRIORITY = ['vmconnect', 'rdp', 'wsl', 'ssh', 'adb'] as const -export type EndpointKind = (typeof ENDPOINT_PRIORITY)[number] +type EndpointKind = (typeof ENDPOINT_PRIORITY)[number] export type EndpointAction = 'open' | 'terminal' | 'vscode' | 'config' | 'edit' | 'shell' | 'copy' @@ -102,7 +102,7 @@ function rank(kind: string): number { return i < 0 ? ENDPOINT_PRIORITY.length : i } -export function isEndpointKind(kind: string): kind is EndpointKind { +function isEndpointKind(kind: string): kind is EndpointKind { return rank(kind) < ENDPOINT_PRIORITY.length } @@ -121,7 +121,7 @@ export function secondaryEndpointActions(kind: string): EndpointAction[] { return endpointActions(kind).slice(1) } -export interface EndpointSplit { +interface EndpointSplit { /** The highest-priority ready endpoint; absent when none is ready. */ primary?: VMEndpoint /** All other endpoints in priority order, never the primary one. */ diff --git a/frontend/src/lib/format.ts b/frontend/src/lib/format.ts index 7d93675..9a565da 100644 --- a/frontend/src/lib/format.ts +++ b/frontend/src/lib/format.ts @@ -10,10 +10,6 @@ function currentDocLocale(): string { // Human-readable values for the main view (see docs/design-guidelines.md). // Raw values stay available under "Technical details". -export function formatNameList(locale: Locale, names: string[]): string { - return new Intl.ListFormat(locale === 'auto' ? currentDocLocale() : locale, { style: 'long', type: 'conjunction' }).format(names) -} - const MEMORY_CHOICES = [4, 6, 8, 12, 16, 24, 32, 48, 64] /** @@ -143,7 +139,7 @@ export function shortGPUName(name: string): string { } /** "1920x1080" → "1080p"; non-16:9 sizes keep "W×H". */ -export function resolutionLabel(raw: string): string { +function resolutionLabel(raw: string): string { const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(raw ?? '') if (!m) return raw const w = Number(m[1]), h = Number(m[2]) @@ -426,7 +422,7 @@ export function recommendedResolution(host: HostReport): string { return rec?.resolution ?? '1920x1080' } -export interface GuestLangPreset { +interface GuestLangPreset { value: string labelKey: I18nKey detailKey?: I18nKey @@ -472,15 +468,6 @@ export function guestLangLabel(locale: Locale, code: string | undefined): string return detail ? `${label} (${detail})` : label } -/** - * Split "简体中文(美式键盘,推荐)" / "Simplified Chinese (US Keyboard)" into a - * pop-up label and its grey detail, so the menu reads like macOS. - */ -export function splitLangLabel(value: string, text: string): { value: string; label: string; detail?: string } { - const m = /^(.*?)\s*[((](.*)[))]\s*$/.exec(text) - return m ? { value, label: m[1], detail: m[2] } : { value, label: text } -} - /** * A change saved while the VM runs, as the user would say it: * `memory 8G→16G` becomes "内存 8 GB → 16 GB". Field names come from diff --git a/frontend/src/lib/fullscreenHotkey.ts b/frontend/src/lib/fullscreenHotkey.ts index b000f9a..f63a356 100644 --- a/frontend/src/lib/fullscreenHotkey.ts +++ b/frontend/src/lib/fullscreenHotkey.ts @@ -1,13 +1,13 @@ export const DEFAULT_FULLSCREEN_HOTKEY = 'Ctrl+Shift+F' -export interface HotkeyModifiers { +interface HotkeyModifiers { ctrl: boolean shift: boolean alt: boolean win: boolean } -export interface HotkeyKeyEventLike { +interface HotkeyKeyEventLike { code?: string key?: string ctrlKey?: boolean @@ -17,15 +17,15 @@ export interface HotkeyKeyEventLike { repeat?: boolean } -export type FullscreenHotkeyErrorReason = 'unsupported' | 'needs_modifier' | 'reserved' +type FullscreenHotkeyErrorReason = 'unsupported' | 'needs_modifier' | 'reserved' -export type FullscreenHotkeyCaptureResult = +type FullscreenHotkeyCaptureResult = | { kind: 'cancel' } | { kind: 'ignore' } | { kind: 'ok'; hotkey: string } | { kind: 'error'; reason: FullscreenHotkeyErrorReason; hotkey?: string } -export type FullscreenHotkeyParseResult = +type FullscreenHotkeyParseResult = | { ok: true; hotkey: string } | { ok: false; reason: FullscreenHotkeyErrorReason | 'invalid'; hotkey?: string } @@ -100,11 +100,11 @@ const CODE_TO_KEY: Record = { ArrowRight: 'Right', } -export function isFunctionKey(key: string): boolean { +function isFunctionKey(key: string): boolean { return /^F(?:[1-9]|1[0-2])$/.test(key) } -export function isReservedFullscreenHotkey(mods: HotkeyModifiers, key: string): boolean { +function isReservedFullscreenHotkey(mods: HotkeyModifiers, key: string): boolean { return ( (mods.ctrl && mods.alt && key === 'Delete') || (mods.alt && (key === 'F4' || key === 'Tab')) || @@ -158,7 +158,7 @@ function mapEventPrimaryKey(e: HotkeyKeyEventLike): string | null { return normalizePrimaryToken(key, EVENT_KEY_ALIASES) } -export function parseFullscreenHotkey(raw: string): FullscreenHotkeyParseResult { +function parseFullscreenHotkey(raw: string): FullscreenHotkeyParseResult { const input = trimGoSpace(raw) || DEFAULT_FULLSCREEN_HOTKEY const mods: HotkeyModifiers = { ctrl: false, shift: false, alt: false, win: false } let primary = '' diff --git a/frontend/src/lib/hypervisor.ts b/frontend/src/lib/hypervisor.ts index dc5613b..3e7c0c4 100644 --- a/frontend/src/lib/hypervisor.ts +++ b/frontend/src/lib/hypervisor.ts @@ -3,7 +3,7 @@ import { I18nKey, t } from '../i18n' import { vmRefKey } from './vmRef' import type { Config, HostReport, Locale, Task, VMListItem } from '../types' -export interface HypervisorSettingsView { +interface HypervisorSettingsView { supported: boolean gateEnabled: boolean expanded: boolean @@ -18,7 +18,7 @@ export interface HypervisorSettingsView { showHVCINotice: boolean } -export interface HostWHPXSummary { +interface HostWHPXSummary { short: string hint: string tone: 'ok' | 'warn' diff --git a/frontend/src/lib/logs.ts b/frontend/src/lib/logs.ts index 0f14690..8751240 100644 --- a/frontend/src/lib/logs.ts +++ b/frontend/src/lib/logs.ts @@ -1,13 +1,13 @@ import { LogEntry } from '../types' -export type LogLevel = 'info' | 'warn' | 'error' +type LogLevel = 'info' | 'warn' | 'error' export interface LogLine extends LogEntry { id: number level: LogLevel } -export const MAX_LOG_LINES = 2000 +const MAX_LOG_LINES = 2000 // Progress no longer reaches the log: the backend turns it into tasks // (tasks.go, "reims:task"). Levels are still guessed from the text until the @@ -17,7 +17,7 @@ const WARN_RE = /\bwarn(ing)?\b/i let nextId = 1 -export function classify(entry: LogEntry): LogLine { +function classify(entry: LogEntry): LogLine { const ts = typeof entry?.ts === 'string' ? entry.ts : '' const source = typeof entry?.source === 'string' ? entry.source : '' const line = typeof entry?.line === 'string' ? entry.line : String(entry?.line ?? '') diff --git a/frontend/src/lib/optimizations.ts b/frontend/src/lib/optimizations.ts index e136beb..54f3f7b 100644 --- a/frontend/src/lib/optimizations.ts +++ b/frontend/src/lib/optimizations.ts @@ -2,7 +2,7 @@ import '../i18n/domains/settings.gen' import { I18nKey, t } from '../i18n' import { Locale, Optimization, OptimizationStatus } from '../types' -export type KernelIrqchipMode = 'auto' | 'on' | 'off' +type KernelIrqchipMode = 'auto' | 'on' | 'off' export function findOptimization(list: Optimization[] | undefined, id: string): Optimization | undefined { return (list ?? []).find((o) => o.id === id) diff --git a/frontend/src/lib/pluginViewActions.ts b/frontend/src/lib/pluginViewActions.ts index 9a449d8..1c69ee2 100644 --- a/frontend/src/lib/pluginViewActions.ts +++ b/frontend/src/lib/pluginViewActions.ts @@ -19,7 +19,7 @@ export interface PluginFormResult { values?: Record } -export interface PluginViewActionHandlers { +interface PluginViewActionHandlers { invoke(method: string, params: Record): Promise confirm(request: PluginConfirmRequest): Promise showForm(request: PluginFormRequest): Promise diff --git a/frontend/src/lib/pluginViewEvents.ts b/frontend/src/lib/pluginViewEvents.ts index ddc63b2..74095d6 100644 --- a/frontend/src/lib/pluginViewEvents.ts +++ b/frontend/src/lib/pluginViewEvents.ts @@ -1,5 +1,5 @@ -export type PluginHostEvent = 'vm.stateChanged' | 'task.updated' -export type PluginHostEventListener = (event: PluginHostEvent, data: unknown) => void +type PluginHostEvent = 'vm.stateChanged' | 'task.updated' +type PluginHostEventListener = (event: PluginHostEvent, data: unknown) => void const listeners = new Set() diff --git a/frontend/src/lib/pluginViewRouter.ts b/frontend/src/lib/pluginViewRouter.ts index b58e806..d3337ad 100644 --- a/frontend/src/lib/pluginViewRouter.ts +++ b/frontend/src/lib/pluginViewRouter.ts @@ -1,4 +1,4 @@ -export type PluginViewLocation = 'sidebar' | 'vm.tab' | 'settings' | 'dialog' +type PluginViewLocation = 'sidebar' | 'vm.tab' | 'settings' | 'dialog' export interface PluginViewRoute { pluginId: string diff --git a/frontend/src/lib/tasks.ts b/frontend/src/lib/tasks.ts index 228dbd0..f4652cc 100644 --- a/frontend/src/lib/tasks.ts +++ b/frontend/src/lib/tasks.ts @@ -93,14 +93,14 @@ export function taskInstallerKey(task: Task): string { return `${kind}:${v}` } -export function matchesOnlineInstallerTitle(title: string | undefined, target: string): boolean { +function matchesOnlineInstallerTitle(title: string | undefined, target: string): boolean { const want = target.trim().toLowerCase() if (!want) return false const norm = (title ?? '').trim().toLowerCase().replace(/^macos\s+/, '') return norm === want || norm.replace(/\s+/g, '-') === want } -export function matchesCachedInstaller(item: CachedInstaller, task: Task): boolean { +function matchesCachedInstaller(item: CachedInstaller, task: Task): boolean { if (!isActiveInstallerTask(task)) return false const kind = taskInstallerKind(task) if (!kind || kind !== item.kind) return false diff --git a/frontend/src/lib/themeEngine.ts b/frontend/src/lib/themeEngine.ts index 268b09a..e9e57d6 100644 --- a/frontend/src/lib/themeEngine.ts +++ b/frontend/src/lib/themeEngine.ts @@ -86,7 +86,7 @@ function decodeCSSEscapes(s: string): string { } /** Validates a token key+value against the UI Contract whitelist and CSS injection rules. */ -export function sanitizeTokenValue(key: string, value: string): string | null { +function sanitizeTokenValue(key: string, value: string): string | null { if (!ALLOWED_CONTRACT_TOKENS.has(key)) return null if (typeof value !== 'string') return null const trimmed = value.trim() @@ -133,7 +133,7 @@ const LAYOUT_ATTRS: Record = { const ALLOWED_LAYOUT = new Set(UI_CONTRACT_LAYOUT_OPTIONS) /** Writes the active theme's layout options as data-layout-* attributes; null clears them. */ -export function applyThemeLayout(layout: Record | null | undefined): void { +function applyThemeLayout(layout: Record | null | undefined): void { const el = document.documentElement for (const [option, attr] of Object.entries(LAYOUT_ATTRS)) { const value = layout?.[option] @@ -143,7 +143,7 @@ export function applyThemeLayout(layout: Record | null | undefi } /** Verifies stylesheet has balanced braces and no unclosed strings/comments so it cannot escape `@layer theme`. */ -export function isBalancedThemeCSS(css: string): boolean { +function isBalancedThemeCSS(css: string): boolean { if (css.toLowerCase().includes(' console.warn('[theme] sound playback failed:', eventName, e)) - } catch (e) { - console.warn('[theme] sound init failed:', eventName, e) - } -} diff --git a/frontend/src/lib/uiSdk.ts b/frontend/src/lib/uiSdk.ts index 53e27f4..2d503c9 100644 --- a/frontend/src/lib/uiSdk.ts +++ b/frontend/src/lib/uiSdk.ts @@ -8,7 +8,7 @@ import { import { hideWailsGlobals } from '../wails' import type { ThemeSDKHostActions, UIStateSnapshot } from './themeEngine' -export interface ReimsUISDK { +interface ReimsUISDK { readonly uiApi: string /** Stable host features (e.g. `slot.sidebar.footer`); feature-detect instead of comparing versions. */ readonly features: readonly string[] diff --git a/frontend/src/lib/vmRef.ts b/frontend/src/lib/vmRef.ts index b09026f..1e9916b 100644 --- a/frontend/src/lib/vmRef.ts +++ b/frontend/src/lib/vmRef.ts @@ -1,4 +1,4 @@ -export interface VMRefLike { +interface VMRefLike { name: string driver_id?: string } diff --git a/frontend/src/lib/vmStats.ts b/frontend/src/lib/vmStats.ts index 5bd0f6d..0a39599 100644 --- a/frontend/src/lib/vmStats.ts +++ b/frontend/src/lib/vmStats.ts @@ -21,14 +21,14 @@ const statsKey = (driverID: string, name: string) => `${driverID}:${name}` function sample(key: string, driverID: string, name: string, entryRef: Entry) { if (entries.get(key) !== entryRef) return const reqSeq = ++entryRef.seq - api.GetVMStatsWithDriver(driverID, name) + api.GetVMStats(driverID, name) .then((s) => { if (entries.get(key) !== entryRef || reqSeq <= entryRef.appliedSeq) return entryRef.appliedSeq = reqSeq entryRef.last = s entryRef.subs.forEach((f) => f(s)) }) - .catch((e) => console.warn('[vmStats] GetVMStatsWithDriver failed:', key, e)) + .catch((e) => console.warn('[vmStats] GetVMStats failed:', key, e)) } function schedule(key: string, driverID: string, name: string, e: Entry) { @@ -51,13 +51,12 @@ if (typeof document !== 'undefined') { } /** Latest stats seen for a VM, without subscribing (e.g. when a dialog opens). */ -export function latestVMStatsWithDriver(driverID: string, name: string | undefined | null): VMStats | null { +export function latestVMStats(driverID: string, name: string | undefined | null): VMStats | null { return name ? entries.get(statsKey(driverID, name))?.last ?? null : null } -export function latestVMStats(name: string | undefined | null): VMStats | null { return latestVMStatsWithDriver('', name) } /** Immediately patch cached stats (if any) and re-sample a VM's stats. */ -export function refreshVMStatsWithDriver(driverID: string, name: string, patch?: Partial) { +export function refreshVMStats(driverID: string, name: string, patch?: Partial) { const key = statsKey(driverID, name) const e = entries.get(key) if (!e) return @@ -68,7 +67,6 @@ export function refreshVMStatsWithDriver(driverID: string, name: string, patch?: } sample(key, driverID, name, e) } -export function refreshVMStats(name: string, patch?: Partial) { refreshVMStatsWithDriver('', name, patch) } /** Re-sample all currently subscribed VMs (e.g. after a tray-triggered state change). */ export function refreshSubscribedVMStats() { @@ -82,7 +80,7 @@ export function refreshSubscribedVMStats() { /** Live stats for one VM; `running` picks the sampling rate. Null name: none. */ export function useVMStats(driverID: string, name: string | null, running: boolean): VMStats | null { - const [stats, setStats] = useState(() => latestVMStatsWithDriver(driverID, name)) + const [stats, setStats] = useState(() => latestVMStats(driverID, name)) useEffect(() => { if (!name) { setStats(null); return } const key = statsKey(driverID, name) diff --git a/frontend/src/styles/ui-contract.ts b/frontend/src/styles/ui-contract.ts index 6661b06..04347e3 100644 --- a/frontend/src/styles/ui-contract.ts +++ b/frontend/src/styles/ui-contract.ts @@ -238,31 +238,6 @@ export const UI_CONTRACT_TOKENS = [ '--titlebar-h', '--logbar-h', '--sidebar-w', '--page-max', ] as const -export const UI_CONTRACT = { - uiApi: UI_API_VERSION, - parts: [...UI_CONTRACT_PARTS], - stateAttrs: [...UI_CONTRACT_STATE_ATTRS], - itemStates: [...UI_CONTRACT_ITEM_STATES], - slots: [...UI_CONTRACT_SLOTS], - layers: [...UI_CONTRACT_LAYERS], - layoutOptions: [...UI_CONTRACT_LAYOUT_OPTIONS], - icons: [...UI_CONTRACT_ICONS], - viewLocations: [...UI_CONTRACT_VIEW_LOCATIONS], - sdkEvents: [...UI_CONTRACT_SDK_EVENTS], - tokens: [...UI_CONTRACT_TOKENS], - experimental: { - parts: [...UI_CONTRACT_PARTS_EXPERIMENTAL], - stateAttrs: [...UI_CONTRACT_STATE_ATTRS_EXPERIMENTAL], - itemStates: [...UI_CONTRACT_ITEM_STATES_EXPERIMENTAL], - slots: [...UI_CONTRACT_SLOTS_EXPERIMENTAL], - layers: [...UI_CONTRACT_LAYERS_EXPERIMENTAL], - layoutOptions: [...UI_CONTRACT_LAYOUT_OPTIONS_EXPERIMENTAL], - icons: [...UI_CONTRACT_ICONS_EXPERIMENTAL], - viewLocations: [...UI_CONTRACT_VIEW_LOCATIONS_EXPERIMENTAL], - sdkEvents: [...UI_CONTRACT_SDK_EVENTS_EXPERIMENTAL], - }, -} - // Stable host features advertised to themes through the UI SDK. export const UI_CONTRACT_FEATURES: readonly string[] = [ ...UI_CONTRACT_SLOTS.map((s) => `slot.${s}`), diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 41e32ed..34c0b98 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -16,11 +16,9 @@ export type Config = Model & { export type DisplayInfo = host.DisplayInfo export type DisplayPreset = host.DisplayPreset -export type AudioInfo = host.AudioInfo -export type WHPXCapabilities = host.WHPXCapabilities export type LogicalCPUInfo = host.LogicalCPUInfo -export type GPUCompat = 'supported' | 'warn' | 'unsupported' | 'unknown' +type GPUCompat = 'supported' | 'warn' | 'unsupported' | 'unknown' export type GPUInfo = Omit, 'compat'> & { kind: 'discrete' | 'integrated' | 'virtual' | 'unknown' @@ -41,16 +39,15 @@ export type HostReport = Omit, 'gpus' | 'recommended_gpu'> & recommended_gpu?: GPUInfo } -export type RuntimeManifest = Model export type InstalledRuntime = Model export type RemoteRuntime = Model & { channel: 'stable' | 'alpha' } -export type VMState = 'running' | 'stopped' | 'suspended' | 'broken' | 'driver_unavailable' -export type VMPhase = 'normal' | 'installer' | 'recovery' -export type GuestOSInfo = Model +type VMState = 'running' | 'stopped' | 'suspended' | 'broken' | 'driver_unavailable' +type VMPhase = 'normal' | 'installer' | 'recovery' +type GuestOSInfo = Model export type VMEndpoint = Model & { kind: 'ssh' | 'wsl' | 'rdp' | 'vmconnect' | 'adb' | (string & {}) } @@ -83,7 +80,6 @@ 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 @@ -126,7 +122,7 @@ export type CreateOpts = Model & { displays: number } -export type TaskStatus = 'running' | 'done' | 'failed' | 'canceled' +type TaskStatus = 'running' | 'done' | 'failed' | 'canceled' export type InstallerKind = 'offline' | 'online' export type InstallerPhase = 'queued' | 'downloading' @@ -155,23 +151,15 @@ export type PermissionSpec = plugin.PermissionSpec export type SettingProperty = plugin.SettingProperty export type SettingsSchema = plugin.SettingsSchema export type PluginInfo = plugin.PluginInfo -export type DoctorFinding = plugin.DoctorFinding -export type ScanFinding = plugin.ScanFinding -export type ExecutableFile = plugin.ExecutableFile -export type CapabilityItem = plugin.CapabilityItem export type ScanReport = plugin.ScanReport -export type MarketEntry = plugin.MarketEntry -export type MarketWithdrawal = plugin.MarketWithdrawal export type MarketCatalogItem = plugin.MarketCatalogItem export type MarketBrowseResult = plugin.MarketBrowseResult export type TokenDeriveRule = plugin.TokenDeriveRule -export type ThemeScheme = plugin.ThemeScheme export type ThemeDecoration = plugin.ThemeDecoration export type ThemeDecorationState = plugin.ThemeDecorationState -export type ThemeContribution = plugin.ThemeContribution export type CustomThemeScheme = plugin.CustomThemeScheme export type ActiveThemePayload = plugin.ActiveThemePayload -export interface ResolvedLocaleFont { +interface ResolvedLocaleFont { family: string url: string weight?: string @@ -184,15 +172,11 @@ export type ResolvedLocalePack = Model & { plugin_messages?: Record> fonts?: ResolvedLocaleFont[] } -export type MenuContribution = plugin.MenuContribution -export type VMCardContribution = plugin.VMCardContribution export type PanelContribution = plugin.PanelContribution export type ViewContribution = plugin.ViewContribution export type ImageSourceContribution = plugin.ImageSourceContribution -export type StatusItemContribution = plugin.StatusItemContribution export type PluginUIContributions = app.PluginUIContributions export type DriverSummary = driver.DriverSummary -export type DriverCreateRequest = driver.CreateRequest export type RuntimeKindSpec = runtime.KindSpec /** A "reims:log" event (internal/app/app.go emitLog); not a Go struct, so not generated. */ diff --git a/frontend/src/ui/controls.tsx b/frontend/src/ui/controls.tsx index f9ca694..83c409e 100644 --- a/frontend/src/ui/controls.tsx +++ b/frontend/src/ui/controls.tsx @@ -92,7 +92,7 @@ export const IconButton = React.forwardRef( ) IconButton.displayName = 'IconButton' -export type StatusKind = 'running' | 'stopped' | 'suspended' | 'busy' | 'broken' | 'warn' +type StatusKind = 'running' | 'stopped' | 'suspended' | 'busy' | 'broken' | 'warn' export function statusKind(state: string): StatusKind { if (state === 'running') return 'running' diff --git a/frontend/src/ui/settings.tsx b/frontend/src/ui/settings.tsx index 9bf8718..557095d 100644 --- a/frontend/src/ui/settings.tsx +++ b/frontend/src/ui/settings.tsx @@ -89,7 +89,7 @@ export const Switch: React.FC<{ checked: boolean; onChange: (v: boolean) => void ) -export interface SegOption { +interface SegOption { value: V label: string disabled?: boolean @@ -247,7 +247,7 @@ function thinMarks(marks: RangeMark[], min: number, max: number, gap = 9): Range return out } -export interface RangeMark { +interface RangeMark { value: number label: string } @@ -326,7 +326,7 @@ export const RangeField: React.FC = ({ value, min, max, step = 1, un ) } -export interface CardOption { +interface CardOption { value: V title: string sub?: string @@ -362,7 +362,7 @@ export function OptionCards({ options, value, onChange, label, ) } -export interface PopupOption { +interface PopupOption { value: V label: string /** Secondary text drawn after the label in grey, e.g. a build number. */ diff --git a/frontend/src/ui/themeVisuals.tsx b/frontend/src/ui/themeVisuals.tsx index 9d3edbd..f82a6ab 100644 --- a/frontend/src/ui/themeVisuals.tsx +++ b/frontend/src/ui/themeVisuals.tsx @@ -13,7 +13,7 @@ const DEFAULT_BRAND_MARK = '/logo.svg' const KNOWN_ICONS = new Set(UI_CONTRACT_ICONS) const KNOWN_TARGETS = new Set([...UI_CONTRACT_SLOTS, ...UI_CONTRACT_LAYERS]) -export interface ThemeVisuals { +interface ThemeVisuals { brandMarkURL: string icons: Partial> } @@ -25,7 +25,7 @@ function isBuiltin(payload: ActiveThemePayload | null): boolean { return !payload?.theme || payload.theme_id === 'builtin.theme.default' } -export function resolveThemeVisuals(payload: ActiveThemePayload | null): ThemeVisuals { +function resolveThemeVisuals(payload: ActiveThemePayload | null): ThemeVisuals { if (isBuiltin(payload)) return EMPTY const th = payload!.theme! const icons: Partial> = {} @@ -41,7 +41,7 @@ export const ThemeVisualsProvider: React.FC<{ payload: ActiveThemePayload | null return {children} } -export function useThemeVisuals(): ThemeVisuals { +function useThemeVisuals(): ThemeVisuals { return useContext(ThemeVisualsContext) } diff --git a/frontend/src/ui/toast.tsx b/frontend/src/ui/toast.tsx index 56cadc0..7a88bb4 100644 --- a/frontend/src/ui/toast.tsx +++ b/frontend/src/ui/toast.tsx @@ -16,7 +16,7 @@ export interface ToastInput { action?: { label: string; onClick: () => void } } -export interface ToastItem extends ToastInput { +interface ToastItem extends ToastInput { id: number } diff --git a/frontend/src/wails.ts b/frontend/src/wails.ts index 3597729..249b8eb 100644 --- a/frontend/src/wails.ts +++ b/frontend/src/wails.ts @@ -155,10 +155,8 @@ export const api = { InstallNpcap: boundGo.InstallNpcap as () => Promise, GetState: boundGo.GetState as () => Promise, GetTasks: boundGo.GetTasks as () => Promise, - GetVMAffinity: boundGo.GetVMAffinity as (name: string) => Promise, - SetVMAffinity: boundGo.SetVMAffinity as (name: string, req: VMAffinityUpdate) => Promise, - GetVMAffinityWithDriver: boundGo.GetVMAffinityWithDriver as (driverID: string, name: string) => Promise, - SetVMAffinityWithDriver: boundGo.SetVMAffinityWithDriver as (driverID: string, name: string, req: VMAffinityUpdate) => Promise, + GetVMAffinity: boundGo.GetVMAffinity as (driverID: string, name: string) => Promise, + SetVMAffinity: boundGo.SetVMAffinity as (driverID: string, name: string, req: VMAffinityUpdate) => Promise, GetVMKeymap: boundGo.GetVMKeymap as (name: string) => Promise, GetVMInfo: boundGo.GetVMInfo as (driverID: string, name: string) => Promise, SetVMKeymap: boundGo.SetVMKeymap as (name: string, req: VMKeymapUpdate) => Promise, diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json index 42650fe..14e5242 100644 --- a/frontend/tsconfig.json +++ b/frontend/tsconfig.json @@ -11,7 +11,9 @@ "moduleDetection": "force", "noEmit": true, "jsx": "react-jsx", - "strict": true + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true }, "include": ["src"] } diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index a6eacb3..72eb1a9 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -34,23 +34,15 @@ export function CheckAppUpdate(arg1:boolean):Promise; export function CheckDataRoot(arg1:string):Promise; -export function CloneVMCoW(arg1:string,arg2:string):Promise; +export function CloneVMCoW(arg1:string,arg2:string,arg3:string):Promise; -export function CloneVMCoWWithDriver(arg1:string,arg2:string,arg3:string):Promise; - -export function CompactVMDisk(arg1:string):Promise; - -export function CompactVMDiskWithDriver(arg1:string,arg2:string):Promise; +export function CompactVMDisk(arg1:string,arg2:string):Promise; export function CompleteSetup(arg1:string):Promise; -export function CopyVMScreenshot(arg1:string):Promise; +export function CopyVMScreenshot(arg1:string,arg2:string):Promise; -export function CopyVMScreenshotWithDriver(arg1:string,arg2:string):Promise; - -export function CreateSnapshot(arg1:string,arg2:string):Promise; - -export function CreateSnapshotWithDriver(arg1:string,arg2:string,arg3:string):Promise; +export function CreateSnapshot(arg1:string,arg2:string,arg3:string):Promise; export function CreateVM(arg1:reims.CreateOpts):Promise; @@ -60,13 +52,9 @@ export function DeleteCustomThemeScheme(arg1:string):Promise; export function DeleteInstaller(arg1:string):Promise; -export function DeleteSnapshot(arg1:string,arg2:string):Promise; +export function DeleteSnapshot(arg1:string,arg2:string,arg3:string):Promise; -export function DeleteSnapshotWithDriver(arg1:string,arg2:string,arg3:string):Promise; - -export function DeleteVM(arg1:string,arg2:boolean):Promise; - -export function DeleteVMWithDriver(arg1:string,arg2:string,arg3:boolean):Promise; +export function DeleteVM(arg1:string,arg2:string,arg3:boolean):Promise; export function DeliverFileToGuest(arg1:string):Promise; @@ -76,13 +64,7 @@ export function DetachGuestTools(arg1:string):Promise; export function DisablePlugin(arg1:string):Promise; -export function DiscardSuspend(arg1:string):Promise; - -export function DiscardSuspendWithDriver(arg1:string,arg2:string):Promise; - -export function DismissTask(arg1:string):Promise; - -export function DoctorPlugin(arg1:string):Promise>; +export function DiscardSuspend(arg1:string,arg2:string):Promise; export function DownloadAndAttachOnlineRecovery(arg1:string,arg2:string):Promise; @@ -90,25 +72,17 @@ export function DownloadAppUpdate():Promise; export function DownloadInstaller(arg1:string):Promise; -export function EjectInstaller(arg1:string):Promise; - -export function EjectInstallerWithDriver(arg1:string,arg2:string):Promise; +export function EjectInstaller(arg1:string,arg2:string):Promise; export function EnablePlugin(arg1:string,arg2:boolean):Promise; -export function EnableWHPX():Promise; - export function EnterRecovery(arg1:string):Promise; -export function ExportDiagnostics(arg1:string):Promise; - -export function ExportDiagnosticsWithDriver(arg1:string,arg2:string):Promise; +export function ExportDiagnostics(arg1:string,arg2:string):Promise; export function FinishInstall(arg1:string):Promise; -export function FocusVMWindow(arg1:string):Promise; - -export function FocusVMWindowWithDriver(arg1:string,arg2:string):Promise; +export function FocusVMWindow(arg1:string,arg2:string):Promise; export function ForceQuitApp():Promise; @@ -136,17 +110,16 @@ export function GetStorageBreakdown():Promise; export function GetTasks():Promise>; -export function GetVMAffinity(arg1:string):Promise; - -export function GetVMAffinityWithDriver(arg1:string,arg2:string):Promise; +export function GetVMAffinity(arg1:string,arg2:string):Promise; export function GetVMDetail(arg1:string):Promise; -export function GetVMDisplayWithDriver(arg1:string,arg2:string):Promise; +export function GetVMDisplay(arg1:string,arg2:string):Promise; export function GetVMDriveShareSettings(arg1:string):Promise; -export function GetVMEndpointCommandWithDriver(arg1:string,arg2:string,arg3:string):Promise; +export function GetVMEndpointCommand(arg1:string,arg2:string,arg3:string):Promise; + export function GetVMInfo(arg1:string,arg2:string):Promise; export function GetVMKeymap(arg1:string):Promise; @@ -157,30 +130,21 @@ export function GetVMNetworkPlan(arg1:string,arg2:string,arg3:string):Promise; -export function GetVMNote(arg1:string):Promise; -export function GetVMNoteWithDriver(arg1:string,arg2:string):Promise; +export function GetVMNote(arg1:string,arg2:string):Promise; export function GetVMPluginSettings(arg1:string):Promise>>; export function GetVMSMBIOS(arg1:string):Promise; -export function GetVMSSHUser(arg1:string):Promise; - -export function GetVMSSHUserWithDriver(arg1:string,arg2:string):Promise; +export function GetVMSSHUser(arg1:string,arg2:string):Promise; export function GetVMSharedFolderSettings(arg1:string):Promise; -export function GetVMStats(arg1:string):Promise; +export function GetVMStats(arg1:string,arg2:string):Promise; -export function GetVMStatsWithDriver(arg1:string,arg2:string):Promise; +export function GetVMThumbnail(arg1:string,arg2:string):Promise; -export function GetVMThumbnail(arg1:string):Promise; - -export function GetVMThumbnailWithDriver(arg1:string,arg2:string):Promise; - -export function GetVMTimezone(arg1:string):Promise; - -export function GetVMTimezoneWithDriver(arg1:string,arg2:string):Promise; +export function GetVMTimezone(arg1:string,arg2:string):Promise; export function InspectPluginArchive(arg1:string):Promise; @@ -214,36 +178,29 @@ export function ListRemoteRuntimes():Promise>; export function ListRuntimeKinds():Promise>; -export function ListSnapshots(arg1:string):Promise>; - -export function ListSnapshotsWithDriver(arg1:string,arg2:string):Promise>; +export function ListSnapshots(arg1:string,arg2:string):Promise>; export function OpenProcessorScheduling():Promise; export function OpenQQGroup():Promise; -export function OpenSSHTerminal(arg1:string,arg2:string):Promise; - -export function OpenSSHTerminalWithDriver(arg1:string,arg2:string,arg3:string):Promise; +export function OpenSSHTerminal(arg1:string,arg2:string,arg3:string):Promise; export function OpenSharedFolder(arg1:string):Promise; export function OpenURL(arg1:string):Promise; -export function OpenVMEndpointWithDriver(arg1:string,arg2:string,arg3:string,arg4:string):Promise; +export function OpenVMEndpoint(arg1:string,arg2:string,arg3:string,arg4:string):Promise; + export function OpenVMFolder(arg1:string):Promise; -export function OpenVSCodeSSH(arg1:string,arg2:string):Promise; - -export function OpenVSCodeSSHWithDriver(arg1:string,arg2:string,arg3:string):Promise; +export function OpenVSCodeSSH(arg1:string,arg2:string,arg3:string):Promise; export function OpenWindowsCoreIsolation():Promise; export function OpenWindowsSecurityExclusions():Promise; -export function OptimizeVMDisk(arg1:string):Promise; - -export function OptimizeVMDiskWithDriver(arg1:string,arg2:string):Promise; +export function OptimizeVMDisk(arg1:string,arg2:string):Promise; export function PanelBridgeCall(arg1:string,arg2:string,arg3:Record):Promise; @@ -261,9 +218,7 @@ export function QuitApp():Promise; export function ReadPluginLog(arg1:string):Promise; -export function ReadVMLogs(arg1:string,arg2:boolean):Promise; - -export function ReadVMLogsWithDriver(arg1:string,arg2:string,arg3:boolean):Promise; +export function ReadVMLogs(arg1:string,arg2:string,arg3:boolean):Promise; export function RemovePlugin(arg1:string,arg2:boolean):Promise; @@ -275,23 +230,15 @@ export function ReopenDataRoot(arg1:boolean):Promise; export function RequestClose():Promise; -export function ResizeVMDisk(arg1:string,arg2:string):Promise; - -export function ResizeVMDiskWithDriver(arg1:string,arg2:string,arg3:string):Promise; +export function ResizeVMDisk(arg1:string,arg2:string,arg3:string):Promise; export function ResolveElevationRequest(arg1:string,arg2:boolean):Promise; -export function RestartVM(arg1:string):Promise; +export function RestartVM(arg1:string,arg2:string):Promise; -export function RestartVMWithDriver(arg1:string,arg2:string):Promise; +export function RestoreSnapshot(arg1:string,arg2:string,arg3:string):Promise; -export function RestoreSnapshot(arg1:string,arg2:string):Promise; - -export function RestoreSnapshotWithDriver(arg1:string,arg2:string,arg3:string):Promise; - -export function ResumeVM(arg1:string):Promise; - -export function ResumeVMWithDriver(arg1:string,arg2:string):Promise; +export function ResumeVM(arg1:string,arg2:string):Promise; export function SaveCustomThemeScheme(arg1:plugin.CustomThemeScheme):Promise; @@ -327,62 +274,41 @@ export function SetRuntimeChannel(arg1:string):Promise; export function SetSyncHostMemorySMBIOS(arg1:boolean):Promise; -export function SetVMAffinity(arg1:string,arg2:app.VMAffinityUpdate):Promise; +export function SetVMAffinity(arg1:string,arg2:string,arg3:app.VMAffinityUpdate):Promise; -export function SetVMAffinityWithDriver(arg1:string,arg2:string,arg3:app.VMAffinityUpdate):Promise; - -export function SetVMDisplayWithDriver(arg1:string,arg2:string,arg3:string):Promise; +export function SetVMDisplay(arg1:string,arg2:string,arg3:string):Promise; export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array):Promise; export function SetVMKeymap(arg1:string,arg2:app.VMKeymapUpdate):Promise; -export function SetVMNote(arg1:string,arg2:string):Promise; -export function SetVMNoteWithDriver(arg1:string,arg2:string,arg3:string):Promise; +export function SetVMNote(arg1:string,arg2:string,arg3:string):Promise; -export function SetVMSSHUser(arg1:string,arg2:string):Promise; - -export function SetVMSSHUserWithDriver(arg1:string,arg2:string,arg3:string):Promise; +export function SetVMSSHUser(arg1:string,arg2:string,arg3:string):Promise; export function SetVMSharedFolderMode(arg1:string,arg2:string,arg3:string):Promise; -export function SetVMTimezone(arg1:string,arg2:string):Promise; +export function SetVMTimezone(arg1:string,arg2:string,arg3:string):Promise; -export function SetVMTimezoneWithDriver(arg1:string,arg2:string,arg3:string):Promise; +export function StartVM(arg1:string,arg2:string):Promise; -export function ShowMainWindow():Promise; - -export function StartVM(arg1:string):Promise; - -export function StartVMWithDriver(arg1:string,arg2:string):Promise; - -export function StopVM(arg1:string,arg2:boolean):Promise; - -export function StopVMWithDriver(arg1:string,arg2:string,arg3:boolean):Promise; +export function StopVM(arg1:string,arg2:string,arg3:boolean):Promise; export function SuggestDataRoots():Promise>; export function SuggestLanguagePack():Promise; -export function SuspendVM(arg1:string):Promise; - -export function SuspendVMWithDriver(arg1:string,arg2:string):Promise; +export function SuspendVM(arg1:string,arg2:string):Promise; export function TestHostDNS(arg1:guesttools.HostDNSConfig):Promise; export function ToggleBorderless(arg1:string,arg2:boolean):Promise; -export function ToggleVMFullscreen(arg1:string):Promise; +export function ToggleVMFullscreen(arg1:string,arg2:string):Promise; -export function ToggleVMFullscreenWithDriver(arg1:string,arg2:string):Promise; +export function TypeClipboard(arg1:string,arg2:string):Promise; -export function TypeClipboard(arg1:string):Promise; - -export function TypeClipboardWithDriver(arg1:string,arg2:string):Promise; - -export function TypeText(arg1:string,arg2:string):Promise; - -export function TypeTextWithDriver(arg1:string,arg2:string,arg3:string):Promise; +export function TypeText(arg1:string,arg2:string,arg3:string):Promise; export function UpgradeDiskToNVMe(arg1:string):Promise; @@ -392,6 +318,4 @@ export function ValidateCreate(arg1:reims.CreateOpts):Promise>; -export function WriteSSHConfig(arg1:string,arg2:string):Promise; - -export function WriteSSHConfigWithDriver(arg1:string,arg2:string,arg3:string):Promise; +export function WriteSSHConfig(arg1:string,arg2:string,arg3:string):Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index c003f0e..878fded 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -46,40 +46,24 @@ export function CheckDataRoot(arg1) { return window['go']['app']['App']['CheckDataRoot'](arg1); } -export function CloneVMCoW(arg1, arg2) { - return window['go']['app']['App']['CloneVMCoW'](arg1, arg2); +export function CloneVMCoW(arg1, arg2, arg3) { + return window['go']['app']['App']['CloneVMCoW'](arg1, arg2, arg3); } -export function CloneVMCoWWithDriver(arg1, arg2, arg3) { - return window['go']['app']['App']['CloneVMCoWWithDriver'](arg1, arg2, arg3); -} - -export function CompactVMDisk(arg1) { - return window['go']['app']['App']['CompactVMDisk'](arg1); -} - -export function CompactVMDiskWithDriver(arg1, arg2) { - return window['go']['app']['App']['CompactVMDiskWithDriver'](arg1, arg2); +export function CompactVMDisk(arg1, arg2) { + return window['go']['app']['App']['CompactVMDisk'](arg1, arg2); } export function CompleteSetup(arg1) { return window['go']['app']['App']['CompleteSetup'](arg1); } -export function CopyVMScreenshot(arg1) { - return window['go']['app']['App']['CopyVMScreenshot'](arg1); +export function CopyVMScreenshot(arg1, arg2) { + return window['go']['app']['App']['CopyVMScreenshot'](arg1, arg2); } -export function CopyVMScreenshotWithDriver(arg1, arg2) { - return window['go']['app']['App']['CopyVMScreenshotWithDriver'](arg1, arg2); -} - -export function CreateSnapshot(arg1, arg2) { - return window['go']['app']['App']['CreateSnapshot'](arg1, arg2); -} - -export function CreateSnapshotWithDriver(arg1, arg2, arg3) { - return window['go']['app']['App']['CreateSnapshotWithDriver'](arg1, arg2, arg3); +export function CreateSnapshot(arg1, arg2, arg3) { + return window['go']['app']['App']['CreateSnapshot'](arg1, arg2, arg3); } export function CreateVM(arg1) { @@ -98,20 +82,12 @@ export function DeleteInstaller(arg1) { return window['go']['app']['App']['DeleteInstaller'](arg1); } -export function DeleteSnapshot(arg1, arg2) { - return window['go']['app']['App']['DeleteSnapshot'](arg1, arg2); +export function DeleteSnapshot(arg1, arg2, arg3) { + return window['go']['app']['App']['DeleteSnapshot'](arg1, arg2, arg3); } -export function DeleteSnapshotWithDriver(arg1, arg2, arg3) { - return window['go']['app']['App']['DeleteSnapshotWithDriver'](arg1, arg2, arg3); -} - -export function DeleteVM(arg1, arg2) { - return window['go']['app']['App']['DeleteVM'](arg1, arg2); -} - -export function DeleteVMWithDriver(arg1, arg2, arg3) { - return window['go']['app']['App']['DeleteVMWithDriver'](arg1, arg2, arg3); +export function DeleteVM(arg1, arg2, arg3) { + return window['go']['app']['App']['DeleteVM'](arg1, arg2, arg3); } export function DeliverFileToGuest(arg1) { @@ -130,20 +106,8 @@ export function DisablePlugin(arg1) { return window['go']['app']['App']['DisablePlugin'](arg1); } -export function DiscardSuspend(arg1) { - return window['go']['app']['App']['DiscardSuspend'](arg1); -} - -export function DiscardSuspendWithDriver(arg1, arg2) { - return window['go']['app']['App']['DiscardSuspendWithDriver'](arg1, arg2); -} - -export function DismissTask(arg1) { - return window['go']['app']['App']['DismissTask'](arg1); -} - -export function DoctorPlugin(arg1) { - return window['go']['app']['App']['DoctorPlugin'](arg1); +export function DiscardSuspend(arg1, arg2) { + return window['go']['app']['App']['DiscardSuspend'](arg1, arg2); } export function DownloadAndAttachOnlineRecovery(arg1, arg2) { @@ -158,44 +122,28 @@ export function DownloadInstaller(arg1) { return window['go']['app']['App']['DownloadInstaller'](arg1); } -export function EjectInstaller(arg1) { - return window['go']['app']['App']['EjectInstaller'](arg1); -} - -export function EjectInstallerWithDriver(arg1, arg2) { - return window['go']['app']['App']['EjectInstallerWithDriver'](arg1, arg2); +export function EjectInstaller(arg1, arg2) { + return window['go']['app']['App']['EjectInstaller'](arg1, arg2); } export function EnablePlugin(arg1, arg2) { return window['go']['app']['App']['EnablePlugin'](arg1, arg2); } -export function EnableWHPX() { - return window['go']['app']['App']['EnableWHPX'](); -} - export function EnterRecovery(arg1) { return window['go']['app']['App']['EnterRecovery'](arg1); } -export function ExportDiagnostics(arg1) { - return window['go']['app']['App']['ExportDiagnostics'](arg1); -} - -export function ExportDiagnosticsWithDriver(arg1, arg2) { - return window['go']['app']['App']['ExportDiagnosticsWithDriver'](arg1, arg2); +export function ExportDiagnostics(arg1, arg2) { + return window['go']['app']['App']['ExportDiagnostics'](arg1, arg2); } export function FinishInstall(arg1) { return window['go']['app']['App']['FinishInstall'](arg1); } -export function FocusVMWindow(arg1) { - return window['go']['app']['App']['FocusVMWindow'](arg1); -} - -export function FocusVMWindowWithDriver(arg1, arg2) { - return window['go']['app']['App']['FocusVMWindowWithDriver'](arg1, arg2); +export function FocusVMWindow(arg1, arg2) { + return window['go']['app']['App']['FocusVMWindow'](arg1, arg2); } export function ForceQuitApp() { @@ -250,28 +198,24 @@ export function GetTasks() { return window['go']['app']['App']['GetTasks'](); } -export function GetVMAffinity(arg1) { - return window['go']['app']['App']['GetVMAffinity'](arg1); -} - -export function GetVMAffinityWithDriver(arg1, arg2) { - return window['go']['app']['App']['GetVMAffinityWithDriver'](arg1, arg2); +export function GetVMAffinity(arg1, arg2) { + return window['go']['app']['App']['GetVMAffinity'](arg1, arg2); } export function GetVMDetail(arg1) { return window['go']['app']['App']['GetVMDetail'](arg1); } -export function GetVMDisplayWithDriver(arg1, arg2) { - return window['go']['app']['App']['GetVMDisplayWithDriver'](arg1, arg2); +export function GetVMDisplay(arg1, arg2) { + return window['go']['app']['App']['GetVMDisplay'](arg1, arg2); } export function GetVMDriveShareSettings(arg1) { return window['go']['app']['App']['GetVMDriveShareSettings'](arg1); } -export function GetVMEndpointCommandWithDriver(arg1, arg2, arg3) { - return window['go']['app']['App']['GetVMEndpointCommandWithDriver'](arg1, arg2, arg3); +export function GetVMEndpointCommand(arg1, arg2, arg3) { + return window['go']['app']['App']['GetVMEndpointCommand'](arg1, arg2, arg3); } export function GetVMInfo(arg1, arg2) { @@ -294,8 +238,8 @@ export function GetVMNetworkSettings(arg1) { return window['go']['app']['App']['GetVMNetworkSettings'](arg1); } -export function GetVMNote(arg1) { - return window['go']['app']['App']['GetVMNote'](arg1); +export function GetVMNote(arg1, arg2) { + return window['go']['app']['App']['GetVMNote'](arg1, arg2); } export function GetVMPluginSettings(arg1) { @@ -306,44 +250,24 @@ export function GetVMSMBIOS(arg1) { return window['go']['app']['App']['GetVMSMBIOS'](arg1); } -export function GetVMNoteWithDriver(arg1, arg2) { - return window['go']['app']['App']['GetVMNoteWithDriver'](arg1, arg2); -} - -export function GetVMSSHUser(arg1) { - return window['go']['app']['App']['GetVMSSHUser'](arg1); -} - -export function GetVMSSHUserWithDriver(arg1, arg2) { - return window['go']['app']['App']['GetVMSSHUserWithDriver'](arg1, arg2); +export function GetVMSSHUser(arg1, arg2) { + return window['go']['app']['App']['GetVMSSHUser'](arg1, arg2); } export function GetVMSharedFolderSettings(arg1) { return window['go']['app']['App']['GetVMSharedFolderSettings'](arg1); } -export function GetVMStats(arg1) { - return window['go']['app']['App']['GetVMStats'](arg1); +export function GetVMStats(arg1, arg2) { + return window['go']['app']['App']['GetVMStats'](arg1, arg2); } -export function GetVMStatsWithDriver(arg1, arg2) { - return window['go']['app']['App']['GetVMStatsWithDriver'](arg1, arg2); +export function GetVMThumbnail(arg1, arg2) { + return window['go']['app']['App']['GetVMThumbnail'](arg1, arg2); } -export function GetVMThumbnail(arg1) { - return window['go']['app']['App']['GetVMThumbnail'](arg1); -} - -export function GetVMThumbnailWithDriver(arg1, arg2) { - return window['go']['app']['App']['GetVMThumbnailWithDriver'](arg1, arg2); -} - -export function GetVMTimezone(arg1) { - return window['go']['app']['App']['GetVMTimezone'](arg1); -} - -export function GetVMTimezoneWithDriver(arg1, arg2) { - return window['go']['app']['App']['GetVMTimezoneWithDriver'](arg1, arg2); +export function GetVMTimezone(arg1, arg2) { + return window['go']['app']['App']['GetVMTimezone'](arg1, arg2); } export function InspectPluginArchive(arg1) { @@ -410,12 +334,8 @@ export function ListRuntimeKinds() { return window['go']['app']['App']['ListRuntimeKinds'](); } -export function ListSnapshots(arg1) { - return window['go']['app']['App']['ListSnapshots'](arg1); -} - -export function ListSnapshotsWithDriver(arg1, arg2) { - return window['go']['app']['App']['ListSnapshotsWithDriver'](arg1, arg2); +export function ListSnapshots(arg1, arg2) { + return window['go']['app']['App']['ListSnapshots'](arg1, arg2); } export function OpenProcessorScheduling() { @@ -426,12 +346,8 @@ export function OpenQQGroup() { return window['go']['app']['App']['OpenQQGroup'](); } -export function OpenSSHTerminal(arg1, arg2) { - return window['go']['app']['App']['OpenSSHTerminal'](arg1, arg2); -} - -export function OpenSSHTerminalWithDriver(arg1, arg2, arg3) { - return window['go']['app']['App']['OpenSSHTerminalWithDriver'](arg1, arg2, arg3); +export function OpenSSHTerminal(arg1, arg2, arg3) { + return window['go']['app']['App']['OpenSSHTerminal'](arg1, arg2, arg3); } export function OpenSharedFolder(arg1) { @@ -442,20 +358,16 @@ export function OpenURL(arg1) { return window['go']['app']['App']['OpenURL'](arg1); } -export function OpenVMEndpointWithDriver(arg1, arg2, arg3, arg4) { - return window['go']['app']['App']['OpenVMEndpointWithDriver'](arg1, arg2, arg3, arg4); +export function OpenVMEndpoint(arg1, arg2, arg3, arg4) { + return window['go']['app']['App']['OpenVMEndpoint'](arg1, arg2, arg3, arg4); } export function OpenVMFolder(arg1) { return window['go']['app']['App']['OpenVMFolder'](arg1); } -export function OpenVSCodeSSH(arg1, arg2) { - return window['go']['app']['App']['OpenVSCodeSSH'](arg1, arg2); -} - -export function OpenVSCodeSSHWithDriver(arg1, arg2, arg3) { - return window['go']['app']['App']['OpenVSCodeSSHWithDriver'](arg1, arg2, arg3); +export function OpenVSCodeSSH(arg1, arg2, arg3) { + return window['go']['app']['App']['OpenVSCodeSSH'](arg1, arg2, arg3); } export function OpenWindowsCoreIsolation() { @@ -466,12 +378,8 @@ export function OpenWindowsSecurityExclusions() { return window['go']['app']['App']['OpenWindowsSecurityExclusions'](); } -export function OptimizeVMDisk(arg1) { - return window['go']['app']['App']['OptimizeVMDisk'](arg1); -} - -export function OptimizeVMDiskWithDriver(arg1, arg2) { - return window['go']['app']['App']['OptimizeVMDiskWithDriver'](arg1, arg2); +export function OptimizeVMDisk(arg1, arg2) { + return window['go']['app']['App']['OptimizeVMDisk'](arg1, arg2); } export function PanelBridgeCall(arg1, arg2, arg3) { @@ -506,12 +414,8 @@ export function ReadPluginLog(arg1) { return window['go']['app']['App']['ReadPluginLog'](arg1); } -export function ReadVMLogs(arg1, arg2) { - return window['go']['app']['App']['ReadVMLogs'](arg1, arg2); -} - -export function ReadVMLogsWithDriver(arg1, arg2, arg3) { - return window['go']['app']['App']['ReadVMLogsWithDriver'](arg1, arg2, arg3); +export function ReadVMLogs(arg1, arg2, arg3) { + return window['go']['app']['App']['ReadVMLogs'](arg1, arg2, arg3); } export function RemovePlugin(arg1, arg2) { @@ -534,40 +438,24 @@ export function RequestClose() { return window['go']['app']['App']['RequestClose'](); } -export function ResizeVMDisk(arg1, arg2) { - return window['go']['app']['App']['ResizeVMDisk'](arg1, arg2); -} - -export function ResizeVMDiskWithDriver(arg1, arg2, arg3) { - return window['go']['app']['App']['ResizeVMDiskWithDriver'](arg1, arg2, arg3); +export function ResizeVMDisk(arg1, arg2, arg3) { + return window['go']['app']['App']['ResizeVMDisk'](arg1, arg2, arg3); } export function ResolveElevationRequest(arg1, arg2) { return window['go']['app']['App']['ResolveElevationRequest'](arg1, arg2); } -export function RestartVM(arg1) { - return window['go']['app']['App']['RestartVM'](arg1); +export function RestartVM(arg1, arg2) { + return window['go']['app']['App']['RestartVM'](arg1, arg2); } -export function RestartVMWithDriver(arg1, arg2) { - return window['go']['app']['App']['RestartVMWithDriver'](arg1, arg2); +export function RestoreSnapshot(arg1, arg2, arg3) { + return window['go']['app']['App']['RestoreSnapshot'](arg1, arg2, arg3); } -export function RestoreSnapshot(arg1, arg2) { - return window['go']['app']['App']['RestoreSnapshot'](arg1, arg2); -} - -export function RestoreSnapshotWithDriver(arg1, arg2, arg3) { - return window['go']['app']['App']['RestoreSnapshotWithDriver'](arg1, arg2, arg3); -} - -export function ResumeVM(arg1) { - return window['go']['app']['App']['ResumeVM'](arg1); -} - -export function ResumeVMWithDriver(arg1, arg2) { - return window['go']['app']['App']['ResumeVMWithDriver'](arg1, arg2); +export function ResumeVM(arg1, arg2) { + return window['go']['app']['App']['ResumeVM'](arg1, arg2); } export function SaveCustomThemeScheme(arg1) { @@ -638,16 +526,12 @@ export function SetSyncHostMemorySMBIOS(arg1) { return window['go']['app']['App']['SetSyncHostMemorySMBIOS'](arg1); } -export function SetVMAffinity(arg1, arg2) { - return window['go']['app']['App']['SetVMAffinity'](arg1, arg2); +export function SetVMAffinity(arg1, arg2, arg3) { + return window['go']['app']['App']['SetVMAffinity'](arg1, arg2, arg3); } -export function SetVMAffinityWithDriver(arg1, arg2, arg3) { - return window['go']['app']['App']['SetVMAffinityWithDriver'](arg1, arg2, arg3); -} - -export function SetVMDisplayWithDriver(arg1, arg2, arg3) { - return window['go']['app']['App']['SetVMDisplayWithDriver'](arg1, arg2, arg3); +export function SetVMDisplay(arg1, arg2, arg3) { + return window['go']['app']['App']['SetVMDisplay'](arg1, arg2, arg3); } export function SetVMDriveShareSettings(arg1, arg2, arg3) { @@ -658,52 +542,28 @@ export function SetVMKeymap(arg1, arg2) { return window['go']['app']['App']['SetVMKeymap'](arg1, arg2); } -export function SetVMNote(arg1, arg2) { - return window['go']['app']['App']['SetVMNote'](arg1, arg2); +export function SetVMNote(arg1, arg2, arg3) { + return window['go']['app']['App']['SetVMNote'](arg1, arg2, arg3); } -export function SetVMNoteWithDriver(arg1, arg2, arg3) { - return window['go']['app']['App']['SetVMNoteWithDriver'](arg1, arg2, arg3); -} - -export function SetVMSSHUser(arg1, arg2) { - return window['go']['app']['App']['SetVMSSHUser'](arg1, arg2); -} - -export function SetVMSSHUserWithDriver(arg1, arg2, arg3) { - return window['go']['app']['App']['SetVMSSHUserWithDriver'](arg1, arg2, arg3); +export function SetVMSSHUser(arg1, arg2, arg3) { + return window['go']['app']['App']['SetVMSSHUser'](arg1, arg2, arg3); } export function SetVMSharedFolderMode(arg1, arg2, arg3) { return window['go']['app']['App']['SetVMSharedFolderMode'](arg1, arg2, arg3); } -export function SetVMTimezone(arg1, arg2) { - return window['go']['app']['App']['SetVMTimezone'](arg1, arg2); +export function SetVMTimezone(arg1, arg2, arg3) { + return window['go']['app']['App']['SetVMTimezone'](arg1, arg2, arg3); } -export function SetVMTimezoneWithDriver(arg1, arg2, arg3) { - return window['go']['app']['App']['SetVMTimezoneWithDriver'](arg1, arg2, arg3); +export function StartVM(arg1, arg2) { + return window['go']['app']['App']['StartVM'](arg1, arg2); } -export function ShowMainWindow() { - return window['go']['app']['App']['ShowMainWindow'](); -} - -export function StartVM(arg1) { - return window['go']['app']['App']['StartVM'](arg1); -} - -export function StartVMWithDriver(arg1, arg2) { - return window['go']['app']['App']['StartVMWithDriver'](arg1, arg2); -} - -export function StopVM(arg1, arg2) { - return window['go']['app']['App']['StopVM'](arg1, arg2); -} - -export function StopVMWithDriver(arg1, arg2, arg3) { - return window['go']['app']['App']['StopVMWithDriver'](arg1, arg2, arg3); +export function StopVM(arg1, arg2, arg3) { + return window['go']['app']['App']['StopVM'](arg1, arg2, arg3); } export function SuggestDataRoots() { @@ -714,12 +574,8 @@ export function SuggestLanguagePack() { return window['go']['app']['App']['SuggestLanguagePack'](); } -export function SuspendVM(arg1) { - return window['go']['app']['App']['SuspendVM'](arg1); -} - -export function SuspendVMWithDriver(arg1, arg2) { - return window['go']['app']['App']['SuspendVMWithDriver'](arg1, arg2); +export function SuspendVM(arg1, arg2) { + return window['go']['app']['App']['SuspendVM'](arg1, arg2); } export function TestHostDNS(arg1) { @@ -730,28 +586,16 @@ export function ToggleBorderless(arg1, arg2) { return window['go']['app']['App']['ToggleBorderless'](arg1, arg2); } -export function ToggleVMFullscreen(arg1) { - return window['go']['app']['App']['ToggleVMFullscreen'](arg1); +export function ToggleVMFullscreen(arg1, arg2) { + return window['go']['app']['App']['ToggleVMFullscreen'](arg1, arg2); } -export function ToggleVMFullscreenWithDriver(arg1, arg2) { - return window['go']['app']['App']['ToggleVMFullscreenWithDriver'](arg1, arg2); +export function TypeClipboard(arg1, arg2) { + return window['go']['app']['App']['TypeClipboard'](arg1, arg2); } -export function TypeClipboard(arg1) { - return window['go']['app']['App']['TypeClipboard'](arg1); -} - -export function TypeClipboardWithDriver(arg1, arg2) { - return window['go']['app']['App']['TypeClipboardWithDriver'](arg1, arg2); -} - -export function TypeText(arg1, arg2) { - return window['go']['app']['App']['TypeText'](arg1, arg2); -} - -export function TypeTextWithDriver(arg1, arg2, arg3) { - return window['go']['app']['App']['TypeTextWithDriver'](arg1, arg2, arg3); +export function TypeText(arg1, arg2, arg3) { + return window['go']['app']['App']['TypeText'](arg1, arg2, arg3); } export function UpgradeDiskToNVMe(arg1) { @@ -770,10 +614,6 @@ export function ValidateSet(arg1) { return window['go']['app']['App']['ValidateSet'](arg1); } -export function WriteSSHConfig(arg1, arg2) { - return window['go']['app']['App']['WriteSSHConfig'](arg1, arg2); -} - -export function WriteSSHConfigWithDriver(arg1, arg2, arg3) { - return window['go']['app']['App']['WriteSSHConfigWithDriver'](arg1, arg2, arg3); +export function WriteSSHConfig(arg1, arg2, arg3) { + return window['go']['app']['App']['WriteSSHConfig'](arg1, arg2, arg3); } diff --git a/internal/app/affinity_flow.go b/internal/app/affinity_flow.go index c934073..730de8c 100644 --- a/internal/app/affinity_flow.go +++ b/internal/app/affinity_flow.go @@ -96,10 +96,7 @@ func buildVMAffinityStatus(detail driver.VMInfo, rep host.Report, globalAutoPin // GetVMAffinity returns the per-VM processor affinity configuration, resolved // effective CPU set, and live QEMU process affinity mask when running. -func (a *App) GetVMAffinity(name string) (VMAffinityStatus, error) { - return a.GetVMAffinityWithDriver("", name) -} -func (a *App) GetVMAffinityWithDriver(driverID, name string) (VMAffinityStatus, error) { +func (a *App) GetVMAffinity(driverID, name string) (VMAffinityStatus, error) { vm, err := a.resolveVMInfo(driverID, name) if err != nil { return VMAffinityStatus{}, err @@ -127,10 +124,7 @@ func (a *App) GetVMAffinityWithDriver(driverID, name string) (VMAffinityStatus, // SetVMAffinity saves a VM's processor affinity mapping and immediately applies // it (plus EcoQoS power-throttling control) to the running QEMU process if active. -func (a *App) SetVMAffinity(name string, req VMAffinityUpdate) (VMAffinityStatus, error) { - return a.SetVMAffinityWithDriver("", name, req) -} -func (a *App) SetVMAffinityWithDriver(driverID, name string, req VMAffinityUpdate) (VMAffinityStatus, error) { +func (a *App) SetVMAffinity(driverID, name string, req VMAffinityUpdate) (VMAffinityStatus, error) { vm, err := a.resolveVMInfo(driverID, name) if err != nil { return VMAffinityStatus{}, err diff --git a/internal/app/app.go b/internal/app/app.go index 09db2c4..4bc5373 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -924,8 +924,8 @@ func (a *App) SetSyncHostMemorySMBIOS(enabled bool) error { return a.saveConfigLocked() } -// ShowMainWindow restores and focuses the Wails window from the system tray. -func (a *App) ShowMainWindow() { +// showMainWindow restores and focuses the Wails window from the system tray. +func (a *App) showMainWindow() { if a.ctx == nil { return } @@ -946,10 +946,10 @@ func (a *App) RequestClose() { func (a *App) startTray() { mgr, err := tray.Start(a.trayIcon, "Reims-Go", tray.Callbacks{ OnShow: func() { - a.ShowMainWindow() + a.showMainWindow() }, OnNewVM: func() { - a.ShowMainWindow() + a.showMainWindow() a.emit("reims:tray-new-vm") }, OnVMAction: a.trayVMAction, @@ -1021,34 +1021,34 @@ func (a *App) trayVMAction(driverID, name string, act tray.Action) { var failTitle string switch act { case tray.ActStart: - err, failTitle = a.StartVMWithDriver(driverID, name), i18n.M(loc, "tray.notify.start_fail", vars) + err, failTitle = a.StartVM(driverID, name), i18n.M(loc, "tray.notify.start_fail", vars) case tray.ActSuspend: - err, failTitle = a.SuspendVMWithDriver(driverID, name), i18n.M(loc, "tray.notify.suspend_fail", vars) + err, failTitle = a.SuspendVM(driverID, name), i18n.M(loc, "tray.notify.suspend_fail", vars) case tray.ActResume: - err, failTitle = a.ResumeVMWithDriver(driverID, name), i18n.M(loc, "tray.notify.resume_fail", vars) + err, failTitle = a.ResumeVM(driverID, name), i18n.M(loc, "tray.notify.resume_fail", vars) case tray.ActDiscardSuspend: - a.ShowMainWindow() + a.showMainWindow() a.emit("reims:tray-discard-suspend", name) case tray.ActStop: - err, failTitle = a.StopVMWithDriver(driverID, name, false), i18n.M(loc, "tray.notify.stop_fail", vars) + err, failTitle = a.StopVM(driverID, name, false), i18n.M(loc, "tray.notify.stop_fail", vars) case tray.ActForceStop: - err, failTitle = a.StopVMWithDriver(driverID, name, true), i18n.M(loc, "tray.notify.force_stop_fail", vars) + err, failTitle = a.StopVM(driverID, name, true), i18n.M(loc, "tray.notify.force_stop_fail", vars) case tray.ActRestart: - err, failTitle = a.RestartVMWithDriver(driverID, name), i18n.M(loc, "tray.notify.restart_fail", vars) + err, failTitle = a.RestartVM(driverID, name), i18n.M(loc, "tray.notify.restart_fail", vars) case tray.ActShowWindow: - err, failTitle = a.FocusVMWindowWithDriver(driverID, name), i18n.M(loc, "tray.notify.focus_fail", vars) + err, failTitle = a.FocusVMWindow(driverID, name), i18n.M(loc, "tray.notify.focus_fail", vars) case tray.ActToggleFullscreen: - _, err = a.ToggleVMFullscreenWithDriver(driverID, name) + _, err = a.ToggleVMFullscreen(driverID, name) failTitle = i18n.M(loc, "tray.notify.fullscreen_fail", vars) case tray.ActScreenshot: - if err = a.CopyVMScreenshotWithDriver(driverID, name); err == nil && tm != nil { + if err = a.CopyVMScreenshot(driverID, name); err == nil && tm != nil { tm.Notify(i18n.T(loc, "tray.notify.screenshot_ok"), name, false) } failTitle = i18n.M(loc, "tray.notify.screenshot_fail", vars) case tray.ActSharedFolder: err, failTitle = a.OpenSharedFolder(name), i18n.T(loc, "tray.notify.shared_fail") case tray.ActOpenInApp: - a.ShowMainWindow() + a.showMainWindow() a.emit("reims:tray-select-vm", name) } if err != nil { diff --git a/internal/app/clone_flow.go b/internal/app/clone_flow.go index e2d2337..b92b595 100644 --- a/internal/app/clone_flow.go +++ b/internal/app/clone_flow.go @@ -8,16 +8,12 @@ import ( ) // CloneVMCoW derives a VM through the source VM's owning driver. -func (a *App) CloneVMCoW(sourceName, cloneName string) error { - return a.CloneVMCoWWithDriver("", sourceName, cloneName) -} - -func (a *App) CloneVMCoWWithDriver(driverID, sourceName, cloneName string) error { - _, err := a.cloneVMCoWWithDriverInfo(driverID, sourceName, cloneName) +func (a *App) CloneVMCoW(driverID, sourceName, cloneName string) error { + _, err := a.cloneVM(driverID, sourceName, cloneName) return err } -func (a *App) cloneVMCoWWithDriverInfo(driverID, sourceName, cloneName string) (driver.VMInfo, error) { +func (a *App) cloneVM(driverID, sourceName, cloneName string) (driver.VMInfo, error) { a.mu.Lock() svc := a.lifecycleSvc a.mu.Unlock() diff --git a/internal/app/computer_use_host.go b/internal/app/computer_use_host.go index b78e9f4..d04940b 100644 --- a/internal/app/computer_use_host.go +++ b/internal/app/computer_use_host.go @@ -46,8 +46,8 @@ func (a *App) computerUseHostHandlers(mgr *plugin.Manager, pluginID string) map[ "host/vm.get": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:read", "host/vm.get", a.handleComputerUseVMGet), "host/vm.start": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.start", a.handleComputerUseVMStart), "host/vm.shutdown": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.shutdown", a.handleComputerUseVMShutdown), - "host/vm.suspend": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.suspend", a.handleComputerUseVMStateChange(a.SuspendVMWithDriver)), - "host/vm.resume": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.resume", a.handleComputerUseVMStateChange(a.ResumeVMWithDriver)), + "host/vm.suspend": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.suspend", a.handleComputerUseVMStateChange(a.SuspendVM)), + "host/vm.resume": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.resume", a.handleComputerUseVMStateChange(a.ResumeVM)), "host/vm.clone": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.clone", a.handleComputerUseVMClone), "host/vm.delete": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.delete", a.handleComputerUseVMDelete), "host/vm.snapshot.list": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList), @@ -175,7 +175,7 @@ func (a *App) computerUseVMView(vm driver.VMInfo, mgr *plugin.Manager, pluginID view["capabilities"] = append([]string(nil), vm.Capabilities...) } if accessEnabled { - username := a.GetVMSSHUserWithDriver(vm.DriverID, vm.Name) + username := a.GetVMSSHUser(vm.DriverID, vm.Name) if mgr != nil { settings := mgr.GetSettings(pluginID, vm.Ref().Key(), false) if configured, ok := settings["username"].(string); ok && strings.TrimSpace(configured) != "" { @@ -200,7 +200,7 @@ func (a *App) handleComputerUseVMStart(_ context.Context, raw json.RawMessage, m if err != nil { return nil, err } - if err := a.StartVMWithDriver(vm.DriverID, vm.Name); err != nil { + if err := a.StartVM(vm.DriverID, vm.Name); err != nil { return nil, err } return map[string]any{"ok": true}, nil @@ -217,7 +217,7 @@ func (a *App) handleComputerUseVMShutdown(_ context.Context, raw json.RawMessage if err != nil { return nil, err } - if err := a.StopVMWithDriver(vm.DriverID, vm.Name, false); err != nil { + if err := a.StopVM(vm.DriverID, vm.Name, false); err != nil { return nil, err } return map[string]any{"ok": true}, nil @@ -273,14 +273,14 @@ func (a *App) handleComputerUseVMClone(ctx context.Context, raw json.RawMessage, }) { return nil, fmt.Errorf("VM name %q is already taken", cloneName) } - cloned, err := a.cloneVMCoWWithDriverInfo(vm.DriverID, vm.Name, cloneName) + cloned, err := a.cloneVM(vm.DriverID, vm.Name, cloneName) if err != nil { return nil, err } cloneRef := cloned.Ref() err = persistComputerUseOwnership(cloned, pluginID, cloneRef.Key()) if err != nil { - if cleanupErr := a.DeleteVMWithDriver(vm.DriverID, cloneName, false); cleanupErr != nil { + if cleanupErr := a.DeleteVM(vm.DriverID, cloneName, false); cleanupErr != nil { return nil, errors.Join(err, fmt.Errorf("clean up unregistered clone %q: %w", cloneName, cleanupErr)) } return nil, err @@ -307,13 +307,13 @@ func (a *App) handleComputerUseVMDelete(ctx context.Context, raw json.RawMessage return nil, a.computerUseHostError("not_authorized", "err.computer_use.not_owned", i18n.Vars{"name": vm.Name}) } if vm.State == "running" { - if err := a.stopVMWithDriverCtx(ctx, vm.DriverID, vm.Name, false); err != nil { - if forceErr := a.stopVMWithDriverCtx(ctx, vm.DriverID, vm.Name, true); forceErr != nil { + if err := a.stopVM(ctx, vm.DriverID, vm.Name, false); err != nil { + if forceErr := a.stopVM(ctx, vm.DriverID, vm.Name, true); forceErr != nil { return nil, errors.Join(err, fmt.Errorf("force stop temporary VM %q: %w", vm.Name, forceErr)) } } } - if err := a.DeleteVMWithDriver(vm.DriverID, vm.Name, false); err != nil { + if err := a.DeleteVM(vm.DriverID, vm.Name, false); err != nil { return nil, err } removeComputerUseOwnership(vm.Directory) @@ -332,7 +332,7 @@ func (a *App) handleComputerUseVMSnapshotList(ctx context.Context, raw json.RawM if err != nil { return nil, err } - snapshots, err := a.ListSnapshotsWithDriver(vm.DriverID, vm.Name) + snapshots, err := a.ListSnapshots(vm.DriverID, vm.Name) if err != nil { return nil, err } @@ -351,7 +351,7 @@ func (a *App) handleComputerUseVMSnapshotCreate(_ context.Context, raw json.RawM if err != nil { return nil, err } - if err := a.CreateSnapshotWithDriver(vm.DriverID, vm.Name, req.Name); err != nil { + if err := a.CreateSnapshot(vm.DriverID, vm.Name, req.Name); err != nil { return nil, err } return map[string]any{"ok": true, "name": strings.TrimSpace(req.Name)}, nil @@ -372,7 +372,7 @@ func (a *App) handleComputerUseVMSnapshotRestore(_ context.Context, raw json.Raw if !a.computerUseOwned(pluginID, vm.Ref().Key()) { return nil, a.computerUseHostError("confirmation_required", "err.computer_use.restore_confirmation", i18n.Vars{"name": vm.Name}) } - if err := a.RestoreSnapshotWithDriver(vm.DriverID, vm.Name, req.Name); err != nil { + if err := a.RestoreSnapshot(vm.DriverID, vm.Name, req.Name); err != nil { return nil, err } return map[string]any{"ok": true, "name": strings.TrimSpace(req.Name)}, nil @@ -588,11 +588,11 @@ func (a *App) restoreComputerUseOwnedVMs(ctx context.Context) error { } if item.State == "running" { stopCtx, stopCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) - err := a.stopVMWithDriverCtx(stopCtx, item.DriverID, item.Name, false) + err := a.stopVM(stopCtx, item.DriverID, item.Name, false) stopCancel() if err != nil { forceCtx, forceCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) - forceErr := a.stopVMWithDriverCtx(forceCtx, item.DriverID, item.Name, true) + forceErr := a.stopVM(forceCtx, item.DriverID, item.Name, true) forceCancel() if forceErr != nil { cleanupErrors = append(cleanupErrors, errors.Join( @@ -603,7 +603,7 @@ func (a *App) restoreComputerUseOwnedVMs(ctx context.Context) error { } } } - if err := a.DeleteVMWithDriver(item.DriverID, item.Name, false); err != nil { + if err := a.DeleteVM(item.DriverID, item.Name, false); err != nil { cleanupErrors = append(cleanupErrors, fmt.Errorf("delete orphaned temporary VM %q: %w", item.Name, err)) continue } diff --git a/internal/app/console_router_test.go b/internal/app/console_router_test.go index f6639b5..9cff02a 100644 --- a/internal/app/console_router_test.go +++ b/internal/app/console_router_test.go @@ -93,14 +93,14 @@ func TestDriverConsoleServesGUIThumbnailAndTyping(t *testing.T) { ct := newConsoleTestApp(t) a := ct.app - thumb, err := a.GetVMThumbnailWithDriver(ct.drv.ID(), "dev") + thumb, err := a.GetVMThumbnail(ct.drv.ID(), "dev") if err != nil || !thumb.Live || !strings.HasPrefix(thumb.DataURL, "data:image/jpeg;base64,") { t.Fatalf("thumbnail = live %v, %.30q, %v; want a live frame from the driver console", thumb.Live, thumb.DataURL, err) } - n, err := a.TypeTextWithDriver(ct.drv.ID(), "dev", "hello") + n, err := a.TypeText(ct.drv.ID(), "dev", "hello") if err != nil || n != 5 { - t.Fatalf("TypeTextWithDriver = %d, %v", n, err) + t.Fatalf("TypeText = %d, %v", n, err) } if got := ct.log(t); !strings.Contains(got, "type dev hello") { t.Fatalf("the driver never received the text; its log is %q", got) diff --git a/internal/app/create_flow.go b/internal/app/create_flow.go index c8b7e89..56280ab 100644 --- a/internal/app/create_flow.go +++ b/internal/app/create_flow.go @@ -227,7 +227,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) { a.emitVMLog(opts.Name, "VM "+opts.Name+" ready.") a.emitStateChanged() if startAfterCreate && ctx.Err() == nil { - return a.StartVMWithDriver(driver.BuiltinReimsMacOSDriverID, opts.Name) + return a.StartVM(driver.BuiltinReimsMacOSDriverID, opts.Name) } return nil } diff --git a/internal/app/dataroot_flow_test.go b/internal/app/dataroot_flow_test.go index a507982..fd82445 100644 --- a/internal/app/dataroot_flow_test.go +++ b/internal/app/dataroot_flow_test.go @@ -45,7 +45,7 @@ func TestNothingWrittenBeforeSetup(t *testing.T) { if got := dirEntries(t, dir); len(got) != 0 { t.Fatalf("suggested folder written before setup: %v", got) } - if err := a.StartVM("mac"); err == nil { + if err := a.StartVM("", "mac"); err == nil { t.Fatal("StartVM before setup must be refused") } } @@ -76,7 +76,7 @@ func TestReadOnlyFolderRefusesWrites(t *testing.T) { if raw, _ := os.ReadFile(cfgPath); string(raw) != `{"data_root": "x", "locale": "zh-CN"}` { t.Fatalf("config rewritten: %s", raw) } - if err := a.StartVM("mac"); err == nil { + if err := a.StartVM("", "mac"); err == nil { t.Fatal("StartVM on a read-only folder must be refused") } a.initPlugins() diff --git a/internal/app/diagnostics_flow.go b/internal/app/diagnostics_flow.go index aae9a94..a2f2abe 100644 --- a/internal/app/diagnostics_flow.go +++ b/internal/app/diagnostics_flow.go @@ -126,10 +126,7 @@ func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error { } // ExportDiagnostics collects a redacted troubleshooting zip bundle through the owning driver. -func (a *App) ExportDiagnostics(name string) (string, error) { - return a.ExportDiagnosticsWithDriver("", name) -} -func (a *App) ExportDiagnosticsWithDriver(driverID, name string) (string, error) { +func (a *App) ExportDiagnostics(driverID, name string) (string, error) { var vm driver.VMInfo var err error if strings.TrimSpace(name) != "" { @@ -154,12 +151,12 @@ func (a *App) ExportDiagnosticsWithDriver(driverID, name string) (string, error) ref := vm.Ref() pluginKey = ref.Key() if ref.DriverID != driver.BuiltinReimsMacOSDriverID { - label = sshHostAliasForDriver(ref.DriverID, vm.Name) + label = sshHostAlias(ref.DriverID, vm.Name) } - if serial, err := a.ReadVMLogsWithDriver(ref.DriverID, vm.Name, true); err == nil { + if serial, err := a.ReadVMLogs(ref.DriverID, vm.Name, true); err == nil { bundle.SerialLog = serial } - if qemuLog, err := a.ReadVMLogsWithDriver(ref.DriverID, vm.Name, false); err == nil { + if qemuLog, err := a.ReadVMLogs(ref.DriverID, vm.Name, false); err == nil { bundle.QEMULog = qemuLog } } diff --git a/internal/app/disk_flow.go b/internal/app/disk_flow.go index 1d139f6..6590c41 100644 --- a/internal/app/disk_flow.go +++ b/internal/app/disk_flow.go @@ -10,10 +10,7 @@ import ( ) // ResizeVMDisk expands a stopped VM's virtual disk through its owning driver. -func (a *App) ResizeVMDisk(name, newSize string) (driver.DiskResizeResult, error) { - return a.ResizeVMDiskWithDriver("", name, newSize) -} -func (a *App) ResizeVMDiskWithDriver(driverID, name, newSize string) (driver.DiskResizeResult, error) { +func (a *App) ResizeVMDisk(driverID, name, newSize string) (driver.DiskResizeResult, error) { a.mu.Lock() svc := a.lifecycleSvc a.mu.Unlock() @@ -39,18 +36,12 @@ func (a *App) ResizeVMDiskWithDriver(driverID, name, newSize string) (driver.Dis } // CompactVMDisk reclaims unused host space through the owning driver. -func (a *App) CompactVMDisk(name string) (driver.DiskCompactResult, error) { - return a.CompactVMDiskWithDriver("", name) -} -func (a *App) CompactVMDiskWithDriver(driverID, name string) (driver.DiskCompactResult, error) { +func (a *App) CompactVMDisk(driverID, name string) (driver.DiskCompactResult, error) { return a.runCompactVMDisk(driverID, name, false) } // OptimizeVMDisk rewrites a stopped VM's qcow2 disk with extended L2 subclusters. -func (a *App) OptimizeVMDisk(name string) (driver.DiskCompactResult, error) { - return a.OptimizeVMDiskWithDriver("", name) -} -func (a *App) OptimizeVMDiskWithDriver(driverID, name string) (driver.DiskCompactResult, error) { +func (a *App) OptimizeVMDisk(driverID, name string) (driver.DiskCompactResult, error) { return a.runCompactVMDisk(driverID, name, true) } diff --git a/internal/app/disk_flow_test.go b/internal/app/disk_flow_test.go index a08a514..abd2e12 100644 --- a/internal/app/disk_flow_test.go +++ b/internal/app/disk_flow_test.go @@ -63,7 +63,7 @@ func TestVMStatsDiskHeaderMeta(t *testing.T) { lastVMsAt: time.Now(), lifecycleSvc: vmlifecycle.New(reg, router, nil), } - stats, err := a.GetVMStats("test") + stats, err := a.GetVMStats("", "test") if err != nil || !stats.DiskExtendedL2 || stats.DiskSnapshotCount != 2 { t.Fatalf("GetVMStats = %+v, %v", stats, err) } diff --git a/internal/app/display_flow.go b/internal/app/display_flow.go index 0aaf702..4e03348 100644 --- a/internal/app/display_flow.go +++ b/internal/app/display_flow.go @@ -74,7 +74,7 @@ func buildVMDisplayStatus(vm driver.VMInfo, cfg vmstart.VMDisplayConfig, display return status } -func (a *App) GetVMDisplayWithDriver(driverID, name string) (VMDisplayStatus, error) { +func (a *App) GetVMDisplay(driverID, name string) (VMDisplayStatus, error) { vm, err := a.resolveVMInfo(driverID, name) if err != nil { return VMDisplayStatus{}, err @@ -82,7 +82,7 @@ func (a *App) GetVMDisplayWithDriver(driverID, name string) (VMDisplayStatus, er return buildVMDisplayStatus(vm, vmstart.ReadVMDisplay(vm.Directory), a.displayHost.displays()), nil } -func (a *App) SetVMDisplayWithDriver(driverID, name, targetDisplay string) (VMDisplayStatus, error) { +func (a *App) SetVMDisplay(driverID, name, targetDisplay string) (VMDisplayStatus, error) { if err := a.requireWritableDataRoot(); err != nil { return VMDisplayStatus{}, err } diff --git a/internal/app/display_flow_test.go b/internal/app/display_flow_test.go index 1ff08ad..6cb3082 100644 --- a/internal/app/display_flow_test.go +++ b/internal/app/display_flow_test.go @@ -72,15 +72,15 @@ func TestGetAndSetVMDisplay(t *testing.T) { }, } - status, err := a.GetVMDisplayWithDriver(driverID, name) + status, err := a.GetVMDisplay(driverID, name) if err != nil || status.TargetDisplay != "" || status.EffectiveDisplay != "DISPLAY1" || !status.Connected || status.FallbackToPrimary || status.Running || len(status.Displays) != 2 { t.Fatalf("get default = %+v, %v", status, err) } - if _, err := a.SetVMDisplayWithDriver(driverID, name, "DISCONNECTED"); !errors.Is(err, host.ErrDisplayNotFound) { + if _, err := a.SetVMDisplay(driverID, name, "DISCONNECTED"); !errors.Is(err, host.ErrDisplayNotFound) { t.Fatalf("new offline display error = %v", err) } - status, err = a.SetVMDisplayWithDriver(driverID, name, " DISPLAY2 ") + status, err = a.SetVMDisplay(driverID, name, " DISPLAY2 ") if err != nil || status.TargetDisplay != "DISPLAY2" || status.EffectiveDisplay != "DISPLAY2" || moveCalls != 0 { t.Fatalf("set while stopped = %+v, %v, %d moves", status, err, moveCalls) } @@ -89,14 +89,14 @@ func TestGetAndSetVMDisplay(t *testing.T) { t.Fatalf("display recommendations = %+v", status) } displays = displays[:1] - status, err = a.GetVMDisplayWithDriver(driverID, name) + status, err = a.GetVMDisplay(driverID, name) if err != nil || status.TargetDisplay != "DISPLAY2" || status.EffectiveDisplay != "DISPLAY1" || status.Connected || !status.FallbackToPrimary { t.Fatalf("get offline display = %+v, %v", status, err) } - if status, err := a.SetVMDisplayWithDriver(driverID, name, "display2"); err != nil || !status.FallbackToPrimary { + if status, err := a.SetVMDisplay(driverID, name, "display2"); err != nil || !status.FallbackToPrimary { t.Fatalf("keep offline display = %+v, %v", status, err) } - if status, err := a.SetVMDisplayWithDriver(driverID, name, " PRIMARY "); err != nil || status.TargetDisplay != "" || + if status, err := a.SetVMDisplay(driverID, name, " PRIMARY "); err != nil || status.TargetDisplay != "" || status.FallbackToPrimary || vmstart.ReadVMDisplay(vm.Directory).TargetDisplay != "" { t.Fatalf("clear offline display = %+v, %v", status, err) } @@ -106,13 +106,13 @@ func TestGetAndSetVMDisplay(t *testing.T) { // The detail view for the built-in driver gets its PID from the list. a.lastVMsAt = time.Now() a.lastVMs = []driver.VMListItem{{Name: name, DriverID: driverID, State: "running", PID: &pid}} - status, err = a.SetVMDisplayWithDriver(driverID, name, "display2") + status, err = a.SetVMDisplay(driverID, name, "display2") if err != nil || !status.Running || !status.Connected || status.EffectiveDisplay != "DISPLAY2" || !status.AppliedLive || status.MoveError != "" || moveCalls != 1 { t.Fatalf("set while running = %+v, %v, %d moves", status, err, moveCalls) } moveErr = host.ErrDisplayWindowNotFound - if status, err := a.SetVMDisplayWithDriver(driverID, name, "display2"); err != nil || status.AppliedLive || status.MoveError != "" || moveCalls != 2 { + if status, err := a.SetVMDisplay(driverID, name, "display2"); err != nil || status.AppliedLive || status.MoveError != "" || moveCalls != 2 { t.Fatalf("set before window creation = %+v, %v, %d moves", status, err, moveCalls) } if logs := strings.Join(a.recentLogs, "\n"); !strings.Contains(logs, "Moved VM window") || !strings.Contains(logs, "Display window not ready") { @@ -122,7 +122,7 @@ func TestGetAndSetVMDisplay(t *testing.T) { t.Fatal(err) } moveErr = errors.New("move failed") - status, err = a.SetVMDisplayWithDriver(driverID, name, "display2") + status, err = a.SetVMDisplay(driverID, name, "display2") if err != nil || status.AppliedLive || !strings.Contains(status.MoveError, moveErr.Error()) || moveCalls != 3 { t.Fatalf("set with move failure = %+v, %v, %d moves", status, err, moveCalls) } @@ -145,7 +145,7 @@ func TestSetVMDisplayReadOnly(t *testing.T) { t.Fatal(err) } for _, target := range []string{"DISPLAY2", ""} { - _, err := a.SetVMDisplayWithDriver(driverID, vm.Name, target) + _, err := a.SetVMDisplay(driverID, vm.Name, target) var coded *i18n.CodedError if !errors.As(err, &coded) || coded.Code != "E_DATAROOT_NEWER" { t.Fatalf("set %q on read-only data root: %v", target, err) @@ -160,8 +160,8 @@ func TestSetVMDisplayReadOnly(t *testing.T) { func TestVMDisplayRejectsUnknownDriverWithoutLifecycleService(t *testing.T) { a := &App{cfg: config.Default()} const driverID = "test.driver.other" - _, getErr := a.GetVMDisplayWithDriver(driverID, "test-vm") - _, setErr := a.SetVMDisplayWithDriver(driverID, "test-vm", "") + _, getErr := a.GetVMDisplay(driverID, "test-vm") + _, setErr := a.SetVMDisplay(driverID, "test-vm", "") for _, err := range []error{getErr, setErr} { if err == nil || err.Error() != `driver "test.driver.other" is unavailable without the plugin manager` { t.Fatalf("unknown driver error = %v", err) @@ -200,13 +200,13 @@ func TestSetVMDisplayRefreshesStoppedPIDCache(t *testing.T) { return true, nil }, } - status, err := a.SetVMDisplayWithDriver(driverID, vm.Name, "DISPLAY1") + status, err := a.SetVMDisplay(driverID, vm.Name, "DISPLAY1") if err != nil || !status.Running || !status.AppliedLive || status.MoveError != "" || moveCalls != 1 { t.Fatalf("set with stale cache = %+v, %v, %d moves", status, err, moveCalls) } d.listErr = errors.New("PID lookup failed") - status, err = a.SetVMDisplayWithDriver(driverID, vm.Name, "DISPLAY2") + status, err = a.SetVMDisplay(driverID, vm.Name, "DISPLAY2") if err != nil || status.AppliedLive || !strings.Contains(status.MoveError, d.listErr.Error()) || moveCalls != 1 { t.Fatalf("set with PID lookup failure = %+v, %v, %d moves", status, err, moveCalls) } @@ -238,7 +238,7 @@ func TestSetVMDisplayDoesNotBlockOtherVMs(t *testing.T) { }() aResult := make(chan error, 1) pending.Go(func() { - _, err := a.SetVMDisplayWithDriver(driverID, vmA.Name, "DISPLAY2") + _, err := a.SetVMDisplay(driverID, vmA.Name, "DISPLAY2") aResult <- err }) select { @@ -250,7 +250,7 @@ func TestSetVMDisplayDoesNotBlockOtherVMs(t *testing.T) { } bResult := make(chan error, 1) pending.Go(func() { - _, err := a.SetVMDisplayWithDriver(driverID, vmB.Name, "DISPLAY2") + _, err := a.SetVMDisplay(driverID, vmB.Name, "DISPLAY2") bResult <- err }) select { @@ -261,7 +261,7 @@ func TestSetVMDisplayDoesNotBlockOtherVMs(t *testing.T) { case <-time.After(5 * time.Second): t.Fatal("VM-B could not save while VM-A was moving") } - if status, err := a.GetVMDisplayWithDriver(driverID, vmB.Name); err != nil || status.TargetDisplay != "DISPLAY2" { + if status, err := a.GetVMDisplay(driverID, vmB.Name); err != nil || status.TargetDisplay != "DISPLAY2" { t.Fatalf("get VM-B while VM-A is moving = %+v, %v", status, err) } } @@ -303,7 +303,7 @@ func TestPositionVMDisplayOnStartAfterManualSelection(t *testing.T) { ticks <- time.Time{} close(ticks) a.positionVMDisplayOnStart(context.Background(), vm, ticks, func(context.Context) (int, error) { - status, err := a.SetVMDisplayWithDriver(driverID, vm.Name, "DISPLAY2") + status, err := a.SetVMDisplay(driverID, vm.Name, "DISPLAY2") if err != nil || status.AppliedLive != manualMoved || status.MoveError != "" { t.Fatalf("manual move = %+v, %v", status, err) } diff --git a/internal/app/elevate_flow.go b/internal/app/elevate_flow.go index 980be9d..41a673b 100644 --- a/internal/app/elevate_flow.go +++ b/internal/app/elevate_flow.go @@ -130,7 +130,7 @@ func (a *App) requestElevation(ctx context.Context, broker *plugin.Broker, reg * if emit != nil { emit(prompt) } else { - a.ShowMainWindow() + a.showMainWindow() a.emit("reims:elevate-request", prompt) } diff --git a/internal/app/endpoints_flow.go b/internal/app/endpoints_flow.go index b9f8fa7..663ac68 100644 --- a/internal/app/endpoints_flow.go +++ b/internal/app/endpoints_flow.go @@ -141,10 +141,10 @@ func findEndpoint(vm driver.VMInfo, kind string) (driver.VMEndpoint, error) { return driver.VMEndpoint{}, fmt.Errorf("%s has no %s endpoint", vm.Name, kind) } -// OpenVMEndpointWithDriver opens one way into a running guest: a terminal, a +// OpenVMEndpoint opens one way into a running guest: a terminal, a // remote desktop, VMConnect or an adb shell. kind picks the endpoint and action // one of its fixed actions ("" is its default). -func (a *App) OpenVMEndpointWithDriver(driverID, name, kind, action string) error { +func (a *App) OpenVMEndpoint(driverID, name, kind, action string) error { vm, err := a.resolveVMInfo(driverID, name) if err != nil { return err @@ -175,11 +175,11 @@ func (a *App) OpenVMEndpointWithDriver(driverID, name, kind, action string) erro if kind == driver.EndpointSSH { switch action { case endpointActionDefault, endpointActionTerminal: - return a.OpenSSHTerminalWithDriver(vm.DriverID, vm.Name, "") + return a.OpenSSHTerminal(vm.DriverID, vm.Name, "") case endpointActionVSCode: - return a.OpenVSCodeSSHWithDriver(vm.DriverID, vm.Name, "") + return a.OpenVSCodeSSH(vm.DriverID, vm.Name, "") case endpointActionConfig: - _, err := a.WriteSSHConfigWithDriver(vm.DriverID, vm.Name, "") + _, err := a.WriteSSHConfig(vm.DriverID, vm.Name, "") return err } return fmt.Errorf("the ssh endpoint has no %q action", action) @@ -195,9 +195,9 @@ func (a *App) OpenVMEndpointWithDriver(driverID, name, kind, action string) erro return nil } -// GetVMEndpointCommandWithDriver returns the command line that reaches an +// GetVMEndpointCommand returns the command line that reaches an // endpoint, for the user to copy. -func (a *App) GetVMEndpointCommandWithDriver(driverID, name, kind string) (string, error) { +func (a *App) GetVMEndpointCommand(driverID, name, kind string) (string, error) { vm, err := a.resolveVMInfo(driverID, name) if err != nil { return "", err diff --git a/internal/app/endpoints_flow_test.go b/internal/app/endpoints_flow_test.go index 532c0b1..190cdf1 100644 --- a/internal/app/endpoints_flow_test.go +++ b/internal/app/endpoints_flow_test.go @@ -153,9 +153,9 @@ func TestSSHTargetPrefersTheEndpoint(t *testing.T) { } func TestSSHHostAliasSeparatesDrivers(t *testing.T) { - mac := sshHostAliasForDriver("", "dev") - other := sshHostAliasForDriver("vendor.driver.linux", "dev") - another := sshHostAliasForDriver("vendor.driver.windows", "dev") + mac := sshHostAlias("", "dev") + other := sshHostAlias("vendor.driver.linux", "dev") + another := sshHostAlias("vendor.driver.windows", "dev") if mac == other || other == another || mac == another { t.Fatalf("aliases collide: %q %q %q", mac, other, another) } diff --git a/internal/app/extras_flow.go b/internal/app/extras_flow.go index 0dd5ec8..1630a88 100644 --- a/internal/app/extras_flow.go +++ b/internal/app/extras_flow.go @@ -47,10 +47,7 @@ func (a *App) vmDirectoryForDriver(driverID, name string) string { } // GetVMNote returns the optional single-line note saved for a VM. -func (a *App) GetVMNote(name string) string { return a.GetVMNoteWithDriver("", name) } - -// GetVMNoteWithDriver returns the note of the VM that driverID owns. -func (a *App) GetVMNoteWithDriver(driverID, name string) string { +func (a *App) GetVMNote(driverID, name string) string { dir := a.vmDirectoryForDriver(driverID, name) if dir == "" { return "" @@ -63,10 +60,7 @@ func (a *App) GetVMNoteWithDriver(driverID, name string) string { } // SetVMNote stores a short single-line note next to the VM directory. -func (a *App) SetVMNote(name, note string) error { return a.SetVMNoteWithDriver("", name, note) } - -// SetVMNoteWithDriver stores the note of the VM that driverID owns. -func (a *App) SetVMNoteWithDriver(driverID, name, note string) error { +func (a *App) SetVMNote(driverID, name, note string) error { note = sanitizeVMNote(note) dir := a.vmDirectoryForDriver(driverID, name) if dir == "" { diff --git a/internal/app/fullscreen_hotkey_flow.go b/internal/app/fullscreen_hotkey_flow.go index 32e376e..ca59368 100644 --- a/internal/app/fullscreen_hotkey_flow.go +++ b/internal/app/fullscreen_hotkey_flow.go @@ -153,7 +153,7 @@ func (a *App) onFullscreenHotkey(target host.IMETarget, hwnd uintptr) { if !host.IsForegroundDisplayWindow(hwnd, target.PID) { return } - if _, err := a.ToggleVMFullscreenWithDriver(vm.DriverID, target.VMName); err != nil { + if _, err := a.ToggleVMFullscreen(vm.DriverID, target.VMName); err != nil { a.emitVMLogForDriver(vm.DriverID, target.VMName, err.Error()) } return diff --git a/internal/app/hosted_driver_test.go b/internal/app/hosted_driver_test.go index 46bc3b2..556ee8b 100644 --- a/internal/app/hosted_driver_test.go +++ b/internal/app/hosted_driver_test.go @@ -140,16 +140,16 @@ func TestSameNameVMsOfTwoDriversStayIsolatedInTheApp(t *testing.T) { tw := newTwoDriverApp(t) a := tw.app - if err := a.SetVMNoteWithDriver(tw.hosted.ID(), "dev", "hosted note"); err != nil { + if err := a.SetVMNote(tw.hosted.ID(), "dev", "hosted note"); err != nil { t.Fatal(err) } - if err := a.SetVMNoteWithDriver(tw.process.ID(), "dev", "process note"); err != nil { + if err := a.SetVMNote(tw.process.ID(), "dev", "process note"); err != nil { t.Fatal(err) } - if got := a.GetVMNoteWithDriver(tw.hosted.ID(), "dev"); got != "hosted note" { + if got := a.GetVMNote(tw.hosted.ID(), "dev"); got != "hosted note" { t.Fatalf("hosted note = %q", got) } - if got := a.GetVMNoteWithDriver(tw.process.ID(), "dev"); got != "process note" { + if got := a.GetVMNote(tw.process.ID(), "dev"); got != "process note" { t.Fatalf("process note = %q", got) } for dir, want := range map[string]string{tw.hostedDir: "hosted note", tw.processDir: "process note"} { @@ -158,15 +158,15 @@ func TestSameNameVMsOfTwoDriversStayIsolatedInTheApp(t *testing.T) { t.Fatalf("note file in %s = %q, %v; want %q", dir, raw, err, want) } } - if err := a.SetVMNoteWithDriver(tw.hosted.ID(), "dev", ""); err != nil { + if err := a.SetVMNote(tw.hosted.ID(), "dev", ""); err != nil { t.Fatal(err) } - if a.GetVMNoteWithDriver(tw.hosted.ID(), "dev") != "" || a.GetVMNoteWithDriver(tw.process.ID(), "dev") != "process note" { + if a.GetVMNote(tw.hosted.ID(), "dev") != "" || a.GetVMNote(tw.process.ID(), "dev") != "process note" { t.Fatal("clearing one VM's note touched the other") } - if logs, err := a.ReadVMLogsWithDriver(tw.hosted.ID(), "dev", false); err != nil || logs == "" { - t.Fatalf("ReadVMLogsWithDriver = %q, %v", logs, err) + if logs, err := a.ReadVMLogs(tw.hosted.ID(), "dev", false); err != nil || logs == "" { + t.Fatalf("ReadVMLogs = %q, %v", logs, err) } if _, err := a.GetVMInfo("", "dev"); err == nil { t.Fatal("a bare same-name lookup was not rejected as ambiguous") @@ -180,21 +180,21 @@ func TestHostedVMIsGatedFromWindowAndProcessFeatures(t *testing.T) { id := tw.hosted.ID() // Not running and not ready: nothing to open. - if err := a.FocusVMWindowWithDriver(id, "dev"); err == nil || !strings.Contains(err.Error(), "no ready endpoint") { - t.Fatalf("FocusVMWindowWithDriver on a stopped hosted VM = %v", err) + if err := a.FocusVMWindow(id, "dev"); err == nil || !strings.Contains(err.Error(), "no ready endpoint") { + t.Fatalf("FocusVMWindow on a stopped hosted VM = %v", err) } if _, err := tw.svc.Start(ctx, tw.hostedRef, io.Discard, io.Discard); err != nil { t.Fatal(err) } waitFor(t, "the hosted VM to run", func() bool { return tw.listed(t, tw.hostedRef).State == "running" }) - if cmd, err := a.GetVMEndpointCommandWithDriver(id, "dev", driver.EndpointWSL); err != nil || cmd != "wsl.exe -d dev" { + if cmd, err := a.GetVMEndpointCommand(id, "dev", driver.EndpointWSL); err != nil || cmd != "wsl.exe -d dev" { t.Fatalf("endpoint command = %q, %v", cmd, err) } - if _, err := a.GetVMEndpointCommandWithDriver(tw.process.ID(), "dev", driver.EndpointWSL); err == nil { + if _, err := a.GetVMEndpointCommand(tw.process.ID(), "dev", driver.EndpointWSL); err == nil { t.Fatal("the stopped same-name process VM exposed the hosted VM's endpoint") } - stats, err := a.GetVMStatsWithDriver(id, "dev") + stats, err := a.GetVMStats(id, "dev") if err != nil { t.Fatal(err) } @@ -202,22 +202,22 @@ func TestHostedVMIsGatedFromWindowAndProcessFeatures(t *testing.T) { t.Fatalf("hosted stats = %+v, want running with no process telemetry", stats) } - _, err = a.ToggleVMFullscreenWithDriver(id, "dev") + _, err = a.ToggleVMFullscreen(id, "dev") var coded *i18n.CodedError if !errors.As(err, &coded) || coded.Code != "E_VM_WINDOW_NOT_FOUND" { - t.Fatalf("ToggleVMFullscreenWithDriver = %v, want E_VM_WINDOW_NOT_FOUND", err) + t.Fatalf("ToggleVMFullscreen = %v, want E_VM_WINDOW_NOT_FOUND", err) } - if err := a.CopyVMScreenshotWithDriver(id, "dev"); err == nil { + if err := a.CopyVMScreenshot(id, "dev"); err == nil { t.Fatal("a hosted VM must not offer screenshots") } - if _, err := a.SetVMAffinityWithDriver(id, "dev", VMAffinityUpdate{}); err == nil { + if _, err := a.SetVMAffinity(id, "dev", VMAffinityUpdate{}); err == nil { t.Fatal("a hosted VM must not accept CPU affinity") } - if _, err := a.TypeTextWithDriver(id, "dev", "hello"); err == nil { + if _, err := a.TypeText(id, "dev", "hello"); err == nil { t.Fatal("a hosted VM must not accept QMP typing") } - if thumb, err := a.GetVMThumbnailWithDriver(id, "dev"); err != nil || thumb.Live { - t.Fatalf("GetVMThumbnailWithDriver = %+v, %v; want no live frame", thumb, err) + if thumb, err := a.GetVMThumbnail(id, "dev"); err != nil || thumb.Live { + t.Fatalf("GetVMThumbnail = %+v, %v; want no live frame", thumb, err) } } @@ -239,14 +239,14 @@ func TestProcessVMStatsFollowTheSpawnedJob(t *testing.T) { waitFor(t, "the broker to track the spawned VM", func() bool { return tw.harness.Broker.IsManagedVMRunning(tw.process.ID(), "dev") }) - stats, err := a.GetVMStatsWithDriver(tw.process.ID(), "dev") + stats, err := a.GetVMStats(tw.process.ID(), "dev") if err != nil { t.Fatal(err) } if !stats.Running || stats.PID <= 0 { t.Fatalf("process VM stats = %+v, want running with a PID", stats) } - if hostedStats, err := a.GetVMStatsWithDriver(tw.hosted.ID(), "dev"); err != nil || hostedStats.Running || hostedStats.PID != 0 { + if hostedStats, err := a.GetVMStats(tw.hosted.ID(), "dev"); err != nil || hostedStats.Running || hostedStats.PID != 0 { t.Fatalf("same-name hosted VM stats = %+v, %v; want stopped", hostedStats, err) } } diff --git a/internal/app/hypervisor_flow.go b/internal/app/hypervisor_flow.go index 791f2dd..de6c056 100644 --- a/internal/app/hypervisor_flow.go +++ b/internal/app/hypervisor_flow.go @@ -34,21 +34,10 @@ func (a *App) SetEnableHypervisorSwitch(enabled bool) error { return err } -// EnableWHPX enables Windows Hypervisor Platform (if missing) and sets Windows -// hypervisor boot launch to auto via UAC. Declining UAC is a no-op. -func (a *App) EnableWHPX() error { - _, err := a.setHypervisorBootInternal(true) - return err -} - // SetHypervisorBoot prompts for UAC and updates Windows hypervisor boot launch // (`auto` when enable is true, `off` when false). It returns changed=false with // err=nil when the person declines the UAC prompt, and never restarts Windows. func (a *App) SetHypervisorBoot(enable bool) (bool, error) { - return a.setHypervisorBootInternal(enable) -} - -func (a *App) setHypervisorBootInternal(enable bool) (bool, error) { a.mu.Lock() loc := i18n.EffectiveLocale(a.cfg.Locale) dataRoot := a.cfg.DataRoot diff --git a/internal/app/hypervisor_flow_test.go b/internal/app/hypervisor_flow_test.go index 86abeab..871169e 100644 --- a/internal/app/hypervisor_flow_test.go +++ b/internal/app/hypervisor_flow_test.go @@ -116,8 +116,8 @@ func TestHypervisorSwitchGateAndBootGuards(t *testing.T) { if changed, err := a.SetHypervisorBoot(false); err != nil || changed { t.Fatalf("UAC decline should return (false, nil), got (%v, %v)", changed, err) } - if err := a.EnableWHPX(); err != nil { - t.Fatalf("EnableWHPX on UAC decline should return nil, got %v", err) + if _, err := a.SetHypervisorBoot(true); err != nil { + t.Fatalf("SetHypervisorBoot(true) on UAC decline should return nil, got %v", err) } if recordedPending != "" { t.Fatalf("UAC decline must not record pending boot, got %q", recordedPending) @@ -149,13 +149,13 @@ func TestHypervisorSwitchGateAndBootGuards(t *testing.T) { t.Fatalf("after undo: lastEnable=%v pending=%q", lastEnable, recordedPending) } - // 7. EnableWHPX when hypervisor_off sets pending="auto". + // 7. SetHypervisorBoot(true) when hypervisor_off sets pending="auto". liveWHPX = host.WHPXHypervisorOff - if err := a.EnableWHPX(); err != nil { - t.Fatalf("EnableWHPX from hypervisor_off: %v", err) + if _, err := a.SetHypervisorBoot(true); err != nil { + t.Fatalf("SetHypervisorBoot(true) from hypervisor_off: %v", err) } if lastEnable != true || recordedPending != host.HypervisorBootAuto { - t.Fatalf("after EnableWHPX: lastEnable=%v pending=%q", lastEnable, recordedPending) + t.Fatalf("after SetHypervisorBoot(true): lastEnable=%v pending=%q", lastEnable, recordedPending) } } @@ -214,7 +214,7 @@ func TestHypervisorReadOnlyAndFirstRunIsolation(t *testing.T) { t.Fatal("read-only mode must never write hypervisor-boot-pending.json") } - // Case B: First-run setup (needsSetup=true) allows EnableWHPX in memory, + // Case B: First-run setup (needsSetup=true) allows SetHypervisorBoot(true) in memory, // but must never write to the unconfirmed default candidate folder on disk. firstCfg := config.Default() firstCfg.DataRoot = dir @@ -225,16 +225,15 @@ func TestHypervisorReadOnlyAndFirstRunIsolation(t *testing.T) { transitions: make(map[string]string), pendingChanges: make(map[string][]PendingChange), } - if err := firstApp.EnableWHPX(); err != nil { - t.Fatalf("EnableWHPX during first-run setup: %v", err) + if _, err := firstApp.SetHypervisorBoot(true); err != nil { + t.Fatalf("SetHypervisorBoot(true) during first-run setup: %v", err) } if elevatedCalls != 1 { - t.Fatalf("expected 1 elevated call during first-run EnableWHPX, got %d", elevatedCalls) + t.Fatalf("expected 1 elevated call during first-run SetHypervisorBoot(true), got %d", elevatedCalls) } if fileExistsForTest(filepath.Join(tmpSub, "hypervisor-boot-pending.json")) { - t.Fatal("first-run EnableWHPX must not write to unconfirmed candidate dataRoot/tmp") + t.Fatal("first-run SetHypervisorBoot(true) must not write to unconfirmed candidate dataRoot/tmp") } // Clean up in-memory pending state. _ = host.RecordPendingHypervisorBoot("", host.WHPXReady, true) } - diff --git a/internal/app/install_guide.go b/internal/app/install_guide.go index c545577..aff10fe 100644 --- a/internal/app/install_guide.go +++ b/internal/app/install_guide.go @@ -125,7 +125,7 @@ func (a *App) buildInstallGuide(ctx context.Context, g installguide.Guide, d rei if err := checkBoot(); err != nil { return err } - _, err := a.TypeText(name, text) + _, err := a.TypeText("", name, text) return err } g.FinishRecovery = func() error { diff --git a/internal/app/lifecycle_flow.go b/internal/app/lifecycle_flow.go index fb38694..24ffeaa 100644 --- a/internal/app/lifecycle_flow.go +++ b/internal/app/lifecycle_flow.go @@ -89,9 +89,7 @@ func (a *App) GetVMInfo(driverID, name string) (driver.VMInfo, error) { return vm, err } -func (a *App) StartVM(name string) error { return a.StartVMWithDriver("", name) } - -func (a *App) StartVMWithDriver(driverID, name string) error { +func (a *App) StartVM(driverID, name string) error { if err := a.beginVMStart(); err != nil { return err } @@ -119,7 +117,7 @@ func (a *App) StartVMWithDriver(driverID, name string) error { return err } if vm.State == "suspended" { - return a.ResumeVMWithDriver(vm.DriverID, vm.Name) + return a.ResumeVM(vm.DriverID, vm.Name) } return a.withComputerUseVM(context.Background(), vm.Directory, func(ctx context.Context) error { return a.startResolvedVMLocked(ctx, svc, vm) @@ -172,13 +170,11 @@ func (a *App) startResolvedVMLocked(ctx context.Context, svc interface { return nil } -func (a *App) StopVM(name string, force bool) error { return a.StopVMWithDriver("", name, force) } - -func (a *App) StopVMWithDriver(driverID, name string, force bool) error { - return a.stopVMWithDriverCtx(context.Background(), driverID, name, force) +func (a *App) StopVM(driverID, name string, force bool) error { + return a.stopVM(context.Background(), driverID, name, force) } -func (a *App) stopVMWithDriverCtx(ctx context.Context, driverID, name string, force bool) error { +func (a *App) stopVM(ctx context.Context, driverID, name string, force bool) error { a.mu.Lock() svc := a.lifecycleSvc a.mu.Unlock() @@ -221,9 +217,7 @@ func (a *App) stopVMWithDriverCtx(ctx context.Context, driverID, name string, fo return nil }) } -func (a *App) EjectInstaller(name string) error { return a.EjectInstallerWithDriver("", name) } - -func (a *App) EjectInstallerWithDriver(driverID, name string) error { +func (a *App) EjectInstaller(driverID, name string) error { a.mu.Lock() svc := a.lifecycleSvc a.mu.Unlock() @@ -248,7 +242,7 @@ func (a *App) EjectInstallerWithDriver(driverID, name string) error { return err } -func (a *App) ReadVMLogsWithDriver(driverID, name string, serial bool) (string, error) { +func (a *App) ReadVMLogs(driverID, name string, serial bool) (string, error) { a.mu.Lock() svc := a.lifecycleSvc a.mu.Unlock() @@ -258,7 +252,7 @@ func (a *App) ReadVMLogsWithDriver(driverID, name string, serial bool) (string, return svc.ReadLogs(context.Background(), driver.VMRef{DriverID: driverID, Name: name}, serial) } -func (a *App) RestartVMWithDriver(driverID, name string) error { +func (a *App) RestartVM(driverID, name string) error { if err := a.beginVMStart(); err != nil { return err } @@ -289,7 +283,7 @@ func (a *App) RestartVMWithDriver(driverID, name string) error { return err } return a.withComputerUseVM(a.baseCtx(), vm.Directory, func(ctx context.Context) error { - if err := a.stopVMWithDriverCtx(ctx, ref.DriverID, ref.Name, false); err != nil { + if err := a.stopVM(ctx, ref.DriverID, ref.Name, false); err != nil { return err } return a.startResolvedVMLocked(ctx, svc, vm) @@ -299,11 +293,7 @@ func (a *App) RestartVMWithDriver(driverID, name string) error { return err } -func (a *App) DeleteVM(name string, keepFiles bool) error { - return a.DeleteVMWithDriver("", name, keepFiles) -} - -func (a *App) DeleteVMWithDriver(driverID, name string, keepFiles bool) error { +func (a *App) DeleteVM(driverID, name string, keepFiles bool) error { a.mu.Lock() svc := a.lifecycleSvc a.mu.Unlock() diff --git a/internal/app/lifecycle_flow_test.go b/internal/app/lifecycle_flow_test.go index 9bf26de..ac810ea 100644 --- a/internal/app/lifecycle_flow_test.go +++ b/internal/app/lifecycle_flow_test.go @@ -92,10 +92,10 @@ func TestAppSecondDriverUserEntry(t *testing.T) { if err != nil || len(vms) != 1 || vms[0].DriverID != driverID { t.Fatalf("list = %+v, %v", vms, err) } - if err := a.StartVMWithDriver(driverID, "ubuntu"); err != nil { + if err := a.StartVM(driverID, "ubuntu"); err != nil { t.Fatal(err) } - if err := a.StopVMWithDriver(driverID, "ubuntu", false); err != nil { + if err := a.StopVM(driverID, "ubuntu", false); err != nil { t.Fatal(err) } if err := a.startHandedVM(driverID, "ubuntu"); err != nil { @@ -104,10 +104,10 @@ func TestAppSecondDriverUserEntry(t *testing.T) { if err := a.lifecycleSvc.Set(context.Background(), driver.NewVMRef(driverID, "ubuntu"), map[string]any{"memory": "8G"}, io.Discard, io.Discard); err != nil { t.Fatal(err) } - if err := a.RestartVMWithDriver(driverID, "ubuntu"); err != nil { + if err := a.RestartVM(driverID, "ubuntu"); err != nil { t.Fatal(err) } - if err := a.DeleteVMWithDriver(driverID, "ubuntu", false); err != nil { + if err := a.DeleteVM(driverID, "ubuntu", false); err != nil { t.Fatal(err) } if drv.starts != 3 || drv.stops != 2 || drv.deletes != 1 || drv.sets != 1 { @@ -190,14 +190,14 @@ func TestSameNameVMsAcrossDriversStayIndependent(t *testing.T) { 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 { + 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 { + if err := a.RestartVM(driver.BuiltinReimsMacOSDriverID, "dup"); err != nil { t.Fatal(err) } if mac.stops != 1 || mac.starts != 1 || lin.stops != 0 || lin.starts != 0 { diff --git a/internal/app/macos_lifecycle_native.go b/internal/app/macos_lifecycle_native.go index 29902e6..bf63ee4 100644 --- a/internal/app/macos_lifecycle_native.go +++ b/internal/app/macos_lifecycle_native.go @@ -173,7 +173,7 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) { if watchCtx.Err() != nil { return } - if err := a.StartVMWithDriver(driver.BuiltinReimsMacOSDriverID, name); err != nil { + if err := a.StartVM(driver.BuiltinReimsMacOSDriverID, name); err != nil { a.emitVMLog(name, "Win10 WHPX cold-reboot start failed: "+err.Error()) } }() @@ -491,8 +491,6 @@ func (a *App) stopMacOSVMLocked(ctx context.Context, name string, force bool, c return nil } -func (a *App) RestartVM(name string) error { return a.RestartVMWithDriver("", name) } - // restartMacOSVM restarts a built-in macOS VM, waiting for the old QEMU // process and its committed memory to go away before starting again. func (a *App) restartMacOSVM(ctx context.Context, name string) (stopped bool, err error) { @@ -509,7 +507,7 @@ func (a *App) restartMacOSVM(ctx context.Context, name string) (stopped bool, er func (a *App) restartMacOSVMLocked(ctx context.Context, name string) (stopped bool, err error) { oldPID := a.cachedVMPID(name) - if err := a.stopVMWithDriverCtx(ctx, driver.BuiltinReimsMacOSDriverID, name, false); err != nil { + if err := a.stopVM(ctx, driver.BuiltinReimsMacOSDriverID, name, false); err != nil { return false, err } a.waitForVMProcessExit(ctx, oldPID, vmExitWaitTimeout) @@ -619,10 +617,6 @@ func (a *App) OpenVMFolder(name string) error { return host.OpenFolder(d.Directory) } -func (a *App) ReadVMLogs(name string, serial bool) (string, error) { - return a.ReadVMLogsWithDriver("", name, serial) -} - func (a *App) readMacOSVMLogs(name string, serial bool) (string, error) { c, err := a.client() if err != nil { diff --git a/internal/app/plugins_flow.go b/internal/app/plugins_flow.go index babf561..137a3dc 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -955,31 +955,6 @@ func (a *App) ReadPluginLog(pluginID string) (string, error) { return host.RedactText(string(raw)), nil } -func (a *App) DoctorPlugin(pluginID string) []plugin.DoctorFinding { - a.mu.Lock() - mgr := a.pluginMgr - a.mu.Unlock() - if mgr == nil { - return nil - } - info, ok := mgr.Registry().Info(pluginID) - if !ok { - return []plugin.DoctorFinding{{ - Severity: "error", - Check: "lookup", - Message: fmt.Sprintf("plugin %q not found", pluginID), - }} - } - if info.InstallDir == "" { - return []plugin.DoctorFinding{{ - Severity: "ok", - Check: "builtin", - Message: fmt.Sprintf("%s@%s (%s)", info.ID, info.Version, info.State), - }} - } - return plugin.DoctorDirectory(info.InstallDir, version.Version, nil) -} - // InspectPluginArchive runs the unified static security scanner on a local .zip // package before installing it so the UI can display hard blockers, capabilities, // and L3 native execution notices. diff --git a/internal/app/quit_flow.go b/internal/app/quit_flow.go index 6feb17e..74d3c6a 100644 --- a/internal/app/quit_flow.go +++ b/internal/app/quit_flow.go @@ -79,7 +79,7 @@ func (a *App) forceStopRunningVMs(ctx context.Context) error { return vms, err } return stopListedVMs(ctx, loc, list, func(ctx context.Context, vm driver.VMListItem) error { - return a.stopVMWithDriverCtx(ctx, vm.DriverID, vm.Name, true) + return a.stopVM(ctx, vm.DriverID, vm.Name, true) }) } diff --git a/internal/app/quit_flow_test.go b/internal/app/quit_flow_test.go index 20fb4da..bfb7523 100644 --- a/internal/app/quit_flow_test.go +++ b/internal/app/quit_flow_test.go @@ -119,8 +119,8 @@ func TestForceQuitAppWaitsForStartsAndCanRetry(t *testing.T) { } 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") { + for _, launch := range []func(driverID, name 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) } } diff --git a/internal/app/snapshot_flow.go b/internal/app/snapshot_flow.go index a1b85b8..ad7ba89 100644 --- a/internal/app/snapshot_flow.go +++ b/internal/app/snapshot_flow.go @@ -11,10 +11,7 @@ import ( ) // ListSnapshots returns all driver-owned restore points for a VM, newest first. -func (a *App) ListSnapshots(name string) ([]driver.DiskSnapshot, error) { - return a.ListSnapshotsWithDriver("", name) -} -func (a *App) ListSnapshotsWithDriver(driverID, name string) ([]driver.DiskSnapshot, error) { +func (a *App) ListSnapshots(driverID, name string) ([]driver.DiskSnapshot, error) { a.mu.Lock() svc := a.lifecycleSvc a.mu.Unlock() @@ -24,26 +21,17 @@ func (a *App) ListSnapshotsWithDriver(driverID, name string) ([]driver.DiskSnaps return svc.ListSnapshots(a.baseCtx(), driver.VMRef{DriverID: driverID, Name: name}) } -func (a *App) CreateSnapshot(name, snapName string) error { - return a.CreateSnapshotWithDriver("", name, snapName) +func (a *App) CreateSnapshot(driverID, name, snapName string) error { + return a.runSnapshotOp(driverID, name, "create", snapName, "Created restore point") } -func (a *App) CreateSnapshotWithDriver(driverID, name, snapName string) error { - return a.runSnapshotOpWithDriver(driverID, name, "create", snapName, "Created restore point") +func (a *App) RestoreSnapshot(driverID, name, snapName string) error { + return a.runSnapshotOp(driverID, name, "restore", snapName, "Restored restore point") } -func (a *App) RestoreSnapshot(name, snapName string) error { - return a.RestoreSnapshotWithDriver("", name, snapName) -} -func (a *App) RestoreSnapshotWithDriver(driverID, name, snapName string) error { - return a.runSnapshotOpWithDriver(driverID, name, "restore", snapName, "Restored restore point") -} -func (a *App) DeleteSnapshot(name, snapName string) error { - return a.DeleteSnapshotWithDriver("", name, snapName) -} -func (a *App) DeleteSnapshotWithDriver(driverID, name, snapName string) error { - return a.runSnapshotOpWithDriver(driverID, name, "delete", snapName, "Deleted restore point") +func (a *App) DeleteSnapshot(driverID, name, snapName string) error { + return a.runSnapshotOp(driverID, name, "delete", snapName, "Deleted restore point") } -func (a *App) runSnapshotOpWithDriver(driverID, name, operation, snapName, verb string) error { +func (a *App) runSnapshotOp(driverID, name, operation, snapName, verb string) error { loc := a.locale() cleanSnap := strings.TrimSpace(snapName) if cleanSnap == "" { diff --git a/internal/app/ssh_flow.go b/internal/app/ssh_flow.go index b89215f..6002564 100644 --- a/internal/app/ssh_flow.go +++ b/internal/app/ssh_flow.go @@ -15,7 +15,7 @@ const sshUserFileName = ".reims-go-ssh-user" var safeSSHUserRe = regexp.MustCompile(`^[A-Za-z0-9._-]+$`) -func sshHostAliasForDriver(driverID, vmName string) string { +func sshHostAlias(driverID, vmName string) string { var b strings.Builder b.WriteString("reims-") if id := driver.CanonicalDriverID(driverID); id != "" && id != driver.BuiltinReimsMacOSDriverID { @@ -46,8 +46,7 @@ func sshConfigKey(driverID, name string) string { } // GetVMSSHUser returns the remembered SSH login user for a VM (empty if unset). -func (a *App) GetVMSSHUser(name string) string { return a.GetVMSSHUserWithDriver("", name) } -func (a *App) GetVMSSHUserWithDriver(driverID, name string) string { +func (a *App) GetVMSSHUser(driverID, name string) string { d, err := a.resolveVMInfo(driverID, name) if err != nil || d.Directory == "" { return "" @@ -60,8 +59,7 @@ func (a *App) GetVMSSHUserWithDriver(driverID, name string) string { } // SetVMSSHUser persists the preferred SSH login user for a VM. -func (a *App) SetVMSSHUser(name, user string) error { return a.SetVMSSHUserWithDriver("", name, user) } -func (a *App) SetVMSSHUserWithDriver(driverID, name, user string) error { +func (a *App) SetVMSSHUser(driverID, name, user string) error { user = strings.TrimSpace(user) if user != "" && !safeSSHUserRe.MatchString(user) { return fmt.Errorf("invalid SSH username %q", user) @@ -81,12 +79,6 @@ func (a *App) SetVMSSHUserWithDriver(driverID, name, user string) error { return os.WriteFile(p, []byte(user+"\n"), 0o644) } -// OpenSSHTerminal launches an interactive Windows Terminal (falling back to -// PowerShell) connected to the VM's forwarded SSH port. -func (a *App) OpenSSHTerminal(name, user string) error { - return a.OpenSSHTerminalWithDriver("", name, user) -} - // sshTarget is where a VM's SSH server answers: the ssh endpoint the driver // reports (a hosted VM may sit on its own address), else the forwarded port. func sshTarget(vm driver.VMInfo) (host string, port int, user string, ok bool) { @@ -105,7 +97,9 @@ func sshTarget(vm driver.VMInfo) (host string, port int, user string, ok bool) { return "", 0, "", false } -func (a *App) OpenSSHTerminalWithDriver(driverID, name, user string) error { +// OpenSSHTerminal launches an interactive Windows Terminal (falling back to +// PowerShell) connected to the VM's forwarded SSH port. +func (a *App) OpenSSHTerminal(driverID, name, user string) error { d, err := a.resolveVMInfo(driverID, name) if err != nil { return err @@ -116,11 +110,11 @@ func (a *App) OpenSSHTerminalWithDriver(driverID, name, user string) error { } user = strings.TrimSpace(user) if user == "" { - user = a.GetVMSSHUserWithDriver(driverID, name) + user = a.GetVMSSHUser(driverID, name) } else if !safeSSHUserRe.MatchString(user) { return fmt.Errorf("invalid SSH username %q", user) } else { - _ = a.SetVMSSHUserWithDriver(driverID, name, user) + _ = a.SetVMSSHUser(driverID, name, user) } if user == "" { user = endpointUser @@ -147,10 +141,7 @@ func (a *App) OpenSSHTerminalWithDriver(driverID, name, user string) error { // WriteSSHConfig idempotently writes or updates a Host block for the VM in // ~/.ssh/config and returns the configured Host alias (e.g. "reims-macos-tahoe"). -func (a *App) WriteSSHConfig(name, user string) (string, error) { - return a.WriteSSHConfigWithDriver("", name, user) -} -func (a *App) WriteSSHConfigWithDriver(driverID, name, user string) (string, error) { +func (a *App) WriteSSHConfig(driverID, name, user string) (string, error) { d, err := a.resolveVMInfo(driverID, name) if err != nil { return "", err @@ -161,11 +152,11 @@ func (a *App) WriteSSHConfigWithDriver(driverID, name, user string) (string, err } user = strings.TrimSpace(user) if user == "" { - user = a.GetVMSSHUserWithDriver(driverID, name) + user = a.GetVMSSHUser(driverID, name) } else if !safeSSHUserRe.MatchString(user) { return "", fmt.Errorf("invalid SSH username %q", user) } else { - _ = a.SetVMSSHUserWithDriver(driverID, name, user) + _ = a.SetVMSSHUser(driverID, name, user) } if user == "" { user = endpointUser @@ -179,7 +170,7 @@ func (a *App) WriteSSHConfigWithDriver(driverID, name, user string) (string, err return "", fmt.Errorf("create ~/.ssh: %w", err) } cfgPath := filepath.Join(sshDir, "config") - alias := sshHostAliasForDriver(driverID, name) + alias := sshHostAlias(driverID, name) if err := upsertSSHConfigBlock(cfgPath, sshConfigKey(driverID, name), alias, sshHost, sshPort, user); err != nil { return "", err } @@ -189,11 +180,8 @@ func (a *App) WriteSSHConfigWithDriver(driverID, name, user string) (string, err // OpenVSCodeSSH ensures the VM's Host block is present in ~/.ssh/config and // launches VS Code (falling back to Cursor) in Remote-SSH mode. -func (a *App) OpenVSCodeSSH(name, user string) error { - return a.OpenVSCodeSSHWithDriver("", name, user) -} -func (a *App) OpenVSCodeSSHWithDriver(driverID, name, user string) error { - alias, err := a.WriteSSHConfigWithDriver(driverID, name, user) +func (a *App) OpenVSCodeSSH(driverID, name, user string) error { + alias, err := a.WriteSSHConfig(driverID, name, user) if err != nil { return err } diff --git a/internal/app/ssh_flow_test.go b/internal/app/ssh_flow_test.go index a0099c6..91d96c8 100644 --- a/internal/app/ssh_flow_test.go +++ b/internal/app/ssh_flow_test.go @@ -8,13 +8,13 @@ import ( ) func TestSSHHostAlias(t *testing.T) { - if sshHostAliasForDriver("test.driver.linux", "dev") == sshHostAliasForDriver("", "dev") { + if sshHostAlias("test.driver.linux", "dev") == sshHostAlias("", "dev") { t.Fatal("same-name drivers share an SSH alias") } - if got := sshHostAliasForDriver("", "macos-tahoe"); got != "reims-macos-tahoe" { + if got := sshHostAlias("", "macos-tahoe"); got != "reims-macos-tahoe" { t.Fatalf("alias = %q", got) } - if got := sshHostAliasForDriver("", "My Mac 26"); got != "reims-my-mac-26" { + if got := sshHostAlias("", "My Mac 26"); got != "reims-my-mac-26" { t.Fatalf("alias = %q", got) } } diff --git a/internal/app/stats_flow.go b/internal/app/stats_flow.go index bd239ee..24c78fd 100644 --- a/internal/app/stats_flow.go +++ b/internal/app/stats_flow.go @@ -34,8 +34,7 @@ type VMStats struct { } // GetVMStats samples host-side process and disk telemetry through the owning driver. -func (a *App) GetVMStats(name string) (VMStats, error) { return a.GetVMStatsWithDriver("", name) } -func (a *App) GetVMStatsWithDriver(driverID, name string) (VMStats, error) { +func (a *App) GetVMStats(driverID, name string) (VMStats, error) { vm, err := a.resolveVMInfo(driverID, name) if err != nil { return VMStats{Name: name}, err diff --git a/internal/app/stats_flow_test.go b/internal/app/stats_flow_test.go index dba3708..d52aaa8 100644 --- a/internal/app/stats_flow_test.go +++ b/internal/app/stats_flow_test.go @@ -62,7 +62,7 @@ func TestVMStatsReportsLiveGuestToolsAgentVersion(t *testing.T) { if res.StatusCode != http.StatusOK { t.Fatalf("agent status: %s", res.Status) } - stats, err := a.GetVMStats(name) + stats, err := a.GetVMStats("", name) if err != nil || !stats.GuestToolsConnected || stats.GuestToolsAgentVersion != version { t.Fatalf("VM stats: %+v, %v", stats, err) } diff --git a/internal/app/suspend_flow.go b/internal/app/suspend_flow.go index 157b874..86375e0 100644 --- a/internal/app/suspend_flow.go +++ b/internal/app/suspend_flow.go @@ -14,11 +14,7 @@ import ( ) // SuspendVM saves a VM's running state and closes its QEMU process. -func (a *App) SuspendVM(name string) error { - return a.SuspendVMWithDriver("", name) -} - -func (a *App) SuspendVMWithDriver(driverID, name string) error { +func (a *App) SuspendVM(driverID, name string) error { if err := a.requireWritableDataRoot(); err != nil { return err } @@ -73,11 +69,7 @@ func (a *App) SuspendVMWithDriver(driverID, name string) error { } // ResumeVM restores a suspended VM with its original media and devices. -func (a *App) ResumeVM(name string) error { - return a.ResumeVMWithDriver("", name) -} - -func (a *App) ResumeVMWithDriver(driverID, name string) error { +func (a *App) ResumeVM(driverID, name string) error { if err := a.beginVMStart(); err != nil { return err } @@ -225,11 +217,7 @@ func (a *App) registerResumeGuestTools(vm driver.VMInfo, epoch uint64, unicodeIn } // DiscardSuspend deletes a stopped VM's saved execution state. -func (a *App) DiscardSuspend(name string) error { - return a.DiscardSuspendWithDriver("", name) -} - -func (a *App) DiscardSuspendWithDriver(driverID, name string) error { +func (a *App) DiscardSuspend(driverID, name string) error { if err := a.requireWritableDataRoot(); err != nil { return err } diff --git a/internal/app/suspend_flow_test.go b/internal/app/suspend_flow_test.go index 2c4383e..89e7853 100644 --- a/internal/app/suspend_flow_test.go +++ b/internal/app/suspend_flow_test.go @@ -187,7 +187,7 @@ func TestResumeVMRegistersSavedGuestToolsWithoutUnicodeInput(t *testing.T) { } } }) - if err := a.ResumeVM(name); !errors.Is(err, tc.resumeErr) { + if err := a.ResumeVM("", name); !errors.Is(err, tc.resumeErr) { t.Fatalf("ResumeVM error = %v, want %v", err, tc.resumeErr) } if !tc.savedConfig { diff --git a/internal/app/tasks.go b/internal/app/tasks.go index da604a8..895cb4b 100644 --- a/internal/app/tasks.go +++ b/internal/app/tasks.go @@ -294,14 +294,6 @@ func (m *taskManager) cancelAll() { } } -func (m *taskManager) dismiss(id string) { - m.mu.Lock() - if e, ok := m.tasks[id]; ok && e.task.Status != TaskRunning { - delete(m.tasks, id) - } - m.mu.Unlock() -} - func (m *taskManager) get(id string) (Task, bool) { m.mu.Lock() defer m.mu.Unlock() @@ -379,9 +371,6 @@ func (a *App) GetTasks() []Task { // CancelTask stops a cancelable task (a download pauses; rerunning resumes it). func (a *App) CancelTask(id string) error { return tasks.cancel(id) } -// DismissTask forgets a finished task. -func (a *App) DismissTask(id string) { tasks.dismiss(id) } - func (a *App) ensureTaskEmitter() { tasks.mu.Lock() if tasks.emit == nil { diff --git a/internal/app/tasks_test.go b/internal/app/tasks_test.go index aa3c24b..daf2b51 100644 --- a/internal/app/tasks_test.go +++ b/internal/app/tasks_test.go @@ -97,3 +97,12 @@ func TestCtlTaskWriterRoutesProgressToTheTask(t *testing.T) { t.Fatalf("final = %+v", final) } } + +// dismiss drops a finished task, so one test does not see another's. +func (m *taskManager) dismiss(id string) { + m.mu.Lock() + if e, ok := m.tasks[id]; ok && e.task.Status != TaskRunning { + delete(m.tasks, id) + } + m.mu.Unlock() +} diff --git a/internal/app/thumbnail_flow.go b/internal/app/thumbnail_flow.go index 1919c77..0bff8f8 100644 --- a/internal/app/thumbnail_flow.go +++ b/internal/app/thumbnail_flow.go @@ -42,7 +42,7 @@ var thumbLocks = struct { locks map[string]*sync.Mutex }{locks: make(map[string]*sync.Mutex)} -func (a *App) thumbPathForDriver(driverID, name string) string { +func (a *App) thumbPath(driverID, name string) string { a.mu.Lock() dir := a.cfg.XDGCacheDir() a.mu.Unlock() @@ -58,7 +58,7 @@ func (a *App) thumbPathForDriver(driverID, name string) string { return filepath.Join(dir, "thumbs", prefix+name+".jpg") } -func vmThumbLockForDriver(driverID, name string) *sync.Mutex { +func vmThumbLock(driverID, name string) *sync.Mutex { key := vmKeyForDriver(driverID, name) thumbLocks.mu.Lock() defer thumbLocks.mu.Unlock() @@ -76,7 +76,7 @@ func releaseVMThumbnail(name string) { releaseVMThumbnailForDriver("", name) } func releaseVMThumbnailForDriver(driverID, name string) { key := vmKeyForDriver(driverID, name) - mu := vmThumbLockForDriver(driverID, name) + mu := vmThumbLock(driverID, name) mu.Lock() thumbLocks.mu.Lock() if thumbLocks.locks[key] == mu { @@ -88,15 +88,12 @@ func releaseVMThumbnailForDriver(driverID, name string) { // GetVMThumbnail returns the VM's screen: a fresh frame while it runs, else // the last one saved. An empty DataURL means there is no frame to show. -func (a *App) GetVMThumbnail(name string) (VMThumbnail, error) { - return a.GetVMThumbnailWithDriver("", name) -} -func (a *App) GetVMThumbnailWithDriver(driverID, name string) (VMThumbnail, error) { - path := a.thumbPathForDriver(driverID, name) - mu := vmThumbLockForDriver(driverID, name) +func (a *App) GetVMThumbnail(driverID, name string) (VMThumbnail, error) { + path := a.thumbPath(driverID, name) + mu := vmThumbLock(driverID, name) if mu.TryLock() { defer mu.Unlock() - if t, ok := a.captureThumbWithDriver(driverID, name, path); ok { + if t, ok := a.captureThumb(driverID, name, path); ok { return t, nil } } @@ -105,8 +102,7 @@ func (a *App) GetVMThumbnailWithDriver(driverID, name string) (VMThumbnail, erro // FocusVMWindow brings a running VM's QEMU display window to the foreground, // restoring it first if minimized. -func (a *App) FocusVMWindow(name string) error { return a.FocusVMWindowWithDriver("", name) } -func (a *App) FocusVMWindowWithDriver(driverID, name string) error { +func (a *App) FocusVMWindow(driverID, name string) error { info, err := a.resolveVMInfo(driverID, name) if err != nil { return err @@ -117,7 +113,7 @@ func (a *App) FocusVMWindowWithDriver(driverID, name string) error { if !ok { return fmt.Errorf("%s has no ready endpoint to open", name) } - return a.OpenVMEndpointWithDriver(info.DriverID, info.Name, ep.Kind, "") + return a.OpenVMEndpoint(info.DriverID, info.Name, ep.Kind, "") } vm, ok := a.polledVMForDriver(info.DriverID, name) if !ok || vm.State != "running" { @@ -141,10 +137,7 @@ func (a *App) FocusVMWindowWithDriver(driverID, name string) error { } // ToggleVMFullscreen switches the running VM's display through its owning driver. -func (a *App) ToggleVMFullscreen(name string) (bool, error) { - return a.ToggleVMFullscreenWithDriver("", name) -} -func (a *App) ToggleVMFullscreenWithDriver(driverID, name string) (bool, error) { +func (a *App) ToggleVMFullscreen(driverID, name string) (bool, error) { a.mu.Lock() preference := a.cfg.Locale a.mu.Unlock() @@ -190,8 +183,7 @@ func (a *App) ToggleVMFullscreenWithDriver(driverID, name string) (bool, error) // CopyVMScreenshot captures a full-resolution frame from a running VM over QMP // and writes it as a PNG/DIB image to the Windows clipboard. -func (a *App) CopyVMScreenshot(name string) error { return a.CopyVMScreenshotWithDriver("", name) } -func (a *App) CopyVMScreenshotWithDriver(driverID, name string) error { +func (a *App) CopyVMScreenshot(driverID, name string) error { info, err := a.resolveVMInfo(driverID, name) if err != nil { return err @@ -210,7 +202,7 @@ func (a *App) CopyVMScreenshotWithDriver(driverID, name string) error { if route.kind == consoleRouteQMP && route.vm.Directory == "" { return fmt.Errorf("VM %s is not running", name) } - mu := vmThumbLockForDriver(driverID, name) + mu := vmThumbLock(driverID, name) mu.Lock() defer mu.Unlock() @@ -236,7 +228,7 @@ func (a *App) CopyVMScreenshotWithDriver(driverID, name string) error { return nil } -func (a *App) captureThumbWithDriver(driverID, name, path string) (VMThumbnail, bool) { +func (a *App) captureThumb(driverID, name, path string) (VMThumbnail, bool) { typing.mu.Lock() busy := typing.busy[vmKeyForDriver(driverID, name)] typing.mu.Unlock() diff --git a/internal/app/thumbnail_flow_test.go b/internal/app/thumbnail_flow_test.go index 44e6fd6..2564fbe 100644 --- a/internal/app/thumbnail_flow_test.go +++ b/internal/app/thumbnail_flow_test.go @@ -17,8 +17,8 @@ import ( func TestReleaseVMThumbnailRemovesLock(t *testing.T) { const name = "thumbnail-release-test" t.Cleanup(func() { releaseVMThumbnail(name) }) - first := vmThumbLockForDriver("", name) - if got := vmThumbLockForDriver("", name); got != first { + first := vmThumbLock("", name) + if got := vmThumbLock("", name); got != first { t.Fatal("same VM should share a thumbnail lock") } releaseVMThumbnail(name) @@ -28,7 +28,7 @@ func TestReleaseVMThumbnailRemovesLock(t *testing.T) { if remaining != 0 { t.Fatalf("thumbnail locks remain after release: %d", remaining) } - if got := vmThumbLockForDriver("", name); got == first { + if got := vmThumbLock("", name); got == first { t.Fatal("released lock was reused") } } @@ -74,7 +74,7 @@ func TestToggleVMFullscreenLocalizesErrors(t *testing.T) { a := &App{cfg: &config.Config{DataRoot: t.TempDir(), Locale: i18n.Locale(locale)}, lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil), transitions: map[string]string{}, pendingChanges: map[string][]PendingChange{}} - got, err := a.ToggleVMFullscreen("Tahoe") + got, err := a.ToggleVMFullscreen("", "Tahoe") if got || err == nil { t.Fatalf("toggle = (%v, %v), want an error", got, err) } diff --git a/internal/app/timezone_flow.go b/internal/app/timezone_flow.go index 6ebd838..2ed878d 100644 --- a/internal/app/timezone_flow.go +++ b/internal/app/timezone_flow.go @@ -24,11 +24,7 @@ type VMTimezoneStatus struct { Running bool `json:"running"` } -func (a *App) GetVMTimezone(name string) (VMTimezoneStatus, error) { - return a.GetVMTimezoneWithDriver("", name) -} - -func (a *App) GetVMTimezoneWithDriver(driverID, name string) (VMTimezoneStatus, error) { +func (a *App) GetVMTimezone(driverID, name string) (VMTimezoneStatus, error) { vm, err := a.resolveVMInfo(driverID, name) if err != nil { return VMTimezoneStatus{}, err @@ -42,11 +38,7 @@ func (a *App) GetVMTimezoneWithDriver(driverID, name string) (VMTimezoneStatus, return a.timezoneStatus(vm, cfg.GuestTimezone), nil } -func (a *App) SetVMTimezone(name, setting string) (VMTimezoneStatus, error) { - return a.SetVMTimezoneWithDriver("", name, setting) -} - -func (a *App) SetVMTimezoneWithDriver(driverID, name, setting string) (VMTimezoneStatus, error) { +func (a *App) SetVMTimezone(driverID, name, setting string) (VMTimezoneStatus, error) { if err := a.requireWritableDataRoot(); err != nil { return VMTimezoneStatus{}, err } diff --git a/internal/app/timezone_flow_test.go b/internal/app/timezone_flow_test.go index 9761d1d..f3c88a1 100644 --- a/internal/app/timezone_flow_test.go +++ b/internal/app/timezone_flow_test.go @@ -44,7 +44,7 @@ func TestVMTimezone(t *testing.T) { lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil), } - initial, err := a.GetVMTimezone(vm.Name) + initial, err := a.GetVMTimezone("", vm.Name) if err != nil || initial.Mode != "host" || initial.EffectiveTimezone != initial.HostTimezone || !initial.Running || initial.RequiredAgentVersion != 11 || initial.GuestConnected { t.Fatalf("initial timezone = %+v, %v", initial, err) @@ -87,7 +87,7 @@ func TestVMTimezone(t *testing.T) { {"America/Argentina/Buenos_Aires", "custom", "America/Argentina/Buenos_Aires", "America/Argentina/Buenos_Aires"}, {"", "host", "", initial.HostTimezone}, } { - got, err := a.SetVMTimezone(vm.Name, tc.setting) + got, err := a.SetVMTimezone("", vm.Name, tc.setting) if err != nil || got.Mode != tc.mode || got.Timezone != tc.custom || got.EffectiveTimezone != tc.effective { t.Fatalf("set %q = %+v, %v", tc.setting, got, err) } @@ -97,13 +97,13 @@ func TestVMTimezone(t *testing.T) { t.Fatalf("stored timezone = %q, other settings preserved = %v, %v", stored.GuestTimezone, stored.Token == cfg.Token && stored.Port == cfg.Port && stored.SharedDir == cfg.SharedDir && stored.PreventSleep, err) } - persisted, err := a.GetVMTimezoneWithDriver(driverID, vm.Name) + persisted, err := a.GetVMTimezone(driverID, vm.Name) if err != nil || persisted.Mode != tc.mode || persisted.EffectiveTimezone != tc.effective { t.Fatalf("get after set = %+v, %v", persisted, err) } checkLiveTimezone(t, tc.effective) } - if _, err := a.SetVMTimezoneWithDriver(driverID, vm.Name, "../Asia/Shanghai"); err == nil { + if _, err := a.SetVMTimezone(driverID, vm.Name, "../Asia/Shanghai"); err == nil { t.Fatal("accepted invalid timezone") } stored, _, err := guesttools.ReadVMConfigStrict(vm.Directory) @@ -122,7 +122,7 @@ func TestVMTimezone(t *testing.T) { t.Fatal(err) } res.Body.Close() - status, err := a.GetVMTimezoneWithDriver(driverID, vm.Name) + status, err := a.GetVMTimezone(driverID, vm.Name) if err != nil || res.StatusCode != http.StatusOK || !status.GuestConnected || !status.HelperReady || status.TimezoneError != "apply_failed" { t.Fatalf("guest timezone status = %+v, HTTP %d, %v", status, res.StatusCode, err) @@ -135,7 +135,7 @@ func TestVMTimezone(t *testing.T) { t.Fatal(err) } a.root = dataroot.Status{ReadOnly: true, Reason: dataroot.ReasonNewer} - if got, err := a.SetVMTimezoneWithDriver(driverID, vm.Name, "off"); err == nil || got != (VMTimezoneStatus{}) { + if got, err := a.SetVMTimezone(driverID, vm.Name, "off"); err == nil || got != (VMTimezoneStatus{}) { t.Fatalf("set on read-only root = %+v, %v", got, err) } after, err := os.ReadFile(path) diff --git a/internal/app/type_flow.go b/internal/app/type_flow.go index 18dea6a..2c5aaaf 100644 --- a/internal/app/type_flow.go +++ b/internal/app/type_flow.go @@ -71,14 +71,9 @@ func hasNonASCII(s string) bool { // sent. When Guest Tools is connected, arbitrary UTF-8 (including Chinese and // emoji) is injected via the Guest Tools bridge + QMP Command+V; otherwise pure // US-ASCII falls back to direct QMP USB keyboard strokes (works in Recovery and -// at the Login Window). -func (a *App) TypeText(name, text string) (int, error) { - return a.TypeTextWithDriver("", name, text) -} - -// TypeTextWithDriver types into the VM that driverID owns, so two VMs with the -// same name under different drivers never share a typing job. -func (a *App) TypeTextWithDriver(driverID, name, text string) (int, error) { +// at the Login Window). Two VMs with the same name under different drivers never +// share a typing job. +func (a *App) TypeText(driverID, name, text string) (int, error) { return a.injectTextIntoVMForDriver(driverID, name, "", text, false, false) } @@ -332,10 +327,7 @@ func (a *App) runRemoteTextQueue(key, vmName string, ch <-chan remoteTextItem) { } // TypeClipboard types or injects the host clipboard's text into a running VM. -func (a *App) TypeClipboard(name string) (int, error) { return a.TypeClipboardWithDriver("", name) } - -// TypeClipboardWithDriver types the clipboard into the VM that driverID owns. -func (a *App) TypeClipboardWithDriver(driverID, name string) (int, error) { +func (a *App) TypeClipboard(driverID, name string) (int, error) { if a.ctx == nil { return 0, errors.New("no window") } @@ -346,5 +338,5 @@ func (a *App) TypeClipboardWithDriver(driverID, name string) (int, error) { if text == "" { return 0, errors.New("the clipboard has no text") } - return a.TypeTextWithDriver(driverID, name, text) + return a.TypeText(driverID, name, text) } diff --git a/internal/app/vm_close_windows.go b/internal/app/vm_close_windows.go index 71e2068..28c2708 100644 --- a/internal/app/vm_close_windows.go +++ b/internal/app/vm_close_windows.go @@ -49,7 +49,7 @@ func (a *App) confirmVMWindowClose(name string) { ref = vm.Ref() canSuspend = slices.Contains(vm.Capabilities, driver.CapSuspend) } - label := strings.TrimSpace(a.GetVMNote(ref.Name)) + label := strings.TrimSpace(a.GetVMNote(ref.DriverID, ref.Name)) if label == "" { label = ref.Name } diff --git a/internal/app/vmref_test.go b/internal/app/vmref_test.go index e9c4d7f..00a21f7 100644 --- a/internal/app/vmref_test.go +++ b/internal/app/vmref_test.go @@ -32,7 +32,7 @@ func TestSameNamedVMMemoryStatesUseDriverQualifiedKeys(t *testing.T) { t.Fatal("driver-qualified cache keys collided") } a.cfg = &config.Config{DataRoot: t.TempDir()} - if a.thumbPathForDriver("test.driver.a", "shared") == a.thumbPathForDriver("test.driver.b", "shared") { + if a.thumbPath("test.driver.a", "shared") == a.thumbPath("test.driver.b", "shared") { t.Fatal("same-named VMs share a thumbnail path") } } diff --git a/internal/app/window_launch.go b/internal/app/window_launch.go index 14f15eb..1c8a3d0 100644 --- a/internal/app/window_launch.go +++ b/internal/app/window_launch.go @@ -21,7 +21,7 @@ func (a *App) afterStartup() { noTray := a.trayMgr == nil a.mu.Unlock() if launch.Background && noTray { - a.ShowMainWindow() + a.showMainWindow() } a.handleWindowArgs(launch, false) } @@ -47,7 +47,7 @@ func (a *App) handleWindowArgs(w cli.WindowArgs, secondLaunch bool) { } if w.StartVM == "" && w.ResumeVM == "" { if secondLaunch && !w.Background { - a.ShowMainWindow() + a.showMainWindow() } return } @@ -65,7 +65,7 @@ func (a *App) handleWindowArgs(w cli.WindowArgs, secondLaunch bool) { capture := a.captureLogs(key) var err error if w.ResumeVM != "" { - err = a.ResumeVMWithDriver(w.StartDriver, name) + err = a.ResumeVM(w.StartDriver, name) } else { err = a.startHandedVM(w.StartDriver, name) } @@ -84,7 +84,7 @@ func (a *App) handleWindowArgs(w cli.WindowArgs, secondLaunch bool) { } func (a *App) startHandedVM(driverID, name string) error { - return a.StartVMWithDriver(driverID, name) + return a.StartVM(driverID, name) } // logCapture keeps the last few log lines one source emits while it is diff --git a/internal/archtest/bindings_test.go b/internal/archtest/bindings_test.go new file mode 100644 index 0000000..dbbf2ed --- /dev/null +++ b/internal/archtest/bindings_test.go @@ -0,0 +1,86 @@ +package archtest + +import ( + "go/ast" + "io/fs" + "os" + "path/filepath" + "regexp" + "strings" + "testing" +) + +// TestWindowBindingsMatch keeps the methods App exposes to the window in step +// with the frontend: Wails exposes every exported method, so each one needs a +// caller, and frontend/wailsjs must be regenerated after a change +// (wails generate module). +func TestWindowBindingsMatch(t *testing.T) { + generated := map[string]bool{} + raw, err := os.ReadFile("../../frontend/wailsjs/go/app/App.d.ts") + if err != nil { + t.Fatal(err) + } + for _, m := range regexp.MustCompile(`export function (\w+)\(`).FindAllStringSubmatch(string(raw), -1) { + generated[m[1]] = true + } + + used := map[string]bool{} + call := regexp.MustCompile(`\b(?:api|boundGo)\.(\w+)`) + err = filepath.WalkDir("../../frontend/src", func(p string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() || !strings.Contains(filepath.Ext(p), ".ts") { + return err + } + src, err := os.ReadFile(p) + for _, m := range call.FindAllStringSubmatch(string(src), -1) { + used[m[1]] = true + } + return err + }) + if err != nil { + t.Fatal(err) + } + + exported := map[string]bool{} + for _, s := range sources(t) { + if s.rel == "main.go" { + ast.Inspect(s.file, func(n ast.Node) bool { + if sel, ok := n.(*ast.SelectorExpr); ok { + used[sel.Sel.Name] = true + } + return true + }) + } + if s.isTest() || s.dir() != "internal/app" { + continue + } + for _, decl := range s.file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Recv == nil || !fn.Name.IsExported() { + continue + } + star, ok := fn.Recv.List[0].Type.(*ast.StarExpr) + if !ok { + continue + } + if id, ok := star.X.(*ast.Ident); ok && id.Name == "App" { + exported[fn.Name.Name] = true + } + } + } + if len(exported) < 100 || len(generated) < 100 { + t.Fatalf("found only %d App methods and %d generated bindings", len(exported), len(generated)) + } + for name := range exported { + if !used[name] { + t.Errorf("the window never calls App.%s: delete or unexport it", name) + } + if !generated[name] { + t.Errorf("App.%s is missing from frontend/wailsjs: run wails generate module", name) + } + } + for name := range generated { + if !exported[name] { + t.Errorf("frontend/wailsjs still has App.%s: run wails generate module", name) + } + } +} diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 265b4f4..f72a96b 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -508,7 +508,7 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e if fs.NArg() < 1 { return fmt.Errorf("usage: reims-go vm start [--driver ] ") } - return startVMWithDriver(ctx, cfg, *driverID, fs.Arg(0), viaWindow) + return startVM(ctx, cfg, *driverID, fs.Arg(0), viaWindow) case "stop": fs := flag.NewFlagSet("vm stop", flag.ContinueOnError) driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") diff --git a/internal/cli/macos_native.go b/internal/cli/macos_native.go index b58c8e0..db79ec4 100644 --- a/internal/cli/macos_native.go +++ b/internal/cli/macos_native.go @@ -119,7 +119,7 @@ func createMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, in } } if startAfterCreate { - if err := startVMWithDriver(ctx, cfg, driver.BuiltinReimsMacOSDriverID, in.Name, viaWindow); err != nil { + if err := startVM(ctx, cfg, driver.BuiltinReimsMacOSDriverID, in.Name, viaWindow); err != nil { return err } } diff --git a/internal/cli/start.go b/internal/cli/start.go index 50c2334..078a7ff 100644 --- a/internal/cli/start.go +++ b/internal/cli/start.go @@ -21,14 +21,14 @@ import ( // report back. Preparation can rebuild the OpenCore image before QEMU starts. const startHandoffTimeout = 5 * time.Minute -// startVMWithDriver resolves the VM, then hands it to the desktop window: the +// startVM resolves the VM, then hands it to the desktop window: the // one already running, or a new one in the tray (`--background`). The window // runs the GUI's StartVM, so a VM started from the command line gets Guest // Tools and the Win10 cold-reboot watcher too; both need a process that stays // up after this command exits. // // 显式传入管理器当前数据目录仍交给管理器;其他目录的桥接禁止直接启动。 -func startVMWithDriver(ctx context.Context, cfg *config.Config, driverID, name string, viaWindow bool) error { +func startVM(ctx context.Context, cfg *config.Config, driverID, name string, viaWindow bool) error { mgr, router, err := openCLIPluginManager(cfg, false) if err != nil { return err diff --git a/internal/plugin/manager_sidecar_test.go b/internal/plugin/manager_sidecar_test.go index 2bd296e..0b30f4d 100644 --- a/internal/plugin/manager_sidecar_test.go +++ b/internal/plugin/manager_sidecar_test.go @@ -222,7 +222,7 @@ func TestTransactionalInstallSigningRedlinesAndThemeDoctor(t *testing.T) { Parts: []string{"rg-p-sidebar"}, Tokens: []string{"--surface-sidebar"}, } - findings := plugin.DoctorDirectory(info.InstallDir, "0.2.6", contract) + findings := plugin.ScanDirectory(info.InstallDir, "0.2.6", plugin.ScanOptions{Contract: contract}).ToDoctorFindings() for _, f := range findings { if f.Severity == "error" || f.Severity == "warn" { t.Fatalf("unexpected doctor finding on valid theme: %+v", f) diff --git a/internal/plugin/package.go b/internal/plugin/package.go index 3c6ac4e..63a59c2 100644 --- a/internal/plugin/package.go +++ b/internal/plugin/package.go @@ -684,16 +684,6 @@ func InstallArchive(layout PluginsLayout, archivePath string, opts PackageInstal }, nil } -// DoctorDirectory validates a plugin directory (installed or local dev link), -// checking manifest, SHA256SUMS (if present), static risk rules, CSS safety, -// and UI contract compliance (§5.1, §10). -func DoctorDirectory(dir string, hostVersion string, contract *UIContract) []DoctorFinding { - return ScanDirectory(dir, hostVersion, ScanOptions{ - Contract: contract, - RequireChecksums: false, - }).ToDoctorFindings() -} - var ( reCSSClass = regexp.MustCompile(`\.([a-zA-Z_-][a-zA-Z0-9_-]*)`) reCSSVar = regexp.MustCompile(`var\(\s*(--[a-zA-Z0-9_-]+)`) diff --git a/internal/plugin/scanner.go b/internal/plugin/scanner.go index e02596b..ff07e89 100644 --- a/internal/plugin/scanner.go +++ b/internal/plugin/scanner.go @@ -561,8 +561,7 @@ func finalizeScanReport(rep *ScanReport) { } } -// ToDoctorFindings converts a ScanReport into backward-compatible DoctorFinding -// entries so `DoctorDirectory` and existing callers/tests share one engine. +// ToDoctorFindings lists a ScanReport's results the way `plugin doctor` prints them. func (r ScanReport) ToDoctorFindings() []DoctorFinding { var out []DoctorFinding hasManifestErr := false From 128ffa94ad30d38d704fe75af87fc6412b3a11c3 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: Thu, 3 Dec 2026 21:17:04 -0700 Subject: [PATCH 05/22] style: remove CSS classes no component uses Co-Authored-By: Claude Opus 5.5 --- frontend/scripts/test-unused-css.mjs | 24 +++++++++++++++ frontend/src/styles/app.css | 46 ++-------------------------- 2 files changed, 26 insertions(+), 44 deletions(-) create mode 100644 frontend/scripts/test-unused-css.mjs diff --git a/frontend/scripts/test-unused-css.mjs b/frontend/scripts/test-unused-css.mjs new file mode 100644 index 0000000..11b6287 --- /dev/null +++ b/frontend/scripts/test-unused-css.mjs @@ -0,0 +1,24 @@ +// Rejects classes in app.css that no source file uses. A class built from a +// template such as `status-${kind}` counts as used by its prefix. +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' + +const src = path.resolve(import.meta.dirname, '..', 'src') + +test('every class in app.css is used', () => { + const code = fs.readdirSync(src, { recursive: true }) + .filter((name) => /\.tsx?$/.test(name)) + .map((name) => fs.readFileSync(path.join(src, name), 'utf8')) + .join('\n') + const css = fs.readFileSync(path.join(src, 'styles', 'app.css'), 'utf8') + .replace(/\/\*[\s\S]*?\*\//g, '') + .replace(/url\([^)]*\)|"[^"]*"/g, '') + + const words = new Set(code.match(/[A-Za-z_][\w-]*/g)) + const prefixes = [...code.matchAll(/([A-Za-z][\w-]*-)\$\{/g)].map((m) => m[1]) + const classes = new Set([...css.matchAll(/\.([A-Za-z_][\w-]*)/g)].map((m) => m[1])) + assert.ok(classes.size > 300, `found only ${classes.size} classes in app.css`) + assert.deepEqual([...classes].filter((c) => !words.has(c) && !prefixes.some((p) => c.startsWith(p))), []) +}) diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 51a7955..1ddac6b 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -22,7 +22,7 @@ html, body, #root { html:lang(ja) { line-break: strict; } html:lang(ko) { word-break: keep-all; } :is(:lang(zh), :lang(ja), :lang(ko)) :is(em, i) { font-style: normal; font-weight: var(--fw-medium); } -:is(:lang(zh), :lang(ja), :lang(ko)) :is(.brand, .sidebar-head, .sidebar-section-label, .sidebar-brand-name, .about-hero-text h1) { +:is(:lang(zh), :lang(ja), :lang(ko)) :is(.brand, .sidebar-head, .sidebar-brand-name, .about-hero-text h1) { letter-spacing: var(--heading-tracking, 0em); } @@ -166,12 +166,6 @@ h1, h2, h3, p { margin: 0; } font-size: var(--fs-13); font-weight: var(--fw-strong); letter-spacing: -0.01em; color: var(--text); } -.sidebar-section-label { - padding: 4px 10px 4px; - font-size: var(--fs-13); font-weight: var(--fw-strong); letter-spacing: -0.01em; - color: var(--text); -} -.sidebar-sep { height: 1px; background: var(--border); margin: 8px 10px 6px; } .sidebar-brand { display: flex; align-items: center; gap: 9px; padding: 2px 4px 12px 8px; min-height: 34px; @@ -321,7 +315,6 @@ h1, h2, h3, p { margin: 0; } .page-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); min-height: 34px; } .page-title { display: flex; align-items: center; gap: 10px; min-width: 0; } .page-title h1 { font-size: 18px; font-weight: var(--fw-strong); letter-spacing: -0.015em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.state-text { display: inline-flex; align-items: center; gap: 6px; font-size: var(--fs-12); color: var(--text-2); white-space: nowrap; } .actions { display: flex; align-items: center; gap: 6px; flex-shrink: 0; } /* ── macOS Tahoe "About This Mac" Hero ─────────────────── */ @@ -499,24 +492,6 @@ h1, h2, h3, p { margin: 0; } display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); min-height: 26px; } -.tahoe-group { - background: var(--surface-1); - border: 1px solid var(--border); - border-radius: var(--r-lg); - overflow: hidden; -} -.tahoe-row { - display: flex; align-items: center; justify-content: space-between; gap: 16px; - min-height: 40px; padding: 9px 16px; - position: relative; font-size: 13.5px; -} -.tahoe-row + .tahoe-row::before { - content: ""; position: absolute; top: 0; left: 16px; right: 16px; - height: 1px; background: var(--border); -} -.tahoe-label { color: var(--text); font-weight: var(--fw-regular); display: inline-flex; align-items: center; gap: 10px; flex-shrink: 0; } -.tahoe-value { color: var(--text-2); text-align: right; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; user-select: text; } - /* ── Buttons ───────────────────────────────────────────── */ .btn { height: 31px; padding: 0 13px; @@ -605,12 +580,6 @@ h1, h2, h3, p { margin: 0; } display: flex; align-items: flex-start; gap: 12px; font-size: var(--fs-13); color: var(--text-2); line-height: 1.55; } -.guide-step-num { - width: 22px; height: 22px; border-radius: 50%; flex-shrink: 0; margin-top: 1px; - display: grid; place-items: center; - background: var(--accent-soft); color: var(--accent-soft-text); - font-size: var(--fs-11); font-weight: var(--fw-strong); font-variant-numeric: tabular-nums; -} .guide-step-body { flex: 1; min-width: 0; } .steps { margin: 0; padding-left: var(--sp-6); display: flex; flex-direction: column; gap: var(--sp-1); color: var(--text-2); font-size: var(--fs-13); } @@ -623,8 +592,6 @@ h1, h2, h3, p { margin: 0; } .cmd-line > svg { color: var(--text-3); flex-shrink: 0; } .cmd-line code { flex: 1; min-width: 0; font-family: var(--font-mono); font-size: var(--fs-12); color: var(--text-code); user-select: text; overflow-wrap: anywhere; } .cmd-line-spaced { margin-top: 6px; } - -.tech-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); } .tech > summary { list-style: none; cursor: pointer; display: inline-flex; align-items: center; gap: var(--sp-1); padding: 4px 6px; margin-left: -6px; @@ -897,8 +864,6 @@ button.status-issue + .status-metric { margin-left: 6px; } .status-metric.high { color: var(--danger-text); } .status-metric.high > svg { color: var(--danger-text); } .status-metric.ok { color: var(--ok-text); } -.status-metric-dim { color: var(--text-3); } -.status-sep { color: var(--border-strong); flex-shrink: 0; } .status-mini-bar { display: inline-block; width: 34px; height: 4px; border-radius: 999px; background: var(--surface-active); overflow: hidden; flex-shrink: 0; @@ -1065,7 +1030,6 @@ button.status-issue + .status-metric { margin-left: 6px; } .field { display: flex; flex-direction: column; gap: 6px; } .field-spaced { margin-top: 10px; } .field-label { font-size: var(--fs-13); font-weight: var(--fw-medium); color: var(--text-2); } -.field-row { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-4); } .input, .select { width: 100%; height: 32px; padding: 0 10px; border-radius: var(--r-md); border: 1px solid var(--border-strong); @@ -1377,12 +1341,6 @@ button.status-issue + .status-metric { margin-left: 6px; } .guide-cmd { margin-top: var(--sp-2); } /* ── Telemetry meter (GPU compositor scaleX) ───────────── */ -.resource-meter { - height: 5px; - border-radius: 999px; - background: var(--surface-active); - overflow: hidden; -} .meter-fill { display: block; width: 100%; @@ -2072,7 +2030,7 @@ button.status-issue + .status-metric { margin-left: 6px; } } @media (max-width: 640px) { - .source-cards, .field-row, .review-groups { grid-template-columns: 1fr; } + .source-cards, .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)); } From 5c1a280271488669a822c94f108c5ce7bdbc7484 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: Thu, 3 Dec 2026 21:20:53 -0700 Subject: [PATCH 06/22] refactor(plugin): share the registry and localization boilerplate Registering, listing and counting contributions each had one copy per contribution kind, and so did overriding their text from language packs. One generic helper now covers each. Co-Authored-By: Claude Opus 5.5 --- internal/plugin/broker.go | 8 +- internal/plugin/job_windows.go | 6 +- internal/plugin/locale_test.go | 1 - internal/plugin/manager.go | 208 ++++++++--------------- internal/plugin/registry.go | 293 +++++++-------------------------- internal/plugin/rpc.go | 8 +- internal/plugin/scope.go | 4 +- 7 files changed, 142 insertions(+), 386 deletions(-) diff --git a/internal/plugin/broker.go b/internal/plugin/broker.go index 8c3ccc7..f5ee117 100644 --- a/internal/plugin/broker.go +++ b/internal/plugin/broker.go @@ -44,10 +44,10 @@ type Broker struct { procs map[int]*ManagedProcess procsByRef map[string]*ManagedProcess // VMs being spawned right now, so two requests cannot both start one. - spawning map[string]bool - onNotify func(pluginID, title, body string) - onVMExit func(driverID, vmName string) - onVMState func(pluginID string, rep ReportedVMState) error + spawning map[string]bool + onNotify func(pluginID, title, body string) + onVMExit func(driverID, vmName string) + onVMState func(pluginID string, rep ReportedVMState) error } type rateWindow struct { diff --git a/internal/plugin/job_windows.go b/internal/plugin/job_windows.go index 8776653..ccf5be5 100644 --- a/internal/plugin/job_windows.go +++ b/internal/plugin/job_windows.go @@ -14,9 +14,9 @@ import ( ) const ( - createNoWindow = 0x08000000 - createBreakawayFromJob = 0x01000000 - createNewProcessGroup = 0x00000200 + createNoWindow = 0x08000000 + createBreakawayFromJob = 0x01000000 + createNewProcessGroup = 0x00000200 ) func configureSidecarCmd(cmd *exec.Cmd) { diff --git a/internal/plugin/locale_test.go b/internal/plugin/locale_test.go index e70d243..1d068af 100644 --- a/internal/plugin/locale_test.go +++ b/internal/plugin/locale_test.go @@ -548,4 +548,3 @@ func TestCommunityLocaleTrustBoundaryAndNoInUseWakeup(t *testing.T) { t.Fatalf("community pack failed to fill missing fr-FR name: %+v", localized[0].Name) } } - diff --git a/internal/plugin/manager.go b/internal/plugin/manager.go index 5612917..82b6433 100644 --- a/internal/plugin/manager.go +++ b/internal/plugin/manager.go @@ -8,6 +8,7 @@ import ( "net/url" "os" "path/filepath" + "slices" "sort" "strings" "sync" @@ -1807,170 +1808,93 @@ func (m *Manager) LocalizePluginInfos(infos []PluginInfo) []PluginInfo { return out } -// LocalizeMenus applies active Language Pack manifest overrides onto MenuContribution titles. +// overridableText is a contribution text that a Language Pack may replace, and +// the override fields that do so, in order of preference. +type overridableText struct { + text *LocalizedText + keys []string +} + +// localizeContributions returns a copy of items with the active Language Pack +// overrides applied to the texts that texts lists for each item. +func localizeContributions[T any](m *Manager, items []T, texts func(*T) (pluginID string, list []overridableText)) []T { + ovs := m.activeManifestOverrides() + if len(ovs) == 0 || len(items) == 0 { + return items + } + out := slices.Clone(items) + for i := range out { + pluginID, list := texts(&out[i]) + for _, t := range list { + if len(ovs[pluginID]) > 0 { + *t.text = cloneLocalizedText(*t.text) + } + for _, r := range ovs[pluginID] { + if v := firstNonEmptyField(r.ov.Fields, t.keys...); v != "" { + applyLocalizedOverride(t.text, r.locale, v, r.privileged) + } + } + } + } + return out +} + +// LocalizeMenus applies Language Pack overrides to menu titles. func (m *Manager) LocalizeMenus(items []MenuContribution) []MenuContribution { - ovs := m.activeManifestOverrides() - if len(ovs) == 0 || len(items) == 0 { - return items - } - out := make([]MenuContribution, len(items)) - for i, it := range items { - cp := it - if list := ovs[it.PluginID]; len(list) > 0 { - cp.Title = cloneLocalizedText(it.Title) - for _, r := range list { - if v := firstNonEmptyField(r.ov.Fields, "menu."+it.ID+".title", "command."+it.Command+".title"); v != "" { - applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged) - } - } - } - out[i] = cp - } - return out + return localizeContributions(m, items, func(c *MenuContribution) (string, []overridableText) { + return c.PluginID, []overridableText{{&c.Title, []string{"menu." + c.ID + ".title", "command." + c.Command + ".title"}}} + }) } -// LocalizePanels applies active Language Pack manifest overrides onto PanelContribution titles. +// LocalizePanels applies Language Pack overrides to panel titles. func (m *Manager) LocalizePanels(items []PanelContribution) []PanelContribution { - ovs := m.activeManifestOverrides() - if len(ovs) == 0 || len(items) == 0 { - return items - } - out := make([]PanelContribution, len(items)) - for i, it := range items { - cp := it - if list := ovs[it.PluginID]; len(list) > 0 { - cp.Title = cloneLocalizedText(it.Title) - for _, r := range list { - if v := firstNonEmptyField(r.ov.Fields, "panel."+it.ID+".title"); v != "" { - applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged) - } - } - } - out[i] = cp - } - return out + return localizeContributions(m, items, func(c *PanelContribution) (string, []overridableText) { + return c.PluginID, []overridableText{{&c.Title, []string{"panel." + c.ID + ".title"}}} + }) } -// LocalizeViews applies active Language Pack manifest overrides onto ViewContribution titles. +// LocalizeViews applies Language Pack overrides to view titles. func (m *Manager) LocalizeViews(items []ViewContribution) []ViewContribution { - ovs := m.activeManifestOverrides() - if len(ovs) == 0 || len(items) == 0 { - return items - } - out := make([]ViewContribution, len(items)) - for i, it := range items { - cp := it - if list := ovs[it.PluginID]; len(list) > 0 { - cp.Title = cloneLocalizedText(it.Title) - for _, r := range list { - if v := firstNonEmptyField(r.ov.Fields, "view."+it.ID+".title"); v != "" { - applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged) - } - } - } - out[i] = cp - } - return out + return localizeContributions(m, items, func(c *ViewContribution) (string, []overridableText) { + return c.PluginID, []overridableText{{&c.Title, []string{"view." + c.ID + ".title"}}} + }) } -// LocalizeImageSources applies active Language Pack manifest overrides onto ImageSourceContribution labels. +// LocalizeImageSources applies Language Pack overrides to image source titles and descriptions. func (m *Manager) LocalizeImageSources(items []ImageSourceContribution) []ImageSourceContribution { - ovs := m.activeManifestOverrides() - if len(ovs) == 0 || len(items) == 0 { - return items - } - out := make([]ImageSourceContribution, len(items)) - for i, it := range items { - cp := it - if list := ovs[it.PluginID]; len(list) > 0 { - cp.Title = cloneLocalizedText(it.Title) - cp.Description = cloneLocalizedText(it.Description) - for _, r := range list { - if v := firstNonEmptyField(r.ov.Fields, "imageSource."+it.ID+".title"); v != "" { - applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged) - } - if v := firstNonEmptyField(r.ov.Fields, "imageSource."+it.ID+".description"); v != "" { - applyLocalizedOverride(&cp.Description, r.locale, v, r.privileged) - } - } + return localizeContributions(m, items, func(c *ImageSourceContribution) (string, []overridableText) { + return c.PluginID, []overridableText{ + {&c.Title, []string{"imageSource." + c.ID + ".title"}}, + {&c.Description, []string{"imageSource." + c.ID + ".description"}}, } - out[i] = cp - } - return out + }) } -// LocalizeVMCards applies active Language Pack manifest overrides onto VMCardContribution labels. +// LocalizeVMCards applies Language Pack overrides to VM card titles and values. func (m *Manager) LocalizeVMCards(items []VMCardContribution) []VMCardContribution { - ovs := m.activeManifestOverrides() - if len(ovs) == 0 || len(items) == 0 { - return items - } - out := make([]VMCardContribution, len(items)) - for i, it := range items { - cp := it - if list := ovs[it.PluginID]; len(list) > 0 { - cp.Title = cloneLocalizedText(it.Title) - cp.Value = cloneLocalizedText(it.Value) - for _, r := range list { - if v := firstNonEmptyField(r.ov.Fields, "vmCard."+it.ID+".title"); v != "" { - applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged) - } - if v := firstNonEmptyField(r.ov.Fields, "vmCard."+it.ID+".value"); v != "" { - applyLocalizedOverride(&cp.Value, r.locale, v, r.privileged) - } - } + return localizeContributions(m, items, func(c *VMCardContribution) (string, []overridableText) { + return c.PluginID, []overridableText{ + {&c.Title, []string{"vmCard." + c.ID + ".title"}}, + {&c.Value, []string{"vmCard." + c.ID + ".value"}}, } - out[i] = cp - } - return out + }) } -// LocalizeSettingsPages applies active Language Pack manifest overrides onto SettingsPageContribution titles. +// LocalizeSettingsPages applies Language Pack overrides to settings page titles. func (m *Manager) LocalizeSettingsPages(items []SettingsPageContribution) []SettingsPageContribution { - ovs := m.activeManifestOverrides() - if len(ovs) == 0 || len(items) == 0 { - return items - } - out := make([]SettingsPageContribution, len(items)) - for i, it := range items { - cp := it - if list := ovs[it.PluginID]; len(list) > 0 { - cp.Title = cloneLocalizedText(it.Title) - for _, r := range list { - if v := firstNonEmptyField(r.ov.Fields, "settingsPage."+it.ID+".title"); v != "" { - applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged) - } - } - } - out[i] = cp - } - return out + return localizeContributions(m, items, func(c *SettingsPageContribution) (string, []overridableText) { + return c.PluginID, []overridableText{{&c.Title, []string{"settingsPage." + c.ID + ".title"}}} + }) } -// LocalizeStatusItems applies active Language Pack manifest overrides onto StatusItemContribution labels. +// LocalizeStatusItems applies Language Pack overrides to status item texts and tooltips. func (m *Manager) LocalizeStatusItems(items []StatusItemContribution) []StatusItemContribution { - ovs := m.activeManifestOverrides() - if len(ovs) == 0 || len(items) == 0 { - return items - } - out := make([]StatusItemContribution, len(items)) - for i, it := range items { - cp := it - if list := ovs[it.PluginID]; len(list) > 0 { - cp.Text = cloneLocalizedText(it.Text) - cp.Tooltip = cloneLocalizedText(it.Tooltip) - for _, r := range list { - if v := firstNonEmptyField(r.ov.Fields, "statusItem."+it.ID+".text"); v != "" { - applyLocalizedOverride(&cp.Text, r.locale, v, r.privileged) - } - if v := firstNonEmptyField(r.ov.Fields, "statusItem."+it.ID+".tooltip"); v != "" { - applyLocalizedOverride(&cp.Tooltip, r.locale, v, r.privileged) - } - } + return localizeContributions(m, items, func(c *StatusItemContribution) (string, []overridableText) { + return c.PluginID, []overridableText{ + {&c.Text, []string{"statusItem." + c.ID + ".text"}}, + {&c.Tooltip, []string{"statusItem." + c.ID + ".tooltip"}}, } - out[i] = cp - } - return out + }) } // CurrentLocale returns the active effective host locale for plugin operations. diff --git a/internal/plugin/registry.go b/internal/plugin/registry.go index abfa6e9..15ba382 100644 --- a/internal/plugin/registry.go +++ b/internal/plugin/registry.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "slices" "sort" "strings" "sync" @@ -764,6 +765,42 @@ func (r *Registry) LookupService(name string) (any, bool) { // --- Extension point registration (all reversible via Scope.OnDispose) --- +// addScoped appends item to list until sc is disposed. admit, when set, decides +// under the lock whether the list still takes it; same finds the item again. +func addScoped[T any](r *Registry, sc *Scope, list *[]T, item T, same func(T) bool, admit func() bool) { + r.mu.Lock() + ok := admit == nil || admit() + if ok { + *list = append(*list, item) + } + r.mu.Unlock() + if !ok { + return + } + sc.OnDispose(func() { + r.mu.Lock() + *list = slices.DeleteFunc(*list, same) + r.mu.Unlock() + }) +} + +// listScoped copies a list for a reader; the copy is never nil. +func listScoped[T any](r *Registry, list *[]T) []T { + r.mu.RLock() + defer r.mu.RUnlock() + return append([]T{}, *list...) +} + +func countFunc[T any](list []T, match func(T) bool) int { + n := 0 + for _, item := range list { + if match(item) { + n++ + } + } + return n +} + func (r *Registry) RegisterTheme(sc *Scope, th ThemeContribution) { if th.ID == "" { return @@ -969,86 +1006,31 @@ func (r *Registry) RegisterInputFilter(sc *Scope, flt InputFilterContribution) { return } flt.PluginID = sc.PluginID() - r.mu.Lock() - r.inputFilters = append(r.inputFilters, flt) - r.mu.Unlock() - sc.OnDispose(func() { - r.mu.Lock() - kept := r.inputFilters[:0] - for _, item := range r.inputFilters { - if !(item.PluginID == sc.PluginID() && item.ID == flt.ID) { - kept = append(kept, item) - } - } - r.inputFilters = kept - r.mu.Unlock() - }) + addScoped(r, sc, &r.inputFilters, flt, func(x InputFilterContribution) bool { return x.PluginID == flt.PluginID && x.ID == flt.ID }, nil) } -func (r *Registry) InputFilters() []InputFilterContribution { - r.mu.RLock() - defer r.mu.RUnlock() - out := make([]InputFilterContribution, len(r.inputFilters)) - copy(out, r.inputFilters) - return out -} +func (r *Registry) InputFilters() []InputFilterContribution { return listScoped(r, &r.inputFilters) } func (r *Registry) RegisterVMTemplate(sc *Scope, tpl VMTemplateContribution) { if tpl.ID == "" { return } tpl.PluginID = sc.PluginID() - r.mu.Lock() - r.vmTemplates = append(r.vmTemplates, tpl) - r.mu.Unlock() - sc.OnDispose(func() { - r.mu.Lock() - kept := r.vmTemplates[:0] - for _, item := range r.vmTemplates { - if !(item.PluginID == sc.PluginID() && item.ID == tpl.ID) { - kept = append(kept, item) - } - } - r.vmTemplates = kept - r.mu.Unlock() - }) + addScoped(r, sc, &r.vmTemplates, tpl, func(x VMTemplateContribution) bool { return x.PluginID == tpl.PluginID && x.ID == tpl.ID }, nil) } -func (r *Registry) VMTemplates() []VMTemplateContribution { - r.mu.RLock() - defer r.mu.RUnlock() - out := make([]VMTemplateContribution, len(r.vmTemplates)) - copy(out, r.vmTemplates) - return out -} +func (r *Registry) VMTemplates() []VMTemplateContribution { return listScoped(r, &r.vmTemplates) } func (r *Registry) RegisterRuntimeSource(sc *Scope, rs RuntimeSourceContribution) { if rs.ID == "" || rs.IndexURL == "" { return } rs.PluginID = sc.PluginID() - r.mu.Lock() - r.runtimeSources = append(r.runtimeSources, rs) - r.mu.Unlock() - sc.OnDispose(func() { - r.mu.Lock() - kept := r.runtimeSources[:0] - for _, item := range r.runtimeSources { - if !(item.PluginID == sc.PluginID() && item.ID == rs.ID) { - kept = append(kept, item) - } - } - r.runtimeSources = kept - r.mu.Unlock() - }) + addScoped(r, sc, &r.runtimeSources, rs, func(x RuntimeSourceContribution) bool { return x.PluginID == rs.PluginID && x.ID == rs.ID }, nil) } func (r *Registry) RuntimeSources() []RuntimeSourceContribution { - r.mu.RLock() - defer r.mu.RUnlock() - out := make([]RuntimeSourceContribution, len(r.runtimeSources)) - copy(out, r.runtimeSources) - return out + return listScoped(r, &r.runtimeSources) } func (r *Registry) RegisterRuntimeKind(sc *Scope, rk RuntimeKindContribution) { @@ -1258,29 +1240,8 @@ func (r *Registry) RegisterMenu(sc *Scope, m MenuContribution) { return } m.PluginID = sc.PluginID() - r.mu.Lock() - count := 0 - for _, existing := range r.menus { - if existing.Slot == m.Slot { - count++ - } - } - if count >= DeclaredUISlots[m.Slot] { - r.mu.Unlock() - return - } - r.menus = append(r.menus, m) - r.mu.Unlock() - sc.OnDispose(func() { - r.mu.Lock() - kept := r.menus[:0] - for _, item := range r.menus { - if !(item.PluginID == sc.PluginID() && item.ID == m.ID) { - kept = append(kept, item) - } - } - r.menus = kept - r.mu.Unlock() + addScoped(r, sc, &r.menus, m, func(x MenuContribution) bool { return x.PluginID == m.PluginID && x.ID == m.ID }, func() bool { + return countFunc(r.menus, func(x MenuContribution) bool { return x.Slot == m.Slot }) < DeclaredUISlots[m.Slot] }) } @@ -1298,63 +1259,17 @@ func (r *Registry) Menus(slot string) []MenuContribution { func (r *Registry) RegisterVMCard(sc *Scope, c VMCardContribution) { c.PluginID = sc.PluginID() - r.mu.Lock() - if len(r.vmCards) >= DeclaredUISlots["vm.card"] { - r.mu.Unlock() - return - } - r.vmCards = append(r.vmCards, c) - r.mu.Unlock() - sc.OnDispose(func() { - r.mu.Lock() - kept := r.vmCards[:0] - for _, item := range r.vmCards { - if !(item.PluginID == sc.PluginID() && item.ID == c.ID) { - kept = append(kept, item) - } - } - r.vmCards = kept - r.mu.Unlock() - }) + addScoped(r, sc, &r.vmCards, c, func(x VMCardContribution) bool { return x.PluginID == c.PluginID && x.ID == c.ID }, func() bool { return len(r.vmCards) < DeclaredUISlots["vm.card"] }) } -func (r *Registry) VMCards() []VMCardContribution { - r.mu.RLock() - defer r.mu.RUnlock() - out := make([]VMCardContribution, len(r.vmCards)) - copy(out, r.vmCards) - return out -} +func (r *Registry) VMCards() []VMCardContribution { return listScoped(r, &r.vmCards) } func (r *Registry) RegisterSettingsPage(sc *Scope, sp SettingsPageContribution) { sp.PluginID = sc.PluginID() - r.mu.Lock() - if len(r.settingsPages) >= DeclaredUISlots["settings.plugin"] { - r.mu.Unlock() - return - } - r.settingsPages = append(r.settingsPages, sp) - r.mu.Unlock() - sc.OnDispose(func() { - r.mu.Lock() - kept := r.settingsPages[:0] - for _, item := range r.settingsPages { - if !(item.PluginID == sc.PluginID() && item.ID == sp.ID) { - kept = append(kept, item) - } - } - r.settingsPages = kept - r.mu.Unlock() - }) + addScoped(r, sc, &r.settingsPages, sp, func(x SettingsPageContribution) bool { return x.PluginID == sp.PluginID && x.ID == sp.ID }, func() bool { return len(r.settingsPages) < DeclaredUISlots["settings.plugin"] }) } -func (r *Registry) SettingsPages() []SettingsPageContribution { - r.mu.RLock() - defer r.mu.RUnlock() - out := make([]SettingsPageContribution, len(r.settingsPages)) - copy(out, r.settingsPages) - return out -} +func (r *Registry) SettingsPages() []SettingsPageContribution { return listScoped(r, &r.settingsPages) } func (r *Registry) RegisterStatusItem(sc *Scope, si StatusItemContribution) { if si.Slot == "" { @@ -1364,62 +1279,18 @@ func (r *Registry) RegisterStatusItem(sc *Scope, si StatusItemContribution) { return } si.PluginID = sc.PluginID() - r.mu.Lock() - if len(r.statusItems) >= DeclaredUISlots[si.Slot] { - r.mu.Unlock() - return - } - r.statusItems = append(r.statusItems, si) - r.mu.Unlock() - sc.OnDispose(func() { - r.mu.Lock() - kept := r.statusItems[:0] - for _, item := range r.statusItems { - if !(item.PluginID == sc.PluginID() && item.ID == si.ID) { - kept = append(kept, item) - } - } - r.statusItems = kept - r.mu.Unlock() - }) + addScoped(r, sc, &r.statusItems, si, func(x StatusItemContribution) bool { return x.PluginID == si.PluginID && x.ID == si.ID }, func() bool { return len(r.statusItems) < DeclaredUISlots[si.Slot] }) } -func (r *Registry) StatusItems() []StatusItemContribution { - r.mu.RLock() - defer r.mu.RUnlock() - out := make([]StatusItemContribution, len(r.statusItems)) - copy(out, r.statusItems) - return out -} +func (r *Registry) StatusItems() []StatusItemContribution { return listScoped(r, &r.statusItems) } func (r *Registry) RegisterPanel(sc *Scope, p PanelContribution) { if !IsDeclaredSlot(p.Slot) { return } p.PluginID = sc.PluginID() - r.mu.Lock() - count := 0 - for _, existing := range r.panels { - if existing.Slot == p.Slot { - count++ - } - } - if count >= DeclaredUISlots[p.Slot] { - r.mu.Unlock() - return - } - r.panels = append(r.panels, p) - r.mu.Unlock() - sc.OnDispose(func() { - r.mu.Lock() - kept := r.panels[:0] - for _, item := range r.panels { - if !(item.PluginID == sc.PluginID() && item.ID == p.ID) { - kept = append(kept, item) - } - } - r.panels = kept - r.mu.Unlock() + addScoped(r, sc, &r.panels, p, func(x PanelContribution) bool { return x.PluginID == p.PluginID && x.ID == p.ID }, func() bool { + return countFunc(r.panels, func(x PanelContribution) bool { return x.Slot == p.Slot }) < DeclaredUISlots[p.Slot] }) } @@ -1437,44 +1308,17 @@ func (r *Registry) Panels(slot string) []PanelContribution { func (r *Registry) RegisterView(sc *Scope, view ViewContribution) { view.ID = strings.TrimSpace(view.ID) - if view.ID == "" { - return - } location, ok := ViewLocationCatalog[view.Location] - if !ok { + if view.ID == "" || !ok { return } view.PluginID = sc.PluginID() - r.mu.Lock() - count := 0 - for _, existing := range r.views { - if existing.PluginID != view.PluginID { - continue - } - if existing.ID == view.ID { - r.mu.Unlock() - return - } - if existing.Location == view.Location { - count++ - } - } - if location.PerPlugin > 0 && count >= location.PerPlugin { - r.mu.Unlock() - return - } - r.views = append(r.views, view) - r.mu.Unlock() - sc.OnDispose(func() { - r.mu.Lock() - kept := r.views[:0] - for _, item := range r.views { - if !(item.PluginID == sc.PluginID() && item.ID == view.ID) { - kept = append(kept, item) - } - } - r.views = kept - r.mu.Unlock() + same := func(x ViewContribution) bool { return x.PluginID == view.PluginID && x.ID == view.ID } + addScoped(r, sc, &r.views, view, same, func() bool { + atLocation := countFunc(r.views, func(x ViewContribution) bool { + return x.PluginID == view.PluginID && x.Location == view.Location + }) + return !slices.ContainsFunc(r.views, same) && (location.PerPlugin <= 0 || atLocation < location.PerPlugin) }) } @@ -1569,20 +1413,9 @@ func (r *Registry) RegisterDiagnostics(sc *Scope, contrib DiagnosticsContributio return } contrib.PluginID = sc.PluginID() - r.mu.Lock() - r.diagnostics = append(r.diagnostics, RegisteredDiagnostics{Contribution: contrib, Collector: collector}) - r.mu.Unlock() - sc.OnDispose(func() { - r.mu.Lock() - kept := r.diagnostics[:0] - for _, item := range r.diagnostics { - if !(item.Contribution.PluginID == sc.PluginID() && item.Contribution.ID == contrib.ID) { - kept = append(kept, item) - } - } - r.diagnostics = kept - r.mu.Unlock() - }) + addScoped(r, sc, &r.diagnostics, RegisteredDiagnostics{Contribution: contrib, Collector: collector}, func(x RegisteredDiagnostics) bool { + return x.Contribution.PluginID == contrib.PluginID && x.Contribution.ID == contrib.ID + }, nil) } // CollectDiagnostics invokes all registered diagnostics collectors, skipping diff --git a/internal/plugin/rpc.go b/internal/plugin/rpc.go index aa9c4b8..6335c33 100644 --- a/internal/plugin/rpc.go +++ b/internal/plugin/rpc.go @@ -44,10 +44,10 @@ type RPCRequestHandler func(ctx context.Context, params json.RawMessage) (any, e // RPCConn implements bidirectional Content-Length framed JSON-RPC 2.0 over // stdio pipes with a single writer goroutine and bounded queue (§8). type RPCConn struct { - r *bufio.Reader - w io.Writer - writeCh chan []byte - closeCh chan struct{} + r *bufio.Reader + w io.Writer + writeCh chan []byte + closeCh chan struct{} closeOnce sync.Once nextID atomic.Uint64 diff --git a/internal/plugin/scope.go b/internal/plugin/scope.go index b08f8d6..5667a13 100644 --- a/internal/plugin/scope.go +++ b/internal/plugin/scope.go @@ -11,9 +11,9 @@ type Scope struct { pluginID string registry *Registry - mu sync.Mutex + mu sync.Mutex disposers []func() - disposed bool + disposed bool } func newScope(pluginID string, reg *Registry) *Scope { From a4e2ecc3ceeb98901c629715afc8035fd3c8b408 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: Thu, 3 Dec 2026 21:23:00 -0700 Subject: [PATCH 07/22] refactor(cli): split the plugin and vm commands by subcommand Each subcommand is its own function. Opening the lifecycle service, parsing a VM target, printing JSON and reading the UI contract had many copies and now have one. The vm usage line also lists delete, resize and compact. Co-Authored-By: Claude Opus 5.5 --- internal/cli/cli.go | 306 +++++++------- internal/cli/plugin.go | 914 ++++++++++++++++++++-------------------- internal/cli/start.go | 47 ++- internal/cli/suspend.go | 16 +- 4 files changed, 646 insertions(+), 637 deletions(-) diff --git a/internal/cli/cli.go b/internal/cli/cli.go index f72a96b..7c92845 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -163,9 +163,7 @@ func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error { "config": cfg, "runtime": active, } - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") - return enc.Encode(payload) + return printJSON(payload) } fmt.Printf("=== %s ===\n", i18n.T(loc, "doctor.title")) @@ -380,18 +378,17 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error { func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) error { if len(args) == 0 { - return fmt.Errorf("usage: reims-go vm ") + return fmt.Errorf("usage: reims-go vm ") } ctx := context.Background() switch args[0] { case "list": - mgr, router, err := openCLIPluginManager(cfg, false) + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) + defer closeService() vms, err := svc.List(ctx) if len(vms) == 0 { if err != nil { @@ -400,155 +397,41 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e fmt.Println(i18n.T(loc, "vm.empty")) return nil } - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") - return errors.Join(enc.Encode(vms), err) + return errors.Join(printJSON(vms), err) case "create": - fs := flag.NewFlagSet("vm create", flag.ContinueOnError) - driverID := fs.String("driver", driver.BuiltinReimsMacOSDriverID, "Guest VM driver ID (default: builtin.driver.reims-macos)") - dir := fs.String("dir", "", "Custom VM directory") - macos := fs.String("macos", "tahoe", "macOS version (e.g. tahoe)") - cpus := fs.Int("cpus", 8, "vCPU count") - mem := fs.String("memory", "16G", "RAM size (e.g. 8G, 16G)") - diskSize := fs.String("disk-size", "128G", "New disk size (e.g. 128G)") - gpu := fs.String("gpu", "auto", "GPU selector or Vulkan ICD JSON path") - capture := fs.Bool("capture", false, "Capture keyboard and mouse on window click") - logs := fs.Bool("logs", true, "Keep graphics and serial logs") - guestLang := fs.String("guest-lang", defaultMacOSGuestLang(loc), "macOS boot/recovery language prev-lang:kbd (e.g. zh-Hans:0, en-US:0)") - start := fs.Bool("start", false, "Start VM immediately after creation") - if err := fs.Parse(args[1:]); err != nil { - return err - } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go vm create [flags] ") - } - name := fs.Arg(0) - // Route non-reims guest drivers through the plugin Driver Router (§5.3, §10). - if strings.TrimSpace(*driverID) != "" && *driverID != driver.BuiltinReimsMacOSDriverID { - mgr, router, err := openCLIPluginManager(cfg, false) - if err != nil { - return err - } - defer mgr.Close() - drv, err := router.DriverByID(*driverID) - if err != nil { - return err - } - req := driver.CreateRequest{ - DriverID: drv.ID(), - Name: name, - Dir: *dir, - Options: map[string]any{ - "cpus": *cpus, - "memory": *mem, - "disk_size": *diskSize, - }, - } - if issues := drv.ValidateCreate(ctx, req); len(issues) > 0 { - return fmt.Errorf("%s", issues[0].Message) - } - if err := drv.Create(ctx, req, os.Stdout, os.Stderr); err != nil { - return err - } - if *start { - svc := lifecycle.New(mgr.Registry(), router, nil) - _, err := svc.Start(ctx, driver.NewVMRef(drv.ID(), name), os.Stdout, os.Stderr) - return err - } - return nil - } - return createMacOSVM(ctx, cfg, loc, macOSCreateOptions{Name: name, Dir: *dir, MacOS: *macos, CPUs: *cpus, Memory: *mem, DiskSize: *diskSize, GPU: *gpu, Capture: *capture, Logs: *logs, GuestLang: *guestLang}, *start, viaWindow) + return vmCreate(ctx, cfg, loc, args[1:], viaWindow) case "set": - fs := flag.NewFlagSet("vm set", flag.ContinueOnError) - driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") - cpus := fs.Int("cpus", 0, "vCPU count") - mem := fs.String("memory", "", "RAM size") - gpu := fs.String("gpu", "", "GPU selector or Vulkan ICD JSON") - res := fs.String("resolution", "", "Window resolution WIDTHxHEIGHT") - audioBackend := fs.String("audio-backend", "", "Audio backend (auto, dsound, none, wav)") - guestLang := fs.String("guest-lang", "", "macOS boot/recovery language prev-lang:kbd") - nestedVirt := fs.Bool("nested-virt", false, "Enable nested virtualization on the next cold start (macOS only)") - if err := fs.Parse(args[1:]); err != nil { - return err - } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go vm set [--driver ] [flags] ") - } - changes := map[string]any{} - if *cpus != 0 { - changes["cpus"] = *cpus - } - if *mem != "" { - changes["memory"] = *mem - } - if *gpu != "" { - changes["gpu"] = *gpu - } - if *res != "" { - changes["resolution"] = *res - } - if *audioBackend != "" { - changes["audio_backend"] = *audioBackend - } - if *guestLang != "" { - changes["guest_lang"] = *guestLang - } - fs.Visit(func(f *flag.Flag) { - if f.Name == "nested-virt" { - changes["nested_virt"] = *nestedVirt - } - }) - return setVM(ctx, cfg, *driverID, fs.Arg(0), changes) + return vmSet(ctx, cfg, args[1:]) case "start": - fs := flag.NewFlagSet("vm start", flag.ContinueOnError) - driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") - if err := fs.Parse(args[1:]); err != nil { + driverID, name, err := parseVMTarget(args) + if err != nil { return err } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go vm start [--driver ] ") - } - return startVM(ctx, cfg, *driverID, fs.Arg(0), viaWindow) + return startVM(ctx, cfg, driverID, name, viaWindow) case "stop": - fs := flag.NewFlagSet("vm stop", flag.ContinueOnError) - driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") - if err := fs.Parse(args[1:]); err != nil { + driverID, name, err := parseVMTarget(args) + if err != nil { return err } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go vm stop [--driver ] ") - } - return stopVM(ctx, cfg, *driverID, fs.Arg(0), false) + return stopVM(ctx, cfg, driverID, name) case "suspend": - fs := flag.NewFlagSet("vm suspend", flag.ContinueOnError) - driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") - if err := fs.Parse(args[1:]); err != nil { + driverID, name, err := parseVMTarget(args) + if err != nil { return err } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go vm suspend [--driver ] ") - } - return suspendVM(ctx, cfg, *driverID, fs.Arg(0)) + return suspendVM(ctx, cfg, driverID, name) case "resume": - fs := flag.NewFlagSet("vm resume", flag.ContinueOnError) - driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") - if err := fs.Parse(args[1:]); err != nil { + driverID, name, err := parseVMTarget(args) + if err != nil { return err } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go vm resume [--driver ] ") - } - return resumeVM(ctx, cfg, *driverID, fs.Arg(0), viaWindow) + return resumeVM(ctx, cfg, driverID, name, viaWindow) case "discard-suspend": - fs := flag.NewFlagSet("vm discard-suspend", flag.ContinueOnError) - driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") - if err := fs.Parse(args[1:]); err != nil { + driverID, name, err := parseVMTarget(args) + if err != nil { return err } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go vm discard-suspend [--driver ] ") - } - return discardSuspendVM(ctx, cfg, *driverID, fs.Arg(0)) + return discardSuspendVM(ctx, cfg, driverID, name) case "delete": fs := flag.NewFlagSet("vm delete", flag.ContinueOnError) driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") @@ -561,15 +444,11 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e } return deleteVM(ctx, cfg, *driverID, fs.Arg(0), *keepFiles) case "eject": - fs := flag.NewFlagSet("vm eject", flag.ContinueOnError) - driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") - if err := fs.Parse(args[1:]); err != nil { + driverID, name, err := parseVMTarget(args) + if err != nil { return err } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go vm eject [--driver ] ") - } - return actionVM(ctx, cfg, *driverID, fs.Arg(0), "eject", nil) + return actionVM(ctx, cfg, driverID, name, "eject", nil) case "type": return typeMacOSVM(ctx, cfg, loc, args) case "resize": @@ -588,25 +467,140 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e fmt.Println(i18n.T(loc, "vm.resize.done", fs.Arg(0), float64(res.OldVirtualBytes)/float64(1<<30), float64(res.NewVirtualBytes)/float64(1<<30), res.GuestExpandCmd)) return nil case "compact": - fs := flag.NewFlagSet("vm compact", flag.ContinueOnError) - driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") - if err := fs.Parse(args[1:]); err != nil { - return err - } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go vm compact [--driver ] ") - } - res, err := compactVM(ctx, cfg, *driverID, fs.Arg(0)) + driverID, name, err := parseVMTarget(args) if err != nil { return err } - fmt.Println(i18n.T(loc, "vm.compact.done", fs.Arg(0), float64(res.BeforeBytes)/float64(1<<30), float64(res.AfterBytes)/float64(1<<30), float64(res.ReclaimedBytes)/float64(1<<30))) + res, err := compactVM(ctx, cfg, driverID, name) + if err != nil { + return err + } + fmt.Println(i18n.T(loc, "vm.compact.done", name, float64(res.BeforeBytes)/float64(1<<30), float64(res.AfterBytes)/float64(1<<30), float64(res.ReclaimedBytes)/float64(1<<30))) return nil default: return fmt.Errorf("unknown vm subcommand %q", strings.Join(args, " ")) } } +// parseVMTarget parses " [--driver ] ". +func parseVMTarget(args []string) (driverID, name string, err error) { + fs := flag.NewFlagSet("vm "+args[0], flag.ContinueOnError) + fs.StringVar(&driverID, "driver", "", "Owning driver ID when VM names are ambiguous") + if err := fs.Parse(args[1:]); err != nil { + return "", "", err + } + if fs.NArg() < 1 { + return "", "", fmt.Errorf("usage: reims-go vm %s [--driver ] ", args[0]) + } + return driverID, fs.Arg(0), nil +} + +func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) error { + fs := flag.NewFlagSet("vm create", flag.ContinueOnError) + driverID := fs.String("driver", driver.BuiltinReimsMacOSDriverID, "Guest VM driver ID (default: builtin.driver.reims-macos)") + dir := fs.String("dir", "", "Custom VM directory") + macos := fs.String("macos", "tahoe", "macOS version (e.g. tahoe)") + cpus := fs.Int("cpus", 8, "vCPU count") + mem := fs.String("memory", "16G", "RAM size (e.g. 8G, 16G)") + diskSize := fs.String("disk-size", "128G", "New disk size (e.g. 128G)") + gpu := fs.String("gpu", "auto", "GPU selector or Vulkan ICD JSON path") + capture := fs.Bool("capture", false, "Capture keyboard and mouse on window click") + logs := fs.Bool("logs", true, "Keep graphics and serial logs") + guestLang := fs.String("guest-lang", defaultMacOSGuestLang(loc), "macOS boot/recovery language prev-lang:kbd (e.g. zh-Hans:0, en-US:0)") + start := fs.Bool("start", false, "Start VM immediately after creation") + if err := fs.Parse(args); err != nil { + return err + } + if fs.NArg() < 1 { + return fmt.Errorf("usage: reims-go vm create [flags] ") + } + name := fs.Arg(0) + // Route non-reims guest drivers through the plugin Driver Router (§5.3, §10). + if strings.TrimSpace(*driverID) != "" && *driverID != driver.BuiltinReimsMacOSDriverID { + mgr, router, err := openCLIPluginManager(cfg, false) + if err != nil { + return err + } + defer mgr.Close() + drv, err := router.DriverByID(*driverID) + if err != nil { + return err + } + req := driver.CreateRequest{ + DriverID: drv.ID(), + Name: name, + Dir: *dir, + Options: map[string]any{ + "cpus": *cpus, + "memory": *mem, + "disk_size": *diskSize, + }, + } + if issues := drv.ValidateCreate(ctx, req); len(issues) > 0 { + return fmt.Errorf("%s", issues[0].Message) + } + if err := drv.Create(ctx, req, os.Stdout, os.Stderr); err != nil { + return err + } + if *start { + svc := lifecycle.New(mgr.Registry(), router, nil) + _, err := svc.Start(ctx, driver.NewVMRef(drv.ID(), name), os.Stdout, os.Stderr) + return err + } + return nil + } + return createMacOSVM(ctx, cfg, loc, macOSCreateOptions{Name: name, Dir: *dir, MacOS: *macos, CPUs: *cpus, Memory: *mem, DiskSize: *diskSize, GPU: *gpu, Capture: *capture, Logs: *logs, GuestLang: *guestLang}, *start, viaWindow) +} + +func vmSet(ctx context.Context, cfg *config.Config, args []string) error { + fs := flag.NewFlagSet("vm set", flag.ContinueOnError) + driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") + cpus := fs.Int("cpus", 0, "vCPU count") + mem := fs.String("memory", "", "RAM size") + gpu := fs.String("gpu", "", "GPU selector or Vulkan ICD JSON") + res := fs.String("resolution", "", "Window resolution WIDTHxHEIGHT") + audioBackend := fs.String("audio-backend", "", "Audio backend (auto, dsound, none, wav)") + guestLang := fs.String("guest-lang", "", "macOS boot/recovery language prev-lang:kbd") + nestedVirt := fs.Bool("nested-virt", false, "Enable nested virtualization on the next cold start (macOS only)") + if err := fs.Parse(args); err != nil { + return err + } + if fs.NArg() < 1 { + return fmt.Errorf("usage: reims-go vm set [--driver ] [flags] ") + } + changes := map[string]any{} + if *cpus != 0 { + changes["cpus"] = *cpus + } + if *mem != "" { + changes["memory"] = *mem + } + if *gpu != "" { + changes["gpu"] = *gpu + } + if *res != "" { + changes["resolution"] = *res + } + if *audioBackend != "" { + changes["audio_backend"] = *audioBackend + } + if *guestLang != "" { + changes["guest_lang"] = *guestLang + } + fs.Visit(func(f *flag.Flag) { + if f.Name == "nested-virt" { + changes["nested_virt"] = *nestedVirt + } + }) + return setVM(ctx, cfg, *driverID, fs.Arg(0), changes) +} + +func printJSON(v any) error { + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + return enc.Encode(v) +} + // readOnlySafeCommand reports whether cmd runs without writing to the data // folder, so it may run while the folder is open read-only. func readOnlySafeCommand(cmd string) bool { diff --git a/internal/cli/plugin.go b/internal/cli/plugin.go index 5966720..25e1d41 100644 --- a/internal/cli/plugin.go +++ b/internal/cli/plugin.go @@ -87,465 +87,487 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error { case "connect": return pluginConnect(args[1:], cfg.DataRoot) case "search": - fs := flag.NewFlagSet("plugin search", flag.ContinueOnError) - kind := fs.String("kind", "", "Filter by plugin kind (theme, locale, driver, tool, template, runtime)") - includeAlpha := fs.Bool("alpha", false, "Include alpha channel plugins") - refresh := fs.Bool("refresh", false, "Bypass cache and refresh market index") - asJSON := fs.Bool("json", false, "Output JSON") - if err := fs.Parse(args[1:]); err != nil { - return err - } - mgr, _, err := openCLIPluginManager(cfg, true) - if err != nil { - return err - } - defer mgr.Close() - mc := openCLIMarketClient(cfg) - query := strings.TrimSpace(strings.Join(fs.Args(), " ")) - res := mc.Browse(ctx, mgr.Registry().List(), plugin.MarketBrowseOptions{ - Query: query, - Kind: *kind, - IncludeAlpha: *includeAlpha, - ForceRefresh: *refresh, - }) - if *asJSON { - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") - return enc.Encode(res) - } - if res.Stale && res.FetchError != "" { - fmt.Fprintf(os.Stderr, "[warn] %s (%s)\n", i18n.T(loc, "plugin.market.stale_warn"), res.FetchError) - } - for _, w := range res.WithdrawnInstalled { - fmt.Fprintf(os.Stderr, "[warn] %s: %s", w.ID, w.Reason.Get(string(loc))) - if w.InsteadID != "" { - fmt.Fprintf(os.Stderr, " -> %s", w.InsteadID) - } - fmt.Fprintln(os.Stderr) - } - if len(res.Items) == 0 { - fmt.Println(i18n.T(loc, "plugin.market.empty")) - return nil - } - for _, it := range res.Items { - status := it.Entry.Channel - switch { - case it.Withdrawn != nil: - status = "withdrawn" - case !it.Compatible: - status = "incompat" - case it.UpdateAvailable: - status = "update:" + it.InstalledVersion + "->" + it.Entry.Version - case it.Installed: - status = "installed" - } - kindLabel := it.Entry.Kind - if kindLabel == "" { - kindLabel = string(it.Entry.Tier) - } - if kindLabel == "" { - kindLabel = "-" - } - fmt.Printf("%-34s %-10s %-8s %-9s %-18s %s\n", - it.Entry.ID, it.Entry.Version, kindLabel, it.Entry.Trust, status, it.Entry.Name.Get(string(loc))) - } - return nil - + return pluginSearch(ctx, cfg, loc, args[1:]) case "list": - fs := flag.NewFlagSet("plugin list", flag.ContinueOnError) - asJSON := fs.Bool("json", false, "Output JSON") - if err := fs.Parse(args[1:]); err != nil { - return err - } - mgr, _, err := openCLIPluginManager(cfg, false) - if err != nil { - return err - } - defer mgr.Close() - list := mgr.LocalizePluginInfos(mgr.Registry().ListVisible()) - if *asJSON { - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") - return enc.Encode(list) - } - for _, p := range list { - mark := " " - switch p.State { - case plugin.StateActive: - mark = "*" - case plugin.StateDegraded, plugin.StateFailed: - mark = "!" - } - fmt.Printf("%s %-34s %-8s %-8s %-9s %-8s %s\n", - mark, p.ID, p.Version, p.Tier, p.Trust, p.State, p.Name.Get(string(loc))) - } - return nil - + return pluginList(cfg, loc, args[1:]) case "install": - fs := flag.NewFlagSet("plugin install", flag.ContinueOnError) - includeAlpha := fs.Bool("alpha", false, "Allow alpha channel when installing by market plugin ID") - refresh := fs.Bool("refresh", false, "Refresh market index before installing") - if err := fs.Parse(args[1:]); err != nil { - return err - } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go plugin install [--alpha] [--refresh] ") - } - target := fs.Arg(0) - mgr, _, err := openCLIPluginManager(cfg, false) - if err != nil { - return err - } - defer mgr.Close() - - isLocalFile := false - if st, statErr := os.Stat(target); statErr == nil && !st.IsDir() { - isLocalFile = true - } else if strings.HasSuffix(strings.ToLower(target), ".zip") || strings.ContainsAny(target, `/\`) { - isLocalFile = true - } - - var info *plugin.PluginInfo - if isLocalFile { - info, err = mgr.InstallLocalArchive(ctx, target, plugin.PackageInstallOptions{}) - } else { - mc := openCLIMarketClient(cfg) - info, err = mc.InstallFromMarket(ctx, mgr, target, plugin.MarketInstallOptions{ - IncludeAlpha: *includeAlpha, - ForceRefresh: *refresh, - }) - } - if err != nil { - return err - } - fmt.Println(i18n.T(loc, "plugin.installed", info.ID, info.Version, info.Trust, info.Tier)) - if info.NeedsApproval { - fmt.Println(i18n.T(loc, "plugin.needs_approval", info.ID)) - } - return nil - + return pluginInstall(ctx, cfg, loc, args[1:]) case "update": - fs := flag.NewFlagSet("plugin update", flag.ContinueOnError) - includeAlpha := fs.Bool("alpha", false, "Allow alpha channel updates") - refresh := fs.Bool("refresh", true, "Refresh market index before checking updates") - if err := fs.Parse(args[1:]); err != nil { - return err - } - mgr, _, err := openCLIPluginManager(cfg, false) - if err != nil { - return err - } - defer mgr.Close() - mc := openCLIMarketClient(cfg) - if fs.NArg() > 0 { - id := fs.Arg(0) - if _, ok := mgr.Registry().Info(id); !ok { - return fmt.Errorf("%s", i18n.T(loc, "plugin.not_found", id)) - } - info, uErr := mc.InstallFromMarket(ctx, mgr, id, plugin.MarketInstallOptions{ - IncludeAlpha: *includeAlpha, - ForceRefresh: *refresh, - }) - if uErr != nil { - return uErr - } - fmt.Println(i18n.T(loc, "plugin.installed", info.ID, info.Version, info.Trust, info.Tier)) - if info.NeedsApproval { - fmt.Println(i18n.T(loc, "plugin.needs_approval", info.ID)) - } - return nil - } - updates, browse := mc.CheckUpdates(ctx, mgr.Registry().List(), *includeAlpha, *refresh) - if browse.Stale && browse.FetchError != "" { - fmt.Fprintf(os.Stderr, "[warn] %s (%s)\n", i18n.T(loc, "plugin.market.stale_warn"), browse.FetchError) - } - if len(updates) == 0 { - fmt.Println(i18n.T(loc, "plugin.market.up_to_date")) - return nil - } - for _, up := range updates { - info, uErr := mc.InstallFromMarket(ctx, mgr, up.Entry.ID, plugin.MarketInstallOptions{ - IncludeAlpha: *includeAlpha, - ForceRefresh: false, - }) - if uErr != nil { - return fmt.Errorf("update %s: %w", up.Entry.ID, uErr) - } - fmt.Println(i18n.T(loc, "plugin.installed", info.ID, info.Version, info.Trust, info.Tier)) - if info.NeedsApproval { - fmt.Println(i18n.T(loc, "plugin.needs_approval", info.ID)) - } - } - return nil - + return pluginUpdate(ctx, cfg, loc, args[1:]) case "pack": - fs := flag.NewFlagSet("plugin pack", flag.ContinueOnError) - outPath := fs.String("out", "", "Output .zip path (defaults to -.zip)") - contractPath := fs.String("contract", "", "Optional path to ui-contract.json for CSS validation") - signKeySpec := fs.String("sign-key", "", "Optional ed25519 private key (file path or hex/base64) to sign SHA256SUMS.sig") - asJSON := fs.Bool("json", false, "Output JSON summary") - if err := fs.Parse(args[1:]); err != nil { - return err - } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go plugin pack [--out file.zip] [--contract ui-contract.json] [--sign-key key] [--json] ") - } - var contract *plugin.UIContract - if *contractPath != "" { - raw, rErr := os.ReadFile(*contractPath) - if rErr != nil { - return rErr - } - var c plugin.UIContract - if rErr := json.Unmarshal(raw, &c); rErr != nil { - return fmt.Errorf("parse ui-contract.json: %w", rErr) - } - contract = &c - } - packOpts := plugin.PackOptions{ - HostVersion: version.Version, - Contract: contract, - OutputPath: *outPath, - } - if strings.TrimSpace(*signKeySpec) != "" { - pk, kErr := plugin.ParseEd25519PrivateKey(*signKeySpec) - if kErr != nil { - return fmt.Errorf("parse --sign-key: %w", kErr) - } - packOpts.SignKey = pk - } - res, pErr := plugin.PackDirectory(fs.Arg(0), packOpts) - if pErr != nil { - if res.Report.HardBlocked && !*asJSON { - fmt.Fprintln(os.Stderr, res.Report.SummaryText(string(loc))) - } - return pErr - } - if *asJSON { - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") - return enc.Encode(res) - } - fmt.Println(i18n.T(loc, "plugin.packed", res.PluginID, res.Version, res.OutputPath)) - fmt.Printf("SHA-256: %s\n", res.SHA256) - fmt.Printf("Size: %d bytes (%d files, signed=%v)\n", res.SizeBytes, res.FileCount, res.Signed) - return nil - + return pluginPack(loc, args[1:]) case "link": - if len(args) < 2 { - return fmt.Errorf("usage: reims-go plugin link ") - } - mgr, _, err := openCLIPluginManager(cfg, false) - if err != nil { - return err - } - defer mgr.Close() - info, err := mgr.LinkDev(ctx, args[1]) - if err != nil { - return err - } - fmt.Println(i18n.T(loc, "plugin.linked", info.ID, info.Version, info.InstallDir)) - return nil - + return pluginLink(ctx, cfg, loc, args[1:]) case "enable": - fs := flag.NewFlagSet("plugin enable", flag.ContinueOnError) - approve := fs.Bool("approve-high-risk", false, "Explicitly approve high-risk permissions or community L3 execution") - if err := fs.Parse(args[1:]); err != nil { - return err - } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go plugin enable [--approve-high-risk] ") - } - mgr, _, err := openCLIPluginManager(cfg, false) - if err != nil { - return err - } - defer mgr.Close() - if err := mgr.Enable(ctx, fs.Arg(0), *approve); err != nil { - return err - } - fmt.Println(i18n.T(loc, "plugin.enabled", fs.Arg(0))) - return nil - + return pluginEnable(ctx, cfg, loc, args[1:]) case "disable": - if len(args) < 2 { - return fmt.Errorf("usage: reims-go plugin disable ") - } - // Load in safeMode so a broken external plugin never prevents disabling it. - mgr, _, err := openCLIPluginManager(cfg, true) - if err != nil { - return err - } - defer mgr.Close() - if err := mgr.Disable(ctx, args[1]); err != nil { - return err - } - fmt.Println(i18n.T(loc, "plugin.disabled", args[1])) - return nil - + return pluginDisable(ctx, cfg, loc, args[1:]) case "remove": - fs := flag.NewFlagSet("plugin remove", flag.ContinueOnError) - purge := fs.Bool("purge", false, "Also delete plugin private data and logs") - if err := fs.Parse(args[1:]); err != nil { - return err - } - if fs.NArg() != 1 { - return fmt.Errorf("usage: reims-go plugin remove [--purge] ") - } - mgr, _, err := openCLIPluginManager(cfg, true) - if err != nil { - return err - } - defer mgr.Close() - if err := mgr.Remove(ctx, fs.Arg(0), *purge); err != nil { - return err - } - fmt.Println(i18n.T(loc, "plugin.removed", fs.Arg(0), *purge)) - return nil - + return pluginRemove(ctx, cfg, loc, args[1:]) case "info": - if len(args) < 2 { - return fmt.Errorf("usage: reims-go plugin info ") - } - mgr, _, err := openCLIPluginManager(cfg, true) - if err != nil { - return err - } - defer mgr.Close() - info, ok := mgr.Registry().Info(args[1]) - if !ok { - return fmt.Errorf("%s", i18n.T(loc, "plugin.not_found", args[1])) - } - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") - return enc.Encode(info) - + return pluginInfo(cfg, loc, args[1:]) case "doctor": - fs := flag.NewFlagSet("plugin doctor", flag.ContinueOnError) - contractPath := fs.String("contract", "", "Optional path to ui-contract.json for CSS validation") - asJSON := fs.Bool("json", false, "Output structured ScanReport JSON") - if err := fs.Parse(args[1:]); err != nil { - return err - } - var contract *plugin.UIContract - if *contractPath != "" { - raw, err := os.ReadFile(*contractPath) - if err != nil { - return err - } - var c plugin.UIContract - if err := json.Unmarshal(raw, &c); err != nil { - return fmt.Errorf("parse ui-contract.json: %w", err) - } - contract = &c - } - scanOpts := plugin.ScanOptions{Contract: contract, Keyring: plugin.DefaultKeyring()} - target := "" - if fs.NArg() > 0 { - target = fs.Arg(0) - } - // Direct directory or .zip archive inspection (developer & market CI workflow, §5.1). - if target != "" { - if st, err := os.Stat(target); err == nil { - if st.IsDir() { - rep := plugin.ScanDirectory(target, version.Version, scanOpts) - return printScanReports(loc, []plugin.ScanReport{rep}, *asJSON) - } - if strings.HasSuffix(strings.ToLower(target), ".zip") { - layout := plugin.NewPluginsLayout(cfg.DataRoot) - rep, sErr := plugin.ScanArchive(target, layout.TmpDir(), version.Version, scanOpts) - if sErr != nil { - return sErr - } - return printScanReports(loc, []plugin.ScanReport{rep}, *asJSON) - } - } - } - mgr, _, err := openCLIPluginManager(cfg, false) - if err != nil { - return err - } - defer mgr.Close() - if target != "" { - info, ok := mgr.Registry().Info(target) - if !ok { - return fmt.Errorf("%s", i18n.T(loc, "plugin.target_not_found", target)) - } - if info.InstallDir == "" { - if *asJSON { - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") - return enc.Encode(plugin.ScanReport{ - PluginID: info.ID, - Version: info.Version, - Name: info.Name, - Tier: info.Tier, - Trust: info.Trust, - Passed: true, - Headline: plugin.LocalizedText{ - ZhCN: "内置插件状态正常", - EnUS: "Built-in plugin is healthy", - }, - }) - } - fmt.Printf("[ok] %s@%s (%s, state=%s)\n", info.ID, info.Version, info.Source, info.State) - return nil - } - rep := plugin.ScanDirectory(info.InstallDir, version.Version, scanOpts) - return printScanReports(loc, []plugin.ScanReport{rep}, *asJSON) - } - // Audit all installed external plugins. - var reports []plugin.ScanReport - for _, info := range mgr.Registry().List() { - if info.InstallDir != "" { - reports = append(reports, plugin.ScanDirectory(info.InstallDir, version.Version, scanOpts)) - } - } - if len(reports) == 0 { - if *asJSON { - fmt.Println("[]") - return nil - } - 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 - } - return printScanReports(loc, reports, *asJSON) - + return pluginDoctor(cfg, loc, args[1:]) case "locale": return cmdPluginLocale(loc, args[1:]) - case "run": - if len(args) < 3 { - return fmt.Errorf("usage: reims-go plugin run [key=value...]") - } - mgr, _, err := openCLIPluginManager(cfg, false) - if err != nil { - return err - } - defer mgr.Close() - cmdArgs := map[string]any{} - for _, kv := range args[3:] { - k, v, ok := strings.Cut(kv, "=") - if !ok || strings.TrimSpace(k) == "" { - return fmt.Errorf("invalid argument %q (expected key=value)", kv) - } - cmdArgs[k] = v - } - res, err := mgr.Registry().InvokeCommand(ctx, args[1], args[2], cmdArgs) - if err != nil { - return err - } - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") - return enc.Encode(res) - + return pluginRun(ctx, cfg, args[1:]) default: return fmt.Errorf("unknown plugin subcommand %q", args[0]) } } +func pluginSearch(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string) error { + fs := flag.NewFlagSet("plugin search", flag.ContinueOnError) + kind := fs.String("kind", "", "Filter by plugin kind (theme, locale, driver, tool, template, runtime)") + includeAlpha := fs.Bool("alpha", false, "Include alpha channel plugins") + refresh := fs.Bool("refresh", false, "Bypass cache and refresh market index") + asJSON := fs.Bool("json", false, "Output JSON") + if err := fs.Parse(args); err != nil { + return err + } + mgr, _, err := openCLIPluginManager(cfg, true) + if err != nil { + return err + } + defer mgr.Close() + mc := openCLIMarketClient(cfg) + query := strings.TrimSpace(strings.Join(fs.Args(), " ")) + res := mc.Browse(ctx, mgr.Registry().List(), plugin.MarketBrowseOptions{ + Query: query, + Kind: *kind, + IncludeAlpha: *includeAlpha, + ForceRefresh: *refresh, + }) + if *asJSON { + return printJSON(res) + } + if res.Stale && res.FetchError != "" { + fmt.Fprintf(os.Stderr, "[warn] %s (%s)\n", i18n.T(loc, "plugin.market.stale_warn"), res.FetchError) + } + for _, w := range res.WithdrawnInstalled { + fmt.Fprintf(os.Stderr, "[warn] %s: %s", w.ID, w.Reason.Get(string(loc))) + if w.InsteadID != "" { + fmt.Fprintf(os.Stderr, " -> %s", w.InsteadID) + } + fmt.Fprintln(os.Stderr) + } + if len(res.Items) == 0 { + fmt.Println(i18n.T(loc, "plugin.market.empty")) + return nil + } + for _, it := range res.Items { + status := it.Entry.Channel + switch { + case it.Withdrawn != nil: + status = "withdrawn" + case !it.Compatible: + status = "incompat" + case it.UpdateAvailable: + status = "update:" + it.InstalledVersion + "->" + it.Entry.Version + case it.Installed: + status = "installed" + } + kindLabel := it.Entry.Kind + if kindLabel == "" { + kindLabel = string(it.Entry.Tier) + } + if kindLabel == "" { + kindLabel = "-" + } + fmt.Printf("%-34s %-10s %-8s %-9s %-18s %s\n", + it.Entry.ID, it.Entry.Version, kindLabel, it.Entry.Trust, status, it.Entry.Name.Get(string(loc))) + } + return nil +} + +func pluginList(cfg *config.Config, loc i18n.Locale, args []string) error { + fs := flag.NewFlagSet("plugin list", flag.ContinueOnError) + asJSON := fs.Bool("json", false, "Output JSON") + if err := fs.Parse(args); err != nil { + return err + } + mgr, _, err := openCLIPluginManager(cfg, false) + if err != nil { + return err + } + defer mgr.Close() + list := mgr.LocalizePluginInfos(mgr.Registry().ListVisible()) + if *asJSON { + return printJSON(list) + } + for _, p := range list { + mark := " " + switch p.State { + case plugin.StateActive: + mark = "*" + case plugin.StateDegraded, plugin.StateFailed: + mark = "!" + } + fmt.Printf("%s %-34s %-8s %-8s %-9s %-8s %s\n", + mark, p.ID, p.Version, p.Tier, p.Trust, p.State, p.Name.Get(string(loc))) + } + return nil +} + +func pluginInstall(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string) error { + fs := flag.NewFlagSet("plugin install", flag.ContinueOnError) + includeAlpha := fs.Bool("alpha", false, "Allow alpha channel when installing by market plugin ID") + refresh := fs.Bool("refresh", false, "Refresh market index before installing") + if err := fs.Parse(args); err != nil { + return err + } + if fs.NArg() < 1 { + return fmt.Errorf("usage: reims-go plugin install [--alpha] [--refresh] ") + } + target := fs.Arg(0) + mgr, _, err := openCLIPluginManager(cfg, false) + if err != nil { + return err + } + defer mgr.Close() + + isLocalFile := false + if st, statErr := os.Stat(target); statErr == nil && !st.IsDir() { + isLocalFile = true + } else if strings.HasSuffix(strings.ToLower(target), ".zip") || strings.ContainsAny(target, `/\`) { + isLocalFile = true + } + + var info *plugin.PluginInfo + if isLocalFile { + info, err = mgr.InstallLocalArchive(ctx, target, plugin.PackageInstallOptions{}) + } else { + mc := openCLIMarketClient(cfg) + info, err = mc.InstallFromMarket(ctx, mgr, target, plugin.MarketInstallOptions{ + IncludeAlpha: *includeAlpha, + ForceRefresh: *refresh, + }) + } + if err != nil { + return err + } + printInstalled(loc, info) + return nil +} + +func pluginUpdate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string) error { + fs := flag.NewFlagSet("plugin update", flag.ContinueOnError) + includeAlpha := fs.Bool("alpha", false, "Allow alpha channel updates") + refresh := fs.Bool("refresh", true, "Refresh market index before checking updates") + if err := fs.Parse(args); err != nil { + return err + } + mgr, _, err := openCLIPluginManager(cfg, false) + if err != nil { + return err + } + defer mgr.Close() + mc := openCLIMarketClient(cfg) + if fs.NArg() > 0 { + id := fs.Arg(0) + if _, ok := mgr.Registry().Info(id); !ok { + return fmt.Errorf("%s", i18n.T(loc, "plugin.not_found", id)) + } + info, uErr := mc.InstallFromMarket(ctx, mgr, id, plugin.MarketInstallOptions{ + IncludeAlpha: *includeAlpha, + ForceRefresh: *refresh, + }) + if uErr != nil { + return uErr + } + printInstalled(loc, info) + return nil + } + updates, browse := mc.CheckUpdates(ctx, mgr.Registry().List(), *includeAlpha, *refresh) + if browse.Stale && browse.FetchError != "" { + fmt.Fprintf(os.Stderr, "[warn] %s (%s)\n", i18n.T(loc, "plugin.market.stale_warn"), browse.FetchError) + } + if len(updates) == 0 { + fmt.Println(i18n.T(loc, "plugin.market.up_to_date")) + return nil + } + for _, up := range updates { + info, uErr := mc.InstallFromMarket(ctx, mgr, up.Entry.ID, plugin.MarketInstallOptions{ + IncludeAlpha: *includeAlpha, + ForceRefresh: false, + }) + if uErr != nil { + return fmt.Errorf("update %s: %w", up.Entry.ID, uErr) + } + printInstalled(loc, info) + } + return nil +} + +func pluginPack(loc i18n.Locale, args []string) error { + fs := flag.NewFlagSet("plugin pack", flag.ContinueOnError) + outPath := fs.String("out", "", "Output .zip path (defaults to -.zip)") + contractPath := fs.String("contract", "", "Optional path to ui-contract.json for CSS validation") + signKeySpec := fs.String("sign-key", "", "Optional ed25519 private key (file path or hex/base64) to sign SHA256SUMS.sig") + asJSON := fs.Bool("json", false, "Output JSON summary") + if err := fs.Parse(args); err != nil { + return err + } + if fs.NArg() < 1 { + return fmt.Errorf("usage: reims-go plugin pack [--out file.zip] [--contract ui-contract.json] [--sign-key key] [--json] ") + } + contract, err := loadUIContract(*contractPath) + if err != nil { + return err + } + packOpts := plugin.PackOptions{ + HostVersion: version.Version, + Contract: contract, + OutputPath: *outPath, + } + if strings.TrimSpace(*signKeySpec) != "" { + pk, kErr := plugin.ParseEd25519PrivateKey(*signKeySpec) + if kErr != nil { + return fmt.Errorf("parse --sign-key: %w", kErr) + } + packOpts.SignKey = pk + } + res, pErr := plugin.PackDirectory(fs.Arg(0), packOpts) + if pErr != nil { + if res.Report.HardBlocked && !*asJSON { + fmt.Fprintln(os.Stderr, res.Report.SummaryText(string(loc))) + } + return pErr + } + if *asJSON { + return printJSON(res) + } + fmt.Println(i18n.T(loc, "plugin.packed", res.PluginID, res.Version, res.OutputPath)) + fmt.Printf("SHA-256: %s\n", res.SHA256) + fmt.Printf("Size: %d bytes (%d files, signed=%v)\n", res.SizeBytes, res.FileCount, res.Signed) + return nil +} + +func pluginLink(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string) error { + if len(args) < 1 { + return fmt.Errorf("usage: reims-go plugin link ") + } + mgr, _, err := openCLIPluginManager(cfg, false) + if err != nil { + return err + } + defer mgr.Close() + info, err := mgr.LinkDev(ctx, args[0]) + if err != nil { + return err + } + fmt.Println(i18n.T(loc, "plugin.linked", info.ID, info.Version, info.InstallDir)) + return nil +} + +func pluginEnable(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string) error { + fs := flag.NewFlagSet("plugin enable", flag.ContinueOnError) + approve := fs.Bool("approve-high-risk", false, "Explicitly approve high-risk permissions or community L3 execution") + if err := fs.Parse(args); err != nil { + return err + } + if fs.NArg() < 1 { + return fmt.Errorf("usage: reims-go plugin enable [--approve-high-risk] ") + } + mgr, _, err := openCLIPluginManager(cfg, false) + if err != nil { + return err + } + defer mgr.Close() + if err := mgr.Enable(ctx, fs.Arg(0), *approve); err != nil { + return err + } + fmt.Println(i18n.T(loc, "plugin.enabled", fs.Arg(0))) + return nil +} + +func pluginDisable(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string) error { + if len(args) < 1 { + return fmt.Errorf("usage: reims-go plugin disable ") + } + // Load in safeMode so a broken external plugin never prevents disabling it. + mgr, _, err := openCLIPluginManager(cfg, true) + if err != nil { + return err + } + defer mgr.Close() + if err := mgr.Disable(ctx, args[0]); err != nil { + return err + } + fmt.Println(i18n.T(loc, "plugin.disabled", args[0])) + return nil +} + +func pluginRemove(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string) error { + fs := flag.NewFlagSet("plugin remove", flag.ContinueOnError) + purge := fs.Bool("purge", false, "Also delete plugin private data and logs") + if err := fs.Parse(args); err != nil { + return err + } + if fs.NArg() != 1 { + return fmt.Errorf("usage: reims-go plugin remove [--purge] ") + } + mgr, _, err := openCLIPluginManager(cfg, true) + if err != nil { + return err + } + defer mgr.Close() + if err := mgr.Remove(ctx, fs.Arg(0), *purge); err != nil { + return err + } + fmt.Println(i18n.T(loc, "plugin.removed", fs.Arg(0), *purge)) + return nil +} + +func pluginInfo(cfg *config.Config, loc i18n.Locale, args []string) error { + if len(args) < 1 { + return fmt.Errorf("usage: reims-go plugin info ") + } + mgr, _, err := openCLIPluginManager(cfg, true) + if err != nil { + return err + } + defer mgr.Close() + info, ok := mgr.Registry().Info(args[0]) + if !ok { + return fmt.Errorf("%s", i18n.T(loc, "plugin.not_found", args[0])) + } + return printJSON(info) +} + +func pluginDoctor(cfg *config.Config, loc i18n.Locale, args []string) error { + fs := flag.NewFlagSet("plugin doctor", flag.ContinueOnError) + contractPath := fs.String("contract", "", "Optional path to ui-contract.json for CSS validation") + asJSON := fs.Bool("json", false, "Output structured ScanReport JSON") + if err := fs.Parse(args); err != nil { + return err + } + contract, err := loadUIContract(*contractPath) + if err != nil { + return err + } + scanOpts := plugin.ScanOptions{Contract: contract, Keyring: plugin.DefaultKeyring()} + target := "" + if fs.NArg() > 0 { + target = fs.Arg(0) + } + // Direct directory or .zip archive inspection (developer & market CI workflow, §5.1). + if target != "" { + if st, err := os.Stat(target); err == nil { + if st.IsDir() { + rep := plugin.ScanDirectory(target, version.Version, scanOpts) + return printScanReports(loc, []plugin.ScanReport{rep}, *asJSON) + } + if strings.HasSuffix(strings.ToLower(target), ".zip") { + layout := plugin.NewPluginsLayout(cfg.DataRoot) + rep, sErr := plugin.ScanArchive(target, layout.TmpDir(), version.Version, scanOpts) + if sErr != nil { + return sErr + } + return printScanReports(loc, []plugin.ScanReport{rep}, *asJSON) + } + } + } + mgr, _, err := openCLIPluginManager(cfg, false) + if err != nil { + return err + } + defer mgr.Close() + if target != "" { + info, ok := mgr.Registry().Info(target) + if !ok { + return fmt.Errorf("%s", i18n.T(loc, "plugin.target_not_found", target)) + } + if info.InstallDir == "" { + if *asJSON { + return printJSON(plugin.ScanReport{ + PluginID: info.ID, + Version: info.Version, + Name: info.Name, + Tier: info.Tier, + Trust: info.Trust, + Passed: true, + Headline: plugin.LocalizedText{ + ZhCN: "内置插件状态正常", + EnUS: "Built-in plugin is healthy", + }, + }) + } + fmt.Printf("[ok] %s@%s (%s, state=%s)\n", info.ID, info.Version, info.Source, info.State) + return nil + } + rep := plugin.ScanDirectory(info.InstallDir, version.Version, scanOpts) + return printScanReports(loc, []plugin.ScanReport{rep}, *asJSON) + } + // Audit all installed external plugins. + var reports []plugin.ScanReport + for _, info := range mgr.Registry().List() { + if info.InstallDir != "" { + reports = append(reports, plugin.ScanDirectory(info.InstallDir, version.Version, scanOpts)) + } + } + if len(reports) == 0 { + if *asJSON { + fmt.Println("[]") + return nil + } + 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 + } + return printScanReports(loc, reports, *asJSON) +} + +func pluginRun(ctx context.Context, cfg *config.Config, args []string) error { + if len(args) < 2 { + return fmt.Errorf("usage: reims-go plugin run [key=value...]") + } + mgr, _, err := openCLIPluginManager(cfg, false) + if err != nil { + return err + } + defer mgr.Close() + cmdArgs := map[string]any{} + for _, kv := range args[2:] { + k, v, ok := strings.Cut(kv, "=") + if !ok || strings.TrimSpace(k) == "" { + return fmt.Errorf("invalid argument %q (expected key=value)", kv) + } + cmdArgs[k] = v + } + res, err := mgr.Registry().InvokeCommand(ctx, args[0], args[1], cmdArgs) + if err != nil { + return err + } + return printJSON(res) +} + +func printInstalled(loc i18n.Locale, info *plugin.PluginInfo) { + fmt.Println(i18n.T(loc, "plugin.installed", info.ID, info.Version, info.Trust, info.Tier)) + if info.NeedsApproval { + fmt.Println(i18n.T(loc, "plugin.needs_approval", info.ID)) + } +} + +// loadUIContract reads the ui-contract.json used for CSS validation. An empty +// path means no contract. +func loadUIContract(path string) (*plugin.UIContract, error) { + if path == "" { + return nil, nil + } + raw, err := os.ReadFile(path) + if err != nil { + return nil, err + } + var c plugin.UIContract + if err := json.Unmarshal(raw, &c); err != nil { + return nil, fmt.Errorf("parse ui-contract.json: %w", err) + } + return &c, nil +} + func printScanReports(loc i18n.Locale, reports []plugin.ScanReport, asJSON bool) error { hasErr := false for _, r := range reports { @@ -554,14 +576,12 @@ func printScanReports(loc i18n.Locale, reports []plugin.ScanReport, asJSON bool) } } if asJSON { - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") if len(reports) == 1 { - if err := enc.Encode(reports[0]); err != nil { + if err := printJSON(reports[0]); err != nil { return err } } else { - if err := enc.Encode(reports); err != nil { + if err := printJSON(reports); err != nil { return err } } @@ -648,9 +668,7 @@ func cmdPluginLocale(loc i18n.Locale, args []string) error { return err } if *asJSON { - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") - if err := enc.Encode(reports); err != nil { + if err := printJSON(reports); err != nil { return err } } else { diff --git a/internal/cli/start.go b/internal/cli/start.go index 078a7ff..9d24bd1 100644 --- a/internal/cli/start.go +++ b/internal/cli/start.go @@ -21,6 +21,14 @@ import ( // report back. Preparation can rebuild the OpenCore image before QEMU starts. const startHandoffTimeout = 5 * time.Minute +func openCLILifecycle(cfg *config.Config) (*lifecycle.Service, func(), error) { + mgr, router, err := openCLIPluginManager(cfg, false) + if err != nil { + return nil, nil, err + } + return lifecycle.New(mgr.Registry(), router, nil), mgr.Close, nil +} + // startVM resolves the VM, then hands it to the desktop window: the // one already running, or a new one in the tray (`--background`). The window // runs the GUI's StartVM, so a VM started from the command line gets Guest @@ -29,12 +37,11 @@ const startHandoffTimeout = 5 * time.Minute // // 显式传入管理器当前数据目录仍交给管理器;其他目录的桥接禁止直接启动。 func startVM(ctx context.Context, cfg *config.Config, driverID, name string, viaWindow bool) error { - mgr, router, err := openCLIPluginManager(cfg, false) + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) + defer closeService() _, vm, err := svc.Resolve(ctx, driverID, name) if err != nil { return err @@ -50,64 +57,58 @@ func startVM(ctx context.Context, cfg *config.Config, driverID, name string, via } func actionVM(ctx context.Context, cfg *config.Config, driverID, name, action string, params map[string]any) error { - mgr, router, err := openCLIPluginManager(cfg, false) + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) + defer closeService() _, err = svc.InvokeAction(ctx, driver.VMRef{DriverID: driverID, Name: name}, action, params) return err } func setVM(ctx context.Context, cfg *config.Config, driverID, name string, changes map[string]any) error { - mgr, router, err := openCLIPluginManager(cfg, false) + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) + defer closeService() return svc.Set(ctx, driver.VMRef{DriverID: driverID, Name: name}, changes, os.Stdout, os.Stderr) } func deleteVM(ctx context.Context, cfg *config.Config, driverID, name string, keepFiles bool) error { - mgr, router, err := openCLIPluginManager(cfg, false) + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) + defer closeService() return svc.Delete(ctx, driver.VMRef{DriverID: driverID, Name: name}, keepFiles, os.Stdout, os.Stderr) } func resizeVM(ctx context.Context, cfg *config.Config, driverID, name, newSize string) (driver.DiskResizeResult, error) { - mgr, router, err := openCLIPluginManager(cfg, false) + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return driver.DiskResizeResult{}, err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) + defer closeService() return svc.ResizeDisk(ctx, driver.VMRef{DriverID: driverID, Name: name}, newSize, os.Stdout, os.Stderr) } func compactVM(ctx context.Context, cfg *config.Config, driverID, name string) (driver.DiskCompactResult, error) { - mgr, router, err := openCLIPluginManager(cfg, false) + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return driver.DiskCompactResult{}, err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) + defer closeService() return svc.CompactDisk(ctx, driver.VMRef{DriverID: driverID, Name: name}, os.Stdout, os.Stderr) } -func stopVM(ctx context.Context, cfg *config.Config, driverID, name string, force bool) error { - mgr, router, err := openCLIPluginManager(cfg, false) +func stopVM(ctx context.Context, cfg *config.Config, driverID, name string) error { + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) - return svc.Stop(ctx, driver.VMRef{DriverID: driverID, Name: name}, force, os.Stdout, os.Stderr) + defer closeService() + return svc.Stop(ctx, driver.VMRef{DriverID: driverID, Name: name}, false, os.Stdout, os.Stderr) } func startInWindow(ctx context.Context, cfg *config.Config, driverID, name string) error { diff --git a/internal/cli/suspend.go b/internal/cli/suspend.go index dcd6ef2..f9c101c 100644 --- a/internal/cli/suspend.go +++ b/internal/cli/suspend.go @@ -9,17 +9,15 @@ import ( "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/host" - "github.com/Nwflower/reims-go/internal/lifecycle" "github.com/Nwflower/reims-go/internal/vmstart" ) func suspendVM(ctx context.Context, cfg *config.Config, driverID, name string) error { - mgr, router, err := openCLIPluginManager(cfg, false) + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) + defer closeService() _, vm, err := svc.Resolve(ctx, driverID, name) if err != nil { return err @@ -34,12 +32,11 @@ func suspendVM(ctx context.Context, cfg *config.Config, driverID, name string) e } func resumeVM(ctx context.Context, cfg *config.Config, driverID, name string, viaWindow bool) error { - mgr, router, err := openCLIPluginManager(cfg, false) + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) + defer closeService() _, vm, err := svc.Resolve(ctx, driverID, name) if err != nil { return err @@ -76,12 +73,11 @@ func resumeVM(ctx context.Context, cfg *config.Config, driverID, name string, vi } func discardSuspendVM(ctx context.Context, cfg *config.Config, driverID, name string) error { - mgr, router, err := openCLIPluginManager(cfg, false) + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) + defer closeService() if err := svc.DiscardSuspend(ctx, driver.VMRef{DriverID: driverID, Name: name}); err != nil { return err } From 165f26351de2014f8b03df5d5337c102f29205dc 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: Thu, 3 Dec 2026 21:26:54 -0700 Subject: [PATCH 08/22] refactor(app): split the VM poll loop into steps The poll loop was one 290-line function that did everything that follows the VM list. Its steps are now separate and recording a listing has a test. The install guide part moved next to the rest of the guide code. Running process IDs and capabilities are read through one method each. Co-Authored-By: Claude Opus 5.5 --- internal/app/affinity_flow.go | 18 +- internal/app/app.go | 441 ------------------------ internal/app/app_poll_test.go | 39 +++ internal/app/console_router.go | 2 +- internal/app/fullscreen_hotkey_flow.go | 7 +- internal/app/install_guide.go | 55 ++- internal/app/keymap_flow.go | 2 +- internal/app/macos_lifecycle_native.go | 7 +- internal/app/vm_close_windows.go | 12 +- internal/app/vm_monitor.go | 6 +- internal/app/vm_poll.go | 458 +++++++++++++++++++++++++ internal/driver/driver.go | 15 + 12 files changed, 579 insertions(+), 483 deletions(-) create mode 100644 internal/app/vm_poll.go diff --git a/internal/app/affinity_flow.go b/internal/app/affinity_flow.go index 730de8c..3bdbab7 100644 --- a/internal/app/affinity_flow.go +++ b/internal/app/affinity_flow.go @@ -38,22 +38,10 @@ type VMAffinityStatus struct { func (a *App) findRunningVMPID(ctx context.Context, name string) int { if c, err := a.client(); err == nil { if vms, lerr := c.List(ctx); lerr == nil { - for _, vm := range vms { - if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 { - return *vm.PID - } - } - return 0 + return runningPIDByName(vms, name) } } - a.mu.Lock() - defer a.mu.Unlock() - for _, vm := range a.lastVMs { - if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 { - return *vm.PID - } - } - return 0 + return a.cachedVMPID(name) } func buildVMAffinityStatus(detail driver.VMInfo, rep host.Report, globalAutoPin bool, pid int) VMAffinityStatus { @@ -133,7 +121,7 @@ func (a *App) SetVMAffinity(driverID, name string, req VMAffinityUpdate) (VMAffi if err != nil { return VMAffinityStatus{}, err } - if driver.IsHosted(vm.Capabilities) || (len(vm.Capabilities) > 0 && !driver.HasCapability(vm.Capabilities, driver.CapAffinity)) { + if driver.IsHosted(vm.Capabilities) || !driver.SupportsCapability(vm.Capabilities, driver.CapAffinity) { return VMAffinityStatus{}, fmt.Errorf("CPU affinity is not available for %s", name) } if detail.Directory == "" { diff --git a/internal/app/app.go b/internal/app/app.go index 4bc5373..4a44fcd 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "maps" "os" "path/filepath" "strings" @@ -333,446 +332,6 @@ func (a *App) shutdown(ctx context.Context) { releaseVMTyping("") } -// pollVMs refreshes the VM list every pollBusy while a VM is starting or -// stopping and every pollSteady otherwise; each tick runs one `reims-ctl list`. -// Start, stop and delete call wakePoll so their result shows up at once. -const ( - pollBusy = 2 * time.Second - // Exits are caught at once by watchExits and GUI actions call wakePoll, so - // the steady tick only has to notice VMs started or removed elsewhere (CLI). - pollSteady = 10 * time.Second - // polledMaxAge is how old lastVMs may be for polledVMs to reuse it. It sits - // above pollSteady so a poll that runs a little late still counts. - polledMaxAge = pollSteady + 3*time.Second -) - -func (a *App) pollVMs(ctx context.Context) { - timer := time.NewTimer(pollBusy) - defer timer.Stop() - // Cache static hybrid P-core mask once instead of querying host every tick. - a.mu.Lock() - initRoot := a.cfg.DataRoot - a.mu.Unlock() - cachedHost := host.Inspect(initRoot) - var lastSig string - pinnedPIDs := make(map[int]bool) - guideCheckedPIDs := make(map[int]bool) - lastGuideMgr := a.getInstallGuideManager() - exitWatched := make(map[int]bool) - - for { - select { - case <-ctx.Done(): - return - case <-timer.C: - case <-a.pollWake: - } - a.mu.Lock() - next := pollSteady - if len(a.transitions) > 0 { - next = pollBusy - } - a.mu.Unlock() - timer.Reset(next) - // reims-ctl keeps its state in the data folder; leave it alone until - // setup has chosen one, and while it is open read-only. - if !a.dataRootUsable() { - continue - } - vms, err := a.listVMsInternal(ctx) - if err != nil { - a.mu.Lock() - changed := a.lastVMListErr == nil || a.lastVMListErr.Error() != err.Error() - a.lastVMListErr = err - if a.lastVMsAt.IsZero() && a.lastVMs == nil { - a.lastVMs = vms - } - a.lastVMsAt = time.Now() - a.mu.Unlock() - if changed { - a.emitStateChanged() - } - continue - } - a.syncComputerUseOwnership(vms) - // Only VMs whose process the host neither spawned (the broker watches - // those through their job) nor leaves to the driver (hosted) need a - // per-PID exit watcher. - procVMs := make([]driver.VMListItem, 0, len(vms)) - for _, vm := range vms { - if !driver.IsHosted(vm.Capabilities) && !a.brokerRunsVM(vm.DriverID, vm.Name) { - procVMs = append(procVMs, vm) - } - } - watchExits(ctx, procVMs, exitWatched, a.wakePoll) - type pinCandidate struct { - driverID string - name string - dir string - pid int - } - var toPin []pinCandidate - a.mu.Lock() - loc := a.cfg.Locale - autoPin := a.cfg.AutoPinPCores - tm := a.trayMgr - runningCount := 0 - var b strings.Builder - var imeTargets []host.IMETarget - for _, vm := range vms { - key := vmKeyForDriver(vm.DriverID, vm.Name) - if vm.State == "running" { - runningCount++ - // The remote IME bridge types through the macOS guest's tools. - if vm.PID != nil && *vm.PID > 0 && (driver.HasCapability(vm.Capabilities, driver.CapGuestTools) || len(vm.Capabilities) == 0) { - imeTargets = append(imeTargets, host.IMETarget{ - VMName: vm.Name, - VMDir: vm.Dir, - PID: uint32(*vm.PID), - }) - } - } - if tr, ok := a.transitions[key]; ok { - if (tr == "starting" && vm.State == "running") || - (tr == "stopping" && vm.State == "stopped") || - (tr == "suspending" && (vm.State == "suspended" || vm.State == "stopped")) || - (tr == "resuming" && vm.State == "running") { - delete(a.transitions, key) - if vm.State == "stopped" { - delete(a.pendingChanges, key) - } - } - } - if vm.State == "running" && vm.PID != nil && *vm.PID > 0 && !pinnedPIDs[*vm.PID] && - !driver.IsHosted(vm.Capabilities) && (driver.HasCapability(vm.Capabilities, driver.CapAffinity) || len(vm.Capabilities) == 0) { - pinnedPIDs[*vm.PID] = true - toPin = append(toPin, pinCandidate{driverID: vm.DriverID, name: vm.Name, dir: vm.Dir, pid: *vm.PID}) - } - fmt.Fprintf(&b, "%s:%s:%s:%s:%s:%s;", key, vm.State, a.transitions[key], vm.Phase, readyToken(vm.Ready), endpointSignature(vm.Endpoints)) - } - sig := b.String() - ib := a.imeBridge - liveVMs := make(map[string]struct{}, len(vms)) - for _, vm := range vms { - liveVMs[vmKeyForDriver(vm.DriverID, vm.Name)] = struct{}{} - } - removedVMs := make(map[string]struct{}) - for _, vm := range a.lastVMs { - key := vmKeyForDriver(vm.DriverID, vm.Name) - if _, ok := liveVMs[key]; !ok { - removedVMs[key] = struct{}{} - } - } - for name := range a.rebootWatchers { - if _, ok := liveVMs[name]; !ok { - removedVMs[name] = struct{}{} - } - } - for name := range a.diskPaths { - if _, ok := liveVMs[name]; !ok { - removedVMs[name] = struct{}{} - } - } - for name := range a.procSamples { - if _, ok := liveVMs[name]; !ok { - removedVMs[name] = struct{}{} - } - } - maps.DeleteFunc(a.diskPaths, func(name string, _ cachedDiskPath) bool { - _, ok := liveVMs[name] - return !ok - }) - maps.DeleteFunc(a.procSamples, func(name string, _ host.ProcessSample) bool { - _, ok := liveVMs[name] - return !ok - }) - var stoppedBridges []string - for _, prev := range a.lastVMs { - if prev.State != "running" || prev.DriverID != driver.BuiltinReimsMacOSDriverID { - continue - } - key := vmKeyForDriver(prev.DriverID, prev.Name) - tr := a.transitions[key] - if tr == "starting" || tr == "resuming" { - continue - } - for _, cur := range vms { - if cur.DriverID == prev.DriverID && cur.Name == prev.Name && cur.State != "running" { - stoppedBridges = append(stoppedBridges, cur.Name) - break - } - } - } - gt := a.guestTools - a.lastVMs = append([]driver.VMListItem(nil), vms...) - a.lastVMsAt = time.Now() - listRecovered := a.lastVMListErr != nil - a.lastVMListErr = nil - a.mu.Unlock() - for _, vmName := range stoppedBridges { - a.stopPacketBridge(vmName) - if gt != nil { - gt.StopManagementNetwork(vmName) - } - } - prunePinnedPIDs(pinnedPIDs, vms) - prunePinnedPIDs(guideCheckedPIDs, vms) - guideMgr := a.getInstallGuideManager() - if guideMgr != lastGuideMgr { - clear(guideCheckedPIDs) - lastGuideMgr = guideMgr - } - runningPIDs := make(map[int]bool, len(vms)) - for _, vm := range vms { - if vm.State == "running" && vm.PID != nil && *vm.PID > 0 { - runningPIDs[*vm.PID] = true - } - } - guidesChanged := false - if guideMgr != nil { - guidesChanged = guideMgr.CancelStopped(runningPIDs) - } - for key := range removedVMs { - name := vmNameFromKey(key) - if ref, ok := driver.ParseVMRef(key); ok && ref.DriverID == driver.BuiltinReimsMacOSDriverID { - a.stopPacketBridge(name) - } - a.forgetComputerUseOwnedVM(key) - ref, parsed := driver.ParseVMRef(key) - // A disabled driver's VMs may leave the list without being deleted. - if parsed && a.driverFor(driver.VMInfo{DriverID: ref.DriverID}) != nil { - a.discardMaterializedSecretsForVM(key) - } - a.mu.Lock() - delete(a.transitions, key) - delete(a.pendingChanges, key) - a.mu.Unlock() - if !parsed || ref.DriverID == driver.BuiltinReimsMacOSDriverID { - // These helpers are keyed by bare name and belong to macOS VMs only. - stopVMMonitor(name) - releaseVMTyping(name) - releaseVMThumbnail(name) - } else { - releaseVMTypingForDriver(ref.DriverID, ref.Name) - releaseVMThumbnailForDriver(ref.DriverID, ref.Name) - } - if parsed { - a.stateTable().Delete(ref) - } - a.cancelRebootWatcherKey(key) - if gt != nil { - gt.UnregisterVM(key) - } - } - if ib != nil { - ib.SetTargets(imeTargets) - } - a.syncKeymapRules() - a.syncFullscreenHotkeyTargets() - if tm != nil { - effLoc := i18n.EffectiveLocale(loc) - if runningCount >= 1 { - tm.UpdateTooltip(i18n.M(effLoc, "tray.running", i18n.Vars{"count": runningCount})) - } else { - tm.UpdateTooltip("Reims-Go") - } - } - shownDetails := make(map[string]driver.VMInfo, len(toPin)) - for _, cand := range toPin { - det, err := a.resolveVMInfo(cand.driverID, cand.name) - if err != nil { - // Retry boot discovery if the runtime was still starting. - delete(pinnedPIDs, cand.pid) - continue - } - vmDir := cand.dir - if vmDir == "" { - vmDir = det.Directory - } - if det.Directory == "" { - det.Directory = vmDir - } - shownDetails[vmKeyForDriver(cand.driverID, cand.name)] = det - if line, _ := a.applyVMAffinity(loc, cachedHost, driver.NewVMRef(cand.driverID, cand.name), vmDir, autoPin, cand.pid, det.CPUs, false); line != "" { - if driver.NewVMRef(cand.driverID, cand.name).DriverID == driver.BuiltinReimsMacOSDriverID { - a.emitLog(cand.name, line) - } else { - a.emitVMLogForDriver(cand.driverID, cand.name, line) - } - } - } - if guideMgr != nil { - for _, vm := range vms { - if vm.State != "running" || vm.PID == nil || *vm.PID <= 0 { - continue - } - // The install guide belongs to the macOS installer flow. - if len(vm.Capabilities) > 0 && !driver.HasCapability(vm.Capabilities, driver.CapOpenCore) { - continue - } - pid := *vm.PID - if guideCheckedPIDs[pid] { - continue - } - det, ok := shownDetails[vmKeyForDriver(vm.DriverID, vm.Name)] - if !ok { - d, err := a.resolveVMInfo(vm.DriverID, vm.Name) - if err != nil { - continue - } - if d.Directory == "" { - d.Directory = vm.Dir - } - det = d - } - guideCheckedPIDs[pid] = true - if a.maybeStartInstallGuide(ctx, guideMgr, vm.Name, pid, det, loc) { - guidesChanged = true - } - } - } - if sig != lastSig || guidesChanged || listRecovered { - lastSig = sig - a.emitStateChanged() - } - } -} - -func (a *App) listVMsInternal(ctx context.Context) ([]driver.VMListItem, error) { - a.mu.Lock() - svc := a.lifecycleSvc - a.mu.Unlock() - if svc != nil { - vms, err := svc.List(ctx) - out := make([]driver.VMListItem, 0, len(vms)) - for _, vm := range vms { - out = append(out, driver.VMListItem{ - Name: vm.Name, DriverID: vm.DriverID, Dir: vm.Directory, PID: vm.PID, State: vm.State, - Capabilities: vm.Capabilities, GuestOS: vm.GuestOS, Phase: vm.Phase, Ready: vm.Ready, Endpoints: vm.Endpoints, - }) - } - return out, err - } - c, err := a.client() - if err != nil { - return nil, err - } - vms, err := c.List(ctx) - if err != nil { - return nil, err - } - for i := range vms { - vms[i].DriverID = driver.BuiltinReimsMacOSDriverID - } - enrichMacOSVMListStates(vms) - return vms, nil -} - -// qemuImage is the executable reims-ctl reports as a running VM's PID. -const qemuImage = "qemu-system-x86_64.exe" - -// watchExits waits on every running VM's QEMU process not yet watched and -// calls onExit the moment one exits, so a VM that stops by itself (macOS shut -// down, QEMU quit or crashed) shows as stopped at once instead of at the next -// steady poll. watched holds the PIDs being waited on; PIDs no longer running -// are dropped so a reused PID is watched again. -func watchExits(ctx context.Context, vms []driver.VMListItem, watched map[int]bool, onExit func()) { - running := make(map[int]bool, len(vms)) - for _, vm := range vms { - if vm.State != "running" || vm.PID == nil || *vm.PID <= 0 { - continue - } - pid := *vm.PID - running[pid] = true - if watched[pid] { - continue - } - watched[pid] = true - go func() { - if err := host.WaitProcessExit(ctx, uint32(pid), qemuImage); err == nil { - onExit() - } - }() - } - for pid := range watched { - if !running[pid] { - delete(watched, pid) - } - } -} - -func prunePinnedPIDs(pinned map[int]bool, vms []driver.VMListItem) { - running := make(map[int]struct{}, len(vms)) - for _, vm := range vms { - if vm.State == "running" && vm.PID != nil && *vm.PID > 0 { - running[*vm.PID] = struct{}{} - } - } - for pid := range pinned { - if _, ok := running[pid]; !ok { - delete(pinned, pid) - } - } -} - -// polledVMs returns the list pollVMs saw last if it is at most polledMaxAge -// old, so per-VM samplers (stats, thumbnails, heartbeats) don't each spawn -// their own `reims-ctl list`. A stale or missing poll falls back to one. -func (a *App) polledVMs(ctx context.Context) ([]driver.VMListItem, error) { - a.mu.Lock() - if !a.lastVMsAt.IsZero() && time.Since(a.lastVMsAt) <= polledMaxAge { - vms := append([]driver.VMListItem(nil), a.lastVMs...) - err := a.lastVMListErr - a.mu.Unlock() - return vms, err - } - a.mu.Unlock() - return a.listVMsInternal(ctx) -} - -// polledVM looks name up in polledVMs. -func (a *App) polledVM(name string) (driver.VMListItem, bool) { - vms, err := a.polledVMs(context.Background()) - if err != nil { - return driver.VMListItem{}, false - } - for _, vm := range vms { - if vm.Name == name { - return vm, true - } - } - return driver.VMListItem{}, false -} - -func (a *App) polledVMForDriver(driverID, name string) (driver.VMListItem, bool) { - vms, err := a.polledVMs(context.Background()) - if err != nil { - return driver.VMListItem{}, false - } - driverID = driver.CanonicalDriverID(driverID) - if driverID == "" { - driverID = driver.BuiltinReimsMacOSDriverID - } - for _, vm := range vms { - if vm.Name == name && driver.CanonicalDriverID(vm.DriverID) == driverID { - return vm, true - } - } - return driver.VMListItem{}, false -} - -// wakePoll marks the polled list stale and runs pollVMs now. Call it after -// anything that changes which VMs exist or run. -func (a *App) wakePoll() { - a.mu.Lock() - a.lastVMsAt = time.Time{} - a.mu.Unlock() - select { - case a.pollWake <- struct{}{}: - default: - } -} - // cachedDiskPath is one VM's disk path from `reims-ctl show`, kept for // diskPathTTL so GetVMStats doesn't run `show` every few seconds. type cachedDiskPath struct { diff --git a/internal/app/app_poll_test.go b/internal/app/app_poll_test.go index a1b80fd..32574e5 100644 --- a/internal/app/app_poll_test.go +++ b/internal/app/app_poll_test.go @@ -2,10 +2,13 @@ package app import ( "context" + "errors" "runtime" + "slices" "testing" "time" + "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/macos/reims" ) @@ -140,3 +143,39 @@ func TestCachedVMPID(t *testing.T) { t.Fatalf("cachedVMPID(missing-vm) = %d, want 0", got) } } + +func TestRecordVMListReportsWhatChanged(t *testing.T) { + mac := driver.BuiltinReimsMacOSDriverID + item := func(name, state string) driver.VMListItem { + return driver.VMListItem{DriverID: mac, Name: name, State: state} + } + key := func(name string) string { return vmKeyForDriver(mac, name) } + a := &App{ + lastVMs: []driver.VMListItem{item("gone", "running"), item("crashed", "running"), item("rebooting", "running"), item("kept", "running")}, + lastVMListErr: errors.New("reims-ctl failed"), + transitions: map[string]string{key("rebooting"): "starting", key("new"): "starting"}, + pendingChanges: map[string][]PendingChange{}, + diskPaths: map[string]cachedDiskPath{key("old-disk"): {}, key("kept"): {}}, + } + change := a.recordVMList([]driver.VMListItem{item("crashed", "stopped"), item("rebooting", "stopped"), item("kept", "running"), item("new", "running")}) + + if !change.recovered || a.lastVMListErr != nil { + t.Error("a good listing after a failed one must count as recovered") + } + if len(change.removed) != 2 { + t.Errorf("removed = %v, want gone and old-disk", change.removed) + } + if _, ok := a.diskPaths[key("old-disk")]; ok || len(a.diskPaths) != 1 { + t.Errorf("diskPaths = %v, want only kept", a.diskPaths) + } + // "rebooting" is down only because it is being started again. + if !slices.Equal(change.stoppedBridges, []string{"crashed"}) { + t.Errorf("stoppedBridges = %v, want crashed", change.stoppedBridges) + } + if _, ok := a.transitions[key("new")]; ok { + t.Error("a running VM must not stay in the starting transition") + } + if a.transitions[key("rebooting")] != "starting" { + t.Error("an unfinished transition must be kept") + } +} diff --git a/internal/app/console_router.go b/internal/app/console_router.go index 3d3f13e..cf3d4f3 100644 --- a/internal/app/console_router.go +++ b/internal/app/console_router.go @@ -49,7 +49,7 @@ func (a *App) resolveConsoleRoute(vm driver.VMInfo) (consoleRoute, error) { if cd, ok := driver.DriverServesConsole(a.driverFor(vm)); ok && driver.HasCapability(vm.Capabilities, driver.CapConsole) { return consoleRoute{kind: consoleRouteDriver, vm: vm, console: cd}, nil } - if !driver.IsHosted(vm.Capabilities) && (len(vm.Capabilities) == 0 || driver.HasCapability(vm.Capabilities, driver.CapQMP)) { + if !driver.IsHosted(vm.Capabilities) && driver.SupportsCapability(vm.Capabilities, driver.CapQMP) { return consoleRoute{kind: consoleRouteQMP, vm: vm}, nil } return consoleRoute{}, fmt.Errorf("computer_use_unavailable: driver %q has no console the host can reach", vm.DriverID) diff --git a/internal/app/fullscreen_hotkey_flow.go b/internal/app/fullscreen_hotkey_flow.go index ca59368..db07531 100644 --- a/internal/app/fullscreen_hotkey_flow.go +++ b/internal/app/fullscreen_hotkey_flow.go @@ -109,10 +109,11 @@ func (a *App) fullscreenHotkeyTargets(vms []driver.VMListItem, legacy bool, cach var targets []host.IMETarget support := make(map[fullscreenHotkeyVM]bool, len(cached)) for _, vm := range vms { - if vm.State != "running" || vm.PID == nil || *vm.PID <= 0 { + pid := vm.RunningPID() + if pid == 0 { continue } - target := host.IMETarget{VMName: vm.Name, VMDir: vm.Dir, PID: uint32(*vm.PID)} + target := host.IMETarget{VMName: vm.Name, VMDir: vm.Dir, PID: uint32(pid)} key := fullscreenHotkeyVM{driverID: vm.DriverID, target: target} supported, known := cached[key] if !known { @@ -146,7 +147,7 @@ func (a *App) onFullscreenHotkey(target host.IMETarget, hwnd uintptr) { return } for _, vm := range a.lastVMs { - if vm.State != "running" || vm.Name != target.VMName || vm.Dir != target.VMDir || vm.PID == nil || *vm.PID != int(target.PID) { + if vm.Name != target.VMName || vm.Dir != target.VMDir || vm.RunningPID() == 0 || vm.RunningPID() != int(target.PID) { continue } a.mu.Unlock() diff --git a/internal/app/install_guide.go b/internal/app/install_guide.go index aff10fe..cf4db49 100644 --- a/internal/app/install_guide.go +++ b/internal/app/install_guide.go @@ -75,6 +75,59 @@ func installGuideKind(d reims.VMDetail) (installguide.Kind, bool) { return installguide.BuiltIn, startprep.ReadRecoveryMarker(d.Directory) == "on" } +// guideTracker follows the install guides of running VMs for the poll loop. +type guideTracker struct { + a *App + mgr *installguide.Manager // nil while the guide service is disabled + checked map[int]bool // PIDs already offered a guide by mgr +} + +func (a *App) newGuideTracker() *guideTracker { + return &guideTracker{a: a, mgr: a.getInstallGuideManager(), checked: make(map[int]bool)} +} + +// cancelStopped closes the guides of VMs that stopped and reports whether any +// did. A restarted guide service checks every running VM again. +func (t *guideTracker) cancelStopped(vms []driver.VMListItem) bool { + prunePinnedPIDs(t.checked, vms) + if mgr := t.a.getInstallGuideManager(); mgr != t.mgr { + clear(t.checked) + t.mgr = mgr + } + return t.mgr != nil && t.mgr.CancelStopped(runningPIDs(vms)) +} + +// startMissing opens the guide of running VMs that need one and reports +// whether any opened. details holds VM details already looked up, by VM key. +func (t *guideTracker) startMissing(ctx context.Context, vms []driver.VMListItem, details map[string]driver.VMInfo, loc i18n.Locale) bool { + if t.mgr == nil { + return false + } + started := false + for _, vm := range vms { + pid := vm.RunningPID() + // The install guide belongs to the macOS installer flow. + if pid == 0 || t.checked[pid] || !driver.SupportsCapability(vm.Capabilities, driver.CapOpenCore) { + continue + } + det, ok := details[vmKeyForDriver(vm.DriverID, vm.Name)] + if !ok { + var err error + if det, err = t.a.resolveVMInfo(vm.DriverID, vm.Name); err != nil { + continue + } + if det.Directory == "" { + det.Directory = vm.Dir + } + } + t.checked[pid] = true + if t.a.maybeStartInstallGuide(ctx, t.mgr, vm.Name, pid, det, loc) { + started = true + } + } + return started +} + func (a *App) maybeStartInstallGuide(ctx context.Context, gm *installguide.Manager, name string, pid int, vm driver.VMInfo, loc i18n.Locale) bool { if gm == nil || pid <= 0 || gm.HasActive(name, pid) { return false @@ -114,7 +167,7 @@ func (a *App) buildInstallGuide(ctx context.Context, g installguide.Guide, d rei return err } for _, vm := range vms { - if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID == pid { + if vm.Name == name && vm.RunningPID() == pid { return ctx.Err() } } diff --git a/internal/app/keymap_flow.go b/internal/app/keymap_flow.go index 104083f..f15769d 100644 --- a/internal/app/keymap_flow.go +++ b/internal/app/keymap_flow.go @@ -118,7 +118,7 @@ func (a *App) syncKeymapRulesLocked() { var targets []host.IMETarget pids := make(map[string]int) for _, vm := range vms { - if vm.State != "running" || vm.PID == nil || *vm.PID <= 0 { + if vm.RunningPID() == 0 { if srv != nil { srv.SetKeymapCarrier(vm.Name, false) } diff --git a/internal/app/macos_lifecycle_native.go b/internal/app/macos_lifecycle_native.go index bf63ee4..451d7ff 100644 --- a/internal/app/macos_lifecycle_native.go +++ b/internal/app/macos_lifecycle_native.go @@ -29,12 +29,7 @@ const ( func (a *App) cachedVMPID(name string) int { a.mu.Lock() defer a.mu.Unlock() - for _, vm := range a.lastVMs { - if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 { - return *vm.PID - } - } - return 0 + return runningPIDByName(a.lastVMs, name) } func (a *App) waitForVMProcessExit(ctx context.Context, pid int, timeout time.Duration) { diff --git a/internal/app/vm_close_windows.go b/internal/app/vm_close_windows.go index 28c2708..5f184f5 100644 --- a/internal/app/vm_close_windows.go +++ b/internal/app/vm_close_windows.go @@ -12,16 +12,6 @@ import ( "github.com/Nwflower/reims-go/internal/tray" ) -// runningVMPID returns the process ID of the named VM when it is running. -func runningVMPID(vms []driver.VMListItem, name string) (uint32, bool) { - for _, vm := range vms { - if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 { - return uint32(*vm.PID), true - } - } - return 0, false -} - func (a *App) confirmVMWindowClose(name string) { if _, pending := a.vmClosePrompts.LoadOrStore(name, struct{}{}); pending { return @@ -66,7 +56,7 @@ func (a *App) confirmVMWindowClose(name string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, err.Error()) return } - if current, running := runningVMPID(vms, ref.Name); !running || current != uint32(pid) { + if current := runningPIDByName(vms, ref.Name); current == 0 || current != pid { return } if choice == host.VMCloseSuspend { diff --git a/internal/app/vm_monitor.go b/internal/app/vm_monitor.go index 94a4a82..91e8e84 100644 --- a/internal/app/vm_monitor.go +++ b/internal/app/vm_monitor.go @@ -197,10 +197,8 @@ func (a *App) currentVMPID(ctx context.Context, name string) (int, bool) { } for _, vm := range vms { if vm.Name == name { - if vm.State == "running" && vm.PID != nil && *vm.PID > 0 { - return *vm.PID, true - } - return 0, false + pid := vm.RunningPID() + return pid, pid > 0 } } return 0, false diff --git a/internal/app/vm_poll.go b/internal/app/vm_poll.go new file mode 100644 index 0000000..fc5667c --- /dev/null +++ b/internal/app/vm_poll.go @@ -0,0 +1,458 @@ +package app + +import ( + "context" + "fmt" + "maps" + "strings" + "time" + + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" +) + +// pollVMs refreshes the VM list every pollBusy while a VM is starting or +// stopping and every pollSteady otherwise; each tick runs one `reims-ctl list`. +// Start, stop and delete call wakePoll so their result shows up at once. +const ( + pollBusy = 2 * time.Second + // Exits are caught at once by watchExits and GUI actions call wakePoll, so + // the steady tick only has to notice VMs started or removed elsewhere (CLI). + pollSteady = 10 * time.Second + // polledMaxAge is how old lastVMs may be for polledVMs to reuse it. It sits + // above pollSteady so a poll that runs a little late still counts. + polledMaxAge = pollSteady + 3*time.Second +) + +// vmPoller holds what the poll loop remembers between ticks. Only the loop +// touches it, so it needs no lock. +type vmPoller struct { + a *App + // host is inspected once: pinning only needs the static P-core mask. + host host.Report + lastSig string + pinned map[int]bool + exitWatched map[int]bool + guides *guideTracker +} + +func (a *App) pollVMs(ctx context.Context) { + timer := time.NewTimer(pollBusy) + defer timer.Stop() + a.mu.Lock() + root := a.cfg.DataRoot + a.mu.Unlock() + p := &vmPoller{ + a: a, + host: host.Inspect(root), + pinned: make(map[int]bool), + exitWatched: make(map[int]bool), + guides: a.newGuideTracker(), + } + for { + select { + case <-ctx.Done(): + return + case <-timer.C: + case <-a.pollWake: + } + a.mu.Lock() + next := pollSteady + if len(a.transitions) > 0 { + next = pollBusy + } + a.mu.Unlock() + timer.Reset(next) + // reims-ctl keeps its state in the data folder; leave it alone until + // setup has chosen one, and while it is open read-only. + if a.dataRootUsable() { + p.tick(ctx) + } + } +} + +// tick lists the VMs once and brings everything that follows them up to date. +func (p *vmPoller) tick(ctx context.Context) { + a := p.a + vms, err := a.listVMsInternal(ctx) + if err != nil { + if a.recordVMListError(vms, err) { + a.emitStateChanged() + } + return + } + a.syncComputerUseOwnership(vms) + // Only VMs whose process the host neither spawned (the broker watches + // those through their job) nor leaves to the driver (hosted) need a + // per-PID exit watcher. + procVMs := make([]driver.VMListItem, 0, len(vms)) + for _, vm := range vms { + if !driver.IsHosted(vm.Capabilities) && !a.brokerRunsVM(vm.DriverID, vm.Name) { + procVMs = append(procVMs, vm) + } + } + watchExits(ctx, procVMs, p.exitWatched, a.wakePoll) + + change := a.recordVMList(vms) + a.mu.Lock() + loc := a.cfg.Locale + autoPin := a.cfg.AutoPinPCores + tm := a.trayMgr + ib := a.imeBridge + gt := a.guestTools + a.mu.Unlock() + + for _, name := range change.stoppedBridges { + a.stopPacketBridge(name) + if gt != nil { + gt.StopManagementNetwork(name) + } + } + prunePinnedPIDs(p.pinned, vms) + guidesChanged := p.guides.cancelStopped(vms) + for key := range change.removed { + a.forgetVM(key) + } + if ib != nil { + ib.SetTargets(imeTargets(vms)) + } + a.syncKeymapRules() + a.syncFullscreenHotkeyTargets() + if tm != nil { + tm.UpdateTooltip(trayTooltip(loc, vms)) + } + details := p.pinStarted(vms, loc, autoPin) + if p.guides.startMissing(ctx, vms, details, loc) { + guidesChanged = true + } + if change.signature != p.lastSig || guidesChanged || change.recovered { + p.lastSig = change.signature + a.emitStateChanged() + } +} + +// recordVMListError remembers a failed listing and reports whether the error +// is new. +func (a *App) recordVMListError(vms []driver.VMListItem, err error) bool { + a.mu.Lock() + defer a.mu.Unlock() + changed := a.lastVMListErr == nil || a.lastVMListErr.Error() != err.Error() + a.lastVMListErr = err + if a.lastVMsAt.IsZero() && a.lastVMs == nil { + a.lastVMs = vms + } + a.lastVMsAt = time.Now() + return changed +} + +// vmListChange is how a listing differs from the one before it. +type vmListChange struct { + signature string // everything the UI shows about the VMs + removed map[string]struct{} // keys of VMs no longer listed + stoppedBridges []string // macOS VMs that stopped by themselves + recovered bool // the previous listing failed +} + +// recordVMList makes vms the current list and settles finished transitions. +func (a *App) recordVMList(vms []driver.VMListItem) vmListChange { + a.mu.Lock() + defer a.mu.Unlock() + change := vmListChange{removed: make(map[string]struct{}), recovered: a.lastVMListErr != nil} + live := make(map[string]driver.VMListItem, len(vms)) + var sig strings.Builder + for _, vm := range vms { + key := vmKeyForDriver(vm.DriverID, vm.Name) + live[key] = vm + if transitionDone(a.transitions[key], vm.State) { + delete(a.transitions, key) + if vm.State == "stopped" { + delete(a.pendingChanges, key) + } + } + fmt.Fprintf(&sig, "%s:%s:%s:%s:%s:%s;", key, vm.State, a.transitions[key], vm.Phase, readyToken(vm.Ready), endpointSignature(vm.Endpoints)) + } + change.signature = sig.String() + + // gone reports whether key is no longer listed, and notes it as removed. + gone := func(key string) bool { + if _, ok := live[key]; ok { + return false + } + change.removed[key] = struct{}{} + return true + } + for key := range a.rebootWatchers { + gone(key) + } + maps.DeleteFunc(a.diskPaths, func(key string, _ cachedDiskPath) bool { return gone(key) }) + maps.DeleteFunc(a.procSamples, func(key string, _ host.ProcessSample) bool { return gone(key) }) + for _, prev := range a.lastVMs { + key := vmKeyForDriver(prev.DriverID, prev.Name) + if gone(key) || prev.State != "running" || prev.DriverID != driver.BuiltinReimsMacOSDriverID { + continue + } + if tr := a.transitions[key]; tr != "starting" && tr != "resuming" && live[key].State != "running" { + change.stoppedBridges = append(change.stoppedBridges, prev.Name) + } + } + a.lastVMs = append([]driver.VMListItem(nil), vms...) + a.lastVMsAt = time.Now() + a.lastVMListErr = nil + return change +} + +// transitionDone reports whether a VM now in state has finished transition. +func transitionDone(transition, state string) bool { + switch transition { + case "starting", "resuming": + return state == "running" + case "stopping": + return state == "stopped" + case "suspending": + return state == "suspended" || state == "stopped" + } + return false +} + +// forgetVM releases everything held for a VM that is no longer listed. +func (a *App) forgetVM(key string) { + name := vmNameFromKey(key) + ref, parsed := driver.ParseVMRef(key) + if parsed && ref.DriverID == driver.BuiltinReimsMacOSDriverID { + a.stopPacketBridge(name) + } + a.forgetComputerUseOwnedVM(key) + // A disabled driver's VMs may leave the list without being deleted. + if parsed && a.driverFor(driver.VMInfo{DriverID: ref.DriverID}) != nil { + a.discardMaterializedSecretsForVM(key) + } + a.mu.Lock() + delete(a.transitions, key) + delete(a.pendingChanges, key) + gt := a.guestTools + a.mu.Unlock() + if !parsed || ref.DriverID == driver.BuiltinReimsMacOSDriverID { + // These helpers are keyed by bare name and belong to macOS VMs only. + stopVMMonitor(name) + releaseVMTyping(name) + releaseVMThumbnail(name) + } else { + releaseVMTypingForDriver(ref.DriverID, ref.Name) + releaseVMThumbnailForDriver(ref.DriverID, ref.Name) + } + if parsed { + a.stateTable().Delete(ref) + } + a.cancelRebootWatcherKey(key) + if gt != nil { + gt.UnregisterVM(key) + } +} + +// imeTargets lists the running VMs the remote IME bridge can type into. It +// types through the macOS guest's tools. +func imeTargets(vms []driver.VMListItem) []host.IMETarget { + var targets []host.IMETarget + for _, vm := range vms { + if pid := vm.RunningPID(); pid > 0 && driver.SupportsCapability(vm.Capabilities, driver.CapGuestTools) { + targets = append(targets, host.IMETarget{VMName: vm.Name, VMDir: vm.Dir, PID: uint32(pid)}) + } + } + return targets +} + +func trayTooltip(loc i18n.Locale, vms []driver.VMListItem) string { + running := 0 + for _, vm := range vms { + if vm.State == "running" { + running++ + } + } + if running == 0 { + return "Reims-Go" + } + return i18n.M(i18n.EffectiveLocale(loc), "tray.running", i18n.Vars{"count": running}) +} + +// pinStarted applies the CPU affinity of VMs that started since the last tick. +// It returns the details it looked up, by VM key. +func (p *vmPoller) pinStarted(vms []driver.VMListItem, loc i18n.Locale, autoPin bool) map[string]driver.VMInfo { + details := make(map[string]driver.VMInfo) + for _, vm := range vms { + pid := vm.RunningPID() + if pid == 0 || p.pinned[pid] || driver.IsHosted(vm.Capabilities) || !driver.SupportsCapability(vm.Capabilities, driver.CapAffinity) { + continue + } + det, err := p.a.resolveVMInfo(vm.DriverID, vm.Name) + if err != nil { + // Try again next tick: the runtime may still be starting. + continue + } + p.pinned[pid] = true + vmDir := vm.Dir + if vmDir == "" { + vmDir = det.Directory + } + if det.Directory == "" { + det.Directory = vmDir + } + details[vmKeyForDriver(vm.DriverID, vm.Name)] = det + ref := driver.NewVMRef(vm.DriverID, vm.Name) + if line, _ := p.a.applyVMAffinity(loc, p.host, ref, vmDir, autoPin, pid, det.CPUs, false); line != "" { + if ref.DriverID == driver.BuiltinReimsMacOSDriverID { + p.a.emitLog(vm.Name, line) + } else { + p.a.emitVMLogForDriver(vm.DriverID, vm.Name, line) + } + } + } + return details +} + +func (a *App) listVMsInternal(ctx context.Context) ([]driver.VMListItem, error) { + a.mu.Lock() + svc := a.lifecycleSvc + a.mu.Unlock() + if svc != nil { + vms, err := svc.List(ctx) + out := make([]driver.VMListItem, 0, len(vms)) + for _, vm := range vms { + out = append(out, driver.VMListItem{ + Name: vm.Name, DriverID: vm.DriverID, Dir: vm.Directory, PID: vm.PID, State: vm.State, + Capabilities: vm.Capabilities, GuestOS: vm.GuestOS, Phase: vm.Phase, Ready: vm.Ready, Endpoints: vm.Endpoints, + }) + } + return out, err + } + c, err := a.client() + if err != nil { + return nil, err + } + vms, err := c.List(ctx) + if err != nil { + return nil, err + } + for i := range vms { + vms[i].DriverID = driver.BuiltinReimsMacOSDriverID + } + enrichMacOSVMListStates(vms) + return vms, nil +} + +// qemuImage is the executable reims-ctl reports as a running VM's PID. +const qemuImage = "qemu-system-x86_64.exe" + +// watchExits waits on every running VM's QEMU process not yet watched and +// calls onExit the moment one exits, so a VM that stops by itself (macOS shut +// down, QEMU quit or crashed) shows as stopped at once instead of at the next +// steady poll. watched holds the PIDs being waited on; PIDs no longer running +// are dropped so a reused PID is watched again. +func watchExits(ctx context.Context, vms []driver.VMListItem, watched map[int]bool, onExit func()) { + running := make(map[int]bool, len(vms)) + for _, vm := range vms { + pid := vm.RunningPID() + if pid == 0 { + continue + } + running[pid] = true + if watched[pid] { + continue + } + watched[pid] = true + go func() { + if err := host.WaitProcessExit(ctx, uint32(pid), qemuImage); err == nil { + onExit() + } + }() + } + for pid := range watched { + if !running[pid] { + delete(watched, pid) + } + } +} + +// runningPIDs is the set of process IDs of the running VMs. +func runningPIDs(vms []driver.VMListItem) map[int]bool { + running := make(map[int]bool, len(vms)) + for _, vm := range vms { + if pid := vm.RunningPID(); pid > 0 { + running[pid] = true + } + } + return running +} + +// runningPIDByName is the process ID of the running VM called name, or 0. +func runningPIDByName(vms []driver.VMListItem, name string) int { + for _, vm := range vms { + if pid := vm.RunningPID(); pid > 0 && vm.Name == name { + return pid + } + } + return 0 +} + +func prunePinnedPIDs(pinned map[int]bool, vms []driver.VMListItem) { + running := runningPIDs(vms) + maps.DeleteFunc(pinned, func(pid int, _ bool) bool { return !running[pid] }) +} + +// polledVMs returns the list pollVMs saw last if it is at most polledMaxAge +// old, so per-VM samplers (stats, thumbnails, heartbeats) don't each spawn +// their own `reims-ctl list`. A stale or missing poll falls back to one. +func (a *App) polledVMs(ctx context.Context) ([]driver.VMListItem, error) { + a.mu.Lock() + if !a.lastVMsAt.IsZero() && time.Since(a.lastVMsAt) <= polledMaxAge { + vms := append([]driver.VMListItem(nil), a.lastVMs...) + err := a.lastVMListErr + a.mu.Unlock() + return vms, err + } + a.mu.Unlock() + return a.listVMsInternal(ctx) +} + +// polledVM looks name up in polledVMs. +func (a *App) polledVM(name string) (driver.VMListItem, bool) { + vms, err := a.polledVMs(context.Background()) + if err != nil { + return driver.VMListItem{}, false + } + for _, vm := range vms { + if vm.Name == name { + return vm, true + } + } + return driver.VMListItem{}, false +} + +func (a *App) polledVMForDriver(driverID, name string) (driver.VMListItem, bool) { + vms, err := a.polledVMs(context.Background()) + if err != nil { + return driver.VMListItem{}, false + } + driverID = driver.CanonicalDriverID(driverID) + if driverID == "" { + driverID = driver.BuiltinReimsMacOSDriverID + } + for _, vm := range vms { + if vm.Name == name && driver.CanonicalDriverID(vm.DriverID) == driverID { + return vm, true + } + } + return driver.VMListItem{}, false +} + +// wakePoll marks the polled list stale and runs pollVMs now. Call it after +// anything that changes which VMs exist or run. +func (a *App) wakePoll() { + a.mu.Lock() + a.lastVMsAt = time.Time{} + a.mu.Unlock() + select { + case a.pollWake <- struct{}{}: + default: + } +} diff --git a/internal/driver/driver.go b/internal/driver/driver.go index cc33f87..5052fc9 100644 --- a/internal/driver/driver.go +++ b/internal/driver/driver.go @@ -58,6 +58,12 @@ func HasCapability(caps []string, capability string) bool { return false } +// SupportsCapability is HasCapability for a listed VM. A list that carries no +// capabilities comes from reims-ctl, whose VMs support everything. +func SupportsCapability(caps []string, capability string) bool { + return len(caps) == 0 || HasCapability(caps, capability) +} + // IsHosted reports whether caps marks a driver-hosted VM. func IsHosted(caps []string) bool { return HasCapability(caps, CapHosted) } @@ -120,6 +126,15 @@ type VMListItem struct { Endpoints []VMEndpoint `json:"endpoints,omitempty"` } +// RunningPID is the VM's process ID, or 0 when it is not running or has no +// process on this host. +func (vm VMListItem) RunningPID() int { + if vm.State != "running" || vm.PID == nil || *vm.PID <= 0 { + return 0 + } + return *vm.PID +} + // VMInfo is the generic cross-driver VM model (§5.3). type VMInfo struct { Name string `json:"name"` From 0ed522656d74f046c37753f277b458e886fb5f7e 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: Thu, 3 Dec 2026 21:27:52 -0700 Subject: [PATCH 09/22] fix(app): log every VM line under the VM's key Some lines used the bare VM name as their source, so the log lines reported with a failed command-line start left them out. Disk tasks also kept the VM name in their step text. Co-Authored-By: Claude Opus 5.5 --- changes/start-failure-log-lines.json | 7 +++++++ internal/app/create_flow.go | 2 +- internal/app/guesttools_flow.go | 22 +++++++++++----------- internal/app/macos_settings.go | 8 ++++---- internal/app/plugins_flow.go | 2 +- internal/app/suspend_flow.go | 8 ++++---- internal/app/tasks.go | 16 +++++++++++----- internal/app/vm_close_windows.go | 2 +- internal/app/vm_poll.go | 6 +----- internal/app/window_launch.go | 6 +++--- 10 files changed, 44 insertions(+), 35 deletions(-) create mode 100644 changes/start-failure-log-lines.json diff --git a/changes/start-failure-log-lines.json b/changes/start-failure-log-lines.json new file mode 100644 index 0000000..5b348e9 --- /dev/null +++ b/changes/start-failure-log-lines.json @@ -0,0 +1,7 @@ +{ + "group": "fixes", + "order": 0, + "authors": ["Nwflower"], + "zh": "从命令行启动虚拟机失败时,一并显示 Guest Tools 和网络相关的日志。", + "en": "Include Guest Tools and network log lines when a VM fails to start from the command line." +} diff --git a/internal/app/create_flow.go b/internal/app/create_flow.go index 56280ab..767376f 100644 --- a/internal/app/create_flow.go +++ b/internal/app/create_flow.go @@ -218,7 +218,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) { if _, networkErr := a.applyVMNetwork(ctx, opts.Name, "bridge", opts.UplinkGUID); networkErr != nil { err = networkmsg.Error("create_bridge_pending", networkErr, "name", opts.Name) finishTask(err) - a.emitLog(opts.Name, networkmsg.Text(a.locale(), "log.create_bridge_failed")+" "+networkmsg.Localize(networkErr, a.locale()).Error()) + a.emitVMLog(opts.Name, networkmsg.Text(a.locale(), "log.create_bridge_failed")+" "+networkmsg.Localize(networkErr, a.locale()).Error()) a.emitStateChanged() return err } diff --git a/internal/app/guesttools_flow.go b/internal/app/guesttools_flow.go index bbc9aaf..36869bb 100644 --- a/internal/app/guesttools_flow.go +++ b/internal/app/guesttools_flow.go @@ -301,12 +301,12 @@ func (a *App) registerSavedGuestToolsConfig(srv *guesttools.Server, port int, na return } if err := requireGuestToolsVM(vmDir); err != nil { - a.emitLog(name, "Warning: could not register Guest Tools config: "+err.Error()) + a.emitVMLog(name, "Warning: could not register Guest Tools config: "+err.Error()) return } cfg, ok, err := guesttools.ReadVMConfigStrict(vmDir) if err != nil { - a.emitLog(name, "Warning: could not load Guest Tools config: "+err.Error()) + a.emitVMLog(name, "Warning: could not load Guest Tools config: "+err.Error()) return } if !ok { @@ -318,7 +318,7 @@ func (a *App) registerSavedGuestToolsConfig(srv *guesttools.Server, port int, na cfg.VMDir = vmDir cfg.QEMUPath = a.activeQemuPath() if _, err := srv.EnsureManagementNetwork(cfg); err != nil { - a.emitLog(name, networkmsg.Text(a.locale(), "log.management_restore_failed")+" "+networkmsg.Localize(err, a.locale()).Error()) + a.emitVMLog(name, networkmsg.Text(a.locale(), "log.management_restore_failed")+" "+networkmsg.Localize(err, a.locale()).Error()) return } } else if len(networkMode) > 0 { @@ -332,12 +332,12 @@ func (a *App) registerSavedGuestToolsConfig(srv *guesttools.Server, port int, na if sharedDirChanged || cfg.Port != port { cfg.Port = port if err := guesttools.SaveVMConfig(vmDir, cfg); err != nil { - a.emitLog(name, "Warning: could not save Guest Tools config: "+err.Error()) + a.emitVMLog(name, "Warning: could not save Guest Tools config: "+err.Error()) return } } if err := a.registerGuestToolsConfig(srv, vmDir, cfg); err != nil { - a.emitLog(name, "Warning: could not register Guest Tools config: "+err.Error()) + a.emitVMLog(name, "Warning: could not register Guest Tools config: "+err.Error()) } } @@ -359,7 +359,7 @@ func (a *App) populateGuestToolsDetail(d *reims.VMDetail, epoch uint64) { } cfg, ok, err := guesttools.ReadVMConfigStrict(d.Directory) if err != nil { - a.emitLog(d.Name, "Warning: could not load Guest Tools config: "+err.Error()) + a.emitVMLog(d.Name, "Warning: could not load Guest Tools config: "+err.Error()) return } if ok { @@ -369,12 +369,12 @@ func (a *App) populateGuestToolsDetail(d *reims.VMDetail, epoch uint64) { if sharedDir != "" && cfg.SharedDir != sharedDir { cfg.SharedDir = sharedDir if err := guesttools.SaveVMConfig(d.Directory, cfg); err != nil { - a.emitLog(d.Name, "Warning: could not save Guest Tools config: "+err.Error()) + a.emitVMLog(d.Name, "Warning: could not save Guest Tools config: "+err.Error()) } } if srv, _, err := a.ensureGuestToolsBridge(); err == nil { if err := a.registerGuestToolsConfig(srv, d.Directory, cfg); err != nil { - a.emitLog(d.Name, "Warning: could not register Guest Tools config: "+err.Error()) + a.emitVMLog(d.Name, "Warning: could not register Guest Tools config: "+err.Error()) return } st := srv.Status(d.Name, 15*time.Second) @@ -397,7 +397,7 @@ func (a *App) syncGuestTools(c *reims.Client, name string, cur *reims.VMDetail, _, configured, err := guesttools.ReadVMConfigStrict(cur.Directory) unlock() if err != nil { - a.emitLog(name, "Warning: could not load Guest Tools config: "+err.Error()) + a.emitVMLog(name, "Warning: could not load Guest Tools config: "+err.Error()) return } if !attached && !configured { @@ -417,7 +417,7 @@ func (a *App) syncGuestTools(c *reims.Client, name string, cur *reims.VMDetail, if cur.NetworkMode == "bridge" && a.npcapPluginEnabled() { tokens, argsErr := reims.GuestToolsNetworkUnixArgs(cur.Directory, cfg.ManagementOutSock, cfg.ManagementInSock) if argsErr != nil { - a.emitLog(name, networkmsg.Localize(argsErr, a.locale()).Error()) + a.emitVMLog(name, networkmsg.Localize(argsErr, a.locale()).Error()) return } merged = strings.TrimSpace(merged + " " + strings.Join(tokens, " ")) @@ -427,7 +427,7 @@ func (a *App) syncGuestTools(c *reims.Client, name string, cur *reims.VMDetail, if attached { imgPath := a.guestToolsImagePath(name) if err := guesttools.BuildToolsDiskImage(imgPath, cfg); err != nil { - a.emitLog(name, "Warning: could not refresh REIMSTOOLS disk: "+err.Error()) + a.emitVMLog(name, "Warning: could not refresh REIMSTOOLS disk: "+err.Error()) return } merged = reims.MergeGuestToolsArgs(merged, imgPath) diff --git a/internal/app/macos_settings.go b/internal/app/macos_settings.go index 4ae82c0..13dcab4 100644 --- a/internal/app/macos_settings.go +++ b/internal/app/macos_settings.go @@ -482,7 +482,7 @@ func (a *App) applyVMNetwork(parent context.Context, name, mode, uplink string) a.emitStateChanged() settings, err := a.GetVMNetworkSettings(name) if err != nil { - a.emitLog(name, networkmsg.Text(a.locale(), "log.refresh_failed")) + a.emitVMLog(name, networkmsg.Text(a.locale(), "log.refresh_failed")) return VMNetworkSettings{Mode: mode, UplinkGUID: selected.GUID, UplinkName: selected.Name, Ready: true}, nil } return settings, nil @@ -706,7 +706,7 @@ func (a *App) registerExistingPacketBridges(ctx context.Context) { err = a.preparePacketNetwork(ctx, c, d, record, true) } if err != nil { - a.emitLog(vm.Name, networkmsg.Text(a.locale(), "log.packet_restore_failed")+" "+networkmsg.Localize(err, a.locale()).Error()) + a.emitVMLog(vm.Name, networkmsg.Text(a.locale(), "log.packet_restore_failed")+" "+networkmsg.Localize(err, a.locale()).Error()) } } } @@ -807,7 +807,7 @@ func (a *App) switchPacketUplink(ctx context.Context, c networkControlClient, d } return err } - a.emitLog(d.Name, networkmsg.Text(a.locale(), "log.uplink_switched")) + a.emitVMLog(d.Name, networkmsg.Text(a.locale(), "log.uplink_switched")) return nil } @@ -903,6 +903,6 @@ func (a *App) applyPacketNetwork(ctx context.Context, c networkControlClient, d srv.StopManagementNetwork(d.Name) } } - a.emitLog(d.Name, networkmsg.Text(a.locale(), "log.mode_applied", "mode", networkmsg.Text(a.locale(), "mode."+strings.ToLower(mode)))) + a.emitVMLog(d.Name, networkmsg.Text(a.locale(), "log.mode_applied", "mode", networkmsg.Text(a.locale(), "mode."+strings.ToLower(mode)))) return nil } diff --git a/internal/app/plugins_flow.go b/internal/app/plugins_flow.go index 137a3dc..351ec11 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -903,7 +903,7 @@ func (a *App) CreateVMWithDriver(req driver.CreateRequest) error { if issues := drv.ValidateCreate(ctx, req); len(issues) > 0 { return errors.New(issues[0].Message) } - w := vmstart.LineWriter(func(line string) { a.emitLog(req.Name, line) }) + w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(req.DriverID, req.Name, line) }) if err := drv.Create(ctx, req, w, w); err != nil { return err } diff --git a/internal/app/suspend_flow.go b/internal/app/suspend_flow.go index 86375e0..2c5535b 100644 --- a/internal/app/suspend_flow.go +++ b/internal/app/suspend_flow.go @@ -157,14 +157,14 @@ func (a *App) registerResumeGuestTools(vm driver.VMInfo, epoch uint64, unicodeIn } cfg, configured, err := guesttools.ReadVMConfigStrict(vm.Directory) if err != nil { - a.emitLog(ref.Name, "Warning: could not load Guest Tools config: "+err.Error()) + a.emitVMLog(ref.Name, "Warning: could not load Guest Tools config: "+err.Error()) return nil, nil, 0 } if !configured { return nil, nil, 0 } if err := requireGuestToolsVM(vm.Directory); err != nil { - a.emitLog(ref.Name, "Warning: could not register Guest Tools config: "+err.Error()) + a.emitVMLog(ref.Name, "Warning: could not register Guest Tools config: "+err.Error()) return nil, nil, 0 } srv, port, err := a.ensureGuestToolsBridge() @@ -182,12 +182,12 @@ func (a *App) registerResumeGuestTools(vm driver.VMInfo, epoch uint64, unicodeIn if cfg.Port != port || (windowBridge && (oldName != cfg.VMName || oldDir != cfg.SharedDir)) { cfg.Port = port if err := guesttools.SaveVMConfig(vm.Directory, cfg); err != nil { - a.emitLog(ref.Name, "Warning: could not save Guest Tools config: "+err.Error()) + a.emitVMLog(ref.Name, "Warning: could not save Guest Tools config: "+err.Error()) return nil, nil, 0 } } if err := a.registerGuestToolsConfig(srv, vm.Directory, cfg); err != nil { - a.emitLog(ref.Name, "Warning: could not register Guest Tools config: "+err.Error()) + a.emitVMLog(ref.Name, "Warning: could not register Guest Tools config: "+err.Error()) return nil, nil, 0 } diff --git a/internal/app/tasks.go b/internal/app/tasks.go index 895cb4b..57aa758 100644 --- a/internal/app/tasks.go +++ b/internal/app/tasks.go @@ -390,7 +390,13 @@ func (a *App) ctlTaskWriter(kind, vm string, cancel context.CancelFunc) (id stri id = tasks.start(kind, vm, vm, cancel) lastStep := "" lastLogAt := time.Now() - trim := func(s string) string { return strings.TrimPrefix(s, vm+": ") } + // vm is a VM name or a VM key. + name := vmNameFromKey(vm) + source := vm + if name == vm { + source = vmKey(vm) + } + trim := func(s string) string { return strings.TrimPrefix(s, name+": ") } w = vmstart.LineWriter(func(line string) { u, ok := host.ParseCtlLine(line) if !ok { @@ -401,19 +407,19 @@ func (a *App) ctlTaskWriter(kind, vm string, cancel context.CancelFunc) (id stri if u.Step != lastStep { lastStep = u.Step lastLogAt = time.Now() - a.emitLog(vm, u.Step) + a.emitLog(source, u.Step) } else if time.Since(lastLogAt) >= 30*time.Second { lastLogAt = time.Now() if u.Total > 0 { - a.emitLog(vm, fmt.Sprintf("%s: %.0f%% (%.1f / %.1f MB)", u.Step, u.Percent, float64(u.Done)/1e6, float64(u.Total)/1e6)) + a.emitLog(source, fmt.Sprintf("%s: %.0f%% (%.1f / %.1f MB)", u.Step, u.Percent, float64(u.Done)/1e6, float64(u.Total)/1e6)) } else if u.Done > 0 { - a.emitLog(vm, fmt.Sprintf("%s: %.1f MB", u.Step, float64(u.Done)/1e6)) + a.emitLog(source, fmt.Sprintf("%s: %.1f MB", u.Step, float64(u.Done)/1e6)) } } tasks.update(id, u) return } - a.emitLog(vm, line) + a.emitLog(source, line) step := trim(u.Message) lastStep = step lastLogAt = time.Now() diff --git a/internal/app/vm_close_windows.go b/internal/app/vm_close_windows.go index 5f184f5..a20facd 100644 --- a/internal/app/vm_close_windows.go +++ b/internal/app/vm_close_windows.go @@ -25,7 +25,7 @@ func (a *App) confirmVMWindowClose(name string) { owner = host.ProcessDisplayWindow(uint32(pid)) } if owner == 0 { - a.emitLog(name, "Could not locate the VM display window for close confirmation") + a.emitVMLog(name, "Could not locate the VM display window for close confirmation") return } a.mu.Lock() diff --git a/internal/app/vm_poll.go b/internal/app/vm_poll.go index fc5667c..82d4286 100644 --- a/internal/app/vm_poll.go +++ b/internal/app/vm_poll.go @@ -300,11 +300,7 @@ func (p *vmPoller) pinStarted(vms []driver.VMListItem, loc i18n.Locale, autoPin details[vmKeyForDriver(vm.DriverID, vm.Name)] = det ref := driver.NewVMRef(vm.DriverID, vm.Name) if line, _ := p.a.applyVMAffinity(loc, p.host, ref, vmDir, autoPin, pid, det.CPUs, false); line != "" { - if ref.DriverID == driver.BuiltinReimsMacOSDriverID { - p.a.emitLog(vm.Name, line) - } else { - p.a.emitVMLogForDriver(vm.DriverID, vm.Name, line) - } + p.a.emitVMLogForDriver(vm.DriverID, vm.Name, line) } } return details diff --git a/internal/app/window_launch.go b/internal/app/window_launch.go index 1c8a3d0..51360d5 100644 --- a/internal/app/window_launch.go +++ b/internal/app/window_launch.go @@ -57,9 +57,9 @@ func (a *App) handleWindowArgs(w cli.WindowArgs, secondLaunch bool) { } result := a.startResultPath(w.StartResult) if w.StartResult != "" && result == "" { - a.emitVMLog(name, "Ignored a start result path outside the Reims-Go temp folder: "+w.StartResult) + a.emitVMLogForDriver(w.StartDriver, name, "Ignored a start result path outside the Reims-Go temp folder: "+w.StartResult) } - a.emitVMLog(name, "Start requested from the command line") + a.emitVMLogForDriver(w.StartDriver, name, "Start requested from the command line") go func() { key := vmKeyForDriver(w.StartDriver, name) capture := a.captureLogs(key) @@ -77,7 +77,7 @@ func (a *App) handleWindowArgs(w cli.WindowArgs, secondLaunch bool) { } if result != "" { if werr := cli.WriteStartResult(result, err); werr != nil { - a.emitVMLog(name, "Could not report the start result to the command line: "+werr.Error()) + a.emitVMLogForDriver(w.StartDriver, name, "Could not report the start result to the command line: "+werr.Error()) } } }() From ab93899f45ef7ebcf5d4c358834d3cd04adb30d2 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: Thu, 3 Dec 2026 21:31:11 -0700 Subject: [PATCH 10/22] style: drop unused variables and parameters Co-Authored-By: Claude Opus 5.5 --- cmd/i18ngen/main.go | 7 ++--- internal/app/suspend_flow.go | 3 -- internal/console/manager.go | 18 ++++++------ internal/host/close_vm_windows.go | 41 ++++++++++++--------------- internal/macos/macosdriver/prepare.go | 4 +-- internal/packetbridge/frame.go | 2 +- internal/plugin/broker.go | 13 +++++---- internal/plugin/builtin/builtin.go | 4 +-- internal/plugin/hooks.go | 1 - internal/plugin/sidecar.go | 2 +- 10 files changed, 44 insertions(+), 51 deletions(-) diff --git a/cmd/i18ngen/main.go b/cmd/i18ngen/main.go index 94bb026..76c1c9f 100644 --- a/cmd/i18ngen/main.go +++ b/cmd/i18ngen/main.go @@ -24,10 +24,9 @@ import ( ) var ( - allDomains = []string{"core", "vm", "wizard", "settings", "plugins", "native", "macos-glossary"} - goDomains = []string{"native", "macos-glossary", "core"} - feEagerDomains = []string{"core", "vm"} - feLazyDomains = []string{"wizard", "settings", "plugins"} + allDomains = []string{"core", "vm", "wizard", "settings", "plugins", "native", "macos-glossary"} + goDomains = []string{"native", "macos-glossary", "core"} + feLazyDomains = []string{"wizard", "settings", "plugins"} ) type parsedEntry struct { diff --git a/internal/app/suspend_flow.go b/internal/app/suspend_flow.go index 2c5535b..cbf917d 100644 --- a/internal/app/suspend_flow.go +++ b/internal/app/suspend_flow.go @@ -283,6 +283,3 @@ func suspendProgressPercent(p driver.SuspendProgress) (int, bool) { } return pct, true } - -// Keep context import used cleanly for future cancellation hooks. -var _ context.Context diff --git a/internal/console/manager.go b/internal/console/manager.go index e692929..a785801 100644 --- a/internal/console/manager.go +++ b/internal/console/manager.go @@ -303,7 +303,7 @@ func (m *Manager) withConnMode(ctx context.Context, vmDir string, cancelIO bool, return err } nested := m.hasLockScope(ctx, key) - _, release, err := m.acquire(ctx, vmDir) + release, err := m.acquire(ctx, vmDir) if err != nil { return err } @@ -347,7 +347,7 @@ func (m *Manager) withVM(ctx context.Context, vmDir string, operation func(conte if m.hasLockScope(ctx, key) { return operation(ctx) } - _, release, err := m.acquire(ctx, vmDir) + release, err := m.acquire(ctx, vmDir) if err != nil { return err } @@ -358,19 +358,19 @@ func (m *Manager) withVM(ctx context.Context, vmDir string, operation func(conte return operation(context.WithValue(ctx, lockScopeKey{}, scope)) } -func (m *Manager) acquire(ctx context.Context, vmDir string) (*vmLock, func(), error) { +func (m *Manager) acquire(ctx context.Context, vmDir string) (func(), error) { if m == nil { - return nil, nil, errors.New("console manager is unavailable") + return nil, errors.New("console manager is unavailable") } if ctx == nil { - return nil, nil, errors.New("console context is unavailable") + return nil, errors.New("console context is unavailable") } key, err := lockKey(vmDir) if err != nil { - return nil, nil, err + return nil, err } if m.hasLockScope(ctx, key) { - return &vmLock{}, func() {}, nil + return func() {}, nil } m.mu.Lock() @@ -388,7 +388,7 @@ func (m *Manager) acquire(ctx context.Context, vmDir string) (*vmLock, func(), e select { case lock.semaphore <- struct{}{}: var once sync.Once - return lock, func() { + return func() { once.Do(func() { <-lock.semaphore m.release(key, lock) @@ -396,7 +396,7 @@ func (m *Manager) acquire(ctx context.Context, vmDir string) (*vmLock, func(), e }, nil case <-ctx.Done(): m.release(key, lock) - return nil, nil, ctx.Err() + return nil, ctx.Err() } } diff --git a/internal/host/close_vm_windows.go b/internal/host/close_vm_windows.go index c181d99..1f24c5e 100644 --- a/internal/host/close_vm_windows.go +++ b/internal/host/close_vm_windows.go @@ -54,27 +54,25 @@ var ( vcDrawText = user32.NewProc("DrawTextW") vcFillRect = user32.NewProc("FillRect") vcGetWindowTextW = user32.NewProc("GetWindowTextW") - vcInvalidateRect = user32.NewProc("InvalidateRect") vcSetLayeredAttr = user32.NewProc("SetLayeredWindowAttributes") vcSetWindowRgn = user32.NewProc("SetWindowRgn") vcBeginPaint = user32.NewProc("BeginPaint") vcEndPaint = user32.NewProc("EndPaint") vcIsWindowEnabled = user32.NewProc("IsWindowEnabled") vcMoveWindow = user32.NewProc("MoveWindow") - vcGetParent = user32.NewProc("GetParent") - vcSelectObj = vcGDI.NewProc("SelectObject") - vcStockObj = vcGDI.NewProc("GetStockObject") - vcDeleteObj = vcGDI.NewProc("DeleteObject") - vcSetDCBrushColor = vcGDI.NewProc("SetDCBrushColor") - vcSetDCPenColor = vcGDI.NewProc("SetDCPenColor") - vcSetTextColor = vcGDI.NewProc("SetTextColor") - vcSetBkMode = vcGDI.NewProc("SetBkMode") - vcCreateFontW = vcGDI.NewProc("CreateFontIndirectW") - vcCreateRoundRect = vcGDI.NewProc("CreateRoundRectRgn") - vcRoundRect = vcGDI.NewProc("RoundRect") - vcDwmSetWindowAttr = vcDWM.NewProc("DwmSetWindowAttribute") - vcRtlMoveMemory = vcKernel.NewProc("RtlMoveMemory") + vcSelectObj = vcGDI.NewProc("SelectObject") + vcStockObj = vcGDI.NewProc("GetStockObject") + vcDeleteObj = vcGDI.NewProc("DeleteObject") + vcSetDCBrushColor = vcGDI.NewProc("SetDCBrushColor") + vcSetDCPenColor = vcGDI.NewProc("SetDCPenColor") + vcSetTextColor = vcGDI.NewProc("SetTextColor") + vcSetBkMode = vcGDI.NewProc("SetBkMode") + vcCreateFontW = vcGDI.NewProc("CreateFontIndirectW") + vcCreateRoundRect = vcGDI.NewProc("CreateRoundRectRgn") + vcRoundRect = vcGDI.NewProc("RoundRect") + vcDwmSetWindowAttr = vcDWM.NewProc("DwmSetWindowAttribute") + vcRtlMoveMemory = vcKernel.NewProc("RtlMoveMemory") ) type vcRect struct{ left, top, right, bottom int32 } @@ -116,11 +114,11 @@ type vcLogFont struct { } type vcPalette struct { - surface, border, divider uintptr - text, text2, textDisabled uintptr - accent, accentPress uintptr - btnFill, btnPress, btnBorder uintptr - dangerText uintptr + surface, border, divider uintptr + text, text2, textDisabled uintptr + accent, accentPress uintptr + btnFill, btnPress, btnBorder uintptr + dangerText uintptr } func vcRGB(r, g, b uint8) uintptr { @@ -327,7 +325,7 @@ func vcBuildDialogTemplate(title, body, left, right, cancel string, disableRight style := uint16(0x5000) // WS_CHILD | WS_VISIBLE var ctlStyle uint16 if class == clsButton { - style |= 1 // WS_TABSTOP + style |= 1 // WS_TABSTOP ctlStyle = 0x0b // BS_OWNERDRAW if disabled { style |= 0x0800 // WS_DISABLED @@ -599,6 +597,3 @@ func centerVMCloseDialog(hwnd, owner uintptr) { procSetWindowPos.Call(hwnd, 0, uintptr(x), uintptr(y), 0, 0, 0x0215) } } - -var _ = vcGetParent -var _ = vcInvalidateRect diff --git a/internal/macos/macosdriver/prepare.go b/internal/macos/macosdriver/prepare.go index 7320b86..b4da163 100644 --- a/internal/macos/macosdriver/prepare.go +++ b/internal/macos/macosdriver/prepare.go @@ -142,7 +142,7 @@ func (d *ReimsMacOSDriver) prepareStart(ctx context.Context, cfg config.Config, if err := d.prepareOfflineHelper(cfg, cur, &in); err != nil { return in, err } - if err := d.prepareRecoveryBoot(ctx, cfg, c, name, cur.Directory, log); err != nil { + if err := d.prepareRecoveryBoot(ctx, c, name, cur.Directory, log); err != nil { return in, err } if err := d.prepareGuestLang(ctx, cfg, active, cur.Directory); err != nil { @@ -178,7 +178,7 @@ func (d *ReimsMacOSDriver) prepareOfflineHelper(cfg config.Config, cur reims.VMD return nil } -func (d *ReimsMacOSDriver) prepareRecoveryBoot(ctx context.Context, cfg config.Config, c *reims.Client, name, vmDir string, log io.Writer) error { +func (d *ReimsMacOSDriver) prepareRecoveryBoot(ctx context.Context, c *reims.Client, name, vmDir string, log io.Writer) error { marker := startprep.ReadRecoveryMarker(vmDir) if marker != "want" && marker != "restore" { return nil diff --git a/internal/packetbridge/frame.go b/internal/packetbridge/frame.go index 56cc91e..377e913 100644 --- a/internal/packetbridge/frame.go +++ b/internal/packetbridge/frame.go @@ -153,7 +153,7 @@ func (t *translator) inbound(frame []byte) ([]byte, bool) { return append([]byte(nil), frame...), true } multicast := frame[0]&1 != 0 - deliver := multicast + var deliver bool var multicastMAC net.HardwareAddr switch binary.BigEndian.Uint16(frame[12:14]) { case 0x0806: diff --git a/internal/plugin/broker.go b/internal/plugin/broker.go index f5ee117..b5bc0fe 100644 --- a/internal/plugin/broker.go +++ b/internal/plugin/broker.go @@ -181,7 +181,7 @@ func (b *Broker) AuthorizeNetOrigin(pluginID, rawURL string) error { } for _, p := range info.Permissions { if netPermissionMatches(p.Name, u) { - if !b.allowRate(pluginID, 120) { + if !b.allowRate(pluginID) { b.Audit(pluginID, "RATE_LIMIT", "net:"+u.Host) return fmt.Errorf("plugin %q exceeded Host API rate limit", pluginID) } @@ -242,7 +242,7 @@ func (b *Broker) Authorize(pluginID, perm string) error { } } // Rate limit: max 120 Host API calls / second per plugin. - if !b.allowRate(pluginID, 120) { + if !b.allowRate(pluginID) { b.Audit(pluginID, "RATE_LIMIT", perm) return fmt.Errorf("plugin %q exceeded Host API rate limit", pluginID) } @@ -261,14 +261,17 @@ func (b *Broker) AllowRate(pluginID string) error { if st := b.reg.StateOf(pluginID); st != StateActive && st != StateDegraded { return fmt.Errorf("plugin %q is not active (state=%s)", pluginID, st) } - if !b.allowRate(pluginID, 120) { + if !b.allowRate(pluginID) { b.Audit(pluginID, "RATE_LIMIT", "i18n.getBundle") return fmt.Errorf("plugin %q exceeded Host API rate limit", pluginID) } return nil } -func (b *Broker) allowRate(pluginID string, limitPerSec int) bool { +// hostCallsPerSecond is how many Host API calls one plugin may make per second. +const hostCallsPerSecond = 120 + +func (b *Broker) allowRate(pluginID string) bool { b.mu.Lock() defer b.mu.Unlock() now := time.Now() @@ -277,7 +280,7 @@ func (b *Broker) allowRate(pluginID string, limitPerSec int) bool { b.rates[pluginID] = &rateWindow{windowStart: now, count: 1} return true } - if rw.count >= limitPerSec { + if rw.count >= hostCallsPerSecond { return false } rw.count++ diff --git a/internal/plugin/builtin/builtin.go b/internal/plugin/builtin/builtin.go index 0bfc7a5..069c510 100644 --- a/internal/plugin/builtin/builtin.go +++ b/internal/plugin/builtin/builtin.go @@ -88,7 +88,7 @@ func RegisterAll(reg *plugin.Registry, cb HostCallbacks, desiredFn func(id strin defs := []plugin.PluginDef{ defCore(ver), defGuestTools(ver, cb, desiredFn), - defClipboard(ver, cb, desiredFn), + defClipboard(ver, desiredFn), defInput(ver, cb, desiredFn), defNpcapBridge(ver, cb, desiredFn), defComputerUse(ver, desiredFn), @@ -219,7 +219,7 @@ func defGuestTools(ver string, cb HostCallbacks, desiredFn func(string, bool) bo } } -func defClipboard(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef { +func defClipboard(ver string, desiredFn func(string, bool) bool) plugin.PluginDef { minMB := 1.0 maxMB := 16.0 minFileMB := float64(guesttools.MinClipboardMaxFileMB) diff --git a/internal/plugin/hooks.go b/internal/plugin/hooks.go index 5e24753..8c1d01f 100644 --- a/internal/plugin/hooks.go +++ b/internal/plugin/hooks.go @@ -108,7 +108,6 @@ type HookBus struct { mu sync.RWMutex handlers map[string][]*HookRegistration - seq uint64 // Zero-overhead counter for log.onLine (§8.1): checked with atomic load // before constructing LogLineEvent objects. diff --git a/internal/plugin/sidecar.go b/internal/plugin/sidecar.go index 0060111..f9e1ff2 100644 --- a/internal/plugin/sidecar.go +++ b/internal/plugin/sidecar.go @@ -314,7 +314,7 @@ func (s *SidecarSupervisor) registerReverseHostAPI(conn *RPCConn) { conn.Handle("host/audit", func(_ context.Context, raw json.RawMessage) (any, error) { if broker != nil { - if !broker.allowRate(pid, 120) { + if !broker.allowRate(pid) { return nil, fmt.Errorf("plugin %q exceeded audit rate limit", pid) } var req struct { From 848089c2b2f1cae123ff59da97eff224e86e1f83 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: Thu, 3 Dec 2026 21:34:47 -0700 Subject: [PATCH 11/22] refactor(plugin): share language pack merging and split the package scan The app and the command line each had their own copy of the language pack merge order. The locale code now has its own file. The package scan is split by what it checks, and a new test limits how long one function may get. Co-Authored-By: Claude Opus 5.5 --- internal/archtest/function_length_test.go | 33 + internal/plugin/manager.go | 896 ---------------------- internal/plugin/manager_locale.go | 844 ++++++++++++++++++++ internal/plugin/scanner.go | 486 ++++++------ 4 files changed, 1133 insertions(+), 1126 deletions(-) create mode 100644 internal/archtest/function_length_test.go create mode 100644 internal/plugin/manager_locale.go diff --git a/internal/archtest/function_length_test.go b/internal/archtest/function_length_test.go new file mode 100644 index 0000000..3ccd228 --- /dev/null +++ b/internal/archtest/function_length_test.go @@ -0,0 +1,33 @@ +package archtest + +import ( + "go/ast" + "testing" +) + +// maxFunctionLines keeps one function from collecting every step of a feature, +// where two changes to unrelated steps collide. Split it into named steps. +const maxFunctionLines = 300 + +func TestFunctionLength(t *testing.T) { + for _, src := range sources(t) { + for _, decl := range src.file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok { + continue + } + start, end := fileSet.Position(fn.Pos()).Line, fileSet.Position(fn.End()).Line + lines := end - start + 1 + // Embedded scripts and templates are text, not steps. + ast.Inspect(fn, func(n ast.Node) bool { + if lit, ok := n.(*ast.BasicLit); ok { + lines -= fileSet.Position(lit.End()).Line - fileSet.Position(lit.Pos()).Line + } + return true + }) + if lines > maxFunctionLines { + t.Errorf("%s:%d: %s has %d lines, the limit is %d", src.rel, start, fn.Name.Name, lines, maxFunctionLines) + } + } + } +} diff --git a/internal/plugin/manager.go b/internal/plugin/manager.go index 82b6433..a4d2a01 100644 --- a/internal/plugin/manager.go +++ b/internal/plugin/manager.go @@ -8,7 +8,6 @@ import ( "net/url" "os" "path/filepath" - "slices" "sort" "strings" "sync" @@ -1377,901 +1376,6 @@ func (m *Manager) ActiveThemePayload() ActiveThemePayload { return payload } -// ResolvedLocalePacks loads and merges all active plugin locale contributions -// and per-plugin l10n bundles into frontend UI packs and backend/CLI catalogs. -// Returns nil in safe mode. -func (m *Manager) ResolvedLocalePacks() ([]ResolvedLocalePack, map[i18n.Locale]i18n.PluginCatalog) { - if m.safeMode { - return nil, nil - } - contribs := m.registry.Locales() - - m.mu.RLock() - dirs := make(map[string]string, len(m.installDirs)) - for k, v := range m.installDirs { - dirs[k] = v - } - m.mu.RUnlock() - - type mergedPack struct { - pack ResolvedLocalePack - seenPID map[string]bool - backend map[string]string - } - byLocale := make(map[string]*mergedPack) - - ensurePack := func(canon i18n.Locale) *mergedPack { - key := string(canon) - mp := byLocale[key] - if mp == nil { - mp = &mergedPack{ - pack: ResolvedLocalePack{ - Locale: key, - Fallback: string(i18n.DefaultFallback(canon)), - Messages: make(map[string]string), - }, - seenPID: make(map[string]bool), - backend: make(map[string]string), - } - byLocale[key] = mp - } - return mp - } - - setPluginMsg := func(mp *mergedPack, targetPID, k, v string, overwrite bool) { - if targetPID == "" || k == "" || v == "" { - return - } - if mp.pack.PluginMessages == nil { - mp.pack.PluginMessages = make(map[string]map[string]string) - } - pm := mp.pack.PluginMessages[targetPID] - if pm == nil { - pm = make(map[string]string) - mp.pack.PluginMessages[targetPID] = pm - } - if !overwrite { - if _, exists := pm[k]; exists { - return - } - } - pm[k] = v - } - - // 1. Collect private `/.json` bundles from active/degraded functional plugins (underlay). - // Use ActivePluginIDs() rather than List() so we never trigger inUseChecker / Sidecar wake-ups - // while Registry.Reconcile holds reconcileMu. - activeIDs := m.registry.ActivePluginIDs() - sortedActiveIDs := make([]string, 0, len(activeIDs)) - for pid := range activeIDs { - sortedActiveIDs = append(sortedActiveIDs, pid) - } - sort.Strings(sortedActiveIDs) - for _, pid := range sortedActiveIDs { - man, ok := m.registry.ManifestOf(pid) - if !ok || strings.TrimSpace(man.L10n) == "" { - continue - } - selfDir := dirs[pid] - if selfDir == "" { - continue - } - l10nClean := strings.Trim(strings.TrimSpace(man.L10n), "/") - fullL10n, err := safeJoin(selfDir, l10nClean) - if err != nil { - continue - } - entries, err := os.ReadDir(fullL10n) - if err != nil { - continue - } - for _, ent := range entries { - if ent.IsDir() || !strings.HasSuffix(strings.ToLower(ent.Name()), ".json") { - continue - } - tagRaw := strings.TrimSuffix(ent.Name(), filepath.Ext(ent.Name())) - canon, ok := i18n.ParseLocale(tagRaw) - if !ok { - continue - } - loaded, err := loadLocaleJSONFile(selfDir, l10nClean+"/"+ent.Name()) - if err != nil || len(loaded) == 0 { - continue - } - mp := ensurePack(canon) - for k, v := range loaded { - setPluginMsg(mp, pid, k, v, true) - } - } - } - - // 2. Layer active Language Pack contributions (sorted deterministically by TrustRank -> Priority -> PluginID). - uiDomains := []string{"core", "vm", "wizard", "settings", "plugins", "macosGlossary", "macos-glossary"} - backendDomains := []string{"native", "macosGlossary", "macos-glossary", "core"} - - for _, lc := range contribs { - canon, ok := i18n.ParseLocale(lc.Locale) - if !ok { - continue - } - privileged := isPrivilegedLocaleTrustRank(lc.TrustRank) - if !privileged && (canon == i18n.ZhCN || canon == i18n.EnUS) { - // Community/unprivileged language packs may not hijack built-in host catalogs. - continue - } - mp := ensurePack(canon) - if lbl := strings.TrimSpace(lc.Label); lbl != "" { - mp.pack.Label = lbl - } - if fb := strings.TrimSpace(lc.Fallback); fb != "" { - if cfb, ok := i18n.ParseLocale(fb); ok { - mp.pack.Fallback = string(cfb) - } - } - installDir := dirs[lc.PluginID] - if installDir != "" && strings.TrimSpace(lc.File) != "" { - if loaded, err := loadLocaleJSONFile(installDir, lc.File); err == nil { - for k, v := range loaded { - if k != "" && v != "" { - mp.pack.Messages[k] = v - } - } - } - } - if installDir != "" && len(lc.Files) > 0 { - for _, dom := range uiDomains { - if rel := strings.TrimSpace(lc.Files[dom]); rel != "" { - if loaded, err := loadLocaleJSONFile(installDir, rel); err == nil { - for k, v := range loaded { - if k != "" && v != "" { - mp.pack.Messages[k] = v - } - } - } - } - } - for _, dom := range backendDomains { - if rel := strings.TrimSpace(lc.Files[dom]); rel != "" { - if loaded, err := loadLocaleJSONFile(installDir, rel); err == nil { - for k, v := range loaded { - if k != "" && v != "" { - mp.backend[k] = v - } - } - } - } - } - } - for k, v := range lc.Messages { - if k != "" && v != "" { - mp.pack.Messages[k] = v - } - } - if installDir != "" && strings.TrimSpace(lc.BackendFile) != "" { - if loaded, err := loadLocaleJSONFile(installDir, lc.BackendFile); err == nil { - for k, v := range loaded { - if k != "" && v != "" { - mp.backend[k] = v - } - } - } - } - for k, v := range lc.Backend { - if k != "" && v != "" { - mp.backend[k] = v - } - } - - // Resolve bundled WOFF2 WebFonts via AssetServer. - if installDir != "" && m.assets != nil && len(lc.Fonts) > 0 { - for _, f := range lc.Fonts { - if strings.TrimSpace(f.Family) == "" || !strings.EqualFold(filepath.Ext(strings.TrimSpace(f.File)), ".woff2") { - continue - } - if full, err := safeJoin(installDir, f.File); err == nil && verifyWOFF2Header(full) == nil { - mp.pack.Fonts = append(mp.pack.Fonts, ResolvedLocaleFont{ - Family: f.Family, - URL: m.assets.AssetURL(lc.PluginID, f.File), - Weight: f.Weight, - Style: f.Style, - UnicodeRange: f.UnicodeRange, - }) - } - } - } - - // Layer cross-plugin message overrides onto PluginMessages[targetID]. - // Unprivileged community packs may only fill in missing keys, never overwrite - // a target plugin's own messages. - for targetID, ov := range lc.PluginOverrides { - if installDir != "" && strings.TrimSpace(ov.MessagesFile) != "" { - if loaded, err := loadLocaleJSONFile(installDir, ov.MessagesFile); err == nil { - for k, v := range loaded { - setPluginMsg(mp, targetID, k, v, privileged) - } - } - } - for k, v := range ov.Messages { - setPluginMsg(mp, targetID, k, v, privileged) - } - } - - if lc.PluginID != "" && !mp.seenPID[lc.PluginID] { - mp.seenPID[lc.PluginID] = true - mp.pack.PluginIDs = append(mp.pack.PluginIDs, lc.PluginID) - } - } - - if len(byLocale) == 0 { - return nil, nil - } - - uiPacks := make([]ResolvedLocalePack, 0, len(byLocale)) - backendPacks := make(map[i18n.Locale]i18n.PluginCatalog, len(byLocale)) - for key, mp := range byLocale { - if mp.pack.Label == "" { - mp.pack.Label = defaultLocaleLabel(key) - } - sort.Strings(mp.pack.PluginIDs) - if len(mp.pack.Messages) > 0 { - mp.pack.HasUIMessages = true - } else { - mp.pack.Messages = nil - } - uiPacks = append(uiPacks, mp.pack) - if len(mp.backend) > 0 { - backendPacks[i18n.Locale(key)] = i18n.PluginCatalog{ - Fallback: i18n.Locale(mp.pack.Fallback), - Messages: mp.backend, - } - } - } - sort.Slice(uiPacks, func(i, j int) bool { - return uiPacks[i].Locale < uiPacks[j].Locale - }) - if len(backendPacks) == 0 { - backendPacks = nil - } - return uiPacks, backendPacks -} - -type resolvedManifestOverride struct { - locale string - privileged bool - ov PluginManifestOverride -} - -func applyLocalizedOverride(lt *LocalizedText, locale, val string, privileged bool) { - if privileged { - lt.Set(locale, val) - } else { - lt.SetIfEmpty(locale, val) - } -} - -func (m *Manager) activeManifestOverrides() map[string][]resolvedManifestOverride { - if m == nil || m.safeMode { - return nil - } - contribs := m.registry.Locales() - if len(contribs) == 0 { - return nil - } - m.mu.RLock() - dirs := make(map[string]string, len(m.installDirs)) - for k, v := range m.installDirs { - dirs[k] = v - } - m.mu.RUnlock() - - var out map[string][]resolvedManifestOverride - for _, lc := range contribs { - if len(lc.PluginOverrides) == 0 { - continue - } - canon, ok := i18n.ParseLocale(lc.Locale) - if !ok { - continue - } - privileged := isPrivilegedLocaleTrustRank(lc.TrustRank) - if !privileged && (canon == i18n.ZhCN || canon == i18n.EnUS) { - continue - } - packDir := dirs[lc.PluginID] - for targetID, po := range lc.PluginOverrides { - var merged PluginManifestOverride - hasAny := false - if packDir != "" && strings.TrimSpace(po.ManifestFile) != "" { - if loaded, err := loadPluginManifestOverrideFile(packDir, po.ManifestFile); err == nil && loaded != nil { - merged = *loaded - hasAny = true - } - } - if po.Manifest != nil { - if po.Manifest.Name != "" { - merged.Name = po.Manifest.Name - } - if po.Manifest.Description != "" { - merged.Description = po.Manifest.Description - } - if len(po.Manifest.Fields) > 0 { - if merged.Fields == nil { - merged.Fields = make(map[string]string, len(po.Manifest.Fields)) - } - for fk, fv := range po.Manifest.Fields { - merged.Fields[fk] = fv - } - } - hasAny = true - } - if !hasAny { - continue - } - if out == nil { - out = make(map[string][]resolvedManifestOverride) - } - out[targetID] = append(out[targetID], resolvedManifestOverride{ - locale: string(canon), - privileged: privileged, - ov: merged, - }) - } - } - return out -} - -func cloneLocalizedText(lt LocalizedText) LocalizedText { - out := LocalizedText{ZhCN: lt.ZhCN, EnUS: lt.EnUS} - if len(lt.Extra) > 0 { - out.Extra = make(map[string]string, len(lt.Extra)) - for k, v := range lt.Extra { - out.Extra[k] = v - } - } - return out -} - -func cloneSettingsSchemaWithOverrides(sc *SettingsSchema, list []resolvedManifestOverride) *SettingsSchema { - if sc == nil { - return nil - } - cp := *sc - cp.Title = cloneLocalizedText(sc.Title) - if len(sc.Properties) > 0 { - cp.Properties = make(map[string]SettingProperty, len(sc.Properties)) - for pk, prop := range sc.Properties { - pcp := prop - pcp.Title = cloneLocalizedText(prop.Title) - pcp.Description = cloneLocalizedText(prop.Description) - cp.Properties[pk] = pcp - } - } - for _, r := range list { - if v := r.ov.Fields["settings.title"]; v != "" { - applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged) - } - for pk, prop := range cp.Properties { - changed := false - if v := firstNonEmptyField(r.ov.Fields, "setting."+pk+".title", pk+".title"); v != "" { - applyLocalizedOverride(&prop.Title, r.locale, v, r.privileged) - changed = true - } - if v := firstNonEmptyField(r.ov.Fields, "setting."+pk+".description", pk+".description"); v != "" { - applyLocalizedOverride(&prop.Description, r.locale, v, r.privileged) - changed = true - } - if changed { - cp.Properties[pk] = prop - } - } - } - return &cp -} - -func firstNonEmptyField(fields map[string]string, keys ...string) string { - if len(fields) == 0 { - return "" - } - for _, k := range keys { - if v := strings.TrimSpace(fields[k]); v != "" { - return v - } - } - return "" -} - -// LocalizePluginInfos returns a copy of infos enriched with any active Language Pack -// `pluginOverrides` translations for plugin Name, Description, and SettingsSchema. -func (m *Manager) LocalizePluginInfos(infos []PluginInfo) []PluginInfo { - ovs := m.activeManifestOverrides() - if len(ovs) == 0 || len(infos) == 0 { - return infos - } - out := make([]PluginInfo, len(infos)) - for i, info := range infos { - cp := info - if list := ovs[info.ID]; len(list) > 0 { - cp.Name = cloneLocalizedText(info.Name) - cp.Description = cloneLocalizedText(info.Description) - for _, r := range list { - if r.ov.Name != "" { - applyLocalizedOverride(&cp.Name, r.locale, r.ov.Name, r.privileged) - } - if r.ov.Description != "" { - applyLocalizedOverride(&cp.Description, r.locale, r.ov.Description, r.privileged) - } - } - cp.Settings = cloneSettingsSchemaWithOverrides(info.Settings, list) - } - out[i] = cp - } - return out -} - -// overridableText is a contribution text that a Language Pack may replace, and -// the override fields that do so, in order of preference. -type overridableText struct { - text *LocalizedText - keys []string -} - -// localizeContributions returns a copy of items with the active Language Pack -// overrides applied to the texts that texts lists for each item. -func localizeContributions[T any](m *Manager, items []T, texts func(*T) (pluginID string, list []overridableText)) []T { - ovs := m.activeManifestOverrides() - if len(ovs) == 0 || len(items) == 0 { - return items - } - out := slices.Clone(items) - for i := range out { - pluginID, list := texts(&out[i]) - for _, t := range list { - if len(ovs[pluginID]) > 0 { - *t.text = cloneLocalizedText(*t.text) - } - for _, r := range ovs[pluginID] { - if v := firstNonEmptyField(r.ov.Fields, t.keys...); v != "" { - applyLocalizedOverride(t.text, r.locale, v, r.privileged) - } - } - } - } - return out -} - -// LocalizeMenus applies Language Pack overrides to menu titles. -func (m *Manager) LocalizeMenus(items []MenuContribution) []MenuContribution { - return localizeContributions(m, items, func(c *MenuContribution) (string, []overridableText) { - return c.PluginID, []overridableText{{&c.Title, []string{"menu." + c.ID + ".title", "command." + c.Command + ".title"}}} - }) -} - -// LocalizePanels applies Language Pack overrides to panel titles. -func (m *Manager) LocalizePanels(items []PanelContribution) []PanelContribution { - return localizeContributions(m, items, func(c *PanelContribution) (string, []overridableText) { - return c.PluginID, []overridableText{{&c.Title, []string{"panel." + c.ID + ".title"}}} - }) -} - -// LocalizeViews applies Language Pack overrides to view titles. -func (m *Manager) LocalizeViews(items []ViewContribution) []ViewContribution { - return localizeContributions(m, items, func(c *ViewContribution) (string, []overridableText) { - return c.PluginID, []overridableText{{&c.Title, []string{"view." + c.ID + ".title"}}} - }) -} - -// LocalizeImageSources applies Language Pack overrides to image source titles and descriptions. -func (m *Manager) LocalizeImageSources(items []ImageSourceContribution) []ImageSourceContribution { - return localizeContributions(m, items, func(c *ImageSourceContribution) (string, []overridableText) { - return c.PluginID, []overridableText{ - {&c.Title, []string{"imageSource." + c.ID + ".title"}}, - {&c.Description, []string{"imageSource." + c.ID + ".description"}}, - } - }) -} - -// LocalizeVMCards applies Language Pack overrides to VM card titles and values. -func (m *Manager) LocalizeVMCards(items []VMCardContribution) []VMCardContribution { - return localizeContributions(m, items, func(c *VMCardContribution) (string, []overridableText) { - return c.PluginID, []overridableText{ - {&c.Title, []string{"vmCard." + c.ID + ".title"}}, - {&c.Value, []string{"vmCard." + c.ID + ".value"}}, - } - }) -} - -// LocalizeSettingsPages applies Language Pack overrides to settings page titles. -func (m *Manager) LocalizeSettingsPages(items []SettingsPageContribution) []SettingsPageContribution { - return localizeContributions(m, items, func(c *SettingsPageContribution) (string, []overridableText) { - return c.PluginID, []overridableText{{&c.Title, []string{"settingsPage." + c.ID + ".title"}}} - }) -} - -// LocalizeStatusItems applies Language Pack overrides to status item texts and tooltips. -func (m *Manager) LocalizeStatusItems(items []StatusItemContribution) []StatusItemContribution { - return localizeContributions(m, items, func(c *StatusItemContribution) (string, []overridableText) { - return c.PluginID, []overridableText{ - {&c.Text, []string{"statusItem." + c.ID + ".text"}}, - {&c.Tooltip, []string{"statusItem." + c.ID + ".tooltip"}}, - } - }) -} - -// CurrentLocale returns the active effective host locale for plugin operations. -func (m *Manager) CurrentLocale() i18n.Locale { - if m != nil && m.opts.LocaleFn != nil { - return i18n.EffectiveLocale(m.opts.LocaleFn()) - } - return i18n.Detect() -} - -// PluginL10nBundle builds the merged private localization dictionary for pluginID -// in loc, layering the plugin's own `/.json` files underneath any -// active Language Pack `pluginOverrides[pluginID]` entries along FallbackChain(loc). -func (m *Manager) PluginL10nBundle(pluginID string, loc i18n.Locale) map[string]string { - if m == nil || pluginID == "" || m.safeMode { - return nil - } - cacheKey := pluginID + "\x00" + string(loc) - m.mu.RLock() - gen := m.l10nGen - if cached, ok := m.l10nCache[cacheKey]; ok { - m.mu.RUnlock() - if len(cached) == 0 { - return nil - } - cp := make(map[string]string, len(cached)) - for k, v := range cached { - cp[k] = v - } - return cp - } - selfDir := m.installDirs[pluginID] - dirs := make(map[string]string, len(m.installDirs)) - for k, v := range m.installDirs { - dirs[k] = v - } - m.mu.RUnlock() - - chain := i18n.FallbackChain(loc) - out := make(map[string]string) - - var l10nRel string - selfLocaleFiles := make(map[string]string) - if man, ok := m.registry.ManifestOf(pluginID); ok && strings.TrimSpace(man.L10n) != "" { - l10nRel = strings.Trim(strings.TrimSpace(man.L10n), "/") - if selfDir != "" && l10nRel != "" { - if fullL10n, err := safeJoin(selfDir, l10nRel); err == nil { - if entries, err := os.ReadDir(fullL10n); err == nil { - for _, ent := range entries { - if ent.IsDir() || !strings.HasSuffix(strings.ToLower(ent.Name()), ".json") { - continue - } - tagRaw := strings.TrimSuffix(ent.Name(), filepath.Ext(ent.Name())) - if canon, ok := i18n.ParseLocale(tagRaw); ok { - if _, exists := selfLocaleFiles[string(canon)]; !exists { - selfLocaleFiles[string(canon)] = l10nRel + "/" + ent.Name() - } - } - } - } - } - } - } - - contribs := m.registry.Locales() - // Walk fallback chain from least specific to most specific so higher-priority hops win. - for idx := len(chain) - 1; idx >= 0; idx-- { - step := string(chain[idx]) - selfKeysThisStep := make(map[string]bool) - if rel, ok := selfLocaleFiles[step]; ok { - if loaded, err := loadLocaleJSONFile(selfDir, rel); err == nil { - for k, v := range loaded { - if k != "" && v != "" { - out[k] = v - selfKeysThisStep[k] = true - } - } - } - } - for _, lc := range contribs { - if lc.Locale != step { - continue - } - privileged := isPrivilegedLocaleTrustRank(lc.TrustRank) - if !privileged && (step == string(i18n.ZhCN) || step == string(i18n.EnUS)) { - continue - } - ov, ok := lc.PluginOverrides[pluginID] - if !ok { - continue - } - applyMsg := func(k, v string) { - if k == "" || v == "" { - return - } - if !privileged && selfKeysThisStep[k] { - return - } - out[k] = v - } - packDir := dirs[lc.PluginID] - if packDir != "" && strings.TrimSpace(ov.MessagesFile) != "" { - if loaded, err := loadLocaleJSONFile(packDir, ov.MessagesFile); err == nil { - for k, v := range loaded { - applyMsg(k, v) - } - } - } - for k, v := range ov.Messages { - applyMsg(k, v) - } - } - } - m.mu.Lock() - if m.l10nGen == gen { - if len(m.l10nCache) >= 512 { - clear(m.l10nCache) - } - if len(out) == 0 { - m.l10nCache[cacheKey] = nil - } else { - stored := make(map[string]string, len(out)) - for k, v := range out { - stored[k] = v - } - m.l10nCache[cacheKey] = stored - } - } - m.mu.Unlock() - if len(out) == 0 { - return nil - } - return out -} - -// NotifyLocaleChanged broadcasts `plugin/localeChanged` to all currently running -// L3 Sidecar processes without waking sleeping Sidecars. -func (m *Manager) NotifyLocaleChanged(eff i18n.Locale) { - if m == nil { - return - } - m.mu.RLock() - sups := make(map[string]*SidecarSupervisor, len(m.supervisors)) - for pid, s := range m.supervisors { - sups[pid] = s - } - m.mu.RUnlock() - if len(sups) == 0 { - return - } - chain := i18n.FallbackChain(eff) - strChain := make([]string, len(chain)) - for i, c := range chain { - strChain[i] = string(c) - } - for pid, sup := range sups { - if sup.PID() == 0 { - continue - } - sup.NotifyIfRunning("plugin/localeChanged", map[string]any{ - "locale": string(eff), - "fallbackChain": strChain, - "l10nBundle": m.PluginL10nBundle(pid, eff), - }) - } -} - -func defaultLocaleLabel(code string) string { - switch code { - case string(i18n.ZhCN): - return "简体中文" - case string(i18n.EnUS): - return "English" - default: - return code - } -} - -func isPrivilegedLocaleTrustRank(rank int) bool { - return rank == 10 || rank == 20 || rank >= 50 -} - -func localeTrustRank(source SourceKind, trust TrustLevel) int { - switch { - case source == SourceBuiltin: - return 10 - case source == SourceBundled: - return 20 - case trust == TrustCommunity: - return 30 - case trust == TrustVerified: - return 40 - case trust == TrustOfficial: - return 50 - case source == SourceDevLink || trust == TrustDev: - return 60 - default: - return 30 - } -} - -// LoadStaticLocalePacks performs an ultra-fast (< 2ms), side-effect-free scan of -// enabled plugins under dataRoot to populate backend/CLI language packs without -// starting any L3 Sidecars, AssetServer, or service dependency reconciliation. -func LoadStaticLocalePacks(dataRoot string) map[i18n.Locale]i18n.PluginCatalog { - if strings.TrimSpace(dataRoot) == "" { - i18n.SetPluginCatalogs(nil) - return nil - } - layout := NewPluginsLayout(dataRoot) - if DidLastStartupCrash(layout.Root) { - i18n.SetPluginCatalogs(nil) - return nil - } - st, err := NewStateStore(layout.Root).Load() - if err != nil || st == nil || len(st.Plugins) == 0 { - i18n.SetPluginCatalogs(nil) - return nil - } - - type staticCandidate struct { - id string - dir string - rec *PluginRecord - rank int - } - var candidates []staticCandidate - for id, rec := range st.Plugins { - if rec == nil || !rec.Enabled || rec.Source == SourceBuiltin || rec.Source == SourceBundled { - continue - } - var dir string - if rec.Source == SourceDevLink { - if !st.DeveloperMode || strings.TrimSpace(rec.DevPath) == "" { - continue - } - dir = rec.DevPath - } else { - if rec.Version == "" || !reReverseDomainID.MatchString(id) { - continue - } - if _, err := ParseSemVer(rec.Version); err != nil { - continue - } - safeDir, err := safeJoin(layout.PkgsDir(), id+"/"+rec.Version) - if err != nil { - continue - } - dir = safeDir - } - candidates = append(candidates, staticCandidate{ - id: id, - dir: dir, - rec: rec, - rank: localeTrustRank(rec.Source, rec.Trust), - }) - } - sort.Slice(candidates, func(i, j int) bool { - if candidates[i].rank != candidates[j].rank { - return candidates[i].rank < candidates[j].rank - } - return candidates[i].id < candidates[j].id - }) - - type staticLocaleItem struct { - canon i18n.Locale - rank int - id string - dir string - lc LocaleContribution - } - var items []staticLocaleItem - for _, c := range candidates { - raw, err := os.ReadFile(filepath.Join(c.dir, "plugin.json")) - if err != nil { - continue - } - var man Manifest - if json.Unmarshal(raw, &man) != nil || len(man.Contributes.Locales) == 0 { - continue - } - if c.id != "" && man.ID != c.id { - continue - } - trust := c.rec.Trust - if trust == "" { - trust = TrustCommunity - } - if c.rec.Source == SourceDevLink { - trust = TrustDev - } - _, _, entryHash, err := resolveManifestEntry(man, c.dir, false) - if err != nil { - continue - } - if computeNeedsApproval(man, trust, c.rec.ApprovedPermissions, c.rec.ApprovedEntryHash, entryHash) { - continue - } - for _, lc := range man.Contributes.Locales { - canon, ok := i18n.ParseLocale(lc.Locale) - if !ok { - continue - } - items = append(items, staticLocaleItem{ - canon: canon, - rank: c.rank, - id: c.id, - dir: c.dir, - lc: lc, - }) - } - } - - sort.Slice(items, func(i, j int) bool { - if items[i].canon != items[j].canon { - return items[i].canon < items[j].canon - } - if items[i].rank != items[j].rank { - return items[i].rank < items[j].rank - } - if items[i].lc.Priority != items[j].lc.Priority { - return items[i].lc.Priority < items[j].lc.Priority - } - return items[i].id < items[j].id - }) - - packs := make(map[i18n.Locale]i18n.PluginCatalog) - for _, it := range items { - canon := it.canon - if !isPrivilegedLocaleTrustRank(it.rank) && (canon == i18n.ZhCN || canon == i18n.EnUS) { - continue - } - lc := it.lc - cur, exists := packs[canon] - if !exists { - cur = i18n.PluginCatalog{ - Fallback: i18n.DefaultFallback(canon), - Messages: make(map[string]string), - } - } - if fb, ok := i18n.ParseLocale(lc.Fallback); ok { - cur.Fallback = fb - } - // Match ResolvedLocalePacks precedence: Files first, then BackendFile, then inline Backend. - for _, domKey := range []string{"native", "macosGlossary", "macos-glossary", "core"} { - if rel := strings.TrimSpace(lc.Files[domKey]); rel != "" { - if loaded, err := loadLocaleJSONFile(it.dir, rel); err == nil { - for k, v := range loaded { - if k != "" && v != "" { - cur.Messages[k] = v - } - } - } - } - } - if strings.TrimSpace(lc.BackendFile) != "" { - if loaded, err := loadLocaleJSONFile(it.dir, lc.BackendFile); err == nil { - for k, v := range loaded { - if k != "" && v != "" { - cur.Messages[k] = v - } - } - } - } - for k, v := range lc.Backend { - if k != "" && v != "" { - cur.Messages[k] = v - } - } - if len(cur.Messages) > 0 { - packs[canon] = cur - } - } - i18n.SetPluginCatalogs(packs) - return packs -} - // ActiveVMNamesWithSetting scans saved VM settings for pluginID where key==true. func (m *Manager) ActiveVMNamesWithSetting(pluginID, key string) []string { m.mu.RLock() diff --git a/internal/plugin/manager_locale.go b/internal/plugin/manager_locale.go new file mode 100644 index 0000000..eaee9df --- /dev/null +++ b/internal/plugin/manager_locale.go @@ -0,0 +1,844 @@ +package plugin + +import ( + "encoding/json" + "maps" + "os" + "path/filepath" + "slices" + "sort" + "strings" + + "github.com/Nwflower/reims-go/internal/i18n" +) + +// ResolvedLocalePacks loads and merges all active plugin locale contributions +// and per-plugin l10n bundles into frontend UI packs and backend/CLI catalogs. +// Returns nil in safe mode. +func (m *Manager) ResolvedLocalePacks() ([]ResolvedLocalePack, map[i18n.Locale]i18n.PluginCatalog) { + if m.safeMode { + return nil, nil + } + contribs := m.registry.Locales() + + m.mu.RLock() + dirs := maps.Clone(m.installDirs) + m.mu.RUnlock() + + type mergedPack struct { + pack ResolvedLocalePack + seenPID map[string]bool + backend map[string]string + } + byLocale := make(map[string]*mergedPack) + + ensurePack := func(canon i18n.Locale) *mergedPack { + key := string(canon) + mp := byLocale[key] + if mp == nil { + mp = &mergedPack{ + pack: ResolvedLocalePack{ + Locale: key, + Fallback: string(i18n.DefaultFallback(canon)), + Messages: make(map[string]string), + }, + seenPID: make(map[string]bool), + backend: make(map[string]string), + } + byLocale[key] = mp + } + return mp + } + + setPluginMsg := func(mp *mergedPack, targetPID, k, v string, overwrite bool) { + if targetPID == "" || k == "" || v == "" { + return + } + if mp.pack.PluginMessages == nil { + mp.pack.PluginMessages = make(map[string]map[string]string) + } + pm := mp.pack.PluginMessages[targetPID] + if pm == nil { + pm = make(map[string]string) + mp.pack.PluginMessages[targetPID] = pm + } + if !overwrite { + if _, exists := pm[k]; exists { + return + } + } + pm[k] = v + } + + // 1. Collect private `/.json` bundles from active/degraded functional plugins (underlay). + // Use ActivePluginIDs() rather than List() so we never trigger inUseChecker / Sidecar wake-ups + // while Registry.Reconcile holds reconcileMu. + activeIDs := m.registry.ActivePluginIDs() + sortedActiveIDs := make([]string, 0, len(activeIDs)) + for pid := range activeIDs { + sortedActiveIDs = append(sortedActiveIDs, pid) + } + sort.Strings(sortedActiveIDs) + for _, pid := range sortedActiveIDs { + man, ok := m.registry.ManifestOf(pid) + if !ok { + continue + } + for _, file := range l10nFiles(dirs[pid], man.L10n) { + loaded, err := loadLocaleJSONFile(dirs[pid], file.rel) + if err != nil || len(loaded) == 0 { + continue + } + mp := ensurePack(file.locale) + for k, v := range loaded { + setPluginMsg(mp, pid, k, v, true) + } + } + } + + // 2. Layer active Language Pack contributions (sorted deterministically by TrustRank -> Priority -> PluginID). + uiDomains := []string{"core", "vm", "wizard", "settings", "plugins", "macosGlossary", "macos-glossary"} + + for _, lc := range contribs { + canon, ok := i18n.ParseLocale(lc.Locale) + if !ok { + continue + } + privileged := isPrivilegedLocaleTrustRank(lc.TrustRank) + if !privileged && (canon == i18n.ZhCN || canon == i18n.EnUS) { + // Community/unprivileged language packs may not hijack built-in host catalogs. + continue + } + mp := ensurePack(canon) + if lbl := strings.TrimSpace(lc.Label); lbl != "" { + mp.pack.Label = lbl + } + if fb := strings.TrimSpace(lc.Fallback); fb != "" { + if cfb, ok := i18n.ParseLocale(fb); ok { + mp.pack.Fallback = string(cfb) + } + } + installDir := dirs[lc.PluginID] + mergeLocaleFile(mp.pack.Messages, installDir, lc.File) + for _, dom := range uiDomains { + mergeLocaleFile(mp.pack.Messages, installDir, lc.Files[dom]) + } + mergeMessages(mp.pack.Messages, lc.Messages) + mergeBackendMessages(mp.backend, installDir, lc) + + // Resolve bundled WOFF2 WebFonts via AssetServer. + if installDir != "" && m.assets != nil && len(lc.Fonts) > 0 { + for _, f := range lc.Fonts { + if strings.TrimSpace(f.Family) == "" || !strings.EqualFold(filepath.Ext(strings.TrimSpace(f.File)), ".woff2") { + continue + } + if full, err := safeJoin(installDir, f.File); err == nil && verifyWOFF2Header(full) == nil { + mp.pack.Fonts = append(mp.pack.Fonts, ResolvedLocaleFont{ + Family: f.Family, + URL: m.assets.AssetURL(lc.PluginID, f.File), + Weight: f.Weight, + Style: f.Style, + UnicodeRange: f.UnicodeRange, + }) + } + } + } + + // Layer cross-plugin message overrides onto PluginMessages[targetID]. + // Unprivileged community packs may only fill in missing keys, never overwrite + // a target plugin's own messages. + for targetID, ov := range lc.PluginOverrides { + if installDir != "" && strings.TrimSpace(ov.MessagesFile) != "" { + if loaded, err := loadLocaleJSONFile(installDir, ov.MessagesFile); err == nil { + for k, v := range loaded { + setPluginMsg(mp, targetID, k, v, privileged) + } + } + } + for k, v := range ov.Messages { + setPluginMsg(mp, targetID, k, v, privileged) + } + } + + if lc.PluginID != "" && !mp.seenPID[lc.PluginID] { + mp.seenPID[lc.PluginID] = true + mp.pack.PluginIDs = append(mp.pack.PluginIDs, lc.PluginID) + } + } + + if len(byLocale) == 0 { + return nil, nil + } + + uiPacks := make([]ResolvedLocalePack, 0, len(byLocale)) + backendPacks := make(map[i18n.Locale]i18n.PluginCatalog, len(byLocale)) + for key, mp := range byLocale { + if mp.pack.Label == "" { + mp.pack.Label = defaultLocaleLabel(key) + } + sort.Strings(mp.pack.PluginIDs) + if len(mp.pack.Messages) > 0 { + mp.pack.HasUIMessages = true + } else { + mp.pack.Messages = nil + } + uiPacks = append(uiPacks, mp.pack) + if len(mp.backend) > 0 { + backendPacks[i18n.Locale(key)] = i18n.PluginCatalog{ + Fallback: i18n.Locale(mp.pack.Fallback), + Messages: mp.backend, + } + } + } + sort.Slice(uiPacks, func(i, j int) bool { + return uiPacks[i].Locale < uiPacks[j].Locale + }) + if len(backendPacks) == 0 { + backendPacks = nil + } + return uiPacks, backendPacks +} + +type resolvedManifestOverride struct { + locale string + privileged bool + ov PluginManifestOverride +} + +func applyLocalizedOverride(lt *LocalizedText, locale, val string, privileged bool) { + if privileged { + lt.Set(locale, val) + } else { + lt.SetIfEmpty(locale, val) + } +} + +func (m *Manager) activeManifestOverrides() map[string][]resolvedManifestOverride { + if m == nil || m.safeMode { + return nil + } + contribs := m.registry.Locales() + if len(contribs) == 0 { + return nil + } + m.mu.RLock() + dirs := maps.Clone(m.installDirs) + m.mu.RUnlock() + + var out map[string][]resolvedManifestOverride + for _, lc := range contribs { + if len(lc.PluginOverrides) == 0 { + continue + } + canon, ok := i18n.ParseLocale(lc.Locale) + if !ok { + continue + } + privileged := isPrivilegedLocaleTrustRank(lc.TrustRank) + if !privileged && (canon == i18n.ZhCN || canon == i18n.EnUS) { + continue + } + packDir := dirs[lc.PluginID] + for targetID, po := range lc.PluginOverrides { + var merged PluginManifestOverride + hasAny := false + if packDir != "" && strings.TrimSpace(po.ManifestFile) != "" { + if loaded, err := loadPluginManifestOverrideFile(packDir, po.ManifestFile); err == nil && loaded != nil { + merged = *loaded + hasAny = true + } + } + if po.Manifest != nil { + if po.Manifest.Name != "" { + merged.Name = po.Manifest.Name + } + if po.Manifest.Description != "" { + merged.Description = po.Manifest.Description + } + if len(po.Manifest.Fields) > 0 { + if merged.Fields == nil { + merged.Fields = make(map[string]string, len(po.Manifest.Fields)) + } + for fk, fv := range po.Manifest.Fields { + merged.Fields[fk] = fv + } + } + hasAny = true + } + if !hasAny { + continue + } + if out == nil { + out = make(map[string][]resolvedManifestOverride) + } + out[targetID] = append(out[targetID], resolvedManifestOverride{ + locale: string(canon), + privileged: privileged, + ov: merged, + }) + } + } + return out +} + +func cloneLocalizedText(lt LocalizedText) LocalizedText { + out := LocalizedText{ZhCN: lt.ZhCN, EnUS: lt.EnUS} + if len(lt.Extra) > 0 { + out.Extra = make(map[string]string, len(lt.Extra)) + for k, v := range lt.Extra { + out.Extra[k] = v + } + } + return out +} + +func cloneSettingsSchemaWithOverrides(sc *SettingsSchema, list []resolvedManifestOverride) *SettingsSchema { + if sc == nil { + return nil + } + cp := *sc + cp.Title = cloneLocalizedText(sc.Title) + if len(sc.Properties) > 0 { + cp.Properties = make(map[string]SettingProperty, len(sc.Properties)) + for pk, prop := range sc.Properties { + pcp := prop + pcp.Title = cloneLocalizedText(prop.Title) + pcp.Description = cloneLocalizedText(prop.Description) + cp.Properties[pk] = pcp + } + } + for _, r := range list { + if v := r.ov.Fields["settings.title"]; v != "" { + applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged) + } + for pk, prop := range cp.Properties { + changed := false + if v := firstNonEmptyField(r.ov.Fields, "setting."+pk+".title", pk+".title"); v != "" { + applyLocalizedOverride(&prop.Title, r.locale, v, r.privileged) + changed = true + } + if v := firstNonEmptyField(r.ov.Fields, "setting."+pk+".description", pk+".description"); v != "" { + applyLocalizedOverride(&prop.Description, r.locale, v, r.privileged) + changed = true + } + if changed { + cp.Properties[pk] = prop + } + } + } + return &cp +} + +func firstNonEmptyField(fields map[string]string, keys ...string) string { + if len(fields) == 0 { + return "" + } + for _, k := range keys { + if v := strings.TrimSpace(fields[k]); v != "" { + return v + } + } + return "" +} + +// LocalizePluginInfos returns a copy of infos enriched with any active Language Pack +// `pluginOverrides` translations for plugin Name, Description, and SettingsSchema. +func (m *Manager) LocalizePluginInfos(infos []PluginInfo) []PluginInfo { + ovs := m.activeManifestOverrides() + if len(ovs) == 0 || len(infos) == 0 { + return infos + } + out := make([]PluginInfo, len(infos)) + for i, info := range infos { + cp := info + if list := ovs[info.ID]; len(list) > 0 { + cp.Name = cloneLocalizedText(info.Name) + cp.Description = cloneLocalizedText(info.Description) + for _, r := range list { + if r.ov.Name != "" { + applyLocalizedOverride(&cp.Name, r.locale, r.ov.Name, r.privileged) + } + if r.ov.Description != "" { + applyLocalizedOverride(&cp.Description, r.locale, r.ov.Description, r.privileged) + } + } + cp.Settings = cloneSettingsSchemaWithOverrides(info.Settings, list) + } + out[i] = cp + } + return out +} + +// overridableText is a contribution text that a Language Pack may replace, and +// the override fields that do so, in order of preference. +type overridableText struct { + text *LocalizedText + keys []string +} + +// localizeContributions returns a copy of items with the active Language Pack +// overrides applied to the texts that texts lists for each item. +func localizeContributions[T any](m *Manager, items []T, texts func(*T) (pluginID string, list []overridableText)) []T { + ovs := m.activeManifestOverrides() + if len(ovs) == 0 || len(items) == 0 { + return items + } + out := slices.Clone(items) + for i := range out { + pluginID, list := texts(&out[i]) + for _, t := range list { + if len(ovs[pluginID]) > 0 { + *t.text = cloneLocalizedText(*t.text) + } + for _, r := range ovs[pluginID] { + if v := firstNonEmptyField(r.ov.Fields, t.keys...); v != "" { + applyLocalizedOverride(t.text, r.locale, v, r.privileged) + } + } + } + } + return out +} + +// LocalizeMenus applies Language Pack overrides to menu titles. +func (m *Manager) LocalizeMenus(items []MenuContribution) []MenuContribution { + return localizeContributions(m, items, func(c *MenuContribution) (string, []overridableText) { + return c.PluginID, []overridableText{{&c.Title, []string{"menu." + c.ID + ".title", "command." + c.Command + ".title"}}} + }) +} + +// LocalizePanels applies Language Pack overrides to panel titles. +func (m *Manager) LocalizePanels(items []PanelContribution) []PanelContribution { + return localizeContributions(m, items, func(c *PanelContribution) (string, []overridableText) { + return c.PluginID, []overridableText{{&c.Title, []string{"panel." + c.ID + ".title"}}} + }) +} + +// LocalizeViews applies Language Pack overrides to view titles. +func (m *Manager) LocalizeViews(items []ViewContribution) []ViewContribution { + return localizeContributions(m, items, func(c *ViewContribution) (string, []overridableText) { + return c.PluginID, []overridableText{{&c.Title, []string{"view." + c.ID + ".title"}}} + }) +} + +// LocalizeImageSources applies Language Pack overrides to image source titles and descriptions. +func (m *Manager) LocalizeImageSources(items []ImageSourceContribution) []ImageSourceContribution { + return localizeContributions(m, items, func(c *ImageSourceContribution) (string, []overridableText) { + return c.PluginID, []overridableText{ + {&c.Title, []string{"imageSource." + c.ID + ".title"}}, + {&c.Description, []string{"imageSource." + c.ID + ".description"}}, + } + }) +} + +// LocalizeVMCards applies Language Pack overrides to VM card titles and values. +func (m *Manager) LocalizeVMCards(items []VMCardContribution) []VMCardContribution { + return localizeContributions(m, items, func(c *VMCardContribution) (string, []overridableText) { + return c.PluginID, []overridableText{ + {&c.Title, []string{"vmCard." + c.ID + ".title"}}, + {&c.Value, []string{"vmCard." + c.ID + ".value"}}, + } + }) +} + +// LocalizeSettingsPages applies Language Pack overrides to settings page titles. +func (m *Manager) LocalizeSettingsPages(items []SettingsPageContribution) []SettingsPageContribution { + return localizeContributions(m, items, func(c *SettingsPageContribution) (string, []overridableText) { + return c.PluginID, []overridableText{{&c.Title, []string{"settingsPage." + c.ID + ".title"}}} + }) +} + +// LocalizeStatusItems applies Language Pack overrides to status item texts and tooltips. +func (m *Manager) LocalizeStatusItems(items []StatusItemContribution) []StatusItemContribution { + return localizeContributions(m, items, func(c *StatusItemContribution) (string, []overridableText) { + return c.PluginID, []overridableText{ + {&c.Text, []string{"statusItem." + c.ID + ".text"}}, + {&c.Tooltip, []string{"statusItem." + c.ID + ".tooltip"}}, + } + }) +} + +// CurrentLocale returns the active effective host locale for plugin operations. +func (m *Manager) CurrentLocale() i18n.Locale { + if m != nil && m.opts.LocaleFn != nil { + return i18n.EffectiveLocale(m.opts.LocaleFn()) + } + return i18n.Detect() +} + +// PluginL10nBundle builds the merged private localization dictionary for pluginID +// in loc, layering the plugin's own `/.json` files underneath any +// active Language Pack `pluginOverrides[pluginID]` entries along FallbackChain(loc). +func (m *Manager) PluginL10nBundle(pluginID string, loc i18n.Locale) map[string]string { + if m == nil || pluginID == "" || m.safeMode { + return nil + } + cacheKey := pluginID + "\x00" + string(loc) + m.mu.RLock() + gen := m.l10nGen + if cached, ok := m.l10nCache[cacheKey]; ok { + m.mu.RUnlock() + if len(cached) == 0 { + return nil + } + return maps.Clone(cached) + } + selfDir := m.installDirs[pluginID] + dirs := maps.Clone(m.installDirs) + m.mu.RUnlock() + + chain := i18n.FallbackChain(loc) + out := make(map[string]string) + + selfLocaleFiles := make(map[string]string) + if man, ok := m.registry.ManifestOf(pluginID); ok { + for _, file := range l10nFiles(selfDir, man.L10n) { + if _, exists := selfLocaleFiles[string(file.locale)]; !exists { + selfLocaleFiles[string(file.locale)] = file.rel + } + } + } + + contribs := m.registry.Locales() + // Walk fallback chain from least specific to most specific so higher-priority hops win. + for idx := len(chain) - 1; idx >= 0; idx-- { + step := string(chain[idx]) + selfKeysThisStep := make(map[string]bool) + if rel, ok := selfLocaleFiles[step]; ok { + if loaded, err := loadLocaleJSONFile(selfDir, rel); err == nil { + for k, v := range loaded { + if k != "" && v != "" { + out[k] = v + selfKeysThisStep[k] = true + } + } + } + } + for _, lc := range contribs { + if lc.Locale != step { + continue + } + privileged := isPrivilegedLocaleTrustRank(lc.TrustRank) + if !privileged && (step == string(i18n.ZhCN) || step == string(i18n.EnUS)) { + continue + } + ov, ok := lc.PluginOverrides[pluginID] + if !ok { + continue + } + applyMsg := func(k, v string) { + if k == "" || v == "" { + return + } + if !privileged && selfKeysThisStep[k] { + return + } + out[k] = v + } + packDir := dirs[lc.PluginID] + if packDir != "" && strings.TrimSpace(ov.MessagesFile) != "" { + if loaded, err := loadLocaleJSONFile(packDir, ov.MessagesFile); err == nil { + for k, v := range loaded { + applyMsg(k, v) + } + } + } + for k, v := range ov.Messages { + applyMsg(k, v) + } + } + } + m.mu.Lock() + if m.l10nGen == gen { + if len(m.l10nCache) >= 512 { + clear(m.l10nCache) + } + if len(out) == 0 { + m.l10nCache[cacheKey] = nil + } else { + m.l10nCache[cacheKey] = maps.Clone(out) + } + } + m.mu.Unlock() + if len(out) == 0 { + return nil + } + return out +} + +// NotifyLocaleChanged broadcasts `plugin/localeChanged` to all currently running +// L3 Sidecar processes without waking sleeping Sidecars. +func (m *Manager) NotifyLocaleChanged(eff i18n.Locale) { + if m == nil { + return + } + m.mu.RLock() + sups := maps.Clone(m.supervisors) + m.mu.RUnlock() + if len(sups) == 0 { + return + } + chain := i18n.FallbackChain(eff) + strChain := make([]string, len(chain)) + for i, c := range chain { + strChain[i] = string(c) + } + for pid, sup := range sups { + if sup.PID() == 0 { + continue + } + sup.NotifyIfRunning("plugin/localeChanged", map[string]any{ + "locale": string(eff), + "fallbackChain": strChain, + "l10nBundle": m.PluginL10nBundle(pid, eff), + }) + } +} + +func defaultLocaleLabel(code string) string { + switch code { + case string(i18n.ZhCN): + return "简体中文" + case string(i18n.EnUS): + return "English" + default: + return code + } +} + +func isPrivilegedLocaleTrustRank(rank int) bool { + return rank == 10 || rank == 20 || rank >= 50 +} + +func localeTrustRank(source SourceKind, trust TrustLevel) int { + switch { + case source == SourceBuiltin: + return 10 + case source == SourceBundled: + return 20 + case trust == TrustCommunity: + return 30 + case trust == TrustVerified: + return 40 + case trust == TrustOfficial: + return 50 + case source == SourceDevLink || trust == TrustDev: + return 60 + default: + return 30 + } +} + +func mergeMessages(dst, src map[string]string) { + for k, v := range src { + if k != "" && v != "" { + dst[k] = v + } + } +} + +// mergeLocaleFile merges the messages in dir/rel into dst. A missing or +// invalid file adds nothing; the plugin scanner reports those. +func mergeLocaleFile(dst map[string]string, dir, rel string) { + rel = strings.TrimSpace(rel) + if dir == "" || rel == "" { + return + } + if loaded, err := loadLocaleJSONFile(dir, rel); err == nil { + mergeMessages(dst, loaded) + } +} + +// mergeBackendMessages merges the Go-side messages of one language pack. +// Later sources win: domain files, the backend file, then inline messages. +func mergeBackendMessages(dst map[string]string, dir string, lc LocaleContribution) { + for _, dom := range []string{"native", "macosGlossary", "macos-glossary", "core"} { + mergeLocaleFile(dst, dir, lc.Files[dom]) + } + mergeLocaleFile(dst, dir, lc.BackendFile) + mergeMessages(dst, lc.Backend) +} + +// l10nFile is one `/.json` message file of a plugin. +type l10nFile struct { + locale i18n.Locale + rel string +} + +// l10nFiles lists the private message files a plugin ships in its l10n folder. +func l10nFiles(pluginDir, l10n string) []l10nFile { + l10n = strings.Trim(strings.TrimSpace(l10n), "/") + if pluginDir == "" || l10n == "" { + return nil + } + full, err := safeJoin(pluginDir, l10n) + if err != nil { + return nil + } + entries, err := os.ReadDir(full) + if err != nil { + return nil + } + var files []l10nFile + for _, ent := range entries { + if ent.IsDir() || !strings.HasSuffix(strings.ToLower(ent.Name()), ".json") { + continue + } + tag := strings.TrimSuffix(ent.Name(), filepath.Ext(ent.Name())) + if canon, ok := i18n.ParseLocale(tag); ok { + files = append(files, l10nFile{locale: canon, rel: l10n + "/" + ent.Name()}) + } + } + return files +} + +// LoadStaticLocalePacks performs an ultra-fast (< 2ms), side-effect-free scan of +// enabled plugins under dataRoot to populate backend/CLI language packs without +// starting any L3 Sidecars, AssetServer, or service dependency reconciliation. +func LoadStaticLocalePacks(dataRoot string) map[i18n.Locale]i18n.PluginCatalog { + if strings.TrimSpace(dataRoot) == "" { + i18n.SetPluginCatalogs(nil) + return nil + } + layout := NewPluginsLayout(dataRoot) + if DidLastStartupCrash(layout.Root) { + i18n.SetPluginCatalogs(nil) + return nil + } + st, err := NewStateStore(layout.Root).Load() + if err != nil || st == nil || len(st.Plugins) == 0 { + i18n.SetPluginCatalogs(nil) + return nil + } + + type staticCandidate struct { + id string + dir string + rec *PluginRecord + rank int + } + var candidates []staticCandidate + for id, rec := range st.Plugins { + if rec == nil || !rec.Enabled || rec.Source == SourceBuiltin || rec.Source == SourceBundled { + continue + } + var dir string + if rec.Source == SourceDevLink { + if !st.DeveloperMode || strings.TrimSpace(rec.DevPath) == "" { + continue + } + dir = rec.DevPath + } else { + if rec.Version == "" || !reReverseDomainID.MatchString(id) { + continue + } + if _, err := ParseSemVer(rec.Version); err != nil { + continue + } + safeDir, err := safeJoin(layout.PkgsDir(), id+"/"+rec.Version) + if err != nil { + continue + } + dir = safeDir + } + candidates = append(candidates, staticCandidate{ + id: id, + dir: dir, + rec: rec, + rank: localeTrustRank(rec.Source, rec.Trust), + }) + } + sort.Slice(candidates, func(i, j int) bool { + if candidates[i].rank != candidates[j].rank { + return candidates[i].rank < candidates[j].rank + } + return candidates[i].id < candidates[j].id + }) + + type staticLocaleItem struct { + canon i18n.Locale + rank int + id string + dir string + lc LocaleContribution + } + var items []staticLocaleItem + for _, c := range candidates { + raw, err := os.ReadFile(filepath.Join(c.dir, "plugin.json")) + if err != nil { + continue + } + var man Manifest + if json.Unmarshal(raw, &man) != nil || len(man.Contributes.Locales) == 0 { + continue + } + if c.id != "" && man.ID != c.id { + continue + } + trust := c.rec.Trust + if trust == "" { + trust = TrustCommunity + } + if c.rec.Source == SourceDevLink { + trust = TrustDev + } + _, _, entryHash, err := resolveManifestEntry(man, c.dir, false) + if err != nil { + continue + } + if computeNeedsApproval(man, trust, c.rec.ApprovedPermissions, c.rec.ApprovedEntryHash, entryHash) { + continue + } + for _, lc := range man.Contributes.Locales { + canon, ok := i18n.ParseLocale(lc.Locale) + if !ok { + continue + } + items = append(items, staticLocaleItem{ + canon: canon, + rank: c.rank, + id: c.id, + dir: c.dir, + lc: lc, + }) + } + } + + sort.Slice(items, func(i, j int) bool { + if items[i].canon != items[j].canon { + return items[i].canon < items[j].canon + } + if items[i].rank != items[j].rank { + return items[i].rank < items[j].rank + } + if items[i].lc.Priority != items[j].lc.Priority { + return items[i].lc.Priority < items[j].lc.Priority + } + return items[i].id < items[j].id + }) + + packs := make(map[i18n.Locale]i18n.PluginCatalog) + for _, it := range items { + canon := it.canon + if !isPrivilegedLocaleTrustRank(it.rank) && (canon == i18n.ZhCN || canon == i18n.EnUS) { + continue + } + lc := it.lc + cur, exists := packs[canon] + if !exists { + cur = i18n.PluginCatalog{ + Fallback: i18n.DefaultFallback(canon), + Messages: make(map[string]string), + } + } + if fb, ok := i18n.ParseLocale(lc.Fallback); ok { + cur.Fallback = fb + } + mergeBackendMessages(cur.Messages, it.dir, lc) + if len(cur.Messages) > 0 { + packs[canon] = cur + } + } + i18n.SetPluginCatalogs(packs) + return packs +} diff --git a/internal/plugin/scanner.go b/internal/plugin/scanner.go index ff07e89..81cc375 100644 --- a/internal/plugin/scanner.go +++ b/internal/plugin/scanner.go @@ -173,137 +173,170 @@ func ScanArchive(archivePath, tmpParentDir, hostVersion string, opts ScanOptions return ScanDirectory(stageDir, hostVersion, opts), nil } +// packageScan is one ScanDirectory run. +type packageScan struct { + dir string + opts ScanOptions + m Manifest + rep ScanReport + + sidecar string // declared entries, normalized + panelDir string + runtimeDirs []string + hasNetPerm bool + themeCSS map[string]bool // stylesheets checked with their theme + netScripts []string // scripts that use a declared net permission +} + +func (s *packageScan) hard(check, target, msg string, zh, en string) { + s.rep.HardFindings = append(s.rep.HardFindings, ScanFinding{ + Severity: ScanSeverityHard, + Check: check, + Target: target, + Message: msg, + Localized: LocalizedText{ZhCN: zh, EnUS: en}, + }) +} + +func (s *packageScan) pending(check, target, msg string, zh, en string) { + s.rep.PendingFindings = append(s.rep.PendingFindings, ScanFinding{ + Severity: ScanSeverityPending, + Check: check, + Target: target, + Message: msg, + Localized: LocalizedText{ZhCN: zh, EnUS: en}, + }) +} + // ScanDirectory performs a comprehensive static risk and policy scan on a plugin // directory (unpacked archive, installed package, or dev-linked directory). func ScanDirectory(dir, hostVersion string, opts ScanOptions) ScanReport { - rep := ScanReport{ - Trust: TrustCommunity, - } - addHard := func(check, target, msg string, zh, en string) { - rep.HardFindings = append(rep.HardFindings, ScanFinding{ - Severity: ScanSeverityHard, - Check: check, - Target: target, - Message: msg, - Localized: LocalizedText{ZhCN: zh, EnUS: en}, - }) - } - addPending := func(check, target, msg string, zh, en string) { - rep.PendingFindings = append(rep.PendingFindings, ScanFinding{ - Severity: ScanSeverityPending, - Check: check, - Target: target, - Message: msg, - Localized: LocalizedText{ZhCN: zh, EnUS: en}, - }) - } - - raw, err := os.ReadFile(filepath.Join(dir, "plugin.json")) + s := &packageScan{dir: dir, opts: opts, rep: ScanReport{Trust: TrustCommunity}, themeCSS: map[string]bool{}} + raw, err := os.ReadFile(filepath.Join(s.dir, "plugin.json")) if err != nil { - addHard("manifest", "plugin.json", "cannot read plugin.json: "+err.Error(), + s.hard("manifest", "plugin.json", "cannot read plugin.json: "+err.Error(), "缺少或无法读取 plugin.json 清单文件", "Cannot read plugin.json manifest") - finalizeScanReport(&rep) - return rep + finalizeScanReport(&s.rep) + return s.rep } - var m Manifest - if err := json.Unmarshal(raw, &m); err != nil { - addHard("manifest", "plugin.json", "invalid plugin.json JSON: "+err.Error(), + if err := json.Unmarshal(raw, &s.m); err != nil { + s.hard("manifest", "plugin.json", "invalid plugin.json JSON: "+err.Error(), "plugin.json 格式无效:"+err.Error(), "Invalid plugin.json JSON: "+err.Error()) - finalizeScanReport(&rep) - return rep + finalizeScanReport(&s.rep) + return s.rep } - rep.PluginID = m.ID - rep.Version = m.Version - rep.Name = m.Name - rep.Tier = m.InferTier(false) - rep.Publisher = m.Publisher - rep.License = m.License + s.rep.PluginID = s.m.ID + s.rep.Version = s.m.Version + s.rep.Name = s.m.Name + s.rep.Tier = s.m.InferTier(false) + s.rep.Publisher = s.m.Publisher + s.rep.License = s.m.License - if err := ValidateManifest(m, hostVersion, false); err != nil { - addHard("manifest", "plugin.json", err.Error(), + if err := ValidateManifest(s.m, hostVersion, false); err != nil { + s.hard("manifest", "plugin.json", err.Error(), "清单校验未通过:"+err.Error(), "Manifest validation failed: "+err.Error()) } - rep.PendingFindings = append(rep.PendingFindings, ContractFindings(m, raw)...) + s.rep.PendingFindings = append(s.rep.PendingFindings, ContractFindings(s.m, raw)...) // Build normalized sets of declared entries & runtime directories. - declaredSidecar := normalizeRel(m.Entry.Sidecar) - declaredPanelDir := normalizeRel(m.Entry.PanelDir) - runtimeDirs := make([]string, 0, len(m.Contributes.Runtimes)) - for _, rtPack := range m.Contributes.Runtimes { + s.sidecar = normalizeRel(s.m.Entry.Sidecar) + s.panelDir = normalizeRel(s.m.Entry.PanelDir) + for _, rtPack := range s.m.Contributes.Runtimes { if d := normalizeRel(rtPack.Dir); d != "" { - runtimeDirs = append(runtimeDirs, d) + s.runtimeDirs = append(s.runtimeDirs, d) } } - hasNetPerm := false - for _, p := range m.Permissions { + for _, p := range s.m.Permissions { if strings.HasPrefix(strings.TrimSpace(p), "net:") { - hasNetPerm = true + s.hasNetPerm = true break } } - // Verify declared entries exist on disk. + s.checkEntries() + s.checkThemes() + s.checkFiles() + s.checkChecksums() + s.checkLocales() + + // Build plain-language capability explanations & L3 native boundary notice (§7.2). + s.rep.Capabilities = buildCapabilityItems(s.m, s.rep.Tier, s.rep.Executables, s.netScripts) + if s.rep.Tier == TierL3 { + s.rep.NativeExecNotice = LocalizedText{ + ZhCN: "此插件包含原生可执行程序(L3 Sidecar),启动后将以当前 Windows 账户完整权限运行。静态扫描只能核对清单完整性与哈希,无法证明原生二进制内部行为安全,请务必核对作者来源与 SHA-256。", + EnUS: "This plugin ships a native executable (L3 Sidecar) that runs with full current Windows user privileges. Static scanning verifies manifest integrity and hashes only and cannot prove native binary safety; verify publisher provenance and SHA-256 before enabling.", + } + } + _, _, entryHash, _ := resolveManifestEntry(s.m, s.dir, false) + s.rep.NeedsApproval = computeNeedsApproval(s.m, s.rep.Trust, nil, "", entryHash) + + finalizeScanReport(&s.rep) + return s.rep +} + +// checkEntries verifies that the declared entries exist on disk. +func (s *packageScan) checkEntries() { checkEntryFile := func(label, rel string, expectDir bool) { if strings.TrimSpace(rel) == "" { return } - full, jErr := safeJoin(dir, rel) + full, jErr := safeJoin(s.dir, rel) if jErr != nil { - addHard("missing-entry", rel, fmt.Sprintf("invalid %s path %q: %v", label, rel, jErr), + s.hard("missing-entry", rel, fmt.Sprintf("invalid %s path %q: %v", label, rel, jErr), fmt.Sprintf("声明的入口路径 %s 非法:%v", rel, jErr), fmt.Sprintf("Declared %s path %q is invalid: %v", label, rel, jErr)) return } st, sErr := os.Stat(full) if sErr != nil { - addHard("missing-entry", rel, fmt.Sprintf("declared %s %q is missing", label, rel), + s.hard("missing-entry", rel, fmt.Sprintf("declared %s %q is missing", label, rel), fmt.Sprintf("清单声明的入口 %s 不存在", rel), fmt.Sprintf("Declared %s %q is missing from package", label, rel)) return } if expectDir && !st.IsDir() { - addHard("missing-entry", rel, fmt.Sprintf("declared %s %q is not a directory", label, rel), + s.hard("missing-entry", rel, fmt.Sprintf("declared %s %q is not a directory", label, rel), fmt.Sprintf("清单声明的目录入口 %s 不是目录", rel), fmt.Sprintf("Declared %s %q is not a directory", label, rel)) } else if !expectDir && st.IsDir() { - addHard("missing-entry", rel, fmt.Sprintf("declared %s %q is a directory, expected file", label, rel), + s.hard("missing-entry", rel, fmt.Sprintf("declared %s %q is a directory, expected file", label, rel), fmt.Sprintf("清单声明的文件入口 %s 是目录而非文件", rel), fmt.Sprintf("Declared %s %q is a directory, expected a file", label, rel)) } } - checkEntryFile("entry.sidecar", m.Entry.Sidecar, false) - checkEntryFile("entry.script", m.Entry.Script, false) - checkEntryFile("entry.uiScript", m.Entry.UIScript, false) - checkEntryFile("entry.panelDir", m.Entry.PanelDir, true) - for _, us := range m.Contributes.UIScripts { + checkEntryFile("entry.sidecar", s.m.Entry.Sidecar, false) + checkEntryFile("entry.script", s.m.Entry.Script, false) + checkEntryFile("entry.uiScript", s.m.Entry.UIScript, false) + checkEntryFile("entry.panelDir", s.m.Entry.PanelDir, true) + for _, us := range s.m.Contributes.UIScripts { checkEntryFile("contributes.uiScripts", us.Script, false) } - for _, panel := range m.Contributes.Panels { - if declaredPanelDir != "" && panel.Entry != "" { - checkEntryFile("panel entry", declaredPanelDir+"/"+strings.TrimPrefix(panel.Entry, "/"), false) + for _, panel := range s.m.Contributes.Panels { + if s.panelDir != "" && panel.Entry != "" { + checkEntryFile("panel entry", s.panelDir+"/"+strings.TrimPrefix(panel.Entry, "/"), false) } } +} - // Track theme stylesheets so we don't duplicate CSS checks in the directory walk. - declaredThemeCSS := map[string]bool{} - for _, th := range m.Contributes.Themes { +func (s *packageScan) checkThemes() { + for _, th := range s.m.Contributes.Themes { if th.Stylesheet != "" { - declaredThemeCSS[normalizeRel(th.Stylesheet)] = true + s.themeCSS[normalizeRel(th.Stylesheet)] = true } - if err := ValidateThemeContribution(th, dir); err != nil { - addHard("theme-css", th.Stylesheet, err.Error(), + if err := ValidateThemeContribution(th, s.dir); err != nil { + s.hard("theme-css", th.Stylesheet, err.Error(), "主题样式或资源未通过安全校验:"+err.Error(), "Theme stylesheet or asset failed safety validation: "+err.Error()) } - if th.Stylesheet != "" && opts.Contract != nil { - if cssPath, jErr := safeJoin(dir, th.Stylesheet); jErr == nil { + if th.Stylesheet != "" && s.opts.Contract != nil { + if cssPath, jErr := safeJoin(s.dir, th.Stylesheet); jErr == nil { if cssBytes, rErr := os.ReadFile(cssPath); rErr == nil { - for _, issue := range CheckCSSAgainstContract(string(cssBytes), *opts.Contract) { - addPending("ui-contract", th.Stylesheet, issue, + for _, issue := range CheckCSSAgainstContract(string(cssBytes), *s.opts.Contract) { + s.pending("ui-contract", th.Stylesheet, issue, fmt.Sprintf("主题样式 %s 存在 UI 契约提示:%s", th.Stylesheet, issue), fmt.Sprintf("Theme CSS %s UI contract advisory: %s", th.Stylesheet, issue)) } @@ -311,15 +344,15 @@ func ScanDirectory(dir, hostVersion string, opts ScanOptions) ScanReport { } } } +} - // Walk all files in the package for redlines, executables, SVG scripts, CSS, and JS safety. - var netScriptHits []string +func (s *packageScan) checkFiles() { var walkFiles []string - _ = filepath.Walk(dir, func(p string, info os.FileInfo, wErr error) error { + _ = filepath.Walk(s.dir, func(p string, info os.FileInfo, wErr error) error { if wErr != nil || info == nil || info.IsDir() { return nil } - rel, rErr := filepath.Rel(dir, p) + rel, rErr := filepath.Rel(s.dir, p) if rErr != nil { return nil } @@ -327,202 +360,195 @@ func ScanDirectory(dir, hostVersion string, opts ScanOptions) ScanReport { return nil }) sort.Strings(walkFiles) - for _, rel := range walkFiles { - full := filepath.Join(dir, filepath.FromSlash(rel)) - info, sErr := os.Stat(full) - if sErr != nil || info.IsDir() { - continue - } - lowName := strings.ToLower(info.Name()) - ext := strings.ToLower(filepath.Ext(lowName)) + s.checkFile(rel) + } +} - for _, pat := range ForbiddenMarketPatterns { - if strings.Contains(lowName, pat) { - addHard("redline", rel, fmt.Sprintf("forbidden proprietary file detected (%s)", rel), - fmt.Sprintf("检测到禁止分发的专有系统文件:%s", rel), - fmt.Sprintf("Forbidden proprietary file detected: %s", rel)) - } - } - if info.Size() <= 256*1024 && isRedlineTextExt(ext) { - if b, rErr := os.ReadFile(full); rErr == nil { - if containsForbiddenSMCKey(strings.ToLower(string(b))) { - addHard("redline", rel, fmt.Sprintf("forbidden Apple SMC OSK detected in %s", rel), - fmt.Sprintf("在 %s 中检测到禁止分发的 Apple SMC OSK 密钥", rel), - fmt.Sprintf("Forbidden Apple SMC OSK detected in %s", rel)) - } - } - } +// checkFile looks for redlines, executables, SVG scripts, and unsafe CSS and JS. +func (s *packageScan) checkFile(rel string) { + full := filepath.Join(s.dir, filepath.FromSlash(rel)) + info, sErr := os.Stat(full) + if sErr != nil || info.IsDir() { + return + } + lowName := strings.ToLower(info.Name()) + ext := strings.ToLower(filepath.Ext(lowName)) - if ForbiddenBinaryExtensions[ext] { - sum, _ := fileSHA256Hex(full) - declared := false - switch rep.Tier { - case TierL3: - if declaredSidecar != "" && strings.EqualFold(rel, declaredSidecar) { - declared = true - } - case TierRuntime: - for _, rd := range runtimeDirs { - if rel == rd || strings.HasPrefix(strings.ToLower(rel), strings.ToLower(rd)+"/") { - declared = true - break - } - } - } - rep.Executables = append(rep.Executables, ExecutableFile{ - Path: rel, - SHA256: sum, - Declared: declared, - SizeBytes: info.Size(), - }) - if !declared { - if rep.Tier == TierL3 || rep.Tier == TierRuntime { - addHard("unlisted-executable", rel, - fmt.Sprintf("unlisted executable or script %q not declared in manifest", rel), - fmt.Sprintf("包含未在清单中声明的可执行文件或脚本:%s", rel), - fmt.Sprintf("Unlisted executable or script not declared in manifest: %s", rel)) - } else { - addHard("forbidden-binary", rel, - fmt.Sprintf("executable or OS script %q is forbidden in %s plugin packages", rel, rep.Tier), - fmt.Sprintf("%s 类型插件禁止夹带可执行文件或系统脚本:%s", rep.Tier, rel), - fmt.Sprintf("Executable or OS script %q is forbidden in %s packages", rel, rep.Tier)) - } - } + for _, pat := range ForbiddenMarketPatterns { + if strings.Contains(lowName, pat) { + s.hard("redline", rel, fmt.Sprintf("forbidden proprietary file detected (%s)", rel), + fmt.Sprintf("检测到禁止分发的专有系统文件:%s", rel), + fmt.Sprintf("Forbidden proprietary file detected: %s", rel)) } - - if ext == ".svg" && info.Size() <= maxScanTextBytes { - if b, rErr := os.ReadFile(full); rErr == nil { - if reason := scanSVGActiveContent(string(b)); reason != "" { - addHard("svg-script", rel, fmt.Sprintf("unsafe active content in SVG %s: %s", rel, reason), - fmt.Sprintf("SVG 文件 %s 包含被禁止的脚本或事件属性(%s)", rel, reason), - fmt.Sprintf("SVG file %s contains forbidden active content (%s)", rel, reason)) - } - } - } - - if ext == ".css" && !declaredThemeCSS[rel] && !inRelDir(rel, declaredPanelDir) && info.Size() <= maxScanTextBytes { - if b, rErr := os.ReadFile(full); rErr == nil { - if err := ValidateThemeCSSSafety(string(b), filepath.Dir(full)); err != nil { - addHard("theme-css", rel, fmt.Sprintf("unsafe CSS %s: %v", rel, err), - fmt.Sprintf("样式文件 %s 未通过安全校验:%v", rel, err), - fmt.Sprintf("Stylesheet %s failed safety check: %v", rel, err)) - } - } - } - - if (ext == ".js" || ext == ".mjs" || ext == ".cjs") && info.Size() <= maxScanTextBytes { - if b, rErr := os.ReadFile(full); rErr == nil { - hits, hasNet := scanScriptContent(string(b), false) - for _, hit := range hits { - addHard("ui-script", rel, fmt.Sprintf("forbidden JS pattern (%s) in %s", hit, rel), - fmt.Sprintf("脚本 %s 包含被禁止的宿主逃逸或动态执行语句(%s)", rel, hit), - fmt.Sprintf("Script %s contains forbidden host-escape or dynamic-eval pattern (%s)", rel, hit)) - } - if hasNet { - if !hasNetPerm { - addHard("ui-script-undeclared-net", rel, - fmt.Sprintf("script %s calls network APIs without declaring any net: permission", rel), - fmt.Sprintf("脚本 %s 调用了网络接口,但清单未声明 net: 权限", rel), - fmt.Sprintf("Script %s calls network APIs without declaring any net: permission", rel)) - } else { - netScriptHits = append(netScriptHits, rel) - } - } - } - } - if (ext == ".html" || ext == ".htm") && inRelDir(rel, declaredPanelDir) && info.Size() <= maxScanTextBytes { - if b, rErr := os.ReadFile(full); rErr == nil { - hits, _ := scanScriptContent(string(b), true) - for _, hit := range hits { - addHard("panel-html", rel, fmt.Sprintf("forbidden host-escape pattern (%s) in panel %s", hit, rel), - fmt.Sprintf("面板页面 %s 包含被禁止的宿主逃逸语句(%s)", rel, hit), - fmt.Sprintf("Panel HTML %s contains forbidden host-escape pattern (%s)", rel, hit)) - } + } + if info.Size() <= 256*1024 && isRedlineTextExt(ext) { + if b, rErr := os.ReadFile(full); rErr == nil { + if containsForbiddenSMCKey(strings.ToLower(string(b))) { + s.hard("redline", rel, fmt.Sprintf("forbidden Apple SMC OSK detected in %s", rel), + fmt.Sprintf("在 %s 中检测到禁止分发的 Apple SMC OSK 密钥", rel), + fmt.Sprintf("Forbidden Apple SMC OSK detected in %s", rel)) } } } - sumsPath := filepath.Join(dir, "SHA256SUMS") - if sumsRaw, sErr := os.ReadFile(sumsPath); sErr == nil { - if err := verifyDirSHA256Sums(dir, sumsRaw); err != nil { - addHard("checksum", "SHA256SUMS", err.Error(), - "SHA256SUMS 完整性校验失败:"+err.Error(), - "SHA256SUMS integrity verification failed: "+err.Error()) - } - if sigRaw, sigErr := os.ReadFile(filepath.Join(dir, "SHA256SUMS.sig")); sigErr == nil { - if len(opts.Keyring) > 0 { - t, vErr := verifyEd25519Signature(sumsRaw, sigRaw, opts.Keyring) - if vErr != nil { - addHard("signature", "SHA256SUMS.sig", "invalid package signature: "+vErr.Error(), - "插件签名验证失败:"+vErr.Error(), - "Plugin signature verification failed: "+vErr.Error()) - } else { - rep.Trust = t + if ForbiddenBinaryExtensions[ext] { + sum, _ := fileSHA256Hex(full) + declared := false + switch s.rep.Tier { + case TierL3: + if s.sidecar != "" && strings.EqualFold(rel, s.sidecar) { + declared = true + } + case TierRuntime: + for _, rd := range s.runtimeDirs { + if rel == rd || strings.HasPrefix(strings.ToLower(rel), strings.ToLower(rd)+"/") { + declared = true + break } } } - } else if opts.RequireChecksums { - addHard("checksum", "SHA256SUMS", "package missing SHA256SUMS", + s.rep.Executables = append(s.rep.Executables, ExecutableFile{ + Path: rel, + SHA256: sum, + Declared: declared, + SizeBytes: info.Size(), + }) + if !declared { + if s.rep.Tier == TierL3 || s.rep.Tier == TierRuntime { + s.hard("unlisted-executable", rel, + fmt.Sprintf("unlisted executable or script %q not declared in manifest", rel), + fmt.Sprintf("包含未在清单中声明的可执行文件或脚本:%s", rel), + fmt.Sprintf("Unlisted executable or script not declared in manifest: %s", rel)) + } else { + s.hard("forbidden-binary", rel, + fmt.Sprintf("executable or OS script %q is forbidden in %s plugin packages", rel, s.rep.Tier), + fmt.Sprintf("%s 类型插件禁止夹带可执行文件或系统脚本:%s", s.rep.Tier, rel), + fmt.Sprintf("Executable or OS script %q is forbidden in %s packages", rel, s.rep.Tier)) + } + } + } + + if ext == ".svg" && info.Size() <= maxScanTextBytes { + if b, rErr := os.ReadFile(full); rErr == nil { + if reason := scanSVGActiveContent(string(b)); reason != "" { + s.hard("svg-script", rel, fmt.Sprintf("unsafe active content in SVG %s: %s", rel, reason), + fmt.Sprintf("SVG 文件 %s 包含被禁止的脚本或事件属性(%s)", rel, reason), + fmt.Sprintf("SVG file %s contains forbidden active content (%s)", rel, reason)) + } + } + } + + if ext == ".css" && !s.themeCSS[rel] && !inRelDir(rel, s.panelDir) && info.Size() <= maxScanTextBytes { + if b, rErr := os.ReadFile(full); rErr == nil { + if err := ValidateThemeCSSSafety(string(b), filepath.Dir(full)); err != nil { + s.hard("theme-css", rel, fmt.Sprintf("unsafe CSS %s: %v", rel, err), + fmt.Sprintf("样式文件 %s 未通过安全校验:%v", rel, err), + fmt.Sprintf("Stylesheet %s failed safety check: %v", rel, err)) + } + } + } + + if (ext == ".js" || ext == ".mjs" || ext == ".cjs") && info.Size() <= maxScanTextBytes { + if b, rErr := os.ReadFile(full); rErr == nil { + hits, hasNet := scanScriptContent(string(b), false) + for _, hit := range hits { + s.hard("ui-script", rel, fmt.Sprintf("forbidden JS pattern (%s) in %s", hit, rel), + fmt.Sprintf("脚本 %s 包含被禁止的宿主逃逸或动态执行语句(%s)", rel, hit), + fmt.Sprintf("Script %s contains forbidden host-escape or dynamic-eval pattern (%s)", rel, hit)) + } + if hasNet { + if !s.hasNetPerm { + s.hard("ui-script-undeclared-net", rel, + fmt.Sprintf("script %s calls network APIs without declaring any net: permission", rel), + fmt.Sprintf("脚本 %s 调用了网络接口,但清单未声明 net: 权限", rel), + fmt.Sprintf("Script %s calls network APIs without declaring any net: permission", rel)) + } else { + s.netScripts = append(s.netScripts, rel) + } + } + } + } + if (ext == ".html" || ext == ".htm") && inRelDir(rel, s.panelDir) && info.Size() <= maxScanTextBytes { + if b, rErr := os.ReadFile(full); rErr == nil { + hits, _ := scanScriptContent(string(b), true) + for _, hit := range hits { + s.hard("panel-html", rel, fmt.Sprintf("forbidden host-escape pattern (%s) in panel %s", hit, rel), + fmt.Sprintf("面板页面 %s 包含被禁止的宿主逃逸语句(%s)", rel, hit), + fmt.Sprintf("Panel HTML %s contains forbidden host-escape pattern (%s)", rel, hit)) + } + } + } +} + +func (s *packageScan) checkChecksums() { + sumsPath := filepath.Join(s.dir, "SHA256SUMS") + if sumsRaw, sErr := os.ReadFile(sumsPath); sErr == nil { + if err := verifyDirSHA256Sums(s.dir, sumsRaw); err != nil { + s.hard("checksum", "SHA256SUMS", err.Error(), + "SHA256SUMS 完整性校验失败:"+err.Error(), + "SHA256SUMS integrity verification failed: "+err.Error()) + } + if sigRaw, sigErr := os.ReadFile(filepath.Join(s.dir, "SHA256SUMS.sig")); sigErr == nil { + if len(s.opts.Keyring) > 0 { + t, vErr := verifyEd25519Signature(sumsRaw, sigRaw, s.opts.Keyring) + if vErr != nil { + s.hard("signature", "SHA256SUMS.sig", "invalid package signature: "+vErr.Error(), + "插件签名验证失败:"+vErr.Error(), + "Plugin signature verification failed: "+vErr.Error()) + } else { + s.rep.Trust = t + } + } + } + } else if s.opts.RequireChecksums { + s.hard("checksum", "SHA256SUMS", "package missing SHA256SUMS", "分发压缩包缺少必需的 SHA256SUMS 校验文件", "Distribution package is missing required SHA256SUMS file") } else { - addPending("checksum", "SHA256SUMS", "SHA256SUMS absent (acceptable in dev link mode; required for .zip distribution)", + s.pending("checksum", "SHA256SUMS", "SHA256SUMS absent (acceptable in dev link mode; required for .zip distribution)", "未包含 SHA256SUMS(本地开发链接可忽略,打包分发 .zip 时必需)", "SHA256SUMS absent (acceptable in dev link mode; required for .zip distribution)") } - if rep.Trust == TrustCommunity { - addPending("trust-unsigned", "", "community package is not signed by an official or verified market key", + if s.rep.Trust == TrustCommunity { + s.pending("trust-unsigned", "", "community package is not signed by an official or verified market key", "社区插件未携带官方或已审核签名,请仅安装来自可信作者的插件包", "Community package is not signed by an official or verified key; install only from authors you trust") } +} - // 7. L10n & Locale contributions. - if strings.TrimSpace(m.L10n) != "" { - if err := validatePluginL10nDir(m.L10n, dir); err != nil { - addHard("l10n", m.L10n, err.Error(), +func (s *packageScan) checkLocales() { + if strings.TrimSpace(s.m.L10n) != "" { + if err := validatePluginL10nDir(s.m.L10n, s.dir); err != nil { + s.hard("l10n", s.m.L10n, err.Error(), "插件本地化目录校验失败:"+err.Error(), "Plugin l10n directory validation failed: "+err.Error()) } } - if len(m.Contributes.Locales) > 0 { - if _, locFindings, cErr := CheckLocalePack(dir); cErr == nil && len(locFindings) > 0 { + if len(s.m.Contributes.Locales) > 0 { + if _, locFindings, cErr := CheckLocalePack(s.dir); cErr == nil && len(locFindings) > 0 { for _, lf := range locFindings { if lf.Severity == "error" { - addHard("locale", lf.Check, lf.Message, + s.hard("locale", lf.Check, lf.Message, "语言包校验错误:"+lf.Message, "Language pack validation error: "+lf.Message) } else if lf.Severity == "warn" { - addPending("locale", lf.Check, lf.Message, + s.pending("locale", lf.Check, lf.Message, "语言包提示:"+lf.Message, "Language pack advisory: "+lf.Message) } } } else { - for _, lc := range m.Contributes.Locales { - if err := ValidateLocaleContribution(lc, dir); err != nil { - addHard("locale", lc.Locale, err.Error(), + for _, lc := range s.m.Contributes.Locales { + if err := ValidateLocaleContribution(lc, s.dir); err != nil { + s.hard("locale", lc.Locale, err.Error(), fmt.Sprintf("语言包 %s 校验失败:%v", lc.Locale, err), fmt.Sprintf("Locale %s validation failed: %v", lc.Locale, err)) } } } } - - // 8. Build plain-language capability explanations & L3 native boundary notice (§7.2). - rep.Capabilities = buildCapabilityItems(m, rep.Tier, rep.Executables, netScriptHits) - if rep.Tier == TierL3 { - rep.NativeExecNotice = LocalizedText{ - ZhCN: "此插件包含原生可执行程序(L3 Sidecar),启动后将以当前 Windows 账户完整权限运行。静态扫描只能核对清单完整性与哈希,无法证明原生二进制内部行为安全,请务必核对作者来源与 SHA-256。", - EnUS: "This plugin ships a native executable (L3 Sidecar) that runs with full current Windows user privileges. Static scanning verifies manifest integrity and hashes only and cannot prove native binary safety; verify publisher provenance and SHA-256 before enabling.", - } - } - _, _, entryHash, _ := resolveManifestEntry(m, dir, false) - rep.NeedsApproval = computeNeedsApproval(m, rep.Trust, nil, "", entryHash) - - finalizeScanReport(&rep) - return rep } func finalizeScanReport(rep *ScanReport) { From 50c03a083563ae6b5eaf7c919a1515fd3411dd12 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: Thu, 3 Dec 2026 21:38:17 -0700 Subject: [PATCH 12/22] perf(frontend): load the settings and plugin texts on demand again App.tsx imported a one-line helper from SchemaForm, which pulled both text domains into the startup bundle. The i18n test now follows the real import graph instead of a hand-kept file list, so it catches this. npm test runs every test file. Co-Authored-By: Claude Opus 5.5 --- frontend/package.json | 2 +- frontend/scripts/test-i18n.mjs | 116 ++++++++----------- frontend/src/App.tsx | 40 +++---- frontend/src/components/ImagesPage.tsx | 3 +- frontend/src/components/PluginMarket.tsx | 3 +- frontend/src/components/PluginPanelFrame.tsx | 4 +- frontend/src/components/PluginViewHost.tsx | 3 +- frontend/src/components/PluginsPage.tsx | 4 +- frontend/src/components/SchemaForm.tsx | 2 - frontend/src/i18n/domains/settings.gen.ts | 2 - frontend/src/i18n/domains/vm.gen.ts | 2 + locales/en-US/settings.json | 1 - locales/en-US/vm.json | 3 +- locales/zh-CN/settings.json | 1 - locales/zh-CN/vm.json | 3 +- 15 files changed, 84 insertions(+), 105 deletions(-) diff --git a/frontend/package.json b/frontend/package.json index 8a74cc6..4e454cc 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -5,7 +5,7 @@ "type": "module", "scripts": { "dev": "vite", - "test": "node --test --test-concurrency=2 scripts/test-i18n.mjs scripts/test-keymap.mjs scripts/test-plugins.mjs scripts/test-tasks.mjs scripts/test-display-presets.mjs scripts/test-endpoints.mjs scripts/test-guest-tools.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs scripts/test-unused-exports.mjs scripts/test-hypervisor.mjs", + "test": "node --test --test-concurrency=2 \"scripts/test-*.mjs\"", "typecheck": "tsc --noEmit", "bundle": "vite build && node scripts/check-ui-contract.mjs", "build": "tsc --noEmit && pnpm run bundle", diff --git a/frontend/scripts/test-i18n.mjs b/frontend/scripts/test-i18n.mjs index 52b22cf..fcd240b 100644 --- a/frontend/scripts/test-i18n.mjs +++ b/frontend/scripts/test-i18n.mjs @@ -20,79 +20,63 @@ function walkFiles(dir, exts) { return out } -test('lazy i18n domain keys are always backed by domain .gen imports', () => { +/** Static imports and dynamic import() targets of a source file, as absolute paths. */ +function importsOf(file) { + const src = fs.readFileSync(file, 'utf8') + const resolve = (spec) => { + const target = path.resolve(path.dirname(file), spec) + return ['', '.ts', '.tsx', '/index.ts', '/index.tsx'].map((ext) => target + ext).find((p) => fs.existsSync(p) && fs.statSync(p).isFile()) + } + const collect = (re) => [...src.matchAll(re)].map((m) => resolve(m[1])).filter((p) => p && /\.tsx?$/.test(p)) + return { + eager: collect(/^(?:import(?! type\b)|export)\b[^'"]*?['"](\.[^'"]+)['"]/gm), + lazy: collect(/\bimport\(\s*['"](\.[^'"]+)['"]\s*\)/g), + } +} + +/** Every module loaded together with entry. */ +function loadedWith(entry, imports) { + const seen = new Set([entry]) + for (const file of seen) for (const next of imports.get(file)?.eager ?? []) seen.add(next) + return seen +} + +test('every chunk registers the lazy i18n domains its keys belong to', () => { const lazyDomains = ['wizard', 'settings', 'plugins'] const keyToDomain = new Map() - for (const dom of ['core', 'vm', ...lazyDomains]) { + for (const dom of lazyDomains) { const raw = JSON.parse(fs.readFileSync(path.join(localesDir, `${dom}.json`), 'utf8')) - for (const k of Object.keys(raw)) { - if (!k.startsWith('$')) keyToDomain.set(k, dom) - } + for (const k of Object.keys(raw)) keyToDomain.set(k, dom) } + const files = walkFiles(srcDir, ['.ts', '.tsx']) + const imports = new Map(files.map((file) => [file, importsOf(file)])) + const entries = new Set([path.join(srcDir, 'main.tsx'), ...[...imports.values()].flatMap((i) => i.lazy)]) + assert.ok(entries.size > 5, 'found no lazy chunks: the import patterns no longer match') - // Known lazy-loaded chunk entry trees (loaded via React.lazy or dynamic import in App.tsx) - const lazyEntryBasenames = new Set([ - 'CreateWizard.tsx', - 'SettingsModal.tsx', - // 网络设置仅随延迟加载的 SettingsModal 进入,使用同一语言域。 - 'VMNetworkSettings.tsx', - // 由新建向导和网络设置两个延迟入口共用。 - 'NpcapDependency.tsx', - 'AffinityDialog.tsx', - 'Setup.tsx', - 'RuntimeOnline.tsx', - 'HostView.tsx', - 'ImagesPage.tsx', - 'InstallersPage.tsx', - 'PluginsPage.tsx', - 'PluginMarket.tsx', - 'PluginParts.tsx', - 'AppSettingsPage.tsx', - 'AboutPage.tsx', - 'PluginPanelFrame.tsx', - 'SchemaForm.tsx', - 'optimizations.ts', - // 仅由延迟加载的 AppSettingsPage、HostView、Setup 共用,自带 settings.gen 域注册。 - 'hypervisor.ts', - ]) - - for (const file of walkFiles(srcDir, ['.ts', '.tsx'])) { - const rel = path.relative(srcDir, file).replace(/\\/g, '/') - if (rel.startsWith('i18n/')) continue - const base = path.basename(file) - const src = fs.readFileSync(file, 'utf8') - - // Match string literals passed to t(..., 'key'), tr('key'), labelKey: 'key', detailKey: 'key', titleKey: 'key', descKey: 'key' - const referencedLazyDomains = new Set() - const callMatches = [ - ...src.matchAll(/\b(?:tr|t)\(\s*(?:[a-zA-Z0-9_$.]+\s*,\s*)?'([a-zA-Z0-9_.]+)'/g), - ...src.matchAll(/\b(?:labelKey|detailKey|titleKey|descKey)\s*:\s*'([a-zA-Z0-9_.]+)'/g), - ] - for (const m of callMatches) { - const dom = keyToDomain.get(m[1]) - if (dom && lazyDomains.includes(dom)) { - referencedLazyDomains.add(`${dom}:${m[1]}`) + for (const entry of entries) { + const modules = [...loadedWith(entry, imports)].filter((file) => !path.relative(srcDir, file).startsWith('i18n')) + const registered = new Set() + for (const file of modules) { + for (const m of fs.readFileSync(file, 'utf8').matchAll(/i18n\/domains\/(\w+)\.gen/g)) registered.add(m[1]) + } + for (const file of modules) { + const src = fs.readFileSync(file, 'utf8') + const keys = [ + ...src.matchAll(/\b(?:tr|t)\(\s*(?:[a-zA-Z0-9_$.]+\s*,\s*)?'([a-zA-Z0-9_.]+)'/g), + ...src.matchAll(/\b(?:label|labelKey|detailKey|titleKey|descKey)\s*:\s*'([a-zA-Z0-9_.]+)'/g), + ].map((m) => m[1]) + for (const key of keys) { + const dom = keyToDomain.get(key) + assert.ok( + !dom || registered.has(dom), + `${path.relative(srcDir, file)} uses ${dom} key "${key}", but the chunk of ${path.relative(srcDir, entry)} never imports i18n/domains/${dom}.gen`, + ) } } - - if (referencedLazyDomains.size === 0) continue - - assert.ok( - lazyEntryBasenames.has(base), - `Eager module ${rel} references lazy domain keys (${[...referencedLazyDomains].join(', ')})! Either move keys to core/vm or lazy-load the module.`, - ) - - for (const item of referencedLazyDomains) { - const [dom, key] = item.split(':') - // Sub-dialogs rendered exclusively inside lazy parent chunks inherit their parent's domain registration - if (base === 'AffinityDialog.tsx' && dom === 'settings') continue - if (base === 'RuntimeOnline.tsx' && (dom === 'wizard' || dom === 'settings')) continue - assert.match( - src, - new RegExp(`i18n/domains/${dom}\\.gen`), - `Module ${rel} uses ${dom} key "${key}" without importing i18n/domains/${dom}.gen`, - ) - } + } + const eager = loadedWith(path.join(srcDir, 'main.tsx'), imports) + for (const dom of lazyDomains) { + assert.ok(!eager.has(path.join(srcDir, 'i18n', 'domains', `${dom}.gen.ts`)), `the ${dom} texts must not load with the main window`) } }) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 087bf2d..22dfee4 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -12,10 +12,8 @@ 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 { PluginViewHost } from './components/PluginViewHost' -import { locText } from './components/SchemaForm' import { VMAction, VMBusyAction, VMPage } from './components/VMPage' -import { buildFallbackChain, I18nKey, localeDir, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n' +import { buildFallbackChain, I18nKey, localeDir, locText, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n' import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format' import { isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints' import { resolveFullscreenHotkey } from './lib/fullscreenHotkey' @@ -47,6 +45,7 @@ const HostView = lazy(() => import('./components/HostView').then((m) => ({ defau const ImagesPage = lazy(() => import('./components/ImagesPage').then((m) => ({ default: m.ImagesPage }))) const InstallersPage = lazy(() => import('./macos/InstallersPage').then((m) => ({ default: m.InstallersPage }))) const PluginsPage = lazy(() => import('./components/PluginsPage').then((m) => ({ default: m.PluginsPage }))) +const PluginViewHost = lazy(() => import('./components/PluginViewHost').then((m) => ({ default: m.PluginViewHost }))) const AppSettingsPage = lazy(() => import('./components/AppSettingsPage').then((m) => ({ default: m.AppSettingsPage }))) const AboutPage = lazy(() => import('./components/AboutPage').then((m) => ({ default: m.AboutPage }))) @@ -356,23 +355,24 @@ export const App: React.FC = () => { const activePluginView = routedView && viewAvailable(routedView, pluginViewState.route?.vm) ? routedView : undefined const activePluginRoute = activePluginView ? pluginViewState.route : null const renderPluginView = (route: PluginViewRoute, view: ViewContribution, dialog = false) => ( - updateViewMetadata(view, metadata)} - onOpenView={openView} - onCloseView={dialog ? () => { - setPluginViewState((current) => closePluginDialog(current, route)) - return { closed: true } - } : closeView} - onNavigate={navigateHost} - /> + + updateViewMetadata(view, metadata)} + onOpenView={openView} + onCloseView={dialog ? () => { + setPluginViewState((current) => closePluginDialog(current, route)) + return { closed: true } + } : closeView} + onNavigate={navigateHost} + /> + ) const renderVMTabs = () => { if (!selectedVM) return null diff --git a/frontend/src/components/ImagesPage.tsx b/frontend/src/components/ImagesPage.tsx index 35982c4..1d065f9 100644 --- a/frontend/src/components/ImagesPage.tsx +++ b/frontend/src/components/ImagesPage.tsx @@ -1,12 +1,11 @@ import { Disc3, Puzzle, RefreshCw } from 'lucide-react' import React, { useCallback, useEffect, useMemo, useState } from 'react' import '../i18n/domains/settings.gen' -import { I18nKey, t } from '../i18n' +import { I18nKey, locText, t } from '../i18n' import { ImageSourceContribution, Locale, PluginUIContributions } from '../types' import { Button, IconButton } from '../ui/controls' import { Segmented } from '../ui/settings' import { PluginPanelFrame } from './PluginPanelFrame' -import { locText } from './SchemaForm' import { WordmarkLoader } from './WordmarkLoader' interface NativeImageSourceRenderOpts { diff --git a/frontend/src/components/PluginMarket.tsx b/frontend/src/components/PluginMarket.tsx index 42f29b9..5b8bb9c 100644 --- a/frontend/src/components/PluginMarket.tsx +++ b/frontend/src/components/PluginMarket.tsx @@ -1,13 +1,12 @@ import { AlertTriangle, Check, Download, ShieldAlert } from 'lucide-react' import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import '../i18n/domains/plugins.gen' -import { I18nKey, t } from '../i18n' +import { I18nKey, locText, t } from '../i18n' import { Locale, MarketBrowseResult, MarketCatalogItem, PluginInfo, ScanReport } from '../types' import { Button, Tip } from '../ui/controls' import { Modal } from '../ui/dialog' import { api, events, MarketInstallProgress } from '../wails' import { PluginAppIcon, PluginApprovalBody, PluginSearchInput, PluginTrustBadge, RiskList } from './PluginParts' -import { locText } from './SchemaForm' import { WordmarkLoader } from './WordmarkLoader' // Cards are revealed in pages as the feed scrolls into view. diff --git a/frontend/src/components/PluginPanelFrame.tsx b/frontend/src/components/PluginPanelFrame.tsx index b645c52..a58346d 100644 --- a/frontend/src/components/PluginPanelFrame.tsx +++ b/frontend/src/components/PluginPanelFrame.tsx @@ -1,6 +1,6 @@ import { AlertTriangle } from 'lucide-react' import React, { useEffect, useRef, useState } from 'react' -import { getPluginMessageBundle, localeDir, parseAppError, t } from '../i18n' +import { getPluginMessageBundle, localeDir, locText, parseAppError, t } from '../i18n' import { Locale, PanelContribution, ViewContribution } from '../types' import { Button } from '../ui/controls' import { ConfirmDialog } from '../ui/dialog' @@ -12,7 +12,7 @@ import { } from '../lib/pluginViewActions' import { buildSafePluginAssetURL } from '../lib/pluginAssets' import { subscribePluginHostEvents } from '../lib/pluginViewEvents' -import { locText, SchemaForm } from './SchemaForm' +import { SchemaForm } from './SchemaForm' interface Props { locale: Locale diff --git a/frontend/src/components/PluginViewHost.tsx b/frontend/src/components/PluginViewHost.tsx index cbf0578..2c89ba9 100644 --- a/frontend/src/components/PluginViewHost.tsx +++ b/frontend/src/components/PluginViewHost.tsx @@ -1,10 +1,9 @@ import React from 'react' -import { t } from '../i18n' +import { locText, t } from '../i18n' import { Locale, ViewContribution } from '../types' import { Button } from '../ui/controls' import { Modal } from '../ui/dialog' import { PluginPanelFrame } from './PluginPanelFrame' -import { locText } from './SchemaForm' interface Props { view: ViewContribution diff --git a/frontend/src/components/PluginsPage.tsx b/frontend/src/components/PluginsPage.tsx index 6b3f9cb..7a49ab6 100644 --- a/frontend/src/components/PluginsPage.tsx +++ b/frontend/src/components/PluginsPage.tsx @@ -5,7 +5,7 @@ import { import React, { useEffect, useMemo, useRef, useState } from 'react' import '../i18n/domains/plugins.gen' import '../i18n/domains/settings.gen' -import { I18nKey, t } from '../i18n' +import { I18nKey, locText, t } from '../i18n' import { ActiveThemePayload, CustomThemeScheme, Locale, PluginInfo, PluginUIContributions, ScanReport, ViewContribution, } from '../types' @@ -16,7 +16,7 @@ import { api } from '../wails' import { PluginMarket } from './PluginMarket' import { PluginPanelFrame } from './PluginPanelFrame' import { PluginAppIcon, PluginApprovalBody, PluginSearchInput, PluginTrustBadge } from './PluginParts' -import { SchemaForm, locText } from './SchemaForm' +import { SchemaForm } from './SchemaForm' // Search only earns its space once the list is long enough to scan. const SEARCH_THRESHOLD = 12 diff --git a/frontend/src/components/SchemaForm.tsx b/frontend/src/components/SchemaForm.tsx index 0cc1f2b..6e9c73f 100644 --- a/frontend/src/components/SchemaForm.tsx +++ b/frontend/src/components/SchemaForm.tsx @@ -5,8 +5,6 @@ import { locText, t } from '../i18n' import { Locale, SettingProperty, SettingsSchema } from '../types' import { NumberField, PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../ui/settings' -export { locText } - interface Props { locale: Locale schema: SettingsSchema diff --git a/frontend/src/i18n/domains/settings.gen.ts b/frontend/src/i18n/domains/settings.gen.ts index aca3c0a..af57493 100644 --- a/frontend/src/i18n/domains/settings.gen.ts +++ b/frontend/src/i18n/domains/settings.gen.ts @@ -411,7 +411,6 @@ export const settingsZh: Record = { "navHasIssue": "这一页有需要修改的项", "nestedVirtDesc": "允许 macOS 运行自己的虚拟机,完全关机后再次启动时生效。", "nestedVirtInvalid": "保存的设置无法读取,虚拟机将按默认 CPU 设置启动。", - "nestedVirtLabel": "嵌套虚拟化", "nestedVirtUnavailable": "当前 Windows 宿主机无法通过 WHPX 提供 VMX。", "networkBridge": "桥接", "networkNAT": "NAT", @@ -954,7 +953,6 @@ export const settingsEn: Record = { "navHasIssue": "This page has settings to fix", "nestedVirtDesc": "Lets macOS run its own virtual machines. Applies on a full restart.", "nestedVirtInvalid": "The saved setting could not be read. The VM starts with the default CPU settings.", - "nestedVirtLabel": "Nested virtualization", "nestedVirtUnavailable": "The Windows host does not provide VMX through WHPX.", "networkBridge": "Bridged", "networkNAT": "NAT", diff --git a/frontend/src/i18n/domains/vm.gen.ts b/frontend/src/i18n/domains/vm.gen.ts index f70fda9..34aef86 100644 --- a/frontend/src/i18n/domains/vm.gen.ts +++ b/frontend/src/i18n/domains/vm.gen.ts @@ -139,6 +139,7 @@ export const vmZh: Record = { "hostDNSStatusPending": "待应用", "hostDNSStatusStale": "配置已过期", "hostDNSStatusStillActive": "macOS 代理未移除", + "nestedVirtLabel": "嵌套虚拟化", "netBridge": "桥接网络", "netCustom": "自定义网络", "netOff": "无网络", @@ -394,6 +395,7 @@ export const vmEn: Record = { "hostDNSStatusPending": "Not applied", "hostDNSStatusStale": "Config outdated", "hostDNSStatusStillActive": "Still active in macOS", + "nestedVirtLabel": "Nested virtualization", "netBridge": "Bridged network", "netCustom": "Custom network", "netOff": "No network", diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index c9f06ae..4f58d38 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -355,7 +355,6 @@ "kernelIrqchipAuto": "Auto", "kernelIrqchipOn": "On", "kernelIrqchipOff": "Off", - "nestedVirtLabel": "Nested virtualization", "nestedVirtDesc": "Lets macOS run its own virtual machines. Applies on a full restart.", "nestedVirtUnavailable": "The Windows host does not provide VMX through WHPX.", "nestedVirtInvalid": "The saved setting could not be read. The VM starts with the default CPU settings.", diff --git a/locales/en-US/vm.json b/locales/en-US/vm.json index 52c0b85..0644a8e 100644 --- a/locales/en-US/vm.json +++ b/locales/en-US/vm.json @@ -269,5 +269,6 @@ "factGuestOS": "System", "fieldDriver": "Driver", "failEndpointOpen": "Could not open connection", - "failEndpointCommand": "Could not get the command" + "failEndpointCommand": "Could not get the command", + "nestedVirtLabel": "Nested virtualization" } diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index 6a1e680..ff0a68f 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -355,7 +355,6 @@ "kernelIrqchipAuto": "自动", "kernelIrqchipOn": "开启", "kernelIrqchipOff": "关闭", - "nestedVirtLabel": "嵌套虚拟化", "nestedVirtDesc": "允许 macOS 运行自己的虚拟机,完全关机后再次启动时生效。", "nestedVirtUnavailable": "当前 Windows 宿主机无法通过 WHPX 提供 VMX。", "nestedVirtInvalid": "保存的设置无法读取,虚拟机将按默认 CPU 设置启动。", diff --git a/locales/zh-CN/vm.json b/locales/zh-CN/vm.json index 8873f4b..33c0c70 100644 --- a/locales/zh-CN/vm.json +++ b/locales/zh-CN/vm.json @@ -269,5 +269,6 @@ "factGuestOS": "系统", "fieldDriver": "驱动", "failEndpointOpen": "无法打开连接", - "failEndpointCommand": "无法获取命令" + "failEndpointCommand": "无法获取命令", + "nestedVirtLabel": "嵌套虚拟化" } From 8beaaa3d6be5e99639f059540098735552b9f8ab 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: Thu, 3 Dec 2026 21:45:13 -0700 Subject: [PATCH 13/22] refactor(frontend): move the VM settings features out of SettingsModal The modal held the state of seven independent features next to the staged settings form. Each feature now has its own file with a hook for its state and the rows that show it. Co-Authored-By: Claude Opus 5.5 --- frontend/src/components/SettingsModal.tsx | 1173 +---------------- frontend/src/components/vmSettings/disk.tsx | 247 ++++ frontend/src/components/vmSettings/keymap.tsx | 86 ++ .../src/components/vmSettings/plugins.tsx | 64 + .../src/components/vmSettings/sharing.tsx | 323 +++++ frontend/src/components/vmSettings/smbios.tsx | 279 ++++ .../components/vmSettings/targetDisplay.tsx | 217 +++ .../src/components/vmSettings/timezone.tsx | 158 +++ 8 files changed, 1424 insertions(+), 1123 deletions(-) create mode 100644 frontend/src/components/vmSettings/disk.tsx create mode 100644 frontend/src/components/vmSettings/keymap.tsx create mode 100644 frontend/src/components/vmSettings/plugins.tsx create mode 100644 frontend/src/components/vmSettings/sharing.tsx create mode 100644 frontend/src/components/vmSettings/smbios.tsx create mode 100644 frontend/src/components/vmSettings/targetDisplay.tsx create mode 100644 frontend/src/components/vmSettings/timezone.tsx diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index 0a6b9de..95e3c63 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -1,6 +1,5 @@ -import * as Alert from '@radix-ui/react-alert-dialog' -import { Check, CircleAlert, Copy, Cpu, Eye, EyeOff, FolderPlus, HardDrive, Info, Keyboard, LucideIcon, Monitor, Shuffle, Trash2, Wrench } from 'lucide-react' -import React, { Suspense, lazy, useEffect, useMemo, useRef, useState } from 'react' +import { CircleAlert, Cpu, HardDrive, Info, Keyboard, LucideIcon, Monitor, Wrench } from 'lucide-react' +import React, { useEffect, useMemo, useRef, useState } from 'react' import '../i18n/domains/settings.gen' import { I18nKey, parseAppError, t } from '../i18n' import { @@ -11,9 +10,6 @@ import { formatBytes, gpuCompatHint, gpuOptionValue, - humanDisplayFallbackName, - humanDisplayMeta, - humanDisplayTitle, memorySafeLimitGB, parseMemoryGB, recommendedCPUs, @@ -27,25 +23,25 @@ import { recommendedMemoryGB, recommendedResolution, shortGPUName, - sortDisplaysForPicker, sshCommand, } from '../lib/format' import { applyKernelIrqchip, findOptimization, kernelIrqchipHint, parseKernelIrqchip } from '../lib/optimizations' import { useVMStats } from '../lib/vmStats' -import { createKeymapRequests, keymapPresetUpdate, keymapUpdate, type KeymapState } from '../lib/vmKeymap' -import { createVMSettingRequests, type VMSettingState } from '../lib/vmSettingRequests' -import { DiskCompactResult, DiskResizeResult, DisplayInfo, DriveShareSettings, HostReport, Locale, Optimization, PluginInfo, SetOpts, SharedFolderInfo, SharedFolderMode, SharedFolderSettings, SMBIOSIdentity, ValidationIssue, VMAffinityStatus, VMDetail, VMStats } from '../types' -import { Button, IconButton } from '../ui/controls' +import { HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMAffinityStatus, VMDetail, VMStats } from '../types' +import { Button } from '../ui/controls' import { Modal } from '../ui/dialog' import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, SetValue, Switch } from '../ui/settings' import type { ToastInput } from '../ui/toast' import { api } from '../wails' -import type { app as WailsApp } from '../../wailsjs/go/models' import { formatAffinitySummary } from './AffinityDialog' import { VMNetworkSettings } from './VMNetworkSettings' -import type { VMKeymapPreset, VMKeymapHostModifier, VMKeymapGuestModifier } from '../types' - -const SchemaForm = lazy(() => import('./SchemaForm').then((m) => ({ default: m.SchemaForm }))) +import { DefenderExclusionRow, DiskMaintenanceRows, useDiskMaintenance } from './vmSettings/disk' +import { KeymapSection, useKeymap } from './vmSettings/keymap' +import { useVMPluginSettings, VMPluginGroup } from './vmSettings/plugins' +import { DriveShareSection, SharedFolderSection, useDriveShares, useSharedFolders, WritableFolderDialog } from './vmSettings/sharing' +import { SMBIOSDialog, SMBIOSSection, useSMBIOS } from './vmSettings/smbios' +import { TargetDisplayRow, useTargetDisplay } from './vmSettings/targetDisplay' +import { GuestTimezoneRow, useGuestTimezone } from './vmSettings/timezone' // VM settings (see docs/design-guidelines.md): edits are staged here and written in // one `reims-ctl set` on Save, because upstream applies every change on the @@ -90,39 +86,12 @@ const FIELDS = Object.keys(FIELD_CAT) as Field[] const LOG_LEVELS = ['error', 'warn', 'info', 'debug', 'trace'] as const const CUSTOM = '__custom' -const PRIMARY_DISPLAY_OPT = '__primary' const RES_RE = /^\s*\d{3,5}\s*[x×]\s*\d{3,5}\s*$/i -type VMTimezoneStatus = Awaited> - -const GUEST_TOOLS_INSTALL_CMD = 'sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command' -const GUEST_TIMEZONE_APPLY_CMD = 'sh /Volumes/REIMSTOOLS/Apply-Timezone.command' - -const GUEST_TIMEZONE_PRESETS: ReadonlyArray<{ value: string; labelKey: I18nKey; detail?: string }> = [ - { value: 'Asia/Shanghai', labelKey: 'guestTimezoneShanghai', detail: 'Asia/Shanghai' }, - { value: 'Asia/Hong_Kong', labelKey: 'guestTimezoneHongKong', detail: 'Asia/Hong_Kong' }, - { value: 'Asia/Taipei', labelKey: 'guestTimezoneTaipei', detail: 'Asia/Taipei' }, - { value: 'Asia/Tokyo', labelKey: 'guestTimezoneTokyo', detail: 'Asia/Tokyo' }, - { value: 'Asia/Seoul', labelKey: 'guestTimezoneSeoul', detail: 'Asia/Seoul' }, - { value: 'Asia/Singapore', labelKey: 'guestTimezoneSingapore', detail: 'Asia/Singapore' }, - { value: 'Europe/London', labelKey: 'guestTimezoneLondon', detail: 'Europe/London' }, - { value: 'Europe/Berlin', labelKey: 'guestTimezoneBerlin', detail: 'Europe/Berlin' }, - { value: 'America/Los_Angeles', labelKey: 'guestTimezoneLosAngeles', detail: 'America/Los_Angeles' }, - { value: 'America/New_York', labelKey: 'guestTimezoneNewYork', detail: 'America/New_York' }, - { value: 'Australia/Sydney', labelKey: 'guestTimezoneSydney', detail: 'Australia/Sydney' }, - { value: 'UTC', labelKey: 'guestTimezoneUTC' }, -] 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) { @@ -194,120 +163,25 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats const [issues, setIssues] = useState([]) const [err, setErr] = useState('') const [form, setForm] = useState(base) - const [resizeInput, setResizeInput] = useState('+64G') - const [diskOpBusy, setDiskOpBusy] = useState<'resize' | 'compact' | 'optimize' | ''>('') - const [resizeResult, setResizeResult] = useState(null) - const [compactResult, setCompactResult] = useState(null) - const [optimizeResult, setOptimizeResult] = useState(null) - const [driveSettings, setDriveSettings] = useState(null) - const [driveBusy, setDriveBusy] = useState(false) - const driveBusyRef = useRef(false) - const activeVMNameRef = useRef(detail.name) - activeVMNameRef.current = detail.name - const [driveErr, setDriveErr] = useState('') - const [folderSettings, setFolderSettings] = useState(null) - const [folderBusy, setFolderBusy] = useState(false) - const folderBusyRef = useRef(false) - const folderOpSeqRef = useRef(0) - const [folderErr, setFolderErr] = useState('') - const [confirmRWFolder, setConfirmRWFolder] = useState(null) const liveStats = useVMStats(driverID, detail.name, running) ?? stats - const gtConnected = liveStats?.guest_tools_connected ?? detail.guest_tools_connected ?? false - const gtAgentVersion = liveStats?.guest_tools_agent_version ?? detail.guest_tools_agent_version ?? 0 + const toolsConnected = liveStats?.guest_tools_connected ?? detail.guest_tools_connected ?? false + const toolsVersion = toolsConnected ? liveStats?.guest_tools_agent_version ?? detail.guest_tools_agent_version ?? 0 : 0 const [affinityStatus, setAffinityStatus] = useState(null) - const [displayStatus, setDisplayStatus] = useState(null) - const [displayBusy, setDisplayBusy] = useState(false) - const [displayErr, setDisplayErr] = useState('') - const displayBusyRef = useRef(false) - const displayReqSeqRef = useRef(0) - const [{ keymap, error: keymapErr, busy: keymapBusy }, setKeymapState] = useState({ keymap: null, error: '', busy: false }) - const [keymapRequests] = useState(() => createKeymapRequests(api, () => activeVMNameRef.current, - (patch) => setKeymapState((state) => ({ ...state, ...patch })))) - const [vmPlugins, setVmPlugins] = useState([]) - const [vmPluginVals, setVmPluginVals] = useState>>({}) - const vmPluginSettingsSaveQueues = useRef(new Map>()) - const vmSettingsKey = `${driverID}:${detail.name}` - const activeVMKeyRef = useRef(vmSettingsKey) - activeVMKeyRef.current = vmSettingsKey - const [{ value: tzStatus, error: tzErr, busy: tzBusy }, setTzState] = useState>({ value: null, error: '', busy: false }) - const [tzRequests] = useState(() => createVMSettingRequests(() => activeVMKeyRef.current, - (patch) => setTzState((state) => ({ ...state, ...patch })))) - 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 drives = useDriveShares(detail.name) + const folders = useSharedFolders(detail.name, locale) + const smbios = useSMBIOS(detail, running) + const keymap = useKeymap(detail.name, running, cat === 'input') + const plugins = useVMPluginSettings(`${driverID}:${detail.name}`, setErr) + const disk = useDiskMaintenance({ locale, driverID, vm: detail.name, running, stats, onError: setErr, onDiskChanged }) + const timezone = useGuestTimezone(driverID, detail.name, running, cat === 'general') + const display = useTargetDisplay({ + locale, driverID, vm: detail.name, running, host, shown: cat === 'display', onToast, + isBlocked: () => busy || timezone.isWriting(), + }) + const { displayBusy, connectedDisplays, activeTargetDisplay, activeTargetDisplayTitle, displayProfile } = display + const tzBusy = timezone.tzBusy const pane = useRef(null) - useEffect(() => { - let live = true - setResizeResult(null) - setCompactResult(null) - setOptimizeResult(null) - Promise.all([api.ListPlugins(), api.GetVMPluginSettings(vmSettingsKey)]) - .then(([list, vals]) => { - if (!live) return - const activeWithVM = (list ?? []).filter((p) => (p.state === 'active' || p.state === 'degraded') && !!p.settings) - setVmPlugins(activeWithVM) - setVmPluginVals((vals ?? {}) as Record>) - }) - .catch((e) => console.warn('[settings] load VM plugin settings failed:', e)) - return () => { live = false } - }, [driverID, detail.name]) - - const updateVMPluginSetting = (pluginID: string, patch: Record) => { - setVmPluginVals((prev) => ({ ...prev, [pluginID]: { ...prev[pluginID], ...patch } })) - const queueKey = JSON.stringify([pluginID, vmSettingsKey]) - const previous = vmPluginSettingsSaveQueues.current.get(queueKey) ?? Promise.resolve() - const save = previous.catch((error) => { - console.warn('[settings] previous plugin save failed:', error) - }).then(() => api.SetPluginSettings(pluginID, vmSettingsKey, patch)) - vmPluginSettingsSaveQueues.current.set(queueKey, save) - void save.catch((e) => setErr(parseAppError(e).summary)).finally(() => { - if (vmPluginSettingsSaveQueues.current.get(queueKey) === save) { - vmPluginSettingsSaveQueues.current.delete(queueKey) - } - }) - } - - const renderVMPluginGroup = (group: string) => { - const matched = vmPlugins.filter((p) => p.settings && (p.settings['x-group'] === group || Object.values(p.settings.properties ?? {}).some((prop) => prop['x-group'] === group))) - if (matched.length === 0) return null - return ( - - {matched.map((p) => ( - updateVMPluginSetting(p.id, patch)} - /> - ))} - - ) - } - - const connectedDisplays = useMemo( - () => sortDisplaysForPicker(displayStatus?.displays ?? host.displays ?? []), - [displayStatus, host.displays], - ) - const activeTargetDisplay = displayStatus - ? connectedDisplays.find((d) => d.name === displayStatus.effective_display) - : host.primary_display - const displayProfile = useMemo(() => displayStatus ? { - ...host, - primary_display: activeTargetDisplay, - display_presets: displayStatus.display_presets, - fullscreen_hidpi: displayStatus.fullscreen_hidpi, - hidpi_advice: displayStatus.hidpi_advice, - recommended_resolution: undefined, - } : host, [host, displayStatus, activeTargetDisplay]) const presets = windowDisplayPresets(displayProfile, fixedModeSupported) const fsPresets = fullscreenDisplayPresets(displayProfile) const activePresets: FullscreenDisplayPreset[] = form.borderless ? fsPresets : presets @@ -366,25 +240,6 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats el?.scrollIntoView({ block: 'nearest', behavior: 'smooth' }) }, [issues, cat]) - useEffect(() => { - let active = true - folderOpSeqRef.current += 1 - folderBusyRef.current = false - setFolderBusy(false) - setDriveSettings(null) - setDriveErr('') - setFolderSettings(null) - setFolderErr('') - setConfirmRWFolder(null) - api.GetVMDriveShareSettings(detail.name) - .then((settings) => { if (active) setDriveSettings(settings) }) - .catch((e) => { if (active) setDriveErr(parseAppError(e).summary) }) - api.GetVMSharedFolderSettings(detail.name) - .then((settings) => { if (active) setFolderSettings(settings) }) - .catch((e) => { if (active) setFolderErr(formatFolderError(e)) }) - return () => { active = false } - }, [detail.name]) - useEffect(() => { let active = true api.GetVMAffinity(driverID, detail.name) @@ -393,263 +248,6 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats return () => { active = false } }, [detail.name, running, affinityVersion]) - const hostDisplaysSig = (host.displays ?? []) - .map((d) => `${d.name ?? ''}:${d.friendly_name ?? ''}:${d.width}x${d.height}@${d.scale_pct}:${d.refresh_hz ?? 0}:${d.work_width ?? 0}x${d.work_height ?? 0}:${d.primary ? 1 : 0}`) - .join('|') - - useEffect(() => { - displayReqSeqRef.current += 1 - displayBusyRef.current = false - setDisplayStatus(null) - setDisplayBusy(false) - setDisplayErr('') - }, [driverID, detail.name]) - - useEffect(() => { - let active = true - const reqSeq = displayReqSeqRef.current - if (displayBusyRef.current) return () => { active = false } - api.GetVMDisplay(driverID, detail.name) - .then((st) => { - if (active && displayReqSeqRef.current === reqSeq) { - setDisplayStatus(st) - setDisplayErr('') - } - }) - .catch((e) => { - if (active && displayReqSeqRef.current === reqSeq) { - setDisplayErr(parseAppError(e).summary) - } - }) - return () => { active = false } - }, [driverID, detail.name, running, hostDisplaysSig, cat === 'display']) - - useEffect(() => { - setTzState({ value: null, error: '', busy: tzRequests.isWriting(vmSettingsKey) }) - }, [vmSettingsKey, tzRequests]) - - useEffect(() => { - if (cat !== 'general') return - const { refresh, stop } = tzRequests.watch(vmSettingsKey, () => api.GetVMTimezone(driverID, detail.name)) - void refresh() - const timer = window.setInterval(refresh, 3000) - return () => { stop(); window.clearInterval(timer) } - }, [cat, driverID, detail.name, running, vmSettingsKey, tzRequests]) - - const updateTimezone = async (nextSetting: string) => { - if (busy || displayBusyRef.current || !tzStatus) return - const currentSetting = tzStatus.mode === 'off' ? 'off' : tzStatus.mode === 'custom' ? tzStatus.timezone : 'host' - if (nextSetting === currentSetting) return - if (await tzRequests.write(vmSettingsKey, () => api.SetVMTimezone(driverID, detail.name, nextSetting))) { - onToast({ kind: 'ok', title: tr('guestTimezoneSaved') }) - } - } - - 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('') - } - } - - useEffect(() => { - setKeymapState(keymapRequests.initial(detail.name)) - }, [detail.name, keymapRequests]) - - useEffect(() => { - if (cat !== 'input') return - const { refresh, stop } = keymapRequests.watch(detail.name) - void refresh() - const timer = window.setInterval(refresh, 3000) - return () => { stop(); window.clearInterval(timer) } - }, [cat, detail.name, running, keymapRequests]) - - const updateDriveShares = async (enabled: boolean, selected: string[]) => { - if (driveBusyRef.current || !driveSettings) return - driveBusyRef.current = true - const vmName = detail.name - setDriveBusy(true) - setDriveErr('') - try { - const next = await api.SetVMDriveShareSettings(vmName, enabled, selected) - if (activeVMNameRef.current === vmName) setDriveSettings(next) - } catch (e) { - if (activeVMNameRef.current === vmName) setDriveErr(parseAppError(e).summary) - } finally { - driveBusyRef.current = false - setDriveBusy(false) - } - } - - const selectedDrives = () => (driveSettings?.drives ?? []).filter((d) => d.selected).map((d) => d.drive) - - const formatFolderIssue = (issue?: string) => { - switch (issue) { - case 'missing': return tr('folderShareIssueMissing') - case 'volume_mismatch': return tr('folderShareIssueVolumeMismatch') - case 'path_changed': return tr('folderShareIssuePathChanged') - case 'overlap': return tr('folderShareIssueOverlap') - case 'blocked': return tr('folderShareIssueBlocked') - case 'not_found': return tr('folderShareIssueNotFound') - case 'invalid_mode': return tr('folderShareIssueInvalidMode') - case 'corrupt_config': return tr('folderShareIssueCorruptConfig') - default: return '' - } - } - - const formatFolderError = (e: unknown) => { - const summary = parseAppError(e).summary - const match = summary.match(/shared folder:\s*(missing|volume_mismatch|path_changed|overlap|blocked|not_found|invalid_mode|corrupt_config)\b/i) - if (match) return formatFolderIssue(match[1].toLowerCase()) - return summary - } - - const runFolderOp = async (op: (vmName: string) => Promise) => { - if (folderBusyRef.current || !folderSettings) return - const opSeq = ++folderOpSeqRef.current - folderBusyRef.current = true - const vmName = detail.name - setFolderBusy(true) - setFolderErr('') - try { - const next = await op(vmName) - if (next && activeVMNameRef.current === vmName && folderOpSeqRef.current === opSeq) { - setFolderSettings(next) - } - } catch (e) { - if (activeVMNameRef.current === vmName && folderOpSeqRef.current === opSeq) { - setFolderErr(formatFolderError(e)) - } - } finally { - if (folderOpSeqRef.current === opSeq) { - folderBusyRef.current = false - setFolderBusy(false) - } - } - } - - const handleAddFolder = () => runFolderOp(async (vmName) => { - const picked = await api.PickDirectory(tr('folderSharePickTitle')) - if (!picked || activeVMNameRef.current !== vmName) return null - return api.AddVMSharedFolder(vmName, picked) - }) - - const updateFolderMode = (folderID: string, mode: SharedFolderMode) => - runFolderOp((vmName) => api.SetVMSharedFolderMode(vmName, folderID, mode)) - - const handleRemoveFolder = (folderID: string) => - runFolderOp((vmName) => api.RemoveVMSharedFolder(vmName, folderID)) - - const numberedDisplay = (n: number) => tr('targetDisplayNumbered', { n }) - - const displayErrorToast = (title: string, error: unknown) => { - const parsed = parseAppError(error) - onToast({ - kind: 'error', - title, - description: parsed.summary, - errorCode: parsed.code, - rawDetail: parsed.rawDetail, - detailsLabel: tr('errRawDetailsToggle'), - copyDetailsLabel: tr('errCopyDetails'), - }) - } - - const handleTargetDisplayChange = async (nextValue: string) => { - if (busy || displayBusyRef.current || tzRequests.isWriting(vmSettingsKey) || displayStatus === null) return - const nextTarget = nextValue === PRIMARY_DISPLAY_OPT ? '' : nextValue - const currentTarget = displayStatus.target_display ?? '' - if (nextTarget.toLowerCase() === currentTarget.toLowerCase()) return - - const vmName = detail.name - const opSeq = ++displayReqSeqRef.current - displayBusyRef.current = true - setDisplayBusy(true) - setDisplayErr('') - try { - const next = await api.SetVMDisplay(driverID, vmName, nextTarget) - if (activeVMNameRef.current !== vmName || displayReqSeqRef.current !== opSeq) return - setDisplayStatus(next) - const chosenLabel = displayOptions.find((o) => o.value === nextValue)?.label - ?? humanDisplayFallbackName(next.target_display, numberedDisplay) - if (next.move_error) { - displayErrorToast(tr('targetDisplayToastSaved', { display: chosenLabel }), next.move_error) - } else { - onToast({ - kind: 'ok', - title: next.applied_live - ? tr('targetDisplayToastMoved', { display: chosenLabel }) - : tr('targetDisplayToastSaved', { display: chosenLabel }), - }) - } - } catch (e) { - if (activeVMNameRef.current !== vmName || displayReqSeqRef.current !== opSeq) return - displayErrorToast(tr('targetDisplaySaveFailed'), e) - } finally { - if (displayReqSeqRef.current === opSeq) { - displayBusyRef.current = false - setDisplayBusy(false) - } - } - } - // Windows-wide, not staged with Save: one UAC prompt opens Windows' own // Performance Options, and the new choice shows after the host refresh. const [openingSched, setOpeningSched] = useState(false) @@ -666,7 +264,7 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats } const handleSave = async () => { - if (busy || displayBusyRef.current || tzRequests.isWriting(vmSettingsKey) || changed.length === 0 || localBlock) return + if (busy || display.isBusy() || timezone.isWriting() || changed.length === 0 || localBlock) return setErr('') setIssues([]) setBusy(true) @@ -714,53 +312,6 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats // ── Pages ──────────────────────────────────────────────── - const detectedHostTZ = tzStatus?.host_timezone || host.timezone || '' - const tzSelectedValue = tzStatus?.mode === 'custom' ? tzStatus.timezone : tzStatus?.mode - const tzOptions = [ - { value: 'host', label: tr('guestTimezoneHost'), detail: detectedHostTZ || undefined }, - ...GUEST_TIMEZONE_PRESETS.map((p) => ({ - value: p.value, - label: tr(p.labelKey), - detail: p.detail, - })), - ...(tzStatus?.mode === 'custom' && tzStatus.timezone && !GUEST_TIMEZONE_PRESETS.some((p) => p.value === tzStatus.timezone) - ? [{ value: tzStatus.timezone, label: tzStatus.timezone }] - : []), - { value: 'off', label: tr('guestTimezoneOff') }, - ] - let tzDesc: React.ReactNode = tr('guestTimezoneDesc') - let tzCommand = '' - if (tzStatus) { - const tzEffective = tzStatus.effective_timezone - if (tzStatus.mode === 'off') { - tzDesc = tr('guestTimezoneOffDesc') - } else if (detail.guest_tools_disabled) { - tzDesc = {tr('gtStatusOffTip')} - } else if (!tzEffective) { - tzDesc = {tr('guestTimezoneHostUnknown')} - } else if (tzStatus.running && tzStatus.guest_connected) { - const tzFailure = tzStatus.timezone_error - ? {tr('guestTimezoneApplyFailed', { tz: tzEffective })} - : null - if (tzStatus.guest_agent_version < tzStatus.required_agent_version) { - tzDesc = {tr(detail.guest_tools_attached ? 'guestTimezoneUpgradeHint' : 'guestTimezoneUpgradeAttachHint', { version: tzStatus.required_agent_version })} - if (detail.guest_tools_attached) tzCommand = GUEST_TOOLS_INSTALL_CMD - } else if (!tzStatus.helper_ready) { - const hint = tr(detail.guest_tools_attached ? 'guestTimezoneApplyHint' : 'guestTimezoneApplyAttachHint') - tzDesc = tzFailure ?
{tzFailure}{hint}
: hint - if (detail.guest_tools_attached) tzCommand = GUEST_TIMEZONE_APPLY_CMD - } else if (tzFailure) { - tzDesc = tzFailure - } else if (tzStatus.guest_applied === tzEffective) { - tzDesc = - } else { - tzDesc = tr('guestTimezoneSyncing', { tz: tzEffective }) - } - } else if (detail.guest_tools_attached) { - tzCommand = GUEST_TOOLS_INSTALL_CMD - } - } - const general = ( <> @@ -782,28 +333,15 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats /> } /> - - } - block={tzCommand ? ( -
- {tzCommand} - {onCopy && ( - } onClick={() => onCopy(tzCommand)} /> - )} -
- ) : undefined} + busy || display.isBusy()} + onToast={onToast} + onCopy={onCopy} />
@@ -813,60 +351,8 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats - {detail.has_opencore && ( - - - )} - {renderVMPluginGroup('collaboration')} + {detail.has_opencore && } + ) @@ -1013,60 +499,11 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats } set({ borderless }) } - const displayOptions = useMemo(() => { - const opts: Array<{ value: string; label: string; detail?: string }> = [ - { - value: PRIMARY_DISPLAY_OPT, - label: tr('targetDisplayPrimaryDefault'), - }, - ...connectedDisplays - .filter((d): d is DisplayInfo & { name: string } => Boolean(d.name?.trim())) - .map((d, idx) => ({ - value: d.name, - label: humanDisplayTitle(d, idx + 1, numberedDisplay), - detail: humanDisplayMeta(d, d.primary ? tr('hostDisplayPrimary') : undefined), - })), - ] - const savedTarget = displayStatus?.target_display?.trim() - if (savedTarget && displayStatus?.fallback_to_primary) { - if (!opts.some((o) => o.value.toLowerCase() === savedTarget.toLowerCase())) { - opts.push({ - value: savedTarget, - label: humanDisplayFallbackName(savedTarget, numberedDisplay), - detail: tr('targetDisplayDisconnectedOption'), - }) - } - } - return opts - }, [connectedDisplays, displayStatus?.fallback_to_primary, displayStatus?.target_display, locale]) - const selectedDisplayValue = useMemo(() => { - const saved = displayStatus?.target_display?.trim() - if (!saved) return PRIMARY_DISPLAY_OPT - return displayOptions.find((o) => o.value.toLowerCase() === saved.toLowerCase())?.value ?? saved - }, [displayOptions, displayStatus?.target_display]) - const targetDisplayDesc = displayStatus?.fallback_to_primary && displayStatus.target_display - ? ( - - {tr('targetDisplayFallbackHint', { - name: humanDisplayFallbackName(displayStatus.target_display, numberedDisplay), - })} - - ) - : connectedDisplays.length === 0 - ? tr('targetDisplayNoneHint') - : connectedDisplays.length === 1 - ? tr('targetDisplaySingleHint') - : tr(running ? 'targetDisplayRunningHint' : 'targetDisplayStoppedHint') - const activeTargetDisplayTitle = useMemo(() => { - if (!activeTargetDisplay) return '' - const idx = connectedDisplays.findIndex((d) => d === activeTargetDisplay || (d.name && activeTargetDisplay.name && d.name.toLowerCase() === activeTargetDisplay.name.toLowerCase())) - return humanDisplayTitle(activeTargetDisplay, idx >= 0 ? idx + 1 : 1, numberedDisplay) - }, [activeTargetDisplay, connectedDisplays, locale]) const resArt = (r: string) => { const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(r) return m ? : } - const display = ( + const displayPage = ( <> = ({ locale, detail, driverID, stats /> - void handleTargetDisplayChange(v)} - options={displayOptions} - /> - } - /> + = ({ locale, detail, driverID, stats ) - const handleResizeDisk = async () => { - if (running || diskOpBusy || !resizeInput.trim()) return - const vmName = detail.name - setErr('') - setDiskOpBusy('resize') - try { - const res = await api.ResizeVMDisk(driverID, vmName, resizeInput.trim()) - if (activeVMNameRef.current === vmName) { - setResizeResult(res) - } - onDiskChanged?.() - } catch (e) { - if (activeVMNameRef.current === vmName) { - setErr(parseAppError(e).summary) - } - } finally { - setDiskOpBusy('') - } - } - - const isQcow2 = !stats?.disk_format || stats.disk_format === 'qcow2' - const diskRewriteBaseReason = running ? tr('stopBeforeDiskOp') - : (stats?.disk_snapshot_count ?? 0) > 0 ? tr('diskRewriteSnapshots') - : (stats?.disk_backing_depth ?? 0) > 0 ? tr('diskRewriteOverlay') - : !isQcow2 ? tr('diskCompactQcow2Only') - : undefined - const compactRowReason = diskRewriteBaseReason ?? (diskOpBusy && diskOpBusy !== 'compact' ? tr('diskRewriteBusy') : undefined) - const optimizeRowReason = diskRewriteBaseReason ?? (diskOpBusy && diskOpBusy !== 'optimize' ? tr('diskRewriteBusy') : undefined) - - const handleCompactDisk = async (optimize: boolean) => { - if (diskRewriteBaseReason || diskOpBusy) return - const vmName = detail.name - setErr('') - setDiskOpBusy(optimize ? 'optimize' : 'compact') - try { - if (optimize) { - const res = await api.OptimizeVMDisk(driverID, vmName) - if (activeVMNameRef.current === vmName) { - setOptimizeResult(res) - setCompactResult(null) - } - } else { - const res = await api.CompactVMDisk(driverID, vmName) - if (activeVMNameRef.current === vmName) { - setCompactResult(res) - } - } - onDiskChanged?.() - } catch (e) { - if (activeVMNameRef.current === vmName) { - setErr(parseAppError(e).summary) - } - } finally { - setDiskOpBusy('') - } - } - - const handleDefender = async (copy: boolean) => { - setErr('') - try { - if (copy) { - const command = await api.GetDefenderExclusionCommand() - if (command) onCopy?.(command) - } else { - await api.OpenWindowsSecurityExclusions() - } - } catch (e) { - setErr(parseAppError(e).summary) - } - } - - const extendedL2 = stats?.disk_extended_l2 || optimizeResult?.extended_l2_enabled const diskControllerDesc = detail.has_installer ? tr('diskControllerInstallHint') : form.disk_controller === 'virtio' @@ -1329,243 +681,11 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats /> } /> - -
-
- {['+32G', '+64G', '+128G', '256G', '512G'].map((v) => ( - - ))} -
-
-
- setResizeInput(e.target.value)} - placeholder="+64G / 256G" - /> - -
- {resizeResult && ( -
-
{tr('diskResizeDone', { size: formatBytes(resizeResult.new_virtual_bytes, locale) })}
-
- {resizeResult.guest_expand_cmd} - {onCopy && ( - } onClick={() => onCopy(resizeResult.guest_expand_cmd)} /> - )} -
-
- )} - - } - /> - 0 - ? tr('diskCompactDone', { - before: formatBytes(compactResult.before_bytes, locale), - after: formatBytes(compactResult.after_bytes, locale), - reclaimed: formatBytes(compactResult.reclaimed_bytes, locale), - }) - : tr('diskCompactNoGain') - : tr('diskCompactDesc')} - disabled={!!compactRowReason} - reason={compactRowReason} - control={ - - } - /> - handleCompactDisk(true)}> - {tr('diskOptimizeAction')} - - )} - /> - {host.defender_realtime_active && ( - - - {onCopy && } - - } - /> - )} -
- - void updateDriveShares(enabled, selectedDrives())} - /> - } - /> - {detail.guest_tools_disabled &&
{tr('gtStatusOffTip')}
} - {driveErr &&
{driveErr}
} - {driveSettings?.enabled && selectedDrives().length > 0 && - gtConnected && - gtAgentVersion > 0 && - gtAgentVersion < driveSettings.required_agent_version && ( -
{tr('driveShareNeedsTools', { version: driveSettings.required_agent_version })}
- )} - {/* Drives are only worth choosing once sharing is on. */} - {driveSettings?.enabled && driveSettings.drives.map((drive) => { - const title = `Windows (${drive.drive}:)` - return ( - {tr('driveShareSystem')} : undefined} - disabled={driveBusy || !!detail.guest_tools_disabled} - control={ - { - const next = selectedDrives().filter((letter) => letter !== drive.drive) - if (enabled) next.push(drive.drive) - void updateDriveShares(driveSettings?.enabled ?? false, next) - }} - /> - } - /> - ) - })} - {driveSettings && driveSettings.drives.length === 0 && ( - - )} -
- - + + 0} onBusy={setBusy} onSaved={onSaved} /> = ({ locale, detail, driverID, stats control={ set({ capture })} />} /> - - {keymapErr &&
{keymapErr}
} - {keymap && <> - label={tr('keymapPresetTitle')} value={keymap.preset} - options={[{ value: 'off', label: tr('keymapPresetOff') }, { value: 'win_to_cmd', label: tr('keymapPresetWinToCmd') }, { value: 'swap_alt_win', label: tr('keymapPresetSwapAltWin') }, { value: 'custom', label: tr('keymapPresetCustom') }]} - onChange={(preset) => { - const request = keymapPresetUpdate(keymap, preset) - if (request) void keymapRequests.write(detail.name, request) - }} />} - /> - { void keymapRequests.write(detail.name, keymapUpdate(keymap, { capture_host_shortcuts })) }} />} - /> - {keymap.preset === 'custom' && ([ - ['lwin', 'keymapHostLwin'], - ['rwin', 'keymapHostRwin'], - ['lalt', 'keymapHostLalt'], - ['ralt', 'keymapHostRalt'], - ['lctrl', 'keymapHostLctrl'], - ['rctrl', 'keymapHostRctrl'], - ['capslock', 'keymapHostCapslock'], - ] as const satisfies readonly (readonly [VMKeymapHostModifier, I18nKey])[]).map(([modifier, label]) => ( - label={tr(label)} value={keymap.bindings[modifier] ?? 'default'} - options={[ - { value: 'default', label: tr('keymapGuestDefault') }, - { value: 'lcmd', label: tr('keymapGuestLcmd') }, - { value: 'rcmd', label: tr('keymapGuestRcmd') }, - { value: 'lopt', label: tr('keymapGuestLopt') }, - { value: 'ropt', label: tr('keymapGuestRopt') }, - { value: 'lctrl', label: tr('keymapGuestLctrl') }, - { value: 'rctrl', label: tr('keymapGuestRctrl') }, - { value: 'esc', label: tr('keymapGuestEsc') }, - { value: 'disabled', label: tr('keymapGuestDisabled') }, - ]} - onChange={(target) => { void keymapRequests.write(detail.name, keymapUpdate(keymap, { bindings: { [modifier]: target } })) }} />} - /> - ))} - } -
- {renderVMPluginGroup('keyboard')} + + = ({ locale, detail, driverID, stats ) - const pages: Record = { general, compute, display, storage, input, advanced } + const pages: Record = { general, compute, display: displayPage, storage, input, advanced } return ( <> @@ -1765,7 +836,7 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats title={tr('settingsTitle', { name: detail.name })} subtitle={`${tr(running ? 'state_running' : 'state_stopped')} · ${tr('appliesNextStart')}`} closeLabel={tr('close')} - dismissable={!busy && !displayBusy && !tzBusy && !confirmRWFolder} + dismissable={!busy && !displayBusy && !tzBusy && !folders.confirmRWFolder} onClose={onClose} >
@@ -1820,153 +891,9 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats
- {smbiosOpen && ( - setSmbiosOpen(false)} - > -
-
- {tr('smbiosWarning')} -
-
- - {onCopy && smbiosDraft?.serial && ( - - )} -
- - - - {smbios?.rom && ( -
- {tr('smbiosROM')}: {smbios.rom} -
- )} -
{tr('smbiosCheckHint')}
- {smbiosModalErr &&
{smbiosModalErr}
} -
-
- - - - - -
-
- )} + {smbios.smbiosOpen && } - {confirmRWFolder && ( - { if (!open) setConfirmRWFolder(null) }}> - - - -
- {tr('folderShareConfirmRWTitle')} - - {tr('folderShareConfirmRWDesc', { name: confirmRWFolder.name, path: confirmRWFolder.host_path })} - -
-
- - - - - - -
-
-
-
- )} + ) } diff --git a/frontend/src/components/vmSettings/disk.tsx b/frontend/src/components/vmSettings/disk.tsx new file mode 100644 index 0000000..66d232a --- /dev/null +++ b/frontend/src/components/vmSettings/disk.tsx @@ -0,0 +1,247 @@ +import { Copy } from 'lucide-react' +import React, { useEffect, useRef, useState } from 'react' +import { I18nKey, parseAppError, t } from '../../i18n' +import { formatBytes } from '../../lib/format' +import { DiskCompactResult, DiskResizeResult, Locale, VMStats } from '../../types' +import { Button, IconButton } from '../../ui/controls' +import { SetRow } from '../../ui/settings' +import { api } from '../../wails' + +interface DiskOptions { + locale: Locale + driverID: string + vm: string + running: boolean + stats?: VMStats | null + onError: (message: string) => void + onDiskChanged?: () => void +} + +/** Resizing, compacting and optimizing the VM's disk, one at a time. */ +export function useDiskMaintenance({ locale, driverID, vm, running, stats, onError, onDiskChanged }: DiskOptions) { + const tr = (k: I18nKey, v?: Record) => t(locale, k, v) + const activeVMNameRef = useRef(vm) + activeVMNameRef.current = vm + const [resizeInput, setResizeInput] = useState('+64G') + const [diskOpBusy, setDiskOpBusy] = useState<'resize' | 'compact' | 'optimize' | ''>('') + const [resizeResult, setResizeResult] = useState(null) + const [compactResult, setCompactResult] = useState(null) + const [optimizeResult, setOptimizeResult] = useState(null) + + useEffect(() => { + setResizeResult(null) + setCompactResult(null) + setOptimizeResult(null) + }, [driverID, vm]) + + const handleResizeDisk = async () => { + if (running || diskOpBusy || !resizeInput.trim()) return + onError('') + setDiskOpBusy('resize') + try { + const res = await api.ResizeVMDisk(driverID, vm, resizeInput.trim()) + if (activeVMNameRef.current === vm) { + setResizeResult(res) + } + onDiskChanged?.() + } catch (e) { + if (activeVMNameRef.current === vm) { + onError(parseAppError(e).summary) + } + } finally { + setDiskOpBusy('') + } + } + + const isQcow2 = !stats?.disk_format || stats.disk_format === 'qcow2' + const diskRewriteBaseReason = running ? tr('stopBeforeDiskOp') + : (stats?.disk_snapshot_count ?? 0) > 0 ? tr('diskRewriteSnapshots') + : (stats?.disk_backing_depth ?? 0) > 0 ? tr('diskRewriteOverlay') + : !isQcow2 ? tr('diskCompactQcow2Only') + : undefined + const compactRowReason = diskRewriteBaseReason ?? (diskOpBusy && diskOpBusy !== 'compact' ? tr('diskRewriteBusy') : undefined) + const optimizeRowReason = diskRewriteBaseReason ?? (diskOpBusy && diskOpBusy !== 'optimize' ? tr('diskRewriteBusy') : undefined) + + const handleCompactDisk = async (optimize: boolean) => { + if (diskRewriteBaseReason || diskOpBusy) return + onError('') + setDiskOpBusy(optimize ? 'optimize' : 'compact') + try { + if (optimize) { + const res = await api.OptimizeVMDisk(driverID, vm) + if (activeVMNameRef.current === vm) { + setOptimizeResult(res) + setCompactResult(null) + } + } else { + const res = await api.CompactVMDisk(driverID, vm) + if (activeVMNameRef.current === vm) { + setCompactResult(res) + } + } + onDiskChanged?.() + } catch (e) { + if (activeVMNameRef.current === vm) { + onError(parseAppError(e).summary) + } + } finally { + setDiskOpBusy('') + } + } + + const extendedL2 = stats?.disk_extended_l2 || optimizeResult?.extended_l2_enabled + + return { + resizeInput, setResizeInput, diskOpBusy, resizeResult, compactResult, optimizeResult, extendedL2, + compactRowReason, optimizeRowReason, handleResizeDisk, handleCompactDisk, + } +} + +interface RowsProps { + locale: Locale + running: boolean + state: ReturnType + onCopy?: (text: string) => void +} + +export const DiskMaintenanceRows: React.FC = ({ locale, running, state, onCopy }) => { + const tr = (k: I18nKey, v?: Record) => t(locale, k, v) + const { resizeInput, setResizeInput, diskOpBusy, resizeResult, compactResult, optimizeResult, extendedL2, compactRowReason, optimizeRowReason, handleResizeDisk, handleCompactDisk } = state + return ( + <> + +
+
+ {['+32G', '+64G', '+128G', '256G', '512G'].map((v) => ( + + ))} +
+
+
+ setResizeInput(e.target.value)} + placeholder="+64G / 256G" + /> + +
+ {resizeResult && ( +
+
{tr('diskResizeDone', { size: formatBytes(resizeResult.new_virtual_bytes, locale) })}
+
+ {resizeResult.guest_expand_cmd} + {onCopy && ( + } onClick={() => onCopy(resizeResult.guest_expand_cmd)} /> + )} +
+
+ )} + + } + /> + 0 + ? tr('diskCompactDone', { + before: formatBytes(compactResult.before_bytes, locale), + after: formatBytes(compactResult.after_bytes, locale), + reclaimed: formatBytes(compactResult.reclaimed_bytes, locale), + }) + : tr('diskCompactNoGain') + : tr('diskCompactDesc')} + disabled={!!compactRowReason} + reason={compactRowReason} + control={ + + } + /> + handleCompactDisk(true)}> + {tr('diskOptimizeAction')} + + )} + /> + + ) +} + +interface DefenderProps { + locale: Locale + dataRoot: string + onCopy?: (text: string) => void + onError: (message: string) => void +} + +export const DefenderExclusionRow: React.FC = ({ locale, dataRoot, onCopy, onError }) => { + const tr = (k: I18nKey, v?: Record) => t(locale, k, v) + const handleDefender = async (copy: boolean) => { + onError('') + try { + if (copy) { + const command = await api.GetDefenderExclusionCommand() + if (command) onCopy?.(command) + } else { + await api.OpenWindowsSecurityExclusions() + } + } catch (e) { + onError(parseAppError(e).summary) + } + } + return ( + + + {onCopy && } + + } + /> + ) +} diff --git a/frontend/src/components/vmSettings/keymap.tsx b/frontend/src/components/vmSettings/keymap.tsx new file mode 100644 index 0000000..6e68d2f --- /dev/null +++ b/frontend/src/components/vmSettings/keymap.tsx @@ -0,0 +1,86 @@ +import React, { useEffect, useRef, useState } from 'react' +import { I18nKey, t } from '../../i18n' +import { createKeymapRequests, keymapPresetUpdate, keymapUpdate, type KeymapState } from '../../lib/vmKeymap' +import { Locale, VMKeymapGuestModifier, VMKeymapHostModifier, VMKeymapPreset } from '../../types' +import { PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../../ui/settings' +import { api } from '../../wails' + +/** The VM's modifier key mapping, refreshed while shown. */ +export function useKeymap(vm: string, running: boolean, shown: boolean) { + const activeVMNameRef = useRef(vm) + activeVMNameRef.current = vm + const [{ keymap, error: keymapErr, busy: keymapBusy }, setKeymapState] = useState({ keymap: null, error: '', busy: false }) + const [keymapRequests] = useState(() => createKeymapRequests(api, () => activeVMNameRef.current, + (patch) => setKeymapState((state) => ({ ...state, ...patch })))) + + useEffect(() => { + setKeymapState(keymapRequests.initial(vm)) + }, [vm, keymapRequests]) + + useEffect(() => { + if (!shown) return + const { refresh, stop } = keymapRequests.watch(vm) + void refresh() + const timer = window.setInterval(refresh, 3000) + return () => { stop(); window.clearInterval(timer) } + }, [shown, vm, running, keymapRequests]) + + return { keymap, keymapErr, keymapBusy, write: keymapRequests.write } +} + +export const KeymapSection: React.FC<{ locale: Locale; vm: string; state: ReturnType }> = ({ locale, vm, state }) => { + const tr = (k: I18nKey, v?: Record) => t(locale, k, v) + const { keymap, keymapErr, keymapBusy, write } = state + return ( + + {keymapErr &&
{keymapErr}
} + {keymap && <> + label={tr('keymapPresetTitle')} value={keymap.preset} + options={[{ value: 'off', label: tr('keymapPresetOff') }, { value: 'win_to_cmd', label: tr('keymapPresetWinToCmd') }, { value: 'swap_alt_win', label: tr('keymapPresetSwapAltWin') }, { value: 'custom', label: tr('keymapPresetCustom') }]} + onChange={(preset) => { + const request = keymapPresetUpdate(keymap, preset) + if (request) void write(vm, request) + }} />} + /> + { void write(vm, keymapUpdate(keymap, { capture_host_shortcuts })) }} />} + /> + {keymap.preset === 'custom' && ([ + ['lwin', 'keymapHostLwin'], + ['rwin', 'keymapHostRwin'], + ['lalt', 'keymapHostLalt'], + ['ralt', 'keymapHostRalt'], + ['lctrl', 'keymapHostLctrl'], + ['rctrl', 'keymapHostRctrl'], + ['capslock', 'keymapHostCapslock'], + ] as const satisfies readonly (readonly [VMKeymapHostModifier, I18nKey])[]).map(([modifier, label]) => ( + label={tr(label)} value={keymap.bindings[modifier] ?? 'default'} + options={[ + { value: 'default', label: tr('keymapGuestDefault') }, + { value: 'lcmd', label: tr('keymapGuestLcmd') }, + { value: 'rcmd', label: tr('keymapGuestRcmd') }, + { value: 'lopt', label: tr('keymapGuestLopt') }, + { value: 'ropt', label: tr('keymapGuestRopt') }, + { value: 'lctrl', label: tr('keymapGuestLctrl') }, + { value: 'rctrl', label: tr('keymapGuestRctrl') }, + { value: 'esc', label: tr('keymapGuestEsc') }, + { value: 'disabled', label: tr('keymapGuestDisabled') }, + ]} + onChange={(target) => { void write(vm, keymapUpdate(keymap, { bindings: { [modifier]: target } })) }} />} + /> + ))} + } +
+ ) +} diff --git a/frontend/src/components/vmSettings/plugins.tsx b/frontend/src/components/vmSettings/plugins.tsx new file mode 100644 index 0000000..68c2447 --- /dev/null +++ b/frontend/src/components/vmSettings/plugins.tsx @@ -0,0 +1,64 @@ +import React, { Suspense, lazy, useEffect, useRef, useState } from 'react' +import { parseAppError } from '../../i18n' +import { Locale, PluginInfo } from '../../types' +import { api } from '../../wails' + +const SchemaForm = lazy(() => import('../SchemaForm').then((m) => ({ default: m.SchemaForm }))) + +/** Per-VM settings of the active plugins. Changes save at once, in order. */ +export function useVMPluginSettings(vmKey: string, onError: (message: string) => void) { + const [vmPlugins, setVmPlugins] = useState([]) + const [vmPluginVals, setVmPluginVals] = useState>>({}) + const vmPluginSettingsSaveQueues = useRef(new Map>()) + + useEffect(() => { + let live = true + Promise.all([api.ListPlugins(), api.GetVMPluginSettings(vmKey)]) + .then(([list, vals]) => { + if (!live) return + const activeWithVM = (list ?? []).filter((p) => (p.state === 'active' || p.state === 'degraded') && !!p.settings) + setVmPlugins(activeWithVM) + setVmPluginVals((vals ?? {}) as Record>) + }) + .catch((e) => console.warn('[settings] load VM plugin settings failed:', e)) + return () => { live = false } + }, [vmKey]) + + const updateVMPluginSetting = (pluginID: string, patch: Record) => { + setVmPluginVals((prev) => ({ ...prev, [pluginID]: { ...prev[pluginID], ...patch } })) + const queueKey = JSON.stringify([pluginID, vmKey]) + const previous = vmPluginSettingsSaveQueues.current.get(queueKey) ?? Promise.resolve() + const save = previous.catch((error) => { + console.warn('[settings] previous plugin save failed:', error) + }).then(() => api.SetPluginSettings(pluginID, vmKey, patch)) + vmPluginSettingsSaveQueues.current.set(queueKey, save) + void save.catch((e) => onError(parseAppError(e).summary)).finally(() => { + if (vmPluginSettingsSaveQueues.current.get(queueKey) === save) { + vmPluginSettingsSaveQueues.current.delete(queueKey) + } + }) + } + + return { vmPlugins, vmPluginVals, updateVMPluginSetting } +} + +export const VMPluginGroup: React.FC<{ locale: Locale; group: string; state: ReturnType }> = ({ locale, group, state }) => { + const { vmPlugins, vmPluginVals, updateVMPluginSetting } = state + const matched = vmPlugins.filter((p) => p.settings && (p.settings['x-group'] === group || Object.values(p.settings.properties ?? {}).some((prop) => prop['x-group'] === group))) + if (matched.length === 0) return null + return ( + + {matched.map((p) => ( + updateVMPluginSetting(p.id, patch)} + /> + ))} + + ) +} diff --git a/frontend/src/components/vmSettings/sharing.tsx b/frontend/src/components/vmSettings/sharing.tsx new file mode 100644 index 0000000..adf0f16 --- /dev/null +++ b/frontend/src/components/vmSettings/sharing.tsx @@ -0,0 +1,323 @@ +import * as Alert from '@radix-ui/react-alert-dialog' +import { FolderPlus, Trash2 } from 'lucide-react' +import React, { useEffect, useRef, useState } from 'react' +import { I18nKey, parseAppError, t } from '../../i18n' +import { DriveShareSettings, Locale, SharedFolderInfo, SharedFolderMode, SharedFolderSettings, VMDetail } from '../../types' +import { Button, IconButton } from '../../ui/controls' +import { Segmented, SetGroup, SetRow, SetValue, Switch } from '../../ui/settings' +import { api } from '../../wails' + +/** Windows drives shared with the VM. */ +export function useDriveShares(vm: string) { + const [driveSettings, setDriveSettings] = useState(null) + const [driveBusy, setDriveBusy] = useState(false) + const driveBusyRef = useRef(false) + const [driveErr, setDriveErr] = useState('') + const activeVMNameRef = useRef(vm) + activeVMNameRef.current = vm + + useEffect(() => { + let active = true + setDriveSettings(null) + setDriveErr('') + api.GetVMDriveShareSettings(vm) + .then((settings) => { if (active) setDriveSettings(settings) }) + .catch((e) => { if (active) setDriveErr(parseAppError(e).summary) }) + return () => { active = false } + }, [vm]) + + const updateDriveShares = async (enabled: boolean, selected: string[]) => { + if (driveBusyRef.current || !driveSettings) return + driveBusyRef.current = true + setDriveBusy(true) + setDriveErr('') + try { + const next = await api.SetVMDriveShareSettings(vm, enabled, selected) + if (activeVMNameRef.current === vm) setDriveSettings(next) + } catch (e) { + if (activeVMNameRef.current === vm) setDriveErr(parseAppError(e).summary) + } finally { + driveBusyRef.current = false + setDriveBusy(false) + } + } + + const selectedDrives = () => (driveSettings?.drives ?? []).filter((d) => d.selected).map((d) => d.drive) + + return { driveSettings, driveBusy, driveErr, updateDriveShares, selectedDrives } +} + +/** Single folders shared with the VM. */ +export function useSharedFolders(vm: string, locale: Locale) { + const tr = (k: I18nKey, v?: Record) => t(locale, k, v) + const [folderSettings, setFolderSettings] = useState(null) + const [folderBusy, setFolderBusy] = useState(false) + const folderBusyRef = useRef(false) + const folderOpSeqRef = useRef(0) + const [folderErr, setFolderErr] = useState('') + const [confirmRWFolder, setConfirmRWFolder] = useState(null) + const activeVMNameRef = useRef(vm) + activeVMNameRef.current = vm + + useEffect(() => { + let active = true + folderOpSeqRef.current += 1 + folderBusyRef.current = false + setFolderBusy(false) + setFolderSettings(null) + setFolderErr('') + setConfirmRWFolder(null) + api.GetVMSharedFolderSettings(vm) + .then((settings) => { if (active) setFolderSettings(settings) }) + .catch((e) => { if (active) setFolderErr(formatFolderError(e)) }) + return () => { active = false } + }, [vm]) + + const formatFolderIssue = (issue?: string) => { + switch (issue) { + case 'missing': return tr('folderShareIssueMissing') + case 'volume_mismatch': return tr('folderShareIssueVolumeMismatch') + case 'path_changed': return tr('folderShareIssuePathChanged') + case 'overlap': return tr('folderShareIssueOverlap') + case 'blocked': return tr('folderShareIssueBlocked') + case 'not_found': return tr('folderShareIssueNotFound') + case 'invalid_mode': return tr('folderShareIssueInvalidMode') + case 'corrupt_config': return tr('folderShareIssueCorruptConfig') + default: return '' + } + } + + const formatFolderError = (e: unknown) => { + const summary = parseAppError(e).summary + const match = summary.match(/shared folder:\s*(missing|volume_mismatch|path_changed|overlap|blocked|not_found|invalid_mode|corrupt_config)\b/i) + if (match) return formatFolderIssue(match[1].toLowerCase()) + return summary + } + + const runFolderOp = async (op: (vm: string) => Promise) => { + if (folderBusyRef.current || !folderSettings) return + const opSeq = ++folderOpSeqRef.current + folderBusyRef.current = true + setFolderBusy(true) + setFolderErr('') + try { + const next = await op(vm) + if (next && activeVMNameRef.current === vm && folderOpSeqRef.current === opSeq) { + setFolderSettings(next) + } + } catch (e) { + if (activeVMNameRef.current === vm && folderOpSeqRef.current === opSeq) { + setFolderErr(formatFolderError(e)) + } + } finally { + if (folderOpSeqRef.current === opSeq) { + folderBusyRef.current = false + setFolderBusy(false) + } + } + } + + const handleAddFolder = () => runFolderOp(async (vm) => { + const picked = await api.PickDirectory(tr('folderSharePickTitle')) + if (!picked || activeVMNameRef.current !== vm) return null + return api.AddVMSharedFolder(vm, picked) + }) + + const updateFolderMode = (folderID: string, mode: SharedFolderMode) => + runFolderOp((vm) => api.SetVMSharedFolderMode(vm, folderID, mode)) + + const handleRemoveFolder = (folderID: string) => + runFolderOp((vm) => api.RemoveVMSharedFolder(vm, folderID)) + + return { + folderSettings, folderBusy, folderErr, confirmRWFolder, setConfirmRWFolder, formatFolderIssue, + handleAddFolder, updateFolderMode, handleRemoveFolder, + } +} + +interface SectionProps { + locale: Locale + detail: VMDetail + state: State + /** Version of the connected Guest Tools agent, 0 when none is connected. */ + toolsVersion: number +} + +export const DriveShareSection: React.FC>> = ({ locale, detail, state, toolsVersion }) => { + const tr = (k: I18nKey, v?: Record) => t(locale, k, v) + const { driveSettings, driveBusy, driveErr, updateDriveShares, selectedDrives } = state + return ( + + void updateDriveShares(enabled, selectedDrives())} + /> + } + /> + {detail.guest_tools_disabled &&
{tr('gtStatusOffTip')}
} + {driveErr &&
{driveErr}
} + {driveSettings?.enabled && selectedDrives().length > 0 && + toolsVersion > 0 && + toolsVersion < driveSettings.required_agent_version && ( +
{tr('driveShareNeedsTools', { version: driveSettings.required_agent_version })}
+ )} + {/* Drives are only worth choosing once sharing is on. */} + {driveSettings?.enabled && driveSettings.drives.map((drive) => { + const title = `Windows (${drive.drive}:)` + return ( + {tr('driveShareSystem')} : undefined} + disabled={driveBusy || !!detail.guest_tools_disabled} + control={ + { + const next = selectedDrives().filter((letter) => letter !== drive.drive) + if (enabled) next.push(drive.drive) + void updateDriveShares(driveSettings?.enabled ?? false, next) + }} + /> + } + /> + ) + })} + {driveSettings && driveSettings.drives.length === 0 && ( + + )} +
+ ) +} + +export const SharedFolderSection: React.FC>> = ({ locale, detail, state, toolsVersion }) => { + const tr = (k: I18nKey, v?: Record) => t(locale, k, v) + const { folderSettings, folderBusy, folderErr, setConfirmRWFolder, formatFolderIssue, handleAddFolder, updateFolderMode, handleRemoveFolder } = state + return ( + + + ) +} + +/** Asks before the VM may change files in a shared folder. */ +export const WritableFolderDialog: React.FC<{ locale: Locale; state: ReturnType }> = ({ locale, state }) => { + const tr = (k: I18nKey, v?: Record) => t(locale, k, v) + const { confirmRWFolder, setConfirmRWFolder, updateFolderMode } = state + if (!confirmRWFolder) return null + return ( + { if (!open) setConfirmRWFolder(null) }}> + + + +
+ {tr('folderShareConfirmRWTitle')} + + {tr('folderShareConfirmRWDesc', { name: confirmRWFolder.name, path: confirmRWFolder.host_path })} + +
+
+ + + + + + +
+
+
+
+ ) +} diff --git a/frontend/src/components/vmSettings/smbios.tsx b/frontend/src/components/vmSettings/smbios.tsx new file mode 100644 index 0000000..095a98b --- /dev/null +++ b/frontend/src/components/vmSettings/smbios.tsx @@ -0,0 +1,279 @@ +import { Copy, Eye, EyeOff, Shuffle } from 'lucide-react' +import React, { useEffect, useState } from 'react' +import { I18nKey, parseAppError, t } from '../../i18n' +import { Locale, SMBIOSIdentity, VMDetail } from '../../types' +import { Button, IconButton } from '../../ui/controls' +import { Modal } from '../../ui/dialog' +import { SetGroup, SetRow, SetValue } from '../../ui/settings' +import { api } from '../../wails' + +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)}` +} + +/** The VM's SMBIOS identity and the dialog that replaces it. */ +export function useSMBIOS(detail: VMDetail, running: boolean) { + 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) + + 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('') + } + } + + return { + smbios, smbiosErr, smbiosReveal, setSmbiosReveal, smbiosOpen, setSmbiosOpen, smbiosDraft, + setSmbiosDraft, smbiosBusy, smbiosModalErr, smbiosApplied, smbiosLocked, openSmbiosRotate, + handleGenerateSmbios, handleApplySmbios, + } +} + +interface Props { + locale: Locale + state: ReturnType + onCopy?: (text: string) => void +} + +export const SMBIOSSection: React.FC = ({ locale, state, onCopy }) => { + const tr = (k: I18nKey, v?: Record) => t(locale, k, v) + const { smbios, smbiosErr, smbiosReveal, setSmbiosReveal, smbiosApplied, smbiosLocked, openSmbiosRotate } = state + return ( + + + ) +} + +export const SMBIOSDialog: React.FC = ({ locale, state, onCopy }) => { + const tr = (k: I18nKey, v?: Record) => t(locale, k, v) + const { smbios, setSmbiosOpen, smbiosDraft, setSmbiosDraft, smbiosBusy, smbiosModalErr, smbiosLocked, handleGenerateSmbios, handleApplySmbios } = state + return ( + setSmbiosOpen(false)} + > +
+
+ {tr('smbiosWarning')} +
+
+ + {onCopy && smbiosDraft?.serial && ( + + )} +
+ + + + {smbios?.rom && ( +
+ {tr('smbiosROM')}: {smbios.rom} +
+ )} +
{tr('smbiosCheckHint')}
+ {smbiosModalErr &&
{smbiosModalErr}
} +
+
+ + + + + +
+
+ ) +} diff --git a/frontend/src/components/vmSettings/targetDisplay.tsx b/frontend/src/components/vmSettings/targetDisplay.tsx new file mode 100644 index 0000000..ea4c77c --- /dev/null +++ b/frontend/src/components/vmSettings/targetDisplay.tsx @@ -0,0 +1,217 @@ +import React, { useEffect, useMemo, useRef, useState } from 'react' +import type { app as WailsApp } from '../../../wailsjs/go/models' +import { I18nKey, parseAppError, t } from '../../i18n' +import { humanDisplayFallbackName, humanDisplayMeta, humanDisplayTitle, sortDisplaysForPicker } from '../../lib/format' +import { DisplayInfo, HostReport, Locale } from '../../types' +import { PopupSelect, SetRow } from '../../ui/settings' +import type { ToastInput } from '../../ui/toast' +import { api } from '../../wails' + +const PRIMARY_DISPLAY_OPT = '__primary' + +interface Options { + locale: Locale + driverID: string + vm: string + running: boolean + host: HostReport + shown: boolean + isBlocked: () => boolean + onToast: (toast: ToastInput) => void +} + +/** The host display the VM window opens on. A change applies at once. */ +export function useTargetDisplay({ locale, driverID, vm, running, host, shown, isBlocked, onToast }: Options) { + const tr = (k: I18nKey, v?: Record) => t(locale, k, v) + const activeVMNameRef = useRef(vm) + activeVMNameRef.current = vm + const [displayStatus, setDisplayStatus] = useState(null) + const [displayBusy, setDisplayBusy] = useState(false) + const [displayErr, setDisplayErr] = useState('') + const displayBusyRef = useRef(false) + const displayReqSeqRef = useRef(0) + + const connectedDisplays = useMemo( + () => sortDisplaysForPicker(displayStatus?.displays ?? host.displays ?? []), + [displayStatus, host.displays], + ) + const activeTargetDisplay = displayStatus + ? connectedDisplays.find((d) => d.name === displayStatus.effective_display) + : host.primary_display + const displayProfile = useMemo(() => displayStatus ? { + ...host, + primary_display: activeTargetDisplay, + display_presets: displayStatus.display_presets, + fullscreen_hidpi: displayStatus.fullscreen_hidpi, + hidpi_advice: displayStatus.hidpi_advice, + recommended_resolution: undefined, + } : host, [host, displayStatus, activeTargetDisplay]) + + const hostDisplaysSig = (host.displays ?? []) + .map((d) => `${d.name ?? ''}:${d.friendly_name ?? ''}:${d.width}x${d.height}@${d.scale_pct}:${d.refresh_hz ?? 0}:${d.work_width ?? 0}x${d.work_height ?? 0}:${d.primary ? 1 : 0}`) + .join('|') + + useEffect(() => { + displayReqSeqRef.current += 1 + displayBusyRef.current = false + setDisplayStatus(null) + setDisplayBusy(false) + setDisplayErr('') + }, [driverID, vm]) + + useEffect(() => { + let active = true + const reqSeq = displayReqSeqRef.current + if (displayBusyRef.current) return () => { active = false } + api.GetVMDisplay(driverID, vm) + .then((st) => { + if (active && displayReqSeqRef.current === reqSeq) { + setDisplayStatus(st) + setDisplayErr('') + } + }) + .catch((e) => { + if (active && displayReqSeqRef.current === reqSeq) { + setDisplayErr(parseAppError(e).summary) + } + }) + return () => { active = false } + }, [driverID, vm, running, hostDisplaysSig, shown]) + + const numberedDisplay = (n: number) => tr('targetDisplayNumbered', { n }) + + const displayOptions = useMemo(() => { + const opts: Array<{ value: string; label: string; detail?: string }> = [ + { + value: PRIMARY_DISPLAY_OPT, + label: tr('targetDisplayPrimaryDefault'), + }, + ...connectedDisplays + .filter((d): d is DisplayInfo & { name: string } => Boolean(d.name?.trim())) + .map((d, idx) => ({ + value: d.name, + label: humanDisplayTitle(d, idx + 1, numberedDisplay), + detail: humanDisplayMeta(d, d.primary ? tr('hostDisplayPrimary') : undefined), + })), + ] + const savedTarget = displayStatus?.target_display?.trim() + if (savedTarget && displayStatus?.fallback_to_primary) { + if (!opts.some((o) => o.value.toLowerCase() === savedTarget.toLowerCase())) { + opts.push({ + value: savedTarget, + label: humanDisplayFallbackName(savedTarget, numberedDisplay), + detail: tr('targetDisplayDisconnectedOption'), + }) + } + } + return opts + }, [connectedDisplays, displayStatus?.fallback_to_primary, displayStatus?.target_display, locale]) + const selectedDisplayValue = useMemo(() => { + const saved = displayStatus?.target_display?.trim() + if (!saved) return PRIMARY_DISPLAY_OPT + return displayOptions.find((o) => o.value.toLowerCase() === saved.toLowerCase())?.value ?? saved + }, [displayOptions, displayStatus?.target_display]) + const activeTargetDisplayTitle = useMemo(() => { + if (!activeTargetDisplay) return '' + const idx = connectedDisplays.findIndex((d) => d === activeTargetDisplay || (d.name && activeTargetDisplay.name && d.name.toLowerCase() === activeTargetDisplay.name.toLowerCase())) + return humanDisplayTitle(activeTargetDisplay, idx >= 0 ? idx + 1 : 1, numberedDisplay) + }, [activeTargetDisplay, connectedDisplays, locale]) + const displayErrorToast = (title: string, error: unknown) => { + const parsed = parseAppError(error) + onToast({ + kind: 'error', + title, + description: parsed.summary, + errorCode: parsed.code, + rawDetail: parsed.rawDetail, + detailsLabel: tr('errRawDetailsToggle'), + copyDetailsLabel: tr('errCopyDetails'), + }) + } + + const handleTargetDisplayChange = async (nextValue: string) => { + if (isBlocked() || displayBusyRef.current || displayStatus === null) return + const nextTarget = nextValue === PRIMARY_DISPLAY_OPT ? '' : nextValue + const currentTarget = displayStatus.target_display ?? '' + if (nextTarget.toLowerCase() === currentTarget.toLowerCase()) return + + const opSeq = ++displayReqSeqRef.current + displayBusyRef.current = true + setDisplayBusy(true) + setDisplayErr('') + try { + const next = await api.SetVMDisplay(driverID, vm, nextTarget) + if (activeVMNameRef.current !== vm || displayReqSeqRef.current !== opSeq) return + setDisplayStatus(next) + const chosenLabel = displayOptions.find((o) => o.value === nextValue)?.label + ?? humanDisplayFallbackName(next.target_display, numberedDisplay) + if (next.move_error) { + displayErrorToast(tr('targetDisplayToastSaved', { display: chosenLabel }), next.move_error) + } else { + onToast({ + kind: 'ok', + title: next.applied_live + ? tr('targetDisplayToastMoved', { display: chosenLabel }) + : tr('targetDisplayToastSaved', { display: chosenLabel }), + }) + } + } catch (e) { + if (activeVMNameRef.current !== vm || displayReqSeqRef.current !== opSeq) return + displayErrorToast(tr('targetDisplaySaveFailed'), e) + } finally { + if (displayReqSeqRef.current === opSeq) { + displayBusyRef.current = false + setDisplayBusy(false) + } + } + } + + return { + displayStatus, displayBusy, displayErr, connectedDisplays, activeTargetDisplay, + activeTargetDisplayTitle, displayProfile, displayOptions, selectedDisplayValue, handleTargetDisplayChange, + /** Whether a change is being saved right now, ahead of the next render. */ + isBusy: () => displayBusyRef.current, + } +} + +interface RowProps { + locale: Locale + running: boolean + disabled: boolean + state: ReturnType +} + +export const TargetDisplayRow: React.FC = ({ locale, running, disabled, state }) => { + const tr = (k: I18nKey, v?: Record) => t(locale, k, v) + const { displayStatus, displayBusy, displayErr, connectedDisplays, displayOptions, selectedDisplayValue, handleTargetDisplayChange } = state + const numberedDisplay = (n: number) => tr('targetDisplayNumbered', { n }) + const targetDisplayDesc = displayStatus?.fallback_to_primary && displayStatus.target_display + ? ( + + {tr('targetDisplayFallbackHint', { + name: humanDisplayFallbackName(displayStatus.target_display, numberedDisplay), + })} + + ) + : connectedDisplays.length === 0 + ? tr('targetDisplayNoneHint') + : connectedDisplays.length === 1 + ? tr('targetDisplaySingleHint') + : tr(running ? 'targetDisplayRunningHint' : 'targetDisplayStoppedHint') + return ( + void handleTargetDisplayChange(v)} + options={displayOptions} + /> + } + /> + ) +} diff --git a/frontend/src/components/vmSettings/timezone.tsx b/frontend/src/components/vmSettings/timezone.tsx new file mode 100644 index 0000000..5adf8e4 --- /dev/null +++ b/frontend/src/components/vmSettings/timezone.tsx @@ -0,0 +1,158 @@ +import { Check, Copy } from 'lucide-react' +import React, { useEffect, useRef, useState } from 'react' +import { I18nKey, t } from '../../i18n' +import { createVMSettingRequests, type VMSettingState } from '../../lib/vmSettingRequests' +import { Locale, VMDetail } from '../../types' +import { IconButton } from '../../ui/controls' +import { PopupSelect, SetRow } from '../../ui/settings' +import type { ToastInput } from '../../ui/toast' +import { api } from '../../wails' + +type VMTimezoneStatus = Awaited> + +const GUEST_TOOLS_INSTALL_CMD = 'sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command' +const GUEST_TIMEZONE_APPLY_CMD = 'sh /Volumes/REIMSTOOLS/Apply-Timezone.command' + +const GUEST_TIMEZONE_PRESETS: ReadonlyArray<{ value: string; labelKey: I18nKey; detail?: string }> = [ + { value: 'Asia/Shanghai', labelKey: 'guestTimezoneShanghai', detail: 'Asia/Shanghai' }, + { value: 'Asia/Hong_Kong', labelKey: 'guestTimezoneHongKong', detail: 'Asia/Hong_Kong' }, + { value: 'Asia/Taipei', labelKey: 'guestTimezoneTaipei', detail: 'Asia/Taipei' }, + { value: 'Asia/Tokyo', labelKey: 'guestTimezoneTokyo', detail: 'Asia/Tokyo' }, + { value: 'Asia/Seoul', labelKey: 'guestTimezoneSeoul', detail: 'Asia/Seoul' }, + { value: 'Asia/Singapore', labelKey: 'guestTimezoneSingapore', detail: 'Asia/Singapore' }, + { value: 'Europe/London', labelKey: 'guestTimezoneLondon', detail: 'Europe/London' }, + { value: 'Europe/Berlin', labelKey: 'guestTimezoneBerlin', detail: 'Europe/Berlin' }, + { value: 'America/Los_Angeles', labelKey: 'guestTimezoneLosAngeles', detail: 'America/Los_Angeles' }, + { value: 'America/New_York', labelKey: 'guestTimezoneNewYork', detail: 'America/New_York' }, + { value: 'Australia/Sydney', labelKey: 'guestTimezoneSydney', detail: 'Australia/Sydney' }, + { value: 'UTC', labelKey: 'guestTimezoneUTC' }, +] + +/** The time zone the VM follows, refreshed while shown. */ +export function useGuestTimezone(driverID: string, vm: string, running: boolean, shown: boolean) { + const vmSettingsKey = `${driverID}:${vm}` + const activeVMKeyRef = useRef(vmSettingsKey) + activeVMKeyRef.current = vmSettingsKey + const [{ value: tzStatus, error: tzErr, busy: tzBusy }, setTzState] = useState>({ value: null, error: '', busy: false }) + const [tzRequests] = useState(() => createVMSettingRequests(() => activeVMKeyRef.current, + (patch) => setTzState((state) => ({ ...state, ...patch })))) + + useEffect(() => { + setTzState({ value: null, error: '', busy: tzRequests.isWriting(vmSettingsKey) }) + }, [vmSettingsKey, tzRequests]) + + useEffect(() => { + if (!shown) return + const { refresh, stop } = tzRequests.watch(vmSettingsKey, () => api.GetVMTimezone(driverID, vm)) + void refresh() + const timer = window.setInterval(refresh, 3000) + return () => { stop(); window.clearInterval(timer) } + }, [shown, driverID, vm, running, vmSettingsKey, tzRequests]) + + return { + tzStatus, + tzErr, + tzBusy, + /** Whether a change is being saved right now, ahead of the next render. */ + isWriting: () => tzRequests.isWriting(vmSettingsKey), + write: (setting: string) => tzRequests.write(vmSettingsKey, () => api.SetVMTimezone(driverID, vm, setting)), + } +} + +interface Props { + locale: Locale + detail: VMDetail + hostTimezone?: string + state: ReturnType + disabled: boolean + isBlocked: () => boolean + onToast: (toast: ToastInput) => void + onCopy?: (text: string) => void +} + +export const GuestTimezoneRow: React.FC = ({ locale, detail, hostTimezone, state, disabled, isBlocked, onToast, onCopy }) => { + const tr = (k: I18nKey, v?: Record) => t(locale, k, v) + const { tzStatus, tzErr, tzBusy, write } = state + + const updateTimezone = async (nextSetting: string) => { + if (isBlocked() || !tzStatus) return + const currentSetting = tzStatus.mode === 'off' ? 'off' : tzStatus.mode === 'custom' ? tzStatus.timezone : 'host' + if (nextSetting === currentSetting) return + if (await write(nextSetting)) { + onToast({ kind: 'ok', title: tr('guestTimezoneSaved') }) + } + } + + const detectedHostTZ = tzStatus?.host_timezone || hostTimezone || '' + const tzSelectedValue = tzStatus?.mode === 'custom' ? tzStatus.timezone : tzStatus?.mode + const tzOptions = [ + { value: 'host', label: tr('guestTimezoneHost'), detail: detectedHostTZ || undefined }, + ...GUEST_TIMEZONE_PRESETS.map((p) => ({ + value: p.value, + label: tr(p.labelKey), + detail: p.detail, + })), + ...(tzStatus?.mode === 'custom' && tzStatus.timezone && !GUEST_TIMEZONE_PRESETS.some((p) => p.value === tzStatus.timezone) + ? [{ value: tzStatus.timezone, label: tzStatus.timezone }] + : []), + { value: 'off', label: tr('guestTimezoneOff') }, + ] + let tzDesc: React.ReactNode = tr('guestTimezoneDesc') + let tzCommand = '' + if (tzStatus) { + const tzEffective = tzStatus.effective_timezone + if (tzStatus.mode === 'off') { + tzDesc = tr('guestTimezoneOffDesc') + } else if (detail.guest_tools_disabled) { + tzDesc = {tr('gtStatusOffTip')} + } else if (!tzEffective) { + tzDesc = {tr('guestTimezoneHostUnknown')} + } else if (tzStatus.running && tzStatus.guest_connected) { + const tzFailure = tzStatus.timezone_error + ? {tr('guestTimezoneApplyFailed', { tz: tzEffective })} + : null + if (tzStatus.guest_agent_version < tzStatus.required_agent_version) { + tzDesc = {tr(detail.guest_tools_attached ? 'guestTimezoneUpgradeHint' : 'guestTimezoneUpgradeAttachHint', { version: tzStatus.required_agent_version })} + if (detail.guest_tools_attached) tzCommand = GUEST_TOOLS_INSTALL_CMD + } else if (!tzStatus.helper_ready) { + const hint = tr(detail.guest_tools_attached ? 'guestTimezoneApplyHint' : 'guestTimezoneApplyAttachHint') + tzDesc = tzFailure ?
{tzFailure}{hint}
: hint + if (detail.guest_tools_attached) tzCommand = GUEST_TIMEZONE_APPLY_CMD + } else if (tzFailure) { + tzDesc = tzFailure + } else if (tzStatus.guest_applied === tzEffective) { + tzDesc = + } else { + tzDesc = tr('guestTimezoneSyncing', { tz: tzEffective }) + } + } else if (detail.guest_tools_attached) { + tzCommand = GUEST_TOOLS_INSTALL_CMD + } + } + + return ( + + } + block={tzCommand ? ( +
+ {tzCommand} + {onCopy && ( + } onClick={() => onCopy(tzCommand)} /> + )} +
+ ) : undefined} + /> + ) +} From 5b31ade958ac6ac9a1257697502fe2850bee69e2 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: Thu, 3 Dec 2026 21:54:18 -0700 Subject: [PATCH 14/22] refactor(frontend): split the VM page by feature VMPage was one 1587-line component. Restore points, SSH access, host DNS, endpoints, the install card, notices, the summary and the technical details now have their own files, and both ellipsis menus share one ActionMenu. Remove the borderless toggle and the runtime-kind listing, which no part of the window used. The binding test no longer counts a binding's type declaration in wails.ts as a caller. Co-Authored-By: Claude Opus 5.5 --- frontend/src/App.tsx | 8 - frontend/src/components/VMPage.tsx | 1606 ++--------------- .../src/components/vmPage/connections.tsx | 159 ++ frontend/src/components/vmPage/endpoints.tsx | 137 ++ frontend/src/components/vmPage/hostDNS.tsx | 235 +++ .../src/components/vmPage/installCard.tsx | 162 ++ frontend/src/components/vmPage/notices.tsx | 124 ++ frontend/src/components/vmPage/screen.tsx | 91 + frontend/src/components/vmPage/snapshots.tsx | 191 ++ frontend/src/components/vmPage/ssh.tsx | 134 ++ frontend/src/components/vmPage/summary.tsx | 156 ++ frontend/src/components/vmPage/techInfo.tsx | 85 + frontend/src/i18n/domains/core.gen.ts | 4 - frontend/src/i18n/keys.gen.ts | 2 - frontend/src/lib/format.ts | 11 + frontend/src/types.ts | 1 - frontend/src/ui/menu.tsx | 73 + frontend/src/wails.ts | 3 +- frontend/wailsjs/go/app/App.d.ts | 4 - frontend/wailsjs/go/app/App.js | 8 - frontend/wailsjs/go/models.ts | 123 +- internal/app/macos_settings.go | 6 - internal/app/plugins_flow.go | 10 - internal/archtest/bindings_test.go | 2 +- internal/i18n/catalog_gen.go | 4 - locales/en-US/core.json | 2 - locales/zh-CN/core.json | 2 - 27 files changed, 1777 insertions(+), 1566 deletions(-) create mode 100644 frontend/src/components/vmPage/connections.tsx create mode 100644 frontend/src/components/vmPage/endpoints.tsx create mode 100644 frontend/src/components/vmPage/hostDNS.tsx create mode 100644 frontend/src/components/vmPage/installCard.tsx create mode 100644 frontend/src/components/vmPage/notices.tsx create mode 100644 frontend/src/components/vmPage/screen.tsx create mode 100644 frontend/src/components/vmPage/snapshots.tsx create mode 100644 frontend/src/components/vmPage/ssh.tsx create mode 100644 frontend/src/components/vmPage/summary.tsx create mode 100644 frontend/src/components/vmPage/techInfo.tsx create mode 100644 frontend/src/ui/menu.tsx diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 22dfee4..c9c785e 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1486,14 +1486,6 @@ export const App: React.FC = () => { onViewLogs={() => { openLogs('serial'); loadSerial() }} onCopy={copy} onTypeText={(text) => typeInto(vmRefKey(selectedVM), () => api.TypeText(selectedVM.driver_id ?? '', selectedVM.name, text))} - onToggleBorderless={(enabled) => { - api.ToggleBorderless(selectedVM.name, enabled) - .then(() => { - toasts.push({ kind: 'ok', title: tr(effectiveState === 'running' ? 'toastBorderlessNextStart' : 'toastBorderlessUpdated') }) - return refresh() - }) - .catch((e) => fail(tr('failGeneric'), e)) - }} onTogglePreventSleep={(enabled) => { api.SetGuestPreventSleep(selectedVM.name, enabled) .then(() => { diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index 5c8583c..ddefda8 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -1,67 +1,57 @@ -import * as Alert from '@radix-ui/react-alert-dialog' import * as Menu from '@radix-ui/react-dropdown-menu' import { - Activity, - AlertTriangle, AppWindow, Archive, Camera, Check, ChevronDown, - ChevronRight, - Code2, - Copy, CopyPlus, Cpu, - Disc, - Ellipsis, - FileCode2, FolderOpen, - Globe, - HardDrive, - History, - Info, Keyboard, LifeBuoy, Maximize2, - MemoryStick, Minimize2, - Monitor, - MonitorPlay, - Network, Pause, Pencil, Play, - Plus, Power, - RotateCcw, RotateCw, Settings, Square, Terminal, Trash, Upload, - UserRound, } from 'lucide-react' import React, { useEffect, useId, useRef, useState } from 'react' -import { I18nKey, localeDir, locText, parseAppError, t } from '../i18n' +import { I18nKey, localeDir, locText, t } from '../i18n' +import { formatUptime } from '../lib/format' import { - controllerLabel, formatBytes, formatDiskUsage, formatMemory, formatUptime, graphicsLabel, - parseMemoryGB, pendingChangeText, resolveGuestLang, sshCommand, -} from '../lib/format' -import { hasVisibleDialog } from '../lib/dialogState' -import { - EndpointAction, defaultEndpointAction, endpointActions, endpointKey, guestFamilyOf, isMacOSDriver as isMacOSDriverID, - orderEndpoints, secondaryEndpointActions, splitEndpoints, vmFeatures, + defaultEndpointAction, + endpointKey, + guestFamilyOf, + isMacOSDriver as isMacOSDriverID, + splitEndpoints, + vmFeatures, } from '../lib/endpoints' import { useVMStats } from '../lib/vmStats' -import { DiskSnapshot, HostReport, Locale, PendingChange, PluginUIContributions, VMDetail, VMEndpoint, VMInfo, VMThumbnail } from '../types' +import { HostReport, Locale, PendingChange, PluginUIContributions, VMDetail, VMInfo } from '../types' import { api } from '../wails' -import { Button, IconButton, StatusShape, Tip, statusKind } from '../ui/controls' -import { Switch } from '../ui/settings' +import { Button, StatusShape, Tip, statusKind } from '../ui/controls' +import { ActionMenu } from '../ui/menu' import { HostIcon } from '../ui/themeVisuals' import { VersionArt } from '../macos/VersionArt' import { GuestArt, hasGuestArt } from './GuestIcon' +import { ConnectionSection } from './vmPage/connections' +import { endpointIcon, EndpointSection, useEndpointActions } from './vmPage/endpoints' +import { useHostDNS } from './vmPage/hostDNS' +import { InstallCard } from './vmPage/installCard' +import { VMNotices } from './vmPage/notices' +import { useVMThumbnail, VMScreen } from './vmPage/screen' +import { SnapshotSection } from './vmPage/snapshots' +import { SSHUserDialog, useSSHAccess } from './vmPage/ssh' +import { VMSummary } from './vmPage/summary' +import { TechInfo } from './vmPage/techInfo' export type VMAction = | 'start' @@ -91,35 +81,8 @@ export type VMAction = export type VMBusyAction = VMAction | 'pluginCommand' -// Runs from reims-go's pre-extracted HFS+ helper disk (REIMSHELP), bypassing -// macOS Recovery's `installer -target` fallback to read-only `/` and missing `pkgutil`. -const OFFLINE_INSTALL_CMD = 'sh /Volumes/REIMSHELP/install.sh' -const GUEST_TOOLS_INSTALL_CMD = 'sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command' -const HOST_DNS_APPLY_CMD = 'sh /Volumes/REIMSTOOLS/Apply-Host-DNS.command' -const HOST_DNS_DISABLE_CMD = 'sh /Volumes/REIMSTOOLS/Disable-Host-DNS.command' const PRIMARY_SHORTCUT = 'Ctrl+Enter' -const GUEST_FAMILY_LABEL: Record = { macos: 'macOS', linux: 'Linux', windows: 'Windows', android: 'Android' } - -/** The built-in icon of an endpoint kind; each is themeable by name. */ -function endpointIcon(kind: string, size: number): React.ReactNode { - return kind === 'vmconnect' || kind === 'rdp' - ? - : -} - -/** A short, user-facing description of where an endpoint points. */ -function endpointDetail(ep: VMEndpoint): string { - switch (ep.kind) { - case 'ssh': return `${ep.user ? `${ep.user}@` : ''}${ep.host || '127.0.0.1'}${ep.port ? `:${ep.port}` : ''}` - case 'wsl': return ep.distro ?? '' - case 'rdp': return `${ep.host ?? ''}${ep.port ? `:${ep.port}` : ''}` - case 'vmconnect': return ep.vm ?? '' - case 'adb': return ep.serial ?? '' - default: return '' - } -} - interface Props { locale: Locale /** The VM's identifier (folder, CLI, reims-ctl). */ @@ -153,7 +116,6 @@ interface Props { onViewLogs: () => void onCopy: (text: string) => void onTypeText: (text: string) => void - onToggleBorderless: (enabled: boolean) => void onTogglePreventSleep: (enabled: boolean) => void onDeliverFile: () => void onToast: (title: string) => void @@ -164,10 +126,6 @@ interface Props { pluginUI?: PluginUIContributions | null } -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' @@ -202,17 +160,6 @@ function ShutdownButton({ locale, busyAction, onAction }: Pick = ({ locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, currentAgentVersion, guideActive, installGuideEnabled, detail, vmInfo, host, pending, busyAction, onAction, onPluginCommand, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI, fullscreenHotkey, }) => { @@ -222,8 +169,8 @@ export const VMPage: React.FC = ({ const suspended = state === 'suspended' const guestToolsLocked = suspended || state === 'suspending' || state === 'resuming' const resumeHintId = useId() - const guestToolsHintId = useId() const installing = !!detail && (detail.has_installer || detail.recovery_mode) + const vmKey = `${driverID}:${name}` const transitioning = state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming' const isMacOSDriver = isMacOSDriverID(driverID) const toolbarMenus = (pluginUI?.menus ?? []).filter(({ slot, when }) => { @@ -247,113 +194,12 @@ export const VMPage: React.FC = ({ // A running hosted VM has no window: its best ready endpoint is the header action. const { primary: bestEndpoint } = splitEndpoints(vmInfo?.endpoints) const promotedEndpoint = features.hosted && running ? bestEndpoint : undefined - const [endpointBusy, setEndpointBusy] = useState('') + const endpoints = useEndpointActions({ locale, driverID, name, onCopy, onError }) + const { endpointBusy, runEndpointAction, endpointActionLabel, endpointKindLabel } = endpoints // Polled here rather than in App so each tick re-renders only this page. const stats = useVMStats(driverID, name, running) - - // Per-VM Host DNS proxy state (host_dns_flow.go). - const [hostDNS, setHostDNS] = useState<{ - host_dns_enabled: boolean - host_dns_active: boolean - host_dns_config_stale: boolean - host_dns_reported: boolean - } | null>(null) - const [hostDNSLoadErr, setHostDNSLoadErr] = useState('') - const [hostDNSBusy, setHostDNSBusy] = useState(false) - const hostDNSWriteSeq = useRef(0) - useEffect(() => { - hostDNSWriteSeq.current += 1 - setHostDNS(null) - setHostDNSLoadErr('') - setHostDNSBusy(false) - }, [driverID, name]) - useEffect(() => { - if (!canUseHostDNS) { - setHostDNS(null) - setHostDNSLoadErr('') - return - } - let live = true - const pull = (force = false) => { - if (!force && document.hidden) return - const seq = hostDNSWriteSeq.current - api.GetGuestToolsHostDNS(name) - .then((s) => { - if (live && seq === hostDNSWriteSeq.current) { - setHostDNS(s) - setHostDNSLoadErr('') - } - }) - .catch((e) => { - console.warn('[vm] GetGuestToolsHostDNS failed:', e) - if (live && seq === hostDNSWriteSeq.current) { - setHostDNSLoadErr(parseAppError(e).summary) - } - }) - } - pull(true) - const onVisible = () => { - if (!document.hidden) pull(true) - } - document.addEventListener('visibilitychange', onVisible) - const timer = running ? window.setInterval(() => pull(false), 5000) : undefined - return () => { - live = false - document.removeEventListener('visibilitychange', onVisible) - if (timer) window.clearInterval(timer) - } - }, [driverID, name, canUseHostDNS, running, state, detail?.guest_tools_connected, detail?.guest_tools_attached]) - - const handleToggleHostDNS = async (enabled: boolean) => { - if (hostDNSBusy || guestToolsLocked || !canUseHostDNS || hostDNS === null) return - const writeSeq = ++hostDNSWriteSeq.current - setHostDNSBusy(true) - try { - await api.SetGuestToolsHostDNS(name, enabled) - onToast(tr(enabled ? 'toastHostDNSOn' : 'toastHostDNSOff')) - try { - const next = await api.GetGuestToolsHostDNS(name) - if (writeSeq === hostDNSWriteSeq.current) { - setHostDNS(next) - setHostDNSLoadErr('') - } - } catch (e) { - console.warn('[vm] GetGuestToolsHostDNS after toggle failed:', e) - if (writeSeq === hostDNSWriteSeq.current) { - setHostDNS((prev) => ({ - host_dns_enabled: enabled, - host_dns_active: prev?.host_dns_active ?? false, - host_dns_config_stale: prev?.host_dns_config_stale ?? false, - host_dns_reported: prev?.host_dns_reported ?? false, - })) - } - } - } catch (e) { - onError(tr('failGuestTools'), e) - } finally { - if (writeSeq === hostDNSWriteSeq.current) setHostDNSBusy(false) - } - } - - // Screen thumbnail (thumbnail_flow.go): a fresh frame every 15 s while the VM - // runs, otherwise the last frame saved. Skipped while this window is hidden; - // the backend also skips it while the VM's own window is in front. - const [thumb, setThumb] = useState(null) - useEffect(() => { setThumb(null) }, [driverID, name]) - const thumbnails = features.screenshot - useEffect(() => { - if (!thumbnails) return - let live = true - const pull = () => { - if (document.hidden) return - api.GetVMThumbnail(driverID, name) - .then((t) => { if (live && t?.data_url) setThumb(t) }) - .catch((e) => console.warn('[vm] GetVMThumbnail failed:', e)) - } - pull() - const timer = running ? window.setInterval(pull, 15000) : undefined - return () => { live = false; if (timer) window.clearInterval(timer) } - }, [driverID, name, running, thumbnails]) + const hostDNS = useHostDNS({ locale, driverID, name, state, detail, available: canUseHostDNS, locked: guestToolsLocked, onToast, onError }) + const thumb = useVMThumbnail(driverID, name, running, features.screenshot) // Display name, stored as the VM's note (.reims-go-note). Clicking the title // edits it in place; clearing it (or typing the name) falls back to the name. @@ -365,12 +211,6 @@ export const VMPage: React.FC = ({ // which would blur (and so save) the name field or pop the trigger's tooltip. const renameFromMenu = useRef(false) const nameInputRef = useRef(null) - const [moreMenuOpen, setMoreMenuOpen] = useState(false) - const moreOpenedByPointer = useRef(false) - const morePointerClosed = useRef(false) - const [sshMenuOpen, setSshMenuOpen] = useState(false) - const sshOpenedByPointer = useRef(false) - const sshPointerClosed = useRef(false) const saveName = async () => { setEditingName(false) let next = nameDraft.trim() @@ -384,177 +224,14 @@ export const VMPage: React.FC = ({ } } - // Remembered SSH username (.reims-go-ssh-user) - const [sshUser, setSshUser] = useState('') - const [sshUserDialog, setSshUserDialog] = useState(false) - const [sshUserDraft, setSshUserDraft] = useState('') - useEffect(() => { - setEditingName(false) - setMoreMenuOpen(false) - setSshMenuOpen(false) - setSshUserDialog(false) - setEndpointBusy('') - }, [driverID, name]) - useEffect(() => { - // The remembered SSH user belongs to the macOS connection row; other drivers keep theirs in their endpoints. - if (!isMacOSDriver) { setSshUser(''); return } - let live = true - api.GetVMSSHUser(driverID, name).then((u) => { if (live) setSshUser(u ?? '') }).catch(() => { if (live) setSshUser('') }) - return () => { live = false } - }, [driverID, name, isMacOSDriver]) - - const runEndpointAction = (ep: VMEndpoint, action: EndpointAction | '') => { - const busyKey = `${endpointKey(ep)}:${action}` - setEndpointBusy(busyKey) - const done = () => setEndpointBusy((cur) => (cur === busyKey ? '' : cur)) - if (action === 'copy') { - api.GetVMEndpointCommand(driverID, name, ep.kind) - .then((cmd) => onCopy(cmd)) - .catch((e) => onError(tr('failEndpointCommand'), e)) - .finally(done) - return - } - api.OpenVMEndpoint(driverID, name, ep.kind, action) - .catch((e) => onError(tr('failEndpointOpen'), e)) - .finally(done) - } - const endpointActionLabel = (kind: string, action: EndpointAction): string => { - switch (action) { - case 'terminal': return tr('endpointOpenTerminal') - case 'vscode': return tr('endpointOpenVSCode') - case 'config': return tr('sshWriteConfig') - case 'edit': return tr('endpointEditConnection') - case 'shell': return tr('endpointOpenADBShell') - case 'copy': return tr('endpointCopyADB') - case 'open': return tr(kind === 'vmconnect' ? 'endpointOpenVMConnect' : 'endpointOpenRDP') - } - } - const endpointKindLabel = (kind: string): string => { - switch (kind) { - case 'ssh': return tr('endpointKindSSH') - case 'wsl': return tr('endpointKindWSL') - case 'rdp': return tr('endpointKindRDP') - case 'vmconnect': return tr('endpointKindVMConnect') - case 'adb': return tr('endpointKindADB') - default: return kind - } - } - - const openSSHTerminal = () => { - api.OpenSSHTerminal(driverID, name, sshUser).catch((e) => onError(tr('failSSH'), e)) - } - const writeSSHConfig = () => { - api.WriteSSHConfig(driverID, name, sshUser) - .then((alias) => onToast(tr('toastSSHConfigWritten', { alias }))) - .catch((e) => onError(tr('failSSH'), e)) - } - const openVSCodeSSH = () => { - api.OpenVSCodeSSH(driverID, name, sshUser).catch((e) => onError(tr('failSSH'), e)) - } - const saveSSHUser = async () => { - const next = sshUserDraft.trim() - setSshUserDialog(false) - try { - await api.SetVMSSHUser(driverID, name, next) - setSshUser(next) - onToast(tr('toastSSHUserSaved')) - } catch (e) { - onError(tr('failSSH'), e) - } - } - - // Interactive install guide step checkboxes (persisted per VM in localStorage) - const guideKey = `reims-go-guide:${name}` - const [doneSteps, setDoneSteps] = useState([]) - useEffect(() => { - try { - const raw = localStorage.getItem(guideKey) - setDoneSteps(raw ? JSON.parse(raw) : []) - } catch { - setDoneSteps([]) - } - }, [guideKey]) - const toggleGuideStep = (step: number) => { - setDoneSteps((prev) => { - const next = prev.includes(step) ? prev.filter((x) => x !== step) : [...prev, step] - try { localStorage.setItem(guideKey, JSON.stringify(next)) } catch (e) { console.warn('[vm] persist guide progress failed:', e) } - return next - }) - } + useEffect(() => { setEditingName(false) }, [driverID, name]) + const ssh = useSSHAccess({ locale, driverID, name, enabled: isMacOSDriver, onToast, onError }) // Offline qcow2 restore points (snapshot_flow.go); other drivers offer them when they report `snapshot`. const isQcow2 = !!detail && /\.qcow2$/i.test(detail.disk ?? '') const showSnapshots = isMacOSDriver ? !!detail && !detail.has_installer && !detail.recovery_mode && isQcow2 : features.snapshot && state !== 'broken' && state !== 'driver_unavailable' - const [snapshots, setSnapshots] = useState([]) - const [creatingSnap, setCreatingSnap] = useState(false) - const [snapDraft, setSnapDraft] = useState('') - const [snapBusy, setSnapBusy] = useState('') - const [restoreTarget, setRestoreTarget] = useState(null) - - const loadSnapshots = () => { - if (!showSnapshots) { setSnapshots([]); return } - api.ListSnapshots(driverID, name).then((list) => setSnapshots(list ?? [])).catch(() => setSnapshots([])) - } - useEffect(() => { - setCreatingSnap(false) - setSnapDraft('') - setRestoreTarget(null) - loadSnapshots() - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [driverID, name, showSnapshots, state]) - - const handleCreateSnapshot = async () => { - const label = snapDraft.trim() - if (!label) return - setSnapBusy('create') - try { - await api.CreateSnapshot(driverID, name, label) - setSnapDraft('') - setCreatingSnap(false) - onToast(tr('toastSnapshotCreated', { name: label })) - loadSnapshots() - } catch (e) { - onError(tr('failSnapshot'), e) - } finally { - setSnapBusy('') - } - } - const handleRestoreSnapshot = async (snapName: string) => { - setRestoreTarget(null) - setSnapBusy(`restore:${snapName}`) - try { - await api.RestoreSnapshot(driverID, name, snapName) - onToast(tr('toastSnapshotRestored', { name: snapName })) - loadSnapshots() - } catch (e) { - onError(tr('failSnapshot'), e) - } finally { - setSnapBusy('') - } - } - const handleDeleteSnapshot = async (snapName: string) => { - setSnapBusy(`delete:${snapName}`) - try { - await api.DeleteSnapshot(driverID, name, snapName) - onToast(tr('toastSnapshotDeleted', { name: snapName })) - loadSnapshots() - } catch (e) { - onError(tr('failSnapshot'), e) - } finally { - setSnapBusy('') - } - } - const formatSnapTime = (sec: number) => { - if (!sec) return '' - try { - const loc = locale === 'en-XA' ? 'en-US' : locale - return new Intl.DateTimeFormat(loc, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }).format(new Date(sec * 1000)) - } catch { - return '' - } - } // One primary action per state (see docs/design-guidelines.md): Start while // stopped, Resume while suspended, Show Window while running. Ctrl+Enter triggers it (App.tsx). @@ -638,314 +315,131 @@ export const VMPage: React.FC = ({ // "More" menu, grouped by purpose with destructive items last (see docs/design-guidelines.md). const menu = ( - { - if (o) morePointerClosed.current = false - setMoreMenuOpen(o) - }} - > - - - - - - - { - if (!(e.target as HTMLElement | null)?.closest('[data-disabled]')) { - morePointerClosed.current = true - } - }} - onKeyDownCapture={() => { morePointerClosed.current = false }} - onPointerDownOutside={() => { morePointerClosed.current = true }} - onCloseAutoFocus={(e) => { - if (renameFromMenu.current) { - renameFromMenu.current = false - e.preventDefault() - nameInputRef.current?.focus() - return - } - if ( - moreOpenedByPointer.current - || morePointerClosed.current - || hasVisibleDialog() - ) { - e.preventDefault() - } - }} - > - {running && ( - <> - {features.fullscreen && detail?.graphics !== 'vmware-svga' && ( - onAction('fullscreen')}> - {stats?.window_fullscreen ? : } - {tr(stats?.window_fullscreen ? 'exitFullscreen' : 'enterFullscreen')} - {fullscreenHotkey && {fullscreenHotkey}} - - )} - onAction('restart')}> - {tr('restart')} - - {features.sendText && ( - <> - onAction('sendText')}> - {tr('sendText')} - - onAction('type')}> - {tr('typeClipboard')} - - - )} - {features.screenshot && ( - onAction('screenshot')}> - {tr('copyScreenshot')} - - )} - - - )} - {!isMacOSDriver && ( - <> - {features.clone && ( - onAction('cloneVM')}> - {tr('cloneVM')} - - )} - {features.affinity && ( - - {tr('affinityMenu')} - - )} - { renameFromMenu.current = true; startRename() }}> - {tr('displayNameEditEllipsis')} - - - - )} - {detail && ( - <> - {installing ? ( - onAction('finishInstall')}> - {tr('finishInstall')} - - ) : ( - <> - onAction('enterRecovery')}> - {tr('enterRecovery')} - - onAction('cloneVM')}> - {tr('cloneVM')} - - - )} - - {tr('affinityMenu')} - - { renameFromMenu.current = true; startRename() }}> - {tr('displayNameEditEllipsis')} - - - - )} - {isMacOSDriver && ( - onAction('openFolder')}> - {tr('openFolder')} + { + if (!renameFromMenu.current) return false + renameFromMenu.current = false + nameInputRef.current?.focus() + return true + }}> + {running && ( + <> + {features.fullscreen && detail?.graphics !== 'vmware-svga' && ( + onAction('fullscreen')}> + {stats?.window_fullscreen ? : } + {tr(stats?.window_fullscreen ? 'exitFullscreen' : 'enterFullscreen')} + {fullscreenHotkey && {fullscreenHotkey}} )} - - {tr('viewLogs')} + onAction('restart')}> + {tr('restart')} - onAction('exportDiagnostics')}> - {tr('exportDiagnostics')} - - {toolbarMenus.map((m) => { - const title = locText(m.title, locale, m.id) - return ( - onPluginCommand(m.pluginId ?? '', m.command, title)} - > - {title} + {features.sendText && ( + <> + onAction('sendText')}> + {tr('sendText')} - ) - })} + onAction('type')}> + {tr('typeClipboard')} + + + )} + {features.screenshot && ( + onAction('screenshot')}> + {tr('copyScreenshot')} + + )} - {suspended && ( - onAction('discardSuspend')}> - {tr('discardSuspend')} + + )} + {!isMacOSDriver && ( + <> + {features.clone && ( + onAction('cloneVM')}> + {tr('cloneVM')} )} - {(running || transitioning) && ( - onAction('forceStop')}> - {tr('forceStop')} + {features.affinity && ( + + {tr('affinityMenu')} )} - - {tr('delete')} + { renameFromMenu.current = true; startRename() }}> + {tr('displayNameEditEllipsis')} - - - + + + )} + {detail && ( + <> + {installing ? ( + onAction('finishInstall')}> + {tr('finishInstall')} + + ) : ( + <> + onAction('enterRecovery')}> + {tr('enterRecovery')} + + onAction('cloneVM')}> + {tr('cloneVM')} + + + )} + + {tr('affinityMenu')} + + { renameFromMenu.current = true; startRename() }}> + {tr('displayNameEditEllipsis')} + + + + )} + {isMacOSDriver && ( + onAction('openFolder')}> + {tr('openFolder')} + + )} + + {tr('viewLogs')} + + onAction('exportDiagnostics')}> + {tr('exportDiagnostics')} + + {toolbarMenus.map((m) => { + const title = locText(m.title, locale, m.id) + return ( + onPluginCommand(m.pluginId ?? '', m.command, title)} + > + {title} + + ) + })} + + {suspended && ( + onAction('discardSuspend')}> + {tr('discardSuspend')} + + )} + {(running || transitioning) && ( + onAction('forceStop')}> + {tr('forceStop')} + + )} + + {tr('delete')} + + ) - // Summary presents each fact once in user-facing words; raw upstream values stay in "Technical details". - const specs: Spec[] = [] - if (detail) { - const live = running && !!stats - const cpuPct = live ? clampPct(stats!.cpu_percent || 0) : 0 - const memGB = parseMemoryGB(detail.memory) ?? 0 - const rss = live ? stats!.memory_rss_bytes : 0 - const memPct = memGB > 0 && rss > 0 ? clampPct((rss / (memGB * 1024 ** 3)) * 100) : 0 - const diskKnown = !!stats && stats.disk_virtual_bytes > 0 && stats.disk_actual_bytes > 0 - const diskPct = diskKnown ? clampPct((stats!.disk_actual_bytes / stats!.disk_virtual_bytes) * 100) : 0 - const mem = formatMemory(detail.memory, locale) - - specs.push( - { - key: 'cpu', label: tr('factCPU'), icon: