Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f63565ff3a | ||
|
|
8f64bb6016 | ||
|
|
577b2f73ed | ||
|
|
34e6678eb6 | ||
|
|
2e879ab074 | ||
|
|
1f30307178 | ||
|
|
7fd1947bef | ||
|
|
c181cc3c50 | ||
|
|
ee45f40888 | ||
|
|
e0ff794b0e | ||
|
|
7d02b77d7a | ||
|
|
74242c323a | ||
|
|
7f07999a3b | ||
|
|
2caf459647 | ||
|
|
d8c9abc3df | ||
|
|
ea6390e8ca | ||
|
|
44905aaa17 | ||
|
|
92573ce550 | ||
|
|
aac3979373 | ||
|
|
1d15e41482 | ||
|
|
c08ddd7b48 | ||
|
|
9006e6d9a7 |
No files matched your search
@@ -0,0 +1,115 @@
|
||||
name: Windows CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: reims-windows-ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
REIMS_CI_WORKSPACE: D:/RgCI/${{ github.run_id }}-${{ github.run_attempt }}
|
||||
GOCACHE: D:/RgCI/${{ github.run_id }}-${{ github.run_attempt }}/.debug/cache/go-build
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: reims-windows-x64
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Check out the triggering commit
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$PSNativeCommandUseErrorActionPreference = $true
|
||||
if (Test-Path -LiteralPath $env:REIMS_CI_WORKSPACE) { throw 'The CI checkout directory already exists' }
|
||||
New-Item -ItemType Directory -Path $env:REIMS_CI_WORKSPACE -Force | Out-Null
|
||||
Set-Location -LiteralPath $env:REIMS_CI_WORKSPACE
|
||||
git init .
|
||||
git remote add origin "$env:GITHUB_SERVER_URL/$env:GITHUB_REPOSITORY.git"
|
||||
git fetch --depth=1 origin $env:GITHUB_SHA
|
||||
git checkout --detach FETCH_HEAD
|
||||
if ((git rev-parse HEAD) -ne $env:GITHUB_SHA) { throw 'Unexpected checkout commit' }
|
||||
|
||||
- name: Verify installed build tools
|
||||
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$PSNativeCommandUseErrorActionPreference = $true
|
||||
git --version
|
||||
go version
|
||||
node --version
|
||||
pnpm --version
|
||||
|
||||
- name: Verify CHANGELOG.md matches current version
|
||||
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
node scripts/changelog.mjs check
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Changelog validation failed' }
|
||||
$verFile = Get-Content -Raw -LiteralPath 'internal/version/version.go'
|
||||
if ($verFile -notmatch 'var\s+Version\s*=\s*"(v[^"]+)"') {
|
||||
throw 'Could not parse Version from internal/version/version.go'
|
||||
}
|
||||
$ver = $Matches[1]
|
||||
New-Item -ItemType Directory -Force -Path .debug/runs/ci | Out-Null
|
||||
$tmp = Join-Path $PWD ".debug/runs/ci/release-notes-$ver.md"
|
||||
& ./scripts/build-release-notes.ps1 -Tag $ver -OutFile $tmp
|
||||
"REIMS_APP_VERSION=$ver" >> $env:GITHUB_ENV
|
||||
Write-Host "PASS CHANGELOG.md contains valid release notes for $ver ($((Get-Item -LiteralPath $tmp).Length) bytes)"
|
||||
|
||||
- name: Workspace hygiene
|
||||
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
|
||||
shell: pwsh
|
||||
run: node scripts/debug/check.mjs
|
||||
|
||||
- name: Install frontend dependencies
|
||||
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
|
||||
shell: pwsh
|
||||
run: pnpm --dir frontend install --frozen-lockfile
|
||||
|
||||
- name: CI tests
|
||||
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
|
||||
shell: pwsh
|
||||
run: node scripts/test.mjs ci
|
||||
|
||||
- name: Bundle frontend
|
||||
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
|
||||
shell: pwsh
|
||||
run: pnpm --dir frontend bundle
|
||||
|
||||
- name: Build reims-go.exe (window + command-line mode)
|
||||
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
$env:GOTMPDIR = (Resolve-Path .debug/runs/ci).Path
|
||||
$exe = '.debug/runs/ci/reims-go.exe'
|
||||
go vet -tags desktop,production .
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Go desktop vet failed' }
|
||||
go build -trimpath -tags desktop,production -ldflags "-H windowsgui" -o $exe .
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Go desktop build failed' }
|
||||
./scripts/check-release-artifact.ps1 -Executable $exe -Version $env:REIMS_APP_VERSION
|
||||
|
||||
- name: WebView2 first-launch smoke
|
||||
working-directory: ${{ env.REIMS_CI_WORKSPACE }}
|
||||
timeout-minutes: 3
|
||||
run: node scripts/test.mjs webview2 .debug/runs/ci/reims-go.exe
|
||||
|
||||
- name: Remove the CI checkout
|
||||
if: always()
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (!(Test-Path -LiteralPath $env:REIMS_CI_WORKSPACE)) { return }
|
||||
$checkout = Get-Item -LiteralPath $env:REIMS_CI_WORKSPACE
|
||||
$parent = Get-Item -LiteralPath 'D:/RgCI'
|
||||
if ($checkout.Parent.FullName -ne $parent.FullName -or
|
||||
$checkout.Name -notmatch '^[0-9]+-[0-9]+$' -or
|
||||
($checkout.Attributes -band [IO.FileAttributes]::ReparsePoint) -or
|
||||
($parent.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
|
||||
throw 'Refusing to remove an unexpected CI checkout path'
|
||||
}
|
||||
Remove-Item -LiteralPath $checkout.FullName -Recurse -Force
|
||||
@@ -21,4 +21,4 @@
|
||||
- [ ] 改动归属清晰,跨仓实现已按职责拆分并附上游源码或提交依据
|
||||
- [ ] 涉及默认值、配置迁移或插件行为时,已附上[已有用户升级兼容性](https://github.com/Nwflower/Reims-Go/blob/main/docs/pr-review-guidelines.md#已有用户升级兼容性)验证记录
|
||||
- [ ] `node scripts/debug/check.mjs`、`node scripts/changelog.mjs check` 与 `node scripts/test.mjs ci` 通过
|
||||
- [ ] 面向用户或集成方的变化已写入 `changes/<slug>.json`(纯内部重构无需添加)
|
||||
- [ ] 面向用户或集成方的变化已写入 `.github/changes/<slug>.json`(纯内部重构无需添加)
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "new",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "Apple 芯片 Mac 的实验性源码构建新增原生 macOS 虚拟机后端,可用本地 `.ipsw` 创建虚拟机并在独立窗口启动和关机。",
|
||||
"en": "The experimental Apple silicon source build can create macOS VMs from local `.ipsw` restores, start them with a separate viewer, and shut them down."
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "new",
|
||||
"order": 0,
|
||||
"authors": ["icaruszezen"],
|
||||
"zh": "新增默认启用的官方内置「macOS 自动装机助手」插件(`builtin.macos.autoinstall`)、AI 受控会话可视化、键鼠接管与画面防误触锁定、受保护阶段确认机制、macOS 离线首启预配置(跳过设置助理)以及自动装机宿主扩展能力。内置自动装机插件采用纯本地 Windows OCR(支持按需下载或离线校验导入 RapidOCR ONNX 备选模型)与声明式规则推进恢复终端安装、跨重启等待、退出恢复并重启与设置助理,截屏与密码均不离开本机,且可在「插件」页随时停用并立即结束会话、零残留隐藏入口。虚拟机处于安装或恢复阶段时,自动化截图与键鼠输入均需经主窗口弹窗授权(支持 10/30/60 分钟或直到离开阶段,仅存内存);拒绝授权或插件权限不足导致自动化脚本未运行时,自动中止会话、清理临时凭证并兜底展示原版手动安装引导;操作期间在侧栏、详情页、系统托盘与虚拟机窗口浮层显示受控状态并提供暂停与停止按钮,支持物理键鼠接管暂停(可在设置页调整恢复时长)与防误触输入锁定模式。内置 macOS 离线安装新增按虚拟机隔离的只读预配置卷(新建向导与 `vm provision` 命令行均可选启用,与自动恢复安装独立开关、无插件亦可独立使用),仅在内存中派生加盐 PBKDF2 密码哈希(不落盘明文、不启自动登录),经原生 OpenDirectory 接口或离线目录属性表创建管理员、跳过设置助理与键盘设置助理并按需预装 Guest Tools,退出恢复模式或删机时自动覆零清理。插件契约升级为 `pluginApi 1.3.0` 和 `uiApi 2.2.0`,新增 `contributes.autoInstallers` 通用自动装机扩展点、`vm autoinstall` 命令行、归一化区域无损 PNG 截图、`host/vm.finishInstall`、`host/vm.restart`、`host/vm.telemetry`、`host/ui.confirm`、`host/session.*`、`vm/phaseChanged` 以及 `host/download.start` 超时与自定义镜像二次确认([#103](https://github.com/Nwflower/Reims-Go/issues/103)、[#105](https://github.com/Nwflower/Reims-Go/issues/105)、[#129](https://github.com/Nwflower/Reims-Go/issues/129))。",
|
||||
"en": "Add the default-enabled official built-in macOS Auto-Install Assistant plugin (`builtin.macos.autoinstall`), AI remote-control session visibility, physical input takeover and optional VM input lock, protected-phase confirmation, offline macOS first-boot provisioning (Setup Assistant skip), and generic auto-installer host foundations. The built-in auto-install plugin drives Recovery terminal installation, cross-reboot monitoring, exit recovery and restart, and Setup Assistant purely locally via Windows OCR (with optional user-confirmed RapidOCR ONNX fallback or SHA-256-verified offline bundle import) and declarative rules without sending screenshots or secrets off-device, and can be disabled in Plugins with immediate session teardown and zero UI residue. While a VM is in the installer or recovery phase, automated screenshots and input require an in-memory host confirmation grant (10/30/60 minutes or until phase exit); denying confirmation or plugin permissions when automation scripts cannot run aborts the session, wipes temporary credentials, and falls back to showing the original manual installation guide; active sessions appear in the sidebar, VM page, system tray, and a Win32 VM-window overlay with Pause and Stop controls, supporting physical takeover pause (with a configurable resume delay in Settings) and input-locked client shielding. Built-in offline macOS installation adds an opt-in per-VM read-only provisioning disk (independent of recovery auto-install in the Create Wizard and `vm provision` CLI, usable without plugins) that hashes passwords in memory via salted PBKDF2 (never writing plaintext passwords or auto-login), creates the local admin through native OpenDirectory or offline dslocal plists, skips Setup Assistant and Keyboard Setup Assistant, stages Guest Tools, and securely wipes the image on finish_install or VM deletion. The contracts move to `pluginApi 1.3.0` and `uiApi 2.2.0`, adding the generic `contributes.autoInstallers` extension point, `vm autoinstall` CLI subcommands, normalized-region PNG screenshots, `host/vm.finishInstall`, `host/vm.restart`, `host/vm.telemetry`, `host/ui.confirm`, `host/session.*`, `vm/phaseChanged`, and `host/download.start` connect/stall timeouts plus SHA-256-pinned custom mirror confirmation ([#103](https://github.com/Nwflower/Reims-Go/issues/103), [#105](https://github.com/Nwflower/Reims-Go/issues/105), [#129](https://github.com/Nwflower/Reims-Go/issues/129))."
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "improvements",
|
||||
"order": 0,
|
||||
"authors": ["reiasu2"],
|
||||
"zh": "日志栏新增「导出排障包」入口,导出后弹出引导窗口展示自动检查结论与环境摘要,支持一键复制 `.zip` 压缩包文件或打开位置;框选多行「活动」日志时自动合并为单行格式,复制大段日志前提示导出排障包避免刷屏。",
|
||||
"en": "Add an Export diagnostics button to the log bar and open a guidance dialog after export with automatic checks, an environment summary, Show in folder, and one-click `.zip` file copy; normalize multi-line Activity log selections into single lines and prompt before copying long log output."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "Apple 芯片 Mac 的恢复镜像目录查询支持重试与 Apple 官方来源回退,原生红黄绿按钮与标题栏菜单纵向对齐。",
|
||||
"en": "Retry Apple silicon restore catalog queries with an official Apple fallback, and vertically align the native window controls with the title bar menus."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "修复 macOS 上的开发构建,并防止关闭窗口时把应用隐藏到不存在的托盘。内置虚拟机运行时仍仅支持 Windows x64。",
|
||||
"en": "Fix development builds on macOS and prevent the window from hiding to an unavailable tray. The built-in VM runtime still requires Windows x64."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "new",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "Apple 芯片 Mac 可在镜像页或新建向导内从 Apple 下载兼容恢复镜像,支持暂停续传,并使用系统原生的红黄绿窗口按钮。",
|
||||
"en": "Download a compatible Apple restore image with pause and resume in Images or New VM on Apple silicon, and use the native macOS window controls."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "Mac 客户端使用系统采样显示宿主机内存,不再误报内存满载,并修复无法显示的插件 SVG 图标。",
|
||||
"en": "Show sampled host memory on macOS instead of reporting full memory use, and fix plugin SVG icons that failed to render."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "macOS 的应用、编辑和窗口菜单跟随当前界面语言,应用菜单统一显示 Reims-Go。",
|
||||
"en": "Match the macOS application, Edit, and Window menus to the selected interface language and show Reims-Go as the application name."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "improvements",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "macOS 的「虚拟机」「视图」和「帮助」移至屏幕顶部的系统菜单栏,Windows 保留窗口内菜单。",
|
||||
"en": "Move VM, View, and Help to the macOS system menu bar and keep them in the app window on Windows."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "在 macOS 上使用本机 QQ 打开交流群邀请;不能直接打开时仍可打开邀请页。虚拟机的 SSH 入口也可在 Mac 的终端中打开。",
|
||||
"en": "Open QQ group invites with the installed QQ app on macOS, with the invite page as a fallback. Open VM SSH sessions in the Mac terminal."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "macOS 恢复镜像校验暂时失败后可继续重试,启动虚拟机时会等待读取状态,宿主机诊断会同时显示原生虚拟化和常规诊断信息。",
|
||||
"en": "Retry temporary macOS restore image verification failures without redownloading, tolerate transient VM startup status errors, and show native virtualization alongside standard host diagnostics."
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "improvements",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "Apple 芯片 Mac 的实验版改用独立的 Nivfold 运行器,支持安全取消安装,并在保存时检查宿主和客体的 CPU 与内存要求。",
|
||||
"en": "The experimental Apple silicon build uses the standalone Nivfold runner, supports cooperative installation cancellation, and checks host and guest CPU and memory requirements before saving settings."
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["yxc0915"],
|
||||
"zh": "修复 ARM macOS 虚拟机在桌面或登录窗口从客户端请求正常关机时可能超时的问题。",
|
||||
"en": "Fix graceful shutdown of ARM macOS VMs from the desktop or login window."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "new",
|
||||
"order": 0,
|
||||
"authors": ["yxc0915"],
|
||||
"zh": "支持在 Windows x86-64 上使用 Stambha 实验运行时启动 ARM macOS。导入配套运行时后,可从已有的启动介质和虚拟磁盘创建虚拟机。",
|
||||
"en": "Run ARM macOS on Windows x86-64 with the Stambha preview runtime. Import the matching runtime to create a VM from existing boot media and a virtual disk."
|
||||
}
|
||||
@@ -10,6 +10,8 @@ Reims-Go 是面向 Windows x86-64 的免编译 macOS 虚拟机桌面启动器与
|
||||
|
||||
Reims-Go 发布的便携运行时基于团队独立维护的 `reims-go/reims-vgpu` 和 `reims-go/qemu-reims-vgpu` 构建。运行时维护仓库通过 `vendor/qemu` 固定团队 QEMU 仓库的提交,并负责编译、依赖补丁、打包和预览发布。 [运行时维护仓库](https://github.com/reims-go/reims-vgpu) · [QEMU 维护仓库](https://github.com/reims-go/qemu-reims-vgpu) · [运行时构建流程](https://github.com/reims-go/reims-vgpu/blob/master/.github/workflows/runtime-preview.yml)
|
||||
|
||||
Apple 芯片 Mac 的实验性后端使用独立 `nivfold` 仓库中的原生运行器。虚拟设备、安装事务和运行器测试归 Nivfold;此仓库只维护客户端及兼容协议适配。
|
||||
|
||||
## 存储与调试目录纪律
|
||||
|
||||
1. 便携运行时、系统镜像、虚拟磁盘与快照只保存在用户本地指定的数据目录,不提交到仓库,也不放入 `.debug/`。
|
||||
@@ -48,7 +50,7 @@ Reims-Go 发布的便携运行时基于团队独立维护的 `reims-go/reims-vgp
|
||||
|
||||
## 版本变更与开源合规
|
||||
|
||||
面向用户或集成方的变化随改动写入 `changes/<slug>.json`,准备正式版时编入 [`CHANGELOG.md`](CHANGELOG.md),格式与命令见 [`docs/changelog.md`](docs/changelog.md)。
|
||||
面向用户或集成方的变化随改动写入 `.github/changes/<slug>.json`,准备正式版时编入 [`CHANGELOG.md`](CHANGELOG.md),格式与命令见 [`docs/changelog.md`](docs/changelog.md)。
|
||||
|
||||
Reims-Go 自身代码采用 [Apache-2.0](LICENSE) 协议。便携运行时以独立子进程和独立压缩包形式集成,公开运行时发布必须同处附带对应源码包、本地补丁与完整许可证文本(见 [`NOTICE.md`](NOTICE.md))。应用不打包也不托管任何 Apple 系统文件。
|
||||
|
||||
|
||||
@@ -108,6 +108,21 @@ authorization of the copyright holder.
|
||||
|
||||
SPDX-License-Identifier: Unicode-3.0
|
||||
|
||||
## Optional local OCR fallback (built-in macOS Auto-Install Assistant)
|
||||
|
||||
When the Windows host lacks the required `Windows.Media.Ocr` language pack and
|
||||
the user explicitly confirms fallback download or imports an offline archive
|
||||
verified by SHA-256, the built-in macOS Auto-Install Assistant plugin may store
|
||||
the following open-source components under its private plugin data directory
|
||||
(`plugins/data/builtin.macos.autoinstall/ocr/`):
|
||||
|
||||
1. **RapidOCR / RapidOcrOnnx** (<https://github.com/RapidAI/RapidOcrOnnx>, <https://github.com/RapidAI/RapidOCR>) is licensed under the Apache License, Version 2.0.
|
||||
2. **PP-OCRv4 mobile models** (PaddleOCR / RapidOCR ONNX weights) are licensed under the Apache License, Version 2.0.
|
||||
3. **ONNX Runtime** (<https://github.com/microsoft/onnxruntime>) is licensed under the MIT License.
|
||||
|
||||
Reims-Go never bundles, downloads, or redistributes undocumented Windows OCR
|
||||
libraries (`oneocr.dll`).
|
||||
|
||||
## Portable runtime
|
||||
|
||||
The portable runtime bundle (`reims-runtime-win-x64-<commit>.tar.zst`) contains
|
||||
|
||||
@@ -123,6 +123,26 @@ reims-go vm start macos-tahoe | Out-Host # Start the VM
|
||||
|
||||
With Go 1.26+, Node.js 22, pnpm 10 and the [Wails CLI](https://wails.io/docs/gettingstarted/installation) v2.17.1, run `wails build` in the repository root; the binary is written to `build\bin\reims-go.exe`. The runtime is built separately by the [Reims vGPU fork](https://github.com/reims-go/reims-vgpu).
|
||||
|
||||
On Apple silicon, the experimental client uses the standalone Nivfold runner instead of the Windows QEMU runtime. Run `sh build.sh` in a separate `nivfold` checkout first. Building the runner requires Xcode with Swift 6, and running it requires macOS 13 or later. The example assumes sibling checkouts; omit `--runtime` to build only the client.
|
||||
|
||||
```sh
|
||||
node scripts/build-macos.mjs --runtime ../nivfold/.debug/runs/nivfold/nivfold
|
||||
.debug/runs/macos-client/reims-go doctor
|
||||
.debug/runs/macos-client/reims-go
|
||||
```
|
||||
|
||||
In New VM, download the compatible macOS restore image offered by Apple for the current host, or choose an existing local `.ipsw`. The Images page can also download and manage cached images. Transfer only starts when you click Download, and downloaded images can be reused. Creation installs macOS onto a new virtual disk. When it finishes, start the VM and complete Setup Assistant manually in the separate guest window. CLI creation takes the absolute path to a local restore image:
|
||||
|
||||
```sh
|
||||
client=.debug/runs/macos-client/reims-go
|
||||
"$client" vm create --ipsw /absolute/path/to/Restore.ipsw mac-test
|
||||
"$client" vm list
|
||||
"$client" vm start mac-test
|
||||
"$client" vm stop mac-test
|
||||
```
|
||||
|
||||
The native backend cannot open Windows x86-64 VMs or their snapshots. This experimental build does not support snapshots, suspend, restore points, shared folders, or Reims vGPU.
|
||||
|
||||
</details>
|
||||
|
||||
## FAQ
|
||||
|
||||
@@ -119,6 +119,26 @@ reims-go vm start macos-tahoe | Out-Host # 启动虚拟机
|
||||
|
||||
需要 Go 1.26+、Node.js 22、pnpm 10 和 [Wails CLI](https://wails.io/docs/gettingstarted/installation) v2.17.1,在仓库根目录运行 `wails build`,产物在 `build\bin\reims-go.exe`。运行时由 [Reims vGPU fork](https://github.com/reims-go/reims-vgpu) 单独构建。
|
||||
|
||||
Apple 芯片 Mac 的实验版使用独立的 Nivfold 运行器,不安装 Windows 的 QEMU 运行时。先在单独检出的 `nivfold` 仓库运行 `sh build.sh`。运行器构建需要带 Swift 6 的 Xcode,运行需要 macOS 13 或更高版本。下例假设两个仓库位于同一个父目录;只构建客户端时可省略 `--runtime`。
|
||||
|
||||
```sh
|
||||
node scripts/build-macos.mjs --runtime ../nivfold/.debug/runs/nivfold/nivfold
|
||||
.debug/runs/macos-client/reims-go doctor
|
||||
.debug/runs/macos-client/reims-go
|
||||
```
|
||||
|
||||
在「新建虚拟机」中下载 Apple 为当前宿主提供的兼容恢复镜像,或选择已有的本地 `.ipsw`。「镜像」页也可下载和管理缓存。应用只在你点击下载后传输镜像,下载好的镜像可重复使用。创建会把系统安装到新虚拟磁盘;完成后点击「启动」,在独立窗口里手动完成客体的设置助理。命令行创建使用本地镜像的绝对路径:
|
||||
|
||||
```sh
|
||||
client=.debug/runs/macos-client/reims-go
|
||||
"$client" vm create --ipsw /absolute/path/to/Restore.ipsw mac-test
|
||||
"$client" vm list
|
||||
"$client" vm start mac-test
|
||||
"$client" vm stop mac-test
|
||||
```
|
||||
|
||||
Windows 上创建的 x86-64 虚拟机和快照不能在原生后端打开。实验版暂不支持快照、挂起、恢复点、共享文件夹或 Reims vGPU。
|
||||
|
||||
</details>
|
||||
|
||||
## 常见问题
|
||||
|
||||
File renamed without changes.
|
Before Width: | Height: | Size: 35 KiB After Width: | Height: | Size: 35 KiB |
File renamed without changes.
|
Before Width: | Height: | Size: 3.2 KiB After Width: | Height: | Size: 3.2 KiB |
@@ -1,6 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package main
|
||||
|
||||
// attachConsole is only needed for Windows GUI-subsystem builds.
|
||||
func attachConsole() {}
|
||||
+16
-4
@@ -1,6 +1,6 @@
|
||||
# 系统架构
|
||||
|
||||
桌面窗口与命令行共用同一份 Go 核心,面向 64 位 Windows 10 与 Windows 11。客户端只负责环境体检、资产下载、配置校验、生命周期编排与宿客协作,底层虚拟化与图形转换以受控子进程方式调用便携运行时完成。
|
||||
桌面窗口与命令行共用同一份 Go 核心。Windows x64 使用 Reims vGPU 与 QEMU 运行时。Apple 芯片 Mac 可使用实验性原生驱动,通过独立运行器调用系统的虚拟化框架。客户端负责环境体检、配置校验与虚拟机生命周期编排。
|
||||
|
||||
## 总体分层
|
||||
|
||||
@@ -33,7 +33,7 @@ flowchart TB
|
||||
Ctl --> QEMU
|
||||
```
|
||||
|
||||
非 Windows 平台通过构建标签隔离系统原生调用并提供桩实现,保证全平台均可编译和运行单元测试。多语言词表在编译期同时生成前后端字典,默认跟随系统语言并支持通过声明式语言包扩展。
|
||||
构建标签隔离系统原生调用,不支持的能力由对应平台拒绝。上图展示 Windows 的 Reims vGPU 路径。多语言词表在编译期同时生成前后端字典,默认跟随系统语言并支持通过声明式语言包扩展。
|
||||
|
||||
## 核心机制与安全边界
|
||||
|
||||
@@ -49,7 +49,7 @@ flowchart TB
|
||||
|
||||
便携运行时为每台运行中的虚拟机创建本地 Unix 域 QMP 套接字。宿主通过统一控制台路由串行处理每台虚拟机的截图、鼠标、键盘和文本输入,按驱动声明与虚拟机能力分派至内置虚拟机交互服务的 QMP 代理(每次操作后关闭连接,与生命周期操作共用同一把虚拟机锁)或驱动自带的控制台接口;缩略图、截屏、打字与代理控制共用该路由,桌面文本输入期间暂停后台缩略图捕获。
|
||||
|
||||
L3 插件经权限核验的 Host API 请求虚拟机状态、截图和输入操作,宿主不接受插件提供的 QMP 套接字或虚拟机目录。MCP 客户端通过 `reims-go plugin connect <plugin-id> <channel>` 与桌面进程通信;Windows 命名管道按可执行文件路径和用户 SID 摘要区分,ACL 限制当前用户并拒绝远程客户端。
|
||||
L3 插件经权限核验的 Host API 请求虚拟机状态、截图和输入操作,宿主不接受插件提供的 QMP 套接字或虚拟机目录。虚拟机处于安装或恢复阶段时,外部插件的截图与键鼠输入必须先经主窗口弹窗确认,授权仅保留在内存中并在离开阶段、停机或点击停止后立即失效。外部插件操作期间,宿主通过独立的 Win32 虚拟机窗口浮层、详情页、侧栏和系统托盘展示受控状态并提供立即停止按钮,同时在虚拟机窗口内挂接物理键鼠监听,用户在窗口内操作键鼠时自动接管并暂停外部输入;受控会话激活期间自动抑制静态人工安装引导浮层。官方 macOS 自动装机助手以默认启用的内置插件接入同一套 `contributes.autoInstallers` 扩展点与宿主权限管道,连接新建向导、详情页与 `vm autoinstall` 命令行,停用后不展示任何入口且不阻碍第三方自动装机插件并存。MCP 客户端通过 `reims-go plugin connect <plugin-id> <channel>` 与桌面进程通信;Windows 命名管道按可执行文件路径和用户 SID 摘要区分,ACL 限制当前用户并拒绝远程客户端。
|
||||
|
||||
Windows 10 缺少虚拟化分区热重置能力,客体内部重启会导致虚拟化后端异常退出。在 Windows 10 宿主机上,客户端为虚拟机附加不自动重启标志,并额外挂载一条独立的本地 Unix 域控制套接字监听重启退出事件,进程干净退出后自动重新拉起。QMP 和插件控制通道均不使用 TCP 端口,防止虚拟机经用户态网络反向访问宿主机控制面。
|
||||
|
||||
@@ -57,6 +57,8 @@ Windows 10 缺少虚拟化分区热重置能力,客体内部重启会导致虚
|
||||
|
||||
宿客协作服务仅监听本机回环地址 `127.0.0.1`,为每台虚拟机分配独立的 256 位随机访问令牌,所有连接状态、剪贴板策略与文件路由均按驱动和实例隔离。
|
||||
|
||||
macOS 离线安装支持通过新建向导或 `reims-go vm provision` 按虚拟机生成只读首启预配置卷(`REIMSPROV`)。密码仅在内存中派生为加盐 SHA-512 PBKDF2 二进制属性表哈希,不向磁盘、配置或日志写入明文密码,且不写入自动登录凭据或免密 `sudo`。恢复辅助脚本检测到该卷时优先以 `startosinstall --installpackage` 注入自包含安装包,若安装器不支持则自动回退到标准安装并输出降级标记;预配置脚本在活体首启阶段经原生 OpenDirectory 接口(离线恢复阶段经本地目录属性表)创建本地管理员、跳过设置助理与键盘设置助理并按需预装 Guest Tools。退出恢复模式、非安装态冷启动与删除虚拟机均会剥离该盘参数并先覆零再删除镜像。
|
||||
|
||||
共享文件夹服务对每次读写强制约束在授权根目录之内,拦截目录穿越与越界符号链接。Windows 盘符只读共享默认全部关闭;启用后同时限制只读打开标志与写请求方法、核对持久化卷标识防止盘符漂移、限制目录遍历深度,并验证目录联接与符号链接目标仍位于已授权盘符内。
|
||||
|
||||
### 物理出口桥接
|
||||
@@ -85,7 +87,7 @@ Npcap 桥接由可停用的内置扩展提供,通过逐台虚拟机的本地 U
|
||||
|
||||
### 托管型与进程型客体驱动
|
||||
|
||||
客体驱动按虚拟机进程的归属分为两类。进程型驱动让宿主拉起虚拟机进程,宿主据此判断运行状态、定位显示窗口并绑定处理器核心。托管型驱动在声明中带有 `hosted` 能力,虚拟机由驱动自己的管理层运行,宿主不探测其进程与窗口,也不提供全屏和绑核入口;仅当驱动同时声明控制台能力时才开放截屏与键入。
|
||||
客体驱动按虚拟机进程的归属分为两类。进程型驱动让宿主拉起虚拟机进程,宿主据此判断运行状态、定位显示窗口并绑定处理器核心。托管型驱动在声明中带有 `hosted` 能力,虚拟机由驱动自己的管理层运行。宿主不探测托管型驱动的进程与窗口。声明查看窗口能力的驱动可自行唤出查看器。宿主不提供全屏和绑核入口;仅当驱动同时声明控制台能力时才开放截屏与键入。
|
||||
|
||||
托管型驱动通过宿主接口主动推送虚拟机的生命周期状态、就绪状态、所处阶段与客体系统信息。电源状态仍只取 `stopped`、`starting`、`running`、`stopping`、`suspended`、`broken` 与 `driver_unavailable`,就绪与阶段是独立字段,因此仍在启动中的客体显示为运行中但未就绪。推送缺失或过期时,宿主回退为向驱动查询。推送只对驱动自己名下的虚拟机生效。
|
||||
|
||||
@@ -111,6 +113,16 @@ macOS 专属逻辑集中在 `internal/macos/` 与 `frontend/src/macos/`,宿主
|
||||
|
||||
测试同时拒绝没有调用者的函数、前端导出、样式类与文案,拒绝前端模块循环引用,并限制单个 Go 函数的长度。
|
||||
|
||||
## Apple 芯片 Mac 原生后端
|
||||
|
||||
原生驱动只在 Darwin ARM64 上注册。独立 Nivfold 仓库维护运行器、签名和底层测试。Reims-Go 不包含它的源码,不在客户端构建中编译或下载运行器。客户端在自身可执行文件旁查找 Nivfold,不搜索工作目录或系统路径,并检查运行器标识和协议。开发构建可显式传入兼容的签名二进制。
|
||||
|
||||
Nivfold 按虚拟机独立启动。它使用本地恢复镜像安装系统,并一次发布虚拟硬件身份、辅助存储、磁盘和客体资源下限。只有完整安装的磁盘才可启动。旧版磁盘没有客体资源下限记录,保留兼容读取。原生磁盘与 Windows 的虚拟机、快照和挂起状态互不兼容。
|
||||
|
||||
运行器持有逐虚拟机的系统文件锁。管理命令使用当前用户限定的本地 Unix 套接字,不通过 PID 发送关机信号,也不开放 TCP 控制端口。虚拟机由运行器持有,独立于客户端窗口。系统启动后由用户在虚拟机窗口中完成客体设置。
|
||||
|
||||
Mac 与 Windows 共用镜像页和下载任务。Mac 通过 Nivfold 查询 Apple 为当前宿主提供的最新兼容恢复镜像。框架目录重试失败时,Nivfold 使用 Apple 设备目录中同时提供给当前 Mac 型号和虚拟 Mac 的恢复镜像。客户端只在用户触发后从 Apple 的 HTTPS 源下载。客户端根据强 ETag 续传,校验可用的官方摘要,并在框架确认镜像版本和兼容性后发布缓存。旧运行器或网络不可用时仍可选择本地镜像。
|
||||
|
||||
## 便携运行时与跨仓边界
|
||||
|
||||
便携运行时基于团队独立维护的 `reims-go/reims-vgpu` 和 `reims-go/qemu-reims-vgpu` 构建。运行时仓库固定 QEMU 子模块的提交,负责构建、依赖补丁、打包与 Alpha 发布。压缩包包含 `reims-ctl.exe`、`reims-util.exe`、QEMU、自包含运行库、实际应用的补丁和许可证全文。`manifest.json` 记录各组件的实际源码提交及补丁,调试符号单独打包分发。 [运行时维护仓库](https://github.com/reims-go/reims-vgpu) · [QEMU 维护仓库](https://github.com/reims-go/qemu-reims-vgpu)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# 运行 ARM macOS 实验版
|
||||
|
||||
ARM 实验运行时通过 QEMU/WHPX 和 Stambha 在 Windows x86-64 上运行 ARM macOS。使用同一预览配套的 Reims-Go 客户端和 `stambha-hosted` 运行时包。运行时可以和现有 Intel macOS 运行时共存。
|
||||
|
||||
## 准备
|
||||
|
||||
- Windows x86-64 主机,启用 Windows 虚拟机监控程序平台(WHPX),安装支持 Vulkan 的显卡驱动。
|
||||
- 一套你自己的 Stambha 启动介质和与之匹配的 ARM macOS 虚拟磁盘。启动目录至少包含 `EFI/stela/stela.cfg`,其中的磁盘分区标识须与虚拟磁盘一致。从目录启动时,客户端在 VM 的独立引导目录中放入运行时自带的 Stambha EFI。
|
||||
- 为每台运行中的虚拟机准备独立可写副本或 QCOW2 写入层。来宾写入保存在该磁盘文件中。运行时包内提供启动程序、固件和显卡组件,系统文件由用户自行准备。
|
||||
|
||||
macOS 27.2.1 的实验配置使用 8 个 vCPU 和 16 GiB 内存。首次登录后,系统索引和缓存初始化会影响交互速度。
|
||||
|
||||
## 启动
|
||||
|
||||
在运行时页面导入 ARM64 预览包。它以 `stambha-hosted` 类型单独安装。Intel 虚拟机继续绑定选中的 x86-64 运行时,ARM 虚拟机自动使用已安装且兼容的 ARM64 运行时。
|
||||
|
||||
新建虚拟机时选择「macOS ARM64(预览)」。可从 Apple 下载 macOS 27.2.1 恢复镜像,下载支持暂停和续传,文件保存到数据目录的 `images/arm64`,完成后核对 SHA-256。本预览需要先将 IPSW 制作成 Stambha 启动介质。填写准备好的启动目录及对应的可写磁盘路径后即可创建和启动。GPU 加速窗口由运行时打开。
|
||||
|
||||
也可在 PowerShell 中操作。将示例路径替换成自己的文件位置。
|
||||
|
||||
```powershell
|
||||
.\reims-go.exe runtime install .\reims-stambha-runtime-win-x64-stambha-arm64-preview.2.tar.zst
|
||||
.\reims-go.exe vm create --driver builtin.driver.stambha --boot-volume .\arm-boot --disk .\arm-system.qcow2 --cpus 8 --memory 16G arm-macos
|
||||
.\reims-go.exe vm start --driver builtin.driver.stambha arm-macos
|
||||
.\reims-go.exe vm stop --driver builtin.driver.stambha arm-macos
|
||||
```
|
||||
|
||||
如果配置使用原始安装介质,可以用 `--usb-image` 指定文件。原始介质须预先包含与托管 Reims vGPU 相容的 Stambha EFI。首次从 IPSW 制作 ARM 安装介质仍是独立流程。
|
||||
|
||||
客户端的「关机」会请求 macOS 正常退出。在桌面上,macOS 可以提示保存工作。在登录窗口,客户端通过 Windows OCR 识别电源菜单中的「关机」,目前支持英语、简体中文和繁体中文菜单。若提示无法识别,请在虚拟机中手动选择「关机」。只在来宾无响应时使用强制停止。
|
||||
+2
-2
@@ -1,10 +1,10 @@
|
||||
# 更新日志编写与发布
|
||||
|
||||
[`CHANGELOG.md`](../CHANGELOG.md) 保存已编入版本的客户端变更,也是 GitHub Release 说明的正文来源。待发布的条目随改动提交到仓库根目录的 `changes/`。便携运行时 `runtime-*` 在对应的运行时 Release 中记录。客户端条目只在需要时写明它依赖的运行时版本。
|
||||
[`CHANGELOG.md`](../CHANGELOG.md) 保存已编入版本的客户端变更,也是 GitHub Release 说明的正文来源。待发布的条目随改动提交到 `.github/changes/`。便携运行时 `runtime-*` 在对应的运行时 Release 中记录。客户端条目只在需要时写明它依赖的运行时版本。
|
||||
|
||||
## 写入待发布条目
|
||||
|
||||
每项值得告知用户或集成方的变化写一个 `changes/<slug>.json`,文件名用小写英文和连字符。将同一行为涉及的多个提交合为一条。内部重构、纯格式调整和日常依赖更新留在提交记录中。
|
||||
每项值得告知用户或集成方的变化写一个 `.github/changes/<slug>.json`,文件名用小写英文和连字符。将同一行为涉及的多个提交合为一条。内部重构、纯格式调整和日常依赖更新留在提交记录中。
|
||||
|
||||
```json
|
||||
{
|
||||
|
||||
@@ -35,7 +35,7 @@
|
||||
|
||||
## 布局层级与视觉基线
|
||||
|
||||
窗口由左侧可折叠侧栏(`Ctrl+B`)、右侧主内容区、底部常驻状态栏与可收起日志抽屉(`Ctrl+L`)组成。侧栏上方列出虚拟机实例与新建入口(`Ctrl+N`),下方固定提供「镜像」「插件」「内核」「设置」(`Ctrl+,`)与「关于」入口。虚拟机操作按钮固定在详情页头而非全局标题栏,避免切换页面时顶栏跳动。
|
||||
窗口由左侧可折叠侧栏(`Ctrl+B`)、右侧主内容区、底部常驻状态栏与可收起日志抽屉(`Ctrl+L`)组成。侧栏上方列出虚拟机实例与新建入口(`Ctrl+N`),下方固定提供「镜像」「插件」「内核」「设置」(`Ctrl+,`)与「关于」入口。虚拟机操作按钮固定在详情页头而非全局标题栏,避免切换页面时顶栏跳动。macOS 在系统菜单栏提供「虚拟机」「视图」和「帮助」菜单,应用及标准菜单均跟随界面语言,使用 `Command` 组合键;`Command+,` 打开应用设置,原有 `Ctrl` 快捷键仍可在窗口中使用。Windows 在窗口标题栏提供这三项菜单。
|
||||
|
||||
- 同一项硬件规格或运行状态在同一视图内只展示一次,相同动作不在同屏提供两个按钮出口。
|
||||
- 页面只用单层分组容器或留白表达层级,禁止卡片嵌套卡片;下拉选择统一使用自绘弹出控件,不混用系统原生表单控件。
|
||||
|
||||
@@ -20,7 +20,7 @@ flowchart TB
|
||||
|
||||
| 层级 | 运行形态 | 隔离与约束边界 |
|
||||
| :--- | :--- | :--- |
|
||||
| 编译期内置扩展 | 随主程序编译的模块,经同一注册表装载 | 核心默认主题始终启用;macOS 客体支持、宿客传输、剪贴板互通、输入服务、虚拟机交互与并行下载器可独立启停且停用零残留 |
|
||||
| 编译期内置扩展 | 随主程序编译的模块,经同一注册表装载 | 核心默认主题始终启用;macOS 客体支持、macOS 镜像源、macOS 自动装机助手、宿客传输、剪贴板互通、输入服务、虚拟机交互与并行下载器可独立启停且停用零残留 |
|
||||
| L1 声明式插件 | 纯 JSON 配置、词表、字体与静态样式资源 | 不含可执行代码,全部字段经宿主白名单与静态扫描校验 |
|
||||
| 运行时包 | 原生虚拟化与工具二进制归档 | 自身不注册插件代码,仅由客体驱动以受控子进程调用 |
|
||||
| L3 外部进程插件 | 每插件独立子进程,采用 `Content-Length` 分帧的双向 JSON-RPC 2.0 通信(日志走标准错误流) | 崩溃或死循环不拖垮主窗口;操作系统层面拥有当前用户完整账户权限,仅宿主接口受权限表约束 |
|
||||
@@ -35,12 +35,16 @@ flowchart TB
|
||||
|
||||
内置 macOS 应用窗口插件默认关闭,依赖 Guest Tools 传输与虚拟机交互服务。用户启用后可在运行中的 macOS 虚拟机操作菜单中打开前台应用窗口。停用插件会移除操作入口并关闭独立窗口。
|
||||
|
||||
内置 macOS 自动装机助手插件默认启用,依赖虚拟机交互服务,在主进程内经同一套扩展点与宿主接口权限管道运行。它结合本机 Windows OCR(缺少语言包时可按需下载或离线导入 RapidOCR ONNX)与声明式规则推进恢复模式离线安装与设置助理,不向外部上传截屏或密文,停用后立即结束活动会话并移除新建向导、详情页与命令行的全部入口。
|
||||
|
||||
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`。截图可指定一块区域,区域坐标默认按源分辨率计算,也可附带参考图像尺寸,由宿主换算到源分辨率;宿主在全分辨率帧上裁剪区域后再缩放,超出支持范围的宽度会被收进范围内而不是被拒绝。按键可单独按住和松开,按住时可同时带修饰键,宿主一并按住或抬起;释放接口一次抬起指定的按键和鼠标键;驱动控制台只支持按键单击。关机可指定强制停止。宿主记录每个插件在各台虚拟机上仍按住的键与鼠标键,包括驱动控制台上的鼠标键,在插件进程退出、插件停用、虚拟机停止或两分钟不再调用时替它抬起;按住状态只由输入事件维护,不依赖连接存活,虚拟机未运行时记录直接丢弃,不在开机后补发过期的释放。
|
||||
Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 VM 目录。读取 VM 状态和恢复点列表要求 `vm:read`,截图要求 `vm:screen`,输入要求 `qmp:write`,VM 启停要求 `vm:control`。截图可指定一块区域,区域坐标默认按源分辨率计算,也可附带参考图像尺寸,由宿主换算到源分辨率;宿主在全分辨率帧上裁剪区域后再缩放,支持 JPEG 与无损 PNG 格式并可按宽度或最长边限制尺寸(`max_edge` 为 `0` 时返回原始分辨率),超出支持范围的宽度会被收进范围内而不是被拒绝。按键可单独按住和松开,按住时可同时带修饰键,宿主一并按住或抬起;释放接口一次抬起指定的按键和鼠标键;驱动控制台只支持按键单击。关机可指定强制停止。宿主记录每个插件在各台虚拟机上仍按住的键与鼠标键,包括驱动控制台上的鼠标键,在插件进程退出、插件停用、虚拟机停止或两分钟不再调用时替它抬起;按住状态只由输入事件维护,不依赖连接存活,虚拟机未运行时记录直接丢弃,不在开机后补发过期的释放。
|
||||
|
||||
键入敏感设置对所有持有 `qmp:write` 且用户已按虚拟机授权访问的插件开放,不再只对官方插件开放。宿主只键入该插件自己的设置,不向插件返回明文,审计日志只记录设置名与长度。恢复点还原对已授权访问的虚拟机开放;删除虚拟机仍只限插件自己创建的临时虚拟机,克隆名称由插件自定,宿主以自己写入的归属标记识别临时虚拟机。Host API 审核插件权限并记录方法名,不把输入文本写入审计日志。开机、登录和切换显示时画面可能是纯色,此时截图照常返回该帧并标记 `blank`,插件据此继续等待,而不是当作失败。登录密码由 Windows DPAPI 保护。插件自己的下载器敏感设置仅在下载请求中解密并传给该插件进程。
|
||||
|
||||
虚拟机处于 `installer` 或 `recovery` 阶段时,外部插件的截图与键鼠输入操作均须先经主窗口弹窗获得用户确认。授权仅驻留内存,默认有效期 30 分钟,可选 10 分钟、60 分钟或直到离开当前阶段,离开阶段、关机或点停止后立即撤销。外部插件操作虚拟机期间,宿主在侧栏、详情页、系统托盘和虚拟机窗口浮层显示受控状态与暂停/停止入口;普通接管模式下,用户在虚拟机窗口按下键盘、点击、滚轮或移动鼠标超过 24 像素即自动暂停外部输入,锁定模式下由宿主拦截对虚拟机客户区的误触键鼠输入(保留 `Alt+Tab`、`Alt+Esc` 与 `Win` 等系统逃生快捷键)并在点击浮层或主窗口「暂停」后立即解锁。
|
||||
|
||||
## 生命周期、参数账本与资源预算
|
||||
|
||||
每个启用中的插件拥有独立的作用域,注册的服务、事件订阅、界面槽位、后台监听与系统钩子均绑定释放函数;插件停用、卸载或激活失败时按逆序完整拆除。服务依赖变更时先停用失去依赖的插件,再按依赖拓扑激活就绪插件。
|
||||
@@ -80,7 +84,7 @@ Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 V
|
||||
|
||||
每个公开的稳定契约项在发布时均具备宿主实现与契约测试;尚未实现的预留项在契约文件中标记为 `experimental`,清单校验予以放行但 `reims-go plugin doctor` 会给出实验性提示,正式版市场插件不得依赖实验项。主版本内只做向后兼容的可选扩展,插件在握手阶段根据宿主下发的 `features` 特性列表按需降级,未知清单字段忽略并提示。宿主接口目录中的每个方法同样以特性名宣告,测试保证目录中的稳定方法都有实现、宿主实现的方法都在目录内。
|
||||
|
||||
当前插件契约为 `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` 拒绝;更早的插件继续忽略未知字段,以便已发布插件在宿主补齐字段前照常工作。
|
||||
当前插件契约为 `pluginApi 1.3.0`,界面契约为 `uiApi 2.2.0`。客体驱动在清单中以 `runtimeKind` 为 `external` 声明自带运行环境,并可用 `consoleEndpoint`、`pasteCombo`、`keymap` 声明控制台接入方式、客体粘贴组合键与键位映射。`contributes.autoInstallers` 允许插件按客体家族声明自动装机提供方,供新建向导、虚拟机详情页与 `vm autoinstall` 子命令通用发现,宿主核心不硬编码具体插件标识。`driver.console`、`host.secret.materialize`、`host.download`、`host.download.timeouts`、`host.download.custom_mirror`、`host.elevate.request`、`host.ui.confirm`、`host.session`、`host.console.screenshot.region`、`host.vm.finishInstall`、`host.vm.restart`、`host.vm.telemetry` 与 `vm.phaseChanged` 均已进入稳定契约,并在 Sidecar 握手特性列表中宣告。声明 `pluginApi` 1.3 或更高范围的插件,其宿主接口请求中未定义的字段会以 JSON-RPC `-32602` 拒绝;更早的插件继续忽略未知字段,以便已发布插件在宿主补齐字段前照常工作。界面契约新增列表项与虚拟机页的 `data-remote-control` 受控状态属性及 `remote-control` 主题图标。
|
||||
|
||||
## 客体驱动的 Sidecar 协议
|
||||
|
||||
@@ -92,7 +96,9 @@ Sidecar 可通过宿主接口请求为指定虚拟机拉起进程,宿主以「
|
||||
|
||||
客体驱动可通过 `host/secret.materialize` 委托宿主把受 Windows DPAPI 保护的敏感设置按模板(支持原样、XML 转义与 Base64 UTF-16LE)写入虚拟机目录内的新文件,文件权限沿用该目录。插件本身不接触明文,审计日志只记录设置名与字节长度;宿主持久化记录已物化路径,在插件调用 `host/secret.discard` 或用户删除虚拟机时先覆写清零再删除文件。
|
||||
|
||||
插件可通过 `host/download.start` 与 `host/download.cancel` 委托宿主执行受 `net:<origin>` 权限约束的后台下载。宿主只放行已声明来源的 HTTPS 地址(测试用回环地址除外),要求提供并校验 SHA-256,检查重定向安全,禁止 HTTPS 降级为明文 HTTP 以及指向本机或私网地址的重定向,并限制落盘目录位于插件私有数据目录或该驱动声明的虚拟机根目录内。下载进度同步到桌面任务栏与 Sidecar 的 `download/progress` 通知;存在进行中的下载时,关闭主窗口会先弹出确认提示。
|
||||
插件可通过 `host/download.start` 与 `host/download.cancel` 委托宿主执行受 `net:<origin>` 权限约束的后台下载。宿主只放行已声明来源的 HTTPS 地址(测试用回环地址除外),要求提供并校验 SHA-256,检查重定向安全,禁止 HTTPS 降级为明文 HTTP 以及指向本机或私网地址的重定向,并限制落盘目录位于插件私有数据目录或该驱动声明的虚拟机根目录内。调用方可为下载指定连接超时与卡死无进展超时;请求用户自定义镜像来源时必须提供固定 SHA-256 校验值,并经主窗口弹窗由用户确认来源后才放行。下载进度同步到桌面任务栏与 Sidecar 的 `download/progress` 通知;存在进行中的下载时,关闭主窗口会先弹出确认提示。
|
||||
|
||||
插件可通过 `host/vm.finishInstall`、`host/vm.restart` 与 `host/vm.telemetry` 分别完成移除安装介质、带重启计数触发重启以及读取虚拟机磁盘大小、串口启动里程碑(含离线首启预配置就绪信号)、最近日志与运行时状态摘要。宿主在虚拟机阶段变化时向运行中的 Sidecar 推送 `vm/phaseChanged` 通知,插件也可经 `host/ui.confirm` 发起受宿主渲染的确认弹窗。
|
||||
|
||||
客体驱动可通过 `host/elevate.request` 请求白名单内的 Windows 系统功能配置,当前仅支持启用 Hyper-V、将当前账户加入 Hyper-V Administrators 组与启用 Windows Sandbox。宿主先唤起主窗口并展示默认聚焦取消按钮的确认对话框,明确告知请求插件来源、操作内容、权限范围以及后续需要手动重启或重新登录,确认后才通过 Windows UAC 直接运行对应的系统工具。提权操作在无桌面窗口时直接拒绝,且绝不自动重启系统。
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
| QEMU 虚拟化层 | WHPX / TCG、客体机器与设备模型、`reims-graphics-pci` 的 PCI 设备侧、QMP 命令实现、`qcow2` 格式与迁移机制 | [`steelbrain/qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu)。核对构建提交中的 `vendor/qemu` gitlink 及其来源。 |
|
||||
| 独立上游工具 | `reims-util` 内的引导资源生成、安装镜像处理和工具自身的参数语义 | [`steelbrain/reims-util`](https://github.com/steelbrain/reims-util)。按运行时锁定的提交定位。 |
|
||||
| 独立图形依赖 | Metal 到 Vulkan 的命令、资源和着色器转换实现 | [`steelbrain/metal2vulkan`](https://github.com/steelbrain/metal2vulkan)。按运行时锁定的提交定位。 |
|
||||
| Apple 芯片 Mac 原生运行器 | 虚拟机设备、安装事务、实例锁、查看器和关机协议 | 独立 `nivfold` 仓库。客户端的驱动注册、命令适配与任务界面仍归 `Reims-Go`。 |
|
||||
| 其他独立引擎 | 引擎自身的执行、翻译和固件实现 | 对应引擎的源代码仓库。客户端的驱动注册、启动参数适配和状态展示仍归 `Reims-Go`。 |
|
||||
| 运行时集成与分发 | 上游版本选取、依赖补丁、运行时编译、打包、能力清单及 Preview 发布 | [`reims-go/reims-vgpu`](https://github.com/reims-go/reims-vgpu) 的运行时流水线。构建及发布规则见[便携运行时与跨仓边界](architecture.md#便携运行时与跨仓边界)。 |
|
||||
|
||||
|
||||
+4
-2
@@ -9,9 +9,11 @@
|
||||
| 改动持久化或升级 | `node scripts/test.mjs quick storage` | 配置和数据目录、迁移及插件状态存储,使用真实临时文件 |
|
||||
| 改动调试工具 | `node scripts/test.mjs quick tooling` | 临时目录和工单工具自测 |
|
||||
| 改动 GitHub 自动化脚本 | `node scripts/test.mjs quick automation` | `scripts/ci/` 下 PR 审核、Issue 分诊、代码诊断和申报校验脚本的自测 |
|
||||
| 跨模块改动或提 PR | `node scripts/test.mjs ci` | 前端测试和类型检查、`cmd/`、`internal/`、`pkg/`、`scripts/` 下的 Go 测试与 vet、调试工具自测、GitHub 自动化脚本自测 |
|
||||
| 跨模块改动或提 PR | `node scripts/test.mjs ci` | 前端测试和类型检查、`internal/`、`pkg/`、`scripts/` 下的 Go 测试与 vet、调试工具自测、GitHub 自动化脚本自测 |
|
||||
| 核对发布候选 | `node scripts/test.mjs release` | 使用 `desktop,production` 构建标签运行同一套 Go 检查,禁用测试结果缓存并随机化用例顺序 |
|
||||
| Windows 桌面冒烟 | `node scripts/test.mjs webview2 build/bin/reims-go.exe` | 启动已构建的客户端,在真实 WebView2 中完成首启数据目录设置 |
|
||||
| Apple 芯片 Mac 构建 | `node scripts/build-macos.mjs` | 独立构建桌面端。`--runtime` 可接入已构建并签名的 Nivfold |
|
||||
| Mac 客户端运行时契约检查 | `node scripts/test.mjs applevz .debug/runs/macos-client/nivfold` | 无系统镜像地检查 Nivfold 签名、协议、宿主能力和空实例状态。运行器内部套接字和安装取消测试在 Nivfold 仓库执行 |
|
||||
|
||||
GitHub CI 额外检查变更日志、工作区纪律、前端生产打包、Windows GUI 可执行文件的 `version` 输出与 WebView2 首启。滚动开发版检查推送到 `main` 的最新提交消息的第一行,包含 `#` 且不包含 `docs`(忽略大小写)时才复用该提交的 CI 测试自动构建。自动构建跳过有多个父提交的合并提交及纯文档推送。手动构建会跑 CI 测试并冒烟。带版本标签的发布与每日 Alpha 先跑发布候选测试,再对待发布的 EXE 运行桌面冒烟。两个发布流程都在上传前验证实际 EXE 的版本、ZIP 内的文件和 SHA-256 校验和。
|
||||
|
||||
@@ -28,4 +30,4 @@ Go 包并发默认为可用 CPU 数与 4 的较小值,每个包的运行上限
|
||||
- 前端测试直接加载生产模块验证任务排序和过期事件。涉及界面交互时优先覆盖用户可观察的状态切换,不按源码行或正则截取组件源码执行。
|
||||
- Go 单包测试验证领域规则,跨层测试保留桌面桥接、控制套接字、本地 HTTP、子进程与数据迁移等真实接口用例。异步用例通过完成信号控制时序,超时只用于报告卡死。
|
||||
- 存储层测试使用真实临时目录验证配置、目录锁、版本升级、插件状态备份与损坏恢复。
|
||||
- 依赖真实便携运行时、磁盘工具、引导镜像与安装包的集成用例仅在传入对应的 `REIMS_GO_TEST_*` 环境变量时运行,常规档位自动跳过。改动涉及虚拟机运行或磁盘操作时须在 Windows 宿主机实测验证。
|
||||
- 依赖真实便携运行时、磁盘工具、引导镜像与安装包的集成用例仅在传入对应的 `REIMS_GO_TEST_*` 环境变量时运行,常规档位自动跳过。改动涉及虚拟机运行或磁盘操作时须在对应宿主实测。Mac 原生后端的完整冒烟需使用数据目录外的本地 Apple `.ipsw`,验证安装、首次启动、重新显示窗口和正常关机。执行客体图形安装向导前必须确认。
|
||||
@@ -0,0 +1,78 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { loadTestModule } from './load-test-module.mjs'
|
||||
|
||||
const { buildNativeMenu, resolveMenuClick, buildTitleMenus, runMenuCommand, vmFeatures } = await loadTestModule(`
|
||||
import './i18n/domains/core.gen'
|
||||
import './i18n/domains/vm.gen'
|
||||
export * from './macos/applicationMenuModel'
|
||||
export * from './lib/titleMenu'
|
||||
export { vmFeatures } from './lib/endpoints'
|
||||
`)
|
||||
const props = { locale: 'en-US', sidebarOpen: true, logsOpen: false, themeMode: 'system', canLight: true, canDark: true, vm: null }
|
||||
const state = { workspaceReady: true, dialogOpen: false, vmSettingsReady: false }
|
||||
const vm = { name: 'test', state: 'stopped', busy: false, canSuspend: false, features: vmFeatures() }
|
||||
const find = (model, command) => model.groups.flatMap((group) => group.rows).find((row) => row.command === command)
|
||||
|
||||
test('the native bar localizes three menus and reflects view state and Command shortcuts', () => {
|
||||
const { groups } = buildNativeMenu({ ...props, locale: 'zh-CN' }, state)
|
||||
assert.deepEqual(groups.map(({ label }) => label), ['虚拟机', '视图', '帮助'])
|
||||
const menu = buildNativeMenu({ ...props, canDark: false, themeMode: 'light', logsOpen: true, vm }, state)
|
||||
assert.deepEqual(menu.groups.map(({ label }) => label), ['VM', 'View', 'Help'])
|
||||
assert.equal(find(menu, 'sidebar').checked, true)
|
||||
assert.equal(find(menu, 'logs').checked, true)
|
||||
assert.equal(find(menu, 'theme:light').checked, true)
|
||||
assert.equal(find(menu, 'theme:dark'), undefined)
|
||||
assert.equal(find(menu, 'theme:system'), undefined)
|
||||
assert.deepEqual(['new', 'sidebar', 'logs', 'settings', 'vm:start'].map((command) => find(menu, command).key), ['n', 'b', 'l', ',', '\r'])
|
||||
assert.equal(buildTitleMenus(props).vm.rows[0].shortcut, 'Ctrl+N')
|
||||
})
|
||||
|
||||
test('standard macOS menus use the same locale as the app-defined menus', () => {
|
||||
const { standard: zh } = buildNativeMenu({ ...props, locale: 'zh-CN' }, state)
|
||||
const { standard: en } = buildNativeMenu(props, state)
|
||||
assert.deepEqual([zh.edit, zh.window, zh['hide:'], zh.Quit], ['编辑', '窗口', '隐藏 Reims-Go', '退出 Reims-Go'])
|
||||
assert.deepEqual([en.edit, en.window, en['hide:'], en.Quit], ['Edit', 'Window', 'Hide Reims-Go', 'Quit Reims-Go'])
|
||||
assert.deepEqual([zh['undo:'], zh['redo:'], zh['pasteAsRichText:'], zh['startSpeaking:']], ['撤销', '重做', '粘贴并匹配样式', '开始朗读'])
|
||||
for (const key of Object.keys(en)) assert.notEqual(zh[key], en[key], key)
|
||||
})
|
||||
|
||||
test('VM menu validates the current VM state and ignores stale targets', () => {
|
||||
const selected = { ...state, selectedVMKey: 'driver:test', vmSettingsReady: true }
|
||||
let menu = buildNativeMenu({ ...props, vm }, selected)
|
||||
const click = (command, scope = selected.selectedVMKey) => resolveMenuClick({ command, scope }, menu.scope, menu.commands)
|
||||
assert.equal(click('vm:start'), 'vm:start')
|
||||
assert.equal(click('vm:start', 'another-driver:test'), undefined)
|
||||
assert.equal(click('vmSettings'), 'vmSettings')
|
||||
assert.equal(click('vm:stop'), undefined)
|
||||
|
||||
menu = buildNativeMenu({ ...props, vm: { ...vm, state: 'running' } }, selected)
|
||||
assert.equal(click('vm:start'), undefined)
|
||||
assert.equal(click('vm:focus'), 'vm:focus')
|
||||
assert.equal(click('vm:stop'), 'vm:stop')
|
||||
assert.equal(click('vm:delete'), undefined)
|
||||
|
||||
menu = buildNativeMenu({ ...props, vm: { ...vm, state: 'suspended' } }, selected)
|
||||
assert.equal(click('vm:resume'), undefined)
|
||||
assert.equal(click('vmSettings'), undefined)
|
||||
assert.equal(click('vm:discardSuspend'), 'vm:discardSuspend')
|
||||
})
|
||||
|
||||
test('setup only exposes external help, and modal dialogs block native menu commands', () => {
|
||||
const setup = buildNativeMenu(props, { ...state, workspaceReady: false })
|
||||
assert.deepEqual([...setup.commands], ['website', 'docs', 'project', 'report'])
|
||||
assert.equal(buildNativeMenu(props, { ...state, dialogOpen: true }).commands.size, 0)
|
||||
})
|
||||
|
||||
test('native menu commands reuse the renderer actions and URL localization', () => {
|
||||
const calls = []
|
||||
const actions = { ...props, locale: 'zh-CN',
|
||||
onVMAction: (action) => calls.push(action),
|
||||
onVMDelete: () => calls.push('confirm delete'),
|
||||
onNavigate: (page) => calls.push(page),
|
||||
onThemeMode: (mode) => calls.push(mode),
|
||||
onOpenURL: (url) => calls.push(url),
|
||||
}
|
||||
for (const id of ['vm:stop', 'vm:delete', 'settings', 'update', 'theme:dark', 'docs']) runMenuCommand(actions, id)
|
||||
assert.deepEqual(calls, ['stop', 'confirm delete', 'settings', 'about', 'dark', 'https://reims.dev/docs/quick-start'])
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { loadTestModule } from './load-test-module.mjs'
|
||||
|
||||
const { defaultAutoInstallDraft, validateAutoInstallDraft } = await loadTestModule(
|
||||
`export * from './lib/autoInstallDraft'`
|
||||
)
|
||||
|
||||
test('recovery_only auto-install requires explicit Apple SLA confirmation', () => {
|
||||
const draft = defaultAutoInstallDraft()
|
||||
assert.equal(draft.enabled, false)
|
||||
assert.equal(draft.autoInstall, true)
|
||||
assert.equal(draft.slaAccepted, false)
|
||||
// Without explicit SLA confirmation, starting recovery_only auto-install must be blocked.
|
||||
assert.equal(validateAutoInstallDraft(draft, true), false)
|
||||
// Once user explicitly confirms Apple SLA, recovery_only is valid without account credentials.
|
||||
assert.equal(validateAutoInstallDraft({ ...draft, slaAccepted: true }, true), true)
|
||||
})
|
||||
|
||||
test('full mode auto-install requires SLA confirmation and valid ASCII credentials', () => {
|
||||
const base = {
|
||||
...defaultAutoInstallDraft(),
|
||||
enabled: true,
|
||||
fullName: 'Reims User',
|
||||
accountName: 'reims',
|
||||
password: 'Password123',
|
||||
slaAccepted: false,
|
||||
}
|
||||
assert.equal(validateAutoInstallDraft(base, true), false)
|
||||
assert.equal(validateAutoInstallDraft({ ...base, slaAccepted: true }, true), true)
|
||||
assert.equal(validateAutoInstallDraft({ ...base, slaAccepted: true, password: '123' }, true), false)
|
||||
assert.equal(validateAutoInstallDraft({ ...base, slaAccepted: true, fullName: '中文' }, true), false)
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
// scripts/brand/wordmark.py is the single source of the icon and the wordmark
|
||||
// geometry: it copies assets/logo.svg into public/ and generates
|
||||
// geometry: it copies build/assets/logo.svg into public/ and generates
|
||||
// wordmark.gen.ts. Neither copy may be edited by hand.
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
@@ -8,8 +8,8 @@ import path from 'node:path'
|
||||
|
||||
const repoRoot = path.resolve(import.meta.dirname, '..', '..')
|
||||
|
||||
test('frontend/public/logo.svg is the copy of assets/logo.svg', () => {
|
||||
const source = fs.readFileSync(path.join(repoRoot, 'assets', 'logo.svg'))
|
||||
test('frontend/public/logo.svg is the copy of build/assets/logo.svg', () => {
|
||||
const source = fs.readFileSync(path.join(repoRoot, 'build', 'assets', 'logo.svg'))
|
||||
const served = fs.readFileSync(path.join(repoRoot, 'frontend', 'public', 'logo.svg'))
|
||||
assert.ok(source.equals(served), 'run python scripts/brand/wordmark.py to refresh frontend/public/logo.svg')
|
||||
})
|
||||
|
||||
@@ -103,7 +103,7 @@ test('macOS VMs keep every action; other VMs follow their capabilities', () => {
|
||||
assert.equal(withAffinity.screenshot, false)
|
||||
})
|
||||
|
||||
test('hosted VMs never offer window, fullscreen, affinity, screenshot or typing', () => {
|
||||
test('hosted VMs without a window or console do not offer process or display controls', () => {
|
||||
const hosted = lib.vmFeatures({
|
||||
driver_id: 'acme.wsl',
|
||||
capabilities: ['hosted', 'affinity', 'qmp', 'snapshot'],
|
||||
@@ -117,6 +117,20 @@ test('hosted VMs never offer window, fullscreen, affinity, screenshot or typing'
|
||||
assert.equal(hosted.snapshot, true)
|
||||
})
|
||||
|
||||
test('a hosted native window takes priority over ready endpoints', () => {
|
||||
const windowed = lib.vmFeatures({ driver_id: 'example.native', capabilities: ['hosted', 'window', 'affinity'] })
|
||||
const ssh = ep('ssh')
|
||||
assert.equal(windowed.window, true)
|
||||
assert.equal(windowed.fullscreen, false)
|
||||
assert.equal(windowed.affinity, false)
|
||||
assert.deepEqual(lib.primaryVMAccess(windowed, [ssh]), { kind: 'window' })
|
||||
assert.deepEqual(lib.primaryVMAccess(windowed, []), { kind: 'window' })
|
||||
|
||||
const endpointOnly = lib.vmFeatures({ driver_id: 'example.wsl', capabilities: ['hosted'] })
|
||||
assert.deepEqual(lib.primaryVMAccess(endpointOnly, [ssh]), { kind: 'endpoint', endpoint: ssh })
|
||||
assert.equal(lib.primaryVMAccess(endpointOnly, [ep('ssh', false)]), undefined)
|
||||
})
|
||||
|
||||
test('a hosted VM offers screenshots and typing only when its driver serves a console', () => {
|
||||
const withConsole = lib.vmFeatures({ driver_id: 'acme.wsl', capabilities: ['hosted', 'console'] })
|
||||
assert.equal(withConsole.screenshot, true)
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { loadTestModule } from './load-test-module.mjs'
|
||||
|
||||
const { defaultGuestDriver, eligibleGuestDrivers, hasRestoreImagePicker, needsRuntimeSetup, restoreImageField } = await loadTestModule(`export * from './lib/guestDrivers'`)
|
||||
|
||||
const mac = { os: 'darwin', arch: 'arm64' }
|
||||
const win = { os: 'windows', arch: 'amd64' }
|
||||
const restore = { type: 'string', 'x-filePattern': '*.ipsw' }
|
||||
const create_schema = { properties: { restore_path: restore } }
|
||||
const native = { id: 'example.native', runtime_kind: 'external', builtin: true, create_schema }
|
||||
const thirdParty = { id: 'example.additional', runtime_kind: 'external', create_schema }
|
||||
const legacy = { id: 'builtin.driver.reims-macos', runtime_kind: 'reims-vgpu', builtin: true }
|
||||
|
||||
test('Apple Silicon skips portable runtime setup, but Windows still offers it when missing', () => {
|
||||
assert.equal(needsRuntimeSetup(mac, false), false)
|
||||
assert.equal(needsRuntimeSetup(win, false), true)
|
||||
assert.equal(needsRuntimeSetup(win, true), false)
|
||||
assert.equal(needsRuntimeSetup({ os: 'darwin', arch: 'amd64' }, false), true)
|
||||
})
|
||||
|
||||
test('a host-provided external driver can create without a portable runtime', () => {
|
||||
const eligible = eligibleGuestDrivers([legacy, native, thirdParty], false)
|
||||
assert.deepEqual(eligible, [native, thirdParty])
|
||||
assert.equal(defaultGuestDriver(eligible, mac), native)
|
||||
assert.equal(defaultGuestDriver([thirdParty, native], mac), thirdParty)
|
||||
assert.equal(defaultGuestDriver(eligible, mac, 'offline'), undefined)
|
||||
assert.equal(defaultGuestDriver([thirdParty, legacy], win), legacy)
|
||||
assert.equal(defaultGuestDriver([thirdParty, legacy], win, 'online'), legacy)
|
||||
assert.deepEqual(eligibleGuestDrivers([legacy, native], true), [legacy, native])
|
||||
})
|
||||
|
||||
test('Windows exposes only the managed drivers with their matching runtime', () => {
|
||||
const arm = { id: 'builtin.driver.stambha', runtime_kind: 'stambha-hosted', builtin: true }
|
||||
const drivers = [legacy, arm]
|
||||
assert.deepEqual(eligibleGuestDrivers(drivers, false, true), [arm])
|
||||
assert.equal(defaultGuestDriver([arm], win), arm)
|
||||
assert.deepEqual(eligibleGuestDrivers(drivers, true, false), [legacy])
|
||||
assert.deepEqual(eligibleGuestDrivers(drivers, true, true), drivers)
|
||||
})
|
||||
|
||||
test('cached IPSW routes only to the trusted native restore driver', () => {
|
||||
assert.equal(defaultGuestDriver([thirdParty, legacy, native], mac, 'ipsw'), native)
|
||||
assert.equal(defaultGuestDriver([thirdParty, legacy], mac, 'ipsw'), undefined)
|
||||
assert.equal(defaultGuestDriver([legacy, native], win, 'ipsw'), undefined)
|
||||
assert.equal(restoreImageField(native, mac), 'restore_path')
|
||||
})
|
||||
|
||||
test('only a host-trusted create schema can add the IPSW picker', () => {
|
||||
assert.equal(hasRestoreImagePicker(native, restore), true)
|
||||
assert.equal(hasRestoreImagePicker(thirdParty, restore), false)
|
||||
assert.equal(hasRestoreImagePicker(native, { ...restore, 'x-filePattern': '*.ipsw;*' }), false)
|
||||
assert.equal(hasRestoreImagePicker(native, { ...restore, type: 'integer' }), false)
|
||||
})
|
||||
@@ -2,7 +2,16 @@ import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { loadTestModule } from './load-test-module.mjs'
|
||||
|
||||
const { createLogLine } = await loadTestModule(`export * from './lib/logs'`)
|
||||
const {
|
||||
LARGE_LOG_CHAR_THRESHOLD,
|
||||
LARGE_LOG_LINE_THRESHOLD,
|
||||
countLogLines,
|
||||
createLogLine,
|
||||
formatLogLine,
|
||||
formatLogLines,
|
||||
formatSelectedLogRows,
|
||||
isLargeLogPayload,
|
||||
} = await loadTestModule(`export * from './lib/logs'`)
|
||||
|
||||
const renderSelector = 'newRenderPipelineStateWithDescriptor:error:'
|
||||
const computeSelector = 'newComputePipelineStateWithDescriptor:options:reflection:error:'
|
||||
@@ -29,3 +38,66 @@ test('pipeline refusals and fatal errors retain their error level', () => {
|
||||
assert.equal(createLogLine({ line }).level, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
test('formatLogLine and formatLogLines emit single-line entries', () => {
|
||||
const row = createLogLine({ ts: '12:34:56', source: 'qemu', line: 'booting kernel' })
|
||||
assert.equal(formatLogLine(row), '12:34:56 [qemu] booting kernel')
|
||||
assert.equal(
|
||||
formatLogLines([
|
||||
row,
|
||||
createLogLine({ ts: '12:34:57', source: 'app', line: 'guest ready' }),
|
||||
]),
|
||||
'12:34:56 [qemu] booting kernel\n12:34:57 [app] guest ready',
|
||||
)
|
||||
})
|
||||
|
||||
test('countLogLines handles empty strings, CRLF, and trailing newlines', () => {
|
||||
assert.equal(countLogLines(''), 0)
|
||||
assert.equal(countLogLines('\n'), 0)
|
||||
assert.equal(countLogLines('one line'), 1)
|
||||
assert.equal(countLogLines('a\nb\n'), 2)
|
||||
assert.equal(countLogLines('a\r\nb\r\nc'), 3)
|
||||
})
|
||||
|
||||
test('isLargeLogPayload enforces line and character thresholds', () => {
|
||||
assert.equal(LARGE_LOG_LINE_THRESHOLD, 20)
|
||||
assert.equal(LARGE_LOG_CHAR_THRESHOLD, 2000)
|
||||
|
||||
const nineteenLines = Array.from({ length: 19 }, (_, i) => `line ${i + 1}`).join('\n')
|
||||
const twentyLines = Array.from({ length: 20 }, (_, i) => `line ${i + 1}`).join('\n')
|
||||
assert.equal(isLargeLogPayload(''), false)
|
||||
assert.equal(isLargeLogPayload(nineteenLines), false)
|
||||
assert.equal(isLargeLogPayload(`${nineteenLines}\n`), false)
|
||||
assert.equal(isLargeLogPayload(twentyLines), true)
|
||||
|
||||
assert.equal(isLargeLogPayload('x'.repeat(1999)), false)
|
||||
assert.equal(isLargeLogPayload('x'.repeat(2000)), true)
|
||||
})
|
||||
|
||||
test('formatSelectedLogRows normalizes multi-row DOM selections into single lines', () => {
|
||||
const normalized = formatSelectedLogRows([
|
||||
{ ts: ' 09:00:01 ', source: ' host ', line: ' indented message' },
|
||||
{ ts: '09:00:02', source: 'qemu', line: 'vgpu ready' },
|
||||
])
|
||||
assert.equal(
|
||||
normalized,
|
||||
'09:00:01 [host] indented message\n09:00:02 [qemu] vgpu ready',
|
||||
)
|
||||
})
|
||||
|
||||
test('formatSelectedLogRows flattens embedded LF, CRLF, and CR breaks within a log row', () => {
|
||||
const normalized = formatSelectedLogRows([
|
||||
{ ts: '00:00:00', source: 'app', line: 'first\ncontinued\n\ntrailing\n' },
|
||||
{ ts: '00:00:01', source: 'qemu', line: 'win\r\nsecond line\r\n' },
|
||||
{ ts: '00:00:02', source: 'host', line: '\rcr\rjoined' },
|
||||
])
|
||||
assert.equal(
|
||||
normalized,
|
||||
'00:00:00 [app] first continued trailing\n00:00:01 [qemu] win second line\n00:00:02 [host] cr joined',
|
||||
)
|
||||
assert.equal(countLogLines(normalized), 3)
|
||||
assert.equal(
|
||||
formatLogLine({ ts: '00:00:03', source: 'app', line: 'alpha\r\nbeta\ngamma' }),
|
||||
'00:00:03 [app] alpha beta gamma',
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { loadTestModule } from './load-test-module.mjs'
|
||||
|
||||
const { cachedRestoreImage, matchesRestoreImage, restoreImageChoiceKey, restoreImageChoices, restoreImagePathMissing } = await loadTestModule(`export * from './lib/restoreImages'`)
|
||||
|
||||
const latest = { version: '26.6.2', build: '25G83', title: 'macOS Tahoe' }
|
||||
const olderBuild = { kind: 'ipsw', version: latest.version, build: '25G82', title: 'macOS Tahoe', path: '/saved/old.ipsw' }
|
||||
const partial = { ...olderBuild, build: latest.build, path: '/saved/new.ipsw.part', partial: true }
|
||||
const otherKind = { ...olderBuild, build: latest.build, kind: 'offline' }
|
||||
|
||||
test('a previous IPSW build stays selectable without masking the latest one', () => {
|
||||
const cache = [olderBuild, partial, otherKind]
|
||||
assert.deepEqual(restoreImageChoices(latest, cache).map((choice) => choice.key), [
|
||||
restoreImageChoiceKey(latest.version, latest.build), restoreImageChoiceKey(olderBuild.version, olderBuild.build),
|
||||
])
|
||||
assert.equal(cachedRestoreImage(cache, latest.version, latest.build), undefined)
|
||||
assert.equal(cachedRestoreImage(cache, olderBuild.version, olderBuild.build), olderBuild)
|
||||
assert.equal(matchesRestoreImage(olderBuild, latest.version, latest.build), false)
|
||||
assert.equal(matchesRestoreImage(partial, latest.version, latest.build), true)
|
||||
})
|
||||
|
||||
test('a downloaded latest build is not repeated and is used by its exact matching row', () => {
|
||||
const complete = { ...partial, partial: false, path: '/saved/new.ipsw' }
|
||||
const cache = [otherKind, olderBuild, partial, complete]
|
||||
assert.equal(restoreImageChoices(latest, cache).length, 2)
|
||||
assert.equal(cachedRestoreImage(cache, latest.version, latest.build), complete)
|
||||
assert.equal(restoreImageChoices(undefined, [otherKind, olderBuild, partial]).length, 1)
|
||||
})
|
||||
|
||||
test('a completed IPSW missing a cache path is distinct from an absent or partial download', () => {
|
||||
const missing = { ...partial, partial: false, path: '' }
|
||||
assert.equal(restoreImagePathMissing([missing], latest.version, latest.build), true)
|
||||
assert.equal(restoreImagePathMissing([olderBuild, otherKind, { ...partial, path: '' }], latest.version, latest.build), false)
|
||||
assert.equal(restoreImagePathMissing([missing], latest.version, olderBuild.build), false)
|
||||
})
|
||||
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { loadTestModule } from './load-test-module.mjs'
|
||||
|
||||
const { creatingVMTasks, currentTask, findActiveOfflineTask, pruneFinishedTasks, taskDetail, upsertTask } =
|
||||
const { creatingVMTasks, currentTask, findActiveCachedTask, findActiveInstallerTask, findRunningRestoreTask, groupUnmatchedInstallerTasks, pruneFinishedTasks, taskDetail, taskStopAction, taskTitle, upsertTask } =
|
||||
await loadTestModule(`export * from './lib/tasks'`)
|
||||
|
||||
const task = (id, overrides = {}) => ({
|
||||
@@ -29,11 +29,23 @@ test('one installer download represents the VM creations waiting for it', () =>
|
||||
const download = task('download', { kind: 'installer-download', started_at: 15 })
|
||||
const vm = task('vm', { vm: 'vm one' })
|
||||
const other = task('other', { installer_version: '15.8.3' })
|
||||
assert.deepEqual(findActiveOfflineTask([vm, other, download], '26.7.3'), {
|
||||
assert.deepEqual(findActiveInstallerTask([vm, other, download], 'offline', '26.7.3'), {
|
||||
primary: download, waitingVMs: ['vm one'], matchedIDs: ['download', 'vm'],
|
||||
})
|
||||
})
|
||||
|
||||
test('native and Windows installers of the same version keep separate download state', () => {
|
||||
const win = task('win', { kind: 'installer-download' })
|
||||
const mac = task('mac', { kind: 'installer-download', installer_kind: 'ipsw' })
|
||||
const other = task('other', { kind: 'installer-download', installer_kind: 'ipsw', installer_version: '27.0' })
|
||||
const tasks = [win, mac, other]
|
||||
assert.equal(findActiveInstallerTask(tasks, 'ipsw', '26.7.3')?.primary, mac)
|
||||
assert.equal(findActiveInstallerTask(tasks, 'offline', '26.7.3')?.primary, win)
|
||||
assert.equal(findActiveCachedTask(tasks, { kind: 'ipsw', version: '26.7.3', partial: true })?.primary, mac)
|
||||
assert.deepEqual(groupUnmatchedInstallerTasks(tasks, new Set()).map((match) => match.primary.id), ['win', 'mac', 'other'])
|
||||
assert.deepEqual(taskStopAction('en-US', mac), { kind: 'pause', label: 'Pause download' })
|
||||
})
|
||||
|
||||
test('taskDetail formats download speeds under 1 MB/s in KB/s', () => {
|
||||
assert.equal(taskDetail(task('slow', { done: 5e6, total: 50e6, rate: 512e3 })), '5 MB / 50 MB · 512 KB/s')
|
||||
assert.equal(taskDetail(task('tiny', { done: 1e6, total: 10e6, rate: 200 })), '1 MB / 10 MB · 1 KB/s')
|
||||
@@ -41,6 +53,23 @@ test('taskDetail formats download speeds under 1 MB/s in KB/s', () => {
|
||||
assert.equal(taskDetail(task('gig', { done: 2e9, total: 10e9, rate: 1.2e9 })), '2.0 GB / 10.0 GB · 1.2 GB/s')
|
||||
})
|
||||
|
||||
test('guest restore is labeled as installing and can be canceled, not paused', () => {
|
||||
const restore = task('macOS', { kind: 'vm-restore', installer_kind: '', installer_phase: '' })
|
||||
assert.equal(taskTitle('en-US', restore), 'Installing macOS on macOS')
|
||||
assert.deepEqual(taskStopAction('en-US', restore), { kind: 'cancel', label: 'Cancel creation' })
|
||||
})
|
||||
|
||||
test('restore progress and cancel target the matching driver and case-preserved VM name', () => {
|
||||
const running = task('native', { kind: 'vm-restore', vm: 'builtin.driver.apple-vz:Test VM' })
|
||||
const otherDriver = { ...running, id: 'other', vm: 'example.driver:Test VM' }
|
||||
const finished = { ...running, id: 'finished', status: 'done' }
|
||||
const tasks = [otherDriver, finished, running]
|
||||
assert.equal(findRunningRestoreTask(tasks, 'builtin.driver.apple-vz', ' Test VM '), running)
|
||||
assert.equal(findRunningRestoreTask(tasks, 'example.driver', 'Test VM'), otherDriver)
|
||||
assert.equal(findRunningRestoreTask(tasks, 'builtin.driver.apple-vz', 'test vm'), undefined)
|
||||
assert.equal(findRunningRestoreTask(tasks, '', 'Test VM'), undefined)
|
||||
})
|
||||
|
||||
test('creatingVMTasks lists only running vm-create tasks not yet present in vms, oldest first', () => {
|
||||
const first = task('t1', { subject: 'macos-a', started_at: 10 })
|
||||
const second = task('t2', { subject: 'macos-b', started_at: 20 })
|
||||
|
||||
+266
-77
@@ -2,9 +2,12 @@ import { Minus, Moon, Square, Sun, X } from 'lucide-react'
|
||||
import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { WizardDraft } from './components/CreateWizard'
|
||||
import { AppDialogs } from './components/AppDialogs'
|
||||
import { DiagnosticsExportDialog } from './components/DiagnosticsExportDialog'
|
||||
import { OnlineRecoveryDialog } from './macos/OnlineRecoveryDialog'
|
||||
import { LogPanel, LogTab } from './components/LogPanel'
|
||||
import { TitleMenus } from './components/TitleMenus'
|
||||
import { SidebarToggle, TitleMenus } from './components/TitleMenus'
|
||||
import { ApplicationMenu } from './macos/ApplicationMenu'
|
||||
import type { TitleMenuProps } from './lib/titleMenu'
|
||||
import { UpdateCapsule } from './components/UpdateCapsule'
|
||||
import { DataRootReadOnly } from './components/DataRootReadOnly'
|
||||
import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar'
|
||||
@@ -13,7 +16,8 @@ import { VMPage } from './components/VMPage'
|
||||
import { buildFallbackChain, I18nKey, localeDir, locText, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
|
||||
import { defaultGuestLang, recommendedMemoryGB } from './lib/format'
|
||||
import { initialWizardResolution } from './lib/displayResolution'
|
||||
import { isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints'
|
||||
import { hasStambhaRuntime, isMacOSDriver, liveVMInfo, primaryVMAccess, vmFeatures } from './lib/endpoints'
|
||||
import { defaultGuestDriver, eligibleGuestDrivers, isAppleSilicon, needsRuntimeSetup } from './lib/guestDrivers'
|
||||
import { resolveFullscreenHotkey } from './lib/fullscreenHotkey'
|
||||
import { LogLine, appendLog, createLogLine } from './lib/logs'
|
||||
import { macOSMajor } from './macos/macosRelease'
|
||||
@@ -31,11 +35,11 @@ import { vmRefKey } from './lib/vmRef'
|
||||
import { closePluginDialog, closePluginView, emptyPluginViewState, matchViewCondition, openPluginView, pluginViewKey, prunePluginViews, type PluginViewRoute, type PluginViewState } from './lib/pluginViewRouter'
|
||||
import { publishPluginHostEvent } from './lib/pluginViewEvents'
|
||||
import { buildSafePluginAssetURL } from './lib/pluginAssets'
|
||||
import { ActiveThemePayload, AppState, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMAction, VMBusyAction, VMDetail, VMInfo, VMListItem, ViewContribution } from './types'
|
||||
import { ActiveThemePayload, AppState, AutoInstallerProviderView, AutoInstallStartRequest, CachedInstaller, CreateOpts, DiagnosticsExportResult, DriverSummary, Locale, PluginUIContributions, ProvisionRequest, Task, VMAction, VMBusyAction, VMDetail, VMInfo, VMListItem, ViewContribution } from './types'
|
||||
import { Tip, TooltipProvider } from './ui/controls'
|
||||
import { errorToast, Toaster, type ToastInput, useToasts } from './ui/toast'
|
||||
import { BrandMark, ThemeDecorations, ThemeVisualsProvider } from './ui/themeVisuals'
|
||||
import { api, DROP_NETWORK_VOLUMES_DENIED, events, WindowMinimise, WindowToggleMaximise, type ElevationPrompt } from './wails'
|
||||
import { api, DROP_NETWORK_VOLUMES_DENIED, events, WindowMinimise, WindowToggleMaximise, type ConfirmPrompt, type ConfirmResolvedEvent, type ElevationPrompt } from './wails'
|
||||
|
||||
// Opened on demand, so each is its own chunk and stays out of the startup
|
||||
// bundle: first-run setup, and the Engine / Installers / Settings pages.
|
||||
@@ -48,6 +52,10 @@ const PluginViewHost = lazy(() => import('./components/PluginViewHost').then((m)
|
||||
const AppSettingsPage = lazy(() => import('./components/AppSettingsPage').then((m) => ({ default: m.AppSettingsPage })))
|
||||
const AboutPage = lazy(() => import('./components/AboutPage').then((m) => ({ default: m.AboutPage })))
|
||||
|
||||
// Detect desktop chrome before GetState resolves, including the loading and setup screens.
|
||||
const nativeTitlebar = navigator.platform.startsWith('Mac')
|
||||
const titleMenuPages = { installers: INSTALLERS_ID, plugins: PLUGINS_ID, host: HOST_ID, settings: SETTINGS_ID, about: ABOUT_ID }
|
||||
|
||||
const errText = (e: unknown) => parseAppError(e).summary
|
||||
|
||||
type HostDropAck = { status: string; error?: string }
|
||||
@@ -100,12 +108,15 @@ const failKey: Record<VMBusyAction, I18nKey> = {
|
||||
|
||||
export const App: React.FC = () => {
|
||||
const [state, setState] = useState<AppState | null>(null)
|
||||
const [nativeMenuReady, setNativeMenuReady] = useState(false)
|
||||
const [selected, setSelectedPage] = useState<string>(HOST_ID)
|
||||
const [detail, setDetail] = useState<VMDetail | null>(null)
|
||||
// GetVMInfo for the selected non-macOS VM; macOS VMs use `detail` (GetVMDetail).
|
||||
const [vmInfoLoaded, setVMInfoLoaded] = useState<VMInfo | null>(null)
|
||||
const [detailRevision, setDetailRevision] = useState(0)
|
||||
const [showWizard, setShowWizard] = useState(false)
|
||||
const [wizardDrivers, setWizardDrivers] = useState<DriverSummary[]>([])
|
||||
const loadingWizardDrivers = useRef(false)
|
||||
const [wizardDraft, setWizardDraft] = useState<WizardDraft | null>(null)
|
||||
const [pendingCreates, setPendingCreates] = useState<string[]>([])
|
||||
const [showSettings, setShowSettings] = useState(false)
|
||||
@@ -115,9 +126,17 @@ export const App: React.FC = () => {
|
||||
const [discardSuspendTarget, setDiscardSuspendTarget] = useState<string | null>(null)
|
||||
const [closeDownloadsOpen, setCloseDownloadsOpen] = useState(false)
|
||||
const [elevationQueue, setElevationQueue] = useState<ElevationPrompt[]>([])
|
||||
const [confirmQueue, setConfirmQueue] = useState<ConfirmPrompt[]>([])
|
||||
const activeConfirmIDsRef = useRef(new Set<string>())
|
||||
const [autoInstallers, setAutoInstallers] = useState<AutoInstallerProviderView[]>([])
|
||||
const [cloneSource, setCloneSource] = useState<{ name: string; driverID: string } | null>(null)
|
||||
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
|
||||
const [sendTextTarget, setSendTextTarget] = useState<string | null>(null)
|
||||
const [diagResult, setDiagResult] = useState<DiagnosticsExportResult | null>(null)
|
||||
const [diagExporting, setDiagExporting] = useState(false)
|
||||
const diagExportingRef = useRef(false)
|
||||
const [diagCopyingFile, setDiagCopyingFile] = useState(false)
|
||||
const [diagRevealingFile, setDiagRevealingFile] = useState(false)
|
||||
const vmBusy = useVMBusy()
|
||||
const [loadError, setLoadError] = useState('')
|
||||
const [pluginUI, setPluginUI] = useState<PluginUIContributions | null>(null)
|
||||
@@ -488,7 +507,9 @@ export const App: React.FC = () => {
|
||||
const pending = selectedVM ? (state?.pending_changes[vmRefKey(selectedVM)] ?? []) : []
|
||||
const fixedModeSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'display-fixed-mode') ?? false
|
||||
const diskCacheSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'win32-native-aio') ?? false
|
||||
const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime
|
||||
const stambhaAvailable = hasStambhaRuntime(state?.runtimes)
|
||||
const nativeHost = isAppleSilicon(state?.host)
|
||||
const hostReady = !!state && (nativeHost ? !!state.host.apple_virtualization?.ready : state.host.whpx === 'ready' && (!!state.active_runtime || stambhaAvailable))
|
||||
const canSuspend = state?.can_suspend ?? false
|
||||
const fullscreenHotkey = state?.config.fullscreen_hotkey_enabled
|
||||
? resolveFullscreenHotkey(state.config.fullscreen_hotkey)
|
||||
@@ -595,14 +616,14 @@ export const App: React.FC = () => {
|
||||
try {
|
||||
const s = await api.GetState()
|
||||
setState(s)
|
||||
setSetupStage(s?.active_runtime ? null : 'runtime')
|
||||
setSetupStage(needsRuntimeSetup(s.host, !!s.active_runtime || hasStambhaRuntime(s.runtimes)) ? 'runtime' : null)
|
||||
} catch (e) {
|
||||
console.warn('[app] GetState after setup failed:', e)
|
||||
fail(tr('failGeneric'), e)
|
||||
setSetupStage('runtime')
|
||||
setSetupStage(!nativeHost ? 'runtime' : null)
|
||||
}
|
||||
}
|
||||
const showSetup = !!state && (state.needs_setup || setupStage === 'runtime')
|
||||
const showSetup = !!state && (state.needs_setup || (!nativeHost && setupStage === 'runtime'))
|
||||
// The data folder opened read-only (internal/dataroot): nothing in it may be
|
||||
// changed, so the workspace gives way to a screen that explains why.
|
||||
const showReadOnly = !!state && !showSetup && !!state.data_root_status?.read_only
|
||||
@@ -664,8 +685,14 @@ export const App: React.FC = () => {
|
||||
console.warn('[app] GetPluginUIContributions failed:', e)
|
||||
if (live) setPluginUI((previous) => previous ?? {} as PluginUIContributions)
|
||||
})
|
||||
api.ListAutoInstallers('').then((list) => {
|
||||
if (live) setAutoInstallers(list ?? [])
|
||||
}).catch((e) => {
|
||||
console.warn('[app] ListAutoInstallers failed:', e)
|
||||
if (live) setAutoInstallers([])
|
||||
})
|
||||
return () => { live = false }
|
||||
}, [themeRevision, state?.safe_mode])
|
||||
}, [themeRevision, state?.safe_mode, locale])
|
||||
|
||||
useEffect(() => {
|
||||
void applyActiveTheme(
|
||||
@@ -787,15 +814,6 @@ export const App: React.FC = () => {
|
||||
}
|
||||
}
|
||||
|
||||
// Hosted VMs have no window: the primary action is their best ready endpoint.
|
||||
const openEndpoint = (vm: VMListItem, kind: string) => {
|
||||
api.OpenVMEndpoint(vm.driver_id ?? '', vm.name, kind, '').catch((e) => fail(tr('failEndpointOpen'), e))
|
||||
}
|
||||
const openPrimaryEndpoint = (vm: VMListItem) => {
|
||||
const { primary } = splitEndpoints(vm.endpoints)
|
||||
if (primary) openEndpoint(vm, primary.kind)
|
||||
}
|
||||
|
||||
// Actions that only the macOS driver implements (name-based or macOS guest features).
|
||||
const MACOS_ONLY_ACTIONS: readonly VMAction[] = [
|
||||
'finishInstall', 'enterRecovery', 'attachInstaller', 'attachGuestTools', 'detachGuestTools',
|
||||
@@ -810,18 +828,16 @@ export const App: React.FC = () => {
|
||||
const features = vmFeatures(actionVM)
|
||||
if (!canSuspendVM(actionVM) && (action === 'suspend' || action === 'resume')) return
|
||||
if (!features.macos && MACOS_ONLY_ACTIONS.includes(action)) return
|
||||
if (action === 'focus' && !features.window) return
|
||||
if (action === 'fullscreen' && !features.fullscreen) return
|
||||
if (action === 'screenshot' && !features.screenshot) return
|
||||
if ((action === 'type' || action === 'sendText') && !features.sendText) return
|
||||
if (action === 'focus' && !features.window) {
|
||||
if (actionVM) openPrimaryEndpoint(actionVM)
|
||||
return
|
||||
}
|
||||
const activeBusy = vmBusy.current(key)
|
||||
if (
|
||||
activeBusy
|
||||
&& action !== 'openFolder'
|
||||
&& action !== 'openSharedFolder'
|
||||
&& action !== 'exportDiagnostics'
|
||||
&& (action !== 'forceStop' || activeBusy === 'forceStop')
|
||||
) {
|
||||
return
|
||||
@@ -852,7 +868,7 @@ export const App: React.FC = () => {
|
||||
case 'upgradeNVMe':
|
||||
return runVMAction(key, action, () => api.UpgradeDiskToNVMe(name), tr(isRunning ? 'toastNVMeNextStart' : 'toastNVMeReady'))
|
||||
case 'exportDiagnostics':
|
||||
return runVMAction(key, action, async () => { await api.ExportDiagnostics(actionDriverID, name) }, tr('toastDiagExported'))
|
||||
return void handleExportDiagnostics({ driverID: actionDriverID, name })
|
||||
case 'cloneVM':
|
||||
if (!features.clone) return
|
||||
return setCloneSource({ name, driverID: actionDriverID })
|
||||
@@ -883,9 +899,7 @@ export const App: React.FC = () => {
|
||||
onVMActionFor(name, action, st === 'running')
|
||||
}
|
||||
|
||||
// The state's own main action (Start, Resume while suspended, or Show Window while running), shared by
|
||||
// Ctrl+Enter and a double-click in the sidebar. A running hosted VM has no window; its action is its
|
||||
// best ready endpoint, and nothing when none is ready.
|
||||
// Ctrl+Enter and sidebar double-click use the same primary action as the VM page.
|
||||
const primaryAction = (name: string) => {
|
||||
const vm = findVM(name)
|
||||
if (!vm) return
|
||||
@@ -894,7 +908,13 @@ export const App: React.FC = () => {
|
||||
const st = state?.transitions[key] ?? vm.state
|
||||
if (st === 'stopped') onVMActionFor(key, 'start', false)
|
||||
else if (st === 'suspended') onVMActionFor(key, 'resume', false)
|
||||
else if (st === 'running') onVMActionFor(key, 'focus', true)
|
||||
else if (st === 'running') {
|
||||
const access = primaryVMAccess(vmFeatures(vm), vm.endpoints)
|
||||
if (access?.kind === 'window') onVMActionFor(key, 'focus', true)
|
||||
else if (access?.kind === 'endpoint') {
|
||||
api.OpenVMEndpoint(vm.driver_id ?? '', vm.name, access.endpoint.kind, '').catch((e) => fail(tr('failEndpointOpen'), e))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const confirmDelete = (keepFiles: boolean) => {
|
||||
@@ -936,26 +956,44 @@ export const App: React.FC = () => {
|
||||
}, tr('toastCloned', { name: cloneName }))
|
||||
}
|
||||
|
||||
const openWizard = () => {
|
||||
if (!state?.active_runtime) {
|
||||
const loadWizardDrivers = async (kind?: 'offline' | 'online' | 'ipsw') => {
|
||||
if (!state || loadingWizardDrivers.current) return false
|
||||
loadingWizardDrivers.current = true
|
||||
try {
|
||||
const drivers = eligibleGuestDrivers(await api.ListDrivers() ?? [], !!state.active_runtime, stambhaAvailable)
|
||||
if (defaultGuestDriver(drivers, state.host, kind)) {
|
||||
setWizardDrivers(drivers)
|
||||
return true
|
||||
}
|
||||
setSelected(HOST_ID)
|
||||
toasts.push({ kind: 'error', title: tr('noRuntimeAlert') })
|
||||
return
|
||||
toasts.push({ kind: 'error', title: tr(needsRuntimeSetup(state.host, !!state.active_runtime || stambhaAvailable) ? 'noRuntimeAlert' : 'wizardNoDriver') })
|
||||
return false
|
||||
} catch (e) {
|
||||
fail(tr('wizardDriverListFailed'), e)
|
||||
return false
|
||||
} finally {
|
||||
loadingWizardDrivers.current = false
|
||||
}
|
||||
}
|
||||
|
||||
const openWizard = async () => {
|
||||
if (!(await loadWizardDrivers())) return
|
||||
setWizardDraft(null)
|
||||
setShowWizard(true)
|
||||
}
|
||||
|
||||
const openWizardWithInstaller = (item: CachedInstaller) => {
|
||||
if (!state?.active_runtime) {
|
||||
setSelected(HOST_ID)
|
||||
toasts.push({ kind: 'error', title: tr('noRuntimeAlert') })
|
||||
return
|
||||
}
|
||||
const openWizardWithInstaller = async (item: CachedInstaller) => {
|
||||
if (!state || item.partial || item.kind === 'other' || !item.path || !(await loadWizardDrivers(item.kind))) return
|
||||
const existing = new Set((state.vms ?? []).map((v) => v.name.toLowerCase()))
|
||||
let defaultName = 'macos-tahoe'
|
||||
const baseName = item.kind === 'ipsw' ? 'macos' : 'macos-tahoe'
|
||||
let defaultName = baseName
|
||||
for (let i = 2; existing.has(defaultName.toLowerCase()); i++) {
|
||||
defaultName = `macos-tahoe-${i}`
|
||||
defaultName = `${baseName}-${i}`
|
||||
}
|
||||
if (item.kind === 'ipsw') {
|
||||
setWizardDraft({ step: 1, restoreImage: item, name: defaultName })
|
||||
setShowWizard(true)
|
||||
return
|
||||
}
|
||||
const isOffline = item.kind === 'offline' && !!item.version
|
||||
const graphics = state.host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga'
|
||||
@@ -993,17 +1031,53 @@ export const App: React.FC = () => {
|
||||
|
||||
// The wizard closes as soon as the create starts; progress shows in the sidebar,
|
||||
// main view, and status bar. On failure or cancel the toast offers returning to the wizard.
|
||||
const submitCreate = (payload: CreateOpts, draft: WizardDraft) => {
|
||||
const submitCreate = (payload: CreateOpts, draft: WizardDraft, autoInstall?: AutoInstallStartRequest, provision?: ProvisionRequest) => {
|
||||
setShowWizard(false)
|
||||
setWizardDraft(null)
|
||||
const name = payload.name
|
||||
const hasDownload = payload.source_mode === 'offline' || payload.source_mode === 'apple'
|
||||
const startAfterProvision = !!payload.start
|
||||
const createPayload = (provision || autoInstall) ? { ...payload, start: false } : payload
|
||||
setPendingCreates((prev) => (prev.includes(name) ? prev : [...prev, name]))
|
||||
setSelected(name)
|
||||
api.CreateVM(payload)
|
||||
.then(() => {
|
||||
api.CreateVM(createPayload)
|
||||
.then(async () => {
|
||||
toasts.push({ kind: 'ok', title: tr('toastCreated', { name }) })
|
||||
setSelected(name)
|
||||
if (provision) {
|
||||
try {
|
||||
await api.PrepareVMProvision(name, provision)
|
||||
} catch (err) {
|
||||
fail(tr('failProvision'), err)
|
||||
return refresh()
|
||||
}
|
||||
}
|
||||
if (autoInstall) {
|
||||
try {
|
||||
await api.StartAutoInstall({ ...autoInstall, vm_name: name, start_vm_if_stopped: true })
|
||||
} catch (err) {
|
||||
fail(tr('autoInstallStart'), err)
|
||||
if (!/start VM for auto-install/i.test(errText(err))) {
|
||||
try {
|
||||
const latest = await api.GetState()
|
||||
const created = latest?.vms?.find((v) => v.name === name && (!v.driver_id || v.driver_id === 'builtin.driver.reims-macos'))
|
||||
if (!created || created.state === 'stopped') {
|
||||
await api.StartVM('builtin.driver.reims-macos', name)
|
||||
}
|
||||
} catch (startErr) {
|
||||
fail(tr('failGeneric'), startErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
return refresh()
|
||||
}
|
||||
if (provision && startAfterProvision) {
|
||||
try {
|
||||
await api.StartVM('builtin.driver.reims-macos', name)
|
||||
} catch (err) {
|
||||
fail(tr('failGeneric'), err)
|
||||
}
|
||||
}
|
||||
return refresh()
|
||||
})
|
||||
.catch((e) => {
|
||||
@@ -1046,6 +1120,47 @@ export const App: React.FC = () => {
|
||||
}
|
||||
}
|
||||
|
||||
const handleExportDiagnostics = async (target?: { driverID: string; name: string }) => {
|
||||
if (showReadOnly || diagExportingRef.current) return
|
||||
const resolved = target ?? (selectedVM ? { driverID: selectedVM.driver_id ?? '', name: selectedVM.name } : { driverID: '', name: '' })
|
||||
diagExportingRef.current = true
|
||||
setDiagExporting(true)
|
||||
try {
|
||||
const result = await api.ExportDiagnostics(resolved.driverID, resolved.name)
|
||||
setDiagResult(result)
|
||||
} catch (e) {
|
||||
fail(tr('failExportDiagnostics'), e)
|
||||
} finally {
|
||||
diagExportingRef.current = false
|
||||
setDiagExporting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCopyDiagnosticsFile = async () => {
|
||||
if (!diagResult || diagCopyingFile) return
|
||||
setDiagCopyingFile(true)
|
||||
try {
|
||||
await api.CopyDiagnosticsFile(diagResult.path)
|
||||
toasts.push({ kind: 'ok', title: tr('toastDiagFileCopied') })
|
||||
} catch (e) {
|
||||
fail(tr('failCopyDiagnosticsFile'), e)
|
||||
} finally {
|
||||
setDiagCopyingFile(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleRevealDiagnosticsFile = async () => {
|
||||
if (!diagResult || diagRevealingFile) return
|
||||
setDiagRevealingFile(true)
|
||||
try {
|
||||
await api.RevealDiagnosticsFile(diagResult.path)
|
||||
} catch (e) {
|
||||
fail(tr('failOpenFolder'), e)
|
||||
} finally {
|
||||
setDiagRevealingFile(false)
|
||||
}
|
||||
}
|
||||
|
||||
const setLang = async (l: Locale) => {
|
||||
await api.SetLocale(l)
|
||||
refresh()
|
||||
@@ -1054,7 +1169,7 @@ export const App: React.FC = () => {
|
||||
// Global shortcuts (see docs/design-guidelines.md). Dialogs own the keyboard while open.
|
||||
const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {})
|
||||
const appDialogOpen = showSetup || showReadOnly || showWizard || showSettings || affinityTarget || deleteTarget ||
|
||||
discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || update.confirming || closeDownloadsOpen || elevationQueue.length > 0
|
||||
discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || diagResult || update.confirming || closeDownloadsOpen || elevationQueue.length > 0 || confirmQueue.length > 0
|
||||
shortcutRef.current = (e: KeyboardEvent) => {
|
||||
if (!e.ctrlKey || e.altKey || e.metaKey) return
|
||||
if (appDialogOpen) return
|
||||
@@ -1096,6 +1211,26 @@ export const App: React.FC = () => {
|
||||
)))
|
||||
return () => { offRequest(); offResolved() }
|
||||
}, [])
|
||||
// #105 protected-phase authorization, host/ui.confirm, and custom mirror confirmation prompts.
|
||||
const onConfirmResolvedRef = useRef<(ev: ConfirmResolvedEvent | string) => void>(() => {})
|
||||
onConfirmResolvedRef.current = (ev) => {
|
||||
const id = typeof ev === 'string' ? ev : ev?.id
|
||||
const reason = typeof ev === 'string' ? '' : (ev?.reason ?? '')
|
||||
if (!id) return
|
||||
const wasPending = activeConfirmIDsRef.current.delete(id)
|
||||
setConfirmQueue((q) => (q.some((item) => item.id === id) ? q.filter((item) => item.id !== id) : q))
|
||||
if (wasPending && reason === 'timeout') {
|
||||
toasts.push({ kind: 'error', title: tr('confirmTimedOut') })
|
||||
}
|
||||
}
|
||||
useEffect(() => {
|
||||
const offRequest = events.onConfirmRequest((req) => {
|
||||
activeConfirmIDsRef.current.add(req.id)
|
||||
setConfirmQueue((q) => (q.some((item) => item.id === req.id) ? q : [...q, req]))
|
||||
})
|
||||
const offResolved = events.onConfirmResolved((ev) => onConfirmResolvedRef.current(ev))
|
||||
return () => { offRequest(); offResolved() }
|
||||
}, [])
|
||||
|
||||
// Files dropped on the window go to the selected VM's shared folder.
|
||||
const dropping = useFileDrop(!!selectedVM && !!detail && !detail.has_installer && !detail.recovery_mode, (paths) => {
|
||||
@@ -1109,47 +1244,52 @@ export const App: React.FC = () => {
|
||||
.catch((e) => fail(tr('failGuestTools'), e))
|
||||
})
|
||||
|
||||
const workspaceReady = !!state && !showSetup && !showReadOnly
|
||||
const titleMenuProps: TitleMenuProps = {
|
||||
locale, sidebarOpen, logsOpen, themeMode, canLight, canDark, fullscreenHotkey,
|
||||
vm: selectedVM ? {
|
||||
name: selectedVM.name,
|
||||
driver_id: selectedVM.driver_id,
|
||||
state: effectiveState,
|
||||
busy: vmRefKey(selectedVM) in vmBusy.busy,
|
||||
graphics: detail?.name === selectedVM.name ? detail.graphics : undefined,
|
||||
canSuspend: canSuspendVM(selectedVM),
|
||||
features: selectedFeatures,
|
||||
} : null,
|
||||
appVersion: state?.app_version,
|
||||
onToggleSidebar: toggleSidebar,
|
||||
onToggleLogs: toggleLogs,
|
||||
onThemeMode: setThemeMode,
|
||||
onNewVM: openWizard,
|
||||
onVMAction,
|
||||
onVMSettings: () => { if (detail && effectiveState !== 'suspended') setShowSettings(true) },
|
||||
onVMDelete: () => { if (selectedVM) setDeleteTarget(vmRefKey(selectedVM)) },
|
||||
onNavigate: (page) => setSelected(titleMenuPages[page]),
|
||||
onOpenURL: (url) => { api.OpenURL(url).catch((e) => fail(tr('failGeneric'), e)) },
|
||||
}
|
||||
|
||||
return (
|
||||
<ThemeVisualsProvider payload={activeThemePayload}>
|
||||
<TooltipProvider>
|
||||
{nativeTitlebar && <ApplicationMenu props={titleMenuProps} onReady={setNativeMenuReady} state={{
|
||||
workspaceReady,
|
||||
dialogOpen: workspaceReady && (!!appDialogOpen || pluginViewState.dialogs.length > 0),
|
||||
selectedVMKey: selectedVM && vmRefKey(selectedVM),
|
||||
vmSettingsReady: !!detail && detail.name === selectedVM?.name,
|
||||
}} />}
|
||||
<div className="app-shell rg-p-shell">
|
||||
<div className="rg-layer rg-layer-background" data-rg-layer="layer.background" aria-hidden="true" />
|
||||
<header className="titlebar rg-p-titlebar" onDoubleClick={() => WindowToggleMaximise()}>
|
||||
{showSetup || showReadOnly || !state ? (
|
||||
<header className="titlebar rg-p-titlebar" data-native-titlebar={nativeTitlebar || undefined} onDoubleClick={nativeTitlebar ? undefined : WindowToggleMaximise}>
|
||||
{!workspaceReady ? (
|
||||
<div className="brand rg-p-brand">
|
||||
<BrandMark className="brand-mark" />
|
||||
Reims-Go
|
||||
</div>
|
||||
) : (
|
||||
<TitleMenus
|
||||
locale={locale}
|
||||
sidebarOpen={sidebarOpen}
|
||||
onToggleSidebar={toggleSidebar}
|
||||
logsOpen={logsOpen}
|
||||
onToggleLogs={toggleLogs}
|
||||
themeMode={themeMode}
|
||||
canLight={canLight}
|
||||
canDark={canDark}
|
||||
onThemeMode={setThemeMode}
|
||||
vm={selectedVM ? {
|
||||
name: selectedVM.name,
|
||||
driver_id: selectedVM.driver_id,
|
||||
state: effectiveState,
|
||||
busy: vmRefKey(selectedVM) in vmBusy.busy,
|
||||
graphics: detail?.name === selectedVM.name ? detail.graphics : undefined,
|
||||
canSuspend: canSuspendVM(selectedVM),
|
||||
features: selectedFeatures,
|
||||
} : null}
|
||||
fullscreenHotkey={fullscreenHotkey}
|
||||
onNewVM={openWizard}
|
||||
onVMAction={onVMAction}
|
||||
onVMSettings={() => { if (detail && effectiveState !== 'suspended') setShowSettings(true) }}
|
||||
onVMDelete={() => { if (selectedVM) setDeleteTarget(vmRefKey(selectedVM)) }}
|
||||
onNavigate={setSelected}
|
||||
onOpenURL={(url) => { api.OpenURL(url).catch((e) => fail(tr('failGeneric'), e)) }}
|
||||
appVersion={state.app_version}
|
||||
/>
|
||||
)}
|
||||
) : nativeTitlebar && nativeMenuReady ? (
|
||||
<div className="titlebar-left">
|
||||
<SidebarToggle {...titleMenuProps} mac />
|
||||
</div>
|
||||
) : <TitleMenus {...titleMenuProps} />}
|
||||
<div className="rg-slot-anchor titlebar-center" data-rg-slot="titlebar.center" />
|
||||
<div className="titlebar-right" onDoubleClick={(e) => e.stopPropagation()}>
|
||||
{canLight && canDark && (
|
||||
@@ -1164,11 +1304,11 @@ export const App: React.FC = () => {
|
||||
</button>
|
||||
</Tip>
|
||||
)}
|
||||
<div className="win-controls">
|
||||
{!nativeTitlebar && <div className="win-controls">
|
||||
<button type="button" className="win-btn" aria-label={tr('minimize')} onClick={() => WindowMinimise()}><Minus size={14} aria-hidden="true" /></button>
|
||||
<button type="button" className="win-btn" aria-label={tr('maximize')} onClick={() => WindowToggleMaximise()}><Square size={12} aria-hidden="true" /></button>
|
||||
<button type="button" className="win-btn close" aria-label={tr('closeWindow')} onClick={() => api.RequestClose()}><X size={15} aria-hidden="true" /></button>
|
||||
</div>
|
||||
</div>}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -1239,6 +1379,7 @@ export const App: React.FC = () => {
|
||||
safeMode={state?.safe_mode}
|
||||
updateDot={!!update.info?.has_update}
|
||||
pluginViews={sidebarPluginViews}
|
||||
agentSessions={state?.agent_sessions}
|
||||
creatingVMs={creatingItems.map((item) => ({ name: item.name, percent: item.task?.percent ?? -1 }))}
|
||||
updateCard={update.shown ? (
|
||||
<UpdateCapsule
|
||||
@@ -1332,6 +1473,7 @@ export const App: React.FC = () => {
|
||||
host={state.host}
|
||||
pending={pending}
|
||||
busyAction={vmBusy.busy[vmRefKey(selectedVM)]}
|
||||
exportingDiagnostics={diagExporting}
|
||||
onAction={onVMAction}
|
||||
onPluginCommand={(pluginID, command, title) => {
|
||||
const name = selectedVM.name
|
||||
@@ -1366,6 +1508,24 @@ export const App: React.FC = () => {
|
||||
fullscreenHotkey={fullscreenHotkey}
|
||||
dropping={dropping}
|
||||
pluginUI={pluginUI}
|
||||
agentSession={(state.agent_sessions ?? []).find((s) => s.vm_key === vmRefKey(selectedVM) || (!s.driver_id && s.vm_name === selectedVM.name)) ?? null}
|
||||
provisionReady={selectedIsMacOS && (state.provision_ready_vms?.includes(vmRefKey(selectedVM)) ?? false)}
|
||||
autoInstallers={autoInstallers}
|
||||
onStopAgentSession={() => {
|
||||
api.StopAgentSession(selectedVM.driver_id ?? '', selectedVM.name)
|
||||
.then(() => refresh())
|
||||
.catch((e) => fail(tr('remoteControlStop'), e))
|
||||
}}
|
||||
onPauseAgentSession={() => {
|
||||
api.PauseAgentSession(selectedVM.driver_id ?? '', selectedVM.name)
|
||||
.then(() => refresh())
|
||||
.catch((e) => fail(tr('remoteControlPause'), e))
|
||||
}}
|
||||
onResumeAgentSession={() => {
|
||||
api.ResumeAgentSession(selectedVM.driver_id ?? '', selectedVM.name)
|
||||
.then(() => refresh())
|
||||
.catch((e) => fail(tr('remoteControlResume'), e))
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
) : selected === SETTINGS_ID ? (
|
||||
@@ -1407,6 +1567,7 @@ export const App: React.FC = () => {
|
||||
locale={locale}
|
||||
onRefresh={refresh}
|
||||
onNewVM={openWizard}
|
||||
hostReady={hostReady}
|
||||
onError={fail}
|
||||
onToast={(title) => toasts.push({ kind: 'ok', title })}
|
||||
runtimeTask={runtimeTask}
|
||||
@@ -1443,6 +1604,8 @@ export const App: React.FC = () => {
|
||||
host={state?.host}
|
||||
runningVMs={runningVMCount}
|
||||
onCopy={copy}
|
||||
onExportDiagnostics={showReadOnly ? undefined : () => { void handleExportDiagnostics() }}
|
||||
exportingDiagnostics={diagExporting}
|
||||
hostReady={hostReady}
|
||||
onOpenHost={() => setSelected(HOST_ID)}
|
||||
/>
|
||||
@@ -1462,7 +1625,13 @@ export const App: React.FC = () => {
|
||||
displayNames={displayNames}
|
||||
showWizard={showWizard}
|
||||
wizardDraft={wizardDraft}
|
||||
autoInstallers={autoInstallers}
|
||||
wizardDrivers={wizardDrivers}
|
||||
onCloseWizard={() => { setShowWizard(false); setWizardDraft(null) }}
|
||||
onDriverCreated={(driverID, name) => {
|
||||
toasts.push({ kind: 'ok', title: tr('toastCreated', { name }) })
|
||||
void refresh().then(() => setSelected(vmRefKey({ driver_id: driverID, name })))
|
||||
}}
|
||||
onSubmitCreate={submitCreate}
|
||||
showSettings={showSettings}
|
||||
onCloseSettings={() => setShowSettings(false)}
|
||||
@@ -1502,6 +1671,13 @@ export const App: React.FC = () => {
|
||||
setElevationQueue((q) => q.filter((item) => item.id !== id))
|
||||
api.ResolveElevationRequest(id, approved).catch((e) => console.warn('[app] ResolveElevationRequest failed:', e))
|
||||
}}
|
||||
confirmQueue={confirmQueue}
|
||||
onResolveConfirm={(id, approved, durationMinutes, untilPhaseExit) => {
|
||||
activeConfirmIDsRef.current.delete(id)
|
||||
setConfirmQueue((q) => q.filter((item) => item.id !== id))
|
||||
api.ResolveConfirmRequest(id, approved, durationMinutes, untilPhaseExit)
|
||||
.catch((e) => fail(tr('confirmTimedOut'), e))
|
||||
}}
|
||||
discardSuspendTarget={discardSuspendTarget}
|
||||
onCancelDiscardSuspend={() => setDiscardSuspendTarget(null)}
|
||||
onConfirmDiscardSuspend={confirmDiscardSuspend}
|
||||
@@ -1532,6 +1708,19 @@ export const App: React.FC = () => {
|
||||
/>
|
||||
)}
|
||||
|
||||
{diagResult && (
|
||||
<DiagnosticsExportDialog
|
||||
locale={locale}
|
||||
result={diagResult}
|
||||
copyingFile={diagCopyingFile}
|
||||
revealingFile={diagRevealingFile}
|
||||
onCopyFile={() => { void handleCopyDiagnosticsFile() }}
|
||||
onRevealFile={() => { void handleRevealDiagnosticsFile() }}
|
||||
onCopySummary={() => { if (diagResult.summary_text) void copy(diagResult.summary_text) }}
|
||||
onClose={() => setDiagResult(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="rg-layer rg-layer-overlay" data-rg-layer="layer.overlay" aria-hidden="true" />
|
||||
</div>
|
||||
{/* Outside the isolated shell so toasts stay above dialogs and the overlay layer. */}
|
||||
|
||||
@@ -8,12 +8,13 @@ import { Button, IconButton } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { Segmented } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
import { REPO_URL, siteURL } from './TitleMenus'
|
||||
import { REPO_URL, siteURL } from '../lib/titleMenu'
|
||||
import type { UpdatePhase } from '../lib/useAppUpdate'
|
||||
import { BrandMark } from '../ui/themeVisuals'
|
||||
|
||||
const DISCORD_INVITE_URL = 'https://discord.gg/Tj682rW5rS'
|
||||
const QQ_GROUP_ID = '1136042744'
|
||||
const QQ_GROUP_INVITE_URL = 'https://qm.qq.com/q/TBmRJlVbSo'
|
||||
|
||||
type AppUpdateChannel = 'stable' | 'alpha' | 'dev'
|
||||
|
||||
@@ -100,7 +101,7 @@ export const AboutPage: React.FC<Props> = ({
|
||||
.then((ok) => { if (!cancelled) setQQInstalled(!!ok) })
|
||||
.catch((e) => {
|
||||
console.warn('[about] CanOpenQQGroup failed:', e)
|
||||
if (!cancelled) setQQInstalled(false)
|
||||
if (!cancelled) setQQLaunchErr(String(e))
|
||||
})
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
@@ -319,25 +320,23 @@ export const AboutPage: React.FC<Props> = ({
|
||||
) : null}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{onCopy && (
|
||||
<IconButton
|
||||
small
|
||||
label={tr('aboutCopyQQGroup')}
|
||||
icon={<Copy size={14} aria-hidden="true" />}
|
||||
onClick={() => onCopy(QQ_GROUP_ID)}
|
||||
/>
|
||||
)}
|
||||
{qqInstalled && !qqLaunchErr ? (
|
||||
<>
|
||||
{onCopy && (
|
||||
<IconButton
|
||||
small
|
||||
label={tr('aboutCopyQQGroup')}
|
||||
icon={<Copy size={14} aria-hidden="true" />}
|
||||
onClick={() => onCopy(QQ_GROUP_ID)}
|
||||
/>
|
||||
)}
|
||||
<Button busy={openingQQ} icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => void openQQGroup()}>
|
||||
{tr('aboutJoinQQGroup')}
|
||||
</Button>
|
||||
</>
|
||||
) : onCopy ? (
|
||||
<Button icon={<Copy size={14} aria-hidden="true" />} onClick={() => onCopy(QQ_GROUP_ID)}>
|
||||
{tr('aboutCopyQQGroup')}
|
||||
<Button busy={openingQQ} icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => void openQQGroup()}>
|
||||
{tr('aboutJoinQQGroup')}
|
||||
</Button>
|
||||
) : null}
|
||||
) : (
|
||||
<Button icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(QQ_GROUP_INVITE_URL)}>
|
||||
{tr('aboutQQOpenInvite')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,17 +2,19 @@ import React, { Suspense, lazy } from 'react'
|
||||
import type { WizardDraft } from './CreateWizard'
|
||||
import { DeleteDialog } from './DeleteDialog'
|
||||
import { ElevationDialog } from './ElevationDialog'
|
||||
import { HostConfirmDialog } from './HostConfirmDialog'
|
||||
import { CloneDialog } from './CloneDialog'
|
||||
import { SendTextDialog } from './SendTextDialog'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { hasStambhaRuntime, STAMBHA_DRIVER_ID } from '../lib/endpoints'
|
||||
import { latestVMStats } from '../lib/vmStats'
|
||||
import { vmRefKey } from '../lib/vmRef'
|
||||
import type { PluginViewRoute } from '../lib/pluginViewRouter'
|
||||
import type { AppState, CreateOpts, Locale, Task, VMDetail, VMListItem, ViewContribution } from '../types'
|
||||
import type { AppState, AutoInstallerProviderView, AutoInstallStartRequest, CreateOpts, DriverSummary, Locale, ProvisionRequest, 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'
|
||||
import { api, type ConfirmPrompt, type ElevationPrompt } from '../wails'
|
||||
|
||||
const CreateWizard = lazy(() => import('./CreateWizard').then((m) => ({ default: m.CreateWizard })))
|
||||
const SettingsModal = lazy(() => import('./SettingsModal').then((m) => ({ default: m.SettingsModal })))
|
||||
@@ -33,8 +35,11 @@ interface AppDialogsProps {
|
||||
|
||||
showWizard: boolean
|
||||
wizardDraft: WizardDraft | null
|
||||
autoInstallers?: AutoInstallerProviderView[]
|
||||
wizardDrivers: DriverSummary[]
|
||||
onCloseWizard: () => void
|
||||
onSubmitCreate: (payload: CreateOpts, draft: WizardDraft) => void
|
||||
onDriverCreated: (driverID: string, name: string) => void
|
||||
onSubmitCreate: (payload: CreateOpts, draft: WizardDraft, autoInstall?: AutoInstallStartRequest, provision?: ProvisionRequest) => void
|
||||
|
||||
showSettings: boolean
|
||||
onCloseSettings: () => void
|
||||
@@ -61,6 +66,9 @@ interface AppDialogsProps {
|
||||
elevationQueue: ElevationPrompt[]
|
||||
onResolveElevation: (id: string, approved: boolean) => void
|
||||
|
||||
confirmQueue: ConfirmPrompt[]
|
||||
onResolveConfirm: (id: string, approved: boolean, durationMinutes: number, untilPhaseExit: boolean) => void
|
||||
|
||||
discardSuspendTarget: string | null
|
||||
onCancelDiscardSuspend: () => void
|
||||
onConfirmDiscardSuspend: () => void
|
||||
@@ -87,13 +95,14 @@ export const AppDialogs: React.FC<AppDialogsProps> = (props) => {
|
||||
const {
|
||||
locale, state, detail, selectedVM, selectedIsMacOS, effectiveState,
|
||||
fixedModeSupported, diskCacheSupported, runningVMCount, tasks, displayNames,
|
||||
showWizard, wizardDraft, onCloseWizard, onSubmitCreate,
|
||||
showWizard, wizardDraft, autoInstallers, wizardDrivers, onCloseWizard, onDriverCreated, onSubmitCreate,
|
||||
showSettings, onCloseSettings, onSavedSettings,
|
||||
affinityTarget, affinityVersion, onOpenAffinity, onCloseAffinity, onAffinityApplied,
|
||||
updateConfirming, updateLatest, onCancelInstallUpdate, onConfirmInstallUpdate,
|
||||
deleteTarget, onCancelDelete, onConfirmDelete,
|
||||
closeDownloadsOpen, onCancelCloseDownloads,
|
||||
elevationQueue, onResolveElevation,
|
||||
confirmQueue, onResolveConfirm,
|
||||
discardSuspendTarget, onCancelDiscardSuspend, onConfirmDiscardSuspend,
|
||||
cloneSource, onCancelClone, onConfirmClone,
|
||||
sendTextTarget, onCancelSendText, onConfirmSendText,
|
||||
@@ -109,11 +118,16 @@ export const AppDialogs: React.FC<AppDialogsProps> = (props) => {
|
||||
<CreateWizard
|
||||
locale={locale}
|
||||
host={state.host}
|
||||
drivers={wizardDrivers}
|
||||
fixedModeSupported={fixedModeSupported}
|
||||
captureSupported={state.runtime_capture_supported}
|
||||
initialDriverID={!state.active_runtime && hasStambhaRuntime(state.runtimes) ? STAMBHA_DRIVER_ID : undefined}
|
||||
tasks={tasks}
|
||||
draft={wizardDraft}
|
||||
autoInstallers={autoInstallers}
|
||||
onCancelTask={api.CancelTask}
|
||||
onClose={onCloseWizard}
|
||||
onDriverCreated={onDriverCreated}
|
||||
onSubmit={onSubmitCreate}
|
||||
/>
|
||||
</Suspense>
|
||||
@@ -208,6 +222,15 @@ export const AppDialogs: React.FC<AppDialogsProps> = (props) => {
|
||||
/>
|
||||
)}
|
||||
|
||||
{confirmQueue.length > 0 && (
|
||||
<HostConfirmDialog
|
||||
key={confirmQueue[0].id}
|
||||
locale={locale}
|
||||
request={confirmQueue[0]}
|
||||
onResolve={(approved, durationMinutes, untilPhaseExit) => onResolveConfirm(confirmQueue[0].id, approved, durationMinutes, untilPhaseExit)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{discardSuspendTarget && (() => {
|
||||
const targetVM = findVM(discardSuspendTarget)
|
||||
const targetName = targetVM?.name ?? discardSuspendTarget
|
||||
|
||||
@@ -659,6 +659,26 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('agentTakeoverPauseTitle')}</div>
|
||||
<div className="row-sub">{tr('agentTakeoverPauseDesc')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<PopupSelect<string>
|
||||
label={tr('agentTakeoverPauseTitle')}
|
||||
value={String(config.agent_takeover_pause_sec ?? 5)}
|
||||
onChange={(v) => guard(() => api.SetAgentTakeoverPauseSec(Number(v)))()}
|
||||
options={[
|
||||
{ value: '0', label: tr('agentTakeoverPauseManual') },
|
||||
{ value: '3', label: tr('agentTakeoverPauseSeconds', { seconds: 3 }) },
|
||||
{ value: '5', label: tr('agentTakeoverPauseSeconds', { seconds: 5 }) },
|
||||
{ value: '10', label: tr('agentTakeoverPauseSeconds', { seconds: 10 }) },
|
||||
{ value: '30', label: tr('agentTakeoverPauseSeconds', { seconds: 30 }) },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('hostDNSModeTitle')}</div>
|
||||
|
||||
@@ -0,0 +1,443 @@
|
||||
import { Copy, Pause, Play, RotateCw, Square } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { AutoInstallDraftFields, defaultAutoInstallDraft, validateAutoInstallDraft } from '../lib/autoInstallDraft'
|
||||
import { AutoInstallerProviderView, AutoInstallStartRequest, AutoInstallStatus, Locale } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
|
||||
interface OCRRowProps {
|
||||
locale: Locale
|
||||
provider?: AutoInstallerProviderView
|
||||
guestLang: string
|
||||
onError?: (title: string, err: unknown) => void
|
||||
}
|
||||
|
||||
export const AutoInstallOCRStatusRow: React.FC<OCRRowProps> = ({
|
||||
locale, provider, guestLang, onError,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, vars?: Record<string, string | number>) => t(locale, k, vars)
|
||||
const [ocrStatus, setOcrStatus] = useState<{ ready: boolean; backend: string; canDownload: boolean } | null>(null)
|
||||
const [downloadingOCR, setDownloadingOCR] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!provider) {
|
||||
setOcrStatus(null)
|
||||
return
|
||||
}
|
||||
let alive = true
|
||||
api.PreflightAutoInstall(provider.plugin_id, '', '', guestLang || 'zh-Hans:0')
|
||||
.then((res) => {
|
||||
if (!alive) return
|
||||
const ocr = (res?.ocr ?? {}) as { active_backend?: string; needs_rapidocr_download?: boolean; needs_rapidocr_import?: boolean }
|
||||
const ready = typeof res?.ready === 'boolean'
|
||||
? res.ready
|
||||
: (ocr.active_backend !== 'missing' && !ocr.needs_rapidocr_download && !ocr.needs_rapidocr_import)
|
||||
setOcrStatus({
|
||||
ready,
|
||||
backend: ocr.active_backend || 'winocr',
|
||||
canDownload: res?.can_download_ocr === true,
|
||||
})
|
||||
})
|
||||
.catch((err) => {
|
||||
if (alive) console.warn('[autoinstall] preflight probe failed:', err)
|
||||
})
|
||||
return () => { alive = false }
|
||||
}, [provider?.plugin_id, guestLang])
|
||||
|
||||
const downloadOCR = async () => {
|
||||
if (!provider) return
|
||||
setDownloadingOCR(true)
|
||||
try {
|
||||
await api.DownloadAutoInstallOCR(provider.plugin_id, '')
|
||||
const res = await api.PreflightAutoInstall(provider.plugin_id, '', '', guestLang || 'zh-Hans:0')
|
||||
const ocr = (res?.ocr ?? {}) as { active_backend?: string; needs_rapidocr_download?: boolean; needs_rapidocr_import?: boolean }
|
||||
const ready = typeof res?.ready === 'boolean'
|
||||
? res.ready
|
||||
: (ocr.active_backend !== 'missing' && !ocr.needs_rapidocr_download && !ocr.needs_rapidocr_import)
|
||||
setOcrStatus({
|
||||
ready,
|
||||
backend: ocr.active_backend || 'rapidocr',
|
||||
canDownload: res?.can_download_ocr === true,
|
||||
})
|
||||
} catch (err) {
|
||||
if (onError) onError(tr('autoInstallDownloadOCR'), err)
|
||||
else console.warn('[autoinstall] download OCR failed:', err)
|
||||
} finally {
|
||||
setDownloadingOCR(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!provider || !ocrStatus) return null
|
||||
return (
|
||||
<SetRow
|
||||
title={
|
||||
ocrStatus.ready
|
||||
? tr('autoInstallOCRReady', { backend: ocrStatus.backend })
|
||||
: tr(ocrStatus.canDownload ? 'autoInstallOCRMissing' : 'autoInstallOCRMissingInstallPack')
|
||||
}
|
||||
control={!ocrStatus.ready && ocrStatus.canDownload ? (
|
||||
<Button disabled={downloadingOCR} onClick={() => void downloadOCR()}>
|
||||
{tr('autoInstallDownloadOCR')}
|
||||
</Button>
|
||||
) : undefined}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
interface FieldsProps {
|
||||
locale: Locale
|
||||
provider?: AutoInstallerProviderView
|
||||
showPluginFields?: boolean
|
||||
showOCRRow?: boolean
|
||||
showGuestToolsOption?: boolean
|
||||
showSLARow?: boolean
|
||||
guestLang: string
|
||||
draft: AutoInstallDraftFields
|
||||
onChange: (next: AutoInstallDraftFields) => void
|
||||
onError?: (title: string, err: unknown) => void
|
||||
}
|
||||
|
||||
export const AutoInstallPreflightFields: React.FC<FieldsProps> = ({
|
||||
locale, provider, showPluginFields = true, showOCRRow = true, showGuestToolsOption = false, showSLARow = true, guestLang, draft, onChange, onError,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, vars?: Record<string, string | number>) => t(locale, k, vars)
|
||||
const pluginActive = !!provider && showPluginFields
|
||||
const set = (patch: Partial<AutoInstallDraftFields>) => onChange({ ...draft, ...patch })
|
||||
|
||||
return (
|
||||
<>
|
||||
{pluginActive && showOCRRow && (
|
||||
<AutoInstallOCRStatusRow locale={locale} provider={provider} guestLang={guestLang} onError={onError} />
|
||||
)}
|
||||
<SetRow
|
||||
title={tr('autoInstallFullName')}
|
||||
control={
|
||||
<input
|
||||
className="input rg-p-input"
|
||||
aria-label={tr('autoInstallFullName')}
|
||||
value={draft.fullName}
|
||||
onChange={(e) => set({ fullName: e.target.value })}
|
||||
spellCheck={false}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('autoInstallAccountName')}
|
||||
control={
|
||||
<input
|
||||
className="input rg-p-input"
|
||||
aria-label={tr('autoInstallAccountName')}
|
||||
value={draft.accountName}
|
||||
onChange={(e) => set({ accountName: e.target.value.toLowerCase() })}
|
||||
spellCheck={false}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('autoInstallPassword')}
|
||||
control={
|
||||
<input
|
||||
type="password"
|
||||
className="input rg-p-input"
|
||||
aria-label={tr('autoInstallPassword')}
|
||||
value={draft.password}
|
||||
onChange={(e) => set({ password: e.target.value })}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('autoInstallAppearance')}
|
||||
control={
|
||||
<Segmented
|
||||
label={tr('autoInstallAppearance')}
|
||||
value={draft.appearance}
|
||||
onChange={(appearance) => set({ appearance })}
|
||||
options={[
|
||||
{ value: 'auto' as const, label: tr('autoInstallAppearanceAuto') },
|
||||
{ value: 'light' as const, label: tr('autoInstallAppearanceLight') },
|
||||
{ value: 'dark' as const, label: tr('autoInstallAppearanceDark') },
|
||||
]}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{showGuestToolsOption && (
|
||||
<SetRow
|
||||
title={tr('provisionInstallGuestTools')}
|
||||
control={
|
||||
<Switch
|
||||
label={tr('provisionInstallGuestTools')}
|
||||
checked={draft.installGuestTools}
|
||||
onChange={(installGuestTools) => set({ installGuestTools })}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{pluginActive && (
|
||||
<SetRow
|
||||
title={tr('autoInstallSaveUnlock')}
|
||||
desc={tr('autoInstallFileVaultNote')}
|
||||
control={
|
||||
<Switch
|
||||
label={tr('autoInstallSaveUnlock')}
|
||||
checked={draft.saveUnlockCredential}
|
||||
onChange={(saveUnlockCredential) => set({ saveUnlockCredential })}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{showSLARow && (
|
||||
<SetRow
|
||||
title={tr('autoInstallSLAConfirm')}
|
||||
control={
|
||||
<Switch
|
||||
label={tr('autoInstallSLAConfirm')}
|
||||
checked={draft.slaAccepted}
|
||||
onChange={(slaAccepted) => set({ slaAccepted })}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
interface VMCardProps {
|
||||
locale: Locale
|
||||
provider: AutoInstallerProviderView
|
||||
driverID: string
|
||||
vmName: string
|
||||
guestLang: string
|
||||
sessionRefreshKey?: string
|
||||
onCopy: (text: string) => void
|
||||
onError: (title: string, err: unknown) => void
|
||||
onToast: (title: string) => void
|
||||
}
|
||||
|
||||
export const VMAutoInstallPanel: React.FC<VMCardProps> = ({
|
||||
locale, provider, driverID, vmName, guestLang, sessionRefreshKey = '', onCopy, onError, onToast,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, vars?: Record<string, string | number>) => t(locale, k, vars)
|
||||
const [status, setStatus] = useState<AutoInstallStatus | null>(null)
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [draft, setDraft] = useState<AutoInstallDraftFields>(() => defaultAutoInstallDraft())
|
||||
|
||||
const refreshStatus = async (isAlive?: () => boolean) => {
|
||||
try {
|
||||
const st = await api.GetAutoInstallStatus(provider.plugin_id, driverID, vmName)
|
||||
if (isAlive && !isAlive()) return
|
||||
setStatus(st)
|
||||
} catch (err) {
|
||||
if (!isAlive || isAlive()) console.warn('[autoinstall] status refresh failed:', err)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
setStatus(null)
|
||||
}, [provider.plugin_id, driverID, vmName])
|
||||
|
||||
const active = status?.status === 'running' || status?.status === 'paused_for_user'
|
||||
const paused = status?.status === 'paused_for_user'
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true
|
||||
const check = () => alive
|
||||
void refreshStatus(check)
|
||||
return () => {
|
||||
alive = false
|
||||
}
|
||||
}, [provider.plugin_id, driverID, vmName, sessionRefreshKey])
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) return
|
||||
let alive = true
|
||||
const check = () => alive
|
||||
const id = window.setInterval(() => { void refreshStatus(check) }, 4000)
|
||||
return () => {
|
||||
alive = false
|
||||
window.clearInterval(id)
|
||||
}
|
||||
}, [active, provider.plugin_id, driverID, vmName])
|
||||
|
||||
const canStart = validateAutoInstallDraft(draft, true)
|
||||
|
||||
const start = async () => {
|
||||
if (!canStart) {
|
||||
if (!expanded) setExpanded(true)
|
||||
return
|
||||
}
|
||||
setBusy(true)
|
||||
try {
|
||||
const fullMode = draft.enabled
|
||||
const req: AutoInstallStartRequest = {
|
||||
plugin_id: provider.plugin_id,
|
||||
driver_id: driverID,
|
||||
vm_name: vmName,
|
||||
mode: fullMode ? 'full' : 'recovery_only',
|
||||
guest_lang: guestLang || 'zh-Hans:0',
|
||||
full_name: fullMode ? draft.fullName.trim() : '',
|
||||
account_name: fullMode ? draft.accountName.trim().toLowerCase() : '',
|
||||
password: fullMode ? draft.password : '',
|
||||
appearance: fullMode ? draft.appearance : undefined,
|
||||
sla_accepted: draft.slaAccepted,
|
||||
save_unlock_credential: fullMode && draft.saveUnlockCredential,
|
||||
start_vm_if_stopped: true,
|
||||
}
|
||||
await api.StartAutoInstall(req)
|
||||
setDraft((d) => ({ ...d, password: '' }))
|
||||
setExpanded(false)
|
||||
await refreshStatus()
|
||||
} catch (err) {
|
||||
onError(tr('autoInstallStart'), err)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const pause = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
await api.PauseAgentSession(driverID, vmName)
|
||||
await refreshStatus()
|
||||
} catch (err) {
|
||||
onError(tr('autoInstallPause'), err)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const resume = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
await api.ResumeAutoInstall(provider.plugin_id, driverID, vmName)
|
||||
await refreshStatus()
|
||||
} catch (err) {
|
||||
onError(tr('autoInstallResume'), err)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const stop = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
await api.StopAutoInstall(provider.plugin_id, driverID, vmName)
|
||||
await refreshStatus()
|
||||
} catch (err) {
|
||||
onError(tr('autoInstallStop'), err)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const copySummary = async () => {
|
||||
try {
|
||||
const sum = await api.GetAutoInstallDiagnosticSummary(provider.plugin_id, driverID, vmName)
|
||||
onCopy(JSON.stringify(sum, null, 2))
|
||||
onToast(tr('autoInstallSummaryCopied'))
|
||||
} catch (err) {
|
||||
onError(tr('autoInstallCopySummary'), err)
|
||||
}
|
||||
}
|
||||
|
||||
const statusText =
|
||||
status?.status === 'running' ? tr('autoInstallStatusRunning')
|
||||
: status?.status === 'paused_for_user' ? tr('autoInstallStatusPaused')
|
||||
: status?.status === 'completed' ? tr('autoInstallStatusCompleted')
|
||||
: status?.status === 'failed' ? tr('autoInstallStatusFailed')
|
||||
: tr('autoInstallDesc')
|
||||
|
||||
return (
|
||||
<SetGroup title={provider.title || tr('autoInstallTitle')}>
|
||||
<SetRow
|
||||
title={status?.message || statusText}
|
||||
desc={status?.stage_label || status?.stage || tr('autoInstallDesc')}
|
||||
control={
|
||||
<div className="hstack">
|
||||
{active && !paused && (
|
||||
<Button icon={<Pause size={14} />} disabled={busy} onClick={() => void pause()}>
|
||||
{tr('autoInstallPause')}
|
||||
</Button>
|
||||
)}
|
||||
{paused && (
|
||||
<Button variant="primary" icon={<RotateCw size={14} />} disabled={busy} onClick={() => void resume()}>
|
||||
{tr('autoInstallResume')}
|
||||
</Button>
|
||||
)}
|
||||
{active && (
|
||||
<Button variant="danger" icon={<Square size={14} />} disabled={busy} onClick={() => void stop()}>
|
||||
{tr('autoInstallStop')}
|
||||
</Button>
|
||||
)}
|
||||
{(paused || status?.unknown_page_summary) && (
|
||||
<Button icon={<Copy size={14} />} onClick={() => void copySummary()}>
|
||||
{tr('autoInstallCopySummary')}
|
||||
</Button>
|
||||
)}
|
||||
{!active && (
|
||||
<>
|
||||
<Button variant="ghost" disabled={busy} onClick={() => setExpanded((v) => !v)}>
|
||||
{tr(expanded ? 'autoInstallHideOptions' : 'autoInstallOptions')}
|
||||
</Button>
|
||||
{!expanded && (
|
||||
<Button variant="primary" icon={<Play size={14} />} disabled={busy} onClick={() => void start()}>
|
||||
{tr('autoInstallStart')}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
{!active && expanded && (
|
||||
<>
|
||||
<AutoInstallOCRStatusRow locale={locale} provider={provider} guestLang={guestLang} onError={onError} />
|
||||
<SetRow
|
||||
title={tr('autoInstallIncludeAccountToggle')}
|
||||
desc={tr('autoInstallRecoveryOnlyHint')}
|
||||
control={
|
||||
<Switch
|
||||
label={tr('autoInstallIncludeAccountToggle')}
|
||||
checked={draft.enabled}
|
||||
onChange={(enabled) => setDraft((d) => ({ ...d, enabled }))}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{draft.enabled && (
|
||||
<AutoInstallPreflightFields
|
||||
locale={locale}
|
||||
provider={provider}
|
||||
showOCRRow={false}
|
||||
showSLARow={false}
|
||||
guestLang={guestLang}
|
||||
draft={draft}
|
||||
onChange={setDraft}
|
||||
onError={onError}
|
||||
/>
|
||||
)}
|
||||
<SetRow
|
||||
title={tr('autoInstallSLAConfirm')}
|
||||
control={
|
||||
<Switch
|
||||
label={tr('autoInstallSLAConfirm')}
|
||||
checked={draft.slaAccepted}
|
||||
onChange={(slaAccepted) => setDraft((d) => ({ ...d, slaAccepted }))}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<SetRow
|
||||
title=""
|
||||
control={
|
||||
<Button variant="primary" disabled={busy || !canStart} onClick={() => void start()}>
|
||||
{tr('autoInstallStart')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</SetGroup>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Check, ChevronRight, CircleAlert, CircleCheck, CloudDownload, Copy, Disc3, HardDrive, LucideIcon, Package } from 'lucide-react'
|
||||
import React, { Suspense, lazy, useEffect, useMemo, useState } from 'react'
|
||||
import React, { Suspense, lazy, useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { useNetworkPlan } from '../lib/useNetworkPlan'
|
||||
import { NpcapDependency } from './NpcapDependency'
|
||||
import { NetworkErrorNotice } from './NetworkErrorNotice'
|
||||
@@ -44,33 +44,40 @@ import {
|
||||
switchWizardGraphics,
|
||||
toggleWizardBorderless,
|
||||
} from '../lib/displayResolution'
|
||||
import { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, Task, ValidationIssue, VMNetworkSettings } from '../types'
|
||||
import { findActiveOfflineTask, taskInstallerPhase } from '../lib/tasks'
|
||||
import { AutoInstallerProviderView, AutoInstallStartRequest, CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, ProvisionRequest, Release, Task, ValidationIssue, VMNetworkSettings } from '../types'
|
||||
import { findActiveInstallerTask, findRunningRestoreTask, taskInstallerPhase, taskStopAction, taskTitle } from '../lib/tasks'
|
||||
import { isMacOSDriver, STAMBHA_DRIVER_ID } from '../lib/endpoints'
|
||||
import { defaultGuestDriver, hasRestoreImagePicker, restoreImageField } from '../lib/guestDrivers'
|
||||
import { RestoreImageSource } from './RestoreImageSource'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { api } from '../wails'
|
||||
import { AutoInstallDraftFields, defaultAutoInstallDraft, validateAutoInstallDraft } from '../lib/autoInstallDraft'
|
||||
import { AutoInstallOCRStatusRow, AutoInstallPreflightFields } from './AutoInstallPanel'
|
||||
|
||||
const SchemaForm = lazy(() => import('./SchemaForm').then((m) => ({ default: m.SchemaForm })))
|
||||
const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos'
|
||||
|
||||
/** Reopen the wizard where the user left it (e.g. after a failed create). */
|
||||
export interface WizardDraft {
|
||||
opts: CreateOpts
|
||||
step: number
|
||||
manualResolution?: boolean
|
||||
}
|
||||
export type WizardDraft =
|
||||
| { opts: CreateOpts; step: number; manualResolution?: boolean; restoreImage?: never; name?: never }
|
||||
| { step: number; restoreImage: CachedInstaller; name: string; opts?: never; manualResolution?: never }
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
host: HostReport
|
||||
drivers: DriverSummary[]
|
||||
fixedModeSupported?: boolean
|
||||
captureSupported?: boolean
|
||||
initialDriverID?: string
|
||||
tasks?: Task[]
|
||||
draft?: WizardDraft | null
|
||||
autoInstallers?: AutoInstallerProviderView[]
|
||||
onCancelTask: (id: string) => Promise<void>
|
||||
onClose: () => void
|
||||
onDriverCreated: (driverID: string, name: string) => void
|
||||
/** Called with the cleaned payload; the caller runs the create in the background. */
|
||||
onSubmit: (payload: CreateOpts, draft: WizardDraft) => void
|
||||
onSubmit: (payload: CreateOpts, draft: WizardDraft, autoInstall?: AutoInstallStartRequest, provision?: ProvisionRequest) => void
|
||||
}
|
||||
|
||||
const REVIEW_STEP = 5
|
||||
@@ -93,7 +100,7 @@ const SOURCES: { mode: 'offline' | 'apple' | 'installer' | 'disk'; icon: LucideI
|
||||
{ mode: 'disk', icon: HardDrive, title: 'srcDiskTitle', sub: 'srcDiskSub' },
|
||||
]
|
||||
|
||||
export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported = false, captureSupported = false, tasks = [], draft, onClose, onSubmit }) => {
|
||||
export const CreateWizard: React.FC<Props> = ({ locale, host, drivers, fixedModeSupported = false, captureSupported = false, initialDriverID, tasks = [], draft, autoInstallers = [], onCancelTask, onClose, onDriverCreated, onSubmit }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [step, setStep] = useState(draft?.step ?? 1)
|
||||
// Once the user has reached the review step, keep validating so step markers stay current.
|
||||
@@ -102,25 +109,29 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
const [err, setErr] = useState('')
|
||||
const [issues, setIssues] = useState<ValidationIssue[]>([])
|
||||
const [cmdPreview, setCmdPreview] = useState('')
|
||||
const [drivers, setDrivers] = useState<DriverSummary[]>([])
|
||||
const [driverID, setDriverID] = useState(BUILTIN_MACOS_DRIVER)
|
||||
const [driverID, setDriverID] = useState(() => {
|
||||
if (!draft && initialDriverID && drivers.some((d) => d.id === initialDriverID)) return initialDriverID
|
||||
const source = draft?.restoreImage ? 'ipsw' : draft?.opts ? 'offline' : undefined
|
||||
return defaultGuestDriver(drivers, host, source)?.id ?? ''
|
||||
})
|
||||
const [driverOpts, setDriverOpts] = useState<Record<string, unknown>>({})
|
||||
const [restorePath, setRestorePath] = useState('')
|
||||
const [driverCreating, setDriverCreating] = useState(false)
|
||||
const [canceling, setCanceling] = useState(false)
|
||||
const [dependencyBusy, setDependencyBusy] = useState(false)
|
||||
const [dependencyRefresh, setDependencyRefresh] = useState(0)
|
||||
const [autoDraft, setAutoDraft] = useState<AutoInstallDraftFields>(() => defaultAutoInstallDraft())
|
||||
const [validationRefresh, setValidationRefresh] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
api.ListDrivers().then((list) => { if (live) setDrivers(list ?? []) }).catch((e) => console.warn('[wizard] ListDrivers failed:', e))
|
||||
return () => { live = false }
|
||||
}, [])
|
||||
const armImageTask = [...tasks].reverse().find((task) => task.installer_kind === 'arm-ipsw')
|
||||
const activeDriver = drivers.find((d) => d.id === driverID)
|
||||
const isCustomDriver = driverID !== BUILTIN_MACOS_DRIVER && !!activeDriver
|
||||
const legacyDriver = !!activeDriver && isMacOSDriver(activeDriver.id)
|
||||
const restoreField = activeDriver && restoreImageField(activeDriver, host)
|
||||
const updateRestorePath = useCallback((path: string) => setRestorePath(path), [])
|
||||
|
||||
const defaultGraphics = host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga'
|
||||
const [opts, setOpts] = useState<CreateOpts>(draft?.opts ?? {
|
||||
name: 'macos-tahoe',
|
||||
name: draft?.name ?? (driverID === STAMBHA_DRIVER_ID ? 'macos-arm64' : 'macos-tahoe'),
|
||||
dir: '',
|
||||
// 离线安装默认关闭网络,减少恢复环境依赖;用户仍可在第 4 步改为 NAT 或桥接。
|
||||
source_mode: 'offline',
|
||||
@@ -150,17 +161,17 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
start: true,
|
||||
})
|
||||
const [manualResolutionPicked, setManualResolutionPicked] = useState(() =>
|
||||
initialWizardManualResolution(draft),
|
||||
initialWizardManualResolution(draft?.opts ? { ...draft, opts: draft.opts } : null),
|
||||
)
|
||||
const [networkTouched, setNetworkTouched] = useState(!!draft?.opts)
|
||||
const set = (patch: Partial<CreateOpts>) => setOpts((o) => ({ ...o, ...patch }))
|
||||
const networkMode = opts.network_mode ?? (opts.network ? 'nat' : 'off')
|
||||
const [networkAdapters, setNetworkAdapters] = useState<VMNetworkSettings['adapters'] | null>(null)
|
||||
const [networkError, setNetworkError] = useState<ParsedAppError | null>(null)
|
||||
const { plan: networkPlan, planning: networkPlanning, planError: networkPlanError } = useNetworkPlan(opts.name.trim(), networkMode, opts.uplink_guid ?? '', step >= 4 && networkMode === 'bridge', `${dependencyRefresh}:${locale}`)
|
||||
const { plan: networkPlan, planning: networkPlanning, planError: networkPlanError } = useNetworkPlan(opts.name.trim(), networkMode, opts.uplink_guid ?? '', legacyDriver && step >= 4 && networkMode === 'bridge', `${dependencyRefresh}:${locale}`)
|
||||
const networkBlocked = networkMode === 'bridge' && (networkPlanning || !!networkPlanError || !networkPlan || !opts.uplink_guid)
|
||||
useEffect(() => {
|
||||
if (step !== 4 || networkMode !== 'bridge') return
|
||||
if (!legacyDriver || step !== 4 || networkMode !== 'bridge') return
|
||||
let active = true
|
||||
setNetworkError(null)
|
||||
api.ListNetworkAdapters().then((list) => {
|
||||
@@ -170,7 +181,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
if (connected.length === 1) setOpts((current) => current.uplink_guid ? current : { ...current, uplink_guid: connected[0].guid })
|
||||
}).catch((error) => { if (active) setNetworkError(parseAppError(error)) })
|
||||
return () => { active = false }
|
||||
}, [step, networkMode, locale])
|
||||
}, [legacyDriver, step, networkMode, locale])
|
||||
const windowPresets = windowDisplayPresets(host, fixedModeSupported)
|
||||
const fullscreenPresets = fullscreenDisplayPresets(host)
|
||||
const activePresets: FullscreenDisplayPreset[] = opts.borderless ? fullscreenPresets : windowPresets
|
||||
@@ -218,7 +229,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
const [cached, setCached] = useState<CachedInstaller[]>([])
|
||||
const [releasesErr, setReleasesErr] = useState('')
|
||||
useEffect(() => {
|
||||
if (opts.source_mode !== 'offline' || releases) return
|
||||
if (!legacyDriver || opts.source_mode !== 'offline' || releases) return
|
||||
let live = true
|
||||
api.ListInstallers().then((l) => { if (live) setCached(l ?? []) }).catch((e) => console.warn('[wizard] ListInstallers failed:', e))
|
||||
api.ListOfflineReleases()
|
||||
@@ -229,9 +240,9 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
})
|
||||
.catch((e) => { if (live) setReleasesErr(String(e).replace(/^Error:\s*/, '')) })
|
||||
return () => { live = false }
|
||||
}, [opts.source_mode])
|
||||
}, [legacyDriver, opts.source_mode])
|
||||
const isCached = (v: string) => cached.some((c) => c.kind === 'offline' && !c.partial && c.version === v)
|
||||
const activeRelease = (v: string) => findActiveOfflineTask(tasks, v)
|
||||
const activeRelease = (v: string) => findActiveInstallerTask(tasks, 'offline', v)
|
||||
const chosenRelease = releases?.find((r) => r.version === opts.macos)
|
||||
// reims-util pre-allocates the whole image as it starts (19.7 GB for an 18.4 GB release, measured).
|
||||
const needGB = chosenRelease && !isCached(chosenRelease.version) && !activeRelease(chosenRelease.version)
|
||||
@@ -246,7 +257,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
}, [reviewed, issues.length])
|
||||
|
||||
useEffect(() => {
|
||||
if (!reviewed && step !== REVIEW_STEP) return
|
||||
if (!legacyDriver || (!reviewed && step !== REVIEW_STEP)) return
|
||||
let live = true
|
||||
setChecking(true)
|
||||
const timer = setTimeout(() => {
|
||||
@@ -262,7 +273,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
.finally(() => { if (live) setChecking(false) })
|
||||
}, 200)
|
||||
return () => { live = false; clearTimeout(timer) }
|
||||
}, [step, reviewed, effectiveOpts, validationRefresh, captureSupported])
|
||||
}, [legacyDriver, step, reviewed, effectiveOpts, validationRefresh, captureSupported])
|
||||
|
||||
const pickDir = async () => {
|
||||
const dir = await api.PickDirectory(tr('vmDir'))
|
||||
@@ -274,9 +285,47 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
if (f) set({ [field]: f })
|
||||
}
|
||||
|
||||
const macAutoInstaller = autoInstallers.find((p) => !p.guest_families?.length || p.guest_families.includes('macos'))
|
||||
const provisionSupported = legacyDriver && (opts.source_mode === 'offline' || opts.source_mode === 'installer')
|
||||
const autoInstallSupported = provisionSupported && !!macAutoInstaller
|
||||
const provisionActive = provisionSupported && autoDraft.enabled
|
||||
const autoInstallActive = autoInstallSupported && autoDraft.autoInstall
|
||||
const autoInstallValid = (!provisionActive && !autoInstallActive) || validateAutoInstallDraft(autoDraft, true)
|
||||
|
||||
const handleCreate = () => {
|
||||
if (dependencyBusy || networkBlocked) return
|
||||
onSubmit(buildPayload(), { opts: effectiveOpts, step: REVIEW_STEP, manualResolution: manualResolutionPicked })
|
||||
if (dependencyBusy || networkBlocked || !autoInstallValid) return
|
||||
const payload = buildPayload()
|
||||
const savedDraft: WizardDraft = { opts: effectiveOpts, step: REVIEW_STEP, manualResolution: manualResolutionPicked }
|
||||
const provisionReq: ProvisionRequest | undefined = provisionActive
|
||||
? {
|
||||
full_name: autoDraft.fullName.trim(),
|
||||
account_name: autoDraft.accountName.trim().toLowerCase(),
|
||||
password: autoDraft.password,
|
||||
appearance: autoDraft.appearance,
|
||||
sla_accepted: autoDraft.slaAccepted,
|
||||
install_guest_tools: autoDraft.installGuestTools,
|
||||
}
|
||||
: undefined
|
||||
if (autoInstallActive && macAutoInstaller) {
|
||||
const autoReq: AutoInstallStartRequest = {
|
||||
plugin_id: macAutoInstaller.plugin_id,
|
||||
driver_id: activeDriver?.id || 'builtin.driver.reims-macos',
|
||||
vm_name: payload.name,
|
||||
mode: provisionActive ? 'full' : 'recovery_only',
|
||||
guest_lang: payload.guest_lang || 'zh-Hans:0',
|
||||
full_name: provisionActive ? autoDraft.fullName.trim() : '',
|
||||
account_name: provisionActive ? autoDraft.accountName.trim().toLowerCase() : '',
|
||||
password: provisionActive ? autoDraft.password : '',
|
||||
appearance: provisionActive ? autoDraft.appearance : undefined,
|
||||
sla_accepted: autoDraft.slaAccepted,
|
||||
save_unlock_credential: provisionActive && autoDraft.saveUnlockCredential,
|
||||
install_guest_tools: provisionActive ? autoDraft.installGuestTools : undefined,
|
||||
start_vm_if_stopped: true,
|
||||
}
|
||||
onSubmit({ ...payload, start: false }, savedDraft, autoReq, provisionReq)
|
||||
return
|
||||
}
|
||||
onSubmit(payload, savedDraft, undefined, provisionReq)
|
||||
}
|
||||
const issueSteps = new Set(reviewed ? issues.map(stepOfIssue) : [])
|
||||
|
||||
@@ -290,11 +339,11 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
const memMax = Math.max(Math.floor((host.total_ram_gb || 16) * 0.85), memRec, 4)
|
||||
const memGB = Math.round(parseMemoryGB(opts.memory) ?? memRec)
|
||||
const steps: I18nKey[] = ['step1', 'step2', 'step3', 'step4', 'step5']
|
||||
|
||||
const restoreTask = driverCreating ? findRunningRestoreTask(tasks, driverID, opts.name) : undefined
|
||||
|
||||
return (
|
||||
<Modal className="wizard-dialog" title={tr('wizardTitle')} closeLabel={tr('close')} onClose={onClose}>
|
||||
<nav className="wizard-steps" aria-label={tr('wizardTitle')}>
|
||||
<Modal className="wizard-dialog" title={tr('wizardTitle')} closeLabel={tr('close')} dismissable={!driverCreating} onClose={onClose}>
|
||||
{legacyDriver && <nav className="wizard-steps" aria-label={tr('wizardTitle')}>
|
||||
{steps.map((key, idx) => {
|
||||
const n = idx + 1
|
||||
const bad = issueSteps.has(n) && n !== REVIEW_STEP
|
||||
@@ -312,10 +361,16 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</nav>
|
||||
</nav>}
|
||||
|
||||
<div className="dialog-body">
|
||||
{err && <div className="notice notice-error">{err}</div>}
|
||||
{err && <div className="notice notice-error" role="alert">{err}</div>}
|
||||
{restoreTask && (
|
||||
<div role="status" className="hstack">
|
||||
<span>{taskTitle(locale, restoreTask)}</span>
|
||||
<progress aria-label={taskTitle(locale, restoreTask)} max={100} value={restoreTask.percent >= 0 ? restoreTask.percent : undefined} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div key={step} className="step-anim">
|
||||
{step === 1 && (
|
||||
@@ -324,6 +379,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
<SetGroup title={tr('wizardDriverGroup')}>
|
||||
<SetRow
|
||||
title={tr('wizardDriverType')}
|
||||
disabled={driverCreating}
|
||||
control={
|
||||
<PopupSelect
|
||||
label={tr('wizardDriverType')}
|
||||
@@ -332,27 +388,64 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
value: d.id,
|
||||
label: locText(d.name, locale, d.id),
|
||||
}))}
|
||||
onChange={(id) => { setDriverID(id); setErr('') }}
|
||||
onChange={(id) => { setDriverID(id); setDriverOpts({}); setRestorePath(''); setErr('') }}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SetGroup>
|
||||
)}
|
||||
{isCustomDriver ? (
|
||||
{!activeDriver ? <div className="notice notice-error" role="alert">{tr('wizardNoDriver')}</div> : !legacyDriver ? (
|
||||
<div className="stack-3">
|
||||
{restoreField && <RestoreImageSource
|
||||
key={activeDriver.id}
|
||||
locale={locale}
|
||||
host={host}
|
||||
tasks={tasks}
|
||||
initialImage={draft?.restoreImage}
|
||||
disabled={driverCreating}
|
||||
selectedPath={restorePath}
|
||||
onPathChange={updateRestorePath}
|
||||
onCancelTask={onCancelTask}
|
||||
/>}
|
||||
<SetGroup title={tr('wizardBasics')}>
|
||||
<SetRow
|
||||
title={tr('vmName')}
|
||||
control={<input className="input rg-p-input" value={opts.name} onChange={(e) => set({ name: e.target.value })} />}
|
||||
disabled={driverCreating}
|
||||
control={<input aria-label={tr('vmName')} className="input rg-p-input" value={opts.name} onChange={(e) => set({ name: e.target.value })} />}
|
||||
/>
|
||||
</SetGroup>
|
||||
{driverID === STAMBHA_DRIVER_ID && (
|
||||
<SetGroup title={tr('armRestoreGroup')}>
|
||||
<SetRow title={tr('armRestoreVersion')} desc={tr('armRestoreMediaHint')} control={
|
||||
<Button busy={armImageTask?.status === 'running'} onClick={() => {
|
||||
setErr('')
|
||||
void api.DownloadARMImage().catch((e) => setErr(parseAppError(e).summary))
|
||||
}}>{tr('armRestoreDownload')}</Button>
|
||||
} />
|
||||
{armImageTask?.status === 'done' && armImageTask.result && (
|
||||
<SetRow title={tr('armRestoreDownloaded')} desc={<span className="mono path-text">{armImageTask.result}</span>} />
|
||||
)}
|
||||
</SetGroup>
|
||||
)}
|
||||
{activeDriver.create_schema && (
|
||||
<Suspense fallback={null}>
|
||||
<SchemaForm
|
||||
key={activeDriver.id}
|
||||
locale={locale}
|
||||
schema={activeDriver.create_schema}
|
||||
values={driverOpts}
|
||||
disabled={driverCreating}
|
||||
hideFields={restoreField ? [restoreField] : undefined}
|
||||
onChange={setDriverOpts}
|
||||
pathFields={driverID === STAMBHA_DRIVER_ID ? {
|
||||
boot_volume: true,
|
||||
raw_disk: '*.qcow2;*.raw;*.img',
|
||||
usb_image: '*.raw;*.img;*.bin',
|
||||
} : undefined}
|
||||
filePicker={activeDriver.builtin ? {
|
||||
supports: (prop) => hasRestoreImagePicker(activeDriver, prop),
|
||||
pick: (label) => api.PickFile(label, '*.ipsw'),
|
||||
} : undefined}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
@@ -703,7 +796,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
{networkAdapters?.length === 0 && <span className="muted">{tr('bridgeNoAdapters')}</span>}
|
||||
</div>} />}
|
||||
{networkMode === 'bridge' && <>
|
||||
<NpcapDependency plan={networkPlan} locale={locale} disabled={checking || driverCreating} onBusy={setDependencyBusy} onInstalled={() => setDependencyRefresh((value) => value + 1)} />
|
||||
<NpcapDependency plan={networkPlan} locale={locale} disabled={checking} onBusy={setDependencyBusy} onInstalled={() => setDependencyRefresh((value) => value + 1)} />
|
||||
{networkPlanning && <div className="srow-desc" role="status">{tr('bridgePlanPending')}</div>}
|
||||
<NetworkErrorNotice error={networkPlanError} locale={locale} />
|
||||
</>}
|
||||
@@ -764,10 +857,14 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
host={host}
|
||||
opts={effectiveOpts}
|
||||
captureSupported={captureSupported}
|
||||
networkUplink={networkAdapters?.find((adapter) => adapter.guid === opts.uplink_guid)?.name}
|
||||
networkUplink={networkAdapters?.find((adapter) => adapter.guid === opts.uplink_guid)?.name}
|
||||
issues={issues}
|
||||
checking={checking}
|
||||
command={cmdPreview}
|
||||
provisionSupported={provisionSupported}
|
||||
autoInstaller={autoInstallSupported ? macAutoInstaller : undefined}
|
||||
autoDraft={autoDraft}
|
||||
onAutoDraft={setAutoDraft}
|
||||
onEdit={setStep}
|
||||
onName={(name) => set({ name })}
|
||||
onPickDir={pickDir}
|
||||
@@ -779,26 +876,39 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
</div>
|
||||
|
||||
<div className="dialog-foot">
|
||||
<Button variant="ghost" disabled={step === 1 || isCustomDriver} onClick={() => setStep(step - 1)}>{tr('back')}</Button>
|
||||
{isCustomDriver ? (
|
||||
{legacyDriver && <Button variant="ghost" disabled={step === 1} onClick={() => setStep(step - 1)}>{tr('back')}</Button>}
|
||||
{restoreTask && (
|
||||
<Button variant="ghost" busy={canceling} disabled={canceling} onClick={async () => {
|
||||
setCanceling(true)
|
||||
try {
|
||||
await onCancelTask(restoreTask.id)
|
||||
} catch (e) {
|
||||
setErr(parseAppError(e).summary)
|
||||
setCanceling(false)
|
||||
}
|
||||
}}>
|
||||
{taskStopAction(locale, restoreTask).label}
|
||||
</Button>
|
||||
)}
|
||||
{!legacyDriver ? (
|
||||
<Button
|
||||
variant="primary"
|
||||
busy={driverCreating}
|
||||
disabled={!opts.name.trim() || driverCreating}
|
||||
disabled={!activeDriver || !opts.name.trim() || driverCreating || (!!restoreField && !restorePath.trim())}
|
||||
onClick={async () => {
|
||||
const name = opts.name.trim()
|
||||
setDriverCreating(true)
|
||||
setErr('')
|
||||
try {
|
||||
await api.CreateVMWithDriver({
|
||||
driver_id: driverID,
|
||||
name: opts.name.trim(),
|
||||
dir: opts.dir,
|
||||
options: driverOpts,
|
||||
})
|
||||
const options = restoreField ? { ...driverOpts, [restoreField]: restorePath.trim() } : driverOpts
|
||||
await api.CreateVMWithDriver({ driver_id: driverID, name, dir: driverID === STAMBHA_DRIVER_ID ? '' : opts.dir, options })
|
||||
onDriverCreated(driverID, name)
|
||||
onClose()
|
||||
} catch (e) {
|
||||
setErr(parseAppError(e).summary)
|
||||
const message = parseAppError(e).summary
|
||||
setErr(/\bcontext canceled\b/i.test(message) ? tr('toastCreateCanceled', { name }) : message)
|
||||
} finally {
|
||||
setCanceling(false)
|
||||
setDriverCreating(false)
|
||||
}
|
||||
}}
|
||||
@@ -810,8 +920,8 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
) : (
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={dependencyBusy || checking || !!err || issues.length > 0 || !cmdPreview || networkBlocked}
|
||||
title={tr('createStartedHint')}
|
||||
disabled={dependencyBusy || checking || !!err || issues.length > 0 || !cmdPreview || networkBlocked || !autoInstallValid}
|
||||
title={!autoInstallValid ? tr('autoInstallSLAConfirm') : tr('createStartedHint')}
|
||||
onClick={handleCreate}
|
||||
>
|
||||
{tr('createNow')}
|
||||
@@ -823,7 +933,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
}
|
||||
|
||||
interface ReviewProps {
|
||||
networkUplink?: string
|
||||
networkUplink?: string
|
||||
locale: Locale
|
||||
host: HostReport
|
||||
opts: CreateOpts
|
||||
@@ -831,6 +941,10 @@ interface ReviewProps {
|
||||
issues: ValidationIssue[]
|
||||
checking: boolean
|
||||
command: string
|
||||
provisionSupported: boolean
|
||||
autoInstaller?: AutoInstallerProviderView
|
||||
autoDraft: AutoInstallDraftFields
|
||||
onAutoDraft: (next: AutoInstallDraftFields) => void
|
||||
onEdit: (step: number) => void
|
||||
onName: (name: string) => void
|
||||
onDir: (dir: string) => void
|
||||
@@ -843,7 +957,7 @@ type Row = { label: string; value: string; mono?: boolean }
|
||||
const fileName = (p?: string) => (p ?? '').split(/[\\/]/).pop() || (p ?? '')
|
||||
|
||||
/** Step ⑤: what will be created, grouped by the step that set it, with the CLI equivalent folded away. */
|
||||
const Review: React.FC<ReviewProps> = ({ locale, host, opts, captureSupported, issues, checking, command, onEdit, onName, onDir, onPickDir, onStartAfter, networkUplink }) => {
|
||||
const Review: React.FC<ReviewProps> = ({ locale, host, opts, captureSupported, issues, checking, command, provisionSupported, autoInstaller, autoDraft, onAutoDraft, onEdit, onName, onDir, onPickDir, onStartAfter, networkUplink }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [copied, setCopied] = useState(false)
|
||||
const onOff = (b?: boolean) => tr(b ? 'summaryOn' : 'off')
|
||||
@@ -941,10 +1055,74 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, captureSupported, i
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('startAfterCreate')}
|
||||
control={<Switch label={tr('startAfterCreate')} checked={!!opts.start} onChange={onStartAfter} />}
|
||||
disabled={!!autoInstaller && autoDraft.autoInstall}
|
||||
control={<Switch label={tr('startAfterCreate')} checked={!!opts.start || (!!autoInstaller && autoDraft.autoInstall)} disabled={!!autoInstaller && autoDraft.autoInstall} onChange={onStartAfter} />}
|
||||
/>
|
||||
</SetGroup>
|
||||
|
||||
{provisionSupported && (
|
||||
<SetGroup title={tr(autoInstaller ? 'autoSetupGroupTitle' : 'provisionGroupTitle')}>
|
||||
{autoInstaller && (
|
||||
<>
|
||||
<SetRow
|
||||
title={tr('autoRecoveryToggle')}
|
||||
desc={tr('autoRecoveryDesc')}
|
||||
control={
|
||||
<Switch
|
||||
label={tr('autoRecoveryToggle')}
|
||||
checked={autoDraft.autoInstall}
|
||||
onChange={(autoInstall) => onAutoDraft({ ...autoDraft, autoInstall })}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{autoDraft.autoInstall && (
|
||||
<AutoInstallOCRStatusRow
|
||||
locale={locale}
|
||||
provider={autoInstaller}
|
||||
guestLang={opts.guest_lang || 'zh-Hans:0'}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<SetRow
|
||||
title={tr('provisionToggle')}
|
||||
desc={tr('provisionDesc')}
|
||||
control={
|
||||
<Switch
|
||||
label={tr('provisionToggle')}
|
||||
checked={autoDraft.enabled}
|
||||
onChange={(enabled) => onAutoDraft({ ...autoDraft, enabled })}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{autoDraft.enabled ? (
|
||||
<AutoInstallPreflightFields
|
||||
locale={locale}
|
||||
provider={autoInstaller}
|
||||
showPluginFields={!!autoInstaller && autoDraft.autoInstall}
|
||||
showOCRRow={false}
|
||||
showGuestToolsOption={true}
|
||||
guestLang={opts.guest_lang || 'zh-Hans:0'}
|
||||
draft={autoDraft}
|
||||
onChange={onAutoDraft}
|
||||
/>
|
||||
) : (
|
||||
!!autoInstaller && autoDraft.autoInstall && (
|
||||
<SetRow
|
||||
title={tr('autoInstallSLAConfirm')}
|
||||
control={
|
||||
<Switch
|
||||
label={tr('autoInstallSLAConfirm')}
|
||||
checked={autoDraft.slaAccepted}
|
||||
onChange={(slaAccepted) => onAutoDraft({ ...autoDraft, slaAccepted })}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</SetGroup>
|
||||
)}
|
||||
|
||||
{checking && issues.length === 0 ? (
|
||||
<div className="review-status">{tr('validationChecking')}</div>
|
||||
) : issues.length > 0 ? (
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import { AlertCircle, AlertTriangle, Archive, Copy, FolderOpen, Info } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { formatBytes } from '../lib/format'
|
||||
import { DiagnosticFinding, DiagnosticsExportResult, Locale } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { HostIcon } from '../ui/themeVisuals'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
result: DiagnosticsExportResult
|
||||
copyingFile?: boolean
|
||||
revealingFile?: boolean
|
||||
onCopyFile: () => void
|
||||
onRevealFile: () => void
|
||||
onCopySummary: () => void
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
const FINDING_COPY: Record<DiagnosticFinding['code'], { title: I18nKey; desc: I18nKey }> = {
|
||||
gpu_device_lost: { title: 'diagFindingGpuDeviceLostTitle', desc: 'diagFindingGpuDeviceLostDesc' },
|
||||
gpu_vulkan_floor: { title: 'diagFindingGpuVulkanFloorTitle', desc: 'diagFindingGpuVulkanFloorDesc' },
|
||||
whpx_unavailable: { title: 'diagFindingWhpxUnavailableTitle', desc: 'diagFindingWhpxUnavailableDesc' },
|
||||
low_memory: { title: 'diagFindingLowMemoryTitle', desc: 'diagFindingLowMemoryDesc' },
|
||||
low_disk: { title: 'diagFindingLowDiskTitle', desc: 'diagFindingLowDiskDesc' },
|
||||
}
|
||||
|
||||
export const DiagnosticsExportDialog: React.FC<Props> = ({
|
||||
locale,
|
||||
result,
|
||||
copyingFile = false,
|
||||
revealingFile = false,
|
||||
onCopyFile,
|
||||
onRevealFile,
|
||||
onCopySummary,
|
||||
onClose,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const findings = result.findings ?? []
|
||||
const includedFiles = result.included_files ?? []
|
||||
const sizeText = result.size_bytes > 0 ? formatBytes(result.size_bytes, locale) : ''
|
||||
const subtitle = [result.file_name, sizeText].filter(Boolean).join(' · ')
|
||||
const busy = copyingFile || revealingFile
|
||||
|
||||
return (
|
||||
<Modal
|
||||
className="md"
|
||||
title={tr('diagDialogTitle')}
|
||||
subtitle={subtitle}
|
||||
closeLabel={tr('close')}
|
||||
onClose={onClose}
|
||||
>
|
||||
<div className="dialog-body">
|
||||
<div className="diag-findings">
|
||||
{findings.length > 0 ? (
|
||||
findings.map((finding, idx) => {
|
||||
const isError = finding.severity === 'error'
|
||||
const copyKeys = FINDING_COPY[finding.code]
|
||||
const title = copyKeys ? tr(copyKeys.title) : finding.code
|
||||
const desc = copyKeys ? tr(copyKeys.desc) : ''
|
||||
return (
|
||||
<div
|
||||
key={`${finding.code}-${idx}`}
|
||||
className={`notice ${isError ? 'notice-error' : 'notice-warn'} diag-finding`}
|
||||
role={isError ? 'alert' : 'status'}
|
||||
>
|
||||
<div className="notice-main">
|
||||
<span className="notice-icon" aria-hidden="true">
|
||||
<HostIcon name={isError ? 'error' : 'warning'}>
|
||||
{isError ? <AlertCircle size={15} /> : <AlertTriangle size={15} />}
|
||||
</HostIcon>
|
||||
</span>
|
||||
<div className="notice-text">
|
||||
<div className="notice-title">{title}</div>
|
||||
{desc && <div className="notice-sub">{desc}</div>}
|
||||
{finding.detail && (
|
||||
<details className="network-error-details diag-finding-details">
|
||||
<summary>{tr('errRawDetailsToggle')}</summary>
|
||||
<pre className="selectable">{finding.detail}</pre>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
) : (
|
||||
<div className="notice notice-info" role="status">
|
||||
<div className="notice-main">
|
||||
<span className="notice-icon" aria-hidden="true">
|
||||
<HostIcon name="info"><Info size={15} /></HostIcon>
|
||||
</span>
|
||||
<div className="notice-text">
|
||||
<div className="notice-title">{tr('diagNoFindingsTitle')}</div>
|
||||
<div className="notice-sub">{tr('diagNoFindingsDesc')}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<section className="diag-card" aria-label={tr('diagChecklistTitle')}>
|
||||
<div className="diag-card-title">{tr('diagChecklistTitle')}</div>
|
||||
<ul className="diag-checklist">
|
||||
<li>{tr('diagChecklistZip')}</li>
|
||||
<li>{tr('diagChecklistSteps')}</li>
|
||||
</ul>
|
||||
{includedFiles.length > 0 && (
|
||||
<div className="diag-files-section">
|
||||
<div className="diag-files-label">{tr('diagIncludedFiles')}</div>
|
||||
<div className="diag-files">
|
||||
{includedFiles.map((file) => (
|
||||
<span key={file} className="diag-file-pill selectable">{file}</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{result.summary_text && (
|
||||
<details className="diag-summary-details">
|
||||
<summary>{tr('diagSummaryToggle')}</summary>
|
||||
<pre className="diag-summary-pre selectable">{result.summary_text}</pre>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="dialog-foot">
|
||||
<div className="diag-foot-secondary">
|
||||
<Button
|
||||
icon={<Copy size={14} aria-hidden="true" />}
|
||||
disabled={!result.summary_text || busy}
|
||||
onClick={onCopySummary}
|
||||
>
|
||||
{tr('diagCopySummary')}
|
||||
</Button>
|
||||
{result.can_copy_file && (
|
||||
<Button
|
||||
icon={<FolderOpen size={14} aria-hidden="true" />}
|
||||
busy={revealingFile}
|
||||
disabled={copyingFile}
|
||||
onClick={onRevealFile}
|
||||
>
|
||||
{tr('diagRevealFile')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{result.can_copy_file ? (
|
||||
<Button
|
||||
variant="primary"
|
||||
icon={<Archive size={14} aria-hidden="true" />}
|
||||
busy={copyingFile}
|
||||
disabled={revealingFile}
|
||||
onClick={onCopyFile}
|
||||
>
|
||||
{tr('diagCopyArchive')}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="primary"
|
||||
icon={<FolderOpen size={14} aria-hidden="true" />}
|
||||
busy={revealingFile}
|
||||
onClick={onRevealFile}
|
||||
>
|
||||
{tr('diagRevealFile')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import * as Alert from '@radix-ui/react-alert-dialog'
|
||||
import React, { useRef, useState } from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { Locale } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { PopupSelect } from '../ui/settings'
|
||||
import type { ConfirmPrompt } from '../wails'
|
||||
|
||||
type DurationChoice = '10' | '30' | '60' | 'until_phase_exit'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
request: ConfirmPrompt
|
||||
onResolve: (approved: boolean, durationMinutes: number, untilPhaseExit: boolean) => void
|
||||
}
|
||||
|
||||
export const HostConfirmDialog: React.FC<Props> = ({ locale, request, onResolve }) => {
|
||||
const cancelRef = useRef<HTMLButtonElement | null>(null)
|
||||
const resolvedRef = useRef(false)
|
||||
const initialChoice: DurationChoice = request.prefer_until_phase_exit
|
||||
? 'until_phase_exit'
|
||||
: request.default_duration_minutes === 10
|
||||
? '10'
|
||||
: request.default_duration_minutes === 60
|
||||
? '60'
|
||||
: '30'
|
||||
const [duration, setDuration] = useState<DurationChoice>(initialChoice)
|
||||
|
||||
const resolveOnce = (approved: boolean) => {
|
||||
if (resolvedRef.current) return
|
||||
resolvedRef.current = true
|
||||
const untilExit = duration === 'until_phase_exit'
|
||||
const mins = untilExit ? 0 : Number(duration) || 30
|
||||
onResolve(approved, mins, untilExit)
|
||||
}
|
||||
|
||||
const prevFocusRef = useRef<HTMLElement | null>(
|
||||
typeof document !== 'undefined' && document.activeElement instanceof HTMLElement
|
||||
? document.activeElement
|
||||
: null,
|
||||
)
|
||||
|
||||
const sourceDetail = [request.publisher, request.trust].filter(Boolean).join(' · ')
|
||||
const allowLabel = request.confirm_label || t(locale, 'confirmAllow')
|
||||
const denyLabel = request.cancel_label || t(locale, 'confirmDeny')
|
||||
|
||||
return (
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) resolveOnce(false) }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content
|
||||
className="dialog rg-p-dialog sm"
|
||||
data-tone={request.danger ? 'warn' : 'info'}
|
||||
onOpenAutoFocus={(e) => {
|
||||
e.preventDefault()
|
||||
cancelRef.current?.focus({ preventScroll: true })
|
||||
}}
|
||||
onCloseAutoFocus={(e) => {
|
||||
e.preventDefault()
|
||||
const prev = prevFocusRef.current
|
||||
if (prev?.isConnected) prev.focus({ preventScroll: true })
|
||||
}}
|
||||
>
|
||||
<div className="dialog-body">
|
||||
<Alert.Title className="dialog-title">{request.title}</Alert.Title>
|
||||
<div className="stack-2" style={{ marginTop: 'var(--sp-2)', fontSize: 'var(--fs-13)' }}>
|
||||
<div className="muted">
|
||||
{t(locale, 'elevateSource', { name: request.plugin_name || request.plugin_id })}
|
||||
{sourceDetail ? ` (${sourceDetail})` : ''}
|
||||
</div>
|
||||
<Alert.Description className="dialog-desc" style={{ marginTop: 0 }}>{request.message}</Alert.Description>
|
||||
{request.kind === 'protected_phase' && (
|
||||
<div className="muted">{t(locale, 'confirmPhaseScope')}</div>
|
||||
)}
|
||||
{request.allow_duration_choice && (
|
||||
<div className="hstack" style={{ justifyContent: 'space-between', marginTop: 'var(--sp-2)' }}>
|
||||
<span>{t(locale, 'confirmDurationLabel')}</span>
|
||||
<PopupSelect<DurationChoice>
|
||||
label={t(locale, 'confirmDurationLabel')}
|
||||
value={duration}
|
||||
onChange={setDuration}
|
||||
options={[
|
||||
{ value: '10', label: t(locale, 'confirmDuration10') },
|
||||
{ value: '30', label: t(locale, 'confirmDuration30') },
|
||||
{ value: '60', label: t(locale, 'confirmDuration60') },
|
||||
{ value: 'until_phase_exit', label: t(locale, 'confirmDurationUntilExit') },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild>
|
||||
<Button ref={cancelRef} autoFocus onClick={() => resolveOnce(false)}>{denyLabel}</Button>
|
||||
</Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<Button variant={request.danger ? 'danger' : 'primary'} onClick={() => resolveOnce(true)}>{allowLabel}</Button>
|
||||
</Alert.Action>
|
||||
</div>
|
||||
</Alert.Content>
|
||||
</Alert.Portal>
|
||||
</Alert.Root>
|
||||
)
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import '../i18n/domains/wizard.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { formatBytes, gpuCompatHint, gpuKey, gpuMetaLine, sameGPU } from '../lib/format'
|
||||
import { describeHostWHPX } from '../lib/hypervisor'
|
||||
import { STAMBHA_RUNTIME_KIND } from '../lib/endpoints'
|
||||
import { isAppleSilicon } from '../lib/guestDrivers'
|
||||
import { AppState, Locale, StorageBreakdown, Task } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { Switch } from '../ui/settings'
|
||||
@@ -17,6 +19,7 @@ interface Props {
|
||||
locale: Locale
|
||||
onRefresh: () => Promise<void>
|
||||
onNewVM?: () => void
|
||||
hostReady: boolean
|
||||
onError: (title: string, e: unknown) => void
|
||||
onToast?: (title: string) => void
|
||||
runtimeTask: Task | null
|
||||
@@ -26,7 +29,7 @@ interface Props {
|
||||
onCancelTask: (id: string) => void
|
||||
}
|
||||
|
||||
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, onError, onToast, runtimeTask, onChannel, onInstallRuntime, onImportRuntime, onCancelTask }) => {
|
||||
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, hostReady, onError, onToast, runtimeTask, onChannel, onInstallRuntime, onImportRuntime, onCancelTask }) => {
|
||||
const [importing, setImporting] = useState(false)
|
||||
const [enabling, setEnabling] = useState(false)
|
||||
const [savingASLR, setSavingASLR] = useState(false)
|
||||
@@ -43,7 +46,13 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
|
||||
return () => { live = false }
|
||||
}, [state.config.data_root, state.vms?.length, state.runtimes?.length])
|
||||
|
||||
const whpx = describeHostWHPX(locale, host)
|
||||
const nativeHost = isAppleSilicon(host)
|
||||
const virtualization = nativeHost ? {
|
||||
short: tr(hostReady ? 'hostReady' : 'hostNeedsAction'),
|
||||
hint: host.apple_virtualization?.detail,
|
||||
tone: hostReady ? 'ok' : 'warn',
|
||||
canEnable: false,
|
||||
} : describeHostWHPX(locale, host)
|
||||
|
||||
const guard = (fn: () => Promise<unknown>) => async () => {
|
||||
try {
|
||||
@@ -111,7 +120,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{(state.vms?.length ?? 0) === 0 && host.whpx === 'ready' && !!state.active_runtime && onNewVM && (
|
||||
{(state.vms?.length ?? 0) === 0 && hostReady && onNewVM && (
|
||||
<section className="welcome-card">
|
||||
<h1>{tr('welcomeTitle')}</h1>
|
||||
<p>{tr('welcomeSub')}</p>
|
||||
@@ -124,14 +133,14 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
|
||||
<div className="tiles">
|
||||
<div className="tile">
|
||||
<div className="tile-head">
|
||||
<span className={`tile-icon ${whpx.tone}`} aria-hidden="true"><ShieldCheck size={13} /></span>
|
||||
{tr('whpxTitle')}
|
||||
<span className={`tile-icon ${virtualization.tone}`} aria-hidden="true"><ShieldCheck size={13} /></span>
|
||||
{tr(nativeHost ? 'appleVirtualizationTitle' : 'whpxTitle')}
|
||||
</div>
|
||||
<div className={`tile-value ${whpx.tone}`}>{whpx.short}</div>
|
||||
{whpx.canEnable ? (
|
||||
<div className={`tile-value ${virtualization.tone}`}>{virtualization.short}</div>
|
||||
{virtualization.canEnable ? (
|
||||
<Button variant="primary" className="tile-action" busy={enabling} onClick={enableWHPX}>{tr('enableWHPX')}</Button>
|
||||
) : whpx.hint ? (
|
||||
<div className="tile-sub" title={whpx.hint}>{whpx.hint}</div>
|
||||
) : virtualization.hint ? (
|
||||
<div className="tile-sub" title={virtualization.hint}>{virtualization.hint}</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="tile">
|
||||
@@ -149,13 +158,17 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
|
||||
<span className="tile-icon accent" aria-hidden="true"><MemoryStick size={13} /></span>
|
||||
{tr('hostRAM')}
|
||||
</div>
|
||||
<div className="tile-value">{tr('hostRAMAvail', { n: host.avail_ram_gb.toFixed(1) })}</div>
|
||||
<div className="tile-sub">
|
||||
<div className="tile-value">
|
||||
{host.memory_usage_known
|
||||
? tr('hostRAMAvail', { n: host.avail_ram_gb.toFixed(1) })
|
||||
: host.total_ram_gb > 0 ? tr('hostRAMTotal', { n: host.total_ram_gb.toFixed(1) }) : '—'}
|
||||
</div>
|
||||
{host.memory_usage_known && <div className="tile-sub">
|
||||
{tr('hostRAMTotal', { n: host.total_ram_gb.toFixed(1) })}
|
||||
{host.memory_spec?.speed_mhz
|
||||
? ` · ${host.memory_spec.speed_mhz} MHz${host.memory_spec.type_name ? ` ${host.memory_spec.type_name}` : ''}`
|
||||
: ''}
|
||||
</div>
|
||||
</div>}
|
||||
</div>
|
||||
<div className="tile">
|
||||
<div className="tile-head">
|
||||
@@ -201,7 +214,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
|
||||
)
|
||||
})()}
|
||||
|
||||
<section className="section">
|
||||
{!nativeHost && <section className="section">
|
||||
<div className="section-title">
|
||||
{tr('hostRuntime')}
|
||||
<Button variant="ghost" busy={importing} onClick={importRuntime}>
|
||||
@@ -228,47 +241,55 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
|
||||
<Switch label={tr('qemuASLR')} checked={!!config.qemu_aslr} disabled={savingASLR} onChange={setQEMUASLR} />
|
||||
</div>
|
||||
</div>
|
||||
{(runtimes ?? []).filter((rt) => !rt.active).map((rt) => (
|
||||
<div className="row" key={rt.commit}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className="mono">{rt.commit}</span>
|
||||
{latestRuntimeCommit && sameRuntimeId(rt.commit, latestRuntimeCommit) && (
|
||||
<span className="badge rg-p-badge badge-ok">{tr('runtimeLatestBadge')}</span>
|
||||
{(runtimes ?? []).filter((rt) => !rt.active).map((rt) => {
|
||||
const stambha = rt.kind === STAMBHA_RUNTIME_KIND
|
||||
const ref = stambha ? STAMBHA_RUNTIME_KIND + '/' + rt.commit : rt.commit
|
||||
return (
|
||||
<div className="row" key={ref}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className="mono">{stambha ? rt.manifest.name || rt.commit : rt.commit}</span>
|
||||
{(stambha || !rt.kind || rt.kind === 'reims-vgpu') &&
|
||||
<span className="badge rg-p-badge">{tr(stambha ? 'armRuntimeLabel' : 'x86RuntimeLabel')}</span>}
|
||||
{!stambha && latestRuntimeCommit && sameRuntimeId(rt.commit, latestRuntimeCommit) && (
|
||||
<span className="badge rg-p-badge badge-ok">{tr('runtimeLatestBadge')}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-sub">{rt.manifest.qemu_version?.replace(/^QEMU emulator version\s*/i, 'QEMU ')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{confirmDelete === ref ? (
|
||||
<>
|
||||
<Button variant="ghost" disabled={removing === ref} onClick={() => setConfirmDelete('')}>
|
||||
{tr('cancel')}
|
||||
</Button>
|
||||
<Button variant="danger" busy={removing === ref} onClick={() => removeRuntime(ref)}>
|
||||
{tr('runtimeDeleteConfirm')}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{!stambha && (
|
||||
<Button disabled={removing === ref} onClick={guard(() => api.UseRuntime(rt.commit))}>
|
||||
{tr('activate')}
|
||||
</Button>
|
||||
)}
|
||||
<IconButton
|
||||
label={tr('runtimeDelete')}
|
||||
icon={<Trash size={15} />}
|
||||
disabled={removing !== ''}
|
||||
onClick={() => setConfirmDelete(ref)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-sub">{rt.manifest.qemu_version.replace(/^QEMU emulator version\s*/i, 'QEMU ')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{confirmDelete === rt.commit ? (
|
||||
<>
|
||||
<Button variant="ghost" disabled={removing === rt.commit} onClick={() => setConfirmDelete('')}>
|
||||
{tr('cancel')}
|
||||
</Button>
|
||||
<Button variant="danger" busy={removing === rt.commit} onClick={() => removeRuntime(rt.commit)}>
|
||||
{tr('runtimeDeleteConfirm')}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Button disabled={removing === rt.commit} onClick={guard(() => api.UseRuntime(rt.commit))}>
|
||||
{tr('activate')}
|
||||
</Button>
|
||||
<IconButton
|
||||
label={tr('runtimeDelete')}
|
||||
icon={<Trash size={15} />}
|
||||
disabled={removing !== ''}
|
||||
onClick={() => setConfirmDelete(rt.commit)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
</section>}
|
||||
|
||||
<section className="section">
|
||||
{!nativeHost && <section className="section">
|
||||
<div className="section-title">{tr('hostGPUs')}</div>
|
||||
<div className="list">
|
||||
{realGPUs.length === 0 ? (
|
||||
@@ -296,7 +317,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
</section>}
|
||||
{(host.displays?.length ?? 0) > 0 && (
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('hostDisplays')}</div>
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { AlertTriangle, ArrowDown, ChevronDown, ChevronUp, Copy, Eraser, LoaderCircle, Pause, RefreshCw, X } from 'lucide-react'
|
||||
import { AlertTriangle, Archive, ArrowDown, ChevronDown, ChevronUp, Copy, Eraser, LoaderCircle, Pause, RefreshCw, X } from 'lucide-react'
|
||||
import React, { useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { LogLine } from '../lib/logs'
|
||||
import { LogLine, countLogLines, formatLogLines, formatSelectedLogRows, isLargeLogPayload } from '../lib/logs'
|
||||
import { taskDetail, taskInstallerPhase, taskStopAction, taskTitle } from '../lib/tasks'
|
||||
import { HostReport, Locale, Task } from '../types'
|
||||
import { Button, IconButton, Tip } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { HostIcon } from '../ui/themeVisuals'
|
||||
|
||||
export type LogTab = 'app' | 'serial' | 'qemu'
|
||||
@@ -29,6 +30,8 @@ interface Props {
|
||||
host?: HostReport
|
||||
runningVMs?: number
|
||||
onCopy?: (text: string) => void
|
||||
onExportDiagnostics?: () => void
|
||||
exportingDiagnostics?: boolean
|
||||
/** False when WHPX or the runtime needs attention; the bar then leads with a link to the host page. */
|
||||
hostReady?: boolean
|
||||
onOpenHost?: () => void
|
||||
@@ -73,11 +76,12 @@ const MAX_LOG_HEIGHT = 520
|
||||
|
||||
export const LogPanel: React.FC<Props> = ({
|
||||
locale, open, onToggle, tab, onTab, lines, unseenErrors, onClear, serialText, qemuText, showSerial, onRefreshSerial, onRefreshQemu,
|
||||
task, runningTasks, onCancelTask, host, runningVMs = 0, onCopy, hostReady = true, onOpenHost,
|
||||
task, runningTasks, onCancelTask, host, runningVMs = 0, onCopy, onExportDiagnostics, exportingDiagnostics = false, hostReady = true, onOpenHost,
|
||||
}) => {
|
||||
const tr = (k: Parameters<typeof t>[1], v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [query, setQuery] = useState('')
|
||||
const [errorsOnly, setErrorsOnly] = useState(false)
|
||||
const [largeCopyPending, setLargeCopyPending] = useState<{ text: string; lines: number } | null>(null)
|
||||
|
||||
const q = query.trim().toLowerCase()
|
||||
const filteredLines = useMemo(() => {
|
||||
@@ -98,26 +102,66 @@ export const LogPanel: React.FC<Props> = ({
|
||||
return raw.split('\n').filter((line) => line.toLowerCase().includes(q)).join('\n')
|
||||
}, [tab, serialText, qemuText, q])
|
||||
|
||||
const requestCopy = (text: string) => {
|
||||
if (!text || !onCopy) return
|
||||
if (onExportDiagnostics && isLargeLogPayload(text)) {
|
||||
setLargeCopyPending({ text, lines: countLogLines(text) })
|
||||
return
|
||||
}
|
||||
onCopy(text)
|
||||
}
|
||||
|
||||
const copyVisible = () => {
|
||||
if (!onCopy) return
|
||||
const txt = tab === 'app' ? formatLogLines(filteredLines) : filteredText
|
||||
if (txt) requestCopy(txt)
|
||||
}
|
||||
|
||||
const handleBodyCopy = (e: React.ClipboardEvent<HTMLDivElement>) => {
|
||||
const sel = window.getSelection()
|
||||
if (!sel || sel.isCollapsed || sel.rangeCount === 0) return
|
||||
const range = sel.getRangeAt(0)
|
||||
if (!e.currentTarget.contains(range.commonAncestorContainer)) return
|
||||
|
||||
if (tab === 'app') {
|
||||
const txt = filteredLines.map((l) => `${l.ts} [${l.source}] ${l.line}`).join('\n')
|
||||
if (txt) onCopy(txt)
|
||||
} else if (filteredText) {
|
||||
onCopy(filteredText)
|
||||
const lineEls = Array.from(e.currentTarget.querySelectorAll<HTMLElement>('.log-line')).filter((el) => {
|
||||
try {
|
||||
return range.intersectsNode(el)
|
||||
} catch (err) {
|
||||
console.warn('[logPanel] selection intersectsNode failed:', err)
|
||||
return false
|
||||
}
|
||||
})
|
||||
if (lineEls.length >= 2) {
|
||||
const normalized = formatSelectedLogRows(
|
||||
lineEls.map((el) => ({
|
||||
ts: el.querySelector('.log-ts')?.textContent ?? '',
|
||||
source: el.querySelector('.log-src')?.textContent ?? '',
|
||||
line: el.querySelector('.log-msg')?.textContent ?? '',
|
||||
})),
|
||||
)
|
||||
if (onExportDiagnostics && isLargeLogPayload(normalized)) {
|
||||
e.preventDefault()
|
||||
setLargeCopyPending({ text: normalized, lines: countLogLines(normalized) })
|
||||
return
|
||||
}
|
||||
e.preventDefault()
|
||||
e.clipboardData.setData('text/plain', normalized)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const selectedText = sel.toString()
|
||||
if (onExportDiagnostics && isLargeLogPayload(selectedText)) {
|
||||
e.preventDefault()
|
||||
setLargeCopyPending({ text: selectedText, lines: countLogLines(selectedText) })
|
||||
}
|
||||
}
|
||||
|
||||
const content = tab === 'app' ? filteredLines : filteredText
|
||||
const { ref, stuck, onScroll, jump } = useStickToBottom(content, open)
|
||||
|
||||
const memPct = host
|
||||
? Math.max(0, Math.min(100, host.memory_load_pct > 0
|
||||
? host.memory_load_pct
|
||||
: host.total_ram_gb > 0
|
||||
? Math.round(((host.total_ram_gb - host.avail_ram_gb) / host.total_ram_gb) * 100)
|
||||
: 0))
|
||||
: 0
|
||||
const memPct = Math.max(0, Math.min(100, host?.memory_load_pct ?? 0))
|
||||
const usedMemGB = host && host.total_ram_gb > 0 ? Math.max(0, host.total_ram_gb - host.avail_ram_gb) : 0
|
||||
const memTone = memPct >= 90 ? ' high' : memPct >= 80 ? ' warn' : ''
|
||||
const lowDisk = !!host && host.free_disk_gb > 0 && host.free_disk_gb < 30
|
||||
@@ -247,7 +291,7 @@ export const LogPanel: React.FC<Props> = ({
|
||||
</button>
|
||||
</Tip>
|
||||
)}
|
||||
{host.total_ram_gb > 0 && (
|
||||
{host.memory_usage_known && host.total_ram_gb > 0 && (
|
||||
<Tip
|
||||
side="top"
|
||||
label={tr('footerMemTip', {
|
||||
@@ -338,6 +382,16 @@ export const LogPanel: React.FC<Props> = ({
|
||||
{open && onCopy && (
|
||||
<IconButton small tipSide="top" label={tr('logCopy')} icon={<Copy size={14} />} onClick={copyVisible} />
|
||||
)}
|
||||
{open && onExportDiagnostics && (
|
||||
<Button
|
||||
className="log-export-btn"
|
||||
icon={<Archive size={13} aria-hidden="true" />}
|
||||
busy={exportingDiagnostics}
|
||||
onClick={onExportDiagnostics}
|
||||
>
|
||||
{tr('logExportDiagnostics')}
|
||||
</Button>
|
||||
)}
|
||||
{open && tab === 'app' && lines.length > 0 && (
|
||||
<IconButton small tipSide="top" label={tr('clear')} icon={<Eraser size={14} />} onClick={onClear} />
|
||||
)}
|
||||
@@ -365,7 +419,7 @@ export const LogPanel: React.FC<Props> = ({
|
||||
|
||||
{open && (
|
||||
<div className="logs-body-wrap">
|
||||
<div className="logs-body" style={{ height }} ref={ref} onScroll={onScroll} role="log" aria-live="off">
|
||||
<div className="logs-body" style={{ height }} ref={ref} onScroll={onScroll} onCopy={handleBodyCopy} role="log" aria-live="off">
|
||||
{tab === 'app'
|
||||
? (filteredLines.length === 0
|
||||
? <span className="muted">{tr('logsEmpty')}</span>
|
||||
@@ -379,6 +433,40 @@ export const LogPanel: React.FC<Props> = ({
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{largeCopyPending && onExportDiagnostics && (
|
||||
<Modal
|
||||
className="sm"
|
||||
tone="neutral"
|
||||
title={tr('logLargeCopyTitle')}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setLargeCopyPending(null)}
|
||||
>
|
||||
<div className="dialog-body dialog-prose">
|
||||
<p>{tr('logLargeCopyDesc', { n: largeCopyPending.lines })}</p>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Button
|
||||
onClick={() => {
|
||||
const pending = largeCopyPending
|
||||
setLargeCopyPending(null)
|
||||
if (onCopy) onCopy(pending.text)
|
||||
}}
|
||||
>
|
||||
{tr('logCopyAnyway')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
busy={exportingDiagnostics}
|
||||
onClick={() => {
|
||||
setLargeCopyPending(null)
|
||||
onExportDiagnostics()
|
||||
}}
|
||||
>
|
||||
{tr('logExportDiagnostics')}
|
||||
</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { CloudDownload, Disc3, Download, Pause, X } from 'lucide-react'
|
||||
import { useEffect, useLayoutEffect, useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import '../i18n/domains/wizard.gen'
|
||||
import { parseAppError, t } from '../i18n'
|
||||
import { cachedRestoreImage, matchesRestoreImage, restoreImageChoiceKey, restoreImageChoices } from '../lib/restoreImages'
|
||||
import { findActiveInstallerTask, taskDetail, taskInstallerKind, taskInstallerPhase, taskStopAction } from '../lib/tasks'
|
||||
import type { CachedInstaller, HostReport, Locale, Release, Task } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { PopupSelect, SetGroup, SetRow } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
|
||||
type Source = 'apple' | 'local'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
host: HostReport
|
||||
tasks: Task[]
|
||||
initialImage?: CachedInstaller
|
||||
disabled: boolean
|
||||
selectedPath: string
|
||||
onPathChange: (path: string) => void
|
||||
onCancelTask: (id: string) => Promise<void>
|
||||
}
|
||||
|
||||
export function RestoreImageSource({ locale, host, tasks, initialImage, disabled, selectedPath, onPathChange, onCancelTask }: Props) {
|
||||
const [source, setSource] = useState<Source>('apple')
|
||||
const [localPath, setLocalPath] = useState('')
|
||||
const [cached, setCached] = useState<CachedInstaller[]>(() => initialImage ? [initialImage] : [])
|
||||
const [latest, setLatest] = useState<Release | null>()
|
||||
const [selection, setSelection] = useState(() => initialImage?.version ? restoreImageChoiceKey(initialImage.version, initialImage.build ?? '') : '')
|
||||
const [releaseErr, setReleaseErr] = useState('')
|
||||
const [cacheErr, setCacheErr] = useState('')
|
||||
const [actionErr, setActionErr] = useState('')
|
||||
const [catalogRequest, setCatalogRequest] = useState(0)
|
||||
const [pending, setPending] = useState<'download' | 'stop' | 'file' | ''>('')
|
||||
const tr = (key: Parameters<typeof t>[1], vars?: Record<string, string | number>) => t(locale, key, vars)
|
||||
|
||||
const tasksSig = tasks.filter((task) => taskInstallerKind(task) === 'ipsw')
|
||||
.map((task) => `${task.id}:${task.status}:${task.installer_phase}`).join('|')
|
||||
useEffect(() => {
|
||||
if (source !== 'apple') return
|
||||
let live = true
|
||||
api.ListInstallers().then((items) => {
|
||||
if (!live) return
|
||||
setCacheErr('')
|
||||
setCached(items ?? [])
|
||||
}).catch((error) => { if (live) setCacheErr(parseAppError(error).summary) })
|
||||
return () => { live = false }
|
||||
}, [source, tasksSig, catalogRequest])
|
||||
useEffect(() => {
|
||||
if (source !== 'apple') return
|
||||
let live = true
|
||||
setReleaseErr('')
|
||||
setLatest(undefined)
|
||||
api.ListOfflineReleases().then((items) => {
|
||||
if (live) setLatest(items?.[0] ?? null)
|
||||
}).catch((error) => {
|
||||
if (!live) return
|
||||
setLatest(null)
|
||||
setReleaseErr(parseAppError(error).summary)
|
||||
})
|
||||
return () => { live = false }
|
||||
}, [source, catalogRequest])
|
||||
|
||||
const choices = restoreImageChoices(latest ?? undefined, cached)
|
||||
const selected = choices.find((choice) => choice.key === selection) ?? choices[0]
|
||||
const complete = selected && cachedRestoreImage(cached, selected.version, selected.build)
|
||||
const currentRelease = selected && latest?.version === selected.version && latest.build === selected.build ? latest : undefined
|
||||
const active = currentRelease && findActiveInstallerTask(tasks, 'ipsw', currentRelease.version)?.primary
|
||||
const partial = currentRelease && cached.find((item) => item.partial && matchesRestoreImage(item, currentRelease.version, currentRelease.build))
|
||||
const needGB = currentRelease?.size ? Math.max(0, currentRelease.size - (partial?.bytes ?? 0)) / (2 ** 30) : 0
|
||||
const lowSpace = needGB > 0 && !complete && !active && host.free_disk_gb > 0 && host.free_disk_gb < needGB
|
||||
const local = source === 'local'
|
||||
const path = local ? localPath : complete?.path ?? ''
|
||||
// Update the parent submit control before the new selection is painted.
|
||||
useLayoutEffect(() => { if (selectedPath !== path) onPathChange(path) }, [path, selectedPath, onPathChange])
|
||||
|
||||
const doAction = async (action: Exclude<typeof pending, ''>, fn: () => Promise<void>) => {
|
||||
setPending(action)
|
||||
setActionErr('')
|
||||
try {
|
||||
await fn()
|
||||
} catch (error) {
|
||||
setActionErr(parseAppError(error).summary)
|
||||
} finally {
|
||||
setPending('')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="source-cards" role="radiogroup" aria-label={tr('step1')}>
|
||||
{(['apple', 'local'] as const).map((mode) => {
|
||||
const apple = mode === 'apple'
|
||||
const Icon = apple ? CloudDownload : Disc3
|
||||
return <label key={mode} className="source-card" data-selected={source === mode || undefined}>
|
||||
<input type="radio" name="restore-source" checked={source === mode} disabled={disabled} onChange={() => { setActionErr(''); setSource(mode) }} />
|
||||
<span className={`source-icon source-icon-${apple ? 'apple' : 'installer'}`} aria-hidden="true"><Icon size={20} /></span>
|
||||
<span className="source-title">{tr(apple ? 'srcIPSWDownloadTitle' : 'srcIPSWLocalTitle')}</span>
|
||||
<span className="source-sub">{tr(apple ? 'srcIPSWDownloadSub' : 'srcIPSWLocalSub')}</span>
|
||||
</label>
|
||||
})}
|
||||
</div>
|
||||
{actionErr && <div className="notice notice-error" role="alert">{actionErr}</div>}
|
||||
{local ? <SetGroup>
|
||||
<SetRow title={tr('srcIPSWLocalTitle')} disabled={disabled} control={
|
||||
<div className="input-group">
|
||||
<input className="input rg-p-input mono" value={localPath} aria-label={tr('srcIPSWLocalTitle')} onChange={(e) => setLocalPath(e.target.value)} />
|
||||
<Button busy={pending === 'file'} disabled={!!pending} onClick={() => doAction('file', async () => {
|
||||
const file = await api.PickFile(tr('srcIPSWLocalTitle'), '*.ipsw')
|
||||
if (file) setLocalPath(file)
|
||||
})}>{tr('wizChooseFile')}</Button>
|
||||
</div>
|
||||
} />
|
||||
</SetGroup> : <SetGroup>
|
||||
{choices.length > 0 && <SetRow title={tr('macosVersion')} disabled={disabled} control={
|
||||
<PopupSelect label={tr('macosVersion')} value={selected?.key ?? ''} onChange={setSelection} options={choices.map((choice) => ({ value: choice.key, label: choice.label }))} />
|
||||
} />}
|
||||
{active ? <SetRow title={tr(taskInstallerPhase(active) === 'queued' ? 'offlineQueued' : 'offlineDownloading')} desc={taskDetail(active)} disabled={disabled} control={
|
||||
<div className="hstack" role="status">
|
||||
<progress aria-label={tr('offlineDownloading')} max={100} value={active.percent >= 0 ? active.percent : undefined} />
|
||||
{active.cancelable && <Button icon={taskStopAction(locale, active).kind === 'pause' ? <Pause size={14} /> : <X size={14} />} busy={pending === 'stop'} disabled={!!pending} onClick={() => doAction('stop', () => onCancelTask(active.id))}>{taskStopAction(locale, active).label}</Button>}
|
||||
</div>
|
||||
} /> : complete ? <SetRow title={tr('offlineCached')} desc={selected?.label} /> : currentRelease && <SetRow title={tr('srcIPSWDownloadTitle')} disabled={disabled} desc={lowSpace ? tr('offlineSpaceWarn', { free: host.free_disk_gb.toFixed(0), need: Math.ceil(needGB) }) : undefined} control={
|
||||
<Button icon={<Download size={14} />} busy={pending === 'download'} disabled={!!pending || lowSpace} onClick={() => doAction('download', async () => { await api.DownloadInstaller(currentRelease.version) })}>{tr(partial ? 'installersResume' : 'installersDownload')}</Button>
|
||||
} />}
|
||||
{(releaseErr || cacheErr) && <div className="notice notice-error hstack" role="alert">
|
||||
<span>{releaseErr || cacheErr}</span>
|
||||
<Button onClick={() => setCatalogRequest((id) => id + 1)}>{tr('installersRetry')}</Button>
|
||||
</div>}
|
||||
{!releaseErr && latest === undefined && !complete && <p className="hint" role="status">{tr('offlineLoading')}</p>}
|
||||
{!releaseErr && latest === null && choices.length === 0 && <p className="hint">{tr('srcIPSWNone')}</p>}
|
||||
</SetGroup>}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
import React from 'react'
|
||||
import React, { useState } from 'react'
|
||||
import { FolderOpen } from 'lucide-react'
|
||||
import '../i18n/domains/plugins.gen'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { locText, t } from '../i18n'
|
||||
import { locText, parseAppError, t } from '../i18n'
|
||||
import { Locale, SettingProperty, SettingsSchema } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { NumberField, PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
@@ -13,6 +16,11 @@ interface Props {
|
||||
groupFilter?: string
|
||||
onChange: (next: Record<string, unknown>, patch: Record<string, unknown>) => void
|
||||
hideGroupHeader?: boolean
|
||||
pathFields?: Readonly<Record<string, string | true>>
|
||||
hideFields?: readonly string[]
|
||||
disabled?: boolean
|
||||
/** Only the trusted driver's create form supplies a native file picker. */
|
||||
filePicker?: { supports: (prop: SettingProperty) => boolean; pick: (label: string) => Promise<string> }
|
||||
}
|
||||
|
||||
const SECRET_MASK = '••••••••'
|
||||
@@ -20,13 +28,16 @@ const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
|
||||
|
||||
/** Lazy-loaded JSON Schema form renderer supporting x-secret, x-effect, and x-scope. */
|
||||
export const SchemaForm: React.FC<Props> = ({
|
||||
locale, schema, values, scopeFilter, groupFilter, onChange, hideGroupHeader,
|
||||
locale, schema, values, scopeFilter, groupFilter, onChange, hideGroupHeader, hideFields, pathFields, disabled, filePicker,
|
||||
}) => {
|
||||
const [picking, setPicking] = useState('')
|
||||
const [pickError, setPickError] = useState<{ key: string; text: string } | null>(null)
|
||||
const propsMap = schema.properties ?? {}
|
||||
const keys = (schema['x-order'] && schema['x-order'].length > 0
|
||||
? schema['x-order'].filter((k) => !FORBIDDEN_KEYS.has(k) && Object.prototype.hasOwnProperty.call(propsMap, k))
|
||||
: Object.keys(propsMap).filter((k) => !FORBIDDEN_KEYS.has(k))
|
||||
).filter((k) => {
|
||||
if (hideFields?.includes(k)) return false
|
||||
const prop = propsMap[k]
|
||||
const effScope = prop['x-scope'] || schema['x-scope'] || 'app'
|
||||
const effGroup = prop['x-group'] || schema['x-group'] || ''
|
||||
@@ -134,7 +145,7 @@ export const SchemaForm: React.FC<Props> = ({
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
const textInput = (
|
||||
<input
|
||||
type="text"
|
||||
className="input rg-p-input"
|
||||
@@ -143,6 +154,27 @@ export const SchemaForm: React.FC<Props> = ({
|
||||
onChange={(e) => setKey(k, e.target.value)}
|
||||
/>
|
||||
)
|
||||
const pathField = pathFields?.[k]
|
||||
if (pathField === undefined && !filePicker?.supports(prop)) return textInput
|
||||
return (
|
||||
<div className="input-group">
|
||||
{textInput}
|
||||
<Button icon={<FolderOpen size={14} />} busy={picking === k} disabled={!!picking} onClick={async () => {
|
||||
setPicking(k)
|
||||
setPickError(null)
|
||||
try {
|
||||
const path = pathField === true ? await api.PickDirectory(label)
|
||||
: typeof pathField === 'string' ? await api.PickFile(label, pathField)
|
||||
: await filePicker!.pick(label)
|
||||
if (path) setKey(k, path)
|
||||
} catch (e) {
|
||||
setPickError({ key: k, text: parseAppError(e).summary })
|
||||
} finally {
|
||||
setPicking('')
|
||||
}
|
||||
}}>{t(locale, 'choose')}</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const rows = keys.map((k) => {
|
||||
@@ -154,6 +186,8 @@ export const SchemaForm: React.FC<Props> = ({
|
||||
<SetRow
|
||||
key={k}
|
||||
title={title}
|
||||
disabled={disabled}
|
||||
error={pickError?.key === k ? pickError.text : undefined}
|
||||
desc={badge || desc ? <span className="hstack">{badge}{desc ? <span>{desc}</span> : null}</span> : undefined}
|
||||
control={renderControl(k, prop)}
|
||||
/>
|
||||
|
||||
@@ -8,6 +8,7 @@ import { Button } from '../ui/controls'
|
||||
import { PopupSelect } from '../ui/settings'
|
||||
import { gpuCompatHint, recommendedMemoryGB, shortGPUName } from '../lib/format'
|
||||
import { describeHostWHPX } from '../lib/hypervisor'
|
||||
import { hasStambhaRuntime } from '../lib/endpoints'
|
||||
import { api } from '../wails'
|
||||
import { PluginAppIcon } from './PluginAppIcon'
|
||||
import { RuntimeOnline } from './RuntimeOnline'
|
||||
@@ -205,7 +206,7 @@ const FolderStep: React.FC<StepProps> = ({ locale, locales, state, tr, onLocale,
|
||||
}
|
||||
|
||||
const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onChannel, onInstallRuntime, onCancelTask, onImportRuntime, onFolderDone, onFinish, onError }) => {
|
||||
const ready = !!state.active_runtime
|
||||
const ready = !!state.active_runtime || hasStambhaRuntime(state.runtimes)
|
||||
const { host } = state
|
||||
const [enabling, setEnabling] = useState(false)
|
||||
const [activating, setActivating] = useState('')
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import * as Ctx from '@radix-ui/react-context-menu'
|
||||
import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Maximize2, Pause, Play, Plus, Power, Puzzle, RotateCw, Settings, Square, Trash } from 'lucide-react'
|
||||
import { AppWindow, Bot, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Maximize2, Pause, Play, Plus, Power, Puzzle, RotateCw, Settings, Square, Trash } from 'lucide-react'
|
||||
import React, { useRef } from 'react'
|
||||
import { I18nKey, localeDir, t } from '../i18n'
|
||||
import { guestFamilyOf, vmFeatures } from '../lib/endpoints'
|
||||
import { Locale, VMAction, VMBusyAction, VMListItem } from '../types'
|
||||
import { AgentSessionView, Locale, VMAction, VMBusyAction, VMListItem } from '../types'
|
||||
import { hasVisibleDialog } from '../lib/dialogState'
|
||||
import { vmRefKey } from '../lib/vmRef'
|
||||
import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
|
||||
@@ -49,12 +49,14 @@ interface Props {
|
||||
updateDot?: boolean
|
||||
/** Declared plugin pages shown after the built-in Plugins entry. */
|
||||
pluginViews?: { id: string; title: string; badge?: string; icon?: string }[]
|
||||
/** Active remote-control / AI agent sessions across VMs. */
|
||||
agentSessions?: AgentSessionView[]
|
||||
/** VMs currently being created (not yet in `vms`). */
|
||||
creatingVMs?: { name: string; percent: number }[]
|
||||
}
|
||||
|
||||
export const Sidebar: React.FC<Props> = ({
|
||||
locale, vms, transitions, busyActions = {}, selected, hostReady, canSuspend, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode, updateCard, updateDot, pluginViews = [], creatingVMs = [],
|
||||
locale, vms, transitions, busyActions = {}, selected, hostReady, canSuspend, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode, updateCard, updateDot, pluginViews = [], agentSessions = [], creatingVMs = [],
|
||||
}) => {
|
||||
const tr = (k: I18nKey) => t(locale, k)
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
@@ -85,7 +87,7 @@ export const Sidebar: React.FC<Props> = ({
|
||||
kind: ReturnType<typeof statusKind> | null,
|
||||
onDoubleClick?: () => void,
|
||||
dot?: boolean,
|
||||
vm?: { state: string; driver: string; busy: boolean; family: string },
|
||||
vm?: { state: string; driver: string; busy: boolean; family: string; remoteControlled?: boolean; remoteLabel?: string },
|
||||
badgeText?: string,
|
||||
) => (
|
||||
<button
|
||||
@@ -99,6 +101,7 @@ export const Sidebar: React.FC<Props> = ({
|
||||
data-driver={vm?.driver}
|
||||
data-guest-family={vm?.family}
|
||||
data-busy={vm ? (vm.busy ? 'true' : 'false') : undefined}
|
||||
data-remote-control={vm?.remoteControlled ? 'true' : undefined}
|
||||
aria-selected={selected === id}
|
||||
aria-label={stateLabel ? t(locale, 'sidebarItemAria', { label, state: stateLabel }) : label}
|
||||
tabIndex={selected === id || (!hasSelectedInList && id === ids[0]) ? 0 : -1}
|
||||
@@ -107,6 +110,13 @@ export const Sidebar: React.FC<Props> = ({
|
||||
>
|
||||
<span className={`nav-icon-badge ${badgeClass}`} aria-hidden="true">{icon}</span>
|
||||
<span className="nav-label">{label}</span>
|
||||
{vm?.remoteControlled && (
|
||||
<Tip label={vm.remoteLabel || tr('remoteControlActive')} side="right">
|
||||
<span className="hstack" aria-hidden="true">
|
||||
<HostIcon name="remote-control"><Bot size={13} aria-hidden="true" /></HostIcon>
|
||||
</span>
|
||||
</Tip>
|
||||
)}
|
||||
{dot && <span className="nav-dot" aria-hidden="true" />}
|
||||
{badgeText && <span className="badge rg-p-badge badge-idle">{badgeText}</span>}
|
||||
{kind && (
|
||||
@@ -148,6 +158,10 @@ export const Sidebar: React.FC<Props> = ({
|
||||
const family = guestFamilyOf(vm)
|
||||
const vmCanSuspend = features.macos ? canSuspend : features.suspend
|
||||
const guestArt = hasGuestArt(family)
|
||||
const session = agentSessions.find((s) => s.vm_key === key || (!s.driver_id && s.vm_name === vm.name))
|
||||
const remoteLabel = session
|
||||
? t(locale, 'remoteControlActive', { plugin: session.plugin_name || session.plugin_id })
|
||||
: undefined
|
||||
const trigger = navBtn(
|
||||
key,
|
||||
label,
|
||||
@@ -157,7 +171,7 @@ export const Sidebar: React.FC<Props> = ({
|
||||
statusKind(st),
|
||||
onActivate ? () => onActivate(key) : undefined,
|
||||
undefined,
|
||||
{ state: st, driver: vm.driver_id ?? '', busy: vmBusy || transitioning, family },
|
||||
{ state: st, driver: vm.driver_id ?? '', busy: vmBusy || transitioning, family, remoteControlled: !!session, remoteLabel },
|
||||
)
|
||||
if (!onVMContextAction) return trigger
|
||||
return (
|
||||
|
||||
@@ -1,49 +1,23 @@
|
||||
import * as Menu from '@radix-ui/react-dropdown-menu'
|
||||
import { Check, PanelLeft } from 'lucide-react'
|
||||
import React, { useRef, useState } from 'react'
|
||||
import { I18nKey, localeDir, t } from '../i18n'
|
||||
import { localeDir, t } from '../i18n'
|
||||
import { hasVisibleDialog } from '../lib/dialogState'
|
||||
import { VMFeatures, vmFeatures } from '../lib/endpoints'
|
||||
import { buildTitleMenus, MENU_IDS, runMenuCommand, type MenuId, type MenuRow, type TitleMenuProps } from '../lib/titleMenu'
|
||||
import { useVMStats } from '../lib/vmStats'
|
||||
import { Locale, VMAction } from '../types'
|
||||
import { Tip } from '../ui/controls'
|
||||
import type { ThemeMode } from '../lib/useAppearance'
|
||||
import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PLUGINS_ID, SETTINGS_ID } from './Sidebar'
|
||||
|
||||
export const REPO_URL = 'https://github.com/Nwflower/Reims-Go'
|
||||
|
||||
/** A page on reims.dev in the UI language: Chinese at the root, every other locale under /en. */
|
||||
export function siteURL(locale: Locale, path = ''): string {
|
||||
const base = locale.toLowerCase().startsWith('zh') ? 'https://reims.dev' : 'https://reims.dev/en'
|
||||
return path ? `${base}${path}` : `${base}/`
|
||||
}
|
||||
|
||||
const MENU_IDS = ['vm', 'view', 'help'] as const
|
||||
type MenuId = (typeof MENU_IDS)[number]
|
||||
|
||||
const HOVER_CLICK_GUARD_MS = 300
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
sidebarOpen: boolean
|
||||
onToggleSidebar: () => void
|
||||
logsOpen: boolean
|
||||
onToggleLogs: () => void
|
||||
themeMode: ThemeMode
|
||||
canLight?: boolean
|
||||
canDark?: boolean
|
||||
onThemeMode: (mode: ThemeMode) => void
|
||||
/** The selected VM and its current state, or null on the system pages. `features` gates actions by driver capabilities (default: everything a macOS VM offers). */
|
||||
vm: { name: string; driver_id?: string; state: string; busy: boolean; graphics?: string; canSuspend: boolean; features?: VMFeatures } | null
|
||||
/** Active global fullscreen toggle shortcut when enabled, else undefined. */
|
||||
fullscreenHotkey?: string
|
||||
onNewVM: () => void
|
||||
onVMAction: (action: VMAction) => void
|
||||
onVMSettings: () => void
|
||||
onVMDelete: () => void
|
||||
onNavigate: (id: string) => void
|
||||
onOpenURL: (url: string) => void
|
||||
appVersion: string
|
||||
export function SidebarToggle({ locale, sidebarOpen, onToggleSidebar, mac, disabled }: Pick<TitleMenuProps, 'locale' | 'sidebarOpen' | 'onToggleSidebar'> & { mac?: boolean; disabled?: boolean }) {
|
||||
const label = t(locale, sidebarOpen ? 'hideSidebar' : 'showSidebar')
|
||||
return (
|
||||
<Tip label={label} shortcut={mac ? '⌘B' : 'Ctrl+B'} disabled={disabled}>
|
||||
<button type="button" className="titlebar-icon" aria-label={label} aria-pressed={sidebarOpen} onClick={onToggleSidebar}>
|
||||
<PanelLeft size={16} aria-hidden="true" />
|
||||
</button>
|
||||
</Tip>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -52,11 +26,8 @@ interface Props {
|
||||
* discoverable and still reachable with the sidebar hidden. Once one menu is
|
||||
* open, hovering the next title switches to it, as in a native menu bar.
|
||||
*/
|
||||
export const TitleMenus: React.FC<Props> = ({
|
||||
locale, sidebarOpen, onToggleSidebar, logsOpen, onToggleLogs, themeMode, canLight = true, canDark = true, onThemeMode,
|
||||
vm, fullscreenHotkey, onNewVM, onVMAction, onVMSettings, onVMDelete, onNavigate, onOpenURL, appVersion,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
export const TitleMenus: React.FC<TitleMenuProps> = (props) => {
|
||||
const { locale, vm, themeMode } = props
|
||||
const [menuState, setMenuState] = useState<{ id: MenuId | null; switched: boolean }>({ id: null, switched: false })
|
||||
const openRef = useRef<MenuId | null>(null)
|
||||
const navRef = useRef<HTMLElement>(null)
|
||||
@@ -70,36 +41,55 @@ export const TitleMenus: React.FC<Props> = ({
|
||||
}
|
||||
|
||||
const running = vm?.state === 'running'
|
||||
const stopped = vm?.state === 'stopped'
|
||||
const suspended = vm?.state === 'suspended'
|
||||
const transitioning = vm?.state === 'starting' || vm?.state === 'stopping' || vm?.state === 'suspending' || vm?.state === 'resuming'
|
||||
const vmBusy = !vm || vm.busy
|
||||
const features = vm?.features ?? vmFeatures(null)
|
||||
const canFullscreen = running && features.fullscreen && vm?.graphics !== 'vmware-svga'
|
||||
const stats = useVMStats(vm?.driver_id ?? '', canFullscreen && vm ? vm.name : null, running)
|
||||
const fullscreenLabel = !canFullscreen || !stats?.running
|
||||
? tr('toggleFullscreen')
|
||||
: stats.window_fullscreen
|
||||
? tr('exitFullscreen')
|
||||
: tr('enterFullscreen')
|
||||
const stats = useVMStats(vm?.driver_id ?? '', running && vm.features.fullscreen && vm.graphics !== 'vmware-svga' ? vm.name : null, running)
|
||||
const menus = buildTitleMenus(props, stats?.running ? stats.window_fullscreen : undefined)
|
||||
|
||||
const item = (label: string, onSelect: () => void, opts: { shortcut?: string; disabled?: boolean; danger?: boolean } = {}) => (
|
||||
<Menu.Item className={`menu-item rg-p-menu-item${opts.danger ? ' danger' : ''}`} disabled={opts.disabled} onSelect={onSelect}>
|
||||
<span className="menu-label">{label}</span>
|
||||
{opts.shortcut && <kbd className="menu-shortcut">{opts.shortcut}</kbd>}
|
||||
</Menu.Item>
|
||||
)
|
||||
const check = (label: string, checked: boolean, onSelect: () => void, shortcut?: string) => (
|
||||
<Menu.CheckboxItem className="menu-item rg-p-menu-item menu-item-check" checked={checked} onSelect={onSelect}>
|
||||
<Menu.ItemIndicator className="menu-check"><Check size={13} /></Menu.ItemIndicator>
|
||||
<span className="menu-label">{label}</span>
|
||||
{shortcut && <kbd className="menu-shortcut">{shortcut}</kbd>}
|
||||
</Menu.CheckboxItem>
|
||||
)
|
||||
const renderRow = (row: MenuRow, index: number) => {
|
||||
if (row.kind === 'separator') return <Menu.Separator key={index} className="menu-sep" />
|
||||
if (row.kind === 'label') return <Menu.Label key={index} className="menu-group-label">{row.label}</Menu.Label>
|
||||
const onSelect = () => runMenuCommand(props, row.command)
|
||||
const label = <span className="menu-label">{row.label}</span>
|
||||
const shortcut = row.shortcut && <kbd className="menu-shortcut">{row.shortcut}</kbd>
|
||||
const indicator = <Menu.ItemIndicator className="menu-check"><Check size={13} /></Menu.ItemIndicator>
|
||||
if (row.kind === 'radio') return (
|
||||
<Menu.RadioItem key={row.command} className="menu-item rg-p-menu-item menu-item-check" value={row.command} disabled={row.disabled}>
|
||||
{indicator}{label}
|
||||
</Menu.RadioItem>
|
||||
)
|
||||
if (row.kind === 'check') return (
|
||||
<Menu.CheckboxItem key={row.command} className="menu-item rg-p-menu-item menu-item-check" checked={row.checked} disabled={row.disabled} onSelect={onSelect}>
|
||||
{indicator}{label}{shortcut}
|
||||
</Menu.CheckboxItem>
|
||||
)
|
||||
return (
|
||||
<Menu.Item key={row.command} className={`menu-item rg-p-menu-item${row.danger ? ' danger' : ''}`} disabled={row.disabled} onSelect={onSelect}>
|
||||
{label}{shortcut}
|
||||
</Menu.Item>
|
||||
)
|
||||
}
|
||||
|
||||
const renderRows = (rows: MenuRow[]) => {
|
||||
const firstRadio = rows.findIndex((row) => row.kind === 'radio')
|
||||
if (firstRadio === -1) return rows.map(renderRow)
|
||||
const radioRows = rows.filter((row) => row.kind === 'radio')
|
||||
return (
|
||||
<>
|
||||
{rows.slice(0, firstRadio).map(renderRow)}
|
||||
<Menu.RadioGroup value={`theme:${themeMode}`} onValueChange={(value) => {
|
||||
const row = radioRows.find((entry) => entry.kind === 'radio' && entry.command === value)
|
||||
if (row?.kind === 'radio') runMenuCommand(props, row.command)
|
||||
}}>
|
||||
{radioRows.map(renderRow)}
|
||||
</Menu.RadioGroup>
|
||||
{rows.slice(firstRadio + radioRows.length).map((row, i) => renderRow(row, firstRadio + radioRows.length + i))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// `indented`: the menu has check marks, so every row shares their indent.
|
||||
const menu = (id: MenuId, label: string, content: React.ReactNode, indented = false) => (
|
||||
<Menu.Root
|
||||
key={id}
|
||||
dir={localeDir(locale)}
|
||||
modal={false}
|
||||
open={menuState.id === id}
|
||||
@@ -214,80 +204,9 @@ export const TitleMenus: React.FC<Props> = ({
|
||||
|
||||
return (
|
||||
<div className="titlebar-left" onDoubleClick={(e) => e.stopPropagation()}>
|
||||
<Tip label={tr(sidebarOpen ? 'hideSidebar' : 'showSidebar')} shortcut="Ctrl+B" disabled={menuState.id !== null}>
|
||||
<button
|
||||
type="button"
|
||||
className="titlebar-icon"
|
||||
aria-label={tr(sidebarOpen ? 'hideSidebar' : 'showSidebar')}
|
||||
aria-pressed={sidebarOpen}
|
||||
onClick={onToggleSidebar}
|
||||
>
|
||||
<PanelLeft size={16} aria-hidden="true" />
|
||||
</button>
|
||||
</Tip>
|
||||
<nav ref={navRef} className="titlebar-menus" aria-label={tr('menuBar')}>
|
||||
{menu('vm', tr('menuVM'), (
|
||||
<>
|
||||
{item(tr('newVMEllipsis'), onNewVM, { shortcut: 'Ctrl+N' })}
|
||||
<Menu.Separator className="menu-sep" />
|
||||
{running
|
||||
? (features.window && item(tr('showWindow'), () => onVMAction('focus'), { shortcut: 'Ctrl+Enter', disabled: vmBusy }))
|
||||
: suspended
|
||||
? item(tr('resume'), () => onVMAction('resume'), { shortcut: vm?.canSuspend ? 'Ctrl+Enter' : undefined, disabled: vmBusy || !vm?.canSuspend })
|
||||
: item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })}
|
||||
{suspended && !vm?.canSuspend && <Menu.Label className="menu-group-label">{tr('resumeUnavailable')}</Menu.Label>}
|
||||
{features.fullscreen && item(fullscreenLabel, () => onVMAction('fullscreen'), { shortcut: fullscreenHotkey, disabled: vmBusy || !canFullscreen })}
|
||||
{features.suspend && item(tr('suspend'), () => onVMAction('suspend'), { disabled: vmBusy || !running || !vm?.canSuspend })}
|
||||
{item(tr('stop'), () => onVMAction('stop'), { disabled: vmBusy || !running })}
|
||||
{item(tr('restart'), () => onVMAction('restart'), { disabled: vmBusy || !running })}
|
||||
{features.screenshot && item(tr('copyScreenshot'), () => onVMAction('screenshot'), { disabled: vmBusy || !running })}
|
||||
<Menu.Separator className="menu-sep" />
|
||||
{features.macos && item(tr('settingsEllipsis'), onVMSettings, { shortcut: 'Ctrl+,', disabled: !vm || suspended || transitioning })}
|
||||
{features.macos && item(tr('openFolder'), () => onVMAction('openFolder'), { disabled: !vm })}
|
||||
<Menu.Separator className="menu-sep" />
|
||||
{suspended && item(tr('discardSuspend'), () => onVMAction('discardSuspend'), { danger: true, disabled: vmBusy })}
|
||||
{item(tr('forceStop'), () => onVMAction('forceStop'), { danger: true, disabled: !vm || !(running || transitioning) })}
|
||||
{item(tr('deleteEllipsis'), onVMDelete, { danger: true, disabled: vmBusy || running || suspended || transitioning })}
|
||||
</>
|
||||
))}
|
||||
{menu('view', tr('menuView'), (
|
||||
<>
|
||||
{check(tr('sidebarLabel'), sidebarOpen, onToggleSidebar, 'Ctrl+B')}
|
||||
{check(tr('logButton'), logsOpen, onToggleLogs, 'Ctrl+L')}
|
||||
<Menu.Separator className="menu-sep" />
|
||||
<Menu.Label className="menu-group-label">{tr('appearance')}</Menu.Label>
|
||||
<Menu.RadioGroup value={themeMode} onValueChange={(v) => onThemeMode(v as ThemeMode)}>
|
||||
{(['light', 'dark', 'system'] as const).map((m) => (
|
||||
<Menu.RadioItem
|
||||
key={m}
|
||||
className="menu-item rg-p-menu-item menu-item-check"
|
||||
value={m}
|
||||
disabled={(m === 'light' && !canLight) || (m === 'dark' && !canDark) || (m === 'system' && (!canLight || !canDark))}
|
||||
>
|
||||
<Menu.ItemIndicator className="menu-check"><Check size={13} /></Menu.ItemIndicator>
|
||||
<span className="menu-label">{tr(m === 'light' ? 'themeLight' : m === 'dark' ? 'themeDark' : 'themeSystem')}</span>
|
||||
</Menu.RadioItem>
|
||||
))}
|
||||
</Menu.RadioGroup>
|
||||
<Menu.Separator className="menu-sep" />
|
||||
{item(tr('sidebarInstallers'), () => onNavigate(INSTALLERS_ID))}
|
||||
{item(tr('sidebarPlugins'), () => onNavigate(PLUGINS_ID))}
|
||||
{item(tr('sidebarHost'), () => onNavigate(HOST_ID))}
|
||||
{item(tr('sidebarSettings'), () => onNavigate(SETTINGS_ID))}
|
||||
</>
|
||||
), true)}
|
||||
{menu('help', tr('menuHelp'), (
|
||||
<>
|
||||
{item(tr('helpWebsite'), () => onOpenURL(siteURL(locale)))}
|
||||
{item(tr('helpDocs'), () => onOpenURL(siteURL(locale, '/docs/quick-start')))}
|
||||
{item(tr('helpProjectPage'), () => onOpenURL(REPO_URL))}
|
||||
{item(tr('helpReportIssue'), () => onOpenURL(`${REPO_URL}/issues`))}
|
||||
{item(tr('helpCheckUpdate'), () => onNavigate(ABOUT_ID))}
|
||||
{item(tr('helpAbout'), () => onNavigate(ABOUT_ID))}
|
||||
<Menu.Separator className="menu-sep" />
|
||||
<Menu.Label className="menu-group-label">Reims-Go {appVersion}</Menu.Label>
|
||||
</>
|
||||
))}
|
||||
<SidebarToggle {...props} disabled={menuState.id !== null} />
|
||||
<nav ref={navRef} className="titlebar-menus" aria-label={t(locale, 'menuBar')}>
|
||||
{MENU_IDS.map((id) => menu(id, menus[id].label, renderRows(menus[id].rows), id === 'view'))}
|
||||
</nav>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -2,6 +2,7 @@ import * as Menu from '@radix-ui/react-dropdown-menu'
|
||||
import {
|
||||
AppWindow,
|
||||
Archive,
|
||||
Bot,
|
||||
Camera,
|
||||
Check,
|
||||
ChevronDown,
|
||||
@@ -31,17 +32,18 @@ import {
|
||||
endpointKey,
|
||||
guestFamilyOf,
|
||||
isMacOSDriver as isMacOSDriverID,
|
||||
splitEndpoints,
|
||||
primaryVMAccess,
|
||||
vmFeatures,
|
||||
} from '../lib/endpoints'
|
||||
import { useVMStats } from '../lib/vmStats'
|
||||
import { HostReport, Locale, PendingChange, PluginUIContributions, VMAction, VMBusyAction, VMDetail, VMInfo } from '../types'
|
||||
import { AgentSessionView, AutoInstallerProviderView, HostReport, Locale, PendingChange, PluginUIContributions, VMAction, VMBusyAction, VMDetail, VMInfo } from '../types'
|
||||
import { api } from '../wails'
|
||||
import { Button, StatusShape, Tip, statusKind } from '../ui/controls'
|
||||
import { ActionMenu } from '../ui/menu'
|
||||
import { HostIcon } from '../ui/themeVisuals'
|
||||
import { VersionArt } from '../macos/VersionArt'
|
||||
import { GuestArt, hasGuestArt } from './GuestIcon'
|
||||
import { VMAutoInstallPanel } from './AutoInstallPanel'
|
||||
import { ConnectionSection } from './vmPage/connections'
|
||||
import { endpointIcon, EndpointSection, useEndpointActions } from './vmPage/endpoints'
|
||||
import { useHostDNS } from './vmPage/hostDNS'
|
||||
@@ -80,6 +82,7 @@ interface Props {
|
||||
host: HostReport
|
||||
pending: PendingChange[]
|
||||
busyAction?: VMBusyAction
|
||||
exportingDiagnostics?: boolean
|
||||
onAction: (action: VMAction) => void
|
||||
onPluginCommand: (pluginID: string, command: string, title: string) => void
|
||||
onSettings: () => void
|
||||
@@ -96,6 +99,12 @@ interface Props {
|
||||
fullscreenHotkey?: string
|
||||
dropping?: boolean
|
||||
pluginUI?: PluginUIContributions | null
|
||||
agentSession?: AgentSessionView | null
|
||||
provisionReady?: boolean
|
||||
autoInstallers?: AutoInstallerProviderView[]
|
||||
onStopAgentSession?: () => void
|
||||
onPauseAgentSession?: () => void
|
||||
onResumeAgentSession?: () => void
|
||||
}
|
||||
|
||||
function ShutdownButton({ locale, busyAction, onAction }: Pick<Props, 'locale' | 'busyAction' | 'onAction'>) {
|
||||
@@ -133,7 +142,7 @@ function ShutdownButton({ locale, busyAction, onAction }: Pick<Props, 'locale' |
|
||||
}
|
||||
|
||||
export const VMPage: React.FC<Props> = ({
|
||||
locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, currentAgentVersion, guideActive, installGuideEnabled, detail, vmInfo, host, pending, busyAction, onAction, onPluginCommand, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI, fullscreenHotkey,
|
||||
locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, currentAgentVersion, guideActive, installGuideEnabled, detail, vmInfo, host, pending, busyAction, exportingDiagnostics = false, onAction, onPluginCommand, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI, fullscreenHotkey, agentSession, provisionReady, autoInstallers, onStopAgentSession, onPauseAgentSession, onResumeAgentSession,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const busy = busyAction !== undefined
|
||||
@@ -163,9 +172,8 @@ export const VMPage: React.FC<Props> = ({
|
||||
const guestArt = !isMacOSDriver && hasGuestArt(guestFamily)
|
||||
const phase = vmInfo?.phase
|
||||
const waitingForGuest = running && vmInfo?.ready === false
|
||||
// A running hosted VM has no window: its best ready endpoint is the header action.
|
||||
const { primary: bestEndpoint } = splitEndpoints(vmInfo?.endpoints)
|
||||
const promotedEndpoint = features.hosted && running ? bestEndpoint : undefined
|
||||
const access = running ? primaryVMAccess(features, vmInfo?.endpoints) : undefined
|
||||
const promotedEndpoint = access?.kind === 'endpoint' ? access.endpoint : undefined
|
||||
const endpoints = useEndpointActions({ locale, driverID, name, onCopy, onError })
|
||||
const { endpointBusy, runEndpointAction, endpointActionLabel, endpointKindLabel } = endpoints
|
||||
// Polled here rather than in App so each tick re-renders only this page.
|
||||
@@ -242,27 +250,23 @@ export const VMPage: React.FC<Props> = ({
|
||||
primary = <Button variant="primary" busy>{tr('state_resuming')}</Button>
|
||||
} else if (running) {
|
||||
const showLabel = tr(guideActive ? 'showInstallGuide' : 'showWindow')
|
||||
if (features.hosted) {
|
||||
// No window to show: the header action is the best ready endpoint, and with none ready there is no
|
||||
// primary action at all (a disabled button never takes the primary slot).
|
||||
if (promotedEndpoint) {
|
||||
const action = defaultEndpointAction(promotedEndpoint.kind)
|
||||
const label = action ? endpointActionLabel(promotedEndpoint.kind, action) : endpointKindLabel(promotedEndpoint.kind)
|
||||
primary = (
|
||||
<Tip label={label} shortcut={PRIMARY_SHORTCUT}>
|
||||
<Button
|
||||
variant="primary"
|
||||
icon={endpointIcon(promotedEndpoint.kind, 14)}
|
||||
busy={endpointBusy === `${endpointKey(promotedEndpoint)}:`}
|
||||
disabled={busy}
|
||||
onClick={() => runEndpointAction(promotedEndpoint, '')}
|
||||
>
|
||||
{label}
|
||||
</Button>
|
||||
</Tip>
|
||||
)
|
||||
}
|
||||
} else {
|
||||
if (promotedEndpoint) {
|
||||
const action = defaultEndpointAction(promotedEndpoint.kind)
|
||||
const label = action ? endpointActionLabel(promotedEndpoint.kind, action) : endpointKindLabel(promotedEndpoint.kind)
|
||||
primary = (
|
||||
<Tip label={label} shortcut={PRIMARY_SHORTCUT}>
|
||||
<Button
|
||||
variant="primary"
|
||||
icon={endpointIcon(promotedEndpoint.kind, 14)}
|
||||
busy={endpointBusy === `${endpointKey(promotedEndpoint)}:`}
|
||||
disabled={busy}
|
||||
onClick={() => runEndpointAction(promotedEndpoint, '')}
|
||||
>
|
||||
{label}
|
||||
</Button>
|
||||
</Tip>
|
||||
)
|
||||
} else if (access?.kind === 'window') {
|
||||
primary = (
|
||||
<Tip label={showLabel} shortcut={PRIMARY_SHORTCUT}>
|
||||
<Button variant="primary" icon={<AppWindow size={14} aria-hidden="true" />} busy={busyAction === 'focus'} disabled={busy} onClick={() => onAction('focus')}>
|
||||
@@ -374,7 +378,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
<Menu.Item className="menu-item rg-p-menu-item" onSelect={onViewLogs}>
|
||||
<HostIcon name="logs"><Terminal size={14} /></HostIcon> {tr('viewLogs')}
|
||||
</Menu.Item>
|
||||
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy} onSelect={() => onAction('exportDiagnostics')}>
|
||||
<Menu.Item className="menu-item rg-p-menu-item" disabled={exportingDiagnostics} onSelect={() => onAction('exportDiagnostics')}>
|
||||
<Archive size={14} /> {tr('exportDiagnostics')}
|
||||
</Menu.Item>
|
||||
{toolbarMenus.map((m) => {
|
||||
@@ -412,8 +416,19 @@ export const VMPage: React.FC<Props> = ({
|
||||
? ({ '--wails-drop-target': 'drop' } as React.CSSProperties)
|
||||
: undefined
|
||||
|
||||
const matchedAutoInstaller = (autoInstallers ?? []).find((p) => !p.guest_families?.length || p.guest_families.includes(guestFamily))
|
||||
const showAutoInstaller = !!matchedAutoInstaller && (
|
||||
installing || phase === 'installer' || phase === 'recovery' || agentSession?.plugin_id === matchedAutoInstaller.plugin_id
|
||||
)
|
||||
return (
|
||||
<div className="page vm-page vm-page-drop rg-p-vm-page" data-vm-state={state} data-driver={driverID} data-guest-family={guestFamily} style={dropStyle}>
|
||||
<div
|
||||
className="page vm-page vm-page-drop rg-p-vm-page"
|
||||
data-vm-state={state}
|
||||
data-driver={driverID}
|
||||
data-guest-family={guestFamily}
|
||||
data-remote-control={agentSession ? 'true' : undefined}
|
||||
style={dropStyle}
|
||||
>
|
||||
{dropping && (
|
||||
<div className="drop-banner" role="status" aria-live="polite">
|
||||
<Upload size={16} aria-hidden="true" />
|
||||
@@ -497,11 +512,84 @@ export const VMPage: React.FC<Props> = ({
|
||||
<VMSummary locale={locale} running={running} detail={detail} vmInfo={vmInfo} isMacOSDriver={isMacOSDriver} guestFamily={guestFamily} host={host} stats={stats} />
|
||||
</div>
|
||||
|
||||
{agentSession && (() => {
|
||||
const phaseLabel = agentSession.phase === 'installer'
|
||||
? tr('phaseInstaller')
|
||||
: agentSession.phase === 'recovery'
|
||||
? tr('phaseRecovery')
|
||||
: ''
|
||||
const title = phaseLabel
|
||||
? (!agentSession.auth_until_phase_exit && (agentSession.auth_remaining_sec ?? 0) > 0
|
||||
? tr('remoteControlPhaseAuthTimer', {
|
||||
phase: phaseLabel,
|
||||
minutes: Math.max(1, Math.ceil((agentSession.auth_remaining_sec ?? 0) / 60)),
|
||||
})
|
||||
: tr('remoteControlPhaseAuth', { phase: phaseLabel }))
|
||||
: tr('remoteControlActive', { plugin: agentSession.plugin_name || agentSession.plugin_id })
|
||||
const paused = !!(agentSession.paused_for_user || agentSession.takeover_paused)
|
||||
const sub = agentSession.takeover_paused && !agentSession.takeover_manual_wait && (agentSession.takeover_remaining_sec ?? 0) > 0
|
||||
? tr('remoteControlTakeoverCountdown', { seconds: agentSession.takeover_remaining_sec ?? 1 })
|
||||
: paused
|
||||
? (agentSession.message || tr('remoteControlPaused'))
|
||||
: [agentSession.input_locked ? tr('remoteControlInputLocked') : '', agentSession.stage_label || agentSession.stage, agentSession.message].filter(Boolean).join(' · ')
|
||||
return (
|
||||
<div className="notice notice-info" role="status" aria-live="polite">
|
||||
<span className="notice-main">
|
||||
<HostIcon name="remote-control"><Bot size={15} className="notice-icon" aria-hidden="true" /></HostIcon>
|
||||
<span className="notice-text">
|
||||
<span className="notice-title">{title}</span>
|
||||
{sub && <span className="notice-sub">{sub}</span>}
|
||||
</span>
|
||||
</span>
|
||||
<div className="hstack">
|
||||
{!paused && onPauseAgentSession && (
|
||||
<Button onClick={onPauseAgentSession}>{tr('remoteControlPause')}</Button>
|
||||
)}
|
||||
{paused && onResumeAgentSession && (
|
||||
<Button variant="primary" onClick={onResumeAgentSession}>{tr('remoteControlResume')}</Button>
|
||||
)}
|
||||
{onStopAgentSession && (
|
||||
<Button variant="danger" onClick={onStopAgentSession}>{tr('remoteControlStop')}</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})()}
|
||||
|
||||
{provisionReady && installing && !agentSession && (
|
||||
<div className="notice notice-info" role="status" aria-live="polite">
|
||||
<span className="notice-main">
|
||||
<Check size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span className="notice-text">
|
||||
<span className="notice-title">{tr('provisionReadyNoticeTitle')}</span>
|
||||
<span className="notice-sub">{tr('provisionReadyNoticeDesc')}</span>
|
||||
</span>
|
||||
</span>
|
||||
<Button variant="primary" busy={busyAction === 'finishInstall'} disabled={busy} onClick={() => onAction('finishInstall')}>
|
||||
{tr('finishInstall')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<VMNotices
|
||||
locale={locale} state={state} canSuspend={canSuspend} resumeHintId={resumeHintId} detail={detail} stats={stats}
|
||||
host={host} pending={pending} busyAction={busyAction} onAction={onAction}
|
||||
/>
|
||||
|
||||
{showAutoInstaller && matchedAutoInstaller && (
|
||||
<VMAutoInstallPanel
|
||||
locale={locale}
|
||||
provider={matchedAutoInstaller}
|
||||
driverID={driverID}
|
||||
vmName={name}
|
||||
guestLang={detail?.guest_lang || 'zh-Hans:0'}
|
||||
sessionRefreshKey={agentSession ? `${agentSession.plugin_id}:${agentSession.status ?? ''}:${agentSession.stage ?? ''}` : ''}
|
||||
onCopy={onCopy}
|
||||
onError={onError}
|
||||
onToast={onToast}
|
||||
/>
|
||||
)}
|
||||
|
||||
{detail && installing && (!installGuideEnabled || state === 'stopped') && (
|
||||
<InstallCard
|
||||
key={name} locale={locale} name={name} detail={detail} running={running} installGuideEnabled={installGuideEnabled}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Code generated by cmd/i18ngen; DO NOT EDIT.
|
||||
// Code generated by scripts/i18ngen; DO NOT EDIT.
|
||||
|
||||
export const coreZh: Record<string, string> = {
|
||||
"affinityMenu": "处理器相关性…",
|
||||
@@ -12,7 +12,7 @@ export const coreZh: Record<string, string> = {
|
||||
"clear": "清空",
|
||||
"close": "关闭",
|
||||
"closeDownloadsConfirm": "退出",
|
||||
"closeDownloadsDesc": "仍有下载正在进行,退出会中断它们。",
|
||||
"closeDownloadsDesc": "退出会中断正在进行的下载或 macOS 安装。",
|
||||
"closeDownloadsTitle": "退出 Reims-Go?",
|
||||
"closeWindow": "关闭",
|
||||
"collapseLogs": "收起日志",
|
||||
@@ -28,6 +28,27 @@ export const coreZh: Record<string, string> = {
|
||||
"dataRootRetry": "重试",
|
||||
"delete": "删除…",
|
||||
"deleteEllipsis": "删除…",
|
||||
"diagChecklistSteps": "一并说明问题现象、卡住的阶段或触发前的操作",
|
||||
"diagChecklistTitle": "反馈清单",
|
||||
"diagChecklistZip": "直接发送此 .zip 压缩包,内含已脱敏的环境信息、配置与日志,无需再贴大段文字或截图",
|
||||
"diagCopyArchive": "复制压缩包",
|
||||
"diagCopySummary": "复制摘要",
|
||||
"diagDialogTitle": "排障包",
|
||||
"diagFindingGpuDeviceLostDesc": "更新显卡驱动、改选其他独立显卡,或暂时改用 VMware SVGA(软件渲染)",
|
||||
"diagFindingGpuDeviceLostTitle": "显卡设备丢失",
|
||||
"diagFindingGpuVulkanFloorDesc": "更新显卡驱动以支持 Vulkan 1.3 与必需扩展,或改用 VMware SVGA(软件渲染)",
|
||||
"diagFindingGpuVulkanFloorTitle": "Vulkan 版本或扩展不足",
|
||||
"diagFindingLowDiskDesc": "清理数据盘空间,或将数据目录迁移到可用空间更大的磁盘",
|
||||
"diagFindingLowDiskTitle": "数据盘可用空间偏低",
|
||||
"diagFindingLowMemoryDesc": "关闭占用较高的宿主机程序,或调低虚拟机分配内存后重试",
|
||||
"diagFindingLowMemoryTitle": "宿主机可用内存偏低",
|
||||
"diagFindingWhpxUnavailableDesc": "打开「内核」页检查 Windows 虚拟机监控程序平台状态并按提示启用",
|
||||
"diagFindingWhpxUnavailableTitle": "WHPX 虚拟化不可用",
|
||||
"diagIncludedFiles": "包含文件",
|
||||
"diagNoFindingsDesc": "日志与环境检查未发现常见故障,求助时补充具体现象(如黑屏、卡进度条)便于排查",
|
||||
"diagNoFindingsTitle": "未发现已知异常",
|
||||
"diagRevealFile": "打开位置",
|
||||
"diagSummaryToggle": "环境摘要",
|
||||
"displays": "显示器数量",
|
||||
"eject": "弹出安装盘",
|
||||
"elevateActionFallbackDesc": "随后将弹出系统 UAC 授权提示,本程序不会自动重启 Windows。",
|
||||
@@ -47,6 +68,7 @@ export const coreZh: Record<string, string> = {
|
||||
"errorBoundaryReload": "重新加载界面",
|
||||
"errorBoundaryTitle": "界面遇到意外错误",
|
||||
"expandLogs": "展开日志",
|
||||
"failCopyDiagnosticsFile": "复制排障包失败",
|
||||
"failCreate": "{name} 创建失败",
|
||||
"failDownload": "下载失败",
|
||||
"failGeneric": "操作失败",
|
||||
@@ -101,7 +123,11 @@ export const coreZh: Record<string, string> = {
|
||||
"logActivity": "活动",
|
||||
"logButton": "日志",
|
||||
"logCopy": "复制日志",
|
||||
"logCopyAnyway": "仍然复制",
|
||||
"logErrorsOnly": "仅错误/警告",
|
||||
"logExportDiagnostics": "导出排障包",
|
||||
"logLargeCopyDesc": "即将复制 {n} 行日志,直接粘贴容易刷屏且缺少环境信息,建议导出排障包",
|
||||
"logLargeCopyTitle": "大段日志",
|
||||
"logQemu": "QEMU",
|
||||
"logSearchPlaceholder": "筛选日志…",
|
||||
"logSerial": "串口",
|
||||
@@ -121,6 +147,24 @@ export const coreZh: Record<string, string> = {
|
||||
"maximize": "最大化",
|
||||
"menuBar": "菜单栏",
|
||||
"menuHelp": "帮助",
|
||||
"menuMacCut": "剪切",
|
||||
"menuMacDelete": "删除",
|
||||
"menuMacEdit": "编辑",
|
||||
"menuMacFullScreen": "进入全屏幕",
|
||||
"menuMacHide": "隐藏 Reims-Go",
|
||||
"menuMacHideOthers": "隐藏其他应用",
|
||||
"menuMacPaste": "粘贴",
|
||||
"menuMacPasteMatchStyle": "粘贴并匹配样式",
|
||||
"menuMacQuit": "退出 Reims-Go",
|
||||
"menuMacRedo": "重做",
|
||||
"menuMacSelectAll": "全选",
|
||||
"menuMacShowAll": "显示全部",
|
||||
"menuMacSpeech": "朗读",
|
||||
"menuMacStartSpeaking": "开始朗读",
|
||||
"menuMacStopSpeaking": "停止朗读",
|
||||
"menuMacUndo": "撤销",
|
||||
"menuMacWindow": "窗口",
|
||||
"menuMacZoom": "缩放",
|
||||
"menuVM": "虚拟机",
|
||||
"menuView": "视图",
|
||||
"minimize": "最小化",
|
||||
@@ -172,6 +216,7 @@ export const coreZh: Record<string, string> = {
|
||||
"taskDownload": "下载 macOS {v}",
|
||||
"taskPluginDownload": "下载 {name}",
|
||||
"taskRecoveryDownload": "正在为 {name} 拉取并挂载在线恢复镜像",
|
||||
"taskRestoreVM": "在 {name} 上安装 macOS",
|
||||
"taskRuntime": "安装运行时 {v}",
|
||||
"tasksRunning": "{n, plural, other {# 个任务进行中}}",
|
||||
"themeDark": "深色",
|
||||
@@ -185,6 +230,7 @@ export const coreZh: Record<string, string> = {
|
||||
"toastCreateCanceled": "已取消创建 {name}",
|
||||
"toastCreateCanceledPartial": "已下载部分已保留,可继续下载或返回修改",
|
||||
"toastCreated": "{name} 已创建",
|
||||
"toastDiagFileCopied": "已复制排障包文件,可直接粘贴发送",
|
||||
"toastDownloadPaused": "已暂停,再次下载会从中断处继续",
|
||||
"toastInstallerReady": "macOS {v} 安装包已就绪",
|
||||
"toastQueueCanceled": "已取消排队",
|
||||
@@ -213,6 +259,8 @@ export const coreZh: Record<string, string> = {
|
||||
"uptimeMinutesSeconds": "{m} 分 {s} 秒",
|
||||
"uptimeSeconds": "{s} 秒",
|
||||
"viewLogs": "查看日志",
|
||||
"wizardDriverListFailed": "无法加载客体驱动",
|
||||
"wizardNoDriver": "没有可用的客体驱动",
|
||||
}
|
||||
|
||||
export const coreEn: Record<string, string> = {
|
||||
@@ -227,7 +275,7 @@ export const coreEn: Record<string, string> = {
|
||||
"clear": "Clear",
|
||||
"close": "Close",
|
||||
"closeDownloadsConfirm": "Quit",
|
||||
"closeDownloadsDesc": "Downloads are still running. Quitting stops them.",
|
||||
"closeDownloadsDesc": "Quitting stops any downloads or macOS installations in progress.",
|
||||
"closeDownloadsTitle": "Quit Reims-Go?",
|
||||
"closeWindow": "Close",
|
||||
"collapseLogs": "Hide logs",
|
||||
@@ -243,6 +291,27 @@ export const coreEn: Record<string, string> = {
|
||||
"dataRootRetry": "Try again",
|
||||
"delete": "Delete…",
|
||||
"deleteEllipsis": "Delete…",
|
||||
"diagChecklistSteps": "Briefly describe what happened, where it stopped, and the steps leading up to it",
|
||||
"diagChecklistTitle": "Sharing checklist",
|
||||
"diagChecklistZip": "Send this .zip archive directly; it includes redacted host details, settings, and logs, with no need to paste long text",
|
||||
"diagCopyArchive": "Copy archive",
|
||||
"diagCopySummary": "Copy summary",
|
||||
"diagDialogTitle": "Diagnostics archive",
|
||||
"diagFindingGpuDeviceLostDesc": "Update the GPU driver, choose another discrete GPU, or switch to VMware SVGA (software rendering) for now",
|
||||
"diagFindingGpuDeviceLostTitle": "GPU device lost",
|
||||
"diagFindingGpuVulkanFloorDesc": "Update the GPU driver for Vulkan 1.3 and required extensions, or switch to VMware SVGA (software rendering)",
|
||||
"diagFindingGpuVulkanFloorTitle": "Vulkan requirements not met",
|
||||
"diagFindingLowDiskDesc": "Free up space on the data drive, or move the data folder to a drive with more space",
|
||||
"diagFindingLowDiskTitle": "Low free space on data drive",
|
||||
"diagFindingLowMemoryDesc": "Close memory-heavy apps on the host, or lower the VM’s memory allocation and try again",
|
||||
"diagFindingLowMemoryTitle": "Low available host memory",
|
||||
"diagFindingWhpxUnavailableDesc": "Open the Engine page to check Windows Hypervisor Platform status and enable virtualization",
|
||||
"diagFindingWhpxUnavailableTitle": "WHPX virtualization unavailable",
|
||||
"diagIncludedFiles": "Included files",
|
||||
"diagNoFindingsDesc": "No common faults appeared in logs or host checks; note the symptom (such as a black screen or stalled boot) when asking for help",
|
||||
"diagNoFindingsTitle": "No known issues found",
|
||||
"diagRevealFile": "Show in folder",
|
||||
"diagSummaryToggle": "Environment summary",
|
||||
"displays": "Displays",
|
||||
"eject": "Eject installer",
|
||||
"elevateActionFallbackDesc": "A Windows UAC prompt will follow. Reims-Go will not reboot Windows automatically.",
|
||||
@@ -262,6 +331,7 @@ export const coreEn: Record<string, string> = {
|
||||
"errorBoundaryReload": "Reload window",
|
||||
"errorBoundaryTitle": "Something went wrong in the window",
|
||||
"expandLogs": "Show logs",
|
||||
"failCopyDiagnosticsFile": "Couldn’t copy diagnostics archive",
|
||||
"failCreate": "Couldn’t create {name}",
|
||||
"failDownload": "Download failed",
|
||||
"failGeneric": "Something went wrong",
|
||||
@@ -316,7 +386,11 @@ export const coreEn: Record<string, string> = {
|
||||
"logActivity": "Activity",
|
||||
"logButton": "Logs",
|
||||
"logCopy": "Copy logs",
|
||||
"logCopyAnyway": "Copy anyway",
|
||||
"logErrorsOnly": "Errors \u0026 warnings",
|
||||
"logExportDiagnostics": "Export diagnostics",
|
||||
"logLargeCopyDesc": "Pasting {n} lines of logs can flood chat and omits system details; export diagnostics instead",
|
||||
"logLargeCopyTitle": "Long log output",
|
||||
"logQemu": "QEMU",
|
||||
"logSearchPlaceholder": "Filter logs…",
|
||||
"logSerial": "Serial",
|
||||
@@ -336,6 +410,24 @@ export const coreEn: Record<string, string> = {
|
||||
"maximize": "Maximize",
|
||||
"menuBar": "Menu bar",
|
||||
"menuHelp": "Help",
|
||||
"menuMacCut": "Cut",
|
||||
"menuMacDelete": "Delete",
|
||||
"menuMacEdit": "Edit",
|
||||
"menuMacFullScreen": "Enter Full Screen",
|
||||
"menuMacHide": "Hide Reims-Go",
|
||||
"menuMacHideOthers": "Hide Others",
|
||||
"menuMacPaste": "Paste",
|
||||
"menuMacPasteMatchStyle": "Paste and Match Style",
|
||||
"menuMacQuit": "Quit Reims-Go",
|
||||
"menuMacRedo": "Redo",
|
||||
"menuMacSelectAll": "Select All",
|
||||
"menuMacShowAll": "Show All",
|
||||
"menuMacSpeech": "Speech",
|
||||
"menuMacStartSpeaking": "Start Speaking",
|
||||
"menuMacStopSpeaking": "Stop Speaking",
|
||||
"menuMacUndo": "Undo",
|
||||
"menuMacWindow": "Window",
|
||||
"menuMacZoom": "Zoom",
|
||||
"menuVM": "VM",
|
||||
"menuView": "View",
|
||||
"minimize": "Minimize",
|
||||
@@ -387,6 +479,7 @@ export const coreEn: Record<string, string> = {
|
||||
"taskDownload": "Downloading macOS {v}",
|
||||
"taskPluginDownload": "Downloading {name}",
|
||||
"taskRecoveryDownload": "Downloading online recovery for {name}",
|
||||
"taskRestoreVM": "Installing macOS on {name}",
|
||||
"taskRuntime": "Installing runtime {v}",
|
||||
"tasksRunning": "{n, plural, one {# task running} other {# tasks running}}",
|
||||
"themeDark": "Dark",
|
||||
@@ -400,6 +493,7 @@ export const coreEn: Record<string, string> = {
|
||||
"toastCreateCanceled": "Canceled creating {name}",
|
||||
"toastCreateCanceledPartial": "Downloaded progress is kept; resume anytime or edit and retry",
|
||||
"toastCreated": "{name} created",
|
||||
"toastDiagFileCopied": "Diagnostics archive copied — paste to send",
|
||||
"toastDownloadPaused": "Paused — downloading again continues where it stopped",
|
||||
"toastInstallerReady": "macOS {v} installer ready",
|
||||
"toastQueueCanceled": "Removed from download queue",
|
||||
@@ -428,4 +522,6 @@ export const coreEn: Record<string, string> = {
|
||||
"uptimeMinutesSeconds": "{m}m {s}s",
|
||||
"uptimeSeconds": "{s}s",
|
||||
"viewLogs": "View logs",
|
||||
"wizardDriverListFailed": "Could not load guest drivers",
|
||||
"wizardNoDriver": "No eligible guest driver is available",
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// Code generated by cmd/i18ngen; DO NOT EDIT.
|
||||
// Code generated by scripts/i18ngen; DO NOT EDIT.
|
||||
import { registerBuiltinDomain } from '../runtime'
|
||||
|
||||
export const pluginsZh: Record<string, string> = {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Code generated by cmd/i18ngen; DO NOT EDIT.
|
||||
// Code generated by scripts/i18ngen; DO NOT EDIT.
|
||||
import { registerBuiltinDomain } from '../runtime'
|
||||
|
||||
export const settingsZh: Record<string, string> = {
|
||||
@@ -15,9 +15,10 @@ export const settingsZh: Record<string, string> = {
|
||||
"aboutLicensesTitle": "开源许可与声明",
|
||||
"aboutLicensesView": "查看",
|
||||
"aboutQQGroup": "QQ 交流群",
|
||||
"aboutQQLaunchFailed": "未能拉起 QQ,可复制群号手动搜索加入",
|
||||
"aboutQQNotInstalled": "未安装 QQ",
|
||||
"aboutQQNotInstalledSub": "未检测到本地 QQ,可复制群号手动搜索加入",
|
||||
"aboutQQLaunchFailed": "未能打开 QQ,可打开邀请页或复制群号",
|
||||
"aboutQQNotInstalled": "无法直接打开 QQ",
|
||||
"aboutQQNotInstalledSub": "未找到可处理加群链接的 QQ,可打开邀请页或复制群号",
|
||||
"aboutQQOpenInvite": "打开邀请页",
|
||||
"aboutTagline": "在 Windows 上开一台带 GPU 加速的 macOS 虚拟机——免编译,开箱即用。",
|
||||
"activate": "使用",
|
||||
"affinityApplyNow": "立即应用",
|
||||
@@ -53,6 +54,10 @@ export const settingsZh: Record<string, string> = {
|
||||
"affinitySummaryNonLPE": "P + E 核({count} 线程 · {mask})",
|
||||
"affinitySummaryPCores": "仅 P 核({count} 线程 · {mask})",
|
||||
"affinityTitle": "处理器核心",
|
||||
"agentTakeoverPauseDesc": "在虚拟机窗口操作键鼠后暂停外部输入的时间,设为「手动恢复」则需点击继续",
|
||||
"agentTakeoverPauseManual": "直到手动恢复",
|
||||
"agentTakeoverPauseSeconds": "{seconds} 秒",
|
||||
"agentTakeoverPauseTitle": "AI 操作接管暂停时长",
|
||||
"appCheckUpdate": "检查更新",
|
||||
"appUpToDate": "已是最新",
|
||||
"appUpdateAvailable": "发现新版本 {v}(稳定版)",
|
||||
@@ -66,6 +71,7 @@ export const settingsZh: Record<string, string> = {
|
||||
"appUpdateChannelTitle": "更新通道",
|
||||
"appUpdateLookupFailed": "暂时无法连接 GitHub 检查更新",
|
||||
"appVersionTitle": "客户端版本",
|
||||
"appleVirtualizationTitle": "Apple 虚拟化",
|
||||
"appliesNextStart": "下次启动生效",
|
||||
"audioBackendAuto": "自动",
|
||||
"audioBackendDesc": "「静音」保留 macOS 的声卡但不出声,适合排查音频问题",
|
||||
@@ -345,6 +351,7 @@ export const settingsZh: Record<string, string> = {
|
||||
"imagesOpenPlugins": "前往插件",
|
||||
"imagesSourcesLabel": "镜像来源",
|
||||
"installersAvailable": "Apple 提供的版本",
|
||||
"installersCacheUnavailable": "缓存镜像不可用",
|
||||
"installersCreateVM": "新建虚拟机",
|
||||
"installersDelete": "删除",
|
||||
"installersDeleteConfirm": "确认删除",
|
||||
@@ -531,9 +538,10 @@ export const settingsEn: Record<string, string> = {
|
||||
"aboutLicensesTitle": "Open-source licenses",
|
||||
"aboutLicensesView": "View",
|
||||
"aboutQQGroup": "QQ Group",
|
||||
"aboutQQLaunchFailed": "Couldn’t launch QQ — copy the group ID to join manually",
|
||||
"aboutQQNotInstalled": "QQ not installed",
|
||||
"aboutQQNotInstalledSub": "Local QQ wasn’t detected — copy the group ID to join manually",
|
||||
"aboutQQLaunchFailed": "Couldn’t open QQ — open the invite page or copy the group ID",
|
||||
"aboutQQNotInstalled": "Can’t open QQ directly",
|
||||
"aboutQQNotInstalledSub": "No QQ app can handle the invite link — open the invite page or copy the group ID",
|
||||
"aboutQQOpenInvite": "Open invite page",
|
||||
"aboutTagline": "Run a GPU-accelerated macOS virtual machine on Windows — prebuilt, ready out of the box.",
|
||||
"activate": "Use",
|
||||
"affinityApplyNow": "Apply Now",
|
||||
@@ -569,6 +577,10 @@ export const settingsEn: Record<string, string> = {
|
||||
"affinitySummaryNonLPE": "P + E ({count}T · {mask})",
|
||||
"affinitySummaryPCores": "P-Cores ({count}T · {mask})",
|
||||
"affinityTitle": "CPU cores",
|
||||
"agentTakeoverPauseDesc": "How long external control pauses after physical keyboard or mouse input in a VM window",
|
||||
"agentTakeoverPauseManual": "Until manual resume",
|
||||
"agentTakeoverPauseSeconds": "{seconds} seconds",
|
||||
"agentTakeoverPauseTitle": "AI takeover pause duration",
|
||||
"appCheckUpdate": "Check for updates",
|
||||
"appUpToDate": "Up to date",
|
||||
"appUpdateAvailable": "New stable release {v} available",
|
||||
@@ -582,6 +594,7 @@ export const settingsEn: Record<string, string> = {
|
||||
"appUpdateChannelTitle": "Update channel",
|
||||
"appUpdateLookupFailed": "Couldn’t check GitHub for updates",
|
||||
"appVersionTitle": "App version",
|
||||
"appleVirtualizationTitle": "Apple Virtualization",
|
||||
"appliesNextStart": "Applies on next start",
|
||||
"audioBackendAuto": "Auto",
|
||||
"audioBackendDesc": "Silent keeps the macOS sound card but plays nothing; useful for troubleshooting",
|
||||
@@ -861,6 +874,7 @@ export const settingsEn: Record<string, string> = {
|
||||
"imagesOpenPlugins": "Open Plugins",
|
||||
"imagesSourcesLabel": "Image sources",
|
||||
"installersAvailable": "Releases from Apple",
|
||||
"installersCacheUnavailable": "Cached image unavailable",
|
||||
"installersCreateVM": "Create VM",
|
||||
"installersDelete": "Delete",
|
||||
"installersDeleteConfirm": "Confirm delete",
|
||||
|
||||
@@ -1,8 +1,41 @@
|
||||
// Code generated by cmd/i18ngen; DO NOT EDIT.
|
||||
// Code generated by scripts/i18ngen; DO NOT EDIT.
|
||||
|
||||
export const vmZh: Record<string, string> = {
|
||||
"attachGuestTools": "挂载 Guest Tools",
|
||||
"attachInstaller": "挂载离线镜像",
|
||||
"autoInstallAccountName": "账户短名(小写 ASCII)",
|
||||
"autoInstallAppearance": "系统外观",
|
||||
"autoInstallAppearanceAuto": "自动",
|
||||
"autoInstallAppearanceDark": "深色",
|
||||
"autoInstallAppearanceLight": "浅色",
|
||||
"autoInstallCopySummary": "复制脱敏摘要",
|
||||
"autoInstallDesc": "纯本地视觉定位与状态机自动走完恢复终端、跨重启等待与设置助理,无需联网模型",
|
||||
"autoInstallDownloadOCR": "下载 RapidOCR",
|
||||
"autoInstallFileVaultNote": "自动装机默认关闭 FileVault 以免阻断无人值守重启,进入桌面后可按需开启",
|
||||
"autoInstallFullName": "账户全名(ASCII)",
|
||||
"autoInstallHideOptions": "收起选项",
|
||||
"autoInstallIncludeAccountToggle": "同时预置本地账户并自动登录桌面(REIMSPROV)",
|
||||
"autoInstallOCRMissing": "当前 Windows 缺少目标语种 OCR 包,可按需下载 RapidOCR 备选模型",
|
||||
"autoInstallOCRMissingInstallPack": "当前 Windows 缺少目标语种 OCR 包,需在 Windows 设置安装对应语言包或离线导入 RapidOCR 包",
|
||||
"autoInstallOCRReady": "本地 OCR 已就绪({backend})",
|
||||
"autoInstallOptions": "选项…",
|
||||
"autoInstallPassword": "账户密码(≥4 位可见 ASCII)",
|
||||
"autoInstallPause": "暂停",
|
||||
"autoInstallRecoveryOnlyHint": "仅自动完成恢复模式安装(无需账户密码;启动即同意 Apple 软件许可协议)",
|
||||
"autoInstallResume": "继续自动安装",
|
||||
"autoInstallSLAConfirm": "已阅读并同意 Apple 软件许可协议,允许自动确认许可与完成安装",
|
||||
"autoInstallSaveUnlock": "安装完成后保留密码作解锁凭据(默认进桌面后自动清除)",
|
||||
"autoInstallStart": "开始自动安装",
|
||||
"autoInstallStatusCompleted": "已进入可用桌面",
|
||||
"autoInstallStatusFailed": "自动安装已中止",
|
||||
"autoInstallStatusPaused": "已暂停等待处理",
|
||||
"autoInstallStatusRunning": "正在自动安装",
|
||||
"autoInstallStop": "停止装机",
|
||||
"autoInstallSummaryCopied": "已复制脱敏摘要",
|
||||
"autoInstallTitle": "自动完成 macOS 安装",
|
||||
"autoRecoveryDesc": "自动识别恢复界面、快捷键打开终端运行安装脚本并等待重启进入系统;运行期间锁定虚拟机画面防干扰(点右上角悬浮窗「暂停」可接管);开启即同意 Apple 软件许可协议(startosinstall --agreetolicense)",
|
||||
"autoRecoveryToggle": "自动完成恢复模式安装",
|
||||
"autoSetupGroupTitle": "自动安装与首启预配置",
|
||||
"bridgeCreateCommandHint": "此命令创建基础配置;桥接由管理器随后应用,单独运行命令不会配置宿主出口",
|
||||
"brokenHint": "这台虚拟机的配置无法读取",
|
||||
"cloneConfirm": "立即派生",
|
||||
@@ -10,6 +43,15 @@ export const vmZh: Record<string, string> = {
|
||||
"cloneNameLabel": "新虚拟机名称",
|
||||
"cloneTitle": "从「{name}」派生 CoW 副本",
|
||||
"cloneVM": "秒级派生副本 (CoW)",
|
||||
"confirmAllow": "允许",
|
||||
"confirmDeny": "拒绝",
|
||||
"confirmDuration10": "10 分钟",
|
||||
"confirmDuration30": "30 分钟",
|
||||
"confirmDuration60": "60 分钟",
|
||||
"confirmDurationLabel": "授权时长",
|
||||
"confirmDurationUntilExit": "直到离开此阶段",
|
||||
"confirmPhaseScope": "授权范围:截屏与键鼠输入(仅存内存,退出或点停止立即撤销)",
|
||||
"confirmTimedOut": "授权确认已超时关闭,对应操作已按拒绝处理",
|
||||
"connGroup": "连接",
|
||||
"copyScreenshot": "截屏并复制",
|
||||
"cores": "{n, plural, other {# 核}}",
|
||||
@@ -75,6 +117,7 @@ export const vmZh: Record<string, string> = {
|
||||
"failFullscreen": "无法切换全屏",
|
||||
"failGuestTools": "Guest Tools 操作失败",
|
||||
"failOpenFolder": "无法打开文件夹",
|
||||
"failProvision": "写入预配置卷失败",
|
||||
"failRestart": "重启失败",
|
||||
"failResume": "恢复失败",
|
||||
"failScreenshot": "截屏失败",
|
||||
@@ -158,6 +201,21 @@ export const vmZh: Record<string, string> = {
|
||||
"phaseInstaller": "安装阶段",
|
||||
"phaseRecovery": "恢复模式",
|
||||
"pickRecoveryTitle": "选择离线镜像(.img / .dmg)",
|
||||
"provisionDesc": "离线安装时通过 PBKDF2 哈希创建本地管理员、跳过设置助理与键盘向导,并预装 Guest Tools(明文密码不落盘)",
|
||||
"provisionGroupTitle": "首启预配置(跳过设置助理)",
|
||||
"provisionInstallGuestTools": "预装 Reims Guest Tools(启用网络后首次登录自动启动)",
|
||||
"provisionReadyNoticeDesc": "点击「退出恢复模式」以弹出安装介质、覆零清理预配置卷并启用网络与 Guest Tools",
|
||||
"provisionReadyNoticeTitle": "macOS 安装已完成并首次启动就绪",
|
||||
"provisionToggle": "预置本地账户并跳过设置助理",
|
||||
"remoteControlActive": "AI 正在操作 · {plugin}",
|
||||
"remoteControlInputLocked": "画面已锁定防干扰",
|
||||
"remoteControlPause": "暂停",
|
||||
"remoteControlPaused": "已暂停,手动处理后点击继续",
|
||||
"remoteControlPhaseAuth": "AI 正在操作({phase}已授权)",
|
||||
"remoteControlPhaseAuthTimer": "AI 正在操作({phase}已授权 · 剩余 {minutes} 分钟)",
|
||||
"remoteControlResume": "继续",
|
||||
"remoteControlStop": "停止",
|
||||
"remoteControlTakeoverCountdown": "检测到键鼠操作,{seconds} 秒后自动恢复",
|
||||
"restartToApply": "重启以应用",
|
||||
"resume": "恢复",
|
||||
"resumeUnavailable": "切换到支持挂起的内核后可恢复",
|
||||
@@ -222,7 +280,6 @@ export const vmZh: Record<string, string> = {
|
||||
"techInfo": "技术信息",
|
||||
"toastCloned": "已派生 CoW 副本「{name}」",
|
||||
"toastDeleted": "已删除 {name}",
|
||||
"toastDiagExported": "已导出脱敏排障日志包 (.zip)",
|
||||
"toastDiscardSuspend": "已放弃 {name} 的挂起状态",
|
||||
"toastEjected": "已弹出安装盘",
|
||||
"toastEnterRecovery": "已进入恢复模式,启动后可在引导菜单选 Recovery",
|
||||
@@ -263,6 +320,39 @@ export const vmZh: Record<string, string> = {
|
||||
export const vmEn: Record<string, string> = {
|
||||
"attachGuestTools": "Attach Guest Tools",
|
||||
"attachInstaller": "Attach offline image",
|
||||
"autoInstallAccountName": "Account name (lowercase ASCII)",
|
||||
"autoInstallAppearance": "Appearance",
|
||||
"autoInstallAppearanceAuto": "Auto",
|
||||
"autoInstallAppearanceDark": "Dark",
|
||||
"autoInstallAppearanceLight": "Light",
|
||||
"autoInstallCopySummary": "Copy redacted summary",
|
||||
"autoInstallDesc": "Local OCR and declarative state machine automate Recovery, reboots, and Setup Assistant without cloud APIs",
|
||||
"autoInstallDownloadOCR": "Download RapidOCR",
|
||||
"autoInstallFileVaultNote": "FileVault stays off during unattended setup so reboots never block; enable it after reaching Desktop",
|
||||
"autoInstallFullName": "Full name (ASCII)",
|
||||
"autoInstallHideOptions": "Hide options",
|
||||
"autoInstallIncludeAccountToggle": "Also pre-configure local account and unlock desktop (REIMSPROV)",
|
||||
"autoInstallOCRMissing": "Windows OCR language pack is missing; download the RapidOCR fallback bundle",
|
||||
"autoInstallOCRMissingInstallPack": "Windows OCR language pack is missing; install the language pack in Windows Settings or import an offline RapidOCR bundle",
|
||||
"autoInstallOCRReady": "Local OCR ready ({backend})",
|
||||
"autoInstallOptions": "Options…",
|
||||
"autoInstallPassword": "Password (4+ printable ASCII)",
|
||||
"autoInstallPause": "Pause",
|
||||
"autoInstallRecoveryOnlyHint": "Automate Recovery mode only (no account required; starting accepts the Apple Software License Agreement)",
|
||||
"autoInstallResume": "Resume auto-install",
|
||||
"autoInstallSLAConfirm": "I accept the Apple Software License Agreement and authorize unattended installation",
|
||||
"autoInstallSaveUnlock": "Keep password as unlock credential after setup (cleared on desktop arrival by default)",
|
||||
"autoInstallStart": "Start auto-install",
|
||||
"autoInstallStatusCompleted": "Desktop ready",
|
||||
"autoInstallStatusFailed": "Auto-install stopped",
|
||||
"autoInstallStatusPaused": "Paused for user",
|
||||
"autoInstallStatusRunning": "Auto-install running",
|
||||
"autoInstallStop": "Stop install",
|
||||
"autoInstallSummaryCopied": "Redacted summary copied",
|
||||
"autoInstallTitle": "Automatic macOS installation",
|
||||
"autoRecoveryDesc": "Detects macOS Recovery, opens Terminal via shortcut to run the installer script, and restarts into macOS automatically. VM screen input is locked while running (click Pause on the top-right HUD to take over). Enabling accepts the Apple Software License Agreement (startosinstall --agreetolicense)",
|
||||
"autoRecoveryToggle": "Automate Recovery mode installation",
|
||||
"autoSetupGroupTitle": "Automated setup and provisioning",
|
||||
"bridgeCreateCommandHint": "This command creates the base configuration; the manager applies bridging afterward. Running this command alone does not configure the host uplink.",
|
||||
"brokenHint": "This VM’s configuration can’t be read",
|
||||
"cloneConfirm": "Create clone",
|
||||
@@ -270,6 +360,15 @@ export const vmEn: Record<string, string> = {
|
||||
"cloneNameLabel": "New VM name",
|
||||
"cloneTitle": "Derive CoW clone from “{name}”",
|
||||
"cloneVM": "Derive CoW clone",
|
||||
"confirmAllow": "Allow",
|
||||
"confirmDeny": "Deny",
|
||||
"confirmDuration10": "10 minutes",
|
||||
"confirmDuration30": "30 minutes",
|
||||
"confirmDuration60": "60 minutes",
|
||||
"confirmDurationLabel": "Authorization duration",
|
||||
"confirmDurationUntilExit": "Until leaving this phase",
|
||||
"confirmPhaseScope": "Scope: screenshots and keyboard/mouse input (memory only; revoked on exit or Stop)",
|
||||
"confirmTimedOut": "Confirmation timed out and was treated as denied",
|
||||
"connGroup": "Connection",
|
||||
"copyScreenshot": "Copy screenshot",
|
||||
"cores": "{n, plural, one {# core} other {# cores}}",
|
||||
@@ -335,6 +434,7 @@ export const vmEn: Record<string, string> = {
|
||||
"failFullscreen": "Couldn’t toggle full screen",
|
||||
"failGuestTools": "Guest Tools operation failed",
|
||||
"failOpenFolder": "Couldn’t open the folder",
|
||||
"failProvision": "Failed to prepare provisioning disk",
|
||||
"failRestart": "Couldn’t restart",
|
||||
"failResume": "Couldn’t resume",
|
||||
"failScreenshot": "Screenshot failed",
|
||||
@@ -418,6 +518,21 @@ export const vmEn: Record<string, string> = {
|
||||
"phaseInstaller": "Installer",
|
||||
"phaseRecovery": "Recovery",
|
||||
"pickRecoveryTitle": "Choose an offline image (.img / .dmg)",
|
||||
"provisionDesc": "Creates a local admin using a PBKDF2 hash during offline install, skips Setup Assistant and Keyboard Assistant, and stages Guest Tools (no plaintext password on disk)",
|
||||
"provisionGroupTitle": "First-boot provisioning (skip Setup Assistant)",
|
||||
"provisionInstallGuestTools": "Pre-stage Reims Guest Tools (starts on first login once network is enabled)",
|
||||
"provisionReadyNoticeDesc": "Click Exit recovery mode to eject the installer, wipe the provisioning disk, and enable network and Guest Tools",
|
||||
"provisionReadyNoticeTitle": "macOS installation finished and reached first boot",
|
||||
"provisionToggle": "Pre-configure local account and skip Setup Assistant",
|
||||
"remoteControlActive": "AI controlling · {plugin}",
|
||||
"remoteControlInputLocked": "Screen input locked",
|
||||
"remoteControlPause": "Pause",
|
||||
"remoteControlPaused": "Paused; finish this step and click Resume",
|
||||
"remoteControlPhaseAuth": "AI controlling ({phase} authorized)",
|
||||
"remoteControlPhaseAuthTimer": "AI controlling ({phase} authorized · {minutes}m left)",
|
||||
"remoteControlResume": "Resume",
|
||||
"remoteControlStop": "Stop",
|
||||
"remoteControlTakeoverCountdown": "User input detected; resumes in {seconds}s",
|
||||
"restartToApply": "Restart to apply",
|
||||
"resume": "Resume",
|
||||
"resumeUnavailable": "Switch to a runtime that supports suspend to resume this VM",
|
||||
@@ -482,7 +597,6 @@ export const vmEn: Record<string, string> = {
|
||||
"techInfo": "Technical details",
|
||||
"toastCloned": "CoW clone “{name}” created",
|
||||
"toastDeleted": "{name} deleted",
|
||||
"toastDiagExported": "Redacted diagnostics archive exported (.zip)",
|
||||
"toastDiscardSuspend": "Discarded saved state for {name}",
|
||||
"toastEjected": "Installer ejected",
|
||||
"toastEnterRecovery": "Recovery mode ready — pick Recovery in OpenCore on next start",
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
// Code generated by cmd/i18ngen; DO NOT EDIT.
|
||||
// Code generated by scripts/i18ngen; DO NOT EDIT.
|
||||
import { registerBuiltinDomain } from '../runtime'
|
||||
|
||||
export const wizardZh: Record<string, string> = {
|
||||
"armRestoreDownload": "下载 IPSW",
|
||||
"armRestoreDownloaded": "已下载的 IPSW",
|
||||
"armRestoreGroup": "ARM 恢复镜像",
|
||||
"armRestoreMediaHint": "从 Apple 下载 IPSW。创建虚拟机时,请在下方选择已制作的 Stambha 启动介质和可写虚拟磁盘。",
|
||||
"armRestoreVersion": "macOS 27.2.1 (26B131) · 25.6 GB",
|
||||
"armRuntimeLabel": "ARM64 来宾",
|
||||
"commandToggle": "等效命令",
|
||||
"commandToggleHint": "在终端运行下面这条命令效果相同",
|
||||
"createNow": "创建",
|
||||
@@ -59,6 +65,11 @@ export const wizardZh: Record<string, string> = {
|
||||
"srcAppleTitle": "从 Apple 下载",
|
||||
"srcDiskSub": "已装好 macOS 的 .qcow2 等磁盘",
|
||||
"srcDiskTitle": "已有磁盘",
|
||||
"srcIPSWDownloadSub": "从 Apple 下载或使用已下载的镜像",
|
||||
"srcIPSWDownloadTitle": "兼容恢复镜像",
|
||||
"srcIPSWLocalSub": "选择这台 Mac 上的 .ipsw 文件",
|
||||
"srcIPSWLocalTitle": "本地恢复镜像",
|
||||
"srcIPSWNone": "没有兼容的恢复镜像",
|
||||
"srcInstallerSub": "本机上的 .img 或 .dmg",
|
||||
"srcInstallerTitle": "安装镜像",
|
||||
"srcOfflineSub": "完整安装包,装机时不联网",
|
||||
@@ -90,9 +101,16 @@ export const wizardZh: Record<string, string> = {
|
||||
"wizardDriverGroup": "客体平台驱动",
|
||||
"wizardDriverType": "驱动类型",
|
||||
"wizardTitle": "新建虚拟机",
|
||||
"x86RuntimeLabel": "x86-64 来宾",
|
||||
}
|
||||
|
||||
export const wizardEn: Record<string, string> = {
|
||||
"armRestoreDownload": "Download IPSW",
|
||||
"armRestoreDownloaded": "Downloaded IPSW",
|
||||
"armRestoreGroup": "ARM restore image",
|
||||
"armRestoreMediaHint": "Download the IPSW from Apple. To create a VM, select prepared Stambha boot media and a writable virtual disk below.",
|
||||
"armRestoreVersion": "macOS 27.2.1 (26B131) · 25.6 GB",
|
||||
"armRuntimeLabel": "ARM64 guest",
|
||||
"commandToggle": "Equivalent command",
|
||||
"commandToggleHint": "Running this in a terminal does the same thing",
|
||||
"createNow": "Create",
|
||||
@@ -150,6 +168,11 @@ export const wizardEn: Record<string, string> = {
|
||||
"srcAppleTitle": "Download from Apple",
|
||||
"srcDiskSub": "A .qcow2 or other disk with macOS installed",
|
||||
"srcDiskTitle": "Existing disk",
|
||||
"srcIPSWDownloadSub": "Download from Apple or use a saved restore image",
|
||||
"srcIPSWDownloadTitle": "Compatible restore image",
|
||||
"srcIPSWLocalSub": "Choose an .ipsw file on this Mac",
|
||||
"srcIPSWLocalTitle": "Local restore image",
|
||||
"srcIPSWNone": "No compatible restore image is available",
|
||||
"srcInstallerSub": "An .img or .dmg on this PC",
|
||||
"srcInstallerTitle": "Installer image",
|
||||
"srcOfflineSub": "The full installer; installs with no network",
|
||||
@@ -181,6 +204,7 @@ export const wizardEn: Record<string, string> = {
|
||||
"wizardDriverGroup": "Guest driver",
|
||||
"wizardDriverType": "Driver",
|
||||
"wizardTitle": "New virtual machine",
|
||||
"x86RuntimeLabel": "x86-64 guest",
|
||||
}
|
||||
|
||||
registerBuiltinDomain(wizardZh, wizardEn)
|
||||
@@ -1,4 +1,4 @@
|
||||
// Code generated by cmd/i18ngen; DO NOT EDIT.
|
||||
// Code generated by scripts/i18ngen; DO NOT EDIT.
|
||||
|
||||
export type I18nKey =
|
||||
| "aboutCommunity"
|
||||
@@ -17,6 +17,7 @@ export type I18nKey =
|
||||
| "aboutQQLaunchFailed"
|
||||
| "aboutQQNotInstalled"
|
||||
| "aboutQQNotInstalledSub"
|
||||
| "aboutQQOpenInvite"
|
||||
| "aboutTagline"
|
||||
| "activate"
|
||||
| "affinityApplyNow"
|
||||
@@ -53,6 +54,10 @@ export type I18nKey =
|
||||
| "affinitySummaryNonLPE"
|
||||
| "affinitySummaryPCores"
|
||||
| "affinityTitle"
|
||||
| "agentTakeoverPauseDesc"
|
||||
| "agentTakeoverPauseManual"
|
||||
| "agentTakeoverPauseSeconds"
|
||||
| "agentTakeoverPauseTitle"
|
||||
| "appCheckUpdate"
|
||||
| "appUpToDate"
|
||||
| "appUpdateAvailable"
|
||||
@@ -67,7 +72,14 @@ export type I18nKey =
|
||||
| "appUpdateLookupFailed"
|
||||
| "appVersionTitle"
|
||||
| "appearance"
|
||||
| "appleVirtualizationTitle"
|
||||
| "appliesNextStart"
|
||||
| "armRestoreDownload"
|
||||
| "armRestoreDownloaded"
|
||||
| "armRestoreGroup"
|
||||
| "armRestoreMediaHint"
|
||||
| "armRestoreVersion"
|
||||
| "armRuntimeLabel"
|
||||
| "attachGuestTools"
|
||||
| "attachInstaller"
|
||||
| "audioBackendAuto"
|
||||
@@ -78,8 +90,41 @@ export type I18nKey =
|
||||
| "audioDesc"
|
||||
| "audioDisabledReason"
|
||||
| "audioTroubleshootNote"
|
||||
| "autoInstallAccountName"
|
||||
| "autoInstallAppearance"
|
||||
| "autoInstallAppearanceAuto"
|
||||
| "autoInstallAppearanceDark"
|
||||
| "autoInstallAppearanceLight"
|
||||
| "autoInstallCopySummary"
|
||||
| "autoInstallDesc"
|
||||
| "autoInstallDownloadOCR"
|
||||
| "autoInstallFileVaultNote"
|
||||
| "autoInstallFullName"
|
||||
| "autoInstallHideOptions"
|
||||
| "autoInstallIncludeAccountToggle"
|
||||
| "autoInstallOCRMissing"
|
||||
| "autoInstallOCRMissingInstallPack"
|
||||
| "autoInstallOCRReady"
|
||||
| "autoInstallOptions"
|
||||
| "autoInstallPassword"
|
||||
| "autoInstallPause"
|
||||
| "autoInstallRecoveryOnlyHint"
|
||||
| "autoInstallResume"
|
||||
| "autoInstallSLAConfirm"
|
||||
| "autoInstallSaveUnlock"
|
||||
| "autoInstallStart"
|
||||
| "autoInstallStatusCompleted"
|
||||
| "autoInstallStatusFailed"
|
||||
| "autoInstallStatusPaused"
|
||||
| "autoInstallStatusRunning"
|
||||
| "autoInstallStop"
|
||||
| "autoInstallSummaryCopied"
|
||||
| "autoInstallTitle"
|
||||
| "autoPinPCores"
|
||||
| "autoRecoveryDesc"
|
||||
| "autoRecoveryToggle"
|
||||
| "autoResolution"
|
||||
| "autoSetupGroupTitle"
|
||||
| "back"
|
||||
| "backToEdit"
|
||||
| "borderless"
|
||||
@@ -139,6 +184,15 @@ export type I18nKey =
|
||||
| "commandToggleHint"
|
||||
| "configured"
|
||||
| "confirm"
|
||||
| "confirmAllow"
|
||||
| "confirmDeny"
|
||||
| "confirmDuration10"
|
||||
| "confirmDuration30"
|
||||
| "confirmDuration60"
|
||||
| "confirmDurationLabel"
|
||||
| "confirmDurationUntilExit"
|
||||
| "confirmPhaseScope"
|
||||
| "confirmTimedOut"
|
||||
| "connGroup"
|
||||
| "copy"
|
||||
| "copyScreenshot"
|
||||
@@ -174,8 +228,29 @@ export type I18nKey =
|
||||
| "diagAhciUpgradeHint"
|
||||
| "diagBackingChainBroken"
|
||||
| "diagBackingChainWarn"
|
||||
| "diagChecklistSteps"
|
||||
| "diagChecklistTitle"
|
||||
| "diagChecklistZip"
|
||||
| "diagCopyArchive"
|
||||
| "diagCopySummary"
|
||||
| "diagDialogTitle"
|
||||
| "diagExternalDriveWarn"
|
||||
| "diagFindingGpuDeviceLostDesc"
|
||||
| "diagFindingGpuDeviceLostTitle"
|
||||
| "diagFindingGpuVulkanFloorDesc"
|
||||
| "diagFindingGpuVulkanFloorTitle"
|
||||
| "diagFindingLowDiskDesc"
|
||||
| "diagFindingLowDiskTitle"
|
||||
| "diagFindingLowMemoryDesc"
|
||||
| "diagFindingLowMemoryTitle"
|
||||
| "diagFindingWhpxUnavailableDesc"
|
||||
| "diagFindingWhpxUnavailableTitle"
|
||||
| "diagHighMemWarn"
|
||||
| "diagIncludedFiles"
|
||||
| "diagNoFindingsDesc"
|
||||
| "diagNoFindingsTitle"
|
||||
| "diagRevealFile"
|
||||
| "diagSummaryToggle"
|
||||
| "discardSuspend"
|
||||
| "discardSuspendConfirm"
|
||||
| "discardSuspendDesc"
|
||||
@@ -287,6 +362,7 @@ export type I18nKey =
|
||||
| "factMemory"
|
||||
| "failAttachInstaller"
|
||||
| "failCloneVM"
|
||||
| "failCopyDiagnosticsFile"
|
||||
| "failCreate"
|
||||
| "failDelete"
|
||||
| "failDiscardSuspend"
|
||||
@@ -303,6 +379,7 @@ export type I18nKey =
|
||||
| "failGeneric"
|
||||
| "failGuestTools"
|
||||
| "failOpenFolder"
|
||||
| "failProvision"
|
||||
| "failRestart"
|
||||
| "failResume"
|
||||
| "failRuntime"
|
||||
@@ -581,6 +658,7 @@ export type I18nKey =
|
||||
| "imagesSourcesLabel"
|
||||
| "importRuntime"
|
||||
| "installersAvailable"
|
||||
| "installersCacheUnavailable"
|
||||
| "installersCreateVM"
|
||||
| "installersDelete"
|
||||
| "installersDeleteConfirm"
|
||||
@@ -616,7 +694,11 @@ export type I18nKey =
|
||||
| "logActivity"
|
||||
| "logButton"
|
||||
| "logCopy"
|
||||
| "logCopyAnyway"
|
||||
| "logErrorsOnly"
|
||||
| "logExportDiagnostics"
|
||||
| "logLargeCopyDesc"
|
||||
| "logLargeCopyTitle"
|
||||
| "logLevel"
|
||||
| "logLevelCustom"
|
||||
| "logLevelDesc"
|
||||
@@ -645,6 +727,24 @@ export type I18nKey =
|
||||
| "memRecHint"
|
||||
| "menuBar"
|
||||
| "menuHelp"
|
||||
| "menuMacCut"
|
||||
| "menuMacDelete"
|
||||
| "menuMacEdit"
|
||||
| "menuMacFullScreen"
|
||||
| "menuMacHide"
|
||||
| "menuMacHideOthers"
|
||||
| "menuMacPaste"
|
||||
| "menuMacPasteMatchStyle"
|
||||
| "menuMacQuit"
|
||||
| "menuMacRedo"
|
||||
| "menuMacSelectAll"
|
||||
| "menuMacShowAll"
|
||||
| "menuMacSpeech"
|
||||
| "menuMacStartSpeaking"
|
||||
| "menuMacStopSpeaking"
|
||||
| "menuMacUndo"
|
||||
| "menuMacWindow"
|
||||
| "menuMacZoom"
|
||||
| "menuVM"
|
||||
| "menuView"
|
||||
| "minimize"
|
||||
@@ -839,12 +939,27 @@ export type I18nKey =
|
||||
| "pluginTrustDev"
|
||||
| "pluginTrustOfficial"
|
||||
| "pluginTrustVerified"
|
||||
| "provisionDesc"
|
||||
| "provisionGroupTitle"
|
||||
| "provisionInstallGuestTools"
|
||||
| "provisionReadyNoticeDesc"
|
||||
| "provisionReadyNoticeTitle"
|
||||
| "provisionToggle"
|
||||
| "qemuASLR"
|
||||
| "qemuASLRHint"
|
||||
| "quitFailed"
|
||||
| "quitInProgress"
|
||||
| "recommendedBadge"
|
||||
| "refresh"
|
||||
| "remoteControlActive"
|
||||
| "remoteControlInputLocked"
|
||||
| "remoteControlPause"
|
||||
| "remoteControlPaused"
|
||||
| "remoteControlPhaseAuth"
|
||||
| "remoteControlPhaseAuthTimer"
|
||||
| "remoteControlResume"
|
||||
| "remoteControlStop"
|
||||
| "remoteControlTakeoverCountdown"
|
||||
| "resAuto"
|
||||
| "resAutoSub"
|
||||
| "resAutoValue"
|
||||
@@ -990,6 +1105,11 @@ export type I18nKey =
|
||||
| "srcAppleTitle"
|
||||
| "srcDiskSub"
|
||||
| "srcDiskTitle"
|
||||
| "srcIPSWDownloadSub"
|
||||
| "srcIPSWDownloadTitle"
|
||||
| "srcIPSWLocalSub"
|
||||
| "srcIPSWLocalTitle"
|
||||
| "srcIPSWNone"
|
||||
| "srcInstallerSub"
|
||||
| "srcInstallerTitle"
|
||||
| "srcOfflineSub"
|
||||
@@ -1069,6 +1189,7 @@ export type I18nKey =
|
||||
| "taskDownload"
|
||||
| "taskPluginDownload"
|
||||
| "taskRecoveryDownload"
|
||||
| "taskRestoreVM"
|
||||
| "taskRuntime"
|
||||
| "tasksRunning"
|
||||
| "techInfo"
|
||||
@@ -1088,7 +1209,7 @@ export type I18nKey =
|
||||
| "toastCreateCanceledPartial"
|
||||
| "toastCreated"
|
||||
| "toastDeleted"
|
||||
| "toastDiagExported"
|
||||
| "toastDiagFileCopied"
|
||||
| "toastDiscardSuspend"
|
||||
| "toastDownloadPaused"
|
||||
| "toastEjected"
|
||||
@@ -1188,5 +1309,8 @@ export type I18nKey =
|
||||
| "wizOptions"
|
||||
| "wizardBasics"
|
||||
| "wizardDriverGroup"
|
||||
| "wizardDriverListFailed"
|
||||
| "wizardDriverType"
|
||||
| "wizardTitle";
|
||||
| "wizardNoDriver"
|
||||
| "wizardTitle"
|
||||
| "x86RuntimeLabel";
|
||||
@@ -0,0 +1,36 @@
|
||||
export interface AutoInstallDraftFields {
|
||||
enabled: boolean
|
||||
autoInstall: boolean
|
||||
installGuestTools: boolean
|
||||
fullName: string
|
||||
accountName: string
|
||||
password: string
|
||||
appearance: 'auto' | 'light' | 'dark'
|
||||
slaAccepted: boolean
|
||||
saveUnlockCredential: boolean
|
||||
}
|
||||
|
||||
export const defaultAutoInstallDraft = (): AutoInstallDraftFields => ({
|
||||
enabled: false,
|
||||
autoInstall: true,
|
||||
installGuestTools: true,
|
||||
fullName: 'Reims User',
|
||||
accountName: 'reims',
|
||||
password: '',
|
||||
appearance: 'auto',
|
||||
slaAccepted: false,
|
||||
saveUnlockCredential: false,
|
||||
})
|
||||
|
||||
const ASCII_PRINTABLE = /^[\x20-\x7E]+$/
|
||||
const ACCOUNT_NAME_RE = /^[a-z][a-z0-9_-]{0,31}$/
|
||||
|
||||
export function validateAutoInstallDraft(d: AutoInstallDraftFields, requireSLA = d.enabled): boolean {
|
||||
if (requireSLA && !d.slaAccepted) return false
|
||||
if (!d.enabled) return true
|
||||
if (!d.slaAccepted) return false
|
||||
if (!d.fullName.trim() || !ASCII_PRINTABLE.test(d.fullName.trim())) return false
|
||||
if (!ACCOUNT_NAME_RE.test(d.accountName.trim().toLowerCase())) return false
|
||||
if (d.password.length < 4 || d.password.length > 256 || !ASCII_PRINTABLE.test(d.password)) return false
|
||||
return true
|
||||
}
|
||||
@@ -1,9 +1,15 @@
|
||||
import type { VMEndpoint, VMInfo, VMListItem } from '../types'
|
||||
import type { InstalledRuntime, VMEndpoint, VMInfo, VMListItem } from '../types'
|
||||
|
||||
// Guest family, driver capabilities and endpoint ordering for non-macOS guests.
|
||||
// Everything here is pure so node:test can load it (scripts/test-endpoints.mjs).
|
||||
|
||||
const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos'
|
||||
export const STAMBHA_DRIVER_ID = 'builtin.driver.stambha'
|
||||
export const STAMBHA_RUNTIME_KIND = 'stambha-hosted'
|
||||
|
||||
export function hasStambhaRuntime(runtimes?: InstalledRuntime[] | null): boolean {
|
||||
return runtimes?.some((rt) => rt.kind === STAMBHA_RUNTIME_KIND && rt.manifest.runtime_api === '0.1.0') ?? false
|
||||
}
|
||||
|
||||
export type GuestFamily = 'macos' | 'linux' | 'windows' | 'android' | ''
|
||||
|
||||
@@ -34,7 +40,7 @@ export function hasCap(caps: readonly string[] | null | undefined, capability: s
|
||||
return !!caps && caps.includes(capability)
|
||||
}
|
||||
|
||||
/** Hosted VMs are run by their driver: no process, window, PID or QMP socket on the host side. */
|
||||
/** Hosted VMs are managed by their driver rather than a host-owned VM process. */
|
||||
export function isHosted(caps: readonly string[] | null | undefined): boolean {
|
||||
return hasCap(caps, 'hosted')
|
||||
}
|
||||
@@ -78,7 +84,7 @@ export function vmFeatures(vm?: { driver_id?: string; capabilities?: readonly st
|
||||
screenshot: hasCap(caps, 'console') || (hasCap(caps, 'qmp') && !hosted),
|
||||
sendText: hasCap(caps, 'console') || (hasCap(caps, 'qmp') && !hosted),
|
||||
suspend: hasCap(caps, 'suspend'),
|
||||
window: !hosted,
|
||||
window: !hosted || hasCap(caps, 'window'),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,6 +150,15 @@ export function splitEndpoints(endpoints: readonly VMEndpoint[] | null | undefin
|
||||
return primaryIdx < 0 ? { rest } : { primary: list[primaryIdx], rest }
|
||||
}
|
||||
|
||||
/** A display window takes precedence over remote access; shell-only drivers keep their endpoint shortcut. */
|
||||
export function primaryVMAccess(features: VMFeatures, endpoints?: readonly VMEndpoint[] | null):
|
||||
{ kind: 'window' } | { kind: 'endpoint'; endpoint: VMEndpoint } | undefined {
|
||||
if (features.window) return { kind: 'window' }
|
||||
if (!features.hosted) return
|
||||
const { primary } = splitEndpoints(endpoints)
|
||||
if (primary) return { kind: 'endpoint', endpoint: primary }
|
||||
}
|
||||
|
||||
/** A stable React key for an endpoint row. */
|
||||
export function endpointKey(ep: VMEndpoint): string {
|
||||
return [ep.kind, ep.host ?? '', ep.port ?? '', ep.distro ?? '', ep.vm ?? '', ep.serial ?? ''].join('|')
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { DriverSummary, HostReport, InstallerKind, SettingProperty } from '../types'
|
||||
import { isMacOSDriver, STAMBHA_RUNTIME_KIND } from './endpoints'
|
||||
|
||||
type HostPlatform = Pick<HostReport, 'os' | 'arch'>
|
||||
|
||||
export function isAppleSilicon(host?: HostPlatform): boolean {
|
||||
return host?.os === 'darwin' && host.arch === 'arm64'
|
||||
}
|
||||
|
||||
export function needsRuntimeSetup(host: HostPlatform, hasRuntime: boolean): boolean {
|
||||
return !isAppleSilicon(host) && !hasRuntime
|
||||
}
|
||||
|
||||
export function eligibleGuestDrivers(drivers: DriverSummary[], hasRuntime: boolean, hasStambha = false): DriverSummary[] {
|
||||
return drivers.filter((driver) => {
|
||||
if (driver.runtime_kind === STAMBHA_RUNTIME_KIND) return hasStambha
|
||||
return driver.runtime_kind === 'external' || hasRuntime
|
||||
})
|
||||
}
|
||||
|
||||
export function defaultGuestDriver(drivers: DriverSummary[], host: HostPlatform, installerKind?: InstallerKind): DriverSummary | undefined {
|
||||
const legacy = drivers.find((driver) => isMacOSDriver(driver.id))
|
||||
if (installerKind === 'ipsw') return drivers.find((driver) => !!restoreImageField(driver, host))
|
||||
if (installerKind) return legacy
|
||||
return isAppleSilicon(host) ? drivers[0] : legacy ?? drivers[0]
|
||||
}
|
||||
|
||||
export function restoreImageField(driver: DriverSummary, host: HostPlatform): string | undefined {
|
||||
if (!isAppleSilicon(host)) return undefined
|
||||
return Object.entries(driver.create_schema?.properties ?? {}).find(([, prop]) => hasRestoreImagePicker(driver, prop))?.[0]
|
||||
}
|
||||
|
||||
/** Only create schemas supplied by the host's trusted built-ins may request a restore picker. */
|
||||
export function hasRestoreImagePicker(driver: DriverSummary, prop: SettingProperty): boolean {
|
||||
return driver.builtin === true && prop.type === 'string' && prop['x-filePattern'] === '*.ipsw'
|
||||
}
|
||||
@@ -28,6 +28,50 @@ export function createLogLine(entry: LogEntry): LogLine {
|
||||
return { ts, source, line, id: nextId++, level }
|
||||
}
|
||||
|
||||
export const LARGE_LOG_LINE_THRESHOLD = 20
|
||||
export const LARGE_LOG_CHAR_THRESHOLD = 2000
|
||||
|
||||
interface FormattableLogRow {
|
||||
ts: string
|
||||
source: string
|
||||
line: string
|
||||
}
|
||||
|
||||
function flattenLogMessage(line: string): string {
|
||||
return line.replace(/^[\r\n]+|[\r\n]+$/g, '').replace(/[\r\n]+/g, ' ')
|
||||
}
|
||||
|
||||
export function formatLogLine(line: FormattableLogRow): string {
|
||||
return `${line.ts} [${line.source}] ${flattenLogMessage(line.line)}`
|
||||
}
|
||||
|
||||
export function formatLogLines(lines: readonly FormattableLogRow[]): string {
|
||||
return lines.map(formatLogLine).join('\n')
|
||||
}
|
||||
|
||||
export function countLogLines(text: string): number {
|
||||
if (!text) return 0
|
||||
const normalized = text.replace(/\r\n?/g, '\n')
|
||||
const trimmed = normalized.endsWith('\n') ? normalized.slice(0, -1) : normalized
|
||||
if (!trimmed) return 0
|
||||
return trimmed.split('\n').length
|
||||
}
|
||||
|
||||
export function isLargeLogPayload(text: string): boolean {
|
||||
if (!text) return false
|
||||
return countLogLines(text) >= LARGE_LOG_LINE_THRESHOLD || text.length >= LARGE_LOG_CHAR_THRESHOLD
|
||||
}
|
||||
|
||||
export function formatSelectedLogRows(rows: ReadonlyArray<{ ts: string; source: string; line: string }>): string {
|
||||
return formatLogLines(
|
||||
rows.map((row) => ({
|
||||
ts: row.ts.trim(),
|
||||
source: row.source.trim(),
|
||||
line: row.line,
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
export function appendLog(prev: LogLine[], line: LogLine): LogLine[] {
|
||||
const next = [...prev, line]
|
||||
return next.length > MAX_LOG_LINES ? next.slice(next.length - MAX_LOG_LINES) : next
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { CachedInstaller, Release } from '../types'
|
||||
|
||||
interface RestoreImageChoice {
|
||||
version: string
|
||||
build: string
|
||||
label: string
|
||||
key: string
|
||||
}
|
||||
|
||||
/** Offer the catalog release and all finished restore images for local reuse. */
|
||||
export function restoreImageChoices(release: Release | undefined, cached: CachedInstaller[]): RestoreImageChoice[] {
|
||||
const choices = new Map<string, RestoreImageChoice>()
|
||||
const add = (title: string, version: string, build: string) => {
|
||||
const key = restoreImageChoiceKey(version, build)
|
||||
if (choices.has(key)) return
|
||||
const label = title.includes(version) ? title : `${title} ${version}`
|
||||
choices.set(key, { key, version, build, label: build ? `${label} (${build})` : label })
|
||||
}
|
||||
if (release) add(release.title, release.version, release.build)
|
||||
for (const image of cached) {
|
||||
if (image.kind !== 'ipsw' || image.partial || !image.path || !image.version) continue
|
||||
add(image.title || 'macOS', image.version, image.build ?? '')
|
||||
}
|
||||
return [...choices.values()]
|
||||
}
|
||||
|
||||
export function restoreImageChoiceKey(version: string, build: string): string {
|
||||
return `${version}|${build}`
|
||||
}
|
||||
|
||||
export function matchesRestoreImage(image: CachedInstaller, version: string, build: string): boolean {
|
||||
return image.kind === 'ipsw' && image.version === version && (image.build ?? '') === build
|
||||
}
|
||||
|
||||
export function cachedRestoreImage(cached: CachedInstaller[], version: string, build: string): CachedInstaller | undefined {
|
||||
return cached.find((image) => !image.partial && !!image.path && matchesRestoreImage(image, version, build))
|
||||
}
|
||||
|
||||
export function restoreImagePathMissing(cached: CachedInstaller[], version: string, build: string): boolean {
|
||||
return cached.some((image) => !image.partial && !image.path && matchesRestoreImage(image, version, build))
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { t } from '../i18n'
|
||||
import { CachedInstaller, InstallerKind, InstallerPhase, Locale, Task } from '../types'
|
||||
import { vmRefKey } from './vmRef'
|
||||
|
||||
// Match the finished-task retention period in internal/app/tasks.go.
|
||||
export const finishedTaskTTL = 10 * 60 * 1000
|
||||
@@ -40,12 +41,21 @@ export function creatingVMTasks(all: Record<string, Task>, existingNames: Readon
|
||||
.sort((a, b) => a.started_at - b.started_at || a.subject.localeCompare(b.subject))
|
||||
}
|
||||
|
||||
/** Match the driver-scoped VM key sent by the restore task emitter. */
|
||||
export function findRunningRestoreTask(tasks: Task[], driverID: string, name: string): Task | undefined {
|
||||
const driver_id = driverID.trim()
|
||||
if (!driver_id || !name.trim()) return undefined
|
||||
const key = vmRefKey({ driver_id, name: name.trim() })
|
||||
return tasks.find((task) => task.kind === 'vm-restore' && task.status === 'running' && task.vm === key)
|
||||
}
|
||||
|
||||
/** Localized title; the upstream step (English) goes in the tooltip. */
|
||||
export function taskTitle(locale: Locale, task: Task): string {
|
||||
switch (task.kind) {
|
||||
case 'installer-download': return t(locale, 'taskDownload', { v: task.subject })
|
||||
case 'recovery-download': return t(locale, 'taskRecoveryDownload', { name: task.subject })
|
||||
case 'vm-create': return t(locale, 'taskCreate', { name: task.subject })
|
||||
case 'vm-restore': return t(locale, 'taskRestoreVM', { name: task.subject })
|
||||
case 'runtime-install': return t(locale, 'taskRuntime', { v: task.subject })
|
||||
case 'app-update': return t(locale, 'taskAppUpdate', { v: task.subject })
|
||||
case 'plugin-download': return t(locale, 'taskPluginDownload', { name: task.subject })
|
||||
@@ -67,7 +77,7 @@ export function isInstallerTask(task: Task): boolean {
|
||||
}
|
||||
|
||||
export function taskInstallerKind(task: Task): InstallerKind | '' {
|
||||
if (task.installer_kind === 'offline' || task.installer_kind === 'online') return task.installer_kind
|
||||
if (task.installer_kind === 'offline' || task.installer_kind === 'online' || task.installer_kind === 'arm-ipsw' || task.installer_kind === 'ipsw') return task.installer_kind
|
||||
if (task.kind === 'installer-download') return 'offline'
|
||||
if (task.kind === 'recovery-download') return 'online'
|
||||
return ''
|
||||
@@ -112,6 +122,7 @@ function matchesCachedInstaller(item: CachedInstaller, task: Task): boolean {
|
||||
const kind = taskInstallerKind(task)
|
||||
if (!kind || kind !== item.kind) return false
|
||||
const v = taskInstallerVersion(task).toLowerCase()
|
||||
if (kind === 'ipsw') return !!v && item.version?.toLowerCase() === v
|
||||
if (kind === 'offline') {
|
||||
if (item.version && item.version.toLowerCase() === v) return true
|
||||
return item.partial && !!v && !/^\d/.test(v) && matchesOnlineInstallerTitle(item.title, v)
|
||||
@@ -151,11 +162,11 @@ function pickPrimaryInstallerTask(matches: Task[]): ActiveInstallerMatch | null
|
||||
return { primary, waitingVMs, matchedIDs: sorted.map((x) => x.id) }
|
||||
}
|
||||
|
||||
export function findActiveOfflineTask(tasks: Task[], version: string): ActiveInstallerMatch | null {
|
||||
export function findActiveInstallerTask(tasks: Task[], kind: InstallerKind, version: string): ActiveInstallerMatch | null {
|
||||
const want = version.trim().toLowerCase()
|
||||
if (!want) return null
|
||||
const matches = tasks.filter(
|
||||
(x) => isActiveInstallerTask(x) && taskInstallerKind(x) === 'offline' && taskInstallerVersion(x).toLowerCase() === want,
|
||||
(x) => isActiveInstallerTask(x) && taskInstallerKind(x) === kind && taskInstallerVersion(x).toLowerCase() === want,
|
||||
)
|
||||
return pickPrimaryInstallerTask(matches)
|
||||
}
|
||||
@@ -184,7 +195,7 @@ export function groupUnmatchedInstallerTasks(activeTasks: Task[], matchedTaskIDs
|
||||
}
|
||||
|
||||
export function taskStopAction(locale: Locale, task: Task): { kind: 'pause' | 'cancel'; label: string } {
|
||||
if (task.kind === 'vm-create') return { kind: 'cancel', label: t(locale, 'cancelCreate') }
|
||||
if (task.kind === 'vm-create' || task.kind === 'vm-restore') return { kind: 'cancel', label: t(locale, 'cancelCreate') }
|
||||
if (task.kind === 'app-update') return { kind: 'cancel', label: t(locale, 'updateCancel') }
|
||||
if (taskInstallerPhase(task) === 'queued') return { kind: 'cancel', label: t(locale, 'cancelQueue') }
|
||||
return { kind: 'pause', label: t(locale, 'pauseDownload') }
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import { t } from '../i18n'
|
||||
import type { Locale, VMAction } from '../types'
|
||||
import { vmFeatures, type VMFeatures } from './endpoints'
|
||||
import type { ThemeMode } from './useAppearance'
|
||||
|
||||
export const REPO_URL = 'https://github.com/Nwflower/Reims-Go'
|
||||
|
||||
export function siteURL(locale: Locale, path = ''): string {
|
||||
const base = locale.toLowerCase().startsWith('zh') ? 'https://reims.dev' : 'https://reims.dev/en'
|
||||
return path ? `${base}${path}` : base
|
||||
}
|
||||
|
||||
export const MENU_IDS = ['vm', 'view', 'help'] as const
|
||||
export type MenuId = (typeof MENU_IDS)[number]
|
||||
|
||||
export type MenuCommand = 'new' | 'vmSettings' | 'sidebar' | 'logs' | 'installers' | 'plugins' | 'host' | 'settings' |
|
||||
'website' | 'docs' | 'project' | 'report' | 'update' | 'about' | `vm:${VMAction}` | `theme:${ThemeMode}`
|
||||
|
||||
export type MenuRow =
|
||||
| { kind: 'separator' }
|
||||
| { kind: 'label'; label: string }
|
||||
| { kind: 'action' | 'check' | 'radio'; command: MenuCommand; label: string; disabled?: boolean; checked?: boolean; danger?: boolean; shortcut?: string; macKey?: string }
|
||||
|
||||
export interface TitleMenuState {
|
||||
locale: Locale
|
||||
sidebarOpen: boolean
|
||||
logsOpen: boolean
|
||||
themeMode: ThemeMode
|
||||
canLight: boolean
|
||||
canDark: boolean
|
||||
vm: { name: string; driver_id?: string; state: string; busy: boolean; graphics?: string; canSuspend: boolean; features: VMFeatures } | null
|
||||
fullscreenHotkey?: string
|
||||
appVersion?: string
|
||||
}
|
||||
|
||||
export interface TitleMenuProps extends TitleMenuState {
|
||||
onToggleSidebar: () => void
|
||||
onToggleLogs: () => void
|
||||
onThemeMode: (mode: ThemeMode) => void
|
||||
onNewVM: () => void
|
||||
onVMAction: (action: VMAction) => void
|
||||
onVMSettings: () => void
|
||||
onVMDelete: () => void
|
||||
onNavigate: (page: 'installers' | 'plugins' | 'host' | 'settings' | 'about') => void
|
||||
onOpenURL: (url: string) => void
|
||||
}
|
||||
|
||||
export function buildTitleMenus(state: TitleMenuState, fullscreen: boolean | undefined = undefined) {
|
||||
const { vm, locale, appVersion, fullscreenHotkey, sidebarOpen, logsOpen, canLight, canDark, themeMode } = state
|
||||
const tr = (key: Parameters<typeof t>[1]) => t(locale, key)
|
||||
const running = vm?.state === 'running'
|
||||
const stopped = vm?.state === 'stopped'
|
||||
const suspended = vm?.state === 'suspended'
|
||||
const transitioning = vm?.state === 'starting' || vm?.state === 'stopping' || vm?.state === 'suspending' || vm?.state === 'resuming'
|
||||
const busy = !vm || vm.busy
|
||||
const features = vm?.features ?? vmFeatures(null)
|
||||
const canFullscreen = running && features.fullscreen && vm?.graphics !== 'vmware-svga'
|
||||
const fullscreenLabel = !canFullscreen || fullscreen === undefined ? tr('toggleFullscreen') : fullscreen ? tr('exitFullscreen') : tr('enterFullscreen')
|
||||
const sep = { kind: 'separator' } as const
|
||||
const vmRows: MenuRow[] = [{ kind: 'action', command: 'new', label: tr('newVMEllipsis'), shortcut: 'Ctrl+N', macKey: 'n' }, sep]
|
||||
if (running) {
|
||||
if (features.window) vmRows.push({ kind: 'action', command: 'vm:focus', label: tr('showWindow'), shortcut: 'Ctrl+Enter', macKey: '\r', disabled: busy })
|
||||
} else if (suspended) {
|
||||
vmRows.push({ kind: 'action', command: 'vm:resume', label: tr('resume'), shortcut: vm.canSuspend ? 'Ctrl+Enter' : undefined, macKey: vm.canSuspend ? '\r' : undefined, disabled: busy || !vm.canSuspend })
|
||||
if (!vm.canSuspend) vmRows.push({ kind: 'label', label: tr('resumeUnavailable') })
|
||||
} else {
|
||||
vmRows.push({ kind: 'action', command: 'vm:start', label: tr('start'), shortcut: 'Ctrl+Enter', macKey: '\r', disabled: busy || !stopped })
|
||||
}
|
||||
if (features.fullscreen) vmRows.push({ kind: 'action', command: 'vm:fullscreen', label: fullscreenLabel, shortcut: fullscreenHotkey, disabled: busy || !canFullscreen })
|
||||
if (features.suspend) vmRows.push({ kind: 'action', command: 'vm:suspend', label: tr('suspend'), disabled: busy || !running || !vm?.canSuspend })
|
||||
vmRows.push(
|
||||
{ kind: 'action', command: 'vm:stop', label: tr('stop'), disabled: busy || !running },
|
||||
{ kind: 'action', command: 'vm:restart', label: tr('restart'), disabled: busy || !running },
|
||||
)
|
||||
if (features.screenshot) vmRows.push({ kind: 'action', command: 'vm:screenshot', label: tr('copyScreenshot'), disabled: busy || !running })
|
||||
if (features.macos) vmRows.push(sep,
|
||||
{ kind: 'action', command: 'vmSettings', label: tr('settingsEllipsis'), shortcut: 'Ctrl+,', disabled: !vm || suspended || transitioning },
|
||||
{ kind: 'action', command: 'vm:openFolder', label: tr('openFolder'), disabled: !vm },
|
||||
)
|
||||
vmRows.push(sep)
|
||||
if (suspended) vmRows.push({ kind: 'action', command: 'vm:discardSuspend', label: tr('discardSuspend'), danger: true, disabled: busy })
|
||||
vmRows.push(
|
||||
{ kind: 'action', command: 'vm:forceStop', label: tr('forceStop'), danger: true, disabled: !vm || !(running || transitioning) },
|
||||
{ kind: 'action', command: 'vm:delete', label: tr('deleteEllipsis'), danger: true, disabled: busy || running || suspended || transitioning },
|
||||
)
|
||||
const viewRows: MenuRow[] = [
|
||||
{ kind: 'check', command: 'sidebar', label: tr('sidebarLabel'), checked: sidebarOpen, shortcut: 'Ctrl+B', macKey: 'b' },
|
||||
{ kind: 'check', command: 'logs', label: tr('logButton'), checked: logsOpen, shortcut: 'Ctrl+L', macKey: 'l' },
|
||||
sep,
|
||||
{ kind: 'label', label: tr('appearance') },
|
||||
...(['light', 'dark', 'system'] as const).map((mode): MenuRow => ({
|
||||
kind: 'radio', command: `theme:${mode}`, checked: themeMode === mode,
|
||||
label: tr(mode === 'light' ? 'themeLight' : mode === 'dark' ? 'themeDark' : 'themeSystem'),
|
||||
disabled: mode === 'light' ? !canLight : mode === 'dark' ? !canDark : !canLight || !canDark,
|
||||
})),
|
||||
sep,
|
||||
{ kind: 'action', command: 'installers', label: tr('sidebarInstallers') },
|
||||
{ kind: 'action', command: 'plugins', label: tr('sidebarPlugins') },
|
||||
{ kind: 'action', command: 'host', label: tr('sidebarHost') },
|
||||
{ kind: 'action', command: 'settings', label: tr('sidebarSettings'), macKey: ',' },
|
||||
]
|
||||
const helpRows: MenuRow[] = [
|
||||
{ kind: 'action', command: 'website', label: tr('helpWebsite') },
|
||||
{ kind: 'action', command: 'docs', label: tr('helpDocs') },
|
||||
{ kind: 'action', command: 'project', label: tr('helpProjectPage') },
|
||||
{ kind: 'action', command: 'report', label: tr('helpReportIssue') },
|
||||
{ kind: 'action', command: 'update', label: tr('helpCheckUpdate') },
|
||||
{ kind: 'action', command: 'about', label: tr('helpAbout') },
|
||||
]
|
||||
if (appVersion) helpRows.push(sep, { kind: 'label', label: `Reims-Go ${appVersion}` })
|
||||
return {
|
||||
vm: { label: tr('menuVM'), rows: vmRows },
|
||||
view: { label: tr('menuView'), rows: viewRows },
|
||||
help: { label: tr('menuHelp'), rows: helpRows },
|
||||
}
|
||||
}
|
||||
|
||||
export function runMenuCommand(props: TitleMenuProps, command: MenuCommand): void {
|
||||
switch (command) {
|
||||
case 'new': return props.onNewVM()
|
||||
case 'vmSettings': return props.onVMSettings()
|
||||
case 'vm:delete': return props.onVMDelete()
|
||||
case 'sidebar': return props.onToggleSidebar()
|
||||
case 'logs': return props.onToggleLogs()
|
||||
case 'installers': case 'plugins': case 'host': case 'settings': case 'about': return props.onNavigate(command)
|
||||
case 'update': return props.onNavigate('about')
|
||||
case 'website': return props.onOpenURL(siteURL(props.locale))
|
||||
case 'docs': return props.onOpenURL(siteURL(props.locale, '/docs/quick-start'))
|
||||
case 'project': return props.onOpenURL(REPO_URL)
|
||||
case 'report': return props.onOpenURL(`${REPO_URL}/issues`)
|
||||
}
|
||||
if (command.startsWith('vm:')) props.onVMAction(command.slice(3) as VMAction)
|
||||
else if (command.startsWith('theme:')) props.onThemeMode(command.slice(6) as ThemeMode)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { useEffect, useLayoutEffect, useRef } from 'react'
|
||||
import { hasVisibleDialog } from '../lib/dialogState'
|
||||
import { runMenuCommand, type TitleMenuProps } from '../lib/titleMenu'
|
||||
import { useVMStats } from '../lib/vmStats'
|
||||
import { api, events } from '../wails'
|
||||
import { buildNativeMenu, resolveMenuClick, type MenuClick, type NativeMenuState } from './applicationMenuModel'
|
||||
|
||||
// Use distinct tokens across snapshots, also across renderer reloads while
|
||||
// the old native menu is still installed. A click must never be retargeted.
|
||||
let nextToken = 1 + Math.floor(Math.random() * 0x20000000)
|
||||
|
||||
export function ApplicationMenu({ props, state, onReady }: {
|
||||
props: TitleMenuProps
|
||||
state: NativeMenuState
|
||||
onReady: (ready: boolean) => void
|
||||
}) {
|
||||
const { vm } = props
|
||||
const running = vm?.state === 'running'
|
||||
const stats = useVMStats(vm?.driver_id ?? '', running && vm.features.fullscreen && vm.graphics !== 'vmware-svga' ? vm.name : null, running)
|
||||
const model = buildNativeMenu(props, state, stats?.running ? stats.window_fullscreen : undefined)
|
||||
const key = JSON.stringify([model.scope, model.groups, model.standard])
|
||||
const latest = useRef({ ...model, props })
|
||||
const installed = useRef(new Map<number, MenuClick>())
|
||||
useLayoutEffect(() => { latest.current = { ...model, props } })
|
||||
|
||||
useEffect(() => events.onApplicationMenuCommand((token) => {
|
||||
const entry = installed.current.get(token)
|
||||
const current = latest.current
|
||||
if (!entry || hasVisibleDialog()) return
|
||||
const command = resolveMenuClick(entry, current.scope, current.commands)
|
||||
if (command) runMenuCommand(current.props, command)
|
||||
}), [])
|
||||
|
||||
useEffect(() => {
|
||||
let canceled = false
|
||||
let retry: number | undefined
|
||||
const publish = (attempt: number) => {
|
||||
const { groups, scope, standard } = latest.current
|
||||
const active = new Map<number, MenuClick>()
|
||||
const appGroups = groups.map((group) => ({
|
||||
label: group.label,
|
||||
rows: group.rows.map(({ command, ...row }) => {
|
||||
if (!command) return row
|
||||
const token = nextToken++
|
||||
active.set(token, { scope, command })
|
||||
return { ...row, token }
|
||||
}),
|
||||
}))
|
||||
installed.current = active
|
||||
api.SyncApplicationMenu(JSON.stringify({ groups: appGroups, standard })).then(() => {
|
||||
if (!canceled) onReady(true)
|
||||
}).catch((error) => {
|
||||
if (canceled) return
|
||||
if (attempt < 2) {
|
||||
retry = window.setTimeout(() => publish(attempt + 1), 250)
|
||||
return
|
||||
}
|
||||
installed.current.clear()
|
||||
onReady(false)
|
||||
console.warn('[app] Could not update the macOS application menu:', error)
|
||||
})
|
||||
}
|
||||
publish(0)
|
||||
return () => {
|
||||
canceled = true
|
||||
window.clearTimeout(retry)
|
||||
}
|
||||
}, [key, onReady])
|
||||
return null
|
||||
}
|
||||
@@ -3,12 +3,14 @@ import React, { useEffect, useRef, useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import '../i18n/domains/wizard.gen'
|
||||
import { WordmarkLoader } from '../components/WordmarkLoader'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { I18nKey, parseAppError, t } from '../i18n'
|
||||
import { macOSMajor } from './macosRelease'
|
||||
import { isAppleSilicon } from '../lib/guestDrivers'
|
||||
import { matchesRestoreImage, restoreImagePathMissing } from '../lib/restoreImages'
|
||||
import {
|
||||
ActiveInstallerMatch,
|
||||
findActiveCachedTask,
|
||||
findActiveOfflineTask,
|
||||
findActiveInstallerTask,
|
||||
groupUnmatchedInstallerTasks,
|
||||
isActiveInstallerTask,
|
||||
isInstallerTask,
|
||||
@@ -82,6 +84,7 @@ export const InstallersPage: React.FC<Props> = ({
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [cached, setCached] = useState<CachedInstaller[] | null>(null)
|
||||
const [cacheError, setCacheError] = useState(false)
|
||||
const [releases, setReleases] = useState<Release[] | null>(null)
|
||||
const [releasesErr, setReleasesErr] = useState('')
|
||||
const [confirmDelete, setConfirmDelete] = useState('')
|
||||
@@ -89,20 +92,23 @@ export const InstallersPage: React.FC<Props> = ({
|
||||
const onBusyChangeRef = useRef(onBusyChange)
|
||||
onBusyChangeRef.current = onBusyChange
|
||||
|
||||
const installerTasks = tasks.filter(isInstallerTask)
|
||||
const releaseKind = isAppleSilicon(host) ? 'ipsw' : 'offline'
|
||||
const installerTasks = tasks.filter((task) => isInstallerTask(task) && (releaseKind === 'ipsw') === (taskInstallerKind(task) === 'ipsw'))
|
||||
const activeInstallerTasks = installerTasks.filter(isActiveInstallerTask)
|
||||
const installerTasksSig = installerTasks
|
||||
.map((x) => `${x.id}:${x.status}:${x.installer_phase ?? ''}`)
|
||||
.sort()
|
||||
.join('|')
|
||||
|
||||
const loadCached = () => api.ListInstallers().then((l) => setCached(l ?? [])).catch((e) => onError(tr('failGeneric'), e))
|
||||
const loadCached = () => api.ListInstallers()
|
||||
.then((l) => { setCached(l ?? []); setCacheError(false) })
|
||||
.catch((e) => { setCacheError(true); onError(tr('failGeneric'), e) })
|
||||
const loadReleases = () => {
|
||||
setReleases(null)
|
||||
setReleasesErr('')
|
||||
api.ListOfflineReleases()
|
||||
.then((l) => setReleases(l ?? []))
|
||||
.catch((e) => setReleasesErr(String(e).replace(/^Error:\s*/, '')))
|
||||
.catch((e) => setReleasesErr(parseAppError(e).summary))
|
||||
}
|
||||
useEffect(() => { loadReleases() }, [])
|
||||
useEffect(() => {
|
||||
@@ -127,9 +133,13 @@ export const InstallersPage: React.FC<Props> = ({
|
||||
api.OpenURL(APPLE_SLA_URL).catch((e) => onError(tr('failGeneric'), e))
|
||||
}
|
||||
|
||||
const downloaded = (version: string) => (cached ?? []).find((c) => c.kind === 'offline' && !c.partial && c.version === version)
|
||||
const partial = (version: string) => (cached ?? []).some((c) => c.kind === 'offline' && c.partial && c.version === version)
|
||||
const activeForRelease = (version: string) => findActiveOfflineTask(activeInstallerTasks, version)
|
||||
const matchesRelease = (item: CachedInstaller, r: Release) => releaseKind === 'ipsw'
|
||||
? matchesRestoreImage(item, r.version, r.build)
|
||||
: item.kind === 'offline' && item.version === r.version
|
||||
const downloaded = (r: Release) => (cached ?? []).find((c) => matchesRelease(c, r) && !!c.path && !c.partial)
|
||||
const partial = (r: Release) => (cached ?? []).find((c) => matchesRelease(c, r) && c.partial)
|
||||
const missingRestorePath = (r: Release) => releaseKind === 'ipsw' && restoreImagePathMissing(cached ?? [], r.version, r.build)
|
||||
const activeForRelease = (version: string) => findActiveInstallerTask(activeInstallerTasks, releaseKind, version)
|
||||
|
||||
const download = (version: string) => {
|
||||
api.DownloadInstaller(version).catch((e) => onError(tr('failDownload'), e))
|
||||
@@ -173,7 +183,10 @@ export const InstallersPage: React.FC<Props> = ({
|
||||
)
|
||||
}
|
||||
|
||||
const spaceShort = (r: Release) => !downloaded(r.version) && !activeForRelease(r.version) && host.free_disk_gb > 0 && host.free_disk_gb * 1e9 < needBytes(r)
|
||||
const remainingGB = (r: Release) => releaseKind === 'ipsw'
|
||||
? Math.max(0, r.size - (partial(r)?.bytes ?? 0)) / (2 ** 30)
|
||||
: needBytes(r) / 1e9
|
||||
const spaceShort = (r: Release) => !downloaded(r) && !missingRestorePath(r) && !activeForRelease(r.version) && host.free_disk_gb > 0 && host.free_disk_gb < remainingGB(r)
|
||||
|
||||
const releaseAction = (r: Release) => {
|
||||
const active = activeForRelease(r.version)
|
||||
@@ -194,7 +207,7 @@ export const InstallersPage: React.FC<Props> = ({
|
||||
</span>
|
||||
)
|
||||
}
|
||||
const item = downloaded(r.version)
|
||||
const item = downloaded(r)
|
||||
if (item) {
|
||||
return (
|
||||
<Button variant="primary" icon={<Plus size={14} />} onClick={() => onCreateWithInstaller(item)}>
|
||||
@@ -202,22 +215,26 @@ export const InstallersPage: React.FC<Props> = ({
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
if (missingRestorePath(r)) return <span className="warn-text" role="status">{tr('installersCacheUnavailable')}</span>
|
||||
if (releaseKind === 'ipsw' && cacheError) return <Button onClick={loadCached}>{tr('installersRetry')}</Button>
|
||||
return (
|
||||
<Button icon={<Download size={14} />} disabled={spaceShort(r)} onClick={() => download(r.version)}>
|
||||
{partial(r.version) ? tr('installersResume') : tr('installersDownload')}
|
||||
<Button icon={<Download size={14} />} disabled={spaceShort(r) || (releaseKind === 'ipsw' && cached === null)} onClick={() => download(r.version)}>
|
||||
{partial(r) ? tr('installersResume') : tr('installersDownload')}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
const releaseMeta = (r: Release) => (
|
||||
<div className="row-sub">
|
||||
{r.posted} · {gb(r.size)}
|
||||
{spaceShort(r) && <span className="warn-text"> · {tr('installersNoSpace', { need: Math.ceil(needBytes(r) / 1e9), free: host.free_disk_gb.toFixed(0) })}</span>}
|
||||
const releaseMeta = (r: Release) => {
|
||||
const details = [r.posted, r.size > 0 ? gb(r.size) : ''].filter(Boolean).join(' · ')
|
||||
if (!details) return null
|
||||
return <div className="row-sub">
|
||||
{details}
|
||||
{spaceShort(r) && <span className="warn-text"> · {tr('installersNoSpace', { need: Math.ceil(remainingGB(r)), free: host.free_disk_gb.toFixed(0) })}</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const matchedTaskIDs = new Set<string>()
|
||||
const cachedRows: DownloadedRow[] = (cached ?? []).map((c) => {
|
||||
const cachedRows: DownloadedRow[] = (cached ?? []).filter((item) => releaseKind !== 'ipsw' || item.kind === 'ipsw').map((c) => {
|
||||
const active = findActiveCachedTask(activeInstallerTasks, c)
|
||||
if (active) {
|
||||
for (const id of active.matchedIDs) matchedTaskIDs.add(id)
|
||||
@@ -236,16 +253,19 @@ export const InstallersPage: React.FC<Props> = ({
|
||||
const task = active.primary
|
||||
const kind = taskInstallerKind(task) || 'offline'
|
||||
const version = taskInstallerVersion(task)
|
||||
if (kind === 'offline') {
|
||||
if (kind === 'offline' || kind === 'ipsw') {
|
||||
const rel = (releases ?? []).find((r) => r.version.toLowerCase() === version.toLowerCase())
|
||||
return {
|
||||
key: `active-${taskInstallerKey(task) || task.id}`,
|
||||
title: rel?.title ?? 'macOS',
|
||||
version: rel?.version ?? version,
|
||||
kind: 'offline',
|
||||
kind,
|
||||
active,
|
||||
}
|
||||
}
|
||||
if (kind === 'arm-ipsw') {
|
||||
return { key: `active-${task.id}`, title: task.subject, version, kind: 'ipsw', active }
|
||||
}
|
||||
return {
|
||||
key: `active-${taskInstallerKey(task) || task.id}`,
|
||||
title: formatOnlineTitle(version),
|
||||
@@ -302,6 +322,7 @@ export const InstallersPage: React.FC<Props> = ({
|
||||
<div className="row-title">
|
||||
<span>{row.title}{row.version ? ` ${row.version}` : ''}</span>
|
||||
{!task && c?.kind === 'offline' && !c.partial && <span className="badge rg-p-badge badge-ok">{tr('installersKindOffline')}</span>}
|
||||
{!task && c?.kind === 'ipsw' && !c.partial && <span className="badge rg-p-badge badge-ok">IPSW</span>}
|
||||
{(!task && c?.kind === 'online' && !c.partial) || (task && row.kind === 'online')
|
||||
? <span className="badge rg-p-badge">{tr('installersKindOnline')}</span>
|
||||
: null}
|
||||
@@ -333,12 +354,12 @@ export const InstallersPage: React.FC<Props> = ({
|
||||
/>
|
||||
) : c ? (
|
||||
<>
|
||||
{!c.partial && (c.kind === 'offline' || c.kind === 'online') && (
|
||||
<Button variant={c.kind === 'offline' ? 'primary' : 'secondary'} icon={<Plus size={14} />} onClick={() => onCreateWithInstaller(c)}>
|
||||
{!c.partial && !!c.path && c.kind !== 'other' && (c.kind !== 'ipsw' || releaseKind === 'ipsw') && (
|
||||
<Button variant={c.kind === 'online' ? 'secondary' : 'primary'} icon={<Plus size={14} />} onClick={() => onCreateWithInstaller(c)}>
|
||||
{tr('installersCreateVM')}
|
||||
</Button>
|
||||
)}
|
||||
{c.partial && c.kind === 'offline' && c.version && (
|
||||
{c.partial && c.version && (c.kind === 'offline' || (c.kind === 'ipsw' && (releases ?? []).some((r) => matchesRelease(c, r)))) && (
|
||||
<Button icon={<Download size={14} />} onClick={() => download(c.version!)}>{tr('installersResume')}</Button>
|
||||
)}
|
||||
{confirmDelete === c.name ? (
|
||||
@@ -362,7 +383,7 @@ export const InstallersPage: React.FC<Props> = ({
|
||||
<div className="notice notice-error" role="alert">
|
||||
<span className="notice-main">
|
||||
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{tr('offlineListFailedDetail', { err: releasesErr })}</span>
|
||||
<span>{releaseKind === 'ipsw' ? releasesErr : tr('offlineListFailedDetail', { err: releasesErr })}</span>
|
||||
</span>
|
||||
<Button onClick={loadReleases}>{tr('installersRetry')}</Button>
|
||||
</div>
|
||||
@@ -383,7 +404,7 @@ export const InstallersPage: React.FC<Props> = ({
|
||||
<span>{latest.title}</span>
|
||||
<strong>{latest.version}</strong>
|
||||
{groupIndex === 0 && <span className="badge rg-p-badge badge-accent">{tr('installersLatest')}</span>}
|
||||
{downloaded(latest.version) && <Check size={15} className="ok-text" aria-label={tr('offlineCached')} />}
|
||||
{downloaded(latest) && <Check size={15} className="ok-text" aria-label={tr('offlineCached')} />}
|
||||
</div>
|
||||
{releaseMeta(latest)}
|
||||
</div>
|
||||
@@ -402,7 +423,7 @@ export const InstallersPage: React.FC<Props> = ({
|
||||
<div className="row-title">
|
||||
<span>{r.version}</span>
|
||||
<span className="muted">{r.build}</span>
|
||||
{downloaded(r.version) && <span className="badge rg-p-badge badge-ok">{tr('offlineCached')}</span>}
|
||||
{downloaded(r) && <span className="badge rg-p-badge badge-ok">{tr('offlineCached')}</span>}
|
||||
</div>
|
||||
{releaseMeta(r)}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { t, type I18nKey } from '../i18n'
|
||||
import { buildTitleMenus, MENU_IDS, type MenuCommand, type TitleMenuState } from '../lib/titleMenu'
|
||||
|
||||
// Match Wails’ standard items by action, not by their original English title.
|
||||
const standardMenuKeys = {
|
||||
edit: 'menuMacEdit', window: 'menuMacWindow', speech: 'menuMacSpeech',
|
||||
About: 'helpAbout', Quit: 'menuMacQuit',
|
||||
'hide:': 'menuMacHide', 'hideOtherApplications:': 'menuMacHideOthers', 'unhideAllApplications:': 'menuMacShowAll',
|
||||
'undo:': 'menuMacUndo', 'redo:': 'menuMacRedo',
|
||||
'cut:': 'menuMacCut', 'copy:': 'copy', 'paste:': 'menuMacPaste', 'pasteAsRichText:': 'menuMacPasteMatchStyle',
|
||||
'delete:': 'menuMacDelete', 'selectAll:': 'menuMacSelectAll',
|
||||
'startSpeaking:': 'menuMacStartSpeaking', 'stopSpeaking:': 'menuMacStopSpeaking',
|
||||
'performMiniaturize:': 'minimize', 'performZoom:': 'menuMacZoom', 'enterFullScreenMode:': 'menuMacFullScreen',
|
||||
} satisfies Record<string, I18nKey>
|
||||
|
||||
type NativeRow = { label?: string; command?: MenuCommand; checked?: boolean; key?: string }
|
||||
export type MenuClick = { scope: string; command: MenuCommand }
|
||||
|
||||
export interface NativeMenuState {
|
||||
workspaceReady: boolean
|
||||
dialogOpen: boolean
|
||||
selectedVMKey?: string
|
||||
vmSettingsReady: boolean
|
||||
}
|
||||
|
||||
export function buildNativeMenu(props: TitleMenuState, state: NativeMenuState, fullscreen?: boolean) {
|
||||
const menus = buildTitleMenus(props, fullscreen)
|
||||
const commands = new Set<MenuCommand>()
|
||||
const groups = MENU_IDS.map((id) => ({
|
||||
label: menus[id].label,
|
||||
rows: menus[id].rows.map((row): NativeRow => {
|
||||
if (row.kind === 'separator') return {}
|
||||
if (row.kind === 'label') return { label: row.label }
|
||||
const alwaysAvailable = row.command === 'website' || row.command === 'docs' || row.command === 'project' || row.command === 'report'
|
||||
const enabled = !state.dialogOpen && (state.workspaceReady || alwaysAvailable) && !row.disabled
|
||||
&& (row.command !== 'vmSettings' || state.vmSettingsReady)
|
||||
if (enabled) commands.add(row.command)
|
||||
return { label: row.label, command: enabled ? row.command : undefined, checked: row.checked, key: row.macKey }
|
||||
}),
|
||||
}))
|
||||
const standard = Object.fromEntries(Object.entries(standardMenuKeys).map(([item, key]) => [item, t(props.locale, key)]))
|
||||
return { groups, standard, commands, scope: state.selectedVMKey ?? '' }
|
||||
}
|
||||
|
||||
export function resolveMenuClick(entry: MenuClick, scope: string, commands: ReadonlySet<MenuCommand>): MenuCommand | undefined {
|
||||
if (!commands.has(entry.command)) return undefined
|
||||
if ((entry.command.startsWith('vm:') || entry.command === 'vmSettings') && entry.scope !== scope) return undefined
|
||||
return entry.command
|
||||
}
|
||||
@@ -1645,7 +1645,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
|
||||
/* Log filter controls */
|
||||
.log-filter-input {
|
||||
width: 148px; height: 24px; padding: 0 8px; flex-shrink: 0;
|
||||
width: clamp(104px, 15vw, 148px); height: 24px; padding: 0 8px; flex-shrink: 0;
|
||||
border-radius: var(--r-sm); border: 1px solid var(--border-strong);
|
||||
background: var(--surface-input); color: var(--text); font: inherit; font-size: var(--fs-12);
|
||||
}
|
||||
@@ -1658,6 +1658,57 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
}
|
||||
.log-filter-pill:hover { color: var(--text); background: var(--surface-hover); }
|
||||
.log-filter-pill[aria-pressed="true"] { background: var(--warn-soft); border-color: transparent; color: var(--warn-text); font-weight: var(--fw-medium); }
|
||||
.btn.log-export-btn {
|
||||
height: 24px; padding: 0 8px; gap: 5px; flex-shrink: 0; white-space: nowrap;
|
||||
font-size: var(--fs-12); border-radius: var(--r-sm);
|
||||
}
|
||||
|
||||
/* Diagnostics export guidance dialog */
|
||||
.diag-findings { display: flex; flex-direction: column; gap: var(--sp-2); }
|
||||
.diag-finding { align-items: flex-start; }
|
||||
.diag-finding-details { color: var(--text-2); font-size: var(--fs-12); }
|
||||
.diag-finding-details > summary { cursor: pointer; user-select: none; color: var(--text-2); }
|
||||
.diag-finding-details pre {
|
||||
padding: var(--sp-2); border-radius: var(--r-sm);
|
||||
background: var(--surface-0); border: 1px solid var(--border);
|
||||
font-family: var(--font-mono); font-size: var(--fs-11); line-height: 1.5;
|
||||
color: var(--text-code); max-height: 120px; overflow: auto;
|
||||
}
|
||||
.diag-card {
|
||||
background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-md);
|
||||
padding: var(--sp-3) var(--sp-4); display: flex; flex-direction: column; gap: var(--sp-2);
|
||||
}
|
||||
.diag-card-title { font-size: var(--fs-13); font-weight: var(--fw-strong); color: var(--text); }
|
||||
.diag-checklist {
|
||||
margin: 0; padding-inline-start: 18px;
|
||||
display: flex; flex-direction: column; gap: 6px;
|
||||
font-size: var(--fs-13); color: var(--text-2); line-height: 1.5;
|
||||
}
|
||||
.diag-files-section {
|
||||
display: flex; flex-direction: column; gap: 6px;
|
||||
padding-top: var(--sp-2); border-top: 1px solid var(--border);
|
||||
}
|
||||
.diag-files-label { font-size: var(--fs-12); color: var(--text-3); }
|
||||
.diag-files { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.diag-file-pill {
|
||||
display: inline-flex; align-items: center;
|
||||
padding: 2px 8px; border-radius: var(--r-sm);
|
||||
background: var(--surface-0); border: 1px solid var(--border);
|
||||
font-family: var(--font-mono); font-size: var(--fs-11); color: var(--text-2);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.diag-summary-details { font-size: var(--fs-12); color: var(--text-2); }
|
||||
.diag-summary-details > summary {
|
||||
cursor: pointer; user-select: none; font-weight: var(--fw-medium); color: var(--text-2);
|
||||
}
|
||||
.diag-summary-pre {
|
||||
margin: var(--sp-2) 0 0; padding: var(--sp-3);
|
||||
border-radius: var(--r-md); background: var(--surface-1); border: 1px solid var(--border);
|
||||
font-family: var(--font-mono); font-size: var(--fs-11); line-height: 1.5;
|
||||
color: var(--text-code); white-space: pre-wrap; overflow-wrap: anywhere;
|
||||
max-height: 180px; overflow: auto;
|
||||
}
|
||||
.diag-foot-secondary { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); }
|
||||
|
||||
/* Storage breakdown bar (Engine page) */
|
||||
.storage-bar {
|
||||
@@ -2069,6 +2120,13 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
cannot override them even with !important. */
|
||||
@layer host-guard {
|
||||
.rg-p-titlebar { --wails-draggable: drag !important; }
|
||||
/* Match the native titlebar's centerline. The top padding balances the bottom border.
|
||||
AppKit's controls occupy the physical left edge, even when the app is RTL. */
|
||||
.rg-p-titlebar[data-native-titlebar] {
|
||||
height: 32px !important;
|
||||
padding-top: 1px !important;
|
||||
padding-left: 96px !important;
|
||||
}
|
||||
:focus-visible:not(.dialog):not(.menu) { box-shadow: var(--focus-ring) !important; }
|
||||
.icon-btn, .win-btn { min-width: 28px !important; min-height: 28px !important; }
|
||||
/* Layers and decorations never take input, whatever a theme says. */
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
// options, icon names and view locations in internal/plugin/contract.go, and a
|
||||
// Go test keeps both in step.
|
||||
|
||||
export const UI_API_VERSION = '2.1.0' as const
|
||||
export const UI_API_VERSION = '2.2.0' as const
|
||||
|
||||
export const UI_CONTRACT_PARTS = [
|
||||
'rg-p-shell',
|
||||
@@ -81,9 +81,11 @@ export const UI_CONTRACT_ITEM_STATES = [
|
||||
'rg-p-nav-item:data-selected',
|
||||
'rg-p-nav-item:data-busy',
|
||||
'rg-p-nav-item:data-guest-family',
|
||||
'rg-p-nav-item:data-remote-control',
|
||||
'rg-p-vm-page:data-vm-state',
|
||||
'rg-p-vm-page:data-driver',
|
||||
'rg-p-vm-page:data-guest-family',
|
||||
'rg-p-vm-page:data-remote-control',
|
||||
'rg-p-button:data-variant',
|
||||
'rg-p-button:data-busy',
|
||||
'rg-p-icon-button:data-busy',
|
||||
@@ -182,6 +184,7 @@ export const UI_CONTRACT_ICONS = [
|
||||
'guest-windows',
|
||||
'guest-android',
|
||||
'remote-desktop',
|
||||
'remote-control',
|
||||
'terminal',
|
||||
] as const
|
||||
|
||||
|
||||
+87
-1
@@ -12,6 +12,7 @@ export type Locale = BuiltinLocale | (string & {})
|
||||
export type Config = Model<config.Config> & {
|
||||
locale: Locale
|
||||
runtime_channel?: 'stable' | 'alpha' | ''
|
||||
agent_takeover_pause_sec?: number
|
||||
}
|
||||
|
||||
export type DisplayInfo = host.DisplayInfo
|
||||
@@ -39,6 +40,15 @@ export type HostReport = Omit<Model<host.Report>, 'gpus' | 'recommended_gpu'> &
|
||||
recommended_gpu?: GPUInfo
|
||||
}
|
||||
|
||||
export type DiagnosticFinding = Model<host.DiagnosticFinding> & {
|
||||
code: 'gpu_device_lost' | 'gpu_vulkan_floor' | 'whpx_unavailable' | 'low_memory' | 'low_disk'
|
||||
severity: 'error' | 'warn'
|
||||
}
|
||||
|
||||
export type DiagnosticsExportResult = Omit<Model<app.DiagnosticsExportResult>, 'findings'> & {
|
||||
findings: DiagnosticFinding[]
|
||||
}
|
||||
|
||||
export type InstalledRuntime = Model<runtime.Installed>
|
||||
|
||||
export type RemoteRuntime = Model<runtime.Remote> & {
|
||||
@@ -69,6 +79,80 @@ export type VMInfo = Omit<Model<driver.VMInfo>, 'guest_os' | 'phase' | 'endpoint
|
||||
|
||||
export type PendingChange = app.PendingChange
|
||||
|
||||
export interface AgentSessionView {
|
||||
vm_key: string
|
||||
driver_id: string
|
||||
vm_name: string
|
||||
plugin_id: string
|
||||
plugin_name: string
|
||||
label?: string
|
||||
stage?: string
|
||||
stage_label?: string
|
||||
status?: string
|
||||
message?: string
|
||||
phase?: string
|
||||
auth_until_phase_exit?: boolean
|
||||
auth_remaining_sec?: number
|
||||
takeover_policy?: string
|
||||
input_locked?: boolean
|
||||
paused_for_user?: boolean
|
||||
takeover_paused?: boolean
|
||||
takeover_manual_wait?: boolean
|
||||
takeover_remaining_sec?: number
|
||||
started_at: string
|
||||
}
|
||||
|
||||
export interface AutoInstallerProviderView {
|
||||
plugin_id: string
|
||||
id: string
|
||||
title: string
|
||||
description?: string
|
||||
guest_families: string[]
|
||||
requires_offline_installer?: boolean
|
||||
secret_setting: string
|
||||
}
|
||||
|
||||
export interface AutoInstallStartRequest {
|
||||
plugin_id?: string
|
||||
driver_id?: string
|
||||
vm_name: string
|
||||
mode?: 'recovery_only' | 'full'
|
||||
guest_lang?: string
|
||||
full_name?: string
|
||||
account_name?: string
|
||||
password?: string
|
||||
region?: string
|
||||
appearance?: 'auto' | 'light' | 'dark'
|
||||
age_range?: string
|
||||
sla_accepted: boolean
|
||||
save_unlock_credential?: boolean
|
||||
install_guest_tools?: boolean
|
||||
ocr_backend?: string
|
||||
custom_ocr_mirror?: string
|
||||
start_vm_if_stopped?: boolean
|
||||
}
|
||||
|
||||
export interface ProvisionRequest {
|
||||
full_name: string
|
||||
account_name: string
|
||||
password: string
|
||||
appearance?: 'auto' | 'light' | 'dark'
|
||||
sla_accepted: boolean
|
||||
install_guest_tools?: boolean
|
||||
}
|
||||
|
||||
export interface AutoInstallStatus {
|
||||
vm: string
|
||||
stage?: string
|
||||
stage_label?: string
|
||||
status?: string
|
||||
message?: string
|
||||
pause_reason?: string
|
||||
unknown_page_summary?: string
|
||||
matched_rules?: string[]
|
||||
finish_install_done?: boolean
|
||||
}
|
||||
|
||||
export type AppState = Omit<Model<app.AppState>, 'config' | 'host' | 'optimizations' | 'runtimes' | 'active_runtime' | 'vms'> & {
|
||||
config: Config
|
||||
host: HostReport
|
||||
@@ -77,6 +161,8 @@ export type AppState = Omit<Model<app.AppState>, 'config' | 'host' | 'optimizati
|
||||
active_runtime?: InstalledRuntime
|
||||
vms: VMListItem[] | null
|
||||
vm_list_error?: string
|
||||
agent_sessions?: AgentSessionView[]
|
||||
provision_ready_vms?: string[]
|
||||
}
|
||||
|
||||
export type AppUpdateInfo = version.UpdateInfo
|
||||
@@ -126,7 +212,7 @@ export type CreateOpts = Model<reims.CreateOpts> & {
|
||||
|
||||
type TaskStatus = 'running' | 'done' | 'failed' | 'canceled'
|
||||
|
||||
export type InstallerKind = 'offline' | 'online'
|
||||
export type InstallerKind = 'offline' | 'online' | 'arm-ipsw' | 'ipsw'
|
||||
export type InstallerPhase = 'queued' | 'downloading'
|
||||
|
||||
/** A tracked long-running job pushed as "reims:task" (internal/app/tasks.go). */
|
||||
|
||||
+47
-2
@@ -15,8 +15,8 @@ import {
|
||||
WindowToggleMaximise as RawWindowToggleMaximise,
|
||||
} from '../wailsjs/runtime/runtime'
|
||||
import type {
|
||||
ActiveThemePayload, AppState, CachedInstaller, DataRootChoice, DriverSummary,
|
||||
LogEntry, MarketBrowseResult, PluginInfo, PluginUIContributions, RemoteRuntime,
|
||||
ActiveThemePayload, AppState, AutoInstallerProviderView, AutoInstallStartRequest, AutoInstallStatus, CachedInstaller, DataRootChoice, DiagnosticsExportResult, DriverSummary,
|
||||
LogEntry, MarketBrowseResult, PluginInfo, PluginUIContributions, ProvisionRequest, RemoteRuntime,
|
||||
ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMInfo, VMNetworkSettings, VMNetworkPlan,
|
||||
} from './types'
|
||||
|
||||
@@ -148,6 +148,7 @@ function eventsEmit(eventName: string, ...args: unknown[]): void {
|
||||
|
||||
export const api = {
|
||||
...boundGo,
|
||||
ExportDiagnostics: boundGo.ExportDiagnostics as (driverID: string, name: string) => Promise<DiagnosticsExportResult>,
|
||||
GetVMNetworkSettings: boundGo.GetVMNetworkSettings as (name: string) => Promise<VMNetworkSettings>,
|
||||
GetVMNetworkPlan: boundGo.GetVMNetworkPlan as (name: string, mode: string, uplink: string) => Promise<VMNetworkPlan>,
|
||||
ListNetworkAdapters: boundGo.ListNetworkAdapters as () => Promise<VMNetworkSettings['adapters']>,
|
||||
@@ -171,6 +172,46 @@ export const api = {
|
||||
GetPluginUIContributions: boundGo.GetPluginUIContributions as () => Promise<PluginUIContributions>,
|
||||
GetActiveTheme: boundGo.GetActiveTheme as () => Promise<ActiveThemePayload>,
|
||||
ListDrivers: boundGo.ListDrivers as () => Promise<DriverSummary[] | null>,
|
||||
ResolveConfirmRequest: boundGo.ResolveConfirmRequest as (id: string, approved: boolean, durationMinutes: number, untilPhaseExit: boolean) => Promise<void>,
|
||||
PauseAgentSession: boundGo.PauseAgentSession as (driverID: string, name: string) => Promise<void>,
|
||||
ResumeAgentSession: boundGo.ResumeAgentSession as (driverID: string, name: string) => Promise<void>,
|
||||
StopAgentSession: boundGo.StopAgentSession as (driverID: string, name: string) => Promise<void>,
|
||||
SetAgentTakeoverPauseSec: boundGo.SetAgentTakeoverPauseSec as (seconds: number) => Promise<void>,
|
||||
ListAutoInstallers: boundGo.ListAutoInstallers as (guestFamily: string) => Promise<AutoInstallerProviderView[] | null>,
|
||||
PreflightAutoInstall: boundGo.PreflightAutoInstall as (pluginID: string, driverID: string, vmName: string, guestLang: string) => Promise<Record<string, unknown>>,
|
||||
StartAutoInstall: boundGo.StartAutoInstall as (req: AutoInstallStartRequest) => Promise<Record<string, unknown>>,
|
||||
GetAutoInstallStatus: boundGo.GetAutoInstallStatus as (pluginID: string, driverID: string, vmName: string) => Promise<AutoInstallStatus>,
|
||||
ResumeAutoInstall: boundGo.ResumeAutoInstall as (pluginID: string, driverID: string, vmName: string) => Promise<AutoInstallStatus>,
|
||||
StopAutoInstall: boundGo.StopAutoInstall as (pluginID: string, driverID: string, vmName: string) => Promise<void>,
|
||||
GetAutoInstallDiagnosticSummary: boundGo.GetAutoInstallDiagnosticSummary as (pluginID: string, driverID: string, vmName: string) => Promise<Record<string, unknown>>,
|
||||
DownloadAutoInstallOCR: boundGo.DownloadAutoInstallOCR as (pluginID: string, customMirror: string) => Promise<Record<string, unknown>>,
|
||||
PrepareVMProvision: boundGo.PrepareVMProvision as (name: string, req: ProvisionRequest) => Promise<void>,
|
||||
}
|
||||
|
||||
export interface ConfirmPrompt {
|
||||
id: string
|
||||
kind: 'generic' | 'protected_phase' | 'custom_mirror' | string
|
||||
plugin_id: string
|
||||
plugin_name: string
|
||||
publisher?: string
|
||||
trust?: string
|
||||
vm?: string
|
||||
vm_name?: string
|
||||
phase?: string
|
||||
title: string
|
||||
message: string
|
||||
confirm_label?: string
|
||||
cancel_label?: string
|
||||
danger?: boolean
|
||||
allow_duration_choice?: boolean
|
||||
default_duration_minutes?: number
|
||||
prefer_until_phase_exit?: boolean
|
||||
origin?: string
|
||||
}
|
||||
|
||||
export interface ConfirmResolvedEvent {
|
||||
id: string
|
||||
reason?: string
|
||||
}
|
||||
|
||||
export interface MarketInstallProgress {
|
||||
@@ -198,6 +239,7 @@ export const events = {
|
||||
onHostDropAck: (cb: (payload: { vm: string; drop_id: string; status: string; target_kind?: string; target_label?: string; placed_names?: string[]; error?: string }) => void) => eventsOn('reims:host-drop-ack', cb),
|
||||
onTask: (cb: (task: Task) => void) => eventsOn('reims:task', cb),
|
||||
onStateChanged: (cb: () => void) => eventsOn('reims:state-changed', cb),
|
||||
onApplicationMenuCommand: (cb: (token: number) => void) => eventsOn('reims:application-menu-command', cb),
|
||||
onLog: (cb: (entry: LogEntry) => void) => eventsOn('reims:log', cb),
|
||||
onRuntimeWarning: (cb: (message: string) => void) => eventsOn('reims:runtime-warning', cb),
|
||||
// Market install progress (internal/app/plugins_flow.go InstallMarketPlugin).
|
||||
@@ -211,6 +253,9 @@ export const events = {
|
||||
// Controlled elevation request from a guest driver plugin (internal/app/elevate_flow.go).
|
||||
onElevateRequest: (cb: (req: ElevationPrompt) => void) => eventsOn('reims:elevate-request', cb),
|
||||
onElevateResolved: (cb: (id: string) => void) => eventsOn('reims:elevate-resolved', cb),
|
||||
// #105 protected-phase, host/ui.confirm, and custom mirror confirmation prompts.
|
||||
onConfirmRequest: (cb: (req: ConfirmPrompt) => void) => eventsOn('reims:confirm-request', cb),
|
||||
onConfirmResolved: (cb: (ev: ConfirmResolvedEvent | string) => void) => eventsOn('reims:confirm-resolved', cb),
|
||||
// Renderer health watchdog & crash reporting (internal/app/ui_health.go).
|
||||
onUIPing: (cb: () => void) => eventsOn('reims:ui-ping', cb),
|
||||
emitUIPong: () => eventsEmit('reims:ui-pong'),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"uiApi": "2.1.0",
|
||||
"uiApi": "2.2.0",
|
||||
"parts": [
|
||||
"rg-p-shell",
|
||||
"rg-p-titlebar",
|
||||
@@ -57,9 +57,11 @@
|
||||
"rg-p-nav-item:data-selected",
|
||||
"rg-p-nav-item:data-busy",
|
||||
"rg-p-nav-item:data-guest-family",
|
||||
"rg-p-nav-item:data-remote-control",
|
||||
"rg-p-vm-page:data-vm-state",
|
||||
"rg-p-vm-page:data-driver",
|
||||
"rg-p-vm-page:data-guest-family",
|
||||
"rg-p-vm-page:data-remote-control",
|
||||
"rg-p-button:data-variant",
|
||||
"rg-p-button:data-busy",
|
||||
"rg-p-icon-button:data-busy",
|
||||
@@ -130,6 +132,7 @@
|
||||
"guest-windows",
|
||||
"guest-android",
|
||||
"remote-desktop",
|
||||
"remote-control",
|
||||
"terminal"
|
||||
],
|
||||
"viewLocations": [
|
||||
|
||||
Vendored
+37
-1
@@ -40,6 +40,8 @@ export function CompactVMDisk(arg1:string,arg2:string):Promise<driver.DiskCompac
|
||||
|
||||
export function CompleteSetup(arg1:string):Promise<void>;
|
||||
|
||||
export function CopyDiagnosticsFile(arg1:string):Promise<void>;
|
||||
|
||||
export function CopyVMScreenshot(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function CreateSnapshot(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
@@ -72,13 +74,15 @@ export function DownloadAppUpdate():Promise<string>;
|
||||
|
||||
export function DownloadInstaller(arg1:string):Promise<string>;
|
||||
|
||||
export function DownloadARMImage():Promise<string>;
|
||||
|
||||
export function EjectInstaller(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function EnablePlugin(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function EnterRecovery(arg1:string):Promise<void>;
|
||||
|
||||
export function ExportDiagnostics(arg1:string,arg2:string):Promise<string>;
|
||||
export function ExportDiagnostics(arg1:string,arg2:string):Promise<app.DiagnosticsExportResult>;
|
||||
|
||||
export function FinishInstall(arg1:string):Promise<void>;
|
||||
|
||||
@@ -230,12 +234,42 @@ export function ResizeVMDisk(arg1:string,arg2:string,arg3:string):Promise<driver
|
||||
|
||||
export function ResolveElevationRequest(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function ResolveConfirmRequest(arg1:string,arg2:boolean,arg3:number,arg4:boolean):Promise<void>;
|
||||
|
||||
export function PauseAgentSession(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function ResumeAgentSession(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function StopAgentSession(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function SetAgentTakeoverPauseSec(arg1:number):Promise<void>;
|
||||
|
||||
export function ListAutoInstallers(arg1:string):Promise<Array<any>>;
|
||||
|
||||
export function PreflightAutoInstall(arg1:string,arg2:string,arg3:string,arg4:string):Promise<Record<string,any>>;
|
||||
|
||||
export function StartAutoInstall(arg1:Record<string,any>):Promise<Record<string,any>>;
|
||||
|
||||
export function GetAutoInstallStatus(arg1:string,arg2:string,arg3:string):Promise<Record<string,any>>;
|
||||
|
||||
export function ResumeAutoInstall(arg1:string,arg2:string,arg3:string):Promise<Record<string,any>>;
|
||||
|
||||
export function StopAutoInstall(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function GetAutoInstallDiagnosticSummary(arg1:string,arg2:string,arg3:string):Promise<Record<string,any>>;
|
||||
|
||||
export function DownloadAutoInstallOCR(arg1:string,arg2:string):Promise<Record<string,any>>;
|
||||
|
||||
export function PrepareVMProvision(arg1:string,arg2:any):Promise<void>;
|
||||
|
||||
export function RestartVM(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function RestoreSnapshot(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function ResumeVM(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function RevealDiagnosticsFile(arg1:string):Promise<void>;
|
||||
|
||||
export function SaveCustomThemeScheme(arg1:plugin.CustomThemeScheme):Promise<void>;
|
||||
|
||||
export function ScanInstalledPlugin(arg1:string):Promise<plugin.ScanReport>;
|
||||
@@ -294,6 +328,8 @@ export function SuggestLanguagePack():Promise<plugin.MarketCatalogItem>;
|
||||
|
||||
export function SuspendVM(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function SyncApplicationMenu(arg1:string):Promise<void>;
|
||||
|
||||
export function TestHostDNS(arg1:guesttools.HostDNSConfig):Promise<guesttools.HostDNSTestResult>;
|
||||
|
||||
export function ToggleVMFullscreen(arg1:string,arg2:string):Promise<boolean>;
|
||||
|
||||
@@ -58,6 +58,10 @@ export function CompleteSetup(arg1) {
|
||||
return window['go']['app']['App']['CompleteSetup'](arg1);
|
||||
}
|
||||
|
||||
export function CopyDiagnosticsFile(arg1) {
|
||||
return window['go']['app']['App']['CopyDiagnosticsFile'](arg1);
|
||||
}
|
||||
|
||||
export function CopyVMScreenshot(arg1, arg2) {
|
||||
return window['go']['app']['App']['CopyVMScreenshot'](arg1, arg2);
|
||||
}
|
||||
@@ -118,6 +122,10 @@ export function DownloadAppUpdate() {
|
||||
return window['go']['app']['App']['DownloadAppUpdate']();
|
||||
}
|
||||
|
||||
export function DownloadARMImage() {
|
||||
return window['go']['app']['App']['DownloadARMImage']();
|
||||
}
|
||||
|
||||
export function DownloadInstaller(arg1) {
|
||||
return window['go']['app']['App']['DownloadInstaller'](arg1);
|
||||
}
|
||||
@@ -450,6 +458,10 @@ export function ResumeVM(arg1, arg2) {
|
||||
return window['go']['app']['App']['ResumeVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function RevealDiagnosticsFile(arg1) {
|
||||
return window['go']['app']['App']['RevealDiagnosticsFile'](arg1);
|
||||
}
|
||||
|
||||
export function SaveCustomThemeScheme(arg1) {
|
||||
return window['go']['app']['App']['SaveCustomThemeScheme'](arg1);
|
||||
}
|
||||
@@ -566,6 +578,10 @@ export function SuspendVM(arg1, arg2) {
|
||||
return window['go']['app']['App']['SuspendVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SyncApplicationMenu(arg1) {
|
||||
return window['go']['app']['App']['SyncApplicationMenu'](arg1);
|
||||
}
|
||||
|
||||
export function TestHostDNS(arg1) {
|
||||
return window['go']['app']['App']['TestHostDNS'](arg1);
|
||||
}
|
||||
@@ -601,3 +617,59 @@ export function ValidateSet(arg1) {
|
||||
export function WriteSSHConfig(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['WriteSSHConfig'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function ResolveConfirmRequest(arg1, arg2, arg3, arg4) {
|
||||
return window['go']['app']['App']['ResolveConfirmRequest'](arg1, arg2, arg3, arg4);
|
||||
}
|
||||
|
||||
export function PauseAgentSession(arg1, arg2) {
|
||||
return window['go']['app']['App']['PauseAgentSession'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function ResumeAgentSession(arg1, arg2) {
|
||||
return window['go']['app']['App']['ResumeAgentSession'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function StopAgentSession(arg1, arg2) {
|
||||
return window['go']['app']['App']['StopAgentSession'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SetAgentTakeoverPauseSec(arg1) {
|
||||
return window['go']['app']['App']['SetAgentTakeoverPauseSec'](arg1);
|
||||
}
|
||||
|
||||
export function ListAutoInstallers(arg1) {
|
||||
return window['go']['app']['App']['ListAutoInstallers'](arg1);
|
||||
}
|
||||
|
||||
export function PreflightAutoInstall(arg1, arg2, arg3, arg4) {
|
||||
return window['go']['app']['App']['PreflightAutoInstall'](arg1, arg2, arg3, arg4);
|
||||
}
|
||||
|
||||
export function StartAutoInstall(arg1) {
|
||||
return window['go']['app']['App']['StartAutoInstall'](arg1);
|
||||
}
|
||||
|
||||
export function GetAutoInstallStatus(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['GetAutoInstallStatus'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function ResumeAutoInstall(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['ResumeAutoInstall'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function StopAutoInstall(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['StopAutoInstall'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function GetAutoInstallDiagnosticSummary(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['GetAutoInstallDiagnosticSummary'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function DownloadAutoInstallOCR(arg1, arg2) {
|
||||
return window['go']['app']['App']['DownloadAutoInstallOCR'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function PrepareVMProvision(arg1, arg2) {
|
||||
return window['go']['app']['App']['PrepareVMProvision'](arg1, arg2);
|
||||
}
|
||||
@@ -118,6 +118,50 @@ export namespace app {
|
||||
this.recommended = source["recommended"];
|
||||
}
|
||||
}
|
||||
export class DiagnosticsExportResult {
|
||||
path: string;
|
||||
file_name: string;
|
||||
size_bytes: number;
|
||||
target_label: string;
|
||||
included_files: string[];
|
||||
summary_text: string;
|
||||
findings: host.DiagnosticFinding[];
|
||||
can_copy_file: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DiagnosticsExportResult(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.path = source["path"];
|
||||
this.file_name = source["file_name"];
|
||||
this.size_bytes = source["size_bytes"];
|
||||
this.target_label = source["target_label"];
|
||||
this.included_files = source["included_files"];
|
||||
this.summary_text = source["summary_text"];
|
||||
this.findings = this.convertValues(source["findings"], host.DiagnosticFinding);
|
||||
this.can_copy_file = source["can_copy_file"];
|
||||
}
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
}
|
||||
if (a.slice && a.map) {
|
||||
return (a as any[]).map(elem => this.convertValues(elem, classs));
|
||||
} else if ("object" === typeof a) {
|
||||
if (asMap) {
|
||||
for (const key of Object.keys(a)) {
|
||||
a[key] = new classs(a[key]);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
return new classs(a);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class DriveShareInfo {
|
||||
drive: string;
|
||||
root: string;
|
||||
@@ -1188,6 +1232,22 @@ export namespace host {
|
||||
this.broken = source["broken"];
|
||||
}
|
||||
}
|
||||
export class DiagnosticFinding {
|
||||
code: string;
|
||||
severity: string;
|
||||
detail?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DiagnosticFinding(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.code = source["code"];
|
||||
this.severity = source["severity"];
|
||||
this.detail = source["detail"];
|
||||
}
|
||||
}
|
||||
export class DisplayInfo {
|
||||
name?: string;
|
||||
friendly_name?: string;
|
||||
@@ -1344,7 +1404,22 @@ export namespace host {
|
||||
this.nested_virt_probe_error = source["nested_virt_probe_error"];
|
||||
}
|
||||
}
|
||||
export class AppleVirtualizationStatus {
|
||||
ready: boolean;
|
||||
detail?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new AppleVirtualizationStatus(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.ready = source["ready"];
|
||||
this.detail = source["detail"];
|
||||
}
|
||||
}
|
||||
export class Report {
|
||||
apple_virtualization?: AppleVirtualizationStatus;
|
||||
defender_realtime_active?: boolean;
|
||||
os: string;
|
||||
arch: string;
|
||||
@@ -1366,6 +1441,7 @@ export namespace host {
|
||||
total_ram_gb: number;
|
||||
avail_ram_gb: number;
|
||||
memory_load_pct: number;
|
||||
memory_usage_known?: boolean;
|
||||
memory_spec?: HostMemorySpec;
|
||||
commit_avail_gb: number;
|
||||
commit_limit_gb: number;
|
||||
@@ -1399,6 +1475,7 @@ export namespace host {
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.apple_virtualization = this.convertValues(source["apple_virtualization"], AppleVirtualizationStatus);
|
||||
this.defender_realtime_active = source["defender_realtime_active"];
|
||||
this.os = source["os"];
|
||||
this.arch = source["arch"];
|
||||
@@ -1420,6 +1497,7 @@ export namespace host {
|
||||
this.total_ram_gb = source["total_ram_gb"];
|
||||
this.avail_ram_gb = source["avail_ram_gb"];
|
||||
this.memory_load_pct = source["memory_load_pct"];
|
||||
this.memory_usage_known = source["memory_usage_known"];
|
||||
this.memory_spec = this.convertValues(source["memory_spec"], HostMemorySpec);
|
||||
this.commit_avail_gb = source["commit_avail_gb"];
|
||||
this.commit_limit_gb = source["commit_limit_gb"];
|
||||
@@ -2341,6 +2419,7 @@ export namespace plugin {
|
||||
}
|
||||
export class SettingProperty {
|
||||
type: string;
|
||||
"x-filePattern"?: string;
|
||||
title: LocalizedText;
|
||||
description?: LocalizedText;
|
||||
default?: any;
|
||||
@@ -2361,6 +2440,7 @@ export namespace plugin {
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.type = source["type"];
|
||||
this["x-filePattern"] = source["x-filePattern"];
|
||||
this.title = this.convertValues(source["title"], LocalizedText);
|
||||
this.description = this.convertValues(source["description"], LocalizedText);
|
||||
this.default = source["default"];
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,246 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
)
|
||||
|
||||
func TestFormatSessionStageAndOverlayStep(t *testing.T) {
|
||||
cases := []struct {
|
||||
loc i18n.Locale
|
||||
raw string
|
||||
want string
|
||||
}{
|
||||
{i18n.ZhCN, "stage0_preflight", "环境准备"},
|
||||
{i18n.ZhCN, "stage1_boot_recovery", "步骤 1 · 进入恢复环境"},
|
||||
{i18n.ZhCN, "stage2a_offline_terminal", "步骤 2 · 运行离线安装脚本"},
|
||||
{i18n.ZhCN, "stage2_disk_utility", "步骤 2 · 磁盘工具抹盘"},
|
||||
{i18n.ZhCN, "stage3_install_wait", "步骤 3 · 等待系统安装"},
|
||||
{i18n.ZhCN, "stage3_reinstall_macos", "步骤 3 · 安装 macOS"},
|
||||
{i18n.ZhCN, "stage3_wait_reboot", "步骤 3 · 等待系统重启"},
|
||||
{i18n.ZhCN, "stage4_finish_install", "步骤 4 · 退出恢复并重启"},
|
||||
{i18n.ZhCN, "stage4_setup_assistant", "步骤 4 · 完成设置助理"},
|
||||
{i18n.ZhCN, "stage5_wait_reboot", "步骤 5 · 等待系统重启"},
|
||||
{i18n.ZhCN, "stage5_guest_tools", "步骤 5 · 安装 Guest Tools"},
|
||||
{i18n.ZhCN, "正在抹掉 APFS 磁盘", "正在抹掉 APFS 磁盘"},
|
||||
{i18n.EnUS, "stage0_preflight", "Preflight check"},
|
||||
{i18n.EnUS, "stage1_boot_recovery", "Step 1 · Boot into Recovery"},
|
||||
{i18n.EnUS, "stage2a_offline_terminal", "Step 2 · Run offline installer"},
|
||||
{i18n.EnUS, "stage3_install_wait", "Step 3 · Wait for macOS install"},
|
||||
{i18n.EnUS, "stage3_wait_reboot", "Step 3 · Waiting for reboot"},
|
||||
{i18n.EnUS, "stage4_finish_install", "Step 4 · Exit recovery and restart"},
|
||||
{i18n.EnUS, "Step 2/5: Formatting volume", "Step 2/5: Formatting volume"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := formatSessionStage(tc.loc, tc.raw); got != tc.want {
|
||||
t.Errorf("formatSessionStage(%s, %q) = %q, want %q", tc.loc, tc.raw, got, tc.want)
|
||||
}
|
||||
}
|
||||
|
||||
a := &App{}
|
||||
view := AgentSessionView{
|
||||
Stage: "stage2_disk_utility",
|
||||
Message: "正在抹掉磁盘",
|
||||
InputLocked: true,
|
||||
}
|
||||
step := a.sessionOverlayStep(i18n.ZhCN, view)
|
||||
if step != "步骤 2 · 磁盘工具抹盘" {
|
||||
t.Fatalf("sessionOverlayStep = %q, want 步骤 2 · 磁盘工具抹盘", step)
|
||||
}
|
||||
status := a.sessionOverlayStatusLine(i18n.ZhCN, view, step)
|
||||
if status != "画面已锁定防干扰 · 正在抹掉磁盘" {
|
||||
t.Fatalf("sessionOverlayStatusLine = %q, want 画面已锁定防干扰 · 正在抹掉磁盘", status)
|
||||
}
|
||||
|
||||
// Syncing autoinstall/status progress updates session stage & message without clobbering user pause.
|
||||
vm := driver.VMInfo{DriverID: driver.BuiltinReimsMacOSDriverID, Name: "tahoe-step-test"}
|
||||
key := vm.Ref().Key()
|
||||
a.beginAgentSession(nil, "reims.autoinstall", vm, "macOS Auto-Install", "stage0_preflight", "lock", true)
|
||||
a.syncAutoInstallSessionProgress(key, "reims.autoinstall", "stage2_disk_utility", "点击抹掉")
|
||||
views := a.activeAgentSessions()
|
||||
if len(views) != 1 || views[0].Stage != "stage2_disk_utility" || views[0].Message != "点击抹掉" {
|
||||
t.Fatalf("syncAutoInstallSessionProgress did not update session: %+v", views)
|
||||
}
|
||||
if err := a.PauseAgentSession(vm.DriverID, vm.Name); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a.syncAutoInstallSessionProgress(key, "reims.autoinstall", "stage2_disk_utility", "should not overwrite pause msg")
|
||||
views = a.activeAgentSessions()
|
||||
if views[0].Message == "should not overwrite pause msg" {
|
||||
t.Fatalf("syncAutoInstallSessionProgress overwrote paused user message: %+v", views[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentSessionLockPauseResumeAndWriteGuard(t *testing.T) {
|
||||
a := &App{}
|
||||
vm := driver.VMInfo{
|
||||
DriverID: driver.BuiltinReimsMacOSDriverID,
|
||||
Name: "tahoe-lock-test",
|
||||
}
|
||||
vmKey := vm.Ref().Key()
|
||||
|
||||
a.beginAgentSession(nil, "reims.autoinstall", vm, "macOS Auto-Install", "stage1_boot_recovery", "lock", true)
|
||||
|
||||
views := a.activeAgentSessions()
|
||||
if len(views) != 1 {
|
||||
t.Fatalf("ActiveAgentSessions len = %d, want 1", len(views))
|
||||
}
|
||||
if views[0].TakeoverPolicy != "lock" || !views[0].InputLocked || views[0].PausedForUser {
|
||||
t.Fatalf("expected active locked session, got %+v", views[0])
|
||||
}
|
||||
if err := a.checkUserTakeover(vmKey, vm.Name); err != nil {
|
||||
t.Fatalf("running locked session should allow plugin QMP writes, got %v", err)
|
||||
}
|
||||
|
||||
// Pausing from HUD/UI must unlock VM input and reject any in-flight plugin QMP writes.
|
||||
if err := a.PauseAgentSession(vm.DriverID, vm.Name); err != nil {
|
||||
t.Fatalf("PauseAgentSession: %v", err)
|
||||
}
|
||||
views = a.activeAgentSessions()
|
||||
if len(views) != 1 || !views[0].PausedForUser || views[0].InputLocked {
|
||||
t.Fatalf("expected paused & unlocked session, got %+v", views)
|
||||
}
|
||||
if err := a.checkUserTakeover(vmKey, vm.Name); err == nil {
|
||||
t.Fatal("paused session must block in-flight plugin QMP writes")
|
||||
}
|
||||
|
||||
// Resuming must re-lock VM input and allow plugin QMP writes again.
|
||||
if err := a.ResumeAgentSession(vm.DriverID, vm.Name); err != nil {
|
||||
t.Fatalf("ResumeAgentSession: %v", err)
|
||||
}
|
||||
views = a.activeAgentSessions()
|
||||
if len(views) != 1 || views[0].PausedForUser || !views[0].InputLocked {
|
||||
t.Fatalf("expected resumed & re-locked session, got %+v", views)
|
||||
}
|
||||
if err := a.checkUserTakeover(vmKey, vm.Name); err != nil {
|
||||
t.Fatalf("resumed session should allow plugin QMP writes again, got %v", err)
|
||||
}
|
||||
|
||||
a.endAgentSession(nil, "reims.autoinstall", vmKey, "completed")
|
||||
if got := len(a.activeAgentSessions()); got != 0 {
|
||||
t.Fatalf("expected 0 active sessions after end, got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentSessionUnboundDiscoveryAndImmediatePIDBind(t *testing.T) {
|
||||
a := &App{}
|
||||
vm := driver.VMInfo{
|
||||
DriverID: driver.BuiltinReimsMacOSDriverID,
|
||||
Name: "tahoe-bind-test",
|
||||
}
|
||||
vmKey := vm.Ref().Key()
|
||||
|
||||
if a.hasActiveAgentSessions() || a.hasUnboundAgentSession() {
|
||||
t.Fatal("idle app should report no active or unbound agent sessions")
|
||||
}
|
||||
|
||||
// Starting a session before the VM PID is known marks it unbound so pollVMs uses fast discovery.
|
||||
a.beginAgentSession(nil, "reims.autoinstall", vm, "macOS Auto-Install", "stage0_preflight", "lock", true)
|
||||
if !a.hasActiveAgentSessions() || !a.hasUnboundAgentSession() {
|
||||
t.Fatal("new session without live PID must be tracked as active & unbound")
|
||||
}
|
||||
|
||||
// Binding a freshly observed live PID (e.g., from first screenshot/write or VM start) resolves it immediately.
|
||||
a.bindAgentSessionPID(vmKey, 42424)
|
||||
if a.hasUnboundAgentSession() {
|
||||
t.Fatal("bindAgentSessionPID should clear unbound state immediately")
|
||||
}
|
||||
if !a.hasActiveAgentSessions() {
|
||||
t.Fatal("session should remain active after PID binding")
|
||||
}
|
||||
|
||||
// A rate-limited concurrent refresh (stale cache + probe skipped within 300ms)
|
||||
// must NOT wipe the already-bound PID back to 0.
|
||||
a.mu.Lock()
|
||||
a.ctx = context.Background()
|
||||
a.lastVMs = nil
|
||||
a.lastVMsAt = time.Now()
|
||||
a.mu.Unlock()
|
||||
a.sessionMu.Lock()
|
||||
a.agentSessions[vmKey].lastPIDProbeAt = time.Now()
|
||||
a.sessionMu.Unlock()
|
||||
a.refreshAgentSessionVisuals(vmKey)
|
||||
if a.hasUnboundAgentSession() {
|
||||
t.Fatal("rate-limited refresh clobbered bound lastOverlayPID back to 0")
|
||||
}
|
||||
a.closeAgentSessions()
|
||||
}
|
||||
|
||||
func TestComputerUseLocaleResolvesAuto(t *testing.T) {
|
||||
a := &App{cfg: &config.Config{Locale: i18n.Auto}}
|
||||
got := a.computerUseLocale()
|
||||
if got == "" || got == i18n.Auto {
|
||||
t.Fatalf("computerUseLocale() for Auto = %q, want concrete resolved locale", got)
|
||||
}
|
||||
if want := i18n.EffectiveLocale(i18n.Auto); got != want {
|
||||
t.Fatalf("computerUseLocale() = %q, want %q", got, want)
|
||||
}
|
||||
a.cfg.Locale = i18n.EnUS
|
||||
if got := a.computerUseLocale(); got != i18n.EnUS {
|
||||
t.Fatalf("computerUseLocale() for en-US = %q, want en-US", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompletedSessionRetainsCompletedOverlayAndUnlocksInput(t *testing.T) {
|
||||
a := &App{cfg: &config.Config{Locale: i18n.ZhCN}}
|
||||
vm := driver.VMInfo{
|
||||
DriverID: driver.BuiltinReimsMacOSDriverID,
|
||||
Name: "tahoe-recovery-done",
|
||||
}
|
||||
vmKey := vm.Ref().Key()
|
||||
const pluginID = "builtin.macos.autoinstall"
|
||||
|
||||
a.grantEphemeralVMAccess(pluginID, vmKey)
|
||||
a.grantProtectedPhase(pluginID, vmKey, driver.PhaseInstaller, 0, true)
|
||||
a.beginAgentSession(nil, pluginID, vm, "macOS Auto-Install", "stage3_install_wait", "lock", true)
|
||||
a.bindAgentSessionPID(vmKey, 31337)
|
||||
|
||||
// Mark completed (as runner.completeRecoveryOnly does right before EndSession).
|
||||
a.sessionMu.Lock()
|
||||
sess := a.agentSessions[vmKey]
|
||||
sess.stage = "stage6_desktop_ready"
|
||||
sess.status = "completed"
|
||||
sess.message = "已完成恢复模式安装并进入 macOS,画面输入已解锁"
|
||||
a.sessionMu.Unlock()
|
||||
|
||||
if step := a.sessionOverlayStep(i18n.ZhCN, a.activeAgentSessions()[0]); step != "已完成" {
|
||||
t.Fatalf("sessionOverlayStep for completed = %q, want 已完成", step)
|
||||
}
|
||||
st := a.completedSessionOverlayState(i18n.ZhCN, sess, 31337, true)
|
||||
if !st.Completed || st.InputLocked || st.CanPause || st.CanResume {
|
||||
t.Fatalf("completed overlay state must unlock input and hide pause/resume: %+v", st)
|
||||
}
|
||||
if st.StepText != "已完成" || st.CloseLabel != "关闭" {
|
||||
t.Fatalf("unexpected completed overlay labels: StepText=%q CloseLabel=%q", st.StepText, st.CloseLabel)
|
||||
}
|
||||
|
||||
// Ending the completed session exits active control, revokes grants, and retains completed overlay tracking.
|
||||
a.endAgentSession(nil, pluginID, vmKey, "session_ended")
|
||||
if len(a.activeAgentSessions()) != 0 {
|
||||
t.Fatal("completed session must not remain in ActiveAgentSessions")
|
||||
}
|
||||
if a.hasEphemeralVMAccess(pluginID, vmKey) {
|
||||
t.Fatal("completed session must revoke ephemeral VM access")
|
||||
}
|
||||
if _, ok := a.lookupProtectedPhaseGrant(pluginID, vmKey); ok {
|
||||
t.Fatal("completed session must revoke protected-phase grant")
|
||||
}
|
||||
if !a.isCompletedOverlay(vmKey) {
|
||||
t.Fatal("expected completed overlay marker to remain active until dismissed or VM stops")
|
||||
}
|
||||
|
||||
// Polling while VM is stopped cleans up the completed overlay automatically.
|
||||
a.mu.Lock()
|
||||
a.lastVMs = []driver.VMListItem{{DriverID: vm.DriverID, Name: vm.Name, State: "stopped"}}
|
||||
a.lastVMsAt = time.Now()
|
||||
a.mu.Unlock()
|
||||
a.cleanupStaleCompletedOverlays()
|
||||
if a.isCompletedOverlay(vmKey) {
|
||||
t.Fatal("completed overlay marker should be cleared when VM stops")
|
||||
}
|
||||
}
|
||||
+127
-69
@@ -17,10 +17,12 @@ 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/host/sessionoverlay"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
"github.com/Nwflower/reims-go/internal/packetbridge"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/market"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/tray"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
@@ -47,18 +49,20 @@ type PendingChange struct {
|
||||
}
|
||||
|
||||
type AppState struct {
|
||||
QuitMode string `json:"quit_mode,omitempty"`
|
||||
Config *config.Config `json:"config"`
|
||||
Host host.Report `json:"host"`
|
||||
Optimizations []host.Optimization `json:"optimizations"`
|
||||
Runtimes []rt.Installed `json:"runtimes"`
|
||||
ActiveRuntime *rt.Installed `json:"active_runtime,omitempty"`
|
||||
CanSuspend bool `json:"can_suspend"`
|
||||
VMs []driver.VMListItem `json:"vms"`
|
||||
VMListError string `json:"vm_list_error,omitempty"`
|
||||
Transitions map[string]string `json:"transitions"`
|
||||
PendingChanges map[string][]PendingChange `json:"pending_changes"`
|
||||
ActiveGuides []string `json:"active_guides,omitempty"`
|
||||
QuitMode string `json:"quit_mode,omitempty"`
|
||||
Config *config.Config `json:"config"`
|
||||
Host host.Report `json:"host"`
|
||||
Optimizations []host.Optimization `json:"optimizations"`
|
||||
Runtimes []rt.Installed `json:"runtimes"`
|
||||
ActiveRuntime *rt.Installed `json:"active_runtime,omitempty"`
|
||||
CanSuspend bool `json:"can_suspend"`
|
||||
VMs []driver.VMListItem `json:"vms"`
|
||||
VMListError string `json:"vm_list_error,omitempty"`
|
||||
Transitions map[string]string `json:"transitions"`
|
||||
PendingChanges map[string][]PendingChange `json:"pending_changes"`
|
||||
ActiveGuides []string `json:"active_guides,omitempty"`
|
||||
AgentSessions []AgentSessionView `json:"agent_sessions,omitempty"`
|
||||
ProvisionReadyVMs []string `json:"provision_ready_vms,omitempty"`
|
||||
// InstallGuideEnabled reports whether the VM-window install guide service is active.
|
||||
InstallGuideEnabled bool `json:"install_guide_enabled,omitempty"`
|
||||
// NeedsSetup is true on first launch, until a data folder is chosen (setup.go).
|
||||
@@ -121,55 +125,70 @@ type App struct {
|
||||
trayMgr *tray.Manager
|
||||
allowQuit bool
|
||||
launchPrevDataRoot string
|
||||
quitMode string
|
||||
vmStarts sync.WaitGroup
|
||||
lastVMs []driver.VMListItem
|
||||
lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale
|
||||
lastVMListErr error
|
||||
pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick
|
||||
diskPaths map[string]cachedDiskPath
|
||||
procSamples map[string]host.ProcessSample
|
||||
recentLogs []string
|
||||
needsSetup bool
|
||||
root dataroot.Status // how the current data folder opened (dataroot_flow.go)
|
||||
launch cli.WindowArgs // flags this window was started with (window_launch.go)
|
||||
trayIcon []byte // embedded PNG passed in from package main
|
||||
logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go)
|
||||
pluginMgr *plugin.Manager
|
||||
pluginFiles map[string]pluginFileGrant
|
||||
pluginMarket *plugin.MarketClient
|
||||
controlServer *control.Server
|
||||
driverRouter *driver.Router
|
||||
vmStateTable *driver.StateTable
|
||||
lifecycleSvc *vmlifecycle.Service
|
||||
runtimeKinds *rt.KindRegistry
|
||||
uiHealth uiHealthState
|
||||
themeMode string
|
||||
vmClosePrompts sync.Map
|
||||
displayHost vmDisplayHost
|
||||
quitMode string
|
||||
vmStarts sync.WaitGroup
|
||||
lastVMs []driver.VMListItem
|
||||
lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale
|
||||
lastVMListErr error
|
||||
pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick
|
||||
diskPaths map[string]cachedDiskPath
|
||||
procSamples map[string]host.ProcessSample
|
||||
recentLogs []string
|
||||
needsSetup bool
|
||||
root dataroot.Status // how the current data folder opened (dataroot_flow.go)
|
||||
launch cli.WindowArgs // flags this window was started with (window_launch.go)
|
||||
trayIcon []byte // embedded PNG passed in from package main
|
||||
logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go)
|
||||
pluginMgr *plugin.Manager
|
||||
pluginMarket *market.MarketClient
|
||||
controlServer *control.Server
|
||||
driverRouter *driver.Router
|
||||
vmStateTable *driver.StateTable
|
||||
lifecycleSvc *vmlifecycle.Service
|
||||
runtimeKinds *rt.KindRegistry
|
||||
uiHealth uiHealthState
|
||||
appleVZProbeOnce sync.Once
|
||||
appleVZProbe host.AppleVirtualizationStatus
|
||||
themeMode string
|
||||
vmClosePrompts sync.Map
|
||||
displayHost vmDisplayHost
|
||||
|
||||
displayPlacements sync.Map
|
||||
|
||||
inputShuttingDown bool
|
||||
// computerUseOwnedVMs caches ownership markers for MCP-created temporary VMs.
|
||||
computerUseOwnedVMs map[string]map[string]bool
|
||||
computerUseCloneMu sync.Mutex
|
||||
// computerUseHeld records the keys and pointer buttons each plugin left
|
||||
// held in a guest, so the host can release them when the plugin goes away.
|
||||
computerUseHeld map[string]map[string]*heldInputs
|
||||
computerUseHeldMu sync.Mutex
|
||||
fullscreenHotkey host.FullscreenHotkeyService
|
||||
fullscreenSyncMu sync.Mutex
|
||||
fullscreenTargets fullscreenHotkeyTargetCache
|
||||
|
||||
// Plugin elevation requests (elevate_flow.go).
|
||||
elevatePromptMu sync.Mutex
|
||||
elevateMu sync.Mutex
|
||||
elevatePending map[string]chan bool
|
||||
elevateSeq uint64
|
||||
elevateEmit func(ElevationPrompt)
|
||||
elevateDismiss func(string)
|
||||
elevateRunner elevationRunner
|
||||
// Host-side plugin API service (computer-use, secrets, downloads, elevation, file grants).
|
||||
hostAPI HostAPIService
|
||||
|
||||
// #105 host confirmation & protected-phase grants (confirm_flow.go).
|
||||
confirmMu sync.Mutex
|
||||
confirmPending map[string]chan ConfirmResolution
|
||||
confirmSeq uint64
|
||||
confirmEmit func(ConfirmPrompt)
|
||||
confirmDismiss func(id, reason string)
|
||||
protectedPhaseGrants map[phaseGrantKey]protectedPhaseGrant
|
||||
protectedPhaseInFlight map[phaseGrantKey]bool
|
||||
lastVMPhases map[string]string
|
||||
|
||||
// #103 Agent sessions, physical input takeover, and Win32 overlay (agent_session_flow.go).
|
||||
sessionMu sync.Mutex
|
||||
agentSessions map[string]*agentSession
|
||||
completedOverlays map[string]completedOverlayEntry
|
||||
ephemeralVMAccess map[string]map[string]bool
|
||||
takeoverMon *host.TakeoverMonitor
|
||||
sessionOverlay *sessionoverlay.Manager
|
||||
sessionShuttingDown bool
|
||||
|
||||
// Install guide recheck & post-install handoff state (install_guide.go, guarded by mu).
|
||||
guideRecheckVMs map[string]bool
|
||||
pendingGuideHandoffs map[string]string
|
||||
|
||||
// Read-only VM runtime telemetry snapshots (vm_monitor.go / computer_use_host.go).
|
||||
telemetryMu sync.Mutex
|
||||
vmTelemetry map[string]*vmTelemetryState
|
||||
}
|
||||
|
||||
// Lifecycle exposes Wails lifecycle callbacks without exporting them as
|
||||
@@ -204,17 +223,18 @@ func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) {
|
||||
needsSetup: needsSetup,
|
||||
launch: launch,
|
||||
launchPrevDataRoot: launchPrevDataRoot,
|
||||
trayIcon: trayIcon,
|
||||
transitions: make(map[string]string),
|
||||
pendingChanges: make(map[string][]PendingChange),
|
||||
rebootWatchers: make(map[string]rebootWatcherEntry),
|
||||
pollWake: make(chan struct{}, 1),
|
||||
diskPaths: make(map[string]cachedDiskPath),
|
||||
procSamples: make(map[string]host.ProcessSample),
|
||||
pluginFiles: make(map[string]pluginFileGrant),
|
||||
uiHealth: uiHealthState{windowHidden: launch.Background},
|
||||
displayHost: vmDisplayHost{displays: host.ConnectedDisplays, move: host.MoveProcessWindowToDisplay},
|
||||
trayIcon: trayIcon,
|
||||
transitions: make(map[string]string),
|
||||
pendingChanges: make(map[string][]PendingChange),
|
||||
rebootWatchers: make(map[string]rebootWatcherEntry),
|
||||
pollWake: make(chan struct{}, 1),
|
||||
diskPaths: make(map[string]cachedDiskPath),
|
||||
procSamples: make(map[string]host.ProcessSample),
|
||||
uiHealth: uiHealthState{windowHidden: launch.Background},
|
||||
displayHost: vmDisplayHost{displays: host.ConnectedDisplays, move: host.MoveProcessWindowToDisplay},
|
||||
}
|
||||
a.hostAPI.app = a
|
||||
a.hostAPI.pluginFiles = make(map[string]pluginFileGrant)
|
||||
return a, Lifecycle{
|
||||
OnStartup: a.startup,
|
||||
OnBeforeClose: a.beforeClose,
|
||||
@@ -290,8 +310,8 @@ func (a *App) beforeClose(ctx context.Context) bool {
|
||||
wailsRuntime.WindowHide(ctx)
|
||||
return true
|
||||
}
|
||||
if tasks.hasRunningDownload() {
|
||||
// Closing now would abort a download: ask first. The window's
|
||||
if tasks.hasRunningDownload() || tasks.hasRunningRestore() {
|
||||
// Closing now would abort a download or restore: ask first. The window's
|
||||
// confirmation calls QuitApp, which lets the next close through.
|
||||
a.emit("reims:confirm-close-downloads", true)
|
||||
return true
|
||||
@@ -306,6 +326,8 @@ func (a *App) shutdown(ctx context.Context) {
|
||||
}
|
||||
tasks.cancelAll()
|
||||
a.cancelPendingElevations()
|
||||
a.cancelPendingConfirmations()
|
||||
a.closeAgentSessions()
|
||||
stopAllVMMonitors()
|
||||
a.stopPluginControlServer()
|
||||
a.mu.Lock()
|
||||
@@ -386,12 +408,13 @@ func (a *App) GetState() AppState {
|
||||
a.mu.Unlock()
|
||||
|
||||
rep := host.Inspect(cfgCopy.DataRoot)
|
||||
rep.AppleVirtualization = a.nativeVirtualizationStatus()
|
||||
if needsSetup || rootStatus.ReadOnly {
|
||||
rep.PendingHypervisorBoot = host.ReadPendingHypervisorBoot("", rep.WHPX)
|
||||
}
|
||||
runtimes, _ := rt.List(&cfgCopy)
|
||||
active, _ := rt.ResolveActive(&cfgCopy)
|
||||
// The poller's list (≤ polledMaxAge old, and invalidated by wakePoll after
|
||||
// The poller's list (鈮?polledMaxAge old, and invalidated by wakePoll after
|
||||
// start/stop/delete) instead of another `reims-ctl list` per refresh.
|
||||
var vms []driver.VMListItem
|
||||
var listError string
|
||||
@@ -438,6 +461,8 @@ func (a *App) GetState() AppState {
|
||||
Transitions: trCopy,
|
||||
PendingChanges: pcCopy,
|
||||
ActiveGuides: activeGuides,
|
||||
AgentSessions: a.activeAgentSessions(),
|
||||
ProvisionReadyVMs: a.provisionReadyVMKeys(),
|
||||
InstallGuideEnabled: installGuideEnabled,
|
||||
NeedsSetup: needsSetup,
|
||||
DataRoot: rootStatus,
|
||||
@@ -477,6 +502,19 @@ func (a *App) SetMinimizeToTray(enabled bool) error {
|
||||
return a.setPreference(func(cfg *config.Config) { cfg.MinimizeToTray = &enabled })
|
||||
}
|
||||
|
||||
// SetAgentTakeoverPauseSec updates how long Agent input pauses after physical
|
||||
// keyboard/mouse takeover on a VM window (0 = pause until manual Resume).
|
||||
func (a *App) SetAgentTakeoverPauseSec(seconds int) error {
|
||||
if seconds < 0 {
|
||||
seconds = 0
|
||||
}
|
||||
if seconds > 300 {
|
||||
seconds = 300
|
||||
}
|
||||
v := seconds
|
||||
return a.setPreference(func(cfg *config.Config) { cfg.AgentTakeoverPauseSec = &v })
|
||||
}
|
||||
|
||||
// showMainWindow restores and focuses the Wails window from the system tray.
|
||||
func (a *App) showMainWindow() {
|
||||
if a.ctx == nil {
|
||||
@@ -526,10 +564,16 @@ func (a *App) startTray() {
|
||||
cached = vms
|
||||
}
|
||||
}
|
||||
effLoc := i18n.EffectiveLocale(loc)
|
||||
activeSessions := map[string]AgentSessionView{}
|
||||
for _, s := range a.activeAgentSessions() {
|
||||
activeSessions[s.VMKey] = s
|
||||
}
|
||||
items := make([]tray.VMItem, 0, len(cached))
|
||||
for _, vm := range cached {
|
||||
key := vmKeyForDriver(vm.DriverID, vm.Name)
|
||||
state := vm.State
|
||||
if t := transitions[vmKeyForDriver(vm.DriverID, vm.Name)]; t != "" {
|
||||
if t := transitions[key]; t != "" {
|
||||
state = t
|
||||
}
|
||||
// The display name is the VM's note, read straight from its
|
||||
@@ -540,7 +584,13 @@ func (a *App) startTray() {
|
||||
label = sanitizeVMNote(string(b))
|
||||
}
|
||||
}
|
||||
items = append(items, tray.VMItem{DriverID: vm.DriverID, Name: vm.Name, Label: label, State: state})
|
||||
item := tray.VMItem{DriverID: vm.DriverID, Name: vm.Name, Label: label, State: state}
|
||||
if sess, ok := activeSessions[key]; ok {
|
||||
item.HasRemoteControl = true
|
||||
title, _ := a.sessionBannerText(effLoc, sess)
|
||||
item.RemoteControlLabel = title
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return tray.Snapshot{
|
||||
Locale: i18n.EffectiveLocale(loc),
|
||||
@@ -601,6 +651,8 @@ func (a *App) trayVMAction(driverID, name string, act tray.Action) {
|
||||
case tray.ActOpenInApp:
|
||||
a.showMainWindow()
|
||||
a.emit("reims:tray-select-vm", name)
|
||||
case tray.ActStopRemoteControl:
|
||||
err = a.StopAgentSession(driverID, name)
|
||||
}
|
||||
if err != nil {
|
||||
a.emitVMLog(name, failTitle+": "+err.Error())
|
||||
@@ -617,8 +669,10 @@ func (a *App) resetDataRootCaches() {
|
||||
a.lastVMListErr = nil
|
||||
a.diskPaths = make(map[string]cachedDiskPath)
|
||||
a.procSamples = make(map[string]host.ProcessSample)
|
||||
a.pluginFiles = make(map[string]pluginFileGrant)
|
||||
a.guideRecheckVMs = nil
|
||||
a.pendingGuideHandoffs = nil
|
||||
a.mu.Unlock()
|
||||
a.hostAPISvc().ResetPluginFiles()
|
||||
cancelPluginTasks("")
|
||||
}
|
||||
|
||||
@@ -834,6 +888,10 @@ func (a *App) InstallRuntimeArchive(archivePath string) (*rt.Installed, error) {
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if inst.Kind == rt.StambhaKind {
|
||||
a.emitLog("runtime", fmt.Sprintf("Runtime %s installed -> %s", inst.Commit, inst.Dir))
|
||||
return inst, nil
|
||||
}
|
||||
if err := a.activateInstalledRuntime(&cfg, inst.Commit); err != nil {
|
||||
inst.Active = false
|
||||
a.emitLog("runtime", err.Error())
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type applicationMenuSnapshot struct {
|
||||
Groups []applicationMenuGroup `json:"groups"`
|
||||
Standard map[string]string `json:"standard"`
|
||||
}
|
||||
|
||||
type applicationMenuGroup struct {
|
||||
Label string `json:"label"`
|
||||
Rows []applicationMenuRow `json:"rows"`
|
||||
}
|
||||
|
||||
type applicationMenuRow struct {
|
||||
Label string `json:"label,omitempty"`
|
||||
Key string `json:"key,omitempty"`
|
||||
Token int32 `json:"token,omitempty"`
|
||||
Checked bool `json:"checked,omitempty"`
|
||||
}
|
||||
|
||||
func parseApplicationMenu(raw string) (applicationMenuSnapshot, error) {
|
||||
var snapshot applicationMenuSnapshot
|
||||
if err := json.Unmarshal([]byte(raw), &snapshot); err != nil || len(snapshot.Groups) != 3 {
|
||||
return snapshot, errors.New("invalid application menu groups")
|
||||
}
|
||||
for _, key := range []string{"edit", "window", "speech", "hide:", "Quit"} {
|
||||
if strings.TrimSpace(snapshot.Standard[key]) == "" {
|
||||
return snapshot, errors.New("missing standard application menu labels")
|
||||
}
|
||||
}
|
||||
tokens := make(map[int32]bool)
|
||||
for _, group := range snapshot.Groups {
|
||||
if strings.TrimSpace(group.Label) == "" || len(group.Rows) == 0 || len(group.Rows) > 40 {
|
||||
return snapshot, errors.New("invalid application menu group")
|
||||
}
|
||||
for _, row := range group.Rows {
|
||||
switch row.Key {
|
||||
case "", "n", "b", "l", ",", "\r":
|
||||
default:
|
||||
return snapshot, errors.New("invalid application menu shortcut")
|
||||
}
|
||||
if row.Token < 0 || (row.Token > 0 && (row.Label == "" || tokens[row.Token])) {
|
||||
return snapshot, errors.New("invalid application menu action")
|
||||
}
|
||||
if row.Token > 0 {
|
||||
tokens[row.Token] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return snapshot, nil
|
||||
}
|
||||
|
||||
// SyncApplicationMenu publishes the renderer's localized menu and current
|
||||
// action availability to the host's native menu bar.
|
||||
func (a *App) SyncApplicationMenu(raw string) error {
|
||||
if a.ctx == nil {
|
||||
return errors.New("application menu is not ready")
|
||||
}
|
||||
if len(raw) > 32<<10 {
|
||||
return errors.New("application menu snapshot is too large")
|
||||
}
|
||||
snapshot, err := parseApplicationMenu(raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return a.syncApplicationMenu(snapshot)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//go:build darwin && cgo
|
||||
|
||||
package app
|
||||
|
||||
/*
|
||||
#cgo CFLAGS: -x objective-c
|
||||
#cgo LDFLAGS: -framework AppKit
|
||||
#include <stdlib.h>
|
||||
int reimsSyncApplicationMenu(const char *snapshot);
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"sync/atomic"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var nativeMenuOwner atomic.Pointer[App]
|
||||
|
||||
func (a *App) syncApplicationMenu(menu applicationMenuSnapshot) error {
|
||||
snapshot, err := json.Marshal(menu)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data := C.CString(string(snapshot))
|
||||
defer C.free(unsafe.Pointer(data))
|
||||
nativeMenuOwner.Store(a)
|
||||
if C.reimsSyncApplicationMenu(data) == 0 {
|
||||
return errors.New("macOS application menu is not ready")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//export reimsApplicationMenuClicked
|
||||
func reimsApplicationMenuClicked(token C.int) {
|
||||
if a := nativeMenuOwner.Load(); a != nil {
|
||||
// Let AppKit finish handling the input before emitting back to WebKit.
|
||||
go a.emit("reims:application-menu-command", int(token))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
//go:build darwin && cgo
|
||||
|
||||
#import <AppKit/AppKit.h>
|
||||
|
||||
extern void reimsApplicationMenuClicked(int token);
|
||||
|
||||
@interface ReimsMenuTarget : NSObject
|
||||
- (void)invoke:(NSMenuItem *)sender;
|
||||
@end
|
||||
|
||||
@implementation ReimsMenuTarget
|
||||
- (void)invoke:(NSMenuItem *)sender {
|
||||
reimsApplicationMenuClicked((int)sender.tag);
|
||||
}
|
||||
@end
|
||||
|
||||
static ReimsMenuTarget *menuTarget;
|
||||
static NSArray<NSMenuItem *> *managedItems;
|
||||
static NSArray<NSMenuItem *> *standardItems;
|
||||
|
||||
static void setMenuTitle(NSMenuItem *item, NSString *title) {
|
||||
if (title.length == 0) return;
|
||||
item.title = title;
|
||||
item.submenu.title = title;
|
||||
}
|
||||
|
||||
static void localizeStandardItems(NSMenu *menu, NSDictionary<NSString *, NSString *> *labels) {
|
||||
for (NSMenuItem *item in menu.itemArray) {
|
||||
if (item.isSeparatorItem) continue;
|
||||
if (item.hasSubmenu) {
|
||||
// AppKit can also inject its own submenus, such as AutoFill.
|
||||
// Only relabel the speech submenu created by Wails.
|
||||
for (NSMenuItem *child in item.submenu.itemArray) {
|
||||
if (child.action == @selector(startSpeaking:)) {
|
||||
setMenuTitle(item, labels[@"speech"]);
|
||||
localizeStandardItems(item.submenu, labels);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (item.action) {
|
||||
NSString *action = NSStringFromSelector(item.action);
|
||||
// Wails sends both Undo and Redo to undo:, with Shift for Redo.
|
||||
if (item.action == @selector(undo:) && (item.keyEquivalentModifierMask & NSEventModifierFlagShift)) {
|
||||
action = @"redo:";
|
||||
}
|
||||
setMenuTitle(item, labels[action]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static NSMenu *buildMenu(NSDictionary *group) {
|
||||
NSMenu *menu = [[[NSMenu alloc] initWithTitle:group[@"label"]] autorelease];
|
||||
menu.autoenablesItems = NO;
|
||||
for (NSDictionary *row in group[@"rows"]) {
|
||||
if (!row[@"label"]) {
|
||||
[menu addItem:[NSMenuItem separatorItem]];
|
||||
continue;
|
||||
}
|
||||
NSInteger token = [row[@"token"] integerValue];
|
||||
NSMenuItem *item = [[[NSMenuItem alloc] initWithTitle:row[@"label"]
|
||||
action:token ? @selector(invoke:) : NULL
|
||||
keyEquivalent:row[@"key"] ?: @""] autorelease];
|
||||
item.keyEquivalentModifierMask = NSEventModifierFlagCommand;
|
||||
item.tag = token;
|
||||
item.target = menuTarget;
|
||||
item.enabled = token != 0;
|
||||
item.state = [row[@"checked"] boolValue] ? NSControlStateValueOn : NSControlStateValueOff;
|
||||
[menu addItem:item];
|
||||
}
|
||||
return menu;
|
||||
}
|
||||
|
||||
static BOOL setMenuGroups(NSDictionary *snapshot) {
|
||||
NSMenu *main = NSApp.mainMenu;
|
||||
NSArray<NSDictionary *> *groups = snapshot[@"groups"];
|
||||
if (!main || groups.count != 3) return NO;
|
||||
if (!menuTarget) menuTarget = [ReimsMenuTarget new];
|
||||
|
||||
if (!managedItems || managedItems.firstObject.menu != main) {
|
||||
// Wails initializes App, Edit and Window in this order. Keep the
|
||||
// original items so localization does not change targets or shortcuts.
|
||||
if (main.numberOfItems != 3) return NO;
|
||||
[standardItems release];
|
||||
standardItems = [main.itemArray copy];
|
||||
NSMutableArray *items = [NSMutableArray arrayWithCapacity:3];
|
||||
NSInteger index = 2;
|
||||
for (NSDictionary *group in groups) {
|
||||
[items addObject:[[[NSMenuItem alloc] initWithTitle:group[@"label"] action:NULL keyEquivalent:@""] autorelease]];
|
||||
}
|
||||
[main insertItem:items[0] atIndex:index];
|
||||
[main insertItem:items[1] atIndex:index + 1];
|
||||
[main addItem:items[2]];
|
||||
[managedItems release];
|
||||
managedItems = [items copy];
|
||||
}
|
||||
NSDictionary<NSString *, NSString *> *labels = snapshot[@"standard"];
|
||||
setMenuTitle(standardItems[0], @"Reims-Go");
|
||||
setMenuTitle(standardItems[1], labels[@"edit"]);
|
||||
setMenuTitle(standardItems[2], labels[@"window"]);
|
||||
for (NSMenuItem *item in standardItems) localizeStandardItems(item.submenu, labels);
|
||||
|
||||
for (NSUInteger i = 0; i < groups.count; i++) {
|
||||
NSMenuItem *item = managedItems[i];
|
||||
item.title = groups[i][@"label"];
|
||||
item.submenu = buildMenu(groups[i]);
|
||||
}
|
||||
NSApp.helpMenu = managedItems.lastObject.submenu;
|
||||
return YES;
|
||||
}
|
||||
|
||||
int reimsSyncApplicationMenu(const char *snapshot) {
|
||||
@autoreleasepool {
|
||||
NSData *data = [NSData dataWithBytes:snapshot length:strlen(snapshot)];
|
||||
NSDictionary *menu = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
|
||||
if (NSThread.isMainThread) return setMenuGroups(menu);
|
||||
__block BOOL updated = NO;
|
||||
dispatch_sync(dispatch_get_main_queue(), ^{ updated = setMenuGroups(menu); });
|
||||
return updated;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//go:build !darwin || !cgo
|
||||
|
||||
package app
|
||||
|
||||
import "errors"
|
||||
|
||||
func (a *App) syncApplicationMenu(applicationMenuSnapshot) error {
|
||||
return errors.New("native application menu is unavailable")
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package app
|
||||
|
||||
import "testing"
|
||||
|
||||
const standardMenuFixture = `,"standard":{"edit":"编辑","window":"窗口","speech":"朗读","hide:":"隐藏 Reims-Go","Quit":"退出 Reims-Go"}`
|
||||
|
||||
func TestParseApplicationMenu(t *testing.T) {
|
||||
const groups = `[{"label":"虚拟机","rows":[{"label":"Start","token":1,"key":"\r"}]},{"label":"View","rows":[{}, {"label":"Sidebar","checked":true,"token":2}]},{"label":"Help","rows":[{"label":"Reims-Go"}]}]`
|
||||
parsed, err := parseApplicationMenu(`{"groups":` + groups + standardMenuFixture + `}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if parsed.Groups[0].Rows[0].Key != "\r" || !parsed.Groups[1].Rows[1].Checked || parsed.Groups[2].Rows[0].Token != 0 {
|
||||
t.Fatalf("menu snapshot did not keep shortcut, checked state and disabled row: %+v", parsed)
|
||||
}
|
||||
if parsed.Standard["edit"] != "编辑" || parsed.Standard["Quit"] != "退出 Reims-Go" {
|
||||
t.Fatalf("menu snapshot did not keep localized standard items: %+v", parsed.Standard)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseApplicationMenuRejectsInvalidSnapshots(t *testing.T) {
|
||||
for _, groups := range []string{
|
||||
`null`,
|
||||
`[{"label":"VM","rows":[{}]}]`,
|
||||
`[{"label":"VM","rows":[{"label":"Start","token":1}]},{"label":"View","rows":[{"label":"Sidebar","token":1}]},{"label":"Help","rows":[{}]}]`,
|
||||
`[{"label":"VM","rows":[{"label":"Start","token":1,"key":"q"}]},{"label":"View","rows":[{}]},{"label":"Help","rows":[{}]}]`,
|
||||
} {
|
||||
if _, err := parseApplicationMenu(`{"groups":` + groups + standardMenuFixture + `}`); err == nil {
|
||||
t.Errorf("accepted invalid groups: %s", groups)
|
||||
}
|
||||
}
|
||||
if _, err := parseApplicationMenu(`{"groups":[{"label":"VM","rows":[{}]},{"label":"View","rows":[{}]},{"label":"Help","rows":[{}]}]}`); err == nil {
|
||||
t.Error("accepted missing standard menu labels")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/fetch"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/netproxy"
|
||||
)
|
||||
|
||||
const (
|
||||
armImageBuild = "26B131"
|
||||
armImageName = "UniversalMac_27.2.1_26B131_Restore.ipsw"
|
||||
armImageURL = "https://updates.cdn-apple.com/2026FallFCS/c202a724-db7e-4d56-917b-110aa0226507/" + armImageName
|
||||
armImageSHA = "233e85a09887579d47d0b195e7db72be7f204261059c6946f719acf6b300814f"
|
||||
armImageSize = int64(25595954706)
|
||||
)
|
||||
|
||||
// DownloadARMImage fetches the pinned ARM restore image from Apple into the user data folder.
|
||||
func (a *App) DownloadARMImage() (string, error) {
|
||||
cfg := a.runtimeConfig()
|
||||
if err := cfg.EnsureDirs(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
final := filepath.Join(cfg.ImagesDir(), "arm64", armImageName)
|
||||
if err := os.MkdirAll(filepath.Dir(final), 0o755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
a.ensureTaskEmitter()
|
||||
var ctx context.Context
|
||||
var cancel context.CancelFunc
|
||||
run, id, owned := installerDownloads.reserveOrFind("arm-ipsw", armImageBuild, "installer-download", func(initialPhase string) string {
|
||||
ctx, cancel = context.WithCancel(a.baseCtx())
|
||||
return tasks.startWithInstaller("installer-download", "macOS 27.2.1 路 ARM64", "", "arm-ipsw", armImageBuild, initialPhase, cancel)
|
||||
})
|
||||
if !owned {
|
||||
return id, nil
|
||||
}
|
||||
go func() {
|
||||
defer cancel()
|
||||
client := netproxy.NewClient()
|
||||
client.Timeout = 0
|
||||
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 10 || req.URL.Scheme != "https" || req.URL.Hostname() != "updates.cdn-apple.com" {
|
||||
return errors.New("ARM restore image download redirected outside Apple's update server")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
path, err := fetch.ResumeDirect(ctx, client, armImageURL, final, armImageSize, armImageSHA, func(done, total int64) {
|
||||
update := host.Update{Kind: host.KindProgress, Done: done, Total: total, Percent: percent(done, total)}
|
||||
tasks.update(id, update)
|
||||
run.publish(update)
|
||||
}, fetch.ResumeOptions{MaxBytes: armImageSize, StallTimeout: 45 * time.Second})
|
||||
if err == nil {
|
||||
if info, statErr := os.Stat(path); statErr != nil {
|
||||
err = statErr
|
||||
} else if info.Size() != armImageSize {
|
||||
err = errors.New("ARM restore image size does not match the pinned build")
|
||||
}
|
||||
}
|
||||
if err != nil && ctx.Err() != nil {
|
||||
err = ctx.Err()
|
||||
}
|
||||
if err != nil {
|
||||
path = ""
|
||||
}
|
||||
installerDownloads.completeImage(run, path, err)
|
||||
tasks.finish(id, path, err)
|
||||
}()
|
||||
return id, nil
|
||||
}
|
||||
@@ -0,0 +1,636 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
// AutoInstallerProviderView describes one enabled built-in or Sidecar plugin
|
||||
// that provides unattended guest installation for a guest OS family.
|
||||
type AutoInstallerProviderView struct {
|
||||
PluginID string `json:"plugin_id"`
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description,omitempty"`
|
||||
GuestFamilies []string `json:"guest_families"`
|
||||
RequiresOfflineInstaller bool `json:"requires_offline_installer,omitempty"`
|
||||
SecretSetting string `json:"secret_setting"`
|
||||
}
|
||||
|
||||
// AutoInstallStartRequest carries Stage 0 preflight parameters submitted by the
|
||||
// host Create Wizard or VM Detail Page. Password is encrypted directly into
|
||||
// host DPAPI storage and never sent to the plugin or written to logs.
|
||||
type AutoInstallStartRequest struct {
|
||||
PluginID string `json:"plugin_id,omitempty"`
|
||||
DriverID string `json:"driver_id,omitempty"`
|
||||
VMName string `json:"vm_name"`
|
||||
Mode string `json:"mode,omitempty"` // "recovery_only" | "full"
|
||||
GuestLang string `json:"guest_lang,omitempty"`
|
||||
FullName string `json:"full_name"`
|
||||
AccountName string `json:"account_name"`
|
||||
Password string `json:"password"`
|
||||
Region string `json:"region,omitempty"`
|
||||
Appearance string `json:"appearance,omitempty"`
|
||||
AgeRange string `json:"age_range,omitempty"`
|
||||
SLAAccepted bool `json:"sla_accepted"`
|
||||
SaveUnlockCredential bool `json:"save_unlock_credential,omitempty"`
|
||||
InstallGuestTools *bool `json:"install_guest_tools,omitempty"`
|
||||
OCRBackend string `json:"ocr_backend,omitempty"`
|
||||
CustomOCRMirror string `json:"custom_ocr_mirror,omitempty"`
|
||||
StartVMIfStopped bool `json:"start_vm_if_stopped,omitempty"`
|
||||
}
|
||||
|
||||
// ListAutoInstallers returns enabled auto-installer plugins matching guestFamily
|
||||
// (or all enabled providers when guestFamily is empty). Disabling a plugin
|
||||
// immediately removes it from this list so the UI leaves zero residue.
|
||||
func (a *App) ListAutoInstallers(guestFamily string) []AutoInstallerProviderView {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
if mgr == nil || mgr.Registry() == nil {
|
||||
return nil
|
||||
}
|
||||
loc := string(a.computerUseLocale())
|
||||
items := mgr.Registry().AutoInstallersForFamily(guestFamily)
|
||||
out := make([]AutoInstallerProviderView, 0, len(items))
|
||||
for _, item := range items {
|
||||
secretKey := strings.TrimSpace(item.SecretSetting)
|
||||
out = append(out, AutoInstallerProviderView{
|
||||
PluginID: item.PluginID,
|
||||
ID: item.ID,
|
||||
Title: item.Title.Get(loc),
|
||||
Description: item.Description.Get(loc),
|
||||
GuestFamilies: append([]string(nil), item.GuestFamilies...),
|
||||
RequiresOfflineInstaller: item.RequiresOfflineInstaller,
|
||||
SecretSetting: secretKey,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (a *App) resolveAutoInstallerProvider(pluginID, guestFamily string) (*plugin.Manager, AutoInstallerProviderView, error) {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
if mgr == nil || mgr.Registry() == nil {
|
||||
return nil, AutoInstallerProviderView{}, errors.New("plugin manager is unavailable")
|
||||
}
|
||||
providers := a.ListAutoInstallers(guestFamily)
|
||||
if len(providers) == 0 && guestFamily != "" {
|
||||
providers = a.ListAutoInstallers("")
|
||||
}
|
||||
if len(providers) == 0 {
|
||||
return nil, AutoInstallerProviderView{}, errors.New("no enabled auto-installer plugin is available")
|
||||
}
|
||||
pid := strings.TrimSpace(pluginID)
|
||||
if pid == "" {
|
||||
return mgr, providers[0], nil
|
||||
}
|
||||
for _, p := range providers {
|
||||
if p.PluginID == pid {
|
||||
return mgr, p, nil
|
||||
}
|
||||
}
|
||||
return nil, AutoInstallerProviderView{}, fmt.Errorf("auto-installer plugin %q is not enabled", pid)
|
||||
}
|
||||
|
||||
func validatePluginSecretSetting(mgr *plugin.Manager, pluginID, settingKey string) error {
|
||||
settingKey = strings.TrimSpace(settingKey)
|
||||
if settingKey == "" {
|
||||
return fmt.Errorf("auto-installer plugin %q does not declare a secret_setting for password storage", pluginID)
|
||||
}
|
||||
if mgr == nil || mgr.Registry() == nil {
|
||||
return errors.New("plugin manager is unavailable")
|
||||
}
|
||||
info, ok := mgr.Registry().Info(pluginID)
|
||||
if !ok {
|
||||
return fmt.Errorf("auto-installer plugin %q is not registered", pluginID)
|
||||
}
|
||||
if info.Settings == nil {
|
||||
return fmt.Errorf("auto-installer plugin %q does not declare secret setting %q in its manifest", pluginID, settingKey)
|
||||
}
|
||||
prop, exists := info.Settings.Properties[settingKey]
|
||||
if !exists || !prop.Secret {
|
||||
return fmt.Errorf("auto-installer plugin %q setting %q is not declared as secret", pluginID, settingKey)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stambha can boot macOS, but cannot supply the guest console or installation phase.
|
||||
func validateAutoInstallDriver(driverID string) error {
|
||||
if driver.CanonicalDriverID(strings.TrimSpace(driverID)) == driver.BuiltinStambhaDriverID {
|
||||
return errors.New("automatic installation is unavailable for Stambha VMs")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isPrintableASCIIPassword(s string) bool {
|
||||
if len(s) < 4 || len(s) > 256 {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
if r < 0x20 || r > 0x7E {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// PreflightAutoInstall queries the enabled auto-installer plugin for local OCR
|
||||
// readiness and resumable checkpoint status.
|
||||
func (a *App) PreflightAutoInstall(pluginID, driverID, vmName, guestLang string) (map[string]any, error) {
|
||||
if err := validateAutoInstallDriver(driverID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mgr, provider, err := a.resolveAutoInstallerProvider(pluginID, "macos")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vmKeyStr := ""
|
||||
if strings.TrimSpace(vmName) != "" {
|
||||
vmKeyStr = vmKeyForDriver(driverID, vmName)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
var resp map[string]any
|
||||
err = mgr.CallSidecar(ctx, provider.PluginID, "autoinstall/preflight", map[string]any{
|
||||
"vm": vmKeyStr,
|
||||
"guest_lang": guestLang,
|
||||
}, &resp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp == nil {
|
||||
resp = map[string]any{}
|
||||
}
|
||||
resp["plugin_id"] = provider.PluginID
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// StartAutoInstall configures host session & authorization (plus optional DPAPI
|
||||
// account credentials and REIMSPROV provisioning in "full" mode), starts the VM
|
||||
// if requested, and launches the auto-installer's state machine with screen input lock.
|
||||
func (a *App) StartAutoInstall(req AutoInstallStartRequest) (map[string]any, error) {
|
||||
password := req.Password
|
||||
req.Password = ""
|
||||
defer func() { password = "" }()
|
||||
|
||||
mode := strings.ToLower(strings.TrimSpace(req.Mode))
|
||||
if mode == "" {
|
||||
if strings.TrimSpace(req.FullName) == "" && strings.TrimSpace(req.AccountName) == "" && password == "" {
|
||||
mode = "recovery_only"
|
||||
} else {
|
||||
mode = "full"
|
||||
}
|
||||
}
|
||||
if mode != "recovery_only" && mode != "full" {
|
||||
return nil, fmt.Errorf("unsupported auto-install mode %q", mode)
|
||||
}
|
||||
if !req.SLAAccepted {
|
||||
return nil, errors.New("explicit Apple SLA confirmation is required before starting auto-install")
|
||||
}
|
||||
if mode == "full" && !isPrintableASCIIPassword(password) {
|
||||
return nil, errors.New("password must be 4–256 printable ASCII characters")
|
||||
}
|
||||
vm, err := a.resolveVMInfo(req.DriverID, req.VMName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := validateAutoInstallDriver(vm.DriverID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
family := "macos"
|
||||
if vm.GuestOS != nil && vm.GuestOS.Family != "" {
|
||||
family = vm.GuestOS.Family
|
||||
}
|
||||
mgr, provider, err := a.resolveAutoInstallerProvider(req.PluginID, family)
|
||||
if err != nil {
|
||||
if vm.State == "running" {
|
||||
a.restoreManualInstallGuideFallback(vm.DriverID, vm.Name)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if broker := mgr.Broker(); broker != nil {
|
||||
for _, perm := range []string{"vm:read", "vm:screen", "qmp:write", "vm:control"} {
|
||||
if perr := broker.Authorize(provider.PluginID, perm); perr != nil {
|
||||
if vm.State == "running" {
|
||||
a.restoreManualInstallGuideFallback(vm.DriverID, vm.Name)
|
||||
}
|
||||
return nil, perr
|
||||
}
|
||||
}
|
||||
}
|
||||
vmKeyStr := vm.Ref().Key()
|
||||
secretSetting := ""
|
||||
if mode == "full" {
|
||||
secretSetting = strings.TrimSpace(provider.SecretSetting)
|
||||
if err := validatePluginSecretSetting(mgr, provider.PluginID, secretSetting); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Encrypt password straight into host DPAPI storage (never passed in RPC payload).
|
||||
if err := mgr.SetSettings(provider.PluginID, vmKeyStr, map[string]any{
|
||||
secretSetting: password,
|
||||
}); err != nil {
|
||||
return nil, fmt.Errorf("store DPAPI password: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Grant ephemeral per-VM console access and #105 protected-phase authorization
|
||||
// backed by the user's explicit host preflight confirmation, and lock VM input
|
||||
// against accidental physical mouse/keyboard interference while running.
|
||||
a.grantEphemeralVMAccess(provider.PluginID, vmKeyStr)
|
||||
phase := a.effectiveVMPhase(vm)
|
||||
if phase == driver.PhaseNormal {
|
||||
phase = driver.PhaseInstaller
|
||||
}
|
||||
a.grantProtectedPhase(provider.PluginID, vmKeyStr, phase, 0, true)
|
||||
a.beginAgentSession(mgr, provider.PluginID, vm, provider.Title, "stage0_preflight", "lock", true)
|
||||
a.setAgentSessionAutoInstallConfig(vmKeyStr, provider.PluginID, mode, secretSetting, mode == "full" && req.SaveUnlockCredential)
|
||||
|
||||
// Stage (or rebuild) per-VM REIMSPROV (hash-only offline provisioning disk)
|
||||
// before cold start in full mode so offline install always matches the latest
|
||||
// requested credentials and skips Setup Assistant & Keyboard Setup Assistant.
|
||||
if mode == "full" && family == "macos" && vm.Directory != "" && vm.State != "running" &&
|
||||
strings.TrimSpace(req.FullName) != "" && strings.TrimSpace(req.AccountName) != "" {
|
||||
if perr := a.prepareVMProvisionForDir(vm.Name, vm.Directory, ProvisionRequest{
|
||||
FullName: strings.TrimSpace(req.FullName),
|
||||
AccountName: strings.TrimSpace(req.AccountName),
|
||||
Password: password,
|
||||
Appearance: strings.TrimSpace(req.Appearance),
|
||||
SLAAccepted: req.SLAAccepted,
|
||||
InstallGuestTools: req.InstallGuestTools,
|
||||
}); perr != nil {
|
||||
a.emitVMLog(vm.Name, "Warning: REIMSPROV provisioning skipped (continuing with OCR fallback): "+perr.Error())
|
||||
}
|
||||
}
|
||||
|
||||
if req.StartVMIfStopped && vm.State != "running" {
|
||||
if err := a.StartVM(vm.DriverID, vm.Name); err != nil {
|
||||
if secretSetting != "" {
|
||||
_ = mgr.SetSettings(provider.PluginID, vmKeyStr, map[string]any{secretSetting: ""})
|
||||
}
|
||||
_ = a.StopAgentSession(vm.DriverID, vm.Name)
|
||||
return nil, fmt.Errorf("start VM for auto-install: %w", err)
|
||||
}
|
||||
// Ensure the protected-phase grant stays active after cold start even if
|
||||
// an early poll tick observed the VM stopped before QEMU launched.
|
||||
a.grantProtectedPhase(provider.PluginID, vmKeyStr, phase, 0, true)
|
||||
// Immediately bind the newly launched VM PID to the floating island and input shield.
|
||||
a.refreshActiveAgentSessionAfterStart(vmKeyStr)
|
||||
}
|
||||
|
||||
guestLang := strings.TrimSpace(req.GuestLang)
|
||||
if guestLang == "" {
|
||||
guestLang = vmInfoString(vm, "guest_lang")
|
||||
}
|
||||
if guestLang == "" {
|
||||
guestLang = "zh-Hans:0"
|
||||
}
|
||||
|
||||
payload := map[string]any{
|
||||
"vm": vmKeyStr,
|
||||
"mode": mode,
|
||||
"guest_lang": guestLang,
|
||||
"full_name": strings.TrimSpace(req.FullName),
|
||||
"account_name": strings.TrimSpace(req.AccountName),
|
||||
"secret_setting": secretSetting,
|
||||
"region": strings.TrimSpace(req.Region),
|
||||
"appearance": strings.TrimSpace(req.Appearance),
|
||||
"age_range": strings.TrimSpace(req.AgeRange),
|
||||
"sla_accepted": req.SLAAccepted,
|
||||
"save_unlock_credential": mode == "full" && req.SaveUnlockCredential,
|
||||
"ocr_backend": strings.TrimSpace(req.OCRBackend),
|
||||
"custom_ocr_mirror": strings.TrimSpace(req.CustomOCRMirror),
|
||||
"has_provision_disk": mode == "full" && a.hasVMProvisionDir(vm.Directory),
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
var resp map[string]any
|
||||
if err := mgr.CallSidecar(ctx, provider.PluginID, "autoinstall/start", payload, &resp); err != nil {
|
||||
if secretSetting != "" {
|
||||
_ = mgr.SetSettings(provider.PluginID, vmKeyStr, map[string]any{secretSetting: ""})
|
||||
}
|
||||
_ = a.StopAgentSession(vm.DriverID, vm.Name)
|
||||
return nil, err
|
||||
}
|
||||
if watchCtx, watchGen, ok := a.startAutoInstallSessionWatch(vmKeyStr, provider.PluginID); ok {
|
||||
go a.watchAutoInstallSession(watchCtx, watchGen, mgr, provider.PluginID, vmKeyStr, secretSetting, secretSetting != "" && !req.SaveUnlockCredential)
|
||||
}
|
||||
if resp == nil {
|
||||
resp = map[string]any{}
|
||||
}
|
||||
resp["plugin_id"] = provider.PluginID
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
var autoInstallWatchInterval = 3 * time.Second
|
||||
|
||||
// watchAutoInstallSession monitors an auto-install run so temporary DPAPI
|
||||
// credentials are cleared and any lingering host session (for example if an
|
||||
// external plugin exits or fails after permission denial without calling
|
||||
// host/session.end) is ended cleanly to restore the manual installation guide.
|
||||
func (a *App) watchAutoInstallSession(watchCtx context.Context, watchGen uint64, mgr *plugin.Manager, pluginID, vmKeyStr, secretSetting string, clearSecret bool) {
|
||||
ticker := time.NewTicker(autoInstallWatchInterval)
|
||||
defer ticker.Stop()
|
||||
timeout := time.NewTimer(2 * time.Hour)
|
||||
defer timeout.Stop()
|
||||
var watchDone <-chan struct{}
|
||||
if watchCtx != nil {
|
||||
watchDone = watchCtx.Done()
|
||||
}
|
||||
cleanupSecret := func(completed bool) {
|
||||
if secretSetting != "" && (clearSecret || !completed) {
|
||||
_ = mgr.SetSettings(pluginID, vmKeyStr, map[string]any{secretSetting: ""})
|
||||
}
|
||||
}
|
||||
consecutiveErrs := 0
|
||||
for {
|
||||
select {
|
||||
case <-watchDone:
|
||||
return
|
||||
case <-timeout.C:
|
||||
if !a.isCurrentAutoInstallSessionWatch(vmKeyStr, pluginID, watchGen) {
|
||||
return
|
||||
}
|
||||
cleanupSecret(false)
|
||||
a.revokeEphemeralVMAccess(pluginID, vmKeyStr)
|
||||
if a.isCurrentAutoInstallSessionWatch(vmKeyStr, pluginID, watchGen) {
|
||||
a.endAgentSession(mgr, pluginID, vmKeyStr, "timeout")
|
||||
}
|
||||
return
|
||||
case <-ticker.C:
|
||||
if !a.isCurrentAutoInstallSessionWatch(vmKeyStr, pluginID, watchGen) {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
var st struct {
|
||||
Status string `json:"status"`
|
||||
Stage string `json:"stage"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
err := mgr.CallSidecar(ctx, pluginID, "autoinstall/status", map[string]any{"vm": vmKeyStr}, &st)
|
||||
cancel()
|
||||
if !a.isCurrentAutoInstallSessionWatch(vmKeyStr, pluginID, watchGen) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
consecutiveErrs++
|
||||
if consecutiveErrs < 3 {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
consecutiveErrs = 0
|
||||
if st.Stage != "" || st.Message != "" {
|
||||
a.syncAutoInstallSessionProgress(vmKeyStr, pluginID, st.Stage, st.Message)
|
||||
}
|
||||
}
|
||||
if err != nil || st.Status == "completed" || st.Status == "stopped" || st.Status == "failed" || st.Status == "idle" {
|
||||
if !a.isCurrentAutoInstallSessionWatch(vmKeyStr, pluginID, watchGen) {
|
||||
return
|
||||
}
|
||||
completed := err == nil && st.Status == "completed"
|
||||
cleanupSecret(completed)
|
||||
a.revokeEphemeralVMAccess(pluginID, vmKeyStr)
|
||||
if a.isCurrentAutoInstallSessionWatch(vmKeyStr, pluginID, watchGen) {
|
||||
status := strings.TrimSpace(st.Status)
|
||||
if err != nil || status == "" || status == "idle" {
|
||||
status = "failed"
|
||||
}
|
||||
a.sessionMu.Lock()
|
||||
if sess := a.agentSessions[vmKeyStr]; sess != nil && sess.pluginID == pluginID && sess.watchGen == watchGen {
|
||||
sess.status = status
|
||||
if strings.TrimSpace(st.Message) != "" {
|
||||
sess.message = strings.TrimSpace(st.Message)
|
||||
}
|
||||
}
|
||||
a.sessionMu.Unlock()
|
||||
a.endAgentSession(mgr, pluginID, vmKeyStr, "autoinstall_"+status)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// listAutoInstallStatuses returns all live and persisted auto-install runs for
|
||||
// the selected provider (used by CLI control-pipe status queries without a VM).
|
||||
func (a *App) listAutoInstallStatuses(pluginID string) (map[string]any, error) {
|
||||
mgr, provider, err := a.resolveAutoInstallerProvider(pluginID, "macos")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
var resp map[string]any
|
||||
if err := mgr.CallSidecar(ctx, provider.PluginID, "autoinstall/status", map[string]any{"vm": ""}, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp == nil {
|
||||
resp = map[string]any{"runs": []any{}}
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// GetAutoInstallStatus queries the auto-installer plugin for one VM's progress.
|
||||
func (a *App) GetAutoInstallStatus(pluginID, driverID, vmName string) (map[string]any, error) {
|
||||
mgr, provider, err := a.resolveAutoInstallerProvider(pluginID, "macos")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
vmKeyStr := vmKeyForDriver(driverID, vmName)
|
||||
var resp map[string]any
|
||||
err = mgr.CallSidecar(ctx, provider.PluginID, "autoinstall/status", map[string]any{
|
||||
"vm": vmKeyStr,
|
||||
}, &resp)
|
||||
if err == nil && resp != nil {
|
||||
stage, _ := resp["stage"].(string)
|
||||
msg, _ := resp["message"].(string)
|
||||
if stage != "" {
|
||||
if existing, _ := resp["stage_label"].(string); existing == "" {
|
||||
if label := stageKnownName(a.computerUseLocale(), stage); label != "" {
|
||||
resp["stage_label"] = label
|
||||
}
|
||||
}
|
||||
}
|
||||
a.syncAutoInstallSessionProgress(vmKeyStr, provider.PluginID, stage, msg)
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func (a *App) autoInstallResumeVM(driverID, vmName string) (driver.VMInfo, error) {
|
||||
vm, err := a.resolveVMInfo(driverID, vmName)
|
||||
if err != nil {
|
||||
// An explicit driver can resume from its saved checkpoint. A bare
|
||||
// name must resolve before granting access to any particular VM.
|
||||
if strings.TrimSpace(driverID) == "" {
|
||||
return driver.VMInfo{}, err
|
||||
}
|
||||
ref := driver.NewVMRef(driverID, vmName)
|
||||
vm = driver.VMInfo{DriverID: ref.DriverID, Name: ref.Name}
|
||||
}
|
||||
return vm, validateAutoInstallDriver(vm.DriverID)
|
||||
}
|
||||
|
||||
// resumeAutoInstallFromControl handles `resume` requests arriving over the
|
||||
// local named-pipe control channel (e.g. `reims-go vm autoinstall resume`).
|
||||
// Because any same-user process (including an L3 sidecar plugin) can connect to
|
||||
// the named pipe, this path requires explicit desktop UI confirmation before
|
||||
// granting ephemeral VM access, protected-phase authorization, or clearing
|
||||
// host-initiated pauses.
|
||||
func (a *App) resumeAutoInstallFromControl(ctx context.Context, pluginID, driverID, vmName string) (map[string]any, error) {
|
||||
mgr, provider, err := a.resolveAutoInstallerProvider(pluginID, "macos")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if broker := mgr.Broker(); broker != nil {
|
||||
for _, perm := range []string{"vm:read", "vm:screen", "qmp:write", "vm:control"} {
|
||||
if perr := broker.Authorize(provider.PluginID, perm); perr != nil {
|
||||
return nil, perr
|
||||
}
|
||||
}
|
||||
}
|
||||
vmInfo, err := a.autoInstallResumeVM(driverID, vmName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
phase := a.effectiveVMPhase(vmInfo)
|
||||
if phase != driver.PhaseInstaller && phase != driver.PhaseRecovery {
|
||||
phase = driver.PhaseInstaller
|
||||
}
|
||||
prompt := a.buildProtectedPhasePrompt(provider.PluginID, vmInfo, phase, true)
|
||||
res, err := a.requestHostConfirm(ctx, mgr.Broker(), mgr.Registry(), provider.PluginID, prompt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !res.Approved {
|
||||
return nil, errors.New("confirmation_denied: user declined auto-install resume")
|
||||
}
|
||||
return a.ResumeAutoInstall(provider.PluginID, vmInfo.DriverID, vmInfo.Name)
|
||||
}
|
||||
|
||||
// ResumeAutoInstall resumes a paused_for_user or takeover-paused installation.
|
||||
func (a *App) ResumeAutoInstall(pluginID, driverID, vmName string) (map[string]any, error) {
|
||||
mgr, provider, err := a.resolveAutoInstallerProvider(pluginID, "macos")
|
||||
if err != nil {
|
||||
a.restoreManualInstallGuideFallback(driverID, vmName)
|
||||
return nil, err
|
||||
}
|
||||
resumeVM, err := a.autoInstallResumeVM(driverID, vmName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
driverID, vmName = resumeVM.DriverID, resumeVM.Name
|
||||
vmKeyStr := resumeVM.Ref().Key()
|
||||
if broker := mgr.Broker(); broker != nil {
|
||||
for _, perm := range []string{"vm:read", "vm:screen", "qmp:write", "vm:control"} {
|
||||
if perr := broker.Authorize(provider.PluginID, perm); perr != nil {
|
||||
a.handlePluginPermissionDeniedForVM(mgr, provider.PluginID, vmKeyStr, vmName, "permission_denied")
|
||||
return nil, perr
|
||||
}
|
||||
}
|
||||
}
|
||||
hadSession := a.hasActiveAgentSessionOwnedBy(vmKeyStr, provider.PluginID)
|
||||
a.grantEphemeralVMAccess(provider.PluginID, vmKeyStr)
|
||||
if !hadSession {
|
||||
phase := a.effectiveVMPhase(resumeVM)
|
||||
if phase == driver.PhaseNormal {
|
||||
phase = driver.PhaseInstaller
|
||||
}
|
||||
a.grantProtectedPhase(provider.PluginID, vmKeyStr, phase, 0, true)
|
||||
}
|
||||
_ = a.ResumeAgentSession(driverID, vmName)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
var resp map[string]any
|
||||
err = mgr.CallSidecar(ctx, provider.PluginID, "autoinstall/resume", map[string]any{
|
||||
"vm": vmKeyStr,
|
||||
}, &resp)
|
||||
if err != nil {
|
||||
if !hadSession {
|
||||
a.revokeEphemeralVMAccess(provider.PluginID, vmKeyStr)
|
||||
a.revokeProtectedPhaseForPluginVM(provider.PluginID, vmKeyStr, "resume_failed")
|
||||
}
|
||||
if !a.hasActiveAgentSession(vmKeyStr) {
|
||||
a.restoreManualInstallGuideFallback(driverID, vmName)
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
// If resuming restarted a runner from a persisted checkpoint (no prior live
|
||||
// session in memory), establish the host session with input-lock policy and
|
||||
// start the session watcher so temporary credentials and grants are always
|
||||
// cleaned up on completion.
|
||||
if !hadSession {
|
||||
saveUnlock, _ := resp["save_unlock_credential"].(bool)
|
||||
stage, _ := resp["stage"].(string)
|
||||
secretKey := strings.TrimSpace(provider.SecretSetting)
|
||||
if validatePluginSecretSetting(mgr, provider.PluginID, secretKey) != nil {
|
||||
secretKey = ""
|
||||
}
|
||||
if !a.hasActiveAgentSessionOwnedBy(vmKeyStr, provider.PluginID) {
|
||||
a.beginAgentSession(mgr, provider.PluginID, resumeVM, provider.Title, stage, "lock", true)
|
||||
}
|
||||
a.setAgentSessionAutoInstallConfig(vmKeyStr, provider.PluginID, "", secretKey, saveUnlock)
|
||||
if watchCtx, watchGen, ok := a.startAutoInstallSessionWatch(vmKeyStr, provider.PluginID); ok {
|
||||
go a.watchAutoInstallSession(watchCtx, watchGen, mgr, provider.PluginID, vmKeyStr, secretKey, !saveUnlock)
|
||||
}
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// StopAutoInstall aborts the active auto-install session, revokes authorization,
|
||||
// and clears the temporary DPAPI password setting.
|
||||
func (a *App) StopAutoInstall(pluginID, driverID, vmName string) error {
|
||||
_ = a.StopAgentSession(driverID, vmName)
|
||||
mgr, provider, err := a.resolveAutoInstallerProvider(pluginID, "macos")
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
vmKeyStr := vmKeyForDriver(driverID, vmName)
|
||||
secretSetting := strings.TrimSpace(provider.SecretSetting)
|
||||
if validatePluginSecretSetting(mgr, provider.PluginID, secretSetting) == nil {
|
||||
_ = mgr.SetSettings(provider.PluginID, vmKeyStr, map[string]any{secretSetting: ""})
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = mgr.CallSidecar(ctx, provider.PluginID, "autoinstall/stop", map[string]any{"vm": vmKeyStr}, nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAutoInstallDiagnosticSummary returns a redacted unknown-page/error summary
|
||||
// safe for the user to copy and share without exposing names, passwords, or images.
|
||||
func (a *App) GetAutoInstallDiagnosticSummary(pluginID, driverID, vmName string) (map[string]any, error) {
|
||||
mgr, provider, err := a.resolveAutoInstallerProvider(pluginID, "macos")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
var resp map[string]any
|
||||
err = mgr.CallSidecar(ctx, provider.PluginID, "autoinstall/diagnosticSummary", map[string]any{
|
||||
"vm": vmKeyForDriver(driverID, vmName),
|
||||
}, &resp)
|
||||
return resp, err
|
||||
}
|
||||
|
||||
// DownloadAutoInstallOCR asks the auto-installer plugin to download RapidOCR ONNX fallback assets.
|
||||
func (a *App) DownloadAutoInstallOCR(pluginID, customMirror string) (map[string]any, error) {
|
||||
mgr, provider, err := a.resolveAutoInstallerProvider(pluginID, "macos")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
|
||||
defer cancel()
|
||||
var resp map[string]any
|
||||
err = mgr.CallSidecar(ctx, provider.PluginID, "autoinstall/downloadOCR", map[string]any{
|
||||
"custom_mirror": strings.TrimSpace(customMirror),
|
||||
}, &resp)
|
||||
return resp, err
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
)
|
||||
|
||||
func TestListAutoInstallersZeroResidueWhenDisabled(t *testing.T) {
|
||||
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}}
|
||||
mgr, err := plugin.NewManager(plugin.ManagerOptions{
|
||||
DataRoot: a.cfg.DataRoot,
|
||||
HostVersion: "0.3.0",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer mgr.Close()
|
||||
a.pluginMgr = mgr
|
||||
|
||||
// Register a mock auto-installer plugin.
|
||||
if err := mgr.Registry().Register(plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: "test.autoinstall",
|
||||
Version: "1.0.0",
|
||||
Name: plugin.LocalizedText{EnUS: "Test AutoInstall"},
|
||||
Entry: plugin.Entry{Sidecar: "bin/auto.exe"},
|
||||
Contributes: plugin.Contributes{
|
||||
AutoInstallers: []plugin.AutoInstallerContribution{{
|
||||
ID: "macos-local",
|
||||
Title: plugin.LocalizedText{EnUS: "macOS Auto-Install"},
|
||||
GuestFamilies: []string{"macos"},
|
||||
RequiresOfflineInstaller: true,
|
||||
}},
|
||||
},
|
||||
},
|
||||
Source: plugin.SourceDevLink,
|
||||
Trust: plugin.TrustDev,
|
||||
Desired: true,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr.Registry().Reconcile(t.Context())
|
||||
|
||||
got := a.ListAutoInstallers("macos")
|
||||
if len(got) != 1 || got[0].PluginID != "test.autoinstall" || got[0].SecretSetting != "account_password" {
|
||||
t.Fatalf("expected 1 enabled macOS auto-installer, got %+v", got)
|
||||
}
|
||||
if len(a.ListAutoInstallers("linux")) != 0 {
|
||||
t.Fatal("macOS-only auto-installer must not match linux family")
|
||||
}
|
||||
|
||||
// Disabling the plugin removes the contribution with zero residue.
|
||||
if err := mgr.Registry().SetDesired(t.Context(), "test.autoinstall", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr.Registry().Reconcile(t.Context())
|
||||
if len(a.ListAutoInstallers("macos")) != 0 {
|
||||
t.Fatal("disabled auto-installer must leave zero providers")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuiltinAutoInstallDefaultEnabledAndDisableCleansSession(t *testing.T) {
|
||||
dataRoot := t.TempDir()
|
||||
cfg := config.Default()
|
||||
cfg.DataRoot = dataRoot
|
||||
a := &App{cfg: cfg, pollWake: make(chan struct{}, 1)}
|
||||
|
||||
var mgr *plugin.Manager
|
||||
var err error
|
||||
mgr, err = plugin.NewManager(plugin.ManagerOptions{
|
||||
DataRoot: dataRoot,
|
||||
HostVersion: "0.3.0",
|
||||
HostHandlers: func(pluginID string) map[string]plugin.RPCRequestHandler {
|
||||
return a.hostAPISvc().Handlers(mgr, pluginID)
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer mgr.Close()
|
||||
a.pluginMgr = mgr
|
||||
|
||||
cb := builtin.HostCallbacks{
|
||||
GetConfig: func() config.Config { return *cfg },
|
||||
GetSetting: func(pluginID, vmName, key string) (any, bool) {
|
||||
v, ok := mgr.GetSettings(pluginID, vmName, false)[key]
|
||||
return v, ok
|
||||
},
|
||||
PluginDataDir: mgr.Layout().DataDir,
|
||||
PluginLogPath: mgr.Layout().LogPath,
|
||||
CallHostAPI: mgr.CallHostAPI,
|
||||
}
|
||||
if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr.Registry().OnChange(func() {
|
||||
a.stopAgentSessionsForInactivePlugins(mgr)
|
||||
})
|
||||
mgr.Registry().Reconcile(context.Background())
|
||||
|
||||
// Official built-in auto-installer must be enabled and discoverable by default.
|
||||
providers := a.ListAutoInstallers("macos")
|
||||
if len(providers) != 1 || providers[0].PluginID != guest.IDAutoInstall {
|
||||
t.Fatalf("expected default-enabled %s, got %+v", guest.IDAutoInstall, providers)
|
||||
}
|
||||
if err := mgr.Broker().Authorize(guest.IDAutoInstall, "qmp:write"); err != nil {
|
||||
t.Fatalf("official built-in auto-install plugin must hold qmp:write for DPAPI secret typing: %v", err)
|
||||
}
|
||||
|
||||
// Preflight, status, diagnosticSummary, and DPAPI secret storage all work out of the box.
|
||||
pf, err := a.PreflightAutoInstall("", driver.BuiltinReimsMacOSDriverID, "demo", "zh-Hans:0")
|
||||
if err != nil {
|
||||
t.Fatalf("PreflightAutoInstall: %v", err)
|
||||
}
|
||||
if pf["plugin_id"] != guest.IDAutoInstall {
|
||||
t.Fatalf("unexpected preflight response: %+v", pf)
|
||||
}
|
||||
st, err := a.GetAutoInstallStatus("", driver.BuiltinReimsMacOSDriverID, "demo")
|
||||
if err != nil {
|
||||
t.Fatalf("GetAutoInstallStatus: %v", err)
|
||||
}
|
||||
if st["status"] != "idle" {
|
||||
t.Fatalf("expected idle status, got %+v", st)
|
||||
}
|
||||
diag, err := a.GetAutoInstallDiagnosticSummary("", driver.BuiltinReimsMacOSDriverID, "demo")
|
||||
if err != nil {
|
||||
t.Fatalf("GetAutoInstallDiagnosticSummary: %v", err)
|
||||
}
|
||||
if diag["status"] != "idle" {
|
||||
t.Fatalf("expected idle diagnostic summary, got %+v", diag)
|
||||
}
|
||||
|
||||
vmKey := vmKeyForDriver(driver.BuiltinReimsMacOSDriverID, "demo")
|
||||
if err := mgr.SetSettings(guest.IDAutoInstall, vmKey, map[string]any{"account_password": "TestPass123"}); err != nil {
|
||||
t.Fatalf("SetSettings secret: %v", err)
|
||||
}
|
||||
secret, err := mgr.SecretSetting(guest.IDAutoInstall, vmKey, "account_password")
|
||||
if err != nil || secret != "TestPass123" {
|
||||
t.Fatalf("SecretSetting = %q, %v", secret, err)
|
||||
}
|
||||
|
||||
// Simulate an active session owned by the built-in auto-install plugin and
|
||||
// verify disabling the plugin stops the session and removes all providers.
|
||||
a.grantEphemeralVMAccess(guest.IDAutoInstall, vmKey)
|
||||
a.grantProtectedPhase(guest.IDAutoInstall, vmKey, driver.PhaseInstaller, 0, true)
|
||||
a.beginAgentSession(mgr, guest.IDAutoInstall, driver.VMInfo{
|
||||
DriverID: driver.BuiltinReimsMacOSDriverID,
|
||||
Name: "demo",
|
||||
}, "Auto-Install", "stage1_boot_recovery", "lock", true)
|
||||
if !a.hasActiveAgentSession(vmKey) {
|
||||
t.Fatal("expected active agent session before disable")
|
||||
}
|
||||
|
||||
if err := mgr.Disable(context.Background(), guest.IDAutoInstall); err != nil {
|
||||
t.Fatalf("Disable builtin auto-install: %v", err)
|
||||
}
|
||||
if len(a.ListAutoInstallers("macos")) != 0 {
|
||||
t.Fatal("expected zero auto-installers after disabling builtin plugin")
|
||||
}
|
||||
if a.hasActiveAgentSession(vmKey) {
|
||||
t.Fatal("expected active agent session to be torn down when plugin is disabled")
|
||||
}
|
||||
if _, ok := a.lookupProtectedPhaseGrant(guest.IDAutoInstall, vmKey); ok {
|
||||
t.Fatal("expected protected-phase grant to be revoked when plugin is disabled")
|
||||
}
|
||||
|
||||
// Re-enabling restores the built-in provider cleanly.
|
||||
if err := mgr.Enable(context.Background(), guest.IDAutoInstall, false); err != nil {
|
||||
t.Fatalf("Enable builtin auto-install: %v", err)
|
||||
}
|
||||
providers = a.ListAutoInstallers("macos")
|
||||
if len(providers) != 1 || providers[0].PluginID != guest.IDAutoInstall {
|
||||
t.Fatalf("expected %s restored after enable, got %+v", guest.IDAutoInstall, providers)
|
||||
}
|
||||
|
||||
// Disabling the plugin must also clear any retained completed overlay (zero residue).
|
||||
a.sessionMu.Lock()
|
||||
a.completedOverlays = map[string]completedOverlayEntry{
|
||||
vmKey: {pluginID: guest.IDAutoInstall, driverID: driver.BuiltinReimsMacOSDriverID, vmName: "demo", pid: 4242},
|
||||
}
|
||||
a.sessionMu.Unlock()
|
||||
if err := mgr.Disable(context.Background(), guest.IDAutoInstall); err != nil {
|
||||
t.Fatalf("Disable builtin auto-install (completed overlay cleanup): %v", err)
|
||||
}
|
||||
if a.isCompletedOverlay(vmKey) {
|
||||
t.Fatal("expected completed overlay to be cleared when owning plugin is disabled")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/control"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
func newHardeningTestApp(t *testing.T, vms ...driver.VMInfo) (*App, *plugin.Manager, string) {
|
||||
t.Helper()
|
||||
dataRoot := t.TempDir()
|
||||
mgr := newR3TestManager(t, dataRoot)
|
||||
drvReg := plugin.NewRegistry(nil)
|
||||
stubDrv := &stubMultiVMMacOSDriver{vms: vms}
|
||||
if err := drvReg.Register(plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: "test.macos.driver.hardening",
|
||||
Version: "1.0.0",
|
||||
Name: plugin.LocalizedText{EnUS: "macOS Stub"},
|
||||
},
|
||||
Source: plugin.SourceBuiltin,
|
||||
Trust: plugin.TrustOfficial,
|
||||
Desired: true,
|
||||
Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
sc.Registry().RegisterGuestDriver(sc, driver.BuiltinReimsMacOSDriverID, stubDrv)
|
||||
return nil
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
drvReg.Reconcile(context.Background())
|
||||
router := driver.NewRouter(drvReg, func() string { return dataRoot })
|
||||
stateTable := driver.NewStateTable()
|
||||
router.SetStateTable(stateTable)
|
||||
a := &App{
|
||||
cfg: &config.Config{DataRoot: dataRoot},
|
||||
pluginMgr: mgr,
|
||||
driverRouter: router,
|
||||
vmStateTable: stateTable,
|
||||
lifecycleSvc: vmlifecycle.New(drvReg, router, nil),
|
||||
}
|
||||
return a, mgr, dataRoot
|
||||
}
|
||||
|
||||
func registerTestPluginWithPerms(t *testing.T, mgr *plugin.Manager, id string, perms []string, autoInstaller bool) {
|
||||
t.Helper()
|
||||
m := plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: id,
|
||||
Version: "1.0.0",
|
||||
Name: plugin.LocalizedText{EnUS: id},
|
||||
Permissions: perms,
|
||||
}
|
||||
if autoInstaller {
|
||||
m.Contributes.AutoInstallers = []plugin.AutoInstallerContribution{
|
||||
{
|
||||
ID: "auto",
|
||||
Title: plugin.LocalizedText{EnUS: "Auto"},
|
||||
GuestFamilies: []string{"macos"},
|
||||
},
|
||||
}
|
||||
}
|
||||
if err := mgr.Registry().Register(plugin.PluginDef{
|
||||
Manifest: m,
|
||||
Source: plugin.SourceBuiltin,
|
||||
Trust: plugin.TrustOfficial,
|
||||
Desired: true,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr.Registry().Reconcile(context.Background())
|
||||
}
|
||||
|
||||
func TestHostUIConfirmCannotSpoofProtectedPhasePromptOrCrossPhase(t *testing.T) {
|
||||
vm := driver.VMInfo{
|
||||
DriverID: driver.BuiltinReimsMacOSDriverID,
|
||||
Name: "tahoe-confirm",
|
||||
State: "running",
|
||||
Phase: driver.PhaseInstaller,
|
||||
}
|
||||
a, mgr, _ := newHardeningTestApp(t, vm)
|
||||
const pid = "test.plugin.spoof"
|
||||
registerTestPluginWithPerms(t, mgr, pid, []string{"ui:notify", "vm:read", "vm:screen"}, false)
|
||||
|
||||
var seen ConfirmPrompt
|
||||
a.confirmEmit = func(p ConfirmPrompt) {
|
||||
seen = p
|
||||
go func() { _ = a.ResolveConfirmRequest(p.ID, true, 30, false) }()
|
||||
}
|
||||
|
||||
rawReq, _ := json.Marshal(map[string]any{
|
||||
"vm": vm.Ref().Key(),
|
||||
"protected_phase": driver.PhaseInstaller,
|
||||
"title": "Totally Harmless Update",
|
||||
"message": "Click OK to continue",
|
||||
"confirm_label": "OK",
|
||||
"danger": false,
|
||||
})
|
||||
handlers := a.hostAPISvc().Handlers(mgr, pid)
|
||||
if _, err := handlers["host/ui.confirm"](context.Background(), rawReq); err != nil {
|
||||
t.Fatalf("host/ui.confirm returned error: %v", err)
|
||||
}
|
||||
if !seen.Danger {
|
||||
t.Fatal("protected_phase confirmation must force Danger=true")
|
||||
}
|
||||
if seen.Title == "Totally Harmless Update" || seen.Message == "Click OK to continue" {
|
||||
t.Fatalf("protected_phase confirmation allowed spoofed title/message: %+v", seen)
|
||||
}
|
||||
|
||||
// An installer-phase grant must NOT authorize recovery phase.
|
||||
if err := a.authorizeProtectedPhase(context.Background(), mgr, pid, vm, driver.PhaseInstaller, false, false); err != nil {
|
||||
t.Fatalf("installer grant should be active for installer phase: %v", err)
|
||||
}
|
||||
a.confirmEmit = func(p ConfirmPrompt) {
|
||||
go func() { _ = a.ResolveConfirmRequest(p.ID, false, 0, false) }()
|
||||
}
|
||||
if err := a.authorizeProtectedPhase(context.Background(), mgr, pid, vm, driver.PhaseRecovery, false, false); err == nil || !strings.Contains(err.Error(), "confirmation_required") {
|
||||
t.Fatalf("installer grant must not authorize recovery phase; got err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestControlAutoInstallRejectsMissingDataRootAndRequiresConfirmForResume(t *testing.T) {
|
||||
vm := driver.VMInfo{
|
||||
DriverID: driver.BuiltinReimsMacOSDriverID,
|
||||
Name: "tahoe-pipe",
|
||||
State: "running",
|
||||
Phase: driver.PhaseInstaller,
|
||||
}
|
||||
a, mgr, dataRoot := newHardeningTestApp(t, vm)
|
||||
const pid = "test.plugin.autoinstall"
|
||||
registerTestPluginWithPerms(t, mgr, pid, []string{"vm:read", "vm:screen", "qmp:write", "vm:control"}, true)
|
||||
|
||||
// 1. Missing data_root must be rejected when desktop app has a DataRoot configured.
|
||||
rawNoRoot, _ := json.Marshal(control.AutoInstallRequest{
|
||||
Action: "resume",
|
||||
PluginID: pid,
|
||||
DriverID: vm.DriverID,
|
||||
VMName: vm.Name,
|
||||
})
|
||||
if _, err := a.handleControlAutoInstall(context.Background(), rawNoRoot); err == nil || !strings.Contains(err.Error(), "data_root_mismatch") {
|
||||
t.Fatalf("expected data_root_mismatch when data_root omitted, got %v", err)
|
||||
}
|
||||
|
||||
// 2. Named-pipe resume must require desktop confirmation and never silently
|
||||
// grant ephemeral/protected-phase access or clear hostPaused when denied.
|
||||
a.beginAgentSession(mgr, pid, vm, "Auto", "stage1", "lock", true)
|
||||
if err := a.PauseAgentSession(vm.DriverID, vm.Name); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prompted := false
|
||||
a.confirmEmit = func(p ConfirmPrompt) {
|
||||
prompted = true
|
||||
go func() { _ = a.ResolveConfirmRequest(p.ID, false, 0, false) }()
|
||||
}
|
||||
rawResume, _ := json.Marshal(control.AutoInstallRequest{
|
||||
Action: "resume",
|
||||
DataRoot: dataRoot,
|
||||
PluginID: pid,
|
||||
DriverID: vm.DriverID,
|
||||
VMName: vm.Name,
|
||||
})
|
||||
if _, err := a.handleControlAutoInstall(context.Background(), rawResume); err == nil || !strings.Contains(err.Error(), "confirmation_denied") {
|
||||
t.Fatalf("expected confirmation_denied on denied control resume, got %v", err)
|
||||
}
|
||||
if !prompted {
|
||||
t.Fatal("expected control resume to prompt user in desktop UI")
|
||||
}
|
||||
if _, ok := a.lookupProtectedPhaseGrant(pid, vm.Ref().Key()); ok {
|
||||
t.Fatal("denied control resume must not mint protected-phase grant")
|
||||
}
|
||||
a.sessionMu.Lock()
|
||||
sess := a.agentSessions[vm.Ref().Key()]
|
||||
stillHostPaused := sess != nil && sess.hostPaused && sess.pausedForUser
|
||||
a.sessionMu.Unlock()
|
||||
if !stillHostPaused {
|
||||
t.Fatal("denied control resume must preserve hostPaused state")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDisablePluginRevokesProtectedPhaseGrantWithoutSession(t *testing.T) {
|
||||
vm := driver.VMInfo{
|
||||
DriverID: driver.BuiltinReimsMacOSDriverID,
|
||||
Name: "tahoe-readonly-grant",
|
||||
State: "running",
|
||||
Phase: driver.PhaseInstaller,
|
||||
}
|
||||
a, mgr, _ := newHardeningTestApp(t, vm)
|
||||
const pid = "test.plugin.readonly"
|
||||
registerTestPluginWithPerms(t, mgr, pid, []string{"vm:read", "vm:screen"}, false)
|
||||
|
||||
a.grantProtectedPhase(pid, vm.Ref().Key(), driver.PhaseInstaller, 30, false)
|
||||
if _, ok := a.lookupProtectedPhaseGrant(pid, vm.Ref().Key()); !ok {
|
||||
t.Fatal("expected grant to be recorded")
|
||||
}
|
||||
|
||||
// Disable plugin (no active agentSession exists) and reconcile.
|
||||
if err := mgr.Registry().SetDesired(context.Background(), pid, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr.Registry().Reconcile(context.Background())
|
||||
a.stopAgentSessionsForInactivePlugins(mgr)
|
||||
|
||||
if _, ok := a.lookupProtectedPhaseGrant(pid, vm.Ref().Key()); ok {
|
||||
t.Fatal("disabling plugin must revoke protected-phase grant even without an active agentSession")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBeginAgentSessionReplacementCleansPreviousPluginState(t *testing.T) {
|
||||
vm := driver.VMInfo{
|
||||
DriverID: driver.BuiltinReimsMacOSDriverID,
|
||||
Name: "tahoe-replace",
|
||||
State: "running",
|
||||
Phase: driver.PhaseInstaller,
|
||||
}
|
||||
a, mgr, _ := newHardeningTestApp(t, vm)
|
||||
const pidA = "test.plugin.a"
|
||||
const pidB = "test.plugin.b"
|
||||
registerTestPluginWithPerms(t, mgr, pidA, []string{"vm:read", "qmp:write"}, false)
|
||||
registerTestPluginWithPerms(t, mgr, pidB, []string{"vm:read", "qmp:write"}, false)
|
||||
|
||||
a.grantEphemeralVMAccess(pidA, vm.Ref().Key())
|
||||
a.grantProtectedPhase(pidA, vm.Ref().Key(), driver.PhaseInstaller, 30, false)
|
||||
a.beginAgentSession(mgr, pidA, vm, "Plugin A", "stage1", "lock", true)
|
||||
|
||||
a.beginAgentSession(mgr, pidB, vm, "Plugin B", "stage2", "auto", false)
|
||||
|
||||
if a.hasEphemeralVMAccess(pidA, vm.Ref().Key()) {
|
||||
t.Fatal("replacing session must revoke previous plugin's ephemeral VM access")
|
||||
}
|
||||
if _, ok := a.lookupProtectedPhaseGrant(pidA, vm.Ref().Key()); ok {
|
||||
t.Fatal("replacing session must revoke previous plugin's protected-phase grant")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVMRestartAndFinishInstallEnforceTakeoverAndProtectedPhase(t *testing.T) {
|
||||
vm := driver.VMInfo{
|
||||
DriverID: driver.BuiltinReimsMacOSDriverID,
|
||||
Name: "tahoe-restart-guard",
|
||||
State: "running",
|
||||
Phase: driver.PhaseInstaller,
|
||||
}
|
||||
a, mgr, _ := newHardeningTestApp(t, vm)
|
||||
const pid = "test.plugin.restart"
|
||||
registerTestPluginWithPerms(t, mgr, pid, []string{"vm:read", "vm:control"}, false)
|
||||
a.grantEphemeralVMAccess(pid, vm.Ref().Key())
|
||||
|
||||
prompted := make(chan struct{}, 1)
|
||||
a.confirmEmit = func(p ConfirmPrompt) {
|
||||
select {
|
||||
case prompted <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
go func() { _ = a.ResolveConfirmRequest(p.ID, false, 0, false) }()
|
||||
}
|
||||
rawVM, _ := json.Marshal(map[string]any{"vm": vm.Ref().Key()})
|
||||
|
||||
// 1. Without protected-phase grant, host/vm.restart must be blocked in installer phase.
|
||||
if _, err := a.handleComputerUseVMRestart(context.Background(), rawVM, mgr, pid); err == nil || !strings.Contains(err.Error(), "confirmation_required") {
|
||||
t.Fatalf("expected confirmation_required on host/vm.restart in installer phase, got %v", err)
|
||||
}
|
||||
<-prompted
|
||||
// Wait for the async denial goroutine to settle before step 2.
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
a.confirmMu.Lock()
|
||||
inFlight := a.protectedPhaseInFlight[phaseGrantKey{pluginID: pid, vmKey: vm.Ref().Key()}]
|
||||
a.confirmMu.Unlock()
|
||||
if !inFlight {
|
||||
break
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
|
||||
// 2. While host-paused/taken over, both restart and finishInstall must be blocked.
|
||||
a.grantEphemeralVMAccess(pid, vm.Ref().Key())
|
||||
a.grantProtectedPhase(pid, vm.Ref().Key(), driver.PhaseInstaller, 30, false)
|
||||
a.beginAgentSession(mgr, pid, vm, "Test", "stage1", "auto", false)
|
||||
a.sessionMu.Lock()
|
||||
a.agentSessions[vm.Ref().Key()].takeoverPaused = true
|
||||
a.agentSessions[vm.Ref().Key()].takeoverUntil = time.Now().Add(30 * time.Second)
|
||||
a.sessionMu.Unlock()
|
||||
|
||||
if _, err := a.handleComputerUseVMRestart(context.Background(), rawVM, mgr, pid); err == nil || !strings.Contains(err.Error(), "user_takeover") {
|
||||
t.Fatalf("expected user_takeover on host/vm.restart during takeover, got %v", err)
|
||||
}
|
||||
if _, err := a.handleComputerUseVMFinishInstall(context.Background(), rawVM, mgr, pid); err == nil || !strings.Contains(err.Error(), "user_takeover") {
|
||||
t.Fatalf("expected user_takeover on host/vm.finishInstall during takeover, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type phaseErrorDriver struct {
|
||||
stubMultiVMMacOSDriver
|
||||
phaseErr error
|
||||
}
|
||||
|
||||
type stambhaAutomationTestDriver struct{ stubMultiVMMacOSDriver }
|
||||
|
||||
func (*stambhaAutomationTestDriver) ID() string { return driver.BuiltinStambhaDriverID }
|
||||
|
||||
func TestStambhaAutomationRequiresSupportedConsoleAndKnownPhase(t *testing.T) {
|
||||
vm := driver.VMInfo{
|
||||
DriverID: driver.BuiltinStambhaDriverID, Name: "arm-guest", State: "running",
|
||||
Capabilities: []string{"guest.arm64"}, DriverData: map[string]any{"usb_image": "boot.raw"},
|
||||
}
|
||||
a, mgr, dataRoot := newHardeningTestApp(t)
|
||||
drv := &stambhaAutomationTestDriver{stubMultiVMMacOSDriver{vms: []driver.VMInfo{vm}}}
|
||||
reg := mgr.Registry()
|
||||
if err := reg.Register(plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{Schema: 1, ID: "test.stambha", Version: "1.0.0", Name: plugin.LocalizedText{EnUS: "Stambha"}},
|
||||
Source: plugin.SourceBuiltin, Trust: plugin.TrustOfficial, Desired: true,
|
||||
Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
sc.Registry().RegisterGuestDriver(sc, drv.ID(), drv)
|
||||
return nil
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const pid = "test.plugin.stambha"
|
||||
registerTestPluginWithPerms(t, mgr, pid, []string{"vm:read", "vm:screen", "qmp:write", "vm:control"}, true)
|
||||
a.driverRouter = driver.NewRouter(reg, func() string { return dataRoot })
|
||||
a.driverRouter.SetStateTable(a.vmStateTable)
|
||||
a.lifecycleSvc = vmlifecycle.New(reg, a.driverRouter, nil)
|
||||
a.confirmEmit = func(p ConfirmPrompt) {
|
||||
t.Error("unsupported auto-install requested confirmation")
|
||||
go func() { _ = a.ResolveConfirmRequest(p.ID, false, 0, false) }()
|
||||
}
|
||||
|
||||
assertUnavailable := func(err error) {
|
||||
t.Helper()
|
||||
if err == nil || !strings.Contains(err.Error(), "unavailable for Stambha") {
|
||||
t.Fatalf("want unsupported auto-install, got %v", err)
|
||||
}
|
||||
}
|
||||
_, err := a.PreflightAutoInstall(pid, vm.DriverID, vm.Name, "")
|
||||
assertUnavailable(err)
|
||||
for _, id := range []string{vm.DriverID, ""} {
|
||||
_, err = a.StartAutoInstall(AutoInstallStartRequest{
|
||||
PluginID: pid, DriverID: id, VMName: vm.Name, Mode: "full", SLAAccepted: true, Password: "test-password",
|
||||
})
|
||||
assertUnavailable(err)
|
||||
_, err = a.ResumeAutoInstall(pid, id, vm.Name)
|
||||
assertUnavailable(err)
|
||||
_, err = a.resumeAutoInstallFromControl(t.Context(), pid, id, vm.Name)
|
||||
assertUnavailable(err)
|
||||
}
|
||||
key := vm.Ref().Key()
|
||||
if a.hasEphemeralVMAccess(pid, key) || a.hasActiveAgentSession(key) {
|
||||
t.Fatal("unsupported installation granted access or started a session")
|
||||
}
|
||||
if _, ok := a.lookupProtectedPhaseGrant(pid, key); ok {
|
||||
t.Fatal("unsupported installation granted protected-phase access")
|
||||
}
|
||||
a.grantEphemeralVMAccess(pid, key)
|
||||
raw, _ := json.Marshal(map[string]any{"vm": key})
|
||||
for _, handler := range []computerUseVMHandler{a.handleComputerUseVMRestart, a.handleComputerUseVMFinishInstall} {
|
||||
if _, err := handler(t.Context(), raw, mgr, pid); err == nil || !strings.Contains(err.Error(), "installation phase") {
|
||||
t.Fatalf("want unknown installation phase, got %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (d *phaseErrorDriver) Phase(_ context.Context, _ string) (string, error) {
|
||||
return "", d.phaseErr
|
||||
}
|
||||
|
||||
func TestEffectiveVMPhaseStrictAllowsMethodNotFoundAndFailsClosedOnOtherErrors(t *testing.T) {
|
||||
vm := driver.VMInfo{
|
||||
DriverID: driver.BuiltinReimsMacOSDriverID,
|
||||
Name: "sidecar-vm",
|
||||
State: "running",
|
||||
}
|
||||
makeApp := func(phaseErr error) *App {
|
||||
dataRoot := t.TempDir()
|
||||
drvReg := plugin.NewRegistry(nil)
|
||||
stub := &phaseErrorDriver{
|
||||
stubMultiVMMacOSDriver: stubMultiVMMacOSDriver{vms: []driver.VMInfo{vm}},
|
||||
phaseErr: phaseErr,
|
||||
}
|
||||
if err := drvReg.Register(plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: "test.macos.driver.phaseerr",
|
||||
Version: "1.0.0",
|
||||
Name: plugin.LocalizedText{EnUS: "Phase Err Driver"},
|
||||
},
|
||||
Source: plugin.SourceBuiltin,
|
||||
Trust: plugin.TrustOfficial,
|
||||
Desired: true,
|
||||
Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
sc.Registry().RegisterGuestDriver(sc, driver.BuiltinReimsMacOSDriverID, stub)
|
||||
return nil
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
drvReg.Reconcile(context.Background())
|
||||
return &App{driverRouter: driver.NewRouter(drvReg, func() string { return dataRoot })}
|
||||
}
|
||||
|
||||
// Older sidecar without driver/phase (RPCMethodNotFound) must fall back to normal.
|
||||
a1 := makeApp(&plugin.RPCError{Code: plugin.RPCMethodNotFound, Message: "method not found"})
|
||||
phase, err := a1.effectiveVMPhaseStrict(vm)
|
||||
if err != nil || phase != driver.PhaseNormal {
|
||||
t.Fatalf("RPCMethodNotFound: got (%q, %v), want (%q, nil)", phase, err, driver.PhaseNormal)
|
||||
}
|
||||
|
||||
// Real/transient error must fail closed.
|
||||
a2 := makeApp(context.DeadlineExceeded)
|
||||
if _, err := a2.effectiveVMPhaseStrict(vm); err == nil {
|
||||
t.Fatal("expected effectiveVMPhaseStrict to fail closed on transient error")
|
||||
}
|
||||
}
|
||||
@@ -44,8 +44,8 @@ type heldInputs struct {
|
||||
// noteHeldKey records or forgets one key transition. code must already be a
|
||||
// QKeyCode.
|
||||
func (a *App) noteHeldKey(pluginID, vmKey, code string, down bool) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
held := a.heldLocked(pluginID, vmKey)
|
||||
if down {
|
||||
held.keys[code] = true
|
||||
@@ -57,8 +57,8 @@ func (a *App) noteHeldKey(pluginID, vmKey, code string, down bool) {
|
||||
|
||||
// noteHeldButton records or forgets one pointer button transition.
|
||||
func (a *App) noteHeldButton(pluginID, vmKey, button string, down bool) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
held := a.heldLocked(pluginID, vmKey)
|
||||
if down {
|
||||
held.buttons[button] = true
|
||||
@@ -71,13 +71,13 @@ func (a *App) noteHeldButton(pluginID, vmKey, button string, down bool) {
|
||||
// heldLocked returns the record for one plugin and VM, creating it when
|
||||
// needed. The caller holds computerUseHeldMu.
|
||||
func (a *App) heldLocked(pluginID, vmKey string) *heldInputs {
|
||||
if a.computerUseHeld == nil {
|
||||
a.computerUseHeld = map[string]map[string]*heldInputs{}
|
||||
if a.hostAPI.computerUseHeld == nil {
|
||||
a.hostAPI.computerUseHeld = map[string]map[string]*heldInputs{}
|
||||
}
|
||||
byVM := a.computerUseHeld[pluginID]
|
||||
byVM := a.hostAPI.computerUseHeld[pluginID]
|
||||
if byVM == nil {
|
||||
byVM = map[string]*heldInputs{}
|
||||
a.computerUseHeld[pluginID] = byVM
|
||||
a.hostAPI.computerUseHeld[pluginID] = byVM
|
||||
}
|
||||
held := byVM[vmKey]
|
||||
if held == nil {
|
||||
@@ -113,7 +113,7 @@ func (a *App) armHeldTimerLocked(pluginID, vmKey string, held *heldInputs, d tim
|
||||
// pruneHeldLocked drops a record that holds nothing, so an idle plugin leaves
|
||||
// no state behind. The caller holds computerUseHeldMu.
|
||||
func (a *App) pruneHeldLocked(pluginID, vmKey string) {
|
||||
byVM := a.computerUseHeld[pluginID]
|
||||
byVM := a.hostAPI.computerUseHeld[pluginID]
|
||||
if byVM == nil {
|
||||
return
|
||||
}
|
||||
@@ -125,16 +125,16 @@ func (a *App) pruneHeldLocked(pluginID, vmKey string) {
|
||||
delete(byVM, vmKey)
|
||||
}
|
||||
if len(byVM) == 0 {
|
||||
delete(a.computerUseHeld, pluginID)
|
||||
delete(a.hostAPI.computerUseHeld, pluginID)
|
||||
}
|
||||
}
|
||||
|
||||
// heldSnapshot returns what one plugin holds in one VM, sorted, with the
|
||||
// generation it was read at.
|
||||
func (a *App) heldSnapshot(pluginID, vmKey string) (keys, buttons []string, generation uint64) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
byVM := a.computerUseHeld[pluginID]
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
byVM := a.hostAPI.computerUseHeld[pluginID]
|
||||
if byVM == nil {
|
||||
return nil, nil, 0
|
||||
}
|
||||
@@ -156,9 +156,9 @@ func (a *App) heldSnapshot(pluginID, vmKey string) (keys, buttons []string, gene
|
||||
// heldGeneration returns the record's current generation, or 0 when there is
|
||||
// no record.
|
||||
func (a *App) heldGeneration(pluginID, vmKey string) uint64 {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
if held := a.computerUseHeld[pluginID][vmKey]; held != nil {
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
if held := a.hostAPI.computerUseHeld[pluginID][vmKey]; held != nil {
|
||||
return held.generation
|
||||
}
|
||||
return 0
|
||||
@@ -166,10 +166,10 @@ func (a *App) heldGeneration(pluginID, vmKey string) uint64 {
|
||||
|
||||
// heldVMs lists the VMs one plugin currently holds input in.
|
||||
func (a *App) heldVMs(pluginID string) map[string]bool {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
out := map[string]bool{}
|
||||
for vmKey := range a.computerUseHeld[pluginID] {
|
||||
for vmKey := range a.hostAPI.computerUseHeld[pluginID] {
|
||||
out[vmKey] = true
|
||||
}
|
||||
return out
|
||||
@@ -179,9 +179,9 @@ func (a *App) heldVMs(pluginID string) map[string]bool {
|
||||
// when the caller itself named what it lifted, so there is no snapshot to
|
||||
// compare with.
|
||||
func (a *App) dropHeld(pluginID, vmKey string, keys, buttons []string) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
held := a.computerUseHeld[pluginID][vmKey]
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
held := a.hostAPI.computerUseHeld[pluginID][vmKey]
|
||||
if held == nil {
|
||||
return
|
||||
}
|
||||
@@ -199,9 +199,9 @@ func (a *App) dropHeld(pluginID, vmKey string, keys, buttons []string) {
|
||||
// meantime may hold a press this release did not lift, so it keeps everything
|
||||
// and its timer releases it later.
|
||||
func (a *App) dropHeldIfGeneration(pluginID, vmKey string, keys, buttons []string, generation uint64) bool {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
held := a.computerUseHeld[pluginID][vmKey]
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
held := a.hostAPI.computerUseHeld[pluginID][vmKey]
|
||||
if held == nil {
|
||||
return false
|
||||
}
|
||||
@@ -221,9 +221,9 @@ func (a *App) dropHeldIfGeneration(pluginID, vmKey string, keys, buttons []strin
|
||||
// rearmHeld schedules another fallback release for a record whose release
|
||||
// failed while the VM is still running.
|
||||
func (a *App) rearmHeld(pluginID, vmKey string) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
held := a.computerUseHeld[pluginID][vmKey]
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
held := a.hostAPI.computerUseHeld[pluginID][vmKey]
|
||||
if held == nil || len(held.keys)+len(held.buttons) == 0 {
|
||||
return
|
||||
}
|
||||
@@ -235,8 +235,8 @@ func (a *App) rearmHeld(pluginID, vmKey string) {
|
||||
// can still be held, and a release sent later could lift a key the user is
|
||||
// pressing after the VM starts again.
|
||||
func (a *App) forgetHeld(pluginID, vmKey string) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
a.pruneHeldLocked(pluginID, vmKey)
|
||||
}
|
||||
|
||||
|
||||
@@ -10,12 +10,14 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/console"
|
||||
"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/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/thumb"
|
||||
@@ -48,23 +50,26 @@ func (a *App) computerUseHostHandlers(mgr *plugin.Manager, pluginID string) map[
|
||||
return nil
|
||||
}
|
||||
return map[string]plugin.RPCRequestHandler{
|
||||
"host/vm.list": a.hostVMMethod(mgr, pluginID, "host/vm.list", a.handleComputerUseVMList),
|
||||
"host/vm.get": a.hostVMMethod(mgr, pluginID, "host/vm.get", a.handleComputerUseVMGet),
|
||||
"host/vm.start": a.hostVMMethod(mgr, pluginID, "host/vm.start", a.handleComputerUseVMStart),
|
||||
"host/vm.shutdown": a.hostVMMethod(mgr, pluginID, "host/vm.shutdown", a.handleComputerUseVMShutdown),
|
||||
"host/vm.suspend": a.hostVMMethod(mgr, pluginID, "host/vm.suspend", a.handleComputerUseVMStateChange("host/vm.suspend", a.SuspendVM)),
|
||||
"host/vm.resume": a.hostVMMethod(mgr, pluginID, "host/vm.resume", a.handleComputerUseVMStateChange("host/vm.resume", a.ResumeVM)),
|
||||
"host/vm.clone": a.hostVMMethod(mgr, pluginID, "host/vm.clone", a.handleComputerUseVMClone),
|
||||
"host/vm.delete": a.hostVMMethod(mgr, pluginID, "host/vm.delete", a.handleComputerUseVMDelete),
|
||||
"host/vm.snapshot.list": a.hostVMMethod(mgr, pluginID, "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList),
|
||||
"host/vm.snapshot.create": a.hostVMMethod(mgr, pluginID, "host/vm.snapshot.create", a.handleComputerUseVMSnapshotCreate),
|
||||
"host/vm.snapshot.restore": a.hostVMMethod(mgr, pluginID, "host/vm.snapshot.restore", a.handleComputerUseVMSnapshotRestore),
|
||||
"host/console.screenshot": a.hostVMMethod(mgr, pluginID, "host/console.screenshot", a.handleComputerUseScreenshot),
|
||||
"host/console.pointer": a.hostVMMethod(mgr, pluginID, "host/console.pointer", a.handleComputerUsePointer),
|
||||
"host/console.key": a.hostVMMethod(mgr, pluginID, "host/console.key", a.handleComputerUseKey),
|
||||
"host/console.type": a.hostVMMethod(mgr, pluginID, "host/console.type", a.handleComputerUseType),
|
||||
"host/console.typeSecret": a.hostVMMethod(mgr, pluginID, "host/console.typeSecret", a.handleComputerUseTypeSecret),
|
||||
"host/console.release": a.hostVMMethod(mgr, pluginID, "host/console.release", a.handleComputerUseRelease),
|
||||
"host/vm.list": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.list", a.handleComputerUseVMList),
|
||||
"host/vm.get": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.get", a.handleComputerUseVMGet),
|
||||
"host/vm.telemetry": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.telemetry", a.handleComputerUseVMTelemetry),
|
||||
"host/vm.start": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.start", a.handleComputerUseVMStart),
|
||||
"host/vm.shutdown": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.shutdown", a.handleComputerUseVMShutdown),
|
||||
"host/vm.suspend": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.suspend", a.handleComputerUseVMStateChange("host/vm.suspend", a.SuspendVM)),
|
||||
"host/vm.resume": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.resume", a.handleComputerUseVMStateChange("host/vm.resume", a.ResumeVM)),
|
||||
"host/vm.restart": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.restart", a.handleComputerUseVMRestart),
|
||||
"host/vm.finishInstall": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.finishInstall", a.handleComputerUseVMFinishInstall),
|
||||
"host/vm.clone": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.clone", a.handleComputerUseVMClone),
|
||||
"host/vm.delete": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.delete", a.handleComputerUseVMDelete),
|
||||
"host/vm.snapshot.list": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList),
|
||||
"host/vm.snapshot.create": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.snapshot.create", a.handleComputerUseVMSnapshotCreate),
|
||||
"host/vm.snapshot.restore": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.snapshot.restore", a.handleComputerUseVMSnapshotRestore),
|
||||
"host/console.screenshot": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.screenshot", a.handleComputerUseScreenshot),
|
||||
"host/console.pointer": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.pointer", a.handleComputerUsePointer),
|
||||
"host/console.key": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.key", a.handleComputerUseKey),
|
||||
"host/console.type": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.type", a.handleComputerUseType),
|
||||
"host/console.typeSecret": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.typeSecret", a.handleComputerUseTypeSecret),
|
||||
"host/console.release": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.release", a.handleComputerUseRelease),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,17 +86,18 @@ func (a *App) handleComputerUseTypeSecret(ctx context.Context, raw json.RawMessa
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(req.Setting) == "" {
|
||||
settingName := strings.TrimSpace(req.Setting)
|
||||
if settingName == "" {
|
||||
return nil, errors.New("secret setting name is required")
|
||||
}
|
||||
vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
|
||||
vm, route, err := a.resolveComputerUseVM(ctx, mgr, pluginID, req.VM, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if mgr == nil {
|
||||
return nil, errors.New("plugin manager is unavailable")
|
||||
}
|
||||
secret, err := a.computerUseSecretSetting(mgr, pluginID, vm, req.Setting)
|
||||
secret, err := a.computerUseSecretSetting(mgr, pluginID, vm, settingName)
|
||||
if err != nil {
|
||||
if errors.Is(err, plugin.ErrSecretEmpty) {
|
||||
return nil, a.computerUseHostError("secret_missing", "err.computer_use.secret_missing", i18n.Vars{"name": vm.Name})
|
||||
@@ -99,22 +105,28 @@ func (a *App) handleComputerUseTypeSecret(ctx context.Context, raw json.RawMessa
|
||||
return nil, err
|
||||
}
|
||||
defer func() { secret = "" }()
|
||||
if len(secret) == 0 || utf8.RuneCountInString(secret) > computerUseMaxTextRunes {
|
||||
runeCount := utf8.RuneCountInString(secret)
|
||||
if len(secret) == 0 || runeCount > computerUseMaxTextRunes {
|
||||
return nil, errors.New("secret must contain between 1 and 4000 characters")
|
||||
}
|
||||
callCtx, cancelCall := a.withSessionContext(ctx, vm.Ref().Key())
|
||||
defer cancelCall()
|
||||
var count int
|
||||
if route.kind == consoleRouteDriver {
|
||||
count, err = route.console.ConsoleType(ctx, vm.Name, secret)
|
||||
count, err = route.console.ConsoleType(callCtx, vm.Name, secret)
|
||||
} else {
|
||||
service, svcErr := a.computerUseService()
|
||||
if svcErr != nil {
|
||||
return nil, svcErr
|
||||
}
|
||||
count, err = service.TypeText(ctx, vm.Directory, secret, nil)
|
||||
count, err = service.TypeText(callCtx, vm.Directory, secret, nil)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if mgr.Broker() != nil {
|
||||
mgr.Broker().Audit(pluginID, "TYPE_SECRET", fmt.Sprintf("setting=%s len=%d", settingName, runeCount))
|
||||
}
|
||||
return pluginproto.CharactersResult{Characters: count}, nil
|
||||
}
|
||||
|
||||
@@ -230,6 +242,218 @@ func (a *App) handleComputerUseVMStateChange(method string, change func(driverID
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) handleComputerUseVMRestart(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
|
||||
req, err := decodeHostParams[pluginproto.VMRestartParams](mgr, pluginID, "host/vm.restart", raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := a.checkUserTakeover(vm.Ref().Key(), vm.Name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
phase, err := a.effectiveVMPhaseStrict(vm)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if phase == driver.PhaseInstaller || phase == driver.PhaseRecovery {
|
||||
if err := a.authorizeProtectedPhase(ctx, mgr, pluginID, vm, phase, false, true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
callCtx, cancel := a.withSessionContext(ctx, vm.Ref().Key())
|
||||
defer cancel()
|
||||
if err := callCtx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// macOS Setup Assistant & Login Window ignore ACPI powerdown for the full
|
||||
// 90s stop_timeout_secs; cap graceful shutdown for built-in macOS restarts
|
||||
// triggered by automation so Stage 4 restarts in ~10s instead of stalling 90s.
|
||||
if vm.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
grace := 10 * time.Second
|
||||
if req.GracefulTimeoutSec > 0 && req.GracefulTimeoutSec <= 90 {
|
||||
grace = time.Duration(req.GracefulTimeoutSec) * time.Second
|
||||
}
|
||||
if err := a.beginVMStart(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer a.vmStarts.Done()
|
||||
if _, err := a.restartMacOSVMWithGrace(callCtx, vm.Name, grace); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else if err := a.RestartVM(vm.DriverID, vm.Name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.wakePoll()
|
||||
pid := int(a.rebindAgentSessionAfterRestart(vm.Ref().Key()))
|
||||
if pid == 0 {
|
||||
if polled, ok := a.polledVMForDriver(vm.DriverID, vm.Name); ok && polled.PID != nil {
|
||||
pid = *polled.PID
|
||||
}
|
||||
}
|
||||
return map[string]any{"ok": true, "vm": vm.Ref().Key(), "pid": pid}, nil
|
||||
}
|
||||
|
||||
func (a *App) handleComputerUseVMFinishInstall(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
|
||||
req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, "host/vm.finishInstall", raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := a.checkUserTakeover(vm.Ref().Key(), vm.Name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
phase, err := a.effectiveVMPhaseStrict(vm)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if phase == driver.PhaseInstaller || phase == driver.PhaseRecovery {
|
||||
if err := a.authorizeProtectedPhase(ctx, mgr, pluginID, vm, phase, false, true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
callCtx, cancel := a.withSessionContext(ctx, vm.Ref().Key())
|
||||
defer cancel()
|
||||
commitGuideHandoff := a.prepareInstallGuideFinishHandoff(vm)
|
||||
livePID := 0
|
||||
if polled, ok := a.polledVMForDriver(vm.DriverID, vm.Name); ok && polled.State == "running" && polled.PID != nil && *polled.PID > 0 {
|
||||
livePID = *polled.PID
|
||||
}
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
if err := a.FinishInstall(vm.Name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
commitGuideHandoff(livePID > 0, livePID)
|
||||
a.markAgentSessionFinishInstallDone(vm.Ref().Key())
|
||||
if !a.hasActiveAgentSession(vm.Ref().Key()) {
|
||||
a.markInstallGuideRecheck(vm.Name)
|
||||
}
|
||||
return map[string]any{"ok": true, "vm": vm.Ref().Key()}, nil
|
||||
}
|
||||
var out any
|
||||
err = a.withComputerUseVM(callCtx, vm.Directory, func(opCtx context.Context) error {
|
||||
var invokeErr error
|
||||
out, invokeErr = svc.InvokeAction(opCtx, vm.Ref(), "finish_install", nil)
|
||||
return invokeErr
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, _ := out.(map[string]any)
|
||||
if result == nil {
|
||||
result = map[string]any{}
|
||||
}
|
||||
running, hasRunning := result["running"].(bool)
|
||||
if !hasRunning {
|
||||
running = livePID > 0
|
||||
}
|
||||
a.applyFinishInstallResult(vm.DriverID, vm.Name, result)
|
||||
commitGuideHandoff(running, livePID)
|
||||
a.markAgentSessionFinishInstallDone(vm.Ref().Key())
|
||||
result["ok"] = true
|
||||
result["vm"] = vm.Ref().Key()
|
||||
if !a.hasActiveAgentSession(vm.Ref().Key()) {
|
||||
a.markInstallGuideRecheck(vm.Name)
|
||||
}
|
||||
a.wakePoll()
|
||||
if a.hasActiveAgentSession(vm.Ref().Key()) {
|
||||
go a.refreshActiveAgentSessionAfterStart(vm.Ref().Key())
|
||||
}
|
||||
a.emitStateChanged()
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (a *App) handleComputerUseVMTelemetry(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
|
||||
req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, "host/vm.telemetry", raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
key := vm.Ref().Key()
|
||||
pid := 0
|
||||
state := vm.State
|
||||
if polled, ok := a.polledVMForDriver(vm.DriverID, vm.Name); ok {
|
||||
state = polled.State
|
||||
if polled.PID != nil {
|
||||
pid = *polled.PID
|
||||
}
|
||||
if vm.Directory == "" {
|
||||
vm.Directory = polled.Dir
|
||||
}
|
||||
}
|
||||
phase := a.effectiveVMPhase(vm)
|
||||
|
||||
var milestones []telemetryMilestone
|
||||
var qemuErrors []string
|
||||
var diskBytes, diskDelta int64
|
||||
cpuPct := -1.0
|
||||
coldReboots := 0
|
||||
var updatedAt string
|
||||
|
||||
a.telemetryMu.Lock()
|
||||
if st := a.vmTelemetry[key]; st != nil {
|
||||
milestones = make([]telemetryMilestone, 0, len(st.milestones))
|
||||
for _, m := range st.milestones {
|
||||
milestones = append(milestones, m)
|
||||
}
|
||||
sort.Slice(milestones, func(i, j int) bool { return milestones[i].Key < milestones[j].Key })
|
||||
qemuErrors = make([]string, 0, len(st.qemuErrors))
|
||||
for _, line := range st.qemuErrors {
|
||||
qemuErrors = append(qemuErrors, host.RedactText(line))
|
||||
}
|
||||
diskBytes = st.diskBytes
|
||||
diskDelta = st.diskDeltaBytes
|
||||
cpuPct = st.cpuPercent
|
||||
coldReboots = st.coldRebootCount
|
||||
if !st.updatedAt.IsZero() {
|
||||
updatedAt = st.updatedAt.UTC().Format(time.RFC3339)
|
||||
}
|
||||
}
|
||||
a.telemetryMu.Unlock()
|
||||
|
||||
if vm.Directory != "" && a.hasProvisionReadyMarker(vm.Directory) {
|
||||
hasReady := false
|
||||
for _, m := range milestones {
|
||||
if m.Key == "serial:provision_ready" {
|
||||
hasReady = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasReady {
|
||||
milestones = append(milestones, telemetryMilestone{Key: "serial:provision_ready", Count: 1})
|
||||
sort.Slice(milestones, func(i, j int) bool { return milestones[i].Key < milestones[j].Key })
|
||||
}
|
||||
}
|
||||
|
||||
if diskBytes == 0 && vm.Directory != "" {
|
||||
diskBytes = fileSizeBytes(filepath.Join(vm.Directory, "disk.qcow2"))
|
||||
}
|
||||
return map[string]any{
|
||||
"vm": key,
|
||||
"state": state,
|
||||
"phase": phase,
|
||||
"pid": pid,
|
||||
"boot_milestones": milestones,
|
||||
"qemu_errors": qemuErrors,
|
||||
"disk_bytes": diskBytes,
|
||||
"disk_delta_bytes": diskDelta,
|
||||
"cpu_percent": cpuPct,
|
||||
"cold_reboot_count": coldReboots,
|
||||
"updated_at": updatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *App) handleComputerUseVMClone(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
|
||||
req, err := decodeHostParams[pluginproto.VMCloneParams](mgr, pluginID, "host/vm.clone", raw)
|
||||
if err != nil {
|
||||
@@ -243,8 +467,8 @@ func (a *App) handleComputerUseVMClone(ctx context.Context, raw json.RawMessage,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.computerUseCloneMu.Lock()
|
||||
defer a.computerUseCloneMu.Unlock()
|
||||
a.hostAPI.computerUseCloneMu.Lock()
|
||||
defer a.hostAPI.computerUseCloneMu.Unlock()
|
||||
if existing, listErr := a.listVMsInternal(ctx); listErr != nil {
|
||||
return nil, listErr
|
||||
} else if slices.ContainsFunc(existing, func(item driver.VMListItem) bool {
|
||||
@@ -362,14 +586,18 @@ func (a *App) handleComputerUseVMSnapshotRestore(_ context.Context, raw json.Raw
|
||||
|
||||
// resolveComputerUseVM returns the VM and the console route Agent calls use.
|
||||
// A VM whose driver serves its own console needs no host process; every other
|
||||
// VM must be a running QMP-reachable process.
|
||||
func (a *App) resolveComputerUseVM(mgr *plugin.Manager, pluginID, ref string) (driver.VMInfo, consoleRoute, error) {
|
||||
// VM must be a running QMP-reachable process. It enforces #105 protected-phase
|
||||
// confirmation and, for write operations, #103 session visibility and user takeover.
|
||||
func (a *App) resolveComputerUseVM(ctx context.Context, mgr *plugin.Manager, pluginID, ref string, isWrite bool) (driver.VMInfo, consoleRoute, error) {
|
||||
ref = strings.TrimSpace(ref)
|
||||
if ref == "" {
|
||||
return driver.VMInfo{}, consoleRoute{}, errors.New("VM reference is required")
|
||||
}
|
||||
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, ref)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "not_authorized") {
|
||||
a.abortAgentSessionForVMRef(mgr, pluginID, ref, "permission_denied", false)
|
||||
}
|
||||
return driver.VMInfo{}, consoleRoute{}, err
|
||||
}
|
||||
// A plugin that stopped calling mid-hold must not leave a key down.
|
||||
@@ -388,6 +616,11 @@ func (a *App) resolveComputerUseVM(mgr *plugin.Manager, pluginID, ref string) (d
|
||||
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})
|
||||
}
|
||||
livePID := uint32(0)
|
||||
if current.PID != nil && *current.PID > 0 {
|
||||
livePID = uint32(*current.PID)
|
||||
a.bindAgentSessionPID(vm.Ref().Key(), livePID)
|
||||
}
|
||||
if vm.Phase == "" {
|
||||
if pr, ok := a.driverFor(vm).(driver.PhaseReporter); ok {
|
||||
pctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
@@ -402,9 +635,20 @@ func (a *App) resolveComputerUseVM(mgr *plugin.Manager, pluginID, ref string) (d
|
||||
vm.Phase = phase
|
||||
}
|
||||
}
|
||||
if phase := computerUseVMPhase(vm); phase != "normal" {
|
||||
phaseLabel := i18n.M(a.computerUseLocale(), "err.computer_use.phase."+phase, nil)
|
||||
return driver.VMInfo{}, consoleRoute{}, a.computerUseHostError("confirmation_required", "err.computer_use.phase_confirmation", i18n.Vars{"name": vm.Name, "phase": phaseLabel})
|
||||
phase := computerUseVMPhase(vm)
|
||||
if phase != driver.PhaseNormal {
|
||||
if err := a.authorizeProtectedPhase(ctx, mgr, pluginID, vm, phase, false, false); err != nil {
|
||||
return driver.VMInfo{}, consoleRoute{}, err
|
||||
}
|
||||
}
|
||||
if isWrite {
|
||||
a.ensureAgentSessionForWrite(mgr, pluginID, vm)
|
||||
if livePID > 0 {
|
||||
a.bindAgentSessionPID(vm.Ref().Key(), livePID)
|
||||
}
|
||||
if err := a.checkUserTakeover(vm.Ref().Key(), vm.Name); err != nil {
|
||||
return driver.VMInfo{}, consoleRoute{}, err
|
||||
}
|
||||
}
|
||||
if vm.Directory == "" {
|
||||
vm.Directory = current.Dir
|
||||
@@ -433,37 +677,39 @@ func (a *App) computerUseHostError(code, key string, params i18n.Vars) error {
|
||||
|
||||
func (a *App) computerUseLocale() i18n.Locale {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
loc := i18n.ZhCN
|
||||
raw := i18n.ZhCN
|
||||
if a.cfg != nil {
|
||||
loc = a.cfg.Locale
|
||||
raw = a.cfg.Locale
|
||||
}
|
||||
return loc
|
||||
a.mu.Unlock()
|
||||
return i18n.EffectiveLocale(raw)
|
||||
}
|
||||
|
||||
func (a *App) computerUseVMAccessEnabled(mgr *plugin.Manager, pluginID, vmKey string) bool {
|
||||
return computerUseVMAccessEnabled(mgr, pluginID, vmKey) || a.computerUseOwned(pluginID, vmKey)
|
||||
return computerUseVMAccessEnabled(mgr, pluginID, vmKey) || a.computerUseOwned(pluginID, vmKey) || a.hasEphemeralVMAccess(pluginID, vmKey)
|
||||
}
|
||||
|
||||
func (a *App) computerUseOwned(pluginID, vmKey string) bool {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.computerUseOwnedVMs != nil && a.computerUseOwnedVMs[pluginID] != nil && a.computerUseOwnedVMs[pluginID][vmKey]
|
||||
h := a.hostAPISvc()
|
||||
h.ownedMu.Lock()
|
||||
defer h.ownedMu.Unlock()
|
||||
return h.computerUseOwnedVMs != nil && h.computerUseOwnedVMs[pluginID] != nil && h.computerUseOwnedVMs[pluginID][vmKey]
|
||||
}
|
||||
|
||||
func (a *App) markComputerUseOwnedVM(pluginID, vmKey string, owned bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.computerUseOwnedVMs == nil {
|
||||
a.computerUseOwnedVMs = make(map[string]map[string]bool)
|
||||
h := a.hostAPISvc()
|
||||
h.ownedMu.Lock()
|
||||
defer h.ownedMu.Unlock()
|
||||
if h.computerUseOwnedVMs == nil {
|
||||
h.computerUseOwnedVMs = make(map[string]map[string]bool)
|
||||
}
|
||||
if a.computerUseOwnedVMs[pluginID] == nil {
|
||||
a.computerUseOwnedVMs[pluginID] = make(map[string]bool)
|
||||
if h.computerUseOwnedVMs[pluginID] == nil {
|
||||
h.computerUseOwnedVMs[pluginID] = make(map[string]bool)
|
||||
}
|
||||
if owned {
|
||||
a.computerUseOwnedVMs[pluginID][vmKey] = true
|
||||
h.computerUseOwnedVMs[pluginID][vmKey] = true
|
||||
} else {
|
||||
delete(a.computerUseOwnedVMs[pluginID], vmKey)
|
||||
delete(h.computerUseOwnedVMs[pluginID], vmKey)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -472,12 +718,13 @@ func (a *App) forgetComputerUseOwnedVM(vmKey string) {
|
||||
if vmKey == "" {
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for pluginID, owned := range a.computerUseOwnedVMs {
|
||||
h := a.hostAPISvc()
|
||||
h.ownedMu.Lock()
|
||||
defer h.ownedMu.Unlock()
|
||||
for pluginID, owned := range h.computerUseOwnedVMs {
|
||||
delete(owned, vmKey)
|
||||
if len(owned) == 0 {
|
||||
delete(a.computerUseOwnedVMs, pluginID)
|
||||
delete(h.computerUseOwnedVMs, pluginID)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -611,14 +858,15 @@ func (a *App) syncComputerUseOwnership(vms []driver.VMListItem) {
|
||||
continue
|
||||
}
|
||||
key := vm.Ref().Key()
|
||||
a.mu.Lock()
|
||||
h := a.hostAPISvc()
|
||||
h.ownedMu.Lock()
|
||||
var pluginIDs []string
|
||||
for pluginID, owned := range a.computerUseOwnedVMs {
|
||||
for pluginID, owned := range h.computerUseOwnedVMs {
|
||||
if owned[key] {
|
||||
pluginIDs = append(pluginIDs, pluginID)
|
||||
}
|
||||
}
|
||||
a.mu.Unlock()
|
||||
h.ownedMu.Unlock()
|
||||
for _, pluginID := range pluginIDs {
|
||||
// The source VM is no longer known on this repair path (the marker
|
||||
// was lost), so write an empty source: no fallback, same as before.
|
||||
@@ -810,45 +1058,101 @@ func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessa
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
maxWidth := computerUseScreenshotWidth(req.MaxWidth)
|
||||
outFormat := strings.ToLower(strings.TrimSpace(req.Format))
|
||||
if outFormat == "" {
|
||||
outFormat = "jpeg"
|
||||
}
|
||||
if outFormat != "jpeg" && outFormat != "png" {
|
||||
return nil, fmt.Errorf("unsupported screenshot format %q (want jpeg or png)", req.Format)
|
||||
}
|
||||
if req.Region != nil && (req.Region.Width <= 0 || req.Region.Height <= 0) {
|
||||
return nil, errors.New("region width and height must be positive")
|
||||
}
|
||||
_, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
|
||||
if req.MaxEdge != nil && (*req.MaxEdge < 0 || *req.MaxEdge > 16384) {
|
||||
return nil, fmt.Errorf("invalid max_edge %d", *req.MaxEdge)
|
||||
}
|
||||
maxWidth := computerUseScreenshotWidth(req.MaxWidth)
|
||||
|
||||
vm, route, err := a.resolveComputerUseVM(ctx, mgr, pluginID, req.VM, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
callCtx, cancelCall := a.withSessionContext(ctx, vm.Ref().Key())
|
||||
defer cancelCall()
|
||||
|
||||
// A region is cut from the full-resolution frame, so the driver must not
|
||||
// shrink it first.
|
||||
captureEdge := maxWidth
|
||||
if req.MaxEdge != nil {
|
||||
captureEdge = *req.MaxEdge
|
||||
}
|
||||
if req.Region != nil {
|
||||
captureEdge = 0
|
||||
}
|
||||
path, format, cleanup, err := a.consoleCapture(ctx, route, captureEdge)
|
||||
path, frameFormat, cleanup, err := a.consoleCapture(callCtx, route, captureEdge)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer cleanup()
|
||||
sourceSize, err := thumb.Size(path, format)
|
||||
sourceSize, err := thumb.Size(path, frameFormat)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var (
|
||||
frame image.Image
|
||||
blank bool
|
||||
)
|
||||
result := pluginproto.ScreenshotResult{
|
||||
MIMEType: "image/jpeg", SourceWidth: sourceSize.X, SourceHeight: sourceSize.Y,
|
||||
mimeType := "image/jpeg"
|
||||
if outFormat == "png" {
|
||||
mimeType = "image/png"
|
||||
}
|
||||
if req.Region == nil {
|
||||
// A blank frame is a normal screen state during boot, login and display
|
||||
// switches. Return it with a flag so pollers can keep waiting through it.
|
||||
frame, blank, err = thumb.LoadPreviewFrame(path, format, maxWidth)
|
||||
result := pluginproto.ScreenshotResult{
|
||||
MIMEType: mimeType, SourceWidth: sourceSize.X, SourceHeight: sourceSize.Y,
|
||||
}
|
||||
if req.MaxEdge != nil {
|
||||
var cropRect *image.Rectangle
|
||||
if req.Region != nil {
|
||||
mapped := computerUseRegionToSource(computerUseRegion{
|
||||
X: req.Region.X, Y: req.Region.Y, Width: req.Region.Width, Height: req.Region.Height,
|
||||
}, req.Width, req.Height, sourceSize)
|
||||
r := image.Rect(mapped.X, mapped.Y, mapped.X+mapped.Width, mapped.Y+mapped.Height)
|
||||
cropRect = &r
|
||||
}
|
||||
var actualCrop image.Rectangle
|
||||
frame, actualCrop, blank, err = thumb.LoadRegionFrame(path, frameFormat, cropRect, *req.MaxEdge)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cropRect != nil {
|
||||
result.Region = &pluginproto.Region{
|
||||
X: actualCrop.Min.X, Y: actualCrop.Min.Y,
|
||||
Width: actualCrop.Dx(), Height: actualCrop.Dy(),
|
||||
}
|
||||
}
|
||||
} else if req.Region == nil {
|
||||
// A blank frame is a normal screen state during boot, login and display
|
||||
// switches. Return it with a flag so pollers can keep waiting through it.
|
||||
frame, blank, err = thumb.LoadPreviewFrame(path, frameFormat, maxWidth)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else if req.MaxWidth == 0 && outFormat == "png" {
|
||||
mapped := computerUseRegionToSource(computerUseRegion{
|
||||
X: req.Region.X, Y: req.Region.Y, Width: req.Region.Width, Height: req.Region.Height,
|
||||
}, req.Width, req.Height, sourceSize)
|
||||
r := image.Rect(mapped.X, mapped.Y, mapped.X+mapped.Width, mapped.Y+mapped.Height)
|
||||
var actualCrop image.Rectangle
|
||||
frame, actualCrop, blank, err = thumb.LoadRegionFrame(path, frameFormat, &r, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result.Region = &pluginproto.Region{
|
||||
X: actualCrop.Min.X, Y: actualCrop.Min.Y,
|
||||
Width: actualCrop.Dx(), Height: actualCrop.Dy(),
|
||||
}
|
||||
} else {
|
||||
full, err := thumb.Load(path, format)
|
||||
full, err := thumb.Load(path, frameFormat)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -864,7 +1168,12 @@ func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessa
|
||||
blank = thumb.Blank(full)
|
||||
result.Region = &pluginproto.Region{X: applied.X, Y: applied.Y, Width: applied.Width, Height: applied.Height}
|
||||
}
|
||||
encoded, err := thumb.JPEG(frame, 84)
|
||||
var encoded []byte
|
||||
if outFormat == "png" {
|
||||
encoded, err = thumb.PNG(frame)
|
||||
} else {
|
||||
encoded, err = thumb.JPEG(frame, 84)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -887,10 +1196,12 @@ func (a *App) handleComputerUsePointer(ctx context.Context, raw json.RawMessage,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
|
||||
vm, route, err := a.resolveComputerUseVM(ctx, mgr, pluginID, req.VM, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
callCtx, cancelCall := a.withSessionContext(ctx, vm.Ref().Key())
|
||||
defer cancelCall()
|
||||
// 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.
|
||||
@@ -906,7 +1217,7 @@ func (a *App) handleComputerUsePointer(ctx context.Context, raw json.RawMessage,
|
||||
a.noteHeldButton(pluginID, vm.Ref().Key(), button, true)
|
||||
}
|
||||
}
|
||||
if err := a.consolePointer(ctx, route, driver.ConsolePointerRequest{
|
||||
if err := a.consolePointer(callCtx, route, driver.ConsolePointerRequest{
|
||||
Action: req.Action, X: req.X, Y: req.Y, Width: req.Width, Height: req.Height,
|
||||
Button: req.Button, Down: req.Down, Delta: req.Delta, Horizontal: req.Horizontal,
|
||||
}); err != nil {
|
||||
@@ -926,12 +1237,14 @@ func (a *App) handleComputerUseKey(ctx context.Context, raw json.RawMessage, mgr
|
||||
if strings.TrimSpace(req.Key) == "" {
|
||||
return nil, errors.New("key is required")
|
||||
}
|
||||
vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
|
||||
vm, route, err := a.resolveComputerUseVM(ctx, mgr, pluginID, req.VM, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
callCtx, cancelCall := a.withSessionContext(ctx, vm.Ref().Key())
|
||||
defer cancelCall()
|
||||
if req.Down == nil {
|
||||
if err := a.consoleKey(ctx, route, req.Key, req.Modifiers); err != nil {
|
||||
if err := a.consoleKey(callCtx, route, req.Key, req.Modifiers); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return pluginproto.OKResult{OK: true}, nil
|
||||
@@ -955,7 +1268,7 @@ func (a *App) handleComputerUseKey(ctx context.Context, raw json.RawMessage, mgr
|
||||
}
|
||||
}
|
||||
for _, code := range codes {
|
||||
if err := a.consoleKeyState(ctx, route, code, *req.Down); err != nil {
|
||||
if err := a.consoleKeyState(callCtx, route, code, *req.Down); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
@@ -974,7 +1287,7 @@ func (a *App) handleComputerUseRelease(ctx context.Context, raw json.RawMessage,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
|
||||
vm, route, err := a.resolveComputerUseVM(ctx, mgr, pluginID, req.VM, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1004,7 +1317,7 @@ func (a *App) handleComputerUseType(ctx context.Context, raw json.RawMessage, mg
|
||||
if utf8.RuneCountInString(req.Text) > computerUseMaxTextRunes {
|
||||
return nil, fmt.Errorf("text exceeds %d characters", computerUseMaxTextRunes)
|
||||
}
|
||||
vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
|
||||
vm, route, err := a.resolveComputerUseVM(ctx, mgr, pluginID, req.VM, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1014,6 +1327,11 @@ func (a *App) handleComputerUseType(ctx context.Context, raw json.RawMessage, mg
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
callCtx, cancelCall := a.withSessionContext(ctx, vm.Ref().Key())
|
||||
defer cancelCall()
|
||||
if err := callCtx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n, err := a.injectTextIntoVMForDriver(vm.DriverID, vm.Name, vm.Directory, req.Text, false, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -0,0 +1,744 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/pkg/pluginproto"
|
||||
)
|
||||
|
||||
var (
|
||||
confirmPromptTimeout = 2 * time.Minute
|
||||
protectedPhaseDenialCooldown = 30 * time.Second
|
||||
)
|
||||
|
||||
// ConfirmResolvedEvent notifies the desktop window when a pending confirmation
|
||||
// prompt closes (answered, timed out, or canceled) so stale modals never linger.
|
||||
type ConfirmResolvedEvent struct {
|
||||
ID string `json:"id"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
// ConfirmPrompt describes a host-native confirmation dialog shown for
|
||||
// `host/ui.confirm`, #105 protected-phase authorization, or custom download mirrors.
|
||||
type ConfirmPrompt struct {
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind"` // "generic" | "protected_phase" | "custom_mirror"
|
||||
PluginID string `json:"plugin_id"`
|
||||
PluginName string `json:"plugin_name"`
|
||||
Publisher string `json:"publisher,omitempty"`
|
||||
Trust string `json:"trust,omitempty"`
|
||||
VM string `json:"vm,omitempty"`
|
||||
VMName string `json:"vm_name,omitempty"`
|
||||
Phase string `json:"phase,omitempty"`
|
||||
Title string `json:"title"`
|
||||
Message string `json:"message"`
|
||||
ConfirmLabel string `json:"confirm_label,omitempty"`
|
||||
CancelLabel string `json:"cancel_label,omitempty"`
|
||||
Danger bool `json:"danger,omitempty"`
|
||||
AllowDurationChoice bool `json:"allow_duration_choice,omitempty"`
|
||||
DefaultDurationMin int `json:"default_duration_minutes,omitempty"`
|
||||
PreferUntilPhaseExit bool `json:"prefer_until_phase_exit,omitempty"`
|
||||
Origin string `json:"origin,omitempty"`
|
||||
}
|
||||
|
||||
// ConfirmResolution carries the user's answer from the desktop confirmation dialog.
|
||||
type ConfirmResolution struct {
|
||||
Approved bool `json:"approved"`
|
||||
DurationMinutes int `json:"duration_minutes,omitempty"`
|
||||
UntilPhaseExit bool `json:"until_phase_exit,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
type phaseGrantKey struct {
|
||||
pluginID string
|
||||
vmKey string
|
||||
}
|
||||
|
||||
type protectedPhaseGrant struct {
|
||||
pluginID string
|
||||
vmKey string
|
||||
phase string
|
||||
grantedAt time.Time
|
||||
expiresAt time.Time
|
||||
untilPhaseExit bool
|
||||
denied bool
|
||||
}
|
||||
|
||||
func (g protectedPhaseGrant) isActive(now time.Time) bool {
|
||||
if g.denied {
|
||||
return false
|
||||
}
|
||||
if g.untilPhaseExit {
|
||||
return true
|
||||
}
|
||||
return !g.expiresAt.IsZero() && now.Before(g.expiresAt)
|
||||
}
|
||||
|
||||
func (g protectedPhaseGrant) isDeniedActive(now time.Time) bool {
|
||||
if !g.denied {
|
||||
return false
|
||||
}
|
||||
return g.expiresAt.IsZero() || now.Before(g.expiresAt)
|
||||
}
|
||||
|
||||
func (g protectedPhaseGrant) remainingSeconds(now time.Time) int {
|
||||
if !g.isActive(now) || g.untilPhaseExit {
|
||||
return 0
|
||||
}
|
||||
rem := int(time.Until(g.expiresAt).Seconds())
|
||||
if rem < 0 {
|
||||
return 0
|
||||
}
|
||||
return rem
|
||||
}
|
||||
|
||||
func (a *App) confirmHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
|
||||
if mgr == nil || mgr.Broker() == nil {
|
||||
return nil
|
||||
}
|
||||
broker := mgr.Broker()
|
||||
return map[string]plugin.RPCRequestHandler{
|
||||
"host/ui.confirm": a.hostAPISvc().hostMethod(mgr, pluginID, "host/ui.confirm", func(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
req, err := decodeHostParams[pluginproto.ConfirmParams](mgr, pluginID, "host/ui.confirm", raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(req.Title) == "" && strings.TrimSpace(req.Message) == "" {
|
||||
return nil, errors.New("title or message is required")
|
||||
}
|
||||
kind := "generic"
|
||||
var vmKeyStr, vmName string
|
||||
if strings.TrimSpace(req.VM) != "" {
|
||||
if info, err := a.resolveComputerUseVMInfo(req.VM); err == nil {
|
||||
vmKeyStr = info.Ref().Key()
|
||||
vmName = info.Name
|
||||
} else {
|
||||
vmKeyStr = strings.TrimSpace(req.VM)
|
||||
vmName = vmNameFromKey(vmKeyStr)
|
||||
}
|
||||
}
|
||||
phase := strings.TrimSpace(req.ProtectedPhase)
|
||||
var prompt ConfirmPrompt
|
||||
if phase == driver.PhaseInstaller || phase == driver.PhaseRecovery {
|
||||
if strings.TrimSpace(req.VM) == "" {
|
||||
return nil, errors.New("vm is required for protected_phase confirmation")
|
||||
}
|
||||
vmInfo, err := a.resolveComputerUseVMInfo(req.VM)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
kind = "protected_phase"
|
||||
vmKeyStr = vmInfo.Ref().Key()
|
||||
vmName = vmInfo.Name
|
||||
// Never allow plugins to spoof the #105 protected-phase dialog title,
|
||||
// message, button labels, or danger flag; always render the host's
|
||||
// canonical warning prompt.
|
||||
prompt = a.buildProtectedPhasePrompt(pluginID, vmInfo, phase, req.PreferUntilPhaseExit)
|
||||
if req.DefaultDurationMin > 0 {
|
||||
prompt.DefaultDurationMin = req.DefaultDurationMin
|
||||
}
|
||||
} else {
|
||||
prompt = ConfirmPrompt{
|
||||
Kind: kind,
|
||||
VM: vmKeyStr,
|
||||
VMName: vmName,
|
||||
Phase: phase,
|
||||
Title: strings.TrimSpace(req.Title),
|
||||
Message: strings.TrimSpace(req.Message),
|
||||
ConfirmLabel: strings.TrimSpace(req.ConfirmLabel),
|
||||
CancelLabel: strings.TrimSpace(req.CancelLabel),
|
||||
Danger: req.Danger,
|
||||
AllowDurationChoice: req.AllowDurationChoice,
|
||||
DefaultDurationMin: req.DefaultDurationMin,
|
||||
PreferUntilPhaseExit: req.PreferUntilPhaseExit,
|
||||
}
|
||||
}
|
||||
res, err := a.requestHostConfirm(ctx, broker, mgr.Registry(), pluginID, prompt)
|
||||
if err != nil {
|
||||
if kind == "protected_phase" && vmKeyStr != "" {
|
||||
a.handlePluginPermissionDeniedForVM(mgr, pluginID, vmKeyStr, vmName, "confirmation_denied")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if kind == "protected_phase" && vmKeyStr != "" {
|
||||
if res.Approved {
|
||||
a.recordProtectedPhaseGrant(broker, pluginID, vmKeyStr, phase, res.DurationMinutes, res.UntilPhaseExit)
|
||||
} else {
|
||||
a.recordProtectedPhaseDenial(mgr, broker, pluginID, vmKeyStr, vmName, phase)
|
||||
}
|
||||
}
|
||||
return pluginproto.ConfirmResult{
|
||||
Approved: res.Approved,
|
||||
DurationMinutes: res.DurationMinutes,
|
||||
UntilPhaseExit: res.UntilPhaseExit,
|
||||
Reason: res.Reason,
|
||||
}, nil
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) requestHostConfirm(ctx context.Context, broker *plugin.Broker, reg *plugin.Registry, pluginID string, prompt ConfirmPrompt) (ConfirmResolution, error) {
|
||||
a.mu.Lock()
|
||||
emit := a.confirmEmit
|
||||
dismiss := a.confirmDismiss
|
||||
hasWindow := a.ctx != nil
|
||||
locale := i18n.EffectiveLocale(i18n.Auto)
|
||||
if a.cfg != nil {
|
||||
locale = i18n.EffectiveLocale(a.cfg.Locale)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
if emit == nil && !hasWindow {
|
||||
return ConfirmResolution{}, errors.New("confirmation_unavailable: the desktop window is required to confirm this action")
|
||||
}
|
||||
|
||||
prompt.PluginID = pluginID
|
||||
if prompt.PluginName == "" {
|
||||
prompt.PluginName = pluginID
|
||||
}
|
||||
if reg != nil {
|
||||
if info, found := reg.Info(pluginID); found {
|
||||
if name := strings.TrimSpace(info.Name.Get(string(locale))); name != "" {
|
||||
prompt.PluginName = name
|
||||
}
|
||||
prompt.Publisher = info.Publisher
|
||||
prompt.Trust = string(info.Trust)
|
||||
}
|
||||
}
|
||||
|
||||
ch := make(chan ConfirmResolution, 1)
|
||||
a.confirmMu.Lock()
|
||||
if a.confirmPending == nil {
|
||||
a.confirmPending = map[string]chan ConfirmResolution{}
|
||||
}
|
||||
a.confirmSeq++
|
||||
prompt.ID = fmt.Sprintf("confirm-%d", a.confirmSeq)
|
||||
a.confirmPending[prompt.ID] = ch
|
||||
a.confirmMu.Unlock()
|
||||
|
||||
dismissed := false
|
||||
clearPrompt := func(reason string) {
|
||||
a.confirmMu.Lock()
|
||||
delete(a.confirmPending, prompt.ID)
|
||||
a.confirmMu.Unlock()
|
||||
if dismissed {
|
||||
return
|
||||
}
|
||||
dismissed = true
|
||||
if dismiss != nil {
|
||||
dismiss(prompt.ID, reason)
|
||||
} else if emit == nil {
|
||||
a.emit("reims:confirm-resolved", ConfirmResolvedEvent{ID: prompt.ID, Reason: reason})
|
||||
}
|
||||
}
|
||||
defer clearPrompt("canceled")
|
||||
|
||||
if emit != nil {
|
||||
emit(prompt)
|
||||
} else {
|
||||
a.showMainWindow()
|
||||
a.emit("reims:confirm-request", prompt)
|
||||
}
|
||||
|
||||
timer := time.NewTimer(confirmPromptTimeout)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case res, open := <-ch:
|
||||
if !open {
|
||||
clearPrompt("canceled")
|
||||
return ConfirmResolution{Approved: false, Reason: "canceled"}, nil
|
||||
}
|
||||
reason := res.Reason
|
||||
if reason == "" {
|
||||
if res.Approved {
|
||||
reason = "approved"
|
||||
} else {
|
||||
reason = "denied"
|
||||
}
|
||||
}
|
||||
clearPrompt(reason)
|
||||
return res, nil
|
||||
case <-ctx.Done():
|
||||
clearPrompt("canceled")
|
||||
return ConfirmResolution{Approved: false, Reason: "canceled"}, ctx.Err()
|
||||
case <-timer.C:
|
||||
clearPrompt("timeout")
|
||||
if broker != nil {
|
||||
broker.Audit(pluginID, "CONFIRM_TIMEOUT", prompt.Kind)
|
||||
}
|
||||
return ConfirmResolution{Approved: false, Reason: "timeout"}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// ResolveConfirmRequest delivers the user's answer to a pending host confirmation dialog.
|
||||
func (a *App) ResolveConfirmRequest(id string, approved bool, durationMinutes int, untilPhaseExit bool) error {
|
||||
if approved && !untilPhaseExit && durationMinutes <= 0 {
|
||||
durationMinutes = 30
|
||||
}
|
||||
a.confirmMu.Lock()
|
||||
ch, ok := a.confirmPending[id]
|
||||
if !ok {
|
||||
a.confirmMu.Unlock()
|
||||
return errors.New("confirmation request has expired or was already resolved")
|
||||
}
|
||||
delete(a.confirmPending, id)
|
||||
select {
|
||||
case ch <- ConfirmResolution{
|
||||
Approved: approved,
|
||||
DurationMinutes: durationMinutes,
|
||||
UntilPhaseExit: untilPhaseExit,
|
||||
}:
|
||||
default:
|
||||
}
|
||||
a.confirmMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) cancelPendingConfirmations() {
|
||||
a.confirmMu.Lock()
|
||||
pending := a.confirmPending
|
||||
a.confirmPending = nil
|
||||
a.protectedPhaseGrants = nil
|
||||
a.protectedPhaseInFlight = nil
|
||||
a.confirmMu.Unlock()
|
||||
a.mu.Lock()
|
||||
emit := a.confirmEmit
|
||||
dismiss := a.confirmDismiss
|
||||
a.mu.Unlock()
|
||||
for id, ch := range pending {
|
||||
close(ch)
|
||||
if dismiss != nil {
|
||||
dismiss(id, "canceled")
|
||||
} else if emit == nil {
|
||||
a.emit("reims:confirm-resolved", ConfirmResolvedEvent{ID: id, Reason: "canceled"})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeGrantDuration(minutes int) time.Duration {
|
||||
switch minutes {
|
||||
case 10, 30, 60:
|
||||
return time.Duration(minutes) * time.Minute
|
||||
default:
|
||||
if minutes <= 0 {
|
||||
return 30 * time.Minute
|
||||
}
|
||||
if minutes > 120 {
|
||||
return 120 * time.Minute
|
||||
}
|
||||
return time.Duration(minutes) * time.Minute
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) recordProtectedPhaseGrant(broker *plugin.Broker, pluginID, vmKey, phase string, durationMinutes int, untilPhaseExit bool) {
|
||||
now := time.Now()
|
||||
grant := protectedPhaseGrant{
|
||||
pluginID: pluginID,
|
||||
vmKey: vmKey,
|
||||
phase: phase,
|
||||
grantedAt: now,
|
||||
untilPhaseExit: untilPhaseExit,
|
||||
}
|
||||
if !untilPhaseExit {
|
||||
grant.expiresAt = now.Add(normalizeGrantDuration(durationMinutes))
|
||||
}
|
||||
a.confirmMu.Lock()
|
||||
if a.protectedPhaseGrants == nil {
|
||||
a.protectedPhaseGrants = map[phaseGrantKey]protectedPhaseGrant{}
|
||||
}
|
||||
a.protectedPhaseGrants[phaseGrantKey{pluginID: pluginID, vmKey: vmKey}] = grant
|
||||
a.confirmMu.Unlock()
|
||||
if broker != nil {
|
||||
scope := fmt.Sprintf("%s:%dm", phase, durationMinutes)
|
||||
if untilPhaseExit {
|
||||
scope = phase + ":until_phase_exit"
|
||||
}
|
||||
broker.Audit(pluginID, "PHASE_AUTH_GRANTED", vmKey+" "+scope)
|
||||
}
|
||||
a.refreshAgentSessionVisuals(vmKey)
|
||||
}
|
||||
|
||||
func (a *App) recordProtectedPhaseDenial(mgr *plugin.Manager, broker *plugin.Broker, pluginID, vmKey, vmName, phase string) {
|
||||
now := time.Now()
|
||||
a.confirmMu.Lock()
|
||||
if a.protectedPhaseGrants == nil {
|
||||
a.protectedPhaseGrants = map[phaseGrantKey]protectedPhaseGrant{}
|
||||
}
|
||||
a.protectedPhaseGrants[phaseGrantKey{pluginID: pluginID, vmKey: vmKey}] = protectedPhaseGrant{
|
||||
pluginID: pluginID,
|
||||
vmKey: vmKey,
|
||||
phase: phase,
|
||||
grantedAt: now,
|
||||
expiresAt: now.Add(protectedPhaseDenialCooldown),
|
||||
denied: true,
|
||||
}
|
||||
a.confirmMu.Unlock()
|
||||
if broker != nil {
|
||||
broker.Audit(pluginID, "PHASE_AUTH_DENIED", vmKey+" "+phase)
|
||||
}
|
||||
a.handlePluginPermissionDeniedForVM(mgr, pluginID, vmKey, vmName, "confirmation_denied")
|
||||
}
|
||||
|
||||
// grantProtectedPhase records an in-memory #105 authorization directly from a
|
||||
// host-owned confirmation UI (for example the auto-install preflight flow).
|
||||
func (a *App) grantProtectedPhase(pluginID, vmKey, phase string, durationMinutes int, untilPhaseExit bool) {
|
||||
var broker *plugin.Broker
|
||||
a.mu.Lock()
|
||||
if a.pluginMgr != nil {
|
||||
broker = a.pluginMgr.Broker()
|
||||
}
|
||||
a.mu.Unlock()
|
||||
if phase == "" {
|
||||
phase = driver.PhaseInstaller
|
||||
}
|
||||
a.recordProtectedPhaseGrant(broker, pluginID, vmKey, phase, durationMinutes, untilPhaseExit)
|
||||
}
|
||||
|
||||
func (a *App) lookupProtectedPhaseGrant(pluginID, vmKey string) (protectedPhaseGrant, bool) {
|
||||
now := time.Now()
|
||||
key := phaseGrantKey{pluginID: pluginID, vmKey: vmKey}
|
||||
a.confirmMu.Lock()
|
||||
defer a.confirmMu.Unlock()
|
||||
g, ok := a.protectedPhaseGrants[key]
|
||||
if !ok {
|
||||
return protectedPhaseGrant{}, false
|
||||
}
|
||||
if g.denied && !g.isDeniedActive(now) {
|
||||
delete(a.protectedPhaseGrants, key)
|
||||
return protectedPhaseGrant{}, false
|
||||
}
|
||||
if !g.denied && !g.isActive(now) {
|
||||
delete(a.protectedPhaseGrants, key)
|
||||
return protectedPhaseGrant{pluginID: pluginID, vmKey: vmKey, phase: g.phase, expiresAt: g.expiresAt}, false
|
||||
}
|
||||
return g, true
|
||||
}
|
||||
|
||||
func (a *App) revokeProtectedPhaseForPluginVM(pluginID, vmKey, reason string) {
|
||||
a.confirmMu.Lock()
|
||||
var revoked []protectedPhaseGrant
|
||||
for k, g := range a.protectedPhaseGrants {
|
||||
if k.vmKey == vmKey && (pluginID == "" || k.pluginID == pluginID) {
|
||||
revoked = append(revoked, g)
|
||||
delete(a.protectedPhaseGrants, k)
|
||||
}
|
||||
}
|
||||
for k := range a.protectedPhaseInFlight {
|
||||
if k.vmKey == vmKey && (pluginID == "" || k.pluginID == pluginID) {
|
||||
delete(a.protectedPhaseInFlight, k)
|
||||
}
|
||||
}
|
||||
a.confirmMu.Unlock()
|
||||
var broker *plugin.Broker
|
||||
a.mu.Lock()
|
||||
if a.pluginMgr != nil {
|
||||
broker = a.pluginMgr.Broker()
|
||||
}
|
||||
a.mu.Unlock()
|
||||
if broker != nil {
|
||||
for _, g := range revoked {
|
||||
if !g.denied {
|
||||
broker.Audit(g.pluginID, "PHASE_AUTH_REVOKED", vmKey+" "+reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) revokeApprovedProtectedPhaseForPluginVM(pluginID, vmKey, reason string) {
|
||||
a.confirmMu.Lock()
|
||||
var revoked []protectedPhaseGrant
|
||||
for k, g := range a.protectedPhaseGrants {
|
||||
if k.vmKey == vmKey && (pluginID == "" || k.pluginID == pluginID) && !g.denied {
|
||||
revoked = append(revoked, g)
|
||||
delete(a.protectedPhaseGrants, k)
|
||||
}
|
||||
}
|
||||
a.confirmMu.Unlock()
|
||||
var broker *plugin.Broker
|
||||
a.mu.Lock()
|
||||
if a.pluginMgr != nil {
|
||||
broker = a.pluginMgr.Broker()
|
||||
}
|
||||
a.mu.Unlock()
|
||||
if broker != nil {
|
||||
for _, g := range revoked {
|
||||
broker.Audit(g.pluginID, "PHASE_AUTH_REVOKED", vmKey+" "+reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) revokeProtectedPhaseForVM(vmKey, reason string) {
|
||||
a.confirmMu.Lock()
|
||||
var revoked []protectedPhaseGrant
|
||||
for k, g := range a.protectedPhaseGrants {
|
||||
if k.vmKey == vmKey {
|
||||
revoked = append(revoked, g)
|
||||
delete(a.protectedPhaseGrants, k)
|
||||
}
|
||||
}
|
||||
for k := range a.protectedPhaseInFlight {
|
||||
if k.vmKey == vmKey {
|
||||
delete(a.protectedPhaseInFlight, k)
|
||||
}
|
||||
}
|
||||
a.confirmMu.Unlock()
|
||||
var broker *plugin.Broker
|
||||
a.mu.Lock()
|
||||
if a.pluginMgr != nil {
|
||||
broker = a.pluginMgr.Broker()
|
||||
}
|
||||
a.mu.Unlock()
|
||||
if broker != nil {
|
||||
for _, g := range revoked {
|
||||
if !g.denied {
|
||||
broker.Audit(g.pluginID, "PHASE_AUTH_REVOKED", vmKey+" "+reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) buildProtectedPhasePrompt(pluginID string, vm driver.VMInfo, phase string, preferUntilExit bool) ConfirmPrompt {
|
||||
loc := a.computerUseLocale()
|
||||
phaseLabel := i18n.M(loc, "err.computer_use.phase."+phase, nil)
|
||||
return ConfirmPrompt{
|
||||
Kind: "protected_phase",
|
||||
PluginID: pluginID,
|
||||
VM: vm.Ref().Key(),
|
||||
VMName: vm.Name,
|
||||
Phase: phase,
|
||||
Title: i18n.M(loc, "confirm.phase.title", i18n.Vars{"phase": phaseLabel}),
|
||||
Message: i18n.M(loc, "confirm.phase.message", i18n.Vars{"name": vm.Name, "phase": phaseLabel}),
|
||||
ConfirmLabel: i18n.T(loc, "confirm.phase.allow"),
|
||||
CancelLabel: i18n.T(loc, "confirm.phase.deny"),
|
||||
Danger: true,
|
||||
AllowDurationChoice: true,
|
||||
DefaultDurationMin: 30,
|
||||
PreferUntilPhaseExit: preferUntilExit,
|
||||
}
|
||||
}
|
||||
|
||||
// authorizeProtectedPhase enforces #105 for `installer` and `recovery` phases.
|
||||
// When blocking is false (ordinary host/console.* calls), an unauthorized call
|
||||
// triggers a native confirmation dialog asynchronously and returns
|
||||
// `confirmation_required` immediately. When blocking is true (explicit
|
||||
// host/session.begin requesting protected-phase auth), it waits for the user's
|
||||
// decision and returns nil or `confirmation_denied`.
|
||||
func (a *App) authorizeProtectedPhase(ctx context.Context, mgr *plugin.Manager, pluginID string, vm driver.VMInfo, phase string, blocking, preferUntilExit bool) error {
|
||||
if phase != driver.PhaseInstaller && phase != driver.PhaseRecovery {
|
||||
return nil
|
||||
}
|
||||
vmKeyStr := vm.Ref().Key()
|
||||
var broker *plugin.Broker
|
||||
var reg *plugin.Registry
|
||||
if mgr != nil {
|
||||
broker = mgr.Broker()
|
||||
reg = mgr.Registry()
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
key := phaseGrantKey{pluginID: pluginID, vmKey: vmKeyStr}
|
||||
a.confirmMu.Lock()
|
||||
g, exists := a.protectedPhaseGrants[key]
|
||||
if exists && g.denied && !g.isDeniedActive(now) {
|
||||
delete(a.protectedPhaseGrants, key)
|
||||
exists = false
|
||||
} else if exists && !g.denied && !g.isActive(now) {
|
||||
delete(a.protectedPhaseGrants, key)
|
||||
exists = false
|
||||
if broker != nil {
|
||||
broker.Audit(pluginID, "PHASE_AUTH_EXPIRED", vmKeyStr+" "+g.phase)
|
||||
}
|
||||
}
|
||||
a.confirmMu.Unlock()
|
||||
|
||||
if exists && g.isActive(now) && g.phase == phase {
|
||||
return nil
|
||||
}
|
||||
if exists && g.denied && !blocking {
|
||||
if a.hasActiveAgentSessionOwnedBy(vmKeyStr, pluginID) {
|
||||
a.handlePluginPermissionDeniedForVM(mgr, pluginID, vmKeyStr, vm.Name, "confirmation_denied")
|
||||
}
|
||||
return a.computerUseHostError("confirmation_denied", "err.computer_use.phase_denied", i18n.Vars{"name": vm.Name})
|
||||
}
|
||||
|
||||
prompt := a.buildProtectedPhasePrompt(pluginID, vm, phase, preferUntilExit)
|
||||
if blocking {
|
||||
res, err := a.requestHostConfirm(ctx, broker, reg, pluginID, prompt)
|
||||
if err != nil {
|
||||
a.handlePluginPermissionDeniedForVM(mgr, pluginID, vmKeyStr, vm.Name, "confirmation_denied")
|
||||
return err
|
||||
}
|
||||
if res.Approved {
|
||||
a.recordProtectedPhaseGrant(broker, pluginID, vmKeyStr, phase, res.DurationMinutes, res.UntilPhaseExit)
|
||||
return nil
|
||||
}
|
||||
a.recordProtectedPhaseDenial(mgr, broker, pluginID, vmKeyStr, vm.Name, phase)
|
||||
return a.computerUseHostError("confirmation_denied", "err.computer_use.phase_denied", i18n.Vars{"name": vm.Name})
|
||||
}
|
||||
|
||||
// Non-blocking path: trigger at most one in-flight confirmation dialog per (plugin, VM).
|
||||
a.confirmMu.Lock()
|
||||
if a.protectedPhaseInFlight == nil {
|
||||
a.protectedPhaseInFlight = map[phaseGrantKey]bool{}
|
||||
}
|
||||
alreadyInFlight := a.protectedPhaseInFlight[key]
|
||||
if !alreadyInFlight {
|
||||
a.protectedPhaseInFlight[key] = true
|
||||
}
|
||||
a.confirmMu.Unlock()
|
||||
|
||||
if !alreadyInFlight {
|
||||
go func() {
|
||||
defer func() {
|
||||
a.confirmMu.Lock()
|
||||
delete(a.protectedPhaseInFlight, key)
|
||||
a.confirmMu.Unlock()
|
||||
}()
|
||||
res, err := a.requestHostConfirm(context.Background(), broker, reg, pluginID, prompt)
|
||||
if err != nil {
|
||||
a.handlePluginPermissionDeniedForVM(mgr, pluginID, vmKeyStr, vm.Name, "confirmation_denied")
|
||||
return
|
||||
}
|
||||
if res.Approved {
|
||||
a.recordProtectedPhaseGrant(broker, pluginID, vmKeyStr, phase, res.DurationMinutes, res.UntilPhaseExit)
|
||||
} else {
|
||||
a.recordProtectedPhaseDenial(mgr, broker, pluginID, vmKeyStr, vm.Name, phase)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
phaseLabel := i18n.M(a.computerUseLocale(), "err.computer_use.phase."+phase, nil)
|
||||
return a.computerUseHostError("confirmation_required", "err.computer_use.phase_confirmation", i18n.Vars{"name": vm.Name, "phase": phaseLabel})
|
||||
}
|
||||
|
||||
// trackVMPhaseTransitions compares current VM phases against the last observed
|
||||
// values, broadcasts `vm/phaseChanged` to running Sidecars, and revokes
|
||||
// protected-phase authorizations whenever a VM leaves installer/recovery or stops.
|
||||
func (a *App) trackVMPhaseTransitions(vms []driver.VMListItem) {
|
||||
a.mu.Lock()
|
||||
var startingVMs map[string]bool
|
||||
if len(a.transitions) > 0 {
|
||||
startingVMs = make(map[string]bool, len(a.transitions))
|
||||
for k, tr := range a.transitions {
|
||||
if tr == "starting" || tr == "resuming" {
|
||||
startingVMs[k] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
a.mu.Unlock()
|
||||
|
||||
a.confirmMu.Lock()
|
||||
if a.lastVMPhases == nil {
|
||||
a.lastVMPhases = map[string]string{}
|
||||
}
|
||||
type transition struct {
|
||||
vmKey, driverID, name, from, to string
|
||||
stopped bool
|
||||
}
|
||||
var changes []transition
|
||||
seen := map[string]bool{}
|
||||
for _, vm := range vms {
|
||||
key := vmKeyForDriver(vm.DriverID, vm.Name)
|
||||
seen[key] = true
|
||||
phase := strings.TrimSpace(vm.Phase)
|
||||
if phase == "" {
|
||||
phase = driver.PhaseNormal
|
||||
}
|
||||
prev, hadPrev := a.lastVMPhases[key]
|
||||
if !hadPrev {
|
||||
a.lastVMPhases[key] = phase
|
||||
continue
|
||||
}
|
||||
if prev != phase {
|
||||
a.lastVMPhases[key] = phase
|
||||
changes = append(changes, transition{
|
||||
vmKey: key, driverID: vm.DriverID, name: vm.Name,
|
||||
from: prev, to: phase, stopped: vm.State != "running" && !startingVMs[key],
|
||||
})
|
||||
} else if vm.State == "stopped" || vm.State == "suspended" || vm.State == "broken" {
|
||||
// Skip revoking grants while a VM is actively transitioning into start/resume
|
||||
// (e.g. StartAutoInstall launching a stopped VM), otherwise ensure stopped VMs
|
||||
// never keep stale in-memory phase grants alive.
|
||||
if !(vm.State == "stopped" && startingVMs[key]) && a.hasProtectedPhaseGrantLocked(key) {
|
||||
changes = append(changes, transition{
|
||||
vmKey: key, driverID: vm.DriverID, name: vm.Name,
|
||||
from: prev, to: phase, stopped: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
var vanished []string
|
||||
for key := range a.lastVMPhases {
|
||||
if !seen[key] {
|
||||
delete(a.lastVMPhases, key)
|
||||
if a.hasProtectedPhaseGrantLocked(key) {
|
||||
vanished = append(vanished, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
a.confirmMu.Unlock()
|
||||
|
||||
for _, key := range vanished {
|
||||
a.revokeProtectedPhaseForVM(key, "vm_removed")
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
|
||||
for _, ch := range changes {
|
||||
if ch.stopped {
|
||||
a.revokeProtectedPhaseForVM(ch.vmKey, "vm_stopped")
|
||||
} else if (ch.from == driver.PhaseInstaller || ch.from == driver.PhaseRecovery) && ch.to != ch.from {
|
||||
a.revokeProtectedPhaseForVM(ch.vmKey, "left_protected_phase")
|
||||
}
|
||||
if ch.from != ch.to && mgr != nil {
|
||||
mgr.NotifyRunningSidecars("vm/phaseChanged", map[string]any{
|
||||
"vm": ch.vmKey,
|
||||
"driver_id": ch.driverID,
|
||||
"name": ch.name,
|
||||
"from": ch.from,
|
||||
"to": ch.to,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) hasProtectedPhaseGrantLocked(vmKey string) bool {
|
||||
for k, g := range a.protectedPhaseGrants {
|
||||
if k.vmKey == vmKey && !g.denied {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// revokeProtectedPhaseForInactivePlugins removes any in-memory protected-phase
|
||||
// grants held by plugins that are no longer active, even if they never opened
|
||||
// an Agent session (e.g. read-only screenshot or host/ui.confirm grants).
|
||||
func (a *App) revokeProtectedPhaseForInactivePlugins(reg *plugin.Registry, broker *plugin.Broker, reason string) {
|
||||
if reg == nil {
|
||||
return
|
||||
}
|
||||
var revoked []phaseGrantKey
|
||||
a.confirmMu.Lock()
|
||||
for k := range a.protectedPhaseGrants {
|
||||
if !reg.IsActive(k.pluginID) {
|
||||
delete(a.protectedPhaseGrants, k)
|
||||
revoked = append(revoked, k)
|
||||
}
|
||||
}
|
||||
a.confirmMu.Unlock()
|
||||
if broker != nil {
|
||||
for _, k := range revoked {
|
||||
broker.Audit(k.pluginID, "PHASE_AUTH_REVOKED", k.vmKey+" "+reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 346 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user