Compare commits

...
18 Commits
Author SHA1 Message Date
YXC0915 d8c9abc3df fix(cli): route ARM and Intel disk options separately 2026-12-06 00:12:34 +08:00
YXC0915 ea6390e8ca feat: download ARM restore images and isolate runtime selection 2026-12-06 00:09:59 +08:00
YXC0915 44905aaa17 fix(stambha): report the newest unusable runtime 2026-12-06 00:03:06 +08:00
YXC0915 92573ce550 feat: support the QEMU Stambha ARM64 preview runtime 2026-12-06 00:03:06 +08:00
YXC0915 1d15e41482 ci: shorten Windows checkout paths for Unix socket tests
Windows CI / verify (push) Successful in 6m45s
2026-12-05 21:23:41 +08:00
YXC0915 c08ddd7b48 ci: run Windows verification on Gitea
Windows CI / verify (push) Failing after 2m35s
2026-12-05 21:11:03 +08:00
千川白浪 9006e6d9a7 refactor: 抽离 HostAPIService 并将 internal/plugin 拆分为四层无环子包 (#202)
CI / verify (push) Canceled after 0s
CI / rolling-release (push) Canceled after 0s
2026-12-05 06:05:41 -07:00
千川白浪 107a8d73e0 refactor: 收拢核心管线、强化错误处理、优化热路径与更新体积 (#200)
* refactor: 收拢核心管线、强化错误处理、优化热路径与更新体积

* fix: preserve download recovery and bound PBZX decoding

Keep VM diagnostics available during plugin initialization failures and verify settings through the unified driver lifecycle.
2026-12-05 20:54:41 +08:00
千川白浪 96ea9928e0 fix: 按提交标题触发滚动开发版构建(#199) 2026-12-05 20:14:50 +08:00
千川白浪 08409a1fa3 fix: 移除虚拟机修饰键重映射和宿主机全局热键拦截(#198) 2026-12-05 19:48:11 +08:00
千川白浪 bff26d8fe1 fix: 恢复移动硬盘更换盘符后的虚拟机注册路径(#197) 2026-12-05 19:45:17 +08:00
cosimawei c7419e7196 fix: 插件市场直接安装推荐版本(#195) 2026-12-05 19:40:13 +08:00
千川白浪 1e1649ed03 Merge pull request #189 from reiasu2/feat/auto-resolution
feat(display): add automatic per-display HiDPI resolution mode
2026-12-05 18:20:17 +08:00
Nwflower 6388865cbb fix(display): honor runtime VM screen environment 2026-12-05 03:13:28 -07:00
千川白浪 6f22f20fae Merge pull request #194 from Nwflower/fix/auto-gpu-on-stale-vulkan-manifest
fix(vm): fall back to automatic GPU selection for stale Vulkan manifests
2026-12-05 18:10:53 +08:00
Nwflower e180b55a7b fix(vm): fall back to automatic GPU selection for stale Vulkan manifests 2026-12-05 02:34:20 -07:00
棠渚听潮 e0a25bb243 fix(display): address PR #189 review feedback on guest_lang order and pending change merge 2026-12-05 16:19:43 +08:00
棠渚听潮 e25c7952ca feat(display): add automatic per-display HiDPI resolution mode 2026-12-05 16:02:42 +08:00
234 changed files with 9078 additions and 6662 deletions

No files matched your search

+115
View File
@@ -0,0 +1,115 @@
name: Windows CI
on:
push:
branches: [main]
workflow_dispatch:
concurrency:
group: reims-windows-ci-${{ github.ref }}
cancel-in-progress: true
env:
REIMS_CI_WORKSPACE: D:/RgCI/${{ github.run_id }}-${{ github.run_attempt }}
GOCACHE: D:/RgCI/${{ github.run_id }}-${{ github.run_attempt }}/.debug/cache/go-build
jobs:
verify:
runs-on: reims-windows-x64
timeout-minutes: 30
steps:
- name: Check out the triggering commit
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true
if (Test-Path -LiteralPath $env:REIMS_CI_WORKSPACE) { throw 'The CI checkout directory already exists' }
New-Item -ItemType Directory -Path $env:REIMS_CI_WORKSPACE -Force | Out-Null
Set-Location -LiteralPath $env:REIMS_CI_WORKSPACE
git init .
git remote add origin "$env:GITHUB_SERVER_URL/$env:GITHUB_REPOSITORY.git"
git fetch --depth=1 origin $env:GITHUB_SHA
git checkout --detach FETCH_HEAD
if ((git rev-parse HEAD) -ne $env:GITHUB_SHA) { throw 'Unexpected checkout commit' }
- name: Verify installed build tools
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true
git --version
go version
node --version
pnpm --version
- name: Verify CHANGELOG.md matches current version
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
node scripts/changelog.mjs check
if ($LASTEXITCODE -ne 0) { throw 'Changelog validation failed' }
$verFile = Get-Content -Raw -LiteralPath 'internal/version/version.go'
if ($verFile -notmatch 'var\s+Version\s*=\s*"(v[^"]+)"') {
throw 'Could not parse Version from internal/version/version.go'
}
$ver = $Matches[1]
New-Item -ItemType Directory -Force -Path .debug/runs/ci | Out-Null
$tmp = Join-Path $PWD ".debug/runs/ci/release-notes-$ver.md"
& ./scripts/build-release-notes.ps1 -Tag $ver -OutFile $tmp
"REIMS_APP_VERSION=$ver" >> $env:GITHUB_ENV
Write-Host "PASS CHANGELOG.md contains valid release notes for $ver ($((Get-Item -LiteralPath $tmp).Length) bytes)"
- name: Workspace hygiene
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
shell: pwsh
run: node scripts/debug/check.mjs
- name: Install frontend dependencies
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
shell: pwsh
run: pnpm --dir frontend install --frozen-lockfile
- name: CI tests
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
shell: pwsh
run: node scripts/test.mjs ci
- name: Bundle frontend
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
shell: pwsh
run: pnpm --dir frontend bundle
- name: Build reims-go.exe (window + command-line mode)
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
shell: pwsh
run: |
$env:GOTMPDIR = (Resolve-Path .debug/runs/ci).Path
$exe = '.debug/runs/ci/reims-go.exe'
go vet -tags desktop,production .
if ($LASTEXITCODE -ne 0) { throw 'Go desktop vet failed' }
go build -trimpath -tags desktop,production -ldflags "-H windowsgui" -o $exe .
if ($LASTEXITCODE -ne 0) { throw 'Go desktop build failed' }
./scripts/check-release-artifact.ps1 -Executable $exe -Version $env:REIMS_APP_VERSION
- name: WebView2 first-launch smoke
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
timeout-minutes: 3
run: node scripts/test.mjs webview2 .debug/runs/ci/reims-go.exe
- name: Remove the CI checkout
if: always()
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
if (!(Test-Path -LiteralPath $env:REIMS_CI_WORKSPACE)) { return }
$checkout = Get-Item -LiteralPath $env:REIMS_CI_WORKSPACE
$parent = Get-Item -LiteralPath 'D:/RgCI'
if ($checkout.Parent.FullName -ne $parent.FullName -or
$checkout.Name -notmatch '^[0-9]+-[0-9]+$' -or
($checkout.Attributes -band [IO.FileAttributes]::ReparsePoint) -or
($parent.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
throw 'Refusing to remove an unexpected CI checkout path'
}
Remove-Item -LiteralPath $checkout.FullName -Recurse -Force
+9 -2
View File
@@ -45,8 +45,15 @@ jobs:
PREVIOUS_SHA: ${{ github.event.before }}
shell: pwsh
run: |
$publish = $true
if ($env:PREVIOUS_SHA -notmatch '^0+$') {
# Read the commit object so shallow checkouts retain its parent headers.
$commitLines = @(git cat-file commit HEAD)
if ($LASTEXITCODE -ne 0) { throw 'Could not read the main commit' }
$headerEnd = [Array]::IndexOf($commitLines, '')
if ($headerEnd -lt 1) { throw 'Could not locate the main commit message' }
$parents = @($commitLines[0..($headerEnd - 1)] -like 'parent *')
$subject = $commitLines[$headerEnd + 1]
$publish = $parents.Count -le 1 -and $subject -like '*#*' -and $subject -notlike '*docs*'
if ($publish -and $env:PREVIOUS_SHA -notmatch '^0+$') {
git fetch --depth=1 origin $env:PREVIOUS_SHA
if ($LASTEXITCODE -ne 0) { throw 'Could not fetch the previous main commit' }
$changed = git diff --name-only $env:PREVIOUS_SHA HEAD -- . ':(exclude)docs/**' ':(exclude)README.md' ':(exclude,glob)README.*.md' ':(exclude)AGENTS.md' ':(exclude).github/ISSUE_TEMPLATE/**' ':(exclude).github/PULL_REQUEST_TEMPLATE.md' ':(exclude).github/readme/**'
+2
View File
@@ -137,6 +137,8 @@ jobs:
- name: Build Windows x64 binary
shell: pwsh
env:
CGO_ENABLED: "0"
run: |
$ErrorActionPreference = 'Stop'
$ver = $env:DEV_VERSION
+2
View File
@@ -103,6 +103,8 @@ jobs:
- name: Build Windows x64 binary
shell: pwsh
env:
CGO_ENABLED: "0"
run: |
$ErrorActionPreference = 'Stop'
$tag = $env:RELEASE_TAG
+7
View File
@@ -0,0 +1,7 @@
{
"group": "new",
"order": 0,
"authors": ["reiasu2"],
"zh": "虚拟机可在冷启动时自动选用当前目标显示器的推荐分辨率。",
"en": "VMs can automatically use the target monitor's recommended resolution on cold start."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "chores",
"order": 0,
"authors": ["Nwflower"],
"zh": "滚动开发版仅在合入主分支的提交标题包含 `#` 且不包含 `docs` 时自动构建。",
"en": "Automatically build rolling Dev releases only when the commit title on the main branch contains `#` and does not contain `docs`."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "improvements",
"order": 0,
"authors": ["cosimawei"],
"zh": "在插件市场点击安装或更新时直接使用市场推荐的最新版本。",
"en": "Install or update directly to the latest version offered by the plugin market."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "移动硬盘换盘符后,即使旧版已保存新的数据目录,客户端启动或重新选择目录时仍会修复默认位置虚拟机的旧路径。([#181](https://github.com/Nwflower/Reims-Go/issues/181))",
"en": "Repair stale paths for VMs in the default location when the client opens or reselects a data folder after an external drive changes letters, even if an older version already saved the new folder. ([#181](https://github.com/Nwflower/Reims-Go/issues/181))"
}
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "虚拟机的 Vulkan 清单丢失或无法枚举显卡时,客户端会保存唯一匹配的新清单,找不到时改为自动选卡,再继续启动。",
"en": "If a VM's Vulkan manifest is missing or cannot enumerate GPUs, the client saves the only matching replacement if one exists, otherwise selects Automatic, then continues startup."
}
@@ -0,0 +1,7 @@
{
"group": "improvements",
"order": 10,
"authors": ["Nwflower"],
"zh": "应用内更新改为优先下载已校验的 `.zip` 压缩包(更新流量减少约 62%),并优化物理桥接转发吞吐与离线安装镜像 PBZX 并发解压速度。",
"en": "Download verified `.zip` release archives for in-app updates (~62% smaller update downloads), reduce per-packet allocations in the packet bridge, and parallelize PBZX chunk decompression for offline installer packages."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "removals",
"order": 0,
"authors": ["Nwflower"],
"zh": "移除按虚拟机设置的修饰键重映射和「拦截宿主机全局热键」。升级后,原有设置停止生效,虚拟机恢复默认按键处理。",
"en": "Remove per-VM modifier-key remapping and host global shortcut blocking. Existing settings stop taking effect after upgrading, and VMs return to default keyboard handling."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "new",
"order": 0,
"authors": ["yxc0915"],
"zh": "支持在 Windows x86-64 上使用 Stambha 实验运行时启动 ARM macOS。导入配套运行时后,可从已有的启动介质和虚拟磁盘创建虚拟机。",
"en": "Run ARM macOS on Windows x86-64 with the Stambha preview runtime. Import the matching runtime to create a VM from existing boot media and a virtual disk."
}
+30
View File
@@ -0,0 +1,30 @@
# 运行 ARM macOS 实验版
ARM 实验运行时通过 QEMU/WHPX 和 Stambha 在 Windows x86-64 上运行 ARM macOS。使用同一预览配套的 Reims-Go 客户端和 `stambha-hosted` 运行时包。运行时可以和现有 Intel macOS 运行时共存。
## 准备
- Windows x86-64 主机,启用 Windows 虚拟机监控程序平台(WHPX),安装支持 Vulkan 的显卡驱动。
- 一套你自己的 Stambha 启动介质和与之匹配的 ARM macOS 虚拟磁盘。启动目录至少包含 `EFI/stela/stela.cfg`,其中的磁盘分区标识须与虚拟磁盘一致。从目录启动时,客户端在 VM 的独立引导目录中放入运行时自带的 Stambha EFI。
- 为每台运行中的虚拟机准备独立可写副本或 QCOW2 写入层。来宾写入保存在该磁盘文件中。运行时包内提供启动程序、固件和显卡组件,系统文件由用户自行准备。
macOS 27.2.1 的实验配置使用 8 个 vCPU 和 16 GiB 内存。首次登录后,系统索引和缓存初始化会影响交互速度。
## 启动
在运行时页面导入 ARM64 预览包。它以 `stambha-hosted` 类型单独安装。Intel 虚拟机继续绑定选中的 x86-64 运行时,ARM 虚拟机自动使用已安装且兼容的 ARM64 运行时。
新建虚拟机时选择「macOS ARM64(预览)」。可从 Apple 下载 macOS 27.2.1 恢复镜像,下载支持暂停和续传,文件保存到数据目录的 `images/arm64`,完成后核对 SHA-256。本预览需要先将 IPSW 制作成 Stambha 启动介质。填写准备好的启动目录及对应的可写磁盘路径后即可创建和启动。GPU 加速窗口由运行时打开。
也可在 PowerShell 中操作。将示例路径替换成自己的文件位置。
```powershell
.\reims-go.exe runtime install .\reims-stambha-runtime-win-x64-stambha-arm64-preview.2.tar.zst
.\reims-go.exe vm create --driver builtin.driver.stambha --boot-volume .\arm-boot --disk .\arm-system.qcow2 --cpus 8 --memory 16G arm-macos
.\reims-go.exe vm start --driver builtin.driver.stambha arm-macos
.\reims-go.exe vm stop --driver builtin.driver.stambha arm-macos
```
如果配置使用原始安装介质,可以用 `--usb-image` 指定文件。原始介质须预先包含与托管 Reims vGPU 相容的 Stambha EFI。首次从 IPSW 制作 ARM 安装介质仍是独立流程。
日常关机请在 macOS 的苹果菜单中选择「关机」。客户端的停止操作会向来宾发送电源按键事件。若来宾没有退出,可回到桌面完成关机。只在来宾无响应时使用强制停止。
+2 -2
View File
@@ -13,7 +13,7 @@
| 核对发布候选 | `node scripts/test.mjs release` | 使用 `desktop,production` 构建标签运行同一套 Go 检查,禁用测试结果缓存并随机化用例顺序 |
| Windows 桌面冒烟 | `node scripts/test.mjs webview2 build/bin/reims-go.exe` | 启动已构建的客户端,在真实 WebView2 中完成首启数据目录设置 |
GitHub CI 额外检查变更日志、工作区纪律、前端生产打包、Windows GUI 可执行文件的 `version` 输出与 WebView2 首启。`main` 的滚动版复用同一提交的 CI 测试,手动构建会跑 CI 测试并冒烟。带版本标签的发布与每日 Alpha 先跑发布候选测试,再对待发布的 EXE 运行桌面冒烟。两个发布流程都在上传前验证实际 EXE 的版本、ZIP 内的文件和 SHA-256 校验和。
GitHub CI 额外检查变更日志、工作区纪律、前端生产打包、Windows GUI 可执行文件的 `version` 输出与 WebView2 首启。滚动开发版检查推送到 `main` 的最新提交消息的第一行,包含 `#` 且不包含 `docs`(忽略大小写)时才复用该提交的 CI 测试自动构建。自动构建跳过有多个父提交的合并提交及纯文档推送。手动构建会跑 CI 测试并冒烟。带版本标签的发布与每日 Alpha 先跑发布候选测试,再对待发布的 EXE 运行桌面冒烟。两个发布流程都在上传前验证实际 EXE 的版本、ZIP 内的文件和 SHA-256 校验和。
桌面冒烟需要已安装 WebView2 Runtime 的 Windows 桌面会话。测试通过 Windows UI Automation 填入独立的数据目录、点击继续,检查配置和目录指针落盘,并等待运行时设置页渲染。每次运行使用独立的 WebView2 配置目录。失败时,测试入口打印保留的目录,应用日志在其中的 `app.log`。
@@ -25,7 +25,7 @@ Go 包并发默认为可用 CPU 数与 4 的较小值,每个包的运行上限
## 覆盖和后续改进
- 前端测试直接加载生产模块验证任务排序、过期事件和键位映射。涉及界面交互时优先覆盖用户可观察的状态切换,不按源码行或正则截取组件源码执行。
- 前端测试直接加载生产模块验证任务排序和过期事件。涉及界面交互时优先覆盖用户可观察的状态切换,不按源码行或正则截取组件源码执行。
- Go 单包测试验证领域规则,跨层测试保留桌面桥接、控制套接字、本地 HTTP、子进程与数据迁移等真实接口用例。异步用例通过完成信号控制时序,超时只用于报告卡死。
- 存储层测试使用真实临时目录验证配置、目录锁、版本升级、插件状态备份与损坏恢复。
- 依赖真实便携运行时、磁盘工具、引导镜像与安装包的集成用例仅在传入对应的 `REIMS_GO_TEST_*` 环境变量时运行,常规档位自动跳过。改动涉及虚拟机运行或磁盘操作时须在 Windows 宿主机实测验证。
+712
View File
@@ -0,0 +1,712 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { loadTestModule } from './load-test-module.mjs'
const mod = await loadTestModule(`
import './i18n/domains/settings.gen'
import './i18n/domains/wizard.gen'
export * from './i18n'
export * from './lib/format'
export * from './lib/displayResolution'
`)
const host4K150 = {
primary_display: { width: 3840, height: 2160, scale_pct: 150, work_width: 3840, work_height: 2088, primary: true },
display_presets: [
{ resolution: '3200x1800', label: '3200 × 1800', hidpi: true, recommended: true },
{ resolution: '2880x1620', label: '2880 × 1620', hidpi: true },
{ resolution: '2560x1440', label: '2560 × 1440', hidpi: false },
],
fullscreen_hidpi: true,
recommended_gpu: { name: 'NVIDIA GeForce RTX 4070', kind: 'discrete' },
gpus: [{ name: 'NVIDIA GeForce RTX 4070', kind: 'discrete' }],
}
const host32K200 = {
primary_display: { width: 3200, height: 2000, scale_pct: 200, work_width: 3200, work_height: 1904, primary: true },
display_presets: [
{ resolution: '2880x1800', label: '2880 × 1800', hidpi: true, recommended: true },
{ resolution: '2560x1600', label: '2560 × 1600', hidpi: true },
{ resolution: '1920x1200', label: '1920 × 1200', hidpi: false },
],
fullscreen_hidpi: true,
recommended_gpu: { name: 'Intel(R) Arc Graphics', kind: 'integrated' },
gpus: [{ name: 'Intel(R) Arc Graphics', kind: 'integrated' }],
}
test('resolveAutoDisplayPreset matches Go RecommendAutoResolution for 4K 16:9 and 3.2K 16:10', () => {
// 4K 16:9 @ 150%
const win4k = mod.resolveAutoDisplayPreset(host4K150, false, true)
assert.equal(win4k.resolution, '3200x1800')
assert.equal(win4k.hidpi, true)
const fs4kFixed = mod.resolveAutoDisplayPreset(host4K150, true, true)
assert.equal(fs4kFixed.resolution, '5120x2880')
assert.equal(fs4kFixed.hidpi, true)
assert.equal(fs4kFixed.scaleBadge, '1.5×')
const fs4kNoFixed = mod.resolveAutoDisplayPreset(host4K150, true, false)
assert.equal(fs4kNoFixed.resolution, '3840x2160')
assert.equal(fs4kNoFixed.hidpi, true)
assert.equal(fs4kNoFixed.native, true)
// 3.2K 16:10 @ 200% (scale >= 175 -> native fullscreen even with fixedModeSupported)
const win32k = mod.resolveAutoDisplayPreset(host32K200, false, true)
assert.equal(win32k.resolution, '2880x1800')
assert.equal(win32k.hidpi, true)
const fs32kFixed = mod.resolveAutoDisplayPreset(host32K200, true, true)
assert.equal(fs32kFixed.resolution, '3200x2000')
assert.equal(fs32kFixed.hidpi, true)
assert.equal(fs32kFixed.native, true)
const fs32kNoFixed = mod.resolveAutoDisplayPreset(host32K200, true, false)
assert.equal(fs32kNoFixed.resolution, '3200x2000')
assert.equal(fs32kNoFixed.hidpi, true)
assert.equal(fs32kNoFixed.native, true)
})
test('resolveAutoDisplayPreset falls back safely to 1920x1080 non-HiDPI when host display is empty or invalid (#6)', () => {
const emptyHost = {}
const winEmpty = mod.resolveAutoDisplayPreset(emptyHost, false, true)
assert.equal(winEmpty.resolution, '1920x1080')
assert.equal(winEmpty.hidpi, false)
for (const fixedModeSupported of [true, false]) {
const fsEmpty = mod.resolveAutoDisplayPreset(emptyHost, true, fixedModeSupported)
assert.equal(fsEmpty.resolution, '1920x1080')
assert.equal(fsEmpty.label, '1920 × 1080')
assert.equal(fsEmpty.hidpi, false)
assert.equal(fsEmpty.native, true)
assert.equal(fsEmpty.recommended, true)
const zeroHeightHost = {
primary_display: { width: 3200, height: 0, scale_pct: 150, primary: true },
fullscreen_hidpi: true,
}
const fsZeroHeight = mod.resolveAutoDisplayPreset(zeroHeightHost, true, fixedModeSupported)
assert.equal(fsZeroHeight.resolution, '1920x1080')
assert.equal(fsZeroHeight.label, '1920 × 1080')
assert.equal(fsZeroHeight.hidpi, false)
assert.equal(fsZeroHeight.native, true)
}
})
test('SettingsModal auto resolution never falls into custom or resBad across display and borderless switches', () => {
// Auto mode with a resolution from 4K screen, now moved to 3.2K screen where 3200x1800 is not a preset
const onLaptop = mod.deriveSettingsResolutionState({
form: { auto_resolution: true, resolution: '3200x1800', borderless: false },
displayProfile: host32K200,
fixedModeSupported: true,
forceCustomRes: false,
})
assert.equal(onLaptop.presetHit, false)
assert.equal(onLaptop.customRes, false)
assert.equal(onLaptop.resValue, mod.AUTO_RESOLUTION_OPTION)
assert.equal(onLaptop.resBad, false)
assert.equal(onLaptop.autoPreset.resolution, '2880x1800')
// Even empty or invalid resolution string must not trigger resBad while auto_resolution is on
const emptyResAuto = mod.deriveSettingsResolutionState({
form: { auto_resolution: true, resolution: '', borderless: false },
displayProfile: host4K150,
fixedModeSupported: true,
forceCustomRes: true,
})
assert.equal(emptyResAuto.customRes, false)
assert.equal(emptyResAuto.resBad, false)
assert.equal(emptyResAuto.resValue, mod.AUTO_RESOLUTION_OPTION)
// Toggling borderless in auto mode keeps auto_resolution intact and refreshes autoPreset
const borderlessPatch = mod.toggleSettingsBorderless({
borderless: true,
form: { auto_resolution: true, resolution: '3200x1800' },
displayProfile: host4K150,
targetDisplay: host4K150.primary_display,
presets: onLaptop.presets,
fsPresets: onLaptop.fsPresets,
customRes: false,
})
assert.deepEqual(borderlessPatch, { borderless: true })
const afterBorderless = mod.deriveSettingsResolutionState({
form: { auto_resolution: true, resolution: '3200x1800', borderless: true },
displayProfile: host4K150,
fixedModeSupported: true,
forceCustomRes: false,
})
assert.equal(afterBorderless.resValue, mod.AUTO_RESOLUTION_OPTION)
assert.equal(afterBorderless.autoPreset.resolution, '5120x2880')
})
test('SettingsModal dirty count, save payload, reset, and custom blur snap-back behave consistently', () => {
const baseFixed = { name: 'mac', auto_resolution: false, resolution: '3200x1800', borderless: false }
const autoPreset = mod.resolveAutoDisplayPreset(host4K150, false, true)
// Fixed -> Auto: keeps base.resolution so only auto_resolution is dirty (count = 1), save diff omits resolution
const toAuto = mod.selectSettingsResolution({
value: mod.AUTO_RESOLUTION_OPTION,
form: { resolution: '2560x1440' },
base: baseFixed,
autoPreset,
})
assert.equal(toAuto.forceCustomRes, false)
assert.deepEqual(toAuto.patch, { auto_resolution: true, resolution: '3200x1800' })
assert.equal(mod.countChangedSettingsFields(['auto_resolution']), 1)
assert.deepEqual(
mod.buildSettingsSaveDiff('mac', ['auto_resolution', 'resolution'], { ...baseFixed, auto_resolution: true, resolution: '2560x1440' }),
{ name: 'mac', auto_resolution: true },
)
// Auto -> Fixed different resolution: both fields dirty, UI count = 1, save diff sends both
assert.equal(mod.countChangedSettingsFields(['auto_resolution', 'resolution']), 1)
assert.equal(mod.countChangedSettingsFields(['auto_resolution', 'resolution', 'borderless']), 2)
assert.deepEqual(
mod.buildSettingsSaveDiff('mac', ['auto_resolution', 'resolution'], { ...baseFixed, auto_resolution: false, resolution: '2560x1440' }),
{ name: 'mac', auto_resolution: false, resolution: '2560x1440' },
)
// Selecting custom disables auto_resolution and falls back to autoPreset when empty
const toCustom = mod.selectSettingsResolution({
value: mod.CUSTOM_RESOLUTION_OPTION,
form: { resolution: '' },
base: baseFixed,
autoPreset,
})
assert.equal(toCustom.forceCustomRes, true)
assert.deepEqual(toCustom.patch, { auto_resolution: false, resolution: '3200x1800' })
// Typing a known preset in custom input snaps back to preset card on blur
const typedPreset = mod.deriveSettingsResolutionState({
form: { auto_resolution: false, resolution: '3200x1800', borderless: false },
displayProfile: host4K150,
fixedModeSupported: true,
forceCustomRes: true,
})
assert.equal(typedPreset.presetHit, true)
assert.equal(typedPreset.customRes, true)
assert.equal(
mod.shouldExitCustomResOnBlur({ autoResolution: false, forceCustomRes: true, presetHit: typedPreset.presetHit }),
true,
)
// Typing an invalid custom resolution triggers resBad and does not snap back
const typedInvalid = mod.deriveSettingsResolutionState({
form: { auto_resolution: false, resolution: 'not-a-res', borderless: false },
displayProfile: host4K150,
fixedModeSupported: true,
forceCustomRes: true,
})
assert.equal(typedInvalid.presetHit, false)
assert.equal(typedInvalid.resBad, true)
assert.equal(
mod.shouldExitCustomResOnBlur({ autoResolution: false, forceCustomRes: true, presetHit: typedInvalid.presetHit }),
false,
)
})
test('CreateWizard defaults to auto resolution and keeps preview resolution synced on borderless toggle', () => {
const init = mod.initialWizardResolution(host4K150, true)
assert.deepEqual(init, { auto_resolution: true, resolution: '3200x1800' })
const windowPresets = mod.windowDisplayPresets(host4K150, true)
const fullscreenPresets = mod.fullscreenDisplayPresets(host4K150)
// Toggling borderless ON in auto mode updates preview resolution to fullscreen auto preset
const fsOnFixed = mod.toggleWizardBorderless({
borderless: true,
opts: init,
host: host4K150,
fixedModeSupported: true,
windowPresets,
fullscreenPresets,
})
assert.deepEqual(fsOnFixed, { borderless: true, auto_resolution: true, resolution: '5120x2880' })
const fsOnNoFixed = mod.toggleWizardBorderless({
borderless: true,
opts: init,
host: host4K150,
fixedModeSupported: false,
windowPresets,
fullscreenPresets,
})
assert.deepEqual(fsOnNoFixed, { borderless: true, auto_resolution: true, resolution: '3840x2160' })
// Selecting a fixed preset turns auto_resolution off
const fixedChoice = mod.selectWizardResolution('2560x1440', mod.resolveAutoDisplayPreset(host4K150, false, true))
assert.deepEqual(fixedChoice, { auto_resolution: false, resolution: '2560x1440' })
// Selecting AUTO turns auto_resolution back on with current autoPreset
const autoChoice = mod.selectWizardResolution(mod.AUTO_RESOLUTION_OPTION, mod.resolveAutoDisplayPreset(host4K150, true, true))
assert.deepEqual(autoChoice, { auto_resolution: true, resolution: '5120x2880' })
})
test('VM summary, formatResolutionLabel, and pendingChangeText format auto_resolution in zh-CN and en-US', () => {
const trZh = (k, v) => mod.t('zh-CN', k, v)
const trEn = (k, v) => mod.t('en-US', k, v)
assert.equal(mod.formatResolutionLabel('3200x1800', true, trZh), '自动(3200 × 1800)')
assert.equal(mod.formatResolutionLabel('3200x1800', true, trEn), 'Auto (3200 × 1800)')
assert.equal(mod.formatResolutionLabel('3200x1800', false, trZh), '3200 × 1800')
assert.equal(mod.formatResolutionLabel('', true, trEn), 'Auto')
const autoDetail = {
graphics: 'reims-vgpu',
gpu: 'auto',
resolution: '3200x1800',
auto_resolution: true,
displays: 1,
}
assert.equal(mod.graphicsLabel('zh-CN', autoDetail, host4K150), 'RTX 4070 · 自动(3200 × 1800)')
assert.equal(mod.graphicsLabel('en-US', autoDetail, host4K150), 'RTX 4070 · Auto (3200 × 1800)')
const fixedDetail = { ...autoDetail, auto_resolution: false }
assert.equal(mod.graphicsLabel('en-US', fixedDetail, host4K150), 'RTX 4070 · 1800p')
const pendingOnZh = mod.pendingChangeText('zh-CN', { field: 'auto_resolution', from: 'false', to: 'true' }, host4K150)
const pendingOffEn = mod.pendingChangeText('en-US', { field: 'auto_resolution', from: 'true', to: 'false' }, host4K150)
assert.equal(pendingOnZh, '自动分辨率 关闭 → 开启')
assert.equal(pendingOffEn, 'Auto resolution On → Off')
assert.ok(!pendingOnZh.includes('auto_resolution'))
assert.ok(!pendingOffEn.includes('auto_resolution'))
})
test('vmware-svga disables and hides auto resolution across wizard, settings, and summary (#5)', () => {
// Wizard initialization: svga defaults to auto_resolution: false, reims-vgpu defaults to true
assert.deepEqual(mod.initialWizardResolution(host4K150, true, 'vmware-svga'), {
auto_resolution: false,
resolution: '3200x1800',
})
assert.deepEqual(mod.initialWizardResolution(host4K150, true, 'reims-vgpu'), {
auto_resolution: true,
resolution: '3200x1800',
})
// Switching graphics in wizard disables auto on svga, and restores auto on reims-vgpu only if user did not pick a fixed preset
const autoPreset = mod.resolveAutoDisplayPreset(host4K150, false, true)
assert.deepEqual(
mod.switchWizardGraphics({ graphics: 'vmware-svga', manualResolutionPicked: false, autoPreset }),
{ graphics: 'vmware-svga', auto_resolution: false },
)
assert.deepEqual(
mod.switchWizardGraphics({ graphics: 'reims-vgpu', manualResolutionPicked: false, autoPreset }),
{ graphics: 'reims-vgpu', auto_resolution: true, resolution: '3200x1800' },
)
assert.deepEqual(
mod.switchWizardGraphics({ graphics: 'reims-vgpu', manualResolutionPicked: true, autoPreset }),
{ graphics: 'reims-vgpu' },
)
// SettingsModal switching to svga only patches graphics and exits custom input (R2 #11)
assert.deepEqual(mod.switchSettingsGraphics('vmware-svga'), {
patch: { graphics: 'vmware-svga' },
forceCustomRes: false,
})
const svgaState = mod.deriveSettingsResolutionState({
form: { graphics: 'vmware-svga', auto_resolution: true, resolution: 'not-a-res', borderless: false },
displayProfile: host4K150,
fixedModeSupported: true,
forceCustomRes: true,
})
assert.notEqual(svgaState.resValue, mod.AUTO_RESOLUTION_OPTION)
assert.equal(svgaState.customRes, false)
assert.equal(svgaState.resBad, false)
// R2 #2: SVGA never includes the AUTO resolution card in SettingsModal or CreateWizard options
const activePresets = mod.windowDisplayPresets(host4K150, true)
const settingsSvgaOpts = mod.buildResolutionOptions({
graphics: 'vmware-svga',
autoPreset,
activePresets,
includeCustom: true,
})
const wizardSvgaOpts = mod.buildResolutionOptions({
graphics: 'vmware-svga',
autoPreset,
activePresets,
})
assert.equal(settingsSvgaOpts.some((o) => o.value === mod.AUTO_RESOLUTION_OPTION), false)
assert.equal(wizardSvgaOpts.some((o) => o.value === mod.AUTO_RESOLUTION_OPTION), false)
const settingsVgpuOpts = mod.buildResolutionOptions({
graphics: 'reims-vgpu',
autoPreset,
activePresets,
includeCustom: true,
})
const wizardVgpuOpts = mod.buildResolutionOptions({
graphics: 'reims-vgpu',
autoPreset,
activePresets,
})
assert.equal(settingsVgpuOpts[0].value, mod.AUTO_RESOLUTION_OPTION)
assert.equal(wizardVgpuOpts[0].value, mod.AUTO_RESOLUTION_OPTION)
// Settings save diff never sends auto_resolution: true for vmware-svga
assert.deepEqual(
mod.buildSettingsSaveDiff('mac', ['graphics', 'auto_resolution'], {
name: 'mac',
graphics: 'vmware-svga',
auto_resolution: true,
resolution: '1920x1080',
}),
{ name: 'mac', graphics: 'vmware-svga', auto_resolution: false },
)
// graphicsLabel never renders auto resolution label for vmware-svga
const svgaDetail = {
graphics: 'vmware-svga',
gpu: 'auto',
resolution: '3200x1800',
auto_resolution: true,
displays: 1,
}
assert.equal(mod.graphicsLabel('zh-CN', svgaDetail, host4K150), mod.t('zh-CN', 'softwareGraphics'))
assert.equal(mod.graphicsLabel('en-US', svgaDetail, host4K150), mod.t('en-US', 'softwareGraphics'))
})
test('installer wizard draft enables auto resolution by default while preserving user fixed drafts (#7)', () => {
const installerDraftVgpu = mod.initialWizardResolution(host4K150, true, 'reims-vgpu')
assert.deepEqual(installerDraftVgpu, { auto_resolution: true, resolution: '3200x1800' })
const installerDraftSvga = mod.initialWizardResolution(host4K150, true, 'vmware-svga')
assert.deepEqual(installerDraftSvga, { auto_resolution: false, resolution: '3200x1800' })
// Returning from a failed create preserves explicit auto_resolution: false
const failedFixedDraft = {
name: 'macos-tahoe',
graphics: 'reims-vgpu',
auto_resolution: false,
resolution: '2560x1440',
borderless: false,
}
const effectiveFixed = mod.resolveEffectiveWizardOpts(
failedFixedDraft,
mod.resolveAutoDisplayPreset(host32K200, false, true),
)
assert.equal(effectiveFixed.auto_resolution, false)
assert.equal(effectiveFixed.resolution, '2560x1440')
})
test('effective wizard opts track host screen changes in auto mode without mutating fixed mode (#8)', () => {
const autoOptsFrom4K = {
name: 'macos-tahoe',
graphics: 'reims-vgpu',
auto_resolution: true,
resolution: '3200x1800',
borderless: false,
}
// Host switches to 3.2K screen while wizard stays open or restores an auto draft
const effectiveOn32K = mod.resolveEffectiveWizardOpts(
autoOptsFrom4K,
mod.resolveAutoDisplayPreset(host32K200, false, true),
)
assert.equal(effectiveOn32K.auto_resolution, true)
assert.equal(effectiveOn32K.resolution, '2880x1800')
// Borderless auto mode on 4K updates to 5120x2880
const effectiveBorderless = mod.resolveEffectiveWizardOpts(
{ ...autoOptsFrom4K, borderless: true },
mod.resolveAutoDisplayPreset(host4K150, true, true),
)
assert.equal(effectiveBorderless.resolution, '5120x2880')
// Fixed mode keeps user-selected resolution even when host changes
const fixedOpts = { ...autoOptsFrom4K, auto_resolution: false, resolution: '2560x1440' }
const effectiveFixed = mod.resolveEffectiveWizardOpts(
fixedOpts,
mod.resolveAutoDisplayPreset(host32K200, false, true),
)
assert.equal(effectiveFixed.auto_resolution, false)
assert.equal(effectiveFixed.resolution, '2560x1440')
})
test('custom resolution canonicalizes on blur and save diff to match Go validator (#9)', () => {
assert.equal(mod.canonicalResolution('3200 × 1800'), '3200x1800')
assert.equal(mod.canonicalResolution(' 3200X1800 '), '3200x1800')
assert.equal(mod.canonicalResolution('2400 x 1500'), '2400x1500')
assert.equal(mod.canonicalResolution(''), '')
const presets = mod.windowDisplayPresets(host4K150, true)
// Typing a known preset with × or uppercase X snaps back and writes canonical preset value
assert.deepEqual(
mod.resolveCustomResBlur({
resolution: '3200 × 1800',
autoResolution: false,
forceCustomRes: true,
activePresets: presets,
}),
{ exitCustom: true, nextResolution: '3200x1800' },
)
assert.deepEqual(
mod.resolveCustomResBlur({
resolution: '3200X1800',
autoResolution: false,
forceCustomRes: true,
activePresets: presets,
}),
{ exitCustom: true, nextResolution: '3200x1800' },
)
// Typing a non-preset valid size canonicalizes without exiting custom input
assert.deepEqual(
mod.resolveCustomResBlur({
resolution: ' 2400 × 1500 ',
autoResolution: false,
forceCustomRes: true,
activePresets: presets,
}),
{ exitCustom: false, nextResolution: '2400x1500' },
)
// Save diff always canonicalizes resolution even if saved before blur
assert.deepEqual(
mod.buildSettingsSaveDiff('mac', ['auto_resolution', 'resolution'], {
name: 'mac',
graphics: 'reims-vgpu',
auto_resolution: false,
resolution: '3200 × 1800',
}),
{ name: 'mac', auto_resolution: false, resolution: '3200x1800' },
)
})
test('background baseline refresh syncs untouched fields so saving memory never overwrites external auto_resolution (#11)', () => {
const initialBase = {
name: 'mac',
memory: '8G',
graphics: 'reims-vgpu',
auto_resolution: true,
resolution: '3200x1800',
}
// User only edits memory
const touched = new Set(mod.expandTouchedSettingsFields(['memory']))
const editedForm = { ...initialBase, memory: '16G' }
// External CLI disables auto_resolution and sets fixed 2560x1440; background poll refreshes base
const refreshedBase = {
...initialBase,
auto_resolution: false,
resolution: '2560x1440',
}
const syncedForm = mod.syncUntouchedSettingsForm(editedForm, refreshedBase, touched)
assert.equal(syncedForm.memory, '16G')
assert.equal(syncedForm.auto_resolution, false)
assert.equal(syncedForm.resolution, '2560x1440')
// Only memory differs from refreshedBase, so save diff only sends memory
const dirtyFields = ['memory', 'auto_resolution', 'resolution'].filter(
(k) => syncedForm[k] !== refreshedBase[k],
)
assert.deepEqual(dirtyFields, ['memory'])
assert.deepEqual(mod.buildSettingsSaveDiff('mac', dirtyFields, syncedForm), {
name: 'mac',
memory: '16G',
})
// Touching resolution pairs both resolution and auto_resolution so background refresh preserves user edits
const resTouched = new Set(mod.expandTouchedSettingsFields(['resolution']))
assert.ok(resTouched.has('resolution'))
assert.ok(resTouched.has('auto_resolution'))
const editedResForm = { ...initialBase, auto_resolution: false, resolution: '1920x1080' }
const syncedWhileEditingRes = mod.syncUntouchedSettingsForm(editedResForm, refreshedBase, resTouched)
assert.equal(syncedWhileEditingRes.auto_resolution, false)
assert.equal(syncedWhileEditingRes.resolution, '1920x1080')
})
test('R2 #7: switching VMs resets settings draft to target VM baseline without leaking previous VM edits', () => {
const baseA = {
name: 'vm-a',
graphics: 'reims-vgpu',
auto_resolution: true,
resolution: '3200x1800',
memory: '8G',
}
const baseB = {
name: 'vm-b',
graphics: 'reims-vgpu',
auto_resolution: true,
resolution: '2880x1800',
memory: '16G',
}
const touchedA = new Set(mod.expandTouchedSettingsFields(['resolution', 'memory']))
const editedA = { ...baseA, auto_resolution: false, resolution: '2560x1440', memory: '12G' }
const switched = mod.reconcileSettingsFormOnBaseChange({
previousVMKey: 'builtin.driver.reims-macos:vm-a',
nextVMKey: 'builtin.driver.reims-macos:vm-b',
form: editedA,
base: baseB,
touchedFields: touchedA,
})
assert.equal(switched.resetDraft, true)
assert.deepEqual(switched.form, baseB)
const dirtyB = Object.keys(baseB).filter((k) => switched.form[k] !== baseB[k])
assert.deepEqual(dirtyB, [])
assert.deepEqual(mod.buildSettingsSaveDiff('vm-b', dirtyB, switched.form, baseB), { name: 'vm-b' })
})
test('R2 #5: internal digit spaces never match presets, keep custom input visible, and block save', () => {
const hostWith1080 = {
...host4K150,
display_presets: [
...host4K150.display_presets,
{ resolution: '1920x1080', label: '1920 × 1080', hidpi: false },
],
}
assert.equal(mod.canonicalResolution('1 920x1080'), '1 920x1080')
assert.equal(mod.normalizeResolution('1 920x1080'), '1 920x1080')
assert.equal(mod.isValidResolution('1 920x1080'), false)
// Even when forceCustomRes is false (custom input opened automatically due to non-preset old value),
// pasting "1 920x1080" must NOT match 1920x1080 preset, must keep input visible, and must set resBad = true.
const badState = mod.deriveSettingsResolutionState({
form: { graphics: 'reims-vgpu', auto_resolution: false, resolution: '1 920x1080', borderless: false },
displayProfile: hostWith1080,
fixedModeSupported: true,
forceCustomRes: false,
})
assert.equal(badState.presetHit, false)
assert.equal(badState.customRes, true)
assert.equal(badState.resBad, true)
// Spaces around × or uppercase X still match preset and canonicalize to 3200x1800
assert.equal(mod.isValidResolution('3200 × 1800'), true)
assert.equal(mod.isValidResolution('3200X1800'), true)
const goodState = mod.deriveSettingsResolutionState({
form: { graphics: 'reims-vgpu', auto_resolution: false, resolution: '3200 × 1800', borderless: false },
displayProfile: hostWith1080,
fixedModeSupported: true,
forceCustomRes: false,
})
assert.equal(goodState.presetHit, true)
assert.equal(goodState.matchedPreset?.resolution, '3200x1800')
assert.equal(goodState.resBad, false)
assert.deepEqual(
mod.resolveCustomResBlur({
resolution: '3200 × 1800',
autoResolution: false,
forceCustomRes: false,
activePresets: goodState.activePresets,
}),
{ exitCustom: true, nextResolution: '3200x1800' },
)
})
test('R2 #11: switching vGPU+auto to SVGA and resetting graphics leaves 0 changes; saving SVGA disables auto', () => {
const base = {
name: 'mac',
graphics: 'reims-vgpu',
auto_resolution: true,
resolution: '3200x1800',
}
// Temporarily switch to SVGA
const svgaSwitch = mod.switchSettingsGraphics('vmware-svga')
assert.deepEqual(svgaSwitch, { patch: { graphics: 'vmware-svga' }, forceCustomRes: false })
const svgaForm = { ...base, ...svgaSwitch.patch }
assert.equal(svgaForm.auto_resolution, true)
// Resetting graphics row back to reims-vgpu restores clean form with 0 changes
const resetForm = { ...svgaForm, graphics: base.graphics }
const dirtyAfterReset = ['graphics', 'auto_resolution', 'resolution'].filter((k) => resetForm[k] !== base[k])
assert.deepEqual(dirtyAfterReset, [])
assert.equal(mod.countChangedSettingsFields(dirtyAfterReset), 0)
assert.deepEqual(mod.buildSettingsSaveDiff('mac', dirtyAfterReset, resetForm, base), { name: 'mac' })
// Saving SVGA directly sends graphics: 'vmware-svga' and turns off auto_resolution when base had it on
const dirtyOnSvga = ['graphics', 'auto_resolution', 'resolution'].filter((k) => svgaForm[k] !== base[k])
assert.deepEqual(dirtyOnSvga, ['graphics'])
assert.deepEqual(mod.buildSettingsSaveDiff('mac', dirtyOnSvga, svgaForm, base), {
name: 'mac',
graphics: 'vmware-svga',
auto_resolution: false,
})
// If base already had auto_resolution: false, saving SVGA only sends graphics
const baseFixed = { ...base, auto_resolution: false }
assert.deepEqual(mod.buildSettingsSaveDiff('mac', ['graphics'], { ...baseFixed, graphics: 'vmware-svga' }, baseFixed), {
name: 'mac',
graphics: 'vmware-svga',
})
})
test('R2 #3: CreateWizard preserves manual fixed resolution across SVGA create failure and return to vGPU', () => {
const autoPreset = mod.resolveAutoDisplayPreset(host4K150, false, true)
// Step 1: User starts on vGPU and manually picks fixed 2560x1440
let opts = {
name: 'macos-tahoe',
graphics: 'reims-vgpu',
...mod.initialWizardResolution(host4K150, true, 'reims-vgpu'),
borderless: false,
}
let manualResolutionPicked = true
opts = { ...opts, ...mod.selectWizardResolution('2560x1440', autoPreset) }
assert.equal(opts.auto_resolution, false)
assert.equal(opts.resolution, '2560x1440')
// Step 2: User switches to SVGA and submits; create fails and saves draft with manualResolution: true
opts = { ...opts, ...mod.switchWizardGraphics({ graphics: 'vmware-svga', manualResolutionPicked, autoPreset }) }
const failedDraft = {
opts: mod.resolveEffectiveWizardOpts(opts, autoPreset),
step: 5,
manualResolution: manualResolutionPicked,
}
assert.equal(failedDraft.opts.graphics, 'vmware-svga')
assert.equal(failedDraft.opts.auto_resolution, false)
assert.equal(failedDraft.opts.resolution, '2560x1440')
// Step 3: Reopen wizard from failed draft and switch back to vGPU
const restoredManual = mod.initialWizardManualResolution(failedDraft)
assert.equal(restoredManual, true)
const backToVgpu = mod.switchWizardGraphics({
graphics: 'reims-vgpu',
manualResolutionPicked: restoredManual,
autoPreset,
})
const restoredOpts = { ...failedDraft.opts, ...backToVgpu }
assert.equal(restoredOpts.graphics, 'reims-vgpu')
assert.equal(restoredOpts.auto_resolution, false)
assert.equal(restoredOpts.resolution, '2560x1440')
// Fallback behavior when draft.manualResolution is omitted
assert.equal(mod.initialWizardManualResolution(null), false)
assert.equal(
mod.initialWizardManualResolution({ opts: { graphics: 'vmware-svga', auto_resolution: false } }),
false,
)
assert.equal(
mod.initialWizardManualResolution({ opts: { graphics: 'reims-vgpu', auto_resolution: false } }),
true,
)
})
test('R3 #3 & #6: turning off auto includes fixed resolution; switching to SVGA omits hidden invalid resolution', () => {
// R3 #3: switching from auto back to fixed card matching display-0 resolution still submits explicit resolution
// so any per-display list (e.g. 3200x1800,2560x1440) is replaced uniformly.
const baseAuto = { name: 'mac', graphics: 'reims-vgpu', auto_resolution: true, resolution: '3200x1800' }
const formFixed = { ...baseAuto, auto_resolution: false, resolution: '3200x1800' }
assert.deepEqual(mod.buildSettingsSaveDiff('mac', ['auto_resolution'], formFixed, baseAuto), {
name: 'mac',
auto_resolution: false,
resolution: '3200x1800',
})
// R3 #6: typing invalid custom resolution then switching to SVGA does not submit hidden invalid resolution
const baseVgpu = { name: 'mac', graphics: 'reims-vgpu', auto_resolution: false, resolution: '2560x1440' }
const formSvgaWithHiddenInvalid = {
...baseVgpu,
graphics: 'vmware-svga',
resolution: '1 920x1080',
}
assert.deepEqual(
mod.buildSettingsSaveDiff('mac', ['graphics', 'resolution'], formSvgaWithHiddenInvalid, baseVgpu),
{
name: 'mac',
graphics: 'vmware-svga',
},
)
})
-150
View File
@@ -1,150 +0,0 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { loadTestModule } from './load-test-module.mjs'
const { createKeymapRequests, keymapPresetUpdate, keymapStatusHint, keymapUpdate, visibleKeymapPresets } = await loadTestModule(`export * from './lib/vmKeymap'`)
const off = { preset: 'off', bindings: {}, capture_host_shortcuts: false }
const custom = { preset: 'custom', bindings: { lwin: 'lcmd' }, capture_host_shortcuts: true }
test('switching presets preserves shortcut capture and carries bindings into custom', () => {
const preset = { ...custom, preset: 'win_to_cmd' }
assert.equal(keymapPresetUpdate(preset, 'win_to_cmd'), undefined)
assert.deepEqual(keymapPresetUpdate(preset, 'custom'), custom)
assert.deepEqual(keymapPresetUpdate(custom, 'off'), { ...off, capture_host_shortcuts: true })
assert.deepEqual(keymapPresetUpdate(off, 'custom'), { ...off, preset: 'custom' })
})
test('editing one binding preserves the other bindings, preset, and shortcut capture', () => {
assert.deepEqual(keymapUpdate(custom, { bindings: { lalt: 'disabled' } }), {
...custom,
bindings: { lwin: 'lcmd', lalt: 'disabled' },
})
})
test('toggling shortcut capture preserves the preset and bindings', () => {
const captureOff = { ...custom, capture_host_shortcuts: false }
assert.deepEqual(keymapUpdate(captureOff, { capture_host_shortcuts: true }), custom)
assert.deepEqual(keymapUpdate(custom, { capture_host_shortcuts: false }), captureOff)
assert.deepEqual(keymapUpdate(off, { capture_host_shortcuts: true }), { ...off, capture_host_shortcuts: true })
})
test('a pending write for one VM does not block or overwrite another VM', async () => {
const saved = Promise.withResolvers()
const writes = []
let active = 'a'
let state = {}
const requests = createKeymapRequests({
async GetVMKeymap(name) {
assert.equal(name, 'b')
return off
},
SetVMKeymap(name, request) {
writes.push([name, request])
return saved.promise
},
}, () => active, (patch) => Object.assign(state, patch))
const write = requests.write('a', custom)
await requests.write('a', off)
assert.deepEqual(writes, [['a', custom]])
assert.equal(state.busy, true)
active = 'b'
state = requests.initial('b')
await requests.watch('b').refresh()
saved.resolve(custom)
await write
assert.deepEqual(state, { keymap: off, busy: false, error: '' })
assert.equal(requests.initial('a').busy, false)
})
test('a failed keymap read recovers on the next refresh', async () => {
let fail = true
const state = {}
const requests = createKeymapRequests({
async GetVMKeymap() {
if (fail) throw new Error('temporary')
return off
},
}, () => 'vm', (patch) => Object.assign(state, patch))
const watch = requests.watch('vm')
await watch.refresh()
assert.equal(state.error, 'temporary')
fail = false
await watch.refresh()
assert.deepEqual(state, { keymap: off, error: '' })
})
test('a read started before a write cannot restore the old keymap', async () => {
const previousRead = Promise.withResolvers()
const state = {}
const requests = createKeymapRequests({
GetVMKeymap: () => previousRead.promise,
SetVMKeymap: async () => custom,
}, () => 'vm', (patch) => Object.assign(state, patch))
const read = requests.watch('vm').refresh()
await requests.write('vm', custom)
previousRead.resolve(off)
await read
assert.deepEqual(state, { keymap: custom, busy: false, error: '' })
})
test('visibleKeymapPresets hides win_to_cmd on modern runtimes unless already selected', () => {
assert.deepEqual(visibleKeymapPresets('off', false), ['off', 'swap_alt_win', 'custom'])
assert.deepEqual(visibleKeymapPresets('swap_alt_win', false), ['off', 'swap_alt_win', 'custom'])
assert.deepEqual(visibleKeymapPresets('custom', false), ['off', 'swap_alt_win', 'custom'])
assert.deepEqual(visibleKeymapPresets('win_to_cmd', false), ['off', 'win_to_cmd', 'swap_alt_win', 'custom'])
assert.deepEqual(visibleKeymapPresets('off', true), ['off', 'win_to_cmd', 'swap_alt_win', 'custom'])
assert.deepEqual(visibleKeymapPresets('swap_alt_win', true), ['off', 'win_to_cmd', 'swap_alt_win', 'custom'])
})
test('keymapStatusHint returns null when both preset and shortcut capture are off', () => {
const base = {
preset: 'off',
bindings: {},
capture_host_shortcuts: false,
needs_guest_tools: false,
guest_connected: true,
guest_agent_version: 5,
required_agent_version: 5,
input_service_available: true,
guest_keymap_active: true,
hook_active: true,
running: true,
}
assert.equal(keymapStatusHint(base), null)
})
test('keymapStatusHint resolves priority when only capture_host_shortcuts is enabled', () => {
const base = {
preset: 'off',
bindings: {},
capture_host_shortcuts: true,
needs_guest_tools: false,
guest_connected: false,
guest_agent_version: 0,
required_agent_version: 4,
input_service_available: true,
guest_keymap_active: false,
hook_active: true,
running: true,
}
assert.deepEqual(keymapStatusHint(base), { key: 'keymapRunning' })
assert.deepEqual(keymapStatusHint({ ...base, hook_active: false }), { key: 'keymapInactive' })
assert.deepEqual(keymapStatusHint({ ...base, running: false }), { key: 'keymapStopped' })
assert.deepEqual(keymapStatusHint({ ...base, input_service_available: false, running: false }), { key: 'keymapInputServiceRequired' })
assert.deepEqual(keymapStatusHint({ ...base, needs_guest_tools: true, guest_connected: false }), { key: 'keymapWaiting' })
assert.deepEqual(
keymapStatusHint({ ...base, needs_guest_tools: true, guest_connected: true, guest_agent_version: 3, required_agent_version: 4 }),
{ key: 'keymapUpgrade', vars: { version: 4 } },
)
assert.deepEqual(
keymapStatusHint({ ...base, needs_guest_tools: true, guest_connected: true, guest_agent_version: 4, required_agent_version: 4, guest_keymap_active: false }),
{ key: 'keymapPending' },
)
assert.deepEqual(
keymapStatusHint({ ...base, needs_guest_tools: true, guest_connected: true, guest_agent_version: 4, required_agent_version: 4, guest_keymap_active: true }),
{ key: 'keymapRunning' },
)
})
+39 -6
View File
@@ -30,11 +30,39 @@ function isEmptyBlock(block) {
return ts.isBlock(block) && block.statements.every((stmt) => ts.isEmptyStatement(stmt))
}
function isEmptyFunctionBody(expr) {
function isSilentLiteralExpr(expr) {
let current = expr
while (ts.isParenthesizedExpression(current)) current = current.expression
if (
current.kind === ts.SyntaxKind.NullKeyword ||
current.kind === ts.SyntaxKind.TrueKeyword ||
current.kind === ts.SyntaxKind.FalseKeyword ||
ts.isStringLiteralLike(current) ||
ts.isNumericLiteral(current) ||
ts.isVoidExpression(current)
) {
return true
}
if (ts.isIdentifier(current) && current.text === 'undefined') return true
if (ts.isArrayLiteralExpression(current) && current.elements.length === 0) return true
if (ts.isObjectLiteralExpression(current) && current.properties.length === 0) return true
return false
}
function isSilentFunctionBody(expr) {
let current = expr
while (ts.isParenthesizedExpression(current)) current = current.expression
if (ts.isArrowFunction(current) || ts.isFunctionExpression(current)) {
return isEmptyBlock(current.body)
if (isEmptyBlock(current.body)) return true
if (!ts.isBlock(current.body) && isSilentLiteralExpr(current.body)) return true
if (
ts.isBlock(current.body) &&
current.body.statements.length === 1 &&
ts.isReturnStatement(current.body.statements[0]) &&
(!current.body.statements[0].expression || isSilentLiteralExpr(current.body.statements[0].expression))
) {
return true
}
}
return false
}
@@ -70,9 +98,9 @@ export function findEmptyCatchesInJS(sourceText, filePath = 'sample.ts') {
record(node, 'empty-catch-clause')
} else if (ts.isCallExpression(node)) {
const method = getCalleeMethodName(node.expression)
if (method === 'catch' && node.arguments.length >= 1 && isEmptyFunctionBody(node.arguments[0])) {
if (method === 'catch' && node.arguments.length >= 1 && isSilentFunctionBody(node.arguments[0])) {
record(node.arguments[0], 'empty-promise-catch')
} else if (method === 'then' && node.arguments.length >= 2 && isEmptyFunctionBody(node.arguments[1])) {
} else if (method === 'then' && node.arguments.length >= 2 && isSilentFunctionBody(node.arguments[1])) {
record(node.arguments[1], 'empty-promise-then-reject')
}
}
@@ -321,10 +349,15 @@ test('detector self-test: catches all empty JS/TS catch forms and allows handled
'p.catch(async () => { ; })',
'p.then(ok, () => {})',
'p.then(ok, (err) => { // noop\n})',
'p.catch(() => null)',
'p.catch(() => "")',
'p.catch(() => false)',
'p.catch(() => [])',
'p.catch(() => { return null })',
].join('\n')
const badFindings = findEmptyCatchesInJS(bad, 'bad.ts')
assert.equal(badFindings.length, 11, `expected 11 findings, got ${JSON.stringify(badFindings)}`)
assert.equal(badFindings.length, 16, `expected 16 findings, got ${JSON.stringify(badFindings)}`)
const good = [
'const text = "try { a() } catch {} .catch(() => {})"',
@@ -332,7 +365,7 @@ test('detector self-test: catches all empty JS/TS catch forms and allows handled
'try { a() } catch (e) { console.warn(e) }',
'try { a() } catch { return fallback }',
'p.catch((e) => console.warn(e))',
'p.catch(() => null)',
'p.catch((e) => { console.warn(e); return null })',
'p.then(ok, (e) => handle(e))',
].join('\n')
+101 -189
View File
@@ -1,11 +1,8 @@
import { Minus, Moon, Square, Sun, X } from 'lucide-react'
import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react'
import type { WizardDraft } from './components/CreateWizard'
import { DeleteDialog } from './components/DeleteDialog'
import { ElevationDialog } from './components/ElevationDialog'
import { CloneDialog } from './components/CloneDialog'
import { AppDialogs } from './components/AppDialogs'
import { OnlineRecoveryDialog } from './macos/OnlineRecoveryDialog'
import { SendTextDialog } from './components/SendTextDialog'
import { LogPanel, LogTab } from './components/LogPanel'
import { TitleMenus } from './components/TitleMenus'
import { UpdateCapsule } from './components/UpdateCapsule'
@@ -14,8 +11,9 @@ import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Si
import { CreatingVMView } from './components/CreatingVMView'
import { VMPage } from './components/VMPage'
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 { defaultGuestLang, recommendedMemoryGB } from './lib/format'
import { initialWizardResolution } from './lib/displayResolution'
import { hasStambhaRuntime, isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints'
import { resolveFullscreenHotkey } from './lib/fullscreenHotkey'
import { LogLine, appendLog, createLogLine } from './lib/logs'
import { macOSMajor } from './macos/macosRelease'
@@ -23,7 +21,7 @@ import { creatingVMTasks, currentTask, finishedTaskTTL, isActiveInstallerTask, p
import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, notifyInteractiveThemeState } from './lib/themeEngine'
import type { UIStateSnapshot } from './lib/uiSdk'
import { hasVisibleDialog } from './lib/dialogState'
import { latestVMStats, refreshSubscribedVMStats, refreshVMStats } from './lib/vmStats'
import { refreshSubscribedVMStats, refreshVMStats } from './lib/vmStats'
import { useAppearance } from './lib/useAppearance'
import { useAppUpdate } from './lib/useAppUpdate'
import { useFileDrop } from './lib/useFileDrop'
@@ -34,18 +32,13 @@ import { closePluginDialog, closePluginView, emptyPluginViewState, matchViewCond
import { publishPluginHostEvent } from './lib/pluginViewEvents'
import { buildSafePluginAssetURL } from './lib/pluginAssets'
import { ActiveThemePayload, AppState, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMAction, VMBusyAction, VMDetail, VMInfo, VMListItem, ViewContribution } from './types'
import { Button, Tip, TooltipProvider } from './ui/controls'
import { ConfirmDialog, Modal } from './ui/dialog'
import { Tip, TooltipProvider } from './ui/controls'
import { errorToast, Toaster, type ToastInput, useToasts } from './ui/toast'
import { BrandMark, ThemeDecorations, ThemeVisualsProvider } from './ui/themeVisuals'
import { api, DROP_NETWORK_VOLUMES_DENIED, events, WindowMinimise, WindowToggleMaximise, type ElevationPrompt } from './wails'
// Opened on demand, so each is its own chunk and stays out of the startup
// bundle: the wizard, VM settings and affinity dialogs, first-run setup, and
// the Engine / Installers / Settings pages.
const CreateWizard = lazy(() => import('./components/CreateWizard').then((m) => ({ default: m.CreateWizard })))
const SettingsModal = lazy(() => import('./components/SettingsModal').then((m) => ({ default: m.SettingsModal })))
const AffinityDialog = lazy(() => import('./components/AffinityDialog').then((m) => ({ default: m.AffinityDialog })))
// bundle: first-run setup, and the Engine / Installers / Settings pages.
const Setup = lazy(() => import('./components/Setup').then((m) => ({ default: m.Setup })))
const HostView = lazy(() => import('./components/HostView').then((m) => ({ default: m.HostView })))
const ImagesPage = lazy(() => import('./components/ImagesPage').then((m) => ({ default: m.ImagesPage })))
@@ -151,7 +144,7 @@ export const App: React.FC = () => {
// Sidebar can be hidden (Ctrl+B or the title-bar toggle); remembered per user.
const [sidebarOpen, setSidebarOpen] = useState<boolean>(() => {
try { return localStorage.getItem('reims-go-sidebar') !== 'hidden' } catch { return true }
try { return localStorage.getItem('reims-go-sidebar') !== 'hidden' } catch (e) { console.warn('[app] read sidebar state failed:', e); return true }
})
const toggleSidebar = () => setSidebarOpen((open) => {
try { localStorage.setItem('reims-go-sidebar', open ? 'hidden' : 'shown') } catch (e) { console.warn('[app] persist sidebar state failed:', e) }
@@ -371,7 +364,10 @@ export const App: React.FC = () => {
let live = true
api.GetVMDetail(selectedVM.name)
.then((d) => { if (live) setDetail(d) })
.catch(() => { if (live) setDetail(null) })
.catch((e) => {
console.warn('[app] GetVMDetail failed:', selectedVM.name, e)
if (live) setDetail(null)
})
return () => { live = false }
}, [selectedVM?.name, selectedVM?.driver_id, selectedVM?.state, selectedTransition, selectedIsMacOS, detailRevision, state?.active_runtime?.commit, state?.runtime_capture_supported])
@@ -492,7 +488,8 @@ export const App: React.FC = () => {
const pending = selectedVM ? (state?.pending_changes[vmRefKey(selectedVM)] ?? []) : []
const fixedModeSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'display-fixed-mode') ?? false
const diskCacheSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'win32-native-aio') ?? false
const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime
const stambhaAvailable = hasStambhaRuntime(state?.runtimes)
const hostReady = !!state && state.host.whpx === 'ready' && (!!state.active_runtime || stambhaAvailable)
const canSuspend = state?.can_suspend ?? false
const fullscreenHotkey = state?.config.fullscreen_hotkey_enabled
? resolveFullscreenHotkey(state.config.fullscreen_hotkey)
@@ -596,9 +593,15 @@ export const App: React.FC = () => {
}
}
const folderDone = async () => {
const s = await api.GetState().catch(() => null)
if (s) setState(s)
setSetupStage(s?.active_runtime ? null : 'runtime')
try {
const s = await api.GetState()
setState(s)
setSetupStage(s?.active_runtime || hasStambhaRuntime(s?.runtimes) ? null : 'runtime')
} catch (e) {
console.warn('[app] GetState after setup failed:', e)
fail(tr('failGeneric'), e)
setSetupStage('runtime')
}
}
const showSetup = !!state && (state.needs_setup || setupStage === 'runtime')
// The data folder opened read-only (internal/dataroot): nothing in it may be
@@ -935,7 +938,7 @@ export const App: React.FC = () => {
}
const openWizard = () => {
if (!state?.active_runtime) {
if (!state?.active_runtime && !stambhaAvailable) {
setSelected(HOST_ID)
toasts.push({ kind: 'error', title: tr('noRuntimeAlert') })
return
@@ -956,6 +959,7 @@ export const App: React.FC = () => {
defaultName = `macos-tahoe-${i}`
}
const isOffline = item.kind === 'offline' && !!item.version
const graphics = state.host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga'
setWizardDraft({
step: 1,
opts: {
@@ -970,9 +974,9 @@ export const App: React.FC = () => {
disk_size: '128G',
disk_mode: 'copy',
disk_controller: 'nvme',
graphics: 'reims-vgpu',
graphics,
gpu: state.host.recommended_gpu?.vulkan_icd ?? 'auto',
resolution: recommendedResolution(state.host),
...initialWizardResolution(state.host, fixedModeSupported, graphics),
displays: 1,
borderless: false,
capture: false,
@@ -1445,148 +1449,80 @@ export const App: React.FC = () => {
/>
)}
{showWizard && state && (
<Suspense fallback={null}>
<CreateWizard
locale={locale}
host={state.host}
fixedModeSupported={fixedModeSupported}
captureSupported={state.runtime_capture_supported}
tasks={Object.values(taskMap)}
draft={wizardDraft}
onClose={() => { setShowWizard(false); setWizardDraft(null) }}
onSubmit={submitCreate}
/>
</Suspense>
)}
{showSettings && state && detail && (
<Suspense fallback={null}>
<SettingsModal
locale={locale}
detail={detail}
driverID={selectedVM?.driver_id ?? ''}
stats={latestVMStats(selectedVM?.driver_id ?? '', detail.name)}
host={state.host}
fixedModeSupported={fixedModeSupported}
diskCacheSupported={diskCacheSupported}
optimizations={state.optimizations}
running={effectiveState === 'running'}
onCopy={copy}
onDiskChanged={refresh}
onOpenAffinity={() => setAffinityTarget({ name: detail.name, driverID: selectedVM?.driver_id ?? '' })}
affinityVersion={affinityVersion}
onHostChanged={refresh}
onToast={toasts.push}
onClose={() => setShowSettings(false)}
onSaved={() => {
setShowSettings(false)
toasts.push({ kind: 'ok', title: tr(effectiveState === 'running' ? 'toastSavedNextStart' : 'toastSaved') })
refresh()
}}
/>
</Suspense>
)}
{affinityTarget && state && (
<Suspense fallback={null}>
<AffinityDialog
locale={locale}
vmName={affinityTarget.name}
driverID={affinityTarget.driverID}
vcpus={detail?.name === affinityTarget.name ? detail.cpus : 4}
host={state.host}
globalAutoPin={state.config.auto_pin_pcores}
onClose={() => setAffinityTarget(null)}
onApplied={(st) => {
setAffinityTarget(null)
setAffinityVersion((v) => v + 1)
const count = st.effective_cpus?.length ?? 0
const mask = st.live_mask_hex || st.effective_mask_hex || '0x0'
toasts.push({
kind: 'ok',
title: st.running
? tr('toastAffinityApplied', { count, mask })
: tr('toastAffinitySaved'),
})
refresh()
}}
/>
</Suspense>
)}
{update.confirming && (
<Modal
title={tr('updateConfirmTitle', { v: update.info?.latest ?? '' })}
closeLabel={tr('close')}
onClose={() => update.cancelInstall()}
>
<div className="stack-2" style={{ padding: 'var(--sp-4)', fontSize: 'var(--fs-13)', color: 'var(--text-2)' }}>
<p style={{ margin: 0 }}>{tr('updateConfirmBody', { n: runningVMCount })}</p>
{state?.host.needs_cold_reboot_workaround && <p style={{ margin: 0 }}>{tr('updateConfirmWin10')}</p>}
</div>
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" onClick={() => update.cancelInstall()}>{tr('cancel')}</Button>
<Button variant="primary" onClick={update.confirmInstall}>{tr('updateRestart')}</Button>
</span>
</div>
</Modal>
)}
{deleteTarget && (
<DeleteDialog locale={locale} name={findVM(deleteTarget)?.name ?? deleteTarget} onCancel={() => setDeleteTarget(null)} onConfirm={confirmDelete} />
)}
{closeDownloadsOpen && (
<ConfirmDialog
title={tr('closeDownloadsTitle')}
description={tr('closeDownloadsDesc')}
cancelLabel={tr('cancel')}
confirmLabel={tr('closeDownloadsConfirm')}
onCancel={() => setCloseDownloadsOpen(false)}
onConfirm={() => { setCloseDownloadsOpen(false); void api.QuitApp() }}
/>
)}
{elevationQueue.length > 0 && (
<ElevationDialog
key={elevationQueue[0].id}
locale={locale}
request={elevationQueue[0]}
onResolve={(approved) => {
const active = elevationQueue[0]
setElevationQueue((q) => q.filter((item) => item.id !== active.id))
api.ResolveElevationRequest(active.id, approved).catch((e) => console.warn('[app] ResolveElevationRequest failed:', e))
}}
/>
)}
{discardSuspendTarget && (() => {
const targetVM = findVM(discardSuspendTarget)
const targetName = targetVM?.name ?? discardSuspendTarget
return (
<ConfirmDialog
title={tr('discardSuspendTitle', { name: displayNames[targetVM ? vmRefKey(targetVM) : targetName] || targetName })}
description={tr('discardSuspendDesc')}
cancelLabel={tr('cancel')}
confirmLabel={tr('discardSuspendConfirm')}
onCancel={() => setDiscardSuspendTarget(null)}
onConfirm={confirmDiscardSuspend}
/>
)
})()}
{cloneSource && (
<CloneDialog
locale={locale}
sourceName={cloneSource.name}
defaultCloneName={`${cloneSource.name}-clone`}
onCancel={() => setCloneSource(null)}
onConfirm={confirmClone}
/>
)}
<AppDialogs
locale={locale}
state={state}
detail={detail}
selectedVM={selectedVM}
selectedIsMacOS={selectedIsMacOS}
effectiveState={effectiveState}
fixedModeSupported={fixedModeSupported}
diskCacheSupported={diskCacheSupported}
runningVMCount={runningVMCount}
tasks={Object.values(taskMap)}
displayNames={displayNames}
showWizard={showWizard}
wizardDraft={wizardDraft}
onCloseWizard={() => { setShowWizard(false); setWizardDraft(null) }}
onSubmitCreate={submitCreate}
showSettings={showSettings}
onCloseSettings={() => setShowSettings(false)}
onSavedSettings={() => {
setShowSettings(false)
toasts.push({ kind: 'ok', title: tr(effectiveState === 'running' ? 'toastSavedNextStart' : 'toastSaved') })
refresh()
}}
affinityTarget={affinityTarget}
affinityVersion={affinityVersion}
onOpenAffinity={setAffinityTarget}
onCloseAffinity={() => setAffinityTarget(null)}
onAffinityApplied={(st) => {
setAffinityTarget(null)
setAffinityVersion((v) => v + 1)
const count = st.effective_cpus?.length ?? 0
const mask = st.live_mask_hex || st.effective_mask_hex || '0x0'
toasts.push({
kind: 'ok',
title: st.running
? tr('toastAffinityApplied', { count, mask })
: tr('toastAffinitySaved'),
})
refresh()
}}
updateConfirming={update.confirming}
updateLatest={update.info?.latest ?? ''}
onCancelInstallUpdate={() => update.cancelInstall()}
onConfirmInstallUpdate={update.confirmInstall}
deleteTarget={deleteTarget}
onCancelDelete={() => setDeleteTarget(null)}
onConfirmDelete={confirmDelete}
closeDownloadsOpen={closeDownloadsOpen}
onCancelCloseDownloads={() => setCloseDownloadsOpen(false)}
elevationQueue={elevationQueue}
onResolveElevation={(id, approved) => {
setElevationQueue((q) => q.filter((item) => item.id !== id))
api.ResolveElevationRequest(id, approved).catch((e) => console.warn('[app] ResolveElevationRequest failed:', e))
}}
discardSuspendTarget={discardSuspendTarget}
onCancelDiscardSuspend={() => setDiscardSuspendTarget(null)}
onConfirmDiscardSuspend={confirmDiscardSuspend}
cloneSource={cloneSource}
onCancelClone={() => setCloneSource(null)}
onConfirmClone={confirmClone}
sendTextTarget={sendTextTarget}
onCancelSendText={() => setSendTextTarget(null)}
onConfirmSendText={(key, driverID, name, text) => {
setSendTextTarget(null)
typeInto(key, () => api.TypeText(driverID, name, text))
}}
pluginDialogs={pluginViewState.dialogs}
findRouteView={findRouteView}
renderPluginView={renderPluginView}
findVM={findVM}
onCopy={copy}
onRefresh={refresh}
onToast={toasts.push}
/>
{onlineRecoveryTarget && (
<OnlineRecoveryDialog
@@ -1597,30 +1533,6 @@ export const App: React.FC = () => {
/>
)}
{sendTextTarget && (() => {
const sendVM = findVM(sendTextTarget)
const sendName = sendVM?.name ?? sendTextTarget
return (
<SendTextDialog
locale={locale}
vmName={sendName}
guestToolsConnected={Boolean(latestVMStats(sendVM?.driver_id ?? '', sendName)?.guest_tools_connected ?? (selectedIsMacOS ? detail?.guest_tools_connected : false))}
onCancel={() => setSendTextTarget(null)}
onConfirm={(text) => {
const target = sendTextTarget
setSendTextTarget(null)
typeInto(sendVM ? vmRefKey(sendVM) : target, () => api.TypeText(sendVM?.driver_id ?? '', sendName, text))
}}
/>
)
})()}
{/* Every open dialog stays mounted so the ones underneath keep their state. */}
{pluginViewState.dialogs.map((route) => {
const view = findRouteView(route)
return view && renderPluginView(route, view, true)
})}
<div className="rg-layer rg-layer-overlay" data-rg-layer="layer.overlay" aria-hidden="true" />
</div>
{/* Outside the isolated shell so toasts stay above dialogs and the overlay layer. */}
+4 -1
View File
@@ -98,7 +98,10 @@ export const AboutPage: React.FC<Props> = ({
let cancelled = false
api.CanOpenQQGroup()
.then((ok) => { if (!cancelled) setQQInstalled(!!ok) })
.catch(() => { if (!cancelled) setQQInstalled(false) })
.catch((e) => {
console.warn('[about] CanOpenQQGroup failed:', e)
if (!cancelled) setQQInstalled(false)
})
return () => {
mountedRef.current = false
cancelled = true
+259
View File
@@ -0,0 +1,259 @@
import React, { Suspense, lazy } from 'react'
import type { WizardDraft } from './CreateWizard'
import { DeleteDialog } from './DeleteDialog'
import { ElevationDialog } from './ElevationDialog'
import { CloneDialog } from './CloneDialog'
import { SendTextDialog } from './SendTextDialog'
import { I18nKey, t } from '../i18n'
import { hasStambhaRuntime, STAMBHA_DRIVER_ID } from '../lib/endpoints'
import { latestVMStats } from '../lib/vmStats'
import { vmRefKey } from '../lib/vmRef'
import type { PluginViewRoute } from '../lib/pluginViewRouter'
import type { AppState, CreateOpts, Locale, Task, VMDetail, VMListItem, ViewContribution } from '../types'
import { Button } from '../ui/controls'
import { ConfirmDialog, Modal } from '../ui/dialog'
import type { ToastInput } from '../ui/toast'
import { api, type ElevationPrompt } from '../wails'
const CreateWizard = lazy(() => import('./CreateWizard').then((m) => ({ default: m.CreateWizard })))
const SettingsModal = lazy(() => import('./SettingsModal').then((m) => ({ default: m.SettingsModal })))
const AffinityDialog = lazy(() => import('./AffinityDialog').then((m) => ({ default: m.AffinityDialog })))
interface AppDialogsProps {
locale: Locale
state: AppState | null
detail: VMDetail | null
selectedVM: VMListItem | undefined
selectedIsMacOS: boolean
effectiveState: string
fixedModeSupported: boolean
diskCacheSupported: boolean
runningVMCount: number
tasks: Task[]
displayNames: Record<string, string>
showWizard: boolean
wizardDraft: WizardDraft | null
onCloseWizard: () => void
onSubmitCreate: (payload: CreateOpts, draft: WizardDraft) => void
showSettings: boolean
onCloseSettings: () => void
onSavedSettings: () => void
affinityTarget: { name: string; driverID: string } | null
affinityVersion: number
onOpenAffinity: (target: { name: string; driverID: string }) => void
onCloseAffinity: () => void
onAffinityApplied: (st: { running?: boolean; effective_cpus?: number[]; live_mask_hex?: string; effective_mask_hex?: string }) => void
updateConfirming: boolean
updateLatest: string
onCancelInstallUpdate: () => void
onConfirmInstallUpdate: () => void
deleteTarget: string | null
onCancelDelete: () => void
onConfirmDelete: (keepFiles: boolean) => void
closeDownloadsOpen: boolean
onCancelCloseDownloads: () => void
elevationQueue: ElevationPrompt[]
onResolveElevation: (id: string, approved: boolean) => void
discardSuspendTarget: string | null
onCancelDiscardSuspend: () => void
onConfirmDiscardSuspend: () => void
cloneSource: { name: string; driverID: string } | null
onCancelClone: () => void
onConfirmClone: (cloneName: string) => void
sendTextTarget: string | null
onCancelSendText: () => void
onConfirmSendText: (vmKey: string, driverID: string, vmName: string, text: string) => void
pluginDialogs: PluginViewRoute[]
findRouteView: (route: PluginViewRoute) => ViewContribution | undefined
renderPluginView: (route: PluginViewRoute, view: ViewContribution, asDialog: boolean) => React.ReactNode
findVM: (keyOrName: string) => VMListItem | undefined
onCopy: (text: string) => void
onRefresh: () => void
onToast: (toast: ToastInput) => void
}
export const AppDialogs: React.FC<AppDialogsProps> = (props) => {
const {
locale, state, detail, selectedVM, selectedIsMacOS, effectiveState,
fixedModeSupported, diskCacheSupported, runningVMCount, tasks, displayNames,
showWizard, wizardDraft, onCloseWizard, onSubmitCreate,
showSettings, onCloseSettings, onSavedSettings,
affinityTarget, affinityVersion, onOpenAffinity, onCloseAffinity, onAffinityApplied,
updateConfirming, updateLatest, onCancelInstallUpdate, onConfirmInstallUpdate,
deleteTarget, onCancelDelete, onConfirmDelete,
closeDownloadsOpen, onCancelCloseDownloads,
elevationQueue, onResolveElevation,
discardSuspendTarget, onCancelDiscardSuspend, onConfirmDiscardSuspend,
cloneSource, onCancelClone, onConfirmClone,
sendTextTarget, onCancelSendText, onConfirmSendText,
pluginDialogs, findRouteView, renderPluginView,
findVM, onCopy, onRefresh, onToast,
} = props
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
return (
<>
{showWizard && state && (
<Suspense fallback={null}>
<CreateWizard
locale={locale}
host={state.host}
fixedModeSupported={fixedModeSupported}
captureSupported={state.runtime_capture_supported}
initialDriverID={!state.active_runtime && hasStambhaRuntime(state.runtimes) ? STAMBHA_DRIVER_ID : undefined}
tasks={tasks}
draft={wizardDraft}
onClose={onCloseWizard}
onSubmit={onSubmitCreate}
/>
</Suspense>
)}
{showSettings && state && detail && (
<Suspense fallback={null}>
<SettingsModal
key={`${selectedVM?.driver_id ?? ''}:${detail.name}`}
locale={locale}
detail={detail}
driverID={selectedVM?.driver_id ?? ''}
stats={latestVMStats(selectedVM?.driver_id ?? '', detail.name)}
host={state.host}
fixedModeSupported={fixedModeSupported}
diskCacheSupported={diskCacheSupported}
optimizations={state.optimizations}
running={effectiveState === 'running'}
onCopy={onCopy}
onDiskChanged={onRefresh}
onOpenAffinity={() => onOpenAffinity({ name: detail.name, driverID: selectedVM?.driver_id ?? '' })}
affinityVersion={affinityVersion}
onHostChanged={onRefresh}
onToast={onToast}
onClose={onCloseSettings}
onSaved={onSavedSettings}
/>
</Suspense>
)}
{affinityTarget && state && (
<Suspense fallback={null}>
<AffinityDialog
locale={locale}
vmName={affinityTarget.name}
driverID={affinityTarget.driverID}
vcpus={detail?.name === affinityTarget.name ? detail.cpus : 4}
host={state.host}
globalAutoPin={state.config.auto_pin_pcores}
onClose={onCloseAffinity}
onApplied={onAffinityApplied}
/>
</Suspense>
)}
{updateConfirming && (
<Modal
title={tr('updateConfirmTitle', { v: updateLatest })}
closeLabel={tr('close')}
onClose={onCancelInstallUpdate}
>
<div className="stack-2" style={{ padding: 'var(--sp-4)', fontSize: 'var(--fs-13)', color: 'var(--text-2)' }}>
<p style={{ margin: 0 }}>{tr('updateConfirmBody', { n: runningVMCount })}</p>
{state?.host.needs_cold_reboot_workaround && <p style={{ margin: 0 }}>{tr('updateConfirmWin10')}</p>}
</div>
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" onClick={onCancelInstallUpdate}>{tr('cancel')}</Button>
<Button variant="primary" onClick={onConfirmInstallUpdate}>{tr('updateRestart')}</Button>
</span>
</div>
</Modal>
)}
{deleteTarget && (
<DeleteDialog
locale={locale}
name={findVM(deleteTarget)?.name ?? deleteTarget}
onCancel={onCancelDelete}
onConfirm={onConfirmDelete}
/>
)}
{closeDownloadsOpen && (
<ConfirmDialog
title={tr('closeDownloadsTitle')}
description={tr('closeDownloadsDesc')}
cancelLabel={tr('cancel')}
confirmLabel={tr('closeDownloadsConfirm')}
onCancel={onCancelCloseDownloads}
onConfirm={() => { onCancelCloseDownloads(); void api.QuitApp() }}
/>
)}
{elevationQueue.length > 0 && (
<ElevationDialog
key={elevationQueue[0].id}
locale={locale}
request={elevationQueue[0]}
onResolve={(approved) => onResolveElevation(elevationQueue[0].id, approved)}
/>
)}
{discardSuspendTarget && (() => {
const targetVM = findVM(discardSuspendTarget)
const targetName = targetVM?.name ?? discardSuspendTarget
return (
<ConfirmDialog
title={tr('discardSuspendTitle', { name: displayNames[targetVM ? vmRefKey(targetVM) : targetName] || targetName })}
description={tr('discardSuspendDesc')}
cancelLabel={tr('cancel')}
confirmLabel={tr('discardSuspendConfirm')}
onCancel={onCancelDiscardSuspend}
onConfirm={onConfirmDiscardSuspend}
/>
)
})()}
{cloneSource && (
<CloneDialog
locale={locale}
sourceName={cloneSource.name}
defaultCloneName={`${cloneSource.name}-clone`}
onCancel={onCancelClone}
onConfirm={onConfirmClone}
/>
)}
{sendTextTarget && (() => {
const sendVM = findVM(sendTextTarget)
const sendName = sendVM?.name ?? sendTextTarget
return (
<SendTextDialog
locale={locale}
vmName={sendName}
guestToolsConnected={Boolean(latestVMStats(sendVM?.driver_id ?? '', sendName)?.guest_tools_connected ?? (selectedIsMacOS ? detail?.guest_tools_connected : false))}
onCancel={onCancelSendText}
onConfirm={(text) => onConfirmSendText(sendVM ? vmRefKey(sendVM) : sendTextTarget, sendVM?.driver_id ?? '', sendName, text)}
/>
)
})()}
{/* Every open dialog stays mounted so the ones underneath keep their state. */}
{pluginDialogs.map((route) => {
const view = findRouteView(route)
return view && renderPluginView(route, view, true)
})}
</>
)
}
+119 -42
View File
@@ -1,6 +1,7 @@
import { Check, ChevronRight, CircleAlert, CircleCheck, CloudDownload, Copy, Disc3, HardDrive, LucideIcon, Package } from 'lucide-react'
import React, { Suspense, lazy, useEffect, useState } from 'react'
import React, { Suspense, lazy, useEffect, useMemo, useState } from 'react'
import { useNetworkPlan } from '../lib/useNetworkPlan'
import { STAMBHA_DRIVER_ID } from '../lib/endpoints'
import { NpcapDependency } from './NpcapDependency'
import { NetworkErrorNotice } from './NetworkErrorNotice'
import type { ParsedAppError } from '../i18n'
@@ -14,6 +15,7 @@ import {
defaultGuestLang,
findGPU,
formatMemory,
formatResolutionLabel,
gpuCompatHint,
gpuLabel,
gpuOptionValue,
@@ -21,22 +23,32 @@ import {
memorySafeLimitGB,
parseMemoryGB,
recommendedCPUs,
canKeepDisplayPreset,
fullscreenDisplayPresets,
FullscreenDisplayPreset,
hidpiLooksLike,
hostDisplayAdvice,
hostDisplayDesc,
resolveAutoDisplayPreset,
windowDisplayPresets,
recommendedMemoryGB,
recommendedResolution,
shortGPUName,
sshCommand,
} from '../lib/format'
import {
AUTO_RESOLUTION_OPTION,
buildResolutionOptions,
initialWizardManualResolution,
initialWizardResolution,
resolveEffectiveWizardOpts,
selectWizardResolution,
supportsAutoResolution,
switchWizardGraphics,
toggleWizardBorderless,
} from '../lib/displayResolution'
import { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, Task, ValidationIssue, VMNetworkSettings } from '../types'
import { findActiveOfflineTask, taskInstallerPhase } from '../lib/tasks'
import { Button, IconButton } from '../ui/controls'
import { NumberField, PopupSelect, RangeField, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
import { Modal } from '../ui/dialog'
import { api } from '../wails'
@@ -47,6 +59,7 @@ const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos'
export interface WizardDraft {
opts: CreateOpts
step: number
manualResolution?: boolean
}
interface Props {
@@ -54,6 +67,7 @@ interface Props {
host: HostReport
fixedModeSupported?: boolean
captureSupported?: boolean
initialDriverID?: string
tasks?: Task[]
draft?: WizardDraft | null
onClose: () => void
@@ -81,7 +95,7 @@ const SOURCES: { mode: 'offline' | 'apple' | 'installer' | 'disk'; icon: LucideI
{ mode: 'disk', icon: HardDrive, title: 'srcDiskTitle', sub: 'srcDiskSub' },
]
export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported = false, captureSupported = false, tasks = [], draft, onClose, onSubmit }) => {
export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported = false, captureSupported = false, initialDriverID = BUILTIN_MACOS_DRIVER, tasks = [], draft, onClose, onSubmit }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [step, setStep] = useState(draft?.step ?? 1)
// Once the user has reached the review step, keep validating so step markers stay current.
@@ -91,7 +105,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
const [issues, setIssues] = useState<ValidationIssue[]>([])
const [cmdPreview, setCmdPreview] = useState('')
const [drivers, setDrivers] = useState<DriverSummary[]>([])
const [driverID, setDriverID] = useState(BUILTIN_MACOS_DRIVER)
const [driverID, setDriverID] = useState(initialDriverID)
const [driverOpts, setDriverOpts] = useState<Record<string, unknown>>({})
const [driverCreating, setDriverCreating] = useState(false)
const [dependencyBusy, setDependencyBusy] = useState(false)
@@ -103,11 +117,13 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
api.ListDrivers().then((list) => { if (live) setDrivers(list ?? []) }).catch((e) => console.warn('[wizard] ListDrivers failed:', e))
return () => { live = false }
}, [])
const armImageTask = [...tasks].reverse().find((task) => task.installer_kind === 'arm-ipsw')
const activeDriver = drivers.find((d) => d.id === driverID)
const isCustomDriver = driverID !== BUILTIN_MACOS_DRIVER && !!activeDriver
const defaultGraphics = host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga'
const [opts, setOpts] = useState<CreateOpts>(draft?.opts ?? {
name: 'macos-tahoe',
name: initialDriverID === STAMBHA_DRIVER_ID ? 'macos-arm64' : 'macos-tahoe',
dir: '',
// 离线安装默认关闭网络,减少恢复环境依赖;用户仍可在第 4 步改为 NAT 或桥接。
source_mode: 'offline',
@@ -120,11 +136,11 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
disk: '',
disk_mode: 'copy',
disk_controller: 'nvme',
graphics: host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga',
graphics: defaultGraphics,
// Default to "auto" rather than a DriverStore FileRepository ICD path so
// Windows GPU driver updates never break existing VM configs.
gpu: 'auto',
resolution: recommendedResolution(host),
...initialWizardResolution(host, fixedModeSupported, defaultGraphics),
displays: 1,
borderless: false,
...(captureSupported ? { capture: false } : {}),
@@ -136,6 +152,9 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
guest_lang: defaultGuestLang(locale),
start: true,
})
const [manualResolutionPicked, setManualResolutionPicked] = useState(() =>
initialWizardManualResolution(draft),
)
const [networkTouched, setNetworkTouched] = useState(!!draft?.opts)
const set = (patch: Partial<CreateOpts>) => setOpts((o) => ({ ...o, ...patch }))
const networkMode = opts.network_mode ?? (opts.network ? 'nat' : 'off')
@@ -157,9 +176,22 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
}, [step, networkMode, locale])
const windowPresets = windowDisplayPresets(host, fixedModeSupported)
const fullscreenPresets = fullscreenDisplayPresets(host)
const activePresets: FullscreenDisplayPreset[] = opts.borderless ? fullscreenPresets : windowPresets
const autoPreset = resolveAutoDisplayPreset(host, !!opts.borderless, fixedModeSupported)
const effectiveOpts = useMemo(
() => resolveEffectiveWizardOpts(opts, autoPreset),
[opts, autoPreset.resolution],
)
const changeGraphics = (graphics: CreateOpts['graphics']) => {
set(switchWizardGraphics({ graphics, manualResolutionPicked, autoPreset }))
}
const resArt = (r: string) => {
const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(r)
return m ? <ScreenArt w={Number(m[1])} h={Number(m[2])} /> : <ScreenArt w={16} h={10} />
}
const buildPayload = (): CreateOpts => {
const p: CreateOpts = { ...opts, offline: opts.source_mode === 'offline' }
const p: CreateOpts = { ...effectiveOpts, offline: effectiveOpts.source_mode === 'offline' }
if (!captureSupported) {
delete p.capture
}
@@ -233,7 +265,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
.finally(() => { if (live) setChecking(false) })
}, 200)
return () => { live = false; clearTimeout(timer) }
}, [step, reviewed, opts, validationRefresh, captureSupported])
}, [step, reviewed, effectiveOpts, validationRefresh, captureSupported])
const pickDir = async () => {
const dir = await api.PickDirectory(tr('vmDir'))
@@ -247,7 +279,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
const handleCreate = () => {
if (dependencyBusy || networkBlocked) return
onSubmit(buildPayload(), { opts, step: REVIEW_STEP })
onSubmit(buildPayload(), { opts: effectiveOpts, step: REVIEW_STEP, manualResolution: manualResolutionPicked })
}
const issueSteps = new Set(reviewed ? issues.map(stepOfIssue) : [])
@@ -265,7 +297,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
return (
<Modal className="wizard-dialog" title={tr('wizardTitle')} closeLabel={tr('close')} onClose={onClose}>
<nav className="wizard-steps" aria-label={tr('wizardTitle')}>
{driverID !== STAMBHA_DRIVER_ID && <nav className="wizard-steps" aria-label={tr('wizardTitle')}>
{steps.map((key, idx) => {
const n = idx + 1
const bad = issueSteps.has(n) && n !== REVIEW_STEP
@@ -283,7 +315,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
</button>
)
})}
</nav>
</nav>}
<div className="dialog-body">
{err && <div className="notice notice-error">{err}</div>}
@@ -303,7 +335,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
value: d.id,
label: locText(d.name, locale, d.id),
}))}
onChange={(id) => { setDriverID(id); setErr('') }}
onChange={(id) => { setDriverID(id); setDriverOpts({}); setErr('') }}
/>
}
/>
@@ -317,6 +349,19 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
control={<input className="input rg-p-input" value={opts.name} onChange={(e) => set({ name: e.target.value })} />}
/>
</SetGroup>
{driverID === STAMBHA_DRIVER_ID && (
<SetGroup title={tr('armRestoreGroup')}>
<SetRow title={tr('armRestoreVersion')} desc={tr('armRestoreMediaHint')} control={
<Button busy={armImageTask?.status === 'running'} onClick={() => {
setErr('')
void api.DownloadARMImage().catch((e) => setErr(parseAppError(e).summary))
}}>{tr('armRestoreDownload')}</Button>
} />
{armImageTask?.status === 'done' && armImageTask.result && (
<SetRow title={tr('armRestoreDownloaded')} desc={<span className="mono path-text">{armImageTask.result}</span>} />
)}
</SetGroup>
)}
{activeDriver.create_schema && (
<Suspense fallback={null}>
<SchemaForm
@@ -324,6 +369,12 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
schema={activeDriver.create_schema}
values={driverOpts}
onChange={setDriverOpts}
pathFields={driverID === STAMBHA_DRIVER_ID ? {
boot_volume: true,
raw_disk: '*.qcow2;*.raw;*.img',
usb_image: '*.raw;*.img;*.bin',
} : undefined}
onPickError={(e) => setErr(parseAppError(e).summary)}
/>
</Suspense>
)}
@@ -545,7 +596,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
<Segmented
label={tr('graphicsBackend')}
value={opts.graphics}
onChange={(graphics) => set({ graphics })}
onChange={changeGraphics}
options={[
{ value: 'reims-vgpu' as const, label: tr('graphicsReimsShort') },
{ value: 'vmware-svga' as const, label: tr('graphicsSvgaShort') },
@@ -566,7 +617,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
<button
type="button"
className="link-btn"
onClick={() => set({ graphics: 'vmware-svga' })}
onClick={() => changeGraphics('vmware-svga')}
>
{tr('gpuSwitchSvga')}
</button>
@@ -602,23 +653,47 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
disabled={opts.graphics !== 'reims-vgpu'}
reason={tr('gpuSvgaReason')}
desc={[hostDisplayDesc(host, tr), !opts.borderless ? hostDisplayAdvice(host, tr, windowPresets) : undefined].filter(Boolean).join(' · ') || undefined}
control={
<PopupSelect
id="vm-res"
block={
<OptionCards
label={tr('resolution')}
value={opts.resolution}
onChange={(resolution) => set({ resolution })}
options={(opts.borderless ? fullscreenPresets : windowPresets).map((p: FullscreenDisplayPreset) => ({
value: p.resolution,
label: p.label,
detail: [
p.hidpi ? `${tr('hidpiPresetBadge')} · ${hidpiLooksLike(p.resolution, tr) ?? ''}` : '',
p.scaleBadge ?? '',
p.native ? tr('resNativeBadge') : '',
p.scaleToFit ? tr('resScaleToFitWindow') : '',
p.recommended ? tr('recommendedBadge') : '',
].filter(Boolean).join(' · ') || undefined,
}))}
value={supportsAutoResolution(opts.graphics) && opts.auto_resolution ? AUTO_RESOLUTION_OPTION : opts.resolution}
onChange={(v) => {
setManualResolutionPicked(v !== AUTO_RESOLUTION_OPTION)
set(selectWizardResolution(v, autoPreset))
}}
options={buildResolutionOptions({
graphics: opts.graphics,
autoPreset,
activePresets,
}).map((item) => {
const p = item.preset!
if (item.kind === 'auto') {
return {
value: item.value,
title: tr('resAuto'),
sub: tr('resAutoSub', { res: p.label }),
art: resArt(p.resolution),
badges: [
p.hidpi ? tr('hidpiPresetBadge') : '',
p.scaleBadge ?? '',
tr('recommendedBadge'),
].filter(Boolean),
}
}
return {
value: item.value,
title: p.label,
sub: p.hidpi ? hidpiLooksLike(p.resolution, tr) : undefined,
art: resArt(p.resolution),
badges: [
p.hidpi ? tr('hidpiPresetBadge') : '',
p.scaleBadge ?? '',
p.native ? tr('resNativeBadge') : '',
p.scaleToFit ? tr('resScaleToFitWindow') : '',
p.recommended ? tr('recommendedBadge') : '',
].filter(Boolean),
}
})}
/>
}
/>
@@ -686,12 +761,14 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
<Switch
label={tr('fullscreenLaunch')}
checked={!!opts.borderless}
onChange={(borderless) => {
const list = borderless ? fullscreenPresets : windowPresets
const keep = list.some((p) => canKeepDisplayPreset(p, opts.resolution, borderless))
const fallback = list.find((p) => p.recommended)?.resolution ?? list[0]?.resolution ?? opts.resolution
set(keep ? { borderless } : { borderless, resolution: fallback })
}}
onChange={(borderless) => set(toggleWizardBorderless({
borderless,
opts,
host,
fixedModeSupported,
windowPresets,
fullscreenPresets,
}))}
/>
}
/>
@@ -707,7 +784,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
<Review
locale={locale}
host={host}
opts={opts}
opts={effectiveOpts}
captureSupported={captureSupported}
networkUplink={networkAdapters?.find((adapter) => adapter.guid === opts.uplink_guid)?.name}
issues={issues}
@@ -737,7 +814,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
await api.CreateVMWithDriver({
driver_id: driverID,
name: opts.name.trim(),
dir: opts.dir,
dir: driverID === STAMBHA_DRIVER_ID ? '' : opts.dir,
options: driverOpts,
})
onClose()
@@ -801,7 +878,7 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, captureSupported, i
? tr('summaryInstallerSource', { file: fileName(opts.installer) })
: tr('summaryDiskSource', { file: fileName(opts.disk) })
const res = (opts.resolution ?? '').replace(/x/i, ' × ')
const res = formatResolutionLabel(opts.resolution ?? '', !!opts.auto_resolution, tr)
const graphicsRows: Row[] = opts.graphics === 'reims-vgpu'
? [
{ label: tr('factGraphics'), value: `${gpuLabel(locale, opts.gpu, host)} · reims-vgpu` },
+44 -35
View File
@@ -5,6 +5,7 @@ import '../i18n/domains/wizard.gen'
import { I18nKey, t } from '../i18n'
import { formatBytes, gpuCompatHint, gpuKey, gpuMetaLine, sameGPU } from '../lib/format'
import { describeHostWHPX } from '../lib/hypervisor'
import { hasStambhaRuntime, STAMBHA_RUNTIME_KIND } from '../lib/endpoints'
import { AppState, Locale, StorageBreakdown, Task } from '../types'
import { Button, IconButton } from '../ui/controls'
import { Switch } from '../ui/settings'
@@ -111,7 +112,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
</div>
</header>
{(state.vms?.length ?? 0) === 0 && host.whpx === 'ready' && !!state.active_runtime && onNewVM && (
{(state.vms?.length ?? 0) === 0 && host.whpx === 'ready' && (!!state.active_runtime || hasStambhaRuntime(runtimes)) && onNewVM && (
<section className="welcome-card">
<h1>{tr('welcomeTitle')}</h1>
<p>{tr('welcomeSub')}</p>
@@ -228,43 +229,51 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
<Switch label={tr('qemuASLR')} checked={!!config.qemu_aslr} disabled={savingASLR} onChange={setQEMUASLR} />
</div>
</div>
{(runtimes ?? []).filter((rt) => !rt.active).map((rt) => (
<div className="row" key={rt.commit}>
<div className="row-main">
<div className="row-title">
<span className="mono">{rt.commit}</span>
{latestRuntimeCommit && sameRuntimeId(rt.commit, latestRuntimeCommit) && (
<span className="badge rg-p-badge badge-ok">{tr('runtimeLatestBadge')}</span>
{(runtimes ?? []).filter((rt) => !rt.active).map((rt) => {
const stambha = rt.kind === STAMBHA_RUNTIME_KIND
const ref = stambha ? STAMBHA_RUNTIME_KIND + '/' + rt.commit : rt.commit
return (
<div className="row" key={ref}>
<div className="row-main">
<div className="row-title">
<span className="mono">{stambha ? rt.manifest.name || rt.commit : rt.commit}</span>
{(stambha || !rt.kind || rt.kind === 'reims-vgpu') &&
<span className="badge rg-p-badge">{tr(stambha ? 'armRuntimeLabel' : 'x86RuntimeLabel')}</span>}
{!stambha && latestRuntimeCommit && sameRuntimeId(rt.commit, latestRuntimeCommit) && (
<span className="badge rg-p-badge badge-ok">{tr('runtimeLatestBadge')}</span>
)}
</div>
<div className="row-sub">{rt.manifest.qemu_version?.replace(/^QEMU emulator version\s*/i, 'QEMU ')}</div>
</div>
<div className="row-right">
{confirmDelete === ref ? (
<>
<Button variant="ghost" disabled={removing === ref} onClick={() => setConfirmDelete('')}>
{tr('cancel')}
</Button>
<Button variant="danger" busy={removing === ref} onClick={() => removeRuntime(ref)}>
{tr('runtimeDeleteConfirm')}
</Button>
</>
) : (
<>
{!stambha && (
<Button disabled={removing === ref} onClick={guard(() => api.UseRuntime(rt.commit))}>
{tr('activate')}
</Button>
)}
<IconButton
label={tr('runtimeDelete')}
icon={<Trash size={15} />}
disabled={removing !== ''}
onClick={() => setConfirmDelete(ref)}
/>
</>
)}
</div>
<div className="row-sub">{rt.manifest.qemu_version.replace(/^QEMU emulator version\s*/i, 'QEMU ')}</div>
</div>
<div className="row-right">
{confirmDelete === rt.commit ? (
<>
<Button variant="ghost" disabled={removing === rt.commit} onClick={() => setConfirmDelete('')}>
{tr('cancel')}
</Button>
<Button variant="danger" busy={removing === rt.commit} onClick={() => removeRuntime(rt.commit)}>
{tr('runtimeDeleteConfirm')}
</Button>
</>
) : (
<>
<Button disabled={removing === rt.commit} onClick={guard(() => api.UseRuntime(rt.commit))}>
{tr('activate')}
</Button>
<IconButton
label={tr('runtimeDelete')}
icon={<Trash size={15} />}
disabled={removing !== ''}
onClick={() => setConfirmDelete(rt.commit)}
/>
</>
)}
</div>
</div>
))}
)
})}
</div>
</section>
+5 -110
View File
@@ -34,20 +34,6 @@ function formatCompactCount(n: number): string {
return String(n)
}
function formatByteSize(bytes?: number): string {
if (!bytes || bytes <= 0) return ''
if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
if (bytes >= 1024) return `${Math.max(1, Math.round(bytes / 1024))} KB`
return `${bytes} B`
}
function formatShortDate(iso?: string): string {
if (!iso) return ''
const ms = Date.parse(iso)
if (Number.isNaN(ms)) return ''
return new Date(ms).toISOString().slice(0, 10)
}
function parseTimestamp(iso?: string): number {
if (!iso) return 0
const ms = Date.parse(iso)
@@ -62,20 +48,6 @@ function compositeScore(item: MarketCatalogItem, nowMs: number): number {
return recency + downloads
}
function entryReleases(item: MarketCatalogItem) {
const e = item.entry
if (e.releases && e.releases.length > 0) return e.releases
return [{
version: e.version,
channel: e.channel || 'stable',
download_url: e.download_url,
sha256: e.sha256,
size_bytes: e.size_bytes,
published_at: e.updated_at,
changelog: e.changelog,
}]
}
interface Props {
locale: Locale
safeMode?: boolean
@@ -102,7 +74,6 @@ export const PluginMarket: React.FC<Props> = ({
const [query, setQuery] = useState('')
const [kind, setKind] = useState('')
const [sortBy, setSortBy] = useState<MarketSortMode>('composite')
const [versionPick, setVersionPick] = useState<{ item: MarketCatalogItem; selected: string } | null>(null)
const [result, setResult] = useState<MarketBrowseResult | null>(null)
const [syncing, setSyncing] = useState(false)
const [refreshing, setRefreshing] = useState(false)
@@ -277,22 +248,13 @@ export const PluginMarket: React.FC<Props> = ({
advancePrompt()
}
const openVersionPicker = (item: MarketCatalogItem) => {
const list = entryReleases(item)
const defaultVer = list.find((r) => r.version === item.entry.version)?.version ?? list[0]?.version ?? item.entry.version
setVersionPick({ item, selected: defaultVer })
}
const install = async (item: MarketCatalogItem, version?: string) => {
const install = async (item: MarketCatalogItem) => {
const id = item.entry.id
if (installingRef.current.has(id)) return
installingRef.current.add(id)
const rel = entryReleases(item).find((r) => r.version === version)
setProgress((prev) => ({ ...prev, [id]: { id, phase: 'download', done: 0, total: rel?.size_bytes ?? item.entry.size_bytes ?? 0 } }))
setProgress((prev) => ({ ...prev, [id]: { id, phase: 'download', done: 0, total: item.entry.size_bytes ?? 0 } }))
try {
const info = version
? await api.InstallMarketPluginVersion(id, version)
: await api.InstallMarketPlugin(id, true)
const info = await api.InstallMarketPluginVersion(id, item.entry.version)
await onChanged({})
if (info && !info.enabled) {
if (promptTargetIDRef.current) {
@@ -372,7 +334,7 @@ export const PluginMarket: React.FC<Props> = ({
return (
<Tip label={tr('pluginMarketVersionTip', { installed: item.installed_version ?? '', version: e.version })}>
<span>
<Button className="market-btn" variant="primary" disabled={!!safeMode} icon={<Download size={13} aria-hidden="true" />} onClick={() => openVersionPicker(item)}>
<Button className="market-btn" variant="primary" disabled={!!safeMode} icon={<Download size={13} aria-hidden="true" />} onClick={() => void install(item)}>
{tr('pluginMarketUpdateShort')}
</Button>
</span>
@@ -380,7 +342,7 @@ export const PluginMarket: React.FC<Props> = ({
)
}
return (
<Button className="market-btn" disabled={!!safeMode} icon={<Download size={13} aria-hidden="true" />} onClick={() => openVersionPicker(item)}>
<Button className="market-btn" disabled={!!safeMode} icon={<Download size={13} aria-hidden="true" />} onClick={() => void install(item)}>
{tr('pluginMarketInstall')}
</Button>
)
@@ -536,73 +498,6 @@ export const PluginMarket: React.FC<Props> = ({
</>
)}
{versionPick && (
<Modal
title={tr('pluginMarketPickVersionTitle')}
subtitle={locText(versionPick.item.entry.name, locale, versionPick.item.entry.id)}
closeLabel={tr('close')}
onClose={() => setVersionPick(null)}
>
<div className="dialog-body">
<div className="market-version-list" role="radiogroup" aria-label={tr('pluginMarketPickVersionTitle')}>
{entryReleases(versionPick.item).map((rel) => {
const selected = versionPick.selected === rel.version
const isCurrent = versionPick.item.installed && versionPick.item.installed_version === rel.version
const notes = locText(rel.changelog, locale, '')
const date = formatShortDate(rel.published_at)
const size = formatByteSize(rel.size_bytes)
return (
<label
key={rel.version}
className={`market-version-opt${selected ? ' is-selected' : ''}`}
>
<input
type="radio"
name="market-version"
checked={selected}
onChange={() => setVersionPick({ ...versionPick, selected: rel.version })}
/>
<div className="market-version-main">
<div className="market-version-head">
<span className="market-card-version">v{rel.version}</span>
{rel.channel === 'alpha' && (
<span className="market-alpha-badge">{tr('pluginMarketAlphaTag')}</span>
)}
{isCurrent && (
<span className="market-version-current">{tr('pluginMarketCurrentVersion')}</span>
)}
<span className="market-version-meta">
{[date, size].filter(Boolean).join(' · ')}
</span>
</div>
{notes && <p className="market-version-notes">{notes}</p>}
</div>
</label>
)
})}
</div>
</div>
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" onClick={() => setVersionPick(null)}>{tr('cancel')}</Button>
<Button
variant="primary"
disabled={!versionPick.selected || !!safeMode}
icon={<Download size={13} aria-hidden="true" />}
onClick={() => {
const target = versionPick
setVersionPick(null)
void install(target.item, target.selected)
}}
>
{tr('pluginMarketPickVersionInstall')}
</Button>
</span>
</div>
</Modal>
)}
{prompt && (
<Modal
title={tr('pluginEnablePromptTitle', { name: locText(prompt.name, locale, prompt.id) })}
+28 -1
View File
@@ -4,6 +4,8 @@ import '../i18n/domains/settings.gen'
import { locText, t } from '../i18n'
import { Locale, SettingProperty, SettingsSchema } from '../types'
import { NumberField, PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
import { Button } from '../ui/controls'
import { api } from '../wails'
interface Props {
locale: Locale
@@ -13,6 +15,8 @@ interface Props {
groupFilter?: string
onChange: (next: Record<string, unknown>, patch: Record<string, unknown>) => void
hideGroupHeader?: boolean
pathFields?: Readonly<Record<string, string | true>>
onPickError?: (error: unknown) => void
}
const SECRET_MASK = '••••••••'
@@ -20,7 +24,7 @@ const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
/** Lazy-loaded JSON Schema form renderer supporting x-secret, x-effect, and x-scope. */
export const SchemaForm: React.FC<Props> = ({
locale, schema, values, scopeFilter, groupFilter, onChange, hideGroupHeader,
locale, schema, values, scopeFilter, groupFilter, onChange, hideGroupHeader, pathFields, onPickError,
}) => {
const propsMap = schema.properties ?? {}
const keys = (schema['x-order'] && schema['x-order'].length > 0
@@ -134,6 +138,29 @@ export const SchemaForm: React.FC<Props> = ({
)
}
const pathField = pathFields?.[k]
if (pathField !== undefined) {
return (
<div className="input-group">
<input
type="text"
className="input rg-p-input"
aria-label={label}
value={String(cur ?? '')}
onChange={(e) => setKey(k, e.target.value)}
/>
<Button onClick={async () => {
try {
const path = pathField === true ? await api.PickDirectory(label) : await api.PickFile(label, pathField)
if (path) setKey(k, path)
} catch (error) {
onPickError?.(error)
}
}}>{t(locale, 'choose')}</Button>
</div>
)
}
return (
<input
type="text"
+144 -61
View File
@@ -13,18 +13,26 @@ import {
memorySafeLimitGB,
parseMemoryGB,
recommendedCPUs,
canKeepDisplayPreset,
fullscreenDisplayPresets,
FullscreenDisplayPreset,
hidpiLooksLike,
hostDisplayAdvice,
hostDisplayDesc,
windowDisplayPresets,
recommendedMemoryGB,
recommendedResolution,
shortGPUName,
sshCommand,
} from '../lib/format'
import {
buildResolutionOptions,
buildSettingsSaveDiff,
countChangedSettingsFields,
deriveSettingsResolutionState,
expandTouchedSettingsFields,
normalizeResolution,
reconcileSettingsFormOnBaseChange,
resolveCustomResBlur,
selectSettingsResolution,
switchSettingsGraphics,
toggleSettingsBorderless,
} from '../lib/displayResolution'
import { applyKernelIrqchip, findOptimization, kernelIrqchipHint, parseKernelIrqchip } from '../lib/optimizations'
import { useVMStats } from '../lib/vmStats'
import { HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMAffinityStatus, VMDetail, VMStats, DiskCache } from '../types'
@@ -37,7 +45,6 @@ import { formatAffinitySummary } from './AffinityDialog'
import { VMNetworkSettings } from './VMNetworkSettings'
import { DefenderExclusionRow, DiskMaintenanceRows, useDiskMaintenance } from './vmSettings/disk'
import { DiskCacheRow } from './vmSettings/diskCache'
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'
@@ -70,6 +77,7 @@ const FIELD_CAT: Record<Field, Cat> = {
graphics: 'display',
gpu: 'display',
resolution: 'display',
auto_resolution: 'display',
displays: 'display',
borderless: 'display',
disk_controller: 'storage',
@@ -88,18 +96,16 @@ const FIELDS = Object.keys(FIELD_CAT) as Field[]
const LOG_LEVELS = ['error', 'warn', 'info', 'debug', 'trace'] as const
const CUSTOM = '__custom'
const RES_RE = /^\s*\d{3,5}\s*[x×]\s*\d{3,5}\s*$/i
const normPath = (s: string | undefined) => (s ?? '').replace(/\//g, '\\').toLowerCase()
const normRes = (s: string | undefined) => (s ?? '').replace(/\s/g, '').replace(/×/g, 'x').toLowerCase()
/** 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) {
case 'memory': return parseMemoryGB(a as string) === parseMemoryGB(b as string)
case 'gpu': return normPath(a as string) === normPath(b as string)
case 'resolution': return normRes(a as string) === normRes(b as string)
case 'resolution': return normalizeResolution(a as string) === normalizeResolution(b as string)
case 'log_level':
case 'extra_args':
case 'audio_backend':
@@ -122,6 +128,7 @@ function baseline(detail: VMDetail, host: HostReport): SetOpts {
disk_controller: detail.disk_controller,
disk_cache: (detail.disk_cache as DiskCache) || 'default',
resolution: detail.resolution,
auto_resolution: !!detail.auto_resolution,
borderless: detail.borderless,
...(detail.capture_supported ? { capture: detail.capture } : {}),
gpu: icd ?? (detail.gpu || 'auto'),
@@ -175,7 +182,6 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
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, diskPath: detail.disk, running, stats, onError: setErr, onDiskChanged })
const timezone = useGuestTimezone(driverID, detail.name, running, cat === 'general')
@@ -187,24 +193,47 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
const tzBusy = timezone.tzBusy
const pane = useRef<HTMLDivElement>(null)
const presets = windowDisplayPresets(displayProfile, fixedModeSupported)
const fsPresets = fullscreenDisplayPresets(displayProfile)
const activePresets: FullscreenDisplayPreset[] = form.borderless ? fsPresets : presets
const presetHit = activePresets.some((p) => same('resolution', p.resolution, form.resolution))
const [forceCustomRes, setCustomRes] = useState(false)
const customRes = forceCustomRes || !presetHit
const { presets, fsPresets, activePresets, autoPreset, customRes, resValue, resBad } = deriveSettingsResolutionState({
form,
displayProfile,
fixedModeSupported,
forceCustomRes,
})
const [customLog, setCustomLog] = useState(!!form.log_level && !(LOG_LEVELS as readonly string[]).includes(form.log_level))
// The detail the panel opened with can be a stale one (reopened right after
// a save, before the refreshed detail arrives): follow newer details until
// the person changes something.
const edited = useRef(false)
// a save, before the refreshed detail arrives) or refreshed in the background:
// sync untouched fields from the latest baseline while preserving user edits.
const vmIdentity = `${driverID}:${detail.name}`
const vmIdentityRef = useRef(vmIdentity)
const touchedFieldsRef = useRef<Set<Field>>(new Set())
useEffect(() => {
if (edited.current) return
setForm(base)
setCustomRes(false)
setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
}, [base])
const prevKey = vmIdentityRef.current
vmIdentityRef.current = vmIdentity
if (prevKey !== vmIdentity) {
touchedFieldsRef.current.clear()
setIssues([])
setErr('')
setCustomRes(false)
setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
} else {
const touched = touchedFieldsRef.current
if (!touched.has('resolution') && !touched.has('auto_resolution')) {
setCustomRes(false)
}
if (!touched.has('log_level')) {
setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
}
}
setForm((cur) => reconcileSettingsFormOnBaseChange({
previousVMKey: prevKey,
nextVMKey: vmIdentity,
form: cur,
base,
touchedFields: touchedFieldsRef.current,
}).form)
}, [base, vmIdentity])
useEffect(() => {
setForm((f) => {
@@ -216,25 +245,34 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
}, [detail.capture_supported, detail.capture])
const set = (patch: Partial<SetOpts>) => {
edited.current = true
const touched = expandTouchedSettingsFields(Object.keys(patch)) as Field[]
for (const f of touched) touchedFieldsRef.current.add(f)
setForm((f) => ({ ...f, ...patch }))
const touched = Object.keys(patch)
setIssues((list) => list.filter((i) => !touched.includes(i.field)))
setIssues((list) => list.filter((i) => !touched.includes(i.field as Field)))
}
const dirty = (f: Field) => (f === 'capture' && !detail.capture_supported ? false : !same(f, form[f], base[f]))
const reset = (f: Field) => () => {
set({ [f]: base[f] } as Partial<SetOpts>)
if (f === 'resolution' || f === 'borderless') setCustomRes(false)
const toClear = expandTouchedSettingsFields([f]) as Field[]
for (const field of toClear) touchedFieldsRef.current.delete(field)
setForm((cur) => {
const next = { ...cur }
for (const field of toClear) {
;(next as unknown as Record<string, unknown>)[field] = (base as unknown as Record<string, unknown>)[field]
}
return next
})
setIssues((list) => list.filter((i) => !toClear.includes(i.field as Field)))
if (f === 'resolution' || f === 'auto_resolution' || f === 'borderless') setCustomRes(false)
if (f === 'log_level') setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
}
const changed = FIELDS.filter(dirty)
const changedIn = (c: Cat) => changed.filter((f) => FIELD_CAT[f] === c).length
const changedCount = countChangedSettingsFields(changed)
const changedIn = (c: Cat) => countChangedSettingsFields(changed.filter((f) => FIELD_CAT[f] === c))
const issueOf = (f: Field) => issues.find((i) => i.field === f)?.message
const issueIn = (c: Cat) => issues.some((i) => FIELD_CAT[i.field as Field] === c) || (c === 'display' && resBad)
const strayIssues = issues.filter((i) => !(i.field in FIELD_CAT))
// Inline checks the backend would also reject, so the row says it first.
const resBad = customRes && !RES_RE.test(form.resolution ?? '')
const sshOn = (form.ssh_port ?? 0) > 0
const localBlock = resBad
const nestedVirtAvailable = host.whpx === 'ready' && host.whpx_caps?.nested_vmx && !host.needs_cold_reboot_workaround
@@ -283,8 +321,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
setIssues([])
setBusy(true)
try {
const diff: SetOpts = { name: detail.name }
for (const f of changed) (diff as unknown as Record<string, unknown>)[f] = form[f]
const diff = buildSettingsSaveDiff(detail.name, changed, form, base)
const iss = await api.ValidateSet(diff)
if (iss && iss.length > 0) {
setIssues(iss)
@@ -302,7 +339,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
}
const resetAll = () => {
edited.current = false
touchedFieldsRef.current.clear()
setForm(base)
setIssues([])
setCustomRes(false)
@@ -499,19 +536,21 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
const vgpu = form.graphics !== 'vmware-svga'
const targetDisp = activeTargetDisplay
const hidpiAdvice = hostDisplayAdvice(displayProfile, tr, presets)
const resValue = customRes ? CUSTOM : activePresets.find((p) => same('resolution', p.resolution, form.resolution))?.resolution
const changeGraphics = (graphics: string) => {
const next = switchSettingsGraphics(graphics)
if (next.forceCustomRes !== undefined) setCustomRes(next.forceCustomRes)
set(next.patch)
}
const toggleBorderless = (borderless: boolean) => {
const targetPresets = borderless ? fsPresets : presets
if (!customRes && !targetPresets.some((p) => canKeepDisplayPreset(p, form.resolution, borderless))) {
const nextRes = borderless
? (targetDisp && targetDisp.width > 0 && targetDisp.height > 0
? `${targetDisp.width}x${targetDisp.height}`
: targetPresets[0]?.resolution ?? form.resolution)
: recommendedResolution(displayProfile)
set({ borderless, resolution: nextRes })
return
}
set({ borderless })
set(toggleSettingsBorderless({
borderless,
form,
displayProfile,
targetDisplay: targetDisp,
presets,
fsPresets,
customRes,
}))
}
const resArt = (r: string) => {
const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(r)
@@ -530,7 +569,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
<Segmented
label={tr('graphicsBackend')}
value={form.graphics}
onChange={(graphics) => set({ graphics })}
onChange={changeGraphics}
options={[
{ value: 'reims-vgpu', label: tr('graphicsReimsShort') },
{ value: 'vmware-svga', label: tr('graphicsSvgaShort') },
@@ -553,7 +592,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
<button
type="button"
className="link-btn"
onClick={() => set({ graphics: 'vmware-svga' })}
onClick={() => changeGraphics('vmware-svga')}
>
{tr('gpuSwitchSvga')}
</button>
@@ -577,7 +616,11 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
/>
<SetRow
{...rowProps('resolution')}
error={issueOf('resolution') ?? (resBad ? tr('resInvalid') : undefined)}
dirty={dirty('resolution') || dirty('auto_resolution')}
onReset={reset('resolution')}
disabled={!vgpu}
reason={tr('gpuSvgaReason')}
error={issueOf('resolution') ?? issueOf('auto_resolution') ?? (resBad ? tr('resInvalid') : undefined)}
title={tr('resolution')}
desc={hostDisplayDesc(host, tr, activeTargetDisplay, (d) =>
tr('targetDisplayHint', {
@@ -593,13 +636,41 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
label={tr('resolution')}
value={resValue}
onChange={(v) => {
if (v === CUSTOM) { setCustomRes(true); return }
setCustomRes(false)
set({ resolution: v })
const next = selectSettingsResolution({ value: v, form, base, autoPreset })
setCustomRes(next.forceCustomRes)
set(next.patch)
}}
options={[
...activePresets.map((p) => ({
value: p.resolution,
options={buildResolutionOptions({
graphics: form.graphics,
autoPreset,
activePresets,
includeCustom: true,
}).map((item) => {
if (item.kind === 'auto') {
const p = item.preset!
return {
value: item.value,
title: tr('resAuto'),
sub: tr('resAutoSub', { res: p.label }),
art: resArt(p.resolution),
badges: [
p.hidpi ? tr('hidpiPresetBadge') : '',
p.scaleBadge ?? '',
tr('recommendedBadge'),
].filter(Boolean),
}
}
if (item.kind === 'custom') {
return {
value: item.value,
title: tr('resCustom'),
sub: tr('resCustomSub'),
art: <span className="screen-art custom" aria-hidden="true" />,
}
}
const p = item.preset!
return {
value: item.value,
title: p.label,
sub: p.hidpi ? hidpiLooksLike(p.resolution, tr) : undefined,
art: resArt(p.resolution),
@@ -610,9 +681,8 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
p.scaleToFit ? tr('resScaleToFitWindow') : '',
p.recommended ? tr('recommendedBadge') : '',
].filter(Boolean),
})),
{ value: CUSTOM, title: tr('resCustom'), sub: tr('resCustomSub'), art: <span className="screen-art custom" aria-hidden="true" /> },
]}
}
})}
/>
{customRes && (
<input
@@ -622,6 +692,20 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
autoFocus
value={form.resolution ?? ''}
onChange={(e) => set({ resolution: e.target.value })}
onBlur={() => {
const blurred = resolveCustomResBlur({
resolution: form.resolution,
autoResolution: form.auto_resolution,
forceCustomRes,
activePresets,
})
if (blurred.nextResolution !== undefined && blurred.nextResolution !== form.resolution) {
set({ resolution: blurred.nextResolution })
}
if (blurred.exitCustom) {
setCustomRes(false)
}
}}
/>
)}
{!form.borderless && hidpiAdvice && <div className="srow-desc res-advice">{hidpiAdvice}</div>}
@@ -760,7 +844,6 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
/>
</SetGroup>
)}
<KeymapSection locale={locale} vm={detail.name} state={keymap} captureSupported={detail.capture_supported} />
<VMPluginGroup locale={locale} group="keyboard" state={plugins} />
<SetGroup title={tr('catAudio')} note={tr('audioTroubleshootNote')}>
<SetRow
@@ -904,10 +987,10 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
<div className="dialog-foot">
<span className="foot-status" aria-live="polite">
{changed.length > 0
? <><span className="dirty-dot" aria-hidden="true" />{tr('pendingChanges', { n: changed.length })}</>
{changedCount > 0
? <><span className="dirty-dot" aria-hidden="true" />{tr('pendingChanges', { n: changedCount })}</>
: <span className="muted">{tr('noChanges')}</span>}
{changed.length > 0 && (
{changedCount > 0 && (
<button type="button" className="link-btn" disabled={busy} onClick={resetAll}>{tr('resetAll')}</button>
)}
</span>
+9 -3
View File
@@ -8,6 +8,7 @@ import { Button } from '../ui/controls'
import { PopupSelect } from '../ui/settings'
import { gpuCompatHint, recommendedMemoryGB, shortGPUName } from '../lib/format'
import { describeHostWHPX } from '../lib/hypervisor'
import { hasStambhaRuntime } from '../lib/endpoints'
import { api } from '../wails'
import { PluginAppIcon } from './PluginAppIcon'
import { RuntimeOnline } from './RuntimeOnline'
@@ -80,8 +81,13 @@ const FolderStep: React.FC<StepProps> = ({ locale, locales, state, tr, onLocale,
}, [selected])
const browse = async () => {
const dir = await api.PickDirectory(tr('setupTitle')).catch(() => '')
if (dir) { setCustom(dir); setCustomMode(true); setSelected(dir) }
try {
const dir = await api.PickDirectory(tr('setupTitle'))
if (dir) { setCustom(dir); setCustomMode(true); setSelected(dir) }
} catch (e) {
console.warn('[setup] PickDirectory failed:', e)
onError(tr('failGeneric'), e)
}
}
const next = async () => {
@@ -200,7 +206,7 @@ const FolderStep: React.FC<StepProps> = ({ locale, locales, state, tr, onLocale,
}
const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onChannel, onInstallRuntime, onCancelTask, onImportRuntime, onFolderDone, onFinish, onError }) => {
const ready = !!state.active_runtime
const ready = !!state.active_runtime || hasStambhaRuntime(state.runtimes)
const { host } = state
const [enabling, setEnabling] = useState(false)
const [activating, setActivating] = useState('')
+6 -1
View File
@@ -32,7 +32,12 @@ export const SnapshotSection: React.FC<Props> = ({ locale, driverID, name, state
const loadSnapshots = () => {
if (!shown) { setSnapshots([]); return }
api.ListSnapshots(driverID, name).then((list) => setSnapshots(list ?? [])).catch(() => setSnapshots([]))
api.ListSnapshots(driverID, name)
.then((list) => setSnapshots(list ?? []))
.catch((e) => {
console.warn('[snapshots] ListSnapshots failed:', driverID, name, e)
setSnapshots([])
})
}
useEffect(() => {
setCreatingSnap(false)
+6 -1
View File
@@ -29,7 +29,12 @@ export function useSSHAccess({ locale, driverID, name, enabled, onToast, onError
useEffect(() => {
if (!enabled) { setSshUser(''); return }
let live = true
api.GetVMSSHUser(driverID, name).then((u) => { if (live) setSshUser(u ?? '') }).catch(() => { if (live) setSshUser('') })
api.GetVMSSHUser(driverID, name)
.then((u) => { if (live) setSshUser(u ?? '') })
.catch((e) => {
console.warn('[ssh] GetVMSSHUser failed:', driverID, name, e)
if (live) setSshUser('')
})
return () => { live = false }
}, [driverID, name, enabled])
+6 -2
View File
@@ -1,6 +1,7 @@
import { ChevronRight, Copy } from 'lucide-react'
import React from 'react'
import { I18nKey, t } from '../../i18n'
import { formatResolutionLabel } from '../../lib/format'
import { Locale, VMDetail, VMInfo } from '../../types'
import { IconButton } from '../../ui/controls'
@@ -16,6 +17,9 @@ interface Props {
/** The raw values upstream tools use for the VM, folded by default. */
export const TechInfo: React.FC<Props> = ({ locale, name, driverID, detail, vmInfo, onCopy }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const resolutionValue = detail
? (detail.graphics !== 'vmware-svga' && detail.auto_resolution ? formatResolutionLabel(detail.resolution, true, tr) : detail.resolution)
: ''
const copyTechSummary = () => {
if (!detail) {
if (!vmInfo) return
@@ -32,7 +36,7 @@ export const TechInfo: React.FC<Props> = ({ locale, name, driverID, detail, vmIn
`${tr('fieldCPUModel')}: ${detail.cpu_model || 'auto'}`,
`${tr('fieldGraphicsBackend')}: ${detail.graphics}`,
...(detail.gpu && detail.gpu !== 'auto' ? [`${tr('fieldICD')}: ${detail.gpu}`] : []),
`${tr('resolution')}: ${detail.displays} × ${detail.resolution}`,
`${tr('resolution')}: ${detail.displays} × ${resolutionValue}`,
`${tr('fieldController')}: ${detail.disk_controller}`,
`${tr('fieldDisk')}: ${detail.disk}`,
`${tr('fieldNetwork')}: ${detail.network_summary || tr('off')}`,
@@ -71,7 +75,7 @@ export const TechInfo: React.FC<Props> = ({ locale, name, driverID, detail, vmIn
<dt>{tr('fieldCPUModel')}</dt><dd className="mono">{detail.cpu_model || 'auto'}</dd>
<dt>{tr('fieldGraphicsBackend')}</dt><dd>{detail.graphics}</dd>
{detail.gpu && detail.gpu !== 'auto' && (<><dt>{tr('fieldICD')}</dt><dd className="mono">{detail.gpu}</dd></>)}
<dt>{tr('resolution')}</dt><dd>{detail.displays} × {detail.resolution}</dd>
<dt>{tr('resolution')}</dt><dd>{detail.displays} × {resolutionValue}</dd>
<dt>{tr('fieldController')}</dt><dd>{detail.disk_controller}</dd>
<dt>{tr('fieldDisk')}</dt><dd className="mono">{detail.disk}</dd>
<dt>{tr('fieldNetwork')}</dt><dd className="mono">{detail.network_summary || tr('off')}</dd>
@@ -1,92 +0,0 @@
import React, { useEffect, useRef, useState } from 'react'
import { I18nKey, t } from '../../i18n'
import { createKeymapRequests, keymapPresetUpdate, keymapStatusHint, keymapUpdate, visibleKeymapPresets, type KeymapState } from '../../lib/vmKeymap'
import { Locale, VMKeymapGuestModifier, VMKeymapHostModifier, VMKeymapPreset } from '../../types'
import { PopupSelect, Segmented, SetGroup, SetRow, SetValue, Switch } from '../../ui/settings'
import { api } from '../../wails'
const PRESET_LABEL: Record<VMKeymapPreset, I18nKey> = {
off: 'keymapPresetOff',
win_to_cmd: 'keymapPresetWinToCmd',
swap_alt_win: 'keymapPresetSwapAltWin',
custom: 'keymapPresetCustom',
}
/** 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<KeymapState>({ 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<typeof useKeymap>; captureSupported: boolean }> = ({ locale, vm, state, captureSupported }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const { keymap, keymapErr, keymapBusy, write } = state
const statusHint = keymap ? keymapStatusHint(keymap) : null
const presetOptions = keymap
? visibleKeymapPresets(keymap.preset, captureSupported).map((value) => ({ value, label: tr(PRESET_LABEL[value]) }))
: []
return (
<SetGroup title={tr('keymapGroupTitle')} note={tr('keymapGroupNote')}>
{keymapErr && <div className="notice notice-error" role="alert">{keymapErr}</div>}
{keymap && <>
<SetRow title={tr('keymapPresetTitle')} desc={tr('keymapPresetDesc')} disabled={keymapBusy}
control={<Segmented<VMKeymapPreset> label={tr('keymapPresetTitle')} value={keymap.preset}
options={presetOptions}
onChange={(preset) => {
const request = keymapPresetUpdate(keymap, preset)
if (request) void write(vm, request)
}} />}
/>
<SetRow title={tr('keymapCaptureHostShortcutsTitle')} desc={tr('keymapCaptureHostShortcutsDesc')} disabled={keymapBusy}
control={<Switch label={tr('keymapCaptureHostShortcutsTitle')} checked={keymap.capture_host_shortcuts}
onChange={(capture_host_shortcuts) => { void write(vm, keymapUpdate(keymap, { capture_host_shortcuts })) }} />}
/>
{statusHint && (
<SetValue title={tr('keymapStatusTitle')} value={tr(statusHint.key, statusHint.vars)} />
)}
{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]) => (
<SetRow key={modifier} title={tr(label)} disabled={keymapBusy}
control={<PopupSelect<VMKeymapGuestModifier> 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 } })) }} />}
/>
))}
</>}
</SetGroup>
)
}
+6
View File
@@ -3,6 +3,7 @@
export const coreZh: Record<string, string> = {
"affinityMenu": "处理器相关性…",
"appearance": "外观",
"autoResolution": "自动分辨率",
"backToEdit": "返回修改",
"borderless": "无边框全屏",
"cancel": "取消",
@@ -138,6 +139,8 @@ export const coreZh: Record<string, string> = {
"quitFailed": "已取消退出",
"quitInProgress": "正在退出…",
"refresh": "刷新",
"resAuto": "自动",
"resAutoValue": "自动({res})",
"resLooksLike": "看起来像 {w} × {h}",
"resizeLogPanel": "拖动调整日志高度",
"resolution": "分辨率",
@@ -215,6 +218,7 @@ export const coreZh: Record<string, string> = {
export const coreEn: Record<string, string> = {
"affinityMenu": "Processor Affinity…",
"appearance": "Appearance",
"autoResolution": "Auto resolution",
"backToEdit": "Edit and retry",
"borderless": "Borderless full screen",
"cancel": "Cancel",
@@ -350,6 +354,8 @@ export const coreEn: Record<string, string> = {
"quitFailed": "Quit canceled",
"quitInProgress": "Quitting…",
"refresh": "Refresh",
"resAuto": "Auto",
"resAutoValue": "Auto ({res})",
"resLooksLike": "Looks like {w} × {h}",
"resizeLogPanel": "Drag to resize log panel",
"resolution": "Resolution",
-6
View File
@@ -48,7 +48,6 @@ export const pluginsZh: Record<string, string> = {
"pluginLinkDevBtn": "链接插件开发目录",
"pluginLinkDevTitle": "链接本地开发插件目录",
"pluginMarketAlphaTag": "Alpha",
"pluginMarketCurrentVersion": "当前已安装",
"pluginMarketDownloading": "下载中",
"pluginMarketEmpty": "当前插件市场暂无可用条目,你仍可导入本地 .zip 插件包或配置自定义市场索引地址",
"pluginMarketFeedEnd": "共 {count} 个插件",
@@ -64,8 +63,6 @@ export const pluginsZh: Record<string, string> = {
"pluginMarketKindTheme": "主题",
"pluginMarketKindTool": "工具",
"pluginMarketLoading": "正在读取插件市场",
"pluginMarketPickVersionInstall": "安装此版本",
"pluginMarketPickVersionTitle": "选择安装版本",
"pluginMarketRefresh": "刷新索引",
"pluginMarketSearchPlaceholder": "搜索市场插件、作者或标签",
"pluginMarketSortComposite": "综合排序",
@@ -173,7 +170,6 @@ export const pluginsEn: Record<string, string> = {
"pluginLinkDevBtn": "Link plugin dev folder",
"pluginLinkDevTitle": "Link local dev plugin folder",
"pluginMarketAlphaTag": "Alpha",
"pluginMarketCurrentVersion": "Installed",
"pluginMarketDownloading": "Downloading",
"pluginMarketEmpty": "No plugins available in the market index yet. You can still import local .zip packages or configure a custom index URL.",
"pluginMarketFeedEnd": "{count} plugins",
@@ -189,8 +185,6 @@ export const pluginsEn: Record<string, string> = {
"pluginMarketKindTheme": "Themes",
"pluginMarketKindTool": "Tools",
"pluginMarketLoading": "Loading the plugin market",
"pluginMarketPickVersionInstall": "Install version",
"pluginMarketPickVersionTitle": "Select version",
"pluginMarketRefresh": "Refresh index",
"pluginMarketSearchPlaceholder": "Search market plugins, publishers, or tags",
"pluginMarketSortComposite": "Recommended",
+2 -68
View File
@@ -368,40 +368,6 @@ export const settingsZh: Record<string, string> = {
"kernelIrqchipLabel": "中断加速",
"kernelIrqchipOff": "关闭",
"kernelIrqchipOn": "开启",
"keymapCaptureHostShortcutsDesc": "虚拟机获得焦点时拦截宿主机及第三方软件的 Win / Alt 全局热键(如截图 Alt+A、Ctrl+Alt+A),避免误触;未单独映射的 Win 和 Alt 在 macOS 中仍对应 Command 和 Option",
"keymapCaptureHostShortcutsTitle": "拦截宿主机全局热键",
"keymapGroupNote": "仅在此虚拟机窗口位于前台时生效;更改立即生效,无需点击保存。Ctrl+Alt+Win 保留用于释放键盘捕获",
"keymapGroupTitle": "修饰键映射",
"keymapGuestDefault": "默认",
"keymapGuestDisabled": "禁用",
"keymapGuestEsc": "Esc",
"keymapGuestLcmd": "左 ⌘ Command",
"keymapGuestLctrl": "左 ⌃ Control",
"keymapGuestLopt": "左 ⌥ Option",
"keymapGuestRcmd": "右 ⌘ Command",
"keymapGuestRctrl": "右 ⌃ Control",
"keymapGuestRopt": "右 ⌥ Option",
"keymapHostCapslock": "Caps Lock",
"keymapHostLalt": "左 Alt",
"keymapHostLctrl": "左 Ctrl",
"keymapHostLwin": "左 Win",
"keymapHostRalt": "右 Alt",
"keymapHostRctrl": "右 Ctrl",
"keymapHostRwin": "右 Win",
"keymapInactive": "修饰键映射未启用",
"keymapInputServiceRequired": "请启用宿主输入服务以使用修饰键映射",
"keymapPending": "等待 Guest Tools 启用修饰键映射",
"keymapPresetCustom": "自定义",
"keymapPresetDesc": "调整修饰键映射(如将空格旁的 Alt 与 Win 互换以贴合 Mac 键位);不改键位时保持关闭即可",
"keymapPresetOff": "关闭",
"keymapPresetSwapAltWin": "Alt ↔ Win",
"keymapPresetTitle": "映射预设",
"keymapPresetWinToCmd": "Win → ⌘",
"keymapRunning": "虚拟机获得焦点时生效",
"keymapStatusTitle": "生效状态",
"keymapStopped": "虚拟机启动后生效",
"keymapUpgrade": "请将 Guest Tools 更新到版本 {version}",
"keymapWaiting": "等待 Guest Tools 连接",
"language": "语言",
"languageSub": "内置简体中文与英语,可通过插件扩展更多语言",
"logLevel": "日志级别",
@@ -454,6 +420,7 @@ export const settingsZh: Record<string, string> = {
"qemuASLR": "自动为 QEMU 启用 ASLR",
"qemuASLRHint": "设置随运行时版本切换,虚拟机关机后再启动时生效,可能解决 macOS Dock 图标空白的问题",
"recommendedBadge": "推荐",
"resAutoSub": "当前屏 {res}",
"resCustom": "自定义",
"resCustomSub": "宽 × 高",
"resInvalid": "格式为 宽x高,例如 2560x1600",
@@ -917,40 +884,6 @@ export const settingsEn: Record<string, string> = {
"kernelIrqchipLabel": "Interrupt acceleration",
"kernelIrqchipOff": "Off",
"kernelIrqchipOn": "On",
"keymapCaptureHostShortcutsDesc": "Blocks Win and Alt global hotkeys from the host and third-party apps (such as Alt+A or Ctrl+Alt+A for screenshots) while the VM is focused, preventing accidental triggers; unmapped Win and Alt keys still act as Command and Option in macOS",
"keymapCaptureHostShortcutsTitle": "Block host global hotkeys",
"keymapGroupNote": "Active only while this VM window is focused; changes apply immediately without clicking Save. Ctrl+Alt+Win is reserved for releasing keyboard capture",
"keymapGroupTitle": "Modifier keys",
"keymapGuestDefault": "Default",
"keymapGuestDisabled": "Disabled",
"keymapGuestEsc": "Esc",
"keymapGuestLcmd": "Left ⌘ Command",
"keymapGuestLctrl": "Left ⌃ Control",
"keymapGuestLopt": "Left ⌥ Option",
"keymapGuestRcmd": "Right ⌘ Command",
"keymapGuestRctrl": "Right ⌃ Control",
"keymapGuestRopt": "Right ⌥ Option",
"keymapHostCapslock": "Caps Lock",
"keymapHostLalt": "Left Alt",
"keymapHostLctrl": "Left Ctrl",
"keymapHostLwin": "Left Win",
"keymapHostRalt": "Right Alt",
"keymapHostRctrl": "Right Ctrl",
"keymapHostRwin": "Right Win",
"keymapInactive": "Modifier mapping is inactive",
"keymapInputServiceRequired": "Enable Host Input Service to use modifier mapping",
"keymapPending": "Waiting for Guest Tools to activate modifier mapping",
"keymapPresetCustom": "Custom",
"keymapPresetDesc": "Remaps modifier keys (such as swapping Alt and Win next to Space to match a Mac keyboard); leave Off if no remapping is needed",
"keymapPresetOff": "Off",
"keymapPresetSwapAltWin": "Alt ↔ Win",
"keymapPresetTitle": "Preset",
"keymapPresetWinToCmd": "Win → ⌘",
"keymapRunning": "Active while this VM is focused",
"keymapStatusTitle": "Status",
"keymapStopped": "Applies when this VM is running",
"keymapUpgrade": "Update Guest Tools to version {version}",
"keymapWaiting": "Waiting for Guest Tools to connect",
"language": "Language",
"languageSub": "Simplified Chinese and English built in; add more via plugins",
"logLevel": "Log level",
@@ -1003,6 +936,7 @@ export const settingsEn: Record<string, string> = {
"qemuASLR": "Automatically enable ASLR for QEMU",
"qemuASLRHint": "Applies to the selected runtime and may restore blank macOS Dock icons after you shut down and start the VM again",
"recommendedBadge": "Recommended",
"resAutoSub": "Follows display · {res}",
"resCustom": "Custom",
"resCustomSub": "Width × height",
"resInvalid": "Use WIDTHxHEIGHT, e.g. 2560x1600",
+14
View File
@@ -2,6 +2,12 @@
import { registerBuiltinDomain } from '../runtime'
export const wizardZh: Record<string, string> = {
"armRestoreDownload": "下载 IPSW",
"armRestoreDownloaded": "已下载的 IPSW",
"armRestoreGroup": "ARM 恢复镜像",
"armRestoreMediaHint": "从 Apple 下载 IPSW。创建虚拟机时,请在下方选择已制作的 Stambha 启动介质和可写虚拟磁盘。",
"armRestoreVersion": "macOS 27.2.1 (26B131) · 25.6 GB",
"armRuntimeLabel": "ARM64 来宾",
"commandToggle": "等效命令",
"commandToggleHint": "在终端运行下面这条命令效果相同",
"createNow": "创建",
@@ -90,9 +96,16 @@ export const wizardZh: Record<string, string> = {
"wizardDriverGroup": "客体平台驱动",
"wizardDriverType": "驱动类型",
"wizardTitle": "新建虚拟机",
"x86RuntimeLabel": "x86-64 来宾",
}
export const wizardEn: Record<string, string> = {
"armRestoreDownload": "Download IPSW",
"armRestoreDownloaded": "Downloaded IPSW",
"armRestoreGroup": "ARM restore image",
"armRestoreMediaHint": "Download the IPSW from Apple. To create a VM, select prepared Stambha boot media and a writable virtual disk below.",
"armRestoreVersion": "macOS 27.2.1 (26B131) · 25.6 GB",
"armRuntimeLabel": "ARM64 guest",
"commandToggle": "Equivalent command",
"commandToggleHint": "Running this in a terminal does the same thing",
"createNow": "Create",
@@ -181,6 +194,7 @@ export const wizardEn: Record<string, string> = {
"wizardDriverGroup": "Guest driver",
"wizardDriverType": "Driver",
"wizardTitle": "New virtual machine",
"x86RuntimeLabel": "x86-64 guest",
}
registerBuiltinDomain(wizardZh, wizardEn)
+12 -38
View File
@@ -68,6 +68,12 @@ export type I18nKey =
| "appVersionTitle"
| "appearance"
| "appliesNextStart"
| "armRestoreDownload"
| "armRestoreDownloaded"
| "armRestoreGroup"
| "armRestoreMediaHint"
| "armRestoreVersion"
| "armRuntimeLabel"
| "attachGuestTools"
| "attachInstaller"
| "audioBackendAuto"
@@ -79,6 +85,7 @@ export type I18nKey =
| "audioDisabledReason"
| "audioTroubleshootNote"
| "autoPinPCores"
| "autoResolution"
| "back"
| "backToEdit"
| "borderless"
@@ -608,40 +615,6 @@ export type I18nKey =
| "kernelIrqchipLabel"
| "kernelIrqchipOff"
| "kernelIrqchipOn"
| "keymapCaptureHostShortcutsDesc"
| "keymapCaptureHostShortcutsTitle"
| "keymapGroupNote"
| "keymapGroupTitle"
| "keymapGuestDefault"
| "keymapGuestDisabled"
| "keymapGuestEsc"
| "keymapGuestLcmd"
| "keymapGuestLctrl"
| "keymapGuestLopt"
| "keymapGuestRcmd"
| "keymapGuestRctrl"
| "keymapGuestRopt"
| "keymapHostCapslock"
| "keymapHostLalt"
| "keymapHostLctrl"
| "keymapHostLwin"
| "keymapHostRalt"
| "keymapHostRctrl"
| "keymapHostRwin"
| "keymapInactive"
| "keymapInputServiceRequired"
| "keymapPending"
| "keymapPresetCustom"
| "keymapPresetDesc"
| "keymapPresetOff"
| "keymapPresetSwapAltWin"
| "keymapPresetTitle"
| "keymapPresetWinToCmd"
| "keymapRunning"
| "keymapStatusTitle"
| "keymapStopped"
| "keymapUpgrade"
| "keymapWaiting"
| "language"
| "languageSub"
| "localeAuto"
@@ -798,7 +771,6 @@ export type I18nKey =
| "pluginLinkDevBtn"
| "pluginLinkDevTitle"
| "pluginMarketAlphaTag"
| "pluginMarketCurrentVersion"
| "pluginMarketDownloading"
| "pluginMarketEmpty"
| "pluginMarketFeedEnd"
@@ -814,8 +786,6 @@ export type I18nKey =
| "pluginMarketKindTheme"
| "pluginMarketKindTool"
| "pluginMarketLoading"
| "pluginMarketPickVersionInstall"
| "pluginMarketPickVersionTitle"
| "pluginMarketRefresh"
| "pluginMarketSearchPlaceholder"
| "pluginMarketSortComposite"
@@ -881,6 +851,9 @@ export type I18nKey =
| "quitInProgress"
| "recommendedBadge"
| "refresh"
| "resAuto"
| "resAutoSub"
| "resAutoValue"
| "resCustom"
| "resCustomSub"
| "resInvalid"
@@ -1222,4 +1195,5 @@ export type I18nKey =
| "wizardBasics"
| "wizardDriverGroup"
| "wizardDriverType"
| "wizardTitle";
| "wizardTitle"
| "x86RuntimeLabel";
+325
View File
@@ -0,0 +1,325 @@
import {
canKeepDisplayPreset,
FullscreenDisplayPreset,
fullscreenDisplayPresets,
recommendedResolution,
resolveAutoDisplayPreset,
windowDisplayPresets,
} from './format'
import { CreateOpts, DisplayInfo, HostReport, SetOpts } from '../types'
export const AUTO_RESOLUTION_OPTION = '__auto'
export const CUSTOM_RESOLUTION_OPTION = '__custom'
const CANONICAL_RESOLUTION_RE = /^\d{3,5}x\d{3,5}$/
export function canonicalResolution(raw: string | undefined): string {
const trimmed = (raw ?? '').trim()
const m = /^(\d+)\s*[x×X]\s*(\d+)$/.exec(trimmed)
return m ? `${m[1]}x${m[2]}` : trimmed
}
export const normalizeResolution = (raw: string | undefined) => canonicalResolution(raw).toLowerCase()
export function isValidResolution(raw: string | undefined): boolean {
return CANONICAL_RESOLUTION_RE.test(canonicalResolution(raw))
}
interface ResolutionOptionItem {
value: string
kind: 'auto' | 'preset' | 'custom'
preset?: FullscreenDisplayPreset
}
export function buildResolutionOptions(params: {
graphics?: string
autoPreset: FullscreenDisplayPreset
activePresets: FullscreenDisplayPreset[]
includeCustom?: boolean
}): ResolutionOptionItem[] {
const items: ResolutionOptionItem[] = []
if (supportsAutoResolution(params.graphics)) {
items.push({ value: AUTO_RESOLUTION_OPTION, kind: 'auto', preset: params.autoPreset })
}
for (const preset of params.activePresets) {
items.push({ value: preset.resolution, kind: 'preset', preset })
}
if (params.includeCustom) {
items.push({ value: CUSTOM_RESOLUTION_OPTION, kind: 'custom' })
}
return items
}
export function supportsAutoResolution(graphics: string | undefined): boolean {
return graphics !== 'vmware-svga'
}
export function deriveSettingsResolutionState(params: {
form: Pick<SetOpts, 'graphics' | 'resolution' | 'auto_resolution' | 'borderless'>
displayProfile: HostReport
fixedModeSupported: boolean
forceCustomRes: boolean
}) {
const { form, displayProfile, fixedModeSupported, forceCustomRes } = params
const vgpu = supportsAutoResolution(form.graphics)
const autoOn = vgpu && !!form.auto_resolution
const presets = windowDisplayPresets(displayProfile, fixedModeSupported)
const fsPresets = fullscreenDisplayPresets(displayProfile)
const activePresets: FullscreenDisplayPreset[] = form.borderless ? fsPresets : presets
const autoPreset = resolveAutoDisplayPreset(displayProfile, !!form.borderless, fixedModeSupported)
const matchedPreset = activePresets.find((p) => normalizeResolution(p.resolution) === normalizeResolution(form.resolution))
const presetHit = !!matchedPreset
const customRes = vgpu && !autoOn && (forceCustomRes || !presetHit)
const resValue = autoOn
? AUTO_RESOLUTION_OPTION
: (customRes ? CUSTOM_RESOLUTION_OPTION : matchedPreset?.resolution)
const resBad = vgpu && !autoOn && customRes && !isValidResolution(form.resolution)
return { presets, fsPresets, activePresets, autoPreset, matchedPreset, presetHit, customRes, resValue, resBad }
}
export function selectSettingsResolution(params: {
value: string
form: Pick<SetOpts, 'resolution'>
base: Pick<SetOpts, 'resolution'>
autoPreset: FullscreenDisplayPreset
}): { patch: Partial<SetOpts>; forceCustomRes: boolean } {
const { value, form, base, autoPreset } = params
if (value === AUTO_RESOLUTION_OPTION) {
return {
patch: { auto_resolution: true, resolution: base.resolution },
forceCustomRes: false,
}
}
if (value === CUSTOM_RESOLUTION_OPTION) {
return {
patch: { auto_resolution: false, resolution: form.resolution || autoPreset.resolution },
forceCustomRes: true,
}
}
return {
patch: { auto_resolution: false, resolution: value },
forceCustomRes: false,
}
}
export function shouldExitCustomResOnBlur(params: {
autoResolution?: boolean
forceCustomRes: boolean
presetHit: boolean
}): boolean {
return !params.autoResolution && params.forceCustomRes && params.presetHit
}
export function resolveCustomResBlur(params: {
resolution?: string
autoResolution?: boolean
forceCustomRes: boolean
activePresets: FullscreenDisplayPreset[]
}): { exitCustom: boolean; nextResolution?: string } {
const { resolution, autoResolution, forceCustomRes, activePresets } = params
if (autoResolution) return { exitCustom: false }
const matched = activePresets.find((p) => normalizeResolution(p.resolution) === normalizeResolution(resolution))
if (matched) {
return {
exitCustom: forceCustomRes || true,
nextResolution: matched.resolution,
}
}
if (isValidResolution(resolution)) {
const canonical = canonicalResolution(resolution)
if (canonical && canonical !== resolution) {
return { exitCustom: false, nextResolution: canonical }
}
}
return { exitCustom: false }
}
export function switchSettingsGraphics(graphics: string): { patch: Partial<SetOpts>; forceCustomRes?: boolean } {
if (!supportsAutoResolution(graphics)) {
return { patch: { graphics }, forceCustomRes: false }
}
return { patch: { graphics } }
}
export function expandTouchedSettingsFields(fields: Iterable<string>): string[] {
const out = new Set<string>()
for (const field of fields) {
out.add(field)
if (field === 'resolution' || field === 'auto_resolution') {
out.add('resolution')
out.add('auto_resolution')
}
}
return Array.from(out)
}
export function syncUntouchedSettingsForm<T extends object>(
form: T,
base: T,
touchedFields: ReadonlySet<string>,
): T {
let changed = false
const next = { ...form } as Record<string, unknown>
const baseRec = base as Record<string, unknown>
for (const key of Object.keys(baseRec)) {
if (touchedFields.has(key)) continue
if (next[key] !== baseRec[key]) {
next[key] = baseRec[key]
changed = true
}
}
return changed ? (next as T) : form
}
export function reconcileSettingsFormOnBaseChange<T extends object>(params: {
previousVMKey: string
nextVMKey: string
form: T
base: T
touchedFields: ReadonlySet<string>
}): { form: T; resetDraft: boolean } {
const { previousVMKey, nextVMKey, form, base, touchedFields } = params
if (previousVMKey !== nextVMKey) {
return { form: base, resetDraft: true }
}
return { form: syncUntouchedSettingsForm(form, base, touchedFields), resetDraft: false }
}
export function toggleSettingsBorderless(params: {
borderless: boolean
form: Pick<SetOpts, 'resolution' | 'auto_resolution'>
displayProfile: HostReport
targetDisplay?: DisplayInfo
presets: FullscreenDisplayPreset[]
fsPresets: FullscreenDisplayPreset[]
customRes: boolean
}): Partial<SetOpts> {
const { borderless, form, displayProfile, targetDisplay, presets, fsPresets, customRes } = params
if (form.auto_resolution) {
return { borderless }
}
const targetPresets = borderless ? fsPresets : presets
if (!customRes && !targetPresets.some((p) => canKeepDisplayPreset(p, form.resolution, borderless))) {
const nextRes = borderless
? (targetDisplay && targetDisplay.width > 0 && targetDisplay.height > 0
? `${targetDisplay.width}x${targetDisplay.height}`
: targetPresets[0]?.resolution ?? form.resolution)
: recommendedResolution(displayProfile)
return { borderless, resolution: nextRes }
}
return { borderless }
}
export function countChangedSettingsFields(changedFields: readonly string[]): number {
const hasBothRes = changedFields.includes('resolution') && changedFields.includes('auto_resolution')
return changedFields.length - (hasBothRes ? 1 : 0)
}
export function buildSettingsSaveDiff(
name: string,
changedFields: readonly string[],
form: SetOpts,
base?: Pick<SetOpts, 'auto_resolution'>,
): SetOpts {
const diff: SetOpts = { name }
const vgpu = supportsAutoResolution(form.graphics)
const effectiveAuto = vgpu && !!form.auto_resolution
for (const field of changedFields) {
if (field === 'resolution') {
if (!vgpu || effectiveAuto) continue
diff.resolution = canonicalResolution(form.resolution)
continue
}
if (field === 'auto_resolution') {
diff.auto_resolution = effectiveAuto
continue
}
;(diff as unknown as Record<string, unknown>)[field] = (form as unknown as Record<string, unknown>)[field]
}
if (!vgpu && changedFields.includes('graphics') && base?.auto_resolution) {
diff.auto_resolution = false
}
if (vgpu && !effectiveAuto && diff.auto_resolution === false && !diff.resolution) {
const resolved = canonicalResolution(form.resolution)
if (resolved) diff.resolution = resolved
}
return diff
}
export function initialWizardManualResolution(
draft?: { opts: Pick<CreateOpts, 'graphics' | 'auto_resolution'>; manualResolution?: boolean } | null,
): boolean {
if (!draft) return false
if (typeof draft.manualResolution === 'boolean') return draft.manualResolution
return supportsAutoResolution(draft.opts.graphics) && draft.opts.auto_resolution === false
}
export function initialWizardResolution(
host: HostReport,
fixedModeSupported: boolean,
graphics: string = 'reims-vgpu',
): Pick<CreateOpts, 'auto_resolution' | 'resolution'> {
return {
auto_resolution: supportsAutoResolution(graphics),
resolution: resolveAutoDisplayPreset(host, false, fixedModeSupported).resolution,
}
}
export function resolveEffectiveWizardOpts(
opts: CreateOpts,
autoPreset: FullscreenDisplayPreset,
): CreateOpts {
if (!supportsAutoResolution(opts.graphics)) {
return opts.auto_resolution ? { ...opts, auto_resolution: false } : opts
}
if (opts.auto_resolution) {
return { ...opts, resolution: autoPreset.resolution }
}
return opts
}
export function switchWizardGraphics(params: {
graphics: CreateOpts['graphics']
manualResolutionPicked: boolean
autoPreset: FullscreenDisplayPreset
}): Partial<CreateOpts> {
const { graphics, manualResolutionPicked, autoPreset } = params
if (!supportsAutoResolution(graphics)) {
return { graphics, auto_resolution: false }
}
if (!manualResolutionPicked) {
return { graphics, auto_resolution: true, resolution: autoPreset.resolution }
}
return { graphics }
}
export function selectWizardResolution(
value: string,
autoPreset: FullscreenDisplayPreset,
): Pick<CreateOpts, 'auto_resolution' | 'resolution'> {
if (value === AUTO_RESOLUTION_OPTION) {
return { auto_resolution: true, resolution: autoPreset.resolution }
}
return { auto_resolution: false, resolution: value }
}
export function toggleWizardBorderless(params: {
borderless: boolean
opts: Pick<CreateOpts, 'graphics' | 'auto_resolution' | 'resolution'>
host: HostReport
fixedModeSupported: boolean
windowPresets: FullscreenDisplayPreset[]
fullscreenPresets: FullscreenDisplayPreset[]
}): Partial<CreateOpts> {
const { borderless, opts, host, fixedModeSupported, windowPresets, fullscreenPresets } = params
if (supportsAutoResolution(opts.graphics) && opts.auto_resolution) {
return {
borderless,
auto_resolution: true,
resolution: resolveAutoDisplayPreset(host, borderless, fixedModeSupported).resolution,
}
}
const list = borderless ? fullscreenPresets : windowPresets
const keep = list.some((p) => canKeepDisplayPreset(p, opts.resolution, borderless))
const fallback = list.find((p) => p.recommended)?.resolution ?? list[0]?.resolution ?? opts.resolution
return keep ? { borderless } : { borderless, resolution: fallback }
}
+7 -1
View File
@@ -1,9 +1,15 @@
import type { VMEndpoint, VMInfo, VMListItem } from '../types'
import type { InstalledRuntime, 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).
const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos'
export const STAMBHA_DRIVER_ID = 'builtin.driver.stambha'
export const STAMBHA_RUNTIME_KIND = 'stambha-hosted'
export function hasStambhaRuntime(runtimes?: InstalledRuntime[] | null): boolean {
return runtimes?.some((rt) => rt.kind === STAMBHA_RUNTIME_KIND && rt.manifest.runtime_api === '0.1.0') ?? false
}
export type GuestFamily = 'macos' | 'linux' | 'windows' | 'android' | ''
+42 -1
View File
@@ -155,10 +155,18 @@ export function gpuLabel(locale: Locale, icd: string | undefined, host: HostRepo
return found ? shortGPUName(found.name) : t(locale, 'gpuAuto')
}
export function formatResolutionLabel(res: string, auto: boolean, tr: Tr): string {
const displayRes = (res ?? '').trim().replace(/\s*[x×]\s*/i, ' × ')
if (!auto) return displayRes
return displayRes ? tr('resAutoValue', { res: displayRes }) : tr('resAuto')
}
export function graphicsLabel(locale: Locale, d: VMDetail, host: HostReport): string {
if (d.graphics && d.graphics !== 'reims-vgpu') return t(locale, 'softwareGraphics')
const gpu = gpuLabel(locale, d.gpu, host)
const res = resolutionLabel(d.resolution)
const tr: Tr = (k, v) => t(locale, k, v)
const isAuto = d.graphics !== 'vmware-svga' && !!d.auto_resolution
const res = isAuto ? formatResolutionLabel(d.resolution, true, tr) : resolutionLabel(d.resolution)
const screens = d.displays > 1 ? `${d.displays} × ${res}` : res
return res ? `${gpu} · ${screens}` : gpu
}
@@ -427,6 +435,38 @@ export function fullscreenDisplayPresets(host: HostReport): FullscreenDisplayPre
return out
}
export function resolveAutoDisplayPreset(
host: HostReport,
borderless: boolean,
fixedModeSupported: boolean,
): FullscreenDisplayPreset {
if (!borderless) {
const presets = recommendedDisplayPresets(host)
return presets.find((p) => p.recommended) ?? presets[0]
}
const d = host.primary_display
if (!d || d.width <= 0 || d.height <= 0) {
return {
resolution: '1920x1080',
label: '1920 × 1080',
hidpi: false,
native: true,
recommended: true,
}
}
const fsPresets = fullscreenDisplayPresets(host)
if (fixedModeSupported) {
return fsPresets.find((p) => p.recommended) ?? fsPresets[0]
}
return {
resolution: `${d.width}x${d.height}`,
label: `${d.width} × ${d.height}`,
hidpi: !!host.fullscreen_hidpi,
native: true,
recommended: true,
}
}
export function recommendedResolution(host: HostReport): string {
if (host.recommended_resolution) return host.recommended_resolution
const rec = recommendedDisplayPresets(host).find((p) => p.recommended)
@@ -492,6 +532,7 @@ export function pendingChangeText(locale: Locale, p: { field: string; from: stri
cpus: { label: 'factCPU', fmt: (v) => tr('cores', { n: v }) },
memory: { label: 'factMemory', fmt: (v) => formatMemory(v, locale) },
resolution: { label: 'resolution', fmt: resolutionLabel },
auto_resolution: { label: 'autoResolution', fmt: bool },
gpu: { label: 'factGraphics', fmt: (v) => gpuLabel(locale, v, host) },
displays: { label: 'displays', fmt: (v) => v },
borderless: { label: 'borderless', fmt: bool },
+1 -1
View File
@@ -67,7 +67,7 @@ export function isInstallerTask(task: Task): boolean {
}
export function taskInstallerKind(task: Task): InstallerKind | '' {
if (task.installer_kind === 'offline' || task.installer_kind === 'online') return task.installer_kind
if (task.installer_kind === 'offline' || task.installer_kind === 'online' || task.installer_kind === 'arm-ipsw') return task.installer_kind
if (task.kind === 'installer-download') return 'offline'
if (task.kind === 'recovery-download') return 'online'
return ''
+2 -1
View File
@@ -159,8 +159,9 @@ export async function mountInteractiveThemeScript(
addDisposer(localDispose)
try {
setup((fn) => localDisposers.push(fn))
} catch {
} catch (e) {
// Feature-isolated error: tear down only this feature.
console.warn('[uiSdk] feature setup failed:', _name, e)
localDispose()
}
},
-77
View File
@@ -1,77 +0,0 @@
import type { VMKeymapPreset, VMKeymapStatus, VMKeymapUpdate } from '../types'
import { createVMSettingRequests } from './vmSettingRequests'
type KeymapAPI = {
GetVMKeymap(name: string): Promise<VMKeymapStatus>
SetVMKeymap(name: string, request: VMKeymapUpdate): Promise<VMKeymapStatus>
}
export type KeymapState = { keymap: VMKeymapStatus | null; error: string; busy: boolean }
type KeymapStatusKey =
| 'keymapInputServiceRequired'
| 'keymapStopped'
| 'keymapWaiting'
| 'keymapUpgrade'
| 'keymapPending'
| 'keymapRunning'
| 'keymapInactive'
type KeymapStatusHint = { key: KeymapStatusKey; vars?: { version: number } }
const ALL_KEYMAP_PRESETS: readonly VMKeymapPreset[] = ['off', 'win_to_cmd', 'swap_alt_win', 'custom']
const MODERN_KEYMAP_PRESETS: readonly VMKeymapPreset[] = ['off', 'swap_alt_win', 'custom']
export function visibleKeymapPresets(preset: VMKeymapPreset, captureSupported: boolean): readonly VMKeymapPreset[] {
if (!captureSupported && preset !== 'win_to_cmd') return MODERN_KEYMAP_PRESETS
return ALL_KEYMAP_PRESETS
}
export function keymapStatusHint(keymap: VMKeymapStatus): KeymapStatusHint | null {
if (keymap.preset === 'off' && !keymap.capture_host_shortcuts) return null
if (!keymap.input_service_available) return { key: 'keymapInputServiceRequired' }
if (!keymap.running) return { key: 'keymapStopped' }
if (keymap.needs_guest_tools && !keymap.guest_connected) return { key: 'keymapWaiting' }
if (keymap.needs_guest_tools && (keymap.guest_agent_version ?? 0) < keymap.required_agent_version) {
return { key: 'keymapUpgrade', vars: { version: keymap.required_agent_version } }
}
if (keymap.needs_guest_tools && !keymap.guest_keymap_active) return { key: 'keymapPending' }
return { key: keymap.hook_active ? 'keymapRunning' : 'keymapInactive' }
}
type KeymapRequest = Required<VMKeymapUpdate>
export function keymapUpdate(current: VMKeymapStatus, changes: Partial<KeymapRequest>): KeymapRequest {
const preset = changes.preset ?? current.preset
const bindings = preset === current.preset || (preset === 'custom' && current.preset !== 'off')
? current.bindings
: {}
return {
preset,
bindings: changes.bindings ? { ...bindings, ...changes.bindings } : bindings,
capture_host_shortcuts: changes.capture_host_shortcuts ?? current.capture_host_shortcuts,
}
}
export function keymapPresetUpdate(current: VMKeymapStatus, preset: VMKeymapPreset): KeymapRequest | undefined {
if (preset === current.preset) return undefined
return keymapUpdate(current, { preset })
}
export function createKeymapRequests(api: KeymapAPI, activeVM: () => string, update: (patch: Partial<KeymapState>) => void) {
const requests = createVMSettingRequests<VMKeymapStatus>(activeVM, ({ value, ...patch }) => {
update(value === undefined ? patch : { ...patch, keymap: value })
})
return {
initial(name: string): KeymapState {
return { keymap: null, error: '', busy: requests.isWriting(name) }
},
watch(name: string) {
return requests.watch(name, () => api.GetVMKeymap(name))
},
write(name: string, request: VMKeymapUpdate) {
return requests.write(name, () => api.SetVMKeymap(name, request))
},
}
}
+3
View File
@@ -246,6 +246,9 @@ export const InstallersPage: React.FC<Props> = ({
active,
}
}
if (kind === 'arm-ipsw') {
return { key: `active-${task.id}`, title: task.subject, version, kind: 'ipsw', active }
}
return {
key: `active-${taskInstallerKey(task) || task.id}`,
title: formatOnlineTitle(version),
-20
View File
@@ -1878,26 +1878,6 @@ button.status-issue + .status-metric { margin-left: 6px; }
border-radius: 4px; font-size: 10px; font-weight: 600; flex-shrink: 0;
color: var(--amber); background: color-mix(in srgb, var(--amber) 14%, transparent);
}
.market-version-list { display: flex; flex-direction: column; gap: 8px; }
.market-version-opt {
display: flex; align-items: flex-start; gap: 10px; padding: 10px 12px;
border-radius: var(--r-md); border: 1px solid var(--border);
background: var(--surface-1); cursor: pointer;
}
.market-version-opt.is-selected {
border-color: var(--accent);
background: color-mix(in srgb, var(--accent) 6%, var(--surface-1));
}
.market-version-opt input[type='radio'] { margin-top: 3px; flex-shrink: 0; }
.market-version-main { display: flex; flex-direction: column; gap: 4px; min-width: 0; flex: 1; }
.market-version-head { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; font-size: var(--fs-13); }
.market-version-current {
display: inline-flex; align-items: center; padding: 0 5px; height: 16px;
border-radius: 4px; font-size: 10px; font-weight: 600;
color: var(--accent); background: color-mix(in srgb, var(--accent) 14%, transparent);
}
.market-version-meta { margin-left: auto; font-size: var(--fs-12); color: var(--text-3); font-variant-numeric: tabular-nums; }
.market-version-notes { margin: 0; font-size: var(--fs-12); color: var(--text-2); line-height: 1.45; }
.plugin-title-link { color: inherit; text-decoration: none; }
.plugin-title-link:hover { color: var(--accent); text-decoration: underline; text-underline-offset: 2px; }
.market-card-action { flex-shrink: 0; }
+1 -22
View File
@@ -126,7 +126,7 @@ export type CreateOpts = Model<reims.CreateOpts> & {
type TaskStatus = 'running' | 'done' | 'failed' | 'canceled'
export type InstallerKind = 'offline' | 'online'
export type InstallerKind = 'offline' | 'online' | 'arm-ipsw'
export type InstallerPhase = 'queued' | 'downloading'
/** A tracked long-running job pushed as "reims:task" (internal/app/tasks.go). */
@@ -215,24 +215,3 @@ export interface LogEntry {
source: string
line: string
}
export type VMKeymapPreset = 'off' | 'win_to_cmd' | 'swap_alt_win' | 'custom'
export type VMKeymapHostModifier = 'lwin' | 'rwin' | 'lalt' | 'ralt' | 'lctrl' | 'rctrl' | 'capslock'
export type VMKeymapGuestModifier = 'default' | 'lcmd' | 'rcmd' | 'lopt' | 'ropt' | 'lctrl' | 'rctrl' | 'esc' | 'disabled'
export interface VMKeymapUpdate {
preset: VMKeymapPreset
bindings: Partial<Record<VMKeymapHostModifier, VMKeymapGuestModifier>>
capture_host_shortcuts?: boolean
}
export interface VMKeymapStatus extends VMKeymapUpdate {
capture_host_shortcuts: boolean
needs_guest_tools: boolean
guest_connected: boolean
guest_agent_version?: number
required_agent_version: number
input_service_available: boolean
guest_keymap_active: boolean
hook_active: boolean
running: boolean
}
+1 -3
View File
@@ -17,7 +17,7 @@ import {
import type {
ActiveThemePayload, AppState, CachedInstaller, DataRootChoice, DriverSummary,
LogEntry, MarketBrowseResult, PluginInfo, PluginUIContributions, RemoteRuntime,
ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMInfo, VMNetworkSettings, VMNetworkPlan, VMKeymapStatus, VMKeymapUpdate,
ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMInfo, VMNetworkSettings, VMNetworkPlan,
} from './types'
type AnyFn = (...args: never[]) => unknown
@@ -157,9 +157,7 @@ export const api = {
GetTasks: boundGo.GetTasks as () => Promise<Task[]>,
GetVMAffinity: boundGo.GetVMAffinity as (driverID: string, name: string) => Promise<VMAffinityStatus>,
SetVMAffinity: boundGo.SetVMAffinity as (driverID: string, name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
GetVMKeymap: boundGo.GetVMKeymap as (name: string) => Promise<VMKeymapStatus>,
GetVMInfo: boundGo.GetVMInfo as (driverID: string, name: string) => Promise<VMInfo>,
SetVMKeymap: boundGo.SetVMKeymap as (name: string, req: VMKeymapUpdate) => Promise<VMKeymapStatus>,
ListInstallers: boundGo.ListInstallers as () => Promise<CachedInstaller[] | null>,
ListRemoteRuntimes: boundGo.ListRemoteRuntimes as () => Promise<RemoteRuntime[] | null>,
SuggestDataRoots: boundGo.SuggestDataRoots as () => Promise<DataRootChoice[] | null>,
+2 -4
View File
@@ -72,6 +72,8 @@ export function DownloadAppUpdate():Promise<string>;
export function DownloadInstaller(arg1:string):Promise<string>;
export function DownloadARMImage():Promise<string>;
export function EjectInstaller(arg1:string,arg2:string):Promise<void>;
export function EnablePlugin(arg1:string,arg2:boolean):Promise<void>;
@@ -122,8 +124,6 @@ export function GetVMEndpointCommand(arg1:string,arg2:string,arg3:string):Promis
export function GetVMInfo(arg1:string,arg2:string):Promise<driver.VMInfo>;
export function GetVMKeymap(arg1:string):Promise<app.VMKeymapStatus>;
export function GetVMMacOS(arg1:string):Promise<string>;
export function GetVMNetworkPlan(arg1:string,arg2:string,arg3:string):Promise<app.VMNetworkPlan>;
@@ -278,8 +278,6 @@ export function SetVMDisplay(arg1:string,arg2:string,arg3:string):Promise<app.VM
export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array<string>):Promise<app.DriveShareSettings>;
export function SetVMKeymap(arg1:string,arg2:app.VMKeymapUpdate):Promise<app.VMKeymapStatus>;
export function SetVMNote(arg1:string,arg2:string,arg3:string):Promise<void>;
export function SetVMSSHUser(arg1:string,arg2:string,arg3:string):Promise<void>;
+4 -8
View File
@@ -118,6 +118,10 @@ export function DownloadAppUpdate() {
return window['go']['app']['App']['DownloadAppUpdate']();
}
export function DownloadARMImage() {
return window['go']['app']['App']['DownloadARMImage']();
}
export function DownloadInstaller(arg1) {
return window['go']['app']['App']['DownloadInstaller'](arg1);
}
@@ -222,10 +226,6 @@ export function GetVMInfo(arg1, arg2) {
return window['go']['app']['App']['GetVMInfo'](arg1, arg2);
}
export function GetVMKeymap(arg1) {
return window['go']['app']['App']['GetVMKeymap'](arg1);
}
export function GetVMMacOS(arg1) {
return window['go']['app']['App']['GetVMMacOS'](arg1);
}
@@ -534,10 +534,6 @@ export function SetVMDriveShareSettings(arg1, arg2, arg3) {
return window['go']['app']['App']['SetVMDriveShareSettings'](arg1, arg2, arg3);
}
export function SetVMKeymap(arg1, arg2) {
return window['go']['app']['App']['SetVMKeymap'](arg1, arg2);
}
export function SetVMNote(arg1, arg2, arg3) {
return window['go']['app']['App']['SetVMNote'](arg1, arg2, arg3);
}
+10 -48
View File
@@ -592,54 +592,6 @@ export namespace app {
return a;
}
}
export class VMKeymapStatus {
preset: string;
bindings: Record<string, string>;
capture_host_shortcuts: boolean;
needs_guest_tools: boolean;
guest_connected: boolean;
guest_agent_version?: number;
required_agent_version: number;
guest_keymap_active: boolean;
input_service_available: boolean;
hook_active: boolean;
running: boolean;
static createFrom(source: any = {}) {
return new VMKeymapStatus(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.preset = source["preset"];
this.bindings = source["bindings"];
this.capture_host_shortcuts = source["capture_host_shortcuts"];
this.needs_guest_tools = source["needs_guest_tools"];
this.guest_connected = source["guest_connected"];
this.guest_agent_version = source["guest_agent_version"];
this.required_agent_version = source["required_agent_version"];
this.guest_keymap_active = source["guest_keymap_active"];
this.input_service_available = source["input_service_available"];
this.hook_active = source["hook_active"];
this.running = source["running"];
}
}
export class VMKeymapUpdate {
preset: string;
bindings: Record<string, string>;
capture_host_shortcuts?: boolean;
static createFrom(source: any = {}) {
return new VMKeymapUpdate(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.preset = source["preset"];
this.bindings = source["bindings"];
this.capture_host_shortcuts = source["capture_host_shortcuts"];
}
}
export class VMNetworkPlan {
npcap_installed: boolean;
running_vms: string[];
@@ -1244,6 +1196,8 @@ export namespace host {
scale_pct: number;
refresh_hz?: number;
primary: boolean;
left?: number;
top?: number;
work_width?: number;
work_height?: number;
@@ -1260,6 +1214,8 @@ export namespace host {
this.scale_pct = source["scale_pct"];
this.refresh_hz = source["refresh_hz"];
this.primary = source["primary"];
this.left = source["left"];
this.top = source["top"];
this.work_width = source["work_width"];
this.work_height = source["work_height"];
}
@@ -3023,6 +2979,7 @@ export namespace reims {
graphics?: string;
gpu?: string;
resolution?: string;
auto_resolution?: boolean;
displays?: number;
borderless?: boolean;
capture?: boolean;
@@ -3057,6 +3014,7 @@ export namespace reims {
this.graphics = source["graphics"];
this.gpu = source["gpu"];
this.resolution = source["resolution"];
this.auto_resolution = source["auto_resolution"];
this.displays = source["displays"];
this.borderless = source["borderless"];
this.capture = source["capture"];
@@ -3079,6 +3037,7 @@ export namespace reims {
disk_controller?: string;
disk_cache?: string;
resolution?: string;
auto_resolution?: boolean;
borderless?: boolean;
capture?: boolean;
gpu?: string;
@@ -3108,6 +3067,7 @@ export namespace reims {
this.disk_controller = source["disk_controller"];
this.disk_cache = source["disk_cache"];
this.resolution = source["resolution"];
this.auto_resolution = source["auto_resolution"];
this.borderless = source["borderless"];
this.capture = source["capture"];
this.gpu = source["gpu"];
@@ -3186,6 +3146,7 @@ export namespace reims {
display: string;
displays: number;
resolution: string;
auto_resolution: boolean;
gpu: string;
has_opencore: boolean;
has_installer: boolean;
@@ -3240,6 +3201,7 @@ export namespace reims {
this.display = source["display"];
this.displays = source["displays"];
this.resolution = source["resolution"];
this.auto_resolution = source["auto_resolution"];
this.gpu = source["gpu"];
this.has_opencore = source["has_opencore"];
this.has_installer = source["has_installer"];
+45 -62
View File
@@ -21,6 +21,7 @@ import (
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/packetbridge"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/market"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/tray"
"github.com/Nwflower/reims-go/internal/version"
@@ -121,58 +122,41 @@ type App struct {
trayMgr *tray.Manager
allowQuit bool
launchPrevDataRoot string
quitMode string
vmStarts sync.WaitGroup
lastVMs []driver.VMListItem
lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale
lastVMListErr error
pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick
diskPaths map[string]cachedDiskPath
procSamples map[string]host.ProcessSample
recentLogs []string
needsSetup bool
root dataroot.Status // how the current data folder opened (dataroot_flow.go)
launch cli.WindowArgs // flags this window was started with (window_launch.go)
trayIcon []byte // embedded PNG passed in from package main
logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go)
pluginMgr *plugin.Manager
pluginFiles map[string]pluginFileGrant
pluginMarket *plugin.MarketClient
controlServer *control.Server
driverRouter *driver.Router
vmStateTable *driver.StateTable
lifecycleSvc *vmlifecycle.Service
runtimeKinds *rt.KindRegistry
uiHealth uiHealthState
themeMode string
vmClosePrompts sync.Map
displayHost vmDisplayHost
quitMode string
vmStarts sync.WaitGroup
lastVMs []driver.VMListItem
lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale
lastVMListErr error
pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick
diskPaths map[string]cachedDiskPath
procSamples map[string]host.ProcessSample
recentLogs []string
needsSetup bool
root dataroot.Status // how the current data folder opened (dataroot_flow.go)
launch cli.WindowArgs // flags this window was started with (window_launch.go)
trayIcon []byte // embedded PNG passed in from package main
logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go)
pluginMgr *plugin.Manager
pluginMarket *market.MarketClient
controlServer *control.Server
driverRouter *driver.Router
vmStateTable *driver.StateTable
lifecycleSvc *vmlifecycle.Service
runtimeKinds *rt.KindRegistry
uiHealth uiHealthState
themeMode string
vmClosePrompts sync.Map
displayHost vmDisplayHost
displayPlacements sync.Map
keymapMu sync.Mutex
keymapPIDs map[string]int
fallbackInputSvc *host.InputService
inputShuttingDown bool
// computerUseOwnedVMs caches ownership markers for MCP-created temporary VMs.
computerUseOwnedVMs map[string]map[string]bool
computerUseCloneMu sync.Mutex
// computerUseHeld records the keys and pointer buttons each plugin left
// held in a guest, so the host can release them when the plugin goes away.
computerUseHeld map[string]map[string]*heldInputs
computerUseHeldMu sync.Mutex
fullscreenHotkey host.FullscreenHotkeyService
fullscreenSyncMu sync.Mutex
fullscreenTargets fullscreenHotkeyTargetCache
// Plugin elevation requests (elevate_flow.go).
elevatePromptMu sync.Mutex
elevateMu sync.Mutex
elevatePending map[string]chan bool
elevateSeq uint64
elevateEmit func(ElevationPrompt)
elevateDismiss func(string)
elevateRunner elevationRunner
// Host-side plugin API service (computer-use, secrets, downloads, elevation, file grants).
hostAPI HostAPIService
}
// Lifecycle exposes Wails lifecycle callbacks without exporting them as
@@ -207,17 +191,18 @@ func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) {
needsSetup: needsSetup,
launch: launch,
launchPrevDataRoot: launchPrevDataRoot,
trayIcon: trayIcon,
transitions: make(map[string]string),
pendingChanges: make(map[string][]PendingChange),
rebootWatchers: make(map[string]rebootWatcherEntry),
pollWake: make(chan struct{}, 1),
diskPaths: make(map[string]cachedDiskPath),
procSamples: make(map[string]host.ProcessSample),
pluginFiles: make(map[string]pluginFileGrant),
uiHealth: uiHealthState{windowHidden: launch.Background},
displayHost: vmDisplayHost{displays: host.ConnectedDisplays, move: host.MoveProcessWindowToDisplay},
trayIcon: trayIcon,
transitions: make(map[string]string),
pendingChanges: make(map[string][]PendingChange),
rebootWatchers: make(map[string]rebootWatcherEntry),
pollWake: make(chan struct{}, 1),
diskPaths: make(map[string]cachedDiskPath),
procSamples: make(map[string]host.ProcessSample),
uiHealth: uiHealthState{windowHidden: launch.Background},
displayHost: vmDisplayHost{displays: host.ConnectedDisplays, move: host.MoveProcessWindowToDisplay},
}
a.hostAPI.app = a
a.hostAPI.pluginFiles = make(map[string]pluginFileGrant)
return a, Lifecycle{
OnStartup: a.startup,
OnBeforeClose: a.beforeClose,
@@ -313,12 +298,8 @@ func (a *App) shutdown(ctx context.Context) {
a.stopPluginControlServer()
a.mu.Lock()
a.inputShuttingDown = true
fallback := a.fallbackInputSvc
a.mu.Unlock()
a.fullscreenHotkey.Close()
if fallback != nil {
fallback.Close()
}
a.shutdownPlugins()
a.mu.Lock()
for name, entry := range a.rebootWatchers {
@@ -549,10 +530,8 @@ func (a *App) startTray() {
}
items = append(items, tray.VMItem{DriverID: vm.DriverID, Name: vm.Name, Label: label, State: state})
}
effLoc := i18n.EffectiveLocale(loc)
return tray.Snapshot{
Locale: effLoc,
LocaleZh: effLoc == i18n.ZhCN,
Locale: i18n.EffectiveLocale(loc),
CanSuspend: canSuspend,
VMs: items,
}
@@ -626,8 +605,8 @@ func (a *App) resetDataRootCaches() {
a.lastVMListErr = nil
a.diskPaths = make(map[string]cachedDiskPath)
a.procSamples = make(map[string]host.ProcessSample)
a.pluginFiles = make(map[string]pluginFileGrant)
a.mu.Unlock()
a.hostAPISvc().ResetPluginFiles()
cancelPluginTasks("")
}
@@ -843,6 +822,10 @@ func (a *App) InstallRuntimeArchive(archivePath string) (*rt.Installed, error) {
}
return nil, err
}
if inst.Kind == rt.StambhaKind {
a.emitLog("runtime", fmt.Sprintf("Runtime %s installed -> %s", inst.Commit, inst.Dir))
return inst, nil
}
if err := a.activateInstalledRuntime(&cfg, inst.Commit); err != nil {
inst.Active = false
a.emitLog("runtime", err.Error())
+3 -8
View File
@@ -18,15 +18,10 @@ func TestPolledVMsReusesFreshPoll(t *testing.T) {
a.lastVMs = []reims.VMListItem{{Name: "m0", Dir: `D:\vms\m0`, PID: &pid, State: "running"}}
a.lastVMsAt = time.Now()
vm, ok := a.polledVM("m0")
if !ok || vm.State != "running" || vm.Dir != `D:\vms\m0` || *vm.PID != 42 {
t.Fatalf("polledVM = %+v, %v", vm, ok)
vms, err := a.polledVMs(context.Background())
if err != nil || len(vms) != 1 || vms[0].Name != "m0" {
t.Fatalf("polledVMs = %+v, %v", vms, err)
}
if _, ok := a.polledVM("missing"); ok {
t.Fatal("unknown VM should not be found")
}
vms, _ := a.polledVMs(context.Background())
vms[0].State = "stopped"
if a.lastVMs[0].State != "running" {
t.Fatal("polledVMs must return a copy, not the cached slice")
+63 -2
View File
@@ -6,9 +6,13 @@ package app
// running; Guest Tools reconnects once the new window is up.
import (
"archive/zip"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
@@ -121,8 +125,10 @@ func (a *App) DownloadAppUpdate() (string, error) {
return id, nil
}
// downloadAppUpdate fetches info's executable into dir and checks it against
// GitHub's assets[].digest SHA-256. It returns the file and its hash.
// downloadAppUpdate fetches info's release asset (.zip or .exe) into dir,
// checks it against GitHub's assets[].digest SHA-256, extracts the executable
// when a .zip archive was downloaded, and returns the executable path and its
// SHA-256 hash.
func downloadAppUpdate(ctx context.Context, info version.UpdateInfo, dir string, onProgress fetch.Progress) (string, string, error) {
want := strings.ToLower(strings.TrimSpace(info.AssetSHA256))
if len(want) != 64 {
@@ -136,9 +142,64 @@ func downloadAppUpdate(ctx context.Context, info version.UpdateInfo, dir string,
if err != nil {
return "", "", err
}
if strings.HasSuffix(strings.ToLower(path), ".zip") {
exePath, exeSum, err := extractAppUpdateZip(path, dir)
if err != nil {
return "", "", err
}
return exePath, exeSum, nil
}
return path, want, nil
}
// extractAppUpdateZip extracts the single Windows executable from a verified
// release .zip into dir and returns its path and SHA-256 digest.
func extractAppUpdateZip(zipPath, dir string) (string, string, error) {
zr, err := zip.OpenReader(zipPath)
if err != nil {
return "", "", fmt.Errorf("open update archive: %w", err)
}
defer zr.Close()
const maxUpdateExeBytes = 256 << 20 // 256 MiB safety cap against zip bombs
for _, f := range zr.File {
if f.FileInfo().IsDir() {
continue
}
base := filepath.Base(f.Name)
if base == "." || base == ".." || strings.ContainsAny(f.Name, `/\`) {
continue
}
lower := strings.ToLower(base)
if !strings.HasSuffix(lower, ".exe") || strings.Contains(lower, "-cli-") {
continue
}
rc, err := f.Open()
if err != nil {
return "", "", fmt.Errorf("read %s from update archive: %w", base, err)
}
dest := filepath.Join(dir, base)
out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
if err != nil {
_ = rc.Close()
return "", "", fmt.Errorf("create extracted update %s: %w", base, err)
}
h := sha256.New()
n, copyErr := io.Copy(io.MultiWriter(out, h), io.LimitReader(rc, maxUpdateExeBytes+1))
closeErr := errors.Join(rc.Close(), out.Close())
if copyErr != nil || closeErr != nil {
_ = os.Remove(dest)
return "", "", fmt.Errorf("extract %s from update archive: %w", base, errors.Join(copyErr, closeErr))
}
if n > maxUpdateExeBytes {
_ = os.Remove(dest)
return "", "", fmt.Errorf("extracted update %s exceeds %d byte limit", base, maxUpdateExeBytes)
}
return dest, hex.EncodeToString(h.Sum(nil)), nil
}
return "", "", errors.New("update archive does not contain a Windows executable")
}
// InstallAppUpdate swaps the downloaded update in for the running executable,
// starts it, and quits this window. The new window waits for this process to
// exit before it opens. Running VMs are not touched.
+57
View File
@@ -1,6 +1,8 @@
package app
import (
"archive/zip"
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
@@ -56,6 +58,61 @@ func TestDownloadAppUpdateVerifiesAgainstAssetDigest(t *testing.T) {
}
}
func TestDownloadAppUpdateExtractsZipAndVerifiesDigest(t *testing.T) {
exePayload := []byte("MZ-reims-go-zip-update-binary")
exeHash := sha256.Sum256(exePayload)
wantExeSum := hex.EncodeToString(exeHash[:])
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
w, err := zw.Create("reims-go-v9.9.9-windows-amd64.exe")
if err != nil {
t.Fatal(err)
}
if _, err := w.Write(exePayload); err != nil {
t.Fatal(err)
}
if err := zw.Close(); err != nil {
t.Fatal(err)
}
zipBytes := buf.Bytes()
zipHash := sha256.Sum256(zipBytes)
wantZipSum := hex.EncodeToString(zipHash[:])
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/app.zip" {
_, _ = w.Write(zipBytes)
return
}
http.NotFound(w, r)
}))
defer srv.Close()
dir := t.TempDir()
info := version.UpdateInfo{
Latest: "v9.9.9",
HasUpdate: true,
AssetName: "reims-go-v9.9.9-windows-amd64.zip",
AssetSize: int64(len(zipBytes)),
DownloadURL: srv.URL + "/app.zip",
AssetSHA256: wantZipSum,
}
gotPath, gotSum, err := downloadAppUpdate(context.Background(), info, dir, nil)
if err != nil {
t.Fatalf("downloadAppUpdate(zip): %v", err)
}
if filepath.Base(gotPath) != "reims-go-v9.9.9-windows-amd64.exe" {
t.Fatalf("extracted path = %s, want reims-go-v9.9.9-windows-amd64.exe", gotPath)
}
if gotSum != wantExeSum {
t.Fatalf("extracted exe sum = %s, want %s", gotSum, wantExeSum)
}
gotBody, err := os.ReadFile(gotPath)
if err != nil || !bytes.Equal(gotBody, exePayload) {
t.Fatalf("extracted exe content mismatch: %q, err=%v", gotBody, err)
}
}
func TestInstallAppUpdateGuards(t *testing.T) {
cfg := config.Default()
cfg.Locale = i18n.EnUS
+80
View File
@@ -0,0 +1,80 @@
package app
import (
"context"
"errors"
"net/http"
"os"
"path/filepath"
"time"
"github.com/Nwflower/reims-go/internal/fetch"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/macos/installer"
"github.com/Nwflower/reims-go/internal/netproxy"
)
const (
armImageBuild = "26B131"
armImageName = "UniversalMac_27.2.1_26B131_Restore.ipsw"
armImageURL = "https://updates.cdn-apple.com/2026FallFCS/c202a724-db7e-4d56-917b-110aa0226507/" + armImageName
armImageSHA = "233e85a09887579d47d0b195e7db72be7f204261059c6946f719acf6b300814f"
armImageSize = int64(25595954706)
)
// DownloadARMImage fetches the pinned ARM restore image from Apple into the user data folder.
func (a *App) DownloadARMImage() (string, error) {
cfg := a.runtimeConfig()
if err := cfg.EnsureDirs(); err != nil {
return "", err
}
final := filepath.Join(cfg.ImagesDir(), "arm64", armImageName)
if err := os.MkdirAll(filepath.Dir(final), 0o755); err != nil {
return "", err
}
a.ensureTaskEmitter()
var ctx context.Context
var cancel context.CancelFunc
run, id, owned := installerDownloads.reserveOrFind("arm-ipsw", armImageBuild, "installer-download", func(initialPhase string) string {
ctx, cancel = context.WithCancel(a.baseCtx())
return tasks.startWithInstaller("installer-download", "macOS 27.2.1 · ARM64", "", "arm-ipsw", armImageBuild, initialPhase, cancel)
})
if !owned {
return id, nil
}
go func() {
defer cancel()
client := netproxy.NewClient()
client.Timeout = 0
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
if len(via) >= 10 || req.URL.Scheme != "https" || req.URL.Hostname() != "updates.cdn-apple.com" {
return errors.New("ARM restore image download redirected outside Apple's update server")
}
return nil
}
path, err := fetch.ResumeDirect(ctx, client, armImageURL, final, armImageSize, armImageSHA, func(done, total int64) {
update := host.Update{Kind: host.KindProgress, Done: done, Total: total, Percent: percent(done, total)}
tasks.update(id, update)
run.publish(update)
}, fetch.ResumeOptions{MaxBytes: armImageSize, StallTimeout: 45 * time.Second})
if err == nil {
if info, statErr := os.Stat(path); statErr != nil {
err = statErr
} else if info.Size() != armImageSize {
err = errors.New("ARM restore image size does not match the pinned build")
}
}
if err != nil && ctx.Err() != nil {
err = ctx.Err()
}
var result *installer.Result
if err == nil {
result = &installer.Result{Image: path}
} else {
path = ""
}
installerDownloads.complete(run, result, err)
tasks.finish(id, path, err)
}()
return id, nil
}
+30 -30
View File
@@ -44,8 +44,8 @@ type heldInputs struct {
// noteHeldKey records or forgets one key transition. code must already be a
// QKeyCode.
func (a *App) noteHeldKey(pluginID, vmKey, code string, down bool) {
a.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
a.hostAPI.heldMu.Lock()
defer a.hostAPI.heldMu.Unlock()
held := a.heldLocked(pluginID, vmKey)
if down {
held.keys[code] = true
@@ -57,8 +57,8 @@ func (a *App) noteHeldKey(pluginID, vmKey, code string, down bool) {
// noteHeldButton records or forgets one pointer button transition.
func (a *App) noteHeldButton(pluginID, vmKey, button string, down bool) {
a.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
a.hostAPI.heldMu.Lock()
defer a.hostAPI.heldMu.Unlock()
held := a.heldLocked(pluginID, vmKey)
if down {
held.buttons[button] = true
@@ -71,13 +71,13 @@ func (a *App) noteHeldButton(pluginID, vmKey, button string, down bool) {
// heldLocked returns the record for one plugin and VM, creating it when
// needed. The caller holds computerUseHeldMu.
func (a *App) heldLocked(pluginID, vmKey string) *heldInputs {
if a.computerUseHeld == nil {
a.computerUseHeld = map[string]map[string]*heldInputs{}
if a.hostAPI.computerUseHeld == nil {
a.hostAPI.computerUseHeld = map[string]map[string]*heldInputs{}
}
byVM := a.computerUseHeld[pluginID]
byVM := a.hostAPI.computerUseHeld[pluginID]
if byVM == nil {
byVM = map[string]*heldInputs{}
a.computerUseHeld[pluginID] = byVM
a.hostAPI.computerUseHeld[pluginID] = byVM
}
held := byVM[vmKey]
if held == nil {
@@ -113,7 +113,7 @@ func (a *App) armHeldTimerLocked(pluginID, vmKey string, held *heldInputs, d tim
// pruneHeldLocked drops a record that holds nothing, so an idle plugin leaves
// no state behind. The caller holds computerUseHeldMu.
func (a *App) pruneHeldLocked(pluginID, vmKey string) {
byVM := a.computerUseHeld[pluginID]
byVM := a.hostAPI.computerUseHeld[pluginID]
if byVM == nil {
return
}
@@ -125,16 +125,16 @@ func (a *App) pruneHeldLocked(pluginID, vmKey string) {
delete(byVM, vmKey)
}
if len(byVM) == 0 {
delete(a.computerUseHeld, pluginID)
delete(a.hostAPI.computerUseHeld, pluginID)
}
}
// heldSnapshot returns what one plugin holds in one VM, sorted, with the
// generation it was read at.
func (a *App) heldSnapshot(pluginID, vmKey string) (keys, buttons []string, generation uint64) {
a.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
byVM := a.computerUseHeld[pluginID]
a.hostAPI.heldMu.Lock()
defer a.hostAPI.heldMu.Unlock()
byVM := a.hostAPI.computerUseHeld[pluginID]
if byVM == nil {
return nil, nil, 0
}
@@ -156,9 +156,9 @@ func (a *App) heldSnapshot(pluginID, vmKey string) (keys, buttons []string, gene
// heldGeneration returns the record's current generation, or 0 when there is
// no record.
func (a *App) heldGeneration(pluginID, vmKey string) uint64 {
a.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
if held := a.computerUseHeld[pluginID][vmKey]; held != nil {
a.hostAPI.heldMu.Lock()
defer a.hostAPI.heldMu.Unlock()
if held := a.hostAPI.computerUseHeld[pluginID][vmKey]; held != nil {
return held.generation
}
return 0
@@ -166,10 +166,10 @@ func (a *App) heldGeneration(pluginID, vmKey string) uint64 {
// heldVMs lists the VMs one plugin currently holds input in.
func (a *App) heldVMs(pluginID string) map[string]bool {
a.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
a.hostAPI.heldMu.Lock()
defer a.hostAPI.heldMu.Unlock()
out := map[string]bool{}
for vmKey := range a.computerUseHeld[pluginID] {
for vmKey := range a.hostAPI.computerUseHeld[pluginID] {
out[vmKey] = true
}
return out
@@ -179,9 +179,9 @@ func (a *App) heldVMs(pluginID string) map[string]bool {
// when the caller itself named what it lifted, so there is no snapshot to
// compare with.
func (a *App) dropHeld(pluginID, vmKey string, keys, buttons []string) {
a.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
held := a.computerUseHeld[pluginID][vmKey]
a.hostAPI.heldMu.Lock()
defer a.hostAPI.heldMu.Unlock()
held := a.hostAPI.computerUseHeld[pluginID][vmKey]
if held == nil {
return
}
@@ -199,9 +199,9 @@ func (a *App) dropHeld(pluginID, vmKey string, keys, buttons []string) {
// meantime may hold a press this release did not lift, so it keeps everything
// and its timer releases it later.
func (a *App) dropHeldIfGeneration(pluginID, vmKey string, keys, buttons []string, generation uint64) bool {
a.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
held := a.computerUseHeld[pluginID][vmKey]
a.hostAPI.heldMu.Lock()
defer a.hostAPI.heldMu.Unlock()
held := a.hostAPI.computerUseHeld[pluginID][vmKey]
if held == nil {
return false
}
@@ -221,9 +221,9 @@ func (a *App) dropHeldIfGeneration(pluginID, vmKey string, keys, buttons []strin
// rearmHeld schedules another fallback release for a record whose release
// failed while the VM is still running.
func (a *App) rearmHeld(pluginID, vmKey string) {
a.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
held := a.computerUseHeld[pluginID][vmKey]
a.hostAPI.heldMu.Lock()
defer a.hostAPI.heldMu.Unlock()
held := a.hostAPI.computerUseHeld[pluginID][vmKey]
if held == nil || len(held.keys)+len(held.buttons) == 0 {
return
}
@@ -235,8 +235,8 @@ func (a *App) rearmHeld(pluginID, vmKey string) {
// can still be held, and a release sent later could lift a key the user is
// pressing after the VM starts again.
func (a *App) forgetHeld(pluginID, vmKey string) {
a.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
a.hostAPI.heldMu.Lock()
defer a.hostAPI.heldMu.Unlock()
a.pruneHeldLocked(pluginID, vmKey)
}
+41 -37
View File
@@ -48,23 +48,23 @@ func (a *App) computerUseHostHandlers(mgr *plugin.Manager, pluginID string) map[
return nil
}
return map[string]plugin.RPCRequestHandler{
"host/vm.list": a.hostVMMethod(mgr, pluginID, "host/vm.list", a.handleComputerUseVMList),
"host/vm.get": a.hostVMMethod(mgr, pluginID, "host/vm.get", a.handleComputerUseVMGet),
"host/vm.start": a.hostVMMethod(mgr, pluginID, "host/vm.start", a.handleComputerUseVMStart),
"host/vm.shutdown": a.hostVMMethod(mgr, pluginID, "host/vm.shutdown", a.handleComputerUseVMShutdown),
"host/vm.suspend": a.hostVMMethod(mgr, pluginID, "host/vm.suspend", a.handleComputerUseVMStateChange("host/vm.suspend", a.SuspendVM)),
"host/vm.resume": a.hostVMMethod(mgr, pluginID, "host/vm.resume", a.handleComputerUseVMStateChange("host/vm.resume", a.ResumeVM)),
"host/vm.clone": a.hostVMMethod(mgr, pluginID, "host/vm.clone", a.handleComputerUseVMClone),
"host/vm.delete": a.hostVMMethod(mgr, pluginID, "host/vm.delete", a.handleComputerUseVMDelete),
"host/vm.snapshot.list": a.hostVMMethod(mgr, pluginID, "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList),
"host/vm.snapshot.create": a.hostVMMethod(mgr, pluginID, "host/vm.snapshot.create", a.handleComputerUseVMSnapshotCreate),
"host/vm.snapshot.restore": a.hostVMMethod(mgr, pluginID, "host/vm.snapshot.restore", a.handleComputerUseVMSnapshotRestore),
"host/console.screenshot": a.hostVMMethod(mgr, pluginID, "host/console.screenshot", a.handleComputerUseScreenshot),
"host/console.pointer": a.hostVMMethod(mgr, pluginID, "host/console.pointer", a.handleComputerUsePointer),
"host/console.key": a.hostVMMethod(mgr, pluginID, "host/console.key", a.handleComputerUseKey),
"host/console.type": a.hostVMMethod(mgr, pluginID, "host/console.type", a.handleComputerUseType),
"host/console.typeSecret": a.hostVMMethod(mgr, pluginID, "host/console.typeSecret", a.handleComputerUseTypeSecret),
"host/console.release": a.hostVMMethod(mgr, pluginID, "host/console.release", a.handleComputerUseRelease),
"host/vm.list": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.list", a.handleComputerUseVMList),
"host/vm.get": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.get", a.handleComputerUseVMGet),
"host/vm.start": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.start", a.handleComputerUseVMStart),
"host/vm.shutdown": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.shutdown", a.handleComputerUseVMShutdown),
"host/vm.suspend": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.suspend", a.handleComputerUseVMStateChange("host/vm.suspend", a.SuspendVM)),
"host/vm.resume": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.resume", a.handleComputerUseVMStateChange("host/vm.resume", a.ResumeVM)),
"host/vm.clone": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.clone", a.handleComputerUseVMClone),
"host/vm.delete": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.delete", a.handleComputerUseVMDelete),
"host/vm.snapshot.list": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList),
"host/vm.snapshot.create": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.snapshot.create", a.handleComputerUseVMSnapshotCreate),
"host/vm.snapshot.restore": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.snapshot.restore", a.handleComputerUseVMSnapshotRestore),
"host/console.screenshot": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.screenshot", a.handleComputerUseScreenshot),
"host/console.pointer": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.pointer", a.handleComputerUsePointer),
"host/console.key": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.key", a.handleComputerUseKey),
"host/console.type": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.type", a.handleComputerUseType),
"host/console.typeSecret": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.typeSecret", a.handleComputerUseTypeSecret),
"host/console.release": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.release", a.handleComputerUseRelease),
}
}
@@ -243,8 +243,8 @@ func (a *App) handleComputerUseVMClone(ctx context.Context, raw json.RawMessage,
if err != nil {
return nil, err
}
a.computerUseCloneMu.Lock()
defer a.computerUseCloneMu.Unlock()
a.hostAPI.computerUseCloneMu.Lock()
defer a.hostAPI.computerUseCloneMu.Unlock()
if existing, listErr := a.listVMsInternal(ctx); listErr != nil {
return nil, listErr
} else if slices.ContainsFunc(existing, func(item driver.VMListItem) bool {
@@ -446,24 +446,26 @@ func (a *App) computerUseVMAccessEnabled(mgr *plugin.Manager, pluginID, vmKey st
}
func (a *App) computerUseOwned(pluginID, vmKey string) bool {
a.mu.Lock()
defer a.mu.Unlock()
return a.computerUseOwnedVMs != nil && a.computerUseOwnedVMs[pluginID] != nil && a.computerUseOwnedVMs[pluginID][vmKey]
h := a.hostAPISvc()
h.ownedMu.Lock()
defer h.ownedMu.Unlock()
return h.computerUseOwnedVMs != nil && h.computerUseOwnedVMs[pluginID] != nil && h.computerUseOwnedVMs[pluginID][vmKey]
}
func (a *App) markComputerUseOwnedVM(pluginID, vmKey string, owned bool) {
a.mu.Lock()
defer a.mu.Unlock()
if a.computerUseOwnedVMs == nil {
a.computerUseOwnedVMs = make(map[string]map[string]bool)
h := a.hostAPISvc()
h.ownedMu.Lock()
defer h.ownedMu.Unlock()
if h.computerUseOwnedVMs == nil {
h.computerUseOwnedVMs = make(map[string]map[string]bool)
}
if a.computerUseOwnedVMs[pluginID] == nil {
a.computerUseOwnedVMs[pluginID] = make(map[string]bool)
if h.computerUseOwnedVMs[pluginID] == nil {
h.computerUseOwnedVMs[pluginID] = make(map[string]bool)
}
if owned {
a.computerUseOwnedVMs[pluginID][vmKey] = true
h.computerUseOwnedVMs[pluginID][vmKey] = true
} else {
delete(a.computerUseOwnedVMs[pluginID], vmKey)
delete(h.computerUseOwnedVMs[pluginID], vmKey)
}
}
@@ -472,12 +474,13 @@ func (a *App) forgetComputerUseOwnedVM(vmKey string) {
if vmKey == "" {
return
}
a.mu.Lock()
defer a.mu.Unlock()
for pluginID, owned := range a.computerUseOwnedVMs {
h := a.hostAPISvc()
h.ownedMu.Lock()
defer h.ownedMu.Unlock()
for pluginID, owned := range h.computerUseOwnedVMs {
delete(owned, vmKey)
if len(owned) == 0 {
delete(a.computerUseOwnedVMs, pluginID)
delete(h.computerUseOwnedVMs, pluginID)
}
}
}
@@ -611,14 +614,15 @@ func (a *App) syncComputerUseOwnership(vms []driver.VMListItem) {
continue
}
key := vm.Ref().Key()
a.mu.Lock()
h := a.hostAPISvc()
h.ownedMu.Lock()
var pluginIDs []string
for pluginID, owned := range a.computerUseOwnedVMs {
for pluginID, owned := range h.computerUseOwnedVMs {
if owned[key] {
pluginIDs = append(pluginIDs, pluginID)
}
}
a.mu.Unlock()
h.ownedMu.Unlock()
for _, pluginID := range pluginIDs {
// The source VM is no longer known on this repair path (the marker
// was lost), so write an empty source: no fallback, same as before.
+13 -1
View File
@@ -10,6 +10,7 @@ import (
"time"
"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/installer"
"github.com/Nwflower/reims-go/internal/macos/opencore"
@@ -17,9 +18,10 @@ import (
"github.com/Nwflower/reims-go/internal/networkmsg"
"github.com/Nwflower/reims-go/internal/packetbridge"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/vmstart"
)
func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
func (a *App) createVMFlow(opts reims.CreateOpts, connectedDisplays func() []host.DisplayInfo) (err error) {
defer func() {
var coded *i18n.CodedError
if errors.As(err, &coded) && strings.HasPrefix(coded.Code, "E_NETWORK_") {
@@ -54,6 +56,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
}
}
c := reims.NewClient(&cfgCopy, *active)
autoResolution := opts.AutoResolution != nil && *opts.AutoResolution && vmstart.SupportsAutoResolution(opts.Graphics)
// Always defer starting to StartVM so commit-memory checks, Win10 cold-reboot
// QMP wiring, and Win11 WHPX nested-virt fallback apply uniformly.
@@ -171,6 +174,9 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
opts.DiskMode = "copy"
}
if autoResolution {
opts.Resolution, _ = host.RecommendAutoResolution(host.PrimaryDisplayOf(connectedDisplays()), opts.Borderless != nil && *opts.Borderless, c.DisplayFixedMode)
}
err = c.Create(ctx, opts, w, w)
if err != nil {
if ctx.Err() != nil {
@@ -195,6 +201,12 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
finishTask(err)
return fmt.Errorf("record VM driver ownership: %w", err)
}
if autoResolution {
if _, err := vmstart.SaveVMAutoResolution(createdDir, true); err != nil {
finishTask(err)
return err
}
}
if postSet, ok := reims.PostCreateSetOptsWithCapture(opts, c.AllowsSetCapture()); ok {
var parts []string
if postSet.DiskController != "" {
+4 -1
View File
@@ -3,6 +3,7 @@ package app
import (
"errors"
"fmt"
"os"
"strings"
"github.com/Nwflower/reims-go/internal/config"
@@ -27,7 +28,9 @@ func (a *App) openDataRoot() dataroot.Status {
a.syncClipboardStagingLocked()
a.mu.Unlock()
a.logDataRoot(st)
if st.Writable() && explicitLaunch {
// Older clients could save the new data folder while leaving its registry stale.
// A registry explicitly shared outside the data folder still requires an explicit launch.
if st.Writable() && (explicitLaunch || strings.TrimSpace(os.Getenv("REIMS_CTL_CONFIG_DIR")) == "") {
a.relocateRegisteredVMs(dir, prevRoot)
}
return st
+57 -19
View File
@@ -9,6 +9,7 @@ import (
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/cli"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/datamigrate"
"github.com/Nwflower/reims-go/internal/dataroot"
@@ -181,22 +182,7 @@ func TestSetDataRoot_RelocatesMovedVMRegistry(t *testing.T) {
if err := config.Save(filepath.Join(newRoot, "reims-go.json"), oldCfg); err != nil {
t.Fatal(err)
}
newVMDir := filepath.Join((&config.Config{DataRoot: newRoot}).XDGDataDir(), "reims-ctl", "vms", "macos-tahoe")
if err := os.MkdirAll(newVMDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(newVMDir, "vm.toml"), []byte("disk = \"disk.qcow2\"\n"), 0o644); err != nil {
t.Fatal(err)
}
oldVMDir := filepath.Join((&config.Config{DataRoot: oldRoot}).XDGDataDir(), "reims-ctl", "vms", "macos-tahoe")
regDir := filepath.Join((&config.Config{DataRoot: newRoot}).XDGConfigDir(), "reims-ctl")
if err := os.MkdirAll(regDir, 0o755); err != nil {
t.Fatal(err)
}
vmsToml := "[[vm]]\nname = 'macos-tahoe'\ndir = '" + strings.ReplaceAll(oldVMDir, "'", "''") + "'\n"
if err := os.WriteFile(filepath.Join(regDir, "vms.toml"), []byte(vmsToml), 0o644); err != nil {
t.Fatal(err)
}
_, newVMDir := writeMovedVMRegistry(t, oldRoot, newRoot)
a := &App{
cfg: &config.Config{DataRoot: oldRoot, Locale: "zh-CN"},
@@ -206,15 +192,67 @@ func TestSetDataRoot_RelocatesMovedVMRegistry(t *testing.T) {
if err := a.setDataRoot(newRoot, noopASLR); err != nil {
t.Fatalf("setDataRoot: %v", err)
}
assertRegisteredVMDir(t, newRoot, newVMDir)
}
vms, err := reims.ListRegisteredVMs(newRoot)
func TestOpenDataRoot_RepairsPreviouslySelectedVMRegistry(t *testing.T) {
t.Setenv("REIMS_CTL_CONFIG_DIR", "")
t.Setenv("REIMS_GO_DATA_ROOT", "")
base := t.TempDir()
t.Setenv("REIMS_GO_LOCATION_FILE", filepath.Join(base, "location.json"))
oldRoot := filepath.Join(base, "old-drive")
newRoot := filepath.Join(base, "new-drive")
oldVMDir, newVMDir := writeMovedVMRegistry(t, oldRoot, newRoot)
// An older release saved the new data root but left the old VM registration.
cfg := &config.Config{DataRoot: newRoot}
if err := config.Save("", cfg); err != nil {
t.Fatal(err)
}
if err := config.SaveLocation(newRoot); err != nil {
t.Fatal(err)
}
assertRegisteredVMDir(t, newRoot, oldVMDir)
a, _ := New(nil, cli.WindowArgs{})
if st := a.openDataRoot(); !st.Writable() {
t.Fatalf("openDataRoot: %+v", st)
}
assertRegisteredVMDir(t, newRoot, newVMDir)
}
func writeMovedVMRegistry(t *testing.T, oldRoot, newRoot string) (oldVMDir, newVMDir string) {
t.Helper()
newVMDir = filepath.Join(datamigrate.VMRoot(newRoot), "macos-tahoe")
if err := os.MkdirAll(newVMDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(newVMDir, "vm.toml"), []byte("name = \"macos-tahoe\"\ndisk = \"disk.qcow2\"\n"), 0o644); err != nil {
t.Fatal(err)
}
oldVMDir = filepath.Join(datamigrate.VMRoot(oldRoot), "macos-tahoe")
regDir := filepath.Join((&config.Config{DataRoot: newRoot}).XDGConfigDir(), "reims-ctl")
if err := os.MkdirAll(regDir, 0o755); err != nil {
t.Fatal(err)
}
vmsToml := "[[vm]]\nname = 'macos-tahoe'\ndir = '" + strings.ReplaceAll(oldVMDir, "'", "''") + "'\n"
if err := os.WriteFile(filepath.Join(regDir, "vms.toml"), []byte(vmsToml), 0o644); err != nil {
t.Fatal(err)
}
return oldVMDir, newVMDir
}
func assertRegisteredVMDir(t *testing.T, root, want string) {
t.Helper()
vms, err := reims.ListRegisteredVMs(root)
if err != nil {
t.Fatalf("ListRegisteredVMs: %v", err)
}
if len(vms) != 1 {
t.Fatalf("got %d vms, want 1", len(vms))
}
if !strings.EqualFold(filepath.Clean(vms[0].Directory), filepath.Clean(newVMDir)) {
t.Fatalf("vm dir = %q, want %q", vms[0].Directory, newVMDir)
if vms[0].Directory != want {
t.Fatalf("vm dir = %q, want %q", vms[0].Directory, want)
}
}
+25 -9
View File
@@ -94,21 +94,16 @@ func (a *App) SetVMDisplay(driverID, name, targetDisplay string) (VMDisplayStatu
placement.Lock()
defer placement.Unlock()
displays := a.displayHost.displays()
cfg := vmstart.VMDisplayConfig{TargetDisplay: vmstart.NormalizeTargetDisplay(targetDisplay)}
status := buildVMDisplayStatus(vm, cfg, displays)
if status.FallbackToPrimary && !strings.EqualFold(cfg.TargetDisplay, vmstart.ReadVMDisplay(vm.Directory).TargetDisplay) {
return VMDisplayStatus{}, fmt.Errorf("%w: %q is not connected", host.ErrDisplayNotFound, cfg.TargetDisplay)
}
if _, err := vmstart.SaveVMDisplay(vm.Directory, cfg); err != nil {
status, err := saveVMTargetDisplay(vm, targetDisplay, a.displayHost.displays())
if err != nil {
return VMDisplayStatus{}, err
}
defer a.emitStateChanged()
if !status.Running || len(displays) == 0 {
if !status.Running || len(status.Displays) == 0 {
return status, nil
}
if status.FallbackToPrimary {
a.emitVMLogForDriver(vm.DriverID, vm.Name, displayFallbackLog(cfg.TargetDisplay))
a.emitVMLogForDriver(vm.DriverID, vm.Name, displayFallbackLog(status.TargetDisplay))
}
if driver.IsHosted(vm.Capabilities) {
// The driver owns a hosted VM's display; only the choice is saved.
@@ -158,6 +153,27 @@ func (a *App) SetVMDisplay(driverID, name, targetDisplay string) (VMDisplayStatu
return status, nil
}
func saveVMTargetDisplay(vm driver.VMInfo, targetDisplay string, displays []host.DisplayInfo) (VMDisplayStatus, error) {
if vm.DriverID == driver.BuiltinReimsMacOSDriverID {
release, err := lockMacOSDisplaySettings(vm.Directory)
if err != nil {
return VMDisplayStatus{}, err
}
defer release()
}
cfg := vmstart.ReadVMDisplay(vm.Directory)
previousTarget := cfg.TargetDisplay
cfg.TargetDisplay = vmstart.NormalizeTargetDisplay(targetDisplay)
status := buildVMDisplayStatus(vm, cfg, displays)
if status.FallbackToPrimary && !strings.EqualFold(cfg.TargetDisplay, previousTarget) {
return VMDisplayStatus{}, fmt.Errorf("%w: %q is not connected", host.ErrDisplayNotFound, cfg.TargetDisplay)
}
if _, err := vmstart.SaveVMDisplay(vm.Directory, cfg); err != nil {
return VMDisplayStatus{}, err
}
return status, nil
}
func displayFallbackLog(target string) string {
return fmt.Sprintf("Display %q is disconnected. Using the primary display.", target)
}
+20
View File
@@ -131,6 +131,26 @@ func TestGetAndSetVMDisplay(t *testing.T) {
}
}
func TestSetVMDisplayPreservesAutoResolution(t *testing.T) {
const driverID = driver.BuiltinReimsMacOSDriverID
vm := driver.VMInfo{Name: "test-vm", DriverID: driverID, Directory: t.TempDir(), State: "stopped"}
a := newDisplayTestApp(t, &appSecondDriver{id: driverID, vms: []driver.VMInfo{vm}})
a.displayHost.displays = func() []host.DisplayInfo {
return []host.DisplayInfo{{Name: "DISPLAY1", Primary: true}, {Name: "DISPLAY2"}}
}
if _, err := vmstart.SaveVMAutoResolution(vm.Directory, true); err != nil {
t.Fatal(err)
}
for _, target := range []string{"DISPLAY2", ""} {
if _, err := a.SetVMDisplay(driverID, vm.Name, target); err != nil {
t.Fatal(err)
}
if got := vmstart.ReadVMDisplay(vm.Directory); got != (vmstart.VMDisplayConfig{TargetDisplay: target, AutoResolution: true}) {
t.Fatalf("selection %q saved %+v", target, got)
}
}
}
func TestSetVMDisplayReadOnly(t *testing.T) {
const driverID = driver.BuiltinReimsMacOSDriverID
vm := driver.VMInfo{Name: "test-vm", DriverID: driverID, Directory: t.TempDir(), State: "stopped"}
+2 -2
View File
@@ -51,7 +51,7 @@ func (a *App) downloadHostHandlers(mgr *plugin.Manager, pluginID string) map[str
}
broker := mgr.Broker()
return map[string]plugin.RPCRequestHandler{
"host/download.start": a.hostMethod(mgr, pluginID, "host/download.start", func(_ context.Context, raw json.RawMessage) (any, error) {
"host/download.start": a.hostAPISvc().hostMethod(mgr, pluginID, "host/download.start", func(_ context.Context, raw json.RawMessage) (any, error) {
a.mu.Lock()
dataRoot := ""
if a.cfg != nil {
@@ -62,7 +62,7 @@ func (a *App) downloadHostHandlers(mgr *plugin.Manager, pluginID string) map[str
notify := func(method string, params any) { mgr.NotifySidecar(pluginID, method, params) }
return a.startPluginDownload(mgr, broker, notify, pluginID, roots, raw)
}),
"host/download.cancel": a.hostMethod(mgr, pluginID, "host/download.cancel", func(_ context.Context, raw json.RawMessage) (any, error) {
"host/download.cancel": a.hostAPISvc().hostMethod(mgr, pluginID, "host/download.cancel", func(_ context.Context, raw json.RawMessage) (any, error) {
return cancelPluginDownload(mgr, pluginID, raw)
}),
}
+31 -26
View File
@@ -33,14 +33,14 @@ type ElevationPrompt struct {
type elevationRunner func(ctx context.Context, action, targetUser string) (host.ElevationResult, error)
func (a *App) elevateHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
func (h *HostAPIService) elevateHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
if mgr == nil || mgr.Broker() == nil {
return nil
}
broker := mgr.Broker()
return map[string]plugin.RPCRequestHandler{
"host/elevate.request": a.hostMethod(mgr, pluginID, "host/elevate.request", func(ctx context.Context, raw json.RawMessage) (any, error) {
return a.requestElevation(ctx, mgr, broker, mgr.Registry(), pluginID, raw)
"host/elevate.request": h.hostMethod(mgr, pluginID, "host/elevate.request", func(ctx context.Context, raw json.RawMessage) (any, error) {
return h.app.requestElevation(ctx, mgr, broker, mgr.Registry(), pluginID, raw)
}),
}
}
@@ -60,9 +60,6 @@ func (a *App) requestElevation(ctx context.Context, kernel hostMethodHost, broke
}
a.mu.Lock()
emit := a.elevateEmit
dismiss := a.elevateDismiss
runner := a.elevateRunner
winCtx := a.ctx
hasWindow := winCtx != nil
locale := i18n.EffectiveLocale(i18n.Auto)
@@ -70,14 +67,20 @@ func (a *App) requestElevation(ctx context.Context, kernel hostMethodHost, broke
locale = i18n.EffectiveLocale(a.cfg.Locale)
}
a.mu.Unlock()
h := a.hostAPISvc()
h.elevateMu.Lock()
emit := h.elevateEmit
dismiss := h.elevateDismiss
runner := h.elevateRunner
h.elevateMu.Unlock()
if emit == nil && !hasWindow {
broker.Audit(pluginID, "ELEVATE_UNAVAILABLE", spec.Action)
return nil, errors.New("elevation_unavailable: the desktop window is required to confirm elevation")
}
// One confirmation and one servicing run at a time.
a.elevatePromptMu.Lock()
defer a.elevatePromptMu.Unlock()
h.elevatePromptMu.Lock()
defer h.elevatePromptMu.Unlock()
prompt := ElevationPrompt{
PluginID: pluginID, PluginName: pluginID, Action: spec.Action,
@@ -92,19 +95,19 @@ func (a *App) requestElevation(ctx context.Context, kernel hostMethodHost, broke
}
ch := make(chan bool, 1)
a.elevateMu.Lock()
if a.elevatePending == nil {
a.elevatePending = map[string]chan bool{}
h.elevateMu.Lock()
if h.elevatePending == nil {
h.elevatePending = map[string]chan bool{}
}
a.elevateSeq++
prompt.ID = fmt.Sprintf("elevate-%d", a.elevateSeq)
a.elevatePending[prompt.ID] = ch
a.elevateMu.Unlock()
h.elevateSeq++
prompt.ID = fmt.Sprintf("elevate-%d", h.elevateSeq)
h.elevatePending[prompt.ID] = ch
h.elevateMu.Unlock()
dismissed := false
clearPrompt := func() {
a.elevateMu.Lock()
delete(a.elevatePending, prompt.ID)
a.elevateMu.Unlock()
h.elevateMu.Lock()
delete(h.elevatePending, prompt.ID)
h.elevateMu.Unlock()
if dismissed {
return
}
@@ -178,10 +181,11 @@ func (a *App) requestElevation(ctx context.Context, kernel hostMethodHost, broke
// ResolveElevationRequest delivers the person's answer to a pending plugin
// elevation request. An expired or answered request is ignored.
func (a *App) ResolveElevationRequest(id string, approved bool) error {
a.elevateMu.Lock()
ch, ok := a.elevatePending[id]
delete(a.elevatePending, id)
a.elevateMu.Unlock()
h := a.hostAPISvc()
h.elevateMu.Lock()
ch, ok := h.elevatePending[id]
delete(h.elevatePending, id)
h.elevateMu.Unlock()
if !ok {
return nil
}
@@ -195,10 +199,11 @@ func (a *App) ResolveElevationRequest(id string, approved bool) error {
// cancelPendingElevations answers every waiting request with a no, so
// shutting down never leaves a plugin waiting on a dialog.
func (a *App) cancelPendingElevations() {
a.elevateMu.Lock()
pending := a.elevatePending
a.elevatePending = nil
a.elevateMu.Unlock()
h := a.hostAPISvc()
h.elevateMu.Lock()
pending := h.elevatePending
h.elevatePending = nil
h.elevateMu.Unlock()
for _, ch := range pending {
close(ch)
}
+5 -5
View File
@@ -40,7 +40,7 @@ func newElevateTestEnv(t *testing.T) *elevateTestEnv {
e := &elevateTestEnv{h: h, plugin: "test.fake.elev"}
h.Add("hosted", e.plugin, "test.driver.elev")
e.app = &App{cfg: &config.Config{DataRoot: h.DataRoot}}
e.app.elevateEmit = func(p ElevationPrompt) {
e.app.hostAPI.elevateEmit = func(p ElevationPrompt) {
e.mu.Lock()
e.prompts = append(e.prompts, p)
answer := e.onPrompt
@@ -49,12 +49,12 @@ func newElevateTestEnv(t *testing.T) *elevateTestEnv {
go answer(p)
}
}
e.app.elevateDismiss = func(id string) {
e.app.hostAPI.elevateDismiss = func(id string) {
e.mu.Lock()
e.dismissed = append(e.dismissed, id)
e.mu.Unlock()
}
e.app.elevateRunner = func(_ context.Context, action, targetUser string) (host.ElevationResult, error) {
e.app.hostAPI.elevateRunner = func(_ context.Context, action, targetUser string) (host.ElevationResult, error) {
e.runs.Add(1)
e.mu.Lock()
e.runArgs = []string{action, targetUser}
@@ -83,7 +83,7 @@ func (e *elevateTestEnv) kernel() testHostMethodHost {
func (e *elevateTestEnv) request(ctx context.Context, pluginID, action string) (any, error) {
raw, _ := json.Marshal(map[string]any{"action": action})
handler := e.app.hostMethod(e.kernel(), pluginID, "host/elevate.request", func(ctx context.Context, raw json.RawMessage) (any, error) {
handler := e.app.hostAPISvc().hostMethod(e.kernel(), pluginID, "host/elevate.request", func(ctx context.Context, raw json.RawMessage) (any, error) {
return e.app.requestElevation(ctx, e.kernel(), e.h.Broker, e.h.Registry, pluginID, raw)
})
return handler(ctx, raw)
@@ -138,7 +138,7 @@ func TestElevationRejectsActionsOutsideTheWhitelist(t *testing.T) {
func TestElevationIsRefusedWithoutADesktopWindow(t *testing.T) {
e := newElevateTestEnv(t)
e.app.elevateEmit = nil
e.app.hostAPI.elevateEmit = nil
_, err := e.request(context.Background(), e.plugin, host.ElevateHyperVEnable)
if err == nil || !strings.Contains(err.Error(), "elevation_unavailable") {
t.Fatalf("err = %v, want elevation_unavailable", err)
+20 -102
View File
@@ -14,6 +14,7 @@ import (
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/installer"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep"
"github.com/Nwflower/reims-go/internal/networkmsg"
@@ -119,6 +120,23 @@ func (a *App) guestToolsImagePath(name string) string {
return filepath.Join(cacheDir, "reims-go", "guest-tools", name+"-tools.img")
}
func buildToolsHFSImage(outPath string, cfg guesttools.VMConfig) error {
if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil {
return err
}
src := guesttools.ToolsDiskFiles(cfg)
files := make([]installer.HFSFile, len(src))
for i, f := range src {
files[i] = installer.HFSFile{
Name: f.Name,
Mode: f.Mode,
Size: f.Size,
Open: f.Open,
}
}
return installer.BuildHFSPlusDiskImage(outPath, guesttools.ToolsVolumeName, files)
}
// buildGuestToolsImage runs in the macOS driver after all start hooks pass.
func (a *App) buildGuestToolsImage(vmName, vmDir string) error {
_, port, _, err := a.startGuestToolsServer()
@@ -132,7 +150,7 @@ func (a *App) buildGuestToolsImage(vmName, vmDir string) error {
return err
}
cfg, _ = a.validatedShareConfig(cfg)
return guesttools.BuildToolsDiskImage(a.guestToolsImagePath(vmName), cfg)
return buildToolsHFSImage(a.guestToolsImagePath(vmName), cfg)
}
// startGuestToolsServer starts the shared localhost HTTP bridge once. Only the
@@ -161,7 +179,6 @@ func (a *App) startGuestToolsServer() (srv *guesttools.Server, port int, created
})
a.guestTools = srv
srv.SetHostDNSConfig(a.hostDNSConfigLocked())
srv.SetStatusChangeHandler(func(string) { a.syncKeymapRules() })
created = true
}
a.syncClipboardStagingLocked()
@@ -214,51 +231,6 @@ func (a *App) guestToolsEnabled() bool {
return err == nil
}
// inputBridgeEnv returns REIMS_GO_INPUT_URL and REIMS_GO_INPUT_TOKEN env vars
// for the VM's QEMU/reims-vgpu-window child process so direct WM_CHAR / IME
// commits can forward to reims-go's local text router.
func (a *App) inputBridgeEnv(name, vmDir string, epoch uint64) []string {
if vmDir == "" {
return nil
}
srv, port, err := a.ensureGuestToolsBridge()
if err != nil || port <= 0 {
return nil
}
cfg, err := a.loadAndRegisterGuestTools(srv, port, vmDir, name, epoch)
if err != nil || cfg.Token == "" {
return nil
}
srv.SetKeymapCarrier(name, false)
a.syncKeymapRules()
return []string{
fmt.Sprintf("REIMS_GO_INPUT_URL=http://127.0.0.1:%d/v1/host-text", port),
"REIMS_GO_INPUT_TOKEN=" + cfg.Token,
}
}
func (a *App) dropBridgeEnv(name, vmDir string, epoch uint64) []string {
if vmDir == "" {
return nil
}
srv, port, err := a.ensureGuestToolsBridge()
if err != nil || port <= 0 {
return nil
}
cfg, err := a.loadAndRegisterGuestTools(srv, port, vmDir, name, epoch)
if err != nil || cfg.Token == "" {
return nil
}
token := srv.HostDropToken(cfg.DriverID, name)
if token == "" {
return nil
}
return []string{
fmt.Sprintf("REIMS_GO_DROP_URL=http://127.0.0.1:%d/v1/host-drop", port),
"REIMS_GO_DROP_TOKEN=" + token,
}
}
func (a *App) registerExistingGuestTools(ctx context.Context) {
srv, port, err := a.ensureGuestToolsBridge()
if err != nil {
@@ -271,7 +243,6 @@ func (a *App) registerExistingGuestTools(ctx context.Context) {
// guest agent that is already running reconnects after reims-go restarts or
// the Guest Tools plugin is switched back on.
func (a *App) registerVMsWithBridge(ctx context.Context, srv *guesttools.Server, port int) {
defer a.syncKeymapRules()
c, err := a.client()
if err != nil {
return
@@ -387,59 +358,6 @@ func (a *App) populateGuestToolsDetail(d *reims.VMDetail, epoch uint64) {
}
}
// syncGuestTools ensures the host HTTP bridge is running and refreshes the
// REIMSTOOLS HFS+ image before VM start when Guest Tools is configured or attached.
func (a *App) syncGuestTools(c *reims.Client, name string, cur *reims.VMDetail, epoch uint64) {
if cur.Directory == "" {
return
}
attached := reims.HasGuestToolsArgs(cur.ExtraArgs)
unlock := a.lockGuestToolsVM(name)
_, configured, err := guesttools.ReadVMConfigStrict(cur.Directory)
unlock()
if err != nil {
a.emitVMLog(name, "Warning: could not load Guest Tools config: "+err.Error())
return
}
if !attached && !configured {
return
}
srv, port, err := a.ensureGuestToolsBridge()
if err != nil {
a.emitVMLog(name, "Warning: could not start Guest Tools bridge: "+err.Error())
return
}
cfg, err := a.loadAndRegisterGuestTools(srv, port, cur.Directory, name, epoch, cur.NetworkMode)
if err != nil {
a.emitVMLog(name, "Warning: could not load Guest Tools config: "+err.Error())
return
}
merged := reims.StripGuestToolsNetworkArgs(cur.ExtraArgs)
if cur.NetworkMode == "bridge" && a.npcapPluginEnabled() {
tokens, argsErr := reims.GuestToolsNetworkUnixArgs(cur.Directory, cfg.ManagementOutSock, cfg.ManagementInSock)
if argsErr != nil {
a.emitVMLog(name, networkmsg.Localize(argsErr, a.locale()).Error())
return
}
merged = strings.TrimSpace(merged + " " + strings.Join(tokens, " "))
} else {
srv.StopManagementNetwork(name)
}
if attached {
imgPath := a.guestToolsImagePath(name)
if err := guesttools.BuildToolsDiskImage(imgPath, cfg); err != nil {
a.emitVMLog(name, "Warning: could not refresh REIMSTOOLS disk: "+err.Error())
return
}
merged = reims.MergeGuestToolsArgs(merged, imgPath)
}
if merged != cur.ExtraArgs {
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err == nil {
cur.ExtraArgs = merged
}
}
}
// AttachGuestTools prepares the per-VM Bearer token, ensures the shared folder
// and localhost bridge are active, builds the read-only REIMSTOOLS HFS+ disk,
// and attaches it to the VM via `reims-ctl set --extra-args`.
@@ -468,7 +386,7 @@ func (a *App) AttachGuestTools(name string) error {
}
imgPath := a.guestToolsImagePath(name)
if err := guesttools.BuildToolsDiskImage(imgPath, cfg); err != nil {
if err := buildToolsHFSImage(imgPath, cfg); err != nil {
return fmt.Errorf("build REIMSTOOLS disk: %w", err)
}
merged := reims.MergeGuestToolsArgs(d.ExtraArgs, imgPath)
+3 -3
View File
@@ -77,7 +77,7 @@ func decodeHostParams[T any](host hostMethodHost, pluginID, method string, raw j
// audits the call under the method name, and hands the request to run. No
// handler states its own permission, so a permission cannot drift from the
// method it guards.
func (a *App) hostMethod(host hostMethodHost, pluginID, method string, run hostMethodHandler) plugin.RPCRequestHandler {
func (h *HostAPIService) hostMethod(host hostMethodHost, pluginID, method string, run hostMethodHandler) plugin.RPCRequestHandler {
return func(ctx context.Context, raw json.RawMessage) (any, error) {
if err := authorizeHostMethod(host, pluginID, method); err != nil {
return nil, err
@@ -94,8 +94,8 @@ func (a *App) hostMethod(host hostMethodHost, pluginID, method string, run hostM
}
// hostVMMethod wraps a handler that needs the manager and the calling plugin.
func (a *App) hostVMMethod(mgr *plugin.Manager, pluginID, method string, run computerUseVMHandler) plugin.RPCRequestHandler {
return a.hostMethod(mgr, pluginID, method, func(ctx context.Context, raw json.RawMessage) (any, error) {
func (h *HostAPIService) hostVMMethod(mgr *plugin.Manager, pluginID, method string, run computerUseVMHandler) plugin.RPCRequestHandler {
return h.hostMethod(mgr, pluginID, method, func(ctx context.Context, raw json.RawMessage) (any, error) {
return run(ctx, raw, mgr, pluginID)
})
}
+48
View File
@@ -0,0 +1,48 @@
package app
import "sync"
// HostAPIService owns the state and RPC handlers for all host-side plugin
// capabilities: computer-use VM control & held inputs, secret materialization,
// host downloads, plugin elevation prompts, and panel file grants.
// Keeping this state off *App isolates lock domains and keeps *App focused on
// Wails IPC bindings and desktop lifecycle coordination.
type HostAPIService struct {
app *App
// Plugin panel file grants (plugin_bridge_files.go).
filesMu sync.Mutex
pluginFiles map[string]pluginFileGrant
// Computer-use VM ownership & held console inputs (computer_use_host.go, computer_use_held.go).
ownedMu sync.Mutex
computerUseOwnedVMs map[string]map[string]bool
computerUseCloneMu sync.Mutex
heldMu sync.Mutex
computerUseHeld map[string]map[string]*heldInputs
// Plugin elevation requests (elevate_flow.go).
elevatePromptMu sync.Mutex
elevateMu sync.Mutex
elevatePending map[string]chan bool
elevateSeq uint64
elevateEmit func(ElevationPrompt)
elevateDismiss func(string)
elevateRunner elevationRunner
}
func (h *HostAPIService) ResetPluginFiles() {
h.filesMu.Lock()
h.pluginFiles = make(map[string]pluginFileGrant)
h.filesMu.Unlock()
}
func (a *App) hostAPISvc() *HostAPIService {
a.mu.Lock()
if a.hostAPI.app == nil {
a.hostAPI.app = a
}
svc := &a.hostAPI
a.mu.Unlock()
return svc
}
+1 -1
View File
@@ -51,7 +51,7 @@ func TestEveryStableHostMethodIsServed(t *testing.T) {
for _, method := range plugin.ReverseHostAPIMethods() {
served[method] = true
}
for method := range app.hostHandlers(mgr, hostContractPlugin) {
for method := range app.hostAPISvc().Handlers(mgr, hostContractPlugin) {
if _, ok := pluginproto.Lookup(method); !ok {
t.Errorf("%s is served but not in the contract catalog", method)
}
+6 -6
View File
@@ -2,15 +2,15 @@ package app
import "github.com/Nwflower/reims-go/internal/plugin"
// hostHandlers returns every host-owned RPC a Sidecar may call, each guarded
// Handlers returns every host-owned RPC a Sidecar may call, each guarded
// by its own permission check.
func (a *App) hostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
func (h *HostAPIService) Handlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
out := map[string]plugin.RPCRequestHandler{}
for _, set := range []map[string]plugin.RPCRequestHandler{
a.computerUseHostHandlers(mgr, pluginID),
a.secretHostHandlers(mgr, pluginID),
a.downloadHostHandlers(mgr, pluginID),
a.elevateHostHandlers(mgr, pluginID),
h.app.computerUseHostHandlers(mgr, pluginID),
h.app.secretHostHandlers(mgr, pluginID),
h.app.downloadHostHandlers(mgr, pluginID),
h.elevateHostHandlers(mgr, pluginID),
} {
for method, handler := range set {
out[method] = handler
-153
View File
@@ -1,153 +0,0 @@
package app
import (
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/vmstart"
)
const KeymapRequiredAgentVersion = guesttools.KeymapAgentVersion
type VMKeymapUpdate struct {
Preset string `json:"preset"`
Bindings map[string]string `json:"bindings"`
CaptureHostShortcuts *bool `json:"capture_host_shortcuts,omitempty"`
}
type VMKeymapStatus struct {
Preset string `json:"preset"`
Bindings map[string]string `json:"bindings"`
CaptureHostShortcuts bool `json:"capture_host_shortcuts"`
NeedsGuestTools bool `json:"needs_guest_tools"`
GuestConnected bool `json:"guest_connected"`
GuestAgentVersion int `json:"guest_agent_version,omitempty"`
RequiredAgentVersion int `json:"required_agent_version"`
GuestKeymapActive bool `json:"guest_keymap_active"`
InputServiceAvailable bool `json:"input_service_available"`
HookActive bool `json:"hook_active"`
Running bool `json:"running"`
}
func (a *App) GetVMKeymap(name string) (VMKeymapStatus, error) {
if vm, ok := a.polledVM(name); ok && vm.Dir != "" {
return a.keymapStatus(name, vm.State == "running", vmstart.ReadVMKeymap(vm.Dir)), nil
}
detail, err := a.GetVMDetail(name)
if err != nil {
return VMKeymapStatus{}, err
}
return a.keymapStatus(name, detail.State == "running", vmstart.ReadVMKeymap(detail.Directory)), nil
}
func (a *App) SetVMKeymap(name string, req VMKeymapUpdate) (VMKeymapStatus, error) {
detail, err := a.GetVMDetail(name)
if err != nil {
return VMKeymapStatus{}, err
}
a.keymapMu.Lock()
capture := vmstart.ReadVMKeymap(detail.Directory).CaptureHostShortcuts
if req.CaptureHostShortcuts != nil {
capture = *req.CaptureHostShortcuts
}
cfg := vmstart.VMKeymapConfig{
Preset: vmstart.KeymapPreset(req.Preset),
Bindings: make(map[vmstart.HostModifier]vmstart.GuestModifier, len(req.Bindings)),
CaptureHostShortcuts: capture,
}
for k, v := range req.Bindings {
cfg.Bindings[vmstart.HostModifier(k)] = vmstart.GuestModifier(v)
}
cfg, err = vmstart.SaveVMKeymap(detail.Directory, cfg)
if err != nil {
a.keymapMu.Unlock()
return VMKeymapStatus{}, err
}
a.syncKeymapRulesLocked()
a.keymapMu.Unlock()
return a.keymapStatus(name, detail.State == "running", cfg), nil
}
func (a *App) keymapStatus(name string, running bool, cfg vmstart.VMKeymapConfig) VMKeymapStatus {
status := VMKeymapStatus{
Preset: string(cfg.Preset),
Bindings: keymapBindingStrings(vmstart.ResolveKeymapBindings(cfg)),
CaptureHostShortcuts: cfg.CaptureHostShortcuts,
NeedsGuestTools: vmstart.NeedsGuestCarrier(vmstart.EffectiveKeymapBindings(cfg)),
RequiredAgentVersion: KeymapRequiredAgentVersion,
Running: running,
}
a.mu.Lock()
srv := a.guestTools
a.mu.Unlock()
if srv != nil && running {
guest := srv.Status(name, guesttools.KeymapStatusMaxAge)
status.GuestConnected = guest.Connected
status.GuestAgentVersion = guest.AgentVersion
status.GuestKeymapActive = guest.KeymapActive
}
svc := a.getInputService()
status.InputServiceAvailable = svc != nil
if svc != nil && running {
status.HookActive = svc.IsKeymapActiveForVM(name)
}
return status
}
func keymapBindingStrings(bindings map[vmstart.HostModifier]vmstart.GuestModifier) map[string]string {
out := make(map[string]string, len(bindings))
for k, v := range bindings {
out[string(k)] = string(v)
}
return out
}
func (a *App) syncKeymapRules() {
a.keymapMu.Lock()
defer a.keymapMu.Unlock()
a.syncKeymapRulesLocked()
}
func (a *App) syncKeymapRulesLocked() {
a.mu.Lock()
vms := append([]driver.VMListItem(nil), a.lastVMs...)
srv := a.guestTools
a.mu.Unlock()
svc := a.getInputService()
var rules []host.KeymapRule
var targets []host.IMETarget
pids := make(map[string]int)
for _, vm := range vms {
if vm.RunningPID() == 0 {
if srv != nil {
srv.SetKeymapCarrier(vm.Name, false)
}
continue
}
dir := vm.Dir
if dir == "" {
if detail, err := a.GetVMDetail(vm.Name); err == nil {
dir = detail.Directory
}
}
targets = append(targets, host.IMETarget{VMName: vm.Name, VMDir: dir, PID: uint32(*vm.PID)})
pids[vm.Name] = *vm.PID
cfg := vmstart.ReadVMKeymap(dir)
effective := vmstart.EffectiveKeymapBindings(cfg)
rule := host.KeymapRule{VMName: vm.Name, Bindings: keymapBindingStrings(effective)}
if srv != nil {
if oldPID := a.keymapPIDs[vm.Name]; oldPID != 0 && oldPID != *vm.PID {
srv.SetKeymapCarrier(vm.Name, false)
}
srv.SetKeymapCarrier(vm.Name, svc != nil && vmstart.NeedsGuestCarrier(effective))
rule.CarrierReady = srv.Status(vm.Name, guesttools.KeymapStatusMaxAge).KeymapActive
}
if len(effective) != 0 {
rules = append(rules, rule)
}
}
a.keymapPIDs = pids
if svc != nil {
svc.SetTargetsAndKeymapRules(targets, rules)
}
}
-124
View File
@@ -1,124 +0,0 @@
package app
import (
"context"
"encoding/json"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/vmstart"
)
func boolPtr(v bool) *bool { return &v }
func TestVMKeymapCaptureStatus(t *testing.T) {
dir := t.TempDir()
id := driver.BuiltinReimsMacOSDriverID
drv := &appSecondDriver{id: id, vms: []driver.VMInfo{{Name: "mac", DriverID: id, Directory: dir, State: "running"}}}
reg := plugin.NewRegistry(nil)
if err := reg.Register(plugin.PluginDef{
Manifest: plugin.Manifest{ID: "test." + id, Version: "1.0.0"},
Source: plugin.SourceBuiltin,
Desired: true,
Activate: func(_ context.Context, sc *plugin.Scope) error {
reg.RegisterGuestDriver(sc, id, drv)
return nil
},
}); err != nil {
t.Fatal(err)
}
reg.Reconcile(context.Background())
a := &App{cfg: &config.Config{DataRoot: dir}, lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil)}
t.Cleanup(func() { a.getInputService().Close() })
for _, enabled := range []bool{true, false} {
got, err := a.SetVMKeymap("mac", VMKeymapUpdate{Preset: "off", CaptureHostShortcuts: boolPtr(enabled)})
if err != nil || got.Preset != "off" || !got.Running || got.CaptureHostShortcuts != enabled || got.NeedsGuestTools != enabled || len(got.Bindings) != 0 {
t.Fatalf("SetVMKeymap capture=%v: %+v, %v", enabled, got, err)
}
got, err = a.GetVMKeymap("mac")
if err != nil || got.Preset != "off" || !got.Running || got.CaptureHostShortcuts != enabled || got.NeedsGuestTools != enabled || len(got.Bindings) != 0 {
t.Fatalf("GetVMKeymap capture=%v: %+v, %v", enabled, got, err)
}
}
// Legacy Wails payloads omitting capture_host_shortcuts must preserve existing setting.
if _, err := a.SetVMKeymap("mac", VMKeymapUpdate{Preset: "off", CaptureHostShortcuts: boolPtr(true)}); err != nil {
t.Fatal(err)
}
for _, raw := range []string{`{"preset":"win_to_cmd","bindings":{}}`, `{"preset":"off","bindings":{}}`} {
var legacy VMKeymapUpdate
if err := json.Unmarshal([]byte(raw), &legacy); err != nil {
t.Fatal(err)
}
if legacy.CaptureHostShortcuts != nil {
t.Fatalf("legacy payload %s unexpectedly set pointer", raw)
}
got, err := a.SetVMKeymap("mac", legacy)
if err != nil || !got.CaptureHostShortcuts || !got.NeedsGuestTools {
t.Fatalf("legacy update %s lost capture flag: %+v, %v", raw, got, err)
}
}
got, err := a.SetVMKeymap("mac", VMKeymapUpdate{Preset: "off", CaptureHostShortcuts: boolPtr(false)})
if err != nil || got.CaptureHostShortcuts || got.NeedsGuestTools {
t.Fatalf("explicit false did not disable capture: %+v, %v", got, err)
}
// Concurrent explicit enable + legacy update (omitting capture_host_shortcuts)
// must serialize read-merge-save and never clobber capture back to false.
const iterations = 16
for i := 0; i < iterations; i++ {
if _, err := a.SetVMKeymap("mac", VMKeymapUpdate{Preset: "off", CaptureHostShortcuts: boolPtr(false)}); err != nil {
t.Fatal(err)
}
start := make(chan struct{})
done := make(chan error, 2)
go func() {
<-start
_, err := a.SetVMKeymap("mac", VMKeymapUpdate{Preset: "off", CaptureHostShortcuts: boolPtr(true)})
done <- err
}()
go func() {
<-start
_, err := a.SetVMKeymap("mac", VMKeymapUpdate{Preset: "win_to_cmd"})
done <- err
}()
close(start)
for j := 0; j < 2; j++ {
if err := <-done; err != nil {
t.Fatal(err)
}
}
final, err := a.GetVMKeymap("mac")
if err != nil || !final.CaptureHostShortcuts {
t.Fatalf("iter %d: concurrent legacy update clobbered capture flag: %+v, %v", i, final, err)
}
}
}
func TestKeymapStatusWithoutPluginManager(t *testing.T) {
a := &App{}
t.Cleanup(func() { a.getInputService().Close() })
a.syncKeymapRules()
cfg := vmstart.VMKeymapConfig{Preset: vmstart.KeymapWinToCmd}
got := a.keymapStatus("mac", true, cfg)
if got.Preset != "win_to_cmd" || got.Bindings["lwin"] != "lcmd" ||
!got.NeedsGuestTools || !got.InputServiceAvailable || !got.Running || got.RequiredAgentVersion != KeymapRequiredAgentVersion ||
got.GuestConnected || got.GuestKeymapActive || got.HookActive {
t.Fatalf("unexpected status: %+v", got)
}
got = a.keymapStatus("mac", false, vmstart.DefaultVMKeymapConfig())
if got.Preset != "off" || got.Running || got.NeedsGuestTools || got.Bindings == nil || len(got.Bindings) != 0 {
t.Fatalf("unexpected defaults: %+v", got)
}
}
func TestKeymapStatusWithoutInputService(t *testing.T) {
a := &App{inputShuttingDown: true}
status := a.keymapStatus("mac", true, vmstart.VMKeymapConfig{Preset: vmstart.KeymapWinToCmd})
if status.InputServiceAvailable || status.HookActive || !status.NeedsGuestTools {
t.Fatalf("unexpected status: %+v", status)
}
}
+23 -4
View File
@@ -1,9 +1,11 @@
package app
import (
"encoding/json"
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/macos/guest"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/plugin"
@@ -11,6 +13,23 @@ import (
"github.com/Nwflower/reims-go/internal/qmp"
)
func stripLegacyManagedExtraArgs(extraArgs string) string {
s := reims.StripGuestToolsArgs(extraArgs)
s = reims.StripPacketBridgeArgs(s)
s = reims.StripGuestToolsNetworkArgs(s)
s = reims.StripOfflineHelperArgs(s)
s = qmp.StripLegacyWin10RebootArgs(s)
s = reims.StripIncomingDeferArgs(s)
return strings.TrimSpace(s)
}
func vmInfoFromMacOSDetail(detail reims.VMDetail) driver.VMInfo {
raw, _ := json.Marshal(detail)
var data map[string]any
_ = json.Unmarshal(raw, &data)
return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: detail.DiskPath(), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort, DriverData: data}
}
func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) {
// Simulate an existing pre-plugin VM whose vm.toml already contains:
// user arg + REIMSTOOLS + REIMSHELP + Win10 managed QMP args, with NO ledger file yet.
@@ -45,7 +64,7 @@ func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) {
}
base := stripLegacyManagedExtraArgs(legacy)
res := plugin.ReconcileStartIntents(base, ledger, active, intents)
res := plugin.ReconcileStartIntentsForDriver(base, ledger, active, "", intents)
if !strings.Contains(res.ExtraArgs, "-cpu host") {
t.Fatalf("user arg lost: %s", res.ExtraArgs)
@@ -62,7 +81,7 @@ func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) {
{PluginID: guest.ID, ClearKeys: []string{"reimshelp", "win10-cold-reboot"}},
}
base2 := stripLegacyManagedExtraArgs(res.ExtraArgs)
res2 := plugin.ReconcileStartIntents(base2, ledger, active, nextIntents)
res2 := plugin.ReconcileStartIntentsForDriver(base2, ledger, active, "", nextIntents)
if res2.ExtraArgs != "-cpu host" {
t.Fatalf("expected only user arg after clearing managed keys, got: %q", res2.ExtraArgs)
}
@@ -94,7 +113,7 @@ func TestPreMergeLedgerFragmentsCarriedIntoCore(t *testing.T) {
}}
}
unmigrated := plugin.ReconcileStartIntents(extra, newLedger(), active, intents)
unmigrated := plugin.ReconcileStartIntentsForDriver(extra, newLedger(), active, "", intents)
if strings.Contains(unmigrated.ExtraArgs, "kernel-irqchip") {
t.Fatalf("test premise: an unmigrated ledger should drop the fragment, got %q", unmigrated.ExtraArgs)
}
@@ -103,7 +122,7 @@ func TestPreMergeLedgerFragmentsCarriedIntoCore(t *testing.T) {
if !guest.MigrateLedger(ledger) {
t.Fatal("MigrateLedger reported no change for a retired owner")
}
res := plugin.ReconcileStartIntents(extra, ledger, active, intents)
res := plugin.ReconcileStartIntentsForDriver(extra, ledger, active, "", intents)
if got := strings.Count(res.ExtraArgs, "kernel-irqchip=off"); got != 1 {
t.Fatalf("want kernel-irqchip=off carried exactly once, got %d in %q", got, res.ExtraArgs)
}
+27 -45
View File
@@ -75,7 +75,12 @@ func (a *App) resolveVMInfo(driverID, name string) (driver.VMInfo, error) {
if err != nil {
return driver.VMInfo{}, err
}
return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: detail.DiskPath(), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort}, nil
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,
}, nil
}
func (a *App) GetVMInfo(driverID, name string) (driver.VMInfo, error) {
@@ -101,16 +106,7 @@ func (a *App) StartVM(driverID, name string) error {
svc := a.lifecycleSvc
a.mu.Unlock()
if svc == nil {
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
return fmt.Errorf("driver %q is unavailable without the plugin manager", driverID)
}
vm, err := a.resolveVMInfo(driver.BuiltinReimsMacOSDriverID, name)
if err != nil {
return err
}
return a.withComputerUseVM(context.Background(), vm.Directory, func(context.Context) error {
return a.startMacOSVM(vm.Name)
})
return errors.New("driver lifecycle is not initialized")
}
_, vm, err := svc.Resolve(context.Background(), driverID, name)
if err != nil {
@@ -128,7 +124,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.startMacOSVM(vm.Name)
return errors.New("driver lifecycle is not initialized")
}
ref := vm.Ref()
key := ref.Key()
@@ -179,10 +175,7 @@ func (a *App) stopVM(ctx context.Context, driverID, name string, force bool) err
svc := a.lifecycleSvc
a.mu.Unlock()
if svc == nil {
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
return errors.New("driver is unavailable without the plugin manager")
}
return a.stopMacOSVM(ctx, name, force)
return errors.New("driver lifecycle is not initialized")
}
_, vm, err := svc.Resolve(ctx, driverID, name)
if err != nil {
@@ -222,10 +215,7 @@ func (a *App) EjectInstaller(driverID, name string) error {
svc := a.lifecycleSvc
a.mu.Unlock()
if svc == nil {
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
return errors.New("driver is unavailable without the plugin manager")
}
return a.ejectMacOSInstaller(name)
return errors.New("driver lifecycle is not initialized")
}
vm, err := a.resolveVMInfo(driverID, name)
if err != nil {
@@ -247,7 +237,14 @@ func (a *App) ReadVMLogs(driverID, name string, serial bool) (string, error) {
svc := a.lifecycleSvc
a.mu.Unlock()
if svc == nil {
return a.readMacOSVMLogs(name, serial)
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
return "", fmt.Errorf("driver %q is unavailable without the plugin manager", driverID)
}
c, err := a.client()
if err != nil {
return "", err
}
return c.ReadLogs(context.Background(), name, serial)
}
return svc.ReadLogs(context.Background(), driver.VMRef{DriverID: driverID, Name: name}, serial)
}
@@ -261,27 +258,15 @@ func (a *App) RestartVM(driverID, name string) error {
a.mu.Lock()
svc := a.lifecycleSvc
a.mu.Unlock()
var ref driver.VMRef
if svc != nil {
_, vm, err := svc.Resolve(context.Background(), driverID, name)
if err != nil {
return err
}
ref = vm.Ref()
} else {
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
return fmt.Errorf("driver %q is unavailable without the plugin manager", driverID)
}
ref = driver.NewVMRef(driver.BuiltinReimsMacOSDriverID, name)
if svc == nil {
return errors.New("driver lifecycle is not initialized")
}
_, vm, err := svc.Resolve(context.Background(), driverID, name)
if err != nil {
return err
}
ref := vm.Ref()
if ref.DriverID != driver.BuiltinReimsMacOSDriverID {
if svc == nil {
return errors.New("driver lifecycle is not initialized")
}
_, vm, err := svc.Resolve(a.baseCtx(), ref.DriverID, ref.Name)
if err != nil {
return err
}
return a.withComputerUseVM(a.baseCtx(), vm.Directory, func(ctx context.Context) error {
if err := a.stopVM(ctx, ref.DriverID, ref.Name, false); err != nil {
return err
@@ -289,7 +274,7 @@ func (a *App) RestartVM(driverID, name string) error {
return a.startResolvedVMLocked(ctx, svc, vm)
})
}
_, err := a.restartMacOSVM(a.baseCtx(), ref.Name)
_, err = a.restartMacOSVM(a.baseCtx(), ref.Name)
return err
}
@@ -298,10 +283,7 @@ func (a *App) DeleteVM(driverID, name string, keepFiles bool) error {
svc := a.lifecycleSvc
a.mu.Unlock()
if svc == nil {
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
return errors.New("driver is unavailable without the plugin manager")
}
return a.deleteMacOSVM(name, keepFiles)
return errors.New("driver lifecycle is not initialized")
}
d, vm, err := svc.ResolveForDelete(context.Background(), driverID, name)
if err != nil {
-100
View File
@@ -1,12 +1,9 @@
package app
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"net"
"os"
"path/filepath"
"strings"
@@ -15,12 +12,10 @@ import (
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/macos/macosdriver"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/qmp"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/tray"
"github.com/Nwflower/reims-go/internal/vmstart"
@@ -67,101 +62,6 @@ func TestMacOSLaunchUsesLatestRuntimeSelection(t *testing.T) {
}
}
func TestPrepareLegacyColdStart(t *testing.T) {
log := func(line string) { t.Log(line) }
t.Run("recoverable snapshot", func(t *testing.T) {
dir := t.TempDir()
state := reims.SuspendStatePath(dir) + ".tmp"
meta := reims.SuspendMetaPath(dir) + ".tmp"
for _, path := range []string{state, meta} {
if err := os.WriteFile(path, []byte("snapshot data"), 0o600); err != nil {
t.Fatal(err)
}
}
err := prepareLegacyColdStart(t.Context(), i18n.EnUS, "mac", "", reims.VMDetail{Directory: dir, State: "stopped"}, log)
var coded *i18n.CodedError
if !errors.As(err, &coded) || coded.Code != "E_VM_SUSPENDED" || coded.Key != "err.suspend.action_blocked" {
t.Fatalf("legacy cold start = %v, want E_VM_SUSPENDED", err)
}
if !reims.HasSuspendState(dir) {
t.Fatal("recoverable snapshot was removed")
}
})
t.Run("inspection error", func(t *testing.T) {
dir := t.TempDir()
staged := reims.SuspendStatePath(dir) + ".tmp"
if err := os.WriteFile(staged, []byte("snapshot data"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(reims.SuspendMetaPath(dir)+".tmp", 0o700); err != nil {
t.Fatal(err)
}
err := prepareLegacyColdStart(t.Context(), i18n.EnUS, "mac", "", reims.VMDetail{Directory: dir, State: "stopped"}, log)
if !errors.Is(err, reims.ErrSuspendArtifactsUncertain) {
t.Fatalf("legacy cold start = %v, want inspection error", err)
}
if data, err := os.ReadFile(staged); err != nil || string(data) != "snapshot data" {
t.Fatalf("staged state = %q, %v", data, err)
}
})
for _, tt := range []struct {
name, dir string
}{
{"postmigrate", "."},
{"postmigrate on short socket for long VM directory", strings.Repeat("v", 100)},
} {
t.Run(tt.name, func(t *testing.T) {
t.Chdir(t.TempDir())
const name, tmpDir = "mac", "tmp"
if err := os.MkdirAll(tt.dir, 0o700); err != nil {
t.Fatal(err)
}
staged := reims.SuspendStatePath(tt.dir) + ".tmp"
if err := os.WriteFile(staged, []byte("snapshot data"), 0o600); err != nil {
t.Fatal(err)
}
socket := qmp.SocketPathForVM(tt.dir, name, tmpDir)
if err := os.MkdirAll(filepath.Dir(socket), 0o700); err != nil {
t.Fatal(err)
}
ln, err := net.Listen("unix", socket)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = ln.Close() })
if tt.dir != "." {
if _, err := os.Lstat(qmp.SocketPath(tt.dir)); !os.IsNotExist(err) {
t.Fatalf("unexpected VM directory socket: %v", err)
}
}
go func() {
conn, err := ln.Accept()
if err != nil {
return
}
defer conn.Close()
_, _ = fmt.Fprintln(conn, `{"QMP":{}}`)
sc := bufio.NewScanner(conn)
if sc.Scan() {
_, _ = fmt.Fprintln(conn, `{"return":{}}`)
}
if sc.Scan() {
_, _ = fmt.Fprintln(conn, `{"return":{"running":false,"status":"postmigrate"}}`)
}
}()
err = prepareLegacyColdStart(t.Context(), i18n.EnUS, name, tmpDir, reims.VMDetail{Directory: tt.dir, State: "stopped"}, log)
if err == nil || !strings.Contains(err.Error(), "QEMU is still active (QMP status: postmigrate)") {
t.Fatalf("legacy cold start = %v, want active QEMU error", err)
}
if data, err := os.ReadFile(staged); err != nil || string(data) != "snapshot data" {
t.Fatalf("staged state = %q, %v", data, err)
}
})
}
}
type appSecondDriver struct {
id string
vms []driver.VMInfo
+2 -7
View File
@@ -23,13 +23,6 @@ func macOSDetailFromVMInfo(vm driver.VMInfo) (reims.VMDetail, error) {
return detail, nil
}
func vmInfoFromMacOSDetail(detail reims.VMDetail) driver.VMInfo {
raw, _ := json.Marshal(detail)
var data map[string]any
_ = json.Unmarshal(raw, &data)
return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: detail.DiskPath(), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort, DriverData: data}
}
func (a *App) loadMacOSVMDetail(name string, epoch uint64) (reims.VMDetail, error) {
c, err := a.client()
if err != nil {
@@ -44,6 +37,7 @@ func (a *App) loadMacOSVMDetail(name string, epoch uint64) (reims.VMDetail, erro
a.populateGuestLangDetail(&d)
populateSuspendDetail(&d)
populateNestedVirtDetail(&d)
d.AutoResolution = vmstart.SupportsAutoResolution(d.Graphics) && vmstart.ReadVMDisplay(d.Directory).AutoResolution
return d, nil
}
@@ -78,6 +72,7 @@ func (a *App) getVMDetail(name string, epoch uint64) (reims.VMDetail, error) {
a.populateGuestLangDetail(&d)
populateSuspendDetail(&d)
populateNestedVirtDetail(&d)
d.AutoResolution = vmstart.SupportsAutoResolution(d.Graphics) && vmstart.ReadVMDisplay(d.Directory).AutoResolution
return d, nil
}
+1 -465
View File
@@ -4,23 +4,11 @@ import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
"time"
"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/guest"
"github.com/Nwflower/reims-go/internal/macos/macosdriver"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep"
"github.com/Nwflower/reims-go/internal/networkmsg"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"github.com/Nwflower/reims-go/internal/qmp"
"github.com/Nwflower/reims-go/internal/vmstart"
)
@@ -178,353 +166,6 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) {
}()
}
// stripLegacyManagedExtraArgs removes reims-go internally managed QEMU arg
// fragments (reimstools, reimshelp, and legacy managed Win10 QMP targets)
// before ledger reconciliation so pre-plugin VMs and out-of-band helpers never
// produce duplicate QEMU device IDs on upgrade.
func stripLegacyManagedExtraArgs(extraArgs string) string {
s := reims.StripGuestToolsArgs(extraArgs)
s = reims.StripPacketBridgeArgs(s)
s = reims.StripGuestToolsNetworkArgs(s)
s = reims.StripOfflineHelperArgs(s)
s = qmp.StripLegacyWin10RebootArgs(s)
s = reims.StripIncomingDeferArgs(s)
return strings.TrimSpace(s)
}
func (a *App) startMacOSVM(name string) error {
if err := a.requireWritableDataRoot(); err != nil {
return err
}
prep, err := a.prep(name)
if err != nil {
return err
}
c := prep.Client
a.mu.Lock()
root := a.cfg.DataRoot
tmpDir := a.cfg.TempDir()
locale := a.cfg.Locale
a.mu.Unlock()
rep := host.Inspect(root)
if err := prep.CheckWHPX(rep); err != nil {
a.emitVMLog(name, "Start refused: "+err.Error())
return err
}
curDetail, release, err := startprep.LockVM(context.Background(), c, name)
if err != nil {
return err
}
unlock := sync.OnceFunc(release)
defer unlock()
if err := prepareLegacyColdStart(context.Background(), c.Locale, name, tmpDir, curDetail, func(line string) {
a.emitVMLog(name, line)
}); err != nil {
return err
}
releaseNet, err := a.prepareManagedVMNetwork(context.Background(), name, false)
if err != nil {
return err
}
if releaseNet != nil {
defer releaseNet()
}
if err := prep.CheckMemory(curDetail.Memory, rep); err != nil {
a.emitVMLog(name, "Start refused: "+err.Error())
return err
}
a.cancelRebootWatcher(name)
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
var qmpAddr string
if mgr != nil {
// Unified plugin-kernel start pipeline (§4.4): collect all vm.beforeStart
// intents (builtin + L1 rule hooks + L3 code hooks) and write merged
// extra-args via AT MOST ONE `reims-ctl set --extra-args` call.
rtCaps := prep.Runtime.Manifest.EffectiveCapabilities()
intents, blockErr := mgr.Registry().Hooks().DispatchBeforeStart(context.Background(), plugin.BeforeStartPayload{
VMName: name,
VMSettingsKey: driver.NewVMRef(builtin.IDDriverReimsMacOS, name).Key(),
VMDir: curDetail.Directory,
DriverID: builtin.IDDriverReimsMacOS,
ExtraArgs: curDetail.ExtraArgs,
HasInstaller: curDetail.HasInstaller,
InstallerPath: curDetail.InstallerPath,
RuntimeKind: prep.Runtime.Manifest.EffectiveKind(),
RuntimeCaps: rtCaps,
HostFacts: buildHostFacts(rep, rtCaps),
VMCaps: macosdriver.ReimsMacOSCapabilities,
State: curDetail.State,
})
if blockErr != nil {
a.emitVMLog(name, "Start blocked: "+blockErr.Error())
return blockErr
}
ledger, ledgerErr := plugin.LoadArgLedger(curDetail.Directory)
if ledgerErr != nil {
a.emitVMLog(name, "Warning: could not read arg ledger: "+ledgerErr.Error())
ledger = &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{}}
}
// Reassign macOS-owned fragments from legacy builtin.core records to
// builtin.guest.macos before reconciling.
guest.MigrateLedger(ledger)
// Strip pre-ledger or out-of-band managed fragments so upgrading existing
// VMs never duplicates QEMU device IDs.
baseExtraArgs := stripLegacyManagedExtraArgs(curDetail.ExtraArgs)
nested := plugin.StartIntent{PluginID: builtin.IDDriverReimsMacOS}
macosdriver.AppendNestedVirtIntent(&nested, locale, curDetail.Directory, plugin.UserExtraArgs(baseExtraArgs, ledger), rep)
reconciled := plugin.ReconcileStartIntentsForDriver(baseExtraArgs, ledger, mgr.Registry().ActivePluginIDs(), nested.PluginID, append(intents, nested))
reconciled.Changed = strings.TrimSpace(curDetail.ExtraArgs) != reconciled.ExtraArgs
for _, warn := range reconciled.Warnings {
a.emitVMLog(name, "[plugin] "+warn)
}
if len(reconciled.Env) > 0 {
c.Env = append(c.Env, reconciled.Env...)
}
if reconciled.Changed {
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &reconciled.ExtraArgs}, io.Discard, io.Discard); err != nil {
a.emitVMLog(name, "Warning: could not apply reconciled start extra-args: "+err.Error())
} else {
curDetail.ExtraArgs = reconciled.ExtraArgs
_ = plugin.SaveArgLedger(curDetail.Directory, ledger)
}
} else {
_ = plugin.SaveArgLedger(curDetail.Directory, ledger)
}
for _, act := range reconciled.PostStart {
if act.Kind == "qmp.watch_cold_reboot" {
if addr, ok := act.Params["qmp_addr"].(string); ok && addr != "" {
qmpAddr = addr
}
}
}
} else {
if err := a.reconcileLegacyBridgeArgs(context.Background(), c, &curDetail); err != nil {
return err
}
a.syncGuestTools(c, name, &curDetail, a.vmDeleteEpoch(name))
if prep.Runtime.Manifest.HasCapability("win32-unicode-input") {
if env := a.inputBridgeEnv(name, curDetail.Directory, a.vmDeleteEpoch(name)); len(env) > 0 {
c.Env = append(c.Env, env...)
}
}
if prep.Runtime.Manifest.HasCapability("window-file-drop") {
c.Env = append(c.Env, a.dropBridgeEnv(name, curDetail.Directory, a.vmDeleteEpoch(name))...)
}
prep.Prepare(context.Background(), name, rep, &curDetail)
if rep.NeedsColdRebootWorkaround {
sockPath := qmp.RebootSocketPath(curDetail.Directory, tmpDir, name)
_ = os.MkdirAll(filepath.Dir(sockPath), 0o755)
_ = os.Remove(sockPath)
merged := qmp.MergeWin10RebootUnixArgs(curDetail.ExtraArgs, sockPath)
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err != nil {
a.emitVMLog(name, "Win10 cold-reboot extra-args setup skipped: "+err.Error())
} else {
qmpAddr = "unix:" + sockPath
curDetail.ExtraArgs = merged
}
}
ledger, err := plugin.LoadArgLedger(curDetail.Directory)
if err != nil {
return err
}
nested := plugin.StartIntent{PluginID: builtin.IDDriverReimsMacOS}
macosdriver.AppendNestedVirtIntent(&nested, locale, curDetail.Directory, plugin.UserExtraArgs(curDetail.ExtraArgs, ledger), rep)
reconciled := plugin.ReconcileStartIntentsForDriver(curDetail.ExtraArgs, ledger, nil, nested.PluginID, []plugin.StartIntent{nested})
for _, warning := range reconciled.Warnings {
a.emitVMLog(name, warning)
}
if reconciled.Changed {
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &reconciled.ExtraArgs}, io.Discard, io.Discard); err != nil {
return err
}
if err := plugin.SaveArgLedger(curDetail.Directory, ledger); err != nil {
return err
}
curDetail.ExtraArgs = reconciled.ExtraArgs
}
}
if prep.Runtime.Manifest.HasCapability("display-fixed-mode") &&
vmstart.UsesFixedGuestMode(curDetail.Directory, rep.Displays, curDetail.Borderless, curDetail.Resolution) {
c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
}
if prep.Runtime.Manifest.HasCapability("client-window-close") {
c.Env = append(c.Env, vmstart.CloseRequestEnv(name)...)
}
a.mu.Lock()
a.transitions[vmKey(name)] = "starting"
delete(a.pendingChanges, vmKey(name))
a.mu.Unlock()
a.emitStateChanged()
startAt := time.Now()
a.emitStartSummary(name, vmInfoFromMacOSDetail(curDetail), rep, qmpAddr)
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
a.emitVMLog(name, "Starting "+name+"...")
err = c.StartWithCompat(context.Background(), name, w, w, func(msg string) {
a.emitVMLog(name, msg)
})
unlock()
if err != nil {
a.mu.Lock()
delete(a.transitions, vmKey(name))
a.mu.Unlock()
a.emitVMLog(name, "Start error: "+err.Error())
a.emitStateChanged()
return err
}
if qmpAddr != "" && mgr == nil {
a.watchWin10ColdReboot(name, qmpAddr)
}
if mgr != nil {
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStart, plugin.VMEventPayload{
VMName: name,
VMDir: curDetail.Directory,
DriverID: builtin.IDDriverReimsMacOS,
QMPAddr: qmpAddr,
})
}
a.startVMMonitor(name, vmInfoFromMacOSDetail(curDetail), startAt)
a.wakePoll()
a.emitStateChanged()
return nil
}
// 备用启动同样记录参数归属,停用扩展时可精确移除桥接片段。
func (a *App) reconcileLegacyBridgeArgs(ctx context.Context, c networkControlClient, detail *reims.VMDetail) error {
ledger, err := plugin.LoadArgLedger(detail.Directory)
if err != nil {
return err
}
intent := plugin.StartIntent{PluginID: builtin.IDNpcapBridge, ClearKeys: []string{"bridge-network", "npcap-bridge"}}
if detail.NetworkMode == "bridge" {
record, err := reims.ReadNetworkRecord(detail.Directory)
if err != nil {
return err
}
if record.Corrupt {
return networkmsg.Error("record_invalid", nil)
}
if record.Pending {
return networkmsg.Error("packet_pending", nil)
}
mac, err := resolveVMNetworkMAC(ctx, c, *detail)
if err != nil {
return err
}
sockPath := record.SocketPath
if sockPath == "" {
sockPath = reims.VMUnixSocketPath(detail.Directory, a.tempDir(), detail.Name, "bridge.sock")
}
tokens, err := reims.PacketBridgeUnixTokens(mac, sockPath)
if err != nil {
return err
}
intent.Args = []plugin.ArgFragment{{PluginID: builtin.IDNpcapBridge, Key: "bridge-network", Tokens: tokens, Builtin: true, Priority: 78}}
}
// 先剥除旧版未登记的主通道;管理网卡和用户参数保持各自归属。
extra := reims.StripPacketBridgeArgs(detail.ExtraArgs)
result := plugin.ReconcileStartIntents(extra, ledger, nil, []plugin.StartIntent{intent})
for _, warning := range result.Warnings {
a.emitVMLog(detail.Name, warning)
}
if result.ExtraArgs != detail.ExtraArgs {
if err := c.Set(ctx, reims.SetOpts{Name: detail.Name, ExtraArgs: &result.ExtraArgs}, io.Discard, io.Discard); err != nil {
return networkmsg.Error("config_save", err)
}
}
if err := plugin.SaveArgLedger(detail.Directory, ledger); err != nil {
return err
}
detail.ExtraArgs = result.ExtraArgs
return nil
}
// prepareLegacyColdStart guards the older start path against a stopped VM that
// still holds suspend artifacts. It drops provably orphaned files, then refuses
// the start while a recoverable snapshot remains: this path cannot resume one,
// and cold-starting over it would discard the guest's saved state. Resume or
// discard the snapshot from the UI first.
func prepareLegacyColdStart(ctx context.Context, locale i18n.Locale, name, tmpDir string, cur reims.VMDetail, log func(string)) error {
if cur.State != "stopped" {
return nil
}
suspended, err := reims.InspectSuspendState(cur.Directory)
if err != nil {
return err
}
if !suspended {
err := startprep.CleanStaleSuspendBeforeStart(ctx, cur.Directory, name, tmpDir, log, log)
if !errors.Is(err, reims.ErrSuspendStatePresent) {
return err
}
}
return i18n.NewCodedError(locale, "E_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil)
}
func (a *App) stopMacOSVM(ctx context.Context, name string, force bool) error {
c, err := a.client()
if err != nil {
return err
}
detail, err := c.Show(ctx, name)
if err != nil {
return err
}
return a.withComputerUseVM(ctx, detail.Directory, func(operationCtx context.Context) error {
return a.stopMacOSVMLocked(operationCtx, name, force, c)
})
}
func (a *App) stopMacOSVMLocked(ctx context.Context, name string, force bool, c *reims.Client) error {
a.cancelRebootWatcher(name)
stopVMMonitor(name)
a.mu.Lock()
mgr := a.pluginMgr
a.transitions[vmKey(name)] = "stopping"
a.mu.Unlock()
if mgr != nil {
mgr.Registry().Hooks().DispatchBeforeStop(ctx, plugin.VMEventPayload{
VMName: name,
DriverID: builtin.IDDriverReimsMacOS,
})
}
a.emitStateChanged()
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
a.emitVMLog(name, fmt.Sprintf("Stopping %s (force=%v)...", name, force))
var err error
if force {
err = c.StopForce(ctx, name, w, w)
} else {
err = c.Stop(ctx, name, w, w)
}
if err != nil {
a.mu.Lock()
delete(a.transitions, vmKey(name))
a.mu.Unlock()
a.emitVMLog(name, "Stop error: "+err.Error())
return err
}
a.stopPacketBridge(name)
a.mu.Lock()
delete(a.pendingChanges, vmKey(name))
a.mu.Unlock()
if mgr != nil {
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStop, plugin.VMEventPayload{
VMName: name,
DriverID: builtin.IDDriverReimsMacOS,
})
}
a.wakePoll()
a.emitStateChanged()
return nil
}
// 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) {
@@ -555,11 +196,7 @@ func (a *App) restartMacOSVMLocked(ctx context.Context, name string) (stopped bo
svc := a.lifecycleSvc
a.mu.Unlock()
if svc == nil {
vm, resolveErr := a.resolveVMInfo(driver.BuiltinReimsMacOSDriverID, name)
if resolveErr != nil {
return true, resolveErr
}
return true, a.startResolvedVMLocked(ctx, nil, vm)
return true, errors.New("driver lifecycle is not initialized")
}
_, vm, err := svc.Resolve(ctx, driver.BuiltinReimsMacOSDriverID, name)
if err != nil {
@@ -568,99 +205,6 @@ func (a *App) restartMacOSVMLocked(ctx context.Context, name string) (stopped bo
return true, a.startResolvedVMLocked(ctx, svc, vm)
}
func (a *App) ejectMacOSInstaller(name string) error {
c, err := a.client()
if err != nil {
return err
}
detail, err := c.Show(context.Background(), name)
if err != nil {
return err
}
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
a.emitVMLog(name, "Ejecting installer from "+name+"...")
if err := a.withComputerUseVM(context.Background(), detail.Directory, func(ctx context.Context) error {
return c.Eject(ctx, name, w, w)
}); err != nil {
a.emitVMLog(name, "Eject error: "+err.Error())
return err
}
a.emitVMLog(name, "Installer ejected.")
a.emitStateChanged()
return nil
}
func (a *App) deleteMacOSVM(name string, keepFiles bool) error {
c, err := a.client()
if err != nil {
return err
}
detail, err := c.Show(context.Background(), name)
if err != nil {
return err
}
removed := false
err = a.withComputerUseVM(context.Background(), detail.Directory, func(ctx context.Context) error {
return a.deleteMacOSVMLocked(ctx, detail, keepFiles, c, &removed)
})
if removed {
releaseVMTyping(name)
releaseVMThumbnail(name)
}
return err
}
func (a *App) deleteMacOSVMLocked(ctx context.Context, detail reims.VMDetail, keepFiles bool, c *reims.Client, removed *bool) error {
name := detail.Name
if detail.State != "running" {
a.cancelRebootWatcher(name)
stopVMMonitor(name)
a.stopPacketBridge(name)
}
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
a.emitVMLog(name, fmt.Sprintf("Deleting VM %s (keepFiles=%v)...", name, keepFiles))
deleted, deleteErr := a.deleteVMWithGuestTools(name, func() error {
return c.Delete(ctx, name, keepFiles, w, w)
}, func() (bool, error) {
vms, err := c.List(ctx)
if err != nil {
return false, err
}
for _, vm := range vms {
if strings.EqualFold(vm.Name, name) {
return true, nil
}
}
return false, nil
})
if deleteErr != nil {
a.emitVMLog(name, "Delete error: "+deleteErr.Error())
}
if !deleted {
return deleteErr
}
*removed = true
a.cancelRebootWatcher(name)
stopVMMonitor(name)
a.stopPacketBridge(name)
a.mu.Lock()
delete(a.pendingChanges, vmKey(name))
delete(a.transitions, vmKey(name))
delete(a.diskPaths, vmKey(name))
delete(a.procSamples, vmKey(name))
delMgr := a.pluginMgr
a.mu.Unlock()
if delMgr != nil {
delMgr.Registry().Hooks().DispatchObserve(plugin.EventVMDeleted, plugin.VMEventPayload{
VMName: name,
DriverID: builtin.IDDriverReimsMacOS,
})
}
a.wakePoll()
a.emitStateChanged()
return deleteErr
}
// OpenVMFolder shows the VM's directory in File Explorer.
func (a *App) OpenVMFolder(name string) error {
d, err := a.GetVMDetail(name)
@@ -672,11 +216,3 @@ func (a *App) OpenVMFolder(name string) error {
}
return host.OpenFolder(d.Directory)
}
func (a *App) readMacOSVMLogs(name string, serial bool) (string, error) {
c, err := a.client()
if err != nil {
return "", err
}
return c.ReadLogs(context.Background(), name, serial)
}
+89 -110
View File
@@ -6,13 +6,17 @@ import (
"errors"
"fmt"
"io"
"log"
"path/filepath"
"slices"
"strconv"
"strings"
"time"
"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/macosdriver"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep"
"github.com/Nwflower/reims-go/internal/networkmsg"
@@ -79,7 +83,7 @@ func (a *App) CreateVM(opts reims.CreateOpts) error {
if err := a.requireWritableDataRoot(); err != nil {
return err
}
return a.createVMFlow(opts)
return a.createVMFlow(opts, host.ConnectedDisplays)
}
func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) {
@@ -132,126 +136,99 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) {
if issues := reims.ValidateSet(opts, cur, host.Inspect(root), loc); len(issues) > 0 {
return fmt.Errorf("%s", issues[0].Message)
}
var outcome macosdriver.SettingsOutcome
ctx := macosdriver.WithSettingsOutcome(context.Background(), &outcome)
w := vmstart.LineWriter(func(line string) { a.emitVMLog(opts.Name, line) })
a.mu.Lock()
svc := a.lifecycleSvc
a.mu.Unlock()
guestLangChanged := strings.TrimSpace(opts.GuestLang) != "" && strings.TrimSpace(opts.GuestLang) != cur.GuestLang
if svc != nil {
raw, _ := json.Marshal(opts)
var changes map[string]any
_ = json.Unmarshal(raw, &changes)
if err := svc.Set(context.Background(), driver.NewVMRef("", opts.Name), changes, w, w); err != nil {
a.emitVMLog(opts.Name, "Set error: "+err.Error())
return err
}
} else {
if strings.TrimSpace(opts.DiskCache) != "" {
cfg := a.runtimeConfig()
active, err := rt.ResolveActive(&cfg)
if err != nil {
return fmt.Errorf("%s", i18n.T(cfg.Locale, "err.runtime_not_installed"))
}
if !active.Manifest.HasCapability("win32-native-aio") {
return errors.New(i18n.T(i18n.EffectiveLocale(loc), "validate.disk_cache_requires_runtime"))
}
}
c, err := a.client()
if err != nil {
return err
}
locked, release, err := startprep.LockMutableVM(a.baseCtx(), c, opts.Name)
if err != nil {
return err
}
defer release()
if reims.HasCtlSetChanges(opts) {
if err := c.Set(context.Background(), opts, w, w); err != nil {
a.emitVMLog(opts.Name, "Set error: "+err.Error())
return err
}
}
if opts.NestedVirt != nil {
if err := vmstart.SaveVMNestedVirt(locked.Directory, vmstart.VMNestedVirtConfig{Enabled: *opts.NestedVirt}); err != nil {
return err
}
}
if guestLangChanged {
prep, err := a.prep(opts.Name)
if err == nil {
err = prep.ApplyGuestLang(context.Background(), cur.Directory, opts.GuestLang, cur.State == "running")
}
if err != nil {
a.emitVMLog(opts.Name, "Guest language error: "+err.Error())
return err
}
} else if cur.State != "running" && opts.Graphics != "" && opts.Graphics != cur.Graphics {
if prep, err := a.prep(opts.Name); err == nil {
prep.ReplayGuestLang(context.Background(), cur.Directory)
}
}
if svc == nil {
return errors.New("driver lifecycle is not initialized")
}
if cur.State == "running" {
var diffs []PendingChange
if opts.CPUs > 0 && opts.CPUs != cur.CPUs {
diffs = append(diffs, PendingChange{Field: "cpus", From: fmt.Sprintf("%d", cur.CPUs), To: fmt.Sprintf("%d", opts.CPUs)})
}
if opts.Memory != "" && !strings.EqualFold(opts.Memory, cur.Memory) {
diffs = append(diffs, PendingChange{Field: "memory", From: cur.Memory, To: opts.Memory})
}
if opts.Resolution != "" && opts.Resolution != cur.Resolution {
diffs = append(diffs, PendingChange{Field: "resolution", From: cur.Resolution, To: opts.Resolution})
}
if opts.GPU != "" && opts.GPU != cur.GPU {
diffs = append(diffs, PendingChange{Field: "gpu", From: cur.GPU, To: opts.GPU})
}
if opts.Displays > 0 && opts.Displays != cur.Displays {
diffs = append(diffs, PendingChange{Field: "displays", From: fmt.Sprintf("%d", cur.Displays), To: fmt.Sprintf("%d", opts.Displays)})
}
if dc := strings.ToLower(strings.TrimSpace(opts.DiskController)); dc != "" && !strings.EqualFold(dc, cur.DiskController) {
diffs = append(diffs, PendingChange{Field: "disk_controller", From: cur.DiskController, To: dc})
}
if dcache := strings.ToLower(strings.TrimSpace(opts.DiskCache)); dcache != "" && !strings.EqualFold(dcache, cur.DiskCache) {
from := cur.DiskCache
if from == "" {
from = "default"
}
diffs = append(diffs, PendingChange{Field: "disk_cache", From: from, To: dcache})
}
if opts.Borderless != nil && *opts.Borderless != cur.Borderless {
diffs = append(diffs, PendingChange{Field: "borderless", From: fmt.Sprintf("%v", cur.Borderless), To: fmt.Sprintf("%v", *opts.Borderless)})
}
if opts.NestedVirt != nil && *opts.NestedVirt != cur.NestedVirt {
diffs = append(diffs, PendingChange{Field: "nested_virt", From: fmt.Sprintf("%v", cur.NestedVirt), To: fmt.Sprintf("%v", *opts.NestedVirt)})
}
if opts.Audio != nil && *opts.Audio != cur.Audio {
diffs = append(diffs, PendingChange{Field: "audio", From: fmt.Sprintf("%v", cur.Audio), To: fmt.Sprintf("%v", *opts.Audio)})
}
if opts.AudioBackend != "" && opts.AudioBackend != cur.AudioBackend {
from := cur.AudioBackend
if from == "" {
from = "auto"
}
diffs = append(diffs, PendingChange{Field: "audio_backend", From: from, To: opts.AudioBackend})
}
if guestLangChanged {
from := cur.GuestLang
if from == "" {
from = "en-US:0"
}
diffs = append(diffs, PendingChange{Field: "guest_lang", From: from, To: strings.TrimSpace(opts.GuestLang)})
}
if len(diffs) > 0 {
a.mu.Lock()
a.pendingChanges[vmKey(opts.Name)] = append(a.pendingChanges[vmKey(opts.Name)], diffs...)
a.mu.Unlock()
raw, merr := json.Marshal(opts)
if merr != nil {
return fmt.Errorf("encode VM settings: %w", merr)
}
var changes map[string]any
if uerr := json.Unmarshal(raw, &changes); uerr != nil {
return fmt.Errorf("decode VM settings: %w", uerr)
}
if err := svc.Set(ctx, driver.NewVMRef(driver.BuiltinReimsMacOSDriverID, opts.Name), changes, w, w); err != nil {
a.emitVMLog(opts.Name, "Set error: "+err.Error())
return err
}
if diffs := pendingVMSettingsChanges(outcome, opts); len(diffs) > 0 {
a.mu.Lock()
key := vmKey(opts.Name)
a.pendingChanges[key] = mergePendingChanges(a.pendingChanges[key], diffs)
if len(a.pendingChanges[key]) == 0 {
delete(a.pendingChanges, key)
}
a.mu.Unlock()
}
a.emitVMLog(opts.Name, "Updated VM settings for "+opts.Name)
a.emitStateChanged()
return nil
}
func pendingVMSettingsChanges(outcome macosdriver.SettingsOutcome, opts reims.SetOpts) []PendingChange {
if !outcome.Valid || !outcome.Running {
return nil
}
before, after := outcome.Before, outcome.After
candidates := []struct {
touched bool
change PendingChange
}{
{opts.CPUs > 0, PendingChange{Field: "cpus", From: strconv.Itoa(before.CPUs), To: strconv.Itoa(after.CPUs)}},
{opts.Memory != "", PendingChange{Field: "memory", From: before.Memory, To: after.Memory}},
{opts.AutoResolution != nil, PendingChange{Field: "auto_resolution", From: strconv.FormatBool(before.AutoResolution), To: strconv.FormatBool(after.AutoResolution)}},
{opts.Resolution != "", PendingChange{Field: "resolution", From: before.Resolution, To: after.Resolution}},
{opts.GPU != "", PendingChange{Field: "gpu", From: before.GPU, To: after.GPU}},
{opts.Displays > 0, PendingChange{Field: "displays", From: strconv.Itoa(before.Displays), To: strconv.Itoa(after.Displays)}},
{strings.TrimSpace(opts.DiskController) != "", PendingChange{Field: "disk_controller", From: before.DiskController, To: after.DiskController}},
{strings.TrimSpace(opts.DiskCache) != "", PendingChange{Field: "disk_cache", From: before.DiskCache, To: after.DiskCache}},
{opts.Borderless != nil, PendingChange{Field: "borderless", From: strconv.FormatBool(before.Borderless), To: strconv.FormatBool(after.Borderless)}},
{opts.NestedVirt != nil, PendingChange{Field: "nested_virt", From: strconv.FormatBool(before.NestedVirt), To: strconv.FormatBool(after.NestedVirt)}},
{opts.Audio != nil, PendingChange{Field: "audio", From: strconv.FormatBool(before.Audio), To: strconv.FormatBool(after.Audio)}},
{opts.AudioBackend != "", PendingChange{Field: "audio_backend", From: before.AudioBackend, To: after.AudioBackend}},
{strings.TrimSpace(opts.GuestLang) != "", PendingChange{Field: "guest_lang", From: before.GuestLang, To: after.GuestLang}},
}
out := make([]PendingChange, 0, len(candidates))
for _, item := range candidates {
if item.touched || !noPendingChange(item.change) {
out = append(out, item.change)
}
}
return out
}
func mergePendingChanges(existing, incoming []PendingChange) []PendingChange {
merged := make([]PendingChange, 0, len(existing)+len(incoming))
for _, changes := range [2][]PendingChange{existing, incoming} {
for _, change := range changes {
index := slices.IndexFunc(merged, func(pending PendingChange) bool { return pending.Field == change.Field })
if index < 0 {
merged = append(merged, change)
} else {
merged[index].To = change.To
}
}
}
return slices.DeleteFunc(merged, noPendingChange)
}
func noPendingChange(change PendingChange) bool {
if change.Field == "memory" || change.Field == "resolution" || change.Field == "disk_controller" || change.Field == "disk_cache" {
return strings.EqualFold(change.From, change.To)
}
return change.From == change.To
}
func lockMacOSDisplaySettings(vmDir string) (func(), error) {
return reims.LockVMOperation(vmDir)
}
type VMNetworkSettings struct {
Adapters []NetworkAdapter `json:"adapters"`
UplinkGUID string `json:"uplink_guid"`
@@ -325,7 +302,9 @@ func clearManagedNetworkLedger(vmDir string) {
}
}
if changed {
_ = plugin.SaveArgLedger(vmDir, ledger)
if err := plugin.SaveArgLedger(vmDir, ledger); err != nil {
log.Printf("[app] save plugin arg ledger failed (%s): %v", vmDir, err)
}
}
}
+663
View File
@@ -0,0 +1,663 @@
package app
import (
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"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/macos/macosdriver"
"github.com/Nwflower/reims-go/internal/macos/reims"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/vmstart"
)
const (
displayFixtureVM = "test-vm"
displayFixtureClone = "test-clone"
)
type displayCtlFixture struct {
Dir, State, Resolution string
Memory string
BeforeLockResolution string
Shows int
Graphics string
CloneDir string
Borderless bool
FailSet bool
NestedVirtBeforeSet bool
FailShowAfterSet bool
ReplaceDisplayAfterSet bool
Commands []string
}
func TestMain(m *testing.M) {
if path := os.Getenv("REIMS_TEST_DISPLAY_CTL"); path != "" {
switch filepath.Base(os.Args[0]) {
case "reims-ctl", "reims-ctl.exe":
if err := runDisplayCtl(path, os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
case "qemu-img", "qemu-img.exe":
if os.Args[1] == "info" {
fmt.Println(`{"format":"qcow2"}`)
return
}
if os.Args[1] == "create" {
if err := os.WriteFile(os.Args[len(os.Args)-1], []byte("overlay"), 0o600); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
if os.Args[1] == "convert" {
if err := os.WriteFile(os.Args[len(os.Args)-1], []byte("converted disk"), 0o600); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
fmt.Fprintln(os.Stderr, "unexpected qemu-img call", os.Args[1:])
os.Exit(1)
}
}
os.Exit(m.Run())
}
func runDisplayCtl(path string, args []string) error {
raw, err := os.ReadFile(path)
if err != nil {
return err
}
var vm displayCtlFixture
if err := json.Unmarshal(raw, &vm); err != nil {
return err
}
switch args[0] {
case "show":
if args[1] == displayFixtureClone && vm.CloneDir != "" {
fmt.Printf("state stopped\ndirectory %s\ndisplay one opening at %s\n", vm.CloneDir, vm.Resolution)
return nil
}
if vm.State == "" || args[1] != displayFixtureVM || vm.FailShowAfterSet && len(vm.Commands) > 0 {
return fmt.Errorf("VM %q not found", args[1])
}
if vm.BeforeLockResolution != "" {
vm.Shows++
if vm.Shows == 2 {
unlock, err := reims.LockVMOperation(vm.Dir)
if err != nil {
return err
}
defer unlock()
vm.Resolution = vm.BeforeLockResolution
if err := writeDisplayCtlResolution(vm.Dir, vm.Resolution); err != nil {
return err
}
if _, err := vmstart.SaveVMAutoResolution(vm.Dir, false); err != nil {
return err
}
}
raw, err := json.Marshal(vm)
if err != nil {
return err
}
if err := os.WriteFile(path, raw, 0o600); err != nil {
return err
}
}
fmt.Printf("state %s\ndirectory %s\ndisk system.qcow2\ngraphics %s\nmemory %s\n", vm.State, vm.Dir, vm.Graphics, vm.Memory)
if vm.Borderless {
fmt.Printf("display one borderless at %s\n", vm.Resolution)
} else {
fmt.Printf("display one opening at %s\n", vm.Resolution)
}
return nil
case "list":
if vm.State == "" {
fmt.Println("[]")
return nil
}
return json.NewEncoder(os.Stdout).Encode([]reims.VMListItem{{Name: displayFixtureVM, State: vm.State, Dir: vm.Dir}})
case "create":
if args[1] == displayFixtureClone {
vm.CloneDir = filepath.Join(filepath.Dir(vm.Dir), displayFixtureClone)
if err := os.MkdirAll(vm.CloneDir, 0o700); err != nil {
return err
}
} else {
vm.State = "stopped"
if err := os.MkdirAll(vm.Dir, 0o700); err != nil {
return err
}
}
case "set", "start":
if args[0] == "set" && len(args) > 1 && args[1] == "--help" {
return nil
}
default:
return fmt.Errorf("unexpected command %v", args)
}
failSet := args[0] == "set" && vm.FailSet
if failSet {
nested, err := vmstart.ReadVMNestedVirt(vm.Dir)
if err != nil {
return err
}
vm.NestedVirtBeforeSet = nested.Enabled
}
for i := 2; !failSet && i+1 < len(args); i++ {
switch args[i] {
case "--resolution":
vm.Resolution = args[i+1]
if err := writeDisplayCtlResolution(vm.Dir, vm.Resolution); err != nil {
return err
}
case "--borderless":
vm.Borderless = args[i+1] == "true"
case "--graphics":
vm.Graphics = args[i+1]
case "--memory":
vm.Memory = args[i+1]
}
}
if args[0] == "set" && vm.ReplaceDisplayAfterSet {
vm.Resolution = "1024x768"
if _, err := vmstart.SaveVMAutoResolution(vm.Dir, false); err != nil {
return err
}
}
command := strings.Join(args, " ")
if args[0] == "start" {
command += " fixed=" + os.Getenv("REIMS_VGPU_WINDOW_FIXED_MODE")
}
vm.Commands = append(vm.Commands, command)
raw, err = json.Marshal(vm)
if err != nil {
return err
}
if err := os.WriteFile(path, raw, 0o600); err != nil {
return err
}
if args[0] == "start" {
return fmt.Errorf("stop before launching QEMU")
}
if failSet {
return fmt.Errorf("fixture refused set")
}
return nil
}
func writeDisplayCtlResolution(dir, resolution string) error {
config := fmt.Sprintf("disk = 'system.qcow2'\n[display]\nresolution = %q\n", resolution)
return os.WriteFile(filepath.Join(dir, "vm.toml"), []byte(config), 0o600)
}
func newDisplayCtlApp(t *testing.T, vm displayCtlFixture, useDriver bool) (*App, func() displayCtlFixture) {
t.Helper()
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "test-rt"}
if err := cfg.EnsureDirs(); err != nil {
t.Fatal(err)
}
active := rt.Installed{Dir: filepath.Join(cfg.RuntimesDir(), cfg.ActiveRuntime)}
control := active.ControlPath()
if err := os.MkdirAll(filepath.Dir(control), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(active.Dir, "manifest.json"), []byte(`{"schema_version":2,"commit":"test-rt","kind":"reims-vgpu","runtime_api":"1.0.0","capabilities":["display-fixed-mode","vm-suspend"]}`), 0o600); err != nil {
t.Fatal(err)
}
self, err := os.Executable()
if err != nil {
t.Fatal(err)
}
exe, err := os.ReadFile(self)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(control, exe, 0o755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Dir(active.QemuImgPath()), 0o700); err != nil {
t.Fatal(err)
}
if err := os.Link(control, active.QemuImgPath()); err != nil {
t.Fatal(err)
}
fixturePath := filepath.Join(cfg.DataRoot, "display-fixture.json")
t.Setenv("REIMS_TEST_DISPLAY_CTL", fixturePath)
t.Setenv("REIMS_VGPU_WINDOW_FIXED_MODE", "")
t.Setenv("GORACE", "atexit_sleep_ms=0")
registryDir := filepath.Join(cfg.XDGConfigDir(), "reims-ctl")
t.Setenv("REIMS_CTL_CONFIG_DIR", registryDir)
if err := os.MkdirAll(registryDir, 0o700); err != nil {
t.Fatal(err)
}
vm.Dir = filepath.Join(cfg.DataRoot, displayFixtureVM)
if vm.State != "" {
if err := os.MkdirAll(vm.Dir, 0o700); err != nil {
t.Fatal(err)
}
if err := writeDisplayCtlResolution(vm.Dir, vm.Resolution); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(vm.Dir, "system.qcow2"), []byte("source disk fixture"), 0o600); err != nil {
t.Fatal(err)
}
registry := fmt.Sprintf("[[vm]]\nname = %q\ndir = '%s'\n", displayFixtureVM, vm.Dir)
if err := os.WriteFile(filepath.Join(registryDir, "vms.toml"), []byte(registry), 0o600); err != nil {
t.Fatal(err)
}
}
raw, err := json.Marshal(vm)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(fixturePath, raw, 0o600); err != nil {
t.Fatal(err)
}
a := &App{}
if useDriver {
a = newDisplayTestApp(t, macosdriver.NewReimsMacOSDriver(func() config.Config { return cfg }))
}
a.cfg = &cfg
a.transitions = map[string]string{}
a.pendingChanges = map[string][]PendingChange{}
return a, func() displayCtlFixture {
t.Helper()
raw, err := os.ReadFile(fixturePath)
if err != nil {
t.Fatal(err)
}
var current displayCtlFixture
if err := json.Unmarshal(raw, &current); err != nil {
t.Fatal(err)
}
return current
}
}
func TestApplyAutoResolutionWhileRunning(t *testing.T) {
for _, state := range []string{"running", "paused"} {
t.Run(state, func(t *testing.T) {
initial := "1234x876"
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: state, Resolution: initial}, true)
on := true
if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: "1280x800", AutoResolution: &on}); err != nil {
t.Fatal(err)
}
vm := fixture()
want := []PendingChange{
{Field: "auto_resolution", From: "false", To: "true"},
}
if vm.Resolution != initial || len(vm.Commands) != 0 || !vmstart.ReadVMDisplay(vm.Dir).AutoResolution || !slices.Equal(a.pendingChanges[vmKey(displayFixtureVM)], want) {
t.Fatalf("enable auto: VM %+v, changes %+v, want %+v", vm, a.pendingChanges, want)
}
if raw, found := reims.ReadConfiguredResolution(vm.Dir); !found || raw != initial {
t.Fatalf("configured resolution = %q, found = %t, want %q", raw, found, initial)
}
if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: initial}); err != nil {
t.Fatal(err)
}
vm = fixture()
if vm.Resolution != initial || vmstart.ReadVMDisplay(vm.Dir).AutoResolution || len(a.pendingChanges) != 0 {
t.Fatalf("manual resolution: VM %+v, want initial resolution and no pending changes, got %+v", vm, a.pendingChanges)
}
if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: "1280x800"}); err != nil {
t.Fatal(err)
}
want = []PendingChange{{Field: "resolution", From: initial, To: "1280x800"}}
if vm = fixture(); vm.Resolution != "1280x800" || !slices.Equal(a.pendingChanges[vmKey(displayFixtureVM)], want) {
t.Fatalf("changed fixed resolution: VM %+v, changes %+v, want %+v", vm, a.pendingChanges, want)
}
})
}
}
func TestApplyAutoResolutionDoesNotReadBackSettings(t *testing.T) {
for _, tc := range []struct {
name string
failShow, replace bool
}{
{name: "show fails", failShow: true},
{name: "display changed externally", replace: true},
} {
t.Run(tc.name, func(t *testing.T) {
const initial = "1234x876"
a, fixture := newDisplayCtlApp(t, displayCtlFixture{
State: "running", Resolution: initial, FailShowAfterSet: tc.failShow, ReplaceDisplayAfterSet: tc.replace,
}, true)
on := true
if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, CPUs: 1, AutoResolution: &on}); err != nil {
t.Fatal(err)
}
want := []PendingChange{
{Field: "cpus", From: "0", To: "1"},
{Field: "auto_resolution", From: "false", To: "true"},
}
if got := a.pendingChanges[vmKey(displayFixtureVM)]; !slices.Equal(got, want) {
t.Fatalf("pending changes = %+v, want %+v", got, want)
}
if got := fixture().Commands; !slices.Equal(got, []string{"set test-vm --cpus 1"}) {
t.Fatalf("commands = %v", got)
}
})
}
}
func TestApplyAutoResolutionUsesLockedSettingsForPendingChanges(t *testing.T) {
a, fixture := newDisplayCtlApp(t, displayCtlFixture{
State: "running", Resolution: "1234x876", BeforeLockResolution: "2560x1600", Memory: "2G",
}, true)
if _, err := vmstart.SaveVMAutoResolution(fixture().Dir, true); err != nil {
t.Fatal(err)
}
if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Memory: "3G"}); err != nil {
t.Fatal(err)
}
vm := fixture()
if vm.Resolution != "2560x1600" || vm.Memory != "3G" || vmstart.ReadVMDisplay(vm.Dir).AutoResolution {
t.Fatalf("saved VM = %+v, display = %+v", vm, vmstart.ReadVMDisplay(vm.Dir))
}
want := []PendingChange{{Field: "memory", From: "2G", To: "3G"}}
if got := a.pendingChanges[vmKey(displayFixtureVM)]; !slices.Equal(got, want) {
t.Fatalf("pending changes = %+v, want %+v", got, want)
}
}
func TestMergePendingChangesKeepsRunningValues(t *testing.T) {
existing := []PendingChange{
{Field: "memory", From: "8G", To: "12G"},
{Field: "resolution", From: "1920x1080", To: "2560x1440"},
{Field: "gpu", From: "gpu-a", To: "gpu-b"},
{Field: "cpus", From: "4", To: "6"},
}
incoming := []PendingChange{
{Field: "memory", From: "12G", To: "8g"},
{Field: "resolution", From: "2560x1440", To: "1920X1080"},
{Field: "gpu", From: "gpu-b", To: "GPU-A"},
{Field: "cpus", From: "6", To: "8"},
}
want := []PendingChange{
{Field: "gpu", From: "gpu-a", To: "GPU-A"},
{Field: "cpus", From: "4", To: "8"},
}
if got := mergePendingChanges(existing, incoming); !slices.Equal(got, want) {
t.Fatalf("merge = %+v, want %+v", got, want)
}
// When show reports live running value (4 -> 4) while user explicitly sets cpus back to 4,
// pendingVMSettingsChanges still emits cpus so mergePendingChanges removes stale 4 -> 8
// without disturbing unrelated pending entries.
liveOutcome := macosdriver.SettingsOutcome{
Valid: true,
Running: true,
Before: macosdriver.SettingsState{CPUs: 4, Memory: "8G"},
After: macosdriver.SettingsState{CPUs: 4, Memory: "8G"},
}
diffs := pendingVMSettingsChanges(liveOutcome, reims.SetOpts{Name: displayFixtureVM, CPUs: 4})
got := mergePendingChanges([]PendingChange{
{Field: "cpus", From: "4", To: "8"},
{Field: "memory", From: "8G", To: "12G"},
}, diffs)
wantAfterRevert := []PendingChange{{Field: "memory", From: "8G", To: "12G"}}
if !slices.Equal(got, wantAfterRevert) {
t.Fatalf("merge after live-value revert = %+v, want %+v", got, wantAfterRevert)
}
}
func TestApplyAutoResolutionTransaction(t *testing.T) {
for _, tc := range []struct {
name string
failSidecar, failSet bool
}{
{name: "saved"},
{name: "sidecar write fails", failSidecar: true},
{name: "set fails", failSet: true},
} {
t.Run(tc.name, func(t *testing.T) {
const initial = "1234x876"
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: "stopped", Resolution: initial, FailSet: tc.failSet}, true)
dir := fixture().Dir
prev := vmstart.VMDisplayConfig{TargetDisplay: "unplugged-display"}
if tc.failSidecar {
if err := os.Mkdir(filepath.Join(dir, ".reims-go-display.json"), 0o700); err != nil {
t.Fatal(err)
}
} else if _, err := vmstart.SaveVMDisplay(dir, prev); err != nil {
t.Fatal(err)
}
on := true
err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: "1280x800", AutoResolution: &on, NestedVirt: &on})
if tc.failSidecar {
if err == nil || len(fixture().Commands) != 0 {
t.Fatalf("save = %v, commands = %v, want sidecar error before set", err, fixture().Commands)
}
return
}
vm := fixture()
target, _ := host.RecommendAutoResolution(host.PrimaryDisplayOf(host.ConnectedDisplays()), false, true)
if !slices.Equal(vm.Commands, []string{"set test-vm --resolution " + target}) {
t.Fatalf("commands = %v", vm.Commands)
}
if nested, readErr := vmstart.ReadVMNestedVirt(dir); readErr != nil || nested.Enabled != !tc.failSet {
t.Fatalf("nested virtualization = %+v, %v, want enabled = %t", nested, readErr, !tc.failSet)
}
if tc.failSet {
if err == nil || !vm.NestedVirtBeforeSet || vm.Resolution != initial || vmstart.ReadVMDisplay(dir) != prev {
t.Fatalf("save = %v, VM = %+v, display = %+v, want original settings", err, vm, vmstart.ReadVMDisplay(dir))
}
return
}
prev.AutoResolution = true
if err != nil || vm.Resolution != target || vmstart.ReadVMDisplay(dir) != prev {
t.Fatalf("save = %v, VM = %+v, display = %+v, want %s and %+v", err, vm, vmstart.ReadVMDisplay(dir), target, prev)
}
})
}
}
func TestApplyAutoResolutionWithSVGA(t *testing.T) {
for _, graphics := range []string{"vmware-svga", "reims-vgpu"} {
t.Run(graphics, func(t *testing.T) {
const initial = "1234x876"
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: "stopped", Resolution: initial, Graphics: graphics}, true)
dir := fixture().Dir
prev := vmstart.VMDisplayConfig{TargetDisplay: "secondary", AutoResolution: true}
if _, err := vmstart.SaveVMDisplay(dir, prev); err != nil {
t.Fatal(err)
}
detail, err := a.GetVMDetail(displayFixtureVM)
if err != nil || detail.AutoResolution != (graphics == "reims-vgpu") {
t.Fatalf("details = %+v, %v", detail, err)
}
on := true
opts := reims.SetOpts{Name: displayFixtureVM, AutoResolution: &on}
var want []string
if graphics != "vmware-svga" {
opts.Graphics = "vmware-svga"
want = []string{"set test-vm --graphics vmware-svga"}
}
if err := a.ApplyVMSettings(opts); err != nil {
t.Fatal(err)
}
prev.AutoResolution = false
if vm := fixture(); vm.Graphics != "vmware-svga" || vm.Resolution != initial ||
!slices.Equal(vm.Commands, want) || vmstart.ReadVMDisplay(dir) != prev {
t.Fatalf("VM = %+v, display = %+v, want commands %v and display %+v", vm, vmstart.ReadVMDisplay(dir), want, prev)
}
})
}
}
func TestApplyAutoResolutionRollsBackDisplayOnLaterFailure(t *testing.T) {
for _, tc := range []struct {
state, blockedFile string
}{
{"running", ".reims-go-nested-virt.json"},
{"stopped", ".reims-go-nested-virt.json"},
{"running", ".reims-go-guest-lang"},
{"stopped", ".reims-go-guest-lang"},
} {
t.Run(tc.state+"/"+tc.blockedFile, func(t *testing.T) {
const initial = "1234x876"
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: tc.state, Resolution: initial}, true)
dir := fixture().Dir
prev := vmstart.VMDisplayConfig{TargetDisplay: "unplugged-display"}
if _, err := vmstart.SaveVMDisplay(dir, prev); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(filepath.Join(dir, tc.blockedFile), 0o700); err != nil {
t.Fatal(err)
}
on := true
opts := reims.SetOpts{Name: displayFixtureVM, Memory: "4G", AutoResolution: &on, NestedVirt: &on}
if tc.blockedFile == ".reims-go-guest-lang" {
opts.GuestLang = "zh-Hans:0"
}
if err := a.ApplyVMSettings(opts); err == nil || !strings.Contains(err.Error(), tc.blockedFile) {
t.Fatalf("save = %v, want error writing %s", err, tc.blockedFile)
}
if commands := fixture().Commands; len(commands) != 0 {
t.Fatalf("commands = %v, want no reims-ctl set call before local failures", commands)
}
if got := vmstart.ReadVMDisplay(dir); got != prev || len(a.pendingChanges) != 0 {
t.Fatalf("display = %+v, want %+v; pending = %+v", got, prev, a.pendingChanges)
}
if raw, found := reims.ReadConfiguredResolution(dir); !found || raw != initial {
t.Fatalf("configured resolution = %q, found = %t, want %q", raw, found, initial)
}
if opts.GuestLang != "" {
if nested, err := vmstart.ReadVMNestedVirt(dir); err != nil || nested.Enabled {
t.Fatalf("nested virtualization = %+v, %v, want disabled", nested, err)
}
}
})
}
}
func TestApplyAutoResolutionSyncsExistingConfiguration(t *testing.T) {
for _, tc := range []struct {
name, graphics string
borderless bool
}{
{name: "windowed multi-display"},
{name: "borderless multi-display", borderless: true},
{name: "from SVGA", graphics: "vmware-svga"},
} {
t.Run(tc.name, func(t *testing.T) {
res, _ := host.RecommendAutoResolution(host.PrimaryDisplayOf(host.ConnectedDisplays()), tc.borderless, true)
raw := res
want := "set test-vm --resolution " + res
on := true
opts := reims.SetOpts{Name: displayFixtureVM, AutoResolution: &on}
if tc.graphics == "vmware-svga" {
opts.Graphics = "reims-vgpu"
want = "set test-vm --graphics reims-vgpu --resolution " + res
} else {
raw += ",2560x1440"
}
a, fixture := newDisplayCtlApp(t, displayCtlFixture{
State: "stopped", Resolution: res, Graphics: tc.graphics, Borderless: tc.borderless,
}, true)
dir := fixture().Dir
if err := writeDisplayCtlResolution(dir, raw); err != nil {
t.Fatal(err)
}
if err := a.ApplyVMSettings(opts); err != nil {
t.Fatal(err)
}
if got := fixture().Commands; !slices.Equal(got, []string{want}) {
t.Fatalf("commands = %v, want %q", got, want)
}
})
}
}
func TestCreateVMWithAutoResolution(t *testing.T) {
for _, useDriver := range []bool{false, true} {
for _, tc := range []struct {
name, graphics, resolution string
wantAuto bool
}{
{name: "no draft", wantAuto: true},
{name: "stale draft", resolution: "1234x876", wantAuto: true},
{name: "SVGA", graphics: "vmware-svga", resolution: "1234x876"},
{name: "SVGA without resolution", graphics: "vmware-svga"},
} {
t.Run(fmt.Sprintf("driver=%t/%s", useDriver, tc.name), func(t *testing.T) {
a, fixture := newDisplayCtlApp(t, displayCtlFixture{}, false)
if useDriver {
d := macosdriver.NewReimsMacOSDriver(func() config.Config { return *a.cfg })
req := driver.CreateRequest{Name: displayFixtureVM, Options: map[string]any{"auto_resolution": true, "resolution": tc.resolution, "graphics": tc.graphics}}
if err := d.Create(t.Context(), req, io.Discard, io.Discard); err != nil {
t.Fatal(err)
}
} else {
on := true
if err := a.CreateVM(reims.CreateOpts{Name: displayFixtureVM, CPUs: 1, SourceMode: "disk", AutoResolution: &on, Resolution: tc.resolution, Graphics: tc.graphics}); err != nil {
t.Fatal(err)
}
}
vm := fixture()
want := tc.resolution
if tc.wantAuto {
want, _ = host.RecommendAutoResolution(host.PrimaryDisplayOf(host.ConnectedDisplays()), false, true)
}
if vm.Resolution != want || vmstart.ReadVMDisplay(vm.Dir).AutoResolution != tc.wantAuto {
t.Fatalf("created VM = %+v, want resolution %s and automatic mode %t", vm, want, tc.wantAuto)
}
})
}
}
}
func TestCreateVMWithAutoResolutionRefreshesAfterDiskConversion(t *testing.T) {
a, fixture := newDisplayCtlApp(t, displayCtlFixture{}, false)
source := filepath.Join(a.cfg.DataRoot, "source.raw")
if err := os.WriteFile(source, []byte("raw disk"), 0o600); err != nil {
t.Fatal(err)
}
connectedDisplays := func() []host.DisplayInfo {
converted, err := filepath.Glob(filepath.Join(a.cfg.TempDir(), "import-*.qcow2"))
if err != nil {
t.Fatal(err)
}
if len(converted) == 0 {
return []host.DisplayInfo{{Primary: true, Width: 3840, Height: 2160, ScalePct: 150}}
}
return []host.DisplayInfo{{Primary: true, Width: 3200, Height: 2000, ScalePct: 200}}
}
on := true
opts := reims.CreateOpts{Name: displayFixtureVM, CPUs: 1, SourceMode: "disk", Disk: source, AutoResolution: &on, Borderless: &on}
if err := a.createVMFlow(opts, connectedDisplays); err != nil {
t.Fatal(err)
}
if vm := fixture(); vm.Resolution != "3200x2000" || !vmstart.ReadVMDisplay(vm.Dir).AutoResolution {
t.Fatalf("created VM = %+v, want automatic 3200x2000", vm)
}
}
func TestClonePreservesAutoResolution(t *testing.T) {
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: "stopped", Resolution: "2880x1800"}, false)
source := fixture().Dir
if _, err := vmstart.SaveVMDisplay(source, vmstart.VMDisplayConfig{TargetDisplay: "DISPLAY2", AutoResolution: true}); err != nil {
t.Fatal(err)
}
d := macosdriver.NewReimsMacOSDriver(func() config.Config { return *a.cfg })
if err := d.CloneCoW(t.Context(), displayFixtureVM, displayFixtureClone, io.Discard, io.Discard); err != nil {
t.Fatal(err)
}
if got := vmstart.ReadVMDisplay(fixture().CloneDir); got != (vmstart.VMDisplayConfig{AutoResolution: true}) {
t.Fatalf("cloned display preference = %+v", got)
}
}
-129
View File
@@ -1,143 +1,14 @@
package app
import (
"context"
"errors"
"fmt"
"io"
"path/filepath"
"runtime"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
)
type reviewNetworkControl struct {
extra string
writes int
setErr error
}
func (*reviewNetworkControl) List(context.Context) ([]reims.VMListItem, error) { return nil, nil }
func (*reviewNetworkControl) Show(context.Context, string) (reims.VMDetail, error) {
return reims.VMDetail{}, nil
}
func (*reviewNetworkControl) CommandText(context.Context, string) (string, error) {
return "qemu -netdev user,id=net0 -device virtio-net-pci,netdev=net0,id=net0,mac=02:00:00:00:00:01", nil
}
func (c *reviewNetworkControl) Set(_ context.Context, opts reims.SetOpts, _, _ io.Writer) error {
if c.setErr != nil {
return c.setErr
}
if opts.ExtraArgs != nil {
c.extra = *opts.ExtraArgs
c.writes++
}
return nil
}
func TestLegacyBridgeArgsHaveRemovableOwner(t *testing.T) {
dir := t.TempDir()
detail := reims.VMDetail{Name: "fake-vm", Directory: dir, NetworkMode: "bridge", ExtraArgs: "-cpu host"}
if err := reims.SaveNetworkRecord(dir, reims.NetworkRecord{Mode: "bridge", SocketPath: filepath.Join(dir, "bridge.sock")}); err != nil {
t.Fatal(err)
}
control := &reviewNetworkControl{}
a := &App{}
if err := a.reconcileLegacyBridgeArgs(context.Background(), control, &detail); err != nil {
t.Fatal(err)
}
if !strings.Contains(control.extra, "id=reimsbridge0") {
t.Fatal("隔离客户端未收到桥接参数")
}
ledger, err := plugin.LoadArgLedger(dir)
if err != nil {
t.Fatal(err)
}
if len(ledger.Owners[builtin.IDNpcapBridge]) != 1 {
t.Fatalf("桥接参数已写入,但 Npcap 账本条目数为 %d", len(ledger.Owners[builtin.IDNpcapBridge]))
}
if err := a.reconcileLegacyBridgeArgs(context.Background(), control, &detail); err != nil {
t.Fatal(err)
}
if control.writes != 1 {
t.Fatalf("重复准备写入了 %d 次参数", control.writes)
}
if strings.Count(detail.ExtraArgs, "id=reimsbridge0,") != 1 {
t.Fatal("重复准备产生重复桥接设备")
}
clean := plugin.ReconcileStartIntents(detail.ExtraArgs, ledger, map[string]bool{}, nil)
if clean.ExtraArgs != "-cpu host" {
t.Fatalf("停用后残留桥接参数:%s", clean.ExtraArgs)
}
}
func TestLegacyBridgeArgsStopOnInvalidRecordOrWriteFailure(t *testing.T) {
for _, mode := range []string{"corrupt", "pending", "set failure"} {
t.Run(mode, func(t *testing.T) {
dir := t.TempDir()
detail := reims.VMDetail{Name: "fake-vm", Directory: dir, NetworkMode: "bridge", ExtraArgs: "-cpu host"}
record := reims.NetworkRecord{Mode: "bridge", SocketPath: filepath.Join(dir, "bridge.sock")}
code := "E_NETWORK_CONFIG_SAVE"
control := &reviewNetworkControl{setErr: errors.New("模拟配置写入失败")}
if mode == "corrupt" {
record.Version = 99
code = "E_NETWORK_RECORD_INVALID"
}
if mode == "pending" {
record.Pending = true
code = "E_NETWORK_PACKET_PENDING"
}
if err := reims.SaveNetworkRecord(dir, record); err != nil {
t.Fatal(err)
}
err := (&App{}).reconcileLegacyBridgeArgs(context.Background(), control, &detail)
var coded *i18n.CodedError
if !errors.As(err, &coded) || coded.Code != code {
t.Fatalf("错误 = %v,预期 %s", err, code)
}
ledger, err := plugin.LoadArgLedger(dir)
if err != nil {
t.Fatal(err)
}
if detail.ExtraArgs != "-cpu host" || len(ledger.Owners) != 0 {
t.Fatal("准备失败却更新了参数或归属")
}
})
}
}
func TestLegacyBridgeArgsClearOwnerWhenLeavingBridge(t *testing.T) {
dir := t.TempDir()
detail := reims.VMDetail{Name: "fake-vm", Directory: dir, NetworkMode: "bridge", ExtraArgs: "-cpu host"}
if err := reims.SaveNetworkRecord(dir, reims.NetworkRecord{Mode: "bridge", SocketPath: filepath.Join(dir, "bridge.sock")}); err != nil {
t.Fatal(err)
}
a := &App{}
control := &reviewNetworkControl{}
if err := a.reconcileLegacyBridgeArgs(context.Background(), control, &detail); err != nil {
t.Fatal(err)
}
detail.NetworkMode = "nat"
if err := a.reconcileLegacyBridgeArgs(context.Background(), control, &detail); err != nil {
t.Fatal(err)
}
ledger, err := plugin.LoadArgLedger(dir)
if err != nil {
t.Fatal(err)
}
if detail.ExtraArgs != "-cpu host" || len(ledger.Owners[builtin.IDNpcapBridge]) != 0 {
t.Fatal("离开桥接后仍残留参数或归属")
}
}
func networkLockCount(a *App) int {
count := 0
a.vmNetworkLocks.Range(func(_, _ any) bool { count++; return true })
+2 -2
View File
@@ -219,9 +219,9 @@ func TestPluginFileGrantsExpireAndAreCapped(t *testing.T) {
if _, err := a.issuePluginFileGrant("vendor.panel", path, true); err == nil {
t.Fatal("plugin exceeded its file grant limit")
}
grant := a.pluginFiles[first]
grant := a.hostAPI.pluginFiles[first]
grant.Expires = time.Now().Add(-time.Minute)
a.pluginFiles[first] = grant
a.hostAPI.pluginFiles[first] = grant
if _, err := a.pluginFilePath("vendor.panel", first, true); err == nil {
t.Fatal("expired file grant was accepted")
}
+18 -15
View File
@@ -50,13 +50,14 @@ func (a *App) issuePluginFileGrant(pluginID, path string, write bool) (map[strin
} else if !write {
return nil, err
}
a.mu.Lock()
defer a.mu.Unlock()
h := a.hostAPISvc()
h.filesMu.Lock()
defer h.filesMu.Unlock()
now := time.Now()
count := 0
for key, grant := range a.pluginFiles {
for key, grant := range h.pluginFiles {
if !now.Before(grant.Expires) {
delete(a.pluginFiles, key)
delete(h.pluginFiles, key)
} else if grant.PluginID == pluginID {
count++
}
@@ -64,29 +65,31 @@ func (a *App) issuePluginFileGrant(pluginID, path string, write bool) (map[strin
if count >= maxPluginFileGrants {
return nil, errors.New("too many open file handles for this plugin")
}
if a.pluginFiles == nil {
a.pluginFiles = make(map[string]pluginFileGrant)
if h.pluginFiles == nil {
h.pluginFiles = make(map[string]pluginFileGrant)
}
a.pluginFiles[id] = pluginFileGrant{PluginID: pluginID, Path: clean, Write: write, Expires: now.Add(pluginFileGrantTTL)}
h.pluginFiles[id] = pluginFileGrant{PluginID: pluginID, Path: clean, Write: write, Expires: now.Add(pluginFileGrantTTL)}
return result, nil
}
func (a *App) revokePluginFiles(pluginID string) {
a.mu.Lock()
defer a.mu.Unlock()
for id, grant := range a.pluginFiles {
h := a.hostAPISvc()
h.filesMu.Lock()
defer h.filesMu.Unlock()
for id, grant := range h.pluginFiles {
if grant.PluginID == pluginID {
delete(a.pluginFiles, id)
delete(h.pluginFiles, id)
}
}
}
func (a *App) pluginFilePath(pluginID, id string, write bool) (string, error) {
a.mu.Lock()
defer a.mu.Unlock()
grant, ok := a.pluginFiles[id]
h := a.hostAPISvc()
h.filesMu.Lock()
defer h.filesMu.Unlock()
grant, ok := h.pluginFiles[id]
if ok && !time.Now().Before(grant.Expires) {
delete(a.pluginFiles, id)
delete(h.pluginFiles, id)
ok = false
}
if !ok || grant.PluginID != pluginID || (write && !grant.Write) {
+100 -135
View File
@@ -25,6 +25,7 @@ import (
"github.com/Nwflower/reims-go/internal/macos/guest"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"github.com/Nwflower/reims-go/internal/plugin/market"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/version"
"github.com/Nwflower/reims-go/internal/vmstart"
@@ -70,23 +71,24 @@ func (a *App) initPlugins() {
return
}
var mgr *plugin.Manager
mgr, err := plugin.NewManager(plugin.ManagerOptions{
DataRoot: dataRoot,
HostVersion: version.Version,
SafeMode: safeMode,
RedactFn: host.RedactText,
LocaleFn: a.locale,
var drvRouter *driver.Router
mgr, drvRouter, err := builtin.BootstrapKernel(builtin.KernelBootstrapOptions{
DataRoot: dataRoot,
DataRootFn: func() string {
a.mu.Lock()
defer a.mu.Unlock()
return a.cfg.DataRoot
},
SafeMode: safeMode,
LocaleFn: a.locale,
Logger: func(source, line string) {
a.emitLog(source, line)
},
SidecarDriverFactory: func(contrib plugin.GuestDriverContribution, sup *plugin.SidecarSupervisor) any {
return driver.NewSidecarDriver(contrib, sup)
},
HostHandlers: func(pluginID string) map[string]plugin.RPCRequestHandler {
a.mu.Lock()
current := a.pluginMgr
a.mu.Unlock()
return a.hostHandlers(current, pluginID)
return a.hostAPISvc().Handlers(current, pluginID)
},
OnSettingsChanged: func(pluginID, vmName string) {
a.onPluginSettingsChanged(pluginID, vmName)
@@ -96,23 +98,86 @@ func (a *App) initPlugins() {
// longer release it, so the host lifts what it left down.
a.releaseHeldForPlugin(pluginID)
},
VMInventory: guest.VMInventory(),
Callbacks: builtin.HostCallbacks{
GetConfig: a.runtimeConfig,
Log: func(source, line string) {
a.emitLog(source, line)
},
EnsureGuestTools: func() (*guesttools.Server, int, error) {
srv, port, created, err := a.startGuestToolsServer()
if err == nil && created {
// A fresh server knows no VM tokens: at startup and when the
// plugin is switched back on, re-register configured VMs.
go a.registerVMsWithBridge(context.Background(), srv, port)
}
return srv, port, err
},
StopGuestTools: func() {
a.mu.Lock()
gt := a.guestTools
a.guestTools = nil
a.mu.Unlock()
if gt != nil {
shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
_ = gt.Close(shutCtx)
cancel()
}
},
LoadAndRegisterGuestTools: func(srv *guesttools.Server, port int, dir, name string) (guesttools.VMConfig, error) {
epoch := a.vmDeleteEpoch(name)
// The start hook can receive a directory read before the VM was deleted.
if epoch != 0 {
vms, err := a.listVMsInternal(context.Background())
if err != nil {
return guesttools.VMConfig{}, err
}
if !slices.ContainsFunc(vms, func(vm driver.VMListItem) bool {
return strings.EqualFold(vm.Name, name) && filepath.Clean(vm.Dir) == filepath.Clean(dir)
}) {
return guesttools.VMConfig{}, os.ErrNotExist
}
}
return a.loadAndRegisterNetworkGuestTools(srv, port, dir, name, epoch)
},
OnIMEText: func(target host.IMETarget, text string) {
go a.injectRemoteText(target.VMName, target.VMDir, text)
},
StartColdReboot: func(vmName, qmpAddr string) {
a.watchWin10ColdReboot(vmName, qmpAddr)
},
CancelColdReboot: func(vmName string) {
a.cancelRebootWatcher(vmName)
},
GuestToolsImg: func(vmName string) string {
return a.guestToolsImagePath(vmName)
},
BuildGuestToolsImage: a.buildGuestToolsImage,
OpenAppWindow: a.openAppWindow,
PrepareVMNetwork: a.prepareManagedVMNetwork,
RestorePacketBridges: func(ctx context.Context) func() {
return a.startPacketBridgeRestore(ctx, func(ctx context.Context) {
if a.dataRootUsable() {
a.registerExistingPacketBridges(ctx)
}
})
},
StopPacketBridges: a.closePacketBridges,
OnInstallGuidesChanged: func() {
a.emitStateChanged()
},
SyncInstallGuides: func() {
a.wakePoll()
},
},
RegisterGuest: guest.Register,
})
if err != nil {
a.emitLog("plugin", "Plugin state warning: "+err.Error())
if mgr == nil {
return
}
a.emitLog("plugin", "Could not initialize plugin manager: "+err.Error())
return
}
kindReg := rt.NewKindRegistry()
drvRouter := driver.NewRouter(mgr.Registry(), func() string {
a.mu.Lock()
defer a.mu.Unlock()
return a.cfg.DataRoot
}, guest.VMInventory())
mgr.Registry().SetInUseChecker(drvRouter.PluginInUseChecker())
mgr.Registry().SetBusyChecker(drvRouter.PluginBusyChecker())
// Drivers push the state of the VMs they host; the router merges the table
// into what the drivers return. A spawned VM's exit wakes the poll at once.
@@ -133,92 +198,6 @@ func (a *App) initPlugins() {
a.emitLog("plugin:"+pluginID, title+": "+body)
})
cb := builtin.HostCallbacks{
GetConfig: a.runtimeConfig,
Log: func(source, line string) {
a.emitLog(source, line)
},
EnsureGuestTools: func() (*guesttools.Server, int, error) {
srv, port, created, err := a.startGuestToolsServer()
if err == nil && created {
// A fresh server knows no VM tokens: at startup and when the
// plugin is switched back on, re-register configured VMs.
go a.registerVMsWithBridge(context.Background(), srv, port)
}
return srv, port, err
},
StopGuestTools: func() {
a.mu.Lock()
gt := a.guestTools
a.guestTools = nil
a.mu.Unlock()
if gt != nil {
shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
_ = gt.Close(shutCtx)
cancel()
}
},
LoadAndRegisterGuestTools: func(srv *guesttools.Server, port int, dir, name string) (guesttools.VMConfig, error) {
epoch := a.vmDeleteEpoch(name)
// The start hook can receive a directory read before the VM was deleted.
if epoch != 0 {
vms, err := a.listVMsInternal(context.Background())
if err != nil {
return guesttools.VMConfig{}, err
}
if !slices.ContainsFunc(vms, func(vm driver.VMListItem) bool {
return strings.EqualFold(vm.Name, name) && filepath.Clean(vm.Dir) == filepath.Clean(dir)
}) {
return guesttools.VMConfig{}, os.ErrNotExist
}
}
return a.loadAndRegisterNetworkGuestTools(srv, port, dir, name, epoch)
},
OnIMEText: func(target host.IMETarget, text string) {
go a.injectRemoteText(target.VMName, target.VMDir, text)
},
StartColdReboot: func(vmName, qmpAddr string) {
a.watchWin10ColdReboot(vmName, qmpAddr)
},
CancelColdReboot: func(vmName string) {
a.cancelRebootWatcher(vmName)
},
GuestToolsImg: func(vmName string) string {
return a.guestToolsImagePath(vmName)
},
BuildGuestToolsImage: a.buildGuestToolsImage,
OpenAppWindow: a.openAppWindow,
PrepareVMNetwork: a.prepareManagedVMNetwork,
RestorePacketBridges: func(ctx context.Context) func() {
return a.startPacketBridgeRestore(ctx, func(ctx context.Context) {
if a.dataRootUsable() {
a.registerExistingPacketBridges(ctx)
}
})
},
StopPacketBridges: a.closePacketBridges,
OnInstallGuidesChanged: func() {
a.emitStateChanged()
},
SyncInstallGuides: func() {
a.wakePoll()
},
GetSetting: func(pluginID, vmName, key string) (any, bool) {
v, ok := mgr.GetSettings(pluginID, vmName, false)[key]
return v, ok
},
}
if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
a.emitLog("plugin", "Builtin extension register error: "+err.Error())
}
if err := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
a.emitLog("plugin", "macOS guest plugin register error: "+err.Error())
}
if err := mgr.LoadExternal(); err != nil {
a.emitLog("plugin", "External plugin load warning: "+err.Error())
}
// Sync runtime kinds, input filters, clipboard policies, and locales whenever registry state changes.
mgr.Registry().OnChange(func() {
active := map[string]bool{}
@@ -228,27 +207,19 @@ func (a *App) initPlugins() {
stateTable.PruneDrivers(active)
a.syncRuntimeKinds(kindReg, mgr.Registry())
a.syncInputFilters()
a.syncKeymapRules()
a.syncClipboardPolicies()
a.syncLocales()
a.wakePoll()
a.emitStateChanged()
})
a.keymapMu.Lock()
a.mu.Lock()
fallback := a.fallbackInputSvc
a.fallbackInputSvc = nil
a.pluginMgr = mgr
a.driverRouter = drvRouter
a.vmStateTable = stateTable
a.lifecycleSvc = vmlifecycle.New(mgr.Registry(), drvRouter, a.startHookPayload)
a.runtimeKinds = kindReg
a.mu.Unlock()
if fallback != nil {
fallback.Close()
}
a.keymapMu.Unlock()
fetch.SetDefaultDownloader(a.activeDownloader)
@@ -258,7 +229,6 @@ func (a *App) initPlugins() {
}
mgr.MarkBootComplete()
a.syncInputFilters()
a.syncKeymapRules()
a.syncClipboardPolicies()
a.syncLocales()
a.startPluginControlServer()
@@ -296,7 +266,7 @@ func (a *App) shutdownPlugins() {
}
}
func (a *App) getPluginMarket() *plugin.MarketClient {
func (a *App) getPluginMarket() *market.MarketClient {
a.mu.Lock()
defer a.mu.Unlock()
if a.needsSetup {
@@ -304,7 +274,7 @@ func (a *App) getPluginMarket() *plugin.MarketClient {
// only the default suggestion), so nothing may be cached or
// downloaded into it. A throwaway client keeps the index in memory;
// the first call after setup builds the real one.
return plugin.NewMarketClient(plugin.MarketClientOptions{HostVersion: version.Version})
return market.NewMarketClient(market.MarketClientOptions{HostVersion: version.Version})
}
if a.pluginMarket != nil {
return a.pluginMarket
@@ -313,7 +283,7 @@ func (a *App) getPluginMarket() *plugin.MarketClient {
if a.cfg != nil {
dataRoot = a.cfg.DataRoot
}
a.pluginMarket = plugin.NewMarketClient(plugin.MarketClientOptions{
a.pluginMarket = market.NewMarketClient(market.MarketClientOptions{
Layout: plugin.NewPluginsLayout(dataRoot),
HostVersion: version.Version,
})
@@ -407,15 +377,10 @@ func (a *App) getInputService() *host.InputService {
return nil
}
mgr := a.pluginMgr
if mgr == nil {
if a.fallbackInputSvc == nil {
a.fallbackInputSvc = host.NewInputService(nil)
}
svc := a.fallbackInputSvc
a.mu.Unlock()
return svc
}
a.mu.Unlock()
if mgr == nil {
return nil
}
raw, ok := mgr.Registry().LookupService(builtin.ServiceHostInput)
if !ok {
return nil
@@ -984,7 +949,7 @@ func (a *App) ScanInstalledPlugin(pluginID string) (plugin.ScanReport, error) {
// BrowsePluginMarket lazily queries the remote/cached/fallback plugin market
// index (never called at app startup, §8.1, §9).
func (a *App) BrowsePluginMarket(query, kind string, includeAlpha, forceRefresh bool) plugin.MarketBrowseResult {
func (a *App) BrowsePluginMarket(query, kind string, includeAlpha, forceRefresh bool) market.MarketBrowseResult {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
@@ -992,7 +957,7 @@ func (a *App) BrowsePluginMarket(query, kind string, includeAlpha, forceRefresh
if mgr != nil {
installed = mgr.Registry().List()
}
return a.getPluginMarket().Browse(context.Background(), installed, plugin.MarketBrowseOptions{
return a.getPluginMarket().Browse(context.Background(), installed, market.MarketBrowseOptions{
Query: query,
Kind: kind,
IncludeAlpha: includeAlpha,
@@ -1003,7 +968,7 @@ func (a *App) BrowsePluginMarket(query, kind string, includeAlpha, forceRefresh
// PeekPluginMarket returns the market from memory, disk cache or the embedded
// fallback with no network I/O, so the page can paint before
// BrowsePluginMarket revalidates.
func (a *App) PeekPluginMarket(query, kind string) plugin.MarketBrowseResult {
func (a *App) PeekPluginMarket(query, kind string) market.MarketBrowseResult {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
@@ -1011,7 +976,7 @@ func (a *App) PeekPluginMarket(query, kind string) plugin.MarketBrowseResult {
if mgr != nil {
installed = mgr.Registry().List()
}
return a.getPluginMarket().Peek(installed, plugin.MarketBrowseOptions{Query: query, Kind: kind, IncludeAlpha: true})
return a.getPluginMarket().Peek(installed, market.MarketBrowseOptions{Query: query, Kind: kind, IncludeAlpha: true})
}
// SuggestLanguagePack looks up the market once for a language pack matching
@@ -1019,7 +984,7 @@ func (a *App) PeekPluginMarket(query, kind string) plugin.MarketBrowseResult {
// request made without the user opening the market (§8.1), and returns nil
// when a built-in language already covers the OS language, the market is
// unreachable or turned off, or nothing matches.
func (a *App) SuggestLanguagePack() *plugin.MarketCatalogItem {
func (a *App) SuggestLanguagePack() *market.MarketCatalogItem {
tag := i18n.DetectOSLocaleTag()
if builtinCoversLocale(string(tag)) {
return nil
@@ -1080,13 +1045,13 @@ func (a *App) installMarketPlugin(pluginID, ver string, includeAlpha bool) (*plu
}
var (
progMu sync.Mutex
phase = plugin.MarketPhaseDownload
phase = market.MarketPhaseDownload
lastEmit time.Time
)
emit := func(p MarketInstallProgress) {
a.emit("reims:plugin-install", p)
}
info, err := a.getPluginMarket().InstallFromMarket(context.Background(), mgr, pluginID, plugin.MarketInstallOptions{
info, err := a.getPluginMarket().InstallFromMarket(context.Background(), mgr, pluginID, market.MarketInstallOptions{
Version: ver,
IncludeAlpha: includeAlpha,
OnPhase: func(ph string) {
+2 -2
View File
@@ -62,10 +62,10 @@ func (a *App) secretHostHandlers(mgr *plugin.Manager, pluginID string) map[strin
return value, err
}
return map[string]plugin.RPCRequestHandler{
"host/secret.materialize": a.hostMethod(mgr, pluginID, "host/secret.materialize", func(_ context.Context, raw json.RawMessage) (any, error) {
"host/secret.materialize": a.hostAPISvc().hostMethod(mgr, pluginID, "host/secret.materialize", func(_ context.Context, raw json.RawMessage) (any, error) {
return a.materializeSecret(mgr, broker, source, pluginID, raw)
}),
"host/secret.discard": a.hostMethod(mgr, pluginID, "host/secret.discard", func(_ context.Context, raw json.RawMessage) (any, error) {
"host/secret.discard": a.hostAPISvc().hostMethod(mgr, pluginID, "host/secret.discard", func(_ context.Context, raw json.RawMessage) (any, error) {
return a.discardSecret(mgr, broker, pluginID, raw)
}),
}
-4
View File
@@ -109,9 +109,6 @@ func (a *App) ResumeVM(driverID, name string) error {
unicodeInput := hasRuntime && active.Manifest.HasCapability("win32-unicode-input")
windowDrop := hasRuntime && active.Manifest.HasCapability("window-file-drop")
extraEnv, newRegistration, newRegGen = a.registerResumeGuestTools(vm, epoch, unicodeInput, windowDrop)
if unicodeInput && len(extraEnv) > 0 {
a.syncKeymapRules()
}
}
startAt := time.Now()
@@ -199,7 +196,6 @@ func (a *App) registerResumeGuestTools(vm driver.VMInfo, epoch uint64, unicodeIn
}
var env []string
if unicodeInput {
srv.SetKeymapCarrier(ref.Name, false)
env = append(env,
fmt.Sprintf("REIMS_GO_INPUT_URL=http://127.0.0.1:%d/v1/host-text", port),
"REIMS_GO_INPUT_TOKEN="+cfg.Token,
+5 -2
View File
@@ -12,6 +12,7 @@ import (
"errors"
"fmt"
"image/png"
"log"
"os"
"path/filepath"
"strings"
@@ -281,8 +282,10 @@ func (a *App) captureThumb(driverID, name, path string) (VMThumbnail, bool) {
if err != nil {
return VMThumbnail{}, false
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err == nil {
_ = atomicfile.Write(path, jpg, 0o644)
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
log.Printf("[thumb] create cache dir failed (%s): %v", filepath.Dir(path), err)
} else if err := atomicfile.Write(path, jpg, 0o644); err != nil {
log.Printf("[thumb] write cache failed (%s): %v", path, err)
}
return VMThumbnail{
DataURL: "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(jpg),
+9 -15
View File
@@ -117,7 +117,15 @@ func (p *vmPoller) tick(ctx context.Context) {
if ib != nil {
ib.SetTargets(imeTargets(vms))
}
a.syncKeymapRules()
if svc := a.getInputService(); svc != nil {
var targets []host.IMETarget
for _, vm := range vms {
if pid := vm.RunningPID(); pid > 0 {
targets = append(targets, host.IMETarget{VMName: vm.Name, VMDir: vm.Dir, PID: uint32(pid)})
}
}
svc.SetTargets(targets)
}
a.syncFullscreenHotkeyTargets()
if tm != nil {
tm.UpdateTooltip(trayTooltip(loc, vms))
@@ -410,20 +418,6 @@ func (a *App) polledVMs(ctx context.Context) ([]driver.VMListItem, error) {
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 {
+95
View File
@@ -0,0 +1,95 @@
package archtest
import (
"go/ast"
"go/token"
"testing"
)
// TestNoSilentRecover forbids bare `recover()` and `_ = recover()` statements
// in production code so panics are never silently swallowed without logging or
// surfacing an error.
func TestNoSilentRecover(t *testing.T) {
for _, s := range sources(t) {
if s.isTest() {
continue
}
ast.Inspect(s.file, func(n ast.Node) bool {
switch stmt := n.(type) {
case *ast.ExprStmt:
if isRecoverCall(stmt.X) {
pos := fileSet.Position(stmt.Pos())
t.Errorf("%s:%d: bare recover() silently swallows panics; bind and log/report it", s.rel, pos.Line)
}
case *ast.AssignStmt:
if len(stmt.Rhs) == 1 && isRecoverCall(stmt.Rhs[0]) && allBlankIdents(stmt.Lhs) {
pos := fileSet.Position(stmt.Pos())
t.Errorf("%s:%d: `_ = recover()` silently swallows panics; bind and log/report it", s.rel, pos.Line)
}
}
return true
})
}
}
func isRecoverCall(expr ast.Expr) bool {
call, ok := expr.(*ast.CallExpr)
if !ok {
return false
}
ident, ok := call.Fun.(*ast.Ident)
return ok && ident.Name == "recover"
}
func allBlankIdents(exprs []ast.Expr) bool {
if len(exprs) == 0 {
return false
}
for _, e := range exprs {
id, ok := e.(*ast.Ident)
if !ok || id.Name != "_" {
return false
}
}
return true
}
// TestNoSilentFatalPersistenceDiscards guards against `_ = <call>` on critical
// persistence/rollback primitives where dropping an error silently corrupts
// on-disk state.
func TestNoSilentFatalPersistenceDiscards(t *testing.T) {
guarded := map[string]bool{
"atomicfile.Write": true,
"atomicfile.WriteJSON": true,
"plugin.SaveArgLedger": true,
}
for _, s := range sources(t) {
if s.isTest() {
continue
}
ast.Inspect(s.file, func(n ast.Node) bool {
assign, ok := n.(*ast.AssignStmt)
if !ok || assign.Tok != token.ASSIGN || len(assign.Rhs) != 1 || !allBlankIdents(assign.Lhs) {
return true
}
call, ok := assign.Rhs[0].(*ast.CallExpr)
if !ok {
return true
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return true
}
pkg, ok := sel.X.(*ast.Ident)
if !ok {
return true
}
key := pkg.Name + "." + sel.Sel.Name
if guarded[key] {
pos := fileSet.Position(assign.Pos())
t.Errorf("%s:%d: discarding error from %s with `_ =` is forbidden; handle or log the error", s.rel, pos.Line, key)
}
return true
})
}
}
+1 -1
View File
@@ -24,7 +24,7 @@ var renameOwners = map[string]bool{
"internal/macos/reims/suspend_fileops_other.go": true, // state and metadata commit together
"internal/macos/reims/suspend_fileops_windows.go": true, // state and metadata commit together
"internal/plugin/broker.go": true, // log rotation
"internal/plugin/pack.go": true, // archive
"internal/plugin/market/pack.go": true, // archive
"internal/plugin/package_rename_other.go": true, // plugin directory
"internal/plugin/package_rename_windows.go": true, // plugin directory
"internal/runtime/runtime.go": true, // runtime directory
-1
View File
@@ -20,7 +20,6 @@ var macosImporters = map[string]macosImporter{
"internal/app": {test: true, why: "GUI composition root tests may exercise native macOS flows"},
"internal/datamigrate": {src: true, test: true, why: "data layout 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"},
}
// macosSourceFiles is the file-scoped native macOS boundary. plugins_flow.go
+80 -8
View File
@@ -305,8 +305,10 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
}
return err
}
if err := activateRuntime(context.Background(), cfg, loc, inst.Commit); err != nil {
return err
if inst.Kind != rt.StambhaKind {
if err := activateRuntime(context.Background(), cfg, loc, inst.Commit); err != nil {
return err
}
}
fmt.Println(i18n.T(loc, "runtime.installed", inst.Commit, inst.Dir))
return nil
@@ -409,11 +411,16 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
}
return startVM(ctx, cfg, driverID, name, viaWindow)
case "stop":
driverID, name, err := parseVMTarget(args)
if err != nil {
fs := flag.NewFlagSet("vm stop", flag.ContinueOnError)
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
force := fs.Bool("force", false, "Force stop without waiting for guest shutdown")
if err := fs.Parse(args[1:]); err != nil {
return err
}
return stopVM(ctx, cfg, driverID, name)
if fs.NArg() != 1 {
return errors.New("usage: reims-go vm stop [--driver <id>] [--force] <name>")
}
return stopVM(ctx, cfg, *driverID, fs.Arg(0), *force)
case "suspend":
driverID, name, err := parseVMTarget(args)
if err != nil {
@@ -511,6 +518,7 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
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")
stambhaFlags := registerStambhaVMFlags(fs, disk)
if err := fs.Parse(args); err != nil {
return err
}
@@ -518,6 +526,10 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
return fmt.Errorf("usage: reims-go vm create [flags] <name>")
}
name := fs.Arg(0)
stambhaOpts := collectStambhaVMFlags(fs, stambhaFlags)
if len(stambhaOpts) > 0 && *driverID != driver.BuiltinStambhaDriverID {
return fmt.Errorf("Stambha VM flags require --driver %s", driver.BuiltinStambhaDriverID)
}
// 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)
@@ -529,8 +541,11 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
if err != nil {
return err
}
if strings.TrimSpace(*disk) != "" || strings.TrimSpace(*diskMode) != "" || strings.TrimSpace(*diskCache) != "" {
return fmt.Errorf("--disk, --disk-mode, and --disk-cache are only supported by the %s driver", driver.BuiltinReimsMacOSDriverID)
if strings.TrimSpace(*diskMode) != "" || strings.TrimSpace(*diskCache) != "" {
return fmt.Errorf("--disk-mode and --disk-cache are only supported by the %s driver", driver.BuiltinReimsMacOSDriverID)
}
if drv.ID() != driver.BuiltinStambhaDriverID && strings.TrimSpace(*disk) != "" {
return fmt.Errorf("--disk is not supported by the %s driver", drv.ID())
}
req := driver.CreateRequest{
DriverID: drv.ID(),
@@ -542,6 +557,14 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
"disk_size": *diskSize,
},
}
if drv.ID() == driver.BuiltinStambhaDriverID {
delete(req.Options, "disk_size")
req.Options["gpu"] = *gpu
req.Options["raw_disk"] = *disk
for key, value := range stambhaOpts {
req.Options[key] = value
}
}
if issues := drv.ValidateCreate(ctx, req); len(issues) > 0 {
return fmt.Errorf("%s", issues[0].Message)
}
@@ -569,13 +592,17 @@ func vmSet(ctx context.Context, cfg *config.Config, args []string) error {
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)")
stambhaFlags := registerStambhaVMFlags(fs, nil)
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() < 1 {
return fmt.Errorf("usage: reims-go vm set [--driver <id>] [flags] <name>")
}
changes := map[string]any{}
changes := collectStambhaVMFlags(fs, stambhaFlags)
if len(changes) > 0 && *driverID != driver.BuiltinStambhaDriverID {
return fmt.Errorf("Stambha VM flags require --driver %s", driver.BuiltinStambhaDriverID)
}
if *cpus != 0 {
changes["cpus"] = *cpus
}
@@ -605,6 +632,51 @@ func vmSet(ctx context.Context, cfg *config.Config, args []string) error {
return setVM(ctx, cfg, *driverID, fs.Arg(0), changes)
}
type stambhaVMFlag struct {
option string
value func() any
}
func registerStambhaVMFlags(fs *flag.FlagSet, disk *string) map[string]stambhaVMFlag {
boot := fs.String("boot-volume", "", "Stambha boot folder containing EFI/stela/stela.cfg")
usb := fs.String("usb-image", "", "Stambha RAW boot image")
bus := fs.String("media-bus", "", "Stambha RAW boot image bus (usb or nvme)")
sharedDisk := disk != nil
if !sharedDisk {
disk = fs.String("disk", "", "Stambha writable RAW or QCOW2 virtual disk")
}
fs.StringVar(disk, "raw-disk", "", "Alias for --disk")
accelerator := fs.String("accelerator", "", "Stambha accelerator (whpx or tcg)")
hosted := fs.Bool("hosted-gpu", true, "Use Reims vGPU for a Stambha VM")
headless := fs.Bool("headless", false, "Run Stambha without a display window")
args := fs.String("stela-args", "", "Additional Stambha options for a boot folder")
flags := map[string]stambhaVMFlag{
"boot-volume": {"boot_volume", func() any { return *boot }},
"usb-image": {"usb_image", func() any { return *usb }},
"media-bus": {"media_bus", func() any { return *bus }},
"disk": {"raw_disk", func() any { return *disk }},
"raw-disk": {"raw_disk", func() any { return *disk }},
"accelerator": {"accelerator", func() any { return *accelerator }},
"hosted-gpu": {"hosted_gpu", func() any { return *hosted }},
"headless": {"display", func() any { return !*headless }},
"stela-args": {"stela_args", func() any { return *args }},
}
if sharedDisk {
delete(flags, "disk")
}
return flags
}
func collectStambhaVMFlags(fs *flag.FlagSet, declared map[string]stambhaVMFlag) map[string]any {
options := make(map[string]any)
fs.Visit(func(f *flag.Flag) {
if spec, ok := declared[f.Name]; ok {
options[spec.option] = spec.value()
}
})
return options
}
func printJSON(v any) error {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
+25 -44
View File
@@ -10,11 +10,11 @@ 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/i18n"
"github.com/Nwflower/reims-go/internal/macos/guest"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"github.com/Nwflower/reims-go/internal/plugin/market"
"github.com/Nwflower/reims-go/internal/version"
)
@@ -22,57 +22,38 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, *
if err := guest.MigrateFiles(cfg.DataRoot); err != nil {
return nil, nil, err
}
mgr, err := plugin.NewManager(plugin.ManagerOptions{
DataRoot: cfg.DataRoot,
HostVersion: version.Version,
SafeMode: safeMode,
RedactFn: host.RedactText,
logf := func(source, line string) {
fmt.Fprintf(os.Stderr, "[%s] %s\n", source, line)
}
mgr, router, err := builtin.BootstrapKernel(builtin.KernelBootstrapOptions{
DataRoot: cfg.DataRoot,
SafeMode: safeMode,
LocaleFn: func() i18n.Locale {
return i18n.EffectiveLocale(cfg.Locale)
},
Logger: func(source, line string) {
fmt.Fprintf(os.Stderr, "[%s] %s\n", source, line)
},
SidecarDriverFactory: func(contrib plugin.GuestDriverContribution, sup *plugin.SidecarSupervisor) any {
return driver.NewSidecarDriver(contrib, sup)
Logger: logf,
VMInventory: guest.VMInventory(),
Callbacks: builtin.HostCallbacks{
GetConfig: func() config.Config { return *cfg },
PrepareVMNetwork: func(ctx context.Context, name string, _ bool) (func(), error) {
return nil, checkDirectMacOSNetwork(ctx, cfg, name)
},
Log: logf,
},
RegisterGuest: guest.Register,
StrictRegister: true,
})
if err != nil {
return nil, nil, err
}
cb := builtin.HostCallbacks{
GetConfig: func() config.Config { return *cfg },
PrepareVMNetwork: func(ctx context.Context, name string, _ bool) (func(), error) {
return nil, checkDirectMacOSNetwork(ctx, cfg, name)
},
Log: func(source, line string) {
fmt.Fprintf(os.Stderr, "[%s] %s\n", source, line)
},
GetSetting: func(pluginID, vmName, key string) (any, bool) {
value, ok := mgr.GetSettings(pluginID, vmName, false)[key]
return value, ok
},
}
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 {
mgr.Close()
return nil, nil, err
}
if err := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
mgr.Close()
return nil, nil, err
}
_ = mgr.LoadExternal()
mgr.Registry().Reconcile(context.Background())
mgr.MarkBootComplete()
return mgr, router, nil
}
func openCLIMarketClient(cfg *config.Config) *plugin.MarketClient {
return plugin.NewMarketClient(plugin.MarketClientOptions{
func openCLIMarketClient(cfg *config.Config) *market.MarketClient {
return market.NewMarketClient(market.MarketClientOptions{
Layout: plugin.NewPluginsLayout(cfg.DataRoot),
HostVersion: version.Version,
})
@@ -133,7 +114,7 @@ func pluginSearch(ctx context.Context, cfg *config.Config, loc i18n.Locale, args
defer mgr.Close()
mc := openCLIMarketClient(cfg)
query := strings.TrimSpace(strings.Join(fs.Args(), " "))
res := mc.Browse(ctx, mgr.Registry().List(), plugin.MarketBrowseOptions{
res := mc.Browse(ctx, mgr.Registry().List(), market.MarketBrowseOptions{
Query: query,
Kind: *kind,
IncludeAlpha: *includeAlpha,
@@ -239,7 +220,7 @@ func pluginInstall(ctx context.Context, cfg *config.Config, loc i18n.Locale, arg
info, err = mgr.InstallLocalArchive(ctx, target, plugin.PackageInstallOptions{})
} else {
mc := openCLIMarketClient(cfg)
info, err = mc.InstallFromMarket(ctx, mgr, target, plugin.MarketInstallOptions{
info, err = mc.InstallFromMarket(ctx, mgr, target, market.MarketInstallOptions{
IncludeAlpha: *includeAlpha,
ForceRefresh: *refresh,
})
@@ -269,7 +250,7 @@ func pluginUpdate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args
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{
info, uErr := mc.InstallFromMarket(ctx, mgr, id, market.MarketInstallOptions{
IncludeAlpha: *includeAlpha,
ForceRefresh: *refresh,
})
@@ -288,7 +269,7 @@ func pluginUpdate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args
return nil
}
for _, up := range updates {
info, uErr := mc.InstallFromMarket(ctx, mgr, up.Entry.ID, plugin.MarketInstallOptions{
info, uErr := mc.InstallFromMarket(ctx, mgr, up.Entry.ID, market.MarketInstallOptions{
IncludeAlpha: *includeAlpha,
ForceRefresh: false,
})
@@ -316,7 +297,7 @@ func pluginPack(loc i18n.Locale, args []string) error {
if err != nil {
return err
}
packOpts := plugin.PackOptions{
packOpts := market.PackOptions{
HostVersion: version.Version,
Contract: contract,
OutputPath: *outPath,
@@ -328,7 +309,7 @@ func pluginPack(loc i18n.Locale, args []string) error {
}
packOpts.SignKey = pk
}
res, pErr := plugin.PackDirectory(fs.Arg(0), packOpts)
res, pErr := market.PackDirectory(fs.Arg(0), packOpts)
if pErr != nil {
if res.Report.HardBlocked && !*asJSON {
fmt.Fprintln(os.Stderr, res.Report.SummaryText(string(loc)))
+59
View File
@@ -0,0 +1,59 @@
package cli
import (
"context"
"encoding/json"
"os"
"path/filepath"
"runtime"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
)
func TestStambhaCLIUsesPreviewMediaWithoutAnIntelRuntime(t *testing.T) {
if runtime.GOOS != "windows" || runtime.GOARCH != "amd64" {
t.Skip("the built-in Stambha driver runs on Windows x86-64")
}
dir := t.TempDir()
cfg := &config.Config{DataRoot: filepath.Join(dir, "data-root")}
boot := filepath.Join(dir, "boot")
bootConfig := filepath.Join(boot, "EFI", "stela", "stela.cfg")
if err := os.MkdirAll(filepath.Dir(bootConfig), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(bootConfig, []byte("--system\n"), 0o644); err != nil {
t.Fatal(err)
}
disk := filepath.Join(dir, "system.qcow2")
if err := os.WriteFile(disk, []byte("fixture"), 0o644); err != nil {
t.Fatal(err)
}
ctx := context.Background()
args := []string{"--driver", driver.BuiltinStambhaDriverID, "--boot-volume", boot, "--disk", disk, "arm"}
if err := vmCreate(ctx, cfg, i18n.Detect(), args, false); err != nil {
t.Fatal(err)
}
args = []string{"--driver", driver.BuiltinStambhaDriverID, "--hosted-gpu=false", "--headless", "arm"}
if err := vmSet(ctx, cfg, args); err != nil {
t.Fatal(err)
}
raw, err := os.ReadFile(filepath.Join(cfg.XDGDataDir(), "stambha", "vms", "arm", "stambha.json"))
if err != nil {
t.Fatal(err)
}
var profile struct {
Disk string `json:"raw_disk"`
Display bool `json:"display"`
HostedGPU bool `json:"hosted_gpu"`
Accelerator string `json:"accelerator"`
}
if err := json.Unmarshal(raw, &profile); err != nil {
t.Fatal(err)
}
if profile.Disk != disk || profile.Display || profile.HostedGPU || profile.Accelerator != "whpx" {
t.Fatalf("unexpected preview profile %+v", profile)
}
}
+4 -3
View File
@@ -15,6 +15,7 @@ import (
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/vmstart"
)
// startHandoffTimeout bounds how long `vm start` waits for the window to
@@ -52,7 +53,7 @@ func startVM(ctx context.Context, cfg *config.Config, driverID, name string, via
if err := requireDirectNetwork(vm); err != nil {
return err
}
_, err = svc.Start(ctx, vm.Ref(), os.Stdout, os.Stderr)
_, err = svc.Start(vmstart.WithPrimaryDisplayOnly(ctx), vm.Ref(), os.Stdout, os.Stderr)
return err
}
@@ -102,13 +103,13 @@ func compactVM(ctx context.Context, cfg *config.Config, driverID, name string) (
return svc.CompactDisk(ctx, driver.VMRef{DriverID: driverID, Name: name}, os.Stdout, os.Stderr)
}
func stopVM(ctx context.Context, cfg *config.Config, driverID, name string) error {
func stopVM(ctx context.Context, cfg *config.Config, driverID, name string, force bool) error {
svc, closeService, err := openCLILifecycle(cfg)
if err != nil {
return err
}
defer closeService()
return svc.Stop(ctx, driver.VMRef{DriverID: driverID, Name: name}, false, os.Stdout, os.Stderr)
return svc.Stop(ctx, driver.VMRef{DriverID: driverID, Name: name}, force, os.Stdout, os.Stderr)
}
func startInWindow(ctx context.Context, cfg *config.Config, driverID, name string) error {
+3 -1
View File
@@ -99,7 +99,9 @@ func run(dataRoot, appVersion string, steps []Step, current int, now func() time
}
if err := s.Run(dataRoot); err != nil {
if res.To > res.From {
_ = writeStamp(dataRoot, Stamp{DataVersion: res.To, WrittenBy: appVersion, UpdatedAt: now()})
if serr := writeStamp(dataRoot, Stamp{DataVersion: res.To, WrittenBy: appVersion, UpdatedAt: now()}); serr != nil {
return res, fmt.Errorf("data migration %q (to v%d): %w (also failed to persist partial stamp v%d: %v)", s.Name, s.To, err, res.To, serr)
}
}
return res, fmt.Errorf("data migration %q (to v%d): %w", s.Name, s.To, err)
}
+27 -1
View File
@@ -9,6 +9,7 @@ import (
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
@@ -141,6 +142,28 @@ func statePath(destPath string) string {
return filepath.Join(filepath.Dir(destPath), "."+filepath.Base(destPath)+".reims-dl.json")
}
// DiscardPartial removes the checkpoint before deleting the payload it tracks.
func DiscardPartial(destPath string) error {
for _, path := range []string{statePath(destPath), destPath} {
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("discard download partial: %w", err)
}
}
return nil
}
// PrepareHTTPResume removes a parallel partial before a sequential client
// treats the file's length as a contiguous download offset.
func PrepareHTTPResume(destPath string) error {
if _, err := os.Stat(statePath(destPath)); err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil
}
return fmt.Errorf("check download checkpoint: %w", err)
}
return DiscardPartial(destPath)
}
func loadResumeState(destPath, rawURL string, destOffset, totalSize int64, chunkCount int) []bool {
raw, err := os.ReadFile(statePath(destPath))
if err != nil {
@@ -166,9 +189,12 @@ func saveResumeState(destPath, rawURL string, destOffset, totalSize int64, done
}
raw, err := json.Marshal(st)
if err != nil {
log.Printf("[downloader] marshal resume state failed (%s): %v", destPath, err)
return
}
_ = atomicfile.Write(statePath(destPath), raw, 0o644)
if err := atomicfile.Write(statePath(destPath), raw, 0o644); err != nil {
log.Printf("[downloader] save resume state failed (%s): %v", destPath, err)
}
}
// Download fetches req.URL into req.DestPath (at req.DestOffset) using concurrent
+11
View File
@@ -12,6 +12,7 @@ import (
"strings"
"time"
"github.com/Nwflower/reims-go/internal/atomicfile"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/plugin"
)
@@ -19,6 +20,8 @@ import (
const (
// BuiltinReimsMacOSDriverID is the default driver for all unmarked/existing VMs.
BuiltinReimsMacOSDriverID = "builtin.driver.reims-macos"
// BuiltinStambhaDriverID is the ARM64 macOS driver's persisted ID.
BuiltinStambhaDriverID = "builtin.driver.stambha"
// OwnerMarkerFile persists the owning driver ID inside a VM directory.
OwnerMarkerFile = ".reims-go-driver"
)
@@ -324,6 +327,14 @@ func WriteOwnerDriver(vmDir, driverID string) error {
return os.WriteFile(filepath.Join(vmDir, OwnerMarkerFile), []byte(strings.TrimSpace(driverID)+"\n"), 0o644)
}
// WriteVMRecord atomically replaces a driver's local JSON record in its VM directory.
func WriteVMRecord(vmDir, name string, value any) error {
if !filepath.IsLocal(name) || filepath.Base(name) != name || name == "." {
return fmt.Errorf("invalid VM record name %q", name)
}
return atomicfile.WriteJSON(filepath.Join(vmDir, name), value, 0o600)
}
// HostedReportMaxAge is how long a driver-pushed state counts as fresh; past
// it the host asks the driver with `driver/show` while listing.
const HostedReportMaxAge = 15 * time.Second
+35 -9
View File
@@ -8,8 +8,10 @@ import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
@@ -146,7 +148,8 @@ func resumeWithOptions(ctx context.Context, client *http.Client, url, final stri
}
part := final + ".part"
// Try the active downloader plugin first unless bypassed for security-sensitive paths.
// Try the active downloader first unless this transfer requires the
// caller's HTTP client (for example, plugin market downloads).
if !opts.BypassDownloader {
if prov := activeDownloader(); prov != nil {
err := prov.Download(ctx, downloader.Request{
@@ -158,23 +161,46 @@ func resumeWithOptions(ctx context.Context, client *http.Client, url, final stri
}, func(p downloader.Progress) {
onProgress(p.Done, p.Total)
})
if ctx.Err() != nil {
return "", ctx.Err()
}
if err == nil {
if got, herr := FileSHA256(part); herr == nil && strings.EqualFold(got, want) {
if rerr := os.Rename(part, final); rerr != nil {
return "", rerr
got, hashErr := FileSHA256(part)
switch {
case hashErr != nil:
err = hashErr
case !strings.EqualFold(got, want):
err = fmt.Errorf("SHA256 mismatch (got %s, want %s)", got, want)
default:
if err := os.Rename(part, final); err != nil {
return "", err
}
return final, nil
}
}
if ctx.Err() != nil {
return "", ctx.Err()
// A parallel partial can contain holes. Discard its checkpoint
// together with the file before the HTTP client starts over.
providerErr := fmt.Errorf("download %s (%s): %w", name, prov.ID(), err)
if err := downloader.DiscardPartial(part); err != nil {
return "", errors.Join(providerErr, err)
}
// Clean up any partial multi-range file before single-stream fallback so
// sequential append doesn't concatenate onto sparse holes.
_ = os.Remove(part)
log.Printf("[fetch] downloader %s failed for %s; retrying with the HTTP client", prov.ID(), name)
path, err := resumeHTTP(ctx, client, url, final, size, want, onProgress, opts)
if err != nil {
return "", errors.Join(providerErr, err)
}
return path, nil
}
}
return resumeHTTP(ctx, client, url, final, size, want, onProgress, opts)
}
func resumeHTTP(ctx context.Context, client *http.Client, url, final string, size int64, want string, onProgress Progress, opts ResumeOptions) (string, error) {
name := filepath.Base(final)
part := final + ".part"
if err := downloader.PrepareHTTPResume(part); err != nil {
return "", err
}
for attempt := 0; ; attempt++ {
var have int64
if st, err := os.Stat(part); err == nil {
+75 -1
View File
@@ -4,6 +4,7 @@ import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"net/http"
"net/http/httptest"
@@ -101,15 +102,88 @@ var timeZero = time.Time{}
type spyDownloader struct {
called atomic.Int32
run func(context.Context, downloader.Request) error
}
func (s *spyDownloader) ID() string { return "test.spy" }
func (s *spyDownloader) Download(_ context.Context, _ downloader.Request, _ func(downloader.Progress)) error {
func (s *spyDownloader) Download(ctx context.Context, req downloader.Request, _ func(downloader.Progress)) error {
s.called.Add(1)
if s.run != nil {
return s.run(ctx, req)
}
return nil
}
func TestResumePreservesCanceledDownloadAndDiscardsFailedCheckpoint(t *testing.T) {
body := []byte("verified download")
srv := rangeServer(t, "app.exe", body, "")
final := filepath.Join(t.TempDir(), "app.exe")
part := final + ".part"
checkpoint := filepath.Join(filepath.Dir(part), ".app.exe.part.reims-dl.json")
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
pluginErr := errors.New("plugin transfer failed")
provider := &spyDownloader{run: func(_ context.Context, req downloader.Request) error {
if req.DestPath != part || !req.Resume {
t.Fatalf("wrong resumable destination: %+v", req)
}
if err := os.WriteFile(part, make([]byte, len(body)), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(checkpoint, []byte("checkpoint"), 0o600); err != nil {
t.Fatal(err)
}
cancel()
return pluginErr
}}
SetDefaultDownloader(func() downloader.Provider { return provider })
t.Cleanup(func() { SetDefaultDownloader(nil) })
if _, err := Resume(ctx, srv.Client(), srv.URL+"/file", final, int64(len(body)), sum(body), nil); !errors.Is(err, context.Canceled) {
t.Fatalf("canceled resume = %v, want context.Canceled", err)
}
for _, path := range []string{part, checkpoint} {
if _, err := os.Stat(path); err != nil {
t.Fatalf("canceled resume lost %s: %v", path, err)
}
}
provider.run = func(context.Context, downloader.Request) error { return pluginErr }
path, err := Resume(t.Context(), srv.Client(), srv.URL+"/file", final, int64(len(body)), sum(body), nil)
if err != nil || path != final {
t.Fatalf("HTTP fallback = %q, %v", path, err)
}
for _, path := range []string{part, checkpoint} {
if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("HTTP fallback kept %s: %v", path, err)
}
}
}
func TestResumeClearsParallelCheckpointWhenPluginIsDisabled(t *testing.T) {
body := []byte("verified download")
srv := rangeServer(t, "app.exe", body, "")
final := filepath.Join(t.TempDir(), "app.exe")
part := final + ".part"
checkpoint := filepath.Join(filepath.Dir(part), ".app.exe.part.reims-dl.json")
if err := os.WriteFile(part, make([]byte, len(body)/2), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(checkpoint, []byte("checkpoint"), 0o600); err != nil {
t.Fatal(err)
}
path, err := Resume(t.Context(), srv.Client(), srv.URL+"/file", final, int64(len(body)), sum(body), nil)
if err != nil || path != final {
t.Fatalf("HTTP resume = %q, %v", path, err)
}
if _, err := os.Stat(checkpoint); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("HTTP resume kept %s: %v", checkpoint, err)
}
}
func TestResumeDirectBypassesDownloaderAndEnforcesMaxBytesAndStall(t *testing.T) {
spy := &spyDownloader{}
SetDefaultDownloader(func() downloader.Provider { return spy })
+5 -10
View File
@@ -4,7 +4,7 @@ import "testing"
func TestGuestAgentFileSyncControlLoop(t *testing.T) {
agent := string(GuestAgentScript())
state := scriptSection(t, agent, "\nFILE_SYNC_PID=", "\nkeymap_active=")
state := scriptSection(t, agent, "\nFILE_SYNC_PID=", "\n\n")
cleanup := scriptSection(t, agent, "\ncleanup() {", "\n\n")
worker := scriptSection(t, agent, "\nreap_file_sync() {", "\ntext_input_loop &")
config := scriptSection(t, agent, "\napply_host_config() {", "\nreport_status() {")
@@ -16,7 +16,6 @@ func TestGuestAgentFileSyncControlLoop(t *testing.T) {
})
t.Run("cleanup_running_worker", func(t *testing.T) {
runShareShell(t, fixture+`
report_status() { [ "$1" = 1 ]; }
sync_files() {
: > "$TMP_DIR/sync-download.part"
sleep 30 >/dev/null 2>&1 &
@@ -36,7 +35,7 @@ child_pid=$(cat child.pid)
command kill "$child_pid" 2>/dev/null || true
[ "$elapsed" -lt 5 ] || fail "cleanup blocked for ${elapsed}s waiting on foreground child"
check "$(cat reaped)" "$worker_pid" "cleanup reaped the worker"
check "$(cat parent-cleanup)" disable "parent cleanup disabled the keymap once"
check "$(cat parent-cleanup)" stopped "parent cleanup stopped the window reporter once"
[ ! -f "$FILE_SYNC_DONE" ] && [ ! -f "$TMP_DIR/sync-download.part" ] ||
fail "cleanup left files from the terminated worker"
[ ! -f "$INJECT_LOCK" ] || fail "cleanup left the injection lock"
@@ -58,7 +57,6 @@ REIMS_TOKEN=token
REIMS_VM=guest
DROP_MOUNT=./drop_mount
mount_mode=webdav
keymap_active=false
sleep_active=false
timezone_helper_ready=false
timezone_error=
@@ -125,7 +123,6 @@ CAFFEINATE_PID=""
TEXT_INPUT_PID=""
DROP_EVENTS_PID=""
CLIPBOARD_PID=""
keymap_applied=true
tick=0
: > "$INJECT_LOCK"
: > parent-cleanup
@@ -142,9 +139,8 @@ await_file() {
sleep 0.05
done
}
stop_window_reporter() { :; }
stop_window_reporter() { printf 'stopped\n' >> parent-cleanup; }
sync_window_reporter() { :; }
apply_hidutil_carrier() { printf '%s\n' "$1" >> parent-cleanup; }
# Model a completed child that still answers kill -0 until wait.
kill() {
@@ -177,7 +173,6 @@ ensure_webdav_mount() {
}
ensure_drop_webdav_mount() { :; }
curl() { printf '%s\n' '{"shared_folders_count":2}'; }
sync_keymap_carrier() { printf '%s keymap\n' "$tick" >> config; }
sync_drive_mounts() { printf '%s drives\n' "$tick" >> config; }
sync_folder_mounts() { printf '%s folders=%s\n' "$tick" "$1" >> config; }
sync_timezone() { :; }
@@ -199,8 +194,8 @@ sleep() {
check "$FILE_SYNC_PID" "$first_pid" "only one worker ran while the first was blocked"
check "$(cat started)" 0 "fallback runs before the gate opens"
check "$(cat status)" "$(printf '0\n5\n10')" "status ticks while the worker is blocked"
check "$(cat config)" "$(printf '%s\n' '0 keymap' '0 drives' '0 folders=2' \
'5 keymap' '5 drives' '5 folders=2' '10 keymap' '10 drives' '10 folders=2')" "host config order"
check "$(cat config)" "$(printf '%s\n' '0 drives' '0 folders=2' \
'5 drives' '5 folders=2' '10 drives' '10 folders=2')" "host config order"
: > release-0
await_file "$FILE_SYNC_DONE"
[ ! -s parent-cleanup ] && [ -f "$INJECT_LOCK" ] || fail "worker ran parent cleanup"
+3 -2
View File
@@ -256,8 +256,9 @@ func (s *Server) handleDropEvents(w http.ResponseWriter, r *http.Request) {
cur.dropQueue[0] = nil
cur.dropQueue = cur.dropQueue[1:]
cur.dropActive[item.DropID] = item
cur.markSeen(time.Now())
cur.lastDropPoll = time.Now()
now := time.Now()
cur.lastSeen = now
cur.lastDropPoll = now
s.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
+18 -6
View File
@@ -2,6 +2,7 @@ package guesttools
import (
"bytes"
"io"
"os"
"os/exec"
"path/filepath"
@@ -20,13 +21,24 @@ func TestToolsDiskImageIncludesDropResolveJS(t *testing.T) {
if !strings.Contains(resolver, "com.apple.finder") || strings.Contains(resolver, "'Finder'") {
t.Fatal("drop resolver must identify Finder by bundle ID")
}
path := filepath.Join(t.TempDir(), "tools.img")
if err := BuildToolsDiskImage(path, VMConfig{VMName: "mac"}); err != nil {
t.Fatal(err)
var foundResolver bool
for _, f := range ToolsDiskFiles(VMConfig{VMName: "mac"}) {
if f.Name != "drop-resolve.js" {
continue
}
rc, err := f.Open()
if err != nil {
t.Fatal(err)
}
data, err := io.ReadAll(rc)
_ = rc.Close()
if err != nil || !bytes.Contains(data, []byte(resolver)) {
t.Fatalf("missing resolver in tools disk files: %v", err)
}
foundResolver = true
}
image, err := os.ReadFile(path)
if err != nil || !bytes.Contains(image, []byte(resolver)) {
t.Fatalf("missing resolver in image: %v", err)
if !foundResolver {
t.Fatal("missing drop-resolve.js in tools disk files")
}
install := string(GuestInstallScript())
agent := string(GuestAgentScript())
Loaded 100 of 234 files, more files were not shown because too many files have changed in this diff. Show more