Compare commits

...
20 Commits
Author SHA1 Message Date
千川白浪 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
千川白浪 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
千川白浪 e180b55a7b fix(vm): fall back to automatic GPU selection for stale Vulkan manifests 2026-12-05 02:34:20 -07:00
千川白浪 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
千川白浪 892d67644b fix(runtime): fall back to Reims-Go releases 2026-12-05 02:19:03 -07:00
千川白浪 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
千川白浪 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
千川白浪 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
千川白浪 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
224 changed files with 8095 additions and 6234 deletions

No files matched your search

+1
View File
@@ -24,6 +24,7 @@ concurrency:
jobs: jobs:
plan: plan:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 10
permissions: permissions:
contents: write contents: write
outputs: outputs:
+26 -2
View File
@@ -3,8 +3,24 @@ name: CI
on: on:
push: push:
branches: [main] branches: [main]
paths-ignore:
- 'docs/**'
- 'README.md'
- 'README.*.md'
- 'AGENTS.md'
- '.github/ISSUE_TEMPLATE/**'
- '.github/PULL_REQUEST_TEMPLATE.md'
- '.github/readme/**'
pull_request: pull_request:
branches: [main] branches: [main]
paths-ignore:
- 'docs/**'
- 'README.md'
- 'README.*.md'
- 'AGENTS.md'
- '.github/ISSUE_TEMPLATE/**'
- '.github/PULL_REQUEST_TEMPLATE.md'
- '.github/readme/**'
concurrency: concurrency:
group: ci-${{ github.event.pull_request.number || github.ref }} group: ci-${{ github.event.pull_request.number || github.ref }}
@@ -16,6 +32,7 @@ env:
jobs: jobs:
verify: verify:
runs-on: windows-latest runs-on: windows-latest
timeout-minutes: 30
outputs: outputs:
rolling: ${{ steps.rolling.outputs.publish }} rolling: ${{ steps.rolling.outputs.publish }}
steps: steps:
@@ -28,8 +45,15 @@ jobs:
PREVIOUS_SHA: ${{ github.event.before }} PREVIOUS_SHA: ${{ github.event.before }}
shell: pwsh shell: pwsh
run: | run: |
$publish = $true # Read the commit object so shallow checkouts retain its parent headers.
if ($env:PREVIOUS_SHA -notmatch '^0+$') { $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 git fetch --depth=1 origin $env:PREVIOUS_SHA
if ($LASTEXITCODE -ne 0) { throw 'Could not fetch the previous main commit' } 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/**' $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: jobs:
dev-release: dev-release:
runs-on: windows-latest runs-on: windows-latest
timeout-minutes: 30
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with: with:
@@ -136,6 +137,8 @@ jobs:
- name: Build Windows x64 binary - name: Build Windows x64 binary
shell: pwsh shell: pwsh
env:
CGO_ENABLED: "0"
run: | run: |
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
$ver = $env:DEV_VERSION $ver = $env:DEV_VERSION
+3
View File
@@ -25,6 +25,7 @@ env:
jobs: jobs:
release: release:
runs-on: windows-latest runs-on: windows-latest
timeout-minutes: 30
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with: with:
@@ -102,6 +103,8 @@ jobs:
- name: Build Windows x64 binary - name: Build Windows x64 binary
shell: pwsh shell: pwsh
env:
CGO_ENABLED: "0"
run: | run: |
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
$tag = $env:RELEASE_TAG $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). 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 ## v0.2.13 — 2026-12-04
[中文](#cn-v0.2.13) | [English](#en-v0.2.13) [中文](#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)."
}
@@ -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."
}
+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 的客体命令和文件传输。 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` | 清单结构、扩展点、钩子载荷、权限名与子进程 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)(前端构建校验每个稳定项均已渲染) | | `uiApi` | 主题令牌、部件类名、状态属性、槽位、全窗图层、布局选项、图标名与交互事件 | [`frontend/ui-contract.json`](../frontend/ui-contract.json)(前端构建校验每个稳定项均已渲染) |
| `bridgeApi` | 沙箱面板与宿主之间的消息方法与事件 | [`frontend/bridge-contract.json`](../frontend/bridge-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 协议 ## 客体驱动的 Sidecar 协议
+2 -2
View File
@@ -13,7 +13,7 @@
| 核对发布候选 | `node scripts/test.mjs release` | 使用 `desktop,production` 构建标签运行同一套 Go 检查,禁用测试结果缓存并随机化用例顺序 | | 核对发布候选 | `node scripts/test.mjs release` | 使用 `desktop,production` 构建标签运行同一套 Go 检查,禁用测试结果缓存并随机化用例顺序 |
| Windows 桌面冒烟 | `node scripts/test.mjs webview2 build/bin/reims-go.exe` | 启动已构建的客户端,在真实 WebView2 中完成首启数据目录设置 | | 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`。 桌面冒烟需要已安装 WebView2 Runtime 的 Windows 桌面会话。测试通过 Windows UI Automation 填入独立的数据目录、点击继续,检查配置和目录指针落盘,并等待运行时设置页渲染。每次运行使用独立的 WebView2 配置目录。失败时,测试入口打印保留的目录,应用日志在其中的 `app.log`。
@@ -25,7 +25,7 @@ Go 包并发默认为可用 CPU 数与 4 的较小值,每个包的运行上限
## 覆盖和后续改进 ## 覆盖和后续改进
- 前端测试直接加载生产模块验证任务排序、过期事件和键位映射。涉及界面交互时优先覆盖用户可观察的状态切换,不按源码行或正则截取组件源码执行。 - 前端测试直接加载生产模块验证任务排序和过期事件。涉及界面交互时优先覆盖用户可观察的状态切换,不按源码行或正则截取组件源码执行。
- Go 单包测试验证领域规则,跨层测试保留桌面桥接、控制套接字、本地 HTTP、子进程与数据迁移等真实接口用例。异步用例通过完成信号控制时序,超时只用于报告卡死。 - Go 单包测试验证领域规则,跨层测试保留桌面桥接、控制套接字、本地 HTTP、子进程与数据迁移等真实接口用例。异步用例通过完成信号控制时序,超时只用于报告卡死。
- 存储层测试使用真实临时目录验证配置、目录锁、版本升级、插件状态备份与损坏恢复。 - 存储层测试使用真实临时目录验证配置、目录锁、版本升级、插件状态备份与损坏恢复。
- 依赖真实便携运行时、磁盘工具、引导镜像与安装包的集成用例仅在传入对应的 `REIMS_GO_TEST_*` 环境变量时运行,常规档位自动跳过。改动涉及虚拟机运行或磁盘操作时须在 Windows 宿主机实测验证。 - 依赖真实便携运行时、磁盘工具、引导镜像与安装包的集成用例仅在传入对应的 `REIMS_GO_TEST_*` 环境变量时运行,常规档位自动跳过。改动涉及虚拟机运行或磁盘操作时须在 Windows 宿主机实测验证。
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "reims-go-frontend", "name": "reims-go-frontend",
"private": true, "private": true,
"version": "0.2.13", "version": "0.2.15",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "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)) 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 let current = expr
while (ts.isParenthesizedExpression(current)) current = current.expression while (ts.isParenthesizedExpression(current)) current = current.expression
if (ts.isArrowFunction(current) || ts.isFunctionExpression(current)) { 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 return false
} }
@@ -70,9 +98,9 @@ export function findEmptyCatchesInJS(sourceText, filePath = 'sample.ts') {
record(node, 'empty-catch-clause') record(node, 'empty-catch-clause')
} else if (ts.isCallExpression(node)) { } else if (ts.isCallExpression(node)) {
const method = getCalleeMethodName(node.expression) 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') 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') 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.catch(async () => { ; })',
'p.then(ok, () => {})', 'p.then(ok, () => {})',
'p.then(ok, (err) => { // noop\n})', 'p.then(ok, (err) => { // noop\n})',
'p.catch(() => null)',
'p.catch(() => "")',
'p.catch(() => false)',
'p.catch(() => [])',
'p.catch(() => { return null })',
].join('\n') ].join('\n')
const badFindings = findEmptyCatchesInJS(bad, 'bad.ts') 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 good = [
'const text = "try { a() } catch {} .catch(() => {})"', '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 (e) { console.warn(e) }',
'try { a() } catch { return fallback }', 'try { a() } catch { return fallback }',
'p.catch((e) => console.warn(e))', 'p.catch((e) => console.warn(e))',
'p.catch(() => null)', 'p.catch((e) => { console.warn(e); return null })',
'p.then(ok, (e) => handle(e))', 'p.then(ok, (e) => handle(e))',
].join('\n') ].join('\n')
+97 -186
View File
@@ -1,11 +1,8 @@
import { Minus, Moon, Square, Sun, X } from 'lucide-react' import { Minus, Moon, Square, Sun, X } from 'lucide-react'
import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react' import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react'
import type { WizardDraft } from './components/CreateWizard' import type { WizardDraft } from './components/CreateWizard'
import { DeleteDialog } from './components/DeleteDialog' import { AppDialogs } from './components/AppDialogs'
import { ElevationDialog } from './components/ElevationDialog'
import { CloneDialog } from './components/CloneDialog'
import { OnlineRecoveryDialog } from './macos/OnlineRecoveryDialog' import { OnlineRecoveryDialog } from './macos/OnlineRecoveryDialog'
import { SendTextDialog } from './components/SendTextDialog'
import { LogPanel, LogTab } from './components/LogPanel' import { LogPanel, LogTab } from './components/LogPanel'
import { TitleMenus } from './components/TitleMenus' import { TitleMenus } from './components/TitleMenus'
import { UpdateCapsule } from './components/UpdateCapsule' import { UpdateCapsule } from './components/UpdateCapsule'
@@ -14,7 +11,8 @@ import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Si
import { CreatingVMView } from './components/CreatingVMView' import { CreatingVMView } from './components/CreatingVMView'
import { VMPage } from './components/VMPage' import { VMPage } from './components/VMPage'
import { buildFallbackChain, I18nKey, localeDir, locText, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n' import { buildFallbackChain, I18nKey, localeDir, locText, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format' import { defaultGuestLang, recommendedMemoryGB } from './lib/format'
import { initialWizardResolution } from './lib/displayResolution'
import { isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints' import { isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints'
import { resolveFullscreenHotkey } from './lib/fullscreenHotkey' import { resolveFullscreenHotkey } from './lib/fullscreenHotkey'
import { LogLine, appendLog, createLogLine } from './lib/logs' import { LogLine, appendLog, createLogLine } from './lib/logs'
@@ -23,7 +21,7 @@ import { creatingVMTasks, currentTask, finishedTaskTTL, isActiveInstallerTask, p
import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, notifyInteractiveThemeState } from './lib/themeEngine' import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, notifyInteractiveThemeState } from './lib/themeEngine'
import type { UIStateSnapshot } from './lib/uiSdk' import type { UIStateSnapshot } from './lib/uiSdk'
import { hasVisibleDialog } from './lib/dialogState' import { hasVisibleDialog } from './lib/dialogState'
import { latestVMStats, refreshSubscribedVMStats, refreshVMStats } from './lib/vmStats' import { refreshSubscribedVMStats, refreshVMStats } from './lib/vmStats'
import { useAppearance } from './lib/useAppearance' import { useAppearance } from './lib/useAppearance'
import { useAppUpdate } from './lib/useAppUpdate' import { useAppUpdate } from './lib/useAppUpdate'
import { useFileDrop } from './lib/useFileDrop' import { useFileDrop } from './lib/useFileDrop'
@@ -34,18 +32,13 @@ import { closePluginDialog, closePluginView, emptyPluginViewState, matchViewCond
import { publishPluginHostEvent } from './lib/pluginViewEvents' import { publishPluginHostEvent } from './lib/pluginViewEvents'
import { buildSafePluginAssetURL } from './lib/pluginAssets' import { buildSafePluginAssetURL } from './lib/pluginAssets'
import { ActiveThemePayload, AppState, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMAction, VMBusyAction, VMDetail, VMInfo, VMListItem, ViewContribution } from './types' import { ActiveThemePayload, AppState, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMAction, VMBusyAction, VMDetail, VMInfo, VMListItem, ViewContribution } from './types'
import { Button, Tip, TooltipProvider } from './ui/controls' import { Tip, TooltipProvider } from './ui/controls'
import { ConfirmDialog, Modal } from './ui/dialog'
import { errorToast, Toaster, type ToastInput, useToasts } from './ui/toast' import { errorToast, Toaster, type ToastInput, useToasts } from './ui/toast'
import { BrandMark, ThemeDecorations, ThemeVisualsProvider } from './ui/themeVisuals' import { BrandMark, ThemeDecorations, ThemeVisualsProvider } from './ui/themeVisuals'
import { api, DROP_NETWORK_VOLUMES_DENIED, events, WindowMinimise, WindowToggleMaximise, type ElevationPrompt } from './wails' 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 // 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 // bundle: first-run setup, and the Engine / Installers / Settings pages.
// 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 })))
const Setup = lazy(() => import('./components/Setup').then((m) => ({ default: m.Setup }))) const Setup = lazy(() => import('./components/Setup').then((m) => ({ default: m.Setup })))
const HostView = lazy(() => import('./components/HostView').then((m) => ({ default: m.HostView }))) const HostView = lazy(() => import('./components/HostView').then((m) => ({ default: m.HostView })))
const ImagesPage = lazy(() => import('./components/ImagesPage').then((m) => ({ default: m.ImagesPage }))) 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. // Sidebar can be hidden (Ctrl+B or the title-bar toggle); remembered per user.
const [sidebarOpen, setSidebarOpen] = useState<boolean>(() => { 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) => { const toggleSidebar = () => setSidebarOpen((open) => {
try { localStorage.setItem('reims-go-sidebar', open ? 'hidden' : 'shown') } catch (e) { console.warn('[app] persist sidebar state failed:', e) } 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 let live = true
api.GetVMDetail(selectedVM.name) api.GetVMDetail(selectedVM.name)
.then((d) => { if (live) setDetail(d) }) .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 } return () => { live = false }
}, [selectedVM?.name, selectedVM?.driver_id, selectedVM?.state, selectedTransition, selectedIsMacOS, detailRevision, state?.active_runtime?.commit, state?.runtime_capture_supported]) }, [selectedVM?.name, selectedVM?.driver_id, selectedVM?.state, selectedTransition, selectedIsMacOS, detailRevision, state?.active_runtime?.commit, state?.runtime_capture_supported])
@@ -596,9 +592,15 @@ export const App: React.FC = () => {
} }
} }
const folderDone = async () => { const folderDone = async () => {
const s = await api.GetState().catch(() => null) try {
if (s) setState(s) const s = await api.GetState()
setSetupStage(s?.active_runtime ? null : 'runtime') setState(s)
setSetupStage(s?.active_runtime ? 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') const showSetup = !!state && (state.needs_setup || setupStage === 'runtime')
// The data folder opened read-only (internal/dataroot): nothing in it may be // The data folder opened read-only (internal/dataroot): nothing in it may be
@@ -956,6 +958,7 @@ export const App: React.FC = () => {
defaultName = `macos-tahoe-${i}` defaultName = `macos-tahoe-${i}`
} }
const isOffline = item.kind === 'offline' && !!item.version const isOffline = item.kind === 'offline' && !!item.version
const graphics = state.host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga'
setWizardDraft({ setWizardDraft({
step: 1, step: 1,
opts: { opts: {
@@ -970,9 +973,9 @@ export const App: React.FC = () => {
disk_size: '128G', disk_size: '128G',
disk_mode: 'copy', disk_mode: 'copy',
disk_controller: 'nvme', disk_controller: 'nvme',
graphics: 'reims-vgpu', graphics,
gpu: state.host.recommended_gpu?.vulkan_icd ?? 'auto', gpu: state.host.recommended_gpu?.vulkan_icd ?? 'auto',
resolution: recommendedResolution(state.host), ...initialWizardResolution(state.host, fixedModeSupported, graphics),
displays: 1, displays: 1,
borderless: false, borderless: false,
capture: false, capture: false,
@@ -1445,148 +1448,80 @@ export const App: React.FC = () => {
/> />
)} )}
{showWizard && state && ( <AppDialogs
<Suspense fallback={null}> locale={locale}
<CreateWizard state={state}
locale={locale} detail={detail}
host={state.host} selectedVM={selectedVM}
fixedModeSupported={fixedModeSupported} selectedIsMacOS={selectedIsMacOS}
captureSupported={state.runtime_capture_supported} effectiveState={effectiveState}
tasks={Object.values(taskMap)} fixedModeSupported={fixedModeSupported}
draft={wizardDraft} diskCacheSupported={diskCacheSupported}
onClose={() => { setShowWizard(false); setWizardDraft(null) }} runningVMCount={runningVMCount}
onSubmit={submitCreate} tasks={Object.values(taskMap)}
/> displayNames={displayNames}
</Suspense> showWizard={showWizard}
)} wizardDraft={wizardDraft}
onCloseWizard={() => { setShowWizard(false); setWizardDraft(null) }}
{showSettings && state && detail && ( onSubmitCreate={submitCreate}
<Suspense fallback={null}> showSettings={showSettings}
<SettingsModal onCloseSettings={() => setShowSettings(false)}
locale={locale} onSavedSettings={() => {
detail={detail} setShowSettings(false)
driverID={selectedVM?.driver_id ?? ''} toasts.push({ kind: 'ok', title: tr(effectiveState === 'running' ? 'toastSavedNextStart' : 'toastSaved') })
stats={latestVMStats(selectedVM?.driver_id ?? '', detail.name)} refresh()
host={state.host} }}
fixedModeSupported={fixedModeSupported} affinityTarget={affinityTarget}
diskCacheSupported={diskCacheSupported} affinityVersion={affinityVersion}
optimizations={state.optimizations} onOpenAffinity={setAffinityTarget}
running={effectiveState === 'running'} onCloseAffinity={() => setAffinityTarget(null)}
onCopy={copy} onAffinityApplied={(st) => {
onDiskChanged={refresh} setAffinityTarget(null)
onOpenAffinity={() => setAffinityTarget({ name: detail.name, driverID: selectedVM?.driver_id ?? '' })} setAffinityVersion((v) => v + 1)
affinityVersion={affinityVersion} const count = st.effective_cpus?.length ?? 0
onHostChanged={refresh} const mask = st.live_mask_hex || st.effective_mask_hex || '0x0'
onToast={toasts.push} toasts.push({
onClose={() => setShowSettings(false)} kind: 'ok',
onSaved={() => { title: st.running
setShowSettings(false) ? tr('toastAffinityApplied', { count, mask })
toasts.push({ kind: 'ok', title: tr(effectiveState === 'running' ? 'toastSavedNextStart' : 'toastSaved') }) : tr('toastAffinitySaved'),
refresh() })
}} refresh()
/> }}
</Suspense> updateConfirming={update.confirming}
)} updateLatest={update.info?.latest ?? ''}
onCancelInstallUpdate={() => update.cancelInstall()}
{affinityTarget && state && ( onConfirmInstallUpdate={update.confirmInstall}
<Suspense fallback={null}> deleteTarget={deleteTarget}
<AffinityDialog onCancelDelete={() => setDeleteTarget(null)}
locale={locale} onConfirmDelete={confirmDelete}
vmName={affinityTarget.name} closeDownloadsOpen={closeDownloadsOpen}
driverID={affinityTarget.driverID} onCancelCloseDownloads={() => setCloseDownloadsOpen(false)}
vcpus={detail?.name === affinityTarget.name ? detail.cpus : 4} elevationQueue={elevationQueue}
host={state.host} onResolveElevation={(id, approved) => {
globalAutoPin={state.config.auto_pin_pcores} setElevationQueue((q) => q.filter((item) => item.id !== id))
onClose={() => setAffinityTarget(null)} api.ResolveElevationRequest(id, approved).catch((e) => console.warn('[app] ResolveElevationRequest failed:', e))
onApplied={(st) => { }}
setAffinityTarget(null) discardSuspendTarget={discardSuspendTarget}
setAffinityVersion((v) => v + 1) onCancelDiscardSuspend={() => setDiscardSuspendTarget(null)}
const count = st.effective_cpus?.length ?? 0 onConfirmDiscardSuspend={confirmDiscardSuspend}
const mask = st.live_mask_hex || st.effective_mask_hex || '0x0' cloneSource={cloneSource}
toasts.push({ onCancelClone={() => setCloneSource(null)}
kind: 'ok', onConfirmClone={confirmClone}
title: st.running sendTextTarget={sendTextTarget}
? tr('toastAffinityApplied', { count, mask }) onCancelSendText={() => setSendTextTarget(null)}
: tr('toastAffinitySaved'), onConfirmSendText={(key, driverID, name, text) => {
}) setSendTextTarget(null)
refresh() typeInto(key, () => api.TypeText(driverID, name, text))
}} }}
/> pluginDialogs={pluginViewState.dialogs}
</Suspense> findRouteView={findRouteView}
)} renderPluginView={renderPluginView}
findVM={findVM}
{update.confirming && ( onCopy={copy}
<Modal onRefresh={refresh}
title={tr('updateConfirmTitle', { v: update.info?.latest ?? '' })} onToast={toasts.push}
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}
/>
)}
{onlineRecoveryTarget && ( {onlineRecoveryTarget && (
<OnlineRecoveryDialog <OnlineRecoveryDialog
@@ -1597,30 +1532,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 className="rg-layer rg-layer-overlay" data-rg-layer="layer.overlay" aria-hidden="true" />
</div> </div>
{/* Outside the isolated shell so toasts stay above dialogs and the overlay layer. */} {/* 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 let cancelled = false
api.CanOpenQQGroup() api.CanOpenQQGroup()
.then((ok) => { if (!cancelled) setQQInstalled(!!ok) }) .then((ok) => { if (!cancelled) setQQInstalled(!!ok) })
.catch(() => { if (!cancelled) setQQInstalled(false) }) .catch((e) => {
console.warn('[about] CanOpenQQGroup failed:', e)
if (!cancelled) setQQInstalled(false)
})
return () => { return () => {
mountedRef.current = false mountedRef.current = false
cancelled = true cancelled = true
+257
View File
@@ -0,0 +1,257 @@
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 { 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}
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)
})}
</>
)
}
+90 -35
View File
@@ -1,5 +1,5 @@
import { Check, ChevronRight, CircleAlert, CircleCheck, CloudDownload, Copy, Disc3, HardDrive, LucideIcon, Package } from 'lucide-react' 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 { useNetworkPlan } from '../lib/useNetworkPlan'
import { NpcapDependency } from './NpcapDependency' import { NpcapDependency } from './NpcapDependency'
import { NetworkErrorNotice } from './NetworkErrorNotice' import { NetworkErrorNotice } from './NetworkErrorNotice'
@@ -14,6 +14,7 @@ import {
defaultGuestLang, defaultGuestLang,
findGPU, findGPU,
formatMemory, formatMemory,
formatResolutionLabel,
gpuCompatHint, gpuCompatHint,
gpuLabel, gpuLabel,
gpuOptionValue, gpuOptionValue,
@@ -21,22 +22,32 @@ import {
memorySafeLimitGB, memorySafeLimitGB,
parseMemoryGB, parseMemoryGB,
recommendedCPUs, recommendedCPUs,
canKeepDisplayPreset,
fullscreenDisplayPresets, fullscreenDisplayPresets,
FullscreenDisplayPreset, FullscreenDisplayPreset,
hidpiLooksLike, hidpiLooksLike,
hostDisplayAdvice, hostDisplayAdvice,
hostDisplayDesc, hostDisplayDesc,
resolveAutoDisplayPreset,
windowDisplayPresets, windowDisplayPresets,
recommendedMemoryGB, recommendedMemoryGB,
recommendedResolution,
shortGPUName, shortGPUName,
sshCommand, sshCommand,
} from '../lib/format' } 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 { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, Task, ValidationIssue, VMNetworkSettings } from '../types'
import { findActiveOfflineTask, taskInstallerPhase } from '../lib/tasks' import { findActiveOfflineTask, taskInstallerPhase } from '../lib/tasks'
import { Button, IconButton } from '../ui/controls' 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 { Modal } from '../ui/dialog'
import { api } from '../wails' import { api } from '../wails'
@@ -47,6 +58,7 @@ const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos'
export interface WizardDraft { export interface WizardDraft {
opts: CreateOpts opts: CreateOpts
step: number step: number
manualResolution?: boolean
} }
interface Props { interface Props {
@@ -106,6 +118,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
const activeDriver = drivers.find((d) => d.id === driverID) const activeDriver = drivers.find((d) => d.id === driverID)
const isCustomDriver = driverID !== BUILTIN_MACOS_DRIVER && !!activeDriver const isCustomDriver = driverID !== BUILTIN_MACOS_DRIVER && !!activeDriver
const defaultGraphics = host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga'
const [opts, setOpts] = useState<CreateOpts>(draft?.opts ?? { const [opts, setOpts] = useState<CreateOpts>(draft?.opts ?? {
name: 'macos-tahoe', name: 'macos-tahoe',
dir: '', dir: '',
@@ -120,11 +133,11 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
disk: '', disk: '',
disk_mode: 'copy', disk_mode: 'copy',
disk_controller: 'nvme', disk_controller: 'nvme',
graphics: host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga', graphics: defaultGraphics,
// Default to "auto" rather than a DriverStore FileRepository ICD path so // Default to "auto" rather than a DriverStore FileRepository ICD path so
// Windows GPU driver updates never break existing VM configs. // Windows GPU driver updates never break existing VM configs.
gpu: 'auto', gpu: 'auto',
resolution: recommendedResolution(host), ...initialWizardResolution(host, fixedModeSupported, defaultGraphics),
displays: 1, displays: 1,
borderless: false, borderless: false,
...(captureSupported ? { capture: false } : {}), ...(captureSupported ? { capture: false } : {}),
@@ -136,6 +149,9 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
guest_lang: defaultGuestLang(locale), guest_lang: defaultGuestLang(locale),
start: true, start: true,
}) })
const [manualResolutionPicked, setManualResolutionPicked] = useState(() =>
initialWizardManualResolution(draft),
)
const [networkTouched, setNetworkTouched] = useState(!!draft?.opts) const [networkTouched, setNetworkTouched] = useState(!!draft?.opts)
const set = (patch: Partial<CreateOpts>) => setOpts((o) => ({ ...o, ...patch })) const set = (patch: Partial<CreateOpts>) => setOpts((o) => ({ ...o, ...patch }))
const networkMode = opts.network_mode ?? (opts.network ? 'nat' : 'off') const networkMode = opts.network_mode ?? (opts.network ? 'nat' : 'off')
@@ -157,9 +173,22 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
}, [step, networkMode, locale]) }, [step, networkMode, locale])
const windowPresets = windowDisplayPresets(host, fixedModeSupported) const windowPresets = windowDisplayPresets(host, fixedModeSupported)
const fullscreenPresets = fullscreenDisplayPresets(host) 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 buildPayload = (): CreateOpts => {
const p: CreateOpts = { ...opts, offline: opts.source_mode === 'offline' } const p: CreateOpts = { ...effectiveOpts, offline: effectiveOpts.source_mode === 'offline' }
if (!captureSupported) { if (!captureSupported) {
delete p.capture delete p.capture
} }
@@ -233,7 +262,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
.finally(() => { if (live) setChecking(false) }) .finally(() => { if (live) setChecking(false) })
}, 200) }, 200)
return () => { live = false; clearTimeout(timer) } return () => { live = false; clearTimeout(timer) }
}, [step, reviewed, opts, validationRefresh, captureSupported]) }, [step, reviewed, effectiveOpts, validationRefresh, captureSupported])
const pickDir = async () => { const pickDir = async () => {
const dir = await api.PickDirectory(tr('vmDir')) const dir = await api.PickDirectory(tr('vmDir'))
@@ -247,7 +276,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
const handleCreate = () => { const handleCreate = () => {
if (dependencyBusy || networkBlocked) return 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) : []) const issueSteps = new Set(reviewed ? issues.map(stepOfIssue) : [])
@@ -545,7 +574,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
<Segmented <Segmented
label={tr('graphicsBackend')} label={tr('graphicsBackend')}
value={opts.graphics} value={opts.graphics}
onChange={(graphics) => set({ graphics })} onChange={changeGraphics}
options={[ options={[
{ value: 'reims-vgpu' as const, label: tr('graphicsReimsShort') }, { value: 'reims-vgpu' as const, label: tr('graphicsReimsShort') },
{ value: 'vmware-svga' as const, label: tr('graphicsSvgaShort') }, { value: 'vmware-svga' as const, label: tr('graphicsSvgaShort') },
@@ -566,7 +595,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
<button <button
type="button" type="button"
className="link-btn" className="link-btn"
onClick={() => set({ graphics: 'vmware-svga' })} onClick={() => changeGraphics('vmware-svga')}
> >
{tr('gpuSwitchSvga')} {tr('gpuSwitchSvga')}
</button> </button>
@@ -602,23 +631,47 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
disabled={opts.graphics !== 'reims-vgpu'} disabled={opts.graphics !== 'reims-vgpu'}
reason={tr('gpuSvgaReason')} reason={tr('gpuSvgaReason')}
desc={[hostDisplayDesc(host, tr), !opts.borderless ? hostDisplayAdvice(host, tr, windowPresets) : undefined].filter(Boolean).join(' · ') || undefined} desc={[hostDisplayDesc(host, tr), !opts.borderless ? hostDisplayAdvice(host, tr, windowPresets) : undefined].filter(Boolean).join(' · ') || undefined}
control={ block={
<PopupSelect <OptionCards
id="vm-res"
label={tr('resolution')} label={tr('resolution')}
value={opts.resolution} value={supportsAutoResolution(opts.graphics) && opts.auto_resolution ? AUTO_RESOLUTION_OPTION : opts.resolution}
onChange={(resolution) => set({ resolution })} onChange={(v) => {
options={(opts.borderless ? fullscreenPresets : windowPresets).map((p: FullscreenDisplayPreset) => ({ setManualResolutionPicked(v !== AUTO_RESOLUTION_OPTION)
value: p.resolution, set(selectWizardResolution(v, autoPreset))
label: p.label, }}
detail: [ options={buildResolutionOptions({
p.hidpi ? `${tr('hidpiPresetBadge')} · ${hidpiLooksLike(p.resolution, tr) ?? ''}` : '', graphics: opts.graphics,
p.scaleBadge ?? '', autoPreset,
p.native ? tr('resNativeBadge') : '', activePresets,
p.scaleToFit ? tr('resScaleToFitWindow') : '', }).map((item) => {
p.recommended ? tr('recommendedBadge') : '', const p = item.preset!
].filter(Boolean).join(' · ') || undefined, 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 +739,14 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
<Switch <Switch
label={tr('fullscreenLaunch')} label={tr('fullscreenLaunch')}
checked={!!opts.borderless} checked={!!opts.borderless}
onChange={(borderless) => { onChange={(borderless) => set(toggleWizardBorderless({
const list = borderless ? fullscreenPresets : windowPresets borderless,
const keep = list.some((p) => canKeepDisplayPreset(p, opts.resolution, borderless)) opts,
const fallback = list.find((p) => p.recommended)?.resolution ?? list[0]?.resolution ?? opts.resolution host,
set(keep ? { borderless } : { borderless, resolution: fallback }) fixedModeSupported,
}} windowPresets,
fullscreenPresets,
}))}
/> />
} }
/> />
@@ -707,7 +762,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
<Review <Review
locale={locale} locale={locale}
host={host} host={host}
opts={opts} opts={effectiveOpts}
captureSupported={captureSupported} captureSupported={captureSupported}
networkUplink={networkAdapters?.find((adapter) => adapter.guid === opts.uplink_guid)?.name} networkUplink={networkAdapters?.find((adapter) => adapter.guid === opts.uplink_guid)?.name}
issues={issues} issues={issues}
@@ -801,7 +856,7 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, captureSupported, i
? tr('summaryInstallerSource', { file: fileName(opts.installer) }) ? tr('summaryInstallerSource', { file: fileName(opts.installer) })
: tr('summaryDiskSource', { file: fileName(opts.disk) }) : 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' const graphicsRows: Row[] = opts.graphics === 'reims-vgpu'
? [ ? [
{ label: tr('factGraphics'), value: `${gpuLabel(locale, opts.gpu, host)} · reims-vgpu` }, { label: tr('factGraphics'), value: `${gpuLabel(locale, opts.gpu, host)} · reims-vgpu` },
+5 -110
View File
@@ -34,20 +34,6 @@ function formatCompactCount(n: number): string {
return String(n) 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 { function parseTimestamp(iso?: string): number {
if (!iso) return 0 if (!iso) return 0
const ms = Date.parse(iso) const ms = Date.parse(iso)
@@ -62,20 +48,6 @@ function compositeScore(item: MarketCatalogItem, nowMs: number): number {
return recency + downloads 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 { interface Props {
locale: Locale locale: Locale
safeMode?: boolean safeMode?: boolean
@@ -102,7 +74,6 @@ export const PluginMarket: React.FC<Props> = ({
const [query, setQuery] = useState('') const [query, setQuery] = useState('')
const [kind, setKind] = useState('') const [kind, setKind] = useState('')
const [sortBy, setSortBy] = useState<MarketSortMode>('composite') const [sortBy, setSortBy] = useState<MarketSortMode>('composite')
const [versionPick, setVersionPick] = useState<{ item: MarketCatalogItem; selected: string } | null>(null)
const [result, setResult] = useState<MarketBrowseResult | null>(null) const [result, setResult] = useState<MarketBrowseResult | null>(null)
const [syncing, setSyncing] = useState(false) const [syncing, setSyncing] = useState(false)
const [refreshing, setRefreshing] = useState(false) const [refreshing, setRefreshing] = useState(false)
@@ -277,22 +248,13 @@ export const PluginMarket: React.FC<Props> = ({
advancePrompt() advancePrompt()
} }
const openVersionPicker = (item: MarketCatalogItem) => { const install = async (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 id = item.entry.id const id = item.entry.id
if (installingRef.current.has(id)) return if (installingRef.current.has(id)) return
installingRef.current.add(id) installingRef.current.add(id)
const rel = entryReleases(item).find((r) => r.version === version) setProgress((prev) => ({ ...prev, [id]: { id, phase: 'download', done: 0, total: item.entry.size_bytes ?? 0 } }))
setProgress((prev) => ({ ...prev, [id]: { id, phase: 'download', done: 0, total: rel?.size_bytes ?? item.entry.size_bytes ?? 0 } }))
try { try {
const info = version const info = await api.InstallMarketPluginVersion(id, item.entry.version)
? await api.InstallMarketPluginVersion(id, version)
: await api.InstallMarketPlugin(id, true)
await onChanged({}) await onChanged({})
if (info && !info.enabled) { if (info && !info.enabled) {
if (promptTargetIDRef.current) { if (promptTargetIDRef.current) {
@@ -372,7 +334,7 @@ export const PluginMarket: React.FC<Props> = ({
return ( return (
<Tip label={tr('pluginMarketVersionTip', { installed: item.installed_version ?? '', version: e.version })}> <Tip label={tr('pluginMarketVersionTip', { installed: item.installed_version ?? '', version: e.version })}>
<span> <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')} {tr('pluginMarketUpdateShort')}
</Button> </Button>
</span> </span>
@@ -380,7 +342,7 @@ export const PluginMarket: React.FC<Props> = ({
) )
} }
return ( 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')} {tr('pluginMarketInstall')}
</Button> </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 && ( {prompt && (
<Modal <Modal
title={tr('pluginEnablePromptTitle', { name: locText(prompt.name, locale, prompt.id) })} title={tr('pluginEnablePromptTitle', { name: locText(prompt.name, locale, prompt.id) })}
+144 -61
View File
@@ -13,18 +13,26 @@ import {
memorySafeLimitGB, memorySafeLimitGB,
parseMemoryGB, parseMemoryGB,
recommendedCPUs, recommendedCPUs,
canKeepDisplayPreset,
fullscreenDisplayPresets,
FullscreenDisplayPreset,
hidpiLooksLike, hidpiLooksLike,
hostDisplayAdvice, hostDisplayAdvice,
hostDisplayDesc, hostDisplayDesc,
windowDisplayPresets,
recommendedMemoryGB, recommendedMemoryGB,
recommendedResolution,
shortGPUName, shortGPUName,
sshCommand, sshCommand,
} from '../lib/format' } 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 { applyKernelIrqchip, findOptimization, kernelIrqchipHint, parseKernelIrqchip } from '../lib/optimizations'
import { useVMStats } from '../lib/vmStats' import { useVMStats } from '../lib/vmStats'
import { HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMAffinityStatus, VMDetail, VMStats, DiskCache } from '../types' 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 { VMNetworkSettings } from './VMNetworkSettings'
import { DefenderExclusionRow, DiskMaintenanceRows, useDiskMaintenance } from './vmSettings/disk' import { DefenderExclusionRow, DiskMaintenanceRows, useDiskMaintenance } from './vmSettings/disk'
import { DiskCacheRow } from './vmSettings/diskCache' import { DiskCacheRow } from './vmSettings/diskCache'
import { KeymapSection, useKeymap } from './vmSettings/keymap'
import { useVMPluginSettings, VMPluginGroup } from './vmSettings/plugins' import { useVMPluginSettings, VMPluginGroup } from './vmSettings/plugins'
import { DriveShareSection, SharedFolderSection, useDriveShares, useSharedFolders, WritableFolderDialog } from './vmSettings/sharing' import { DriveShareSection, SharedFolderSection, useDriveShares, useSharedFolders, WritableFolderDialog } from './vmSettings/sharing'
import { SMBIOSDialog, SMBIOSSection, useSMBIOS } from './vmSettings/smbios' import { SMBIOSDialog, SMBIOSSection, useSMBIOS } from './vmSettings/smbios'
@@ -70,6 +77,7 @@ const FIELD_CAT: Record<Field, Cat> = {
graphics: 'display', graphics: 'display',
gpu: 'display', gpu: 'display',
resolution: 'display', resolution: 'display',
auto_resolution: 'display',
displays: 'display', displays: 'display',
borderless: 'display', borderless: 'display',
disk_controller: 'storage', 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 LOG_LEVELS = ['error', 'warn', 'info', 'debug', 'trace'] as const
const CUSTOM = '__custom' 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 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. */ /** Whether two values of a field mean the same thing to reims-ctl. */
function same(field: Field, a: SetOpts[Field], b: SetOpts[Field]): boolean { function same(field: Field, a: SetOpts[Field], b: SetOpts[Field]): boolean {
switch (field) { switch (field) {
case 'memory': return parseMemoryGB(a as string) === parseMemoryGB(b as string) case 'memory': return parseMemoryGB(a as string) === parseMemoryGB(b as string)
case 'gpu': return normPath(a as string) === normPath(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 'log_level':
case 'extra_args': case 'extra_args':
case 'audio_backend': case 'audio_backend':
@@ -122,6 +128,7 @@ function baseline(detail: VMDetail, host: HostReport): SetOpts {
disk_controller: detail.disk_controller, disk_controller: detail.disk_controller,
disk_cache: (detail.disk_cache as DiskCache) || 'default', disk_cache: (detail.disk_cache as DiskCache) || 'default',
resolution: detail.resolution, resolution: detail.resolution,
auto_resolution: !!detail.auto_resolution,
borderless: detail.borderless, borderless: detail.borderless,
...(detail.capture_supported ? { capture: detail.capture } : {}), ...(detail.capture_supported ? { capture: detail.capture } : {}),
gpu: icd ?? (detail.gpu || 'auto'), 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 drives = useDriveShares(detail.name)
const folders = useSharedFolders(detail.name, locale) const folders = useSharedFolders(detail.name, locale)
const smbios = useSMBIOS(detail, running) const smbios = useSMBIOS(detail, running)
const keymap = useKeymap(detail.name, running, cat === 'input')
const plugins = useVMPluginSettings(`${driverID}:${detail.name}`, setErr) const plugins = useVMPluginSettings(`${driverID}:${detail.name}`, setErr)
const disk = useDiskMaintenance({ locale, driverID, vm: detail.name, diskPath: detail.disk, running, stats, onError: setErr, onDiskChanged }) 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') 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 tzBusy = timezone.tzBusy
const pane = useRef<HTMLDivElement>(null) 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 [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)) 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 // 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 // a save, before the refreshed detail arrives) or refreshed in the background:
// the person changes something. // sync untouched fields from the latest baseline while preserving user edits.
const edited = useRef(false) const vmIdentity = `${driverID}:${detail.name}`
const vmIdentityRef = useRef(vmIdentity)
const touchedFieldsRef = useRef<Set<Field>>(new Set())
useEffect(() => { useEffect(() => {
if (edited.current) return const prevKey = vmIdentityRef.current
setForm(base) vmIdentityRef.current = vmIdentity
setCustomRes(false) if (prevKey !== vmIdentity) {
setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level)) touchedFieldsRef.current.clear()
}, [base]) 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(() => { useEffect(() => {
setForm((f) => { setForm((f) => {
@@ -216,25 +245,34 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
}, [detail.capture_supported, detail.capture]) }, [detail.capture_supported, detail.capture])
const set = (patch: Partial<SetOpts>) => { 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 })) setForm((f) => ({ ...f, ...patch }))
const touched = Object.keys(patch) setIssues((list) => list.filter((i) => !touched.includes(i.field as Field)))
setIssues((list) => list.filter((i) => !touched.includes(i.field)))
} }
const dirty = (f: Field) => (f === 'capture' && !detail.capture_supported ? false : !same(f, form[f], base[f])) const dirty = (f: Field) => (f === 'capture' && !detail.capture_supported ? false : !same(f, form[f], base[f]))
const reset = (f: Field) => () => { const reset = (f: Field) => () => {
set({ [f]: base[f] } as Partial<SetOpts>) const toClear = expandTouchedSettingsFields([f]) as Field[]
if (f === 'resolution' || f === 'borderless') setCustomRes(false) 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)) if (f === 'log_level') setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
} }
const changed = FIELDS.filter(dirty) 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 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 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)) const strayIssues = issues.filter((i) => !(i.field in FIELD_CAT))
// Inline checks the backend would also reject, so the row says it first. // 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 sshOn = (form.ssh_port ?? 0) > 0
const localBlock = resBad const localBlock = resBad
const nestedVirtAvailable = host.whpx === 'ready' && host.whpx_caps?.nested_vmx && !host.needs_cold_reboot_workaround 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([]) setIssues([])
setBusy(true) setBusy(true)
try { try {
const diff: SetOpts = { name: detail.name } const diff = buildSettingsSaveDiff(detail.name, changed, form, base)
for (const f of changed) (diff as unknown as Record<string, unknown>)[f] = form[f]
const iss = await api.ValidateSet(diff) const iss = await api.ValidateSet(diff)
if (iss && iss.length > 0) { if (iss && iss.length > 0) {
setIssues(iss) setIssues(iss)
@@ -302,7 +339,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
} }
const resetAll = () => { const resetAll = () => {
edited.current = false touchedFieldsRef.current.clear()
setForm(base) setForm(base)
setIssues([]) setIssues([])
setCustomRes(false) setCustomRes(false)
@@ -499,19 +536,21 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
const vgpu = form.graphics !== 'vmware-svga' const vgpu = form.graphics !== 'vmware-svga'
const targetDisp = activeTargetDisplay const targetDisp = activeTargetDisplay
const hidpiAdvice = hostDisplayAdvice(displayProfile, tr, presets) 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 toggleBorderless = (borderless: boolean) => {
const targetPresets = borderless ? fsPresets : presets set(toggleSettingsBorderless({
if (!customRes && !targetPresets.some((p) => canKeepDisplayPreset(p, form.resolution, borderless))) { borderless,
const nextRes = borderless form,
? (targetDisp && targetDisp.width > 0 && targetDisp.height > 0 displayProfile,
? `${targetDisp.width}x${targetDisp.height}` targetDisplay: targetDisp,
: targetPresets[0]?.resolution ?? form.resolution) presets,
: recommendedResolution(displayProfile) fsPresets,
set({ borderless, resolution: nextRes }) customRes,
return }))
}
set({ borderless })
} }
const resArt = (r: string) => { const resArt = (r: string) => {
const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(r) 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 <Segmented
label={tr('graphicsBackend')} label={tr('graphicsBackend')}
value={form.graphics} value={form.graphics}
onChange={(graphics) => set({ graphics })} onChange={changeGraphics}
options={[ options={[
{ value: 'reims-vgpu', label: tr('graphicsReimsShort') }, { value: 'reims-vgpu', label: tr('graphicsReimsShort') },
{ value: 'vmware-svga', label: tr('graphicsSvgaShort') }, { value: 'vmware-svga', label: tr('graphicsSvgaShort') },
@@ -553,7 +592,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
<button <button
type="button" type="button"
className="link-btn" className="link-btn"
onClick={() => set({ graphics: 'vmware-svga' })} onClick={() => changeGraphics('vmware-svga')}
> >
{tr('gpuSwitchSvga')} {tr('gpuSwitchSvga')}
</button> </button>
@@ -577,7 +616,11 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
/> />
<SetRow <SetRow
{...rowProps('resolution')} {...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')} title={tr('resolution')}
desc={hostDisplayDesc(host, tr, activeTargetDisplay, (d) => desc={hostDisplayDesc(host, tr, activeTargetDisplay, (d) =>
tr('targetDisplayHint', { tr('targetDisplayHint', {
@@ -593,13 +636,41 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
label={tr('resolution')} label={tr('resolution')}
value={resValue} value={resValue}
onChange={(v) => { onChange={(v) => {
if (v === CUSTOM) { setCustomRes(true); return } const next = selectSettingsResolution({ value: v, form, base, autoPreset })
setCustomRes(false) setCustomRes(next.forceCustomRes)
set({ resolution: v }) set(next.patch)
}} }}
options={[ options={buildResolutionOptions({
...activePresets.map((p) => ({ graphics: form.graphics,
value: p.resolution, 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, title: p.label,
sub: p.hidpi ? hidpiLooksLike(p.resolution, tr) : undefined, sub: p.hidpi ? hidpiLooksLike(p.resolution, tr) : undefined,
art: resArt(p.resolution), art: resArt(p.resolution),
@@ -610,9 +681,8 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
p.scaleToFit ? tr('resScaleToFitWindow') : '', p.scaleToFit ? tr('resScaleToFitWindow') : '',
p.recommended ? tr('recommendedBadge') : '', p.recommended ? tr('recommendedBadge') : '',
].filter(Boolean), ].filter(Boolean),
})), }
{ value: CUSTOM, title: tr('resCustom'), sub: tr('resCustomSub'), art: <span className="screen-art custom" aria-hidden="true" /> }, })}
]}
/> />
{customRes && ( {customRes && (
<input <input
@@ -622,6 +692,20 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
autoFocus autoFocus
value={form.resolution ?? ''} value={form.resolution ?? ''}
onChange={(e) => set({ resolution: e.target.value })} 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>} {!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> </SetGroup>
)} )}
<KeymapSection locale={locale} vm={detail.name} state={keymap} captureSupported={detail.capture_supported} />
<VMPluginGroup locale={locale} group="keyboard" state={plugins} /> <VMPluginGroup locale={locale} group="keyboard" state={plugins} />
<SetGroup title={tr('catAudio')} note={tr('audioTroubleshootNote')}> <SetGroup title={tr('catAudio')} note={tr('audioTroubleshootNote')}>
<SetRow <SetRow
@@ -904,10 +987,10 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
<div className="dialog-foot"> <div className="dialog-foot">
<span className="foot-status" aria-live="polite"> <span className="foot-status" aria-live="polite">
{changed.length > 0 {changedCount > 0
? <><span className="dirty-dot" aria-hidden="true" />{tr('pendingChanges', { n: changed.length })}</> ? <><span className="dirty-dot" aria-hidden="true" />{tr('pendingChanges', { n: changedCount })}</>
: <span className="muted">{tr('noChanges')}</span>} : <span className="muted">{tr('noChanges')}</span>}
{changed.length > 0 && ( {changedCount > 0 && (
<button type="button" className="link-btn" disabled={busy} onClick={resetAll}>{tr('resetAll')}</button> <button type="button" className="link-btn" disabled={busy} onClick={resetAll}>{tr('resetAll')}</button>
)} )}
</span> </span>
+7 -2
View File
@@ -80,8 +80,13 @@ const FolderStep: React.FC<StepProps> = ({ locale, locales, state, tr, onLocale,
}, [selected]) }, [selected])
const browse = async () => { const browse = async () => {
const dir = await api.PickDirectory(tr('setupTitle')).catch(() => '') try {
if (dir) { setCustom(dir); setCustomMode(true); setSelected(dir) } 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 () => { const next = async () => {
+6 -1
View File
@@ -32,7 +32,12 @@ export const SnapshotSection: React.FC<Props> = ({ locale, driverID, name, state
const loadSnapshots = () => { const loadSnapshots = () => {
if (!shown) { setSnapshots([]); return } 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(() => { useEffect(() => {
setCreatingSnap(false) setCreatingSnap(false)
+6 -1
View File
@@ -29,7 +29,12 @@ export function useSSHAccess({ locale, driverID, name, enabled, onToast, onError
useEffect(() => { useEffect(() => {
if (!enabled) { setSshUser(''); return } if (!enabled) { setSshUser(''); return }
let live = true 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 } return () => { live = false }
}, [driverID, name, enabled]) }, [driverID, name, enabled])
+6 -2
View File
@@ -1,6 +1,7 @@
import { ChevronRight, Copy } from 'lucide-react' import { ChevronRight, Copy } from 'lucide-react'
import React from 'react' import React from 'react'
import { I18nKey, t } from '../../i18n' import { I18nKey, t } from '../../i18n'
import { formatResolutionLabel } from '../../lib/format'
import { Locale, VMDetail, VMInfo } from '../../types' import { Locale, VMDetail, VMInfo } from '../../types'
import { IconButton } from '../../ui/controls' import { IconButton } from '../../ui/controls'
@@ -16,6 +17,9 @@ interface Props {
/** The raw values upstream tools use for the VM, folded by default. */ /** The raw values upstream tools use for the VM, folded by default. */
export const TechInfo: React.FC<Props> = ({ locale, name, driverID, detail, vmInfo, onCopy }) => { 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 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 = () => { const copyTechSummary = () => {
if (!detail) { if (!detail) {
if (!vmInfo) return 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('fieldCPUModel')}: ${detail.cpu_model || 'auto'}`,
`${tr('fieldGraphicsBackend')}: ${detail.graphics}`, `${tr('fieldGraphicsBackend')}: ${detail.graphics}`,
...(detail.gpu && detail.gpu !== 'auto' ? [`${tr('fieldICD')}: ${detail.gpu}`] : []), ...(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('fieldController')}: ${detail.disk_controller}`,
`${tr('fieldDisk')}: ${detail.disk}`, `${tr('fieldDisk')}: ${detail.disk}`,
`${tr('fieldNetwork')}: ${detail.network_summary || tr('off')}`, `${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('fieldCPUModel')}</dt><dd className="mono">{detail.cpu_model || 'auto'}</dd>
<dt>{tr('fieldGraphicsBackend')}</dt><dd>{detail.graphics}</dd> <dt>{tr('fieldGraphicsBackend')}</dt><dd>{detail.graphics}</dd>
{detail.gpu && detail.gpu !== 'auto' && (<><dt>{tr('fieldICD')}</dt><dd className="mono">{detail.gpu}</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('fieldController')}</dt><dd>{detail.disk_controller}</dd>
<dt>{tr('fieldDisk')}</dt><dd className="mono">{detail.disk}</dd> <dt>{tr('fieldDisk')}</dt><dd className="mono">{detail.disk}</dd>
<dt>{tr('fieldNetwork')}</dt><dd className="mono">{detail.network_summary || tr('off')}</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> = { export const coreZh: Record<string, string> = {
"affinityMenu": "处理器相关性…", "affinityMenu": "处理器相关性…",
"appearance": "外观", "appearance": "外观",
"autoResolution": "自动分辨率",
"backToEdit": "返回修改", "backToEdit": "返回修改",
"borderless": "无边框全屏", "borderless": "无边框全屏",
"cancel": "取消", "cancel": "取消",
@@ -138,6 +139,8 @@ export const coreZh: Record<string, string> = {
"quitFailed": "已取消退出", "quitFailed": "已取消退出",
"quitInProgress": "正在退出…", "quitInProgress": "正在退出…",
"refresh": "刷新", "refresh": "刷新",
"resAuto": "自动",
"resAutoValue": "自动({res})",
"resLooksLike": "看起来像 {w} × {h}", "resLooksLike": "看起来像 {w} × {h}",
"resizeLogPanel": "拖动调整日志高度", "resizeLogPanel": "拖动调整日志高度",
"resolution": "分辨率", "resolution": "分辨率",
@@ -215,6 +218,7 @@ export const coreZh: Record<string, string> = {
export const coreEn: Record<string, string> = { export const coreEn: Record<string, string> = {
"affinityMenu": "Processor Affinity…", "affinityMenu": "Processor Affinity…",
"appearance": "Appearance", "appearance": "Appearance",
"autoResolution": "Auto resolution",
"backToEdit": "Edit and retry", "backToEdit": "Edit and retry",
"borderless": "Borderless full screen", "borderless": "Borderless full screen",
"cancel": "Cancel", "cancel": "Cancel",
@@ -350,6 +354,8 @@ export const coreEn: Record<string, string> = {
"quitFailed": "Quit canceled", "quitFailed": "Quit canceled",
"quitInProgress": "Quitting…", "quitInProgress": "Quitting…",
"refresh": "Refresh", "refresh": "Refresh",
"resAuto": "Auto",
"resAutoValue": "Auto ({res})",
"resLooksLike": "Looks like {w} × {h}", "resLooksLike": "Looks like {w} × {h}",
"resizeLogPanel": "Drag to resize log panel", "resizeLogPanel": "Drag to resize log panel",
"resolution": "Resolution", "resolution": "Resolution",
-6
View File
@@ -48,7 +48,6 @@ export const pluginsZh: Record<string, string> = {
"pluginLinkDevBtn": "链接插件开发目录", "pluginLinkDevBtn": "链接插件开发目录",
"pluginLinkDevTitle": "链接本地开发插件目录", "pluginLinkDevTitle": "链接本地开发插件目录",
"pluginMarketAlphaTag": "Alpha", "pluginMarketAlphaTag": "Alpha",
"pluginMarketCurrentVersion": "当前已安装",
"pluginMarketDownloading": "下载中", "pluginMarketDownloading": "下载中",
"pluginMarketEmpty": "当前插件市场暂无可用条目,你仍可导入本地 .zip 插件包或配置自定义市场索引地址", "pluginMarketEmpty": "当前插件市场暂无可用条目,你仍可导入本地 .zip 插件包或配置自定义市场索引地址",
"pluginMarketFeedEnd": "共 {count} 个插件", "pluginMarketFeedEnd": "共 {count} 个插件",
@@ -64,8 +63,6 @@ export const pluginsZh: Record<string, string> = {
"pluginMarketKindTheme": "主题", "pluginMarketKindTheme": "主题",
"pluginMarketKindTool": "工具", "pluginMarketKindTool": "工具",
"pluginMarketLoading": "正在读取插件市场", "pluginMarketLoading": "正在读取插件市场",
"pluginMarketPickVersionInstall": "安装此版本",
"pluginMarketPickVersionTitle": "选择安装版本",
"pluginMarketRefresh": "刷新索引", "pluginMarketRefresh": "刷新索引",
"pluginMarketSearchPlaceholder": "搜索市场插件、作者或标签", "pluginMarketSearchPlaceholder": "搜索市场插件、作者或标签",
"pluginMarketSortComposite": "综合排序", "pluginMarketSortComposite": "综合排序",
@@ -173,7 +170,6 @@ export const pluginsEn: Record<string, string> = {
"pluginLinkDevBtn": "Link plugin dev folder", "pluginLinkDevBtn": "Link plugin dev folder",
"pluginLinkDevTitle": "Link local dev plugin folder", "pluginLinkDevTitle": "Link local dev plugin folder",
"pluginMarketAlphaTag": "Alpha", "pluginMarketAlphaTag": "Alpha",
"pluginMarketCurrentVersion": "Installed",
"pluginMarketDownloading": "Downloading", "pluginMarketDownloading": "Downloading",
"pluginMarketEmpty": "No plugins available in the market index yet. You can still import local .zip packages or configure a custom index URL.", "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", "pluginMarketFeedEnd": "{count} plugins",
@@ -189,8 +185,6 @@ export const pluginsEn: Record<string, string> = {
"pluginMarketKindTheme": "Themes", "pluginMarketKindTheme": "Themes",
"pluginMarketKindTool": "Tools", "pluginMarketKindTool": "Tools",
"pluginMarketLoading": "Loading the plugin market", "pluginMarketLoading": "Loading the plugin market",
"pluginMarketPickVersionInstall": "Install version",
"pluginMarketPickVersionTitle": "Select version",
"pluginMarketRefresh": "Refresh index", "pluginMarketRefresh": "Refresh index",
"pluginMarketSearchPlaceholder": "Search market plugins, publishers, or tags", "pluginMarketSearchPlaceholder": "Search market plugins, publishers, or tags",
"pluginMarketSortComposite": "Recommended", "pluginMarketSortComposite": "Recommended",
+2 -68
View File
@@ -368,40 +368,6 @@ export const settingsZh: Record<string, string> = {
"kernelIrqchipLabel": "中断加速", "kernelIrqchipLabel": "中断加速",
"kernelIrqchipOff": "关闭", "kernelIrqchipOff": "关闭",
"kernelIrqchipOn": "开启", "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": "语言", "language": "语言",
"languageSub": "内置简体中文与英语,可通过插件扩展更多语言", "languageSub": "内置简体中文与英语,可通过插件扩展更多语言",
"logLevel": "日志级别", "logLevel": "日志级别",
@@ -454,6 +420,7 @@ export const settingsZh: Record<string, string> = {
"qemuASLR": "自动为 QEMU 启用 ASLR", "qemuASLR": "自动为 QEMU 启用 ASLR",
"qemuASLRHint": "设置随运行时版本切换,虚拟机关机后再启动时生效,可能解决 macOS Dock 图标空白的问题", "qemuASLRHint": "设置随运行时版本切换,虚拟机关机后再启动时生效,可能解决 macOS Dock 图标空白的问题",
"recommendedBadge": "推荐", "recommendedBadge": "推荐",
"resAutoSub": "当前屏 {res}",
"resCustom": "自定义", "resCustom": "自定义",
"resCustomSub": "宽 × 高", "resCustomSub": "宽 × 高",
"resInvalid": "格式为 宽x高,例如 2560x1600", "resInvalid": "格式为 宽x高,例如 2560x1600",
@@ -917,40 +884,6 @@ export const settingsEn: Record<string, string> = {
"kernelIrqchipLabel": "Interrupt acceleration", "kernelIrqchipLabel": "Interrupt acceleration",
"kernelIrqchipOff": "Off", "kernelIrqchipOff": "Off",
"kernelIrqchipOn": "On", "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", "language": "Language",
"languageSub": "Simplified Chinese and English built in; add more via plugins", "languageSub": "Simplified Chinese and English built in; add more via plugins",
"logLevel": "Log level", "logLevel": "Log level",
@@ -1003,6 +936,7 @@ export const settingsEn: Record<string, string> = {
"qemuASLR": "Automatically enable ASLR for QEMU", "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", "qemuASLRHint": "Applies to the selected runtime and may restore blank macOS Dock icons after you shut down and start the VM again",
"recommendedBadge": "Recommended", "recommendedBadge": "Recommended",
"resAutoSub": "Follows display · {res}",
"resCustom": "Custom", "resCustom": "Custom",
"resCustomSub": "Width × height", "resCustomSub": "Width × height",
"resInvalid": "Use WIDTHxHEIGHT, e.g. 2560x1600", "resInvalid": "Use WIDTHxHEIGHT, e.g. 2560x1600",
+4 -37
View File
@@ -79,6 +79,7 @@ export type I18nKey =
| "audioDisabledReason" | "audioDisabledReason"
| "audioTroubleshootNote" | "audioTroubleshootNote"
| "autoPinPCores" | "autoPinPCores"
| "autoResolution"
| "back" | "back"
| "backToEdit" | "backToEdit"
| "borderless" | "borderless"
@@ -608,40 +609,6 @@ export type I18nKey =
| "kernelIrqchipLabel" | "kernelIrqchipLabel"
| "kernelIrqchipOff" | "kernelIrqchipOff"
| "kernelIrqchipOn" | "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" | "language"
| "languageSub" | "languageSub"
| "localeAuto" | "localeAuto"
@@ -798,7 +765,6 @@ export type I18nKey =
| "pluginLinkDevBtn" | "pluginLinkDevBtn"
| "pluginLinkDevTitle" | "pluginLinkDevTitle"
| "pluginMarketAlphaTag" | "pluginMarketAlphaTag"
| "pluginMarketCurrentVersion"
| "pluginMarketDownloading" | "pluginMarketDownloading"
| "pluginMarketEmpty" | "pluginMarketEmpty"
| "pluginMarketFeedEnd" | "pluginMarketFeedEnd"
@@ -814,8 +780,6 @@ export type I18nKey =
| "pluginMarketKindTheme" | "pluginMarketKindTheme"
| "pluginMarketKindTool" | "pluginMarketKindTool"
| "pluginMarketLoading" | "pluginMarketLoading"
| "pluginMarketPickVersionInstall"
| "pluginMarketPickVersionTitle"
| "pluginMarketRefresh" | "pluginMarketRefresh"
| "pluginMarketSearchPlaceholder" | "pluginMarketSearchPlaceholder"
| "pluginMarketSortComposite" | "pluginMarketSortComposite"
@@ -881,6 +845,9 @@ export type I18nKey =
| "quitInProgress" | "quitInProgress"
| "recommendedBadge" | "recommendedBadge"
| "refresh" | "refresh"
| "resAuto"
| "resAutoSub"
| "resAutoValue"
| "resCustom" | "resCustom"
| "resCustomSub" | "resCustomSub"
| "resInvalid" | "resInvalid"
+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 }
}
+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') 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 { export function graphicsLabel(locale: Locale, d: VMDetail, host: HostReport): string {
if (d.graphics && d.graphics !== 'reims-vgpu') return t(locale, 'softwareGraphics') if (d.graphics && d.graphics !== 'reims-vgpu') return t(locale, 'softwareGraphics')
const gpu = gpuLabel(locale, d.gpu, host) 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 const screens = d.displays > 1 ? `${d.displays} × ${res}` : res
return res ? `${gpu} · ${screens}` : gpu return res ? `${gpu} · ${screens}` : gpu
} }
@@ -427,6 +435,38 @@ export function fullscreenDisplayPresets(host: HostReport): FullscreenDisplayPre
return out 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 { export function recommendedResolution(host: HostReport): string {
if (host.recommended_resolution) return host.recommended_resolution if (host.recommended_resolution) return host.recommended_resolution
const rec = recommendedDisplayPresets(host).find((p) => p.recommended) 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 }) }, cpus: { label: 'factCPU', fmt: (v) => tr('cores', { n: v }) },
memory: { label: 'factMemory', fmt: (v) => formatMemory(v, locale) }, memory: { label: 'factMemory', fmt: (v) => formatMemory(v, locale) },
resolution: { label: 'resolution', fmt: resolutionLabel }, resolution: { label: 'resolution', fmt: resolutionLabel },
auto_resolution: { label: 'autoResolution', fmt: bool },
gpu: { label: 'factGraphics', fmt: (v) => gpuLabel(locale, v, host) }, gpu: { label: 'factGraphics', fmt: (v) => gpuLabel(locale, v, host) },
displays: { label: 'displays', fmt: (v) => v }, displays: { label: 'displays', fmt: (v) => v },
borderless: { label: 'borderless', fmt: bool }, borderless: { label: 'borderless', fmt: bool },
+2 -1
View File
@@ -159,8 +159,9 @@ export async function mountInteractiveThemeScript(
addDisposer(localDispose) addDisposer(localDispose)
try { try {
setup((fn) => localDisposers.push(fn)) setup((fn) => localDisposers.push(fn))
} catch { } catch (e) {
// Feature-isolated error: tear down only this feature. // Feature-isolated error: tear down only this feature.
console.warn('[uiSdk] feature setup failed:', _name, e)
localDispose() 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))
},
}
}
-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; border-radius: 4px; font-size: 10px; font-weight: 600; flex-shrink: 0;
color: var(--amber); background: color-mix(in srgb, var(--amber) 14%, transparent); 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 { color: inherit; text-decoration: none; }
.plugin-title-link:hover { color: var(--accent); text-decoration: underline; text-underline-offset: 2px; } .plugin-title-link:hover { color: var(--accent); text-decoration: underline; text-underline-offset: 2px; }
.market-card-action { flex-shrink: 0; } .market-card-action { flex-shrink: 0; }
-21
View File
@@ -215,24 +215,3 @@ export interface LogEntry {
source: string source: string
line: 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 { import type {
ActiveThemePayload, AppState, CachedInstaller, DataRootChoice, DriverSummary, ActiveThemePayload, AppState, CachedInstaller, DataRootChoice, DriverSummary,
LogEntry, MarketBrowseResult, PluginInfo, PluginUIContributions, RemoteRuntime, LogEntry, MarketBrowseResult, PluginInfo, PluginUIContributions, RemoteRuntime,
ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMInfo, VMNetworkSettings, VMNetworkPlan, VMKeymapStatus, VMKeymapUpdate, ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMInfo, VMNetworkSettings, VMNetworkPlan,
} from './types' } from './types'
type AnyFn = (...args: never[]) => unknown type AnyFn = (...args: never[]) => unknown
@@ -157,9 +157,7 @@ export const api = {
GetTasks: boundGo.GetTasks as () => Promise<Task[]>, GetTasks: boundGo.GetTasks as () => Promise<Task[]>,
GetVMAffinity: boundGo.GetVMAffinity as (driverID: string, name: string) => Promise<VMAffinityStatus>, GetVMAffinity: boundGo.GetVMAffinity as (driverID: string, name: string) => Promise<VMAffinityStatus>,
SetVMAffinity: boundGo.SetVMAffinity as (driverID: string, name: string, req: VMAffinityUpdate) => 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>, 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>, ListInstallers: boundGo.ListInstallers as () => Promise<CachedInstaller[] | null>,
ListRemoteRuntimes: boundGo.ListRemoteRuntimes as () => Promise<RemoteRuntime[] | null>, ListRemoteRuntimes: boundGo.ListRemoteRuntimes as () => Promise<RemoteRuntime[] | null>,
SuggestDataRoots: boundGo.SuggestDataRoots as () => Promise<DataRootChoice[] | null>, SuggestDataRoots: boundGo.SuggestDataRoots as () => Promise<DataRootChoice[] | null>,
-4
View File
@@ -122,8 +122,6 @@ export function GetVMEndpointCommand(arg1:string,arg2:string,arg3:string):Promis
export function GetVMInfo(arg1:string,arg2:string):Promise<driver.VMInfo>; 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 GetVMMacOS(arg1:string):Promise<string>;
export function GetVMNetworkPlan(arg1:string,arg2:string,arg3:string):Promise<app.VMNetworkPlan>; export function GetVMNetworkPlan(arg1:string,arg2:string,arg3:string):Promise<app.VMNetworkPlan>;
@@ -278,8 +276,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 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 SetVMNote(arg1:string,arg2:string,arg3:string):Promise<void>;
export function SetVMSSHUser(arg1:string,arg2:string,arg3:string):Promise<void>; export function SetVMSSHUser(arg1:string,arg2:string,arg3:string):Promise<void>;
-8
View File
@@ -222,10 +222,6 @@ export function GetVMInfo(arg1, arg2) {
return window['go']['app']['App']['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) { export function GetVMMacOS(arg1) {
return window['go']['app']['App']['GetVMMacOS'](arg1); return window['go']['app']['App']['GetVMMacOS'](arg1);
} }
@@ -534,10 +530,6 @@ export function SetVMDriveShareSettings(arg1, arg2, arg3) {
return window['go']['app']['App']['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) { export function SetVMNote(arg1, arg2, arg3) {
return window['go']['app']['App']['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; 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 { export class VMNetworkPlan {
npcap_installed: boolean; npcap_installed: boolean;
running_vms: string[]; running_vms: string[];
@@ -1244,6 +1196,8 @@ export namespace host {
scale_pct: number; scale_pct: number;
refresh_hz?: number; refresh_hz?: number;
primary: boolean; primary: boolean;
left?: number;
top?: number;
work_width?: number; work_width?: number;
work_height?: number; work_height?: number;
@@ -1260,6 +1214,8 @@ export namespace host {
this.scale_pct = source["scale_pct"]; this.scale_pct = source["scale_pct"];
this.refresh_hz = source["refresh_hz"]; this.refresh_hz = source["refresh_hz"];
this.primary = source["primary"]; this.primary = source["primary"];
this.left = source["left"];
this.top = source["top"];
this.work_width = source["work_width"]; this.work_width = source["work_width"];
this.work_height = source["work_height"]; this.work_height = source["work_height"];
} }
@@ -3023,6 +2979,7 @@ export namespace reims {
graphics?: string; graphics?: string;
gpu?: string; gpu?: string;
resolution?: string; resolution?: string;
auto_resolution?: boolean;
displays?: number; displays?: number;
borderless?: boolean; borderless?: boolean;
capture?: boolean; capture?: boolean;
@@ -3057,6 +3014,7 @@ export namespace reims {
this.graphics = source["graphics"]; this.graphics = source["graphics"];
this.gpu = source["gpu"]; this.gpu = source["gpu"];
this.resolution = source["resolution"]; this.resolution = source["resolution"];
this.auto_resolution = source["auto_resolution"];
this.displays = source["displays"]; this.displays = source["displays"];
this.borderless = source["borderless"]; this.borderless = source["borderless"];
this.capture = source["capture"]; this.capture = source["capture"];
@@ -3079,6 +3037,7 @@ export namespace reims {
disk_controller?: string; disk_controller?: string;
disk_cache?: string; disk_cache?: string;
resolution?: string; resolution?: string;
auto_resolution?: boolean;
borderless?: boolean; borderless?: boolean;
capture?: boolean; capture?: boolean;
gpu?: string; gpu?: string;
@@ -3108,6 +3067,7 @@ export namespace reims {
this.disk_controller = source["disk_controller"]; this.disk_controller = source["disk_controller"];
this.disk_cache = source["disk_cache"]; this.disk_cache = source["disk_cache"];
this.resolution = source["resolution"]; this.resolution = source["resolution"];
this.auto_resolution = source["auto_resolution"];
this.borderless = source["borderless"]; this.borderless = source["borderless"];
this.capture = source["capture"]; this.capture = source["capture"];
this.gpu = source["gpu"]; this.gpu = source["gpu"];
@@ -3186,6 +3146,7 @@ export namespace reims {
display: string; display: string;
displays: number; displays: number;
resolution: string; resolution: string;
auto_resolution: boolean;
gpu: string; gpu: string;
has_opencore: boolean; has_opencore: boolean;
has_installer: boolean; has_installer: boolean;
@@ -3240,6 +3201,7 @@ export namespace reims {
this.display = source["display"]; this.display = source["display"];
this.displays = source["displays"]; this.displays = source["displays"];
this.resolution = source["resolution"]; this.resolution = source["resolution"];
this.auto_resolution = source["auto_resolution"];
this.gpu = source["gpu"]; this.gpu = source["gpu"];
this.has_opencore = source["has_opencore"]; this.has_opencore = source["has_opencore"];
this.has_installer = source["has_installer"]; this.has_installer = source["has_installer"];
+8 -13
View File
@@ -150,16 +150,17 @@ type App struct {
displayPlacements sync.Map displayPlacements sync.Map
keymapMu sync.Mutex
keymapPIDs map[string]int
fallbackInputSvc *host.InputService
inputShuttingDown bool inputShuttingDown bool
// computerUseOwnedVMs caches ownership markers for MCP-created temporary VMs. // computerUseOwnedVMs caches ownership markers for MCP-created temporary VMs.
computerUseOwnedVMs map[string]map[string]bool computerUseOwnedVMs map[string]map[string]bool
computerUseCloneMu sync.Mutex computerUseCloneMu sync.Mutex
fullscreenHotkey host.FullscreenHotkeyService // computerUseHeld records the keys and pointer buttons each plugin left
fullscreenSyncMu sync.Mutex // held in a guest, so the host can release them when the plugin goes away.
fullscreenTargets fullscreenHotkeyTargetCache computerUseHeld map[string]map[string]*heldInputs
computerUseHeldMu sync.Mutex
fullscreenHotkey host.FullscreenHotkeyService
fullscreenSyncMu sync.Mutex
fullscreenTargets fullscreenHotkeyTargetCache
// Plugin elevation requests (elevate_flow.go). // Plugin elevation requests (elevate_flow.go).
elevatePromptMu sync.Mutex elevatePromptMu sync.Mutex
@@ -309,12 +310,8 @@ func (a *App) shutdown(ctx context.Context) {
a.stopPluginControlServer() a.stopPluginControlServer()
a.mu.Lock() a.mu.Lock()
a.inputShuttingDown = true a.inputShuttingDown = true
fallback := a.fallbackInputSvc
a.mu.Unlock() a.mu.Unlock()
a.fullscreenHotkey.Close() a.fullscreenHotkey.Close()
if fallback != nil {
fallback.Close()
}
a.shutdownPlugins() a.shutdownPlugins()
a.mu.Lock() a.mu.Lock()
for name, entry := range a.rebootWatchers { for name, entry := range a.rebootWatchers {
@@ -545,10 +542,8 @@ func (a *App) startTray() {
} }
items = append(items, tray.VMItem{DriverID: vm.DriverID, Name: vm.Name, Label: label, State: state}) items = append(items, tray.VMItem{DriverID: vm.DriverID, Name: vm.Name, Label: label, State: state})
} }
effLoc := i18n.EffectiveLocale(loc)
return tray.Snapshot{ return tray.Snapshot{
Locale: effLoc, Locale: i18n.EffectiveLocale(loc),
LocaleZh: effLoc == i18n.ZhCN,
CanSuspend: canSuspend, CanSuspend: canSuspend,
VMs: items, VMs: items,
} }
+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.lastVMs = []reims.VMListItem{{Name: "m0", Dir: `D:\vms\m0`, PID: &pid, State: "running"}}
a.lastVMsAt = time.Now() a.lastVMsAt = time.Now()
vm, ok := a.polledVM("m0") vms, err := a.polledVMs(context.Background())
if !ok || vm.State != "running" || vm.Dir != `D:\vms\m0` || *vm.PID != 42 { if err != nil || len(vms) != 1 || vms[0].Name != "m0" {
t.Fatalf("polledVM = %+v, %v", vm, ok) 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" vms[0].State = "stopped"
if a.lastVMs[0].State != "running" { if a.lastVMs[0].State != "running" {
t.Fatal("polledVMs must return a copy, not the cached slice") 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. // running; Guest Tools reconnects once the new window is up.
import ( import (
"archive/zip"
"context" "context"
"crypto/sha256"
"encoding/hex"
"errors" "errors"
"fmt" "fmt"
"io"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -121,8 +125,10 @@ func (a *App) DownloadAppUpdate() (string, error) {
return id, nil return id, nil
} }
// downloadAppUpdate fetches info's executable into dir and checks it against // downloadAppUpdate fetches info's release asset (.zip or .exe) into dir,
// GitHub's assets[].digest SHA-256. It returns the file and its hash. // 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) { func downloadAppUpdate(ctx context.Context, info version.UpdateInfo, dir string, onProgress fetch.Progress) (string, string, error) {
want := strings.ToLower(strings.TrimSpace(info.AssetSHA256)) want := strings.ToLower(strings.TrimSpace(info.AssetSHA256))
if len(want) != 64 { if len(want) != 64 {
@@ -136,9 +142,64 @@ func downloadAppUpdate(ctx context.Context, info version.UpdateInfo, dir string,
if err != nil { if err != nil {
return "", "", err 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 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, // InstallAppUpdate swaps the downloaded update in for the running executable,
// starts it, and quits this window. The new window waits for this process to // starts it, and quits this window. The new window waits for this process to
// exit before it opens. Running VMs are not touched. // exit before it opens. Running VMs are not touched.
+57
View File
@@ -1,6 +1,8 @@
package app package app
import ( import (
"archive/zip"
"bytes"
"context" "context"
"crypto/sha256" "crypto/sha256"
"encoding/hex" "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) { func TestInstallAppUpdateGuards(t *testing.T) {
cfg := config.Default() cfg := config.Default()
cfg.Locale = i18n.EnUS cfg.Locale = i18n.EnUS
+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.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.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.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.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.computerUseHeld == nil {
a.computerUseHeld = map[string]map[string]*heldInputs{}
}
byVM := a.computerUseHeld[pluginID]
if byVM == nil {
byVM = map[string]*heldInputs{}
a.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.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.computerUseHeld, pluginID)
}
}
// heldSnapshot returns what one plugin holds in one VM, sorted, with the
// generation it was read at.
func (a *App) heldSnapshot(pluginID, vmKey string) (keys, buttons []string, generation uint64) {
a.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
byVM := a.computerUseHeld[pluginID]
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.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
if held := a.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.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
out := map[string]bool{}
for vmKey := range a.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.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
held := a.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.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
held := a.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.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
held := a.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.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.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)
}
}
+215 -215
View File
@@ -14,24 +14,20 @@ import (
"time" "time"
"unicode/utf8" "unicode/utf8"
"github.com/Nwflower/reims-go/internal/console"
"github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n" "github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/thumb" "github.com/Nwflower/reims-go/internal/thumb"
"github.com/Nwflower/reims-go/pkg/pluginproto"
) )
const computerUsePreviewWidth = 1280 const computerUsePreviewWidth = 1280
const computerUseMaxImageWidth = 2560 const computerUseMaxImageWidth = 2560
const computerUseMinImageWidth = 64
const computerUseMaxTextRunes = 4000 const computerUseMaxTextRunes = 4000
const computerUseSecretPluginID = "reims.agent"
const computerUseOwnershipFile = ".reims-go-computer-use" 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 { type computerUseOwnership struct {
Version int `json:"version"` Version int `json:"version"`
@@ -44,52 +40,45 @@ type computerUseOwnership struct {
SourceVM string `json:"source_vm,omitempty"` 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 { func (a *App) computerUseHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
if mgr == nil || mgr.Broker() == nil { if mgr == nil || mgr.Broker() == nil {
return nil return nil
} }
handlers := map[string]plugin.RPCRequestHandler{ return map[string]plugin.RPCRequestHandler{
"host/vm.list": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:read", "host/vm.list", a.handleComputerUseVMList), "host/vm.list": a.hostVMMethod(mgr, pluginID, "host/vm.list", a.handleComputerUseVMList),
"host/vm.get": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:read", "host/vm.get", a.handleComputerUseVMGet), "host/vm.get": a.hostVMMethod(mgr, pluginID, "host/vm.get", a.handleComputerUseVMGet),
"host/vm.start": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.start", a.handleComputerUseVMStart), "host/vm.start": a.hostVMMethod(mgr, pluginID, "host/vm.start", a.handleComputerUseVMStart),
"host/vm.shutdown": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.shutdown", a.handleComputerUseVMShutdown), "host/vm.shutdown": a.hostVMMethod(mgr, pluginID, "host/vm.shutdown", a.handleComputerUseVMShutdown),
"host/vm.suspend": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.suspend", a.handleComputerUseVMStateChange(a.SuspendVM)), "host/vm.suspend": a.hostVMMethod(mgr, pluginID, "host/vm.suspend", a.handleComputerUseVMStateChange("host/vm.suspend", a.SuspendVM)),
"host/vm.resume": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.resume", a.handleComputerUseVMStateChange(a.ResumeVM)), "host/vm.resume": a.hostVMMethod(mgr, pluginID, "host/vm.resume", a.handleComputerUseVMStateChange("host/vm.resume", a.ResumeVM)),
"host/vm.clone": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.clone", a.handleComputerUseVMClone), "host/vm.clone": a.hostVMMethod(mgr, pluginID, "host/vm.clone", a.handleComputerUseVMClone),
"host/vm.delete": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.delete", a.handleComputerUseVMDelete), "host/vm.delete": a.hostVMMethod(mgr, pluginID, "host/vm.delete", a.handleComputerUseVMDelete),
"host/vm.snapshot.list": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:read", "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList), "host/vm.snapshot.list": a.hostVMMethod(mgr, pluginID, "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.create": a.hostVMMethod(mgr, pluginID, "host/vm.snapshot.create", a.handleComputerUseVMSnapshotCreate),
"host/vm.snapshot.restore": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.snapshot.restore", a.handleComputerUseVMSnapshotRestore), "host/vm.snapshot.restore": a.hostVMMethod(mgr, pluginID, "host/vm.snapshot.restore", a.handleComputerUseVMSnapshotRestore),
"host/console.screenshot": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:screen", "host/console.screenshot", a.handleComputerUseScreenshot), "host/console.screenshot": a.hostVMMethod(mgr, pluginID, "host/console.screenshot", a.handleComputerUseScreenshot),
"host/console.pointer": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.pointer", a.handleComputerUsePointer), "host/console.pointer": a.hostVMMethod(mgr, pluginID, "host/console.pointer", a.handleComputerUsePointer),
"host/console.key": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.key", a.handleComputerUseKey), "host/console.key": a.hostVMMethod(mgr, pluginID, "host/console.key", a.handleComputerUseKey),
"host/console.type": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.type", a.handleComputerUseType), "host/console.type": a.hostVMMethod(mgr, pluginID, "host/console.type", a.handleComputerUseType),
"host/console.release": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.release", a.handleComputerUseRelease), "host/console.typeSecret": a.hostVMMethod(mgr, pluginID, "host/console.typeSecret", a.handleComputerUseTypeSecret),
"host/console.release": a.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) 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 { // handleComputerUseTypeSecret types one of the calling plugin's own settings
return a.authorizedComputerUseHandler(mgr, pluginID, permission, method, func(ctx context.Context, raw json.RawMessage) (any, error) { // into a VM the user authorized that plugin to access. The host never returns
return run(ctx, raw, mgr, pluginID) // 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) { func (a *App) handleComputerUseTypeSecret(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
if pluginID != computerUseSecretPluginID { req, err := decodeHostParams[pluginproto.TypeSecretParams](mgr, pluginID, "host/console.typeSecret", raw)
return nil, errors.New("secret typing is reserved for reims.agent") if err != nil {
}
var req struct {
VM string `json:"vm"`
Setting string `json:"setting"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err return nil, err
} }
if strings.TrimSpace(req.Setting) == "" { if strings.TrimSpace(req.Setting) == "" {
@@ -126,15 +115,18 @@ func (a *App) handleComputerUseTypeSecret(ctx context.Context, raw json.RawMessa
if err != nil { if err != nil {
return nil, err 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) items, err := a.listVMsInternal(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
vms := make([]map[string]any, 0, len(items)) vms := make([]pluginproto.VMView, 0, len(items))
for _, item := range items { for _, item := range items {
info, err := a.resolveVMInfo(item.DriverID, item.Name) info, err := a.resolveVMInfo(item.DriverID, item.Name)
if err != nil { 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)) 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) { func (a *App) handleComputerUseVMGet(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct { req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, "host/vm.get", raw)
VM string `json:"vm"` if err != nil {
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err return nil, err
} }
info, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM) 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 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()) accessEnabled := a.computerUseVMAccessEnabled(mgr, pluginID, vm.Ref().Key())
view := map[string]any{ view := pluginproto.VMView{
"vm": vm.Ref().Key(), VM: vm.Ref().Key(),
"name": vm.Name, Name: vm.Name,
"driver_id": vm.DriverID, DriverID: vm.DriverID,
"state": vm.State, State: vm.State,
"authorized": accessEnabled, Authorized: accessEnabled,
"phase": computerUseVMPhase(vm), Phase: computerUseVMPhase(vm),
"owned": a.computerUseOwned(pluginID, vm.Ref().Key()), Owned: a.computerUseOwned(pluginID, vm.Ref().Key()),
} }
if vm.CPUs > 0 { if vm.CPUs > 0 {
view["cpus"] = vm.CPUs view.CPUs = vm.CPUs
} }
if vm.Memory != "" { if vm.Memory != "" {
view["memory"] = vm.Memory view.Memory = vm.Memory
} }
if vm.DiskSummary != "" { if vm.DiskSummary != "" {
view["disk_summary"] = vm.DiskSummary view.DiskSummary = vm.DiskSummary
} }
if accessEnabled && vm.SSHPort > 0 { if accessEnabled && vm.SSHPort > 0 {
view["ssh_port"] = vm.SSHPort view.SSHPort = vm.SSHPort
} }
if len(vm.Capabilities) > 0 { if len(vm.Capabilities) > 0 {
view["capabilities"] = append([]string(nil), vm.Capabilities...) view.Capabilities = append([]string(nil), vm.Capabilities...)
} }
if accessEnabled { if accessEnabled {
if username := a.computerUseSSHUser(mgr, pluginID, vm); username != "" { if username := a.computerUseSSHUser(mgr, pluginID, vm); username != "" {
view["ssh_username"] = username view.SSHUsername = username
} }
} }
return view return view
} }
func (a *App) handleComputerUseVMStart(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) { func (a *App) handleComputerUseVMStart(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct { req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, "host/vm.start", raw)
VM string `json:"vm"` if err != nil {
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err return nil, err
} }
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM) 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 { if err := a.StartVM(vm.DriverID, vm.Name); err != nil {
return nil, err 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) { func (a *App) handleComputerUseVMShutdown(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct { req, err := decodeHostParams[pluginproto.VMShutdownParams](mgr, pluginID, "host/vm.shutdown", raw)
VM string `json:"vm"` if err != nil {
Force bool `json:"force"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err return nil, err
} }
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM) 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 { if err := a.StopVM(vm.DriverID, vm.Name, req.Force); err != nil {
return nil, err 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) { return func(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct { req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, method, raw)
VM string `json:"vm"` if err != nil {
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err return nil, err
} }
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM) vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
@@ -243,28 +226,19 @@ func (a *App) handleComputerUseVMStateChange(change func(driverID, name string)
if err := change(vm.DriverID, vm.Name); err != nil { if err := change(vm.DriverID, vm.Name); err != nil {
return nil, err 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) { func (a *App) handleComputerUseVMClone(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct { req, err := decodeHostParams[pluginproto.VMCloneParams](mgr, pluginID, "host/vm.clone", raw)
VM string `json:"vm"` if err != nil {
CloneName string `json:"clone_name"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err return nil, err
} }
cloneName := strings.TrimSpace(req.CloneName) cloneName := strings.TrimSpace(req.CloneName)
if cloneName == "" { if cloneName == "" {
return nil, errors.New("clone_name is required") 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) vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -294,20 +268,22 @@ func (a *App) handleComputerUseVMClone(ctx context.Context, raw json.RawMessage,
// inventory poll. Return the canonical reference immediately so callers can // inventory poll. Return the canonical reference immediately so callers can
// start the clone without turning a successful clone into a false failure. // start the clone without turning a successful clone into a false failure.
a.markComputerUseOwnedVM(pluginID, cloneRef.Key(), true) 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) { func (a *App) handleComputerUseVMDelete(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct { req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, "host/vm.delete", raw)
VM string `json:"vm"` if err != nil {
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err return nil, err
} }
vm, err := a.resolveComputerUseVMInfo(req.VM) vm, err := a.resolveComputerUseVMInfo(req.VM)
if err != nil { if err != nil {
return nil, err 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()) { if !a.computerUseOwned(pluginID, vm.Ref().Key()) {
return nil, a.computerUseHostError("not_authorized", "err.computer_use.not_owned", i18n.Vars{"name": vm.Name}) 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) removeComputerUseOwnership(vm.Directory)
a.markComputerUseOwnedVM(pluginID, vm.Ref().Key(), false) 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) { func (a *App) handleComputerUseVMSnapshotList(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct { req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, "host/vm.snapshot.list", raw)
VM string `json:"vm"` if err != nil {
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err return nil, err
} }
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM) 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 { if err != nil {
return nil, err 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) { func (a *App) handleComputerUseVMSnapshotCreate(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct { req, err := decodeHostParams[pluginproto.SnapshotNameParams](mgr, pluginID, "host/vm.snapshot.create", raw)
VM string `json:"vm"` if err != nil {
Name string `json:"name"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err return nil, err
} }
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM) 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 { if err := a.CreateSnapshot(vm.DriverID, vm.Name, req.Name); err != nil {
return nil, err 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) { func (a *App) handleComputerUseVMSnapshotRestore(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct { req, err := decodeHostParams[pluginproto.SnapshotNameParams](mgr, pluginID, "host/vm.snapshot.restore", raw)
VM string `json:"vm"` if err != nil {
Name string `json:"name"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err return nil, err
} }
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM) vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil { if err != nil {
return nil, err 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 { if err := a.RestoreSnapshot(vm.DriverID, vm.Name, req.Name); err != nil {
return nil, err 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
}
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
}
} }
// resolveComputerUseVM returns the VM and the console route Agent calls use. // 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 { if err != nil {
return driver.VMInfo{}, consoleRoute{}, err return driver.VMInfo{}, consoleRoute{}, err
} }
// A plugin that stopped calling mid-hold must not leave a key down.
route, err := a.resolveConsoleRoute(vm) route, err := a.resolveConsoleRoute(vm)
if err != nil { if err != nil {
return driver.VMInfo{}, consoleRoute{}, err return driver.VMInfo{}, consoleRoute{}, err
} }
current, ok := a.polledVMForDriver(vm.DriverID, vm.Name) current, ok := a.polledVMForDriver(vm.DriverID, vm.Name)
if !ok || current.State != "running" { 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}) 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) { 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}) return driver.VMInfo{}, consoleRoute{}, a.computerUseHostError("vm_not_running", "err.computer_use.vm_not_running", i18n.Vars{"name": vm.Name})
} }
if vm.Phase == "" { if vm.Phase == "" {
@@ -561,8 +525,11 @@ func removeComputerUseOwnership(vmDir string) {
_ = os.Remove(filepath.Join(vmDir, computerUseOwnershipFile)) _ = 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) { func readComputerUseOwnership(vm driver.VMInfo) (computerUseOwnership, bool) {
if vm.Directory == "" || !isComputerUseCloneName(vm.Name) { if vm.Directory == "" {
return computerUseOwnership{}, false return computerUseOwnership{}, false
} }
raw, err := os.ReadFile(filepath.Join(vm.Directory, computerUseOwnershipFile)) raw, err := os.ReadFile(filepath.Join(vm.Directory, computerUseOwnershipFile))
@@ -635,7 +602,7 @@ func persistComputerUseOwnership(vm driver.VMInfo, pluginID, vmKey, sourceVM str
func (a *App) syncComputerUseOwnership(vms []driver.VMListItem) { func (a *App) syncComputerUseOwnership(vms []driver.VMListItem) {
for _, item := range vms { for _, item := range vms {
vm := driver.VMInfo{Name: item.Name, DriverID: item.DriverID, Directory: item.Dir} vm := driver.VMInfo{Name: item.Name, DriverID: item.DriverID, Directory: item.Dir}
if vm.Directory == "" || !isComputerUseCloneName(vm.Name) { if vm.Directory == "" {
continue continue
} }
marker, ok := readComputerUseOwnership(vm) marker, ok := readComputerUseOwnership(vm)
@@ -827,26 +794,23 @@ func computerUseRegionToSource(region computerUseRegion, refW, refH int, source
return computerUseRegion{X: x0, Y: y0, Width: x1 - x0, Height: y1 - y0} 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) { // computerUseScreenshotWidth returns the width the returned image is scaled
var req struct { // to. A request outside the supported range is brought into it rather than
VM string `json:"vm"` // refused, so a caller that asks for more than the host encodes still gets a
Region *computerUseRegion `json:"region"` // usable frame.
MaxWidth int `json:"max_width"` func computerUseScreenshotWidth(requested int) int {
// Width and Height name the image the region was measured in; without if requested == 0 {
// them the region is in source pixels. return computerUsePreviewWidth
Width int `json:"width"`
Height int `json:"height"`
} }
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 return nil, err
} }
maxWidth := req.MaxWidth maxWidth := computerUseScreenshotWidth(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)
}
if req.Region != nil && (req.Region.Width <= 0 || req.Region.Height <= 0) { if req.Region != nil && (req.Region.Width <= 0 || req.Region.Height <= 0) {
return nil, errors.New("region width and height must be positive") return nil, errors.New("region width and height must be positive")
} }
@@ -873,7 +837,9 @@ func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessa
frame image.Image frame image.Image
blank bool 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 { if req.Region == nil {
// A blank frame is a normal screen state during boot, login and display // 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. // switches. Return it with a flag so pollers can keep waiting through it.
@@ -887,115 +853,149 @@ func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessa
return nil, err return nil, err
} }
var applied computerUseRegion var applied computerUseRegion
region := computerUseRegionToSource(*req.Region, req.Width, req.Height, full.Bounds().Size()) region := computerUseRegionToSource(computerUseRegion{
result["source_width"], result["source_height"] = full.Bounds().Dx(), full.Bounds().Dy() 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) frame, applied, err = computerUseRegionFrame(full, region, maxWidth)
if err != nil { if err != nil {
return nil, err return nil, err
} }
blank = thumb.Blank(full) 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) encoded, err := thumb.JPEG(frame, 84)
if err != nil { if err != nil {
return nil, err return nil, err
} }
bounds := frame.Bounds() bounds := frame.Bounds()
result["width"] = bounds.Dx() result.Width = bounds.Dx()
result["height"] = bounds.Dy() result.Height = bounds.Dy()
result["blank"] = blank result.Blank = blank
result["data"] = base64.StdEncoding.EncodeToString(encoded) result.Data = base64.StdEncoding.EncodeToString(encoded)
return result, nil 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) { func (a *App) handleComputerUsePointer(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct { req, err := decodeHostParams[pluginproto.PointerParams](mgr, pluginID, "host/console.pointer", raw)
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)
if err != nil { if err != nil {
return nil, err 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{ if err := a.consolePointer(ctx, route, driver.ConsolePointerRequest{
Action: req.Action, X: req.X, Y: req.Y, Width: req.Width, Height: req.Height, 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, Button: req.Button, Down: req.Down, Delta: req.Delta, Horizontal: req.Horizontal,
}); err != nil { }); err != nil {
return nil, err 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) { func (a *App) handleComputerUseKey(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct { req, err := decodeHostParams[pluginproto.KeyParams](mgr, pluginID, "host/console.key", raw)
VM string `json:"vm"` if err != nil {
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 {
return nil, err return nil, err
} }
if strings.TrimSpace(req.Key) == "" { if strings.TrimSpace(req.Key) == "" {
return nil, errors.New("key is required") return nil, errors.New("key is required")
} }
if req.Down != nil && len(req.Modifiers) > 0 { vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
return nil, errors.New("a held key takes no modifiers; hold each key separately")
}
_, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if req.Down != nil { if req.Down == nil {
err = a.consoleKeyState(ctx, route, req.Key, *req.Down) if err := a.consoleKey(ctx, route, req.Key, req.Modifiers); err != nil {
} else { return nil, err
err = a.consoleKey(ctx, route, req.Key, req.Modifiers) }
return pluginproto.OKResult{OK: true}, nil
} }
if err != nil { // A held key may carry modifiers: each one is held or released with it, so
return nil, err // 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 // handleComputerUseRelease lifts the given keys and pointer buttons in one
// report, so a client that stops mid-gesture never leaves input held. // 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) { func (a *App) handleComputerUseRelease(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct { req, err := decodeHostParams[pluginproto.ReleaseParams](mgr, pluginID, "host/console.release", raw)
VM string `json:"vm"` if err != nil {
Keys []string `json:"keys"`
Buttons []string `json:"buttons"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err return nil, err
} }
_, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM) vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if err := a.consoleRelease(ctx, route, req.Keys, req.Buttons); err != nil { if err := a.consoleRelease(ctx, route, req.Keys, req.Buttons); err != nil {
return nil, err 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) { func (a *App) handleComputerUseType(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct { req, err := decodeHostParams[pluginproto.TypeParams](mgr, pluginID, "host/console.type", raw)
VM string `json:"vm"` if err != nil {
Text string `json:"text"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err return nil, err
} }
if len(req.Text) == 0 || !utf8.ValidString(req.Text) { if len(req.Text) == 0 || !utf8.ValidString(req.Text) {
@@ -1018,5 +1018,5 @@ func (a *App) handleComputerUseType(ctx context.Context, raw json.RawMessage, mg
if err != nil { if err != nil {
return nil, err 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" "time"
"github.com/Nwflower/reims-go/internal/driver" "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/i18n"
"github.com/Nwflower/reims-go/internal/macos/installer" "github.com/Nwflower/reims-go/internal/macos/installer"
"github.com/Nwflower/reims-go/internal/macos/opencore" "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/networkmsg"
"github.com/Nwflower/reims-go/internal/packetbridge" "github.com/Nwflower/reims-go/internal/packetbridge"
rt "github.com/Nwflower/reims-go/internal/runtime" 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() { defer func() {
var coded *i18n.CodedError var coded *i18n.CodedError
if errors.As(err, &coded) && strings.HasPrefix(coded.Code, "E_NETWORK_") { 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) 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 // Always defer starting to StartVM so commit-memory checks, Win10 cold-reboot
// QMP wiring, and Win11 WHPX nested-virt fallback apply uniformly. // 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" 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) err = c.Create(ctx, opts, w, w)
if err != nil { if err != nil {
if ctx.Err() != nil { if ctx.Err() != nil {
@@ -195,6 +201,12 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
finishTask(err) finishTask(err)
return fmt.Errorf("record VM driver ownership: %w", 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 { if postSet, ok := reims.PostCreateSetOptsWithCapture(opts, c.AllowsSetCapture()); ok {
var parts []string var parts []string
if postSet.DiskController != "" { if postSet.DiskController != "" {
+4 -1
View File
@@ -3,6 +3,7 @@ package app
import ( import (
"errors" "errors"
"fmt" "fmt"
"os"
"strings" "strings"
"github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/config"
@@ -27,7 +28,9 @@ func (a *App) openDataRoot() dataroot.Status {
a.syncClipboardStagingLocked() a.syncClipboardStagingLocked()
a.mu.Unlock() a.mu.Unlock()
a.logDataRoot(st) 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) a.relocateRegisteredVMs(dir, prevRoot)
} }
return st return st
+57 -19
View File
@@ -9,6 +9,7 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/Nwflower/reims-go/internal/cli"
"github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/datamigrate" "github.com/Nwflower/reims-go/internal/datamigrate"
"github.com/Nwflower/reims-go/internal/dataroot" "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 { if err := config.Save(filepath.Join(newRoot, "reims-go.json"), oldCfg); err != nil {
t.Fatal(err) t.Fatal(err)
} }
newVMDir := filepath.Join((&config.Config{DataRoot: newRoot}).XDGDataDir(), "reims-ctl", "vms", "macos-tahoe") _, newVMDir := writeMovedVMRegistry(t, oldRoot, newRoot)
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)
}
a := &App{ a := &App{
cfg: &config.Config{DataRoot: oldRoot, Locale: "zh-CN"}, 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 { if err := a.setDataRoot(newRoot, noopASLR); err != nil {
t.Fatalf("setDataRoot: %v", err) 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 { if err != nil {
t.Fatalf("ListRegisteredVMs: %v", err) t.Fatalf("ListRegisteredVMs: %v", err)
} }
if len(vms) != 1 { if len(vms) != 1 {
t.Fatalf("got %d vms, want 1", len(vms)) t.Fatalf("got %d vms, want 1", len(vms))
} }
if !strings.EqualFold(filepath.Clean(vms[0].Directory), filepath.Clean(newVMDir)) { if vms[0].Directory != want {
t.Fatalf("vm dir = %q, want %q", vms[0].Directory, newVMDir) 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() placement.Lock()
defer placement.Unlock() defer placement.Unlock()
displays := a.displayHost.displays() status, err := saveVMTargetDisplay(vm, targetDisplay, a.displayHost.displays())
cfg := vmstart.VMDisplayConfig{TargetDisplay: vmstart.NormalizeTargetDisplay(targetDisplay)} if err != nil {
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 {
return VMDisplayStatus{}, err return VMDisplayStatus{}, err
} }
defer a.emitStateChanged() defer a.emitStateChanged()
if !status.Running || len(displays) == 0 { if !status.Running || len(status.Displays) == 0 {
return status, nil return status, nil
} }
if status.FallbackToPrimary { 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) { if driver.IsHosted(vm.Capabilities) {
// The driver owns a hosted VM's display; only the choice is saved. // 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 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 { func displayFallbackLog(target string) string {
return fmt.Sprintf("Display %q is disconnected. Using the primary display.", target) 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) { func TestSetVMDisplayReadOnly(t *testing.T) {
const driverID = driver.BuiltinReimsMacOSDriverID const driverID = driver.BuiltinReimsMacOSDriverID
vm := driver.VMInfo{Name: "test-vm", DriverID: driverID, Directory: t.TempDir(), State: "stopped"} 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/host"
"github.com/Nwflower/reims-go/internal/netproxy" "github.com/Nwflower/reims-go/internal/netproxy"
"github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginproto"
) )
const ( const (
@@ -50,7 +51,7 @@ func (a *App) downloadHostHandlers(mgr *plugin.Manager, pluginID string) map[str
} }
broker := mgr.Broker() broker := mgr.Broker()
return map[string]plugin.RPCRequestHandler{ return map[string]plugin.RPCRequestHandler{
"host/download.start": func(_ context.Context, raw json.RawMessage) (any, error) { "host/download.start": a.hostMethod(mgr, pluginID, "host/download.start", func(_ context.Context, raw json.RawMessage) (any, error) {
a.mu.Lock() a.mu.Lock()
dataRoot := "" dataRoot := ""
if a.cfg != nil { if a.cfg != nil {
@@ -59,22 +60,11 @@ func (a *App) downloadHostHandlers(mgr *plugin.Manager, pluginID string) map[str
a.mu.Unlock() a.mu.Unlock()
roots := downloadRoots(mgr, pluginID, dataRoot) roots := downloadRoots(mgr, pluginID, dataRoot)
notify := func(method string, params any) { mgr.NotifySidecar(pluginID, method, params) } notify := func(method string, params any) { mgr.NotifySidecar(pluginID, method, params) }
res, err := a.startPluginDownload(broker, notify, pluginID, roots, raw) return a.startPluginDownload(mgr, broker, notify, pluginID, roots, raw)
if err != nil { }),
broker.Audit(pluginID, "HOST_API_ERROR", "host/download.start") "host/download.cancel": a.hostMethod(mgr, pluginID, "host/download.cancel", func(_ context.Context, raw json.RawMessage) (any, error) {
return nil, err return cancelPluginDownload(mgr, pluginID, raw)
} }),
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
},
} }
} }
@@ -222,17 +212,9 @@ type downloadEvent struct {
// startPluginDownload validates a download request and runs it in the // startPluginDownload validates a download request and runs it in the
// background as a task. It returns the download ID at once. // 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) { func (a *App) startPluginDownload(kernel hostMethodHost, broker *plugin.Broker, notify downloadNotifier, pluginID string, roots []string, raw json.RawMessage) (any, error) {
var req struct { req, err := decodeHostParams[pluginproto.DownloadParams](kernel, pluginID, "host/download.start", raw)
URL string `json:"url"` if err != nil {
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 {
return nil, err return nil, err
} }
if err := broker.AuthorizeNetOrigin(pluginID, req.URL); err != nil { 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) notify("download/progress", ev)
broker.Audit(pluginID, "DOWNLOAD_"+strings.ToUpper(ev.Status), id) 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. // cancelPluginDownload stops one of pluginID's own downloads.
func cancelPluginDownload(pluginID string, raw json.RawMessage) (any, error) { func cancelPluginDownload(kernel hostMethodHost, pluginID string, raw json.RawMessage) (any, error) {
var req struct { req, err := decodeHostParams[pluginproto.DownloadCancelParams](kernel, pluginID, "host/download.cancel", raw)
ID string `json:"id"` if err != nil {
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err return nil, err
} }
pluginDownloads.mu.Lock() 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) return nil, fmt.Errorf("no download %q of this plugin is running", req.ID)
} }
d.cancel() 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/config"
"github.com/Nwflower/reims-go/internal/testutil/fakedriver" "github.com/Nwflower/reims-go/internal/testutil/fakedriver"
"github.com/Nwflower/reims-go/pkg/pluginproto"
) )
type downloadTestEnv struct { 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) { func (e *downloadTestEnv) start(t *testing.T, pluginID string, req map[string]any) (string, error) {
t.Helper() t.Helper()
raw, _ := json.Marshal(req) 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 { if err != nil {
return "", err 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. // 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 { cancelBy := func(plugin string) error {
raw, _ := json.Marshal(map[string]any{"id": id}) raw, _ := json.Marshal(map[string]any{"id": id})
_, err := cancelPluginDownload(plugin, raw) _, err := cancelPluginDownload(nil, plugin, raw)
return err return err
} }
if err := cancelBy(e.other); err == nil { if err := cancelBy(e.other); err == nil {
+14 -18
View File
@@ -12,6 +12,7 @@ import (
"github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n" "github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginproto"
) )
// elevatePromptTimeout is how long a confirmation waits for the person. // elevatePromptTimeout is how long a confirmation waits for the person.
@@ -38,15 +39,9 @@ func (a *App) elevateHostHandlers(mgr *plugin.Manager, pluginID string) map[stri
} }
broker := mgr.Broker() broker := mgr.Broker()
return map[string]plugin.RPCRequestHandler{ return map[string]plugin.RPCRequestHandler{
"host/elevate.request": func(ctx context.Context, raw json.RawMessage) (any, error) { "host/elevate.request": a.hostMethod(mgr, pluginID, "host/elevate.request", func(ctx context.Context, raw json.RawMessage) (any, error) {
res, err := a.requestElevation(ctx, broker, mgr.Registry(), pluginID, raw) return a.requestElevation(ctx, mgr, 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
},
} }
} }
@@ -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 // 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 yes run the action (which raises the Windows UAC prompt). A no,
// a timeout or a missing window ends the request before anything runs. // 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) { func (a *App) requestElevation(ctx context.Context, kernel hostMethodHost, broker *plugin.Broker, reg *plugin.Registry, pluginID string, raw json.RawMessage) (any, error) {
if err := broker.Authorize(pluginID, "driver:vm"); err != nil { req, err := decodeHostParams[pluginproto.ElevateParams](kernel, pluginID, "host/elevate.request", raw)
return nil, err if err != nil {
}
var req struct {
Action string `json:"action"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err return nil, err
} }
spec, ok := host.LookupElevationAction(req.Action) spec, ok := host.LookupElevationAction(req.Action)
@@ -176,7 +166,13 @@ func (a *App) requestElevation(ctx context.Context, broker *plugin.Broker, reg *
return nil, err return nil, err
} }
broker.Audit(pluginID, "ELEVATE_OK", spec.Action) 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 // ResolveElevationRequest delivers the person's answer to a pending plugin
+21 -2
View File
@@ -14,7 +14,9 @@ import (
"github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host" "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/internal/testutil/fakedriver"
"github.com/Nwflower/reims-go/pkg/pluginproto"
) )
type elevateTestEnv struct { type elevateTestEnv struct {
@@ -65,9 +67,26 @@ func newElevateTestEnv(t *testing.T) *elevateTestEnv {
return e 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) { func (e *elevateTestEnv) request(ctx context.Context, pluginID, action string) (any, error) {
raw, _ := json.Marshal(map[string]any{"action": action}) raw, _ := json.Marshal(map[string]any{"action": action})
return e.app.requestElevation(ctx, e.h.Broker, e.h.Registry, pluginID, raw) handler := e.app.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 { func (e *elevateTestEnv) promptCount() int {
@@ -155,7 +174,7 @@ func TestElevationApprovedRunsTheActionOnce(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
got, ok := res.(host.ElevationResult) got, ok := res.(pluginproto.ElevateResult)
if !ok || !got.OK || !got.RebootRequired { if !ok || !got.OK || !got.RebootRequired {
t.Fatalf("result = %#v", res) 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/guesttools"
"github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n" "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/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep" "github.com/Nwflower/reims-go/internal/macos/startprep"
"github.com/Nwflower/reims-go/internal/networkmsg" "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") 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. // buildGuestToolsImage runs in the macOS driver after all start hooks pass.
func (a *App) buildGuestToolsImage(vmName, vmDir string) error { func (a *App) buildGuestToolsImage(vmName, vmDir string) error {
_, port, _, err := a.startGuestToolsServer() _, port, _, err := a.startGuestToolsServer()
@@ -132,7 +150,7 @@ func (a *App) buildGuestToolsImage(vmName, vmDir string) error {
return err return err
} }
cfg, _ = a.validatedShareConfig(cfg) 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 // 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 a.guestTools = srv
srv.SetHostDNSConfig(a.hostDNSConfigLocked()) srv.SetHostDNSConfig(a.hostDNSConfigLocked())
srv.SetStatusChangeHandler(func(string) { a.syncKeymapRules() })
created = true created = true
} }
a.syncClipboardStagingLocked() a.syncClipboardStagingLocked()
@@ -214,51 +231,6 @@ func (a *App) guestToolsEnabled() bool {
return err == nil 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) { func (a *App) registerExistingGuestTools(ctx context.Context) {
srv, port, err := a.ensureGuestToolsBridge() srv, port, err := a.ensureGuestToolsBridge()
if err != nil { 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 // guest agent that is already running reconnects after reims-go restarts or
// the Guest Tools plugin is switched back on. // the Guest Tools plugin is switched back on.
func (a *App) registerVMsWithBridge(ctx context.Context, srv *guesttools.Server, port int) { func (a *App) registerVMsWithBridge(ctx context.Context, srv *guesttools.Server, port int) {
defer a.syncKeymapRules()
c, err := a.client() c, err := a.client()
if err != nil { if err != nil {
return 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 // AttachGuestTools prepares the per-VM Bearer token, ensures the shared folder
// and localhost bridge are active, builds the read-only REIMSTOOLS HFS+ disk, // and localhost bridge are active, builds the read-only REIMSTOOLS HFS+ disk,
// and attaches it to the VM via `reims-ctl set --extra-args`. // 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) 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) return fmt.Errorf("build REIMSTOOLS disk: %w", err)
} }
merged := reims.MergeGuestToolsArgs(d.ExtraArgs, imgPath) 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 (a *App) 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 (a *App) hostVMMethod(mgr *plugin.Manager, pluginID, method string, run computerUseVMHandler) plugin.RPCRequestHandler {
return a.hostMethod(mgr, pluginID, method, func(ctx context.Context, raw json.RawMessage) (any, error) {
return run(ctx, raw, mgr, pluginID)
})
}
+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.hostHandlers(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)
}
}
-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 package app
import ( import (
"encoding/json"
"strings" "strings"
"testing" "testing"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/macos/guest" "github.com/Nwflower/reims-go/internal/macos/guest"
"github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/internal/plugin"
@@ -11,6 +13,23 @@ import (
"github.com/Nwflower/reims-go/internal/qmp" "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) { func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) {
// Simulate an existing pre-plugin VM whose vm.toml already contains: // Simulate an existing pre-plugin VM whose vm.toml already contains:
// user arg + REIMSTOOLS + REIMSHELP + Win10 managed QMP args, with NO ledger file yet. // 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) base := stripLegacyManagedExtraArgs(legacy)
res := plugin.ReconcileStartIntents(base, ledger, active, intents) res := plugin.ReconcileStartIntentsForDriver(base, ledger, active, "", intents)
if !strings.Contains(res.ExtraArgs, "-cpu host") { if !strings.Contains(res.ExtraArgs, "-cpu host") {
t.Fatalf("user arg lost: %s", res.ExtraArgs) 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"}}, {PluginID: guest.ID, ClearKeys: []string{"reimshelp", "win10-cold-reboot"}},
} }
base2 := stripLegacyManagedExtraArgs(res.ExtraArgs) base2 := stripLegacyManagedExtraArgs(res.ExtraArgs)
res2 := plugin.ReconcileStartIntents(base2, ledger, active, nextIntents) res2 := plugin.ReconcileStartIntentsForDriver(base2, ledger, active, "", nextIntents)
if res2.ExtraArgs != "-cpu host" { if res2.ExtraArgs != "-cpu host" {
t.Fatalf("expected only user arg after clearing managed keys, got: %q", res2.ExtraArgs) 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") { if strings.Contains(unmigrated.ExtraArgs, "kernel-irqchip") {
t.Fatalf("test premise: an unmigrated ledger should drop the fragment, got %q", unmigrated.ExtraArgs) 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) { if !guest.MigrateLedger(ledger) {
t.Fatal("MigrateLedger reported no change for a retired owner") 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 { 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) 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 { if err != nil {
return driver.VMInfo{}, err 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) { 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 svc := a.lifecycleSvc
a.mu.Unlock() a.mu.Unlock()
if svc == nil { if svc == nil {
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID { return errors.New("driver lifecycle is not initialized")
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)
})
} }
_, vm, err := svc.Resolve(context.Background(), driverID, name) _, vm, err := svc.Resolve(context.Background(), driverID, name)
if err != nil { 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) Start(context.Context, driver.VMRef, io.Writer, io.Writer) (driver.StartResult, error)
}, vm driver.VMInfo) error { }, vm driver.VMInfo) error {
if svc == nil { if svc == nil {
return a.startMacOSVM(vm.Name) return errors.New("driver lifecycle is not initialized")
} }
ref := vm.Ref() ref := vm.Ref()
key := ref.Key() key := ref.Key()
@@ -179,10 +175,7 @@ func (a *App) stopVM(ctx context.Context, driverID, name string, force bool) err
svc := a.lifecycleSvc svc := a.lifecycleSvc
a.mu.Unlock() a.mu.Unlock()
if svc == nil { if svc == nil {
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID { return errors.New("driver lifecycle is not initialized")
return errors.New("driver is unavailable without the plugin manager")
}
return a.stopMacOSVM(ctx, name, force)
} }
_, vm, err := svc.Resolve(ctx, driverID, name) _, vm, err := svc.Resolve(ctx, driverID, name)
if err != nil { if err != nil {
@@ -222,10 +215,7 @@ func (a *App) EjectInstaller(driverID, name string) error {
svc := a.lifecycleSvc svc := a.lifecycleSvc
a.mu.Unlock() a.mu.Unlock()
if svc == nil { if svc == nil {
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID { return errors.New("driver lifecycle is not initialized")
return errors.New("driver is unavailable without the plugin manager")
}
return a.ejectMacOSInstaller(name)
} }
vm, err := a.resolveVMInfo(driverID, name) vm, err := a.resolveVMInfo(driverID, name)
if err != nil { if err != nil {
@@ -247,7 +237,14 @@ func (a *App) ReadVMLogs(driverID, name string, serial bool) (string, error) {
svc := a.lifecycleSvc svc := a.lifecycleSvc
a.mu.Unlock() a.mu.Unlock()
if svc == nil { 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) 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() a.mu.Lock()
svc := a.lifecycleSvc svc := a.lifecycleSvc
a.mu.Unlock() a.mu.Unlock()
var ref driver.VMRef if svc == nil {
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()
} 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)
} }
_, vm, err := svc.Resolve(context.Background(), driverID, name)
if err != nil {
return err
}
ref := vm.Ref()
if ref.DriverID != driver.BuiltinReimsMacOSDriverID { 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 { return a.withComputerUseVM(a.baseCtx(), vm.Directory, func(ctx context.Context) error {
if err := a.stopVM(ctx, ref.DriverID, ref.Name, false); err != nil { if err := a.stopVM(ctx, ref.DriverID, ref.Name, false); err != nil {
return err return err
@@ -289,7 +274,7 @@ func (a *App) RestartVM(driverID, name string) error {
return a.startResolvedVMLocked(ctx, svc, vm) return a.startResolvedVMLocked(ctx, svc, vm)
}) })
} }
_, err := a.restartMacOSVM(a.baseCtx(), ref.Name) _, err = a.restartMacOSVM(a.baseCtx(), ref.Name)
return err return err
} }
@@ -298,10 +283,7 @@ func (a *App) DeleteVM(driverID, name string, keepFiles bool) error {
svc := a.lifecycleSvc svc := a.lifecycleSvc
a.mu.Unlock() a.mu.Unlock()
if svc == nil { if svc == nil {
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID { return errors.New("driver lifecycle is not initialized")
return errors.New("driver is unavailable without the plugin manager")
}
return a.deleteMacOSVM(name, keepFiles)
} }
d, vm, err := svc.ResolveForDelete(context.Background(), driverID, name) d, vm, err := svc.ResolveForDelete(context.Background(), driverID, name)
if err != nil { if err != nil {
-100
View File
@@ -1,12 +1,9 @@
package app package app
import ( import (
"bufio"
"context" "context"
"errors" "errors"
"fmt"
"io" "io"
"net"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -15,12 +12,10 @@ import (
"github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle" vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/macos/macosdriver" "github.com/Nwflower/reims-go/internal/macos/macosdriver"
"github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/qmp"
rt "github.com/Nwflower/reims-go/internal/runtime" rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/tray" "github.com/Nwflower/reims-go/internal/tray"
"github.com/Nwflower/reims-go/internal/vmstart" "github.com/Nwflower/reims-go/internal/vmstart"
@@ -67,101 +62,6 @@ func TestMacOSLaunchUsesLatestRuntimeSelection(t *testing.T) {
} }
} }
func TestPrepareLegacyColdStart(t *testing.T) {
log := func(line string) { t.Log(line) }
t.Run("recoverable snapshot", func(t *testing.T) {
dir := t.TempDir()
state := reims.SuspendStatePath(dir) + ".tmp"
meta := reims.SuspendMetaPath(dir) + ".tmp"
for _, path := range []string{state, meta} {
if err := os.WriteFile(path, []byte("snapshot data"), 0o600); err != nil {
t.Fatal(err)
}
}
err := prepareLegacyColdStart(t.Context(), i18n.EnUS, "mac", "", reims.VMDetail{Directory: dir, State: "stopped"}, log)
var coded *i18n.CodedError
if !errors.As(err, &coded) || coded.Code != "E_VM_SUSPENDED" || coded.Key != "err.suspend.action_blocked" {
t.Fatalf("legacy cold start = %v, want E_VM_SUSPENDED", err)
}
if !reims.HasSuspendState(dir) {
t.Fatal("recoverable snapshot was removed")
}
})
t.Run("inspection error", func(t *testing.T) {
dir := t.TempDir()
staged := reims.SuspendStatePath(dir) + ".tmp"
if err := os.WriteFile(staged, []byte("snapshot data"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(reims.SuspendMetaPath(dir)+".tmp", 0o700); err != nil {
t.Fatal(err)
}
err := prepareLegacyColdStart(t.Context(), i18n.EnUS, "mac", "", reims.VMDetail{Directory: dir, State: "stopped"}, log)
if !errors.Is(err, reims.ErrSuspendArtifactsUncertain) {
t.Fatalf("legacy cold start = %v, want inspection error", err)
}
if data, err := os.ReadFile(staged); err != nil || string(data) != "snapshot data" {
t.Fatalf("staged state = %q, %v", data, err)
}
})
for _, tt := range []struct {
name, dir string
}{
{"postmigrate", "."},
{"postmigrate on short socket for long VM directory", strings.Repeat("v", 100)},
} {
t.Run(tt.name, func(t *testing.T) {
t.Chdir(t.TempDir())
const name, tmpDir = "mac", "tmp"
if err := os.MkdirAll(tt.dir, 0o700); err != nil {
t.Fatal(err)
}
staged := reims.SuspendStatePath(tt.dir) + ".tmp"
if err := os.WriteFile(staged, []byte("snapshot data"), 0o600); err != nil {
t.Fatal(err)
}
socket := qmp.SocketPathForVM(tt.dir, name, tmpDir)
if err := os.MkdirAll(filepath.Dir(socket), 0o700); err != nil {
t.Fatal(err)
}
ln, err := net.Listen("unix", socket)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = ln.Close() })
if tt.dir != "." {
if _, err := os.Lstat(qmp.SocketPath(tt.dir)); !os.IsNotExist(err) {
t.Fatalf("unexpected VM directory socket: %v", err)
}
}
go func() {
conn, err := ln.Accept()
if err != nil {
return
}
defer conn.Close()
_, _ = fmt.Fprintln(conn, `{"QMP":{}}`)
sc := bufio.NewScanner(conn)
if sc.Scan() {
_, _ = fmt.Fprintln(conn, `{"return":{}}`)
}
if sc.Scan() {
_, _ = fmt.Fprintln(conn, `{"return":{"running":false,"status":"postmigrate"}}`)
}
}()
err = prepareLegacyColdStart(t.Context(), i18n.EnUS, name, tmpDir, reims.VMDetail{Directory: tt.dir, State: "stopped"}, log)
if err == nil || !strings.Contains(err.Error(), "QEMU is still active (QMP status: postmigrate)") {
t.Fatalf("legacy cold start = %v, want active QEMU error", err)
}
if data, err := os.ReadFile(staged); err != nil || string(data) != "snapshot data" {
t.Fatalf("staged state = %q, %v", data, err)
}
})
}
}
type appSecondDriver struct { type appSecondDriver struct {
id string id string
vms []driver.VMInfo vms []driver.VMInfo
+2 -7
View File
@@ -23,13 +23,6 @@ func macOSDetailFromVMInfo(vm driver.VMInfo) (reims.VMDetail, error) {
return detail, nil return detail, nil
} }
func vmInfoFromMacOSDetail(detail reims.VMDetail) driver.VMInfo {
raw, _ := json.Marshal(detail)
var data map[string]any
_ = json.Unmarshal(raw, &data)
return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: detail.DiskPath(), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort, DriverData: data}
}
func (a *App) loadMacOSVMDetail(name string, epoch uint64) (reims.VMDetail, error) { func (a *App) loadMacOSVMDetail(name string, epoch uint64) (reims.VMDetail, error) {
c, err := a.client() c, err := a.client()
if err != nil { if err != nil {
@@ -44,6 +37,7 @@ func (a *App) loadMacOSVMDetail(name string, epoch uint64) (reims.VMDetail, erro
a.populateGuestLangDetail(&d) a.populateGuestLangDetail(&d)
populateSuspendDetail(&d) populateSuspendDetail(&d)
populateNestedVirtDetail(&d) populateNestedVirtDetail(&d)
d.AutoResolution = vmstart.SupportsAutoResolution(d.Graphics) && vmstart.ReadVMDisplay(d.Directory).AutoResolution
return d, nil return d, nil
} }
@@ -78,6 +72,7 @@ func (a *App) getVMDetail(name string, epoch uint64) (reims.VMDetail, error) {
a.populateGuestLangDetail(&d) a.populateGuestLangDetail(&d)
populateSuspendDetail(&d) populateSuspendDetail(&d)
populateNestedVirtDetail(&d) populateNestedVirtDetail(&d)
d.AutoResolution = vmstart.SupportsAutoResolution(d.Graphics) && vmstart.ReadVMDisplay(d.Directory).AutoResolution
return d, nil return d, nil
} }
+1 -465
View File
@@ -4,23 +4,11 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
"time" "time"
"github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/guest"
"github.com/Nwflower/reims-go/internal/macos/macosdriver"
"github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep"
"github.com/Nwflower/reims-go/internal/networkmsg"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"github.com/Nwflower/reims-go/internal/qmp" "github.com/Nwflower/reims-go/internal/qmp"
"github.com/Nwflower/reims-go/internal/vmstart" "github.com/Nwflower/reims-go/internal/vmstart"
) )
@@ -178,353 +166,6 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) {
}() }()
} }
// stripLegacyManagedExtraArgs removes reims-go internally managed QEMU arg
// fragments (reimstools, reimshelp, and legacy managed Win10 QMP targets)
// before ledger reconciliation so pre-plugin VMs and out-of-band helpers never
// produce duplicate QEMU device IDs on upgrade.
func stripLegacyManagedExtraArgs(extraArgs string) string {
s := reims.StripGuestToolsArgs(extraArgs)
s = reims.StripPacketBridgeArgs(s)
s = reims.StripGuestToolsNetworkArgs(s)
s = reims.StripOfflineHelperArgs(s)
s = qmp.StripLegacyWin10RebootArgs(s)
s = reims.StripIncomingDeferArgs(s)
return strings.TrimSpace(s)
}
func (a *App) startMacOSVM(name string) error {
if err := a.requireWritableDataRoot(); err != nil {
return err
}
prep, err := a.prep(name)
if err != nil {
return err
}
c := prep.Client
a.mu.Lock()
root := a.cfg.DataRoot
tmpDir := a.cfg.TempDir()
locale := a.cfg.Locale
a.mu.Unlock()
rep := host.Inspect(root)
if err := prep.CheckWHPX(rep); err != nil {
a.emitVMLog(name, "Start refused: "+err.Error())
return err
}
curDetail, release, err := startprep.LockVM(context.Background(), c, name)
if err != nil {
return err
}
unlock := sync.OnceFunc(release)
defer unlock()
if err := prepareLegacyColdStart(context.Background(), c.Locale, name, tmpDir, curDetail, func(line string) {
a.emitVMLog(name, line)
}); err != nil {
return err
}
releaseNet, err := a.prepareManagedVMNetwork(context.Background(), name, false)
if err != nil {
return err
}
if releaseNet != nil {
defer releaseNet()
}
if err := prep.CheckMemory(curDetail.Memory, rep); err != nil {
a.emitVMLog(name, "Start refused: "+err.Error())
return err
}
a.cancelRebootWatcher(name)
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
var qmpAddr string
if mgr != nil {
// Unified plugin-kernel start pipeline (§4.4): collect all vm.beforeStart
// intents (builtin + L1 rule hooks + L3 code hooks) and write merged
// extra-args via AT MOST ONE `reims-ctl set --extra-args` call.
rtCaps := prep.Runtime.Manifest.EffectiveCapabilities()
intents, blockErr := mgr.Registry().Hooks().DispatchBeforeStart(context.Background(), plugin.BeforeStartPayload{
VMName: name,
VMSettingsKey: driver.NewVMRef(builtin.IDDriverReimsMacOS, name).Key(),
VMDir: curDetail.Directory,
DriverID: builtin.IDDriverReimsMacOS,
ExtraArgs: curDetail.ExtraArgs,
HasInstaller: curDetail.HasInstaller,
InstallerPath: curDetail.InstallerPath,
RuntimeKind: prep.Runtime.Manifest.EffectiveKind(),
RuntimeCaps: rtCaps,
HostFacts: buildHostFacts(rep, rtCaps),
VMCaps: macosdriver.ReimsMacOSCapabilities,
State: curDetail.State,
})
if blockErr != nil {
a.emitVMLog(name, "Start blocked: "+blockErr.Error())
return blockErr
}
ledger, ledgerErr := plugin.LoadArgLedger(curDetail.Directory)
if ledgerErr != nil {
a.emitVMLog(name, "Warning: could not read arg ledger: "+ledgerErr.Error())
ledger = &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{}}
}
// Reassign macOS-owned fragments from legacy builtin.core records to
// builtin.guest.macos before reconciling.
guest.MigrateLedger(ledger)
// Strip pre-ledger or out-of-band managed fragments so upgrading existing
// VMs never duplicates QEMU device IDs.
baseExtraArgs := stripLegacyManagedExtraArgs(curDetail.ExtraArgs)
nested := plugin.StartIntent{PluginID: builtin.IDDriverReimsMacOS}
macosdriver.AppendNestedVirtIntent(&nested, locale, curDetail.Directory, plugin.UserExtraArgs(baseExtraArgs, ledger), rep)
reconciled := plugin.ReconcileStartIntentsForDriver(baseExtraArgs, ledger, mgr.Registry().ActivePluginIDs(), nested.PluginID, append(intents, nested))
reconciled.Changed = strings.TrimSpace(curDetail.ExtraArgs) != reconciled.ExtraArgs
for _, warn := range reconciled.Warnings {
a.emitVMLog(name, "[plugin] "+warn)
}
if len(reconciled.Env) > 0 {
c.Env = append(c.Env, reconciled.Env...)
}
if reconciled.Changed {
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &reconciled.ExtraArgs}, io.Discard, io.Discard); err != nil {
a.emitVMLog(name, "Warning: could not apply reconciled start extra-args: "+err.Error())
} else {
curDetail.ExtraArgs = reconciled.ExtraArgs
_ = plugin.SaveArgLedger(curDetail.Directory, ledger)
}
} else {
_ = plugin.SaveArgLedger(curDetail.Directory, ledger)
}
for _, act := range reconciled.PostStart {
if act.Kind == "qmp.watch_cold_reboot" {
if addr, ok := act.Params["qmp_addr"].(string); ok && addr != "" {
qmpAddr = addr
}
}
}
} else {
if err := a.reconcileLegacyBridgeArgs(context.Background(), c, &curDetail); err != nil {
return err
}
a.syncGuestTools(c, name, &curDetail, a.vmDeleteEpoch(name))
if prep.Runtime.Manifest.HasCapability("win32-unicode-input") {
if env := a.inputBridgeEnv(name, curDetail.Directory, a.vmDeleteEpoch(name)); len(env) > 0 {
c.Env = append(c.Env, env...)
}
}
if prep.Runtime.Manifest.HasCapability("window-file-drop") {
c.Env = append(c.Env, a.dropBridgeEnv(name, curDetail.Directory, a.vmDeleteEpoch(name))...)
}
prep.Prepare(context.Background(), name, rep, &curDetail)
if rep.NeedsColdRebootWorkaround {
sockPath := qmp.RebootSocketPath(curDetail.Directory, tmpDir, name)
_ = os.MkdirAll(filepath.Dir(sockPath), 0o755)
_ = os.Remove(sockPath)
merged := qmp.MergeWin10RebootUnixArgs(curDetail.ExtraArgs, sockPath)
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err != nil {
a.emitVMLog(name, "Win10 cold-reboot extra-args setup skipped: "+err.Error())
} else {
qmpAddr = "unix:" + sockPath
curDetail.ExtraArgs = merged
}
}
ledger, err := plugin.LoadArgLedger(curDetail.Directory)
if err != nil {
return err
}
nested := plugin.StartIntent{PluginID: builtin.IDDriverReimsMacOS}
macosdriver.AppendNestedVirtIntent(&nested, locale, curDetail.Directory, plugin.UserExtraArgs(curDetail.ExtraArgs, ledger), rep)
reconciled := plugin.ReconcileStartIntentsForDriver(curDetail.ExtraArgs, ledger, nil, nested.PluginID, []plugin.StartIntent{nested})
for _, warning := range reconciled.Warnings {
a.emitVMLog(name, warning)
}
if reconciled.Changed {
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &reconciled.ExtraArgs}, io.Discard, io.Discard); err != nil {
return err
}
if err := plugin.SaveArgLedger(curDetail.Directory, ledger); err != nil {
return err
}
curDetail.ExtraArgs = reconciled.ExtraArgs
}
}
if prep.Runtime.Manifest.HasCapability("display-fixed-mode") &&
vmstart.UsesFixedGuestMode(curDetail.Directory, rep.Displays, curDetail.Borderless, curDetail.Resolution) {
c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
}
if prep.Runtime.Manifest.HasCapability("client-window-close") {
c.Env = append(c.Env, vmstart.CloseRequestEnv(name)...)
}
a.mu.Lock()
a.transitions[vmKey(name)] = "starting"
delete(a.pendingChanges, vmKey(name))
a.mu.Unlock()
a.emitStateChanged()
startAt := time.Now()
a.emitStartSummary(name, vmInfoFromMacOSDetail(curDetail), rep, qmpAddr)
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
a.emitVMLog(name, "Starting "+name+"...")
err = c.StartWithCompat(context.Background(), name, w, w, func(msg string) {
a.emitVMLog(name, msg)
})
unlock()
if err != nil {
a.mu.Lock()
delete(a.transitions, vmKey(name))
a.mu.Unlock()
a.emitVMLog(name, "Start error: "+err.Error())
a.emitStateChanged()
return err
}
if qmpAddr != "" && mgr == nil {
a.watchWin10ColdReboot(name, qmpAddr)
}
if mgr != nil {
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStart, plugin.VMEventPayload{
VMName: name,
VMDir: curDetail.Directory,
DriverID: builtin.IDDriverReimsMacOS,
QMPAddr: qmpAddr,
})
}
a.startVMMonitor(name, vmInfoFromMacOSDetail(curDetail), startAt)
a.wakePoll()
a.emitStateChanged()
return nil
}
// 备用启动同样记录参数归属,停用扩展时可精确移除桥接片段。
func (a *App) reconcileLegacyBridgeArgs(ctx context.Context, c networkControlClient, detail *reims.VMDetail) error {
ledger, err := plugin.LoadArgLedger(detail.Directory)
if err != nil {
return err
}
intent := plugin.StartIntent{PluginID: builtin.IDNpcapBridge, ClearKeys: []string{"bridge-network", "npcap-bridge"}}
if detail.NetworkMode == "bridge" {
record, err := reims.ReadNetworkRecord(detail.Directory)
if err != nil {
return err
}
if record.Corrupt {
return networkmsg.Error("record_invalid", nil)
}
if record.Pending {
return networkmsg.Error("packet_pending", nil)
}
mac, err := resolveVMNetworkMAC(ctx, c, *detail)
if err != nil {
return err
}
sockPath := record.SocketPath
if sockPath == "" {
sockPath = reims.VMUnixSocketPath(detail.Directory, a.tempDir(), detail.Name, "bridge.sock")
}
tokens, err := reims.PacketBridgeUnixTokens(mac, sockPath)
if err != nil {
return err
}
intent.Args = []plugin.ArgFragment{{PluginID: builtin.IDNpcapBridge, Key: "bridge-network", Tokens: tokens, Builtin: true, Priority: 78}}
}
// 先剥除旧版未登记的主通道;管理网卡和用户参数保持各自归属。
extra := reims.StripPacketBridgeArgs(detail.ExtraArgs)
result := plugin.ReconcileStartIntents(extra, ledger, nil, []plugin.StartIntent{intent})
for _, warning := range result.Warnings {
a.emitVMLog(detail.Name, warning)
}
if result.ExtraArgs != detail.ExtraArgs {
if err := c.Set(ctx, reims.SetOpts{Name: detail.Name, ExtraArgs: &result.ExtraArgs}, io.Discard, io.Discard); err != nil {
return networkmsg.Error("config_save", err)
}
}
if err := plugin.SaveArgLedger(detail.Directory, ledger); err != nil {
return err
}
detail.ExtraArgs = result.ExtraArgs
return nil
}
// prepareLegacyColdStart guards the older start path against a stopped VM that
// still holds suspend artifacts. It drops provably orphaned files, then refuses
// the start while a recoverable snapshot remains: this path cannot resume one,
// and cold-starting over it would discard the guest's saved state. Resume or
// discard the snapshot from the UI first.
func prepareLegacyColdStart(ctx context.Context, locale i18n.Locale, name, tmpDir string, cur reims.VMDetail, log func(string)) error {
if cur.State != "stopped" {
return nil
}
suspended, err := reims.InspectSuspendState(cur.Directory)
if err != nil {
return err
}
if !suspended {
err := startprep.CleanStaleSuspendBeforeStart(ctx, cur.Directory, name, tmpDir, log, log)
if !errors.Is(err, reims.ErrSuspendStatePresent) {
return err
}
}
return i18n.NewCodedError(locale, "E_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil)
}
func (a *App) stopMacOSVM(ctx context.Context, name string, force bool) error {
c, err := a.client()
if err != nil {
return err
}
detail, err := c.Show(ctx, name)
if err != nil {
return err
}
return a.withComputerUseVM(ctx, detail.Directory, func(operationCtx context.Context) error {
return a.stopMacOSVMLocked(operationCtx, name, force, c)
})
}
func (a *App) stopMacOSVMLocked(ctx context.Context, name string, force bool, c *reims.Client) error {
a.cancelRebootWatcher(name)
stopVMMonitor(name)
a.mu.Lock()
mgr := a.pluginMgr
a.transitions[vmKey(name)] = "stopping"
a.mu.Unlock()
if mgr != nil {
mgr.Registry().Hooks().DispatchBeforeStop(ctx, plugin.VMEventPayload{
VMName: name,
DriverID: builtin.IDDriverReimsMacOS,
})
}
a.emitStateChanged()
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
a.emitVMLog(name, fmt.Sprintf("Stopping %s (force=%v)...", name, force))
var err error
if force {
err = c.StopForce(ctx, name, w, w)
} else {
err = c.Stop(ctx, name, w, w)
}
if err != nil {
a.mu.Lock()
delete(a.transitions, vmKey(name))
a.mu.Unlock()
a.emitVMLog(name, "Stop error: "+err.Error())
return err
}
a.stopPacketBridge(name)
a.mu.Lock()
delete(a.pendingChanges, vmKey(name))
a.mu.Unlock()
if mgr != nil {
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStop, plugin.VMEventPayload{
VMName: name,
DriverID: builtin.IDDriverReimsMacOS,
})
}
a.wakePoll()
a.emitStateChanged()
return nil
}
// restartMacOSVM restarts a built-in macOS VM, waiting for the old QEMU // restartMacOSVM restarts a built-in macOS VM, waiting for the old QEMU
// process and its committed memory to go away before starting again. // process and its committed memory to go away before starting again.
func (a *App) restartMacOSVM(ctx context.Context, name string) (stopped bool, err error) { func (a *App) restartMacOSVM(ctx context.Context, name string) (stopped bool, err error) {
@@ -555,11 +196,7 @@ func (a *App) restartMacOSVMLocked(ctx context.Context, name string) (stopped bo
svc := a.lifecycleSvc svc := a.lifecycleSvc
a.mu.Unlock() a.mu.Unlock()
if svc == nil { if svc == nil {
vm, resolveErr := a.resolveVMInfo(driver.BuiltinReimsMacOSDriverID, name) return true, errors.New("driver lifecycle is not initialized")
if resolveErr != nil {
return true, resolveErr
}
return true, a.startResolvedVMLocked(ctx, nil, vm)
} }
_, vm, err := svc.Resolve(ctx, driver.BuiltinReimsMacOSDriverID, name) _, vm, err := svc.Resolve(ctx, driver.BuiltinReimsMacOSDriverID, name)
if err != nil { if err != nil {
@@ -568,99 +205,6 @@ func (a *App) restartMacOSVMLocked(ctx context.Context, name string) (stopped bo
return true, a.startResolvedVMLocked(ctx, svc, vm) return true, a.startResolvedVMLocked(ctx, svc, vm)
} }
func (a *App) ejectMacOSInstaller(name string) error {
c, err := a.client()
if err != nil {
return err
}
detail, err := c.Show(context.Background(), name)
if err != nil {
return err
}
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
a.emitVMLog(name, "Ejecting installer from "+name+"...")
if err := a.withComputerUseVM(context.Background(), detail.Directory, func(ctx context.Context) error {
return c.Eject(ctx, name, w, w)
}); err != nil {
a.emitVMLog(name, "Eject error: "+err.Error())
return err
}
a.emitVMLog(name, "Installer ejected.")
a.emitStateChanged()
return nil
}
func (a *App) deleteMacOSVM(name string, keepFiles bool) error {
c, err := a.client()
if err != nil {
return err
}
detail, err := c.Show(context.Background(), name)
if err != nil {
return err
}
removed := false
err = a.withComputerUseVM(context.Background(), detail.Directory, func(ctx context.Context) error {
return a.deleteMacOSVMLocked(ctx, detail, keepFiles, c, &removed)
})
if removed {
releaseVMTyping(name)
releaseVMThumbnail(name)
}
return err
}
func (a *App) deleteMacOSVMLocked(ctx context.Context, detail reims.VMDetail, keepFiles bool, c *reims.Client, removed *bool) error {
name := detail.Name
if detail.State != "running" {
a.cancelRebootWatcher(name)
stopVMMonitor(name)
a.stopPacketBridge(name)
}
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
a.emitVMLog(name, fmt.Sprintf("Deleting VM %s (keepFiles=%v)...", name, keepFiles))
deleted, deleteErr := a.deleteVMWithGuestTools(name, func() error {
return c.Delete(ctx, name, keepFiles, w, w)
}, func() (bool, error) {
vms, err := c.List(ctx)
if err != nil {
return false, err
}
for _, vm := range vms {
if strings.EqualFold(vm.Name, name) {
return true, nil
}
}
return false, nil
})
if deleteErr != nil {
a.emitVMLog(name, "Delete error: "+deleteErr.Error())
}
if !deleted {
return deleteErr
}
*removed = true
a.cancelRebootWatcher(name)
stopVMMonitor(name)
a.stopPacketBridge(name)
a.mu.Lock()
delete(a.pendingChanges, vmKey(name))
delete(a.transitions, vmKey(name))
delete(a.diskPaths, vmKey(name))
delete(a.procSamples, vmKey(name))
delMgr := a.pluginMgr
a.mu.Unlock()
if delMgr != nil {
delMgr.Registry().Hooks().DispatchObserve(plugin.EventVMDeleted, plugin.VMEventPayload{
VMName: name,
DriverID: builtin.IDDriverReimsMacOS,
})
}
a.wakePoll()
a.emitStateChanged()
return deleteErr
}
// OpenVMFolder shows the VM's directory in File Explorer. // OpenVMFolder shows the VM's directory in File Explorer.
func (a *App) OpenVMFolder(name string) error { func (a *App) OpenVMFolder(name string) error {
d, err := a.GetVMDetail(name) d, err := a.GetVMDetail(name)
@@ -672,11 +216,3 @@ func (a *App) OpenVMFolder(name string) error {
} }
return host.OpenFolder(d.Directory) return host.OpenFolder(d.Directory)
} }
func (a *App) readMacOSVMLogs(name string, serial bool) (string, error) {
c, err := a.client()
if err != nil {
return "", err
}
return c.ReadLogs(context.Background(), name, serial)
}
+89 -110
View File
@@ -6,13 +6,17 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"log"
"path/filepath" "path/filepath"
"slices"
"strconv"
"strings" "strings"
"time" "time"
"github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n" "github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/macosdriver"
"github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep" "github.com/Nwflower/reims-go/internal/macos/startprep"
"github.com/Nwflower/reims-go/internal/networkmsg" "github.com/Nwflower/reims-go/internal/networkmsg"
@@ -79,7 +83,7 @@ func (a *App) CreateVM(opts reims.CreateOpts) error {
if err := a.requireWritableDataRoot(); err != nil { if err := a.requireWritableDataRoot(); err != nil {
return err return err
} }
return a.createVMFlow(opts) return a.createVMFlow(opts, host.ConnectedDisplays)
} }
func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) { func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) {
@@ -132,126 +136,99 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) {
if issues := reims.ValidateSet(opts, cur, host.Inspect(root), loc); len(issues) > 0 { if issues := reims.ValidateSet(opts, cur, host.Inspect(root), loc); len(issues) > 0 {
return fmt.Errorf("%s", issues[0].Message) return fmt.Errorf("%s", issues[0].Message)
} }
var outcome macosdriver.SettingsOutcome
ctx := macosdriver.WithSettingsOutcome(context.Background(), &outcome)
w := vmstart.LineWriter(func(line string) { a.emitVMLog(opts.Name, line) }) w := vmstart.LineWriter(func(line string) { a.emitVMLog(opts.Name, line) })
a.mu.Lock() a.mu.Lock()
svc := a.lifecycleSvc svc := a.lifecycleSvc
a.mu.Unlock() a.mu.Unlock()
guestLangChanged := strings.TrimSpace(opts.GuestLang) != "" && strings.TrimSpace(opts.GuestLang) != cur.GuestLang if svc == nil {
if svc != nil { return errors.New("driver lifecycle is not initialized")
raw, _ := json.Marshal(opts)
var changes map[string]any
_ = json.Unmarshal(raw, &changes)
if err := svc.Set(context.Background(), driver.NewVMRef("", opts.Name), changes, w, w); err != nil {
a.emitVMLog(opts.Name, "Set error: "+err.Error())
return err
}
} else {
if strings.TrimSpace(opts.DiskCache) != "" {
cfg := a.runtimeConfig()
active, err := rt.ResolveActive(&cfg)
if err != nil {
return fmt.Errorf("%s", i18n.T(cfg.Locale, "err.runtime_not_installed"))
}
if !active.Manifest.HasCapability("win32-native-aio") {
return errors.New(i18n.T(i18n.EffectiveLocale(loc), "validate.disk_cache_requires_runtime"))
}
}
c, err := a.client()
if err != nil {
return err
}
locked, release, err := startprep.LockMutableVM(a.baseCtx(), c, opts.Name)
if err != nil {
return err
}
defer release()
if reims.HasCtlSetChanges(opts) {
if err := c.Set(context.Background(), opts, w, w); err != nil {
a.emitVMLog(opts.Name, "Set error: "+err.Error())
return err
}
}
if opts.NestedVirt != nil {
if err := vmstart.SaveVMNestedVirt(locked.Directory, vmstart.VMNestedVirtConfig{Enabled: *opts.NestedVirt}); err != nil {
return err
}
}
if guestLangChanged {
prep, err := a.prep(opts.Name)
if err == nil {
err = prep.ApplyGuestLang(context.Background(), cur.Directory, opts.GuestLang, cur.State == "running")
}
if err != nil {
a.emitVMLog(opts.Name, "Guest language error: "+err.Error())
return err
}
} else if cur.State != "running" && opts.Graphics != "" && opts.Graphics != cur.Graphics {
if prep, err := a.prep(opts.Name); err == nil {
prep.ReplayGuestLang(context.Background(), cur.Directory)
}
}
} }
if cur.State == "running" { raw, merr := json.Marshal(opts)
var diffs []PendingChange if merr != nil {
if opts.CPUs > 0 && opts.CPUs != cur.CPUs { return fmt.Errorf("encode VM settings: %w", merr)
diffs = append(diffs, PendingChange{Field: "cpus", From: fmt.Sprintf("%d", cur.CPUs), To: fmt.Sprintf("%d", opts.CPUs)}) }
} var changes map[string]any
if opts.Memory != "" && !strings.EqualFold(opts.Memory, cur.Memory) { if uerr := json.Unmarshal(raw, &changes); uerr != nil {
diffs = append(diffs, PendingChange{Field: "memory", From: cur.Memory, To: opts.Memory}) return fmt.Errorf("decode VM settings: %w", uerr)
} }
if opts.Resolution != "" && opts.Resolution != cur.Resolution { if err := svc.Set(ctx, driver.NewVMRef(driver.BuiltinReimsMacOSDriverID, opts.Name), changes, w, w); err != nil {
diffs = append(diffs, PendingChange{Field: "resolution", From: cur.Resolution, To: opts.Resolution}) a.emitVMLog(opts.Name, "Set error: "+err.Error())
} return err
if opts.GPU != "" && opts.GPU != cur.GPU { }
diffs = append(diffs, PendingChange{Field: "gpu", From: cur.GPU, To: opts.GPU}) if diffs := pendingVMSettingsChanges(outcome, opts); len(diffs) > 0 {
} a.mu.Lock()
if opts.Displays > 0 && opts.Displays != cur.Displays { key := vmKey(opts.Name)
diffs = append(diffs, PendingChange{Field: "displays", From: fmt.Sprintf("%d", cur.Displays), To: fmt.Sprintf("%d", opts.Displays)}) a.pendingChanges[key] = mergePendingChanges(a.pendingChanges[key], diffs)
} if len(a.pendingChanges[key]) == 0 {
if dc := strings.ToLower(strings.TrimSpace(opts.DiskController)); dc != "" && !strings.EqualFold(dc, cur.DiskController) { delete(a.pendingChanges, key)
diffs = append(diffs, PendingChange{Field: "disk_controller", From: cur.DiskController, To: dc})
}
if dcache := strings.ToLower(strings.TrimSpace(opts.DiskCache)); dcache != "" && !strings.EqualFold(dcache, cur.DiskCache) {
from := cur.DiskCache
if from == "" {
from = "default"
}
diffs = append(diffs, PendingChange{Field: "disk_cache", From: from, To: dcache})
}
if opts.Borderless != nil && *opts.Borderless != cur.Borderless {
diffs = append(diffs, PendingChange{Field: "borderless", From: fmt.Sprintf("%v", cur.Borderless), To: fmt.Sprintf("%v", *opts.Borderless)})
}
if opts.NestedVirt != nil && *opts.NestedVirt != cur.NestedVirt {
diffs = append(diffs, PendingChange{Field: "nested_virt", From: fmt.Sprintf("%v", cur.NestedVirt), To: fmt.Sprintf("%v", *opts.NestedVirt)})
}
if opts.Audio != nil && *opts.Audio != cur.Audio {
diffs = append(diffs, PendingChange{Field: "audio", From: fmt.Sprintf("%v", cur.Audio), To: fmt.Sprintf("%v", *opts.Audio)})
}
if opts.AudioBackend != "" && opts.AudioBackend != cur.AudioBackend {
from := cur.AudioBackend
if from == "" {
from = "auto"
}
diffs = append(diffs, PendingChange{Field: "audio_backend", From: from, To: opts.AudioBackend})
}
if guestLangChanged {
from := cur.GuestLang
if from == "" {
from = "en-US:0"
}
diffs = append(diffs, PendingChange{Field: "guest_lang", From: from, To: strings.TrimSpace(opts.GuestLang)})
}
if len(diffs) > 0 {
a.mu.Lock()
a.pendingChanges[vmKey(opts.Name)] = append(a.pendingChanges[vmKey(opts.Name)], diffs...)
a.mu.Unlock()
} }
a.mu.Unlock()
} }
a.emitVMLog(opts.Name, "Updated VM settings for "+opts.Name) a.emitVMLog(opts.Name, "Updated VM settings for "+opts.Name)
a.emitStateChanged() a.emitStateChanged()
return nil return nil
} }
func pendingVMSettingsChanges(outcome macosdriver.SettingsOutcome, opts reims.SetOpts) []PendingChange {
if !outcome.Valid || !outcome.Running {
return nil
}
before, after := outcome.Before, outcome.After
candidates := []struct {
touched bool
change PendingChange
}{
{opts.CPUs > 0, PendingChange{Field: "cpus", From: strconv.Itoa(before.CPUs), To: strconv.Itoa(after.CPUs)}},
{opts.Memory != "", PendingChange{Field: "memory", From: before.Memory, To: after.Memory}},
{opts.AutoResolution != nil, PendingChange{Field: "auto_resolution", From: strconv.FormatBool(before.AutoResolution), To: strconv.FormatBool(after.AutoResolution)}},
{opts.Resolution != "", PendingChange{Field: "resolution", From: before.Resolution, To: after.Resolution}},
{opts.GPU != "", PendingChange{Field: "gpu", From: before.GPU, To: after.GPU}},
{opts.Displays > 0, PendingChange{Field: "displays", From: strconv.Itoa(before.Displays), To: strconv.Itoa(after.Displays)}},
{strings.TrimSpace(opts.DiskController) != "", PendingChange{Field: "disk_controller", From: before.DiskController, To: after.DiskController}},
{strings.TrimSpace(opts.DiskCache) != "", PendingChange{Field: "disk_cache", From: before.DiskCache, To: after.DiskCache}},
{opts.Borderless != nil, PendingChange{Field: "borderless", From: strconv.FormatBool(before.Borderless), To: strconv.FormatBool(after.Borderless)}},
{opts.NestedVirt != nil, PendingChange{Field: "nested_virt", From: strconv.FormatBool(before.NestedVirt), To: strconv.FormatBool(after.NestedVirt)}},
{opts.Audio != nil, PendingChange{Field: "audio", From: strconv.FormatBool(before.Audio), To: strconv.FormatBool(after.Audio)}},
{opts.AudioBackend != "", PendingChange{Field: "audio_backend", From: before.AudioBackend, To: after.AudioBackend}},
{strings.TrimSpace(opts.GuestLang) != "", PendingChange{Field: "guest_lang", From: before.GuestLang, To: after.GuestLang}},
}
out := make([]PendingChange, 0, len(candidates))
for _, item := range candidates {
if item.touched || !noPendingChange(item.change) {
out = append(out, item.change)
}
}
return out
}
func mergePendingChanges(existing, incoming []PendingChange) []PendingChange {
merged := make([]PendingChange, 0, len(existing)+len(incoming))
for _, changes := range [2][]PendingChange{existing, incoming} {
for _, change := range changes {
index := slices.IndexFunc(merged, func(pending PendingChange) bool { return pending.Field == change.Field })
if index < 0 {
merged = append(merged, change)
} else {
merged[index].To = change.To
}
}
}
return slices.DeleteFunc(merged, noPendingChange)
}
func noPendingChange(change PendingChange) bool {
if change.Field == "memory" || change.Field == "resolution" || change.Field == "disk_controller" || change.Field == "disk_cache" {
return strings.EqualFold(change.From, change.To)
}
return change.From == change.To
}
func lockMacOSDisplaySettings(vmDir string) (func(), error) {
return reims.LockVMOperation(vmDir)
}
type VMNetworkSettings struct { type VMNetworkSettings struct {
Adapters []NetworkAdapter `json:"adapters"` Adapters []NetworkAdapter `json:"adapters"`
UplinkGUID string `json:"uplink_guid"` UplinkGUID string `json:"uplink_guid"`
@@ -325,7 +302,9 @@ func clearManagedNetworkLedger(vmDir string) {
} }
} }
if changed { if changed {
_ = plugin.SaveArgLedger(vmDir, ledger) if err := plugin.SaveArgLedger(vmDir, ledger); err != nil {
log.Printf("[app] save plugin arg ledger failed (%s): %v", vmDir, err)
}
} }
} }
+663
View File
@@ -0,0 +1,663 @@
package app
import (
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/macos/macosdriver"
"github.com/Nwflower/reims-go/internal/macos/reims"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/vmstart"
)
const (
displayFixtureVM = "test-vm"
displayFixtureClone = "test-clone"
)
type displayCtlFixture struct {
Dir, State, Resolution string
Memory string
BeforeLockResolution string
Shows int
Graphics string
CloneDir string
Borderless bool
FailSet bool
NestedVirtBeforeSet bool
FailShowAfterSet bool
ReplaceDisplayAfterSet bool
Commands []string
}
func TestMain(m *testing.M) {
if path := os.Getenv("REIMS_TEST_DISPLAY_CTL"); path != "" {
switch filepath.Base(os.Args[0]) {
case "reims-ctl", "reims-ctl.exe":
if err := runDisplayCtl(path, os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
case "qemu-img", "qemu-img.exe":
if os.Args[1] == "info" {
fmt.Println(`{"format":"qcow2"}`)
return
}
if os.Args[1] == "create" {
if err := os.WriteFile(os.Args[len(os.Args)-1], []byte("overlay"), 0o600); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
if os.Args[1] == "convert" {
if err := os.WriteFile(os.Args[len(os.Args)-1], []byte("converted disk"), 0o600); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
fmt.Fprintln(os.Stderr, "unexpected qemu-img call", os.Args[1:])
os.Exit(1)
}
}
os.Exit(m.Run())
}
func runDisplayCtl(path string, args []string) error {
raw, err := os.ReadFile(path)
if err != nil {
return err
}
var vm displayCtlFixture
if err := json.Unmarshal(raw, &vm); err != nil {
return err
}
switch args[0] {
case "show":
if args[1] == displayFixtureClone && vm.CloneDir != "" {
fmt.Printf("state stopped\ndirectory %s\ndisplay one opening at %s\n", vm.CloneDir, vm.Resolution)
return nil
}
if vm.State == "" || args[1] != displayFixtureVM || vm.FailShowAfterSet && len(vm.Commands) > 0 {
return fmt.Errorf("VM %q not found", args[1])
}
if vm.BeforeLockResolution != "" {
vm.Shows++
if vm.Shows == 2 {
unlock, err := reims.LockVMOperation(vm.Dir)
if err != nil {
return err
}
defer unlock()
vm.Resolution = vm.BeforeLockResolution
if err := writeDisplayCtlResolution(vm.Dir, vm.Resolution); err != nil {
return err
}
if _, err := vmstart.SaveVMAutoResolution(vm.Dir, false); err != nil {
return err
}
}
raw, err := json.Marshal(vm)
if err != nil {
return err
}
if err := os.WriteFile(path, raw, 0o600); err != nil {
return err
}
}
fmt.Printf("state %s\ndirectory %s\ndisk system.qcow2\ngraphics %s\nmemory %s\n", vm.State, vm.Dir, vm.Graphics, vm.Memory)
if vm.Borderless {
fmt.Printf("display one borderless at %s\n", vm.Resolution)
} else {
fmt.Printf("display one opening at %s\n", vm.Resolution)
}
return nil
case "list":
if vm.State == "" {
fmt.Println("[]")
return nil
}
return json.NewEncoder(os.Stdout).Encode([]reims.VMListItem{{Name: displayFixtureVM, State: vm.State, Dir: vm.Dir}})
case "create":
if args[1] == displayFixtureClone {
vm.CloneDir = filepath.Join(filepath.Dir(vm.Dir), displayFixtureClone)
if err := os.MkdirAll(vm.CloneDir, 0o700); err != nil {
return err
}
} else {
vm.State = "stopped"
if err := os.MkdirAll(vm.Dir, 0o700); err != nil {
return err
}
}
case "set", "start":
if args[0] == "set" && len(args) > 1 && args[1] == "--help" {
return nil
}
default:
return fmt.Errorf("unexpected command %v", args)
}
failSet := args[0] == "set" && vm.FailSet
if failSet {
nested, err := vmstart.ReadVMNestedVirt(vm.Dir)
if err != nil {
return err
}
vm.NestedVirtBeforeSet = nested.Enabled
}
for i := 2; !failSet && i+1 < len(args); i++ {
switch args[i] {
case "--resolution":
vm.Resolution = args[i+1]
if err := writeDisplayCtlResolution(vm.Dir, vm.Resolution); err != nil {
return err
}
case "--borderless":
vm.Borderless = args[i+1] == "true"
case "--graphics":
vm.Graphics = args[i+1]
case "--memory":
vm.Memory = args[i+1]
}
}
if args[0] == "set" && vm.ReplaceDisplayAfterSet {
vm.Resolution = "1024x768"
if _, err := vmstart.SaveVMAutoResolution(vm.Dir, false); err != nil {
return err
}
}
command := strings.Join(args, " ")
if args[0] == "start" {
command += " fixed=" + os.Getenv("REIMS_VGPU_WINDOW_FIXED_MODE")
}
vm.Commands = append(vm.Commands, command)
raw, err = json.Marshal(vm)
if err != nil {
return err
}
if err := os.WriteFile(path, raw, 0o600); err != nil {
return err
}
if args[0] == "start" {
return fmt.Errorf("stop before launching QEMU")
}
if failSet {
return fmt.Errorf("fixture refused set")
}
return nil
}
func writeDisplayCtlResolution(dir, resolution string) error {
config := fmt.Sprintf("disk = 'system.qcow2'\n[display]\nresolution = %q\n", resolution)
return os.WriteFile(filepath.Join(dir, "vm.toml"), []byte(config), 0o600)
}
func newDisplayCtlApp(t *testing.T, vm displayCtlFixture, useDriver bool) (*App, func() displayCtlFixture) {
t.Helper()
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "test-rt"}
if err := cfg.EnsureDirs(); err != nil {
t.Fatal(err)
}
active := rt.Installed{Dir: filepath.Join(cfg.RuntimesDir(), cfg.ActiveRuntime)}
control := active.ControlPath()
if err := os.MkdirAll(filepath.Dir(control), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(active.Dir, "manifest.json"), []byte(`{"schema_version":2,"commit":"test-rt","kind":"reims-vgpu","runtime_api":"1.0.0","capabilities":["display-fixed-mode","vm-suspend"]}`), 0o600); err != nil {
t.Fatal(err)
}
self, err := os.Executable()
if err != nil {
t.Fatal(err)
}
exe, err := os.ReadFile(self)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(control, exe, 0o755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Dir(active.QemuImgPath()), 0o700); err != nil {
t.Fatal(err)
}
if err := os.Link(control, active.QemuImgPath()); err != nil {
t.Fatal(err)
}
fixturePath := filepath.Join(cfg.DataRoot, "display-fixture.json")
t.Setenv("REIMS_TEST_DISPLAY_CTL", fixturePath)
t.Setenv("REIMS_VGPU_WINDOW_FIXED_MODE", "")
t.Setenv("GORACE", "atexit_sleep_ms=0")
registryDir := filepath.Join(cfg.XDGConfigDir(), "reims-ctl")
t.Setenv("REIMS_CTL_CONFIG_DIR", registryDir)
if err := os.MkdirAll(registryDir, 0o700); err != nil {
t.Fatal(err)
}
vm.Dir = filepath.Join(cfg.DataRoot, displayFixtureVM)
if vm.State != "" {
if err := os.MkdirAll(vm.Dir, 0o700); err != nil {
t.Fatal(err)
}
if err := writeDisplayCtlResolution(vm.Dir, vm.Resolution); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(vm.Dir, "system.qcow2"), []byte("source disk fixture"), 0o600); err != nil {
t.Fatal(err)
}
registry := fmt.Sprintf("[[vm]]\nname = %q\ndir = '%s'\n", displayFixtureVM, vm.Dir)
if err := os.WriteFile(filepath.Join(registryDir, "vms.toml"), []byte(registry), 0o600); err != nil {
t.Fatal(err)
}
}
raw, err := json.Marshal(vm)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(fixturePath, raw, 0o600); err != nil {
t.Fatal(err)
}
a := &App{}
if useDriver {
a = newDisplayTestApp(t, macosdriver.NewReimsMacOSDriver(func() config.Config { return cfg }))
}
a.cfg = &cfg
a.transitions = map[string]string{}
a.pendingChanges = map[string][]PendingChange{}
return a, func() displayCtlFixture {
t.Helper()
raw, err := os.ReadFile(fixturePath)
if err != nil {
t.Fatal(err)
}
var current displayCtlFixture
if err := json.Unmarshal(raw, &current); err != nil {
t.Fatal(err)
}
return current
}
}
func TestApplyAutoResolutionWhileRunning(t *testing.T) {
for _, state := range []string{"running", "paused"} {
t.Run(state, func(t *testing.T) {
initial := "1234x876"
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: state, Resolution: initial}, true)
on := true
if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: "1280x800", AutoResolution: &on}); err != nil {
t.Fatal(err)
}
vm := fixture()
want := []PendingChange{
{Field: "auto_resolution", From: "false", To: "true"},
}
if vm.Resolution != initial || len(vm.Commands) != 0 || !vmstart.ReadVMDisplay(vm.Dir).AutoResolution || !slices.Equal(a.pendingChanges[vmKey(displayFixtureVM)], want) {
t.Fatalf("enable auto: VM %+v, changes %+v, want %+v", vm, a.pendingChanges, want)
}
if raw, found := reims.ReadConfiguredResolution(vm.Dir); !found || raw != initial {
t.Fatalf("configured resolution = %q, found = %t, want %q", raw, found, initial)
}
if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: initial}); err != nil {
t.Fatal(err)
}
vm = fixture()
if vm.Resolution != initial || vmstart.ReadVMDisplay(vm.Dir).AutoResolution || len(a.pendingChanges) != 0 {
t.Fatalf("manual resolution: VM %+v, want initial resolution and no pending changes, got %+v", vm, a.pendingChanges)
}
if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: "1280x800"}); err != nil {
t.Fatal(err)
}
want = []PendingChange{{Field: "resolution", From: initial, To: "1280x800"}}
if vm = fixture(); vm.Resolution != "1280x800" || !slices.Equal(a.pendingChanges[vmKey(displayFixtureVM)], want) {
t.Fatalf("changed fixed resolution: VM %+v, changes %+v, want %+v", vm, a.pendingChanges, want)
}
})
}
}
func TestApplyAutoResolutionDoesNotReadBackSettings(t *testing.T) {
for _, tc := range []struct {
name string
failShow, replace bool
}{
{name: "show fails", failShow: true},
{name: "display changed externally", replace: true},
} {
t.Run(tc.name, func(t *testing.T) {
const initial = "1234x876"
a, fixture := newDisplayCtlApp(t, displayCtlFixture{
State: "running", Resolution: initial, FailShowAfterSet: tc.failShow, ReplaceDisplayAfterSet: tc.replace,
}, true)
on := true
if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, CPUs: 1, AutoResolution: &on}); err != nil {
t.Fatal(err)
}
want := []PendingChange{
{Field: "cpus", From: "0", To: "1"},
{Field: "auto_resolution", From: "false", To: "true"},
}
if got := a.pendingChanges[vmKey(displayFixtureVM)]; !slices.Equal(got, want) {
t.Fatalf("pending changes = %+v, want %+v", got, want)
}
if got := fixture().Commands; !slices.Equal(got, []string{"set test-vm --cpus 1"}) {
t.Fatalf("commands = %v", got)
}
})
}
}
func TestApplyAutoResolutionUsesLockedSettingsForPendingChanges(t *testing.T) {
a, fixture := newDisplayCtlApp(t, displayCtlFixture{
State: "running", Resolution: "1234x876", BeforeLockResolution: "2560x1600", Memory: "2G",
}, true)
if _, err := vmstart.SaveVMAutoResolution(fixture().Dir, true); err != nil {
t.Fatal(err)
}
if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Memory: "3G"}); err != nil {
t.Fatal(err)
}
vm := fixture()
if vm.Resolution != "2560x1600" || vm.Memory != "3G" || vmstart.ReadVMDisplay(vm.Dir).AutoResolution {
t.Fatalf("saved VM = %+v, display = %+v", vm, vmstart.ReadVMDisplay(vm.Dir))
}
want := []PendingChange{{Field: "memory", From: "2G", To: "3G"}}
if got := a.pendingChanges[vmKey(displayFixtureVM)]; !slices.Equal(got, want) {
t.Fatalf("pending changes = %+v, want %+v", got, want)
}
}
func TestMergePendingChangesKeepsRunningValues(t *testing.T) {
existing := []PendingChange{
{Field: "memory", From: "8G", To: "12G"},
{Field: "resolution", From: "1920x1080", To: "2560x1440"},
{Field: "gpu", From: "gpu-a", To: "gpu-b"},
{Field: "cpus", From: "4", To: "6"},
}
incoming := []PendingChange{
{Field: "memory", From: "12G", To: "8g"},
{Field: "resolution", From: "2560x1440", To: "1920X1080"},
{Field: "gpu", From: "gpu-b", To: "GPU-A"},
{Field: "cpus", From: "6", To: "8"},
}
want := []PendingChange{
{Field: "gpu", From: "gpu-a", To: "GPU-A"},
{Field: "cpus", From: "4", To: "8"},
}
if got := mergePendingChanges(existing, incoming); !slices.Equal(got, want) {
t.Fatalf("merge = %+v, want %+v", got, want)
}
// When show reports live running value (4 -> 4) while user explicitly sets cpus back to 4,
// pendingVMSettingsChanges still emits cpus so mergePendingChanges removes stale 4 -> 8
// without disturbing unrelated pending entries.
liveOutcome := macosdriver.SettingsOutcome{
Valid: true,
Running: true,
Before: macosdriver.SettingsState{CPUs: 4, Memory: "8G"},
After: macosdriver.SettingsState{CPUs: 4, Memory: "8G"},
}
diffs := pendingVMSettingsChanges(liveOutcome, reims.SetOpts{Name: displayFixtureVM, CPUs: 4})
got := mergePendingChanges([]PendingChange{
{Field: "cpus", From: "4", To: "8"},
{Field: "memory", From: "8G", To: "12G"},
}, diffs)
wantAfterRevert := []PendingChange{{Field: "memory", From: "8G", To: "12G"}}
if !slices.Equal(got, wantAfterRevert) {
t.Fatalf("merge after live-value revert = %+v, want %+v", got, wantAfterRevert)
}
}
func TestApplyAutoResolutionTransaction(t *testing.T) {
for _, tc := range []struct {
name string
failSidecar, failSet bool
}{
{name: "saved"},
{name: "sidecar write fails", failSidecar: true},
{name: "set fails", failSet: true},
} {
t.Run(tc.name, func(t *testing.T) {
const initial = "1234x876"
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: "stopped", Resolution: initial, FailSet: tc.failSet}, true)
dir := fixture().Dir
prev := vmstart.VMDisplayConfig{TargetDisplay: "unplugged-display"}
if tc.failSidecar {
if err := os.Mkdir(filepath.Join(dir, ".reims-go-display.json"), 0o700); err != nil {
t.Fatal(err)
}
} else if _, err := vmstart.SaveVMDisplay(dir, prev); err != nil {
t.Fatal(err)
}
on := true
err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: "1280x800", AutoResolution: &on, NestedVirt: &on})
if tc.failSidecar {
if err == nil || len(fixture().Commands) != 0 {
t.Fatalf("save = %v, commands = %v, want sidecar error before set", err, fixture().Commands)
}
return
}
vm := fixture()
target, _ := host.RecommendAutoResolution(host.PrimaryDisplayOf(host.ConnectedDisplays()), false, true)
if !slices.Equal(vm.Commands, []string{"set test-vm --resolution " + target}) {
t.Fatalf("commands = %v", vm.Commands)
}
if nested, readErr := vmstart.ReadVMNestedVirt(dir); readErr != nil || nested.Enabled != !tc.failSet {
t.Fatalf("nested virtualization = %+v, %v, want enabled = %t", nested, readErr, !tc.failSet)
}
if tc.failSet {
if err == nil || !vm.NestedVirtBeforeSet || vm.Resolution != initial || vmstart.ReadVMDisplay(dir) != prev {
t.Fatalf("save = %v, VM = %+v, display = %+v, want original settings", err, vm, vmstart.ReadVMDisplay(dir))
}
return
}
prev.AutoResolution = true
if err != nil || vm.Resolution != target || vmstart.ReadVMDisplay(dir) != prev {
t.Fatalf("save = %v, VM = %+v, display = %+v, want %s and %+v", err, vm, vmstart.ReadVMDisplay(dir), target, prev)
}
})
}
}
func TestApplyAutoResolutionWithSVGA(t *testing.T) {
for _, graphics := range []string{"vmware-svga", "reims-vgpu"} {
t.Run(graphics, func(t *testing.T) {
const initial = "1234x876"
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: "stopped", Resolution: initial, Graphics: graphics}, true)
dir := fixture().Dir
prev := vmstart.VMDisplayConfig{TargetDisplay: "secondary", AutoResolution: true}
if _, err := vmstart.SaveVMDisplay(dir, prev); err != nil {
t.Fatal(err)
}
detail, err := a.GetVMDetail(displayFixtureVM)
if err != nil || detail.AutoResolution != (graphics == "reims-vgpu") {
t.Fatalf("details = %+v, %v", detail, err)
}
on := true
opts := reims.SetOpts{Name: displayFixtureVM, AutoResolution: &on}
var want []string
if graphics != "vmware-svga" {
opts.Graphics = "vmware-svga"
want = []string{"set test-vm --graphics vmware-svga"}
}
if err := a.ApplyVMSettings(opts); err != nil {
t.Fatal(err)
}
prev.AutoResolution = false
if vm := fixture(); vm.Graphics != "vmware-svga" || vm.Resolution != initial ||
!slices.Equal(vm.Commands, want) || vmstart.ReadVMDisplay(dir) != prev {
t.Fatalf("VM = %+v, display = %+v, want commands %v and display %+v", vm, vmstart.ReadVMDisplay(dir), want, prev)
}
})
}
}
func TestApplyAutoResolutionRollsBackDisplayOnLaterFailure(t *testing.T) {
for _, tc := range []struct {
state, blockedFile string
}{
{"running", ".reims-go-nested-virt.json"},
{"stopped", ".reims-go-nested-virt.json"},
{"running", ".reims-go-guest-lang"},
{"stopped", ".reims-go-guest-lang"},
} {
t.Run(tc.state+"/"+tc.blockedFile, func(t *testing.T) {
const initial = "1234x876"
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: tc.state, Resolution: initial}, true)
dir := fixture().Dir
prev := vmstart.VMDisplayConfig{TargetDisplay: "unplugged-display"}
if _, err := vmstart.SaveVMDisplay(dir, prev); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(filepath.Join(dir, tc.blockedFile), 0o700); err != nil {
t.Fatal(err)
}
on := true
opts := reims.SetOpts{Name: displayFixtureVM, Memory: "4G", AutoResolution: &on, NestedVirt: &on}
if tc.blockedFile == ".reims-go-guest-lang" {
opts.GuestLang = "zh-Hans:0"
}
if err := a.ApplyVMSettings(opts); err == nil || !strings.Contains(err.Error(), tc.blockedFile) {
t.Fatalf("save = %v, want error writing %s", err, tc.blockedFile)
}
if commands := fixture().Commands; len(commands) != 0 {
t.Fatalf("commands = %v, want no reims-ctl set call before local failures", commands)
}
if got := vmstart.ReadVMDisplay(dir); got != prev || len(a.pendingChanges) != 0 {
t.Fatalf("display = %+v, want %+v; pending = %+v", got, prev, a.pendingChanges)
}
if raw, found := reims.ReadConfiguredResolution(dir); !found || raw != initial {
t.Fatalf("configured resolution = %q, found = %t, want %q", raw, found, initial)
}
if opts.GuestLang != "" {
if nested, err := vmstart.ReadVMNestedVirt(dir); err != nil || nested.Enabled {
t.Fatalf("nested virtualization = %+v, %v, want disabled", nested, err)
}
}
})
}
}
func TestApplyAutoResolutionSyncsExistingConfiguration(t *testing.T) {
for _, tc := range []struct {
name, graphics string
borderless bool
}{
{name: "windowed multi-display"},
{name: "borderless multi-display", borderless: true},
{name: "from SVGA", graphics: "vmware-svga"},
} {
t.Run(tc.name, func(t *testing.T) {
res, _ := host.RecommendAutoResolution(host.PrimaryDisplayOf(host.ConnectedDisplays()), tc.borderless, true)
raw := res
want := "set test-vm --resolution " + res
on := true
opts := reims.SetOpts{Name: displayFixtureVM, AutoResolution: &on}
if tc.graphics == "vmware-svga" {
opts.Graphics = "reims-vgpu"
want = "set test-vm --graphics reims-vgpu --resolution " + res
} else {
raw += ",2560x1440"
}
a, fixture := newDisplayCtlApp(t, displayCtlFixture{
State: "stopped", Resolution: res, Graphics: tc.graphics, Borderless: tc.borderless,
}, true)
dir := fixture().Dir
if err := writeDisplayCtlResolution(dir, raw); err != nil {
t.Fatal(err)
}
if err := a.ApplyVMSettings(opts); err != nil {
t.Fatal(err)
}
if got := fixture().Commands; !slices.Equal(got, []string{want}) {
t.Fatalf("commands = %v, want %q", got, want)
}
})
}
}
func TestCreateVMWithAutoResolution(t *testing.T) {
for _, useDriver := range []bool{false, true} {
for _, tc := range []struct {
name, graphics, resolution string
wantAuto bool
}{
{name: "no draft", wantAuto: true},
{name: "stale draft", resolution: "1234x876", wantAuto: true},
{name: "SVGA", graphics: "vmware-svga", resolution: "1234x876"},
{name: "SVGA without resolution", graphics: "vmware-svga"},
} {
t.Run(fmt.Sprintf("driver=%t/%s", useDriver, tc.name), func(t *testing.T) {
a, fixture := newDisplayCtlApp(t, displayCtlFixture{}, false)
if useDriver {
d := macosdriver.NewReimsMacOSDriver(func() config.Config { return *a.cfg })
req := driver.CreateRequest{Name: displayFixtureVM, Options: map[string]any{"auto_resolution": true, "resolution": tc.resolution, "graphics": tc.graphics}}
if err := d.Create(t.Context(), req, io.Discard, io.Discard); err != nil {
t.Fatal(err)
}
} else {
on := true
if err := a.CreateVM(reims.CreateOpts{Name: displayFixtureVM, CPUs: 1, SourceMode: "disk", AutoResolution: &on, Resolution: tc.resolution, Graphics: tc.graphics}); err != nil {
t.Fatal(err)
}
}
vm := fixture()
want := tc.resolution
if tc.wantAuto {
want, _ = host.RecommendAutoResolution(host.PrimaryDisplayOf(host.ConnectedDisplays()), false, true)
}
if vm.Resolution != want || vmstart.ReadVMDisplay(vm.Dir).AutoResolution != tc.wantAuto {
t.Fatalf("created VM = %+v, want resolution %s and automatic mode %t", vm, want, tc.wantAuto)
}
})
}
}
}
func TestCreateVMWithAutoResolutionRefreshesAfterDiskConversion(t *testing.T) {
a, fixture := newDisplayCtlApp(t, displayCtlFixture{}, false)
source := filepath.Join(a.cfg.DataRoot, "source.raw")
if err := os.WriteFile(source, []byte("raw disk"), 0o600); err != nil {
t.Fatal(err)
}
connectedDisplays := func() []host.DisplayInfo {
converted, err := filepath.Glob(filepath.Join(a.cfg.TempDir(), "import-*.qcow2"))
if err != nil {
t.Fatal(err)
}
if len(converted) == 0 {
return []host.DisplayInfo{{Primary: true, Width: 3840, Height: 2160, ScalePct: 150}}
}
return []host.DisplayInfo{{Primary: true, Width: 3200, Height: 2000, ScalePct: 200}}
}
on := true
opts := reims.CreateOpts{Name: displayFixtureVM, CPUs: 1, SourceMode: "disk", Disk: source, AutoResolution: &on, Borderless: &on}
if err := a.createVMFlow(opts, connectedDisplays); err != nil {
t.Fatal(err)
}
if vm := fixture(); vm.Resolution != "3200x2000" || !vmstart.ReadVMDisplay(vm.Dir).AutoResolution {
t.Fatalf("created VM = %+v, want automatic 3200x2000", vm)
}
}
func TestClonePreservesAutoResolution(t *testing.T) {
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: "stopped", Resolution: "2880x1800"}, false)
source := fixture().Dir
if _, err := vmstart.SaveVMDisplay(source, vmstart.VMDisplayConfig{TargetDisplay: "DISPLAY2", AutoResolution: true}); err != nil {
t.Fatal(err)
}
d := macosdriver.NewReimsMacOSDriver(func() config.Config { return *a.cfg })
if err := d.CloneCoW(t.Context(), displayFixtureVM, displayFixtureClone, io.Discard, io.Discard); err != nil {
t.Fatal(err)
}
if got := vmstart.ReadVMDisplay(fixture().CloneDir); got != (vmstart.VMDisplayConfig{AutoResolution: true}) {
t.Fatalf("cloned display preference = %+v", got)
}
}
-129
View File
@@ -1,143 +1,14 @@
package app package app
import ( import (
"context"
"errors"
"fmt" "fmt"
"io"
"path/filepath"
"runtime" "runtime"
"strings"
"sync" "sync"
"sync/atomic" "sync/atomic"
"testing" "testing"
"time" "time"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
) )
type reviewNetworkControl struct {
extra string
writes int
setErr error
}
func (*reviewNetworkControl) List(context.Context) ([]reims.VMListItem, error) { return nil, nil }
func (*reviewNetworkControl) Show(context.Context, string) (reims.VMDetail, error) {
return reims.VMDetail{}, nil
}
func (*reviewNetworkControl) CommandText(context.Context, string) (string, error) {
return "qemu -netdev user,id=net0 -device virtio-net-pci,netdev=net0,id=net0,mac=02:00:00:00:00:01", nil
}
func (c *reviewNetworkControl) Set(_ context.Context, opts reims.SetOpts, _, _ io.Writer) error {
if c.setErr != nil {
return c.setErr
}
if opts.ExtraArgs != nil {
c.extra = *opts.ExtraArgs
c.writes++
}
return nil
}
func TestLegacyBridgeArgsHaveRemovableOwner(t *testing.T) {
dir := t.TempDir()
detail := reims.VMDetail{Name: "fake-vm", Directory: dir, NetworkMode: "bridge", ExtraArgs: "-cpu host"}
if err := reims.SaveNetworkRecord(dir, reims.NetworkRecord{Mode: "bridge", SocketPath: filepath.Join(dir, "bridge.sock")}); err != nil {
t.Fatal(err)
}
control := &reviewNetworkControl{}
a := &App{}
if err := a.reconcileLegacyBridgeArgs(context.Background(), control, &detail); err != nil {
t.Fatal(err)
}
if !strings.Contains(control.extra, "id=reimsbridge0") {
t.Fatal("隔离客户端未收到桥接参数")
}
ledger, err := plugin.LoadArgLedger(dir)
if err != nil {
t.Fatal(err)
}
if len(ledger.Owners[builtin.IDNpcapBridge]) != 1 {
t.Fatalf("桥接参数已写入,但 Npcap 账本条目数为 %d", len(ledger.Owners[builtin.IDNpcapBridge]))
}
if err := a.reconcileLegacyBridgeArgs(context.Background(), control, &detail); err != nil {
t.Fatal(err)
}
if control.writes != 1 {
t.Fatalf("重复准备写入了 %d 次参数", control.writes)
}
if strings.Count(detail.ExtraArgs, "id=reimsbridge0,") != 1 {
t.Fatal("重复准备产生重复桥接设备")
}
clean := plugin.ReconcileStartIntents(detail.ExtraArgs, ledger, map[string]bool{}, nil)
if clean.ExtraArgs != "-cpu host" {
t.Fatalf("停用后残留桥接参数:%s", clean.ExtraArgs)
}
}
func TestLegacyBridgeArgsStopOnInvalidRecordOrWriteFailure(t *testing.T) {
for _, mode := range []string{"corrupt", "pending", "set failure"} {
t.Run(mode, func(t *testing.T) {
dir := t.TempDir()
detail := reims.VMDetail{Name: "fake-vm", Directory: dir, NetworkMode: "bridge", ExtraArgs: "-cpu host"}
record := reims.NetworkRecord{Mode: "bridge", SocketPath: filepath.Join(dir, "bridge.sock")}
code := "E_NETWORK_CONFIG_SAVE"
control := &reviewNetworkControl{setErr: errors.New("模拟配置写入失败")}
if mode == "corrupt" {
record.Version = 99
code = "E_NETWORK_RECORD_INVALID"
}
if mode == "pending" {
record.Pending = true
code = "E_NETWORK_PACKET_PENDING"
}
if err := reims.SaveNetworkRecord(dir, record); err != nil {
t.Fatal(err)
}
err := (&App{}).reconcileLegacyBridgeArgs(context.Background(), control, &detail)
var coded *i18n.CodedError
if !errors.As(err, &coded) || coded.Code != code {
t.Fatalf("错误 = %v,预期 %s", err, code)
}
ledger, err := plugin.LoadArgLedger(dir)
if err != nil {
t.Fatal(err)
}
if detail.ExtraArgs != "-cpu host" || len(ledger.Owners) != 0 {
t.Fatal("准备失败却更新了参数或归属")
}
})
}
}
func TestLegacyBridgeArgsClearOwnerWhenLeavingBridge(t *testing.T) {
dir := t.TempDir()
detail := reims.VMDetail{Name: "fake-vm", Directory: dir, NetworkMode: "bridge", ExtraArgs: "-cpu host"}
if err := reims.SaveNetworkRecord(dir, reims.NetworkRecord{Mode: "bridge", SocketPath: filepath.Join(dir, "bridge.sock")}); err != nil {
t.Fatal(err)
}
a := &App{}
control := &reviewNetworkControl{}
if err := a.reconcileLegacyBridgeArgs(context.Background(), control, &detail); err != nil {
t.Fatal(err)
}
detail.NetworkMode = "nat"
if err := a.reconcileLegacyBridgeArgs(context.Background(), control, &detail); err != nil {
t.Fatal(err)
}
ledger, err := plugin.LoadArgLedger(dir)
if err != nil {
t.Fatal(err)
}
if detail.ExtraArgs != "-cpu host" || len(ledger.Owners[builtin.IDNpcapBridge]) != 0 {
t.Fatal("离开桥接后仍残留参数或归属")
}
}
func networkLockCount(a *App) int { func networkLockCount(a *App) int {
count := 0 count := 0
a.vmNetworkLocks.Range(func(_, _ any) bool { count++; return true }) a.vmNetworkLocks.Range(func(_, _ any) bool { count++; return true })
+93 -124
View File
@@ -70,18 +70,19 @@ func (a *App) initPlugins() {
return return
} }
var mgr *plugin.Manager var mgr *plugin.Manager
mgr, err := plugin.NewManager(plugin.ManagerOptions{ var drvRouter *driver.Router
DataRoot: dataRoot, mgr, drvRouter, err := builtin.BootstrapKernel(builtin.KernelBootstrapOptions{
HostVersion: version.Version, DataRoot: dataRoot,
SafeMode: safeMode, DataRootFn: func() string {
RedactFn: host.RedactText, a.mu.Lock()
LocaleFn: a.locale, defer a.mu.Unlock()
return a.cfg.DataRoot
},
SafeMode: safeMode,
LocaleFn: a.locale,
Logger: func(source, line string) { Logger: func(source, line string) {
a.emitLog(source, line) a.emitLog(source, line)
}, },
SidecarDriverFactory: func(contrib plugin.GuestDriverContribution, sup *plugin.SidecarSupervisor) any {
return driver.NewSidecarDriver(contrib, sup)
},
HostHandlers: func(pluginID string) map[string]plugin.RPCRequestHandler { HostHandlers: func(pluginID string) map[string]plugin.RPCRequestHandler {
a.mu.Lock() a.mu.Lock()
current := a.pluginMgr current := a.pluginMgr
@@ -91,23 +92,91 @@ func (a *App) initPlugins() {
OnSettingsChanged: func(pluginID, vmName string) { OnSettingsChanged: func(pluginID, vmName string) {
a.onPluginSettingsChanged(pluginID, vmName) a.onPluginSettingsChanged(pluginID, vmName)
}, },
OnSidecarStopped: func(pluginID string) {
// A plugin that held a key or a pointer button in a guest can no
// longer release it, so the host lifts what it left down.
a.releaseHeldForPlugin(pluginID)
},
VMInventory: guest.VMInventory(),
Callbacks: builtin.HostCallbacks{
GetConfig: a.runtimeConfig,
Log: func(source, line string) {
a.emitLog(source, line)
},
EnsureGuestTools: func() (*guesttools.Server, int, error) {
srv, port, created, err := a.startGuestToolsServer()
if err == nil && created {
// A fresh server knows no VM tokens: at startup and when the
// plugin is switched back on, re-register configured VMs.
go a.registerVMsWithBridge(context.Background(), srv, port)
}
return srv, port, err
},
StopGuestTools: func() {
a.mu.Lock()
gt := a.guestTools
a.guestTools = nil
a.mu.Unlock()
if gt != nil {
shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
_ = gt.Close(shutCtx)
cancel()
}
},
LoadAndRegisterGuestTools: func(srv *guesttools.Server, port int, dir, name string) (guesttools.VMConfig, error) {
epoch := a.vmDeleteEpoch(name)
// The start hook can receive a directory read before the VM was deleted.
if epoch != 0 {
vms, err := a.listVMsInternal(context.Background())
if err != nil {
return guesttools.VMConfig{}, err
}
if !slices.ContainsFunc(vms, func(vm driver.VMListItem) bool {
return strings.EqualFold(vm.Name, name) && filepath.Clean(vm.Dir) == filepath.Clean(dir)
}) {
return guesttools.VMConfig{}, os.ErrNotExist
}
}
return a.loadAndRegisterNetworkGuestTools(srv, port, dir, name, epoch)
},
OnIMEText: func(target host.IMETarget, text string) {
go a.injectRemoteText(target.VMName, target.VMDir, text)
},
StartColdReboot: func(vmName, qmpAddr string) {
a.watchWin10ColdReboot(vmName, qmpAddr)
},
CancelColdReboot: func(vmName string) {
a.cancelRebootWatcher(vmName)
},
GuestToolsImg: func(vmName string) string {
return a.guestToolsImagePath(vmName)
},
BuildGuestToolsImage: a.buildGuestToolsImage,
OpenAppWindow: a.openAppWindow,
PrepareVMNetwork: a.prepareManagedVMNetwork,
RestorePacketBridges: func(ctx context.Context) func() {
return a.startPacketBridgeRestore(ctx, func(ctx context.Context) {
if a.dataRootUsable() {
a.registerExistingPacketBridges(ctx)
}
})
},
StopPacketBridges: a.closePacketBridges,
OnInstallGuidesChanged: func() {
a.emitStateChanged()
},
SyncInstallGuides: func() {
a.wakePoll()
},
},
RegisterGuest: guest.Register,
}) })
if err != nil { if err != nil {
a.emitLog("plugin", "Plugin state warning: "+err.Error()) a.emitLog("plugin", "Could not initialize plugin manager: "+err.Error())
if mgr == nil { return
return
}
} }
kindReg := rt.NewKindRegistry() kindReg := rt.NewKindRegistry()
drvRouter := driver.NewRouter(mgr.Registry(), func() string {
a.mu.Lock()
defer a.mu.Unlock()
return a.cfg.DataRoot
}, guest.VMInventory())
mgr.Registry().SetInUseChecker(drvRouter.PluginInUseChecker())
mgr.Registry().SetBusyChecker(drvRouter.PluginBusyChecker())
// Drivers push the state of the VMs they host; the router merges the table // Drivers push the state of the VMs they host; the router merges the table
// into what the drivers return. A spawned VM's exit wakes the poll at once. // into what the drivers return. A spawned VM's exit wakes the poll at once.
@@ -128,92 +197,6 @@ func (a *App) initPlugins() {
a.emitLog("plugin:"+pluginID, title+": "+body) a.emitLog("plugin:"+pluginID, title+": "+body)
}) })
cb := builtin.HostCallbacks{
GetConfig: a.runtimeConfig,
Log: func(source, line string) {
a.emitLog(source, line)
},
EnsureGuestTools: func() (*guesttools.Server, int, error) {
srv, port, created, err := a.startGuestToolsServer()
if err == nil && created {
// A fresh server knows no VM tokens: at startup and when the
// plugin is switched back on, re-register configured VMs.
go a.registerVMsWithBridge(context.Background(), srv, port)
}
return srv, port, err
},
StopGuestTools: func() {
a.mu.Lock()
gt := a.guestTools
a.guestTools = nil
a.mu.Unlock()
if gt != nil {
shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
_ = gt.Close(shutCtx)
cancel()
}
},
LoadAndRegisterGuestTools: func(srv *guesttools.Server, port int, dir, name string) (guesttools.VMConfig, error) {
epoch := a.vmDeleteEpoch(name)
// The start hook can receive a directory read before the VM was deleted.
if epoch != 0 {
vms, err := a.listVMsInternal(context.Background())
if err != nil {
return guesttools.VMConfig{}, err
}
if !slices.ContainsFunc(vms, func(vm driver.VMListItem) bool {
return strings.EqualFold(vm.Name, name) && filepath.Clean(vm.Dir) == filepath.Clean(dir)
}) {
return guesttools.VMConfig{}, os.ErrNotExist
}
}
return a.loadAndRegisterNetworkGuestTools(srv, port, dir, name, epoch)
},
OnIMEText: func(target host.IMETarget, text string) {
go a.injectRemoteText(target.VMName, target.VMDir, text)
},
StartColdReboot: func(vmName, qmpAddr string) {
a.watchWin10ColdReboot(vmName, qmpAddr)
},
CancelColdReboot: func(vmName string) {
a.cancelRebootWatcher(vmName)
},
GuestToolsImg: func(vmName string) string {
return a.guestToolsImagePath(vmName)
},
BuildGuestToolsImage: a.buildGuestToolsImage,
OpenAppWindow: a.openAppWindow,
PrepareVMNetwork: a.prepareManagedVMNetwork,
RestorePacketBridges: func(ctx context.Context) func() {
return a.startPacketBridgeRestore(ctx, func(ctx context.Context) {
if a.dataRootUsable() {
a.registerExistingPacketBridges(ctx)
}
})
},
StopPacketBridges: a.closePacketBridges,
OnInstallGuidesChanged: func() {
a.emitStateChanged()
},
SyncInstallGuides: func() {
a.wakePoll()
},
GetSetting: func(pluginID, vmName, key string) (any, bool) {
v, ok := mgr.GetSettings(pluginID, vmName, false)[key]
return v, ok
},
}
if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
a.emitLog("plugin", "Builtin extension register error: "+err.Error())
}
if err := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
a.emitLog("plugin", "macOS guest plugin register error: "+err.Error())
}
if err := mgr.LoadExternal(); err != nil {
a.emitLog("plugin", "External plugin load warning: "+err.Error())
}
// Sync runtime kinds, input filters, clipboard policies, and locales whenever registry state changes. // Sync runtime kinds, input filters, clipboard policies, and locales whenever registry state changes.
mgr.Registry().OnChange(func() { mgr.Registry().OnChange(func() {
active := map[string]bool{} active := map[string]bool{}
@@ -223,27 +206,19 @@ func (a *App) initPlugins() {
stateTable.PruneDrivers(active) stateTable.PruneDrivers(active)
a.syncRuntimeKinds(kindReg, mgr.Registry()) a.syncRuntimeKinds(kindReg, mgr.Registry())
a.syncInputFilters() a.syncInputFilters()
a.syncKeymapRules()
a.syncClipboardPolicies() a.syncClipboardPolicies()
a.syncLocales() a.syncLocales()
a.wakePoll() a.wakePoll()
a.emitStateChanged() a.emitStateChanged()
}) })
a.keymapMu.Lock()
a.mu.Lock() a.mu.Lock()
fallback := a.fallbackInputSvc
a.fallbackInputSvc = nil
a.pluginMgr = mgr a.pluginMgr = mgr
a.driverRouter = drvRouter a.driverRouter = drvRouter
a.vmStateTable = stateTable a.vmStateTable = stateTable
a.lifecycleSvc = vmlifecycle.New(mgr.Registry(), drvRouter, a.startHookPayload) a.lifecycleSvc = vmlifecycle.New(mgr.Registry(), drvRouter, a.startHookPayload)
a.runtimeKinds = kindReg a.runtimeKinds = kindReg
a.mu.Unlock() a.mu.Unlock()
if fallback != nil {
fallback.Close()
}
a.keymapMu.Unlock()
fetch.SetDefaultDownloader(a.activeDownloader) fetch.SetDefaultDownloader(a.activeDownloader)
@@ -253,7 +228,6 @@ func (a *App) initPlugins() {
} }
mgr.MarkBootComplete() mgr.MarkBootComplete()
a.syncInputFilters() a.syncInputFilters()
a.syncKeymapRules()
a.syncClipboardPolicies() a.syncClipboardPolicies()
a.syncLocales() a.syncLocales()
a.startPluginControlServer() a.startPluginControlServer()
@@ -402,15 +376,10 @@ func (a *App) getInputService() *host.InputService {
return nil return nil
} }
mgr := a.pluginMgr mgr := a.pluginMgr
if mgr == nil {
if a.fallbackInputSvc == nil {
a.fallbackInputSvc = host.NewInputService(nil)
}
svc := a.fallbackInputSvc
a.mu.Unlock()
return svc
}
a.mu.Unlock() a.mu.Unlock()
if mgr == nil {
return nil
}
raw, ok := mgr.Registry().LookupService(builtin.ServiceHostInput) raw, ok := mgr.Registry().LookupService(builtin.ServiceHostInput)
if !ok { if !ok {
return nil return nil
+13 -24
View File
@@ -17,6 +17,7 @@ import (
"github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/atomicfile"
"github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginproto"
) )
const ( const (
@@ -61,14 +62,11 @@ func (a *App) secretHostHandlers(mgr *plugin.Manager, pluginID string) map[strin
return value, err return value, err
} }
return map[string]plugin.RPCRequestHandler{ return map[string]plugin.RPCRequestHandler{
"host/secret.materialize": a.authorizedComputerUseHandler(mgr, pluginID, "driver:vm", "host/secret.materialize", func(_ context.Context, raw json.RawMessage) (any, error) { "host/secret.materialize": a.hostMethod(mgr, pluginID, "host/secret.materialize", func(_ context.Context, raw json.RawMessage) (any, error) {
if err := broker.Authorize(pluginID, "fs:vm_dir"); err != nil { return a.materializeSecret(mgr, broker, source, pluginID, raw)
return nil, err
}
return a.materializeSecret(broker, source, pluginID, raw)
}), }),
"host/secret.discard": a.authorizedComputerUseHandler(mgr, pluginID, "driver:vm", "host/secret.discard", func(_ context.Context, raw json.RawMessage) (any, error) { "host/secret.discard": a.hostMethod(mgr, pluginID, "host/secret.discard", func(_ context.Context, raw json.RawMessage) (any, error) {
return a.discardSecret(broker, pluginID, raw) return a.discardSecret(mgr, broker, pluginID, raw)
}), }),
} }
} }
@@ -96,15 +94,9 @@ func encodeSecret(secret, format string) (string, error) {
// materializeSecret fills template with a secret setting and writes the // materializeSecret fills template with a secret setting and writes the
// result into the VM's folder. The plugin gets back only the path. // result into the VM's folder. The plugin gets back only the path.
func (a *App) materializeSecret(broker *plugin.Broker, source secretSource, pluginID string, raw json.RawMessage) (any, error) { func (a *App) materializeSecret(kernel hostMethodHost, broker *plugin.Broker, source secretSource, pluginID string, raw json.RawMessage) (any, error) {
var req struct { req, err := decodeHostParams[pluginproto.SecretMaterializeParams](kernel, pluginID, "host/secret.materialize", raw)
Setting string `json:"setting"` if err != nil {
Ref plugin.VMRef `json:"ref"`
Template string `json:"template"`
Dest string `json:"dest"`
Format string `json:"format"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err return nil, err
} }
if strings.TrimSpace(req.Setting) == "" { if strings.TrimSpace(req.Setting) == "" {
@@ -167,7 +159,7 @@ func (a *App) materializeSecret(broker *plugin.Broker, source secretSource, plug
} }
// The audit line names the setting and its size, never the value. // The audit line names the setting and its size, never the value.
broker.Audit(pluginID, "SECRET_MATERIALIZE", fmt.Sprintf("vm=%s setting=%s bytes=%d", vm.Ref().Key(), req.Setting, len(secret))) broker.Audit(pluginID, "SECRET_MATERIALIZE", fmt.Sprintf("vm=%s setting=%s bytes=%d", vm.Ref().Key(), req.Setting, len(secret)))
return map[string]any{"path": dest}, nil return pluginproto.SecretMaterializeResult{Path: dest}, nil
} }
func writeSecretFile(dest string, content []byte) error { func writeSecretFile(dest string, content []byte) error {
@@ -306,12 +298,9 @@ func (a *App) removeMaterialized(match func(materializedSecret) bool) (int, erro
// discardSecret deletes the files a plugin materialized for one VM, or just // discardSecret deletes the files a plugin materialized for one VM, or just
// the one named by path. // the one named by path.
func (a *App) discardSecret(broker *plugin.Broker, pluginID string, raw json.RawMessage) (any, error) { func (a *App) discardSecret(kernel hostMethodHost, broker *plugin.Broker, pluginID string, raw json.RawMessage) (any, error) {
var req struct { req, err := decodeHostParams[pluginproto.SecretDiscardParams](kernel, pluginID, "host/secret.discard", raw)
Ref plugin.VMRef `json:"ref"` if err != nil {
Path string `json:"path"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err return nil, err
} }
driverID, err := broker.ResolveRefDriver(pluginID, req.Ref.DriverID) driverID, err := broker.ResolveRefDriver(pluginID, req.Ref.DriverID)
@@ -330,7 +319,7 @@ func (a *App) discardSecret(broker *plugin.Broker, pluginID string, raw json.Raw
return nil, err return nil, err
} }
broker.Audit(pluginID, "SECRET_DISCARD", fmt.Sprintf("vm=%s files=%d", vmKey, n)) broker.Audit(pluginID, "SECRET_DISCARD", fmt.Sprintf("vm=%s files=%d", vmKey, n))
return map[string]any{"removed": n}, nil return pluginproto.SecretDiscardResult{Removed: n}, nil
} }
// discardMaterializedSecretsForVM deletes every secret file of a VM that is // discardMaterializedSecretsForVM deletes every secret file of a VM that is
+8 -7
View File
@@ -15,6 +15,7 @@ import (
"github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/lifecycle" "github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/testutil/fakedriver" "github.com/Nwflower/reims-go/internal/testutil/fakedriver"
"github.com/Nwflower/reims-go/pkg/pluginproto"
) )
const testSecret = `p@ss<&>w0rd"é` const testSecret = `p@ss<&>w0rd"é`
@@ -70,7 +71,7 @@ func newSecretTestEnv(t *testing.T) *secretTestEnv {
func (e *secretTestEnv) materialize(t *testing.T, pluginID string, req map[string]any) (any, error) { func (e *secretTestEnv) materialize(t *testing.T, pluginID string, req map[string]any) (any, error) {
t.Helper() t.Helper()
raw, _ := json.Marshal(req) raw, _ := json.Marshal(req)
return e.app.materializeSecret(e.h.Broker, e.source, pluginID, raw) return e.app.materializeSecret(nil, e.h.Broker, e.source, pluginID, raw)
} }
func (e *secretTestEnv) request(dest, format string) map[string]any { func (e *secretTestEnv) request(dest, format string) map[string]any {
@@ -85,7 +86,7 @@ func (e *secretTestEnv) request(dest, format string) map[string]any {
func (e *secretTestEnv) read(t *testing.T, res any) string { func (e *secretTestEnv) read(t *testing.T, res any) string {
t.Helper() t.Helper()
path := res.(map[string]any)["path"].(string) path := res.(pluginproto.SecretMaterializeResult).Path
raw, err := os.ReadFile(path) raw, err := os.ReadFile(path)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -102,7 +103,7 @@ func TestMaterializeSecretFormats(t *testing.T) {
if got := e.read(t, res); got != "<Password>"+testSecret+"</Password>" { if got := e.read(t, res); got != "<Password>"+testSecret+"</Password>" {
t.Fatalf("raw = %q", got) t.Fatalf("raw = %q", got)
} }
path := res.(map[string]any)["path"].(string) path := res.(pluginproto.SecretMaterializeResult).Path
if !pathInside(e.vmDir, path) { if !pathInside(e.vmDir, path) {
t.Fatalf("%s is outside the VM folder %s", path, e.vmDir) t.Fatalf("%s is outside the VM folder %s", path, e.vmDir)
} }
@@ -213,15 +214,15 @@ func TestDiscardSecretAndVMDeletionRemoveTheFiles(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
p1, p2 := first.(map[string]any)["path"].(string), second.(map[string]any)["path"].(string) p1, p2 := first.(pluginproto.SecretMaterializeResult).Path, second.(pluginproto.SecretMaterializeResult).Path
discard := func(plugin string, req map[string]any) int { discard := func(plugin string, req map[string]any) int {
raw, _ := json.Marshal(req) raw, _ := json.Marshal(req)
res, err := e.app.discardSecret(e.h.Broker, plugin, raw) res, err := e.app.discardSecret(nil, e.h.Broker, plugin, raw)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
return res.(map[string]any)["removed"].(int) return res.(pluginproto.SecretDiscardResult).Removed
} }
ref := map[string]any{"driver_id": e.ownerDriver.ID(), "name": "dev"} ref := map[string]any{"driver_id": e.ownerDriver.ID(), "name": "dev"}
if n := discard(e.ownerPlugin, map[string]any{"ref": ref, "path": p1}); n != 1 { if n := discard(e.ownerPlugin, map[string]any{"ref": ref, "path": p1}); n != 1 {
@@ -274,7 +275,7 @@ func TestDiscardSecretRetriesAFileItCouldNotDelete(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
path := res.(map[string]any)["path"].(string) path := res.(pluginproto.SecretMaterializeResult).Path
// A non-empty folder in the file's place cannot be removed. // A non-empty folder in the file's place cannot be removed.
if err := os.Remove(path); err != nil { if err := os.Remove(path); err != nil {
t.Fatal(err) t.Fatal(err)
-4
View File
@@ -109,9 +109,6 @@ func (a *App) ResumeVM(driverID, name string) error {
unicodeInput := hasRuntime && active.Manifest.HasCapability("win32-unicode-input") unicodeInput := hasRuntime && active.Manifest.HasCapability("win32-unicode-input")
windowDrop := hasRuntime && active.Manifest.HasCapability("window-file-drop") windowDrop := hasRuntime && active.Manifest.HasCapability("window-file-drop")
extraEnv, newRegistration, newRegGen = a.registerResumeGuestTools(vm, epoch, unicodeInput, windowDrop) extraEnv, newRegistration, newRegGen = a.registerResumeGuestTools(vm, epoch, unicodeInput, windowDrop)
if unicodeInput && len(extraEnv) > 0 {
a.syncKeymapRules()
}
} }
startAt := time.Now() startAt := time.Now()
@@ -199,7 +196,6 @@ func (a *App) registerResumeGuestTools(vm driver.VMInfo, epoch uint64, unicodeIn
} }
var env []string var env []string
if unicodeInput { if unicodeInput {
srv.SetKeymapCarrier(ref.Name, false)
env = append(env, env = append(env,
fmt.Sprintf("REIMS_GO_INPUT_URL=http://127.0.0.1:%d/v1/host-text", port), fmt.Sprintf("REIMS_GO_INPUT_URL=http://127.0.0.1:%d/v1/host-text", port),
"REIMS_GO_INPUT_TOKEN="+cfg.Token, "REIMS_GO_INPUT_TOKEN="+cfg.Token,
+5 -2
View File
@@ -12,6 +12,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"image/png" "image/png"
"log"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -281,8 +282,10 @@ func (a *App) captureThumb(driverID, name, path string) (VMThumbnail, bool) {
if err != nil { if err != nil {
return VMThumbnail{}, false return VMThumbnail{}, false
} }
if err := os.MkdirAll(filepath.Dir(path), 0o755); err == nil { if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
_ = atomicfile.Write(path, jpg, 0o644) log.Printf("[thumb] create cache dir failed (%s): %v", filepath.Dir(path), err)
} else if err := atomicfile.Write(path, jpg, 0o644); err != nil {
log.Printf("[thumb] write cache failed (%s): %v", path, err)
} }
return VMThumbnail{ return VMThumbnail{
DataURL: "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(jpg), DataURL: "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(jpg),
+9 -15
View File
@@ -117,7 +117,15 @@ func (p *vmPoller) tick(ctx context.Context) {
if ib != nil { if ib != nil {
ib.SetTargets(imeTargets(vms)) ib.SetTargets(imeTargets(vms))
} }
a.syncKeymapRules() if svc := a.getInputService(); svc != nil {
var targets []host.IMETarget
for _, vm := range vms {
if pid := vm.RunningPID(); pid > 0 {
targets = append(targets, host.IMETarget{VMName: vm.Name, VMDir: vm.Dir, PID: uint32(pid)})
}
}
svc.SetTargets(targets)
}
a.syncFullscreenHotkeyTargets() a.syncFullscreenHotkeyTargets()
if tm != nil { if tm != nil {
tm.UpdateTooltip(trayTooltip(loc, vms)) tm.UpdateTooltip(trayTooltip(loc, vms))
@@ -410,20 +418,6 @@ func (a *App) polledVMs(ctx context.Context) ([]driver.VMListItem, error) {
return a.listVMsInternal(ctx) return a.listVMsInternal(ctx)
} }
// polledVM looks name up in polledVMs.
func (a *App) polledVM(name string) (driver.VMListItem, bool) {
vms, err := a.polledVMs(context.Background())
if err != nil {
return driver.VMListItem{}, false
}
for _, vm := range vms {
if vm.Name == name {
return vm, true
}
}
return driver.VMListItem{}, false
}
func (a *App) polledVMForDriver(driverID, name string) (driver.VMListItem, bool) { func (a *App) polledVMForDriver(driverID, name string) (driver.VMListItem, bool) {
vms, err := a.polledVMs(context.Background()) vms, err := a.polledVMs(context.Background())
if err != nil { if err != nil {
Loaded 100 of 224 files, more files were not shown because too many files have changed in this diff. Show more