feat: add host computer-use and MCP bridge
This commit is contained in:
1 parent
c9a7bffc1d
commit
352aa2f4a0
43 files changed
+2458
-112
No files matched your search
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"group": "new",
|
||||||
|
"order": 0,
|
||||||
|
"authors": ["bvzrays"],
|
||||||
|
"zh": "新增默认启用的「虚拟机交互」扩展,统一处理虚拟机截图、鼠标、键盘与文本输入;新增受权限核验的插件控制通道与官方 MCP 服务插件,支持客体 SSH 命令和 SFTP 文件传输。",
|
||||||
|
"en": "Add the enabled-by-default Computer Use extension for VM screenshots, pointer, keyboard, and text input, plus a permission-checked plugin channel and official MCP service with guest SSH commands and SFTP transfers."
|
||||||
|
}
|
||||||
@@ -45,11 +45,13 @@ flowchart TB
|
|||||||
|
|
||||||
客户端编译为 Windows 图形子系统程序。命令行模式下保留调用方传入的管道或文件句柄,缺失时自动挂载父终端控制台;在交互式终端中追加 `| Out-Host` 可等待命令执行完毕。
|
客户端编译为 Windows 图形子系统程序。命令行模式下保留调用方传入的管道或文件句柄,缺失时自动挂载父终端控制台;在交互式终端中追加 `| Out-Host` 可等待命令执行完毕。
|
||||||
|
|
||||||
### 双通道本地控制套接字
|
### 宿主控制台代理与本地控制通道
|
||||||
|
|
||||||
便携运行时为每台运行中的虚拟机创建本地 Unix 域控制套接字。由于单个控制端点同一时刻只服务一个连接,客户端对自动键入、屏幕截图与状态迁移按虚拟机串行复用短连接,键入期间自动暂停后台截图。
|
便携运行时为每台运行中的虚拟机创建本地 Unix 域 QMP 套接字。内置 `builtin.computer-use` 服务按虚拟机复用 QMP 长连接并串行处理截图、鼠标、键盘和文本输入;缩略图与打字流程共用该服务,键入期间暂停后台截图。
|
||||||
|
|
||||||
Windows 10 缺少虚拟化分区热重置能力,客体内部重启会导致虚拟化后端异常退出。在 Windows 10 宿主机上,客户端为虚拟机附加不自动重启标志,并额外挂载一条独立的本地 Unix 域控制套接字监听重启退出事件,进程干净退出后自动重新拉起。两条通道均不使用 TCP 端口,防止虚拟机经用户态网络反向访问宿主机控制面。
|
L3 插件经权限核验的 Host API 请求虚拟机状态、截图和输入操作,宿主不接受插件提供的 QMP 套接字或虚拟机目录。MCP 客户端通过 `reims-go plugin connect <plugin-id> <channel>` 与桌面进程通信;Windows 命名管道按可执行文件路径和用户 SID 摘要区分,ACL 限制当前用户并拒绝远程客户端。
|
||||||
|
|
||||||
|
Windows 10 缺少虚拟化分区热重置能力,客体内部重启会导致虚拟化后端异常退出。在 Windows 10 宿主机上,客户端为虚拟机附加不自动重启标志,并额外挂载一条独立的本地 Unix 域控制套接字监听重启退出事件,进程干净退出后自动重新拉起。QMP 和插件控制通道均不使用 TCP 端口,防止虚拟机经用户态网络反向访问宿主机控制面。
|
||||||
|
|
||||||
### 宿客协作与目录隔离
|
### 宿客协作与目录隔离
|
||||||
|
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ flowchart TB
|
|||||||
|
|
||||||
| 层级 | 运行形态 | 隔离与约束边界 |
|
| 层级 | 运行形态 | 隔离与约束边界 |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| 编译期内置扩展 | 随主程序编译的模块,经同一注册表装载 | 核心默认主题始终启用;macOS 客体支持、宿客传输、剪贴板互通、输入服务与并行下载器可独立启停且停用零残留 |
|
| 编译期内置扩展 | 随主程序编译的模块,经同一注册表装载 | 核心默认主题始终启用;macOS 客体支持、宿客传输、剪贴板互通、输入服务、虚拟机交互与并行下载器可独立启停且停用零残留 |
|
||||||
| L1 声明式插件 | 纯 JSON 配置、词表、字体与静态样式资源 | 不含可执行代码,全部字段经宿主白名单与静态扫描校验 |
|
| L1 声明式插件 | 纯 JSON 配置、词表、字体与静态样式资源 | 不含可执行代码,全部字段经宿主白名单与静态扫描校验 |
|
||||||
| 运行时包 | 原生虚拟化与工具二进制归档 | 自身不注册插件代码,仅由客体驱动以受控子进程调用 |
|
| 运行时包 | 原生虚拟化与工具二进制归档 | 自身不注册插件代码,仅由客体驱动以受控子进程调用 |
|
||||||
| L3 外部进程插件 | 每插件独立子进程,采用 `Content-Length` 分帧的双向 JSON-RPC 2.0 通信(日志走标准错误流) | 崩溃或死循环不拖垮主窗口;操作系统层面拥有当前用户完整账户权限,仅宿主接口受权限表约束 |
|
| L3 外部进程插件 | 每插件独立子进程,采用 `Content-Length` 分帧的双向 JSON-RPC 2.0 通信(日志走标准错误流) | 崩溃或死循环不拖垮主窗口;操作系统层面拥有当前用户完整账户权限,仅宿主接口受权限表约束 |
|
||||||
@@ -30,6 +30,12 @@ flowchart TB
|
|||||||
2. Apache-2.0 客户端本体与外部组件仅通过独立子进程和协议交互,插件包、私有数据、缓存与日志全部隔离在数据目录的 `plugins/` 下。
|
2. Apache-2.0 客户端本体与外部组件仅通过独立子进程和协议交互,插件包、私有数据、缓存与日志全部隔离在数据目录的 `plugins/` 下。
|
||||||
3. 插件无权读取硬件序列号、UUID、ROM 或 MAC 地址,无权静默触发管理员提权或系统重启,也无权直接改写 `vm.toml`;插件贡献的排障数据一律经宿主脱敏后才写入排障包。
|
3. 插件无权读取硬件序列号、UUID、ROM 或 MAC 地址,无权静默触发管理员提权或系统重启,也无权直接改写 `vm.toml`;插件贡献的排障数据一律经宿主脱敏后才写入排障包。
|
||||||
|
|
||||||
|
内置 `builtin.computer-use` 默认启用,通过宿主控制台代理串行处理每台虚拟机的截图、鼠标、键盘和文本输入,现有缩略图与打字入口共用该服务。它不实现 MCP 协议。
|
||||||
|
|
||||||
|
L3 插件可在清单 `contributes.channels` 中声明 `jsonl` 通道。桌面端的 `plugin connect` 经 Windows 当前用户限定的命名管道转发消息,不开放 TCP 或 HTTP MCP 监听。官方 `reims.agent` 插件实现 MCP 工具、VM 状态与桌面控制,以及通过 SSH/SFTP 的客体命令和文件传输。
|
||||||
|
|
||||||
|
Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 VM 目录。读取 VM 状态要求 `vm:read`,截图要求 `vm:screen`,输入要求 `qmp:write`,VM 启停要求 `vm:control`。Host API 审核插件权限并记录方法名,不把输入文本写入审计日志。登录密码由 Windows DPAPI 保护,宿主只提供按设置键名键入的操作,不向插件返回明文。
|
||||||
|
|
||||||
## 生命周期、参数账本与资源预算
|
## 生命周期、参数账本与资源预算
|
||||||
|
|
||||||
每个启用中的插件拥有独立的作用域,注册的服务、事件订阅、界面槽位、后台监听与系统钩子均绑定释放函数;插件停用、卸载或激活失败时按逆序完整拆除。服务依赖变更时先停用失去依赖的插件,再按依赖拓扑激活就绪插件。
|
每个启用中的插件拥有独立的作用域,注册的服务、事件订阅、界面槽位、后台监听与系统钩子均绑定释放函数;插件停用、卸载或激活失败时按逆序完整拆除。服务依赖变更时先停用失去依赖的插件,再按依赖拓扑激活就绪插件。
|
||||||
@@ -66,7 +72,7 @@ flowchart TB
|
|||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| 低危 | `vm:read`、`ui:notify`、`task:progress`、`fs:plugin_data`、`log:read` | 启用时展示用途说明,纯声明式语言包无需高危权限 |
|
| 低危 | `vm:read`、`ui:notify`、`task:progress`、`fs:plugin_data`、`log:read` | 启用时展示用途说明,纯声明式语言包无需高危权限 |
|
||||||
| 中危 | `vm:intent`、`runtime:source`、`net:<origin>`、`ui:slot`、`input:filter`、`fs:pick` | 首次启用时由用户确认 |
|
| 中危 | `vm:intent`、`runtime:source`、`net:<origin>`、`ui:slot`、`input:filter`、`fs:pick` | 首次启用时由用户确认 |
|
||||||
| 高危 | `driver:vm`、`runtime:provider`、`process:spawn`、`vm:control`、`qmp:write`、`fs:vm_dir`、`fs:shared`、`host:clipboard`、`ui:script` | 市场端与已安装页统一展示风险说明、入口路径、SHA-256、发布者、许可证与能力明细并要求显式勾选;升级新增高危权限,或 L3 原生程序及 `ui:script` 交互脚本入口哈希变化时自动暂停并重新审批(仅开发链接模式跳过哈希锚定) |
|
| 高危 | `driver:vm`、`runtime:provider`、`process:spawn`、`vm:control`、`vm:screen`、`qmp:write`、`fs:vm_dir`、`fs:shared`、`host:clipboard`、`ui:script` | 市场端与已安装页统一展示风险说明、入口路径、SHA-256、发布者、许可证与能力明细并要求显式勾选;升级新增高危权限,或 L3 原生程序及 `ui:script` 交互脚本入口哈希变化时自动暂停并重新审批(仅开发链接模式跳过哈希锚定) |
|
||||||
|
|
||||||
市场预检与本地安装共用同一套平台及版本兼容校验:平台支持 `windows-x64`、`windows/amd64`、`*` 与 `any`(不区分大小写,省略时默认全平台兼容),引擎范围同时核验 `pluginApi`、`uiApi`、`bridgeApi` 与 `reims-go`(开发构建跳过宿主版本门槛)。市场索引与插件包下载统一走直连客户端(不委派外部或并行下载器插件),遵循系统代理,拒绝向非本机明文 HTTP 的降级重定向,并对包体大小与流式读空闲施加硬上限。仅当前会话经官方 HTTPS 市场索引新鲜拉取的条目或带内置可信签名的包可获得 `official` 或 `verified` 信任级;第三方自定义镜像、冷启动未联网的磁盘缓存以及网络异常回退的陈旧缓存均降为 `community`,且卡片展示与实际安装保持一致,网络恢复后下次查询即重新拉取。
|
市场预检与本地安装共用同一套平台及版本兼容校验:平台支持 `windows-x64`、`windows/amd64`、`*` 与 `any`(不区分大小写,省略时默认全平台兼容),引擎范围同时核验 `pluginApi`、`uiApi`、`bridgeApi` 与 `reims-go`(开发构建跳过宿主版本门槛)。市场索引与插件包下载统一走直连客户端(不委派外部或并行下载器插件),遵循系统代理,拒绝向非本机明文 HTTP 的降级重定向,并对包体大小与流式读空闲施加硬上限。仅当前会话经官方 HTTPS 市场索引新鲜拉取的条目或带内置可信签名的包可获得 `official` 或 `verified` 信任级;第三方自定义镜像、冷启动未联网的磁盘缓存以及网络异常回退的陈旧缓存均降为 `community`,且卡片展示与实际安装保持一致,网络恢复后下次查询即重新拉取。
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ require (
|
|||||||
|
|
||||||
require (
|
require (
|
||||||
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 // indirect
|
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 // indirect
|
||||||
|
github.com/Microsoft/go-winio v0.6.2 // indirect
|
||||||
github.com/bep/debounce v1.2.1 // indirect
|
github.com/bep/debounce v1.2.1 // indirect
|
||||||
github.com/gabriel-vasile/mimetype v1.4.16 // indirect
|
github.com/gabriel-vasile/mimetype v1.4.16 // indirect
|
||||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 h1:N3IGoHHp9pb6mj1cbXbuaSXV/UMKwmbKLf53nQmtqMA=
|
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 h1:N3IGoHHp9pb6mj1cbXbuaSXV/UMKwmbKLf53nQmtqMA=
|
||||||
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3/go.mod h1:QtOLZGz8olr4qH2vWK0QH0w0O4T9fEIjMuWpKUsH7nc=
|
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3/go.mod h1:QtOLZGz8olr4qH2vWK0QH0w0O4T9fEIjMuWpKUsH7nc=
|
||||||
|
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||||
|
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||||
github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY=
|
github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY=
|
||||||
github.com/bep/debounce v1.2.1/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0=
|
github.com/bep/debounce v1.2.1/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
|||||||
+4
-1
@@ -13,6 +13,7 @@ import (
|
|||||||
|
|
||||||
"github.com/Nwflower/reims-go/internal/cli"
|
"github.com/Nwflower/reims-go/internal/cli"
|
||||||
"github.com/Nwflower/reims-go/internal/config"
|
"github.com/Nwflower/reims-go/internal/config"
|
||||||
|
"github.com/Nwflower/reims-go/internal/control"
|
||||||
"github.com/Nwflower/reims-go/internal/dataroot"
|
"github.com/Nwflower/reims-go/internal/dataroot"
|
||||||
"github.com/Nwflower/reims-go/internal/driver"
|
"github.com/Nwflower/reims-go/internal/driver"
|
||||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||||
@@ -112,7 +113,7 @@ type App struct {
|
|||||||
quitMode string
|
quitMode string
|
||||||
vmStarts sync.WaitGroup
|
vmStarts sync.WaitGroup
|
||||||
lastVMs []driver.VMListItem
|
lastVMs []driver.VMListItem
|
||||||
lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale
|
lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale
|
||||||
lastVMListErr error
|
lastVMListErr error
|
||||||
pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick
|
pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick
|
||||||
diskPaths map[string]cachedDiskPath
|
diskPaths map[string]cachedDiskPath
|
||||||
@@ -125,6 +126,7 @@ type App struct {
|
|||||||
logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go)
|
logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go)
|
||||||
pluginMgr *plugin.Manager
|
pluginMgr *plugin.Manager
|
||||||
pluginMarket *plugin.MarketClient
|
pluginMarket *plugin.MarketClient
|
||||||
|
controlServer *control.Server
|
||||||
driverRouter *driver.Router
|
driverRouter *driver.Router
|
||||||
lifecycleSvc *vmlifecycle.Service
|
lifecycleSvc *vmlifecycle.Service
|
||||||
runtimeKinds *rt.KindRegistry
|
runtimeKinds *rt.KindRegistry
|
||||||
@@ -254,6 +256,7 @@ func (a *App) shutdown(ctx context.Context) {
|
|||||||
}
|
}
|
||||||
tasks.cancelAll()
|
tasks.cancelAll()
|
||||||
stopAllVMMonitors()
|
stopAllVMMonitors()
|
||||||
|
a.stopPluginControlServer()
|
||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
a.inputShuttingDown = true
|
a.inputShuttingDown = true
|
||||||
fallback := a.fallbackInputSvc
|
fallback := a.fallbackInputSvc
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"github.com/Nwflower/reims-go/internal/console"
|
||||||
|
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||||
|
)
|
||||||
|
|
||||||
|
var fallbackComputerUse = console.NewManager()
|
||||||
|
|
||||||
|
func (a *App) computerUseService() (builtin.ComputerUseService, error) {
|
||||||
|
a.mu.Lock()
|
||||||
|
mgr := a.pluginMgr
|
||||||
|
a.mu.Unlock()
|
||||||
|
if mgr == nil {
|
||||||
|
return fallbackComputerUse, nil
|
||||||
|
}
|
||||||
|
raw, ok := mgr.Registry().LookupService(builtin.ServiceComputerUse)
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("virtual machine interaction is disabled")
|
||||||
|
}
|
||||||
|
service, ok := raw.(builtin.ComputerUseService)
|
||||||
|
if !ok || service == nil {
|
||||||
|
return nil, errors.New("virtual machine interaction service is unavailable")
|
||||||
|
}
|
||||||
|
return service, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,401 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/Nwflower/reims-go/internal/driver"
|
||||||
|
"github.com/Nwflower/reims-go/internal/plugin"
|
||||||
|
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||||
|
"github.com/Nwflower/reims-go/internal/thumb"
|
||||||
|
)
|
||||||
|
|
||||||
|
const computerUsePreviewWidth = 1280
|
||||||
|
const computerUseMaxTextRunes = 4000
|
||||||
|
|
||||||
|
func (a *App) computerUseHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
|
||||||
|
if mgr == nil || mgr.Broker() == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return map[string]plugin.RPCRequestHandler{
|
||||||
|
"host/vm.list": a.authorizedComputerUseHandler(mgr, pluginID, "vm:read", "host/vm.list", a.handleComputerUseVMList),
|
||||||
|
"host/vm.get": a.authorizedComputerUseHandler(mgr, pluginID, "vm:read", "host/vm.get", a.handleComputerUseVMGet),
|
||||||
|
"host/vm.start": a.authorizedComputerUseHandler(mgr, pluginID, "vm:control", "host/vm.start", a.handleComputerUseVMStart),
|
||||||
|
"host/vm.shutdown": a.authorizedComputerUseHandler(mgr, pluginID, "vm:control", "host/vm.shutdown", a.handleComputerUseVMShutdown),
|
||||||
|
"host/console.screenshot": a.authorizedComputerUseHandler(mgr, pluginID, "vm:screen", "host/console.screenshot", a.handleComputerUseScreenshot),
|
||||||
|
"host/console.pointer": a.authorizedComputerUseHandler(mgr, pluginID, "qmp:write", "host/console.pointer", a.handleComputerUsePointer),
|
||||||
|
"host/console.key": a.authorizedComputerUseHandler(mgr, pluginID, "qmp:write", "host/console.key", a.handleComputerUseKey),
|
||||||
|
"host/console.type": a.authorizedComputerUseHandler(mgr, pluginID, "qmp:write", "host/console.type", a.handleComputerUseType),
|
||||||
|
"host/console.typeSecret": a.authorizedComputerUseHandler(mgr, pluginID, "qmp:write", "host/console.typeSecret", func(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||||
|
if pluginID != "reims.agent" {
|
||||||
|
return nil, errors.New("secret typing is reserved for reims.agent")
|
||||||
|
}
|
||||||
|
return a.handleComputerUseTypeSecret(ctx, raw)
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) handleComputerUseTypeSecret(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||||
|
var req struct {
|
||||||
|
VM string `json:"vm"`
|
||||||
|
Setting string `json:"setting"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &req); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.Setting) == "" {
|
||||||
|
return nil, errors.New("secret setting name is required")
|
||||||
|
}
|
||||||
|
vm, err := a.resolveComputerUseVM(req.VM)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
a.mu.Lock()
|
||||||
|
mgr := a.pluginMgr
|
||||||
|
a.mu.Unlock()
|
||||||
|
if mgr == nil {
|
||||||
|
return nil, errors.New("plugin manager is unavailable")
|
||||||
|
}
|
||||||
|
secret, err := mgr.SecretSetting("reims.agent", vm.Ref().Key(), req.Setting)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer func() { secret = "" }()
|
||||||
|
if len(secret) == 0 || utf8.RuneCountInString(secret) > computerUseMaxTextRunes {
|
||||||
|
return nil, errors.New("secret must contain between 1 and 4000 characters")
|
||||||
|
}
|
||||||
|
count, err := a.injectTextIntoVMWithLogging(vm.Name, vm.Directory, secret, false, true)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return map[string]any{"characters": count}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) handleComputerUseVMList(ctx context.Context, _ json.RawMessage) (any, error) {
|
||||||
|
items, err := a.listVMsInternal(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
vms := make([]map[string]any, 0, len(items))
|
||||||
|
for _, item := range items {
|
||||||
|
info, err := a.resolveVMInfo(item.DriverID, item.Name)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
vms = append(vms, a.computerUseVMView(info))
|
||||||
|
}
|
||||||
|
return map[string]any{"vms": vms}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) handleComputerUseVMGet(_ 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
|
||||||
|
}
|
||||||
|
info, err := a.resolveComputerUseVMInfo(req.VM)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return a.computerUseVMView(info), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) computerUseVMView(vm driver.VMInfo) map[string]any {
|
||||||
|
view := map[string]any{
|
||||||
|
"vm": vm.Ref().Key(),
|
||||||
|
"name": vm.Name,
|
||||||
|
"driver_id": vm.DriverID,
|
||||||
|
"state": vm.State,
|
||||||
|
}
|
||||||
|
if vm.CPUs > 0 {
|
||||||
|
view["cpus"] = vm.CPUs
|
||||||
|
}
|
||||||
|
if vm.Memory != "" {
|
||||||
|
view["memory"] = vm.Memory
|
||||||
|
}
|
||||||
|
if vm.DiskSummary != "" {
|
||||||
|
view["disk_summary"] = vm.DiskSummary
|
||||||
|
}
|
||||||
|
if vm.SSHPort > 0 {
|
||||||
|
view["ssh_port"] = vm.SSHPort
|
||||||
|
}
|
||||||
|
if len(vm.Capabilities) > 0 {
|
||||||
|
view["capabilities"] = append([]string(nil), vm.Capabilities...)
|
||||||
|
}
|
||||||
|
username := a.GetVMSSHUserWithDriver(vm.DriverID, vm.Name)
|
||||||
|
a.mu.Lock()
|
||||||
|
mgr := a.pluginMgr
|
||||||
|
a.mu.Unlock()
|
||||||
|
if mgr != nil {
|
||||||
|
settings := mgr.GetSettings("reims.agent", vm.Ref().Key(), false)
|
||||||
|
if configured, ok := settings["username"].(string); ok && strings.TrimSpace(configured) != "" {
|
||||||
|
username = strings.TrimSpace(configured)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if username != "" {
|
||||||
|
view["ssh_username"] = username
|
||||||
|
}
|
||||||
|
return view
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) handleComputerUseVMStart(_ 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, err := a.resolveComputerUseVMInfo(req.VM)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := a.StartVMWithDriver(vm.DriverID, vm.Name); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return map[string]any{"ok": true}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) handleComputerUseVMShutdown(_ 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, err := a.resolveComputerUseVMInfo(req.VM)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := a.StopVMWithDriver(vm.DriverID, vm.Name, false); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return map[string]any{"ok": true}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type computerUseHandler func(context.Context, json.RawMessage) (any, error)
|
||||||
|
|
||||||
|
func (a *App) authorizedComputerUseHandler(mgr *plugin.Manager, pluginID, permission, method string, run computerUseHandler) plugin.RPCRequestHandler {
|
||||||
|
return func(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||||
|
broker := mgr.Broker()
|
||||||
|
if err := broker.Authorize(pluginID, permission); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
result, err := run(ctx, raw)
|
||||||
|
if err != nil {
|
||||||
|
broker.Audit(pluginID, "HOST_API_ERROR", method)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
broker.Audit(pluginID, "HOST_API", method)
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) resolveComputerUseVM(ref string) (driver.VMInfo, error) {
|
||||||
|
ref = strings.TrimSpace(ref)
|
||||||
|
if ref == "" {
|
||||||
|
return driver.VMInfo{}, errors.New("VM reference is required")
|
||||||
|
}
|
||||||
|
vm, err := a.resolveComputerUseVMInfo(ref)
|
||||||
|
if err != nil {
|
||||||
|
return driver.VMInfo{}, err
|
||||||
|
}
|
||||||
|
if driver.CanonicalDriverID(vm.DriverID) != builtin.IDDriverReimsMacOS {
|
||||||
|
return driver.VMInfo{}, fmt.Errorf("computer use is unavailable for driver %q", vm.DriverID)
|
||||||
|
}
|
||||||
|
current, ok := a.polledVMForDriver(vm.DriverID, vm.Name)
|
||||||
|
if !ok || current.State != "running" || current.PID == nil || *current.PID <= 0 {
|
||||||
|
return driver.VMInfo{}, fmt.Errorf("VM %q is not running", vm.Name)
|
||||||
|
}
|
||||||
|
if vm.Directory == "" {
|
||||||
|
vm.Directory = current.Dir
|
||||||
|
}
|
||||||
|
if vm.Directory == "" {
|
||||||
|
return driver.VMInfo{}, fmt.Errorf("VM %q has no console directory", vm.Name)
|
||||||
|
}
|
||||||
|
return vm, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolveComputerUseVMInfo accepts the bare VM name used by the UI and the
|
||||||
|
// canonical driverID:name reference returned by the VM list and resource APIs.
|
||||||
|
func (a *App) resolveComputerUseVMInfo(ref string) (driver.VMInfo, error) {
|
||||||
|
ref = strings.TrimSpace(ref)
|
||||||
|
if parsed, ok := driver.ParseVMRef(ref); ok {
|
||||||
|
return a.resolveVMInfo(parsed.DriverID, parsed.Name)
|
||||||
|
}
|
||||||
|
return a.resolveVMInfo("", ref)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) handleComputerUseScreenshot(ctx 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, err := a.resolveComputerUseVM(req.VM)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
service, err := a.computerUseService()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
a.mu.Lock()
|
||||||
|
if a.cfg == nil {
|
||||||
|
a.mu.Unlock()
|
||||||
|
return nil, errors.New("application configuration is unavailable")
|
||||||
|
}
|
||||||
|
tempDir := a.cfg.TempDir()
|
||||||
|
a.mu.Unlock()
|
||||||
|
if err := os.MkdirAll(tempDir, 0o755); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
file, err := os.CreateTemp(tempDir, "computer-use-*.ppm")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
path := file.Name()
|
||||||
|
if err := file.Close(); err != nil {
|
||||||
|
_ = os.Remove(path)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer os.Remove(path)
|
||||||
|
format, err := service.Screendump(ctx, vm.Directory, path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
sourceSize, err := thumb.Size(path, format)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
preview, err := thumb.LoadPreview(path, format, computerUsePreviewWidth)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if preview == nil {
|
||||||
|
return nil, errors.New("VM screen is blank")
|
||||||
|
}
|
||||||
|
encoded, err := thumb.JPEG(preview, 84)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
bounds := preview.Bounds()
|
||||||
|
return map[string]any{
|
||||||
|
"mime_type": "image/jpeg",
|
||||||
|
"width": bounds.Dx(),
|
||||||
|
"height": bounds.Dy(),
|
||||||
|
"source_width": sourceSize.X,
|
||||||
|
"source_height": sourceSize.Y,
|
||||||
|
"data": base64.StdEncoding.EncodeToString(encoded),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) handleComputerUsePointer(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||||
|
var req struct {
|
||||||
|
VM string `json:"vm"`
|
||||||
|
Action string `json:"action"`
|
||||||
|
X int `json:"x"`
|
||||||
|
Y int `json:"y"`
|
||||||
|
Width int `json:"width"`
|
||||||
|
Height int `json:"height"`
|
||||||
|
Button string `json:"button"`
|
||||||
|
Down *bool `json:"down"`
|
||||||
|
Delta int `json:"delta"`
|
||||||
|
Horizontal bool `json:"horizontal"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &req); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
vm, err := a.resolveComputerUseVM(req.VM)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
service, err := a.computerUseService()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
switch strings.ToLower(strings.TrimSpace(req.Action)) {
|
||||||
|
case "move":
|
||||||
|
available, err := service.PointerAvailable(ctx, vm.Directory)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !available {
|
||||||
|
return nil, errors.New("VM has no active absolute pointer")
|
||||||
|
}
|
||||||
|
err = service.MouseMove(ctx, vm.Directory, req.X, req.Y, req.Width, req.Height)
|
||||||
|
case "button":
|
||||||
|
if req.Down == nil {
|
||||||
|
return nil, errors.New("button action requires down")
|
||||||
|
}
|
||||||
|
err = service.MouseButton(ctx, vm.Directory, req.Button, *req.Down)
|
||||||
|
case "click":
|
||||||
|
err = service.MouseClick(ctx, vm.Directory, req.Button)
|
||||||
|
case "scroll":
|
||||||
|
err = service.MouseScroll(ctx, vm.Directory, req.Delta, req.Horizontal)
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unsupported pointer action %q", req.Action)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return map[string]any{"ok": true}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) handleComputerUseKey(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||||
|
var req struct {
|
||||||
|
VM string `json:"vm"`
|
||||||
|
Key string `json:"key"`
|
||||||
|
Modifiers []string `json:"modifiers"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &req); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.Key) == "" {
|
||||||
|
return nil, errors.New("key is required")
|
||||||
|
}
|
||||||
|
vm, err := a.resolveComputerUseVM(req.VM)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
service, err := a.computerUseService()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := service.PressKey(ctx, vm.Directory, req.Key, req.Modifiers...); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return map[string]any{"ok": true}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) handleComputerUseType(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||||
|
var req struct {
|
||||||
|
VM string `json:"vm"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &req); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(req.Text) == 0 || !utf8.ValidString(req.Text) {
|
||||||
|
return nil, errors.New("text must be non-empty valid UTF-8")
|
||||||
|
}
|
||||||
|
if utf8.RuneCountInString(req.Text) > computerUseMaxTextRunes {
|
||||||
|
return nil, fmt.Errorf("text exceeds %d characters", computerUseMaxTextRunes)
|
||||||
|
}
|
||||||
|
vm, err := a.resolveComputerUseVM(req.VM)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
n, err := a.injectTextIntoVMWithLogging(vm.Name, vm.Directory, req.Text, false, true)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return map[string]any{"characters": n}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/Nwflower/reims-go/internal/plugin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestComputerUseHostHandlersArePermissionCheckedAndAudited(t *testing.T) {
|
||||||
|
dataRoot := t.TempDir()
|
||||||
|
mgr, err := plugin.NewManager(plugin.ManagerOptions{DataRoot: dataRoot, HostVersion: "0.2.11"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("NewManager: %v", err)
|
||||||
|
}
|
||||||
|
defer mgr.Close()
|
||||||
|
|
||||||
|
const pluginID = "test.mcp.computer-use"
|
||||||
|
if err := mgr.Registry().Register(plugin.PluginDef{
|
||||||
|
Manifest: plugin.Manifest{
|
||||||
|
ID: pluginID,
|
||||||
|
Version: "1.0.0",
|
||||||
|
Permissions: []string{"qmp:write"},
|
||||||
|
},
|
||||||
|
Source: plugin.SourceMarket,
|
||||||
|
Trust: plugin.TrustOfficial,
|
||||||
|
Desired: true,
|
||||||
|
ApprovedPermissions: []string{"qmp:write"},
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("Register: %v", err)
|
||||||
|
}
|
||||||
|
mgr.Registry().Reconcile(context.Background())
|
||||||
|
|
||||||
|
app := &App{}
|
||||||
|
called := false
|
||||||
|
const secret = "caller-provided-secret"
|
||||||
|
handler := app.authorizedComputerUseHandler(mgr, pluginID, "qmp:write", "host/console.type", func(_ context.Context, _ json.RawMessage) (any, error) {
|
||||||
|
called = true
|
||||||
|
return map[string]any{"ok": true}, nil
|
||||||
|
})
|
||||||
|
result, err := handler(context.Background(), json.RawMessage(`{"text":"`+secret+`"}`))
|
||||||
|
if err != nil || !called || result == nil {
|
||||||
|
t.Fatalf("authorized handler result=%v called=%t err=%v", result, called, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
log, err := os.ReadFile(plugin.NewPluginsLayout(dataRoot).LogPath(pluginID))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read audit log: %v", err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(log), "host/console.type") || strings.Contains(string(log), secret) {
|
||||||
|
t.Fatalf("audit log did not record only the method name: %s", log)
|
||||||
|
}
|
||||||
|
|
||||||
|
deniedCalled := false
|
||||||
|
denied := app.authorizedComputerUseHandler(mgr, pluginID, "vm:screen", "host/console.screenshot", func(context.Context, json.RawMessage) (any, error) {
|
||||||
|
deniedCalled = true
|
||||||
|
return nil, nil
|
||||||
|
})
|
||||||
|
if _, err := denied(context.Background(), nil); err == nil || deniedCalled {
|
||||||
|
t.Fatalf("undeclared permission call err=%v called=%t", err, deniedCalled)
|
||||||
|
}
|
||||||
|
|
||||||
|
methods := app.computerUseHostHandlers(mgr, pluginID)
|
||||||
|
want := []string{
|
||||||
|
"host/vm.list", "host/vm.get", "host/vm.start", "host/vm.shutdown",
|
||||||
|
"host/console.screenshot", "host/console.pointer", "host/console.key", "host/console.type", "host/console.typeSecret",
|
||||||
|
}
|
||||||
|
for _, method := range want {
|
||||||
|
if methods[method] == nil {
|
||||||
|
t.Errorf("missing Host API handler %q", method)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := methods["host/console.typeSecret"](context.Background(), json.RawMessage(`{"vm":"fixture","setting":"login_password"}`)); err == nil {
|
||||||
|
t.Fatal("non-agent plugin accessed the secret typing handler")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"github.com/Nwflower/reims-go/internal/control"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (a *App) startPluginControlServer() {
|
||||||
|
a.mu.Lock()
|
||||||
|
if a.ctx == nil || a.pluginMgr == nil || a.controlServer != nil {
|
||||||
|
a.mu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
a.mu.Unlock()
|
||||||
|
|
||||||
|
server, err := control.Listen(func(ctx context.Context, pluginID, channel string, message json.RawMessage) (json.RawMessage, error) {
|
||||||
|
a.mu.Lock()
|
||||||
|
mgr := a.pluginMgr
|
||||||
|
a.mu.Unlock()
|
||||||
|
if mgr == nil {
|
||||||
|
return nil, errors.New("plugin manager is not ready")
|
||||||
|
}
|
||||||
|
return mgr.ChannelMessage(ctx, pluginID, channel, message)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
a.emitLog("plugin", "Could not open local plugin control channel: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
a.mu.Lock()
|
||||||
|
if a.ctx == nil || a.pluginMgr == nil || a.controlServer != nil {
|
||||||
|
a.mu.Unlock()
|
||||||
|
_ = server.Close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
a.controlServer = server
|
||||||
|
a.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) stopPluginControlServer() {
|
||||||
|
a.mu.Lock()
|
||||||
|
server := a.controlServer
|
||||||
|
a.controlServer = nil
|
||||||
|
a.mu.Unlock()
|
||||||
|
if server != nil {
|
||||||
|
_ = server.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -69,6 +69,7 @@ func (a *App) initPlugins() {
|
|||||||
a.emitLog("plugin", "Could not migrate macOS guest state: "+err.Error())
|
a.emitLog("plugin", "Could not migrate macOS guest state: "+err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
var mgr *plugin.Manager
|
||||||
mgr, err := plugin.NewManager(plugin.ManagerOptions{
|
mgr, err := plugin.NewManager(plugin.ManagerOptions{
|
||||||
DataRoot: dataRoot,
|
DataRoot: dataRoot,
|
||||||
HostVersion: version.Version,
|
HostVersion: version.Version,
|
||||||
@@ -81,6 +82,9 @@ func (a *App) initPlugins() {
|
|||||||
SidecarDriverFactory: func(contrib plugin.GuestDriverContribution, sup *plugin.SidecarSupervisor) any {
|
SidecarDriverFactory: func(contrib plugin.GuestDriverContribution, sup *plugin.SidecarSupervisor) any {
|
||||||
return driver.NewSidecarDriver(contrib, sup)
|
return driver.NewSidecarDriver(contrib, sup)
|
||||||
},
|
},
|
||||||
|
HostHandlers: func(pluginID string) map[string]plugin.RPCRequestHandler {
|
||||||
|
return a.computerUseHostHandlers(mgr, pluginID)
|
||||||
|
},
|
||||||
OnSettingsChanged: func(pluginID, vmName string) {
|
OnSettingsChanged: func(pluginID, vmName string) {
|
||||||
a.onPluginSettingsChanged(pluginID, vmName)
|
a.onPluginSettingsChanged(pluginID, vmName)
|
||||||
},
|
},
|
||||||
@@ -224,6 +228,7 @@ func (a *App) initPlugins() {
|
|||||||
a.syncKeymapRules()
|
a.syncKeymapRules()
|
||||||
a.syncClipboardPolicies()
|
a.syncClipboardPolicies()
|
||||||
a.syncLocales()
|
a.syncLocales()
|
||||||
|
a.startPluginControlServer()
|
||||||
}
|
}
|
||||||
|
|
||||||
// activeDownloader returns the highest-priority active downloader plugin provider,
|
// activeDownloader returns the highest-priority active downloader plugin provider,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
package app
|
package app
|
||||||
|
|
||||||
// VM screen thumbnails for the VM page: while a VM runs,
|
// VM screen thumbnails for the VM page: while a VM runs,
|
||||||
// grab one frame over its QMP socket (`screendump`), shrink it to a small
|
// grab one frame through the built-in computer-use console (`screendump`), shrink it to a small
|
||||||
// JPEG and keep it under <data root>\cache\thumbs, so a stopped VM can still
|
// JPEG and keep it under <data root>\cache\thumbs, so a stopped VM can still
|
||||||
// show its last screen. Nothing here touches vm.toml or the guest.
|
// show its last screen. Nothing here touches vm.toml or the guest.
|
||||||
|
|
||||||
@@ -22,7 +22,6 @@ import (
|
|||||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||||
"github.com/Nwflower/reims-go/internal/host"
|
"github.com/Nwflower/reims-go/internal/host"
|
||||||
"github.com/Nwflower/reims-go/internal/i18n"
|
"github.com/Nwflower/reims-go/internal/i18n"
|
||||||
"github.com/Nwflower/reims-go/internal/qmp"
|
|
||||||
"github.com/Nwflower/reims-go/internal/thumb"
|
"github.com/Nwflower/reims-go/internal/thumb"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -185,7 +184,11 @@ func (a *App) CopyVMScreenshotWithDriver(driverID, name string) error {
|
|||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
format, err := qmp.ScreendumpVM(ctx, vm.Dir, raw)
|
service, err := a.computerUseService()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
format, err := service.Screendump(ctx, vm.Dir, raw)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("capture screen: %w", err)
|
return fmt.Errorf("capture screen: %w", err)
|
||||||
}
|
}
|
||||||
@@ -239,7 +242,11 @@ func (a *App) captureThumbWithDriver(driverID, name, path string) (VMThumbnail,
|
|||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
format, err := qmp.ScreendumpVM(ctx, vm.Dir, raw)
|
service, err := a.computerUseService()
|
||||||
|
if err != nil {
|
||||||
|
return VMThumbnail{}, false
|
||||||
|
}
|
||||||
|
format, err := service.Screendump(ctx, vm.Dir, raw)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return VMThumbnail{}, false
|
return VMThumbnail{}, false
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -76,6 +76,10 @@ func (a *App) TypeText(name, text string) (int, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool) (int, error) {
|
func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool) (int, error) {
|
||||||
|
return a.injectTextIntoVMWithLogging(name, knownDir, text, fromRemoteIME, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) injectTextIntoVMWithLogging(name, knownDir, text string, fromRemoteIME, suppressLogs bool) (int, error) {
|
||||||
text = strings.ReplaceAll(text, "\r\n", "\n")
|
text = strings.ReplaceAll(text, "\r\n", "\n")
|
||||||
text = strings.ReplaceAll(text, "\r", "\n")
|
text = strings.ReplaceAll(text, "\r", "\n")
|
||||||
if text == "" {
|
if text == "" {
|
||||||
@@ -108,6 +112,10 @@ func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool)
|
|||||||
}
|
}
|
||||||
vmDir = d.Directory
|
vmDir = d.Directory
|
||||||
}
|
}
|
||||||
|
computerUse, err := a.computerUseService()
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
// Prefer Guest Tools Unicode injection for:
|
// Prefer Guest Tools Unicode injection for:
|
||||||
// - any non-ASCII (Chinese, CJK punctuation, emoji), OR
|
// - any non-ASCII (Chinese, CJK punctuation, emoji), OR
|
||||||
@@ -127,24 +135,24 @@ func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool)
|
|||||||
if srv != nil {
|
if srv != nil {
|
||||||
pasteCtx, cancel := context.WithTimeout(ctx, 6*time.Second)
|
pasteCtx, cancel := context.WithTimeout(ctx, 6*time.Second)
|
||||||
mode, err := srv.InjectText(pasteCtx, name, text, func(c context.Context) error {
|
mode, err := srv.InjectText(pasteCtx, name, text, func(c context.Context) error {
|
||||||
return qmp.SendPasteShortcut(c, vmDir)
|
return computerUse.SendPasteShortcut(c, vmDir)
|
||||||
})
|
})
|
||||||
cancel()
|
cancel()
|
||||||
if err == nil {
|
if err == nil {
|
||||||
n := utf8.RuneCountInString(text)
|
n := utf8.RuneCountInString(text)
|
||||||
if !fromRemoteIME {
|
if !fromRemoteIME && !suppressLogs {
|
||||||
a.emitVMLog(name, fmt.Sprintf("Injected %d character(s) into %s via Guest Tools (%s) + Cmd+V.", n, name, mode))
|
a.emitVMLog(name, fmt.Sprintf("Injected %d character(s) into %s via Guest Tools (%s) + Cmd+V.", n, name, mode))
|
||||||
}
|
}
|
||||||
return n, nil
|
return n, nil
|
||||||
}
|
}
|
||||||
if !errors.Is(err, guesttools.ErrGuestToolsNotConnected) {
|
if !suppressLogs && !errors.Is(err, guesttools.ErrGuestToolsNotConnected) {
|
||||||
a.emitVMLog(name, fmt.Sprintf("Guest Tools text injection (%s) failed: %v", mode, err))
|
a.emitVMLog(name, fmt.Sprintf("Guest Tools text injection (%s) failed: %v", mode, err))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fallback (or bare Enter/Tab / Recovery / Login screen): QMP US keystrokes.
|
// Fallback (or bare Enter/Tab / Recovery / Login screen): QMP US keystrokes.
|
||||||
n, err := qmp.TypeIntoVM(ctx, vmDir, text, nil)
|
n, err := computerUse.TypeText(ctx, vmDir, text, nil)
|
||||||
var ue *qmp.UntypeableError
|
var ue *qmp.UntypeableError
|
||||||
if errors.As(err, &ue) {
|
if errors.As(err, &ue) {
|
||||||
if fromRemoteIME {
|
if fromRemoteIME {
|
||||||
@@ -155,19 +163,21 @@ func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool)
|
|||||||
typing.lastHintAt[key] = time.Now()
|
typing.lastHintAt[key] = time.Now()
|
||||||
}
|
}
|
||||||
typing.mu.Unlock()
|
typing.mu.Unlock()
|
||||||
if shouldLog {
|
if shouldLog && !suppressLogs {
|
||||||
a.emitVMLog(name, "Remote IME Unicode text received, but Guest Tools is not connected in macOS yet (install Guest Tools to enable Chinese/Unicode remote input).")
|
a.emitVMLog(name, "Remote IME Unicode text received, but Guest Tools is not connected in macOS yet (install Guest Tools to enable Chinese/Unicode remote input).")
|
||||||
}
|
}
|
||||||
} else {
|
} else if !suppressLogs {
|
||||||
a.emitVMLog(name, "Paste as keystrokes refused: "+ue.Error())
|
a.emitVMLog(name, "Paste as keystrokes refused: "+ue.Error())
|
||||||
}
|
}
|
||||||
return 0, fmt.Errorf("%w: %s", ErrNotTypeable, ue.Error())
|
return 0, fmt.Errorf("%w: %s", ErrNotTypeable, ue.Error())
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.emitVMLog(name, fmt.Sprintf("Paste as keystrokes stopped after %d keys: %v", n, err))
|
if !suppressLogs {
|
||||||
|
a.emitVMLog(name, fmt.Sprintf("Paste as keystrokes stopped after %d keys: %v", n, err))
|
||||||
|
}
|
||||||
return n, err
|
return n, err
|
||||||
}
|
}
|
||||||
if !fromRemoteIME {
|
if !fromRemoteIME && !suppressLogs {
|
||||||
a.emitVMLog(name, fmt.Sprintf("Typed %d keys into %s.", n, name))
|
a.emitVMLog(name, fmt.Sprintf("Typed %d keys into %s.", n, name))
|
||||||
}
|
}
|
||||||
return n, nil
|
return n, nil
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/Nwflower/reims-go/internal/config"
|
"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/driver"
|
||||||
"github.com/Nwflower/reims-go/internal/i18n"
|
"github.com/Nwflower/reims-go/internal/i18n"
|
||||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||||
@@ -18,7 +19,6 @@ import (
|
|||||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||||
"github.com/Nwflower/reims-go/internal/plugin"
|
"github.com/Nwflower/reims-go/internal/plugin"
|
||||||
"github.com/Nwflower/reims-go/internal/qmp"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func defaultMacOSGuestLang(loc i18n.Locale) string { return opencore.DefaultGuestLang(loc) }
|
func defaultMacOSGuestLang(loc i18n.Locale) string { return opencore.DefaultGuestLang(loc) }
|
||||||
@@ -124,7 +124,7 @@ func typeMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, args
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
n, err := qmp.TypeIntoVM(ctx, detail.Directory, text, nil)
|
n, err := console.NewManager().TypeText(ctx, detail.Directory, text, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -77,10 +77,12 @@ func openCLIMarketClient(cfg *config.Config) *plugin.MarketClient {
|
|||||||
|
|
||||||
func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
|
func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||||
if len(args) == 0 {
|
if len(args) == 0 {
|
||||||
return fmt.Errorf("usage: reims-go plugin <list|search|install|update|pack|link|enable|disable|remove|info|doctor|locale|run>")
|
return fmt.Errorf("usage: reims-go plugin <list|search|install|update|pack|link|enable|disable|remove|info|doctor|locale|run|connect>")
|
||||||
}
|
}
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
switch args[0] {
|
switch args[0] {
|
||||||
|
case "connect":
|
||||||
|
return pluginConnect(args[1:])
|
||||||
case "search":
|
case "search":
|
||||||
fs := flag.NewFlagSet("plugin search", flag.ContinueOnError)
|
fs := flag.NewFlagSet("plugin search", flag.ContinueOnError)
|
||||||
kind := fs.String("kind", "", "Filter by plugin kind (theme, locale, driver, tool, template, runtime)")
|
kind := fs.String("kind", "", "Filter by plugin kind (theme, locale, driver, tool, template, runtime)")
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
//go:build !windows
|
||||||
|
|
||||||
|
package cli
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
|
func pluginConnect([]string) error {
|
||||||
|
return errors.New("plugin connect is available on Windows desktop builds")
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Nwflower/reims-go/internal/control"
|
||||||
|
)
|
||||||
|
|
||||||
|
func pluginConnect(args []string) error {
|
||||||
|
if len(args) != 2 || strings.TrimSpace(args[0]) == "" || strings.TrimSpace(args[1]) == "" {
|
||||||
|
return errors.New("usage: reims-go plugin connect <plugin-id> <channel>")
|
||||||
|
}
|
||||||
|
pluginID, channel := strings.TrimSpace(args[0]), strings.TrimSpace(args[1])
|
||||||
|
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
|
defer cancel()
|
||||||
|
conn, err := control.Dial(ctx)
|
||||||
|
if err != nil {
|
||||||
|
if startErr := spawnWindow([]string{"--background"}); startErr != nil {
|
||||||
|
return fmt.Errorf("connect to Reims-Go desktop: %w", err)
|
||||||
|
}
|
||||||
|
conn, err = waitForPluginControl(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("connect to Reims-Go desktop: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
go func() {
|
||||||
|
<-ctx.Done()
|
||||||
|
_ = conn.Close()
|
||||||
|
}()
|
||||||
|
|
||||||
|
encoder := json.NewEncoder(conn)
|
||||||
|
stdinDone := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
defer conn.Close()
|
||||||
|
scanner := bufio.NewScanner(os.Stdin)
|
||||||
|
scanner.Buffer(make([]byte, 64*1024), control.MaxFrameBytes)
|
||||||
|
for scanner.Scan() {
|
||||||
|
message := append(json.RawMessage(nil), scanner.Bytes()...)
|
||||||
|
if !json.Valid(message) {
|
||||||
|
stdinDone <- errors.New("MCP input line is not valid JSON")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := encoder.Encode(control.Request{PluginID: pluginID, Channel: channel, Message: message}); err != nil {
|
||||||
|
stdinDone <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
stdinDone <- scanner.Err()
|
||||||
|
_ = conn.Close()
|
||||||
|
}()
|
||||||
|
|
||||||
|
responseScanner := bufio.NewScanner(conn)
|
||||||
|
responseScanner.Buffer(make([]byte, 64*1024), control.MaxFrameBytes)
|
||||||
|
for responseScanner.Scan() {
|
||||||
|
var response control.Response
|
||||||
|
if err := json.Unmarshal(responseScanner.Bytes(), &response); err != nil {
|
||||||
|
return fmt.Errorf("decode host control response: %w", err)
|
||||||
|
}
|
||||||
|
if response.Error != "" {
|
||||||
|
return errors.New(response.Error)
|
||||||
|
}
|
||||||
|
if len(response.Message) > 0 && string(response.Message) != "null" {
|
||||||
|
if _, err := os.Stdout.Write(response.Message); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := os.Stdout.Write([]byte{'\n'}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := responseScanner.Err(); err != nil {
|
||||||
|
// Closing stdin closes the named pipe from the writer goroutine. The
|
||||||
|
// response reader can observe that close just before stdinDone is
|
||||||
|
// scheduled, so give the writer a short chance to report a clean EOF.
|
||||||
|
stdinTimer := time.NewTimer(250 * time.Millisecond)
|
||||||
|
defer stdinTimer.Stop()
|
||||||
|
select {
|
||||||
|
case stdinErr := <-stdinDone:
|
||||||
|
if stdinErr != nil && !errors.Is(stdinErr, context.Canceled) {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return stdinErr
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
case <-stdinTimer.C:
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitForPluginControl(ctx context.Context) (net.Conn, error) {
|
||||||
|
deadline := time.NewTimer(15 * time.Second)
|
||||||
|
defer deadline.Stop()
|
||||||
|
ticker := time.NewTicker(150 * time.Millisecond)
|
||||||
|
defer ticker.Stop()
|
||||||
|
var lastErr error
|
||||||
|
for {
|
||||||
|
conn, err := control.Dial(ctx)
|
||||||
|
if err == nil {
|
||||||
|
return conn, nil
|
||||||
|
}
|
||||||
|
lastErr = err
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nil, ctx.Err()
|
||||||
|
case <-deadline.C:
|
||||||
|
return nil, lastErr
|
||||||
|
case <-ticker.C:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,343 @@
|
|||||||
|
// Package console serializes host-owned QMP console operations per VM.
|
||||||
|
package console
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Nwflower/reims-go/internal/qmp"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Manager arbitrates screen and input operations so concurrent host features
|
||||||
|
// never open competing QMP clients for the same VM.
|
||||||
|
type Manager struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
locks map[string]*vmLock
|
||||||
|
dial func(context.Context, string) (qmpSession, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type vmLock struct {
|
||||||
|
semaphore chan struct{}
|
||||||
|
users int
|
||||||
|
conn qmpSession
|
||||||
|
}
|
||||||
|
|
||||||
|
type qmpSession interface {
|
||||||
|
qmp.Executor
|
||||||
|
qmp.QueryExecutor
|
||||||
|
Screendump(string) (string, error)
|
||||||
|
Close() error
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewManager() *Manager {
|
||||||
|
return &Manager{
|
||||||
|
locks: make(map[string]*vmLock),
|
||||||
|
dial: func(ctx context.Context, vmDir string) (qmpSession, error) {
|
||||||
|
return qmp.Dial(ctx, "unix", qmp.SocketPath(vmDir))
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Forget closes the cached QMP session for a VM. Lifecycle code calls this
|
||||||
|
// before stopping or deleting the VM so QEMU can release its single-client
|
||||||
|
// console socket.
|
||||||
|
func (m *Manager) Forget(ctx context.Context, vmDir string) error {
|
||||||
|
lock, release, err := m.acquire(ctx, vmDir)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer release()
|
||||||
|
if lock.conn != nil {
|
||||||
|
err := lock.conn.Close()
|
||||||
|
lock.conn = nil
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close releases every cached QMP session when the owning plugin is disposed.
|
||||||
|
func (m *Manager) Close() {
|
||||||
|
if m == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
m.mu.Lock()
|
||||||
|
dirs := make([]string, 0, len(m.locks))
|
||||||
|
for dir := range m.locks {
|
||||||
|
dirs = append(dirs, dir)
|
||||||
|
}
|
||||||
|
m.mu.Unlock()
|
||||||
|
for _, dir := range dirs {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||||
|
_ = m.Forget(ctx, dir)
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Screendump writes one PPM frame while holding the VM's console lock.
|
||||||
|
func (m *Manager) Screendump(ctx context.Context, vmDir, path string) (string, error) {
|
||||||
|
var format string
|
||||||
|
err := m.withConn(ctx, vmDir, func(conn qmpSession) error {
|
||||||
|
var err error
|
||||||
|
format, err = conn.Screendump(path)
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
return format, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// TypeText sends US-layout key strokes as one serialized console job.
|
||||||
|
func (m *Manager) TypeText(ctx context.Context, vmDir, text string, progress func(done, total int)) (int, error) {
|
||||||
|
strokes, err := qmp.Strokes(text)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if len(strokes) == 0 {
|
||||||
|
return 0, errors.New("nothing to type")
|
||||||
|
}
|
||||||
|
done := 0
|
||||||
|
err = m.withConn(ctx, vmDir, func(conn qmpSession) error {
|
||||||
|
return qmp.TypeStrokes(ctx, conn, strokes, 20*time.Millisecond, 15*time.Millisecond, func(n int) {
|
||||||
|
done = n
|
||||||
|
if progress != nil {
|
||||||
|
progress(n, len(strokes))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
return done, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// SendPasteShortcut sends Command+V through the same exclusive console path.
|
||||||
|
func (m *Manager) SendPasteShortcut(ctx context.Context, vmDir string) error {
|
||||||
|
return m.withConn(ctx, vmDir, func(conn qmpSession) error {
|
||||||
|
return qmp.PressCombo(ctx, conn, 25*time.Millisecond, "v", "meta_l")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) PointerAvailable(ctx context.Context, vmDir string) (bool, error) {
|
||||||
|
var available bool
|
||||||
|
err := m.withConn(ctx, vmDir, func(conn qmpSession) error {
|
||||||
|
mice, err := qmp.QueryMice(conn)
|
||||||
|
if err == nil {
|
||||||
|
available = qmp.HasCurrentAbsoluteMouse(mice)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
return available, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) MouseMove(ctx context.Context, vmDir string, x, y, width, height int) error {
|
||||||
|
return m.withConn(ctx, vmDir, func(conn qmpSession) error {
|
||||||
|
return qmp.MouseMove(conn, x, y, width, height)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) MouseButton(ctx context.Context, vmDir, button string, down bool) error {
|
||||||
|
return m.withConn(ctx, vmDir, func(conn qmpSession) error {
|
||||||
|
return qmp.MouseButton(conn, button, down)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) MouseClick(ctx context.Context, vmDir, button string) error {
|
||||||
|
return m.withConn(ctx, vmDir, func(conn qmpSession) error {
|
||||||
|
if err := qmp.MouseButton(conn, button, true); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
released := false
|
||||||
|
defer func() {
|
||||||
|
if !released {
|
||||||
|
_ = qmp.MouseButton(conn, button, false)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
timer := time.NewTimer(50 * time.Millisecond)
|
||||||
|
defer timer.Stop()
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
case <-timer.C:
|
||||||
|
}
|
||||||
|
if err := qmp.MouseButton(conn, button, false); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
released = true
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) MouseScroll(ctx context.Context, vmDir string, delta int, horizontal bool) error {
|
||||||
|
return m.withConn(ctx, vmDir, func(conn qmpSession) error {
|
||||||
|
return qmp.MouseScroll(conn, delta, horizontal)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) PressKey(ctx context.Context, vmDir, key string, modifiers ...string) error {
|
||||||
|
key, err := normalizeKeyCode(key)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
normalizedModifiers := make([]string, len(modifiers))
|
||||||
|
for i, modifier := range modifiers {
|
||||||
|
normalizedModifiers[i], err = normalizeModifier(modifier)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return m.withConn(ctx, vmDir, func(conn qmpSession) error {
|
||||||
|
return qmp.PressCombo(ctx, conn, 25*time.Millisecond, key, normalizedModifiers...)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeKeyCode(key string) (string, error) {
|
||||||
|
if key == " " {
|
||||||
|
return "spc", nil
|
||||||
|
}
|
||||||
|
code := strings.ToLower(strings.TrimSpace(key))
|
||||||
|
switch code {
|
||||||
|
case "space":
|
||||||
|
code = "spc"
|
||||||
|
case "escape":
|
||||||
|
code = "esc"
|
||||||
|
case "enter", "return":
|
||||||
|
code = "ret"
|
||||||
|
case "pageup":
|
||||||
|
code = "page_up"
|
||||||
|
case "pagedown":
|
||||||
|
code = "page_down"
|
||||||
|
}
|
||||||
|
if code == "" {
|
||||||
|
return "", errors.New("key is required")
|
||||||
|
}
|
||||||
|
for _, r := range code {
|
||||||
|
if (r < 'a' || r > 'z') && (r < '0' || r > '9') && r != '_' {
|
||||||
|
return "", fmt.Errorf("unsupported key code %q", key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return code, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeModifier(modifier string) (string, error) {
|
||||||
|
code := strings.ToLower(strings.TrimSpace(modifier))
|
||||||
|
switch code {
|
||||||
|
case "cmd", "command", "meta", "super":
|
||||||
|
code = "meta_l"
|
||||||
|
case "ctrl", "control":
|
||||||
|
code = "ctrl"
|
||||||
|
case "option":
|
||||||
|
code = "alt"
|
||||||
|
}
|
||||||
|
switch code {
|
||||||
|
case "shift", "shift_r", "ctrl", "ctrl_r", "alt", "alt_r", "meta_l", "meta_r":
|
||||||
|
return code, nil
|
||||||
|
default:
|
||||||
|
return "", fmt.Errorf("unsupported key modifier %q", modifier)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) withConn(ctx context.Context, vmDir string, operation func(qmpSession) error) error {
|
||||||
|
if operation == nil {
|
||||||
|
return errors.New("console operation is unavailable")
|
||||||
|
}
|
||||||
|
lock, release, err := m.acquire(ctx, vmDir)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer release()
|
||||||
|
if lock.conn == nil {
|
||||||
|
dial := m.dial
|
||||||
|
if dial == nil {
|
||||||
|
dial = func(ctx context.Context, vmDir string) (qmpSession, error) {
|
||||||
|
return qmp.Dial(ctx, "unix", qmp.SocketPath(vmDir))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
conn, err := dial(ctx, vmDir)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
lock.conn = conn
|
||||||
|
}
|
||||||
|
if err := operation(lock.conn); err != nil {
|
||||||
|
_ = lock.conn.Close()
|
||||||
|
lock.conn = nil
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) withVM(ctx context.Context, vmDir string, operation func() error) error {
|
||||||
|
if operation == nil {
|
||||||
|
return errors.New("console operation is unavailable")
|
||||||
|
}
|
||||||
|
_, release, err := m.acquire(ctx, vmDir)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer release()
|
||||||
|
return operation()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) acquire(ctx context.Context, vmDir string) (*vmLock, func(), error) {
|
||||||
|
if m == nil {
|
||||||
|
return nil, nil, errors.New("console manager is unavailable")
|
||||||
|
}
|
||||||
|
if ctx == nil {
|
||||||
|
return nil, nil, errors.New("console context is unavailable")
|
||||||
|
}
|
||||||
|
key, err := lockKey(vmDir)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
m.mu.Lock()
|
||||||
|
if m.locks == nil {
|
||||||
|
m.locks = make(map[string]*vmLock)
|
||||||
|
}
|
||||||
|
lock := m.locks[key]
|
||||||
|
if lock == nil {
|
||||||
|
lock = &vmLock{semaphore: make(chan struct{}, 1)}
|
||||||
|
m.locks[key] = lock
|
||||||
|
}
|
||||||
|
lock.users++
|
||||||
|
m.mu.Unlock()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case lock.semaphore <- struct{}{}:
|
||||||
|
var once sync.Once
|
||||||
|
return lock, func() {
|
||||||
|
once.Do(func() {
|
||||||
|
<-lock.semaphore
|
||||||
|
m.release(key, lock)
|
||||||
|
})
|
||||||
|
}, nil
|
||||||
|
case <-ctx.Done():
|
||||||
|
m.release(key, lock)
|
||||||
|
return nil, nil, ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) release(key string, lock *vmLock) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
lock.users--
|
||||||
|
if lock.users == 0 && lock.conn == nil && m.locks[key] == lock {
|
||||||
|
delete(m.locks, key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func lockKey(vmDir string) (string, error) {
|
||||||
|
if strings.TrimSpace(vmDir) == "" {
|
||||||
|
return "", errors.New("VM directory is unavailable")
|
||||||
|
}
|
||||||
|
abs, err := filepath.Abs(vmDir)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("resolve VM directory: %w", err)
|
||||||
|
}
|
||||||
|
key := filepath.Clean(abs)
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
key = strings.ToLower(key)
|
||||||
|
}
|
||||||
|
return key, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
package console
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type fakeQMPSession struct {
|
||||||
|
closeCount *int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *fakeQMPSession) Execute(string, any) error { return nil }
|
||||||
|
func (s *fakeQMPSession) Query(string, any) (json.RawMessage, error) {
|
||||||
|
return json.RawMessage(`[]`), nil
|
||||||
|
}
|
||||||
|
func (s *fakeQMPSession) Screendump(string) (string, error) { return "ppm", nil }
|
||||||
|
func (s *fakeQMPSession) Close() error {
|
||||||
|
(*s.closeCount)++
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeKeyCodeAndModifiers(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
input string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{input: " Escape ", want: "esc"},
|
||||||
|
{input: "Enter", want: "ret"},
|
||||||
|
{input: "space", want: "spc"},
|
||||||
|
{input: "pageup", want: "page_up"},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
got, err := normalizeKeyCode(tt.input)
|
||||||
|
if err != nil || got != tt.want {
|
||||||
|
t.Fatalf("normalizeKeyCode(%q) = %q, %v, want %q", tt.input, got, err, tt.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got, err := normalizeModifier("command"); err != nil || got != "meta_l" {
|
||||||
|
t.Fatalf("command modifier = %q, %v", got, err)
|
||||||
|
}
|
||||||
|
if _, err := normalizeKeyCode("bad key"); err == nil {
|
||||||
|
t.Fatal("expected invalid qcode characters to be rejected")
|
||||||
|
}
|
||||||
|
if _, err := normalizeModifier("made up"); err == nil {
|
||||||
|
t.Fatal("expected unsupported modifiers to be rejected")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManagerSerializesOperationsPerVM(t *testing.T) {
|
||||||
|
m := NewManager()
|
||||||
|
firstStarted := make(chan struct{})
|
||||||
|
firstRelease := make(chan struct{})
|
||||||
|
secondStarted := make(chan struct{})
|
||||||
|
firstDone := make(chan error, 1)
|
||||||
|
secondDone := make(chan error, 1)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
firstDone <- m.withVM(context.Background(), `C:\vms\one`, func() error {
|
||||||
|
close(firstStarted)
|
||||||
|
<-firstRelease
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}()
|
||||||
|
<-firstStarted
|
||||||
|
go func() {
|
||||||
|
secondDone <- m.withVM(context.Background(), `c:\VMS\ONE`, func() error {
|
||||||
|
close(secondStarted)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-secondStarted:
|
||||||
|
t.Fatal("second operation entered while the first operation held the VM console")
|
||||||
|
case <-time.After(30 * time.Millisecond):
|
||||||
|
}
|
||||||
|
close(firstRelease)
|
||||||
|
select {
|
||||||
|
case <-secondStarted:
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("second operation did not enter after the first released the console")
|
||||||
|
}
|
||||||
|
if err := <-firstDone; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := <-secondDone; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManagerLetsDifferentVMsRunConcurrently(t *testing.T) {
|
||||||
|
m := NewManager()
|
||||||
|
started := make(chan string, 2)
|
||||||
|
blocked := make(chan struct{})
|
||||||
|
done := make(chan error, 2)
|
||||||
|
for _, vmDir := range []string{`C:\vms\one`, `C:\vms\two`} {
|
||||||
|
go func(vmDir string) {
|
||||||
|
done <- m.withVM(context.Background(), vmDir, func() error {
|
||||||
|
started <- vmDir
|
||||||
|
<-blocked
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}(vmDir)
|
||||||
|
}
|
||||||
|
first := <-started
|
||||||
|
second := <-started
|
||||||
|
if first == second {
|
||||||
|
t.Fatalf("both operations used the same VM lock: %q", first)
|
||||||
|
}
|
||||||
|
close(blocked)
|
||||||
|
for range 2 {
|
||||||
|
if err := <-done; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManagerCanceledWaitDoesNotLeakVMLock(t *testing.T) {
|
||||||
|
m := NewManager()
|
||||||
|
locked := make(chan struct{})
|
||||||
|
release := make(chan struct{})
|
||||||
|
done := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
done <- m.withVM(context.Background(), `C:\vms\one`, func() error {
|
||||||
|
close(locked)
|
||||||
|
<-release
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}()
|
||||||
|
<-locked
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
if err := m.withVM(ctx, `C:\vms\one`, func() error { return nil }); err == nil {
|
||||||
|
t.Fatal("expected canceled console wait to fail")
|
||||||
|
}
|
||||||
|
close(release)
|
||||||
|
if err := <-done; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := m.withVM(context.Background(), `C:\vms\one`, func() error { return nil }); err != nil {
|
||||||
|
t.Fatalf("console lock remained blocked: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManagerReusesAndForgetsQMPConnection(t *testing.T) {
|
||||||
|
m := NewManager()
|
||||||
|
dials := 0
|
||||||
|
closes := 0
|
||||||
|
m.dial = func(context.Context, string) (qmpSession, error) {
|
||||||
|
dials++
|
||||||
|
return &fakeQMPSession{closeCount: &closes}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
for range 2 {
|
||||||
|
if err := m.PressKey(context.Background(), `C:\vms\one`, "a"); err != nil {
|
||||||
|
t.Fatalf("PressKey: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if dials != 1 || closes != 0 {
|
||||||
|
t.Fatalf("after repeated operations: dials=%d closes=%d, want 1 and 0", dials, closes)
|
||||||
|
}
|
||||||
|
if err := m.Forget(context.Background(), `C:\vms\one`); err != nil {
|
||||||
|
t.Fatalf("Forget: %v", err)
|
||||||
|
}
|
||||||
|
if closes != 1 {
|
||||||
|
t.Fatalf("Close called %d times, want 1", closes)
|
||||||
|
}
|
||||||
|
if err := m.PressKey(context.Background(), `C:\vms\one`, "b"); err != nil {
|
||||||
|
t.Fatalf("PressKey after Forget: %v", err)
|
||||||
|
}
|
||||||
|
if dials != 2 {
|
||||||
|
t.Fatalf("dial count after Forget = %d, want 2", dials)
|
||||||
|
}
|
||||||
|
m.Close()
|
||||||
|
if closes != 2 {
|
||||||
|
t.Fatalf("Close called %d times after manager Close, want 2", closes)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package control
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
const MaxFrameBytes = 8 << 20
|
||||||
|
|
||||||
|
type Request struct {
|
||||||
|
PluginID string `json:"plugin_id"`
|
||||||
|
Channel string `json:"channel"`
|
||||||
|
Message json.RawMessage `json:"message"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Response struct {
|
||||||
|
Message json.RawMessage `json:"message,omitempty"`
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Handler func(ctx context.Context, pluginID, channel string, message json.RawMessage) (json.RawMessage, error)
|
||||||
|
|
||||||
|
// PipeName gives the desktop process and its CLI clients a deterministic
|
||||||
|
// endpoint scoped to this installation path and Windows user.
|
||||||
|
func PipeName() string {
|
||||||
|
exe, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
exe = "reims-go"
|
||||||
|
}
|
||||||
|
identity := filepath.Clean(exe)
|
||||||
|
sum := sha256.Sum256([]byte(identity))
|
||||||
|
userScope := currentUserScope()
|
||||||
|
return `\\.\pipe\reims-go-control-` + hex.EncodeToString(sum[:8]) + "-" + userScope
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
//go:build !windows
|
||||||
|
|
||||||
|
package control
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Server struct{}
|
||||||
|
|
||||||
|
func currentUserScope() string { return "unsupported" }
|
||||||
|
|
||||||
|
func Listen(Handler) (*Server, error) {
|
||||||
|
return nil, errors.ErrUnsupported
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListenAt(string, Handler) (*Server, error) {
|
||||||
|
return nil, errors.ErrUnsupported
|
||||||
|
}
|
||||||
|
|
||||||
|
func Dial(context.Context) (net.Conn, error) {
|
||||||
|
return nil, errors.ErrUnsupported
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*Server) Close() error { return nil }
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package control
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPipeNameIncludesInstallationAndUserScope(t *testing.T) {
|
||||||
|
name := PipeName()
|
||||||
|
if !strings.HasPrefix(name, `\\.\pipe\reims-go-control-`) {
|
||||||
|
t.Fatalf("unexpected named pipe path %q", name)
|
||||||
|
}
|
||||||
|
if !strings.HasSuffix(name, "-"+currentUserScope()) {
|
||||||
|
t.Fatalf("named pipe is not scoped to the current user: %q", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package control
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/Microsoft/go-winio"
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
func currentUserScope() string {
|
||||||
|
token := windows.GetCurrentProcessToken()
|
||||||
|
user, err := token.GetTokenUser()
|
||||||
|
if err != nil {
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
|
sum := sha256.Sum256([]byte(user.User.Sid.String()))
|
||||||
|
return hex.EncodeToString(sum[:8])
|
||||||
|
}
|
||||||
|
|
||||||
|
type Server struct {
|
||||||
|
listener net.Listener
|
||||||
|
handler Handler
|
||||||
|
cancel context.CancelFunc
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
conns map[net.Conn]struct{}
|
||||||
|
wg sync.WaitGroup
|
||||||
|
}
|
||||||
|
|
||||||
|
func Listen(handler Handler) (*Server, error) {
|
||||||
|
return ListenAt(PipeName(), handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListenAt(pipeName string, handler Handler) (*Server, error) {
|
||||||
|
if handler == nil {
|
||||||
|
return nil, errors.New("control handler is required")
|
||||||
|
}
|
||||||
|
token := windows.GetCurrentProcessToken()
|
||||||
|
user, err := token.GetTokenUser()
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("read current user SID: %w", err)
|
||||||
|
}
|
||||||
|
descriptor := "D:P(A;;GA;;;" + user.User.Sid.String() + ")"
|
||||||
|
listener, err := winio.ListenPipe(pipeName, &winio.PipeConfig{
|
||||||
|
SecurityDescriptor: descriptor,
|
||||||
|
InputBufferSize: 64 * 1024,
|
||||||
|
OutputBufferSize: 64 * 1024,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("listen on the Reims-Go control pipe: %w", err)
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
s := &Server{listener: listener, handler: handler, cancel: cancel, conns: make(map[net.Conn]struct{})}
|
||||||
|
s.wg.Add(1)
|
||||||
|
go s.acceptLoop(ctx)
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func Dial(ctx context.Context) (net.Conn, error) {
|
||||||
|
return winio.DialPipeContext(ctx, PipeName())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) acceptLoop(ctx context.Context) {
|
||||||
|
defer s.wg.Done()
|
||||||
|
for {
|
||||||
|
conn, err := s.listener.Accept()
|
||||||
|
if err != nil {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.mu.Lock()
|
||||||
|
s.conns[conn] = struct{}{}
|
||||||
|
s.wg.Add(1)
|
||||||
|
s.mu.Unlock()
|
||||||
|
go s.serveConn(ctx, conn)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) serveConn(serverCtx context.Context, conn net.Conn) {
|
||||||
|
defer s.wg.Done()
|
||||||
|
defer func() {
|
||||||
|
s.mu.Lock()
|
||||||
|
delete(s.conns, conn)
|
||||||
|
s.mu.Unlock()
|
||||||
|
_ = conn.Close()
|
||||||
|
}()
|
||||||
|
|
||||||
|
scanner := bufio.NewScanner(conn)
|
||||||
|
scanner.Buffer(make([]byte, 64*1024), MaxFrameBytes)
|
||||||
|
writer := bufio.NewWriter(conn)
|
||||||
|
for scanner.Scan() {
|
||||||
|
var req Request
|
||||||
|
if err := json.Unmarshal(scanner.Bytes(), &req); err != nil {
|
||||||
|
if writeErr := writeResponse(writer, Response{Error: "invalid control request"}); writeErr != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if req.PluginID == "" || req.Channel == "" || len(req.Message) == 0 || !json.Valid(req.Message) {
|
||||||
|
if err := writeResponse(writer, Response{Error: "plugin, channel and valid JSON message are required"}); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
result, err := s.handler(serverCtx, req.PluginID, req.Channel, req.Message)
|
||||||
|
response := Response{Message: result}
|
||||||
|
if err != nil {
|
||||||
|
response = Response{Error: err.Error()}
|
||||||
|
}
|
||||||
|
if err := writeResponse(writer, response); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-serverCtx.Done():
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeResponse(writer *bufio.Writer, response Response) error {
|
||||||
|
frame, err := json.Marshal(response)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(frame) > MaxFrameBytes {
|
||||||
|
return errors.New("control response exceeds frame limit")
|
||||||
|
}
|
||||||
|
if _, err := writer.Write(frame); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := writer.WriteByte('\n'); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return writer.Flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) Close() error {
|
||||||
|
if s == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
s.cancel()
|
||||||
|
listenerErr := s.listener.Close()
|
||||||
|
s.mu.Lock()
|
||||||
|
for conn := range s.conns {
|
||||||
|
_ = conn.Close()
|
||||||
|
}
|
||||||
|
s.mu.Unlock()
|
||||||
|
s.wg.Wait()
|
||||||
|
return listenerErr
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package control
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Microsoft/go-winio"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestNamedPipeForwardsDeclaredPluginMessage(t *testing.T) {
|
||||||
|
pipeName := fmt.Sprintf(`\\.\pipe\reims-go-control-test-%d`, time.Now().UnixNano())
|
||||||
|
server, err := ListenAt(pipeName, func(_ context.Context, pluginID, channel string, message json.RawMessage) (json.RawMessage, error) {
|
||||||
|
if pluginID != "test.agent" || channel != "mcp" {
|
||||||
|
t.Fatalf("unexpected channel target %s/%s", pluginID, channel)
|
||||||
|
}
|
||||||
|
return message, nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = server.Close() })
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
conn, err := winio.DialPipeContext(ctx, pipeName)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
if _, err := fmt.Fprintln(conn, `{"plugin_id":"test.agent","channel":"mcp","message":{"jsonrpc":"2.0","id":1,"method":"ping"}}`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
response, err := bufio.NewReader(conn).ReadBytes('\n')
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var result Response
|
||||||
|
if err := json.Unmarshal(response, &result); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if string(result.Message) != `{"jsonrpc":"2.0","id":1,"method":"ping"}` || result.Error != "" {
|
||||||
|
t.Fatalf("unexpected host response: %+v", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -30,12 +30,14 @@ const (
|
|||||||
IDGuestTools = "builtin.bridge.guest-tools"
|
IDGuestTools = "builtin.bridge.guest-tools"
|
||||||
IDClipboard = "builtin.bridge.clipboard"
|
IDClipboard = "builtin.bridge.clipboard"
|
||||||
IDInput = "builtin.input"
|
IDInput = "builtin.input"
|
||||||
|
IDComputerUse = "builtin.computer-use"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Service names provided by builtin extensions.
|
// Service names provided by builtin extensions.
|
||||||
const (
|
const (
|
||||||
ServiceGuestToolsTransport = "guest-tools.transport"
|
ServiceGuestToolsTransport = "guest-tools.transport"
|
||||||
ServiceHostInput = "host.input"
|
ServiceHostInput = "host.input"
|
||||||
|
ServiceComputerUse = "computer-use.console"
|
||||||
)
|
)
|
||||||
|
|
||||||
// HostCallbacks connects builtin extensions to host runtime services without
|
// HostCallbacks connects builtin extensions to host runtime services without
|
||||||
@@ -86,6 +88,7 @@ func RegisterAll(reg *plugin.Registry, cb HostCallbacks, desiredFn func(id strin
|
|||||||
defGuestTools(ver, cb, desiredFn),
|
defGuestTools(ver, cb, desiredFn),
|
||||||
defClipboard(ver, cb, desiredFn),
|
defClipboard(ver, cb, desiredFn),
|
||||||
defInput(ver, cb, desiredFn),
|
defInput(ver, cb, desiredFn),
|
||||||
|
defComputerUse(ver, desiredFn),
|
||||||
defDownloaderParallel(ver, cb, desiredFn),
|
defDownloaderParallel(ver, cb, desiredFn),
|
||||||
}
|
}
|
||||||
for _, d := range defs {
|
for _, d := range defs {
|
||||||
|
|||||||
@@ -85,6 +85,34 @@ func TestInputServiceTypeCheck(t *testing.T) {
|
|||||||
_ = host.NewInputService(nil)
|
_ = host.NewInputService(nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestComputerUseIsAnOptionalBuiltinService(t *testing.T) {
|
||||||
|
reg := plugin.NewRegistry(nil)
|
||||||
|
if err := RegisterAll(reg, HostCallbacks{}, nil); err != nil {
|
||||||
|
t.Fatalf("RegisterAll: %v", err)
|
||||||
|
}
|
||||||
|
reg.Reconcile(context.Background())
|
||||||
|
|
||||||
|
info, ok := reg.Info(IDComputerUse)
|
||||||
|
if !ok || info.Name.Get("zh-CN") != "虚拟机交互" || !reg.IsActive(IDComputerUse) {
|
||||||
|
t.Fatalf("computer-use plugin info=%+v active=%t", info, reg.IsActive(IDComputerUse))
|
||||||
|
}
|
||||||
|
if _, ok := reg.LookupService(ServiceComputerUse); !ok {
|
||||||
|
t.Fatal("expected the built-in computer-use service to be provided")
|
||||||
|
}
|
||||||
|
if err := reg.SetDesired(context.Background(), IDComputerUse, false); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, ok := reg.LookupService(ServiceComputerUse); ok {
|
||||||
|
t.Fatal("expected the computer-use service to be removed when disabled")
|
||||||
|
}
|
||||||
|
if err := reg.SetDesired(context.Background(), IDComputerUse, true); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, ok := reg.LookupService(ServiceComputerUse); !ok {
|
||||||
|
t.Fatal("expected the computer-use service to return after re-enable")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestGuestToolsInputBridgeEnvGating(t *testing.T) {
|
func TestGuestToolsInputBridgeEnvGating(t *testing.T) {
|
||||||
reg := plugin.NewRegistry(nil)
|
reg := plugin.NewRegistry(nil)
|
||||||
gtSrv := guesttools.NewTransportServer(nil)
|
gtSrv := guesttools.NewTransportServer(nil)
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package builtin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"github.com/Nwflower/reims-go/internal/console"
|
||||||
|
"github.com/Nwflower/reims-go/internal/plugin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ComputerUseService is the host-owned console surface exposed to in-process
|
||||||
|
// features and permission-checked Sidecar Host API handlers.
|
||||||
|
type ComputerUseService interface {
|
||||||
|
Screendump(ctx context.Context, vmDir, path string) (string, error)
|
||||||
|
TypeText(ctx context.Context, vmDir, text string, progress func(done, total int)) (int, error)
|
||||||
|
Forget(ctx context.Context, vmDir string) error
|
||||||
|
Close()
|
||||||
|
SendPasteShortcut(ctx context.Context, vmDir string) error
|
||||||
|
PointerAvailable(ctx context.Context, vmDir string) (bool, error)
|
||||||
|
MouseMove(ctx context.Context, vmDir string, x, y, width, height int) error
|
||||||
|
MouseButton(ctx context.Context, vmDir, button string, down bool) error
|
||||||
|
MouseClick(ctx context.Context, vmDir, button string) error
|
||||||
|
MouseScroll(ctx context.Context, vmDir string, delta int, horizontal bool) error
|
||||||
|
PressKey(ctx context.Context, vmDir, key string, modifiers ...string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
func defComputerUse(ver string, desiredFn func(string, bool) bool) plugin.PluginDef {
|
||||||
|
return plugin.PluginDef{
|
||||||
|
Manifest: plugin.Manifest{
|
||||||
|
Schema: 1,
|
||||||
|
ID: IDComputerUse,
|
||||||
|
Version: ver,
|
||||||
|
Name: plugin.LocalizedText{ZhCN: "虚拟机交互", EnUS: "Computer Use"},
|
||||||
|
Description: plugin.LocalizedText{
|
||||||
|
ZhCN: "通过宿主控制台串行访问虚拟机屏幕、鼠标和键盘",
|
||||||
|
EnUS: "Serializes host console access to VM screens, pointers, and keyboards",
|
||||||
|
},
|
||||||
|
Publisher: "Reims-Go",
|
||||||
|
License: "Apache-2.0",
|
||||||
|
Provides: []plugin.ServiceProvision{{Service: ServiceComputerUse, Version: "1.0.0"}},
|
||||||
|
Permissions: []string{"vm:screen", "qmp:write"},
|
||||||
|
DefaultEnabled: true,
|
||||||
|
},
|
||||||
|
Source: plugin.SourceBuiltin,
|
||||||
|
Trust: plugin.TrustOfficial,
|
||||||
|
Desired: desiredFn(IDComputerUse, true),
|
||||||
|
Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||||
|
manager := console.NewManager()
|
||||||
|
sc.Provide(ServiceComputerUse, "1.0.0", manager)
|
||||||
|
sc.OnDispose(manager.Close)
|
||||||
|
for _, event := range []string{plugin.EventVMBeforeStop, plugin.EventVMDeleted} {
|
||||||
|
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
|
||||||
|
Event: event,
|
||||||
|
Builtin: true,
|
||||||
|
Handler: func(ctx context.Context, raw any) (any, error) {
|
||||||
|
payload, ok := raw.(plugin.VMEventPayload)
|
||||||
|
if !ok || payload.VMDir == "" {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return nil, manager.Forget(ctx, payload.VMDir)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package plugin
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestManifestValidatesChannels(t *testing.T) {
|
||||||
|
base := Manifest{
|
||||||
|
ID: "vendor.agent",
|
||||||
|
Version: "1.0.0",
|
||||||
|
Name: LocalizedText{EnUS: "Agent"},
|
||||||
|
Entry: Entry{Sidecar: "bin/agent.exe"},
|
||||||
|
Contributes: Contributes{Channels: []ChannelContribution{
|
||||||
|
{ID: "mcp", Framing: "jsonl"},
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
if err := ValidateManifest(base, "dev", false); err != nil {
|
||||||
|
t.Fatalf("valid JSONL channel rejected: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
channels []ChannelContribution
|
||||||
|
sidecar string
|
||||||
|
}{
|
||||||
|
{name: "unknown framing", channels: []ChannelContribution{{ID: "mcp", Framing: "raw"}}, sidecar: "bin/agent.exe"},
|
||||||
|
{name: "duplicate id", channels: []ChannelContribution{{ID: "mcp", Framing: "jsonl"}, {ID: "mcp", Framing: "jsonl"}}, sidecar: "bin/agent.exe"},
|
||||||
|
{name: "invalid id", channels: []ChannelContribution{{ID: "MCP", Framing: "jsonl"}}, sidecar: "bin/agent.exe"},
|
||||||
|
{name: "missing sidecar", channels: []ChannelContribution{{ID: "mcp", Framing: "jsonl"}}},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
m := base
|
||||||
|
m.Entry.Sidecar = tc.sidecar
|
||||||
|
m.Contributes.Channels = tc.channels
|
||||||
|
if err := ValidateManifest(m, "dev", false); err == nil {
|
||||||
|
t.Fatal("invalid channel declaration accepted")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -32,6 +32,7 @@ const (
|
|||||||
// ContributionCatalog lists every `contributes` key (its JSON name).
|
// ContributionCatalog lists every `contributes` key (its JSON name).
|
||||||
var ContributionCatalog = map[string]ContractStatus{
|
var ContributionCatalog = map[string]ContractStatus{
|
||||||
"themes": ContractStable,
|
"themes": ContractStable,
|
||||||
|
"channels": ContractStable,
|
||||||
"uiScripts": ContractExperimental, // theme.uiScript is the implemented path
|
"uiScripts": ContractExperimental, // theme.uiScript is the implemented path
|
||||||
"locales": ContractStable,
|
"locales": ContractStable,
|
||||||
"inputFilters": ContractStable,
|
"inputFilters": ContractStable,
|
||||||
@@ -263,6 +264,23 @@ var reContributionID = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]*$`)
|
|||||||
// catalogs: unknown slots, locations, layout values or icon names are errors;
|
// catalogs: unknown slots, locations, layout values or icon names are errors;
|
||||||
// experimental ones are accepted and reported by ContractFindings.
|
// experimental ones are accepted and reported by ContractFindings.
|
||||||
func validateUIContract(m Manifest) error {
|
func validateUIContract(m Manifest) error {
|
||||||
|
channelIDs := make(map[string]bool, len(m.Contributes.Channels))
|
||||||
|
for _, channel := range m.Contributes.Channels {
|
||||||
|
if channel.ID != strings.TrimSpace(channel.ID) || !reContributionID.MatchString(channel.ID) {
|
||||||
|
return fmt.Errorf("invalid channel id %q", channel.ID)
|
||||||
|
}
|
||||||
|
if channelIDs[channel.ID] {
|
||||||
|
return fmt.Errorf("duplicate channel id %q", channel.ID)
|
||||||
|
}
|
||||||
|
channelIDs[channel.ID] = true
|
||||||
|
if channel.Framing != "jsonl" {
|
||||||
|
return fmt.Errorf("channel %q uses unsupported framing %q", channel.ID, channel.Framing)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(channelIDs) > 0 && strings.TrimSpace(m.Entry.Sidecar) == "" {
|
||||||
|
return fmt.Errorf("plugin channels require a Sidecar entry")
|
||||||
|
}
|
||||||
|
|
||||||
checkSlot := func(what, id, slot, kind string) error {
|
checkSlot := func(what, id, slot, kind string) error {
|
||||||
spec, ok := UISlotCatalog[slot]
|
spec, ok := UISlotCatalog[slot]
|
||||||
if !ok {
|
if !ok {
|
||||||
|
|||||||
+130
-14
@@ -20,6 +20,9 @@ import (
|
|||||||
// and supervisor without importing internal/driver into internal/plugin.
|
// and supervisor without importing internal/driver into internal/plugin.
|
||||||
type SidecarDriverFactory func(contrib GuestDriverContribution, sup *SidecarSupervisor) any
|
type SidecarDriverFactory func(contrib GuestDriverContribution, sup *SidecarSupervisor) any
|
||||||
|
|
||||||
|
// HostHandlerFactory adds host-owned RPC handlers to each Sidecar.
|
||||||
|
type HostHandlerFactory func(pluginID string) map[string]RPCRequestHandler
|
||||||
|
|
||||||
// ManagerOptions configures the high-level Plugin Manager.
|
// ManagerOptions configures the high-level Plugin Manager.
|
||||||
type ManagerOptions struct {
|
type ManagerOptions struct {
|
||||||
DataRoot string
|
DataRoot string
|
||||||
@@ -30,6 +33,7 @@ type ManagerOptions struct {
|
|||||||
Logger func(source, line string)
|
Logger func(source, line string)
|
||||||
LocaleFn func() i18n.Locale
|
LocaleFn func() i18n.Locale
|
||||||
SidecarDriverFactory SidecarDriverFactory
|
SidecarDriverFactory SidecarDriverFactory
|
||||||
|
HostHandlers HostHandlerFactory
|
||||||
OnSettingsChanged func(pluginID, vmName string)
|
OnSettingsChanged func(pluginID, vmName string)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,12 +53,12 @@ type ActiveThemePayload struct {
|
|||||||
// Manager coordinates Registry, StateStore, package installation, safe mode,
|
// Manager coordinates Registry, StateStore, package installation, safe mode,
|
||||||
// settings, themes, AssetServer, Broker, and L3 Sidecar supervisors.
|
// settings, themes, AssetServer, Broker, and L3 Sidecar supervisors.
|
||||||
type Manager struct {
|
type Manager struct {
|
||||||
opts ManagerOptions
|
opts ManagerOptions
|
||||||
layout PluginsLayout
|
layout PluginsLayout
|
||||||
store *StateStore
|
store *StateStore
|
||||||
registry *Registry
|
registry *Registry
|
||||||
broker *Broker
|
broker *Broker
|
||||||
assets *AssetServer
|
assets *AssetServer
|
||||||
|
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
state *StateFile
|
state *StateFile
|
||||||
@@ -115,12 +119,61 @@ func NewManager(opts ManagerOptions) (*Manager, error) {
|
|||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Manager) Registry() *Registry { return m.registry }
|
func (m *Manager) Registry() *Registry { return m.registry }
|
||||||
func (m *Manager) Broker() *Broker { return m.broker }
|
func (m *Manager) Broker() *Broker { return m.broker }
|
||||||
func (m *Manager) Assets() *AssetServer { return m.assets }
|
func (m *Manager) Assets() *AssetServer { return m.assets }
|
||||||
func (m *Manager) Layout() PluginsLayout { return m.layout }
|
func (m *Manager) Layout() PluginsLayout { return m.layout }
|
||||||
func (m *Manager) SafeMode() bool { return m.safeMode }
|
func (m *Manager) SafeMode() bool { return m.safeMode }
|
||||||
func (m *Manager) CrashDetected() bool { return m.crashDetected }
|
func (m *Manager) CrashDetected() bool { return m.crashDetected }
|
||||||
|
|
||||||
|
// ChannelMessage forwards one JSON line to a declared, active Sidecar channel.
|
||||||
|
// Channel payloads are never written to the host audit log.
|
||||||
|
func (m *Manager) ChannelMessage(ctx context.Context, pluginID, channelID string, message json.RawMessage) (json.RawMessage, error) {
|
||||||
|
if m == nil || m.registry == nil {
|
||||||
|
return nil, errors.New("plugin manager is unavailable")
|
||||||
|
}
|
||||||
|
if len(message) == 0 || len(message) > maxRPCFrameBytes || !json.Valid(message) {
|
||||||
|
return nil, errors.New("channel message must be valid JSON within the frame limit")
|
||||||
|
}
|
||||||
|
manifest, ok := m.registry.ManifestOf(pluginID)
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("plugin %q is not installed", pluginID)
|
||||||
|
}
|
||||||
|
declared := false
|
||||||
|
for _, channel := range manifest.Contributes.Channels {
|
||||||
|
if channel.ID == channelID && channel.Framing == "jsonl" {
|
||||||
|
declared = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !declared {
|
||||||
|
return nil, fmt.Errorf("plugin %q does not declare JSONL channel %q", pluginID, channelID)
|
||||||
|
}
|
||||||
|
if !m.registry.IsActive(pluginID) {
|
||||||
|
return nil, fmt.Errorf("plugin %q is not enabled", pluginID)
|
||||||
|
}
|
||||||
|
if ctx == nil {
|
||||||
|
ctx = context.Background()
|
||||||
|
}
|
||||||
|
m.mu.RLock()
|
||||||
|
supervisor := m.supervisors[pluginID]
|
||||||
|
m.mu.RUnlock()
|
||||||
|
if supervisor == nil {
|
||||||
|
return nil, fmt.Errorf("plugin %q channel is unavailable", pluginID)
|
||||||
|
}
|
||||||
|
var response struct {
|
||||||
|
Message json.RawMessage `json:"message"`
|
||||||
|
}
|
||||||
|
err := supervisor.Call(ctx, "channel/"+channelID+"/message", map[string]json.RawMessage{"message": message}, &response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(response.Message) > maxRPCFrameBytes || (len(response.Message) > 0 && string(response.Message) != "null" && !json.Valid(response.Message)) {
|
||||||
|
return nil, errors.New("Sidecar returned an invalid channel message")
|
||||||
|
}
|
||||||
|
m.broker.Audit(pluginID, "CHANNEL_MESSAGE", channelID)
|
||||||
|
return response.Message, nil
|
||||||
|
}
|
||||||
|
|
||||||
// DesiredFor returns whether pluginID should be enabled according to state.json,
|
// DesiredFor returns whether pluginID should be enabled according to state.json,
|
||||||
// falling back to defaultEnabled if no saved record exists.
|
// falling back to defaultEnabled if no saved record exists.
|
||||||
@@ -329,6 +382,17 @@ func (m *Manager) buildSidecarActivator(man Manifest, exePath string, blockingAl
|
|||||||
"host/downloader.progress": dlHub.handleRPC,
|
"host/downloader.progress": dlHub.handleRPC,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if m.opts.HostHandlers != nil {
|
||||||
|
if extraHandlers == nil {
|
||||||
|
extraHandlers = make(map[string]RPCRequestHandler)
|
||||||
|
}
|
||||||
|
for method, handler := range m.opts.HostHandlers(pid) {
|
||||||
|
if _, exists := extraHandlers[method]; exists {
|
||||||
|
return fmt.Errorf("Sidecar Host API method %q is already registered", method)
|
||||||
|
}
|
||||||
|
extraHandlers[method] = handler
|
||||||
|
}
|
||||||
|
}
|
||||||
sup := NewSidecarSupervisor(SidecarOptions{
|
sup := NewSidecarSupervisor(SidecarOptions{
|
||||||
PluginID: pid,
|
PluginID: pid,
|
||||||
ExePath: exePath,
|
ExePath: exePath,
|
||||||
@@ -887,6 +951,27 @@ func (m *Manager) GetSettings(pluginID, vmName string, maskSecrets bool) map[str
|
|||||||
|
|
||||||
func (m *Manager) SetSettings(pluginID, vmName string, values map[string]any) error {
|
func (m *Manager) SetSettings(pluginID, vmName string, values map[string]any) error {
|
||||||
info, hasInfo := m.registry.Info(pluginID)
|
info, hasInfo := m.registry.Info(pluginID)
|
||||||
|
prepared := make(map[string]any, len(values))
|
||||||
|
for key, value := range values {
|
||||||
|
if hasInfo && info.Settings != nil {
|
||||||
|
if property, ok := info.Settings.Properties[key]; ok && property.Secret {
|
||||||
|
if value == "••••••••" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
text, ok := value.(string)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("secret setting %q must be a string", key)
|
||||||
|
}
|
||||||
|
protected, err := protectSettingSecret(text)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("protect secret setting %q: %w", key, err)
|
||||||
|
}
|
||||||
|
prepared[key] = protected
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
prepared[key] = value
|
||||||
|
}
|
||||||
m.mu.Lock()
|
m.mu.Lock()
|
||||||
if m.state == nil {
|
if m.state == nil {
|
||||||
m.mu.Unlock()
|
m.mu.Unlock()
|
||||||
@@ -917,7 +1002,7 @@ func (m *Manager) SetSettings(pluginID, vmName string, values map[string]any) er
|
|||||||
if rec.AppSettings == nil {
|
if rec.AppSettings == nil {
|
||||||
rec.AppSettings = map[string]any{}
|
rec.AppSettings = map[string]any{}
|
||||||
}
|
}
|
||||||
for k, v := range values {
|
for k, v := range prepared {
|
||||||
if isSecretMask(k, v) {
|
if isSecretMask(k, v) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -930,7 +1015,7 @@ func (m *Manager) SetSettings(pluginID, vmName string, values map[string]any) er
|
|||||||
if rec.VMSettings[vmName] == nil {
|
if rec.VMSettings[vmName] == nil {
|
||||||
rec.VMSettings[vmName] = map[string]any{}
|
rec.VMSettings[vmName] = map[string]any{}
|
||||||
}
|
}
|
||||||
for k, v := range values {
|
for k, v := range prepared {
|
||||||
if isSecretMask(k, v) {
|
if isSecretMask(k, v) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -947,6 +1032,37 @@ func (m *Manager) SetSettings(pluginID, vmName string, values map[string]any) er
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SecretSetting decrypts a DPAPI-protected setting only for host-owned use.
|
||||||
|
// The caller must never return the plaintext to a plugin or frontend.
|
||||||
|
func (m *Manager) SecretSetting(pluginID, vmName, key string) (string, error) {
|
||||||
|
info, ok := m.registry.Info(pluginID)
|
||||||
|
if !ok || info.Settings == nil {
|
||||||
|
return "", fmt.Errorf("plugin %q has no settings schema", pluginID)
|
||||||
|
}
|
||||||
|
property, ok := info.Settings.Properties[key]
|
||||||
|
if !ok || !property.Secret {
|
||||||
|
return "", fmt.Errorf("setting %q is not a secret", key)
|
||||||
|
}
|
||||||
|
m.mu.RLock()
|
||||||
|
defer m.mu.RUnlock()
|
||||||
|
if m.state == nil {
|
||||||
|
return "", m.stateNotLoadedErr()
|
||||||
|
}
|
||||||
|
values := map[string]any(nil)
|
||||||
|
if record := m.state.Plugins[pluginID]; record != nil {
|
||||||
|
if vmName == "" {
|
||||||
|
values = record.AppSettings
|
||||||
|
} else {
|
||||||
|
values = record.VMSettings[vmName]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
text, _ := values[key].(string)
|
||||||
|
if text == "" {
|
||||||
|
return "", errors.New("secret setting is empty")
|
||||||
|
}
|
||||||
|
return unprotectSettingSecret(text)
|
||||||
|
}
|
||||||
|
|
||||||
// SavedVMSettingsForPlugin returns a copy of all saved per-VM setting maps for pluginID.
|
// SavedVMSettingsForPlugin returns a copy of all saved per-VM setting maps for pluginID.
|
||||||
func (m *Manager) SavedVMSettingsForPlugin(pluginID string) map[string]map[string]any {
|
func (m *Manager) SavedVMSettingsForPlugin(pluginID string) map[string]map[string]any {
|
||||||
m.mu.RLock()
|
m.mu.RLock()
|
||||||
|
|||||||
@@ -97,7 +97,7 @@ func addPermissionRisks(set map[string]bool, perm string) {
|
|||||||
set[RiskNetwork] = true
|
set[RiskNetwork] = true
|
||||||
case "fs:vm_dir", "fs:shared":
|
case "fs:vm_dir", "fs:shared":
|
||||||
set[RiskFiles] = true
|
set[RiskFiles] = true
|
||||||
case "vm:control", "qmp:write", "driver:vm", "runtime:provider", "process:spawn", "vm:intent":
|
case "vm:control", "vm:screen", "qmp:write", "driver:vm", "runtime:provider", "process:spawn", "vm:intent":
|
||||||
set[RiskVM] = true
|
set[RiskVM] = true
|
||||||
case "host:clipboard":
|
case "host:clipboard":
|
||||||
set[RiskClipboard] = true
|
set[RiskClipboard] = true
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ func TestManifestRisks(t *testing.T) {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"permissions map to categories in severity order",
|
"permissions map to categories in severity order",
|
||||||
plugin.Manifest{Permissions: []string{"ui:slot", "input:filter", "net:api.example.com", "fs:shared", "vm:control"}},
|
plugin.Manifest{Permissions: []string{"ui:slot", "input:filter", "net:api.example.com", "fs:shared", "vm:control", "vm:screen"}},
|
||||||
plugin.TierL1,
|
plugin.TierL1,
|
||||||
[]string{plugin.RiskNetwork, plugin.RiskFiles, plugin.RiskVM, plugin.RiskInput, plugin.RiskUI},
|
[]string{plugin.RiskNetwork, plugin.RiskFiles, plugin.RiskVM, plugin.RiskInput, plugin.RiskUI},
|
||||||
},
|
},
|
||||||
@@ -58,6 +58,16 @@ func TestMarketEntryRisks(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestScreenPermissionIsHighRisk(t *testing.T) {
|
||||||
|
if got := plugin.ClassifyPermission("vm:screen"); got != plugin.PermHigh {
|
||||||
|
t.Fatalf("vm:screen level = %q, want %q", got, plugin.PermHigh)
|
||||||
|
}
|
||||||
|
got := plugin.MarketEntryRisks(plugin.MarketEntry{Kind: "tool", Tier: plugin.TierL3, Permissions: []string{"vm:screen"}})
|
||||||
|
if !reflect.DeepEqual(got, []string{plugin.RiskNative, plugin.RiskBackground, plugin.RiskNetwork, plugin.RiskFiles, plugin.RiskVM}) {
|
||||||
|
t.Fatalf("market risks = %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestMarketKindFacetsAndPeek(t *testing.T) {
|
func TestMarketKindFacetsAndPeek(t *testing.T) {
|
||||||
var hits atomic.Int32
|
var hits atomic.Int32
|
||||||
entry := func(id, kind string) plugin.MarketEntry {
|
entry := func(id, kind string) plugin.MarketEntry {
|
||||||
|
|||||||
@@ -869,6 +869,9 @@ func describePermission(perm string) (LocalizedText, LocalizedText) {
|
|||||||
case "vm:control":
|
case "vm:control":
|
||||||
return LocalizedText{ZhCN: "控制虚拟机启停", EnUS: "Control VM power state"},
|
return LocalizedText{ZhCN: "控制虚拟机启停", EnUS: "Control VM power state"},
|
||||||
LocalizedText{ZhCN: "可以启动、停止或重启你的虚拟机。", EnUS: "Can start, stop, or reboot your virtual machines."}
|
LocalizedText{ZhCN: "可以启动、停止或重启你的虚拟机。", EnUS: "Can start, stop, or reboot your virtual machines."}
|
||||||
|
case "vm:screen":
|
||||||
|
return LocalizedText{ZhCN: "读取虚拟机屏幕", EnUS: "Read VM screen"},
|
||||||
|
LocalizedText{ZhCN: "可截取运行中虚拟机的屏幕内容。", EnUS: "Can capture the screen of a running virtual machine."}
|
||||||
case "qmp:write":
|
case "qmp:write":
|
||||||
return LocalizedText{ZhCN: "向 QEMU 发送写命令", EnUS: "Send QEMU QMP write commands"},
|
return LocalizedText{ZhCN: "向 QEMU 发送写命令", EnUS: "Send QEMU QMP write commands"},
|
||||||
LocalizedText{ZhCN: "可向运行中的 QEMU 虚拟机发送控制指令。", EnUS: "Can send mutating control commands to running QEMU VMs."}
|
LocalizedText{ZhCN: "可向运行中的 QEMU 虚拟机发送控制指令。", EnUS: "Can send mutating control commands to running QEMU VMs."}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package plugin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
const protectedSecretPrefix = "dpapi:v1:"
|
||||||
|
|
||||||
|
var ErrSecretNotProtected = errors.New("stored secret is not protected")
|
||||||
|
|
||||||
|
func protectSettingSecret(value string) (string, error) {
|
||||||
|
if value == "" || strings.HasPrefix(value, protectedSecretPrefix) {
|
||||||
|
return value, nil
|
||||||
|
}
|
||||||
|
protected, err := protectSecretBytes([]byte(value))
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return protectedSecretPrefix + base64.StdEncoding.EncodeToString(protected), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func unprotectSettingSecret(value string) (string, error) {
|
||||||
|
if !strings.HasPrefix(value, protectedSecretPrefix) {
|
||||||
|
return "", ErrSecretNotProtected
|
||||||
|
}
|
||||||
|
encoded := strings.TrimPrefix(value, protectedSecretPrefix)
|
||||||
|
protected, err := base64.StdEncoding.DecodeString(encoded)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
plain, err := unprotectSecretBytes(protected)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return string(plain), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
//go:build !windows
|
||||||
|
|
||||||
|
package plugin
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
|
func protectSecretBytes([]byte) ([]byte, error) {
|
||||||
|
return nil, errors.New("secret settings require Windows DPAPI")
|
||||||
|
}
|
||||||
|
|
||||||
|
func unprotectSecretBytes([]byte) ([]byte, error) {
|
||||||
|
return nil, errors.New("secret settings require Windows DPAPI")
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package plugin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
func protectSecretBytes(plain []byte) ([]byte, error) {
|
||||||
|
input := windows.DataBlob{Size: uint32(len(plain))}
|
||||||
|
if len(plain) > 0 {
|
||||||
|
input.Data = &plain[0]
|
||||||
|
}
|
||||||
|
var output windows.DataBlob
|
||||||
|
if err := windows.CryptProtectData(&input, nil, nil, 0, nil, windows.CRYPTPROTECT_UI_FORBIDDEN, &output); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer windows.LocalFree(windows.Handle(unsafe.Pointer(output.Data)))
|
||||||
|
if output.Size == 0 || output.Data == nil {
|
||||||
|
return nil, errors.New("DPAPI returned an empty protected value")
|
||||||
|
}
|
||||||
|
return append([]byte(nil), unsafe.Slice(output.Data, output.Size)...), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func unprotectSecretBytes(ciphertext []byte) ([]byte, error) {
|
||||||
|
input := windows.DataBlob{Size: uint32(len(ciphertext))}
|
||||||
|
if len(ciphertext) > 0 {
|
||||||
|
input.Data = &ciphertext[0]
|
||||||
|
}
|
||||||
|
var output windows.DataBlob
|
||||||
|
if err := windows.CryptUnprotectData(&input, nil, nil, 0, nil, windows.CRYPTPROTECT_UI_FORBIDDEN, &output); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer windows.LocalFree(windows.Handle(unsafe.Pointer(output.Data)))
|
||||||
|
if output.Size == 0 || output.Data == nil {
|
||||||
|
return nil, errors.New("DPAPI returned an empty plaintext value")
|
||||||
|
}
|
||||||
|
return append([]byte(nil), unsafe.Slice(output.Data, output.Size)...), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package plugin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSecretSettingsAreProtectedAtRest(t *testing.T) {
|
||||||
|
dataRoot := t.TempDir()
|
||||||
|
mgr, err := NewManager(ManagerOptions{DataRoot: dataRoot, HostVersion: "dev"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer mgr.Close()
|
||||||
|
|
||||||
|
const pluginID = "test.secret.settings"
|
||||||
|
if err := mgr.Registry().Register(PluginDef{
|
||||||
|
Manifest: Manifest{
|
||||||
|
ID: pluginID,
|
||||||
|
Version: "1.0.0",
|
||||||
|
Name: LocalizedText{EnUS: "Secret settings test"},
|
||||||
|
Settings: &SettingsSchema{Properties: map[string]SettingProperty{
|
||||||
|
"password": {Type: "string", Secret: true},
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
Source: SourceBuiltin,
|
||||||
|
Desired: true,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
mgr.Registry().Reconcile(context.Background())
|
||||||
|
|
||||||
|
const vmKey = "builtin.driver.reims-macos:fixture"
|
||||||
|
const password = "windows-dpapi-fixture"
|
||||||
|
if err := mgr.SetSettings(pluginID, vmKey, map[string]any{"password": password}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
masked := mgr.GetSettings(pluginID, vmKey, true)["password"]
|
||||||
|
if masked != "••••••••" {
|
||||||
|
t.Fatalf("masked password = %v", masked)
|
||||||
|
}
|
||||||
|
stored := mgr.GetSettings(pluginID, vmKey, false)["password"].(string)
|
||||||
|
if strings.Contains(stored, password) || !strings.HasPrefix(stored, protectedSecretPrefix) {
|
||||||
|
t.Fatalf("stored secret was not encrypted: %q", stored)
|
||||||
|
}
|
||||||
|
plain, err := mgr.SecretSetting(pluginID, vmKey, "password")
|
||||||
|
if err != nil || plain != password {
|
||||||
|
t.Fatalf("SecretSetting = %q, %v", plain, err)
|
||||||
|
}
|
||||||
|
stateBytes, err := os.ReadFile(filepath.Join(NewPluginsLayout(dataRoot).Root, StateFileName))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if strings.Contains(string(stateBytes), password) {
|
||||||
|
t.Fatal("settings state contains plaintext secret")
|
||||||
|
}
|
||||||
|
}
|
||||||
+83
-74
@@ -15,7 +15,7 @@ import (
|
|||||||
|
|
||||||
const (
|
const (
|
||||||
// PluginAPIVersion is the host plugin API contract version (SemVer).
|
// PluginAPIVersion is the host plugin API contract version (SemVer).
|
||||||
PluginAPIVersion = "1.0.0"
|
PluginAPIVersion = "1.1.0"
|
||||||
// UIAPIVersion is the frontend UI contract version (SemVer); the contract
|
// UIAPIVersion is the frontend UI contract version (SemVer); the contract
|
||||||
// itself lives in frontend/src/styles/ui-contract.ts (§5.1, §6.3).
|
// itself lives in frontend/src/styles/ui-contract.ts (§5.1, §6.3).
|
||||||
UIAPIVersion = "2.0.0"
|
UIAPIVersion = "2.0.0"
|
||||||
@@ -304,6 +304,7 @@ func (m Manifest) InferTier(isBuiltin bool) Tier {
|
|||||||
// Contributes enumerates all extension-point declarations in plugin.json (§4.2).
|
// Contributes enumerates all extension-point declarations in plugin.json (§4.2).
|
||||||
type Contributes struct {
|
type Contributes struct {
|
||||||
Themes []ThemeContribution `json:"themes,omitempty"`
|
Themes []ThemeContribution `json:"themes,omitempty"`
|
||||||
|
Channels []ChannelContribution `json:"channels,omitempty"`
|
||||||
UIScripts []UIScriptContribution `json:"uiScripts,omitempty"`
|
UIScripts []UIScriptContribution `json:"uiScripts,omitempty"`
|
||||||
Locales []LocaleContribution `json:"locales,omitempty"`
|
Locales []LocaleContribution `json:"locales,omitempty"`
|
||||||
InputFilters []InputFilterContribution `json:"inputFilters,omitempty"`
|
InputFilters []InputFilterContribution `json:"inputFilters,omitempty"`
|
||||||
@@ -326,6 +327,14 @@ type Contributes struct {
|
|||||||
Diagnostics []DiagnosticsContribution `json:"diagnostics,omitempty"`
|
Diagnostics []DiagnosticsContribution `json:"diagnostics,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ChannelContribution declares a framed message channel exposed through
|
||||||
|
// `reims-go plugin connect`. The host validates the declaration before it
|
||||||
|
// forwards any client data to the Sidecar.
|
||||||
|
type ChannelContribution struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Framing string `json:"framing"`
|
||||||
|
}
|
||||||
|
|
||||||
// DownloaderContribution registers a pluggable file/region downloader (Builtin or L3 Sidecar).
|
// DownloaderContribution registers a pluggable file/region downloader (Builtin or L3 Sidecar).
|
||||||
type DownloaderContribution struct {
|
type DownloaderContribution struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
@@ -336,25 +345,25 @@ type DownloaderContribution struct {
|
|||||||
|
|
||||||
// ThemeContribution describes a L1 token/style theme or tier-3 interactive theme (§5.1).
|
// ThemeContribution describes a L1 token/style theme or tier-3 interactive theme (§5.1).
|
||||||
type ThemeContribution struct {
|
type ThemeContribution struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Name LocalizedText `json:"name"`
|
Name LocalizedText `json:"name"`
|
||||||
Description LocalizedText `json:"description,omitempty"`
|
Description LocalizedText `json:"description,omitempty"`
|
||||||
Appearance string `json:"appearance,omitempty"` // "light" | "dark" | "both"
|
Appearance string `json:"appearance,omitempty"` // "light" | "dark" | "both"
|
||||||
Seeds map[string]string `json:"seeds,omitempty"`
|
Seeds map[string]string `json:"seeds,omitempty"`
|
||||||
Schemes []ThemeScheme `json:"schemes,omitempty"`
|
Schemes []ThemeScheme `json:"schemes,omitempty"`
|
||||||
DeriveRules []TokenDeriveRule `json:"deriveRules,omitempty"`
|
DeriveRules []TokenDeriveRule `json:"deriveRules,omitempty"`
|
||||||
Tokens map[string]string `json:"tokens,omitempty"`
|
Tokens map[string]string `json:"tokens,omitempty"`
|
||||||
DarkTokens map[string]string `json:"darkTokens,omitempty"`
|
DarkTokens map[string]string `json:"darkTokens,omitempty"`
|
||||||
Fonts []ThemeFont `json:"fonts,omitempty"`
|
Fonts []ThemeFont `json:"fonts,omitempty"`
|
||||||
Icons map[string]string `json:"icons,omitempty"`
|
Icons map[string]string `json:"icons,omitempty"`
|
||||||
BrandMark string `json:"brandMark,omitempty"`
|
BrandMark string `json:"brandMark,omitempty"`
|
||||||
Background string `json:"background,omitempty"`
|
Background string `json:"background,omitempty"`
|
||||||
Sounds map[string]string `json:"sounds,omitempty"`
|
Sounds map[string]string `json:"sounds,omitempty"`
|
||||||
Stylesheet string `json:"stylesheet,omitempty"` // relative path inside package
|
Stylesheet string `json:"stylesheet,omitempty"` // relative path inside package
|
||||||
Decorations []ThemeDecoration `json:"decorations,omitempty"`
|
Decorations []ThemeDecoration `json:"decorations,omitempty"`
|
||||||
UIScript string `json:"uiScript,omitempty"` // requires ui:script
|
UIScript string `json:"uiScript,omitempty"` // requires ui:script
|
||||||
Layout *ThemeLayout `json:"layout,omitempty"`
|
Layout *ThemeLayout `json:"layout,omitempty"`
|
||||||
PluginID string `json:"pluginId,omitempty"`
|
PluginID string `json:"pluginId,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ThemeScheme is a named seed-color preset inside a theme pack.
|
// ThemeScheme is a named seed-color preset inside a theme pack.
|
||||||
@@ -387,12 +396,12 @@ type ThemeFont struct {
|
|||||||
|
|
||||||
// ThemeDecoration defines a declarative state-driven sprite/frame decoration anchored to a slot.
|
// ThemeDecoration defines a declarative state-driven sprite/frame decoration anchored to a slot.
|
||||||
type ThemeDecoration struct {
|
type ThemeDecoration struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Slot string `json:"slot"` // e.g. "sidebar.footer", "vm.preview.br"
|
Slot string `json:"slot"` // e.g. "sidebar.footer", "vm.preview.br"
|
||||||
Width int `json:"width,omitempty"`
|
Width int `json:"width,omitempty"`
|
||||||
Height int `json:"height,omitempty"`
|
Height int `json:"height,omitempty"`
|
||||||
Alt LocalizedText `json:"alt,omitempty"`
|
Alt LocalizedText `json:"alt,omitempty"`
|
||||||
States []ThemeDecorationState `json:"states"`
|
States []ThemeDecorationState `json:"states"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ThemeDecorationState maps a state expression (e.g. "vmState==running") to a static/animated asset.
|
// ThemeDecorationState maps a state expression (e.g. "vmState==running") to a static/animated asset.
|
||||||
@@ -469,16 +478,16 @@ type ResolvedLocalePack struct {
|
|||||||
|
|
||||||
// InputFilterContribution declares a host-side input filter rule (§5.4).
|
// InputFilterContribution declares a host-side input filter rule (§5.4).
|
||||||
type InputFilterContribution struct {
|
type InputFilterContribution struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Event string `json:"event"` // "mouse_wheel"
|
Event string `json:"event"` // "mouse_wheel"
|
||||||
Axis string `json:"axis,omitempty"` // "vertical" | "horizontal" | "both"
|
Axis string `json:"axis,omitempty"` // "vertical" | "horizontal" | "both"
|
||||||
Transform string `json:"transform"` // "invert"
|
Transform string `json:"transform"` // "invert"
|
||||||
Scope string `json:"scope"` // "vm_foreground"
|
Scope string `json:"scope"` // "vm_foreground"
|
||||||
SettingKey string `json:"settingKey,omitempty"` // VM-scoped boolean key
|
SettingKey string `json:"settingKey,omitempty"` // VM-scoped boolean key
|
||||||
HorizKey string `json:"horizontalKey,omitempty"`
|
HorizKey string `json:"horizontalKey,omitempty"`
|
||||||
VertKey string `json:"verticalKey,omitempty"`
|
VertKey string `json:"verticalKey,omitempty"`
|
||||||
Name LocalizedText `json:"name,omitempty"`
|
Name LocalizedText `json:"name,omitempty"`
|
||||||
PluginID string `json:"pluginId,omitempty"`
|
PluginID string `json:"pluginId,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// VMTemplateContribution contributes a VM creation preset.
|
// VMTemplateContribution contributes a VM creation preset.
|
||||||
@@ -493,34 +502,34 @@ type VMTemplateContribution struct {
|
|||||||
|
|
||||||
// RuntimeSourceContribution contributes an additional runtime download mirror/source.
|
// RuntimeSourceContribution contributes an additional runtime download mirror/source.
|
||||||
type RuntimeSourceContribution struct {
|
type RuntimeSourceContribution struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Kind string `json:"kind"`
|
Kind string `json:"kind"`
|
||||||
Name LocalizedText `json:"name"`
|
Name LocalizedText `json:"name"`
|
||||||
IndexURL string `json:"indexUrl"`
|
IndexURL string `json:"indexUrl"`
|
||||||
Channel string `json:"channel,omitempty"`
|
Channel string `json:"channel,omitempty"`
|
||||||
License string `json:"license,omitempty"`
|
License string `json:"license,omitempty"`
|
||||||
Publisher string `json:"publisher,omitempty"`
|
Publisher string `json:"publisher,omitempty"`
|
||||||
PluginID string `json:"pluginId,omitempty"`
|
PluginID string `json:"pluginId,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// RuntimeKindContribution registers a new runtime kind (e.g. "qemu-ovmf").
|
// RuntimeKindContribution registers a new runtime kind (e.g. "qemu-ovmf").
|
||||||
type RuntimeKindContribution struct {
|
type RuntimeKindContribution struct {
|
||||||
Kind string `json:"kind"`
|
Kind string `json:"kind"`
|
||||||
Name LocalizedText `json:"name"`
|
Name LocalizedText `json:"name"`
|
||||||
Description LocalizedText `json:"description,omitempty"`
|
Description LocalizedText `json:"description,omitempty"`
|
||||||
RequiredFiles []string `json:"requiredFiles,omitempty"`
|
RequiredFiles []string `json:"requiredFiles,omitempty"`
|
||||||
DefaultAPIVer string `json:"defaultApiVersion,omitempty"`
|
DefaultAPIVer string `json:"defaultApiVersion,omitempty"`
|
||||||
PluginID string `json:"pluginId,omitempty"`
|
PluginID string `json:"pluginId,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// RuntimePackContribution declares an archive/binary runtime package inside a plugin.
|
// RuntimePackContribution declares an archive/binary runtime package inside a plugin.
|
||||||
type RuntimePackContribution struct {
|
type RuntimePackContribution struct {
|
||||||
Kind string `json:"kind"`
|
Kind string `json:"kind"`
|
||||||
Version string `json:"version"`
|
Version string `json:"version"`
|
||||||
RuntimeAPI string `json:"runtimeApi"`
|
RuntimeAPI string `json:"runtimeApi"`
|
||||||
Capabilities []string `json:"capabilities,omitempty"`
|
Capabilities []string `json:"capabilities,omitempty"`
|
||||||
Dir string `json:"dir,omitempty"`
|
Dir string `json:"dir,omitempty"`
|
||||||
PluginID string `json:"pluginId,omitempty"`
|
PluginID string `json:"pluginId,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// GuestDriverContribution declares a guest VM driver provided by an L3 Sidecar or builtin.
|
// GuestDriverContribution declares a guest VM driver provided by an L3 Sidecar or builtin.
|
||||||
@@ -649,28 +658,28 @@ type DiagnosticsContribution struct {
|
|||||||
|
|
||||||
// SettingsSchema is a JSON Schema subset with Reims-Go extensions (§6.2).
|
// SettingsSchema is a JSON Schema subset with Reims-Go extensions (§6.2).
|
||||||
type SettingsSchema struct {
|
type SettingsSchema struct {
|
||||||
Title LocalizedText `json:"title,omitempty"`
|
Title LocalizedText `json:"title,omitempty"`
|
||||||
Group string `json:"x-group,omitempty"` // e.g. "keyboard", "collaboration"
|
Group string `json:"x-group,omitempty"` // e.g. "keyboard", "collaboration"
|
||||||
Scope string `json:"x-scope,omitempty"` // "app" | "vm"
|
Scope string `json:"x-scope,omitempty"` // "app" | "vm"
|
||||||
Properties map[string]SettingProperty `json:"properties"`
|
Properties map[string]SettingProperty `json:"properties"`
|
||||||
Order []string `json:"x-order,omitempty"`
|
Order []string `json:"x-order,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// SettingProperty describes one configurable field.
|
// SettingProperty describes one configurable field.
|
||||||
type SettingProperty struct {
|
type SettingProperty struct {
|
||||||
Type string `json:"type"` // "boolean" | "string" | "number" | "integer"
|
Type string `json:"type"` // "boolean" | "string" | "number" | "integer"
|
||||||
Title LocalizedText `json:"title"`
|
Title LocalizedText `json:"title"`
|
||||||
Description LocalizedText `json:"description,omitempty"`
|
Description LocalizedText `json:"description,omitempty"`
|
||||||
Default any `json:"default,omitempty"`
|
Default any `json:"default,omitempty"`
|
||||||
Enum []string `json:"enum,omitempty"`
|
Enum []string `json:"enum,omitempty"`
|
||||||
EnumLabels []LocalizedText `json:"x-enumLabels,omitempty"`
|
EnumLabels []LocalizedText `json:"x-enumLabels,omitempty"`
|
||||||
Minimum *float64 `json:"minimum,omitempty"`
|
Minimum *float64 `json:"minimum,omitempty"`
|
||||||
Maximum *float64 `json:"maximum,omitempty"`
|
Maximum *float64 `json:"maximum,omitempty"`
|
||||||
Secret bool `json:"x-secret,omitempty"`
|
Secret bool `json:"x-secret,omitempty"`
|
||||||
Effect string `json:"x-effect,omitempty"` // "immediate" | "next_start"
|
Effect string `json:"x-effect,omitempty"` // "immediate" | "next_start"
|
||||||
Scope string `json:"x-scope,omitempty"` // "app" | "vm"
|
Scope string `json:"x-scope,omitempty"` // "app" | "vm"
|
||||||
Group string `json:"x-group,omitempty"` // VM settings section id
|
Group string `json:"x-group,omitempty"` // VM settings section id
|
||||||
Required bool `json:"required,omitempty"`
|
Required bool `json:"required,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// PermissionLevel categorizes permission risk (§7.1).
|
// PermissionLevel categorizes permission risk (§7.1).
|
||||||
@@ -697,7 +706,7 @@ func ClassifyPermission(perm string) PermissionLevel {
|
|||||||
return PermLow
|
return PermLow
|
||||||
case "vm:intent", "runtime:source", "ui:slot", "input:filter", "fs:pick":
|
case "vm:intent", "runtime:source", "ui:slot", "input:filter", "fs:pick":
|
||||||
return PermMedium
|
return PermMedium
|
||||||
case "driver:vm", "runtime:provider", "process:spawn", "vm:control",
|
case "driver:vm", "runtime:provider", "process:spawn", "vm:control", "vm:screen",
|
||||||
"qmp:write", "fs:vm_dir", "fs:shared", "host:clipboard", "ui:script":
|
"qmp:write", "fs:vm_dir", "fs:shared", "host:clipboard", "ui:script":
|
||||||
return PermHigh
|
return PermHigh
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,162 @@
|
|||||||
|
package qmp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// QueryExecutor is the read-only part of a QMP session used by mouse probing.
|
||||||
|
type QueryExecutor interface {
|
||||||
|
Query(command string, args any) (json.RawMessage, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MouseInfo describes a QEMU input device returned by query-mice.
|
||||||
|
type MouseInfo struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Index int `json:"index"`
|
||||||
|
Current bool `json:"current"`
|
||||||
|
Absolute bool `json:"absolute"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueryMice returns the guest input devices currently exposed by QEMU.
|
||||||
|
func QueryMice(q QueryExecutor) ([]MouseInfo, error) {
|
||||||
|
if q == nil {
|
||||||
|
return nil, errors.New("QMP session is unavailable")
|
||||||
|
}
|
||||||
|
data, err := q.Query("query-mice", nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var mice []MouseInfo
|
||||||
|
if err := json.Unmarshal(data, &mice); err != nil {
|
||||||
|
return nil, fmt.Errorf("decode QMP query-mice: %w", err)
|
||||||
|
}
|
||||||
|
return mice, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// HasCurrentAbsoluteMouse reports whether QEMU selected an absolute pointer.
|
||||||
|
func HasCurrentAbsoluteMouse(mice []MouseInfo) bool {
|
||||||
|
for _, mouse := range mice {
|
||||||
|
if mouse.Current && mouse.Absolute {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// MouseMove converts framebuffer coordinates to QEMU's 0..32767 absolute axes.
|
||||||
|
func MouseMove(q Executor, x, y, width, height int) error {
|
||||||
|
if q == nil {
|
||||||
|
return errors.New("QMP session is unavailable")
|
||||||
|
}
|
||||||
|
ax, err := absoluteAxis(x, width)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("mouse x coordinate: %w", err)
|
||||||
|
}
|
||||||
|
ay, err := absoluteAxis(y, height)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("mouse y coordinate: %w", err)
|
||||||
|
}
|
||||||
|
return q.Execute("input-send-event", map[string]any{"events": []any{
|
||||||
|
map[string]any{"type": "abs", "data": map[string]any{"axis": "x", "value": ax}},
|
||||||
|
map[string]any{"type": "abs", "data": map[string]any{"axis": "y", "value": ay}},
|
||||||
|
}})
|
||||||
|
}
|
||||||
|
|
||||||
|
// MouseButton sends one supported QEMU mouse button transition.
|
||||||
|
func MouseButton(q Executor, button string, down bool) error {
|
||||||
|
if q == nil {
|
||||||
|
return errors.New("QMP session is unavailable")
|
||||||
|
}
|
||||||
|
button = normalizeMouseButton(button)
|
||||||
|
if !validMouseButton(button) {
|
||||||
|
return fmt.Errorf("unsupported mouse button %q", button)
|
||||||
|
}
|
||||||
|
return sendMouseButton(q, button, down)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MouseClick presses and releases a mouse button as one serialized QMP job.
|
||||||
|
func MouseClick(q Executor, button string) error {
|
||||||
|
if q == nil {
|
||||||
|
return errors.New("QMP session is unavailable")
|
||||||
|
}
|
||||||
|
button = normalizeMouseButton(button)
|
||||||
|
if !validMouseButton(button) {
|
||||||
|
return fmt.Errorf("unsupported mouse button %q", button)
|
||||||
|
}
|
||||||
|
return q.Execute("input-send-event", map[string]any{"events": []any{
|
||||||
|
mouseButtonEvent(button, true),
|
||||||
|
mouseButtonEvent(button, false),
|
||||||
|
}})
|
||||||
|
}
|
||||||
|
|
||||||
|
// MouseScroll sends vertical or horizontal wheel steps. A positive delta means
|
||||||
|
// down or right, and a negative delta means up or left.
|
||||||
|
func MouseScroll(q Executor, delta int, horizontal bool) error {
|
||||||
|
if q == nil {
|
||||||
|
return errors.New("QMP session is unavailable")
|
||||||
|
}
|
||||||
|
if delta == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if delta > 120 || delta < -120 {
|
||||||
|
return errors.New("mouse scroll exceeds 120 steps")
|
||||||
|
}
|
||||||
|
steps := delta
|
||||||
|
if steps < 0 {
|
||||||
|
steps = -steps
|
||||||
|
}
|
||||||
|
button := "wheel-down"
|
||||||
|
if horizontal {
|
||||||
|
button = "wheel-right"
|
||||||
|
}
|
||||||
|
if delta < 0 {
|
||||||
|
button = "wheel-up"
|
||||||
|
if horizontal {
|
||||||
|
button = "wheel-left"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
events := make([]any, 0, steps*2)
|
||||||
|
for range steps {
|
||||||
|
events = append(events,
|
||||||
|
map[string]any{"type": "btn", "data": map[string]any{"down": true, "button": button}},
|
||||||
|
map[string]any{"type": "btn", "data": map[string]any{"down": false, "button": button}},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return q.Execute("input-send-event", map[string]any{"events": events})
|
||||||
|
}
|
||||||
|
|
||||||
|
func absoluteAxis(position, size int) (int, error) {
|
||||||
|
if size <= 0 || position < 0 || position >= size {
|
||||||
|
return 0, errors.New("coordinate is outside the framebuffer")
|
||||||
|
}
|
||||||
|
if size == 1 {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
return int(math.Round(float64(position) * 32767 / float64(size-1))), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validMouseButton(button string) bool {
|
||||||
|
switch button {
|
||||||
|
case "left", "right", "middle", "wheel-up", "wheel-down", "wheel-left", "wheel-right":
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeMouseButton(button string) string {
|
||||||
|
return strings.ToLower(strings.TrimSpace(button))
|
||||||
|
}
|
||||||
|
|
||||||
|
func mouseButtonEvent(button string, down bool) map[string]any {
|
||||||
|
return map[string]any{"type": "btn", "data": map[string]any{"down": down, "button": button}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func sendMouseButton(q Executor, button string, down bool) error {
|
||||||
|
button = normalizeMouseButton(button)
|
||||||
|
return q.Execute("input-send-event", map[string]any{"events": []any{mouseButtonEvent(button, down)}})
|
||||||
|
}
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
package qmp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
type pointerRecorder struct {
|
||||||
|
command string
|
||||||
|
args any
|
||||||
|
result json.RawMessage
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *pointerRecorder) Execute(command string, args any) error {
|
||||||
|
r.command, r.args = command, args
|
||||||
|
return r.err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *pointerRecorder) Query(command string, args any) (json.RawMessage, error) {
|
||||||
|
r.command, r.args = command, args
|
||||||
|
return r.result, r.err
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestQueryMiceAndAbsolutePointerDetection(t *testing.T) {
|
||||||
|
q := &pointerRecorder{result: json.RawMessage(`[
|
||||||
|
{"name":"PS/2 Mouse","index":0,"current":false,"absolute":false},
|
||||||
|
{"name":"QEMU HID Tablet","index":1,"current":true,"absolute":true}
|
||||||
|
]`)}
|
||||||
|
mice, err := QueryMice(q)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if q.command != "query-mice" || !HasCurrentAbsoluteMouse(mice) {
|
||||||
|
t.Fatalf("query=%q mice=%+v", q.command, mice)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMouseMoveMapsFramebufferCoordinates(t *testing.T) {
|
||||||
|
q := &pointerRecorder{}
|
||||||
|
if err := MouseMove(q, 4, 2, 5, 3); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := map[string]any{"events": []any{
|
||||||
|
map[string]any{"type": "abs", "data": map[string]any{"axis": "x", "value": 32767}},
|
||||||
|
map[string]any{"type": "abs", "data": map[string]any{"axis": "y", "value": 32767}},
|
||||||
|
}}
|
||||||
|
if q.command != "input-send-event" || !reflect.DeepEqual(q.args, want) {
|
||||||
|
t.Fatalf("command=%q args=%#v, want %#v", q.command, q.args, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMouseClickIsOneSerializedEventSequence(t *testing.T) {
|
||||||
|
q := &pointerRecorder{}
|
||||||
|
if err := MouseClick(q, " LEFT "); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if q.command != "input-send-event" {
|
||||||
|
t.Fatalf("command=%q", q.command)
|
||||||
|
}
|
||||||
|
want := map[string]any{"events": []any{
|
||||||
|
map[string]any{"type": "btn", "data": map[string]any{"down": true, "button": "left"}},
|
||||||
|
map[string]any{"type": "btn", "data": map[string]any{"down": false, "button": "left"}},
|
||||||
|
}}
|
||||||
|
if !reflect.DeepEqual(q.args, want) {
|
||||||
|
t.Fatalf("args=%#v, want %#v", q.args, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMouseScrollDirectionAndBounds(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
delta int
|
||||||
|
horizontal bool
|
||||||
|
button string
|
||||||
|
}{
|
||||||
|
{name: "down", delta: 2, button: "wheel-down"},
|
||||||
|
{name: "up", delta: -1, button: "wheel-up"},
|
||||||
|
{name: "right", delta: 1, horizontal: true, button: "wheel-right"},
|
||||||
|
{name: "left", delta: -2, horizontal: true, button: "wheel-left"},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
q := &pointerRecorder{}
|
||||||
|
if err := MouseScroll(q, tt.delta, tt.horizontal); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var args struct {
|
||||||
|
Events []struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Data struct {
|
||||||
|
Down bool `json:"down"`
|
||||||
|
Button string `json:"button"`
|
||||||
|
} `json:"data"`
|
||||||
|
} `json:"events"`
|
||||||
|
}
|
||||||
|
b, err := json.Marshal(q.args)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(b, &args); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(args.Events) != 2*absInt(tt.delta) {
|
||||||
|
t.Fatalf("event count=%d", len(args.Events))
|
||||||
|
}
|
||||||
|
for i, event := range args.Events {
|
||||||
|
if event.Type != "btn" || event.Data.Button != tt.button || event.Data.Down != (i%2 == 0) {
|
||||||
|
t.Fatalf("event %d=%+v", i, event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
for _, delta := range []int{121, -121, -int(^uint(0)>>1) - 1} {
|
||||||
|
if err := MouseScroll(&pointerRecorder{}, delta, false); err == nil {
|
||||||
|
t.Fatalf("MouseScroll(%d) unexpectedly succeeded", delta)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMouseMoveAndButtonRejectInvalidInputs(t *testing.T) {
|
||||||
|
if err := MouseMove(&pointerRecorder{}, 0, 0, 0, 10); err == nil {
|
||||||
|
t.Fatal("expected invalid framebuffer dimensions to fail")
|
||||||
|
}
|
||||||
|
if err := MouseButton(&pointerRecorder{}, "side", true); err == nil {
|
||||||
|
t.Fatal("expected unsupported button to fail")
|
||||||
|
}
|
||||||
|
if err := MouseClick(&pointerRecorder{}, "side"); err == nil {
|
||||||
|
t.Fatal("expected unsupported click button to fail")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func absInt(value int) int {
|
||||||
|
if value < 0 {
|
||||||
|
return -value
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
@@ -28,6 +28,26 @@ func Load(path, format string) (image.Image, error) {
|
|||||||
return decodePPM(bufio.NewReader(f))
|
return decodePPM(bufio.NewReader(f))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Size returns the source-frame dimensions without decoding its pixels.
|
||||||
|
func Size(path, format string) (image.Point, error) {
|
||||||
|
f, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return image.Point{}, err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
if format == "png" {
|
||||||
|
cfg, err := png.DecodeConfig(bufio.NewReader(f))
|
||||||
|
if err != nil {
|
||||||
|
return image.Point{}, err
|
||||||
|
}
|
||||||
|
return image.Pt(cfg.Width, cfg.Height), nil
|
||||||
|
}
|
||||||
|
if format != "ppm" {
|
||||||
|
return image.Point{}, fmt.Errorf("unsupported screendump format %q", format)
|
||||||
|
}
|
||||||
|
return ppmSize(bufio.NewReader(f))
|
||||||
|
}
|
||||||
|
|
||||||
// decodePPM reads a binary PPM (P6, maxval ≤ 255), the format QEMU's
|
// decodePPM reads a binary PPM (P6, maxval ≤ 255), the format QEMU's
|
||||||
// screendump writes when no format is given.
|
// screendump writes when no format is given.
|
||||||
func decodePPM(r *bufio.Reader) (image.Image, error) {
|
func decodePPM(r *bufio.Reader) (image.Image, error) {
|
||||||
|
|||||||
@@ -51,6 +51,20 @@ func TestDecodePPMRejectsTruncatedPixels(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSourceSizeReadsPPMHeader(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "frame.ppm")
|
||||||
|
if err := os.WriteFile(path, ppm(1440, 750, func(int, int) [3]byte { return [3]byte{} }), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
size, err := Size(path, "ppm")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if size != image.Pt(1440, 750) {
|
||||||
|
t.Fatalf("source size = %v", size)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func BenchmarkDecodePPM4K(b *testing.B) {
|
func BenchmarkDecodePPM4K(b *testing.B) {
|
||||||
data := ppm(3840, 2160, func(x, y int) [3]byte { return [3]byte{byte(x), byte(y), 7} })
|
data := ppm(3840, 2160, func(x, y int) [3]byte { return [3]byte{byte(x), byte(y), 7} })
|
||||||
b.SetBytes(int64(len(data)))
|
b.SetBytes(int64(len(data)))
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// PluginAPIVersion is the protocol version spoken by this SDK.
|
// PluginAPIVersion is the protocol version spoken by this SDK.
|
||||||
const PluginAPIVersion = "1.0.0"
|
const PluginAPIVersion = "1.1.0"
|
||||||
|
|
||||||
// Handler handles one inbound JSON-RPC method from the Reims-Go host.
|
// Handler handles one inbound JSON-RPC method from the Reims-Go host.
|
||||||
type Handler func(ctx context.Context, params json.RawMessage) (any, error)
|
type Handler func(ctx context.Context, params json.RawMessage) (any, error)
|
||||||
|
|||||||
Reference in new issue
Block a user