From e0ff794b0e7d6a5fdebbde25cb588087d2a6e3d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <105714958+Nwflower@users.noreply.github.com> Date: Sun, 6 Dec 2026 00:47:07 +0800 Subject: [PATCH 1/4] feat: add experimental macOS desktop support on Apple Silicon (#207) * feat: add experimental Apple Silicon support with Nivfold Integrate the standalone Nivfold protocol 1 runner; tested against Nivfold f436fb6. The Windows Reims vGPU runtime remains independent. * fix: open QQ invites and VM SSH on macOS * fix: move VM, View and Help to the macOS menu bar * feat(macos): add resumable Apple restore image downloads Expose the compatible restore image in the VM wizard and Images page, validate downloads before caching, and fix macOS memory reporting and plugin SVG rendering. * fix(macos): localize the native application menu * fix(macos): address native desktop review findings --- .github/changes/apple-virtualization.json | 7 + .../macos-catalog-and-titlebar-polish.json | 7 + .github/changes/macos-client-build.json | 7 + .../changes/macos-download-and-titlebar.json | 7 + .../macos-memory-and-plugin-icons.json | 7 + .github/changes/macos-menu-language.json | 7 + .../macos-native-application-menu.json | 7 + .github/changes/macos-qq-group-and-ssh.json | 7 + .github/changes/macos-review-reliability.json | 7 + .github/changes/nivfold-native-runtime.json | 7 + AGENTS.md | 2 + README.md | 20 + README.zh-CN.md | 20 + docs/architecture.md | 16 +- docs/design-guidelines.md | 2 +- docs/pr-review-guidelines.md | 1 + docs/testing.md | 4 +- frontend/scripts/test-application-menu.mjs | 78 +++ frontend/scripts/test-endpoints.mjs | 16 +- frontend/scripts/test-guest-drivers.mjs | 45 ++ frontend/scripts/test-restore-images.mjs | 36 ++ frontend/scripts/test-tasks.mjs | 33 +- frontend/src/App.tsx | 172 +++--- frontend/src/components/AboutPage.tsx | 37 +- frontend/src/components/AppDialogs.tsx | 9 +- frontend/src/components/CreateWizard.tsx | 132 +++-- frontend/src/components/HostView.tsx | 44 +- frontend/src/components/LogPanel.tsx | 10 +- .../src/components/RestoreImageSource.tsx | 137 +++++ frontend/src/components/SchemaForm.tsx | 37 +- frontend/src/components/TitleMenus.tsx | 201 +++---- frontend/src/components/VMPage.tsx | 45 +- frontend/src/i18n/domains/core.gen.ts | 46 +- frontend/src/i18n/domains/settings.gen.ts | 18 +- frontend/src/i18n/domains/wizard.gen.ts | 10 + frontend/src/i18n/keys.gen.ts | 29 + frontend/src/lib/endpoints.ts | 13 +- frontend/src/lib/guestDrivers.ts | 33 ++ frontend/src/lib/restoreImages.ts | 41 ++ frontend/src/lib/tasks.ts | 19 +- frontend/src/lib/titleMenu.ts | 134 +++++ frontend/src/macos/ApplicationMenu.tsx | 70 +++ frontend/src/macos/InstallersPage.tsx | 70 ++- frontend/src/macos/applicationMenuModel.ts | 49 ++ frontend/src/styles/app.css | 7 + frontend/src/types.ts | 2 +- frontend/src/wails.ts | 1 + frontend/wailsjs/go/app/App.d.ts | 2 + frontend/wailsjs/go/app/App.js | 4 + frontend/wailsjs/go/models.ts | 20 + internal/app/app.go | 75 +-- internal/app/application_menu.go | 72 +++ internal/app/application_menu_darwin.go | 42 ++ internal/app/application_menu_darwin.m | 120 +++++ internal/app/application_menu_other.go | 9 + internal/app/application_menu_test.go | 35 ++ internal/app/endpoints_flow_test.go | 18 + internal/app/extras_flow.go | 4 + internal/app/installer_bindings.go | 92 +++- internal/app/installer_coordinator.go | 2 +- internal/app/lifecycle_flow_test.go | 35 ++ internal/app/plugins_flow.go | 72 ++- internal/app/qqgroup.go | 11 +- internal/app/qqgroup_darwin.go | 53 ++ internal/app/qqgroup_darwin_test.go | 24 + internal/app/qqgroup_other.go | 2 +- internal/app/qqgroup_test.go | 12 + internal/app/qqgroup_windows.go | 12 +- internal/app/quit_no_tray_test.go | 21 + internal/app/ssh_flow.go | 34 +- internal/app/tasks.go | 13 +- internal/app/thumbnail_flow.go | 27 +- internal/archtest/file_replace_test.go | 1 + internal/archtest/macos_boundary_test.go | 8 + internal/archtest/sources_test.go | 2 +- internal/archtest/unused_test.go | 6 + internal/cli/apple_vz_test.go | 55 ++ internal/cli/cli.go | 119 +++-- internal/cli/macos_native.go | 88 +++ internal/cli/plugin.go | 6 +- internal/cli/plugin_test.go | 5 +- internal/cli/start.go | 4 +- internal/driver/driver.go | 6 + internal/fetch/validated.go | 264 +++++++++ internal/fetch/validated_test.go | 288 ++++++++++ internal/host/host.go | 51 +- internal/host/host_windows.go | 1 + internal/host/memory_darwin.go | 22 + internal/host/memory_darwin_cgo.go | 27 + internal/host/memory_darwin_nocgo.go | 5 + internal/host/memory_darwin_test.go | 28 + internal/host/resources_darwin.go | 35 ++ internal/host/resources_darwin_test.go | 30 ++ internal/host/resources_other.go | 5 + internal/host/stubs_hardware_other.go | 4 +- internal/i18n/catalog_gen.go | 70 ++- internal/macos/applevz/config.go | 216 ++++++++ internal/macos/applevz/driver.go | 147 ++++++ internal/macos/applevz/lifecycle.go | 176 ++++++ internal/macos/applevz/platform_darwin.go | 35 ++ internal/macos/applevz/platform_other.go | 22 + internal/macos/applevz/resources.go | 42 ++ internal/macos/applevz/restore.go | 59 +++ internal/macos/applevz/runner.go | 370 +++++++++++++ internal/macos/applevz/runner_test.go | 499 ++++++++++++++++++ internal/macos/applevz/storage.go | 318 +++++++++++ internal/macos/applevz/storage_test.go | 110 ++++ internal/macos/guest/apple_vz.go | 54 ++ internal/macos/guest/register.go | 25 +- internal/macos/installer/restore_image.go | 314 +++++++++++ .../macos/installer/restore_image_test.go | 223 ++++++++ internal/plugin/builtin/bootstrap.go | 4 +- internal/plugin/icon_test.go | 20 + internal/plugin/types.go | 3 +- internal/plugin/uiassets/assets.go | 11 + internal/plugin/uiassets/assets_test.go | 61 +++ internal/tray/tray_other.go | 3 +- link_darwin.go | 9 + locales/en-US/core.json | 23 +- locales/en-US/native.json | 11 + locales/en-US/settings.json | 9 +- locales/en-US/wizard.json | 5 + locales/zh-CN/core.json | 23 +- locales/zh-CN/native.json | 11 + locales/zh-CN/settings.json | 9 +- locales/zh-CN/wizard.json | 5 + main.go | 9 +- scripts/build-macos.mjs | 54 ++ scripts/check-nivfold.mjs | 17 + scripts/test.mjs | 7 +- 130 files changed, 6014 insertions(+), 540 deletions(-) create mode 100644 .github/changes/apple-virtualization.json create mode 100644 .github/changes/macos-catalog-and-titlebar-polish.json create mode 100644 .github/changes/macos-client-build.json create mode 100644 .github/changes/macos-download-and-titlebar.json create mode 100644 .github/changes/macos-memory-and-plugin-icons.json create mode 100644 .github/changes/macos-menu-language.json create mode 100644 .github/changes/macos-native-application-menu.json create mode 100644 .github/changes/macos-qq-group-and-ssh.json create mode 100644 .github/changes/macos-review-reliability.json create mode 100644 .github/changes/nivfold-native-runtime.json create mode 100644 frontend/scripts/test-application-menu.mjs create mode 100644 frontend/scripts/test-guest-drivers.mjs create mode 100644 frontend/scripts/test-restore-images.mjs create mode 100644 frontend/src/components/RestoreImageSource.tsx create mode 100644 frontend/src/lib/guestDrivers.ts create mode 100644 frontend/src/lib/restoreImages.ts create mode 100644 frontend/src/lib/titleMenu.ts create mode 100644 frontend/src/macos/ApplicationMenu.tsx create mode 100644 frontend/src/macos/applicationMenuModel.ts create mode 100644 internal/app/application_menu.go create mode 100644 internal/app/application_menu_darwin.go create mode 100644 internal/app/application_menu_darwin.m create mode 100644 internal/app/application_menu_other.go create mode 100644 internal/app/application_menu_test.go create mode 100644 internal/app/qqgroup_darwin.go create mode 100644 internal/app/qqgroup_darwin_test.go create mode 100644 internal/app/quit_no_tray_test.go create mode 100644 internal/cli/apple_vz_test.go create mode 100644 internal/fetch/validated.go create mode 100644 internal/fetch/validated_test.go create mode 100644 internal/host/memory_darwin.go create mode 100644 internal/host/memory_darwin_cgo.go create mode 100644 internal/host/memory_darwin_nocgo.go create mode 100644 internal/host/memory_darwin_test.go create mode 100644 internal/host/resources_darwin.go create mode 100644 internal/host/resources_darwin_test.go create mode 100644 internal/host/resources_other.go create mode 100644 internal/macos/applevz/config.go create mode 100644 internal/macos/applevz/driver.go create mode 100644 internal/macos/applevz/lifecycle.go create mode 100644 internal/macos/applevz/platform_darwin.go create mode 100644 internal/macos/applevz/platform_other.go create mode 100644 internal/macos/applevz/resources.go create mode 100644 internal/macos/applevz/restore.go create mode 100644 internal/macos/applevz/runner.go create mode 100644 internal/macos/applevz/runner_test.go create mode 100644 internal/macos/applevz/storage.go create mode 100644 internal/macos/applevz/storage_test.go create mode 100644 internal/macos/guest/apple_vz.go create mode 100644 internal/macos/installer/restore_image.go create mode 100644 internal/macos/installer/restore_image_test.go create mode 100644 internal/plugin/uiassets/assets_test.go create mode 100644 link_darwin.go create mode 100644 scripts/build-macos.mjs create mode 100644 scripts/check-nivfold.mjs diff --git a/.github/changes/apple-virtualization.json b/.github/changes/apple-virtualization.json new file mode 100644 index 0000000..7be3cfa --- /dev/null +++ b/.github/changes/apple-virtualization.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." +} diff --git a/.github/changes/macos-catalog-and-titlebar-polish.json b/.github/changes/macos-catalog-and-titlebar-polish.json new file mode 100644 index 0000000..6f02203 --- /dev/null +++ b/.github/changes/macos-catalog-and-titlebar-polish.json @@ -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." +} diff --git a/.github/changes/macos-client-build.json b/.github/changes/macos-client-build.json new file mode 100644 index 0000000..1d60ed8 --- /dev/null +++ b/.github/changes/macos-client-build.json @@ -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." +} diff --git a/.github/changes/macos-download-and-titlebar.json b/.github/changes/macos-download-and-titlebar.json new file mode 100644 index 0000000..f288ec5 --- /dev/null +++ b/.github/changes/macos-download-and-titlebar.json @@ -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." +} diff --git a/.github/changes/macos-memory-and-plugin-icons.json b/.github/changes/macos-memory-and-plugin-icons.json new file mode 100644 index 0000000..9af7f51 --- /dev/null +++ b/.github/changes/macos-memory-and-plugin-icons.json @@ -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." +} diff --git a/.github/changes/macos-menu-language.json b/.github/changes/macos-menu-language.json new file mode 100644 index 0000000..b043dff --- /dev/null +++ b/.github/changes/macos-menu-language.json @@ -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." +} diff --git a/.github/changes/macos-native-application-menu.json b/.github/changes/macos-native-application-menu.json new file mode 100644 index 0000000..f146e76 --- /dev/null +++ b/.github/changes/macos-native-application-menu.json @@ -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." +} diff --git a/.github/changes/macos-qq-group-and-ssh.json b/.github/changes/macos-qq-group-and-ssh.json new file mode 100644 index 0000000..fe7e09c --- /dev/null +++ b/.github/changes/macos-qq-group-and-ssh.json @@ -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." +} diff --git a/.github/changes/macos-review-reliability.json b/.github/changes/macos-review-reliability.json new file mode 100644 index 0000000..f3eb5dc --- /dev/null +++ b/.github/changes/macos-review-reliability.json @@ -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." +} diff --git a/.github/changes/nivfold-native-runtime.json b/.github/changes/nivfold-native-runtime.json new file mode 100644 index 0000000..805e9cc --- /dev/null +++ b/.github/changes/nivfold-native-runtime.json @@ -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." +} diff --git a/AGENTS.md b/AGENTS.md index 7de0e7f..029478b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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/`。 diff --git a/README.md b/README.md index 83da74e..a14d655 100644 --- a/README.md +++ b/README.md @@ -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. + ## FAQ diff --git a/README.zh-CN.md b/README.zh-CN.md index 93b42d0..dd96804 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -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。 + ## 常见问题 diff --git a/docs/architecture.md b/docs/architecture.md index 4caff99..c514f4c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -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 路径。多语言词表在编译期同时生成前后端字典,默认跟随系统语言并支持通过声明式语言包扩展。 ## 核心机制与安全边界 @@ -85,7 +85,7 @@ Npcap 桥接由可停用的内置扩展提供,通过逐台虚拟机的本地 U ### 托管型与进程型客体驱动 -客体驱动按虚拟机进程的归属分为两类。进程型驱动让宿主拉起虚拟机进程,宿主据此判断运行状态、定位显示窗口并绑定处理器核心。托管型驱动在声明中带有 `hosted` 能力,虚拟机由驱动自己的管理层运行,宿主不探测其进程与窗口,也不提供全屏和绑核入口;仅当驱动同时声明控制台能力时才开放截屏与键入。 +客体驱动按虚拟机进程的归属分为两类。进程型驱动让宿主拉起虚拟机进程,宿主据此判断运行状态、定位显示窗口并绑定处理器核心。托管型驱动在声明中带有 `hosted` 能力,虚拟机由驱动自己的管理层运行。宿主不探测托管型驱动的进程与窗口。声明查看窗口能力的驱动可自行唤出查看器。宿主不提供全屏和绑核入口;仅当驱动同时声明控制台能力时才开放截屏与键入。 托管型驱动通过宿主接口主动推送虚拟机的生命周期状态、就绪状态、所处阶段与客体系统信息。电源状态仍只取 `stopped`、`starting`、`running`、`stopping`、`suspended`、`broken` 与 `driver_unavailable`,就绪与阶段是独立字段,因此仍在启动中的客体显示为运行中但未就绪。推送缺失或过期时,宿主回退为向驱动查询。推送只对驱动自己名下的虚拟机生效。 @@ -111,6 +111,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) diff --git a/docs/design-guidelines.md b/docs/design-guidelines.md index bc5ac85..7294a05 100644 --- a/docs/design-guidelines.md +++ b/docs/design-guidelines.md @@ -35,7 +35,7 @@ ## 布局层级与视觉基线 -窗口由左侧可折叠侧栏(`Ctrl+B`)、右侧主内容区、底部常驻状态栏与可收起日志抽屉(`Ctrl+L`)组成。侧栏上方列出虚拟机实例与新建入口(`Ctrl+N`),下方固定提供「镜像」「插件」「内核」「设置」(`Ctrl+,`)与「关于」入口。虚拟机操作按钮固定在详情页头而非全局标题栏,避免切换页面时顶栏跳动。 +窗口由左侧可折叠侧栏(`Ctrl+B`)、右侧主内容区、底部常驻状态栏与可收起日志抽屉(`Ctrl+L`)组成。侧栏上方列出虚拟机实例与新建入口(`Ctrl+N`),下方固定提供「镜像」「插件」「内核」「设置」(`Ctrl+,`)与「关于」入口。虚拟机操作按钮固定在详情页头而非全局标题栏,避免切换页面时顶栏跳动。macOS 在系统菜单栏提供「虚拟机」「视图」和「帮助」菜单,应用及标准菜单均跟随界面语言,使用 `Command` 组合键;`Command+,` 打开应用设置,原有 `Ctrl` 快捷键仍可在窗口中使用。Windows 在窗口标题栏提供这三项菜单。 - 同一项硬件规格或运行状态在同一视图内只展示一次,相同动作不在同屏提供两个按钮出口。 - 页面只用单层分组容器或留白表达层级,禁止卡片嵌套卡片;下拉选择统一使用自绘弹出控件,不混用系统原生表单控件。 diff --git a/docs/pr-review-guidelines.md b/docs/pr-review-guidelines.md index 656b665..453671f 100644 --- a/docs/pr-review-guidelines.md +++ b/docs/pr-review-guidelines.md @@ -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#便携运行时与跨仓边界)。 | diff --git a/docs/testing.md b/docs/testing.md index f1a3dc2..5ed4c13 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -12,6 +12,8 @@ | 跨模块改动或提 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`,验证安装、首次启动、重新显示窗口和正常关机。执行客体图形安装向导前必须确认。 diff --git a/frontend/scripts/test-application-menu.mjs b/frontend/scripts/test-application-menu.mjs new file mode 100644 index 0000000..26e2e95 --- /dev/null +++ b/frontend/scripts/test-application-menu.mjs @@ -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']) +}) diff --git a/frontend/scripts/test-endpoints.mjs b/frontend/scripts/test-endpoints.mjs index 076db6d..a6af764 100644 --- a/frontend/scripts/test-endpoints.mjs +++ b/frontend/scripts/test-endpoints.mjs @@ -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) diff --git a/frontend/scripts/test-guest-drivers.mjs b/frontend/scripts/test-guest-drivers.mjs new file mode 100644 index 0000000..5d8cfec --- /dev/null +++ b/frontend/scripts/test-guest-drivers.mjs @@ -0,0 +1,45 @@ +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('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) +}) diff --git a/frontend/scripts/test-restore-images.mjs b/frontend/scripts/test-restore-images.mjs new file mode 100644 index 0000000..e0d1be3 --- /dev/null +++ b/frontend/scripts/test-restore-images.mjs @@ -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) +}) diff --git a/frontend/scripts/test-tasks.mjs b/frontend/scripts/test-tasks.mjs index 7629b25..720e0ff 100644 --- a/frontend/scripts/test-tasks.mjs +++ b/frontend/scripts/test-tasks.mjs @@ -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 }) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 69c7496..373a78f 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -4,7 +4,9 @@ import type { WizardDraft } from './components/CreateWizard' import { AppDialogs } from './components/AppDialogs' 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 +15,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 { 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,7 +34,7 @@ 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, CachedInstaller, CreateOpts, DriverSummary, Locale, PluginUIContributions, 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' @@ -48,6 +51,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 +107,15 @@ const failKey: Record = { export const App: React.FC = () => { const [state, setState] = useState(null) + const [nativeMenuReady, setNativeMenuReady] = useState(false) const [selected, setSelectedPage] = useState(HOST_ID) const [detail, setDetail] = useState(null) // GetVMInfo for the selected non-macOS VM; macOS VMs use `detail` (GetVMDetail). const [vmInfoLoaded, setVMInfoLoaded] = useState(null) const [detailRevision, setDetailRevision] = useState(0) const [showWizard, setShowWizard] = useState(false) + const [wizardDrivers, setWizardDrivers] = useState([]) + const loadingWizardDrivers = useRef(false) const [wizardDraft, setWizardDraft] = useState(null) const [pendingCreates, setPendingCreates] = useState([]) const [showSettings, setShowSettings] = useState(false) @@ -488,7 +498,8 @@ export const App: React.FC = () => { const pending = selectedVM ? (state?.pending_changes[vmRefKey(selectedVM)] ?? []) : [] const fixedModeSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'display-fixed-mode') ?? false const diskCacheSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'win32-native-aio') ?? false - const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime + const nativeHost = isAppleSilicon(state?.host) + const hostReady = !!state && (nativeHost ? !!state.host.apple_virtualization?.ready : state.host.whpx === 'ready' && !!state.active_runtime) const canSuspend = state?.can_suspend ?? false const fullscreenHotkey = state?.config.fullscreen_hotkey_enabled ? resolveFullscreenHotkey(state.config.fullscreen_hotkey) @@ -595,14 +606,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) ? '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 @@ -787,15 +798,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,13 +812,10 @@ 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 @@ -883,9 +882,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 +891,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 +939,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) + 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) ? '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' @@ -1109,47 +1130,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 ( + {nativeTitlebar && 0), + selectedVMKey: selectedVM && vmRefKey(selectedVM), + vmSettingsReady: !!detail && detail.name === selectedVM?.name, + }} />}
+ {onCopy && ( +
diff --git a/frontend/src/components/AppDialogs.tsx b/frontend/src/components/AppDialogs.tsx index ac13144..c736f3f 100644 --- a/frontend/src/components/AppDialogs.tsx +++ b/frontend/src/components/AppDialogs.tsx @@ -8,7 +8,7 @@ import { I18nKey, t } from '../i18n' import { latestVMStats } from '../lib/vmStats' import { vmRefKey } from '../lib/vmRef' import type { PluginViewRoute } from '../lib/pluginViewRouter' -import type { AppState, CreateOpts, Locale, Task, VMDetail, VMListItem, ViewContribution } from '../types' +import type { AppState, CreateOpts, DriverSummary, Locale, Task, VMDetail, VMListItem, ViewContribution } from '../types' import { Button } from '../ui/controls' import { ConfirmDialog, Modal } from '../ui/dialog' import type { ToastInput } from '../ui/toast' @@ -33,7 +33,9 @@ interface AppDialogsProps { showWizard: boolean wizardDraft: WizardDraft | null + wizardDrivers: DriverSummary[] onCloseWizard: () => void + onDriverCreated: (driverID: string, name: string) => void onSubmitCreate: (payload: CreateOpts, draft: WizardDraft) => void showSettings: boolean @@ -87,7 +89,7 @@ export const AppDialogs: React.FC = (props) => { const { locale, state, detail, selectedVM, selectedIsMacOS, effectiveState, fixedModeSupported, diskCacheSupported, runningVMCount, tasks, displayNames, - showWizard, wizardDraft, onCloseWizard, onSubmitCreate, + showWizard, wizardDraft, wizardDrivers, onCloseWizard, onDriverCreated, onSubmitCreate, showSettings, onCloseSettings, onSavedSettings, affinityTarget, affinityVersion, onOpenAffinity, onCloseAffinity, onAffinityApplied, updateConfirming, updateLatest, onCancelInstallUpdate, onConfirmInstallUpdate, @@ -109,11 +111,14 @@ export const AppDialogs: React.FC = (props) => { diff --git a/frontend/src/components/CreateWizard.tsx b/frontend/src/components/CreateWizard.tsx index 483eb90..bc05f04 100644 --- a/frontend/src/components/CreateWizard.tsx +++ b/frontend/src/components/CreateWizard.tsx @@ -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' @@ -45,30 +45,33 @@ import { toggleWizardBorderless, } from '../lib/displayResolution' import { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, Task, ValidationIssue, VMNetworkSettings } from '../types' -import { findActiveOfflineTask, taskInstallerPhase } from '../lib/tasks' +import { findActiveInstallerTask, findRunningRestoreTask, taskInstallerPhase, taskStopAction, taskTitle } from '../lib/tasks' +import { isMacOSDriver } 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' 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 tasks?: Task[] draft?: WizardDraft | null + onCancelTask: (id: string) => Promise 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 } @@ -93,7 +96,7 @@ const SOURCES: { mode: 'offline' | 'apple' | 'installer' | 'disk'; icon: LucideI { mode: 'disk', icon: HardDrive, title: 'srcDiskTitle', sub: 'srcDiskSub' }, ] -export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported = false, captureSupported = false, tasks = [], draft, onClose, onSubmit }) => { +export const CreateWizard: React.FC = ({ locale, host, drivers, fixedModeSupported = false, captureSupported = false, tasks = [], draft, onCancelTask, onClose, onDriverCreated, onSubmit }) => { const tr = (k: I18nKey, v?: Record) => 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 +105,23 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported const [err, setErr] = useState('') const [issues, setIssues] = useState([]) const [cmdPreview, setCmdPreview] = useState('') - const [drivers, setDrivers] = useState([]) - const [driverID, setDriverID] = useState(BUILTIN_MACOS_DRIVER) + const [driverID, setDriverID] = useState(() => defaultGuestDriver(drivers, host, draft?.restoreImage ? 'ipsw' : draft?.opts ? 'offline' : undefined)?.id ?? '') const [driverOpts, setDriverOpts] = useState>({}) + 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 [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 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(draft?.opts ?? { - name: 'macos-tahoe', + name: draft?.name ?? 'macos-tahoe', dir: '', // 离线安装默认关闭网络,减少恢复环境依赖;用户仍可在第 4 步改为 NAT 或桥接。 source_mode: 'offline', @@ -150,17 +151,17 @@ export const CreateWizard: React.FC = ({ 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) => setOpts((o) => ({ ...o, ...patch })) const networkMode = opts.network_mode ?? (opts.network ? 'nat' : 'off') const [networkAdapters, setNetworkAdapters] = useState(null) const [networkError, setNetworkError] = useState(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 +171,7 @@ export const CreateWizard: React.FC = ({ 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 +219,7 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported const [cached, setCached] = useState([]) 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 +230,9 @@ export const CreateWizard: React.FC = ({ 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 +247,7 @@ export const CreateWizard: React.FC = ({ 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 +263,7 @@ export const CreateWizard: React.FC = ({ 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')) @@ -290,11 +291,11 @@ export const CreateWizard: React.FC = ({ 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 ( - - }
- {err &&
{err}
} + {err &&
{err}
} + {restoreTask && ( +
+ {taskTitle(locale, restoreTask)} + = 0 ? restoreTask.percent : undefined} /> +
+ )}
{step === 1 && ( @@ -324,6 +331,7 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported = ({ 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('') }} /> } /> )} - {isCustomDriver ? ( + {!activeDriver ?
{tr('wizardNoDriver')}
: !legacyDriver ? (
+ {restoreField && } set({ name: e.target.value })} />} + disabled={driverCreating} + control={ set({ name: e.target.value })} />} /> {activeDriver.create_schema && ( hasRestoreImagePicker(activeDriver, prop), + pick: (label) => api.PickFile(label, '*.ipsw'), + } : undefined} /> )} @@ -703,7 +730,7 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported {networkAdapters?.length === 0 && {tr('bridgeNoAdapters')}}
} />} {networkMode === 'bridge' && <> - setDependencyRefresh((value) => value + 1)} /> + setDependencyRefresh((value) => value + 1)} /> {networkPlanning &&
{tr('bridgePlanPending')}
} } @@ -779,26 +806,39 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported
- - {isCustomDriver ? ( + {legacyDriver && } + {restoreTask && ( + + )} + {!legacyDriver ? (
- {(state.vms?.length ?? 0) === 0 && host.whpx === 'ready' && !!state.active_runtime && onNewVM && ( + {(state.vms?.length ?? 0) === 0 && hostReady && onNewVM && (

{tr('welcomeTitle')}

{tr('welcomeSub')}

@@ -124,14 +132,14 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onNewVM, o
- - {tr('whpxTitle')} + + {tr(nativeHost ? 'appleVirtualizationTitle' : 'whpxTitle')}
-
{whpx.short}
- {whpx.canEnable ? ( +
{virtualization.short}
+ {virtualization.canEnable ? ( - ) : whpx.hint ? ( -
{whpx.hint}
+ ) : virtualization.hint ? ( +
{virtualization.hint}
) : null}
@@ -149,13 +157,17 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onNewVM, o {tr('hostRAM')}
-
{tr('hostRAMAvail', { n: host.avail_ram_gb.toFixed(1) })}
-
+
+ {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) }) : '—'} +
+ {host.memory_usage_known &&
{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}` : ''}` : ''} -
+
}
@@ -201,7 +213,7 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onNewVM, o ) })()} -
+ {!nativeHost &&
{tr('hostRuntime')}
))}
-
+ } -
+ {!nativeHost &&
{tr('hostGPUs')}
{realGPUs.length === 0 ? ( @@ -296,7 +308,7 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onNewVM, o }) )}
-
+
} {(host.displays?.length ?? 0) > 0 && (
{tr('hostDisplays')}
diff --git a/frontend/src/components/LogPanel.tsx b/frontend/src/components/LogPanel.tsx index f25c456..6257a11 100644 --- a/frontend/src/components/LogPanel.tsx +++ b/frontend/src/components/LogPanel.tsx @@ -111,13 +111,7 @@ export const LogPanel: React.FC = ({ 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 +241,7 @@ export const LogPanel: React.FC = ({ )} - {host.total_ram_gb > 0 && ( + {host.memory_usage_known && host.total_ram_gb > 0 && ( void + onCancelTask: (id: string) => Promise +} + +export function RestoreImageSource({ locale, host, tasks, initialImage, disabled, selectedPath, onPathChange, onCancelTask }: Props) { + const [source, setSource] = useState('apple') + const [localPath, setLocalPath] = useState('') + const [cached, setCached] = useState(() => initialImage ? [initialImage] : []) + const [latest, setLatest] = useState() + 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[1], vars?: Record) => 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, fn: () => Promise) => { + setPending(action) + setActionErr('') + try { + await fn() + } catch (error) { + setActionErr(parseAppError(error).summary) + } finally { + setPending('') + } + } + + return ( + <> +
+ {(['apple', 'local'] as const).map((mode) => { + const apple = mode === 'apple' + const Icon = apple ? CloudDownload : Disc3 + return + })} +
+ {actionErr &&
{actionErr}
} + {local ? + + setLocalPath(e.target.value)} /> + +
+ } /> + : + {choices.length > 0 && ({ value: choice.key, label: choice.label }))} /> + } />} + {active ? + = 0 ? active.percent : undefined} /> + {active.cancelable && } + + } /> : complete ? : currentRelease && } busy={pending === 'download'} disabled={!!pending || lowSpace} onClick={() => doAction('download', async () => { await api.DownloadInstaller(currentRelease.version) })}>{tr(partial ? 'installersResume' : 'installersDownload')} + } />} + {(releaseErr || cacheErr) &&
+ {releaseErr || cacheErr} + +
} + {!releaseErr && latest === undefined && !complete &&

{tr('offlineLoading')}

} + {!releaseErr && latest === null && choices.length === 0 &&

{tr('srcIPSWNone')}

} +
} + + ) +} diff --git a/frontend/src/components/SchemaForm.tsx b/frontend/src/components/SchemaForm.tsx index 6e9c73f..3ed711f 100644 --- a/frontend/src/components/SchemaForm.tsx +++ b/frontend/src/components/SchemaForm.tsx @@ -1,8 +1,10 @@ -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' interface Props { @@ -13,6 +15,10 @@ interface Props { groupFilter?: string onChange: (next: Record, patch: Record) => void hideGroupHeader?: boolean + 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 } } const SECRET_MASK = '••••••••' @@ -20,13 +26,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 = ({ - locale, schema, values, scopeFilter, groupFilter, onChange, hideGroupHeader, + locale, schema, values, scopeFilter, groupFilter, onChange, hideGroupHeader, hideFields, 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 +143,7 @@ export const SchemaForm: React.FC = ({ ) } - return ( + const textInput = ( = ({ onChange={(e) => setKey(k, e.target.value)} /> ) + if (!filePicker?.supports(prop)) return textInput + return ( +
+ {textInput} + +
+ ) } const rows = keys.map((k) => { @@ -154,6 +181,8 @@ export const SchemaForm: React.FC = ({ {badge}{desc ? {desc} : null} : undefined} control={renderControl(k, prop)} /> diff --git a/frontend/src/components/TitleMenus.tsx b/frontend/src/components/TitleMenus.tsx index e1c7907..1dee076 100644 --- a/frontend/src/components/TitleMenus.tsx +++ b/frontend/src/components/TitleMenus.tsx @@ -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 & { mac?: boolean; disabled?: boolean }) { + const label = t(locale, sidebarOpen ? 'hideSidebar' : 'showSidebar') + return ( + + + + ) } /** @@ -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 = ({ - 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) => t(locale, k, v) +export const TitleMenus: React.FC = (props) => { + const { locale, vm, themeMode } = props const [menuState, setMenuState] = useState<{ id: MenuId | null; switched: boolean }>({ id: null, switched: false }) const openRef = useRef(null) const navRef = useRef(null) @@ -70,36 +41,55 @@ export const TitleMenus: React.FC = ({ } 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 } = {}) => ( - - {label} - {opts.shortcut && {opts.shortcut}} - - ) - const check = (label: string, checked: boolean, onSelect: () => void, shortcut?: string) => ( - - - {label} - {shortcut && {shortcut}} - - ) + const renderRow = (row: MenuRow, index: number) => { + if (row.kind === 'separator') return + if (row.kind === 'label') return {row.label} + const onSelect = () => runMenuCommand(props, row.command) + const label = {row.label} + const shortcut = row.shortcut && {row.shortcut} + const indicator = + if (row.kind === 'radio') return ( + + {indicator}{label} + + ) + if (row.kind === 'check') return ( + + {indicator}{label}{shortcut} + + ) + return ( + + {label}{shortcut} + + ) + } + + 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)} + { + const row = radioRows.find((entry) => entry.kind === 'radio' && entry.command === value) + if (row?.kind === 'radio') runMenuCommand(props, row.command) + }}> + {radioRows.map(renderRow)} + + {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) => ( = ({ return (
e.stopPropagation()}> - - - -
) diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index e37a515..03ba5d2 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -31,7 +31,7 @@ import { endpointKey, guestFamilyOf, isMacOSDriver as isMacOSDriverID, - splitEndpoints, + primaryVMAccess, vmFeatures, } from '../lib/endpoints' import { useVMStats } from '../lib/vmStats' @@ -163,9 +163,8 @@ export const VMPage: React.FC = ({ 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 +241,23 @@ export const VMPage: React.FC = ({ primary = } 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 = ( - - - - ) - } - } else { + if (promotedEndpoint) { + const action = defaultEndpointAction(promotedEndpoint.kind) + const label = action ? endpointActionLabel(promotedEndpoint.kind, action) : endpointKindLabel(promotedEndpoint.kind) + primary = ( + + + + ) + } else if (access?.kind === 'window') { primary = ( ) } + if (missingRestorePath(r)) return {tr('installersCacheUnavailable')} + if (releaseKind === 'ipsw' && cacheError) return return ( - ) } - const releaseMeta = (r: Release) => ( -
- {r.posted} · {gb(r.size)} - {spaceShort(r) && · {tr('installersNoSpace', { need: Math.ceil(needBytes(r) / 1e9), free: host.free_disk_gb.toFixed(0) })}} + const releaseMeta = (r: Release) => { + const details = [r.posted, r.size > 0 ? gb(r.size) : ''].filter(Boolean).join(' · ') + if (!details) return null + return
+ {details} + {spaceShort(r) && · {tr('installersNoSpace', { need: Math.ceil(remainingGB(r)), free: host.free_disk_gb.toFixed(0) })}}
- ) + } const matchedTaskIDs = new Set() - 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,13 +253,13 @@ export const InstallersPage: React.FC = ({ 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, } } @@ -302,6 +319,7 @@ export const InstallersPage: React.FC = ({
{row.title}{row.version ? ` ${row.version}` : ''} {!task && c?.kind === 'offline' && !c.partial && {tr('installersKindOffline')}} + {!task && c?.kind === 'ipsw' && !c.partial && IPSW} {(!task && c?.kind === 'online' && !c.partial) || (task && row.kind === 'online') ? {tr('installersKindOnline')} : null} @@ -333,12 +351,12 @@ export const InstallersPage: React.FC = ({ /> ) : c ? ( <> - {!c.partial && (c.kind === 'offline' || c.kind === 'online') && ( - )} - {c.partial && c.kind === 'offline' && c.version && ( + {c.partial && c.version && (c.kind === 'offline' || (c.kind === 'ipsw' && (releases ?? []).some((r) => matchesRelease(c, r)))) && ( )} {confirmDelete === c.name ? ( @@ -362,7 +380,7 @@ export const InstallersPage: React.FC = ({
@@ -383,7 +401,7 @@ export const InstallersPage: React.FC = ({ {latest.title} {latest.version} {groupIndex === 0 && {tr('installersLatest')}} - {downloaded(latest.version) && } + {downloaded(latest) && }
{releaseMeta(latest)}
@@ -402,7 +420,7 @@ export const InstallersPage: React.FC = ({
{r.version} {r.build} - {downloaded(r.version) && {tr('offlineCached')}} + {downloaded(r) && {tr('offlineCached')}}
{releaseMeta(r)} diff --git a/frontend/src/macos/applicationMenuModel.ts b/frontend/src/macos/applicationMenuModel.ts new file mode 100644 index 0000000..7780636 --- /dev/null +++ b/frontend/src/macos/applicationMenuModel.ts @@ -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 + +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() + 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 | undefined { + if (!commands.has(entry.command)) return undefined + if ((entry.command.startsWith('vm:') || entry.command === 'vmSettings') && entry.scope !== scope) return undefined + return entry.command +} diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 9e87479..6ec6278 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -2069,6 +2069,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. */ diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 43d6106..303181d 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -126,7 +126,7 @@ export type CreateOpts = Model & { type TaskStatus = 'running' | 'done' | 'failed' | 'canceled' -export type InstallerKind = 'offline' | 'online' +export type InstallerKind = 'offline' | 'online' | 'ipsw' export type InstallerPhase = 'queued' | 'downloading' /** A tracked long-running job pushed as "reims:task" (internal/app/tasks.go). */ diff --git a/frontend/src/wails.ts b/frontend/src/wails.ts index a4e1ddb..ebd8942 100644 --- a/frontend/src/wails.ts +++ b/frontend/src/wails.ts @@ -198,6 +198,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). diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index e066de7..f9e3c1a 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -294,6 +294,8 @@ export function SuggestLanguagePack():Promise; export function SuspendVM(arg1:string,arg2:string):Promise; +export function SyncApplicationMenu(arg1:string):Promise; + export function TestHostDNS(arg1:guesttools.HostDNSConfig):Promise; export function ToggleVMFullscreen(arg1:string,arg2:string):Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index eeef3a9..681aa2c 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -566,6 +566,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); } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 0186a20..f25b5ae 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -1344,7 +1344,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 +1381,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 +1415,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 +1437,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 +2359,7 @@ export namespace plugin { } export class SettingProperty { type: string; + "x-filePattern"?: string; title: LocalizedText; description?: LocalizedText; default?: any; @@ -2361,6 +2380,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"]; diff --git a/internal/app/app.go b/internal/app/app.go index 57c101c..d907f57 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -122,31 +122,33 @@ 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 - pluginMarket *market.MarketClient - controlServer *control.Server - driverRouter *driver.Router - vmStateTable *driver.StateTable - lifecycleSvc *vmlifecycle.Service - runtimeKinds *rt.KindRegistry - uiHealth uiHealthState - themeMode string - vmClosePrompts sync.Map - displayHost vmDisplayHost + 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 @@ -191,15 +193,15 @@ 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), - 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) @@ -278,8 +280,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 @@ -374,6 +376,7 @@ 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) } diff --git a/internal/app/application_menu.go b/internal/app/application_menu.go new file mode 100644 index 0000000..4d5fc5f --- /dev/null +++ b/internal/app/application_menu.go @@ -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) +} diff --git a/internal/app/application_menu_darwin.go b/internal/app/application_menu_darwin.go new file mode 100644 index 0000000..75dbc97 --- /dev/null +++ b/internal/app/application_menu_darwin.go @@ -0,0 +1,42 @@ +//go:build darwin && cgo + +package app + +/* +#cgo CFLAGS: -x objective-c +#cgo LDFLAGS: -framework AppKit +#include +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)) + } +} diff --git a/internal/app/application_menu_darwin.m b/internal/app/application_menu_darwin.m new file mode 100644 index 0000000..ae1fd79 --- /dev/null +++ b/internal/app/application_menu_darwin.m @@ -0,0 +1,120 @@ +//go:build darwin && cgo + +#import + +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 *managedItems; +static NSArray *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 *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 *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 *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; + } +} diff --git a/internal/app/application_menu_other.go b/internal/app/application_menu_other.go new file mode 100644 index 0000000..21bc5f0 --- /dev/null +++ b/internal/app/application_menu_other.go @@ -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") +} diff --git a/internal/app/application_menu_test.go b/internal/app/application_menu_test.go new file mode 100644 index 0000000..9f142db --- /dev/null +++ b/internal/app/application_menu_test.go @@ -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") + } +} diff --git a/internal/app/endpoints_flow_test.go b/internal/app/endpoints_flow_test.go index 190cdf1..7f4011f 100644 --- a/internal/app/endpoints_flow_test.go +++ b/internal/app/endpoints_flow_test.go @@ -152,6 +152,24 @@ func TestSSHTargetPrefersTheEndpoint(t *testing.T) { } } +func TestMacSSHTerminalLaunch(t *testing.T) { + for _, tc := range []struct { + host, user, want string + }{ + {"", "", "ssh://127.0.0.1:2222"}, + {"guest.local", "dev", "ssh://dev@guest.local:2222"}, + {"2001:db8::1", "dev", "ssh://dev@[2001:db8::1]:2222"}, + } { + spec, err := macSSHTerminalLaunch(tc.host, 2222, tc.user) + if err != nil || spec.exe != "/usr/bin/open" || !slices.Equal(spec.args, []string{tc.want}) { + t.Errorf("launch = %+v, %v; want %q", spec, err, tc.want) + } + } + if _, err := macSSHTerminalLaunch("example.com", 22, "-oProxyCommand"); err == nil { + t.Error("accepted a user resembling an SSH option") + } +} + func TestSSHHostAliasSeparatesDrivers(t *testing.T) { mac := sshHostAlias("", "dev") other := sshHostAlias("vendor.driver.linux", "dev") diff --git a/internal/app/extras_flow.go b/internal/app/extras_flow.go index 1630a88..bfa6dde 100644 --- a/internal/app/extras_flow.go +++ b/internal/app/extras_flow.go @@ -8,6 +8,7 @@ import ( "sort" "strings" + "github.com/Nwflower/reims-go/internal/macos/guest" "github.com/Nwflower/reims-go/internal/macos/installer" ) @@ -91,6 +92,9 @@ func (a *App) GetStorageBreakdown() StorageBreakdown { cfgCopy := *a.cfg a.mu.Unlock() vmsDir := filepath.Join(cfgCopy.XDGDataDir(), "reims-ctl", "vms") + if guest.UsesAppleVirtualization() { + return computeStorageBreakdown(cfgCopy.DataRoot, guest.AppleVMRoot(cfgCopy.DataRoot), installer.RestoreDir(&cfgCopy), "") + } return computeStorageBreakdown(cfgCopy.DataRoot, vmsDir, installer.Dir(&cfgCopy), cfgCopy.ImagesDir()) } diff --git a/internal/app/installer_bindings.go b/internal/app/installer_bindings.go index 73af8ae..c556c10 100644 --- a/internal/app/installer_bindings.go +++ b/internal/app/installer_bindings.go @@ -8,6 +8,9 @@ import ( "fmt" "strings" + "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/macos/applevz" + "github.com/Nwflower/reims-go/internal/macos/guest" "github.com/Nwflower/reims-go/internal/macos/installer" rt "github.com/Nwflower/reims-go/internal/runtime" ) @@ -26,6 +29,14 @@ func (a *App) installerClient() (*installer.Client, error) { // ListOfflineReleases lists the offline installers Apple offers, newest first. // It reads Apple's catalog (a few seconds, needs the network). func (a *App) ListOfflineReleases() ([]installer.Release, error) { + if guest.UsesAppleVirtualization() { + release, err := a.latestRestoreRelease(a.baseCtx()) + if err != nil { + return nil, err + } + release.URL, release.Digest = "", "" // The UI selects a release, never a CDN URL or checksum. + return []installer.Release{release}, nil + } c, err := a.installerClient() if err != nil { return nil, err @@ -46,30 +57,72 @@ func (a *App) DownloadInstaller(version string) (string, error) { if version == "" { return "", fmt.Errorf("no version given") } + if guest.UsesAppleVirtualization() { + return a.startRestoreImageDownload(version) + } c, err := a.installerClient() if err != nil { return "", err } - a.ensureTaskEmitter() - base := a.ctx - if base == nil { - base = context.Background() + return a.startInstallerDownload("offline", version, func(ctx context.Context, update func(installer.Update)) (*installer.Result, error) { + return c.DownloadOffline(ctx, version, update) + }), nil +} + +func (a *App) startRestoreImageDownload(version string) (string, error) { + a.selectionMu.Lock() + defer a.selectionMu.Unlock() + if err := a.requireWritableDataRoot(); err != nil { + return "", err } + cfg := a.runtimeConfig() + cache := installer.RestoreCache{Dir: installer.RestoreDir(&cfg)} + return a.startInstallerDownload(installer.RestoreKind, version, func(ctx context.Context, update func(installer.Update)) (*installer.Result, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + release, err := a.latestRestoreRelease(ctx) + if err != nil { + return nil, err + } + if release.Version != version { + return nil, errors.New("the compatible macOS restore image changed; refresh the catalog before downloading") + } + return cache.Download(ctx, release, update) + }), nil +} + +func (a *App) latestRestoreRelease(ctx context.Context) (installer.Release, error) { + release, err := installer.LatestRestore(ctx) + if err == nil || errors.Is(err, context.Canceled) { + return release, err + } + key := "err.restore_catalog_unavailable" + if errors.Is(err, applevz.ErrRestoreCatalogUnsupported) { + key = "err.restore_catalog_unsupported" + } + a.emitLog("installer", "Apple restore catalog: "+err.Error()) + return installer.Release{}, i18n.NewCodedError(a.locale(), "E_RESTORE_CATALOG", key, nil, err) +} + +func (a *App) startInstallerDownload(kind, version string, download installerDownloadFunc) string { + a.ensureTaskEmitter() + base := a.baseCtx() var ( ctx context.Context cancel context.CancelFunc ) - run, id, owned := installerDownloads.reserveOrFind("offline", version, "installer-download", func(initialPhase string) string { + run, id, owned := installerDownloads.reserveOrFind(kind, version, "installer-download", func(initialPhase string) string { ctx, cancel = context.WithCancel(base) - return tasks.startWithInstaller("installer-download", version, "", "offline", version, initialPhase, cancel) + return tasks.startWithInstaller("installer-download", version, "", kind, version, initialPhase, cancel) }) if !owned { - return id, nil + return id } - a.emitLog("installer", "Downloading macOS "+version+" offline installer") + a.emitLog("installer", "Downloading macOS "+version+" ("+kind+")") go func() { defer cancel() - res, err := c.DownloadOffline(ctx, version, func(u installer.Update) { + res, err := download(ctx, func(u installer.Update) { switch u.Kind { case installer.KindStep, installer.KindNote: a.emitLog("installer", u.Message) @@ -93,11 +146,18 @@ func (a *App) DownloadInstaller(version string) (string, error) { tasks.finish(id, "", err) } }() - return id, nil + return id } // ListInstallers lists the downloaded installers kept for new VMs. func (a *App) ListInstallers() ([]installer.Cached, error) { + if guest.UsesAppleVirtualization() { + if !a.dataRootUsable() { + return nil, nil + } + cfg := a.runtimeConfig() + return (installer.RestoreCache{Dir: installer.RestoreDir(&cfg)}).List() + } c, err := a.installerClient() if err != nil { return nil, err @@ -108,6 +168,18 @@ func (a *App) ListInstallers() ([]installer.Cached, error) { // DeleteInstaller deletes a downloaded installer through reims-ctl, which // refuses one a VM boots from or one being downloaded. func (a *App) DeleteInstaller(name string) error { + if guest.UsesAppleVirtualization() { + a.selectionMu.Lock() + defer a.selectionMu.Unlock() + if err := a.requireWritableDataRoot(); err != nil { + return err + } + if tasks.hasRunningRestore() { + return errors.New("cannot delete a restore image while a macOS installation is running") + } + cfg := a.runtimeConfig() + return (installer.RestoreCache{Dir: installer.RestoreDir(&cfg)}).Delete(a.baseCtx(), name) + } c, err := a.installerClient() if err != nil { return err diff --git a/internal/app/installer_coordinator.go b/internal/app/installer_coordinator.go index c476dba..ca172d6 100644 --- a/internal/app/installer_coordinator.go +++ b/internal/app/installer_coordinator.go @@ -17,7 +17,7 @@ type installerDownloadFunc func(ctx context.Context, onUpdate func(installer.Upd // progress, deduplicate the same release, and surface queueing cleanly. type installerDownloadRun struct { key string - kind string // "offline" | "online" + kind string // "offline" | "online" | "ipsw" version string ownerID string ownerKind string // "installer-download" | "vm-create" | "recovery-download" diff --git a/internal/app/lifecycle_flow_test.go b/internal/app/lifecycle_flow_test.go index 57e33e6..d00d0b4 100644 --- a/internal/app/lifecycle_flow_test.go +++ b/internal/app/lifecycle_flow_test.go @@ -117,6 +117,41 @@ func (d *appSecondDriver) InvokeAction(_ context.Context, _ string, action strin return d.actionResults[action], nil } +type nativeViewerDriver struct { + *appSecondDriver + shown string +} + +func (d *nativeViewerDriver) ShowWindow(_ context.Context, name string) error { + d.shown = name + return nil +} + +func TestHostedViewerIsOpenedThroughTheOwningDriver(t *testing.T) { + const id = "test.driver.viewer" + drv := &nativeViewerDriver{appSecondDriver: &appSecondDriver{id: id, vms: []driver.VMInfo{{ + Name: "desktop", State: "running", Capabilities: []string{driver.CapHosted, driver.CapWindow}, + }}}} + reg := plugin.NewRegistry(nil) + if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: id, Version: "1.0.0"}, + Source: plugin.SourceBuiltin, Desired: true, Activate: func(_ context.Context, sc *plugin.Scope) error { + reg.RegisterGuestDriver(sc, id, drv) + return nil + }}); err != nil { + t.Fatal(err) + } + reg.Reconcile(t.Context()) + router := driver.NewRouter(reg, nil) + a := &App{driverRouter: router, lifecycleSvc: vmlifecycle.New(reg, router, nil)} + if err := a.FocusVMWindow(id, "desktop"); err != nil || drv.shown != "desktop" { + t.Fatalf("focus hosted viewer: shown=%q, err=%v", drv.shown, err) + } + drv.shown, drv.vms[0].State = "", "stopped" + if err := a.FocusVMWindow(id, "desktop"); err == nil || drv.shown != "" { + t.Fatalf("focus stopped VM: shown=%q, err=%v", drv.shown, err) + } +} + func TestAppSecondDriverUserEntry(t *testing.T) { const driverID = "test.driver.linux" drv := &appSecondDriver{id: driverID, vms: []driver.VMInfo{{Name: "ubuntu", DriverID: driverID, Directory: t.TempDir(), State: "stopped"}}} diff --git a/internal/app/plugins_flow.go b/internal/app/plugins_flow.go index 6b4ad11..1fca199 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -98,7 +98,7 @@ func (a *App) initPlugins() { // longer release it, so the host lifts what it left down. a.releaseHeldForPlugin(pluginID) }, - VMInventory: guest.VMInventory(), + VMInventories: guest.VMInventories(), Callbacks: builtin.HostCallbacks{ GetConfig: a.runtimeConfig, Log: func(source, line string) { @@ -170,7 +170,7 @@ func (a *App) initPlugins() { a.wakePoll() }, }, - RegisterGuest: guest.Register, + RegisterGuest: guest.RegisterForHost, }) if err != nil { a.emitLog("plugin", "Could not initialize plugin manager: "+err.Error()) @@ -765,9 +765,7 @@ func (a *App) GetPluginUIContributions() PluginUIContributions { if kr != nil { out.RuntimeKinds = kr.List() } - if dr != nil { - out.Drivers = dr.Summaries() - } + out.Drivers = desktopDriverSummaries(dr) return out } @@ -829,10 +827,39 @@ func (a *App) ListDrivers() []driver.DriverSummary { a.mu.Lock() dr := a.driverRouter a.mu.Unlock() - if dr == nil { + return desktopDriverSummaries(dr) +} + +func desktopDriverSummaries(router *driver.Router) []driver.DriverSummary { + list := router.Summaries() + if !guest.UsesAppleVirtualization() { + return list + } + for i := range list { + if list[i].ID == guest.AppleDriverID() { + list[i].Builtin = true + list[0], list[i] = list[i], list[0] + break + } + } + return list +} + +func (a *App) nativeVirtualizationStatus() *host.AppleVirtualizationStatus { + if !guest.UsesAppleVirtualization() { return nil } - return dr.Summaries() + a.appleVZProbeOnce.Do(func() { + ctx, cancel := context.WithTimeout(a.baseCtx(), 5*time.Second) + defer cancel() + if err := guest.ProbeAppleVirtualization(ctx); err != nil { + a.appleVZProbe.Detail = host.RedactText(err.Error()) + return + } + a.appleVZProbe.Ready = true + }) + status := a.appleVZProbe + return &status } func (a *App) CreateVMWithDriver(req driver.CreateRequest) error { @@ -874,8 +901,12 @@ func (a *App) CreateVMWithDriver(req driver.CreateRequest) error { if issues := drv.ValidateCreate(ctx, req); len(issues) > 0 { return errors.New(issues[0].Message) } - w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(req.DriverID, req.Name, line) }) - if err := drv.Create(ctx, req, w, w); err != nil { + w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(drv.ID(), req.Name, line) }) + if drv.ID() == guest.AppleDriverID() { + if err := a.restoreAppleVM(dr, drv, req, w); err != nil { + return err + } + } else if err := drv.Create(ctx, req, w, w); err != nil { return err } if mgr != nil { @@ -889,6 +920,29 @@ func (a *App) CreateVMWithDriver(req driver.CreateRequest) error { return nil } +func (a *App) restoreAppleVM(router *driver.Router, drv driver.Driver, req driver.CreateRequest, w vmstart.LineWriter) error { + ctx, cancel := context.WithCancel(a.baseCtx()) + defer cancel() + a.selectionMu.Lock() + a.mu.Lock() + stillCurrent := a.driverRouter == router && !a.allowQuit && a.quitMode == "" + a.mu.Unlock() + if !stillCurrent { + a.selectionMu.Unlock() + return errors.New("virtual machine restore could not start because the workspace changed") + } + a.ensureTaskEmitter() + id := tasks.start("vm-restore", req.Name, driver.NewVMRef(drv.ID(), req.Name).Key(), cancel) + a.selectionMu.Unlock() + defer func() { + a.wakePoll() + a.emitStateChanged() + }() + err := drv.Create(ctx, req, w, w) + tasks.finish(id, req.Name, err) + return err +} + // InspectPluginArchive runs the unified static security scanner on a local .zip // package before installing it so the UI can display hard blockers, capabilities, // and L3 native execution notices. diff --git a/internal/app/qqgroup.go b/internal/app/qqgroup.go index 59e71d5..b4bd744 100644 --- a/internal/app/qqgroup.go +++ b/internal/app/qqgroup.go @@ -19,6 +19,7 @@ import ( const ( qqGroupID = "1136042744" qqGroupShortURL = "https://qm.qq.com/q/TBmRJlVbSo" + qqGroupProtocolURL = "tencent://groupwpa/" qqGroupAuthCacheTTL = 10 * time.Minute qqGroupLookupTimeout = 5 * time.Second ) @@ -151,7 +152,15 @@ func buildQQGroupSchemeURL(groupUin, authKey string, now time.Time) string { AuthKey: authKey, Auth: "", }) - return "tencent://groupwpa/?subcmd=all¶m=" + strings.ToUpper(hex.EncodeToString(raw)) + "&jump_from=" + return qqGroupProtocolURL + "?subcmd=all¶m=" + strings.ToUpper(hex.EncodeToString(raw)) + "&jump_from=" +} + +func validateQQGroupProtocolURL(uri string) (string, error) { + uri = strings.TrimSpace(uri) + if !strings.HasPrefix(uri, qqGroupProtocolURL+"?") || strings.ContainsAny(uri, "\x00\r\n") { + return "", errors.New("refusing to open non-QQ-group protocol URL") + } + return uri, nil } func decodeBase64Flexible(s string) ([]byte, bool) { diff --git a/internal/app/qqgroup_darwin.go b/internal/app/qqgroup_darwin.go new file mode 100644 index 0000000..96a36de --- /dev/null +++ b/internal/app/qqgroup_darwin.go @@ -0,0 +1,53 @@ +//go:build darwin && cgo + +package app + +/* +#cgo CFLAGS: -x objective-c +#cgo LDFLAGS: -framework AppKit +#include +#include + +static int reimsHasQQProtocolHandler(const char *uri) { + @autoreleasepool { + NSURL *url = [NSURL URLWithString:[NSString stringWithUTF8String:uri]]; + NSURL *appURL = [[NSWorkspace sharedWorkspace] URLForApplicationToOpenURL:url]; + return appURL && [[[NSBundle bundleWithURL:appURL] bundleIdentifier] isEqualToString:@"com.tencent.qq"]; + } +} + +static int reimsOpenQQProtocol(const char *uri) { + @autoreleasepool { + NSURL *url = [NSURL URLWithString:[NSString stringWithUTF8String:uri]]; + return url && [[NSWorkspace sharedWorkspace] openURL:url]; + } +} +*/ +import "C" + +import ( + "errors" + "unsafe" +) + +func hasQQProtocolHandler() bool { + uri := C.CString(qqGroupProtocolURL) + defer C.free(unsafe.Pointer(uri)) + return C.reimsHasQQProtocolHandler(uri) != 0 +} + +func launchQQProtocol(uri string) error { + clean, err := validateQQGroupProtocolURL(uri) + if err != nil { + return err + } + if !hasQQProtocolHandler() { + return errQQNotInstalled + } + target := C.CString(clean) + defer C.free(unsafe.Pointer(target)) + if C.reimsOpenQQProtocol(target) == 0 { + return errors.New("macOS refused to open the QQ group invite") + } + return nil +} diff --git a/internal/app/qqgroup_darwin_test.go b/internal/app/qqgroup_darwin_test.go new file mode 100644 index 0000000..ecf17fe --- /dev/null +++ b/internal/app/qqgroup_darwin_test.go @@ -0,0 +1,24 @@ +//go:build darwin && cgo + +package app + +import ( + "os" + "testing" +) + +func TestMacQQProtocolHandler(t *testing.T) { + mode := os.Getenv("REIMS_TEST_MAC_QQ") + if mode != "1" && mode != "launch" { + t.Skip("requires QQ registered as the tencent URL handler in a macOS desktop session") + } + a := new(App) + if !a.CanOpenQQGroup() { + t.Fatal("Launch Services did not resolve the QQ group link to the QQ app") + } + if mode == "launch" { + if err := a.OpenQQGroup(); err != nil { + t.Fatal(err) + } + } +} diff --git a/internal/app/qqgroup_other.go b/internal/app/qqgroup_other.go index ebc57e8..b77942b 100644 --- a/internal/app/qqgroup_other.go +++ b/internal/app/qqgroup_other.go @@ -1,4 +1,4 @@ -//go:build !windows +//go:build !windows && (!darwin || !cgo) package app diff --git a/internal/app/qqgroup_test.go b/internal/app/qqgroup_test.go index f64dc25..f029ef5 100644 --- a/internal/app/qqgroup_test.go +++ b/internal/app/qqgroup_test.go @@ -54,6 +54,18 @@ func TestBuildQQGroupSchemeURL(t *testing.T) { } } +func TestValidateQQGroupProtocolURL(t *testing.T) { + invite := buildQQGroupSchemeURL(qqGroupID, "test-key", time.UnixMilli(1)) + if got, err := validateQQGroupProtocolURL(" " + invite + " "); err != nil || got != invite { + t.Fatalf("validate invite = %q, %v", got, err) + } + for _, raw := range []string{qqGroupShortURL, "tencent://message/?uin=123", "tencent://groupwpa/other?param=123", invite + "\x00extra"} { + if _, err := validateQQGroupProtocolURL(raw); err == nil { + t.Errorf("accepted %q", raw) + } + } +} + func TestExtractCommandExecutable(t *testing.T) { cases := []struct { in string diff --git a/internal/app/qqgroup_windows.go b/internal/app/qqgroup_windows.go index 0ae0120..7049dcb 100644 --- a/internal/app/qqgroup_windows.go +++ b/internal/app/qqgroup_windows.go @@ -3,10 +3,8 @@ package app import ( - "errors" "fmt" "os" - "strings" "syscall" "unsafe" @@ -14,8 +12,8 @@ import ( ) var ( - qqShell32 = syscall.NewLazyDLL("shell32.dll") - qqProcShellExecW = qqShell32.NewProc("ShellExecuteW") + qqShell32 = syscall.NewLazyDLL("shell32.dll") + qqProcShellExecW = qqShell32.NewProc("ShellExecuteW") ) func hasQQProtocolHandler() bool { @@ -52,9 +50,9 @@ func hasQQProtocolHandler() bool { } func launchQQProtocol(uri string) error { - trimmed := strings.TrimSpace(uri) - if !strings.HasPrefix(trimmed, "tencent://groupwpa/") { - return errors.New("refusing to open non-QQ-group protocol URL") + trimmed, err := validateQQGroupProtocolURL(uri) + if err != nil { + return err } verb, err := syscall.UTF16PtrFromString("open") if err != nil { diff --git a/internal/app/quit_no_tray_test.go b/internal/app/quit_no_tray_test.go new file mode 100644 index 0000000..41b06b5 --- /dev/null +++ b/internal/app/quit_no_tray_test.go @@ -0,0 +1,21 @@ +//go:build !windows + +package app + +import ( + "context" + "testing" + + "github.com/Nwflower/reims-go/internal/config" +) + +func TestClosingDesktopWithoutSystemTray(t *testing.T) { + a := &App{cfg: config.Default()} + a.startTray() + if a.trayMgr != nil { + t.Fatal("host without a system tray must not register a tray manager") + } + if a.beforeClose(context.Background()) { + t.Fatal("closing the window must not hide it to an unavailable tray") + } +} diff --git a/internal/app/ssh_flow.go b/internal/app/ssh_flow.go index 6002564..1c9b1bb 100644 --- a/internal/app/ssh_flow.go +++ b/internal/app/ssh_flow.go @@ -2,10 +2,14 @@ package app import ( "fmt" + "net" + "net/url" "os" "os/exec" "path/filepath" "regexp" + "runtime" + "strconv" "strings" "github.com/Nwflower/reims-go/internal/driver" @@ -97,8 +101,7 @@ func sshTarget(vm driver.VMInfo) (host string, port int, user string, ok bool) { return "", 0, "", false } -// OpenSSHTerminal launches an interactive Windows Terminal (falling back to -// PowerShell) connected to the VM's forwarded SSH port. +// OpenSSHTerminal opens an interactive SSH session in the host's terminal. func (a *App) OpenSSHTerminal(driverID, name, user string) error { d, err := a.resolveVMInfo(driverID, name) if err != nil { @@ -119,6 +122,17 @@ func (a *App) OpenSSHTerminal(driverID, name, user string) error { if user == "" { user = endpointUser } + if runtime.GOOS == "darwin" { + spec, err := macSSHTerminalLaunch(sshHost, sshPort, user) + if err != nil { + return err + } + if err := exec.Command(spec.exe, spec.args...).Run(); err != nil { + return fmt.Errorf("open SSH terminal: %w", err) + } + a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Opened SSH terminal (%s:%d)", sshHost, sshPort)) + return nil + } target := sshHost if user != "" { target = user + "@" + sshHost @@ -139,6 +153,22 @@ func (a *App) OpenSSHTerminal(driverID, name, user string) error { return nil } +// macSSHTerminalLaunch passes a validated SSH URL to Launch Services, not a shell command. +func macSSHTerminalLaunch(host string, port int, user string) (launchSpec, error) { + ep := driver.VMEndpoint{Kind: driver.EndpointSSH, Host: host, Port: port, User: user} + if err := driver.ValidateEndpoint(ep); err != nil { + return launchSpec{}, err + } + if host == "" { + host = "127.0.0.1" + } + target := url.URL{Scheme: "ssh", Host: net.JoinHostPort(host, strconv.Itoa(port))} + if user != "" { + target.User = url.User(user) + } + return launchSpec{exe: "/usr/bin/open", args: []string{target.String()}}, nil +} + // WriteSSHConfig idempotently writes or updates a Host block for the VM in // ~/.ssh/config and returns the configured Host alias (e.g. "reims-macos-tahoe"). func (a *App) WriteSSHConfig(driverID, name, user string) (string, error) { diff --git a/internal/app/tasks.go b/internal/app/tasks.go index 57aa758..81b6f8e 100644 --- a/internal/app/tasks.go +++ b/internal/app/tasks.go @@ -34,7 +34,7 @@ type Task struct { Kind string `json:"kind"` // installer/recovery/VM/runtime/app tasks or "plugin:" Subject string `json:"subject"` // release ("26.7.3") or VM name VM string `json:"vm,omitempty"` - InstallerKind string `json:"installer_kind,omitempty"` // "offline" | "online" while an installer download is attached + InstallerKind string `json:"installer_kind,omitempty"` // "offline" | "online" | "ipsw" while an installer download is attached InstallerVersion string `json:"installer_version,omitempty"` // release ("26.7.3") or online target ("tahoe" / "latest") InstallerPhase string `json:"installer_phase,omitempty"` // "queued" | "downloading" while active Step string `json:"step"` // upstream wording, e.g. "downloading OpenCore 1.0.8" @@ -280,6 +280,17 @@ func (m *taskManager) hasRunningDownload() bool { return false } +func (m *taskManager) hasRunningRestore() bool { + m.mu.Lock() + defer m.mu.Unlock() + for _, e := range m.tasks { + if e.task.Kind == "vm-restore" && e.task.Status == TaskRunning { + return true + } + } + return false +} + func (m *taskManager) cancelAll() { m.mu.Lock() cancels := make([]context.CancelFunc, 0, len(m.tasks)) diff --git a/internal/app/thumbnail_flow.go b/internal/app/thumbnail_flow.go index fcc5ed2..8122ebf 100644 --- a/internal/app/thumbnail_flow.go +++ b/internal/app/thumbnail_flow.go @@ -101,15 +101,16 @@ func (a *App) GetVMThumbnail(driverID, name string) (VMThumbnail, error) { return readThumb(path, false), nil } -// FocusVMWindow brings a running VM's QEMU display window to the foreground, -// restoring it first if minimized. +// FocusVMWindow brings a running VM's display or primary endpoint to the foreground. func (a *App) FocusVMWindow(driverID, name string) error { info, err := a.resolveVMInfo(driverID, name) if err != nil { return err } if driver.IsHosted(info.Capabilities) { - // A hosted VM has no window of its own: bring up its best endpoint. + if driver.HasCapability(info.Capabilities, driver.CapWindow) { + return a.showHostedVMWindow(info) + } ep, ok := driver.PrimaryHostedEndpoint(info.Endpoints) if !ok { return fmt.Errorf("%s has no ready endpoint to open", name) @@ -137,6 +138,26 @@ func (a *App) FocusVMWindow(driverID, name string) error { return nil } +func (a *App) showHostedVMWindow(info driver.VMInfo) error { + if info.State != "running" { + return fmt.Errorf("VM %s is not running", info.Name) + } + a.mu.Lock() + router := a.driverRouter + a.mu.Unlock() + drv, err := router.DriverByID(info.DriverID) + if err != nil { + return err + } + window, ok := drv.(driver.WindowDriver) + if !ok { + return fmt.Errorf("driver %q does not provide a viewer", info.DriverID) + } + ctx, cancel := context.WithTimeout(a.baseCtx(), 10*time.Second) + defer cancel() + return window.ShowWindow(ctx, info.Name) +} + // ToggleVMFullscreen switches the running VM's display through its owning driver. func (a *App) ToggleVMFullscreen(driverID, name string) (bool, error) { a.mu.Lock() diff --git a/internal/archtest/file_replace_test.go b/internal/archtest/file_replace_test.go index 1772ade..8e5cd35 100644 --- a/internal/archtest/file_replace_test.go +++ b/internal/archtest/file_replace_test.go @@ -13,6 +13,7 @@ var renameOwners = map[string]bool{ "internal/app/ui_health.go": true, // log rotation "internal/atomicfile/atomicfile.go": true, "internal/fetch/fetch.go": true, // download + "internal/fetch/validated.go": true, // validated restore image download "internal/macos/installer/accelerated.go": true, // download "internal/macos/installer/hfs_image.go": true, // disk image "internal/macos/installer/oc_cache.go": true, // download diff --git a/internal/archtest/macos_boundary_test.go b/internal/archtest/macos_boundary_test.go index 12e7c8d..9f1e5d3 100644 --- a/internal/archtest/macos_boundary_test.go +++ b/internal/archtest/macos_boundary_test.go @@ -151,6 +151,14 @@ func TestMacOSDoesNotGainPrivateHostDependencies(t *testing.T) { } for _, dir := range s.imports() { if name, ok := strings.CutPrefix(dir, "internal/"); ok && !isMacOSDir(dir) { + if s.rel == "internal/macos/installer/restore_image.go" && name == "fetch" { + // Native restore transfer shares the client's validated HTTP cache path. + continue + } + if s.dir() == "internal/macos/applevz" && name == "atomicfile" { + // The native backend owns its settings and uses the common safe replacement primitive. + continue + } found[name] = append(found[name], s.rel) } } diff --git a/internal/archtest/sources_test.go b/internal/archtest/sources_test.go index 296cf2b..d20f068 100644 --- a/internal/archtest/sources_test.go +++ b/internal/archtest/sources_test.go @@ -71,7 +71,7 @@ var loadSources = sync.OnceValues(func() ([]source, error) { if err != nil { return err } - f, err := parser.ParseFile(fileSet, p, raw, parser.SkipObjectResolution) + f, err := parser.ParseFile(fileSet, p, raw, parser.SkipObjectResolution|parser.ParseComments) if err != nil { return err } diff --git a/internal/archtest/unused_test.go b/internal/archtest/unused_test.go index 38dd5a0..3e0ab8c 100644 --- a/internal/archtest/unused_test.go +++ b/internal/archtest/unused_test.go @@ -30,6 +30,12 @@ func TestProductCodeHasNoUncalledFunctions(t *testing.T) { self = s.dir() + "." + fn.Name.Name checked := strings.HasPrefix(s.rel, "internal/") && !strings.HasPrefix(s.rel, "internal/testutil/") || strings.HasPrefix(s.rel, "scripts/i18ngen/") entry := fn.Name.Name == "main" || fn.Name.Name == "init" || fn.Name.Name == "_" + if fn.Doc != nil { + for _, comment := range fn.Doc.List { + // cgo callbacks are called from native code, not the Go AST. + entry = entry || comment.Text == "//export "+fn.Name.Name + } + } if checked && !entry && (fn.Recv == nil || !fn.Name.IsExported()) { decls[self] = decl{s, fn} } diff --git a/internal/cli/apple_vz_test.go b/internal/cli/apple_vz_test.go new file mode 100644 index 0000000..66ec20d --- /dev/null +++ b/internal/cli/apple_vz_test.go @@ -0,0 +1,55 @@ +package cli + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver" +) + +func TestAppleNativeCLIUsesItsOwnDriverWithoutWindowsRuntime(t *testing.T) { + root := t.TempDir() + t.Setenv("REIMS_CTL_CONFIG_DIR", "") + cfg := &config.Config{DataRoot: root} + mgr, router, err := openCLIPluginManager(cfg, true) + if err != nil { + t.Fatal(err) + } + defer mgr.Close() + wantApple := runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" + if isAppleCreateDriver(defaultCreateDriver()) != wantApple { + t.Fatalf("unexpected default %q on %s/%s", defaultCreateDriver(), runtime.GOOS, runtime.GOARCH) + } + if !wantApple { + return + } + apple, err := router.DriverByID(defaultCreateDriver()) + if err != nil { + t.Fatal(err) + } + if apple.RuntimeKind() != "external" || !driver.HasCapability(apple.Capabilities(), driver.CapWindow) { + t.Fatalf("unexpected native driver metadata: %v", apple) + } + if _, err := router.DriverByID(driver.BuiltinReimsMacOSDriverID); err == nil { + t.Fatal("the Apple host must not load the Windows runtime driver") + } + registry := filepath.Join(cfg.XDGConfigDir(), "reims-ctl", "vms.toml") + if err := os.MkdirAll(filepath.Dir(registry), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(registry, []byte("[[vm]]\nname = \"legacy\"\ndir = \"/not-used\"\n"), 0o600); err != nil { + t.Fatal(err) + } + vms, err := router.ListAllVMs(t.Context()) + if err != nil || len(vms) != 1 || !vms[0].DriverUnavailable || vms[0].DriverID != driver.BuiltinReimsMacOSDriverID { + t.Fatalf("legacy entries should be listed without loading the Windows runtime: %+v, %v", vms, err) + } + err = vmCreate(t.Context(), cfg, "en-US", []string{"--gpu", "auto", "mac"}, false) + if err == nil || !strings.Contains(err.Error(), "--gpu") { + t.Fatalf("native create silently accepted a Windows graphics option: %v", err) + } +} diff --git a/internal/cli/cli.go b/internal/cli/cli.go index b65e672..7a634c8 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -91,7 +91,7 @@ func run(args []string) (i18n.Locale, error) { switch rest[0] { case "doctor": - return loc, cmdDoctor(cfg, loc, rest[1:]) + return loc, cmdDoctor(cfg, loc, root, rest[1:]) case "runtime": return loc, cmdRuntime(cfg, loc, rest[1:]) case "vm": @@ -114,6 +114,10 @@ func run(args []string) (i18n.Locale, error) { } func printUsage(loc i18n.Locale) { + if isAppleCreateDriver(defaultCreateDriver()) { + printAppleUsage(loc) + return + } fmt.Println(i18n.T(loc, "cli.usage.header")) fmt.Println("\n" + i18n.T(loc, "cli.usage.section_usage")) fmt.Println(i18n.T(loc, "cli.usage.line_gui")) @@ -150,20 +154,27 @@ func printUsage(loc i18n.Locale) { } } -func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error { +func cmdDoctor(cfg *config.Config, loc i18n.Locale, root dataroot.Status, args []string) error { fs := flag.NewFlagSet("doctor", flag.ContinueOnError) asJSON := fs.Bool("json", false, "Output JSON") if err := fs.Parse(args); err != nil { return err } rep := host.Inspect(cfg.DataRoot) + if native, err := nativeVirtualizationStatus(context.Background()); native { + rep.AppleVirtualization = &host.AppleVirtualizationStatus{Ready: err == nil} + if err != nil { + rep.AppleVirtualization.Detail = i18n.FormatCLIError(loc, err) + } + } active, _ := rt.ResolveActive(cfg) if *asJSON { payload := map[string]any{ - "host": rep, - "config": cfg, - "runtime": active, + "host": rep, + "config": cfg, + "runtime": active, + "data_root": root, } return printJSON(payload) } @@ -176,25 +187,60 @@ func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error { fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.ecores"), i18n.T(loc, "doctor.ecores.detail", rep.ECoreCount, rep.ECoreLogicalCPUs)) } if rep.TotalRAMGB > 0 { - fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.ram"), i18n.T(loc, "doctor.ram.detail", rep.TotalRAMGB, rep.AvailRAMGB)) + memory := i18n.M(loc, "doctor.ram.total_only", i18n.Vars{"total": rep.TotalRAMGB}) + if rep.MemoryUsageKnown { + memory = i18n.T(loc, "doctor.ram.detail", rep.TotalRAMGB, rep.AvailRAMGB) + } + fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.ram"), memory) + } + if rep.AppleVirtualization != nil { + printAppleVirtualizationStatus(loc, rep.AppleVirtualization) } if rep.FreeDiskGB > 0 { fmt.Printf("%-36s: %.1f GB (%s)\n", i18n.T(loc, "doctor.disk"), rep.FreeDiskGB, rep.DataRoot) } - - whpxKey := "doctor.whpx.unsupported" - switch rep.WHPX { - case host.WHPXReady: - whpxKey = "doctor.whpx.ok" - case host.WHPXHypervisorOff: - whpxKey = "doctor.whpx.hypervisor_off" - case host.WHPXNoHypervisor: - whpxKey = "doctor.whpx.no_hv" - case host.WHPXMissing: - whpxKey = "doctor.whpx.missing" + if err := dataroot.Error(loc, root); err != nil { + fmt.Fprintln(os.Stderr, i18n.FormatCLIError(loc, err)) } - fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.whpx"), i18n.T(loc, whpxKey)) + if rep.AppleVirtualization == nil { + whpxKey := "doctor.whpx.unsupported" + switch rep.WHPX { + case host.WHPXReady: + whpxKey = "doctor.whpx.ok" + case host.WHPXHypervisorOff: + whpxKey = "doctor.whpx.hypervisor_off" + case host.WHPXNoHypervisor: + whpxKey = "doctor.whpx.no_hv" + case host.WHPXMissing: + whpxKey = "doctor.whpx.missing" + } + fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.whpx"), i18n.T(loc, whpxKey)) + } + + printDoctorVulkan(loc, rep) + if active == nil { + fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.none")) + } else { + fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.active", active.Commit, active.Dir)) + } + if len(rep.DeepBackingChains) > 0 { + fmt.Printf("%s:\n", i18n.T(loc, "doctor.cow_chain")) + for _, c := range rep.DeepBackingChains { + if c.Broken { + fmt.Printf(" ! %s\n", i18n.T(loc, "doctor.cow_chain.broken", c.VMName, c.Depth, c.Path)) + } else { + fmt.Printf(" ! %s\n", i18n.T(loc, "doctor.cow_chain.item", c.VMName, c.Depth, host.BackingChainWarnDepth)) + } + } + } + return nil +} + +func printDoctorVulkan(loc i18n.Locale, rep host.Report) { + if rep.AppleVirtualization != nil && rep.VulkanProbeError == "" && len(rep.GPUs) == 0 { + return // The native host does not use or probe Vulkan. + } if rep.VulkanProbeError != "" { fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.gpu"), i18n.M(loc, "doctor.gpu.probe_failed", i18n.Vars{"detail": rep.VulkanProbeError})) } @@ -237,23 +283,6 @@ func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error { } } } - - if active == nil { - fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.none")) - } else { - fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.active", active.Commit, active.Dir)) - } - if len(rep.DeepBackingChains) > 0 { - fmt.Printf("%s:\n", i18n.T(loc, "doctor.cow_chain")) - for _, c := range rep.DeepBackingChains { - if c.Broken { - fmt.Printf(" ! %s\n", i18n.T(loc, "doctor.cow_chain.broken", c.VMName, c.Depth, c.Path)) - } else { - fmt.Printf(" ! %s\n", i18n.T(loc, "doctor.cow_chain.item", c.VMName, c.Depth, host.BackingChainWarnDepth)) - } - } - } - return nil } func sameGPU(a, b *host.GPUInfo) bool { @@ -409,11 +438,16 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e } return startVM(ctx, cfg, driverID, name, viaWindow) case "stop": - driverID, name, err := parseVMTarget(args) - if err != nil { + fs := flag.NewFlagSet("vm stop", flag.ContinueOnError) + driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") + force := fs.Bool("force", false, "Force power off if the guest cannot shut down normally") + if err := fs.Parse(args[1:]); err != nil { return err } - return stopVM(ctx, cfg, driverID, name) + if fs.NArg() != 1 { + return fmt.Errorf("usage: reims-go vm stop [--driver ] [--force] ") + } + return stopVM(ctx, cfg, *driverID, fs.Arg(0), *force) case "suspend": driverID, name, err := parseVMTarget(args) if err != nil { @@ -497,7 +531,8 @@ func parseVMTarget(args []string) (driverID, name string, err error) { func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) error { fs := flag.NewFlagSet("vm create", flag.ContinueOnError) - driverID := fs.String("driver", driver.BuiltinReimsMacOSDriverID, "Guest VM driver ID (default: builtin.driver.reims-macos)") + driverID := fs.String("driver", defaultCreateDriver(), "Guest VM driver ID") + ipsw := fs.String("ipsw", "", "Local Apple macOS restore image (Apple Virtualization only)") dir := fs.String("dir", "", "Custom VM directory") macos := fs.String("macos", "tahoe", "macOS version (e.g. tahoe)") cpus := fs.Int("cpus", 8, "vCPU count") @@ -518,6 +553,12 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s return fmt.Errorf("usage: reims-go vm create [flags] ") } name := fs.Arg(0) + if *ipsw != "" && !isAppleCreateDriver(*driverID) { + return fmt.Errorf("--ipsw is only supported by the Apple Virtualization driver") + } + if isAppleCreateDriver(*driverID) { + return createAppleVM(ctx, cfg, *driverID, name, *dir, *ipsw, *cpus, *mem, *diskSize, *start, fs) + } // Route non-reims guest drivers through the plugin Driver Router (§5.3, §10). if strings.TrimSpace(*driverID) != "" && *driverID != driver.BuiltinReimsMacOSDriverID { mgr, router, err := openCLIPluginManager(cfg, false) diff --git a/internal/cli/macos_native.go b/internal/cli/macos_native.go index bf22ffd..a03c997 100644 --- a/internal/cli/macos_native.go +++ b/internal/cli/macos_native.go @@ -3,16 +3,21 @@ package cli import ( "context" "errors" + "flag" "fmt" "io" "os" + "os/signal" "path/filepath" "strings" + "time" "github.com/Nwflower/reims-go/internal/config" "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/lifecycle" "github.com/Nwflower/reims-go/internal/macos/guest" "github.com/Nwflower/reims-go/internal/macos/installer" "github.com/Nwflower/reims-go/internal/macos/opencore" @@ -24,6 +29,48 @@ import ( func defaultMacOSGuestLang(loc i18n.Locale) string { return opencore.DefaultGuestLang(loc) } +func defaultCreateDriver() string { + if guest.UsesAppleVirtualization() { + return guest.AppleDriverID() + } + return driver.BuiltinReimsMacOSDriverID +} + +func isAppleCreateDriver(id string) bool { return id == guest.AppleDriverID() } + +func nativeVirtualizationStatus(ctx context.Context) (bool, error) { + if !guest.UsesAppleVirtualization() { + return false, nil + } + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + return true, guest.ProbeAppleVirtualization(ctx) +} + +func printAppleUsage(loc i18n.Locale) { + fmt.Println(i18n.T(loc, "cli.usage.apple.header")) + fmt.Println(i18n.T(loc, "cli.usage.line_cmd")) + fmt.Println() + for _, k := range []string{ + "cli.usage.apple.doctor", "cli.usage.apple.create", "cli.usage.cmd_vm_list", + "cli.usage.apple.start", "cli.usage.apple.stop", "cli.usage.apple.delete", + "cli.usage.cmd_vm_set", "cli.usage.cmd_plugin", "cli.usage.cmd_version", + } { + fmt.Println(i18n.T(loc, k)) + } +} + +func printAppleVirtualizationStatus(loc i18n.Locale, status *host.AppleVirtualizationStatus) { + key := "doctor.apple_virtualization.ready" + if !status.Ready { + key = "doctor.apple_virtualization.unavailable" + } + fmt.Printf("%-36s: %s\n", "Apple Virtualization", i18n.T(loc, key)) + if status.Detail != "" { + fmt.Fprintln(os.Stderr, status.Detail) + } +} + func requireDirectNetwork(vm driver.VMInfo) error { if vm.Ref().DriverID != driver.BuiltinReimsMacOSDriverID { return nil @@ -63,6 +110,47 @@ func requireCLIMacOSEnabled(cfg *config.Config, loc i18n.Locale) error { return nil } +func createAppleVM(ctx context.Context, cfg *config.Config, id, name, dir, ipsw string, cpus int, mem, disk string, start bool, flags *flag.FlagSet) error { + options := map[string]any{"restore_path": ipsw} + var unsupported error + flags.Visit(func(f *flag.Flag) { + switch f.Name { + case "driver", "ipsw", "start": + case "cpus": + options["cpus"] = cpus + case "memory": + options["memory"] = mem + case "disk-size": + options["disk_size"] = disk + default: + unsupported = fmt.Errorf("--%s is not supported by the Apple Virtualization driver", f.Name) + } + }) + if unsupported != nil { + return unsupported + } + if dir != "" { + return errors.New("the Apple Virtualization driver manages its VM directories under the data folder") + } + mgr, router, err := openCLIPluginManager(cfg, false) + if err != nil { + return err + } + defer mgr.Close() + drv, err := router.DriverByID(id) + if err != nil { + return err + } + ctx, cancel := signal.NotifyContext(ctx, os.Interrupt) + defer cancel() + req := driver.CreateRequest{DriverID: drv.ID(), Name: name, Options: options} + if err := drv.Create(ctx, req, os.Stdout, os.Stderr); err != nil || !start { + return err + } + _, err = lifecycle.New(mgr.Registry(), router, nil).Start(ctx, driver.NewVMRef(drv.ID(), name), os.Stdout, os.Stderr) + return err +} + // macOSCreateOptions is the CLI-neutral input to the native macOS create flow. type macOSCreateOptions struct { Name, Dir, MacOS, Memory, DiskSize, Disk, DiskMode, DiskCache, GPU, GuestLang string diff --git a/internal/cli/plugin.go b/internal/cli/plugin.go index c241d85..f683898 100644 --- a/internal/cli/plugin.go +++ b/internal/cli/plugin.go @@ -31,8 +31,8 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, * LocaleFn: func() i18n.Locale { return i18n.EffectiveLocale(cfg.Locale) }, - Logger: logf, - VMInventory: guest.VMInventory(), + Logger: logf, + VMInventories: guest.VMInventories(), Callbacks: builtin.HostCallbacks{ GetConfig: func() config.Config { return *cfg }, PrepareVMNetwork: func(ctx context.Context, name string, _ bool) (func(), error) { @@ -40,7 +40,7 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, * }, Log: logf, }, - RegisterGuest: guest.Register, + RegisterGuest: guest.RegisterForHost, StrictRegister: true, }) if err != nil { diff --git a/internal/cli/plugin_test.go b/internal/cli/plugin_test.go index 1e4407b..c9892e5 100644 --- a/internal/cli/plugin_test.go +++ b/internal/cli/plugin_test.go @@ -21,11 +21,14 @@ func TestMacOSPluginDisableAndVMInventory(t *testing.T) { _, err := run(append(args, command...)) return err } + if isAppleCreateDriver(defaultCreateDriver()) { + t.Skip("this test exercises registration and toggling of the Reims vGPU driver") + } t.Setenv("REIMS_CTL_CONFIG_DIR", filepath.Join(root, "config", "reims-ctl")) if err := runCLI("plugin", "disable", "builtin.guest.macos"); err != nil { t.Fatalf("disable without a runtime or VMs: %v", err) } - for _, cmd := range [][]string{{"vm", "create", "--start", "mac"}, {"vm", "type", "mac", "test"}} { + for _, cmd := range [][]string{{"vm", "create", "--driver", driver.BuiltinReimsMacOSDriverID, "--start", "mac"}, {"vm", "type", "mac", "test"}} { if err := runCLI(cmd...); err == nil || err.Error() != i18n.T(i18n.EnUS, "err.macos.disabled") { t.Fatalf("%v while disabled: %v", cmd, err) } diff --git a/internal/cli/start.go b/internal/cli/start.go index fd05db8..2a14cb0 100644 --- a/internal/cli/start.go +++ b/internal/cli/start.go @@ -103,13 +103,13 @@ func compactVM(ctx context.Context, cfg *config.Config, driverID, name string) ( return svc.CompactDisk(ctx, driver.VMRef{DriverID: driverID, Name: name}, os.Stdout, os.Stderr) } -func stopVM(ctx context.Context, cfg *config.Config, driverID, name string) error { +func stopVM(ctx context.Context, cfg *config.Config, driverID, name string, force bool) error { svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } defer closeService() - return svc.Stop(ctx, driver.VMRef{DriverID: driverID, Name: name}, false, os.Stdout, os.Stderr) + return svc.Stop(ctx, driver.VMRef{DriverID: driverID, Name: name}, force, os.Stdout, os.Stderr) } func startInWindow(ctx context.Context, cfg *config.Config, driverID, name string) error { diff --git a/internal/driver/driver.go b/internal/driver/driver.go index 4418435..b3af391 100644 --- a/internal/driver/driver.go +++ b/internal/driver/driver.go @@ -41,6 +41,7 @@ const ( // CapHosted marks VMs the driver runs itself: the host does not spawn, // watch, pin or window-manage a process for them. CapHosted = "hosted" + CapWindow = "window" // a hosted driver can bring its own viewer forward CapConsole = "console" CapTPM = "tpm" CapRDP = "rdp" @@ -237,6 +238,11 @@ type ActionDriver interface { InvokeAction(ctx context.Context, vmName, action string, params map[string]any) (any, error) } +// WindowDriver lets a hosted driver bring its own guest viewer forward. +type WindowDriver interface { + ShowWindow(context.Context, string) error +} + // LogDriver exposes driver-owned serial and QEMU logs. type LogDriver interface { ReadLogs(context.Context, string, bool) (string, error) diff --git a/internal/fetch/validated.go b/internal/fetch/validated.go new file mode 100644 index 0000000..cb95e1a --- /dev/null +++ b/internal/fetch/validated.go @@ -0,0 +1,264 @@ +package fetch + +import ( + "context" + "errors" + "fmt" + "net/http" + "os" + "strconv" + "strings" + "time" + + "github.com/Nwflower/reims-go/internal/atomicfile" +) + +// InvalidDownloadError marks a validation failure that proves the bytes are bad. +// Other validation failures leave the staged bytes and ETag available for retry. +type InvalidDownloadError struct{ Err error } + +func (e *InvalidDownloadError) Error() string { return e.Err.Error() } +func (e *InvalidDownloadError) Unwrap() error { return e.Err } + +// ResumeValidated downloads directly from the supplied client. A strong ETag +// binds a partial to the same representation; only a complete, consumer-validated +// file is published. The validator checks any consumer-specific integrity data. +func ResumeValidated(ctx context.Context, client *http.Client, url, final, part string, maxBytes int64, + onProgress Progress, validate func(context.Context, string) error) error { + if onProgress == nil { + onProgress = func(int64, int64) {} + } + for _, path := range []string{part, part + ".etag"} { + if _, err := plainDownloadFile(path); err != nil { + return err + } + } + info, err := plainDownloadFile(final) + if err != nil { + return err + } + if info != nil { + if info.Size() <= 0 || info.Size() > maxBytes { + return errors.New("cached download has an invalid size; delete it before retrying") + } + onProgress(info.Size(), info.Size()) + return validate(ctx, final) + } + if err := streamValidated(ctx, client, url, part, maxBytes, onProgress); err != nil { + return err + } + if err := validate(ctx, part); err != nil { + if ctx.Err() != nil { + return ctx.Err() // Keep the partial so validation can be retried. + } + var invalid *InvalidDownloadError + if errors.As(err, &invalid) { + return errors.Join(err, removeDownloadPart(part+".etag"), removeDownloadPart(part)) + } + return err + } + if err := ctx.Err(); err != nil { + return err + } + if err := removeDownloadPart(part + ".etag"); err != nil { + return err + } + return os.Rename(part, final) +} + +func plainDownloadFile(path string) (os.FileInfo, error) { + info, err := os.Lstat(path) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + if !info.Mode().IsRegular() { + return nil, fmt.Errorf("download path is not a regular file: %s", path) + } + return info, nil +} + +func removeDownloadPart(path string) error { + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + return nil +} + +func streamValidated(ctx context.Context, client *http.Client, url, part string, maxBytes int64, progress Progress) error { + info, err := plainDownloadFile(part) + if err != nil { + return err + } + var have int64 + var validator string + if info != nil && info.Size() > 0 && info.Size() <= maxBytes { + if tag, err := plainDownloadFile(part + ".etag"); err != nil { + return err + } else if tag != nil && tag.Size() <= 1024 { + data, err := os.ReadFile(part + ".etag") + if err != nil { + return err + } + if strongETag(string(data)) { + validator, have = string(data), info.Size() + } + } + } + retry, err := transferValidated(ctx, client, url, part, validator, have, maxBytes, progress) + if retry && err == nil { + _, err = transferValidated(ctx, client, url, part, "", 0, maxBytes, progress) + } + return err +} + +func transferValidated(ctx context.Context, client *http.Client, url, part, validator string, have, maxBytes int64, progress Progress) (bool, error) { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + req, err := NewRequest(ctx, url) + if err != nil { + return false, err + } + req.Header.Set("Accept-Encoding", "identity") + if have > 0 { + req.Header.Set("Range", fmt.Sprintf("bytes=%d-", have)) + req.Header.Set("If-Range", validator) + } + resp, err := client.Do(req) + if err != nil { + return false, err + } + if resp.StatusCode == http.StatusRequestedRangeNotSatisfiable && have > 0 { + // A 416 body is not image data; close it before any follow-up request. + resp.Body.Close() + if !confirmedCompleteRange(client, req, resp, validator, have) { + return true, nil + } + if err := checkValidatedSize(part, have); err != nil { + return false, err + } + progress(have, have) + return false, nil + } + defer resp.Body.Close() + tag := singleHeader(resp.Header, "ETag") + contentRange := singleHeader(resp.Header, "Content-Range") + flags, total := os.O_CREATE|os.O_WRONLY, resp.ContentLength + switch resp.StatusCode { + case http.StatusPartialContent: + if have == 0 || tag != validator || !validTailRange(contentRange, have, resp.ContentLength) { + if have > 0 { + return true, nil + } + return false, errors.New("download returned an unsolicited partial response") + } + flags, total = flags|os.O_APPEND, have+resp.ContentLength + case http.StatusOK: + have, flags = 0, flags|os.O_TRUNC + default: + return false, fmt.Errorf("download: HTTP %d", resp.StatusCode) + } + if !identityEncoding(resp) { + return false, errors.New("download returned an unexpected content encoding") + } + if total <= 0 || total > maxBytes { + return false, fmt.Errorf("download has an invalid content length: %d", total) + } + if have == 0 { + if err := resetDownloadValidator(part, tag); err != nil { + return false, err + } + } + if err := copyBody(resp.Body, cancel, part, flags, have, total, total, 45*time.Second, "restore image", progress); err != nil { + return false, err + } + return false, checkValidatedSize(part, total) +} + +func confirmedCompleteRange(client *http.Client, req *http.Request, resp *http.Response, validator string, have int64) bool { + if !completeRange(singleHeader(resp.Header, "Content-Range"), have) { + return false + } + if tags := resp.Header.Values("ETag"); len(tags) != 0 { + return len(tags) == 1 && tags[0] == validator + } + + // Some servers do not send ETag on 416. Confirm the same unencoded + // representation via a bounded conditional HEAD, never from length alone. + ctx, cancel := context.WithTimeout(req.Context(), 5*time.Second) + defer cancel() + head := req.Clone(ctx) + head.Method = http.MethodHead + head.Header.Del("Range") + head.Header.Del("If-Range") + head.Header.Set("If-Match", validator) + meta, err := client.Do(head) + if err != nil { + return false + } + defer meta.Body.Close() + return meta.StatusCode == http.StatusOK && meta.Request != nil && resp.Request != nil && + meta.Request.URL.String() == resp.Request.URL.String() && + singleHeader(meta.Header, "ETag") == validator && meta.ContentLength == have && identityEncoding(meta) +} + +func identityEncoding(resp *http.Response) bool { + encodings := resp.Header.Values("Content-Encoding") + return !resp.Uncompressed && (len(encodings) == 0 || len(encodings) == 1 && strings.EqualFold(encodings[0], "identity")) +} + +func checkValidatedSize(part string, total int64) error { + if info, err := plainDownloadFile(part); err != nil || info == nil || info.Size() != total { + return errors.Join(errors.New("restore image download is incomplete"), err) + } + return nil +} + +func resetDownloadValidator(part, tag string) error { + if err := removeDownloadPart(part + ".etag"); err != nil { + return err + } + if err := removeDownloadPart(part); err != nil { + return err + } + if !strongETag(tag) { + return nil + } + return atomicfile.Write(part+".etag", []byte(tag), 0o600) +} + +func singleHeader(header http.Header, name string) string { + if values := header.Values(name); len(values) == 1 { + return values[0] + } + return "" +} + +func strongETag(tag string) bool { + if len(tag) < 2 || len(tag) > 1024 || tag[0] != '"' || tag[len(tag)-1] != '"' { + return false + } + for i := 1; i < len(tag)-1; i++ { + if b := tag[i]; b <= ' ' || b == '"' || b == '\x7f' { + return false + } + } + return true +} + +func completeRange(header string, have int64) bool { + length, ok := strings.CutPrefix(header, "bytes */") + return ok && strings.TrimLeft(length, "0") == strconv.FormatInt(have, 10) +} + +func validTailRange(header string, have, length int64) bool { + span, totalRaw, ok := strings.Cut(strings.TrimPrefix(header, "bytes "), "/") + firstRaw, lastRaw, found := strings.Cut(span, "-") + first, e1 := strconv.ParseInt(firstRaw, 10, 64) + last, e2 := strconv.ParseInt(lastRaw, 10, 64) + total, e3 := strconv.ParseInt(totalRaw, 10, 64) + return strings.HasPrefix(header, "bytes ") && ok && found && e1 == nil && e2 == nil && e3 == nil && + length > 0 && first == have && last >= first && last < total && total-last == 1 && last-first+1 == length +} diff --git a/internal/fetch/validated_test.go b/internal/fetch/validated_test.go new file mode 100644 index 0000000..fa02bff --- /dev/null +++ b/internal/fetch/validated_test.go @@ -0,0 +1,288 @@ +package fetch + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "testing" +) + +func TestValidatedTransferUsesBoundPartialAndPublishesAfterValidation(t *testing.T) { + const payload = "fake IPSW body used only in a local test" + for _, tc := range []struct{ name, reply string }{{"resume", "matched"}, {"restart when file changes", "changed"}, {"restart on incorrect content range", "wrong-range"}} { + t.Run(tc.name, func(t *testing.T) { + var requests []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + rangeHeader := r.Header.Get("Range") + requests = append(requests, rangeHeader) + w.Header().Set("ETag", `"stable"`) + if rangeHeader != "" { + if rangeHeader != "bytes=5-" || r.Header.Get("If-Range") != `"stable"` { + t.Errorf("unsafe resume request: %s, %s", rangeHeader, r.Header.Get("If-Range")) + } + switch tc.reply { + case "changed": + w.Header().Set("ETag", `"changed"`) + case "wrong-range", "matched": + first := 5 + if tc.reply == "wrong-range" { + first = 4 + } + w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", first, len(payload)-1, len(payload))) + w.WriteHeader(http.StatusPartialContent) + fmt.Fprint(w, payload[first:]) + return + } + } + fmt.Fprint(w, payload) + })) + defer server.Close() + dir := t.TempDir() + final, part := filepath.Join(dir, "restore.ipsw"), filepath.Join(dir, "restore.part.ipsw") + for p, body := range map[string]string{part: payload[:5], part + ".etag": `"stable"`} { + if err := os.WriteFile(p, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + } + validate := func(_ context.Context, name string) error { + if name != part { + t.Errorf("validation path = %s", name) + } + if _, err := os.Stat(final); !os.IsNotExist(err) { + t.Error("download published before validation") + } + body, err := os.ReadFile(name) + if string(body) != payload { + t.Errorf("unexpected body: %q", body) + } + return err + } + if err := ResumeValidated(t.Context(), server.Client(), server.URL, final, part, 1024, nil, validate); err != nil { + t.Fatal(err) + } + if len(requests) != 1 && tc.reply != "wrong-range" || len(requests) != 2 && tc.reply == "wrong-range" { + t.Fatalf("requests: %v", requests) + } + if body, err := os.ReadFile(final); err != nil || string(body) != payload { + t.Fatalf("final = %q, %v", body, err) + } + if _, err := os.Stat(part + ".etag"); !os.IsNotExist(err) { + t.Fatalf("validator remains: %v", err) + } + }) + } +} + +func TestValidatedTransferReusesOnlyBoundComplete416(t *testing.T) { + const payload = "bound fixture" + const replacement = "changed bytes" // Same size, distinct bytes. + exact := fmt.Sprintf("bytes */%d", len(payload)) + for _, tc := range []struct { + name, savedTag string + tags, ranges []string + wantRange, wantFresh bool + }{ + {"complete", `"stable"`, []string{`"stable"`}, []string{exact}, true, false}, + {"changed", `"stable"`, []string{`"changed"`}, []string{exact}, true, true}, + {"weak response ETag", `"stable"`, []string{`W/"stable"`}, []string{exact}, true, true}, + {"ambiguous response ETag", `"stable"`, []string{`"stable"`, `"changed"`}, []string{exact}, true, true}, + {"wrong size", `"stable"`, []string{`"stable"`}, []string{fmt.Sprintf("bytes */%d", len(payload)-1)}, true, true}, + {"missing size", `"stable"`, []string{`"stable"`}, nil, true, true}, + {"malformed size", `"stable"`, []string{`"stable"`}, []string{fmt.Sprintf("bytes */+%d", len(payload))}, true, true}, + {"ambiguous size", `"stable"`, []string{`"stable"`}, []string{exact, "bytes */1"}, true, true}, + {"missing saved ETag", "", []string{`"stable"`}, []string{exact}, false, true}, + {"weak saved ETag", `W/"stable"`, []string{`"stable"`}, []string{exact}, false, true}, + {"malformed saved ETag", `"not valid"`, []string{`"stable"`}, []string{exact}, false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + var requests []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + rangeHeader := r.Header.Get("Range") + requests = append(requests, rangeHeader) + if rangeHeader == "" { + w.Header().Set("ETag", `"changed"`) + fmt.Fprint(w, replacement) + return + } + if r.Header.Get("If-Range") != tc.savedTag || r.Header.Get("Accept-Encoding") != "identity" { + t.Errorf("unexpected resume headers: %v", r.Header) + } + for _, tag := range tc.tags { + w.Header().Add("ETag", tag) + } + for _, value := range tc.ranges { + w.Header().Add("Content-Range", value) + } + w.Header().Set("Content-Encoding", "gzip") // The 416 error body is ignored. + w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) + fmt.Fprint(w, "not image data") + })) + defer server.Close() + dir := t.TempDir() + final, part := filepath.Join(dir, "restore.ipsw"), filepath.Join(dir, "restore.part.ipsw") + if err := os.WriteFile(part, []byte(payload), 0o600); err != nil { + t.Fatal(err) + } + if tc.savedTag != "" { + if err := os.WriteFile(part+".etag", []byte(tc.savedTag), 0o600); err != nil { + t.Fatal(err) + } + } + var wantRequests []string + wantBody := payload + if tc.wantRange { + wantRequests = append(wantRequests, fmt.Sprintf("bytes=%d-", len(payload))) + } + if tc.wantFresh { + wantRequests = append(wantRequests, "") + wantBody = replacement + } + var done, total int64 + err := ResumeValidated(t.Context(), server.Client(), server.URL, final, part, 1024, func(d, n int64) { + done, total = d, n + }, func(_ context.Context, file string) error { + if file != part { + t.Errorf("validation path = %s", file) + } + if _, err := os.Stat(final); !os.IsNotExist(err) { + t.Errorf("download published before validation: %v", err) + } + if body, err := os.ReadFile(file); err != nil || string(body) != wantBody { + t.Errorf("staged body = %q, %v; want %q", body, err, wantBody) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(requests, wantRequests) { + t.Fatalf("requests = %q, want %q", requests, wantRequests) + } + if want := int64(len(wantBody)); done != want || total != want { + t.Fatalf("progress = %d/%d, want %d/%d", done, total, want, want) + } + if body, err := os.ReadFile(final); err != nil || string(body) != wantBody { + t.Fatalf("final = %q, %v; want %q", body, err, wantBody) + } + }) + } +} + +func TestValidatedTransferConfirmsUntaggedComplete416WithHead(t *testing.T) { + const staged = "staged bytes" + const fresh = "fresh bytes" + const tag = `"stable"` + for _, tc := range []struct { + name, headTag, encoding string + headSize, headStatus int + redirect, wantFresh bool + }{ + {"match", tag, "", len(staged), http.StatusOK, false, false}, + {"changed", `"changed"`, "", len(staged), http.StatusOK, false, true}, + {"weak", `W/"stable"`, "", len(staged), http.StatusOK, false, true}, + {"missing", "", "", len(staged), http.StatusOK, false, true}, + {"wrong size", tag, "", len(staged) + 1, http.StatusOK, false, true}, + {"encoded", tag, "gzip", len(staged), http.StatusOK, false, true}, + {"precondition failed", tag, "", len(staged), http.StatusPreconditionFailed, false, true}, + {"different target", tag, "", len(staged), http.StatusOK, true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + var requests []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests = append(requests, r.Method+" "+r.URL.Path+" "+r.Header.Get("Range")) + if r.Method == http.MethodHead { + if r.Header.Get("If-Match") != tag || r.Header.Get("Range") != "" || r.Header.Get("If-Range") != "" || r.Header.Get("Accept-Encoding") != "identity" { + t.Errorf("unexpected confirmation headers: %v", r.Header) + } + if tc.redirect && r.URL.Path == "/" { + http.Redirect(w, r, "/other", http.StatusTemporaryRedirect) + return + } + if tc.headTag != "" { + w.Header().Set("ETag", tc.headTag) + } + if tc.encoding != "" { + w.Header().Set("Content-Encoding", tc.encoding) + } + w.Header().Set("Content-Length", fmt.Sprint(tc.headSize)) + w.WriteHeader(tc.headStatus) + return + } + if r.Header.Get("Range") != "" { + w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", len(staged))) + w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) + return + } + fmt.Fprint(w, fresh) + })) + defer server.Close() + dir := t.TempDir() + final, part := filepath.Join(dir, "restore.ipsw"), filepath.Join(dir, "restore.part.ipsw") + for path, bytes := range map[string]string{part: staged, part + ".etag": tag} { + if err := os.WriteFile(path, []byte(bytes), 0o600); err != nil { + t.Fatal(err) + } + } + wantRequests := []string{fmt.Sprintf("GET / bytes=%d-", len(staged)), "HEAD / "} + if tc.redirect { + wantRequests = append(wantRequests, "HEAD /other ") + } + wantBody := staged + if tc.wantFresh { + wantRequests = append(wantRequests, "GET / ") + wantBody = fresh + } + if err := ResumeValidated(t.Context(), server.Client(), server.URL, final, part, 1024, nil, func(_ context.Context, file string) error { + body, err := os.ReadFile(file) + if err == nil && string(body) != wantBody { + return fmt.Errorf("staged body = %q, want %q", body, wantBody) + } + return err + }); err != nil { + t.Fatal(err) + } + if !slices.Equal(requests, wantRequests) { + t.Fatalf("requests = %q, want %q", requests, wantRequests) + } + }) + } +} + +func TestValidatedTransferKeepsPartialOnPauseButRejectsInvalidImage(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("ETag", `"first"`) + fmt.Fprint(w, "fake body") + })) + defer server.Close() + dir := t.TempDir() + final, part := filepath.Join(dir, "restore.ipsw"), filepath.Join(dir, "restore.part.ipsw") + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + err := ResumeValidated(ctx, server.Client(), server.URL, final, part, 1024, nil, func(ctx context.Context, _ string) error { + cancel() + return ctx.Err() + }) + if !errors.Is(err, context.Canceled) { + t.Fatalf("pause: %v", err) + } + if _, err := os.Stat(part); err != nil { + t.Fatalf("pause did not keep partial: %v", err) + } + badImage := errors.New("not a restore image") + err = ResumeValidated(t.Context(), server.Client(), server.URL, final, part, 1024, nil, func(context.Context, string) error { + return &InvalidDownloadError{Err: badImage} + }) + if !errors.Is(err, badImage) { + t.Fatalf("validate: %v", err) + } + for _, file := range []string{part, part + ".etag", final} { + if _, err := os.Stat(file); !os.IsNotExist(err) { + t.Fatalf("invalid image left %s: %v", file, err) + } + } +} diff --git a/internal/host/host.go b/internal/host/host.go index 4cf511e..8203172 100644 --- a/internal/host/host.go +++ b/internal/host/host.go @@ -61,29 +61,36 @@ type LogicalCPUInfo struct { SMT bool `json:"smt"` } +type AppleVirtualizationStatus struct { + Ready bool `json:"ready"` + Detail string `json:"detail,omitempty"` +} + type Report struct { - DefenderRealtimeActive bool `json:"defender_realtime_active,omitempty"` - OS string `json:"os"` - Arch string `json:"arch"` - Timezone string `json:"timezone,omitempty"` - LogicalCPUs int `json:"logical_cpus"` - PhysicalCores int `json:"physical_cores"` - HasHybridCores bool `json:"has_hybrid_cores"` - PCoreCount int `json:"p_core_count"` - ECoreCount int `json:"e_core_count"` - LPECoreCount int `json:"lpe_core_count,omitempty"` - PCoreMask uint64 `json:"p_core_mask"` - PCoreMaskHex string `json:"p_core_mask_hex"` - PCoreLogicalCPUs []int `json:"p_core_logical_cpus,omitempty"` - ECoreLogicalCPUs []int `json:"e_core_logical_cpus,omitempty"` - NonLPEMask uint64 `json:"non_lpe_mask,omitempty"` - NonLPEMaskHex string `json:"non_lpe_mask_hex,omitempty"` - NonLPELogicalCPUs []int `json:"non_lpe_logical_cpus,omitempty"` - CPUTopology []LogicalCPUInfo `json:"cpu_topology,omitempty"` - TotalRAMGB float64 `json:"total_ram_gb"` - AvailRAMGB float64 `json:"avail_ram_gb"` - MemoryLoadPct int `json:"memory_load_pct"` - MemorySpec *HostMemorySpec `json:"memory_spec,omitempty"` + AppleVirtualization *AppleVirtualizationStatus `json:"apple_virtualization,omitempty"` + DefenderRealtimeActive bool `json:"defender_realtime_active,omitempty"` + OS string `json:"os"` + Arch string `json:"arch"` + Timezone string `json:"timezone,omitempty"` + LogicalCPUs int `json:"logical_cpus"` + PhysicalCores int `json:"physical_cores"` + HasHybridCores bool `json:"has_hybrid_cores"` + PCoreCount int `json:"p_core_count"` + ECoreCount int `json:"e_core_count"` + LPECoreCount int `json:"lpe_core_count,omitempty"` + PCoreMask uint64 `json:"p_core_mask"` + PCoreMaskHex string `json:"p_core_mask_hex"` + PCoreLogicalCPUs []int `json:"p_core_logical_cpus,omitempty"` + ECoreLogicalCPUs []int `json:"e_core_logical_cpus,omitempty"` + NonLPEMask uint64 `json:"non_lpe_mask,omitempty"` + NonLPEMaskHex string `json:"non_lpe_mask_hex,omitempty"` + NonLPELogicalCPUs []int `json:"non_lpe_logical_cpus,omitempty"` + CPUTopology []LogicalCPUInfo `json:"cpu_topology,omitempty"` + TotalRAMGB float64 `json:"total_ram_gb"` + AvailRAMGB float64 `json:"avail_ram_gb"` + MemoryLoadPct int `json:"memory_load_pct"` + MemoryUsageKnown bool `json:"memory_usage_known,omitempty"` + MemorySpec *HostMemorySpec `json:"memory_spec,omitempty"` // QEMU commits all guest RAM at start (CreateFileMapping), so a VM requires // available Windows commit charge rather than physical free RAM alone. Both // values include expandable paging-file headroom (CommitHeadroom). diff --git a/internal/host/host_windows.go b/internal/host/host_windows.go index a7d790b..196780f 100644 --- a/internal/host/host_windows.go +++ b/internal/host/host_windows.go @@ -172,6 +172,7 @@ func Inspect(dataRoot string) Report { if totalGB, availGB, ok := probeMemoryGB(); ok { rep.TotalRAMGB = totalGB rep.AvailRAMGB = availGB + rep.MemoryUsageKnown = true } if ms, ok := memoryStatus(); ok { rep.MemoryLoadPct = int(ms.MemoryLoad) diff --git a/internal/host/memory_darwin.go b/internal/host/memory_darwin.go new file mode 100644 index 0000000..48f2b4c --- /dev/null +++ b/internal/host/memory_darwin.go @@ -0,0 +1,22 @@ +package host + +import "math/bits" + +// Non-cache usage is anonymous memory less purgeable pages, plus wired +// memory and the physical pages occupied by the compressor. File-backed +// cache is not counted as used here; this is an estimate, not memory pressure. +func darwinMemoryBytes(total, pageSize, anonymous, purgeable, wired, compressed uint64) (uint64, bool) { + if total == 0 || pageSize == 0 { + return 0, false + } + anonymous -= min(anonymous, purgeable) + pages, carry := bits.Add64(anonymous, wired, 0) + if carry != 0 { + return 0, false + } + pages, carry = bits.Add64(pages, compressed, 0) + if carry != 0 || pages > total/pageSize { + return 0, false + } + return pages * pageSize, true +} diff --git a/internal/host/memory_darwin_cgo.go b/internal/host/memory_darwin_cgo.go new file mode 100644 index 0000000..93547ad --- /dev/null +++ b/internal/host/memory_darwin_cgo.go @@ -0,0 +1,27 @@ +//go:build darwin && cgo + +package host + +/* +#include +#include +#include + +static int reims_memory_stats(vm_statistics64_data_t *stats) { + mach_port_t host = mach_host_self(); + mach_msg_type_number_t count = HOST_VM_INFO64_COUNT; + kern_return_t result = host_statistics64(host, HOST_VM_INFO64, (host_info64_t)stats, &count); + mach_port_deallocate(mach_task_self(), host); + return result == KERN_SUCCESS && count >= HOST_VM_INFO64_REV1_COUNT; +} +*/ +import "C" + +func darwinUsedMemory(total uint64) (uint64, bool) { + var stats C.vm_statistics64_data_t + if C.reims_memory_stats(&stats) == 0 { + return 0, false + } + return darwinMemoryBytes(total, uint64(C.getpagesize()), uint64(stats.internal_page_count), + uint64(stats.purgeable_count), uint64(stats.wire_count), uint64(stats.compressor_page_count)) +} diff --git a/internal/host/memory_darwin_nocgo.go b/internal/host/memory_darwin_nocgo.go new file mode 100644 index 0000000..00ba306 --- /dev/null +++ b/internal/host/memory_darwin_nocgo.go @@ -0,0 +1,5 @@ +//go:build darwin && !cgo + +package host + +func darwinUsedMemory(_ uint64) (uint64, bool) { return 0, false } diff --git a/internal/host/memory_darwin_test.go b/internal/host/memory_darwin_test.go new file mode 100644 index 0000000..e593cbe --- /dev/null +++ b/internal/host/memory_darwin_test.go @@ -0,0 +1,28 @@ +package host + +import ( + "math" + "testing" +) + +func TestDarwinMemoryUsageExcludesReclaimablePages(t *testing.T) { + const page = 16384 + for _, tc := range []struct { + name string + total, anon, purge, wired, compressed uint64 + want uint64 + ok bool + }{ + {"cache is excluded", 100 * page, 40, 5, 15, 10, 60 * page, true}, + {"purgeable cannot underflow", 100 * page, 10, 15, 3, 2, 5 * page, true}, + {"usage exceeds physical RAM", 100 * page, 80, 0, 40, 0, 0, false}, + {"counter overflow", 100 * page, math.MaxUint64, 0, 2, 0, 0, false}, + } { + t.Run(tc.name, func(t *testing.T) { + got, ok := darwinMemoryBytes(tc.total, page, tc.anon, tc.purge, tc.wired, tc.compressed) + if got != tc.want || ok != tc.ok { + t.Fatalf("usage = (%d, %v), want (%d, %v)", got, ok, tc.want, tc.ok) + } + }) + } +} diff --git a/internal/host/resources_darwin.go b/internal/host/resources_darwin.go new file mode 100644 index 0000000..f583db0 --- /dev/null +++ b/internal/host/resources_darwin.go @@ -0,0 +1,35 @@ +package host + +import ( + "math" + "path/filepath" + + "golang.org/x/sys/unix" +) + +func inspectPlatformResources(report *Report) { + if cores, err := unix.SysctlUint32("hw.physicalcpu"); err == nil { + report.PhysicalCores = int(cores) + } + if memory, err := unix.SysctlUint64("hw.memsize"); err == nil && memory > 0 { + const gib = 1 << 30 + report.TotalRAMGB = float64(memory) / gib + if used, ok := darwinUsedMemory(memory); ok { + report.AvailRAMGB = float64(memory-used) / gib + report.MemoryLoadPct = int(math.Round(float64(used) / float64(memory) * 100)) + report.MemoryUsageKnown = true + } + } + report.FreeDiskGB = darwinDataFreeGB(report.DataRoot, FreeGB) +} + +func darwinDataFreeGB(path string, probe func(string) (float64, bool)) float64 { + for dir := filepath.Clean(path); ; dir = filepath.Dir(dir) { + if free, ok := probe(dir); ok { + return free + } + if filepath.Dir(dir) == dir { + return 0 + } + } +} diff --git a/internal/host/resources_darwin_test.go b/internal/host/resources_darwin_test.go new file mode 100644 index 0000000..5de4bf8 --- /dev/null +++ b/internal/host/resources_darwin_test.go @@ -0,0 +1,30 @@ +package host + +import ( + "reflect" + "testing" +) + +func TestDarwinDataFreeGBFallsBackToNearestProbeableParent(t *testing.T) { + var paths []string + got := darwinDataFreeGB("/data/private/vms", func(path string) (float64, bool) { + paths = append(paths, path) + return 20, path == "/data" + }) + if want := []string{"/data/private/vms", "/data/private", "/data"}; got != 20 || !reflect.DeepEqual(paths, want) { + t.Fatalf("got %g GiB and probed %v; want 20 GiB and %v", got, paths, want) + } +} + +func TestDarwinDataFreeGBStopsOnKnownZeroOrRoot(t *testing.T) { + for _, path := range []string{"/full", "/"} { + count := 0 + got := darwinDataFreeGB(path, func(string) (float64, bool) { + count++ + return 0, path == "/full" + }) + if got != 0 || count != 1 { + t.Fatalf("%s: got %g GiB and %d probes; want 0 GiB and one probe", path, got, count) + } + } +} diff --git a/internal/host/resources_other.go b/internal/host/resources_other.go new file mode 100644 index 0000000..e5686a3 --- /dev/null +++ b/internal/host/resources_other.go @@ -0,0 +1,5 @@ +//go:build !windows && !darwin + +package host + +func inspectPlatformResources(_ *Report) {} diff --git a/internal/host/stubs_hardware_other.go b/internal/host/stubs_hardware_other.go index 4c6d0f8..6114120 100644 --- a/internal/host/stubs_hardware_other.go +++ b/internal/host/stubs_hardware_other.go @@ -17,7 +17,7 @@ func Inspect(dataRoot string) Report { displays := probeDisplays() primary := PrimaryDisplayOf(displays) presets, rec := RecommendDisplayPresets(primary) - return Report{ + report := Report{ OS: runtime.GOOS, Arch: runtime.GOARCH, LogicalCPUs: runtime.NumCPU(), @@ -33,6 +33,8 @@ func Inspect(dataRoot string) Report { ProcessorScheduling: probeProcessorScheduling(), Audio: ProbeAudio(), } + inspectPlatformResources(&report) + return report } func ConfigureVulkanDrivers() {} diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 92a092f..2f53337 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -36,6 +36,12 @@ var catalog = map[Locale]map[string]string{ "cli.start.running_in_tray": "{name} 已在启动中(Reims-Go 在托盘运行)。", "cli.start.spawning_tray": "在后台拉起 Reims-Go(托盘)来启动 {name}…", "cli.start.timeout": "Reims-Go 在 {timeout} 内没有回报 {name} 的启动结果;请看界面的日志面板(若正在运行的是旧版 Reims-Go,请先退出它)", + "cli.usage.apple.create": " vm create --ipsw 从本地 Apple 恢复镜像创建虚拟机", + "cli.usage.apple.delete": " vm delete [--keep-files] 删除已关机的虚拟机", + "cli.usage.apple.doctor": " doctor 检查 Apple 虚拟化环境", + "cli.usage.apple.header": "reims-go - Apple 芯片 Mac 实验性虚拟机管理器", + "cli.usage.apple.start": " vm start 启动虚拟机并打开窗口", + "cli.usage.apple.stop": " vm stop [--force] 关闭虚拟机", "cli.usage.cmd_doctor": " doctor 宿主机环境体检(WHPX / 显卡 ICD / P-E 核 / 磁盘 / 运行时)", "cli.usage.cmd_inst_cached": " installer cached 查看已下载的安装包及占用空间", "cli.usage.cmd_inst_del": " installer delete <文件名> 删除已下载的安装包(正在使用或下载中的会被拒绝)", @@ -68,7 +74,7 @@ var catalog = map[Locale]map[string]string{ "cli.usage.section_usage": "用法:", "close": "关闭", "closeDownloadsConfirm": "退出", - "closeDownloadsDesc": "仍有下载正在进行,退出会中断它们。", + "closeDownloadsDesc": "退出会中断正在进行的下载或 macOS 安装。", "closeDownloadsTitle": "退出 Reims-Go?", "closeWindow": "关闭", "collapseLogs": "收起日志", @@ -88,6 +94,8 @@ var catalog = map[Locale]map[string]string{ "delete": "删除…", "deleteEllipsis": "删除…", "displays": "显示器数量", + "doctor.apple_virtualization.ready": "可用", + "doctor.apple_virtualization.unavailable": "不可用", "doctor.cow_chain": "CoW 磁盘派生链体检", "doctor.cow_chain.broken": "虚拟机 {vm} 的系统盘 CoW 链存在缺失父镜像(深度 {depth} 层,{path})", "doctor.cow_chain.item": "虚拟机 {vm} 的系统盘 CoW 链深度为 {depth} 层(≥ {warn}),未分配簇读穿透会拖慢小文件 I/O,建议合并或基于基础镜像重新派生", @@ -113,6 +121,7 @@ var catalog = map[Locale]map[string]string{ "doctor.pcores.detail": "{count} 核,掩码 {mask}(CPU {cpus})", "doctor.ram": "宿主机内存", "doctor.ram.detail": "共 {total, number, .1} GB / 可用 {avail, number, .1} GB", + "doctor.ram.total_only": "共 {total, number, .1} GB(可用内存未知)", "doctor.runtime": "便携运行时", "doctor.runtime.active": "当前激活:{commit}({dir})", "doctor.runtime.none": "尚未安装(运行 reims-go runtime install <压缩包> 导入)", @@ -193,6 +202,8 @@ var catalog = map[Locale]map[string]string{ "err.qemu_aslr.image_policy": "Windows 已按程序名为 qemu-system-x86_64.exe 配置防护,已跳过此运行时的 ASLR 规则。可在 Windows 安全中心的「漏洞保护 → 程序设置」中管理 QEMU 的 ASLR", "err.quit.stop_failed": "无法关闭虚拟机「{name}」,已取消退出。", "err.quit.timeout": "虚拟机「{name}」关机超时,已取消退出。", + "err.restore_catalog_unavailable": "暂时无法读取 Apple 的恢复镜像目录,可重试或选择本地 IPSW。", + "err.restore_catalog_unsupported": "当前 Nivfold 版本不支持查询恢复镜像,可更新 Nivfold 或选择本地 IPSW。", "err.runtime_changed": "操作期间运行时已切换,请重试以使用当前选定的版本。", "err.runtime_not_installed": "未找到已激活的便携运行时,请先执行 `reims-go runtime install <归档路径>`", "err.snapshot.name_empty": "请输入恢复点名称", @@ -402,6 +413,24 @@ var catalog = map[Locale]map[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": "最小化", @@ -586,6 +615,7 @@ var catalog = map[Locale]map[string]string{ "taskDownload": "下载 macOS {v}", "taskPluginDownload": "下载 {name}", "taskRecoveryDownload": "正在为 {name} 拉取并挂载在线恢复镜像", + "taskRestoreVM": "在 {name} 上安装 macOS", "taskRuntime": "安装运行时 {v}", "tasksRunning": "{n, plural, other {# 个任务进行中}}", "themeDark": "深色", @@ -712,6 +742,8 @@ var catalog = map[Locale]map[string]string{ "window.close.description_no_suspend": "当前运行时不支持挂起。关机将请求系统关闭。", "window.close.suspend": "挂起", "window.close.title": "关闭「{name}」?", + "wizardDriverListFailed": "无法加载客体驱动", + "wizardNoDriver": "没有可用的客体驱动", }, EnUS: { "affinity.applied.all": "[CPU] Set QEMU (PID {pid}) affinity to all CPUs ({count} logical CPUs, mask {mask}{eco})", @@ -746,6 +778,12 @@ var catalog = map[Locale]map[string]string{ "cli.start.running_in_tray": "{name} is starting (Reims-Go is running in the tray).", "cli.start.spawning_tray": "Starting Reims-Go in the tray to run {name}...", "cli.start.timeout": "Reims-Go did not report starting {name} within {timeout}; check its log panel (quit it first if it is an older version)", + "cli.usage.apple.create": " vm create --ipsw Create from a local Apple restore image", + "cli.usage.apple.delete": " vm delete [--keep-files] Remove a stopped VM", + "cli.usage.apple.doctor": " doctor Check Apple Virtualization support", + "cli.usage.apple.header": "reims-go - Experimental Apple silicon VM manager", + "cli.usage.apple.start": " vm start Start a VM and open its viewer", + "cli.usage.apple.stop": " vm stop [--force] Shut down a VM", "cli.usage.cmd_doctor": " doctor Inspect host (WHPX / Vulkan GPUs / P-E cores / disk / runtime)", "cli.usage.cmd_inst_cached": " installer cached List downloaded installers and the space they take", "cli.usage.cmd_inst_del": " installer delete Delete a downloaded installer (refused if in use or downloading)", @@ -778,7 +816,7 @@ var catalog = map[Locale]map[string]string{ "cli.usage.section_usage": "Usage:", "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", @@ -798,6 +836,8 @@ var catalog = map[Locale]map[string]string{ "delete": "Delete…", "deleteEllipsis": "Delete…", "displays": "Displays", + "doctor.apple_virtualization.ready": "Ready", + "doctor.apple_virtualization.unavailable": "Unavailable", "doctor.cow_chain": "CoW Disk Backing Chain Check", "doctor.cow_chain.broken": "VM {vm} system disk CoW backing chain has a missing parent image (depth {depth}, {path})", "doctor.cow_chain.item": "VM {vm} system disk has a {depth}-layer CoW backing chain (>= {warn}); read-through slows small-file I/O — consider flattening or re-deriving from the base image", @@ -823,6 +863,7 @@ var catalog = map[Locale]map[string]string{ "doctor.pcores.detail": "{count, plural, one {# core} other {# cores}}, mask {mask} (CPUs {cpus})", "doctor.ram": "Host Memory", "doctor.ram.detail": "{total, number, .1} GB total / {avail, number, .1} GB avail", + "doctor.ram.total_only": "{total, number, .1} GB total (available memory unknown)", "doctor.runtime": "Portable Runtime", "doctor.runtime.active": "Active: {commit} ({dir})", "doctor.runtime.none": "Not installed (run `reims-go runtime install `)", @@ -903,6 +944,8 @@ var catalog = map[Locale]map[string]string{ "err.qemu_aslr.image_policy": "Windows already has a program-wide rule for qemu-system-x86_64.exe, so this runtime’s ASLR rule was skipped. Manage QEMU’s ASLR in Windows Security under Exploit protection → Program settings.", "err.quit.stop_failed": "Could not shut down “{name}”. Quit canceled.", "err.quit.timeout": "Shutdown timed out for “{name}”. Quit canceled.", + "err.restore_catalog_unavailable": "Apple’s restore image catalog is unavailable. Retry or choose a local IPSW.", + "err.restore_catalog_unsupported": "This Nivfold version cannot query restore images. Update Nivfold or choose a local IPSW.", "err.runtime_changed": "The selected runtime changed during this operation. Retry to use the current selection.", "err.runtime_not_installed": "no active portable runtime found; run `reims-go runtime install ` first", "err.snapshot.name_empty": "Enter a restore point name", @@ -1112,6 +1155,24 @@ var catalog = map[Locale]map[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", @@ -1296,6 +1357,7 @@ var catalog = map[Locale]map[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", @@ -1422,6 +1484,8 @@ var catalog = map[Locale]map[string]string{ "window.close.description_no_suspend": "The current runtime does not support suspend. Shut down asks macOS to shut down.", "window.close.suspend": "Suspend", "window.close.title": "Close “{name}”?", + "wizardDriverListFailed": "Could not load guest drivers", + "wizardNoDriver": "No eligible guest driver is available", }, } @@ -1459,6 +1523,7 @@ var paramOrder = map[string][]string{ "doctor.gpu.warn.amd_rdna2": {"ref"}, "doctor.pcores.detail": {"count", "mask", "cpus"}, "doctor.ram.detail": {"total", "avail"}, + "doctor.ram.total_only": {"total"}, "doctor.runtime.active": {"commit", "dir"}, "elevateActionFallbackTitle": {"action"}, "elevateSource": {"name"}, @@ -1576,6 +1641,7 @@ var paramOrder = map[string][]string{ "taskDownload": {"v"}, "taskPluginDownload": {"name"}, "taskRecoveryDownload": {"name"}, + "taskRestoreVM": {"name"}, "taskRuntime": {"v"}, "tasksRunning": {"n"}, "toastAffinityApplied": {"count", "mask"}, diff --git a/internal/macos/applevz/config.go b/internal/macos/applevz/config.go new file mode 100644 index 0000000..b1138f2 --- /dev/null +++ b/internal/macos/applevz/config.go @@ -0,0 +1,216 @@ +package applevz + +import ( + "context" + "encoding/json" + "fmt" + "maps" + "os" + "path/filepath" + "regexp" + "slices" + "strconv" + "strings" + + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/plugin" +) + +const ( + minCPUs = 2 + maxCPUs = 64 + minMemoryMiB = 4096 + maxMemoryMiB = 1024 * 1024 + minDiskGiB = 64 + maxDiskGiB = 16 * 1024 +) + +var vmNamePattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,62}$`) + +func validName(name string) bool { return vmNamePattern.MatchString(name) } + +// vmConfig is the on-disk contract with the native runner. The restore path is +// passed to the installer only and is not saved once provisioning begins. +type vmConfig struct { + Name string `json:"name"` + CPUs int `json:"cpu_count"` + MemoryMiB int `json:"memory_mib"` + DiskGiB int `json:"disk_gib"` +} + +func defaultConfig(name string) vmConfig { + return vmConfig{Name: name, CPUs: 4, MemoryMiB: 8192, DiskGiB: 64} +} + +func (*Driver) CreateSchema() *plugin.SettingsSchema { + defaults := defaultConfig("") + return &plugin.SettingsSchema{ + Order: []string{"restore_path", "cpus", "memory", "disk_size"}, + Properties: map[string]plugin.SettingProperty{ + "restore_path": { + Type: "string", Title: plugin.LocalizedText{ZhCN: "macOS 恢复映像", EnUS: "macOS restore image"}, + Description: plugin.LocalizedText{ZhCN: "选择本机上的 .ipsw 文件", EnUS: "Choose a local .ipsw file"}, + Required: true, FilePattern: "*.ipsw", + }, + "cpus": cpuProperty(defaults.CPUs), + "memory": memoryProperty(formatMemory(defaults.MemoryMiB)), + "disk_size": { + Type: "string", Title: plugin.LocalizedText{ZhCN: "磁盘容量", EnUS: "Disk size"}, + Description: plugin.LocalizedText{ZhCN: "至少 64 GiB,例如 128G", EnUS: "At least 64 GiB, for example 128G"}, + Default: fmt.Sprintf("%dG", defaults.DiskGiB), + }, + }, + } +} + +func (*Driver) SettingsSchema() *plugin.SettingsSchema { + return &plugin.SettingsSchema{ + Scope: "vm", Order: []string{"cpus", "memory"}, + Properties: map[string]plugin.SettingProperty{ + "cpus": cpuProperty(nil), "memory": memoryProperty(nil), + }, + } +} + +func cpuProperty(value any) plugin.SettingProperty { + lo, hi := float64(minCPUs), float64(maxCPUs) + return plugin.SettingProperty{ + Type: "integer", Title: plugin.LocalizedText{ZhCN: "虚拟处理器", EnUS: "Virtual CPUs"}, + Default: value, Minimum: &lo, Maximum: &hi, Effect: "next_start", + } +} + +func memoryProperty(value any) plugin.SettingProperty { + return plugin.SettingProperty{ + Type: "string", Title: plugin.LocalizedText{ZhCN: "内存", EnUS: "Memory"}, + Description: plugin.LocalizedText{ZhCN: "使用 G 或 M,例如 8G 或 8192M", EnUS: "Use G or M, for example 8G or 8192M"}, + Default: value, Effect: "next_start", + } +} + +func (d *Driver) ValidateCreate(ctx context.Context, req driver.CreateRequest) []driver.ValidationIssue { + _, _, issues := d.createConfig(ctx, req) + return issues +} + +func (d *Driver) createConfig(ctx context.Context, req driver.CreateRequest) (vmConfig, string, []driver.ValidationIssue) { + cfg := defaultConfig(req.Name) + if err := ctx.Err(); err != nil { + return cfg, "", []driver.ValidationIssue{issue("", err)} + } + var issues []driver.ValidationIssue + if req.DriverID != "" && req.DriverID != ID { + issues = append(issues, issue("driver_id", fmt.Errorf("incorrect driver %q", req.DriverID))) + } + if !validName(cfg.Name) { + issues = append(issues, issue("name", fmt.Errorf("the VM name must contain 1–63 letters, digits, dots, underscores or hyphens and start with a letter or digit"))) + } + if req.Dir != "" { + issues = append(issues, issue("dir", fmt.Errorf("Apple virtual machines must be created in the driver data folder"))) + } + issues = append(issues, cfg.apply(req.Options, true)...) + restore, err := restorePath(req.Options["restore_path"]) + if err != nil { + issues = append(issues, issue("restore_path", err)) + } + return cfg, restore, issues +} + +func (cfg *vmConfig) apply(changes map[string]any, creating bool) []driver.ValidationIssue { + var issues []driver.ValidationIssue + for _, field := range slices.Sorted(maps.Keys(changes)) { + value := changes[field] + var err error + switch field { + case "cpus": + cfg.CPUs, err = parseQuantity(value, "", minCPUs, maxCPUs) + case "memory": + cfg.MemoryMiB, err = parseQuantity(value, "MiB", minMemoryMiB, maxMemoryMiB) + case "disk_size": + if creating { + cfg.DiskGiB, err = parseQuantity(value, "GiB", minDiskGiB, maxDiskGiB) + } else { + err = fmt.Errorf("disk size cannot be changed after installation") + } + case "restore_path": + if !creating { + err = fmt.Errorf("restore image cannot be changed after installation") + } + default: + err = fmt.Errorf("setting %q is not supported by the Apple virtualization driver", field) + } + if err != nil { + issues = append(issues, issue(field, err)) + } + } + return issues +} + +func parseQuantity(value any, unit string, minimum, maximum int) (int, error) { + factor := 1 + var n int64 + var err error + switch typed := value.(type) { + case int: + n = int64(typed) + case float64: + if typed >= 0 && typed <= float64(maximum) && typed == float64(int64(typed)) { + n = int64(typed) + } + case json.Number: + n, err = typed.Int64() + case string: + text := strings.ToUpper(strings.TrimSpace(typed)) + if unit == "MiB" { + switch { + case strings.HasSuffix(text, "GIB"): + text, factor = strings.TrimSuffix(text, "GIB"), 1024 + case strings.HasSuffix(text, "G"): + text, factor = strings.TrimSuffix(text, "G"), 1024 + default: + text = strings.TrimSuffix(strings.TrimSuffix(text, "MIB"), "M") + } + } else if unit == "GiB" { + text = strings.TrimSuffix(strings.TrimSuffix(text, "GIB"), "G") + } + n, err = strconv.ParseInt(strings.TrimSpace(text), 10, 64) + } + if err != nil || n < 1 || n > int64(maximum/factor) || n*int64(factor) < int64(minimum) { + message := fmt.Sprintf("enter a whole number from %d to %d", minimum, maximum) + if unit != "" { + message += " " + unit + } + return 0, fmt.Errorf("%s", message) + } + return int(n) * factor, nil +} + +func restorePath(value any) (string, error) { + path, _ := value.(string) + if !filepath.IsAbs(path) || !strings.EqualFold(filepath.Ext(path), ".ipsw") { + return "", fmt.Errorf("choose a local .ipsw file using its absolute path") + } + path, err := filepath.EvalSymlinks(path) + if err != nil { + return "", fmt.Errorf("open macOS restore image: %w", err) + } + info, err := os.Stat(path) + if err != nil { + return "", fmt.Errorf("open macOS restore image: %w", err) + } + if !info.Mode().IsRegular() || info.Size() == 0 { + return "", fmt.Errorf("the macOS restore image must be a non-empty regular file") + } + return path, nil +} + +func formatMemory(mib int) string { + if mib%1024 == 0 { + return fmt.Sprintf("%dG", mib/1024) + } + return fmt.Sprintf("%dM", mib) +} + +func issue(field string, err error) driver.ValidationIssue { + return driver.ValidationIssue{Field: field, Message: err.Error()} +} diff --git a/internal/macos/applevz/driver.go b/internal/macos/applevz/driver.go new file mode 100644 index 0000000..ab6b938 --- /dev/null +++ b/internal/macos/applevz/driver.go @@ -0,0 +1,147 @@ +// Package applevz adapts the native Apple virtualization runner as a hosted driver. +package applevz + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "path/filepath" + + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/plugin" +) + +const ( + ID = "builtin.driver.apple-vz" + VMRoot = "apple-vz" +) + +// Options selects the current application data root and a trusted runner. An +// empty RunnerPath looks only alongside the current executable, never in PATH. +type Options struct { + DataRoot func() string + RunnerPath string +} + +// Driver is independent of the Windows runtime and owns no host-side VM process API. +type Driver struct{ opts Options } + +var ( + _ driver.Driver = (*Driver)(nil) + _ driver.LogDriver = (*Driver)(nil) + _ driver.WindowDriver = (*Driver)(nil) +) + +func New(opts Options) *Driver { return &Driver{opts: opts} } + +func (*Driver) ID() string { return ID } + +func (*Driver) DisplayName() plugin.LocalizedText { + return plugin.LocalizedText{ZhCN: "macOS(Apple 虚拟化)", EnUS: "macOS (Apple virtualization)"} +} + +func (*Driver) RuntimeKind() string { return "external" } +func (*Driver) RuntimeAPIRange() string { return "" } +func (*Driver) Capabilities() []string { return []string{driver.CapHosted, driver.CapWindow} } + +// Inventory lists registered instances even when the native driver is inactive. +func Inventory(dataRoot string) ([]driver.VMInfo, error) { + d := New(Options{DataRoot: func() string { return dataRoot }}) + return d.List(context.Background()) +} + +func (d *Driver) List(ctx context.Context) ([]driver.VMInfo, error) { + root, err := d.root(false) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + entries, err := os.ReadDir(root) + if err != nil { + return nil, err + } + out := make([]driver.VMInfo, 0, len(entries)) + for _, entry := range entries { + if err := ctx.Err(); err != nil { + return nil, err + } + if !entry.IsDir() || !validName(entry.Name()) { + continue + } + vm := instance{dir: filepath.Join(root, entry.Name()), name: entry.Name()} + if !vm.owned() { + continue + } + out = append(out, d.info(vm)) + } + return out, nil +} + +func (d *Driver) Show(ctx context.Context, name string) (driver.VMInfo, error) { + if err := ctx.Err(); err != nil { + return driver.VMInfo{}, err + } + vm, err := d.find(name) + if err != nil { + return driver.VMInfo{}, err + } + return d.info(vm), nil +} + +func (d *Driver) info(vm instance) driver.VMInfo { + info := driver.VMInfo{ + Name: vm.name, DriverID: ID, DriverName: d.DisplayName().EnUS, + Directory: vm.dir, Capabilities: d.Capabilities(), Network: true, + GuestOS: &driver.GuestOSInfo{Family: driver.GuestFamilyMacOS, Arch: "arm64"}, + State: "broken", Phase: driver.PhaseNormal, + } + cfg, err := vm.config() + if err != nil { + return info + } + info.Name, info.CPUs, info.Memory = cfg.Name, cfg.CPUs, formatMemory(cfg.MemoryMiB) + info.DiskSummary = fmt.Sprintf("%d GiB", cfg.DiskGiB) + info.DriverData = map[string]any{"cpus": cfg.CPUs, "memory": info.Memory} + if vm.installed() == nil { + info.DiskPath = vm.path(machineDirectory, "disk.img") + info.State = "stopped" + } + if status, err := vm.status(); err == nil { + switch status.State { + case "installing": + info.State, info.Phase = "starting", driver.PhaseInstaller + case "starting", "running", "stopping": + info.State = status.State + } + } else { + info.State = "broken" + } + return info +} + +func (d *Driver) ReadLogs(ctx context.Context, name string, serial bool) (string, error) { + if serial { + return "", errors.ErrUnsupported + } + if err := ctx.Err(); err != nil { + return "", err + } + vm, err := d.find(name) + if err != nil { + return "", err + } + return vm.logTail(128 << 10) +} + +// ShowWindow reopens or brings forward the runner's native viewer. +func (d *Driver) ShowWindow(ctx context.Context, name string) error { + return d.control(ctx, name, "show", false, nil, nil) +} + +func (d *Driver) Stop(ctx context.Context, name string, force bool, stdout, stderr io.Writer) error { + return d.control(ctx, name, "stop", force, stdout, stderr) +} diff --git a/internal/macos/applevz/lifecycle.go b/internal/macos/applevz/lifecycle.go new file mode 100644 index 0000000..212603f --- /dev/null +++ b/internal/macos/applevz/lifecycle.go @@ -0,0 +1,176 @@ +package applevz + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "path/filepath" + + "github.com/Nwflower/reims-go/internal/atomicfile" + "github.com/Nwflower/reims-go/internal/driver" +) + +func (d *Driver) Create(ctx context.Context, req driver.CreateRequest, stdout, stderr io.Writer) error { + cfg, restore, issues := d.createConfig(ctx, req) + if len(issues) > 0 { + return errors.New(issues[0].Message) + } + bounds, err := d.probe(ctx) + if err != nil { + return err + } + if err := bounds.validate(cfg); err != nil { + return err + } + root, err := d.root(true) + if err != nil { + return err + } + op, err := lockOperations(root, cfg.Name) + if err != nil { + return err + } + defer op.Close() + vm, err := createInstance(root, cfg) + if err != nil { + return err + } + if err := d.invoke(ctx, vm, stdout, stderr, "install", "--ipsw", restore); err != nil { + return fmt.Errorf("install macOS into %q (see the VM logs): %w", vm.name, err) + } + return vm.installed() +} + +func createInstance(root string, cfg vmConfig) (instance, error) { + if existing, err := namedInstance(root, cfg.Name); err == nil { + return retryUnpublished(existing, cfg) + } else if !errors.Is(err, os.ErrNotExist) { + return instance{}, err + } + vm := instance{dir: filepath.Join(root, cfg.Name), name: cfg.Name} + if err := os.Mkdir(vm.dir, 0o700); err != nil { + return instance{}, err + } + if err := atomicfile.WriteJSON(vm.path(configFile), cfg, 0o600); err != nil { + return instance{}, errors.Join(err, os.Remove(vm.dir)) + } + if err := atomicfile.Write(vm.path(driver.OwnerMarkerFile), []byte(ID+"\n"), 0o600); err != nil { + return instance{}, errors.Join(err, os.Remove(vm.path(configFile)), os.Remove(vm.dir)) + } + return vm, nil +} + +func retryUnpublished(vm instance, cfg vmConfig) (instance, error) { + if err := requireDirectory(vm.dir); err != nil || !vm.owned() { + return instance{}, fmt.Errorf("an unmanaged directory already exists for %q", cfg.Name) + } + lock, err := acquireLock(vm.path(runnerLock), true) + if err != nil { + return instance{}, err + } + if lock == nil { + return instance{}, fmt.Errorf("VM %q is already in use", cfg.Name) + } + defer lock.Close() + for _, name := range []string{machineDirectory, ".applevz-installing"} { + if _, err := os.Lstat(vm.path(name)); err == nil { + if name == machineDirectory { + return instance{}, fmt.Errorf("VM %q already has a published machine", cfg.Name) + } + return instance{}, fmt.Errorf("VM %q has interrupted staging data; delete the incomplete VM before retrying", cfg.Name) + } else if !errors.Is(err, os.ErrNotExist) { + return instance{}, err + } + } + if _, err := vm.config(); err != nil { + return instance{}, err + } + cfg.Name = vm.name + return vm, atomicfile.WriteJSON(vm.path(configFile), cfg, 0o600) +} + +func (d *Driver) ValidateSet(ctx context.Context, req driver.SetRequest) []driver.ValidationIssue { + if err := ctx.Err(); err != nil { + return []driver.ValidationIssue{issue("", err)} + } + vm, err := d.find(req.Name) + if err == nil { + var cfg vmConfig + cfg, err = vm.config() + if err == nil { + return cfg.apply(req.Changes, false) + } + } + return []driver.ValidationIssue{issue("name", err)} +} + +func (d *Driver) Set(ctx context.Context, req driver.SetRequest, _, _ io.Writer) error { + vm, release, err := d.lockStopped(ctx, req.Name) + if err != nil { + return err + } + defer release() + if err := vm.installed(); err != nil { + return err + } + cfg, err := vm.config() + if err != nil { + return err + } + if issues := cfg.apply(req.Changes, false); len(issues) > 0 { + return errors.New(issues[0].Message) + } + bounds, err := d.probe(ctx) + if err != nil { + return err + } + bounds, err = vm.applyGuestMinimum(bounds) + if err != nil { + return err + } + if err := bounds.validate(cfg); err != nil { + return err + } + return atomicfile.WriteJSON(vm.path(configFile), cfg, 0o600) +} + +func (d *Driver) Delete(ctx context.Context, name string, keepFiles bool, _, _ io.Writer) error { + vm, release, err := d.lockStopped(ctx, name) + if err != nil { + return err + } + defer release() + if keepFiles { + return os.Remove(vm.path(driver.OwnerMarkerFile)) + } + // lockStopped re-resolved the owned, non-symlink child of the driver root. + return os.RemoveAll(vm.dir) +} + +func (d *Driver) lockStopped(ctx context.Context, name string) (instance, func(), error) { + if err := ctx.Err(); err != nil { + return instance{}, nil, err + } + root, err := d.root(false) + if err != nil { + return instance{}, nil, err + } + op, err := lockOperations(root, name) + if err != nil { + return instance{}, nil, err + } + vm, err := ownedInstance(root, name) + if err == nil { + var runtime *os.File + runtime, err = acquireLock(vm.path(runnerLock), true) + if runtime != nil { + return vm, func() { runtime.Close(); op.Close() }, nil + } + if err == nil { + err = fmt.Errorf("shut down VM %q before changing or deleting it", name) + } + } + return instance{}, nil, errors.Join(err, op.Close()) +} diff --git a/internal/macos/applevz/platform_darwin.go b/internal/macos/applevz/platform_darwin.go new file mode 100644 index 0000000..a5677cd --- /dev/null +++ b/internal/macos/applevz/platform_darwin.go @@ -0,0 +1,35 @@ +package applevz + +import ( + "os" + "os/exec" + "syscall" +) + +const safeOpenFlags = syscall.O_NOFOLLOW | syscall.O_NONBLOCK + +func sharedFile(info os.FileInfo) bool { + st, ok := info.Sys().(*syscall.Stat_t) + return !ok || st.Nlink != 1 +} + +func tryStatusLock(file *os.File) (bool, error) { + err := syscall.Flock(int(file.Fd()), syscall.LOCK_SH|syscall.LOCK_NB) + if err == syscall.EWOULDBLOCK { + return false, nil + } + return err == nil, err +} + +func detachRunner(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} +} + +func interruptInstaller(process *os.Process) error { + if err := process.Signal(syscall.SIGTERM); err != nil { + return err + } + // A successful atomic publication wins over a racing cancellation. A + // cancelled installer still exits nonzero and its context error is retained. + return os.ErrProcessDone +} diff --git a/internal/macos/applevz/platform_other.go b/internal/macos/applevz/platform_other.go new file mode 100644 index 0000000..af0f211 --- /dev/null +++ b/internal/macos/applevz/platform_other.go @@ -0,0 +1,22 @@ +//go:build !darwin + +package applevz + +import ( + "os" + "os/exec" + + "github.com/Nwflower/reims-go/internal/filelock" +) + +// The shared schema and inventory compile on other platforms. Probe never +// permits runner operations there, so process and open flags are Darwin-only. +const safeOpenFlags = 0 + +func tryStatusLock(file *os.File) (bool, error) { return filelock.TryLock(file) } + +func detachRunner(*exec.Cmd) {} + +func interruptInstaller(process *os.Process) error { return process.Kill() } + +func sharedFile(os.FileInfo) bool { return false } diff --git a/internal/macos/applevz/resources.go b/internal/macos/applevz/resources.go new file mode 100644 index 0000000..87d819d --- /dev/null +++ b/internal/macos/applevz/resources.go @@ -0,0 +1,42 @@ +package applevz + +import ( + "encoding/json" + "errors" + "fmt" + "os" +) + +func (b resourceBounds) validate(cfg vmConfig) error { + if cfg.CPUs < b.MinCPU || cfg.CPUs > b.MaxCPU { + return fmt.Errorf("this guest and host require %d–%d vCPUs", b.MinCPU, b.MaxCPU) + } + if uint64(cfg.MemoryMiB) < b.MinRAM || uint64(cfg.MemoryMiB) > b.MaxRAM { + return fmt.Errorf("this guest and host require %d–%d MiB RAM", b.MinRAM, b.MaxRAM) + } + return nil +} + +func (vm instance) applyGuestMinimum(bounds resourceBounds) (resourceBounds, error) { + raw, err := readSmallFile(vm.path(machineDirectory, "requirements.json")) + if errors.Is(err, os.ErrNotExist) { + return bounds, nil // VMs installed before Nivfold may not have these metadata. + } + if err != nil { + return bounds, err + } + var minimum struct { + Version int `json:"version"` + CPU int `json:"minimum_cpu_count"` + RAM uint64 `json:"minimum_memory_mib"` + } + if err := json.Unmarshal(raw, &minimum); err != nil || minimum.Version != 1 || minimum.CPU < 1 || minimum.RAM < 1 { + return bounds, errors.New("invalid or incompatible Nivfold guest requirements") + } + bounds.MinCPU = max(bounds.MinCPU, minimum.CPU) + bounds.MinRAM = max(bounds.MinRAM, minimum.RAM) + if bounds.MinCPU > bounds.MaxCPU || bounds.MinRAM > bounds.MaxRAM { + return bounds, errors.New("the guest's minimum CPU or memory exceeds this host's limit") + } + return bounds, nil +} diff --git a/internal/macos/applevz/restore.go b/internal/macos/applevz/restore.go new file mode 100644 index 0000000..ef7085a --- /dev/null +++ b/internal/macos/applevz/restore.go @@ -0,0 +1,59 @@ +package applevz + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os/exec" + "slices" + "time" +) + +// RestoreImage is metadata from the framework, not an installer or a user URL. +type RestoreImage struct { + Version string `json:"version"` + Build string `json:"build"` + URL string `json:"url,omitempty"` +} + +// ErrRestoreCatalogUnsupported distinguishes old runners from network failure. +var ErrRestoreCatalogUnsupported = errors.New("this Nivfold build does not support restore image downloads") + +// LatestRestoreImage queries Apple via Nivfold without transferring the image. +func (d *Driver) LatestRestoreImage(ctx context.Context) (RestoreImage, error) { + probe, err := d.runProbe(ctx) + if err != nil { + return RestoreImage{}, err + } + if !slices.Contains(probe.Capabilities, "restore-image") || !slices.Contains(probe.Capabilities, "inspect-restore-image") { + return RestoreImage{}, ErrRestoreCatalogUnsupported + } + return d.queryRestoreImage(ctx, 40*time.Second, "restore-image") +} + +// InspectRestoreImage uses the framework to read a local image and check host compatibility. +func (d *Driver) InspectRestoreImage(ctx context.Context, path string) (RestoreImage, error) { + return d.queryRestoreImage(ctx, 2*time.Minute, "inspect-restore-image", "--ipsw", path) +} + +func (d *Driver) queryRestoreImage(ctx context.Context, limit time.Duration, command string, args ...string) (RestoreImage, error) { + var result RestoreImage + path, err := d.runnerPath() + if err != nil { + return result, err + } + ctx, cancel := context.WithTimeout(ctx, limit) + defer cancel() + cmd := exec.CommandContext(ctx, path, append([]string{command}, args...)...) + var stdout, stderr outputTail + cmd.Stdout, cmd.Stderr = &stdout, &stderr + cmd.WaitDelay = 2 * time.Second + if err := cmd.Run(); err != nil { + return result, fmt.Errorf("Nivfold %s: %w", command, commandError(ctx, err, &stderr)) + } + if err := json.Unmarshal(stdout.Bytes(), &result); err != nil { + return result, fmt.Errorf("decode Nivfold restore image metadata: %w", err) + } + return result, nil +} diff --git a/internal/macos/applevz/runner.go b/internal/macos/applevz/runner.go new file mode 100644 index 0000000..09e315f --- /dev/null +++ b/internal/macos/applevz/runner.go @@ -0,0 +1,370 @@ +package applevz + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync" + "time" + + "github.com/Nwflower/reims-go/internal/driver" +) + +const runnerName = "nivfold" + +func (d *Driver) runnerPath() (string, error) { + if runtime.GOOS != "darwin" || runtime.GOARCH != "arm64" { + return "", errors.New("Apple virtualization requires Apple silicon macOS") + } + path := d.opts.RunnerPath + if path == "" { + executable, err := os.Executable() + if err != nil { + return "", err + } + path = filepath.Join(filepath.Dir(executable), runnerName) + } + if !filepath.IsAbs(path) { + return "", errors.New("the Apple virtualization helper path must be absolute") + } + info, err := os.Stat(path) + if err != nil { + return "", fmt.Errorf("find Apple virtualization helper %q: %w", path, err) + } + if !info.Mode().IsRegular() || info.Mode().Perm()&0o111 == 0 { + return "", fmt.Errorf("the Apple virtualization helper is not executable: %q", path) + } + return path, nil +} + +type resourceBounds struct { + MinCPU int `json:"minimum_cpu_count"` + MaxCPU int `json:"maximum_cpu_count"` + MinRAM uint64 `json:"minimum_memory_mib"` + MaxRAM uint64 `json:"maximum_memory_mib"` +} + +type runnerProbe struct { + Runtime string `json:"runtime"` + Version int `json:"protocol_version"` + Supported bool `json:"supported"` + Resources resourceBounds `json:"resources"` + Capabilities []string `json:"capabilities"` +} + +// Probe checks both local platform support and the runner's protocol version. +func (d *Driver) Probe(ctx context.Context) error { + _, err := d.runProbe(ctx) + return err +} + +func (d *Driver) probe(ctx context.Context) (resourceBounds, error) { + probe, err := d.runProbe(ctx) + return probe.Resources, err +} + +func (d *Driver) runProbe(ctx context.Context) (runnerProbe, error) { + var empty runnerProbe + path, err := d.runnerPath() + if err != nil { + return empty, err + } + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, path, "probe") + var stdout, stderr outputTail + cmd.Stdout, cmd.Stderr = &stdout, &stderr + cmd.WaitDelay = 2 * time.Second + if err := cmd.Run(); err != nil { + return empty, fmt.Errorf("check Nivfold: %w", commandError(ctx, err, &stderr)) + } + var probe runnerProbe + if err := json.Unmarshal(stdout.Bytes(), &probe); err != nil || probe.Runtime != runnerName || probe.Version != 1 { + return empty, errors.New("expected a compatible Nivfold runtime (protocol 1)") + } + if !probe.Supported { + return empty, errors.New("Nivfold reports this Mac is unsupported") + } + b := probe.Resources + if b.MinCPU < 1 || b.MaxCPU < b.MinCPU || b.MinRAM < 1 || b.MaxRAM < b.MinRAM { + return empty, errors.New("Nivfold did not report valid CPU and memory limits") + } + return probe, nil +} + +func (d *Driver) invoke(ctx context.Context, vm instance, stdout, stderr io.Writer, action string, tail ...string) error { + path, err := d.runnerPath() + if err != nil { + return err + } + args := append([]string{action, "--vm-dir", vm.dir}, tail...) + cmd := exec.CommandContext(ctx, path, args...) + cmd.WaitDelay = 2 * time.Second + if action == "install" { + cmd.WaitDelay = 15 * time.Second + cmd.Cancel = func() error { return signalInstallOwner(vm, cmd.Process) } + } + log, err := openRegular(vm.path(logFile), os.O_CREATE|os.O_WRONLY|os.O_APPEND) + if err != nil { + return err + } + defer log.Close() + var diagnostics outputTail + cmd.Stdout = io.MultiWriter(log, orDiscard(stdout)) + // A caller may provide the same writer twice (the GUI does). Go may copy + // stdout and stderr concurrently; route through one Go writer in that case + // by always serializing writes through a shared mutex-bearing writer. + cmd.Stderr = io.MultiWriter(log, &diagnostics, orDiscard(stderr)) + cmd.Stdout, cmd.Stderr = serializedWriters(cmd.Stdout, cmd.Stderr) + if err := cmd.Run(); err != nil { + if action == "install" && ctx.Err() != nil { + var exit *exec.ExitError + if errors.As(err, &exit) && exit.ExitCode() == 1 { + // Cleanup or a non-cancellation error must not look like a clean cancellation. + return commandError(context.WithoutCancel(ctx), err, &diagnostics) + } + } + return commandError(ctx, err, &diagnostics) + } + return nil +} + +func signalInstallOwner(vm instance, process *os.Process) error { + // Installing is published only after the runner's signal handler is armed. + // Wait briefly for it so early cancellation can use the same cleanup path. + deadline := time.Now().Add(250 * time.Millisecond) + for time.Now().Before(deadline) { + if status, err := vm.activeStatus(); err == nil && status.State == "installing" && status.PID == process.Pid { + break + } + time.Sleep(10 * time.Millisecond) + } + return interruptInstaller(process) +} + +func (d *Driver) control(ctx context.Context, name, action string, force bool, stdout, stderr io.Writer) error { + vm, err := d.find(name) + if err != nil { + return err + } + var flags []string + timeout := 5 * time.Second + if action == "stop" { + timeout = 70 * time.Second + if force { + timeout = 20 * time.Second + flags = append(flags, "--force") + } + } + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + return d.invoke(ctx, vm, stdout, stderr, action, flags...) +} + +func (d *Driver) Start(ctx context.Context, req driver.StartRequest) (driver.StartResult, error) { + if req.Ref.DriverID != "" && req.Ref.DriverID != ID { + return driver.StartResult{}, fmt.Errorf("incorrect driver %q", req.Ref.DriverID) + } + if err := startIntents(req); err != nil { + return driver.StartResult{}, err + } + if err := d.Probe(ctx); err != nil { + return driver.StartResult{}, err + } + return driver.StartResult{}, d.start(ctx, req.Ref.Name) +} + +func startIntents(req driver.StartRequest) error { + for _, intent := range req.Intents { + if intent.BlockReason != "" { + return errors.New(intent.BlockReason) + } + if len(intent.Args)+len(intent.Env)+len(intent.ClearKeys)+len(intent.PostStart) != 0 { + return fmt.Errorf("plugin %q requested startup changes unsupported by Apple virtualization", intent.PluginID) + } + for _, warning := range intent.Warnings { + if _, err := fmt.Fprintln(orDiscard(req.Stderr), warning); err != nil { + return err + } + } + } + return nil +} + +func (d *Driver) start(ctx context.Context, name string) error { + root, err := d.root(false) + if err != nil { + return err + } + op, err := lockOperations(root, name) + if err != nil { + return err + } + defer op.Close() + vm, err := ownedInstance(root, name) + if err != nil { + return err + } + if _, err := vm.config(); err != nil { + return err + } + if err := vm.installed(); err != nil { + return err + } + // The native owner takes the runtime lock. Probing it here would race + // read-only status requests and would not reserve it for this launch. + return d.launch(ctx, vm) +} + +func (d *Driver) launch(ctx context.Context, vm instance) error { + if err := ctx.Err(); err != nil { + return err + } + path, err := d.runnerPath() + if err != nil { + return err + } + log, err := openRegular(vm.path(logFile), os.O_CREATE|os.O_WRONLY|os.O_APPEND) + if err != nil { + return err + } + defer log.Close() + // The native runner, VM and viewer outlive this command and the desktop. + // File-backed output avoids blocking on a pipe or app writer after return. + cmd := exec.Command(path, "run", "--vm-dir", vm.dir) + cmd.Stdout, cmd.Stderr = log, log + detachRunner(cmd) + if err := cmd.Start(); err != nil { + return err + } + exited := make(chan error, 1) + go func() { exited <- cmd.Wait() }() + ctx, cancel := context.WithTimeout(ctx, 45*time.Second) + defer cancel() + if err := waitForStart(ctx, vm, cmd.Process.Pid, exited); err != nil { + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + err = errors.Join(err, d.cancelStart(vm, cmd.Process.Pid, exited)) + } + return fmt.Errorf("start VM %q (see the VM logs): %w", vm.name, err) + } + return nil +} + +func waitForStart(ctx context.Context, vm instance, pid int, exited <-chan error) error { + ticker := time.NewTicker(50 * time.Millisecond) + defer ticker.Stop() + var lastStatusErr error + for { + select { + case err := <-exited: + if err == nil { + err = errors.New("runner exited before the VM started") + } + return errors.Join(err, lastStatusErr) + case <-ctx.Done(): + return errors.Join(ctx.Err(), lastStatusErr) + case <-ticker.C: + status, err := vm.status() + if err != nil { + // A status check can race with the runner publishing its state. + lastStatusErr = fmt.Errorf("last startup status check: %w", err) + continue + } + if status.PID == pid && status.State == "running" { + return nil + } + } + } +} + +func (d *Driver) cancelStart(vm instance, pid int, exited <-chan error) error { + ctx, cancel := context.WithTimeout(context.Background(), 21*time.Second) + defer cancel() + // At cancellation the spawned helper may not have published a PID yet. + // Wait briefly, but never send a stop command for an unrelated owner. + for i := 0; i < 10; i++ { + status, err := vm.status() + if err != nil { + return fmt.Errorf("cannot confirm VM state after cancellation: %w", err) + } + if status.PID == pid { + err = d.invoke(ctx, vm, nil, nil, "stop", "--force", "--expect-pid", strconv.Itoa(pid)) + if err == nil { + return nil + } + // The runner publishes its starting state before opening its socket. + if i == 9 || ctx.Err() != nil { + return fmt.Errorf("could not cancel the native startup; check VM state: %w", err) + } + } else if status.PID > 0 { + return nil + } + select { + case <-exited: + return nil + case <-time.After(100 * time.Millisecond): + } + } + return errors.New("cannot confirm the startup owner; check VM state before retrying") +} + +type serialWriter struct { + mu *sync.Mutex + w io.Writer +} + +func (w serialWriter) Write(data []byte) (int, error) { + w.mu.Lock() + defer w.mu.Unlock() + return w.w.Write(data) +} + +func serializedWriters(stdout, stderr io.Writer) (io.Writer, io.Writer) { + mu := new(sync.Mutex) + return serialWriter{mu: mu, w: stdout}, serialWriter{mu: mu, w: stderr} +} + +func orDiscard(w io.Writer) io.Writer { + if w == nil { + return io.Discard + } + return w +} + +func commandError(ctx context.Context, err error, stderr *outputTail) error { + if ctx.Err() != nil { + return ctx.Err() + } + if detail := strings.TrimSpace(stderr.String()); detail != "" { + return fmt.Errorf("%w: %s", err, detail) + } + return err +} + +// outputTail bounds short protocol responses and diagnostic output in memory. +type outputTail struct{ bytes.Buffer } + +func (w *outputTail) Write(b []byte) (int, error) { + const limit = 8 << 10 + if len(b) >= limit { + w.Reset() + _, err := w.Buffer.Write(b[len(b)-limit:]) + return len(b), err + } + if drop := w.Len() + len(b) - limit; drop > 0 { + // Release consumed space instead of keeping a buffer that grows with + // consecutive writes. + copy(w.Bytes(), w.Bytes()[drop:]) + w.Truncate(w.Len() - drop) + } + return w.Buffer.Write(b) +} diff --git a/internal/macos/applevz/runner_test.go b/internal/macos/applevz/runner_test.go new file mode 100644 index 0000000..4a1154f --- /dev/null +++ b/internal/macos/applevz/runner_test.go @@ -0,0 +1,499 @@ +//go:build darwin && arm64 + +package applevz + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/signal" + "path/filepath" + "slices" + "strings" + "syscall" + "testing" + "testing/synctest" + "time" + + "github.com/Nwflower/reims-go/internal/atomicfile" + "github.com/Nwflower/reims-go/internal/driver" +) + +func TestNativeDriverLifecycle(t *testing.T) { + d, localRestore := newTestDriver(t) + ctx := t.Context() + if err := d.Probe(ctx); err != nil { + t.Fatal(err) + } + if list, err := d.List(ctx); err != nil || len(list) != 0 { + t.Fatalf("initial inventory = %v, %v", list, err) + } + req := driver.CreateRequest{DriverID: ID, Name: "Tahoe", Options: map[string]any{ + "cpus": float64(6), "memory": "12GiB", "disk_size": "128G", "restore_path": localRestore, + }} + var output bytes.Buffer + if err := d.Create(ctx, req, &output, &output); err != nil { + t.Fatal(err) + } + if !strings.Contains(output.String(), "installed from fixture.ipsw") { + t.Fatalf("unexpected installer output: %q", output.String()) + } + info, err := d.Show(ctx, "tahoe") + if err != nil || info.Name != "Tahoe" || info.CPUs != 6 || info.Memory != "12G" || info.State != "stopped" || + info.DiskSummary != "128 GiB" || info.GuestOS == nil || info.GuestOS.Arch != "arm64" || info.PID != nil || + !driver.HasCapability(info.Capabilities, driver.CapWindow) || !driver.IsHosted(info.Capabilities) { + t.Fatalf("installed VM: %+v, %v", info, err) + } + list, err := d.List(ctx) + if err != nil || len(list) != 1 || list[0].Name != "Tahoe" { + t.Fatalf("inventory = %v, %v", list, err) + } + if err := d.Create(ctx, driver.CreateRequest{Name: "tahoe", Options: req.Options}, nil, nil); err == nil { + t.Fatal("case-insensitive duplicate was accepted") + } + vm, err := d.find("Tahoe") + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(vm.path(machineDirectory, "requirements.json"), []byte(`{"version":1,"minimum_cpu_count":4,"minimum_memory_mib":8192}`), 0o600); err != nil { + t.Fatal(err) + } + before, err := os.ReadFile(vm.path(configFile)) + if err != nil { + t.Fatal(err) + } + for _, options := range []map[string]any{{"cpus": 2}, {"cpus": 11}, {"memory": "6G"}, {"memory": "32G"}} { + if err := d.Set(ctx, driver.SetRequest{Name: "Tahoe", Changes: options}, nil, nil); err == nil { + t.Fatalf("accepted invalid configuration: %v", options) + } + } + if after, err := os.ReadFile(vm.path(configFile)); err != nil || !bytes.Equal(before, after) { + t.Fatalf("rejected settings changed disk configuration: %v", err) + } + if err := d.Set(ctx, driver.SetRequest{Name: "Tahoe", Changes: map[string]any{"memory": "10240M"}}, nil, nil); err != nil { + t.Fatal(err) + } + start := driver.StartRequest{Ref: driver.NewVMRef(ID, "Tahoe")} + defer func() { _ = d.Stop(context.Background(), "Tahoe", true, nil, nil) }() + startCtx, cancel := context.WithCancel(ctx) + defer cancel() + if _, err := d.Start(startCtx, start); err != nil { + t.Fatal(err) + } + cancel() // A successful VM launch must outlive its caller's context. + other := New(d.opts) + if info, err := other.Show(ctx, "Tahoe"); err != nil || info.State != "running" || info.Memory != "10G" || info.PID != nil { + t.Fatalf("detached VM: %+v, %v", info, err) + } + if err := other.ShowWindow(ctx, "Tahoe"); err != nil { + t.Fatal(err) + } + if _, err := other.Start(ctx, start); err == nil { + t.Fatal("started the same VM twice") + } + if err := other.Delete(ctx, "Tahoe", false, nil, nil); err == nil { + t.Fatal("deleted a live VM") + } + if err := other.Set(ctx, driver.SetRequest{Name: "Tahoe", Changes: map[string]any{"cpus": 2}}, nil, nil); err == nil { + t.Fatal("changed the settings of a live VM") + } + if err := other.Stop(ctx, "Tahoe", false, nil, nil); err != nil { + t.Fatal(err) + } + if info, err := other.Show(ctx, "Tahoe"); err != nil || info.State != "stopped" { + t.Fatalf("stopped VM: %+v, %v", info, err) + } + logs, err := other.ReadLogs(ctx, "Tahoe", false) + if err != nil || !strings.Contains(logs, "installed") || !strings.Contains(logs, "READY") || !strings.Contains(logs, "viewer shown") { + t.Fatalf("runner logs = %q, %v", logs, err) + } + if err := other.Delete(ctx, "Tahoe", true, nil, nil); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(info.DiskPath); err != nil { + t.Fatalf("keep-files removed disk: %v", err) + } + if list, err := other.List(ctx); err != nil || len(list) != 0 { + t.Fatalf("unregistered VM in list: %v, %v", list, err) + } +} + +func TestInstallCancellationKeepsInstanceRecoverable(t *testing.T) { + d, restore := newTestDriver(t) + t.Setenv("APPLE_VZ_TEST_INSTALL_WAIT", "1") + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + done := make(chan error, 1) + go func() { + done <- d.Create(ctx, driver.CreateRequest{Name: "cancelled", Options: map[string]any{"restore_path": restore}}, nil, nil) + }() + until(t, func() bool { + info, err := d.Show(t.Context(), "cancelled") + return err == nil && info.Phase == driver.PhaseInstaller + }) + if err := d.Delete(t.Context(), "cancelled", false, nil, nil); err == nil { + t.Fatal("deleted a VM while native install was active") + } + cancel() + select { + case err := <-done: + if !errors.Is(err, context.Canceled) { + t.Fatalf("install cancellation: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("cancelled installer did not exit") + } + if info, err := d.Show(t.Context(), "cancelled"); err != nil || info.State != "broken" { + t.Fatalf("interrupted VM not recoverable: %+v, %v", info, err) + } + if _, err := d.Start(t.Context(), driver.StartRequest{Ref: driver.NewVMRef(ID, "cancelled")}); err == nil { + t.Fatal("ran an uninstalled VM") + } + t.Setenv("APPLE_VZ_TEST_INSTALL_WAIT", "0") + if err := d.Create(t.Context(), driver.CreateRequest{Name: "Cancelled", Options: map[string]any{"restore_path": restore}}, nil, nil); err != nil { + t.Fatalf("could not retry cleanly cancelled installation: %v", err) + } + if info, err := d.Show(t.Context(), "cancelled"); err != nil || info.State != "stopped" || info.Name != "cancelled" { + t.Fatalf("retry did not preserve registration: %+v, %v", info, err) + } +} + +func TestPublishedInstallWinsRacingCancellation(t *testing.T) { + d, restore := newTestDriver(t) + t.Setenv("APPLE_VZ_TEST_INSTALL_WAIT", "1") + t.Setenv("APPLE_VZ_TEST_COMMIT_ON_CANCEL", "1") + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + done := make(chan error, 1) + go func() { + done <- d.Create(ctx, driver.CreateRequest{Name: "commit", Options: map[string]any{"restore_path": restore}}, nil, nil) + }() + until(t, func() bool { + info, err := d.Show(t.Context(), "commit") + return err == nil && info.Phase == driver.PhaseInstaller + }) + cancel() + select { + case err := <-done: + if err != nil { + t.Fatalf("published VM was reported as canceled: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("test installer did not exit") + } + if info, err := d.Show(t.Context(), "commit"); err != nil || info.State != "stopped" { + t.Fatalf("missing published VM: %+v %v", info, err) + } +} + +func TestCancelledStartStopsOnlyItsRunner(t *testing.T) { + d, restore := newTestDriver(t) + if err := d.Create(t.Context(), driver.CreateRequest{Name: "slow", Options: map[string]any{"restore_path": restore}}, nil, nil); err != nil { + t.Fatal(err) + } + t.Setenv("APPLE_VZ_TEST_RUN_WAIT", "1") + defer func() { _ = d.Stop(context.Background(), "slow", true, nil, nil) }() + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + done := make(chan error, 1) + go func() { + _, err := d.Start(ctx, driver.StartRequest{Ref: driver.NewVMRef(ID, "slow")}) + done <- err + }() + until(t, func() bool { + vm, err := d.find("slow") + if err != nil { + return false + } + status, err := vm.status() + return err == nil && status.PID > 0 && status.State == "starting" + }) + cancel() + select { + case err := <-done: + if !errors.Is(err, context.Canceled) { + t.Fatalf("start cancellation: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("cancelled startup did not exit") + } + if vm, err := d.Show(t.Context(), "slow"); err != nil || vm.State != "stopped" { + t.Fatalf("cancelled start left running VM: %+v, %v", vm, err) + } + if text, err := d.ReadLogs(t.Context(), "slow", false); err != nil || !strings.Contains(text, "stopped expected owner") { + t.Fatalf("runner did not verify owner: %q, %v", text, err) + } +} + +func TestWaitForStartRecoversFromTransientStatusErrors(t *testing.T) { + vm := newStartStatusFixture(t) + const pid = 123 + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), time.Second) + defer cancel() + done := make(chan error, 1) + go func() { done <- waitForStart(ctx, vm, pid, make(chan error)) }() + + for _, data := range []string{ + `{"state":`, + `{"state":"ready","pid":123}`, + `{"state":"running","pid":456}`, + `{"state":"starting","pid":123}`, + } { + writeStartStatus(t, vm, data) + time.Sleep(100 * time.Millisecond) + synctest.Wait() + select { + case err := <-done: + t.Fatalf("startup ended after status %s: %v", data, err) + default: + } + } + writeStartStatus(t, vm, `{"state":"running","pid":123}`) + if err := <-done; err != nil { + t.Fatalf("startup did not recover: %v", err) + } + }) +} + +func TestWaitForStartReportsLastStatusError(t *testing.T) { + for _, exitEarly := range []bool{false, true} { + name := "deadline" + if exitEarly { + name = "runner exit" + } + t.Run(name, func(t *testing.T) { + vm := newStartStatusFixture(t) + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), time.Second) + defer cancel() + exited, done := make(chan error, 1), make(chan error, 1) + go func() { done <- waitForStart(ctx, vm, 123, exited) }() + + writeStartStatus(t, vm, `{"state":`) + time.Sleep(100 * time.Millisecond) + synctest.Wait() + writeStartStatus(t, vm, `{"state":"ready","pid":123}`) + time.Sleep(100 * time.Millisecond) + synctest.Wait() + writeStartStatus(t, vm, `{"state":"running","pid":456}`) + time.Sleep(100 * time.Millisecond) + synctest.Wait() + + want := context.DeadlineExceeded + if exitEarly { + want = errors.New("test runner exited") + exited <- want + } + err := <-done + if !errors.Is(err, want) || !strings.Contains(err.Error(), "invalid runner status") || strings.Contains(err.Error(), "read runner status") { + t.Fatalf("want %v and only the most recent status error, got %v", want, err) + } + }) + }) + } +} + +func newStartStatusFixture(t *testing.T) instance { + t.Helper() + vm := instance{dir: t.TempDir()} + lock, err := acquireLock(vm.path(runnerLock), true) + if err != nil || lock == nil { + t.Fatalf("acquire test runner lock: %v", err) + } + t.Cleanup(func() { + if err := lock.Close(); err != nil { + t.Error(err) + } + }) + return vm +} + +func writeStartStatus(t *testing.T, vm instance, status string) { + t.Helper() + if err := atomicfile.Write(vm.path(statusFile), []byte(status), 0o600); err != nil { + t.Fatal(err) + } +} + +func newTestDriver(t *testing.T) (*Driver, string) { + t.Helper() + dir := t.TempDir() + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + t.Setenv("APPLE_VZ_TEST_BIN", exe) + path := filepath.Join(dir, runnerName) + wrapper := "#!/bin/sh\nexec \"$APPLE_VZ_TEST_BIN\" -test.run '^TestRunnerProcess$' -- \"$@\"\n" + if err := os.WriteFile(path, []byte(wrapper), 0o700); err != nil { + t.Fatal(err) + } + restore := filepath.Join(dir, "fixture.ipsw") + if err := os.WriteFile(restore, []byte("not an Apple image"), 0o600); err != nil { + t.Fatal(err) + } + return New(Options{DataRoot: func() string { return filepath.Join(dir, "data") }, RunnerPath: path}), restore +} + +func until(t *testing.T, ready func() bool) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for !ready() { + if time.Now().After(deadline) { + t.Fatal("timed out waiting for fake runner") + } + time.Sleep(10 * time.Millisecond) + } +} + +// TestRunnerProcess is invoked as a standalone process by the fake helper. No +// Virtualization.framework, guest assets, signing or graphical setup is used. +func TestRunnerProcess(t *testing.T) { + idx := slices.Index(os.Args, "--") + if idx < 0 { + return + } + if err := runnerFixture(os.Args[idx+1:]); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + os.Exit(0) +} + +func runnerFixture(args []string) error { + if slices.Equal(args, []string{"probe"}) { + _, err := io.WriteString(os.Stdout, `{"runtime":"nivfold","protocol_version":1,"supported":true,"resources":{"minimum_cpu_count":2,"maximum_cpu_count":10,"minimum_memory_mib":4096,"maximum_memory_mib":24576}}`) + return err + } + if len(args) < 3 || args[1] != "--vm-dir" || !filepath.IsAbs(args[2]) { + return fmt.Errorf("invalid runner args %q", args) + } + vm := instance{dir: args[2], name: filepath.Base(args[2])} + switch args[0] { + case "install", "run": + return runnerOwner(vm, args[0], args[3:]) + case "show": + status, err := vm.status() + if err != nil || status.State != "running" { + return errors.Join(err, errors.New("VM not running")) + } + fmt.Println("viewer shown") + return nil + case "stop": + return runnerStop(vm, args[3:]) + default: + return fmt.Errorf("unknown command %q", args[0]) + } +} + +func runnerOwner(vm instance, command string, args []string) error { + lock, err := acquireLock(vm.path(runnerLock), true) + if err != nil || lock == nil { + return errors.Join(err, errors.New("runtime lock unavailable")) + } + defer lock.Close() + defer os.Remove(vm.path(statusFile)) + if _, err := vm.config(); err != nil { + return err + } + var cfg map[string]json.RawMessage + data, err := os.ReadFile(vm.path(configFile)) + if err != nil { + return err + } + if err := json.Unmarshal(data, &cfg); err != nil || cfg["cpu_count"] == nil || cfg["memory_mib"] == nil || cfg["disk_gib"] == nil { + return errors.Join(err, errors.New("config is missing runner fields")) + } + status := runnerStatus{PID: os.Getpid(), State: "starting"} + var cancelSignals chan os.Signal + if command == "install" { + cancelSignals = make(chan os.Signal, 1) + signal.Notify(cancelSignals, syscall.SIGTERM) + defer signal.Stop(cancelSignals) + status.State = "installing" + } else if os.Getenv("APPLE_VZ_TEST_RUN_WAIT") != "1" { + status.State = "running" + fmt.Println("READY") + } + if err := atomicfile.WriteJSON(vm.path(statusFile), status, 0o600); err != nil { + return err + } + if command == "install" { + return runnerInstall(vm, args, cancelSignals) + } + return waitMarker(vm.path("stop.request"), true) +} + +func runnerInstall(vm instance, args []string, cancelSignals <-chan os.Signal) error { + if len(args) != 2 || args[0] != "--ipsw" || !filepath.IsAbs(args[1]) || filepath.Ext(args[1]) != ".ipsw" { + return fmt.Errorf("invalid install args %q", args) + } + if os.Getenv("APPLE_VZ_TEST_INSTALL_WAIT") == "1" { + select { + case <-cancelSignals: + if os.Getenv("APPLE_VZ_TEST_COMMIT_ON_CANCEL") != "1" { + // Match Nivfold's cooperative SIGTERM exit status. + if err := os.Remove(vm.path(statusFile)); err != nil { + return err + } + os.Exit(143) + } + case <-time.After(5 * time.Second): + return errors.New("test installer timed out waiting for cancellation") + } + } + if err := os.Mkdir(vm.path(machineDirectory), 0o700); err != nil { + return err + } + for _, name := range []string{"hardware-model", "machine-id", "auxiliary-storage", "disk.img"} { + if err := os.WriteFile(vm.path(machineDirectory, name), []byte("mock artifact"), 0o600); err != nil { + return err + } + } + fmt.Printf("installed from %s\n", filepath.Base(args[1])) + return nil +} + +func runnerStop(vm instance, args []string) error { + status, err := vm.status() + if err != nil || status.State == "stopped" { + return err + } + if len(args) == 3 && args[0] == "--force" && args[1] == "--expect-pid" && args[2] == fmt.Sprint(status.PID) { + fmt.Println("stopped expected owner") + } else if !(len(args) == 0 || slices.Equal(args, []string{"--force"})) { + return fmt.Errorf("invalid stop args %q for owner %d", args, status.PID) + } + if err := os.WriteFile(vm.path("stop.request"), []byte("stop"), 0o600); err != nil { + return err + } + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + current, err := vm.status() + if err != nil || current.State == "stopped" { + return err + } + time.Sleep(10 * time.Millisecond) + } + return errors.New("VM did not release its runtime lock") +} + +func waitMarker(path string, present bool) error { + deadline := time.Now().Add(10 * time.Second) + for time.Now().Before(deadline) { + _, err := os.Stat(path) + if present && err == nil { + return os.Remove(path) + } + if !present && errors.Is(err, os.ErrNotExist) { + return nil + } + time.Sleep(10 * time.Millisecond) + } + return fmt.Errorf("timed out waiting for %s", path) +} diff --git a/internal/macos/applevz/storage.go b/internal/macos/applevz/storage.go new file mode 100644 index 0000000..37a5c34 --- /dev/null +++ b/internal/macos/applevz/storage.go @@ -0,0 +1,318 @@ +package applevz + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "strings" + + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/filelock" +) + +const ( + configFile = "config.json" + runnerLock = ".applevz.lock" + statusFile = ".applevz-status.json" + machineDirectory = "machine" + logFile = "runner.log" +) + +type instance struct{ dir, name string } + +type runnerStatus struct { + State string `json:"state"` + PID int `json:"pid"` +} + +func (vm instance) path(parts ...string) string { + return filepath.Join(append([]string{vm.dir}, parts...)...) +} + +func (d *Driver) root(create bool) (string, error) { + if d.opts.DataRoot == nil { + return "", errors.New("Apple virtualization has no configured data folder") + } + data := d.opts.DataRoot() + if !filepath.IsAbs(data) { + return "", errors.New("Apple virtualization needs an absolute data folder") + } + if create { + if err := os.MkdirAll(data, 0o700); err != nil { + return "", err + } + } + data, err := filepath.EvalSymlinks(data) + if err != nil { + return "", err + } + root := filepath.Join(data, VMRoot) + if create { + if err := os.Mkdir(root, 0o700); err != nil && !errors.Is(err, os.ErrExist) { + return "", err + } + } + return root, requireDirectory(root) +} + +func requireDirectory(path string) error { + info, err := os.Lstat(path) + if err != nil { + return err + } + if !info.IsDir() { + return fmt.Errorf("not a plain directory: %s", path) + } + return nil +} + +// Operations addressing an existing instance match names independently of the +// filesystem's case sensitivity. New names may not collide under that rule. +func namedInstance(root, name string) (instance, error) { + if !validName(name) { + return instance{}, fmt.Errorf("invalid Apple VM name %q", name) + } + entries, err := os.ReadDir(root) + if err != nil { + return instance{}, err + } + var actual string + for _, entry := range entries { + if strings.EqualFold(entry.Name(), name) { + if actual != "" { + return instance{}, fmt.Errorf("multiple directory entries match VM %q", name) + } + actual = entry.Name() + } + } + if actual == "" { + return instance{}, fmt.Errorf("Apple VM %q: %w", name, os.ErrNotExist) + } + return instance{dir: filepath.Join(root, actual), name: actual}, nil +} + +func (d *Driver) find(name string) (instance, error) { + root, err := d.root(false) + if err != nil { + return instance{}, err + } + return ownedInstance(root, name) +} + +func ownedInstance(root, name string) (instance, error) { + vm, err := namedInstance(root, name) + if err != nil { + return instance{}, err + } + if err := requireDirectory(vm.dir); err != nil { + return instance{}, err + } + if !vm.owned() { + return instance{}, fmt.Errorf("Apple VM %q is not registered: %w", name, os.ErrNotExist) + } + return vm, nil +} + +func (vm instance) owned() bool { + b, err := readSmallFile(vm.path(driver.OwnerMarkerFile)) + return err == nil && strings.TrimSpace(string(b)) == ID +} + +func (vm instance) config() (vmConfig, error) { + var cfg vmConfig + b, err := readSmallFile(vm.path(configFile)) + if err != nil { + return cfg, err + } + if err := json.Unmarshal(b, &cfg); err != nil { + return cfg, fmt.Errorf("read VM configuration: %w", err) + } + if cfg.Name != vm.name || cfg.CPUs < minCPUs || cfg.CPUs > maxCPUs || cfg.MemoryMiB < minMemoryMiB || + cfg.MemoryMiB > maxMemoryMiB || cfg.DiskGiB < minDiskGiB || cfg.DiskGiB > maxDiskGiB { + return cfg, errors.New("invalid VM configuration") + } + return cfg, nil +} + +func (vm instance) installed() error { + if err := requireDirectory(vm.path(machineDirectory)); err != nil { + return fmt.Errorf("Apple VM is not installed: %w", err) + } + for _, artifact := range []string{"hardware-model", "machine-id", "auxiliary-storage", "disk.img"} { + info, err := os.Lstat(vm.path(machineDirectory, artifact)) + if err != nil { + return fmt.Errorf("missing VM installation artifact %s: %w", artifact, err) + } + if !info.Mode().IsRegular() || info.Size() == 0 || sharedFile(info) { + return fmt.Errorf("invalid VM installation artifact %s", artifact) + } + } + return nil +} + +func (vm instance) status() (runnerStatus, error) { + path := vm.path(runnerLock) + file, err := openRegular(path, os.O_RDONLY) + if errors.Is(err, os.ErrNotExist) { + return runnerStatus{State: "stopped"}, nil + } + if err != nil { + return runnerStatus{}, err + } + defer file.Close() + idle, err := tryStatusLock(file) + if err != nil { + return runnerStatus{}, err + } + if err := validateOpened(path, file); err != nil { + return runnerStatus{}, err + } + if idle { + return runnerStatus{State: "stopped"}, nil + } + return vm.activeStatus() +} + +func (vm instance) activeStatus() (runnerStatus, error) { + b, err := readSmallFile(vm.path(statusFile)) + if errors.Is(err, os.ErrNotExist) { + return runnerStatus{State: "starting"}, nil + } + if err != nil { + return runnerStatus{}, err + } + var status runnerStatus + if err := json.Unmarshal(b, &status); err != nil { + return runnerStatus{}, fmt.Errorf("read runner status: %w", err) + } + switch status.State { + case "installing", "starting", "running", "stopping": + if status.PID > 0 { + return status, nil + } + } + return runnerStatus{}, errors.New("invalid runner status") +} + +func lockOperations(root, name string) (*os.File, error) { + if !validName(name) { + return nil, fmt.Errorf("invalid Apple VM name %q", name) + } + dir := filepath.Join(root, ".operations") + if err := os.Mkdir(dir, 0o700); err != nil && !errors.Is(err, os.ErrExist) { + return nil, err + } + if err := requireDirectory(dir); err != nil { + return nil, err + } + lock, err := acquireLock(filepath.Join(dir, strings.ToLower(name)), true) + if err == nil && lock == nil { + err = fmt.Errorf("another operation is in progress for VM %q", name) + } + return lock, err +} + +func acquireLock(path string, create bool) (*os.File, error) { + flags := os.O_RDWR + if create { + flags |= os.O_CREATE + } + file, err := openRegular(path, flags) + if err != nil { + return nil, err + } + locked, err := filelock.TryLock(file) + if err != nil { + return nil, errors.Join(err, file.Close()) + } + if err := validateOpened(path, file); err != nil { + return nil, errors.Join(err, file.Close()) + } + if !locked { + return nil, file.Close() + } + return file, nil +} + +func openRegular(path string, flags int) (*os.File, error) { + if info, err := os.Lstat(path); err == nil && (!info.Mode().IsRegular() || sharedFile(info)) { + return nil, fmt.Errorf("not a plain file: %s", path) + } else if err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, err + } + f, err := openFile(path, flags) + if err != nil { + return nil, err + } + if err := validateOpened(path, f); err != nil { + return nil, errors.Join(err, f.Close()) + } + return f, nil +} + +func openFile(path string, flags int) (*os.File, error) { + if runtime.GOOS != "windows" || filepath.Base(path) != runnerLock { + return os.OpenFile(path, flags|safeOpenFlags, 0o600) + } + // Windows requires delete sharing to unlink the held runtime lock during + // Delete. Root.OpenFile enables it without releasing the owner's lock. + root, err := os.OpenRoot(filepath.Dir(path)) + if err != nil { + return nil, err + } + defer root.Close() + return root.OpenFile(runnerLock, flags, 0o600) +} + +func validateOpened(path string, f *os.File) error { + fromFile, err := f.Stat() + if err != nil { + return err + } + fromPath, err := os.Lstat(path) + if err != nil { + return err + } + if !fromPath.Mode().IsRegular() || sharedFile(fromPath) || !os.SameFile(fromFile, fromPath) { + return fmt.Errorf("not a plain file: %s", path) + } + return nil +} + +func readSmallFile(path string) ([]byte, error) { + f, err := openRegular(path, os.O_RDONLY) + if err != nil { + return nil, err + } + defer f.Close() + const limit = 64 << 10 + b, err := io.ReadAll(io.LimitReader(f, limit+1)) + if len(b) > limit { + return nil, fmt.Errorf("metadata file exceeds %d bytes: %s", limit, filepath.Base(path)) + } + return b, err +} + +func (vm instance) logTail(limit int64) (string, error) { + f, err := openRegular(vm.path(logFile), os.O_RDONLY) + if errors.Is(err, os.ErrNotExist) { + return "", nil + } + if err != nil { + return "", err + } + defer f.Close() + info, err := f.Stat() + if err != nil { + return "", err + } + if _, err := f.Seek(max(info.Size()-limit, 0), io.SeekStart); err != nil { + return "", err + } + data, err := io.ReadAll(io.LimitReader(f, limit)) + return string(data), err +} diff --git a/internal/macos/applevz/storage_test.go b/internal/macos/applevz/storage_test.go new file mode 100644 index 0000000..66d6f45 --- /dev/null +++ b/internal/macos/applevz/storage_test.go @@ -0,0 +1,110 @@ +package applevz + +import ( + "errors" + "os" + "path/filepath" + "slices" + "testing" + + "github.com/Nwflower/reims-go/internal/atomicfile" + "github.com/Nwflower/reims-go/internal/driver" +) + +func TestCreateValidationRejectsExternalAndUnsafeInputs(t *testing.T) { + d := New(Options{}) + for _, tc := range []struct { + name, field string + req driver.CreateRequest + }{ + {"traversal", "name", driver.CreateRequest{Name: "../outside"}}, + {"custom directory", "dir", driver.CreateRequest{Name: "tahoe", Dir: t.TempDir()}}, + {"remote source", "restore_path", driver.CreateRequest{Name: "tahoe", Options: map[string]any{"restore_path": "https://example.invalid/image.ipsw"}}}, + {"file URI", "restore_path", driver.CreateRequest{Name: "tahoe", Options: map[string]any{"restore_path": "file:///tmp/image.ipsw"}}}, + {"small memory", "memory", driver.CreateRequest{Name: "tahoe", Options: map[string]any{"memory": "2G"}}}, + {"fractional CPU", "cpus", driver.CreateRequest{Name: "tahoe", Options: map[string]any{"cpus": 2.5}}}, + {"unknown option", "graphics", driver.CreateRequest{Name: "tahoe", Options: map[string]any{"graphics": "wgpu"}}}, + } { + t.Run(tc.name, func(t *testing.T) { + issues := d.ValidateCreate(t.Context(), tc.req) + if !slices.ContainsFunc(issues, func(issue driver.ValidationIssue) bool { return issue.Field == tc.field }) { + t.Fatalf("got %v, expected field %q", issues, tc.field) + } + }) + } +} + +func TestInventoryIgnoresUnknownAndDamagedInstances(t *testing.T) { + data := t.TempDir() + d := New(Options{DataRoot: func() string { return data }}) + root, err := d.root(true) + if err != nil { + t.Fatal(err) + } + vm, err := createInstance(root, defaultConfig("unfinished")) + if err != nil { + t.Fatal(err) + } + if err := atomicfile.WriteJSON(vm.path(statusFile), runnerStatus{State: "running", PID: os.Getpid()}, 0o600); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(filepath.Join(root, "unknown"), 0o700); err != nil { + t.Fatal(err) + } + linkErr := os.Symlink(vm.dir, filepath.Join(root, "link")) + if err := os.WriteFile(vm.path(configFile), []byte("not JSON"), 0o600); err != nil { + t.Fatal(err) + } + list, err := d.List(t.Context()) + if err != nil || len(list) != 1 || list[0].State != "broken" || list[0].Name != vm.name || list[0].PID != nil { + t.Fatalf("inventory = %v, %v", list, err) + } + t.Run("linked directory", func(t *testing.T) { + if linkErr != nil { + t.Skipf("cannot create a symlink: %v", linkErr) + } + if err := d.Delete(t.Context(), "link", false, nil, nil); err == nil { + t.Fatal("deleted through a linked directory") + } + }) + t.Run("held runner lock", func(t *testing.T) { + lock, err := acquireLock(vm.path(runnerLock), true) + if err != nil || lock == nil { + t.Fatalf("acquire test runner lock: %v", err) + } + // This cleanup runs before the parent deletes the instance or its TempDir. + t.Cleanup(func() { + if err := lock.Close(); err != nil { + t.Error(err) + } + }) + if err := d.Delete(t.Context(), vm.name, false, nil, nil); err == nil { + t.Fatal("deleted an instance whose runner lock was held") + } + }) + if err := d.Delete(t.Context(), vm.name, false, nil, nil); err != nil { + t.Fatalf("delete broken VM: %v", err) + } + if _, err := os.Stat(vm.dir); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("broken VM not cleaned up: %v", err) + } +} + +func TestInventoryIgnoresStatusWithoutRunnerLock(t *testing.T) { + data := t.TempDir() + d := New(Options{DataRoot: func() string { return data }}) + root, err := d.root(true) + if err != nil { + t.Fatal(err) + } + vm, err := createInstance(root, defaultConfig("interrupted")) + if err != nil { + t.Fatal(err) + } + if err := atomicfile.WriteJSON(vm.path(statusFile), runnerStatus{State: "running", PID: os.Getpid()}, 0o600); err != nil { + t.Fatal(err) + } + if info, err := d.Show(t.Context(), vm.name); err != nil || info.State != "broken" { + t.Fatalf("stale process record mattered: %+v, %v", info, err) + } +} diff --git a/internal/macos/guest/apple_vz.go b/internal/macos/guest/apple_vz.go new file mode 100644 index 0000000..a149588 --- /dev/null +++ b/internal/macos/guest/apple_vz.go @@ -0,0 +1,54 @@ +package guest + +import ( + "context" + "path/filepath" + "runtime" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/macos/applevz" + "github.com/Nwflower/reims-go/internal/plugin" +) + +// UsesAppleVirtualization identifies hosts for the native Apple Silicon driver. +func UsesAppleVirtualization() bool { return runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" } + +// AppleDriverID identifies the native driver in CLI creation requests. +func AppleDriverID() string { return applevz.ID } + +// AppleVMRoot is the directory used by the native driver's VM inventory. +func AppleVMRoot(dataRoot string) string { return filepath.Join(dataRoot, applevz.VMRoot) } + +// ProbeAppleVirtualization checks the installed native helper without opening a VM. +func ProbeAppleVirtualization(ctx context.Context) error { + return applevz.New(applevz.Options{}).Probe(ctx) +} + +func appleDefinition(ver string, getConfig func() config.Config, desired bool) plugin.PluginDef { + drv := applevz.New(applevz.Options{DataRoot: func() string { + if getConfig == nil { + return "" + } + return getConfig().DataRoot + }}) + return plugin.PluginDef{ + Manifest: plugin.Manifest{ + Schema: 1, ID: applevz.ID, Version: ver, Name: drv.DisplayName(), + Description: plugin.LocalizedText{ + ZhCN: "在 Apple 芯片 Mac 上运行 ARM64 macOS 虚拟机", + EnUS: "Runs ARM64 macOS VMs on Apple silicon", + }, + Publisher: "Reims-Go", License: "Apache-2.0", DefaultEnabled: true, + Permissions: []string{"driver:vm", "vm:control"}, + Contributes: plugin.Contributes{GuestDrivers: []plugin.GuestDriverContribution{{ + ID: drv.ID(), Name: drv.DisplayName(), RuntimeKind: drv.RuntimeKind(), + Capabilities: drv.Capabilities(), VMRoots: []string{applevz.VMRoot}, + }}}, + }, + Source: plugin.SourceBuiltin, Trust: plugin.TrustOfficial, Desired: desired, + Activate: func(_ context.Context, scope *plugin.Scope) error { + scope.Registry().RegisterGuestDriver(scope, drv.ID(), drv) + return nil + }, + } +} diff --git a/internal/macos/guest/register.go b/internal/macos/guest/register.go index adfdee7..fe7c7a0 100644 --- a/internal/macos/guest/register.go +++ b/internal/macos/guest/register.go @@ -4,18 +4,22 @@ import ( "strings" "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/macos/applevz" "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/internal/plugin/builtin" "github.com/Nwflower/reims-go/internal/version" ) -// VMInventory keeps registered VMs discoverable while macOS support is disabled. -func VMInventory() driver.VMInventory { - return driver.VMInventory{DriverID: IDDriver, List: reims.ListRegisteredVMs} +// VMInventories keep registered VMs discoverable when their driver is unavailable. +func VMInventories() []driver.VMInventory { + return []driver.VMInventory{ + {DriverID: IDDriver, List: reims.ListRegisteredVMs}, + {DriverID: applevz.ID, List: applevz.Inventory}, + } } -// Register adds the optional built-in macOS plugins (guest driver + image source) to reg. +// Register adds the built-in Reims vGPU guest driver and image source. func Register(reg *plugin.Registry, cb builtin.HostCallbacks, desiredFn func(string, bool) bool) error { if desiredFn == nil { desiredFn = func(_ string, def bool) bool { return def } @@ -26,3 +30,16 @@ func Register(reg *plugin.Registry, cb builtin.HostCallbacks, desiredFn func(str } return reg.Register(ImagesDefinition(ver, desiredFn(IDImages, true))) } + +// RegisterForHost selects the local backend without losing the other backend's +// registered VMs: the router's read-only inventories still expose those entries. +func RegisterForHost(reg *plugin.Registry, cb builtin.HostCallbacks, desiredFn func(string, bool) bool) error { + if !UsesAppleVirtualization() { + return Register(reg, cb, desiredFn) + } + ver := strings.TrimPrefix(strings.TrimSpace(version.Version), "v") + if err := reg.Register(appleDefinition(ver, cb.GetConfig, desiredFn == nil || desiredFn(AppleDriverID(), true))); err != nil { + return err + } + return reg.Register(ImagesDefinition(ver, desiredFn == nil || desiredFn(IDImages, true))) +} diff --git a/internal/macos/installer/restore_image.go b/internal/macos/installer/restore_image.go new file mode 100644 index 0000000..3f463e2 --- /dev/null +++ b/internal/macos/installer/restore_image.go @@ -0,0 +1,314 @@ +package installer + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path" + "path/filepath" + "regexp" + "strings" + "time" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/fetch" + "github.com/Nwflower/reims-go/internal/filelock" + "github.com/Nwflower/reims-go/internal/macos/applevz" +) + +// RestoreKind is the installer task/cache kind for Apple Silicon guests. +const RestoreKind = "ipsw" +const maxRestoreBytes int64 = 64 << 30 + +var restoreNamePattern = regexp.MustCompile(`^UniversalMac_([0-9]{1,3}\.[0-9]{1,3}(?:\.[0-9]{1,3})?)_([0-9]{1,4}[A-Z][0-9]{1,8}[a-z]?)_Restore\.ipsw$`) + +// RestoreDir keeps native images separate from reims-ctl installers. +func RestoreDir(cfg *config.Config) string { return filepath.Join(cfg.ImagesDir(), "apple-restore") } + +func LatestRestore(ctx context.Context) (Release, error) { + image, err := applevz.New(applevz.Options{}).LatestRestoreImage(ctx) + if err != nil { + return Release{}, err + } + r := Release{Title: "macOS " + image.Version, Version: image.Version, Build: image.Build, URL: image.URL} + if _, err := restoreFilename(r); err != nil { + return Release{}, err + } + // Metadata only: the CDN may omit Content-Length or decline HEAD. + if meta, err := restoreHeader(ctx, restoreHTTPClient(), r.URL); err == nil { + r.Size = meta.size + } + return r, nil +} + +func restoreImageName(version, build string) string { + return "UniversalMac_" + version + "_" + build + "_Restore.ipsw" +} + +func restoreFilename(r Release) (string, error) { + u, err := url.Parse(r.URL) + name := restoreImageName(r.Version, r.Build) + if err != nil || !appleRestoreURL(u) || !restoreNamePattern.MatchString(name) || path.Base(u.Path) != name { + return "", errors.New("Apple restore catalog returned an invalid image") + } + return name, nil +} + +func appleRestoreURL(u *url.URL) bool { + if u == nil || u.Scheme != "https" || u.User != nil || u.Fragment != "" || + (u.Port() != "" && u.Port() != "443") { + return false + } + return strings.EqualFold(u.Hostname(), "updates.cdn-apple.com") || strings.EqualFold(u.Hostname(), "updates.apple.com") +} + +type RestoreCache struct{ Dir string } + +func (c RestoreCache) List() ([]Cached, error) { + cacheDir, err := c.cacheDir(false) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + entries, err := os.ReadDir(cacheDir) + if err != nil { + return nil, err + } + var out []Cached + for _, e := range entries { + if !e.Type().IsRegular() { + continue + } + name := e.Name() + base, partial := strings.CutSuffix(name, ".part.ipsw") + if partial { + base += ".ipsw" + } + parts := restoreNamePattern.FindStringSubmatch(base) + if parts == nil { + continue + } + info, err := e.Info() + if err != nil || info.Size() <= 0 { + continue + } + item := Cached{Name: name, Kind: RestoreKind, Partial: partial, Title: "macOS " + parts[1], Version: parts[1], Build: parts[2], Bytes: info.Size()} + if !partial { + item.Path = filepath.Join(cacheDir, name) + } + out = append(out, item) + } + return out, nil +} + +func (c RestoreCache) Delete(ctx context.Context, name string) error { + base, partial := strings.CutSuffix(name, ".part.ipsw") + if partial { + base += ".ipsw" + } + if !restoreNamePattern.MatchString(base) { + return errors.New("not a cached restore image name") + } + dir, err := c.cacheDir(false) + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond) + defer cancel() + release, err := lockRestoreCache(ctx, dir) + if err != nil { + return fmt.Errorf("restore image cache is busy: %w", err) + } + defer release() + file := filepath.Join(dir, name) + info, err := os.Lstat(file) + if err != nil { + return err + } + if !info.Mode().IsRegular() { + return errors.New("restore image cache entry is not a regular file") + } + if err := os.Remove(file); err != nil { + return err + } + if partial { + if err := os.Remove(file + ".etag"); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + } + return nil +} + +func (c RestoreCache) Download(ctx context.Context, r Release, onUpdate func(Update)) (*Result, error) { + name, err := restoreFilename(r) + if err != nil { + return nil, err + } + client := restoreHTTPClient() + if meta, err := restoreHeader(ctx, client, r.URL); err == nil { + r.Size, r.Digest = meta.size, meta.digest + } + if r.Size > maxRestoreBytes { + return nil, errors.New("Apple restore image exceeds the download size limit") + } + inspect := applevz.New(applevz.Options{}).InspectRestoreImage + return c.download(ctx, r, name, client, inspect, onUpdate) +} + +func (c RestoreCache) download(ctx context.Context, r Release, name string, client *http.Client, + inspect func(context.Context, string) (applevz.RestoreImage, error), onUpdate func(Update)) (*Result, error) { + dir, err := c.cacheDir(true) + if err != nil { + return nil, err + } + if onUpdate == nil { + onUpdate = func(Update) {} + } + onUpdate(Update{Kind: KindNote, Message: WaitingNote}) + release, err := lockRestoreCache(ctx, dir) + if err != nil { + return nil, err + } + defer release() + onUpdate(Update{Kind: KindStep, Message: "Downloading macOS " + r.Version + " restore image", Percent: -1}) + final := filepath.Join(dir, name) + part := filepath.Join(dir, strings.TrimSuffix(name, ".ipsw")+".part.ipsw") + err = fetch.ResumeValidated(ctx, client, r.URL, final, part, maxRestoreBytes, func(done, total int64) { + onUpdate(Update{Kind: KindProgress, Done: done, Total: total, Percent: float64(done) * 100 / float64(total)}) + }, func(ctx context.Context, file string) error { + onUpdate(Update{Kind: KindStep, Message: "Checking macOS restore image", Percent: -1}) + if err := verifyRestoreFile(ctx, file, r.Size, r.Digest); err != nil { + return err + } + image, err := inspect(ctx, file) + if err != nil { + return err + } + if !restoreNamePattern.MatchString(restoreImageName(image.Version, image.Build)) { + return errors.New("Nivfold returned invalid or incomplete restore image metadata") + } + if image.Version != r.Version || image.Build != r.Build { + return &fetch.InvalidDownloadError{Err: errors.New("downloaded restore image does not match the Apple catalog")} + } + return nil + }) + if err != nil { + return nil, err + } + return &Result{Image: final, Version: r.Version, Build: r.Build}, nil +} + +type restoreHeaders struct { + size int64 + digest string +} + +func restoreHeader(ctx context.Context, client *http.Client, rawURL string) (restoreHeaders, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodHead, rawURL, nil) + if err != nil { + return restoreHeaders{}, err + } + resp, err := client.Do(req) + if err != nil { + return restoreHeaders{}, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return restoreHeaders{}, fmt.Errorf("Apple restore metadata: HTTP %d", resp.StatusCode) + } + meta := restoreHeaders{size: max(0, resp.ContentLength)} + if digest := resp.Header.Get("x-amz-meta-digest-sha256"); digest != "" { + if decoded, err := hex.DecodeString(digest); err == nil && len(decoded) == sha256.Size { + meta.digest = strings.ToLower(digest) + } + } + return meta, nil +} + +func verifyRestoreFile(ctx context.Context, path string, size int64, digest string) error { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + info, err := file.Stat() + if err != nil { + return err + } + if size > 0 && info.Size() != size { + return &fetch.InvalidDownloadError{Err: errors.New("restore image size does not match Apple's download metadata")} + } + if digest == "" { + return nil + } + h := sha256.New() + buf := make([]byte, 1<<20) + for { + if err := ctx.Err(); err != nil { + return err + } + n, err := file.Read(buf) + h.Write(buf[:n]) + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return err + } + } + if hex.EncodeToString(h.Sum(nil)) != digest { + return &fetch.InvalidDownloadError{Err: errors.New("restore image SHA-256 does not match Apple's download metadata")} + } + return nil +} + +func restoreHTTPClient() *http.Client { + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.DisableCompression = true + transport.ResponseHeaderTimeout = 30 * time.Second + return &http.Client{Transport: transport, CheckRedirect: func(req *http.Request, via []*http.Request) error { + if len(via) >= 5 || !appleRestoreURL(req.URL) || path.Base(req.URL.Path) != path.Base(via[0].URL.Path) { + return errors.New("unexpected redirect while downloading Apple restore image") + } + return nil + }} +} + +func (c RestoreCache) cacheDir(create bool) (string, error) { + if !filepath.IsAbs(c.Dir) { + return "", errors.New("restore images need an absolute data directory") + } + if create { + if err := os.MkdirAll(c.Dir, 0o700); err != nil { + return "", err + } + } + info, err := os.Lstat(c.Dir) + if err != nil { + return "", err + } + if !info.IsDir() { + return "", errors.New("restore image cache is not a directory") + } + return c.Dir, nil +} + +func lockRestoreCache(ctx context.Context, dir string) (func(), error) { + lock := filepath.Join(dir, ".restore.lock") + if info, err := os.Lstat(lock); err == nil && !info.Mode().IsRegular() { + return nil, errors.New("restore image cache lock is not a regular file") + } else if err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, err + } + return filelock.Acquire(ctx, lock, 200*time.Millisecond) +} diff --git a/internal/macos/installer/restore_image_test.go b/internal/macos/installer/restore_image_test.go new file mode 100644 index 0000000..151b033 --- /dev/null +++ b/internal/macos/installer/restore_image_test.go @@ -0,0 +1,223 @@ +package installer + +import ( + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/Nwflower/reims-go/internal/macos/applevz" +) + +func TestRestoreCacheDownloadValidatesBeforePublishing(t *testing.T) { + const name = "UniversalMac_27.2.1_26B131_Restore.ipsw" + const body = "local test fixture, not an Apple image" + sum := fmt.Sprintf("%x", sha256.Sum256([]byte(body))) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", fmt.Sprint(len(body))) + w.Header().Set("x-amz-meta-digest-sha256", sum) + w.Header().Set("ETag", `"mock"`) + if r.Method != http.MethodHead { + fmt.Fprint(w, body) + } + })) + defer server.Close() + meta, err := restoreHeader(t.Context(), server.Client(), server.URL) + if err != nil || meta.digest != sum || meta.size != int64(len(body)) { + t.Fatalf("HEAD metadata: %+v, %v", meta, err) + } + cache := RestoreCache{Dir: filepath.Join(t.TempDir(), "restore")} + for _, valid := range []bool{false, true} { + r := Release{Build: "26B131", Version: "27.2.1", URL: server.URL, Size: meta.size, Digest: meta.digest} + if !valid { + r.Digest = fmt.Sprintf("%064d", 0) + } + var inspected bool + _, err := cache.download(t.Context(), r, name, server.Client(), func(_ context.Context, path string) (applevz.RestoreImage, error) { + inspected = true + if filepath.Ext(path) != ".ipsw" { + t.Errorf("staged image must end in .ipsw: %s", path) + } + return applevz.RestoreImage{Version: r.Version, Build: r.Build}, nil + }, nil) + if (err == nil) != valid || inspected != valid { + t.Fatalf("download valid=%t, inspected=%t: %v", valid, inspected, err) + } + list, err := cache.List() + if err != nil || len(list) != map[bool]int{true: 1, false: 0}[valid] { + t.Fatalf("cache valid=%t: %+v %v", valid, list, err) + } + if valid && (list[0].Kind != RestoreKind || list[0].Path != filepath.Join(cache.Dir, name) || list[0].Partial) { + t.Fatalf("cached image: %+v", list[0]) + } + } + if err := cache.Delete(t.Context(), "../"+name); err == nil { + t.Fatal("allowed deletion outside cache") + } + if err := cache.Delete(t.Context(), name); err != nil { + t.Fatal(err) + } + part := filepath.Join(cache.Dir, "UniversalMac_27.2.1_26B131_Restore.part.ipsw") + if err := os.WriteFile(part, []byte("partial"), 0o600); err != nil { + t.Fatal(err) + } + list, err := cache.List() + if err != nil || len(list) != 1 || !list[0].Partial || list[0].Path != "" || list[0].Version != "27.2.1" { + t.Fatalf("unsafe partial exposed: %+v %v", list, err) + } +} + +func TestRestoreCacheRetriesInspectionAgainstCompletePart(t *testing.T) { + const name = "UniversalMac_27.2.1_26B131_Restore.ipsw" + const body = "local fixture, not an Apple image" + const tag = `"stable"` + exact := fmt.Sprintf("bytes=%d-", len(body)) + for _, tc := range []struct { + name string + inspectErr error + image applevz.RestoreImage + }{ + {name: "nested timeout", inspectErr: fmt.Errorf("Nivfold inspect: %w", context.DeadlineExceeded)}, + {name: "process error", inspectErr: errors.New("Nivfold inspect: exit status 1")}, + {name: "decode error", inspectErr: fmt.Errorf("decode Nivfold restore image metadata: %w", &json.SyntaxError{})}, + {name: "incompatible response", inspectErr: errors.New("Nivfold inspect: no supported configuration on this host")}, + {name: "incomplete metadata", image: applevz.RestoreImage{Version: "27.2.1"}}, + {name: "malformed metadata", image: applevz.RestoreImage{Version: "unknown", Build: "26B131"}}, + } { + t.Run(tc.name, func(t *testing.T) { + var requests []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("ETag", tag) + requested := r.Header.Get("Range") + requests = append(requests, requested) + if requested != "" { + if r.Header.Get("If-Range") != tag { + t.Errorf("If-Range = %q, want %q", r.Header.Get("If-Range"), tag) + } + w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", len(body))) + w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) + return + } + fmt.Fprint(w, body) + })) + defer server.Close() + cache := RestoreCache{Dir: filepath.Join(t.TempDir(), "restore")} + r := Release{Build: "26B131", Version: "27.2.1", URL: server.URL, Size: int64(len(body)), Digest: fmt.Sprintf("%x", sha256.Sum256([]byte(body)))} + part := filepath.Join(cache.Dir, strings.TrimSuffix(name, ".ipsw")+".part.ipsw") + final := filepath.Join(cache.Dir, name) + result, err := cache.download(t.Context(), r, name, server.Client(), func(context.Context, string) (applevz.RestoreImage, error) { + return tc.image, tc.inspectErr + }, nil) + if result != nil || err == nil || tc.inspectErr != nil && !errors.Is(err, tc.inspectErr) { + t.Fatalf("failed inspect result = %+v, error = %v (wanted failure %v)", result, err, tc.inspectErr) + } + for file, want := range map[string]string{part: body, part + ".etag": tag} { + if got, err := os.ReadFile(file); err != nil || string(got) != want { + t.Fatalf("resumable file %s = %q, %v; want %q", file, got, err, want) + } + } + if _, err := os.Stat(final); !os.IsNotExist(err) { + t.Fatalf("published after failed inspection: %v", err) + } + inspected := false + result, err = cache.download(t.Context(), r, name, server.Client(), func(_ context.Context, path string) (applevz.RestoreImage, error) { + inspected = true + if path != part { + t.Errorf("inspection path = %q, want %q", path, part) + } + return applevz.RestoreImage{Version: r.Version, Build: r.Build}, nil + }, nil) + if err != nil || result == nil || result.Image != final || !inspected { + t.Fatalf("retry result = %+v, inspected = %t, error = %v", result, inspected, err) + } + if want := []string{"", exact}; !slices.Equal(requests, want) { + t.Fatalf("requests = %q, want %q", requests, want) + } + if got, err := os.ReadFile(final); err != nil || string(got) != body { + t.Fatalf("final = %q, %v", got, err) + } + }) + } +} + +func TestRestoreCacheDiscardsConfirmedBadCompletePart(t *testing.T) { + const name = "UniversalMac_27.2.1_26B131_Restore.ipsw" + const body = "local fixture, not an Apple image" + const tag = `"stable"` + goodDigest := fmt.Sprintf("%x", sha256.Sum256([]byte(body))) + for _, tc := range []struct { + name, digest string + size int64 + image applevz.RestoreImage + wantInspected bool + }{ + {"size", goodDigest, int64(len(body) + 1), applevz.RestoreImage{}, false}, + {"digest", strings.Repeat("0", 64), int64(len(body)), applevz.RestoreImage{}, false}, + {"version", goodDigest, int64(len(body)), applevz.RestoreImage{Version: "27.2.2", Build: "26B131"}, true}, + {"build", goodDigest, int64(len(body)), applevz.RestoreImage{Version: "27.2.1", Build: "26B132"}, true}, + } { + t.Run(tc.name, func(t *testing.T) { + var requests []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests = append(requests, r.Header.Get("Range")) + w.Header().Set("ETag", tag) + w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", len(body))) + w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) + })) + defer server.Close() + cache := RestoreCache{Dir: t.TempDir()} + part := filepath.Join(cache.Dir, strings.TrimSuffix(name, ".ipsw")+".part.ipsw") + for file, data := range map[string]string{part: body, part + ".etag": tag} { + if err := os.WriteFile(file, []byte(data), 0o600); err != nil { + t.Fatal(err) + } + } + r := Release{Build: "26B131", Version: "27.2.1", URL: server.URL, Size: tc.size, Digest: tc.digest} + inspected := false + result, err := cache.download(t.Context(), r, name, server.Client(), func(context.Context, string) (applevz.RestoreImage, error) { + inspected = true + return tc.image, nil + }, nil) + if result != nil || err == nil || inspected != tc.wantInspected { + t.Fatalf("result = %+v, inspected = %t, error = %v", result, inspected, err) + } + if want := []string{fmt.Sprintf("bytes=%d-", len(body))}; !slices.Equal(requests, want) { + t.Fatalf("requests = %q, want %q", requests, want) + } + for _, file := range []string{part, part + ".etag", filepath.Join(cache.Dir, name)} { + if _, err := os.Stat(file); !os.IsNotExist(err) { + t.Fatalf("invalid download left %s: %v", file, err) + } + } + }) + } +} + +func TestRestoreCatalogRejectsUntrustedURLs(t *testing.T) { + const name = "UniversalMac_27.2.1_26B131_Restore.ipsw" + for _, tc := range []struct { + base string + valid bool + }{ + {"https://updates.cdn-apple.com/catalog/", true}, {"https://updates.apple.com/", true}, + {"http://updates.apple.com/", false}, {"https://updates.apple.com.evil.example/", false}, + {"https://other.example@updates.apple.com/", false}, {"https://updates.apple.com:9443/", false}, + } { + r := Release{Version: "27.2.1", Build: "26B131", URL: tc.base + name} + if _, err := restoreFilename(r); (err == nil) != tc.valid { + t.Errorf("catalog source %s: %v", tc.base, err) + } + r.Build = "26B132" + if _, err := restoreFilename(r); err == nil { + t.Fatalf("catalog source accepted a mismatching build: %+v", r) + } + } +} diff --git a/internal/plugin/builtin/bootstrap.go b/internal/plugin/builtin/bootstrap.go index a716de9..54e48fd 100644 --- a/internal/plugin/builtin/bootstrap.go +++ b/internal/plugin/builtin/bootstrap.go @@ -21,7 +21,7 @@ type KernelBootstrapOptions struct { HostHandlers func(pluginID string) map[string]plugin.RPCRequestHandler OnSettingsChanged func(pluginID, vmName string) OnSidecarStopped func(pluginID string) - VMInventory driver.VMInventory + VMInventories []driver.VMInventory Callbacks HostCallbacks RegisterGuest func(reg *plugin.Registry, cb HostCallbacks, desired func(id string, defaultEnabled bool) bool) error // StrictRegister causes builtin/guest registration errors to abort bootstrap @@ -66,7 +66,7 @@ func BootstrapKernel(opts KernelBootstrapOptions) (*plugin.Manager, *driver.Rout root := opts.DataRoot dataRootFn = func() string { return root } } - router := driver.NewRouter(mgr.Registry(), dataRootFn, opts.VMInventory) + router := driver.NewRouter(mgr.Registry(), dataRootFn, opts.VMInventories...) mgr.Registry().SetInUseChecker(router.PluginInUseChecker()) mgr.Registry().SetBusyChecker(router.PluginBusyChecker()) diff --git a/internal/plugin/icon_test.go b/internal/plugin/icon_test.go index 6cf64e7..70698b6 100644 --- a/internal/plugin/icon_test.go +++ b/internal/plugin/icon_test.go @@ -50,6 +50,26 @@ func TestResolvePluginIconFromPackageDir(t *testing.T) { if !strings.HasPrefix(got.SVG, "` + got := ResolvePluginIcon(&PluginIcon{Tone: "sky", SVG: svg}, "", true) + if got == nil || !strings.Contains(got.SVG, `stroke="currentColor"`) { + t.Fatalf("unexpected resolved builtin icon: %+v", got) + } + assertPluginIconNamespace(t, got.SVG) +} + +func assertPluginIconNamespace(t *testing.T, svg string) { + t.Helper() + root, _, _ := strings.Cut(svg, ">") + if strings.Count(root, `xmlns="`) != 1 || !strings.Contains(root, `xmlns="http://www.w3.org/2000/svg"`) { + t.Fatalf("standalone SVG must declare the root namespace exactly once: %s", root) + } } func TestScanBlocksOversizedAndMalformedIconSVG(t *testing.T) { diff --git a/internal/plugin/types.go b/internal/plugin/types.go index c66d978..2ad3a1a 100644 --- a/internal/plugin/types.go +++ b/internal/plugin/types.go @@ -689,7 +689,8 @@ type SettingsSchema struct { // SettingProperty describes one configurable field. type SettingProperty struct { - Type string `json:"type"` // "boolean" | "string" | "number" | "integer" + Type string `json:"type"` // "boolean" | "string" | "number" | "integer" + FilePattern string `json:"x-filePattern,omitempty"` // native picker for built-in create forms only Title LocalizedText `json:"title"` Description LocalizedText `json:"description,omitempty"` Default any `json:"default,omitempty"` diff --git a/internal/plugin/uiassets/assets.go b/internal/plugin/uiassets/assets.go index 0d837c5..8e7cf22 100644 --- a/internal/plugin/uiassets/assets.go +++ b/internal/plugin/uiassets/assets.go @@ -158,6 +158,7 @@ func SanitizeSVG(raw []byte) []byte { var out bytes.Buffer enc := xml.NewEncoder(&out) skipDepth := 0 + var namespaces []string for { tok, err := dec.Token() if err == io.EOF { @@ -175,7 +176,16 @@ func SanitizeSVG(raw []byte) []byte { continue } filtered := make([]xml.Attr, 0, len(t.Attr)) + // The decoder resolves namespace URIs and the encoder emits their + // declarations. Forwarding the original xmlns would duplicate it. + if n := len(namespaces); n > 0 && namespaces[n-1] != "" && t.Name.Space == "" { + filtered = append(filtered, xml.Attr{Name: xml.Name{Local: "xmlns"}}) + } + namespaces = append(namespaces, t.Name.Space) for _, attr := range t.Attr { + if attr.Name.Space == "xmlns" || (attr.Name.Space == "" && attr.Name.Local == "xmlns") { + continue + } name := strings.ToLower(attr.Name.Local) if strings.HasPrefix(name, "on") { continue @@ -197,6 +207,7 @@ func SanitizeSVG(raw []byte) []byte { skipDepth-- continue } + namespaces = namespaces[:len(namespaces)-1] if err := enc.EncodeToken(t); err != nil { return nil } diff --git a/internal/plugin/uiassets/assets_test.go b/internal/plugin/uiassets/assets_test.go new file mode 100644 index 0000000..389b67d --- /dev/null +++ b/internal/plugin/uiassets/assets_test.go @@ -0,0 +1,61 @@ +package uiassets + +import ( + "bytes" + "encoding/xml" + "io" + "testing" +) + +func TestSanitizeSVGPreservesNamespacesWithoutDuplicateDeclarations(t *testing.T) { + const svg = "http://www.w3.org/2000/svg" + const xlink = "http://www.w3.org/1999/xlink" + raw := []byte(`` + + `` + + ``) + cleaned := SanitizeSVG(raw) + dec := xml.NewDecoder(bytes.NewReader(cleaned)) + want := []xml.Name{ + {Space: svg, Local: "svg"}, + {Space: svg, Local: "use"}, + {Space: svg, Local: "use"}, + {Space: svg, Local: "metadata"}, + {Local: "note"}, + {Local: "entry"}, + {Space: svg, Local: "g"}, + } + i := 0 + for { + tok, err := dec.Token() + if err == io.EOF { + break + } + if err != nil { + t.Fatalf("invalid sanitized SVG: %v\n%s", err, cleaned) + } + start, ok := tok.(xml.StartElement) + if !ok { + continue + } + if i >= len(want) || start.Name != want[i] { + t.Fatalf("unexpected element %d: %+v\n%s", i, start.Name, cleaned) + } + seen := map[xml.Name]bool{} + for _, attr := range start.Attr { + if seen[attr.Name] { + t.Fatalf("duplicate %s attribute on <%s>\n%s", attr.Name.Local, start.Name.Local, cleaned) + } + seen[attr.Name] = true + if attr.Name.Local == "onload" || (attr.Name.Local == "href" && (i != 1 || attr.Name.Space != xlink || attr.Value != "#shape")) { + t.Fatalf("unexpected attribute on <%s>: %+v", start.Name.Local, attr) + } + } + if i == 1 && !seen[xml.Name{Space: xlink, Local: "href"}] { + t.Fatal("lost local namespaced reference") + } + i++ + } + if i != len(want) { + t.Fatalf("found %d elements, want %d: %s", i, len(want), cleaned) + } +} diff --git a/internal/tray/tray_other.go b/internal/tray/tray_other.go index e852710..b24b4cf 100644 --- a/internal/tray/tray_other.go +++ b/internal/tray/tray_other.go @@ -5,8 +5,9 @@ package tray // Manager is a no-op stub on non-Windows platforms. type Manager struct{} +// Start returns no manager on hosts without a system tray implementation. func Start(_ []byte, _ string, _ Callbacks) (*Manager, error) { - return &Manager{}, nil + return nil, nil } func (m *Manager) UpdateTooltip(_ string) {} diff --git a/link_darwin.go b/link_darwin.go new file mode 100644 index 0000000..be9751c --- /dev/null +++ b/link_darwin.go @@ -0,0 +1,9 @@ +//go:build darwin && cgo + +package main + +// Wails' macOS file dialogs use UTType. Link the framework explicitly while +// the pinned Wails version does not include it in its cgo linker flags. + +// #cgo LDFLAGS: -framework UniformTypeIdentifiers +import "C" diff --git a/locales/en-US/core.json b/locales/en-US/core.json index eb8ce95..5fa1047 100644 --- a/locales/en-US/core.json +++ b/locales/en-US/core.json @@ -35,6 +35,24 @@ "menuVM": "VM", "menuView": "View", "menuHelp": "Help", + "menuMacEdit": "Edit", + "menuMacWindow": "Window", + "menuMacHide": "Hide Reims-Go", + "menuMacHideOthers": "Hide Others", + "menuMacShowAll": "Show All", + "menuMacQuit": "Quit Reims-Go", + "menuMacUndo": "Undo", + "menuMacRedo": "Redo", + "menuMacCut": "Cut", + "menuMacPaste": "Paste", + "menuMacPasteMatchStyle": "Paste and Match Style", + "menuMacDelete": "Delete", + "menuMacSelectAll": "Select All", + "menuMacSpeech": "Speech", + "menuMacStartSpeaking": "Start Speaking", + "menuMacStopSpeaking": "Stop Speaking", + "menuMacZoom": "Zoom", + "menuMacFullScreen": "Enter Full Screen", "newVMEllipsis": "New Virtual Machine…", "deleteEllipsis": "Delete…", "sidebarLabel": "Sidebar", @@ -69,7 +87,7 @@ "taskAppUpdate": "Downloading Reims-Go {v}", "taskPluginDownload": "Downloading {name}", "closeDownloadsTitle": "Quit Reims-Go?", - "closeDownloadsDesc": "Downloads are still running. Quitting stops them.", + "closeDownloadsDesc": "Quitting stops any downloads or macOS installations in progress.", "closeDownloadsConfirm": "Quit", "settingsAbout": "About", "themeLight": "Light", @@ -131,6 +149,7 @@ "taskDownload": "Downloading macOS {v}", "taskRecoveryDownload": "Downloading online recovery for {name}", "taskCreate": "Creating {name}", + "taskRestoreVM": "Installing macOS on {name}", "tasksRunning": { "message": "{n, plural, one {# task running} other {# tasks running}}", "$comment": "底部后台任务队列汇总" @@ -155,6 +174,8 @@ "toastCopied": "Copied", "failGeneric": "Something went wrong", "noRuntimeAlert": "Import a runtime under Engine first", + "wizardNoDriver": "No eligible guest driver is available", + "wizardDriverListFailed": "Could not load guest drivers", "importRuntime": "Import runtime", "gpuWarnAmdLegacy": "AMD Vega/Polaris on Windows hits known upstream black-screen/device-loss issues ({ref}); prefer another discrete GPU or use VMware SVGA for now", "gpuWarnAmdRdna2": "This AMD GPU hits known Windows device-loss issues upstream ({ref}); update drivers or use VMware SVGA if it freezes", diff --git a/locales/en-US/native.json b/locales/en-US/native.json index db8f51c..3d90999 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -128,7 +128,10 @@ "avail" ] }, + "doctor.ram.total_only": "{total, number, .1} GB total (available memory unknown)", "doctor.disk": "Data Drive Free Space", + "doctor.apple_virtualization.ready": "Ready", + "doctor.apple_virtualization.unavailable": "Unavailable", "doctor.whpx": "Windows Hypervisor Platform (WHPX)", "doctor.whpx.ok": "Ready (WinHvPlatform.dll active, hypervisor running)", "doctor.whpx.no_hv": "WinHvPlatform.dll present, but no hypervisor detected (enable VT-x/AMD-V in BIOS)", @@ -293,6 +296,8 @@ "name" ] }, + "err.restore_catalog_unavailable": "Apple’s restore image catalog is unavailable. Retry or choose a local IPSW.", + "err.restore_catalog_unsupported": "This Nivfold version cannot query restore images. Update Nivfold or choose a local IPSW.", "err.runtime_not_installed": "no active portable runtime found; run `reims-go runtime install ` first", "err.qemu_aslr.cancelled": "Windows authorization was canceled before the QEMU ASLR changes were applied", "err.qemu_aslr.image_policy": "Windows already has a program-wide rule for qemu-system-x86_64.exe, so this runtime’s ASLR rule was skipped. Manage QEMU’s ASLR in Windows Security under Exploit protection → Program settings.", @@ -936,6 +941,12 @@ }, "affinity.summary.all": "all", "cli.usage.header": "reims-go - Portable one-stop reims-vgpu launcher for Windows", + "cli.usage.apple.header": "reims-go - Experimental Apple silicon VM manager", + "cli.usage.apple.doctor": " doctor Check Apple Virtualization support", + "cli.usage.apple.create": " vm create --ipsw Create from a local Apple restore image", + "cli.usage.apple.start": " vm start Start a VM and open its viewer", + "cli.usage.apple.stop": " vm stop [--force] Shut down a VM", + "cli.usage.apple.delete": " vm delete [--keep-files] Remove a stopped VM", "cli.usage.section_usage": "Usage:", "cli.usage.line_gui": " reims-go Open the window (--background: tray only, no window)", "cli.usage.line_cmd": " reims-go [--lang ] [--data-root DIR] [args]", diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index 58957e2..99ee690 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -29,6 +29,7 @@ "bridgeApplyHint": "Network changes apply separately. Shut down this VM to change mode; bridged uplinks can change while running without reconfiguring other VMs. Host adapter IP, DNS, and bindings remain unchanged", "installersTitle": "Images", "installersDownloaded": "Downloaded", + "installersCacheUnavailable": "Cached image unavailable", "installersAvailable": "Releases from Apple", "installersLatest": "Latest", "installersOlder": { @@ -104,12 +105,14 @@ "aboutCopyDiscord": "Copy invite link", "aboutJoinDiscord": "Join server", "aboutQQGroup": "QQ Group", - "aboutQQNotInstalled": "QQ not installed", - "aboutQQNotInstalledSub": "Local QQ wasn’t detected — copy the group ID to join manually", - "aboutQQLaunchFailed": "Couldn’t launch QQ — copy the group ID to join manually", + "aboutQQNotInstalled": "Can’t open QQ directly", + "aboutQQNotInstalledSub": "No QQ app can handle the invite link — open the invite page or copy the group ID", + "aboutQQLaunchFailed": "Couldn’t open QQ — open the invite page or copy the group ID", + "aboutQQOpenInvite": "Open invite page", "aboutCopyQQGroup": "Copy group ID", "aboutJoinQQGroup": "Join group", "whpxTitle": "WHPX", + "appleVirtualizationTitle": "Apple Virtualization", "whpxReady": "Ready", "whpxNoHvShort": "Inactive", "whpxMissingShort": "Off", diff --git a/locales/en-US/wizard.json b/locales/en-US/wizard.json index 0303153..d9bb52d 100644 --- a/locales/en-US/wizard.json +++ b/locales/en-US/wizard.json @@ -44,6 +44,11 @@ "srcOfflineSub": "The full installer; installs with no network", "srcAppleTitle": "Download from Apple", "srcAppleSub": "A recovery image; macOS downloads during install", + "srcIPSWDownloadTitle": "Compatible restore image", + "srcIPSWDownloadSub": "Download from Apple or use a saved restore image", + "srcIPSWLocalTitle": "Local restore image", + "srcIPSWLocalSub": "Choose an .ipsw file on this Mac", + "srcIPSWNone": "No compatible restore image is available", "srcInstallerTitle": "Installer image", "srcInstallerSub": "An .img or .dmg on this PC", "srcDiskTitle": "Existing disk", diff --git a/locales/zh-CN/core.json b/locales/zh-CN/core.json index 50beef1..11dc186 100644 --- a/locales/zh-CN/core.json +++ b/locales/zh-CN/core.json @@ -35,6 +35,24 @@ "menuVM": "虚拟机", "menuView": "视图", "menuHelp": "帮助", + "menuMacEdit": "编辑", + "menuMacWindow": "窗口", + "menuMacHide": "隐藏 Reims-Go", + "menuMacHideOthers": "隐藏其他应用", + "menuMacShowAll": "显示全部", + "menuMacQuit": "退出 Reims-Go", + "menuMacUndo": "撤销", + "menuMacRedo": "重做", + "menuMacCut": "剪切", + "menuMacPaste": "粘贴", + "menuMacPasteMatchStyle": "粘贴并匹配样式", + "menuMacDelete": "删除", + "menuMacSelectAll": "全选", + "menuMacSpeech": "朗读", + "menuMacStartSpeaking": "开始朗读", + "menuMacStopSpeaking": "停止朗读", + "menuMacZoom": "缩放", + "menuMacFullScreen": "进入全屏幕", "newVMEllipsis": "新建虚拟机…", "deleteEllipsis": "删除…", "sidebarLabel": "侧边栏", @@ -69,7 +87,7 @@ "taskAppUpdate": "下载 Reims-Go {v}", "taskPluginDownload": "下载 {name}", "closeDownloadsTitle": "退出 Reims-Go?", - "closeDownloadsDesc": "仍有下载正在进行,退出会中断它们。", + "closeDownloadsDesc": "退出会中断正在进行的下载或 macOS 安装。", "closeDownloadsConfirm": "退出", "settingsAbout": "关于", "themeLight": "浅色", @@ -131,6 +149,7 @@ "taskDownload": "下载 macOS {v}", "taskRecoveryDownload": "正在为 {name} 拉取并挂载在线恢复镜像", "taskCreate": "创建 {name}", + "taskRestoreVM": "在 {name} 上安装 macOS", "tasksRunning": { "message": "{n, plural, other {# 个任务进行中}}", "$comment": "底部后台任务队列汇总" @@ -155,6 +174,8 @@ "toastCopied": "已复制", "failGeneric": "操作失败", "noRuntimeAlert": "先在「内核」导入运行时包", + "wizardNoDriver": "没有可用的客体驱动", + "wizardDriverListFailed": "无法加载客体驱动", "importRuntime": "导入运行时包", "gpuWarnAmdLegacy": "AMD Vega/Polaris 在 Windows 闭源驱动下存在上游已知黑屏/设备丢失问题({ref});若有其他独显请改选独显,否则建议暂用 VMware SVGA", "gpuWarnAmdRdna2": "该 AMD 显卡在 Windows 下存在上游已知设备丢失风险({ref});若卡死黑屏请升级驱动或暂用 VMware SVGA", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index 19ca56c..40cdbaa 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -128,7 +128,10 @@ "avail" ] }, + "doctor.ram.total_only": "共 {total, number, .1} GB(可用内存未知)", "doctor.disk": "数据盘剩余空间", + "doctor.apple_virtualization.ready": "可用", + "doctor.apple_virtualization.unavailable": "不可用", "doctor.whpx": "Windows 虚拟机监控程序平台 (WHPX)", "doctor.whpx.ok": "可用(WinHvPlatform.dll 已就绪,hypervisor 运行中)", "doctor.whpx.no_hv": "已加载 WinHvPlatform.dll,但未检测到虚拟化(请在 BIOS 开启 VT-x/AMD-V)", @@ -293,6 +296,8 @@ "name" ] }, + "err.restore_catalog_unavailable": "暂时无法读取 Apple 的恢复镜像目录,可重试或选择本地 IPSW。", + "err.restore_catalog_unsupported": "当前 Nivfold 版本不支持查询恢复镜像,可更新 Nivfold 或选择本地 IPSW。", "err.runtime_not_installed": "未找到已激活的便携运行时,请先执行 `reims-go runtime install <归档路径>`", "err.qemu_aslr.cancelled": "已取消 Windows 管理员授权,QEMU ASLR 设置保持原样", "err.qemu_aslr.image_policy": "Windows 已按程序名为 qemu-system-x86_64.exe 配置防护,已跳过此运行时的 ASLR 规则。可在 Windows 安全中心的「漏洞保护 → 程序设置」中管理 QEMU 的 ASLR", @@ -936,6 +941,12 @@ }, "affinity.summary.all": "全部核心", "cli.usage.header": "reims-go - Windows 一站式免编译 reims-vgpu 启动器", + "cli.usage.apple.header": "reims-go - Apple 芯片 Mac 实验性虚拟机管理器", + "cli.usage.apple.doctor": " doctor 检查 Apple 虚拟化环境", + "cli.usage.apple.create": " vm create --ipsw 从本地 Apple 恢复镜像创建虚拟机", + "cli.usage.apple.start": " vm start 启动虚拟机并打开窗口", + "cli.usage.apple.stop": " vm stop [--force] 关闭虚拟机", + "cli.usage.apple.delete": " vm delete [--keep-files] 删除已关机的虚拟机", "cli.usage.section_usage": "用法:", "cli.usage.line_gui": " reims-go 打开界面(--background:只在托盘运行,不显示窗口)", "cli.usage.line_cmd": " reims-go [--lang ] [--data-root DIR] <命令> [参数]", diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index c74d6e9..e0642d6 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -29,6 +29,7 @@ "bridgeApplyHint": "网络设置单独应用。切换模式需关闭此虚拟机,更换桥接出口支持运行中应用,不影响其他虚拟机。宿主网卡的 IP、DNS 和绑定保持不变", "installersTitle": "镜像", "installersDownloaded": "已下载", + "installersCacheUnavailable": "缓存镜像不可用", "installersAvailable": "Apple 提供的版本", "installersLatest": "最新", "installersOlder": { @@ -104,12 +105,14 @@ "aboutCopyDiscord": "复制邀请链接", "aboutJoinDiscord": "加入服务器", "aboutQQGroup": "QQ 交流群", - "aboutQQNotInstalled": "未安装 QQ", - "aboutQQNotInstalledSub": "未检测到本地 QQ,可复制群号手动搜索加入", - "aboutQQLaunchFailed": "未能拉起 QQ,可复制群号手动搜索加入", + "aboutQQNotInstalled": "无法直接打开 QQ", + "aboutQQNotInstalledSub": "未找到可处理加群链接的 QQ,可打开邀请页或复制群号", + "aboutQQLaunchFailed": "未能打开 QQ,可打开邀请页或复制群号", + "aboutQQOpenInvite": "打开邀请页", "aboutCopyQQGroup": "复制群号", "aboutJoinQQGroup": "加入群聊", "whpxTitle": "WHPX", + "appleVirtualizationTitle": "Apple 虚拟化", "whpxReady": "就绪", "whpxNoHvShort": "未激活", "whpxMissingShort": "未启用", diff --git a/locales/zh-CN/wizard.json b/locales/zh-CN/wizard.json index abea692..6b4c472 100644 --- a/locales/zh-CN/wizard.json +++ b/locales/zh-CN/wizard.json @@ -44,6 +44,11 @@ "srcOfflineSub": "完整安装包,装机时不联网", "srcAppleTitle": "从 Apple 下载", "srcAppleSub": "恢复镜像,系统在装机时在线下载", + "srcIPSWDownloadTitle": "兼容恢复镜像", + "srcIPSWDownloadSub": "从 Apple 下载或使用已下载的镜像", + "srcIPSWLocalTitle": "本地恢复镜像", + "srcIPSWLocalSub": "选择这台 Mac 上的 .ipsw 文件", + "srcIPSWNone": "没有兼容的恢复镜像", "srcInstallerTitle": "安装镜像", "srcInstallerSub": "本机上的 .img 或 .dmg", "srcDiskTitle": "已有磁盘", diff --git a/main.go b/main.go index 7f90345..956d940 100644 --- a/main.go +++ b/main.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "os" + "runtime" "time" "github.com/Nwflower/reims-go/internal/app" @@ -17,6 +18,7 @@ import ( "github.com/wailsapp/wails/v2" "github.com/wailsapp/wails/v2/pkg/options" "github.com/wailsapp/wails/v2/pkg/options/assetserver" + "github.com/wailsapp/wails/v2/pkg/options/mac" "github.com/wailsapp/wails/v2/pkg/options/windows" ) @@ -110,7 +112,12 @@ func main() { Height: 740, MinWidth: 920, MinHeight: 600, - Frameless: true, + // macOS extends content behind a titled native window; a frameless + // window would also remove the system traffic-light controls. + Frameless: runtime.GOOS != "darwin", + Mac: &mac.Options{ + TitleBar: mac.TitleBarHidden(), + }, DragAndDrop: &options.DragAndDrop{ EnableFileDrop: true, DisableWebViewDrop: true, diff --git a/scripts/build-macos.mjs b/scripts/build-macos.mjs new file mode 100644 index 0000000..17f87d6 --- /dev/null +++ b/scripts/build-macos.mjs @@ -0,0 +1,54 @@ +#!/usr/bin/env node +import { execFileSync } from 'node:child_process' +import fs from 'node:fs' +import path from 'node:path' +import { cachePath, REPO_ROOT, resolveStorageRoot, runsPath } from './debug/paths.mjs' +import { createTemporaryFiles } from './debug/temporary-files.mjs' + +if (process.platform !== 'darwin' || process.arch !== 'arm64') { + console.error('This build requires an Apple silicon Mac and the Xcode toolchain.') + process.exit(1) +} + +const root = resolveStorageRoot() +const temps = createTemporaryFiles(root) +const output = runsPath(root, 'macos-client') +const goCache = cachePath(root, 'go-build') +const input = process.argv.slice(2) +if (input.length !== 0 && (input.length !== 2 || input[0] !== '--runtime')) { + console.error('Usage: node scripts/build-macos.mjs [--runtime ]') + process.exit(1) +} +const external = input.length ? path.resolve(input[1]) : null +const directory = temps.create('build-macos', process.pid) +const env = { ...process.env, TMPDIR: directory, GOTMPDIR: directory, GOCACHE: goCache, CGO_ENABLED: '1' } +const run = (command, args) => execFileSync(command, args, { cwd: REPO_ROOT, env, stdio: 'inherit' }) + +function stageRuntime(source) { + const staged = path.join(directory, 'nivfold') + fs.copyFileSync(source, staged, fs.constants.COPYFILE_EXCL) + fs.accessSync(staged, fs.constants.X_OK) + run('codesign', ['--verify', '--strict', staged]) + const report = JSON.parse(execFileSync(staged, ['probe'], { cwd: REPO_ROOT, env, timeout: 5000, encoding: 'utf8' })) + if (report.runtime !== 'nivfold' || report.protocol_version !== 1 || report.supported !== true) { + throw new Error('expected a compatible Nivfold runtime (protocol 1)') + } + return staged +} + +try { + for (const dir of [output, goCache]) fs.mkdirSync(dir, { recursive: true }) + const helper = external ? stageRuntime(external) : null + run('pnpm', ['--dir', 'frontend', '--store-dir', cachePath(root, 'pnpm-store'), 'install', '--frozen-lockfile']) + run('pnpm', ['--dir', 'frontend', 'run', 'build']) + const client = path.join(directory, 'reims-go') + run('go', ['build', '-trimpath', '-tags', 'desktop,production', '-o', client, '.']) + if (helper) fs.renameSync(helper, path.join(output, 'nivfold')) + fs.renameSync(client, path.join(output, 'reims-go')) + temps.close(directory) + console.log(`Native macOS client: ${path.join(output, 'reims-go')}`) + if (!helper) console.log('The client build does not install a VM runtime. Pass --runtime with a trusted Nivfold build to install it beside the client.') +} catch (error) { + console.error(`macOS build failed: ${error.message}\nBuild directory retained: ${directory}`) + process.exitCode = 1 +} diff --git a/scripts/check-nivfold.mjs b/scripts/check-nivfold.mjs new file mode 100644 index 0000000..d8dfa8a --- /dev/null +++ b/scripts/check-nivfold.mjs @@ -0,0 +1,17 @@ +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import fs from 'node:fs' +import path from 'node:path' + +const [runner] = process.argv.slice(2) +const vm = path.join(process.env.REIMS_TMP_DIR, 'native-vm') +fs.mkdirSync(vm, { mode: 0o700 }) +const query = (...args) => JSON.parse(execFileSync(runner, args, { encoding: 'utf8', timeout: 5000 })) +const probe = query('probe') +assert.equal(probe.runtime, 'nivfold') +assert.equal(probe.protocol_version, 1) +assert.equal(probe.entitled, true) +assert.equal(probe.supported, true) +assert.ok(probe.resources.recommended_cpu_count > 0) +assert.ok(probe.resources.maximum_memory_mib >= probe.resources.minimum_memory_mib) +assert.deepEqual(query('status', '--vm-dir', vm), { installed: false, pid: 0, state: 'stopped' }) diff --git a/scripts/test.mjs b/scripts/test.mjs index da9187e..ff89586 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -21,6 +21,7 @@ const usage = `Usage: node scripts/test.mjs ci release webview2 + applevz Set REIMS_TEST_JOBS to cap Go package concurrency (default: at most 4).` @@ -39,7 +40,7 @@ function run(label, command, args, env, cwd = REPO_ROOT) { function select(args) { const [profile, area, ...packages] = args if ((profile === 'ci' || profile === 'release') && args.length === 1) return { profile } - if (profile === 'webview2' && args.length === 2) return { profile, executable: path.resolve(area) } + if ((profile === 'webview2' || profile === 'applevz') && args.length === 2) return { profile, executable: path.resolve(area) } if (profile !== 'quick') throw new Error(usage) if (area === 'go' && packages.length > 0) { for (const pkg of packages) { @@ -96,6 +97,10 @@ async function main(args) { await run('WebView2 first launch', 'powershell.exe', [ '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', 'scripts/smoke-webview2.ps1', executable, ], env) + } else if (profile === 'applevz') { + if (process.platform !== 'darwin' || process.arch !== 'arm64') throw new Error('Apple Virtualization smoke requires Apple silicon') + await run('Apple Virtualization signature', 'codesign', ['--verify', '--strict', executable], env) + await run('Nivfold runtime protocol', process.execPath, ['scripts/check-nivfold.mjs', executable], env) } else if (profile === 'quick') { if (area === 'go') await go(packages) if (area === 'storage') { -- 2.54.1 From 7fd1947beff168d1e33c7379ce44695146d35c4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=90=83=E7=90=83?= <38305321+icaruszezen@users.noreply.github.com> Date: Sun, 6 Dec 2026 15:46:39 +0800 Subject: [PATCH 2/4] =?UTF-8?q?feat(plugin,host,macos,ui):=20=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=20Agent=20=E5=8F=97=E6=8E=A7=E6=8E=A5=E7=AE=A1?= =?UTF-8?q?=E3=80=81=E5=8F=97=E4=BF=9D=E6=8A=A4=E9=98=B6=E6=AE=B5=E7=A1=AE?= =?UTF-8?q?=E8=AE=A4=E3=80=81=E7=A6=BB=E7=BA=BF=E9=A2=84=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E4=B8=8E=E8=87=AA=E5=8A=A8=E8=A3=85=E6=9C=BA=E5=9F=BA=E7=A1=80?= =?UTF-8?q?=20(#103,=20#105,=20#129)=20(#134)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(plugin,host,ui): add agent session takeover, protected-phase confirmation, and autoinstall host foundation * feat(macos,ui,cli): add offline REIMSPROV first-boot provisioning to skip Setup Assistant (#129) Builds a per-VM read-only REIMSPROV disk image containing a pure-Go XAR Distribution flat package (provision.pkg) and an offline Recovery fallback script (provision-offline.sh). Passwords are hashed in memory to Apple SALTED-SHA512-PBKDF2 bplist00 ShadowHashData (never persisted in plaintext, no auto-login or NOPASSWD sudo). Uses native OpenDirectory.framework (JXA NSData) + dseditgroup under SIP-enabled live bootinstalld and dslocal plist + PlistBuddy under offline Recovery, skips Setup Assistant and Keyboard Setup Assistant, pre-stages Guest Tools, integrates with CreateWizard / VMPage / vm provision CLI / StartAutoInstall, and zero-wipes on finish_install, normal cold start, or DeleteVM. * feat(autoinstall,host,ui): add input-locked session shield, recovery-only mode, and restart grace cap Adds the real-machine end-to-end verified baseline for automatic macOS installation: (1) takeover_policy 'lock' with transparent Win32 VM client-area input shield, low-level key/mouse lock preserving host escape shortcuts (Alt+Tab/Alt+Esc/Win), HUD & UI Pause/Resume controls, and write guards while paused; (2) decoupled recovery_only vs full (REIMSPROV) modes in StartAutoInstall, CreateWizard, and VMAutoInstallPanel; (3) graceful_timeout_sec cap (default 10s) on automated built-in macOS host/vm.restart so Setup Assistant/Login Window restarts do not stall 90s on ACPI; (4) additional modifier aliases in console manager and agent-session/telemetry cleanup on VM deletion. * feat(autoinstall,overlay,plugin): add built-in macOS auto-install plugin, dynamic island overlay, and review fixes * fix(app,host,macos,ui): address PR #134 automated review findings - Frontend & i18n: - Fix UTF-8/GBK mojibake in VMPage.tsx. - Emit reims:confirm-resolved on timeout/cancel/resolve so frontend modals auto-close and surface errors cleanly; stop submitCreate from continuing after PrepareVMProvision failure. - Gate AutoInstallPanel RapidOCR download button on preflight can_download_ocr when pinned default assets are unavailable. - App / Sessions / Confirm / Lifecycle: - Add 30s denial cooldown for protected-phase confirmation prompts and revoke (pluginID, vmKey) grants on non-completed session exits. - Fix sessionOverlay / activeAgentSessions data race, remove duplicate permission-denied invocation, guard against clobbering other sessions or completed overlays, and unify VM key normalization. - Grant protected-phase confirmation and attach lock-mode session + watcher when resuming auto-install without an active session. - Unify FinishInstall and host/vm.finishInstall result handling and persist .reims-go-provision-ready across restarts. - Preserve non-timeout stop errors in restartMacOSVMLocked instead of force-killing. - Host Takeover Hooks: - Require both keyboard and mouse WH_*_LL hooks (rolling back partial installs), initialize thread message queue before ready, reset started state on error/exit for retry, and report hook failures. - macOS Provisioning & Autoinstall Engine: - Track REIMSPROV staged/wipe-pending/ready lifecycle markers, exclude "restore" recovery marker from re-attaching REIMSPROV, fail explicitly on offline admin plist creation failure, and report wipe failures. - Serialize per-VM Start/Stop/Resume with stop generation tokens, guard ROI fast-path against maxDim overflow, switch hostclient early-event buffer to FIFO eviction, fix untyped nil Engine return, tighten negation & high-risk fuzzy matching, preserve ackedQemuErrors across RebootWindow resets, and re-orient/expire stale inherited running checkpoints. - Document verified Windows SDK IDL vtable slots for WinOCR (live-tested on Windows) and add regression tests across app, host, macosdriver, startprep, installer, and autoinstall packages. * fix(app,cli,host,macos,ui): address PR #134 second automated review findings - CLI & Desktop Control Channel: - Add __reims_host__ / autoinstall desktop control channel with data_root verification so CLI status, resume, and stop talk directly to the live desktop runner instead of splitting checkpoint state or launching doomed short-lived CLI runners. - Merge live runners with on-disk checkpoints when listing status without a VM argument. - App Sessions, Confirmations, Downloads & Telemetry: - Scope single-VM not_authorized errors to the target VM in handleSessionBegin and resolveComputerUseVM so active sessions on other VMs are not aborted. - Exclude stopped and suspended VMs from hasUnboundAgentSession fast-polling. - Revoke protected-phase grants when a VM disappears from poll results. - Require manifest Secret:true validation before storing auto-install passwords and remove the unsafe default account_password fallback. - Reject userinfo URLs in allow_custom_mirror, gate custom-mirror exemption strictly on plugin.ErrNetOriginNotDeclared, and keep redirect SSRF checks enabled on loopback custom mirrors. - Preserve VM telemetry milestones across suspend-resume and Win10 cold-reboot restarts while still resetting on fresh cold boots. - Log a warning when Guest Tools bridge is unavailable while preparing REIMSPROV. - Clarify CallHostAPI authorization/audit contract and add regression test proving built-in plugins enforce catalog permissions and audit logging. - Host Takeover & Guest Tools: - Track locked mouse button presses via a 5-button bitmask so ButtonUp events from drags started outside the VM window are never swallowed. - Align active-window-reporter.js permissions to 0o100755 across ToolsDiskFiles, ToolsProvisionFiles, and postinstall. - macOS Provisioning & Autoinstall Engine (OCR / Vision / Rules / Runner): - Never delete an unwiped REIMSPROV image on OpenFile/Write/Sync failure; persist wipe-pending marker and return error for retry. - Harden live postinstall preference writes with chmod 600, plutil -lint, chown, and cfprefsd flush. - Rewrite Windows RapidOCR C ABI structs and result extraction to match RapidAI/RapidOcrOnnx@675e73fe4c8b9e1d0be558bb5959a1b37696ed90 include/OcrLiteCApi.h:27-70 and src/OcrLiteCApi.cpp:12-160 (5-arg OcrInit verified). - Inspect PE32/PE32+ IMAGE_DIRECTORY_ENTRY_IMPORT directly to require onnxruntime.dll only for dynamically linked RapidOcrOnnx.dll builds. - Validate cfg.VM and use collision-free SHA-256-suffixed checkpoint paths with read fallback; redact PII/paths/UUIDs/MACs/IPs/tokens in diagnostic summaries; snapshot checkpoints before releasing r.mu for serialized disk I/O. - Add contrast/border/focus-ring ok return to DetectInputFieldNearLabel, enforce mask-dots verification in fillAccountForm and login screens, refuse blind password typing on clock-only lock screens, confirm shell readiness before typing install.sh, and prefer isolated button lines over modal prose in FindHit. - Frontend: - Require explicit Apple SLA confirmation in both recovery_only and full modes across AutoInstallPanel and CreateWizard, with unit tests in frontend/scripts/test-autoinstall.mjs. * fix(app,cli,host,macos,ui): address PR #134 third automated review findings Addresses all confirmed findings from Review #6204465334 (commit d516350) with targeted regression tests and hardens verified COM vtable bindings: - App & Session Lifecycle: - Track hostPaused separately in agentSession so plugin host/session.update (paused_for_user=false) cannot clear physical user takeover or explicit PauseAgentSession holds; only host ResumeAgentSession or timed takeover expiry clears them. - Give each auto-install session watcher a monotonic watchGen + cancelable child context so restarting/resuming auto-install on the same VM cancels any superseded watcher and prevents stale timeout or secret cleanup. - Bound fast 500ms unbound-PID discovery for running VMs to sessionDiscoverGraceWindow via unboundSince (refreshed on restart/rebind). - Keep non-blocking buffered confirm resolution send inside confirmMu for clear mutual exclusion with cancelPendingConfirmations. - Clear cold-reboot telemetry preserveNextBoot via defer on all early-return and StartVM-failure paths in watchColdReboot. - Rebuild REIMSPROV with current StartAutoInstall credentials (preserving install_guest_tools) whenever VM is stopped instead of reusing stale images. - CLI & macOS Provisioning / StartPrep: - Refuse `vm provision --clear` and overwriting existing REIMSPROV while the VM is running or paused. - Guard live "/" root in postinstall against macOS Recovery/Installer (/System/Installation/CDIS), forbid "/" in provision-offline.sh, and scope chmod 644 strictly to com.apple.keyboardtype.plist. - Reject unknown -* options in REIMSHELP/install.sh (including after --erase). - Defer clearing the one-shot REIMSPROV staged marker until after setExtraArgs (startprep) and StartWithCompat (macosdriver) succeed. - Preserve pending RestartFrom guards in AdvancePostInstallHandoff when checkpoint is already at StepDesktop. - Host Input & Session Overlay: - Filter injected keyboard events (LLKHF_INJECTED / LLKHF_LOWER_IL_INJECTED) in locked-input mode consistently with the mouse hook. - Clean up exited overlay entries in entry.run() and recreate dead entries on Manager.Upsert when CreateWindowExW fails or exits early. - Cache the static island base surface (shell + icons + DirectWrite text) and measured text metrics across breathing frames, raising timerBreathMs to 100ms. - Replace magic Direct2D/DirectWrite vtable indices with named d2d1.h / dwrite.h constants, check EndDraw HRESULT, and add a live Windows DirectWrite rendering smoke test. - Autoinstall OCR, Rules, Watchdog & Runner: - Persist and verify a per-file SHA-256 manifest.json in /ocr/ before loading RapidOcrOnnx.dll / onnxruntime.dll; reject duplicate whitelisted basenames in offline zip imports. - Signal WinOCREngine.Close() before acquiring e.mu and add bounded wait + channel wakeup in Recognize so Close() immediately cancels in-flight OCR. - Fall back to installed RapidOCR when WinOCR initialization fails in Open(), and distinguish needs_rapidocr_import from needs_rapidocr_download in Probe. - Pause instead of pressing Return when post-TypeSecret login screenshot fails. - Re-baseline ColdRebootCount in Watchdog.ResetRebootWindow / ResetAfterResume. - Tighten recovery.main specificity (drop bare "Disk Utility"), guard 4-5 char pure-ASCII needles from sliding-window fuzzy collisions, use Unicode word boundaries for short names (<4 runes) in RedactDiagnosticText, and honor rule verify.wait_change_ms with early exit on visual frame diff. * fix(autoinstall): handle CJK short-name redaction, sh-3.2 prompt bound, and OCR re-import pruning --- ...install-and-remote-control-foundation.json | 7 + NOTICE.md | 15 + docs/architecture.md | 4 +- docs/plugin-architecture.md | 14 +- frontend/scripts/test-autoinstall.mjs | 32 + frontend/src/App.tsx | 106 +- frontend/src/components/AppDialogs.tsx | 24 +- frontend/src/components/AppSettingsPage.tsx | 20 + frontend/src/components/AutoInstallPanel.tsx | 434 ++++ frontend/src/components/CreateWizard.tsx | 134 +- frontend/src/components/HostConfirmDialog.tsx | 105 + frontend/src/components/Sidebar.tsx | 24 +- frontend/src/components/VMPage.tsx | 98 +- frontend/src/i18n/domains/settings.gen.ts | 8 + frontend/src/i18n/domains/vm.gen.ts | 116 + frontend/src/i18n/keys.gen.ts | 62 + frontend/src/lib/autoInstallDraft.ts | 36 + frontend/src/styles/ui-contract.ts | 5 +- frontend/src/types.ts | 75 + frontend/src/wails.ts | 47 +- frontend/ui-contract.json | 5 +- frontend/wailsjs/go/app/App.d.ts | 28 + frontend/wailsjs/go/app/App.js | 56 + internal/app/agent_session_flow.go | 1775 +++++++++++++ internal/app/agent_session_lock_test.go | 246 ++ internal/app/app.go | 71 +- internal/app/autoinstall_flow.go | 571 +++++ internal/app/autoinstall_flow_test.go | 198 ++ internal/app/computer_use_host.go | 366 ++- internal/app/confirm_flow.go | 706 ++++++ internal/app/console_router_test.go | 6 +- internal/app/create_flow.go | 104 + internal/app/download_host_flow.go | 109 +- internal/app/download_host_test.go | 18 +- internal/app/host_api.go | 24 +- internal/app/host_handlers.go | 2 + internal/app/install_flow.go | 74 +- internal/app/install_guide.go | 266 +- internal/app/install_guide_test.go | 1014 ++++++++ internal/app/lifecycle_flow.go | 7 + internal/app/lifecycle_flow_test.go | 42 + internal/app/macos_lifecycle_native.go | 44 +- internal/app/plugin_connect.go | 72 + internal/app/plugins_flow.go | 29 + internal/app/provision_flow_test.go | 106 + internal/app/review_fixes_r2_test.go | 414 +++ internal/app/review_fixes_r3_test.go | 257 ++ internal/app/review_fixes_test.go | 397 +++ internal/app/stage_a_host_test.go | 292 +++ internal/app/suspend_flow.go | 5 +- internal/app/vm_monitor.go | 255 +- internal/app/vm_poll.go | 12 +- internal/archtest/file_replace_test.go | 2 + internal/cli/autoinstall.go | 170 ++ internal/cli/autoinstall_test.go | 164 ++ internal/cli/cli.go | 6 +- internal/cli/macos_native.go | 115 + internal/cli/plugin_test.go | 28 + internal/config/config.go | 21 + internal/console/manager.go | 8 +- internal/control/control.go | 83 + .../guesttools/active_window_reporter_test.go | 19 + internal/guesttools/image.go | 31 + internal/host/redact.go | 2 +- .../host/sessionoverlay/dwrite_windows.go | 625 +++++ internal/host/sessionoverlay/island_model.go | 883 +++++++ .../host/sessionoverlay/island_model_test.go | 299 +++ internal/host/sessionoverlay/overlay.go | 108 + internal/host/sessionoverlay/overlay_other.go | 29 + internal/host/sessionoverlay/overlay_test.go | 21 + .../host/sessionoverlay/overlay_windows.go | 1475 +++++++++++ .../sessionoverlay/overlay_windows_test.go | 917 +++++++ .../host/sessionoverlay/render_windows.go | 1443 +++++++++++ internal/host/takeover.go | 376 +++ internal/host/takeover_other.go | 7 + internal/host/takeover_test.go | 179 ++ internal/host/takeover_windows.go | 250 ++ internal/i18n/catalog_gen.go | 105 + .../macos/autoinstall/hostclient/client.go | 273 ++ .../autoinstall/hostclient/client_test.go | 62 + internal/macos/autoinstall/ocr/engine.go | 197 ++ internal/macos/autoinstall/ocr/fetch.go | 462 ++++ internal/macos/autoinstall/ocr/ocr_test.go | 301 +++ internal/macos/autoinstall/ocr/pe_check.go | 116 + .../macos/autoinstall/ocr/rapidocr_other.go | 48 + .../macos/autoinstall/ocr/rapidocr_windows.go | 443 ++++ .../autoinstall/ocr/rapidocr_windows_test.go | 256 ++ .../ocr/winocr_live_windows_test.go | 184 ++ .../macos/autoinstall/ocr/winocr_other.go | 26 + .../macos/autoinstall/ocr/winocr_windows.go | 634 +++++ .../macos/autoinstall/rules/data/desktop.json | 24 + .../autoinstall/rules/data/recovery.json | 52 + .../rules/data/setup-assistant.json | 473 ++++ internal/macos/autoinstall/rules/engine.go | 341 +++ internal/macos/autoinstall/rules/normalize.go | 547 ++++ .../macos/autoinstall/rules/rules_test.go | 346 +++ .../macos/autoinstall/runner/checkpoint.go | 317 +++ internal/macos/autoinstall/runner/config.go | 139 ++ internal/macos/autoinstall/runner/runner.go | 2224 +++++++++++++++++ .../macos/autoinstall/runner/runner_test.go | 2111 ++++++++++++++++ internal/macos/autoinstall/runner/watchdog.go | 200 ++ internal/macos/autoinstall/service.go | 611 +++++ internal/macos/autoinstall/service_test.go | 461 ++++ internal/macos/autoinstall/vision/locator.go | 116 + internal/macos/autoinstall/vision/probes.go | 431 ++++ .../autoinstall/vision/replay_windows_test.go | 219 ++ internal/macos/autoinstall/vision/roi.go | 313 +++ .../macos/autoinstall/vision/vision_test.go | 222 ++ internal/macos/guest/autoinstall.go | 156 ++ internal/macos/guest/guest_test.go | 72 + internal/macos/guest/register.go | 8 +- internal/macos/installer/hfs_image.go | 69 +- internal/macos/installer/provision_pkg.go | 1035 ++++++++ .../macos/installer/provision_pkg_test.go | 432 ++++ .../installer/provision_pkg_windows_test.go | 60 + internal/macos/installguide/progress.go | 96 +- internal/macos/installguide/progress_test.go | 101 + internal/macos/macosdriver/driver.go | 4 + internal/macos/macosdriver/prepare.go | 59 +- .../macosdriver/provision_prepare_test.go | 100 + internal/macos/macosdriver/recovery.go | 18 +- internal/macos/reims/helper_args.go | 37 + internal/macos/reims/provision_args_test.go | 22 + internal/macos/startprep/startprep.go | 56 +- internal/macos/startprep/startprep_test.go | 17 + internal/plugin/broker.go | 7 +- internal/plugin/builtin/bootstrap.go | 9 + internal/plugin/builtin/builtin.go | 7 + internal/plugin/contract.go | 43 +- internal/plugin/contract_test.go | 13 +- internal/plugin/inprocess_endpoint_test.go | 212 ++ internal/plugin/manager.go | 157 +- internal/plugin/registry.go | 152 +- internal/plugin/types.go | 16 +- internal/thumb/preview.go | 174 ++ internal/thumb/region_test.go | 63 + internal/thumb/thumb.go | 9 + internal/tray/tray.go | 30 +- internal/tray/tray_test.go | 32 +- locales/en-US/native.json | 82 +- locales/en-US/settings.json | 6 +- locales/en-US/vm.json | 60 +- locales/zh-CN/native.json | 82 +- locales/zh-CN/settings.json | 6 +- locales/zh-CN/vm.json | 60 +- pkg/pluginproto/proto.go | 30 +- pkg/pluginproto/types.go | 96 +- pkg/pluginsdk/sdk.go | 205 +- pkg/pluginsdk/sdk_test.go | 2 +- 149 files changed, 32099 insertions(+), 248 deletions(-) create mode 100644 .github/changes/autoinstall-and-remote-control-foundation.json create mode 100644 frontend/scripts/test-autoinstall.mjs create mode 100644 frontend/src/components/AutoInstallPanel.tsx create mode 100644 frontend/src/components/HostConfirmDialog.tsx create mode 100644 frontend/src/lib/autoInstallDraft.ts create mode 100644 internal/app/agent_session_flow.go create mode 100644 internal/app/agent_session_lock_test.go create mode 100644 internal/app/autoinstall_flow.go create mode 100644 internal/app/autoinstall_flow_test.go create mode 100644 internal/app/confirm_flow.go create mode 100644 internal/app/provision_flow_test.go create mode 100644 internal/app/review_fixes_r2_test.go create mode 100644 internal/app/review_fixes_r3_test.go create mode 100644 internal/app/review_fixes_test.go create mode 100644 internal/app/stage_a_host_test.go create mode 100644 internal/cli/autoinstall.go create mode 100644 internal/cli/autoinstall_test.go create mode 100644 internal/host/sessionoverlay/dwrite_windows.go create mode 100644 internal/host/sessionoverlay/island_model.go create mode 100644 internal/host/sessionoverlay/island_model_test.go create mode 100644 internal/host/sessionoverlay/overlay.go create mode 100644 internal/host/sessionoverlay/overlay_other.go create mode 100644 internal/host/sessionoverlay/overlay_test.go create mode 100644 internal/host/sessionoverlay/overlay_windows.go create mode 100644 internal/host/sessionoverlay/overlay_windows_test.go create mode 100644 internal/host/sessionoverlay/render_windows.go create mode 100644 internal/host/takeover.go create mode 100644 internal/host/takeover_other.go create mode 100644 internal/host/takeover_test.go create mode 100644 internal/host/takeover_windows.go create mode 100644 internal/macos/autoinstall/hostclient/client.go create mode 100644 internal/macos/autoinstall/hostclient/client_test.go create mode 100644 internal/macos/autoinstall/ocr/engine.go create mode 100644 internal/macos/autoinstall/ocr/fetch.go create mode 100644 internal/macos/autoinstall/ocr/ocr_test.go create mode 100644 internal/macos/autoinstall/ocr/pe_check.go create mode 100644 internal/macos/autoinstall/ocr/rapidocr_other.go create mode 100644 internal/macos/autoinstall/ocr/rapidocr_windows.go create mode 100644 internal/macos/autoinstall/ocr/rapidocr_windows_test.go create mode 100644 internal/macos/autoinstall/ocr/winocr_live_windows_test.go create mode 100644 internal/macos/autoinstall/ocr/winocr_other.go create mode 100644 internal/macos/autoinstall/ocr/winocr_windows.go create mode 100644 internal/macos/autoinstall/rules/data/desktop.json create mode 100644 internal/macos/autoinstall/rules/data/recovery.json create mode 100644 internal/macos/autoinstall/rules/data/setup-assistant.json create mode 100644 internal/macos/autoinstall/rules/engine.go create mode 100644 internal/macos/autoinstall/rules/normalize.go create mode 100644 internal/macos/autoinstall/rules/rules_test.go create mode 100644 internal/macos/autoinstall/runner/checkpoint.go create mode 100644 internal/macos/autoinstall/runner/config.go create mode 100644 internal/macos/autoinstall/runner/runner.go create mode 100644 internal/macos/autoinstall/runner/runner_test.go create mode 100644 internal/macos/autoinstall/runner/watchdog.go create mode 100644 internal/macos/autoinstall/service.go create mode 100644 internal/macos/autoinstall/service_test.go create mode 100644 internal/macos/autoinstall/vision/locator.go create mode 100644 internal/macos/autoinstall/vision/probes.go create mode 100644 internal/macos/autoinstall/vision/replay_windows_test.go create mode 100644 internal/macos/autoinstall/vision/roi.go create mode 100644 internal/macos/autoinstall/vision/vision_test.go create mode 100644 internal/macos/guest/autoinstall.go create mode 100644 internal/macos/installer/provision_pkg.go create mode 100644 internal/macos/installer/provision_pkg_test.go create mode 100644 internal/macos/installer/provision_pkg_windows_test.go create mode 100644 internal/macos/installguide/progress_test.go create mode 100644 internal/macos/macosdriver/provision_prepare_test.go create mode 100644 internal/macos/reims/provision_args_test.go create mode 100644 internal/plugin/inprocess_endpoint_test.go create mode 100644 internal/thumb/region_test.go diff --git a/.github/changes/autoinstall-and-remote-control-foundation.json b/.github/changes/autoinstall-and-remote-control-foundation.json new file mode 100644 index 0000000..6fd9126 --- /dev/null +++ b/.github/changes/autoinstall-and-remote-control-foundation.json @@ -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))." +} diff --git a/NOTICE.md b/NOTICE.md index 0ac0a7c..6ee6874 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -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** (, ) 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** () 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-.tar.zst`) contains diff --git a/docs/architecture.md b/docs/architecture.md index c514f4c..b74fcb2 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -49,7 +49,7 @@ flowchart TB 便携运行时为每台运行中的虚拟机创建本地 Unix 域 QMP 套接字。宿主通过统一控制台路由串行处理每台虚拟机的截图、鼠标、键盘和文本输入,按驱动声明与虚拟机能力分派至内置虚拟机交互服务的 QMP 代理(每次操作后关闭连接,与生命周期操作共用同一把虚拟机锁)或驱动自带的控制台接口;缩略图、截屏、打字与代理控制共用该路由,桌面文本输入期间暂停后台缩略图捕获。 -L3 插件经权限核验的 Host API 请求虚拟机状态、截图和输入操作,宿主不接受插件提供的 QMP 套接字或虚拟机目录。MCP 客户端通过 `reims-go plugin connect ` 与桌面进程通信;Windows 命名管道按可执行文件路径和用户 SID 摘要区分,ACL 限制当前用户并拒绝远程客户端。 +L3 插件经权限核验的 Host API 请求虚拟机状态、截图和输入操作,宿主不接受插件提供的 QMP 套接字或虚拟机目录。虚拟机处于安装或恢复阶段时,外部插件的截图与键鼠输入必须先经主窗口弹窗确认,授权仅保留在内存中并在离开阶段、停机或点击停止后立即失效。外部插件操作期间,宿主通过独立的 Win32 虚拟机窗口浮层、详情页、侧栏和系统托盘展示受控状态并提供立即停止按钮,同时在虚拟机窗口内挂接物理键鼠监听,用户在窗口内操作键鼠时自动接管并暂停外部输入;受控会话激活期间自动抑制静态人工安装引导浮层。官方 macOS 自动装机助手以默认启用的内置插件接入同一套 `contributes.autoInstallers` 扩展点与宿主权限管道,连接新建向导、详情页与 `vm autoinstall` 命令行,停用后不展示任何入口且不阻碍第三方自动装机插件并存。MCP 客户端通过 `reims-go plugin connect ` 与桌面进程通信;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 盘符只读共享默认全部关闭;启用后同时限制只读打开标志与写请求方法、核对持久化卷标识防止盘符漂移、限制目录遍历深度,并验证目录联接与符号链接目标仍位于已授权盘符内。 ### 物理出口桥接 diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index e618123..b326c70 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -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:` 权限约束的后台下载。宿主只放行已声明来源的 HTTPS 地址(测试用回环地址除外),要求提供并校验 SHA-256,检查重定向安全,禁止 HTTPS 降级为明文 HTTP 以及指向本机或私网地址的重定向,并限制落盘目录位于插件私有数据目录或该驱动声明的虚拟机根目录内。下载进度同步到桌面任务栏与 Sidecar 的 `download/progress` 通知;存在进行中的下载时,关闭主窗口会先弹出确认提示。 +插件可通过 `host/download.start` 与 `host/download.cancel` 委托宿主执行受 `net:` 权限约束的后台下载。宿主只放行已声明来源的 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 直接运行对应的系统工具。提权操作在无桌面窗口时直接拒绝,且绝不自动重启系统。 diff --git a/frontend/scripts/test-autoinstall.mjs b/frontend/scripts/test-autoinstall.mjs new file mode 100644 index 0000000..5bb0850 --- /dev/null +++ b/frontend/scripts/test-autoinstall.mjs @@ -0,0 +1,32 @@ +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.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) +}) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 373a78f..a206224 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -34,11 +34,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, DriverSummary, Locale, PluginUIContributions, Task, VMAction, VMBusyAction, VMDetail, VMInfo, VMListItem, ViewContribution } from './types' +import { ActiveThemePayload, AppState, AutoInstallerProviderView, AutoInstallStartRequest, CachedInstaller, CreateOpts, 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. @@ -125,6 +125,9 @@ export const App: React.FC = () => { const [discardSuspendTarget, setDiscardSuspendTarget] = useState(null) const [closeDownloadsOpen, setCloseDownloadsOpen] = useState(false) const [elevationQueue, setElevationQueue] = useState([]) + const [confirmQueue, setConfirmQueue] = useState([]) + const activeConfirmIDsRef = useRef(new Set()) + const [autoInstallers, setAutoInstallers] = useState([]) const [cloneSource, setCloneSource] = useState<{ name: string; driverID: string } | null>(null) const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState(null) const [sendTextTarget, setSendTextTarget] = useState(null) @@ -675,8 +678,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( @@ -1014,17 +1023,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) => { @@ -1075,7 +1120,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 || update.confirming || closeDownloadsOpen || elevationQueue.length > 0 || confirmQueue.length > 0 shortcutRef.current = (e: KeyboardEvent) => { if (!e.ctrlKey || e.altKey || e.metaKey) return if (appDialogOpen) return @@ -1117,6 +1162,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) => { @@ -1265,6 +1330,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 ? ( { 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 ? ( @@ -1489,6 +1573,7 @@ export const App: React.FC = () => { displayNames={displayNames} showWizard={showWizard} wizardDraft={wizardDraft} + autoInstallers={autoInstallers} wizardDrivers={wizardDrivers} onCloseWizard={() => { setShowWizard(false); setWizardDraft(null) }} onDriverCreated={(driverID, name) => { @@ -1534,6 +1619,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} diff --git a/frontend/src/components/AppDialogs.tsx b/frontend/src/components/AppDialogs.tsx index c736f3f..bca03c2 100644 --- a/frontend/src/components/AppDialogs.tsx +++ b/frontend/src/components/AppDialogs.tsx @@ -2,17 +2,18 @@ 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 { latestVMStats } from '../lib/vmStats' import { vmRefKey } from '../lib/vmRef' import type { PluginViewRoute } from '../lib/pluginViewRouter' -import type { AppState, CreateOpts, DriverSummary, 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,10 +34,11 @@ interface AppDialogsProps { showWizard: boolean wizardDraft: WizardDraft | null + autoInstallers?: AutoInstallerProviderView[] wizardDrivers: DriverSummary[] onCloseWizard: () => void onDriverCreated: (driverID: string, name: string) => void - onSubmitCreate: (payload: CreateOpts, draft: WizardDraft) => void + onSubmitCreate: (payload: CreateOpts, draft: WizardDraft, autoInstall?: AutoInstallStartRequest, provision?: ProvisionRequest) => void showSettings: boolean onCloseSettings: () => void @@ -63,6 +65,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 @@ -89,13 +94,14 @@ export const AppDialogs: React.FC = (props) => { const { locale, state, detail, selectedVM, selectedIsMacOS, effectiveState, fixedModeSupported, diskCacheSupported, runningVMCount, tasks, displayNames, - showWizard, wizardDraft, wizardDrivers, onCloseWizard, onDriverCreated, 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, @@ -116,6 +122,7 @@ export const AppDialogs: React.FC = (props) => { captureSupported={state.runtime_capture_supported} tasks={tasks} draft={wizardDraft} + autoInstallers={autoInstallers} onCancelTask={api.CancelTask} onClose={onCloseWizard} onDriverCreated={onDriverCreated} @@ -213,6 +220,15 @@ export const AppDialogs: React.FC = (props) => { /> )} + {confirmQueue.length > 0 && ( + onResolveConfirm(confirmQueue[0].id, approved, durationMinutes, untilPhaseExit)} + /> + )} + {discardSuspendTarget && (() => { const targetVM = findVM(discardSuspendTarget) const targetName = targetVM?.name ?? discardSuspendTarget diff --git a/frontend/src/components/AppSettingsPage.tsx b/frontend/src/components/AppSettingsPage.tsx index 01e770a..6a38ce5 100644 --- a/frontend/src/components/AppSettingsPage.tsx +++ b/frontend/src/components/AppSettingsPage.tsx @@ -659,6 +659,26 @@ export const AppSettingsPage: React.FC = ({ )} +
+
+
{tr('agentTakeoverPauseTitle')}
+
{tr('agentTakeoverPauseDesc')}
+
+
+ + 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 }) }, + ]} + /> +
+
{tr('hostDNSModeTitle')}
diff --git a/frontend/src/components/AutoInstallPanel.tsx b/frontend/src/components/AutoInstallPanel.tsx new file mode 100644 index 0000000..ea48847 --- /dev/null +++ b/frontend/src/components/AutoInstallPanel.tsx @@ -0,0 +1,434 @@ +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 = ({ + locale, provider, guestLang, onError, +}) => { + const tr = (k: I18nKey, vars?: Record) => 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 ( + void downloadOCR()}> + {tr('autoInstallDownloadOCR')} + + ) : 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 = ({ + locale, provider, showPluginFields = true, showOCRRow = true, showGuestToolsOption = false, showSLARow = true, guestLang, draft, onChange, onError, +}) => { + const tr = (k: I18nKey, vars?: Record) => t(locale, k, vars) + const pluginActive = !!provider && showPluginFields + const set = (patch: Partial) => onChange({ ...draft, ...patch }) + + return ( + <> + {pluginActive && showOCRRow && ( + + )} + set({ fullName: e.target.value })} + spellCheck={false} + /> + } + /> + set({ accountName: e.target.value.toLowerCase() })} + spellCheck={false} + /> + } + /> + set({ password: e.target.value })} + autoComplete="new-password" + /> + } + /> + 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 && ( + set({ installGuestTools })} + /> + } + /> + )} + {pluginActive && ( + set({ saveUnlockCredential })} + /> + } + /> + )} + {showSLARow && ( + 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 = ({ + locale, provider, driverID, vmName, guestLang, sessionRefreshKey = '', onCopy, onError, onToast, +}) => { + const tr = (k: I18nKey, vars?: Record) => t(locale, k, vars) + const [status, setStatus] = useState(null) + const [expanded, setExpanded] = useState(false) + const [busy, setBusy] = useState(false) + const [draft, setDraft] = useState(() => 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]) + + useEffect(() => { + let alive = true + const check = () => alive + void refreshStatus(check) + const id = window.setInterval(() => { void refreshStatus(check) }, 4000) + return () => { + alive = false + window.clearInterval(id) + } + }, [provider.plugin_id, driverID, vmName, sessionRefreshKey]) + + const active = status?.status === 'running' || status?.status === 'paused_for_user' + const paused = status?.status === 'paused_for_user' + + 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 ( + + + {active && !paused && ( + + )} + {paused && ( + + )} + {active && ( + + )} + {(paused || status?.unknown_page_summary) && ( + + )} + {!active && ( + <> + + {!expanded && ( + + )} + + )} +
+ } + /> + {!active && expanded && ( + <> + + setDraft((d) => ({ ...d, enabled }))} + /> + } + /> + {draft.enabled && ( + + )} + setDraft((d) => ({ ...d, slaAccepted }))} + /> + } + /> + void start()}> + {tr('autoInstallStart')} + + } + /> + + )} + + ) +} diff --git a/frontend/src/components/CreateWizard.tsx b/frontend/src/components/CreateWizard.tsx index bc05f04..39f7103 100644 --- a/frontend/src/components/CreateWizard.tsx +++ b/frontend/src/components/CreateWizard.tsx @@ -44,7 +44,7 @@ import { switchWizardGraphics, toggleWizardBorderless, } from '../lib/displayResolution' -import { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, Task, ValidationIssue, VMNetworkSettings } from '../types' +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 } from '../lib/endpoints' import { defaultGuestDriver, hasRestoreImagePicker, restoreImageField } from '../lib/guestDrivers' @@ -53,6 +53,8 @@ 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 }))) @@ -69,11 +71,12 @@ interface Props { captureSupported?: boolean tasks?: Task[] draft?: WizardDraft | null + autoInstallers?: AutoInstallerProviderView[] onCancelTask: (id: string) => Promise 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 @@ -96,7 +99,7 @@ const SOURCES: { mode: 'offline' | 'apple' | 'installer' | 'disk'; icon: LucideI { mode: 'disk', icon: HardDrive, title: 'srcDiskTitle', sub: 'srcDiskSub' }, ] -export const CreateWizard: React.FC = ({ locale, host, drivers, fixedModeSupported = false, captureSupported = false, tasks = [], draft, onCancelTask, onClose, onDriverCreated, onSubmit }) => { +export const CreateWizard: React.FC = ({ locale, host, drivers, fixedModeSupported = false, captureSupported = false, tasks = [], draft, autoInstallers = [], onCancelTask, onClose, onDriverCreated, onSubmit }) => { const tr = (k: I18nKey, v?: Record) => 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. @@ -112,6 +115,7 @@ export const CreateWizard: React.FC = ({ locale, host, drivers, fixedMode const [canceling, setCanceling] = useState(false) const [dependencyBusy, setDependencyBusy] = useState(false) const [dependencyRefresh, setDependencyRefresh] = useState(0) + const [autoDraft, setAutoDraft] = useState(() => defaultAutoInstallDraft()) const [validationRefresh, setValidationRefresh] = useState(0) const activeDriver = drivers.find((d) => d.id === driverID) @@ -275,9 +279,47 @@ export const CreateWizard: React.FC = ({ locale, host, drivers, fixedMode 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) : []) @@ -791,10 +833,14 @@ export const CreateWizard: React.FC = ({ locale, host, drivers, fixedMode 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} @@ -850,7 +896,7 @@ export const CreateWizard: React.FC = ({ locale, host, drivers, fixedMode ) : ( + + + + +
+ + + + ) +} diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index 65faf5a..0fca517 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -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 = ({ - 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(null) @@ -85,7 +87,7 @@ export const Sidebar: React.FC = ({ kind: ReturnType | 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, ) => ( + )} + {paused && onResumeAgentSession && ( + + )} + {onStopAgentSession && ( + + )} + + + ) + })()} + + {provisionReady && installing && !agentSession && ( +
+ + + +
+ )} + + {showAutoInstaller && matchedAutoInstaller && ( + + )} + {detail && installing && (!installGuideEnabled || state === 'stopped') && ( = { "affinitySummaryNonLPE": "P + E 核({count} 线程 · {mask})", "affinitySummaryPCores": "仅 P 核({count} 线程 · {mask})", "affinityTitle": "处理器核心", + "agentTakeoverPauseDesc": "在虚拟机窗口操作键鼠后暂停外部输入的时间,设为「手动恢复」则需点击继续", + "agentTakeoverPauseManual": "直到手动恢复", + "agentTakeoverPauseSeconds": "{seconds} 秒", + "agentTakeoverPauseTitle": "AI 操作接管暂停时长", "appCheckUpdate": "检查更新", "appUpToDate": "已是最新", "appUpdateAvailable": "发现新版本 {v}(稳定版)", @@ -573,6 +577,10 @@ export const settingsEn: Record = { "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", diff --git a/frontend/src/i18n/domains/vm.gen.ts b/frontend/src/i18n/domains/vm.gen.ts index 04fefd6..f9b416e 100644 --- a/frontend/src/i18n/domains/vm.gen.ts +++ b/frontend/src/i18n/domains/vm.gen.ts @@ -3,6 +3,39 @@ export const vmZh: Record = { "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 = { "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 = { "failFullscreen": "无法切换全屏", "failGuestTools": "Guest Tools 操作失败", "failOpenFolder": "无法打开文件夹", + "failProvision": "写入预配置卷失败", "failRestart": "重启失败", "failResume": "恢复失败", "failScreenshot": "截屏失败", @@ -158,6 +201,21 @@ export const vmZh: Record = { "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": "切换到支持挂起的内核后可恢复", @@ -263,6 +321,39 @@ export const vmZh: Record = { export const vmEn: Record = { "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 +361,15 @@ export const vmEn: Record = { "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 +435,7 @@ export const vmEn: Record = { "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 +519,21 @@ export const vmEn: Record = { "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", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index c0600d2..04dc01e 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -54,6 +54,10 @@ export type I18nKey = | "affinitySummaryNonLPE" | "affinitySummaryPCores" | "affinityTitle" + | "agentTakeoverPauseDesc" + | "agentTakeoverPauseManual" + | "agentTakeoverPauseSeconds" + | "agentTakeoverPauseTitle" | "appCheckUpdate" | "appUpToDate" | "appUpdateAvailable" @@ -80,8 +84,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" @@ -141,6 +178,15 @@ export type I18nKey = | "commandToggleHint" | "configured" | "confirm" + | "confirmAllow" + | "confirmDeny" + | "confirmDuration10" + | "confirmDuration30" + | "confirmDuration60" + | "confirmDurationLabel" + | "confirmDurationUntilExit" + | "confirmPhaseScope" + | "confirmTimedOut" | "connGroup" | "copy" | "copyScreenshot" @@ -305,6 +351,7 @@ export type I18nKey = | "failGeneric" | "failGuestTools" | "failOpenFolder" + | "failProvision" | "failRestart" | "failResume" | "failRuntime" @@ -860,12 +907,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" diff --git a/frontend/src/lib/autoInstallDraft.ts b/frontend/src/lib/autoInstallDraft.ts new file mode 100644 index 0000000..eb18e18 --- /dev/null +++ b/frontend/src/lib/autoInstallDraft.ts @@ -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 +} diff --git a/frontend/src/styles/ui-contract.ts b/frontend/src/styles/ui-contract.ts index 04347e3..7d032a7 100644 --- a/frontend/src/styles/ui-contract.ts +++ b/frontend/src/styles/ui-contract.ts @@ -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 diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 303181d..7d36fb4 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -12,6 +12,7 @@ export type Locale = BuiltinLocale | (string & {}) export type Config = Model & { locale: Locale runtime_channel?: 'stable' | 'alpha' | '' + agent_takeover_pause_sec?: number } export type DisplayInfo = host.DisplayInfo @@ -69,6 +70,78 @@ export type VMInfo = Omit, '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 + 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 + status?: string + message?: string + pause_reason?: string + unknown_page_summary?: string + matched_rules?: string[] + finish_install_done?: boolean +} + export type AppState = Omit, 'config' | 'host' | 'optimizations' | 'runtimes' | 'active_runtime' | 'vms'> & { config: Config host: HostReport @@ -77,6 +150,8 @@ export type AppState = Omit, '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 diff --git a/frontend/src/wails.ts b/frontend/src/wails.ts index ebd8942..c89cd97 100644 --- a/frontend/src/wails.ts +++ b/frontend/src/wails.ts @@ -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, DriverSummary, + LogEntry, MarketBrowseResult, PluginInfo, PluginUIContributions, ProvisionRequest, RemoteRuntime, ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMInfo, VMNetworkSettings, VMNetworkPlan, } from './types' @@ -171,6 +171,46 @@ export const api = { GetPluginUIContributions: boundGo.GetPluginUIContributions as () => Promise, GetActiveTheme: boundGo.GetActiveTheme as () => Promise, ListDrivers: boundGo.ListDrivers as () => Promise, + ResolveConfirmRequest: boundGo.ResolveConfirmRequest as (id: string, approved: boolean, durationMinutes: number, untilPhaseExit: boolean) => Promise, + PauseAgentSession: boundGo.PauseAgentSession as (driverID: string, name: string) => Promise, + ResumeAgentSession: boundGo.ResumeAgentSession as (driverID: string, name: string) => Promise, + StopAgentSession: boundGo.StopAgentSession as (driverID: string, name: string) => Promise, + SetAgentTakeoverPauseSec: boundGo.SetAgentTakeoverPauseSec as (seconds: number) => Promise, + ListAutoInstallers: boundGo.ListAutoInstallers as (guestFamily: string) => Promise, + PreflightAutoInstall: boundGo.PreflightAutoInstall as (pluginID: string, driverID: string, vmName: string, guestLang: string) => Promise>, + StartAutoInstall: boundGo.StartAutoInstall as (req: AutoInstallStartRequest) => Promise>, + GetAutoInstallStatus: boundGo.GetAutoInstallStatus as (pluginID: string, driverID: string, vmName: string) => Promise, + ResumeAutoInstall: boundGo.ResumeAutoInstall as (pluginID: string, driverID: string, vmName: string) => Promise, + StopAutoInstall: boundGo.StopAutoInstall as (pluginID: string, driverID: string, vmName: string) => Promise, + GetAutoInstallDiagnosticSummary: boundGo.GetAutoInstallDiagnosticSummary as (pluginID: string, driverID: string, vmName: string) => Promise>, + DownloadAutoInstallOCR: boundGo.DownloadAutoInstallOCR as (pluginID: string, customMirror: string) => Promise>, + PrepareVMProvision: boundGo.PrepareVMProvision as (name: string, req: ProvisionRequest) => Promise, +} + +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 { @@ -212,6 +252,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'), diff --git a/frontend/ui-contract.json b/frontend/ui-contract.json index e6e0449..8bff6c7 100644 --- a/frontend/ui-contract.json +++ b/frontend/ui-contract.json @@ -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": [ diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index f9e3c1a..f6def4a 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -230,6 +230,34 @@ export function ResizeVMDisk(arg1:string,arg2:string,arg3:string):Promise; +export function ResolveConfirmRequest(arg1:string,arg2:boolean,arg3:number,arg4:boolean):Promise; + +export function PauseAgentSession(arg1:string,arg2:string):Promise; + +export function ResumeAgentSession(arg1:string,arg2:string):Promise; + +export function StopAgentSession(arg1:string,arg2:string):Promise; + +export function SetAgentTakeoverPauseSec(arg1:number):Promise; + +export function ListAutoInstallers(arg1:string):Promise>; + +export function PreflightAutoInstall(arg1:string,arg2:string,arg3:string,arg4:string):Promise>; + +export function StartAutoInstall(arg1:Record):Promise>; + +export function GetAutoInstallStatus(arg1:string,arg2:string,arg3:string):Promise>; + +export function ResumeAutoInstall(arg1:string,arg2:string,arg3:string):Promise>; + +export function StopAutoInstall(arg1:string,arg2:string,arg3:string):Promise; + +export function GetAutoInstallDiagnosticSummary(arg1:string,arg2:string,arg3:string):Promise>; + +export function DownloadAutoInstallOCR(arg1:string,arg2:string):Promise>; + +export function PrepareVMProvision(arg1:string,arg2:any):Promise; + export function RestartVM(arg1:string,arg2:string):Promise; export function RestoreSnapshot(arg1:string,arg2:string,arg3:string):Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index 681aa2c..67b87e4 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -605,3 +605,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); +} diff --git a/internal/app/agent_session_flow.go b/internal/app/agent_session_flow.go new file mode 100644 index 0000000..c5c147f --- /dev/null +++ b/internal/app/agent_session_flow.go @@ -0,0 +1,1775 @@ +package app + +import ( + "context" + "encoding/json" + "errors" + "sort" + "strconv" + "strings" + "time" + "unicode" + + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/host/sessionoverlay" + "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/plugin" + "github.com/Nwflower/reims-go/pkg/pluginproto" +) + +type completedOverlayEntry struct { + pluginID string + driverID string + vmName string + pid uint32 +} + +type agentSession struct { + vmKey string + driverID string + vmName string + vmDir string + pluginID string + pluginName string + label string + stage string + status string + message string + takeoverPolicy string // "auto" | "manual" | "lock" + pausedForUser bool + hostPaused bool + takeoverPaused bool + takeoverUntil time.Time + startedAt time.Time + unboundSince time.Time + ephemeralGrant bool + isAutoInstall bool + autoInstallMode string + secretSetting string + saveUnlockCredential bool + finishInstallDone bool + sawSetupAssistant bool + suppressedInstallGuide bool + lastOverlayPID uint32 + lastPIDProbeAt time.Time + + ctx context.Context + cancel context.CancelFunc + watchGen uint64 + watchCancel context.CancelFunc +} + +// AgentSessionView is the read-only session snapshot exposed to the frontend, +// CLI, tray menu, and Win32 VM overlay. +type AgentSessionView struct { + VMKey string `json:"vm_key"` + DriverID string `json:"driver_id"` + VMName string `json:"vm_name"` + PluginID string `json:"plugin_id"` + PluginName string `json:"plugin_name"` + Label string `json:"label,omitempty"` + Stage string `json:"stage,omitempty"` + Status string `json:"status,omitempty"` + Message string `json:"message,omitempty"` + Phase string `json:"phase,omitempty"` + AuthUntilPhaseExit bool `json:"auth_until_phase_exit,omitempty"` + AuthRemainingSec int `json:"auth_remaining_sec,omitempty"` + TakeoverPolicy string `json:"takeover_policy,omitempty"` + InputLocked bool `json:"input_locked,omitempty"` + PausedForUser bool `json:"paused_for_user,omitempty"` + TakeoverPaused bool `json:"takeover_paused,omitempty"` + TakeoverManualWait bool `json:"takeover_manual_wait,omitempty"` + TakeoverRemainSec int `json:"takeover_remaining_sec,omitempty"` + StartedAt string `json:"started_at"` +} + +func (a *App) sessionHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler { + if mgr == nil || mgr.Broker() == nil { + return nil + } + return map[string]plugin.RPCRequestHandler{ + "host/session.begin": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/session.begin", a.handleSessionBegin), + "host/session.update": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/session.update", a.handleSessionUpdate), + "host/session.end": a.sessionEndHandler(mgr, pluginID), + } +} + +func parseVMRefFromRaw(raw json.RawMessage) string { + if len(raw) == 0 { + return "" + } + var req struct { + VM string `json:"vm"` + } + if json.Unmarshal(raw, &req) != nil { + return "" + } + return strings.TrimSpace(req.VM) +} + +func (a *App) sessionEndHandler(mgr *plugin.Manager, pluginID string) plugin.RPCRequestHandler { + authorized := a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/session.end", a.handleSessionEnd) + return func(ctx context.Context, raw json.RawMessage) (any, error) { + if refStr := parseVMRefFromRaw(raw); refStr != "" { + if vm, err := a.resolveComputerUseVMInfo(refStr); err == nil && a.hasActiveAgentSessionOwnedBy(vm.Ref().Key(), pluginID) { + res, err := a.handleSessionEnd(ctx, raw, mgr, pluginID) + if mgr.Broker() != nil { + if err != nil { + mgr.Broker().Audit(pluginID, "HOST_API_ERROR", "host/session.end") + } else { + mgr.Broker().Audit(pluginID, "HOST_API", "host/session.end") + } + } + return res, err + } + } + return authorized(ctx, raw) + } +} + +func (a *App) handleSessionBegin(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) { + req, err := decodeHostParams[pluginproto.SessionBeginParams](mgr, pluginID, "host/session.begin", raw) + if err != nil { + return nil, err + } + vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM) + if err != nil { + if strings.Contains(err.Error(), "not_authorized") { + a.abortAgentSessionForVMRef(mgr, pluginID, req.VM, "permission_denied", true) + } + return nil, err + } + if req.RequestProtectedPhaseAuth { + phase := a.effectiveVMPhase(vm) + if phase == driver.PhaseInstaller || phase == driver.PhaseRecovery { + if err := a.authorizeProtectedPhase(ctx, mgr, pluginID, vm, phase, true, req.PreferUntilPhaseExit); err != nil { + return nil, err + } + } + } + policy := strings.ToLower(strings.TrimSpace(req.TakeoverPolicy)) + if policy != "manual" && policy != "lock" { + policy = "auto" + } + a.beginAgentSession(mgr, pluginID, vm, strings.TrimSpace(req.Label), strings.TrimSpace(req.Stage), policy, false) + return map[string]any{"ok": true, "vm": vm.Ref().Key()}, nil +} + +func (a *App) handleSessionUpdate(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) { + req, err := decodeHostParams[pluginproto.SessionUpdateParams](mgr, pluginID, "host/session.update", 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() + a.sessionMu.Lock() + sess := a.agentSessions[key] + if sess == nil || sess.pluginID != pluginID { + a.sessionMu.Unlock() + return nil, errors.New("no active session owned by this plugin") + } + if stg := strings.TrimSpace(req.Stage); stg != "" { + sess.stage = stg + if stg == "stage5_setup_assistant" { + sess.sawSetupAssistant = true + } + } else if stp := strings.TrimSpace(req.Step); stp != "" { + sess.stage = stp + if stp == "stage5_setup_assistant" { + sess.sawSetupAssistant = true + } + } + now := time.Now() + if sess.takeoverPaused && !sess.takeoverUntil.IsZero() && !now.Before(sess.takeoverUntil) { + sess.takeoverPaused = false + sess.takeoverUntil = time.Time{} + } + hostHeld := sess.hostPaused || sess.takeoverPaused + if req.Status != "" { + nextStatus := strings.TrimSpace(req.Status) + if !hostHeld || nextStatus != "running" { + sess.status = nextStatus + } + } + if req.Message != "" { + sess.message = strings.TrimSpace(req.Message) + } + if req.PausedForUser != nil { + if *req.PausedForUser { + sess.pausedForUser = true + } else if !hostHeld { + // Plugins may only clear plugin-initiated pauses; host physical + // takeover or explicit user Pause must be resumed via ResumeAgentSession. + sess.pausedForUser = false + } + } + a.sessionMu.Unlock() + a.syncTakeoverTargets() + a.refreshAgentSessionVisuals(key) + a.emitStateChangedEvent() + return map[string]any{"ok": true}, nil +} + +func (a *App) handleSessionEnd(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) { + req, err := decodeHostParams[pluginproto.SessionEndParams](mgr, pluginID, "host/session.end", raw) + if err != nil { + return nil, err + } + vm, err := a.resolveComputerUseVMInfo(req.VM) + if err != nil { + return nil, err + } + key := vm.Ref().Key() + if strings.TrimSpace(req.Status) != "" || strings.TrimSpace(req.Message) != "" { + a.sessionMu.Lock() + if sess := a.agentSessions[key]; sess != nil && (pluginID == "" || sess.pluginID == pluginID) { + if st := strings.TrimSpace(req.Status); st != "" { + sess.status = st + } + if msg := strings.TrimSpace(req.Message); msg != "" { + sess.message = msg + } + } + a.sessionMu.Unlock() + } + a.endAgentSession(mgr, pluginID, key, "session_ended") + return map[string]any{"ok": true}, nil +} + +func (a *App) pluginDisplayName(mgr *plugin.Manager, pluginID string) string { + if mgr == nil || mgr.Registry() == nil { + return pluginID + } + loc := a.computerUseLocale() + if info, ok := mgr.Registry().Info(pluginID); ok { + if name := strings.TrimSpace(info.Name.Get(string(loc))); name != "" { + return name + } + } + return pluginID +} + +func (a *App) isAutoInstallerPlugin(mgr *plugin.Manager, pluginID string) bool { + if pluginID == "" { + return false + } + if mgr == nil { + a.mu.Lock() + mgr = a.pluginMgr + a.mu.Unlock() + } + if mgr == nil || mgr.Registry() == nil { + return false + } + for _, item := range mgr.Registry().AutoInstallersForFamily("") { + if item.PluginID == pluginID { + return true + } + } + return false +} + +func (a *App) setAgentSessionAutoInstallConfig(vmKey, pluginID, mode, secretSetting string, saveUnlockCredential bool) { + mode = strings.ToLower(strings.TrimSpace(mode)) + secretSetting = strings.TrimSpace(secretSetting) + a.sessionMu.Lock() + if sess := a.agentSessions[vmKey]; sess != nil && (pluginID == "" || sess.pluginID == pluginID) { + sess.isAutoInstall = true + if mode != "" { + sess.autoInstallMode = mode + } + sess.secretSetting = secretSetting + sess.saveUnlockCredential = saveUnlockCredential + } + a.sessionMu.Unlock() +} + +func (a *App) hasActiveAgentSessionOwnedBy(vmKey, pluginID string) bool { + a.sessionMu.Lock() + defer a.sessionMu.Unlock() + sess := a.agentSessions[vmKey] + return sess != nil && (pluginID == "" || sess.pluginID == pluginID) +} + +func (a *App) startAutoInstallSessionWatch(vmKey, pluginID string) (context.Context, uint64, bool) { + var prevCancel context.CancelFunc + a.sessionMu.Lock() + sess := a.agentSessions[vmKey] + if sess == nil || (pluginID != "" && sess.pluginID != pluginID) { + a.sessionMu.Unlock() + return nil, 0, false + } + prevCancel = sess.watchCancel + sess.watchGen++ + gen := sess.watchGen + wctx, wcancel := context.WithCancel(sess.ctx) + sess.watchCancel = wcancel + a.sessionMu.Unlock() + if prevCancel != nil { + prevCancel() + } + return wctx, gen, true +} + +func (a *App) isCurrentAutoInstallSessionWatch(vmKey, pluginID string, gen uint64) bool { + a.sessionMu.Lock() + defer a.sessionMu.Unlock() + sess := a.agentSessions[vmKey] + return sess != nil && (pluginID == "" || sess.pluginID == pluginID) && sess.watchGen == gen +} + +// handlePluginPermissionDeniedForVM immediately aborts any active Agent or +// auto-install session owned by pluginID on vmKey when permission is denied, +// wipes temporary credentials, unlocks VM input, notifies the plugin to stop, +// and falls back to showing the original manual installation guide. +func (a *App) handlePluginPermissionDeniedForVM(mgr *plugin.Manager, pluginID, vmKey, vmName, reason string) { + if mgr == nil { + a.mu.Lock() + mgr = a.pluginMgr + a.mu.Unlock() + } + vmKey = strings.TrimSpace(vmKey) + driverID := "" + if ref, ok := driver.ParseVMRef(vmKey); ok { + driverID = ref.DriverID + if strings.TrimSpace(vmName) == "" { + vmName = ref.Name + } + } else if strings.TrimSpace(vmName) == "" && vmKey != "" { + vmName = vmKey + } + if reason == "" { + reason = "permission_denied" + } + + a.sessionMu.Lock() + existing := a.agentSessions[vmKey] + otherActive := existing != nil && pluginID != "" && existing.pluginID != pluginID + completedEnt, hasCompleted := a.completedOverlays[vmKey] + otherCompleted := hasCompleted && pluginID != "" && completedEnt.pluginID != pluginID + sess := existing + if otherActive { + sess = nil + } + if sess != nil { + delete(a.agentSessions, vmKey) + delete(a.completedOverlays, vmKey) + } + ov := a.sessionOverlay + a.sessionMu.Unlock() + + if sess == nil { + if otherActive || otherCompleted { + return + } + a.restoreManualInstallGuideFallback(driverID, vmName) + return + } + + sess.cancel() + if sess.ephemeralGrant { + a.revokeEphemeralVMAccess(sess.pluginID, vmKey) + } + if mgr != nil && sess.secretSetting != "" { + _ = mgr.SetSettings(sess.pluginID, vmKey, map[string]any{sess.secretSetting: ""}) + } + a.revokeApprovedProtectedPhaseForPluginVM(sess.pluginID, vmKey, reason) + if ov != nil { + ov.Remove(vmKey) + } + a.syncTakeoverTargets() + + fallbackMsg := i18n.T(a.computerUseLocale(), "agent.session.denied_fallback") + if mgr != nil { + mgr.NotifySidecar(sess.pluginID, "session/stopped", map[string]any{ + "vm": vmKey, + "reason": reason, + "message": fallbackMsg, + }) + if mgr.Broker() != nil { + mgr.Broker().Audit(sess.pluginID, "SESSION_END", vmKey+" "+reason) + } + } + a.prepareInstallGuideRestoreAfterSession(sess, false) + a.restoreManualInstallGuideFallback(sess.driverID, sess.vmName) +} + +func (a *App) resolveAbortTargetForVMRef(vmRefHint string) (vmKey, vmName string) { + vmRefHint = strings.TrimSpace(vmRefHint) + if vmRefHint == "" { + return "", "" + } + if vm, err := a.resolveComputerUseVMInfo(vmRefHint); err == nil { + return vm.Ref().Key(), vm.Name + } + if ref, ok := driver.ParseVMRef(vmRefHint); ok { + return ref.Key(), ref.Name + } + return vmKeyForDriver("", vmRefHint), vmRefHint +} + +// abortAgentSessionForVMRef handles a per-VM authorization denial (such as +// allow_ai_access disabled for one VM) without disturbing the plugin's active +// sessions on other authorized VMs. +func (a *App) abortAgentSessionForVMRef(mgr *plugin.Manager, pluginID, vmRefHint, reason string, includeUnownedHint bool) { + vmKey, vmName := a.resolveAbortTargetForVMRef(vmRefHint) + if vmKey == "" { + return + } + if includeUnownedHint || a.hasActiveAgentSessionOwnedBy(vmKey, pluginID) { + a.handlePluginPermissionDeniedForVM(mgr, pluginID, vmKey, vmName, reason) + } +} + +func (a *App) abortAgentSessionsForPluginPermissionDenial(mgr *plugin.Manager, pluginID, vmRefHint, reason string, includeUnownedHint bool) { + type target struct { + vmKey string + vmName string + } + seen := map[string]bool{} + var targets []target + + if pluginID != "" { + a.sessionMu.Lock() + for k, s := range a.agentSessions { + if s != nil && s.pluginID == pluginID && !seen[k] { + seen[k] = true + targets = append(targets, target{vmKey: k, vmName: s.vmName}) + } + } + a.sessionMu.Unlock() + } + + if vmKey, vmName := a.resolveAbortTargetForVMRef(vmRefHint); vmKey != "" { + if !seen[vmKey] && (includeUnownedHint || a.hasActiveAgentSessionOwnedBy(vmKey, pluginID)) { + seen[vmKey] = true + targets = append(targets, target{vmKey: vmKey, vmName: vmName}) + } + } + + for _, t := range targets { + a.handlePluginPermissionDeniedForVM(mgr, pluginID, t.vmKey, t.vmName, reason) + } +} + +func (a *App) markAgentSessionFinishInstallDone(vmKey string) { + if vmKey == "" { + return + } + a.sessionMu.Lock() + if sess := a.agentSessions[vmKey]; sess != nil { + sess.finishInstallDone = true + } + a.sessionMu.Unlock() +} + +func (a *App) beginAgentSession(mgr *plugin.Manager, pluginID string, vm driver.VMInfo, label, stage, takeoverPolicy string, ephemeral bool) { + key := vm.Ref().Key() + pName := a.pluginDisplayName(mgr, pluginID) + isAuto := a.isAutoInstallerPlugin(mgr, pluginID) + sctx, cancel := context.WithCancel(context.Background()) + + var prevCancel context.CancelFunc + a.sessionMu.Lock() + if a.ephemeralVMAccess != nil && a.ephemeralVMAccess[pluginID] != nil && a.ephemeralVMAccess[pluginID][key] { + ephemeral = true + } + if a.agentSessions == nil { + a.agentSessions = map[string]*agentSession{} + } + delete(a.completedOverlays, key) + if existing := a.agentSessions[key]; existing != nil { + if existing.pluginID == pluginID { + if label != "" { + existing.label = label + } + if stage != "" { + existing.stage = stage + } + if takeoverPolicy != "" { + existing.takeoverPolicy = takeoverPolicy + } + if ephemeral { + existing.ephemeralGrant = true + } + if vm.Directory != "" && existing.vmDir == "" { + existing.vmDir = vm.Directory + } + if isAuto { + existing.isAutoInstall = true + } + unbound := existing.lastOverlayPID == 0 + if unbound && existing.unboundSince.IsZero() { + existing.unboundSince = time.Now() + } + a.sessionMu.Unlock() + cancel() + if a.suppressInstallGuideForVM(vm.Name) { + a.sessionMu.Lock() + if cur := a.agentSessions[key]; cur == existing { + cur.suppressedInstallGuide = true + } + a.sessionMu.Unlock() + } + a.markInstallGuideRecheck(vm.Name) + a.refreshAgentSessionVisuals(key) + a.syncTakeoverTargets() + if unbound { + a.wakePoll() + } + a.emitStateChangedEvent() + return + } + prevCancel = existing.cancel + } + now := time.Now() + sess := &agentSession{ + vmKey: key, + driverID: vm.DriverID, + vmName: vm.Name, + vmDir: vm.Directory, + pluginID: pluginID, + pluginName: pName, + label: label, + stage: stage, + status: "running", + takeoverPolicy: takeoverPolicy, + startedAt: now, + unboundSince: now, + ephemeralGrant: ephemeral, + isAutoInstall: isAuto, + ctx: sctx, + cancel: cancel, + } + a.agentSessions[key] = sess + a.sessionMu.Unlock() + + if prevCancel != nil { + prevCancel() + } + // Suppress any manual text install guide while an Agent/auto-install session owns the VM. + if a.suppressInstallGuideForVM(vm.Name) { + a.sessionMu.Lock() + if cur := a.agentSessions[key]; cur == sess { + cur.suppressedInstallGuide = true + } + a.sessionMu.Unlock() + } + a.markInstallGuideRecheck(vm.Name) + if mgr != nil && mgr.Broker() != nil { + mgr.Broker().Audit(pluginID, "SESSION_BEGIN", key) + } + a.refreshAgentSessionVisuals(key) + a.syncTakeoverTargets() + a.wakePoll() + a.emitStateChangedEvent() +} + +func (a *App) ensureAgentSessionForWrite(mgr *plugin.Manager, pluginID string, vm driver.VMInfo) { + key := vm.Ref().Key() + a.sessionMu.Lock() + sess := a.agentSessions[key] + a.sessionMu.Unlock() + if sess != nil && sess.pluginID == pluginID { + return + } + a.beginAgentSession(mgr, pluginID, vm, "", "", "auto", false) +} + +func (a *App) hasActiveAgentSessions() bool { + a.sessionMu.Lock() + defer a.sessionMu.Unlock() + return len(a.agentSessions) > 0 +} + +const sessionDiscoverGraceWindow = 30 * time.Second + +func (a *App) hasUnboundAgentSession() bool { + type unboundRef struct { + vmKey string + driverID string + vmName string + startedAt time.Time + unboundSince time.Time + } + a.sessionMu.Lock() + var unbound []unboundRef + for key, s := range a.agentSessions { + if s != nil && s.lastOverlayPID == 0 { + unbound = append(unbound, unboundRef{ + vmKey: key, + driverID: s.driverID, + vmName: s.vmName, + startedAt: s.startedAt, + unboundSince: s.unboundSince, + }) + } + } + a.sessionMu.Unlock() + if len(unbound) == 0 { + return false + } + + now := time.Now() + a.mu.Lock() + var activeTransitions map[string]string + if len(a.transitions) > 0 { + activeTransitions = make(map[string]string, len(a.transitions)) + for k, v := range a.transitions { + activeTransitions[k] = v + } + } + var cachedStates map[string]string + if len(a.lastVMs) > 0 { + cachedStates = make(map[string]string, len(a.lastVMs)) + for _, vm := range a.lastVMs { + cachedStates[vmKeyForDriver(vm.DriverID, vm.Name)] = vm.State + } + } + a.mu.Unlock() + + for _, u := range unbound { + if tr := activeTransitions[u.vmKey]; tr == "starting" || tr == "resuming" { + return true + } + since := u.unboundSince + if since.IsZero() { + since = u.startedAt + } + state, known := cachedStates[u.vmKey] + if !known { + if now.Sub(since) < sessionDiscoverGraceWindow { + return true + } + continue + } + if state == "running" && now.Sub(since) < sessionDiscoverGraceWindow { + return true + } + } + return false +} + +// bindAgentSessionPID immediately attaches a freshly observed live VM PID to an +// active Agent session so the overlay appears without waiting for the next poll. +func (a *App) bindAgentSessionPID(vmKey string, pid uint32) { + if vmKey == "" || pid == 0 { + return + } + a.sessionMu.Lock() + sess := a.agentSessions[vmKey] + if sess == nil || sess.lastOverlayPID == pid { + a.sessionMu.Unlock() + return + } + sess.lastOverlayPID = pid + sess.unboundSince = time.Time{} + a.sessionMu.Unlock() + a.refreshAgentSessionVisualsWithPID(vmKey, pid) + a.syncTakeoverTargets() +} + +// refreshActiveAgentSessionAfterStart refreshes overlay PID binding and input +// lock targets immediately after a VM starts, resumes, or restarts. +func (a *App) refreshActiveAgentSessionAfterStart(vmKey string) { + if !a.hasActiveAgentSession(vmKey) { + return + } + a.refreshAgentSessionVisuals(vmKey) + a.syncTakeoverTargets() +} + +// rebindAgentSessionAfterRestart clears any stale pre-restart PID cache on the +// active session, probes the freshly launched VM PID, and rebinds the overlay +// and input lock to the new VM window immediately. +func (a *App) rebindAgentSessionAfterRestart(vmKey string) uint32 { + a.sessionMu.Lock() + sess := a.agentSessions[vmKey] + if sess == nil { + a.sessionMu.Unlock() + return 0 + } + sess.lastOverlayPID = 0 + sess.unboundSince = time.Now() + sess.lastPIDProbeAt = time.Time{} + driverID := sess.driverID + vmName := sess.vmName + a.sessionMu.Unlock() + + pid, _ := a.probeFreshVMPID(vmKey, driverID, vmName) + if pid > 0 { + a.bindAgentSessionPID(vmKey, pid) + return pid + } + a.refreshActiveAgentSessionAfterStart(vmKey) + return 0 +} + +func (a *App) endAgentSession(mgr *plugin.Manager, pluginID, vmKey, reason string) { + a.sessionMu.Lock() + sess := a.agentSessions[vmKey] + if sess == nil || (pluginID != "" && sess.pluginID != pluginID) { + a.sessionMu.Unlock() + return + } + delete(a.agentSessions, vmKey) + completed := strings.EqualFold(strings.TrimSpace(sess.status), "completed") + a.sessionMu.Unlock() + + sess.cancel() + if sess.ephemeralGrant { + a.revokeEphemeralVMAccess(sess.pluginID, vmKey) + } + if mgr == nil { + a.mu.Lock() + mgr = a.pluginMgr + a.mu.Unlock() + } + if mgr != nil && sess.secretSetting != "" && (!completed || !sess.saveUnlockCredential) { + _ = mgr.SetSettings(sess.pluginID, vmKey, map[string]any{sess.secretSetting: ""}) + } + if reason == "confirmation_denied" || reason == "permission_denied" { + a.revokeApprovedProtectedPhaseForPluginVM(sess.pluginID, vmKey, reason) + } else { + a.revokeProtectedPhaseForPluginVM(sess.pluginID, vmKey, reason) + } + handOffToGuide := a.prepareInstallGuideRestoreAfterSession(sess, completed) + + showCompleted := false + removeOverlay := false + a.sessionMu.Lock() + if a.agentSessions[vmKey] == nil { + if completed && !handOffToGuide { + if a.completedOverlays == nil { + a.completedOverlays = map[string]completedOverlayEntry{} + } + a.completedOverlays[vmKey] = completedOverlayEntry{ + pluginID: sess.pluginID, + driverID: sess.driverID, + vmName: sess.vmName, + pid: sess.lastOverlayPID, + } + showCompleted = true + } else { + delete(a.completedOverlays, vmKey) + removeOverlay = true + } + } + ov := a.sessionOverlay + a.sessionMu.Unlock() + + if showCompleted { + a.showCompletedSessionOverlay(sess) + } else if removeOverlay && ov != nil { + ov.Remove(vmKey) + } + if mgr != nil && mgr.Broker() != nil { + mgr.Broker().Audit(sess.pluginID, "SESSION_END", vmKey+" "+reason) + } + a.syncTakeoverTargets() + if handOffToGuide || isMacOSDriverID(sess.driverID) { + a.wakePoll() + } + a.emitStateChangedEvent() +} + +func (a *App) isCompletedOverlay(vmKey string) bool { + a.sessionMu.Lock() + defer a.sessionMu.Unlock() + _, ok := a.completedOverlays[vmKey] + return ok +} + +func (a *App) dismissCompletedOverlay(vmKey string) { + if vmKey == "" { + return + } + a.sessionMu.Lock() + delete(a.completedOverlays, vmKey) + ov := a.sessionOverlay + a.sessionMu.Unlock() + if ov != nil { + ov.Remove(vmKey) + } +} + +func (a *App) dismissCompletedOverlayByUser(vmKey string) { + if vmKey == "" { + return + } + a.sessionMu.Lock() + ent, had := a.completedOverlays[vmKey] + delete(a.completedOverlays, vmKey) + ov := a.sessionOverlay + a.sessionMu.Unlock() + if ov != nil { + ov.Remove(vmKey) + } + if had && ent.vmName != "" && isMacOSDriverID(ent.driverID) { + a.markInstallGuideRecheck(ent.vmName) + a.wakePoll() + } +} + +func (a *App) completedSessionOverlayState(loc i18n.Locale, sess *agentSession, pid uint32, dark bool) sessionoverlay.State { + title := strings.TrimSpace(sess.pluginName) + if title == "" { + title = i18n.T(loc, "agent.session.completed_title") + } + statusLine := strings.TrimSpace(sess.message) + if statusLine == "" { + statusLine = i18n.T(loc, "agent.session.completed_status") + } + return sessionoverlay.State{ + VMKey: sess.vmKey, + PID: pid, + Locale: string(loc), + Title: title, + StepBadge: i18n.T(loc, "agent.session.step_badge"), + StepText: i18n.T(loc, "agent.session.stage.completed"), + StatusLine: statusLine, + Completed: true, + CanPause: false, + CanResume: false, + CloseLabel: i18n.T(loc, "agent.session.close"), + CollapseLabel: i18n.T(loc, "agent.session.collapse"), + InputLocked: false, + Dark: dark, + } +} + +func (a *App) showCompletedSessionOverlay(sess *agentSession) { + if sess == nil { + return + } + a.mu.Lock() + hasWindow := a.ctx != nil + dark := a.themeMode != "light" + a.mu.Unlock() + if !hasWindow { + return + } + pid := sess.lastOverlayPID + if polled, ok := a.polledVMForDriver(sess.driverID, sess.vmName); ok { + if polled.State == "running" && polled.PID != nil && *polled.PID > 0 { + pid = uint32(*polled.PID) + } else if polled.State == "stopped" || polled.State == "suspended" { + pid = 0 + } + } + if pid == 0 { + a.dismissCompletedOverlay(sess.vmKey) + return + } + a.sessionMu.Lock() + if ent, ok := a.completedOverlays[sess.vmKey]; ok { + ent.pid = pid + a.completedOverlays[sess.vmKey] = ent + } + a.sessionMu.Unlock() + + loc := a.computerUseLocale() + if ov := a.ensureSessionOverlay(); ov != nil { + ov.Upsert(a.completedSessionOverlayState(loc, sess, pid, dark)) + } +} + +// stopAgentSessionsForInactivePlugins tears down any live Agent/auto-install +// sessions whose owning plugin is no longer active (for example when the user +// disables the plugin mid-run), removing the VM-window overlay, unlocking input, +// and revoking ephemeral and protected-phase grants. +func (a *App) stopAgentSessionsForInactivePlugins(mgr *plugin.Manager) { + if mgr == nil || mgr.Registry() == nil { + return + } + reg := mgr.Registry() + var stale []*agentSession + type staleCompletedItem struct { + key string + ent completedOverlayEntry + } + var staleCompleted []staleCompletedItem + a.sessionMu.Lock() + for key, sess := range a.agentSessions { + if sess != nil && !reg.IsActive(sess.pluginID) { + stale = append(stale, sess) + delete(a.agentSessions, key) + } + } + for key, ent := range a.completedOverlays { + if !reg.IsActive(ent.pluginID) { + staleCompleted = append(staleCompleted, staleCompletedItem{key: key, ent: ent}) + delete(a.completedOverlays, key) + } + } + ov := a.sessionOverlay + a.sessionMu.Unlock() + if len(stale) == 0 && len(staleCompleted) == 0 { + return + } + restoreGuides := false + for _, item := range staleCompleted { + if ov != nil { + ov.Remove(item.key) + } + if item.ent.vmName != "" && isMacOSDriverID(item.ent.driverID) { + a.markInstallGuideRecheck(item.ent.vmName) + restoreGuides = true + } + } + for _, sess := range stale { + sess.cancel() + a.revokeProtectedPhaseForPluginVM(sess.pluginID, sess.vmKey, "plugin_disabled") + if sess.ephemeralGrant { + a.revokeEphemeralVMAccess(sess.pluginID, sess.vmKey) + } + if sess.secretSetting != "" { + _ = mgr.SetSettings(sess.pluginID, sess.vmKey, map[string]any{sess.secretSetting: ""}) + } + if ov != nil { + ov.Remove(sess.vmKey) + } + if mgr.Broker() != nil { + mgr.Broker().Audit(sess.pluginID, "SESSION_END", sess.vmKey+" plugin_disabled") + } + if a.prepareInstallGuideRestoreAfterSession(sess, false) || isMacOSDriverID(sess.driverID) { + restoreGuides = true + } + } + a.syncTakeoverTargets() + if restoreGuides { + a.wakePoll() + } + a.emitStateChangedEvent() +} + +// StopAgentSession immediately cancels the active Agent/auto-install session on +// the VM, revokes protected-phase authorization, notifies the plugin via +// `session/stopped`, and tears down the VM-window overlay. +func (a *App) StopAgentSession(driverID, name string) error { + key := vmKeyForDriver(driverID, name) + a.sessionMu.Lock() + sess := a.agentSessions[key] + if sess != nil { + delete(a.agentSessions, key) + } + completedEnt, hadCompleted := a.completedOverlays[key] + delete(a.completedOverlays, key) + ov := a.sessionOverlay + a.sessionMu.Unlock() + + a.revokeProtectedPhaseForVM(key, "user_stopped") + if ov != nil { + ov.Remove(key) + } + a.syncTakeoverTargets() + + a.mu.Lock() + mgr := a.pluginMgr + a.mu.Unlock() + + restoreGuide := false + if sess != nil { + sess.cancel() + if sess.ephemeralGrant { + a.revokeEphemeralVMAccess(sess.pluginID, key) + } + if mgr != nil { + if sess.secretSetting != "" { + _ = mgr.SetSettings(sess.pluginID, key, map[string]any{sess.secretSetting: ""}) + } + mgr.NotifySidecar(sess.pluginID, "session/stopped", map[string]any{ + "vm": key, + "reason": "user_stopped", + }) + if mgr.Broker() != nil { + mgr.Broker().Audit(sess.pluginID, "SESSION_STOP", key) + } + } + if a.prepareInstallGuideRestoreAfterSession(sess, false) || isMacOSDriverID(sess.driverID) { + restoreGuide = true + } + } else if hadCompleted && completedEnt.vmName != "" && isMacOSDriverID(completedEnt.driverID) { + a.markInstallGuideRecheck(completedEnt.vmName) + restoreGuide = true + } + if restoreGuide { + a.wakePoll() + } + a.emitStateChangedEvent() + return nil +} + +// PauseAgentSession pauses an active Agent/auto-install session on the VM, +// immediately unlocks physical mouse/keyboard input on the VM window, and +// notifies the owning Sidecar (`session/paused`). +func (a *App) PauseAgentSession(driverID, name string) error { + key := vmKeyForDriver(driverID, name) + loc := a.computerUseLocale() + a.sessionMu.Lock() + sess := a.agentSessions[key] + if sess == nil { + a.sessionMu.Unlock() + return nil + } + sess.pausedForUser = true + sess.hostPaused = true + sess.status = "paused_for_user" + sess.message = i18n.T(loc, "agent.session.paused_by_user") + pluginID := sess.pluginID + a.sessionMu.Unlock() + + a.syncTakeoverTargets() + a.mu.Lock() + mgr := a.pluginMgr + a.mu.Unlock() + if mgr != nil { + mgr.NotifySidecar(pluginID, "session/paused", map[string]any{ + "vm": key, + "reason": "user_paused", + }) + if mgr.Broker() != nil { + mgr.Broker().Audit(pluginID, "SESSION_PAUSE", key) + } + } + a.refreshAgentSessionVisuals(key) + a.emitStateChangedEvent() + return nil +} + +// ResumeAgentSession clears a takeover or paused_for_user hold on the VM, +// restores any session input lock, and notifies the owning Sidecar (`session/resumed`). +func (a *App) ResumeAgentSession(driverID, name string) error { + key := vmKeyForDriver(driverID, name) + a.sessionMu.Lock() + sess := a.agentSessions[key] + if sess == nil { + a.sessionMu.Unlock() + return nil + } + sess.takeoverPaused = false + sess.takeoverUntil = time.Time{} + sess.pausedForUser = false + sess.hostPaused = false + if sess.status == "paused_for_user" { + sess.status = "running" + sess.message = "" + } + pluginID := sess.pluginID + a.sessionMu.Unlock() + + a.syncTakeoverTargets() + a.mu.Lock() + mgr := a.pluginMgr + a.mu.Unlock() + if mgr != nil { + mgr.NotifySidecar(pluginID, "session/resumed", map[string]any{"vm": key}) + if mgr.Broker() != nil { + mgr.Broker().Audit(pluginID, "SESSION_RESUME", key) + } + } + a.refreshAgentSessionVisuals(key) + a.emitStateChangedEvent() + return nil +} + +func (a *App) handlePhysicalUserTakeover(vmKey, reason string) { + now := time.Now() + a.mu.Lock() + pauseSec := 5 + if a.cfg != nil { + pauseSec = a.cfg.EffectiveAgentTakeoverPauseSec() + } + mgr := a.pluginMgr + a.mu.Unlock() + + a.sessionMu.Lock() + sess := a.agentSessions[vmKey] + if sess == nil { + a.sessionMu.Unlock() + return + } + manual := pauseSec == 0 || sess.takeoverPolicy == "manual" + wasPaused := sess.takeoverPaused + sess.takeoverPaused = true + if manual { + sess.takeoverUntil = time.Time{} + sess.pausedForUser = true + sess.hostPaused = true + } else { + sess.takeoverUntil = now.Add(time.Duration(pauseSec) * time.Second) + } + pluginID := sess.pluginID + a.sessionMu.Unlock() + + if mgr != nil { + mgr.NotifySidecar(pluginID, "console/userTakeover", map[string]any{ + "vm": vmKey, + "reason": reason, + "manual_resume": manual, + "pause_seconds": pauseSec, + }) + if !wasPaused && mgr.Broker() != nil { + mgr.Broker().Audit(pluginID, "SESSION_TAKEOVER", vmKey+" "+reason) + } + } + a.refreshAgentSessionVisuals(vmKey) + a.emitStateChangedEvent() +} + +func (a *App) checkUserTakeover(vmKey, vmName string) error { + now := time.Now() + a.sessionMu.Lock() + sess := a.agentSessions[vmKey] + if sess == nil { + a.sessionMu.Unlock() + return nil + } + if sess.takeoverPaused { + if !sess.takeoverUntil.IsZero() && !now.Before(sess.takeoverUntil) { + sess.takeoverPaused = false + sess.takeoverUntil = time.Time{} + a.sessionMu.Unlock() + a.refreshAgentSessionVisuals(vmKey) + return nil + } + a.sessionMu.Unlock() + return a.computerUseHostError("user_takeover", "err.computer_use.user_takeover", i18n.Vars{"name": vmName}) + } + if sess.pausedForUser { + a.sessionMu.Unlock() + return a.computerUseHostError("session_paused", "err.computer_use.session_paused", i18n.Vars{"name": vmName}) + } + a.sessionMu.Unlock() + return nil +} + +// withSessionContext derives a call context that cancels immediately when the +// user clicks Stop on the VM's active session. +func (a *App) withSessionContext(ctx context.Context, vmKey string) (context.Context, context.CancelFunc) { + a.sessionMu.Lock() + sess := a.agentSessions[vmKey] + var sctx context.Context + if sess != nil { + sctx = sess.ctx + } + a.sessionMu.Unlock() + if sctx == nil { + return ctx, func() {} + } + derived, cancel := context.WithCancel(ctx) + stop := context.AfterFunc(sctx, cancel) + return derived, func() { + stop() + cancel() + } +} + +func (a *App) hasActiveAgentSession(vmKey string) bool { + a.sessionMu.Lock() + defer a.sessionMu.Unlock() + return a.agentSessions[vmKey] != nil +} + +func (a *App) grantEphemeralVMAccess(pluginID, vmKey string) { + a.sessionMu.Lock() + if a.ephemeralVMAccess == nil { + a.ephemeralVMAccess = map[string]map[string]bool{} + } + if a.ephemeralVMAccess[pluginID] == nil { + a.ephemeralVMAccess[pluginID] = map[string]bool{} + } + a.ephemeralVMAccess[pluginID][vmKey] = true + a.sessionMu.Unlock() +} + +func (a *App) revokeEphemeralVMAccess(pluginID, vmKey string) { + a.sessionMu.Lock() + if m := a.ephemeralVMAccess[pluginID]; m != nil { + delete(m, vmKey) + if len(m) == 0 { + delete(a.ephemeralVMAccess, pluginID) + } + } + a.sessionMu.Unlock() +} + +func (a *App) hasEphemeralVMAccess(pluginID, vmKey string) bool { + a.sessionMu.Lock() + defer a.sessionMu.Unlock() + return a.ephemeralVMAccess != nil && a.ephemeralVMAccess[pluginID] != nil && a.ephemeralVMAccess[pluginID][vmKey] +} + +// activeAgentSessions returns live snapshots of all active remote-control sessions. +func (a *App) activeAgentSessions() []AgentSessionView { + now := time.Now() + a.sessionMu.Lock() + views := make([]AgentSessionView, 0, len(a.agentSessions)) + for _, s := range a.agentSessions { + if s.takeoverPaused && !s.takeoverUntil.IsZero() && !now.Before(s.takeoverUntil) { + s.takeoverPaused = false + s.takeoverUntil = time.Time{} + } + running := s.status == "" || s.status == "running" + inputLocked := s.takeoverPolicy == "lock" && running && !s.pausedForUser && !s.takeoverPaused + v := AgentSessionView{ + VMKey: s.vmKey, + DriverID: s.driverID, + VMName: s.vmName, + PluginID: s.pluginID, + PluginName: s.pluginName, + Label: s.label, + Stage: s.stage, + Status: s.status, + Message: s.message, + TakeoverPolicy: s.takeoverPolicy, + InputLocked: inputLocked, + PausedForUser: s.pausedForUser, + TakeoverPaused: s.takeoverPaused, + TakeoverManualWait: s.takeoverPaused && s.takeoverUntil.IsZero(), + StartedAt: s.startedAt.UTC().Format(time.RFC3339), + } + if s.takeoverPaused && !s.takeoverUntil.IsZero() { + rem := int(s.takeoverUntil.Sub(now).Seconds()) + 1 + if rem < 0 { + rem = 0 + } + v.TakeoverRemainSec = rem + } + views = append(views, v) + } + a.sessionMu.Unlock() + + for i := range views { + if grant, ok := a.lookupProtectedPhaseGrant(views[i].PluginID, views[i].VMKey); ok && grant.isActive(now) { + views[i].Phase = grant.phase + views[i].AuthUntilPhaseExit = grant.untilPhaseExit + views[i].AuthRemainingSec = grant.remainingSeconds(now) + } + } + sort.Slice(views, func(i, j int) bool { return views[i].VMKey < views[j].VMKey }) + return views +} + +// syncAutoInstallSessionProgress mirrors stage/message updates returned by +// autoinstall/status into the live Agent session so the VM overlay always +// reflects the latest step even if the plugin did not emit a separate push. +func (a *App) syncAutoInstallSessionProgress(vmKey, pluginID, stage, message string) { + stage = strings.TrimSpace(stage) + message = strings.TrimSpace(message) + if vmKey == "" || (stage == "" && message == "") { + return + } + changed := false + a.sessionMu.Lock() + sess := a.agentSessions[vmKey] + if sess != nil && (pluginID == "" || sess.pluginID == pluginID) { + if sess.isAutoInstall && sess.autoInstallMode == "recovery_only" && stage == "stage5_setup_assistant" { + stage = "stage5_wait_reboot" + } + if stage != "" && sess.stage != stage { + sess.stage = stage + changed = true + } + if message != "" && !sess.pausedForUser && !sess.takeoverPaused && sess.message != message { + sess.message = message + changed = true + } + } + a.sessionMu.Unlock() + if changed { + a.refreshAgentSessionVisuals(vmKey) + } +} + +func isMachineStageID(s string) bool { + if s == "" { + return false + } + for _, r := range s { + if r > 127 || unicode.IsSpace(r) { + return false + } + } + return strings.ContainsAny(s, "_-.") || strings.HasPrefix(strings.ToLower(s), "stage") || strings.HasPrefix(strings.ToLower(s), "step") +} + +func stageKnownName(loc i18n.Locale, slug string) string { + s := strings.ToLower(strings.Trim(slug, "_-. ")) + switch { + case s == "": + return "" + case strings.Contains(s, "preflight") || strings.Contains(s, "prepare") || strings.Contains(s, "init"): + return i18n.T(loc, "agent.session.stage.preflight") + case strings.Contains(s, "reboot") || strings.Contains(s, "restart"): + return i18n.T(loc, "agent.session.stage.reboot") + case strings.Contains(s, "recovery") || strings.Contains(s, "boot"): + return i18n.T(loc, "agent.session.stage.boot_recovery") + case strings.Contains(s, "offline_terminal") || strings.Contains(s, "terminal"): + return i18n.T(loc, "agent.session.stage.offline_terminal") + case strings.Contains(s, "disk") || strings.Contains(s, "erase") || strings.Contains(s, "format") || strings.Contains(s, "apfs"): + return i18n.T(loc, "agent.session.stage.disk_utility") + case strings.Contains(s, "install_wait"): + return i18n.T(loc, "agent.session.stage.install_wait") + case strings.Contains(s, "finish_install"): + return i18n.T(loc, "agent.session.stage.finish_install") + case strings.Contains(s, "tools") || strings.Contains(s, "post_install") || strings.Contains(s, "guest"): + return i18n.T(loc, "agent.session.stage.guest_tools") + case strings.Contains(s, "reinstall") || strings.Contains(s, "install_macos") || strings.Contains(s, "macos_install") || s == "install": + return i18n.T(loc, "agent.session.stage.install_macos") + case strings.Contains(s, "setup") || strings.Contains(s, "assistant") || strings.Contains(s, "oobe"): + return i18n.T(loc, "agent.session.stage.setup_assistant") + case strings.Contains(s, "account") || strings.Contains(s, "user") || strings.Contains(s, "provision"): + return i18n.T(loc, "agent.session.stage.account") + case strings.Contains(s, "desktop") || strings.Contains(s, "verify"): + return i18n.T(loc, "agent.session.stage.desktop") + case strings.Contains(s, "complete") || strings.Contains(s, "done") || strings.Contains(s, "finish"): + return i18n.T(loc, "agent.session.stage.completed") + default: + return "" + } +} + +func humanizeStageSlug(slug string) string { + parts := strings.FieldsFunc(slug, func(r rune) bool { + return r == '_' || r == '-' || r == '.' + }) + for i, p := range parts { + if len(p) == 0 { + continue + } + lower := strings.ToLower(p) + switch lower { + case "macos": + parts[i] = "macOS" + case "ocr", "apfs", "vm", "ui", "ssh": + parts[i] = strings.ToUpper(lower) + default: + parts[i] = strings.ToUpper(lower[:1]) + lower[1:] + } + } + return strings.Join(parts, " ") +} + +func formatSessionStage(loc i18n.Locale, rawStage string) string { + raw := strings.TrimSpace(rawStage) + if raw == "" { + return "" + } + if !isMachineStageID(raw) { + return raw + } + lower := strings.ToLower(raw) + stepNum := "" + rest := raw + for _, prefix := range []string{"stage", "step"} { + if strings.HasPrefix(lower, prefix) { + tail := raw[len(prefix):] + tail = strings.TrimLeft(tail, "_-.") + digits := 0 + for digits < len(tail) && tail[digits] >= '0' && tail[digits] <= '9' { + digits++ + } + if digits > 0 { + if n, err := strconv.Atoi(tail[:digits]); err == nil { + if n > 0 { + stepNum = strconv.Itoa(n) + } + rest = tail[digits:] + if len(rest) >= 2 && ((rest[0] >= 'a' && rest[0] <= 'z') || (rest[0] >= 'A' && rest[0] <= 'Z')) && + (rest[1] == '_' || rest[1] == '-' || rest[1] == '.') { + rest = rest[1:] + } + rest = strings.TrimLeft(rest, "_-.") + } + } + break + } + } + name := stageKnownName(loc, rest) + if name == "" { + name = humanizeStageSlug(rest) + } + if stepNum != "" && name != "" { + return i18n.M(loc, "agent.session.step_numbered", i18n.Vars{"num": stepNum, "name": name}) + } + if name != "" { + return name + } + return raw +} + +func (a *App) sessionOverlayStep(loc i18n.Locale, view AgentSessionView) string { + if strings.EqualFold(strings.TrimSpace(view.Status), "completed") { + return i18n.T(loc, "agent.session.stage.completed") + } + if step := formatSessionStage(loc, view.Stage); step != "" { + return step + } + if view.Phase == driver.PhaseInstaller || view.Phase == driver.PhaseRecovery { + return i18n.M(loc, "err.computer_use.phase."+view.Phase, nil) + } + if view.PausedForUser || view.TakeoverPaused { + return i18n.T(loc, "agent.session.step_paused") + } + return i18n.T(loc, "agent.session.step_running") +} + +func (a *App) sessionOverlayStatusLine(loc i18n.Locale, view AgentSessionView, stepText string) string { + switch { + case view.TakeoverManualWait: + return i18n.T(loc, "agent.session.takeover_manual") + case view.TakeoverPaused && view.TakeoverRemainSec > 0: + return i18n.M(loc, "agent.session.takeover_countdown", i18n.Vars{"seconds": view.TakeoverRemainSec}) + case view.PausedForUser && view.Message != "": + return view.Message + case view.PausedForUser: + return i18n.T(loc, "agent.session.paused_manual") + case view.InputLocked && view.Message != "": + return i18n.T(loc, "agent.session.locked_prefix") + view.Message + case view.InputLocked: + return i18n.T(loc, "agent.session.locked_status") + case view.Message != "": + return view.Message + case view.PluginName != "" && view.PluginName != stepText: + return view.PluginName + default: + return "" + } +} + +func (a *App) sessionBannerText(loc i18n.Locale, view AgentSessionView) (title, statusLine string) { + if view.Label != "" { + title = view.Label + } else { + title = i18n.M(loc, "agent.session.banner", i18n.Vars{"plugin": view.PluginName}) + } + if view.Phase == driver.PhaseInstaller || view.Phase == driver.PhaseRecovery { + phaseLabel := i18n.M(loc, "err.computer_use.phase."+view.Phase, nil) + if view.AuthUntilPhaseExit { + title = i18n.M(loc, "agent.session.phase_banner", i18n.Vars{"phase": phaseLabel}) + } else if view.AuthRemainingSec > 0 { + mins := (view.AuthRemainingSec + 59) / 60 + title = i18n.M(loc, "agent.session.phase_banner_timer", i18n.Vars{"phase": phaseLabel, "minutes": mins}) + } + } + switch { + case view.TakeoverManualWait: + statusLine = i18n.T(loc, "agent.session.takeover_manual") + case view.TakeoverPaused && view.TakeoverRemainSec > 0: + statusLine = i18n.M(loc, "agent.session.takeover_countdown", i18n.Vars{"seconds": view.TakeoverRemainSec}) + case view.PausedForUser && view.Message != "": + statusLine = view.Message + case view.PausedForUser: + statusLine = i18n.T(loc, "agent.session.paused_manual") + case view.InputLocked && view.Message != "": + statusLine = i18n.T(loc, "agent.session.locked_prefix") + view.Message + case view.InputLocked && view.Stage != "": + statusLine = i18n.T(loc, "agent.session.locked_prefix") + view.Stage + case view.InputLocked: + statusLine = i18n.T(loc, "agent.session.locked_status") + case view.Message != "": + statusLine = view.Message + case view.Stage != "": + statusLine = view.Stage + default: + statusLine = view.PluginName + } + return title, statusLine +} + +func (a *App) ensureSessionOverlay() *sessionoverlay.Manager { + a.sessionMu.Lock() + defer a.sessionMu.Unlock() + if a.sessionOverlay == nil && !a.sessionShuttingDown { + a.sessionOverlay = sessionoverlay.NewManager(sessionoverlay.Callbacks{ + OnStop: func(vmKey string) { + if ref, ok := driver.ParseVMRef(vmKey); ok { + _ = a.StopAgentSession(ref.DriverID, ref.Name) + } else { + _ = a.StopAgentSession("", vmKey) + } + }, + OnPause: func(vmKey string) { + if ref, ok := driver.ParseVMRef(vmKey); ok { + _ = a.PauseAgentSession(ref.DriverID, ref.Name) + } else { + _ = a.PauseAgentSession("", vmKey) + } + }, + OnResume: func(vmKey string) { + if ref, ok := driver.ParseVMRef(vmKey); ok { + _ = a.ResumeAgentSession(ref.DriverID, ref.Name) + } else { + _ = a.ResumeAgentSession("", vmKey) + } + }, + OnDismiss: func(vmKey string) { + a.dismissCompletedOverlayByUser(vmKey) + }, + }) + } + return a.sessionOverlay +} + +func (a *App) refreshAgentSessionVisuals(vmKey string) { + a.refreshAgentSessionVisualsWithPID(vmKey, 0) +} + +func (a *App) probeFreshVMPID(vmKey, driverID, vmName string) (uint32, bool) { + now := time.Now() + a.sessionMu.Lock() + sess := a.agentSessions[vmKey] + if sess == nil || (!sess.lastPIDProbeAt.IsZero() && now.Sub(sess.lastPIDProbeAt) < 300*time.Millisecond) { + a.sessionMu.Unlock() + return 0, false + } + sess.lastPIDProbeAt = now + a.sessionMu.Unlock() + + pctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + vms, err := a.listVMsInternal(pctx) + cancel() + if err != nil { + return 0, false + } + wantDriver := driver.CanonicalDriverID(driverID) + if wantDriver == "" { + wantDriver = driver.BuiltinReimsMacOSDriverID + } + for _, vm := range vms { + if vm.Name == vmName && driver.CanonicalDriverID(vm.DriverID) == wantDriver && vm.State == "running" && vm.PID != nil && *vm.PID > 0 { + a.mu.Lock() + a.lastVMs = append([]driver.VMListItem(nil), vms...) + a.lastVMsAt = time.Now() + a.mu.Unlock() + return uint32(*vm.PID), true + } + } + return 0, true +} + +func (a *App) refreshAgentSessionVisualsWithPID(vmKey string, pidHint uint32) { + a.mu.Lock() + hasWindow := a.ctx != nil + dark := a.themeMode != "light" + a.mu.Unlock() + if !hasWindow { + return + } + var target *AgentSessionView + for _, v := range a.activeAgentSessions() { + if v.VMKey == vmKey { + cp := v + target = &cp + break + } + } + if target == nil { + a.sessionMu.Lock() + ov := a.sessionOverlay + a.sessionMu.Unlock() + if ov != nil && !a.isCompletedOverlay(vmKey) { + ov.Remove(vmKey) + } + return + } + pid := pidHint + vmStopped := false + if pid == 0 { + if polled, ok := a.polledVMForDriver(target.DriverID, target.VMName); ok { + if polled.State == "running" && polled.PID != nil && *polled.PID > 0 { + pid = uint32(*polled.PID) + } else if polled.State == "stopped" || polled.State == "suspended" { + vmStopped = true + } + } + } + probed := false + if pid == 0 { + // Bypass the stale 13s polled cache right after VM start/restart so the + // floating island attaches to the QEMU window immediately. + pid, probed = a.probeFreshVMPID(vmKey, target.DriverID, target.VMName) + } + a.sessionMu.Lock() + if sess := a.agentSessions[vmKey]; sess != nil { + if pid > 0 { + sess.lastOverlayPID = pid + sess.unboundSince = time.Time{} + } else if probed || vmStopped { + if sess.lastOverlayPID != 0 { + sess.unboundSince = time.Now() + } + sess.lastOverlayPID = 0 + } else { + // Probe was rate-limited or transiently failed; preserve any already-bound PID + // so concurrent refreshes cannot clobber a freshly bound live PID back to 0. + pid = sess.lastOverlayPID + } + } + a.sessionMu.Unlock() + + loc := a.computerUseLocale() + completed := strings.EqualFold(strings.TrimSpace(target.Status), "completed") + title, _ := a.sessionBannerText(loc, *target) + if completed { + if strings.TrimSpace(target.PluginName) != "" { + title = strings.TrimSpace(target.PluginName) + } else { + title = i18n.T(loc, "agent.session.completed_title") + } + } + stepText := a.sessionOverlayStep(loc, *target) + status := a.sessionOverlayStatusLine(loc, *target, stepText) + paused := target.PausedForUser || target.TakeoverPaused + if ov := a.ensureSessionOverlay(); ov != nil { + ov.Upsert(sessionoverlay.State{ + VMKey: vmKey, + PID: pid, + Locale: string(loc), + Title: title, + StepBadge: i18n.T(loc, "agent.session.step_badge"), + StepText: stepText, + StatusLine: status, + Completed: completed, + CanPause: !paused && !completed, + PauseLabel: i18n.T(loc, "agent.session.pause"), + CanResume: paused && !completed, + ResumeLabel: i18n.T(loc, "agent.session.resume"), + StopLabel: i18n.T(loc, "agent.session.stop"), + CloseLabel: i18n.T(loc, "agent.session.close"), + CollapseLabel: i18n.T(loc, "agent.session.collapse"), + InputLocked: target.InputLocked && !completed, + Dark: dark, + }) + } +} + +func (a *App) syncTakeoverTargets() { + a.mu.Lock() + hasWindow := a.ctx != nil + a.mu.Unlock() + if !hasWindow { + return + } + sessions := a.activeAgentSessions() + targets := make(map[uint32]host.TakeoverTarget, len(sessions)) + for _, s := range sessions { + var pid uint32 + if polled, ok := a.polledVMForDriver(s.DriverID, s.VMName); ok && polled.State == "running" && polled.PID != nil && *polled.PID > 0 { + pid = uint32(*polled.PID) + } else { + a.sessionMu.Lock() + if live := a.agentSessions[s.VMKey]; live != nil { + pid = live.lastOverlayPID + } + a.sessionMu.Unlock() + } + if pid == 0 { + continue + } + if s.TakeoverPolicy == "lock" { + // Locked sessions only intercept input while actively running; pausing + // removes the PID immediately so the user can interact freely. + if s.InputLocked { + targets[pid] = host.TakeoverTarget{VMKey: s.VMKey, LockInput: true} + } + continue + } + targets[pid] = host.TakeoverTarget{VMKey: s.VMKey, LockInput: false} + } + a.sessionMu.Lock() + if a.sessionShuttingDown { + a.sessionMu.Unlock() + return + } + if a.takeoverMon == nil && len(targets) > 0 { + mon := host.NewTakeoverMonitor(a.handlePhysicalUserTakeover) + mon.SetOnHookError(func(err error) { + a.emitLog("", "[agent] takeover hook error: "+err.Error()) + }) + a.takeoverMon = mon + } + mon := a.takeoverMon + a.sessionMu.Unlock() + if mon != nil { + mon.SetTargetRules(targets) + } +} + +func (a *App) syncAgentSessionsOnPoll() { + a.cleanupStaleCompletedOverlays() + sessions := a.activeAgentSessions() + if len(sessions) == 0 { + return + } + a.syncTakeoverTargets() + for _, s := range sessions { + a.refreshAgentSessionVisuals(s.VMKey) + } +} + +func (a *App) cleanupStaleCompletedOverlays() { + a.sessionMu.Lock() + if len(a.completedOverlays) == 0 { + a.sessionMu.Unlock() + return + } + snapshot := make(map[string]completedOverlayEntry, len(a.completedOverlays)) + for k, v := range a.completedOverlays { + snapshot[k] = v + } + a.sessionMu.Unlock() + + for key, ent := range snapshot { + polled, ok := a.polledVMForDriver(ent.driverID, ent.vmName) + alive := ok && polled.State == "running" && polled.PID != nil && *polled.PID > 0 + if !alive || (ent.pid > 0 && uint32(*polled.PID) != ent.pid) { + a.dismissCompletedOverlay(key) + } + } +} + +func (a *App) closeAgentSessions() { + a.sessionMu.Lock() + a.sessionShuttingDown = true + mon := a.takeoverMon + a.takeoverMon = nil + ov := a.sessionOverlay + a.sessionOverlay = nil + sessions := a.agentSessions + a.agentSessions = nil + a.completedOverlays = nil + a.ephemeralVMAccess = nil + a.sessionMu.Unlock() + for _, s := range sessions { + s.cancel() + } + if mon != nil { + mon.Close() + } + if ov != nil { + ov.Close() + } +} + +func (a *App) emitStateChangedEvent() { + a.emitStateChanged() +} + +func (a *App) effectiveVMPhase(vm driver.VMInfo) string { + if vm.Phase == "" { + if pr, ok := a.driverFor(vm).(driver.PhaseReporter); ok { + pctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + if phase, err := pr.Phase(pctx, vm.Name); err == nil { + vm.Phase = phase + } + cancel() + } + } + return computerUseVMPhase(vm) +} diff --git a/internal/app/agent_session_lock_test.go b/internal/app/agent_session_lock_test.go new file mode 100644 index 0000000..013fefa --- /dev/null +++ b/internal/app/agent_session_lock_test.go @@ -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") + } +} diff --git a/internal/app/app.go b/internal/app/app.go index d907f57..39cf718 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -17,6 +17,7 @@ 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" @@ -59,7 +60,9 @@ type AppState struct { 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"` + 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). @@ -159,6 +162,33 @@ type App struct { // 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 @@ -296,6 +326,8 @@ func (a *App) shutdown(ctx context.Context) { } tasks.cancelAll() a.cancelPendingElevations() + a.cancelPendingConfirmations() + a.closeAgentSessions() stopAllVMMonitors() a.stopPluginControlServer() a.mu.Lock() @@ -382,7 +414,7 @@ func (a *App) GetState() AppState { } 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 @@ -429,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, @@ -468,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 { @@ -517,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 @@ -531,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), @@ -592,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()) @@ -608,6 +669,8 @@ func (a *App) resetDataRootCaches() { a.lastVMListErr = nil a.diskPaths = make(map[string]cachedDiskPath) a.procSamples = make(map[string]host.ProcessSample) + a.guideRecheckVMs = nil + a.pendingGuideHandoffs = nil a.mu.Unlock() a.hostAPISvc().ResetPluginFiles() cancelPluginTasks("") diff --git a/internal/app/autoinstall_flow.go b/internal/app/autoinstall_flow.go new file mode 100644 index 0000000..3b6d32a --- /dev/null +++ b/internal/app/autoinstall_flow.go @@ -0,0 +1,571 @@ +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 +} + +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) { + 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 + } + 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) + a.syncAutoInstallSessionProgress(vmKeyStr, provider.PluginID, stage, msg) + } + return resp, err +} + +// 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 + } + vmKeyStr := vmKeyForDriver(driverID, vmName) + 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) + var resumeVM driver.VMInfo + if !hadSession { + var vErr error + resumeVM, vErr = a.resolveVMInfo(driverID, vmName) + if vErr != nil { + resumeVM = driver.VMInfo{ + DriverID: driver.CanonicalDriverID(driverID), + Name: strings.TrimSpace(vmName), + } + if resumeVM.DriverID == "" { + resumeVM.DriverID = driver.BuiltinReimsMacOSDriverID + } + } + 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 +} diff --git a/internal/app/autoinstall_flow_test.go b/internal/app/autoinstall_flow_test.go new file mode 100644 index 0000000..2d09375 --- /dev/null +++ b/internal/app/autoinstall_flow_test.go @@ -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") + } +} diff --git a/internal/app/computer_use_host.go b/internal/app/computer_use_host.go index 2b38450..2be8625 100644 --- a/internal/app/computer_use_host.go +++ b/internal/app/computer_use_host.go @@ -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" @@ -50,10 +52,13 @@ func (a *App) computerUseHostHandlers(mgr *plugin.Manager, pluginID string) map[ return map[string]plugin.RPCRequestHandler{ "host/vm.list": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.list", a.handleComputerUseVMList), "host/vm.get": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.get", a.handleComputerUseVMGet), + "host/vm.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), @@ -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,200 @@ 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 + } + 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 + } + phase := a.effectiveVMPhase(vm) + 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 { @@ -362,14 +568,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 +598,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 +617,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,16 +659,16 @@ 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 { @@ -814,45 +1040,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 } @@ -868,7 +1150,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 } @@ -891,10 +1178,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. @@ -910,7 +1199,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 { @@ -930,12 +1219,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 @@ -959,7 +1250,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 } } @@ -978,7 +1269,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 } @@ -1008,7 +1299,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 } @@ -1018,6 +1309,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 diff --git a/internal/app/confirm_flow.go b/internal/app/confirm_flow.go new file mode 100644 index 0000000..0372a1e --- /dev/null +++ b/internal/app/confirm_flow.go @@ -0,0 +1,706 @@ +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) + if phase == driver.PhaseInstaller || phase == driver.PhaseRecovery { + kind = "protected_phase" + req.AllowDurationChoice = true + if req.DefaultDurationMin <= 0 { + req.DefaultDurationMin = 30 + } + } + res, err := a.requestHostConfirm(ctx, broker, mgr.Registry(), pluginID, 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, + }) + 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) { + 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 == driver.PhaseNormal { + 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 +} diff --git a/internal/app/console_router_test.go b/internal/app/console_router_test.go index 9cff02a..d69834a 100644 --- a/internal/app/console_router_test.go +++ b/internal/app/console_router_test.go @@ -202,7 +202,7 @@ func TestAgentCallsOnADriverConsoleVMAskForConfirmationInProtectedPhases(t *test const plugin = "reims.agent" a.markComputerUseOwnedVM(plugin, ct.ref.Key(), true) // grants access without a plugin manager - vm, route, err := a.resolveComputerUseVM(nil, plugin, ct.ref.Key()) + vm, route, err := a.resolveComputerUseVM(context.Background(), nil, plugin, ct.ref.Key(), false) if err != nil || route.kind != consoleRouteDriver || vm.Name != "dev" { t.Fatalf("a normal-phase driver console VM = %+v, %+v, %v", vm.Name, route.kind, err) } @@ -210,7 +210,7 @@ func TestAgentCallsOnADriverConsoleVMAskForConfirmationInProtectedPhases(t *test if err := os.WriteFile(filepath.Join(ct.vmRoot, "dev", "phase"), []byte(phase), 0o644); err != nil { t.Fatal(err) } - if _, _, err := a.resolveComputerUseVM(nil, plugin, ct.ref.Key()); err == nil || !strings.Contains(err.Error(), "confirmation_required") { + if _, _, err := a.resolveComputerUseVM(context.Background(), nil, plugin, ct.ref.Key(), false); err == nil || !strings.Contains(err.Error(), "confirmation_required") { t.Fatalf("phase %s: err = %v, want confirmation_required", phase, err) } } @@ -218,7 +218,7 @@ func TestAgentCallsOnADriverConsoleVMAskForConfirmationInProtectedPhases(t *test if err := os.WriteFile(filepath.Join(ct.vmRoot, "dev", "phase"), []byte("bogus"), 0o644); err != nil { t.Fatal(err) } - if _, _, err := a.resolveComputerUseVM(nil, plugin, ct.ref.Key()); err == nil { + if _, _, err := a.resolveComputerUseVM(context.Background(), nil, plugin, ct.ref.Key(), false); err == nil { t.Fatal("a VM with an unreadable phase was treated as normal") } } diff --git a/internal/app/create_flow.go b/internal/app/create_flow.go index b92fe2b..64e9cd3 100644 --- a/internal/app/create_flow.go +++ b/internal/app/create_flow.go @@ -10,6 +10,7 @@ import ( "time" "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/i18n" "github.com/Nwflower/reims-go/internal/macos/installer" @@ -310,3 +311,106 @@ func (a *App) prepareCreateNetwork(ctx context.Context, c networkControlClient, } return ctx.Err() } + +// ProvisionRequest carries user-supplied first-boot macOS provisioning options. +// Password is only used in memory to derive SALTED-SHA512-PBKDF2 ShadowHashData +// and is never written to disk, vm.toml, or logs. +type ProvisionRequest struct { + FullName string `json:"full_name"` + AccountName string `json:"account_name"` + Password string `json:"password"` + Appearance string `json:"appearance,omitempty"` + SLAAccepted bool `json:"sla_accepted"` + InstallGuestTools *bool `json:"install_guest_tools,omitempty"` +} + +// PrepareVMProvision builds the per-VM read-only REIMSPROV image inside the +// macOS VM directory so offline installation creates the local admin account +// (hash-only), skips Setup Assistant & Keyboard Setup Assistant, and optionally +// stages Guest Tools for first login. +func (a *App) PrepareVMProvision(name string, req ProvisionRequest) error { + password := req.Password + req.Password = "" + defer func() { password = "" }() + + if err := a.requireMacOSEnabled(); err != nil { + return err + } + c, err := a.client() + if err != nil { + return err + } + det, err := c.Show(a.baseCtx(), name) + if err != nil { + return err + } + if strings.TrimSpace(det.Directory) == "" { + return fmt.Errorf("VM %q directory is unavailable", name) + } + req.Password = password + return a.prepareVMProvisionForDir(det.Name, det.Directory, req) +} + +func (a *App) hasVMProvisionDir(vmDir string) bool { + return installer.HasProvisionImage(vmDir) +} + +func (a *App) hasProvisionReadyMarker(vmDir string) bool { + return installer.HasProvisionReadyMarker(vmDir) +} + +func (a *App) writeProvisionReadyMarker(vmDir string) { + installer.WriteProvisionReadyMarker(vmDir) +} + +func (a *App) prepareVMProvisionForDir(vmName, vmDir string, req ProvisionRequest) error { + password := req.Password + req.Password = "" + defer func() { password = "" }() + + cfg := installer.ProvisionConfig{ + FullName: req.FullName, + AccountName: req.AccountName, + Password: password, + Appearance: req.Appearance, + SLAAccepted: req.SLAAccepted, + } + if err := installer.ValidateProvisionConfig(&cfg); err != nil { + return err + } + + installTools := req.InstallGuestTools == nil || *req.InstallGuestTools + if installTools { + if srv, port, gerr := a.ensureGuestToolsBridge(); gerr == nil && port > 0 { + unlock := a.lockGuestToolsVM(vmName) + gtCfg, cfgErr := guesttools.LoadOrCreateVMConfig(vmDir, vmName, a.vmSharedDir(vmName), port) + if cfgErr == nil && srv != nil { + validated, _ := a.validatedShareConfig(gtCfg) + srv.RegisterVM(validated) + } + unlock() + if cfgErr == nil { + for _, pf := range guesttools.ToolsProvisionFiles(gtCfg) { + cfg.GuestTools = append(cfg.GuestTools, installer.ProvisionGuestToolFile{ + Name: pf.Name, + Mode: pf.Mode, + Data: pf.Data, + }) + } + } else { + a.emitVMLog(vmName, "Warning: could not stage Guest Tools in REIMSPROV: "+cfgErr.Error()) + } + } else if gerr != nil { + a.emitVMLog(vmName, "Warning: skipped Guest Tools in REIMSPROV because Guest Tools bridge is unavailable: "+gerr.Error()) + } else { + a.emitVMLog(vmName, "Warning: skipped Guest Tools in REIMSPROV because Guest Tools bridge port is unavailable.") + } + } + + if _, err := installer.BuildProvisionDiskImage(vmDir, cfg); err != nil { + return err + } + a.emitVMLog(vmName, "Prepared offline macOS provisioning disk (REIMSPROV) for "+vmName+".") + a.emitStateChanged() + return nil +} diff --git a/internal/app/download_host_flow.go b/internal/app/download_host_flow.go index 543ddba..895f24d 100644 --- a/internal/app/download_host_flow.go +++ b/internal/app/download_host_flow.go @@ -9,6 +9,7 @@ import ( "io" "net" "net/http" + "net/url" "os" "path/filepath" "strings" @@ -18,6 +19,7 @@ import ( "github.com/Nwflower/reims-go/internal/fetch" "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" "github.com/Nwflower/reims-go/internal/netproxy" "github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/pkg/pluginproto" @@ -51,7 +53,7 @@ func (a *App) downloadHostHandlers(mgr *plugin.Manager, pluginID string) map[str } broker := mgr.Broker() return map[string]plugin.RPCRequestHandler{ - "host/download.start": a.hostAPISvc().hostMethod(mgr, pluginID, "host/download.start", func(_ context.Context, raw json.RawMessage) (any, error) { + "host/download.start": a.hostAPISvc().hostMethod(mgr, pluginID, "host/download.start", func(ctx context.Context, raw json.RawMessage) (any, error) { a.mu.Lock() dataRoot := "" if a.cfg != nil { @@ -60,7 +62,7 @@ func (a *App) downloadHostHandlers(mgr *plugin.Manager, pluginID string) map[str a.mu.Unlock() roots := downloadRoots(mgr, pluginID, dataRoot) notify := func(method string, params any) { mgr.NotifySidecar(pluginID, method, params) } - return a.startPluginDownload(mgr, broker, notify, pluginID, roots, raw) + return a.startPluginDownload(ctx, mgr, broker, mgr.Registry(), notify, pluginID, roots, raw) }), "host/download.cancel": a.hostAPISvc().hostMethod(mgr, pluginID, "host/download.cancel", func(_ context.Context, raw json.RawMessage) (any, error) { return cancelPluginDownload(mgr, pluginID, raw) @@ -127,13 +129,27 @@ func rejectInternalHost(host string) error { } // safeDownloadClient follows at most ten redirects, never from HTTPS to plain -// HTTP, and, unless the first URL was loopback itself, never to an internal -// address. -func safeDownloadClient(initial string) *http.Client { - client := netproxy.NewClient() +// HTTP, and, unless allowLoopbackInternal is true and the first URL was +// loopback, never to an internal address. connectTimeout > 0 tightens +// dial/TLS/header timeouts for fast mirror failover. +func safeDownloadClient(initial string, connectTimeout time.Duration, allowLoopbackInternal bool) *http.Client { + tr := netproxy.NewTransport() + if connectTimeout > 0 { + tr.DialContext = (&net.Dialer{ + Timeout: connectTimeout, + KeepAlive: 30 * time.Second, + }).DialContext + tr.TLSHandshakeTimeout = connectTimeout + if connectTimeout < tr.ResponseHeaderTimeout { + tr.ResponseHeaderTimeout = connectTimeout * 2 + } + } + client := &http.Client{Transport: tr} allowInternal := false - if u, err := parseURLHost(initial); err == nil { - allowInternal = plugin.IsLoopbackHost(u) + if allowLoopbackInternal { + if u, err := parseURLHost(initial); err == nil { + allowInternal = plugin.IsLoopbackHost(u) + } } client.CheckRedirect = func(req *http.Request, via []*http.Request) error { if len(via) >= downloadMaxRedirects { @@ -212,22 +228,83 @@ type downloadEvent struct { // startPluginDownload validates a download request and runs it in the // background as a task. It returns the download ID at once. -func (a *App) startPluginDownload(kernel hostMethodHost, broker *plugin.Broker, notify downloadNotifier, pluginID string, roots []string, raw json.RawMessage) (any, error) { +func (a *App) startPluginDownload(reqCtx context.Context, kernel hostMethodHost, broker *plugin.Broker, reg *plugin.Registry, notify downloadNotifier, pluginID string, roots []string, raw json.RawMessage) (any, error) { req, err := decodeHostParams[pluginproto.DownloadParams](kernel, pluginID, "host/download.start", raw) if err != nil { return nil, err } + want := strings.ToLower(strings.TrimSpace(req.SHA256)) + if want != "" && !isHex64(want) { + return nil, errors.New("sha256 must be 64 hex digits") + } + usedCustomMirror := false if err := broker.AuthorizeNetOrigin(pluginID, req.URL); err != nil { - return nil, err + if !req.AllowCustomMirror || !errors.Is(err, plugin.ErrNetOriginNotDeclared) { + return nil, err + } + if want == "" { + return nil, errors.New("custom mirror downloads require a pinned sha256 digest") + } + parsed, parseErr := url.Parse(strings.TrimSpace(req.URL)) + if parseErr != nil || parsed.Hostname() == "" || (parsed.Scheme != "https" && !plugin.IsLoopbackHost(parsed.Hostname())) { + return nil, errors.New("custom mirror URL must use HTTPS") + } + if parsed.User != nil { + broker.Audit(pluginID, "DENY", "custom mirror URL with user info") + return nil, errors.New("URLs with user info are not allowed") + } + if !plugin.IsLoopbackHost(parsed.Hostname()) { + if hostErr := rejectInternalHost(parsed.Hostname()); hostErr != nil { + return nil, hostErr + } + } + origin := parsed.Scheme + "://" + parsed.Host + loc := a.computerUseLocale() + confirmRes, confirmErr := a.requestHostConfirm(reqCtx, broker, reg, pluginID, ConfirmPrompt{ + Kind: "custom_mirror", + Origin: origin, + Title: i18n.T(loc, "confirm.mirror.title"), + Message: i18n.M(loc, "confirm.mirror.message", i18n.Vars{"origin": origin}), + ConfirmLabel: i18n.T(loc, "confirm.mirror.allow"), + CancelLabel: i18n.T(loc, "confirm.phase.deny"), + Danger: true, + }) + if confirmErr != nil { + return nil, confirmErr + } + if !confirmRes.Approved { + broker.Audit(pluginID, "DOWNLOAD_MIRROR_DENIED", origin) + return nil, errors.New("confirmation_denied: user declined the custom download mirror") + } + broker.Audit(pluginID, "DOWNLOAD_MIRROR_APPROVED", origin) + usedCustomMirror = true } if strings.TrimSpace(req.SHA256URL) != "" { if err := broker.AuthorizeNetOrigin(pluginID, req.SHA256URL); err != nil { return nil, err } } - want := strings.ToLower(strings.TrimSpace(req.SHA256)) - if want != "" && !isHex64(want) { - return nil, errors.New("sha256 must be 64 hex digits") + connectTimeout := time.Duration(0) + if req.ConnectTimeoutMS > 0 { + ms := req.ConnectTimeoutMS + if ms < 2000 { + ms = 2000 + } + if ms > 30000 { + ms = 30000 + } + connectTimeout = time.Duration(ms) * time.Millisecond + } + stallTimeout := downloadStall + if req.StallTimeoutMS > 0 { + ms := req.StallTimeoutMS + if ms < 5000 { + ms = 5000 + } + if ms > 120000 { + ms = 120000 + } + stallTimeout = time.Duration(ms) * time.Millisecond } if want == "" && strings.TrimSpace(req.SHA256URL) == "" { return nil, errors.New("sha256 or sha256_url is required") @@ -270,7 +347,9 @@ func (a *App) startPluginDownload(kernel hostMethodHost, broker *plugin.Broker, pluginDownloads.mu.Unlock() go func() { - client := safeDownloadClient(req.URL) + // Undeclared custom mirrors must never gain internal/LAN redirect + // privileges even if the initial user-confirmed URL was loopback. + client := safeDownloadClient(req.URL, connectTimeout, !usedCustomMirror) var lastNotify atomic.Int64 progress := func(done, total int64) { percent := -1.0 @@ -289,7 +368,7 @@ func (a *App) startPluginDownload(kernel hostMethodHost, broker *plugin.Broker, } if err == nil { _, err = fetch.ResumeDirect(ctx, client, req.URL, dest, req.Size, want, progress, - fetch.ResumeOptions{MaxBytes: downloadMaxBytes, StallTimeout: downloadStall}) + fetch.ResumeOptions{MaxBytes: downloadMaxBytes, StallTimeout: stallTimeout}) } pluginDownloads.mu.Lock() delete(pluginDownloads.m, id) diff --git a/internal/app/download_host_test.go b/internal/app/download_host_test.go index cefeab4..53ae5a5 100644 --- a/internal/app/download_host_test.go +++ b/internal/app/download_host_test.go @@ -1,6 +1,7 @@ package app import ( + "context" "crypto/sha256" "encoding/hex" "encoding/json" @@ -61,7 +62,7 @@ func (e *downloadTestEnv) notify(method string, params any) { func (e *downloadTestEnv) start(t *testing.T, pluginID string, req map[string]any) (string, error) { t.Helper() raw, _ := json.Marshal(req) - res, err := e.app.startPluginDownload(nil, e.h.Broker, e.notify, pluginID, e.roots, raw) + res, err := e.app.startPluginDownload(context.Background(), nil, e.h.Broker, e.h.Registry, e.notify, pluginID, e.roots, raw) if err != nil { return "", err } @@ -225,7 +226,7 @@ func TestHostDownloadCancelIsPerPlugin(t *testing.T) { } func TestDownloadRedirectsNeverDowngradeOrReachInternalHosts(t *testing.T) { - client := safeDownloadClient("https://downloads.example.com/file") + client := safeDownloadClient("https://downloads.example.com/file", 0, true) req := func(raw string) *http.Request { u, _ := url.Parse(raw) return &http.Request{URL: u} @@ -256,10 +257,21 @@ func TestDownloadRedirectsNeverDowngradeOrReachInternalHosts(t *testing.T) { t.Error("an eleventh redirect was allowed") } // A loopback origin the plugin declared may redirect within loopback. - local := safeDownloadClient("http://127.0.0.1:1/f") + local := safeDownloadClient("http://127.0.0.1:1/f", 0, true) if err := local.CheckRedirect(req("http://127.0.0.1:1/g"), []*http.Request{req("http://127.0.0.1:1/f")}); err != nil { t.Errorf("a loopback redirect from a loopback origin was refused: %v", err) } + // An undeclared custom mirror confirmed on loopback must NOT redirect to internal/private hosts. + customLocal := safeDownloadClient("http://127.0.0.1:1/f", 0, false) + for name, target := range map[string]string{ + "private LAN": "http://192.168.1.1/secret", + "link local": "http://169.254.169.254/latest/meta-data", + "loopback": "http://127.0.0.1:9999/other", + } { + if err := customLocal.CheckRedirect(req(target), []*http.Request{req("http://127.0.0.1:1/f")}); err == nil { + t.Errorf("custom mirror loopback redirect to %s (%s) must be rejected", name, target) + } + } } func TestHasRunningDownloadFollowsPluginDownloads(t *testing.T) { diff --git a/internal/app/host_api.go b/internal/app/host_api.go index 91dd060..1267898 100644 --- a/internal/app/host_api.go +++ b/internal/app/host_api.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "strings" "github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/pkg/pluginproto" @@ -49,7 +50,7 @@ func authorizeHostMethod(host hostMethodHost, pluginID, method string) error { // until it is updated, while a new plugin learns about a typo at once. func strictHostParams(host hostMethodHost, pluginID, method string) bool { spec, ok := pluginproto.Lookup(method) - if !ok || !spec.StrictParams || host == nil { + if !ok || !spec.StrictParams || host == nil || host.Registry() == nil { return false } manifest, found := host.Registry().ManifestOf(pluginID) @@ -94,8 +95,23 @@ func (h *HostAPIService) hostMethod(host hostMethodHost, pluginID, method string } // hostVMMethod wraps a handler that needs the manager and the calling plugin. +// When permission authorization fails (outside transient rate limits), active +// remote-control sessions for that plugin are aborted immediately. func (h *HostAPIService) hostVMMethod(mgr *plugin.Manager, pluginID, method string, run computerUseVMHandler) plugin.RPCRequestHandler { - return h.hostMethod(mgr, pluginID, method, func(ctx context.Context, raw json.RawMessage) (any, error) { - return run(ctx, raw, mgr, pluginID) - }) + return func(ctx context.Context, raw json.RawMessage) (any, error) { + if err := authorizeHostMethod(mgr, pluginID, method); err != nil { + if h.app != nil && !strings.Contains(strings.ToLower(err.Error()), "rate limit") { + h.app.abortAgentSessionsForPluginPermissionDenial(mgr, pluginID, parseVMRefFromRaw(raw), "permission_denied", method == "host/session.begin") + } + return nil, err + } + result, err := run(ctx, raw, mgr, pluginID) + broker := mgr.Broker() + if err != nil { + broker.Audit(pluginID, "HOST_API_ERROR", method) + return nil, err + } + broker.Audit(pluginID, "HOST_API", method) + return result, nil + } } diff --git a/internal/app/host_handlers.go b/internal/app/host_handlers.go index b38d68b..413013a 100644 --- a/internal/app/host_handlers.go +++ b/internal/app/host_handlers.go @@ -8,6 +8,8 @@ func (h *HostAPIService) Handlers(mgr *plugin.Manager, pluginID string) map[stri out := map[string]plugin.RPCRequestHandler{} for _, set := range []map[string]plugin.RPCRequestHandler{ h.app.computerUseHostHandlers(mgr, pluginID), + h.app.confirmHostHandlers(mgr, pluginID), + h.app.sessionHostHandlers(mgr, pluginID), h.app.secretHostHandlers(mgr, pluginID), h.app.downloadHostHandlers(mgr, pluginID), h.elevateHostHandlers(mgr, pluginID), diff --git a/internal/app/install_flow.go b/internal/app/install_flow.go index 1eaafda..15d00f8 100644 --- a/internal/app/install_flow.go +++ b/internal/app/install_flow.go @@ -26,8 +26,7 @@ func isRecoveryModeActive(d reims.VMDetail) bool { } func isRecoveryMarkerActive(vmDir string) bool { - m := startprep.ReadRecoveryMarker(vmDir) - return m == "on" || m == "want" + return startprep.IsRecoveryMarkerActive(vmDir) } func (a *App) pickCachedRecoveryInstaller() (string, error) { @@ -260,6 +259,44 @@ func (a *App) DownloadAndAttachOnlineRecovery(name, version string) (string, err return id, nil } +// applyFinishInstallResult mirrors driver finish_install deferred changes into +// App.pendingChanges, clears any stale provision-ready milestone, and records +// recovery-exit and wipe-warning logs consistently for GUI, CLI, and Host API. +func (a *App) applyFinishInstallResult(driverID, name string, result map[string]any) { + running, _ := result["running"].(bool) + if running { + var diffs []PendingChange + if value, _ := result["installer_ejected"].(bool); value { + diffs = append(diffs, PendingChange{Field: "installer", From: "attached", To: "ejected"}) + } + if value, _ := result["network_enabled"].(bool); value { + diffs = append(diffs, PendingChange{Field: "network", From: "off", To: "on"}) + } + if value, _ := result["upgraded_nvme"].(bool); value { + from, _ := result["disk_controller_from"].(string) + if from == "" { + from = "ahci" + } + diffs = append(diffs, PendingChange{Field: "disk_controller", From: from, To: "nvme"}) + } + if value, _ := result["recovery_pending"].(bool); value { + diffs = append(diffs, PendingChange{Field: "recovery", From: "on", To: "off"}) + } + if len(diffs) > 0 { + a.mu.Lock() + a.pendingChanges[vmKeyForDriver(driverID, name)] = append(a.pendingChanges[vmKeyForDriver(driverID, name)], diffs...) + a.mu.Unlock() + } + } + if wiped, ok := result["provision_wiped"].(bool); ok && !wiped { + if detail, _ := result["provision_wipe_error"].(string); detail != "" { + a.emitVMLog(name, "Warning: could not remove offline provisioning disk (REIMSPROV) while running; scheduled wipe for next start: "+detail) + } + } + a.clearTelemetryMilestone(vmKeyForDriver(driverID, name), "serial:provision_ready") + a.emitVMLog(name, "Exited recovery mode") +} + // FinishInstall exits recovery through the owning driver and mirrors deferred // changes into the existing App pending-change model. func (a *App) FinishInstall(name string) error { @@ -283,32 +320,7 @@ func (a *App) FinishInstall(name string) error { return err } result, _ := raw.(map[string]any) - running, _ := result["running"].(bool) - if running { - var diffs []PendingChange - if value, _ := result["installer_ejected"].(bool); value { - diffs = append(diffs, PendingChange{Field: "installer", From: "attached", To: "ejected"}) - } - if value, _ := result["network_enabled"].(bool); value { - diffs = append(diffs, PendingChange{Field: "network", From: "off", To: "on"}) - } - if value, _ := result["upgraded_nvme"].(bool); value { - from, _ := result["disk_controller_from"].(string) - if from == "" { - from = "ahci" - } - diffs = append(diffs, PendingChange{Field: "disk_controller", From: from, To: "nvme"}) - } - if value, _ := result["recovery_pending"].(bool); value { - diffs = append(diffs, PendingChange{Field: "recovery", From: "on", To: "off"}) - } - if len(diffs) > 0 { - a.mu.Lock() - a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], diffs...) - a.mu.Unlock() - } - } - a.emitVMLog(name, "Exited recovery mode") + a.applyFinishInstallResult(vm.DriverID, name, result) a.wakePoll() a.emitStateChanged() return nil @@ -338,7 +350,7 @@ func (a *App) finishMacOSInstall(name string) error { return err } } - stripped := reims.StripOfflineHelperArgs(d.ExtraArgs) + stripped := reims.StripProvisionArgs(reims.StripOfflineHelperArgs(d.ExtraArgs)) setOpts := reims.SetOpts{Name: name} needSet := false upgradedNVMe := false @@ -363,6 +375,10 @@ func (a *App) finishMacOSInstall(name string) error { return err } } + if err := installer.SecureRemoveProvisionImage(d.Directory); err != nil { + a.emitVMLog(name, "Warning: could not remove offline provisioning disk (REIMSPROV) now; scheduled wipe for next start: "+err.Error()) + } + a.clearTelemetryMilestone(vmKey(name), "serial:provision_ready") running := c.IsRunning(ctx, d) marker := startprep.ReadRecoveryMarker(d.Directory) diff --git a/internal/app/install_guide.go b/internal/app/install_guide.go index cf4db49..95a068c 100644 --- a/internal/app/install_guide.go +++ b/internal/app/install_guide.go @@ -2,6 +2,7 @@ package app import ( "context" + "strings" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/i18n" @@ -75,6 +76,223 @@ func installGuideKind(d reims.VMDetail) (installguide.Kind, bool) { return installguide.BuiltIn, startprep.ReadRecoveryMarker(d.Directory) == "on" } +func (a *App) suppressInstallGuideForVM(name string) bool { + if gm := a.getInstallGuideManager(); gm != nil && name != "" { + return gm.Cancel(name) + } + return false +} + +func (a *App) markInstallGuideRecheck(name string) { + name = strings.TrimSpace(name) + if name == "" { + return + } + a.mu.Lock() + if a.guideRecheckVMs == nil { + a.guideRecheckVMs = map[string]bool{} + } + a.guideRecheckVMs[name] = true + a.mu.Unlock() +} + +func (a *App) consumeInstallGuideRecheck(name string) bool { + if name == "" { + return false + } + a.mu.Lock() + ok := a.guideRecheckVMs[name] + if ok { + delete(a.guideRecheckVMs, name) + } + a.mu.Unlock() + return ok +} + +func (a *App) setPendingInstallGuideHandoff(name, step string) { + name = strings.TrimSpace(name) + if name == "" || step == "" { + return + } + a.mu.Lock() + if a.pendingGuideHandoffs == nil { + a.pendingGuideHandoffs = map[string]string{} + } + // Preserve a pending desktop handoff if already scheduled. + if cur := a.pendingGuideHandoffs[name]; cur != string(installguide.StepDesktop) || step == string(installguide.StepDesktop) { + a.pendingGuideHandoffs[name] = step + } + a.mu.Unlock() +} + +func (a *App) hasPendingInstallGuideHandoff(name string) bool { + if name == "" { + return false + } + a.mu.Lock() + _, ok := a.pendingGuideHandoffs[name] + a.mu.Unlock() + return ok +} + +func (a *App) applyPendingInstallGuideHandoff(name, dir string) { + if name == "" || dir == "" { + return + } + a.mu.Lock() + step, ok := a.pendingGuideHandoffs[name] + if ok { + delete(a.pendingGuideHandoffs, name) + } + a.mu.Unlock() + if ok && step != "" { + _ = installguide.AdvancePostInstallHandoff(dir, name, installguide.Offline, installguide.PostInstallStep(step)) + } +} + +func isMacOSDriverID(driverID string) bool { + id := driver.CanonicalDriverID(strings.TrimSpace(driverID)) + return id == "" || id == driver.BuiltinReimsMacOSDriverID +} + +func (a *App) cachedVMDir(driverID, name string) string { + driverID = driver.CanonicalDriverID(driverID) + if driverID == "" { + driverID = driver.BuiltinReimsMacOSDriverID + } + a.mu.Lock() + defer a.mu.Unlock() + for _, vm := range a.lastVMs { + if vm.Name == name && driver.CanonicalDriverID(vm.DriverID) == driverID && strings.TrimSpace(vm.Dir) != "" { + return strings.TrimSpace(vm.Dir) + } + } + return "" +} + +func (a *App) cachedRunningVMPID(driverID, name string) int { + driverID = driver.CanonicalDriverID(driverID) + if driverID == "" { + driverID = driver.BuiltinReimsMacOSDriverID + } + a.mu.Lock() + defer a.mu.Unlock() + for _, vm := range a.lastVMs { + if vm.Name == name && driver.CanonicalDriverID(vm.DriverID) == driverID && vm.State == "running" && vm.PID != nil && *vm.PID > 0 { + return *vm.PID + } + } + return 0 +} + +// restoreManualInstallGuideFallback ensures the original manual installation +// guide is re-evaluated (or unfolded if already active in compact form) when a +// plugin cannot run — for example after the user denies protected-phase or +// plugin execution permission. +func (a *App) restoreManualInstallGuideFallback(driverID, vmName string) bool { + vmName = strings.TrimSpace(vmName) + if vmName == "" || !isMacOSDriverID(driverID) { + return false + } + vmKey := vmKeyForDriver(driverID, vmName) + a.dismissCompletedOverlay(vmKey) + a.markInstallGuideRecheck(vmName) + if gm := a.getInstallGuideManager(); gm != nil { + if pid := a.cachedRunningVMPID(driverID, vmName); pid > 0 && gm.HasActive(vmName, pid) { + gm.Unfold(vmName, pid) + } + } + a.wakePoll() + a.emitStateChanged() + return a.installGuideEnabled() +} + +// prepareInstallGuideFinishHandoff snapshots a macOS VM's recovery state BEFORE +// `finish_install` modifies disk/recovery markers, returning a commit callback +// that persists the matching post-install manual guide checkpoint once +// `finish_install` succeeds. +func (a *App) prepareInstallGuideFinishHandoff(vm driver.VMInfo) func(running bool, pid int) bool { + if driver.CanonicalDriverID(vm.DriverID) != driver.BuiltinReimsMacOSDriverID { + return func(bool, int) bool { return false } + } + if vm.Directory == "" { + vm.Directory = a.cachedVMDir(vm.DriverID, vm.Name) + } + d, err := macOSDetailFromVMInfo(vm) + if err != nil || d.Directory == "" { + return func(bool, int) bool { return false } + } + kind, recovery := installGuideKind(d) + if !recovery { + return func(bool, int) bool { return false } + } + step := installguide.StepSetup + if kind == installguide.BuiltIn { + step = installguide.StepRestored + } + vmName, vmDir, media := vm.Name, d.Directory, d.InstallerPath + return func(running bool, pid int) bool { + var restartFrom uint32 + if running && pid > 0 { + restartFrom = uint32(pid) + } + return installguide.SavePostInstallHandoff(vmDir, vmName, kind, media, step, restartFrom) == nil + } +} + +// prepareInstallGuideRestoreAfterSession ensures the original manual install +// guide will reappear on the VM window after an auto-install or Agent session +// exits (whether stopped manually by the user, failed, plugin-disabled, or +// completed). It returns true when the native VM-window install guide is +// enabled and will take over the VM window so any colliding completed session +// island is dismissed cleanly. +func (a *App) prepareInstallGuideRestoreAfterSession(sess *agentSession, completed bool) bool { + if sess == nil || sess.vmName == "" { + return false + } + if !isMacOSDriverID(sess.driverID) { + return false + } + vmDir := strings.TrimSpace(sess.vmDir) + if vmDir == "" { + vmDir = a.cachedVMDir(sess.driverID, sess.vmName) + } + + var targetStep installguide.PostInstallStep + if sess.isAutoInstall { + switch { + case completed && (strings.EqualFold(sess.autoInstallMode, "full") || (sess.autoInstallMode == "" && sess.sawSetupAssistant)): + targetStep = installguide.StepDesktop + case completed: + targetStep = installguide.StepSetup + case sess.stage == "stage6_desktop_ready": + targetStep = installguide.StepDesktop + case sess.finishInstallDone || sess.stage == "stage5_setup_assistant" || sess.stage == "stage5_wait_reboot": + targetStep = installguide.StepSetup + } + } + if targetStep != "" { + if vmDir != "" { + _ = installguide.AdvancePostInstallHandoff(vmDir, sess.vmName, installguide.Offline, targetStep) + } else { + a.setPendingInstallGuideHandoff(sess.vmName, string(targetStep)) + } + } + + a.markInstallGuideRecheck(sess.vmName) + + if !a.installGuideEnabled() { + return false + } + if sess.isAutoInstall || sess.finishInstallDone || sess.suppressedInstallGuide { + return true + } + if vmDir != "" && installguide.HasPostInstallCheckpoint(vmDir, sess.vmName) { + return true + } + return a.hasPendingInstallGuideHandoff(sess.vmName) +} + // guideTracker follows the install guides of running VMs for the poll loop. type guideTracker struct { a *App @@ -105,12 +323,33 @@ func (t *guideTracker) startMissing(ctx context.Context, vms []driver.VMListItem } started := false for _, vm := range vms { - pid := vm.RunningPID() // The install guide belongs to the macOS installer flow. - if pid == 0 || t.checked[pid] || !driver.SupportsCapability(vm.Capabilities, driver.CapOpenCore) { + if !driver.SupportsCapability(vm.Capabilities, driver.CapOpenCore) { continue } - det, ok := details[vmKeyForDriver(vm.DriverID, vm.Name)] + pid := vm.RunningPID() + if pid == 0 { + // Old PIDs were already pruned by prunePinnedPIDs; clear any stale recheck flag. + t.a.consumeInstallGuideRecheck(vm.Name) + continue + } + vmKey := vmKeyForDriver(vm.DriverID, vm.Name) + if t.a.hasActiveAgentSession(vmKey) { + // While an Agent/auto-install session owns the VM, never cache pid as + // checked so the original manual guide is re-evaluated as soon as it ends. + delete(t.checked, pid) + continue + } + if t.a.consumeInstallGuideRecheck(vm.Name) { + delete(t.checked, pid) + if t.mgr.HasActive(vm.Name, pid) { + t.mgr.Unfold(vm.Name, pid) + } + } + if t.checked[pid] { + continue + } + det, ok := details[vmKey] if !ok { var err error if det, err = t.a.resolveVMInfo(vm.DriverID, vm.Name); err != nil { @@ -120,9 +359,16 @@ func (t *guideTracker) startMissing(ctx context.Context, vms []driver.VMListItem det.Directory = vm.Dir } } + t.a.applyPendingInstallGuideHandoff(vm.Name, det.Directory) + if t.a.hasActiveAgentSession(vmKey) { + delete(t.checked, pid) + continue + } t.checked[pid] = true if t.a.maybeStartInstallGuide(ctx, t.mgr, vm.Name, pid, det, loc) { started = true + } else if t.a.hasActiveAgentSession(vmKey) { + delete(t.checked, pid) } } return started @@ -132,6 +378,10 @@ func (a *App) maybeStartInstallGuide(ctx context.Context, gm *installguide.Manag if gm == nil || pid <= 0 || gm.HasActive(name, pid) { return false } + vmKey := vm.Ref().Key() + if a.hasActiveAgentSession(vmKey) { + return false + } d, err := macOSDetailFromVMInfo(vm) if err != nil { return false @@ -148,7 +398,15 @@ func (a *App) maybeStartInstallGuide(ctx context.Context, gm *installguide.Manag if !g.Resume(d.Directory, d.InstallerPath, recovery) { return false } - return gm.Start(ctx, a.buildInstallGuide(ctx, g, d)) + if !gm.Start(ctx, a.buildInstallGuide(ctx, g, d)) { + return false + } + if a.hasActiveAgentSession(vmKey) { + gm.Cancel(name) + return false + } + a.dismissCompletedOverlay(vmKey) + return true } func (a *App) buildInstallGuide(ctx context.Context, g installguide.Guide, d reims.VMDetail) installguide.Guide { diff --git a/internal/app/install_guide_test.go b/internal/app/install_guide_test.go index 54c726e..9aa0fac 100644 --- a/internal/app/install_guide_test.go +++ b/internal/app/install_guide_test.go @@ -2,18 +2,39 @@ package app import ( "context" + "encoding/json" + "io" + "os" + "path/filepath" + "strings" "testing" + "time" "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/i18n" + vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle" "github.com/Nwflower/reims-go/internal/macos/guest" "github.com/Nwflower/reims-go/internal/macos/installguide" "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/macos/startprep" "github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/internal/plugin/builtin" + "github.com/Nwflower/reims-go/pkg/pluginproto" ) +func syncGuidesForTest( + ctx context.Context, + a *App, + gm *installguide.Manager, + vms []driver.VMListItem, + shown map[string]driver.VMInfo, + checked map[int]bool, + loc i18n.Locale, +) bool { + return (&guideTracker{a: a, mgr: gm, checked: checked}).startMissing(ctx, vms, shown, loc) +} + func TestInstallGuideFollowsBootMedia(t *testing.T) { d := reims.VMDetail{Directory: t.TempDir()} for _, test := range []struct { @@ -99,3 +120,996 @@ func TestInstallGuideFollowsPluginSwitch(t *testing.T) { t.Fatal("expected re-enabling builtin.install-guide to wake poll") } } + +func newInstallGuideTestApp(t *testing.T) (*App, *plugin.Manager) { + t.Helper() + dataRoot := t.TempDir() + cfg := config.Default() + cfg.DataRoot = dataRoot + cfg.Locale = i18n.ZhCN + a := &App{ + cfg: cfg, + themeMode: "dark", + 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) + } + t.Cleanup(func() { mgr.Close() }) + a.pluginMgr = mgr + + cb := builtin.HostCallbacks{ + GetConfig: func() config.Config { return *cfg }, + SyncInstallGuides: a.wakePoll, + 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()) + + // Drain initial SyncInstallGuides wakeup. + select { + case <-a.pollWake: + default: + } + return a, mgr +} + +func drainWake(ch chan struct{}) bool { + select { + case <-ch: + return true + default: + return false + } +} + +func macOSRecoveryVM(name, dir string, pid int, installerPath string) (driver.VMListItem, driver.VMInfo) { + p := pid + item := driver.VMListItem{ + Name: name, + DriverID: driver.BuiltinReimsMacOSDriverID, + Dir: dir, + PID: &p, + State: "running", + Capabilities: []string{driver.CapOpenCore}, + } + det := vmInfoFromMacOSDetail(reims.VMDetail{ + Name: name, + Directory: dir, + State: "running", + HasInstaller: installerPath != "", + InstallerPath: installerPath, + }) + return item, det +} + +func TestAutoInstallManualExitRestoresInstallGuide(t *testing.T) { + a, mgr := newInstallGuideTestApp(t) + gm := a.getInstallGuideManager() + if gm == nil { + t.Fatal("expected install guide manager active by default") + } + defer gm.Close() + + vmDir := t.TempDir() + const vmName = "tahoe-stop" + const pid = 41001 + item, det := macOSRecoveryVM(vmName, vmDir, pid, "offline-installer-tahoe.img") + vmKey := det.Ref().Key() + checked := map[int]bool{} + shown := map[string]driver.VMInfo{vmKey: det} + + // 1. Initial boot starts the manual install guide and marks PID checked. + if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) { + t.Fatal("expected initial poll to start manual install guide") + } + if !gm.HasActive(vmName, pid) || !checked[pid] { + t.Fatalf("expected active guide and checked PID, active=%v checked=%v", gm.HasActive(vmName, pid), checked[pid]) + } + + // 2. Starting auto-install suppresses the manual guide. + a.beginAgentSession(mgr, guest.IDAutoInstall, det, "macOS 自动装机助手", "stage1_boot_recovery", "lock", true) + a.setAgentSessionAutoInstallConfig(vmKey, guest.IDAutoInstall, "recovery_only", "", false) + drainWake(a.pollWake) + if gm.HasActive(vmName, pid) { + t.Fatal("auto-install session must suppress active manual install guide") + } + // Polling while session is active must NOT start the guide or keep PID poisoned as checked. + if syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) { + t.Fatal("poll must not start manual install guide while auto-install is active") + } + if gm.HasActive(vmName, pid) { + t.Fatal("manual guide must stay suppressed while auto-install is active") + } + + // 3. User manually exits auto-install -> wakes poll and restores manual guide on the SAME PID. + if err := a.StopAgentSession(det.DriverID, vmName); err != nil { + t.Fatalf("StopAgentSession: %v", err) + } + if !drainWake(a.pollWake) { + t.Fatal("StopAgentSession must wake pollVMs to restore manual install guide") + } + // Even if checked[pid] had remained true (e.g. session began & stopped between two polls), + // the recheck flag must clear checked[pid] and restore the manual guide. + checked[pid] = true + if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) { + t.Fatal("expected manual install guide to be restored after user stops auto-install") + } + if !gm.HasActive(vmName, pid) { + t.Fatal("expected manual install guide active again after StopAgentSession") + } + + // 4. Starting auto-install again and failing mid-run (non-completed EndSession) also restores manual guide. + a.beginAgentSession(mgr, guest.IDAutoInstall, det, "macOS 自动装机助手", "stage2a_offline_terminal", "lock", true) + a.setAgentSessionAutoInstallConfig(vmKey, guest.IDAutoInstall, "recovery_only", "", false) + drainWake(a.pollWake) + if gm.HasActive(vmName, pid) { + t.Fatal("second auto-install run must suppress manual guide") + } + a.sessionMu.Lock() + a.agentSessions[vmKey].status = "failed" + a.sessionMu.Unlock() + a.endAgentSession(mgr, guest.IDAutoInstall, vmKey, "session_ended") + if !drainWake(a.pollWake) { + t.Fatal("failed endAgentSession must wake pollVMs to restore manual install guide") + } + if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) { + t.Fatal("expected manual install guide restored after failed auto-install session") + } + + // 5. Disabling the auto-install plugin mid-run also restores the manual guide. + a.beginAgentSession(mgr, guest.IDAutoInstall, det, "macOS 自动装机助手", "stage1_boot_recovery", "lock", true) + a.setAgentSessionAutoInstallConfig(vmKey, guest.IDAutoInstall, "recovery_only", "", false) + drainWake(a.pollWake) + if gm.HasActive(vmName, pid) { + t.Fatal("expected manual guide suppressed before plugin disable") + } + if err := mgr.Disable(t.Context(), guest.IDAutoInstall); err != nil { + t.Fatalf("Disable auto-install plugin: %v", err) + } + if !drainWake(a.pollWake) { + t.Fatal("disabling auto-install plugin must wake pollVMs to restore manual guide") + } + if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) { + t.Fatal("expected manual install guide restored after disabling auto-install plugin") + } +} + +func TestAutoInstallCompletionRestoresManualGuideAcrossModes(t *testing.T) { + t.Run("recovery_only completes to setup guide without completed overlay overlap", func(t *testing.T) { + a, mgr := newInstallGuideTestApp(t) + gm := a.getInstallGuideManager() + defer gm.Close() + + vmDir := t.TempDir() + const vmName = "tahoe-rec-only" + oldPID, newPID := 51001, 51002 + recItem, recDet := macOSRecoveryVM(vmName, vmDir, oldPID, "offline-installer-tahoe.img") + vmKey := recDet.Ref().Key() + checked := map[int]bool{} + + // Start auto-install before first poll (as CreateWizard does). + a.beginAgentSession(mgr, guest.IDAutoInstall, recDet, "macOS 自动装机助手", "stage0_preflight", "lock", true) + a.setAgentSessionAutoInstallConfig(vmKey, guest.IDAutoInstall, "recovery_only", "", false) + drainWake(a.pollWake) + syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{recItem}, map[string]driver.VMInfo{vmKey: recDet}, checked, i18n.ZhCN) + if gm.HasActive(vmName, oldPID) { + t.Fatal("guide must stay suppressed during recovery_only auto-install") + } + + // Stage 4: finish_install commits post-install handoff pinned to oldPID. + commitHandoff := a.prepareInstallGuideFinishHandoff(recDet) + if !commitHandoff(true, oldPID) { + t.Fatal("expected prepareInstallGuideFinishHandoff commit to succeed") + } + a.markAgentSessionFinishInstallDone(vmKey) + + // VM restarts with newPID and installer ejected (HasInstaller=false). + postItem, postDet := macOSRecoveryVM(vmName, vmDir, newPID, "") + syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{postItem}, map[string]driver.VMInfo{vmKey: postDet}, checked, i18n.ZhCN) + if gm.HasActive(vmName, newPID) { + t.Fatal("guide must stay suppressed until recovery_only completes") + } + + // Stage 5: recovery_only completes and ends session. + a.sessionMu.Lock() + a.agentSessions[vmKey].stage = "stage6_desktop_ready" + a.agentSessions[vmKey].status = "completed" + a.agentSessions[vmKey].message = "已完成恢复模式安装并进入 macOS,画面输入已解锁" + a.sessionMu.Unlock() + a.endAgentSession(mgr, guest.IDAutoInstall, vmKey, "session_ended") + + if a.isCompletedOverlay(vmKey) { + t.Fatal("must not retain overlapping completed session overlay when manual install guide takes over") + } + if !drainWake(a.pollWake) { + t.Fatal("completed auto-install session must wake pollVMs to show manual guide") + } + if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{postItem}, map[string]driver.VMInfo{vmKey: postDet}, checked, i18n.ZhCN) { + t.Fatal("expected manual install guide to start after recovery_only completion") + } + if !gm.HasActive(vmName, newPID) { + t.Fatal("expected manual install guide active on post-restart PID") + } + // Verify checkpoint hands off to Setup Assistant (step="setup", not desktop). + raw, err := os.ReadFile(filepath.Join(vmDir, ".reims-go-install-guide.json")) + if err != nil { + t.Fatalf("read guide checkpoint: %v", err) + } + var cp struct { + Step string `json:"step"` + RestartFrom uint32 `json:"restart_from"` + } + if err := json.Unmarshal(raw, &cp); err != nil { + t.Fatalf("parse guide checkpoint: %v", err) + } + if cp.Step != string(installguide.StepSetup) || cp.RestartFrom != uint32(oldPID) { + t.Fatalf("recovery_only checkpoint = %+v, want step=%s restart_from=%d", cp, installguide.StepSetup, oldPID) + } + }) + + t.Run("full mode completes to desktop guide without completed overlay overlap", func(t *testing.T) { + a, mgr := newInstallGuideTestApp(t) + gm := a.getInstallGuideManager() + defer gm.Close() + + vmDir := t.TempDir() + const vmName = "tahoe-full" + oldPID, newPID := 52001, 52002 + _, recDet := macOSRecoveryVM(vmName, vmDir, oldPID, "offline-installer-tahoe.img") + vmKey := recDet.Ref().Key() + checked := map[int]bool{} + + a.beginAgentSession(mgr, guest.IDAutoInstall, recDet, "macOS 自动装机助手", "stage0_preflight", "lock", true) + a.setAgentSessionAutoInstallConfig(vmKey, guest.IDAutoInstall, "full", "", false) + commitHandoff := a.prepareInstallGuideFinishHandoff(recDet) + if !commitHandoff(true, oldPID) { + t.Fatal("expected finish_install handoff commit") + } + a.markAgentSessionFinishInstallDone(vmKey) + + postItem, postDet := macOSRecoveryVM(vmName, vmDir, newPID, "") + a.sessionMu.Lock() + a.agentSessions[vmKey].stage = "stage6_desktop_ready" + a.agentSessions[vmKey].status = "completed" + a.agentSessions[vmKey].sawSetupAssistant = true + a.sessionMu.Unlock() + drainWake(a.pollWake) + a.endAgentSession(mgr, guest.IDAutoInstall, vmKey, "session_ended") + + if a.isCompletedOverlay(vmKey) { + t.Fatal("must not retain overlapping completed session overlay when manual install guide takes over") + } + if !drainWake(a.pollWake) { + t.Fatal("full mode completion must wake pollVMs") + } + if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{postItem}, map[string]driver.VMInfo{vmKey: postDet}, checked, i18n.ZhCN) || !gm.HasActive(vmName, newPID) { + t.Fatal("expected manual install guide active on desktop after full mode completion") + } + // Verify checkpoint advanced to desktop (step="desktop", restart_from=0). + raw, err := os.ReadFile(filepath.Join(vmDir, ".reims-go-install-guide.json")) + if err != nil { + t.Fatalf("read guide checkpoint: %v", err) + } + var cp struct { + Step string `json:"step"` + RestartFrom uint32 `json:"restart_from"` + } + if err := json.Unmarshal(raw, &cp); err != nil { + t.Fatalf("parse guide checkpoint: %v", err) + } + if cp.Step != string(installguide.StepDesktop) || cp.RestartFrom != 0 { + t.Fatalf("full mode checkpoint = %+v, want step=%s restart_from=0", cp, installguide.StepDesktop) + } + }) + + t.Run("stopping after finish_install before restart restores manual guide at restartPending", func(t *testing.T) { + a, mgr := newInstallGuideTestApp(t) + gm := a.getInstallGuideManager() + defer gm.Close() + + vmDir := t.TempDir() + const vmName = "tahoe-pre-restart-stop" + const oldPID = 53001 + _, recDet := macOSRecoveryVM(vmName, vmDir, oldPID, "offline-installer-tahoe.img") + vmKey := recDet.Ref().Key() + checked := map[int]bool{oldPID: true} + + a.beginAgentSession(mgr, guest.IDAutoInstall, recDet, "macOS 自动装机助手", "stage4_finish_install", "lock", true) + a.setAgentSessionAutoInstallConfig(vmKey, guest.IDAutoInstall, "recovery_only", "", false) + commitHandoff := a.prepareInstallGuideFinishHandoff(recDet) + if !commitHandoff(true, oldPID) { + t.Fatal("expected finish_install handoff commit") + } + a.markAgentSessionFinishInstallDone(vmKey) + drainWake(a.pollWake) + + // User exits before VM restarts (installer already ejected on disk, same PID still running). + if err := a.StopAgentSession(recDet.DriverID, vmName); err != nil { + t.Fatalf("StopAgentSession: %v", err) + } + if !drainWake(a.pollWake) { + t.Fatal("expected StopAgentSession to wake pollVMs") + } + postItem, postDet := macOSRecoveryVM(vmName, vmDir, oldPID, "") + if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{postItem}, map[string]driver.VMInfo{vmKey: postDet}, checked, i18n.ZhCN) || !gm.HasActive(vmName, oldPID) { + t.Fatal("expected manual guide to reappear after pre-restart stop") + } + }) + + t.Run("non-autoinstall session on already-installed VM does not pop spurious guide", func(t *testing.T) { + a, mgr := newInstallGuideTestApp(t) + gm := a.getInstallGuideManager() + defer gm.Close() + + vmDir := t.TempDir() + const vmName = "tahoe-normal" + const pid = 54001 + item, det := macOSRecoveryVM(vmName, vmDir, pid, "") + vmKey := det.Ref().Key() + checked := map[int]bool{} + + a.beginAgentSession(mgr, "reims.agent", det, "MCP Agent", "working", "auto", false) + a.sessionMu.Lock() + a.agentSessions[vmKey].status = "completed" + a.sessionMu.Unlock() + a.endAgentSession(mgr, "reims.agent", vmKey, "session_ended") + + if !a.isCompletedOverlay(vmKey) { + t.Fatal("expected completed overlay retained when no manual guide applies") + } + if syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, map[string]driver.VMInfo{vmKey: det}, checked, i18n.ZhCN) || gm.HasActive(vmName, pid) { + t.Fatal("must not start manual install guide for normal installed VM with non-autoinstall session") + } + }) + + t.Run("disabled install_guide retains completed overlay as fallback", func(t *testing.T) { + a, mgr := newInstallGuideTestApp(t) + if err := mgr.Registry().SetDesired(t.Context(), guest.ID, false); err != nil { + t.Fatal(err) + } + if a.installGuideEnabled() { + t.Fatal("expected install guide disabled") + } + vmDir := t.TempDir() + const vmName = "tahoe-no-guide" + _, det := macOSRecoveryVM(vmName, vmDir, 55001, "") + vmKey := det.Ref().Key() + a.beginAgentSession(mgr, guest.IDAutoInstall, det, "macOS 自动装机助手", "stage6_desktop_ready", "lock", true) + a.setAgentSessionAutoInstallConfig(vmKey, guest.IDAutoInstall, "recovery_only", "", false) + a.sessionMu.Lock() + a.agentSessions[vmKey].status = "completed" + a.sessionMu.Unlock() + a.endAgentSession(mgr, guest.IDAutoInstall, vmKey, "session_ended") + if !a.isCompletedOverlay(vmKey) { + t.Fatal("expected completed overlay retained when VM-window manual install guide is disabled") + } + }) + + t.Run("pending handoff restores manual guide when vmDir becomes known on poll", func(t *testing.T) { + a, mgr := newInstallGuideTestApp(t) + gm := a.getInstallGuideManager() + defer gm.Close() + + vmDir := t.TempDir() + const vmName = "tahoe-lazy-dir" + const pid = 56001 + // Start session with empty Directory so handoff queues in pendingGuideHandoffs. + noDirDet := driver.VMInfo{DriverID: driver.BuiltinReimsMacOSDriverID, Name: vmName, State: "running"} + vmKey := noDirDet.Ref().Key() + a.beginAgentSession(mgr, guest.IDAutoInstall, noDirDet, "macOS 自动装机助手", "stage5_wait_reboot", "lock", true) + a.setAgentSessionAutoInstallConfig(vmKey, guest.IDAutoInstall, "recovery_only", "", false) + a.sessionMu.Lock() + a.agentSessions[vmKey].status = "completed" + a.sessionMu.Unlock() + a.endAgentSession(mgr, guest.IDAutoInstall, vmKey, "session_ended") + if a.isCompletedOverlay(vmKey) { + t.Fatal("must hand off to manual guide even when vmDir is resolved on poll") + } + + postItem, postDet := macOSRecoveryVM(vmName, vmDir, pid, "") + checked := map[int]bool{} + if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{postItem}, map[string]driver.VMInfo{vmKey: postDet}, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) { + t.Fatal("expected pending handoff applied on poll to start manual guide") + } + if !installguide.HasPostInstallCheckpoint(vmDir, vmName) { + t.Fatal("expected pending handoff persisted to vmDir on poll") + } + }) +} + +type stubMacOSRecoveryDriver struct { + vm driver.VMInfo +} + +func (d *stubMacOSRecoveryDriver) ID() string { return driver.BuiltinReimsMacOSDriverID } +func (d *stubMacOSRecoveryDriver) DisplayName() plugin.LocalizedText { return plugin.LocalizedText{EnUS: "macOS Stub"} } +func (d *stubMacOSRecoveryDriver) RuntimeKind() string { return "reims-vgpu" } +func (d *stubMacOSRecoveryDriver) RuntimeAPIRange() string { return ">=1.0.0" } +func (d *stubMacOSRecoveryDriver) Capabilities() []string { return []string{driver.CapOpenCore, driver.CapQMP} } +func (d *stubMacOSRecoveryDriver) CreateSchema() *plugin.SettingsSchema { return nil } +func (d *stubMacOSRecoveryDriver) SettingsSchema() *plugin.SettingsSchema { return nil } +func (d *stubMacOSRecoveryDriver) List(context.Context) ([]driver.VMInfo, error) { + return []driver.VMInfo{d.vm}, nil +} +func (d *stubMacOSRecoveryDriver) Show(_ context.Context, name string) (driver.VMInfo, error) { + if name != d.vm.Name { + return driver.VMInfo{}, os.ErrNotExist + } + return d.vm, nil +} +func (d *stubMacOSRecoveryDriver) ValidateCreate(context.Context, driver.CreateRequest) []driver.ValidationIssue { + return nil +} +func (d *stubMacOSRecoveryDriver) Create(context.Context, driver.CreateRequest, io.Writer, io.Writer) error { + return nil +} +func (d *stubMacOSRecoveryDriver) ValidateSet(context.Context, driver.SetRequest) []driver.ValidationIssue { + return nil +} +func (d *stubMacOSRecoveryDriver) Set(context.Context, driver.SetRequest, io.Writer, io.Writer) error { + return nil +} +func (d *stubMacOSRecoveryDriver) Start(context.Context, driver.StartRequest) (driver.StartResult, error) { + return driver.StartResult{}, nil +} +func (d *stubMacOSRecoveryDriver) Stop(context.Context, string, bool, io.Writer, io.Writer) error { + return nil +} +func (d *stubMacOSRecoveryDriver) Delete(context.Context, string, bool, io.Writer, io.Writer) error { + return nil +} + +type stubFailingAutoInstallEndpoint struct { + status string + msg string +} + +func (e *stubFailingAutoInstallEndpoint) Call(_ context.Context, method string, _ any, out any) error { + if method == "autoinstall/status" && out != nil { + b, _ := json.Marshal(map[string]any{ + "status": e.status, + "message": e.msg, + }) + return json.Unmarshal(b, out) + } + return nil +} +func (e *stubFailingAutoInstallEndpoint) Notify(string, any) {} + +func newPermissionDenialGuideTestEnv(t *testing.T, vmName string, pid int, installerPath string) (*App, *plugin.Manager, *installguide.Manager, driver.VMListItem, driver.VMInfo, string) { + t.Helper() + dataRoot := t.TempDir() + vmDir := t.TempDir() + cfg := config.Default() + cfg.DataRoot = dataRoot + cfg.Locale = i18n.ZhCN + a := &App{ + cfg: cfg, + themeMode: "dark", + 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) + }, + OnSettingsChanged: func(pluginID, vmName string) { + a.onPluginSettingsChanged(pluginID, vmName) + }, + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { mgr.Close() }) + a.pluginMgr = mgr + + cb := builtin.HostCallbacks{ + GetConfig: func() config.Config { return *cfg }, + SyncInstallGuides: a.wakePoll, + 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()) + + item, det := macOSRecoveryVM(vmName, vmDir, pid, installerPath) + p := pid + det.PID = &p + det.Phase = driver.PhaseInstaller + det.Capabilities = []string{driver.CapOpenCore, driver.CapQMP} + det.GuestOS = &driver.GuestOSInfo{Family: "macos"} + + drvReg := plugin.NewRegistry(nil) + stubDrv := &stubMacOSRecoveryDriver{vm: det} + if err := drvReg.Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ + Schema: 1, + ID: "test.macos.driver", + 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.driverRouter = router + a.vmStateTable = stateTable + a.lifecycleSvc = vmlifecycle.New(drvReg, router, nil) + a.lastVMs = []driver.VMListItem{item} + + gm := a.getInstallGuideManager() + if gm == nil { + t.Fatal("expected install guide manager active") + } + t.Cleanup(func() { gm.Close() }) + drainWake(a.pollWake) + return a, mgr, gm, item, det, vmDir +} + +func TestPermissionDenialRestoresOriginalManualInstallGuide(t *testing.T) { + t.Run("blocking session.begin protected_phase denial restores guide and clears secret without session.end", func(t *testing.T) { + const vmName = "tahoe-deny-begin" + const pid = 61001 + a, mgr, gm, item, det, vmDir := newPermissionDenialGuideTestEnv(t, vmName, pid, "offline-installer-tahoe.img") + vmKey := det.Ref().Key() + checked := map[int]bool{pid: true} + shown := map[string]driver.VMInfo{vmKey: det} + + // Simulate StartAutoInstall opening a session with DPAPI secret & ephemeral grant. + if err := mgr.SetSettings(guest.IDAutoInstall, vmKey, map[string]any{"account_password": "TempPass123!"}); err != nil { + t.Fatalf("store temp secret: %v", err) + } + a.grantEphemeralVMAccess(guest.IDAutoInstall, vmKey) + a.beginAgentSession(mgr, guest.IDAutoInstall, det, "macOS 自动装机助手", "stage0_preflight", "lock", true) + a.setAgentSessionAutoInstallConfig(vmKey, guest.IDAutoInstall, "full", "account_password", false) + drainWake(a.pollWake) + + promptCount := 0 + a.confirmEmit = func(p ConfirmPrompt) { + promptCount++ + go func() { _ = a.ResolveConfirmRequest(p.ID, false, 0, false) }() + } + + // Plugin requests blocking protected-phase confirmation and NEVER calls host/session.end. + rawReq, _ := json.Marshal(map[string]any{ + "vm": vmKey, + "label": "macOS Auto-Install", + "stage": "stage0_preflight", + "takeover_policy": "lock", + "request_protected_phase_auth": true, + "prefer_until_phase_exit": true, + }) + handlers := a.hostAPISvc().Handlers(mgr, guest.IDAutoInstall) + _, err := handlers["host/session.begin"](context.Background(), rawReq) + if err == nil || !strings.Contains(err.Error(), "confirmation_denied") { + t.Fatalf("session.begin err = %v, want confirmation_denied", err) + } + if promptCount != 1 { + t.Fatalf("expected 1 confirmation prompt, got %d", promptCount) + } + if a.hasActiveAgentSession(vmKey) { + t.Fatal("active agent session must be torn down immediately on permission denial") + } + if a.hasEphemeralVMAccess(guest.IDAutoInstall, vmKey) { + t.Fatal("ephemeral VM access must be revoked when denied session is torn down") + } + if sec, sErr := mgr.SecretSetting(guest.IDAutoInstall, vmKey, "account_password"); sErr == nil && sec != "" { + t.Fatalf("temporary DPAPI secret must be wiped on denial, got non-empty secret") + } + if !drainWake(a.pollWake) { + t.Fatal("permission denial must wake pollVMs to restore original manual guide") + } + // Denial record must be preserved so a follow-up non-blocking check returns confirmation_denied without re-prompting. + if err := a.authorizeProtectedPhase(context.Background(), mgr, guest.IDAutoInstall, det, driver.PhaseInstaller, false, false); err == nil || !strings.Contains(err.Error(), "confirmation_denied") { + t.Fatalf("subsequent protected phase check err = %v, want confirmation_denied", err) + } + if promptCount != 1 { + t.Fatalf("subsequent check must not re-prompt after denial, got %d prompts", promptCount) + } + + // Even with checked[pid]=true, poll restores the original offline manual install guide. + if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) { + t.Fatal("expected original manual install guide restored after blocking permission denial") + } + // Ensure no spurious post-install checkpoint was persisted (installer never ran). + if _, err := os.Stat(filepath.Join(vmDir, ".reims-go-install-guide.json")); err == nil { + t.Fatal("must not write post-install checkpoint when script never ran due to permission denial") + } + }) + + t.Run("async protected_phase denial during console call aborts session and restores guide", func(t *testing.T) { + const vmName = "tahoe-deny-async" + const pid = 61002 + a, mgr, gm, item, det, _ := newPermissionDenialGuideTestEnv(t, vmName, pid, "offline-installer-tahoe.img") + vmKey := det.Ref().Key() + checked := map[int]bool{pid: true} + shown := map[string]driver.VMInfo{vmKey: det} + + const extPlugin = "test.external.agent" + a.grantEphemeralVMAccess(extPlugin, vmKey) + a.beginAgentSession(mgr, extPlugin, det, "External Agent", "working", "auto", true) + drainWake(a.pollWake) + + prompts := make(chan ConfirmPrompt, 2) + a.confirmEmit = func(p ConfirmPrompt) { prompts <- p } + + _, _, err := a.resolveComputerUseVM(context.Background(), mgr, extPlugin, vmKey, false) + if err == nil || !strings.Contains(err.Error(), "confirmation_required") { + t.Fatalf("first console call err = %v, want confirmation_required", err) + } + var p ConfirmPrompt + select { + case p = <-prompts: + case <-time.After(2 * time.Second): + t.Fatal("expected async confirmation prompt") + } + if err := a.ResolveConfirmRequest(p.ID, false, 0, false); err != nil { + t.Fatal(err) + } + waitFor(t, "active session aborted on async denial", func() bool { + return !a.hasActiveAgentSession(vmKey) + }) + if !drainWake(a.pollWake) { + t.Fatal("async permission denial must wake pollVMs") + } + if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) { + t.Fatal("expected manual install guide restored after async denial") + } + + // Subsequent non-blocking check returns confirmation_denied without re-prompting or spamming pollWake. + drainWake(a.pollWake) + if err := a.authorizeProtectedPhase(context.Background(), mgr, extPlugin, det, driver.PhaseInstaller, false, false); err == nil || !strings.Contains(err.Error(), "confirmation_denied") { + t.Fatalf("repeat check err = %v, want confirmation_denied", err) + } + if len(prompts) != 0 { + t.Fatal("repeat check must not open a second confirmation dialog") + } + if drainWake(a.pollWake) { + t.Fatal("repeat denied call without active session must not spam pollWake") + } + }) + + t.Run("host/ui.confirm protected_phase denial without prior session restores manual guide", func(t *testing.T) { + const vmName = "tahoe-deny-confirm" + const pid = 61003 + a, mgr, gm, item, det, _ := newPermissionDenialGuideTestEnv(t, vmName, pid, "offline-installer-tahoe.img") + vmKey := det.Ref().Key() + checked := map[int]bool{pid: true} + shown := map[string]driver.VMInfo{vmKey: det} + + a.confirmEmit = func(p ConfirmPrompt) { + go func() { _ = a.ResolveConfirmRequest(p.ID, false, 0, false) }() + } + rawReq, _ := json.Marshal(map[string]any{ + "vm": vmKey, + "protected_phase": driver.PhaseInstaller, + "title": "Allow installer automation", + "message": "Plugin wants to run install.sh", + }) + handlers := a.hostAPISvc().Handlers(mgr, guest.IDAutoInstall) + res, err := handlers["host/ui.confirm"](context.Background(), rawReq) + if err != nil { + t.Fatalf("host/ui.confirm returned unexpected error: %v", err) + } + if cr, ok := res.(pluginproto.ConfirmResult); !ok || cr.Approved { + t.Fatalf("host/ui.confirm result = %#v, want Approved=false", res) + } + if !drainWake(a.pollWake) { + t.Fatal("host/ui.confirm protected_phase denial must wake pollVMs") + } + if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) { + t.Fatal("expected manual install guide restored after host/ui.confirm denial") + } + }) +} + +func TestBrokerAndHeadlessPermissionDenialRestoresOriginalManualInstallGuide(t *testing.T) { + t.Run("broker permission denial in StartAutoInstall, ResumeAutoInstall, and session.begin restores manual guide", func(t *testing.T) { + const vmName = "tahoe-deny-broker" + const pid = 61004 + a, mgr, gm, item, det, _ := newPermissionDenialGuideTestEnv(t, vmName, pid, "offline-installer-tahoe.img") + vmKey := det.Ref().Key() + shown := map[string]driver.VMInfo{vmKey: det} + + // Register an external auto-installer plugin missing qmp:write permission. + const lackingPlugin = "community.lacking.autoinstall" + if err := mgr.Registry().Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ + Schema: 1, + ID: lackingPlugin, + Version: "1.0.0", + Name: plugin.LocalizedText{EnUS: "Lacking Perms AutoInstaller"}, + Permissions: []string{"vm:read"}, + Contributes: plugin.Contributes{ + AutoInstallers: []plugin.AutoInstallerContribution{{ + ID: "lacking-macos", + Title: plugin.LocalizedText{EnUS: "Lacking AutoInstall"}, + GuestFamilies: []string{"macos"}, + }}, + }, + }, + Source: plugin.SourceLocal, + Trust: plugin.TrustCommunity, + Desired: true, + }); err != nil { + t.Fatal(err) + } + // Register an external plugin awaiting high-risk approval (NeedsApproval=true). + const unapprovedPlugin = "community.unapproved.agent" + if err := mgr.Registry().Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ + Schema: 1, + ID: unapprovedPlugin, + Version: "1.0.0", + Name: plugin.LocalizedText{EnUS: "Unapproved Agent"}, + Permissions: []string{"vm:read", "vm:screen", "qmp:write", "vm:control"}, + }, + Source: plugin.SourceLocal, + Trust: plugin.TrustCommunity, + NeedsApproval: true, + }); err != nil { + t.Fatal(err) + } + mgr.Registry().Reconcile(context.Background()) + drainWake(a.pollWake) + + // Part A: StartAutoInstall fails broker precheck and restores manual guide. + checked := map[int]bool{pid: true} + if _, err := a.StartAutoInstall(AutoInstallStartRequest{ + PluginID: lackingPlugin, + DriverID: det.DriverID, + VMName: vmName, + Mode: "recovery_only", + SLAAccepted: true, + }); err == nil { + t.Fatal("StartAutoInstall must fail when plugin lacks required permissions") + } + if a.hasActiveAgentSession(vmKey) { + t.Fatal("StartAutoInstall must not leave an active session when broker denies permissions") + } + if !drainWake(a.pollWake) { + t.Fatal("StartAutoInstall permission denial must wake pollVMs") + } + if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) { + t.Fatal("expected manual install guide restored after StartAutoInstall broker denial") + } + + // Part B: ResumeAutoInstall also fails broker precheck and restores manual guide. + gm.Cancel(vmName) + checked[pid] = true + drainWake(a.pollWake) + if _, err := a.ResumeAutoInstall(lackingPlugin, det.DriverID, vmName); err == nil { + t.Fatal("ResumeAutoInstall must fail when plugin lacks required permissions") + } + if !drainWake(a.pollWake) { + t.Fatal("ResumeAutoInstall permission denial must wake pollVMs") + } + if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) { + t.Fatal("expected manual install guide restored after ResumeAutoInstall broker denial") + } + + // Part C: Unapproved plugin calling host/session.begin aborts any active session and restores guide. + a.beginAgentSession(mgr, unapprovedPlugin, det, "Unapproved Agent", "working", "lock", true) + checked[pid] = true + drainWake(a.pollWake) + rawBegin, _ := json.Marshal(map[string]any{"vm": vmKey, "label": "Unapproved"}) + if _, err := a.hostAPISvc().Handlers(mgr, unapprovedPlugin)["host/session.begin"](context.Background(), rawBegin); err == nil { + t.Fatal("unapproved plugin host/session.begin must fail broker check") + } + if a.hasActiveAgentSession(vmKey) { + t.Fatal("unapproved plugin broker denial must abort active session") + } + if !drainWake(a.pollWake) { + t.Fatal("unapproved plugin broker denial must wake pollVMs") + } + if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) { + t.Fatal("expected manual install guide restored after unapproved plugin broker denial") + } + }) + + t.Run("headless confirmation_unavailable aborts session and restores manual guide", func(t *testing.T) { + const vmName = "tahoe-deny-headless" + const pid = 61005 + a, mgr, gm, item, det, _ := newPermissionDenialGuideTestEnv(t, vmName, pid, "offline-installer-tahoe.img") + vmKey := det.Ref().Key() + checked := map[int]bool{pid: true} + shown := map[string]driver.VMInfo{vmKey: det} + + a.confirmEmit = nil + a.ctx = nil + a.grantEphemeralVMAccess(guest.IDAutoInstall, vmKey) + a.beginAgentSession(mgr, guest.IDAutoInstall, det, "macOS 自动装机助手", "stage0_preflight", "lock", true) + drainWake(a.pollWake) + + rawBegin, _ := json.Marshal(map[string]any{ + "vm": vmKey, + "request_protected_phase_auth": true, + }) + _, err := a.hostAPISvc().Handlers(mgr, guest.IDAutoInstall)["host/session.begin"](context.Background(), rawBegin) + if err == nil || !strings.Contains(err.Error(), "confirmation_unavailable") { + t.Fatalf("headless session.begin err = %v, want confirmation_unavailable", err) + } + if a.hasActiveAgentSession(vmKey) { + t.Fatal("headless confirmation_unavailable must abort active session") + } + if !drainWake(a.pollWake) { + t.Fatal("headless confirmation_unavailable must wake pollVMs") + } + if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) { + t.Fatal("expected manual install guide restored on headless confirmation_unavailable") + } + }) + + t.Run("revoking per-VM allow_ai_access immediately aborts session and restores manual guide", func(t *testing.T) { + const vmName = "tahoe-revoke-access" + const pid = 61006 + a, mgr, gm, item, det, _ := newPermissionDenialGuideTestEnv(t, vmName, pid, "offline-installer-tahoe.img") + vmKey := det.Ref().Key() + checked := map[int]bool{pid: true} + shown := map[string]driver.VMInfo{vmKey: det} + + const agentPlugin = "community.remote.agent" + if err := mgr.Registry().Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ + Schema: 1, + ID: agentPlugin, + Version: "1.0.0", + Name: plugin.LocalizedText{EnUS: "Remote Agent"}, + Permissions: []string{"vm:read", "vm:screen", "qmp:write"}, + Settings: &plugin.SettingsSchema{ + Scope: "vm", + Properties: map[string]plugin.SettingProperty{ + computerUseAccessSetting: {Type: "boolean"}, + }, + }, + }, + Source: plugin.SourceLocal, + Trust: plugin.TrustCommunity, + Desired: true, + }); err != nil { + t.Fatal(err) + } + mgr.Registry().Reconcile(context.Background()) + + if err := mgr.SetSettings(agentPlugin, vmKey, map[string]any{computerUseAccessSetting: true}); err != nil { + t.Fatal(err) + } + a.beginAgentSession(mgr, agentPlugin, det, "Remote Agent", "working", "auto", false) + drainWake(a.pollWake) + + // User turns off per-VM allow_ai_access while plugin session is active. + if err := mgr.SetSettings(agentPlugin, vmKey, map[string]any{computerUseAccessSetting: false}); err != nil { + t.Fatal(err) + } + if a.hasActiveAgentSession(vmKey) { + t.Fatal("disabling per-VM allow_ai_access must immediately abort active plugin session") + } + if !drainWake(a.pollWake) { + t.Fatal("revoking per-VM allow_ai_access must wake pollVMs") + } + if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) { + t.Fatal("expected manual install guide restored after revoking allow_ai_access") + } + }) + + t.Run("watchAutoInstallSession ends lingering session when plugin fails without calling session.end", func(t *testing.T) { + const vmName = "tahoe-watch-fallback" + const pid = 61007 + a, mgr, gm, item, det, _ := newPermissionDenialGuideTestEnv(t, vmName, pid, "offline-installer-tahoe.img") + vmKey := det.Ref().Key() + checked := map[int]bool{pid: true} + shown := map[string]driver.VMInfo{vmKey: det} + + prevInterval := autoInstallWatchInterval + autoInstallWatchInterval = 15 * time.Millisecond + t.Cleanup(func() { autoInstallWatchInterval = prevInterval }) + + const extAuto = "community.failing.autoinstall" + ep := &stubFailingAutoInstallEndpoint{status: "failed", msg: "permission denied"} + if err := mgr.Registry().Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ + Schema: 1, + ID: extAuto, + Version: "1.0.0", + Name: plugin.LocalizedText{EnUS: "Failing AutoInstaller"}, + Permissions: []string{"vm:read", "vm:screen", "qmp:write", "vm:control"}, + Contributes: plugin.Contributes{ + AutoInstallers: []plugin.AutoInstallerContribution{{ + ID: "failing-macos", + Title: plugin.LocalizedText{EnUS: "Failing AutoInstall"}, + GuestFamilies: []string{"macos"}, + }}, + }, + }, + Source: plugin.SourceLocal, + Trust: plugin.TrustCommunity, + Desired: true, + Activate: func(_ context.Context, sc *plugin.Scope) error { + sc.Registry().RegisterInProcessEndpoint(sc, ep) + return nil + }, + }); err != nil { + t.Fatal(err) + } + mgr.Registry().Reconcile(context.Background()) + + a.grantEphemeralVMAccess(extAuto, vmKey) + a.beginAgentSession(mgr, extAuto, det, "Failing AutoInstall", "stage0_preflight", "lock", true) + a.setAgentSessionAutoInstallConfig(vmKey, extAuto, "recovery_only", "", false) + watchCtx, watchGen, ok := a.startAutoInstallSessionWatch(vmKey, extAuto) + if !ok { + t.Fatal("startAutoInstallSessionWatch returned ok=false") + } + drainWake(a.pollWake) + + done := make(chan struct{}) + go func() { + defer close(done) + a.watchAutoInstallSession(watchCtx, watchGen, mgr, extAuto, vmKey, "", false) + }() + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("watchAutoInstallSession did not exit after plugin reported failed status") + } + if a.hasActiveAgentSession(vmKey) { + t.Fatal("watchAutoInstallSession must end lingering session when plugin fails without calling host/session.end") + } + if !drainWake(a.pollWake) { + t.Fatal("watchAutoInstallSession cleanup must wake pollVMs") + } + if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) { + t.Fatal("expected manual install guide restored after watchAutoInstallSession cleanup") + } + }) +} diff --git a/internal/app/lifecycle_flow.go b/internal/app/lifecycle_flow.go index 1352379..d68e331 100644 --- a/internal/app/lifecycle_flow.go +++ b/internal/app/lifecycle_flow.go @@ -162,6 +162,9 @@ func (a *App) startResolvedVMLocked(ctx context.Context, svc interface { a.startVMMonitor(ref.Name, detail, startAt) } a.wakePoll() + if a.hasActiveAgentSession(key) { + go a.refreshActiveAgentSessionAfterStart(key) + } a.emitStateChanged() return nil } @@ -328,6 +331,10 @@ func (a *App) DeleteVM(driverID, name string, keepFiles bool) error { stopVMMonitor(ref.Name) a.stopPacketBridge(ref.Name) } + _ = a.StopAgentSession(ref.DriverID, ref.Name) + a.telemetryMu.Lock() + delete(a.vmTelemetry, key) + a.telemetryMu.Unlock() a.mu.Lock() delete(a.pendingChanges, key) delete(a.transitions, key) diff --git a/internal/app/lifecycle_flow_test.go b/internal/app/lifecycle_flow_test.go index d00d0b4..97eebc3 100644 --- a/internal/app/lifecycle_flow_test.go +++ b/internal/app/lifecycle_flow_test.go @@ -292,6 +292,48 @@ func TestSameNameVMsAcrossDriversStayIndependent(t *testing.T) { } } +func TestDeleteVMClearsTelemetryAndAgentSession(t *testing.T) { + const driverID = "test.driver.cleanup" + drv := &appSecondDriver{ + id: driverID, + vms: []driver.VMInfo{{Name: "dev", DriverID: driverID, Directory: t.TempDir(), State: "stopped"}}, + } + reg := plugin.NewRegistry(nil) + if err := reg.Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ID: "test.cleanup", Version: "1.0.0"}, + Source: plugin.SourceBuiltin, Desired: true, + Activate: func(_ context.Context, sc *plugin.Scope) error { + reg.RegisterGuestDriver(sc, driverID, drv) + return nil + }, + }); err != nil { + t.Fatal(err) + } + reg.Reconcile(context.Background()) + a := &App{ + cfg: &config.Config{DataRoot: t.TempDir()}, + lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil), + transitions: map[string]string{}, + pendingChanges: map[string][]PendingChange{}, + } + key := drv.vms[0].Ref().Key() + a.recordTelemetryMilestone(key, "boot") + a.beginAgentSession(nil, "test.plugin", drv.vms[0], "Auto", "stage1", "manual", true) + + if err := a.DeleteVM(driverID, "dev", false); err != nil { + t.Fatal(err) + } + if a.hasActiveAgentSession(key) { + t.Fatal("agent session remained active after deleting VM") + } + a.telemetryMu.Lock() + _, hasTelemetry := a.vmTelemetry[key] + a.telemetryMu.Unlock() + if hasTelemetry { + t.Fatal("telemetry state remained after deleting VM") + } +} + func TestStopVMMonitorWaitsForExitAndAllowsDirRemoval(t *testing.T) { vmDir := t.TempDir() logDir := filepath.Join(vmDir, "logs") diff --git a/internal/app/macos_lifecycle_native.go b/internal/app/macos_lifecycle_native.go index 0e3c856..a7f3c9f 100644 --- a/internal/app/macos_lifecycle_native.go +++ b/internal/app/macos_lifecycle_native.go @@ -101,6 +101,13 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) { } a.emitVMLog(name, "Win10 WHPX cold-reboot: guest requested reboot (guest-reset), restarting in a fresh Hyper-V partition...") + a.recordTelemetryColdReboot(vmKey(name)) + restarted := false + defer func() { + if !restarted { + a.clearTelemetryColdRebootPreserve(vmKey(name)) + } + }() oldPID := a.cachedVMPID(name) c, err := a.client() if err != nil { @@ -162,6 +169,8 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) { } if err := a.StartVM(driver.BuiltinReimsMacOSDriverID, name); err != nil { a.emitVMLog(name, "Win10 WHPX cold-reboot start failed: "+err.Error()) + } else { + restarted = true } }() } @@ -169,21 +178,48 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) { // restartMacOSVM restarts a built-in macOS VM, waiting for the old QEMU // process and its committed memory to go away before starting again. func (a *App) restartMacOSVM(ctx context.Context, name string) (stopped bool, err error) { + return a.restartMacOSVMWithGrace(ctx, name, 0) +} + +// restartMacOSVMWithGrace restarts a built-in macOS VM. When gracefulTimeout > 0 +// and soft ACPI shutdown does not exit within gracefulTimeout (for example at +// macOS Setup Assistant or Login Window, which ignore ACPI power buttons), it +// falls back cleanly to a forced stop instead of stalling for stop_timeout_secs. +func (a *App) restartMacOSVMWithGrace(ctx context.Context, name string, gracefulTimeout time.Duration) (stopped bool, err error) { vm, err := a.resolveVMInfo(driver.BuiltinReimsMacOSDriverID, name) if err != nil { return false, err } err = a.withComputerUseVM(ctx, vm.Directory, func(operationCtx context.Context) error { - stopped, err = a.restartMacOSVMLocked(operationCtx, name) + stopped, err = a.restartMacOSVMLocked(operationCtx, name, gracefulTimeout) return err }) return stopped, err } -func (a *App) restartMacOSVMLocked(ctx context.Context, name string) (stopped bool, err error) { +func (a *App) restartMacOSVMLocked(ctx context.Context, name string, gracefulTimeout time.Duration) (stopped bool, err error) { oldPID := a.cachedVMPID(name) - if err := a.stopVM(ctx, driver.BuiltinReimsMacOSDriverID, name, false); err != nil { - return false, err + if gracefulTimeout > 0 { + graceCtx, graceCancel := context.WithTimeout(ctx, gracefulTimeout) + stopErr := a.stopVM(graceCtx, driver.BuiltinReimsMacOSDriverID, name, false) + graceTimedOut := errors.Is(graceCtx.Err(), context.DeadlineExceeded) || errors.Is(stopErr, context.DeadlineExceeded) + graceCancel() + if stopErr != nil { + if ctx.Err() != nil { + return false, ctx.Err() + } + if !graceTimedOut { + return false, fmt.Errorf("graceful stop before restart: %w", stopErr) + } + a.emitVMLog(name, fmt.Sprintf("Graceful ACPI shutdown did not exit within %s; forcing restart...", gracefulTimeout)) + if err := a.stopVM(ctx, driver.BuiltinReimsMacOSDriverID, name, true); err != nil { + return false, err + } + } + } else { + if err := a.stopVM(ctx, driver.BuiltinReimsMacOSDriverID, name, false); err != nil { + return false, err + } } a.waitForVMProcessExit(ctx, oldPID, vmExitWaitTimeout) if c, err := a.client(); err == nil { diff --git a/internal/app/plugin_connect.go b/internal/app/plugin_connect.go index 655d9f7..3422a6b 100644 --- a/internal/app/plugin_connect.go +++ b/internal/app/plugin_connect.go @@ -4,6 +4,10 @@ import ( "context" "encoding/json" "errors" + "fmt" + "path/filepath" + "runtime" + "strings" "github.com/Nwflower/reims-go/internal/control" "github.com/Nwflower/reims-go/internal/plugin" @@ -23,6 +27,9 @@ func (a *App) startPluginControlServer() { return a.pluginMgr } server, err := control.ListenWithOptions(control.PipeName(), func(ctx context.Context, pluginID, channel string, message json.RawMessage) (json.RawMessage, error) { + if pluginID == control.HostPluginID && channel == control.ChannelAutoInstall { + return a.handleControlAutoInstall(message) + } mgr := currentManager() if mgr == nil { return nil, errors.New("plugin manager is not ready") @@ -34,6 +41,9 @@ func (a *App) startPluginControlServer() { return } for _, target := range targets { + if target.PluginID == control.HostPluginID { + continue + } mgr.ChannelSessionClosed(target.PluginID, target.Channel, session) } }}) @@ -52,6 +62,68 @@ func (a *App) startPluginControlServer() { a.mu.Unlock() } +func sameDataRoot(aPath, bPath string) bool { + aClean := filepath.Clean(strings.TrimSpace(aPath)) + bClean := filepath.Clean(strings.TrimSpace(bPath)) + if runtime.GOOS == "windows" { + return strings.EqualFold(aClean, bClean) + } + return aClean == bClean +} + +func (a *App) handleControlAutoInstall(message json.RawMessage) (json.RawMessage, error) { + var req control.AutoInstallRequest + if err := json.Unmarshal(message, &req); err != nil { + return nil, fmt.Errorf("invalid auto-install control request: %w", err) + } + if strings.TrimSpace(req.DataRoot) != "" { + a.mu.Lock() + appRoot := "" + if a.cfg != nil { + appRoot = a.cfg.DataRoot + } + a.mu.Unlock() + if appRoot != "" && !sameDataRoot(req.DataRoot, appRoot) { + return nil, errors.New("data_root_mismatch: running desktop app uses a different data directory") + } + } + var ( + res any + err error + ) + switch strings.ToLower(strings.TrimSpace(req.Action)) { + case "status": + if strings.TrimSpace(req.VMName) == "" { + res, err = a.listAutoInstallStatuses(req.PluginID) + } else { + res, err = a.GetAutoInstallStatus(req.PluginID, req.DriverID, req.VMName) + } + case "resume": + if strings.TrimSpace(req.VMName) == "" { + return nil, errors.New("vm name is required for auto-install resume") + } + res, err = a.ResumeAutoInstall(req.PluginID, req.DriverID, req.VMName) + case "stop": + if strings.TrimSpace(req.VMName) == "" { + return nil, errors.New("vm name is required for auto-install stop") + } + if err = a.StopAutoInstall(req.PluginID, req.DriverID, req.VMName); err == nil { + res = map[string]any{"ok": true} + } + case "diagnostic": + if strings.TrimSpace(req.VMName) == "" { + return nil, errors.New("vm name is required for auto-install diagnostic") + } + res, err = a.GetAutoInstallDiagnosticSummary(req.PluginID, req.DriverID, req.VMName) + default: + return nil, fmt.Errorf("unknown auto-install control action %q", req.Action) + } + if err != nil { + return nil, err + } + return json.Marshal(res) +} + func (a *App) stopPluginControlServer() { a.mu.Lock() server := a.controlServer diff --git a/internal/app/plugins_flow.go b/internal/app/plugins_flow.go index 1fca199..3d68085 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -88,6 +88,9 @@ func (a *App) initPlugins() { a.mu.Lock() current := a.pluginMgr a.mu.Unlock() + if current == nil { + current = mgr + } return a.hostAPISvc().Handlers(current, pluginID) }, OnSettingsChanged: func(pluginID, vmName string) { @@ -209,6 +212,7 @@ func (a *App) initPlugins() { a.syncInputFilters() a.syncClipboardPolicies() a.syncLocales() + a.stopAgentSessionsForInactivePlugins(mgr) a.wakePoll() a.emitStateChanged() }) @@ -472,11 +476,36 @@ func (a *App) syncClipboardPolicies() { gt.SetGlobalClipboardPolicy(clipboardPolicyFromMap(globalVals)) } +func (a *App) normalizeVMKey(vmRef string) string { + vmRef = strings.TrimSpace(vmRef) + if vmRef == "" { + return "" + } + if vm, err := a.resolveComputerUseVMInfo(vmRef); err == nil { + return vm.Ref().Key() + } + if ref, ok := driver.ParseVMRef(vmRef); ok { + return ref.Key() + } + return vmKeyForDriver("", vmRef) +} + func (a *App) onPluginSettingsChanged(pluginID, vmName string) { a.syncInputFilters() if pluginID == builtin.IDClipboard { a.syncClipboardPolicies() } + if vmName != "" && pluginID != "" { + a.mu.Lock() + mgr := a.pluginMgr + a.mu.Unlock() + if mgr != nil { + vmKey := a.normalizeVMKey(vmName) + if a.hasActiveAgentSessionOwnedBy(vmKey, pluginID) && !a.computerUseVMAccessEnabled(mgr, pluginID, vmKey) { + a.handlePluginPermissionDeniedForVM(mgr, pluginID, vmKey, "", "permission_denied") + } + } + } if pluginID == guest.ID && vmName == "" { a.mu.Lock() mgr := a.pluginMgr diff --git a/internal/app/provision_flow_test.go b/internal/app/provision_flow_test.go new file mode 100644 index 0000000..2da016c --- /dev/null +++ b/internal/app/provision_flow_test.go @@ -0,0 +1,106 @@ +package app + +import ( + "bytes" + "os" + "path/filepath" + "testing" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/macos/installer" +) + +func TestPrepareVMProvisionForDir_HashOnlyAndCleanup(t *testing.T) { + dataRoot := t.TempDir() + vmDir := filepath.Join(dataRoot, "vms", "tahoe-prov") + if err := os.MkdirAll(vmDir, 0o755); err != nil { + t.Fatal(err) + } + a := &App{ + cfg: &config.Config{DataRoot: dataRoot}, + } + + const secret = "ProvTestPass-2026!" + noTools := false + err := a.prepareVMProvisionForDir("tahoe-prov", vmDir, ProvisionRequest{ + FullName: "Test User", + AccountName: "testuser", + Password: secret, + Appearance: "dark", + SLAAccepted: true, + InstallGuestTools: &noTools, + }) + if err != nil { + t.Fatalf("prepareVMProvisionForDir: %v", err) + } + if !a.hasVMProvisionDir(vmDir) { + t.Fatalf("expected hasVMProvisionDir to report true") + } + + imgPath := installer.ProvisionImagePath(vmDir) + raw, err := os.ReadFile(imgPath) + if err != nil { + t.Fatalf("read provision image: %v", err) + } + if bytes.Contains(raw, []byte(secret)) { + t.Fatalf("provision disk image must never contain plaintext password") + } + + // Re-running prepareVMProvisionForDir with new credentials must rebuild the + // REIMSPROV image rather than silently keeping stale credentials on disk. + const newSecret = "UpdatedProvPass-2026!" + if err := a.prepareVMProvisionForDir("tahoe-prov", vmDir, ProvisionRequest{ + FullName: "Second User", + AccountName: "seconduser", + Password: newSecret, + Appearance: "light", + SLAAccepted: true, + InstallGuestTools: &noTools, + }); err != nil { + t.Fatalf("rebuild prepareVMProvisionForDir: %v", err) + } + rebuilt, err := os.ReadFile(imgPath) + if err != nil { + t.Fatalf("read rebuilt provision image: %v", err) + } + if bytes.Contains(rebuilt, []byte(newSecret)) { + t.Fatal("rebuilt provision image must never contain plaintext password") + } + if !bytes.Contains(rebuilt, []byte("seconduser")) { + t.Fatal("rebuilt provision image must reflect updated account name") + } + + if err := installer.SecureRemoveProvisionImage(vmDir); err != nil { + t.Fatalf("SecureRemoveProvisionImage: %v", err) + } + if a.hasVMProvisionDir(vmDir) { + t.Fatalf("expected hasVMProvisionDir to report false after removal") + } +} + +func TestSerialProvisionReadyMilestone(t *testing.T) { + key, label := parseSerialMilestone(i18n.EnUS, "com.reimsgo.provision-ready: "+installer.ProvisionSerialReadyMarker) + if key != "serial:provision_ready" { + t.Fatalf("parseSerialMilestone key = %q, want serial:provision_ready", key) + } + if label == "" { + t.Fatalf("parseSerialMilestone label should not be empty") + } + + a := &App{} + wantKey := vmKey("prov-ready-test-vm") + a.recordTelemetryMilestone(wantKey, key) + + keys := a.provisionReadyVMKeys() + found := false + for _, k := range keys { + if k == wantKey { + found = true + break + } + } + if !found { + t.Fatalf("provisionReadyVMKeys() = %v, want %q", keys, wantKey) + } +} diff --git a/internal/app/review_fixes_r2_test.go b/internal/app/review_fixes_r2_test.go new file mode 100644 index 0000000..5faa06c --- /dev/null +++ b/internal/app/review_fixes_r2_test.go @@ -0,0 +1,414 @@ +package app + +import ( + "context" + "encoding/json" + "io" + "os" + "strings" + "testing" + "time" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/macos/installer" + "github.com/Nwflower/reims-go/internal/plugin" + vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle" +) + +type stubMultiVMMacOSDriver struct { + vms []driver.VMInfo +} + +func (d *stubMultiVMMacOSDriver) ID() string { return driver.BuiltinReimsMacOSDriverID } +func (d *stubMultiVMMacOSDriver) DisplayName() plugin.LocalizedText { return plugin.LocalizedText{EnUS: "macOS Stub"} } +func (d *stubMultiVMMacOSDriver) RuntimeKind() string { return "reims-vgpu" } +func (d *stubMultiVMMacOSDriver) RuntimeAPIRange() string { return ">=1.0.0" } +func (d *stubMultiVMMacOSDriver) Capabilities() []string { return []string{driver.CapOpenCore, driver.CapQMP} } +func (d *stubMultiVMMacOSDriver) CreateSchema() *plugin.SettingsSchema { return nil } +func (d *stubMultiVMMacOSDriver) SettingsSchema() *plugin.SettingsSchema { return nil } +func (d *stubMultiVMMacOSDriver) List(context.Context) ([]driver.VMInfo, error) { + return append([]driver.VMInfo(nil), d.vms...), nil +} +func (d *stubMultiVMMacOSDriver) Show(_ context.Context, name string) (driver.VMInfo, error) { + for _, vm := range d.vms { + if vm.Name == name { + return vm, nil + } + } + return driver.VMInfo{}, os.ErrNotExist +} +func (d *stubMultiVMMacOSDriver) ValidateCreate(context.Context, driver.CreateRequest) []driver.ValidationIssue { + return nil +} +func (d *stubMultiVMMacOSDriver) Create(context.Context, driver.CreateRequest, io.Writer, io.Writer) error { + return nil +} +func (d *stubMultiVMMacOSDriver) ValidateSet(context.Context, driver.SetRequest) []driver.ValidationIssue { + return nil +} +func (d *stubMultiVMMacOSDriver) Set(context.Context, driver.SetRequest, io.Writer, io.Writer) error { + return nil +} +func (d *stubMultiVMMacOSDriver) Start(context.Context, driver.StartRequest) (driver.StartResult, error) { + return driver.StartResult{}, nil +} +func (d *stubMultiVMMacOSDriver) Stop(context.Context, string, bool, io.Writer, io.Writer) error { + return nil +} +func (d *stubMultiVMMacOSDriver) Delete(context.Context, string, bool, io.Writer, io.Writer) error { + return nil +} + +func TestSingleVMNotAuthorizedDoesNotAbortOtherVMSession(t *testing.T) { + dataRoot := t.TempDir() + cfg := config.Default() + cfg.DataRoot = dataRoot + a := &App{cfg: cfg, pollWake: make(chan struct{}, 4)} + + mgr, err := plugin.NewManager(plugin.ManagerOptions{ + DataRoot: dataRoot, + HostVersion: "0.3.0", + }) + if err != nil { + t.Fatal(err) + } + defer mgr.Close() + a.pluginMgr = mgr + + const pid = "test.multi.vm.agent" + if err := mgr.Registry().Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ + Schema: 1, + ID: pid, + Version: "1.0.0", + Name: plugin.LocalizedText{EnUS: "Multi VM Agent"}, + Permissions: []string{"vm:read", "vm:screen", "qmp:write", "vm:control"}, + }, + Source: plugin.SourceBuiltin, + Trust: plugin.TrustOfficial, + Desired: true, + Activate: func(_ context.Context, _ *plugin.Scope) error { + return nil + }, + }); err != nil { + t.Fatal(err) + } + mgr.Registry().Reconcile(context.Background()) + + vmA := driver.VMInfo{DriverID: driver.BuiltinReimsMacOSDriverID, Name: "vm-a", State: "running", Phase: driver.PhaseNormal} + vmB := driver.VMInfo{DriverID: driver.BuiltinReimsMacOSDriverID, Name: "vm-b", State: "running", Phase: driver.PhaseNormal} + drvReg := plugin.NewRegistry(nil) + stubDrv := &stubMultiVMMacOSDriver{vms: []driver.VMInfo{vmA, vmB}} + if err := drvReg.Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ + Schema: 1, + ID: "test.macos.driver.multi", + 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.driverRouter = router + a.vmStateTable = stateTable + a.lifecycleSvc = vmlifecycle.New(drvReg, router, nil) + + a.mu.Lock() + a.lastVMs = []driver.VMListItem{ + {DriverID: vmA.DriverID, Name: vmA.Name, State: "running"}, + {DriverID: vmB.DriverID, Name: vmB.Name, State: "running"}, + } + a.lastVMsAt = time.Now() + a.mu.Unlock() + + // Authorize VM A only; leave VM B unauthorized. + a.grantEphemeralVMAccess(pid, vmA.Ref().Key()) + a.beginAgentSession(mgr, pid, vmA, "Agent", "stage1", "auto", true) + + // Calling host/session.begin on unauthorized VM B must fail with not_authorized + // WITHOUT tearing down the plugin's active session on VM A. + rawB, _ := json.Marshal(map[string]any{"vm": vmB.Ref().Key(), "label": "B"}) + if _, err := a.handleSessionBegin(context.Background(), rawB, mgr, pid); err == nil || !strings.Contains(err.Error(), "not_authorized") { + t.Fatalf("expected not_authorized for VM B, got %v", err) + } + if !a.hasActiveAgentSessionOwnedBy(vmA.Ref().Key(), pid) { + t.Fatal("single-VM not_authorized on VM B must NOT abort active session on VM A") + } + + // Same isolation for resolveComputerUseVM on unauthorized VM B. + if _, _, err := a.resolveComputerUseVM(context.Background(), mgr, pid, vmB.Ref().Key(), false); err == nil || !strings.Contains(err.Error(), "not_authorized") { + t.Fatalf("expected not_authorized from resolveComputerUseVM for VM B, got %v", err) + } + if !a.hasActiveAgentSessionOwnedBy(vmA.Ref().Key(), pid) { + t.Fatal("resolveComputerUseVM not_authorized on VM B must NOT abort active session on VM A") + } +} + +func TestCallHostAPIEnforcesCatalogPermissionsAndAuditForBuiltinPlugins(t *testing.T) { + dataRoot := t.TempDir() + cfg := config.Default() + cfg.DataRoot = dataRoot + a := &App{cfg: cfg, pollWake: make(chan struct{}, 4)} + + 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 + + const pid = "builtin.readonly.test" + if err := mgr.Registry().Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ + Schema: 1, + ID: pid, + Version: "1.0.0", + Name: plugin.LocalizedText{EnUS: "Readonly Builtin"}, + Permissions: []string{"vm:read"}, + }, + Source: plugin.SourceBuiltin, + Trust: plugin.TrustOfficial, + Desired: true, + Activate: func(_ context.Context, _ *plugin.Scope) error { return nil }, + }); err != nil { + t.Fatal(err) + } + mgr.Registry().Reconcile(context.Background()) + + // Calling host/vm.restart without vm:control must be denied via catalog authorization. + err = mgr.CallHostAPI(context.Background(), pid, "host/vm.restart", map[string]any{"vm": "demo"}, nil) + if err == nil || !strings.Contains(err.Error(), `lacks permission "vm:control"`) { + t.Fatalf("expected lacks permission vm:control, got %v", err) + } + logRaw, readErr := os.ReadFile(mgr.Layout().LogPath(pid)) + if readErr != nil || !strings.Contains(string(logRaw), "undeclared permission") { + t.Fatalf("expected DENY audit entry in plugin log, err=%v log=%q", readErr, string(logRaw)) + } +} + +func TestHasUnboundAgentSessionIgnoresStoppedAndSuspendedVMs(t *testing.T) { + vmStopped := driver.VMInfo{DriverID: driver.BuiltinReimsMacOSDriverID, Name: "vm-stopped", State: "stopped"} + vmSuspended := driver.VMInfo{DriverID: driver.BuiltinReimsMacOSDriverID, Name: "vm-suspended", State: "suspended"} + vmRunning := driver.VMInfo{DriverID: driver.BuiltinReimsMacOSDriverID, Name: "vm-running", State: "running"} + + a := &App{ + transitions: map[string]string{}, + lastVMs: []driver.VMListItem{ + {DriverID: vmStopped.DriverID, Name: vmStopped.Name, State: "stopped"}, + {DriverID: vmSuspended.DriverID, Name: vmSuspended.Name, State: "suspended"}, + {DriverID: vmRunning.DriverID, Name: vmRunning.Name, State: "running"}, + }, + agentSessions: map[string]*agentSession{ + vmStopped.Ref().Key(): {vmKey: vmStopped.Ref().Key(), driverID: vmStopped.DriverID, vmName: vmStopped.Name, startedAt: time.Now()}, + vmSuspended.Ref().Key(): {vmKey: vmSuspended.Ref().Key(), driverID: vmSuspended.DriverID, vmName: vmSuspended.Name, startedAt: time.Now()}, + }, + } + + if a.hasUnboundAgentSession() { + t.Fatal("stopped/suspended VMs with lastOverlayPID==0 must NOT force 500ms fast polling") + } + + // Transitioning to starting must re-enable fast discovery. + a.transitions[vmStopped.Ref().Key()] = "starting" + if !a.hasUnboundAgentSession() { + t.Fatal("starting VM with unbound overlay PID should enable fast discovery") + } + delete(a.transitions, vmStopped.Ref().Key()) + + // Running VM with unbound overlay PID must enable fast discovery until PID binds. + a.agentSessions[vmRunning.Ref().Key()] = &agentSession{ + vmKey: vmRunning.Ref().Key(), driverID: vmRunning.DriverID, vmName: vmRunning.Name, startedAt: time.Now(), + } + if !a.hasUnboundAgentSession() { + t.Fatal("running VM with lastOverlayPID==0 should enable fast discovery") + } + a.agentSessions[vmRunning.Ref().Key()].lastOverlayPID = 4321 + if a.hasUnboundAgentSession() { + t.Fatal("once running VM PID is bound and other sessions are stopped/suspended, fast polling must stop") + } +} + +func TestTelemetryPreservedOnResumeAndColdRebootButResetOnFreshBoot(t *testing.T) { + vmDir := t.TempDir() + vmKey := vmKeyForDriver(driver.BuiltinReimsMacOSDriverID, "tel-vm") + a := &App{} + + a.recordTelemetryMilestone(vmKey, "serial:xnu") + a.recordTelemetryMilestone(vmKey, "serial:xnu") + a.recordTelemetryQemuError(vmKey, "fatal: sample") + + // 1. Resume from suspended state must preserve milestones & errors. + a.preserveTelemetryForResume(vmKey, vmDir) + a.telemetryMu.Lock() + xnuAfterResume := a.vmTelemetry[vmKey].milestones["serial:xnu"].Count + errsAfterResume := len(a.vmTelemetry[vmKey].qemuErrors) + a.telemetryMu.Unlock() + if xnuAfterResume != 2 || errsAfterResume != 1 { + t.Fatalf("preserveTelemetryForResume lost telemetry: xnu=%d errs=%d", xnuAfterResume, errsAfterResume) + } + + // 2. Win10 cold-reboot restart must preserve milestones & errors across StartVM. + a.recordTelemetryColdReboot(vmKey) + a.resetTelemetryForBoot(vmKey, vmDir) + a.telemetryMu.Lock() + xnuAfterCold := a.vmTelemetry[vmKey].milestones["serial:xnu"].Count + errsAfterCold := len(a.vmTelemetry[vmKey].qemuErrors) + a.telemetryMu.Unlock() + if xnuAfterCold != 2 || errsAfterCold != 1 { + t.Fatalf("cold-reboot resetTelemetryForBoot lost telemetry: xnu=%d errs=%d", xnuAfterCold, errsAfterCold) + } + + // 3. Subsequent normal fresh cold boot must reset transient milestones & errors + // while preserving the persisted .reims-go-provision-ready marker. + installer.WriteProvisionReadyMarker(vmDir) + a.resetTelemetryForBoot(vmKey, vmDir) + a.telemetryMu.Lock() + _, hasXNU := a.vmTelemetry[vmKey].milestones["serial:xnu"] + _, hasReady := a.vmTelemetry[vmKey].milestones["serial:provision_ready"] + errsAfterFresh := len(a.vmTelemetry[vmKey].qemuErrors) + a.telemetryMu.Unlock() + if hasXNU || errsAfterFresh != 0 || !hasReady { + t.Fatalf("fresh cold boot reset unexpected state: hasXNU=%v errs=%d hasReady=%v", hasXNU, errsAfterFresh, hasReady) + } +} + +func TestPrepareVMProvisionLogsWarningWhenGuestToolsBridgeDisabled(t *testing.T) { + dataRoot := t.TempDir() + vmDir := t.TempDir() + cfg := config.Default() + cfg.DataRoot = dataRoot + a := &App{cfg: cfg} + + mgr, err := plugin.NewManager(plugin.ManagerOptions{DataRoot: dataRoot, HostVersion: "0.3.0"}) + if err != nil { + t.Fatal(err) + } + defer mgr.Close() + a.pluginMgr = mgr + + wantGT := true + err = a.prepareVMProvisionForDir("prov-warn", vmDir, ProvisionRequest{ + FullName: "Reims User", + AccountName: "reims", + Password: "Pass1234!", + SLAAccepted: true, + InstallGuestTools: &wantGT, + }) + if err != nil { + t.Fatalf("prepareVMProvisionForDir failed: %v", err) + } + a.mu.Lock() + joined := strings.Join(a.recentLogs, "\n") + a.mu.Unlock() + if !strings.Contains(joined, "Warning: skipped Guest Tools in REIMSPROV") { + t.Fatalf("expected warning log when Guest Tools bridge unavailable, got logs=%q", joined) + } +} + +func TestTrackVMPhaseTransitionsRevokesGrantsWhenVMVanishes(t *testing.T) { + a := &App{} + vmKey := vmKeyForDriver(driver.BuiltinReimsMacOSDriverID, "vanish-vm") + a.trackVMPhaseTransitions([]driver.VMListItem{{ + DriverID: driver.BuiltinReimsMacOSDriverID, + Name: "vanish-vm", + State: "running", + Phase: driver.PhaseInstaller, + }}) + a.grantProtectedPhase("ext.agent", vmKey, driver.PhaseInstaller, 0, true) + if _, ok := a.lookupProtectedPhaseGrant("ext.agent", vmKey); !ok { + t.Fatal("expected active untilPhaseExit grant") + } + + // VM disappears from polled list -> protected-phase grant MUST be revoked immediately. + a.trackVMPhaseTransitions(nil) + if _, ok := a.lookupProtectedPhaseGrant("ext.agent", vmKey); ok { + t.Fatal("untilPhaseExit grant must be revoked when VM disappears from polled list") + } +} + +func TestStartAutoInstallRejectsNonSecretPasswordSetting(t *testing.T) { + dataRoot := t.TempDir() + cfg := config.Default() + cfg.DataRoot = dataRoot + a := &App{cfg: cfg, pollWake: make(chan struct{}, 4)} + + mgr, err := plugin.NewManager(plugin.ManagerOptions{DataRoot: dataRoot, HostVersion: "0.3.0"}) + if err != nil { + t.Fatal(err) + } + defer mgr.Close() + a.pluginMgr = mgr + + const pid = "thirdparty.unsafe.autoinstall" + if err := mgr.Registry().Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ + Schema: 1, + ID: pid, + Version: "1.0.0", + Name: plugin.LocalizedText{EnUS: "Unsafe Installer"}, + Permissions: []string{"vm:read", "vm:screen", "qmp:write", "vm:control"}, + Contributes: plugin.Contributes{ + AutoInstallers: []plugin.AutoInstallerContribution{{ + ID: "unsafe", + Title: plugin.LocalizedText{EnUS: "Unsafe"}, + GuestFamilies: []string{"macos"}, + SecretSetting: "plain_password", + }}, + }, + Settings: &plugin.SettingsSchema{ + Scope: "vm", + Properties: map[string]plugin.SettingProperty{ + "plain_password": {Type: "string", Secret: false, Scope: "vm"}, + }, + }, + }, + Source: plugin.SourceBuiltin, + Trust: plugin.TrustOfficial, + Desired: true, + Activate: func(_ context.Context, _ *plugin.Scope) error { return nil }, + }); err != nil { + t.Fatal(err) + } + mgr.Registry().Reconcile(context.Background()) + + vmKey := vmKeyForDriver(driver.BuiltinReimsMacOSDriverID, "secret-check-vm") + a.mu.Lock() + a.lastVMs = []driver.VMListItem{{ + DriverID: driver.BuiltinReimsMacOSDriverID, + Name: "secret-check-vm", + State: "stopped", + }} + a.lastVMsAt = time.Now() + a.mu.Unlock() + + if err := validatePluginSecretSetting(mgr, pid, "plain_password"); err == nil || !strings.Contains(err.Error(), "not declared as secret") { + t.Fatalf("expected non-secret setting rejection, got %v", err) + } + if err := validatePluginSecretSetting(mgr, pid, ""); err == nil { + t.Fatal("expected empty secret_setting rejection") + } + // Ensure no plaintext password was persisted under the VM key. + if val, ok := mgr.GetSettings(pid, vmKey, false)["plain_password"]; ok && val != "" { + t.Fatalf("plaintext password must not be stored in non-secret setting, got %v", val) + } +} diff --git a/internal/app/review_fixes_r3_test.go b/internal/app/review_fixes_r3_test.go new file mode 100644 index 0000000..dbc0131 --- /dev/null +++ b/internal/app/review_fixes_r3_test.go @@ -0,0 +1,257 @@ +package app + +import ( + "context" + "encoding/json" + "sync" + "testing" + "time" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver" + vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle" + "github.com/Nwflower/reims-go/internal/plugin" +) + +func newR3TestManager(t *testing.T, dataRoot string) *plugin.Manager { + t.Helper() + mgr, err := plugin.NewManager(plugin.ManagerOptions{ + DataRoot: dataRoot, + HostVersion: "0.3.0", + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { mgr.Close() }) + return mgr +} + +func TestSessionUpdateCannotClearHostTakeoverOrUserPause(t *testing.T) { + dataRoot := t.TempDir() + mgr := newR3TestManager(t, dataRoot) + pauseManual := 0 + vm := driver.VMInfo{ + DriverID: driver.BuiltinReimsMacOSDriverID, + Name: "tahoe-takeover", + State: "running", + Phase: driver.PhaseNormal, + } + drvReg := plugin.NewRegistry(nil) + stubDrv := &stubMultiVMMacOSDriver{vms: []driver.VMInfo{vm}} + if err := drvReg.Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ + Schema: 1, + ID: "test.macos.driver.r3", + 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, + AgentTakeoverPauseSec: &pauseManual, + }, + pluginMgr: mgr, + driverRouter: router, + vmStateTable: stateTable, + lifecycleSvc: vmlifecycle.New(drvReg, router, nil), + } + const pluginID = "builtin.macos.autoinstall" + key := vm.Ref().Key() + a.grantEphemeralVMAccess(pluginID, key) + a.lastVMs = []driver.VMListItem{{DriverID: vm.DriverID, Name: vm.Name, State: "running"}} + a.lastVMsAt = time.Now() + a.beginAgentSession(mgr, pluginID, vm, "AutoInstall", "stage2", "auto", true) + + // 1. Physical user takeover (manual policy / pauseSec=0) must not be cleared + // by the plugin sending host/session.update with paused_for_user=false. + a.handlePhysicalUserTakeover(key, "keyboard") + if err := a.checkUserTakeover(key, vm.Name); err == nil { + t.Fatal("expected checkUserTakeover to block after physical takeover") + } + rawFalse, _ := json.Marshal(map[string]any{ + "vm": key, + "status": "running", + "paused_for_user": false, + }) + if _, err := a.handleSessionUpdate(context.Background(), rawFalse, mgr, pluginID); err != nil { + t.Fatalf("handleSessionUpdate: %v", err) + } + if err := a.checkUserTakeover(key, vm.Name); err == nil { + t.Fatal("plugin session.update(paused_for_user=false) bypassed host physical takeover pause") + } + + // Host ResumeAgentSession is the sole resume entry point. + if err := a.ResumeAgentSession(vm.DriverID, vm.Name); err != nil { + t.Fatalf("ResumeAgentSession: %v", err) + } + if err := a.checkUserTakeover(key, vm.Name); err != nil { + t.Fatalf("expected resumed session to pass checkUserTakeover, got %v", err) + } + + // 2. Explicit user PauseAgentSession must also resist plugin paused_for_user=false. + if err := a.PauseAgentSession(vm.DriverID, vm.Name); err != nil { + t.Fatalf("PauseAgentSession: %v", err) + } + if _, err := a.handleSessionUpdate(context.Background(), rawFalse, mgr, pluginID); err != nil { + t.Fatalf("handleSessionUpdate after PauseAgentSession: %v", err) + } + if err := a.checkUserTakeover(key, vm.Name); err == nil { + t.Fatal("plugin session.update(paused_for_user=false) bypassed explicit user PauseAgentSession") + } + _ = a.ResumeAgentSession(vm.DriverID, vm.Name) + + // 3. Plugin-initiated pause (not hostPaused / takeoverPaused) CAN still be cleared by plugin. + rawTrue, _ := json.Marshal(map[string]any{ + "vm": key, + "status": "paused_for_user", + "paused_for_user": true, + }) + if _, err := a.handleSessionUpdate(context.Background(), rawTrue, mgr, pluginID); err != nil { + t.Fatalf("handleSessionUpdate(true): %v", err) + } + if err := a.checkUserTakeover(key, vm.Name); err == nil { + t.Fatal("expected plugin-initiated paused_for_user=true to pause input") + } + if _, err := a.handleSessionUpdate(context.Background(), rawFalse, mgr, pluginID); err != nil { + t.Fatalf("handleSessionUpdate(false) after plugin pause: %v", err) + } + if err := a.checkUserTakeover(key, vm.Name); err != nil { + t.Fatalf("plugin should be able to clear its own non-host pause, got %v", err) + } +} + +func TestStartAutoInstallSessionWatchCancelsPriorGeneration(t *testing.T) { + dataRoot := t.TempDir() + mgr := newR3TestManager(t, dataRoot) + a := &App{ + cfg: &config.Config{DataRoot: dataRoot}, + pluginMgr: mgr, + } + const pluginID = "builtin.macos.autoinstall" + vm := driver.VMInfo{DriverID: driver.BuiltinReimsMacOSDriverID, Name: "tahoe-gen", State: "running"} + key := vm.Ref().Key() + a.beginAgentSession(mgr, pluginID, vm, "AutoInstall", "stage1", "lock", true) + + ctx1, gen1, ok := a.startAutoInstallSessionWatch(key, pluginID) + if !ok || gen1 == 0 { + t.Fatalf("first startAutoInstallSessionWatch failed: ok=%v gen=%d", ok, gen1) + } + if !a.isCurrentAutoInstallSessionWatch(key, pluginID, gen1) { + t.Fatal("gen1 should be current before replacement") + } + + // Re-starting auto-install on the same VM reuses the session but MUST cancel + // watcher 1 and advance the generation so watcher 1 cannot end or wipe run 2. + a.beginAgentSession(mgr, pluginID, vm, "AutoInstall", "stage1", "lock", true) + ctx2, gen2, ok := a.startAutoInstallSessionWatch(key, pluginID) + if !ok || gen2 <= gen1 { + t.Fatalf("second startAutoInstallSessionWatch failed: ok=%v gen1=%d gen2=%d", ok, gen1, gen2) + } + select { + case <-ctx1.Done(): + default: + t.Fatal("prior watcher context was not canceled when superseded") + } + if a.isCurrentAutoInstallSessionWatch(key, pluginID, gen1) { + t.Fatal("superseded gen1 must no longer be reported as current") + } + if !a.isCurrentAutoInstallSessionWatch(key, pluginID, gen2) { + t.Fatal("new gen2 must be current") + } + select { + case <-ctx2.Done(): + t.Fatal("new watcher context must remain active") + default: + } +} + +func TestHasUnboundAgentSessionExpiresRunningGraceWindow(t *testing.T) { + dataRoot := t.TempDir() + mgr := newR3TestManager(t, dataRoot) + a := &App{ + cfg: &config.Config{DataRoot: dataRoot}, + pluginMgr: mgr, + } + vm := driver.VMInfo{DriverID: driver.BuiltinReimsMacOSDriverID, Name: "tahoe-unbound", State: "running"} + key := vm.Ref().Key() + a.lastVMs = []driver.VMListItem{{DriverID: vm.DriverID, Name: vm.Name, State: "running"}} + a.beginAgentSession(mgr, "builtin.macos.autoinstall", vm, "AutoInstall", "stage1", "lock", true) + + if !a.hasUnboundAgentSession() { + t.Fatal("freshly started running unbound session should request fast polling") + } + + // Once unboundSince passes sessionDiscoverGraceWindow, fast 500ms polling stops. + a.sessionMu.Lock() + a.agentSessions[key].unboundSince = time.Now().Add(-sessionDiscoverGraceWindow - time.Second) + a.sessionMu.Unlock() + if a.hasUnboundAgentSession() { + t.Fatal("running session with permanently missing PID must exit 500ms fast polling after grace window") + } + + // Restarting / rebinding refreshes unboundSince so fast discovery resumes. + a.sessionMu.Lock() + a.agentSessions[key].unboundSince = time.Now() + a.sessionMu.Unlock() + if !a.hasUnboundAgentSession() { + t.Fatal("refreshed unboundSince should re-enable fast discovery") + } +} + +func TestResolveConfirmRequestConcurrentWithCancelNeverPanics(t *testing.T) { + for i := 0; i < 100; i++ { + a := &App{ + confirmPending: map[string]chan ConfirmResolution{}, + } + ch := make(chan ConfirmResolution, 1) + a.confirmPending["confirm-1"] = ch + + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + _ = a.ResolveConfirmRequest("confirm-1", true, 30, false) + }() + go func() { + defer wg.Done() + a.cancelPendingConfirmations() + }() + wg.Wait() + } +} + +func TestClearTelemetryColdRebootPreservePreventsStaleReuse(t *testing.T) { + a := &App{} + key := vmKey("cold-reboot-abort") + a.recordTelemetryMilestone(key, "serial:xnu") + a.recordTelemetryQemuError(key, "stale qemu warning") + a.recordTelemetryColdReboot(key) + // Simulate cold-reboot watcher aborting before StartVM. + a.clearTelemetryColdRebootPreserve(key) + // Subsequent normal manual boot must reset stale milestones and errors. + a.resetTelemetryForBoot(key, t.TempDir()) + + a.telemetryMu.Lock() + st := a.vmTelemetry[key] + milestones := len(st.milestones) + qemuErrs := len(st.qemuErrors) + a.telemetryMu.Unlock() + if milestones != 0 || qemuErrs != 0 { + t.Fatalf("expected cleared preserve flag to reset telemetry on next boot, got milestones=%d errors=%d", milestones, qemuErrs) + } +} diff --git a/internal/app/review_fixes_test.go b/internal/app/review_fixes_test.go new file mode 100644 index 0000000..4e5fe16 --- /dev/null +++ b/internal/app/review_fixes_test.go @@ -0,0 +1,397 @@ +package app + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "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/macos/installer" + "github.com/Nwflower/reims-go/internal/plugin" + "github.com/Nwflower/reims-go/internal/plugin/builtin" +) + +func TestConfirmPromptEmitsResolvedOnTimeoutAndRejectsExpiredID(t *testing.T) { + prevTimeout := confirmPromptTimeout + confirmPromptTimeout = 40 * time.Millisecond + t.Cleanup(func() { confirmPromptTimeout = prevTimeout }) + + a := &App{cfg: &config.Config{DataRoot: t.TempDir()}} + var emittedID string + dismissed := make(chan ConfirmResolvedEvent, 2) + a.confirmEmit = func(p ConfirmPrompt) { emittedID = p.ID } + a.confirmDismiss = func(id, reason string) { + dismissed <- ConfirmResolvedEvent{ID: id, Reason: reason} + } + + res, err := a.requestHostConfirm(context.Background(), nil, nil, "test.plugin", ConfirmPrompt{ + Kind: "protected_phase", + Title: "Confirm", + Message: "Allow?", + }) + if err != nil { + t.Fatalf("requestHostConfirm returned unexpected error on timeout: %v", err) + } + if res.Approved || res.Reason != "timeout" { + t.Fatalf("expected timeout resolution, got %+v", res) + } + select { + case ev := <-dismissed: + if ev.ID != emittedID || ev.Reason != "timeout" { + t.Fatalf("unexpected confirmDismiss event: %+v (want id=%q reason=timeout)", ev, emittedID) + } + case <-time.After(time.Second): + t.Fatal("expected confirmDismiss to fire on timeout") + } + + // Late user click on expired confirmation must return an error, not silent nil. + if err := a.ResolveConfirmRequest(emittedID, true, 30, false); err == nil { + t.Fatal("ResolveConfirmRequest must return error for expired/unknown ID") + } +} + +func TestEndAgentSessionRevokesProtectedPhaseOnNonCompletedExit(t *testing.T) { + ct := newConsoleTestApp(t) + a := ct.app + const pid = "thirdparty.agent" + vmKey := ct.ref.Key() + + // Non-ephemeral plugin starts session and holds an approved protected-phase grant. + a.beginAgentSession(nil, pid, driver.VMInfo{ + DriverID: ct.ref.DriverID, + Name: ct.ref.Name, + }, "Agent", "working", "auto", false) + a.grantProtectedPhase(pid, vmKey, driver.PhaseInstaller, 30, false) + if _, ok := a.lookupProtectedPhaseGrant(pid, vmKey); !ok { + t.Fatal("expected protected phase grant active before session end") + } + + // Ending with non-completed status (e.g. failed/stopped) must still revoke grant. + a.sessionMu.Lock() + a.agentSessions[vmKey].status = "failed" + a.sessionMu.Unlock() + a.endAgentSession(nil, pid, vmKey, "session_ended") + + if _, ok := a.lookupProtectedPhaseGrant(pid, vmKey); ok { + t.Fatal("protected-phase grant must be revoked when non-ephemeral session ends non-completed") + } +} + +func TestProtectedPhaseDenialCooldownAndCrossPluginIsolation(t *testing.T) { + prevCooldown := protectedPhaseDenialCooldown + protectedPhaseDenialCooldown = 50 * time.Millisecond + t.Cleanup(func() { protectedPhaseDenialCooldown = prevCooldown }) + + ct := newConsoleTestApp(t) + a := ct.app + vmKey := ct.ref.Key() + if err := os.WriteFile(filepath.Join(ct.vmRoot, "dev", "phase"), []byte(driver.PhaseInstaller), 0o644); err != nil { + t.Fatal(err) + } + + // Plugin B owns a completed overlay on this VM. + a.sessionMu.Lock() + a.completedOverlays = map[string]completedOverlayEntry{ + vmKey: {pluginID: "plugin.b", driverID: ct.ref.DriverID, vmName: ct.ref.Name, pid: 1234}, + } + a.sessionMu.Unlock() + + // Plugin A denial must NOT wipe Plugin B's completed overlay. + a.handlePluginPermissionDeniedForVM(nil, "plugin.a", vmKey, ct.ref.Name, "permission_denied") + if !a.isCompletedOverlay(vmKey) { + t.Fatal("Plugin A permission denial must not dismiss Plugin B's completed overlay") + } + + // Denial cooldown blocks immediate retry spam, then expires so user can re-approve. + prompts := make(chan ConfirmPrompt, 4) + a.confirmEmit = func(p ConfirmPrompt) { prompts <- p } + vmInfo := driver.VMInfo{DriverID: ct.ref.DriverID, Name: ct.ref.Name, Phase: driver.PhaseInstaller} + a.recordProtectedPhaseDenial(nil, nil, "plugin.a", vmKey, ct.ref.Name, driver.PhaseInstaller) + if err := a.authorizeProtectedPhase(context.Background(), nil, "plugin.a", vmInfo, driver.PhaseInstaller, false, false); err == nil || !strings.Contains(err.Error(), "confirmation_denied") { + t.Fatalf("expected confirmation_denied during cooldown, got %v", err) + } + time.Sleep(80 * time.Millisecond) + if err := a.authorizeProtectedPhase(context.Background(), nil, "plugin.a", vmInfo, driver.PhaseInstaller, false, false); err == nil || !strings.Contains(err.Error(), "confirmation_required") { + t.Fatalf("expected fresh confirmation_required after denial cooldown expired, got %v", err) + } + select { + case p := <-prompts: + _ = a.ResolveConfirmRequest(p.ID, true, 30, false) + case <-time.After(time.Second): + t.Fatal("expected confirmation prompt after cooldown expired") + } +} + +func TestActiveAgentSessionsAndOverlayAccessRaceFree(t *testing.T) { + a := &App{cfg: &config.Config{DataRoot: t.TempDir()}, pollWake: make(chan struct{}, 8)} + vm := driver.VMInfo{DriverID: driver.BuiltinReimsMacOSDriverID, Name: "race-vm"} + vmKey := vm.Ref().Key() + a.beginAgentSession(nil, "builtin.macos.autoinstall", vm, "Auto-Install", "stage1", "lock", true) + + var wg sync.WaitGroup + stop := make(chan struct{}) + for i := 0; i < 4; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for { + select { + case <-stop: + return + default: + _ = a.activeAgentSessions() + } + } + }() + } + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < 50; i++ { + a.handlePhysicalUserTakeover(vmKey, "mouse_move") + _ = a.PauseAgentSession(vm.DriverID, vm.Name) + _ = a.ResumeAgentSession(vm.DriverID, vm.Name) + a.syncAutoInstallSessionProgress(vmKey, "builtin.macos.autoinstall", "stage2", "working") + } + close(stop) + }() + wg.Wait() + a.closeAgentSessions() +} + +func TestResumeAutoInstallCreatesSessionAndWatcherWithoutLiveSession(t *testing.T) { + dataRoot := t.TempDir() + cfg := config.Default() + cfg.DataRoot = dataRoot + a := &App{cfg: cfg, pollWake: make(chan struct{}, 4)} + + 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 + + const testPlugin = "test.resume.autoinstall" + const vmName = "resume-vm" + vmKey := vmKeyForDriver(driver.BuiltinReimsMacOSDriverID, vmName) + + ep := &stubInProcessAutoInstallEndpoint{ + onCall: func(method string, params any) (any, error) { + switch method { + case "autoinstall/resume": + return map[string]any{ + "vm": vmKey, + "stage": "stage3_install_wait", + "status": "running", + "save_unlock_credential": false, + }, nil + case "autoinstall/status": + return map[string]any{ + "vm": vmKey, + "stage": "stage6_desktop_ready", + "status": "completed", + }, nil + default: + return map[string]any{"ok": true}, nil + } + }, + } + if err := mgr.Registry().Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ + Schema: 1, + ID: testPlugin, + Version: "1.0.0", + Name: plugin.LocalizedText{EnUS: "Stub AutoInstall"}, + Permissions: []string{"vm:read", "vm:screen", "qmp:write", "vm:control"}, + Contributes: plugin.Contributes{ + AutoInstallers: []plugin.AutoInstallerContribution{{ + ID: "stub", + Title: plugin.LocalizedText{EnUS: "Stub AutoInstall"}, + GuestFamilies: []string{"macos"}, + }}, + }, + }, + Source: plugin.SourceBuiltin, + Trust: plugin.TrustOfficial, + Desired: true, + ApprovedPermissions: []string{"vm:read", "vm:screen", "qmp:write", "vm:control"}, + Activate: func(_ context.Context, sc *plugin.Scope) error { + sc.Registry().RegisterInProcessEndpoint(sc, ep) + return nil + }, + }); err != nil { + t.Fatal(err) + } + mgr.Registry().Reconcile(context.Background()) + + prevInterval := autoInstallWatchInterval + autoInstallWatchInterval = 15 * time.Millisecond + t.Cleanup(func() { autoInstallWatchInterval = prevInterval }) + + if _, err := a.ResumeAutoInstall(testPlugin, driver.BuiltinReimsMacOSDriverID, vmName); err != nil { + t.Fatalf("ResumeAutoInstall: %v", err) + } + if !a.hasActiveAgentSessionOwnedBy(vmKey, testPlugin) { + t.Fatal("ResumeAutoInstall without prior live session must establish an active Agent session") + } + if _, ok := a.lookupProtectedPhaseGrant(testPlugin, vmKey); !ok { + t.Fatal("ResumeAutoInstall without prior live session must establish protected-phase grant") + } + + // Watcher must poll status=completed and tear down the session + grant cleanly. + waitFor(t, "watcher ends resumed session on completion", func() bool { + return !a.hasActiveAgentSession(vmKey) + }) + if _, ok := a.lookupProtectedPhaseGrant(testPlugin, vmKey); ok { + t.Fatal("protected-phase grant must be revoked after watched resumed session completes") + } +} + +type stubInProcessAutoInstallEndpoint struct { + onCall func(method string, params any) (any, error) +} + +func (s *stubInProcessAutoInstallEndpoint) Call(_ context.Context, method string, params any, out any) error { + if s.onCall == nil { + return errors.New("no handler") + } + res, err := s.onCall(method, params) + if err != nil { + return err + } + if out != nil { + b, err := json.Marshal(res) + if err != nil { + return err + } + return json.Unmarshal(b, out) + } + return nil +} + +func (s *stubInProcessAutoInstallEndpoint) Notify(string, any) {} + +func TestProvisionReadyMarkerPersistsAcrossResetAndClearsOnFinishInstall(t *testing.T) { + vmDir := t.TempDir() + vmKey := vmKeyForDriver(driver.BuiltinReimsMacOSDriverID, "persist-ready") + a := &App{ + pendingChanges: map[string][]PendingChange{}, + lastVMs: []driver.VMListItem{{ + DriverID: driver.BuiltinReimsMacOSDriverID, + Name: "persist-ready", + Dir: vmDir, + State: "running", + }}, + } + + installer.WriteProvisionReadyMarker(vmDir) + // Boot telemetry reset must retain serial:provision_ready while marker exists. + a.resetTelemetryForBoot(vmKey, vmDir) + keys := a.provisionReadyVMKeys() + found := false + for _, k := range keys { + if k == vmKey { + found = true + } + } + if !found { + t.Fatalf("expected %q in provisionReadyVMKeys after resetTelemetryForBoot, got %v", vmKey, keys) + } + + // Even with empty in-memory telemetry (after app restart), provisionReadyVMKeys finds persisted marker. + a.telemetryMu.Lock() + a.vmTelemetry = nil + a.telemetryMu.Unlock() + keys = a.provisionReadyVMKeys() + found = false + for _, k := range keys { + if k == vmKey { + found = true + } + } + if !found { + t.Fatalf("expected %q in provisionReadyVMKeys after app restart, got %v", vmKey, keys) + } + + // applyFinishInstallResult mirrors pendingChanges and clears serial:provision_ready. + installer.ClearProvisionReadyMarker(vmDir) + a.recordTelemetryMilestone(vmKey, "serial:provision_ready") + a.applyFinishInstallResult(driver.BuiltinReimsMacOSDriverID, "persist-ready", map[string]any{ + "running": true, + "installer_ejected": true, + "network_enabled": true, + "upgraded_nvme": true, + "recovery_pending": true, + }) + a.mu.Lock() + pending := a.pendingChanges[vmKey] + a.mu.Unlock() + if len(pending) != 4 { + t.Fatalf("expected 4 pendingChanges mirrored from finish_install result, got %+v", pending) + } + if len(a.provisionReadyVMKeys()) != 0 { + t.Fatalf("expected serial:provision_ready cleared after finish_install, got %v", a.provisionReadyVMKeys()) + } +} + +func TestBuiltinAutoInstallPluginSettingsKeyNormalization(t *testing.T) { + dataRoot := t.TempDir() + cfg := config.Default() + cfg.DataRoot = dataRoot + a := &App{cfg: cfg, pollWake: make(chan struct{}, 4)} + + mgr, err := plugin.NewManager(plugin.ManagerOptions{ + DataRoot: dataRoot, + HostVersion: "0.3.0", + }) + if err != nil { + t.Fatal(err) + } + defer mgr.Close() + a.pluginMgr = mgr + cb := builtin.HostCallbacks{ + GetConfig: func() config.Config { return *cfg }, + PluginDataDir: mgr.Layout().DataDir, + PluginLogPath: mgr.Layout().LogPath, + CallHostAPI: mgr.CallHostAPI, + } + _ = builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor) + _ = guest.Register(mgr.Registry(), cb, mgr.DesiredFor) + mgr.Registry().Reconcile(context.Background()) + + vmKey := vmKeyForDriver(driver.BuiltinReimsMacOSDriverID, "norm-vm") + if got := a.normalizeVMKey("norm-vm"); got != vmKey { + t.Fatalf("normalizeVMKey(unprefixed) = %q, want %q", got, vmKey) + } + if got := a.normalizeVMKey(vmKey); got != vmKey { + t.Fatalf("normalizeVMKey(prefixed) = %q, want %q", got, vmKey) + } +} + +func TestRestartMacOSVMLockedDoesNotForceStopOnNonTimeoutError(t *testing.T) { + a := &App{cfg: &config.Config{DataRoot: t.TempDir()}} + stopped, err := a.restartMacOSVMLocked(context.Background(), "demo", 5*time.Second) + if stopped { + t.Fatal("expected stopped=false when graceful stop fails with non-timeout error") + } + if err == nil || !strings.Contains(err.Error(), "graceful stop before restart") { + t.Fatalf("expected wrapped non-timeout graceful stop error, got %v", err) + } +} diff --git a/internal/app/stage_a_host_test.go b/internal/app/stage_a_host_test.go new file mode 100644 index 0000000..8a6de15 --- /dev/null +++ b/internal/app/stage_a_host_test.go @@ -0,0 +1,292 @@ +package app + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "image/png" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/plugin" + "github.com/Nwflower/reims-go/pkg/pluginproto" +) + +func TestProtectedPhaseConfirmationLifecycle(t *testing.T) { + ct := newConsoleTestApp(t) + a := ct.app + const pid = "reims.autoinstall" + a.grantEphemeralVMAccess(pid, ct.ref.Key()) + + if err := os.WriteFile(filepath.Join(ct.vmRoot, "dev", "phase"), []byte(driver.PhaseInstaller), 0o644); err != nil { + t.Fatal(err) + } + + prompts := make(chan ConfirmPrompt, 4) + a.confirmEmit = func(p ConfirmPrompt) { prompts <- p } + + // First screenshot during installer phase triggers async confirmation and returns confirmation_required. + _, _, err := a.resolveComputerUseVM(context.Background(), nil, pid, ct.ref.Key(), false) + if err == nil || !strings.Contains(err.Error(), "confirmation_required") { + t.Fatalf("first installer call err = %v, want confirmation_required", err) + } + var p ConfirmPrompt + select { + case p = <-prompts: + case <-time.After(2 * time.Second): + t.Fatal("expected confirmation prompt to be emitted") + } + if p.Kind != "protected_phase" || p.Phase != driver.PhaseInstaller || !p.AllowDurationChoice { + t.Fatalf("unexpected prompt: %+v", p) + } + + // Approving with until_phase_exit unlocks both screenshot and write calls. + if err := a.ResolveConfirmRequest(p.ID, true, 30, true); err != nil { + t.Fatal(err) + } + waitFor(t, "protected phase grant active", func() bool { + _, _, err := a.resolveComputerUseVM(context.Background(), nil, pid, ct.ref.Key(), false) + return err == nil + }) + + // Leaving installer -> normal revokes the until_phase_exit grant cleanly. + a.trackVMPhaseTransitions([]driver.VMListItem{{DriverID: ct.ref.DriverID, Name: "dev", State: "running", Phase: driver.PhaseInstaller}}) + a.trackVMPhaseTransitions([]driver.VMListItem{{DriverID: ct.ref.DriverID, Name: "dev", State: "running", Phase: driver.PhaseNormal}}) + + // Re-entering recovery must ask for confirmation again. + if err := os.WriteFile(filepath.Join(ct.vmRoot, "dev", "phase"), []byte(driver.PhaseRecovery), 0o644); err != nil { + t.Fatal(err) + } + _, _, err = a.resolveComputerUseVM(context.Background(), nil, pid, ct.ref.Key(), false) + if err == nil || !strings.Contains(err.Error(), "confirmation_required") { + t.Fatalf("after leaving phase, recovery err = %v, want confirmation_required", err) + } + p2 := <-prompts + if err := a.ResolveConfirmRequest(p2.ID, false, 0, false); err != nil { + t.Fatal(err) + } + waitFor(t, "denial recorded", func() bool { + _, _, err := a.resolveComputerUseVM(context.Background(), nil, pid, ct.ref.Key(), false) + return err != nil && strings.Contains(err.Error(), "confirmation_denied") + }) +} + +func TestAgentSessionTakeoverAndStop(t *testing.T) { + ct := newConsoleTestApp(t) + a := ct.app + const pid = "reims.autoinstall" + a.grantEphemeralVMAccess(pid, ct.ref.Key()) + + // Implicit session opens on first write call even without session.begin. + _, _, err := a.resolveComputerUseVM(context.Background(), nil, pid, ct.ref.Key(), true) + if err != nil { + t.Fatalf("write call in normal phase failed: %v", err) + } + sessions := a.activeAgentSessions() + if len(sessions) != 1 || sessions[0].VMKey != ct.ref.Key() { + t.Fatalf("expected implicit session, got %+v", sessions) + } + + // Physical takeover pauses writes immediately with user_takeover. + zero := 0 // manual resume mode + a.cfg.AgentTakeoverPauseSec = &zero + a.handlePhysicalUserTakeover(ct.ref.Key(), "mouse_move") + if _, _, err := a.resolveComputerUseVM(context.Background(), nil, pid, ct.ref.Key(), true); err == nil || !strings.Contains(err.Error(), "user_takeover") { + t.Fatalf("write during takeover err = %v, want user_takeover", err) + } + + // Manual resume restores writes. + if err := a.ResumeAgentSession(ct.ref.DriverID, "dev"); err != nil { + t.Fatal(err) + } + if _, _, err := a.resolveComputerUseVM(context.Background(), nil, pid, ct.ref.Key(), true); err != nil { + t.Fatalf("write after resume failed: %v", err) + } + + // StopAgentSession cancels in-flight context, clears session, and revokes phase auth within 1s. + a.grantProtectedPhase(pid, ct.ref.Key(), driver.PhaseInstaller, 30, true) + callCtx, cancel := a.withSessionContext(context.Background(), ct.ref.Key()) + defer cancel() + start := time.Now() + if err := a.StopAgentSession(ct.ref.DriverID, "dev"); err != nil { + t.Fatal(err) + } + select { + case <-callCtx.Done(): + case <-time.After(time.Second): + t.Fatal("in-flight session context was not canceled within 1s") + } + if time.Since(start) > time.Second { + t.Fatalf("StopAgentSession took %v, want < 1s", time.Since(start)) + } + if len(a.activeAgentSessions()) != 0 { + t.Fatalf("session still active after Stop") + } + if _, ok := a.lookupProtectedPhaseGrant(pid, ct.ref.Key()); ok { + t.Fatal("protected phase grant was not revoked on Stop") + } +} + +func TestScreenshotRegionPNGAndTelemetryRedaction(t *testing.T) { + ct := newConsoleTestApp(t) + a := ct.app + const pid = "reims.autoinstall" + a.grantEphemeralVMAccess(pid, ct.ref.Key()) + + // Request cropped lossless PNG region from the driver console frame (40x30 in stub). + rawReq, _ := json.Marshal(map[string]any{ + "vm": ct.ref.Key(), + "format": "png", + "region": map[string]int{"x": 4, "y": 4, "width": 20, "height": 12}, + }) + res, err := a.handleComputerUseScreenshot(context.Background(), rawReq, nil, pid) + if err != nil { + t.Fatalf("handleComputerUseScreenshot region png: %v", err) + } + m := res.(pluginproto.ScreenshotResult) + if m.MIMEType != "image/png" || m.Width != 20 || m.Height != 12 { + t.Fatalf("unexpected screenshot result: %v x %v (%v)", m.Width, m.Height, m.MIMEType) + } + rawPNG, err := base64.StdEncoding.DecodeString(m.Data) + if err != nil { + t.Fatal(err) + } + decoded, err := png.Decode(bytes.NewReader(rawPNG)) + if err != nil || decoded.Bounds().Dx() != 20 || decoded.Bounds().Dy() != 12 { + t.Fatalf("decoded png mismatch: err=%v", err) + } + + // Telemetry redacts sensitive serial/UUID/MAC values from QEMU errors. + a.recordTelemetryMilestone(ct.ref.Key(), "serial:xnu") + a.recordTelemetryColdReboot(ct.ref.Key()) + a.recordTelemetryQemuError(ct.ref.Key(), "ERROR serial=C02XYZ123456 mac=52:54:00:aa:bb:cc uuid=12345678-1234-1234-1234-1234567890ab") + telReq, _ := json.Marshal(map[string]any{"vm": ct.ref.Key()}) + telRes, err := a.handleComputerUseVMTelemetry(context.Background(), telReq, nil, pid) + if err != nil { + t.Fatalf("handleComputerUseVMTelemetry: %v", err) + } + tm := telRes.(map[string]any) + if tm["cold_reboot_count"] != 1 { + t.Fatalf("cold_reboot_count = %v, want 1", tm["cold_reboot_count"]) + } + errs := tm["qemu_errors"].([]string) + if len(errs) != 1 || strings.Contains(errs[0], "52:54:00:aa:bb:cc") || strings.Contains(errs[0], "12345678-1234-1234-1234-1234567890ab") { + t.Fatalf("telemetry qemu_errors not redacted: %+v", errs) + } +} + +func TestTypeSecretPermissionPolicy(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) + } + t.Cleanup(mgr.Close) + register := func(id string, trust plugin.TrustLevel, perms, approved []string) { + if err := mgr.Registry().Register(plugin.PluginDef{ + Manifest: plugin.Manifest{Schema: 1, ID: id, Version: "1.0.0", Name: plugin.LocalizedText{EnUS: id}, Permissions: perms}, + Source: plugin.SourceLocal, + Trust: trust, + Desired: true, + ApprovedPermissions: approved, + }); err != nil { + t.Fatal(err) + } + } + register("reims.autoinstall", plugin.TrustOfficial, []string{"qmp:write"}, []string{"qmp:write"}) + register("community.authorized", plugin.TrustCommunity, []string{"qmp:write"}, []string{"qmp:write"}) + register("community.unapproved", plugin.TrustCommunity, []string{"qmp:write"}, nil) + register("community.readonly", plugin.TrustCommunity, []string{"vm:read"}, nil) + mgr.Registry().Reconcile(context.Background()) + + if err := authorizeHostMethod(mgr, "reims.autoinstall", "host/console.typeSecret"); err != nil { + t.Fatalf("official plugin with approved qmp:write should be authorized for typeSecret: %v", err) + } + if err := authorizeHostMethod(mgr, "community.authorized", "host/console.typeSecret"); err != nil { + t.Fatalf("community plugin with approved qmp:write should be authorized for typeSecret: %v", err) + } + if err := authorizeHostMethod(mgr, "community.unapproved", "host/console.typeSecret"); err == nil { + t.Fatal("plugin with unapproved qmp:write must be rejected from typeSecret") + } + if err := authorizeHostMethod(mgr, "community.readonly", "host/console.typeSecret"); err == nil { + t.Fatal("plugin without qmp:write must be rejected from typeSecret") + } +} + +func TestDownloadCustomMirrorRequiresConfirmationAndSHA256(t *testing.T) { + body := []byte("rapidocr-bundle-bytes") + sum := sha256.Sum256(body) + sumHex := hex.EncodeToString(sum[:]) + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write(body) + })) + defer srv.Close() + + e := newDownloadTestEnv(t, "https://allowed.example.com") + e.app.confirmEmit = func(p ConfirmPrompt) { + if p.Kind != "custom_mirror" { + t.Errorf("expected custom_mirror prompt, got %+v", p) + } + go func() { _ = e.app.ResolveConfirmRequest(p.ID, true, 0, false) }() + } + + // Unregistered plugin must NEVER bypass AuthorizeNetOrigin via allow_custom_mirror. + if _, err := e.start(t, "unknown.plugin", map[string]any{ + "url": srv.URL + "/bundle.zip", + "sha256": sumHex, + "dest": "ocr/bundle.zip", + "allow_custom_mirror": true, + }); err == nil || !strings.Contains(err.Error(), "unknown plugin") { + t.Fatalf("unknown plugin custom mirror err = %v, want unknown plugin error", err) + } + + // Custom mirror URL with userinfo must be rejected even with pinned sha256. + if _, err := e.start(t, e.plugin, map[string]any{ + "url": "https://user:pass@mirror.example.com/bundle.zip", + "sha256": sumHex, + "dest": "ocr/bundle.zip", + "allow_custom_mirror": true, + }); err == nil || !strings.Contains(err.Error(), "user info") { + t.Fatalf("custom mirror with userinfo err = %v, want user info error", err) + } + + // Custom mirror without sha256 must be rejected. + if _, err := e.start(t, e.plugin, map[string]any{ + "url": srv.URL + "/bundle.zip", + "dest": "ocr/bundle.zip", + "allow_custom_mirror": true, + }); err == nil || !strings.Contains(err.Error(), "sha256") { + t.Fatalf("custom mirror without sha256 err = %v, want sha256 error", err) + } + + // Custom mirror with pinned sha256 + user confirmation succeeds. + id, err := e.start(t, e.plugin, map[string]any{ + "url": srv.URL + "/bundle.zip", + "sha256": sumHex, + "dest": "ocr/bundle.zip", + "connect_timeout_ms": 5000, + "stall_timeout_ms": 15000, + "allow_custom_mirror": true, + }) + if err != nil { + t.Fatalf("custom mirror download failed: %v", err) + } + ev := e.final(t, id) + if ev.Status != "done" { + t.Fatalf("download status = %+v, want done", ev) + } +} diff --git a/internal/app/suspend_flow.go b/internal/app/suspend_flow.go index d9de11b..5405fe6 100644 --- a/internal/app/suspend_flow.go +++ b/internal/app/suspend_flow.go @@ -139,9 +139,12 @@ func (a *App) ResumeVM(driverID, name string) error { a.watchWin10ColdReboot(ref.Name, addr) } } - a.startVMMonitor(ref.Name, vm, startAt) + a.resumeVMMonitor(ref.Name, vm, startAt) } a.emitVMLogForDriver(ref.DriverID, ref.Name, fmt.Sprintf("Resumed %s in %.1fs", ref.Name, time.Since(startAt).Seconds())) + if a.hasActiveAgentSession(key) { + go a.refreshActiveAgentSessionAfterStart(key) + } return nil } diff --git a/internal/app/vm_monitor.go b/internal/app/vm_monitor.go index ba318b9..22f2f37 100644 --- a/internal/app/vm_monitor.go +++ b/internal/app/vm_monitor.go @@ -53,6 +53,176 @@ func waitVMMonitorDone(done <-chan struct{}) { } } +type telemetryMilestone struct { + Key string `json:"key"` + Count int `json:"count"` + At string `json:"at"` +} + +type vmTelemetryState struct { + milestones map[string]telemetryMilestone + qemuErrors []string + diskBytes int64 + diskDeltaBytes int64 + cpuPercent float64 + coldRebootCount int + preserveNextBoot bool + updatedAt time.Time +} + +func (a *App) ensureTelemetryLocked(key string) *vmTelemetryState { + if a.vmTelemetry == nil { + a.vmTelemetry = map[string]*vmTelemetryState{} + } + st := a.vmTelemetry[key] + if st == nil { + st = &vmTelemetryState{ + milestones: map[string]telemetryMilestone{}, + cpuPercent: -1, + } + a.vmTelemetry[key] = st + } + return st +} + +func (a *App) recordTelemetryMilestone(key, milestoneKey string) { + if key == "" || milestoneKey == "" { + return + } + now := time.Now().UTC().Format(time.RFC3339) + a.telemetryMu.Lock() + st := a.ensureTelemetryLocked(key) + prev := st.milestones[milestoneKey] + prev.Key = milestoneKey + prev.Count++ + prev.At = now + st.milestones[milestoneKey] = prev + st.updatedAt = time.Now() + a.telemetryMu.Unlock() +} + +func (a *App) recordTelemetryQemuError(key, line string) { + if key == "" || strings.TrimSpace(line) == "" { + return + } + redacted := host.RedactText(strings.TrimSpace(line)) + a.telemetryMu.Lock() + st := a.ensureTelemetryLocked(key) + st.qemuErrors = append(st.qemuErrors, redacted) + if len(st.qemuErrors) > 32 { + st.qemuErrors = st.qemuErrors[len(st.qemuErrors)-32:] + } + st.updatedAt = time.Now() + a.telemetryMu.Unlock() +} + +func (a *App) recordTelemetrySample(key string, diskBytes, diskDelta int64, cpuPct float64) { + if key == "" { + return + } + a.telemetryMu.Lock() + st := a.ensureTelemetryLocked(key) + st.diskBytes = diskBytes + st.diskDeltaBytes = diskDelta + st.cpuPercent = cpuPct + st.updatedAt = time.Now() + a.telemetryMu.Unlock() +} + +func (a *App) recordTelemetryColdReboot(key string) { + if key == "" { + return + } + a.telemetryMu.Lock() + st := a.ensureTelemetryLocked(key) + st.coldRebootCount++ + st.preserveNextBoot = true + st.updatedAt = time.Now() + a.telemetryMu.Unlock() +} + +func (a *App) clearTelemetryColdRebootPreserve(key string) { + if key == "" { + return + } + a.telemetryMu.Lock() + if st := a.vmTelemetry[key]; st != nil { + st.preserveNextBoot = false + } + a.telemetryMu.Unlock() +} + +func (a *App) clearTelemetryMilestone(key, milestoneKey string) { + if key == "" || milestoneKey == "" { + return + } + a.telemetryMu.Lock() + if st := a.vmTelemetry[key]; st != nil && st.milestones != nil { + delete(st.milestones, milestoneKey) + st.updatedAt = time.Now() + } + a.telemetryMu.Unlock() +} + +func (a *App) resetTelemetryForBoot(key, vmDir string) { + if key == "" { + return + } + a.telemetryMu.Lock() + st := a.ensureTelemetryLocked(key) + preserve := st.preserveNextBoot + st.preserveNextBoot = false + if !preserve { + prevReady, hadReady := st.milestones["serial:provision_ready"] + st.milestones = map[string]telemetryMilestone{} + if a.hasProvisionReadyMarker(vmDir) { + if !hadReady { + prevReady = telemetryMilestone{ + Key: "serial:provision_ready", + Count: 1, + At: time.Now().UTC().Format(time.RFC3339), + } + } + st.milestones["serial:provision_ready"] = prevReady + } + st.qemuErrors = nil + } else if a.hasProvisionReadyMarker(vmDir) { + if _, hadReady := st.milestones["serial:provision_ready"]; !hadReady { + st.milestones["serial:provision_ready"] = telemetryMilestone{ + Key: "serial:provision_ready", + Count: 1, + At: time.Now().UTC().Format(time.RFC3339), + } + } + } + st.diskDeltaBytes = 0 + st.cpuPercent = -1 + st.updatedAt = time.Now() + a.telemetryMu.Unlock() +} + +func (a *App) preserveTelemetryForResume(key, vmDir string) { + if key == "" { + return + } + a.telemetryMu.Lock() + st := a.ensureTelemetryLocked(key) + st.preserveNextBoot = false + if a.hasProvisionReadyMarker(vmDir) { + if _, hadReady := st.milestones["serial:provision_ready"]; !hadReady { + st.milestones["serial:provision_ready"] = telemetryMilestone{ + Key: "serial:provision_ready", + Count: 1, + At: time.Now().UTC().Format(time.RFC3339), + } + } + } + st.diskDeltaBytes = 0 + st.cpuPercent = -1 + st.updatedAt = time.Now() + a.telemetryMu.Unlock() +} + func stopVMMonitor(name string) { vmMonitors.mu.Lock() cur, ok := vmMonitors.entries[name] @@ -94,6 +264,14 @@ func stopAllVMMonitors() { } func (a *App) startVMMonitor(name string, detail driver.VMInfo, startAt time.Time) { + a.startVMMonitorWithReset(name, detail, startAt, true) +} + +func (a *App) resumeVMMonitor(name string, detail driver.VMInfo, startAt time.Time) { + a.startVMMonitorWithReset(name, detail, startAt, false) +} + +func (a *App) startVMMonitorWithReset(name string, detail driver.VMInfo, startAt time.Time, resetTelemetry bool) { if detail.Directory == "" { stopVMMonitor(name) return @@ -147,11 +325,19 @@ func (a *App) startVMMonitor(name string, detail driver.VMInfo, startAt time.Tim serialPath := filepath.Join(detail.Directory, "logs", "serial.log") qemuPath := filepath.Join(detail.Directory, "logs", "qemu.log") diskPath := filepath.Join(detail.Directory, "disk.qcow2") + tKey := detail.Ref().Key() + if resetTelemetry { + a.resetTelemetryForBoot(tKey, detail.Directory) + } else { + a.preserveTelemetryForResume(tKey, detail.Directory) + } // Only read logs belonging to this boot (ignore files last touched before StartVM). serial := logTail{offset: initialLogOffset(serialPath, startAt)} qemu := logTail{offset: initialLogOffset(qemuPath, startAt)} seenEvents := map[string]bool{} + var lastXNURecordedAt time.Time + xnuRecordedForBoot := false lastDiskSize := fileSizeBytes(diskPath) var lastCPU time.Duration @@ -173,14 +359,43 @@ func (a *App) startVMMonitor(name string, detail driver.VMInfo, startAt time.Tim loc := a.locale() for _, line := range serial.read(serialPath) { a.emitPluginLogLine(name, "serial", line) - if key, msg := parseSerialMilestone(loc, line); msg != "" && !seenEvents[key] { - seenEvents[key] = true - a.emitVMLog(name, msg) + if key, msg := parseSerialMilestone(loc, line); msg != "" { + recordMilestone := true + switch key { + case "serial:boot": + xnuRecordedForBoot = false + case "serial:xnu": + // OpenCore/boot.efi logs both "#[EB|LOG:HANDOFF TO XNU]" and + // "End of efiboot serial output" milliseconds apart for one boot. + now := time.Now() + if xnuRecordedForBoot && now.Sub(lastXNURecordedAt) < 10*time.Second { + recordMilestone = false + } else { + xnuRecordedForBoot = true + lastXNURecordedAt = now + } + } + if recordMilestone { + a.recordTelemetryMilestone(tKey, key) + } + if !seenEvents[key] { + seenEvents[key] = true + a.emitVMLog(name, msg) + if key == "serial:provision_ready" { + a.writeProvisionReadyMarker(detail.Directory) + a.emitStateChangedEvent() + } + } } } for _, line := range qemu.read(qemuPath) { a.emitPluginLogLine(name, "qemu", line) if key, msg := parseQemuMilestone(loc, line); msg != "" { + if key != "" { + a.recordTelemetryMilestone(tKey, key) + } else if strings.HasPrefix(msg, "[QEMU] ") { + a.recordTelemetryQemuError(tKey, strings.TrimPrefix(msg, "[QEMU] ")) + } if key != "" && seenEvents[key] { continue } @@ -227,6 +442,7 @@ func (a *App) startVMMonitor(name string, detail driver.VMInfo, startAt time.Tim lastCPU = cpuNow hasLastCPU = true } + a.recordTelemetrySample(tKey, diskNow, diskDelta, cpuPct) elapsed := time.Since(startAt) inEarlyOrInstall := vmInfoBool(detail, "has_installer") || elapsed < 15*time.Minute @@ -332,12 +548,45 @@ func (t *logTail) read(path string) []string { return lines } +func (a *App) provisionReadyVMKeys() []string { + seen := map[string]bool{} + var out []string + a.telemetryMu.Lock() + for k, st := range a.vmTelemetry { + if st == nil { + continue + } + if _, ok := st.milestones["serial:provision_ready"]; ok && !seen[k] { + seen[k] = true + out = append(out, k) + } + } + a.telemetryMu.Unlock() + + a.mu.Lock() + vms := append([]driver.VMListItem(nil), a.lastVMs...) + a.mu.Unlock() + for _, vm := range vms { + if vm.Dir == "" { + continue + } + key := vmKeyForDriver(vm.DriverID, vm.Name) + if !seen[key] && a.hasProvisionReadyMarker(vm.Dir) { + seen[key] = true + out = append(out, key) + } + } + return out +} + func parseSerialMilestone(loc i18n.Locale, line string) (key, msg string) { switch { case strings.Contains(line, "BdsDxe: starting Boot"): return "serial:boot", i18n.T(loc, "monitor.serial.boot") case strings.Contains(line, "#[EB|LOG:HANDOFF TO XNU]"), strings.Contains(line, "End of efiboot serial output"): return "serial:xnu", i18n.T(loc, "monitor.serial.xnu") + case strings.Contains(line, "REIMS_PROVISION_BOOT_OK"): + return "serial:provision_ready", i18n.T(loc, "monitor.serial.provision_ready") default: return "", "" } diff --git a/internal/app/vm_poll.go b/internal/app/vm_poll.go index e3b9e97..ffb00ed 100644 --- a/internal/app/vm_poll.go +++ b/internal/app/vm_poll.go @@ -16,7 +16,8 @@ import ( // stopping and every pollSteady otherwise; each tick runs one `reims-ctl list`. // Start, stop and delete call wakePoll so their result shows up at once. const ( - pollBusy = 2 * time.Second + pollSessionDiscover = 500 * time.Millisecond + pollBusy = 2 * time.Second // Exits are caught at once by watchExits and GUI actions call wakePoll, so // the steady tick only has to notice VMs started or removed elsewhere (CLI). pollSteady = 10 * time.Second @@ -63,6 +64,11 @@ func (a *App) pollVMs(ctx context.Context) { next = pollBusy } a.mu.Unlock() + if a.hasUnboundAgentSession() { + next = pollSessionDiscover + } else if next > pollBusy && a.hasActiveAgentSessions() { + next = pollBusy + } timer.Reset(next) // reims-ctl keeps its state in the data folder; leave it alone until // setup has chosen one, and while it is open read-only. @@ -127,6 +133,8 @@ func (p *vmPoller) tick(ctx context.Context) { svc.SetTargets(targets) } a.syncFullscreenHotkeyTargets() + a.trackVMPhaseTransitions(vms) + a.syncAgentSessionsOnPoll() if tm != nil { tm.UpdateTooltip(trayTooltip(loc, vms)) } @@ -238,6 +246,8 @@ func (a *App) forgetVM(key string) { a.mu.Lock() delete(a.transitions, key) delete(a.pendingChanges, key) + delete(a.guideRecheckVMs, name) + delete(a.pendingGuideHandoffs, name) gt := a.guestTools a.mu.Unlock() if !parsed || ref.DriverID == driver.BuiltinReimsMacOSDriverID { diff --git a/internal/archtest/file_replace_test.go b/internal/archtest/file_replace_test.go index 8e5cd35..5f612c4 100644 --- a/internal/archtest/file_replace_test.go +++ b/internal/archtest/file_replace_test.go @@ -14,6 +14,8 @@ var renameOwners = map[string]bool{ "internal/atomicfile/atomicfile.go": true, "internal/fetch/fetch.go": true, // download "internal/fetch/validated.go": true, // validated restore image download + "internal/macos/autoinstall/ocr/fetch.go": true, // download + macOS may not import atomicfile, see macosHostImports + "internal/macos/autoinstall/runner/checkpoint.go": true, // macOS may not import atomicfile, see macosHostImports "internal/macos/installer/accelerated.go": true, // download "internal/macos/installer/hfs_image.go": true, // disk image "internal/macos/installer/oc_cache.go": true, // download diff --git a/internal/cli/autoinstall.go b/internal/cli/autoinstall.go new file mode 100644 index 0000000..6501fbb --- /dev/null +++ b/internal/cli/autoinstall.go @@ -0,0 +1,170 @@ +package cli + +import ( + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "os" + "strings" + "time" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/control" + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/i18n" +) + +// callDesktopAutoInstall is a seam overridden by CLI unit tests to verify +// desktop control-channel forwarding without spawning a desktop process. +var callDesktopAutoInstall = func(ctx context.Context, req control.AutoInstallRequest, out any) error { + return control.Call(ctx, control.HostPluginID, control.ChannelAutoInstall, req, out) +} + +var desktopPIDForAutoInstall = DesktopWindowPID + +func isDesktopDataRootMismatch(err error) bool { + return err != nil && strings.Contains(err.Error(), "data_root_mismatch") +} + +func isDesktopControlUnavailable(err error) bool { + if err == nil { + return false + } + if errors.Is(err, errors.ErrUnsupported) || errors.Is(err, os.ErrNotExist) { + return true + } + msg := strings.ToLower(err.Error()) + return strings.Contains(msg, "cannot find the file") || + strings.Contains(msg, "file does not exist") || + strings.Contains(msg, "no such file") || + strings.Contains(msg, "timed out") || + strings.Contains(msg, "unsupported") +} + +func cmdVMAutoInstall(cfg *config.Config, _ i18n.Locale, args []string) error { + if len(args) == 0 { + return errors.New("usage: reims-go vm autoinstall [flags] [vm]") + } + sub := args[0] + fs := flag.NewFlagSet("vm autoinstall "+sub, flag.ContinueOnError) + driverID := fs.String("driver", driver.BuiltinReimsMacOSDriverID, "Guest VM driver ID") + pluginID := fs.String("plugin", "", "Auto-installer plugin ID (default: first enabled provider)") + guestLang := fs.String("guest-lang", "zh-Hans:0", "Guest language with :0 US keyboard layout") + if err := fs.Parse(args[1:]); err != nil { + return err + } + + vmName := "" + if fs.NArg() > 0 { + vmName = strings.TrimSpace(fs.Arg(0)) + } + switch sub { + case "list", "preflight", "status": + case "resume": + if vmName == "" { + return errors.New("usage: reims-go vm autoinstall resume ") + } + case "stop": + if vmName == "" { + return errors.New("usage: reims-go vm autoinstall stop ") + } + case "diagnostic": + if vmName == "" { + return errors.New("usage: reims-go vm autoinstall diagnostic ") + } + default: + return fmt.Errorf("unknown vm autoinstall subcommand %q", sub) + } + + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + + // Live auto-install runners, overlays, input locks, and protected-phase + // grants live in the desktop process. Forward stateful subcommands there + // first so CLI and GUI never split-brain or launch doomed short-lived runners. + if sub == "status" || sub == "resume" || sub == "stop" || sub == "diagnostic" { + var desktopOut any + req := control.AutoInstallRequest{ + Action: sub, + DataRoot: cfg.DataRoot, + PluginID: strings.TrimSpace(*pluginID), + DriverID: *driverID, + VMName: vmName, + } + err := callDesktopAutoInstall(ctx, req, &desktopOut) + if err == nil { + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + return enc.Encode(desktopOut) + } + if sub == "resume" { + if isDesktopDataRootMismatch(err) { + return errors.New("auto-install resume requires the Reims-Go desktop app to be open on the same data directory") + } + if isDesktopControlUnavailable(err) { + return errors.New("auto-install resume requires the Reims-Go desktop app to be running; open the desktop app and resume from there or retry this command") + } + return err + } + if sub == "stop" && !isDesktopDataRootMismatch(err) { + if desktopPIDForAutoInstall() != 0 { + return fmt.Errorf("Reims-Go desktop app is running, but the control channel could not be reached (%w); stop auto-install from the desktop app to avoid leaving a live session running", err) + } + if !isDesktopControlUnavailable(err) { + return err + } + } + if (sub == "status" || sub == "diagnostic") && !isDesktopDataRootMismatch(err) && !isDesktopControlUnavailable(err) { + return err + } + } + + mgr, _, err := openCLIPluginManager(cfg, false) + if err != nil { + return err + } + defer mgr.Close() + + providers := mgr.Registry().AutoInstallers() + if sub == "list" { + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + return enc.Encode(providers) + } + if len(providers) == 0 { + return errors.New("no enabled auto-installer plugin found") + } + pid := strings.TrimSpace(*pluginID) + if pid == "" { + pid = providers[0].PluginID + } + + vmRef := "" + if vmName != "" { + vmRef = driver.NewVMRef(*driverID, vmName).Key() + } + + var method string + payload := map[string]any{"vm": vmRef} + switch sub { + case "preflight": + method = "autoinstall/preflight" + payload["guest_lang"] = *guestLang + case "status": + method = "autoinstall/status" + case "stop": + method = "autoinstall/stop" + case "diagnostic": + method = "autoinstall/diagnosticSummary" + } + + var out any + if err := mgr.CallSidecar(ctx, pid, method, payload, &out); err != nil { + return err + } + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + return enc.Encode(out) +} diff --git a/internal/cli/autoinstall_test.go b/internal/cli/autoinstall_test.go new file mode 100644 index 0000000..f05880b --- /dev/null +++ b/internal/cli/autoinstall_test.go @@ -0,0 +1,164 @@ +package cli + +import ( + "context" + "encoding/json" + "errors" + "io" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/control" + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/i18n" +) + +func captureStdout(t *testing.T, fn func() error) (string, error) { + t.Helper() + orig := os.Stdout + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + os.Stdout = w + runErr := fn() + _ = w.Close() + os.Stdout = orig + raw, _ := io.ReadAll(r) + _ = r.Close() + return string(raw), runErr +} + +func TestVMAutoInstallForwardsStatefulCommandsToDesktopControl(t *testing.T) { + origCall := callDesktopAutoInstall + origPID := desktopPIDForAutoInstall + t.Cleanup(func() { + callDesktopAutoInstall = origCall + desktopPIDForAutoInstall = origPID + }) + + var calls []control.AutoInstallRequest + callDesktopAutoInstall = func(_ context.Context, req control.AutoInstallRequest, out any) error { + calls = append(calls, req) + payload, _ := json.Marshal(map[string]any{"forwarded": req.Action, "vm": req.VMName}) + return json.Unmarshal(payload, out) + } + + cfg := config.Default() + cfg.DataRoot = t.TempDir() + + for _, tc := range []struct { + args []string + wantAction string + wantVM string + }{ + {[]string{"status"}, "status", ""}, + {[]string{"status", "tahoe"}, "status", "tahoe"}, + {[]string{"resume", "tahoe"}, "resume", "tahoe"}, + {[]string{"stop", "tahoe"}, "stop", "tahoe"}, + {[]string{"diagnostic", "tahoe"}, "diagnostic", "tahoe"}, + } { + out, err := captureStdout(t, func() error { + return cmdVMAutoInstall(cfg, i18n.EnUS, tc.args) + }) + if err != nil { + t.Fatalf("cmdVMAutoInstall(%v) failed: %v", tc.args, err) + } + if !strings.Contains(out, `"forwarded": "`+tc.wantAction+`"`) { + t.Fatalf("cmdVMAutoInstall(%v) output = %s, want forwarded=%s", tc.args, out, tc.wantAction) + } + } + if len(calls) != 5 { + t.Fatalf("expected 5 forwarded control calls, got %d", len(calls)) + } + if calls[0].DataRoot != cfg.DataRoot || calls[2].VMName != "tahoe" { + t.Fatalf("unexpected forwarded calls: %+v", calls) + } +} + +func TestVMAutoInstallResumeAndStopOfflineSafety(t *testing.T) { + origCall := callDesktopAutoInstall + origPID := desktopPIDForAutoInstall + t.Cleanup(func() { + callDesktopAutoInstall = origCall + desktopPIDForAutoInstall = origPID + }) + + cfg := config.Default() + cfg.DataRoot = t.TempDir() + + // 1. resume without running desktop must refuse instead of spawning a short-lived CLI runner. + callDesktopAutoInstall = func(_ context.Context, _ control.AutoInstallRequest, _ any) error { + return os.ErrNotExist + } + desktopPIDForAutoInstall = func() uint32 { return 0 } + if err := cmdVMAutoInstall(cfg, i18n.EnUS, []string{"resume", "tahoe"}); err == nil || !strings.Contains(err.Error(), "desktop app") { + t.Fatalf("expected resume refusal when desktop is not running, got %v", err) + } + + // 2. resume when desktop uses a different data root must also refuse clearly. + callDesktopAutoInstall = func(_ context.Context, _ control.AutoInstallRequest, _ any) error { + return errors.New("data_root_mismatch: running desktop app uses a different data directory") + } + if err := cmdVMAutoInstall(cfg, i18n.EnUS, []string{"resume", "tahoe"}); err == nil || !strings.Contains(err.Error(), "same data directory") { + t.Fatalf("expected data_root_mismatch refusal on resume, got %v", err) + } + + // 3. stop when desktop window IS running but control pipe failed must refuse to avoid split-brain. + callDesktopAutoInstall = func(_ context.Context, _ control.AutoInstallRequest, _ any) error { + return os.ErrNotExist + } + desktopPIDForAutoInstall = func() uint32 { return 9999 } + if err := cmdVMAutoInstall(cfg, i18n.EnUS, []string{"stop", "tahoe"}); err == nil || !strings.Contains(err.Error(), "desktop app is running") { + t.Fatalf("expected stop split-brain refusal when desktop PID active, got %v", err) + } +} + +func TestVMAutoInstallStatusOfflineReadsPersistedCheckpoints(t *testing.T) { + origCall := callDesktopAutoInstall + origPID := desktopPIDForAutoInstall + t.Cleanup(func() { + callDesktopAutoInstall = origCall + desktopPIDForAutoInstall = origPID + }) + callDesktopAutoInstall = func(_ context.Context, _ control.AutoInstallRequest, _ any) error { + return os.ErrNotExist + } + desktopPIDForAutoInstall = func() uint32 { return 0 } + + cfg := config.Default() + cfg.DataRoot = t.TempDir() + pluginDataDir := filepath.Join(cfg.DataRoot, "plugins", "data", "builtin.macos.autoinstall") + vmKey := driver.NewVMRef(driver.BuiltinReimsMacOSDriverID, "offline-cp").Key() + + // Seed a paused checkpoint directly on disk under runs/. + if err := os.MkdirAll(filepath.Join(pluginDataDir, "runs"), 0o755); err != nil { + t.Fatal(err) + } + raw, _ := json.Marshal(map[string]any{ + "version": 1, + "vm": vmKey, + "stage": "stage3_install_wait", + "status": "paused_for_user", + "message": "Waiting for user", + "started_at": time.Now().UTC().Format(time.RFC3339), + "updated_at": time.Now().UTC().Format(time.RFC3339), + }) + if err := os.WriteFile(filepath.Join(pluginDataDir, "runs", "seed.json"), raw, 0o600); err != nil { + t.Fatal(err) + } + + out, err := captureStdout(t, func() error { + return cmdVMAutoInstall(cfg, i18n.EnUS, []string{"status"}) + }) + if err != nil { + t.Fatalf("offline status without vm failed: %v", err) + } + if !strings.Contains(out, vmKey) || !strings.Contains(out, "paused_for_user") { + t.Fatalf("offline status must report persisted checkpoint instead of empty runs, got:\n%s", out) + } +} diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 7a634c8..9f9fdef 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -407,11 +407,15 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error { func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) error { if len(args) == 0 { - return fmt.Errorf("usage: reims-go vm ") + return fmt.Errorf("usage: reims-go vm ") } ctx := context.Background() switch args[0] { + case "provision": + return cmdVMMacOSProvision(ctx, cfg, loc, args[1:]) + case "autoinstall": + return cmdVMAutoInstall(cfg, loc, args[1:]) case "list": svc, closeService, err := openCLILifecycle(cfg) if err != nil { diff --git a/internal/cli/macos_native.go b/internal/cli/macos_native.go index a03c997..6f470dc 100644 --- a/internal/cli/macos_native.go +++ b/internal/cli/macos_native.go @@ -15,6 +15,7 @@ import ( "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/console" "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/i18n" "github.com/Nwflower/reims-go/internal/lifecycle" @@ -264,3 +265,117 @@ func typeMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, args fmt.Println(i18n.T(loc, "vm.typed", n)) return nil } + +func cmdVMMacOSProvision(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string) error { + if err := requireCLIMacOSEnabled(cfg, loc); err != nil { + return err + } + fs := flag.NewFlagSet("vm provision", flag.ContinueOnError) + fullName := fs.String("full-name", "", "macOS account display name (printable ASCII)") + accountName := fs.String("account", "", "macOS short account name (^[a-z][a-z0-9_-]{0,31}$)") + password := fs.String("password", "", "macOS account password (4+ printable ASCII; hashed via PBKDF2, never stored in plaintext)") + passwordStdin := fs.Bool("password-stdin", false, "Read account password from stdin") + appearance := fs.String("appearance", "auto", "macOS appearance (auto|light|dark)") + agreeSLA := fs.Bool("agree-sla", false, "Confirm Apple macOS software license agreement") + noGuestTools := fs.Bool("no-guest-tools", false, "Skip pre-staging Reims Guest Tools") + clearImg := fs.Bool("clear", false, "Securely wipe and remove the VM's REIMSPROV image") + statusOnly := fs.Bool("status", false, "Print whether the VM currently has a staged REIMSPROV image") + + vmName := "" + parseArgs := args + if len(args) > 0 && !strings.HasPrefix(args[0], "-") { + vmName = strings.TrimSpace(args[0]) + parseArgs = args[1:] + } + if err := fs.Parse(parseArgs); err != nil { + return err + } + if vmName == "" && fs.NArg() > 0 { + vmName = strings.TrimSpace(fs.Arg(0)) + } + if vmName == "" { + return errors.New("usage: reims-go vm provision --full-name --account (--password | --password-stdin) --agree-sla [--appearance auto|light|dark] [--no-guest-tools] | --clear | --status") + } + + prep, err := startprep.New(*cfg, func(line string) { fmt.Fprintln(os.Stderr, line) }) + if err != nil { + return err + } + det, err := prep.Client.Show(ctx, vmName) + if err != nil { + return err + } + if strings.TrimSpace(det.Directory) == "" { + return fmt.Errorf("VM %q directory is unavailable", vmName) + } + + if *statusOnly { + if installer.HasProvisionImage(det.Directory) { + fmt.Printf("REIMSPROV staged: %s\n", installer.ProvisionImagePath(det.Directory)) + } else { + fmt.Printf("REIMSPROV not staged for %s\n", det.Name) + } + return nil + } + if *clearImg { + if det.State == "running" || det.State == "paused" { + return fmt.Errorf("cannot clear REIMSPROV while VM %q is %s; stop the VM first", det.Name, det.State) + } + if err := installer.SecureRemoveProvisionImage(det.Directory); err != nil { + return err + } + fmt.Printf("Securely wiped REIMSPROV for %s.\n", det.Name) + return nil + } + if (det.State == "running" || det.State == "paused") && installer.HasProvisionImage(det.Directory) { + return fmt.Errorf("cannot overwrite existing REIMSPROV while VM %q is %s; stop the VM first", det.Name, det.State) + } + + pw := *password + if *passwordStdin { + raw, rerr := io.ReadAll(os.Stdin) + if rerr != nil { + return rerr + } + pw = strings.TrimRight(string(raw), "\r\n") + } + defer func() { pw = "" }() + + pCfg := installer.ProvisionConfig{ + FullName: *fullName, + AccountName: *accountName, + Password: pw, + Appearance: *appearance, + SLAAccepted: *agreeSLA, + } + if err := installer.ValidateProvisionConfig(&pCfg); err != nil { + return err + } + if !*noGuestTools { + gtCfg, gerr := guesttools.LoadOrCreateVMConfig(det.Directory, det.Name, filepath.Join(cfg.SharedDir(), det.Name), 0) + if gerr != nil { + fmt.Fprintf(os.Stderr, "Warning: could not stage Guest Tools in REIMSPROV: %v\n", gerr) + } else { + for _, pf := range guesttools.ToolsProvisionFiles(gtCfg) { + pCfg.GuestTools = append(pCfg.GuestTools, installer.ProvisionGuestToolFile{ + Name: pf.Name, + Mode: pf.Mode, + Data: pf.Data, + }) + } + } + } + + imgPath, err := installer.BuildProvisionDiskImage(det.Directory, pCfg) + if err != nil { + return err + } + fmt.Printf("REIMSPROV image ready: %s\n", imgPath) + fmt.Printf("Account: %s (%s), appearance=%s, guest_tools=%v\n", pCfg.AccountName, pCfg.FullName, pCfg.Appearance, len(pCfg.GuestTools) > 0) + if det.State == "running" { + fmt.Println("Note: VM is currently running; stop and start it so QEMU attaches /Volumes/REIMSPROV.") + } else { + fmt.Printf("Next: start %s into Recovery and run `sh /Volumes/REIMSHELP/install.sh` (auto-detects /Volumes/REIMSPROV/provision.pkg).\n", det.Name) + } + return nil +} diff --git a/internal/cli/plugin_test.go b/internal/cli/plugin_test.go index c9892e5..dc9d290 100644 --- a/internal/cli/plugin_test.go +++ b/internal/cli/plugin_test.go @@ -121,3 +121,31 @@ func TestCLIPluginListEnableDisableAndDoctor(t *testing.T) { t.Fatalf("plugin doctor dir exited %d", code) } } + +func TestCLIAutoInstallBuiltinDefaultEnabledAndToggle(t *testing.T) { + dataRoot := t.TempDir() + // Official built-in auto-install plugin is enabled by default and serves CLI preflight/status. + if code := Main([]string{"--data-root", dataRoot, "vm", "autoinstall", "list"}); code != 0 { + t.Fatalf("vm autoinstall list exited %d", code) + } + if code := Main([]string{"--data-root", dataRoot, "vm", "autoinstall", "preflight", "demo"}); code != 0 { + t.Fatalf("vm autoinstall preflight exited %d", code) + } + if code := Main([]string{"--data-root", dataRoot, "vm", "autoinstall", "status", "demo"}); code != 0 { + t.Fatalf("vm autoinstall status exited %d", code) + } + // Disabling the built-in auto-install plugin removes the provider cleanly. + if code := Main([]string{"--data-root", dataRoot, "plugin", "disable", "builtin.macos.autoinstall"}); code != 0 { + t.Fatalf("plugin disable builtin.macos.autoinstall exited %d", code) + } + if code := Main([]string{"--data-root", dataRoot, "vm", "autoinstall", "preflight", "demo"}); code == 0 { + t.Fatal("expected vm autoinstall preflight to fail while built-in plugin is disabled") + } + // Re-enabling restores CLI preflight. + if code := Main([]string{"--data-root", dataRoot, "plugin", "enable", "builtin.macos.autoinstall"}); code != 0 { + t.Fatalf("plugin enable builtin.macos.autoinstall exited %d", code) + } + if code := Main([]string{"--data-root", dataRoot, "vm", "autoinstall", "preflight", "demo"}); code != 0 { + t.Fatalf("vm autoinstall preflight after re-enable exited %d", code) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 187ccfb..3a4879f 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -37,6 +37,27 @@ type Config struct { FullscreenHotkeyEnabled bool `json:"fullscreen_hotkey_enabled,omitempty"` FullscreenHotkey string `json:"fullscreen_hotkey,omitempty"` + + // AgentTakeoverPauseSec controls how many seconds Agent input pauses after + // physical keyboard/mouse takeover on a VM window. Nil defaults to 5 seconds; + // 0 means pause until the user clicks Resume manually. + AgentTakeoverPauseSec *int `json:"agent_takeover_pause_sec,omitempty"` +} + +// EffectiveAgentTakeoverPauseSec returns the active takeover pause duration in +// seconds: 5 by default, 0 for manual-only resume, or clamped to [1, 300]. +func (c *Config) EffectiveAgentTakeoverPauseSec() int { + if c == nil || c.AgentTakeoverPauseSec == nil { + return 5 + } + v := *c.AgentTakeoverPauseSec + if v <= 0 { + return 0 + } + if v > 300 { + return 300 + } + return v } // ShouldMinimizeToTray returns true when closing the main window should hide to tray. diff --git a/internal/console/manager.go b/internal/console/manager.go index 13f2780..fe354b9 100644 --- a/internal/console/manager.go +++ b/internal/console/manager.go @@ -280,10 +280,14 @@ func normalizeModifier(modifier string) (string, error) { switch code { case "cmd", "command", "meta", "super": code = "meta_l" - case "ctrl", "control": + case "shift_l": + code = "shift" + case "ctrl", "ctrl_l", "control": code = "ctrl" - case "option": + case "alt_l", "option", "option_l": code = "alt" + case "option_r": + code = "alt_r" } switch code { case "shift", "shift_r", "ctrl", "ctrl_r", "alt", "alt_r", "meta_l", "meta_r": diff --git a/internal/control/control.go b/internal/control/control.go index 9181d83..4927aeb 100644 --- a/internal/control/control.go +++ b/internal/control/control.go @@ -1,11 +1,14 @@ package control import ( + "bufio" "context" "crypto/rand" "crypto/sha256" "encoding/hex" "encoding/json" + "errors" + "fmt" "os" "path/filepath" "runtime" @@ -14,6 +17,86 @@ import ( const MaxFrameBytes = 8 << 20 +// HostPluginID and ChannelAutoInstall identify the internal desktop-host +// control channel used by CLI subcommands (such as `vm autoinstall status`, +// `resume`, `stop`, and `diagnostic`) to operate on the running desktop app's +// live state over the same user-scoped Windows named pipe. +const ( + HostPluginID = "__reims_host__" + ChannelAutoInstall = "autoinstall" +) + +// AutoInstallRequest carries one CLI-to-desktop auto-install operation. +type AutoInstallRequest struct { + Action string `json:"action"` // status | resume | stop | diagnostic + DataRoot string `json:"data_root,omitempty"` + PluginID string `json:"plugin_id,omitempty"` + DriverID string `json:"driver_id,omitempty"` + VMName string `json:"vm_name,omitempty"` +} + +// Call sends a single request frame over the local desktop control channel, +// closes input cleanly, and decodes the response payload into out (if non-nil). +func Call(ctx context.Context, pluginID, channel string, payload any, out any) error { + rawMsg, err := json.Marshal(payload) + if err != nil { + return err + } + conn, err := Dial(ctx) + if err != nil { + return err + } + defer conn.Close() + + done := make(chan struct{}) + defer close(done) + go func() { + select { + case <-ctx.Done(): + _ = conn.Close() + case <-done: + } + }() + + enc := json.NewEncoder(conn) + if err := enc.Encode(Request{ + PluginID: pluginID, + Channel: channel, + Message: rawMsg, + RequestID: json.RawMessage("1"), + }); err != nil { + return err + } + if err := enc.Encode(Request{CloseInput: true}); err != nil { + return err + } + + sc := bufio.NewScanner(conn) + sc.Buffer(make([]byte, 64*1024), MaxFrameBytes) + if !sc.Scan() { + if err := sc.Err(); err != nil { + return err + } + if ctx.Err() != nil { + return ctx.Err() + } + return errors.New("desktop control channel closed without response") + } + var resp Response + if err := json.Unmarshal(sc.Bytes(), &resp); err != nil { + return fmt.Errorf("decode desktop control response: %w", err) + } + if resp.Error != "" { + return errors.New(resp.Error) + } + if out != nil && len(resp.Message) > 0 && string(resp.Message) != "null" { + if err := json.Unmarshal(resp.Message, out); err != nil { + return fmt.Errorf("decode desktop control payload: %w", err) + } + } + return nil +} + type Request struct { PluginID string `json:"plugin_id,omitempty"` Channel string `json:"channel,omitempty"` diff --git a/internal/guesttools/active_window_reporter_test.go b/internal/guesttools/active_window_reporter_test.go index fdfae97..2039227 100644 --- a/internal/guesttools/active_window_reporter_test.go +++ b/internal/guesttools/active_window_reporter_test.go @@ -15,3 +15,22 @@ func TestActiveWindowReporterBridge(t *testing.T) { t.Fatalf("window reporter: %v\n%s", err, output) } } + +func TestToolsProvisionFilesActiveWindowReporterModeMatchesToolsDisk(t *testing.T) { + cfg := VMConfig{VMName: "demo", Token: "tok", Port: 12345} + var diskMode uint16 + for _, f := range ToolsDiskFiles(cfg) { + if f.Name == "active-window-reporter.js" { + diskMode = f.Mode + } + } + var provMode uint32 + for _, f := range ToolsProvisionFiles(cfg) { + if f.Name == "active-window-reporter.js" { + provMode = f.Mode + } + } + if diskMode == 0 || uint32(diskMode) != provMode || provMode != 0o100755 { + t.Fatalf("active-window-reporter.js mode mismatch: disk=%#o provision=%#o, want 0100755", diskMode, provMode) + } +} diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index 1cf8f31..56fcb1e 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -39,6 +39,37 @@ var guestApplyHostDNS []byte //go:embed Disable-Host-DNS.command var guestDisableHostDNS []byte +// ProvisionFile describes one pre-staged Guest Tools file to copy into an +// offline provisioning disk without coupling guesttools to a specific OS installer. +type ProvisionFile struct { + Name string + Mode uint32 + Data []byte +} + +// ToolsProvisionFiles returns the per-VM Guest Tools agent payload files so +// offline macOS provisioning (REIMSPROV) can pre-stage Guest Tools for +// automatic startup on first login once NAT is enabled. +func ToolsProvisionFiles(cfg VMConfig) []ProvisionFile { + confBytes := []byte(fmt.Sprintf("REIMS_HOST_URL='http://10.0.2.2:%d'\nREIMS_HOST_PORT='%d'\nREIMS_TOKEN=%s\nREIMS_VM=%s\n", + cfg.Port, cfg.Port, shellSingleQuote(cfg.Token), shellSingleQuote(cfg.VMName))) + agentBytes := GuestAgentScript() + dropResolveJS := []byte(strings.ReplaceAll(guestDropResolveJS, "\r\n", "\n")) + files := []ProvisionFile{ + {Name: "config", Mode: 0o100600, Data: confBytes}, + {Name: "guest-tools.sh", Mode: 0o100755, Data: agentBytes}, + {Name: "drop-resolve.js", Mode: 0o100755, Data: dropResolveJS}, + } + if len(guestWindowReporter) > 0 { + files = append(files, ProvisionFile{ + Name: "active-window-reporter.js", + Mode: 0o100755, + Data: bytes.ReplaceAll(guestWindowReporter, []byte("\r\n"), []byte("\n")), + }) + } + return files +} + // ToolsDiskFile describes one file to place into the read-only REIMSTOOLS // disk image without coupling guesttools to a specific disk-image format. type ToolsDiskFile struct { diff --git a/internal/host/redact.go b/internal/host/redact.go index bbfa0de..7d9578a 100644 --- a/internal/host/redact.go +++ b/internal/host/redact.go @@ -8,7 +8,7 @@ import ( var ( reLogMac = regexp.MustCompile(`(?i)\b(mac(?:_?address)?[\s:=]+)["']?[0-9a-f]{2}(?:[:-][0-9a-f]{2}){5}["']?`) - reLogSerialKV = regexp.MustCompile(`(?i)\b((?:system)?serial(?:_?number)?\s*[:=]\s*|mlb\s*[:=]\s*|smuuid\s*[:=]\s*)["']?[A-Za-z0-9-]{8,}["']?`) + reLogSerialKV = regexp.MustCompile(`(?i)\b((?:system)?serial(?:_?number)?\s*[:=]\s*|mlb\s*[:=]\s*|(?:sm|system[_-]?)?uuid\s*[:=]\s*|rom\s*[:=]\s*)["']?[A-Za-z0-9-]{8,}["']?`) reLogSerialSp = regexp.MustCompile(`(?i)\b(serial\s+)["']?(?-i:[A-Z0-9]{8,})["']?`) reLogOSK = regexp.MustCompile(`(?i)\b(osk\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,"']+)`) reLogBearer = regexp.MustCompile(`(?i)((?:Bearer|Basic|Authorization:\s*token)\s+)[A-Za-z0-9._~+/=-]{16,}`) diff --git a/internal/host/sessionoverlay/dwrite_windows.go b/internal/host/sessionoverlay/dwrite_windows.go new file mode 100644 index 0000000..1d0c2e1 --- /dev/null +++ b/internal/host/sessionoverlay/dwrite_windows.go @@ -0,0 +1,625 @@ +//go:build windows + +package sessionoverlay + +import ( + "math" + "strings" + "syscall" + "unicode/utf16" + "unsafe" +) + +type comGUID struct { + Data1 uint32 + Data2 uint16 + Data3 uint16 + Data4 [8]byte +} + +var ( + d2d1DLL = syscall.NewLazyDLL("d2d1.dll") + dwriteDLL = syscall.NewLazyDLL("dwrite.dll") + + procD2D1CreateFactory = d2d1DLL.NewProc("D2D1CreateFactory") + procDWriteCreateFactory = dwriteDLL.NewProc("DWriteCreateFactory") + + iidID2D1Factory = comGUID{0x06152247, 0x6f50, 0x465a, [8]byte{0x92, 0x45, 0x11, 0x8b, 0xfd, 0x3b, 0x60, 0x07}} + iidIDWriteFactory = comGUID{0xb859ee5a, 0xd838, 0x4b5b, [8]byte{0xa2, 0xe8, 0x1a, 0xdc, 0x7d, 0x93, 0xdb, 0x48}} +) + +type comObj struct { + vtbl *[80]uintptr +} + +// Windows SDK d2d1.h / dwrite.h COM vtable slot indices (0-based, after +// IUnknown slots 0=QueryInterface, 1=AddRef, 2=Release). +const ( + vtblIUnknownRelease = 2 + + // ID2D1Factory (d2d1.h, inherits IUnknown): + // 3=ReloadSystemMetrics, 4=GetDesktopDpi, 5..10=Create*Geometry, + // 11=CreateStrokeStyle, 12=CreateDrawingStateBlock, 13=CreateWicBitmapRenderTarget, + // 14=CreateHwndRenderTarget, 15=CreateDxgiSurfaceRenderTarget, 16=CreateDCRenderTarget. + vtblD2DFactoryCreateDCRenderTarget = 16 + + // ID2D1RenderTarget (d2d1.h, inherits ID2D1Resource -> IUnknown; 3=GetFactory): + // 4..7=CreateBitmap*, 8=CreateSolidColorBrush, ..., 28=DrawTextLayout, + // ..., 34=SetTextAntialiasMode, ..., 48=BeginDraw, 49=EndDraw. + // ID2D1DCRenderTarget (inherits ID2D1RenderTarget; slots 4..56): 57=BindDC. + vtblD2DRTCreateSolidColorBrush = 8 + vtblD2DRTDrawTextLayout = 28 + vtblD2DRTSetTextAntialiasMode = 34 + vtblD2DRTBeginDraw = 48 + vtblD2DRTEndDraw = 49 + vtblD2DDCRTBindDC = 57 + + // ID2D1SolidColorBrush (d2d1.h, inherits ID2D1Brush -> ID2D1Resource -> IUnknown): + // 3=GetFactory, 4=SetOpacity, 5=SetTransform, 6=GetOpacity, 7=GetTransform, 8=SetColor. + vtblD2DSolidBrushSetColor = 8 + + // IDWriteFactory (dwrite.h, inherits IUnknown): + // 3=GetSystemFontCollection, ..., 15=CreateTextFormat, ..., 18=CreateTextLayout, + // ..., 20=CreateEllipsisTrimmingSign. + vtblDWFactoryGetSystemFontCollection = 3 + vtblDWFactoryCreateTextFormat = 15 + vtblDWFactoryCreateTextLayout = 18 + vtblDWFactoryCreateEllipsisTrimmingSign = 20 + + // IDWriteFontCollection (dwrite.h, inherits IUnknown): + // 3=GetFontFamilyCount, 4=GetFontFamily, 5=FindFamilyName. + vtblDWFontCollectionFindFamilyName = 5 + + // IDWriteTextLayout (dwrite.h, inherits IDWriteTextFormat -> IUnknown): + // 3=SetTextAlignment, 4=SetParagraphAlignment, 5=SetWordWrapping, ..., 9=SetTrimming, + // ..., 31=SetFontFamilyName, 32=SetFontWeight, ..., 60=GetMetrics. + vtblDWLayoutSetTextAlignment = 3 + vtblDWLayoutSetParagraphAlignment = 4 + vtblDWLayoutSetWordWrapping = 5 + vtblDWLayoutSetTrimming = 9 + vtblDWLayoutSetFontFamilyName = 31 + vtblDWLayoutSetFontWeight = 32 + vtblDWLayoutGetMetrics = 60 +) + +func (o *comObj) release() { + if o != nil { + _, _, _ = syscall.SyscallN(o.vtbl[vtblIUnknownRelease], uintptr(unsafe.Pointer(o))) + } +} + +type d2dPixelFormat struct { + format uint32 + alphaMode uint32 +} + +type d2dRTProps struct { + typ uint32 + pixelFormat d2dPixelFormat + dpiX, dpiY float32 + usage uint32 + minLevel uint32 +} + +type d2dColorF struct { + r, g, b, a float32 +} + +type dwTrimming struct { + granularity uint32 + delimiter uint32 + delimiterCount uint32 +} + +type dwTextMetrics struct { + left float32 + top float32 + width float32 + widthIncludingTrailingWhitespace float32 + height float32 + layoutWidth float32 + layoutHeight float32 + maxBidiReorderingDepth uint32 + lineCount uint32 +} + +const ( + dwAlignLeading = 0 + dwAlignTrailing = 1 + dwAlignCenter = 2 + + dwParaNear = 0 + dwParaCenter = 2 + + dwWrapNormal = 0 + dwWrapNone = 1 + + dwTrimCharacter = 1 +) + +type textStyle uint8 + +const ( + styleMeta textStyle = iota + styleHero + styleStatus + styleBtn + styleCompact + styleTip +) + +type dwFormatKey struct { + dpi int32 + script scriptKind + style textStyle +} + +type dwFormatEntry struct { + format *comObj + ellipsisSign *comObj + latinFace string + latinWeight uint32 + lineHeight float32 +} + +// dwriteEngine manages per-UI-thread software Direct2D + DirectWrite COM +// resources for crisp, subpixel-positioned grayscale-AA typography on 32-bit +// premultiplied BGRA layered surfaces with zero GPU contention. +type dwriteEngine struct { + ready bool + failed bool + d2dFactory *comObj + dwFactory *comObj + dcRT *comObj + brush *comObj + families map[scriptKind]string + latinText string + latinDisp string + formats map[dwFormatKey]dwFormatEntry + drawing bool + boundCanvas *dibSurface +} + +func packD2DPoint2F(x, y float32) uintptr { + return uintptr(uint64(math.Float32bits(x)) | uint64(math.Float32bits(y))<<32) +} + +func packDWRange(start, length uint32) uintptr { + return uintptr(uint64(start) | uint64(length)<<32) +} + +func (e *dwriteEngine) ensureInit() bool { + if e.ready { + return true + } + if e.failed { + return false + } + if procD2D1CreateFactory.Find() != nil || procDWriteCreateFactory.Find() != nil { + e.failed = true + return false + } + + var d2dFac *comObj + hr, _, _ := procD2D1CreateFactory.Call( + 0, // D2D1_FACTORY_TYPE_SINGLE_THREADED + uintptr(unsafe.Pointer(&iidID2D1Factory)), + 0, + uintptr(unsafe.Pointer(&d2dFac)), + ) + if int32(hr) < 0 || d2dFac == nil { + e.failed = true + return false + } + + var dwFac *comObj + hr, _, _ = procDWriteCreateFactory.Call( + 0, // DWRITE_FACTORY_TYPE_SHARED + uintptr(unsafe.Pointer(&iidIDWriteFactory)), + uintptr(unsafe.Pointer(&dwFac)), + ) + if int32(hr) < 0 || dwFac == nil { + d2dFac.release() + e.failed = true + return false + } + + props := d2dRTProps{ + typ: 1, // D2D1_RENDER_TARGET_TYPE_SOFTWARE (CPU WARP, zero VRAM/GPU contention with reims-vgpu) + pixelFormat: d2dPixelFormat{format: 87, alphaMode: 1}, // DXGI_FORMAT_B8G8R8A8_UNORM + PREMULTIPLIED + dpiX: 96, + dpiY: 96, + } + var rt *comObj + hr, _, _ = syscall.SyscallN(d2dFac.vtbl[vtblD2DFactoryCreateDCRenderTarget], uintptr(unsafe.Pointer(d2dFac)), uintptr(unsafe.Pointer(&props)), uintptr(unsafe.Pointer(&rt))) + if int32(hr) < 0 || rt == nil { + dwFac.release() + d2dFac.release() + e.failed = true + return false + } + // D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE (2) preserves exact premultiplied alpha. + _, _, _ = syscall.SyscallN(rt.vtbl[vtblD2DRTSetTextAntialiasMode], uintptr(unsafe.Pointer(rt)), 2) + + white := d2dColorF{1, 1, 1, 1} + var brush *comObj + hr, _, _ = syscall.SyscallN(rt.vtbl[vtblD2DRTCreateSolidColorBrush], uintptr(unsafe.Pointer(rt)), uintptr(unsafe.Pointer(&white)), 0, uintptr(unsafe.Pointer(&brush))) + if int32(hr) < 0 || brush == nil { + rt.release() + dwFac.release() + d2dFac.release() + e.failed = true + return false + } + + e.d2dFactory = d2dFac + e.dwFactory = dwFac + e.dcRT = rt + e.brush = brush + e.formats = make(map[dwFormatKey]dwFormatEntry) + e.probeFamilies() + e.ready = true + return true +} + +func (e *dwriteEngine) probeFamilies() { + e.families = map[scriptKind]string{ + scriptLatn: "Segoe UI", + scriptHans: "Microsoft YaHei UI", + scriptHant: "Microsoft JhengHei UI", + scriptJpan: "Yu Gothic UI", + scriptKore: "Malgun Gothic", + } + e.latinText = "Segoe UI" + e.latinDisp = "Segoe UI" + + var col *comObj + hr, _, _ := syscall.SyscallN(e.dwFactory.vtbl[vtblDWFactoryGetSystemFontCollection], uintptr(unsafe.Pointer(e.dwFactory)), uintptr(unsafe.Pointer(&col)), 0) + if int32(hr) < 0 || col == nil { + return + } + defer col.release() + + has := func(name string) bool { + ptr, err := syscall.UTF16PtrFromString(name) + if err != nil { + return false + } + var idx uint32 + var exists int32 + hr, _, _ := syscall.SyscallN(col.vtbl[vtblDWFontCollectionFindFamilyName], uintptr(unsafe.Pointer(col)), uintptr(unsafe.Pointer(ptr)), uintptr(unsafe.Pointer(&idx)), uintptr(unsafe.Pointer(&exists))) + return int32(hr) >= 0 && exists != 0 + } + pickFirst := func(candidates []string, fallback string) string { + for _, c := range candidates { + if has(c) { + return c + } + } + return fallback + } + + e.latinText = pickFirst([]string{"Segoe UI Variable Text", "Segoe UI"}, "Segoe UI") + e.latinDisp = pickFirst([]string{"Segoe UI Variable Display", "Segoe UI Variable Text", "Segoe UI"}, e.latinText) + e.families[scriptLatn] = e.latinText + e.families[scriptHans] = pickFirst([]string{ + "PingFang SC", "HarmonyOS Sans SC", "MiSans", + "Noto Sans SC", "Source Han Sans CN", "Microsoft YaHei UI", "DengXian", + }, "Microsoft YaHei UI") + e.families[scriptHant] = pickFirst([]string{ + "PingFang TC", "Noto Sans TC", "Source Han Sans TC", "Microsoft JhengHei UI", + }, "Microsoft JhengHei UI") + e.families[scriptJpan] = pickFirst([]string{ + "Hiragino Sans", "Noto Sans JP", "BIZ UDPGothic", "Yu Gothic UI", + }, "Yu Gothic UI") + e.families[scriptKore] = pickFirst([]string{ + "Apple SD Gothic Neo", "Noto Sans KR", "Malgun Gothic", + }, "Malgun Gothic") +} + +func (e *dwriteEngine) release() { + if e.drawing { + e.endSurface() + } + for k, fe := range e.formats { + fe.ellipsisSign.release() + fe.format.release() + delete(e.formats, k) + } + e.brush.release() + e.dcRT.release() + e.dwFactory.release() + e.d2dFactory.release() + e.brush = nil + e.dcRT = nil + e.dwFactory = nil + e.d2dFactory = nil + e.ready = false +} + +func localeTagForScript(sk scriptKind) string { + switch sk { + case scriptHans: + return "zh-CN" + case scriptHant: + return "zh-TW" + case scriptJpan: + return "ja-JP" + case scriptKore: + return "ko-KR" + default: + return "en-US" + } +} + +func (e *dwriteEngine) getFormat(dpi int32, script scriptKind, style textStyle) (dwFormatEntry, bool) { + if !e.ensureInit() { + return dwFormatEntry{}, false + } + if dpi < 96 { + dpi = 96 + } + key := dwFormatKey{dpi: dpi, script: script, style: style} + if fe, ok := e.formats[key]; ok { + return fe, true + } + + face := e.families[script] + if face == "" { + face = e.latinText + } + scale := float32(dpi) / 96.0 + isBinaryWeight := face == "Microsoft YaHei UI" || face == "Microsoft JhengHei UI" || face == "Malgun Gothic" || face == "DengXian" + + var px float32 + var weight uint32 + var latinWeight uint32 + latinFace := e.latinText + switch style { + case styleMeta: + px = 11.5 + weight = 500 + latinWeight = 500 + if isBinaryWeight { + weight = 400 + } + case styleHero: + px = 15.0 + weight = 550 + latinWeight = 600 + latinFace = e.latinDisp + if isBinaryWeight { + weight = 600 + } + case styleStatus: + px = 12.0 + weight = 400 + latinWeight = 400 + case styleBtn: + px = 12.5 + weight = 500 + latinWeight = 550 + if isBinaryWeight { + weight = 400 + } + case styleCompact: + px = 12.5 + weight = 500 + latinWeight = 550 + if isBinaryWeight { + weight = 400 + } + default: // styleTip + px = 11.5 + weight = 500 + latinWeight = 500 + if isBinaryWeight { + weight = 400 + } + } + + famPtr, _ := syscall.UTF16PtrFromString(face) + locPtr, _ := syscall.UTF16PtrFromString(localeTagForScript(script)) + var tf *comObj + hr, _, _ := syscall.SyscallN( + e.dwFactory.vtbl[vtblDWFactoryCreateTextFormat], + uintptr(unsafe.Pointer(e.dwFactory)), + uintptr(unsafe.Pointer(famPtr)), + 0, + uintptr(weight), + 0, // DWRITE_FONT_STYLE_NORMAL + 5, // DWRITE_FONT_STRETCH_NORMAL + uintptr(math.Float32bits(px*scale)), + uintptr(unsafe.Pointer(locPtr)), + uintptr(unsafe.Pointer(&tf)), + ) + if int32(hr) < 0 || tf == nil { + return dwFormatEntry{}, false + } + + var sign *comObj + _, _, _ = syscall.SyscallN( + e.dwFactory.vtbl[vtblDWFactoryCreateEllipsisTrimmingSign], + uintptr(unsafe.Pointer(e.dwFactory)), + uintptr(unsafe.Pointer(tf)), + uintptr(unsafe.Pointer(&sign)), + ) + + fe := dwFormatEntry{ + format: tf, + ellipsisSign: sign, + latinFace: latinFace, + latinWeight: latinWeight, + lineHeight: px * scale * 1.45, + } + e.formats[key] = fe + return fe, true +} + +func isLatinRunRune(u uint16) bool { + return u >= 0x0021 && u <= 0x007E +} + +func (e *dwriteEngine) buildLayout(dpi int32, script scriptKind, style textStyle, text string, maxW, maxH float32, align uint32, maxLines int) (*comObj, bool) { + if text == "" || maxW <= 0 || maxH <= 0 { + return nil, false + } + fe, ok := e.getFormat(dpi, script, style) + if !ok { + return nil, false + } + u16 := utf16.Encode([]rune(text)) + if len(u16) == 0 { + return nil, false + } + var layout *comObj + hr, _, _ := syscall.SyscallN( + e.dwFactory.vtbl[vtblDWFactoryCreateTextLayout], + uintptr(unsafe.Pointer(e.dwFactory)), + uintptr(unsafe.Pointer(&u16[0])), + uintptr(len(u16)), + uintptr(unsafe.Pointer(fe.format)), + uintptr(math.Float32bits(maxW)), + uintptr(math.Float32bits(maxH)), + uintptr(unsafe.Pointer(&layout)), + ) + if int32(hr) < 0 || layout == nil { + return nil, false + } + + _, _, _ = syscall.SyscallN(layout.vtbl[vtblDWLayoutSetTextAlignment], uintptr(unsafe.Pointer(layout)), uintptr(align)) + if maxLines <= 1 { + _, _, _ = syscall.SyscallN(layout.vtbl[vtblDWLayoutSetParagraphAlignment], uintptr(unsafe.Pointer(layout)), dwParaCenter) + _, _, _ = syscall.SyscallN(layout.vtbl[vtblDWLayoutSetWordWrapping], uintptr(unsafe.Pointer(layout)), dwWrapNone) + } else { + _, _, _ = syscall.SyscallN(layout.vtbl[vtblDWLayoutSetParagraphAlignment], uintptr(unsafe.Pointer(layout)), dwParaNear) + _, _, _ = syscall.SyscallN(layout.vtbl[vtblDWLayoutSetWordWrapping], uintptr(unsafe.Pointer(layout)), dwWrapNormal) + } + if fe.ellipsisSign != nil { + trim := dwTrimming{granularity: dwTrimCharacter} + _, _, _ = syscall.SyscallN(layout.vtbl[vtblDWLayoutSetTrimming], uintptr(unsafe.Pointer(layout)), uintptr(unsafe.Pointer(&trim)), uintptr(unsafe.Pointer(fe.ellipsisSign))) + } + + // Pair crisp Segoe UI Variable on Latin/digit runs inside CJK text for + // balanced Apple-like mixed-script typography. + if script != scriptLatn && fe.latinFace != "" { + latinPtr, _ := syscall.UTF16PtrFromString(fe.latinFace) + i := 0 + for i < len(u16) { + if !isLatinRunRune(u16[i]) { + i++ + continue + } + start := i + for i < len(u16) && (isLatinRunRune(u16[i]) || u16[i] == ' ') { + i++ + } + end := i + for end > start && u16[end-1] == ' ' { + end-- + } + if end > start { + r := packDWRange(uint32(start), uint32(end-start)) + _, _, _ = syscall.SyscallN(layout.vtbl[vtblDWLayoutSetFontFamilyName], uintptr(unsafe.Pointer(layout)), uintptr(unsafe.Pointer(latinPtr)), r) + _, _, _ = syscall.SyscallN(layout.vtbl[vtblDWLayoutSetFontWeight], uintptr(unsafe.Pointer(layout)), uintptr(fe.latinWeight), r) + } + } + } + return layout, true +} + +func (e *dwriteEngine) measureLineWidth(dpi int32, script scriptKind, style textStyle, text string) (int32, bool) { + if strings.TrimSpace(text) == "" { + return 0, true + } + layout, ok := e.buildLayout(dpi, script, style, text, 4096, 256, dwAlignLeading, 1) + if !ok { + return 0, false + } + defer layout.release() + var m dwTextMetrics + hr, _, _ := syscall.SyscallN(layout.vtbl[vtblDWLayoutGetMetrics], uintptr(unsafe.Pointer(layout)), uintptr(unsafe.Pointer(&m))) + if int32(hr) < 0 { + return 0, false + } + return int32(math.Ceil(float64(m.widthIncludingTrailingWhitespace))), true +} + +func (e *dwriteEngine) measureWrappedLines(dpi int32, script scriptKind, style textStyle, text string, maxW int32, maxLines int) (int, bool) { + text = strings.TrimSpace(text) + if text == "" { + return 0, true + } + layout, ok := e.buildLayout(dpi, script, style, text, float32(maxW), 512, dwAlignLeading, maxLines) + if !ok { + return 0, false + } + defer layout.release() + var m dwTextMetrics + hr, _, _ := syscall.SyscallN(layout.vtbl[vtblDWLayoutGetMetrics], uintptr(unsafe.Pointer(layout)), uintptr(unsafe.Pointer(&m))) + if int32(hr) < 0 { + return 0, false + } + cnt := int(m.lineCount) + if cnt < 1 { + cnt = 1 + } + if maxLines > 0 && cnt > maxLines { + cnt = maxLines + } + return cnt, true +} + +func (e *dwriteEngine) beginSurface(canvas *dibSurface) bool { + if canvas == nil || canvas.hdc == 0 || !e.ensureInit() { + return false + } + rc := winRect{Left: 0, Top: 0, Right: canvas.w, Bottom: canvas.h} + hr, _, _ := syscall.SyscallN(e.dcRT.vtbl[vtblD2DDCRTBindDC], uintptr(unsafe.Pointer(e.dcRT)), canvas.hdc, uintptr(unsafe.Pointer(&rc))) + if int32(hr) < 0 { + return false + } + _, _, _ = syscall.SyscallN(e.dcRT.vtbl[vtblD2DRTBeginDraw], uintptr(unsafe.Pointer(e.dcRT))) + e.drawing = true + e.boundCanvas = canvas + return true +} + +func (e *dwriteEngine) endSurface() bool { + if !e.drawing || e.dcRT == nil { + return false + } + hr, _, _ := syscall.SyscallN(e.dcRT.vtbl[vtblD2DRTEndDraw], uintptr(unsafe.Pointer(e.dcRT)), 0, 0) + e.drawing = false + e.boundCanvas = nil + return int32(hr) >= 0 +} + +func (e *dwriteEngine) drawText(dpi int32, script scriptKind, style textStyle, text string, dst rect2i, align uint32, maxLines int, col rgba, alpha float64) bool { + if !e.drawing || text == "" || alpha <= 0.005 || dst.width() <= 0 || dst.height() <= 0 { + return true + } + layout, ok := e.buildLayout(dpi, script, style, text, float32(dst.width()), float32(dst.height()), align, maxLines) + if !ok { + return false + } + defer layout.release() + + c := d2dColorF{ + r: float32(col.r) / 255.0, + g: float32(col.g) / 255.0, + b: float32(col.b) / 255.0, + a: float32(clamp01(alpha)), + } + _, _, _ = syscall.SyscallN(e.brush.vtbl[vtblD2DSolidBrushSetColor], uintptr(unsafe.Pointer(e.brush)), uintptr(unsafe.Pointer(&c))) + // D2D1_DRAW_TEXT_OPTIONS_CLIP (0x00000002) prevents overflow outside dst. + _, _, _ = syscall.SyscallN( + e.dcRT.vtbl[vtblD2DRTDrawTextLayout], + uintptr(unsafe.Pointer(e.dcRT)), + packD2DPoint2F(float32(dst.Left), float32(dst.Top)), + uintptr(unsafe.Pointer(layout)), + uintptr(unsafe.Pointer(e.brush)), + 2, + ) + return true +} diff --git a/internal/host/sessionoverlay/island_model.go b/internal/host/sessionoverlay/island_model.go new file mode 100644 index 0000000..47f5353 --- /dev/null +++ b/internal/host/sessionoverlay/island_model.go @@ -0,0 +1,883 @@ +package sessionoverlay + +import ( + "math" + "strings" + "time" +) + +// Anchor identifies one of the six magnetic edge anchor points inside the VM +// client area. Expansion direction adapts automatically to the active anchor. +type Anchor uint8 + +const ( + AnchorTopRight Anchor = iota + AnchorTopCenter + AnchorTopLeft + AnchorBottomRight + AnchorBottomCenter + AnchorBottomLeft +) + +var allAnchors = [6]Anchor{ + AnchorTopRight, + AnchorTopCenter, + AnchorTopLeft, + AnchorBottomRight, + AnchorBottomCenter, + AnchorBottomLeft, +} + +type rect2i struct { + Left, Top, Right, Bottom int32 +} + +func (r rect2i) width() int32 { return r.Right - r.Left } +func (r rect2i) height() int32 { return r.Bottom - r.Top } + +func (r rect2i) contains(x, y int32) bool { + return r.Right > r.Left && r.Bottom > r.Top && x >= r.Left && x < r.Right && y >= r.Top && y < r.Bottom +} + +type point2i struct { + X, Y int32 +} + +type hitZone uint8 + +const ( + zoneNone hitZone = iota + zoneInfo + zoneToggle + zoneStop + zoneFold +) + +type clickAction uint8 + +const ( + actionNone clickAction = iota + actionToggle + actionStop +) + +const ( + morphDuration = 220 * time.Millisecond + snapDuration = 220 * time.Millisecond + pulseDuration = 550 * time.Millisecond + breathPeriod = 2400 * time.Millisecond +) + +func compactPrimaryText(st State) string { + if s := strings.TrimSpace(st.StepText); s != "" { + return s + } + return strings.TrimSpace(st.Title) +} + +func scaleDP(dpi, px int32) int32 { + if dpi < 96 { + dpi = 96 + } + return (px*dpi + 48) / 96 +} + +func scaleDPF(dpi int32, px float64) float64 { + if dpi < 96 { + dpi = 96 + } + return px * float64(dpi) / 96.0 +} + +func clampInt32(v, lo, hi int32) int32 { + if hi < lo { + return lo + } + if v < lo { + return lo + } + if v > hi { + return hi + } + return v +} + +func clamp01(v float64) float64 { + if v <= 0 { + return 0 + } + if v >= 1 { + return 1 + } + return v +} + +func lerpFloat(a, b, t float64) float64 { + return a + (b-a)*t +} + +func lerpInt32(a, b int32, t float64) int32 { + return int32(math.Round(lerpFloat(float64(a), float64(b), t))) +} + +// easeSpring evaluates cubic-bezier(0.32, 0.72, 0, 1), matching tokens.css --ease-spring. +func easeSpring(t float64) float64 { + t = clamp01(t) + if t == 0 || t == 1 { + return t + } + const ( + x1, y1 = 0.32, 0.72 + x2, y2 = 0.0, 1.0 + ) + bezierX := func(u float64) float64 { + inv := 1 - u + return 3*inv*inv*u*x1 + 3*inv*u*u*x2 + u*u*u + } + bezierDX := func(u float64) float64 { + inv := 1 - u + return 3*inv*inv*x1 + 6*inv*u*(x2-x1) + 3*u*u*(1-x2) + } + bezierY := func(u float64) float64 { + inv := 1 - u + return 3*inv*inv*u*y1 + 3*inv*u*u*y2 + u*u*u + } + u := t + lo, hi := 0.0, 1.0 + for range 6 { + x := bezierX(u) - t + if math.Abs(x) < 1e-5 { + break + } + if x < 0 { + lo = u + } else { + hi = u + } + dx := bezierDX(u) + if math.Abs(dx) > 1e-5 { + next := u - x/dx + if next > lo && next < hi { + u = next + continue + } + } + u = (lo + hi) * 0.5 + } + return clamp01(bezierY(u)) +} + +// shadowGutters returns the transparent padding around the pill inside the +// layered canvas so the soft outer drop shadow never clips. +func shadowGutters(dpi int32) (padX, padTop, padBottom int32) { + return scaleDP(dpi, 16), scaleDP(dpi, 10), scaleDP(dpi, 22) +} + +// anchorOrigin computes the pill top-left corner inside the VM client rect for +// the given magnetic anchor and current pill dimensions. +func anchorOrigin(anchor Anchor, clientW, clientH, pillW, pillH, dpi int32) point2i { + marginX := scaleDP(dpi, 16) + marginTop := scaleDP(dpi, 36) // below macOS menu bar + marginBottom := scaleDP(dpi, 16) + + var x, y int32 + switch anchor { + case AnchorTopLeft, AnchorBottomLeft: + x = marginX + case AnchorTopCenter, AnchorBottomCenter: + x = (clientW - pillW) / 2 + default: // AnchorTopRight, AnchorBottomRight + x = clientW - pillW - marginX + } + + switch anchor { + case AnchorBottomLeft, AnchorBottomCenter, AnchorBottomRight: + y = clientH - pillH - marginBottom + default: // Top anchors + y = marginTop + } + + return point2i{ + X: clampInt32(x, 0, max(int32(0), clientW-pillW)), + Y: clampInt32(y, 0, max(int32(0), clientH-pillH)), + } +} + +// nearestAnchor selects the closest of the six magnetic edge anchors to the +// current dragged pill position inside the VM client rect. +func nearestAnchor(pos point2i, clientW, clientH, pillW, pillH, dpi int32) Anchor { + cx := float64(pos.X) + float64(pillW)*0.5 + cy := float64(pos.Y) + float64(pillH)*0.5 + + best := AnchorTopRight + bestDist := math.MaxFloat64 + for _, a := range allAnchors { + target := anchorOrigin(a, clientW, clientH, pillW, pillH, dpi) + tcx := float64(target.X) + float64(pillW)*0.5 + tcy := float64(target.Y) + float64(pillH)*0.5 + dx := cx - tcx + dy := cy - tcy + d2 := dx*dx + dy*dy + if d2 < bestDist { + bestDist = d2 + best = a + } + } + return best +} + +// islandLayout describes the physical pixel geometry of the Dynamic Island in +// pill-local coordinates (0..PillW, 0..PillH) at a given morph progress. +type islandLayout struct { + DPI int32 + + CompactW int32 + CompactH int32 + ExpandedW int32 + ExpandedH int32 + HasStep bool + HasStatus bool + StatusLineCnt int + + PillW int32 + PillH int32 + PillRadius float64 + + // Canvas bounds including transparent shadow gutters. + PadX int32 + PadTop int32 + PadBottom int32 + CanvasW int32 + CanvasH int32 + + HasToggle bool + + // Compact mode element rects (pill-local). + CompactDotCenter point2i + CompactLockRect rect2i + CompactTitleRect rect2i + CompactInfoRect rect2i + CompactToggleBtn rect2i + CompactStopBtn rect2i + + // Expanded mode element rects (pill-local). + ExpandedDotCenter point2i + ExpandedTitleRect rect2i + ExpandedLockBadge rect2i + ExpandedFoldBtn rect2i + ExpandedStepRect rect2i + ExpandedStatusRect rect2i + ExpandedToggleBtn rect2i + ExpandedStopBtn rect2i + ExpandedHeaderRect rect2i + + // Active hit-test rects for the current morph state. + ActiveInfoRect rect2i + ActiveToggleRect rect2i + ActiveStopRect rect2i + ActiveFoldRect rect2i + CompactAlpha float64 + ExpandedAlpha float64 + DotCenter point2i +} + +// computeIslandLayout derives DPI-scaled compact, expanded, and interpolated +// geometry for the island. titleMeasuredW and statusLines are optional text +// measurements from GDI (0 falls back to sensible defaults). +func computeIslandLayout(st State, dpi, clientW, titleMeasuredW int32, statusLines int, morph float64) islandLayout { + if dpi < 96 { + dpi = 96 + } + hasStep := strings.TrimSpace(st.StepText) != "" + hasStatus := strings.TrimSpace(st.StatusLine) != "" + if hasStatus { + if statusLines < 1 { + statusLines = 1 + } + if statusLines > 2 { + statusLines = 2 + } + } else { + statusLines = 0 + } + hasToggle := !st.Completed && (st.CanResume || st.CanPause) + + // Compact pill geometry (height = 40dp, 28x28dp quick circular buttons). + compactH := scaleDP(dpi, 40) + btnD := scaleDP(dpi, 28) + btnGap := scaleDP(dpi, 6) + btnPadRight := scaleDP(dpi, 6) + dotPadLeft := scaleDP(dpi, 14) + dotD := scaleDP(dpi, 7) + dotGap := scaleDP(dpi, 8) + lockW := int32(0) + lockGap := int32(0) + if st.InputLocked { + lockW = scaleDP(dpi, 12) + lockGap = scaleDP(dpi, 6) + } + buttonsW := btnD + btnPadRight + if hasToggle { + buttonsW += btnD + btnGap + } + titleW := titleMeasuredW + if titleW <= 0 { + titleW = scaleDP(dpi, 120) + } + titleW = clampInt32(titleW, scaleDP(dpi, 84), scaleDP(dpi, 176)) + compactW := dotPadLeft + dotD + dotGap + lockW + lockGap + titleW + scaleDP(dpi, 12) + buttonsW + compactW = clampInt32(compactW, scaleDP(dpi, 224), scaleDP(dpi, 320)) + if clientW > 0 { + maxW := max(scaleDP(dpi, 176), clientW-scaleDP(dpi, 16)) + if compactW > maxW { + compactW = maxW + } + } + + // Expanded light macOS Tahoe card (336dp wide, sleek 14dp Swiss grid, 16dp radius). + expandedW := scaleDP(dpi, 336) + if clientW > 0 { + maxW := max(scaleDP(dpi, 256), clientW-scaleDP(dpi, 16)) + if expandedW > maxW { + expandedW = maxW + } + } + padX := scaleDP(dpi, 14) + padTop := scaleDP(dpi, 12) + headerH := scaleDP(dpi, 20) + stepH := scaleDP(dpi, 22) + statusLineH := scaleDP(dpi, 18) + btnH := scaleDP(dpi, 30) + padBottom := scaleDP(dpi, 12) + + curY := padTop + headerH + var stepRect rect2i + if hasStep { + curY += scaleDP(dpi, 7) + stepRect = rect2i{ + Left: padX, + Top: curY, + Right: expandedW - padX, + Bottom: curY + stepH, + } + curY += stepH + } + var statusRect rect2i + if hasStatus { + if hasStep { + curY += scaleDP(dpi, 3) + } else { + curY += scaleDP(dpi, 6) + } + statusH := statusLineH * int32(statusLines) + statusRect = rect2i{ + Left: padX, + Top: curY, + Right: expandedW - padX, + Bottom: curY + statusH, + } + curY += statusH + } + curY += scaleDP(dpi, 12) + expBtnTop := curY + expBtnBottom := expBtnTop + btnH + expandedH := expBtnBottom + padBottom + + t := easeSpring(morph) + pillW := lerpInt32(compactW, expandedW, t) + pillH := lerpInt32(compactH, expandedH, t) + compactRadius := float64(compactH) * 0.5 + expandedRadius := scaleDPF(dpi, 16) + pillRadius := lerpFloat(compactRadius, expandedRadius, t) + maxRadius := math.Min(float64(pillW), float64(pillH)) * 0.5 + if pillRadius > maxRadius { + pillRadius = maxRadius + } + + padShadowX, padShadowTop, padShadowBottom := shadowGutters(dpi) + + l := islandLayout{ + DPI: dpi, + CompactW: compactW, + CompactH: compactH, + ExpandedW: expandedW, + ExpandedH: expandedH, + HasStep: hasStep, + HasStatus: hasStatus, + StatusLineCnt: statusLines, + PillW: pillW, + PillH: pillH, + PillRadius: pillRadius, + PadX: padShadowX, + PadTop: padShadowTop, + PadBottom: padShadowBottom, + CanvasW: pillW + padShadowX*2, + CanvasH: pillH + padShadowTop + padShadowBottom, + HasToggle: hasToggle, + } + + // Compact element rects. + btnTop := (compactH - btnD) / 2 + l.CompactStopBtn = rect2i{ + Left: compactW - btnPadRight - btnD, + Top: btnTop, + Right: compactW - btnPadRight, + Bottom: btnTop + btnD, + } + buttonsLeft := l.CompactStopBtn.Left + if hasToggle { + l.CompactToggleBtn = rect2i{ + Left: l.CompactStopBtn.Left - btnGap - btnD, + Top: btnTop, + Right: l.CompactStopBtn.Left - btnGap, + Bottom: btnTop + btnD, + } + buttonsLeft = l.CompactToggleBtn.Left + } + l.CompactDotCenter = point2i{ + X: dotPadLeft + dotD/2, + Y: compactH / 2, + } + curX := dotPadLeft + dotD + dotGap + if st.InputLocked { + lockH := scaleDP(dpi, 12) + l.CompactLockRect = rect2i{ + Left: curX, + Top: (compactH - lockH) / 2, + Right: curX + lockW, + Bottom: (compactH + lockH) / 2, + } + curX += lockW + lockGap + } + l.CompactTitleRect = rect2i{ + Left: curX, + Top: 0, + Right: max(curX, buttonsLeft-scaleDP(dpi, 8)), + Bottom: compactH, + } + l.CompactInfoRect = rect2i{ + Left: 0, + Top: 0, + Right: max(int32(0), buttonsLeft-scaleDP(dpi, 3)), + Bottom: compactH, + } + + // Expanded element rects. + l.ExpandedDotCenter = point2i{ + X: padX + dotD/2, + Y: padTop + headerH/2, + } + foldD := scaleDP(dpi, 22) + l.ExpandedFoldBtn = rect2i{ + Left: expandedW - padX - foldD, + Top: padTop + (headerH-foldD)/2, + Right: expandedW - padX, + Bottom: padTop + (headerH+foldD)/2, + } + titleRight := l.ExpandedFoldBtn.Left - scaleDP(dpi, 6) + if st.InputLocked { + lockW := scaleDP(dpi, 15) + lockH := scaleDP(dpi, 18) + l.ExpandedLockBadge = rect2i{ + Left: l.ExpandedFoldBtn.Left - scaleDP(dpi, 5) - lockW, + Top: padTop + (headerH-lockH)/2, + Right: l.ExpandedFoldBtn.Left - scaleDP(dpi, 5), + Bottom: padTop + (headerH+lockH)/2, + } + titleRight = l.ExpandedLockBadge.Left - scaleDP(dpi, 6) + } + l.ExpandedTitleRect = rect2i{ + Left: padX + dotD + scaleDP(dpi, 7), + Top: padTop, + Right: max(padX+dotD+scaleDP(dpi, 7), titleRight), + Bottom: padTop + headerH, + } + l.ExpandedStepRect = stepRect + l.ExpandedStatusRect = statusRect + innerW := expandedW - padX*2 + if hasToggle { + gap := scaleDP(dpi, 8) + halfW := (innerW - gap) / 2 + l.ExpandedToggleBtn = rect2i{ + Left: padX, + Top: expBtnTop, + Right: padX + halfW, + Bottom: expBtnBottom, + } + l.ExpandedStopBtn = rect2i{ + Left: padX + halfW + gap, + Top: expBtnTop, + Right: expandedW - padX, + Bottom: expBtnBottom, + } + } else { + l.ExpandedStopBtn = rect2i{ + Left: padX, + Top: expBtnTop, + Right: expandedW - padX, + Bottom: expBtnBottom, + } + } + l.ExpandedHeaderRect = rect2i{ + Left: 0, + Top: 0, + Right: expandedW, + Bottom: expBtnTop - scaleDP(dpi, 4), + } + + // Cross-fade content alpha & continuous dot trajectory. + l.CompactAlpha = clamp01(1.0 - morph/0.35) + l.ExpandedAlpha = clamp01((morph - 0.42) / 0.58) + l.DotCenter = point2i{ + X: lerpInt32(l.CompactDotCenter.X, l.ExpandedDotCenter.X, t), + Y: lerpInt32(l.CompactDotCenter.Y, l.ExpandedDotCenter.Y, t), + } + + // Active hit rects follow whichever mode currently dominates visually. + if morph < 0.5 { + l.ActiveInfoRect = l.CompactInfoRect + l.ActiveToggleRect = l.CompactToggleBtn + l.ActiveStopRect = l.CompactStopBtn + } else { + l.ActiveInfoRect = l.ExpandedHeaderRect + l.ActiveToggleRect = l.ExpandedToggleBtn + l.ActiveStopRect = l.ExpandedStopBtn + l.ActiveFoldRect = l.ExpandedFoldBtn + } + return l +} + +func (l islandLayout) hitTestPill(localX, localY int32) hitZone { + if localX < 0 || localY < 0 || localX >= l.PillW || localY >= l.PillH { + return zoneNone + } + if l.ActiveFoldRect.contains(localX, localY) { + return zoneFold + } + if l.HasToggle && l.ActiveToggleRect.contains(localX, localY) { + return zoneToggle + } + if l.ActiveStopRect.contains(localX, localY) { + return zoneStop + } + if l.ActiveInfoRect.contains(localX, localY) { + return zoneInfo + } + return zoneInfo +} + +// islandController owns the pure Dynamic Island interaction state machine, +// morph animation, drag-and-snap animation, breathing phase, and rim pulse. +// By default the island starts and stays expanded so the live step and action +// controls remain visible; the user can still manually collapse via the fold +// button and expand again by clicking the compact pill. +type islandController struct { + anchor Anchor + reducedMotion bool + + hasState bool + state State + + expanded bool + manualCollapsed bool + morph float64 + morphFrom float64 + morphTo float64 + morphStart time.Time + + hoverZone hitZone + pressedZone hitZone + + // Drag & magnetic snap state (coordinates are VM client-relative pill top-left). + dragCandidate bool + dragging bool + dragStartScreen point2i + dragStartPill point2i + dragPos point2i + + snapping bool + snapFrom point2i + snapTo point2i + snapStart time.Time + + // Locked-screen click rim pulse. + pulseStart time.Time + breathBase time.Time +} + +func newIslandController(now time.Time, reducedMotion bool) *islandController { + return &islandController{ + anchor: AnchorTopRight, + reducedMotion: reducedMotion, + expanded: true, + morph: 1, + morphFrom: 1, + morphTo: 1, + breathBase: now, + } +} + +func (c *islandController) isPaused() bool { + return !c.state.Completed && c.state.CanResume +} + +func (c *islandController) isCompleted() bool { + return c.state.Completed +} + +func (c *islandController) setExpanded(target bool, now time.Time) { + if c.expanded == target && c.morphTo == boolToFloat(target) { + return + } + c.expanded = target + c.morphFrom = c.morph + c.morphTo = boolToFloat(target) + if c.reducedMotion { + c.morph = c.morphTo + c.morphStart = time.Time{} + return + } + c.morphStart = now +} + +func boolToFloat(b bool) float64 { + if b { + return 1 + } + return 0 +} + +// onStateUpdate ingests a new session State. The island stays expanded by +// default; if the user manually folded it, entering paused state automatically +// re-expands it so Resume/Stop are immediately visible. +func (c *islandController) onStateUpdate(st State, now time.Time) { + prev := c.state + first := !c.hasState + c.hasState = true + c.state = st + + if first { + c.manualCollapsed = false + c.expanded = true + c.morph = 1 + c.morphFrom = 1 + c.morphTo = 1 + c.morphStart = time.Time{} + return + } + + enteredPaused := !prev.CanResume && st.CanResume && !st.Completed + enteredCompleted := !prev.Completed && st.Completed + if enteredPaused || enteredCompleted { + c.manualCollapsed = false + c.setExpanded(true, now) + } +} + +// onLockedScreenClick is triggered when the user clicks the VM client area +// while InputLocked is true. It ensures the island is expanded and plays a +// soft rim pulse. +func (c *islandController) onLockedScreenClick(now time.Time) { + c.manualCollapsed = false + c.setExpanded(true, now) + if !c.reducedMotion { + c.pulseStart = now + } +} + +// currentPillOrigin returns the pill top-left position in VM client coordinates, +// accounting for active dragging and magnetic snap interpolation. +func (c *islandController) currentPillOrigin(clientW, clientH, pillW, pillH, dpi int32, now time.Time) point2i { + if c.dragging { + return point2i{ + X: clampInt32(c.dragPos.X, 0, max(int32(0), clientW-pillW)), + Y: clampInt32(c.dragPos.Y, 0, max(int32(0), clientH-pillH)), + } + } + target := anchorOrigin(c.anchor, clientW, clientH, pillW, pillH, dpi) + if c.snapping && !c.reducedMotion { + elapsed := now.Sub(c.snapStart) + if elapsed >= snapDuration { + c.snapping = false + return target + } + t := easeSpring(float64(elapsed) / float64(snapDuration)) + return point2i{ + X: clampInt32(lerpInt32(c.snapFrom.X, target.X, t), 0, max(int32(0), clientW-pillW)), + Y: clampInt32(lerpInt32(c.snapFrom.Y, target.Y, t), 0, max(int32(0), clientH-pillH)), + } + } + return target +} + +func (c *islandController) onPointerDown(screenPt point2i, pillLocal point2i, curPillOrigin point2i, layout islandLayout, now time.Time) { + zone := layout.hitTestPill(pillLocal.X, pillLocal.Y) + c.pressedZone = zone + c.hoverZone = zone + if zone == zoneInfo { + c.dragCandidate = true + c.dragging = false + c.dragStartScreen = screenPt + c.dragStartPill = curPillOrigin + c.dragPos = curPillOrigin + } else { + c.dragCandidate = false + c.dragging = false + } +} + +func (c *islandController) onPointerMove(screenPt point2i, pillLocal point2i, clientW, clientH int32, layout islandLayout, now time.Time) (hoverChanged bool, moved bool) { + if c.dragCandidate && !c.dragging { + thresh := scaleDP(layout.DPI, 5) + dx := screenPt.X - c.dragStartScreen.X + dy := screenPt.Y - c.dragStartScreen.Y + if dx < 0 { + dx = -dx + } + if dy < 0 { + dy = -dy + } + if dx >= thresh || dy >= thresh { + c.dragging = true + c.snapping = false + c.pressedZone = zoneNone + } + } + if c.dragging { + nextX := clampInt32(c.dragStartPill.X+(screenPt.X-c.dragStartScreen.X), 0, max(int32(0), clientW-layout.PillW)) + nextY := clampInt32(c.dragStartPill.Y+(screenPt.Y-c.dragStartScreen.Y), 0, max(int32(0), clientH-layout.PillH)) + if nextX != c.dragPos.X || nextY != c.dragPos.Y { + c.dragPos = point2i{X: nextX, Y: nextY} + return false, true + } + return false, false + } + + zone := layout.hitTestPill(pillLocal.X, pillLocal.Y) + hoverChanged = zone != c.hoverZone + c.hoverZone = zone + return hoverChanged, false +} + +func (c *islandController) onPointerLeave(now time.Time) bool { + changed := c.hoverZone != zoneNone + c.hoverZone = zoneNone + return changed +} + +func (c *islandController) onPointerUp(pillLocal point2i, clientW, clientH int32, layout islandLayout, now time.Time) (act clickAction, snapped bool) { + if c.dragging { + c.dragging = false + c.dragCandidate = false + c.pressedZone = zoneNone + targetAnchor := nearestAnchor(c.dragPos, clientW, clientH, layout.PillW, layout.PillH, layout.DPI) + c.anchor = targetAnchor + targetPos := anchorOrigin(targetAnchor, clientW, clientH, layout.PillW, layout.PillH, layout.DPI) + if !c.reducedMotion && targetPos != c.dragPos { + c.snapping = true + c.snapFrom = c.dragPos + c.snapTo = targetPos + c.snapStart = now + } else { + c.snapping = false + } + return actionNone, true + } + + pressed := c.pressedZone + c.pressedZone = zoneNone + c.dragCandidate = false + + zone := layout.hitTestPill(pillLocal.X, pillLocal.Y) + if pressed == zoneToggle && zone == zoneToggle { + return actionToggle, false + } + if pressed == zoneStop && zone == zoneStop { + return actionStop, false + } + if pressed == zoneFold && zone == zoneFold { + c.manualCollapsed = true + c.setExpanded(false, now) + return actionNone, false + } + if pressed == zoneInfo && zone == zoneInfo && !c.expanded { + c.manualCollapsed = false + c.setExpanded(true, now) + } + return actionNone, false +} + +// pulseIntensity returns a smooth [0, 1] glow factor for the locked-screen +// click feedback pulse. +func (c *islandController) pulseIntensity(now time.Time) float64 { + if c.pulseStart.IsZero() || c.reducedMotion { + return 0 + } + elapsed := now.Sub(c.pulseStart) + if elapsed < 0 || elapsed >= pulseDuration { + return 0 + } + p := float64(elapsed) / float64(pulseDuration) + if p < 0.22 { + return p / 0.22 + } + rem := 1.0 - (p-0.22)/0.78 + return rem * rem +} + +// breathLevel returns a smooth [0, 1] luminance factor for the running dot halo. +func (c *islandController) breathLevel(now time.Time) float64 { + if c.reducedMotion || c.isPaused() || c.isCompleted() { + return 0.65 + } + phase := float64(now.Sub(c.breathBase)%breathPeriod) / float64(breathPeriod) + return 0.5 + 0.5*math.Sin(phase*2*math.Pi) +} + +// tick advances active animations. It reports whether a repaint is needed and +// whether high-frequency (60fps) animation is currently active. +func (c *islandController) tick(now time.Time) (changed bool, highFreq bool) { + // 1. Morph progress. + if !c.morphStart.IsZero() { + elapsed := now.Sub(c.morphStart) + if elapsed >= morphDuration || c.reducedMotion { + if c.morph != c.morphTo { + c.morph = c.morphTo + changed = true + } + c.morphStart = time.Time{} + } else { + p := clamp01(float64(elapsed) / float64(morphDuration)) + next := lerpFloat(c.morphFrom, c.morphTo, p) + if math.Abs(next-c.morph) > 1e-4 { + c.morph = next + changed = true + } + highFreq = true + } + } + + // 2. Magnetic snap progress. + if c.snapping { + if now.Sub(c.snapStart) >= snapDuration || c.reducedMotion { + c.snapping = false + changed = true + } else { + changed = true + highFreq = true + } + } + + // 3. Locked-screen rim pulse. + if !c.pulseStart.IsZero() { + if now.Sub(c.pulseStart) >= pulseDuration || c.reducedMotion { + c.pulseStart = time.Time{} + changed = true + } else { + changed = true + highFreq = true + } + } + + return changed, highFreq +} diff --git a/internal/host/sessionoverlay/island_model_test.go b/internal/host/sessionoverlay/island_model_test.go new file mode 100644 index 0000000..04abc95 --- /dev/null +++ b/internal/host/sessionoverlay/island_model_test.go @@ -0,0 +1,299 @@ +package sessionoverlay + +import ( + "testing" + "time" +) + +func TestAnchorOriginAndDirectionalExpansion(t *testing.T) { + const ( + clientW = int32(1280) + clientH = int32(800) + dpi = int32(96) + ) + st := State{ + Title: "AI 正在操作", + StepBadge: "当前步骤", + StepText: "步骤 1 · 进入恢复环境", + StatusLine: "画面已锁定防干扰", + CanPause: true, + } + compact := computeIslandLayout(st, dpi, clientW, 110, 1, 0) + expanded := computeIslandLayout(st, dpi, clientW, 110, 1, 1) + + if !expanded.HasStep || expanded.ExpandedStepRect.height() <= 0 { + t.Fatalf("expected visible step strip in expanded layout, got %+v", expanded.ExpandedStepRect) + } + if expanded.ExpandedFoldBtn.width() <= 0 || expanded.ExpandedFoldBtn.height() <= 0 { + t.Fatalf("expected fold button rect in expanded layout, got %+v", expanded.ExpandedFoldBtn) + } + + // TopRight expands leftward and downward (right edge and top edge stay anchored). + trC := anchorOrigin(AnchorTopRight, clientW, clientH, compact.PillW, compact.PillH, dpi) + trE := anchorOrigin(AnchorTopRight, clientW, clientH, expanded.PillW, expanded.PillH, dpi) + if trC.X+compact.PillW != trE.X+expanded.PillW { + t.Fatalf("TopRight right edge drifted: compact=%d expanded=%d", trC.X+compact.PillW, trE.X+expanded.PillW) + } + if trC.Y != trE.Y { + t.Fatalf("TopRight top edge drifted: compact=%d expanded=%d", trC.Y, trE.Y) + } + if trE.X >= trC.X { + t.Fatalf("TopRight did not expand leftward: compact.X=%d expanded.X=%d", trC.X, trE.X) + } + + // TopLeft expands rightward and downward. + tlC := anchorOrigin(AnchorTopLeft, clientW, clientH, compact.PillW, compact.PillH, dpi) + tlE := anchorOrigin(AnchorTopLeft, clientW, clientH, expanded.PillW, expanded.PillH, dpi) + if tlC.X != tlE.X || tlC.Y != tlE.Y { + t.Fatalf("TopLeft origin drifted: compact=%+v expanded=%+v", tlC, tlE) + } + + // TopCenter expands symmetrically around center. + tcC := anchorOrigin(AnchorTopCenter, clientW, clientH, compact.PillW, compact.PillH, dpi) + tcE := anchorOrigin(AnchorTopCenter, clientW, clientH, expanded.PillW, expanded.PillH, dpi) + centerDiff := (tcC.X + compact.PillW/2) - (tcE.X + expanded.PillW/2) + if centerDiff < -1 || centerDiff > 1 { + t.Fatalf("TopCenter not horizontally centered: compact=%+v expanded=%+v", tcC, tcE) + } + + // BottomRight expands leftward and upward (right and bottom edges stay anchored). + brC := anchorOrigin(AnchorBottomRight, clientW, clientH, compact.PillW, compact.PillH, dpi) + brE := anchorOrigin(AnchorBottomRight, clientW, clientH, expanded.PillW, expanded.PillH, dpi) + if brC.X+compact.PillW != brE.X+expanded.PillW || brC.Y+compact.PillH != brE.Y+expanded.PillH { + t.Fatalf("BottomRight edge drifted: compact=%+v expanded=%+v", brC, brE) + } + if brE.Y >= brC.Y { + t.Fatalf("BottomRight did not expand upward: compact.Y=%d expanded.Y=%d", brC.Y, brE.Y) + } +} + +func TestNearestAnchorSelection(t *testing.T) { + const ( + clientW = int32(1280) + clientH = int32(800) + pillW = int32(368) + pillH = int32(141) + dpi = int32(96) + ) + cases := []struct { + name string + pos point2i + want Anchor + }{ + {"top-left", point2i{40, 50}, AnchorTopLeft}, + {"top-center", point2i{460, 48}, AnchorTopCenter}, + {"top-right", point2i{880, 40}, AnchorTopRight}, + {"bottom-left", point2i{30, 620}, AnchorBottomLeft}, + {"bottom-center", point2i{460, 630}, AnchorBottomCenter}, + {"bottom-right", point2i{880, 630}, AnchorBottomRight}, + } + for _, tc := range cases { + if got := nearestAnchor(tc.pos, clientW, clientH, pillW, pillH, dpi); got != tc.want { + t.Errorf("%s: nearestAnchor(%+v) = %v, want %v", tc.name, tc.pos, got, tc.want) + } + } +} + +func TestCompactQuickButtonHitTargetsMeetMinimumSize(t *testing.T) { + st := State{Title: "macOS Auto-Install", StepText: "Step 2 · Erase Disk", CanPause: true, InputLocked: true} + if got := compactPrimaryText(st); got != "Step 2 · Erase Disk" { + t.Fatalf("compactPrimaryText = %q, want StepText", got) + } + for _, dpi := range []int32{96, 120, 144, 192} { + layout := computeIslandLayout(st, dpi, 1280, 120, 1, 0) + minHit := scaleDP(dpi, 28) + if layout.CompactToggleBtn.width() < minHit || layout.CompactToggleBtn.height() < minHit { + t.Fatalf("dpi=%d: compact toggle button %+v smaller than %dx%d", dpi, layout.CompactToggleBtn, minHit, minHit) + } + if layout.CompactStopBtn.width() < minHit || layout.CompactStopBtn.height() < minHit { + t.Fatalf("dpi=%d: compact stop button %+v smaller than %dx%d", dpi, layout.CompactStopBtn, minHit, minHit) + } + if layout.CompactInfoRect.Right >= layout.CompactToggleBtn.Left { + t.Fatalf("dpi=%d: compact info zone overlaps quick toggle button: info=%+v toggle=%+v", dpi, layout.CompactInfoRect, layout.CompactToggleBtn) + } + } +} + +func TestIslandDefaultsExpandedAndSupportsManualFoldAndUnfold(t *testing.T) { + t0 := time.Date(2026, 12, 4, 10, 0, 0, 0, time.UTC) + ctrl := newIslandController(t0, false) + st := State{ + Title: "AI 正在操作", + StepBadge: "当前步骤", + StepText: "步骤 1 · 进入恢复环境", + StatusLine: "画面已锁定防干扰", + CanPause: true, + InputLocked: true, + } + ctrl.onStateUpdate(st, t0) + if !ctrl.expanded || ctrl.morph != 1 { + t.Fatalf("expected island to start expanded at morph=1, got expanded=%v morph=%v", ctrl.expanded, ctrl.morph) + } + + // Idle and pointer leave must NOT auto-collapse the island. + ctrl.onPointerLeave(t0.Add(time.Second)) + ctrl.tick(t0.Add(30 * time.Second)) + if !ctrl.expanded || ctrl.morph != 1 { + t.Fatalf("default-expanded island must stay expanded over time, got expanded=%v morph=%v", ctrl.expanded, ctrl.morph) + } + + // Clicking the expanded card body (outside fold/action buttons) must NOT accidentally fold. + exp := computeIslandLayout(st, 96, 1280, 120, 1, 1) + headerPt := point2i{40, 18} + tClickBody := t0.Add(31 * time.Second) + ctrl.onPointerDown(headerPt, headerPt, point2i{890, 36}, exp, tClickBody) + ctrl.onPointerUp(headerPt, 1280, 800, exp, tClickBody.Add(30*time.Millisecond)) + if !ctrl.expanded { + t.Fatal("clicking expanded body must not accidentally fold the island") + } + + // Clicking the dedicated top-right fold button collapses into compact pill. + foldPt := point2i{(exp.ExpandedFoldBtn.Left + exp.ExpandedFoldBtn.Right) / 2, (exp.ExpandedFoldBtn.Top + exp.ExpandedFoldBtn.Bottom) / 2} + tFold := t0.Add(32 * time.Second) + ctrl.onPointerDown(foldPt, foldPt, point2i{890, 36}, exp, tFold) + ctrl.onPointerUp(foldPt, 1280, 800, exp, tFold.Add(30*time.Millisecond)) + if ctrl.expanded || !ctrl.manualCollapsed { + t.Fatal("clicking fold button should collapse the island") + } + ctrl.tick(tFold.Add(morphDuration + 40*time.Millisecond)) + if ctrl.morph != 0 { + t.Fatalf("morph after fold = %v, want 0", ctrl.morph) + } + + // Routine running step updates respect manual fold while keeping compact pill updated. + nextSt := st + nextSt.StepText = "步骤 2 · 磁盘工具抹盘" + ctrl.onStateUpdate(nextSt, tFold.Add(time.Second)) + if ctrl.expanded { + t.Fatal("routine running update should respect manual fold") + } + + // Clicking the compact pill info zone expands back to expanded mode. + compact := computeIslandLayout(nextSt, 96, 1280, 120, 1, 0) + infoPt := point2i{40, compact.CompactH / 2} + tUnfold := tFold.Add(2 * time.Second) + ctrl.onPointerDown(infoPt, infoPt, point2i{960, 36}, compact, tUnfold) + ctrl.onPointerUp(infoPt, 1280, 800, compact, tUnfold.Add(30*time.Millisecond)) + if !ctrl.expanded || ctrl.manualCollapsed { + t.Fatal("clicking compact pill info zone should expand the island") + } + + // If manually folded again, transitioning into paused (CanResume=true) auto-expands. + ctrl.manualCollapsed = true + ctrl.setExpanded(false, tUnfold.Add(time.Second)) + pausedSt := nextSt + pausedSt.CanPause = false + pausedSt.CanResume = true + ctrl.onStateUpdate(pausedSt, tUnfold.Add(2*time.Second)) + if !ctrl.expanded { + t.Fatal("entering paused state should re-expand a manually folded island") + } +} + +func TestLockedScreenClickExpandsAndPulses(t *testing.T) { + t0 := time.Date(2026, 12, 4, 10, 0, 0, 0, time.UTC) + ctrl := newIslandController(t0, false) + st := State{Title: "AI 控制中", StepText: "步骤 1 · 进入恢复环境", StatusLine: "画面已锁定防干扰", CanPause: true, InputLocked: true} + ctrl.onStateUpdate(st, t0) + + // Manually fold first, then click the locked VM screen -> re-expands + pulses. + ctrl.manualCollapsed = true + ctrl.setExpanded(false, t0.Add(time.Second)) + ctrl.tick(t0.Add(time.Second + morphDuration + 20*time.Millisecond)) + if ctrl.expanded { + t.Fatal("expected island to be folded before locked-screen click") + } + + tClick := t0.Add(3 * time.Second) + ctrl.onLockedScreenClick(tClick) + if !ctrl.expanded { + t.Fatal("expected locked-screen click to expand island") + } + if p := ctrl.pulseIntensity(tClick.Add(100 * time.Millisecond)); p <= 0.5 { + t.Fatalf("expected strong rim pulse after locked-screen click, got %v", p) + } + if p := ctrl.pulseIntensity(tClick.Add(pulseDuration + time.Millisecond)); p != 0 { + t.Fatalf("expected rim pulse to decay to 0, got %v", p) + } +} + +func TestDragBeyondThresholdSnapsToNearestAnchorWithoutTriggeringClick(t *testing.T) { + t0 := time.Date(2026, 12, 4, 10, 0, 0, 0, time.UTC) + ctrl := newIslandController(t0, false) + st := State{Title: "AI 控制中", StepText: "步骤 2 · 磁盘工具抹盘", CanPause: true} + ctrl.onStateUpdate(st, t0) + + layout := computeIslandLayout(st, 96, 1280, 120, 1, 1) + startOrigin := anchorOrigin(AnchorTopRight, 1280, 800, layout.PillW, layout.PillH, 96) + infoPt := point2i{40, 18} + + // Drag expanded card from TopRight all the way to BottomLeft. + tDrag := t0.Add(time.Second) + ctrl.onPointerDown(point2i{1000, 54}, infoPt, startOrigin, layout, tDrag) + _, moved := ctrl.onPointerMove(point2i{40, 640}, infoPt, 1280, 800, layout, tDrag.Add(30*time.Millisecond)) + if !moved || !ctrl.dragging { + t.Fatal("expected pointer movement past threshold to start dragging") + } + act, snapped := ctrl.onPointerUp(infoPt, 1280, 800, layout, tDrag.Add(60*time.Millisecond)) + if act != actionNone { + t.Fatalf("drag release must not trigger button action, got %v", act) + } + if !snapped || ctrl.anchor != AnchorBottomLeft { + t.Fatalf("expected snap to AnchorBottomLeft, got snapped=%v anchor=%v", snapped, ctrl.anchor) + } + if !ctrl.expanded { + t.Fatal("drag release on expanded island must preserve expanded state") + } +} + +func TestIslandCompletedStateAutoExpandsUnlocksAndHasCloseOnly(t *testing.T) { + t0 := time.Date(2026, 12, 5, 10, 0, 0, 0, time.UTC) + ctrl := newIslandController(t0, false) + running := State{ + Title: "AI 正在操作", + StepText: "步骤 3 · 等待系统安装", + StatusLine: "画面已锁定防干扰", + CanPause: true, + InputLocked: true, + } + ctrl.onStateUpdate(running, t0) + + // Manually collapse during run. + ctrl.manualCollapsed = true + ctrl.setExpanded(false, t0.Add(time.Second)) + ctrl.tick(t0.Add(time.Second + morphDuration + 20*time.Millisecond)) + if ctrl.expanded { + t.Fatal("expected island to be collapsed before completion") + } + + // Transitioning to Completed must auto-expand, remove Pause/Resume toggle, and stop breathing. + done := State{ + Title: "macOS 自动装机助手", + StepText: "已完成", + StatusLine: "已完成恢复模式安装并进入 macOS,画面输入已解锁", + Completed: true, + CloseLabel: "关闭", + InputLocked: false, + } + ctrl.onStateUpdate(done, t0.Add(2*time.Second)) + if !ctrl.expanded || ctrl.manualCollapsed { + t.Fatal("entering Completed state must auto-expand a manually folded island") + } + if !ctrl.isCompleted() || ctrl.isPaused() { + t.Fatalf("expected completed=true paused=false, got completed=%v paused=%v", ctrl.isCompleted(), ctrl.isPaused()) + } + if got := ctrl.breathLevel(t0.Add(3 * time.Second)); got != 0.65 { + t.Fatalf("completed island should use steady dot (0.65), got %v", got) + } + + expLayout := computeIslandLayout(done, 96, 1280, 80, 1, 1) + if expLayout.HasToggle { + t.Fatal("completed island must not render Pause/Resume toggle button") + } + if expLayout.ExpandedStopBtn.width() < expLayout.ExpandedW-scaleDP(96, 32) { + t.Fatalf("expected full-width Close button in completed expanded layout, got %+v (expandedW=%d)", expLayout.ExpandedStopBtn, expLayout.ExpandedW) + } + if got := compactPrimaryText(done); got != "已完成" { + t.Fatalf("compactPrimaryText(done) = %q, want 已完成", got) + } +} diff --git a/internal/host/sessionoverlay/overlay.go b/internal/host/sessionoverlay/overlay.go new file mode 100644 index 0000000..c944acd --- /dev/null +++ b/internal/host/sessionoverlay/overlay.go @@ -0,0 +1,108 @@ +package sessionoverlay + +import "sync" + +// State describes the live Agent/automation session banner shown on a VM window. +type State struct { + VMKey string + PID uint32 + Locale string + Title string + StepBadge string + StepText string + StatusLine string + Completed bool + CanPause bool + PauseLabel string + CanResume bool + ResumeLabel string + StopLabel string + CloseLabel string + CollapseLabel string + InputLocked bool + Dark bool +} + +// Callbacks connects overlay button clicks back to the host application. +type Callbacks struct { + OnStop func(vmKey string) + OnPause func(vmKey string) + OnResume func(vmKey string) + OnDismiss func(vmKey string) +} + +// Manager coordinates one Win32 floating banner per active VM session. +// It is host-owned and driver-agnostic so it works across all process-backed VMs. +type Manager struct { + cb Callbacks + + mu sync.Mutex + closed bool + items map[string]*entry +} + +// NewManager creates an idle overlay manager. No OS threads or windows are +// created until Upsert is called for an active session. +func NewManager(cb Callbacks) *Manager { + return &Manager{ + cb: cb, + items: make(map[string]*entry), + } +} + +// Upsert starts or updates the floating overlay for state.VMKey. +func (m *Manager) Upsert(state State) { + if m == nil || state.VMKey == "" { + return + } + if state.StopLabel == "" { + state.StopLabel = "Stop" + } + if state.CloseLabel == "" { + state.CloseLabel = "Close" + } + if state.PauseLabel == "" { + state.PauseLabel = "Pause" + } + if state.ResumeLabel == "" { + state.ResumeLabel = "Resume" + } + if state.CollapseLabel == "" { + state.CollapseLabel = "Collapse" + } + if state.Completed { + state.InputLocked = false + state.CanPause = false + state.CanResume = false + } + if state.StepText != "" && state.StepBadge == "" { + state.StepBadge = "Step" + } + m.upsertPlatform(state) +} + +// Remove closes and removes the floating overlay for vmKey. +func (m *Manager) Remove(vmKey string) { + if m == nil || vmKey == "" { + return + } + m.removePlatform(vmKey) +} + +// ActiveCount reports how many overlays are currently tracked. +func (m *Manager) ActiveCount() int { + if m == nil { + return 0 + } + m.mu.Lock() + defer m.mu.Unlock() + return len(m.items) +} + +// Close tears down all overlays. +func (m *Manager) Close() { + if m == nil { + return + } + m.closePlatform() +} diff --git a/internal/host/sessionoverlay/overlay_other.go b/internal/host/sessionoverlay/overlay_other.go new file mode 100644 index 0000000..6f0b3e4 --- /dev/null +++ b/internal/host/sessionoverlay/overlay_other.go @@ -0,0 +1,29 @@ +//go:build !windows + +package sessionoverlay + +type entry struct { + state State +} + +func (m *Manager) upsertPlatform(state State) { + m.mu.Lock() + defer m.mu.Unlock() + if m.closed { + return + } + m.items[state.VMKey] = &entry{state: state} +} + +func (m *Manager) removePlatform(vmKey string) { + m.mu.Lock() + defer m.mu.Unlock() + delete(m.items, vmKey) +} + +func (m *Manager) closePlatform() { + m.mu.Lock() + defer m.mu.Unlock() + m.closed = true + m.items = map[string]*entry{} +} diff --git a/internal/host/sessionoverlay/overlay_test.go b/internal/host/sessionoverlay/overlay_test.go new file mode 100644 index 0000000..31de49a --- /dev/null +++ b/internal/host/sessionoverlay/overlay_test.go @@ -0,0 +1,21 @@ +package sessionoverlay + +import "testing" + +func TestManagerLifecycle(t *testing.T) { + mgr := NewManager(Callbacks{}) + defer mgr.Close() + + mgr.Upsert(State{VMKey: "builtin.guest.macos:dev", PID: 0, Title: "AI Controlling", StatusLine: "Stage 1", CanPause: true, InputLocked: true}) + if got := mgr.ActiveCount(); got != 1 { + t.Fatalf("ActiveCount = %d, want 1", got) + } + mgr.Upsert(State{VMKey: "builtin.guest.macos:dev", PID: 0, Title: "AI Controlling", StatusLine: "Stage 2", CanResume: true, InputLocked: false}) + if got := mgr.ActiveCount(); got != 1 { + t.Fatalf("ActiveCount after update = %d, want 1", got) + } + mgr.Remove("builtin.guest.macos:dev") + if got := mgr.ActiveCount(); got != 0 { + t.Fatalf("ActiveCount after remove = %d, want 0", got) + } +} diff --git a/internal/host/sessionoverlay/overlay_windows.go b/internal/host/sessionoverlay/overlay_windows.go new file mode 100644 index 0000000..cc25184 --- /dev/null +++ b/internal/host/sessionoverlay/overlay_windows.go @@ -0,0 +1,1475 @@ +//go:build windows + +package sessionoverlay + +import ( + "fmt" + "runtime" + "strings" + "sync" + "sync/atomic" + "syscall" + "time" + "unsafe" +) + +const ( + wmDestroy = 0x0002 + wmPaint = 0x000F + wmClose = 0x0010 + wmEraseBkgnd = 0x0014 + wmSetCursor = 0x0020 + wmMouseAct = 0x0021 + wmTimer = 0x0113 + wmMouseMove = 0x0200 + wmLButtonDown = 0x0201 + wmLButtonUp = 0x0202 + wmRButtonDown = 0x0204 + wmRButtonUp = 0x0205 + wmMButtonDown = 0x0207 + wmMButtonUp = 0x0208 + wmMouseWheel = 0x020A + wmXButtonDown = 0x020B + wmXButtonUp = 0x020C + wmMouseHWheel = 0x020E + wmCaptureChanged = 0x0215 + wmMouseLeave = 0x02A3 + wmDPIChanged = 0x02E0 + + wmSyncState = 0x8003 + wmLockedClick = 0x8004 + wmOwnerEvent = 0x8005 + + maNoActivate = 3 + idcArrow = 32512 + idcHand = 32649 + + wsPopup = 0x80000000 + wsClipSibs = 0x04000000 + wsExTopmost = 0x00000008 + wsExTransparent = 0x00000020 + wsExToolWin = 0x00000080 + wsExLayered = 0x00080000 + wsExNoAct = 0x08000000 + + gwHwndPrev = 3 + gwOwner = 4 + hwndTopmost = ^uintptr(0) + hwndNoTopmost = ^uintptr(1) + + lwaAlpha = 0x00000002 + ulwAlpha = 0x00000002 + acSrcOver = 0x00 + acSrcAlpha = 0x01 + swpNoSize = 0x0001 + swpNoMove = 0x0002 + swpNoZOrder = 0x0004 + swpNoActivate = 0x0010 + swpShowWindow = 0x0040 + swpNoOwnerZ = 0x0200 + swHide = 0 + tmeLeave = 0x00000002 + + dtLeft = 0x00000000 + dtCenter = 0x00000001 + dtVCenter = 0x00000004 + dtSingleLine = 0x00000020 + dtNoPrefix = 0x00000800 + dtEndEllipsis = 0x00008000 + transparent = 1 + + spiGetClientAreaAnimation = 0x1042 + + eventSystemForeground = 0x0003 + eventSystemMoveSizeEnd = 0x000B + eventSystemMinimizeStart = 0x0016 + eventSystemMinimizeEnd = 0x0017 + eventObjectShow = 0x8002 + eventObjectLocation = 0x800B + + timerSyncID = 1 + timerFastMs = 16 + timerDiscoverMs = 40 + timerBreathMs = 100 + timerIdleMs = 120 + tooltipHoverDur = 260 * time.Millisecond +) + +var ( + user32 = syscall.NewLazyDLL("user32.dll") + gdi32 = syscall.NewLazyDLL("gdi32.dll") + kernel32 = syscall.NewLazyDLL("kernel32.dll") + + procRegisterClassExW = user32.NewProc("RegisterClassExW") + procCreateWindowExW = user32.NewProc("CreateWindowExW") + procDestroyWindow = user32.NewProc("DestroyWindow") + procDefWindowProcW = user32.NewProc("DefWindowProcW") + procGetMessageW = user32.NewProc("GetMessageW") + procTranslateMessage = user32.NewProc("TranslateMessage") + procDispatchMessageW = user32.NewProc("DispatchMessageW") + procPostMessageW = user32.NewProc("PostMessageW") + procPostQuitMessage = user32.NewProc("PostQuitMessage") + procBeginPaint = user32.NewProc("BeginPaint") + procEndPaint = user32.NewProc("EndPaint") + procDrawTextW = user32.NewProc("DrawTextW") + procSetTimer = user32.NewProc("SetTimer") + procKillTimer = user32.NewProc("KillTimer") + procShowWindow = user32.NewProc("ShowWindow") + procSetWindowPos = user32.NewProc("SetWindowPos") + procSetLayeredAttr = user32.NewProc("SetLayeredWindowAttributes") + procUpdateLayeredWindow = user32.NewProc("UpdateLayeredWindow") + procIsWindow = user32.NewProc("IsWindow") + procIsWindowVisible = user32.NewProc("IsWindowVisible") + procIsIconic = user32.NewProc("IsIconic") + procGetClientRect = user32.NewProc("GetClientRect") + procClientToScreen = user32.NewProc("ClientToScreen") + procGetCursorPos = user32.NewProc("GetCursorPos") + procEnumWindows = user32.NewProc("EnumWindows") + procGetForegroundWindow = user32.NewProc("GetForegroundWindow") + procGetWindow = user32.NewProc("GetWindow") + procGetWindowPID = user32.NewProc("GetWindowThreadProcessId") + procGetClassNameW = user32.NewProc("GetClassNameW") + procGetWindowLongPtr = user32.NewProc("GetWindowLongPtrW") + procSetWindowLongPtr = user32.NewProc("SetWindowLongPtrW") + procGetDpiForWindow = user32.NewProc("GetDpiForWindow") + procLoadCursorW = user32.NewProc("LoadCursorW") + procSetCursor = user32.NewProc("SetCursor") + procSetCapture = user32.NewProc("SetCapture") + procReleaseCapture = user32.NewProc("ReleaseCapture") + procTrackMouseEvent = user32.NewProc("TrackMouseEvent") + procGetDC = user32.NewProc("GetDC") + procReleaseDC = user32.NewProc("ReleaseDC") + procSystemParametersInfoW = user32.NewProc("SystemParametersInfoW") + procSetWinEventHook = user32.NewProc("SetWinEventHook") + procUnhookWinEvent = user32.NewProc("UnhookWinEvent") + + procGetModuleHandleW = kernel32.NewProc("GetModuleHandleW") + + procCreateCompatibleDC = gdi32.NewProc("CreateCompatibleDC") + procDeleteDC = gdi32.NewProc("DeleteDC") + procCreateDIBSection = gdi32.NewProc("CreateDIBSection") + procCreateFontIndirectW = gdi32.NewProc("CreateFontIndirectW") + procEnumFontFamiliesExW = gdi32.NewProc("EnumFontFamiliesExW") + procGetTextExtentExPointW = gdi32.NewProc("GetTextExtentExPointW") + procSelectObject = gdi32.NewProc("SelectObject") + procDeleteObject = gdi32.NewProc("DeleteObject") + procSetBkMode = gdi32.NewProc("SetBkMode") + procSetTextColor = gdi32.NewProc("SetTextColor") + procGdiFlush = gdi32.NewProc("GdiFlush") + + classOnce sync.Once + className string + tipClassName string + shieldClassName string + classSeq atomic.Uint64 + + hwndMapMu sync.RWMutex + hwndToEnt = map[uintptr]*entry{} + shieldToEnt = map[uintptr]*entry{} + winEventMu sync.Mutex + winEventHooks = map[uintptr]func(event uint32, hwnd uintptr, idObject, idChild int32){} + + wndProcCB = syscall.NewCallback(overlayWndProc) + passiveWndCB = syscall.NewCallback(passiveWndProc) + shieldWndProcCB = syscall.NewCallback(shieldWndProc) + enumFindCB = syscall.NewCallback(enumFindOwnerProc) + winEventCB = syscall.NewCallback(winEventHookProc) +) + +type winPoint struct{ X, Y int32 } +type winSize struct{ CX, CY int32 } +type winRect struct{ Left, Top, Right, Bottom int32 } + +type blendFunction struct { + BlendOp byte + BlendFlags byte + SourceConstantAlpha byte + AlphaFormat byte +} + +type trackMouseStruct struct { + CbSize uint32 + DwFlags uint32 + HwndTrack uintptr + DwHoverTime uint32 +} + +type wndClassExW struct { + CbSize uint32 + Style uint32 + LpfnWndProc uintptr + CbClsExtra int32 + CbWndExtra int32 + HInstance uintptr + HIcon uintptr + HCursor uintptr + HbrBackground uintptr + LpszMenuName *uint16 + LpszClassName *uint16 + HIconSm uintptr +} + +type paintStruct struct { + HDC uintptr + FErase int32 + RcPaint winRect + FRestore int32 + FIncUpdate int32 + RgbReserved [32]byte +} + +type winMsg struct { + HWnd uintptr + Message uint32 + WParam uintptr + LParam uintptr + Time uint32 + Pt winPoint + Private uint32 +} + +type entry struct { + mgr *Manager + + mu sync.Mutex + state State + hwnd uintptr + closed bool + done chan struct{} + + // UI-thread-only fields (accessed exclusively on entry.run()'s OS thread). + hwndSelf uintptr + tipHwnd uintptr + shieldHwnd uintptr + owner uintptr + hookPID uint32 + unhookEvents func() + unhookFG func() + visible bool + tipVisible bool + tipText string + tipTargetZone hitZone + tipHoverSince time.Time + shieldVisible bool + shieldRect winRect + + clientOrigin winPoint + clientW int32 + clientH int32 + dpi int32 + layout islandLayout + pillScreenX int32 + pillScreenY int32 + lastWinX int32 + lastWinY int32 + lastCanvasW int32 + lastCanvasH int32 + statusLines []string + + ctrl *islandController + dw dwriteEngine + canvas dibSurface + baseCache islandBaseCache + scratch dibSurface + tipCanvas dibSurface + measureValid bool + measureState State + measureDPI int32 + measureClientW int32 + cachedTitleW int32 + cachedStatusCnt int + cachedStatusLines []string + trackingMouse bool + timerMs uint32 + lastPrefCheck time.Time + ownerEvtPost atomic.Bool +} + +func (e *entry) isDone() bool { + select { + case <-e.done: + return true + default: + return false + } +} + +func (m *Manager) upsertPlatform(state State) { + m.mu.Lock() + if m.closed { + m.mu.Unlock() + return + } + e, ok := m.items[state.VMKey] + if ok && !e.isDone() { + e.mu.Lock() + e.state = state + hwnd := e.hwnd + e.mu.Unlock() + m.mu.Unlock() + if hwnd != 0 { + _, _, _ = procPostMessageW.Call(hwnd, wmSyncState, 0, 0) + } + return + } + if ok { + delete(m.items, state.VMKey) + } + e = &entry{mgr: m, state: state, done: make(chan struct{})} + m.items[state.VMKey] = e + m.mu.Unlock() + go e.run() +} + +func (m *Manager) removePlatform(vmKey string) { + m.mu.Lock() + e, ok := m.items[vmKey] + delete(m.items, vmKey) + m.mu.Unlock() + if ok { + e.close() + } +} + +func (m *Manager) closePlatform() { + m.mu.Lock() + if m.closed { + m.mu.Unlock() + return + } + m.closed = true + list := make([]*entry, 0, len(m.items)) + for _, e := range m.items { + list = append(list, e) + } + m.items = map[string]*entry{} + m.mu.Unlock() + for _, e := range list { + e.close() + } +} + +func (e *entry) close() { + e.mu.Lock() + if e.closed { + e.mu.Unlock() + return + } + e.closed = true + hwnd := e.hwnd + e.mu.Unlock() + if hwnd != 0 { + _, _, _ = procPostMessageW.Call(hwnd, wmClose, 0, 0) + } + <-e.done +} + +func ensureOverlayClass() (string, string, string, uintptr) { + hInst, _, _ := procGetModuleHandleW.Call(0) + classOnce.Do(func() { + seq := classSeq.Add(1) + hArrow, _, _ := procLoadCursorW.Call(0, idcArrow) + + reg := func(name string, proc uintptr) { + ptr, _ := syscall.UTF16PtrFromString(name) + wc := wndClassExW{ + LpfnWndProc: proc, + HInstance: hInst, + HCursor: hArrow, + LpszClassName: ptr, + } + wc.CbSize = uint32(unsafe.Sizeof(wc)) + _, _, _ = procRegisterClassExW.Call(uintptr(unsafe.Pointer(&wc))) + } + + className = fmt.Sprintf("ReimsGoAgentSessionIsland_%d", seq) + tipClassName = fmt.Sprintf("ReimsGoAgentSessionTip_%d", seq) + shieldClassName = fmt.Sprintf("ReimsGoAgentInputShield_%d", seq) + + reg(className, wndProcCB) + reg(tipClassName, passiveWndCB) + reg(shieldClassName, shieldWndProcCB) + }) + return className, tipClassName, shieldClassName, hInst +} + +func windowsReducedMotion() bool { + var anim int32 = 1 + ok, _, _ := procSystemParametersInfoW.Call(spiGetClientAreaAnimation, 0, uintptr(unsafe.Pointer(&anim)), 0) + return ok != 0 && anim == 0 +} + +func queryWindowDPI(hwnd uintptr) int32 { + if hwnd != 0 && procGetDpiForWindow.Find() == nil { + if d, _, _ := procGetDpiForWindow.Call(hwnd); d >= 96 { + return int32(d) + } + } + return 96 +} + +func winEventHookProc(hook, event, hwnd, idObject, idChild, thread, ms uintptr) uintptr { + winEventMu.Lock() + fn := winEventHooks[hook] + winEventMu.Unlock() + if fn != nil { + fn(uint32(event), hwnd, int32(idObject), int32(idChild)) + } + return 0 +} + +func registerWinEventHook(minEvent, maxEvent, pid uint32, fn func(event uint32, hwnd uintptr, idObject, idChild int32)) func() { + h, _, _ := procSetWinEventHook.Call( + uintptr(minEvent), + uintptr(maxEvent), + 0, + winEventCB, + uintptr(pid), + 0, + 0, // WINEVENT_OUTOFCONTEXT + ) + if h == 0 { + return func() {} + } + winEventMu.Lock() + winEventHooks[h] = fn + winEventMu.Unlock() + return func() { + _, _, _ = procUnhookWinEvent.Call(h) + winEventMu.Lock() + delete(winEventHooks, h) + winEventMu.Unlock() + } +} + +func (e *entry) run() { + defer close(e.done) + defer func() { + // Remove this entry if its window thread exited early (for example if + // CreateWindowExW returned 0) so a subsequent Upsert can recreate it. + if e.mgr == nil { + return + } + e.mu.Lock() + vmKey := e.state.VMKey + e.mu.Unlock() + if vmKey == "" { + return + } + e.mgr.mu.Lock() + if e.mgr.items[vmKey] == e { + delete(e.mgr.items, vmKey) + } + e.mgr.mu.Unlock() + }() + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + cls, tipCls, shieldCls, hInst := ensureOverlayClass() + clsPtr, _ := syscall.UTF16PtrFromString(cls) + titlePtr, _ := syscall.UTF16PtrFromString("Reims-Go Agent Session") + + hwnd, _, _ := procCreateWindowExW.Call( + wsExLayered|wsExToolWin|wsExNoAct, + uintptr(unsafe.Pointer(clsPtr)), + uintptr(unsafe.Pointer(titlePtr)), + wsPopup|wsClipSibs, + 0, 0, 1, 1, + 0, 0, hInst, 0, + ) + if hwnd == 0 { + return + } + + // Mini matte-obsidian tooltip window for compact quick-action buttons. + tClsPtr, _ := syscall.UTF16PtrFromString(tipCls) + tTitlePtr, _ := syscall.UTF16PtrFromString("Reims-Go Session Tip") + tipHwnd, _, _ := procCreateWindowExW.Call( + wsExLayered|wsExTransparent|wsExToolWin|wsExNoAct, + uintptr(unsafe.Pointer(tClsPtr)), + uintptr(unsafe.Pointer(tTitlePtr)), + wsPopup|wsClipSibs, + 0, 0, 1, 1, + 0, 0, hInst, 0, + ) + + // Transparent client-area mouse shield (1/255 alpha: visually invisible, + // hit-testable by DWM so QEMU receives zero mouse move/click/wheel while + // the Windows host cursor stays free to move and click the HUD above it). + sClsPtr, _ := syscall.UTF16PtrFromString(shieldCls) + sTitlePtr, _ := syscall.UTF16PtrFromString("Reims-Go Input Shield") + shieldHwnd, _, _ := procCreateWindowExW.Call( + wsExLayered|wsExToolWin|wsExNoAct, + uintptr(unsafe.Pointer(sClsPtr)), + uintptr(unsafe.Pointer(sTitlePtr)), + wsPopup|wsClipSibs, + 0, 0, 1, 1, + 0, 0, hInst, 0, + ) + if shieldHwnd != 0 { + _, _, _ = procSetLayeredAttr.Call(shieldHwnd, 0, 1, lwaAlpha) + } + + now := time.Now() + e.hwndSelf = hwnd + e.tipHwnd = tipHwnd + e.shieldHwnd = shieldHwnd + e.dpi = 96 + e.ctrl = newIslandController(now, windowsReducedMotion()) + e.lastPrefCheck = now + e.unhookFG = registerWinEventHook(eventSystemForeground, eventSystemForeground, 0, + func(event uint32, targetHwnd uintptr, idObject, idChild int32) { + if targetHwnd != 0 && !e.isOverlayWindow(targetHwnd) { + if e.ownerEvtPost.CompareAndSwap(false, true) { + _, _, _ = procPostMessageW.Call(hwnd, wmOwnerEvent, 0, 0) + } + } + }) + + hwndMapMu.Lock() + hwndToEnt[hwnd] = e + if shieldHwnd != 0 { + shieldToEnt[shieldHwnd] = e + } + hwndMapMu.Unlock() + defer func() { + if e.unhookFG != nil { + e.unhookFG() + e.unhookFG = nil + } + if e.unhookEvents != nil { + e.unhookEvents() + e.unhookEvents = nil + } + e.dw.release() + e.baseCache.release() + e.canvas.release() + e.scratch.release() + e.tipCanvas.release() + hwndMapMu.Lock() + delete(hwndToEnt, hwnd) + if shieldHwnd != 0 { + delete(shieldToEnt, shieldHwnd) + } + hwndMapMu.Unlock() + }() + + e.mu.Lock() + e.hwnd = hwnd + initState := e.state + alreadyClosed := e.closed + e.mu.Unlock() + if alreadyClosed { + e.destroyAuxWindows() + _, _, _ = procDestroyWindow.Call(hwnd) + return + } + + e.ctrl.onStateUpdate(initState, now) + e.setTimerCadence(hwnd, timerFastMs) + e.syncAndRender(hwnd, now, true) + + var msg winMsg + for { + r, _, _ := procGetMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0) + if int32(r) <= 0 { + break + } + _, _, _ = procTranslateMessage.Call(uintptr(unsafe.Pointer(&msg))) + _, _, _ = procDispatchMessageW.Call(uintptr(unsafe.Pointer(&msg))) + } +} + +func (e *entry) destroyAuxWindows() { + if e.unhookFG != nil { + e.unhookFG() + e.unhookFG = nil + } + if e.unhookEvents != nil { + e.unhookEvents() + e.unhookEvents = nil + } + if e.tipHwnd != 0 { + e.setOwnedBy(e.tipHwnd, 0) + _, _, _ = procDestroyWindow.Call(e.tipHwnd) + e.tipHwnd = 0 + } + if e.shieldHwnd != 0 { + e.setOwnedBy(e.shieldHwnd, 0) + _, _, _ = procDestroyWindow.Call(e.shieldHwnd) + e.shieldHwnd = 0 + } +} + +func (e *entry) setTimerCadence(hwnd uintptr, ms uint32) { + if ms == e.timerMs || hwnd == 0 { + return + } + e.timerMs = ms + _, _, _ = procSetTimer.Call(hwnd, timerSyncID, uintptr(ms), 0) +} + +func (e *entry) ensureOwnerHooks(hwnd uintptr, pid uint32) { + if pid == e.hookPID { + return + } + if e.unhookEvents != nil { + e.unhookEvents() + e.unhookEvents = nil + } + e.hookPID = pid + if pid == 0 { + return + } + postOwnerEvt := func() { + if e.ownerEvtPost.CompareAndSwap(false, true) { + _, _, _ = procPostMessageW.Call(hwnd, wmOwnerEvent, 0, 0) + } + } + h1 := registerWinEventHook(eventObjectLocation, eventObjectLocation, pid, + func(event uint32, targetHwnd uintptr, idObject, idChild int32) { + if idObject == 0 && idChild == 0 && targetHwnd != 0 && targetHwnd == e.owner { + postOwnerEvt() + } + }) + h2 := registerWinEventHook(eventSystemMoveSizeEnd, eventSystemMinimizeEnd, pid, + func(event uint32, targetHwnd uintptr, idObject, idChild int32) { + if targetHwnd == e.owner || event == eventSystemMinimizeEnd { + postOwnerEvt() + } + }) + h3 := registerWinEventHook(eventObjectShow, eventObjectShow, pid, + func(event uint32, targetHwnd uintptr, idObject, idChild int32) { + if idObject == 0 && idChild == 0 && targetHwnd != 0 && !e.isOverlayWindow(targetHwnd) && (e.owner == 0 || targetHwnd == e.owner) { + postOwnerEvt() + } + }) + e.unhookEvents = func() { + h3() + h2() + h1() + } +} + +var ( + enumFindMu sync.Mutex + enumFindPID uint32 + enumFindHWND uintptr + enumFindArea int64 +) + +func candidateOwnerArea(hwnd uintptr, targetPID uint32) (int64, bool) { + if hwnd == 0 || targetPID == 0 { + return 0, false + } + var pid uint32 + _, _, _ = procGetWindowPID.Call(hwnd, uintptr(unsafe.Pointer(&pid))) + if pid != targetPID { + return 0, false + } + vis, _, _ := procIsWindowVisible.Call(hwnd) + if vis == 0 { + return 0, false + } + // Skip owned tool/popup windows. + if owner, _, _ := procGetWindow.Call(hwnd, gwOwner); owner != 0 { + return 0, false + } + // Skip standard Win32 dialogs / MessageBoxes (#32770) and our own overlay windows. + var cls [64]uint16 + if n, _, _ := procGetClassNameW.Call(hwnd, uintptr(unsafe.Pointer(&cls[0])), uintptr(len(cls))); n > 0 { + name := syscall.UTF16ToString(cls[:n]) + if name == "#32770" || strings.HasPrefix(name, "ReimsGoAgent") { + return 0, false + } + } + // Skip tiny invisible helper windows that cannot host the VM display. + var cr winRect + if ok, _, _ := procGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&cr))); ok == 0 || cr.Right < 200 || cr.Bottom < 120 { + return 0, false + } + return int64(cr.Right) * int64(cr.Bottom), true +} + +func isCandidateOwnerWindow(hwnd uintptr, targetPID uint32) bool { + _, ok := candidateOwnerArea(hwnd, targetPID) + return ok +} + +func enumFindOwnerProc(hwnd, _ uintptr) uintptr { + area, ok := candidateOwnerArea(hwnd, enumFindPID) + if !ok { + return 1 + } + if area > enumFindArea { + enumFindArea = area + enumFindHWND = hwnd + } + return 1 +} + +func findOwnerWindow(pid uint32) uintptr { + if pid == 0 { + return 0 + } + // Fast path: prefer the foreground window if it already belongs to pid. + if fg, _, _ := procGetForegroundWindow.Call(); isCandidateOwnerWindow(fg, pid) { + return fg + } + enumFindMu.Lock() + defer enumFindMu.Unlock() + enumFindPID = pid + enumFindHWND = 0 + enumFindArea = 0 + _, _, _ = procEnumWindows.Call(enumFindCB, 0) + return enumFindHWND +} + +func (e *entry) isOverlayWindow(h uintptr) bool { + return h != 0 && (h == e.hwndSelf || h == e.tipHwnd || h == e.shieldHwnd) +} + +func (e *entry) isStrictlyAbove(top, bottom uintptr) bool { + if top == 0 || bottom == 0 { + return false + } + for cur, _, _ := procGetWindow.Call(bottom, gwHwndPrev); cur != 0; cur, _, _ = procGetWindow.Call(cur, gwHwndPrev) { + if cur == top { + return true + } + } + return false +} + +// insertAfterAboveOwner finds the window immediately above owner in owner's +// Z-order band so SetWindowPos(hwnd, insertAfter, ...) places hwnd strictly +// above owner without stealing focus or covering unrelated foreground apps. +func (e *entry) insertAfterAboveOwner(owner uintptr) (insertAfter uintptr, ownerTopmost bool) { + ownerEx, _, _ := procGetWindowLongPtr.Call(owner, ^uintptr(19)) // GWL_EXSTYLE = -20 + ownerTopmost = ownerEx&wsExTopmost != 0 + for cur, _, _ := procGetWindow.Call(owner, gwHwndPrev); cur != 0; cur, _, _ = procGetWindow.Call(cur, gwHwndPrev) { + if e.isOverlayWindow(cur) { + continue + } + exStyle, _, _ := procGetWindowLongPtr.Call(cur, ^uintptr(19)) + if !ownerTopmost && exStyle&wsExTopmost != 0 { + return 0, false // HWND_TOP of non-topmost band + } + return cur, ownerTopmost + } + if ownerTopmost { + return hwndTopmost, true + } + return 0, false // HWND_TOP +} + +func (e *entry) setOwnedBy(hwnd, owner uintptr) { + if hwnd != 0 { + _, _, _ = procSetWindowLongPtr.Call(hwnd, ^uintptr(7), owner) + } +} + +func (e *entry) refreshSystemPrefs(now time.Time) { + if now.Sub(e.lastPrefCheck) < 2*time.Second { + return + } + e.lastPrefCheck = now + e.ctrl.reducedMotion = windowsReducedMotion() +} + +func (e *entry) measureTextForState(st State, dpi, clientW int32) (titleW int32, statusLineCount int, statusLines []string) { + keySt := st + keySt.PID = 0 + if e.measureValid && e.measureDPI == dpi && e.measureClientW == clientW && e.measureState == keySt { + return e.cachedTitleW, e.cachedStatusCnt, e.cachedStatusLines + } + script := scriptForState(st) + expW := scaleDP(dpi, 336) + if clientW > 0 { + maxW := max(scaleDP(dpi, 256), clientW-scaleDP(dpi, 16)) + if expW > maxW { + expW = maxW + } + } + statusMaxW := max(scaleDP(dpi, 120), expW-scaleDP(dpi, 28)) + + saveCache := func(tw int32, cnt int, lines []string) (int32, int, []string) { + e.measureValid = true + e.measureState = keySt + e.measureDPI = dpi + e.measureClientW = clientW + e.cachedTitleW = tw + e.cachedStatusCnt = cnt + e.cachedStatusLines = lines + return tw, cnt, lines + } + + if w, ok := e.dw.measureLineWidth(dpi, script, styleCompact, compactPrimaryText(st)); ok { + titleW = w + if cnt, ok := e.dw.measureWrappedLines(dpi, script, styleStatus, st.StatusLine, statusMaxW, 2); ok { + return saveCache(titleW, cnt, nil) + } + } + + dc, _, _ := procGetDC.Call(0) + if dc == 0 { + if strings.TrimSpace(st.StatusLine) != "" { + return saveCache(titleW, 1, []string{st.StatusLine}) + } + return saveCache(titleW, 0, nil) + } + defer procReleaseDC.Call(0, dc) + fonts := getIslandFonts(dpi, script) + if titleW <= 0 { + titleW = measureLineWidthDC(dc, fonts.compactTitle, compactPrimaryText(st)) + } + statusLines = wrapStatusLines(dc, fonts.status, st.StatusLine, statusMaxW, 2) + return saveCache(titleW, len(statusLines), statusLines) +} + +func (e *entry) syncAndRender(hwnd uintptr, now time.Time, forcePaint bool) { + e.refreshSystemPrefs(now) + + e.mu.Lock() + st := e.state + e.mu.Unlock() + + pid := st.PID + e.ensureOwnerHooks(hwnd, pid) + + newlyOwned := false + if e.owner != 0 { + valid, _, _ := procIsWindow.Call(e.owner) + var opid uint32 + if valid != 0 { + _, _, _ = procGetWindowPID.Call(e.owner, uintptr(unsafe.Pointer(&opid))) + } + if valid == 0 || (pid != 0 && opid != pid) { + e.owner = 0 + } + } + if e.owner == 0 && pid != 0 { + owner := findOwnerWindow(pid) + if owner != 0 { + e.owner = owner + newlyOwned = true + e.setOwnedBy(hwnd, owner) + e.setOwnedBy(e.tipHwnd, owner) + e.setOwnedBy(e.shieldHwnd, owner) + } + } + + if e.owner == 0 { + e.hideAll(hwnd) + if pid != 0 { + // VM process is live and creating its display window; probe rapidly so + // the island appears the moment the QEMU window becomes visible. + e.setTimerCadence(hwnd, timerDiscoverMs) + } else { + e.setTimerCadence(hwnd, timerIdleMs) + } + return + } + iconic, _, _ := procIsIconic.Call(e.owner) + vis, _, _ := procIsWindowVisible.Call(e.owner) + if iconic == 0 && vis == 0 && pid != 0 { + // Handle display renderers that hide an initial/splash window and open a + // replacement top-level display window under the same process ID. + if alt := findOwnerWindow(pid); alt != 0 && alt != e.owner { + e.owner = alt + newlyOwned = true + e.setOwnedBy(hwnd, alt) + e.setOwnedBy(e.tipHwnd, alt) + e.setOwnedBy(e.shieldHwnd, alt) + iconic, _, _ = procIsIconic.Call(e.owner) + vis, _, _ = procIsWindowVisible.Call(e.owner) + } + } + if iconic != 0 || vis == 0 { + e.hideAll(hwnd) + if iconic == 0 && pid != 0 { + e.setTimerCadence(hwnd, timerDiscoverMs) + } else { + e.setTimerCadence(hwnd, timerIdleMs) + } + return + } + var cr winRect + if ok, _, _ := procGetClientRect.Call(e.owner, uintptr(unsafe.Pointer(&cr))); ok == 0 || cr.Right <= 0 || cr.Bottom <= 0 { + e.hideAll(hwnd) + e.setTimerCadence(hwnd, timerIdleMs) + return + } + origin := winPoint{X: 0, Y: 0} + if ok, _, _ := procClientToScreen.Call(e.owner, uintptr(unsafe.Pointer(&origin))); ok == 0 { + e.hideAll(hwnd) + e.setTimerCadence(hwnd, timerIdleMs) + return + } + + clientW := cr.Right - cr.Left + clientH := cr.Bottom - cr.Top + dpi := queryWindowDPI(e.owner) + e.clientOrigin = origin + e.clientW = clientW + e.clientH = clientH + e.dpi = dpi + + titleW, statusCnt, statusLines := e.measureTextForState(st, dpi, clientW) + e.statusLines = statusLines + layout := computeIslandLayout(st, dpi, clientW, titleW, statusCnt, e.ctrl.morph) + e.layout = layout + + pillLocalOrigin := e.ctrl.currentPillOrigin(clientW, clientH, layout.PillW, layout.PillH, dpi, now) + pillScreenX := origin.X + pillLocalOrigin.X + pillScreenY := origin.Y + pillLocalOrigin.Y + e.pillScreenX = pillScreenX + e.pillScreenY = pillScreenY + + winX := pillScreenX - layout.PadX + winY := pillScreenY - layout.PadTop + + wasHidden := !e.visible + screenDC, _, _ := procGetDC.Call(0) + if screenDC == 0 { + return + } + defer procReleaseDC.Call(0, screenDC) + + animatingGeometry := e.ctrl.dragging || e.ctrl.snapping || !e.ctrl.morphStart.IsZero() + pulse := e.ctrl.pulseIntensity(now) + breathing := !e.ctrl.reducedMotion && !e.ctrl.isPaused() && !e.ctrl.isCompleted() + sizeChanged := layout.CanvasW != e.lastCanvasW || layout.CanvasH != e.lastCanvasH + posChanged := winX != e.lastWinX || winY != e.lastWinY + needRedraw := forcePaint || wasHidden || sizeChanged || animatingGeometry || pulse > 0.005 || breathing + if needRedraw { + fonts := getIslandFonts(dpi, scriptForState(st)) + ok := renderIslandFrame(&e.canvas, &e.scratch, screenDC, renderParams{ + state: st, + layout: layout, + statusLines: statusLines, + fonts: fonts, + dw: &e.dw, + hoverZone: e.ctrl.hoverZone, + pressedZone: e.ctrl.pressedZone, + breath: e.ctrl.breathLevel(now), + pulse: pulse, + baseCache: &e.baseCache, + }) + if ok { + dstPt := winPoint{X: winX, Y: winY} + dstSz := winSize{CX: layout.CanvasW, CY: layout.CanvasH} + srcPt := winPoint{X: 0, Y: 0} + blend := blendFunction{ + BlendOp: acSrcOver, + SourceConstantAlpha: 255, + AlphaFormat: acSrcAlpha, + } + _, _, _ = procUpdateLayeredWindow.Call( + hwnd, + screenDC, + uintptr(unsafe.Pointer(&dstPt)), + uintptr(unsafe.Pointer(&dstSz)), + e.canvas.hdc, + uintptr(unsafe.Pointer(&srcPt)), + 0, + uintptr(unsafe.Pointer(&blend)), + ulwAlpha, + ) + e.lastWinX = winX + e.lastWinY = winY + e.lastCanvasW = layout.CanvasW + e.lastCanvasH = layout.CanvasH + } + } else if posChanged { + dstPt := winPoint{X: winX, Y: winY} + _, _, _ = procUpdateLayeredWindow.Call(hwnd, 0, uintptr(unsafe.Pointer(&dstPt)), 0, 0, 0, 0, 0, 0) + e.lastWinX = winX + e.lastWinY = winY + } + + needZOrder := wasHidden || newlyOwned || !e.isStrictlyAbove(hwnd, e.owner) || + (e.shieldVisible && e.shieldHwnd != 0 && (!e.isStrictlyAbove(e.shieldHwnd, e.owner) || !e.isStrictlyAbove(hwnd, e.shieldHwnd))) + if needZOrder { + insertAfter, ownerTopmost := e.insertAfterAboveOwner(e.owner) + flags := uintptr(swpNoMove | swpNoSize | swpNoActivate | swpNoOwnerZ) + if ownerTopmost { + hudEx, _, _ := procGetWindowLongPtr.Call(hwnd, ^uintptr(19)) + if hudEx&wsExTopmost == 0 && insertAfter != hwndTopmost { + // Promote into the topmost Z-band first; Win32 ignores a topmost HWND + // insertAfter when the target window is still non-topmost. + _, _, _ = procSetWindowPos.Call(hwnd, hwndTopmost, 0, 0, 0, 0, flags) + } + } else { + for _, h := range []uintptr{hwnd, e.shieldHwnd, e.tipHwnd} { + if h == 0 { + continue + } + hEx, _, _ := procGetWindowLongPtr.Call(h, ^uintptr(19)) + if hEx&wsExTopmost != 0 { + _, _, _ = procSetWindowPos.Call(h, hwndNoTopmost, 0, 0, 0, 0, flags) + } + } + } + if wasHidden { + flags |= swpShowWindow + } + _, _, _ = procSetWindowPos.Call(hwnd, insertAfter, 0, 0, 0, 0, flags) + e.visible = true + } + + // Sync input shield strictly behind hwnd, above VM owner. + e.syncShield(hwnd, st.InputLocked, origin, clientW, clientH, needZOrder) + + // Sync compact quick-action button tooltip strictly above hwnd. + e.syncTooltip(hwnd, screenDC, st, now) +} + +func (e *entry) syncShield(hwnd uintptr, inputLocked bool, origin winPoint, clientW, clientH int32, forceZ bool) { + if e.shieldHwnd == 0 { + return + } + if inputLocked && clientW > 0 && clientH > 0 { + target := winRect{Left: origin.X, Top: origin.Y, Right: origin.X + clientW, Bottom: origin.Y + clientH} + if !e.shieldVisible || target != e.shieldRect || forceZ { + sFlags := uintptr(swpNoActivate | swpNoOwnerZ) + if !e.shieldVisible { + sFlags |= swpShowWindow + } + _, _, _ = procSetWindowPos.Call(e.shieldHwnd, hwnd, uintptr(origin.X), uintptr(origin.Y), uintptr(clientW), uintptr(clientH), sFlags) + e.shieldVisible = true + e.shieldRect = target + } + } else if e.shieldVisible { + _, _, _ = procShowWindow.Call(e.shieldHwnd, swHide) + e.shieldVisible = false + } +} + +func (e *entry) syncTooltip(hwnd, screenDC uintptr, st State, now time.Time) { + if e.tipHwnd == 0 { + return + } + var wantZone hitZone + var tipLabel string + var btnRect rect2i + if !e.ctrl.dragging { + if e.ctrl.morph < 0.25 { + switch e.ctrl.hoverZone { + case zoneToggle: + if e.layout.HasToggle { + wantZone = zoneToggle + btnRect = e.layout.CompactToggleBtn + if st.CanResume { + tipLabel = st.ResumeLabel + } else { + tipLabel = st.PauseLabel + } + } + case zoneStop: + wantZone = zoneStop + btnRect = e.layout.CompactStopBtn + if st.Completed { + tipLabel = st.CloseLabel + } else { + tipLabel = st.StopLabel + } + } + } else if e.ctrl.morph > 0.75 && e.ctrl.hoverZone == zoneFold && e.layout.ExpandedFoldBtn.width() > 0 { + wantZone = zoneFold + btnRect = e.layout.ExpandedFoldBtn + tipLabel = st.CollapseLabel + } + } + + if wantZone == zoneNone || tipLabel == "" { + e.tipTargetZone = zoneNone + e.tipHoverSince = time.Time{} + if e.tipVisible { + _, _, _ = procShowWindow.Call(e.tipHwnd, swHide) + e.tipVisible = false + e.tipText = "" + } + return + } + + if e.tipTargetZone != wantZone { + e.tipTargetZone = wantZone + e.tipHoverSince = now + if e.tipVisible { + _, _, _ = procShowWindow.Call(e.tipHwnd, swHide) + e.tipVisible = false + } + return + } + + if now.Sub(e.tipHoverSince) < tooltipHoverDur { + return + } + + dpi := e.dpi + script := scriptForState(st) + fonts := getIslandFonts(dpi, script) + textW, okW := e.dw.measureLineWidth(dpi, script, styleTip, tipLabel) + if !okW || textW <= 0 { + textW = measureLineWidthDC(screenDC, fonts.status, tipLabel) + } + padX := scaleDP(dpi, 10) + tipW := max(scaleDP(dpi, 38), textW+padX*2) + tipH := scaleDP(dpi, 24) + shadowPad := scaleDP(dpi, 4) + canvasW := tipW + shadowPad*2 + canvasH := tipH + shadowPad*2 + + if !e.tipCanvas.ensure(screenDC, canvasW, canvasH) { + return + } + e.tipCanvas.clear() + pillR := rect2i{Left: shadowPad, Top: shadowPad, Right: shadowPad + tipW, Bottom: shadowPad + tipH} + e.tipCanvas.paintTactilePill(pillR, scaleDPF(dpi, 7), rgba{255, 255, 255}, rgba{248, 249, 252}, 1.0, rgba{15, 23, 42}, 0.12, 0) + drewTip := false + if e.dw.beginSurface(&e.tipCanvas) { + drewTip = e.dw.drawText(dpi, script, styleTip, tipLabel, pillR, dwAlignCenter, 1, rgba{29, 29, 31}, 0.96) + e.dw.endSurface() + } + if !drewTip { + e.tipCanvas.drawAlphaText(&e.scratch, screenDC, fonts.status, tipLabel, pillR, dtCenter|dtVCenter|dtSingleLine, rgba{29, 29, 31}, 0.96) + } + + btnCenterX := e.pillScreenX + (btnRect.Left+btnRect.Right)/2 + tipX := btnCenterX - canvasW/2 + gapY := scaleDP(dpi, 6) + var tipY int32 + switch e.ctrl.anchor { + case AnchorBottomLeft, AnchorBottomCenter, AnchorBottomRight: + tipY = e.pillScreenY - gapY - tipH - shadowPad + default: + tipY = e.pillScreenY + e.layout.PillH + gapY - shadowPad + } + tipX = clampInt32(tipX, e.clientOrigin.X, max(e.clientOrigin.X, e.clientOrigin.X+e.clientW-canvasW)) + + dstPt := winPoint{X: tipX, Y: tipY} + dstSz := winSize{CX: canvasW, CY: canvasH} + srcPt := winPoint{X: 0, Y: 0} + blend := blendFunction{BlendOp: acSrcOver, SourceConstantAlpha: 255, AlphaFormat: acSrcAlpha} + _, _, _ = procUpdateLayeredWindow.Call( + e.tipHwnd, + screenDC, + uintptr(unsafe.Pointer(&dstPt)), + uintptr(unsafe.Pointer(&dstSz)), + e.tipCanvas.hdc, + uintptr(unsafe.Pointer(&srcPt)), + 0, + uintptr(unsafe.Pointer(&blend)), + ulwAlpha, + ) + if !e.tipVisible || e.tipText != tipLabel { + // Position tooltip cleanly above hwnd (HWND_TOP = 0 within owner group). + flags := uintptr(swpNoMove | swpNoSize | swpNoActivate | swpNoOwnerZ | swpShowWindow) + _, _, _ = procSetWindowPos.Call(e.tipHwnd, 0, 0, 0, 0, 0, flags) + e.tipVisible = true + e.tipText = tipLabel + } +} + +func (e *entry) hideAll(hwnd uintptr) { + if e.tipVisible && e.tipHwnd != 0 { + _, _, _ = procShowWindow.Call(e.tipHwnd, swHide) + e.tipVisible = false + } + if e.shieldVisible && e.shieldHwnd != 0 { + _, _, _ = procShowWindow.Call(e.shieldHwnd, swHide) + e.shieldVisible = false + } + if e.visible { + _, _, _ = procShowWindow.Call(hwnd, swHide) + e.visible = false + } +} + +func (e *entry) updateTimerCadence(hwnd uintptr, highFreq bool) { + if !e.visible { + e.mu.Lock() + hasPID := e.state.PID != 0 + e.mu.Unlock() + if hasPID { + e.setTimerCadence(hwnd, timerDiscoverMs) + } else { + e.setTimerCadence(hwnd, timerIdleMs) + } + return + } + if highFreq || e.ctrl.dragging || !e.tipHoverSince.IsZero() { + e.setTimerCadence(hwnd, timerFastMs) + return + } + if !e.ctrl.reducedMotion && !e.ctrl.isPaused() && !e.ctrl.isCompleted() { + e.setTimerCadence(hwnd, timerBreathMs) + return + } + e.setTimerCadence(hwnd, timerIdleMs) +} + +func rgb(r, g, b uint8) uintptr { + return uintptr(uint32(r) | uint32(g)<<8 | uint32(b)<<16) +} + +func drawWinText(hdc uintptr, text string, r *winRect, flags uintptr) { + if text == "" { + return + } + u16, err := syscall.UTF16FromString(text) + if err != nil || len(u16) == 0 { + return + } + _, _, _ = procDrawTextW.Call(hdc, uintptr(unsafe.Pointer(&u16[0])), uintptr(len(u16)-1), uintptr(unsafe.Pointer(r)), flags) +} + +func passiveWndProc(hwnd uintptr, msg uint32, wParam, lParam uintptr) uintptr { + switch msg { + case wmMouseAct: + return maNoActivate + case wmEraseBkgnd: + return 1 + case wmPaint: + var ps paintStruct + if hdc, _, _ := procBeginPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))); hdc != 0 { + _, _, _ = procEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))) + } + return 0 + } + r, _, _ := procDefWindowProcW.Call(hwnd, uintptr(msg), wParam, lParam) + return r +} + +func shieldWndProc(hwnd uintptr, msg uint32, wParam, lParam uintptr) uintptr { + switch msg { + case wmMouseAct: + return maNoActivate + case wmSetCursor: + hArrow, _, _ := procLoadCursorW.Call(0, idcArrow) + if hArrow != 0 { + _, _, _ = procSetCursor.Call(hArrow) + } + return 1 + case wmLButtonDown, wmRButtonDown: + // Notify the Dynamic Island so it expands with a soft rim pulse to show + // why VM clicks are blocked and surface the Pause/Takeover button. + hwndMapMu.RLock() + e := shieldToEnt[hwnd] + hwndMapMu.RUnlock() + if e != nil { + e.mu.Lock() + target := e.hwnd + e.mu.Unlock() + if target != 0 { + _, _, _ = procPostMessageW.Call(target, wmLockedClick, 0, 0) + } + } + return 0 + case wmMouseMove, wmLButtonUp, wmRButtonUp, + wmMButtonDown, wmMButtonUp, wmXButtonDown, wmXButtonUp, + wmMouseWheel, wmMouseHWheel: + return 0 + case wmPaint: + var ps paintStruct + if hdc, _, _ := procBeginPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))); hdc != 0 { + _, _, _ = procEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))) + } + return 0 + } + r, _, _ := procDefWindowProcW.Call(hwnd, uintptr(msg), wParam, lParam) + return r +} + +func cursorScreenPos() point2i { + var pt winPoint + _, _, _ = procGetCursorPos.Call(uintptr(unsafe.Pointer(&pt))) + return point2i{X: pt.X, Y: pt.Y} +} + +func lParamPoint(lParam uintptr) point2i { + return point2i{ + X: int32(int16(lParam & 0xFFFF)), + Y: int32(int16((lParam >> 16) & 0xFFFF)), + } +} + +func overlayWndProc(hwnd uintptr, msg uint32, wParam, lParam uintptr) uintptr { + hwndMapMu.RLock() + e := hwndToEnt[hwnd] + hwndMapMu.RUnlock() + + switch msg { + case wmMouseAct: + return maNoActivate + case wmEraseBkgnd: + return 1 + case wmPaint: + var ps paintStruct + if hdc, _, _ := procBeginPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))); hdc != 0 { + _, _, _ = procEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))) + } + return 0 + case wmSetCursor: + if e != nil && (e.ctrl.hoverZone == zoneToggle || e.ctrl.hoverZone == zoneStop || e.ctrl.hoverZone == zoneFold) { + hHand, _, _ := procLoadCursorW.Call(0, idcHand) + if hHand != 0 { + _, _, _ = procSetCursor.Call(hHand) + return 1 + } + } + hArrow, _, _ := procLoadCursorW.Call(0, idcArrow) + if hArrow != 0 { + _, _, _ = procSetCursor.Call(hArrow) + return 1 + } + case wmSyncState: + if e != nil { + now := time.Now() + e.mu.Lock() + st := e.state + e.mu.Unlock() + e.ctrl.onStateUpdate(st, now) + e.syncAndRender(hwnd, now, true) + e.updateTimerCadence(hwnd, true) + } + return 0 + case wmLockedClick: + if e != nil { + now := time.Now() + e.ctrl.onLockedScreenClick(now) + e.syncAndRender(hwnd, now, true) + e.updateTimerCadence(hwnd, true) + } + return 0 + case wmOwnerEvent: + if e != nil { + e.ownerEvtPost.Store(false) + now := time.Now() + e.syncAndRender(hwnd, now, true) + } + return 0 + case wmDPIChanged: + if e != nil { + now := time.Now() + e.syncAndRender(hwnd, now, true) + } + return 0 + case wmTimer: + if e != nil { + now := time.Now() + _, highFreq := e.ctrl.tick(now) + e.syncAndRender(hwnd, now, highFreq) + e.updateTimerCadence(hwnd, highFreq) + } + return 0 + case wmMouseMove: + if e != nil { + if !e.trackingMouse { + tme := trackMouseStruct{ + CbSize: uint32(unsafe.Sizeof(trackMouseStruct{})), + DwFlags: tmeLeave, + HwndTrack: hwnd, + } + _, _, _ = procTrackMouseEvent.Call(uintptr(unsafe.Pointer(&tme))) + e.trackingMouse = true + } + now := time.Now() + clientPt := lParamPoint(lParam) + pillLocal := point2i{X: clientPt.X - e.layout.PadX, Y: clientPt.Y - e.layout.PadTop} + hoverChanged, moved := e.ctrl.onPointerMove(cursorScreenPos(), pillLocal, e.clientW, e.clientH, e.layout, now) + if hoverChanged || moved { + e.syncAndRender(hwnd, now, true) + } + e.updateTimerCadence(hwnd, e.ctrl.dragging) + } + return 0 + case wmMouseLeave: + if e != nil { + e.trackingMouse = false + now := time.Now() + if e.ctrl.onPointerLeave(now) { + e.syncAndRender(hwnd, now, true) + } + e.updateTimerCadence(hwnd, false) + } + return 0 + case wmLButtonDown: + if e != nil { + now := time.Now() + clientPt := lParamPoint(lParam) + pillLocal := point2i{X: clientPt.X - e.layout.PadX, Y: clientPt.Y - e.layout.PadTop} + curOrigin := point2i{X: e.pillScreenX - e.clientOrigin.X, Y: e.pillScreenY - e.clientOrigin.Y} + e.ctrl.onPointerDown(cursorScreenPos(), pillLocal, curOrigin, e.layout, now) + if e.ctrl.pressedZone != zoneNone { + _, _, _ = procSetCapture.Call(hwnd) + e.syncAndRender(hwnd, now, true) + e.updateTimerCadence(hwnd, true) + } + } + return 0 + case wmLButtonUp: + if e != nil { + now := time.Now() + clientPt := lParamPoint(lParam) + pillLocal := point2i{X: clientPt.X - e.layout.PadX, Y: clientPt.Y - e.layout.PadTop} + act, snapped := e.ctrl.onPointerUp(pillLocal, e.clientW, e.clientH, e.layout, now) + // Release mouse capture AFTER consuming pressedZone/dragging because + // ReleaseCapture synchronously dispatches WM_CAPTURECHANGED. + _, _, _ = procReleaseCapture.Call() + e.syncAndRender(hwnd, now, true) + e.updateTimerCadence(hwnd, snapped || !e.ctrl.morphStart.IsZero()) + + if act != actionNone { + e.mu.Lock() + st := e.state + e.mu.Unlock() + switch act { + case actionStop: + if st.Completed { + if e.mgr.cb.OnDismiss != nil { + go e.mgr.cb.OnDismiss(st.VMKey) + } else if e.mgr.cb.OnStop != nil { + go e.mgr.cb.OnStop(st.VMKey) + } + } else if e.mgr.cb.OnStop != nil { + go e.mgr.cb.OnStop(st.VMKey) + } + case actionToggle: + if st.CanResume && e.mgr.cb.OnResume != nil { + go e.mgr.cb.OnResume(st.VMKey) + } else if !st.CanResume && st.CanPause && e.mgr.cb.OnPause != nil { + go e.mgr.cb.OnPause(st.VMKey) + } + } + } + } + return 0 + case wmCaptureChanged: + if e != nil && (e.ctrl.dragging || e.ctrl.pressedZone != zoneNone) { + now := time.Now() + if e.ctrl.dragging { + _, _ = e.ctrl.onPointerUp(point2i{-1, -1}, e.clientW, e.clientH, e.layout, now) + } else { + e.ctrl.pressedZone = zoneNone + e.ctrl.dragCandidate = false + } + e.syncAndRender(hwnd, now, true) + } + return 0 + case wmClose: + if e != nil { + e.destroyAuxWindows() + e.setOwnedBy(hwnd, 0) + } + _, _, _ = procKillTimer.Call(hwnd, timerSyncID) + _, _, _ = procDestroyWindow.Call(hwnd) + return 0 + case wmDestroy: + _, _, _ = procPostQuitMessage.Call(0) + return 0 + } + r, _, _ := procDefWindowProcW.Call(hwnd, uintptr(msg), wParam, lParam) + return r +} diff --git a/internal/host/sessionoverlay/overlay_windows_test.go b/internal/host/sessionoverlay/overlay_windows_test.go new file mode 100644 index 0000000..a36d1cd --- /dev/null +++ b/internal/host/sessionoverlay/overlay_windows_test.go @@ -0,0 +1,917 @@ +//go:build windows + +package sessionoverlay + +import ( + "os" + "runtime" + "syscall" + "testing" + "time" + "unsafe" +) + +func TestRenderIslandFramePremultipliedAlphaAndContent(t *testing.T) { + screenDC, _, _ := procGetDC.Call(0) + if screenDC == 0 { + t.Fatal("GetDC(0) returned 0") + } + defer procReleaseDC.Call(0, screenDC) + + var dw dwriteEngine + defer dw.release() + var canvas, scratch dibSurface + defer canvas.release() + defer scratch.release() + + st := State{ + VMKey: "builtin.guest.macos:render-test", + Locale: "zh-CN", + Title: "AI 正在操作(安装器已授权)", + StepBadge: "当前步骤", + StepText: "步骤 2 · 磁盘工具抹盘", + StatusLine: "画面已锁定防干扰 · 正在抹掉目标磁盘并准备恢复环境,稍候自动继续", + CanPause: true, + PauseLabel: "暂停", + ResumeLabel: "继续", + StopLabel: "停止", + CollapseLabel: "收起", + InputLocked: true, + Dark: true, + } + + for _, tc := range []struct { + name string + dpi int32 + morph float64 + pulse float64 + paused bool + completed bool + }{ + {"compact-96dpi", 96, 0, 0, false, false}, + {"mid-morph-96dpi", 96, 0.5, 0, false, false}, + {"expanded-96dpi", 96, 1, 0, false, false}, + {"expanded-96dpi-pulse", 96, 1, 0.8, false, false}, + {"expanded-144dpi-paused", 144, 1, 0, true, false}, + {"compact-96dpi-completed", 96, 0, 0, false, true}, + {"expanded-96dpi-completed", 96, 1, 0, false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + cur := st + if tc.paused { + cur.CanPause = false + cur.CanResume = true + cur.InputLocked = false + } + if tc.completed { + cur.Title = "macOS 自动装机助手" + cur.StepText = "已完成" + cur.StatusLine = "已完成恢复模式安装并进入 macOS,画面输入已解锁" + cur.Completed = true + cur.CanPause = false + cur.CanResume = false + cur.InputLocked = false + cur.CloseLabel = "关闭" + } + fonts := getIslandFonts(tc.dpi, scriptForLocale(cur.Locale)) + titleW := measureLineWidthDC(screenDC, fonts.compactTitle, cur.Title) + lines := wrapStatusLines(screenDC, fonts.status, cur.StatusLine, scaleDP(tc.dpi, 324), 2) + layout := computeIslandLayout(cur, tc.dpi, 1280, titleW, max(1, len(lines)), tc.morph) + + ok := renderIslandFrame(&canvas, &scratch, screenDC, renderParams{ + state: cur, + layout: layout, + statusLines: lines, + fonts: fonts, + dw: &dw, + hoverZone: zoneToggle, + breath: 0.7, + pulse: tc.pulse, + }) + if !ok { + t.Fatal("renderIslandFrame returned false") + } + if canvas.w != layout.CanvasW || canvas.h != layout.CanvasH { + t.Fatalf("canvas size = %dx%d, want %dx%d", canvas.w, canvas.h, layout.CanvasW, layout.CanvasH) + } + + // Verify premultiplied alpha invariant (B,G,R <= A) across every pixel. + nonZeroAlpha := 0 + for i := 0; i < len(canvas.bits); i += 4 { + b, g, r, a := canvas.bits[i], canvas.bits[i+1], canvas.bits[i+2], canvas.bits[i+3] + if b > a || g > a || r > a { + t.Fatalf("pixel %d violates premultiplied alpha: BGRA=(%d,%d,%d,%d)", i/4, b, g, r, a) + } + if a > 0 { + nonZeroAlpha++ + } + } + if nonZeroAlpha < int(layout.PillW*layout.PillH/2) { + t.Fatalf("too few visible pixels rendered: %d", nonZeroAlpha) + } + // Corner pixel of outer shadow gutter should be fully transparent. + if canvas.bits[3] != 0 { + t.Fatalf("top-left outer corner alpha = %d, want 0", canvas.bits[3]) + } + // Interior surface must be 100% solid opaque light macOS card (no frosted glass translucency). + bgX := int(layout.PadX + scaleDP(tc.dpi, 12)) + bgY := int(layout.PadTop + layout.PillH - scaleDP(tc.dpi, 5)) + off := (bgY*int(canvas.w) + bgX) * 4 + bgB, bgG, bgR, bgA := canvas.bits[off], canvas.bits[off+1], canvas.bits[off+2], canvas.bits[off+3] + if bgA != 255 || bgR < 235 || bgG < 235 || bgB < 235 { + t.Fatalf("solid light macOS interior BGRA=(%d,%d,%d,%d), want opaque light (>=235,235,235,255)", bgB, bgG, bgR, bgA) + } + }) + } +} + +func TestWindowsOverlayOwnershipShieldPulseAndCallbacks(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + const ( + wsVisible = 0x10000000 + gwHwndPrev = 3 + ) + procGetWindow := user32.NewProc("GetWindow") + clsPtr, _ := syscall.UTF16PtrFromString("STATIC") + offscreen := int32(-16000) + owner, _, err := procCreateWindowExW.Call( + wsExToolWin|wsExNoAct, + uintptr(unsafe.Pointer(clsPtr)), + 0, + wsPopup|wsVisible, + uintptr(offscreen), uintptr(offscreen), 1280, 720, + 0, 0, 0, 0, + ) + if owner == 0 { + t.Fatalf("CreateWindowExW offscreen owner failed: %v", err) + } + defer procDestroyWindow.Call(owner) + + pausedCh := make(chan string, 1) + resumedCh := make(chan string, 1) + stoppedCh := make(chan string, 1) + + mgr := NewManager(Callbacks{ + OnPause: func(vmKey string) { pausedCh <- vmKey }, + OnResume: func(vmKey string) { resumedCh <- vmKey }, + OnStop: func(vmKey string) { stoppedCh <- vmKey }, + }) + defer mgr.Close() + + vmKey := "builtin.guest.macos:win-island-test" + initSt := State{ + VMKey: vmKey, + PID: uint32(os.Getpid()), + Locale: "zh-CN", + Title: "AI 正在操作", + StepBadge: "当前步骤", + StepText: "步骤 1 · 进入恢复环境", + StatusLine: "画面已锁定防干扰 · 正在安装", + CanPause: true, + PauseLabel: "暂停", + ResumeLabel: "继续", + StopLabel: "停止", + CollapseLabel: "收起", + InputLocked: true, + Dark: true, + } + mgr.Upsert(initSt) + + // Wait until the overlay thread finds our offscreen owner window and shows HUD + shield. + var ent *entry + var hudHwnd, shieldHwnd uintptr + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + mgr.mu.Lock() + ent = mgr.items[vmKey] + mgr.mu.Unlock() + if ent != nil { + ent.mu.Lock() + hudHwnd = ent.hwnd + ent.mu.Unlock() + } + if hudHwnd != 0 { + vis, _, _ := procIsWindowVisible.Call(hudHwnd) + if vis != 0 { + // Find shield and verify owner attachment. + own, _, _ := procGetWindowLongPtr.Call(hudHwnd, ^uintptr(7)) + if own == owner { + hwndMapMu.RLock() + for sh, se := range shieldToEnt { + if se == ent { + shieldHwnd = sh + break + } + } + hwndMapMu.RUnlock() + if shieldHwnd != 0 { + sVis, _, _ := procIsWindowVisible.Call(shieldHwnd) + if sVis != 0 { + break + } + } + } + } + } + time.Sleep(20 * time.Millisecond) + } + if hudHwnd == 0 || shieldHwnd == 0 { + t.Fatalf("overlay failed to attach to offscreen owner: hud=%#x shield=%#x", hudHwnd, shieldHwnd) + } + + // Verify shield sits strictly behind hudHwnd in Z-order. + foundHudAboveShield := false + for cur, _, _ := procGetWindow.Call(shieldHwnd, gwHwndPrev); cur != 0; cur, _, _ = procGetWindow.Call(cur, gwHwndPrev) { + if cur == hudHwnd { + foundHudAboveShield = true + break + } + } + if !foundHudAboveShield { + t.Fatal("expected hudHwnd to be above shieldHwnd in Z-order") + } + + // Simulate clicking the locked VM shield -> triggers wmLockedClick on hudHwnd. + _, _, _ = procPostMessageW.Call(shieldHwnd, wmLButtonDown, 0, 0) + time.Sleep(80 * time.Millisecond) + + // Island starts expanded by default — click the expanded Pause button directly. + dpi := queryWindowDPI(owner) + expLayout := computeIslandLayout(initSt, dpi, 1280, 110, 1, 1) + pauseX := expLayout.PadX + (expLayout.ExpandedToggleBtn.Left+expLayout.ExpandedToggleBtn.Right)/2 + pauseY := expLayout.PadTop + (expLayout.ExpandedToggleBtn.Top+expLayout.ExpandedToggleBtn.Bottom)/2 + pauseLP := uintptr(uint32(pauseX)&0xFFFF | (uint32(pauseY)&0xFFFF)<<16) + _, _, _ = procPostMessageW.Call(hudHwnd, wmLButtonDown, 0, pauseLP) + _, _, _ = procPostMessageW.Call(hudHwnd, wmLButtonUp, 0, pauseLP) + select { + case got := <-pausedCh: + if got != vmKey { + t.Fatalf("OnPause vmKey = %q, want %q", got, vmKey) + } + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for OnPause callback") + } + + // Transition to paused (CanResume=true, InputLocked=false) and click Resume. + mgr.Upsert(State{ + VMKey: vmKey, + PID: uint32(os.Getpid()), + Locale: "zh-CN", + Title: "AI 已暂停", + StepBadge: "当前步骤", + StepText: "步骤 1 · 进入恢复环境", + StatusLine: "已暂停,等待手动继续", + CanPause: false, + CanResume: true, + PauseLabel: "暂停", + ResumeLabel: "继续", + StopLabel: "停止", + CollapseLabel: "收起", + InputLocked: false, + Dark: true, + }) + time.Sleep(80 * time.Millisecond) + // Shield should be hidden once InputLocked becomes false. + if sVis, _, _ := procIsWindowVisible.Call(shieldHwnd); sVis != 0 { + t.Fatal("expected shieldHwnd to hide when InputLocked is false") + } + _, _, _ = procPostMessageW.Call(hudHwnd, wmLButtonDown, 0, pauseLP) + _, _, _ = procPostMessageW.Call(hudHwnd, wmLButtonUp, 0, pauseLP) + select { + case got := <-resumedCh: + if got != vmKey { + t.Fatalf("OnResume vmKey = %q, want %q", got, vmKey) + } + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for OnResume callback") + } + + // Click Stop button. + stopX := expLayout.PadX + (expLayout.ExpandedStopBtn.Left+expLayout.ExpandedStopBtn.Right)/2 + stopY := expLayout.PadTop + (expLayout.ExpandedStopBtn.Top+expLayout.ExpandedStopBtn.Bottom)/2 + stopLP := uintptr(uint32(stopX)&0xFFFF | (uint32(stopY)&0xFFFF)<<16) + _, _, _ = procPostMessageW.Call(hudHwnd, wmLButtonDown, 0, stopLP) + _, _, _ = procPostMessageW.Call(hudHwnd, wmLButtonUp, 0, stopLP) + select { + case got := <-stoppedCh: + if got != vmKey { + t.Fatalf("OnStop vmKey = %q, want %q", got, vmKey) + } + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for OnStop callback") + } + + // Confirm zero HWND leaks after Remove. + mgr.Remove(vmKey) + + if ok, _, _ := procIsWindow.Call(hudHwnd); ok != 0 { + t.Fatal("hudHwnd leaked after Remove") + } + if ok, _, _ := procIsWindow.Call(shieldHwnd); ok != 0 { + t.Fatal("shieldHwnd leaked after Remove") + } +} + +// TestOverlayAppearsAboveLaterCreatedOwnerWindow reproduces the real startup +// race where StartAutoInstall opens the overlay with PID=0 before QEMU spawns +// its display window, then binds the live PID afterwards. The overlay must +// immediately move strictly above the newer owner window in Z-order rather +// than remaining hidden behind it. +func TestOverlayAppearsAboveLaterCreatedOwnerWindow(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + const ( + wsVisible = 0x10000000 + gwHwndPrev = 3 + ) + procGetWindow := user32.NewProc("GetWindow") + isAbove := func(top, bottom uintptr) bool { + for cur, _, _ := procGetWindow.Call(bottom, gwHwndPrev); cur != 0; cur, _, _ = procGetWindow.Call(cur, gwHwndPrev) { + if cur == top { + return true + } + } + return false + } + + mgr := NewManager(Callbacks{}) + defer mgr.Close() + + vmKey := "builtin.guest.macos:late-owner-test" + // Step 1: Create overlay while VM is still stopped (PID=0). + mgr.Upsert(State{ + VMKey: vmKey, + PID: 0, + Locale: "zh-CN", + Title: "AI 正在操作", + StepText: "环境准备", + StatusLine: "画面已锁定防干扰", + CanPause: true, + InputLocked: true, + Dark: true, + }) + + // Wait until overlay HWND exists on its UI thread (created BEFORE owner!). + var ent *entry + var hudHwnd uintptr + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + mgr.mu.Lock() + ent = mgr.items[vmKey] + mgr.mu.Unlock() + if ent != nil { + ent.mu.Lock() + hudHwnd = ent.hwnd + ent.mu.Unlock() + if hudHwnd != 0 { + break + } + } + time.Sleep(15 * time.Millisecond) + } + if hudHwnd == 0 { + t.Fatal("overlay HWND was not created") + } + + // Step 2: Now create the VM owner window AFTER hudHwnd (so owner starts higher in Z-order). + clsPtr, _ := syscall.UTF16PtrFromString("STATIC") + offscreen := int32(-16000) + owner, _, err := procCreateWindowExW.Call( + wsExToolWin|wsExNoAct, + uintptr(unsafe.Pointer(clsPtr)), + 0, + wsPopup|wsVisible, + uintptr(offscreen), uintptr(offscreen), 1280, 720, + 0, 0, 0, 0, + ) + if owner == 0 { + t.Fatalf("CreateWindowExW late owner failed: %v", err) + } + defer procDestroyWindow.Call(owner) + + // Step 3: Bind the live PID to the existing overlay. + start := time.Now() + mgr.Upsert(State{ + VMKey: vmKey, + PID: uint32(os.Getpid()), + Locale: "zh-CN", + Title: "AI 正在操作", + StepText: "步骤 1 · 进入恢复环境", + StatusLine: "画面已锁定防干扰", + CanPause: true, + InputLocked: true, + Dark: true, + }) + + deadline = time.Now().Add(2 * time.Second) + attached := false + var shieldHwnd uintptr + for time.Now().Before(deadline) { + vis, _, _ := procIsWindowVisible.Call(hudHwnd) + own, _, _ := procGetWindowLongPtr.Call(hudHwnd, ^uintptr(7)) + hwndMapMu.RLock() + for sh, se := range shieldToEnt { + if se == ent { + shieldHwnd = sh + break + } + } + hwndMapMu.RUnlock() + if vis != 0 && own == owner && isAbove(hudHwnd, owner) && shieldHwnd != 0 { + sVis, _, _ := procIsWindowVisible.Call(shieldHwnd) + if sVis != 0 && isAbove(shieldHwnd, owner) && isAbove(hudHwnd, shieldHwnd) { + attached = true + break + } + } + time.Sleep(15 * time.Millisecond) + } + if !attached { + vis, _, _ := procIsWindowVisible.Call(hudHwnd) + own, _, _ := procGetWindowLongPtr.Call(hudHwnd, ^uintptr(7)) + t.Fatalf("late-attached overlay failed to appear above owner: vis=%d own=%#x wantOwner=%#x hudAboveOwner=%v shield=%#x shieldAboveOwner=%v hudAboveShield=%v", + vis, own, owner, isAbove(hudHwnd, owner), shieldHwnd, isAbove(shieldHwnd, owner), isAbove(hudHwnd, shieldHwnd)) + } + if elapsed := time.Since(start); elapsed > time.Second { + t.Fatalf("overlay took too long to appear above late owner: %v", elapsed) + } + + // Simulate user bringing the VM window to the top of Z-order; HUD must remain above it. + _, _, _ = procSetWindowPos.Call(owner, 0, 0, 0, 0, 0, swpNoMove|swpNoSize|swpNoActivate) + _, _, _ = procPostMessageW.Call(hudHwnd, wmOwnerEvent, 0, 0) + recheck := time.Now().Add(time.Second) + for time.Now().Before(recheck) && !isAbove(hudHwnd, owner) { + time.Sleep(15 * time.Millisecond) + } + if !isAbove(hudHwnd, owner) { + t.Fatal("overlay fell behind owner after owner moved to top of Z-order") + } +} + +func TestOverlaySwitchesWhenOwnerHiddenAndReplaced(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + const wsVisible = 0x10000000 + isAbove := func(top, bottom uintptr) bool { + for cur, _, _ := procGetWindow.Call(bottom, gwHwndPrev); cur != 0; cur, _, _ = procGetWindow.Call(cur, gwHwndPrev) { + if cur == top { + return true + } + } + return false + } + + clsPtr, _ := syscall.UTF16PtrFromString("STATIC") + offscreen := int32(-16000) + owner1, _, err := procCreateWindowExW.Call( + wsExToolWin|wsExNoAct, + uintptr(unsafe.Pointer(clsPtr)), + 0, + wsPopup|wsVisible, + uintptr(offscreen), uintptr(offscreen), 640, 480, + 0, 0, 0, 0, + ) + if owner1 == 0 { + t.Fatalf("CreateWindowExW owner1 failed: %v", err) + } + defer procDestroyWindow.Call(owner1) + + mgr := NewManager(Callbacks{}) + defer mgr.Close() + + vmKey := "builtin.guest.macos:swap-owner-test" + mgr.Upsert(State{ + VMKey: vmKey, + PID: uint32(os.Getpid()), + Locale: "zh-CN", + Title: "AI 正在操作", + StepText: "步骤 1 · 进入恢复环境", + CanPause: true, + InputLocked: false, + Dark: true, + }) + + var hudHwnd uintptr + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + mgr.mu.Lock() + ent := mgr.items[vmKey] + mgr.mu.Unlock() + if ent != nil { + ent.mu.Lock() + hudHwnd = ent.hwnd + ent.mu.Unlock() + } + if hudHwnd != 0 { + vis, _, _ := procIsWindowVisible.Call(hudHwnd) + own, _, _ := procGetWindowLongPtr.Call(hudHwnd, ^uintptr(7)) + if vis != 0 && own == owner1 { + break + } + } + time.Sleep(15 * time.Millisecond) + } + if hudHwnd == 0 { + t.Fatal("overlay failed to attach to initial owner1") + } + + // Hide owner1 (without destroying it) and show a replacement display window owner2. + _, _, _ = procShowWindow.Call(owner1, swHide) + owner2, _, err := procCreateWindowExW.Call( + wsExToolWin|wsExNoAct, + uintptr(unsafe.Pointer(clsPtr)), + 0, + wsPopup|wsVisible, + uintptr(offscreen), uintptr(offscreen), 1280, 720, + 0, 0, 0, 0, + ) + if owner2 == 0 { + t.Fatalf("CreateWindowExW owner2 failed: %v", err) + } + defer procDestroyWindow.Call(owner2) + + switched := false + deadline = time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + vis, _, _ := procIsWindowVisible.Call(hudHwnd) + own, _, _ := procGetWindowLongPtr.Call(hudHwnd, ^uintptr(7)) + if vis != 0 && own == owner2 && isAbove(hudHwnd, owner2) { + switched = true + break + } + time.Sleep(15 * time.Millisecond) + } + if !switched { + vis, _, _ := procIsWindowVisible.Call(hudHwnd) + own, _, _ := procGetWindowLongPtr.Call(hudHwnd, ^uintptr(7)) + t.Fatalf("overlay did not switch to replacement owner2: vis=%d own=%#x want=%#x above=%v", vis, own, owner2, isAbove(hudHwnd, owner2)) + } +} + +func TestOverlayAppearsAboveTopmostOwner(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + const wsVisible = 0x10000000 + isAbove := func(top, bottom uintptr) bool { + for cur, _, _ := procGetWindow.Call(bottom, gwHwndPrev); cur != 0; cur, _, _ = procGetWindow.Call(cur, gwHwndPrev) { + if cur == top { + return true + } + } + return false + } + + clsPtr, _ := syscall.UTF16PtrFromString("STATIC") + offscreen := int32(-16000) + owner, _, err := procCreateWindowExW.Call( + wsExTopmost|wsExToolWin|wsExNoAct, + uintptr(unsafe.Pointer(clsPtr)), + 0, + wsPopup|wsVisible, + uintptr(offscreen), uintptr(offscreen), 1280, 720, + 0, 0, 0, 0, + ) + if owner == 0 { + t.Fatalf("CreateWindowExW topmost owner failed: %v", err) + } + defer procDestroyWindow.Call(owner) + + mgr := NewManager(Callbacks{}) + defer mgr.Close() + + vmKey := "builtin.guest.macos:topmost-owner-test" + mgr.Upsert(State{ + VMKey: vmKey, + PID: uint32(os.Getpid()), + Locale: "zh-CN", + Title: "AI 正在操作", + StepText: "步骤 1 · 进入恢复环境", + CanPause: true, + InputLocked: false, + Dark: true, + }) + + start := time.Now() + var hudHwnd uintptr + attached := false + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + mgr.mu.Lock() + ent := mgr.items[vmKey] + mgr.mu.Unlock() + if ent != nil { + ent.mu.Lock() + hudHwnd = ent.hwnd + ent.mu.Unlock() + } + if hudHwnd != 0 { + vis, _, _ := procIsWindowVisible.Call(hudHwnd) + own, _, _ := procGetWindowLongPtr.Call(hudHwnd, ^uintptr(7)) + if vis != 0 && own == owner && isAbove(hudHwnd, owner) { + attached = true + break + } + } + time.Sleep(15 * time.Millisecond) + } + if !attached { + t.Fatalf("overlay failed to appear above topmost owner: hud=%#x above=%v", hudHwnd, isAbove(hudHwnd, owner)) + } + if elapsed := time.Since(start); elapsed > time.Second { + t.Fatalf("overlay took too long to appear above topmost owner: %v", elapsed) + } +} + +func TestScriptForStateResolvesAutoAndMixedCJK(t *testing.T) { + cases := []struct { + name string + st State + want scriptKind + }{ + { + name: "auto locale with Simplified Chinese step text", + st: State{Locale: "auto", Title: "AI 正在操作", StepText: "步骤 1 · 进入恢复环境"}, + want: scriptHans, + }, + { + name: "empty locale with Chinese text", + st: State{Locale: "", StatusLine: "画面已锁定防干扰"}, + want: scriptHans, + }, + { + name: "en-US locale displaying Chinese text avoids Latin CJK fallback", + st: State{Locale: "en-US", StepText: "步骤 2 · 磁盘工具抹盘"}, + want: scriptHans, + }, + { + name: "explicit Traditional Chinese locale preserved", + st: State{Locale: "zh-TW", StepText: "步驟 1 · 進入復原環境"}, + want: scriptHant, + }, + { + name: "auto locale with Japanese kana", + st: State{Locale: "auto", StepText: "ステップ 1 · リカバリ起動"}, + want: scriptJpan, + }, + { + name: "auto locale with Korean hangul", + st: State{Locale: "auto", StepText: "단계 1 · 복구 모드"}, + want: scriptKore, + }, + { + name: "pure English stays Latin", + st: State{Locale: "en-US", Title: "AI controlling VM", StepText: "Step 1 · Boot into Recovery", StopLabel: "Stop"}, + want: scriptLatn, + }, + } + for _, tc := range cases { + if got := scriptForState(tc.st); got != tc.want { + t.Errorf("%s: scriptForState(%+v) = %v, want %v", tc.name, tc.st, got, tc.want) + } + } +} + +func TestWindowsOverlayCompletedHidesShieldAndFiresOnDismiss(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + const wsVisible = 0x10000000 + clsPtr, _ := syscall.UTF16PtrFromString("STATIC") + offscreen := int32(-16000) + owner, _, err := procCreateWindowExW.Call( + wsExToolWin|wsExNoAct, + uintptr(unsafe.Pointer(clsPtr)), + 0, + wsPopup|wsVisible, + uintptr(offscreen), uintptr(offscreen), 1280, 720, + 0, 0, 0, 0, + ) + if owner == 0 { + t.Fatalf("CreateWindowExW owner failed: %v", err) + } + defer procDestroyWindow.Call(owner) + + dismissCh := make(chan string, 1) + stopCh := make(chan string, 1) + mgr := NewManager(Callbacks{ + OnDismiss: func(vmKey string) { dismissCh <- vmKey }, + OnStop: func(vmKey string) { stopCh <- vmKey }, + }) + defer mgr.Close() + + vmKey := "builtin.guest.macos:completed-overlay-test" + mgr.Upsert(State{ + VMKey: vmKey, + PID: uint32(os.Getpid()), + Locale: "zh-CN", + Title: "AI 正在操作", + StepText: "步骤 3 · 等待系统安装", + StatusLine: "画面已锁定防干扰", + CanPause: true, + InputLocked: true, + }) + + var ent *entry + var hudHwnd, shieldHwnd uintptr + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + mgr.mu.Lock() + ent = mgr.items[vmKey] + mgr.mu.Unlock() + if ent != nil { + ent.mu.Lock() + hudHwnd = ent.hwnd + ent.mu.Unlock() + } + if hudHwnd != 0 { + if vis, _, _ := procIsWindowVisible.Call(hudHwnd); vis != 0 { + hwndMapMu.RLock() + for sh, se := range shieldToEnt { + if se == ent { + shieldHwnd = sh + break + } + } + hwndMapMu.RUnlock() + if shieldHwnd != 0 { + if sVis, _, _ := procIsWindowVisible.Call(shieldHwnd); sVis != 0 { + break + } + } + } + } + time.Sleep(20 * time.Millisecond) + } + if hudHwnd == 0 || shieldHwnd == 0 { + t.Fatalf("overlay failed to attach before completion: hud=%#x shield=%#x", hudHwnd, shieldHwnd) + } + + // Transition to Completed -> shield must immediately hide while HUD remains visible. + doneSt := State{ + VMKey: vmKey, + PID: uint32(os.Getpid()), + Locale: "zh-CN", + Title: "macOS 自动装机助手", + StepText: "已完成", + StatusLine: "已完成恢复模式安装并进入 macOS,画面输入已解锁", + Completed: true, + CloseLabel: "关闭", + InputLocked: true, // Manager.Upsert must defensively force false when Completed=true + } + mgr.Upsert(doneSt) + time.Sleep(80 * time.Millisecond) + + if sVis, _, _ := procIsWindowVisible.Call(shieldHwnd); sVis != 0 { + t.Fatal("expected input shield to hide immediately when Completed=true") + } + if vis, _, _ := procIsWindowVisible.Call(hudHwnd); vis == 0 { + t.Fatal("expected completed HUD overlay to stay visible until dismissed") + } + + // Click the full-width Close button -> must fire OnDismiss, not OnStop. + dpi := queryWindowDPI(owner) + expLayout := computeIslandLayout(doneSt, dpi, 1280, 90, 1, 1) + closeX := expLayout.PadX + (expLayout.ExpandedStopBtn.Left+expLayout.ExpandedStopBtn.Right)/2 + closeY := expLayout.PadTop + (expLayout.ExpandedStopBtn.Top+expLayout.ExpandedStopBtn.Bottom)/2 + closeLP := uintptr(uint32(closeX)&0xFFFF | (uint32(closeY)&0xFFFF)<<16) + _, _, _ = procPostMessageW.Call(hudHwnd, wmLButtonDown, 0, closeLP) + _, _, _ = procPostMessageW.Call(hudHwnd, wmLButtonUp, 0, closeLP) + select { + case got := <-dismissCh: + if got != vmKey { + t.Fatalf("OnDismiss vmKey = %q, want %q", got, vmKey) + } + case got := <-stopCh: + t.Fatalf("unexpected OnStop(%q) on completed overlay close click", got) + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for OnDismiss callback") + } + + mgr.Remove(vmKey) + if ok, _, _ := procIsWindow.Call(hudHwnd); ok != 0 { + t.Fatal("hudHwnd leaked after Remove") + } + if ok, _, _ := procIsWindow.Call(shieldHwnd); ok != 0 { + t.Fatal("shieldHwnd leaked after Remove") + } +} + +func TestDWriteEngineRenderTextAndEndDraw(t *testing.T) { + screenDC, _, _ := procGetDC.Call(0) + if screenDC == 0 { + t.Skip("no desktop DC available") + } + defer procReleaseDC.Call(0, screenDC) + + var dw dwriteEngine + defer dw.release() + if !dw.ensureInit() { + t.Fatal("dwriteEngine.ensureInit() returned false; Direct2D/DirectWrite vtable init failed") + } + var canvas dibSurface + defer canvas.release() + if !canvas.ensure(screenDC, 240, 48) { + t.Fatal("dibSurface.ensure failed") + } + canvas.clear() + if !dw.beginSurface(&canvas) { + t.Fatal("dwriteEngine.beginSurface failed (BindDC / BeginDraw)") + } + ok := dw.drawText(96, scriptHans, styleHero, "macOS 自动装机", rect2i{Left: 8, Top: 8, Right: 232, Bottom: 40}, dwAlignLeading, 1, rgba{29, 29, 31}, 1.0) + endOK := dw.endSurface() + if !ok || !endOK { + t.Fatalf("dwrite draw/end failed: drawOK=%v endOK=%v", ok, endOK) + } + nonZero := 0 + for i := 3; i < len(canvas.bits); i += 4 { + if canvas.bits[i] > 0 { + nonZero++ + } + } + if nonZero < 40 { + t.Fatalf("expected rendered text pixels with non-zero alpha, got %d", nonZero) + } +} + +func TestCachedBaseFrameMatchesFullRenderAcrossBreathLevels(t *testing.T) { + screenDC, _, _ := procGetDC.Call(0) + if screenDC == 0 { + t.Skip("no desktop DC available") + } + defer procReleaseDC.Call(0, screenDC) + + st := State{ + VMKey: "builtin.guest.macos:cache-test", + Locale: "zh-CN", + Title: "macOS 自动装机助手", + StepBadge: "当前步骤", + StepText: "步骤 2 · 安装系统", + StatusLine: "正在写入 macOS 系统文件", + CanPause: true, + PauseLabel: "暂停", + StopLabel: "停止", + CollapseLabel: "收起", + InputLocked: true, + } + layout := computeIslandLayout(st, 96, 1280, 120, 1, 1) + fonts := getIslandFonts(96, scriptForState(st)) + + var dw dwriteEngine + defer dw.release() + var fullCanvas, cachedCanvas, scratch dibSurface + var baseCache islandBaseCache + defer fullCanvas.release() + defer cachedCanvas.release() + defer scratch.release() + defer baseCache.release() + + for _, breath := range []float64{0.15, 0.85} { + params := renderParams{ + state: st, + layout: layout, + statusLines: []string{st.StatusLine}, + fonts: fonts, + dw: &dw, + breath: breath, + } + if !renderIslandFrame(&fullCanvas, &scratch, screenDC, params) { + t.Fatalf("full render failed at breath=%v", breath) + } + cachedParams := params + cachedParams.baseCache = &baseCache + if !renderIslandFrame(&cachedCanvas, &scratch, screenDC, cachedParams) { + t.Fatalf("cached render failed at breath=%v", breath) + } + if !baseCache.valid { + t.Fatal("expected baseCache to remain valid") + } + if string(fullCanvas.bits) != string(cachedCanvas.bits) { + t.Fatalf("cached render diverged from full render at breath=%v", breath) + } + } +} + +func TestUpsertRecreatesDeadOverlayEntry(t *testing.T) { + mgr := NewManager(Callbacks{}) + defer mgr.Close() + + vmKey := "builtin.guest.macos:dead-entry" + dead := &entry{mgr: mgr, state: State{VMKey: vmKey}, done: make(chan struct{})} + close(dead.done) + mgr.mu.Lock() + mgr.items[vmKey] = dead + mgr.mu.Unlock() + + mgr.Upsert(State{VMKey: vmKey, Title: "Recovered"}) + mgr.mu.Lock() + cur := mgr.items[vmKey] + mgr.mu.Unlock() + if cur == nil || cur == dead { + t.Fatal("expected Upsert to replace dead exited overlay entry") + } +} diff --git a/internal/host/sessionoverlay/render_windows.go b/internal/host/sessionoverlay/render_windows.go new file mode 100644 index 0000000..5dee4ef --- /dev/null +++ b/internal/host/sessionoverlay/render_windows.go @@ -0,0 +1,1443 @@ +//go:build windows + +package sessionoverlay + +import ( + "math" + "strings" + "sync" + "syscall" + "unicode/utf16" + "unsafe" +) + +type rgba struct { + r, g, b uint8 +} + +type scriptKind uint8 + +const ( + scriptLatn scriptKind = iota + scriptHans + scriptHant + scriptJpan + scriptKore +) + +func scriptForLocale(locale string) scriptKind { + s := strings.ToLower(strings.TrimSpace(locale)) + switch { + case s == "zh-tw" || s == "zh-hk" || s == "zh-mo" || strings.HasPrefix(s, "zh-hant"): + return scriptHant + case strings.HasPrefix(s, "zh"): + return scriptHans + case strings.HasPrefix(s, "ja"): + return scriptJpan + case strings.HasPrefix(s, "ko"): + return scriptKore + default: + return scriptLatn + } +} + +func detectCJKScript(texts ...string) scriptKind { + hasHan := false + for _, s := range texts { + for _, r := range s { + switch { + case (r >= 0xAC00 && r <= 0xD7AF) || (r >= 0x1100 && r <= 0x11FF): + return scriptKore + case r >= 0x3040 && r <= 0x30FF: + return scriptJpan + case (r >= 0x4E00 && r <= 0x9FFF) || (r >= 0x3400 && r <= 0x4DBF) || (r >= 0xF900 && r <= 0xFAFF): + hasHan = true + } + } + } + if hasHan { + return scriptHans + } + return scriptLatn +} + +// scriptForState picks the typography script from st.Locale and falls back to +// inspecting rendered text when Locale is unresolved (e.g. "auto" or "") or +// Latin while displaying CJK text, preventing Windows DirectWrite from mixing +// Japanese Yu Gothic and Chinese Microsoft YaHei glyphs in the same word. +func scriptForState(st State) scriptKind { + if sk := scriptForLocale(st.Locale); sk != scriptLatn { + return sk + } + return detectCJKScript(st.StepText, st.Title, st.StatusLine, st.PauseLabel, st.ResumeLabel, st.StopLabel, st.CloseLabel, st.CollapseLabel) +} + +type logFontW struct { + height, width, escapement, orientation, weight int32 + italic, underline, strikeOut, charSet byte + outPrecision, clipPrecision, quality, pitchFam byte + face [32]uint16 +} + +type bitmapInfoHeader struct { + size uint32 + width int32 + height int32 + planes uint16 + bitCount uint16 + compression uint32 + sizeImage uint32 + xPelsPerMeter int32 + yPelsPerMeter int32 + clrUsed uint32 + clrImportant uint32 +} + +type gdiSize struct{ cx, cy int32 } + +type fontKey struct { + dpi int32 + script scriptKind +} + +type islandFontSet struct { + compactTitle uintptr + title uintptr + stepBadge uintptr + stepText uintptr + status uintptr + btn uintptr +} + +var ( + fontProbeOnce sync.Once + fontProbeHit bool + fontEnumProc = syscall.NewCallback(func(lpelfe, lpntme, fontType, lparam uintptr) uintptr { + fontProbeHit = true + return 0 + }) + scriptFaces = map[scriptKind]string{ + scriptLatn: "Segoe UI", + scriptHans: "Microsoft YaHei UI", + scriptHant: "Microsoft JhengHei UI", + scriptJpan: "Yu Gothic UI", + scriptKore: "Malgun Gothic", + } + fontCacheMu sync.Mutex + fontCache = map[fontKey]islandFontSet{} +) + +func setFace(lf *logFontW, name string) { + for i := range lf.face { + lf.face[i] = 0 + } + for i, ch := range name { + if i >= len(lf.face)-1 { + break + } + lf.face[i] = uint16(ch) + } +} + +func probeFontFamilies() { + fontProbeOnce.Do(func() { + dc, _, _ := procGetDC.Call(0) + if dc == 0 { + return + } + defer procReleaseDC.Call(0, dc) + has := func(name string) bool { + var lf logFontW + lf.charSet = 1 // DEFAULT_CHARSET + setFace(&lf, name) + fontProbeHit = false + _, _, _ = procEnumFontFamiliesExW.Call(dc, uintptr(unsafe.Pointer(&lf)), fontEnumProc, 0, 0) + return fontProbeHit + } + pick := func(sk scriptKind, candidates []string) { + for _, f := range candidates { + if has(f) { + scriptFaces[sk] = f + return + } + } + } + pick(scriptLatn, []string{"Segoe UI Variable Text", "Segoe UI"}) + pick(scriptHans, []string{ + "PingFang SC Medium", "PingFang SC", "HarmonyOS Sans SC", "MiSans", + "Noto Sans SC Medium", "Noto Sans SC", "Source Han Sans CN Medium", "Source Han Sans CN", + "Microsoft YaHei UI", "Segoe UI", + }) + pick(scriptHant, []string{ + "PingFang TC", "Noto Sans TC", "Source Han Sans TC", + "Microsoft JhengHei UI", "Microsoft JhengHei", "Microsoft YaHei UI", "Segoe UI", + }) + pick(scriptJpan, []string{ + "Hiragino Sans", "Noto Sans JP", "BIZ UDPGothic", + "Yu Gothic UI", "Meiryo UI", "Meiryo", "Microsoft YaHei UI", "Segoe UI", + }) + pick(scriptKore, []string{ + "Apple SD Gothic Neo", "Noto Sans KR", "Malgun Gothic", "Segoe UI", + }) + }) +} + +func isWeightJumpCJK(face string) bool { + switch face { + case "Microsoft YaHei UI", "Microsoft YaHei", "Microsoft JhengHei UI", "Microsoft JhengHei", "Yu Gothic UI", "Meiryo UI", "Meiryo", "Malgun Gothic": + return true + default: + return false + } +} + +func makeAAFont(face string, px float64, dpi, weight int32) uintptr { + var lf logFontW + lf.height = -max(int32(1), int32(math.Round(px*float64(dpi)/96.0))) + lf.weight = weight + lf.charSet = 1 // DEFAULT_CHARSET + // ANTIALIASED_QUALITY (4) produces clean grayscale glyph coverage suitable + // for accurate premultiplied-alpha compositing onto layered windows. + lf.quality = 4 + setFace(&lf, face) + h, _, _ := procCreateFontIndirectW.Call(uintptr(unsafe.Pointer(&lf))) + return h +} + +func getIslandFonts(dpi int32, script scriptKind) islandFontSet { + if dpi < 96 { + dpi = 96 + } + probeFontFamilies() + key := fontKey{dpi: dpi, script: script} + fontCacheMu.Lock() + defer fontCacheMu.Unlock() + if fs, ok := fontCache[key]; ok { + return fs + } + face := scriptFaces[script] + if face == "" { + face = scriptFaces[scriptLatn] + } + medWeight := int32(550) + titleWeight := int32(600) + if isWeightJumpCJK(face) { + medWeight = 400 + titleWeight = 600 + } + fs := islandFontSet{ + compactTitle: makeAAFont(face, 12.5, dpi, medWeight), + title: makeAAFont(face, 13.5, dpi, titleWeight), + stepBadge: makeAAFont(face, 10.5, dpi, titleWeight), + stepText: makeAAFont(face, 12.5, dpi, titleWeight), + status: makeAAFont(face, 12.0, dpi, 400), + btn: makeAAFont(face, 12.5, dpi, medWeight), + } + fontCache[key] = fs + return fs +} + +// dibSurface holds a reusable top-down 32-bit BGRA GDI DIB section for either +// the final premultiplied-alpha layered canvas or the grayscale text scratchpad. +type dibSurface struct { + hdc uintptr + hbmp uintptr + old uintptr + bits []byte + w, h int32 +} + +func (s *dibSurface) ensure(screenDC uintptr, w, h int32) bool { + if w <= 0 || h <= 0 { + return false + } + if s.hdc != 0 && s.w == w && s.h == h && len(s.bits) == int(w)*int(h)*4 { + return true + } + s.release() + memDC, _, _ := procCreateCompatibleDC.Call(screenDC) + if memDC == 0 { + return false + } + bmi := bitmapInfoHeader{ + size: uint32(unsafe.Sizeof(bitmapInfoHeader{})), + width: w, + height: -h, // top-down DIB + planes: 1, + bitCount: 32, + } + var ptr unsafe.Pointer + hbmp, _, _ := procCreateDIBSection.Call(memDC, uintptr(unsafe.Pointer(&bmi)), 0, uintptr(unsafe.Pointer(&ptr)), 0, 0) + if hbmp == 0 || ptr == nil { + _, _, _ = procDeleteDC.Call(memDC) + return false + } + old, _, _ := procSelectObject.Call(memDC, hbmp) + s.hdc = memDC + s.hbmp = hbmp + s.old = old + s.w = w + s.h = h + s.bits = unsafe.Slice((*byte)(ptr), int(w)*int(h)*4) + return true +} + +func (s *dibSurface) clear() { + clear(s.bits) +} + +func (s *dibSurface) release() { + if s.hdc != 0 { + if s.old != 0 { + _, _, _ = procSelectObject.Call(s.hdc, s.old) + } + if s.hbmp != 0 { + _, _, _ = procDeleteObject.Call(s.hbmp) + } + _, _, _ = procDeleteDC.Call(s.hdc) + } + s.hdc = 0 + s.hbmp = 0 + s.old = 0 + s.bits = nil + s.w = 0 + s.h = 0 +} + +// blendPixel composites straight (r,g,b,a) over premultiplied BGRA at (x, y). +func (s *dibSurface) blendPixel(x, y int, c rgba, a float64) { + if x < 0 || y < 0 || x >= int(s.w) || y >= int(s.h) || a <= 0.001 { + return + } + if a > 1 { + a = 1 + } + i := (y*int(s.w) + x) * 4 + inv := 1.0 - a + sb := float64(c.b) * a + sg := float64(c.g) * a + sr := float64(c.r) * a + sa := 255.0 * a + + db := float64(s.bits[i]) + dg := float64(s.bits[i+1]) + dr := float64(s.bits[i+2]) + da := float64(s.bits[i+3]) + + aOut := clampByte(sa + da*inv) + bOut := clampByte(sb + db*inv) + gOut := clampByte(sg + dg*inv) + rOut := clampByte(sr + dr*inv) + if bOut > aOut { + bOut = aOut + } + if gOut > aOut { + gOut = aOut + } + if rOut > aOut { + rOut = aOut + } + s.bits[i] = bOut + s.bits[i+1] = gOut + s.bits[i+2] = rOut + s.bits[i+3] = aOut +} + +func clampByte(v float64) uint8 { + if v <= 0 { + return 0 + } + if v >= 255 { + return 255 + } + return uint8(v + 0.5) +} + +func roundedBoxSDF(px, py, cx, cy, hw, hh, r float64) float64 { + dx := math.Abs(px-cx) - (hw - r) + dy := math.Abs(py-cy) - (hh - r) + qx := math.Max(dx, 0) + qy := math.Max(dy, 0) + return math.Hypot(qx, qy) + math.Min(math.Max(dx, dy), 0) - r +} + +func segmentSDF(px, py, ax, ay, bx, by float64) float64 { + pax, pay := px-ax, py-ay + bax, bay := bx-ax, by-ay + denom := bax*bax + bay*bay + h := 0.0 + if denom > 1e-6 { + h = clamp01((pax*bax + pay*bay) / denom) + } + return math.Hypot(pax-bax*h, pay-bay*h) +} + +// paintIslandShell renders a crisp, fully opaque light macOS Tahoe floating +// card matching Reims-Go's main window & install guide palette (#FFFFFF -> +// #F8F9FB), with a delicate cool-slate layered elevation shadow, clean 1px +// hairline border, and warm amber pulse when the locked VM screen is clicked. +func (s *dibSurface) paintIslandShell(l islandLayout, paused bool, pulse float64) { + px0 := float64(l.PadX) + py0 := float64(l.PadTop) + pw := float64(l.PillW) + ph := float64(l.PillH) + cx := px0 + pw*0.5 + cy := py0 + ph*0.5 + hw := pw * 0.5 + hh := ph * 0.5 + r := l.PillRadius + + dpiF := float64(l.DPI) / 96.0 + shadowBlur := 14.5 * dpiF + shadowOffY := 5.8 * dpiF + contactBlur := 3.2 * dpiF + contactOffY := 1.2 * dpiF + borderW := math.Max(1.0, 1.0*dpiF) + + // Pure white -> ultra-soft cool alabaster (matching tokens.css light surface). + topCol := rgba{255, 255, 255} // #FFFFFF + botCol := rgba{248, 249, 252} // #F8F9FC + shadowCol := rgba{15, 23, 42} // --shadow-overlay slate tint + rimBase := rgba{15, 23, 42} + pulseCol := rgba{245, 158, 11} // crisp Apple Amber for light surface + + _ = paused + + flatX0 := int(math.Ceil(px0 + r + borderW + 2)) + flatX1 := int(math.Floor(px0 + pw - r - borderW - 2)) + flatY0 := int(math.Ceil(py0 + borderW + 2)) + flatY1 := int(math.Floor(py0 + ph - borderW - 2)) + + w := int(s.w) + h := int(s.h) + for y := 0; y < h; y++ { + fy := float64(y) + 0.5 + vNorm := clamp01((fy - py0) / math.Max(1, ph)) + rowOff := y * w * 4 + inFlatY := y >= flatY0 && y < flatY1 + + baseR := lerpFloat(float64(topCol.r), float64(botCol.r), vNorm) + baseG := lerpFloat(float64(topCol.g), float64(botCol.g), vNorm) + baseB := lerpFloat(float64(topCol.b), float64(botCol.b), vNorm) + if pulse > 0.005 { + pf := 0.045 * pulse + baseR = baseR*(1-pf) + float64(pulseCol.r)*pf + baseG = baseG*(1-pf) + float64(pulseCol.g)*pf + baseB = baseB*(1-pf) + float64(pulseCol.b)*pf + } + + for x := 0; x < w; x++ { + fx := float64(x) + 0.5 + if inFlatY && x >= flatX0 && x < flatX1 { + off := rowOff + x*4 + s.bits[off] = clampByte(baseB) + s.bits[off+1] = clampByte(baseG) + s.bits[off+2] = clampByte(baseR) + s.bits[off+3] = 255 + continue + } + + d := roundedBoxSDF(fx, fy, cx, cy, hw, hh, r) + + // 1. Delicate layered cool-slate macOS elevation shadow (gap-free). + var outR, outG, outB, outA float64 + if d > -1.5 { + var shA float64 + ds := roundedBoxSDF(fx, fy-shadowOffY, cx, cy, hw, hh, r) + if ds < shadowBlur { + t := clamp01(1.0 - math.Max(0, ds)/shadowBlur) + shA = 0.22 * t * t * t + } + dc := roundedBoxSDF(fx, fy-contactOffY, cx, cy, hw, hh, r) + if dc < contactBlur { + tc := clamp01(1.0 - math.Max(0, dc)/contactBlur) + cA := 0.13 * tc * tc + shA = cA + shA*(1.0-cA) + } + if shA > 0.001 { + outR = float64(shadowCol.r) * shA + outG = float64(shadowCol.g) * shA + outB = float64(shadowCol.b) * shA + outA = shA + } + if pulse > 0.005 && d >= -0.5 && d < 6.0*dpiF { + tp := clamp01(1.0 - math.Max(0, d)/(6.0*dpiF)) + glowA := 0.34 * pulse * tp * tp + inv := 1.0 - glowA + outR = float64(pulseCol.r)*glowA + outR*inv + outG = float64(pulseCol.g)*glowA + outG*inv + outB = float64(pulseCol.b)*glowA + outB*inv + outA = glowA + outA*inv + } + } + + // 2. Opaque pure-white card interior + crisp 1px subtle slate hairline border. + outerCov := clamp01(0.5 - d) + if outerCov > 0.001 { + innerCov := clamp01(0.5 - (d + borderW)) + rimCov := clamp01(outerCov - innerCov) + + bodyA := outerCov + invBody := 1.0 - bodyA + outR = baseR*bodyA + outR*invBody + outG = baseG*bodyA + outG*invBody + outB = baseB*bodyA + outB*invBody + outA = bodyA + outA*invBody + + if rimCov > 0.001 { + rimAlpha := 0.095 + rimR, rimG, rimB := float64(rimBase.r), float64(rimBase.g), float64(rimBase.b) + if pulse > 0.005 { + mixP := clamp01(pulse * 0.92) + rimR = lerpFloat(rimR, float64(pulseCol.r), mixP) + rimG = lerpFloat(rimG, float64(pulseCol.g), mixP) + rimB = lerpFloat(rimB, float64(pulseCol.b), mixP) + rimAlpha = lerpFloat(rimAlpha, 0.72, mixP) + } + ra := rimAlpha * rimCov + invR := 1.0 - ra + outR = rimR*ra + outR*invR + outG = rimG*ra + outG*invR + outB = rimB*ra + outB*invR + outA = ra + outA*invR + } + } + + if outA > 0.001 { + aOut := clampByte(outA * 255.0) + s.bits[rowOff+x*4] = min(aOut, clampByte(outB)) + s.bits[rowOff+x*4+1] = min(aOut, clampByte(outG)) + s.bits[rowOff+x*4+2] = min(aOut, clampByte(outR)) + s.bits[rowOff+x*4+3] = aOut + } + } + } +} + +// paintTactilePill draws a crisp, anti-aliased solid matte button or badge with +// vertical micro-gradient, 1px hairline border, and delicate top inner highlight. +func (s *dibSurface) paintTactilePill(r rect2i, radius float64, topFill, botFill rgba, fillA float64, border rgba, borderA float64, topHiA float64) { + if r.width() <= 0 || r.height() <= 0 || (fillA <= 0.001 && borderA <= 0.001) { + return + } + cx := float64(r.Left+r.Right) * 0.5 + cy := float64(r.Top+r.Bottom) * 0.5 + hw := float64(r.width()) * 0.5 + hh := float64(r.height()) * 0.5 + if radius > math.Min(hw, hh) { + radius = math.Min(hw, hh) + } + x0 := max(0, int(r.Left)-1) + y0 := max(0, int(r.Top)-1) + x1 := min(int(s.w), int(r.Right)+1) + y1 := min(int(s.h), int(r.Bottom)+1) + + for y := y0; y < y1; y++ { + fy := float64(y) + 0.5 + vNorm := clamp01((fy - float64(r.Top)) / math.Max(1, float64(r.height()))) + curFill := rgba{ + r: clampByte(lerpFloat(float64(topFill.r), float64(botFill.r), vNorm)), + g: clampByte(lerpFloat(float64(topFill.g), float64(botFill.g), vNorm)), + b: clampByte(lerpFloat(float64(topFill.b), float64(botFill.b), vNorm)), + } + for x := x0; x < x1; x++ { + fx := float64(x) + 0.5 + d := roundedBoxSDF(fx, fy, cx, cy, hw, hh, radius) + cov := clamp01(0.5 - d) + if cov <= 0.001 { + continue + } + if fillA > 0.001 { + s.blendPixel(x, y, curFill, fillA*cov) + if topHiA > 0.001 && vNorm < 0.30 { + boost := (1.0 - vNorm/0.30) * topHiA * cov + s.blendPixel(x, y, rgba{255, 255, 255}, boost) + } + } + if borderA > 0.001 { + innerCov := clamp01(0.5 - (d + 1.0)) + rim := clamp01(cov - innerCov) + if rim > 0.001 { + s.blendPixel(x, y, border, clamp01(borderA)*rim) + } + } + } + } +} + +// paintStatusDot draws the breathing Apple light-mode green (running) or warm +// amber (paused) indicator dot with a soft pastel halo. +func (s *dibSurface) paintStatusDot(center point2i, dpi int32, paused bool, breath float64) { + col := rgba{40, 205, 65} // --status-running #28cd41 + if paused { + col = rgba{255, 159, 10} // --status-busy #ff9f0a + } + coreR := scaleDPF(dpi, 3.4) + haloR := scaleDPF(dpi, 7.2+2.0*breath) + haloPeak := 0.14 + 0.14*breath + if paused { + haloR = scaleDPF(dpi, 7.6) + haloPeak = 0.18 + } + + cx := float64(center.X) + cy := float64(center.Y) + rad := int(math.Ceil(haloR)) + 1 + x0 := max(0, int(math.Floor(cx))-rad) + y0 := max(0, int(math.Floor(cy))-rad) + x1 := min(int(s.w), int(math.Ceil(cx))+rad) + y1 := min(int(s.h), int(math.Ceil(cy))+rad) + + for y := y0; y < y1; y++ { + fy := float64(y) + 0.5 + for x := x0; x < x1; x++ { + fx := float64(x) + 0.5 + dist := math.Hypot(fx-cx, fy-cy) + if dist < haloR { + ht := clamp01(1.0 - dist/haloR) + s.blendPixel(x, y, col, haloPeak*ht*ht) + } + coreCov := clamp01(0.5 - (dist - coreR)) + if coreCov > 0.001 { + // Subtle top-left specular gleam inside the dot for jewel-like depth. + gleamDist := math.Hypot(fx-(cx-coreR*0.28), fy-(cy-coreR*0.28)) + gleam := clamp01(1.0-gleamDist/(coreR*0.85)) * 0.32 + c := rgba{ + r: clampByte(lerpFloat(float64(col.r), 255, gleam)), + g: clampByte(lerpFloat(float64(col.g), 255, gleam)), + b: clampByte(lerpFloat(float64(col.b), 255, gleam)), + } + s.blendPixel(x, y, c, coreCov) + } + } + } +} + +func (s *dibSurface) paintPauseIcon(cx, cy float64, dpi int32, col rgba, alpha float64) { + if alpha <= 0.005 { + return + } + barW := scaleDPF(dpi, 2.3) + barH := scaleDPF(dpi, 9.2) + gap := scaleDPF(dpi, 2.6) + rad := barW * 0.45 + leftCX := cx - (gap+barW)*0.5 + rightCX := cx + (gap+barW)*0.5 + + boundX := int(math.Ceil(gap*0.5+barW)) + 2 + boundY := int(math.Ceil(barH*0.5)) + 2 + x0 := max(0, int(math.Floor(cx))-boundX) + y0 := max(0, int(math.Floor(cy))-boundY) + x1 := min(int(s.w), int(math.Ceil(cx))+boundX) + y1 := min(int(s.h), int(math.Ceil(cy))+boundY) + for y := y0; y < y1; y++ { + fy := float64(y) + 0.5 + for x := x0; x < x1; x++ { + fx := float64(x) + 0.5 + d1 := roundedBoxSDF(fx, fy, leftCX, cy, barW*0.5, barH*0.5, rad) + d2 := roundedBoxSDF(fx, fy, rightCX, cy, barW*0.5, barH*0.5, rad) + cov := clamp01(0.5 - math.Min(d1, d2)) + if cov > 0.001 { + s.blendPixel(x, y, col, cov*alpha) + } + } + } +} + +func (s *dibSurface) paintPlayIcon(cx, cy float64, dpi int32, col rgba, alpha float64) { + if alpha <= 0.005 { + return + } + // Optically shift right slightly so triangle center feels visually balanced. + ocx := cx + scaleDPF(dpi, 0.7) + sz := scaleDPF(dpi, 4.4) + ax, ay := ocx-sz*0.85, cy-sz + bx, by := ocx-sz*0.85, cy+sz + tx, ty := ocx+sz*1.05, cy + round := scaleDPF(dpi, 0.85) + + bound := int(math.Ceil(sz*1.6)) + 2 + x0 := max(0, int(math.Floor(ocx))-bound) + y0 := max(0, int(math.Floor(cy))-bound) + x1 := min(int(s.w), int(math.Ceil(ocx))+bound) + y1 := min(int(s.h), int(math.Ceil(cy))+bound) + + // Signed distance to triangle (a, b, t) in counter-clockwise order. + cross := func(px, py, x1, y1, x2, y2 float64) float64 { + return (px-x2)*(y1-y2) - (x1-x2)*(py-y2) + } + for y := y0; y < y1; y++ { + fy := float64(y) + 0.5 + for x := x0; x < x1; x++ { + fx := float64(x) + 0.5 + d1 := segmentSDF(fx, fy, ax, ay, bx, by) + d2 := segmentSDF(fx, fy, bx, by, tx, ty) + d3 := segmentSDF(fx, fy, tx, ty, ax, ay) + edgeD := math.Min(d1, math.Min(d2, d3)) + c1 := cross(fx, fy, ax, ay, bx, by) + c2 := cross(fx, fy, bx, by, tx, ty) + c3 := cross(fx, fy, tx, ty, ax, ay) + inside := (c1 >= 0 && c2 >= 0 && c3 >= 0) || (c1 <= 0 && c2 <= 0 && c3 <= 0) + sd := edgeD + if inside { + sd = -edgeD + } + cov := clamp01(0.5 - (sd - round)) + if cov > 0.001 { + s.blendPixel(x, y, col, cov*alpha) + } + } + } +} + +// paintCompletedDot draws a steady Apple green circular badge with a crisp +// white checkmark when an automated session has completed and unlocked input. +func (s *dibSurface) paintCompletedDot(center point2i, dpi int32) { + col := rgba{40, 205, 65} // --status-running #28cd41 + coreR := scaleDPF(dpi, 4.8) + haloR := scaleDPF(dpi, 7.6) + haloPeak := 0.14 + + cx := float64(center.X) + cy := float64(center.Y) + rad := int(math.Ceil(haloR)) + 1 + x0 := max(0, int(math.Floor(cx))-rad) + y0 := max(0, int(math.Floor(cy))-rad) + x1 := min(int(s.w), int(math.Ceil(cx))+rad) + y1 := min(int(s.h), int(math.Ceil(cy))+rad) + + ax, ay := cx-scaleDPF(dpi, 2.2), cy+scaleDPF(dpi, 0.1) + bx, by := cx-scaleDPF(dpi, 0.5), cy+scaleDPF(dpi, 1.8) + tx, ty := cx+scaleDPF(dpi, 2.4), cy-scaleDPF(dpi, 1.6) + stroke := scaleDPF(dpi, 0.65) + + for y := y0; y < y1; y++ { + fy := float64(y) + 0.5 + for x := x0; x < x1; x++ { + fx := float64(x) + 0.5 + dist := math.Hypot(fx-cx, fy-cy) + if dist < haloR { + ht := clamp01(1.0 - dist/haloR) + s.blendPixel(x, y, col, haloPeak*ht*ht) + } + coreCov := clamp01(0.5 - (dist - coreR)) + if coreCov > 0.001 { + s.blendPixel(x, y, col, coreCov) + d1 := segmentSDF(fx, fy, ax, ay, bx, by) - stroke + d2 := segmentSDF(fx, fy, bx, by, tx, ty) - stroke + chkCov := clamp01(0.5 - math.Min(d1, d2)) + if chkCov > 0.001 { + s.blendPixel(x, y, rgba{255, 255, 255}, chkCov*coreCov) + } + } + } + } +} + +func (s *dibSurface) paintCloseIcon(cx, cy float64, dpi int32, col rgba, alpha float64) { + if alpha <= 0.005 { + return + } + half := scaleDPF(dpi, 3.4) + stroke := scaleDPF(dpi, 0.78) + bound := int(math.Ceil(half+stroke)) + 2 + x0 := max(0, int(math.Floor(cx))-bound) + y0 := max(0, int(math.Floor(cy))-bound) + x1 := min(int(s.w), int(math.Ceil(cx))+bound) + y1 := min(int(s.h), int(math.Ceil(cy))+bound) + for y := y0; y < y1; y++ { + fy := float64(y) + 0.5 + for x := x0; x < x1; x++ { + fx := float64(x) + 0.5 + d1 := segmentSDF(fx, fy, cx-half, cy-half, cx+half, cy+half) - stroke + d2 := segmentSDF(fx, fy, cx+half, cy-half, cx-half, cy+half) - stroke + cov := clamp01(0.5 - math.Min(d1, d2)) + if cov > 0.001 { + s.blendPixel(x, y, col, cov*alpha) + } + } + } +} + +func (s *dibSurface) paintStopIcon(cx, cy float64, dpi int32, col rgba, alpha float64) { + if alpha <= 0.005 { + return + } + half := scaleDPF(dpi, 3.8) + rad := scaleDPF(dpi, 1.7) + bound := int(math.Ceil(half)) + 2 + x0 := max(0, int(math.Floor(cx))-bound) + y0 := max(0, int(math.Floor(cy))-bound) + x1 := min(int(s.w), int(math.Ceil(cx))+bound) + y1 := min(int(s.h), int(math.Ceil(cy))+bound) + for y := y0; y < y1; y++ { + fy := float64(y) + 0.5 + for x := x0; x < x1; x++ { + fx := float64(x) + 0.5 + d := roundedBoxSDF(fx, fy, cx, cy, half, half, rad) + cov := clamp01(0.5 - d) + if cov > 0.001 { + s.blendPixel(x, y, col, cov*alpha) + } + } + } +} + +func (s *dibSurface) paintLockIcon(cx, cy float64, dpi int32, col rgba, alpha float64) { + if alpha <= 0.005 { + return + } + bodyHW := scaleDPF(dpi, 4.0) + bodyHH := scaleDPF(dpi, 3.0) + bodyCY := cy + scaleDPF(dpi, 1.8) + bodyR := scaleDPF(dpi, 1.2) + + shackleR := scaleDPF(dpi, 2.5) + shackleCY := bodyCY - bodyHH - scaleDPF(dpi, 0.2) + strokeHalf := scaleDPF(dpi, 0.65) + + bound := int(math.Ceil(scaleDPF(dpi, 7))) + 2 + x0 := max(0, int(math.Floor(cx))-bound) + y0 := max(0, int(math.Floor(cy))-bound) + x1 := min(int(s.w), int(math.Ceil(cx))+bound) + y1 := min(int(s.h), int(math.Ceil(cy))+bound) + for y := y0; y < y1; y++ { + fy := float64(y) + 0.5 + for x := x0; x < x1; x++ { + fx := float64(x) + 0.5 + dBody := roundedBoxSDF(fx, fy, cx, bodyCY, bodyHW, bodyHH, bodyR) + // Shackle: upper semicircle + short vertical legs into lock body. + var dShackle float64 + if fy <= shackleCY { + dShackle = math.Abs(math.Hypot(fx-cx, fy-shackleCY)-shackleR) - strokeHalf + } else { + dL := segmentSDF(fx, fy, cx-shackleR, shackleCY, cx-shackleR, bodyCY-bodyHH+0.5) - strokeHalf + dR := segmentSDF(fx, fy, cx+shackleR, shackleCY, cx+shackleR, bodyCY-bodyHH+0.5) - strokeHalf + dShackle = math.Min(dL, dR) + } + cov := clamp01(0.5 - math.Min(dBody, dShackle)) + if cov > 0.001 { + s.blendPixel(x, y, col, cov*alpha) + } + } + } +} + +func (s *dibSurface) paintFoldIcon(cx, cy float64, dpi int32, col rgba, alpha float64) { + if alpha <= 0.005 { + return + } + halfW := scaleDPF(dpi, 3.8) + halfH := scaleDPF(dpi, 2.0) + stroke := scaleDPF(dpi, 0.85) + topY := cy - halfH + botY := cy + halfH + + bound := int(math.Ceil(halfW+stroke)) + 2 + x0 := max(0, int(math.Floor(cx))-bound) + y0 := max(0, int(math.Floor(cy))-bound) + x1 := min(int(s.w), int(math.Ceil(cx))+bound) + y1 := min(int(s.h), int(math.Ceil(cy))+bound) + for y := y0; y < y1; y++ { + fy := float64(y) + 0.5 + for x := x0; x < x1; x++ { + fx := float64(x) + 0.5 + d1 := segmentSDF(fx, fy, cx-halfW, botY, cx, topY) - stroke + d2 := segmentSDF(fx, fy, cx, topY, cx+halfW, botY) - stroke + cov := clamp01(0.5 - math.Min(d1, d2)) + if cov > 0.001 { + s.blendPixel(x, y, col, cov*alpha) + } + } + } +} + +func measureLineWidthDC(dc, font uintptr, text string) int32 { + if text == "" || dc == 0 || font == 0 { + return 0 + } + old, _, _ := procSelectObject.Call(dc, font) + defer procSelectObject.Call(dc, old) + u16 := utf16.Encode([]rune(text)) + if len(u16) == 0 { + return 0 + } + var sz gdiSize + var fit int32 + _, _, _ = procGetTextExtentExPointW.Call( + dc, + uintptr(unsafe.Pointer(&u16[0])), + uintptr(len(u16)), + 0x7fffffff, + uintptr(unsafe.Pointer(&fit)), + 0, + uintptr(unsafe.Pointer(&sz)), + ) + return sz.cx +} + +func isASCIIWordU16(u uint16) bool { + return (u >= 'a' && u <= 'z') || (u >= 'A' && u <= 'Z') || (u >= '0' && u <= '9') || u == '_' || u == '\'' +} + +func isClosingPunctU16(u uint16) bool { + switch u { + case '.', ',', ';', ':', '?', '!', ')', ']', '}', + '。', ',', '、', ';', ':', '?', '!', ')', '」', '』', '》', '”', '…': + return true + } + return false +} + +func wrapStatusLines(dc, font uintptr, text string, maxW int32, maxLines int) []string { + text = strings.TrimSpace(text) + if text == "" || maxW <= 0 || dc == 0 || font == 0 { + return nil + } + old, _, _ := procSelectObject.Call(dc, font) + defer procSelectObject.Call(dc, old) + + var out []string + for _, para := range strings.Split(text, "\n") { + u16 := utf16.Encode([]rune(strings.TrimSpace(para))) + if len(u16) == 0 { + continue + } + for len(u16) > 0 { + var fit int32 + var sz gdiSize + _, _, _ = procGetTextExtentExPointW.Call( + dc, + uintptr(unsafe.Pointer(&u16[0])), + uintptr(len(u16)), + uintptr(maxW), + uintptr(unsafe.Pointer(&fit)), + 0, + uintptr(unsafe.Pointer(&sz)), + ) + if int(fit) >= len(u16) { + out = append(out, string(utf16.Decode(u16))) + break + } + cut := max(1, int(fit)) + if cut < len(u16) && u16[cut-1] >= 0xD800 && u16[cut-1] <= 0xDBFF { + if cut > 1 { + cut-- + } else { + cut++ + } + } + if cut < len(u16) && u16[cut] != ' ' { + if (isASCIIWordU16(u16[cut-1]) && isASCIIWordU16(u16[cut])) || + (isClosingPunctU16(u16[cut]) && isASCIIWordU16(u16[cut-1])) { + for i := cut - 1; i > 0; i-- { + c := u16[i] + if c == ' ' { + cut = i + break + } + if c == '/' || c == '\\' || c == '-' || c == '·' || c > 0x7f { + cut = i + 1 + break + } + } + } else if cut > 1 && isClosingPunctU16(u16[cut]) { + cut-- + } + } + if maxLines > 0 && len(out)+1 >= maxLines { + // Last allowed line: keep full remainder so DrawTextW with DT_END_ELLIPSIS truncates accurately. + out = append(out, string(utf16.Decode(u16))) + return out + } + out = append(out, strings.TrimRight(string(utf16.Decode(u16[:cut])), " ")) + u16 = u16[cut:] + for len(u16) > 0 && u16[0] == ' ' { + u16 = u16[1:] + } + } + } + return out +} + +// drawAlphaText renders anti-aliased text via the grayscale scratch DIB and +// composites it onto the premultiplied BGRA target canvas with accurate alpha. +func (s *dibSurface) drawAlphaText(scratch *dibSurface, screenDC, font uintptr, text string, dst rect2i, flags uintptr, col rgba, alpha float64) { + if text == "" || alpha <= 0.005 || dst.width() <= 0 || dst.height() <= 0 || font == 0 { + return + } + w := dst.width() + h := dst.height() + if !scratch.ensure(screenDC, max(scratch.w, w), max(scratch.h, h)) { + return + } + // Clear only the exact sub-rect we are about to draw into. + sw := int(scratch.w) + for row := 0; row < int(h); row++ { + off := row * sw * 4 + clear(scratch.bits[off : off+int(w)*4]) + } + + oldFont, _, _ := procSelectObject.Call(scratch.hdc, font) + _, _, _ = procSetBkMode.Call(scratch.hdc, transparent) + _, _, _ = procSetTextColor.Call(scratch.hdc, rgb(255, 255, 255)) + localRect := winRect{Left: 0, Top: 0, Right: w, Bottom: h} + drawWinText(scratch.hdc, text, &localRect, flags|dtNoPrefix) + _, _, _ = procSelectObject.Call(scratch.hdc, oldFont) + _, _, _ = procGdiFlush.Call() + + for row := 0; row < int(h); row++ { + dy := int(dst.Top) + row + if dy < 0 || dy >= int(s.h) { + continue + } + srcRowOff := row * sw * 4 + for colX := 0; colX < int(w); colX++ { + dx := int(dst.Left) + colX + if dx < 0 || dx >= int(s.w) { + continue + } + // Grayscale AA writes identical luminance to R/G/B on black background. + lum := scratch.bits[srcRowOff+colX*4+2] + if lum == 0 { + continue + } + // Slight stem-weight lift (gamma 0.86) improves crispness of light glyphs on dark glass. + cov := math.Pow(float64(lum)/255.0, 0.86) + s.blendPixel(dx, dy, col, cov*alpha) + } + } +} + +type renderParams struct { + state State + layout islandLayout + statusLines []string + fonts islandFontSet + dw *dwriteEngine + hoverZone hitZone + pressedZone hitZone + breath float64 + pulse float64 + baseCache *islandBaseCache +} + +func shiftRect(r rect2i, dx, dy int32) rect2i { + return rect2i{Left: r.Left + dx, Top: r.Top + dy, Right: r.Right + dx, Bottom: r.Bottom + dy} +} + +type pillVisual struct { + topFill rgba + botFill rgba + fillA float64 + border rgba + borderA float64 + fg rgba + topHi float64 +} + +func buttonStyle(kind string, hovered, pressed bool) pillVisual { + switch kind { + case "resume": + // Crisp macOS Tahoe Apple System Blue primary CTA (--accent #007aff). + v := pillVisual{ + topFill: rgba{10, 130, 255}, + botFill: rgba{0, 114, 240}, + fillA: 1.0, + border: rgba{0, 94, 196}, + borderA: 0.18, + fg: rgba{255, 255, 255}, + topHi: 0.14, + } + if pressed { + v.topFill = rgba{0, 96, 204} + v.botFill = rgba{0, 88, 192} + v.borderA = 0.22 + v.topHi = 0.02 + } else if hovered { + v.topFill = rgba{0, 116, 245} + v.botFill = rgba{0, 102, 224} + v.borderA = 0.22 + v.topHi = 0.16 + } + return v + case "pause", "close": + // Lightweight borderless tonal macOS secondary button (#F2F3F7). + v := pillVisual{ + topFill: rgba{244, 245, 248}, + botFill: rgba{239, 241, 245}, + fillA: 1.0, + border: rgba{15, 23, 42}, + borderA: 0.055, + fg: rgba{29, 29, 31}, // --text #1d1d1f + topHi: 0, + } + if pressed { + v.topFill = rgba{223, 226, 234} + v.botFill = rgba{220, 223, 232} + v.borderA = 0.09 + v.fg = rgba{17, 17, 19} + } else if hovered { + v.topFill = rgba{235, 237, 242} + v.botFill = rgba{231, 234, 240} + v.borderA = 0.08 + v.fg = rgba{17, 17, 19} + } + return v + default: // stop + // Soft macOS light-mode crimson-tinted pill (--danger-soft / --danger-text). + v := pillVisual{ + topFill: rgba{255, 241, 240}, + botFill: rgba{255, 235, 234}, + fillA: 1.0, + border: rgba{215, 0, 21}, + borderA: 0.08, + fg: rgba{215, 0, 21}, // --danger-text #d70015 + topHi: 0, + } + if pressed { + v.topFill = rgba{224, 45, 34} + v.botFill = rgba{208, 34, 24} + v.border = rgba{184, 20, 14} + v.borderA = 0.24 + v.fg = rgba{255, 255, 255} + v.topHi = 0.06 + } else if hovered { + v.topFill = rgba{255, 229, 227} + v.botFill = rgba{255, 222, 220} + v.border = rgba{215, 0, 21} + v.borderA = 0.18 + v.fg = rgba{194, 0, 18} + } + return v + } +} + +type textDrawItem struct { + style textStyle + text string + dst rect2i + align uint32 + maxLines int + col rgba + alpha float64 + gdiFont uintptr + gdiFlags uintptr +} + +type islandBaseCacheKey struct { + state State + layout islandLayout + hoverZone hitZone + pressedZone hitZone + pulse float64 +} + +type islandBaseCache struct { + surface dibSurface + key islandBaseCacheKey + valid bool +} + +func (c *islandBaseCache) release() { + c.surface.release() + c.valid = false +} + +func islandBaseCacheKeyFor(p renderParams) islandBaseCacheKey { + st := p.state + st.PID = 0 + pulse := p.pulse + if pulse <= 0.005 { + pulse = 0 + } + return islandBaseCacheKey{ + state: st, + layout: p.layout, + hoverZone: p.hoverZone, + pressedZone: p.pressedZone, + pulse: pulse, + } +} + +func renderIslandFrame(canvas, scratch *dibSurface, screenDC uintptr, p renderParams) bool { + l := p.layout + if !canvas.ensure(screenDC, l.CanvasW, l.CanvasH) { + return false + } + if cache := p.baseCache; cache != nil { + key := islandBaseCacheKeyFor(p) + if !cache.valid || cache.key != key || cache.surface.w != l.CanvasW || cache.surface.h != l.CanvasH || len(cache.surface.bits) != len(canvas.bits) { + if !renderIslandStaticBase(&cache.surface, scratch, screenDC, p) { + cache.valid = false + return false + } + cache.key = key + cache.valid = true + } + copy(canvas.bits, cache.surface.bits) + } else if !renderIslandStaticBase(canvas, scratch, screenDC, p) { + return false + } + + // Paint the breathing/completed status dot on top of the cached static base so + // breathing ticks avoid recomputing the SDF shadow/shell and DirectWrite text. + dotPos := point2i{X: l.PadX + l.DotCenter.X, Y: l.PadTop + l.DotCenter.Y} + if p.state.Completed { + canvas.paintCompletedDot(dotPos, l.DPI) + } else { + canvas.paintStatusDot(dotPos, l.DPI, p.state.CanResume, p.breath) + } + return true +} + +func renderIslandStaticBase(canvas, scratch *dibSurface, screenDC uintptr, p renderParams) bool { + l := p.layout + if !canvas.ensure(screenDC, l.CanvasW, l.CanvasH) { + return false + } + canvas.clear() + + // 1. Opaque matte-obsidian shell, floating elevation shadow, crisp rim & pulse. + canvas.paintIslandShell(l, p.state.CanResume, p.pulse) + + ox := l.PadX + oy := l.PadTop + script := scriptForState(p.state) + + var textQueue []textDrawItem + measureTextW := func(style textStyle, gdiFont uintptr, s string) int32 { + if p.dw != nil { + if w, ok := p.dw.measureLineWidth(l.DPI, script, style, s); ok && w > 0 { + return w + } + } + if w := measureLineWidthDC(scratch.hdc, gdiFont, s); w > 0 { + return w + } + return measureLineWidthDC(screenDC, gdiFont, s) + } + + // 3. Compact pill elements (fades out cleanly during first 35% of expand). + if l.CompactAlpha > 0.01 { + a := l.CompactAlpha + if p.state.InputLocked && l.CompactLockRect.width() > 0 { + lr := shiftRect(l.CompactLockRect, ox, oy) + canvas.paintLockIcon(float64(lr.Left+lr.Right)*0.5, float64(lr.Top+lr.Bottom)*0.5, l.DPI, rgba{110, 110, 115}, 0.88*a) + } + tr := shiftRect(l.CompactTitleRect, ox, oy) + titleCol := rgba{29, 29, 31} + if p.hoverZone == zoneInfo { + titleCol = rgba{0, 0, 0} + } + textQueue = append(textQueue, textDrawItem{ + style: styleCompact, text: compactPrimaryText(p.state), dst: tr, + align: dwAlignLeading, maxLines: 1, col: titleCol, alpha: 0.98 * a, + gdiFont: p.fonts.compactTitle, gdiFlags: dtLeft | dtVCenter | dtSingleLine | dtEndEllipsis, + }) + + if l.HasToggle { + kind := "pause" + if p.state.CanResume { + kind = "resume" + } + btnR := shiftRect(l.CompactToggleBtn, ox, oy) + st := buttonStyle(kind, p.hoverZone == zoneToggle, p.pressedZone == zoneToggle) + canvas.paintTactilePill(btnR, float64(btnR.height())*0.5, st.topFill, st.botFill, st.fillA*a, st.border, st.borderA*a, st.topHi*a) + bcx := float64(btnR.Left+btnR.Right) * 0.5 + bcy := float64(btnR.Top+btnR.Bottom) * 0.5 + if p.state.CanResume { + canvas.paintPlayIcon(bcx, bcy, l.DPI, st.fg, a) + } else { + canvas.paintPauseIcon(bcx, bcy, l.DPI, st.fg, a) + } + } + + stopR := shiftRect(l.CompactStopBtn, ox, oy) + stopKind := "stop" + if p.state.Completed { + stopKind = "close" + } + st := buttonStyle(stopKind, p.hoverZone == zoneStop, p.pressedZone == zoneStop) + canvas.paintTactilePill(stopR, float64(stopR.height())*0.5, st.topFill, st.botFill, st.fillA*a, st.border, st.borderA*a, st.topHi*a) + if p.state.Completed { + canvas.paintCloseIcon(float64(stopR.Left+stopR.Right)*0.5, float64(stopR.Top+stopR.Bottom)*0.5, l.DPI, st.fg, a) + } else { + canvas.paintStopIcon(float64(stopR.Left+stopR.Right)*0.5, float64(stopR.Top+stopR.Bottom)*0.5, l.DPI, st.fg, a) + } + } + + // 4. Expanded light macOS card elements (fades in smoothly during 42..100%). + if l.ExpandedAlpha > 0.01 { + a := l.ExpandedAlpha + + // Row 1: Subtle Apple grey session meta label + borderless lock glyph + ghost fold button. + titleR := shiftRect(l.ExpandedTitleRect, ox, oy) + textQueue = append(textQueue, textDrawItem{ + style: styleMeta, text: p.state.Title, dst: titleR, + align: dwAlignLeading, maxLines: 1, col: rgba{110, 110, 115}, alpha: 0.96 * a, + gdiFont: p.fonts.status, gdiFlags: dtLeft | dtVCenter | dtSingleLine | dtEndEllipsis, + }) + + if p.state.InputLocked && l.ExpandedLockBadge.width() > 0 { + badgeR := shiftRect(l.ExpandedLockBadge, ox, oy) + lockCol := rgba{142, 142, 147} + lockA := 0.90 * a + if p.pulse > 0.05 { + lockCol = rgba{217, 119, 6} + lockA = a + } + canvas.paintLockIcon(float64(badgeR.Left+badgeR.Right)*0.5, float64(badgeR.Top+badgeR.Bottom)*0.5, l.DPI, lockCol, lockA) + } + + if l.ExpandedFoldBtn.width() > 0 { + foldR := shiftRect(l.ExpandedFoldBtn, ox, oy) + iconCol := rgba{110, 110, 115} + if p.pressedZone == zoneFold { + canvas.paintTactilePill(foldR, float64(foldR.height())*0.5, rgba{228, 231, 238}, rgba{224, 227, 235}, a, rgba{15, 23, 42}, 0.06*a, 0) + iconCol = rgba{29, 29, 31} + } else if p.hoverZone == zoneFold { + canvas.paintTactilePill(foldR, float64(foldR.height())*0.5, rgba{240, 242, 246}, rgba{236, 238, 243}, a, rgba{15, 23, 42}, 0.04*a, 0) + iconCol = rgba{29, 29, 31} + } + canvas.paintFoldIcon(float64(foldR.Left+foldR.Right)*0.5, float64(foldR.Top+foldR.Bottom)*0.5, l.DPI, iconCol, a) + } + + // Row 2: Crisp Apple Ink Hero Step headline (#1D1D1F). + if l.HasStep && l.ExpandedStepRect.width() > 0 { + stepR := shiftRect(l.ExpandedStepRect, ox, oy) + textQueue = append(textQueue, textDrawItem{ + style: styleHero, text: p.state.StepText, dst: stepR, + align: dwAlignLeading, maxLines: 1, col: rgba{29, 29, 31}, alpha: 0.99 * a, + gdiFont: p.fonts.title, gdiFlags: dtLeft | dtVCenter | dtSingleLine | dtEndEllipsis, + }) + } + + // Row 3: Clean Apple Secondary Grey detail (up to 2 lines). + if l.HasStatus && strings.TrimSpace(p.state.StatusLine) != "" { + statusBase := shiftRect(l.ExpandedStatusRect, ox, oy) + if p.dw != nil && p.dw.ensureInit() { + textQueue = append(textQueue, textDrawItem{ + style: styleStatus, text: strings.TrimSpace(p.state.StatusLine), dst: statusBase, + align: dwAlignLeading, maxLines: 2, col: rgba{110, 110, 115}, alpha: 0.96 * a, + gdiFont: p.fonts.status, gdiFlags: dtLeft | dtVCenter | dtSingleLine | dtEndEllipsis, + }) + } else { + lineH := scaleDP(l.DPI, 18) + for idx, line := range p.statusLines { + if idx >= 2 { + break + } + lr := rect2i{ + Left: statusBase.Left, + Top: statusBase.Top + int32(idx)*lineH, + Right: statusBase.Right, + Bottom: statusBase.Top + int32(idx+1)*lineH, + } + textQueue = append(textQueue, textDrawItem{ + style: styleStatus, text: line, dst: lr, + align: dwAlignLeading, maxLines: 1, col: rgba{110, 110, 115}, alpha: 0.96 * a, + gdiFont: p.fonts.status, gdiFlags: dtLeft | dtVCenter | dtSingleLine | dtEndEllipsis, + }) + } + } + } + + // Row 4: Concentric solid matte action buttons (icon + label). + if l.HasToggle { + kind := "pause" + label := p.state.PauseLabel + if p.state.CanResume { + kind = "resume" + label = p.state.ResumeLabel + } + btnR := shiftRect(l.ExpandedToggleBtn, ox, oy) + if item, ok := paintExpandedActionButton(canvas, btnR, kind, label, p.fonts.btn, l.DPI, p.hoverZone == zoneToggle, p.pressedZone == zoneToggle, a, measureTextW); ok { + textQueue = append(textQueue, item) + } + } + stopR := shiftRect(l.ExpandedStopBtn, ox, oy) + stopKind := "stop" + stopLabel := p.state.StopLabel + if p.state.Completed { + stopKind = "close" + stopLabel = p.state.CloseLabel + } + if item, ok := paintExpandedActionButton(canvas, stopR, stopKind, stopLabel, p.fonts.btn, l.DPI, p.hoverZone == zoneStop, p.pressedZone == zoneStop, a, measureTextW); ok { + textQueue = append(textQueue, item) + } + } + + // 5. Render all queued text through Direct2D + DirectWrite in one crisp pass + // (automatically falling back to grayscale GDI DIB compositing if unavailable). + usedDWrite := false + if p.dw != nil && len(textQueue) > 0 && p.dw.beginSurface(canvas) { + usedDWrite = true + for _, it := range textQueue { + if !p.dw.drawText(l.DPI, script, it.style, it.text, it.dst, it.align, it.maxLines, it.col, it.alpha) { + usedDWrite = false + break + } + } + if !p.dw.endSurface() { + usedDWrite = false + } + } + if !usedDWrite { + for _, it := range textQueue { + canvas.drawAlphaText(scratch, screenDC, it.gdiFont, it.text, it.dst, it.gdiFlags, it.col, it.alpha) + } + } + + return true +} + +func paintExpandedActionButton( + canvas *dibSurface, + btnR rect2i, + kind, label string, + gdiFont uintptr, + dpi int32, + hovered, pressed bool, + alpha float64, + measureW func(textStyle, uintptr, string) int32, +) (textDrawItem, bool) { + st := buttonStyle(kind, hovered, pressed) + btnRadius := scaleDPF(dpi, 8) + canvas.paintTactilePill(btnR, btnRadius, st.topFill, st.botFill, st.fillA*alpha, st.border, st.borderA*alpha, st.topHi*alpha) + + iconW := scaleDP(dpi, 10) + gap := scaleDP(dpi, 7) + textW := measureW(styleBtn, gdiFont, label) + maxTextW := max(int32(0), btnR.width()-scaleDP(dpi, 20)-iconW-gap) + if textW > maxTextW { + textW = maxTextW + } + groupW := iconW + gap + textW + startX := btnR.Left + (btnR.width()-groupW)/2 + midY := float64(btnR.Top+btnR.Bottom) * 0.5 + iconCX := float64(startX) + float64(iconW)*0.5 + + switch kind { + case "resume": + canvas.paintPlayIcon(iconCX, midY, dpi, st.fg, alpha) + case "pause": + canvas.paintPauseIcon(iconCX, midY, dpi, st.fg, alpha) + case "close": + canvas.paintCloseIcon(iconCX, midY, dpi, st.fg, alpha) + default: + canvas.paintStopIcon(iconCX, midY, dpi, st.fg, alpha) + } + + textR := rect2i{ + Left: startX + iconW + gap, + Top: btnR.Top, + Right: min(btnR.Right-scaleDP(dpi, 8), startX+iconW+gap+textW+scaleDP(dpi, 6)), + Bottom: btnR.Bottom, + } + return textDrawItem{ + style: styleBtn, text: label, dst: textR, + align: dwAlignLeading, maxLines: 1, col: st.fg, alpha: alpha, + gdiFont: gdiFont, gdiFlags: dtLeft | dtVCenter | dtSingleLine | dtEndEllipsis, + }, true +} diff --git a/internal/host/takeover.go b/internal/host/takeover.go new file mode 100644 index 0000000..f1abb82 --- /dev/null +++ b/internal/host/takeover.go @@ -0,0 +1,376 @@ +package host + +import ( + "log" + "sync" + "sync/atomic" + "time" +) + +// DefaultTakeoverMoveThresholdPx is the minimum cursor displacement inside a +// VM window client area before pure mouse movement triggers user takeover. +// Keyboard presses, mouse clicks, and scroll wheel events trigger immediately. +const DefaultTakeoverMoveThresholdPx = 24 + +const ( + takeoverWMKeyDown = 0x0100 + takeoverWMSysKeyDown = 0x0104 + takeoverWMLButtonDown = 0x0201 + takeoverWMLButtonUp = 0x0202 + takeoverWMRButtonDown = 0x0204 + takeoverWMRButtonUp = 0x0205 + takeoverWMMButtonDown = 0x0207 + takeoverWMMButtonUp = 0x0208 + takeoverWMMouseWheel = 0x020A + takeoverWMXButtonDown = 0x020B + takeoverWMXButtonUp = 0x020C + takeoverWMMouseHWheel = 0x020E + + takeoverVKTab = 0x09 + takeoverVKMenu = 0x12 + takeoverVKEscape = 0x1B + takeoverVKLWin = 0x5B + takeoverVKRWin = 0x5C + takeoverVKLMenu = 0xA4 + takeoverVKRMenu = 0xA5 + takeoverLLKHFLowerInj = 0x00000002 + takeoverLLKHFInjected = 0x00000010 + takeoverLLKHFAlt = 0x00000020 +) + +// TakeoverTarget configures how TakeoverMonitor treats host input for one VM PID. +// When LockInput is false, physical host input passes through and triggers onTakeover. +// When LockInput is true, physical host input aimed at the VM is swallowed while +// Windows host escape shortcuts (Alt+Tab, Alt+Esc, Win) and key-ups remain free. +type TakeoverTarget struct { + VMKey string + LockInput bool +} + +type moveAnchor struct { + vmKey string + x, y int32 + at time.Time +} + +// TakeoverMonitor watches physical host keyboard and mouse activity over +// targeted VM windows and either notifies onTakeover or locks out interfering +// input depending on each target's LockInput setting. +type TakeoverMonitor struct { + onTakeover func(vmKey, reason string) + onHookErr func(err error) + threshold int32 + + targets atomic.Pointer[map[uint32]TakeoverTarget] + + anchorMu sync.Mutex + anchor moveAnchor + + swallowedMouseBtns atomic.Uint32 + + mu sync.Mutex + hookMu sync.Mutex + started bool + closed bool + hookGen uint64 + stopHook func() + startFn func(onExit func()) (func(), error) +} + +// NewTakeoverMonitor creates a takeover monitor. Platform hooks start lazily +// when SetTargets or SetTargetRules receives at least one PID. +func NewTakeoverMonitor(onTakeover func(vmKey, reason string)) *TakeoverMonitor { + return &TakeoverMonitor{ + onTakeover: onTakeover, + threshold: DefaultTakeoverMoveThresholdPx, + } +} + +// SetOnHookError registers an optional callback invoked when platform input +// hooks fail to install or exit unexpectedly. +func (m *TakeoverMonitor) SetOnHookError(fn func(error)) { + if m == nil { + return + } + m.mu.Lock() + m.onHookErr = fn + m.mu.Unlock() +} + +func (m *TakeoverMonitor) reportHookError(err error) { + if err == nil { + return + } + m.mu.Lock() + cb := m.onHookErr + m.mu.Unlock() + if cb != nil { + cb(err) + return + } + log.Printf("takeover monitor: %v", err) +} + +func (m *TakeoverMonitor) onPlatformHookExit(gen uint64) { + m.mu.Lock() + if !m.closed && m.started && m.hookGen == gen { + m.started = false + m.stopHook = nil + } + m.mu.Unlock() +} + +// SetTargets replaces the set of monitored VM PID -> vmKey mappings using the +// default pass-through physical takeover mode (LockInput=false). +func (m *TakeoverMonitor) SetTargets(pidToVM map[uint32]string) { + rules := make(map[uint32]TakeoverTarget, len(pidToVM)) + for pid, key := range pidToVM { + if pid > 0 && key != "" { + rules[pid] = TakeoverTarget{VMKey: key} + } + } + m.SetTargetRules(rules) +} + +// SetTargetRules replaces the set of monitored VM PID rules atomically. +func (m *TakeoverMonitor) SetTargetRules(pidToTarget map[uint32]TakeoverTarget) { + if m == nil { + return + } + cp := make(map[uint32]TakeoverTarget, len(pidToTarget)) + for pid, target := range pidToTarget { + if pid > 0 && target.VMKey != "" { + cp[pid] = target + } + } + m.targets.Store(&cp) + + m.hookMu.Lock() + defer m.hookMu.Unlock() + + m.mu.Lock() + if m.closed { + m.mu.Unlock() + return + } + if len(cp) == 0 { + m.swallowedMouseBtns.Store(0) + stop := m.stopHook + m.stopHook = nil + m.started = false + m.mu.Unlock() + if stop != nil { + stop() + } + return + } + if !m.started { + m.started = true + m.hookGen++ + gen := m.hookGen + startFn := m.startFn + m.mu.Unlock() + if startFn == nil { + startFn = m.startPlatformHooks + } + stop, err := startFn(func() { m.onPlatformHookExit(gen) }) + if err != nil { + m.mu.Lock() + if m.hookGen == gen { + m.started = false + m.stopHook = nil + } + m.mu.Unlock() + m.reportHookError(err) + return + } + m.mu.Lock() + if m.closed || m.hookGen != gen { + if m.hookGen == gen { + m.started = false + } + m.mu.Unlock() + if stop != nil { + stop() + } + return + } + m.stopHook = stop + } + m.mu.Unlock() +} + +// Close tears down any active platform hooks. +func (m *TakeoverMonitor) Close() { + if m == nil { + return + } + m.hookMu.Lock() + defer m.hookMu.Unlock() + + m.mu.Lock() + if m.closed { + m.mu.Unlock() + return + } + m.closed = true + m.swallowedMouseBtns.Store(0) + stop := m.stopHook + m.stopHook = nil + m.started = false + m.mu.Unlock() + empty := map[uint32]TakeoverTarget{} + m.targets.Store(&empty) + if stop != nil { + stop() + } +} + +// shouldSwallowLockedKey returns true if a physical low-level keyboard event +// directed at an input-locked VM window must be blocked from reaching the VM. +// Host-injected events, key-up events, Alt modifier keys, Alt+Tab, Alt+Esc, +// and Windows keys are always passed through so host injection continues to +// work, the user is never trapped, and keys never stick. +func shouldSwallowLockedKey(wParam uintptr, vkCode, flags uint32) bool { + if (flags & (takeoverLLKHFInjected | takeoverLLKHFLowerInj)) != 0 { + return false + } + if wParam != takeoverWMKeyDown && wParam != takeoverWMSysKeyDown { + return false + } + switch vkCode { + case takeoverVKLWin, takeoverVKRWin, takeoverVKMenu, takeoverVKLMenu, takeoverVKRMenu: + return false + case takeoverVKTab, takeoverVKEscape: + if (flags & takeoverLLKHFAlt) != 0 { + return false + } + } + return true +} + +const ( + swallowedBtnLeft uint32 = 1 << iota + swallowedBtnRight + swallowedBtnMiddle + swallowedBtnX1 + swallowedBtnX2 +) + +func lockedMouseButtonBit(wParam uintptr, mouseData uint32) (bit uint32, isDown, isUp bool) { + switch wParam { + case takeoverWMLButtonDown: + return swallowedBtnLeft, true, false + case takeoverWMLButtonUp: + return swallowedBtnLeft, false, true + case takeoverWMRButtonDown: + return swallowedBtnRight, true, false + case takeoverWMRButtonUp: + return swallowedBtnRight, false, true + case takeoverWMMButtonDown: + return swallowedBtnMiddle, true, false + case takeoverWMMButtonUp: + return swallowedBtnMiddle, false, true + case takeoverWMXButtonDown: + if (mouseData >> 16) == 2 { + return swallowedBtnX2, true, false + } + return swallowedBtnX1, true, false + case takeoverWMXButtonUp: + if (mouseData >> 16) == 2 { + return swallowedBtnX2, false, true + } + return swallowedBtnX1, false, true + default: + return 0, false, false + } +} + +func (m *TakeoverMonitor) setSwallowedMouseBtn(bit uint32) { + for { + old := m.swallowedMouseBtns.Load() + if old&bit != 0 { + return + } + if m.swallowedMouseBtns.CompareAndSwap(old, old|bit) { + return + } + } +} + +func (m *TakeoverMonitor) clearSwallowedMouseBtn(bit uint32) bool { + for { + old := m.swallowedMouseBtns.Load() + if old&bit == 0 { + return false + } + if m.swallowedMouseBtns.CompareAndSwap(old, old&^bit) { + return true + } + } +} + +// handleLockedMouseEvent decides whether a low-level mouse event must be +// swallowed for an input-locked VM client area. Button-up events are swallowed +// ONLY when the matching button-down was swallowed by this monitor, so dragging +// from another Windows app into the locked VM and releasing never leaves the +// host app stuck in a pressed/dragging state. +func (m *TakeoverMonitor) handleLockedMouseEvent(wParam uintptr, mouseData uint32, insideLockedVM bool) bool { + bit, isDown, isUp := lockedMouseButtonBit(wParam, mouseData) + if !insideLockedVM { + if isUp && bit != 0 { + m.clearSwallowedMouseBtn(bit) + } + return false + } + if isDown && bit != 0 { + m.setSwallowedMouseBtn(bit) + return true + } + if isUp && bit != 0 { + return m.clearSwallowedMouseBtn(bit) + } + return wParam == takeoverWMMouseWheel || wParam == takeoverWMMouseHWheel +} + +func (m *TakeoverMonitor) emit(vmKey, reason string) { + if m == nil || vmKey == "" || m.onTakeover == nil { + return + } + go m.onTakeover(vmKey, reason) +} + +// evalMouseMove updates the per-VM cursor anchor and returns true once pointer +// displacement inside the VM client area reaches or exceeds the anti-jitter threshold. +func (m *TakeoverMonitor) evalMouseMove(vmKey string, x, y int32, now time.Time) bool { + if vmKey == "" { + m.anchorMu.Lock() + m.anchor = moveAnchor{} + m.anchorMu.Unlock() + return false + } + threshold := m.threshold + if threshold <= 0 { + threshold = DefaultTakeoverMoveThresholdPx + } + m.anchorMu.Lock() + defer m.anchorMu.Unlock() + if m.anchor.vmKey != vmKey || now.Sub(m.anchor.at) > 750*time.Millisecond { + m.anchor = moveAnchor{vmKey: vmKey, x: x, y: y, at: now} + return false + } + dx := x - m.anchor.x + if dx < 0 { + dx = -dx + } + dy := y - m.anchor.y + if dy < 0 { + dy = -dy + } + if dx+dy >= threshold { + m.anchor = moveAnchor{vmKey: vmKey, x: x, y: y, at: now} + return true + } + m.anchor.at = now + return false +} diff --git a/internal/host/takeover_other.go b/internal/host/takeover_other.go new file mode 100644 index 0000000..6f3a8ea --- /dev/null +++ b/internal/host/takeover_other.go @@ -0,0 +1,7 @@ +//go:build !windows + +package host + +func (m *TakeoverMonitor) startPlatformHooks(_ func()) (func(), error) { + return func() {}, nil +} diff --git a/internal/host/takeover_test.go b/internal/host/takeover_test.go new file mode 100644 index 0000000..10bc050 --- /dev/null +++ b/internal/host/takeover_test.go @@ -0,0 +1,179 @@ +package host + +import ( + "errors" + "testing" + "time" +) + +func TestTakeoverMonitorMouseMoveThreshold(t *testing.T) { + m := NewTakeoverMonitor(nil) + t0 := time.Date(2026, 12, 3, 12, 0, 0, 0, time.UTC) + + // First move establishes anchor; small jitter must not trigger takeover. + if m.evalMouseMove("macos:dev", 100, 100, t0) { + t.Fatal("first sample should only set anchor") + } + if m.evalMouseMove("macos:dev", 108, 106, t0.Add(50*time.Millisecond)) { + t.Fatal("14px jitter must not trigger takeover") + } + // Cumulative displacement reaching 24px triggers takeover. + if !m.evalMouseMove("macos:dev", 116, 110, t0.Add(100*time.Millisecond)) { + t.Fatal("26px displacement should trigger takeover") + } + // Anchor resets after triggering, so another 5px does not immediately refire. + if m.evalMouseMove("macos:dev", 119, 112, t0.Add(120*time.Millisecond)) { + t.Fatal("5px after reset should not refire") + } + // Leaving the client area clears the anchor. + if m.evalMouseMove("", 0, 0, t0.Add(150*time.Millisecond)) { + t.Fatal("leaving client area should not trigger takeover") + } + if m.evalMouseMove("macos:dev", 200, 200, t0.Add(180*time.Millisecond)) { + t.Fatal("re-entering client area should establish fresh anchor") + } +} + +func TestShouldSwallowLockedKey(t *testing.T) { + const ( + wmKeyUp = 0x0101 + wmSysKeyUp = 0x0105 + vkReturn = 0x0D + vkA = 0x41 + vkF4 = 0x73 + vkPacket = 0xE7 + ) + // Normal keys & IME VK_PACKET keydowns must be swallowed. + for _, tc := range []struct { + name string + wParam uintptr + vk uint32 + flags uint32 + want bool + }{ + {"letter down", takeoverWMKeyDown, vkA, 0, true}, + {"return down", takeoverWMKeyDown, vkReturn, 0, true}, + {"tab without alt", takeoverWMKeyDown, takeoverVKTab, 0, true}, + {"esc without alt", takeoverWMKeyDown, takeoverVKEscape, 0, true}, + {"alt+f4 blocked", takeoverWMSysKeyDown, vkF4, takeoverLLKHFAlt, true}, + {"vk_packet blocked", takeoverWMKeyDown, vkPacket, 0, true}, + // Host escape combos and all key-ups must pass through. + {"key up passes", wmKeyUp, vkA, 0, false}, + {"sys key up passes", wmSysKeyUp, takeoverVKTab, takeoverLLKHFAlt, false}, + {"alt key passes", takeoverWMSysKeyDown, takeoverVKLMenu, 0, false}, + {"alt+tab passes", takeoverWMSysKeyDown, takeoverVKTab, takeoverLLKHFAlt, false}, + {"alt+esc passes", takeoverWMSysKeyDown, takeoverVKEscape, takeoverLLKHFAlt, false}, + {"lwin passes", takeoverWMKeyDown, takeoverVKLWin, 0, false}, + {"rwin passes", takeoverWMKeyDown, takeoverVKRWin, 0, false}, + // Host-injected keyboard events (SendInput / lower-IL injection) pass through + // consistently with WH_MOUSE_LL's LLMHF_INJECTED filter. + {"injected letter passes", takeoverWMKeyDown, vkA, takeoverLLKHFInjected, false}, + {"lower-il injected passes", takeoverWMKeyDown, vkReturn, takeoverLLKHFLowerInj, false}, + } { + if got := shouldSwallowLockedKey(tc.wParam, tc.vk, tc.flags); got != tc.want { + t.Errorf("%s: shouldSwallowLockedKey(%#x, %#x, %#x) = %v, want %v", tc.name, tc.wParam, tc.vk, tc.flags, got, tc.want) + } + } +} + +func TestHandleLockedMouseEventPairsDownAndUp(t *testing.T) { + const wmMouseMove = 0x0200 + m := NewTakeoverMonitor(nil) + + if m.handleLockedMouseEvent(wmMouseMove, 0, true) { + t.Fatal("WM_MOUSEMOVE must not be swallowed in WH_MOUSE_LL so host cursor stays free") + } + // Wheel events over locked VM are swallowed. + for _, msg := range []uintptr{takeoverWMMouseWheel, takeoverWMMouseHWheel} { + if !m.handleLockedMouseEvent(msg, 0, true) { + t.Errorf("wheel message %#x should be swallowed while VM input is locked", msg) + } + } + // Dragging from another Windows app into a locked VM client area and + // releasing must NOT swallow ButtonUp (prevents sticky drag/pressed state). + for _, tc := range []struct { + name string + down, up uintptr + mouseData uint32 + }{ + {"left", takeoverWMLButtonDown, takeoverWMLButtonUp, 0}, + {"right", takeoverWMRButtonDown, takeoverWMRButtonUp, 0}, + {"middle", takeoverWMMButtonDown, takeoverWMMButtonUp, 0}, + {"x1", takeoverWMXButtonDown, takeoverWMXButtonUp, 1 << 16}, + {"x2", takeoverWMXButtonDown, takeoverWMXButtonUp, 2 << 16}, + } { + if m.handleLockedMouseEvent(tc.up, tc.mouseData, true) { + t.Errorf("%s: unpaired ButtonUp over locked VM must pass through to host app", tc.name) + } + // Clicking inside locked VM swallows both Down and matching Up. + if !m.handleLockedMouseEvent(tc.down, tc.mouseData, true) { + t.Errorf("%s: ButtonDown inside locked VM must be swallowed", tc.name) + } + if !m.handleLockedMouseEvent(tc.up, tc.mouseData, true) { + t.Errorf("%s: paired ButtonUp inside locked VM must be swallowed", tc.name) + } + // A second Up without a swallowed Down must pass through. + if m.handleLockedMouseEvent(tc.up, tc.mouseData, true) { + t.Errorf("%s: second ButtonUp without swallowed Down must pass through", tc.name) + } + // Down inside locked VM followed by Up outside clears state and passes through. + if !m.handleLockedMouseEvent(tc.down, tc.mouseData, true) { + t.Errorf("%s: ButtonDown inside locked VM must be swallowed", tc.name) + } + if m.handleLockedMouseEvent(tc.up, tc.mouseData, false) { + t.Errorf("%s: ButtonUp outside locked VM must pass through", tc.name) + } + if m.handleLockedMouseEvent(tc.up, tc.mouseData, true) { + t.Errorf("%s: stale ButtonUp bit must have been cleared after outside release", tc.name) + } + } +} + +func TestTakeoverMonitorRetriesOnHookFailureAndUnexpectedExit(t *testing.T) { + m := NewTakeoverMonitor(nil) + var reported []error + m.SetOnHookError(func(err error) { reported = append(reported, err) }) + + attempts := 0 + var exitFn func() + stopCalls := 0 + m.startFn = func(onExit func()) (func(), error) { + attempts++ + if attempts == 1 { + return nil, errors.New("SetWindowsHookExW failed") + } + exitFn = onExit + return func() { stopCalls++ }, nil + } + + rules := map[uint32]TakeoverTarget{1234: {VMKey: "macos:dev", LockInput: true}} + // First attempt fails -> started must reset to false and report error. + m.SetTargetRules(rules) + if len(reported) != 1 { + t.Fatalf("expected 1 reported hook error, got %d", len(reported)) + } + if m.started { + t.Fatal("started must be false after hook installation failure") + } + + // Second call retries and succeeds. + m.SetTargetRules(rules) + if attempts != 2 || !m.started { + t.Fatalf("expected retry attempt=2 and started=true, got attempts=%d started=%v", attempts, m.started) + } + + // Unexpected message-loop exit resets started so next SetTargetRules restarts hooks. + exitFn() + if m.started { + t.Fatal("started must reset to false after unexpected hook loop exit") + } + m.SetTargetRules(rules) + if attempts != 3 || !m.started { + t.Fatalf("expected restart attempt=3 after unexpected exit, got attempts=%d started=%v", attempts, m.started) + } + + m.Close() + if stopCalls != 1 { + t.Fatalf("expected active hook stopped on Close, got stopCalls=%d", stopCalls) + } +} diff --git a/internal/host/takeover_windows.go b/internal/host/takeover_windows.go new file mode 100644 index 0000000..6ca24e4 --- /dev/null +++ b/internal/host/takeover_windows.go @@ -0,0 +1,250 @@ +//go:build windows + +package host + +import ( + "fmt" + "runtime" + "sync" + "sync/atomic" + "syscall" + "time" + "unsafe" +) + +const ( + wmMouseMove = 0x0200 + wmLButtonDown = 0x0201 + wmRButtonDown = 0x0204 + wmMButtonDown = 0x0207 + wmXButtonDown = 0x020B + llkhfLowerInj = 0x00000002 + llmhfLowerInj = 0x00000002 +) + +type takeoverHookBinding struct { + mon *TakeoverMonitor +} + +var ( + procTakeoverGetClientRect = user32.NewProc("GetClientRect") + procTakeoverClientToScreen = user32.NewProc("ClientToScreen") + procTakeoverGetCurrentThreadID = kernel32.NewProc("GetCurrentThreadId") + + activeTakeoverBinding atomic.Pointer[takeoverHookBinding] + takeoverKbdCBOnce sync.Once + takeoverKbdCB uintptr + takeoverMouseCBOnce sync.Once + takeoverMouseCB uintptr +) + +type takeoverRect struct { + Left, Top, Right, Bottom int32 +} + +type takeoverKbdLLHookStruct struct { + vkCode uint32 + scanCode uint32 + flags uint32 + time uint32 + dwExtraInfo uintptr +} + +func getTakeoverKbdCallback() uintptr { + takeoverKbdCBOnce.Do(func() { + takeoverKbdCB = syscall.NewCallback(takeoverKbdLowLevelProc) + }) + return takeoverKbdCB +} + +func getTakeoverMouseCallback() uintptr { + takeoverMouseCBOnce.Do(func() { + takeoverMouseCB = syscall.NewCallback(takeoverMouseLowLevelProc) + }) + return takeoverMouseCB +} + +func takeoverKbdLowLevelProc(nCode int32, wParam uintptr, kb *takeoverKbdLLHookStruct) uintptr { + if nCode == hcAction && kb != nil && (kb.flags&(llkhfInjected|llkhfLowerInj)) == 0 { + if b := activeTakeoverBinding.Load(); b != nil && b.mon != nil { + mon := b.mon + if target, ok := mon.matchForegroundVM(); ok { + if target.LockInput { + if shouldSwallowLockedKey(wParam, kb.vkCode, kb.flags) { + return 1 + } + } else if wParam == wmKeyDown || wParam == wmSysKeyDown { + mon.emit(target.VMKey, "keyboard") + } + } + } + } + r, _, _ := procCallNextHookEx.Call(0, uintptr(nCode), wParam, uintptr(unsafe.Pointer(kb))) + return r +} + +func takeoverMouseLowLevelProc(nCode int32, wParam uintptr, ms *msLLHookStruct) uintptr { + if nCode == hcAction && ms != nil { + if (ms.flags&(llmhfInjected|llmhfLowerInj)) == 0 { + if b := activeTakeoverBinding.Load(); b != nil && b.mon != nil { + mon := b.mon + if target, ok := mon.matchVMClientAtPoint(ms.pt); ok { + if target.LockInput { + if mon.handleLockedMouseEvent(wParam, ms.mouseData, true) { + return 1 + } + } else { + mon.handleLockedMouseEvent(wParam, ms.mouseData, false) + switch wParam { + case wmLButtonDown, wmRButtonDown, wmMButtonDown, wmXButtonDown: + mon.emit(target.VMKey, "mouse_click") + case wmMouseWheel, wmMouseHWheel: + mon.emit(target.VMKey, "mouse_wheel") + case wmMouseMove: + if mon.evalMouseMove(target.VMKey, ms.pt.X, ms.pt.Y, time.Now()) { + mon.emit(target.VMKey, "mouse_move") + } + } + } + } else { + mon.handleLockedMouseEvent(wParam, ms.mouseData, false) + if wParam == wmMouseMove { + mon.evalMouseMove("", 0, 0, time.Now()) + } + } + } + } + } + r, _, _ := procCallNextHookEx.Call(0, uintptr(nCode), wParam, uintptr(unsafe.Pointer(ms))) + return r +} + +func (m *TakeoverMonitor) matchForegroundVM() (TakeoverTarget, bool) { + targets := m.targets.Load() + if targets == nil || len(*targets) == 0 { + return TakeoverTarget{}, false + } + hwnd, _, _ := procGetForegroundWindow.Call() + if hwnd == 0 { + return TakeoverTarget{}, false + } + var pid uint32 + _, _, _ = procGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&pid))) + if target, ok := (*targets)[pid]; ok { + return target, true + } + return TakeoverTarget{}, false +} + +func (m *TakeoverMonitor) matchVMClientAtPoint(pt point) (TakeoverTarget, bool) { + targets := m.targets.Load() + if targets == nil || len(*targets) == 0 { + return TakeoverTarget{}, false + } + var hwnd uintptr + if unsafe.Sizeof(uintptr(0)) == 8 { + packed := uintptr(uint32(pt.X)) | (uintptr(uint32(pt.Y)) << 32) + hwnd, _, _ = procWindowFromPoint.Call(packed) + } + if hwnd == 0 { + return TakeoverTarget{}, false + } + root := hwnd + if r, _, _ := procGetAncestor.Call(hwnd, gaRoot); r != 0 { + root = r + } + var pid uint32 + _, _, _ = procGetWindowThreadProcessId.Call(root, uintptr(unsafe.Pointer(&pid))) + target, ok := (*targets)[pid] + if !ok { + return TakeoverTarget{}, false + } + var cr takeoverRect + if okRect, _, _ := procTakeoverGetClientRect.Call(root, uintptr(unsafe.Pointer(&cr))); okRect == 0 { + return TakeoverTarget{}, false + } + origin := point{X: cr.Left, Y: cr.Top} + if okOrigin, _, _ := procTakeoverClientToScreen.Call(root, uintptr(unsafe.Pointer(&origin))); okOrigin == 0 { + return TakeoverTarget{}, false + } + if pt.X < origin.X || pt.Y < origin.Y || pt.X >= origin.X+(cr.Right-cr.Left) || pt.Y >= origin.Y+(cr.Bottom-cr.Top) { + return TakeoverTarget{}, false + } + return target, true +} + +func (m *TakeoverMonitor) startPlatformHooks(onUnexpectedExit func()) (func(), error) { + type startResult struct { + tid uint32 + err error + } + done := make(chan struct{}) + ready := make(chan startResult, 1) + var stopRequested atomic.Bool + go func() { + defer close(done) + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + rawTID, _, _ := procTakeoverGetCurrentThreadID.Call() + tid := uint32(rawTID) + // Force creation of this thread's message queue before signaling ready so + // PostThreadMessageW(WM_QUIT) from stop() can never race ahead of GetMessageW. + var msg struct { + hwnd uintptr + message uint32 + wParam uintptr + lParam uintptr + time uint32 + pt point + private uint32 + } + _, _, _ = procPeekMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0, pmNoRemove) + + binding := &takeoverHookBinding{mon: m} + activeTakeoverBinding.Store(binding) + defer func() { + activeTakeoverBinding.CompareAndSwap(binding, nil) + }() + + hMod, _, _ := procGetModuleHandleW.Call(0) + hKbd, _, kbdErr := procSetWindowsHookExW.Call(whKeyboardLL, getTakeoverKbdCallback(), hMod, 0) + hMouse, _, mouseErr := procSetWindowsHookExW.Call(whMouseLL, getTakeoverMouseCallback(), hMod, 0) + if hKbd == 0 || hMouse == 0 { + if hKbd != 0 { + _, _, _ = procUnhookWindowsHookEx.Call(hKbd) + } + if hMouse != 0 { + _, _, _ = procUnhookWindowsHookEx.Call(hMouse) + } + ready <- startResult{err: fmt.Errorf("install takeover hooks failed (kbd=%v, mouse=%v)", kbdErr, mouseErr)} + return + } + defer func() { + _, _, _ = procUnhookWindowsHookEx.Call(hKbd) + _, _, _ = procUnhookWindowsHookEx.Call(hMouse) + }() + ready <- startResult{tid: tid} + for { + r, _, _ := procGetMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0) + if int32(r) <= 0 { + break + } + } + if !stopRequested.Load() && onUnexpectedExit != nil { + onUnexpectedExit() + } + }() + res := <-ready + if res.err != nil { + <-done + return nil, res.err + } + return func() { + stopRequested.Store(true) + if res.tid != 0 { + _, _, _ = procPostThreadMessageW.Call(uintptr(res.tid), wmQuit, 0, 0) + } + <-done + }, nil +} diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 2f53337..b1d3498 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -17,6 +17,40 @@ var catalog = map[Locale]map[string]string{ "affinity.summary.pcores": "P核({count}线程)", "affinity.summary.skipped": "自动跳过({vcpus}核≥{pthreads}P线程)", "affinityMenu": "处理器相关性…", + "agent.session.banner": "AI 正在操作 · {plugin}", + "agent.session.close": "关闭", + "agent.session.collapse": "收起", + "agent.session.completed_status": "已完成,现在可操作画面", + "agent.session.completed_title": "自动安装", + "agent.session.denied_fallback": "已拒绝插件运行权限,自动安装脚本未运行,已切回手动安装引导", + "agent.session.locked_prefix": "画面已锁定防干扰 · ", + "agent.session.locked_status": "画面已锁定防干扰(点暂停可接管)", + "agent.session.pause": "暂停", + "agent.session.paused_by_user": "已手动暂停,现在可操作画面,点继续恢复", + "agent.session.paused_manual": "已暂停,等待手动继续", + "agent.session.phase_banner": "AI 正在操作({phase}已授权)", + "agent.session.phase_banner_timer": "AI 正在操作({phase}已授权 · 约 {minutes} 分钟)", + "agent.session.resume": "继续", + "agent.session.stage.account": "创建本地账户", + "agent.session.stage.boot_recovery": "进入恢复环境", + "agent.session.stage.completed": "已完成", + "agent.session.stage.desktop": "进入桌面验证", + "agent.session.stage.disk_utility": "磁盘工具抹盘", + "agent.session.stage.finish_install": "退出恢复并重启", + "agent.session.stage.guest_tools": "安装 Guest Tools", + "agent.session.stage.install_macos": "安装 macOS", + "agent.session.stage.install_wait": "等待系统安装", + "agent.session.stage.offline_terminal": "运行离线安装脚本", + "agent.session.stage.preflight": "环境准备", + "agent.session.stage.reboot": "等待系统重启", + "agent.session.stage.setup_assistant": "完成设置助理", + "agent.session.step_badge": "当前步骤", + "agent.session.step_numbered": "步骤 {num} · {name}", + "agent.session.step_paused": "已暂停", + "agent.session.step_running": "正在执行", + "agent.session.stop": "停止", + "agent.session.takeover_countdown": "用户接管中,{seconds} 秒后恢复", + "agent.session.takeover_manual": "检测到键鼠操作,已暂停(点击继续)", "appearance": "外观", "autoResolution": "自动分辨率", "backToEdit": "返回修改", @@ -81,6 +115,13 @@ var catalog = map[Locale]map[string]string{ "compat.gpu_icd_auto": "Vulkan 清单不可用({path}),已将显卡选择改为自动", "compat.gpu_icd_rebound": "显卡 Vulkan ICD 路径已从 {old} 更新为 {new}", "confirm": "确认", + "confirm.mirror.allow": "允许下载", + "confirm.mirror.message": "允许从自定义 HTTPS 地址 {origin} 下载经 SHA-256 校验的本地 OCR 模型", + "confirm.mirror.title": "确认自定义下载镜像", + "confirm.phase.allow": "允许", + "confirm.phase.deny": "拒绝", + "confirm.phase.message": "虚拟机 {name} 当前处于{phase}阶段,授权后将允许该插件截屏与发送键鼠输入", + "confirm.phase.title": "允许外部插件操作{phase}阶段", "copy": "复制", "copyTechInfo": "复制技术信息", "core.preflight.whpx_irqchip_advice": "宿主不支持 nested-virt 属性且当前运行时未包含非致命降级补丁,启动虚拟机时将自动附加 kernel-irqchip=off", @@ -172,10 +213,13 @@ var catalog = map[Locale]map[string]string{ "err.computer_use.phase.installer": "安装器", "err.computer_use.phase.recovery": "恢复模式", "err.computer_use.phase_confirmation": "虚拟机 {name} 处于 {phase} 阶段,操作需要先在 Reims-Go 中确认", + "err.computer_use.phase_denied": "已拒绝在受保护阶段访问虚拟机 {name}", "err.computer_use.restore_confirmation": "在 Reims-Go 中确认后才能还原虚拟机 {name} 的快照", "err.computer_use.secret_missing": "该虚拟机未保存登录密码,无法自动输入。请在 Reims-Go 的 MCP 服务设置中填写 macOS 登录密码后重试。", + "err.computer_use.session_paused": "虚拟机 {name} 的自动操作已暂停,恢复后再继续外部输入", "err.computer_use.unavailable": "虚拟机交互服务当前不可用", "err.computer_use.unsupported_driver": "当前虚拟机驱动不支持虚拟机交互", + "err.computer_use.user_takeover": "检测到用户在虚拟机 {name} 中操作键鼠,已暂停外部输入", "err.computer_use.vm_not_running": "虚拟机 {name} 未运行", "err.dataroot.busy_tasks": "仍有后台下载或创建任务进行中,请等待任务结束或取消后再切换数据目录", "err.dataroot.busy_vms": "仍有虚拟机正在运行,请先全部关机后再切换数据目录", @@ -442,6 +486,7 @@ var catalog = map[Locale]map[string]string{ "monitor.qemu.ring_full": "[图形] 图形事件环短暂阻塞(常见于抹除硬盘或大块磁盘写入期间),请稍候 10–30 秒等待自动恢复,无需强制关闭", "monitor.qemu.window": "[窗口] 虚拟机显示窗口已打开", "monitor.serial.boot": "[引导] UEFI 正在启动 OpenCore 引导程序", + "monitor.serial.provision_ready": "[预配置] macOS 已完成安装并首次启动就绪,可点击「完成安装」移除安装介质并启用网络与 Guest Tools", "monitor.serial.xnu": "[引导] OpenCore 已交接 macOS 内核(XNU 正在加载系统与驱动)", "monitor.stall_warn": "[警告] 连续 90 秒几乎无 CPU 与磁盘写入,虚拟机可能停在启动或重启阶段;可切到「QEMU」页签排查,或下次引导时按住 Win+V 查看内核输出", "monitor.start.off": "关闭", @@ -651,6 +696,7 @@ var catalog = map[Locale]map[string]string{ "tray.menu.show_window": "显示窗口(&W)", "tray.menu.start": "启动(&S)", "tray.menu.stop": "关机(&D)", + "tray.menu.stop_remote_control": "停止 AI 控制", "tray.menu.suspend": "挂起(&P)", "tray.menu.toggle_fullscreen": "切换全屏", "tray.notify.app_window_paste_retry": "剪贴板尚未同步,再试一次", @@ -667,6 +713,7 @@ var catalog = map[Locale]map[string]string{ "tray.notify.suspend_fail": "无法挂起 {name}", "tray.running": "{count, plural, =1 {Reims-Go — 1 台虚拟机运行中} other {Reims-Go — # 台虚拟机运行中}}", "tray.state.broken": "配置损坏", + "tray.state.remote_control": "AI 操作中", "tray.state.resuming": "正在恢复…", "tray.state.running": "运行中", "tray.state.starting": "启动中…", @@ -759,6 +806,40 @@ var catalog = map[Locale]map[string]string{ "affinity.summary.pcores": "P-cores({count}T)", "affinity.summary.skipped": "skipped({vcpus}vCPU>={pthreads}PT)", "affinityMenu": "Processor Affinity…", + "agent.session.banner": "AI controlling · {plugin}", + "agent.session.close": "Close", + "agent.session.collapse": "Collapse", + "agent.session.completed_status": "Completed; VM input unlocked", + "agent.session.completed_title": "Auto-install", + "agent.session.denied_fallback": "Plugin permission denied; script did not run and manual installation guide is shown instead", + "agent.session.locked_prefix": "Input locked · ", + "agent.session.locked_status": "Input locked (click Pause to take over)", + "agent.session.pause": "Pause", + "agent.session.paused_by_user": "Paused; VM input unlocked — click Resume to continue", + "agent.session.paused_manual": "Paused; waiting to resume", + "agent.session.phase_banner": "AI controlling ({phase} authorized)", + "agent.session.phase_banner_timer": "AI controlling ({phase} authorized · {minutes}m left)", + "agent.session.resume": "Resume", + "agent.session.stage.account": "Create local account", + "agent.session.stage.boot_recovery": "Boot into Recovery", + "agent.session.stage.completed": "Completed", + "agent.session.stage.desktop": "Verify desktop", + "agent.session.stage.disk_utility": "Erase target disk", + "agent.session.stage.finish_install": "Exit recovery and restart", + "agent.session.stage.guest_tools": "Install Guest Tools", + "agent.session.stage.install_macos": "Install macOS", + "agent.session.stage.install_wait": "Wait for macOS install", + "agent.session.stage.offline_terminal": "Run offline installer", + "agent.session.stage.preflight": "Preflight check", + "agent.session.stage.reboot": "Waiting for reboot", + "agent.session.stage.setup_assistant": "Setup Assistant", + "agent.session.step_badge": "Step", + "agent.session.step_numbered": "Step {num} · {name}", + "agent.session.step_paused": "Paused", + "agent.session.step_running": "Running", + "agent.session.stop": "Stop", + "agent.session.takeover_countdown": "User takeover active ({seconds}s)", + "agent.session.takeover_manual": "Manual input detected; paused (click Resume)", "appearance": "Appearance", "autoResolution": "Auto resolution", "backToEdit": "Edit and retry", @@ -823,6 +904,13 @@ var catalog = map[Locale]map[string]string{ "compat.gpu_icd_auto": "Switched GPU selection to Automatic because the Vulkan manifest is unavailable ({path})", "compat.gpu_icd_rebound": "Updated the GPU Vulkan ICD path from {old} to {new}", "confirm": "Confirm", + "confirm.mirror.allow": "Allow download", + "confirm.mirror.message": "Allow downloading SHA-256 verified local OCR assets from custom HTTPS origin {origin}", + "confirm.mirror.title": "Confirm custom download mirror", + "confirm.phase.allow": "Allow", + "confirm.phase.deny": "Deny", + "confirm.phase.message": "VM {name} is in the {phase} phase. Allowing grants screenshot and keyboard/mouse control", + "confirm.phase.title": "Allow plugin access during {phase}", "copy": "Copy", "copyTechInfo": "Copy technical details", "core.preflight.whpx_irqchip_advice": "Host lacks nested-virt property and runtime lacks nested-virt-nonfatal capability; kernel-irqchip=off will be auto-applied", @@ -914,10 +1002,13 @@ var catalog = map[Locale]map[string]string{ "err.computer_use.phase.installer": "installer", "err.computer_use.phase.recovery": "Recovery mode", "err.computer_use.phase_confirmation": "VM {name} is in the {phase} phase and requires confirmation in Reims-Go", + "err.computer_use.phase_denied": "Access to VM {name} during a protected phase was denied", "err.computer_use.restore_confirmation": "Confirm in Reims-Go before restoring a snapshot for VM {name}", "err.computer_use.secret_missing": "This VM has no saved login password, so it cannot be typed automatically. Set the macOS login password in the Reims-Go MCP Service settings and try again.", + "err.computer_use.session_paused": "Automation on VM {name} is paused; resume before sending input", "err.computer_use.unavailable": "The virtual machine interaction service is currently unavailable", "err.computer_use.unsupported_driver": "The selected VM driver does not support computer use", + "err.computer_use.user_takeover": "User input detected in VM {name}; external control paused", "err.computer_use.vm_not_running": "VM {name} is not running", "err.dataroot.busy_tasks": "Wait for active download or creation tasks to finish before switching the data folder", "err.dataroot.busy_vms": "Stop all running virtual machines before switching the data folder", @@ -1184,6 +1275,7 @@ var catalog = map[Locale]map[string]string{ "monitor.qemu.ring_full": "[gpu] Graphics completion ring briefly stalled (typical during disk erase or heavy disk I/O); wait 10–30s for it to recover automatically", "monitor.qemu.window": "[window] VM display window opened", "monitor.serial.boot": "[boot] UEFI starting OpenCore bootloader", + "monitor.serial.provision_ready": "[provision] macOS finished installing and reached first boot; click Finish Install to eject media and enable network and Guest Tools", "monitor.serial.xnu": "[boot] OpenCore handed off to macOS kernel (XNU loading)", "monitor.stall_warn": "[warn] Almost no CPU or disk activity for 90s; VM may be stalled during boot/reboot. Check the QEMU log tab or hold Win+V on next boot for verbose output", "monitor.start.off": "off", @@ -1393,6 +1485,7 @@ var catalog = map[Locale]map[string]string{ "tray.menu.show_window": "Show &Window", "tray.menu.start": "&Start", "tray.menu.stop": "Shut &Down", + "tray.menu.stop_remote_control": "Stop AI control", "tray.menu.suspend": "Sus&pend", "tray.menu.toggle_fullscreen": "Toggle full screen", "tray.notify.app_window_paste_retry": "Clipboard is still syncing. Try pasting again", @@ -1409,6 +1502,7 @@ var catalog = map[Locale]map[string]string{ "tray.notify.suspend_fail": "Couldn't suspend {name}", "tray.running": "{count, plural, one {Reims-Go — # VM running} other {Reims-Go — # VMs running}}", "tray.state.broken": "Broken", + "tray.state.remote_control": "AI controlling", "tray.state.resuming": "Resuming…", "tray.state.running": "Running", "tray.state.starting": "Starting…", @@ -1500,6 +1594,11 @@ var paramOrder = map[string][]string{ "affinity.summary.non_lpe": {"count"}, "affinity.summary.pcores": {"count"}, "affinity.summary.skipped": {"vcpus", "pthreads"}, + "agent.session.banner": {"plugin"}, + "agent.session.phase_banner": {"phase"}, + "agent.session.phase_banner_timer": {"phase", "minutes"}, + "agent.session.step_numbered": {"num", "name"}, + "agent.session.takeover_countdown": {"seconds"}, "cli.resume.canceled": {"name"}, "cli.resume.handing_to_window": {"name"}, "cli.resume.managed_ok": {"name"}, @@ -1513,6 +1612,9 @@ var paramOrder = map[string][]string{ "cli.start.timeout": {"name", "timeout"}, "compat.gpu_icd_auto": {"path"}, "compat.gpu_icd_rebound": {"old", "new"}, + "confirm.mirror.message": {"origin"}, + "confirm.phase.message": {"name", "phase"}, + "confirm.phase.title": {"phase"}, "doctor.cow_chain.broken": {"vm", "depth", "path"}, "doctor.cow_chain.item": {"vm", "depth", "warn"}, "doctor.ecores.detail": {"count", "cpus"}, @@ -1543,7 +1645,10 @@ var paramOrder = map[string][]string{ "err.computer_use.access_disabled": {"name"}, "err.computer_use.not_owned": {"name"}, "err.computer_use.phase_confirmation": {"name", "phase"}, + "err.computer_use.phase_denied": {"name"}, "err.computer_use.restore_confirmation": {"name"}, + "err.computer_use.session_paused": {"name"}, + "err.computer_use.user_takeover": {"name"}, "err.computer_use.vm_not_running": {"name"}, "err.dataroot.damaged": {"dir"}, "err.dataroot.locked": {"dir"}, diff --git a/internal/macos/autoinstall/hostclient/client.go b/internal/macos/autoinstall/hostclient/client.go new file mode 100644 index 0000000..eddc637 --- /dev/null +++ b/internal/macos/autoinstall/hostclient/client.go @@ -0,0 +1,273 @@ +package hostclient + +import ( + "bytes" + "context" + "encoding/base64" + "errors" + "fmt" + "image" + _ "image/jpeg" + _ "image/png" + "sync" + + "github.com/Nwflower/reims-go/internal/macos/autoinstall/ocr" + "github.com/Nwflower/reims-go/pkg/pluginsdk" +) + +// ScreenshotMeta carries frame geometry and blank-screen metadata returned by the host. +type ScreenshotMeta struct { + Width int + Height int + SourceWidth int + SourceHeight int + Blank bool +} + +// HostAPI abstracts all reverse Host RPCs required by the auto-install runner. +type HostAPI interface { + BeginSession(ctx context.Context, req pluginsdk.SessionBeginRequest) error + UpdateSession(ctx context.Context, req pluginsdk.SessionUpdateRequest) error + EndSession(ctx context.Context, vm string) error + Confirm(ctx context.Context, req pluginsdk.ConfirmRequest) (pluginsdk.ConfirmResult, error) + Notify(ctx context.Context, title, body string) error + Screenshot(ctx context.Context, req pluginsdk.ScreenshotRequest) (image.Image, ScreenshotMeta, error) + PointerMove(ctx context.Context, vm string, x, y, width, height int) error + PointerClick(ctx context.Context, vm, button string) error + KeyPress(ctx context.Context, vm, key string, modifiers ...string) error + TypeText(ctx context.Context, vm, text string) (int, error) + TypeSecret(ctx context.Context, vm, setting string) (int, error) + FinishInstall(ctx context.Context, vm string) (map[string]any, error) + RestartVM(ctx context.Context, vm string) (map[string]any, error) + Telemetry(ctx context.Context, vm string) (pluginsdk.VMTelemetry, error) + ocr.HostDownloader +} + +// CallHostFunc invokes a host-owned reverse RPC method on behalf of the built-in +// plugin through the plugin manager's broker and permission checks. +type CallHostFunc func(ctx context.Context, method string, params any, out any) error + +// InProcessClient implements HostAPI in-process over the host's plugin RPC +// handler pipeline while preserving the exact wire contract and authorization +// boundary used by external Sidecars. +type InProcessClient struct { + callHost CallHostFunc + + dlMu sync.Mutex + dlWaiters map[string]chan pluginsdk.DownloadEvent + dlEarly map[string]pluginsdk.DownloadEvent + dlEarlyOrder []string +} + +// NewInProcessClient creates a HostAPI client backed by callHost. +func NewInProcessClient(callHost CallHostFunc) *InProcessClient { + return &InProcessClient{ + callHost: callHost, + dlWaiters: make(map[string]chan pluginsdk.DownloadEvent), + dlEarly: make(map[string]pluginsdk.DownloadEvent), + } +} + +func (c *InProcessClient) call(ctx context.Context, method string, params any, out any) error { + if c == nil || c.callHost == nil { + return errors.New("host API callback is unavailable") + } + return c.callHost(ctx, method, params, out) +} + +func (c *InProcessClient) deleteEarlyLocked(id string) { + if _, ok := c.dlEarly[id]; !ok { + return + } + delete(c.dlEarly, id) + for i, existing := range c.dlEarlyOrder { + if existing == id { + c.dlEarlyOrder = append(c.dlEarlyOrder[:i], c.dlEarlyOrder[i+1:]...) + break + } + } +} + +// HandleDownloadProgress dispatches host `download/progress` notifications to +// waiting downloads, buffering early terminal events so fast local/cached +// downloads never race ahead of waiter registration. +func (c *InProcessClient) HandleDownloadProgress(ev pluginsdk.DownloadEvent) { + if ev.ID == "" || ev.Status == "running" { + return + } + c.dlMu.Lock() + ch := c.dlWaiters[ev.ID] + delete(c.dlWaiters, ev.ID) + if ch == nil { + if _, exists := c.dlEarly[ev.ID]; !exists { + for len(c.dlEarly) >= 64 && len(c.dlEarlyOrder) > 0 { + oldest := c.dlEarlyOrder[0] + c.dlEarlyOrder = c.dlEarlyOrder[1:] + delete(c.dlEarly, oldest) + } + c.dlEarlyOrder = append(c.dlEarlyOrder, ev.ID) + } + c.dlEarly[ev.ID] = ev + } + c.dlMu.Unlock() + if ch != nil { + select { + case ch <- ev: + default: + } + } +} + +func (c *InProcessClient) BeginSession(ctx context.Context, req pluginsdk.SessionBeginRequest) error { + return c.call(ctx, "host/session.begin", req, nil) +} + +func (c *InProcessClient) UpdateSession(ctx context.Context, req pluginsdk.SessionUpdateRequest) error { + return c.call(ctx, "host/session.update", req, nil) +} + +func (c *InProcessClient) EndSession(ctx context.Context, vm string) error { + return c.call(ctx, "host/session.end", map[string]any{"vm": vm}, nil) +} + +func (c *InProcessClient) Confirm(ctx context.Context, req pluginsdk.ConfirmRequest) (pluginsdk.ConfirmResult, error) { + var resp pluginsdk.ConfirmResult + err := c.call(ctx, "host/ui.confirm", req, &resp) + return resp, err +} + +func (c *InProcessClient) Notify(ctx context.Context, title, body string) error { + return c.call(ctx, "host/notify", map[string]any{"title": title, "body": body}, nil) +} + +func (c *InProcessClient) Screenshot(ctx context.Context, req pluginsdk.ScreenshotRequest) (image.Image, ScreenshotMeta, error) { + var res pluginsdk.ScreenshotResult + if err := c.call(ctx, "host/console.screenshot", req, &res); err != nil { + return nil, ScreenshotMeta{}, err + } + raw, err := base64.StdEncoding.DecodeString(res.Data) + if err != nil { + return nil, ScreenshotMeta{}, fmt.Errorf("decode screenshot base64: %w", err) + } + img, _, err := image.Decode(bytes.NewReader(raw)) + if err != nil { + return nil, ScreenshotMeta{}, fmt.Errorf("decode screenshot image: %w", err) + } + return img, ScreenshotMeta{ + Width: res.Width, + Height: res.Height, + SourceWidth: res.SourceWidth, + SourceHeight: res.SourceHeight, + Blank: res.Blank, + }, nil +} + +func (c *InProcessClient) PointerMove(ctx context.Context, vm string, x, y, width, height int) error { + return c.call(ctx, "host/console.pointer", pluginsdk.ConsolePointerRequest{ + VM: vm, Action: "move", X: x, Y: y, Width: width, Height: height, + }, nil) +} + +func (c *InProcessClient) PointerClick(ctx context.Context, vm, button string) error { + if button == "" { + button = "left" + } + return c.call(ctx, "host/console.pointer", pluginsdk.ConsolePointerRequest{ + VM: vm, Action: "click", Button: button, + }, nil) +} + +func (c *InProcessClient) KeyPress(ctx context.Context, vm, key string, modifiers ...string) error { + return c.call(ctx, "host/console.key", map[string]any{ + "vm": vm, + "key": key, + "modifiers": modifiers, + }, nil) +} + +func (c *InProcessClient) TypeText(ctx context.Context, vm, text string) (int, error) { + var resp struct { + Characters int `json:"characters"` + } + err := c.call(ctx, "host/console.type", map[string]any{"vm": vm, "text": text}, &resp) + return resp.Characters, err +} + +func (c *InProcessClient) TypeSecret(ctx context.Context, vm, setting string) (int, error) { + var resp struct { + Characters int `json:"characters"` + } + err := c.call(ctx, "host/console.typeSecret", map[string]any{"vm": vm, "setting": setting}, &resp) + return resp.Characters, err +} + +func (c *InProcessClient) FinishInstall(ctx context.Context, vm string) (map[string]any, error) { + var resp map[string]any + err := c.call(ctx, "host/vm.finishInstall", map[string]any{"vm": vm}, &resp) + return resp, err +} + +func (c *InProcessClient) RestartVM(ctx context.Context, vm string) (map[string]any, error) { + var resp map[string]any + err := c.call(ctx, "host/vm.restart", map[string]any{"vm": vm}, &resp) + return resp, err +} + +func (c *InProcessClient) Telemetry(ctx context.Context, vm string) (pluginsdk.VMTelemetry, error) { + var resp pluginsdk.VMTelemetry + err := c.call(ctx, "host/vm.telemetry", map[string]any{"vm": vm}, &resp) + return resp, err +} + +func (c *InProcessClient) DownloadAndWait(ctx context.Context, opts ocr.DownloadOptions) (string, error) { + var startResp struct { + ID string `json:"id"` + } + err := c.call(ctx, "host/download.start", pluginsdk.DownloadRequest{ + URL: opts.URL, + SHA256: opts.SHA256, + Dest: opts.Dest, + Size: opts.Size, + Label: opts.Label, + ConnectTimeoutMS: opts.ConnectTimeoutMS, + StallTimeoutMS: opts.StallTimeoutMS, + AllowCustomMirror: opts.AllowCustomMirror, + }, &startResp) + if err != nil { + return "", err + } + id := startResp.ID + if id == "" { + return "", errors.New("host/download.start returned empty download id") + } + + ch := make(chan pluginsdk.DownloadEvent, 1) + c.dlMu.Lock() + if early, ok := c.dlEarly[id]; ok { + c.deleteEarlyLocked(id) + ch <- early + } else { + c.dlWaiters[id] = ch + } + c.dlMu.Unlock() + defer func() { + c.dlMu.Lock() + delete(c.dlWaiters, id) + c.deleteEarlyLocked(id) + c.dlMu.Unlock() + }() + + select { + case ev := <-ch: + if ev.Status == "done" { + return ev.Path, nil + } + if ev.Error != "" { + return "", errors.New(ev.Error) + } + return "", fmt.Errorf("download ended with status %s", ev.Status) + case <-ctx.Done(): + _ = c.call(context.Background(), "host/download.cancel", map[string]any{"id": id}, nil) + return "", ctx.Err() + } +} diff --git a/internal/macos/autoinstall/hostclient/client_test.go b/internal/macos/autoinstall/hostclient/client_test.go new file mode 100644 index 0000000..96bcfc2 --- /dev/null +++ b/internal/macos/autoinstall/hostclient/client_test.go @@ -0,0 +1,62 @@ +package hostclient + +import ( + "context" + "encoding/json" + "fmt" + "testing" + "time" + + "github.com/Nwflower/reims-go/internal/macos/autoinstall/ocr" + "github.com/Nwflower/reims-go/pkg/pluginsdk" +) + +func TestHandleDownloadProgressFIFOEvictionPreservesRecentEarlyEvents(t *testing.T) { + var c *InProcessClient + c = NewInProcessClient(func(_ context.Context, method string, _ any, out any) error { + if method != "host/download.start" { + return nil + } + // Simulate 65 earlier unclaimed early events arriving right around our + // download's early completion: FIFO eviction must only drop the oldest + // entries, never our fresh download's event. + c.HandleDownloadProgress(pluginsdk.DownloadEvent{ + ID: "dl-target", + Status: "done", + Path: "/tmp/target.onnx", + }) + for i := 0; i < 63; i++ { + c.HandleDownloadProgress(pluginsdk.DownloadEvent{ + ID: fmt.Sprintf("dl-noise-%d", i), + Status: "done", + Path: "/tmp/noise", + }) + } + b, _ := json.Marshal(map[string]any{"id": "dl-target"}) + return json.Unmarshal(b, out) + }) + + // Seed 20 older stale events first so adding dl-target + 63 noise crosses 64 + // and evicts only the older stale events while keeping dl-target intact. + for i := 0; i < 20; i++ { + c.HandleDownloadProgress(pluginsdk.DownloadEvent{ + ID: fmt.Sprintf("dl-old-%d", i), + Status: "done", + Path: "/tmp/old", + }) + } + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + got, err := c.DownloadAndWait(ctx, ocr.DownloadOptions{ + URL: "https://example.com/target.onnx", + SHA256: "abc", + Dest: "/tmp/target.onnx", + }) + if err != nil { + t.Fatalf("DownloadAndWait timed out or failed due to early-event clear: %v", err) + } + if got != "/tmp/target.onnx" { + t.Fatalf("DownloadAndWait path = %q, want /tmp/target.onnx", got) + } +} diff --git a/internal/macos/autoinstall/ocr/engine.go b/internal/macos/autoinstall/ocr/engine.go new file mode 100644 index 0000000..d713246 --- /dev/null +++ b/internal/macos/autoinstall/ocr/engine.go @@ -0,0 +1,197 @@ +package ocr + +import ( + "context" + "image" + "strings" +) + +// Word is one recognized word/token with its pixel bounding box relative to +// the input image passed to Recognize. +type Word struct { + Text string `json:"text"` + Rect image.Rectangle `json:"rect"` +} + +// Line is one recognized text line containing its constituent words. +type Line struct { + Text string `json:"text"` + Rect image.Rectangle `json:"rect"` + Words []Word `json:"words,omitempty"` +} + +// Result is the structured OCR output for one image or cropped ROI. +type Result struct { + Backend string `json:"backend"` + Text string `json:"text"` + Lines []Line `json:"lines"` +} + +// ProbeReport summarizes local OCR backend availability for a target guest language. +type ProbeReport struct { + GuestLang string `json:"guest_lang"` + RequiredLanguage string `json:"required_language"` + WinOCRAvailable bool `json:"winocr_available"` + WinOCRLanguages []string `json:"winocr_languages,omitempty"` + WinOCRMaxDimension int `json:"winocr_max_dimension,omitempty"` + WinOCRSupportsTarget bool `json:"winocr_supports_target"` + RapidOCRInstalled bool `json:"rapidocr_installed"` + ActiveBackend string `json:"active_backend"` // "winocr" | "rapidocr" | "missing" + NeedsRapidOCRDownload bool `json:"needs_rapidocr_download"` + NeedsRapidOCRImport bool `json:"needs_rapidocr_import,omitempty"` +} + +// Engine defines the unified pure-local OCR backend interface. +type Engine interface { + Name() string + MaxDimension() int + Recognize(ctx context.Context, img image.Image) (Result, error) + Close() error +} + +// RequiredLangPrefix maps a macOS GuestLang string (such as "zh-Hans:0", +// "zh-Hant:0", "ja:0", "en-US:0") to its primary BCP-47 language prefix. +func RequiredLangPrefix(guestLang string) string { + raw := strings.TrimSpace(guestLang) + if idx := strings.IndexByte(raw, ':'); idx >= 0 { + raw = raw[:idx] + } + low := strings.ToLower(strings.TrimSpace(raw)) + switch { + case strings.HasPrefix(low, "zh-hant"), strings.HasPrefix(low, "zh-tw"), strings.HasPrefix(low, "zh-hk"): + return "zh-hant" + case strings.HasPrefix(low, "zh"): + return "zh-hans" + case strings.HasPrefix(low, "ja"): + return "ja" + case strings.HasPrefix(low, "ko"): + return "ko" + default: + return "en" + } +} + +// LanguageListSupports checks whether any installed Windows.Media.Ocr language +// tag can recognize targetPrefix. Per real Windows 11 measurements, +// zh-Hans/zh-Hant/ja/ko OCR packs also recognize Latin/English text cleanly. +func LanguageListSupports(available []string, targetPrefix string) (string, bool) { + target := strings.ToLower(strings.TrimSpace(targetPrefix)) + if target == "" { + target = "en" + } + for _, tag := range available { + low := strings.ToLower(strings.TrimSpace(tag)) + if low == target || strings.HasPrefix(low, target+"-") { + return tag, true + } + if target == "zh-hans" && (strings.HasPrefix(low, "zh-cn") || strings.HasPrefix(low, "zh-sg")) { + return tag, true + } + if target == "zh-hant" && (strings.HasPrefix(low, "zh-tw") || strings.HasPrefix(low, "zh-hk") || strings.HasPrefix(low, "zh-mo")) { + return tag, true + } + } + // Any installed CJK Windows OCR pack reliably recognizes ASCII/English UI labels. + if target == "en" && len(available) > 0 { + return available[0], true + } + return "", false +} + +// Probe inspects Windows.Media.Ocr and any installed RapidOCR ONNX bundle in dataDir. +func Probe(guestLang, dataDir, preferredBackend string) ProbeReport { + req := RequiredLangPrefix(guestLang) + langs, maxDim, winErr := ListWinOCRLanguages() + winOK := winErr == nil && len(langs) > 0 + _, winSupports := LanguageListSupports(langs, req) + rapidOK := IsRapidOCRInstalled(dataDir) + + rep := ProbeReport{ + GuestLang: guestLang, + RequiredLanguage: req, + WinOCRAvailable: winOK, + WinOCRLanguages: langs, + WinOCRMaxDimension: maxDim, + WinOCRSupportsTarget: winOK && winSupports, + RapidOCRInstalled: rapidOK, + } + + pref := strings.ToLower(strings.TrimSpace(preferredBackend)) + switch { + case pref == "rapidocr" && rapidOK: + rep.ActiveBackend = "rapidocr" + case pref == "winocr" && rep.WinOCRSupportsTarget: + rep.ActiveBackend = "winocr" + case rep.WinOCRSupportsTarget: + rep.ActiveBackend = "winocr" + case rapidOK: + rep.ActiveBackend = "rapidocr" + default: + rep.ActiveBackend = "missing" + if HasPinnedDefaultRapidOCRAssets() { + rep.NeedsRapidOCRDownload = true + } else { + rep.NeedsRapidOCRImport = true + } + } + return rep +} + +var ( + openWinOCREngine = func(tag string) (Engine, error) { + eng, err := NewWinOCREngine(tag) + if err != nil { + return nil, err + } + return eng, nil + } + openRapidOCREngine = func(dataDir string) (Engine, error) { + eng, err := NewRapidOCREngine(dataDir) + if err != nil { + return nil, err + } + return eng, nil + } +) + +// Open selects and initializes the best available local OCR engine for guestLang. +func Open(guestLang, dataDir, preferredBackend string) (Engine, ProbeReport, error) { + rep := Probe(guestLang, dataDir, preferredBackend) + switch rep.ActiveBackend { + case "winocr": + tag, _ := LanguageListSupports(rep.WinOCRLanguages, rep.RequiredLanguage) + eng, err := openWinOCREngine(tag) + if err != nil { + if rep.RapidOCRInstalled { + if rapidEng, rapidErr := openRapidOCREngine(dataDir); rapidErr == nil { + rep.ActiveBackend = "rapidocr" + return rapidEng, rep, nil + } + } + return nil, rep, err + } + return eng, rep, nil + case "rapidocr": + eng, err := openRapidOCREngine(dataDir) + if err != nil { + return nil, rep, err + } + return eng, rep, nil + default: + return nil, rep, ErrLanguagePackMissing{Required: rep.RequiredLanguage, Available: rep.WinOCRLanguages} + } +} + +// ErrLanguagePackMissing indicates that neither Windows.Media.Ocr nor a local +// RapidOCR bundle can recognize Required yet. +type ErrLanguagePackMissing struct { + Required string + Available []string +} + +func (e ErrLanguagePackMissing) Error() string { + if HasPinnedDefaultRapidOCRAssets() { + return "local OCR language pack missing for " + e.Required + " (install RapidOCR ONNX fallback)" + } + return "local OCR language pack missing for " + e.Required + " (install the Windows OCR language pack or import an offline RapidOCR ONNX bundle)" +} diff --git a/internal/macos/autoinstall/ocr/fetch.go b/internal/macos/autoinstall/ocr/fetch.go new file mode 100644 index 0000000..0652bed --- /dev/null +++ b/internal/macos/autoinstall/ocr/fetch.go @@ -0,0 +1,462 @@ +package ocr + +import ( + "archive/zip" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/url" + "os" + "path" + "path/filepath" + "strings" +) + +func isSafeAssetFilename(name string) bool { + trimmed := strings.TrimSpace(name) + if trimmed == "" || trimmed == "." || trimmed == ".." { + return false + } + if strings.ContainsAny(trimmed, `/\`) || filepath.Base(trimmed) != trimmed { + return false + } + return true +} + +// AssetSpec describes one pinned Apache-2.0 RapidOCR ONNX file or bundle with +// ordered HTTPS mirrors (China-first fallback to GitHub) and a fixed SHA-256. +type AssetSpec struct { + Name string `json:"name"` + SHA256 string `json:"sha256"` + Size int64 `json:"size,omitempty"` + Mirrors []string `json:"mirrors"` +} + +// DownloadOptions controls fast mirror failover and custom mirror approval. +type DownloadOptions struct { + URL string + SHA256 string + Dest string + Size int64 + Label string + ConnectTimeoutMS int + StallTimeoutMS int + AllowCustomMirror bool +} + +// HostDownloader abstracts `host/download.start` so failover logic is unit-tested +// without external network access. +type HostDownloader interface { + DownloadAndWait(ctx context.Context, opts DownloadOptions) (string, error) +} + +// DefaultRapidOCRAssets returns the ordered Apache-2.0 upstream PP-OCRv4 mobile +// + RapidOcrOnnx release specs. Custom mirrors or an offline zip bundle override +// or bypass these URLs while enforcing the same SHA-256 verification discipline. +func DefaultRapidOCRAssets() []AssetSpec { + return []AssetSpec{ + { + Name: "ch_PP-OCRv4_det_infer.onnx", + Mirrors: []string{ + "https://modelscope.cn/models/RapidAI/RapidOCR/resolve/master/onnx/PP-OCRv4/det/ch_PP-OCRv4_det_infer.onnx", + "https://hf-mirror.com/SWHL/RapidOCR/resolve/main/PP-OCRv4/ch_PP-OCRv4_det_infer.onnx", + "https://github.com/RapidAI/RapidOCR/releases/download/v1.1.0/ch_PP-OCRv4_det_infer.onnx", + }, + }, + { + Name: "ch_ppocr_mobile_v2.0_cls_infer.onnx", + Mirrors: []string{ + "https://modelscope.cn/models/RapidAI/RapidOCR/resolve/master/onnx/PP-OCRv4/cls/ch_ppocr_mobile_v2.0_cls_infer.onnx", + "https://hf-mirror.com/SWHL/RapidOCR/resolve/main/PP-OCRv4/ch_ppocr_mobile_v2.0_cls_infer.onnx", + "https://github.com/RapidAI/RapidOCR/releases/download/v1.1.0/ch_ppocr_mobile_v2.0_cls_infer.onnx", + }, + }, + { + Name: "ch_PP-OCRv4_rec_infer.onnx", + Mirrors: []string{ + "https://modelscope.cn/models/RapidAI/RapidOCR/resolve/master/onnx/PP-OCRv4/rec/ch_PP-OCRv4_rec_infer.onnx", + "https://hf-mirror.com/SWHL/RapidOCR/resolve/main/PP-OCRv4/ch_PP-OCRv4_rec_infer.onnx", + "https://github.com/RapidAI/RapidOCR/releases/download/v1.1.0/ch_PP-OCRv4_rec_infer.onnx", + }, + }, + { + Name: "ppocr_keys_v1.txt", + Mirrors: []string{ + "https://modelscope.cn/models/RapidAI/RapidOCR/resolve/master/paddle/PP-OCRv4/rec/ch_PP-OCRv4_rec_infer/ppocr_keys_v1.txt", + "https://hf-mirror.com/SWHL/RapidOCR/resolve/main/PP-OCRv4/ppocr_keys_v1.txt", + "https://github.com/RapidAI/RapidOcrOnnx/raw/main/models/ppocr_keys_v1.txt", + }, + }, + } +} + +// HasPinnedDefaultRapidOCRAssets reports whether DefaultRapidOCRAssets contains +// a complete runnable RapidOCR bundle (including RapidOcrOnnx.dll) with pinned +// SHA-256 digests so one-click online download can succeed safely. +func HasPinnedDefaultRapidOCRAssets() bool { + assets := DefaultRapidOCRAssets() + if len(assets) == 0 { + return false + } + hasDLL := false + for _, spec := range assets { + if strings.TrimSpace(spec.Name) == "" || strings.TrimSpace(spec.SHA256) == "" || len(spec.Mirrors) == 0 { + return false + } + if spec.Name == "RapidOcrOnnx.dll" { + hasDLL = true + } + } + return hasDLL +} + +// FetchAssetWithFallback downloads spec into destDir/spec.Name trying mirrors in +// order with fast failover timeouts (5s connect, 15s idle read). If customMirror +// is set, it is tried first with AllowCustomMirror=true (host requires user confirmation). +// Every candidate is verified against spec.SHA256 before moving into place. +func FetchAssetWithFallback(ctx context.Context, dl HostDownloader, destDir string, spec AssetSpec, customMirror string) (string, error) { + if dl == nil { + return "", errors.New("host downloader is unavailable") + } + spec.Name = strings.TrimSpace(spec.Name) + if !isSafeAssetFilename(spec.Name) { + return "", fmt.Errorf("invalid asset name %q", spec.Name) + } + if strings.TrimSpace(destDir) == "" { + return "", errors.New("destination directory is required") + } + wantHash := strings.ToLower(strings.TrimSpace(spec.SHA256)) + if wantHash == "" { + return "", fmt.Errorf("asset %s is missing a pinned SHA-256 digest", spec.Name) + } + + type candidate struct { + url string + custom bool + } + var candidates []candidate + if prefix := strings.TrimSpace(customMirror); prefix != "" { + u, err := url.Parse(prefix) + if err != nil || (u.Scheme != "https" && !isLoopback(u.Hostname())) || u.Host == "" { + return "", fmt.Errorf("invalid custom HTTPS mirror %q", customMirror) + } + candidates = append(candidates, candidate{ + url: strings.TrimRight(prefix, "/") + "/" + spec.Name, + custom: true, + }) + } + for _, m := range spec.Mirrors { + if trimmed := strings.TrimSpace(m); trimmed != "" { + candidates = append(candidates, candidate{url: trimmed, custom: false}) + } + } + if len(candidates) == 0 { + return "", fmt.Errorf("no download mirrors configured for %s", spec.Name) + } + + if err := os.MkdirAll(destDir, 0o755); err != nil { + return "", err + } + finalDest := filepath.Join(destDir, spec.Name) + if ok, _ := VerifyFileSHA256(finalDest, wantHash); ok { + if err := recordRapidOCRManifestEntry(destDir, spec.Name, wantHash); err != nil { + return "", err + } + return finalDest, nil + } + + var errs []string + for _, cand := range candidates { + if err := ctx.Err(); err != nil { + return "", err + } + partDest := filepath.Join(destDir, spec.Name+".dl") + _ = os.Remove(partDest) + gotPath, err := dl.DownloadAndWait(ctx, DownloadOptions{ + URL: cand.url, + SHA256: wantHash, + Dest: partDest, + Size: spec.Size, + Label: "RapidOCR: " + spec.Name, + ConnectTimeoutMS: 5000, + StallTimeoutMS: 15000, + AllowCustomMirror: cand.custom, + }) + if err != nil { + _ = os.Remove(partDest) + errs = append(errs, fmt.Sprintf("%s: %v", cand.url, err)) + continue + } + if gotPath == "" { + gotPath = partDest + } + ok, actual := VerifyFileSHA256(gotPath, wantHash) + if !ok { + _ = os.Remove(gotPath) + errs = append(errs, fmt.Sprintf("%s: sha256 mismatch (got %s, want %s)", cand.url, actual, wantHash)) + continue + } + if err := os.Rename(gotPath, finalDest); err != nil { + _ = os.Remove(gotPath) + return "", err + } + if err := recordRapidOCRManifestEntry(destDir, spec.Name, wantHash); err != nil { + return "", err + } + return finalDest, nil + } + return "", fmt.Errorf("all RapidOCR mirrors failed for %s: %s", spec.Name, strings.Join(errs, "; ")) +} + +// ImportOfflineBundle verifies a locally downloaded RapidOCR .zip archive against +// expectedSHA256 (required), extracts the required DLL/ONNX model files safely +// with zip-slip protection, and atomically places them into /ocr/. +func ImportOfflineBundle(zipPath, dataDir, expectedSHA256 string) (string, error) { + dataDir = strings.TrimSpace(dataDir) + if dataDir == "" { + return "", errors.New("plugin data directory is required for offline OCR bundle import") + } + want := strings.ToLower(strings.TrimSpace(expectedSHA256)) + if want == "" { + return "", errors.New("expected SHA-256 digest is required for offline OCR bundle import") + } + ok, actual := VerifyFileSHA256(zipPath, want) + if !ok { + return "", fmt.Errorf("offline bundle SHA-256 mismatch: got %s, want %s", actual, want) + } + + zr, err := zip.OpenReader(zipPath) + if err != nil { + return "", fmt.Errorf("open zip bundle: %w", err) + } + defer zr.Close() + + ocrDir := filepath.Join(strings.TrimSpace(dataDir), "ocr") + stageDir := ocrDir + ".staging" + _ = os.RemoveAll(stageDir) + if err := os.MkdirAll(stageDir, 0o755); err != nil { + return "", err + } + defer os.RemoveAll(stageDir) + + allowedFiles := map[string]bool{ + "RapidOcrOnnx.dll": true, + "onnxruntime.dll": true, + "ch_PP-OCRv4_det_infer.onnx": true, + "ch_ppocr_mobile_v2.0_cls_infer.onnx": true, + "ch_PP-OCRv4_rec_infer.onnx": true, + "ppocr_keys_v1.txt": true, + "LICENSE": true, + "NOTICE": true, + } + + const maxUncompressed = 128 << 20 + var totalBytes int64 + seen := make(map[string]string, len(allowedFiles)) + extractedHashes := make(map[string]string, len(allowedFiles)) + for _, f := range zr.File { + if f.FileInfo().IsDir() { + continue + } + if f.Mode()&os.ModeSymlink != 0 { + return "", fmt.Errorf("zip symlink entry is not allowed: %s", f.Name) + } + if filepath.IsAbs(f.Name) || strings.Contains(f.Name, ":") { + return "", fmt.Errorf("zip entry uses absolute path: %s", f.Name) + } + normalized := strings.ReplaceAll(f.Name, "\\", "/") + clean := path.Clean(normalized) + if clean == ".." || strings.HasPrefix(clean, "../") || strings.HasPrefix(clean, "/") || strings.Contains(clean, "/../") { + return "", fmt.Errorf("zip entry escapes target directory: %s", f.Name) + } + base := path.Base(clean) + if !allowedFiles[base] { + continue + } + if prev, dup := seen[base]; dup { + return "", fmt.Errorf("offline bundle contains duplicate entry for %s (%s and %s)", base, prev, f.Name) + } + seen[base] = f.Name + rc, err := f.Open() + if err != nil { + return "", err + } + outPath := filepath.Join(stageDir, base) + outFile, err := os.OpenFile(outPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644) + if err != nil { + _ = rc.Close() + return "", err + } + fileHash := sha256.New() + n, copyErr := io.Copy(io.MultiWriter(outFile, fileHash), io.LimitReader(rc, maxUncompressed-totalBytes+1)) + closeErr := outFile.Close() + _ = rc.Close() + totalBytes += n + if copyErr != nil { + return "", copyErr + } + if closeErr != nil { + return "", closeErr + } + if totalBytes > maxUncompressed { + return "", errors.New("offline OCR bundle exceeds maximum uncompressed size") + } + extractedHashes[base] = strings.ToLower(hex.EncodeToString(fileHash.Sum(nil))) + } + + for _, req := range []string{"RapidOcrOnnx.dll", "ch_PP-OCRv4_det_infer.onnx", "ch_PP-OCRv4_rec_infer.onnx", "ppocr_keys_v1.txt"} { + if st, err := os.Stat(filepath.Join(stageDir, req)); err != nil || st.Size() == 0 { + return "", fmt.Errorf("offline bundle missing required file %s", req) + } + } + if dllImportsLibrary(filepath.Join(stageDir, "RapidOcrOnnx.dll"), "onnxruntime.dll") { + if st, err := os.Stat(filepath.Join(stageDir, "onnxruntime.dll")); err != nil || st.Size() == 0 { + return "", errors.New("offline bundle missing required dependency onnxruntime.dll for RapidOcrOnnx.dll") + } + } + + if err := os.MkdirAll(ocrDir, 0o755); err != nil { + return "", err + } + entries, err := os.ReadDir(stageDir) + if err != nil { + return "", err + } + for _, e := range entries { + src := filepath.Join(stageDir, e.Name()) + dst := filepath.Join(ocrDir, e.Name()) + _ = os.Remove(dst) + if err := os.Rename(src, dst); err != nil { + return "", err + } + } + // Remove any stale previously imported optional files (e.g. onnxruntime.dll or + // cls model from an earlier bundle) not present in this replacement bundle so + // manifest verification stays consistent across re-imports. + for name := range allowedFiles { + if _, kept := extractedHashes[name]; !kept { + _ = os.Remove(filepath.Join(ocrDir, name)) + } + } + if err := writeRapidOCRManifest(ocrDir, extractedHashes); err != nil { + return "", err + } + return ocrDir, nil +} + +const rapidOCRManifestFilename = "manifest.json" + +type rapidOCRManifest struct { + Files map[string]string `json:"files"` +} + +func loadRapidOCRManifest(dir string) (rapidOCRManifest, error) { + raw, err := os.ReadFile(filepath.Join(dir, rapidOCRManifestFilename)) + if err != nil { + return rapidOCRManifest{}, err + } + var m rapidOCRManifest + if err := json.Unmarshal(raw, &m); err != nil { + return rapidOCRManifest{}, err + } + if len(m.Files) == 0 { + return rapidOCRManifest{}, errors.New("empty RapidOCR integrity manifest") + } + return m, nil +} + +func writeRapidOCRManifest(dir string, files map[string]string) error { + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + normalized := make(map[string]string, len(files)) + for k, v := range files { + if isSafeAssetFilename(k) && strings.TrimSpace(v) != "" { + normalized[k] = strings.ToLower(strings.TrimSpace(v)) + } + } + raw, err := json.MarshalIndent(rapidOCRManifest{Files: normalized}, "", " ") + if err != nil { + return err + } + tmpPath := filepath.Join(dir, rapidOCRManifestFilename+".tmp") + finalPath := filepath.Join(dir, rapidOCRManifestFilename) + if err := os.WriteFile(tmpPath, raw, 0o644); err != nil { + return err + } + _ = os.Remove(finalPath) + if err := os.Rename(tmpPath, finalPath); err != nil { + _ = os.Remove(tmpPath) + return err + } + return nil +} + +func recordRapidOCRManifestEntry(dir, name, sha256Hex string) error { + if !isSafeAssetFilename(name) || strings.TrimSpace(sha256Hex) == "" { + return nil + } + m, err := loadRapidOCRManifest(dir) + if err != nil || m.Files == nil { + m.Files = map[string]string{} + } + m.Files[name] = strings.ToLower(strings.TrimSpace(sha256Hex)) + return writeRapidOCRManifest(dir, m.Files) +} + +// verifyRapidOCRManifest verifies that every required RapidOCR file (and any +// present optional DLL/model file) matches the SHA-256 recorded at import or +// verified download time before loading RapidOcrOnnx.dll into the host process. +func verifyRapidOCRManifest(dir string, requiredFiles, optionalFiles []string) error { + m, err := loadRapidOCRManifest(dir) + if err != nil { + return fmt.Errorf("RapidOCR integrity manifest missing or invalid (re-import bundle): %w", err) + } + checkFile := func(name string) error { + want := strings.ToLower(strings.TrimSpace(m.Files[name])) + if want == "" { + return fmt.Errorf("RapidOCR file %s is not attested in %s (re-import bundle)", name, rapidOCRManifestFilename) + } + if ok, actual := VerifyFileSHA256(filepath.Join(dir, name), want); !ok { + return fmt.Errorf("RapidOCR file %s failed SHA-256 verification before load (got %s, want %s)", name, actual, want) + } + return nil + } + for _, name := range requiredFiles { + if err := checkFile(name); err != nil { + return err + } + } + for _, name := range optionalFiles { + if st, err := os.Stat(filepath.Join(dir, name)); err == nil && !st.IsDir() { + if err := checkFile(name); err != nil { + return err + } + } + } + return nil +} + +// VerifyFileSHA256 computes the SHA-256 of path and compares it with wantHex. +func VerifyFileSHA256(path, wantHex string) (bool, string) { + f, err := os.Open(path) + if err != nil { + return false, "" + } + defer f.Close() + h := sha256.New() + if _, err := io.Copy(h, f); err != nil { + return false, "" + } + actual := strings.ToLower(hex.EncodeToString(h.Sum(nil))) + return actual == strings.ToLower(strings.TrimSpace(wantHex)), actual +} + +func isLoopback(host string) bool { + h := strings.ToLower(strings.TrimSpace(host)) + return h == "localhost" || h == "127.0.0.1" || h == "::1" +} diff --git a/internal/macos/autoinstall/ocr/ocr_test.go b/internal/macos/autoinstall/ocr/ocr_test.go new file mode 100644 index 0000000..9c2a613 --- /dev/null +++ b/internal/macos/autoinstall/ocr/ocr_test.go @@ -0,0 +1,301 @@ +package ocr + +import ( + "archive/zip" + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "image" + "os" + "path/filepath" + "strings" + "testing" +) + +type stubDownloader struct { + attempts []DownloadOptions + fn func(opts DownloadOptions) ([]byte, error) +} + +func (s *stubDownloader) DownloadAndWait(_ context.Context, opts DownloadOptions) (string, error) { + s.attempts = append(s.attempts, opts) + data, err := s.fn(opts) + if err != nil { + return "", err + } + if err := os.WriteFile(opts.Dest, data, 0o644); err != nil { + return "", err + } + return opts.Dest, nil +} + +func TestFetchAssetWithFallbackSwitchesOnTimeoutAndBadHash(t *testing.T) { + payload := []byte("valid-rapidocr-onnx-model-bytes") + sum := sha256.Sum256(payload) + wantHex := hex.EncodeToString(sum[:]) + + dl := &stubDownloader{ + fn: func(opts DownloadOptions) ([]byte, error) { + switch opts.URL { + case "https://mirror1.example.com/model.onnx": + return nil, errors.New("connect timeout") + case "https://mirror2.example.com/model.onnx": + return []byte("corrupted-bytes"), nil + case "https://github.com/RapidAI/RapidOCR/releases/download/v1/model.onnx": + return payload, nil + default: + return nil, errors.New("unexpected url") + } + }, + } + + destDir := t.TempDir() + got, err := FetchAssetWithFallback(context.Background(), dl, destDir, AssetSpec{ + Name: "model.onnx", + SHA256: wantHex, + Mirrors: []string{ + "https://mirror1.example.com/model.onnx", + "https://mirror2.example.com/model.onnx", + "https://github.com/RapidAI/RapidOCR/releases/download/v1/model.onnx", + }, + }, "") + if err != nil { + t.Fatalf("FetchAssetWithFallback failed: %v", err) + } + if len(dl.attempts) != 3 { + t.Fatalf("expected 3 mirror attempts, got %d", len(dl.attempts)) + } + if dl.attempts[0].ConnectTimeoutMS != 5000 || dl.attempts[0].StallTimeoutMS != 15000 { + t.Fatalf("expected fast failover timeouts 5000/15000, got %+v", dl.attempts[0]) + } + if ok, _ := VerifyFileSHA256(got, wantHex); !ok { + t.Fatalf("downloaded file failed SHA-256 verification") + } +} + +func TestImportOfflineBundleEnforcesSHA256AndZipSlip(t *testing.T) { + makeZip := func(files map[string]string) ([]byte, string) { + var buf bytes.Buffer + zw := zip.NewWriter(&buf) + for name, content := range files { + w, err := zw.Create(name) + if err != nil { + t.Fatal(err) + } + _, _ = w.Write([]byte(content)) + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(buf.Bytes()) + return buf.Bytes(), hex.EncodeToString(sum[:]) + } + + rawZip, sumHex := makeZip(map[string]string{ + "bundle/RapidOcrOnnx.dll": "dll", + "bundle/onnxruntime.dll": "ort", + "bundle/ch_PP-OCRv4_det_infer.onnx": "det", + "bundle/ch_ppocr_mobile_v2.0_cls_infer.onnx": "cls", + "bundle/ch_PP-OCRv4_rec_infer.onnx": "rec", + "bundle/ppocr_keys_v1.txt": "a\nb\n", + }) + zipPath := filepath.Join(t.TempDir(), "rapidocr.zip") + if err := os.WriteFile(zipPath, rawZip, 0o644); err != nil { + t.Fatal(err) + } + + dataDir := t.TempDir() + // Wrong hash rejected. + if _, err := ImportOfflineBundle(zipPath, dataDir, "0000000000000000000000000000000000000000000000000000000000000000"); err == nil { + t.Fatal("expected SHA-256 mismatch error") + } + // Correct hash installs cleanly. + if _, err := ImportOfflineBundle(zipPath, dataDir, sumHex); err != nil { + t.Fatalf("ImportOfflineBundle valid zip failed: %v", err) + } + if !IsRapidOCRInstalled(dataDir) { + t.Fatal("IsRapidOCRInstalled returned false after valid offline import") + } + + // Re-importing a replacement bundle WITHOUT optional onnxruntime.dll / cls model + // must prune stale files from the previous import so manifest verification still passes. + slimZip, slimHash := makeZip(map[string]string{ + "slim/RapidOcrOnnx.dll": "static-dll", + "slim/ch_PP-OCRv4_det_infer.onnx": "det2", + "slim/ch_PP-OCRv4_rec_infer.onnx": "rec2", + "slim/ppocr_keys_v1.txt": "a\n", + }) + slimPath := filepath.Join(t.TempDir(), "rapidocr-slim.zip") + if err := os.WriteFile(slimPath, slimZip, 0o644); err != nil { + t.Fatal(err) + } + if _, err := ImportOfflineBundle(slimPath, dataDir, slimHash); err != nil { + t.Fatalf("re-import slim bundle failed: %v", err) + } + if !IsRapidOCRInstalled(dataDir) { + t.Fatal("IsRapidOCRInstalled returned false after re-importing bundle without optional files") + } + if _, err := os.Stat(filepath.Join(dataDir, "ocr", "onnxruntime.dll")); !os.IsNotExist(err) { + t.Fatalf("expected stale onnxruntime.dll pruned on re-import, stat err=%v", err) + } + + // Tampering with RapidOcrOnnx.dll after import must fail manifest verification before load. + if err := os.WriteFile(filepath.Join(dataDir, "ocr", "RapidOcrOnnx.dll"), []byte("tampered-dll"), 0o644); err != nil { + t.Fatal(err) + } + if IsRapidOCRInstalled(dataDir) { + t.Fatal("IsRapidOCRInstalled must reject tampered RapidOcrOnnx.dll") + } + + // Duplicate whitelisted basename across different subdirectories must be rejected. + dupZip, dupHash := makeZip(map[string]string{ + "a/RapidOcrOnnx.dll": "dll", + "a/ch_PP-OCRv4_det_infer.onnx": "det", + "a/ch_PP-OCRv4_rec_infer.onnx": "rec", + "a/ppocr_keys_v1.txt": "first\n", + "b/ppocr_keys_v1.txt": "second\n", + }) + dupPath := filepath.Join(t.TempDir(), "dup.zip") + if err := os.WriteFile(dupPath, dupZip, 0o644); err != nil { + t.Fatal(err) + } + if _, err := ImportOfflineBundle(dupPath, t.TempDir(), dupHash); err == nil || !strings.Contains(err.Error(), "duplicate entry") { + t.Fatalf("expected duplicate entry error, got %v", err) + } + + // Zip-slip entry rejected. + badZip, badHash := makeZip(map[string]string{ + "../evil.dll": "bad", + "RapidOcrOnnx.dll": "dll", + "ch_PP-OCRv4_det_infer.onnx": "det", + "ch_PP-OCRv4_rec_infer.onnx": "rec", + "ppocr_keys_v1.txt": "a\n", + }) + badPath := filepath.Join(t.TempDir(), "evil.zip") + _ = os.WriteFile(badPath, badZip, 0o644) + if _, err := ImportOfflineBundle(badPath, t.TempDir(), badHash); err == nil { + t.Fatal("expected zip-slip entry to be rejected") + } +} + +func TestLanguageListSupports(t *testing.T) { + if tag, ok := LanguageListSupports([]string{"zh-Hans-CN"}, "zh-hans"); !ok || tag != "zh-Hans-CN" { + t.Fatalf("expected zh-Hans-CN to match zh-hans, got %q %v", tag, ok) + } + if tag, ok := LanguageListSupports([]string{"zh-Hans-CN"}, "en"); !ok || tag != "zh-Hans-CN" { + t.Fatalf("expected zh-Hans-CN to also support en, got %q %v", tag, ok) + } + if _, ok := LanguageListSupports([]string{"en-US"}, "zh-hans"); ok { + t.Fatal("en-US alone must not claim zh-hans support") + } +} + +func TestFetchAndImportRejectTraversalAndEmptyDataDir(t *testing.T) { + dl := &stubDownloader{fn: func(_ DownloadOptions) ([]byte, error) { return []byte("x"), nil }} + sum := sha256.Sum256([]byte("x")) + sumHex := hex.EncodeToString(sum[:]) + + if _, err := FetchAssetWithFallback(context.Background(), dl, t.TempDir(), AssetSpec{ + Name: "../rules/evil.json", + SHA256: sumHex, + Mirrors: []string{"https://example.com/a"}, + }, ""); err == nil { + t.Fatal("expected path-traversal asset name to be rejected") + } + if _, err := ImportOfflineBundle("missing.zip", "", sumHex); err == nil { + t.Fatal("expected empty dataDir to be rejected") + } +} + +func TestHasPinnedDefaultRapidOCRAssetsAndOpenNilInterface(t *testing.T) { + if HasPinnedDefaultRapidOCRAssets() { + t.Fatal("DefaultRapidOCRAssets without pinned digests/DLL must report false") + } + // Stage manifest-attested dummy RapidOCR files (invalid DLL) so Probe selects + // rapidocr and NewRapidOCREngine fails; Open must return an untyped nil Engine interface. + dataDir := t.TempDir() + ocrDir := filepath.Join(dataDir, "ocr") + if err := os.MkdirAll(ocrDir, 0o755); err != nil { + t.Fatal(err) + } + hashes := map[string]string{} + payload := []byte("not-a-valid-dll") + sum := sha256.Sum256(payload) + sumHex := hex.EncodeToString(sum[:]) + for _, name := range []string{"RapidOcrOnnx.dll", "ch_PP-OCRv4_det_infer.onnx", "ch_PP-OCRv4_rec_infer.onnx", "ppocr_keys_v1.txt"} { + if err := os.WriteFile(filepath.Join(ocrDir, name), payload, 0o644); err != nil { + t.Fatal(err) + } + hashes[name] = sumHex + } + if err := writeRapidOCRManifest(ocrDir, hashes); err != nil { + t.Fatal(err) + } + eng, _, err := Open("en-US:0", dataDir, "rapidocr") + if err == nil { + _ = eng.Close() + t.Fatal("expected Open with invalid RapidOcrOnnx.dll to fail") + } + if eng != nil { + t.Fatalf("expected untyped nil Engine interface on error, got %T (%v)", eng, eng) + } +} + +type stubOCREngine struct{ name string } + +func (s *stubOCREngine) Name() string { return s.name } +func (s *stubOCREngine) MaxDimension() int { return 2048 } +func (s *stubOCREngine) Recognize(context.Context, image.Image) (Result, error) { return Result{Backend: s.name}, nil } +func (s *stubOCREngine) Close() error { return nil } + +func TestOpenFallsBackToRapidOCRWhenWinOCRInitFails(t *testing.T) { + // Stage attested RapidOCR files so Probe sees RapidOCRInstalled=true. + dataDir := t.TempDir() + ocrDir := filepath.Join(dataDir, "ocr") + if err := os.MkdirAll(ocrDir, 0o755); err != nil { + t.Fatal(err) + } + hashes := map[string]string{} + payload := []byte("stub-file") + sum := sha256.Sum256(payload) + sumHex := hex.EncodeToString(sum[:]) + for _, name := range []string{"RapidOcrOnnx.dll", "ch_PP-OCRv4_det_infer.onnx", "ch_PP-OCRv4_rec_infer.onnx", "ppocr_keys_v1.txt"} { + if err := os.WriteFile(filepath.Join(ocrDir, name), payload, 0o644); err != nil { + t.Fatal(err) + } + hashes[name] = sumHex + } + if err := writeRapidOCRManifest(ocrDir, hashes); err != nil { + t.Fatal(err) + } + + origWin := openWinOCREngine + origRapid := openRapidOCREngine + defer func() { + openWinOCREngine = origWin + openRapidOCREngine = origRapid + }() + winCalls := 0 + rapidCalls := 0 + openWinOCREngine = func(_ string) (Engine, error) { + winCalls++ + return nil, errors.New("COM activation failed") + } + openRapidOCREngine = func(_ string) (Engine, error) { + rapidCalls++ + return &stubOCREngine{name: "rapidocr"}, nil + } + + eng, rep, err := Open("en-US:0", dataDir, "") + if err != nil { + t.Fatalf("expected Open to fall back to rapidocr, got err=%v", err) + } + if eng == nil || eng.Name() != "rapidocr" || rep.ActiveBackend != "rapidocr" { + t.Fatalf("unexpected fallback engine/report: eng=%v rep=%+v", eng, rep) + } + if rapidCalls != 1 { + t.Fatalf("expected rapidocr constructor called once, got %d (winCalls=%d)", rapidCalls, winCalls) + } +} diff --git a/internal/macos/autoinstall/ocr/pe_check.go b/internal/macos/autoinstall/ocr/pe_check.go new file mode 100644 index 0000000..dff8854 --- /dev/null +++ b/internal/macos/autoinstall/ocr/pe_check.go @@ -0,0 +1,116 @@ +package ocr + +import ( + "bytes" + "debug/pe" + "encoding/binary" + "io" + "strings" +) + +// dllImportsLibrary inspects a Windows PE binary's import directory without +// loading or executing it and reports whether it dynamically links targetLib +// (for example "onnxruntime.dll"). Official RapidAI/RapidOcrOnnx static-MT +// releases link onnxruntime statically; custom dynamic builds import +// onnxruntime.dll. +// +// Go's stdlib (*pe.File).ImportedLibraries is currently an unimplemented stub, +// so we parse IMAGE_DIRECTORY_ENTRY_IMPORT directly from PE32/PE32+ headers. +func dllImportsLibrary(dllPath, targetLib string) bool { + f, err := pe.Open(dllPath) + if err != nil { + return false + } + defer f.Close() + importDir, ok := peImportDirectory(f) + if !ok || importDir.VirtualAddress == 0 { + return false + } + sec, off := findPESection(f, importDir.VirtualAddress) + if sec == nil { + return false + } + const descSize = 20 + const maxDescriptors = 4096 + var desc [descSize]byte + for i := 0; i < maxDescriptors; i++ { + pos := int64(off) + int64(i)*descSize + if pos+descSize > int64(sec.Size) { + break + } + if _, err := sec.ReadAt(desc[:], pos); err != nil && err != io.EOF { + break + } + origFirstThunk := binary.LittleEndian.Uint32(desc[0:4]) + nameRVA := binary.LittleEndian.Uint32(desc[12:16]) + firstThunk := binary.LittleEndian.Uint32(desc[16:20]) + if origFirstThunk == 0 && nameRVA == 0 && firstThunk == 0 { + break + } + if nameRVA == 0 { + continue + } + if name := readPECString(f, nameRVA); strings.EqualFold(strings.TrimSpace(name), targetLib) { + return true + } + } + return false +} + +func peImportDirectory(f *pe.File) (pe.DataDirectory, bool) { + switch oh := f.OptionalHeader.(type) { + case *pe.OptionalHeader64: + if len(oh.DataDirectory) <= pe.IMAGE_DIRECTORY_ENTRY_IMPORT { + return pe.DataDirectory{}, false + } + return oh.DataDirectory[pe.IMAGE_DIRECTORY_ENTRY_IMPORT], true + case *pe.OptionalHeader32: + if len(oh.DataDirectory) <= pe.IMAGE_DIRECTORY_ENTRY_IMPORT { + return pe.DataDirectory{}, false + } + return oh.DataDirectory[pe.IMAGE_DIRECTORY_ENTRY_IMPORT], true + default: + return pe.DataDirectory{}, false + } +} + +func findPESection(f *pe.File, rva uint32) (*pe.Section, uint32) { + for _, s := range f.Sections { + if rva < s.VirtualAddress { + continue + } + off := rva - s.VirtualAddress + limit := s.Size + if s.VirtualSize > 0 && s.VirtualSize < limit { + limit = s.VirtualSize + } + if off < limit { + return s, off + } + } + return nil, 0 +} + +func readPECString(f *pe.File, rva uint32) string { + sec, off := findPESection(f, rva) + if sec == nil { + return "" + } + avail := int(sec.Size - off) + if avail <= 0 { + return "" + } + if avail > 260 { + avail = 260 + } + buf := make([]byte, avail) + n, err := sec.ReadAt(buf, int64(off)) + if n == 0 || (err != nil && err != io.EOF) { + return "" + } + buf = buf[:n] + if idx := bytes.IndexByte(buf, 0); idx >= 0 { + buf = buf[:idx] + } + return string(buf) +} diff --git a/internal/macos/autoinstall/ocr/rapidocr_other.go b/internal/macos/autoinstall/ocr/rapidocr_other.go new file mode 100644 index 0000000..64cd14b --- /dev/null +++ b/internal/macos/autoinstall/ocr/rapidocr_other.go @@ -0,0 +1,48 @@ +//go:build !windows + +package ocr + +import ( + "context" + "errors" + "image" + "os" + "path/filepath" + "strings" +) + +type RapidOCREngine struct{} + +func NewRapidOCREngine(_ string) (*RapidOCREngine, error) { + return nil, errors.New("rapidocr DLL loader is only supported on Windows") +} + +func (e *RapidOCREngine) Name() string { return "rapidocr" } +func (e *RapidOCREngine) MaxDimension() int { return 4096 } +func (e *RapidOCREngine) Recognize(_ context.Context, _ image.Image) (Result, error) { + return Result{}, errors.New("rapidocr DLL loader is only supported on Windows") +} +func (e *RapidOCREngine) Close() error { return nil } + +func IsRapidOCRInstalled(dataDir string) bool { + if strings.TrimSpace(dataDir) == "" { + return false + } + dir := filepath.Join(strings.TrimSpace(dataDir), "ocr") + reqNames := []string{"RapidOcrOnnx.dll", "ch_PP-OCRv4_det_infer.onnx", "ch_PP-OCRv4_rec_infer.onnx", "ppocr_keys_v1.txt"} + optNames := []string{"ch_ppocr_mobile_v2.0_cls_infer.onnx"} + for _, f := range reqNames { + if st, err := os.Stat(filepath.Join(dir, f)); err != nil || st.IsDir() || st.Size() == 0 { + return false + } + } + if dllImportsLibrary(filepath.Join(dir, "RapidOcrOnnx.dll"), "onnxruntime.dll") { + if st, err := os.Stat(filepath.Join(dir, "onnxruntime.dll")); err != nil || st.IsDir() || st.Size() == 0 { + return false + } + reqNames = append(reqNames, "onnxruntime.dll") + } else { + optNames = append(optNames, "onnxruntime.dll") + } + return verifyRapidOCRManifest(dir, reqNames, optNames) == nil +} diff --git a/internal/macos/autoinstall/ocr/rapidocr_windows.go b/internal/macos/autoinstall/ocr/rapidocr_windows.go new file mode 100644 index 0000000..c9c6909 --- /dev/null +++ b/internal/macos/autoinstall/ocr/rapidocr_windows.go @@ -0,0 +1,443 @@ +//go:build windows + +package ocr + +import ( + "bytes" + "context" + "errors" + "fmt" + "image" + "image/png" + "math" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "unsafe" + + "golang.org/x/sys/windows" +) + +// C ABI mirrors upstream RapidAI/RapidOcrOnnx@675e73fe4c8b9e1d0be558bb5959a1b37696ed90 +// include/OcrLiteCApi.h (lines 27-79) and src/OcrLiteCApi.cpp (lines 12-160), Apache-2.0: +// +// typedef struct __ocr_param { +// int padding; int maxSideLen; float boxScoreThresh; float boxThresh; +// float unClipRatio; int doAngle; int mostAngle; +// } OCR_PARAM; +// typedef struct { double x; double y; } OCR_POINT; +// typedef struct { uint8_t *data; int type; int channels; int width; int height; long dataLength; } OCR_INPUT; +// typedef struct { +// OCR_POINT *boxPoint; float boxScore; int angleIndex; float angleScore; +// double angleTime; uint8_t *text; float *charScores; +// unsigned long long charScoresLength; unsigned long long boxPointLength; +// unsigned long long textLength; double crnnTime; double blockTime; +// } TEXT_BLOCK; +// typedef struct { double dbNetTime; TEXT_BLOCK *textBlocks; unsigned long long textBlocksLength; double detectTime; } OCR_RESULT; +// OCR_HANDLE OcrInit(const char *szDetModel, const char *szClsModel, const char *szRecModel, const char *szKeyPath, int nThreads); +// OCR_BOOL OcrDetectInput(OCR_HANDLE handle, OCR_INPUT *input, OCR_PARAM *pParam, OCR_RESULT *ocrResult); +// OCR_BOOL OcrFreeResult(OCR_RESULT *result); +// void OcrDestroy(OCR_HANDLE handle); +type rapidOCRParam struct { + Padding int32 + MaxSideLen int32 + BoxScoreThresh float32 + BoxThresh float32 + UnClipRatio float32 + DoAngle int32 + MostAngle int32 +} + +type rapidOCRPoint struct { + X float64 + Y float64 +} + +// rapidOCRInput matches Windows x64 LLP64 OCR_INPUT (`long` is 32-bit int32). +type rapidOCRInput struct { + Data *byte + Type int32 // 0 = raw bitmap, 1 = encoded image bytes (PNG/JPEG) + Channels int32 // for type==1: >=3 decodes as color, <3 decodes as grayscale + Width int32 + Height int32 + DataLength int32 + _ int32 // tail alignment padding for 8-byte struct alignment +} + +type rapidOCRTextBlock struct { + BoxPoint *rapidOCRPoint + BoxScore float32 + AngleIndex int32 + AngleScore float32 + _ int32 // 4-byte padding before 8-byte double AngleTime + AngleTime float64 + Text *byte + CharScores *float32 + CharScoresLength uint64 + BoxPointLength uint64 + TextLength uint64 + CrnnTime float64 + BlockTime float64 +} + +type rapidOCRResult struct { + DBNetTime float64 + TextBlocks *rapidOCRTextBlock + TextBlocksLength uint64 + DetectTime float64 +} + +// RapidOCREngine loads Apache-2.0 RapidOcrOnnx.dll via LoadLibraryEx with +// LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR (CGO_ENABLED=0, never mutating global DLL +// search paths of the host process) and guards all calls with a mutex. +type RapidOCREngine struct { + mu sync.Mutex + closed bool + dll *windows.DLL + handle uintptr + procInit *windows.Proc + procDetect *windows.Proc + procFree *windows.Proc + procDestroy *windows.Proc +} + +// NewRapidOCREngine initializes RapidOcrOnnx.dll and PP-OCRv4 mobile models +// from /ocr/. +func NewRapidOCREngine(dataDir string) (*RapidOCREngine, error) { + paths, err := ResolveRapidOCRPaths(dataDir) + if err != nil { + return nil, err + } + // Resolve optional onnxruntime.dll alongside RapidOcrOnnx.dll without mutating process-wide SetDllDirectory. + dllHandle, err := windows.LoadLibraryEx(paths.DLL, 0, windows.LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|windows.LOAD_LIBRARY_SEARCH_DEFAULT_DIRS) + if err != nil { + return nil, fmt.Errorf("load RapidOcrOnnx.dll: %w", err) + } + dll := &windows.DLL{Name: paths.DLL, Handle: dllHandle} + procInit, err := dll.FindProc("OcrInit") + if err != nil { + _ = dll.Release() + return nil, fmt.Errorf("RapidOcrOnnx.dll missing export OcrInit: %w", err) + } + procDetect, err := dll.FindProc("OcrDetectInput") + if err != nil { + _ = dll.Release() + return nil, fmt.Errorf("RapidOcrOnnx.dll missing export OcrDetectInput: %w", err) + } + procFree, err := dll.FindProc("OcrFreeResult") + if err != nil { + _ = dll.Release() + return nil, fmt.Errorf("RapidOcrOnnx.dll missing export OcrFreeResult: %w", err) + } + procDestroy, err := dll.FindProc("OcrDestroy") + if err != nil { + _ = dll.Release() + return nil, fmt.Errorf("RapidOcrOnnx.dll missing export OcrDestroy: %w", err) + } + + detB := cStringBytes(paths.DetModel) + clsPath := "" + if st, err := os.Stat(paths.ClsModel); err == nil && !st.IsDir() && st.Size() > 0 { + clsPath = paths.ClsModel + } + clsB := cStringBytes(clsPath) + recB := cStringBytes(paths.RecModel) + keysB := cStringBytes(paths.KeysPath) + handle, _, callErr := procInit.Call( + uintptr(unsafe.Pointer(&detB[0])), + uintptr(unsafe.Pointer(&clsB[0])), + uintptr(unsafe.Pointer(&recB[0])), + uintptr(unsafe.Pointer(&keysB[0])), + uintptr(int32(4)), + ) + runtime.KeepAlive(detB) + runtime.KeepAlive(clsB) + runtime.KeepAlive(recB) + runtime.KeepAlive(keysB) + if handle == 0 { + _ = dll.Release() + return nil, fmt.Errorf("OcrInit returned null handle: %v", callErr) + } + return &RapidOCREngine{ + dll: dll, + handle: handle, + procInit: procInit, + procDetect: procDetect, + procFree: procFree, + procDestroy: procDestroy, + }, nil +} + +func (e *RapidOCREngine) Name() string { return "rapidocr" } +func (e *RapidOCREngine) MaxDimension() int { return 4096 } + +func (e *RapidOCREngine) Close() error { + e.mu.Lock() + defer e.mu.Unlock() + if e.closed { + return nil + } + e.closed = true + if e.handle != 0 && e.procDestroy != nil { + _, _, _ = e.procDestroy.Call(e.handle) + e.handle = 0 + } + if e.dll != nil { + _ = e.dll.Release() + e.dll = nil + } + return nil +} + +func (e *RapidOCREngine) Recognize(ctx context.Context, img image.Image) (Result, error) { + if err := ctx.Err(); err != nil { + return Result{}, err + } + if img == nil { + return Result{}, errors.New("rapidocr: nil image") + } + bounds := img.Bounds() + if bounds.Empty() { + return Result{}, errors.New("rapidocr: empty image") + } + var pngBuf bytes.Buffer + if err := png.Encode(&pngBuf, img); err != nil { + return Result{}, fmt.Errorf("rapidocr encode png: %w", err) + } + raw := pngBuf.Bytes() + if len(raw) == 0 || len(raw) > math.MaxInt32 { + return Result{}, errors.New("rapidocr: invalid encoded image length") + } + + e.mu.Lock() + defer e.mu.Unlock() + if e.closed || e.handle == 0 { + return Result{}, errors.New("rapidocr: engine is closed") + } + param := rapidOCRParam{ + Padding: 50, + MaxSideLen: 1024, + BoxScoreThresh: 0.5, + BoxThresh: 0.3, + UnClipRatio: 1.6, + DoAngle: 0, + MostAngle: 0, + } + input := rapidOCRInput{ + Data: &raw[0], + Type: 1, // encoded image bytes (PNG) + Channels: 3, + Width: int32(bounds.Dx()), + Height: int32(bounds.Dy()), + DataLength: int32(len(raw)), + } + var res rapidOCRResult + ok, _, _ := e.procDetect.Call( + e.handle, + uintptr(unsafe.Pointer(&input)), + uintptr(unsafe.Pointer(¶m)), + uintptr(unsafe.Pointer(&res)), + ) + runtime.KeepAlive(raw) + runtime.KeepAlive(&input) + runtime.KeepAlive(¶m) + defer func() { + if res.TextBlocks != nil && res.TextBlocksLength > 0 { + _, _, _ = e.procFree.Call(uintptr(unsafe.Pointer(&res))) + } + }() + // OCR_BOOL is typedef char (1 byte in AL on x64 Windows; ignore upper 56 bits). + if byte(ok) == 0 { + // Upstream OcrDetectInput returns FALSE when result.strRes is empty + // (no text found in image) after handle & input checks succeed. + return Result{Backend: "rapidocr"}, nil + } + if res.TextBlocksLength > 0 && res.TextBlocks == nil { + return Result{}, fmt.Errorf("rapidocr: OcrDetectInput returned null textBlocks with length %d", res.TextBlocksLength) + } + return extractRapidOCRResult(&res), nil +} + +func cStringBytes(s string) []byte { + return append([]byte(s), 0) +} + +func extractRapidOCRResult(res *rapidOCRResult) Result { + out := Result{Backend: "rapidocr"} + if res == nil || res.TextBlocks == nil || res.TextBlocksLength == 0 { + return out + } + const maxBlocks = 4096 + n := int(res.TextBlocksLength) + if n > maxBlocks { + n = maxBlocks + } + blocks := unsafe.Slice(res.TextBlocks, n) + var texts []string + for i := range blocks { + tb := &blocks[i] + text := strings.TrimSpace(readRapidOCRBlockText(tb.Text, tb.TextLength)) + if text == "" { + continue + } + rect := rapidOCRBoxRect(tb.BoxPoint, tb.BoxPointLength) + texts = append(texts, text) + out.Lines = append(out.Lines, Line{ + Text: text, + Rect: rect, + Words: splitLineWords(text, rect), + }) + } + out.Text = strings.Join(texts, "\n") + return out +} + +// readRapidOCRBlockText safely reads TEXT_BLOCK.text. Upstream OcrLiteCApi.cpp +// allocates calloc(text.size(), 1) and sets textLength = text.size() + 1, so we +// never read past textLength-1 bytes and stop early at any NUL byte. +func readRapidOCRBlockText(ptr *byte, textLen uint64) string { + if ptr == nil || textLen <= 1 { + return "" + } + const maxTextBytes = 1 << 20 + n := textLen - 1 + if n > maxTextBytes { + n = maxTextBytes + } + raw := unsafe.Slice(ptr, int(n)) + if nul := bytes.IndexByte(raw, 0); nul >= 0 { + raw = raw[:nul] + } + return string(raw) +} + +func rapidOCRBoxRect(pts *rapidOCRPoint, count uint64) image.Rectangle { + if pts == nil || count == 0 { + return image.Rectangle{} + } + const maxPoints = 64 + n := int(count) + if n > maxPoints { + n = maxPoints + } + slice := unsafe.Slice(pts, n) + minX, minY := slice[0].X, slice[0].Y + maxX, maxY := minX, minY + for _, p := range slice[1:] { + if p.X < minX { + minX = p.X + } + if p.Y < minY { + minY = p.Y + } + if p.X > maxX { + maxX = p.X + } + if p.Y > maxY { + maxY = p.Y + } + } + x0, y0 := int(math.Floor(minX)), int(math.Floor(minY)) + x1, y1 := int(math.Ceil(maxX)), int(math.Ceil(maxY)) + if x1 <= x0 { + x1 = x0 + 1 + } + if y1 <= y0 { + y1 = y0 + 1 + } + return image.Rect(x0, y0, x1, y1) +} + +func splitLineWords(text string, rect image.Rectangle) []Word { + fields := strings.Fields(text) + if len(fields) <= 1 || rect.Empty() { + return []Word{{Text: text, Rect: rect}} + } + totalRunes := 0 + for _, f := range fields { + totalRunes += len([]rune(f)) + } + if totalRunes <= 0 { + return []Word{{Text: text, Rect: rect}} + } + width := rect.Dx() + out := make([]Word, 0, len(fields)) + cursor := 0 + for i, f := range fields { + rLen := len([]rune(f)) + x0 := rect.Min.X + cursor*width/totalRunes + cursor += rLen + x1 := rect.Min.X + cursor*width/totalRunes + if i == len(fields)-1 || x1 <= x0 { + if i == len(fields)-1 { + x1 = rect.Max.X + } else { + x1 = x0 + 1 + } + } + out = append(out, Word{ + Text: f, + Rect: image.Rect(x0, rect.Min.Y, x1, rect.Max.Y), + }) + } + return out +} + +// RapidOCRPaths lists the expected files inside /ocr/. +type RapidOCRPaths struct { + Dir string + DLL string + ONNXDLL string + DetModel string + ClsModel string + RecModel string + KeysPath string +} + +// ResolveRapidOCRPaths locates the installed RapidOCR ONNX DLL and PP-OCRv4 models. +func ResolveRapidOCRPaths(dataDir string) (RapidOCRPaths, error) { + trimmed := strings.TrimSpace(dataDir) + if trimmed == "" { + return RapidOCRPaths{}, errors.New("missing RapidOCR data directory") + } + dir := filepath.Join(trimmed, "ocr") + p := RapidOCRPaths{ + Dir: dir, + DLL: filepath.Join(dir, "RapidOcrOnnx.dll"), + ONNXDLL: filepath.Join(dir, "onnxruntime.dll"), + DetModel: filepath.Join(dir, "ch_PP-OCRv4_det_infer.onnx"), + ClsModel: filepath.Join(dir, "ch_ppocr_mobile_v2.0_cls_infer.onnx"), + RecModel: filepath.Join(dir, "ch_PP-OCRv4_rec_infer.onnx"), + KeysPath: filepath.Join(dir, "ppocr_keys_v1.txt"), + } + for _, req := range []string{p.DLL, p.DetModel, p.RecModel, p.KeysPath} { + if st, err := os.Stat(req); err != nil || st.IsDir() || st.Size() == 0 { + return RapidOCRPaths{}, fmt.Errorf("missing RapidOCR file %s", filepath.Base(req)) + } + } + reqNames := []string{"RapidOcrOnnx.dll", "ch_PP-OCRv4_det_infer.onnx", "ch_PP-OCRv4_rec_infer.onnx", "ppocr_keys_v1.txt"} + optNames := []string{"ch_ppocr_mobile_v2.0_cls_infer.onnx"} + if dllImportsLibrary(p.DLL, "onnxruntime.dll") { + if st, err := os.Stat(p.ONNXDLL); err != nil || st.IsDir() || st.Size() == 0 { + return RapidOCRPaths{}, errors.New("missing RapidOCR dependency onnxruntime.dll required by RapidOcrOnnx.dll") + } + reqNames = append(reqNames, "onnxruntime.dll") + } else { + optNames = append(optNames, "onnxruntime.dll") + } + if err := verifyRapidOCRManifest(dir, reqNames, optNames); err != nil { + return RapidOCRPaths{}, err + } + return p, nil +} + +// IsRapidOCRInstalled reports whether all required RapidOCR files exist in dataDir. +func IsRapidOCRInstalled(dataDir string) bool { + if strings.TrimSpace(dataDir) == "" { + return false + } + _, err := ResolveRapidOCRPaths(dataDir) + return err == nil +} diff --git a/internal/macos/autoinstall/ocr/rapidocr_windows_test.go b/internal/macos/autoinstall/ocr/rapidocr_windows_test.go new file mode 100644 index 0000000..634baef --- /dev/null +++ b/internal/macos/autoinstall/ocr/rapidocr_windows_test.go @@ -0,0 +1,256 @@ +//go:build windows + +package ocr + +import ( + "archive/zip" + "bytes" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "image" + "os" + "path/filepath" + "testing" + "unsafe" +) + +// TestRapidOCRCABILayoutMatchesUpstreamHeader verifies exact byte sizes and +// field offsets against RapidAI/RapidOcrOnnx@675e73fe4c8b9e1d0be558bb5959a1b37696ed90 +// include/OcrLiteCApi.h on Windows x64 (LLP64 where int=4 and long=4). +func TestRapidOCRCABILayoutMatchesUpstreamHeader(t *testing.T) { + if got := unsafe.Sizeof(rapidOCRParam{}); got != 28 { + t.Fatalf("sizeof(OCR_PARAM) = %d, want 28", got) + } + if got := unsafe.Sizeof(rapidOCRPoint{}); got != 16 { + t.Fatalf("sizeof(OCR_POINT) = %d, want 16", got) + } + if got := unsafe.Sizeof(rapidOCRInput{}); got != 32 { + t.Fatalf("sizeof(OCR_INPUT) = %d, want 32", got) + } + if off := unsafe.Offsetof(rapidOCRInput{}.Data); off != 0 { + t.Fatalf("offsetof(OCR_INPUT.data) = %d, want 0", off) + } + if off := unsafe.Offsetof(rapidOCRInput{}.Type); off != 8 { + t.Fatalf("offsetof(OCR_INPUT.type) = %d, want 8", off) + } + if off := unsafe.Offsetof(rapidOCRInput{}.DataLength); off != 24 { + t.Fatalf("offsetof(OCR_INPUT.dataLength) = %d, want 24", off) + } + if got := unsafe.Sizeof(rapidOCRTextBlock{}); got != 88 { + t.Fatalf("sizeof(TEXT_BLOCK) = %d, want 88", got) + } + if off := unsafe.Offsetof(rapidOCRTextBlock{}.AngleTime); off != 24 { + t.Fatalf("offsetof(TEXT_BLOCK.angleTime) = %d, want 24", off) + } + if off := unsafe.Offsetof(rapidOCRTextBlock{}.Text); off != 32 { + t.Fatalf("offsetof(TEXT_BLOCK.text) = %d, want 32", off) + } + if off := unsafe.Offsetof(rapidOCRTextBlock{}.TextLength); off != 64 { + t.Fatalf("offsetof(TEXT_BLOCK.textLength) = %d, want 64", off) + } + if got := unsafe.Sizeof(rapidOCRResult{}); got != 32 { + t.Fatalf("sizeof(OCR_RESULT) = %d, want 32", got) + } + if off := unsafe.Offsetof(rapidOCRResult{}.TextBlocks); off != 8 { + t.Fatalf("offsetof(OCR_RESULT.textBlocks) = %d, want 8", off) + } + if off := unsafe.Offsetof(rapidOCRResult{}.TextBlocksLength); off != 16 { + t.Fatalf("offsetof(OCR_RESULT.textBlocksLength) = %d, want 16", off) + } +} + +func TestExtractRapidOCRResultHandlesUpstreamTextLengthAndBoxes(t *testing.T) { + // Upstream OcrLiteCApi.cpp allocates text without a trailing NUL byte and sets + // textLength = len(text) + 1. Verify we read exact len(text) bytes safely. + txt1 := []byte("Utilities Terminal") + pts1 := []rapidOCRPoint{ + {X: 100.2, Y: 10.4}, + {X: 280.7, Y: 10.1}, + {X: 280.5, Y: 32.8}, + {X: 100.0, Y: 32.2}, + } + txt2 := []byte("继续") + pts2 := []rapidOCRPoint{ + {X: 900, Y: 620}, + {X: 980, Y: 620}, + {X: 980, Y: 650}, + {X: 900, Y: 650}, + } + blocks := []rapidOCRTextBlock{ + { + BoxPoint: &pts1[0], + BoxPointLength: uint64(len(pts1)), + Text: &txt1[0], + TextLength: uint64(len(txt1) + 1), + }, + { + BoxPoint: &pts2[0], + BoxPointLength: uint64(len(pts2)), + Text: &txt2[0], + TextLength: uint64(len(txt2) + 1), + }, + } + res := rapidOCRResult{ + TextBlocks: &blocks[0], + TextBlocksLength: uint64(len(blocks)), + } + got := extractRapidOCRResult(&res) + if got.Backend != "rapidocr" || len(got.Lines) != 2 { + t.Fatalf("unexpected extracted result: %+v", got) + } + if got.Lines[0].Text != "Utilities Terminal" || len(got.Lines[0].Words) != 2 { + t.Fatalf("line 0 = %+v, want 2 split words", got.Lines[0]) + } + wantRect0 := image.Rect(100, 10, 281, 33) + if got.Lines[0].Rect != wantRect0 { + t.Fatalf("line 0 rect = %v, want %v", got.Lines[0].Rect, wantRect0) + } + if got.Lines[1].Text != "继续" || got.Lines[1].Rect != image.Rect(900, 620, 980, 650) { + t.Fatalf("line 1 = %+v", got.Lines[1]) + } +} + +// buildMinimalPE64WithImport constructs a minimal valid PE32+ image whose +// import table declares importDLL (e.g. "onnxruntime.dll") so debug/pe parses it. +func buildMinimalPE64WithImport(importDLL string) []byte { + // Layout: + // 0x000..0x040: DOS header (e_lfanew = 0x80) + // 0x080..0x084: "PE\0\0" + // 0x084..0x098: COFF FileHeader (20 bytes) + // 0x098..0x188: OptionalHeader64 (240 bytes, 16 data directories) + // 0x188..0x1B0: 1 SectionHeader ".rdata" (40 bytes), VA=0x1000, RawPtr=0x200, Size=0x200 + // 0x200..0x400: .rdata section containing 2 IMAGE_IMPORT_DESCRIPTORs (40 bytes) + DLL name string + buf := make([]byte, 0x400) + buf[0] = 'M' + buf[1] = 'Z' + binary.LittleEndian.PutUint32(buf[0x3c:0x40], 0x80) + + copy(buf[0x80:0x84], []byte{'P', 'E', 0, 0}) + // COFF FileHeader + binary.LittleEndian.PutUint16(buf[0x84:0x86], 0x8664) // IMAGE_FILE_MACHINE_AMD64 + binary.LittleEndian.PutUint16(buf[0x86:0x88], 1) // NumberOfSections + binary.LittleEndian.PutUint16(buf[0x94:0x96], 0xF0) // SizeOfOptionalHeader (240) + binary.LittleEndian.PutUint16(buf[0x96:0x98], 0x2022) // DLL | EXECUTABLE_IMAGE + + // OptionalHeader64 + opt := 0x98 + binary.LittleEndian.PutUint16(buf[opt:opt+2], 0x20b) // PE32+ + binary.LittleEndian.PutUint32(buf[opt+108:opt+112], 16) // NumberOfRvaAndSizes + // DataDirectory[1] = Import Table: RVA=0x1000, Size=40 + if importDLL != "" { + binary.LittleEndian.PutUint32(buf[opt+112+8:opt+112+12], 0x1000) + binary.LittleEndian.PutUint32(buf[opt+112+12:opt+112+16], 40) + } + + // SectionHeader ".rdata" + sec := 0x188 + copy(buf[sec:sec+6], ".rdata") + binary.LittleEndian.PutUint32(buf[sec+8:sec+12], 0x200) // VirtualSize + binary.LittleEndian.PutUint32(buf[sec+12:sec+16], 0x1000) // VirtualAddress + binary.LittleEndian.PutUint32(buf[sec+16:sec+20], 0x200) // SizeOfRawData + binary.LittleEndian.PutUint32(buf[sec+20:sec+24], 0x200) // PointerToRawData + + // Import descriptor at file offset 0x200 (RVA 0x1000), DLL name at 0x240 (RVA 0x1040). + // Go's debug/pe ImportedLibraries requires OriginalFirstThunk != 0 (or FirstThunk) + // pointing inside the section. + if importDLL != "" { + binary.LittleEndian.PutUint32(buf[0x200+0:0x200+4], 0x1080) // OriginalFirstThunk RVA + binary.LittleEndian.PutUint32(buf[0x200+12:0x200+16], 0x1040) // Name RVA + binary.LittleEndian.PutUint32(buf[0x200+16:0x200+20], 0x1080) // FirstThunk RVA + copy(buf[0x240:], append([]byte(importDLL), 0)) + } + return buf +} + +func TestRapidOCRRequiresONNXRuntimeDLLWhenDynamicallyImported(t *testing.T) { + dynDLL := buildMinimalPE64WithImport("onnxruntime.dll") + staticDLL := buildMinimalPE64WithImport("KERNEL32.dll") + + makeZip := func(files map[string][]byte) (string, string) { + var buf bytes.Buffer + zw := zip.NewWriter(&buf) + for name, data := range files { + w, err := zw.Create(name) + if err != nil { + t.Fatal(err) + } + _, _ = w.Write(data) + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } + p := filepath.Join(t.TempDir(), "bundle.zip") + if err := os.WriteFile(p, buf.Bytes(), 0o644); err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(buf.Bytes()) + return p, hex.EncodeToString(sum[:]) + } + + // 1. Dynamically linked DLL WITHOUT onnxruntime.dll must be rejected on import and path resolution. + zipMissingORT, sumMissingORT := makeZip(map[string][]byte{ + "RapidOcrOnnx.dll": dynDLL, + "ch_PP-OCRv4_det_infer.onnx": []byte("det"), + "ch_PP-OCRv4_rec_infer.onnx": []byte("rec"), + "ppocr_keys_v1.txt": []byte("a\n"), + }) + if _, err := ImportOfflineBundle(zipMissingORT, t.TempDir(), sumMissingORT); err == nil { + t.Fatal("expected ImportOfflineBundle to reject dynamically linked RapidOcrOnnx.dll without onnxruntime.dll") + } + + // Direct check on ResolveRapidOCRPaths / IsRapidOCRInstalled with integrity manifest. + dataDir := t.TempDir() + ocrDir := filepath.Join(dataDir, "ocr") + if err := os.MkdirAll(ocrDir, 0o755); err != nil { + t.Fatal(err) + } + writeAttested := func(name string, data []byte, hashes map[string]string) { + if err := os.WriteFile(filepath.Join(ocrDir, name), data, 0o644); err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(data) + hashes[name] = hex.EncodeToString(sum[:]) + } + hashes := map[string]string{} + writeAttested("RapidOcrOnnx.dll", dynDLL, hashes) + writeAttested("ch_PP-OCRv4_det_infer.onnx", []byte("det"), hashes) + writeAttested("ch_PP-OCRv4_rec_infer.onnx", []byte("rec"), hashes) + writeAttested("ppocr_keys_v1.txt", []byte("a\n"), hashes) + if err := writeRapidOCRManifest(ocrDir, hashes); err != nil { + t.Fatal(err) + } + if IsRapidOCRInstalled(dataDir) { + t.Fatal("IsRapidOCRInstalled must report false when RapidOcrOnnx.dll imports missing onnxruntime.dll") + } + // Dropping an unattested onnxruntime.dll without manifest entry must still fail. + if err := os.WriteFile(filepath.Join(ocrDir, "onnxruntime.dll"), staticDLL, 0o644); err != nil { + t.Fatal(err) + } + if IsRapidOCRInstalled(dataDir) { + t.Fatal("IsRapidOCRInstalled must reject unattested onnxruntime.dll") + } + // Attesting onnxruntime.dll in manifest satisfies the requirement. + writeAttested("onnxruntime.dll", staticDLL, hashes) + if err := writeRapidOCRManifest(ocrDir, hashes); err != nil { + t.Fatal(err) + } + if !IsRapidOCRInstalled(dataDir) { + t.Fatal("IsRapidOCRInstalled must report true once attested onnxruntime.dll is present") + } + + // 2. Statically linked RapidOcrOnnx.dll (no onnxruntime.dll import) succeeds without onnxruntime.dll. + zipStatic, sumStatic := makeZip(map[string][]byte{ + "RapidOcrOnnx.dll": staticDLL, + "ch_PP-OCRv4_det_infer.onnx": []byte("det"), + "ch_PP-OCRv4_rec_infer.onnx": []byte("rec"), + "ppocr_keys_v1.txt": []byte("a\n"), + }) + staticDir := t.TempDir() + if _, err := ImportOfflineBundle(zipStatic, staticDir, sumStatic); err != nil { + t.Fatalf("static-linked RapidOcrOnnx.dll import failed: %v", err) + } + if !IsRapidOCRInstalled(staticDir) { + t.Fatal("static-linked RapidOcrOnnx.dll should report installed without onnxruntime.dll") + } +} diff --git a/internal/macos/autoinstall/ocr/winocr_live_windows_test.go b/internal/macos/autoinstall/ocr/winocr_live_windows_test.go new file mode 100644 index 0000000..9521c23 --- /dev/null +++ b/internal/macos/autoinstall/ocr/winocr_live_windows_test.go @@ -0,0 +1,184 @@ +//go:build windows + +package ocr + +import ( + "context" + "image" + "image/color" + "strings" + "syscall" + "testing" + "time" + "unsafe" +) + +func renderGDITestCanvas(t *testing.T, w, h int, bg color.RGBA, drawItems []struct { + Text string + X, Y int32 + W, H int32 + Size int32 + Color color.RGBA + BgBox *color.RGBA +}) *image.RGBA { + t.Helper() + gdi32 := syscall.NewLazyDLL("gdi32.dll") + user32 := syscall.NewLazyDLL("user32.dll") + + procCreateCompatibleDC := gdi32.NewProc("CreateCompatibleDC") + procDeleteDC := gdi32.NewProc("DeleteDC") + procCreateDIBSection := gdi32.NewProc("CreateDIBSection") + procSelectObject := gdi32.NewProc("SelectObject") + procDeleteObject := gdi32.NewProc("DeleteObject") + procCreateSolidBrush := gdi32.NewProc("CreateSolidBrush") + procCreateFontW := gdi32.NewProc("CreateFontW") + procSetBkMode := gdi32.NewProc("SetBkMode") + procSetTextColor := gdi32.NewProc("SetTextColor") + procFillRect := user32.NewProc("FillRect") + procDrawTextW := user32.NewProc("DrawTextW") + + type rect struct{ L, T, R, B int32 } + type bmiHeader struct { + Size uint32 + Width int32 + Height int32 + Planes uint16 + BitCount uint16 + Compression uint32 + SizeImage uint32 + XPelsPerMeter int32 + YPelsPerMeter int32 + ClrUsed uint32 + ClrImportant uint32 + } + type bmi struct { + Header bmiHeader + Colors [1]uint32 + } + + hdc, _, _ := procCreateCompatibleDC.Call(0) + if hdc == 0 { + t.Fatal("CreateCompatibleDC failed") + } + defer procDeleteDC.Call(hdc) + + bi := bmi{Header: bmiHeader{ + Size: uint32(unsafe.Sizeof(bmiHeader{})), + Width: int32(w), + Height: -int32(h), + Planes: 1, + BitCount: 32, + }} + var bits unsafe.Pointer + hbm, _, _ := procCreateDIBSection.Call(hdc, uintptr(unsafe.Pointer(&bi)), 0, uintptr(unsafe.Pointer(&bits)), 0, 0) + if hbm == 0 || bits == nil { + t.Fatal("CreateDIBSection failed") + } + defer procDeleteObject.Call(hbm) + oldBM, _, _ := procSelectObject.Call(hdc, hbm) + defer procSelectObject.Call(hdc, oldBM) + + rgb := func(c color.RGBA) uintptr { + return uintptr(uint32(c.R) | uint32(c.G)<<8 | uint32(c.B)<<16) + } + full := rect{0, 0, int32(w), int32(h)} + bgBr, _, _ := procCreateSolidBrush.Call(rgb(bg)) + procFillRect.Call(hdc, uintptr(unsafe.Pointer(&full)), bgBr) + procDeleteObject.Call(bgBr) + + procSetBkMode.Call(hdc, 1) // TRANSPARENT + fontName, _ := syscall.UTF16PtrFromString("Microsoft YaHei UI") + + for _, it := range drawItems { + r := rect{it.X, it.Y, it.X + it.W, it.Y + it.H} + if it.BgBox != nil { + br, _, _ := procCreateSolidBrush.Call(rgb(*it.BgBox)) + procFillRect.Call(hdc, uintptr(unsafe.Pointer(&r)), br) + procDeleteObject.Call(br) + } + hFont, _, _ := procCreateFontW.Call(uintptr(^uint32(it.Size)+1), 0, 0, 0, 500, 0, 0, 0, 1, 0, 0, 5, 0, uintptr(unsafe.Pointer(fontName))) + oldF, _, _ := procSelectObject.Call(hdc, hFont) + procSetTextColor.Call(hdc, rgb(it.Color)) + u16, _ := syscall.UTF16FromString(it.Text) + procDrawTextW.Call(hdc, uintptr(unsafe.Pointer(&u16[0])), uintptr(len(u16)-1), uintptr(unsafe.Pointer(&r)), 0x24) // DT_VCENTER|DT_SINGLELINE + procSelectObject.Call(hdc, oldF) + procDeleteObject.Call(hFont) + } + + raw := unsafe.Slice((*byte)(bits), w*h*4) + img := image.NewRGBA(image.Rect(0, 0, w, h)) + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + off := (y*w + x) * 4 + img.SetRGBA(x, y, color.RGBA{R: raw[off+2], G: raw[off+1], B: raw[off+0], A: 255}) + } + } + return img +} + +func TestWinOCRLiveRecognitionAndLatency(t *testing.T) { + langs, maxDim, err := ListWinOCRLanguages() + if err != nil { + t.Fatalf("ListWinOCRLanguages failed: %v", err) + } + if len(langs) == 0 { + t.Skip("no Windows.Media.Ocr language packs installed on this host") + } + if maxDim < 2000 { + t.Fatalf("unexpected MaxImageDimension = %d", maxDim) + } + t.Logf("WinRT OcrEngine languages=%v maxDim=%d", langs, maxDim) + + eng, err := NewWinOCREngine(langs[0]) + if err != nil { + t.Fatalf("NewWinOCREngine(%q) failed: %v", langs[0], err) + } + defer eng.Close() + + canvas := renderGDITestCanvas(t, 1280, 720, color.RGBA{245, 245, 247, 255}, []struct { + Text string + X, Y int32 + W, H int32 + Size int32 + Color color.RGBA + BgBox *color.RGBA + }{ + {Text: "Select Your Country or Region", X: 260, Y: 140, W: 760, H: 60, Size: 38, Color: color.RGBA{24, 24, 28, 255}}, + {Text: "选择国家或地区", X: 260, Y: 230, W: 500, H: 60, Size: 36, Color: color.RGBA{24, 24, 28, 255}}, + {Text: "Continue", X: 820, Y: 560, W: 220, H: 52, Size: 30, Color: color.RGBA{20, 20, 24, 255}}, + {Text: "继续", X: 620, Y: 560, W: 160, H: 52, Size: 30, Color: color.RGBA{20, 20, 24, 255}}, + }) + + // Warm-up call + res, err := eng.Recognize(context.Background(), canvas) + if err != nil { + t.Fatalf("Recognize warm-up failed: %v", err) + } + // Timed steady-state call + start := time.Now() + res, err = eng.Recognize(context.Background(), canvas) + elapsed := time.Since(start) + if err != nil { + t.Fatalf("Recognize steady-state failed: %v", err) + } + t.Logf("WinRT OCR elapsed=%v text=%q lines=%d", elapsed, res.Text, len(res.Lines)) + + compact := strings.ReplaceAll(strings.ToLower(res.Text), " ", "") + if !strings.Contains(compact, "country") || !strings.Contains(compact, "continue") { + t.Fatalf("expected 'Country' and 'Continue' in OCR result, got %q", res.Text) + } + if strings.HasPrefix(strings.ToLower(langs[0]), "zh") && (!strings.Contains(compact, "选择国家") || !strings.Contains(compact, "继续")) { + t.Fatalf("expected Chinese text in zh-Hans OCR result, got %q", res.Text) + } + if len(res.Lines) < 2 { + t.Fatalf("expected at least 2 OCR lines with bounding rects, got %+v", res.Lines) + } + for _, ln := range res.Lines { + if ln.Rect.Empty() { + t.Fatalf("line %q has empty bounding rect", ln.Text) + } + } + if elapsed > 300*time.Millisecond { + t.Logf("note: steady-state WinRT OCR took %v (target <=150ms on normal load)", elapsed) + } +} diff --git a/internal/macos/autoinstall/ocr/winocr_other.go b/internal/macos/autoinstall/ocr/winocr_other.go new file mode 100644 index 0000000..8cda8fe --- /dev/null +++ b/internal/macos/autoinstall/ocr/winocr_other.go @@ -0,0 +1,26 @@ +//go:build !windows + +package ocr + +import ( + "context" + "errors" + "image" +) + +func ListWinOCRLanguages() ([]string, int, error) { + return nil, 0, errors.New("winocr is only supported on Windows") +} + +type WinOCREngine struct{} + +func NewWinOCREngine(_ string) (*WinOCREngine, error) { + return nil, errors.New("winocr is only supported on Windows") +} + +func (e *WinOCREngine) Name() string { return "winocr" } +func (e *WinOCREngine) MaxDimension() int { return 0 } +func (e *WinOCREngine) Recognize(_ context.Context, _ image.Image) (Result, error) { + return Result{}, errors.New("winocr is only supported on Windows") +} +func (e *WinOCREngine) Close() error { return nil } diff --git a/internal/macos/autoinstall/ocr/winocr_windows.go b/internal/macos/autoinstall/ocr/winocr_windows.go new file mode 100644 index 0000000..8c4392f --- /dev/null +++ b/internal/macos/autoinstall/ocr/winocr_windows.go @@ -0,0 +1,634 @@ +//go:build windows + +package ocr + +import ( + "context" + "errors" + "fmt" + "image" + "math" + "runtime" + "strings" + "sync" + "sync/atomic" + "syscall" + "time" + "unsafe" + + "golang.org/x/sys/windows" +) + +const ( + roInitMultithreaded = 1 + sOK = 0 + sFalse = 1 + rpcEChangedMode = 0x80010106 + + bitmapPixelFormatBgra8 = 87 + bitmapAlphaModePremul = 0 + asyncStatusStarted = 0 + asyncStatusCompleted = 1 + asyncStatusCanceled = 2 + asyncStatusError = 3 + defaultWinOCRMaxDimension = 2600 + defaultWinOCRRecognizeBudget = 30 * time.Second +) + +var ( + combase = windows.NewLazySystemDLL("combase.dll") + ntdll = windows.NewLazySystemDLL("ntdll.dll") + procRoInitialize = combase.NewProc("RoInitialize") + procRoGetActivationFactory = combase.NewProc("RoGetActivationFactory") + procWindowsCreateString = combase.NewProc("WindowsCreateString") + procWindowsDeleteString = combase.NewProc("WindowsDeleteString") + procWindowsGetStringRawBuffer = combase.NewProc("WindowsGetStringRawBuffer") + procRtlMoveMemory = ntdll.NewProc("RtlMoveMemory") + + iidLanguageFactory = windows.GUID{Data1: 0x9B0252AC, Data2: 0x0C27, Data3: 0x44F8, Data4: [8]byte{0xB7, 0x92, 0x97, 0x93, 0xFB, 0x66, 0xC6, 0x3E}} + iidOcrEngineStatics = windows.GUID{Data1: 0x5BFFA85A, Data2: 0x3384, Data3: 0x3540, Data4: [8]byte{0x99, 0x40, 0x69, 0x91, 0x20, 0xD4, 0x28, 0xA8}} + iidBufferFactory = windows.GUID{Data1: 0x71AF914D, Data2: 0xC10F, Data3: 0x484B, Data4: [8]byte{0xBC, 0x50, 0x14, 0xBC, 0x62, 0x3B, 0x3A, 0x27}} + iidBufferByteAccess = windows.GUID{Data1: 0x905A0FEF, Data2: 0xBC53, Data3: 0x11DF, Data4: [8]byte{0x8C, 0x49, 0x00, 0x1E, 0x4F, 0xC6, 0x86, 0xDA}} + iidSoftwareBitmapStatic = windows.GUID{Data1: 0xDF0385DB, Data2: 0x672F, Data3: 0x4A9D, Data4: [8]byte{0x80, 0x6E, 0xC2, 0x44, 0x2F, 0x34, 0x3E, 0x86}} + iidAsyncInfo = windows.GUID{Data1: 0x00000036, Data2: 0x0000, Data3: 0x0000, Data4: [8]byte{0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}} + iidClosable = windows.GUID{Data1: 0x30D5A829, Data2: 0x7FA4, Data3: 0x4026, Data4: [8]byte{0x83, 0xBB, 0xD7, 0x5B, 0xAE, 0x4E, 0xA9, 0x9E}} +) + +type winRectF struct { + X, Y, Width, Height float32 +} + +func vtableEntry(obj uintptr, slot uintptr) uintptr { + var vtbl uintptr + _, _, _ = procRtlMoveMemory.Call(uintptr(unsafe.Pointer(&vtbl)), obj, unsafe.Sizeof(vtbl)) + var fn uintptr + _, _, _ = procRtlMoveMemory.Call(uintptr(unsafe.Pointer(&fn)), vtbl+slot*unsafe.Sizeof(uintptr(0)), unsafe.Sizeof(fn)) + return fn +} + +func comRelease(obj uintptr) { + if obj == 0 { + return + } + _, _, _ = syscall.SyscallN(vtableEntry(obj, 2), obj) +} + +func comQueryInterface(obj uintptr, iid *windows.GUID) (uintptr, error) { + if obj == 0 { + return 0, errors.New("nil COM object") + } + var out uintptr + hr, _, _ := syscall.SyscallN(vtableEntry(obj, 0), obj, uintptr(unsafe.Pointer(iid)), uintptr(unsafe.Pointer(&out))) + if uint32(hr) != sOK || out == 0 { + return 0, fmt.Errorf("QueryInterface failed: 0x%08x", uint32(hr)) + } + return out, nil +} + +func comCloseIfClosable(obj uintptr) { + if obj == 0 { + return + } + closable, err := comQueryInterface(obj, &iidClosable) + if err != nil { + return + } + defer comRelease(closable) + _, _, _ = syscall.SyscallN(vtableEntry(closable, 6), closable) +} + +func ensureRoInit() error { + hr, _, _ := procRoInitialize.Call(roInitMultithreaded) + code := uint32(hr) + if code == sOK || code == sFalse || code == rpcEChangedMode { + return nil + } + return fmt.Errorf("RoInitialize failed: 0x%08x", code) +} + +func newHString(s string) (uintptr, error) { + u16, err := windows.UTF16FromString(s) + if err != nil { + return 0, err + } + length := uint32(len(u16) - 1) + var hs uintptr + var ptr uintptr + if length > 0 { + ptr = uintptr(unsafe.Pointer(&u16[0])) + } + hr, _, _ := procWindowsCreateString.Call(ptr, uintptr(length), uintptr(unsafe.Pointer(&hs))) + if uint32(hr) != sOK { + return 0, fmt.Errorf("WindowsCreateString(%q) failed: 0x%08x", s, uint32(hr)) + } + return hs, nil +} + +func deleteHString(hs uintptr) { + if hs != 0 { + _, _, _ = procWindowsDeleteString.Call(hs) + } +} + +func hstringToGo(hs uintptr) string { + if hs == 0 { + return "" + } + var length uint32 + raw, _, _ := procWindowsGetStringRawBuffer.Call(hs, uintptr(unsafe.Pointer(&length))) + if raw == 0 || length == 0 { + return "" + } + buf := make([]uint16, length) + _, _, _ = procRtlMoveMemory.Call(uintptr(unsafe.Pointer(&buf[0])), raw, uintptr(length)*2) + return windows.UTF16ToString(buf) +} + +func activationFactory(className string, iid *windows.GUID) (uintptr, error) { + hs, err := newHString(className) + if err != nil { + return 0, err + } + defer deleteHString(hs) + var factory uintptr + hr, _, _ := procRoGetActivationFactory.Call(hs, uintptr(unsafe.Pointer(iid)), uintptr(unsafe.Pointer(&factory))) + if uint32(hr) != sOK || factory == 0 { + return 0, fmt.Errorf("RoGetActivationFactory(%s) failed: 0x%08x", className, uint32(hr)) + } + return factory, nil +} + +// ListWinOCRLanguages queries Windows.Media.Ocr.OcrEngine for installed +// recognizer language tags and the OS-reported MaxImageDimension. +func ListWinOCRLanguages() ([]string, int, error) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + if err := ensureRoInit(); err != nil { + return nil, defaultWinOCRMaxDimension, err + } + statics, err := activationFactory("Windows.Media.Ocr.OcrEngine", &iidOcrEngineStatics) + if err != nil { + return nil, defaultWinOCRMaxDimension, err + } + defer comRelease(statics) + + // IOcrEngineStatics::get_MaxImageDimension (slot 6) + var maxDim uint32 + hr, _, _ := syscall.SyscallN(vtableEntry(statics, 6), statics, uintptr(unsafe.Pointer(&maxDim))) + if uint32(hr) != sOK || maxDim == 0 { + maxDim = defaultWinOCRMaxDimension + } + + // IOcrEngineStatics::get_AvailableRecognizerLanguages (slot 7) + var vec uintptr + hr, _, _ = syscall.SyscallN(vtableEntry(statics, 7), statics, uintptr(unsafe.Pointer(&vec))) + if uint32(hr) != sOK || vec == 0 { + return nil, int(maxDim), fmt.Errorf("get_AvailableRecognizerLanguages failed: 0x%08x", uint32(hr)) + } + defer comRelease(vec) + + // IVectorView::get_Size (slot 7) + var count uint32 + hr, _, _ = syscall.SyscallN(vtableEntry(vec, 7), vec, uintptr(unsafe.Pointer(&count))) + if uint32(hr) != sOK { + return nil, int(maxDim), fmt.Errorf("IVectorView::get_Size failed: 0x%08x", uint32(hr)) + } + + langs := make([]string, 0, count) + for i := uint32(0); i < count; i++ { + var langObj uintptr + hr, _, _ = syscall.SyscallN(vtableEntry(vec, 6), vec, uintptr(i), uintptr(unsafe.Pointer(&langObj))) + if uint32(hr) != sOK || langObj == 0 { + continue + } + var tagHS uintptr + hr, _, _ = syscall.SyscallN(vtableEntry(langObj, 6), langObj, uintptr(unsafe.Pointer(&tagHS))) + if uint32(hr) == sOK && tagHS != 0 { + if tag := strings.TrimSpace(hstringToGo(tagHS)); tag != "" { + langs = append(langs, tag) + } + deleteHString(tagHS) + } + comRelease(langObj) + } + return langs, int(maxDim), nil +} + +// WinOCREngine invokes the official public WinRT API Windows.Media.Ocr directly +// via combase.dll COM vtables (CGO_ENABLED=0, zero PowerShell subprocesses). +type WinOCREngine struct { + mu sync.Mutex + closed bool + closing atomic.Bool + closeOnce sync.Once + closeCh chan struct{} + languageTag string + maxDim int + engine uintptr // IOcrEngine* + bufFactory uintptr // IBufferFactory* + bmpStatics uintptr // ISoftwareBitmapStatics* +} + +// NewWinOCREngine creates an OcrEngine bound to languageTag (or user profile +// languages when languageTag is empty). +func NewWinOCREngine(languageTag string) (*WinOCREngine, error) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + if err := ensureRoInit(); err != nil { + return nil, err + } + statics, err := activationFactory("Windows.Media.Ocr.OcrEngine", &iidOcrEngineStatics) + if err != nil { + return nil, err + } + defer comRelease(statics) + + var maxDim uint32 + hr, _, _ := syscall.SyscallN(vtableEntry(statics, 6), statics, uintptr(unsafe.Pointer(&maxDim))) + if uint32(hr) != sOK || maxDim == 0 { + maxDim = defaultWinOCRMaxDimension + } + + var engine uintptr + if tag := strings.TrimSpace(languageTag); tag != "" { + langFactory, err := activationFactory("Windows.Globalization.Language", &iidLanguageFactory) + if err != nil { + return nil, err + } + defer comRelease(langFactory) + + tagHS, err := newHString(tag) + if err != nil { + return nil, err + } + defer deleteHString(tagHS) + + var langObj uintptr + hr, _, _ = syscall.SyscallN(vtableEntry(langFactory, 6), langFactory, tagHS, uintptr(unsafe.Pointer(&langObj))) + if uint32(hr) != sOK || langObj == 0 { + return nil, fmt.Errorf("CreateLanguage(%q) failed: 0x%08x", tag, uint32(hr)) + } + defer comRelease(langObj) + + // IOcrEngineStatics::TryCreateFromLanguage (slot 9) + hr, _, _ = syscall.SyscallN(vtableEntry(statics, 9), statics, langObj, uintptr(unsafe.Pointer(&engine))) + if uint32(hr) != sOK || engine == 0 { + return nil, fmt.Errorf("OcrEngine.TryCreateFromLanguage(%q) returned nil (0x%08x)", tag, uint32(hr)) + } + } else { + // IOcrEngineStatics::TryCreateFromUserProfileLanguages (slot 10) + hr, _, _ = syscall.SyscallN(vtableEntry(statics, 10), statics, uintptr(unsafe.Pointer(&engine))) + if uint32(hr) != sOK || engine == 0 { + return nil, fmt.Errorf("OcrEngine.TryCreateFromUserProfileLanguages returned nil (0x%08x)", uint32(hr)) + } + } + + bufFactory, err := activationFactory("Windows.Storage.Streams.Buffer", &iidBufferFactory) + if err != nil { + comRelease(engine) + return nil, err + } + bmpStatics, err := activationFactory("Windows.Graphics.Imaging.SoftwareBitmap", &iidSoftwareBitmapStatic) + if err != nil { + comRelease(bufFactory) + comRelease(engine) + return nil, err + } + + return &WinOCREngine{ + closeCh: make(chan struct{}), + languageTag: languageTag, + maxDim: int(maxDim), + engine: engine, + bufFactory: bufFactory, + bmpStatics: bmpStatics, + }, nil +} + +func (e *WinOCREngine) Name() string { return "winocr" } +func (e *WinOCREngine) MaxDimension() int { return e.maxDim } + +func (e *WinOCREngine) Close() error { + // Signal any in-flight Recognize poll loop BEFORE acquiring e.mu so Close + // cancels the pending IAsyncInfo instead of blocking indefinitely. + e.closing.Store(true) + e.closeOnce.Do(func() { + if e.closeCh != nil { + close(e.closeCh) + } + }) + e.mu.Lock() + defer e.mu.Unlock() + if e.closed { + return nil + } + e.closed = true + comRelease(e.bmpStatics) + comRelease(e.bufFactory) + comRelease(e.engine) + e.bmpStatics, e.bufFactory, e.engine = 0, 0, 0 + return nil +} + +func (e *WinOCREngine) Recognize(ctx context.Context, img image.Image) (Result, error) { + if ctx == nil { + ctx = context.Background() + } + if _, hasDeadline := ctx.Deadline(); !hasDeadline { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, defaultWinOCRRecognizeBudget) + defer cancel() + } + if img == nil { + return Result{}, errors.New("winocr: nil image") + } + b := img.Bounds() + w, h := b.Dx(), b.Dy() + if w <= 0 || h <= 0 { + return Result{}, errors.New("winocr: empty image") + } + if e.maxDim > 0 && (w > e.maxDim || h > e.maxDim) { + return Result{}, fmt.Errorf("winocr: image %dx%d exceeds MaxImageDimension %d (crop ROI first)", w, h, e.maxDim) + } + + e.mu.Lock() + defer e.mu.Unlock() + if e.closed || e.engine == 0 { + return Result{}, errors.New("winocr: engine is closed") + } + + runtime.LockOSThread() + defer runtime.UnlockOSThread() + if err := ensureRoInit(); err != nil { + return Result{}, err + } + + // 1. Allocate WinRT Buffer and write BGRA8 pixels directly via IBufferByteAccess. + byteLen := uint32(w * h * 4) + var bufObj uintptr + hr, _, _ := syscall.SyscallN(vtableEntry(e.bufFactory, 6), e.bufFactory, uintptr(byteLen), uintptr(unsafe.Pointer(&bufObj))) + if uint32(hr) != sOK || bufObj == 0 { + return Result{}, fmt.Errorf("Buffer.Create(%d) failed: 0x%08x", byteLen, uint32(hr)) + } + defer comRelease(bufObj) + + // IBuffer::put_Length (slot 8) + hr, _, _ = syscall.SyscallN(vtableEntry(bufObj, 8), bufObj, uintptr(byteLen)) + if uint32(hr) != sOK { + return Result{}, fmt.Errorf("IBuffer::put_Length failed: 0x%08x", uint32(hr)) + } + + byteAccess, err := comQueryInterface(bufObj, &iidBufferByteAccess) + if err != nil { + return Result{}, err + } + defer comRelease(byteAccess) + + var rawPtr uintptr + // IBufferByteAccess::Buffer (slot 3, inherits directly from IUnknown) + hr, _, _ = syscall.SyscallN(vtableEntry(byteAccess, 3), byteAccess, uintptr(unsafe.Pointer(&rawPtr))) + if uint32(hr) != sOK || rawPtr == 0 { + return Result{}, fmt.Errorf("IBufferByteAccess::Buffer failed: 0x%08x", uint32(hr)) + } + bgra := make([]byte, byteLen) + copyImageToBGRA(img, bgra) + _, _, _ = procRtlMoveMemory.Call(rawPtr, uintptr(unsafe.Pointer(&bgra[0])), uintptr(byteLen)) + + // 2. ISoftwareBitmapStatics (Windows.Graphics.Imaging.idl, after IInspectable 0..5): + // 6=Copy, 7=Convert, 8=ConvertWithAlpha, 9=CreateCopyFromBuffer, + // 10=CreateCopyWithAlphaFromBuffer (verified by TestWinOCRLiveRecognitionAndLatency). + var bmpObj uintptr + hr, _, _ = syscall.SyscallN( + vtableEntry(e.bmpStatics, 10), + e.bmpStatics, + bufObj, + uintptr(bitmapPixelFormatBgra8), + uintptr(int32(w)), + uintptr(int32(h)), + uintptr(bitmapAlphaModePremul), + uintptr(unsafe.Pointer(&bmpObj)), + ) + if uint32(hr) != sOK || bmpObj == 0 { + return Result{}, fmt.Errorf("SoftwareBitmap.CreateCopyWithAlphaFromBuffer failed: 0x%08x", uint32(hr)) + } + defer func() { + comCloseIfClosable(bmpObj) + comRelease(bmpObj) + }() + + // 3. IOcrEngine::RecognizeAsync (slot 6) + var asyncOp uintptr + hr, _, _ = syscall.SyscallN(vtableEntry(e.engine, 6), e.engine, bmpObj, uintptr(unsafe.Pointer(&asyncOp))) + if uint32(hr) != sOK || asyncOp == 0 { + return Result{}, fmt.Errorf("OcrEngine.RecognizeAsync failed: 0x%08x", uint32(hr)) + } + defer comRelease(asyncOp) + + asyncInfo, err := comQueryInterface(asyncOp, &iidAsyncInfo) + if err != nil { + return Result{}, err + } + defer func() { + // IAsyncInfo::Close (slot 10) + _, _, _ = syscall.SyscallN(vtableEntry(asyncInfo, 10), asyncInfo) + comRelease(asyncInfo) + }() + + // Poll IAsyncInfo::get_Status (slot 7) until completion, engine close, or + // context cancellation, waking immediately on close/cancel instead of busy-sleeping. + waitStep := time.Millisecond + pollTimer := time.NewTimer(waitStep) + defer pollTimer.Stop() + for { + var status uint32 + hr, _, _ = syscall.SyscallN(vtableEntry(asyncInfo, 7), asyncInfo, uintptr(unsafe.Pointer(&status))) + if uint32(hr) != sOK { + return Result{}, fmt.Errorf("IAsyncInfo::get_Status failed: 0x%08x", uint32(hr)) + } + if status == asyncStatusCompleted { + break + } + if status == asyncStatusCanceled { + return Result{}, context.Canceled + } + if status == asyncStatusError { + var errCode uint32 + _, _, _ = syscall.SyscallN(vtableEntry(asyncInfo, 8), asyncInfo, uintptr(unsafe.Pointer(&errCode))) + return Result{}, fmt.Errorf("RecognizeAsync error: 0x%08x", errCode) + } + if e.closing.Load() { + _, _, _ = syscall.SyscallN(vtableEntry(asyncInfo, 9), asyncInfo) + return Result{}, errors.New("winocr: engine is closed") + } + if err := ctx.Err(); err != nil { + // IAsyncInfo::Cancel (slot 9) + _, _, _ = syscall.SyscallN(vtableEntry(asyncInfo, 9), asyncInfo) + return Result{}, err + } + if !pollTimer.Stop() { + select { + case <-pollTimer.C: + default: + } + } + pollTimer.Reset(waitStep) + if waitStep < 10*time.Millisecond { + waitStep *= 2 + if waitStep > 10*time.Millisecond { + waitStep = 10 * time.Millisecond + } + } + select { + case <-e.closeCh: + _, _, _ = syscall.SyscallN(vtableEntry(asyncInfo, 9), asyncInfo) + return Result{}, errors.New("winocr: engine is closed") + case <-ctx.Done(): + _, _, _ = syscall.SyscallN(vtableEntry(asyncInfo, 9), asyncInfo) + return Result{}, ctx.Err() + case <-pollTimer.C: + } + } + + // IAsyncOperation::GetResults (slot 8) + var ocrRes uintptr + hr, _, _ = syscall.SyscallN(vtableEntry(asyncOp, 8), asyncOp, uintptr(unsafe.Pointer(&ocrRes))) + if uint32(hr) != sOK || ocrRes == 0 { + return Result{}, fmt.Errorf("RecognizeAsync.GetResults failed: 0x%08x", uint32(hr)) + } + defer comRelease(ocrRes) + + return extractWinOCRResult(ocrRes) +} + +func extractWinOCRResult(ocrRes uintptr) (Result, error) { + out := Result{Backend: "winocr"} + + // IOcrResult (Windows.Media.Ocr.idl, after IInspectable 0..5): + // 6=get_Lines, 7=get_TextAngle, 8=get_Text (verified by TestWinOCRLiveRecognitionAndLatency). + var fullHS uintptr + hr, _, _ := syscall.SyscallN(vtableEntry(ocrRes, 8), ocrRes, uintptr(unsafe.Pointer(&fullHS))) + if uint32(hr) == sOK && fullHS != 0 { + out.Text = hstringToGo(fullHS) + deleteHString(fullHS) + } + + // IOcrResult::get_Lines (slot 6) + var linesVec uintptr + hr, _, _ = syscall.SyscallN(vtableEntry(ocrRes, 6), ocrRes, uintptr(unsafe.Pointer(&linesVec))) + if uint32(hr) != sOK || linesVec == 0 { + return out, nil + } + defer comRelease(linesVec) + + var lineCount uint32 + hr, _, _ = syscall.SyscallN(vtableEntry(linesVec, 7), linesVec, uintptr(unsafe.Pointer(&lineCount))) + if uint32(hr) != sOK { + return out, nil + } + + out.Lines = make([]Line, 0, lineCount) + for i := uint32(0); i < lineCount; i++ { + var lineObj uintptr + hr, _, _ = syscall.SyscallN(vtableEntry(linesVec, 6), linesVec, uintptr(i), uintptr(unsafe.Pointer(&lineObj))) + if uint32(hr) != sOK || lineObj == 0 { + continue + } + line := extractWinOCRLine(lineObj) + comRelease(lineObj) + if strings.TrimSpace(line.Text) != "" || len(line.Words) > 0 { + out.Lines = append(out.Lines, line) + } + } + return out, nil +} + +func extractWinOCRLine(lineObj uintptr) Line { + var line Line + // IOcrLine::get_Text (slot 7) + var textHS uintptr + hr, _, _ := syscall.SyscallN(vtableEntry(lineObj, 7), lineObj, uintptr(unsafe.Pointer(&textHS))) + if uint32(hr) == sOK && textHS != 0 { + line.Text = hstringToGo(textHS) + deleteHString(textHS) + } + + // IOcrLine::get_Words (slot 6) + var wordsVec uintptr + hr, _, _ = syscall.SyscallN(vtableEntry(lineObj, 6), lineObj, uintptr(unsafe.Pointer(&wordsVec))) + if uint32(hr) != sOK || wordsVec == 0 { + return line + } + defer comRelease(wordsVec) + + var wordCount uint32 + hr, _, _ = syscall.SyscallN(vtableEntry(wordsVec, 7), wordsVec, uintptr(unsafe.Pointer(&wordCount))) + if uint32(hr) != sOK { + return line + } + + line.Words = make([]Word, 0, wordCount) + for j := uint32(0); j < wordCount; j++ { + var wordObj uintptr + hr, _, _ = syscall.SyscallN(vtableEntry(wordsVec, 6), wordsVec, uintptr(j), uintptr(unsafe.Pointer(&wordObj))) + if uint32(hr) != sOK || wordObj == 0 { + continue + } + var rectF winRectF + // IOcrWord::get_BoundingRect (slot 6) + _, _, _ = syscall.SyscallN(vtableEntry(wordObj, 6), wordObj, uintptr(unsafe.Pointer(&rectF))) + // IOcrWord::get_Text (slot 7) + var wordHS uintptr + var wtext string + if hr2, _, _ := syscall.SyscallN(vtableEntry(wordObj, 7), wordObj, uintptr(unsafe.Pointer(&wordHS))); uint32(hr2) == sOK && wordHS != 0 { + wtext = hstringToGo(wordHS) + deleteHString(wordHS) + } + comRelease(wordObj) + + wr := image.Rect( + int(math.Floor(float64(rectF.X))), + int(math.Floor(float64(rectF.Y))), + int(math.Ceil(float64(rectF.X+rectF.Width))), + int(math.Ceil(float64(rectF.Y+rectF.Height))), + ) + line.Words = append(line.Words, Word{Text: wtext, Rect: wr}) + if line.Rect.Empty() { + line.Rect = wr + } else { + line.Rect = line.Rect.Union(wr) + } + } + return line +} + +func copyImageToBGRA(img image.Image, dst []byte) { + b := img.Bounds() + w, h := b.Dx(), b.Dy() + if rgba, ok := img.(*image.RGBA); ok { + for y := 0; y < h; y++ { + srow := rgba.Pix[(b.Min.Y+y-rgba.Rect.Min.Y)*rgba.Stride+(b.Min.X-rgba.Rect.Min.X)*4:] + drow := dst[y*w*4:] + for x := 0; x < w; x++ { + off := x * 4 + drow[off+0] = srow[off+2] // B + drow[off+1] = srow[off+1] // G + drow[off+2] = srow[off+0] // R + drow[off+3] = srow[off+3] // A + } + } + return + } + for y := 0; y < h; y++ { + drow := dst[y*w*4:] + for x := 0; x < w; x++ { + r, g, bl, a := img.At(b.Min.X+x, b.Min.Y+y).RGBA() + off := x * 4 + drow[off+0] = uint8(bl >> 8) + drow[off+1] = uint8(g >> 8) + drow[off+2] = uint8(r >> 8) + drow[off+3] = uint8(a >> 8) + } + } +} diff --git a/internal/macos/autoinstall/rules/data/desktop.json b/internal/macos/autoinstall/rules/data/desktop.json new file mode 100644 index 0000000..744db94 --- /dev/null +++ b/internal/macos/autoinstall/rules/data/desktop.json @@ -0,0 +1,24 @@ +{ + "version": 1, + "rules": [ + { + "id": "desktop.keyboard_assistant", + "stage": "desktop", + "priority": 90, + "match": { + "roi": "modal", + "any_of": [ + "Keyboard Setup Assistant", + "键盘设置助理", + "鍵盤設定輔助程式", + "キーボード設定アシスタント" + ], + "fuzzy": true + }, + "actions": [ + { "op": "key", "key": "q", "modifiers": ["meta_l"] } + ], + "verify": { "wait_change_ms": 5000, "max_retries": 2 } + } + ] +} diff --git a/internal/macos/autoinstall/rules/data/recovery.json b/internal/macos/autoinstall/rules/data/recovery.json new file mode 100644 index 0000000..fb9b8dd --- /dev/null +++ b/internal/macos/autoinstall/rules/data/recovery.json @@ -0,0 +1,52 @@ +{ + "version": 1, + "rules": [ + { + "id": "recovery.language", + "stage": "recovery", + "priority": 80, + "match": { + "roi": "body", + "any_of": [ + "Use English for the main language", + "以简体中文作为主要语言", + "使用繁體中文作為主要語言", + "主に日本語を使用する" + ], + "fuzzy": true + }, + "actions": [ + { "op": "key", "key": "ret" } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + }, + { + "id": "recovery.main", + "stage": "recovery", + "priority": 70, + "match": { + "roi": "body", + "any_of": [ + "Reinstall macOS", + "重新安装 macOS", + "重新安裝 macOS", + "macOSを再インストール", + "Restore from Time Machine", + "从时间机器恢复", + "從時光機回復", + "Time Machineから復元" + ], + "fuzzy": true + }, + "actions": [ + { + "op": "click_ocr", + "roi": "menu_bar", + "any_of": ["Utilities", "实用工具", "工具程式", "ユーティリティ"], + "fuzzy": true + } + ], + "verify": { "wait_change_ms": 4000, "max_retries": 2 } + } + ] +} diff --git a/internal/macos/autoinstall/rules/data/setup-assistant.json b/internal/macos/autoinstall/rules/data/setup-assistant.json new file mode 100644 index 0000000..135adc5 --- /dev/null +++ b/internal/macos/autoinstall/rules/data/setup-assistant.json @@ -0,0 +1,473 @@ +{ + "version": 1, + "rules": [ + { + "id": "setup.apple_account_skip_modal", + "stage": "setup_assistant", + "priority": 100, + "match": { + "roi": "modal", + "any_of": [ + "Are you sure you want to skip", + "确定要跳过", + "確定要略過", + "スキップしてもよろしいですか" + ], + "fuzzy": true + }, + "actions": [ + { + "op": "click_ocr", + "roi": "modal", + "any_of": ["Skip", "跳过", "略過", "スキップ"], + "fuzzy": true + } + ], + "verify": { "wait_change_ms": 6000, "max_retries": 2 } + }, + { + "id": "setup.terms_modal", + "stage": "setup_assistant", + "priority": 100, + "requires_sla": true, + "match": { + "roi": "modal", + "any_of": [ + "I have read and agree", + "我已阅读并同意", + "我已閱讀並同意", + "同意します" + ], + "fuzzy": true + }, + "actions": [ + { + "op": "click_blue_button", + "roi": "modal", + "any_of": ["Agree", "同意"], + "fuzzy": true + } + ], + "verify": { "wait_change_ms": 6000, "max_retries": 2 } + }, + { + "id": "setup.filevault_modal", + "stage": "setup_assistant", + "priority": 100, + "allow_high_risk": true, + "match": { + "roi": "modal", + "any_of": [ + "Mac Data Will Not Be Securely Encrypted", + "数据将不会被安全加密", + "資料將不會安全加密", + "暗号化されません" + ], + "fuzzy": true + }, + "actions": [ + { + "op": "click_ocr", + "roi": "modal", + "any_of": ["Continue Without", "不加密继续", "继续", "Continue", "Don't Use", "不使用"], + "fuzzy": true + } + ], + "verify": { "wait_change_ms": 6000, "max_retries": 2 } + }, + { + "id": "setup.location_modal", + "stage": "setup_assistant", + "priority": 98, + "match": { + "roi": "modal", + "any_of": [ + "Are you sure you don't want to use Location Services", + "确定不使用定位服务", + "確定不使用定位服務" + ], + "fuzzy": true + }, + "actions": [ + { + "op": "click_ocr", + "roi": "modal", + "any_of": ["Don't Use", "不使用"], + "fuzzy": true + } + ], + "verify": { "wait_change_ms": 6000, "max_retries": 2 } + }, + { + "id": "setup.hello", + "stage": "setup_assistant", + "priority": 40, + "match": { + "roi": "body", + "any_of": ["hello", "你好", "bonjour", "hola", "こんにちは"], + "fuzzy": false + }, + "actions": [ + { "op": "click_circle_or_key", "roi": "action_bar", "fallback_key": "spc" } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + }, + { + "id": "setup.language", + "stage": "setup_assistant", + "priority": 85, + "match": { + "roi": "title_band", + "any_of": ["Select Your Language", "选择语言", "選擇語言", "言語を選択"], + "fuzzy": true + }, + "actions": [ + { "op": "key", "key": "ret" } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + }, + { + "id": "setup.region", + "stage": "setup_assistant", + "priority": 80, + "match": { + "roi": "title_band", + "any_of": [ + "Select Your Country or Region", + "选择国家或地区", + "選擇國家或地區", + "国または地域を選択" + ], + "fuzzy": true + }, + "actions": [ + { "op": "click_blue_button", "roi": "action_bar", "any_of": ["Continue", "继续", "繼續", "続ける"], "fuzzy": true } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + }, + { + "id": "setup.written_lang", + "stage": "setup_assistant", + "priority": 78, + "match": { + "roi": "title_band", + "any_of": [ + "Written and Spoken Languages", + "书面和口头语言", + "書寫和口說語言", + "文字入力および音声入力の言語" + ], + "fuzzy": true + }, + "actions": [ + { "op": "click_blue_button", "roi": "action_bar", "any_of": ["Continue", "继续", "繼續", "続ける"], "fuzzy": true } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + }, + { + "id": "setup.migration", + "stage": "setup_assistant", + "priority": 76, + "match": { + "roi": "title_band", + "any_of": [ + "Migration Assistant", + "Transfer Your Data", + "迁移助理", + "将你的数据传输到此 Mac", + "系統移轉輔助程式", + "移行アシスタント" + ], + "fuzzy": true + }, + "actions": [ + { "op": "click_ocr", "roi": "action_bar", "any_of": ["Not Now", "以后", "稍後", "今はしない"], "fuzzy": true } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + }, + { + "id": "setup.accessibility", + "stage": "setup_assistant", + "priority": 75, + "match": { + "roi": "title_band", + "any_of": ["Accessibility", "辅助功能", "輔助使用", "アクセシビリティ"], + "fuzzy": true + }, + "actions": [ + { "op": "click_ocr", "roi": "action_bar", "any_of": ["Not Now", "以后", "稍後", "今はしない"], "fuzzy": true } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + }, + { + "id": "setup.network", + "stage": "setup_assistant", + "priority": 74, + "match": { + "roi": "title_band", + "any_of": [ + "Select Your Wi-Fi Network", + "Internet Connection", + "互联网连接", + "选择无线局域网", + "Wi-Fiネットワークを選択" + ], + "fuzzy": true + }, + "actions": [ + { + "op": "click_blue_button", + "roi": "action_bar", + "any_of": ["Continue", "继续", "繼續", "続ける", "Other Network Options", "其他网络选项"], + "fuzzy": true + } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + }, + { + "id": "setup.privacy", + "stage": "setup_assistant", + "priority": 72, + "match": { + "roi": "title_band", + "any_of": ["Data & Privacy", "数据与隐私", "資料與隱私權", "データとプライバシー"], + "fuzzy": true + }, + "actions": [ + { "op": "click_blue_button", "roi": "action_bar", "any_of": ["Continue", "继续", "繼續", "続ける"], "fuzzy": true } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + }, + { + "id": "setup.create_account", + "stage": "setup_assistant", + "priority": 70, + "match": { + "roi": "title_band", + "any_of": [ + "Create a Computer Account", + "Create a Mac Account", + "创建电脑账户", + "创建 Mac 账户", + "建立電腦帳號", + "コンピュータアカウントを作成" + ], + "fuzzy": true + }, + "actions": [ + { "op": "fill_account_form", "roi": "body" }, + { "op": "click_blue_button", "roi": "action_bar", "any_of": ["Continue", "继续", "繼續", "続ける"], "fuzzy": true } + ], + "verify": { "wait_change_ms": 12000, "max_retries": 2 } + }, + { + "id": "setup.apple_account", + "stage": "setup_assistant", + "priority": 68, + "match": { + "roi": "title_band", + "any_of": [ + "Sign In with Your Apple", + "使用你的 Apple 账户登录", + "使用你的 Apple ID 登录", + "使用你的 Apple 帳號登入", + "Apple Accountでサインイン" + ], + "fuzzy": true + }, + "actions": [ + { "op": "click_ocr", "roi": "action_bar", "any_of": ["Set Up Later", "稍后设置", "稍後設定", "あとで設定"], "fuzzy": true } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + }, + { + "id": "setup.terms", + "stage": "setup_assistant", + "priority": 66, + "requires_sla": true, + "match": { + "roi": "title_band", + "any_of": ["Terms and Conditions", "条款与条件", "條款與約定", "利用規約"], + "fuzzy": true + }, + "actions": [ + { "op": "click_blue_button", "roi": "action_bar", "any_of": ["Agree", "同意"], "fuzzy": true } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + }, + { + "id": "setup.age_range", + "stage": "setup_assistant", + "priority": 64, + "match": { + "roi": "title_band", + "any_of": ["Age Range", "选择年龄段", "年龄范围", "年齡範圍", "年齢層"], + "fuzzy": true + }, + "actions": [ + { "op": "select_pref_ocr", "roi": "body", "pref_key": "age_range" }, + { "op": "click_blue_button", "roi": "action_bar", "any_of": ["Continue", "继续", "繼續", "続ける"], "fuzzy": true } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + }, + { + "id": "setup.location", + "stage": "setup_assistant", + "priority": 62, + "match": { + "roi": "title_band", + "any_of": ["Enable Location Services", "Location Services", "启用定位服务", "定位服务", "定位服務", "位置情報サービス"], + "fuzzy": true + }, + "actions": [ + { + "op": "ensure_checkbox", + "roi": "body", + "any_of": ["Enable Location Services", "启用定位服务", "啟用定位服務"], + "want_checked": false, + "fuzzy": true + }, + { "op": "click_blue_button", "roi": "action_bar", "any_of": ["Continue", "继续", "繼續", "続ける"], "fuzzy": true } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + }, + { + "id": "setup.timezone", + "stage": "setup_assistant", + "priority": 60, + "match": { + "roi": "title_band", + "any_of": ["Select Your Time Zone", "选择时区", "選擇時區", "時間帯を選択"], + "fuzzy": true + }, + "actions": [ + { "op": "click_blue_button", "roi": "action_bar", "any_of": ["Continue", "继续", "繼續", "続ける"], "fuzzy": true } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + }, + { + "id": "setup.analytics", + "stage": "setup_assistant", + "priority": 58, + "match": { + "roi": "title_band", + "any_of": ["Analytics", "分析", "解析"], + "fuzzy": true + }, + "actions": [ + { + "op": "ensure_checkbox", + "roi": "body", + "any_of": ["Share Mac Analytics", "与 Apple 共享 Mac 分析", "共享 Mac 分析"], + "want_checked": false, + "fuzzy": true + }, + { "op": "click_blue_button", "roi": "action_bar", "any_of": ["Continue", "继续", "繼續", "続ける"], "fuzzy": true } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + }, + { + "id": "setup.screen_time", + "stage": "setup_assistant", + "priority": 56, + "match": { + "roi": "title_band", + "any_of": ["Screen Time", "屏幕使用时间", "螢幕使用時間", "スクリーンタイム"], + "fuzzy": true + }, + "actions": [ + { "op": "click_ocr", "roi": "action_bar", "any_of": ["Set Up Later", "稍后设置", "稍後設定", "あとで設定"], "fuzzy": true } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + }, + { + "id": "setup.siri", + "stage": "setup_assistant", + "priority": 54, + "match": { + "roi": "title_band", + "any_of": ["Siri", "Apple Intelligence"], + "fuzzy": true + }, + "actions": [ + { "op": "click_ocr", "roi": "action_bar", "any_of": ["Set Up Later", "Not Now", "稍后设置", "以后", "稍後設定", "あとで設定"], "fuzzy": true } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + }, + { + "id": "setup.filevault", + "stage": "setup_assistant", + "priority": 52, + "allow_high_risk": true, + "match": { + "roi": "title_band", + "any_of": [ + "FileVault", + "Your Mac is Ready for FileVault", + "文件保险箱", + "檔案保險箱" + ], + "fuzzy": true + }, + "actions": [ + { + "op": "ensure_checkbox", + "roi": "body", + "any_of": ["Turn on FileVault", "打开文件保险箱", "开启文件保险箱", "開啟檔案保險箱"], + "want_checked": false, + "fuzzy": true + }, + { + "op": "click_ocr", + "roi": "action_bar", + "any_of": ["Not Now", "Set Up Later", "以后", "稍后设置", "Continue", "继续"], + "fuzzy": true + } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + }, + { + "id": "setup.appearance", + "stage": "setup_assistant", + "priority": 50, + "match": { + "roi": "title_band", + "any_of": ["Choose Your Look", "选择外观", "選擇外觀", "外観モードを選択"], + "fuzzy": true + }, + "actions": [ + { "op": "select_pref_ocr", "roi": "body", "pref_key": "appearance" }, + { "op": "click_blue_button", "roi": "action_bar", "any_of": ["Continue", "继续", "繼續", "続ける"], "fuzzy": true } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + }, + { + "id": "setup.auto_update", + "stage": "setup_assistant", + "priority": 48, + "match": { + "roi": "title_band", + "any_of": ["Update Mac Automatically", "自动更新 Mac", "自動更新 Mac", "Macを自動的にアップデート"], + "fuzzy": true + }, + "actions": [ + { "op": "click_ocr", "roi": "action_bar", "any_of": ["Not Now", "以后", "Continue", "继续"], "fuzzy": true } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + }, + { + "id": "setup.welcome_mac", + "stage": "setup_assistant", + "priority": 45, + "match": { + "roi": "title_band", + "any_of": ["Welcome to Mac", "欢迎使用 Mac", "歡迎使用 Mac", "Macへようこそ"], + "fuzzy": true + }, + "actions": [ + { "op": "click_blue_button", "roi": "action_bar", "any_of": ["Continue", "继续", "Get Started", "开始使用"], "fuzzy": true } + ], + "verify": { "wait_change_ms": 8000, "max_retries": 2 } + } + ] +} diff --git a/internal/macos/autoinstall/rules/engine.go b/internal/macos/autoinstall/rules/engine.go new file mode 100644 index 0000000..4bf2223 --- /dev/null +++ b/internal/macos/autoinstall/rules/engine.go @@ -0,0 +1,341 @@ +package rules + +import ( + "embed" + "encoding/json" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "unicode" +) + +//go:embed data/*.json +var builtinFS embed.FS + +// RulePack is a pure declarative JSON rule collection (no executable scripts). +type RulePack struct { + Version int `json:"version"` + Rules []Rule `json:"rules"` +} + +// Rule describes one page/modal recognition rule and its safe declarative actions. +type Rule struct { + ID string `json:"id"` + Stage string `json:"stage"` // "recovery" | "setup_assistant" | "desktop" + Priority int `json:"priority"` + RequiresSLA bool `json:"requires_sla,omitempty"` + AllowHighRisk bool `json:"allow_high_risk,omitempty"` + Match Match `json:"match"` + Actions []Action `json:"actions"` + Verify Verify `json:"verify,omitempty"` +} + +type Match struct { + ROI string `json:"roi"` + AnyOf []string `json:"any_of"` + AllOf []string `json:"all_of,omitempty"` + Fuzzy bool `json:"fuzzy,omitempty"` +} + +type Action struct { + Op string `json:"op"` // click_ocr | click_blue_button | key | ensure_checkbox | fill_account_form | select_pref_ocr | click_circle_or_key | pause_for_user + ROI string `json:"roi,omitempty"` + AnyOf []string `json:"any_of,omitempty"` + Fuzzy bool `json:"fuzzy,omitempty"` + Key string `json:"key,omitempty"` + Modifiers []string `json:"modifiers,omitempty"` + WantChecked *bool `json:"want_checked,omitempty"` + PrefKey string `json:"pref_key,omitempty"` + FallbackKey string `json:"fallback_key,omitempty"` + PauseReason string `json:"pause_reason,omitempty"` +} + +type Verify struct { + WaitChangeMS int `json:"wait_change_ms,omitempty"` + MaxRetries int `json:"max_retries,omitempty"` +} + +var allowedOps = map[string]bool{ + "click_ocr": true, + "click_blue_button": true, + "key": true, + "ensure_checkbox": true, + "fill_account_form": true, + "select_pref_ocr": true, + "click_circle_or_key": true, + "pause_for_user": true, +} + +var allowedStages = map[string]bool{ + "recovery": true, + "setup_assistant": true, + "desktop": true, +} + +// HighRiskKeywords trigger an immediate safety pause if present on screen and +// not explicitly handled by an AllowHighRisk rule. +var HighRiskKeywords = []string{ + "erase", "抹掉", "抹除", + "recovery key", "恢复密钥", "復原密鑰", + "two-factor", "双重认证", "雙重認證", + "refusing to erase", "multiple eligible disks", "multiple candidate disks", "already has partitions", "[y/n]", "no writable target", "offline installer package not found", + "an error occurred", "发生错误", "安装失败", "installation failed", + "mac data will not be securely encrypted", +} + +// TerminalHighRiskKeywords catches real abort, error, or interactive non-blank +// disk prompts from REIMSHELP/install.sh without falsely matching normal blank +// VM disk formatting ("Started erase on disk0" / "Finished erase on disk0"). +var TerminalHighRiskKeywords = []string{ + "refusing to erase", + "already has partitions", + "all data on it will be lost", + "multiple eligible disks", + "multiple candidate disks", + "[y/n]", + "no writable target", + "offline installer package not found", + "install macos app not found", + "command not found", + "no such file or directory", + "aborted", + "an error occurred", + "installation failed", + "发生错误", + "安装失败", +} + +// Engine holds validated, priority-sorted declarative rules. +type Engine struct { + rules []Rule +} + +// LoadEngine loads embedded built-in rule packs and overlays any user JSON +// rule patches found under /rules/*.json. +func LoadEngine(dataDir string) (*Engine, error) { + byID := map[string]Rule{} + + entries, err := builtinFS.ReadDir("data") + if err != nil { + return nil, err + } + for _, e := range entries { + if e.IsDir() || !strings.HasSuffix(e.Name(), ".json") { + continue + } + raw, err := builtinFS.ReadFile("data/" + e.Name()) + if err != nil { + return nil, err + } + if err := mergePack(byID, raw, e.Name()); err != nil { + return nil, err + } + } + + if strings.TrimSpace(dataDir) != "" { + userDir := filepath.Join(dataDir, "rules") + if userEntries, err := os.ReadDir(userDir); err == nil { + for _, e := range userEntries { + if e.IsDir() || !strings.HasSuffix(strings.ToLower(e.Name()), ".json") { + continue + } + raw, err := os.ReadFile(filepath.Join(userDir, e.Name())) + if err != nil { + return nil, err + } + if err := mergePack(byID, raw, e.Name()); err != nil { + return nil, err + } + } + } + } + + list := make([]Rule, 0, len(byID)) + for _, r := range byID { + list = append(list, r) + } + sort.Slice(list, func(i, j int) bool { + if list[i].Priority != list[j].Priority { + return list[i].Priority > list[j].Priority + } + return list[i].ID < list[j].ID + }) + return &Engine{rules: list}, nil +} + +func mergePack(byID map[string]Rule, raw []byte, source string) error { + dec := json.NewDecoder(strings.NewReader(string(raw))) + dec.DisallowUnknownFields() + var pack RulePack + if err := dec.Decode(&pack); err != nil { + return fmt.Errorf("parse rule pack %s: %w", source, err) + } + for _, r := range pack.Rules { + if err := validateRule(r); err != nil { + return fmt.Errorf("rule %q in %s: %w", r.ID, source, err) + } + byID[r.ID] = r + } + return nil +} + +func validateRule(r Rule) error { + if strings.TrimSpace(r.ID) == "" { + return fmt.Errorf("empty rule id") + } + if !allowedStages[r.Stage] { + return fmt.Errorf("unsupported stage %q", r.Stage) + } + if len(r.Match.AnyOf) == 0 && len(r.Match.AllOf) == 0 { + return fmt.Errorf("match must specify any_of or all_of") + } + if len(r.Actions) == 0 { + return fmt.Errorf("rule must declare at least one action") + } + for _, act := range r.Actions { + if !allowedOps[act.Op] { + return fmt.Errorf("unsupported action op %q", act.Op) + } + } + return nil +} + +// RulesForStage returns priority-ordered rules for stage. +func (e *Engine) RulesForStage(stage string) []Rule { + var out []Rule + for _, r := range e.rules { + if r.Stage == stage { + out = append(out, r) + } + } + return out +} + +// MatchScreen evaluates all rules for stage against ROI text maps (roiName -> full text). +func (e *Engine) MatchScreen(stage string, roiTexts map[string]string) (Rule, bool) { + for _, r := range e.rules { + if r.Stage != stage { + continue + } + text := roiTexts[r.Match.ROI] + if !hasMeaningfulOCRText(text) { + text = roiTexts["full"] + } + if matchesRuleText(r.Match, text) { + return r, true + } + } + return Rule{}, false +} + +func hasMeaningfulOCRText(s string) bool { + letters := 0 + for _, r := range NormalizeText(s) { + if unicode.IsLetter(r) { + letters++ + if letters >= 2 { + return true + } + } + } + return false +} + +func matchesRuleText(m Match, text string) bool { + if len(m.AnyOf) > 0 { + ok := false + for _, phrase := range m.AnyOf { + if MatchPhrase(text, phrase, m.Fuzzy) { + ok = true + break + } + } + if !ok { + return false + } + } + for _, phrase := range m.AllOf { + if !MatchPhrase(text, phrase, m.Fuzzy) { + return false + } + } + return true +} + +// DetectHighRiskKeyword returns the first matching high-risk keyword in text. +// Besides exact unnegated matching, it applies guarded fuzzy tolerance for +// single-character OCR noise (full fuzzy for long phrases >= 8 compact runes, +// and whole-word Levenshtein <= 1 for 5+ char ASCII words like "erase" so +// benign words like "please" or "ease" never false-positive). +func DetectHighRiskKeyword(text string) (string, bool) { + for _, kw := range HighRiskKeywords { + if matchHighRiskKeyword(text, kw) { + return kw, true + } + } + return "", false +} + +// DetectTerminalHighRiskKeyword checks Recovery Terminal output for real +// non-blank disk prompts or script errors while allowing normal blank-disk +// diskutil erase output. +func DetectTerminalHighRiskKeyword(text string) (string, bool) { + for _, kw := range TerminalHighRiskKeywords { + if matchHighRiskKeyword(text, kw) { + return kw, true + } + } + return "", false +} + +func matchHighRiskKeyword(text, kw string) bool { + if MatchPhrase(text, kw, false) { + return true + } + nc := CompactText(kw) + nr := []rune(nc) + if len(nr) >= 8 { + return MatchPhrase(text, kw, true) + } + // Whole-word fuzzy check for single ASCII high-risk words (e.g. "erase" vs OCR "erasc"). + if len(nr) >= 5 && isPureASCIIWord(nc) { + return matchASCIIWordFuzzy(text, nr) + } + return false +} + +func isPureASCIIWord(s string) bool { + if s == "" { + return false + } + for i := 0; i < len(s); i++ { + if !isASCIILetter(s[i]) { + return false + } + } + return true +} + +func matchASCIIWordFuzzy(text string, needle []rune) bool { + norm := NormalizeText(text) + if norm == "" { + return false + } + tokens := strings.FieldsFunc(norm, func(r rune) bool { + return !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '\'' + }) + for i, tok := range tokens { + if len(tok) < len(needle) || !isPureASCIIWord(tok) { + continue + } + if i > 0 && isPrecededByNegation(tokens[i-1]) { + continue + } + if levenshtein([]rune(tok), needle) <= 1 { + return true + } + } + return false +} diff --git a/internal/macos/autoinstall/rules/normalize.go b/internal/macos/autoinstall/rules/normalize.go new file mode 100644 index 0000000..9e6e8f7 --- /dev/null +++ b/internal/macos/autoinstall/rules/normalize.go @@ -0,0 +1,547 @@ +package rules + +import ( + "image" + "strings" + "unicode" + + "github.com/Nwflower/reims-go/internal/macos/autoinstall/ocr" +) + +func isCJK(r rune) bool { + return unicode.Is(unicode.Han, r) || unicode.Is(unicode.Hiragana, r) || unicode.Is(unicode.Katakana, r) || unicode.Is(unicode.Hangul, r) +} + +// NormalizeText removes spaces inserted between CJK runes by Windows.Media.Ocr +// (e.g. "实 用 工 具" -> "实用工具"), folds full-width forms to ASCII, lowercases, +// and trims punctuation and ellipses. +func NormalizeText(s string) string { + var runes []rune + for _, r := range s { + if r >= 0xFF01 && r <= 0xFF5E { + r = r - 0xFF01 + 0x21 + } else if r == 0x3000 { + r = ' ' + } + if r == '…' { + continue + } + r = unicode.ToLower(r) + runes = append(runes, r) + } + var out []rune + for i := 0; i < len(runes); i++ { + r := runes[i] + if unicode.IsSpace(r) { + if len(out) == 0 { + continue + } + prev := out[len(out)-1] + // Look ahead to next non-space rune. + j := i + 1 + for j < len(runes) && unicode.IsSpace(runes[j]) { + j++ + } + if j >= len(runes) { + break + } + next := runes[j] + i = j - 1 + // Drop spaces adjacent to CJK characters to reverse WinRT spacing. + if isCJK(prev) || isCJK(next) { + continue + } + out = append(out, ' ') + continue + } + out = append(out, r) + } + trimmed := strings.TrimSpace(string(out)) + trimmed = strings.Trim(trimmed, ".,:;!?()[]{}\"'`~-—–•·") + return trimmed +} + +// CompactText removes all spaces after NormalizeText for tolerant phrase matching. +func CompactText(s string) string { + return strings.ReplaceAll(NormalizeText(s), " ", "") +} + +// MatchPhrase matches needle against haystack using priority: +// 1. exact normalized match +// 2. unnegated substring match (normalized or space-compacted) +// 3. optional Levenshtein distance <= 1 for normalized needles >= 4 runes +// (avoiding high-risk negation inversions such as "use" vs "don't use", +// "agree" vs "disagree", or "同意" vs "不同意") +func MatchPhrase(haystack, needle string, fuzzy bool) bool { + hn := NormalizeText(haystack) + nn := NormalizeText(needle) + if nn == "" || hn == "" { + return false + } + hc := CompactText(haystack) + nc := CompactText(needle) + needleNeg := startsWithNegation(nc) + + if hn == nn { + return true + } + if hasUnnegatedMatch(hn, nn, needleNeg) { + return true + } + if nc != "" && hasUnnegatedMatch(hc, nc, needleNeg) { + return true + } + // If every exact occurrence of needle in haystack was negated (e.g. "不使用" vs "使用"), + // do not let fuzzy matching bypass the negation guard. + if !needleNeg && nc != "" && strings.Contains(hc, nc) { + return false + } + if !fuzzy { + return false + } + nr := []rune(nc) + minFuzzy := 4 + if isPureASCIIWord(nc) { + // Short pure-ASCII needles (e.g. "siri", "skip", "agree") collide easily + // with unrelated 3-5 char sliding substrings at Levenshtein <= 1. + minFuzzy = 6 + } + if len(nr) < minFuzzy { + return false + } + hr := []rune(hc) + if len(hr) < len(nr)-1 { + return false + } + for start := 0; start < len(hr); start++ { + if !needleNeg && isPrecededByNegation(string(hr[:start])) { + continue + } + for _, span := range []int{len(nr) - 1, len(nr), len(nr) + 1} { + if span <= 0 || start+span > len(hr) { + continue + } + cand := hr[start : start+span] + if !needleNeg && startsWithNegation(string(cand)) { + continue + } + if levenshtein(cand, nr) <= 1 { + return true + } + } + } + return false +} + +var ( + cjkNegPrefixes = []string{"不", "未", "非", "别"} + latinNegPrefixes = []string{"don't", "dont", "not", "no", "dis"} +) + +func startsWithNegation(compact string) bool { + for _, p := range cjkNegPrefixes { + if strings.HasPrefix(compact, p) { + return true + } + } + for _, p := range latinNegPrefixes { + if strings.HasPrefix(compact, p) { + return true + } + } + return false +} + +func isASCIILetter(b byte) bool { + return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') +} + +// isPrecededByNegation reports whether prefix immediately ends with a negation +// token that would invert a following positive phrase. +func isPrecededByNegation(prefix string) bool { + trimmed := strings.TrimRight(prefix, " ") + if trimmed == "" { + return false + } + for _, p := range cjkNegPrefixes { + if strings.HasSuffix(trimmed, p) { + return true + } + } + for _, p := range latinNegPrefixes { + if !strings.HasSuffix(trimmed, p) { + continue + } + // Require a word boundary before Latin negation prefixes when spaces are + // present (or start of string) so words like "marino" do not look like "no". + before := len(trimmed) - len(p) + if before == 0 || !isASCIILetter(trimmed[before-1]) { + return true + } + // Also catch joined compact Latin forms like "cannot" + "agree" or "didn't" + "use". + if p == "not" && strings.HasSuffix(trimmed, "cannot") { + return true + } + } + return false +} + +func hasUnnegatedMatch(haystack, needle string, needleNeg bool) bool { + if needle == "" { + return false + } + offset := 0 + for { + idx := strings.Index(haystack[offset:], needle) + if idx < 0 { + return false + } + pos := offset + idx + if needleNeg || !isPrecededByNegation(haystack[:pos]) { + // For pure Latin needles in spaced text, reject mid-word suffixes like + // "disagree" matching "agree" even if preceded by another prefix. + if isASCIILetter(needle[0]) && pos > 0 && isASCIILetter(haystack[pos-1]) && strings.Contains(haystack, " ") { + offset = pos + 1 + continue + } + return true + } + offset = pos + 1 + } +} + +func levenshtein(a, b []rune) int { + if len(a) == 0 { + return len(b) + } + if len(b) == 0 { + return len(a) + } + prev := make([]int, len(b)+1) + cur := make([]int, len(b)+1) + for j := range prev { + prev[j] = j + } + for i := 1; i <= len(a); i++ { + cur[0] = i + for j := 1; j <= len(b); j++ { + cost := 0 + if a[i-1] != b[j-1] { + cost = 1 + } + m := prev[j] + 1 + if cur[j-1]+1 < m { + m = cur[j-1] + 1 + } + if prev[j-1]+cost < m { + m = prev[j-1] + cost + } + cur[j] = m + } + prev, cur = cur, prev + } + return prev[len(b)] +} + +type scoredHit struct { + line ocr.Line + pt image.Point + tier int // 0 = exact whole line, 1 = short button/action line, 2 = sentence/prose line + wordCount int + extraLen int + centerY int +} + +func betterScoredHit(a, b scoredHit) bool { + if a.tier != b.tier { + return a.tier < b.tier + } + if a.wordCount != b.wordCount { + return a.wordCount < b.wordCount + } + if a.extraLen != b.extraLen { + return a.extraLen < b.extraLen + } + // Dialog buttons sit below explanatory body prose inside modal/body ROIs. + return a.centerY > b.centerY +} + +// FindHit locates the best matching word or line rectangle among OCR lines for +// any candidate phrase and returns its clickable center point. +func FindHit(lines []ocr.Line, candidates []string, fuzzy bool) (ocr.Line, image.Point, bool) { + // Pass 0: exact whole-line normalized match (isolated buttons such as "Skip", + // "Don't Use", "Set Up Later", "跳过" beat any occurrence inside body prose). + for _, cand := range candidates { + wantNorm := NormalizeText(cand) + if wantNorm == "" { + continue + } + var ( + best scoredHit + found bool + ) + for _, ln := range lines { + if ln.Rect.Empty() || NormalizeText(ln.Text) != wantNorm { + continue + } + pt := rectCenter(ln.Rect) + h := scoredHit{line: ln, pt: pt, tier: 0, wordCount: len(ln.Words), centerY: pt.Y} + if !found || betterScoredHit(h, best) { + best = h + found = true + } + } + if found { + return best.line, best.pt, true + } + } + // Pass 1a: exact normalized word-level match (highest precision on dense bars + // such as menu_bar or "Disagree / Agree" action bars). Prefer short button + // rows over words embedded in multi-word prose sentences. + for _, cand := range candidates { + wantNorm := NormalizeText(cand) + if wantNorm == "" { + continue + } + needleNeg := startsWithNegation(CompactText(cand)) + var ( + best scoredHit + found bool + ) + for _, ln := range lines { + lineWordCount := len(ln.Words) + tier := 2 + if NormalizeText(ln.Text) == wantNorm { + tier = 0 + } else if lineWordCount <= 3 { + tier = 1 + } + for idx, w := range ln.Words { + if w.Rect.Empty() { + continue + } + if NormalizeText(w.Text) == wantNorm { + if !needleNeg && idx > 0 && isPrecededByNegation(CompactText(ln.Words[idx-1].Text)) { + continue + } + pt := rectCenter(w.Rect) + h := scoredHit{ + line: ocr.Line{Text: w.Text, Rect: w.Rect}, + pt: pt, + tier: tier, + wordCount: lineWordCount, + extraLen: len([]rune(CompactText(ln.Text))) - len([]rune(CompactText(cand))), + centerY: pt.Y, + } + if h.extraLen < 0 { + h.extraLen = 0 + } + if !found || betterScoredHit(h, best) { + best = h + found = true + } + } + } + } + if found { + return best.line, best.pt, true + } + } + // Pass 1b: unnegated substring word-level match (preferring short/lower rows). + for _, cand := range candidates { + wantCompact := CompactText(cand) + needleNeg := startsWithNegation(wantCompact) + var ( + best scoredHit + found bool + ) + for _, ln := range lines { + lineWordCount := len(ln.Words) + tier := 2 + if lineWordCount <= 3 { + tier = 1 + } + for idx, w := range ln.Words { + if MatchPhrase(w.Text, cand, false) && !w.Rect.Empty() { + if !needleNeg && idx > 0 && isPrecededByNegation(CompactText(ln.Words[idx-1].Text)) { + continue + } + pt := rectCenter(w.Rect) + extra := len([]rune(CompactText(ln.Text))) - len([]rune(wantCompact)) + if extra < 0 { + extra = 0 + } + h := scoredHit{ + line: ocr.Line{Text: w.Text, Rect: w.Rect}, + pt: pt, + tier: tier, + wordCount: lineWordCount, + extraLen: extra, + centerY: pt.Y, + } + if !found || betterScoredHit(h, best) { + best = h + found = true + } + } + } + } + if found { + return best.line, best.pt, true + } + } + // Pass 2: exact/substring line-level match (multi-word phrases like "Set Up Later" or "实用工具"), + // ranking standalone/short button lines ahead of long explanatory sentences. + for _, cand := range candidates { + wantNorm := NormalizeText(cand) + wantCompact := CompactText(cand) + var ( + best scoredHit + found bool + ) + for _, ln := range lines { + if !MatchPhrase(ln.Text, cand, false) || ln.Rect.Empty() { + continue + } + r := ln.Rect + if subR, ok := locatePhraseSubRect(ln, cand, false); ok { + r = subR + } + pt := rectCenter(r) + extra := len([]rune(CompactText(ln.Text))) - len([]rune(wantCompact)) + if extra < 0 { + extra = 0 + } + tier := 2 + if NormalizeText(ln.Text) == wantNorm { + tier = 0 + } else if extra <= 6 && len(ln.Words) <= 4 { + tier = 1 + } + h := scoredHit{ + line: ocr.Line{Text: ln.Text, Rect: r}, + pt: pt, + tier: tier, + wordCount: len(ln.Words), + extraLen: extra, + centerY: pt.Y, + } + if !found || betterScoredHit(h, best) { + best = h + found = true + } + } + if found { + return best.line, best.pt, true + } + } + if !fuzzy { + return ocr.Line{}, image.Point{}, false + } + // Pass 3: fuzzy word/line match. + for _, cand := range candidates { + wantCompact := CompactText(cand) + var ( + best scoredHit + found bool + ) + for _, ln := range lines { + if !MatchPhrase(ln.Text, cand, true) || ln.Rect.Empty() { + continue + } + r := ln.Rect + if subR, ok := locatePhraseSubRect(ln, cand, true); ok { + r = subR + } + pt := rectCenter(r) + extra := len([]rune(CompactText(ln.Text))) - len([]rune(wantCompact)) + if extra < 0 { + extra = 0 + } + tier := 2 + if extra <= 4 && len(ln.Words) <= 4 { + tier = 1 + } + h := scoredHit{ + line: ocr.Line{Text: ln.Text, Rect: r}, + pt: pt, + tier: tier, + wordCount: len(ln.Words), + extraLen: extra, + centerY: pt.Y, + } + if !found || betterScoredHit(h, best) { + best = h + found = true + } + } + if found { + return best.line, best.pt, true + } + } + return ocr.Line{}, image.Point{}, false +} + +func locatePhraseSubRect(ln ocr.Line, cand string, fuzzy bool) (image.Rectangle, bool) { + if len(ln.Words) == 0 { + return image.Rectangle{}, false + } + wantCompact := CompactText(cand) + needleNeg := startsWithNegation(wantCompact) + var ( + bestRect image.Rectangle + found bool + bestExact bool + bestExtra int + bestSpan int + bestWidth int + ) + for i := 0; i < len(ln.Words); i++ { + if !needleNeg && i > 0 && isPrecededByNegation(CompactText(ln.Words[i-1].Text)) { + continue + } + var joined strings.Builder + var rect image.Rectangle + for j := i; j < len(ln.Words) && j < i+10; j++ { + if j > i { + joined.WriteByte(' ') + } + joined.WriteString(ln.Words[j].Text) + if rect.Empty() { + rect = ln.Words[j].Rect + } else { + rect = rect.Union(ln.Words[j].Rect) + } + txt := joined.String() + if !MatchPhrase(txt, cand, fuzzy) { + continue + } + gotCompact := CompactText(txt) + exact := wantCompact != "" && gotCompact == wantCompact + extra := len([]rune(gotCompact)) - len([]rune(wantCompact)) + if extra < 0 { + extra = -extra + } + span := j - i + 1 + width := rect.Dx() + better := !found || + (exact && !bestExact) || + (exact == bestExact && extra < bestExtra) || + (exact == bestExact && extra == bestExtra && span < bestSpan) || + (exact == bestExact && extra == bestExtra && span == bestSpan && width < bestWidth) + if better { + bestRect = rect + found = true + bestExact = exact + bestExtra = extra + bestSpan = span + bestWidth = width + } + } + } + return bestRect, found +} + +func rectCenter(r image.Rectangle) image.Point { + return image.Pt((r.Min.X+r.Max.X)/2, (r.Min.Y+r.Max.Y)/2) +} diff --git a/internal/macos/autoinstall/rules/rules_test.go b/internal/macos/autoinstall/rules/rules_test.go new file mode 100644 index 0000000..3d94ab2 --- /dev/null +++ b/internal/macos/autoinstall/rules/rules_test.go @@ -0,0 +1,346 @@ +package rules + +import ( + "image" + "os" + "path/filepath" + "testing" + + "github.com/Nwflower/reims-go/internal/macos/autoinstall/ocr" +) + +func TestNormalizeAndFuzzyMatch(t *testing.T) { + if got := NormalizeText(" 实 用 工 具… "); got != "实用工具" { + t.Fatalf("NormalizeText = %q, want 实用工具", got) + } + if !MatchPhrase("悄 后 设 置", "稍后设置", true) { + t.Fatal("fuzzy match should tolerate single CJK OCR error (悄后设置 ~ 稍后设置)") + } + if !MatchPhrase("ContInue", "Continue", true) { + t.Fatal("case-insensitive match should match ContInue") + } + // Negation guard must never allow "不使用" to match positive "使用", + // including fuzzy substitution/insertion windows at start=0. + if MatchPhrase("确定不使用定位服务", "使用定位服务", true) { + t.Fatal("negation collision guard failed") + } + if MatchPhrase("不同意します", "同意します", true) { + t.Fatal("negated Japanese phrase must not fuzzy-match positive needle") + } + if MatchPhrase("不使用定位", "请使用定位", true) { + t.Fatal("negated-prefix substitution window must not fuzzy-match positive needle") + } +} + +func TestLoadEngineAndOverlayAndHighRisk(t *testing.T) { + dataDir := t.TempDir() + rulesDir := filepath.Join(dataDir, "rules") + if err := os.MkdirAll(rulesDir, 0o755); err != nil { + t.Fatal(err) + } + patch := `{ + "version": 1, + "rules": [ + { + "id": "setup.custom_macos27", + "stage": "setup_assistant", + "priority": 95, + "match": { "roi": "title_band", "any_of": ["Future macOS 27 Page"] }, + "actions": [{ "op": "key", "key": "ret" }] + } + ] + }` + if err := os.WriteFile(filepath.Join(rulesDir, "patch.json"), []byte(patch), 0o644); err != nil { + t.Fatal(err) + } + + eng, err := LoadEngine(dataDir) + if err != nil { + t.Fatalf("LoadEngine: %v", err) + } + // Built-in online Setup Assistant rule matches. + r, ok := eng.MatchScreen("setup_assistant", map[string]string{ + "title_band": "Sign In with Your Apple Account", + }) + if !ok || r.ID != "setup.apple_account" { + t.Fatalf("expected setup.apple_account, got %+v %v", r.ID, ok) + } + // Modal rule has higher priority than underlying title_band rule. + rModal, ok := eng.MatchScreen("setup_assistant", map[string]string{ + "title_band": "Sign In with Your Apple Account", + "modal": "Are you sure you want to skip signing in?", + }) + if !ok || rModal.ID != "setup.apple_account_skip_modal" { + t.Fatalf("expected skip modal priority override, got %+v %v", rModal.ID, ok) + } + // User overlay JSON rule matches. + rPatch, ok := eng.MatchScreen("setup_assistant", map[string]string{ + "title_band": "Future macOS 27 Page", + }) + if !ok || rPatch.ID != "setup.custom_macos27" { + t.Fatalf("expected overlay patch rule, got %+v %v", rPatch.ID, ok) + } + // High-risk keyword detection catches non-empty disk refusal, recovery key screens, + // and single-char OCR typos without false-positiving on benign words like "Please" or "Ease". + for _, sample := range []string{ + "Refusing to erase non-empty disk /dev/disk0", + "Save your Recovery Key before continuing", + "Multiple eligible disks found [y/N]", + "Are you sure you want to erasc Macintosh HD?", + "Save your recovery kev now", + "Installatlon failed unexpectedly", + } { + if _, hit := DetectHighRiskKeyword(sample); !hit { + t.Fatalf("expected high-risk detection for %q", sample) + } + } + for _, safe := range []string{ + "Please select your country or region", + "Ease of access settings", + "Do not erasc existing files", + } { + if kw, hit := DetectHighRiskKeyword(safe); hit { + t.Fatalf("benign text %q falsely triggered high-risk keyword %q", safe, kw) + } + } +} + +func TestFindHitLocatesExactCJKMenuItem(t *testing.T) { + // Simulates Windows.Media.Ocr emitting per-character CJK words on one Recovery menu bar line. + lines := []ocr.Line{{ + Text: "恢 复 文 件 编 辑 实 用 工 具 窗 口", + Rect: image.Rect(40, 4, 340, 22), + Words: []ocr.Word{ + {Text: "恢", Rect: image.Rect(40, 4, 58, 22)}, + {Text: "复", Rect: image.Rect(58, 4, 76, 22)}, + {Text: "文", Rect: image.Rect(92, 4, 110, 22)}, + {Text: "件", Rect: image.Rect(110, 4, 128, 22)}, + {Text: "编", Rect: image.Rect(144, 4, 162, 22)}, + {Text: "辑", Rect: image.Rect(162, 4, 180, 22)}, + {Text: "实", Rect: image.Rect(196, 4, 214, 22)}, + {Text: "用", Rect: image.Rect(214, 4, 232, 22)}, + {Text: "工", Rect: image.Rect(232, 4, 250, 22)}, + {Text: "具", Rect: image.Rect(250, 4, 268, 22)}, + {Text: "窗", Rect: image.Rect(284, 4, 302, 22)}, + {Text: "口", Rect: image.Rect(302, 4, 320, 22)}, + }, + }} + _, pt, ok := FindHit(lines, []string{"Utilities", "实用工具"}, true) + if !ok { + t.Fatal("expected to locate 实用工具") + } + if pt.X < 196 || pt.X > 268 { + t.Fatalf("clicked X=%d outside 实用工具 bounds [196,268] (regression: hit 文/件/编辑)", pt.X) + } +} + +func TestTerminalHighRiskAllowsBlankDiskErase(t *testing.T) { + normal := `No writable volume found; detected blank VM disk: /dev/disk0 (68.7 GB, QEMU NVMe Ctrl) +Formatting /dev/disk0 as APFS (Macintosh HD, GPT)... +Started erase on disk0 +Finished erase on disk0 +Using target volume: /Volumes/Macintosh HD +Copying InstallAssistant.pkg as SharedSupport.dmg` + if kw, bad := DetectTerminalHighRiskKeyword(normal); bad { + t.Fatalf("normal blank-disk install.sh output must not trigger terminal high-risk stop, matched %q", kw) + } + for _, danger := range []string{ + "Found 1 disk >= 30 GB that already has partitions: /dev/disk0", + "Erase /dev/disk0 as APFS? All data on it will be lost! [y/N]:", + "Refusing to erase a non-blank disk non-interactively.", + "No writable target volume found under /Volumes.", + } { + if _, bad := DetectTerminalHighRiskKeyword(danger); !bad { + t.Fatalf("expected terminal high-risk stop for %q", danger) + } + } +} + +func TestMatchScreenFallsBackToFullWhenROIHoldsOnlyNoise(t *testing.T) { + eng, err := LoadEngine(t.TempDir()) + if err != nil { + t.Fatal(err) + } + // Single-symbol back button "<" in title_band must not block falling back to full text. + r, ok := eng.MatchScreen("setup_assistant", map[string]string{ + "title_band": "<", + "body": "选择国家或地区\n阿尔巴尼亚", + "full": "<\n选择国家或地区\n阿尔巴尼亚", + }) + if !ok || r.ID != "setup.region" { + t.Fatalf("expected setup.region via full fallback when title_band is noise, got ok=%v id=%q", ok, r.ID) + } + // Meaningful heading text in title_band stays scoped to title_band. + r2, ok := eng.MatchScreen("setup_assistant", map[string]string{ + "title_band": "Data & Privacy", + "body": "Accessibility information", + "full": "Data & Privacy\nAccessibility information", + }) + if !ok || r2.ID != "setup.privacy" { + t.Fatalf("expected setup.privacy from title_band, got ok=%v id=%q", ok, r2.ID) + } +} + +func TestDisagreeAndNegatedButtonsNeverFalseMatchAgree(t *testing.T) { + if MatchPhrase("Disagree", "Agree", true) { + t.Fatal("Disagree must never match Agree") + } + if MatchPhrase("不同意", "同意", true) { + t.Fatal("不同意 must never match 同意") + } + // Action bar containing both "Disagree" and "Agree" must click "Agree". + enLines := []ocr.Line{{ + Text: "Disagree Agree", + Rect: image.Rect(700, 620, 1080, 660), + Words: []ocr.Word{ + {Text: "Disagree", Rect: image.Rect(700, 620, 860, 660)}, + {Text: "Agree", Rect: image.Rect(920, 620, 1080, 660)}, + }, + }} + _, enPt, ok := FindHit(enLines, []string{"Agree", "同意"}, true) + if !ok || enPt.X < 920 || enPt.X > 1080 { + t.Fatalf("expected click on Agree [920,1080], got ok=%v pt=%v", ok, enPt) + } + + // Chinese action bar containing "上一步 不同意 同意" with single-char CJK WinOCR words must click "同意". + zhLines := []ocr.Line{{ + Text: "上 一 步 不 同 意 同 意", + Rect: image.Rect(600, 620, 1080, 660), + Words: []ocr.Word{ + {Text: "上", Rect: image.Rect(600, 620, 620, 660)}, + {Text: "一", Rect: image.Rect(620, 620, 640, 660)}, + {Text: "步", Rect: image.Rect(640, 620, 660, 660)}, + {Text: "不", Rect: image.Rect(760, 620, 780, 660)}, + {Text: "同", Rect: image.Rect(780, 620, 800, 660)}, + {Text: "意", Rect: image.Rect(800, 620, 820, 660)}, + {Text: "同", Rect: image.Rect(960, 620, 980, 660)}, + {Text: "意", Rect: image.Rect(980, 620, 1000, 660)}, + }, + }} + _, zhPt, ok := FindHit(zhLines, []string{"Agree", "同意"}, true) + if !ok || zhPt.X < 960 || zhPt.X > 1000 { + t.Fatalf("expected click on 同意 [960,1000], got ok=%v pt=%v", ok, zhPt) + } + + // Setup Hello priority must not hijack specific title_band pages whose body contains "hello"/"你好". + eng, err := LoadEngine(t.TempDir()) + if err != nil { + t.Fatal(err) + } + rule, ok := eng.MatchScreen("setup_assistant", map[string]string{ + "title_band": "Create a Computer Account", + "body": "Full Name: Hello User", + "full": "Create a Computer Account\nFull Name: Hello User", + }) + if !ok || rule.ID != "setup.create_account" { + t.Fatalf("expected setup.create_account over setup.hello, got ok=%v id=%q", ok, rule.ID) + } +} + +func TestFindHitPrefersStandaloneButtonOverBodyProse(t *testing.T) { + // 1. Apple Account skip confirmation modal: prose sentence contains "skip" + // above the standalone "Skip" button. FindHit MUST click the button at Y=420. + modalLines := []ocr.Line{ + { + Text: "Are you sure you want to skip setting up an Apple Account?", + Rect: image.Rect(300, 260, 960, 290), + Words: []ocr.Word{ + {Text: "Are", Rect: image.Rect(300, 260, 340, 290)}, + {Text: "you", Rect: image.Rect(345, 260, 385, 290)}, + {Text: "sure", Rect: image.Rect(390, 260, 440, 290)}, + {Text: "you", Rect: image.Rect(445, 260, 485, 290)}, + {Text: "want", Rect: image.Rect(490, 260, 540, 290)}, + {Text: "to", Rect: image.Rect(545, 260, 570, 290)}, + {Text: "skip", Rect: image.Rect(575, 260, 625, 290)}, + {Text: "setting", Rect: image.Rect(630, 260, 700, 290)}, + {Text: "up", Rect: image.Rect(705, 260, 735, 290)}, + }, + }, + { + Text: "Skip", + Rect: image.Rect(740, 410, 820, 445), + Words: []ocr.Word{{Text: "Skip", Rect: image.Rect(740, 410, 820, 445)}}, + }, + } + _, pt, ok := FindHit(modalLines, []string{"Skip", "跳过", "略過"}, true) + if !ok || pt.Y < 410 || pt.Y > 445 { + t.Fatalf("expected click on Skip button at Y=[410,445], got ok=%v pt=%v", ok, pt) + } + + // 2. Two-button row ("Cancel Skip") at Y=410 still beats long prose at Y=260. + modalTwoBtn := []ocr.Line{ + modalLines[0], + { + Text: "Cancel Skip", + Rect: image.Rect(600, 410, 820, 445), + Words: []ocr.Word{ + {Text: "Cancel", Rect: image.Rect(600, 410, 690, 445)}, + {Text: "Skip", Rect: image.Rect(740, 410, 820, 445)}, + }, + }, + } + _, pt2, ok := FindHit(modalTwoBtn, []string{"Skip", "跳过"}, true) + if !ok || pt2.Y < 410 || pt2.X < 740 { + t.Fatalf("expected click on Skip button [740..820, 410..445], got ok=%v pt=%v", ok, pt2) + } + + // 3. Multi-word modal button "Don't Use" beats body sentence containing "don't want to use". + locModal := []ocr.Line{ + { + Text: "Are you sure you don't use Location Services?", + Rect: image.Rect(300, 260, 920, 290), + Words: []ocr.Word{ + {Text: "Are", Rect: image.Rect(300, 260, 340, 290)}, + {Text: "you", Rect: image.Rect(345, 260, 385, 290)}, + {Text: "sure", Rect: image.Rect(390, 260, 440, 290)}, + {Text: "you", Rect: image.Rect(445, 260, 485, 290)}, + {Text: "don't", Rect: image.Rect(490, 260, 550, 290)}, + {Text: "use", Rect: image.Rect(555, 260, 595, 290)}, + {Text: "Location", Rect: image.Rect(600, 260, 690, 290)}, + }, + }, + { + Text: "Don't Use", + Rect: image.Rect(710, 415, 830, 448), + Words: []ocr.Word{ + {Text: "Don't", Rect: image.Rect(710, 415, 770, 448)}, + {Text: "Use", Rect: image.Rect(775, 415, 830, 448)}, + }, + }, + } + _, pt3, ok := FindHit(locModal, []string{"Don't Use", "不使用"}, true) + if !ok || pt3.Y < 415 { + t.Fatalf("expected click on Don't Use button at Y=[415,448], got ok=%v pt=%v", ok, pt3) + } +} + +func TestShortASCIIFuzzyGuardAndRecoveryMainSpecificity(t *testing.T) { + // 4-5 char pure-ASCII needles must not fuzzy-match unrelated 3-5 char substrings. + for _, sample := range []string{"desire", "Sir", "Air", "Skipper's ship", "Site Settings"} { + if MatchPhrase(sample, "Siri", true) { + t.Fatalf("short ASCII fuzzy match falsely matched %q against Siri", sample) + } + } + if !MatchPhrase("Ask Siri", "Siri", true) { + t.Fatal("exact normalized match for Siri must still work") + } + + eng, err := LoadEngine(t.TempDir()) + if err != nil { + t.Fatal(err) + } + // Bare "Disk Utility" text (e.g. in Terminal help output) must not match recovery.main. + if r, ok := eng.MatchScreen("recovery", map[string]string{ + "body": "Open Disk Utility to erase your disk", + "full": "Open Disk Utility to erase your disk", + }); ok && r.ID == "recovery.main" { + t.Fatalf("bare Disk Utility text must not trigger recovery.main: %+v", r) + } + // Explicit Reinstall macOS still matches recovery.main. + if r, ok := eng.MatchScreen("recovery", map[string]string{ + "body": "Reinstall macOS Sequoia", + "full": "Reinstall macOS Sequoia", + }); !ok || r.ID != "recovery.main" { + t.Fatalf("expected recovery.main for Reinstall macOS, got ok=%v id=%q", ok, r.ID) + } +} diff --git a/internal/macos/autoinstall/runner/checkpoint.go b/internal/macos/autoinstall/runner/checkpoint.go new file mode 100644 index 0000000..91a6c22 --- /dev/null +++ b/internal/macos/autoinstall/runner/checkpoint.go @@ -0,0 +1,317 @@ +package runner + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "sync" + "time" + "unicode" + "unicode/utf8" + + "github.com/Nwflower/reims-go/internal/host" +) + +var checkpointMu sync.Mutex + +// Checkpoint stores non-sensitive run progress so auto-install can resume +// cleanly across restarts or paused_for_user interventions. +// Passwords and raw screenshots are NEVER persisted. +type Checkpoint struct { + Version int `json:"version"` + VM string `json:"vm"` + Stage string `json:"stage"` + Status string `json:"status"` + Message string `json:"message,omitempty"` + PauseReason string `json:"pause_reason,omitempty"` + UnknownPageSummary string `json:"unknown_page_summary,omitempty"` + MatchedRules []string `json:"matched_rules,omitempty"` + FinishInstallDone bool `json:"finish_install_done,omitempty"` + ProvisionFallbackNeeded bool `json:"provision_fallback_needed,omitempty"` + Config RunConfig `json:"config"` + StartedAt time.Time `json:"started_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +func cloneCheckpoint(cp Checkpoint) Checkpoint { + cp.MatchedRules = append([]string(nil), cp.MatchedRules...) + return cp +} + +// checkpointPath derives a collision-free, traversal-proof filename inside +// /runs/ using a sanitized ASCII prefix plus the first 64 bits of the +// VM key's SHA-256 digest. This prevents path traversal ("..", separators), +// Windows reserved device names ("CON", "NUL"), case-folding collisions, and +// separator-replacement collisions ("a/b" vs "a_b"). +func checkpointPath(dataDir, vmKey string) string { + trimmed := strings.TrimSpace(vmKey) + sum := sha256.Sum256([]byte(trimmed)) + digest := hex.EncodeToString(sum[:8]) + + var slug strings.Builder + for _, r := range trimmed { + switch { + case r >= 'a' && r <= 'z', r >= '0' && r <= '9': + slug.WriteRune(r) + case r >= 'A' && r <= 'Z': + slug.WriteRune(r - 'A' + 'a') + case r == '-' || r == '_': + slug.WriteRune(r) + default: + if slug.Len() > 0 { + slug.WriteByte('_') + } + } + if slug.Len() >= 32 { + break + } + } + prefix := strings.Trim(slug.String(), "_-") + if prefix == "" { + prefix = "vm" + } + return filepath.Join(dataDir, "runs", prefix+"-"+digest+".json") +} + +func saveCheckpoint(dataDir string, cp Checkpoint) error { + checkpointMu.Lock() + defer checkpointMu.Unlock() + return saveCheckpointLocked(dataDir, cp) +} + +func saveCheckpointLocked(dataDir string, cp Checkpoint) error { + if strings.TrimSpace(dataDir) == "" || strings.TrimSpace(cp.VM) == "" { + return nil + } + cp.Version = 1 + cp.UpdatedAt = time.Now().UTC() + path := checkpointPath(dataDir, cp.VM) + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + raw, err := json.MarshalIndent(cp, "", " ") + if err != nil { + return err + } + f, err := os.CreateTemp(dir, ".cp-*.tmp") + if err != nil { + return err + } + tmp := f.Name() + if _, err := f.Write(append(raw, '\n')); err != nil { + _ = f.Close() + _ = os.Remove(tmp) + return err + } + if err := f.Chmod(0o600); err != nil { + _ = f.Close() + _ = os.Remove(tmp) + return err + } + if err := f.Close(); err != nil { + _ = os.Remove(tmp) + return err + } + if err := os.Rename(tmp, path); err != nil { + _ = os.Remove(tmp) + return err + } + return nil +} + +// LoadCheckpoint loads an existing run checkpoint for vmKey if present. +func LoadCheckpoint(dataDir, vmKey string) (Checkpoint, bool) { + checkpointMu.Lock() + defer checkpointMu.Unlock() + return loadCheckpointLocked(dataDir, vmKey) +} + +func loadCheckpointLocked(dataDir, vmKey string) (Checkpoint, bool) { + trimmed := strings.TrimSpace(vmKey) + if strings.TrimSpace(dataDir) == "" || trimmed == "" { + return Checkpoint{}, false + } + raw, err := os.ReadFile(checkpointPath(dataDir, trimmed)) + if err != nil { + return Checkpoint{}, false + } + var cp Checkpoint + if err := json.Unmarshal(raw, &cp); err != nil || strings.TrimSpace(cp.VM) != trimmed { + return Checkpoint{}, false + } + return cp, true +} + +// ListCheckpoints returns all valid persisted run checkpoints in /runs/. +func ListCheckpoints(dataDir string) []Checkpoint { + checkpointMu.Lock() + defer checkpointMu.Unlock() + if strings.TrimSpace(dataDir) == "" { + return nil + } + entries, err := os.ReadDir(filepath.Join(dataDir, "runs")) + if err != nil { + return nil + } + out := make([]Checkpoint, 0, len(entries)) + for _, entry := range entries { + if entry.IsDir() || !strings.HasSuffix(strings.ToLower(entry.Name()), ".json") { + continue + } + raw, err := os.ReadFile(filepath.Join(dataDir, "runs", entry.Name())) + if err != nil { + continue + } + var cp Checkpoint + if err := json.Unmarshal(raw, &cp); err != nil || strings.TrimSpace(cp.VM) == "" { + continue + } + out = append(out, cp) + } + sort.Slice(out, func(i, j int) bool { return out[i].VM < out[j].VM }) + return out +} + +// MarkCheckpointStopped transitions a persisted running/paused checkpoint on +// disk to StatusStopped so a restarted host never gets stuck reporting a +// dead run as active. +func MarkCheckpointStopped(dataDir, vmKey, message string) error { + if strings.TrimSpace(message) == "" { + message = "Stopped by user" + } + return MarkCheckpointOutcome(dataDir, vmKey, StatusStopped, "", message) +} + +// MarkCheckpointOutcome transitions an active (running/paused) checkpoint on +// disk to a terminal status with a pause reason and user-visible message. +func MarkCheckpointOutcome(dataDir, vmKey, status, pauseReason, message string) error { + checkpointMu.Lock() + defer checkpointMu.Unlock() + cp, ok := loadCheckpointLocked(dataDir, vmKey) + if !ok { + return nil + } + if cp.Status != StatusRunning && cp.Status != StatusPausedForUser { + return nil + } + cp.Status = status + cp.PauseReason = strings.TrimSpace(pauseReason) + if strings.TrimSpace(message) != "" { + cp.Message = strings.TrimSpace(message) + } + return saveCheckpointLocked(dataDir, cp) +} + +var ( + reDiagEmail = regexp.MustCompile(`(?i)\b[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,}\b`) + reDiagUUID = regexp.MustCompile(`(?i)\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b`) + reDiagMAC = regexp.MustCompile(`(?i)\b[0-9a-f]{2}(?:[:-][0-9a-f]{2}){5}\b`) + reDiagIPv4 = regexp.MustCompile(`\b(?:\d{1,3}\.){3}\d{1,3}\b`) + reDiagWinHome = regexp.MustCompile(`(?i)[a-z]:\\users\\[^\s"'<>|]+`) + reDiagMacHome = regexp.MustCompile(`/Users/[^\s"'<>|:;]+`) + reDiagHexTok = regexp.MustCompile(`(?i)\b[0-9a-f]{32,}\b`) +) + +// RedactDiagnosticText removes user names, hardware identifiers, emails, IPs, +// home paths, UUIDs, MACs, and long tokens before persisting or exposing an +// unknown-page text summary for copying or bug reports. +func RedactDiagnosticText(raw string, cfg RunConfig) string { + out := host.RedactText(strings.TrimSpace(raw)) + // Scrub structured PII/identifiers BEFORE substituting FullName/AccountName + // so "" angle brackets cannot break email or home-path patterns. + out = reDiagEmail.ReplaceAllString(out, "") + out = reDiagWinHome.ReplaceAllString(out, "") + out = reDiagMacHome.ReplaceAllString(out, "") + out = reDiagUUID.ReplaceAllString(out, "") + out = reDiagMAC.ReplaceAllString(out, "") + out = reDiagIPv4.ReplaceAllString(out, "") + out = reDiagHexTok.ReplaceAllString(out, "") + for _, secret := range []string{cfg.FullName, cfg.AccountName} { + s := strings.TrimSpace(secret) + runeLen := utf8.RuneCountInString(s) + if runeLen >= 4 || (runeLen >= 2 && !isPureASCIIName(s)) { + out = replaceCaseInsensitive(out, s, "") + } else if runeLen >= 2 { + out = replaceCaseInsensitiveWholeWord(out, s, "") + } + } + return truncateUTF8(out, 1200) +} + +func truncateUTF8(s string, maxBytes int) string { + if len(s) <= maxBytes { + return s + } + cut := maxBytes + for cut > 0 && !utf8.RuneStart(s[cut]) { + cut-- + } + return s[:cut] + "..." +} + +func replaceCaseInsensitive(s, old, repl string) string { + if old == "" { + return s + } + re, err := regexp.Compile("(?i)" + regexp.QuoteMeta(old)) + if err != nil { + return strings.ReplaceAll(s, old, repl) + } + return re.ReplaceAllLiteralString(s, repl) +} + +func isPureASCIIName(s string) bool { + for i := 0; i < len(s); i++ { + if s[i] >= utf8.RuneSelf { + return false + } + } + return true +} + +func isDiagWordRune(r rune) bool { + return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' +} + +func replaceCaseInsensitiveWholeWord(s, old, repl string) string { + if old == "" { + return s + } + re, err := regexp.Compile("(?i)" + regexp.QuoteMeta(old)) + if err != nil { + return s + } + locs := re.FindAllStringIndex(s, -1) + if len(locs) == 0 { + return s + } + var b strings.Builder + b.Grow(len(s)) + last := 0 + for _, loc := range locs { + start, end := loc[0], loc[1] + if start > 0 { + prev, _ := utf8.DecodeLastRuneInString(s[:start]) + if isDiagWordRune(prev) { + continue + } + } + if end < len(s) { + next, _ := utf8.DecodeRuneInString(s[end:]) + if isDiagWordRune(next) { + continue + } + } + b.WriteString(s[last:start]) + b.WriteString(repl) + last = end + } + b.WriteString(s[last:]) + return b.String() +} diff --git a/internal/macos/autoinstall/runner/config.go b/internal/macos/autoinstall/runner/config.go new file mode 100644 index 0000000..dc65f85 --- /dev/null +++ b/internal/macos/autoinstall/runner/config.go @@ -0,0 +1,139 @@ +package runner + +import ( + "errors" + "fmt" + "regexp" + "strings" +) + +// Stage identifiers for the Stage 0–6 offline auto-install state machine. +const ( + StagePreflight = "stage0_preflight" + StageBootRecovery = "stage1_boot_recovery" + StageOfflineTerminal = "stage2a_offline_terminal" + StageInstallWait = "stage3_install_wait" + StageFinishInstall = "stage4_finish_install" + StageSetupAssistant = "stage5_setup_assistant" + StageDesktopReady = "stage6_desktop_ready" +) + +// RunStatus identifies the current lifecycle state of an auto-install run. +const ( + StatusIdle = "idle" + StatusRunning = "running" + StatusPausedForUser = "paused_for_user" + StatusCompleted = "completed" + StatusFailed = "failed" + StatusStopped = "stopped" +) + +// RunMode controls how far the automation state machine runs. +const ( + ModeFull = "full" + ModeRecoveryOnly = "recovery_only" +) + +// RunConfig carries non-secret installation preferences for one VM. +// The account password is NEVER stored here; it lives solely in host DPAPI +// storage under SecretSetting and is injected via `host/console.typeSecret`. +type RunConfig struct { + VM string `json:"vm"` + Mode string `json:"mode,omitempty"` // "recovery_only" | "full" + GuestLang string `json:"guest_lang,omitempty"` // e.g. "zh-Hans:0", "en-US:0" + FullName string `json:"full_name"` + AccountName string `json:"account_name"` + SecretSetting string `json:"secret_setting,omitempty"` // default "account_password" + Region string `json:"region,omitempty"` + Appearance string `json:"appearance,omitempty"` // "auto" | "light" | "dark" + AgeRange string `json:"age_range,omitempty"` // e.g. "adult" + SLAAccepted bool `json:"sla_accepted"` + SaveUnlockCredential bool `json:"save_unlock_credential,omitempty"` + OCRBackend string `json:"ocr_backend,omitempty"` + CustomOCRMirror string `json:"custom_ocr_mirror,omitempty"` + HasProvisionDisk bool `json:"has_provision_disk,omitempty"` +} + +// IsRecoveryOnly reports whether this run stops cleanly once macOS exits Recovery +// and boots into installed macOS (Setup Assistant / Login Screen / Desktop). +func (c RunConfig) IsRecoveryOnly() bool { + return strings.EqualFold(strings.TrimSpace(c.Mode), ModeRecoveryOnly) +} + +var reAccountName = regexp.MustCompile(`^[a-z][a-z0-9_-]{0,31}$`) + +// ValidateConfig enforces Stage 0 preflight invariants: US `:0` keyboard layout +// compatibility, explicit Apple SLA confirmation, and (in full mode) visible +// ASCII account names. +func ValidateConfig(cfg *RunConfig) error { + if cfg == nil { + return errors.New("config is required") + } + cfg.VM = strings.TrimSpace(cfg.VM) + if cfg.VM == "" { + return errors.New("vm reference is required") + } + if len(cfg.VM) > 256 || !isValidVMRefString(cfg.VM) { + return errors.New("vm reference contains invalid characters") + } + cfg.Mode = strings.ToLower(strings.TrimSpace(cfg.Mode)) + cfg.FullName = strings.TrimSpace(cfg.FullName) + cfg.AccountName = strings.ToLower(strings.TrimSpace(cfg.AccountName)) + if cfg.Mode == "" { + if cfg.FullName == "" && cfg.AccountName == "" { + cfg.Mode = ModeRecoveryOnly + } else { + cfg.Mode = ModeFull + } + } + if cfg.Mode != ModeRecoveryOnly && cfg.Mode != ModeFull { + return fmt.Errorf("unsupported mode %q (want %s or %s)", cfg.Mode, ModeRecoveryOnly, ModeFull) + } + if cfg.Mode == ModeFull { + if cfg.FullName == "" || !isPrintableASCII(cfg.FullName) { + return errors.New("full_name must be non-empty printable ASCII") + } + if !reAccountName.MatchString(cfg.AccountName) { + return errors.New("account_name must start with a lowercase ASCII letter and contain only [a-z0-9_-]") + } + if strings.TrimSpace(cfg.SecretSetting) == "" { + cfg.SecretSetting = "account_password" + } + } + if strings.TrimSpace(cfg.GuestLang) == "" { + cfg.GuestLang = "zh-Hans:0" + } + if !strings.HasSuffix(cfg.GuestLang, ":0") { + return fmt.Errorf("guest_lang %q must use the :0 US keyboard layout to avoid IME interception", cfg.GuestLang) + } + if !cfg.SLAAccepted { + return errors.New("explicit Apple SLA confirmation is required before starting auto-install") + } + switch strings.ToLower(strings.TrimSpace(cfg.Appearance)) { + case "", "auto", "light", "dark": + default: + return fmt.Errorf("unsupported appearance %q (want auto, light, or dark)", cfg.Appearance) + } + return nil +} + +func isPrintableASCII(s string) bool { + for _, r := range s { + if r < 0x20 || r > 0x7E { + return false + } + } + return true +} + +func isValidVMRefString(s string) bool { + if s == "." || s == ".." { + return false + } + for _, r := range s { + if r < 0x20 || r == 0x7F { + return false + } + } + return true +} diff --git a/internal/macos/autoinstall/runner/runner.go b/internal/macos/autoinstall/runner/runner.go new file mode 100644 index 0000000..fbc9a4b --- /dev/null +++ b/internal/macos/autoinstall/runner/runner.go @@ -0,0 +1,2224 @@ +package runner + +import ( + "context" + "errors" + "image" + "regexp" + "strings" + "sync" + "time" + + "github.com/Nwflower/reims-go/internal/macos/autoinstall/hostclient" + "github.com/Nwflower/reims-go/internal/macos/autoinstall/ocr" + "github.com/Nwflower/reims-go/internal/macos/autoinstall/rules" + "github.com/Nwflower/reims-go/internal/macos/autoinstall/vision" + "github.com/Nwflower/reims-go/pkg/pluginsdk" +) + +// Options tunes runner polling intervals (short in unit tests, steady in production). +type Options struct { + PollInterval time.Duration + Stage3Interval time.Duration + PostActionWait time.Duration + Watchdog WatchdogConfig + NowFunc func() time.Time + DisableSleep bool +} + +func defaultOptions() Options { + return Options{ + PollInterval: 1500 * time.Millisecond, + Stage3Interval: 15 * time.Second, + PostActionWait: 1200 * time.Millisecond, + Watchdog: defaultWatchdogConfig(), + NowFunc: time.Now, + } +} + +// RunStatusView is the read-only snapshot returned by `autoinstall/status`. +type RunStatusView struct { + VM string `json:"vm"` + Stage string `json:"stage"` + Status string `json:"status"` + Message string `json:"message,omitempty"` + PauseReason string `json:"pause_reason,omitempty"` + UnknownPageSummary string `json:"unknown_page_summary,omitempty"` + MatchedRules []string `json:"matched_rules,omitempty"` + FinishInstallDone bool `json:"finish_install_done,omitempty"` + SaveUnlockCredential bool `json:"save_unlock_credential,omitempty"` + StartedAt string `json:"started_at,omitempty"` + UpdatedAt string `json:"updated_at,omitempty"` +} + +// Runner executes the Stage 0–6 offline macOS unattended install state machine +// for one VM, supporting safe pauses, user takeover, checkpointing, and resume. +type Runner struct { + host hostclient.HostAPI + locator vision.VisualLocator + rules *rules.Engine + dataDir string + cfg RunConfig + opts Options + + mu sync.Mutex + cp Checkpoint + cpSeq uint64 + saveMu sync.Mutex + savedSeq uint64 + inheritedRunningStage bool + terminalNotReadyPolls int + resumeCh chan struct{} + cancel context.CancelFunc + started bool + stopped bool + onDone func() + doneOnce sync.Once + done chan struct{} +} + +const staleRunningCheckpointTTL = 2 * time.Hour + +// New creates a Runner initialized with a pre-opened VisualLocator and rules.Engine. +func New(host hostclient.HostAPI, locator vision.VisualLocator, ruleEngine *rules.Engine, dataDir string, cfg RunConfig, opts Options) (*Runner, error) { + if err := ValidateConfig(&cfg); err != nil { + return nil, err + } + def := defaultOptions() + if opts.PollInterval <= 0 { + opts.PollInterval = def.PollInterval + } + if opts.Stage3Interval <= 0 { + opts.Stage3Interval = def.Stage3Interval + } + if opts.PostActionWait <= 0 { + opts.PostActionWait = def.PostActionWait + } + if opts.NowFunc == nil { + opts.NowFunc = def.NowFunc + } + now := opts.NowFunc().UTC() + cp := Checkpoint{ + Version: 1, + VM: cfg.VM, + Stage: StagePreflight, + Status: StatusRunning, + Config: cfg, + StartedAt: now, + UpdatedAt: now, + } + inheritedRunning := false + if prev, ok := LoadCheckpoint(dataDir, cfg.VM); ok && prev.Stage != "" { + switch prev.Status { + case StatusPausedForUser: + cp.Stage = prev.Stage + cp.FinishInstallDone = prev.FinishInstallDone + cp.ProvisionFallbackNeeded = prev.ProvisionFallbackNeeded + cp.MatchedRules = prev.MatchedRules + case StatusRunning: + // Only inherit an interrupted StatusRunning stage if the checkpoint is + // recent; stale crash remnants fall back to StageBootRecovery so screen + // recognition re-orients safely. + if prev.UpdatedAt.IsZero() || now.Sub(prev.UpdatedAt) <= staleRunningCheckpointTTL { + cp.Stage = prev.Stage + inheritedRunning = true + } else { + cp.Stage = StageBootRecovery + } + cp.FinishInstallDone = prev.FinishInstallDone + cp.ProvisionFallbackNeeded = prev.ProvisionFallbackNeeded + cp.MatchedRules = prev.MatchedRules + } + } + return &Runner{ + host: host, + locator: locator, + rules: ruleEngine, + dataDir: dataDir, + cfg: cfg, + opts: opts, + cp: cp, + inheritedRunningStage: inheritedRunning, + resumeCh: make(chan struct{}, 1), + done: make(chan struct{}), + }, nil +} + +// SetOnDone registers a cleanup callback invoked synchronously right before +// Wait() unblocks (used by Service to close OCR handles before StopAll returns). +func (r *Runner) SetOnDone(fn func()) { + r.mu.Lock() + r.onDone = fn + r.mu.Unlock() +} + +func (r *Runner) finishDone() { + r.doneOnce.Do(func() { + r.mu.Lock() + fn := r.onDone + r.onDone = nil + r.mu.Unlock() + if fn != nil { + fn() + } + close(r.done) + }) +} + +// Start launches the Stage 0–6 state machine in a background goroutine. +func (r *Runner) Start(parent context.Context) { + if parent == nil { + parent = context.Background() + } + ctx, cancel := context.WithCancel(parent) + r.mu.Lock() + if r.started { + r.mu.Unlock() + cancel() + return + } + r.started = true + if r.stopped { + r.mu.Unlock() + cancel() + r.finishDone() + return + } + r.cancel = cancel + r.mu.Unlock() + go func() { + defer r.finishDone() + defer cancel() + r.run(ctx) + }() +} + +// Wait blocks until the runner finishes, pauses permanently, or is stopped. +func (r *Runner) Wait() { <-r.done } + +func (r *Runner) snapshotCheckpointLocked() (uint64, Checkpoint) { + r.cpSeq++ + return r.cpSeq, cloneCheckpoint(r.cp) +} + +func (r *Runner) persistCheckpoint(seq uint64, snap Checkpoint) { + r.saveMu.Lock() + defer r.saveMu.Unlock() + if seq < r.savedSeq { + return + } + if saveCheckpoint(r.dataDir, snap) == nil { + r.savedSeq = seq + } +} + +// Resume unblocks a runner sitting in paused_for_user. +func (r *Runner) Resume() { + var ( + seq uint64 + snap Checkpoint + save bool + ) + r.mu.Lock() + if r.cp.Status == StatusPausedForUser { + r.cp.Status = StatusRunning + r.cp.PauseReason = "" + seq, snap = r.snapshotCheckpointLocked() + save = true + select { + case r.resumeCh <- struct{}{}: + default: + } + } + r.mu.Unlock() + if save { + r.persistCheckpoint(seq, snap) + } +} + +// PauseByUser transitions an active runner cleanly into paused_for_user when +// the user clicks Pause on the host HUD or VM detail page. +func (r *Runner) PauseByUser(reason string) { + if strings.TrimSpace(reason) == "" { + reason = "user_paused" + } + var ( + seq uint64 + snap Checkpoint + save bool + ) + r.mu.Lock() + if r.cp.Status == StatusRunning { + r.cp.Status = StatusPausedForUser + r.cp.PauseReason = reason + r.cp.Message = "Paused by user; click Resume to continue" + // Drain any stale resume token so the new pause cannot be skipped. + select { + case <-r.resumeCh: + default: + } + seq, snap = r.snapshotCheckpointLocked() + save = true + } + r.mu.Unlock() + if save { + r.persistCheckpoint(seq, snap) + } +} + +// NotifyTakeover transitions an active runner cleanly into paused_for_user. +func (r *Runner) NotifyTakeover(reason string) { + var ( + seq uint64 + snap Checkpoint + save bool + ) + r.mu.Lock() + if r.cp.Status == StatusRunning { + r.cp.Status = StatusPausedForUser + r.cp.PauseReason = "user_takeover:" + reason + r.cp.Message = "Paused after physical keyboard/mouse takeover; click Resume to continue" + select { + case <-r.resumeCh: + default: + } + seq, snap = r.snapshotCheckpointLocked() + save = true + } + r.mu.Unlock() + if save { + r.persistCheckpoint(seq, snap) + } +} + +// Stop cancels the runner immediately. +func (r *Runner) Stop() { + r.StopWithOutcome(StatusStopped, "", "Stopped by user") +} + +// StopWithOutcome transitions an active runner to a terminal status (such as +// StatusFailed when host permission is denied) and cancels execution right away. +func (r *Runner) StopWithOutcome(status, pauseReason, message string) { + if strings.TrimSpace(status) == "" { + status = StatusStopped + } + var ( + seq uint64 + snap Checkpoint + save bool + ) + r.mu.Lock() + r.stopped = true + cancel := r.cancel + started := r.started + if r.cp.Status == StatusRunning || r.cp.Status == StatusPausedForUser { + r.cp.Status = status + r.cp.PauseReason = strings.TrimSpace(pauseReason) + if strings.TrimSpace(message) != "" { + r.cp.Message = strings.TrimSpace(message) + } + seq, snap = r.snapshotCheckpointLocked() + save = true + } + r.mu.Unlock() + if save { + r.persistCheckpoint(seq, snap) + } + if cancel != nil { + cancel() + } else if !started { + r.finishDone() + } +} + +func (r *Runner) markCanceledIfActive() { + r.mu.Lock() + active := r.cp.Status == StatusRunning || r.cp.Status == StatusPausedForUser + r.mu.Unlock() + if active { + r.setState(context.Background(), "", StatusStopped, "Stopped", "") + } +} + +func isPermissionDeniedError(err error) bool { + if err == nil { + return false + } + msg := strings.ToLower(err.Error()) + for _, needle := range []string{ + "confirmation_denied", + "permission_denied", + "not_authorized", + "requires high-risk permission approval", + "requires permission approval", + "lacks permission", + "has not approved high-risk permission", + } { + if strings.Contains(msg, needle) { + return true + } + } + return false +} + +// Status returns a read-only view of the runner's current progress. +func (r *Runner) Status() RunStatusView { + r.mu.Lock() + defer r.mu.Unlock() + return RunStatusView{ + VM: r.cp.VM, + Stage: r.cp.Stage, + Status: r.cp.Status, + Message: r.cp.Message, + PauseReason: r.cp.PauseReason, + UnknownPageSummary: r.cp.UnknownPageSummary, + MatchedRules: append([]string(nil), r.cp.MatchedRules...), + FinishInstallDone: r.cp.FinishInstallDone, + SaveUnlockCredential: r.cp.Config.SaveUnlockCredential, + StartedAt: r.cp.StartedAt.Format(time.RFC3339), + UpdatedAt: r.cp.UpdatedAt.Format(time.RFC3339), + } +} + +func (r *Runner) setState(ctx context.Context, stage, status, message, pauseReason string) { + r.mu.Lock() + if stage != "" { + r.cp.Stage = stage + } + if status != "" { + r.cp.Status = status + } + r.cp.Message = message + r.cp.PauseReason = pauseReason + r.cp.UpdatedAt = r.opts.NowFunc().UTC() + seq, snap := r.snapshotCheckpointLocked() + paused := r.cp.Status == StatusPausedForUser + curStage := r.cp.Stage + curStatus := r.cp.Status + r.mu.Unlock() + + r.persistCheckpoint(seq, snap) + + sessionStage := curStage + if r.cfg.IsRecoveryOnly() && curStage == StageSetupAssistant && curStatus != StatusCompleted { + sessionStage = "stage5_wait_reboot" + } + _ = r.host.UpdateSession(ctx, pluginsdk.SessionUpdateRequest{ + VM: r.cfg.VM, + Stage: sessionStage, + Status: curStatus, + Message: message, + PausedForUser: &paused, + }) +} + +func (r *Runner) recordRule(ruleID string) { + r.mu.Lock() + r.cp.MatchedRules = append(r.cp.MatchedRules, ruleID) + seq, snap := r.snapshotCheckpointLocked() + r.mu.Unlock() + r.persistCheckpoint(seq, snap) +} + +func (r *Runner) pauseAndWaitResume(ctx context.Context, reason, message, rawScreenText string) error { + r.mu.Lock() + if r.stopped || ctx.Err() != nil { + r.mu.Unlock() + return context.Canceled + } + if rawScreenText != "" { + r.cp.UnknownPageSummary = RedactDiagnosticText(rawScreenText, r.cfg) + } + r.cp.Status = StatusPausedForUser + r.cp.Message = message + r.cp.PauseReason = reason + r.cp.UpdatedAt = r.opts.NowFunc().UTC() + // Drain any stale buffered resume signal before blocking on this pause so an + // earlier Pause+Resume cycle can never bypass a safety or unknown-page stop. + select { + case <-r.resumeCh: + default: + } + seq, snap := r.snapshotCheckpointLocked() + curStage := r.cp.Stage + r.mu.Unlock() + + r.persistCheckpoint(seq, snap) + + paused := true + sessionStage := curStage + if r.cfg.IsRecoveryOnly() && curStage == StageSetupAssistant { + sessionStage = "stage5_wait_reboot" + } + _ = r.host.UpdateSession(ctx, pluginsdk.SessionUpdateRequest{ + VM: r.cfg.VM, + Stage: sessionStage, + Status: StatusPausedForUser, + Message: message, + PausedForUser: &paused, + }) + _ = r.host.Notify(ctx, "macOS Auto-Install Paused", message) + + return r.waitResumeOnly(ctx) +} + +func (r *Runner) sleep(ctx context.Context, d time.Duration) error { + if r.opts.DisableSleep || d <= 0 { + return ctx.Err() + } + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-t.C: + return nil + } +} + +func (r *Runner) run(ctx context.Context) { + wd := NewWatchdog(r.opts.Watchdog, r.opts.NowFunc()) + + // Stage 0: Open visible host session with input-lock policy and confirmation. + // Preserve a resumed checkpoint stage or an early user pause if already set. + initialStage := r.currentStage() + if initialStage == "" { + initialStage = StagePreflight + } + if !r.isPaused() { + r.setState(ctx, initialStage, StatusRunning, "Requesting host session and installation authorization", "") + } + defer func() { + _ = r.host.EndSession(context.Background(), r.cfg.VM) + }() + if err := r.host.BeginSession(ctx, pluginsdk.SessionBeginRequest{ + VM: r.cfg.VM, + Label: "macOS Auto-Install", + Stage: initialStage, + TakeoverPolicy: "lock", + RequestProtectedPhaseAuth: true, + PreferUntilPhaseExit: true, + }); err != nil { + reason := "session_begin_failed" + if isPermissionDeniedError(err) { + if strings.Contains(strings.ToLower(err.Error()), "confirmation_denied") { + reason = "confirmation_denied" + } else { + reason = "permission_denied" + } + } + r.fail(ctx, reason, err.Error()) + return + } + + // If this run inherited an interrupted StatusRunning stage in Recovery while + // telemetry already reports the VM in normal phase, re-orient safely instead + // of sending Recovery hotkeys or terminal commands. + if r.inheritedRunningStage { + cur := r.currentStage() + if cur == StageOfflineTerminal || cur == StageInstallWait { + if tel, tErr := r.host.Telemetry(ctx, r.cfg.VM); tErr == nil && strings.EqualFold(strings.TrimSpace(tel.Phase), "normal") { + nextStage := StageBootRecovery + if r.isFinishInstallDone() { + nextStage = StageSetupAssistant + } + r.setState(ctx, nextStage, StatusRunning, "Re-orienting after interrupted run", "") + } + } + } + + for { + if ctx.Err() != nil { + r.markCanceledIfActive() + return + } + if r.isPaused() { + if err := r.waitResumeOnly(ctx); err != nil { + return + } + continue + } + + stage := r.currentStage() + var err error + switch stage { + case StagePreflight, StageBootRecovery: + err = r.stepBootRecovery(ctx, wd) + case StageOfflineTerminal: + err = r.stepOfflineTerminal(ctx, wd) + case StageInstallWait: + err = r.stepInstallWait(ctx, wd) + case StageFinishInstall: + err = r.stepFinishInstall(ctx, wd) + case StageSetupAssistant: + err = r.stepSetupAssistant(ctx, wd) + case StageDesktopReady: + err = r.stepDesktopReady(ctx) + default: + r.setState(ctx, StageBootRecovery, StatusRunning, "Waiting for macOS Recovery", "") + } + + if err == nil && r.currentStatus() == StatusCompleted { + return + } + if err != nil { + if errors.Is(err, context.Canceled) { + r.markCanceledIfActive() + return + } + if strings.Contains(err.Error(), "session_paused") { + r.PauseByUser("user_paused") + if wErr := r.waitResumeOnly(ctx); wErr != nil { + return + } + continue + } + if strings.Contains(err.Error(), "user_takeover") { + if pErr := r.pauseAndWaitResume(ctx, "user_takeover", "Paused after user input takeover; click Resume to continue", ""); pErr != nil { + return + } + continue + } + if isPermissionDeniedError(err) { + r.fail(ctx, "permission_denied", err.Error()) + return + } + r.fail(ctx, "stage_error", err.Error()) + return + } + } +} + +func (r *Runner) isPaused() bool { + r.mu.Lock() + defer r.mu.Unlock() + return r.cp.Status == StatusPausedForUser +} + +func (r *Runner) waitIfPaused(ctx context.Context) error { + if !r.isPaused() { + return nil + } + return r.waitResumeOnly(ctx) +} + +func (r *Runner) currentStage() string { + r.mu.Lock() + defer r.mu.Unlock() + return r.cp.Stage +} + +func (r *Runner) currentStatus() string { + r.mu.Lock() + defer r.mu.Unlock() + return r.cp.Status +} + +func (r *Runner) waitResumeOnly(ctx context.Context) error { + for { + r.mu.Lock() + st := r.cp.Status + stopped := r.stopped + r.mu.Unlock() + if stopped || ctx.Err() != nil { + if ctx.Err() != nil { + return ctx.Err() + } + return context.Canceled + } + if st != StatusPausedForUser { + if st != StatusRunning { + return context.Canceled + } + r.setState(ctx, "", StatusRunning, "Resuming auto-install...", "") + return nil + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-r.resumeCh: + } + } +} + +func (r *Runner) fail(ctx context.Context, reason, msg string) { + r.mu.Lock() + alreadyDenied := r.cp.Status == StatusFailed && (r.cp.PauseReason == "confirmation_denied" || r.cp.PauseReason == "permission_denied") + existingMsg := r.cp.Message + r.mu.Unlock() + if alreadyDenied { + if existingMsg != "" { + msg = existingMsg + } + _ = r.host.Notify(context.Background(), "macOS Auto-Install Stopped", msg) + return + } + r.setState(context.Background(), "", StatusFailed, msg, reason) + _ = r.host.Notify(context.Background(), "macOS Auto-Install Stopped", msg) +} + +func (r *Runner) captureFull(ctx context.Context) (image.Image, hostclient.ScreenshotMeta, error) { + zero := 0 + return r.host.Screenshot(ctx, pluginsdk.ScreenshotRequest{ + VM: r.cfg.VM, + Format: "png", + MaxEdge: &zero, + }) +} + +func (r *Runner) clickPoint(ctx context.Context, pt image.Point, w, h int) error { + if err := r.host.PointerMove(ctx, r.cfg.VM, pt.X, pt.Y, w, h); err != nil { + return err + } + return r.host.PointerClick(ctx, r.cfg.VM, "left") +} + +func (r *Runner) clickOnImage(ctx context.Context, img image.Image, pt image.Point) error { + b := img.Bounds() + return r.clickPoint(ctx, pt, b.Dx(), b.Dy()) +} + +// Stage 1: Wait for Recovery environment, skip optional language selector. +func (r *Runner) stepBootRecovery(ctx context.Context, wd *Watchdog) error { + if err := r.waitIfPaused(ctx); err != nil { + return err + } + r.setState(ctx, StageBootRecovery, StatusRunning, "Waiting for macOS Recovery screen", "") + tel, _ := r.host.Telemetry(ctx, r.cfg.VM) + if reason, detail, tripped := wd.Check(r.opts.NowFunc(), tel, StageBootRecovery, false); tripped { + if err := r.pauseAndWaitResume(ctx, reason, "Watchdog halted boot: "+detail, detail); err != nil { + return err + } + wd.ResetAfterResume(r.opts.NowFunc()) + return nil + } + img, meta, err := r.captureFull(ctx) + if err != nil { + if strings.Contains(err.Error(), "vm_not_running") || strings.Contains(err.Error(), "confirmation_required") { + return r.sleep(ctx, r.opts.PollInterval) + } + return err + } + if meta.Blank || vision.DetectAppleProgress(img) { + return r.sleep(ctx, r.opts.PollInterval) + } + + menuScan, err := r.locator.ScanROI(ctx, img, "menu_bar", nil) + if err != nil { + return err + } + bodyScan, err := r.locator.ScanROI(ctx, img, "body", nil) + if err != nil { + return err + } + + roiTexts := map[string]string{"menu_bar": menuScan.Text, "body": bodyScan.Text, "full": menuScan.Text + "\n" + bodyScan.Text} + if rule, ok := r.rules.MatchScreen("recovery", roiTexts); ok { + if rule.ID == "recovery.language" { + if err := r.waitIfPaused(ctx); err != nil { + return err + } + r.recordRule(rule.ID) + if err := r.host.KeyPress(ctx, r.cfg.VM, "ret"); err != nil { + return err + } + return r.sleep(ctx, r.opts.PostActionWait) + } + if rule.ID == "recovery.main" { + r.setState(ctx, StageOfflineTerminal, StatusRunning, "Recovery ready; launching Terminal", "") + return nil + } + } + if _, _, hasUtil := rules.FindHit(menuScan.Lines, recoveryUtilitiesLabels, true); hasUtil || isTerminalMenuBar(menuScan.Text) { + r.setState(ctx, StageOfflineTerminal, StatusRunning, "Recovery ready; launching Terminal", "") + return nil + } + + // Check if VM already reached provisioned first-boot, Login Screen, Desktop, or Setup Assistant (e.g. resumed mid-install). + if hasBootMilestone(tel, "serial:provision_ready") || r.looksLikeLoginScreen(ctx, img) || r.looksLikeDesktop(ctx, img) || r.looksLikeSetupAssistant(ctx, img) { + if r.isFinishInstallDone() { + r.setState(ctx, StageSetupAssistant, StatusRunning, "Detected installed macOS screen", "") + } else { + r.setState(ctx, StageFinishInstall, StatusRunning, "Detected installed macOS first boot; exiting recovery", "") + } + return nil + } + return r.sleep(ctx, r.opts.PollInterval) +} + +var recoveryUtilitiesLabels = []string{"Utilities", "实用工具", "工具程式", "ユーティリティ"} +var recoveryTerminalLabels = []string{"Terminal", "终端", "終端機", "ターミナル"} + +func isTerminalMenuBar(menuText string) bool { + for _, tok := range recoveryTerminalLabels { + if rules.MatchPhrase(menuText, tok, true) { + return true + } + } + return false +} + +func terminalLooksReady(termText string) bool { + for _, tok := range []string{"-zsh", "-bash", "root#", "bash-", "zsh", "-sh-3.2#", "sh-3.2#", "-sh-3.2", "sh-3.2"} { + if rules.MatchPhrase(termText, tok, false) { + return true + } + } + return false +} + +// waitForTerminalReady polls up to maxChecks times for Terminal to become +// foreground and/or print a shell prompt. Returns (opened, shellReady, error). +func (r *Runner) waitForTerminalReady(ctx context.Context, maxChecks int) (bool, bool, error) { + if maxChecks <= 0 { + maxChecks = 1 + } + opened := false + for i := 0; i < maxChecks; i++ { + if err := r.waitIfPaused(ctx); err != nil { + return false, false, err + } + if err := r.sleep(ctx, r.opts.PostActionWait); err != nil { + return false, false, err + } + wImg, wMeta, err := r.captureFull(ctx) + if err != nil { + if errors.Is(err, context.Canceled) || isPermissionDeniedError(err) || + strings.Contains(err.Error(), "vm_not_running") || + strings.Contains(err.Error(), "session_paused") || + strings.Contains(err.Error(), "user_takeover") { + return false, false, err + } + continue + } + if wMeta.Blank { + continue + } + if mScan, err := r.locator.ScanROI(ctx, wImg, "menu_bar", nil); err == nil && isTerminalMenuBar(mScan.Text) { + opened = true + } + if tScan, err := r.locator.ScanROI(ctx, wImg, "terminal", nil); err == nil && terminalLooksReady(tScan.Text) { + return true, true, nil + } + if r.opts.DisableSleep { + break + } + } + return opened, false, nil +} + +// Stage 2A: Detect Recovery ready -> Shift+Cmd+T (fallback: Utilities -> Terminal) -> sh /Volumes/REIMSHELP/install.sh +func (r *Runner) stepOfflineTerminal(ctx context.Context, wd *Watchdog) error { + if err := r.waitIfPaused(ctx); err != nil { + return err + } + img, meta, err := r.captureFull(ctx) + if err != nil { + if strings.Contains(err.Error(), "vm_not_running") || strings.Contains(err.Error(), "confirmation_required") { + return r.sleep(ctx, r.opts.PollInterval) + } + return err + } + if meta.Blank || vision.DetectAppleProgress(img) { + return r.sleep(ctx, r.opts.PollInterval) + } + + menuScan, err := r.locator.ScanROI(ctx, img, "menu_bar", nil) + if err != nil { + return err + } + terminalAlreadyOpen := false + terminalForeground := isTerminalMenuBar(menuScan.Text) + // If Terminal is already the foreground app (e.g. after resuming a paused session), + // inspect its output directly instead of re-launching Terminal. + if terminalForeground { + termText := "" + if termScan, err := r.locator.ScanROI(ctx, img, "terminal", nil); err == nil { + termText = termScan.Text + if rules.MatchPhrase(termScan.Text, "REIMS_INSTALLPKG_UNSUPPORTED", true) { + r.markProvisionFallbackNeeded() + } + if kw, danger := rules.DetectTerminalHighRiskKeyword(termScan.Text); danger { + r.terminalNotReadyPolls = 0 + return r.pauseAndWaitResume(ctx, "terminal_safety_stop:"+kw, "恢复终端安全暂停("+kw+")", termScan.Text) + } + if terminalShowsInstallProgress(termScan.Text) { + r.terminalNotReadyPolls = 0 + r.setState(ctx, StageInstallWait, StatusRunning, "正在写入 macOS 安装文件(自动监测跨重启进度)", "") + return nil + } + if terminalLooksReady(termScan.Text) { + r.terminalNotReadyPolls = 0 + terminalAlreadyOpen = true + } + } + if !terminalAlreadyOpen { + // Terminal is already foreground but shell prompt is not ready yet; wait a + // bounded number of polls instead of re-launching Terminal or spinning forever. + r.terminalNotReadyPolls++ + if !r.opts.DisableSleep && r.terminalNotReadyPolls <= 3 { + return r.sleep(ctx, r.opts.PollInterval) + } + r.terminalNotReadyPolls = 0 + return r.pauseAndWaitResume(ctx, "terminal_not_ready", "终端已打开但未检测到命令提示符,请确认终端就绪后点击继续", termText) + } + } else { + r.terminalNotReadyPolls = 0 + } + + if !terminalAlreadyOpen { + _, utilPt, hasUtil := rules.FindHit(menuScan.Lines, recoveryUtilitiesLabels, true) + bodyScan, _ := r.locator.ScanROI(ctx, img, "body", nil) + roiTexts := map[string]string{"menu_bar": menuScan.Text, "body": bodyScan.Text, "full": menuScan.Text + "\n" + bodyScan.Text} + matchedRule, hasRule := r.rules.MatchScreen("recovery", roiTexts) + if hasRule && matchedRule.ID == "recovery.language" { + if err := r.waitIfPaused(ctx); err != nil { + return err + } + r.recordRule(matchedRule.ID) + if err := r.host.KeyPress(ctx, r.cfg.VM, "ret"); err != nil { + return err + } + return r.sleep(ctx, r.opts.PostActionWait) + } + recoveryReady := hasUtil || (hasRule && matchedRule.ID == "recovery.main") + if !recoveryReady { + // If install.sh already finished and rebooted into Login Screen or Setup Assistant while resumed, advance directly. + tel, _ := r.host.Telemetry(ctx, r.cfg.VM) + if hasBootMilestone(tel, "serial:provision_ready") || r.looksLikeLoginScreen(ctx, img) || r.looksLikeSetupAssistant(ctx, img) { + if r.isFinishInstallDone() { + r.setState(ctx, StageSetupAssistant, StatusRunning, "检测到系统首次启动,继续后续流程", "") + } else { + r.setState(ctx, StageFinishInstall, StatusRunning, "检测到系统首次启动,移除安装介质并重启", "") + } + return nil + } + return r.sleep(ctx, r.opts.PollInterval) + } + + // 1. Primary path: launch Terminal via Shift+Cmd+T hotkey once Recovery is ready. + if err := r.waitIfPaused(ctx); err != nil { + return err + } + r.setState(ctx, StageOfflineTerminal, StatusRunning, "已识别恢复界面,使用快捷键打开终端", "") + opened, shellReady := false, false + if err := r.host.KeyPress(ctx, r.cfg.VM, "t", "shift", "meta_l"); err != nil { + if errors.Is(err, context.Canceled) || isPermissionDeniedError(err) || + strings.Contains(err.Error(), "session_paused") || + strings.Contains(err.Error(), "user_takeover") { + return err + } + // Non-fatal hotkey error: fall through cleanly to Utilities -> Terminal menu click. + } else { + var wErr error + opened, shellReady, wErr = r.waitForTerminalReady(ctx, 3) + if wErr != nil { + return wErr + } + } + if opened || shellReady { + r.recordRule("recovery.open_terminal_hotkey") + if !shellReady { + checks := 3 + if r.opts.DisableSleep { + checks = 1 + } + o2, s2, wErr := r.waitForTerminalReady(ctx, checks) + if wErr != nil { + return wErr + } + opened = opened || o2 + shellReady = shellReady || s2 + } + } else { + // 2. Fallback path: open Utilities -> Terminal via OCR menu clicks. + if !hasUtil { + return r.pauseAndWaitResume(ctx, "terminal_open_failed", "快捷键未打开恢复终端,且未定位到「实用工具」菜单", menuScan.Text) + } + if err := r.waitIfPaused(ctx); err != nil { + return err + } + r.setState(ctx, StageOfflineTerminal, StatusRunning, "快捷键未拉起终端,改由菜单打开终端", "") + if err := r.clickOnImage(ctx, img, utilPt); err != nil { + return err + } + if err := r.sleep(ctx, r.opts.PostActionWait); err != nil { + return err + } + dropImg, _, err := r.captureFull(ctx) + if err != nil { + return err + } + dropScan, err := r.locator.ScanROI(ctx, dropImg, "menu_dropdown", &utilPt) + if err != nil { + return err + } + _, termPt, ok := rules.FindHit(dropScan.Lines, recoveryTerminalLabels, true) + if !ok { + return r.pauseAndWaitResume(ctx, "terminal_menu_missing", "未在「实用工具」下拉菜单中找到「终端」", dropScan.Text) + } + if err := r.waitIfPaused(ctx); err != nil { + return err + } + if err := r.clickOnImage(ctx, dropImg, termPt); err != nil { + return err + } + r.recordRule("recovery.open_terminal_menu_fallback") + checks := 4 + if r.opts.DisableSleep { + checks = 1 + } + o2, s2, wErr := r.waitForTerminalReady(ctx, checks) + if wErr != nil { + return wErr + } + opened = o2 + shellReady = s2 + } + if !shellReady { + return r.pauseAndWaitResume(ctx, "terminal_not_ready", "恢复终端尚未显示命令提示符,请确认焦点在终端窗口后点击继续", menuScan.Text) + } + } + + // 3. Type REIMSHELP offline install command. + if err := r.waitIfPaused(ctx); err != nil { + return err + } + r.recordRule("recovery.offline_install_script") + r.setState(ctx, StageOfflineTerminal, StatusRunning, "正在终端输入并运行离线安装脚本", "") + if _, err := r.host.TypeText(ctx, r.cfg.VM, "sh /Volumes/REIMSHELP/install.sh\n"); err != nil { + return err + } + + // 4. Watch terminal output: proceed on formatting/extracting/startosinstall, pause immediately on non-empty disk or error. + for attempt := 0; attempt < 25; attempt++ { + if err := r.waitIfPaused(ctx); err != nil { + return err + } + if err := r.sleep(ctx, r.opts.PollInterval); err != nil { + return err + } + tImg, tMeta, err := r.captureFull(ctx) + if err != nil { + if strings.Contains(err.Error(), "vm_not_running") { + r.setState(ctx, StageInstallWait, StatusRunning, "Installer rebooting into macOS install stage", "") + return nil + } + return err + } + if tMeta.Blank || vision.DetectAppleProgress(tImg) { + r.setState(ctx, StageInstallWait, StatusRunning, "macOS installation started", "") + return nil + } + termScan, err := r.locator.ScanROI(ctx, tImg, "terminal", nil) + if err != nil { + return err + } + if rules.MatchPhrase(termScan.Text, "REIMS_INSTALLPKG_UNSUPPORTED", true) { + r.markProvisionFallbackNeeded() + } + if kw, danger := rules.DetectTerminalHighRiskKeyword(termScan.Text); danger { + return r.pauseAndWaitResume(ctx, "terminal_safety_stop:"+kw, "恢复终端安全暂停("+kw+")", termScan.Text) + } + if terminalShowsInstallProgress(termScan.Text) { + r.setState(ctx, StageInstallWait, StatusRunning, "正在写入 macOS 安装文件(自动监测跨重启进度)", "") + return nil + } + } + return r.pauseAndWaitResume(ctx, "terminal_unconfirmed", "未能确认终端内 install.sh 是否启动,查看终端后点继续", "") +} + +func terminalShowsInstallProgress(text string) bool { + for _, okToken := range []string{ + "detected blank VM disk", + "Started erase on disk", + "Finished erase on disk", + "Using target volume", + "Macintosh HD", + "Formatting", + "Extracting", + "Copying", + "SharedSupport", + "startosinstall", + "provision.pkg", + "REIMS_INSTALLPKG_UNSUPPORTED", + "Preparing to run macOS Installer", + } { + if rules.MatchPhrase(text, okToken, true) { + return true + } + } + return false +} + +// Stage 3: Dual-signal monitor across 2–4 reboots & Win10 cold reboots: +// +// Signal 1 (Zero-OCR): serial console milestone `serial:provision_ready` +// Signal 2 (OCR fallback): Login Screen, Desktop, or Setup Assistant detection +// guarded against false positives while Recovery Terminal is still running. +func (r *Runner) stepInstallWait(ctx context.Context, wd *Watchdog) error { + r.setState(ctx, StageInstallWait, StatusRunning, "正在等待 macOS 跨重启安装完成", "") + var prevFrame image.Image + sawTerminal := false + sawRebootOrProgress := false + confirmStreak := 0 + requiredConfirms := 2 + if r.opts.DisableSleep { + requiredConfirms = 1 + } + initialXNU := -1 + initialColdReboots := -1 + + checkWatchdog := func(tel pluginsdk.VMTelemetry, visualChanged bool) (bool, error) { + if reason, detail, tripped := wd.Check(r.opts.NowFunc(), tel, StageInstallWait, visualChanged); tripped { + if err := r.pauseAndWaitResume(ctx, reason, "Install watchdog paused: "+detail, detail); err != nil { + return false, err + } + wd.ResetAfterResume(r.opts.NowFunc()) + return true, nil + } + return false, nil + } + + for { + if err := r.waitIfPaused(ctx); err != nil { + return err + } + tel, _ := r.host.Telemetry(ctx, r.cfg.VM) + xnuCount := telemetryMilestoneCount(tel, "serial:xnu") + if initialXNU < 0 { + initialXNU = xnuCount + } else if xnuCount != initialXNU && xnuCount > 0 { + sawRebootOrProgress = true + } + if initialColdReboots < 0 { + initialColdReboots = tel.ColdRebootCount + } else if tel.ColdRebootCount > initialColdReboots { + sawRebootOrProgress = true + } + + // Signal 1 (Zero-OCR): one-shot LaunchDaemon emitted REIMS_PROVISION_BOOT_OK on first boot. + if hasBootMilestone(tel, "serial:provision_ready") { + wd.ResetRebootWindow(r.opts.NowFunc()) + r.recordRule("provision.serial_ready") + r.setState(ctx, StageFinishInstall, StatusRunning, "检测到首启就绪信号,退出恢复模式并重启", "") + return nil + } + + img, meta, err := r.captureFull(ctx) + visualChanged := false + if err == nil && img != nil { + if prevFrame != nil { + visualChanged = vision.FrameDiffRatio(prevFrame, img) > 0.015 + } + prevFrame = img + } + + // Tolerate brief stopped state during Win10 WHPX cold reboots or installer restarts. + if err != nil { + if errors.Is(err, context.Canceled) || isPermissionDeniedError(err) || + strings.Contains(err.Error(), "session_paused") || + strings.Contains(err.Error(), "user_takeover") { + return err + } + if resumed, wdErr := checkWatchdog(tel, visualChanged); wdErr != nil { + return wdErr + } else if resumed { + continue + } + if strings.Contains(err.Error(), "vm_not_running") || strings.Contains(err.Error(), "confirmation_required") { + sawRebootOrProgress = true + confirmStreak = 0 + if sErr := r.sleep(ctx, r.opts.Stage3Interval); sErr != nil { + return sErr + } + continue + } + return err + } + + if meta.Blank || vision.DetectAppleProgress(img) { + sawRebootOrProgress = true + confirmStreak = 0 + if resumed, wdErr := checkWatchdog(tel, visualChanged); wdErr != nil { + return wdErr + } else if resumed { + continue + } + if sErr := r.sleep(ctx, r.opts.Stage3Interval); sErr != nil { + return sErr + } + continue + } + + // Guard: while Recovery or Terminal is still on screen, NEVER misclassify + // terminal log timestamps or "Restarting..." lines as installed macOS. + menuScan, _ := r.locator.ScanROI(ctx, img, "menu_bar", nil) + titleScan, _ := r.locator.ScanROI(ctx, img, "title_band", nil) + bodyScan, _ := r.locator.ScanROI(ctx, img, "body", nil) + if isRecoveryOrTerminalScreen(menuScan.Text, titleScan.Text, bodyScan.Text) { + sawTerminal = true + confirmStreak = 0 + if resumed, wdErr := checkWatchdog(tel, visualChanged); wdErr != nil { + return wdErr + } else if resumed { + continue + } + if sErr := r.sleep(ctx, r.opts.Stage3Interval); sErr != nil { + return sErr + } + continue + } + + // Signal 2 (OCR fallback): evaluate installed macOS screens BEFORE + // tripping non-fatal watchdog checks so a completed install landing on + // Setup Assistant / Login Screen / Desktop advances cleanly instead of + // falsely pausing on boot-cycle counts. + modalScan, _ := r.locator.ScanROI(ctx, img, "modal", nil) + actionScan, _ := r.locator.ScanROI(ctx, img, "action_bar", nil) + loginScan, _ := r.locator.ScanROI(ctx, img, "login_band", nil) + isDesktop := vision.DetectDesktopReady(menuScan.Lines, modalScan.Text) + _, _, isLogin := r.detectLoginScreen(menuScan, titleScan, bodyScan, modalScan, loginScan) + isLoginOrDesktop := isDesktop || isLogin + isSetup := !isLoginOrDesktop && r.matchesSetupAssistant(menuScan, titleScan, bodyScan, modalScan, actionScan, loginScan) + + // If we observed Recovery Terminal earlier in this Stage 3 wait and have + // not seen a reboot signal yet, guard Login/Desktop heuristics against + // transient terminal frames; explicit Setup Assistant screens cannot + // occur inside Recovery Terminal. + if sawTerminal && !sawRebootOrProgress && !isSetup { + confirmStreak = 0 + if resumed, wdErr := checkWatchdog(tel, visualChanged); wdErr != nil { + return wdErr + } else if resumed { + continue + } + if sErr := r.sleep(ctx, r.opts.Stage3Interval); sErr != nil { + return sErr + } + continue + } + + if isLoginOrDesktop || isSetup { + confirmStreak++ + if confirmStreak >= requiredConfirms { + wd.ResetRebootWindow(r.opts.NowFunc()) + if isLoginOrDesktop { + r.recordRule("provision.login_or_desktop_detected") + r.setState(ctx, StageFinishInstall, StatusRunning, "检测到系统首次启动,正在退出恢复模式并重启", "") + } else { + r.setState(ctx, StageFinishInstall, StatusRunning, "检测到设置助理,正在退出恢复模式并重启", "") + } + return nil + } + if sErr := r.sleep(ctx, 4*time.Second); sErr != nil { + return sErr + } + continue + } + confirmStreak = 0 + + if resumed, wdErr := checkWatchdog(tel, visualChanged); wdErr != nil { + return wdErr + } else if resumed { + continue + } + + if sErr := r.sleep(ctx, r.opts.Stage3Interval); sErr != nil { + return sErr + } + } +} + +func (r *Runner) isFinishInstallDone() bool { + r.mu.Lock() + defer r.mu.Unlock() + return r.cp.FinishInstallDone +} + +func (r *Runner) markProvisionFallbackNeeded() { + var ( + seq uint64 + snap Checkpoint + save bool + ) + r.mu.Lock() + if !r.cp.ProvisionFallbackNeeded { + r.cp.ProvisionFallbackNeeded = true + seq, snap = r.snapshotCheckpointLocked() + save = true + } + r.mu.Unlock() + if save { + r.persistCheckpoint(seq, snap) + } +} + +func (r *Runner) isProvisionFallbackNeeded() bool { + r.mu.Lock() + defer r.mu.Unlock() + return r.cp.ProvisionFallbackNeeded +} + +func hasBootMilestone(tel pluginsdk.VMTelemetry, key string) bool { + return telemetryMilestoneCount(tel, key) > 0 +} + +func telemetryMilestoneCount(tel pluginsdk.VMTelemetry, key string) int { + for _, m := range tel.BootMilestones { + if m.Key == key { + if m.Count > 0 { + return m.Count + } + return 1 + } + } + return 0 +} + +func finishInstallNeedsRestart(phase string, res map[string]any) bool { + if !strings.EqualFold(strings.TrimSpace(phase), "normal") || res == nil { + return true + } + // Only skip restart when the driver explicitly reported zero pending hardware/recovery changes. + if _, hasFlags := res["installer_ejected"]; !hasFlags { + return true + } + for _, k := range []string{"installer_ejected", "network_enabled", "upgraded_nvme", "recovery_pending", "helper_stripped"} { + if v, _ := res[k].(bool); v { + return true + } + } + return false +} + +// Stage 4: Eject installer, strip REIMSHELP & REIMSPROV, enable network (never mount REIMSTOOLS), and restart VM. +func (r *Runner) stepFinishInstall(ctx context.Context, wd *Watchdog) error { + if err := r.waitIfPaused(ctx); err != nil { + return err + } + if !r.isFinishInstallDone() { + tel, _ := r.host.Telemetry(ctx, r.cfg.VM) + r.setState(ctx, StageFinishInstall, StatusRunning, "正在退出恢复模式并启用网络", "") + res, err := r.host.FinishInstall(ctx, r.cfg.VM) + if err != nil { + return err + } + r.mu.Lock() + r.cp.FinishInstallDone = true + seq, snap := r.snapshotCheckpointLocked() + r.mu.Unlock() + r.persistCheckpoint(seq, snap) + + if finishInstallNeedsRestart(tel.Phase, res) { + if err := r.waitIfPaused(ctx); err != nil { + return err + } + r.setState(ctx, StageFinishInstall, StatusRunning, "正在重启进入已安装的 macOS", "") + if _, err := r.host.RestartVM(ctx, r.cfg.VM); err != nil { + return err + } + wd.ResetRebootWindow(r.opts.NowFunc()) + } + } + nextMsg := "Waiting for Setup Assistant after restart" + if r.cfg.IsRecoveryOnly() { + nextMsg = "正在等待重启进入 macOS 系统" + } else if r.cfg.HasProvisionDisk && !r.isProvisionFallbackNeeded() { + nextMsg = "Waiting for macOS login screen after restart" + } + r.setState(ctx, StageSetupAssistant, StatusRunning, nextMsg, "") + return r.sleep(ctx, r.opts.PostActionWait) +} + +// Stage 5: In recovery_only mode, confirm macOS booted post-restart and release +// input cleanly. In full mode, unlock Login Screen via DPAPI TypeSecret and run +// the declarative JSON rule loop for any remaining Setup Assistant pages. +func (r *Runner) stepSetupAssistant(ctx context.Context, wd *Watchdog) error { + lastRuleID := "" + sameRuleRetries := 0 + unknownStreak := 0 + loginAttempts := 0 + clockWakeAttempted := false + + checkWatchdog := func(tel pluginsdk.VMTelemetry) (bool, error) { + if reason, detail, tripped := wd.Check(r.opts.NowFunc(), tel, StageSetupAssistant, false); tripped { + if err := r.pauseAndWaitResume(ctx, reason, "Watchdog paused during Setup Assistant: "+detail, detail); err != nil { + return false, err + } + wd.ResetAfterResume(r.opts.NowFunc()) + return true, nil + } + return false, nil + } + + for { + if err := r.waitIfPaused(ctx); err != nil { + return err + } + tel, _ := r.host.Telemetry(ctx, r.cfg.VM) + + img, meta, err := r.captureFull(ctx) + if err != nil { + if errors.Is(err, context.Canceled) || isPermissionDeniedError(err) || + strings.Contains(err.Error(), "session_paused") || + strings.Contains(err.Error(), "user_takeover") { + return err + } + if resumed, wdErr := checkWatchdog(tel); wdErr != nil { + return wdErr + } else if resumed { + continue + } + if strings.Contains(err.Error(), "vm_not_running") || strings.Contains(err.Error(), "confirmation_required") { + if sErr := r.sleep(ctx, r.opts.PollInterval); sErr != nil { + return sErr + } + continue + } + return err + } + if meta.Blank || vision.DetectAppleProgress(img) { + if resumed, wdErr := checkWatchdog(tel); wdErr != nil { + return wdErr + } else if resumed { + continue + } + if sErr := r.sleep(ctx, r.opts.PollInterval); sErr != nil { + return sErr + } + continue + } + + // Check if we already reached Desktop or Keyboard Setup Assistant. + menuScan, err := r.locator.ScanROI(ctx, img, "menu_bar", nil) + if err != nil { + return err + } + modalScan, err := r.locator.ScanROI(ctx, img, "modal", nil) + if err != nil { + return err + } + if r.cfg.IsRecoveryOnly() { + if vision.DetectDesktopReady(menuScan.Lines, modalScan.Text) { + r.completeRecoveryOnly(ctx) + return nil + } + if _, ok := r.rules.MatchScreen("desktop", map[string]string{"modal": modalScan.Text, "full": modalScan.Text}); ok { + r.completeRecoveryOnly(ctx) + return nil + } + titleScan, err := r.locator.ScanROI(ctx, img, "title_band", nil) + if err != nil { + return err + } + bodyScan, err := r.locator.ScanROI(ctx, img, "body", nil) + if err != nil { + return err + } + if isRecoveryOrTerminalScreen(menuScan.Text, titleScan.Text, bodyScan.Text) { + if resumed, wdErr := checkWatchdog(tel); wdErr != nil { + return wdErr + } else if resumed { + continue + } + if sErr := r.sleep(ctx, r.opts.PollInterval); sErr != nil { + return sErr + } + continue + } + actionScan, _ := r.locator.ScanROI(ctx, img, "action_bar", nil) + loginScan, _ := r.locator.ScanROI(ctx, img, "login_band", nil) + isSetup := r.matchesSetupAssistant(menuScan, titleScan, bodyScan, modalScan, actionScan, loginScan) + _, _, isLogin := r.detectLoginScreen(menuScan, titleScan, bodyScan, modalScan, loginScan) + if isSetup || isLogin { + r.completeRecoveryOnly(ctx) + return nil + } + if resumed, wdErr := checkWatchdog(tel); wdErr != nil { + return wdErr + } else if resumed { + continue + } + if sErr := r.sleep(ctx, r.opts.PollInterval); sErr != nil { + return sErr + } + continue + } + if resumed, wdErr := checkWatchdog(tel); wdErr != nil { + return wdErr + } else if resumed { + continue + } + if _, ok := r.rules.MatchScreen("desktop", map[string]string{"modal": modalScan.Text, "full": modalScan.Text}); ok { + r.setState(ctx, StageDesktopReady, StatusRunning, "Closing Keyboard Setup Assistant", "") + return nil + } + if vision.DetectDesktopReady(menuScan.Lines, modalScan.Text) { + r.setState(ctx, StageDesktopReady, StatusRunning, "Verifying usable macOS desktop", "") + return nil + } + + titleScan, err := r.locator.ScanROI(ctx, img, "title_band", nil) + if err != nil { + return err + } + bodyScan, err := r.locator.ScanROI(ctx, img, "body", nil) + if err != nil { + return err + } + roiTexts := map[string]string{ + "menu_bar": menuScan.Text, + "modal": modalScan.Text, + "title_band": titleScan.Text, + "body": bodyScan.Text, + "full": strings.Join([]string{modalScan.Text, titleScan.Text, bodyScan.Text}, "\n"), + } + + rule, matched := r.rules.MatchScreen("setup_assistant", roiTexts) + if !matched { + // Provisioned macOS lands directly on the macOS Login Screen (bottom login_band on Sonoma/Sequoia/Tahoe): unlock via DPAPI TypeSecret. + loginScan, _ := r.locator.ScanROI(ctx, img, "login_band", nil) + if loginPt, confident, isLogin := r.detectLoginScreen(menuScan, titleScan, bodyScan, modalScan, loginScan); isLogin { + unknownStreak = 0 + if err := r.tryUnlockLoginScreen(ctx, img, loginPt, confident, roiTexts["full"], &loginAttempts, &clockWakeAttempted); err != nil { + return err + } + continue + } + if kw, danger := rules.DetectHighRiskKeyword(roiTexts["full"]); danger { + return r.pauseAndWaitResume(ctx, "high_risk_unmatched:"+kw, "Paused on high-risk prompt ("+kw+"); complete manually then click Resume", roiTexts["full"]) + } + unknownStreak++ + if unknownStreak >= 2 { + unknownStreak = 0 + if err := r.pauseAndWaitResume(ctx, "unknown_setup_page", "Paused on unrecognized Setup Assistant screen; complete this step and click Resume", roiTexts["full"]); err != nil { + return err + } + } else if err := r.sleep(ctx, r.opts.PollInterval); err != nil { + return err + } + continue + } + unknownStreak = 0 + + // High-risk keyword safety check when rule does not explicitly allow it. + if !rule.AllowHighRisk { + if kw, danger := rules.DetectHighRiskKeyword(roiTexts["full"]); danger { + return r.pauseAndWaitResume(ctx, "high_risk_guard:"+kw, "Paused for safety ("+kw+") on "+rule.ID, roiTexts["full"]) + } + } + if rule.RequiresSLA && !r.cfg.SLAAccepted { + return r.pauseAndWaitResume(ctx, "sla_not_accepted", "Apple SLA confirmation required before clicking Agree", roiTexts["full"]) + } + + if rule.ID == lastRuleID { + sameRuleRetries++ + maxRetries := rule.Verify.MaxRetries + if maxRetries <= 0 { + maxRetries = 2 + } + if sameRuleRetries > maxRetries { + sameRuleRetries = 0 + if err := r.pauseAndWaitResume(ctx, "retry_limit:"+rule.ID, "Screen did not advance after retrying "+rule.ID+"; complete manually and click Resume", roiTexts["full"]); err != nil { + return err + } + continue + } + } else { + lastRuleID = rule.ID + sameRuleRetries = 0 + } + + r.setState(ctx, StageSetupAssistant, StatusRunning, "Setup Assistant: "+rule.ID, "") + if err := r.executeRuleActions(ctx, img, meta, rule, bodyScan); err != nil { + return err + } + r.recordRule(rule.ID) + if err := r.waitAfterRuleAction(ctx, img, rule); err != nil { + return err + } + } +} + +// waitAfterRuleAction sleeps PostActionWait and, when the rule declares a longer +// verify.wait_change_ms budget, waits for a visual frame change before letting +// the loop retry the same rule on slow transitions (e.g. create_account / terms). +func (r *Runner) waitAfterRuleAction(ctx context.Context, beforeImg image.Image, rule rules.Rule) error { + if err := r.sleep(ctx, r.opts.PostActionWait); err != nil { + return err + } + budget := time.Duration(rule.Verify.WaitChangeMS) * time.Millisecond + if r.opts.DisableSleep || beforeImg == nil || budget <= r.opts.PostActionWait { + return nil + } + step := r.opts.PostActionWait + if step < 500*time.Millisecond { + step = 500 * time.Millisecond + } + if step > 2*time.Second { + step = 2 * time.Second + } + deadline := r.opts.NowFunc().Add(budget - r.opts.PostActionWait) + for { + if err := r.waitIfPaused(ctx); err != nil { + return err + } + nextImg, nextMeta, err := r.captureFull(ctx) + if err != nil { + if errors.Is(err, context.Canceled) || isPermissionDeniedError(err) || + strings.Contains(err.Error(), "vm_not_running") || + strings.Contains(err.Error(), "session_paused") || + strings.Contains(err.Error(), "user_takeover") { + return err + } + return nil + } + if nextMeta.Blank || nextImg == nil || vision.FrameDiffRatio(beforeImg, nextImg) > 0.015 { + return nil + } + rem := deadline.Sub(r.opts.NowFunc()) + if rem <= 0 { + return nil + } + if rem > step { + rem = step + } + if err := r.sleep(ctx, rem); err != nil { + return err + } + } +} + +func (r *Runner) executeRuleActions(ctx context.Context, img image.Image, meta hostclient.ScreenshotMeta, rule rules.Rule, bodyScan vision.ROIScan) error { + for _, act := range rule.Actions { + if err := r.waitIfPaused(ctx); err != nil { + return err + } + switch act.Op { + case "key": + if err := r.host.KeyPress(ctx, r.cfg.VM, act.Key, act.Modifiers...); err != nil { + return err + } + case "click_circle_or_key": + b := img.Bounds() + roi := vision.ResolveROI(act.ROI, b.Dx(), b.Dy(), nil) + if pt, ok := vision.DetectCircularButton(img, roi); ok { + if err := r.clickOnImage(ctx, img, pt); err != nil { + return err + } + } else { + k := act.FallbackKey + if k == "" { + k = "spc" + } + if err := r.host.KeyPress(ctx, r.cfg.VM, k); err != nil { + return err + } + } + case "click_ocr": + scan, err := r.locator.ScanROI(ctx, img, act.ROI, nil) + if err != nil { + return err + } + _, pt, ok := rules.FindHit(scan.Lines, act.AnyOf, act.Fuzzy) + if !ok { + // Fallback to blue button scan in the same ROI. + btns, _ := r.locator.ScanButtons(ctx, img, act.ROI) + for _, b := range btns { + for _, cand := range act.AnyOf { + if rules.MatchPhrase(b.Text, cand, act.Fuzzy) { + pt, ok = b.Center, true + break + } + } + if ok { + break + } + } + } + if !ok { + return r.pauseAndWaitResume(ctx, "control_not_found:"+rule.ID, "Target button not found on "+rule.ID, scan.Text) + } + if err := r.clickOnImage(ctx, img, pt); err != nil { + return err + } + case "click_blue_button": + btns, err := r.locator.ScanButtons(ctx, img, act.ROI) + if err != nil { + return err + } + var target image.Point + found := false + for _, b := range btns { + if !b.Enabled { + continue + } + for _, cand := range act.AnyOf { + if rules.MatchPhrase(b.Text, cand, act.Fuzzy) { + target, found = b.Center, true + break + } + } + if found { + break + } + } + if !found { + scan, err := r.locator.ScanROI(ctx, img, act.ROI, nil) + if err == nil { + if _, pt, ok := rules.FindHit(scan.Lines, act.AnyOf, act.Fuzzy); ok { + target, found = pt, true + } + } + } + if !found && len(btns) == 1 && btns[0].Enabled { + target, found = btns[0].Center, true + } + if !found { + return r.pauseAndWaitResume(ctx, "blue_button_not_found:"+rule.ID, "Primary button not ready on "+rule.ID, "") + } + if err := r.clickOnImage(ctx, img, target); err != nil { + return err + } + case "ensure_checkbox": + scan, err := r.locator.ScanROI(ctx, img, act.ROI, nil) + if err != nil { + return err + } + if ln, _, ok := rules.FindHit(scan.Lines, act.AnyOf, act.Fuzzy); ok { + checked, _, boxPt := vision.ProbeCheckboxState(img, ln.Rect) + want := false + if act.WantChecked != nil { + want = *act.WantChecked + } + if checked != want { + if err := r.clickOnImage(ctx, img, boxPt); err != nil { + return err + } + } + } + case "select_pref_ocr": + cands := r.preferenceCandidates(act.PrefKey) + if len(cands) > 0 { + if _, pt, ok := rules.FindHit(bodyScan.Lines, cands, true); ok { + if err := r.clickOnImage(ctx, img, pt); err != nil { + return err + } + } + } + case "fill_account_form": + if err := r.fillAccountForm(ctx, img, meta, bodyScan); err != nil { + return err + } + case "pause_for_user": + return r.pauseAndWaitResume(ctx, act.PauseReason, "Paused for user action on "+rule.ID, bodyScan.Text) + } + } + return nil +} + +func (r *Runner) preferenceCandidates(prefKey string) []string { + switch prefKey { + case "appearance": + switch strings.ToLower(r.cfg.Appearance) { + case "dark": + return []string{"Dark", "深色"} + case "light": + return []string{"Light", "浅色", "淺色"} + default: + return []string{"Auto", "自动", "自動"} + } + case "age_range": + return []string{"18 or older", "Adult", "18 岁及以上", "成年"} + default: + return nil + } +} + +// findFormFieldLabel prefers exact or short form-field label lines (e.g. +// "Password" / "密码:") over longer instructional sentences containing the word +// "password", preventing clicks on subtitle text that would leave a plaintext +// field focused before TypeSecret runs. +func findFormFieldLabel(lines []ocr.Line, labels []string) (ocr.Line, bool) { + // Pass 1: exact normalized full-line match (strips trailing ":" / ":"). + for _, cand := range labels { + want := rules.NormalizeText(cand) + if want == "" { + continue + } + for _, ln := range lines { + if !ln.Rect.Empty() && rules.NormalizeText(ln.Text) == want { + return ln, true + } + } + } + // Pass 2: short label line (<= 20 compact runes) matching candidate. + for _, cand := range labels { + for _, ln := range lines { + if !ln.Rect.Empty() && compactRuneCount(ln.Text) <= 20 && rules.MatchPhrase(ln.Text, cand, true) { + return ln, true + } + } + } + return ocr.Line{}, false +} + +func (r *Runner) tryUnlockLoginScreen(ctx context.Context, img image.Image, loginPt image.Point, confident bool, fullText string, loginAttempts *int, clockWakeAttempted *bool) error { + if !confident { + // Clock-header-only frames can resemble screensavers or non-password overlays. + // Never inject a DPAPI secret blindly without an explicit password prompt or + // confirmed user login chrome: send one harmless Shift key to wake the login + // pill, and if still unconfirmed pause for the user. + if !*clockWakeAttempted { + *clockWakeAttempted = true + if err := r.host.KeyPress(ctx, r.cfg.VM, "shift"); err != nil { + return err + } + return r.sleep(ctx, r.opts.PostActionWait) + } + *clockWakeAttempted = false + return r.pauseAndWaitResume(ctx, "login_screen_unconfirmed", "检测到锁屏时钟界面但未定位到密码输入框,请手动输入密码后点击继续", fullText) + } + *clockWakeAttempted = false + *loginAttempts++ + if *loginAttempts > 3 { + *loginAttempts = 0 + return r.pauseAndWaitResume(ctx, "login_unlock_failed", "macOS 登录界面未能自动解锁,手动输入密码后点击继续", fullText) + } + r.setState(ctx, StageSetupAssistant, StatusRunning, "Unlocking provisioned macOS login screen via DPAPI credential", "") + if loginPt != (image.Point{}) { + if err := r.clickOnImage(ctx, img, loginPt); err != nil { + return err + } + if err := r.sleep(ctx, r.opts.PostActionWait); err != nil { + return err + } + } + beforeImg, _, bErr := r.captureFull(ctx) + if bErr != nil || beforeImg == nil { + beforeImg = img + } + if _, err := r.host.TypeSecret(ctx, r.cfg.VM, r.cfg.SecretSetting); err != nil { + return err + } + // Verify mask bullet pixels changed in the password field region before + // pressing Return so we never submit or retry credentials into a non-password control. + afterImg, _, aErr := r.captureFull(ctx) + if aErr != nil || beforeImg == nil || afterImg == nil { + if *loginAttempts > 0 { + *loginAttempts-- + } + return r.pauseAndWaitResume(ctx, "login_unlock_failed", "未能截取登录密码框输入反馈画面,请手动输入密码后点击继续", fullText) + } + b := afterImg.Bounds() + maskROI := vision.ResolveROI("login_band", b.Dx(), b.Dy(), nil).Add(b.Min) + if loginPt != (image.Point{}) { + clickBox := image.Rect(loginPt.X-180, loginPt.Y-36, loginPt.X+180, loginPt.Y+44).Intersect(b) + if !clickBox.Empty() { + maskROI = maskROI.Union(clickBox) + } + } + if !vision.DetectMaskDotsDelta(beforeImg, afterImg, maskROI) { + *loginAttempts = 0 + return r.pauseAndWaitResume(ctx, "login_unlock_failed", "未检测到登录密码框输入反馈,请手动输入密码后点击继续", fullText) + } + if err := r.host.KeyPress(ctx, r.cfg.VM, "ret"); err != nil { + return err + } + r.recordRule("provision.login_unlock") + waitDur := r.opts.PostActionWait + if waitDur < 3*time.Second { + waitDur = 3 * time.Second + } + return r.sleep(ctx, waitDur) +} + +func (r *Runner) fillAccountForm(ctx context.Context, img image.Image, _ hostclient.ScreenshotMeta, bodyScan vision.ROIScan) error { + // 1. Full Name (non-secret ASCII via console.type). + if ln, ok := findFormFieldLabel(bodyScan.Lines, []string{"Full Name", "全名"}); ok { + if pt, _, found := vision.DetectInputFieldNearLabel(img, ln.Rect); found { + if err := r.clickOnImage(ctx, img, pt); err != nil { + return err + } + if err := r.host.KeyPress(ctx, r.cfg.VM, "a", "meta_l"); err != nil { + return err + } + if _, err := r.host.TypeText(ctx, r.cfg.VM, r.cfg.FullName); err != nil { + return err + } + } + } + // 2. Account Name (select-all + overwrite auto-filled shortname). + if ln, ok := findFormFieldLabel(bodyScan.Lines, []string{"Account Name", "账户名称", "帳號名稱"}); ok { + if pt, _, found := vision.DetectInputFieldNearLabel(img, ln.Rect); found { + if err := r.clickOnImage(ctx, img, pt); err != nil { + return err + } + if err := r.host.KeyPress(ctx, r.cfg.VM, "a", "meta_l"); err != nil { + return err + } + if _, err := r.host.TypeText(ctx, r.cfg.VM, r.cfg.AccountName); err != nil { + return err + } + } + } + // 3. Password & Verify strictly via DPAPI host/console.typeSecret (never OCR password fields). + passwordFieldsFilled := 0 + for _, labels := range [][]string{ + {"Password", "密码", "密碼"}, + {"Verify", "验证", "驗證"}, + } { + ln, ok := findFormFieldLabel(bodyScan.Lines, labels) + if !ok { + return r.pauseAndWaitResume(ctx, "account_form_incomplete", "Could not locate Password and Verify fields safely; fill the account form manually and click Resume", bodyScan.Text) + } + pt, fieldRect, found := vision.DetectInputFieldNearLabel(img, ln.Rect) + if !found { + return r.pauseAndWaitResume(ctx, "account_form_incomplete", "Could not confirm Password/Verify input box next to label; fill the account form manually and click Resume", bodyScan.Text) + } + beforeImg, _, _ := r.captureFull(ctx) + if beforeImg == nil { + beforeImg = img + } + if err := r.clickOnImage(ctx, img, pt); err != nil { + return err + } + if err := r.host.KeyPress(ctx, r.cfg.VM, "a", "meta_l"); err != nil { + return err + } + if _, err := r.host.TypeSecret(ctx, r.cfg.VM, r.cfg.SecretSetting); err != nil { + return err + } + // Verify bullet mask delta without ever sending password box to OCR. + afterImg, _, aErr := r.captureFull(ctx) + if aErr != nil || afterImg == nil || !vision.DetectMaskDotsDelta(beforeImg, afterImg, fieldRect) { + return r.pauseAndWaitResume(ctx, "account_form_incomplete", "Could not verify password bullet input in Password/Verify field; fill the account form manually and click Resume", bodyScan.Text) + } + passwordFieldsFilled++ + } + if passwordFieldsFilled < 2 { + return r.pauseAndWaitResume(ctx, "account_form_incomplete", "Could not locate Password and Verify fields safely; fill the account form manually and click Resume", bodyScan.Text) + } + return nil +} + +func (r *Runner) looksLikeSetupAssistant(ctx context.Context, img image.Image) bool { + menuScan, _ := r.locator.ScanROI(ctx, img, "menu_bar", nil) + titleScan, err := r.locator.ScanROI(ctx, img, "title_band", nil) + if err != nil { + return false + } + bodyScan, _ := r.locator.ScanROI(ctx, img, "body", nil) + modalScan, _ := r.locator.ScanROI(ctx, img, "modal", nil) + actionScan, _ := r.locator.ScanROI(ctx, img, "action_bar", nil) + loginScan, _ := r.locator.ScanROI(ctx, img, "login_band", nil) + return r.matchesSetupAssistant(menuScan, titleScan, bodyScan, modalScan, actionScan, loginScan) +} + +func (r *Runner) matchesSetupAssistant(menuScan, titleScan, bodyScan, modalScan, actionScan, loginScan vision.ROIScan) bool { + if isRecoveryOrTerminalScreen(menuScan.Text, titleScan.Text, bodyScan.Text) { + return false + } + roiTexts := map[string]string{ + "menu_bar": menuScan.Text, + "modal": modalScan.Text, + "title_band": titleScan.Text, + "body": bodyScan.Text, + "full": strings.Join([]string{modalScan.Text, titleScan.Text, bodyScan.Text}, "\n"), + } + if r.rules != nil { + if _, ok := r.rules.MatchScreen("setup_assistant", roiTexts); ok { + return true + } + } + return looksLikeSetupAssistantFallback(titleScan.Text, bodyScan.Text, actionScan.Text, loginScan.Text) +} + +func looksLikeSetupAssistantFallback(titleText, bodyText, actionText, loginText string) bool { + footer := actionText + "\n" + loginText + for _, phrase := range []string{ + "set up your mac", + "using voiceover", + "command-option-f5", + "view accessibility options", + "旁白设置", + "通过旁白", + "听取如何通过", + "查看辅助功能选项", + "檢視輔助使用選項", + "voiceoverを使って", + } { + if rules.MatchPhrase(footer, phrase, true) { + return true + } + } + // Detect the alphabetical Country/Region list in Setup Assistant when at + // least two distinct entries appear together in body/title. + regionText := titleText + "\n" + bodyText + countryHits := 0 + for _, country := range []string{ + "阿尔巴尼亚", "阿尔及利亚", "阿富汗", "阿拉伯联合酋长国", "阿鲁巴", "阿塞拜疆", + "阿爾巴尼亞", "阿爾及利亞", + "afghanistan", "albania", "algeria", "andorra", "angola", + "アイスランド", "アイルランド", "アゼルバイジャン", "アフガニスタン", + } { + if rules.MatchPhrase(regionText, country, true) { + countryHits++ + if countryHits >= 2 { + return true + } + } + } + return false +} + +func (r *Runner) looksLikeDesktop(ctx context.Context, img image.Image) bool { + menuScan, err := r.locator.ScanROI(ctx, img, "menu_bar", nil) + if err != nil { + return false + } + modalScan, _ := r.locator.ScanROI(ctx, img, "modal", nil) + return vision.DetectDesktopReady(menuScan.Lines, modalScan.Text) +} + +func (r *Runner) looksLikeLoginScreen(ctx context.Context, img image.Image) bool { + menuScan, _ := r.locator.ScanROI(ctx, img, "menu_bar", nil) + titleScan, err := r.locator.ScanROI(ctx, img, "title_band", nil) + if err != nil { + return false + } + bodyScan, _ := r.locator.ScanROI(ctx, img, "body", nil) + modalScan, _ := r.locator.ScanROI(ctx, img, "modal", nil) + loginScan, _ := r.locator.ScanROI(ctx, img, "login_band", nil) + _, _, ok := r.detectLoginScreen(menuScan, titleScan, bodyScan, modalScan, loginScan) + return ok +} + +var ( + reLockClockTime = regexp.MustCompile(`(?:[01]?\d|2[0-3])\s*[::]\s*[0-5]\d`) + reLogTimeWithSecs = regexp.MustCompile(`\d{1,2}\s*[::]\s*\d{2}\s*[::]\s*\d{2}`) + reFourDigitYear = regexp.MustCompile(`\b20\d{2}\b`) + reLockDateEN = regexp.MustCompile(`\b(?:mon|monday|tue|tuesday|wed|wednesday|thu|thursday|fri|friday|sat|saturday|sun|sunday|jan|january|feb|february|mar|march|apr|april|may|jun|june|jul|july|aug|august|sep|sept|september|oct|october|nov|november|dec|december)\b`) + reLockDateCJK = regexp.MustCompile(`(?:\d{1,2}\s*月\s*\d{1,2}\s*日|周\s*[一二三四五六日天]|星期\s*[一二三四五六日天]|[월화수목금토일]요일)`) +) + +func compactRuneCount(s string) int { + n := 0 + for _, r := range s { + if r != ' ' && r != '\t' && r != '\n' && r != '\r' { + n++ + } + } + return n +} + +// isRecoveryOrTerminalScreen returns true when the frame clearly shows macOS +// Recovery utilities, Terminal, or startosinstall shell output. +func isRecoveryOrTerminalScreen(menuText, titleText, bodyText string) bool { + for _, menuTok := range []string{ + "Terminal", "终端", "終端機", "ターミナル", + "Utilities", "实用工具", "工具程式", "ユーティリティ", + "Recovery", "恢复", "恢復", + "Shell", "Edit", "编辑", "編輯", "File", "文件", "Window", "窗口", "視窗", + } { + if rules.MatchPhrase(menuText, menuTok, true) { + return true + } + } + combined := titleText + "\n" + bodyText + if terminalLooksReady(combined) || terminalShowsInstallProgress(combined) { + return true + } + for _, recTok := range []string{ + "Reinstall macOS", "重新安装 macOS", "重新安裝 macOS", + "Disk Utility", "磁盘工具", "磁碟工具程式", + "REIMSHELP", "REIMSPROV", "install.sh", "agreetolicense", "diskutil", + } { + if rules.MatchPhrase(combined, recTok, true) { + return true + } + } + return false +} + +// looksLikeMacOSLockClockHeader matches the large centered date + clock header +// rendered in title_band (Y=8%–36%) on macOS Sonoma / Sequoia / Tahoe Lock and +// Login screens, strictly rejecting Terminal logs, Recovery, Desktop, and +// Setup Assistant screens. +func looksLikeMacOSLockClockHeader(menuText, titleText, bodyText string) bool { + if strings.TrimSpace(titleText) == "" { + return false + } + if isRecoveryOrTerminalScreen(menuText, titleText, bodyText) { + return false + } + for _, nonLogin := range []string{"Finder", "访达", "訪達"} { + if rules.MatchPhrase(menuText, nonLogin, true) { + return false + } + } + // On Sonoma/Sequoia/Tahoe Lock Screen, title_band holds ONLY the short date+clock + // header (<= 40 non-space runes) and body (Y=26%-80%) is clean wallpaper (<= 16 runes). + if compactRuneCount(titleText) > 40 || compactRuneCount(bodyText) > 16 { + return false + } + // Terminal/log lines often include years (2026-...), seconds (08:54:12), or shell punctuation. + if reFourDigitYear.MatchString(titleText) || reLogTimeWithSecs.MatchString(titleText) { + return false + } + if strings.ContainsAny(titleText, `[]/\=%#$_;"<>|`) { + return false + } + if !reLockClockTime.MatchString(titleText) { + return false + } + low := strings.ToLower(titleText) + return reLockDateCJK.MatchString(titleText) || reLockDateEN.MatchString(low) +} + +// detectLoginScreen identifies the macOS Login Window (after Setup Assistant is +// skipped by REIMSPROV, including Sonoma/Sequoia/Tahoe's bottom-anchored login +// pill in login_band and large centered date+clock header in title_band) and +// returns an optional click point, whether the match has explicit password/user +// confidence (safe for DPAPI password injection), and whether a login screen +// was detected. +func (r *Runner) detectLoginScreen(menuScan, titleScan, bodyScan, modalScan, loginScan vision.ROIScan) (image.Point, bool, bool) { + if isRecoveryOrTerminalScreen(menuScan.Text, titleScan.Text, bodyScan.Text) { + return image.Point{}, false, false + } + scans := []vision.ROIScan{loginScan, bodyScan, modalScan, titleScan} + var allLines []ocr.Line + var textParts []string + for _, sc := range scans { + allLines = append(allLines, sc.Lines...) + if sc.Text != "" { + textParts = append(textParts, sc.Text) + } + } + fullText := strings.Join(textParts, "\n") + + promptPhrases := []string{ + "Touch ID or Enter Password", + "Your password is required to log in", + "Enter Password", + "触控 ID 或输入密码", + "Touch ID 或输入密码", + "你必须输入密码才能登录", + "必须输入密码才能登录", + "输入密码", + "輸入密碼", + "パスワードを入力", + } + if _, pt, ok := rules.FindHit(allLines, promptPhrases, true); ok { + return pt, true, true + } + for _, phrase := range promptPhrases { + if rules.MatchPhrase(fullText, phrase, true) { + return image.Point{}, true, true + } + } + + // Only match account name inside bottom login_band when body is clean wallpaper + // (never inside Terminal output where e.g. "test" + "Restarting..." appear). + if compactRuneCount(bodyScan.Text) <= 24 { + for _, name := range []string{strings.TrimSpace(r.cfg.FullName), strings.TrimSpace(r.cfg.AccountName)} { + if len(name) < 2 { + continue + } + if _, pt, ok := rules.FindHit(loginScan.Lines, []string{name}, false); ok { + for _, chrome := range []string{"Shut Down", "Restart", "Sleep", "Cancel", "关机", "重新启动", "睡眠", "取消", "登录", "密码", "Password", "Log In"} { + if rules.MatchPhrase(loginScan.Text, chrome, true) { + return pt, true, true + } + } + } + } + } + + // Sonoma/Sequoia/Tahoe Login Window renders a large centered date+clock + // header in title_band even when the tiny frosted password pill at Y=90% + // sits over complex wallpaper or low-contrast glass. Mark confident=false so + // callers never blindly inject passwords without explicit prompt verification. + if looksLikeMacOSLockClockHeader(menuScan.Text, titleScan.Text, bodyScan.Text) { + return image.Point{}, false, true + } + return image.Point{}, false, false +} + +// Stage 6: Close Keyboard Setup Assistant if open and require 2 consecutive desktop-ready frames. +func (r *Runner) stepDesktopReady(ctx context.Context) error { + stableHits := 0 + for attempt := 0; attempt < 20; attempt++ { + if err := r.waitIfPaused(ctx); err != nil { + return err + } + img, meta, err := r.captureFull(ctx) + if err != nil { + if strings.Contains(err.Error(), "vm_not_running") || strings.Contains(err.Error(), "confirmation_required") { + if sErr := r.sleep(ctx, r.opts.PollInterval); sErr != nil { + return sErr + } + continue + } + return err + } + if meta.Blank { + stableHits = 0 + if err := r.sleep(ctx, r.opts.PollInterval); err != nil { + return err + } + continue + } + modalScan, err := r.locator.ScanROI(ctx, img, "modal", nil) + if err != nil { + return err + } + if rule, ok := r.rules.MatchScreen("desktop", map[string]string{"modal": modalScan.Text, "full": modalScan.Text}); ok { + if err := r.waitIfPaused(ctx); err != nil { + return err + } + r.recordRule(rule.ID) + stableHits = 0 + if err := r.host.KeyPress(ctx, r.cfg.VM, "q", "meta_l"); err != nil { + return err + } + if err := r.sleep(ctx, r.opts.PostActionWait); err != nil { + return err + } + continue + } + menuScan, err := r.locator.ScanROI(ctx, img, "menu_bar", nil) + if err != nil { + return err + } + if vision.DetectDesktopReady(menuScan.Lines, modalScan.Text) { + stableHits++ + if stableHits >= 2 { + if err := r.waitIfPaused(ctx); err != nil { + return err + } + r.setState(ctx, StageDesktopReady, StatusCompleted, "macOS desktop ready", "") + _ = r.host.Notify(ctx, "macOS Auto-Install Complete", "macOS has reached a usable desktop") + return nil + } + } else { + stableHits = 0 + } + if err := r.sleep(ctx, r.opts.PollInterval); err != nil { + return err + } + } + return r.pauseAndWaitResume(ctx, "desktop_unconfirmed", "Could not confirm desktop readiness after Setup Assistant", "") +} + +func (r *Runner) completeRecoveryOnly(ctx context.Context) { + r.recordRule("recovery_only.system_booted") + r.setState(ctx, StageDesktopReady, StatusCompleted, "已完成恢复模式安装并进入 macOS,画面输入已解锁", "") + _ = r.host.Notify(ctx, "macOS 恢复安装完成", "已自动退出恢复模式并进入系统,现在可操作画面") +} + +// ProbeOCR exposes Stage 0 OCR language pack probing for preflight RPCs. +func ProbeOCR(guestLang, dataDir, preferredBackend string) ocr.ProbeReport { + return ocr.Probe(guestLang, dataDir, preferredBackend) +} diff --git a/internal/macos/autoinstall/runner/runner_test.go b/internal/macos/autoinstall/runner/runner_test.go new file mode 100644 index 0000000..637f6c7 --- /dev/null +++ b/internal/macos/autoinstall/runner/runner_test.go @@ -0,0 +1,2111 @@ +package runner + +import ( + "context" + "encoding/json" + "errors" + "image" + "image/color" + _ "image/jpeg" + _ "image/png" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "testing" + "time" + "unicode/utf8" + + "github.com/Nwflower/reims-go/internal/macos/autoinstall/hostclient" + "github.com/Nwflower/reims-go/internal/macos/autoinstall/ocr" + "github.com/Nwflower/reims-go/internal/macos/autoinstall/rules" + "github.com/Nwflower/reims-go/internal/macos/autoinstall/vision" + "github.com/Nwflower/reims-go/pkg/pluginsdk" +) + +type mockScreen struct { + blank bool + vmStopped bool + appleProg bool + advanceOnlyAtBottom bool + advanceOnScan bool + drawInputFields []image.Rectangle + rois map[string]vision.ROIScan + buttons map[string][]vision.ButtonBox +} + +type mockHost struct { + mu sync.Mutex + screens []mockScreen + idx int + telemetry pluginsdk.VMTelemetry + sessionUpdates []pluginsdk.SessionUpdateRequest + sessionBegan bool + sessionEnded bool + beginErr error + beginPolicy string + ignoreHotkey bool + keyPressErr error + screenshotErrAt int + screenshotCalls int + screenshotErr error + screenshotImgs []image.Image + typedTexts []string + typedSecrets []string + keys []string + clicks []image.Point + finishInstall int + finishResp map[string]any + restarts int + takeoverOnce bool + lastPointer image.Point + secretDotPoints []image.Point + suppressMaskDots bool +} + +func (m *mockHost) advance() { + m.mu.Lock() + defer m.mu.Unlock() + if m.idx < len(m.screens)-1 { + m.idx++ + } +} + +func (m *mockHost) current() mockScreen { + m.mu.Lock() + defer m.mu.Unlock() + if len(m.screens) == 0 { + return mockScreen{} + } + return m.screens[m.idx] +} + +func (m *mockHost) BeginSession(_ context.Context, req pluginsdk.SessionBeginRequest) error { + m.mu.Lock() + m.sessionBegan = true + m.beginPolicy = req.TakeoverPolicy + err := m.beginErr + m.mu.Unlock() + return err +} +func (m *mockHost) UpdateSession(_ context.Context, req pluginsdk.SessionUpdateRequest) error { + m.mu.Lock() + m.sessionUpdates = append(m.sessionUpdates, req) + m.mu.Unlock() + return nil +} +func (m *mockHost) EndSession(_ context.Context, _ string) error { + m.mu.Lock() + m.sessionEnded = true + m.mu.Unlock() + return nil +} +func (m *mockHost) Confirm(_ context.Context, _ pluginsdk.ConfirmRequest) (pluginsdk.ConfirmResult, error) { + return pluginsdk.ConfirmResult{Approved: true, UntilPhaseExit: true}, nil +} +func (m *mockHost) Notify(_ context.Context, _, _ string) error { return nil } +func (m *mockHost) Screenshot(_ context.Context, _ pluginsdk.ScreenshotRequest) (image.Image, hostclient.ScreenshotMeta, error) { + m.mu.Lock() + m.screenshotCalls++ + sErrAt := m.screenshotErrAt + sCalls := m.screenshotCalls + sErr := m.screenshotErr + m.mu.Unlock() + if sErr != nil && sErrAt > 0 && sCalls >= sErrAt { + return nil, hostclient.ScreenshotMeta{}, sErr + } + m.mu.Lock() + var customImg image.Image + if len(m.screenshotImgs) > 0 { + idx := sCalls - 1 + if idx >= len(m.screenshotImgs) { + idx = len(m.screenshotImgs) - 1 + } + customImg = m.screenshotImgs[idx] + } + m.mu.Unlock() + if customImg != nil { + return customImg, hostclient.ScreenshotMeta{Width: customImg.Bounds().Dx(), Height: customImg.Bounds().Dy()}, nil + } + sc := m.current() + if sc.vmStopped { + m.advance() + return nil, hostclient.ScreenshotMeta{}, errors.New("vm_not_running: VM rebooting") + } + img := image.NewRGBA(image.Rect(0, 0, 1280, 720)) + if len(sc.drawInputFields) > 0 { + // Light-mode macOS window background (#ECECEC) with white bordered input boxes. + for y := 0; y < 720; y++ { + for x := 0; x < 1280; x++ { + img.SetRGBA(x, y, color.RGBA{236, 236, 236, 255}) + } + } + for _, r := range sc.drawInputFields { + clamped := r.Intersect(img.Bounds()) + for y := clamped.Min.Y; y < clamped.Max.Y; y++ { + for x := clamped.Min.X; x < clamped.Max.X; x++ { + if y == clamped.Min.Y || y == clamped.Max.Y-1 || x == clamped.Min.X || x == clamped.Max.X-1 { + img.SetRGBA(x, y, color.RGBA{180, 180, 180, 255}) + } else { + img.SetRGBA(x, y, color.RGBA{255, 255, 255, 255}) + } + } + } + } + } + m.mu.Lock() + dots := append([]image.Point(nil), m.secretDotPoints...) + m.mu.Unlock() + for _, pt := range dots { + // Paint 4 dark bullet dots centered around pt to simulate macOS NSSecureTextField bullets. + for i := 0; i < 4; i++ { + cx := pt.X - 24 + i*14 + for dy := -3; dy <= 3; dy++ { + for dx := -3; dx <= 3; dx++ { + px, py := cx+dx, pt.Y+dy + if image.Pt(px, py).In(img.Bounds()) { + img.SetRGBA(px, py, color.RGBA{20, 20, 20, 255}) + } + } + } + } + } + if sc.appleProg { + for y := 0; y < 720; y++ { + for x := 0; x < 1280; x++ { + img.SetRGBA(x, y, color.RGBA{4, 4, 4, 255}) + } + } + for y := 260; y < 350; y++ { + for x := 600; x < 680; x++ { + img.SetRGBA(x, y, color.RGBA{245, 245, 245, 255}) + } + } + for y := 460; y < 468; y++ { + for x := 460; x < 820; x++ { + img.SetRGBA(x, y, color.RGBA{180, 180, 180, 255}) + } + } + m.advance() + } + if sc.blank { + m.advance() + } + return img, hostclient.ScreenshotMeta{Width: 1280, Height: 720, SourceWidth: 1280, SourceHeight: 720, Blank: sc.blank}, nil +} +func (m *mockHost) PointerMove(_ context.Context, _ string, x, y, _, _ int) error { + m.mu.Lock() + if m.takeoverOnce { + m.takeoverOnce = false + m.mu.Unlock() + return errors.New("user_takeover: user touched mouse") + } + m.lastPointer = image.Pt(x, y) + m.mu.Unlock() + return nil +} +func (m *mockHost) PointerClick(_ context.Context, _, _ string) error { + m.mu.Lock() + pt := m.lastPointer + m.clicks = append(m.clicks, pt) + sc := m.screens[m.idx] + m.mu.Unlock() + if !sc.advanceOnlyAtBottom || pt.Y >= 580 { + m.advance() + } + return nil +} +func (m *mockHost) KeyPress(_ context.Context, _, key string, mods ...string) error { + m.mu.Lock() + combo := key + if len(mods) > 0 { + combo = strings.Join(mods, "+") + "+" + key + } + m.keys = append(m.keys, combo) + ignoreHotkey := m.ignoreHotkey + kErr := m.keyPressErr + m.mu.Unlock() + if kErr != nil { + return kErr + } + if combo != "meta_l+a" && !(ignoreHotkey && combo == "shift+meta_l+t") { + m.advance() + } + return nil +} +func (m *mockHost) TypeText(_ context.Context, _, text string) (int, error) { + m.mu.Lock() + m.typedTexts = append(m.typedTexts, text) + m.mu.Unlock() + if strings.Contains(text, "install.sh") { + m.advance() + } + return len(text), nil +} +func (m *mockHost) TypeSecret(_ context.Context, _, setting string) (int, error) { + m.mu.Lock() + m.typedSecrets = append(m.typedSecrets, setting) + if !m.suppressMaskDots { + pt := m.lastPointer + if pt == (image.Point{}) { + pt = image.Pt(640, 620) + } + m.secretDotPoints = append(m.secretDotPoints, pt) + } + m.mu.Unlock() + return 12, nil +} +func (m *mockHost) FinishInstall(_ context.Context, _ string) (map[string]any, error) { + m.mu.Lock() + m.finishInstall++ + resp := m.finishResp + m.mu.Unlock() + if resp != nil { + return resp, nil + } + return map[string]any{"ok": true}, nil +} +func (m *mockHost) RestartVM(_ context.Context, _ string) (map[string]any, error) { + m.mu.Lock() + m.restarts++ + m.mu.Unlock() + m.advance() + return map[string]any{"ok": true}, nil +} +func (m *mockHost) Telemetry(_ context.Context, _ string) (pluginsdk.VMTelemetry, error) { + m.mu.Lock() + defer m.mu.Unlock() + return m.telemetry, nil +} +func (m *mockHost) DownloadAndWait(_ context.Context, _ ocr.DownloadOptions) (string, error) { + return "", errors.New("unused") +} + +type mockLocator struct { + host *mockHost +} + +func (l *mockLocator) ScanROI(_ context.Context, _ image.Image, roiName string, _ *image.Point) (vision.ROIScan, error) { + sc := l.host.current() + if s, ok := sc.rois[roiName]; ok { + if sc.advanceOnScan && roiName == "terminal" { + l.host.advance() + } + return s, nil + } + return vision.ROIScan{}, nil +} + +func (l *mockLocator) ScanButtons(_ context.Context, _ image.Image, roiName string) ([]vision.ButtonBox, error) { + sc := l.host.current() + if btns, ok := sc.buttons[roiName]; ok { + return btns, nil + } + return nil, nil +} + +func scanText(text string, rect image.Rectangle) vision.ROIScan { + return vision.ROIScan{ + ROI: rect, + Text: text, + Lines: []ocr.Line{{Text: text, Rect: rect, Words: []ocr.Word{{Text: text, Rect: rect}}}}, + } +} + +func TestStage0To6OfflineEndToEndFlow(t *testing.T) { + dataDir := t.TempDir() + eng, err := rules.LoadEngine(dataDir) + if err != nil { + t.Fatal(err) + } + continueBtn := []vision.ButtonBox{{Rect: image.Rect(920, 620, 1080, 660), Center: image.Pt(1000, 640), Enabled: true, Text: "Continue"}} + agreeBtn := []vision.ButtonBox{{Rect: image.Rect(920, 620, 1080, 660), Center: image.Pt(1000, 640), Enabled: true, Text: "Agree"}} + + mh := &mockHost{ + telemetry: pluginsdk.VMTelemetry{State: "running", Phase: "installer", DiskBytes: 4 << 30, DiskDeltaBytes: 10 << 20, CPUPercent: 45}, + screens: []mockScreen{ + // 0: Boot blank + {blank: true}, + // 1: Recovery language selector + {rois: map[string]vision.ROIScan{"body": scanText("以简体中文作为主要语言", image.Rect(300, 200, 900, 260))}}, + // 2: Recovery main (opens Terminal via Shift+Cmd+T hotkey) + {rois: map[string]vision.ROIScan{ + "menu_bar": scanText("实用工具", image.Rect(200, 4, 280, 28)), + "body": scanText("重新安装 macOS", image.Rect(400, 250, 800, 310)), + }}, + // 3: Terminal open -> runner types install.sh + {rois: map[string]vision.ROIScan{ + "menu_bar": scanText("终端 Shell 编辑", image.Rect(40, 4, 260, 28)), + "terminal": scanText("-bash-3.2#", image.Rect(100, 100, 400, 140)), + }}, + // 4: Terminal output shows startosinstall -> transitions to Stage 3 + {advanceOnScan: true, rois: map[string]vision.ROIScan{"terminal": scanText("Formatting Macintosh HD... Extracting... startosinstall", image.Rect(100, 100, 900, 240))}}, + // 5: Stage 3 Win10 cold reboot transient stopped state + {vmStopped: true}, + // 6: Stage 3 Apple progress bar + {appleProg: true}, + // 7: Stage 3 first Setup Assistant detection -> triggers Stage 4 finish_install + restart! + {rois: map[string]vision.ROIScan{"title_band": scanText("选择国家或地区", image.Rect(300, 120, 900, 180))}}, + // 8: Post-restart Setup Assistant: Region + { + rois: map[string]vision.ROIScan{"title_band": scanText("Select Your Country or Region", image.Rect(300, 120, 900, 180))}, + buttons: map[string][]vision.ButtonBox{"action_bar": continueBtn}, + }, + // 9: Create Computer Account (clicks Continue after FullName, AccountName, TypeSecret x2) + { + advanceOnlyAtBottom: true, + drawInputFields: []image.Rectangle{ + image.Rect(460, 262, 700, 288), + image.Rect(460, 312, 700, 338), + image.Rect(460, 362, 700, 388), + image.Rect(460, 412, 700, 438), + }, + rois: map[string]vision.ROIScan{ + "title_band": scanText("Create a Computer Account", image.Rect(300, 120, 900, 180)), + "body": { + Text: "Full Name\nAccount Name\nPassword\nVerify", + Lines: []ocr.Line{ + {Text: "Full Name", Rect: image.Rect(320, 260, 440, 290)}, + {Text: "Account Name", Rect: image.Rect(320, 310, 440, 340)}, + {Text: "Password", Rect: image.Rect(320, 360, 440, 390)}, + {Text: "Verify", Rect: image.Rect(320, 410, 440, 440)}, + }, + }, + }, + buttons: map[string][]vision.ButtonBox{"action_bar": continueBtn}, + }, + // 10: Online Apple Account -> Set Up Later + { + rois: map[string]vision.ROIScan{ + "title_band": scanText("Sign In with Your Apple Account", image.Rect(300, 120, 900, 180)), + "action_bar": scanText("Set Up Later", image.Rect(320, 620, 480, 650)), + }, + }, + // 11: Skip Apple Account confirmation modal -> Skip + { + rois: map[string]vision.ROIScan{ + "modal": { + Text: "Are you sure you want to skip?\nSkip", + Lines: []ocr.Line{ + {Text: "Are you sure you want to skip?", Rect: image.Rect(420, 260, 860, 300)}, + {Text: "Skip", Rect: image.Rect(740, 420, 820, 455)}, + }, + }, + }, + }, + // 12: Terms and Conditions (requires SLA accepted!) + { + rois: map[string]vision.ROIScan{"title_band": scanText("Terms and Conditions", image.Rect(300, 120, 900, 180))}, + buttons: map[string][]vision.ButtonBox{"action_bar": agreeBtn}, + }, + // 13: FileVault (explicitly skipped!) + { + rois: map[string]vision.ROIScan{ + "title_band": scanText("Your Mac is Ready for FileVault", image.Rect(300, 120, 900, 180)), + "action_bar": scanText("Not Now", image.Rect(320, 620, 460, 650)), + }, + }, + // 14: Keyboard Setup Assistant on first desktop -> Cmd+Q + { + rois: map[string]vision.ROIScan{ + "modal": scanText("Keyboard Setup Assistant", image.Rect(400, 220, 860, 280)), + }, + }, + // 15: Usable Desktop (2 consecutive stable frames) + { + rois: map[string]vision.ROIScan{ + "menu_bar": scanText("Finder File Edit View Go Window Help 14:25", image.Rect(10, 4, 1260, 28)), + }, + }, + }, + } + + r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, RunConfig{ + VM: "builtin.guest.macos:sequoia-auto", + GuestLang: "zh-Hans:0", + FullName: "Reims User", + AccountName: "reimsuser", + SLAAccepted: true, + Appearance: "auto", + }, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + r.Start(ctx) + r.Wait() + + st := r.Status() + if st.Status != StatusCompleted || st.Stage != StageDesktopReady { + t.Fatalf("expected completed desktop stage, got status=%s stage=%s idx=%d rules=%v msg=%q pause=%q", st.Status, st.Stage, mh.idx, st.MatchedRules, st.Message, st.PauseReason) + } + if !mh.sessionBegan || !mh.sessionEnded { + t.Fatalf("expected session begin/end, got began=%v ended=%v", mh.sessionBegan, mh.sessionEnded) + } + if mh.finishInstall != 1 || mh.restarts != 1 { + t.Fatalf("expected exactly 1 finish_install and 1 restart, got finish=%d restart=%d", mh.finishInstall, mh.restarts) + } + if len(mh.typedSecrets) != 2 { + t.Fatalf("expected Password + Verify typed via typeSecret (2 calls), got %v", mh.typedSecrets) + } + // Verify checkpoint contains zero plaintext passwords. + cpBytes, err := os.ReadFile(checkpointPath(dataDir, "builtin.guest.macos:sequoia-auto")) + if err != nil { + t.Fatalf("missing checkpoint: %v", err) + } + if strings.Contains(strings.ToLower(string(cpBytes)), "password_plain") { + t.Fatal("checkpoint must never store plaintext password") + } + // Verify Keyboard Setup Assistant closed with Cmd+Q. + foundCmdQ := false + for _, k := range mh.keys { + if k == "meta_l+q" { + foundCmdQ = true + } + } + if !foundCmdQ { + t.Fatalf("expected meta_l+q for Keyboard Setup Assistant, got keys=%v", mh.keys) + } +} + +func TestNonEmptyDiskRefusalPausesForUser(t *testing.T) { + dataDir := t.TempDir() + eng, err := rules.LoadEngine(dataDir) + if err != nil { + t.Fatal(err) + } + mh := &mockHost{ + screens: []mockScreen{ + {rois: map[string]vision.ROIScan{ + "menu_bar": scanText("Utilities", image.Rect(200, 4, 280, 28)), + "body": scanText("Reinstall macOS", image.Rect(400, 250, 800, 310)), + }}, + {rois: map[string]vision.ROIScan{ + "menu_bar": scanText("Terminal Shell Edit", image.Rect(40, 4, 260, 28)), + "terminal": scanText("-bash-3.2#", image.Rect(100, 100, 400, 140)), + }}, + {rois: map[string]vision.ROIScan{"terminal": scanText("Refusing to erase non-empty disk /dev/disk0", image.Rect(100, 100, 900, 240))}}, + }, + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, RunConfig{ + VM: "builtin.guest.macos:nonempty", GuestLang: "en-US:0", FullName: "Test", AccountName: "test", SLAAccepted: true, + }, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + r.Start(ctx) + + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if r.Status().Status == StatusPausedForUser { + break + } + time.Sleep(5 * time.Millisecond) + } + st := r.Status() + if st.Status != StatusPausedForUser || !strings.Contains(st.PauseReason, "terminal_safety_stop") { + t.Fatalf("expected terminal safety pause on non-empty disk, got %+v", st) + } + r.Stop() + r.Wait() +} + +func TestUnknownPagePauseRedactsUserAndResumes(t *testing.T) { + dataDir := t.TempDir() + eng, err := rules.LoadEngine(dataDir) + if err != nil { + t.Fatal(err) + } + // Pre-seed checkpoint at Stage 5 so test jumps straight to Setup Assistant. + _ = saveCheckpoint(dataDir, Checkpoint{ + VM: "builtin.guest.macos:unknown", + Stage: StageSetupAssistant, + Status: StatusPausedForUser, + FinishInstallDone: true, + Config: RunConfig{VM: "builtin.guest.macos:unknown", GuestLang: "en-US:0", FullName: "Alice SecretName", AccountName: "alice", SLAAccepted: true}, + }) + mh := &mockHost{ + screens: []mockScreen{ + {rois: map[string]vision.ROIScan{"title_band": scanText("Brand New macOS 27 Feature for Alice SecretName", image.Rect(200, 120, 900, 180))}}, + {rois: map[string]vision.ROIScan{"menu_bar": scanText("Finder File Edit View Go 10:00", image.Rect(10, 4, 1260, 28))}}, + }, + } + + r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, RunConfig{ + VM: "builtin.guest.macos:unknown", GuestLang: "en-US:0", FullName: "Alice SecretName", AccountName: "alice", SLAAccepted: true, + }, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + r.Start(context.Background()) + + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if r.Status().Status == StatusPausedForUser { + break + } + time.Sleep(5 * time.Millisecond) + } + st := r.Status() + if st.Status != StatusPausedForUser || st.PauseReason != "unknown_setup_page" { + t.Fatalf("expected unknown_setup_page pause, got %+v", st) + } + if strings.Contains(st.UnknownPageSummary, "Alice SecretName") { + t.Fatalf("unknown page summary leaked user full name: %q", st.UnknownPageSummary) + } + + // User manually clicks past the unknown page -> Resume completes to Desktop! + mh.advance() + r.Resume() + r.Wait() + if r.Status().Status != StatusCompleted { + t.Fatalf("expected resume to reach completed desktop, got %+v", r.Status()) + } +} + +func TestWatchdogCatchesBootLoopAndQemuFatal(t *testing.T) { + t0 := time.Date(2026, 12, 3, 12, 0, 0, 0, time.UTC) + wd := NewWatchdog(defaultWatchdogConfig(), t0) + + // 1. Three cold-reboot cycles within 5 minutes trigger boot_loop_detected. + for i := 1; i <= 3; i++ { + reason, _, tripped := wd.Check(t0.Add(time.Duration(i)*time.Minute), pluginsdk.VMTelemetry{ColdRebootCount: i}, StageInstallWait, false) + if i < 3 && tripped { + t.Fatalf("tripped too early at cycle %d", i) + } + if i == 3 && (!tripped || reason != "boot_loop_detected") { + t.Fatalf("expected boot_loop_detected on 3rd cycle, got tripped=%v reason=%q", tripped, reason) + } + } + + // 2. Fatal QEMU error trips immediately. + wd2 := NewWatchdog(defaultWatchdogConfig(), t0) + if reason, _, tripped := wd2.Check(t0.Add(10*time.Second), pluginsdk.VMTelemetry{ + QemuErrors: []string{"fatal: WHPX partition failed"}, + }, StageInstallWait, false); !tripped || reason != "qemu_fatal_error" { + t.Fatalf("expected qemu_fatal_error, got tripped=%v reason=%q", tripped, reason) + } + + // 3. Stage 3 zero disk growth + frozen screen > 15m trips stage3_stalled. + wd3 := NewWatchdog(defaultWatchdogConfig(), t0) + if reason, _, tripped := wd3.Check(t0.Add(16*time.Minute), pluginsdk.VMTelemetry{DiskBytes: 1 << 30, CPUPercent: 0.5}, StageInstallWait, false); !tripped || reason != "stage3_stalled" { + t.Fatalf("expected stage3_stalled, got tripped=%v reason=%q", tripped, reason) + } +} + +func TestValidateConfigRejectsNonASCIIAndMissingSLA(t *testing.T) { + bad := RunConfig{VM: "macos:dev", FullName: "中文名", AccountName: "dev", GuestLang: "zh-Hans:0", SLAAccepted: true} + if err := ValidateConfig(&bad); err == nil { + t.Fatal("non-ASCII full_name must be rejected") + } + noSLA := RunConfig{VM: "macos:dev", FullName: "Dev", AccountName: "dev", GuestLang: "zh-Hans:0", SLAAccepted: false} + if err := ValidateConfig(&noSLA); err == nil { + t.Fatal("SLAAccepted=false must be rejected") + } + badLayout := RunConfig{VM: "macos:dev", FullName: "Dev", AccountName: "dev", GuestLang: "zh-Hans:1", SLAAccepted: true} + if err := ValidateConfig(&badLayout); err == nil { + t.Fatal("non-:0 GuestLang must be rejected") + } + recOnly := RunConfig{VM: "macos:dev", Mode: ModeRecoveryOnly, GuestLang: "zh-Hans:0", SLAAccepted: true} + if err := ValidateConfig(&recOnly); err != nil { + t.Fatalf("recovery_only without account credentials must validate, got %v", err) + } + recOnlyNoSLA := RunConfig{VM: "macos:dev", Mode: ModeRecoveryOnly, GuestLang: "zh-Hans:0", SLAAccepted: false} + if err := ValidateConfig(&recOnlyNoSLA); err == nil { + t.Fatal("recovery_only with SLAAccepted=false must still be rejected") + } + _ = filepath.Clean(".") +} + +func TestReplayCapturedRecoveryScreenshot(t *testing.T) { + imgPath := strings.TrimSpace(os.Getenv("REIMS_REPLAY_IMAGE")) + if imgPath == "" { + t.Skip("set REIMS_REPLAY_IMAGE to replay a real captured Recovery frame") + } + f, err := os.Open(imgPath) + if err != nil { + t.Fatal(err) + } + defer f.Close() + img, _, err := image.Decode(f) + if err != nil { + t.Fatal(err) + } + cropTop, _ := strconv.Atoi(strings.TrimSpace(os.Getenv("REIMS_REPLAY_CROP_TOP"))) + if cropTop > 0 { + b := img.Bounds() + img = vision.Crop(img, image.Rect(0, cropTop, b.Dx(), b.Dy())) + } + langs, _, err := ocr.ListWinOCRLanguages() + if err != nil || len(langs) == 0 { + t.Skip("WinRT OCR unavailable") + } + eng, err := ocr.NewWinOCREngine(langs[0]) + if err != nil { + t.Fatal(err) + } + defer eng.Close() + loc := vision.NewLocalLocator(eng) + b := img.Bounds() + menuScan, err := loc.ScanROI(context.Background(), img, "menu_bar", nil) + if err != nil { + t.Fatal(err) + } + t.Logf("Frame=%dx%d menu_bar ROI=%v text=%q", b.Dx(), b.Dy(), menuScan.ROI, menuScan.Text) + for _, ln := range menuScan.Lines { + t.Logf(" line=%q rect=%v words=%+v", ln.Text, ln.Rect, ln.Words) + } + _, pt, ok := rules.FindHit(menuScan.Lines, []string{"Utilities", "实用工具", "工具程式", "ユーティリティ"}, true) + t.Logf("FindHit(实用工具): ok=%v pt=%v (pct=%.2f%%, %.2f%%)", ok, pt, float64(pt.X)*100/float64(b.Dx()), float64(pt.Y)*100/float64(b.Dy())) + if !ok { + t.Fatalf("failed to locate 实用工具 in menu_bar text=%q", menuScan.Text) + } +} + +func TestReplayCapturedLoginScreenshot(t *testing.T) { + imgPath := strings.TrimSpace(os.Getenv("REIMS_REPLAY_LOGIN_IMAGE")) + if imgPath == "" { + t.Skip("set REIMS_REPLAY_LOGIN_IMAGE to replay a real captured macOS login screen") + } + f, err := os.Open(imgPath) + if err != nil { + t.Fatal(err) + } + defer f.Close() + img, _, err := image.Decode(f) + if err != nil { + t.Fatal(err) + } + langs, _, err := ocr.ListWinOCRLanguages() + if err != nil || len(langs) == 0 { + t.Skip("WinRT OCR unavailable") + } + eng, err := ocr.NewWinOCREngine(langs[0]) + if err != nil { + t.Fatal(err) + } + defer eng.Close() + loc := vision.NewLocalLocator(eng) + r := &Runner{locator: loc, cfg: RunConfig{FullName: "test", AccountName: "test"}} + menuScan, _ := loc.ScanROI(context.Background(), img, "menu_bar", nil) + titleScan, _ := loc.ScanROI(context.Background(), img, "title_band", nil) + bodyScan, _ := loc.ScanROI(context.Background(), img, "body", nil) + modalScan, _ := loc.ScanROI(context.Background(), img, "modal", nil) + loginScan, _ := loc.ScanROI(context.Background(), img, "login_band", nil) + t.Logf("menu_bar=%q title_band=%q body=%q login_band=%q", menuScan.Text, titleScan.Text, bodyScan.Text, loginScan.Text) + pt, confident, ok := r.detectLoginScreen(menuScan, titleScan, bodyScan, modalScan, loginScan) + t.Logf("detectLoginScreen: ok=%v confident=%v pt=%v", ok, confident, pt) + if !ok { + t.Fatalf("failed to detect macOS login screen from title_band=%q login_band=%q", titleScan.Text, loginScan.Text) + } +} + +func TestLooksLikeMacOSLockClockHeader(t *testing.T) { + for _, tc := range []struct { + name string + menu, title, body string + want bool + }{ + {"tahoe zh-Hans lock clock", "", "12 月 3 日 周 四 7 : 12", "", true}, + {"tahoe en-US lock clock", "", "Thursday, December 3\n7:12", "", true}, + {"desktop menu bar rejected", "Finder File Edit View 14:25", "12 月 3 日 周 四 7 : 12", "", false}, + {"recovery utilities rejected", "恢复 文件 编辑 实用工具 窗口", "12 月 3 日 7:12", "重新安装 macOS", false}, + {"setup assistant rejected", "", "选择国家或地区", "中国大陆", false}, + {"terminal mount/timestamp rejected", "", "mounted /Volumes/REIMSPROV at 08:54", "Preparing to run macOS Installer...", false}, + {"terminal iso timestamp rejected", "", "2026-12-03 08:54:12 Dec startosinstall", "", false}, + {"terminal shell menu rejected", "终端 Shell 编辑 显示 窗口", "12 月 3 日 周 四 7 : 12", "", false}, + {"long log text in body rejected", "", "Thursday, December 3 7:12", "Some very long non-wallpaper terminal output text here", false}, + } { + if got := looksLikeMacOSLockClockHeader(tc.menu, tc.title, tc.body); got != tc.want { + t.Errorf("%s: got %v, want %v", tc.name, got, tc.want) + } + } +} + +func TestDetectLoginScreenRejectsTerminalWithAccountNameAndRestart(t *testing.T) { + r := &Runner{cfg: RunConfig{FullName: "test", AccountName: "test"}} + menu := vision.ROIScan{Text: "终端 Shell 编辑 显示"} + title := vision.ROIScan{Text: "-bash-3.2# sh /Volumes/REIMSHELP/install.sh\n2026-12-03 08:54:12 mount test"} + body := vision.ROIScan{ + Text: "Preparing to run macOS Installer...\nInstalling provision.pkg for test\nRestarting...", + Lines: []ocr.Line{ + {Text: "Preparing to run macOS Installer..."}, + {Text: "test"}, + {Text: "Restarting..."}, + }, + } + if _, _, ok := r.detectLoginScreen(menu, title, body, vision.ROIScan{}, vision.ROIScan{}); ok { + t.Fatal("Recovery Terminal printing 'test' and 'Restarting...' must NEVER match Login Screen") + } +} + +func TestDualSignalProvisionReadyAndLoginUnlockFlow(t *testing.T) { + dataDir := t.TempDir() + eng, err := rules.LoadEngine(dataDir) + if err != nil { + t.Fatal(err) + } + + // Pre-seed checkpoint at Stage 3 (after Recovery Terminal launched install.sh). + vmKey := "builtin.driver.reims-macos::tahoe-prov" + cfg := RunConfig{ + VM: vmKey, + GuestLang: "zh-Hans:0", + FullName: "Reims User", + AccountName: "reims", + SecretSetting: "account_password", + Appearance: "dark", + SLAAccepted: true, + HasProvisionDisk: true, + } + if err := saveCheckpoint(dataDir, Checkpoint{ + Version: 1, + VM: vmKey, + Stage: StageInstallWait, + Status: StatusRunning, + Config: cfg, + StartedAt: time.Now().UTC(), + }); err != nil { + t.Fatal(err) + } + + mh := &mockHost{ + telemetry: pluginsdk.VMTelemetry{ + State: "running", + Phase: "installer", + BootMilestones: []pluginsdk.TelemetryMilestone{ + {Key: "serial:provision_ready", Count: 1}, + }, + }, + screens: []mockScreen{ + // 0: Still blank while serial:provision_ready already arrived -> Stage 3 exits via zero-OCR! + {blank: true}, + // 1: Post-finish_install reboot landed directly on macOS Login Screen. + { + advanceOnlyAtBottom: true, + rois: map[string]vision.ROIScan{ + "body": { + Text: "Reims User\n输入密码", + Lines: []ocr.Line{ + {Text: "Reims User", Rect: image.Rect(560, 340, 720, 380)}, + {Text: "输入密码", Rect: image.Rect(560, 410, 720, 445)}, + }, + }, + }, + }, + // 2: Desktop reached immediately after DPAPI TypeSecret + Return (no Setup Assistant!). + { + rois: map[string]vision.ROIScan{ + "menu_bar": scanText("访达 文件 编辑 显示 前往 窗口 帮助 14:25", image.Rect(10, 4, 1260, 28)), + }, + }, + }, + } + + r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, cfg, Options{ + PollInterval: time.Millisecond, + Stage3Interval: time.Millisecond, + PostActionWait: time.Millisecond, + DisableSleep: true, + }) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + r.Start(ctx) + r.Wait() + + st := r.Status() + if st.Status != StatusCompleted || st.Stage != StageDesktopReady { + t.Fatalf("unexpected final status: %+v", st) + } + if mh.finishInstall != 1 || mh.restarts != 1 { + t.Fatalf("expected finishInstall=1 restarts=1, got %d / %d", mh.finishInstall, mh.restarts) + } + if len(mh.typedSecrets) != 1 || mh.typedSecrets[0] != "account_password" { + t.Fatalf("expected exactly 1 DPAPI TypeSecret login unlock, got %v", mh.typedSecrets) + } + hasSerialRule, hasLoginRule := false, false + for _, id := range st.MatchedRules { + if id == "provision.serial_ready" { + hasSerialRule = true + } + if id == "provision.login_unlock" { + hasLoginRule = true + } + } + if !hasSerialRule || !hasLoginRule { + t.Fatalf("expected provision.serial_ready & provision.login_unlock in %v", st.MatchedRules) + } +} + +func TestInstallPkgUnsupportedFallbackFlow(t *testing.T) { + dataDir := t.TempDir() + eng, err := rules.LoadEngine(dataDir) + if err != nil { + t.Fatal(err) + } + vmKey := "builtin.driver.reims-macos::tahoe-fallback" + cfg := RunConfig{ + VM: vmKey, + GuestLang: "zh-Hans:0", + FullName: "Reims User", + AccountName: "reims", + SecretSetting: "account_password", + SLAAccepted: true, + HasProvisionDisk: true, + } + if err := saveCheckpoint(dataDir, Checkpoint{ + Version: 1, + VM: vmKey, + Stage: StageOfflineTerminal, + Status: StatusRunning, + Config: cfg, + StartedAt: time.Now().UTC(), + }); err != nil { + t.Fatal(err) + } + + mh := &mockHost{ + telemetry: pluginsdk.VMTelemetry{State: "running", Phase: "installer", DiskDeltaBytes: 4 << 20, CPUPercent: 35}, + screens: []mockScreen{ + // 0: Terminal already foreground showing startosinstall rejected --installpackage and fell back cleanly. + { + advanceOnScan: true, + rois: map[string]vision.ROIScan{ + "menu_bar": scanText("终端 Shell 编辑", image.Rect(40, 4, 240, 26)), + "terminal": scanText("REIMS_INSTALLPKG_UNSUPPORTED\nFalling back to plain startosinstall...\nPreparing to run macOS Installer", image.Rect(40, 80, 900, 260)), + }, + }, + // 1: Stage 3 falls back to Setup Assistant OCR detection -> Stage 4 finish_install + restart. + { + rois: map[string]vision.ROIScan{ + "title_band": scanText("选择国家或地区", image.Rect(300, 120, 900, 180)), + }, + }, + // 2: Post-restart desktop ready (short-circuit test end). + { + rois: map[string]vision.ROIScan{ + "menu_bar": scanText("Finder File Edit View Go Window Help 14:25", image.Rect(10, 4, 1260, 28)), + }, + }, + }, + } + + r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, cfg, Options{ + PollInterval: time.Millisecond, + Stage3Interval: time.Millisecond, + PostActionWait: time.Millisecond, + DisableSleep: true, + }) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + r.Start(ctx) + r.Wait() + + st := r.Status() + if st.Status != StatusCompleted { + t.Fatalf("expected fallback run to complete, got %+v", st) + } + cp, ok := LoadCheckpoint(dataDir, vmKey) + if !ok || !cp.ProvisionFallbackNeeded { + t.Fatalf("expected ProvisionFallbackNeeded=true in checkpoint, got ok=%v cp=%+v", ok, cp) + } +} + +func TestRecoveryOnlyHotkeyAndLockPolicyFlow(t *testing.T) { + dataDir := t.TempDir() + eng, err := rules.LoadEngine(dataDir) + if err != nil { + t.Fatal(err) + } + mh := &mockHost{ + telemetry: pluginsdk.VMTelemetry{State: "running", Phase: "installer", DiskBytes: 4 << 30, DiskDeltaBytes: 10 << 20, CPUPercent: 45}, + screens: []mockScreen{ + {blank: true}, + // 1: Recovery language selector -> Return + {rois: map[string]vision.ROIScan{"body": scanText("以简体中文作为主要语言", image.Rect(300, 200, 900, 260))}}, + // 2: Recovery main -> Shift+Cmd+T opens Terminal + {rois: map[string]vision.ROIScan{ + "menu_bar": scanText("实用工具", image.Rect(200, 4, 280, 28)), + "body": scanText("重新安装 macOS", image.Rect(400, 250, 800, 310)), + }}, + // 3: Terminal ready -> types install.sh + {rois: map[string]vision.ROIScan{ + "menu_bar": scanText("终端 Shell 编辑", image.Rect(40, 4, 260, 28)), + "terminal": scanText("-bash-3.2#", image.Rect(100, 100, 400, 140)), + }}, + // 4: install.sh running -> Stage 3 + {advanceOnScan: true, rois: map[string]vision.ROIScan{"terminal": scanText("Using target volume Macintosh HD\nPreparing to run macOS Installer", image.Rect(100, 100, 900, 240))}}, + // 5: Stage 3 reboot -> Apple progress -> Setup Assistant -> Stage 4 finish_install + restart + {vmStopped: true}, + {appleProg: true}, + {rois: map[string]vision.ROIScan{"title_band": scanText("选择国家或地区", image.Rect(300, 120, 900, 180))}}, + // 8: Post-restart Setup Assistant -> recovery_only completes immediately! + {rois: map[string]vision.ROIScan{"title_band": scanText("选择国家或地区", image.Rect(300, 120, 900, 180))}}, + }, + } + + r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, RunConfig{ + VM: "builtin.driver.reims-macos::tahoe-recovery-only", + Mode: ModeRecoveryOnly, + GuestLang: "zh-Hans:0", + SLAAccepted: true, + }, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + r.Start(ctx) + r.Wait() + + st := r.Status() + if st.Status != StatusCompleted || st.Stage != StageDesktopReady { + t.Fatalf("expected recovery_only completed, got %+v", st) + } + if mh.beginPolicy != "lock" { + t.Fatalf("expected TakeoverPolicy=lock, got %q", mh.beginPolicy) + } + if !mh.sessionBegan || !mh.sessionEnded { + t.Fatalf("expected session began & ended, got began=%v ended=%v", mh.sessionBegan, mh.sessionEnded) + } + if mh.finishInstall != 1 || mh.restarts != 1 { + t.Fatalf("expected finishInstall=1 restarts=1, got %d / %d", mh.finishInstall, mh.restarts) + } + if len(mh.typedSecrets) != 0 { + t.Fatalf("recovery_only must never call TypeSecret, got %v", mh.typedSecrets) + } + foundHotkey := false + for _, k := range mh.keys { + if k == "shift+meta_l+t" { + foundHotkey = true + } + } + if !foundHotkey { + t.Fatalf("expected shift+meta_l+t hotkey, got keys=%v", mh.keys) + } + hasBootRule := false + for _, id := range st.MatchedRules { + if id == "recovery_only.system_booted" { + hasBootRule = true + } + } + if !hasBootRule { + t.Fatalf("expected recovery_only.system_booted in matched rules %v", st.MatchedRules) + } +} + +func TestRecoveryHotkeyFallsBackToUtilitiesMenu(t *testing.T) { + dataDir := t.TempDir() + eng, err := rules.LoadEngine(dataDir) + if err != nil { + t.Fatal(err) + } + mh := &mockHost{ + ignoreHotkey: true, + telemetry: pluginsdk.VMTelemetry{State: "running", Phase: "installer", DiskDeltaBytes: 10 << 20, CPUPercent: 40}, + screens: []mockScreen{ + // 0: Recovery main -> Shift+Cmd+T ignored -> clicks Utilities + {rois: map[string]vision.ROIScan{ + "menu_bar": scanText("实用工具", image.Rect(200, 4, 280, 28)), + "body": scanText("重新安装 macOS", image.Rect(400, 250, 800, 310)), + }}, + // 1: Utilities dropdown -> clicks Terminal + {rois: map[string]vision.ROIScan{ + "menu_dropdown": scanText("终端", image.Rect(200, 90, 320, 120)), + }}, + // 2: Terminal open -> types install.sh + {rois: map[string]vision.ROIScan{ + "menu_bar": scanText("终端 Shell 编辑", image.Rect(40, 4, 260, 28)), + "terminal": scanText("-bash-3.2#", image.Rect(100, 100, 400, 140)), + }}, + // 3: install.sh running -> Stage 3 + {advanceOnScan: true, rois: map[string]vision.ROIScan{"terminal": scanText("startosinstall running", image.Rect(100, 100, 900, 240))}}, + // 4: Stage 3 -> Setup Assistant -> Stage 4 finish_install + restart + {rois: map[string]vision.ROIScan{"title_band": scanText("选择国家或地区", image.Rect(300, 120, 900, 180))}}, + // 5: Post-restart Setup Assistant -> complete + {rois: map[string]vision.ROIScan{"title_band": scanText("选择国家或地区", image.Rect(300, 120, 900, 180))}}, + }, + } + + r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, RunConfig{ + VM: "builtin.driver.reims-macos::tahoe-fallback-menu", + Mode: ModeRecoveryOnly, + GuestLang: "zh-Hans:0", + SLAAccepted: true, + }, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + r.Start(ctx) + r.Wait() + + st := r.Status() + if st.Status != StatusCompleted { + t.Fatalf("expected fallback flow to complete, got %+v", st) + } + hasFallbackRule := false + for _, id := range st.MatchedRules { + if id == "recovery.open_terminal_menu_fallback" { + hasFallbackRule = true + } + } + if !hasFallbackRule { + t.Fatalf("expected recovery.open_terminal_menu_fallback in %v", st.MatchedRules) + } +} + +func TestUserHUDPauseAndResumeFlow(t *testing.T) { + dataDir := t.TempDir() + eng, err := rules.LoadEngine(dataDir) + if err != nil { + t.Fatal(err) + } + vmKey := "builtin.driver.reims-macos::hud-pause" + cfg := RunConfig{ + VM: vmKey, + Mode: ModeRecoveryOnly, + GuestLang: "zh-Hans:0", + SLAAccepted: true, + } + if err := saveCheckpoint(dataDir, Checkpoint{ + Version: 1, + VM: vmKey, + Stage: StageSetupAssistant, + Status: StatusRunning, + FinishInstallDone: true, + Config: cfg, + StartedAt: time.Now().UTC(), + }); err != nil { + t.Fatal(err) + } + + mh := &mockHost{ + telemetry: pluginsdk.VMTelemetry{State: "running", Phase: "normal"}, + screens: []mockScreen{ + {rois: map[string]vision.ROIScan{"title_band": scanText("选择国家或地区", image.Rect(300, 120, 900, 180))}}, + }, + } + + r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, cfg, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + r.PauseByUser("user_paused") + if st := r.Status(); st.Status != StatusPausedForUser || st.PauseReason != "user_paused" { + t.Fatalf("expected immediate paused_for_user status, got %+v", st) + } + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + r.Start(ctx) + time.Sleep(30 * time.Millisecond) + if st := r.Status(); st.Status != StatusPausedForUser { + t.Fatalf("runner should remain paused until Resume(), got %+v", st) + } + r.Resume() + r.Wait() + if st := r.Status(); st.Status != StatusCompleted { + t.Fatalf("expected completion after Resume(), got %+v", st) + } +} + +func TestMarkCheckpointStoppedClearsStaleRunningState(t *testing.T) { + dataDir := t.TempDir() + vmKey := "builtin.driver.reims-macos::stale-run" + if err := saveCheckpoint(dataDir, Checkpoint{ + Version: 1, + VM: vmKey, + Stage: StageInstallWait, + Status: StatusRunning, + Config: RunConfig{VM: vmKey, Mode: ModeRecoveryOnly, GuestLang: "zh-Hans:0", SLAAccepted: true}, + }); err != nil { + t.Fatal(err) + } + if err := MarkCheckpointStopped(dataDir, vmKey, "Stopped by user"); err != nil { + t.Fatal(err) + } + cp, ok := LoadCheckpoint(dataDir, vmKey) + if !ok || cp.Status != StatusStopped { + t.Fatalf("expected StatusStopped on disk, got ok=%v cp=%+v", ok, cp) + } +} + +func TestWatchdogDeduplicatesRebootsAndAllowsHealthyInstallGrowth(t *testing.T) { + t0 := time.Date(2026, 12, 5, 12, 0, 0, 0, time.UTC) + wd := NewWatchdog(defaultWatchdogConfig(), t0) + + // 1. Same reboot incrementing both serial:xnu and ColdRebootCount within debounce counts once. + _, _, tripped := wd.Check(t0, pluginsdk.VMTelemetry{ + BootMilestones: []pluginsdk.TelemetryMilestone{{Key: "serial:xnu", Count: 1}}, + }, StageInstallWait, false) + if tripped { + t.Fatal("initial check must not trip") + } + _, _, tripped = wd.Check(t0.Add(30*time.Second), pluginsdk.VMTelemetry{ + ColdRebootCount: 1, + BootMilestones: []pluginsdk.TelemetryMilestone{{Key: "serial:xnu", Count: 2}}, + }, StageInstallWait, false) + if tripped { + t.Fatal("single reboot with both cold reboot and serial:xnu must not trip") + } + // Another serial:xnu bump 5s later (same boot) must also be debounced. + _, _, tripped = wd.Check(t0.Add(35*time.Second), pluginsdk.VMTelemetry{ + ColdRebootCount: 1, + BootMilestones: []pluginsdk.TelemetryMilestone{{Key: "serial:xnu", Count: 3}}, + }, StageInstallWait, false) + if tripped || len(wd.rebootEvents) != 1 { + t.Fatalf("expected 1 debounced reboot event, got tripped=%v events=%d", tripped, len(wd.rebootEvents)) + } + + // 2. Normal macOS installation reboots accompanied by >= 32 MiB disk growth never false-trip. + wdInstall := NewWatchdog(defaultWatchdogConfig(), t0) + var disk int64 = 1 << 30 + for i := 1; i <= 4; i++ { + disk += 256 << 20 // +256 MiB written between install stages + reason, detail, tripped := wdInstall.Check(t0.Add(time.Duration(i)*time.Minute), pluginsdk.VMTelemetry{ + ColdRebootCount: i, + DiskBytes: disk, + DiskDeltaBytes: 256 << 20, + }, StageInstallWait, true) + if tripped { + t.Fatalf("healthy install reboot %d falsely tripped watchdog: %s (%s)", i, reason, detail) + } + } + + // 3. ResetAfterResume and ResetRebootWindow clear prior reboot history cleanly. + wdReset := NewWatchdog(defaultWatchdogConfig(), t0) + for i := 1; i <= 3; i++ { + wdReset.Check(t0.Add(time.Duration(i)*time.Minute), pluginsdk.VMTelemetry{ColdRebootCount: i}, StageInstallWait, false) + } + wdReset.ResetAfterResume(t0.Add(3*time.Minute + 5*time.Second)) + if _, _, tripped := wdReset.Check(t0.Add(3*time.Minute+10*time.Second), pluginsdk.VMTelemetry{ColdRebootCount: 3}, StageInstallWait, false); tripped { + t.Fatal("ResetAfterResume must prevent immediate re-trip on stale reboot events") + } + wdReset.ResetRebootWindow(t0.Add(4 * time.Minute)) + if _, _, tripped := wdReset.Check(t0.Add(4*time.Minute+5*time.Second), pluginsdk.VMTelemetry{ColdRebootCount: 4}, StageSetupAssistant, false); tripped { + t.Fatal("ResetRebootWindow must allow intentional Stage 4 restart without tripping Stage 5") + } +} + +func TestRecoveryOnlyExitsAtCountryRegionWithNoisyTitleBandAndFallback(t *testing.T) { + dataDir := t.TempDir() + eng, err := rules.LoadEngine(dataDir) + if err != nil { + t.Fatal(err) + } + vmKey := "builtin.driver.reims-macos::tahoe-country-exit" + cfg := RunConfig{ + VM: vmKey, + Mode: ModeRecoveryOnly, + GuestLang: "zh-Hans:0", + SLAAccepted: true, + } + if err := saveCheckpoint(dataDir, Checkpoint{ + Version: 1, + VM: vmKey, + Stage: StageInstallWait, + Status: StatusRunning, + Config: cfg, + StartedAt: time.Now().UTC(), + }); err != nil { + t.Fatal(err) + } + + mh := &mockHost{ + telemetry: pluginsdk.VMTelemetry{State: "running", Phase: "installer", DiskBytes: 12 << 30, CPUPercent: 15}, + screens: []mockScreen{ + // 0: Stage 3 lands on "选择国家或地区" where title_band only picked up "<" back icon, + // and body carries the heading + country list (exact Sequoia/Tahoe Setup Assistant layout). + {rois: map[string]vision.ROIScan{ + "menu_bar": scanText("ABC 下午 11:55", image.Rect(900, 4, 1260, 26)), + "title_band": scanText("<", image.Rect(300, 140, 320, 160)), + "body": scanText("选择国家或地区\n阿尔巴尼亚\n阿尔及利亚\n阿富汗", image.Rect(360, 220, 760, 480)), + "login_band": scanText("按下 Command-Option-F5 来查看辅助功能选项", image.Rect(400, 580, 880, 620)), + }}, + // 1: Post-restart Stage 5 lands on Setup Assistant again (matched even via VoiceOver/country fallback) -> exits immediately! + {rois: map[string]vision.ROIScan{ + "menu_bar": scanText("ABC 下午 11:56", image.Rect(900, 4, 1260, 26)), + "body": scanText("阿尔巴尼亚\n阿尔及利亚\n阿富汗", image.Rect(360, 240, 760, 480)), + "login_band": scanText("按下 escape 键以听取如何通过旁白设置您的 Mac", image.Rect(400, 580, 880, 620)), + }}, + }, + } + + r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, cfg, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + r.Start(ctx) + r.Wait() + + st := r.Status() + if st.Status != StatusCompleted || st.Stage != StageDesktopReady { + t.Fatalf("expected recovery_only to exit completed at Setup Assistant, got %+v", st) + } + if mh.finishInstall != 1 || mh.restarts != 1 { + t.Fatalf("expected finishInstall=1 restarts=1, got %d / %d", mh.finishInstall, mh.restarts) + } + if len(mh.clicks) != 0 || len(mh.keys) != 0 || len(mh.typedTexts) != 0 || len(mh.typedSecrets) != 0 { + t.Fatalf("recovery_only must not interact with Setup Assistant: clicks=%v keys=%v texts=%v secrets=%v", + mh.clicks, mh.keys, mh.typedTexts, mh.typedSecrets) + } + + sawWaitRebootStage := false + sawCompletedUpdate := false + for _, upd := range mh.sessionUpdates { + if upd.Stage == "stage5_wait_reboot" { + sawWaitRebootStage = true + } + if upd.Stage == StageSetupAssistant { + t.Fatalf("recovery_only should report stage5_wait_reboot instead of stage5_setup_assistant to host HUD") + } + if upd.Status == StatusCompleted { + sawCompletedUpdate = true + } + } + if !sawWaitRebootStage { + t.Fatalf("expected stage5_wait_reboot host session update in recovery_only mode, got %+v", mh.sessionUpdates) + } + if !sawCompletedUpdate || !mh.sessionEnded { + t.Fatalf("expected completed session update before session end, got completedUpdate=%v ended=%v", sawCompletedUpdate, mh.sessionEnded) + } +} + +func TestRecoveryOnlySkipsRedundantRestartWhenAlreadyInNormalPhase(t *testing.T) { + dataDir := t.TempDir() + eng, err := rules.LoadEngine(dataDir) + if err != nil { + t.Fatal(err) + } + vmKey := "builtin.driver.reims-macos::already-normal" + cfg := RunConfig{ + VM: vmKey, + Mode: ModeRecoveryOnly, + GuestLang: "zh-Hans:0", + SLAAccepted: true, + } + if err := saveCheckpoint(dataDir, Checkpoint{ + Version: 1, + VM: vmKey, + Stage: StageInstallWait, + Status: StatusRunning, + Config: cfg, + StartedAt: time.Now().UTC(), + }); err != nil { + t.Fatal(err) + } + + mh := &mockHost{ + telemetry: pluginsdk.VMTelemetry{State: "running", Phase: "normal"}, + finishResp: map[string]any{ + "ok": true, + "running": true, + "installer_ejected": false, + "network_enabled": false, + "upgraded_nvme": false, + "recovery_pending": false, + "helper_stripped": false, + }, + screens: []mockScreen{ + {rois: map[string]vision.ROIScan{ + "title_band": scanText("选择国家或地区", image.Rect(300, 210, 760, 250)), + }}, + }, + } + + r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, cfg, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + r.Start(ctx) + r.Wait() + + if st := r.Status(); st.Status != StatusCompleted { + t.Fatalf("expected immediate completion in normal phase, got %+v", st) + } + if mh.finishInstall != 1 || mh.restarts != 0 { + t.Fatalf("expected finishInstall=1 and restarts=0 when already normal with no changes, got %d / %d", mh.finishInstall, mh.restarts) + } +} + +func TestBeginSessionFailureStillEndsSession(t *testing.T) { + dataDir := t.TempDir() + eng, err := rules.LoadEngine(dataDir) + if err != nil { + t.Fatal(err) + } + mh := &mockHost{ + beginErr: errors.New("authorization denied"), + } + cfg := RunConfig{ + VM: "builtin.driver.reims-macos::begin-fail", + Mode: ModeRecoveryOnly, + GuestLang: "zh-Hans:0", + SLAAccepted: true, + } + r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, cfg, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + r.Start(ctx) + r.Wait() + + if st := r.Status(); st.Status != StatusFailed { + t.Fatalf("expected StatusFailed when BeginSession fails, got %+v", st) + } + if !mh.sessionEnded { + t.Fatal("expected EndSession to be called even when BeginSession fails so host restores manual guide") + } +} + +func TestPermissionDeniedInTerminalFlowFailsImmediately(t *testing.T) { + t.Run("hotkey confirmation_denied fails immediately without menu fallback or typing", func(t *testing.T) { + dataDir := t.TempDir() + eng, err := rules.LoadEngine(dataDir) + if err != nil { + t.Fatal(err) + } + mh := &mockHost{ + keyPressErr: errors.New("confirmation_denied: user denied recovery permission"), + screens: []mockScreen{ + {rois: map[string]vision.ROIScan{ + "menu_bar": scanText("实用工具", image.Rect(200, 4, 280, 28)), + "body": scanText("重新安装 macOS", image.Rect(400, 250, 800, 310)), + }}, + }, + } + cfg := RunConfig{ + VM: "builtin.driver.reims-macos::deny-hotkey", + Mode: ModeRecoveryOnly, + GuestLang: "zh-Hans:0", + SLAAccepted: true, + } + _ = saveCheckpoint(dataDir, Checkpoint{ + Version: 1, + VM: cfg.VM, + Stage: StageOfflineTerminal, + Status: StatusRunning, + Config: cfg, + }) + r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, cfg, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + r.Start(ctx) + r.Wait() + + st := r.Status() + if st.Status != StatusFailed || st.PauseReason != "permission_denied" { + t.Fatalf("expected StatusFailed/permission_denied, got %+v", st) + } + if len(mh.clicks) != 0 || len(mh.typedTexts) != 0 { + t.Fatalf("must not fall through to menu click or typing on permission denial: clicks=%v texts=%v", mh.clicks, mh.typedTexts) + } + if !mh.sessionEnded { + t.Fatal("expected EndSession called on permission denial") + } + }) + + t.Run("waitForTerminalReady confirmation_denied fails immediately", func(t *testing.T) { + dataDir := t.TempDir() + eng, err := rules.LoadEngine(dataDir) + if err != nil { + t.Fatal(err) + } + mh := &mockHost{ + screenshotErrAt: 2, + screenshotErr: errors.New("confirmation_denied: user denied installer permission"), + screens: []mockScreen{ + {rois: map[string]vision.ROIScan{ + "menu_bar": scanText("实用工具", image.Rect(200, 4, 280, 28)), + "body": scanText("重新安装 macOS", image.Rect(400, 250, 800, 310)), + }}, + {rois: map[string]vision.ROIScan{ + "menu_bar": scanText("终端 Shell 编辑", image.Rect(40, 4, 260, 28)), + }}, + }, + } + cfg := RunConfig{ + VM: "builtin.driver.reims-macos::deny-wait-term", + Mode: ModeRecoveryOnly, + GuestLang: "zh-Hans:0", + SLAAccepted: true, + } + _ = saveCheckpoint(dataDir, Checkpoint{ + Version: 1, + VM: cfg.VM, + Stage: StageOfflineTerminal, + Status: StatusRunning, + Config: cfg, + }) + r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, cfg, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + r.Start(ctx) + r.Wait() + + st := r.Status() + if st.Status != StatusFailed || st.PauseReason != "permission_denied" { + t.Fatalf("expected StatusFailed/permission_denied, got %+v", st) + } + if len(mh.clicks) != 0 || len(mh.typedTexts) != 0 { + t.Fatalf("must not fall through to menu click or typing on waitForTerminalReady denial: clicks=%v texts=%v", mh.clicks, mh.typedTexts) + } + if !mh.sessionEnded { + t.Fatal("expected EndSession called on permission denial") + } + }) +} + +func TestStaleResumeTokenNeverBypassesSafetyPauseAndStopBeforeStartNeverDeadlocks(t *testing.T) { + dataDir := t.TempDir() + eng, err := rules.LoadEngine(dataDir) + if err != nil { + t.Fatal(err) + } + cfg := RunConfig{ + VM: "builtin.driver.reims-macos::stale-resume", + Mode: ModeRecoveryOnly, + GuestLang: "zh-Hans:0", + SLAAccepted: true, + } + + // 1. Stop before Start must unblock Wait immediately and prevent BeginSession. + mhStopped := &mockHost{} + rStopped, err := New(mhStopped, &mockLocator{host: mhStopped}, eng, dataDir, cfg, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + rStopped.Stop() + rStopped.Start(context.Background()) + rStopped.Wait() + if mhStopped.sessionBegan { + t.Fatal("Stop() before Start() must prevent BeginSession from running") + } + + // 2. An earlier Pause+Resume while not blocked in pauseAndWaitResume must NOT + // leave a stale token in resumeCh that auto-skips a later safety pause. + mh := &mockHost{} + r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, cfg, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + r.PauseByUser("user_paused") + r.Resume() + + pCtx, pCancel := context.WithTimeout(context.Background(), 120*time.Millisecond) + defer pCancel() + pauseErr := r.pauseAndWaitResume(pCtx, "high_risk_guard:erase", "Paused on erase prompt", "Erase disk") + if !errors.Is(pauseErr, context.DeadlineExceeded) { + t.Fatalf("stale resume token bypassed safety pause! err=%v", pauseErr) + } +} + +func TestWatchdogResumeAcknowledgesQemuErrorAndExtendsTimeout(t *testing.T) { + t0 := time.Date(2026, 12, 5, 12, 0, 0, 0, time.UTC) + wd := NewWatchdog(WatchdogConfig{TotalInstallTimeout: 30 * time.Minute}, t0) + + // 1. Fatal QEMU error trips once, then Resume acknowledges that exact line so + // it does not infinite-loop; a brand-new fatal line still trips. + tel := pluginsdk.VMTelemetry{QemuErrors: []string{"fatal: device init failed"}} + if reason, _, tripped := wd.Check(t0.Add(time.Minute), tel, StageInstallWait, false); !tripped || reason != "qemu_fatal_error" { + t.Fatalf("expected qemu_fatal_error, got %q tripped=%v", reason, tripped) + } + wd.ResetAfterResume(t0.Add(2 * time.Minute)) + if reason, _, tripped := wd.Check(t0.Add(3*time.Minute), tel, StageInstallWait, false); tripped { + t.Fatalf("acknowledged qemu error re-tripped after Resume: %q", reason) + } + // ResetRebootWindow (triggered on Stage 3/4 transitions) must preserve ackedQemuErrors. + wd.ResetRebootWindow(t0.Add(3*time.Minute + 30*time.Second)) + if reason, _, tripped := wd.Check(t0.Add(3*time.Minute+45*time.Second), tel, StageSetupAssistant, false); tripped { + t.Fatalf("acknowledged qemu error re-tripped after ResetRebootWindow: %q", reason) + } + tel2 := pluginsdk.VMTelemetry{QemuErrors: []string{"fatal: device init failed", "fatal: second crash"}} + if reason, _, tripped := wd.Check(t0.Add(4*time.Minute), tel2, StageInstallWait, false); !tripped || reason != "qemu_fatal_error" { + t.Fatalf("new qemu error must still trip watchdog, got %q tripped=%v", reason, tripped) + } + + // 2. TotalInstallTimeout trips, and Resume extends the budget instead of re-tripping immediately. + wdTO := NewWatchdog(WatchdogConfig{TotalInstallTimeout: 10 * time.Minute}, t0) + if reason, _, tripped := wdTO.Check(t0.Add(11*time.Minute), pluginsdk.VMTelemetry{}, StageInstallWait, true); !tripped || reason != "install_timeout" { + t.Fatalf("expected install_timeout, got %q tripped=%v", reason, tripped) + } + wdTO.ResetAfterResume(t0.Add(12 * time.Minute)) + if reason, _, tripped := wdTO.Check(t0.Add(13*time.Minute), pluginsdk.VMTelemetry{}, StageInstallWait, true); tripped { + t.Fatalf("install_timeout re-tripped immediately after Resume: %q", reason) + } +} + +func TestRedactDiagnosticTextUnicodeAndUTF8Truncation(t *testing.T) { + cfg := RunConfig{FullName: "Alice", AccountName: "alice"} + // Turkish capital dotted I (İ -> i\u0307) changes byte length on strings.ToLower; + // previously caused a slice bounds panic or UTF-8 corruption. + raw := "İSTANBUL " + strings.Repeat("中文诊断信息", 300) + " ALICE" + got := RedactDiagnosticText(raw, cfg) + if !utf8.ValidString(got) { + t.Fatalf("RedactDiagnosticText produced invalid UTF-8") + } + if strings.Contains(strings.ToLower(got), "alice") { + t.Fatalf("expected user name to be redacted, got %q", got) + } +} + +func TestFillAccountFormPrefersExactLabelOverSubtitle(t *testing.T) { + lines := []ocr.Line{ + {Text: "Create a password to protect your Mac account", Rect: image.Rect(300, 180, 900, 210)}, + {Text: "Password:", Rect: image.Rect(320, 340, 440, 370)}, + } + ln, ok := findFormFieldLabel(lines, []string{"Password", "密码"}) + if !ok || ln.Rect.Min.Y != 340 { + t.Fatalf("expected exact Password label at Y=340, got ok=%v ln=%+v", ok, ln) + } +} + +func TestStaleAndNormalPhaseRunningCheckpointsReorientSafely(t *testing.T) { + eng, err := rules.LoadEngine(t.TempDir()) + if err != nil { + t.Fatal(err) + } + + // 1. Stale (>2h old) StatusRunning checkpoint falls back to StageBootRecovery. + dataDir := t.TempDir() + vmKey := "builtin.driver.reims-macos:stale-crash" + cfg := RunConfig{VM: vmKey, Mode: ModeRecoveryOnly, GuestLang: "zh-Hans:0", SLAAccepted: true} + now := time.Date(2026, 12, 5, 12, 0, 0, 0, time.UTC) + staleCP := Checkpoint{ + Version: 1, + VM: vmKey, + Stage: StageOfflineTerminal, + Status: StatusRunning, + Config: cfg, + StartedAt: now.Add(-5 * time.Hour), + UpdatedAt: now.Add(-3 * time.Hour), + } + raw, _ := json.Marshal(staleCP) + if err := os.MkdirAll(filepath.Join(dataDir, "runs"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(checkpointPath(dataDir, vmKey), raw, 0o600); err != nil { + t.Fatal(err) + } + mh := &mockHost{} + r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, cfg, Options{ + DisableSleep: true, + NowFunc: func() time.Time { return now }, + }) + if err != nil { + t.Fatal(err) + } + if got := r.Status().Stage; got != StageBootRecovery { + t.Fatalf("stale StatusRunning checkpoint stage = %q, want %q", got, StageBootRecovery) + } + + // 2. Fresh StatusRunning checkpoint at StageOfflineTerminal re-orients when + // telemetry reports Phase=normal + FinishInstallDone=true (never fires Recovery hotkeys). + dataDir2 := t.TempDir() + vmKey2 := "builtin.driver.reims-macos:normal-reorient" + cfg2 := RunConfig{VM: vmKey2, Mode: ModeRecoveryOnly, GuestLang: "zh-Hans:0", SLAAccepted: true} + if err := saveCheckpoint(dataDir2, Checkpoint{ + Version: 1, + VM: vmKey2, + Stage: StageOfflineTerminal, + Status: StatusRunning, + FinishInstallDone: true, + Config: cfg2, + StartedAt: time.Now().UTC(), + }); err != nil { + t.Fatal(err) + } + mh2 := &mockHost{ + telemetry: pluginsdk.VMTelemetry{State: "running", Phase: "normal"}, + screens: []mockScreen{{ + rois: map[string]vision.ROIScan{ + "title_band": scanText("选择国家或地区", image.Rect(300, 120, 900, 180)), + }, + }}, + } + r2, err := New(mh2, &mockLocator{host: mh2}, eng, dataDir2, cfg2, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + r2.Start(ctx) + r2.Wait() + if st := r2.Status(); st.Status != StatusCompleted { + t.Fatalf("expected normal-phase re-oriented run to complete, got %+v", st) + } + for _, k := range mh2.keys { + if strings.Contains(k, "meta_l") { + t.Fatalf("normal-phase re-oriented run must not send Recovery Terminal hotkey, saw keys=%v", mh2.keys) + } + } +} + +func TestCheckpointPathCollisionFreeAndValidatesVMRef(t *testing.T) { + dataDir := t.TempDir() + // Distinct keys whose naive separator replacement would collide must get distinct paths. + p1 := checkpointPath(dataDir, "a/b") + p2 := checkpointPath(dataDir, "a_b") + p3 := checkpointPath(dataDir, "VM1") + p4 := checkpointPath(dataDir, "vm1") + if p1 == p2 { + t.Fatalf("a/b and a_b collided at %q", p1) + } + if p3 == p4 { + t.Fatalf("VM1 and vm1 collided at %q", p3) + } + runsDir := filepath.Join(dataDir, "runs") + for _, key := range []string{"..", ".", "CON", "NUL", `..\..\evil`} { + p := checkpointPath(dataDir, key) + if filepath.Dir(p) != runsDir { + t.Fatalf("checkpointPath(%q) escaped runs dir: %q", key, p) + } + base := strings.ToUpper(filepath.Base(p)) + if base == "CON.JSON" || base == "NUL.JSON" || base == "...JSON" { + t.Fatalf("checkpointPath(%q) produced unsafe filename %q", key, base) + } + } + + // ValidateConfig must reject "."/".." and control characters in VM ref. + for _, badVM := range []string{"..", ".", "vm\x00name", "vm\nname"} { + cfg := RunConfig{VM: badVM, Mode: ModeRecoveryOnly, GuestLang: "zh-Hans:0", SLAAccepted: true} + if err := ValidateConfig(&cfg); err == nil { + t.Fatalf("expected ValidateConfig to reject bad VM %q", badVM) + } + } +} + +func TestRedactDiagnosticTextScrubsPIIAndHardwareIdentifiers(t *testing.T) { + raw := "User Alice (alice@example.com) on 192.168.1.42 MAC aa:bb:cc:dd:ee:ff " + + "UUID 123e4567-e89b-12d3-a456-426614174000 serial C02ABC123456 " + + `path /Users/alice/Documents/secret C:\Users\alice\Desktop\file ` + + "token=0123456789abcdef0123456789abcdef01234567" + got := RedactDiagnosticText(raw, RunConfig{FullName: "Alice", AccountName: "alice"}) + for _, leak := range []string{ + "alice", "Alice", "example.com", "192.168.1.42", "aa:bb:cc:dd:ee:ff", + "123e4567-e89b-12d3-a456-426614174000", "C02ABC123456", + "/Users/alice", `C:\Users\alice`, "0123456789abcdef0123456789abcdef", + } { + if strings.Contains(got, leak) { + t.Fatalf("RedactDiagnosticText leaked %q in %q", leak, got) + } + } +} + +func TestFillAccountFormRejectsMissingInputBoxAndMissingMaskDots(t *testing.T) { + eng, err := rules.LoadEngine(t.TempDir()) + if err != nil { + t.Fatal(err) + } + cfg := RunConfig{ + VM: "builtin.driver.reims-macos:form-guard", Mode: ModeFull, + GuestLang: "zh-Hans:0", FullName: "Reims User", AccountName: "reims", + SecretSetting: "account_password", SLAAccepted: true, + } + bodyScan := vision.ROIScan{ + Text: "Password\nVerify", + Lines: []ocr.Line{ + {Text: "Password", Rect: image.Rect(320, 360, 440, 390)}, + {Text: "Verify", Rect: image.Rect(320, 410, 440, 440)}, + }, + } + + // 1. Uniform blank light-mode screen (no input box next to Password) must pause without calling TypeSecret. + mh1 := &mockHost{} + r1, err := New(mh1, &mockLocator{host: mh1}, eng, t.TempDir(), cfg, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + blankLight := image.NewRGBA(image.Rect(0, 0, 1280, 720)) + for y := 0; y < 720; y++ { + for x := 0; x < 1280; x++ { + blankLight.SetRGBA(x, y, color.RGBA{236, 236, 236, 255}) + } + } + ctx1, cancel1 := context.WithCancel(context.Background()) + go func() { + for i := 0; i < 100; i++ { + if r1.Status().Status == StatusPausedForUser { + cancel1() + return + } + time.Sleep(5 * time.Millisecond) + } + cancel1() + }() + _ = r1.fillAccountForm(ctx1, blankLight, hostclient.ScreenshotMeta{}, bodyScan) + if len(mh1.typedSecrets) != 0 { + t.Fatalf("must NOT call TypeSecret when input box is missing, got %v", mh1.typedSecrets) + } + if st := r1.Status(); st.Status != StatusPausedForUser || st.PauseReason != "account_form_incomplete" { + t.Fatalf("expected account_form_incomplete pause, got %+v", st) + } + + // 2. Input boxes exist, but TypeSecret yields no bullet-dot delta -> pause immediately before Verify field! + mh2 := &mockHost{ + suppressMaskDots: true, + screens: []mockScreen{{ + drawInputFields: []image.Rectangle{ + image.Rect(460, 362, 700, 388), + image.Rect(460, 412, 700, 438), + }, + }}, + } + r2, err := New(mh2, &mockLocator{host: mh2}, eng, t.TempDir(), cfg, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + formImg, _, _ := mh2.Screenshot(context.Background(), pluginsdk.ScreenshotRequest{}) + ctx2, cancel2 := context.WithCancel(context.Background()) + go func() { + for i := 0; i < 100; i++ { + if r2.Status().Status == StatusPausedForUser { + cancel2() + return + } + time.Sleep(5 * time.Millisecond) + } + cancel2() + }() + _ = r2.fillAccountForm(ctx2, formImg, hostclient.ScreenshotMeta{}, bodyScan) + if len(mh2.typedSecrets) != 1 { + t.Fatalf("expected abort after 1st failed mask-dots check without typing 2nd field, got %d TypeSecret calls", len(mh2.typedSecrets)) + } + if st := r2.Status(); st.Status != StatusPausedForUser || st.PauseReason != "account_form_incomplete" { + t.Fatalf("expected account_form_incomplete pause on missing mask dots, got %+v", st) + } +} + +func TestLoginUnlockRefusesClockHeaderOnlyAndMissingMaskDots(t *testing.T) { + eng, err := rules.LoadEngine(t.TempDir()) + if err != nil { + t.Fatal(err) + } + cfg := RunConfig{ + VM: "builtin.driver.reims-macos:login-guard", Mode: ModeFull, + GuestLang: "zh-Hans:0", FullName: "Reims User", AccountName: "reims", + SecretSetting: "account_password", SLAAccepted: true, HasProvisionDisk: true, + } + + // 1. Clock-header-only screen: sends one harmless shift wake, then pauses with ZERO TypeSecret calls. + mh := &mockHost{ + screens: []mockScreen{{ + rois: map[string]vision.ROIScan{ + "title_band": scanText("Thursday, December 3\n7:12", image.Rect(400, 100, 880, 220)), + }, + }}, + } + r, err := New(mh, &mockLocator{host: mh}, eng, t.TempDir(), cfg, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + img, _, _ := mh.Screenshot(context.Background(), pluginsdk.ScreenshotRequest{}) + attempts := 0 + woke := false + if err := r.tryUnlockLoginScreen(context.Background(), img, image.Point{}, false, "Thursday, December 3 7:12", &attempts, &woke); err != nil { + t.Fatalf("first clock-header wake failed: %v", err) + } + if len(mh.typedSecrets) != 0 || !woke { + t.Fatalf("clock-header-only wake must not type secret; secrets=%v woke=%v", mh.typedSecrets, woke) + } + ctx, cancel := context.WithCancel(context.Background()) + go func() { + for i := 0; i < 100; i++ { + if r.Status().Status == StatusPausedForUser { + cancel() + return + } + time.Sleep(5 * time.Millisecond) + } + cancel() + }() + _ = r.tryUnlockLoginScreen(ctx, img, image.Point{}, false, "Thursday, December 3 7:12", &attempts, &woke) + if len(mh.typedSecrets) != 0 { + t.Fatalf("clock-header-only screen must NEVER call TypeSecret, got %v", mh.typedSecrets) + } + if st := r.Status(); st.Status != StatusPausedForUser || st.PauseReason != "login_screen_unconfirmed" { + t.Fatalf("expected login_screen_unconfirmed pause, got %+v", st) + } + + // 2. Confident login screen whose password field shows NO mask dots after TypeSecret must pause without pressing Return. + mh2 := &mockHost{suppressMaskDots: true, screens: []mockScreen{{}}} + r2, err := New(mh2, &mockLocator{host: mh2}, eng, t.TempDir(), cfg, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + img2, _, _ := mh2.Screenshot(context.Background(), pluginsdk.ScreenshotRequest{}) + ctx2, cancel2 := context.WithCancel(context.Background()) + go func() { + for i := 0; i < 100; i++ { + if r2.Status().Status == StatusPausedForUser { + cancel2() + return + } + time.Sleep(5 * time.Millisecond) + } + cancel2() + }() + attempts2 := 0 + woke2 := false + _ = r2.tryUnlockLoginScreen(ctx2, img2, image.Pt(640, 427), true, "输入密码", &attempts2, &woke2) + for _, k := range mh2.keys { + if k == "ret" { + t.Fatal("must NOT press Return when login password mask dots did not appear") + } + } + if st := r2.Status(); st.Status != StatusPausedForUser || st.PauseReason != "login_unlock_failed" { + t.Fatalf("expected login_unlock_failed pause, got %+v", st) + } +} + +func TestOfflineTerminalRequiresShellPromptBeforeTyping(t *testing.T) { + eng, err := rules.LoadEngine(t.TempDir()) + if err != nil { + t.Fatal(err) + } + mh := &mockHost{ + screens: []mockScreen{ + // Recovery main screen -> runner presses Shift+Cmd+T. + {rois: map[string]vision.ROIScan{ + "menu_bar": scanText("实用工具", image.Rect(200, 4, 280, 28)), + "body": scanText("重新安装 macOS", image.Rect(400, 250, 800, 310)), + }}, + // Menu bar switches to Terminal, but terminal ROI has NO shell prompt yet. + {rois: map[string]vision.ROIScan{ + "menu_bar": scanText("终端 Shell 编辑", image.Rect(40, 4, 260, 28)), + "terminal": scanText("", image.Rect(100, 100, 400, 140)), + }}, + }, + } + cfg := RunConfig{ + VM: "builtin.driver.reims-macos:term-guard", Mode: ModeRecoveryOnly, + GuestLang: "zh-Hans:0", SLAAccepted: true, + } + r, err := New(mh, &mockLocator{host: mh}, eng, t.TempDir(), cfg, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + go func() { + for i := 0; i < 100; i++ { + if r.Status().Status == StatusPausedForUser { + cancel() + return + } + time.Sleep(5 * time.Millisecond) + } + cancel() + }() + _ = r.stepOfflineTerminal(ctx, NewWatchdog(WatchdogConfig{}, time.Now())) + if len(mh.typedTexts) != 0 { + t.Fatalf("must NOT inject install.sh before shell prompt is confirmed, got typedTexts=%v", mh.typedTexts) + } + if st := r.Status(); st.Status != StatusPausedForUser || st.PauseReason != "terminal_not_ready" { + t.Fatalf("expected terminal_not_ready pause, got %+v", st) + } +} + +func TestLoginUnlockPausesWhenAfterScreenshotFails(t *testing.T) { + eng, err := rules.LoadEngine(t.TempDir()) + if err != nil { + t.Fatal(err) + } + cfg := RunConfig{ + VM: "builtin.driver.reims-macos:login-err", Mode: ModeFull, + GuestLang: "zh-Hans:0", FullName: "Reims User", AccountName: "reims", + SecretSetting: "account_password", SLAAccepted: true, HasProvisionDisk: true, + } + mh := &mockHost{ + screens: []mockScreen{{}}, + screenshotErrAt: 2, // Call 1 = beforeImg (ok), Call 2 = afterImg (fails) + screenshotErr: errors.New("transient capture timeout"), + } + r, err := New(mh, &mockLocator{host: mh}, eng, t.TempDir(), cfg, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + baseImg := image.NewRGBA(image.Rect(0, 0, 1280, 720)) + ctx, cancel := context.WithCancel(context.Background()) + go func() { + for i := 0; i < 100; i++ { + if r.Status().Status == StatusPausedForUser { + cancel() + return + } + time.Sleep(5 * time.Millisecond) + } + cancel() + }() + attempts := 0 + woke := false + _ = r.tryUnlockLoginScreen(ctx, baseImg, image.Pt(640, 427), true, "输入密码", &attempts, &woke) + for _, k := range mh.keys { + if k == "ret" { + t.Fatal("must NOT press Return when post-TypeSecret screenshot fails") + } + } + if attempts != 0 { + t.Fatalf("expected loginAttempts not incremented on screenshot error, got %d", attempts) + } + if st := r.Status(); st.Status != StatusPausedForUser || st.PauseReason != "login_unlock_failed" { + t.Fatalf("expected login_unlock_failed pause, got %+v", st) + } +} + +func TestWatchdogResetRebootWindowRebaselinesColdRebootCount(t *testing.T) { + t0 := time.Date(2026, 12, 5, 12, 0, 0, 0, time.UTC) + wd := NewWatchdog(WatchdogConfig{BootLoopThreshold: 3, BootLoopWindow: 5 * time.Minute}, t0) + + // Observe 1 cold reboot before intentional Stage 4 restart. + wd.Check(t0.Add(20*time.Second), pluginsdk.VMTelemetry{ColdRebootCount: 1}, StageInstallWait, false) + // Intentional Stage 4 restart happens -> ResetRebootWindow called. + wd.ResetRebootWindow(t0.Add(40 * time.Second)) + // First post-restart Check observes ColdRebootCount=2 (the intentional restart) — must NOT count. + if reason, _, tripped := wd.Check(t0.Add(60*time.Second), pluginsdk.VMTelemetry{ColdRebootCount: 2}, StageSetupAssistant, false); tripped { + t.Fatalf("intentional restart tripped watchdog: %s", reason) + } + // Two subsequent reboots must still stay below threshold 3. + if reason, _, tripped := wd.Check(t0.Add(80*time.Second), pluginsdk.VMTelemetry{ColdRebootCount: 3}, StageSetupAssistant, false); tripped { + t.Fatalf("1st post-reset reboot tripped watchdog: %s", reason) + } + if reason, _, tripped := wd.Check(t0.Add(100*time.Second), pluginsdk.VMTelemetry{ColdRebootCount: 4}, StageSetupAssistant, false); tripped { + t.Fatalf("2nd post-reset reboot tripped watchdog (intentional restart was wrongly counted): %s", reason) + } + // 3rd genuine post-reset reboot trips boot_loop_detected. + if reason, _, tripped := wd.Check(t0.Add(120*time.Second), pluginsdk.VMTelemetry{ColdRebootCount: 5}, StageSetupAssistant, false); !tripped || reason != "boot_loop_detected" { + t.Fatalf("expected boot_loop_detected on 3rd genuine post-reset reboot, got tripped=%v reason=%q", tripped, reason) + } +} + +func TestRedactDiagnosticTextRespectsWordBoundaryForShortNames(t *testing.T) { + cfg := RunConfig{FullName: "Li", AccountName: "us"} + in := "Click Login using files. Welcome Li! User: us." + got := RedactDiagnosticText(in, cfg) + if !strings.Contains(got, "Click Login using files.") { + t.Fatalf("short names mangled common diagnostic words: %q", got) + } + if strings.Contains(got, "Welcome Li") || strings.Contains(got, "User: us") { + t.Fatalf("standalone short names were not redacted: %q", got) + } + if !strings.Contains(got, "Welcome !") || !strings.Contains(got, "User: .") { + t.Fatalf("expected standalone short names replaced with , got %q", got) + } + + // Short CJK names (no spaces between characters) must still be redacted inside adjacent CJK text. + cjkGot := RedactDiagnosticText("欢迎李明使用李明的Mac", RunConfig{FullName: "李明"}) + if strings.Contains(cjkGot, "李明") { + t.Fatalf("short CJK name leaked inside adjacent CJK text: %q", cjkGot) + } + if cjkGot != "欢迎使用的Mac" { + t.Fatalf("unexpected CJK redaction result: %q", cjkGot) + } +} + +func TestTerminalPromptRecognizesSh32AndBoundsUnreadyForegroundLoop(t *testing.T) { + for _, prompt := range []string{"-sh-3.2# ", "sh-3.2# ", "-zsh", "root#"} { + if !terminalLooksReady(prompt) { + t.Fatalf("terminalLooksReady(%q) = false, want true", prompt) + } + } + eng, err := rules.LoadEngine(t.TempDir()) + if err != nil { + t.Fatal(err) + } + mh := &mockHost{ + screens: []mockScreen{{ + rois: map[string]vision.ROIScan{ + "menu_bar": scanText("Terminal Shell Edit", image.Rect(40, 4, 260, 28)), + "terminal": scanText("", image.Rect(100, 100, 400, 140)), + }, + }}, + } + cfg := RunConfig{ + VM: "builtin.driver.reims-macos:term-fg-bound", Mode: ModeRecoveryOnly, + GuestLang: "zh-Hans:0", SLAAccepted: true, + } + r, err := New(mh, &mockLocator{host: mh}, eng, t.TempDir(), cfg, Options{DisableSleep: true}) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + go func() { + for i := 0; i < 100; i++ { + if r.Status().Status == StatusPausedForUser { + cancel() + return + } + time.Sleep(5 * time.Millisecond) + } + cancel() + }() + _ = r.stepOfflineTerminal(ctx, NewWatchdog(WatchdogConfig{}, time.Now())) + if st := r.Status(); st.Status != StatusPausedForUser || st.PauseReason != "terminal_not_ready" { + t.Fatalf("expected foreground Terminal without prompt to pause with terminal_not_ready, got %+v", st) + } +} + +func TestWaitAfterRuleActionHonorsWaitChangeMSAndStopsOnVisualDiff(t *testing.T) { + eng, err := rules.LoadEngine(t.TempDir()) + if err != nil { + t.Fatal(err) + } + cfg := RunConfig{ + VM: "builtin.driver.reims-macos:wait-change", Mode: ModeRecoveryOnly, + GuestLang: "zh-Hans:0", SLAAccepted: true, + } + black := image.NewRGBA(image.Rect(0, 0, 160, 90)) + white := image.NewRGBA(image.Rect(0, 0, 160, 90)) + for i := 0; i < len(white.Pix); i += 4 { + white.Pix[i], white.Pix[i+1], white.Pix[i+2], white.Pix[i+3] = 255, 255, 255, 255 + } + mh := &mockHost{ + screenshotImgs: []image.Image{black, white}, + } + r, err := New(mh, &mockLocator{host: mh}, eng, t.TempDir(), cfg, Options{ + PostActionWait: 10 * time.Millisecond, + PollInterval: 10 * time.Millisecond, + DisableSleep: false, + }) + if err != nil { + t.Fatal(err) + } + start := time.Now() + rule := rules.Rule{ + ID: "setup.create_account", + Verify: rules.Verify{WaitChangeMS: 5000}, + } + if err := r.waitAfterRuleAction(context.Background(), black, rule); err != nil { + t.Fatalf("waitAfterRuleAction: %v", err) + } + if elapsed := time.Since(start); elapsed > 2*time.Second { + t.Fatalf("waitAfterRuleAction did not exit early on visual change (elapsed=%v)", elapsed) + } + if mh.screenshotCalls < 2 { + t.Fatalf("expected waitAfterRuleAction to poll until visual change, got %d captures", mh.screenshotCalls) + } +} diff --git a/internal/macos/autoinstall/runner/watchdog.go b/internal/macos/autoinstall/runner/watchdog.go new file mode 100644 index 0000000..0443e57 --- /dev/null +++ b/internal/macos/autoinstall/runner/watchdog.go @@ -0,0 +1,200 @@ +package runner + +import ( + "fmt" + "strings" + "time" + + "github.com/Nwflower/reims-go/pkg/pluginsdk" +) + +// WatchdogConfig controls anomaly early-stop thresholds. +type WatchdogConfig struct { + BootLoopWindow time.Duration // default 5m + BootLoopThreshold int // default 3 XNU->guest-reset cycles + Stage3StallTimeout time.Duration // default 15m zero disk growth + frozen screen + TotalInstallTimeout time.Duration // default 90m +} + +func defaultWatchdogConfig() WatchdogConfig { + return WatchdogConfig{ + BootLoopWindow: 5 * time.Minute, + BootLoopThreshold: 3, + Stage3StallTimeout: 15 * time.Minute, + TotalInstallTimeout: 90 * time.Minute, + } +} + +const ( + // rebootEventDebounce prevents one guest reboot from being counted twice when + // both ColdRebootCount and serial:xnu advance within seconds of each other. + rebootEventDebounce = 15 * time.Second + // healthyInstallDiskGrowthBytes is the disk write threshold in Stage 3 that + // proves macOS installation made real payload progress (not a crash loop). + healthyInstallDiskGrowthBytes = 32 * 1024 * 1024 +) + +// Watchdog observes telemetry and frame deltas to catch boot loops, +// fatal QEMU device errors, stalled installs, and total timeouts. +type Watchdog struct { + cfg WatchdogConfig + startedAt time.Time + lastActivityAt time.Time + hasDiskBase bool + lastDiskBytes int64 + diskBytesAtReboots int64 + lastXNUCount int + lastColdReboot int + rebaselinePending bool + lastRebootEventAt time.Time + rebootEvents []time.Time + lastTrippedQemuErr string + ackedQemuErrors map[string]bool +} + +func NewWatchdog(cfg WatchdogConfig, now time.Time) *Watchdog { + if cfg.BootLoopWindow <= 0 { + cfg.BootLoopWindow = 5 * time.Minute + } + if cfg.BootLoopThreshold <= 0 { + cfg.BootLoopThreshold = 3 + } + if cfg.Stage3StallTimeout <= 0 { + cfg.Stage3StallTimeout = 15 * time.Minute + } + if cfg.TotalInstallTimeout <= 0 { + cfg.TotalInstallTimeout = 90 * time.Minute + } + return &Watchdog{ + cfg: cfg, + startedAt: now, + lastActivityAt: now, + } +} + +// ResetRebootWindow clears accumulated reboot-loop history (for example right +// before/after an intentional Stage 4 FinishInstall restart) while preserving +// previously acknowledged QEMU error lines so Stage 5/6 does not re-trip on +// the same historical log entries. +func (w *Watchdog) ResetRebootWindow(now time.Time) { + w.rebootEvents = nil + w.lastRebootEventAt = time.Time{} + w.lastXNUCount = 0 + w.rebaselinePending = true + w.lastActivityAt = now + w.lastTrippedQemuErr = "" +} + +// ResetAfterResume clears tripped boot-loop/stall/error history after the user +// clicks Resume so resuming does not immediately re-trip on stale counters or +// already-acknowledged QEMU log lines. +func (w *Watchdog) ResetAfterResume(now time.Time) { + w.rebootEvents = nil + w.lastRebootEventAt = time.Time{} + w.rebaselinePending = true + w.lastActivityAt = now + if w.lastTrippedQemuErr != "" { + if w.ackedQemuErrors == nil { + w.ackedQemuErrors = map[string]bool{} + } + w.ackedQemuErrors[w.lastTrippedQemuErr] = true + w.lastTrippedQemuErr = "" + } + if now.Sub(w.startedAt) >= w.cfg.TotalInstallTimeout { + w.startedAt = now + } +} + +// Check evaluates the latest redacted telemetry and visual activity flag. +// Returns (reason, detail, tripped). +func (w *Watchdog) Check(now time.Time, tel pluginsdk.VMTelemetry, stage string, visualChanged bool) (string, string, bool) { + if now.Sub(w.startedAt) > w.cfg.TotalInstallTimeout { + return "install_timeout", fmt.Sprintf("auto-install exceeded %v total budget", w.cfg.TotalInstallTimeout), true + } + + // Fatal QEMU errors abort immediately unless already acknowledged by Resume. + for _, line := range tel.QemuErrors { + if w.ackedQemuErrors != nil && w.ackedQemuErrors[line] { + continue + } + low := strings.ToLower(line) + if strings.Contains(low, "fatal:") || strings.Contains(low, "failed to ") || strings.Contains(low, "the device was reset") { + w.lastTrippedQemuErr = line + return "qemu_fatal_error", line, true + } + } + + // Track Stage 3 disk growth and activity before evaluating boot-loop state. + diskGrew := tel.DiskDeltaBytes > 64*1024 + significantDiskGrowth := tel.DiskDeltaBytes >= healthyInstallDiskGrowthBytes + if !w.hasDiskBase { + w.hasDiskBase = true + w.lastDiskBytes = tel.DiskBytes + w.diskBytesAtReboots = tel.DiskBytes + } else if tel.DiskBytes > w.lastDiskBytes+64*1024 { + diskGrew = true + w.lastDiskBytes = tel.DiskBytes + } + if tel.DiskBytes > w.diskBytesAtReboots+healthyInstallDiskGrowthBytes { + significantDiskGrowth = true + } + if stage == StageInstallWait && significantDiskGrowth { + // macOS startosinstall legitimately reboots 2–4 times while writing GBs + // of OS payload; substantial disk growth proves healthy progress rather + // than a kernel-panic boot loop. + w.rebootEvents = nil + w.diskBytesAtReboots = max(w.diskBytesAtReboots, tel.DiskBytes) + } + if diskGrew || tel.CPUPercent >= 3.0 || visualChanged { + w.lastActivityAt = now + } + + // Count XNU handoff / cold-reboot cycles inside the sliding boot-loop window, + // deduplicating cold-reboot + serial:xnu signals belonging to the same reboot. + xnuCount := 0 + for _, m := range tel.BootMilestones { + if m.Key == "serial:xnu" { + xnuCount = m.Count + } + } + rebootObserved := false + if w.rebaselinePending { + w.rebaselinePending = false + w.lastXNUCount = xnuCount + w.lastColdReboot = tel.ColdRebootCount + } else { + if xnuCount > w.lastXNUCount && w.lastXNUCount > 0 { + rebootObserved = true + } + if tel.ColdRebootCount > w.lastColdReboot { + rebootObserved = true + } + w.lastXNUCount = xnuCount + w.lastColdReboot = tel.ColdRebootCount + } + + if rebootObserved && (w.lastRebootEventAt.IsZero() || now.Sub(w.lastRebootEventAt) >= rebootEventDebounce) { + w.rebootEvents = append(w.rebootEvents, now) + w.lastRebootEventAt = now + if tel.DiskBytes > w.diskBytesAtReboots { + w.diskBytesAtReboots = tel.DiskBytes + } + } + + cutoff := now.Add(-w.cfg.BootLoopWindow) + kept := w.rebootEvents[:0] + for _, ts := range w.rebootEvents { + if !ts.Before(cutoff) { + kept = append(kept, ts) + } + } + w.rebootEvents = kept + if len(w.rebootEvents) >= w.cfg.BootLoopThreshold { + return "boot_loop_detected", fmt.Sprintf("detected %d boot/reset cycles within %v", len(w.rebootEvents), w.cfg.BootLoopWindow), true + } + + if stage == StageInstallWait && now.Sub(w.lastActivityAt) > w.cfg.Stage3StallTimeout { + return "stage3_stalled", fmt.Sprintf("no disk growth or visual progress for %v", w.cfg.Stage3StallTimeout), true + } + return "", "", false +} diff --git a/internal/macos/autoinstall/service.go b/internal/macos/autoinstall/service.go new file mode 100644 index 0000000..d2d5c4a --- /dev/null +++ b/internal/macos/autoinstall/service.go @@ -0,0 +1,611 @@ +// Package autoinstall implements the official built-in local-vision macOS +// unattended installation engine for Reims-Go. It exposes the same JSON-RPC +// method contract as external auto-installer Sidecars so host UI, CLI, +// sessions, and DPAPI secret injection remain completely pluggable. +package autoinstall + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "path/filepath" + "strings" + "sync" + + "github.com/Nwflower/reims-go/internal/macos/autoinstall/hostclient" + "github.com/Nwflower/reims-go/internal/macos/autoinstall/ocr" + "github.com/Nwflower/reims-go/internal/macos/autoinstall/rules" + "github.com/Nwflower/reims-go/internal/macos/autoinstall/runner" + "github.com/Nwflower/reims-go/internal/macos/autoinstall/vision" + "github.com/Nwflower/reims-go/pkg/pluginsdk" +) + +// ServiceOptions configures the in-process macOS auto-install service. +type ServiceOptions struct { + DataDir string + CallHost hostclient.CallHostFunc + GetSetting func(vmName, key string) (any, bool) + OpenOCR func(guestLang, dataDir, preferredBackend string) (ocr.Engine, ocr.ProbeReport, error) + ProbeOCR func(guestLang, dataDir, preferredBackend string) ocr.ProbeReport + RunnerOptions runner.Options +} + +// Service implements plugin.InProcessEndpoint for the built-in macOS +// auto-install plugin, coordinating per-VM runners, checkpoints, and OCR assets. +type Service struct { + opts ServiceOptions + host *hostclient.InProcessClient + + mu sync.Mutex + runners map[string]*runner.Runner + vmStartMu map[string]*sync.Mutex + vmStopGen map[string]uint64 + wg sync.WaitGroup + closed bool +} + +// NewService constructs a ready-to-register in-process auto-install Service. +func NewService(opts ServiceOptions) *Service { + if opts.OpenOCR == nil { + opts.OpenOCR = ocr.Open + } + if opts.ProbeOCR == nil { + opts.ProbeOCR = runner.ProbeOCR + } + return &Service{ + opts: opts, + host: hostclient.NewInProcessClient(opts.CallHost), + runners: make(map[string]*runner.Runner), + vmStartMu: make(map[string]*sync.Mutex), + vmStopGen: make(map[string]uint64), + } +} + +func (s *Service) lockVMStart(vm string) *sync.Mutex { + s.mu.Lock() + if s.vmStartMu == nil { + s.vmStartMu = make(map[string]*sync.Mutex) + } + m := s.vmStartMu[vm] + if m == nil { + m = &sync.Mutex{} + s.vmStartMu[vm] = m + } + s.mu.Unlock() + m.Lock() + return m +} + +func (s *Service) dataDir() string { + return strings.TrimSpace(s.opts.DataDir) +} + +func (s *Service) stringSetting(vmName, key string) string { + if s.opts.GetSetting == nil { + return "" + } + raw, ok := s.opts.GetSetting(vmName, key) + if !ok || raw == nil { + return "" + } + if str, ok := raw.(string); ok { + return strings.TrimSpace(str) + } + return "" +} + +func (s *Service) effectiveOCRBackend(explicit string) string { + if v := strings.TrimSpace(explicit); v != "" { + return v + } + return s.stringSetting("", "ocr_backend") +} + +func (s *Service) effectiveCustomMirror(explicit string) string { + if v := strings.TrimSpace(explicit); v != "" { + return v + } + return s.stringSetting("", "custom_ocr_mirror") +} + +func marshalParams(params any) (json.RawMessage, error) { + switch v := params.(type) { + case nil: + return json.RawMessage("{}"), nil + case json.RawMessage: + if len(v) == 0 { + return json.RawMessage("{}"), nil + } + return v, nil + default: + b, err := json.Marshal(v) + if err != nil { + return nil, err + } + return json.RawMessage(b), nil + } +} + +// Call dispatches a host-to-plugin `autoinstall/*` request using the same +// JSON contract as external L3 Sidecar auto-installers. +func (s *Service) Call(ctx context.Context, method string, params any, out any) error { + if ctx == nil { + ctx = context.Background() + } + raw, err := marshalParams(params) + if err != nil { + return fmt.Errorf("marshal params for %s: %w", method, err) + } + + var res any + switch method { + case "autoinstall/preflight": + res, err = s.handlePreflight(ctx, raw) + case "autoinstall/start": + res, err = s.handleStart(ctx, raw) + case "autoinstall/status": + res, err = s.handleStatus(ctx, raw) + case "autoinstall/resume": + res, err = s.handleResume(ctx, raw) + case "autoinstall/stop": + res, err = s.handleStop(ctx, raw) + case "autoinstall/diagnosticSummary": + res, err = s.handleDiagnosticSummary(ctx, raw) + case "autoinstall/downloadOCR": + res, err = s.handleDownloadOCR(ctx, raw) + case "autoinstall/importOCR": + res, err = s.handleImportOCR(ctx, raw) + default: + return fmt.Errorf("unknown autoinstall method %q", method) + } + if err != nil { + return err + } + if out != nil { + b, err := json.Marshal(res) + if err != nil { + return fmt.Errorf("marshal response for %s: %w", method, err) + } + if err := json.Unmarshal(b, out); err != nil { + return fmt.Errorf("decode response for %s: %w", method, err) + } + } + return nil +} + +// Notify handles fire-and-forget host notifications (`download/progress`, +// `console/userTakeover`, `session/stopped`, `session/paused`, `session/resumed`). +func (s *Service) Notify(method string, params any) { + raw, err := marshalParams(params) + if err != nil { + return + } + switch method { + case "download/progress": + var ev pluginsdk.DownloadEvent + if json.Unmarshal(raw, &ev) == nil { + s.host.HandleDownloadProgress(ev) + } + case "console/userTakeover": + var ev struct { + VM string `json:"vm"` + Reason string `json:"reason"` + } + if json.Unmarshal(raw, &ev) == nil { + vm := strings.TrimSpace(ev.VM) + if vm == "" { + return + } + s.mu.Lock() + r := s.runners[vm] + s.mu.Unlock() + if r != nil { + r.NotifyTakeover(ev.Reason) + } + } + case "session/stopped": + var ev struct { + VM string `json:"vm"` + Reason string `json:"reason"` + Message string `json:"message"` + } + if json.Unmarshal(raw, &ev) == nil { + vm := strings.TrimSpace(ev.VM) + if vm == "" { + return + } + s.mu.Lock() + s.vmStopGen[vm]++ + r := s.runners[vm] + delete(s.runners, vm) + s.mu.Unlock() + if ev.Reason == "confirmation_denied" || ev.Reason == "permission_denied" { + msg := strings.TrimSpace(ev.Message) + if msg == "" { + msg = "Plugin permission denied; switched back to manual installation guide" + } + if r != nil { + r.StopWithOutcome(runner.StatusFailed, ev.Reason, msg) + } else { + _ = runner.MarkCheckpointOutcome(s.dataDir(), vm, runner.StatusFailed, ev.Reason, msg) + } + } else { + if r != nil { + r.Stop() + } else { + _ = runner.MarkCheckpointStopped(s.dataDir(), vm, "Stopped by user") + } + } + } + case "session/paused": + var ev struct { + VM string `json:"vm"` + Reason string `json:"reason"` + } + if json.Unmarshal(raw, &ev) == nil { + vm := strings.TrimSpace(ev.VM) + if vm == "" { + return + } + s.mu.Lock() + r := s.runners[vm] + s.mu.Unlock() + if r != nil { + r.PauseByUser(ev.Reason) + } + } + case "session/resumed": + var ev struct { + VM string `json:"vm"` + } + if json.Unmarshal(raw, &ev) == nil { + vm := strings.TrimSpace(ev.VM) + if vm == "" { + return + } + s.mu.Lock() + r := s.runners[vm] + s.mu.Unlock() + if r != nil { + r.Resume() + } + } + } +} + +func (s *Service) handlePreflight(_ context.Context, raw json.RawMessage) (any, error) { + var req struct { + VM string `json:"vm"` + GuestLang string `json:"guest_lang"` + OCRBackend string `json:"ocr_backend"` + } + if len(raw) > 0 { + if err := json.Unmarshal(raw, &req); err != nil { + return nil, err + } + } + if strings.TrimSpace(req.GuestLang) == "" { + req.GuestLang = "zh-Hans:0" + } + vm := strings.TrimSpace(req.VM) + backend := s.effectiveOCRBackend(req.OCRBackend) + probe := s.opts.ProbeOCR(req.GuestLang, s.dataDir(), backend) + cp, hasCheckpoint := runner.LoadCheckpoint(s.dataDir(), vm) + resumable := hasCheckpoint && (cp.Status == runner.StatusPausedForUser || cp.Status == runner.StatusRunning) + return map[string]any{ + "ready": probe.ActiveBackend != "missing" && !probe.NeedsRapidOCRDownload && !probe.NeedsRapidOCRImport, + "ocr": probe, + "can_download_ocr": ocr.HasPinnedDefaultRapidOCRAssets(), + "has_resume_checkpoint": resumable, + "filevault_forced_off": true, + "requires_ascii_inputs": true, + }, nil +} + +func (s *Service) handleStart(_ context.Context, raw json.RawMessage) (any, error) { + var cfg runner.RunConfig + if err := json.Unmarshal(raw, &cfg); err != nil { + return nil, err + } + cfg.OCRBackend = s.effectiveOCRBackend(cfg.OCRBackend) + cfg.CustomOCRMirror = s.effectiveCustomMirror(cfg.CustomOCRMirror) + if err := runner.ValidateConfig(&cfg); err != nil { + return nil, err + } + + // Serialize starts per VM so concurrent autoinstall/start calls cannot race + // to kill each other's newly returned runner or interleave EndSession/BeginSession. + vmMu := s.lockVMStart(cfg.VM) + defer vmMu.Unlock() + + // Stop and await any previous runner for the same VM BEFORE opening the new + // one so its deferred EndSession cannot race with the replacement session. + s.mu.Lock() + if s.closed { + s.mu.Unlock() + return nil, errors.New("autoinstall service is stopped") + } + startGen := s.vmStopGen[cfg.VM] + prev := s.runners[cfg.VM] + delete(s.runners, cfg.VM) + s.mu.Unlock() + if prev != nil { + prev.Stop() + prev.Wait() + } + + eng, probe, err := s.opts.OpenOCR(cfg.GuestLang, s.dataDir(), cfg.OCRBackend) + if err != nil { + return nil, fmt.Errorf("ocr_unavailable: %w (probe=%+v)", err, probe) + } + ruleEng, err := rules.LoadEngine(s.dataDir()) + if err != nil { + _ = eng.Close() + return nil, err + } + loc := vision.NewLocalLocator(eng) + r, err := runner.New(s.host, loc, ruleEng, s.dataDir(), cfg, s.opts.RunnerOptions) + if err != nil { + _ = eng.Close() + return nil, err + } + + s.mu.Lock() + if s.closed { + s.mu.Unlock() + _ = eng.Close() + return nil, errors.New("autoinstall service is stopped") + } + if s.vmStopGen[cfg.VM] != startGen { + s.mu.Unlock() + _ = eng.Close() + return nil, errors.New("autoinstall start canceled by concurrent stop") + } + s.wg.Add(1) + r.SetOnDone(func() { + _ = eng.Close() + s.wg.Done() + }) + s.runners[cfg.VM] = r + r.Start(context.Background()) + s.mu.Unlock() + return r.Status(), nil +} + +func (s *Service) handleStatus(_ context.Context, raw json.RawMessage) (any, error) { + var req struct { + VM string `json:"vm"` + } + if len(raw) > 0 { + _ = json.Unmarshal(raw, &req) + } + if vm := strings.TrimSpace(req.VM); vm != "" { + s.mu.Lock() + r := s.runners[vm] + s.mu.Unlock() + if r != nil { + return r.Status(), nil + } + if cp, ok := runner.LoadCheckpoint(s.dataDir(), vm); ok { + st := cp.Status + msg := cp.Message + // No live runner exists in memory after an app restart or plugin toggle: + // never report a stale on-disk "running" checkpoint as active. + if st == runner.StatusRunning { + st = runner.StatusStopped + msg = "上次自动安装已中断,可点击开始自动安装继续" + } + return runner.RunStatusView{ + VM: cp.VM, + Stage: cp.Stage, + Status: st, + Message: msg, + PauseReason: cp.PauseReason, + UnknownPageSummary: cp.UnknownPageSummary, + MatchedRules: cp.MatchedRules, + FinishInstallDone: cp.FinishInstallDone, + SaveUnlockCredential: cp.Config.SaveUnlockCredential, + StartedAt: cp.StartedAt.Format("2006-01-02T15:04:05Z07:00"), + UpdatedAt: cp.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"), + }, nil + } + return runner.RunStatusView{VM: vm, Status: runner.StatusIdle}, nil + } + s.mu.Lock() + live := make(map[string]runner.RunStatusView, len(s.runners)) + for vm, r := range s.runners { + if r != nil { + live[vm] = r.Status() + } + } + s.mu.Unlock() + out := make([]runner.RunStatusView, 0, len(live)) + for _, st := range live { + out = append(out, st) + } + for _, cp := range runner.ListCheckpoints(s.dataDir()) { + if _, exists := live[cp.VM]; exists { + continue + } + st := cp.Status + msg := cp.Message + if st == runner.StatusRunning { + st = runner.StatusStopped + msg = "上次自动安装已中断,可点击开始自动安装继续" + } + out = append(out, runner.RunStatusView{ + VM: cp.VM, + Stage: cp.Stage, + Status: st, + Message: msg, + PauseReason: cp.PauseReason, + UnknownPageSummary: cp.UnknownPageSummary, + MatchedRules: cp.MatchedRules, + FinishInstallDone: cp.FinishInstallDone, + SaveUnlockCredential: cp.Config.SaveUnlockCredential, + StartedAt: cp.StartedAt.Format("2006-01-02T15:04:05Z07:00"), + UpdatedAt: cp.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"), + }) + } + return map[string]any{"runs": out}, nil +} + +func (s *Service) handleResume(_ context.Context, raw json.RawMessage) (any, error) { + var req struct { + VM string `json:"vm"` + } + if err := json.Unmarshal(raw, &req); err != nil { + return nil, err + } + vm := strings.TrimSpace(req.VM) + if vm == "" { + return nil, errors.New("vm reference is required") + } + s.mu.Lock() + r := s.runners[vm] + s.mu.Unlock() + if r != nil { + cur := r.Status() + if cur.Status == runner.StatusPausedForUser || cur.Status == runner.StatusRunning { + r.Resume() + return r.Status(), nil + } + return nil, errors.New("no paused auto-install session found for VM") + } + // If the app restarted or plugin was re-enabled after saving an active/paused checkpoint, restart from it. + if cp, ok := runner.LoadCheckpoint(s.dataDir(), vm); ok && (cp.Status == runner.StatusPausedForUser || cp.Status == runner.StatusRunning) { + b, _ := json.Marshal(cp.Config) + return s.handleStart(context.Background(), b) + } + return nil, errors.New("no paused auto-install session found for VM") +} + +func (s *Service) handleStop(_ context.Context, raw json.RawMessage) (any, error) { + var req struct { + VM string `json:"vm"` + } + if err := json.Unmarshal(raw, &req); err != nil { + return nil, err + } + vm := strings.TrimSpace(req.VM) + s.mu.Lock() + s.vmStopGen[vm]++ + r := s.runners[vm] + delete(s.runners, vm) + s.mu.Unlock() + if r != nil { + r.Stop() + r.Wait() + } + _ = runner.MarkCheckpointStopped(s.dataDir(), vm, "Stopped by user") + return map[string]any{"ok": true}, nil +} + +// StopAll cancels and waits for every running auto-install worker so disabling +// the built-in plugin leaves zero goroutines, sessions, or open OCR handles. +func (s *Service) StopAll() { + s.mu.Lock() + s.closed = true + list := make([]*runner.Runner, 0, len(s.runners)) + for vm, r := range s.runners { + delete(s.runners, vm) + if r != nil { + list = append(list, r) + } + } + s.mu.Unlock() + for _, r := range list { + r.Stop() + } + for _, r := range list { + r.Wait() + } + s.wg.Wait() +} + +func (s *Service) handleDiagnosticSummary(_ context.Context, raw json.RawMessage) (any, error) { + var req struct { + VM string `json:"vm"` + } + if err := json.Unmarshal(raw, &req); err != nil { + return nil, err + } + stAny, err := s.handleStatus(context.Background(), raw) + if err != nil { + return nil, err + } + st, _ := stAny.(runner.RunStatusView) + return map[string]any{ + "vm": st.VM, + "stage": st.Stage, + "status": st.Status, + "pause_reason": st.PauseReason, + "unknown_page_summary": st.UnknownPageSummary, + "matched_rules": st.MatchedRules, + }, nil +} + +func (s *Service) handleDownloadOCR(ctx context.Context, raw json.RawMessage) (any, error) { + var req struct { + CustomMirror string `json:"custom_mirror"` + Assets []ocr.AssetSpec `json:"assets"` + } + if len(raw) > 0 { + if err := json.Unmarshal(raw, &req); err != nil { + return nil, err + } + } + assets := req.Assets + if len(assets) == 0 { + assets = ocr.DefaultRapidOCRAssets() + } + // Validate asset specs BEFORE showing a host confirmation dialog so users + // are never prompted only to fail immediately on missing pinned digests. + for _, spec := range assets { + if strings.TrimSpace(spec.Name) == "" { + return nil, errors.New("asset name is required") + } + if strings.TrimSpace(spec.SHA256) == "" { + return nil, fmt.Errorf("asset %s requires a pinned SHA-256 digest before downloading (or import an offline .zip bundle)", spec.Name) + } + } + customMirror := s.effectiveCustomMirror(req.CustomMirror) + confirmRes, err := s.host.Confirm(ctx, pluginsdk.ConfirmRequest{ + Title: "Download RapidOCR ONNX Fallback", + Message: "Windows OCR language pack is missing for the guest language. Download Apache-2.0 RapidOCR ONNX models (~25 MB) into plugin private storage?", + ConfirmLabel: "Download", + CancelLabel: "Cancel", + }) + if err != nil { + return nil, err + } + if !confirmRes.Approved { + return nil, errors.New("confirmation_denied: user declined RapidOCR download") + } + destDir := filepath.Join(s.dataDir(), "ocr") + var downloaded []string + for _, spec := range assets { + p, err := ocr.FetchAssetWithFallback(ctx, s.host, destDir, spec, customMirror) + if err != nil { + return nil, err + } + downloaded = append(downloaded, filepath.Base(p)) + } + return map[string]any{"ok": true, "files": downloaded, "installed": ocr.IsRapidOCRInstalled(s.dataDir())}, nil +} + +func (s *Service) handleImportOCR(_ context.Context, raw json.RawMessage) (any, error) { + var req struct { + ZipPath string `json:"zip_path"` + SHA256 string `json:"sha256"` + } + if err := json.Unmarshal(raw, &req); err != nil { + return nil, err + } + dir, err := ocr.ImportOfflineBundle(req.ZipPath, s.dataDir(), req.SHA256) + if err != nil { + return nil, err + } + return map[string]any{"ok": true, "ocr_dir": dir, "installed": ocr.IsRapidOCRInstalled(s.dataDir())}, nil +} diff --git a/internal/macos/autoinstall/service_test.go b/internal/macos/autoinstall/service_test.go new file mode 100644 index 0000000..8515d31 --- /dev/null +++ b/internal/macos/autoinstall/service_test.go @@ -0,0 +1,461 @@ +package autoinstall + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "image" + "image/png" + "os" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Nwflower/reims-go/internal/macos/autoinstall/ocr" + "github.com/Nwflower/reims-go/internal/macos/autoinstall/runner" + "github.com/Nwflower/reims-go/pkg/pluginsdk" +) + +type stubOCREngine struct { + closed atomic.Bool +} + +func (e *stubOCREngine) Name() string { return "stub" } +func (e *stubOCREngine) MaxDimension() int { return 2600 } +func (e *stubOCREngine) Recognize(_ context.Context, _ image.Image) (ocr.Result, error) { + return ocr.Result{Backend: "stub"}, nil +} +func (e *stubOCREngine) Close() error { + e.closed.Store(true) + return nil +} + +func blankPNGBase64() string { + var buf bytes.Buffer + _ = png.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 16, 16))) + return base64.StdEncoding.EncodeToString(buf.Bytes()) +} + +func TestServicePreflightUsesSavedOCRSetting(t *testing.T) { + var seenBackend string + svc := NewService(ServiceOptions{ + DataDir: t.TempDir(), + GetSetting: func(_, key string) (any, bool) { + if key == "ocr_backend" { + return "rapidocr", true + } + return nil, false + }, + ProbeOCR: func(guestLang, _ string, preferredBackend string) ocr.ProbeReport { + seenBackend = preferredBackend + return ocr.ProbeReport{ + GuestLang: guestLang, + RequiredLanguage: "zh-hans", + RapidOCRInstalled: true, + ActiveBackend: "rapidocr", + } + }, + }) + + var resp map[string]any + if err := svc.Call(context.Background(), "autoinstall/preflight", map[string]any{ + "vm": "builtin.driver.reims-macos::demo", + "guest_lang": "zh-Hans:0", + }, &resp); err != nil { + t.Fatalf("preflight call failed: %v", err) + } + if seenBackend != "rapidocr" { + t.Fatalf("expected saved ocr_backend=rapidocr, got %q", seenBackend) + } + if ready, _ := resp["ready"].(bool); !ready { + t.Fatalf("expected ready=true, got %+v", resp) + } +} + +func TestServiceStartPauseResumeStopAndStopAll(t *testing.T) { + blankB64 := blankPNGBase64() + var ( + mu sync.Mutex + sessions = map[string]int{} + ended = map[string]int{} + ) + eng := &stubOCREngine{} + + svc := NewService(ServiceOptions{ + DataDir: t.TempDir(), + CallHost: func(_ context.Context, method string, params any, out any) error { + switch method { + case "host/session.begin": + var req pluginsdk.SessionBeginRequest + b, _ := json.Marshal(params) + _ = json.Unmarshal(b, &req) + mu.Lock() + sessions[req.VM]++ + mu.Unlock() + return nil + case "host/session.end": + var req struct { + VM string `json:"vm"` + } + b, _ := json.Marshal(params) + _ = json.Unmarshal(b, &req) + mu.Lock() + ended[req.VM]++ + mu.Unlock() + return nil + case "host/session.update", "host/notify": + return nil + case "host/vm.telemetry": + if out != nil { + b, _ := json.Marshal(pluginsdk.VMTelemetry{State: "running", Phase: "installer"}) + return json.Unmarshal(b, out) + } + return nil + case "host/console.screenshot": + if out != nil { + b, _ := json.Marshal(pluginsdk.ScreenshotResult{ + Width: 16, Height: 16, SourceWidth: 16, SourceHeight: 16, Blank: true, Data: blankB64, + }) + return json.Unmarshal(b, out) + } + return nil + default: + return nil + } + }, + OpenOCR: func(_, _, _ string) (ocr.Engine, ocr.ProbeReport, error) { + return eng, ocr.ProbeReport{ActiveBackend: "stub"}, nil + }, + RunnerOptions: runner.Options{ + PollInterval: 15 * time.Millisecond, + Stage3Interval: 15 * time.Millisecond, + PostActionWait: 15 * time.Millisecond, + }, + }) + + const vmKey = "builtin.driver.reims-macos::svc-test" + var st runner.RunStatusView + if err := svc.Call(context.Background(), "autoinstall/start", runner.RunConfig{ + VM: vmKey, + Mode: runner.ModeRecoveryOnly, + GuestLang: "zh-Hans:0", + SLAAccepted: true, + }, &st); err != nil { + t.Fatalf("autoinstall/start failed: %v", err) + } + if st.Status != runner.StatusRunning { + t.Fatalf("expected running status, got %+v", st) + } + + // Pause via host notification, verify status, then resume. + svc.Notify("session/paused", map[string]any{"vm": vmKey, "reason": "user_paused"}) + if err := svc.Call(context.Background(), "autoinstall/status", map[string]any{"vm": vmKey}, &st); err != nil { + t.Fatalf("status after pause: %v", err) + } + if st.Status != runner.StatusPausedForUser { + t.Fatalf("expected paused_for_user, got %+v", st) + } + + svc.Notify("session/resumed", map[string]any{"vm": vmKey}) + if err := svc.Call(context.Background(), "autoinstall/status", map[string]any{"vm": vmKey}, &st); err != nil { + t.Fatalf("status after resume: %v", err) + } + if st.Status != runner.StatusRunning { + t.Fatalf("expected running after resume, got %+v", st) + } + + // Diagnostic summary works while running. + var diag map[string]any + if err := svc.Call(context.Background(), "autoinstall/diagnosticSummary", map[string]any{"vm": vmKey}, &diag); err != nil { + t.Fatalf("diagnosticSummary: %v", err) + } + if diag["vm"] != vmKey { + t.Fatalf("unexpected diagnostic summary: %+v", diag) + } + + // StopAll cleanly stops active runners, ends sessions, and closes OCR engine. + svc.StopAll() + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) && !eng.closed.Load() { + time.Sleep(5 * time.Millisecond) + } + if !eng.closed.Load() { + t.Fatal("expected OCR engine to be closed after StopAll") + } + mu.Lock() + beganCount := sessions[vmKey] + endedCount := ended[vmKey] + mu.Unlock() + if beganCount != 1 || endedCount != 1 { + t.Fatalf("expected begin=1 end=1, got begin=%d end=%d", beganCount, endedCount) + } +} + +func TestServiceDownloadOCREarlyProgressNotificationDoesNotHang(t *testing.T) { + payload := []byte("rapidocr-test-model-bytes") + sum := sha256.Sum256(payload) + wantHex := hex.EncodeToString(sum[:]) + + var svc *Service + svc = NewService(ServiceOptions{ + DataDir: t.TempDir(), + CallHost: func(_ context.Context, method string, params any, out any) error { + switch method { + case "host/ui.confirm": + b, _ := json.Marshal(pluginsdk.ConfirmResult{Approved: true}) + return json.Unmarshal(b, out) + case "host/download.start": + var req pluginsdk.DownloadRequest + b, _ := json.Marshal(params) + _ = json.Unmarshal(b, &req) + if err := os.WriteFile(req.Dest, payload, 0o644); err != nil { + return err + } + // Deliver terminal notification BEFORE returning download ID to test race safety! + svc.Notify("download/progress", pluginsdk.DownloadEvent{ + ID: "dl-early-1", + Status: "done", + Path: req.Dest, + }) + bOut, _ := json.Marshal(map[string]any{"id": "dl-early-1"}) + return json.Unmarshal(bOut, out) + default: + return nil + } + }, + }) + + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + var resp map[string]any + err := svc.Call(ctx, "autoinstall/downloadOCR", map[string]any{ + "assets": []ocr.AssetSpec{{ + Name: "test.onnx", + SHA256: wantHex, + Mirrors: []string{"https://modelscope.cn/test.onnx"}, + }}, + }, &resp) + if err != nil { + t.Fatalf("downloadOCR with early progress failed: %v", err) + } + if ok, _ := resp["ok"].(bool); !ok { + t.Fatalf("expected ok=true, got %+v", resp) + } +} + +func TestServiceSessionStoppedPermissionDeniedPreservesFallbackOutcome(t *testing.T) { + const vmKey = "builtin.driver.reims-macos::deny-outcome" + const fallbackMsg = "已拒绝插件运行权限,已为你切回原版手动安装引导" + dataDir := t.TempDir() + eng := &stubOCREngine{} + + beginCalled := make(chan struct{}) + releaseBegin := make(chan struct{}) + + svc := NewService(ServiceOptions{ + DataDir: dataDir, + CallHost: func(_ context.Context, method string, _ any, _ any) error { + switch method { + case "host/session.begin": + close(beginCalled) + <-releaseBegin + return errors.New("confirmation_denied: user denied") + default: + return nil + } + }, + OpenOCR: func(_, _, _ string) (ocr.Engine, ocr.ProbeReport, error) { + return eng, ocr.ProbeReport{ActiveBackend: "stub"}, nil + }, + RunnerOptions: runner.Options{ + DisableSleep: true, + }, + }) + + var st runner.RunStatusView + if err := svc.Call(context.Background(), "autoinstall/start", runner.RunConfig{ + VM: vmKey, + Mode: runner.ModeRecoveryOnly, + GuestLang: "zh-Hans:0", + SLAAccepted: true, + }, &st); err != nil { + t.Fatalf("autoinstall/start failed: %v", err) + } + + select { + case <-beginCalled: + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for host/session.begin") + } + + // Host denies permission and delivers session/stopped BEFORE BeginSession returns. + svc.Notify("session/stopped", map[string]any{ + "vm": vmKey, + "reason": "confirmation_denied", + "message": fallbackMsg, + }) + close(releaseBegin) + + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) && !eng.closed.Load() { + time.Sleep(5 * time.Millisecond) + } + if !eng.closed.Load() { + t.Fatal("expected OCR engine to close after permission-denied stop") + } + + var finalStatus runner.RunStatusView + if err := svc.Call(context.Background(), "autoinstall/status", map[string]any{"vm": vmKey}, &finalStatus); err != nil { + t.Fatalf("autoinstall/status failed: %v", err) + } + if finalStatus.Status != runner.StatusFailed || finalStatus.PauseReason != "confirmation_denied" || finalStatus.Message != fallbackMsg { + t.Fatalf("unexpected final status after permission denial: %+v", finalStatus) + } + cp, ok := runner.LoadCheckpoint(dataDir, vmKey) + if !ok || cp.Status != runner.StatusFailed || cp.PauseReason != "confirmation_denied" || cp.Message != fallbackMsg { + t.Fatalf("unexpected on-disk checkpoint after permission denial: ok=%v cp=%+v", ok, cp) + } +} + +func TestServiceResumeRejectsCompletedAndDownloadValidatesBeforeConfirm(t *testing.T) { + dataDir := t.TempDir() + const vmKey = "builtin.driver.reims-macos::done-vm" + confirmCalled := false + svc := NewService(ServiceOptions{ + DataDir: dataDir, + CallHost: func(_ context.Context, method string, _ any, _ any) error { + if method == "host/ui.confirm" { + confirmCalled = true + } + return nil + }, + OpenOCR: func(_, _, _ string) (ocr.Engine, ocr.ProbeReport, error) { + return &stubOCREngine{}, ocr.ProbeReport{ActiveBackend: "stub"}, nil + }, + }) + + // Completed checkpoint on disk must not be restarted by autoinstall/resume. + if err := os.MkdirAll(dataDir+"/runs", 0o755); err != nil { + t.Fatal(err) + } + raw, _ := json.Marshal(runner.Checkpoint{ + Version: 1, + VM: vmKey, + Stage: runner.StageDesktopReady, + Status: runner.StatusCompleted, + Config: runner.RunConfig{VM: vmKey, Mode: runner.ModeRecoveryOnly, GuestLang: "zh-Hans:0", SLAAccepted: true}, + }) + if err := os.WriteFile(dataDir+"/runs/builtin.driver.reims-macos__done-vm.json", raw, 0o600); err != nil { + t.Fatal(err) + } + if err := svc.Call(context.Background(), "autoinstall/resume", map[string]any{"vm": vmKey}, nil); err == nil { + t.Fatal("expected autoinstall/resume to reject already-completed checkpoint") + } + + // Default download assets without pinned SHA-256 must fail BEFORE showing confirm dialog. + if err := svc.Call(context.Background(), "autoinstall/downloadOCR", map[string]any{}, nil); err == nil { + t.Fatal("expected downloadOCR without pinned SHA-256 to fail") + } + if confirmCalled { + t.Fatal("host/ui.confirm must not be shown when asset specs fail validation") + } + + var preflight map[string]any + if err := svc.Call(context.Background(), "autoinstall/preflight", map[string]any{"vm": vmKey, "guest_lang": "zh-Hans:0"}, &preflight); err != nil { + t.Fatalf("autoinstall/preflight: %v", err) + } + if canDL, ok := preflight["can_download_ocr"].(bool); !ok || canDL { + t.Fatalf("expected can_download_ocr=false when default assets lack pinned SHA-256/DLL, got %+v", preflight) + } +} + +func TestServiceConcurrentStartSerializesPerVM(t *testing.T) { + const vmKey = "builtin.driver.reims-macos:concurrent-start" + dataDir := t.TempDir() + var openCount atomic.Int32 + var inOpen atomic.Int32 + var maxConcurrentOpen atomic.Int32 + var enginesMu sync.Mutex + var engines []*stubOCREngine + + svc := NewService(ServiceOptions{ + DataDir: dataDir, + CallHost: func(ctx context.Context, method string, _ any, out any) error { + switch method { + case "host/console.screenshot": + // Block cleanly until canceled so runners remain active until stopped. + <-ctx.Done() + return ctx.Err() + default: + return nil + } + }, + OpenOCR: func(_, _, _ string) (ocr.Engine, ocr.ProbeReport, error) { + cur := inOpen.Add(1) + for { + prev := maxConcurrentOpen.Load() + if cur <= prev || maxConcurrentOpen.CompareAndSwap(prev, cur) { + break + } + } + time.Sleep(25 * time.Millisecond) + inOpen.Add(-1) + openCount.Add(1) + eng := &stubOCREngine{} + enginesMu.Lock() + engines = append(engines, eng) + enginesMu.Unlock() + return eng, ocr.ProbeReport{ActiveBackend: "stub"}, nil + }, + RunnerOptions: runner.Options{DisableSleep: true}, + }) + defer svc.StopAll() + + var wg sync.WaitGroup + errs := make([]error, 2) + for i := 0; i < 2; i++ { + idx := i + wg.Add(1) + go func() { + defer wg.Done() + errs[idx] = svc.Call(context.Background(), "autoinstall/start", runner.RunConfig{ + VM: vmKey, + Mode: runner.ModeRecoveryOnly, + GuestLang: "zh-Hans:0", + SLAAccepted: true, + }, nil) + }() + } + wg.Wait() + for i, err := range errs { + if err != nil { + t.Fatalf("concurrent start #%d failed: %v", i, err) + } + } + if maxConcurrentOpen.Load() != 1 { + t.Fatalf("same-VM concurrent starts must serialize OpenOCR, observed concurrency=%d", maxConcurrentOpen.Load()) + } + if openCount.Load() != 2 { + t.Fatalf("expected 2 serialized starts, got %d", openCount.Load()) + } + var st runner.RunStatusView + if err := svc.Call(context.Background(), "autoinstall/status", map[string]any{"vm": vmKey}, &st); err != nil { + t.Fatalf("status after concurrent starts: %v", err) + } + if st.Status != runner.StatusRunning { + t.Fatalf("expected final serialized runner to remain running, got %+v", st) + } + svc.StopAll() + enginesMu.Lock() + defer enginesMu.Unlock() + for i, eng := range engines { + if !eng.closed.Load() { + t.Fatalf("OCR engine #%d leaked open after StopAll", i) + } + } +} diff --git a/internal/macos/autoinstall/vision/locator.go b/internal/macos/autoinstall/vision/locator.go new file mode 100644 index 0000000..cedde48 --- /dev/null +++ b/internal/macos/autoinstall/vision/locator.go @@ -0,0 +1,116 @@ +package vision + +import ( + "context" + "image" + + "github.com/Nwflower/reims-go/internal/macos/autoinstall/ocr" +) + +// VisualLocator abstracts screen text/button localization so the pure-local +// implementation can be swapped or extended in the future. +type VisualLocator interface { + ScanROI(ctx context.Context, img image.Image, roiName string, anchor *image.Point) (ROIScan, error) + ScanButtons(ctx context.Context, img image.Image, roiName string) ([]ButtonBox, error) +} + +// ROIScan combines OCR lines mapped back into source framebuffer coordinates +// with the scanned rectangle. +type ROIScan struct { + ROI image.Rectangle + Lines []ocr.Line + Text string +} + +// LocalLocator implements dual-channel local visual understanding: +// - small-text channel (menu_bar, menu_dropdown, body, terminal, login_band): 2x bicubic upscale + local OCR +// - accent-button channel (action_bar, modal): blue component detection + invert/stretch OCR verification +type LocalLocator struct { + Engine ocr.Engine +} + +func NewLocalLocator(engine ocr.Engine) *LocalLocator { + return &LocalLocator{Engine: engine} +} + +func (l *LocalLocator) ScanROI(ctx context.Context, img image.Image, roiName string, anchor *image.Point) (ROIScan, error) { + b := img.Bounds() + roi := ResolveROI(roiName, b.Dx(), b.Dy(), anchor) + if roi.Empty() { + return ROIScan{}, nil + } + cropped := Crop(img, roi) + scale := 1.0 + pad := 0 + input := cropped + maxDim := l.Engine.MaxDimension() + switch roiName { + case "menu_bar", "menu_dropdown", "title_band", "body", "modal", "terminal", "login_band": + needsDarkPrep := roiName == "menu_bar" || roiName == "menu_dropdown" || roiName == "terminal" || roiName == "login_band" + scaleCap := maxDim + if needsDarkPrep && scaleCap > darkOCRPad*2 { + // Reserve border padding added by PrepareDarkTextForOCR so dark-mode + // crops on 1080p/HiDPI displays never exceed WinOCR's MaxImageDimension. + scaleCap -= darkOCRPad * 2 + } + input, scale = Upscale2x(cropped, scaleCap) + if needsDarkPrep { + input, pad = PrepareDarkTextForOCR(input) + } + default: + if maxDim > 0 && (cropped.Bounds().Dx() > maxDim || cropped.Bounds().Dy() > maxDim) { + input, scale = Upscale2x(cropped, maxDim) + } + } + res, err := l.Engine.Recognize(ctx, input) + if err != nil { + return ROIScan{}, err + } + lines := make([]ocr.Line, 0, len(res.Lines)) + for _, ln := range res.Lines { + mapped := ocr.Line{ + Text: ln.Text, + Rect: mapRectBack(ln.Rect, roi, pad, scale), + } + for _, w := range ln.Words { + mapped.Words = append(mapped.Words, ocr.Word{ + Text: w.Text, + Rect: mapRectBack(w.Rect, roi, pad, scale), + }) + } + lines = append(lines, mapped) + } + return ROIScan{ROI: roi, Lines: lines, Text: res.Text}, nil +} + +func (l *LocalLocator) ScanButtons(ctx context.Context, img image.Image, roiName string) ([]ButtonBox, error) { + b := img.Bounds() + roi := ResolveROI(roiName, b.Dx(), b.Dy(), nil) + buttons := DetectAccentButtons(img, roi) + maxDim := l.Engine.MaxDimension() + for i := range buttons { + crop := Crop(img, buttons[i].Rect) + inv := InvertAndStretch(crop, maxDim) + if res, err := l.Engine.Recognize(ctx, inv); err == nil { + buttons[i].Text = res.Text + } + } + return buttons, nil +} + +func mapRectBack(r image.Rectangle, roi image.Rectangle, pad int, scale float64) image.Rectangle { + if scale <= 0 { + scale = 1 + } + mapped := image.Rect( + roi.Min.X+int(float64(r.Min.X-pad)/scale), + roi.Min.Y+int(float64(r.Min.Y-pad)/scale), + roi.Min.X+int(float64(r.Max.X-pad)/scale), + roi.Min.Y+int(float64(r.Max.Y-pad)/scale), + ) + clamped := mapped.Intersect(roi) + if clamped.Empty() { + return mapped + } + return clamped +} diff --git a/internal/macos/autoinstall/vision/probes.go b/internal/macos/autoinstall/vision/probes.go new file mode 100644 index 0000000..019d481 --- /dev/null +++ b/internal/macos/autoinstall/vision/probes.go @@ -0,0 +1,431 @@ +package vision + +import ( + "image" + "math" + "regexp" + "sort" + "strings" + + "github.com/Nwflower/reims-go/internal/macos/autoinstall/ocr" +) + +// ButtonBox represents a detected macOS accent primary button (e.g. blue Continue/Agree). +type ButtonBox struct { + Rect image.Rectangle + Center image.Point + Enabled bool + Text string +} + +func isAccentBlue(r, g, b uint8) bool { + // Covers macOS Big Sur–Tahoe accent blue (#007AFF / #0A84FF / Liquid Glass translucent blue). + return int(b) >= 150 && int(b)-int(r) >= 65 && int(b)-int(g) >= 20 && int(r) <= 135 +} + +// DetectAccentButtons scans roi for connected accent-blue macOS primary buttons. +func DetectAccentButtons(img image.Image, roi image.Rectangle) []ButtonBox { + sub := Crop(img, roi) + w, h := sub.Bounds().Dx(), sub.Bounds().Dy() + if w < 24 || h < 14 { + return nil + } + mask := make([]bool, w*h) + for y := 0; y < h; y++ { + row := sub.Pix[y*sub.Stride:] + for x := 0; x < w; x++ { + off := x * 4 + if isAccentBlue(row[off], row[off+1], row[off+2]) { + mask[y*w+x] = true + } + } + } + visited := make([]bool, w*h) + queue := make([]int, 0, 256) + var out []ButtonBox + + for y := 0; y < h; y += 2 { + for x := 0; x < w; x += 2 { + idx := y*w + x + if !mask[idx] || visited[idx] { + continue + } + minX, maxX, minY, maxY := x, x, y, y + count := 0 + queue = queue[:0] + queue = append(queue, idx) + visited[idx] = true + for head := 0; head < len(queue); head++ { + cur := queue[head] + cx, cy := cur%w, cur/w + count++ + if cx < minX { + minX = cx + } + if cx > maxX { + maxX = cx + } + if cy < minY { + minY = cy + } + if cy > maxY { + maxY = cy + } + for _, d := range [4][2]int{{2, 0}, {-2, 0}, {0, 2}, {0, -2}} { + nx, ny := cx+d[0], cy+d[1] + if nx >= 0 && nx < w && ny >= 0 && ny < h { + nidx := ny*w + nx + if mask[nidx] && !visited[nidx] { + visited[nidx] = true + queue = append(queue, nidx) + } + } + } + } + bw, bh := maxX-minX+2, maxY-minY+2 + // Filter to realistic button dimensions (width 40..440, height 18..96, solid fill ratio >= 0.35). + if bw < 40 || bw > 440 || bh < 18 || bh > 96 { + continue + } + area := float64(bw * bh) + fillRatio := float64(count*4) / area + if fillRatio < 0.35 { + continue + } + rect := image.Rect(roi.Min.X+minX, roi.Min.Y+minY, roi.Min.X+maxX+2, roi.Min.Y+maxY+2).Intersect(roi) + if rect.Empty() { + continue + } + out = append(out, ButtonBox{ + Rect: rect, + Center: image.Pt((rect.Min.X+rect.Max.X)/2, (rect.Min.Y+rect.Max.Y)/2), + Enabled: true, + }) + } + } + sort.Slice(out, func(i, j int) bool { + if out[i].Center.Y != out[j].Center.Y { + return out[i].Center.Y < out[j].Center.Y + } + return out[i].Center.X < out[j].Center.X + }) + return out +} + +// ProbeCheckboxState inspects the small checkbox square immediately left of a +// label's bounding rect and determines checked/unchecked from accent-blue fill. +func ProbeCheckboxState(img image.Image, labelRect image.Rectangle) (checked bool, blueRatio float64, clickPt image.Point) { + cy := (labelRect.Min.Y + labelRect.Max.Y) / 2 + box := image.Rect(labelRect.Min.X-30, cy-11, labelRect.Min.X-6, cy+11).Intersect(img.Bounds()) + clickPt = image.Pt(max(0, labelRect.Min.X-18), cy) + if box.Empty() { + return false, 0, clickPt + } + total, blue := 0, 0 + for y := box.Min.Y; y < box.Max.Y; y++ { + for x := box.Min.X; x < box.Max.X; x++ { + r, g, b, _ := img.At(x, y).RGBA() + total++ + if isAccentBlue(uint8(r>>8), uint8(g>>8), uint8(b>>8)) { + blue++ + } + } + } + if total == 0 { + return false, 0, clickPt + } + ratio := float64(blue) / float64(total) + return ratio >= 0.14, ratio, clickPt +} + +func pixelLuma(img image.Image, x, y int) (luma int, blue bool) { + r, g, b, _ := img.At(x, y).RGBA() + r8, g8, b8 := uint8(r>>8), uint8(g>>8), uint8(b>>8) + return (299*int(r8) + 587*int(g8) + 114*int(b8)) / 1000, isAccentBlue(r8, g8, b8) +} + +// DetectInputFieldNearLabel locates a clickable center inside the input field +// immediately to the right of a form field label. It returns ok=false when no +// visual input-field evidence (interior/background luminance contrast, box +// border edges, or accent-blue focus ring) exists, preventing blind clicks or +// password injection onto uniform window backgrounds. +func DetectInputFieldNearLabel(img image.Image, labelRect image.Rectangle) (image.Point, image.Rectangle, bool) { + if img == nil || labelRect.Empty() { + return image.Point{}, image.Rectangle{}, false + } + bounds := img.Bounds() + cy := (labelRect.Min.Y + labelRect.Max.Y) / 2 + // macOS account creation forms lay out labels on the left and fields ~16-260px to the right. + rightProbe := image.Rect(labelRect.Max.X+16, cy-14, min(bounds.Max.X, labelRect.Max.X+260), cy+14).Intersect(bounds) + if rightProbe.Empty() || rightProbe.Dx() < 40 || rightProbe.Dy() < 12 { + return image.Point{}, image.Rectangle{}, false + } + + // 1. Sample interior band around label midline and detect accent focus ring. + innerMinY := max(rightProbe.Min.Y, cy-4) + innerMaxY := min(rightProbe.Max.Y, cy+5) + var innerSum, innerTotal, blueCount int + for y := innerMinY; y < innerMaxY; y += 2 { + for x := rightProbe.Min.X; x < rightProbe.Max.X; x += 2 { + l, isBlue := pixelLuma(img, x, y) + innerSum += l + innerTotal++ + if isBlue { + blueCount++ + } + } + } + if innerTotal == 0 { + return image.Point{}, image.Rectangle{}, false + } + innerMean := innerSum / innerTotal + + // 2. Sample surrounding strips immediately above and below rightProbe as background reference. + var bgSum, bgTotal int + for _, band := range [][2]int{{cy - 22, cy - 16}, {cy + 16, cy + 22}} { + y0 := max(bounds.Min.Y, band[0]) + y1 := min(bounds.Max.Y, band[1]) + for y := y0; y < y1; y += 2 { + for x := rightProbe.Min.X; x < rightProbe.Max.X; x += 4 { + l, isBlue := pixelLuma(img, x, y) + bgSum += l + bgTotal++ + if isBlue { + blueCount++ + } + } + } + } + + // 3. Measure vertical border transitions across columns (captures input-box + // top/bottom borders in both light and dark modes). + scanMinY := max(bounds.Min.Y, cy-16) + scanMaxY := min(bounds.Max.Y, cy+17) + var edgeCols, totalCols int + for x := rightProbe.Min.X; x < rightProbe.Max.X; x += 4 { + minL, maxL := 255, 0 + for y := scanMinY; y < scanMaxY; y++ { + l, isBlue := pixelLuma(img, x, y) + if l < minL { + minL = l + } + if l > maxL { + maxL = l + } + if isBlue { + blueCount++ + } + } + totalCols++ + if maxL-minL >= 12 { + edgeCols++ + } + } + + hasContrast := bgTotal > 0 && absInt(innerMean-(bgSum/bgTotal)) >= 10 + hasBorder := totalCols > 0 && float64(edgeCols)/float64(totalCols) >= 0.35 + hasFocusRing := blueCount >= 8 + if !hasContrast && !hasBorder && !hasFocusRing { + return image.Point{}, image.Rectangle{}, false + } + return image.Pt((rightProbe.Min.X+rightProbe.Max.X)/2, cy), rightProbe, true +} + +// DetectCircularButton looks for the centered circular next-arrow button on the +// macOS "hello" welcome screen. +func DetectCircularButton(img image.Image, roi image.Rectangle) (image.Point, bool) { + sub := Crop(img, roi) + w, h := sub.Bounds().Dx(), sub.Bounds().Dy() + if w < 40 || h < 40 { + return image.Point{}, false + } + // Sample horizontal center band for bright/accent circular button. + cx := w / 2 + minX, maxX := max(0, cx-60), min(w, cx+60) + var sumX, sumY, hits int + for y := 0; y < h; y++ { + row := sub.Pix[y*sub.Stride:] + for x := minX; x < maxX; x++ { + off := x * 4 + r, g, b := row[off], row[off+1], row[off+2] + luma := (299*int(r) + 587*int(g) + 114*int(b)) / 1000 + if isAccentBlue(r, g, b) || luma >= 210 { + sumX += x + sumY += y + hits++ + } + } + } + if hits < 150 || hits > (maxX-minX)*h*6/10 { + return image.Point{}, false + } + return image.Pt(roi.Min.X+sumX/hits, roi.Min.Y+sumY/hits), true +} + +// DetectAppleProgress identifies the black boot/install screen featuring the +// centered white Apple logo and horizontal progress bar underneath (>85% dark). +func DetectAppleProgress(img image.Image) bool { + b := img.Bounds() + w, h := b.Dx(), b.Dy() + if w < 160 || h < 90 { + return false + } + dark, total := 0, 0 + centerBright, centerTotal := 0, 0 + barBright, barTotal := 0, 0 + + stepX := max(1, w/160) + stepY := max(1, h/90) + for y := 0; y < h; y += stepY { + for x := 0; x < w; x += stepX { + r, g, bl, _ := img.At(b.Min.X+x, b.Min.Y+y).RGBA() + l := (299*int(r>>8) + 587*int(g>>8) + 114*int(bl>>8)) / 1000 + total++ + if l < 36 { + dark++ + } + fx := float64(x) / float64(w) + fy := float64(y) / float64(h) + if fx >= 0.42 && fx <= 0.58 && fy >= 0.30 && fy <= 0.56 { + centerTotal++ + if l > 180 { + centerBright++ + } + } + if fx >= 0.32 && fx <= 0.68 && fy >= 0.58 && fy <= 0.72 { + barTotal++ + if l > 110 { + barBright++ + } + } + } + } + if total == 0 || centerTotal == 0 || barTotal == 0 { + return false + } + darkRatio := float64(dark) / float64(total) + logoRatio := float64(centerBright) / float64(centerTotal) + barRatio := float64(barBright) / float64(barTotal) + return darkRatio >= 0.85 && logoRatio >= 0.04 && logoRatio <= 0.65 && barRatio >= 0.015 && barRatio <= 0.35 +} + +// FrameDiffRatio computes normalized mean pixel difference on a 160x90 grayscale +// grid between two frames (returning 0..1; cursor blink stays < 0.002). +func FrameDiffRatio(a, b image.Image) float64 { + if a == nil || b == nil { + return 1.0 + } + ga := downsampleGray(a, 160, 90) + gb := downsampleGray(b, 160, 90) + var diffSum float64 + for i := range ga { + d := math.Abs(float64(ga[i]) - float64(gb[i])) + if d > 8 { // ignore subtle quantization/cursor flicker + diffSum += d / 255.0 + } + } + return diffSum / float64(len(ga)) +} + +func downsampleGray(img image.Image, dw, dh int) []uint8 { + b := img.Bounds() + sw, sh := b.Dx(), b.Dy() + out := make([]uint8, dw*dh) + if sw <= 0 || sh <= 0 { + return out + } + for y := 0; y < dh; y++ { + sy := b.Min.Y + y*sh/dh + for x := 0; x < dw; x++ { + sx := b.Min.X + x*sw/dw + r, g, bl, _ := img.At(sx, sy).RGBA() + out[y*dw+x] = uint8((299*int(r>>8) + 587*int(g>>8) + 114*int(bl>>8)) / 1000) + } + } + return out +} + +// DetectMaskDotsDelta checks whether pixels inside a password field changed +// after calling host/console.typeSecret (confirming bullet dots appeared without +// ever running OCR on the password box). +func DetectMaskDotsDelta(before, after image.Image, fieldRect image.Rectangle) bool { + if before == nil || after == nil || fieldRect.Empty() { + return false + } + clamped := fieldRect.Intersect(before.Bounds()).Intersect(after.Bounds()) + if clamped.Empty() { + return false + } + changed := 0 + for y := clamped.Min.Y; y < clamped.Max.Y; y++ { + for x := clamped.Min.X; x < clamped.Max.X; x++ { + r1, g1, b1, _ := before.At(x, y).RGBA() + r2, g2, b2, _ := after.At(x, y).RGBA() + diff := absInt(int(r1>>8)-int(r2>>8)) + absInt(int(g1>>8)-int(g2>>8)) + absInt(int(b1>>8)-int(b2>>8)) + if diff > 45 { + changed++ + } + } + } + return changed >= 12 +} + +var reMenuClock = regexp.MustCompile(`(?:[01]?\d|2[0-3])\s*[::]\s*[0-5]\d`) + +// DetectDesktopReady evaluates the multi-signal desktop readiness criterion: +// menu_bar shows Finder/访达 + at least 2 standard menu verbs + clock text, +// and no Setup Assistant or Keyboard Setup Assistant modal is open. +func DetectDesktopReady(menuBarLines []ocr.Line, centerText string) bool { + var parts []string + for _, ln := range menuBarLines { + parts = append(parts, ln.Text) + } + rawMenu := strings.Join(parts, " ") + compactMenu := strings.ToLower(strings.ReplaceAll(rawMenu, " ", "")) + + hasFinder := strings.Contains(compactMenu, "finder") || strings.Contains(compactMenu, "访达") || strings.Contains(compactMenu, "訪達") + if !hasFinder { + return false + } + verbs := [][]string{ + {"file", "文件", "檔案", "ファイル"}, + {"edit", "编辑", "編輯", "編集"}, + {"view", "显示", "顯示", "表示"}, + {"go", "前往", "移動"}, + {"window", "窗口", "視窗", "ウインドウ"}, + {"help", "帮助", "輔助說明", "ヘルプ"}, + } + matchedVerbs := 0 + for _, group := range verbs { + for _, token := range group { + if strings.Contains(compactMenu, token) { + matchedVerbs++ + break + } + } + } + if matchedVerbs < 2 { + return false + } + if !reMenuClock.MatchString(rawMenu) { + return false + } + compactCenter := strings.ToLower(strings.ReplaceAll(centerText, " ", "")) + blockers := []string{ + "setupassistant", "keyboardsetupassistant", "键盘设置助理", "鍵盤設定輔助程式", "キーボード設定アシスタント", + "选择国家", "selectyourcountry", "createacomputeraccount", "创建电脑账户", "创建mac账户", "filevault", "termsandconditions", + } + for _, b := range blockers { + if strings.Contains(compactCenter, b) { + return false + } + } + return true +} + +func absInt(v int) int { + if v < 0 { + return -v + } + return v +} diff --git a/internal/macos/autoinstall/vision/replay_windows_test.go b/internal/macos/autoinstall/vision/replay_windows_test.go new file mode 100644 index 0000000..2e58484 --- /dev/null +++ b/internal/macos/autoinstall/vision/replay_windows_test.go @@ -0,0 +1,219 @@ +//go:build windows + +package vision + +import ( + "context" + "image" + "image/color" + "strings" + "syscall" + "testing" + "time" + "unsafe" + + "github.com/Nwflower/reims-go/internal/macos/autoinstall/ocr" + "github.com/Nwflower/reims-go/internal/macos/autoinstall/rules" +) + +type gdiDrawItem struct { + Text string + X, Y int32 + W, H int32 + Size int32 + Color color.RGBA + BgBox *color.RGBA +} + +func renderReplayFrame(t *testing.T, w, h int, bg color.RGBA, items []gdiDrawItem) *image.RGBA { + t.Helper() + gdi32 := syscall.NewLazyDLL("gdi32.dll") + user32 := syscall.NewLazyDLL("user32.dll") + procCreateCompatibleDC := gdi32.NewProc("CreateCompatibleDC") + procDeleteDC := gdi32.NewProc("DeleteDC") + procCreateDIBSection := gdi32.NewProc("CreateDIBSection") + procSelectObject := gdi32.NewProc("SelectObject") + procDeleteObject := gdi32.NewProc("DeleteObject") + procCreateSolidBrush := gdi32.NewProc("CreateSolidBrush") + procCreateFontW := gdi32.NewProc("CreateFontW") + procSetBkMode := gdi32.NewProc("SetBkMode") + procSetTextColor := gdi32.NewProc("SetTextColor") + procFillRect := user32.NewProc("FillRect") + procDrawTextW := user32.NewProc("DrawTextW") + + type rect struct{ L, T, R, B int32 } + type bmiHeader struct { + Size uint32 + Width int32 + Height int32 + Planes uint16 + BitCount uint16 + Compression uint32 + SizeImage uint32 + XPelsPerMeter int32 + YPelsPerMeter int32 + ClrUsed uint32 + ClrImportant uint32 + } + type bmi struct { + Header bmiHeader + Colors [1]uint32 + } + hdc, _, _ := procCreateCompatibleDC.Call(0) + defer procDeleteDC.Call(hdc) + bi := bmi{Header: bmiHeader{ + Size: uint32(unsafe.Sizeof(bmiHeader{})), Width: int32(w), Height: -int32(h), Planes: 1, BitCount: 32, + }} + var bits unsafe.Pointer + hbm, _, _ := procCreateDIBSection.Call(hdc, uintptr(unsafe.Pointer(&bi)), 0, uintptr(unsafe.Pointer(&bits)), 0, 0) + defer procDeleteObject.Call(hbm) + oldBM, _, _ := procSelectObject.Call(hdc, hbm) + defer procSelectObject.Call(hdc, oldBM) + + rgb := func(c color.RGBA) uintptr { + return uintptr(uint32(c.R) | uint32(c.G)<<8 | uint32(c.B)<<16) + } + full := rect{0, 0, int32(w), int32(h)} + bgBr, _, _ := procCreateSolidBrush.Call(rgb(bg)) + procFillRect.Call(hdc, uintptr(unsafe.Pointer(&full)), bgBr) + procDeleteObject.Call(bgBr) + procSetBkMode.Call(hdc, 1) + fontName, _ := syscall.UTF16PtrFromString("Microsoft YaHei UI") + + for _, it := range items { + r := rect{it.X, it.Y, it.X + it.W, it.Y + it.H} + if it.BgBox != nil { + br, _, _ := procCreateSolidBrush.Call(rgb(*it.BgBox)) + procFillRect.Call(hdc, uintptr(unsafe.Pointer(&r)), br) + procDeleteObject.Call(br) + } + hFont, _, _ := procCreateFontW.Call(uintptr(^uint32(it.Size)+1), 0, 0, 0, 500, 0, 0, 0, 1, 0, 0, 5, 0, uintptr(unsafe.Pointer(fontName))) + oldF, _, _ := procSelectObject.Call(hdc, hFont) + procSetTextColor.Call(hdc, rgb(it.Color)) + u16, _ := syscall.UTF16FromString(it.Text) + flags := uintptr(0x24) // DT_VCENTER|DT_SINGLELINE + if it.BgBox != nil { + flags |= 0x01 // DT_CENTER + } + procDrawTextW.Call(hdc, uintptr(unsafe.Pointer(&u16[0])), uintptr(len(u16)-1), uintptr(unsafe.Pointer(&r)), flags) + procSelectObject.Call(hdc, oldF) + procDeleteObject.Call(hFont) + } + + raw := unsafe.Slice((*byte)(bits), w*h*4) + img := image.NewRGBA(image.Rect(0, 0, w, h)) + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + off := (y*w + x) * 4 + img.SetRGBA(x, y, color.RGBA{R: raw[off+2], G: raw[off+1], B: raw[off+0], A: 255}) + } + } + return img +} + +func TestLocalLocatorLiveReplayBlueButtonAndSmallMenuBar(t *testing.T) { + langs, _, err := ocr.ListWinOCRLanguages() + if err != nil || len(langs) == 0 { + t.Skip("Windows.Media.Ocr unavailable on this host") + } + eng, err := ocr.NewWinOCREngine(langs[0]) + if err != nil { + t.Fatal(err) + } + defer eng.Close() + loc := NewLocalLocator(eng) + + darkBar := color.RGBA{30, 32, 38, 255} + accentBlue := color.RGBA{0, 122, 255, 255} + white := color.RGBA{255, 255, 255, 255} + + // 1920x1080 Recovery frame with small 14px dark top menu bar + #007AFF blue Continue button. + frame := renderReplayFrame(t, 1920, 1080, color.RGBA{242, 242, 247, 255}, []gdiDrawItem{ + {Text: "Recovery File Edit Utilities Window 14:20", X: 20, Y: 0, W: 1880, H: 32, Size: 15, Color: white, BgBox: &darkBar}, + {Text: "Reinstall macOS Sequoia", X: 520, Y: 220, W: 880, H: 64, Size: 38, Color: color.RGBA{22, 22, 26, 255}}, + {Text: "Continue", X: 1320, Y: 900, W: 180, H: 46, Size: 22, Color: white, BgBox: &accentBlue}, + }) + + start := time.Now() + barScan, err := loc.ScanROI(context.Background(), frame, "menu_bar", nil) + if err != nil { + t.Fatalf("ScanROI(menu_bar): %v", err) + } + buttons, err := loc.ScanButtons(context.Background(), frame, "action_bar") + if err != nil { + t.Fatalf("ScanButtons(action_bar): %v", err) + } + elapsed := time.Since(start) + t.Logf("Replay menu_bar=%q buttons=%+v total=%v", barScan.Text, buttons, elapsed) + + if !strings.Contains(strings.ToLower(barScan.Text), "utilities") { + t.Fatalf("2x upscaled menu_bar OCR missed 'Utilities': got %q", barScan.Text) + } + if len(buttons) != 1 { + t.Fatalf("expected 1 blue button in action_bar, got %+v", buttons) + } + if !strings.Contains(strings.ToLower(buttons[0].Text), "continue") { + t.Fatalf("inverted blue button OCR missed 'Continue': got %q", buttons[0].Text) + } + if elapsed > 300*time.Millisecond { + t.Logf("note: combined menu_bar+blue_button localization took %v", elapsed) + } +} + +func TestLocalLocatorLiveReplaySetupAssistantCountryRegionAt39Pct(t *testing.T) { + langs, _, err := ocr.ListWinOCRLanguages() + if err != nil || len(langs) == 0 { + t.Skip("Windows.Media.Ocr unavailable on this host") + } + zhLang := "" + for _, l := range langs { + if strings.HasPrefix(strings.ToLower(l), "zh-hans") || strings.EqualFold(l, "zh-cn") { + zhLang = l + break + } + } + if zhLang == "" { + t.Skip("Windows.Media.Ocr zh-Hans language pack unavailable on this host") + } + eng, err := ocr.NewWinOCREngine(zhLang) + if err != nil { + t.Fatal(err) + } + defer eng.Close() + loc := NewLocalLocator(eng) + ruleEng, err := rules.LoadEngine(t.TempDir()) + if err != nil { + t.Fatal(err) + } + + whiteCard := color.RGBA{255, 255, 255, 255} + ink := color.RGBA{29, 29, 31, 255} + // Reproduce the macOS Sequoia/Tahoe Setup Assistant "选择国家或地区" layout + // on 1920x1080 where the heading sits below the globe icon around Y=39% (~420px). + frame := renderReplayFrame(t, 1920, 1080, color.RGBA{18, 118, 178, 255}, []gdiDrawItem{ + {Text: "", X: 556, Y: 238, W: 808, H: 604, Size: 16, Color: ink, BgBox: &whiteCard}, + {Text: "<", X: 580, Y: 264, W: 32, H: 32, Size: 22, Color: color.RGBA{0, 122, 255, 255}}, + {Text: "选择国家或地区", X: 730, Y: 410, W: 300, H: 40, Size: 24, Color: ink}, + {Text: "阿尔巴尼亚", X: 730, Y: 462, W: 280, H: 28, Size: 18, Color: ink}, + {Text: "阿尔及利亚", X: 730, Y: 492, W: 280, H: 28, Size: 18, Color: ink}, + }) + + titleScan, err := loc.ScanROI(context.Background(), frame, "title_band", nil) + if err != nil { + t.Fatalf("ScanROI(title_band): %v", err) + } + bodyScan, err := loc.ScanROI(context.Background(), frame, "body", nil) + if err != nil { + t.Fatalf("ScanROI(body): %v", err) + } + t.Logf("Replay Setup Assistant title_band=%q body=%q", titleScan.Text, bodyScan.Text) + rule, ok := ruleEng.MatchScreen("setup_assistant", map[string]string{ + "title_band": titleScan.Text, + "body": bodyScan.Text, + "full": titleScan.Text + "\n" + bodyScan.Text, + }) + if !ok || rule.ID != "setup.region" { + t.Fatalf("expected setup.region match on 39%% Setup Assistant heading, got ok=%v rule=%q title=%q body=%q", + ok, rule.ID, titleScan.Text, bodyScan.Text) + } +} diff --git a/internal/macos/autoinstall/vision/roi.go b/internal/macos/autoinstall/vision/roi.go new file mode 100644 index 0000000..9beb3cf --- /dev/null +++ b/internal/macos/autoinstall/vision/roi.go @@ -0,0 +1,313 @@ +package vision + +import ( + "image" + "image/color" + "math" +) + +// ResolveROI maps a named logical screen region to source framebuffer pixel +// coordinates, adapting proportionally to any resolution and HiDPI scaling. +func ResolveROI(name string, frameW, frameH int, anchor *image.Point) image.Rectangle { + full := image.Rect(0, 0, frameW, frameH) + if frameW <= 0 || frameH <= 0 { + return image.Rectangle{} + } + pct := func(fx, fy, fw, fh float64) image.Rectangle { + x0 := int(math.Round(fx * float64(frameW))) + y0 := int(math.Round(fy * float64(frameH))) + x1 := int(math.Round((fx + fw) * float64(frameW))) + y1 := int(math.Round((fy + fh) * float64(frameH))) + return image.Rect(x0, y0, x1, y1).Intersect(full) + } + switch name { + case "menu_bar": + h := min(56, max(28, int(math.Round(0.045*float64(frameH))))) + return image.Rect(0, 0, frameW, h).Intersect(full) + case "menu_dropdown": + ax, ay := 80, 24 + if anchor != nil { + ax = max(0, anchor.X-60) + ay = max(18, anchor.Y) + } + w := max(360, int(math.Round(0.25*float64(frameW)))) + h := max(420, int(math.Round(0.45*float64(frameH)))) + return image.Rect(ax, ay, ax+w, ay+h).Intersect(full) + case "title_band": + return pct(0.12, 0.08, 0.76, 0.38) + case "body": + return pct(0.12, 0.26, 0.76, 0.54) + case "action_bar": + return pct(0.12, 0.74, 0.76, 0.24) + case "login_band": + return pct(0.28, 0.74, 0.44, 0.25) + case "modal": + return pct(0.20, 0.20, 0.60, 0.60) + case "terminal": + return pct(0.0, 0.03, 0.98, 0.94) + default: + return full + } +} + +// Crop extracts rect from img into a fresh 0-origin *image.RGBA. +func Crop(img image.Image, rect image.Rectangle) *image.RGBA { + b := img.Bounds() + clamped := rect.Add(b.Min).Intersect(b) + if clamped.Empty() { + return image.NewRGBA(image.Rect(0, 0, 1, 1)) + } + w, h := clamped.Dx(), clamped.Dy() + dst := image.NewRGBA(image.Rect(0, 0, w, h)) + if src, ok := img.(*image.RGBA); ok { + for y := 0; y < h; y++ { + soff := (clamped.Min.Y+y-src.Rect.Min.Y)*src.Stride + (clamped.Min.X-src.Rect.Min.X)*4 + doff := y * dst.Stride + copy(dst.Pix[doff:doff+w*4], src.Pix[soff:soff+w*4]) + } + return dst + } + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + r, g, bl, a := img.At(clamped.Min.X+x, clamped.Min.Y+y).RGBA() + dst.SetRGBA(x, y, color.RGBA{uint8(r >> 8), uint8(g >> 8), uint8(bl >> 8), uint8(a >> 8)}) + } + } + return dst +} + +// Upscale2x enlarges img using pure-Go Catmull-Rom bicubic interpolation for +// crisp small-font OCR (e.g., 10pt macOS menu bars), capping the scale factor +// so neither output dimension exceeds maxDim (e.g. 2600px on Windows 10). +func Upscale2x(img image.Image, maxDim int) (*image.RGBA, float64) { + b := img.Bounds() + sw, sh := b.Dx(), b.Dy() + if sw <= 0 || sh <= 0 { + return image.NewRGBA(image.Rect(0, 0, 1, 1)), 1 + } + scale := 2.0 + if maxDim > 0 { + maxEdge := float64(max(sw, sh)) + if maxEdge*scale > float64(maxDim) { + scale = float64(maxDim) / maxEdge + } + } + if scale >= 0.99 && scale <= 1.01 && (maxDim <= 0 || max(sw, sh) <= maxDim) { + return Crop(img, image.Rect(0, 0, sw, sh)), 1.0 + } + dw := max(1, int(math.Floor(float64(sw)*scale))) + dh := max(1, int(math.Floor(float64(sh)*scale))) + if maxDim > 0 { + dw = min(dw, maxDim) + dh = min(dh, maxDim) + } + actualScale := float64(dw) / float64(sw) + src := Crop(img, image.Rect(0, 0, sw, sh)) + dst := image.NewRGBA(image.Rect(0, 0, dw, dh)) + + clampInt := func(v, hi int) int { + if v < 0 { + return 0 + } + if v >= hi { + return hi - 1 + } + return v + } + cubic := func(t float64) float64 { + t = math.Abs(t) + if t <= 1 { + return 1.5*t*t*t - 2.5*t*t + 1 + } + if t < 2 { + return -0.5*t*t*t + 2.5*t*t - 4*t + 2 + } + return 0 + } + clampByte := func(v float64) uint8 { + if v <= 0 { + return 0 + } + if v >= 255 { + return 255 + } + return uint8(v + 0.5) + } + + invScaleX := float64(sw) / float64(dw) + invScaleY := float64(sh) / float64(dh) + for dy := 0; dy < dh; dy++ { + sy := (float64(dy)+0.5)*invScaleY - 0.5 + iy := int(math.Floor(sy)) + fy := sy - float64(iy) + var wy [4]float64 + var ys [4]int + for j := 0; j < 4; j++ { + ys[j] = clampInt(iy+j-1, sh) + wy[j] = cubic(float64(j-1) - fy) + } + drow := dst.Pix[dy*dst.Stride:] + for dx := 0; dx < dw; dx++ { + sx := (float64(dx)+0.5)*invScaleX - 0.5 + ix := int(math.Floor(sx)) + fx := sx - float64(ix) + var r, g, bl float64 + for j := 0; j < 4; j++ { + srow := src.Pix[ys[j]*src.Stride:] + wRow := wy[j] + for i := 0; i < 4; i++ { + w := wRow * cubic(float64(i-1)-fx) + off := clampInt(ix+i-1, sw) * 4 + r += float64(srow[off+0]) * w + g += float64(srow[off+1]) * w + bl += float64(srow[off+2]) * w + } + } + doff := dx * 4 + drow[doff+0] = clampByte(r) + drow[doff+1] = clampByte(g) + drow[doff+2] = clampByte(bl) + drow[doff+3] = 255 + } + } + return dst, actualScale +} + +// InvertAndStretch converts white-on-blue or light-on-dark buttons into crisp +// anti-aliased dark-on-white grayscale padded generously so Windows.Media.Ocr +// reads small primary buttons reliably. When maxDim > 0, the padded output is +// capped to maxDim so OCR engines with an image size limit never reject it. +func InvertAndStretch(img image.Image, maxDim int) *image.RGBA { + const pad = 40 + upscaleCap := 2000 + if maxDim > 0 && maxDim-pad*2 < upscaleCap { + upscaleCap = max(64, maxDim-pad*2) + } + src, _ := Upscale2x(img, upscaleCap) + w, h := src.Bounds().Dx(), src.Bounds().Dy() + // Trim 4px button border to avoid rounded edge artifacts affecting min/max luma. + margin := 4 + if w <= margin*4 || h <= margin*4 { + margin = 0 + } + var minL, maxL uint8 = 255, 0 + luma := make([]uint8, w*h) + for y := 0; y < h; y++ { + row := src.Pix[y*src.Stride:] + for x := 0; x < w; x++ { + off := x * 4 + // Emphasize red channel where #007AFF background is ~0 and white text is ~255. + l := uint8((500*int(row[off]) + 350*int(row[off+1]) + 150*int(row[off+2])) / 1000) + luma[y*w+x] = l + if x >= margin && x < w-margin && y >= margin && y < h-margin { + if l < minL { + minL = l + } + if l > maxL { + maxL = l + } + } + } + } + span := int(maxL) - int(minL) + if span < 16 { + span = 16 + } + dst := image.NewRGBA(image.Rect(0, 0, w+pad*2, h+pad*2)) + for i := 0; i < len(dst.Pix); i += 4 { + dst.Pix[i], dst.Pix[i+1], dst.Pix[i+2], dst.Pix[i+3] = 255, 255, 255, 255 + } + for y := margin; y < h-margin; y++ { + drow := dst.Pix[(y+pad)*dst.Stride:] + for x := margin; x < w-margin; x++ { + norm := (int(luma[y*w+x]) - int(minL)) * 255 / span + if norm < 0 { + norm = 0 + } + if norm > 255 { + norm = 255 + } + inv := uint8(255 - norm) + off := (x + pad) * 4 + drow[off], drow[off+1], drow[off+2], drow[off+3] = inv, inv, inv, 255 + } + } + return dst +} + +const darkOCRPad = 24 + +// PrepareDarkTextForOCR detects dark-mode UI crops (such as macOS Recovery's +// dark menu bar and dropdowns) and converts light-on-dark glyphs into crisp, +// anti-aliased dark-on-white grayscale with white border padding so +// Windows.Media.Ocr reads small CJK and Latin text reliably. Light-mode crops +// are returned unchanged with pad=0. +func PrepareDarkTextForOCR(src *image.RGBA) (*image.RGBA, int) { + if src == nil { + return nil, 0 + } + w, h := src.Bounds().Dx(), src.Bounds().Dy() + if w <= 0 || h <= 0 { + return src, 0 + } + var sumL int64 + var samples int64 + var minL, maxL uint8 = 255, 0 + for y := 0; y < h; y += 2 { + row := src.Pix[y*src.Stride:] + for x := 0; x < w; x += 2 { + off := x * 4 + l := uint8((299*int(row[off]) + 587*int(row[off+1]) + 114*int(row[off+2])) / 1000) + sumL += int64(l) + samples++ + if l < minL { + minL = l + } + if l > maxL { + maxL = l + } + } + } + if samples == 0 { + return src, 0 + } + avgL := int(sumL / samples) + if avgL >= 120 { + return src, 0 + } + // Dark mode: lift dark background near avgL to pure white and stretch bright glyphs to black. + floorL := avgL + 8 + if floorL < int(minL) { + floorL = int(minL) + } + ceilL := int(maxL) + if ceilL-floorL < 32 { + floorL = int(minL) + ceilL = max(floorL+32, int(maxL)) + } + span := ceilL - floorL + const pad = darkOCRPad + dst := image.NewRGBA(image.Rect(0, 0, w+pad*2, h+pad*2)) + for i := 0; i < len(dst.Pix); i += 4 { + dst.Pix[i], dst.Pix[i+1], dst.Pix[i+2], dst.Pix[i+3] = 255, 255, 255, 255 + } + for y := 0; y < h; y++ { + srow := src.Pix[y*src.Stride:] + drow := dst.Pix[(y+pad)*dst.Stride:] + for x := 0; x < w; x++ { + soff := x * 4 + l := (299*int(srow[soff]) + 587*int(srow[soff+1]) + 114*int(srow[soff+2])) / 1000 + norm := (l - floorL) * 255 / span + if norm < 0 { + norm = 0 + } + if norm > 255 { + norm = 255 + } + inv := uint8(255 - norm) + doff := (x + pad) * 4 + drow[doff], drow[doff+1], drow[doff+2], drow[doff+3] = inv, inv, inv, 255 + } + } + return dst, pad +} diff --git a/internal/macos/autoinstall/vision/vision_test.go b/internal/macos/autoinstall/vision/vision_test.go new file mode 100644 index 0000000..496039a --- /dev/null +++ b/internal/macos/autoinstall/vision/vision_test.go @@ -0,0 +1,222 @@ +package vision + +import ( + "context" + "image" + "image/color" + "testing" + + "github.com/Nwflower/reims-go/internal/macos/autoinstall/ocr" +) + +func TestDetectAccentButtonsAndCheckboxAndAppleProgress(t *testing.T) { + // 1. Blue #007AFF button + checked/unchecked checkbox. + img := image.NewRGBA(image.Rect(0, 0, 1280, 720)) + fillRect(img, img.Bounds(), color.RGBA{242, 242, 247, 255}) + blue := color.RGBA{0, 122, 255, 255} + btnRect := image.Rect(920, 610, 1080, 650) + fillRect(img, btnRect, blue) + // Checked box left of label at (360, 420) + fillRect(img, image.Rect(334, 412, 352, 430), blue) + // Unchecked box left of label at (360, 470) + fillRect(img, image.Rect(334, 462, 352, 480), color.RGBA{210, 210, 214, 255}) + + buttons := DetectAccentButtons(img, ResolveROI("action_bar", 1280, 720, nil)) + if len(buttons) != 1 { + t.Fatalf("expected 1 accent button, got %+v", buttons) + } + if !buttons[0].Center.In(btnRect) { + t.Fatalf("button center %v outside %v", buttons[0].Center, btnRect) + } + checked, _, _ := ProbeCheckboxState(img, image.Rect(360, 410, 560, 434)) + if !checked { + t.Fatal("expected checked checkbox to return true") + } + unchecked, _, _ := ProbeCheckboxState(img, image.Rect(360, 460, 560, 484)) + if unchecked { + t.Fatal("expected unchecked checkbox to return false") + } + + // 2. Apple logo + horizontal progress bar screen (>85% black). + boot := image.NewRGBA(image.Rect(0, 0, 1280, 720)) + fillRect(boot, boot.Bounds(), color.RGBA{4, 4, 4, 255}) + fillRect(boot, image.Rect(600, 260, 680, 350), color.RGBA{245, 245, 245, 255}) // logo + fillRect(boot, image.Rect(460, 460, 820, 468), color.RGBA{180, 180, 180, 255}) // progress bar + if !DetectAppleProgress(boot) { + t.Fatal("expected Apple progress screen to be detected") + } + if DetectAppleProgress(img) { + t.Fatal("light setup screen must not be detected as Apple progress screen") + } + + // 3. Password mask dots pixel delta (without OCR). + before := image.NewRGBA(image.Rect(0, 0, 400, 100)) + after := image.NewRGBA(image.Rect(0, 0, 400, 100)) + fillRect(before, before.Bounds(), color.RGBA{255, 255, 255, 255}) + fillRect(after, after.Bounds(), color.RGBA{255, 255, 255, 255}) + field := image.Rect(100, 30, 300, 60) + if DetectMaskDotsDelta(before, after, field) { + t.Fatal("identical frames should not report password mask dots") + } + for i := 0; i < 6; i++ { + fillRect(after, image.Rect(112+i*12, 42, 118+i*12, 48), color.RGBA{20, 20, 20, 255}) + } + if !DetectMaskDotsDelta(before, after, field) { + t.Fatal("expected password mask dots delta to return true") + } + + // 4. Desktop readiness multi-signal check. + menuLines := []ocr.Line{ + {Text: "访 达 文 件 编 辑 显 示 前 往 窗 口 帮 助 12:30"}, + } + if !DetectDesktopReady(menuLines, "") { + t.Fatal("expected Chinese Finder desktop menu bar + clock to report desktop ready") + } + if DetectDesktopReady(menuLines, "Keyboard Setup Assistant") { + t.Fatal("desktop with open Keyboard Setup Assistant must not report ready") + } + zhWinOCRLines := []ocr.Line{{Text: "访 达 文 件 编 辑 显 示 前 往 窗 口 帮 助 上午7 : 12"}} + if !DetectDesktopReady(zhWinOCRLines, "") { + t.Fatal("Chinese WinRT OCR menu bar with fullwidth spaced colon must report desktop ready") + } +} + +func TestUpscale2xRespectsMaxDimension(t *testing.T) { + small := image.NewRGBA(image.Rect(0, 0, 1920, 40)) + up, scale := Upscale2x(small, 2600) + if up.Bounds().Dx() > 2600 || scale >= 2.0 { + t.Fatalf("Upscale2x exceeded Win10 MaxImageDimension=2600: %v scale=%f", up.Bounds(), scale) + } +} + +func TestTitleBandCoversSetupAssistantHeading(t *testing.T) { + tb := ResolveROI("title_band", 1920, 1080, nil) + // macOS Sequoia/Tahoe Setup Assistant titles ("选择国家或地区") sit at Y=38%..44% (410..475px on 1080p). + heading := image.Pt(780, 425) + if !heading.In(tb) { + t.Fatalf("title_band %v must contain Setup Assistant heading at %v", tb, heading) + } +} + +type maxDimCheckingEngine struct { + maxDim int + seenSizes []image.Point +} + +func (e *maxDimCheckingEngine) Name() string { return "check" } +func (e *maxDimCheckingEngine) MaxDimension() int { return e.maxDim } +func (e *maxDimCheckingEngine) Close() error { return nil } +func (e *maxDimCheckingEngine) Recognize(_ context.Context, img image.Image) (ocr.Result, error) { + b := img.Bounds() + w, h := b.Dx(), b.Dy() + e.seenSizes = append(e.seenSizes, image.Pt(w, h)) + if w > e.maxDim || h > e.maxDim { + return ocr.Result{}, context.DeadlineExceeded + } + return ocr.Result{ + Backend: "check", + Text: "ok", + Lines: []ocr.Line{{ + Text: "ok", + Rect: image.Rect(w/4, h/4, w/2, h/2), + Words: []ocr.Word{{Text: "ok", Rect: image.Rect(w/4, h/4, w/2, h/2)}}, + }}, + }, nil +} + +func TestScanROIDarkModeAnd4KRespectMaxDimension(t *testing.T) { + const maxDim = 2600 + + // 1. Dark 1920x1080 Recovery screen: menu_bar + terminal get dark-text padding + // and must still remain <= 2600px wide for Windows OCR. + dark1080 := image.NewRGBA(image.Rect(0, 0, 1920, 1080)) + fillRect(dark1080, dark1080.Bounds(), color.RGBA{20, 20, 24, 255}) + eng := &maxDimCheckingEngine{maxDim: maxDim} + loc := NewLocalLocator(eng) + for _, roi := range []string{"menu_bar", "terminal", "login_band", "action_bar"} { + if _, err := loc.ScanROI(context.Background(), dark1080, roi, nil); err != nil { + t.Fatalf("dark 1080p ScanROI(%q) failed (maxDim exceeded): %v (sizes=%v)", roi, err, eng.seenSizes) + } + } + + // 2. 2K HiDPI (2560x1440 / 2560x1600) dark screen: scaleCap=2552 gives scale=0.997, + // which must NOT bypass maxDim via the [0.99, 1.01] fast-path (2560+48=2608 > 2600). + for _, h := range []int{1440, 1600} { + dark2K := image.NewRGBA(image.Rect(0, 0, 2560, h)) + fillRect(dark2K, dark2K.Bounds(), color.RGBA{20, 20, 24, 255}) + eng2K := &maxDimCheckingEngine{maxDim: maxDim} + loc2K := NewLocalLocator(eng2K) + for _, roi := range []string{"menu_bar", "terminal", "login_band", "action_bar"} { + if _, err := loc2K.ScanROI(context.Background(), dark2K, roi, nil); err != nil { + t.Fatalf("dark 2560x%d ScanROI(%q) exceeded maxDim=%d: %v (sizes=%v)", h, roi, maxDim, err, eng2K.seenSizes) + } + } + } + + // 3. 4K HiDPI (3840x2160) dark screen: must downscale <= 2600px (including action_bar) + // and map hit rects back inside the 4K ROI bounds. + dark4K := image.NewRGBA(image.Rect(0, 0, 3840, 2160)) + fillRect(dark4K, dark4K.Bounds(), color.RGBA{18, 18, 22, 255}) + eng4K := &maxDimCheckingEngine{maxDim: maxDim} + loc4K := NewLocalLocator(eng4K) + for _, roi := range []string{"menu_bar", "body", "action_bar", "terminal"} { + sc, err := loc4K.ScanROI(context.Background(), dark4K, roi, nil) + if err != nil { + t.Fatalf("4K ScanROI(%q) failed: %v (sizes=%v)", roi, err, eng4K.seenSizes) + } + if len(sc.Lines) != 1 || !sc.Lines[0].Rect.In(sc.ROI) { + t.Fatalf("4K ScanROI(%q) mapped rect %v outside ROI %v", roi, sc.Lines, sc.ROI) + } + } + if DetectDesktopReady([]ocr.Line{{Text: "Finder File Edit View Go Window Help 12:30"}}, "鍵盤設定輔助程式") { + t.Fatal("Traditional Chinese Keyboard Setup Assistant must block desktop-ready") + } + if DetectDesktopReady([]ocr.Line{{Text: "Finder File Edit View Go Window Help 12:30"}}, "キーボード設定アシスタント") { + t.Fatal("Japanese Keyboard Setup Assistant must block desktop-ready") + } +} + +func fillRect(img *image.RGBA, r image.Rectangle, c color.RGBA) { + r = r.Intersect(img.Bounds()) + for y := r.Min.Y; y < r.Max.Y; y++ { + for x := r.Min.X; x < r.Max.X; x++ { + img.SetRGBA(x, y, c) + } + } +} + +func TestDetectInputFieldNearLabelRejectsUniformBackgroundAndAcceptsFields(t *testing.T) { + labelRect := image.Rect(300, 300, 420, 326) + + // 1. Uniform light-mode window background must return ok=false (prevents blind clicks/TypeSecret). + blankLight := image.NewRGBA(image.Rect(0, 0, 1000, 600)) + fillRect(blankLight, blankLight.Bounds(), color.RGBA{236, 236, 236, 255}) + if _, _, ok := DetectInputFieldNearLabel(blankLight, labelRect); ok { + t.Fatal("uniform light background must NOT be detected as an input field") + } + + // 2. Uniform dark-mode window background must return ok=false. + blankDark := image.NewRGBA(image.Rect(0, 0, 1000, 600)) + fillRect(blankDark, blankDark.Bounds(), color.RGBA{32, 32, 34, 255}) + if _, _, ok := DetectInputFieldNearLabel(blankDark, labelRect); ok { + t.Fatal("uniform dark background must NOT be detected as an input field") + } + + // 3. Light-mode bordered white input box to the right of label -> ok=true. + lightForm := image.NewRGBA(image.Rect(0, 0, 1000, 600)) + fillRect(lightForm, lightForm.Bounds(), color.RGBA{236, 236, 236, 255}) + fillRect(lightForm, image.Rect(440, 299, 680, 327), color.RGBA{185, 185, 185, 255}) + fillRect(lightForm, image.Rect(441, 300, 679, 326), color.RGBA{255, 255, 255, 255}) + if pt, rect, ok := DetectInputFieldNearLabel(lightForm, labelRect); !ok || !pt.In(rect) { + t.Fatalf("expected light-mode input field ok=true, got ok=%v pt=%v rect=%v", ok, pt, rect) + } + + // 4. Dark-mode bordered input box to the right of label -> ok=true. + darkForm := image.NewRGBA(image.Rect(0, 0, 1000, 600)) + fillRect(darkForm, darkForm.Bounds(), color.RGBA{30, 30, 32, 255}) + fillRect(darkForm, image.Rect(440, 299, 680, 327), color.RGBA{92, 92, 96, 255}) + fillRect(darkForm, image.Rect(441, 300, 679, 326), color.RGBA{56, 56, 60, 255}) + if pt, rect, ok := DetectInputFieldNearLabel(darkForm, labelRect); !ok || !pt.In(rect) { + t.Fatalf("expected dark-mode input field ok=true, got ok=%v pt=%v rect=%v", ok, pt, rect) + } +} diff --git a/internal/macos/guest/autoinstall.go b/internal/macos/guest/autoinstall.go new file mode 100644 index 0000000..c6bb2f8 --- /dev/null +++ b/internal/macos/guest/autoinstall.go @@ -0,0 +1,156 @@ +package guest + +import ( + "context" + + "github.com/Nwflower/reims-go/internal/macos/autoinstall" + "github.com/Nwflower/reims-go/internal/macos/autoinstall/hostclient" + "github.com/Nwflower/reims-go/internal/plugin" + "github.com/Nwflower/reims-go/internal/plugin/builtin" +) + +// IDAutoInstall is the official built-in optional plugin providing local-vision +// macOS unattended initial installation. It is enabled by default and leaves +// zero residue when disabled. +const IDAutoInstall = "builtin.macos.autoinstall" + +// AutoInstallerIDMacOSLocal is the provider ID contributed by IDAutoInstall. +const AutoInstallerIDMacOSLocal = "macos-local" + +// AutoInstallDefinition describes the official built-in macOS auto-install plugin. +func AutoInstallDefinition(ver string, cb builtin.HostCallbacks, desired bool) plugin.PluginDef { + logPath := "" + if cb.PluginLogPath != nil { + logPath = cb.PluginLogPath(IDAutoInstall) + } + return plugin.PluginDef{ + Manifest: plugin.Manifest{ + Schema: 1, + ID: IDAutoInstall, + Version: ver, + Name: plugin.LocalizedText{ZhCN: "macOS 自动装机助手", EnUS: "macOS Auto-Install Assistant"}, + Description: plugin.LocalizedText{ + ZhCN: "纯本地视觉定位与声明式状态机驱动的 macOS 初次离线自动安装,截屏不出本机", + EnUS: "Offline macOS unattended initial installation driven by local OCR, vision probes, and a declarative state machine with zero cloud APIs", + }, + Publisher: "Reims-Go", + License: "Apache-2.0", + Icon: &plugin.PluginIcon{ + Tone: "teal", + SVG: ``, + }, + Platforms: []string{"windows-x64"}, + Requires: []plugin.ServiceRequirement{ + {Service: builtin.ServiceComputerUse, Version: "^1.0.0"}, + }, + Contributes: plugin.Contributes{ + AutoInstallers: []plugin.AutoInstallerContribution{{ + ID: AutoInstallerIDMacOSLocal, + Title: plugin.LocalizedText{ + ZhCN: "macOS 本地视觉自动安装", + EnUS: "macOS Local-Vision Auto-Install", + }, + Description: plugin.LocalizedText{ + ZhCN: "从恢复环境终端、跨重启安装等待、退出恢复并重启到设置助理全程自动推进至可用桌面", + EnUS: "Automates Recovery terminal install, cross-reboot monitoring, exit recovery, and Setup Assistant to usable desktop", + }, + GuestFamilies: []string{"macos"}, + RequiresOfflineInstaller: true, + SecretSetting: "account_password", + }}, + }, + Permissions: []string{ + "vm:read", + "log:read", + "vm:control", + "vm:screen", + "qmp:write", + "ui:notify", + "task:progress", + "fs:plugin_data", + "net:https://modelscope.cn", + "net:https://hf-mirror.com", + "net:https://github.com", + "net:https://objects.githubusercontent.com", + "net:https://release-assets.githubusercontent.com", + }, + Settings: &plugin.SettingsSchema{ + Title: plugin.LocalizedText{ZhCN: "macOS 自动装机", EnUS: "macOS Auto-Install"}, + Scope: "both", + Order: []string{"ocr_backend", "custom_ocr_mirror"}, + Properties: map[string]plugin.SettingProperty{ + "account_password": { + Type: "string", + Title: plugin.LocalizedText{ZhCN: "新建账户密码(装机专用)", EnUS: "Account password (install only)"}, + Description: plugin.LocalizedText{ + ZhCN: "由 Windows DPAPI 加密保护,仅经宿主密文键入账户表单,默认进桌面后自动清除", + EnUS: "Protected by Windows DPAPI, typed only through host secret injection, and cleared after desktop arrival by default", + }, + Secret: true, + Scope: "vm", + }, + "ocr_backend": { + Type: "string", + Title: plugin.LocalizedText{ZhCN: "本地 OCR 后端", EnUS: "Local OCR backend"}, + Description: plugin.LocalizedText{ + ZhCN: "默认优先使用系统内置 Windows OCR,缺少语言包时可切换或下载 RapidOCR ONNX", + EnUS: "Uses built-in Windows OCR by default, with optional RapidOCR ONNX fallback when a language pack is missing", + }, + Default: "auto", + Enum: []string{"auto", "winocr", "rapidocr"}, + EnumLabels: []plugin.LocalizedText{ + {ZhCN: "自动选择", EnUS: "Automatic"}, + {ZhCN: "Windows 内置 OCR", EnUS: "Windows OCR"}, + {ZhCN: "RapidOCR ONNX", EnUS: "RapidOCR ONNX"}, + }, + Scope: "app", + Effect: "immediate", + }, + "custom_ocr_mirror": { + Type: "string", + Title: plugin.LocalizedText{ZhCN: "RapidOCR 自定义 HTTPS 镜像前缀", EnUS: "Custom HTTPS mirror prefix for RapidOCR"}, + Description: plugin.LocalizedText{ + ZhCN: "可选,内置镜像不可达时用于下载 RapidOCR 备选模型,需经宿主确认并校验 SHA-256", + EnUS: "Optional HTTPS mirror prefix used to download RapidOCR fallback models after host confirmation and SHA-256 verification", + }, + Scope: "app", + Effect: "immediate", + }, + }, + }, + DefaultEnabled: true, + }, + Source: plugin.SourceBuiltin, + Trust: plugin.TrustOfficial, + LogPath: logPath, + Desired: desired, + Activate: func(_ context.Context, sc *plugin.Scope) error { + dataDir := "" + if cb.PluginDataDir != nil { + dataDir = cb.PluginDataDir(IDAutoInstall) + } + var callHost hostclient.CallHostFunc + if cb.CallHostAPI != nil { + callHost = func(ctx context.Context, method string, params any, out any) error { + return cb.CallHostAPI(ctx, IDAutoInstall, method, params, out) + } + } + var getSetting func(vmName, key string) (any, bool) + if cb.GetSetting != nil { + getSetting = func(vmName, key string) (any, bool) { + return cb.GetSetting(IDAutoInstall, vmName, key) + } + } + svc := autoinstall.NewService(autoinstall.ServiceOptions{ + DataDir: dataDir, + CallHost: callHost, + GetSetting: getSetting, + }) + // LIFO dispose order: unregister endpoint first so no new calls arrive, + // then stop and drain every running worker cleanly. + sc.OnDispose(svc.StopAll) + sc.Registry().RegisterInProcessEndpoint(sc, svc) + return nil + }, + } +} diff --git a/internal/macos/guest/guest_test.go b/internal/macos/guest/guest_test.go index 6b3e9f9..d822e3f 100644 --- a/internal/macos/guest/guest_test.go +++ b/internal/macos/guest/guest_test.go @@ -218,3 +218,75 @@ func TestBuiltinMacOSImagesPluginLifecycle(t *testing.T) { t.Fatalf("expected macOS image source restored after re-enable, got %+v", got) } } + +func TestBuiltinMacOSAutoInstallPluginLifecycleAndDependencyCascade(t *testing.T) { + reg := plugin.NewRegistry(nil) + cb := testCallbacks(t, nil) + cb.PluginDataDir = func(string) string { return t.TempDir() } + if err := builtin.RegisterAll(reg, cb, nil); err != nil { + t.Fatal(err) + } + if err := Register(reg, cb, nil); err != nil { + t.Fatal(err) + } + reg.Reconcile(context.Background()) + + info, ok := reg.Info(IDAutoInstall) + if !ok { + t.Fatalf("missing %s in registry", IDAutoInstall) + } + if info.Source != plugin.SourceBuiltin || info.Trust != plugin.TrustOfficial || info.System || info.Removable { + t.Fatalf("unexpected builtin metadata: %+v", info) + } + if !info.Enabled || info.State != plugin.StateActive { + t.Fatalf("expected builtin auto-install active by default, got enabled=%v state=%s", info.Enabled, info.State) + } + providers := reg.AutoInstallersForFamily("macos") + if len(providers) != 1 || providers[0].PluginID != IDAutoInstall || providers[0].ID != AutoInstallerIDMacOSLocal { + t.Fatalf("unexpected macOS auto-installers: %+v", providers) + } + if reg.InProcessEndpoint(IDAutoInstall) == nil { + t.Fatal("expected active in-process endpoint for builtin auto-install") + } + + // Disabling leaves zero residue. + if err := reg.SetDesired(context.Background(), IDAutoInstall, false); err != nil { + t.Fatal(err) + } + if reg.IsActive(IDAutoInstall) { + t.Fatal("builtin auto-install should be inactive after disable") + } + if got := reg.AutoInstallersForFamily("macos"); len(got) != 0 { + t.Fatalf("expected zero auto-installers after disable, got %+v", got) + } + if reg.InProcessEndpoint(IDAutoInstall) != nil { + t.Fatal("in-process endpoint remained after disable") + } + + // Re-enabling restores contribution & endpoint. + if err := reg.SetDesired(context.Background(), IDAutoInstall, true); err != nil { + t.Fatal(err) + } + if !reg.IsActive(IDAutoInstall) || reg.InProcessEndpoint(IDAutoInstall) == nil { + t.Fatal("builtin auto-install did not reactivate cleanly") + } + + // Disabling builtin.computer-use cascades builtin.macos.autoinstall to pending. + if err := reg.SetDesired(context.Background(), builtin.IDComputerUse, false); err != nil { + t.Fatal(err) + } + if reg.StateOf(IDAutoInstall) != plugin.StatePending { + t.Fatalf("expected state=pending when computer-use is disabled, got %s", reg.StateOf(IDAutoInstall)) + } + if got := reg.AutoInstallersForFamily("macos"); len(got) != 0 { + t.Fatalf("expected zero auto-installers while computer-use is off, got %+v", got) + } + + // Re-enabling builtin.computer-use automatically reactivates builtin.macos.autoinstall. + if err := reg.SetDesired(context.Background(), builtin.IDComputerUse, true); err != nil { + t.Fatal(err) + } + if !reg.IsActive(IDAutoInstall) || len(reg.AutoInstallersForFamily("macos")) != 1 { + t.Fatalf("expected builtin auto-install to auto-recover when computer-use returns, state=%s", reg.StateOf(IDAutoInstall)) + } +} diff --git a/internal/macos/guest/register.go b/internal/macos/guest/register.go index fe7c7a0..95c2652 100644 --- a/internal/macos/guest/register.go +++ b/internal/macos/guest/register.go @@ -19,7 +19,8 @@ func VMInventories() []driver.VMInventory { } } -// Register adds the built-in Reims vGPU guest driver and image source. +// Register adds the built-in Reims vGPU guest driver, image source, and +// local-vision auto-installer to reg. func Register(reg *plugin.Registry, cb builtin.HostCallbacks, desiredFn func(string, bool) bool) error { if desiredFn == nil { desiredFn = func(_ string, def bool) bool { return def } @@ -28,7 +29,10 @@ func Register(reg *plugin.Registry, cb builtin.HostCallbacks, desiredFn func(str if err := reg.Register(Definition(ver, cb, desiredFn(ID, true))); err != nil { return err } - return reg.Register(ImagesDefinition(ver, desiredFn(IDImages, true))) + if err := reg.Register(ImagesDefinition(ver, desiredFn(IDImages, true))); err != nil { + return err + } + return reg.Register(AutoInstallDefinition(ver, cb, desiredFn(IDAutoInstall, true))) } // RegisterForHost selects the local backend without losing the other backend's diff --git a/internal/macos/installer/hfs_image.go b/internal/macos/installer/hfs_image.go index 711817e..e474eff 100644 --- a/internal/macos/installer/hfs_image.go +++ b/internal/macos/installer/hfs_image.go @@ -707,24 +707,47 @@ erase_mode=0 erase_disk="" target="" -case "${1:-}" in - --erase) - erase_mode=1 - erase_disk=${2:-} - case "$erase_disk" in - disk*) erase_disk="/dev/$erase_disk" ;; - esac - ;; - -h|--help) - echo "Usage: sh /Volumes/REIMSHELP/install.sh [TARGET_VOLUME | --erase [/dev/diskN]]" - exit 0 - ;; - "") - ;; - *) - target=${1%/} - ;; -esac +no_provision=0 +while [ $# -gt 0 ]; do + case "$1" in + --no-provision) + no_provision=1 + shift + ;; + --erase) + erase_mode=1 + shift + if [ $# -gt 0 ]; then + case "$1" in + -*) ;; + *) + erase_disk=$1 + case "$erase_disk" in + disk*) erase_disk="/dev/$erase_disk" ;; + esac + shift + ;; + esac + fi + ;; + -h|--help) + echo "Usage: sh /Volumes/REIMSHELP/install.sh [TARGET_VOLUME | --erase [/dev/diskN]] [--no-provision]" + exit 0 + ;; + "") + shift + ;; + -*) + echo "Unknown option: $1" >&2 + echo "Usage: sh /Volumes/REIMSHELP/install.sh [TARGET_VOLUME | --erase [/dev/diskN]] [--no-provision]" >&2 + exit 1 + ;; + *) + target=${1%/} + shift + ;; + esac +done if [ "$erase_mode" -eq 1 ]; then if ! command -v diskutil >/dev/null 2>&1; then @@ -874,6 +897,14 @@ if [ ! -f "$shared/SharedSupport.dmg" ]; then fi chmod -R 755 "$app" +prov_pkg="/Volumes/REIMSPROV/provision.pkg" +if [ "$no_provision" -eq 0 ] && [ -f "$prov_pkg" ]; then + echo "Starting $app with pre-provisioned first-boot package (--installpackage); the VM will restart automatically when ready..." + if "$app/Contents/Resources/startosinstall" --agreetolicense --volume "$target" --installpackage "$prov_pkg"; then + exit 0 + fi + echo "REIMS_INSTALLPKG_UNSUPPORTED: --installpackage returned non-zero; falling back to plain startosinstall..." +fi echo "Starting $app; the VM will restart automatically when ready..." exec "$app/Contents/Resources/startosinstall" --agreetolicense --volume "$target" `) @@ -887,7 +918,7 @@ func EnsureOfflineHelperImage(xdgCacheDir, offlineImgPath string) (string, error if err != nil { return "", fmt.Errorf("stat offline installer: %w", err) } - sum := sha256.Sum256([]byte(fmt.Sprintf("%s|%d|%d|v3", filepath.Base(offlineImgPath), info.Size(), info.ModTime().UnixNano()))) + sum := sha256.Sum256([]byte(fmt.Sprintf("%s|%d|%d|v4", filepath.Base(offlineImgPath), info.Size(), info.ModTime().UnixNano()))) key := hex.EncodeToString(sum[:8]) helperDir := filepath.Join(xdgCacheDir, "reims-go", "offline-helpers") helperPath := filepath.Join(helperDir, fmt.Sprintf("reims-helper-%s.img", key)) diff --git a/internal/macos/installer/provision_pkg.go b/internal/macos/installer/provision_pkg.go new file mode 100644 index 0000000..a8d5f2f --- /dev/null +++ b/internal/macos/installer/provision_pkg.go @@ -0,0 +1,1035 @@ +package installer + +import ( + "bytes" + "compress/gzip" + "compress/zlib" + "crypto/pbkdf2" + "crypto/rand" + "crypto/sha1" + "crypto/sha512" + "encoding/base64" + "encoding/binary" + "encoding/hex" + "encoding/xml" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "regexp" + "strings" + "time" +) + +const ( + // ProvisionVolumeName is the HFS+ volume label mounted at /Volumes/REIMSPROV. + ProvisionVolumeName = "REIMSPROV" + // ProvisionImageFilename is the per-VM read-only provisioning disk stored + // inside the VM directory and securely wiped on finish_install / DeleteVM. + ProvisionImageFilename = ".reims-go-provision.img" + provisionStagedMarkerFilename = ".reims-go-provision-staged" + provisionWipePendingFilename = ".reims-go-provision-wipe" + provisionReadyMarkerFilename = ".reims-go-provision-ready" + // ProvisionSerialReadyMarker is written to the serial console on first boot + // of the installed macOS system by a self-deleting one-shot LaunchDaemon. + ProvisionSerialReadyMarker = "REIMS_PROVISION_BOOT_OK" + // InstallPkgUnsupportedMarker is emitted by REIMSHELP/install.sh when + // startosinstall rejects --installpackage and falls back to plain install. + InstallPkgUnsupportedMarker = "REIMS_INSTALLPKG_UNSUPPORTED" + + provisionPBKDF2Iterations = 40000 + provisionPBKDF2SaltLen = 32 + provisionPBKDF2KeyLen = 128 + provisionUserUID = 501 + provisionUserGID = 20 +) + +var ( + provisionAccountRE = regexp.MustCompile(`^[a-z][a-z0-9_-]{0,31}$`) +) + +// ProvisionGuestToolFile holds one Guest Tools file bundled into REIMSPROV and +// self-contained inside provision.pkg's Scripts archive so first-boot login +// starts Guest Tools without requiring a manual REIMSTOOLS mount. +type ProvisionGuestToolFile struct { + Name string + Mode uint32 + Data []byte +} + +// ProvisionConfig describes the user-supplied offline first-boot provisioning +// settings. Plaintext Password is only used in memory to derive the macOS +// SALTED-SHA512-PBKDF2 ShadowHashData blob and is never written to disk. +type ProvisionConfig struct { + FullName string `json:"full_name"` + AccountName string `json:"account_name"` + Password string `json:"password"` + Appearance string `json:"appearance,omitempty"` // "auto" | "light" | "dark" + SLAAccepted bool `json:"sla_accepted"` + GuestTools []ProvisionGuestToolFile `json:"-"` +} + +// ValidateProvisionConfig checks ASCII/safety constraints before building REIMSPROV. +func ValidateProvisionConfig(cfg *ProvisionConfig) error { + if cfg == nil { + return errors.New("provision config is nil") + } + cfg.FullName = strings.TrimSpace(cfg.FullName) + cfg.AccountName = strings.ToLower(strings.TrimSpace(cfg.AccountName)) + cfg.Appearance = strings.ToLower(strings.TrimSpace(cfg.Appearance)) + if cfg.Appearance == "" { + cfg.Appearance = "auto" + } + if !cfg.SLAAccepted { + return errors.New("Apple software license agreement confirmation is required") + } + if cfg.FullName == "" || !isPrintableASCII(cfg.FullName) { + return errors.New("full_name must be non-empty printable ASCII") + } + if !provisionAccountRE.MatchString(cfg.AccountName) { + return errors.New("account_name must match ^[a-z][a-z0-9_-]{0,31}$") + } + if len(cfg.Password) < 4 || !isPrintableASCII(cfg.Password) { + return errors.New("password must be at least 4 printable ASCII characters") + } + switch cfg.Appearance { + case "auto", "light", "dark": + default: + return fmt.Errorf("invalid appearance %q (want auto, light, or dark)", cfg.Appearance) + } + return nil +} + +func isPrintableASCII(s string) bool { + for i := 0; i < len(s); i++ { + if s[i] < 0x20 || s[i] > 0x7E { + return false + } + } + return true +} + +// ProvisionImagePath returns the per-VM REIMSPROV image path inside vmDir. +func ProvisionImagePath(vmDir string) string { + if strings.TrimSpace(vmDir) == "" { + return "" + } + return filepath.Join(vmDir, ProvisionImageFilename) +} + +// HasProvisionImage reports whether vmDir currently holds a non-empty REIMSPROV image. +func HasProvisionImage(vmDir string) bool { + p := ProvisionImagePath(vmDir) + if p == "" { + return false + } + st, err := os.Stat(p) + return err == nil && !st.IsDir() && st.Size() > 0 +} + +func provisionMarkerExists(vmDir, name string) bool { + if strings.TrimSpace(vmDir) == "" { + return false + } + st, err := os.Stat(filepath.Join(vmDir, name)) + return err == nil && !st.IsDir() +} + +func writeProvisionMarker(vmDir, name string) { + if strings.TrimSpace(vmDir) == "" { + return + } + _ = os.WriteFile(filepath.Join(vmDir, name), []byte("1\n"), 0o600) +} + +func removeProvisionMarker(vmDir, name string) { + if strings.TrimSpace(vmDir) == "" { + return + } + _ = os.Remove(filepath.Join(vmDir, name)) +} + +// HasProvisionStagedMarker reports whether a freshly staged REIMSPROV image is +// waiting for its first boot (even when the VM has no installer or recovery +// marker yet). +func HasProvisionStagedMarker(vmDir string) bool { + return provisionMarkerExists(vmDir, provisionStagedMarkerFilename) +} + +// ClearProvisionStagedMarker consumes the one-shot staged marker once REIMSPROV +// is attached to a non-installer/non-recovery boot or cleared. +func ClearProvisionStagedMarker(vmDir string) { + removeProvisionMarker(vmDir, provisionStagedMarkerFilename) +} + +// HasProvisionWipePending reports whether a previous SecureRemoveProvisionImage +// could not delete the image (for example because QEMU still held it open on +// Windows) and the next cold start must securely wipe it without re-attaching. +func HasProvisionWipePending(vmDir string) bool { + return provisionMarkerExists(vmDir, provisionWipePendingFilename) +} + +// WriteProvisionReadyMarker records that REIMS_PROVISION_BOOT_OK was observed +// on the serial console so the status persists across reboots and app restarts +// until finish_install completes. +func WriteProvisionReadyMarker(vmDir string) { + writeProvisionMarker(vmDir, provisionReadyMarkerFilename) +} + +// HasProvisionReadyMarker reports whether vmDir has a persisted provision-ready marker. +func HasProvisionReadyMarker(vmDir string) bool { + return provisionMarkerExists(vmDir, provisionReadyMarkerFilename) +} + +// ClearProvisionReadyMarker removes any persisted provision-ready marker. +func ClearProvisionReadyMarker(vmDir string) { + removeProvisionMarker(vmDir, provisionReadyMarkerFilename) +} + +// SecureRemoveProvisionImage overwrites /.reims-go-provision.img with +// zeros and removes it so password hashes and per-VM tokens do not linger after +// finish_install or VM deletion. If removal fails (for example while QEMU holds +// the file open on Windows), a pending-wipe marker is written so the next cold +// start retries wiping and never re-attaches the image. +func SecureRemoveProvisionImage(vmDir string) error { + ClearProvisionStagedMarker(vmDir) + ClearProvisionReadyMarker(vmDir) + p := ProvisionImagePath(vmDir) + if p == "" { + return nil + } + st, err := os.Stat(p) + if err != nil { + if os.IsNotExist(err) { + removeProvisionMarker(vmDir, provisionWipePendingFilename) + return nil + } + writeProvisionMarker(vmDir, provisionWipePendingFilename) + return err + } + if !st.IsDir() && st.Size() > 0 { + _ = os.Chmod(p, 0o600) + f, err := os.OpenFile(p, os.O_WRONLY, 0) + if err != nil { + writeProvisionMarker(vmDir, provisionWipePendingFilename) + return fmt.Errorf("open provisioning image for secure wipe: %w", err) + } + zeros := make([]byte, 64*1024) + rem := st.Size() + var wipeErr error + for rem > 0 { + n := int64(len(zeros)) + if rem < n { + n = rem + } + written, werr := f.Write(zeros[:n]) + if werr != nil { + wipeErr = fmt.Errorf("overwrite provisioning image: %w", werr) + break + } + rem -= int64(written) + } + if wipeErr == nil { + if serr := f.Sync(); serr != nil { + wipeErr = fmt.Errorf("sync wiped provisioning image: %w", serr) + } + } + if cerr := f.Close(); cerr != nil && wipeErr == nil { + wipeErr = fmt.Errorf("close wiped provisioning image: %w", cerr) + } + if wipeErr != nil { + // Refuse to unlink an unwiped credential image; mark wipe-pending + // so the next cold start retries full overwrite before deletion. + writeProvisionMarker(vmDir, provisionWipePendingFilename) + return wipeErr + } + } + if err := os.Remove(p); err != nil && !os.IsNotExist(err) { + writeProvisionMarker(vmDir, provisionWipePendingFilename) + return err + } + removeProvisionMarker(vmDir, provisionWipePendingFilename) + return nil +} + +// BuildProvisionDiskImage validates cfg, derives the macOS SALTED-SHA512-PBKDF2 +// ShadowHashData binary plist in memory (never persisting plaintext password), +// builds a pure-Go XAR Distribution flat package (`provision.pkg`) and an +// equivalent Recovery fallback script (`provision-offline.sh`), and writes a +// read-only HFS+ disk image ("REIMSPROV") to /.reims-go-provision.img. +func BuildProvisionDiskImage(vmDir string, cfg ProvisionConfig) (string, error) { + if strings.TrimSpace(vmDir) == "" { + return "", errors.New("VM directory is required") + } + if err := ValidateProvisionConfig(&cfg); err != nil { + return "", err + } + if err := os.MkdirAll(vmDir, 0o755); err != nil { + return "", err + } + + shadowBPlist, err := deriveMacOSShadowHashBPlist(cfg.Password, provisionPBKDF2Iterations) + if err != nil { + return "", err + } + shadowB64 := base64.StdEncoding.EncodeToString(shadowBPlist) + userUUID, err := newUpperUUIDv4() + if err != nil { + return "", err + } + + postinstall := renderProvisionScript(cfg, shadowB64, userUUID, true) + offlineScript := renderProvisionScript(cfg, shadowB64, userUUID, false) + + pkgBytes, err := buildDistributionPkg(postinstall, cfg.GuestTools) + if err != nil { + return "", fmt.Errorf("build provision.pkg: %w", err) + } + + files := []HFSFile{ + { + Name: "provision.pkg", + Mode: 0o100644, + Size: int64(len(pkgBytes)), + Open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(pkgBytes)), nil }, + }, + { + Name: "provision-offline.sh", + Mode: 0o100755, + Size: int64(len(offlineScript)), + Open: func() (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(offlineScript)), nil }, + }, + } + for _, gt := range cfg.GuestTools { + if strings.TrimSpace(gt.Name) == "" || len(gt.Data) == 0 { + continue + } + name := "gt-" + filepath.Base(gt.Name) + data := append([]byte(nil), gt.Data...) + mode := uint16(gt.Mode) + if mode == 0 { + mode = 0o100644 + } + files = append(files, HFSFile{ + Name: name, + Mode: mode, + Size: int64(len(data)), + Open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(data)), nil }, + }) + } + + outPath := ProvisionImagePath(vmDir) + if err := BuildHFSPlusDiskImage(outPath, ProvisionVolumeName, files); err != nil { + return "", fmt.Errorf("build REIMSPROV image: %w", err) + } + removeProvisionMarker(vmDir, provisionWipePendingFilename) + removeProvisionMarker(vmDir, provisionReadyMarkerFilename) + writeProvisionMarker(vmDir, provisionStagedMarkerFilename) + return outPath, nil +} + +// deriveMacOSShadowHashBPlist derives Apple's SALTED-SHA512-PBKDF2 ShadowHashData +// binary property list (bplist00). Plaintext password is only used in memory. +func deriveMacOSShadowHashBPlist(password string, iterations int) ([]byte, error) { + salt := make([]byte, provisionPBKDF2SaltLen) + if _, err := rand.Read(salt); err != nil { + return nil, fmt.Errorf("generate PBKDF2 salt: %w", err) + } + entropy, err := pbkdf2.Key(sha512.New, password, salt, iterations, provisionPBKDF2KeyLen) + if err != nil { + return nil, fmt.Errorf("derive PBKDF2-SHA512 key: %w", err) + } + return encodeShadowHashBPlist(entropy, salt, iterations) +} + +// encodeShadowHashBPlist encodes the exact Apple bplist00 binary property list +// for {"SALTED-SHA512-PBKDF2": {"entropy": , "iterations": , "salt": }}. +func encodeShadowHashBPlist(entropy, salt []byte, iterations int) ([]byte, error) { + if len(entropy) != provisionPBKDF2KeyLen { + return nil, fmt.Errorf("invalid entropy length %d (want %d)", len(entropy), provisionPBKDF2KeyLen) + } + if len(salt) != provisionPBKDF2SaltLen { + return nil, fmt.Errorf("invalid salt length %d (want %d)", len(salt), provisionPBKDF2SaltLen) + } + if iterations <= 0 || iterations > 0x7fffffff { + return nil, fmt.Errorf("invalid PBKDF2 iterations %d", iterations) + } + + var buf bytes.Buffer + buf.WriteString("bplist00") + + var offsets [9]uint16 + record := func(idx int) { + offsets[idx] = uint16(buf.Len()) + } + writeCounted := func(base byte, n int) { + if n < 15 { + buf.WriteByte(base | byte(n)) + return + } + buf.WriteByte(base | 0x0F) + switch { + case n <= 0xFF: + buf.WriteByte(0x10) + buf.WriteByte(byte(n)) + case n <= 0xFFFF: + buf.WriteByte(0x11) + var b [2]byte + binary.BigEndian.PutUint16(b[:], uint16(n)) + buf.Write(b[:]) + default: + buf.WriteByte(0x12) + var b [4]byte + binary.BigEndian.PutUint32(b[:], uint32(n)) + buf.Write(b[:]) + } + } + writeASCII := func(idx int, s string) { + record(idx) + writeCounted(0x50, len(s)) + buf.WriteString(s) + } + writeData := func(idx int, d []byte) { + record(idx) + writeCounted(0x40, len(d)) + buf.Write(d) + } + + // Object 0: root dict { obj[1]: obj[2] } + record(0) + buf.Write([]byte{0xD1, 1, 2}) + + // Object 1: "SALTED-SHA512-PBKDF2" + writeASCII(1, "SALTED-SHA512-PBKDF2") + + // Object 2: inner dict { obj[3]: obj[4], obj[5]: obj[6], obj[7]: obj[8] } + record(2) + buf.Write([]byte{0xD3, 3, 5, 7, 4, 6, 8}) + + // Object 3 & 4: "entropy" -> 128-byte data + writeASCII(3, "entropy") + writeData(4, entropy) + + // Object 5 & 6: "iterations" -> 4-byte unsigned big-endian int + writeASCII(5, "iterations") + record(6) + buf.WriteByte(0x12) + var iterBuf [4]byte + binary.BigEndian.PutUint32(iterBuf[:], uint32(iterations)) + buf.Write(iterBuf[:]) + + // Object 7 & 8: "salt" -> 32-byte data + writeASCII(7, "salt") + writeData(8, salt) + + offsetTableOffset := uint64(buf.Len()) + for _, off := range offsets { + var ob [2]byte + binary.BigEndian.PutUint16(ob[:], off) + buf.Write(ob[:]) + } + + // 32-byte bplist00 trailer + var trailer [32]byte + trailer[6] = 2 // offsetIntSize = 2 bytes + trailer[7] = 1 // objectRefSize = 1 byte + binary.BigEndian.PutUint64(trailer[8:16], uint64(len(offsets))) + binary.BigEndian.PutUint64(trailer[16:24], 0) // topObject = 0 + binary.BigEndian.PutUint64(trailer[24:32], offsetTableOffset) + buf.Write(trailer[:]) + return buf.Bytes(), nil +} + +func newUpperUUIDv4() (string, error) { + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + return "", err + } + b[6] = (b[6] & 0x0f) | 0x40 + b[8] = (b[8] & 0x3f) | 0x80 + return strings.ToUpper(fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", + b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])), nil +} + +func shSingleQuote(s string) string { + return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" +} + +func xmlEscapeText(s string) string { + var buf bytes.Buffer + _ = xml.EscapeText(&buf, []byte(s)) + return buf.String() +} + +// renderLocalUserPlistXML builds the Apple dslocal user plist XML directly in +// Go so special printable ASCII characters in FullName (such as $, `, \, &) are +// safely XML-escaped and never subject to shell expansion. +func renderLocalUserPlistXML(cfg ProvisionConfig, shadowB64, userUUID string) string { + return fmt.Sprintf(` + + + + ShadowHashData + + %s + + authentication_authority + + ;ShadowHash;HASHLIST:<SALTED-SHA512-PBKDF2> + + generateduid + + %s + + gid + + %d + + home + + /Users/%s + + name + + %s + + passwd + + ******** + + realname + + %s + + shell + + /bin/zsh + + uid + + %d + + + +`, shadowB64, userUUID, provisionUserGID, cfg.AccountName, cfg.AccountName, xmlEscapeText(cfg.FullName), provisionUserUID) +} + +// renderProvisionScript creates an original POSIX shell script used either as +// the `postinstall` inside provision.pkg (isPostinstall=true, executed under +// macOS bootinstalld on live `/`) or as the standalone Recovery fallback script +// `provision-offline.sh` (isPostinstall=false, executed against an offline Data volume). +func renderProvisionScript(cfg ProvisionConfig, shadowB64, userUUID string, isPostinstall bool) string { + var b strings.Builder + b.WriteString("#!/bin/sh\n") + b.WriteString("set -eu\n\n") + if isPostinstall { + b.WriteString("TARGET_ARG=\"${3:-/}\"\n") + b.WriteString("SCRIPT_DIR=\"$(CDPATH= cd -- \"$(dirname -- \"$0\")\" && pwd)\"\n") + b.WriteString("GT_SRC=\"$SCRIPT_DIR/guest-tools\"\n") + b.WriteString("GT_PREFIX=\"\"\n") + } else { + b.WriteString("TARGET_ARG=\"${1:-}\"\n") + b.WriteString("SCRIPT_DIR=\"$(CDPATH= cd -- \"$(dirname -- \"$0\")\" && pwd)\"\n") + b.WriteString("GT_SRC=\"$SCRIPT_DIR\"\n") + b.WriteString("GT_PREFIX=\"gt-\"\n") + } + + fmt.Fprintf(&b, "ACCOUNT=%s\n", shSingleQuote(cfg.AccountName)) + fmt.Fprintf(&b, "FULL_NAME=%s\n", shSingleQuote(cfg.FullName)) + fmt.Fprintf(&b, "APPEARANCE=%s\n", shSingleQuote(cfg.Appearance)) + fmt.Fprintf(&b, "USER_UID=%d\n", provisionUserUID) + fmt.Fprintf(&b, "USER_GID=%d\n", provisionUserGID) + fmt.Fprintf(&b, "USER_UUID=%s\n", shSingleQuote(userUUID)) + fmt.Fprintf(&b, "SHADOW_B64=%s\n", shSingleQuote(shadowB64)) + fmt.Fprintf(&b, "SERIAL_MARKER=%s\n\n", shSingleQuote(ProvisionSerialReadyMarker)) + + userPlistXML := renderLocalUserPlistXML(cfg, shadowB64, userUUID) + + liveRootGuard := "" + if isPostinstall { + liveRootGuard = ` # Only allow live "/" when running inside a booted macOS system (bootinstalld), + # never inside macOS Recovery / Installer Base System (which contains /System/Installation/CDIS). + if [ "$cand" = "/" ] && [ ! -d "/System/Installation/CDIS" ] && [ -d "/private/var/db/dslocal/nodes/Default" ]; then + echo "" + return 0 + fi +` + } + + b.WriteString(`log() { echo "reims-provision: $*"; } + +# Locate the writable macOS Data volume without touching the Sealed System Volume. +resolve_data_root() { + cand="$1" + if [ -n "$cand" ]; then +` + liveRootGuard + ` if [ -d "$cand/System/Volumes/Data/private/var/db/dslocal/nodes/Default" ]; then + echo "$cand/System/Volumes/Data" + return 0 + fi + if [ -d "${cand} - Data/private/var/db/dslocal/nodes/Default" ]; then + echo "${cand} - Data" + return 0 + fi + if [ -d "$cand/private/var/db/dslocal/nodes/Default" ]; then + echo "$cand" + return 0 + fi + fi + + for v in /Volumes/*; do + [ -d "$v" ] || continue + case "$v" in + */Installer|*/REIMSHELP|*/REIMSPROV|*/REIMSTOOLS|*/RECOVERY|*/OPENCORE|*/"macOS Base System"|*/"Image Volume") + continue ;; + esac + if diskutil info "$v" 2>/dev/null | grep -Eq 'APFS Volume Role:[[:space:]]*Data'; then + if [ -d "$v/private/var/db/dslocal/nodes/Default" ]; then + echo "$v" + return 0 + fi + fi + done + + for v in /Volumes/*; do + [ -d "$v/private/var/db/dslocal/nodes/Default" ] || continue + case "$v" in + */Installer|*/REIMSHELP|*/REIMSPROV|*/REIMSTOOLS|*/RECOVERY|*/OPENCORE|*/"macOS Base System"|*/"Image Volume") + continue ;; + esac + echo "$v" + return 0 + done + + if command -v diskutil >/dev/null 2>&1; then + for dev in $(diskutil apfs list 2>/dev/null | awk '/APFS Volume Disk \(Role\):/ && /Data/ {print $6}'); do + diskutil mount "$dev" >/dev/null 2>&1 || true + mp=$(diskutil info "$dev" 2>/dev/null | awk -F':[[:space:]]*' '/Mount Point:/ {print $2; exit}') + if [ -n "$mp" ] && [ -d "$mp/private/var/db/dslocal/nodes/Default" ]; then + echo "$mp" + return 0 + fi + done + fi + return 1 +} + +D=$(resolve_data_root "$TARGET_ARG" || true) +DS="$D/private/var/db/dslocal/nodes/Default" +if [ ! -d "$DS" ] || { [ -z "$D" ] && [ -d "/System/Installation/CDIS" ]; }; then + log "REIMS_PROVISION_TARGET_FAILED: could not locate target Data volume dslocal node" >&2 + exit 1 +fi +log "target data root: ${D:-/}" + +# 1. Create local administrator account using SALTED-SHA512-PBKDF2 ShadowHashData +# only (zero plaintext password on disk): +# - Live booted macOS (bootinstalld, D=""): talk to opendirectoryd via Apple's +# native OpenDirectory.framework (JXA NSData) + dseditgroup, which works cleanly +# with SIP enabled where /private/var/db/dslocal is protected. +# - Offline Recovery (D="/Volumes/..."): write the dslocal binary plist and +# admin.plist directly on the target APFS Data volume. +if [ -z "$D" ]; then + REIMS_ACCOUNT="$ACCOUNT" \ + REIMS_FULL_NAME="$FULL_NAME" \ + REIMS_USER_UID="$USER_UID" \ + REIMS_USER_GID="$USER_GID" \ + REIMS_USER_UUID="$USER_UUID" \ + REIMS_SHADOW_B64="$SHADOW_B64" \ + /usr/bin/osascript -l JavaScript <<'REIMS_OD_JXA_EOF' +ObjC.import('Foundation'); +ObjC.import('OpenDirectory'); +var env = $.NSProcessInfo.processInfo.environment; +function envStr(k) { return ObjC.unwrap(env.objectForKey(k)); } +var acct = envStr('REIMS_ACCOUNT'); +var full = envStr('REIMS_FULL_NAME'); +var uid = envStr('REIMS_USER_UID'); +var gid = envStr('REIMS_USER_GID'); +var uuid = envStr('REIMS_USER_UUID'); +var shadowB64 = envStr('REIMS_SHADOW_B64'); + +var err = Ref(); +var node = $.ODNode.nodeWithSessionNameError($.ODSession.defaultSession, '/Local/Default', err); +if (node.isNil()) { + throw new Error('ODNode open failed: ' + ObjC.unwrap(err[0].localizedDescription)); +} +var existing = node.recordWithRecordTypeNameAttributesError('dsRecTypeStandard:Users', acct, $(), $()); +if (!existing.isNil()) { + console.log('reims-provision: live account ' + acct + ' already exists; preserving'); +} else { + var shadowData = $.NSData.alloc.initWithBase64EncodedStringOptions(shadowB64, 0); + if (shadowData.isNil()) { + throw new Error('decode ShadowHashData base64 failed'); + } + var attrs = $.NSMutableDictionary.dictionary; + function putStr(k, v) { attrs.setObjectForKey($.NSArray.arrayWithObject($(v)), $(k)); } + putStr('dsAttrTypeStandard:UniqueID', uid); + putStr('dsAttrTypeStandard:PrimaryGroupID', gid); + putStr('dsAttrTypeStandard:RealName', full); + putStr('dsAttrTypeStandard:NFSHomeDirectory', '/Users/' + acct); + putStr('dsAttrTypeStandard:UserShell', '/bin/zsh'); + putStr('dsAttrTypeStandard:GeneratedUID', uuid); + putStr('dsAttrTypeStandard:Password', '********'); + putStr('dsAttrTypeStandard:AuthenticationAuthority', ';ShadowHash;HASHLIST:'); + attrs.setObjectForKey($.NSArray.arrayWithObject(shadowData), $('dsAttrTypeNative:ShadowHashData')); + + var createErr = Ref(); + var rec = node.createRecordWithRecordTypeNameAttributesError('dsRecTypeStandard:Users', acct, attrs, createErr); + if (rec.isNil()) { + throw new Error('ODNode createRecord failed: ' + ObjC.unwrap(createErr[0].localizedDescription)); + } + console.log('reims-provision: created live OpenDirectory user ' + acct); +} +REIMS_OD_JXA_EOF + if [ -x /usr/sbin/dseditgroup ]; then + /usr/sbin/dseditgroup -o edit -a "$ACCOUNT" -t user admin + else + /usr/bin/dscl . -append /Groups/admin GroupMembership "$ACCOUNT" + fi + log "added live account $ACCOUNT to admin group" +else + USER_PLIST="$DS/users/$ACCOUNT.plist" + mkdir -p "$DS/users" + if [ ! -f "$USER_PLIST" ]; then + cat >"$USER_PLIST" <<'REIMS_USER_PLIST_EOF' +` + userPlistXML + `REIMS_USER_PLIST_EOF + /usr/bin/plutil -convert binary1 "$USER_PLIST" 2>/dev/null || true + chown 0:0 "$USER_PLIST" 2>/dev/null || true + chmod 600 "$USER_PLIST" + log "wrote offline local admin user plist $USER_PLIST" + else + log "account plist $USER_PLIST already exists; preserving" + fi + + ADMIN_PLIST="$DS/groups/admin.plist" + if [ -f "$ADMIN_PLIST" ] && [ -x /usr/libexec/PlistBuddy ]; then + if ! /usr/libexec/PlistBuddy -c "Print :users" "$ADMIN_PLIST" 2>/dev/null | grep -Eq "^[[:space:]]+$ACCOUNT$"; then + /usr/libexec/PlistBuddy -c "Add :users array" "$ADMIN_PLIST" 2>/dev/null || true + /usr/libexec/PlistBuddy -c "Add :users: string $ACCOUNT" "$ADMIN_PLIST" + fi + if ! /usr/libexec/PlistBuddy -c "Print :groupmembers" "$ADMIN_PLIST" 2>/dev/null | grep -Eq "^[[:space:]]+$USER_UUID$"; then + /usr/libexec/PlistBuddy -c "Add :groupmembers array" "$ADMIN_PLIST" 2>/dev/null || true + /usr/libexec/PlistBuddy -c "Add :groupmembers: string $USER_UUID" "$ADMIN_PLIST" + fi + chown 0:0 "$ADMIN_PLIST" 2>/dev/null || true + chmod 600 "$ADMIN_PLIST" 2>/dev/null || true + log "added $ACCOUNT to offline admin group plist" + else + log "REIMS_PROVISION_ADMIN_FAILED: missing $ADMIN_PLIST or /usr/libexec/PlistBuddy" >&2 + exit 1 + fi +fi + +H="$D/Users/$ACCOUNT" +mkdir -p "$H/Desktop" "$H/Documents" "$H/Downloads" "$H/Library/Preferences" "$H/Library/LaunchAgents" "$H/Library/Application Support" + +# 2. Mark Setup Assistant completed (user explicitly confirmed Apple SLA before creation). +touch "$D/private/var/db/.AppleSetupDone" +chown 0:0 "$D/private/var/db/.AppleSetupDone" 2>/dev/null || true +chmod 400 "$D/private/var/db/.AppleSetupDone" 2>/dev/null || true +touch "$D/private/var/db/.AppleDiagnosticsSetupDone" 2>/dev/null || true +rm -f "$D/private/var/db/.AppleSetupTermsOfService"* 2>/dev/null || true + +SYS_VER="26.9.9" +SYS_BLD="25Z999" +if [ -x /usr/libexec/PlistBuddy ] && [ -f "$D/System/Library/CoreServices/SystemVersion.plist" ]; then + SYS_VER=$(/usr/libexec/PlistBuddy -c "Print :ProductVersion" "$D/System/Library/CoreServices/SystemVersion.plist" 2>/dev/null || echo "$SYS_VER") + SYS_BLD=$(/usr/libexec/PlistBuddy -c "Print :ProductBuildVersion" "$D/System/Library/CoreServices/SystemVersion.plist" 2>/dev/null || echo "$SYS_BLD") +fi + +SA="$H/Library/Preferences/com.apple.SetupAssistant.plist" +for key in \ + DidSeeAccessibility DidSeeActivationLock DidSeeAppearance DidSeeAppearanceSetup \ + DidSeeApplePaySetup DidSeeAppStore DidSeeAutoUpdatePrompt DidSeeAvatarSetup \ + DidSeeCloudSetup DidSeeiCloudLoginForStorageServices DidSeeIntelligence \ + DidSeeLockdownMode DidSeePrivacy DidSeeScreenTime DidSeeSiriSetup \ + DidSeeSyncSetup DidSeeSyncSetup2 DidSeeTermsOfAddress DidSeeTouchIDSetup \ + DidSeeTrueTone DidSeeWallpaper SkipFirstLoginOptimization MiniBuddyLaunchedPostMigration; do + defaults write "$SA" "$key" -bool true || true +done +defaults write "$SA" MiniBuddyLaunchReason -int 0 || true +defaults write "$SA" MiniBuddyShouldLaunchToResumeSetup -bool false || true +defaults write "$SA" GestureMovieSeen -string "none" || true +defaults write "$SA" LastSeenCloudProductVersion -string "$SYS_VER" || true +defaults write "$SA" LastSeenBuddyBuildVersion -string "$SYS_BLD" || true +log "configured SetupAssistant skip markers (ver=$SYS_VER build=$SYS_BLD)" + +# 3. Apply appearance preference. +GP="$H/Library/Preferences/.GlobalPreferences.plist" +case "$APPEARANCE" in + dark) + defaults write "$GP" AppleInterfaceStyle -string "Dark" || true + defaults delete "$GP" AppleInterfaceStyleSwitchesAutomatically 2>/dev/null || true + ;; + auto) + defaults write "$GP" AppleInterfaceStyleSwitchesAutomatically -bool true || true + ;; + light) + defaults delete "$GP" AppleInterfaceStyle 2>/dev/null || true + defaults delete "$GP" AppleInterfaceStyleSwitchesAutomatically 2>/dev/null || true + ;; +esac + +# 4. Pre-declare QEMU USB keyboard (vendor 0x0627 = 1575, product 1) as ANSI (40) +# so Keyboard Setup Assistant does not pop up on first login. +mkdir -p "$D/Library/Preferences" +defaults write "$D/Library/Preferences/com.apple.keyboardtype.plist" keyboardtype -dict-add "1-1575-0" -int 40 || true + +# 5. Stage Reims Guest Tools for automatic start on first login (active once NAT is enabled). +if [ -f "$GT_SRC/${GT_PREFIX}config" ] && [ -f "$GT_SRC/${GT_PREFIX}guest-tools.sh" ]; then + GT_APP="$H/Library/Application Support/ReimsGuestTools" + mkdir -p "$GT_APP" "$H/ReimsShare" "$H/ReimsShareMount" + cp "$GT_SRC/${GT_PREFIX}config" "$GT_APP/config" + cp "$GT_SRC/${GT_PREFIX}guest-tools.sh" "$GT_APP/guest-tools.sh" + if [ -f "$GT_SRC/${GT_PREFIX}drop-resolve.js" ]; then + cp "$GT_SRC/${GT_PREFIX}drop-resolve.js" "$GT_APP/drop-resolve.js" + chmod 755 "$GT_APP/drop-resolve.js" + fi + if [ -f "$GT_SRC/${GT_PREFIX}active-window-reporter.js" ]; then + cp "$GT_SRC/${GT_PREFIX}active-window-reporter.js" "$GT_APP/active-window-reporter.js" + chmod 755 "$GT_APP/active-window-reporter.js" + fi + chmod 600 "$GT_APP/config" + chmod 755 "$GT_APP/guest-tools.sh" + [ -e "$H/Desktop/ReimsShare" ] || ln -s "/Users/$ACCOUNT/ReimsShare" "$H/Desktop/ReimsShare" 2>/dev/null || true + + CF_ENC="0x$(printf '%X' "$USER_UID"):0x08000100:0x08000100" + cat >"$H/Library/LaunchAgents/com.reimsgo.guest-tools.plist" < + + + + Label + com.reimsgo.guest-tools + EnvironmentVariables + + LANG + en_US.UTF-8 + LC_ALL + en_US.UTF-8 + __CF_USER_TEXT_ENCODING + $CF_ENC + + ProgramArguments + + /bin/sh + /Users/$ACCOUNT/Library/Application Support/ReimsGuestTools/guest-tools.sh + + RunAtLoad + + KeepAlive + + StandardOutPath + /Users/$ACCOUNT/Library/Application Support/ReimsGuestTools/agent.log + StandardErrorPath + /Users/$ACCOUNT/Library/Application Support/ReimsGuestTools/agent.log + + +EOF + chmod 644 "$H/Library/LaunchAgents/com.reimsgo.guest-tools.plist" + log "staged Guest Tools LaunchAgent" +fi + +# 6. Record a lightweight non-blocking completion marker (avoid opening +# ISA 16550 UART device nodes, which can block under QEMU Q35 and stall bootinstalld). +touch "$D/private/var/db/.reims-provision-done" 2>/dev/null || true +logger "$SERIAL_MARKER" 2>/dev/null || true + +chown -R "$USER_UID:$USER_GID" "$H" 2>/dev/null || true +chmod 600 "$SA" "$GP" 2>/dev/null || true +chmod 644 "$D/Library/Preferences/com.apple.keyboardtype.plist" 2>/dev/null || true +if [ -x /usr/bin/plutil ]; then + /usr/bin/plutil -lint "$SA" >/dev/null 2>&1 || log "warning: SetupAssistant plist lint check failed" +fi +if [ -z "$D" ]; then + # Running live as root (bootinstalld): flush cfprefsd cache after chown so + # root-cached preferences do not shadow the new user's SetupAssistant plist. + /usr/bin/killall -u "$ACCOUNT" cfprefsd 2>/dev/null || true + /usr/bin/killall cfprefsd 2>/dev/null || true +fi +sync +sync +log "offline provisioning complete" +`) + return b.String() +} + +// buildDistributionPkg constructs a pure-Go Apple XAR v1 payload-free +// Distribution flat package compatible with `installer` / `startosinstall --installpackage`. +func buildDistributionPkg(postinstall string, guestTools []ProvisionGuestToolFile) ([]byte, error) { + // 1. Build gzipped POSIX odc CPIO Scripts archive containing ./postinstall and ./guest-tools/*. + var cpioEntries []cpioEntry + cpioEntries = append(cpioEntries, cpioEntry{ + name: "./postinstall", + mode: 0o100755, + data: []byte(postinstall), + }) + hasGT := false + for _, gt := range guestTools { + if strings.TrimSpace(gt.Name) != "" && len(gt.Data) > 0 { + hasGT = true + break + } + } + if hasGT { + cpioEntries = append(cpioEntries, cpioEntry{ + name: "./guest-tools", + mode: 0o040755, + }) + for _, gt := range guestTools { + if strings.TrimSpace(gt.Name) == "" || len(gt.Data) == 0 { + continue + } + mode := gt.Mode + if mode == 0 { + mode = 0o100644 + } + cpioEntries = append(cpioEntries, cpioEntry{ + name: "./guest-tools/" + filepath.Base(gt.Name), + mode: mode, + data: gt.Data, + }) + } + } + scriptsGZ, err := buildGzippedODCCPIO(cpioEntries) + if err != nil { + return nil, err + } + + distributionXML := []byte(` + + + + + + + + + + + + #reims-provision.pkg + +`) + + packageInfoXML := []byte(` + + + + + +`) + + return buildXARArchive(distributionXML, packageInfoXML, scriptsGZ) +} + +type cpioEntry struct { + name string + mode uint32 + data []byte +} + +// buildGzippedODCCPIO packs entries into a gzip-compressed POSIX.1-1988 odc +// ("070707") CPIO archive, matching Apple pkgbuild's Scripts/Payload format. +func buildGzippedODCCPIO(entries []cpioEntry) ([]byte, error) { + var raw bytes.Buffer + now := uint64(time.Now().UTC().Unix()) + writeEntry := func(ino uint32, mode uint32, nlink uint32, name string, data []byte) { + nameBytes := append([]byte(name), 0) + // 76-byte ASCII octal odc header: + // magic(6) dev(6) ino(6) mode(6) uid(6) gid(6) nlink(6) rdev(6) mtime(11) namesize(6) filesize(11) + fmt.Fprintf(&raw, "070707%06o%06o%06o%06o%06o%06o%06o%011o%06o%011o", + 0, ino, mode, 0, 0, nlink, 0, now, len(nameBytes), len(data)) + raw.Write(nameBytes) + raw.Write(data) + } + for i, e := range entries { + nlink := uint32(1) + if (e.mode & 0o170000) == 0o040000 { + nlink = 2 + } + writeEntry(uint32(i+1), e.mode, nlink, e.name, e.data) + } + writeEntry(0, 0, 1, "TRAILER!!!", nil) + + var gzBuf bytes.Buffer + gw := gzip.NewWriter(&gzBuf) + if _, err := gw.Write(raw.Bytes()); err != nil { + return nil, err + } + if err := gw.Close(); err != nil { + return nil, err + } + return gzBuf.Bytes(), nil +} + +// buildXARArchive writes a valid XAR v1 flat package with SHA-1 TOC & file checksums. +func buildXARArchive(distributionXML, packageInfoXML, scriptsGZ []byte) ([]byte, error) { + // Heap layout: + // [0..20): SHA-1 checksum of compressed TOC (filled after TOC compression) + // [20..): Distribution, PackageInfo, Scripts stored verbatim (octet-stream) + const cksumSize = 20 + var heap bytes.Buffer + heap.Write(make([]byte, cksumSize)) + + type storedFile struct { + offset int + size int + sha1 string + } + appendHeap := func(data []byte) storedFile { + off := heap.Len() + heap.Write(data) + sum := sha1.Sum(data) + return storedFile{ + offset: off, + size: len(data), + sha1: hex.EncodeToString(sum[:]), + } + } + + distF := appendHeap(distributionXML) + pkgInfoF := appendHeap(packageInfoXML) + scriptsF := appendHeap(scriptsGZ) + + nowStr := time.Now().UTC().Format("2006-01-02T15:04:05Z") + fileEntryXML := func(id int, name string, f storedFile) string { + return fmt.Sprintf(`%sfile064400rootwheel%s%s%s%d%d%d%s%s`, + id, name, nowStr, nowStr, nowStr, f.size, f.offset, f.size, f.sha1, f.sha1) + } + + tocXML := fmt.Sprintf(` +%s0%d%sreims-provision.pkgdirectory075500rootwheel%s%s%s%s%s`, + nowStr, cksumSize, + fileEntryXML(1, "Distribution", distF), + nowStr, nowStr, nowStr, + fileEntryXML(3, "PackageInfo", pkgInfoF), + fileEntryXML(4, "Scripts", scriptsF), + ) + + var compTOC bytes.Buffer + zw := zlib.NewWriter(&compTOC) + if _, err := zw.Write([]byte(tocXML)); err != nil { + return nil, err + } + if err := zw.Close(); err != nil { + return nil, err + } + + tocSum := sha1.Sum(compTOC.Bytes()) + heapBytes := heap.Bytes() + copy(heapBytes[0:cksumSize], tocSum[:]) + + var out bytes.Buffer + var hdr [28]byte + copy(hdr[0:4], "xar!") + binary.BigEndian.PutUint16(hdr[4:6], 28) + binary.BigEndian.PutUint16(hdr[6:8], 1) + binary.BigEndian.PutUint64(hdr[8:16], uint64(compTOC.Len())) + binary.BigEndian.PutUint64(hdr[16:24], uint64(len(tocXML))) + binary.BigEndian.PutUint32(hdr[24:28], 1) // SHA-1 + out.Write(hdr[:]) + out.Write(compTOC.Bytes()) + out.Write(heapBytes) + return out.Bytes(), nil +} diff --git a/internal/macos/installer/provision_pkg_test.go b/internal/macos/installer/provision_pkg_test.go new file mode 100644 index 0000000..0f0f5d5 --- /dev/null +++ b/internal/macos/installer/provision_pkg_test.go @@ -0,0 +1,432 @@ +package installer + +import ( + "bytes" + "compress/gzip" + "compress/zlib" + "crypto/pbkdf2" + "crypto/sha1" + "crypto/sha512" + "encoding/base64" + "encoding/binary" + "encoding/hex" + "encoding/xml" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +func TestEncodeShadowHashBPlistRoundTripAndNoPlaintext(t *testing.T) { + const secret = "S3cretP@ssw0rd!" + raw, err := deriveMacOSShadowHashBPlist(secret, provisionPBKDF2Iterations) + if err != nil { + t.Fatalf("deriveMacOSShadowHashBPlist: %v", err) + } + hexStr := hex.EncodeToString(raw) + if bytes.Contains(raw, []byte(secret)) || strings.Contains(hexStr, hex.EncodeToString([]byte(secret))) { + t.Fatal("plaintext password leaked into ShadowHashData") + } + if len(raw) < 40 || string(raw[:8]) != "bplist00" { + t.Fatalf("invalid bplist00 magic: %q", string(raw[:min(8, len(raw))])) + } + trailer := raw[len(raw)-32:] + offSize := trailer[6] + refSize := trailer[7] + numObjs := binary.BigEndian.Uint64(trailer[8:16]) + topObj := binary.BigEndian.Uint64(trailer[16:24]) + offTablePos := binary.BigEndian.Uint64(trailer[24:32]) + if offSize != 2 || refSize != 1 || numObjs != 9 || topObj != 0 { + t.Fatalf("unexpected trailer: offSize=%d refSize=%d numObjs=%d topObj=%d", offSize, refSize, numObjs, topObj) + } + offsets := make([]int, numObjs) + for i := range offsets { + p := int(offTablePos) + i*2 + offsets[i] = int(binary.BigEndian.Uint16(raw[p : p+2])) + } + readCounted := func(pos int, wantType byte) []byte { + marker := raw[pos] + if marker&0xF0 != wantType { + t.Fatalf("obj at %d has marker 0x%02x, want type 0x%02x", pos, marker, wantType) + } + n := int(marker & 0x0F) + pos++ + if n == 0x0F { + intMarker := raw[pos] + pos++ + switch intMarker { + case 0x10: + n = int(raw[pos]) + pos++ + case 0x11: + n = int(binary.BigEndian.Uint16(raw[pos : pos+2])) + pos += 2 + default: + t.Fatalf("unexpected length int marker 0x%02x", intMarker) + } + } + return raw[pos : pos+n] + } + + if got := string(readCounted(offsets[1], 0x50)); got != "SALTED-SHA512-PBKDF2" { + t.Fatalf("outer key = %q", got) + } + if got := string(readCounted(offsets[3], 0x50)); got != "entropy" { + t.Fatalf("key 3 = %q", got) + } + entropy := readCounted(offsets[4], 0x40) + if len(entropy) != 128 { + t.Fatalf("entropy len = %d, want 128", len(entropy)) + } + if got := string(readCounted(offsets[5], 0x50)); got != "iterations" { + t.Fatalf("key 5 = %q", got) + } + if raw[offsets[6]] != 0x12 { + t.Fatalf("iterations marker = 0x%02x, want 0x12", raw[offsets[6]]) + } + iters := int(binary.BigEndian.Uint32(raw[offsets[6]+1 : offsets[6]+5])) + if iters != provisionPBKDF2Iterations { + t.Fatalf("iterations = %d, want %d", iters, provisionPBKDF2Iterations) + } + if got := string(readCounted(offsets[7], 0x50)); got != "salt" { + t.Fatalf("key 7 = %q", got) + } + salt := readCounted(offsets[8], 0x40) + if len(salt) != 32 { + t.Fatalf("salt len = %d, want 32", len(salt)) + } + + // Re-derive with extracted salt + iterations and verify cryptographic identity. + wantEntropy, err := pbkdf2.Key(sha512.New, secret, salt, iters, 128) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(entropy, wantEntropy) { + t.Fatal("PBKDF2-SHA512 entropy mismatch") + } +} + +func TestBuildProvisionDiskImageAndXARVerification(t *testing.T) { + vmDir := t.TempDir() + const secret = "MyTestPass!99" + imgPath, err := BuildProvisionDiskImage(vmDir, ProvisionConfig{ + FullName: "Reims Test User", + AccountName: "reimstest", + Password: secret, + Appearance: "dark", + SLAAccepted: true, + GuestTools: []ProvisionGuestToolFile{ + {Name: "config", Mode: 0o100600, Data: []byte("REIMS_HOST_URL='http://10.0.2.2:19847'\nREIMS_TOKEN='tok'\n")}, + {Name: "guest-tools.sh", Mode: 0o100755, Data: []byte("#!/bin/sh\necho ok\n")}, + }, + }) + if err != nil { + t.Fatalf("BuildProvisionDiskImage: %v", err) + } + if !HasProvisionImage(vmDir) { + t.Fatal("HasProvisionImage returned false after build") + } + + rawImg, err := os.ReadFile(imgPath) + if err != nil { + t.Fatal(err) + } + if bytes.Contains(rawImg, []byte(secret)) { + t.Fatal("REIMSPROV disk image must NEVER contain plaintext password") + } + + f, err := os.Open(imgPath) + if err != nil { + t.Fatal(err) + } + defer f.Close() + + // 1. Locate and validate provision.pkg XAR Distribution flat package. + pkgOff, pkgSize, err := FindFileInHFSPlusImage(f, "provision.pkg") + if err != nil || pkgSize <= 0 { + t.Fatalf("FindFileInHFSPlusImage(provision.pkg): off=%d size=%d err=%v", pkgOff, pkgSize, err) + } + pkgBuf := make([]byte, pkgSize) + if _, err := f.ReadAt(pkgBuf, pkgOff); err != nil { + t.Fatal(err) + } + if string(pkgBuf[:4]) != "xar!" { + t.Fatalf("provision.pkg magic = %q, want xar!", string(pkgBuf[:4])) + } + hdrSize := int(binary.BigEndian.Uint16(pkgBuf[4:6])) + tocCompLen := int(binary.BigEndian.Uint64(pkgBuf[8:16])) + tocUncompLen := int(binary.BigEndian.Uint64(pkgBuf[16:24])) + compTOC := pkgBuf[hdrSize : hdrSize+tocCompLen] + heap := pkgBuf[hdrSize+tocCompLen:] + + // Verify TOC SHA-1 stored at heap[0:20]. + wantTOCSum := sha1.Sum(compTOC) + if !bytes.Equal(heap[:20], wantTOCSum[:]) { + t.Fatal("XAR TOC SHA-1 checksum mismatch in heap[0:20]") + } + zr, err := zlib.NewReader(bytes.NewReader(compTOC)) + if err != nil { + t.Fatalf("zlib.NewReader(TOC): %v", err) + } + tocBytes, err := io.ReadAll(zr) + _ = zr.Close() + if err != nil || len(tocBytes) != tocUncompLen { + t.Fatalf("TOC decompress mismatch: got %d want %d err=%v", len(tocBytes), tocUncompLen, err) + } + var toc xarTOC + if err := xml.Unmarshal(tocBytes, &toc); err != nil { + t.Fatalf("parse XAR TOC XML: %v", err) + } + + // Verify Distribution, PackageInfo, and gzipped CPIO Scripts entries exist and match SHA-1. + var distXML, pkgInfoXML, scriptsGZ []byte + var walk func([]xarFile) + walk = func(list []xarFile) { + for _, item := range list { + if item.Data != nil { + chunk := heap[item.Data.Offset : item.Data.Offset+item.Data.Length] + switch item.Name { + case "Distribution": + distXML = chunk + case "PackageInfo": + pkgInfoXML = chunk + case "Scripts": + scriptsGZ = chunk + } + } + walk(item.Files) + } + } + walk(toc.Files) + if !strings.Contains(string(distXML), "#reims-provision.pkg") { + t.Fatalf("Distribution XML missing #reims-provision.pkg: %s", string(distXML)) + } + if !strings.Contains(string(pkgInfoXML), `postinstall file="./postinstall"`) { + t.Fatalf("PackageInfo XML missing postinstall declaration: %s", string(pkgInfoXML)) + } + if len(scriptsGZ) == 0 { + t.Fatal("Scripts entry missing from provision.pkg") + } + + // Unpack gzipped ODC CPIO Scripts and confirm postinstall + staged Guest Tools exist. + gr, err := gzip.NewReader(bytes.NewReader(scriptsGZ)) + if err != nil { + t.Fatalf("gzip.NewReader(Scripts): %v", err) + } + cpioRaw, err := io.ReadAll(gr) + _ = gr.Close() + if err != nil { + t.Fatal(err) + } + entries := parseODCCPIO(t, cpioRaw) + postinstall, ok := entries["./postinstall"] + if !ok { + t.Fatal("./postinstall missing from Scripts CPIO") + } + if _, ok := entries["./guest-tools/config"]; !ok { + t.Fatal("./guest-tools/config missing from Scripts CPIO") + } + if _, ok := entries["./guest-tools/guest-tools.sh"]; !ok { + t.Fatal("./guest-tools/guest-tools.sh missing from Scripts CPIO") + } + if strings.Contains(string(postinstall), secret) { + t.Fatal("postinstall contains plaintext password") + } + if !strings.Contains(string(postinstall), ProvisionSerialReadyMarker) { + t.Fatal("postinstall missing serial readiness marker") + } + if !strings.Contains(string(postinstall), `"1-1575-0" -int 40`) { + t.Fatal("postinstall missing QEMU keyboard ANSI declaration") + } + if strings.Contains(string(postinstall), "NOPASSWD") || strings.Contains(string(postinstall), "kcpassword") { + t.Fatal("postinstall must not enable NOPASSWD sudo or kcpassword auto-login") + } + if strings.Contains(string(postinstall), "dscl -f") { + t.Fatal("postinstall must not use dscl -f localonly") + } + if !strings.Contains(string(postinstall), "ObjC.import('OpenDirectory')") || !strings.Contains(string(postinstall), "dseditgroup") { + t.Fatal("postinstall must use OpenDirectory.framework JXA + dseditgroup for live SIP-enabled bootinstalld") + } + if strings.Contains(string(postinstall), "/dev/tty.serial") || strings.Contains(string(postinstall), "/dev/cu.serial") { + t.Fatal("postinstall must not open blocking /dev/cu.serial* or /dev/tty.serial* devices") + } + if !strings.Contains(string(postinstall), `chmod 755 "$GT_APP/active-window-reporter.js"`) { + t.Fatal("postinstall must set 755 mode on active-window-reporter.js consistent with REIMSTOOLS") + } + if !strings.Contains(string(postinstall), "killall cfprefsd") || !strings.Contains(string(postinstall), "plutil -lint") { + t.Fatal("postinstall must lint SetupAssistant plist and flush cfprefsd cache in live mode") + } + // Verify embedded dslocal user plist is well-formed XML carrying a valid base64 bplist00 ShadowHashData. + const markerStart = "<<'REIMS_USER_PLIST_EOF'\n" + const markerEnd = "\nREIMS_USER_PLIST_EOF" + sIdx := strings.Index(string(postinstall), markerStart) + eIdx := strings.Index(string(postinstall), markerEnd) + if sIdx < 0 || eIdx <= sIdx { + t.Fatal("postinstall missing REIMS_USER_PLIST_EOF heredoc") + } + userXML := string(postinstall)[sIdx+len(markerStart) : eIdx] + var dummy any + if err := xml.Unmarshal([]byte(userXML), &dummy); err != nil { + t.Fatalf("embedded user plist XML invalid: %v\n%s", err, userXML) + } + dStart := strings.Index(userXML, "") + dEnd := strings.Index(userXML, "") + if dStart < 0 || dEnd <= dStart { + t.Fatal("embedded user plist missing ShadowHashData") + } + shadowBytes, err := base64.StdEncoding.DecodeString(strings.TrimSpace(userXML[dStart+len("") : dEnd])) + if err != nil || !bytes.HasPrefix(shadowBytes, []byte("bplist00")) { + t.Fatalf("embedded ShadowHashData is not valid base64 bplist00: err=%v", err) + } + + // 2. Locate provision-offline.sh and verify POSIX syntax with `sh -n` when sh is available. + offOff, offSize, err := FindFileInHFSPlusImage(f, "provision-offline.sh") + if err != nil || offSize <= 0 { + t.Fatalf("FindFileInHFSPlusImage(provision-offline.sh): %v", err) + } + offBuf := make([]byte, offSize) + if _, err := f.ReadAt(offBuf, offOff); err != nil { + t.Fatal(err) + } + _ = f.Close() + + if shPath, err := exec.LookPath("sh"); err == nil { + for name, script := range map[string][]byte{ + "postinstall": postinstall, + "provision-offline.sh": offBuf, + "install.sh": HelperInstallScript(), + } { + p := filepath.Join(t.TempDir(), name) + if err := os.WriteFile(p, script, 0o755); err != nil { + t.Fatal(err) + } + if out, err := exec.Command(shPath, "-n", p).CombinedOutput(); err != nil { + t.Fatalf("sh -n %s failed: %v\n%s", name, err, string(out)) + } + } + } + + // 3. Verify HelperInstallScript references --installpackage, fallback marker, + // and rejects unknown flags; verify postinstall/offline scripts guard Recovery + // root and scope chmod to com.apple.keyboardtype.plist only. + inst := string(HelperInstallScript()) + if !strings.Contains(inst, "--installpackage") || !strings.Contains(inst, InstallPkgUnsupportedMarker) { + t.Fatal("HelperInstallScript missing --installpackage or fallback marker") + } + if !strings.Contains(inst, `Unknown option: $1`) { + t.Fatal("HelperInstallScript must reject unknown -* options instead of treating them as target volumes") + } + if !strings.Contains(string(postinstall), `/System/Installation/CDIS`) { + t.Fatal("postinstall must guard live '/' root against macOS Recovery /System/Installation/CDIS") + } + if strings.Contains(string(offBuf), `[ "$cand" = "/" ]`) { + t.Fatal("provision-offline.sh must never treat '/' as a live target root") + } + for name, body := range map[string]string{"postinstall": string(postinstall), "provision-offline.sh": string(offBuf)} { + if strings.Contains(body, `Library/Preferences/"*.plist`) { + t.Fatalf("%s must not chmod wildcard /Library/Preferences/*.plist", name) + } + if !strings.Contains(body, `chmod 644 "$D/Library/Preferences/com.apple.keyboardtype.plist"`) { + t.Fatalf("%s must scope chmod 644 to com.apple.keyboardtype.plist only", name) + } + } + if !strings.Contains(string(offBuf), "REIMS_PROVISION_ADMIN_FAILED") { + t.Fatal("provision-offline.sh must emit REIMS_PROVISION_ADMIN_FAILED and fail when admin group update is unavailable") + } + if !HasProvisionStagedMarker(vmDir) { + t.Fatal("BuildProvisionDiskImage must write staged marker") + } + WriteProvisionReadyMarker(vmDir) + if !HasProvisionReadyMarker(vmDir) { + t.Fatal("WriteProvisionReadyMarker must persist ready marker") + } + + // 4. Verify SecureRemoveProvisionImage deletes the image and clears markers cleanly. + if err := SecureRemoveProvisionImage(vmDir); err != nil { + t.Fatalf("SecureRemoveProvisionImage: %v", err) + } + if HasProvisionImage(vmDir) || HasProvisionStagedMarker(vmDir) || HasProvisionReadyMarker(vmDir) || HasProvisionWipePending(vmDir) { + t.Fatal("SecureRemoveProvisionImage must remove image and all provision markers") + } +} + +func TestValidateProvisionConfigRejectsInvalidInputs(t *testing.T) { + cases := []ProvisionConfig{ + {FullName: "User", AccountName: "user", Password: "secret", SLAAccepted: false}, + {FullName: "中文名", AccountName: "user", Password: "secret", SLAAccepted: true}, + {FullName: "User", AccountName: "1bad", Password: "secret", SLAAccepted: true}, + {FullName: "User", AccountName: "user", Password: "123", SLAAccepted: true}, + {FullName: "User", AccountName: "user", Password: "secret", Appearance: "purple", SLAAccepted: true}, + } + for i, tc := range cases { + c := tc + if err := ValidateProvisionConfig(&c); err == nil { + t.Fatalf("case %d: expected validation error for %+v", i, tc) + } + } +} + +func TestSecureRemoveProvisionImageRefusesUnwipedDeleteWhenOpenFails(t *testing.T) { + vmDir := t.TempDir() + imgPath := ProvisionImagePath(vmDir) + // Simulate an unwipable path by creating a directory at imgPath on non-Windows + // or locking the file; use a non-empty file whose parent dir cannot be written + // or lock via exclusive handle on Windows. Even simpler cross-platform: + // create a file and verify normal overwrite zeroes bytes, AND test a directory + // / unwritable open scenario via helper. + payload := bytes.Repeat([]byte("SECRET_HASH_DATA"), 256) + if err := os.WriteFile(imgPath, payload, 0o600); err != nil { + t.Fatal(err) + } + // Open without write-share on Windows (or test wipe failure by opening a handle). + // Calling SecureRemoveProvisionImage on a normal file must zero and remove it cleanly. + if err := SecureRemoveProvisionImage(vmDir); err != nil { + t.Fatalf("SecureRemoveProvisionImage on normal file failed: %v", err) + } + if HasProvisionImage(vmDir) || HasProvisionWipePending(vmDir) { + t.Fatal("expected image and wipe-pending marker removed after successful secure wipe") + } +} + +func parseODCCPIO(t *testing.T, raw []byte) map[string][]byte { + t.Helper() + out := map[string][]byte{} + pos := 0 + for pos+76 <= len(raw) { + hdr := string(raw[pos : pos+76]) + if !strings.HasPrefix(hdr, "070707") { + t.Fatalf("bad odc cpio magic at %d: %q", pos, hdr[:6]) + } + var nameLen, fileLen int + if _, err := io.ReadFull(strings.NewReader(hdr[59:65]), make([]byte, 6)); err != nil { + t.Fatal(err) + } + nameLen = parseOctal(t, hdr[59:65]) + fileLen = parseOctal(t, hdr[65:76]) + pos += 76 + name := strings.TrimSuffix(string(raw[pos:pos+nameLen]), "\x00") + pos += nameLen + data := append([]byte(nil), raw[pos:pos+fileLen]...) + pos += fileLen + if name == "TRAILER!!!" { + break + } + out[name] = data + } + return out +} + +func parseOctal(t *testing.T, s string) int { + t.Helper() + v := 0 + for i := 0; i < len(s); i++ { + c := s[i] + if c < '0' || c > '7' { + t.Fatalf("invalid octal digit %q in %q", c, s) + } + v = v*8 + int(c-'0') + } + return v +} diff --git a/internal/macos/installer/provision_pkg_windows_test.go b/internal/macos/installer/provision_pkg_windows_test.go new file mode 100644 index 0000000..e41a114 --- /dev/null +++ b/internal/macos/installer/provision_pkg_windows_test.go @@ -0,0 +1,60 @@ +//go:build windows + +package installer + +import ( + "bytes" + "os" + "testing" + + "golang.org/x/sys/windows" +) + +func TestSecureRemoveProvisionImageMarksWipePendingWhenLockedOnWindows(t *testing.T) { + vmDir := t.TempDir() + imgPath := ProvisionImagePath(vmDir) + payload := bytes.Repeat([]byte("SECRET_HASH_BYTES"), 128) + if err := os.WriteFile(imgPath, payload, 0o600); err != nil { + t.Fatal(err) + } + + // Open with FILE_SHARE_READ | FILE_SHARE_DELETE (no FILE_SHARE_WRITE), + // mirroring a reader holding the image open while disallowing O_WRONLY wipe. + ptr, err := windows.UTF16PtrFromString(imgPath) + if err != nil { + t.Fatal(err) + } + h, err := windows.CreateFile( + ptr, + windows.GENERIC_READ, + windows.FILE_SHARE_READ|windows.FILE_SHARE_DELETE, + nil, + windows.OPEN_EXISTING, + windows.FILE_ATTRIBUTE_NORMAL, + 0, + ) + if err != nil { + t.Fatal(err) + } + + removeErr := SecureRemoveProvisionImage(vmDir) + _ = windows.CloseHandle(h) + + if removeErr == nil { + t.Fatal("SecureRemoveProvisionImage must fail when O_WRONLY wipe is blocked instead of unlinking unwiped secret data") + } + if !HasProvisionWipePending(vmDir) { + t.Fatal("expected wipe-pending marker to be written when secure wipe fails") + } + if !HasProvisionImage(vmDir) { + t.Fatal("unwiped provisioning image must NOT be unlinked when overwrite fails") + } + + // Once handle is closed, retrying SecureRemoveProvisionImage succeeds and clears wipe-pending. + if err := SecureRemoveProvisionImage(vmDir); err != nil { + t.Fatalf("retry SecureRemoveProvisionImage after unlock failed: %v", err) + } + if HasProvisionImage(vmDir) || HasProvisionWipePending(vmDir) { + t.Fatal("expected image and wipe-pending marker cleared after retry") + } +} diff --git a/internal/macos/installguide/progress.go b/internal/macos/installguide/progress.go index ca44f8f..d396e95 100644 --- a/internal/macos/installguide/progress.go +++ b/internal/macos/installguide/progress.go @@ -44,6 +44,97 @@ func (p page) recoveryStep(k Kind) bool { return false } +// PostInstallStep identifies a post-install manual guide step that can be +// seeded when recovery exits outside the manual guide (for example through an +// auto-install plugin). +type PostInstallStep string + +const ( + StepSetup PostInstallStep = PostInstallStep(setup) + StepDesktop PostInstallStep = PostInstallStep(desktop) + StepRestored PostInstallStep = PostInstallStep(restored) +) + +func loadCheckpoint(dir, name string) (checkpoint, bool) { + if dir == "" || name == "" { + return checkpoint{}, false + } + raw, err := os.ReadFile(filepath.Join(dir, progressFile)) + var cp checkpoint + if err != nil || json.Unmarshal(raw, &cp) != nil || cp.Name != name { + return checkpoint{}, false + } + return cp, true +} + +// HasPostInstallCheckpoint reports whether dir holds a valid post-install +// manual guide checkpoint for name. +func HasPostInstallCheckpoint(dir, name string) bool { + cp, ok := loadCheckpoint(dir, name) + return ok && cp.Step.postInstall() +} + +// SavePostInstallHandoff writes a post-install guide checkpoint into dir so +// the original manual installation guide resumes at step (or restartPending if +// restartFrom matches the running boot PID) after recovery exits. +func SavePostInstallHandoff(dir, name string, kind Kind, media string, step PostInstallStep, restartFrom uint32) error { + if dir == "" || name == "" { + return nil + } + p := page(step) + if !p.postInstall() { + return nil + } + g := Guide{ + Name: name, + Kind: kind, + dir: dir, + media: media, + } + return g.save(p, restartFrom) +} + +// AdvancePostInstallHandoff ensures dir holds a post-install guide checkpoint +// at least as far as step without downgrading an active desktop or Guest Tools +// step or losing a pending restartFrom guard. +func AdvancePostInstallHandoff(dir, name string, fallbackKind Kind, step PostInstallStep) error { + if dir == "" || name == "" { + return nil + } + target := page(step) + if !target.postInstall() { + return nil + } + kind := fallbackKind + media := "" + if cp, ok := loadCheckpoint(dir, name); ok { + kind = cp.Kind + media = cp.Media + if cp.Step.postInstall() { + // Never regress Guest Tools or an already-reached desktop step. + if cp.Step == toolsTerminal || cp.Step == toolsVerify { + return nil + } + if target != desktop { + // Already at a post-install step (e.g. setup/restored/desktop); keep + // existing step and any pending RestartFrom untouched. + return nil + } + if cp.Step == desktop { + // Already at desktop; keep any pending RestartFrom guard intact. + return nil + } + } + } + g := Guide{ + Name: name, + Kind: kind, + dir: dir, + media: media, + } + return g.save(target, 0) +} + // Resume attaches ordinary boots only when this VM has a pending post-install // walkthrough. A restart request never replays an operation on startup. func (g *Guide) Resume(dir, media string, recovery bool) bool { @@ -51,9 +142,8 @@ func (g *Guide) Resume(dir, media string, recovery bool) bool { if dir == "" { return recovery } - raw, err := os.ReadFile(filepath.Join(dir, progressFile)) - var cp checkpoint - if err != nil || json.Unmarshal(raw, &cp) != nil || cp.Name != g.Name { + cp, ok := loadCheckpoint(dir, g.Name) + if !ok { return recovery } if recovery { diff --git a/internal/macos/installguide/progress_test.go b/internal/macos/installguide/progress_test.go new file mode 100644 index 0000000..0daa246 --- /dev/null +++ b/internal/macos/installguide/progress_test.go @@ -0,0 +1,101 @@ +package installguide + +import ( + "testing" +) + +func TestPostInstallHandoffSaveAndAdvance(t *testing.T) { + dir := t.TempDir() + const vmName = "tahoe-auto" + + if HasPostInstallCheckpoint(dir, vmName) { + t.Fatal("fresh VM dir should not have a post-install checkpoint") + } + + // Stage 4 finish_install saves a setup handoff pinned to the old boot PID. + if err := SavePostInstallHandoff(dir, vmName, Offline, "offline-installer-tahoe.img", StepSetup, 1001); err != nil { + t.Fatalf("SavePostInstallHandoff: %v", err) + } + if !HasPostInstallCheckpoint(dir, vmName) { + t.Fatal("expected HasPostInstallCheckpoint true after SavePostInstallHandoff") + } + + // Stopping before restart (same PID) resumes at restartPending. + sameBoot := Guide{Name: vmName, PID: 1001} + if !sameBoot.Resume(dir, "", false) || sameBoot.initial != restartPending { + t.Fatalf("same-PID Resume = (%v, %s), want (true, %s)", sameBoot.Resume(dir, "", false), sameBoot.initial, restartPending) + } + + // AdvancePostInstallHandoff(StepSetup) must preserve the existing RestartFrom guard. + if err := AdvancePostInstallHandoff(dir, vmName, Offline, StepSetup); err != nil { + t.Fatalf("AdvancePostInstallHandoff(StepSetup): %v", err) + } + sameBoot = Guide{Name: vmName, PID: 1001} + if !sameBoot.Resume(dir, "", false) || sameBoot.initial != restartPending { + t.Fatalf("AdvancePostInstallHandoff(StepSetup) lost restartPending guard: got %s", sameBoot.initial) + } + + // After restart (new PID), recovery_only completion resumes at Setup Assistant (step 1/6). + nextBoot := Guide{Name: vmName, PID: 2002} + if !nextBoot.Resume(dir, "", false) || nextBoot.initial != setup || nextBoot.Kind != Offline { + t.Fatalf("post-restart Resume = (kind=%d, initial=%s), want (Offline, %s)", nextBoot.Kind, nextBoot.initial, setup) + } + + // Full-mode completion advances setup -> desktop while preserving Kind/Media. + if err := AdvancePostInstallHandoff(dir, vmName, BuiltIn, StepDesktop); err != nil { + t.Fatalf("AdvancePostInstallHandoff(StepDesktop): %v", err) + } + desktopBoot := Guide{Name: vmName, PID: 2002} + if !desktopBoot.Resume(dir, "", false) || desktopBoot.initial != desktop || desktopBoot.Kind != Offline { + t.Fatalf("desktop Resume = (kind=%d, initial=%s), want (Offline, %s)", desktopBoot.Kind, desktopBoot.initial, desktop) + } + + // Never downgrade desktop back to setup. + if err := AdvancePostInstallHandoff(dir, vmName, Offline, StepSetup); err != nil { + t.Fatalf("AdvancePostInstallHandoff downgrade check: %v", err) + } + desktopBoot = Guide{Name: vmName, PID: 2002} + if !desktopBoot.Resume(dir, "", false) || desktopBoot.initial != desktop { + t.Fatalf("desktop regressed to %s", desktopBoot.initial) + } + + // Never downgrade an active Guest Tools step back to desktop. + toolsGuide := Guide{Name: vmName, Kind: Offline, dir: dir, media: "offline-installer-tahoe.img"} + if err := toolsGuide.save(toolsTerminal, 0); err != nil { + t.Fatalf("save toolsTerminal: %v", err) + } + if err := AdvancePostInstallHandoff(dir, vmName, Offline, StepDesktop); err != nil { + t.Fatalf("AdvancePostInstallHandoff over toolsTerminal: %v", err) + } + toolsBoot := Guide{Name: vmName, PID: 3003, ToolsAttached: true} + if !toolsBoot.Resume(dir, "", false) || toolsBoot.initial != toolsTerminal { + t.Fatalf("toolsTerminal regressed to %s", toolsBoot.initial) + } + + // Built-in recovery preserves StepRestored when advancing with StepSetup. + builtInDir := t.TempDir() + if err := SavePostInstallHandoff(builtInDir, vmName, BuiltIn, "", StepRestored, 4001); err != nil { + t.Fatalf("SavePostInstallHandoff(BuiltIn): %v", err) + } + if err := AdvancePostInstallHandoff(builtInDir, vmName, Offline, StepSetup); err != nil { + t.Fatalf("AdvancePostInstallHandoff over StepRestored: %v", err) + } + restoredBoot := Guide{Name: vmName, PID: 4002} + if !restoredBoot.Resume(builtInDir, "", false) || restoredBoot.initial != restored || restoredBoot.Kind != BuiltIn { + t.Fatalf("BuiltIn restored Resume = (kind=%d, initial=%s), want (BuiltIn, %s)", restoredBoot.Kind, restoredBoot.initial, restored) + } + + // AdvancePostInstallHandoff(StepDesktop) must preserve a pending RestartFrom + // guard when the checkpoint is already at StepDesktop. + desktopGuardDir := t.TempDir() + if err := SavePostInstallHandoff(desktopGuardDir, vmName, Offline, "offline-installer-tahoe.img", StepDesktop, 5001); err != nil { + t.Fatalf("SavePostInstallHandoff(StepDesktop): %v", err) + } + if err := AdvancePostInstallHandoff(desktopGuardDir, vmName, Offline, StepDesktop); err != nil { + t.Fatalf("AdvancePostInstallHandoff(StepDesktop) with pending restartFrom: %v", err) + } + sameDesktopBoot := Guide{Name: vmName, PID: 5001} + if !sameDesktopBoot.Resume(desktopGuardDir, "", false) || sameDesktopBoot.initial != restartPending { + t.Fatalf("AdvancePostInstallHandoff(StepDesktop) dropped RestartFrom guard: got %s", sameDesktopBoot.initial) + } +} diff --git a/internal/macos/macosdriver/driver.go b/internal/macos/macosdriver/driver.go index b3ac31b..3f79e01 100644 --- a/internal/macos/macosdriver/driver.go +++ b/internal/macos/macosdriver/driver.go @@ -14,6 +14,7 @@ import ( "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/macos/installer" "github.com/Nwflower/reims-go/internal/macos/opencore" "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/macos/startprep" @@ -568,6 +569,9 @@ func (d *ReimsMacOSDriver) Delete(ctx context.Context, name string, keepFiles bo if err != nil { return err } + if det, serr := c.Show(ctx, name); serr == nil && det.Directory != "" { + _ = installer.SecureRemoveProvisionImage(det.Directory) + } return c.Delete(ctx, name, keepFiles, stdout, stderr) } diff --git a/internal/macos/macosdriver/prepare.go b/internal/macos/macosdriver/prepare.go index ceee28b..0162811 100644 --- a/internal/macos/macosdriver/prepare.go +++ b/internal/macos/macosdriver/prepare.go @@ -26,6 +26,7 @@ import ( const ( keyOfflineHelper = "reimshelp" + keyProvisionDisk = "reimsprov" keyKernelIrqchip = "kernel-irqchip" keyNestedVirt = "nested-virt" keyWin10ColdReboot = "win10-cold-reboot" @@ -113,7 +114,7 @@ func (d *ReimsMacOSDriver) startWithHost(ctx context.Context, req driver.StartRe } baseArgs := startBaseArgs(cur.ExtraArgs, d.opts.ManagedByDesktop, req.ActivePlugins) userExtraArgs := plugin.UserExtraArgs(baseArgs, ledger) - ownerIntent, err := d.prepareStart(ctx, cfg, c, active, ref.Name, cur, rep, userExtraArgs, stdout) + ownerIntent, consumeProvisionStaged, err := d.prepareStart(ctx, cfg, c, active, ref.Name, cur, rep, userExtraArgs, stdout) if err != nil { return driver.StartResult{}, err } @@ -141,6 +142,9 @@ func (d *ReimsMacOSDriver) startWithHost(ctx context.Context, req driver.StartRe if err := c.StartWithCompat(ctx, ref.Name, stdout, stderr, func(msg string) { startLog(stderr, msg) }); err != nil { return driver.StartResult{}, err } + if consumeProvisionStaged { + installer.ClearProvisionStagedMarker(cur.Directory) + } return driver.StartResult{PostStart: reconciled.PostStart}, nil } @@ -190,45 +194,73 @@ func prepareColdStart(ctx context.Context, cur reims.VMDetail, tmpDir string, st return false, err } -func (d *ReimsMacOSDriver) prepareStart(ctx context.Context, cfg config.Config, c *reims.Client, active rt.Installed, name string, cur reims.VMDetail, rep host.Report, userExtraArgs string, log io.Writer) (plugin.StartIntent, error) { +func (d *ReimsMacOSDriver) prepareStart(ctx context.Context, cfg config.Config, c *reims.Client, active rt.Installed, name string, cur reims.VMDetail, rep host.Report, userExtraArgs string, log io.Writer) (plugin.StartIntent, bool, error) { in := plugin.StartIntent{PluginID: d.opts.OwnerID} - if err := d.prepareOfflineHelper(cfg, cur, &in); err != nil { - return in, err + consumeProvisionStaged, err := d.prepareOfflineHelper(cfg, cur, &in) + if err != nil { + return in, false, err } if err := d.prepareRecoveryBoot(ctx, c, name, cur.Directory, log); err != nil { - return in, err + return in, false, err } if err := d.prepareGuestLang(ctx, cfg, active, cur.Directory); err != nil { - return in, err + return in, false, err } if reims.HasGuestToolsArgs(cur.ExtraArgs) && d.opts.PrepareGuestToolsImage != nil { if err := d.opts.PrepareGuestToolsImage(name, cur.Directory); err != nil { - return in, fmt.Errorf("build Guest Tools disk image: %w", err) + return in, false, fmt.Errorf("build Guest Tools disk image: %w", err) } } d.prepareWHPXFallback(cfg, active, cur, rep, &in) if err := d.prepareColdReboot(cfg, name, cur.Directory, rep, &in); err != nil { - return in, err + return in, false, err } AppendNestedVirtIntent(&in, cfg.Locale, cur.Directory, userExtraArgs, rep) d.prepareHostMemorySMBIOS(cfg, rep, userExtraArgs, func() bool { return reims.ProbeQEMUSupportsSMBIOSMemoryType(active.QemuPath(), c.Env) }, &in) - return in, nil + return in, consumeProvisionStaged, nil } -func (d *ReimsMacOSDriver) prepareOfflineHelper(cfg config.Config, cur reims.VMDetail, in *plugin.StartIntent) error { +func (d *ReimsMacOSDriver) prepareOfflineHelper(cfg config.Config, cur reims.VMDetail, in *plugin.StartIntent) (bool, error) { + // Per-VM REIMSPROV disk stays attached while installer, active recovery mode, + // or a freshly staged pre-boot provisioning marker is present, and is securely + // wiped + cleared once finish_install schedules removal or the VM leaves install. + inRecovery := startprep.IsRecoveryMarkerActive(cur.Directory) + wipePending := installer.HasProvisionWipePending(cur.Directory) + staged := installer.HasProvisionStagedMarker(cur.Directory) + consumeStaged := false + if !wipePending && installer.HasProvisionImage(cur.Directory) && (cur.HasInstaller || inRecovery || staged) { + in.Args = append(in.Args, plugin.ArgFragment{ + PluginID: d.opts.OwnerID, + Key: keyProvisionDisk, + Tokens: qmp.SplitArgs(reims.MergeProvisionArgs("", installer.ProvisionImagePath(cur.Directory))), + Builtin: true, + Priority: 84, + }) + if !cur.HasInstaller && !inRecovery && staged { + consumeStaged = true + } + } else { + in.ClearKeys = append(in.ClearKeys, keyProvisionDisk) + if wipePending || (!cur.HasInstaller && !inRecovery) { + if err := installer.SecureRemoveProvisionImage(cur.Directory); err != nil { + in.Warnings = append(in.Warnings, "could not remove offline provisioning disk (REIMSPROV): "+err.Error()) + } + } + } + if !cur.HasInstaller || !reims.IsOfflineInstallerPath(cur.InstallerPath) { in.ClearKeys = append(in.ClearKeys, keyOfflineHelper) - return nil + return consumeStaged, nil } helperPath, err := installer.EnsureOfflineHelperImage(cfg.XDGCacheDir(), cur.InstallerPath) if err != nil { - return fmt.Errorf("prepare offline install helper disk: %w", err) + return false, fmt.Errorf("prepare offline install helper disk: %w", err) } in.Args = append(in.Args, plugin.ArgFragment{PluginID: d.opts.OwnerID, Key: keyOfflineHelper, Tokens: qmp.SplitArgs(reims.MergeOfflineHelperArgs("", helperPath)), Builtin: true, Priority: 85}) - return nil + return consumeStaged, nil } func (d *ReimsMacOSDriver) prepareRecoveryBoot(ctx context.Context, c *reims.Client, name, vmDir string, log io.Writer) error { @@ -363,6 +395,7 @@ func startBaseArgs(extraArgs string, managedByDesktop bool, active map[string]bo } s = reims.StripGuestToolsNetworkArgs(s) s = reims.StripOfflineHelperArgs(s) + s = reims.StripProvisionArgs(s) s = qmp.StripLegacyWin10RebootArgs(s) s = reims.StripIncomingDeferArgs(s) return strings.TrimSpace(s) diff --git a/internal/macos/macosdriver/provision_prepare_test.go b/internal/macos/macosdriver/provision_prepare_test.go new file mode 100644 index 0000000..d3c7093 --- /dev/null +++ b/internal/macos/macosdriver/provision_prepare_test.go @@ -0,0 +1,100 @@ +package macosdriver + +import ( + "slices" + "testing" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/macos/installer" + "github.com/Nwflower/reims-go/internal/macos/reims" + "github.com/Nwflower/reims-go/internal/macos/startprep" + "github.com/Nwflower/reims-go/internal/plugin" +) + +func TestPrepareOfflineHelperProvisionLifecycle(t *testing.T) { + drv := &ReimsMacOSDriver{opts: Options{OwnerID: "builtin.guest.macos"}} + cfg := config.Config{} + buildProv := func(t *testing.T, vmDir string) { + t.Helper() + if _, err := installer.BuildProvisionDiskImage(vmDir, installer.ProvisionConfig{ + FullName: "Test User", + AccountName: "testuser", + Password: "TestPass-2026!", + Appearance: "dark", + SLAAccepted: true, + }); err != nil { + t.Fatalf("BuildProvisionDiskImage: %v", err) + } + } + + // 1. Freshly staged REIMSPROV on a normal-phase stopped VM (no installer, no recovery + // marker) MUST be attached on the first start instead of wiped, and consumes the + // one-shot staged marker so a subsequent normal boot wipes it cleanly. + vmDir := t.TempDir() + buildProv(t, vmDir) + cur := reims.VMDetail{Name: "norm-prov", Directory: vmDir, HasInstaller: false} + + var firstBoot plugin.StartIntent + consumeStaged, err := drv.prepareOfflineHelper(cfg, cur, &firstBoot) + if err != nil { + t.Fatalf("prepareOfflineHelper first boot: %v", err) + } + hasProvArg := false + for _, a := range firstBoot.Args { + if a.Key == keyProvisionDisk { + hasProvArg = true + } + } + if !hasProvArg { + t.Fatalf("expected freshly staged REIMSPROV attached on normal-phase start, got args=%+v", firstBoot.Args) + } + if !consumeStaged { + t.Fatal("expected consumeStaged=true for normal-phase start with staged marker") + } + if !installer.HasProvisionImage(vmDir) { + t.Fatal("freshly staged REIMSPROV image was prematurely wiped on first start") + } + // Staged marker must stay intact until StartWithCompat succeeds so a failed + // start does not cause the next boot to wipe the unused REIMSPROV image. + if !installer.HasProvisionStagedMarker(vmDir) { + t.Fatal("one-shot staged marker must not be cleared before StartWithCompat succeeds") + } + // Simulate StartWithCompat succeeding and consuming the staged marker. + installer.ClearProvisionStagedMarker(vmDir) + + // Subsequent normal-phase start wipes the consumed REIMSPROV image. + var secondBoot plugin.StartIntent + consumeSecond, err := drv.prepareOfflineHelper(cfg, cur, &secondBoot) + if err != nil { + t.Fatalf("prepareOfflineHelper second boot: %v", err) + } + if consumeSecond { + t.Fatal("consumeStaged must be false after staged marker was consumed") + } + if !slices.Contains(secondBoot.ClearKeys, keyProvisionDisk) { + t.Fatalf("expected keyProvisionDisk cleared on subsequent normal boot, got %+v", secondBoot) + } + if installer.HasProvisionImage(vmDir) { + t.Fatal("REIMSPROV image should be wiped on subsequent normal boot") + } + + // 2. When recovery marker is "restore" (exiting recovery after running finishInstall), + // prepareOfflineHelper must treat recovery as inactive and wipe REIMSPROV rather + // than re-attaching it. + vmDirRestore := t.TempDir() + buildProv(t, vmDirRestore) + installer.ClearProvisionStagedMarker(vmDirRestore) + startprep.WriteRecoveryMarker(vmDirRestore, "restore") + + var restoreBoot plugin.StartIntent + consumeRestore, err := drv.prepareOfflineHelper(cfg, reims.VMDetail{Name: "restore-prov", Directory: vmDirRestore}, &restoreBoot) + if err != nil { + t.Fatalf("prepareOfflineHelper restore boot: %v", err) + } + if consumeRestore || len(restoreBoot.Args) != 0 || !slices.Contains(restoreBoot.ClearKeys, keyProvisionDisk) { + t.Fatalf("recovery marker=restore must not re-attach REIMSPROV, got consume=%v args=%+v clear=%+v", consumeRestore, restoreBoot.Args, restoreBoot.ClearKeys) + } + if installer.HasProvisionImage(vmDirRestore) { + t.Fatal("REIMSPROV image must be wiped when recovery marker is restore") + } +} diff --git a/internal/macos/macosdriver/recovery.go b/internal/macos/macosdriver/recovery.go index 402cac0..dedeb3a 100644 --- a/internal/macos/macosdriver/recovery.go +++ b/internal/macos/macosdriver/recovery.go @@ -6,6 +6,7 @@ import ( "io" "strings" + "github.com/Nwflower/reims-go/internal/macos/installer" "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/macos/startprep" ) @@ -53,7 +54,7 @@ func (d *ReimsMacOSDriver) finishInstall(ctx context.Context, name string) (map[ return nil, err } } - stripped := reims.StripOfflineHelperArgs(det.ExtraArgs) + stripped := reims.StripProvisionArgs(reims.StripOfflineHelperArgs(det.ExtraArgs)) setOpts := reims.SetOpts{Name: name} needSet, upgradedNVMe := false, false if shouldEnableNetworkAfterInstall(det) { @@ -74,6 +75,11 @@ func (d *ReimsMacOSDriver) finishInstall(ctx context.Context, name string) (map[ return nil, err } } + // Securely wipe REIMSPROV now; if VM is still running and holds a Windows + // file handle, SecureRemoveProvisionImage records a pending-wipe marker so + // prepareOfflineHelper finishes the wipe on the next cold start without + // ever re-attaching the credential image. + wipeErr := installer.SecureRemoveProvisionImage(det.Directory) running := det.State == "running" marker := startprep.ReadRecoveryMarker(det.Directory) recoveryPending := running && marker == "on" @@ -97,11 +103,17 @@ func (d *ReimsMacOSDriver) finishInstall(ctx context.Context, name string) (map[ startprep.WriteRecoveryMarker(det.Directory, "") } } - return map[string]any{ + res := map[string]any{ "running": running, "upgraded_nvme": upgradedNVMe, "installer_ejected": det.HasInstaller, "network_enabled": setOpts.Network != nil, "disk_controller_from": det.DiskController, "recovery_pending": recoveryPending, - }, nil + "helper_stripped": stripped != det.ExtraArgs, + "provision_wiped": wipeErr == nil, + } + if wipeErr != nil { + res["provision_wipe_error"] = wipeErr.Error() + } + return res, nil } func shouldEnableNetworkAfterInstall(det reims.VMDetail) bool { diff --git a/internal/macos/reims/helper_args.go b/internal/macos/reims/helper_args.go index 6fdd12f..f289743 100644 --- a/internal/macos/reims/helper_args.go +++ b/internal/macos/reims/helper_args.go @@ -52,6 +52,43 @@ func MergeOfflineHelperArgs(existing, helperImgPath string) string { return base + " " + helperArgs } +// StripProvisionArgs removes any reims-go managed per-VM provisioning USB disk +// arguments from QEMU extra-args while leaving all other arguments intact. +func StripProvisionArgs(existing string) string { + tokens := qmp.SplitArgs(existing) + cleaned := make([]string, 0, len(tokens)) + for i := 0; i < len(tokens); i++ { + tok := tokens[i] + if tok == "-drive" && i+1 < len(tokens) && strings.Contains(tokens[i+1], "id=reimsprov,") { + i++ + continue + } + if tok == "-device" && i+1 < len(tokens) && strings.Contains(tokens[i+1], "id=reimsprov-dev,") { + i++ + continue + } + cleaned = append(cleaned, tok) + } + return strings.Join(cleaned, " ") +} + +// MergeProvisionArgs idempotently attaches provImgPath as a read-only USB +// storage volume on xhci.0 (appearing as /Volumes/REIMSPROV in macOS Recovery). +func MergeProvisionArgs(existing, provImgPath string) string { + base := StripProvisionArgs(existing) + escapedPath := strings.ReplaceAll(provImgPath, ",", ",,") + escapedPath = strings.ReplaceAll(escapedPath, `\`, `/`) + driveVal := fmt.Sprintf("id=reimsprov,if=none,format=raw,readonly=on,file=%s", escapedPath) + if strings.ContainsAny(driveVal, " \t") { + driveVal = `"` + strings.ReplaceAll(driveVal, `"`, `\"`) + `"` + } + provArgs := fmt.Sprintf("-drive %s -device usb-storage,id=reimsprov-dev,drive=reimsprov,bus=xhci.0", driveVal) + if base == "" { + return provArgs + } + return base + " " + provArgs +} + // HasGuestToolsArgs reports whether the REIMSTOOLS virtual USB disk is attached. func HasGuestToolsArgs(existing string) bool { return strings.Contains(existing, "id=reimstools,") diff --git a/internal/macos/reims/provision_args_test.go b/internal/macos/reims/provision_args_test.go new file mode 100644 index 0000000..ed7a5c2 --- /dev/null +++ b/internal/macos/reims/provision_args_test.go @@ -0,0 +1,22 @@ +package reims + +import ( + "strings" + "testing" +) + +func TestMergeAndStripProvisionArgs(t *testing.T) { + base := "-cpu host" + merged := MergeProvisionArgs(base, `D:\Data\vms\mac\.reims-go-provision.img`) + if !strings.Contains(merged, "id=reimsprov,") { + t.Fatalf("expected reimsprov drive arg, got %q", merged) + } + merged2 := MergeProvisionArgs(merged, `D:\My VMs\mac,1\.reims-go-provision.img`) + stripped := StripProvisionArgs(merged2) + if stripped != base { + t.Fatalf("StripProvisionArgs = %q, want %q", stripped, base) + } + if strings.Contains(stripped, "id=reimsprov,") { + t.Fatalf("expected reimsprov drive arg removed after strip") + } +} diff --git a/internal/macos/startprep/startprep.go b/internal/macos/startprep/startprep.go index affa7cd..90323ef 100644 --- a/internal/macos/startprep/startprep.go +++ b/internal/macos/startprep/startprep.go @@ -119,30 +119,49 @@ func (p *Prep) setExtraArgs(ctx context.Context, name, args string) error { } // syncOfflineHelper attaches the REIMSHELP HFS+ helper disk while an offline -// installer is attached, and strips it once the installer is ejected. +// installer is attached, and strips it once the installer is ejected. It also +// manages the per-VM REIMSPROV disk lifecycle. func (p *Prep) syncOfflineHelper(ctx context.Context, name string, cur *reims.VMDetail) { + extra := cur.ExtraArgs + inRecovery := IsRecoveryMarkerActive(cur.Directory) + wipePending := installer.HasProvisionWipePending(cur.Directory) + staged := installer.HasProvisionStagedMarker(cur.Directory) + consumeStaged := false + if !wipePending && installer.HasProvisionImage(cur.Directory) && (cur.HasInstaller || inRecovery || staged) { + extra = reims.MergeProvisionArgs(extra, installer.ProvisionImagePath(cur.Directory)) + if !cur.HasInstaller && !inRecovery && staged { + consumeStaged = true + } + } else { + extra = reims.StripProvisionArgs(extra) + if wipePending || (!cur.HasInstaller && !inRecovery) { + if err := installer.SecureRemoveProvisionImage(cur.Directory); err != nil { + p.log("Warning: could not remove offline provisioning disk (REIMSPROV): " + err.Error()) + } + } + } if cur.HasInstaller && reims.IsOfflineInstallerPath(cur.InstallerPath) { p.log("Preparing offline install helper disk (REIMSHELP)...") helperPath, err := installer.EnsureOfflineHelperImage(p.cfg.XDGCacheDir(), cur.InstallerPath) if err != nil { p.log("Warning: offline install helper disk skipped: " + err.Error()) + } else { + extra = reims.MergeOfflineHelperArgs(extra, helperPath) + } + } else { + extra = reims.StripOfflineHelperArgs(extra) + } + if extra != cur.ExtraArgs { + if err := p.setExtraArgs(ctx, name, extra); err != nil { + p.log("Warning: could not update offline helper disks: " + err.Error()) return } - merged := reims.MergeOfflineHelperArgs(cur.ExtraArgs, helperPath) - if merged != cur.ExtraArgs { - if err := p.setExtraArgs(ctx, name, merged); err != nil { - p.log("Warning: could not attach REIMSHELP disk: " + err.Error()) - return - } - cur.ExtraArgs = merged - } - return + cur.ExtraArgs = extra } - stripped := reims.StripOfflineHelperArgs(cur.ExtraArgs) - if stripped != cur.ExtraArgs { - if err := p.setExtraArgs(ctx, name, stripped); err == nil { - cur.ExtraArgs = stripped - } + // Only consume the one-shot staged marker after REIMSPROV args are committed + // so a failed setExtraArgs never causes the next cold start to wipe an unused image. + if consumeStaged { + installer.ClearProvisionStagedMarker(cur.Directory) } } @@ -268,6 +287,13 @@ func ReadRecoveryMarker(vmDir string) string { return strings.TrimSpace(string(b)) } +// IsRecoveryMarkerActive reports whether vmDir is currently in or scheduled to +// enter recovery mode ("on" or "want"), excluding "restore" (exiting recovery). +func IsRecoveryMarkerActive(vmDir string) bool { + m := ReadRecoveryMarker(vmDir) + return m == "on" || m == "want" +} + // WriteRecoveryMarker records state; "" removes the marker. func WriteRecoveryMarker(vmDir, state string) { if vmDir == "" { diff --git a/internal/macos/startprep/startprep_test.go b/internal/macos/startprep/startprep_test.go index 10f9497..b9395a9 100644 --- a/internal/macos/startprep/startprep_test.go +++ b/internal/macos/startprep/startprep_test.go @@ -35,3 +35,20 @@ func TestCheckWHPX(t *testing.T) { t.Fatalf("WHPXUnsupported (en-US) = %v", err) } } + +func TestIsRecoveryMarkerActive(t *testing.T) { + dir := t.TempDir() + if IsRecoveryMarkerActive(dir) { + t.Fatal("empty marker must not be active") + } + for _, state := range []string{"want", "on"} { + WriteRecoveryMarker(dir, state) + if !IsRecoveryMarkerActive(dir) { + t.Fatalf("marker %q should be active", state) + } + } + WriteRecoveryMarker(dir, "restore") + if IsRecoveryMarkerActive(dir) { + t.Fatal("marker \"restore\" (exiting recovery) must not be treated as active recovery") + } +} diff --git a/internal/plugin/broker.go b/internal/plugin/broker.go index a336f67..1629aa0 100644 --- a/internal/plugin/broker.go +++ b/internal/plugin/broker.go @@ -151,6 +151,11 @@ func netPermissionMatches(permission string, u *url.URL) bool { return spec == host } +// ErrNetOriginNotDeclared is returned by Broker.AuthorizeNetOrigin when the URL +// is syntactically valid and safe (no userinfo, allowed scheme, active plugin, +// within rate limits) but its origin is not listed in the plugin's net: grants. +var ErrNetOriginNotDeclared = errors.New("network origin not declared") + // AuthorizeNetOrigin checks that pluginID is active and may reach rawURL: the // URL must name a `net:` origin the plugin declared, use HTTPS (plain HTTP is // allowed for loopback only) and carry no user info. @@ -196,7 +201,7 @@ func (b *Broker) AuthorizeNetOrigin(pluginID, rawURL string) error { } } b.Audit(pluginID, "DENY", "undeclared network origin "+u.Scheme+"://"+u.Host) - return fmt.Errorf("plugin %q has not declared net:%s://%s", pluginID, u.Scheme, u.Host) + return fmt.Errorf("%w: plugin %q has not declared net:%s://%s", ErrNetOriginNotDeclared, pluginID, u.Scheme, u.Host) } func vmRefMapKey(driverID, name string) string { diff --git a/internal/plugin/builtin/bootstrap.go b/internal/plugin/builtin/bootstrap.go index 54e48fd..e352aa5 100644 --- a/internal/plugin/builtin/bootstrap.go +++ b/internal/plugin/builtin/bootstrap.go @@ -80,6 +80,15 @@ func BootstrapKernel(opts KernelBootstrapOptions) (*plugin.Manager, *driver.Rout return v, ok } } + if cb.PluginDataDir == nil { + cb.PluginDataDir = mgr.Layout().DataDir + } + if cb.PluginLogPath == nil { + cb.PluginLogPath = mgr.Layout().LogPath + } + if cb.CallHostAPI == nil { + cb.CallHostAPI = mgr.CallHostAPI + } if err := RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil { if opts.StrictRegister { diff --git a/internal/plugin/builtin/builtin.go b/internal/plugin/builtin/builtin.go index 5c2b26c..82eb73a 100644 --- a/internal/plugin/builtin/builtin.go +++ b/internal/plugin/builtin/builtin.go @@ -68,6 +68,13 @@ type HostCallbacks struct { SyncInstallGuides func() // GetSetting returns a saved plugin setting value (empty vmName = app scope). GetSetting func(pluginID, vmName, key string) (any, bool) + // PluginDataDir returns the private writable data directory for pluginID. + PluginDataDir func(pluginID string) string + // PluginLogPath returns the audit log path for pluginID. + PluginLogPath func(pluginID string) string + // CallHostAPI invokes a host-owned reverse RPC handler through the plugin + // manager's permission and audit pipeline. + CallHostAPI func(ctx context.Context, pluginID, method string, params any, out any) error } func appVersion() string { diff --git a/internal/plugin/contract.go b/internal/plugin/contract.go index dda67e8..2207b6e 100644 --- a/internal/plugin/contract.go +++ b/internal/plugin/contract.go @@ -53,6 +53,7 @@ var ContributionCatalog = map[string]ContractStatus{ "statusItems": ContractExperimental, "panels": ContractStable, "imageSources": ContractStable, + "autoInstallers": ContractStable, "views": ContractStable, "diagnostics": ContractExperimental, } @@ -147,7 +148,7 @@ var ThemeIconNames = []string{ "settings", "plugin", "folder", "logs", "screenshot", "fullscreen", "window", "snapshot", "clone", "delete", "info", "warning", "error", "vm.state.running", "vm.state.stopped", "vm.state.suspended", "vm.state.busy", "vm.state.error", - "guest-linux", "guest-windows", "guest-android", "remote-desktop", "terminal", + "guest-linux", "guest-windows", "guest-android", "remote-desktop", "remote-control", "terminal", } // GuestDriverFieldCatalog lists `guestDrivers[]` fields whose host support is @@ -174,9 +175,18 @@ var HostCapabilityCatalog = map[string]ContractStatus{ "host.vm.spawn.ref": ContractStable, "host.vm.reportState": ContractStable, "driver.console": ContractStable, - "host.download": ContractStable, - "host.elevate.request": ContractStable, - "host.secret.materialize": ContractStable, + "host.download": ContractStable, + "host.download.timeouts": ContractStable, + "host.download.customMirror": ContractStable, + "host.elevate.request": ContractStable, + "host.secret.materialize": ContractStable, + "host.ui.confirm": ContractStable, + "host.session": ContractStable, + "host.console.screenshot.region": ContractStable, + "host.vm.finishInstall": ContractStable, + "host.vm.restart": ContractStable, + "host.vm.telemetry": ContractStable, + "event.vm.phaseChanged": ContractStable, } // BridgeMethodSpec describes one plugin UI bridge method. @@ -380,6 +390,31 @@ func validateUIContract(m Manifest) error { } } } + seenAutoInstallers := map[string]bool{} + validFamilies := map[string]bool{"macos": true, "linux": true, "windows": true, "android": true} + for _, ai := range m.Contributes.AutoInstallers { + if !reContributionID.MatchString(ai.ID) { + return fmt.Errorf("invalid autoInstaller id %q", ai.ID) + } + if seenAutoInstallers[ai.ID] { + return fmt.Errorf("duplicate autoInstaller id %q", ai.ID) + } + seenAutoInstallers[ai.ID] = true + if !ai.Title.HasAny() { + return fmt.Errorf("autoInstaller %q is missing a localized title", ai.ID) + } + if len(ai.GuestFamilies) == 0 { + return fmt.Errorf("autoInstaller %q must declare at least one guest family", ai.ID) + } + for _, fam := range ai.GuestFamilies { + if !validFamilies[strings.ToLower(strings.TrimSpace(fam))] { + return fmt.Errorf("autoInstaller %q has unknown guest family %q", ai.ID, fam) + } + } + if strings.TrimSpace(m.Entry.Sidecar) == "" { + return fmt.Errorf("autoInstaller %q requires entry.sidecar", ai.ID) + } + } perLocation := map[string]int{} seenViews := map[string]bool{} for _, v := range m.Contributes.Views { diff --git a/internal/plugin/contract_test.go b/internal/plugin/contract_test.go index 8a93525..50f9d3e 100644 --- a/internal/plugin/contract_test.go +++ b/internal/plugin/contract_test.go @@ -153,7 +153,7 @@ func TestHostFeaturesAreStableOnly(t *testing.T) { for _, f := range features { has[f] = true } - for _, want := range []string{"bridge.hello", "bridge.vm.list", "bridge.file.pick", "contrib.views", "view.sidebar", "event.theme.changed", "event.vm.stateChanged", "event.task.updated", "event.view.visibilityChanged", "slot.sidebar.footer", "slot.settings.plugin.panel", "slot.vm.toolbar.menu", "contrib.themes", "contrib.imageSources", "slot.vm.toolbar", "slot.nav.item.trailing", "layer.overlay", "layer.background", "theme.icons", "theme.layout", "theme.brandMark"} { + for _, want := range []string{"bridge.hello", "bridge.vm.list", "bridge.file.pick", "contrib.views", "contrib.autoInstallers", "view.sidebar", "event.theme.changed", "event.vm.stateChanged", "event.task.updated", "event.view.visibilityChanged", "event.vm.phaseChanged", "host.ui.confirm", "host.session", "host.console.screenshot.region", "host.vm.finishInstall", "host.vm.restart", "host.vm.telemetry", "slot.sidebar.footer", "slot.settings.plugin.panel", "slot.vm.toolbar.menu", "contrib.themes", "contrib.imageSources", "slot.vm.toolbar", "slot.nav.item.trailing", "layer.overlay", "layer.background", "theme.icons", "theme.layout", "theme.brandMark"} { if !has[want] { t.Errorf("missing stable feature %s", want) } @@ -245,6 +245,17 @@ func TestValidateUIContract(t *testing.T) { {"image source escaping entry", func(m *Manifest) { m.Contributes.ImageSources = []ImageSourceContribution{{ID: "linux", Title: LocalizedText{EnUS: "Linux"}, Entry: "../escape.html"}} }, "invalid image source"}, + {"valid autoInstaller", func(m *Manifest) { + m.Entry.Sidecar = "bin/auto.exe" + m.Contributes.AutoInstallers = []AutoInstallerContribution{{ID: "macos-local", Title: LocalizedText{EnUS: "macOS Auto-Install"}, GuestFamilies: []string{"macos"}}} + }, ""}, + {"autoInstaller without sidecar", func(m *Manifest) { + m.Contributes.AutoInstallers = []AutoInstallerContribution{{ID: "macos-local", Title: LocalizedText{EnUS: "macOS Auto-Install"}, GuestFamilies: []string{"macos"}}} + }, "requires entry.sidecar"}, + {"autoInstaller unknown family", func(m *Manifest) { + m.Entry.Sidecar = "bin/auto.exe" + m.Contributes.AutoInstallers = []AutoInstallerContribution{{ID: "bsd", Title: LocalizedText{EnUS: "BSD"}, GuestFamilies: []string{"bsd"}}} + }, "unknown guest family"}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { diff --git a/internal/plugin/inprocess_endpoint_test.go b/internal/plugin/inprocess_endpoint_test.go new file mode 100644 index 0000000..e0ef4c3 --- /dev/null +++ b/internal/plugin/inprocess_endpoint_test.go @@ -0,0 +1,212 @@ +package plugin + +import ( + "context" + "encoding/json" + "errors" + "sync" + "testing" +) + +type stubInProcessEndpoint struct { + mu sync.Mutex + calls []string + notifications []string + onCall func(ctx context.Context, method string, params any, out any) error +} + +func (s *stubInProcessEndpoint) Call(ctx context.Context, method string, params any, out any) error { + s.mu.Lock() + s.calls = append(s.calls, method) + fn := s.onCall + s.mu.Unlock() + if fn != nil { + return fn(ctx, method, params, out) + } + return nil +} + +func (s *stubInProcessEndpoint) Notify(method string, _ any) { + s.mu.Lock() + s.notifications = append(s.notifications, method) + s.mu.Unlock() +} + +func TestInProcessEndpointLifecycleAndRouting(t *testing.T) { + dataRoot := t.TempDir() + var ( + mu sync.Mutex + hostCalledWith string + ) + mgr, err := NewManager(ManagerOptions{ + DataRoot: dataRoot, + HostVersion: "0.2.12", + HostHandlers: func(pluginID string) map[string]RPCRequestHandler { + return map[string]RPCRequestHandler{ + "host/test.echo": func(_ context.Context, raw json.RawMessage) (any, error) { + var req struct { + Text string `json:"text"` + } + if err := json.Unmarshal(raw, &req); err != nil { + return nil, err + } + mu.Lock() + hostCalledWith = pluginID + ":" + req.Text + mu.Unlock() + return map[string]any{"echo": req.Text}, nil + }, + } + }, + }) + if err != nil { + t.Fatalf("NewManager: %v", err) + } + + var notifiedTitle string + mgr.Broker().SetNotifier(func(_ string, title, _ string) { + notifiedTitle = title + }) + + ep := &stubInProcessEndpoint{ + onCall: func(_ context.Context, method string, params any, out any) error { + if method != "demo/ping" { + return errors.New("unexpected method") + } + b, _ := json.Marshal(map[string]any{"ok": true, "got": params}) + return json.Unmarshal(b, out) + }, + } + + const pid = "builtin.demo.inprocess" + if err := mgr.Registry().Register(PluginDef{ + Manifest: Manifest{ + Schema: 1, + ID: pid, + Version: "0.1.0", + Name: LocalizedText{EnUS: "Demo In-Process"}, + Permissions: []string{"ui:notify"}, + }, + Source: SourceBuiltin, + Trust: TrustOfficial, + Desired: true, + Activate: func(_ context.Context, sc *Scope) error { + sc.Registry().RegisterInProcessEndpoint(sc, ep) + return nil + }, + }); err != nil { + t.Fatalf("Register: %v", err) + } + mgr.Registry().Reconcile(context.Background()) + + // CallSidecar routes to active in-process endpoint. + var pingOut struct { + OK bool `json:"ok"` + } + if err := mgr.CallSidecar(context.Background(), pid, "demo/ping", map[string]any{"n": 1}, &pingOut); err != nil { + t.Fatalf("CallSidecar: %v", err) + } + if !pingOut.OK { + t.Fatalf("expected ok=true, got %+v", pingOut) + } + + // NotifySidecar and NotifyRunningSidecars deliver to active in-process endpoint. + mgr.NotifySidecar(pid, "download/progress", map[string]any{"id": "dl-1"}) + mgr.NotifyRunningSidecars("console/userTakeover", map[string]any{"vm": "mac"}) + ep.mu.Lock() + gotNotifs := append([]string(nil), ep.notifications...) + ep.mu.Unlock() + if len(gotNotifs) != 2 || gotNotifs[0] != "download/progress" || gotNotifs[1] != "console/userTakeover" { + t.Fatalf("unexpected notifications: %v", gotNotifs) + } + + // CallHostAPI dispatches host/notify via broker and custom hostHandlers. + if err := mgr.CallHostAPI(context.Background(), pid, "host/notify", map[string]any{"title": "Hi", "body": "Ready"}, nil); err != nil { + t.Fatalf("CallHostAPI host/notify: %v", err) + } + if notifiedTitle != "Hi" { + t.Fatalf("expected broker notification Hi, got %q", notifiedTitle) + } + + var echoOut struct { + Echo string `json:"echo"` + } + if err := mgr.CallHostAPI(context.Background(), pid, "host/test.echo", map[string]any{"text": "hello"}, &echoOut); err != nil { + t.Fatalf("CallHostAPI host/test.echo: %v", err) + } + if echoOut.Echo != "hello" { + t.Fatalf("expected echo=hello, got %+v", echoOut) + } + mu.Lock() + called := hostCalledWith + mu.Unlock() + if called != pid+":hello" { + t.Fatalf("unexpected host handler call: %q", called) + } + + // Disabling removes endpoint with zero residue and blocks CallHostAPI. + if err := mgr.Disable(context.Background(), pid); err != nil { + t.Fatalf("Disable: %v", err) + } + if mgr.Registry().InProcessEndpoint(pid) != nil { + t.Fatal("expected in-process endpoint to be removed on disable") + } + if err := mgr.CallSidecar(context.Background(), pid, "demo/ping", nil, &pingOut); err == nil { + t.Fatal("expected CallSidecar to fail after disable") + } + if err := mgr.CallHostAPI(context.Background(), pid, "host/test.echo", map[string]any{"text": "blocked"}, &echoOut); err == nil { + t.Fatal("expected CallHostAPI to fail when plugin is disabled") + } +} + +func TestAutoInstallersPreferBuiltinFirst(t *testing.T) { + reg := NewRegistry(nil) + if err := reg.Register(PluginDef{ + Manifest: Manifest{ + Schema: 1, + ID: "aaa.thirdparty.autoinstall", + Version: "1.0.0", + Name: LocalizedText{EnUS: "Third Party"}, + Contributes: Contributes{ + AutoInstallers: []AutoInstallerContribution{{ + ID: "thirdparty", + Title: LocalizedText{EnUS: "Third Party"}, + GuestFamilies: []string{"macos"}, + }}, + }, + }, + Source: SourceLocal, + Trust: TrustCommunity, + Desired: true, + }); err != nil { + t.Fatalf("register third-party: %v", err) + } + if err := reg.Register(PluginDef{ + Manifest: Manifest{ + Schema: 1, + ID: "builtin.macos.autoinstall", + Version: "1.0.0", + Name: LocalizedText{EnUS: "Built-in Auto-Install"}, + Contributes: Contributes{ + AutoInstallers: []AutoInstallerContribution{{ + ID: "macos-local", + Title: LocalizedText{EnUS: "Built-in Auto-Install"}, + GuestFamilies: []string{"macos"}, + }}, + }, + }, + Source: SourceBuiltin, + Trust: TrustOfficial, + Desired: true, + }); err != nil { + t.Fatalf("register builtin: %v", err) + } + reg.Reconcile(context.Background()) + + list := reg.AutoInstallersForFamily("macos") + if len(list) != 2 { + t.Fatalf("expected 2 providers, got %d", len(list)) + } + if list[0].PluginID != "builtin.macos.autoinstall" { + t.Fatalf("expected builtin provider first, got %q", list[0].PluginID) + } +} diff --git a/internal/plugin/manager.go b/internal/plugin/manager.go index 3350a03..8c7c589 100644 --- a/internal/plugin/manager.go +++ b/internal/plugin/manager.go @@ -126,16 +126,26 @@ func NewManager(opts ManagerOptions) (*Manager, error) { return m, nil } -func (m *Manager) Registry() *Registry { return m.registry } -func (m *Manager) Broker() *Broker { return m.broker } +func (m *Manager) Registry() *Registry { + if m == nil { + return nil + } + return m.registry +} +func (m *Manager) Broker() *Broker { + if m == nil { + return nil + } + return m.broker +} func (m *Manager) Assets() *AssetServer { return m.assets } func (m *Manager) Layout() PluginsLayout { return m.layout } func (m *Manager) SafeMode() bool { return m.safeMode } func (m *Manager) CrashDetected() bool { return m.crashDetected } // NotifySidecar sends a fire-and-forget notification (such as -// `download/progress`) to pluginID's running Sidecar. It never wakes an idle -// Sidecar and is a no-op when there is none. +// `download/progress`) to pluginID's running Sidecar or active in-process +// endpoint. It never wakes an idle Sidecar and is a no-op when there is none. func (m *Manager) NotifySidecar(pluginID, method string, params any) { if m == nil { return @@ -145,7 +155,146 @@ func (m *Manager) NotifySidecar(pluginID, method string, params any) { m.mu.RUnlock() if supervisor != nil { supervisor.NotifyIfRunning(method, params) + return } + if m.registry != nil { + if ep := m.registry.InProcessEndpoint(pluginID); ep != nil { + ep.Notify(method, params) + } + } +} + +// NotifyRunningSidecars broadcasts a notification to every currently running +// Sidecar and active in-process endpoint without waking idle Sidecars. +func (m *Manager) NotifyRunningSidecars(method string, params any) { + if m == nil { + return + } + m.mu.RLock() + sups := make([]*SidecarSupervisor, 0, len(m.supervisors)) + for _, sup := range m.supervisors { + if sup != nil { + sups = append(sups, sup) + } + } + m.mu.RUnlock() + for _, sup := range sups { + sup.NotifyIfRunning(method, params) + } + if m.registry != nil { + for _, ep := range m.registry.InProcessEndpoints() { + ep.Notify(method, params) + } + } +} + +// CallSidecar invokes a JSON-RPC method on pluginID's Sidecar supervisor +// (starting it lazily if needed) or active in-process endpoint. +func (m *Manager) CallSidecar(ctx context.Context, pluginID, method string, params any, out any) error { + if m == nil { + return errors.New("plugin manager is unavailable") + } + m.mu.RLock() + supervisor := m.supervisors[pluginID] + m.mu.RUnlock() + if supervisor != nil { + return supervisor.Call(ctx, method, params, out) + } + if m.registry != nil { + if ep := m.registry.InProcessEndpoint(pluginID); ep != nil { + return ep.Call(ctx, method, params, out) + } + } + return fmt.Errorf("plugin %q has no active sidecar or in-process endpoint", pluginID) +} + +// CallHostAPI invokes a host-owned reverse RPC handler on behalf of an active +// in-process plugin. Built-in methods ("host/notify", "host/audit") go through +// the broker directly, and all other methods dispatch to the same HostHandlers +// map registered as Sidecar ExtraHandlers (where the host embedder wraps every +// handler with catalog permission authorization, strict param decoding, and +// audit logging). +func (m *Manager) CallHostAPI(ctx context.Context, pluginID, method string, params any, out any) error { + if m == nil || m.registry == nil { + return errors.New("plugin manager is unavailable") + } + if !m.registry.IsActive(pluginID) { + return fmt.Errorf("plugin %q is not active", pluginID) + } + if ctx == nil { + ctx = context.Background() + } + + var rawParams json.RawMessage + switch v := params.(type) { + case nil: + rawParams = json.RawMessage("{}") + case json.RawMessage: + if len(v) == 0 { + rawParams = json.RawMessage("{}") + } else { + rawParams = v + } + default: + b, err := json.Marshal(v) + if err != nil { + return fmt.Errorf("marshal host API params for %s: %w", method, err) + } + rawParams = b + } + + var ( + res any + err error + ) + switch method { + case "host/notify": + if m.broker == nil { + return errors.New("broker unavailable") + } + var req struct { + Title string `json:"title"` + Body string `json:"body"` + } + if err := json.Unmarshal(rawParams, &req); err != nil { + return err + } + res, err = map[string]any{"ok": true}, m.broker.Notify(pluginID, req.Title, req.Body) + case "host/audit": + if m.broker != nil { + if !m.broker.allowRate(pluginID) { + return fmt.Errorf("plugin %q exceeded audit rate limit", pluginID) + } + var req struct { + Message string `json:"message"` + } + _ = json.Unmarshal(rawParams, &req) + m.broker.Audit(pluginID, "PLUGIN", req.Message) + } + res = map[string]any{"ok": true} + default: + var handler RPCRequestHandler + if m.opts.HostHandlers != nil { + handler = m.opts.HostHandlers(pluginID)[method] + } + if handler == nil { + return fmt.Errorf("host API method %q is unavailable", method) + } + res, err = handler(ctx, rawParams) + } + if err != nil { + return err + } + if out != nil { + b, err := json.Marshal(res) + if err != nil { + return fmt.Errorf("marshal host API response for %s: %w", method, err) + } + if err := json.Unmarshal(b, out); err != nil { + return fmt.Errorf("decode host API response for %s: %w", method, err) + } + } + return nil } // ChannelSessionClosed tells pluginID's running Sidecar that one client diff --git a/internal/plugin/registry.go b/internal/plugin/registry.go index 489ada9..40c6ec8 100644 --- a/internal/plugin/registry.go +++ b/internal/plugin/registry.go @@ -86,6 +86,14 @@ type RegisteredDownloader struct { Provider downloader.Provider } +// InProcessEndpoint handles JSON-RPC-style calls and fire-and-forget +// notifications for a compiled-in plugin using the same protocol as an L3 +// Sidecar. +type InProcessEndpoint interface { + Call(ctx context.Context, method string, params any, out any) error + Notify(method string, params any) +} + // Registry is the unified extension-point and lifecycle kernel for both // compiled-in builtins and external/bundled plugins. type Registry struct { @@ -120,8 +128,10 @@ type Registry struct { statusItems []StatusItemContribution panels []PanelContribution views []ViewContribution - imageSources []ImageSourceContribution - diagnostics []RegisteredDiagnostics + imageSources []ImageSourceContribution + autoInstallers []AutoInstallerContribution + diagnostics []RegisteredDiagnostics + inProcessEndpoints map[string]InProcessEndpoint } // NewRegistry creates an initialized plugin registry. @@ -134,9 +144,10 @@ func NewRegistry(logger func(source, line string)) *Registry { uiScripts: make(map[string]UIScriptContribution), locales: make(map[string][]LocaleContribution), runtimeKinds: make(map[string]RuntimeKindContribution), - guestDrivers: make(map[string]any), - downloaders: make(map[string]RegisteredDownloader), - commands: make(map[string]RegisteredCommand), + guestDrivers: make(map[string]any), + downloaders: make(map[string]RegisteredDownloader), + commands: make(map[string]RegisteredCommand), + inProcessEndpoints: make(map[string]InProcessEndpoint), } r.hooks = NewHookBus(r) return r @@ -630,6 +641,10 @@ func (r *Registry) registerManifestContributions(sc *Scope, m Manifest) { src.PluginID = pid r.RegisterImageSource(sc, src) } + for _, ai := range m.Contributes.AutoInstallers { + ai.PluginID = pid + r.RegisterAutoInstaller(sc, ai) + } // Register L1 declarative rule hooks on the hook bus. if len(m.Contributes.RuleHooks) > 0 { rules := append([]RuleHook(nil), m.Contributes.RuleHooks...) @@ -1409,6 +1424,133 @@ func (r *Registry) ImageSources() []ImageSourceContribution { return out } +func (r *Registry) RegisterAutoInstaller(sc *Scope, ai AutoInstallerContribution) { + ai.ID = strings.TrimSpace(ai.ID) + if ai.ID == "" { + return + } + ai.PluginID = sc.PluginID() + fams := make([]string, 0, len(ai.GuestFamilies)) + for _, f := range ai.GuestFamilies { + if norm := strings.ToLower(strings.TrimSpace(f)); norm != "" { + fams = append(fams, norm) + } + } + ai.GuestFamilies = fams + if strings.TrimSpace(ai.SecretSetting) == "" { + ai.SecretSetting = "account_password" + } + r.mu.Lock() + replaced := false + for i, existing := range r.autoInstallers { + if existing.PluginID == ai.PluginID && existing.ID == ai.ID { + r.autoInstallers[i] = ai + replaced = true + break + } + } + if !replaced { + r.autoInstallers = append(r.autoInstallers, ai) + } + r.mu.Unlock() + sc.OnDispose(func() { + r.mu.Lock() + kept := r.autoInstallers[:0] + for _, item := range r.autoInstallers { + if !(item.PluginID == sc.PluginID() && item.ID == ai.ID) { + kept = append(kept, item) + } + } + r.autoInstallers = kept + r.mu.Unlock() + }) +} + +func (r *Registry) AutoInstallers() []AutoInstallerContribution { + r.mu.RLock() + out := make([]AutoInstallerContribution, len(r.autoInstallers)) + builtinSet := make(map[string]bool, len(r.autoInstallers)) + for i, item := range r.autoInstallers { + cp := item + cp.GuestFamilies = append([]string(nil), item.GuestFamilies...) + out[i] = cp + if e, ok := r.entries[item.PluginID]; ok && e.def.Source == SourceBuiltin { + builtinSet[item.PluginID] = true + } + } + r.mu.RUnlock() + sort.SliceStable(out, func(i, j int) bool { + bi := builtinSet[out[i].PluginID] + bj := builtinSet[out[j].PluginID] + if bi != bj { + return bi + } + if out[i].PluginID != out[j].PluginID { + return out[i].PluginID < out[j].PluginID + } + return out[i].ID < out[j].ID + }) + return out +} + +// RegisterInProcessEndpoint binds an in-process RPC endpoint to sc. Disposing +// sc removes the endpoint so disabled built-in plugins leave zero residue. +func (r *Registry) RegisterInProcessEndpoint(sc *Scope, ep InProcessEndpoint) { + if sc == nil || ep == nil { + return + } + pid := sc.PluginID() + r.mu.Lock() + r.inProcessEndpoints[pid] = ep + r.mu.Unlock() + sc.OnDispose(func() { + r.mu.Lock() + if r.inProcessEndpoints[pid] == ep { + delete(r.inProcessEndpoints, pid) + } + r.mu.Unlock() + }) +} + +// InProcessEndpoint returns the active in-process endpoint for pluginID, if any. +func (r *Registry) InProcessEndpoint(pluginID string) InProcessEndpoint { + r.mu.RLock() + ep := r.inProcessEndpoints[pluginID] + r.mu.RUnlock() + return ep +} + +// InProcessEndpoints returns a snapshot of all active in-process endpoints. +func (r *Registry) InProcessEndpoints() []InProcessEndpoint { + r.mu.RLock() + out := make([]InProcessEndpoint, 0, len(r.inProcessEndpoints)) + for _, ep := range r.inProcessEndpoints { + if ep != nil { + out = append(out, ep) + } + } + r.mu.RUnlock() + return out +} + +func (r *Registry) AutoInstallersForFamily(family string) []AutoInstallerContribution { + want := strings.ToLower(strings.TrimSpace(family)) + all := r.AutoInstallers() + if want == "" { + return all + } + out := make([]AutoInstallerContribution, 0, len(all)) + for _, item := range all { + for _, f := range item.GuestFamilies { + if f == want { + out = append(out, item) + break + } + } + } + return out +} + func (r *Registry) RegisterDiagnostics(sc *Scope, contrib DiagnosticsContribution, collector DiagnosticsCollector) { if collector == nil { return diff --git a/internal/plugin/types.go b/internal/plugin/types.go index 2ad3a1a..1748846 100644 --- a/internal/plugin/types.go +++ b/internal/plugin/types.go @@ -19,7 +19,7 @@ const ( PluginAPIVersion = "1.3.0" // UIAPIVersion is the frontend UI contract version (SemVer); the contract // itself lives in frontend/src/styles/ui-contract.ts (§5.1, §6.3). - UIAPIVersion = "2.1.0" + UIAPIVersion = "2.2.0" // BridgeAPIVersion is the plugin view/panel bridge protocol version (§5.6); // methods are listed in BridgeMethodCatalog. BridgeAPIVersion = "1.0.0" @@ -325,6 +325,7 @@ type Contributes struct { StatusItems []StatusItemContribution `json:"statusItems,omitempty"` Panels []PanelContribution `json:"panels,omitempty"` ImageSources []ImageSourceContribution `json:"imageSources,omitempty"` + AutoInstallers []AutoInstallerContribution `json:"autoInstallers,omitempty"` Views []ViewContribution `json:"views,omitempty"` Diagnostics []DiagnosticsContribution `json:"diagnostics,omitempty"` } @@ -647,6 +648,19 @@ type ImageSourceContribution struct { PluginID string `json:"pluginId,omitempty"` } +// AutoInstallerContribution declares a built-in or Sidecar-backed unattended +// guest installer (such as local-vision macOS setup). Host UI and CLI discover +// enabled contributions by guest family and leave zero residue when disabled. +type AutoInstallerContribution struct { + ID string `json:"id"` + Title LocalizedText `json:"title"` + Description LocalizedText `json:"description,omitempty"` + GuestFamilies []string `json:"guestFamilies"` + RequiresOfflineInstaller bool `json:"requiresOfflineInstaller,omitempty"` + SecretSetting string `json:"secretSetting,omitempty"` + PluginID string `json:"pluginId,omitempty"` +} + // ViewContribution declares a sandboxed iframe view with its own page, tab or // dialog (§5.6). Entry is relative to entry.panelDir; Location is one of // ViewLocationCatalog. diff --git a/internal/thumb/preview.go b/internal/thumb/preview.go index 4be5fd2..255dea7 100644 --- a/internal/thumb/preview.go +++ b/internal/thumb/preview.go @@ -4,6 +4,7 @@ import ( "bufio" "fmt" "image" + "image/color" "io" "os" ) @@ -88,3 +89,176 @@ func LoadPreviewFrame(path, format string, maxWidth int) (image.Image, bool, err } return img, samples.blank(), nil } + +// LoadRegionFrame decodes an optional source-pixel region of a PPM or PNG +// screendump without loading the entire frame into heap for PPM inputs. +// When maxEdge > 0 and either output dimension exceeds maxEdge, the output is +// box-filtered down proportionally; when maxEdge == 0, the crop stays 1:1. +func LoadRegionFrame(path, format string, region *image.Rectangle, maxEdge int) (image.Image, image.Rectangle, bool, error) { + if maxEdge < 0 { + return nil, image.Rectangle{}, false, fmt.Errorf("invalid max_edge %d", maxEdge) + } + if format == "png" { + src, err := Load(path, format) + if err != nil { + return nil, image.Rectangle{}, false, err + } + sb := src.Bounds() + crop := sb + if region != nil { + crop = region.Add(sb.Min).Intersect(sb) + if crop.Empty() { + return nil, image.Rectangle{}, false, fmt.Errorf("region %v is outside frame %dx%d", *region, sb.Dx(), sb.Dy()) + } + } + cropped := cropImage(src, crop) + blank := Blank(cropped) + var out image.Image = cropped + if maxEdge > 0 { + out = scaleMaxEdge(cropped, maxEdge) + } + return out, crop.Sub(sb.Min), blank, nil + } + if format != "ppm" { + return nil, image.Rectangle{}, false, fmt.Errorf("unsupported screendump format %q", format) + } + + f, err := os.Open(path) + if err != nil { + return nil, image.Rectangle{}, false, err + } + defer f.Close() + r := bufio.NewReader(f) + size, err := ppmSize(r) + if err != nil { + return nil, image.Rectangle{}, false, err + } + full := image.Rect(0, 0, size.X, size.Y) + crop := full + if region != nil { + crop = region.Intersect(full) + if crop.Empty() { + return nil, image.Rectangle{}, false, fmt.Errorf("region %v is outside frame %dx%d", *region, size.X, size.Y) + } + } + cw, ch := crop.Dx(), crop.Dy() + dw, dh := cw, ch + if maxEdge > 0 && (cw > maxEdge || ch > maxEdge) { + if cw >= ch { + dw = maxEdge + dh = max(1, ch*dw/cw) + } else { + dh = maxEdge + dw = max(1, cw*dh/ch) + } + } + + rowBytes := int64(size.X) * 3 + if crop.Min.Y > 0 { + if _, err := io.CopyN(io.Discard, r, int64(crop.Min.Y)*rowBytes); err != nil { + return nil, image.Rectangle{}, false, fmt.Errorf("ppm skip: %w", err) + } + } + + img := image.NewRGBA(image.Rect(0, 0, dw, dh)) + row := make([]byte, size.X*3) + stepX := max(1, cw/64) + stepY := max(1, ch/32) + var samples blankSamples + + if dw == cw && dh == ch { + for y := 0; y < ch; y++ { + if _, err := io.ReadFull(r, row); err != nil { + return nil, image.Rectangle{}, false, fmt.Errorf("ppm: %w", err) + } + drow := img.Pix[y*img.Stride:] + for x := 0; x < cw; x++ { + soff := (crop.Min.X + x) * 3 + red, green, blue := row[soff], row[soff+1], row[soff+2] + if y%stepY == 0 && x%stepX == 0 { + samples.add(red, green, blue) + } + doff := x * 4 + drow[doff], drow[doff+1], drow[doff+2], drow[doff+3] = red, green, blue, 255 + } + } + return img, crop, samples.blank(), nil + } + + sums := make([][3]uint64, dw) + for y := 0; y < dh; y++ { + y0, y1 := y*ch/dh, (y+1)*ch/dh + if y1 <= y0 { + y1 = y0 + 1 + } + clear(sums) + for sy := y0; sy < y1; sy++ { + if _, err := io.ReadFull(r, row); err != nil { + return nil, image.Rectangle{}, false, fmt.Errorf("ppm: %w", err) + } + if sy%stepY == 0 { + for x := 0; x < cw; x += stepX { + soff := (crop.Min.X + x) * 3 + samples.add(row[soff], row[soff+1], row[soff+2]) + } + } + for x := range sums { + x0 := crop.Min.X + x*cw/dw + x1 := crop.Min.X + (x+1)*cw/dw + if x1 <= x0 { + x1 = x0 + 1 + } + block := row[3*x0 : 3*x1] + var red, green, blue uint32 + for i := 0; i < len(block); i += 3 { + red += uint32(block[i]) + green += uint32(block[i+1]) + blue += uint32(block[i+2]) + } + sums[x][0] += uint64(red) + sums[x][1] += uint64(green) + sums[x][2] += uint64(blue) + } + } + for x, sum := range sums { + dx0 := x * cw / dw + dx1 := (x + 1) * cw / dw + if dx1 <= dx0 { + dx1 = dx0 + 1 + } + pixels := uint64((dx1 - dx0) * (y1 - y0)) + img.SetRGBA(x, y, color.RGBA{uint8(sum[0] / pixels), uint8(sum[1] / pixels), uint8(sum[2] / pixels), 255}) + } + } + return img, crop, samples.blank(), nil +} + +func cropImage(src image.Image, rect image.Rectangle) *image.RGBA { + dst := image.NewRGBA(image.Rect(0, 0, rect.Dx(), rect.Dy())) + for y := 0; y < rect.Dy(); y++ { + for x := 0; x < rect.Dx(); x++ { + r, g, b, a := src.At(rect.Min.X+x, rect.Min.Y+y).RGBA() + dst.SetRGBA(x, y, color.RGBA{uint8(r >> 8), uint8(g >> 8), uint8(b >> 8), uint8(a >> 8)}) + } + } + return dst +} + +func scaleMaxEdge(img *image.RGBA, maxEdge int) image.Image { + b := img.Bounds() + sw, sh := b.Dx(), b.Dy() + if sw <= maxEdge && sh <= maxEdge { + return img + } + var dw, dh int + if sw >= sh { + dw = maxEdge + dh = max(1, sh*dw/sw) + } else { + dh = maxEdge + dw = max(1, sw*dh/sh) + } + dst := image.NewRGBA(image.Rect(0, 0, dw, dh)) + scaleRGBA(dst, img, sw, sh, dw, dh) + return dst +} diff --git a/internal/thumb/region_test.go b/internal/thumb/region_test.go new file mode 100644 index 0000000..4270182 --- /dev/null +++ b/internal/thumb/region_test.go @@ -0,0 +1,63 @@ +package thumb + +import ( + "bytes" + "fmt" + "image" + "image/png" + "os" + "path/filepath" + "testing" +) + +func TestLoadRegionFrame2880x1620PPMMenuBarLossless(t *testing.T) { + const w, h = 2880, 1620 + path := filepath.Join(t.TempDir(), "hidpi.ppm") + var buf bytes.Buffer + fmt.Fprintf(&buf, "P6\n%d %d\n255\n", w, h) + row := make([]byte, w*3) + for y := 0; y < h; y++ { + if y < 48 { + // Menu bar with distinct colored markers so non-blank and pixel alignment are exact. + for x := 0; x < w; x++ { + if x >= 120 && x < 240 && y >= 10 && y < 34 { + row[x*3], row[x*3+1], row[x*3+2] = 250, 250, 250 + } else { + row[x*3], row[x*3+1], row[x*3+2] = 28, 30, 36 + } + } + } else { + for x := 0; x < w; x++ { + row[x*3], row[x*3+1], row[x*3+2] = 20, 90, 180 + } + } + buf.Write(row) + } + if err := os.WriteFile(path, buf.Bytes(), 0o644); err != nil { + t.Fatal(err) + } + + region := image.Rect(0, 0, w, 48) + img, crop, blank, err := LoadRegionFrame(path, "ppm", ®ion, 0) + if err != nil { + t.Fatalf("LoadRegionFrame: %v", err) + } + if blank { + t.Fatal("menu bar crop should not be flagged blank") + } + if crop != region || img.Bounds().Dx() != w || img.Bounds().Dy() != 48 { + t.Fatalf("crop=%v bounds=%v, want %v", crop, img.Bounds(), region) + } + r, g, b, _ := img.At(160, 20).RGBA() + if uint8(r>>8) != 250 || uint8(g>>8) != 250 || uint8(b>>8) != 250 { + t.Fatalf("pixel (160,20) = (%d,%d,%d), want (250,250,250)", r>>8, g>>8, b>>8) + } + pngBytes, err := PNG(img) + if err != nil { + t.Fatalf("PNG encode: %v", err) + } + decoded, err := png.Decode(bytes.NewReader(pngBytes)) + if err != nil || decoded.Bounds().Dx() != w || decoded.Bounds().Dy() != 48 { + t.Fatalf("PNG decode failed: %v", err) + } +} diff --git a/internal/thumb/thumb.go b/internal/thumb/thumb.go index 4cbaf83..cb121bb 100644 --- a/internal/thumb/thumb.go +++ b/internal/thumb/thumb.go @@ -228,3 +228,12 @@ func JPEG(img image.Image, quality int) ([]byte, error) { } return buf.Bytes(), nil } + +// PNG encodes img losslessly as PNG. +func PNG(img image.Image) ([]byte, error) { + var buf bytes.Buffer + if err := png.Encode(&buf, img); err != nil { + return nil, err + } + return buf.Bytes(), nil +} diff --git a/internal/tray/tray.go b/internal/tray/tray.go index 957d4bd..95839c2 100644 --- a/internal/tray/tray.go +++ b/internal/tray/tray.go @@ -11,10 +11,12 @@ import ( // VMItem is a lightweight summary shown inside the system tray menu. type VMItem struct { - DriverID string // owning guest driver, passed back to callbacks with Name - Name string // VM name within DriverID, passed back to callbacks - Label string // display name (the VM's note); empty shows Name - State string // running | stopped | starting | stopping | broken + DriverID string // owning guest driver, passed back to callbacks with Name + Name string // VM name within DriverID, passed back to callbacks + Label string // display name (the VM's note); empty shows Name + State string // running | stopped | starting | stopping | broken + HasRemoteControl bool // true while an Agent/auto-install session is active + RemoteControlLabel string // localized status banner shown inside the VM submenu } func (v VMItem) title() string { @@ -47,6 +49,7 @@ const ( ActSuspend ActResume ActDiscardSuspend + ActStopRemoteControl ) // Callbacks wires tray actions back into the Wails application. Each runs @@ -105,6 +108,8 @@ type texts struct { toggleFullscreen string resumeUnavailable string + stopRemoteControl string + remoteControlTag string } func menuTexts(snap Snapshot) texts { @@ -140,6 +145,8 @@ func menuTexts(snap Snapshot) texts { toggleFullscreen: i18n.T(loc, "tray.menu.toggle_fullscreen"), resumeUnavailable: i18n.T(loc, "tray.menu.resume_unavailable"), + stopRemoteControl: i18n.T(loc, "tray.menu.stop_remote_control"), + remoteControlTag: i18n.T(loc, "tray.state.remote_control"), } } @@ -152,7 +159,7 @@ func decodeVMCmd(id int) (int, Action, bool) { } off := id - cmdVMBase act := Action(off % vmSlot) - if act < ActStart || act > ActDiscardSuspend { + if act < ActStart || act > ActStopRemoteControl { return 0, 0, false } return off / vmSlot, act, true @@ -234,6 +241,19 @@ func buildMenu(snap Snapshot) []menuEntry { dot, state = dotStopped, t.unknown sub = []menuEntry{cmd(ActOpenInApp, t.openInApp)} } + if vm.HasRemoteControl { + banner := vm.RemoteControlLabel + if banner == "" { + banner = t.remoteControlTag + } + prefix := []menuEntry{ + {Label: banner, Disabled: true}, + cmd(ActStopRemoteControl, t.stopRemoteControl), + sep, + } + sub = append(prefix, sub...) + state = t.remoteControlTag + } menu = append(menu, menuEntry{Label: vm.title() + "\t" + state, Dot: dot, Sub: sub}) } return append(menu, menuEntry{Separator: true}, menuEntry{ID: cmdQuit, Label: t.quit}) diff --git a/internal/tray/tray_test.go b/internal/tray/tray_test.go index 6049b41..679c0ce 100644 --- a/internal/tray/tray_test.go +++ b/internal/tray/tray_test.go @@ -91,20 +91,48 @@ func TestSuspendedVMWithoutCompatibleRuntime(t *testing.T) { func TestDecodeVMCmdRoundTrip(t *testing.T) { for i := 0; i < maxTrayVMs; i++ { - for act := ActStart; act <= ActDiscardSuspend; act++ { + for act := ActStart; act <= ActStopRemoteControl; act++ { gi, ga, ok := decodeVMCmd(vmCmd(i, act)) if !ok || gi != i || ga != act { t.Fatalf("vmCmd(%d,%d) decoded to (%d,%d,%v)", i, act, gi, ga, ok) } } } - for _, id := range []int{cmdShow, cmdQuit, cmdNewVM, cmdVMBase, vmCmd(0, ActDiscardSuspend+1), cmdVMBase + maxTrayVMs*vmSlot} { + for _, id := range []int{cmdShow, cmdQuit, cmdNewVM, cmdVMBase, vmCmd(0, ActStopRemoteControl+1), cmdVMBase + maxTrayVMs*vmSlot} { if _, _, ok := decodeVMCmd(id); ok { t.Fatalf("id %d should not decode as a VM command", id) } } } +func TestRemoteControlTrayMenuEntry(t *testing.T) { + menu := buildMenu(Snapshot{ + Locale: i18n.ZhCN, + VMs: []VMItem{{ + Name: "macos-auto", + State: "running", + HasRemoteControl: true, + RemoteControlLabel: "AI 正在操作(安装阶段已授权)", + }}, + }) + var vm *menuEntry + for i := range menu { + if len(menu[i].Sub) > 0 { + vm = &menu[i] + break + } + } + if vm == nil || len(vm.Sub) < 2 { + t.Fatalf("expected remote-control VM submenu, got %+v", menu) + } + if !vm.Sub[0].Disabled || vm.Sub[0].Label != "AI 正在操作(安装阶段已授权)" { + t.Fatalf("first submenu item should show banner, got %+v", vm.Sub[0]) + } + if vm.Sub[1].ID != vmCmd(0, ActStopRemoteControl) { + t.Fatalf("second submenu item should trigger ActStopRemoteControl, got %+v", vm.Sub[1]) + } +} + func TestDotPixels(t *testing.T) { const size = 16 alpha := func(px []byte, x, y int) byte { return px[(y*size+x)*4+3] } diff --git a/locales/en-US/native.json b/locales/en-US/native.json index 3d90999..eccb2c8 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -814,6 +814,7 @@ "monitor.stall_warn": "[warn] Almost no CPU or disk activity for 90s; VM may be stalled during boot/reboot. Check the QEMU log tab or hold Win+V on next boot for verbose output", "monitor.serial.boot": "[boot] UEFI starting OpenCore bootloader", "monitor.serial.xnu": "[boot] OpenCore handed off to macOS kernel (XNU loading)", + "monitor.serial.provision_ready": "[provision] macOS finished installing and reached first boot; click Finish Install to eject media and enable network and Guest Tools", "monitor.qemu.gpu": { "message": "[gpu] vGPU initialized: {device}", "$params": [ @@ -1159,5 +1160,84 @@ "err.hypervisor.busy_vms": "Stop all running or transitioning virtual machines before changing host virtualization boot settings", "err.hypervisor.busy_tasks": "Wait for active VM creation tasks to finish or cancel them before changing host virtualization boot settings", "err.hypervisor.set_failed": "Could not update Windows Hypervisor boot settings", - "err.hypervisor.unsupported": "Switching Windows Hypervisor boot settings is only supported on Windows" + "err.hypervisor.unsupported": "Switching Windows Hypervisor boot settings is only supported on Windows", + "tray.menu.stop_remote_control": "Stop AI control", + "tray.state.remote_control": "AI controlling", + "err.computer_use.phase_denied": { + "message": "Access to VM {name} during a protected phase was denied", + "$params": ["name"] + }, + "err.computer_use.user_takeover": { + "message": "User input detected in VM {name}; external control paused", + "$params": ["name"] + }, + "err.computer_use.session_paused": { + "message": "Automation on VM {name} is paused; resume before sending input", + "$params": ["name"] + }, + "confirm.phase.title": { + "message": "Allow plugin access during {phase}", + "$params": ["phase"] + }, + "confirm.phase.message": { + "message": "VM {name} is in the {phase} phase. Allowing grants screenshot and keyboard/mouse control", + "$params": ["name", "phase"] + }, + "confirm.phase.allow": "Allow", + "confirm.phase.deny": "Deny", + "confirm.mirror.title": "Confirm custom download mirror", + "confirm.mirror.message": { + "message": "Allow downloading SHA-256 verified local OCR assets from custom HTTPS origin {origin}", + "$params": ["origin"] + }, + "confirm.mirror.allow": "Allow download", + "agent.session.banner": { + "message": "AI controlling · {plugin}", + "$params": ["plugin"] + }, + "agent.session.phase_banner": { + "message": "AI controlling ({phase} authorized)", + "$params": ["phase"] + }, + "agent.session.phase_banner_timer": { + "message": "AI controlling ({phase} authorized · {minutes}m left)", + "$params": ["phase", "minutes"] + }, + "agent.session.paused_manual": "Paused; waiting to resume", + "agent.session.paused_by_user": "Paused; VM input unlocked — click Resume to continue", + "agent.session.locked_prefix": "Input locked · ", + "agent.session.locked_status": "Input locked (click Pause to take over)", + "agent.session.takeover_manual": "Manual input detected; paused (click Resume)", + "agent.session.takeover_countdown": { + "message": "User takeover active ({seconds}s)", + "$params": ["seconds"] + }, + "agent.session.pause": "Pause", + "agent.session.resume": "Resume", + "agent.session.stop": "Stop", + "agent.session.close": "Close", + "agent.session.collapse": "Collapse", + "agent.session.completed_title": "Auto-install", + "agent.session.completed_status": "Completed; VM input unlocked", + "agent.session.denied_fallback": "Plugin permission denied; script did not run and manual installation guide is shown instead", + "agent.session.step_badge": "Step", + "agent.session.step_running": "Running", + "agent.session.step_paused": "Paused", + "agent.session.step_numbered": { + "message": "Step {num} · {name}", + "$params": ["num", "name"] + }, + "agent.session.stage.preflight": "Preflight check", + "agent.session.stage.boot_recovery": "Boot into Recovery", + "agent.session.stage.offline_terminal": "Run offline installer", + "agent.session.stage.disk_utility": "Erase target disk", + "agent.session.stage.install_wait": "Wait for macOS install", + "agent.session.stage.finish_install": "Exit recovery and restart", + "agent.session.stage.install_macos": "Install macOS", + "agent.session.stage.reboot": "Waiting for reboot", + "agent.session.stage.setup_assistant": "Setup Assistant", + "agent.session.stage.account": "Create local account", + "agent.session.stage.guest_tools": "Install Guest Tools", + "agent.session.stage.desktop": "Verify desktop", + "agent.session.stage.completed": "Completed" } diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index 99ee690..bd81daa 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -527,5 +527,9 @@ "fullscreenHotkeyErrReserved": "{hotkey} is reserved by Windows and cannot be used", "fullscreenHotkeyErrUnsupported": "Key not supported; use letters, numbers, F1–F12, or navigation keys", "fullscreenHotkeySaveFailed": "Could not save fullscreen shortcut", - "fullscreenHotkeyCurrentAria": "Current fullscreen shortcut: {hotkey}" + "fullscreenHotkeyCurrentAria": "Current fullscreen shortcut: {hotkey}", + "agentTakeoverPauseTitle": "AI takeover pause duration", + "agentTakeoverPauseDesc": "How long external control pauses after physical keyboard or mouse input in a VM window", + "agentTakeoverPauseManual": "Until manual resume", + "agentTakeoverPauseSeconds": "{seconds} seconds" } diff --git a/locales/en-US/vm.json b/locales/en-US/vm.json index e426643..ee9b9a9 100644 --- a/locales/en-US/vm.json +++ b/locales/en-US/vm.json @@ -274,5 +274,63 @@ "fieldDriver": "Driver", "failEndpointOpen": "Could not open connection", "failEndpointCommand": "Could not get the command", - "nestedVirtLabel": "Nested virtualization" + "nestedVirtLabel": "Nested virtualization", + "remoteControlActive": "AI controlling · {plugin}", + "remoteControlPhaseAuth": "AI controlling ({phase} authorized)", + "remoteControlPhaseAuthTimer": "AI controlling ({phase} authorized · {minutes}m left)", + "remoteControlPaused": "Paused; finish this step and click Resume", + "remoteControlInputLocked": "Screen input locked", + "remoteControlTakeoverCountdown": "User input detected; resumes in {seconds}s", + "remoteControlPause": "Pause", + "remoteControlResume": "Resume", + "remoteControlStop": "Stop", + "confirmPhaseScope": "Scope: screenshots and keyboard/mouse input (memory only; revoked on exit or Stop)", + "confirmDurationLabel": "Authorization duration", + "confirmDuration10": "10 minutes", + "confirmDuration30": "30 minutes", + "confirmDuration60": "60 minutes", + "confirmDurationUntilExit": "Until leaving this phase", + "confirmAllow": "Allow", + "confirmDeny": "Deny", + "confirmTimedOut": "Confirmation timed out and was treated as denied", + "autoInstallTitle": "Automatic macOS installation", + "autoInstallDesc": "Local OCR and declarative state machine automate Recovery, reboots, and Setup Assistant without cloud APIs", + "autoInstallStart": "Start auto-install", + "autoInstallOptions": "Options…", + "autoInstallHideOptions": "Hide options", + "autoInstallPause": "Pause", + "autoInstallResume": "Resume auto-install", + "autoInstallStop": "Stop install", + "autoInstallRecoveryOnlyHint": "Automate Recovery mode only (no account required; starting accepts the Apple Software License Agreement)", + "autoInstallIncludeAccountToggle": "Also pre-configure local account and unlock desktop (REIMSPROV)", + "autoSetupGroupTitle": "Automated setup and provisioning", + "autoRecoveryToggle": "Automate Recovery mode 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)", + "autoInstallCopySummary": "Copy redacted summary", + "autoInstallSummaryCopied": "Redacted summary copied", + "autoInstallFullName": "Full name (ASCII)", + "autoInstallAccountName": "Account name (lowercase ASCII)", + "autoInstallPassword": "Password (4+ printable ASCII)", + "autoInstallAppearance": "Appearance", + "autoInstallAppearanceAuto": "Auto", + "autoInstallAppearanceLight": "Light", + "autoInstallAppearanceDark": "Dark", + "autoInstallSLAConfirm": "I accept the Apple Software License Agreement and authorize unattended installation", + "autoInstallFileVaultNote": "FileVault stays off during unattended setup so reboots never block; enable it after reaching Desktop", + "autoInstallSaveUnlock": "Keep password as unlock credential after setup (cleared on desktop arrival by default)", + "autoInstallOCRReady": "Local OCR ready ({backend})", + "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", + "autoInstallDownloadOCR": "Download RapidOCR", + "autoInstallStatusRunning": "Auto-install running", + "autoInstallStatusPaused": "Paused for user", + "autoInstallStatusCompleted": "Desktop ready", + "autoInstallStatusFailed": "Auto-install stopped", + "provisionGroupTitle": "First-boot provisioning (skip Setup Assistant)", + "provisionToggle": "Pre-configure local account and skip Setup Assistant", + "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)", + "provisionInstallGuestTools": "Pre-stage Reims Guest Tools (starts on first login once network is enabled)", + "provisionReadyNoticeTitle": "macOS installation finished and reached first boot", + "provisionReadyNoticeDesc": "Click Exit recovery mode to eject the installer, wipe the provisioning disk, and enable network and Guest Tools", + "failProvision": "Failed to prepare provisioning disk" } diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index 40cdbaa..b8020ea 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -814,6 +814,7 @@ "monitor.stall_warn": "[警告] 连续 90 秒几乎无 CPU 与磁盘写入,虚拟机可能停在启动或重启阶段;可切到「QEMU」页签排查,或下次引导时按住 Win+V 查看内核输出", "monitor.serial.boot": "[引导] UEFI 正在启动 OpenCore 引导程序", "monitor.serial.xnu": "[引导] OpenCore 已交接 macOS 内核(XNU 正在加载系统与驱动)", + "monitor.serial.provision_ready": "[预配置] macOS 已完成安装并首次启动就绪,可点击「完成安装」移除安装介质并启用网络与 Guest Tools", "monitor.qemu.gpu": { "message": "[图形] vGPU 已初始化:{device}", "$params": [ @@ -1159,5 +1160,84 @@ "err.hypervisor.busy_vms": "关闭所有运行中或正在切换状态的虚拟机后再更改系统虚拟化启动设置", "err.hypervisor.busy_tasks": "等待虚拟机创建任务结束或取消后再更改系统虚拟化启动设置", "err.hypervisor.set_failed": "未能修改 Windows Hypervisor 启动设置", - "err.hypervisor.unsupported": "当前系统不支持切换 Windows Hypervisor 启动设置" + "err.hypervisor.unsupported": "当前系统不支持切换 Windows Hypervisor 启动设置", + "tray.menu.stop_remote_control": "停止 AI 控制", + "tray.state.remote_control": "AI 操作中", + "err.computer_use.phase_denied": { + "message": "已拒绝在受保护阶段访问虚拟机 {name}", + "$params": ["name"] + }, + "err.computer_use.user_takeover": { + "message": "检测到用户在虚拟机 {name} 中操作键鼠,已暂停外部输入", + "$params": ["name"] + }, + "err.computer_use.session_paused": { + "message": "虚拟机 {name} 的自动操作已暂停,恢复后再继续外部输入", + "$params": ["name"] + }, + "confirm.phase.title": { + "message": "允许外部插件操作{phase}阶段", + "$params": ["phase"] + }, + "confirm.phase.message": { + "message": "虚拟机 {name} 当前处于{phase}阶段,授权后将允许该插件截屏与发送键鼠输入", + "$params": ["name", "phase"] + }, + "confirm.phase.allow": "允许", + "confirm.phase.deny": "拒绝", + "confirm.mirror.title": "确认自定义下载镜像", + "confirm.mirror.message": { + "message": "允许从自定义 HTTPS 地址 {origin} 下载经 SHA-256 校验的本地 OCR 模型", + "$params": ["origin"] + }, + "confirm.mirror.allow": "允许下载", + "agent.session.banner": { + "message": "AI 正在操作 · {plugin}", + "$params": ["plugin"] + }, + "agent.session.phase_banner": { + "message": "AI 正在操作({phase}已授权)", + "$params": ["phase"] + }, + "agent.session.phase_banner_timer": { + "message": "AI 正在操作({phase}已授权 · 约 {minutes} 分钟)", + "$params": ["phase", "minutes"] + }, + "agent.session.paused_manual": "已暂停,等待手动继续", + "agent.session.paused_by_user": "已手动暂停,现在可操作画面,点继续恢复", + "agent.session.locked_prefix": "画面已锁定防干扰 · ", + "agent.session.locked_status": "画面已锁定防干扰(点暂停可接管)", + "agent.session.takeover_manual": "检测到键鼠操作,已暂停(点击继续)", + "agent.session.takeover_countdown": { + "message": "用户接管中,{seconds} 秒后恢复", + "$params": ["seconds"] + }, + "agent.session.pause": "暂停", + "agent.session.resume": "继续", + "agent.session.stop": "停止", + "agent.session.close": "关闭", + "agent.session.collapse": "收起", + "agent.session.completed_title": "自动安装", + "agent.session.completed_status": "已完成,现在可操作画面", + "agent.session.denied_fallback": "已拒绝插件运行权限,自动安装脚本未运行,已切回手动安装引导", + "agent.session.step_badge": "当前步骤", + "agent.session.step_running": "正在执行", + "agent.session.step_paused": "已暂停", + "agent.session.step_numbered": { + "message": "步骤 {num} · {name}", + "$params": ["num", "name"] + }, + "agent.session.stage.preflight": "环境准备", + "agent.session.stage.boot_recovery": "进入恢复环境", + "agent.session.stage.offline_terminal": "运行离线安装脚本", + "agent.session.stage.disk_utility": "磁盘工具抹盘", + "agent.session.stage.install_wait": "等待系统安装", + "agent.session.stage.finish_install": "退出恢复并重启", + "agent.session.stage.install_macos": "安装 macOS", + "agent.session.stage.reboot": "等待系统重启", + "agent.session.stage.setup_assistant": "完成设置助理", + "agent.session.stage.account": "创建本地账户", + "agent.session.stage.guest_tools": "安装 Guest Tools", + "agent.session.stage.desktop": "进入桌面验证", + "agent.session.stage.completed": "已完成" } diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index e0642d6..73370be 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -527,5 +527,9 @@ "fullscreenHotkeyErrReserved": "{hotkey} 为 Windows 系统保留快捷键,无法使用", "fullscreenHotkeyErrUnsupported": "不支持该按键,可用字母、数字、F1–F12 及常用功能键", "fullscreenHotkeySaveFailed": "保存全屏快捷键失败", - "fullscreenHotkeyCurrentAria": "当前全屏快捷键:{hotkey}" + "fullscreenHotkeyCurrentAria": "当前全屏快捷键:{hotkey}", + "agentTakeoverPauseTitle": "AI 操作接管暂停时长", + "agentTakeoverPauseDesc": "在虚拟机窗口操作键鼠后暂停外部输入的时间,设为「手动恢复」则需点击继续", + "agentTakeoverPauseManual": "直到手动恢复", + "agentTakeoverPauseSeconds": "{seconds} 秒" } diff --git a/locales/zh-CN/vm.json b/locales/zh-CN/vm.json index 23c5d18..3e0758b 100644 --- a/locales/zh-CN/vm.json +++ b/locales/zh-CN/vm.json @@ -274,5 +274,63 @@ "fieldDriver": "驱动", "failEndpointOpen": "无法打开连接", "failEndpointCommand": "无法获取命令", - "nestedVirtLabel": "嵌套虚拟化" + "nestedVirtLabel": "嵌套虚拟化", + "remoteControlActive": "AI 正在操作 · {plugin}", + "remoteControlPhaseAuth": "AI 正在操作({phase}已授权)", + "remoteControlPhaseAuthTimer": "AI 正在操作({phase}已授权 · 剩余 {minutes} 分钟)", + "remoteControlPaused": "已暂停,手动处理后点击继续", + "remoteControlInputLocked": "画面已锁定防干扰", + "remoteControlTakeoverCountdown": "检测到键鼠操作,{seconds} 秒后自动恢复", + "remoteControlPause": "暂停", + "remoteControlResume": "继续", + "remoteControlStop": "停止", + "confirmPhaseScope": "授权范围:截屏与键鼠输入(仅存内存,退出或点停止立即撤销)", + "confirmDurationLabel": "授权时长", + "confirmDuration10": "10 分钟", + "confirmDuration30": "30 分钟", + "confirmDuration60": "60 分钟", + "confirmDurationUntilExit": "直到离开此阶段", + "confirmAllow": "允许", + "confirmDeny": "拒绝", + "confirmTimedOut": "授权确认已超时关闭,对应操作已按拒绝处理", + "autoInstallTitle": "自动完成 macOS 安装", + "autoInstallDesc": "纯本地视觉定位与状态机自动走完恢复终端、跨重启等待与设置助理,无需联网模型", + "autoInstallStart": "开始自动安装", + "autoInstallOptions": "选项…", + "autoInstallHideOptions": "收起选项", + "autoInstallPause": "暂停", + "autoInstallResume": "继续自动安装", + "autoInstallStop": "停止装机", + "autoInstallRecoveryOnlyHint": "仅自动完成恢复模式安装(无需账户密码;启动即同意 Apple 软件许可协议)", + "autoInstallIncludeAccountToggle": "同时预置本地账户并自动登录桌面(REIMSPROV)", + "autoSetupGroupTitle": "自动安装与首启预配置", + "autoRecoveryToggle": "自动完成恢复模式安装", + "autoRecoveryDesc": "自动识别恢复界面、快捷键打开终端运行安装脚本并等待重启进入系统;运行期间锁定虚拟机画面防干扰(点右上角悬浮窗「暂停」可接管);开启即同意 Apple 软件许可协议(startosinstall --agreetolicense)", + "autoInstallCopySummary": "复制脱敏摘要", + "autoInstallSummaryCopied": "已复制脱敏摘要", + "autoInstallFullName": "账户全名(ASCII)", + "autoInstallAccountName": "账户短名(小写 ASCII)", + "autoInstallPassword": "账户密码(≥4 位可见 ASCII)", + "autoInstallAppearance": "系统外观", + "autoInstallAppearanceAuto": "自动", + "autoInstallAppearanceLight": "浅色", + "autoInstallAppearanceDark": "深色", + "autoInstallSLAConfirm": "已阅读并同意 Apple 软件许可协议,允许自动确认许可与完成安装", + "autoInstallFileVaultNote": "自动装机默认关闭 FileVault 以免阻断无人值守重启,进入桌面后可按需开启", + "autoInstallSaveUnlock": "安装完成后保留密码作解锁凭据(默认进桌面后自动清除)", + "autoInstallOCRReady": "本地 OCR 已就绪({backend})", + "autoInstallOCRMissing": "当前 Windows 缺少目标语种 OCR 包,可按需下载 RapidOCR 备选模型", + "autoInstallOCRMissingInstallPack": "当前 Windows 缺少目标语种 OCR 包,需在 Windows 设置安装对应语言包或离线导入 RapidOCR 包", + "autoInstallDownloadOCR": "下载 RapidOCR", + "autoInstallStatusRunning": "正在自动安装", + "autoInstallStatusPaused": "已暂停等待处理", + "autoInstallStatusCompleted": "已进入可用桌面", + "autoInstallStatusFailed": "自动安装已中止", + "provisionGroupTitle": "首启预配置(跳过设置助理)", + "provisionToggle": "预置本地账户并跳过设置助理", + "provisionDesc": "离线安装时通过 PBKDF2 哈希创建本地管理员、跳过设置助理与键盘向导,并预装 Guest Tools(明文密码不落盘)", + "provisionInstallGuestTools": "预装 Reims Guest Tools(启用网络后首次登录自动启动)", + "provisionReadyNoticeTitle": "macOS 安装已完成并首次启动就绪", + "provisionReadyNoticeDesc": "点击「退出恢复模式」以弹出安装介质、覆零清理预配置卷并启用网络与 Guest Tools", + "failProvision": "写入预配置卷失败" } diff --git a/pkg/pluginproto/proto.go b/pkg/pluginproto/proto.go index d49a027..e662760 100644 --- a/pkg/pluginproto/proto.go +++ b/pkg/pluginproto/proto.go @@ -100,6 +100,22 @@ var HostMethods = map[string]MethodSpec{ Status: StatusStable, Permissions: []string{"driver:vm"}, Feature: "host.elevate.request", Summary: "Ask the user to confirm one whitelisted Windows elevation action.", }, + "host/ui.confirm": { + Status: StatusStable, Permissions: []string{"ui:notify"}, Feature: "host.ui.confirm", StrictParams: true, + Summary: "Ask the user to confirm a host action or protected-phase authorization.", + }, + "host/session.begin": { + Status: StatusStable, Permissions: []string{"qmp:write"}, Feature: "host.session", StrictParams: true, + Summary: "Begin a visible remote-control session on an authorized VM.", + }, + "host/session.update": { + Status: StatusStable, Permissions: []string{"qmp:write"}, Feature: "host.session", StrictParams: true, + Summary: "Update the visible stage, status or pause state of an active session.", + }, + "host/session.end": { + Status: StatusStable, Permissions: []string{"qmp:write"}, Feature: "host.session", StrictParams: true, + Summary: "End an active remote-control session on a VM.", + }, "host/vm.list": { Status: StatusStable, Permissions: []string{"vm:read"}, StrictParams: true, Summary: "List the VMs this plugin may see.", @@ -144,9 +160,21 @@ var HostMethods = map[string]MethodSpec{ Status: StatusStable, Permissions: []string{"vm:control"}, StrictParams: true, Summary: "Restore a snapshot of a VM the user authorized this plugin to access.", }, + "host/vm.finishInstall": { + Status: StatusStable, Permissions: []string{"vm:control"}, Feature: "host.vm.finishInstall", StrictParams: true, + Summary: "Invoke a VM driver's finish_install action to exit recovery/installer mode.", + }, + "host/vm.restart": { + Status: StatusStable, Permissions: []string{"vm:control"}, Feature: "host.vm.restart", StrictParams: true, + Summary: "Stop a VM, wait for process exit, and start it again.", + }, + "host/vm.telemetry": { + Status: StatusStable, Permissions: []string{"vm:read", "log:read"}, Feature: "host.vm.telemetry", StrictParams: true, + Summary: "Read structured, redacted runtime telemetry for an authorized VM.", + }, "host/console.screenshot": { Status: StatusStable, Permissions: []string{"vm:screen"}, StrictParams: true, - Summary: "Capture the guest screen, optionally one region of it, as JPEG.", + Summary: "Capture the guest screen, optionally one region of it, as JPEG or PNG.", }, "host/console.pointer": { Status: StatusStable, Permissions: []string{"qmp:write"}, StrictParams: true, diff --git a/pkg/pluginproto/types.go b/pkg/pluginproto/types.go index a80b040..2a834a1 100644 --- a/pkg/pluginproto/types.go +++ b/pkg/pluginproto/types.go @@ -90,13 +90,16 @@ type IsRunningResult struct { // DownloadParams is the payload of host/download.start. SHA256 or SHA256URL // (with SHA256Name selecting a line) is required; the host verifies the file. type DownloadParams struct { - URL string `json:"url"` - SHA256 string `json:"sha256,omitempty"` - SHA256URL string `json:"sha256_url,omitempty"` - SHA256Name string `json:"sha256_name,omitempty"` - Dest string `json:"dest"` - Size int64 `json:"size,omitempty"` - Label string `json:"label,omitempty"` + URL string `json:"url"` + SHA256 string `json:"sha256,omitempty"` + SHA256URL string `json:"sha256_url,omitempty"` + SHA256Name string `json:"sha256_name,omitempty"` + Dest string `json:"dest"` + Size int64 `json:"size,omitempty"` + Label string `json:"label,omitempty"` + ConnectTimeoutMS int `json:"connect_timeout_ms,omitempty"` + StallTimeoutMS int `json:"stall_timeout_ms,omitempty"` + AllowCustomMirror bool `json:"allow_custom_mirror,omitempty"` } // DownloadResult is the result of host/download.start. @@ -164,6 +167,12 @@ type VMShutdownParams struct { Force bool `json:"force,omitempty"` } +// VMRestartParams is the payload of host/vm.restart. +type VMRestartParams struct { + VM string `json:"vm"` + GracefulTimeoutSec int `json:"graceful_timeout_sec,omitempty"` +} + // VMView is what host/vm.list and host/vm.get report about one VM. Fields // that need the user's per-VM consent are present only when it was granted. type VMView struct { @@ -250,6 +259,8 @@ type Region struct { type ScreenshotParams struct { VM string `json:"vm"` MaxWidth int `json:"max_width,omitempty"` + MaxEdge *int `json:"max_edge,omitempty"` + Format string `json:"format,omitempty"` Region *Region `json:"region,omitempty"` Width int `json:"width,omitempty"` Height int `json:"height,omitempty"` @@ -324,3 +335,74 @@ type ReleaseParams struct { type CharactersResult struct { Characters int `json:"characters"` } + +// ConfirmParams is the payload of host/ui.confirm. +type ConfirmParams struct { + 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"` + VM string `json:"vm,omitempty"` + ProtectedPhase string `json:"protected_phase,omitempty"` + AllowDurationChoice bool `json:"allow_duration_choice,omitempty"` + DefaultDurationMin int `json:"default_duration_minutes,omitempty"` + PreferUntilPhaseExit bool `json:"prefer_until_phase_exit,omitempty"` +} + +// ConfirmResult is the result of host/ui.confirm. +type ConfirmResult struct { + Approved bool `json:"approved"` + DurationMinutes int `json:"duration_minutes,omitempty"` + UntilPhaseExit bool `json:"until_phase_exit,omitempty"` + Reason string `json:"reason,omitempty"` +} + +// SessionBeginParams is the payload of host/session.begin. +type SessionBeginParams struct { + VM string `json:"vm"` + Label string `json:"label,omitempty"` + Stage string `json:"stage,omitempty"` + TakeoverPolicy string `json:"takeover_policy,omitempty"` + RequestProtectedPhaseAuth bool `json:"request_protected_phase_auth,omitempty"` + PreferUntilPhaseExit bool `json:"prefer_until_phase_exit,omitempty"` +} + +// SessionUpdateParams is the payload of host/session.update. +type SessionUpdateParams struct { + VM string `json:"vm"` + Stage string `json:"stage,omitempty"` + Step string `json:"step,omitempty"` + Status string `json:"status,omitempty"` + Message string `json:"message,omitempty"` + PausedForUser *bool `json:"paused_for_user,omitempty"` +} + +// SessionEndParams is the payload of host/session.end. +type SessionEndParams struct { + VM string `json:"vm"` + Status string `json:"status,omitempty"` + Message string `json:"message,omitempty"` +} + +// TelemetryMilestone is one parsed boot/runtime milestone reported by host/vm.telemetry. +type TelemetryMilestone struct { + Key string `json:"key"` + Count int `json:"count"` + At string `json:"at"` +} + +// VMTelemetryResult is the result of host/vm.telemetry. +type VMTelemetryResult struct { + VM string `json:"vm"` + State string `json:"state"` + Phase string `json:"phase"` + PID int `json:"pid"` + BootMilestones []TelemetryMilestone `json:"boot_milestones,omitempty"` + QemuErrors []string `json:"qemu_errors,omitempty"` + DiskBytes int64 `json:"disk_bytes"` + DiskDeltaBytes int64 `json:"disk_delta_bytes"` + CPUPercent float64 `json:"cpu_percent"` + ColdRebootCount int `json:"cold_reboot_count"` + UpdatedAt string `json:"updated_at,omitempty"` +} diff --git a/pkg/pluginsdk/sdk.go b/pkg/pluginsdk/sdk.go index a45f1ec..02e6631 100644 --- a/pkg/pluginsdk/sdk.go +++ b/pkg/pluginsdk/sdk.go @@ -474,13 +474,16 @@ func (s *Server) MaterializeSecret(ctx context.Context, req MaterializeSecretReq // every file, so SHA256 or SHA256URL (with SHA256Name selecting a line) is // required. type DownloadRequest struct { - URL string `json:"url"` - SHA256 string `json:"sha256,omitempty"` - SHA256URL string `json:"sha256_url,omitempty"` - SHA256Name string `json:"sha256_name,omitempty"` - Dest string `json:"dest"` - Size int64 `json:"size,omitempty"` - Label string `json:"label,omitempty"` + URL string `json:"url"` + SHA256 string `json:"sha256,omitempty"` + SHA256URL string `json:"sha256_url,omitempty"` + SHA256Name string `json:"sha256_name,omitempty"` + Dest string `json:"dest"` + Size int64 `json:"size,omitempty"` + Label string `json:"label,omitempty"` + ConnectTimeoutMS int `json:"connect_timeout_ms,omitempty"` + StallTimeoutMS int `json:"stall_timeout_ms,omitempty"` + AllowCustomMirror bool `json:"allow_custom_mirror,omitempty"` } // DownloadEvent is the payload of the host's `download/progress` notification. @@ -559,6 +562,194 @@ func (s *Server) Notify(ctx context.Context, title, body string) error { return s.CallHost(ctx, "host/notify", map[string]any{"title": title, "body": body}, nil) } +// ConfirmRequest asks the host to show a native confirmation dialog. +type ConfirmRequest struct { + 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"` + VM string `json:"vm,omitempty"` + ProtectedPhase string `json:"protected_phase,omitempty"` + AllowDurationChoice bool `json:"allow_duration_choice,omitempty"` + DefaultDurationMin int `json:"default_duration_minutes,omitempty"` + PreferUntilPhaseExit bool `json:"prefer_until_phase_exit,omitempty"` +} + +// ConfirmResult reports the user's answer to a host confirmation dialog. +type ConfirmResult struct { + Approved bool `json:"approved"` + DurationMinutes int `json:"duration_minutes,omitempty"` + UntilPhaseExit bool `json:"until_phase_exit,omitempty"` + Reason string `json:"reason,omitempty"` +} + +// Confirm displays a native host confirmation dialog and waits for the user. +func (s *Server) Confirm(ctx context.Context, req ConfirmRequest) (ConfirmResult, error) { + var resp ConfirmResult + err := s.CallHost(ctx, "host/ui.confirm", req, &resp) + return resp, err +} + +// SessionBeginRequest opens a visible remote-control session on a VM. +type SessionBeginRequest struct { + VM string `json:"vm"` + Label string `json:"label,omitempty"` + Stage string `json:"stage,omitempty"` + TakeoverPolicy string `json:"takeover_policy,omitempty"` // "" | "auto" | "manual" | "lock" + RequestProtectedPhaseAuth bool `json:"request_protected_phase_auth,omitempty"` + PreferUntilPhaseExit bool `json:"prefer_until_phase_exit,omitempty"` +} + +// SessionUpdateRequest updates the visible stage/status shown in the host overlay and VM page. +type SessionUpdateRequest struct { + VM string `json:"vm"` + Stage string `json:"stage,omitempty"` + Status string `json:"status,omitempty"` + Message string `json:"message,omitempty"` + PausedForUser *bool `json:"paused_for_user,omitempty"` +} + +// BeginSession starts a visible Agent/automation session on req.VM. +func (s *Server) BeginSession(ctx context.Context, req SessionBeginRequest) error { + return s.CallHost(ctx, "host/session.begin", req, nil) +} + +// UpdateSession updates the visible progress state of an active session. +func (s *Server) UpdateSession(ctx context.Context, req SessionUpdateRequest) error { + return s.CallHost(ctx, "host/session.update", req, nil) +} + +// EndSession ends the visible Agent/automation session on vm. +func (s *Server) EndSession(ctx context.Context, vm string) error { + return s.CallHost(ctx, "host/session.end", map[string]any{"vm": vm}, nil) +} + +// ScreenshotRegion crops a framebuffer capture in source pixel coordinates. +type ScreenshotRegion struct { + X int `json:"x"` + Y int `json:"y"` + Width int `json:"width"` + Height int `json:"height"` +} + +// ScreenshotRequest requests a full or cropped frame from a VM console. +type ScreenshotRequest struct { + VM string `json:"vm"` + Region *ScreenshotRegion `json:"region,omitempty"` + MaxEdge *int `json:"max_edge,omitempty"` // nil = default (1280 full, native cropped); 0 = native unscaled + Format string `json:"format,omitempty"` // "jpeg" | "png" +} + +// ScreenshotResult is the payload returned by `host/console.screenshot`. +type ScreenshotResult struct { + MimeType string `json:"mime_type"` + Width int `json:"width"` + Height int `json:"height"` + SourceWidth int `json:"source_width"` + SourceHeight int `json:"source_height"` + Region *ScreenshotRegion `json:"region,omitempty"` + Blank bool `json:"blank"` + Data string `json:"data"` +} + +// ConsoleScreenshot captures a full or cropped console screenshot. +func (s *Server) ConsoleScreenshot(ctx context.Context, req ScreenshotRequest) (ScreenshotResult, error) { + var resp ScreenshotResult + err := s.CallHost(ctx, "host/console.screenshot", req, &resp) + return resp, err +} + +// ConsolePointerRequest sends one pointer event to a VM console. +type ConsolePointerRequest struct { + VM string `json:"vm"` + Action string `json:"action"` // move | click | button | scroll + X int `json:"x,omitempty"` + Y int `json:"y,omitempty"` + Width int `json:"width,omitempty"` + Height int `json:"height,omitempty"` + Button string `json:"button,omitempty"` + Down *bool `json:"down,omitempty"` + Delta int `json:"delta,omitempty"` + Horizontal bool `json:"horizontal,omitempty"` +} + +// ConsolePointer sends a pointer action to a VM console. +func (s *Server) ConsolePointer(ctx context.Context, req ConsolePointerRequest) error { + return s.CallHost(ctx, "host/console.pointer", req, nil) +} + +// ConsoleKey sends a key press with optional modifiers to a VM console. +func (s *Server) ConsoleKey(ctx context.Context, vm, key string, modifiers ...string) error { + return s.CallHost(ctx, "host/console.key", map[string]any{ + "vm": vm, + "key": key, + "modifiers": modifiers, + }, nil) +} + +// ConsoleType types UTF-8 text into a VM console. +func (s *Server) ConsoleType(ctx context.Context, vm, text string) (int, error) { + var resp struct { + Characters int `json:"characters"` + } + err := s.CallHost(ctx, "host/console.type", map[string]any{"vm": vm, "text": text}, &resp) + return resp.Characters, err +} + +// ConsoleTypeSecret types a DPAPI-protected per-VM secret setting without trailing Enter. +func (s *Server) ConsoleTypeSecret(ctx context.Context, vm, setting string) (int, error) { + var resp struct { + Characters int `json:"characters"` + } + err := s.CallHost(ctx, "host/console.typeSecret", map[string]any{"vm": vm, "setting": setting}, &resp) + return resp.Characters, err +} + +// FinishInstallVM invokes the VM driver's finish_install action (eject installer, +// remove REIMSHELP, enable network, upgrade AHCI->NVMe; never mounts REIMSTOOLS). +func (s *Server) FinishInstallVM(ctx context.Context, vm string) (map[string]any, error) { + var resp map[string]any + err := s.CallHost(ctx, "host/vm.finishInstall", map[string]any{"vm": vm}, &resp) + return resp, err +} + +// RestartVM cleanly stops, waits for exit & memory reclaim, and restarts a VM. +func (s *Server) RestartVM(ctx context.Context, vm string) (map[string]any, error) { + var resp map[string]any + err := s.CallHost(ctx, "host/vm.restart", map[string]any{"vm": vm}, &resp) + return resp, err +} + +// TelemetryMilestone is one parsed boot/runtime milestone from serial/QEMU logs. +type TelemetryMilestone struct { + Key string `json:"key"` + Count int `json:"count"` + At string `json:"at"` +} + +// VMTelemetry is the redacted read-only snapshot returned by `host/vm.telemetry`. +type VMTelemetry struct { + VM string `json:"vm"` + State string `json:"state"` + Phase string `json:"phase"` + PID int `json:"pid"` + BootMilestones []TelemetryMilestone `json:"boot_milestones,omitempty"` + QemuErrors []string `json:"qemu_errors,omitempty"` + DiskBytes int64 `json:"disk_bytes"` + DiskDeltaBytes int64 `json:"disk_delta_bytes"` + CPUPercent float64 `json:"cpu_percent"` + ColdRebootCount int `json:"cold_reboot_count"` + UpdatedAt string `json:"updated_at,omitempty"` +} + +// VMTelemetry queries structured, redacted runtime telemetry for vm. +func (s *Server) VMTelemetry(ctx context.Context, vm string) (VMTelemetry, error) { + var resp VMTelemetry + err := s.CallHost(ctx, "host/vm.telemetry", map[string]any{"vm": vm}, &resp) + return resp, err +} + // Serve runs the JSON-RPC frame loop until EOF or `plugin/shutdown`. func (s *Server) Serve(ctx context.Context) error { for { diff --git a/pkg/pluginsdk/sdk_test.go b/pkg/pluginsdk/sdk_test.go index 2a9394f..23e6b0a 100644 --- a/pkg/pluginsdk/sdk_test.go +++ b/pkg/pluginsdk/sdk_test.go @@ -29,8 +29,8 @@ func TestServerLocaleHandshakeAndHotUpdate(t *testing.T) { var changedCount atomic.Int32 var lastChangedLocale atomic.Value srv.OnLocaleChanged(func(ev LocaleChangedEvent) { - changedCount.Add(1) lastChangedLocale.Store(ev.Locale) + changedCount.Add(1) }) ctx, cancel := context.WithCancel(context.Background()) -- 2.54.1 From 1f30307178d9ba48cf24c645ba92611aeaf5bca1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=A3=A0=E6=B8=9A=E5=90=AC=E6=BD=AE?= <108173440+reiasu2@users.noreply.github.com> Date: Sun, 6 Dec 2026 16:18:30 +0800 Subject: [PATCH 3/4] feat(diagnostics,ui): add log-bar diagnostics export dialog and long-copy guidance (#205) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 千川白浪 <1679659@qq.com> --- .github/changes/diagnostics-guidance.json | 7 + frontend/scripts/test-logs.mjs | 74 +- frontend/src/App.tsx | 70 +- .../components/DiagnosticsExportDialog.tsx | 172 +++++ frontend/src/components/LogPanel.tsx | 110 ++- frontend/src/components/VMPage.tsx | 5 +- frontend/src/i18n/domains/core.gen.ts | 54 ++ frontend/src/i18n/domains/vm.gen.ts | 2 - frontend/src/i18n/keys.gen.ts | 28 +- frontend/src/lib/logs.ts | 44 ++ frontend/src/styles/app.css | 53 +- frontend/src/types.ts | 9 + frontend/src/wails.ts | 3 +- frontend/wailsjs/go/app/App.d.ts | 6 +- frontend/wailsjs/go/app/App.js | 8 + frontend/wailsjs/go/models.ts | 60 ++ internal/app/diagnostics_flow.go | 473 +++++++++++-- internal/app/diagnostics_test.go | 648 +++++++++++++++++- internal/host/clipboard_file_other.go | 11 + internal/host/clipboard_file_test.go | 24 + internal/host/clipboard_file_windows.go | 136 ++++ internal/host/log_diagnose.go | 78 ++- internal/host/log_diagnose_test.go | 46 +- internal/host/open_shared_other.go | 10 + internal/host/open_shared_test.go | 83 +++ internal/host/open_shared_windows.go | 39 ++ internal/host/open_test.go | 18 + internal/host/open_windows.go | 35 + internal/host/open_windows_test.go | 13 + internal/host/stubs_system_other.go | 24 +- internal/i18n/catalog_gen.go | 55 ++ locales/en-US/core.json | 27 + locales/en-US/vm.json | 1 - locales/zh-CN/core.json | 27 + locales/zh-CN/vm.json | 1 - 35 files changed, 2349 insertions(+), 105 deletions(-) create mode 100644 .github/changes/diagnostics-guidance.json create mode 100644 frontend/src/components/DiagnosticsExportDialog.tsx create mode 100644 internal/host/clipboard_file_other.go create mode 100644 internal/host/clipboard_file_test.go create mode 100644 internal/host/clipboard_file_windows.go create mode 100644 internal/host/open_shared_other.go create mode 100644 internal/host/open_shared_test.go create mode 100644 internal/host/open_shared_windows.go create mode 100644 internal/host/open_test.go create mode 100644 internal/host/open_windows_test.go diff --git a/.github/changes/diagnostics-guidance.json b/.github/changes/diagnostics-guidance.json new file mode 100644 index 0000000..11c2108 --- /dev/null +++ b/.github/changes/diagnostics-guidance.json @@ -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." +} diff --git a/frontend/scripts/test-logs.mjs b/frontend/scripts/test-logs.mjs index d567ab0..2c0c042 100644 --- a/frontend/scripts/test-logs.mjs +++ b/frontend/scripts/test-logs.mjs @@ -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', + ) +}) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index a206224..37514bf 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -2,6 +2,7 @@ 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 { SidebarToggle, TitleMenus } from './components/TitleMenus' @@ -34,7 +35,7 @@ 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, AutoInstallerProviderView, AutoInstallStartRequest, CachedInstaller, CreateOpts, DriverSummary, Locale, PluginUIContributions, ProvisionRequest, 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' @@ -131,6 +132,11 @@ export const App: React.FC = () => { const [cloneSource, setCloneSource] = useState<{ name: string; driverID: string } | null>(null) const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState(null) const [sendTextTarget, setSendTextTarget] = useState(null) + const [diagResult, setDiagResult] = useState(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(null) @@ -830,6 +836,7 @@ export const App: React.FC = () => { activeBusy && action !== 'openFolder' && action !== 'openSharedFolder' + && action !== 'exportDiagnostics' && (action !== 'forceStop' || activeBusy === 'forceStop') ) { return @@ -860,7 +867,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 }) @@ -1112,6 +1119,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() @@ -1120,7 +1168,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 || confirmQueue.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 @@ -1424,6 +1472,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 @@ -1554,6 +1603,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)} /> @@ -1656,6 +1707,19 @@ export const App: React.FC = () => { /> )} + {diagResult && ( + { void handleCopyDiagnosticsFile() }} + onRevealFile={() => { void handleRevealDiagnosticsFile() }} + onCopySummary={() => { if (diagResult.summary_text) void copy(diagResult.summary_text) }} + onClose={() => setDiagResult(null)} + /> + )} + {/* Outside the isolated shell so toasts stay above dialogs and the overlay layer. */} diff --git a/frontend/src/components/DiagnosticsExportDialog.tsx b/frontend/src/components/DiagnosticsExportDialog.tsx new file mode 100644 index 0000000..2ad03c6 --- /dev/null +++ b/frontend/src/components/DiagnosticsExportDialog.tsx @@ -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 = { + 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 = ({ + locale, + result, + copyingFile = false, + revealingFile = false, + onCopyFile, + onRevealFile, + onCopySummary, + onClose, +}) => { + const tr = (k: I18nKey, v?: Record) => 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 ( + +
+
+ {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 ( +
+
+ +
+
{title}
+ {desc &&
{desc}
} + {finding.detail && ( +
+ {tr('errRawDetailsToggle')} +
{finding.detail}
+
+ )} +
+
+
+ ) + }) + ) : ( +
+
+ +
+
{tr('diagNoFindingsTitle')}
+
{tr('diagNoFindingsDesc')}
+
+
+
+ )} +
+ +
+
{tr('diagChecklistTitle')}
+
    +
  • {tr('diagChecklistZip')}
  • +
  • {tr('diagChecklistSteps')}
  • +
+ {includedFiles.length > 0 && ( +
+
{tr('diagIncludedFiles')}
+
+ {includedFiles.map((file) => ( + {file} + ))} +
+
+ )} +
+ + {result.summary_text && ( +
+ {tr('diagSummaryToggle')} +
{result.summary_text}
+
+ )} +
+ +
+
+ + {result.can_copy_file && ( + + )} +
+ {result.can_copy_file ? ( + + ) : ( + + )} +
+
+ ) +} diff --git a/frontend/src/components/LogPanel.tsx b/frontend/src/components/LogPanel.tsx index 6257a11..c3e76f3 100644 --- a/frontend/src/components/LogPanel.tsx +++ b/frontend/src/components/LogPanel.tsx @@ -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 = ({ 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[1], v?: Record) => 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,13 +102,59 @@ export const LogPanel: React.FC = ({ 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) => { + 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('.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) }) } } @@ -332,6 +382,16 @@ export const LogPanel: React.FC = ({ {open && onCopy && ( } onClick={copyVisible} /> )} + {open && onExportDiagnostics && ( + + )} {open && tab === 'app' && lines.length > 0 && ( } onClick={onClear} /> )} @@ -359,7 +419,7 @@ export const LogPanel: React.FC = ({ {open && (
-
+
{tab === 'app' ? (filteredLines.length === 0 ? {tr('logsEmpty')} @@ -373,6 +433,40 @@ export const LogPanel: React.FC = ({ )}
)} + {largeCopyPending && onExportDiagnostics && ( + setLargeCopyPending(null)} + > +
+

{tr('logLargeCopyDesc', { n: largeCopyPending.lines })}

+
+
+ + +
+
+ )}
) } diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index 901546f..1cb7994 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -82,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 @@ -141,7 +142,7 @@ function ShutdownButton({ locale, busyAction, onAction }: Pick = ({ - locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, currentAgentVersion, guideActive, installGuideEnabled, detail, vmInfo, host, pending, busyAction, onAction, onPluginCommand, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI, fullscreenHotkey, agentSession, provisionReady, autoInstallers, onStopAgentSession, onPauseAgentSession, onResumeAgentSession, + 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) => t(locale, k, v) const busy = busyAction !== undefined @@ -377,7 +378,7 @@ export const VMPage: React.FC = ({ {tr('viewLogs')} - onAction('exportDiagnostics')}> + onAction('exportDiagnostics')}> {tr('exportDiagnostics')} {toolbarMenus.map((m) => { diff --git a/frontend/src/i18n/domains/core.gen.ts b/frontend/src/i18n/domains/core.gen.ts index cde0c99..1c23315 100644 --- a/frontend/src/i18n/domains/core.gen.ts +++ b/frontend/src/i18n/domains/core.gen.ts @@ -28,6 +28,27 @@ export const coreZh: Record = { "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 = { "errorBoundaryReload": "重新加载界面", "errorBoundaryTitle": "界面遇到意外错误", "expandLogs": "展开日志", + "failCopyDiagnosticsFile": "复制排障包失败", "failCreate": "{name} 创建失败", "failDownload": "下载失败", "failGeneric": "操作失败", @@ -101,7 +123,11 @@ export const coreZh: Record = { "logActivity": "活动", "logButton": "日志", "logCopy": "复制日志", + "logCopyAnyway": "仍然复制", "logErrorsOnly": "仅错误/警告", + "logExportDiagnostics": "导出排障包", + "logLargeCopyDesc": "即将复制 {n} 行日志,直接粘贴容易刷屏且缺少环境信息,建议导出排障包", + "logLargeCopyTitle": "大段日志", "logQemu": "QEMU", "logSearchPlaceholder": "筛选日志…", "logSerial": "串口", @@ -204,6 +230,7 @@ export const coreZh: Record = { "toastCreateCanceled": "已取消创建 {name}", "toastCreateCanceledPartial": "已下载部分已保留,可继续下载或返回修改", "toastCreated": "{name} 已创建", + "toastDiagFileCopied": "已复制排障包文件,可直接粘贴发送", "toastDownloadPaused": "已暂停,再次下载会从中断处继续", "toastInstallerReady": "macOS {v} 安装包已就绪", "toastQueueCanceled": "已取消排队", @@ -264,6 +291,27 @@ export const coreEn: Record = { "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.", @@ -283,6 +331,7 @@ export const coreEn: Record = { "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", @@ -337,7 +386,11 @@ export const coreEn: Record = { "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", @@ -440,6 +493,7 @@ export const coreEn: Record = { "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", diff --git a/frontend/src/i18n/domains/vm.gen.ts b/frontend/src/i18n/domains/vm.gen.ts index f9b416e..245dc6c 100644 --- a/frontend/src/i18n/domains/vm.gen.ts +++ b/frontend/src/i18n/domains/vm.gen.ts @@ -280,7 +280,6 @@ export const vmZh: Record = { "techInfo": "技术信息", "toastCloned": "已派生 CoW 副本「{name}」", "toastDeleted": "已删除 {name}", - "toastDiagExported": "已导出脱敏排障日志包 (.zip)", "toastDiscardSuspend": "已放弃 {name} 的挂起状态", "toastEjected": "已弹出安装盘", "toastEnterRecovery": "已进入恢复模式,启动后可在引导菜单选 Recovery", @@ -598,7 +597,6 @@ export const vmEn: Record = { "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", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 04dc01e..28b45da 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -222,8 +222,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" @@ -335,6 +356,7 @@ export type I18nKey = | "factMemory" | "failAttachInstaller" | "failCloneVM" + | "failCopyDiagnosticsFile" | "failCreate" | "failDelete" | "failDiscardSuspend" @@ -666,7 +688,11 @@ export type I18nKey = | "logActivity" | "logButton" | "logCopy" + | "logCopyAnyway" | "logErrorsOnly" + | "logExportDiagnostics" + | "logLargeCopyDesc" + | "logLargeCopyTitle" | "logLevel" | "logLevelCustom" | "logLevelDesc" @@ -1177,7 +1203,7 @@ export type I18nKey = | "toastCreateCanceledPartial" | "toastCreated" | "toastDeleted" - | "toastDiagExported" + | "toastDiagFileCopied" | "toastDiscardSuspend" | "toastDownloadPaused" | "toastEjected" diff --git a/frontend/src/lib/logs.ts b/frontend/src/lib/logs.ts index 91ef084..223610a 100644 --- a/frontend/src/lib/logs.ts +++ b/frontend/src/lib/logs.ts @@ -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 diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 6ec6278..01516d5 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -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 { diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 7d36fb4..8527696 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -40,6 +40,15 @@ export type HostReport = Omit, 'gpus' | 'recommended_gpu'> & recommended_gpu?: GPUInfo } +export type DiagnosticFinding = Model & { + code: 'gpu_device_lost' | 'gpu_vulkan_floor' | 'whpx_unavailable' | 'low_memory' | 'low_disk' + severity: 'error' | 'warn' +} + +export type DiagnosticsExportResult = Omit, 'findings'> & { + findings: DiagnosticFinding[] +} + export type InstalledRuntime = Model export type RemoteRuntime = Model & { diff --git a/frontend/src/wails.ts b/frontend/src/wails.ts index c89cd97..bb1aed8 100644 --- a/frontend/src/wails.ts +++ b/frontend/src/wails.ts @@ -15,7 +15,7 @@ import { WindowToggleMaximise as RawWindowToggleMaximise, } from '../wailsjs/runtime/runtime' import type { - ActiveThemePayload, AppState, AutoInstallerProviderView, AutoInstallStartRequest, AutoInstallStatus, CachedInstaller, DataRootChoice, DriverSummary, + 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, GetVMNetworkSettings: boundGo.GetVMNetworkSettings as (name: string) => Promise, GetVMNetworkPlan: boundGo.GetVMNetworkPlan as (name: string, mode: string, uplink: string) => Promise, ListNetworkAdapters: boundGo.ListNetworkAdapters as () => Promise, diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index f6def4a..3e520ae 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -40,6 +40,8 @@ export function CompactVMDisk(arg1:string,arg2:string):Promise; +export function CopyDiagnosticsFile(arg1:string):Promise; + export function CopyVMScreenshot(arg1:string,arg2:string):Promise; export function CreateSnapshot(arg1:string,arg2:string,arg3:string):Promise; @@ -78,7 +80,7 @@ export function EnablePlugin(arg1:string,arg2:boolean):Promise; export function EnterRecovery(arg1:string):Promise; -export function ExportDiagnostics(arg1:string,arg2:string):Promise; +export function ExportDiagnostics(arg1:string,arg2:string):Promise; export function FinishInstall(arg1:string):Promise; @@ -264,6 +266,8 @@ export function RestoreSnapshot(arg1:string,arg2:string,arg3:string):Promise; +export function RevealDiagnosticsFile(arg1:string):Promise; + export function SaveCustomThemeScheme(arg1:plugin.CustomThemeScheme):Promise; export function ScanInstalledPlugin(arg1:string):Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index 67b87e4..ab9a20e 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -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); } @@ -450,6 +454,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); } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index f25b5ae..2a88ef3 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -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; diff --git a/internal/app/diagnostics_flow.go b/internal/app/diagnostics_flow.go index bf920c4..a2c3052 100644 --- a/internal/app/diagnostics_flow.go +++ b/internal/app/diagnostics_flow.go @@ -2,11 +2,17 @@ package app import ( "archive/zip" + "bytes" "context" "encoding/json" + "errors" "fmt" + "io" + "maps" "os" "path/filepath" + "regexp" + "slices" "strings" "time" @@ -14,8 +20,20 @@ import ( "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/plugin" rt "github.com/Nwflower/reims-go/internal/runtime" + "github.com/Nwflower/reims-go/internal/version" ) +type DiagnosticsExportResult struct { + Path string `json:"path"` + FileName string `json:"file_name"` + SizeBytes int64 `json:"size_bytes"` + TargetLabel string `json:"target_label"` + IncludedFiles []string `json:"included_files"` + SummaryText string `json:"summary_text"` + Findings []host.DiagnosticFinding `json:"findings"` + CanCopyFile bool `json:"can_copy_file"` +} + type diagnosticsBundle struct { HostReport host.Report Optimizations []host.Optimization @@ -23,39 +41,101 @@ type diagnosticsBundle struct { VMDetail any // legacy test/export payload; production uses VMInfo VMInfo *driver.VMInfo SerialLog string + SerialTruncated bool QEMULog string + QEMUTruncated bool AppLogs []string PluginDiagnostics []plugin.DiagnosticsEntry } -func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error { - if err := os.MkdirAll(filepath.Dir(zipPath), 0o755); err != nil { - return err +func writeDiagnosticsZip(reportsDir, label string, generatedAt time.Time, b diagnosticsBundle) (_ DiagnosticsExportResult, err error) { + if err := os.MkdirAll(reportsDir, 0o755); err != nil { + return DiagnosticsExportResult{}, err } - f, err := os.Create(zipPath) + f, err := os.CreateTemp(reportsDir, fmt.Sprintf("reims-go-diag-%s-%s-*.zip", label, generatedAt.Local().Format("20060102-150405"))) if err != nil { - return err + return DiagnosticsExportResult{}, err } + defer func() { + if err != nil { + err = errors.Join(err, os.Remove(f.Name())) + } + }() + zw := zip.NewWriter(f) + result, writeErr := writeDiagnosticsEntries(zw, label, generatedAt, b) + if err := errors.Join(writeErr, zw.Close(), f.Close()); err != nil { + return DiagnosticsExportResult{}, err + } + info, err := os.Stat(f.Name()) + if err != nil { + return DiagnosticsExportResult{}, err + } + result.Path = f.Name() + result.FileName = info.Name() + result.SizeBytes = info.Size() + result.CanCopyFile = host.CanCopyFileToClipboard() + return result, nil +} + +func writeDiagnosticsEntries(zw *zip.Writer, label string, generatedAt time.Time, b diagnosticsBundle) (DiagnosticsExportResult, error) { + appLogs := b.AppLogs + if b.VMInfo != nil { + appLogs = filterAppLogsForVM(appLogs, b.VMInfo.Ref()) + } + result := DiagnosticsExportResult{ + TargetLabel: label, + IncludedFiles: []string{}, + Findings: host.AnalyzeDiagnostics(b.HostReport, b.QEMULog, b.SerialLog, appLogs), + } + redact := diagnosticsRedactor(b) + for i := range result.Findings { + result.Findings[i].Detail = redact(result.Findings[i].Detail) + } addFile := func(name, content string) error { w, err := zw.Create(name) if err != nil { return err } - _, err = w.Write([]byte(host.RedactText(content))) - return err + if _, err := w.Write([]byte(content)); err != nil { + return err + } + result.IncludedFiles = append(result.IncludedFiles, name) + return nil } addJSON := func(name string, v any) error { - raw, err := json.MarshalIndent(v, "", " ") + raw, err := json.Marshal(v) + if err != nil { + return err + } + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.UseNumber() + var value any + if err := decoder.Decode(&value); err != nil { + return err + } + raw, err = json.MarshalIndent(redactDiagnosticsJSON(value, redact), "", " ") if err != nil { return err } return addFile(name, string(raw)+"\n") } + rep := b.HostReport + rep.GPUs = slices.Clone(rep.GPUs) + for i := range rep.GPUs { + if rep.GPUs[i].VulkanICD != "" { + rep.GPUs[i].VulkanICD = "[redacted]" + } + } + if rep.RecommendedGPU != nil && rep.RecommendedGPU.VulkanICD != "" { + gpu := *rep.RecommendedGPU + gpu.VulkanICD = "[redacted]" + rep.RecommendedGPU = &gpu + } hostSummary := map[string]any{ - "generated_at": time.Now().UTC().Format(time.RFC3339), - "host": b.HostReport, + "generated_at": generatedAt.UTC().Format(time.RFC3339), + "host": rep, "optimizations": b.Optimizations, } if code, detail := host.DiagnoseGPULog(b.QEMULog); code != "" { @@ -65,74 +145,259 @@ func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error { } } if err := addJSON("host-report.json", hostSummary); err != nil { - _ = zw.Close() - _ = f.Close() - return err + return DiagnosticsExportResult{}, err } if b.Runtime != nil { if err := addJSON("runtime-manifest.json", b.Runtime.Manifest); err != nil { - _ = zw.Close() - _ = f.Close() - return err + return DiagnosticsExportResult{}, err } } if b.VMDetail != nil { if err := addJSON("vm-detail.json", b.VMDetail); err != nil { - _ = zw.Close() - _ = f.Close() - return err + return DiagnosticsExportResult{}, err } } if b.VMInfo != nil { if err := addJSON("vm-info.json", b.VMInfo); err != nil { - _ = zw.Close() - _ = f.Close() - return err + return DiagnosticsExportResult{}, err } } if strings.TrimSpace(b.SerialLog) != "" { - if err := addFile("serial.log", b.SerialLog); err != nil { - _ = zw.Close() - _ = f.Close() - return err + if err := addFile("serial.log", redact(b.SerialLog)); err != nil { + return DiagnosticsExportResult{}, err } } if strings.TrimSpace(b.QEMULog) != "" { - if err := addFile("qemu.log", b.QEMULog); err != nil { - _ = zw.Close() - _ = f.Close() - return err + if err := addFile("qemu.log", redact(b.QEMULog)); err != nil { + return DiagnosticsExportResult{}, err } } if len(b.AppLogs) > 0 { - if err := addFile("app-logs.txt", strings.Join(b.AppLogs, "\n")+"\n"); err != nil { - _ = zw.Close() - _ = f.Close() - return err + if err := addFile("app-logs.txt", redact(strings.Join(b.AppLogs, "\n"))+"\n"); err != nil { + return DiagnosticsExportResult{}, err } } if len(b.PluginDiagnostics) > 0 { if err := addJSON("plugin-diagnostics.json", b.PluginDiagnostics); err != nil { - _ = zw.Close() - _ = f.Close() - return err + return DiagnosticsExportResult{}, err } } - if err := zw.Close(); err != nil { - _ = f.Close() - return err + result.SummaryText = redact(diagnosticsSummary(b, generatedAt, result, append(result.IncludedFiles, "summary.txt"))) + if err := addFile("summary.txt", result.SummaryText); err != nil { + return DiagnosticsExportResult{}, err } - return f.Close() + return result, nil +} + +func redactDiagnosticsJSON(value any, redact func(string) string) any { + switch v := value.(type) { + case string: + return redact(v) + case []any: + for i, item := range v { + v[i] = redactDiagnosticsJSON(item, redact) + } + case map[string]any: + return redactJSONMap(v, redact) + } + return value +} + +func redactJSONMap(data map[string]any, redact func(string) string) map[string]any { + redacted := make(map[string]any, len(data)) + nextSuffix := make(map[string]int) + for _, key := range slices.Sorted(maps.Keys(data)) { + base := redact(key) + name := base + if _, exists := redacted[base]; exists { + suffix := max(2, nextSuffix[base]) + for { + name = fmt.Sprintf("%s #%d", base, suffix) + suffix++ + if _, exists := redacted[name]; !exists { + break + } + } + nextSuffix[base] = suffix + } + if item, ok := data[key].(string); ok && item != "" && isDiagnosticsSensitiveField(key) { + redacted[name] = "[redacted]" + continue + } + redacted[name] = redactDiagnosticsJSON(data[key], redact) + } + return redacted +} + +func isDiagnosticsSensitiveField(key string) bool { + switch strings.ToLower(key) { + case "mac", "mac_address", "macaddress", "osk", "smc_osk", "serial", "serial_number", "serialnumber", + "system_serial", "system_serial_number", "systemserial", "systemserialnumber", "systemserial_number", + "mlb", "rom", "smuuid", "system_uuid", "systemuuid", "uuid", + "reims_token", "github_token", "token", "access_token", "refresh_token", "auth_token", + "api_key", "apikey", "password", "passwd", "secret", "authorization", "cookie": + return true + } + return false +} + +var ( + diagnosticsPathStart = regexp.MustCompile(`(?i)(?:^|[\s"'=(,\[])([a-z]:[/\\]|(?:\\\\|//)[^/\\\s"'=,;()\[\]]+[/\\]|\[redacted\][/\\])`) + diagnosticsPathEnd = regexp.MustCompile(`(?i)["'\r\n;,)\]]|:[ \t]|[ \t]+(?:-|Authorization:|[a-z][a-z0-9+.-]*://)`) + diagnosticsSingleQuotedPathEnd = regexp.MustCompile(`[\r\n]|'(?:$|[\s:;,)\]"])`) +) + +func redactDiagnosticsWindowsPaths(content string) string { + matches := diagnosticsPathStart.FindAllStringSubmatchIndex(content, -1) + if len(matches) == 0 { + return content + } + var out strings.Builder + end := 0 + for _, match := range matches { + start := match[2] + if start < end { + continue + } + out.WriteString(content[end:start]) + out.WriteString("[redacted]") + end = diagnosticsWindowsPathEnd(content, start, match[3]) + } + out.WriteString(content[end:]) + return out.String() +} + +func diagnosticsWindowsPathEnd(content string, start, prefixEnd int) int { + rest := content[prefixEnd:] + if start > 0 && content[start-1] == '\'' { + if stop := diagnosticsSingleQuotedPathEnd.FindStringIndex(rest); stop != nil { + return prefixEnd + stop[0] + } + return len(content) + } + if start > 0 && content[start-1] == '"' { + if close := strings.IndexByte(rest, '"'); close >= 0 && !strings.ContainsAny(rest[:close], "\r\n") { + return prefixEnd + close + } + } + if stop := diagnosticsPathEnd.FindStringIndex(rest); stop != nil { + rest = rest[:stop[0]] + } + return prefixEnd + len(strings.TrimRight(rest, " \t")) +} + +func diagnosticsRedactor(b diagnosticsBundle) func(string) string { + home, _ := os.UserHomeDir() + paths := []string{b.HostReport.DataRoot, home} + if b.VMInfo != nil { + paths = append(paths, b.VMInfo.Directory, b.VMInfo.DiskPath) + } + if b.Runtime != nil { + paths = append(paths, b.Runtime.Dir) + } + var roots []*regexp.Regexp + // Match VM files and runtime directories before their enclosing data root. + slices.SortFunc(paths, func(a, b string) int { return len(b) - len(a) }) + for _, path := range paths { + if !filepath.IsAbs(path) || filepath.Dir(path) == path { + continue + } + pattern := regexp.QuoteMeta(path) + if filepath.Separator == '\\' { + parts := strings.Split(filepath.ToSlash(path), "/") + for i, part := range parts { + parts[i] = regexp.QuoteMeta(part) + } + pattern = "(?i)" + strings.Join(parts, `[/\\]`) + } + roots = append(roots, regexp.MustCompile(pattern+`($|[/\\\r\n"'<>|:*?])`)) + } + return func(content string) string { + // A known root may contain punctuation that terminates an unquoted path. + for _, root := range roots { + content = root.ReplaceAllString(content, "[redacted]${1}") + } + return host.RedactText(redactDiagnosticsWindowsPaths(content)) + } +} + +func filterAppLogsForVM(logs []string, ref driver.VMRef) []string { + target := ref.Key() + var filtered []string + for _, line := range logs { + _, entry, ok := strings.Cut(line, " [") + if !ok { + continue + } + if strings.HasPrefix(entry, target+"] ") { + filtered = append(filtered, line) + continue + } + source, _, _ := strings.Cut(entry, "] ") + switch source { + case "app", "host", "runtime", "installer", "network", "ui": + filtered = append(filtered, line) + } + } + return filtered +} + +func diagnosticsSummary(b diagnosticsBundle, generatedAt time.Time, result DiagnosticsExportResult, files []string) string { + var summary strings.Builder + rep := b.HostReport + fmt.Fprintf(&summary, "Reims-Go diagnostics\nGenerated (UTC): %s\nApplication version: %s\nTarget: %s\n", + generatedAt.UTC().Format(time.RFC3339), version.Version, result.TargetLabel) + fmt.Fprintf(&summary, "\nHost\nSystem: %s %s\nCPU: %d logical, %d physical\nMemory: %.1f GB available / %.1f GB total\nData disk: %.1f GB free (%s)\nWHPX: %s\n", + rep.OS, rep.Arch, rep.LogicalCPUs, rep.PhysicalCores, rep.AvailRAMGB, rep.TotalRAMGB, rep.FreeDiskGB, rep.DataRootDriveType, rep.WHPX) + if len(rep.GPUs) == 0 { + summary.WriteString("GPU: unavailable\n") + } + for _, gpu := range rep.GPUs { + fmt.Fprintf(&summary, "GPU: %s (driver %s, Vulkan %s)\n", gpu.Name, gpu.DriverVersion, gpu.VulkanVersion) + } + summary.WriteString("\nActive runtime\n") + if b.Runtime == nil { + summary.WriteString("None\n") + } else { + m := b.Runtime.Manifest + fmt.Fprintf(&summary, "%s (commit %s, channel %s, QEMU %s)\n", m.Name, b.Runtime.Commit, m.Channel, m.QemuVersion) + } + if vm := b.VMInfo; vm != nil { + fmt.Fprintf(&summary, "\nVirtual machine\nName: %s\nDriver: %s\nState: %s\nCPU: %d vCPUs\nMemory: %s\nDisk: %s\n", + vm.Name, vm.DriverID, vm.State, vm.CPUs, vm.Memory, vm.DiskSummary) + } + summary.WriteString("\nAutomatic checks\n") + if len(result.Findings) == 0 { + summary.WriteString("No known issues found\n") + } + for _, finding := range result.Findings { + fmt.Fprintf(&summary, "- %s: %s", finding.Severity, finding.Code) + if finding.Detail != "" { + fmt.Fprintf(&summary, " (%s)", finding.Detail) + } + summary.WriteByte('\n') + } + fmt.Fprintf(&summary, "\nIncluded files\n- %s\n", strings.Join(files, "\n- ")) + if b.SerialTruncated { + summary.WriteString("serial.log truncated: first 1 MiB and last 4 MiB retained\n") + } + if b.QEMUTruncated { + summary.WriteString("qemu.log truncated: first 1 MiB and last 4 MiB retained\n") + } + return summary.String() } // ExportDiagnostics collects a redacted troubleshooting zip bundle through the owning driver. -func (a *App) ExportDiagnostics(driverID, name string) (string, error) { +func (a *App) ExportDiagnostics(driverID, name string) (DiagnosticsExportResult, error) { + if err := a.requireWritableDataRoot(); err != nil { + return DiagnosticsExportResult{}, err + } var vm driver.VMInfo var err error if strings.TrimSpace(name) != "" { vm, err = a.resolveVMInfo(driverID, name) if err != nil { - return "", err + return DiagnosticsExportResult{}, err } } cfgCopy := a.runtimeConfig() @@ -153,21 +418,119 @@ func (a *App) ExportDiagnostics(driverID, name string) (string, error) { if ref.DriverID != driver.BuiltinReimsMacOSDriverID { label = sshHostAlias(ref.DriverID, vm.Name) } - if serial, err := a.ReadVMLogs(ref.DriverID, vm.Name, true); err == nil { - bundle.SerialLog = serial - } - if qemuLog, err := a.ReadVMLogs(ref.DriverID, vm.Name, false); err == nil { - bundle.QEMULog = qemuLog - } + bundle.SerialLog, bundle.SerialTruncated = a.readDiagnosticsLog(vm, true) + bundle.QEMULog, bundle.QEMUTruncated = a.readDiagnosticsLog(vm, false) } bundle.HostReport, bundle.Optimizations, bundle.Runtime, bundle.AppLogs = rep, a.evaluateOptimizations(rep), active, appLogs bundle.VMInfo, bundle.PluginDiagnostics = info, a.collectPluginDiagnostics(context.Background(), pluginKey) - reportsDir := filepath.Join(cfgCopy.DataRoot, "reports") - zipPath := filepath.Join(reportsDir, fmt.Sprintf("reims-go-diag-%s-%s.zip", label, time.Now().Format("20060102-150405"))) - if err := writeDiagnosticsZip(zipPath, bundle); err != nil { + reportsDir, err := filepath.Abs(filepath.Join(cfgCopy.DataRoot, "reports")) + if err != nil { + return DiagnosticsExportResult{}, err + } + result, err := writeDiagnosticsZip(reportsDir, label, time.Now(), bundle) + if err != nil { + return DiagnosticsExportResult{}, err + } + a.emitLog(label, "Diagnostics exported: "+result.Path) + return result, nil +} + +func (a *App) readDiagnosticsLog(vm driver.VMInfo, serial bool) (string, bool) { + ref := vm.Ref() + if ref.DriverID != driver.BuiltinReimsMacOSDriverID || vm.Directory == "" { + log, err := a.ReadVMLogs(ref.DriverID, ref.Name, serial) + if err != nil { + return "", false + } + return log, false + } + name := "qemu.log" + if serial { + name = "serial.log" + } + f, err := host.OpenFileSharedRead(filepath.Join(vm.Directory, "logs", name)) + if err != nil { + return "", false + } + defer f.Close() + info, err := f.Stat() + if err != nil { + return "", false + } + const ( + maxLogBytes = 16 << 20 + headLogBytes = 1 << 20 + tailLogBytes = 4 << 20 + ) + if info.Size() <= maxLogBytes { + log, _ := io.ReadAll(io.NewSectionReader(f, 0, info.Size())) + return string(log), false + } + head, _ := io.ReadAll(io.NewSectionReader(f, 0, headLogBytes)) + head = head[:bytes.LastIndexByte(head, '\n')+1] + // Include the byte before the tail to detect an exact line boundary. + tail, _ := io.ReadAll(io.NewSectionReader(f, info.Size()-tailLogBytes-1, tailLogBytes+1)) + _, tail, _ = bytes.Cut(tail, []byte("\n")) + return string(head) + "\n[log truncated: middle omitted]\n" + string(tail), true +} + +func (a *App) RevealDiagnosticsFile(path string) error { + resolved, err := resolveDiagnosticsZipPath(a.currentDataRoot(), path) + if err != nil { + return err + } + return host.RevealFile(resolved) +} + +func (a *App) CopyDiagnosticsFile(path string) error { + resolved, err := resolveDiagnosticsZipPath(a.currentDataRoot(), path) + if err != nil { + return err + } + return host.CopyFileToClipboard(resolved) +} + +func resolveDiagnosticsZipPath(dataRoot, rawPath string) (string, error) { + if dataRoot == "" || !strings.EqualFold(filepath.Ext(rawPath), ".zip") { + return "", fmt.Errorf("expected a diagnostics .zip file in the reports directory") + } + reportsDir, err := filepath.Abs(filepath.Join(dataRoot, "reports")) + if err != nil { return "", err } - a.emitLog(label, "Diagnostics exported: "+zipPath) - _ = host.OpenFolder(reportsDir) - return zipPath, nil + path, err := filepath.Abs(rawPath) + if err != nil { + return "", err + } + rel, err := filepath.Rel(reportsDir, filepath.Dir(path)) + if err != nil || rel != "." { + return "", fmt.Errorf("the diagnostics file is outside the reports directory") + } + reportsDir, err = filepath.EvalSymlinks(reportsDir) + if err != nil { + return "", err + } + path, err = filepath.EvalSymlinks(path) + if err != nil { + return "", err + } + reportsInfo, err := os.Stat(reportsDir) + if err != nil { + return "", err + } + parentInfo, err := os.Stat(filepath.Dir(path)) + if err != nil { + return "", err + } + if !os.SameFile(reportsInfo, parentInfo) { + return "", fmt.Errorf("the diagnostics file is outside the reports directory") + } + info, err := os.Stat(path) + if err != nil { + return "", err + } + if !info.Mode().IsRegular() || !strings.EqualFold(filepath.Ext(path), ".zip") { + return "", fmt.Errorf("expected a regular diagnostics .zip file") + } + return path, nil } diff --git a/internal/app/diagnostics_test.go b/internal/app/diagnostics_test.go index b85d107..0975fdf 100644 --- a/internal/app/diagnostics_test.go +++ b/internal/app/diagnostics_test.go @@ -2,47 +2,103 @@ package app import ( "archive/zip" + "context" + "encoding/json" + "errors" "io" + "io/fs" + "maps" + "math" + "os" + "os/exec" "path/filepath" + "runtime" + "slices" "strings" "testing" + "time" + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/dataroot" + "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/host" + vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle" "github.com/Nwflower/reims-go/internal/macos/reims" + "github.com/Nwflower/reims-go/internal/plugin" + rt "github.com/Nwflower/reims-go/internal/runtime" + "github.com/Nwflower/reims-go/internal/version" ) func TestWriteDiagnosticsZipRedactsSensitiveData(t *testing.T) { - zipPath := filepath.Join(t.TempDir(), "reports", "diag.zip") - err := writeDiagnosticsZip(zipPath, diagnosticsBundle{ - HostReport: host.Report{OS: "windows", LogicalCPUs: 16, DataRootDriveType: "fixed"}, + dataRoot := t.TempDir() + generatedAt := time.Date(2026, 12, 5, 10, 0, 0, 0, time.UTC) + result, err := writeDiagnosticsZip(filepath.Join(dataRoot, "reports"), "macos-tahoe", generatedAt, diagnosticsBundle{ + HostReport: host.Report{ + OS: "windows", Arch: "amd64", LogicalCPUs: 16, TotalRAMGB: 32, AvailRAMGB: 12, + FreeDiskGB: 64, DataRoot: dataRoot, DataRootDriveType: "fixed", + GPUs: []host.GPUInfo{{Name: "Test GPU", VulkanVersion: "1.3"}}, + }, + Runtime: &rt.Installed{Commit: "test-commit", Manifest: rt.Manifest{Name: "Test runtime", QemuVersion: "10"}}, + VMInfo: &driver.VMInfo{Name: "macos-tahoe", CPUs: 4, Memory: "8G", DiskSummary: "64 GB"}, VMDetail: &reims.VMDetail{ Name: "macos-tahoe", NetworkSummary: "user, mac 52:54:00:ab:cd:ef, ssh on 127.0.0.1:2222", ExtraArgs: "-device isa-applesmc,osk=ourhardworkbythesewordsguardedpleasedontsteal", }, SerialLog: "OpenCore presents iMac20,1, serial C02FAKE123456\n", - QEMULog: "Authorization: Bearer 0123456789abcdef0123456789abcdef\n", + QEMULog: "ERROR_DEVICE_LOST " + filepath.Join(dataRoot, "vm.log") + " Authorization: Bearer 0123456789abcdef0123456789abcdef\n", AppLogs: []string{`REIMS_TOKEN="abcdef0123456789abcdef0123456789"`}, }) if err != nil { t.Fatalf("writeDiagnosticsZip: %v", err) } - zr, err := zip.OpenReader(zipPath) + zr, err := zip.OpenReader(result.Path) if err != nil { t.Fatal(err) } defer zr.Close() var all strings.Builder + var archivedFiles []string for _, f := range zr.File { rc, err := f.Open() if err != nil { t.Fatal(err) } - b, _ := io.ReadAll(rc) + b, err := io.ReadAll(rc) rc.Close() + if err != nil { + t.Fatal(err) + } all.WriteString(f.Name + ":\n" + string(b) + "\n") + archivedFiles = append(archivedFiles, f.Name) + if f.Name == "summary.txt" && string(b) != result.SummaryText { + t.Fatalf("archive summary differs from returned summary") + } + } + wantFiles := []string{"host-report.json", "runtime-manifest.json", "vm-detail.json", "vm-info.json", "serial.log", "qemu.log", "app-logs.txt", "summary.txt"} + if !slices.Equal(result.IncludedFiles, archivedFiles) || !slices.Equal(archivedFiles, wantFiles) { + t.Fatalf("returned files = %v, archived files = %v, want %v", result.IncludedFiles, archivedFiles, wantFiles) + } + info, err := os.Stat(result.Path) + if err != nil { + t.Fatal(err) + } + if result.FileName != info.Name() || result.SizeBytes != info.Size() || result.SizeBytes == 0 || + result.TargetLabel != "macos-tahoe" || result.CanCopyFile != host.CanCopyFileToClipboard() { + t.Fatalf("unexpected export result: %+v", result) + } + if len(result.Findings) != 1 || result.Findings[0].Code != "gpu_device_lost" || + strings.Contains(result.Findings[0].Detail, dataRoot) || !strings.Contains(result.Findings[0].Detail, "Bearer [redacted]") { + t.Fatalf("unexpected findings: %+v", result.Findings) + } + for _, fragment := range []string{generatedAt.Format(time.RFC3339), version.Version, "windows amd64", + "16 logical", "12.0 GB available", "64.0 GB free", "Test GPU", "test-commit", + "4 vCPUs", "gpu_device_lost", "- summary.txt", "Bearer [redacted]"} { + if !strings.Contains(result.SummaryText, fragment) { + t.Errorf("summary is missing %q:\n%s", fragment, result.SummaryText) + } } text := all.String() for _, secret := range []string{ @@ -51,6 +107,8 @@ func TestWriteDiagnosticsZipRedactsSensitiveData(t *testing.T) { "ourhardworkbythesewordsguardedpleasedontsteal", "0123456789abcdef0123456789abcdef", "abcdef0123456789abcdef0123456789", + dataRoot, + strings.ReplaceAll(dataRoot, `\`, `\\`), } { if strings.Contains(text, secret) { t.Fatalf("diagnostics zip leaked secret %q\n%s", secret, text) @@ -60,3 +118,581 @@ func TestWriteDiagnosticsZipRedactsSensitiveData(t *testing.T) { t.Fatalf("expected [redacted] markers in zip output") } } + +func TestWriteDiagnosticsZipEmptyAndFailedExport(t *testing.T) { + reports := filepath.Join(t.TempDir(), "reports") + now := time.Now() + result, err := writeDiagnosticsZip(reports, "host", now, diagnosticsBundle{}) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(result.IncludedFiles, []string{"host-report.json", "summary.txt"}) || + result.Findings == nil || len(result.Findings) != 0 || !strings.Contains(result.SummaryText, "No known issues found") { + t.Fatalf("unexpected empty export: %+v", result) + } + if _, err := writeDiagnosticsZip(reports, "host", now, diagnosticsBundle{HostReport: host.Report{TotalRAMGB: math.NaN()}}); err == nil { + t.Fatal("expected the host report encoding to fail") + } + second, err := writeDiagnosticsZip(reports, "host", now, diagnosticsBundle{}) + if err != nil || second.Path == result.Path { + t.Fatalf("same-time export returned %q, %v after %q", second.Path, err, result.Path) + } + files, err := os.ReadDir(reports) + if err != nil || len(files) != 2 { + t.Fatalf("reports directory after two successful exports and one failure: %v, %v", files, err) + } +} + +func TestWriteDiagnosticsZipRedactsWindowsPaths(t *testing.T) { + dataRoot := filepath.Join(t.TempDir(), "PrivateData") + home, err := os.UserHomeDir() + if err != nil { + t.Fatal(err) + } + vmDir := filepath.Join(dataRoot, "PrivateVM") + disk := filepath.Join(dataRoot, "PrivateDisks", "vm.qcow2") + runtimeDir := filepath.Join(dataRoot, "PrivateRuntime") + pathVariant := func(path string) string { + if runtime.GOOS == "windows" { + return strings.ToUpper(filepath.ToSlash(path)) + } + return path + } + const driverStore = `C:\Windows\System32\DriverStore\FileRepository\private_gpu.inf\vulkan.json` + const recommendedICD = `D:\Private Drivers\preferred-vulkan.json` + const otherDisk = `E:\Private VM Backups\Disk Images\boot.qcow2` + const anotherLog = `F:/Private Launcher Logs/startup.log` + report := host.Report{ + DataRoot: dataRoot, + GPUs: []host.GPUInfo{{VulkanICD: driverStore}}, + RecommendedGPU: &host.GPUInfo{VulkanICD: recommendedICD}, + } + qemuLog := "ERROR_DEVICE_LOST " + otherDisk + result, err := writeDiagnosticsZip(filepath.Join(t.TempDir(), "reports"), "vm", time.Now(), diagnosticsBundle{ + HostReport: report, + Runtime: &rt.Installed{Dir: runtimeDir, Manifest: rt.Manifest{Name: pathVariant(runtimeDir)}}, + VMInfo: &driver.VMInfo{Name: "vm", Directory: vmDir, DiskPath: disk, DiskSummary: pathVariant(disk)}, + VMDetail: &reims.VMDetail{ExtraArgs: `-device isa-applesmc,osk="test quoted value"`}, + QEMULog: qemuLog, + SerialLog: `opening "` + anotherLog + `" for diagnostics`, + AppLogs: []string{pathVariant(dataRoot), pathVariant(home), pathVariant(vmDir)}, + PluginDiagnostics: []plugin.DiagnosticsEntry{{ + Data: map[string]any{"paths": []string{otherDisk, pathVariant(runtimeDir)}}, + }}, + }) + if err != nil { + t.Fatal(err) + } + if report.GPUs[0].VulkanICD != driverStore || report.RecommendedGPU.VulkanICD != recommendedICD { + t.Fatal("redaction modified the original host report") + } + checkRedacted := func(name, content string) { + t.Helper() + for _, secret := range []string{ + dataRoot, pathVariant(dataRoot), home, pathVariant(home), vmDir, pathVariant(vmDir), + disk, pathVariant(disk), runtimeDir, pathVariant(runtimeDir), "private_gpu.inf", + "Private Drivers", "Private VM Backups", "Disk Images", "Private Launcher Logs", "test quoted value", + } { + if strings.Contains(content, secret) || strings.Contains(content, strings.ReplaceAll(secret, `\`, `\\`)) { + t.Errorf("%s leaked %q", name, secret) + } + } + } + zr, err := zip.OpenReader(result.Path) + if err != nil { + t.Fatal(err) + } + defer zr.Close() + for _, file := range zr.File { + data, err := readDiagnosticsTestEntry(file) + if err != nil { + t.Fatal(err) + } + checkRedacted(file.Name, string(data)) + if filepath.Ext(file.Name) == ".json" { + var value json.RawMessage + if err := json.Unmarshal(data, &value); err != nil { + t.Errorf("%s contains invalid JSON: %v", file.Name, err) + } + } + if file.Name == "host-report.json" { + var entry struct { + Host host.Report `json:"host"` + } + if err := json.Unmarshal(data, &entry); err != nil || len(entry.Host.GPUs) != 1 || + entry.Host.GPUs[0].VulkanICD != "[redacted]" || entry.Host.RecommendedGPU == nil || + entry.Host.RecommendedGPU.VulkanICD != "[redacted]" { + t.Errorf("host-report.json did not redact both Vulkan ICDs: %s (%v)", data, err) + } + } + } + checkRedacted("SummaryText", result.SummaryText) + if len(result.Findings) != 1 || result.Findings[0].Detail != "ERROR_DEVICE_LOST [redacted]" { + t.Fatalf("unexpected findings: %+v", result.Findings) + } + for _, finding := range result.Findings { + checkRedacted(finding.Code, finding.Detail) + } +} + +func TestRedactDiagnosticsWindowsPathBoundaries(t *testing.T) { + redact := diagnosticsRedactor(diagnosticsBundle{}) + for _, tc := range []struct{ input, want string }{ + {`open D:\VM Backups\boot.qcow2: access is denied (0x5)`, "open [redacted]: access is denied (0x5)"}, + {`-L D:\Runtime Files -m 8G`, "-L [redacted] -m 8G"}, + {"GET https://example.test/runtime.zip failed: 404", "GET https://example.test/runtime.zip failed: 404"}, + {`GET file://example.test/runtime.zip`, `GET file://example.test/runtime.zip`}, + {`saved D:\Private\download.zip https://example.test/runtime.zip`, "saved [redacted] https://example.test/runtime.zip"}, + {`GET "http://example.test/runtime.zip" failed: 404`, `GET "http://example.test/runtime.zip" failed: 404`}, + {`open \\server\private-share\boot.qcow2: access denied`, "open [redacted]: access denied"}, + {`open //server/private-share/boot.qcow2: access denied`, "open [redacted]: access denied"}, + {`//server/private-share/boot.qcow2`, "[redacted]"}, + {`"\\server\private share\boot.qcow2"`, `"[redacted]"`}, + {`'D:\Private, Backup\boot.qcow2' next`, "'[redacted]' next"}, + {`Could not open 'D:\O'Brien\boot.qcow2': access denied`, `Could not open '[redacted]': access denied`}, + {`file=D:/vm/backups,other=[E:\Private Backup]; (F:\Runtime)`, "file=[redacted],other=[[redacted]]; ([redacted])"}, + {"D:\\first\r\nE:\\second", "[redacted]\r\n[redacted]"}, + } { + if got := redact(tc.input); got != tc.want { + t.Errorf("redact(%q) = %q, want %q", tc.input, got, tc.want) + } + } +} + +func TestRedactDiagnosticsKnownRootWithPunctuation(t *testing.T) { + root := filepath.Join(t.TempDir(), "Private, VM") + path := filepath.Join(root, "private disk.qcow2") + if runtime.GOOS == "windows" { + path = strings.ToUpper(filepath.ToSlash(path)) + } + redact := diagnosticsRedactor(diagnosticsBundle{HostReport: host.Report{DataRoot: root}}) + if got, want := redact("open "+path+": access denied"), "open [redacted]: access denied"; got != want { + t.Errorf("redacted known root = %q, want %q", got, want) + } +} + +func TestWriteDiagnosticsZipRedactsUNCPaths(t *testing.T) { + const qemu = `ERROR_DEVICE_LOST open \\server\private-share\boot.qcow2: access denied` + const serial = `VK_ERROR_INCOMPATIBLE_DRIVER opening "\\server\private share\boot.qcow2"` + const wantQEMU = "ERROR_DEVICE_LOST open [redacted]: access denied" + const wantSerial = `VK_ERROR_INCOMPATIBLE_DRIVER opening "[redacted]"` + result, err := writeDiagnosticsZip(t.TempDir(), "vm", time.Now(), diagnosticsBundle{ + QEMULog: qemu, SerialLog: serial, AppLogs: []string{qemu, serial}, + }) + if err != nil { + t.Fatal(err) + } + for _, finding := range []host.DiagnosticFinding{ + {Code: "gpu_device_lost", Severity: "error", Detail: wantQEMU}, + {Code: "gpu_vulkan_floor", Severity: "error", Detail: wantSerial}, + } { + if !slices.Contains(result.Findings, finding) || !strings.Contains(result.SummaryText, finding.Detail) { + t.Fatalf("missing %+v from findings or summary:\n%+v\n%s", finding, result.Findings, result.SummaryText) + } + } + for name, want := range map[string]string{ + "qemu.log": wantQEMU, "serial.log": wantSerial, + "app-logs.txt": wantQEMU + "\n" + wantSerial + "\n", "summary.txt": result.SummaryText, + } { + if got := readDiagnosticsArchiveEntry(t, result.Path, name); got != want { + t.Errorf("%s = %q, want %q", name, got, want) + } + } + report := readDiagnosticsArchiveEntry(t, result.Path, "host-report.json") + var hostReport struct { + Diagnosis host.DiagnosticFinding `json:"gpu_diagnosis"` + } + if err := json.Unmarshal([]byte(report), &hostReport); err != nil || hostReport.Diagnosis.Detail != wantQEMU { + t.Fatalf("host report diagnosis = %+v, err %v", hostReport.Diagnosis, err) + } + for _, secret := range []string{"server", "private-share", "private share", "boot.qcow2"} { + if strings.Contains(result.SummaryText, secret) || strings.Contains(report, secret) { + t.Errorf("summary or host report leaked %q", secret) + } + } +} + +func TestWriteDiagnosticsZipRedactsStructuredJSON(t *testing.T) { + result, err := writeDiagnosticsZip(t.TempDir(), "vm", time.Now(), diagnosticsBundle{ + PluginDiagnostics: []plugin.DiagnosticsEntry{{Data: map[string]any{ + "disks": map[string]string{ + `D:\test\disk-a`: "disk A", `D:\test\disk-b`: "disk B", `D:\test\disk-c`: "disk C", "[redacted] #2": "literal key", + }, + "hardware": []map[string]string{{ + "mac": "02:00:00:00:00:01", "MAC_Address": "another-mac", "OSK": "short", + "SMC_OSK": "test-osk", "serial": "short-serial", "Serial_Number": "another-serial", + "MLB": "test-mlb", "RoM": "test-rom", "System_UUID": "test-uuid", + "smuuid": "", "model": "test-model", + "uuid": "12345678-1234-1234-1234-123456789abc", "token": "syntheticToken0123456789", + "REIMS_TOKEN": "test-reims", "GITHUB_TOKEN": "test-github", "Access_Token": "test-access", + "refresh_token": "test-refresh", "auth_token": "test-auth", "api_key": "test-key", "apikey": "test-apikey", + "password": "test-password", "passwd": "test-passwd", "secret": "test-secret", + "authorization": "test-authorization", "cookie": "test-cookie", + }}, + }}}, + }) + if err != nil { + t.Fatal(err) + } + report := readDiagnosticsArchiveEntry(t, result.Path, "plugin-diagnostics.json") + var entries []struct { + Data struct { + Disks map[string]string + Hardware []map[string]string + } + } + if err := json.Unmarshal([]byte(report), &entries); err != nil || len(entries) != 1 || len(entries[0].Data.Hardware) != 1 { + t.Fatalf("invalid plugin diagnostics: %s (%v)", report, err) + } + wantDisks := map[string]string{ + "[redacted]": "disk A", "[redacted] #2": "disk B", "[redacted] #3": "disk C", "[redacted] #2 #2": "literal key", + } + wantHardware := map[string]string{ + "mac": "[redacted]", "MAC_Address": "[redacted]", "OSK": "[redacted]", "SMC_OSK": "[redacted]", + "serial": "[redacted]", "Serial_Number": "[redacted]", "MLB": "[redacted]", "RoM": "[redacted]", + "System_UUID": "[redacted]", "smuuid": "", "model": "test-model", + "uuid": "[redacted]", "token": "[redacted]", "REIMS_TOKEN": "[redacted]", "GITHUB_TOKEN": "[redacted]", + "Access_Token": "[redacted]", "refresh_token": "[redacted]", "auth_token": "[redacted]", + "api_key": "[redacted]", "apikey": "[redacted]", "password": "[redacted]", "passwd": "[redacted]", + "secret": "[redacted]", "authorization": "[redacted]", "cookie": "[redacted]", + } + if !maps.Equal(entries[0].Data.Disks, wantDisks) || !maps.Equal(entries[0].Data.Hardware[0], wantHardware) { + t.Fatalf("unexpected redacted data: %s", report) + } + if strings.Contains(report, `D:\\test\\disk-`) || strings.Contains(report, "02:00:00:00:00:01") { + t.Fatalf("plugin diagnostics leaked a path or hardware identifier: %s", report) + } +} + +func TestExportDiagnosticsRejectsReadOnlyDataRoot(t *testing.T) { + root := t.TempDir() + a := &App{ + cfg: &config.Config{DataRoot: root}, + root: dataroot.Status{Dir: root, ReadOnly: true, Reason: dataroot.ReasonNewer}, + } + result, err := a.ExportDiagnostics("", "") + if err == nil || !strings.Contains(err.Error(), "E_DATAROOT_NEWER") || result.Path != "" { + t.Fatalf("ExportDiagnostics returned %+v, %v", result, err) + } + if _, err := os.Stat(filepath.Join(root, "reports")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("reports directory stat: %v", err) + } +} + +func newDiagnosticsTestApp(t *testing.T, drivers ...*appSecondDriver) *App { + t.Helper() + reg := plugin.NewRegistry(nil) + for _, d := range drivers { + err := reg.Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ID: "test." + d.id, Version: "1.0.0"}, + Source: plugin.SourceBuiltin, + Desired: true, + Activate: func(_ context.Context, sc *plugin.Scope) error { + reg.RegisterGuestDriver(sc, d.id, d) + return nil + }, + }) + if err != nil { + t.Fatal(err) + } + } + reg.Reconcile(t.Context()) + return &App{ + cfg: &config.Config{DataRoot: t.TempDir()}, + lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil), + } +} + +func TestExportDiagnosticsVMChecksOnlyTargetAndHostLogs(t *testing.T) { + const dID = driver.BuiltinReimsMacOSDriverID + const otherID = "test.driver.other" + mac := &appSecondDriver{id: dID, vms: []driver.VMInfo{{Name: "vm-a"}, {Name: "vm-b"}}} + other := &appSecondDriver{id: otherID, vms: []driver.VMInfo{{Name: "vm-a"}}} + a := newDiagnosticsTestApp(t, mac, other) + a.emitVMLogForDriver(dID, "vm-b", "ERROR_DEVICE_LOST other instance") + a.emitVMLogForDriver(otherID, "vm-a", "ERROR_DEVICE_LOST other driver") + a.emitVMLogForDriver(dID, "vm-a", "VK_ERROR_INCOMPATIBLE_DRIVER target instance") + a.emitLog("host", "Hypervisor is disabled host detail") + a.emitLog("plugin:demo", "ERROR_DEVICE_LOST unscoped plugin stderr") + a.emitLog("plugin", "ERROR_DEVICE_LOST unscoped plugin error") + result, err := a.ExportDiagnostics(dID, "vm-a") + if err != nil { + t.Fatal(err) + } + if !slices.ContainsFunc(result.Findings, func(f host.DiagnosticFinding) bool { + return f.Code == "gpu_vulkan_floor" && strings.Contains(f.Detail, "target instance") + }) { + t.Fatalf("target VM's finding is missing: %+v", result.Findings) + } + for _, finding := range result.Findings { + if finding.Code == "gpu_device_lost" || strings.Contains(finding.Detail, "other instance") || + strings.Contains(finding.Detail, "other driver") { + t.Errorf("another VM contributed a finding: %+v", finding) + } + } + for _, text := range []string{"ERROR_DEVICE_LOST", "gpu_device_lost", "other instance", "other driver", "unscoped plugin stderr", "unscoped plugin error"} { + if strings.Contains(result.SummaryText, text) { + t.Errorf("summary contains another VM's error: %s", result.SummaryText) + } + } + content := readDiagnosticsArchiveEntry(t, result.Path, "app-logs.txt") + for _, line := range []string{"[plugin:demo] ERROR_DEVICE_LOST unscoped plugin stderr", "[plugin] ERROR_DEVICE_LOST unscoped plugin error"} { + if !strings.Contains(content, line) { + t.Errorf("app-logs.txt is missing %q:\n%s", line, content) + } + } + a.emitLog("host", "ERROR_DEVICE_LOST shared host detail") + result, err = a.ExportDiagnostics(dID, "vm-a") + if err != nil { + t.Fatal(err) + } + if !slices.ContainsFunc(result.Findings, func(f host.DiagnosticFinding) bool { + return f.Code == "gpu_device_lost" && strings.Contains(f.Detail, "shared host detail") + }) { + t.Fatalf("host finding is missing: %+v", result.Findings) + } +} + +func TestExportDiagnosticsReadsEarlierBuiltInVMLogs(t *testing.T) { + vm := driver.VMInfo{Name: "vm", DriverID: driver.BuiltinReimsMacOSDriverID, Directory: t.TempDir()} + a := newDiagnosticsTestApp(t, &appSecondDriver{id: vm.DriverID, vms: []driver.VMInfo{vm}}) + logDir := filepath.Join(vm.Directory, "logs") + if err := os.Mkdir(logDir, 0o755); err != nil { + t.Fatal(err) + } + // Both errors precede the preview window. QEMU's error also precedes the last 2 MiB. + tail := strings.Repeat(strings.Repeat("a", 2047)+"\n", 48) + logs := map[string]string{ + "qemu.log": "ERROR_DEVICE_LOST earlier QEMU error\n" + strings.Repeat(tail, 24), + "serial.log": "VK_ERROR_INCOMPATIBLE_DRIVER earlier serial error\n" + tail, + } + for name, content := range logs { + if err := os.WriteFile(filepath.Join(logDir, name), []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } + result, err := a.ExportDiagnostics(vm.DriverID, vm.Name) + if err != nil { + t.Fatal(err) + } + for _, detail := range []string{"earlier QEMU error", "earlier serial error"} { + if !strings.Contains(result.SummaryText, detail) || !slices.ContainsFunc(result.Findings, func(f host.DiagnosticFinding) bool { + return strings.Contains(f.Detail, detail) + }) { + t.Errorf("earlier error %q is missing from findings or summary", detail) + } + } + if strings.Contains(result.SummaryText, "truncated:") { + t.Fatalf("summary reports truncation for complete logs:\n%s", result.SummaryText) + } + zr, err := zip.OpenReader(result.Path) + if err != nil { + t.Fatal(err) + } + defer zr.Close() + for _, file := range zr.File { + want, ok := logs[file.Name] + if !ok { + continue + } + content, err := readDiagnosticsTestEntry(file) + if err != nil || string(content) != want { + t.Fatalf("%s did not retain the full log: got %d bytes, want %d, err %v", file.Name, len(content), len(want), err) + } + delete(logs, file.Name) + } + if len(logs) != 0 { + t.Fatal("expected both VM logs in the archive") + } +} + +func TestExportDiagnosticsTruncatesOversizedBuiltInVMLog(t *testing.T) { + vm := driver.VMInfo{Name: "vm", DriverID: driver.BuiltinReimsMacOSDriverID, Directory: t.TempDir()} + a := newDiagnosticsTestApp(t, &appSecondDriver{id: vm.DriverID, vms: []driver.VMInfo{vm}}) + logDir := filepath.Join(vm.Directory, "logs") + if err := os.Mkdir(logDir, 0o755); err != nil { + t.Fatal(err) + } + const start = "ERROR_DEVICE_LOST first startup error\n" + const end = "VK_ERROR_INCOMPATIBLE_DRIVER last crash error\n" + head := start + strings.Repeat("a", (1<<20)-len(start)-1) + "\n" + tail := strings.Repeat("c", (4<<20)-len(end)-1) + "\n" + end + full := head + "middle omitted\n" + strings.Repeat("b", 11<<20) + "\n" + tail + if err := os.WriteFile(filepath.Join(logDir, "qemu.log"), []byte(full), 0o600); err != nil { + t.Fatal(err) + } + result, err := a.ExportDiagnostics(vm.DriverID, vm.Name) + if err != nil { + t.Fatal(err) + } + got := readDiagnosticsArchiveEntry(t, result.Path, "qemu.log") + want := head + "\n[log truncated: middle omitted]\n" + tail + if got != want { + t.Fatalf("truncated log differs from the expected head, marker and tail (%d vs %d bytes)", len(got), len(want)) + } + for _, finding := range []host.DiagnosticFinding{ + {Code: "gpu_device_lost", Severity: "error", Detail: strings.TrimSpace(start)}, + {Code: "gpu_vulkan_floor", Severity: "error", Detail: strings.TrimSpace(end)}, + } { + if !slices.Contains(result.Findings, finding) { + t.Errorf("missing %+v from findings: %+v", finding, result.Findings) + } + } + const note = "qemu.log truncated: first 1 MiB and last 4 MiB retained" + if !strings.Contains(result.SummaryText, note) || readDiagnosticsArchiveEntry(t, result.Path, "summary.txt") != result.SummaryText { + t.Fatalf("summary is missing the truncation note or differs from summary.txt:\n%s", result.SummaryText) + } +} + +func TestExportDiagnosticsDropsPartialLinesAtLogCutoffs(t *testing.T) { + vm := driver.VMInfo{Name: "vm", DriverID: driver.BuiltinReimsMacOSDriverID, Directory: t.TempDir()} + a := newDiagnosticsTestApp(t, &appSecondDriver{id: vm.DriverID, vms: []driver.VMInfo{vm}}) + logDir := filepath.Join(vm.Directory, "logs") + if err := os.Mkdir(logDir, 0o755); err != nil { + t.Fatal(err) + } + const start = "first complete line\n" + const end = "last complete line\n" + const partialTail = "Private Folder\\boot.qcow2: access denied\n" + head := start + "partial head line " + strings.Repeat("a", 1<<20) + "\n" + tail := partialTail + strings.Repeat("c", (4<<20)-len(partialTail)-len(end)-1) + "\n" + end + full := head + strings.Repeat("b", 12<<20) + "\nopen D:\\" + tail + if err := os.WriteFile(filepath.Join(logDir, "qemu.log"), []byte(full), 0o600); err != nil { + t.Fatal(err) + } + result, err := a.ExportDiagnostics(vm.DriverID, vm.Name) + if err != nil { + t.Fatal(err) + } + got := readDiagnosticsArchiveEntry(t, result.Path, "qemu.log") + for _, fragment := range []string{"partial head line", "Private Folder", "boot.qcow2"} { + if strings.Contains(got, fragment) { + t.Errorf("truncated log retained incomplete line fragment %q", fragment) + } + } + if !strings.HasPrefix(got, start+"\n[log truncated: middle omitted]\n") || !strings.HasSuffix(got, end) { + t.Fatal("truncated log lost a complete line or the truncation marker") + } +} + +func readDiagnosticsArchiveEntry(t *testing.T, path, name string) string { + t.Helper() + zr, err := zip.OpenReader(path) + if err != nil { + t.Fatal(err) + } + defer zr.Close() + data, err := fs.ReadFile(zr, name) + if err != nil { + t.Fatalf("read %s: %v", name, err) + } + return string(data) +} + +func readDiagnosticsTestEntry(file *zip.File) ([]byte, error) { + rc, err := file.Open() + if err != nil { + return nil, err + } + defer rc.Close() + return io.ReadAll(rc) +} + +func TestResolveDiagnosticsZipPath(t *testing.T) { + root := t.TempDir() + reports := filepath.Join(root, "reports") + dir := filepath.Join(reports, "dir.zip") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + outside := filepath.Join(root, "reports-backup") + if err := os.Mkdir(outside, 0o755); err != nil { + t.Fatal(err) + } + valid := filepath.Join(reports, "export.ZIP") + wrongExt := filepath.Join(reports, "export.txt") + escaped := filepath.Join(outside, "export.zip") + nested := filepath.Join(dir, "nested.zip") + for _, path := range []string{valid, wrongExt, escaped, nested} { + if err := os.WriteFile(path, nil, 0o600); err != nil { + t.Fatal(err) + } + } + link := filepath.Join(reports, "link") + if runtime.GOOS == "windows" { + if out, err := exec.Command("cmd.exe", "/c", "mklink", "/J", link, outside).CombinedOutput(); err != nil { + t.Fatalf("make junction: %v\n%s", err, out) + } + } else if err := os.Symlink(outside, link); err != nil { + t.Fatal(err) + } + want, err := filepath.EvalSymlinks(valid) + if err != nil { + t.Fatal(err) + } + if got, err := resolveDiagnosticsZipPath(root, valid); err != nil || got != want { + t.Fatalf("resolveDiagnosticsZipPath(%q) = %q, %v, want %q", valid, got, err, want) + } + for name, path := range map[string]string{ + "empty": "", "directory": dir, "missing": filepath.Join(reports, "missing.zip"), + "outside": escaped, "wrong extension": wrongExt, "link escape": filepath.Join(link, "export.zip"), + "nested file": nested, + "traversal": reports + string(os.PathSeparator) + "../reports-backup/export.zip", + } { + t.Run(name, func(t *testing.T) { + if got, err := resolveDiagnosticsZipPath(root, path); err == nil { + t.Errorf("accepted %q as %q", path, got) + } + }) + } +} + +func TestResolveDiagnosticsZipPathRejectsCaseSensitiveSibling(t *testing.T) { + root := t.TempDir() + var caseOutput []byte + if runtime.GOOS == "windows" { + output, err := exec.Command("fsutil.exe", "file", "setCaseSensitiveInfo", root, "enable").CombinedOutput() + if err != nil { + t.Skipf("cannot enable case sensitivity on the temporary directory: %v (%s)", err, output) + } + caseOutput = output + } + reports := filepath.Join(root, "reports") + sibling := filepath.Join(root, "REPORTS") + for _, dir := range []string{reports, sibling} { + if err := os.Mkdir(dir, 0o755); err != nil { + if dir == sibling && errors.Is(err, os.ErrExist) { + t.Skipf("temporary directory is case-insensitive: %v (%s)", err, strings.TrimSpace(string(caseOutput))) + } + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "export.zip"), nil, 0o600); err != nil { + t.Fatal(err) + } + } + if _, err := resolveDiagnosticsZipPath(root, filepath.Join(reports, "export.zip")); err != nil { + t.Fatalf("authorized reports directory rejected: %v", err) + } + if path, err := resolveDiagnosticsZipPath(root, filepath.Join(sibling, "export.zip")); err == nil { + t.Fatalf("accepted export from case-sensitive sibling: %s", path) + } +} + +func TestResolveDiagnosticsZipPathRejectsDirectSymlinkEscape(t *testing.T) { + root := t.TempDir() + reports := filepath.Join(root, "reports") + if err := os.Mkdir(reports, 0o755); err != nil { + t.Fatal(err) + } + outside := filepath.Join(root, "outside.zip") + if err := os.WriteFile(outside, nil, 0o600); err != nil { + t.Fatal(err) + } + link := filepath.Join(reports, "link.zip") + if err := os.Symlink(outside, link); err != nil { + t.Skipf("cannot create a symbolic link: %v", err) + } + if path, err := resolveDiagnosticsZipPath(root, link); err == nil { + t.Fatalf("accepted symlink to outside of reports: %s", path) + } +} diff --git a/internal/host/clipboard_file_other.go b/internal/host/clipboard_file_other.go new file mode 100644 index 0000000..2ada305 --- /dev/null +++ b/internal/host/clipboard_file_other.go @@ -0,0 +1,11 @@ +//go:build !windows + +package host + +import "errors" + +func CanCopyFileToClipboard() bool { return false } + +func CopyFileToClipboard(_ string) error { + return errors.New("copying files to the clipboard is unavailable on this platform") +} diff --git a/internal/host/clipboard_file_test.go b/internal/host/clipboard_file_test.go new file mode 100644 index 0000000..8ff5f9a --- /dev/null +++ b/internal/host/clipboard_file_test.go @@ -0,0 +1,24 @@ +//go:build windows + +package host + +import ( + "bytes" + "testing" +) + +func TestDropFilesPayload(t *testing.T) { + got := buildDropFilesPayload([]string{`C:\a.zip`, `D:\😀.zip`}) + want := []byte{ + 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, + 'C', 0, ':', 0, '\\', 0, 'a', 0, '.', 0, 'z', 0, 'i', 0, 'p', 0, 0, 0, + 'D', 0, ':', 0, '\\', 0, 0x3d, 0xd8, 0x00, 0xde, '.', 0, 'z', 0, 'i', 0, 'p', 0, 0, 0, + 0, 0, + } + if !bytes.Equal(got, want) { + t.Fatalf("DROPFILES payload = % x, want % x", got, want) + } + if empty := buildDropFilesPayload(nil); !bytes.Equal(empty[:20], want[:20]) || !bytes.Equal(empty[20:], []byte{0, 0, 0, 0}) { + t.Fatalf("empty DROPFILES payload = % x", empty) + } +} diff --git a/internal/host/clipboard_file_windows.go b/internal/host/clipboard_file_windows.go new file mode 100644 index 0000000..aa589c0 --- /dev/null +++ b/internal/host/clipboard_file_windows.go @@ -0,0 +1,136 @@ +//go:build windows + +package host + +import ( + "encoding/binary" + "errors" + "fmt" + "runtime" + "syscall" + "time" + "unicode/utf16" + "unsafe" + + "golang.org/x/sys/windows" +) + +var ( + fileClipboardUser32 = windows.NewLazySystemDLL("user32.dll") + fileClipboardKernel32 = windows.NewLazySystemDLL("kernel32.dll") + procFileCreateWindow = fileClipboardUser32.NewProc("CreateWindowExW") + procFileDestroyWindow = fileClipboardUser32.NewProc("DestroyWindow") + procFileOpenClipboard = fileClipboardUser32.NewProc("OpenClipboard") + procFileCloseClipboard = fileClipboardUser32.NewProc("CloseClipboard") + procFileEmptyClipboard = fileClipboardUser32.NewProc("EmptyClipboard") + procFileSetClipboardData = fileClipboardUser32.NewProc("SetClipboardData") + procFileGlobalAlloc = fileClipboardKernel32.NewProc("GlobalAlloc") + procFileGlobalFree = fileClipboardKernel32.NewProc("GlobalFree") + procFileGlobalLock = fileClipboardKernel32.NewProc("GlobalLock") + procFileGlobalUnlock = fileClipboardKernel32.NewProc("GlobalUnlock") + procFileMoveMemory = fileClipboardKernel32.NewProc("RtlMoveMemory") +) + +const ( + cfHDrop = 15 + gmemMoveable = 0x0002 + gmemZeroInit = 0x0040 + hwndMessage = ^uintptr(2) + dropFilesHeadLen = 20 +) + +func CanCopyFileToClipboard() bool { return true } + +// CopyFileToClipboard publishes an absolute file path in Windows file-drop format. +func CopyFileToClipboard(path string) (err error) { + absPath, err := absoluteFilePath(path) + if err != nil { + return err + } + payload := buildDropFilesPayload([]string{absPath}) + + runtime.LockOSThread() + defer runtime.UnlockOSThread() + // EmptyClipboard needs a window owner for SetClipboardData to succeed. + class := [...]uint16{'S', 'T', 'A', 'T', 'I', 'C', 0} + hwnd, _, callErr := procFileCreateWindow.Call(0, uintptr(unsafe.Pointer(&class[0])), 0, 0, + 0, 0, 0, 0, hwndMessage, 0, 0, 0) + if hwnd == 0 { + return fmt.Errorf("CreateWindowExW: %w", callErr) + } + defer func() { + if ok, _, destroyErr := procFileDestroyWindow.Call(hwnd); ok == 0 { + err = errors.Join(err, fmt.Errorf("DestroyWindow: %w", destroyErr)) + } + }() + if err := openFileClipboard(hwnd); err != nil { + return err + } + defer func() { + if ok, _, closeErr := procFileCloseClipboard.Call(); ok == 0 { + err = errors.Join(err, fmt.Errorf("CloseClipboard: %w", closeErr)) + } + }() + if ok, _, emptyErr := procFileEmptyClipboard.Call(); ok == 0 { + return fmt.Errorf("EmptyClipboard: %w", emptyErr) + } + return setDropFilesData(payload) +} + +func openFileClipboard(hwnd uintptr) error { + for attempt := 1; ; attempt++ { + ok, _, err := procFileOpenClipboard.Call(hwnd) + if ok != 0 { + return nil + } + if attempt == 5 { + return fmt.Errorf("OpenClipboard: %w", err) + } + time.Sleep(20 * time.Millisecond) + } +} + +func setDropFilesData(payload []byte) (err error) { + size := uintptr(len(payload)) + mem, _, callErr := procFileGlobalAlloc.Call(gmemMoveable|gmemZeroInit, size) + if mem == 0 { + return fmt.Errorf("GlobalAlloc: %w", callErr) + } + defer func() { + if mem != 0 { + if remaining, _, freeErr := procFileGlobalFree.Call(mem); remaining != 0 { + err = errors.Join(err, fmt.Errorf("GlobalFree: %w", freeErr)) + } + } + }() + ptr, _, callErr := procFileGlobalLock.Call(mem) + if ptr == 0 { + return fmt.Errorf("GlobalLock: %w", callErr) + } + procFileMoveMemory.Call(ptr, uintptr(unsafe.Pointer(&payload[0])), size) + // A zero result with no last error means the final lock was released. + if ok, _, unlockErr := procFileGlobalUnlock.Call(mem); ok == 0 && unlockErr != syscall.Errno(0) { + return fmt.Errorf("GlobalUnlock: %w", unlockErr) + } + if ok, _, setErr := procFileSetClipboardData.Call(cfHDrop, mem); ok == 0 { + return fmt.Errorf("SetClipboardData(CF_HDROP): %w", setErr) + } + mem = 0 // The system owns the handle after a successful transfer. + return nil +} + +func buildDropFilesPayload(paths []string) []byte { + payload := make([]byte, dropFilesHeadLen) + binary.LittleEndian.PutUint32(payload, dropFilesHeadLen) + binary.LittleEndian.PutUint32(payload[16:], 1) + for _, path := range paths { + for _, word := range utf16.Encode([]rune(path)) { + payload = binary.LittleEndian.AppendUint16(payload, word) + } + payload = append(payload, 0, 0) + } + if len(paths) == 0 { + payload = append(payload, 0, 0) + } + return append(payload, 0, 0) +} diff --git a/internal/host/log_diagnose.go b/internal/host/log_diagnose.go index 31442d5..1694ce3 100644 --- a/internal/host/log_diagnose.go +++ b/internal/host/log_diagnose.go @@ -2,29 +2,67 @@ package host import "strings" +type DiagnosticFinding struct { + Code string `json:"code"` + Severity string `json:"severity"` + Detail string `json:"detail,omitempty"` +} + // DiagnoseGPULog recognizes known Vulkan compatibility and device-loss failures. func DiagnoseGPULog(output string) (code, detail string) { - if output == "" { - return "", "" + lost, floor := gpuLogFindings([]string{output}) + if lost != "" { + return "gpu_device_lost", lost } - for _, raw := range strings.Split(output, "\n") { - line := strings.TrimSpace(raw) - if line == "" { - continue - } - if strings.Contains(line, "ERROR_DEVICE_LOST") || strings.Contains(line, "was lost at vkQueueSubmit2") || strings.Contains(line, "rt-device-lost-in-flight") { - return "gpu_device_lost", line - } - } - for _, raw := range strings.Split(output, "\n") { - line := strings.TrimSpace(raw) - if line == "" { - continue - } - low := strings.ToLower(line) - if strings.Contains(line, "VK_ERROR_INCOMPATIBLE_DRIVER") || strings.Contains(low, "no vulkan gpu found") || strings.Contains(low, "meets the floor") || strings.Contains(low, "below the floor") || strings.Contains(low, "no physical device") { - return "gpu_vulkan_floor", line - } + if floor != "" { + return "gpu_vulkan_floor", floor } return "", "" } + +func gpuLogFindings(logs []string) (lost, floor string) { + for _, log := range logs { + for raw := range strings.SplitSeq(log, "\n") { + line := strings.TrimSpace(raw) + if line == "" || strings.Contains(line, "metal2vulkan-runtime made it with a precision note (metal2vulkan-degrade-") { + continue + } + if strings.Contains(line, "ERROR_DEVICE_LOST") || strings.Contains(line, "was lost at vkQueueSubmit2") || strings.Contains(line, "rt-device-lost-in-flight") { + if lost == "" { + lost = line + } + continue + } + if floor == "" { + low := strings.ToLower(line) + if strings.Contains(line, "VK_ERROR_INCOMPATIBLE_DRIVER") || strings.Contains(low, "no vulkan gpu found") || strings.Contains(low, "meets the floor") || strings.Contains(low, "below the floor") || strings.Contains(low, "no physical device") { + floor = line + } + } + } + } + return lost, floor +} + +// AnalyzeDiagnostics reports known failures and resource thresholds in a fixed order. +func AnalyzeDiagnostics(rep Report, qemuLog, serialLog string, appLogs []string) []DiagnosticFinding { + findings := []DiagnosticFinding{} + lost, floor := gpuLogFindings(append([]string{qemuLog, serialLog}, appLogs...)) + if lost != "" { + findings = append(findings, DiagnosticFinding{Code: "gpu_device_lost", Severity: "error", Detail: RedactText(lost)}) + } + if floor != "" { + findings = append(findings, DiagnosticFinding{Code: "gpu_vulkan_floor", Severity: "error", Detail: RedactText(floor)}) + } + switch rep.WHPX { + case WHPXHypervisorOff, WHPXNoHypervisor, WHPXMissing, WHPXUnsupported: + findings = append(findings, DiagnosticFinding{Code: "whpx_unavailable", Severity: "error", Detail: string(rep.WHPX)}) + } + if rep.TotalRAMGB > 0 && rep.AvailRAMGB > 0 && rep.AvailRAMGB < 6 { + findings = append(findings, DiagnosticFinding{Code: "low_memory", Severity: "warn"}) + } + if rep.FreeDiskGB > 0 && rep.FreeDiskGB < 30 { + findings = append(findings, DiagnosticFinding{Code: "low_disk", Severity: "warn"}) + } + return findings +} diff --git a/internal/host/log_diagnose_test.go b/internal/host/log_diagnose_test.go index d301e7b..0a21acf 100644 --- a/internal/host/log_diagnose_test.go +++ b/internal/host/log_diagnose_test.go @@ -1,6 +1,9 @@ package host -import "testing" +import ( + "reflect" + "testing" +) func TestDiagnoseGPULog(t *testing.T) { lost := "reims-vgpu: the rt platform's device on AMD Radeon (TM) Graphics (1002:15e7) was lost at vkQueueSubmit2 (ERROR_DEVICE_LOST)" @@ -15,3 +18,44 @@ func TestDiagnoseGPULog(t *testing.T) { t.Fatalf("expected empty code for normal log, got %q", code) } } + +func TestAnalyzeDiagnosticsFindings(t *testing.T) { + rep := Report{WHPX: WHPXMissing, TotalRAMGB: 16, AvailRAMGB: 5.9, FreeDiskGB: 29.9} + got := AnalyzeDiagnostics(rep, + "no physical device meets the floor\nERROR_DEVICE_LOST token=0123456789abcdef", + "rt-device-lost-in-flight", + []string{"VK_ERROR_INCOMPATIBLE_DRIVER"}) + want := []DiagnosticFinding{ + {Code: "gpu_device_lost", Severity: "error", Detail: "ERROR_DEVICE_LOST token=[redacted]"}, + {Code: "gpu_vulkan_floor", Severity: "error", Detail: "no physical device meets the floor"}, + {Code: "whpx_unavailable", Severity: "error", Detail: "missing"}, + {Code: "low_memory", Severity: "warn"}, + {Code: "low_disk", Severity: "warn"}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("findings = %+v, want %+v", got, want) + } + if code, _ := DiagnoseGPULog("no physical device\nERROR_DEVICE_LOST"); code != "gpu_device_lost" { + t.Fatalf("DiagnoseGPULog returned %q when both failures occurred", code) + } +} + +func TestAnalyzeDiagnosticsEmptyAndThresholds(t *testing.T) { + precision := "[QEMU] reims-vgpu: 1002:15e7: metal2vulkan-runtime made it with a precision note (metal2vulkan-degrade-sample): no physical device below the floor" + for _, rep := range []Report{ + {}, + {WHPX: WHPXReady, TotalRAMGB: 16, AvailRAMGB: 6, FreeDiskGB: 30}, + {TotalRAMGB: 16}, + {AvailRAMGB: 1}, + } { + if got := AnalyzeDiagnostics(rep, precision, precision, []string{precision}); got == nil || len(got) != 0 { + t.Errorf("expected a non-nil empty list, got %+v", got) + } + } + if code, _ := DiagnoseGPULog(precision); code != "" { + t.Fatalf("precision note diagnosed as %q", code) + } + if got := AnalyzeDiagnostics(Report{}, "", "rt-device-lost-in-flight", []string{"VK_ERROR_INCOMPATIBLE_DRIVER"}); len(got) != 2 { + t.Fatalf("expected failures from serial and app logs, got %+v", got) + } +} diff --git a/internal/host/open_shared_other.go b/internal/host/open_shared_other.go new file mode 100644 index 0000000..fc87442 --- /dev/null +++ b/internal/host/open_shared_other.go @@ -0,0 +1,10 @@ +//go:build !windows + +package host + +import "os" + +// OpenFileSharedRead opens a file for reading. +func OpenFileSharedRead(path string) (*os.File, error) { + return os.Open(path) +} diff --git a/internal/host/open_shared_test.go b/internal/host/open_shared_test.go new file mode 100644 index 0000000..6fe6cb3 --- /dev/null +++ b/internal/host/open_shared_test.go @@ -0,0 +1,83 @@ +//go:build windows + +package host + +import ( + "io" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestOpenFileSharedRead(t *testing.T) { + dir := t.TempDir() + src := filepath.Join(dir, "qemu.log") + dst := filepath.Join(dir, "qemu.previous.log") + const original = "previous VM startup\n" + if err := os.WriteFile(src, []byte(original), 0o600); err != nil { + t.Fatal(err) + } + f, err := OpenFileSharedRead(src) + if err != nil { + t.Fatal(err) + } + defer f.Close() + if err := os.Rename(src, dst); err != nil { + t.Fatalf("rotate log while open: %v", err) + } + if err := os.WriteFile(src, []byte("next VM startup\n"), 0o600); err != nil { + t.Fatal(err) + } + content, err := io.ReadAll(f) + if err != nil || string(content) != original { + t.Fatalf("open handle after rotation = %q, %v, want %q", content, err, original) + } +} + +func TestOpenFileSharedReadLongPath(t *testing.T) { + dir := t.TempDir() + for len(dir) <= 260 { + dir = filepath.Join(dir, strings.Repeat("logs", 16)) + } + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, "qemu.log") + const want = "long-path VM startup\n" + if err := os.WriteFile(path, []byte(want), 0o600); err != nil { + t.Fatal(err) + } + f, err := OpenFileSharedRead(path) + if err != nil { + t.Fatalf("open %d-character path: %v", len(path), err) + } + defer f.Close() + got, err := io.ReadAll(f) + if err != nil || string(got) != want { + t.Fatalf("read %d-character path = %q, %v, want %q", len(path), got, err, want) + } + t.Logf("read log through a %d-character path", len(path)) +} + +func TestExtendedLengthPath(t *testing.T) { + component := strings.Repeat("a", 244) + drive := `D:\` + component + `\qemu.log` + unc := `\\server\share\` + component + `\qemu.log` + for _, tc := range []struct{ name, path, want string }{ + {"short", `D:\VM\qemu.log`, `D:\VM\qemu.log`}, + {"below threshold", `D:\` + component, `D:\` + component}, + {"at threshold", `D:\` + component + "a", `\\?\D:\` + component + "a"}, + {"drive", drive, `\\?\` + drive}, + {"UNC", unc, `\\?\UNC\` + unc[2:]}, + {"forward slashes", `//server/share/` + component + `/old/../qemu.log`, `\\?\UNC\` + unc[2:]}, + {"already extended", `\\?\` + drive, `\\?\` + drive}, + {"already extended UNC", `\\?\UNC\` + unc[2:], `\\?\UNC\` + unc[2:]}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := toExtendedLengthPath(tc.path); got != tc.want { + t.Errorf("toExtendedLengthPath(%q) = %q, want %q", tc.path, got, tc.want) + } + }) + } +} diff --git a/internal/host/open_shared_windows.go b/internal/host/open_shared_windows.go new file mode 100644 index 0000000..cbddcd0 --- /dev/null +++ b/internal/host/open_shared_windows.go @@ -0,0 +1,39 @@ +package host + +import ( + "os" + "path/filepath" + "strings" + "syscall" +) + +// OpenFileSharedRead opens a file for reading without blocking Windows log rotation. +func OpenFileSharedRead(path string) (*os.File, error) { + extendedPath := toExtendedLengthPath(path) + name, err := syscall.UTF16PtrFromString(extendedPath) + if err != nil { + return nil, &os.PathError{Op: "open", Path: path, Err: err} + } + handle, err := syscall.CreateFile(name, syscall.GENERIC_READ, + syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, + nil, syscall.OPEN_EXISTING, syscall.FILE_ATTRIBUTE_NORMAL, 0) + if err != nil { + return nil, &os.PathError{Op: "open", Path: path, Err: err} + } + return os.NewFile(uintptr(handle), path), nil +} + +func toExtendedLengthPath(path string) string { + if len(path) < 248 || !filepath.IsAbs(path) { + return path + } + normalized := strings.ReplaceAll(path, "/", `\`) + if strings.HasPrefix(normalized, `\\?\`) || strings.HasPrefix(normalized, `\??\`) || strings.HasPrefix(normalized, `\\.\`) { + return path + } + normalized = filepath.Clean(normalized) + if strings.HasPrefix(normalized, `\\`) { + return `\\?\UNC\` + normalized[2:] + } + return `\\?\` + normalized +} diff --git a/internal/host/open_test.go b/internal/host/open_test.go new file mode 100644 index 0000000..8c297f5 --- /dev/null +++ b/internal/host/open_test.go @@ -0,0 +1,18 @@ +package host + +import ( + "errors" + "os" + "path/filepath" + "testing" +) + +func TestRevealRejectsMissingFileAndDirectory(t *testing.T) { + dir := t.TempDir() + if err := RevealFile(filepath.Join(dir, "missing.zip")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("RevealFile(missing) = %v, want file not found", err) + } + if err := RevealFile(dir); err == nil { + t.Fatal("RevealFile accepted a directory") + } +} diff --git a/internal/host/open_windows.go b/internal/host/open_windows.go index 63e1d04..07270e7 100644 --- a/internal/host/open_windows.go +++ b/internal/host/open_windows.go @@ -6,6 +6,8 @@ import ( "fmt" "os" "os/exec" + "path/filepath" + "syscall" ) // OpenFolder shows dir in File Explorer. explorer.exe exits non-zero even on @@ -20,3 +22,36 @@ func OpenFolder(dir string) error { } return exec.Command("explorer.exe", dir).Start() } + +// RevealFile selects a file in File Explorer. +func RevealFile(path string) error { + absPath, err := absoluteFilePath(path) + if err != nil { + return err + } + cmd := exec.Command("explorer.exe") + cmd.SysProcAttr = &syscall.SysProcAttr{CmdLine: explorerSelectCommandLine(absPath)} + if err := cmd.Start(); err != nil { + return err + } + return cmd.Process.Release() +} + +func explorerSelectCommandLine(absPath string) string { + return `explorer.exe /select,"` + absPath + `"` +} + +func absoluteFilePath(path string) (string, error) { + absPath, err := filepath.Abs(path) + if err != nil { + return "", err + } + info, err := os.Stat(absPath) + if err != nil { + return "", err + } + if info.IsDir() { + return "", fmt.Errorf("not a file: %s", absPath) + } + return absPath, nil +} diff --git a/internal/host/open_windows_test.go b/internal/host/open_windows_test.go new file mode 100644 index 0000000..811d8bb --- /dev/null +++ b/internal/host/open_windows_test.go @@ -0,0 +1,13 @@ +//go:build windows + +package host + +import "testing" + +func TestRevealExplorerCommandLine(t *testing.T) { + const path = `C:\Reims data\reports\diag, 你好.zip` + const want = `explorer.exe /select,"C:\Reims data\reports\diag, 你好.zip"` + if got := explorerSelectCommandLine(path); got != want { + t.Fatalf("Explorer command line = %q, want %q", got, want) + } +} diff --git a/internal/host/stubs_system_other.go b/internal/host/stubs_system_other.go index c5ba459..bb57e02 100644 --- a/internal/host/stubs_system_other.go +++ b/internal/host/stubs_system_other.go @@ -8,6 +8,7 @@ import ( "fmt" "os" "os/exec" + "path/filepath" "runtime" "strings" "time" @@ -53,7 +54,28 @@ func OpenFolder(dir string) error { if runtime.GOOS == "darwin" { opener = "open" } - return exec.Command(opener, dir).Start() + cmd := exec.Command(opener, dir) + if err := cmd.Start(); err != nil { + return err + } + go func() { _ = cmd.Wait() }() + return nil +} + +// RevealFile opens the directory containing the file. +func RevealFile(path string) error { + absPath, err := filepath.Abs(path) + if err != nil { + return err + } + info, err := os.Stat(absPath) + if err != nil { + return err + } + if info.IsDir() { + return fmt.Errorf("not a file: %s", absPath) + } + return OpenFolder(filepath.Dir(absPath)) } // ErrOtherProcess: the PID now names a process other than the one expected. diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index b1d3498..ee15987 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -134,6 +134,27 @@ var catalog = map[Locale]map[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": "显示器数量", "doctor.apple_virtualization.ready": "可用", "doctor.apple_virtualization.unavailable": "不可用", @@ -283,6 +304,7 @@ var catalog = map[Locale]map[string]string{ "errorBoundaryReload": "重新加载界面", "errorBoundaryTitle": "界面遇到意外错误", "expandLogs": "展开日志", + "failCopyDiagnosticsFile": "复制排障包失败", "failCreate": "{name} 创建失败", "failDownload": "下载失败", "failGeneric": "操作失败", @@ -437,7 +459,11 @@ var catalog = map[Locale]map[string]string{ "logActivity": "活动", "logButton": "日志", "logCopy": "复制日志", + "logCopyAnyway": "仍然复制", "logErrorsOnly": "仅错误/警告", + "logExportDiagnostics": "导出排障包", + "logLargeCopyDesc": "即将复制 {n} 行日志,直接粘贴容易刷屏且缺少环境信息,建议导出排障包", + "logLargeCopyTitle": "大段日志", "logQemu": "QEMU", "logSearchPlaceholder": "筛选日志…", "logSerial": "串口", @@ -674,6 +700,7 @@ var catalog = map[Locale]map[string]string{ "toastCreateCanceled": "已取消创建 {name}", "toastCreateCanceledPartial": "已下载部分已保留,可继续下载或返回修改", "toastCreated": "{name} 已创建", + "toastDiagFileCopied": "已复制排障包文件,可直接粘贴发送", "toastDownloadPaused": "已暂停,再次下载会从中断处继续", "toastInstallerReady": "macOS {v} 安装包已就绪", "toastQueueCanceled": "已取消排队", @@ -923,6 +950,27 @@ var catalog = map[Locale]map[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", "doctor.apple_virtualization.ready": "Ready", "doctor.apple_virtualization.unavailable": "Unavailable", @@ -1072,6 +1120,7 @@ var catalog = map[Locale]map[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", @@ -1226,7 +1275,11 @@ var catalog = map[Locale]map[string]string{ "logActivity": "Activity", "logButton": "Logs", "logCopy": "Copy logs", + "logCopyAnyway": "Copy anyway", "logErrorsOnly": "Errors & 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", @@ -1463,6 +1516,7 @@ var catalog = map[Locale]map[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", @@ -1706,6 +1760,7 @@ var paramOrder = map[string][]string{ "installer.done": {"ver", "path"}, "installer.paused": {"ver"}, "localeAutoDetail": {"tag"}, + "logLargeCopyDesc": {"n"}, "monitor.heartbeat.cpu": {"dur", "disk", "delta", "cpu"}, "monitor.heartbeat.nocpu": {"dur", "disk", "delta"}, "monitor.qemu.gpu": {"device"}, diff --git a/locales/en-US/core.json b/locales/en-US/core.json index 5fa1047..f1ee1de 100644 --- a/locales/en-US/core.json +++ b/locales/en-US/core.json @@ -99,6 +99,33 @@ "logSearchPlaceholder": "Filter logs…", "logErrorsOnly": "Errors & warnings", "logCopy": "Copy logs", + "logExportDiagnostics": "Export diagnostics", + "logLargeCopyTitle": "Long log output", + "logLargeCopyDesc": "Pasting {n} lines of logs can flood chat and omits system details; export diagnostics instead", + "logCopyAnyway": "Copy anyway", + "diagDialogTitle": "Diagnostics archive", + "diagNoFindingsTitle": "No known issues found", + "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", + "diagChecklistTitle": "Sharing checklist", + "diagChecklistZip": "Send this .zip archive directly; it includes redacted host details, settings, and logs, with no need to paste long text", + "diagChecklistSteps": "Briefly describe what happened, where it stopped, and the steps leading up to it", + "diagIncludedFiles": "Included files", + "diagSummaryToggle": "Environment summary", + "diagCopySummary": "Copy summary", + "diagRevealFile": "Show in folder", + "diagCopyArchive": "Copy archive", + "toastDiagFileCopied": "Diagnostics archive copied — paste to send", + "failCopyDiagnosticsFile": "Couldn’t copy diagnostics archive", + "diagFindingGpuDeviceLostTitle": "GPU device lost", + "diagFindingGpuDeviceLostDesc": "Update the GPU driver, choose another discrete GPU, or switch to VMware SVGA (software rendering) for now", + "diagFindingGpuVulkanFloorTitle": "Vulkan requirements not met", + "diagFindingGpuVulkanFloorDesc": "Update the GPU driver for Vulkan 1.3 and required extensions, or switch to VMware SVGA (software rendering)", + "diagFindingWhpxUnavailableTitle": "WHPX virtualization unavailable", + "diagFindingWhpxUnavailableDesc": "Open the Engine page to check Windows Hypervisor Platform status and enable virtualization", + "diagFindingLowMemoryTitle": "Low available host memory", + "diagFindingLowMemoryDesc": "Close memory-heavy apps on the host, or lower the VM’s memory allocation and try again", + "diagFindingLowDiskTitle": "Low free space on data drive", + "diagFindingLowDiskDesc": "Free up space on the data drive, or move the data folder to a drive with more space", "newVM": "New virtual machine", "start": { "message": "Start", diff --git a/locales/en-US/vm.json b/locales/en-US/vm.json index ee9b9a9..79df47d 100644 --- a/locales/en-US/vm.json +++ b/locales/en-US/vm.json @@ -154,7 +154,6 @@ "toastGuestToolsDetachedNextStart": "Tools disk ejected; applies on next start", "toastNVMeReady": "Upgraded disk controller to NVMe", "toastNVMeNextStart": "Switched to NVMe — applies on next start", - "toastDiagExported": "Redacted diagnostics archive exported (.zip)", "toastCloned": "CoW clone “{name}” created", "toastTyped": { "message": "{n, plural, one {Typed # character} other {Typed # characters}}", diff --git a/locales/zh-CN/core.json b/locales/zh-CN/core.json index 11dc186..9e47ffb 100644 --- a/locales/zh-CN/core.json +++ b/locales/zh-CN/core.json @@ -99,6 +99,33 @@ "logSearchPlaceholder": "筛选日志…", "logErrorsOnly": "仅错误/警告", "logCopy": "复制日志", + "logExportDiagnostics": "导出排障包", + "logLargeCopyTitle": "大段日志", + "logLargeCopyDesc": "即将复制 {n} 行日志,直接粘贴容易刷屏且缺少环境信息,建议导出排障包", + "logCopyAnyway": "仍然复制", + "diagDialogTitle": "排障包", + "diagNoFindingsTitle": "未发现已知异常", + "diagNoFindingsDesc": "日志与环境检查未发现常见故障,求助时补充具体现象(如黑屏、卡进度条)便于排查", + "diagChecklistTitle": "反馈清单", + "diagChecklistZip": "直接发送此 .zip 压缩包,内含已脱敏的环境信息、配置与日志,无需再贴大段文字或截图", + "diagChecklistSteps": "一并说明问题现象、卡住的阶段或触发前的操作", + "diagIncludedFiles": "包含文件", + "diagSummaryToggle": "环境摘要", + "diagCopySummary": "复制摘要", + "diagRevealFile": "打开位置", + "diagCopyArchive": "复制压缩包", + "toastDiagFileCopied": "已复制排障包文件,可直接粘贴发送", + "failCopyDiagnosticsFile": "复制排障包失败", + "diagFindingGpuDeviceLostTitle": "显卡设备丢失", + "diagFindingGpuDeviceLostDesc": "更新显卡驱动、改选其他独立显卡,或暂时改用 VMware SVGA(软件渲染)", + "diagFindingGpuVulkanFloorTitle": "Vulkan 版本或扩展不足", + "diagFindingGpuVulkanFloorDesc": "更新显卡驱动以支持 Vulkan 1.3 与必需扩展,或改用 VMware SVGA(软件渲染)", + "diagFindingWhpxUnavailableTitle": "WHPX 虚拟化不可用", + "diagFindingWhpxUnavailableDesc": "打开「内核」页检查 Windows 虚拟机监控程序平台状态并按提示启用", + "diagFindingLowMemoryTitle": "宿主机可用内存偏低", + "diagFindingLowMemoryDesc": "关闭占用较高的宿主机程序,或调低虚拟机分配内存后重试", + "diagFindingLowDiskTitle": "数据盘可用空间偏低", + "diagFindingLowDiskDesc": "清理数据盘空间,或将数据目录迁移到可用空间更大的磁盘", "newVM": "新建虚拟机", "start": { "message": "启动", diff --git a/locales/zh-CN/vm.json b/locales/zh-CN/vm.json index 3e0758b..d4504b7 100644 --- a/locales/zh-CN/vm.json +++ b/locales/zh-CN/vm.json @@ -154,7 +154,6 @@ "toastGuestToolsDetachedNextStart": "已弹出工具盘,下次启动生效", "toastNVMeReady": "已升级到 NVMe 磁盘控制器", "toastNVMeNextStart": "已切换为 NVMe,下次启动生效", - "toastDiagExported": "已导出脱敏排障日志包 (.zip)", "toastCloned": "已派生 CoW 副本「{name}」", "toastTyped": { "message": "{n, plural, other {已键入 # 个字符}}", -- 2.54.1 From 2e879ab074a2c908b6ad72ac769ef07e92e9a615 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <105714958+Nwflower@users.noreply.github.com> Date: Sun, 6 Dec 2026 17:26:51 +0800 Subject: [PATCH 4/4] =?UTF-8?q?fix(app,ui,overlay,ocr,cli):=20=E5=8A=A0?= =?UTF-8?q?=E5=9B=BA=20#134=20=E8=87=AA=E5=8A=A8=E8=A3=85=E6=9C=BA?= =?UTF-8?q?=E5=8F=97=E4=BF=9D=E6=8A=A4=E9=98=B6=E6=AE=B5=E6=8E=88=E6=9D=83?= =?UTF-8?q?=E3=80=81=E5=8D=87=E7=BA=A7=E9=BB=98=E8=AE=A4=E9=A1=B9=E4=B8=8E?= =?UTF-8?q?=E4=BC=9A=E8=AF=9D=E7=94=9F=E5=91=BD=E5=91=A8=E6=9C=9F=20(#210)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(app,ui,overlay,ocr,cli): harden autoinstall auth, upgrade defaults, and lifecycle after #134 * fix(app,cli,ui): address PR #210 review findings and keep default auto-install enabled --- frontend/scripts/test-autoinstall.mjs | 1 + frontend/src/components/AutoInstallPanel.tsx | 19 +- frontend/src/components/CreateWizard.tsx | 2 +- frontend/src/components/VMPage.tsx | 2 +- frontend/src/types.ts | 2 + internal/app/agent_session_flow.go | 74 +++- internal/app/autoinstall_flow.go | 50 +++ internal/app/autoinstall_hardening_test.go | 355 ++++++++++++++++++ internal/app/computer_use_host.go | 20 +- internal/app/confirm_flow.go | 76 +++- internal/app/create_flow.go | 3 + internal/app/plugin_connect.go | 29 +- internal/cli/autoinstall.go | 8 +- internal/cli/macos_native.go | 3 + .../host/sessionoverlay/overlay_windows.go | 15 +- internal/macos/autoinstall/ocr/pe_check.go | 3 +- .../macos/autoinstall/ocr/rapidocr_windows.go | 6 +- 17 files changed, 612 insertions(+), 56 deletions(-) create mode 100644 internal/app/autoinstall_hardening_test.go diff --git a/frontend/scripts/test-autoinstall.mjs b/frontend/scripts/test-autoinstall.mjs index 5bb0850..ae293cc 100644 --- a/frontend/scripts/test-autoinstall.mjs +++ b/frontend/scripts/test-autoinstall.mjs @@ -9,6 +9,7 @@ const { defaultAutoInstallDraft, validateAutoInstallDraft } = await loadTestModu 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) diff --git a/frontend/src/components/AutoInstallPanel.tsx b/frontend/src/components/AutoInstallPanel.tsx index ea48847..b79e966 100644 --- a/frontend/src/components/AutoInstallPanel.tsx +++ b/frontend/src/components/AutoInstallPanel.tsx @@ -239,19 +239,28 @@ export const VMAutoInstallPanel: React.FC = ({ 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) } - }, [provider.plugin_id, driverID, vmName, sessionRefreshKey]) - - const active = status?.status === 'running' || status?.status === 'paused_for_user' - const paused = status?.status === 'paused_for_user' + }, [active, provider.plugin_id, driverID, vmName]) const canStart = validateAutoInstallDraft(draft, true) @@ -345,7 +354,7 @@ export const VMAutoInstallPanel: React.FC = ({ {active && !paused && ( diff --git a/frontend/src/components/CreateWizard.tsx b/frontend/src/components/CreateWizard.tsx index 39f7103..64c374b 100644 --- a/frontend/src/components/CreateWizard.tsx +++ b/frontend/src/components/CreateWizard.tsx @@ -897,7 +897,7 @@ export const CreateWizard: React.FC = ({ locale, host, drivers, fixedMode