feat: offer macOS app windows as an optional built-in plugin

This commit is contained in:
YXC0915 committed 2026-12-03 08:20:01 +08:00
1 parent 619ac88297
commit b21a353b28
23 files changed
+507 -162

No files matched your search

+2 -2
View File
@@ -2,6 +2,6 @@
"group": "new",
"order": 0,
"authors": ["yxc0915"],
"zh": "可在 Windows 无边框独立窗口中操作 macOS 虚拟机的前台应用,并在宿主与客体之间复制粘贴。",
"en": "Interact with the foreground app of a running macOS VM in a separate borderless Windows window with bidirectional copy and paste."
"zh": "启用「macOS 应用窗口」内置插件后,可在 Windows 无边框窗口中操作虚拟机的前台应用,并在宿主与客体之间复制粘贴。",
"en": "Enable the built-in macOS App Windows plugin to use a VM’s foreground app in a borderless Windows window with bidirectional copy and paste."
}
+1 -1
View File
@@ -24,7 +24,7 @@
| 正在创建 | 无(展示分步进度) | 取消创建 |
| 已停止 | 启动 | 设置、恢复点、派生副本、磁盘扩容与空间回收、打开目录、删除 |
| 正在启动 | 启动中(忙碌禁用) | 设置、强制关机 |
| 运行中 | 显示虚拟机窗口 | 打开独立应用窗口(需 Guest Tools)、挂起(需运行时支持)、关机、截屏、设置、重启、强制关机、发送文本、恢复模式切换、导出排障包 |
| 运行中 | 显示虚拟机窗口 | 打开独立应用窗口(需启用 macOS 应用窗口插件并连接 Guest Tools)、挂起(需运行时支持)、关机、截屏、设置、重启、强制关机、发送文本、恢复模式切换、导出排障包 |
| 正在停止 | 停止中(忙碌禁用) | 强制关机 |
| 正在挂起 | 挂起中(忙碌禁用) | 强制关机 |
| 已挂起 | 恢复(需运行时支持) | 放弃挂起状态(需破坏性操作确认)、打开目录 |
+2
View File
@@ -32,6 +32,8 @@ flowchart TB
内置虚拟机交互服务默认启用,通过宿主控制台代理串行处理每台虚拟机的 QMP 操作,每次操作后关闭连接,并与虚拟机生命周期操作共用锁。桌面文本输入期间暂停后台缩略图捕获。该服务不实现 MCP 协议。
内置 macOS 应用窗口插件默认关闭,依赖 Guest Tools 传输与虚拟机交互服务。用户启用后可在运行中的 macOS 虚拟机操作菜单中打开前台应用窗口。停用插件会移除操作入口并关闭独立窗口。
L3 插件可在清单 `contributes.channels` 中声明 `jsonl` 通道。桌面端的 `plugin connect` 经 Windows 当前用户限定的命名管道转发消息,不开放 TCP 或 HTTP MCP 监听。官方 MCP 插件实现工具、虚拟机状态与桌面控制,以及通过 SSH/SFTP 的客体命令和文件传输。
Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 VM 目录。读取 VM 状态要求 `vm:read`,截图要求 `vm:screen`,输入要求 `qmp:write`,VM 启停要求 `vm:control`。Host API 审核插件权限并记录方法名,不把输入文本写入审计日志。开机、登录和切换显示时画面可能是纯色,此时截图照常返回该帧并标记 `blank`,插件据此继续等待,而不是当作失败。登录密码由 Windows DPAPI 保护,宿主只提供按设置键名键入的操作,不向 MCP 插件返回明文。插件自己的下载器敏感设置仅在下载请求中解密并传给该插件进程。
+31 -28
View File
@@ -11,7 +11,7 @@ import { TitleMenus } from './components/TitleMenus'
import { UpdateCapsule, UpdatePhase } from './components/UpdateCapsule'
import { DataRootReadOnly } from './components/DataRootReadOnly'
import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar'
import { VMAction, VMPage } from './components/VMPage'
import { VMAction, VMBusyAction, VMPage } from './components/VMPage'
import { buildFallbackChain, I18nKey, localeDir, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format'
import { LogLine, appendLog } from './lib/logs'
@@ -44,7 +44,7 @@ const AboutPage = lazy(() => import('./components/AboutPage').then((m) => ({ def
const errText = (e: unknown) => parseAppError(e).summary
const failKey: Record<VMAction, I18nKey> = {
const failKey: Record<VMBusyAction, I18nKey> = {
start: 'failStart',
suspend: 'failSuspend',
resume: 'failResume',
@@ -52,7 +52,7 @@ const failKey: Record<VMAction, I18nKey> = {
focus: 'failFocus',
fullscreen: 'failFullscreen',
screenshot: 'failScreenshot',
appWindow: 'failOpenAppWindow',
pluginCommand: 'failGeneric',
stop: 'failStop',
forceStop: 'failStop',
restart: 'failRestart',
@@ -98,8 +98,8 @@ export const App: React.FC = () => {
const [cloneSource, setCloneSource] = useState<{ name: string; driverID: string } | null>(null)
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
const [sendTextTarget, setSendTextTarget] = useState<string | null>(null)
const [busy, setBusy] = useState<Record<string, VMAction>>({})
const busyOpsRef = useRef<Map<string, Map<number, VMAction>>>(new Map())
const [busy, setBusy] = useState<Record<string, VMBusyAction>>({})
const busyOpsRef = useRef<Map<string, Map<number, VMBusyAction>>>(new Map())
const nextBusyTokenRef = useRef(0)
const [dropping, setDropping] = useState(false)
const [loadError, setLoadError] = useState('')
@@ -218,17 +218,7 @@ export const App: React.FC = () => {
}, [])
useEffect(() => {
Promise.all([
api.GetPluginUIContributions().catch(() => null),
refresh(),
]).then(([pui]) => {
if (pui) {
setPluginLocales(pui.locales)
setPluginUI(pui)
} else {
setPluginUI({} as PluginUIContributions)
}
})
void refresh()
events.emitUIPong()
const offPing = events.onUIPing(() => { events.emitUIPong() })
const offState = events.onStateChanged(() => {
@@ -245,7 +235,6 @@ export const App: React.FC = () => {
}
setLogLines((prev) => appendLog(prev, entry))
})
api.GetActiveTheme().then(setActiveThemePayload).catch((e) => console.warn('[app] GetActiveTheme failed:', e))
// Tasks: seed from the backend, then follow events.
api.GetTasks().then((list) => {
setTaskMap((prev) => (list ?? []).reduce(upsertTask, prev))
@@ -557,10 +546,19 @@ export const App: React.FC = () => {
}
}, [taskMap])
// Apply active theme pack (zero extra CSS for builtin default theme).
// Refresh contributions together with the active theme after registry changes.
useEffect(() => {
api.GetActiveTheme().then(setActiveThemePayload).catch((e) => console.warn('[app] GetActiveTheme failed:', e))
api.GetPluginUIContributions().then(setPluginUI).catch((e) => console.warn('[app] GetPluginUIContributions failed:', e))
let live = true
api.GetActiveTheme().then((theme) => {
if (live) setActiveThemePayload(theme)
}).catch((e) => console.warn('[app] GetActiveTheme failed:', e))
api.GetPluginUIContributions().then((contributions) => {
if (live) setPluginUI(contributions)
}).catch((e) => {
console.warn('[app] GetPluginUIContributions failed:', e)
if (live) setPluginUI((previous) => previous ?? {} as PluginUIContributions)
})
return () => { live = false }
}, [themeRevision, state?.safe_mode])
useEffect(() => {
@@ -621,25 +619,25 @@ export const App: React.FC = () => {
if (ack.status === 'failed') fail(tr('failDrop'), ack.error || '')
}
const activeVMBusy = (name: string): VMAction | undefined => {
const activeVMBusy = (name: string): VMBusyAction | undefined => {
const ops = busyOpsRef.current.get(name)
if (!ops || ops.size === 0) return undefined
let latest: VMAction | undefined
let latest: VMBusyAction | undefined
for (const act of ops.values()) latest = act
return latest
}
const syncBusyState = () => {
const next: Record<string, VMAction> = Object.create(null)
const next: Record<string, VMBusyAction> = Object.create(null)
for (const [vmName, ops] of busyOpsRef.current) {
let latest: VMAction | undefined
let latest: VMBusyAction | undefined
for (const act of ops.values()) latest = act
if (latest) next[vmName] = latest
}
setBusy(next)
}
const beginVMBusy = (name: string, action: VMAction): number | null => {
const beginVMBusy = (name: string, action: VMBusyAction): number | null => {
const ops = busyOpsRef.current.get(name)
if (ops && ops.size > 0) {
if (action !== 'forceStop') return null
@@ -648,7 +646,7 @@ export const App: React.FC = () => {
}
}
const token = ++nextBusyTokenRef.current
const vmOps = ops ?? new Map<number, VMAction>()
const vmOps = ops ?? new Map<number, VMBusyAction>()
vmOps.set(token, action)
busyOpsRef.current.set(name, vmOps)
syncBusyState()
@@ -662,7 +660,7 @@ export const App: React.FC = () => {
syncBusyState()
}
const runVMAction = async (name: string, action: VMAction, fn: () => Promise<void>, okTitle?: string) => {
const runVMAction = async (name: string, action: VMBusyAction, fn: () => Promise<void>, okTitle?: string) => {
const token = beginVMBusy(name, action)
if (token === null) return
try {
@@ -752,7 +750,6 @@ export const App: React.FC = () => {
refreshVMStatsWithDriver(actionDriverID, name, { window_fullscreen: isFullscreen })
})
case 'screenshot': return runVMAction(name, action, () => api.CopyVMScreenshotWithDriver(actionDriverID, name), tr('toastScreenshotCopied'))
case 'appWindow': return runVMAction(name, action, () => api.OpenAppWindow(actionDriverID, name))
case 'stop': return runVMAction(name, action, () => api.StopVMWithDriver(actionDriverID, name, false), tr('toastStopped', { name }))
case 'forceStop': return runVMAction(name, action, () => api.StopVMWithDriver(actionDriverID, name, true), tr('toastStopped', { name }))
case 'restart': return runVMAction(name, action, () => api.RestartVMWithDriver(actionDriverID, name))
@@ -1238,6 +1235,12 @@ export const App: React.FC = () => {
pending={pending}
busyAction={Object.prototype.hasOwnProperty.call(busy, selectedVM.name) ? busy[selectedVM.name] : undefined}
onAction={onVMAction}
onPluginCommand={(pluginID, command, title) => {
const name = selectedVM.name
void runVMAction(name, 'pluginCommand', async () => {
await api.InvokePluginCommand(pluginID, command, { vm: name })
}, title)
}}
onSettings={() => setShowSettings(true)}
onOpenAffinity={() => setAffinityTarget({ name: selectedVM.name, driverID: selectedVM.driver_id ?? '' })}
onDelete={() => setDeleteTarget(selectedVM.name)}
+2 -2
View File
@@ -8,7 +8,7 @@ import { vmRefKey } from '../lib/vmRef'
import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
import { VersionArt } from '../macos/VersionArt'
import { BrandMark, HostIcon } from '../ui/themeVisuals'
import { VMAction } from './VMPage'
import type { VMAction, VMBusyAction } from './VMPage'
export const HOST_ID = '__host__'
export const INSTALLERS_ID = '__installers__'
@@ -24,7 +24,7 @@ interface Props {
vms: VMListItem[]
transitions: Record<string, string>
/** VM name → currently running action (disables conflicting context menu actions). */
busyActions?: Record<string, VMAction>
busyActions?: Record<string, VMBusyAction>
selected: string
hostReady: boolean
/** Whether the active runtime supports VM suspend/resume. */
+29 -23
View File
@@ -68,7 +68,6 @@ export type VMAction =
| 'focus'
| 'fullscreen'
| 'screenshot'
| 'appWindow'
| 'eject'
| 'finishInstall'
| 'enterRecovery'
@@ -84,6 +83,8 @@ export type VMAction =
| 'delete'
| 'openFolder'
export type VMBusyAction = VMAction | 'pluginCommand'
// Runs from reims-go's pre-extracted HFS+ helper disk (REIMSHELP), bypassing
// macOS Recovery's `installer -target` fallback to read-only `/` and missing `pkgutil`.
const OFFLINE_INSTALL_CMD = 'sh /Volumes/REIMSHELP/install.sh'
@@ -114,8 +115,9 @@ interface Props {
detail: VMDetail | null
host: HostReport
pending: PendingChange[]
busyAction?: VMAction
busyAction?: VMBusyAction
onAction: (action: VMAction) => void
onPluginCommand: (pluginID: string, command: string, title: string) => void
onSettings: () => void
onOpenAffinity: () => void
onDelete: () => void
@@ -181,7 +183,7 @@ interface Spec {
}
export const VMPage: React.FC<Props> = ({
locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, currentAgentVersion, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI,
locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, currentAgentVersion, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onPluginCommand, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const busy = busyAction !== undefined
@@ -193,6 +195,17 @@ export const VMPage: React.FC<Props> = ({
const installing = !!detail && (detail.has_installer || detail.recovery_mode)
const transitioning = state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming'
const isMacOSDriver = !driverID || driverID === BUILTIN_MACOS_DRIVER
const toolbarMenus = (pluginUI?.menus ?? []).filter(({ slot, when }) => {
if (slot !== 'vm.toolbar') return false
switch (when) {
case undefined:
case '': return true
case 'vm.running': return running
case 'vm.stopped': return state === 'stopped'
case 'vm.macos.running': return running && isMacOSDriver && detail?.name === name && !installing && !guideActive
default: return false
}
})
const canUseHostDNS = !!detail && !installing && !detail.guest_tools_disabled && isMacOSDriver && state !== 'broken'
// Polled here rather than in App so each tick re-renders only this page.
const stats = useVMStats(driverID, name, running)
@@ -593,11 +606,6 @@ export const VMPage: React.FC<Props> = ({
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy} onSelect={() => onAction('screenshot')}>
<HostIcon name="screenshot"><Camera size={14} /></HostIcon> {tr('copyScreenshot')}
</Menu.Item>
{isMacOSDriver && !installing && (
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy} onSelect={() => onAction('appWindow')}>
{tr('openAppWindow')}
</Menu.Item>
)}
<Menu.Separator className="menu-sep" />
</>
)}
@@ -635,21 +643,19 @@ export const VMPage: React.FC<Props> = ({
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy} onSelect={() => onAction('exportDiagnostics')}>
<Archive size={14} /> {tr('exportDiagnostics')}
</Menu.Item>
{(pluginUI?.menus ?? [])
.filter((m) => m.slot === 'vm.toolbar' && (!m.when || (m.when === 'vm.running' ? running : m.when === 'vm.stopped' ? state === 'stopped' : false)))
.map((m) => (
<Menu.Item
key={`${m.pluginId}:${m.id}`}
className="menu-item rg-p-menu-item"
onSelect={() => {
void api.InvokePluginCommand(m.pluginId ?? '', m.command, { vm: name })
.then(() => onToast(locText(m.title, locale, m.id)))
.catch((e) => onError(tr('failGeneric'), e))
}}
>
{locText(m.title, locale, m.id)}
</Menu.Item>
))}
{toolbarMenus.map((m) => {
const title = locText(m.title, locale, m.id)
return (
<Menu.Item
key={`${m.pluginId}:${m.id}`}
className="menu-item rg-p-menu-item"
disabled={busy}
onSelect={() => onPluginCommand(m.pluginId ?? '', m.command, title)}
>
{title}
</Menu.Item>
)
})}
<Menu.Separator className="menu-sep" />
{suspended && (
<Menu.Item className="menu-item rg-p-menu-item danger" disabled={busy} onSelect={() => onAction('discardSuspend')}>
-4
View File
@@ -55,7 +55,6 @@ export const vmZh: Record<string, string> = {
"failFocus": "无法定位虚拟机窗口",
"failFullscreen": "无法切换全屏",
"failGuestTools": "Guest Tools 操作失败",
"failOpenAppWindow": "无法打开独立应用窗口",
"failOpenFolder": "无法打开文件夹",
"failRestart": "重启失败",
"failResume": "恢复失败",
@@ -127,7 +126,6 @@ export const vmZh: Record<string, string> = {
"onlineRecoveryConfirm": "拉取并挂载(约 1 GB)",
"onlineRecoveryDesc": "本地没有恢复镜像。要从 Apple 下载约 1 GB 的恢复镜像并挂载到「{name}」吗?",
"onlineRecoveryTitle": "拉取在线恢复镜像?",
"openAppWindow": "打开独立应用窗口",
"openSharedFolder": "打开共享文件夹",
"openShort": "打开",
"pendingRestartHint": "重启虚拟机后生效",
@@ -290,7 +288,6 @@ export const vmEn: Record<string, string> = {
"failFocus": "Could not focus VM window",
"failFullscreen": "Couldn’t toggle full screen",
"failGuestTools": "Guest Tools operation failed",
"failOpenAppWindow": "Could not open the app window",
"failOpenFolder": "Couldn’t open the folder",
"failRestart": "Couldn’t restart",
"failResume": "Couldn’t resume",
@@ -362,7 +359,6 @@ export const vmEn: Record<string, string> = {
"onlineRecoveryConfirm": "Download \u0026 attach (~1 GB)",
"onlineRecoveryDesc": "No recovery image is on this PC. Download Apple’s recovery image (about 1 GB) and attach it to “{name}”?",
"onlineRecoveryTitle": "Download online recovery image?",
"openAppWindow": "Open app in separate window",
"openSharedFolder": "Open shared folder",
"openShort": "Open",
"pendingRestartHint": "Takes effect after a restart",
-2
View File
@@ -264,7 +264,6 @@ export type I18nKey =
| "failFullscreen"
| "failGeneric"
| "failGuestTools"
| "failOpenAppWindow"
| "failOpenFolder"
| "failRestart"
| "failResume"
@@ -649,7 +648,6 @@ export type I18nKey =
| "onlineRecoveryConfirm"
| "onlineRecoveryDesc"
| "onlineRecoveryTitle"
| "openAppWindow"
| "openFolder"
| "openSharedFolder"
| "openShort"
-2
View File
@@ -214,8 +214,6 @@ export function ListSnapshots(arg1:string):Promise<Array<driver.DiskSnapshot>>;
export function ListSnapshotsWithDriver(arg1:string,arg2:string):Promise<Array<driver.DiskSnapshot>>;
export function OpenAppWindow(arg1:string,arg2:string):Promise<void>;
export function OpenProcessorScheduling():Promise<void>;
export function OpenQQGroup():Promise<void>;
-4
View File
@@ -406,10 +406,6 @@ export function ListSnapshotsWithDriver(arg1, arg2) {
return window['go']['app']['App']['ListSnapshotsWithDriver'](arg1, arg2);
}
export function OpenAppWindow(arg1, arg2) {
return window['go']['app']['App']['OpenAppWindow'](arg1, arg2);
}
export function OpenProcessorScheduling() {
return window['go']['app']['App']['OpenProcessorScheduling']();
}
+1 -3
View File
@@ -111,8 +111,7 @@ type App struct {
stopPoll context.CancelFunc
guestTools *guesttools.Server
guestToolsConfigLocks sync.Map
appWindow *appWindowRun
appWindowClosing bool
appWindowGate sync.Mutex
vmDeleteEpochs map[string]uint64
resolveFolderVolume func(string) (host.DirectoryVolume, error)
imeBridge *host.IMEBridge
@@ -271,7 +270,6 @@ func (a *App) beforeClose(ctx context.Context) bool {
}
func (a *App) shutdown(ctx context.Context) {
a.stopAppWindow()
a.closePacketBridges()
if a.stopPoll != nil {
a.stopPoll()
+59 -87
View File
@@ -4,23 +4,20 @@ import (
"context"
"errors"
"runtime"
"sync"
"time"
"github.com/Nwflower/reims-go/internal/appwindow"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
)
type appWindowRun struct {
cancel context.CancelFunc
done chan struct{}
}
// OpenAppWindow shows the frontmost application window of a running macOS VM.
func (a *App) OpenAppWindow(driverID, name string) error {
func (a *App) openAppWindow(command context.Context, sessions *appwindow.Sessions, bridge *guesttools.Server, service builtin.ComputerUseService, name string) error {
a.mu.Lock()
locale := i18n.EffectiveLocale(a.cfg.Locale)
tmp := a.cfg.TempDir()
a.mu.Unlock()
coded := func(code, key string, cause error) error {
return i18n.NewCodedError(locale, code, key, i18n.Vars{"name": name}, cause)
@@ -28,72 +25,62 @@ func (a *App) OpenAppWindow(driverID, name string) error {
if runtime.GOOS != "windows" {
return coded("E_APP_WINDOW_UNAVAILABLE", "err.app_window_unavailable", nil)
}
info, err := a.resolveVMInfo(driverID, name)
if err != nil {
return err
}
if info.DriverID != driver.BuiltinReimsMacOSDriverID {
return coded("E_APP_WINDOW_UNAVAILABLE", "err.app_window_unavailable", nil)
}
vm, ok := a.polledVMForDriver(info.DriverID, name)
vm, ok := a.polledVMForDriver(driver.BuiltinReimsMacOSDriverID, name)
if !ok || vm.State != "running" || vm.Dir == "" {
return coded("E_VM_NOT_RUNNING", "err.vm_not_running", nil)
}
if !a.guestToolsEnabled() {
return coded("E_APP_WINDOW_GUEST_TOOLS", "err.app_window_guest_tools", nil)
}
a.mu.Lock()
bridge := a.guestTools
if bridge == nil || a.appWindowClosing {
a.mu.Unlock()
return coded("E_APP_WINDOW_GUEST_TOOLS", "err.app_window_guest_tools", nil)
}
if a.appWindow != nil {
a.mu.Unlock()
err := sessions.Start(command, func(ctx context.Context) (func(), error) {
// A previous activation may still be clearing its input when Windows
// takes longer than the plugin's shutdown deadline.
if !a.appWindowGate.TryLock() {
return nil, appwindow.ErrWindowOpen
}
run, err := a.prepareAppWindow(ctx, bridge, service, vm, tmp, locale, coded)
if err != nil {
a.appWindowGate.Unlock()
return nil, err
}
return func() {
defer a.appWindowGate.Unlock()
run()
}, nil
})
switch {
case errors.Is(err, appwindow.ErrWindowOpen):
return coded("E_APP_WINDOW_OPEN", "err.app_window_open", nil)
case errors.Is(err, appwindow.ErrSessionsClosed), errors.Is(err, context.Canceled):
return coded("E_APP_WINDOW_DISABLED", "err.app_window_disabled", nil)
default:
return err
}
ctx, cancel := context.WithCancel(context.Background())
run := &appWindowRun{cancel: cancel, done: make(chan struct{})}
a.appWindow = run
tmp := a.cfg.TempDir()
a.mu.Unlock()
reporting := false
finish := func() {
cancel()
if reporting {
bridge.SetWindowReporting(name, false)
}
a.mu.Lock()
a.appWindow = nil
close(run.done)
a.mu.Unlock()
}
started := false
defer func() {
if !started {
finish()
}
}()
}
func (a *App) prepareAppWindow(ctx context.Context, bridge *guesttools.Server, service builtin.ComputerUseService, vm driver.VMListItem, tmp string, locale i18n.Locale, coded func(string, string, error) error) (func(), error) {
name := vm.Name
status := bridge.Status(name, 15*time.Second)
if !status.Connected {
return coded("E_APP_WINDOW_GUEST_TOOLS", "err.app_window_guest_tools", nil)
return nil, coded("E_APP_WINDOW_GUEST_TOOLS", "err.app_window_guest_tools", nil)
}
if status.AgentVersion < guesttools.PasteReadyAgentVersion {
return coded("E_APP_WINDOW_GUEST_TOOLS_UPDATE", "err.app_window_guest_tools_update", nil)
return nil, coded("E_APP_WINDOW_GUEST_TOOLS_UPDATE", "err.app_window_guest_tools_update", nil)
}
service := a.computerUseInternalService()
probe, stopProbe := context.WithTimeout(ctx, 2*time.Second)
pointer, err := service.PointerAvailable(probe, vm.Dir)
stopProbe()
if err != nil || !pointer {
return coded("E_APP_WINDOW_POINTER", "err.app_window_pointer", err)
if ctx.Err() != nil {
return nil, ctx.Err()
}
reporting = bridge.SetWindowReporting(name, true)
if !reporting {
return coded("E_APP_WINDOW_GUEST_TOOLS", "err.app_window_guest_tools", nil)
if err != nil || !pointer {
return nil, coded("E_APP_WINDOW_POINTER", "err.app_window_pointer", err)
}
if !bridge.SetWindowReporting(name, true) {
return nil, coded("E_APP_WINDOW_GUEST_TOOLS", "err.app_window_guest_tools", nil)
}
clearReporting := sync.OnceFunc(func() { bridge.SetWindowReporting(name, false) })
stopReporting := context.AfterFunc(ctx, clearReporting)
finishReporting := func() {
stopReporting()
clearReporting()
}
show, err := appwindow.Prepare(ctx, appwindow.SessionOptions{
VMDir: vm.Dir,
@@ -106,7 +93,7 @@ func (a *App) OpenAppWindow(driverID, name string) error {
return bridge.PrepareGuestClipboardPaste(wait, name)
},
OnClipboardError: func(err error) {
a.emitVMLogForDriver(info.DriverID, name, "App window paste: "+err.Error())
a.emitVMLogForDriver(vm.DriverID, name, "App window paste: "+err.Error())
a.mu.Lock()
manager := a.trayMgr
a.mu.Unlock()
@@ -115,35 +102,20 @@ func (a *App) OpenAppWindow(driverID, name string) error {
}
},
})
if errors.Is(err, appwindow.ErrNoWindow) {
return coded("E_APP_WINDOW_NO_WINDOW", "err.app_window_no_window", nil)
}
if err != nil {
return coded("E_APP_WINDOW_CAPTURE", "err.app_window_capture", err)
}
started = true
go func() {
defer finish()
if err := show(); err != nil && ctx.Err() == nil {
a.emitVMLogForDriver(info.DriverID, name, "App window closed: "+err.Error())
finishReporting()
if ctx.Err() != nil {
return nil, ctx.Err()
}
}()
return nil
}
func (a *App) stopAppWindow() {
a.mu.Lock()
a.appWindowClosing = true
run := a.appWindow
a.mu.Unlock()
if run == nil {
return
}
run.cancel()
timer := time.NewTimer(5 * time.Second)
defer timer.Stop()
select {
case <-run.done:
case <-timer.C:
if errors.Is(err, appwindow.ErrNoWindow) {
return nil, coded("E_APP_WINDOW_NO_WINDOW", "err.app_window_no_window", nil)
}
return nil, coded("E_APP_WINDOW_CAPTURE", "err.app_window_capture", err)
}
return func() {
defer finishReporting()
if err := show(); err != nil && ctx.Err() == nil {
a.emitVMLogForDriver(vm.DriverID, name, "App window closed: "+err.Error())
}
}, nil
}
+1
View File
@@ -172,6 +172,7 @@ func (a *App) initPlugins() {
return a.guestToolsImagePath(vmName)
},
BuildGuestToolsImage: a.buildGuestToolsImage,
OpenAppWindow: a.openAppWindow,
PrepareVMNetwork: a.prepareManagedVMNetwork,
RestorePacketBridges: func(ctx context.Context) func() {
return a.startPacketBridgeRestore(ctx, func(ctx context.Context) {
+91
View File
@@ -0,0 +1,91 @@
package appwindow
import (
"context"
"errors"
"sync"
"time"
)
var (
ErrWindowOpen = errors.New("an app window is already open")
ErrSessionsClosed = errors.New("app window service is closed")
)
// Sessions owns the single app window opened during one plugin activation.
type Sessions struct {
mu sync.Mutex
closed bool
active *activeSession
}
type activeSession struct {
cancel context.CancelFunc
done chan struct{}
}
// Start prepares the window under the command's cancellation and transfers
// its runtime to Sessions after preparation succeeds.
func (s *Sessions) Start(command context.Context, prepare func(context.Context) (func(), error)) error {
if err := command.Err(); err != nil {
return err
}
s.mu.Lock()
if s.closed {
s.mu.Unlock()
return ErrSessionsClosed
}
if s.active != nil {
s.mu.Unlock()
return ErrWindowOpen
}
ctx, cancel := context.WithCancel(context.Background())
active := &activeSession{cancel: cancel, done: make(chan struct{})}
s.active = active
s.mu.Unlock()
finish := func() {
cancel()
s.mu.Lock()
s.active = nil
close(active.done)
s.mu.Unlock()
}
stopStartup := context.AfterFunc(command, cancel)
run, err := prepare(ctx)
if !stopStartup() {
cancel()
}
if err != nil {
finish()
return err
}
// Run even when startup was canceled after preparation. The prepared
// function owns the initial capture resources and releases them on exit.
startupErr := ctx.Err()
go func() {
defer finish()
run()
}()
return startupErr
}
// Close prevents new sessions and cancels preparation or the active viewer.
func (s *Sessions) Close() {
s.mu.Lock()
s.closed = true
active := s.active
s.mu.Unlock()
if active == nil {
return
}
active.cancel()
// Keep plugin transitions bounded if the OS clipboard owner is stalled.
timer := time.NewTimer(5 * time.Second)
defer timer.Stop()
select {
case <-active.done:
case <-timer.C:
}
}
+70
View File
@@ -0,0 +1,70 @@
package appwindow
import (
"context"
"errors"
"testing"
"time"
)
func TestSessionsEnforcePluginLifetime(t *testing.T) {
var sessions Sessions
command, cancel := context.WithCancel(context.Background())
defer cancel()
var window context.Context
finished := make(chan struct{})
prepare := func(ctx context.Context) (func(), error) {
window = ctx
return func() {
<-ctx.Done()
close(finished)
}, nil
}
if err := sessions.Start(command, prepare); err != nil {
t.Fatal(err)
}
defer sessions.Close()
cancel()
if err := window.Err(); err != nil {
t.Fatalf("command completion canceled the open window: %v", err)
}
if err := sessions.Start(context.Background(), prepare); !errors.Is(err, ErrWindowOpen) {
t.Fatalf("opening a second window: %v", err)
}
sessions.Close()
select {
case <-finished:
default:
t.Fatal("scope closed before the viewer finished")
}
if err := sessions.Start(context.Background(), prepare); !errors.Is(err, ErrSessionsClosed) {
t.Fatalf("opening a window after deactivation: %v", err)
}
}
func TestSessionsCloseCancelsPendingStart(t *testing.T) {
var sessions Sessions
entered := make(chan struct{})
errs := make(chan error, 1)
go func() {
errs <- sessions.Start(context.Background(), func(ctx context.Context) (func(), error) {
close(entered)
<-ctx.Done()
return nil, ctx.Err()
})
}()
select {
case <-entered:
case <-time.After(2 * time.Second):
t.Fatal("preparation did not start")
}
sessions.Close()
select {
case err := <-errs:
if !errors.Is(err, context.Canceled) {
t.Fatalf("startup after deactivation: %v", err)
}
case <-time.After(2 * time.Second):
t.Fatal("preparation did not stop")
}
}
+2
View File
@@ -124,6 +124,7 @@ var catalog = map[Locale]map[string]string{
"emptyVMs": "还没有虚拟机",
"err.affinity.empty_mask": "请至少选择 1 个可用的逻辑处理器",
"err.app_window_capture": "无法获取 {name} 的应用画面",
"err.app_window_disabled": "在插件页启用 macOS 应用窗口后重试",
"err.app_window_guest_tools": "连接 {name} 的 Guest Tools 后再打开独立窗口",
"err.app_window_guest_tools_update": "更新 {name} 的 Guest Tools 后再打开独立窗口",
"err.app_window_no_window": "在 {name} 的单屏桌面打开一个前台应用窗口后重试",
@@ -802,6 +803,7 @@ var catalog = map[Locale]map[string]string{
"emptyVMs": "No virtual machines",
"err.affinity.empty_mask": "Select at least 1 logical processor",
"err.app_window_capture": "Could not capture the app window in {name}",
"err.app_window_disabled": "Enable macOS App Windows under Plugins and try again",
"err.app_window_guest_tools": "Connect Guest Tools in {name} and try again",
"err.app_window_guest_tools_update": "Update Guest Tools in {name} and try again",
"err.app_window_no_window": "Open a foreground app on the single-display desktop of {name} and try again",
+80
View File
@@ -0,0 +1,80 @@
package builtin
import (
"context"
"errors"
"fmt"
"runtime"
"strings"
"github.com/Nwflower/reims-go/internal/appwindow"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/plugin"
)
// IDAppWindow is the optional built-in extension for macOS application windows.
const IDAppWindow = "builtin.macos.app-window"
func defAppWindow(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
const commandID = "open"
title := plugin.LocalizedText{ZhCN: "打开独立应用窗口", EnUS: "Open app in separate window"}
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDAppWindow,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "macOS 应用窗口", EnUS: "macOS App Windows"},
Description: plugin.LocalizedText{
ZhCN: "在 Windows 桌面上显示和操作当前 macOS 应用窗口",
EnUS: "View and control the active macOS app in a separate Windows window",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Platforms: []string{"windows-x64"},
Requires: []plugin.ServiceRequirement{
{Service: ServiceGuestToolsTransport, Version: "^1.0.0"},
{Service: ServiceComputerUse, Version: "^1.0.0"},
},
Permissions: []string{"vm:screen", "qmp:write", "ui:slot"},
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDAppWindow, false),
Activate: func(_ context.Context, sc *plugin.Scope) error {
// The CLI uses this definition to manage plugin state. Only the
// supported desktop host can expose the native window command.
if cb.OpenAppWindow == nil || runtime.GOOS != "windows" || runtime.GOARCH != "amd64" {
return nil
}
rawTools, _ := sc.Lookup(ServiceGuestToolsTransport)
tools, ok := rawTools.(*guesttools.Server)
if !ok || tools == nil {
return fmt.Errorf("invalid %q service instance", ServiceGuestToolsTransport)
}
rawConsole, _ := sc.Lookup(ServiceComputerUse)
console, ok := rawConsole.(ComputerUseService)
if !ok || console == nil {
return fmt.Errorf("invalid %q service instance", ServiceComputerUse)
}
sessions := new(appwindow.Sessions)
sc.OnDispose(sessions.Close)
sc.Registry().RegisterCommand(sc, plugin.CommandContribution{ID: commandID, Title: title},
func(ctx context.Context, args map[string]any) (any, error) {
if sc.Disposed() {
return nil, appwindow.ErrSessionsClosed
}
name, _ := args["vm"].(string)
name = strings.TrimSpace(name)
if name == "" {
return nil, errors.New("a VM name is required")
}
return nil, cb.OpenAppWindow(ctx, sessions, tools, console, name)
})
sc.Registry().RegisterMenu(sc, plugin.MenuContribution{
ID: commandID, Slot: "vm.toolbar", Command: commandID, Title: title, When: "vm.macos.running",
})
return nil
},
}
}
+131
View File
@@ -0,0 +1,131 @@
package builtin
import (
"context"
"errors"
"runtime"
"slices"
"testing"
"github.com/Nwflower/reims-go/internal/appwindow"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/plugin"
)
func TestAppWindowPluginDefaultOffAndCLIState(t *testing.T) {
reg := plugin.NewRegistry(nil)
t.Cleanup(reg.DisposeAll)
if err := RegisterAll(reg, HostCallbacks{}, nil); err != nil {
t.Fatal(err)
}
reg.Reconcile(t.Context())
info, ok := reg.Info(IDAppWindow)
if !ok || info.Enabled || info.State != plugin.StateOff {
t.Fatalf("default app window plugin state: %+v", info)
}
assertAppWindowContributions(t, reg, false)
if err := reg.SetDesired(t.Context(), IDAppWindow, true); err != nil {
t.Fatal(err)
}
if !reg.IsActive(IDAppWindow) {
t.Fatalf("CLI cannot enable app window plugin state: %s", reg.StateOf(IDAppWindow))
}
assertAppWindowContributions(t, reg, false)
}
func TestAppWindowPluginOwnsWindowAcrossDependencyChanges(t *testing.T) {
if runtime.GOOS != "windows" || runtime.GOARCH != "amd64" {
t.Skip("native app window command is available on Windows x64")
}
for _, dependency := range []string{IDGuestTools, IDComputerUse} {
t.Run(dependency, func(t *testing.T) {
reg := plugin.NewRegistry(nil)
t.Cleanup(reg.DisposeAll)
var owner *appwindow.Sessions
var closed chan struct{}
cb := HostCallbacks{
OpenAppWindow: func(ctx context.Context, sessions *appwindow.Sessions, tools *guesttools.Server, console ComputerUseService, vm string) error {
if tools == nil || console == nil || vm != "fixture" {
t.Fatalf("invalid command arguments: tools=%v console=%v vm=%q", tools != nil, console != nil, vm)
}
owner = sessions
done := make(chan struct{})
closed = done
return sessions.Start(ctx, func(sessionCtx context.Context) (func(), error) {
return func() {
<-sessionCtx.Done()
close(done)
}, nil
})
},
}
if err := RegisterAll(reg, cb, nil); err != nil {
t.Fatal(err)
}
if err := reg.SetDesired(t.Context(), IDAppWindow, true); err != nil {
t.Fatal(err)
}
assertAppWindowContributions(t, reg, true)
if _, err := reg.InvokeCommand(t.Context(), IDAppWindow, "open", map[string]any{"vm": 17}); err == nil {
t.Fatal("native window command accepted a non-string VM name")
}
open := func() {
t.Helper()
if _, err := reg.InvokeCommand(t.Context(), IDAppWindow, "open", map[string]any{"vm": "fixture"}); err != nil {
t.Fatal(err)
}
}
open()
first := owner
if err := reg.SetDesired(t.Context(), dependency, false); err != nil {
t.Fatal(err)
}
if reg.StateOf(IDAppWindow) != plugin.StatePending {
t.Fatalf("app window plugin remained active without %s", dependency)
}
select {
case <-closed:
default:
t.Fatalf("window was not closed when %s was disabled", dependency)
}
assertAppWindowContributions(t, reg, false)
if err := first.Start(t.Context(), func(context.Context) (func(), error) {
t.Fatal("disposed scope still accepted a window")
return nil, nil
}); !errors.Is(err, appwindow.ErrSessionsClosed) {
t.Fatalf("disposed session owner returned %v", err)
}
if err := reg.SetDesired(t.Context(), dependency, true); err != nil {
t.Fatal(err)
}
assertAppWindowContributions(t, reg, true)
open()
if owner == first {
t.Fatal("reactivation reused the disposed session owner")
}
if err := reg.SetDesired(t.Context(), IDAppWindow, false); err != nil {
t.Fatal(err)
}
select {
case <-closed:
default:
t.Fatal("disabling the app window plugin left a window open")
}
assertAppWindowContributions(t, reg, false)
})
}
}
func assertAppWindowContributions(t *testing.T, reg *plugin.Registry, want bool) {
t.Helper()
hasCommand := slices.ContainsFunc(reg.Commands(), func(cmd plugin.CommandContribution) bool {
return cmd.PluginID == IDAppWindow && cmd.ID == "open"
})
hasMenu := slices.ContainsFunc(reg.Menus("vm.toolbar"), func(item plugin.MenuContribution) bool {
return item.PluginID == IDAppWindow && item.Command == "open" && item.When == "vm.macos.running"
})
if hasCommand != want || hasMenu != want {
t.Fatalf("app window command=%v menu=%v, want %v", hasCommand, hasMenu, want)
}
}
+3
View File
@@ -10,6 +10,7 @@ import (
"fmt"
"strings"
"github.com/Nwflower/reims-go/internal/appwindow"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/guesttools"
@@ -57,6 +58,7 @@ type HostCallbacks struct {
CancelColdReboot func(vmName string)
GuestToolsImg func(vmName string) string
BuildGuestToolsImage func(vmName, vmDir string) error
OpenAppWindow func(context.Context, *appwindow.Sessions, *guesttools.Server, ComputerUseService, string) error
PrepareVMNetwork func(context.Context, string, bool) (func(), error)
// 返回取消并等待本次恢复任务结束的清理函数,由插件 scope 先于通道释放执行。
RestorePacketBridges func(context.Context) func()
@@ -98,6 +100,7 @@ func RegisterAll(reg *plugin.Registry, cb HostCallbacks, desiredFn func(id strin
defInput(ver, cb, desiredFn),
defNpcapBridge(ver, cb, desiredFn),
defComputerUse(ver, desiredFn),
defAppWindow(ver, cb, desiredFn),
defDownloaderParallel(ver, cb, desiredFn),
}
for _, d := range defs {
+1
View File
@@ -312,6 +312,7 @@
"err.computer_use.restore_confirmation": "Confirm in Reims-Go before restoring a snapshot for VM {name}",
"err.fullscreen_vmware_svga": "Press Ctrl+Alt+F in the QEMU window for {name} to toggle full screen",
"err.app_window_unavailable": "Separate app windows require a macOS VM running on Windows",
"err.app_window_disabled": "Enable macOS App Windows under Plugins and try again",
"err.app_window_guest_tools": "Connect Guest Tools in {name} and try again",
"err.app_window_guest_tools_update": "Update Guest Tools in {name} and try again",
"err.app_window_open": "Close the current separate app window first",
-2
View File
@@ -10,8 +10,6 @@
"failFullscreen": "Couldn’t toggle full screen",
"showInstallGuide": "Show install guide",
"copyScreenshot": "Copy screenshot",
"openAppWindow": "Open app in separate window",
"failOpenAppWindow": "Could not open the app window",
"toastScreenshotCopied": "VM screenshot copied",
"failFocus": "Could not focus VM window",
"failScreenshot": "Screenshot failed",
+1
View File
@@ -312,6 +312,7 @@
"err.computer_use.restore_confirmation": "在 Reims-Go 中确认后才能还原虚拟机 {name} 的快照",
"err.fullscreen_vmware_svga": "在 {name} 的 QEMU 窗口中按 Ctrl+Alt+F 切换全屏",
"err.app_window_unavailable": "独立窗口仅支持 Windows 上运行的 macOS 虚拟机",
"err.app_window_disabled": "在插件页启用 macOS 应用窗口后重试",
"err.app_window_guest_tools": "连接 {name} 的 Guest Tools 后再打开独立窗口",
"err.app_window_guest_tools_update": "更新 {name} 的 Guest Tools 后再打开独立窗口",
"err.app_window_open": "先关闭已打开的独立应用窗口",
-2
View File
@@ -10,8 +10,6 @@
"failFullscreen": "无法切换全屏",
"showInstallGuide": "显示安装引导",
"copyScreenshot": "截屏并复制",
"openAppWindow": "打开独立应用窗口",
"failOpenAppWindow": "无法打开独立应用窗口",
"toastScreenshotCopied": "已复制虚拟机画面",
"failFocus": "无法定位虚拟机窗口",
"failScreenshot": "截屏失败",