Compare commits

...
Author SHA1 Message Date
YXC0915 b899fbdb8c fix(ci): provide embedded assets for the packaging CLI
Build native USB plugin / windows (push) Canceled after 0s
2026-12-04 22:58:25 +08:00
YXC0915 87d75478a6 ci(plugin): build native USB packages in public Actions 2026-12-04 22:56:18 +08:00
YXC0915 a04cf9a491 feat(plugin): add native Windows USB passthrough 2026-12-04 22:12:52 +08:00
9 changed files with 1312 additions and 0 deletions

No files matched your search

+53
View File
@@ -0,0 +1,53 @@
name: Build native USB plugin
on:
push:
paths:
- 'plugins/usb-redir/**'
- '.github/workflows/native-usb-plugin.yml'
workflow_dispatch:
permissions:
contents: read
jobs:
windows:
runs-on: windows-latest
timeout-minutes: 12
env:
CGO_ENABLED: '0'
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
- uses: actions/setup-node@v4
with:
node-version: '22'
- name: Test and pack the Windows plugin
shell: pwsh
run: |
$cli = Join-Path $env:RUNNER_TEMP 'reims-go-cli.exe'
$output = Join-Path $env:RUNNER_TEMP 'native-usb-plugin'
New-Item -ItemType Directory -Path $output | Out-Null
go test -p 2 ./plugins/usb-redir
if ($LASTEXITCODE) { exit $LASTEXITCODE }
New-Item -ItemType Directory -Path 'frontend/dist' -Force | Out-Null
Set-Content -LiteralPath 'frontend/dist/index.html' -Value '<!doctype html>' -Encoding ascii
go build -p 2 -trimpath -o $cli .
if ($LASTEXITCODE) { exit $LASTEXITCODE }
$manifest = Get-Content -LiteralPath 'plugins/usb-redir/plugin.json' -Raw | ConvertFrom-Json
$name = "$($manifest.id)-$($manifest.version).zip"
& 'plugins/usb-redir/build.ps1' -ReimsGoExe $cli -OutputPath (Join-Path $output $name)
if (!$?) { exit 1 }
$hash = (Get-FileHash -LiteralPath (Join-Path $output $name)).Hash.ToLowerInvariant()
"$hash $name" | Set-Content -LiteralPath (Join-Path $output 'SHA256SUMS.txt') -Encoding ascii
- uses: actions/upload-artifact@v4
with:
name: native-usb-plugin
path: ${{ runner.temp }}/native-usb-plugin
if-no-files-found: error
+21
View File
@@ -0,0 +1,21 @@
# USB 直通(原生)
在 Windows x64 的 Reims-Go 中导入本插件 ZIP,再启用「USB 直通(原生)」。在插件面板设置预览包目录或其中的 Windows-USB 目录。使用可信来源的助手包,核对其校验和再启用。
1. 启动使用支持 QEMU `usb-redir` 的运行时的 Reims 虚拟机。已经启用其他 USB 直通方案时,先正常释放它的会话。
2. 在面板选择正在运行的虚拟机,刷新 USB 设备,勾选可用设备。如果 Windows 询问管理员权限,确认后按界面提示拔出设备并插回原端口。
3. 取消勾选发起释放。若面板提示拔出设备,保持断开,等 Windows 驱动恢复完成后再插入。遇到恢复错误时遵循助手包内的恢复说明。
Windows-USB 包需要包含 `scripts/attach.py` 和 `scripts/qmp-relay.exe`,以及 `deps/python`、`deps/powershell` 和 `deps/libusb-win32`。助手在 Windows 中管理签名过滤驱动、设备能力和 QEMU 会话。每台宿主机同时只能进行一个驱动会话。
## Build / 构建
On Windows, use Go and a compatible Reims-Go executable from this repo:
```powershell
pwsh -File plugins/usb-redir/build.ps1 -ReimsGoExe C:\Tools\reims-go.exe -OutputPath D:\Preview\reimscommunity.usb-redir-0.1.0-alpha.1.zip
```
The build validates the ZIP with `plugin doctor --json`. The ZIP contains the sidecar and panel; the Windows-USB helper, signed drivers, QEMU runtime, and Python dependencies are distributed with the separate preview kit.
The sidecar handshake, plugin data layout, panel bridge and packaging pattern adapt the Apache-2.0 community `mango6i/reims-go-usb-passthrough` v0.1.0-beta.6 source. [Pinned community source](https://github.com/mango6i/reims-go-usb-passthrough/tree/6d76f0b918abb19150ad453de16639d96d86a552/plugins/usb-passthrough)
+85
View File
@@ -0,0 +1,85 @@
#Requires -Version 7.0
# SPDX-License-Identifier: Apache-2.0
# Packaging adapted from mango6i/reims-go-usb-passthrough v0.1.0-beta.6.
[CmdletBinding()]
param(
[Parameter(Mandatory)] [string]$ReimsGoExe,
[Parameter(Mandatory)] [string]$OutputPath
)
$ErrorActionPreference = 'Stop'
$repo = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$reims = (Get-Item -LiteralPath $ReimsGoExe).FullName
$output = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputPath)
if (Test-Path -LiteralPath $output) { throw 'The output ZIP already exists.' }
function Invoke-ReimsCli([string[]]$CliArguments) {
$start = [Diagnostics.ProcessStartInfo]::new($reims)
$start.UseShellExecute = $false
$start.CreateNoWindow = $true
$start.RedirectStandardOutput = $true
$start.RedirectStandardError = $true
foreach ($argument in $CliArguments) { $start.ArgumentList.Add($argument) }
$proc = [Diagnostics.Process]::Start($start)
try {
$stdout = $proc.StandardOutput.ReadToEndAsync()
$stderr = $proc.StandardError.ReadToEndAsync()
if (!$proc.WaitForExit(75000)) {
$proc.Kill($true)
throw 'The Reims-Go CLI timed out.'
}
$outText = $stdout.GetAwaiter().GetResult().Trim()
$errText = $stderr.GetAwaiter().GetResult().Trim()
if ($outText) { Write-Host $outText }
if ($proc.ExitCode -ne 0) { throw "Reims-Go CLI failed ($($proc.ExitCode)). $errText" }
if ($errText) { Write-Host $errText }
} finally { $proc.Dispose() }
}
$tmp = Join-Path $repo 'scripts/debug/tmp.mjs'
$stage = & node $tmp new usb-redir-plugin
if ($LASTEXITCODE -ne 0 -or !$stage) { throw 'Could not create a plugin build session.' }
$options = @{
GOOS = 'windows'
GOARCH = 'amd64'
CGO_ENABLED = '0'
GOMAXPROCS = '2'
GOTMPDIR = $stage
REIMS_GO_DATA_ROOT = (Join-Path $stage 'data-root')
REIMS_GO_LOCATION_FILE = (Join-Path $stage 'location.json')
TEMP = $stage
TMP = $stage
}
$previous = @{}
$finished = $false
Push-Location $repo
try {
foreach ($name in $options.Keys) {
$previous[$name] = [Environment]::GetEnvironmentVariable($name, 'Process')
[Environment]::SetEnvironmentVariable($name, $options[$name], 'Process')
}
$package = (New-Item -ItemType Directory -Path (Join-Path $stage 'package')).FullName
$panel = (New-Item -ItemType Directory -Path (Join-Path $package 'panel')).FullName
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'plugin.json'), (Join-Path $PSScriptRoot 'README.md'), (Join-Path $repo 'LICENSE') -Destination $package
$page = Join-Path $PSScriptRoot 'panel/usb.html'
Copy-Item -LiteralPath $page -Destination $panel
# Support hosts that serve the panel entry relative to the package root.
Copy-Item -LiteralPath $page -Destination $package
& go build -p 2 -trimpath '-ldflags=-s -w' -o (Join-Path $package 'reims-usb-redir.exe') ./plugins/usb-redir
if ($LASTEXITCODE -ne 0) { throw 'USB sidecar build failed.' }
Invoke-ReimsCli @('plugin', 'pack', '--out', $output, $package)
Invoke-ReimsCli @('plugin', 'doctor', '--json', $output)
$finished = $true
} finally {
Pop-Location
foreach ($name in $previous.Keys) {
[Environment]::SetEnvironmentVariable($name, $previous[$name], 'Process')
}
if ($finished) {
& node $tmp close $stage
if ($LASTEXITCODE -ne 0) { Write-Warning "Could not close the build session $stage" }
} else {
Write-Host "Build files: $stage"
}
}
+288
View File
@@ -0,0 +1,288 @@
//go:build windows
// SPDX-License-Identifier: Apache-2.0
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/Nwflower/reims-go/internal/qmp"
"github.com/pelletier/go-toml/v2"
"golang.org/x/sys/windows"
)
const reimsDriver = "builtin.driver.reims-macos"
type vmEntry struct {
ID string `json:"vm"`
Name string `json:"name"`
Driver string `json:"driver_id"`
State string `json:"state"`
}
func (p *plugin) listVMs(ctx context.Context, root string) ([]vmEntry, error) {
var reply struct {
VMs []vmEntry `json:"vms"`
}
if err := p.host.CallHost(ctx, "host/vm.list", struct{}{}, &reply); err != nil {
if strings.Contains(err.Error(), "method not found: host/vm.list") {
return listRegisteredVMs(root)
}
return nil, err
}
vms := make([]vmEntry, 0, len(reply.VMs))
for _, vm := range reply.VMs {
if vm.Driver == reimsDriver && vm.ID != "" && vm.Name != "" {
vms = append(vms, vm)
}
}
return vms, nil
}
func (p *plugin) resolveVM(ctx context.Context, root, id string) (vmEntry, string, string, error) {
vms, err := p.listVMs(ctx, root)
if err != nil {
return vmEntry{}, "", "", err
}
for _, vm := range vms {
if vm.ID != id || vm.State != "running" {
continue
}
dir, err := registeredVMDir(root, vm.Name)
if err != nil {
return vmEntry{}, "", "", errors.New(p.text("Could not locate the running VM's monitor.",
"无法定位这台运行中虚拟机的控制接口。"))
}
return vm, dir, qmp.SocketPathForVM(dir, vm.Name, filepath.Join(root, "tmp")), nil
}
return vmEntry{}, "", "", errors.New(p.text("Choose a running Reims virtual machine.", "选择一台运行中的 Reims 虚拟机。"))
}
type registeredVM struct {
Name string `toml:"name"`
Dir string `toml:"dir"`
}
func readRegistry(root string) ([]registeredVM, error) {
var registry struct {
VMs []registeredVM `toml:"vm"`
}
raw, err := os.ReadFile(filepath.Join(root, "config", "reims-ctl", "vms.toml"))
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
if err := toml.Unmarshal(raw, &registry); err != nil {
return nil, err
}
return registry.VMs, nil
}
func listRegisteredVMs(root string) ([]vmEntry, error) {
registered, err := readRegistry(root)
if err != nil {
return nil, err
}
vms := make([]vmEntry, 0, len(registered))
for _, vm := range registered {
if vm.Name == "" || !filepath.IsAbs(vm.Dir) {
continue
}
state := "stopped"
if liveQEMU(vm.Dir) {
state = "running"
}
vms = append(vms, vmEntry{ID: "reims-ctl:" + vm.Name, Name: vm.Name, Driver: reimsDriver, State: state})
}
return vms, nil
}
func registeredVMDir(root, name string) (string, error) {
registered, err := readRegistry(root)
if err != nil {
return "", err
}
var dir string
for _, vm := range registered {
if vm.Name != name {
continue
}
if dir != "" || !filepath.IsAbs(vm.Dir) {
return "", errors.New("ambiguous or relative VM path")
}
dir = filepath.Clean(vm.Dir)
}
if dir == "" {
return "", errors.New("VM not registered")
}
raw, err := os.ReadFile(filepath.Join(dir, "qemu.pid"))
if err != nil {
return "", err
}
if pid, err := strconv.ParseUint(strings.TrimSpace(string(raw)), 10, 32); err != nil || pid == 0 {
return "", errors.New("VM has no valid QEMU PID")
}
return dir, nil
}
// CLI plugin managers do not inject the application's VM list handler.
// Verify the registered VM's PID on Windows before allowing a fallback row
// to be used for attach. A stale PID may have been assigned to another task.
func liveQEMU(dir string) bool {
pidFile := filepath.Join(dir, "qemu.pid")
raw, err := os.ReadFile(pidFile)
if err != nil {
return false
}
pid, err := strconv.ParseUint(strings.TrimSpace(string(raw)), 10, 32)
if err != nil || pid == 0 {
return false
}
info, err := os.Stat(pidFile)
if err != nil {
return false
}
proc, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
if err != nil {
return false
}
defer windows.CloseHandle(proc)
var exit uint32
if windows.GetExitCodeProcess(proc, &exit) != nil || exit != 259 {
return false
}
var created, exited, kernel, user windows.Filetime
if windows.GetProcessTimes(proc, &created, &exited, &kernel, &user) != nil ||
time.Unix(0, created.Nanoseconds()).After(info.ModTime().Add(time.Second)) {
return false
}
image := make([]uint16, 32768)
size := uint32(len(image))
if windows.QueryFullProcessImageName(proc, 0, &image[0], &size) != nil {
return false
}
return strings.EqualFold(filepath.Base(windows.UTF16ToString(image[:size])), "qemu-system-x86_64.exe")
}
type helperBundle struct {
Root, Python, PowerShell, Script, Relay, Driver string
}
func resolveBundle(path string) (helperBundle, error) {
path = strings.Trim(strings.TrimSpace(path), `"`)
volume := filepath.VolumeName(path)
if !filepath.IsAbs(path) || len(volume) != 2 || volume[1] != ':' || strings.Contains(path[len(volume):], ":") {
return helperBundle{}, errors.New("expected an absolute local path")
}
for _, root := range []string{filepath.Clean(path), filepath.Join(path, "Windows-USB")} {
b := helperBundle{
Root: root, Python: filepath.Join(root, "deps", "python", "python.exe"),
PowerShell: filepath.Join(root, "deps", "powershell", "pwsh.exe"),
Script: filepath.Join(root, "scripts", "attach.py"), Relay: filepath.Join(root, "scripts", "qmp-relay.exe"),
Driver: filepath.Join(root, "deps", "libusb-win32", "bin", "amd64"),
}
if !filesExist(filepath.Join(b.Driver, "libusb0.sys"), filepath.Join(b.Driver, "libusb0.dll")) {
b.Driver = filepath.Join(root, "deps", "libusb-win32")
}
if filesExist(b.Python, b.PowerShell, b.Script, b.Relay, filepath.Join(b.Driver, "libusb0.sys"),
filepath.Join(b.Driver, "libusb0.dll")) {
return b, nil
}
}
return helperBundle{}, errors.New("Windows USB helper bundle is incomplete")
}
func filesExist(paths ...string) bool {
for _, path := range paths {
if info, err := os.Stat(path); err != nil || !info.Mode().IsRegular() {
return false
}
}
return true
}
func (b helperBundle) env() []string {
return []string{"PATH=" + filepath.Dir(b.PowerShell) + string(os.PathListSeparator) + os.Getenv("PATH")}
}
type usbEntry struct {
Key string `json:"key"`
Name string `json:"name"`
VID string `json:"vid"`
PID string `json:"pid"`
Port int `json:"port"`
Eligible bool `json:"eligible"`
Reason string `json:"reason"`
}
type inventory struct {
root string
devices []usbEntry
running bool
failed bool
}
// Let the bounded Windows inventory outlive this RPC. PnP enumeration can
// take longer than the panel can hold an interactive command open.
func (p *plugin) startScan(tools helperBundle) {
scan := &inventory{root: tools.Root, running: true}
if p.scan != nil && p.scan.root == tools.Root {
if p.scan.running {
return
}
scan.devices = p.scan.devices
}
p.scan = scan
go func() {
devices, err := tools.list(context.Background())
p.mu.Lock()
defer p.mu.Unlock()
scan.running = false
scan.devices = devices
scan.failed = err != nil
}()
}
func (b helperBundle) list(ctx context.Context) ([]usbEntry, error) {
ctx, cancel := context.WithTimeout(ctx, 45*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, b.Python, "-B", b.Script, "--list-json")
cmd.Dir = b.Root
cmd.Env = append(os.Environ(), b.env()...)
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, err
}
bytes, readErr := io.ReadAll(io.LimitReader(stdout, 1024*1024+1))
if len(bytes) > 1024*1024 || readErr != nil {
_ = cmd.Process.Kill()
_ = cmd.Wait()
return nil, errors.New("invalid USB inventory size")
}
if err := cmd.Wait(); err != nil {
return nil, err
}
var entries []usbEntry
if err := json.Unmarshal(bytes, &entries); err != nil {
return nil, fmt.Errorf("decode USB inventory: %w", err)
}
return entries, nil
}
+172
View File
@@ -0,0 +1,172 @@
//go:build windows
// SPDX-License-Identifier: Apache-2.0
// Sidecar registration and scoped host layout adapted from mango6i's
// reims-go-usb-passthrough v0.1.0-beta.6 (6d76f0b918ab).
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/Nwflower/reims-go/internal/atomicfile"
"github.com/Nwflower/reims-go/pkg/pluginsdk"
)
const pluginID = "reimscommunity.usb-redir"
type platformHost interface {
InitInfo() pluginsdk.InitInfo
CallHost(context.Context, string, any, any) error
SpawnVMProcess(context.Context, string, string, []string, string, []string) (int, error)
IsVMProcessRunning(context.Context, int) (bool, error)
}
type plugin struct {
host platformHost
mu sync.Mutex
scan *inventory
}
type commandArgs struct {
VM string `json:"vm"`
Key string `json:"key"`
Path string `json:"path"`
}
type settings struct {
Path string `json:"path"`
}
type response struct {
Path string `json:"path"`
Ready bool `json:"ready"`
VMs []vmEntry `json:"vms,omitempty"`
Devices []usbEntry `json:"devices,omitempty"`
Session *sessionUI `json:"session,omitempty"`
ScanError string `json:"scan_error,omitempty"`
Scanning bool `json:"scanning"`
}
func main() {
host := pluginsdk.New()
p := &plugin{host: host}
host.Handle("command/invoke", p.command)
if err := host.Serve(context.Background()); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func (p *plugin) text(en, zh string) string {
if strings.HasPrefix(strings.ToLower(p.host.InitInfo().Locale), "zh") {
return zh
}
return en
}
func (p *plugin) directories() (root, data string, err error) {
info := p.host.InitInfo()
data = filepath.Clean(info.DataDir)
plugData := filepath.Dir(data)
plugins := filepath.Dir(plugData)
if info.PluginID != pluginID || !filepath.IsAbs(data) || filepath.Base(data) != pluginID ||
filepath.Base(plugData) != "data" || filepath.Base(plugins) != "plugins" {
return "", "", errors.New(p.text("The plugin data folder is unavailable.", "无法访问插件数据目录。"))
}
return filepath.Dir(plugins), data, nil
}
func (p *plugin) command(ctx context.Context, body json.RawMessage) (any, error) {
var req struct {
Command string `json:"command"`
Args commandArgs `json:"args"`
}
if err := json.Unmarshal(body, &req); err != nil {
return nil, err
}
root, data, err := p.directories()
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
p.mu.Lock()
defer p.mu.Unlock()
var cfg settings
if err := readJSON(filepath.Join(data, "settings.json"), &cfg); err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, err
}
tools, toolsErr := resolveBundle(cfg.Path)
session, err := p.sessionStatus(ctx, data)
if err != nil {
return nil, err
}
result := response{Path: cfg.Path, Ready: toolsErr == nil, Session: session}
if toolsErr == nil && p.scan != nil && p.scan.root == tools.Root {
result.Devices, result.Scanning = p.scan.devices, p.scan.running
if p.scan.failed {
result.ScanError = p.text("Could not scan Windows USB devices. Check the Windows USB helper.",
"无法扫描 Windows USB 设备,检查 Windows USB 助手后重试。")
}
}
switch req.Command {
case "status":
return result, nil
case "scan":
result.VMs, err = p.listVMs(ctx, root)
if err != nil {
return nil, err
}
if toolsErr == nil {
p.startScan(tools)
result.Scanning = true
result.ScanError = ""
}
return result, nil
case "configure":
if session != nil && session.Active {
return nil, errors.New(p.text("Release the current USB session before changing the helper folder.",
"释放当前 USB 会话后再更改助手目录。"))
}
newTools, err := resolveBundle(req.Args.Path)
if err != nil {
return nil, errors.New(p.text("Choose the preview kit folder that contains a complete Windows-USB helper.",
"选择包含完整 Windows-USB 助手的预览包目录。"))
}
cfg.Path = newTools.Root
if err := atomicfile.WriteJSON(filepath.Join(data, "settings.json"), cfg, 0o600); err != nil {
return nil, err
}
p.scan = nil
return response{Path: cfg.Path, Ready: true, Session: session}, nil
case "attach":
if session != nil && session.Active {
return nil, errors.New(p.text("Release the current USB session first.", "先释放当前 USB 会话。"))
}
if toolsErr != nil {
return nil, errors.New(p.text("Set the Windows USB helper folder first.", "先设置 Windows USB 助手目录。"))
}
return p.attach(ctx, root, data, tools, req.Args, session)
case "release":
if session == nil || !session.Active {
return session, nil
}
if err := requestRelease(data, session.record.Dir); err != nil {
return nil, err
}
session.CancelRequested = true
return session, nil
default:
return nil, errors.New(p.text("Unknown USB action.", "无法识别该 USB 操作。"))
}
}
+324
View File
@@ -0,0 +1,324 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Native USB Passthrough</title>
<style>
* { box-sizing: border-box; }
body { margin: 0; background: var(--surface-0, Canvas); color: var(--text, CanvasText); font: 13px/1.45 var(--font-sans, system-ui); }
main { display: grid; gap: 13px; padding: 14px; }
.field { min-width: 0; display: grid; gap: 5px; }
.field > span, .device-name { font-weight: 600; }
.line { display: grid; align-items: end; grid-template-columns: minmax(0, 1fr) max-content; gap: 8px; }
input[type="text"], select, button { min-width: 0; min-height: 34px; padding: 5px 10px; color: inherit; font: inherit; border: 1px solid var(--border, GrayText); border-radius: 7px; background: var(--surface-0, Canvas); }
input[type="text"], select { width: 100%; }
button { cursor: pointer; }
button:disabled, input:disabled, select:disabled { opacity: .57; cursor: default; }
:focus-visible { outline: 2px solid var(--accent, Highlight); outline-offset: 2px; }
.status, .empty { margin: 0; padding: 10px 11px; overflow-wrap: anywhere; }
.status { background: var(--surface-1, Canvas); border: 1px solid var(--border, GrayText); border-radius: 8px; }
.status:empty, .feedback:empty { display: none; }
.status[data-phase="attached"] { border-inline-start: 3px solid var(--accent, Highlight); }
.status[data-phase="error"] { border-inline-start: 3px solid var(--danger, #db4b54); }
.status-head { display: block; font-weight: 600; }
.status-detail, .device-detail, .empty { color: var(--text-2, GrayText); font-size: 12px; }
.devices { max-height: 166px; overflow: auto; border: 1px solid var(--border, GrayText); border-radius: 8px; }
.device { display: grid; grid-template-columns: 18px minmax(0, 1fr); align-items: center; gap: 10px; min-height: 49px; padding: 7px 11px; }
.device + .device { border-top: 1px solid var(--border, GrayText); }
.device input { width: 17px; height: 17px; margin: 0; accent-color: var(--accent, Highlight); }
.device-label > span { display: block; overflow-wrap: anywhere; }
.feedback { margin: 0; color: var(--danger, #b6444a); overflow-wrap: anywhere; }
</style>
</head>
<body>
<main>
<div class="line">
<label class="field">
<span data-text="folder">Windows USB helper folder</span>
<input id="folder" type="text" placeholder="D:\Reims USB Preview\Windows-USB" spellcheck="false">
</label>
<button id="save" data-text="save">Save</button>
</div>
<div class="line">
<label class="field">
<span data-text="vm">Virtual machine</span>
<select id="vm"></select>
</label>
<button id="refresh" data-text="refresh">Refresh</button>
</div>
<div class="devices" id="devices" aria-label="USB devices"></div>
<div id="status" class="status" role="status"></div>
<p id="feedback" class="feedback" role="alert"></p>
</main>
<script>
'use strict';
// Panel bridge pattern adapted from mango6i's Apache-2.0 v0.1.0-beta.6.
const strings = {
en: {
folder: 'Windows USB helper folder', save: 'Save', vm: 'Virtual machine', refresh: 'Refresh',
devices: 'USB devices', chooseVM: 'Choose a running virtual machine', offline: 'Not running',
setFolder: 'Set the folder containing the Windows USB helper.', noDevices: 'No USB devices found.',
scanning: 'Scanning Windows USB devices…',
notAvailable: 'Unavailable', unnamed: 'USB device', port: 'Port {port}',
starting: 'Starting helper', replug: 'Reconnect USB device', attaching: 'Connecting to virtual machine',
attached: 'Connected', releasing: 'Releasing device', unplug: 'Unplug USB device',
released: 'Released to Windows', error: 'USB session ended with an error',
replugHelp: 'Unplug the device, wait two seconds, then plug it into the same port.',
unplugHelp: 'Unplug the device and leave it disconnected until Windows restoration finishes.',
startHelp: 'Approve the Windows prompt if it appears.',
cancel: 'Release requested.', selectToConnect: 'Select a device to connect it to this VM.',
timeout: 'Reims-Go did not respond.', failure: 'The USB operation failed.'
},
zh: {
folder: 'Windows USB 助手目录', save: '保存', vm: '虚拟机', refresh: '刷新',
devices: 'USB 设备', chooseVM: '选择正在运行的虚拟机', offline: '未运行',
setFolder: '设置包含 Windows USB 助手的目录。', noDevices: '未发现 USB 设备。',
scanning: '正在扫描 Windows USB 设备…',
notAvailable: '不可用', unnamed: 'USB 设备', port: '端口 {port}',
starting: '正在启动助手', replug: '重新插入 USB 设备', attaching: '正在连接到虚拟机',
attached: '已连接', releasing: '正在释放设备', unplug: '拔出 USB 设备',
released: '已交还 Windows', error: 'USB 会话发生错误',
replugHelp: '拔出设备,等待两秒后插回同一端口。',
unplugHelp: '拔出设备,等待 Windows 驱动恢复完成后再插入。',
startHelp: '如出现 Windows 权限提示,确认后继续。',
cancel: '已请求释放。', selectToConnect: '勾选设备即可连接到此虚拟机。',
timeout: 'Reims-Go 未响应。', failure: 'USB 操作失败。'
}
};
const folder = document.getElementById('folder');
const vm = document.getElementById('vm');
const save = document.getElementById('save');
const refresh = document.getElementById('refresh');
const deviceList = document.getElementById('devices');
const statusBox = document.getElementById('status');
const feedback = document.getElementById('feedback');
const pending = new Map();
let lang = 'en';
let serial = 0;
let started = false;
let busy = false;
let polling = false;
let revision = 0;
let pathDirty = false;
let ready = false;
let vms = [];
let devices = [];
let session = null;
let scanError = '';
let scanning = false;
function tr(key, values = {}) {
return (strings[lang][key] || strings.en[key] || key)
.replace(/\{(\w+)\}/g, (part, name) => values[name] ?? part);
}
function invoke(command, args = {}) {
return new Promise((resolve, reject) => {
const id = String(++serial);
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error(tr('timeout')));
}, 26000);
pending.set(id, {resolve, reject, timer});
parent.postMessage({type: 'reims:rpc', id, method: 'command.invoke', params: {command, args}}, '*');
});
}
function chooseVMs() {
const selected = session?.active ? session.vm.vm : vm.value;
vm.replaceChildren(new Option(tr('chooseVM'), ''));
for (const entry of vms) {
const option = new Option(entry.state === 'running' ? entry.name : entry.name + ' · ' + tr('offline'), entry.vm);
option.disabled = entry.state !== 'running';
vm.add(option);
}
if (session?.active && !vms.some((entry) => entry.vm === selected)) {
vm.add(new Option(session.vm.name, session.vm.vm));
}
if (Array.from(vm.options).some((option) => option.value === selected)) vm.value = selected;
if (!vm.value && !session?.active) {
const available = vms.filter((entry) => entry.state === 'running');
if (available.length === 1) vm.value = available[0].vm;
}
}
function syncState(result) {
if (!pathDirty) folder.value = result.path || '';
ready = result.ready;
session = result.session || null;
devices = result.devices || [];
scanError = result.scan_error || '';
scanning = result.scanning;
}
async function scan() {
const result = await invoke('scan');
syncState(result);
vms = result.vms || [];
chooseVMs();
}
function deviceRow(device) {
const row = document.createElement('label');
row.className = 'device';
const box = document.createElement('input');
box.type = 'checkbox';
box.dataset.device = device.key;
box.checked = !!session?.active && session.device.key === device.key &&
session.phase !== 'released' && session.phase !== 'error';
box.disabled = busy || (box.checked
? session.cancel_requested || session.phase === 'releasing' || session.phase === 'unplug'
: !!session?.active || scanning || !ready || !vm.value || !device.eligible);
box.addEventListener('change', () => act(async () => {
session = box.checked
? await invoke('attach', {vm: vm.value, key: device.key})
: await invoke('release');
}));
const caption = document.createElement('span');
caption.className = 'device-label';
const name = document.createElement('span');
name.className = 'device-name';
name.textContent = device.name || tr('unnamed');
const detail = document.createElement('span');
detail.className = 'device-detail';
detail.textContent = [device.vid && device.pid && device.vid + ':' + device.pid,
device.port > 0 && tr('port', {port: device.port}),
!device.eligible && (device.reason || tr('notAvailable'))].filter(Boolean).join(' · ');
caption.append(name, detail);
row.append(box, caption);
return row;
}
function renderDevices() {
const focus = document.activeElement?.dataset.device;
let rows = devices;
if (session?.active && !rows.some((device) => device.key === session.device.key)) {
rows = [session.device, ...rows];
}
if (!rows.length) {
const empty = document.createElement('p');
empty.className = 'empty';
empty.textContent = scanError || tr(scanning ? 'scanning' : ready ? 'noDevices' : 'setFolder');
deviceList.replaceChildren(empty);
return;
}
deviceList.replaceChildren(...rows.map(deviceRow));
for (const box of deviceList.querySelectorAll('input')) {
if (box.dataset.device === focus && !box.disabled) box.focus({preventScroll: true});
}
}
function renderStatus() {
statusBox.replaceChildren();
statusBox.dataset.phase = session?.phase || '';
if (!session) {
if (ready && vm.value && devices.some((device) => device.eligible)) {
statusBox.textContent = tr('selectToConnect');
}
return;
}
const heading = document.createElement('span');
heading.className = 'status-head';
heading.textContent = tr(session.phase) + ' · ' + session.vm.name;
const detail = document.createElement('span');
detail.className = 'status-detail';
const message = session.phase === 'replug' ? tr('replugHelp')
: session.phase === 'unplug' ? tr('unplugHelp')
: session.phase === 'starting' ? tr('startHelp')
: session.phase === 'error' ? session.message
: session.cancel_requested && session.active ? tr('cancel') : '';
detail.textContent = message || '';
statusBox.append(heading, detail);
}
function render() {
folder.disabled = busy || !!session?.active;
save.disabled = busy || !!session?.active || !folder.value.trim();
refresh.disabled = busy || scanning;
vm.disabled = busy || !!session?.active || vms.length === 0;
renderDevices();
renderStatus();
}
async function act(task) {
if (busy) return;
busy = true;
revision++;
feedback.textContent = '';
render();
try {
await task();
} catch (error) {
feedback.textContent = error.message || tr('failure');
try {
syncState(await invoke('status'));
} catch (statusError) {
feedback.textContent += ' ' + (statusError.message || tr('failure'));
}
} finally {
busy = false;
render();
}
}
window.addEventListener('message', (event) => {
if (event.source !== parent || !event.data) return;
const message = event.data;
if (message.type === 'reims:theme') {
lang = /^zh/i.test(message.locale || '') ? 'zh' : 'en';
document.documentElement.lang = message.locale || 'en';
document.documentElement.dir = message.dir || 'ltr';
document.documentElement.style.colorScheme = message.appearance === 'dark' ? 'dark' : 'light';
for (const [key, value] of Object.entries(message.tokens || {})) {
if (value && key.startsWith('--')) document.documentElement.style.setProperty(key, value);
}
for (const item of document.querySelectorAll('[data-text]')) item.textContent = tr(item.dataset.text);
deviceList.setAttribute('aria-label', tr('devices'));
chooseVMs();
render();
if (!started) {
started = true;
void act(scan);
}
}
if (message.type === 'reims:rpc-result' && pending.has(message.id)) {
const request = pending.get(message.id);
pending.delete(message.id);
clearTimeout(request.timer);
if (message.ok) request.resolve(message.result);
else request.reject(new Error(message.error || tr('failure')));
}
});
folder.addEventListener('input', () => { pathDirty = true; render(); });
save.addEventListener('click', () => {
void act(async () => {
const result = await invoke('configure', {path: folder.value});
pathDirty = false;
syncState(result);
await scan();
});
});
refresh.addEventListener('click', () => { void act(scan); });
vm.addEventListener('change', render);
setInterval(async () => {
if (!started || busy || polling || (!session?.active && !scanning)) return;
polling = true;
const before = revision;
try {
const result = await invoke('status');
if (!busy && revision === before) {
syncState(result);
render();
}
} catch (error) {
if (!busy && revision === before) feedback.textContent = error.message || tr('failure');
} finally {
polling = false;
}
}, 1000);
render();
</script>
</body>
</html>
+31
View File
@@ -0,0 +1,31 @@
{
"schema": 1,
"id": "reimscommunity.usb-redir",
"version": "0.1.0-alpha.1",
"name": {"zh-CN": "USB 直通(原生)", "en-US": "Native USB Passthrough"},
"description": {
"zh-CN": "将可用的 Windows USB 设备连接到运行中的 Reims 虚拟机。",
"en-US": "Connect available Windows USB devices to a running Reims virtual machine."
},
"license": "Apache-2.0",
"engines": {"reims-go": ">=0.2.12", "pluginApi": "^1.0.0", "uiApi": "^1.0.0 || ^2.0.0", "bridgeApi": "^1.0.0"},
"platforms": ["windows-x64"],
"entry": {"sidecar": "reims-usb-redir.exe", "panelDir": "panel"},
"permissions": ["vm:read", "ui:slot", "fs:plugin_data", "process:spawn"],
"contributes": {
"panels": [{
"id": "usb-redir",
"slot": "settings.plugin",
"title": {"zh-CN": "USB 直通(原生)", "en-US": "Native USB Passthrough"},
"entry": "usb.html",
"height": 440
}],
"commands": [
{"id": "status", "title": {"zh-CN": "查看 USB 会话", "en-US": "View USB session"}},
{"id": "scan", "title": {"zh-CN": "刷新 USB 设备", "en-US": "Refresh USB devices"}},
{"id": "configure", "title": {"zh-CN": "设置 Windows USB 助手目录", "en-US": "Set Windows USB helper folder"}},
{"id": "attach", "title": {"zh-CN": "连接 USB 设备", "en-US": "Connect USB device"}},
{"id": "release", "title": {"zh-CN": "释放 USB 设备", "en-US": "Release USB device"}}
]
}
}
+193
View File
@@ -0,0 +1,193 @@
//go:build windows
// SPDX-License-Identifier: Apache-2.0
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/atomicfile"
)
const (
activeFile = "session.json"
stateFile = "state.json"
cancelFile = "cancel.request"
)
type sessionRecord struct {
Dir string `json:"dir"`
VM vmEntry `json:"vm"`
Device usbEntry `json:"device"`
PID int `json:"pid"`
Started time.Time `json:"started"`
}
type helperState struct {
Phase string `json:"phase"`
Message string `json:"message"`
PID int `json:"pid"`
DescriptorRead bool `json:"descriptor_read"`
}
type sessionUI struct {
VM vmEntry `json:"vm"`
Device usbEntry `json:"device"`
Active bool `json:"active"`
CancelRequested bool `json:"cancel_requested"`
helperState
record sessionRecord
}
func readJSON(path string, out any) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
const limit = 256 * 1024
raw, err := io.ReadAll(io.LimitReader(f, limit+1))
if err != nil {
return err
}
if len(raw) > limit {
return errors.New("USB plugin state file is too large")
}
return json.Unmarshal(raw, out)
}
func sessionDir(data, name string) (string, error) {
if filepath.Base(name) != name || !strings.HasPrefix(name, "usb-session-") || strings.ContainsAny(name, ":\\/") {
return "", errors.New("invalid USB session folder")
}
return filepath.Join(data, name), nil
}
func requestRelease(data, name string) error {
dir, err := sessionDir(data, name)
if err != nil {
return err
}
file, err := os.OpenFile(filepath.Join(dir, cancelFile), os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
return err
}
return file.Close()
}
func terminal(phase string) bool {
return phase == "released" || phase == "error"
}
func (p *plugin) sessionStatus(ctx context.Context, data string) (*sessionUI, error) {
var saved sessionRecord
if err := readJSON(filepath.Join(data, activeFile), &saved); err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
return nil, err
}
dir, err := sessionDir(data, saved.Dir)
if err != nil {
return nil, err
}
result := &sessionUI{VM: saved.VM, Device: saved.Device, record: saved}
if err := readJSON(filepath.Join(dir, stateFile), &result.helperState); err != nil {
if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
result.Phase = "starting"
}
_, markerErr := os.Stat(filepath.Join(dir, cancelFile))
result.CancelRequested = markerErr == nil
pid := saved.PID
if pid == 0 {
pid = result.PID
}
if pid > 0 {
running, err := p.host.IsVMProcessRunning(ctx, pid)
result.Active = running || err != nil
} else {
// A process launch and its PID receipt are separate operations. The
// state file can identify a helper that starts across a sidecar restart.
result.Active = !terminal(result.Phase) && time.Since(saved.Started) < 30*time.Second
}
if !result.Active && !terminal(result.Phase) {
result.Phase = "error"
result.Message = p.text("The helper stopped before reporting a release. Check Windows driver recovery.",
"助手退出前未报告释放结果,检查 Windows 驱动恢复状态。")
}
return result, nil
}
func (p *plugin) attach(ctx context.Context, root, data string, tools helperBundle, args commandArgs,
previous *sessionUI) (*sessionUI, error) {
vm, vmDir, monitor, err := p.resolveVM(ctx, root, args.VM)
if err != nil {
return nil, err
}
if p.scan == nil || p.scan.root != tools.Root || p.scan.failed {
return nil, errors.New(p.text("Refresh the Windows USB device list and try again.", "刷新 Windows USB 设备列表后重试。"))
}
var device usbEntry
for _, item := range p.scan.devices {
if item.Key != args.Key || item.Key == "" || !item.Eligible {
continue
}
if device.Key != "" {
return nil, errors.New(p.text("USB device selection is ambiguous.", "无法唯一确定所选 USB 设备。"))
}
device = item
}
if device.Key == "" {
return nil, errors.New(p.text("The selected USB device is unavailable.", "所选 USB 设备已不可用。"))
}
dir, err := os.MkdirTemp(data, "usb-session-")
if err != nil {
return nil, err
}
saved := sessionRecord{Dir: filepath.Base(dir), VM: vm, Device: device, Started: time.Now()}
receipt := filepath.Join(data, activeFile)
if err := atomicfile.WriteJSON(receipt, saved, 0o600); err != nil {
_ = os.Remove(dir)
return nil, err
}
argv := []string{"-B", tools.Script, "--vm-dir", vmDir, "--qmp", monitor, "--relay", tools.Relay,
"--driver-dir", tools.Driver, "--device=" + device.Key, "--session-dir", dir}
pid, err := p.host.SpawnVMProcess(ctx, saved.Dir, tools.Python, argv, tools.Root, tools.env())
if err != nil || pid <= 0 {
// Cancel by file in case the launch succeeded but its reply was lost.
// Keep the record available to the panel while the helper settles.
return nil, errors.Join(fmt.Errorf("%s", p.text("Could not start the Windows USB helper.", "无法启动 Windows USB 助手。")),
requestRelease(data, saved.Dir))
}
saved.PID = pid
if err := atomicfile.WriteJSON(receipt, saved, 0o600); err != nil {
return nil, errors.Join(err, requestRelease(data, saved.Dir))
}
if previous != nil {
removeFinishedSession(data, previous.record.Dir)
}
return &sessionUI{VM: vm, Device: device, Active: true,
helperState: helperState{Phase: "starting", PID: pid}, record: saved}, nil
}
func removeFinishedSession(data, name string) {
dir, err := sessionDir(data, name)
if err != nil {
return
}
for _, file := range []string{stateFile, cancelFile} {
_ = os.Remove(filepath.Join(dir, file))
}
_ = os.Remove(dir)
}
+145
View File
@@ -0,0 +1,145 @@
//go:build windows
// SPDX-License-Identifier: Apache-2.0
package main
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strconv"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/atomicfile"
"github.com/Nwflower/reims-go/pkg/pluginsdk"
)
type fakeHost struct {
platformHost
running bool
pid int
err error
}
func (h *fakeHost) InitInfo() pluginsdk.InitInfo {
return pluginsdk.InitInfo{Locale: "en-US"}
}
func (h *fakeHost) IsVMProcessRunning(_ context.Context, pid int) (bool, error) {
h.pid = pid
return h.running, h.err
}
func TestSessionStateAndNormalRelease(t *testing.T) {
data := t.TempDir()
dir, err := os.MkdirTemp(data, "usb-session-")
if err != nil {
t.Fatal(err)
}
record := sessionRecord{Dir: filepath.Base(dir), VM: vmEntry{Name: "tahoe"},
Device: usbEntry{Key: "opaque", Name: "USB device"}, PID: 42, Started: time.Now()}
if err := atomicfile.WriteJSON(filepath.Join(data, activeFile), record, 0o600); err != nil {
t.Fatal(err)
}
if err := atomicfile.WriteJSON(filepath.Join(dir, stateFile), helperState{Phase: "attached", PID: 42, DescriptorRead: true}, 0o600); err != nil {
t.Fatal(err)
}
host := &fakeHost{running: true}
p := &plugin{host: host}
result, err := p.sessionStatus(context.Background(), data)
if err != nil || !result.Active || result.Phase != "attached" || !result.DescriptorRead || host.pid != 42 {
t.Fatalf("unexpected active session: %+v, %v", result, err)
}
if err := requestRelease(data, record.Dir); err != nil {
t.Fatal(err)
}
content, err := os.ReadFile(filepath.Join(dir, cancelFile))
if err != nil || len(content) != 0 {
t.Fatalf("cancel file: %q, %v", content, err)
}
result, err = p.sessionStatus(context.Background(), data)
if err != nil || !result.Active || !result.CancelRequested || result.Phase != "attached" {
t.Fatalf("request must not fabricate a release: %+v, %v", result, err)
}
host.err = errors.New("host temporarily unavailable")
result, err = p.sessionStatus(context.Background(), data)
if err != nil || !result.Active {
t.Fatalf("unknown helper liveness must keep the session active: %+v, %v", result, err)
}
host.err, host.running = nil, false
result, err = p.sessionStatus(context.Background(), data)
if err != nil || result.Active || result.Phase != "error" {
t.Fatalf("unexpected interrupted state: %+v, %v", result, err)
}
if err := atomicfile.WriteJSON(filepath.Join(dir, stateFile), helperState{Phase: "released"}, 0o600); err != nil {
t.Fatal(err)
}
result, err = p.sessionStatus(context.Background(), data)
if err != nil || result.Active || result.Phase != "released" {
t.Fatalf("unexpected terminal state: %+v, %v", result, err)
}
}
func TestResolveBundleAcceptsKitOrHelperFolder(t *testing.T) {
kit := t.TempDir()
root := filepath.Join(kit, "Windows-USB")
for _, path := range []string{"deps/python/python.exe", "deps/powershell/pwsh.exe", "scripts/attach.py",
"scripts/qmp-relay.exe", "deps/libusb-win32/bin/amd64/libusb0.sys", "deps/libusb-win32/bin/amd64/libusb0.dll"} {
file := filepath.Join(root, path)
if err := os.MkdirAll(filepath.Dir(file), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(file, []byte("fixture"), 0o600); err != nil {
t.Fatal(err)
}
}
for _, path := range []string{kit, root} {
b, err := resolveBundle(path)
if err != nil || b.Root != root || filepath.Base(b.Driver) != "amd64" {
t.Fatalf("unexpected bundle: %+v, %v", b, err)
}
}
if _, err := resolveBundle(filepath.Join(kit, "absent")); err == nil {
t.Fatal("missing bundle was accepted")
}
}
type unavailableVMList struct {
platformHost
err error
}
func (h unavailableVMList) CallHost(_ context.Context, _ string, _, _ any) error {
return h.err
}
func TestLegacyVMListRejectsUnrelatedPID(t *testing.T) {
root := t.TempDir()
dir := filepath.Join(root, "fake-vm")
registry := filepath.Join(root, "config", "reims-ctl")
for _, path := range []string{dir, registry} {
if err := os.MkdirAll(path, 0o700); err != nil {
t.Fatal(err)
}
}
vm := fmt.Sprintf("[[vm]]\nname = \"fixture\"\ndir = %q\n", filepath.ToSlash(dir))
if err := os.WriteFile(filepath.Join(registry, "vms.toml"), []byte(vm), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "qemu.pid"), []byte(strconv.Itoa(os.Getpid())), 0o600); err != nil {
t.Fatal(err)
}
p := &plugin{host: unavailableVMList{err: errors.New("rpc error -32000: method not found: host/vm.list")}}
list, err := p.listVMs(context.Background(), root)
if err != nil || len(list) != 1 || list[0].Name != "fixture" || list[0].State != "stopped" {
t.Fatalf("unexpected legacy inventory: %+v, %v", list, err)
}
p.host = unavailableVMList{err: errors.New("permission denied")}
if _, err := p.listVMs(context.Background(), root); err == nil {
t.Fatal("permission error must not trigger local inventory fallback")
}
}