Compare 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
Nwflower 24da891365 release: prepare v0.2.15
Release Reims-Go / release (push) Canceled after 0s
Archive the bilingual changelog and synchronize the app and frontend release versions.
2026-12-05 02:23:14 -07:00
千川白浪 e24422176a Merge pull request #193 from Nwflower/ci/workflow-timeouts-and-path-filters
ci: bound job time and skip docs-only pushes
2026-12-05 17:20:48 +08:00
千川白浪 8ea7e3141e Merge pull request #192 from Nwflower/fix/held-input-retry-and-generation
fix(plugin): retry a failed held-input release and keep presses made during it
2026-12-05 17:20:29 +08:00
Nwflower 892d67644b fix(runtime): fall back to Reims-Go releases 2026-12-05 02:19:03 -07:00
Nwflower 875f4df333 ci: bound job time and skip docs-only pushes
A stuck Windows job could hold a runner for the default six hours, so each job now has a timeout: ten minutes for the alpha plan step and thirty for the build jobs.

Pushes and pull requests that only touch documentation, readmes or repository templates no longer start the full verification, which keeps the queue for changes that can break the build.
2026-12-05 02:12:36 -07:00
Nwflower 6501fe2000 fix(plugin): retry a failed held-input release and keep presses made during it
A fallback release that fails while the VM is still running left the record without any retry: its timer had already fired and a plugin that exited never makes the next call, so a modifier stayed pressed in the guest. The record now rearms with a retry timeout, and a VM that stopped while the release was in flight drops the record instead of retrying it.

A release that finishes after the plugin pressed something new lifted that press and then deleted it from the record, so a later fallback no longer knew to lift it. Each record now carries a generation, and a release only clears what it lifted when nothing changed since its snapshot.
2026-12-05 02:07:11 -07:00
Nwflower ddc7f61b06 release: prepare v0.2.14
Release Reims-Go / release (push) Canceled after 0s
Archive the bilingual changelog and synchronize the app and frontend release versions.
2026-12-05 01:57:34 -07:00
千川白浪 22c01cee5b Merge pull request #190 from Nwflower/feat/plugin-host-api-catalog
feat(plugin): catalog the Host API, open secret typing and extend the SDK
2026-12-05 16:48:49 +08:00
Nwflower d55241cba2 feat(plugin): catalog the Host API, open secret typing and extend the SDK
Give the Sidecar Host API one authoritative catalog in pkg/pluginproto: every
host/* method's status, required permissions, handshake feature and request and
result shapes. The host, pkg/pluginsdk and plugins share those types, so a field
can no longer exist on one side only, and permissions come from the catalog
instead of from each handler. Tests gate that every served method is
catalogued, every stable catalogued method is served, and every catalogued
permission is one the host recognizes.

Open the interface up instead of adding consent gates. Typing a secret setting
is no longer reserved for reims.agent: any plugin that holds qmp:write and that
the user authorized for the VM can have the host type the plugin's own setting,
which the plugin never reads back. Restoring a snapshot works on any authorized
VM, a plugin names its own clones, a held key may carry modifiers, and a
screenshot width outside the supported range is brought into range rather than
refused. Deleting a VM stays limited to the temporary VMs a plugin created.

Record the keys and pointer buttons each plugin holds per VM and lift them when
the plugin's process exits, its scope is disposed, the VM stops or it stops
calling, so a guest never stays stuck with a modifier down. Requests from
plugins that declare pluginApi 1.3 or newer are decoded strictly and answer an
undefined field with JSON-RPC -32602, while older plugins keep tolerant
decoding.

Add typed VM and console methods to pkg/pluginsdk so a plugin no longer needs
its own JSON-RPC client. A method the contract does not catalog, or one the
host did not advertise in the handshake, is refused before it is sent, and the
host's JSON-RPC error code reaches the caller.
2026-12-05 01:43:28 -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
278 changed files with 11766 additions and 7236 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
+1
View File
@@ -24,6 +24,7 @@ concurrency:
jobs:
plan:
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: write
outputs:
+26 -2
View File
@@ -3,8 +3,24 @@ name: CI
on:
push:
branches: [main]
paths-ignore:
- 'docs/**'
- 'README.md'
- 'README.*.md'
- 'AGENTS.md'
- '.github/ISSUE_TEMPLATE/**'
- '.github/PULL_REQUEST_TEMPLATE.md'
- '.github/readme/**'
pull_request:
branches: [main]
paths-ignore:
- 'docs/**'
- 'README.md'
- 'README.*.md'
- 'AGENTS.md'
- '.github/ISSUE_TEMPLATE/**'
- '.github/PULL_REQUEST_TEMPLATE.md'
- '.github/readme/**'
concurrency:
group: ci-${{ github.event.pull_request.number || github.ref }}
@@ -16,6 +32,7 @@ env:
jobs:
verify:
runs-on: windows-latest
timeout-minutes: 30
outputs:
rolling: ${{ steps.rolling.outputs.publish }}
steps:
@@ -28,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/**'
+3
View File
@@ -17,6 +17,7 @@ env:
jobs:
dev-release:
runs-on: windows-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
with:
@@ -136,6 +137,8 @@ jobs:
- name: Build Windows x64 binary
shell: pwsh
env:
CGO_ENABLED: "0"
run: |
$ErrorActionPreference = 'Stop'
$ver = $env:DEV_VERSION
+3
View File
@@ -25,6 +25,7 @@ env:
jobs:
release:
runs-on: windows-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
with:
@@ -102,6 +103,8 @@ jobs:
- name: Build Windows x64 binary
shell: pwsh
env:
CGO_ENABLED: "0"
run: |
$ErrorActionPreference = 'Stop'
$tag = $env:RELEASE_TAG
+86
View File
@@ -4,6 +4,92 @@
Client releases are listed newest first. Release notes for portable runtimes (`runtime-*`) are available on [GitHub Releases](https://github.com/Nwflower/Reims-Go/releases).
## v0.2.15 — 2026-12-05
[中文](#cn-v0.2.15) | [English](#en-v0.2.15)
<h3 id="cn-v0.2.15">问题修复</h3>
- 插件退出或长时间不再调用后,宿主替它抬起按住的输入时若释放失败会自动重试,不再让修饰键一直卡在客体里。释放期间插件新按下的键不会被误抬起,也不会从宿主记录中丢失。 — [@Nwflower](https://github.com/Nwflower)
- 主运行时发布仓库无法访问时,自动从 `Nwflower/Reims-Go` 检查可用运行时。 — [@Nwflower](https://github.com/Nwflower)
<h3 id="en-v0.2.15">Bug Fixes</h3>
- When the host lifts input a plugin left held and that release fails, it now retries instead of leaving a modifier stuck in the guest. A key the plugin pressed while a release was in flight is no longer lifted by mistake or dropped from the host's record. — [@Nwflower](https://github.com/Nwflower)
- Check `Nwflower/Reims-Go` for available runtimes when the primary runtime release repository is unavailable. — [@Nwflower](https://github.com/Nwflower)
## v0.2.14 — 2026-12-05
[中文](#cn-v0.2.14) | [English](#en-v0.2.14)
<h3 id="cn-v0.2.14">新增功能</h3>
- 为 Windows Q35 虚拟机新增原生块设备直通模式(支持物理磁盘或分区就地挂载、`--disk-cache` 主机缓存策略配置,以及配合便携运行时新版 QEMU 的 Win32 原生 IOCP/WHPX/NVMe 性能优化)。 — [@yxc0915](https://github.com/yxc0915)
- `pkg/pluginsdk` 新增虚拟机与控制台方法,插件无需自写 JSON-RPC 客户端即可列出和操作虚拟机、截图、按键、键入文本与敏感设置、抬起仍按住的输入。宿主未在握手中宣告的方法会在发送前被拒绝,宿主返回的 JSON-RPC 错误码也会保留给调用方。 — [@Nwflower](https://github.com/Nwflower)
### 体验优化
- 应用内更新改为直接读取 GitHub Releases 接口返回的 `assets[].digest` 校验安装包 SHA-256,不再额外下载 `SHA256SUMS.txt`(该文件计划在 v0.3 退役)。 — [@Nwflower](https://github.com/Nwflower)
- 将「剪贴板互通」的全部配置项从虚拟机设置迁移到插件页的插件配置中统一管理,并在升级时按显式关闭与更严格限制优先的规则自动迁移旧的单虚拟机配置。 — [@Nwflower](https://github.com/Nwflower)
- MCP 插件接口按连接区分会话,客户端断开后会通知插件释放仍按住的输入;截图支持按源分辨率裁剪局部区域,按键支持单独按住和松开,关机支持强制停止,读取恢复点列表只需读取权限。 — [@Nwflower](https://github.com/Nwflower)
- 插件支持在清单中声明颜色令牌与 SVG 前景图标并迁移全部内置插件,插件页新增「上架插件」入口,市场卡片展示 GitHub Star 数与下载量,语言包脚手架默认仅生成目标语言标题与精简描述。 — [@Nwflower](https://github.com/Nwflower)
- 插件日志并入应用日志并标明插件包名,不再使用单独的日志窗口。 — [@Nwflower](https://github.com/Nwflower)
- 插件市场不再隐藏 Alpha 通道插件(改为展示 `Alpha` 标签),安装与更新时弹出版本选择清单,支持按综合(发布日与下载量)、Star、下载量与最新发布排序,并将带主页的插件标题设为可跳转超链接。 — [@Nwflower](https://github.com/Nwflower)
- 已安装插件的安全扫描结论改为在权限提示中显示。 — [@Nwflower](https://github.com/Nwflower)
- 插件自带的设置面板改为从该插件的设置按钮打开,不再排在插件页底部。 — [@Nwflower](https://github.com/Nwflower)
- 下载速度低于 1 MB/s 时改以 KB/s 显示,精简关于页与更新通道文案,默认同步宿主机内存规格并将外观与语言设置分组置顶,更新检查按通道缓存 5 分钟且切换通道时不再禁用控件。 — [@Nwflower](https://github.com/Nwflower)
- 新建虚拟机时在左侧栏显示正在创建的条目,并在主界面直接展示创建进度、步骤说明与取消入口 (#120)。 — [@Nwflower](https://github.com/Nwflower)
- 插件宿主接口新增统一目录,每个 `host/*` 方法的权限与请求、结果字段只定义一次,宿主、SDK 与插件共用。键入敏感设置不再只对官方 MCP 插件开放,任何持有 `qmp:write` 且用户已按虚拟机授权访问的插件都可使用,宿主只键入该插件自己的设置且不返回明文。恢复点还原对已授权访问的虚拟机开放,克隆名称由插件自定。 — [@Nwflower](https://github.com/Nwflower)
- 插件在客体里按住键或鼠标键后退出、停用或两分钟不再调用时,宿主会替它抬起,虚拟机不再卡在修饰键按下的状态。按住按键时可同时带修饰键,截图宽度超出支持范围时会被收进范围内而不是被拒绝。 — [@Nwflower](https://github.com/Nwflower)
### 问题修复
- 修复在处理器核心弹窗中勾选核心、切换模式或调整 EcoQoS 开关后,未保存前因后台状态刷新自动跳回旧配置的问题。 — [@reiasu2](https://github.com/reiasu2)
- 适配新版运行时移除 `reims-ctl set --capture` 参数,按运行时能力隐藏「点击窗口时捕获键鼠」并避免新建、克隆与保存设置报错,同时将修饰键状态行独立显示并明确「拦截宿主机全局热键」用途与立即生效说明。 — [@reiasu2](https://github.com/reiasu2)
- 手动打开更高版本的 Windows 客户端时,自动退出正在运行的旧客户端并在原位置更新,原来的快捷方式仍可使用。 — [@yxc0915](https://github.com/yxc0915)
- 修复克隆虚拟机没有主机 SSH 端口转发的问题。源虚拟机开启端口转发时,克隆出的虚拟机现在会占用源端口之后的一个空闲端口,因此 MCP 临时会话与克隆上的 SSH 相关工具(`guest_exec`、`guest_wait_ready`、`test_run` 等)可以正常连接客体。源虚拟机未开启转发时克隆仍不开启。 — [@Nwflower](https://github.com/Nwflower)
- 修复 MCP 临时克隆无法自动输入登录密码、SSH 用户名常为空的问题。克隆不保存自己的虚拟机设置,现在它读取 `login_password` 和 `username` 时会回退到来源虚拟机,且仅在来源虚拟机仍开启「允许 AI 访问」时生效;撤销来源的授权后克隆立即失去回退。密码不会复制进克隆,克隆销毁后不留存副本。虚拟机未保存登录密码时,解锁会提示去 MCP 服务设置里填写,而不是返回内部错误。 — [@Nwflower](https://github.com/Nwflower)
- 修复宿主机存在多份 Vulkan ICD 驱动清单或重复枚举同一张显卡时,内核页与虚拟机设置页重复显示同一块显卡且缺失驱动版本号的问题。 — [@Nwflower](https://github.com/Nwflower)
- 清理 macOS 独立应用窗口边角残留的桌面画面。拖动标题栏中部即可移动 Windows 窗口,拖动期间保留上一帧,避免闪出来宾桌面。 — [@yxc0915](https://github.com/yxc0915)
- 修复 Guest Tools 窗口上报进程崩溃导致的「打开独立应用窗口」失败。已有虚拟机请重新安装 Guest Tools,更新至 `v22`。 — [@yxc0915](https://github.com/yxc0915)
- 在 Windows 上从插件市场安装、重装插件或导入本地 ZIP 插件包时,若杀毒软件实时防护短暂占用刚解压的插件可执行文件,自动短暂重试,避免报 `Access is denied` 失败。 — [@reiasu2](https://github.com/reiasu2)
- 修复手动移动数据目录并在设置或首启界面重新选择新目录后,因虚拟机注册表保留旧路径导致无法启动虚拟机的问题。 — [@Nwflower](https://github.com/Nwflower)
- 手动切换到旧版运行时后,在内核页将当前运行时标注为不是最新并提示切换,同时将最新标签标注在实际最新版本旁 (#151)。 — [@Nwflower](https://github.com/Nwflower)
<h3 id="en-v0.2.14">New Features</h3>
- Add Windows raw disk/partition in-place mounting and per-VM `--disk-cache` policy support, paired with the Win32 native IOCP AIO, WHPX doorbell/fast-MMIO, and NVMe runtime optimizations. — [@yxc0915](https://github.com/yxc0915)
- Add VM and console methods to `pkg/pluginsdk`, so a plugin can list and control VMs, take screenshots, press keys, type text and secrets and release held input without writing its own JSON-RPC client. A method the host did not advertise in the handshake is refused before it is sent, and the host's JSON-RPC error code reaches the caller. — [@Nwflower](https://github.com/Nwflower)
### Improvements
- Verify in-app update downloads directly against the `assets[].digest` SHA-256 returned by the GitHub Releases API instead of fetching `SHA256SUMS.txt` (planned for retirement in v0.3). — [@Nwflower](https://github.com/Nwflower)
- Move all Clipboard Sync settings from VM settings into the plugin configuration on the Plugins page, automatically migrating legacy per-VM settings on upgrade with explicit-off and stricter limits taking precedence. — [@Nwflower](https://github.com/Nwflower)
- The MCP plugin interface now scopes each client connection as its own session and notifies the plugin when a client disconnects so held input is released. Screenshots can crop a region at source resolution, keys can be held and released individually, shutdown can force-stop, and listing restore points needs only read permission. — [@Nwflower](https://github.com/Nwflower)
- Support custom icon tone tokens and monochrome SVG foregrounds in plugin manifests (migrating all built-in plugins), add a Submit plugin button to the Plugins page, display GitHub star and download counts on market cards, and scaffold language packs with concise native-locale metadata. — [@Nwflower](https://github.com/Nwflower)
- Show plugin logs in the app log, labeled with the plugin ID, instead of a separate log window. — [@Nwflower](https://github.com/Nwflower)
- Show Alpha plugins directly in the marketplace with an `Alpha` tag instead of hiding them, open a version picker when installing or updating, add sorting by Recommended (recency + downloads), Stars, Downloads, and Recently updated, and make plugin titles clickable links to their homepage. — [@Nwflower](https://github.com/Nwflower)
- Show the security scan result of installed plugins in their permissions tooltip. — [@Nwflower](https://github.com/Nwflower)
- Open a plugin's own settings panel from its settings button instead of the bottom of the Plugins page. — [@Nwflower](https://github.com/Nwflower)
- Display download speeds below 1 MB/s in KB/s, tighten About page and update channel copy, sync host memory SMBIOS specs by default and move Appearance & language to the top of Settings, cache update checks per channel for 5 minutes, and keep the update channel selector interactive while switching. — [@Nwflower](https://github.com/Nwflower)
- Show in-progress VM creation in the sidebar and display its progress, current step, and cancel action directly in the main view (#120). — [@Nwflower](https://github.com/Nwflower)
- Add one authoritative catalog for the plugin Host API, so each `host/*` method's permissions and request and result fields are defined once and shared by the host, the SDK and plugins. Typing a secret setting is no longer reserved for the official MCP plugin, so any plugin holding `qmp:write` that the user authorized for that VM can use it, and the host only types the plugin's own setting without returning it. Restoring a snapshot works on any authorized VM, and a plugin names its own clones. — [@Nwflower](https://github.com/Nwflower)
- When a plugin leaves a key or a pointer button held in a guest and then exits, is disabled or stops calling for two minutes, the host lifts it, so a VM no longer stays stuck with a modifier down. A held key may carry modifiers, and a screenshot width outside the supported range is brought into range instead of being refused. — [@Nwflower](https://github.com/Nwflower)
### Bug Fixes
- Preserve unsaved core selections, mode changes, and EcoQoS toggles in the CPU cores dialog when background host refreshes occur. — [@reiasu2](https://github.com/reiasu2)
- Detect whether the active runtime supports `reims-ctl set --capture` so newer runtimes omit `--capture` during create, clone, and settings updates and hide the retired capture toggle, while moving modifier-key status to its own row and clarifying global host hotkey blocking. — [@reiasu2](https://github.com/reiasu2)
- Opening a newer Windows client now closes the running older client and updates its executable in place so existing shortcuts still work. — [@yxc0915](https://github.com/yxc0915)
- Fix cloned VMs having no host SSH port forward. When the source VM forwards SSH, a clone now takes the next free port after the source port, so SSH-based guest tools such as `guest_exec`, `guest_wait_ready`, and `test_run` work on MCP temporary sessions and other clones. A source without forwarding still yields a clone without one. — [@Nwflower](https://github.com/Nwflower)
- Fix MCP temporary clones failing to type the login password and often reporting an empty SSH username. A clone keeps no VM settings of its own, so reads of `login_password` and `username` now fall back to the source VM, and only while the source still allows AI access; revoking access on the source removes the fallback immediately. The password is never copied into the clone, so disposing it leaves no copy behind. When a VM has no saved login password, unlock now asks you to set it in the MCP Service settings instead of returning an internal error. — [@Nwflower](https://github.com/Nwflower)
- Deduplicate repeated Vulkan physical device entries on the Runtime and VM settings pages when the same GPU is enumerated multiple times. — [@Nwflower](https://github.com/Nwflower)
- Remove stray desktop pixels from the corners of separate macOS app windows. Drag the middle of the title bar to move the Windows window. The last frame stays visible during the move to prevent the guest desktop from flashing through. — [@yxc0915](https://github.com/yxc0915)
- Fix a Guest Tools window reporter crash that prevented macOS apps from opening in separate windows. Reinstall Guest Tools in existing VMs to update to `v22`. — [@yxc0915](https://github.com/yxc0915)
- When installing or reinstalling a plugin from the market or importing a local ZIP package on Windows, briefly retry if real-time antivirus protection holds newly extracted plugin executables open so installation does not fail with `Access is denied`. — [@reiasu2](https://github.com/reiasu2)
- Fix VMs failing to start after moving the data folder and reselecting its new location by updating stale paths in the VM registry. — [@Nwflower](https://github.com/Nwflower)
- Mark the active runtime as not latest with a switch hint when an older runtime is selected on the Engine page, and place the Latest badge on the actual newest installed runtime (#151). — [@Nwflower](https://github.com/Nwflower)
## v0.2.13 — 2026-12-04
[中文](#cn-v0.2.13) | [English](#en-v0.2.13)
-7
View File
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["reiasu2"],
"zh": "修复在处理器核心弹窗中勾选核心、切换模式或调整 EcoQoS 开关后,未保存前因后台状态刷新自动跳回旧配置的问题。",
"en": "Preserve unsaved core selections, mode changes, and EcoQoS toggles in the CPU cores dialog when background host refreshes occur."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "improvements",
"order": 0,
"authors": ["Nwflower"],
"zh": "应用内更新改为直接读取 GitHub Releases 接口返回的 `assets[].digest` 校验安装包 SHA-256,不再额外下载 `SHA256SUMS.txt`(该文件计划在 v0.3 退役)。",
"en": "Verify in-app update downloads directly against the `assets[].digest` SHA-256 returned by the GitHub Releases API instead of fetching `SHA256SUMS.txt` (planned for retirement in v0.3)."
}
+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."
}
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["reiasu2"],
"zh": "适配新版运行时移除 `reims-ctl set --capture` 参数,按运行时能力隐藏「点击窗口时捕获键鼠」并避免新建、克隆与保存设置报错,同时将修饰键状态行独立显示并明确「拦截宿主机全局热键」用途与立即生效说明。",
"en": "Detect whether the active runtime supports `reims-ctl set --capture` so newer runtimes omit `--capture` during create, clone, and settings updates and hide the retired capture toggle, while moving modifier-key status to its own row and clarifying global host hotkey blocking."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["yxc0915"],
"zh": "手动打开更高版本的 Windows 客户端时,自动退出正在运行的旧客户端并在原位置更新,原来的快捷方式仍可使用。",
"en": "Opening a newer Windows client now closes the running older client and updates its executable in place so existing shortcuts still work."
}
@@ -1,7 +0,0 @@
{
"group": "improvements",
"order": 0,
"authors": ["Nwflower"],
"zh": "将「剪贴板互通」的全部配置项从虚拟机设置迁移到插件页的插件配置中统一管理,并在升级时按显式关闭与更严格限制优先的规则自动迁移旧的单虚拟机配置。",
"en": "Move all Clipboard Sync settings from VM settings into the plugin configuration on the Plugins page, automatically migrating legacy per-VM settings on upgrade with explicit-off and stricter limits taking precedence."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "修复克隆虚拟机没有主机 SSH 端口转发的问题。源虚拟机开启端口转发时,克隆出的虚拟机现在会占用源端口之后的一个空闲端口,因此 MCP 临时会话与克隆上的 SSH 相关工具(`guest_exec`、`guest_wait_ready`、`test_run` 等)可以正常连接客体。源虚拟机未开启转发时克隆仍不开启。",
"en": "Fix cloned VMs having no host SSH port forward. When the source VM forwards SSH, a clone now takes the next free port after the source port, so SSH-based guest tools such as `guest_exec`, `guest_wait_ready`, and `test_run` work on MCP temporary sessions and other clones. A source without forwarding still yields a clone without one."
}
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "修复 MCP 临时克隆无法自动输入登录密码、SSH 用户名常为空的问题。克隆不保存自己的虚拟机设置,现在它读取 `login_password` 和 `username` 时会回退到来源虚拟机,且仅在来源虚拟机仍开启「允许 AI 访问」时生效;撤销来源的授权后克隆立即失去回退。密码不会复制进克隆,克隆销毁后不留存副本。虚拟机未保存登录密码时,解锁会提示去 MCP 服务设置里填写,而不是返回内部错误。",
"en": "Fix MCP temporary clones failing to type the login password and often reporting an empty SSH username. A clone keeps no VM settings of its own, so reads of `login_password` and `username` now fall back to the source VM, and only while the source still allows AI access; revoking access on the source removes the fallback immediately. The password is never copied into the clone, so disposing it leaves no copy behind. When a VM has no saved login password, unlock now asks you to set it in the MCP Service settings instead of returning an internal error."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "修复宿主机存在多份 Vulkan ICD 驱动清单或重复枚举同一张显卡时,内核页与虚拟机设置页重复显示同一块显卡且缺失驱动版本号的问题。",
"en": "Deduplicate repeated Vulkan physical device entries on the Runtime and VM settings pages when the same GPU is enumerated multiple times."
}
+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
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["yxc0915"],
"zh": "清理 macOS 独立应用窗口边角残留的桌面画面。拖动标题栏中部即可移动 Windows 窗口,拖动期间保留上一帧,避免闪出来宾桌面。",
"en": "Remove stray desktop pixels from the corners of separate macOS app windows. Drag the middle of the title bar to move the Windows window. The last frame stays visible during the move to prevent the guest desktop from flashing through."
}
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["yxc0915"],
"zh": "修复 Guest Tools 窗口上报进程崩溃导致的「打开独立应用窗口」失败。已有虚拟机请重新安装 Guest Tools,更新至 `v22`。",
"en": "Fix a Guest Tools window reporter crash that prevented macOS apps from opening in separate windows. Reinstall Guest Tools in existing VMs to update to `v22`."
}
+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
@@ -1,7 +0,0 @@
{
"group": "improvements",
"order": 0,
"authors": ["Nwflower"],
"zh": "MCP 插件接口按连接区分会话,客户端断开后会通知插件释放仍按住的输入;截图支持按源分辨率裁剪局部区域,按键支持单独按住和松开,关机支持强制停止,读取恢复点列表只需读取权限。",
"en": "The MCP plugin interface now scopes each client connection as its own session and notifies the plugin when a client disconnects so held input is released. Screenshots can crop a region at source resolution, keys can be held and released individually, shutdown can force-stop, and listing restore points needs only read permission."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "improvements",
"order": 0,
"authors": ["Nwflower"],
"zh": "插件支持在清单中声明颜色令牌与 SVG 前景图标并迁移全部内置插件,插件页新增「上架插件」入口,市场卡片展示 GitHub Star 数与下载量,语言包脚手架默认仅生成目标语言标题与精简描述。",
"en": "Support custom icon tone tokens and monochrome SVG foregrounds in plugin manifests (migrating all built-in plugins), add a Submit plugin button to the Plugins page, display GitHub star and download counts on market cards, and scaffold language packs with concise native-locale metadata."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["reiasu2"],
"zh": "在 Windows 上从插件市场安装、重装插件或导入本地 ZIP 插件包时,若杀毒软件实时防护短暂占用刚解压的插件可执行文件,自动短暂重试,避免报 `Access is denied` 失败。",
"en": "When installing or reinstalling a plugin from the market or importing a local ZIP package on Windows, briefly retry if real-time antivirus protection holds newly extracted plugin executables open so installation does not fail with `Access is denied`."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "improvements",
"order": 0,
"authors": ["Nwflower"],
"zh": "插件日志并入应用日志并标明插件包名,不再使用单独的日志窗口。",
"en": "Show plugin logs in the app log, labeled with the plugin ID, instead of a separate log window."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "improvements",
"order": 0,
"authors": ["Nwflower"],
"zh": "插件市场不再隐藏 Alpha 通道插件(改为展示 `Alpha` 标签),安装与更新时弹出版本选择清单,支持按综合(发布日与下载量)、Star、下载量与最新发布排序,并将带主页的插件标题设为可跳转超链接。",
"en": "Show Alpha plugins directly in the marketplace with an `Alpha` tag instead of hiding them, open a version picker when installing or updating, add sorting by Recommended (recency + downloads), Stars, Downloads, and Recently updated, and make plugin titles clickable links to their homepage."
}
@@ -1,7 +0,0 @@
{
"group": "improvements",
"order": 0,
"authors": ["Nwflower"],
"zh": "已安装插件的安全扫描结论改为在权限提示中显示。",
"en": "Show the security scan result of installed plugins in their permissions tooltip."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "improvements",
"order": 0,
"authors": ["Nwflower"],
"zh": "插件自带的设置面板改为从该插件的设置按钮打开,不再排在插件页底部。",
"en": "Open a plugin's own settings panel from its settings button instead of the bottom of the Plugins page."
}
+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."
}
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "修复手动移动数据目录并在设置或首启界面重新选择新目录后,因虚拟机注册表保留旧路径导致无法启动虚拟机的问题。",
"en": "Fix VMs failing to start after moving the data folder and reselecting its new location by updating stale paths in the VM registry."
}
+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
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "手动切换到旧版运行时后,在内核页将当前运行时标注为不是最新并提示切换,同时将最新标签标注在实际最新版本旁 (#151)。",
"en": "Mark the active runtime as not latest with a switch hint when an older runtime is selected on the Engine page, and place the Latest badge on the actual newest installed runtime (#151)."
}
+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."
}
@@ -1,7 +0,0 @@
{
"group": "improvements",
"order": 0,
"authors": ["Nwflower"],
"zh": "下载速度低于 1 MB/s 时改以 KB/s 显示,精简关于页与更新通道文案,默认同步宿主机内存规格并将外观与语言设置分组置顶,更新检查按通道缓存 5 分钟且切换通道时不再禁用控件。",
"en": "Display download speeds below 1 MB/s in KB/s, tighten About page and update channel copy, sync host memory SMBIOS specs by default and move Appearance & language to the top of Settings, cache update checks per channel for 5 minutes, and keep the update channel selector interactive while switching."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "improvements",
"order": 0,
"authors": ["Nwflower"],
"zh": "新建虚拟机时在左侧栏显示正在创建的条目,并在主界面直接展示创建进度、步骤说明与取消入口 (#120)。",
"en": "Show in-progress VM creation in the sidebar and display its progress, current step, and cancel action directly in the main view (#120)."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "new",
"order": 0,
"authors": ["yxc0915"],
"zh": "为 Windows Q35 虚拟机新增原生块设备直通模式(支持物理磁盘或分区就地挂载、`--disk-cache` 主机缓存策略配置,以及配合便携运行时新版 QEMU 的 Win32 原生 IOCP/WHPX/NVMe 性能优化)。",
"en": "Add Windows raw disk/partition in-place mounting and per-VM `--disk-cache` policy support, paired with the Win32 native IOCP AIO, WHPX doorbell/fast-MMIO, and NVMe runtime optimizations."
}
+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 的苹果菜单中选择「关机」。客户端的停止操作会向来宾发送电源按键事件。若来宾没有退出,可回到桌面完成关机。只在来宾无响应时使用强制停止。
+6 -3
View File
@@ -37,7 +37,9 @@ flowchart TB
L3 插件可在清单 `contributes.channels` 中声明 `jsonl` 通道。桌面端的 `plugin connect` 经 Windows 当前用户限定的命名管道转发消息,不开放 TCP 或 HTTP MCP 监听。每条连接带一个会话标识,宿主随 `channel/<通道>/message` 一并转发,插件按会话区分请求 ID 和取消。连接结束后,宿主向正在运行的 Sidecar 发送 `channel/<通道>/closed` 通知,插件据此取消该连接的调用并释放按住的输入。官方 MCP 插件实现工具、虚拟机状态与桌面控制,以及通过 SSH/SFTP 的客体命令和文件传输。
Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 VM 目录。读取 VM 状态和恢复点列表要求 `vm:read`,截图要求 `vm:screen`,输入要求 `qmp:write`,VM 启停要求 `vm:control`。截图可指定一块区域,区域坐标默认按源分辨率计算,也可附带参考图像尺寸,由宿主换算到源分辨率。宿主在全分辨率帧上裁剪区域后再缩放。按键可单独按住和松开,释放接口一次抬起指定的按键和鼠标键;驱动控制台只支持按键单击。关机可指定强制停止。Host API 审核插件权限并记录方法名,不把输入文本写入审计日志。开机、登录和切换显示时画面可能是纯色,此时截图照常返回该帧并标记 `blank`,插件据此继续等待,而不是当作失败。登录密码由 Windows DPAPI 保护,宿主只提供按设置键名键入的操作,不向 MCP 插件返回明文。插件自己的下载器敏感设置仅在下载请求中解密并传给该插件进程。
Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 VM 目录。读取 VM 状态和恢复点列表要求 `vm:read`,截图要求 `vm:screen`,输入要求 `qmp:write`,VM 启停要求 `vm:control`。截图可指定一块区域,区域坐标默认按源分辨率计算,也可附带参考图像尺寸,由宿主换算到源分辨率;宿主在全分辨率帧上裁剪区域后再缩放,超出支持范围的宽度会被收进范围内而不是被拒绝。按键可单独按住和松开,按住时可同时带修饰键,宿主一并按住或抬起;释放接口一次抬起指定的按键和鼠标键;驱动控制台只支持按键单击。关机可指定强制停止。宿主记录每个插件在各台虚拟机上仍按住的键与鼠标键,包括驱动控制台上的鼠标键,在插件进程退出、插件停用、虚拟机停止或两分钟不再调用时替它抬起;按住状态只由输入事件维护,不依赖连接存活,虚拟机未运行时记录直接丢弃,不在开机后补发过期的释放。
键入敏感设置对所有持有 `qmp:write` 且用户已按虚拟机授权访问的插件开放,不再只对官方插件开放。宿主只键入该插件自己的设置,不向插件返回明文,审计日志只记录设置名与长度。恢复点还原对已授权访问的虚拟机开放;删除虚拟机仍只限插件自己创建的临时虚拟机,克隆名称由插件自定,宿主以自己写入的归属标记识别临时虚拟机。Host API 审核插件权限并记录方法名,不把输入文本写入审计日志。开机、登录和切换显示时画面可能是纯色,此时截图照常返回该帧并标记 `blank`,插件据此继续等待,而不是当作失败。登录密码由 Windows DPAPI 保护。插件自己的下载器敏感设置仅在下载请求中解密并传给该插件进程。
## 生命周期、参数账本与资源预算
@@ -72,12 +74,13 @@ Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 V
| 版本面 | 覆盖范围 | 权威契约清单与自动校验 |
| :--- | :--- | :--- |
| `pluginApi` | 清单结构、扩展点、钩子载荷、权限名与子进程 JSON-RPC 协议 | [`internal/plugin/contract.go`](../internal/plugin/contract.go) |
| `pluginApi` 的宿主接口 | Sidecar 可调用的 `host/*` 方法、所需权限与请求和结果的字段 | [`pkg/pluginproto`](../pkg/pluginproto)(宿主、SDK 与插件共用同一份类型) |
| `uiApi` | 主题令牌、部件类名、状态属性、槽位、全窗图层、布局选项、图标名与交互事件 | [`frontend/ui-contract.json`](../frontend/ui-contract.json)(前端构建校验每个稳定项均已渲染) |
| `bridgeApi` | 沙箱面板与宿主之间的消息方法与事件 | [`frontend/bridge-contract.json`](../frontend/bridge-contract.json)(前后端单测双向同步校验) |
每个公开的稳定契约项在发布时均具备宿主实现与契约测试;尚未实现的预留项在契约文件中标记为 `experimental`,清单校验予以放行但 `reims-go plugin doctor` 会给出实验性提示,正式版市场插件不得依赖实验项。主版本内只做向后兼容的可选扩展,插件在握手阶段根据宿主下发的 `features` 特性列表按需降级,未知清单字段忽略并提示。
每个公开的稳定契约项在发布时均具备宿主实现与契约测试;尚未实现的预留项在契约文件中标记为 `experimental`,清单校验予以放行但 `reims-go plugin doctor` 会给出实验性提示,正式版市场插件不得依赖实验项。主版本内只做向后兼容的可选扩展,插件在握手阶段根据宿主下发的 `features` 特性列表按需降级,未知清单字段忽略并提示。宿主接口目录中的每个方法同样以特性名宣告,测试保证目录中的稳定方法都有实现、宿主实现的方法都在目录内。
当前插件契约为 `pluginApi 1.2.0`,界面契约为 `uiApi 2.1.0`。客体驱动在清单中以 `runtimeKind` 为 `external` 声明自带运行环境,并可用 `consoleEndpoint`、`pasteCombo`、`keymap` 声明控制台接入方式、客体粘贴组合键与键位映射。`driver.console`、`host.secret.materialize`、`host.download` 与 `host.elevate.request` 均已进入稳定契约,并在 Sidecar 握手特性列表中宣告。
当前插件契约为 `pluginApi 1.3.0`,界面契约为 `uiApi 2.1.0`。客体驱动在清单中以 `runtimeKind` 为 `external` 声明自带运行环境,并可用 `consoleEndpoint`、`pasteCombo`、`keymap` 声明控制台接入方式、客体粘贴组合键与键位映射。`driver.console`、`host.secret.materialize`、`host.download` 与 `host.elevate.request` 均已进入稳定契约,并在 Sidecar 握手特性列表中宣告。声明 `pluginApi` 1.3 或更高范围的插件,其虚拟机与控制台方法的请求中未定义的字段会以 JSON-RPC `-32602` 拒绝;更早的插件继续忽略未知字段,以便已发布插件在宿主补齐字段前照常工作。
## 客体驱动的 Sidecar 协议
+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 宿主机实测验证。
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "reims-go-frontend",
"private": true,
"version": "0.2.13",
"version": "0.2.15",
"type": "module",
"scripts": {
"dev": "vite",
+1 -1
View File
@@ -1 +1 @@
5cadb9d7959628b248656a4d92bd9c1a
e81d377cfdb873b5f163107395859d09
+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"];
+48 -61
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,54 +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
fullscreenHotkey host.FullscreenHotkeyService
fullscreenSyncMu sync.Mutex
fullscreenTargets fullscreenHotkeyTargetCache
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
@@ -203,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,
@@ -309,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 {
@@ -545,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,
}
@@ -622,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("")
}
@@ -839,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
}
+316
View File
@@ -0,0 +1,316 @@
package app
import (
"context"
"sort"
"time"
"github.com/Nwflower/reims-go/internal/driver"
)
// heldInputIdleTimeout bounds how long a plugin may leave a key or a pointer
// button held in a guest without touching that console again. A plugin that
// stops calling without releasing must not leave the guest stuck with a
// modifier down, so the record carries its own timer instead of waiting for the
// plugin's next call.
var heldInputIdleTimeout = 2 * time.Minute
// heldReleaseRetryTimeout is how long the host waits before trying a fallback
// release again. A release can fail while the VM is still running, for example
// while its console is busy, and a plugin that already exited will never make
// the next call that would otherwise retry it.
var heldReleaseRetryTimeout = 30 * time.Second
// heldReleaseTimeout bounds one fallback release, which runs while the plugin
// that held the input may already be gone.
const heldReleaseTimeout = 5 * time.Second
// heldInputs is what one plugin currently holds in one guest. QEMU and a
// driver's own console keep a pressed key or button down in the guest until a
// release arrives, and that state does not depend on the connection, so the
// host has to remember what it pressed and lift it when the plugin can no
// longer do so.
type heldInputs struct {
keys map[string]bool
buttons map[string]bool
touched time.Time
timer *time.Timer
// generation counts every change to this record. A release that finishes
// after the plugin pressed something new compares it with the generation it
// snapshotted, so it never deletes a press it did not lift.
generation uint64
}
// noteHeldKey records or forgets one key transition. code must already be a
// QKeyCode.
func (a *App) noteHeldKey(pluginID, vmKey, code string, down bool) {
a.hostAPI.heldMu.Lock()
defer a.hostAPI.heldMu.Unlock()
held := a.heldLocked(pluginID, vmKey)
if down {
held.keys[code] = true
} else {
delete(held.keys, code)
}
a.touchHeldLocked(pluginID, vmKey, held)
}
// noteHeldButton records or forgets one pointer button transition.
func (a *App) noteHeldButton(pluginID, vmKey, button string, down bool) {
a.hostAPI.heldMu.Lock()
defer a.hostAPI.heldMu.Unlock()
held := a.heldLocked(pluginID, vmKey)
if down {
held.buttons[button] = true
} else {
delete(held.buttons, button)
}
a.touchHeldLocked(pluginID, vmKey, held)
}
// 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.hostAPI.computerUseHeld == nil {
a.hostAPI.computerUseHeld = map[string]map[string]*heldInputs{}
}
byVM := a.hostAPI.computerUseHeld[pluginID]
if byVM == nil {
byVM = map[string]*heldInputs{}
a.hostAPI.computerUseHeld[pluginID] = byVM
}
held := byVM[vmKey]
if held == nil {
held = &heldInputs{keys: map[string]bool{}, buttons: map[string]bool{}}
byVM[vmKey] = held
}
return held
}
// touchHeldLocked marks the record as changed, drops it when it holds nothing
// and rearms its idle timer otherwise. The caller holds computerUseHeldMu.
func (a *App) touchHeldLocked(pluginID, vmKey string, held *heldInputs) {
held.generation++
held.touched = time.Now()
if len(held.keys)+len(held.buttons) == 0 {
a.pruneHeldLocked(pluginID, vmKey)
return
}
a.armHeldTimerLocked(pluginID, vmKey, held, heldInputIdleTimeout)
}
// armHeldTimerLocked replaces the record's timer with one that fires after d.
// The caller holds computerUseHeldMu.
func (a *App) armHeldTimerLocked(pluginID, vmKey string, held *heldInputs, d time.Duration) {
if held.timer != nil {
held.timer.Stop()
}
held.timer = time.AfterFunc(d, func() {
a.releaseHeldForVM(pluginID, vmKey)
})
}
// 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.hostAPI.computerUseHeld[pluginID]
if byVM == nil {
return
}
if held := byVM[vmKey]; held != nil {
if held.timer != nil {
held.timer.Stop()
held.timer = nil
}
delete(byVM, vmKey)
}
if len(byVM) == 0 {
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.hostAPI.heldMu.Lock()
defer a.hostAPI.heldMu.Unlock()
byVM := a.hostAPI.computerUseHeld[pluginID]
if byVM == nil {
return nil, nil, 0
}
held := byVM[vmKey]
if held == nil {
return nil, nil, 0
}
for code := range held.keys {
keys = append(keys, code)
}
for button := range held.buttons {
buttons = append(buttons, button)
}
sort.Strings(keys)
sort.Strings(buttons)
return keys, buttons, held.generation
}
// heldGeneration returns the record's current generation, or 0 when there is
// no record.
func (a *App) heldGeneration(pluginID, vmKey string) uint64 {
a.hostAPI.heldMu.Lock()
defer a.hostAPI.heldMu.Unlock()
if held := a.hostAPI.computerUseHeld[pluginID][vmKey]; held != nil {
return held.generation
}
return 0
}
// heldVMs lists the VMs one plugin currently holds input in.
func (a *App) heldVMs(pluginID string) map[string]bool {
a.hostAPI.heldMu.Lock()
defer a.hostAPI.heldMu.Unlock()
out := map[string]bool{}
for vmKey := range a.hostAPI.computerUseHeld[pluginID] {
out[vmKey] = true
}
return out
}
// dropHeld forgets the named keys and buttons of one plugin and VM. It is used
// 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.hostAPI.heldMu.Lock()
defer a.hostAPI.heldMu.Unlock()
held := a.hostAPI.computerUseHeld[pluginID][vmKey]
if held == nil {
return
}
for _, code := range keys {
delete(held.keys, code)
}
for _, button := range buttons {
delete(held.buttons, button)
}
a.touchHeldLocked(pluginID, vmKey, held)
}
// dropHeldIfGeneration forgets the named keys and buttons only when the record
// has not changed since generation was read. A record that changed in the
// 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.hostAPI.heldMu.Lock()
defer a.hostAPI.heldMu.Unlock()
held := a.hostAPI.computerUseHeld[pluginID][vmKey]
if held == nil {
return false
}
if held.generation != generation {
return false
}
for _, code := range keys {
delete(held.keys, code)
}
for _, button := range buttons {
delete(held.buttons, button)
}
a.touchHeldLocked(pluginID, vmKey, held)
return true
}
// 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.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
}
a.armHeldTimerLocked(pluginID, vmKey, held, heldReleaseRetryTimeout)
}
// forgetHeld drops the record of one plugin and VM without touching the
// guest. It is for a VM that is not running: nothing in a powered-off guest
// 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.hostAPI.heldMu.Lock()
defer a.hostAPI.heldMu.Unlock()
a.pruneHeldLocked(pluginID, vmKey)
}
// heldConsoleRoute resolves the console a held release has to go through. It
// reports false when the VM is gone or not running, because then nothing can
// be held in it.
func (a *App) heldConsoleRoute(vmKey string) (consoleRoute, bool) {
ref, ok := driver.ParseVMRef(vmKey)
if !ok {
return consoleRoute{}, false
}
vm, err := a.resolveVMInfo(ref.DriverID, ref.Name)
if err != nil {
return consoleRoute{}, false
}
current, ok := a.polledVMForDriver(vm.DriverID, vm.Name)
if !ok || current.State != "running" {
return consoleRoute{}, false
}
if vm.Directory == "" {
vm.Directory = current.Dir
}
route, err := a.resolveConsoleRoute(vm)
if err != nil {
return consoleRoute{}, false
}
route.vm = vm
return route, true
}
// releaseHeldForVM lifts everything one plugin still holds in one VM. It is the
// fallback for a plugin that can no longer release: its process exited, its
// scope was disposed, or it stopped calling. A VM that is not running has
// nothing held, so its record is dropped instead of retried. A release that
// fails while the VM is running keeps its record and is retried.
func (a *App) releaseHeldForVM(pluginID, vmKey string) {
keys, buttons, generation := a.heldSnapshot(pluginID, vmKey)
if len(keys)+len(buttons) == 0 {
a.forgetHeld(pluginID, vmKey)
return
}
route, ok := a.heldConsoleRoute(vmKey)
if !ok {
a.forgetHeld(pluginID, vmKey)
return
}
// The plugin may have pressed something since the snapshot; lifting now
// would undo that press, so wait for the record to settle instead.
if a.heldGeneration(pluginID, vmKey) != generation {
a.rearmHeld(pluginID, vmKey)
return
}
ctx, cancel := context.WithTimeout(context.Background(), heldReleaseTimeout)
defer cancel()
if err := a.consoleRelease(ctx, route, keys, buttons); err != nil {
// The VM may have stopped while the release was in flight.
if _, stillRunning := a.heldConsoleRoute(vmKey); !stillRunning {
a.forgetHeld(pluginID, vmKey)
return
}
a.emitLog("plugin", "Could not release input held by "+pluginID+" in "+vmKey+": "+err.Error())
a.rearmHeld(pluginID, vmKey)
return
}
if !a.dropHeldIfGeneration(pluginID, vmKey, keys, buttons, generation) {
// Something was pressed while the release was in flight. The record
// keeps it, and its timer lifts it if the plugin goes quiet again.
a.rearmHeld(pluginID, vmKey)
}
}
// releaseHeldForPlugin lifts everything one plugin holds in any VM.
func (a *App) releaseHeldForPlugin(pluginID string) {
for vmKey := range a.heldVMs(pluginID) {
a.releaseHeldForVM(pluginID, vmKey)
}
}
+239 -235
View File
@@ -14,24 +14,20 @@ import (
"time"
"unicode/utf8"
"github.com/Nwflower/reims-go/internal/console"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/thumb"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
const computerUsePreviewWidth = 1280
const computerUseMaxImageWidth = 2560
const computerUseMinImageWidth = 64
const computerUseMaxTextRunes = 4000
const computerUseSecretPluginID = "reims.agent"
const computerUseOwnershipFile = ".reims-go-computer-use"
const computerUseCloneRequestPrefix = "__agent-"
const computerUseCloneNamePrefix = "reims-agent-"
func isComputerUseCloneName(name string) bool {
return strings.HasPrefix(name, computerUseCloneNamePrefix) || strings.HasPrefix(name, computerUseCloneRequestPrefix)
}
type computerUseOwnership struct {
Version int `json:"version"`
@@ -44,52 +40,45 @@ type computerUseOwnership struct {
SourceVM string `json:"source_vm,omitempty"`
}
// computerUseHostHandlers serves the VM and console Host API. Every method is
// registered through hostMethod, which authorizes from the contract catalog in
// pkg/pluginproto and audits under the method name.
func (a *App) computerUseHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
if mgr == nil || mgr.Broker() == nil {
return nil
}
handlers := map[string]plugin.RPCRequestHandler{
"host/vm.list": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:read", "host/vm.list", a.handleComputerUseVMList),
"host/vm.get": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:read", "host/vm.get", a.handleComputerUseVMGet),
"host/vm.start": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.start", a.handleComputerUseVMStart),
"host/vm.shutdown": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.shutdown", a.handleComputerUseVMShutdown),
"host/vm.suspend": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.suspend", a.handleComputerUseVMStateChange(a.SuspendVM)),
"host/vm.resume": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.resume", a.handleComputerUseVMStateChange(a.ResumeVM)),
"host/vm.clone": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.clone", a.handleComputerUseVMClone),
"host/vm.delete": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.delete", a.handleComputerUseVMDelete),
"host/vm.snapshot.list": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:read", "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList),
"host/vm.snapshot.create": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.snapshot.create", a.handleComputerUseVMSnapshotCreate),
"host/vm.snapshot.restore": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.snapshot.restore", a.handleComputerUseVMSnapshotRestore),
"host/console.screenshot": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:screen", "host/console.screenshot", a.handleComputerUseScreenshot),
"host/console.pointer": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.pointer", a.handleComputerUsePointer),
"host/console.key": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.key", a.handleComputerUseKey),
"host/console.type": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.type", a.handleComputerUseType),
"host/console.release": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.release", a.handleComputerUseRelease),
return map[string]plugin.RPCRequestHandler{
"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),
}
// The plugin ID is supplied by the manager while wiring the sidecar, never
// by the channel payload. Keep the handler registered for a stable method
// table, then reject every plugin except the official MCP service below.
handlers["host/console.typeSecret"] = a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.typeSecret", a.handleComputerUseTypeSecret)
return handlers
}
type computerUseVMHandler func(context.Context, json.RawMessage, *plugin.Manager, string) (any, error)
func (a *App) authorizedComputerUseVMHandler(mgr *plugin.Manager, pluginID, permission, method string, run computerUseVMHandler) plugin.RPCRequestHandler {
return a.authorizedComputerUseHandler(mgr, pluginID, permission, method, func(ctx context.Context, raw json.RawMessage) (any, error) {
return run(ctx, raw, mgr, pluginID)
})
}
// handleComputerUseTypeSecret types one of the calling plugin's own settings
// into a VM the user authorized that plugin to access. The host never returns
// the value, so a plugin can use a secret it stored without ever reading it.
// The method is open to every plugin that holds qmp:write; the user's per-VM
// access consent is the only gate, and the audit log records the setting name
// and its length.
func (a *App) handleComputerUseTypeSecret(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
if pluginID != computerUseSecretPluginID {
return nil, errors.New("secret typing is reserved for reims.agent")
}
var req struct {
VM string `json:"vm"`
Setting string `json:"setting"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.TypeSecretParams](mgr, pluginID, "host/console.typeSecret", raw)
if err != nil {
return nil, err
}
if strings.TrimSpace(req.Setting) == "" {
@@ -126,15 +115,18 @@ func (a *App) handleComputerUseTypeSecret(ctx context.Context, raw json.RawMessa
if err != nil {
return nil, err
}
return map[string]any{"characters": count}, nil
return pluginproto.CharactersResult{Characters: count}, nil
}
func (a *App) handleComputerUseVMList(ctx context.Context, _ json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
func (a *App) handleComputerUseVMList(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
if _, err := decodeHostParams[struct{}](mgr, pluginID, "host/vm.list", raw); err != nil {
return nil, err
}
items, err := a.listVMsInternal(ctx)
if err != nil {
return nil, err
}
vms := make([]map[string]any, 0, len(items))
vms := make([]pluginproto.VMView, 0, len(items))
for _, item := range items {
info, err := a.resolveVMInfo(item.DriverID, item.Name)
if err != nil {
@@ -142,14 +134,12 @@ func (a *App) handleComputerUseVMList(ctx context.Context, _ json.RawMessage, mg
}
vms = append(vms, a.computerUseVMView(info, mgr, pluginID))
}
return map[string]any{"vms": vms}, nil
return pluginproto.VMListResult{VMs: vms}, nil
}
func (a *App) handleComputerUseVMGet(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, "host/vm.get", raw)
if err != nil {
return nil, err
}
info, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
@@ -159,45 +149,43 @@ func (a *App) handleComputerUseVMGet(_ context.Context, raw json.RawMessage, mgr
return a.computerUseVMView(info, mgr, pluginID), nil
}
func (a *App) computerUseVMView(vm driver.VMInfo, mgr *plugin.Manager, pluginID string) map[string]any {
func (a *App) computerUseVMView(vm driver.VMInfo, mgr *plugin.Manager, pluginID string) pluginproto.VMView {
accessEnabled := a.computerUseVMAccessEnabled(mgr, pluginID, vm.Ref().Key())
view := map[string]any{
"vm": vm.Ref().Key(),
"name": vm.Name,
"driver_id": vm.DriverID,
"state": vm.State,
"authorized": accessEnabled,
"phase": computerUseVMPhase(vm),
"owned": a.computerUseOwned(pluginID, vm.Ref().Key()),
view := pluginproto.VMView{
VM: vm.Ref().Key(),
Name: vm.Name,
DriverID: vm.DriverID,
State: vm.State,
Authorized: accessEnabled,
Phase: computerUseVMPhase(vm),
Owned: a.computerUseOwned(pluginID, vm.Ref().Key()),
}
if vm.CPUs > 0 {
view["cpus"] = vm.CPUs
view.CPUs = vm.CPUs
}
if vm.Memory != "" {
view["memory"] = vm.Memory
view.Memory = vm.Memory
}
if vm.DiskSummary != "" {
view["disk_summary"] = vm.DiskSummary
view.DiskSummary = vm.DiskSummary
}
if accessEnabled && vm.SSHPort > 0 {
view["ssh_port"] = vm.SSHPort
view.SSHPort = vm.SSHPort
}
if len(vm.Capabilities) > 0 {
view["capabilities"] = append([]string(nil), vm.Capabilities...)
view.Capabilities = append([]string(nil), vm.Capabilities...)
}
if accessEnabled {
if username := a.computerUseSSHUser(mgr, pluginID, vm); username != "" {
view["ssh_username"] = username
view.SSHUsername = username
}
}
return view
}
func (a *App) handleComputerUseVMStart(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, "host/vm.start", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
@@ -207,15 +195,12 @@ func (a *App) handleComputerUseVMStart(_ context.Context, raw json.RawMessage, m
if err := a.StartVM(vm.DriverID, vm.Name); err != nil {
return nil, err
}
return map[string]any{"ok": true}, nil
return pluginproto.OKResult{OK: true}, nil
}
func (a *App) handleComputerUseVMShutdown(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Force bool `json:"force"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.VMShutdownParams](mgr, pluginID, "host/vm.shutdown", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
@@ -225,15 +210,13 @@ func (a *App) handleComputerUseVMShutdown(_ context.Context, raw json.RawMessage
if err := a.StopVM(vm.DriverID, vm.Name, req.Force); err != nil {
return nil, err
}
return map[string]any{"ok": true}, nil
return pluginproto.OKResult{OK: true}, nil
}
func (a *App) handleComputerUseVMStateChange(change func(driverID, name string) error) computerUseVMHandler {
func (a *App) handleComputerUseVMStateChange(method string, change func(driverID, name string) error) computerUseVMHandler {
return func(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, method, raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
@@ -243,34 +226,25 @@ func (a *App) handleComputerUseVMStateChange(change func(driverID, name string)
if err := change(vm.DriverID, vm.Name); err != nil {
return nil, err
}
return map[string]any{"ok": true}, nil
return pluginproto.OKResult{OK: true}, nil
}
}
func (a *App) handleComputerUseVMClone(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
CloneName string `json:"clone_name"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.VMCloneParams](mgr, pluginID, "host/vm.clone", raw)
if err != nil {
return nil, err
}
cloneName := strings.TrimSpace(req.CloneName)
if cloneName == "" {
return nil, errors.New("clone_name is required")
}
suffix, ok := strings.CutPrefix(cloneName, computerUseCloneRequestPrefix)
if !ok || suffix == "" {
return nil, errors.New("temporary MCP clone identifiers must begin with __agent- and include a suffix")
}
// Preserve the wire prefix used by released sidecars and register a valid VM name.
cloneName = computerUseCloneNamePrefix + suffix
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
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 {
@@ -294,20 +268,22 @@ func (a *App) handleComputerUseVMClone(ctx context.Context, raw json.RawMessage,
// inventory poll. Return the canonical reference immediately so callers can
// start the clone without turning a successful clone into a false failure.
a.markComputerUseOwnedVM(pluginID, cloneRef.Key(), true)
return map[string]any{"vm": cloneRef.Key(), "name": cloneName, "driver_id": vm.DriverID, "state": "stopped", "owned": true}, nil
return pluginproto.VMCloneResult{
VM: cloneRef.Key(), Name: cloneName, DriverID: vm.DriverID, State: "stopped", Owned: true,
}, nil
}
func (a *App) handleComputerUseVMDelete(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, "host/vm.delete", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveComputerUseVMInfo(req.VM)
if err != nil {
return nil, err
}
// Deleting a VM is irreversible, so it stays limited to the temporary VMs
// this plugin created. Every other VM keeps its own lifecycle.
if !a.computerUseOwned(pluginID, vm.Ref().Key()) {
return nil, a.computerUseHostError("not_authorized", "err.computer_use.not_owned", i18n.Vars{"name": vm.Name})
}
@@ -323,14 +299,14 @@ func (a *App) handleComputerUseVMDelete(ctx context.Context, raw json.RawMessage
}
removeComputerUseOwnership(vm.Directory)
a.markComputerUseOwnedVM(pluginID, vm.Ref().Key(), false)
return map[string]any{"ok": true}, nil
// The guest is gone, so nothing it held can still be held.
a.forgetHeld(pluginID, vm.Ref().Key())
return pluginproto.OKResult{OK: true}, nil
}
func (a *App) handleComputerUseVMSnapshotList(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, "host/vm.snapshot.list", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
@@ -341,15 +317,18 @@ func (a *App) handleComputerUseVMSnapshotList(ctx context.Context, raw json.RawM
if err != nil {
return nil, err
}
return map[string]any{"snapshots": snapshots}, nil
out := make([]pluginproto.Snapshot, 0, len(snapshots))
for _, snap := range snapshots {
out = append(out, pluginproto.Snapshot{
ID: snap.ID, Name: snap.Name, CreatedAt: snap.CreatedAt, VMStateBytes: snap.VMStateBytes,
})
}
return pluginproto.SnapshotListResult{Snapshots: out}, nil
}
func (a *App) handleComputerUseVMSnapshotCreate(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Name string `json:"name"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.SnapshotNameParams](mgr, pluginID, "host/vm.snapshot.create", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
@@ -359,46 +338,26 @@ func (a *App) handleComputerUseVMSnapshotCreate(_ context.Context, raw json.RawM
if err := a.CreateSnapshot(vm.DriverID, vm.Name, req.Name); err != nil {
return nil, err
}
return map[string]any{"ok": true, "name": strings.TrimSpace(req.Name)}, nil
return pluginproto.SnapshotResult{OK: true, Name: strings.TrimSpace(req.Name)}, nil
}
// handleComputerUseVMSnapshotRestore restores a snapshot of any VM the user
// authorized this plugin to access. Restoring replaces the guest's state, which
// the plugin can already stop, start and clone, so it needs no separate
// consent; the call is audited like every other VM control.
func (a *App) handleComputerUseVMSnapshotRestore(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Name string `json:"name"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.SnapshotNameParams](mgr, pluginID, "host/vm.snapshot.restore", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
if !a.computerUseOwned(pluginID, vm.Ref().Key()) {
return nil, a.computerUseHostError("confirmation_required", "err.computer_use.restore_confirmation", i18n.Vars{"name": vm.Name})
}
if err := a.RestoreSnapshot(vm.DriverID, vm.Name, req.Name); err != nil {
return nil, err
}
return map[string]any{"ok": true, "name": strings.TrimSpace(req.Name)}, nil
}
type computerUseHandler func(context.Context, json.RawMessage) (any, error)
func (a *App) authorizedComputerUseHandler(mgr *plugin.Manager, pluginID, permission, method string, run computerUseHandler) plugin.RPCRequestHandler {
return func(ctx context.Context, raw json.RawMessage) (any, error) {
broker := mgr.Broker()
if err := broker.Authorize(pluginID, permission); err != nil {
return nil, err
}
result, err := run(ctx, raw)
if err != nil {
broker.Audit(pluginID, "HOST_API_ERROR", method)
return nil, err
}
broker.Audit(pluginID, "HOST_API", method)
return result, nil
}
return pluginproto.SnapshotResult{OK: true, Name: strings.TrimSpace(req.Name)}, nil
}
// resolveComputerUseVM returns the VM and the console route Agent calls use.
@@ -413,15 +372,20 @@ func (a *App) resolveComputerUseVM(mgr *plugin.Manager, pluginID, ref string) (d
if err != nil {
return driver.VMInfo{}, consoleRoute{}, err
}
// A plugin that stopped calling mid-hold must not leave a key down.
route, err := a.resolveConsoleRoute(vm)
if err != nil {
return driver.VMInfo{}, consoleRoute{}, err
}
current, ok := a.polledVMForDriver(vm.DriverID, vm.Name)
if !ok || current.State != "running" {
// A powered-off guest holds nothing, so the record is dropped rather
// than retried: a later release could lift a key the user is pressing.
a.forgetHeld(pluginID, vm.Ref().Key())
return driver.VMInfo{}, consoleRoute{}, a.computerUseHostError("vm_not_running", "err.computer_use.vm_not_running", i18n.Vars{"name": vm.Name})
}
if route.kind == consoleRouteQMP && (current.PID == nil || *current.PID <= 0) {
a.forgetHeld(pluginID, vm.Ref().Key())
return driver.VMInfo{}, consoleRoute{}, a.computerUseHostError("vm_not_running", "err.computer_use.vm_not_running", i18n.Vars{"name": vm.Name})
}
if vm.Phase == "" {
@@ -482,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)
}
}
@@ -508,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)
}
}
}
@@ -561,8 +528,11 @@ func removeComputerUseOwnership(vmDir string) {
_ = os.Remove(filepath.Join(vmDir, computerUseOwnershipFile))
}
// readComputerUseOwnership reads the marker the host wrote when it cloned a VM
// for a plugin. The marker, not the VM name, is what makes a VM a plugin's
// temporary clone, so a plugin may name its clones freely.
func readComputerUseOwnership(vm driver.VMInfo) (computerUseOwnership, bool) {
if vm.Directory == "" || !isComputerUseCloneName(vm.Name) {
if vm.Directory == "" {
return computerUseOwnership{}, false
}
raw, err := os.ReadFile(filepath.Join(vm.Directory, computerUseOwnershipFile))
@@ -635,7 +605,7 @@ func persistComputerUseOwnership(vm driver.VMInfo, pluginID, vmKey, sourceVM str
func (a *App) syncComputerUseOwnership(vms []driver.VMListItem) {
for _, item := range vms {
vm := driver.VMInfo{Name: item.Name, DriverID: item.DriverID, Directory: item.Dir}
if vm.Directory == "" || !isComputerUseCloneName(vm.Name) {
if vm.Directory == "" {
continue
}
marker, ok := readComputerUseOwnership(vm)
@@ -644,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.
@@ -827,26 +798,23 @@ func computerUseRegionToSource(region computerUseRegion, refW, refH int, source
return computerUseRegion{X: x0, Y: y0, Width: x1 - x0, Height: y1 - y0}
}
func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Region *computerUseRegion `json:"region"`
MaxWidth int `json:"max_width"`
// Width and Height name the image the region was measured in; without
// them the region is in source pixels.
Width int `json:"width"`
Height int `json:"height"`
// computerUseScreenshotWidth returns the width the returned image is scaled
// to. A request outside the supported range is brought into it rather than
// refused, so a caller that asks for more than the host encodes still gets a
// usable frame.
func computerUseScreenshotWidth(requested int) int {
if requested == 0 {
return computerUsePreviewWidth
}
if err := json.Unmarshal(raw, &req); err != nil {
return min(max(requested, computerUseMinImageWidth), computerUseMaxImageWidth)
}
func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.ScreenshotParams](mgr, pluginID, "host/console.screenshot", raw)
if err != nil {
return nil, err
}
maxWidth := req.MaxWidth
if maxWidth == 0 {
maxWidth = computerUsePreviewWidth
}
if maxWidth < 64 || maxWidth > computerUseMaxImageWidth {
return nil, fmt.Errorf("max_width must be between 64 and %d", computerUseMaxImageWidth)
}
maxWidth := computerUseScreenshotWidth(req.MaxWidth)
if req.Region != nil && (req.Region.Width <= 0 || req.Region.Height <= 0) {
return nil, errors.New("region width and height must be positive")
}
@@ -873,7 +841,9 @@ func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessa
frame image.Image
blank bool
)
result := map[string]any{"mime_type": "image/jpeg", "source_width": sourceSize.X, "source_height": sourceSize.Y}
result := pluginproto.ScreenshotResult{
MIMEType: "image/jpeg", SourceWidth: sourceSize.X, SourceHeight: sourceSize.Y,
}
if req.Region == nil {
// A blank frame is a normal screen state during boot, login and display
// switches. Return it with a flag so pollers can keep waiting through it.
@@ -887,115 +857,149 @@ func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessa
return nil, err
}
var applied computerUseRegion
region := computerUseRegionToSource(*req.Region, req.Width, req.Height, full.Bounds().Size())
result["source_width"], result["source_height"] = full.Bounds().Dx(), full.Bounds().Dy()
region := computerUseRegionToSource(computerUseRegion{
X: req.Region.X, Y: req.Region.Y, Width: req.Region.Width, Height: req.Region.Height,
}, req.Width, req.Height, full.Bounds().Size())
result.SourceWidth, result.SourceHeight = full.Bounds().Dx(), full.Bounds().Dy()
frame, applied, err = computerUseRegionFrame(full, region, maxWidth)
if err != nil {
return nil, err
}
blank = thumb.Blank(full)
result["region"] = applied
result.Region = &pluginproto.Region{X: applied.X, Y: applied.Y, Width: applied.Width, Height: applied.Height}
}
encoded, err := thumb.JPEG(frame, 84)
if err != nil {
return nil, err
}
bounds := frame.Bounds()
result["width"] = bounds.Dx()
result["height"] = bounds.Dy()
result["blank"] = blank
result["data"] = base64.StdEncoding.EncodeToString(encoded)
result.Width = bounds.Dx()
result.Height = bounds.Dy()
result.Blank = blank
result.Data = base64.StdEncoding.EncodeToString(encoded)
return result, nil
}
// computerUseHeldButtons normalizes the pointer buttons of a held gesture the
// way consoleRelease does, so the ledger records what will be lifted later.
func computerUseHeldButtons(buttons []string) ([]string, error) {
return normalizeReleaseButtons(buttons)
}
func (a *App) handleComputerUsePointer(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Action string `json:"action"`
X int `json:"x"`
Y int `json:"y"`
Width int `json:"width"`
Height int `json:"height"`
Button string `json:"button"`
Down *bool `json:"down"`
Delta int `json:"delta"`
Horizontal bool `json:"horizontal"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
_, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
req, err := decodeHostParams[pluginproto.PointerParams](mgr, pluginID, "host/console.pointer", raw)
if err != nil {
return nil, err
}
vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
// A button left down stays down in the guest until a release arrives, so
// the host records it on both console kinds and can lift it if the plugin
// goes away.
held := req.Action == "button" && req.Down != nil
button := ""
if held {
names, err := computerUseHeldButtons([]string{req.Button})
if err != nil {
return nil, err
}
button = names[0]
if *req.Down {
a.noteHeldButton(pluginID, vm.Ref().Key(), button, true)
}
}
if err := a.consolePointer(ctx, route, driver.ConsolePointerRequest{
Action: req.Action, X: req.X, Y: req.Y, Width: req.Width, Height: req.Height,
Button: req.Button, Down: req.Down, Delta: req.Delta, Horizontal: req.Horizontal,
}); err != nil {
return nil, err
}
return map[string]any{"ok": true}, nil
if held && !*req.Down {
a.noteHeldButton(pluginID, vm.Ref().Key(), button, false)
}
return pluginproto.OKResult{OK: true}, nil
}
func (a *App) handleComputerUseKey(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Key string `json:"key"`
Modifiers []string `json:"modifiers"`
// Down holds (true) or releases (false) one key instead of pressing it.
Down *bool `json:"down"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.KeyParams](mgr, pluginID, "host/console.key", raw)
if err != nil {
return nil, err
}
if strings.TrimSpace(req.Key) == "" {
return nil, errors.New("key is required")
}
if req.Down != nil && len(req.Modifiers) > 0 {
return nil, errors.New("a held key takes no modifiers; hold each key separately")
}
_, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
if req.Down != nil {
err = a.consoleKeyState(ctx, route, req.Key, *req.Down)
} else {
err = a.consoleKey(ctx, route, req.Key, req.Modifiers)
if req.Down == nil {
if err := a.consoleKey(ctx, route, req.Key, req.Modifiers); err != nil {
return nil, err
}
return pluginproto.OKResult{OK: true}, nil
}
if err != nil {
return nil, err
// A held key may carry modifiers: each one is held or released with it, so
// a caller can hold Command and click without a second round trip.
names := append([]string{req.Key}, req.Modifiers...)
codes := make([]string, 0, len(names))
for _, name := range names {
code, err := console.NormalizeHeldKey(name)
if err != nil {
return nil, err
}
codes = append(codes, code)
}
return map[string]any{"ok": true}, nil
// Record a press before sending it: a call that never returns still left
// the key down, and the fallback release has to know about it.
if *req.Down {
for _, code := range codes {
a.noteHeldKey(pluginID, vm.Ref().Key(), code, true)
}
}
for _, code := range codes {
if err := a.consoleKeyState(ctx, route, code, *req.Down); err != nil {
return nil, err
}
}
if !*req.Down {
for _, code := range codes {
a.noteHeldKey(pluginID, vm.Ref().Key(), code, false)
}
}
return pluginproto.OKResult{OK: true}, nil
}
// handleComputerUseRelease lifts the given keys and pointer buttons in one
// report, so a client that stops mid-gesture never leaves input held.
func (a *App) handleComputerUseRelease(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Keys []string `json:"keys"`
Buttons []string `json:"buttons"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.ReleaseParams](mgr, pluginID, "host/console.release", raw)
if err != nil {
return nil, err
}
_, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
if err := a.consoleRelease(ctx, route, req.Keys, req.Buttons); err != nil {
return nil, err
}
return map[string]any{"ok": true}, nil
// Whatever the caller lifted is no longer held on the host's books either.
codes := make([]string, 0, len(req.Keys))
for _, key := range req.Keys {
if code, err := console.NormalizeHeldKey(key); err == nil {
codes = append(codes, code)
}
}
buttons, _ := computerUseHeldButtons(req.Buttons)
a.dropHeld(pluginID, vm.Ref().Key(), codes, buttons)
return pluginproto.OKResult{OK: true}, nil
}
func (a *App) handleComputerUseType(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Text string `json:"text"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.TypeParams](mgr, pluginID, "host/console.type", raw)
if err != nil {
return nil, err
}
if len(req.Text) == 0 || !utf8.ValidString(req.Text) {
@@ -1018,5 +1022,5 @@ func (a *App) handleComputerUseType(ctx context.Context, raw json.RawMessage, mg
if err != nil {
return nil, err
}
return map[string]any{"characters": n}, nil
return pluginproto.CharactersResult{Characters: n}, nil
}
+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"}
+15 -35
View File
@@ -20,6 +20,7 @@ import (
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/netproxy"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
const (
@@ -50,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": 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 {
@@ -59,22 +60,11 @@ func (a *App) downloadHostHandlers(mgr *plugin.Manager, pluginID string) map[str
a.mu.Unlock()
roots := downloadRoots(mgr, pluginID, dataRoot)
notify := func(method string, params any) { mgr.NotifySidecar(pluginID, method, params) }
res, err := a.startPluginDownload(broker, notify, pluginID, roots, raw)
if err != nil {
broker.Audit(pluginID, "HOST_API_ERROR", "host/download.start")
return nil, err
}
broker.Audit(pluginID, "HOST_API", "host/download.start")
return res, nil
},
"host/download.cancel": func(_ context.Context, raw json.RawMessage) (any, error) {
res, err := cancelPluginDownload(pluginID, raw)
if err != nil {
return nil, err
}
broker.Audit(pluginID, "HOST_API", "host/download.cancel")
return res, nil
},
return a.startPluginDownload(mgr, broker, notify, pluginID, roots, raw)
}),
"host/download.cancel": a.hostAPISvc().hostMethod(mgr, pluginID, "host/download.cancel", func(_ context.Context, raw json.RawMessage) (any, error) {
return cancelPluginDownload(mgr, pluginID, raw)
}),
}
}
@@ -222,17 +212,9 @@ type downloadEvent struct {
// startPluginDownload validates a download request and runs it in the
// background as a task. It returns the download ID at once.
func (a *App) startPluginDownload(broker *plugin.Broker, notify downloadNotifier, pluginID string, roots []string, raw json.RawMessage) (any, error) {
var req struct {
URL string `json:"url"`
SHA256 string `json:"sha256"`
SHA256URL string `json:"sha256_url"`
SHA256Name string `json:"sha256_name"`
Dest string `json:"dest"`
Size int64 `json:"size"`
Label string `json:"label"`
}
if err := json.Unmarshal(raw, &req); err != nil {
func (a *App) startPluginDownload(kernel hostMethodHost, broker *plugin.Broker, notify downloadNotifier, pluginID string, roots []string, raw json.RawMessage) (any, error) {
req, err := decodeHostParams[pluginproto.DownloadParams](kernel, pluginID, "host/download.start", raw)
if err != nil {
return nil, err
}
if err := broker.AuthorizeNetOrigin(pluginID, req.URL); err != nil {
@@ -325,15 +307,13 @@ func (a *App) startPluginDownload(broker *plugin.Broker, notify downloadNotifier
notify("download/progress", ev)
broker.Audit(pluginID, "DOWNLOAD_"+strings.ToUpper(ev.Status), id)
}()
return map[string]any{"id": id, "task_id": taskID}, nil
return pluginproto.DownloadResult{ID: id, TaskID: taskID}, nil
}
// cancelPluginDownload stops one of pluginID's own downloads.
func cancelPluginDownload(pluginID string, raw json.RawMessage) (any, error) {
var req struct {
ID string `json:"id"`
}
if err := json.Unmarshal(raw, &req); err != nil {
func cancelPluginDownload(kernel hostMethodHost, pluginID string, raw json.RawMessage) (any, error) {
req, err := decodeHostParams[pluginproto.DownloadCancelParams](kernel, pluginID, "host/download.cancel", raw)
if err != nil {
return nil, err
}
pluginDownloads.mu.Lock()
@@ -343,5 +323,5 @@ func cancelPluginDownload(pluginID string, raw json.RawMessage) (any, error) {
return nil, fmt.Errorf("no download %q of this plugin is running", req.ID)
}
d.cancel()
return map[string]any{"ok": true}, nil
return pluginproto.OKResult{OK: true}, nil
}
+4 -3
View File
@@ -17,6 +17,7 @@ import (
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/testutil/fakedriver"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
type downloadTestEnv struct {
@@ -60,11 +61,11 @@ func (e *downloadTestEnv) notify(method string, params any) {
func (e *downloadTestEnv) start(t *testing.T, pluginID string, req map[string]any) (string, error) {
t.Helper()
raw, _ := json.Marshal(req)
res, err := e.app.startPluginDownload(e.h.Broker, e.notify, pluginID, e.roots, raw)
res, err := e.app.startPluginDownload(nil, e.h.Broker, e.notify, pluginID, e.roots, raw)
if err != nil {
return "", err
}
return res.(map[string]any)["id"].(string), nil
return res.(pluginproto.DownloadResult).ID, nil
}
// final waits for the last notification of a download and returns it.
@@ -206,7 +207,7 @@ func TestHostDownloadCancelIsPerPlugin(t *testing.T) {
}
cancelBy := func(plugin string) error {
raw, _ := json.Marshal(map[string]any{"id": id})
_, err := cancelPluginDownload(plugin, raw)
_, err := cancelPluginDownload(nil, plugin, raw)
return err
}
if err := cancelBy(e.other); err == nil {
+43 -42
View File
@@ -12,6 +12,7 @@ import (
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
// elevatePromptTimeout is how long a confirmation waits for the person.
@@ -32,21 +33,15 @@ 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": func(ctx context.Context, raw json.RawMessage) (any, error) {
res, err := a.requestElevation(ctx, broker, mgr.Registry(), pluginID, raw)
if err != nil {
broker.Audit(pluginID, "HOST_API_ERROR", "host/elevate.request")
return nil, err
}
broker.Audit(pluginID, "HOST_API", "host/elevate.request")
return res, nil
},
"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)
}),
}
}
@@ -54,14 +49,9 @@ func (a *App) elevateHostHandlers(mgr *plugin.Manager, pluginID string) map[stri
// the closed action list, ask the person in the desktop window, and only after
// a yes run the action (which raises the Windows UAC prompt). A no,
// a timeout or a missing window ends the request before anything runs.
func (a *App) requestElevation(ctx context.Context, broker *plugin.Broker, reg *plugin.Registry, pluginID string, raw json.RawMessage) (any, error) {
if err := broker.Authorize(pluginID, "driver:vm"); err != nil {
return nil, err
}
var req struct {
Action string `json:"action"`
}
if err := json.Unmarshal(raw, &req); err != nil {
func (a *App) requestElevation(ctx context.Context, kernel hostMethodHost, broker *plugin.Broker, reg *plugin.Registry, pluginID string, raw json.RawMessage) (any, error) {
req, err := decodeHostParams[pluginproto.ElevateParams](kernel, pluginID, "host/elevate.request", raw)
if err != nil {
return nil, err
}
spec, ok := host.LookupElevationAction(req.Action)
@@ -70,9 +60,6 @@ func (a *App) requestElevation(ctx context.Context, broker *plugin.Broker, reg *
}
a.mu.Lock()
emit := a.elevateEmit
dismiss := a.elevateDismiss
runner := a.elevateRunner
winCtx := a.ctx
hasWindow := winCtx != nil
locale := i18n.EffectiveLocale(i18n.Auto)
@@ -80,14 +67,20 @@ func (a *App) requestElevation(ctx context.Context, broker *plugin.Broker, reg *
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,
@@ -102,19 +95,19 @@ func (a *App) requestElevation(ctx context.Context, broker *plugin.Broker, reg *
}
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
}
@@ -176,16 +169,23 @@ func (a *App) requestElevation(ctx context.Context, broker *plugin.Broker, reg *
return nil, err
}
broker.Audit(pluginID, "ELEVATE_OK", spec.Action)
return res, nil
return pluginproto.ElevateResult{
OK: res.OK,
Action: res.Action,
ExitCode: res.ExitCode,
RebootRequired: res.RebootRequired,
LogoffRequired: res.LogoffRequired,
}, nil
}
// 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
}
@@ -199,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)
}
+25 -6
View File
@@ -14,7 +14,9 @@ import (
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/testutil/fakedriver"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
type elevateTestEnv struct {
@@ -38,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
@@ -47,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}
@@ -65,9 +67,26 @@ func newElevateTestEnv(t *testing.T) *elevateTestEnv {
return e
}
// testHostMethodHost lets a test serve a host/* method through the same
// catalog-driven wrapper the app registers, without a full plugin manager.
type testHostMethodHost struct {
broker *plugin.Broker
reg *plugin.Registry
}
func (h testHostMethodHost) Broker() *plugin.Broker { return h.broker }
func (h testHostMethodHost) Registry() *plugin.Registry { return h.reg }
func (e *elevateTestEnv) kernel() testHostMethodHost {
return testHostMethodHost{broker: e.h.Broker, reg: e.h.Registry}
}
func (e *elevateTestEnv) request(ctx context.Context, pluginID, action string) (any, error) {
raw, _ := json.Marshal(map[string]any{"action": action})
return e.app.requestElevation(ctx, e.h.Broker, e.h.Registry, pluginID, raw)
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)
}
func (e *elevateTestEnv) promptCount() int {
@@ -119,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)
@@ -155,7 +174,7 @@ func TestElevationApprovedRunsTheActionOnce(t *testing.T) {
if err != nil {
t.Fatal(err)
}
got, ok := res.(host.ElevationResult)
got, ok := res.(pluginproto.ElevateResult)
if !ok || !got.OK || !got.RebootRequired {
t.Fatalf("result = %#v", res)
}
+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)
+101
View File
@@ -0,0 +1,101 @@
package app
import (
"context"
"encoding/json"
"errors"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
// hostMethodHandler serves one host/* request. The caller has already been
// authorized for the method.
type hostMethodHandler func(ctx context.Context, raw json.RawMessage) (any, error)
// hostMethodHost is what serving a host/* method needs from the plugin kernel.
// *plugin.Manager satisfies it; a test can supply a broker and a registry.
type hostMethodHost interface {
Broker() *plugin.Broker
Registry() *plugin.Registry
}
// authorizeHostMethod checks every permission the contract catalog lists for
// method. A method whose authorization depends on the request URL carries
// pluginproto.OriginPermission and is authorized by its own handler, which is
// the only place that sees the URL.
func authorizeHostMethod(host hostMethodHost, pluginID, method string) error {
spec, ok := pluginproto.Lookup(method)
if !ok {
return &plugin.RPCError{Code: plugin.RPCMethodNotFound, Message: "method not found: " + method}
}
if host == nil || host.Broker() == nil {
return errors.New("plugin manager is unavailable")
}
for _, perm := range spec.Permissions {
if perm == pluginproto.OriginPermission {
continue
}
if err := host.Broker().Authorize(pluginID, perm); err != nil {
return err
}
}
return nil
}
// strictHostParams reports whether requests of pluginID to method are decoded
// strictly. Only a plugin that declares pluginApi 1.3 or newer opts in, so a
// released plugin sending a field this host has not implemented keeps working
// until it is updated, while a new plugin learns about a typo at once.
func strictHostParams(host hostMethodHost, pluginID, method string) bool {
spec, ok := pluginproto.Lookup(method)
if !ok || !spec.StrictParams || host == nil {
return false
}
manifest, found := host.Registry().ManifestOf(pluginID)
if !found || manifest.Engines.PluginAPI == "" {
return false
}
return plugin.RangeRequiresAtLeast(manifest.Engines.PluginAPI, pluginproto.StrictParamsVersion)
}
// decodeHostParams decodes one host request through the shared contract types
// and answers a request the contract rejects with JSON-RPC -32602.
func decodeHostParams[T any](host hostMethodHost, pluginID, method string, raw json.RawMessage) (T, error) {
out, err := pluginproto.DecodeParams[T](method, raw, strictHostParams(host, pluginID, method))
if err != nil {
var invalid *pluginproto.InvalidParamsError
if errors.As(err, &invalid) {
return out, &plugin.RPCError{Code: plugin.RPCInvalidParams, Message: invalid.Error()}
}
return out, err
}
return out, nil
}
// hostMethod wraps one host/* method: it authorizes from the contract catalog,
// 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 (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
}
result, err := run(ctx, raw)
broker := host.Broker()
if err != nil {
broker.Audit(pluginID, "HOST_API_ERROR", method)
return nil, err
}
broker.Audit(pluginID, "HOST_API", method)
return result, nil
}
}
// hostVMMethod wraps a handler that needs the manager and the calling plugin.
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
}
+307
View File
@@ -0,0 +1,307 @@
package app
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
const hostContractPlugin = "test.host.contract"
// newHostContractEnv builds a plugin manager with one plugin whose manifest a
// test can vary, plus an App that serves the host API through it.
func newHostContractEnv(t *testing.T, manifest plugin.Manifest) (*App, *plugin.Manager) {
t.Helper()
cfg := config.Default()
cfg.DataRoot = t.TempDir()
mgr, err := plugin.NewManager(plugin.ManagerOptions{DataRoot: cfg.DataRoot, HostVersion: "0.0.0"})
if err != nil {
t.Fatal(err)
}
t.Cleanup(mgr.Close)
manifest.ID = hostContractPlugin
manifest.Version = "1.0.0"
manifest.Name = plugin.LocalizedText{EnUS: hostContractPlugin}
if err := mgr.Registry().Register(plugin.PluginDef{
Manifest: manifest,
Source: plugin.SourceBuiltin,
Desired: true,
Activate: func(context.Context, *plugin.Scope) error { return nil },
}); err != nil {
t.Fatal(err)
}
mgr.Registry().Reconcile(context.Background())
return &App{cfg: cfg, pluginMgr: mgr}, mgr
}
// TestEveryStableHostMethodIsServed is the gate that keeps the host and the
// contract catalog from drifting: every stable method must be implemented
// somewhere, and nothing may be served that the catalog does not list.
func TestEveryStableHostMethodIsServed(t *testing.T) {
app, mgr := newHostContractEnv(t, plugin.Manifest{})
served := map[string]bool{}
for _, method := range plugin.ReverseHostAPIMethods() {
served[method] = true
}
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)
}
served[method] = true
}
for _, method := range pluginproto.Methods() {
spec, _ := pluginproto.Lookup(method)
if spec.Status != pluginproto.StatusStable {
continue
}
if !served[method] {
t.Errorf("%s is stable in the catalog but nothing serves it", method)
}
}
}
// TestCataloguedPermissionsAreReal checks that every permission a method
// declares is one the permission classifier knows, so a typo cannot silently
// turn a method into an always-denied or always-allowed one.
func TestCataloguedPermissionsAreReal(t *testing.T) {
for _, method := range pluginproto.Methods() {
spec, _ := pluginproto.Lookup(method)
for _, perm := range spec.Permissions {
if perm == pluginproto.OriginPermission {
continue
}
if plugin.ClassifyPermission(perm) == plugin.PermForbidden {
t.Errorf("%s requires %q, which the host does not recognize", method, perm)
}
}
}
}
// TestReadingSnapshotsNeedsOnlyReadPermission keeps the catalog from asking for
// more than the operation needs.
func TestReadingSnapshotsNeedsOnlyReadPermission(t *testing.T) {
spec, ok := pluginproto.Lookup("host/vm.snapshot.list")
if !ok || len(spec.Permissions) != 1 || spec.Permissions[0] != "vm:read" {
t.Fatalf("host/vm.snapshot.list requires %v, want vm:read only", spec.Permissions)
}
}
func TestStrictParamsFollowTheDeclaredPluginAPI(t *testing.T) {
cases := map[string]bool{
"": false,
"^1.1.0": false,
"^1.2.0": false,
"^1.3.0": true,
">=1.3.0": true,
}
for engines, want := range cases {
_, mgr := newHostContractEnv(t, plugin.Manifest{Engines: plugin.Engines{PluginAPI: engines}})
raw := json.RawMessage(`{"vm":"a","max_width":640,"nope":1}`)
_, err := decodeHostParams[pluginproto.ScreenshotParams](mgr, hostContractPlugin, "host/console.screenshot", raw)
var rpcErr *plugin.RPCError
strict := errors.As(err, &rpcErr) && rpcErr.Code == plugin.RPCInvalidParams
if strict != want {
t.Errorf("pluginApi %q: strict = %v (%v), want %v", engines, strict, err, want)
}
}
}
func TestUnknownFieldIsRejectedWithInvalidParams(t *testing.T) {
_, mgr := newHostContractEnv(t, plugin.Manifest{Engines: plugin.Engines{PluginAPI: "^1.3.0"}})
_, err := decodeHostParams[pluginproto.KeyParams](mgr, hostContractPlugin, "host/console.key",
json.RawMessage(`{"vm":"a","key":"cmd","down":true,"hold_ms":5}`))
var rpcErr *plugin.RPCError
if !errors.As(err, &rpcErr) || rpcErr.Code != plugin.RPCInvalidParams {
t.Fatalf("err = %v, want JSON-RPC %d", err, plugin.RPCInvalidParams)
}
if !strings.Contains(rpcErr.Message, "hold_ms") {
t.Fatalf("message %q does not name the offending field", rpcErr.Message)
}
}
func TestShutdownForceReachesTheHost(t *testing.T) {
_, mgr := newHostContractEnv(t, plugin.Manifest{Engines: plugin.Engines{PluginAPI: "^1.3.0"}})
req, err := decodeHostParams[pluginproto.VMShutdownParams](mgr, hostContractPlugin, "host/vm.shutdown",
json.RawMessage(`{"vm":"a","force":true}`))
if err != nil {
t.Fatalf("a known field was rejected: %v", err)
}
if !req.Force || req.VM != "a" {
t.Fatalf("request = %+v, want force on vm a", req)
}
if _, err := decodeHostParams[pluginproto.VMShutdownParams](mgr, hostContractPlugin, "host/vm.shutdown",
json.RawMessage(`{"vm":"a","hard":true}`)); err == nil {
t.Fatal("an undefined field was accepted")
}
}
// TestSecretTypingIsOpenToEveryAuthorizedPlugin checks that typing a secret is
// no longer reserved for one plugin id: any plugin reaches the same path and
// is stopped only by the VM reference and the user's per-VM access consent.
func TestSecretTypingIsOpenToEveryAuthorizedPlugin(t *testing.T) {
app, mgr := newHostContractEnv(t, plugin.Manifest{})
_, err := app.handleComputerUseTypeSecret(context.Background(),
json.RawMessage(`{"vm":"","setting":"login_password"}`), mgr, hostContractPlugin)
if err == nil {
t.Fatal("an empty VM reference was accepted")
}
if strings.Contains(err.Error(), "reserved for") {
t.Fatalf("err = %v, want no plugin-id refusal", err)
}
}
// TestCloneOwnershipDoesNotDependOnTheName checks that a plugin may name its
// temporary clones freely: the marker the host writes is what makes a VM a
// clone.
func TestCloneOwnershipDoesNotDependOnTheName(t *testing.T) {
dir := t.TempDir()
vm := driver.VMInfo{Name: "my-own-name", DriverID: "acme.driver", Directory: dir}
key := vm.Ref().Key()
if err := writeComputerUseOwnership(dir, hostContractPlugin, key, ""); err != nil {
t.Fatal(err)
}
marker, ok := readComputerUseOwnership(vm)
if !ok || marker.PluginID != hostContractPlugin || marker.VMKey != key {
t.Fatalf("marker = %+v, ok = %v", marker, ok)
}
}
func TestScreenshotWidthIsBroughtIntoRange(t *testing.T) {
cases := map[int]int{
0: computerUsePreviewWidth,
-5: computerUseMinImageWidth,
1: computerUseMinImageWidth,
640: 640,
9999: computerUseMaxImageWidth,
}
for requested, want := range cases {
if got := computerUseScreenshotWidth(requested); got != want {
t.Errorf("max_width %d = %d, want %d", requested, got, want)
}
}
}
func TestHeldLedgerTracksAndForgets(t *testing.T) {
app := &App{}
const vmKey = "driver:vm"
app.noteHeldKey("p", vmKey, "meta_l", true)
app.noteHeldButton("p", vmKey, "left", true)
app.noteHeldKey("p", vmKey, "a", true)
keys, buttons, _ := app.heldSnapshot("p", vmKey)
if len(keys) != 2 || len(buttons) != 1 {
t.Fatalf("held = %v %v", keys, buttons)
}
// Releasing one key keeps the rest.
app.dropHeld("p", vmKey, []string{"a"}, nil)
if keys, _, _ := app.heldSnapshot("p", vmKey); len(keys) != 1 || keys[0] != "meta_l" {
t.Fatalf("keys after drop = %v", keys)
}
// Lifting everything leaves no record behind.
app.dropHeld("p", vmKey, []string{"meta_l"}, []string{"left"})
if vms := app.heldVMs("p"); len(vms) != 0 {
t.Fatalf("ledger still holds %v", vms)
}
// A VM that is not running is forgotten without touching a console.
app.noteHeldKey("p", vmKey, "shift", true)
app.forgetHeld("p", vmKey)
if vms := app.heldVMs("p"); len(vms) != 0 {
t.Fatalf("ledger still holds %v after forget", vms)
}
}
// TestHeldLedgerKeepsAPressMadeDuringARelease checks that a release which
// finished after the plugin pressed something new does not delete that press
// from the record: the fallback would then no longer know to lift it.
func TestHeldLedgerKeepsAPressMadeDuringARelease(t *testing.T) {
app := &App{}
const vmKey = "driver:vm"
app.noteHeldKey("p", vmKey, "meta_l", true)
keys, buttons, generation := app.heldSnapshot("p", vmKey)
// The plugin presses another key while the release is in flight.
app.noteHeldKey("p", vmKey, "shift", true)
if app.dropHeldIfGeneration("p", vmKey, keys, buttons, generation) {
t.Fatal("a stale release deleted a press it did not lift")
}
if keys, _, _ := app.heldSnapshot("p", vmKey); len(keys) != 2 {
t.Fatalf("keys = %v, want both presses kept", keys)
}
// A release whose snapshot is still current does clear the record.
keys, buttons, generation = app.heldSnapshot("p", vmKey)
if !app.dropHeldIfGeneration("p", vmKey, keys, buttons, generation) {
t.Fatal("a current release was refused")
}
if vms := app.heldVMs("p"); len(vms) != 0 {
t.Fatalf("ledger still holds %v", vms)
}
}
// TestHeldLedgerRetriesAfterTheIdleTimeout checks that a record whose fallback
// release could not run keeps a timer: a plugin that already exited never
// makes the call that would otherwise retry it.
func TestHeldLedgerRetriesAfterTheIdleTimeout(t *testing.T) {
previousIdle, previousRetry := heldInputIdleTimeout, heldReleaseRetryTimeout
heldInputIdleTimeout = time.Hour
heldReleaseRetryTimeout = 20 * time.Millisecond
t.Cleanup(func() { heldInputIdleTimeout, heldReleaseRetryTimeout = previousIdle, previousRetry })
app := &App{}
app.noteHeldKey("p", "driver:vm", "meta_l", true)
app.rearmHeld("p", "driver:vm")
deadline := time.Now().Add(2 * time.Second)
for len(app.heldVMs("p")) > 0 && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
// The VM is not running here, so the retry drops the record instead of
// leaving a key pressed forever.
if vms := app.heldVMs("p"); len(vms) != 0 {
t.Fatalf("the retry left %v behind", vms)
}
}
// TestHeldLedgerReleasesAfterTheIdleTimeout checks that a plugin which stops
// calling mid-hold does not leave the guest stuck: the record carries its own
// timer, and a VM that is not running has nothing left to lift.
func TestHeldLedgerReleasesAfterTheIdleTimeout(t *testing.T) {
previous := heldInputIdleTimeout
heldInputIdleTimeout = 20 * time.Millisecond
t.Cleanup(func() { heldInputIdleTimeout = previous })
app := &App{}
app.noteHeldKey("p", "driver:vm", "meta_l", true)
if vms := app.heldVMs("p"); len(vms) != 1 {
t.Fatalf("ledger = %v, want one record", vms)
}
deadline := time.Now().Add(2 * time.Second)
for len(app.heldVMs("p")) > 0 && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
if vms := app.heldVMs("p"); len(vms) != 0 {
t.Fatalf("the idle timer left %v behind", vms)
}
}
func TestHeldLedgerIsPerPlugin(t *testing.T) {
app := &App{}
app.noteHeldKey("p1", "driver:vm", "meta_l", true)
if vms := app.heldVMs("p2"); len(vms) != 0 {
t.Fatalf("another plugin sees %v", vms)
}
if vms := app.heldVMs("p1"); len(vms) != 1 {
t.Fatalf("own record = %v", vms)
}
}
+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 {
Loaded 100 of 278 files, more files were not shown because too many files have changed in this diff. Show more