feat(plugin,ui): consolidate builtin.core, enforce Guest Tools toggle, and add QQ group entry
- Merge essential builtins (driver, default theme, start prep, host workarounds) into always-on system plugin builtin.core, with state.json and arg-ledger migration plus app-scoped workaround settings honored by both GUI and CLI. - Ensure disabling builtin.bridge.guest-tools stops the localhost bridge without being restarted by feature callers, fix guesttools.Server Start/Close race, and reflect the disabled state in VMPage and SettingsModal. - Add QQ community group entry in About settings with Windows tencent:// protocol detection, cached invite redirect resolution, and copy-ID fallback. - Update docs/plugin-architecture.md, Wails bindings, and i18n strings.
This commit is contained in:
1 parent
007f2ac93c
commit
181c616909
35 files changed
+1432
-578
No files matched your search
@@ -60,7 +60,7 @@
|
||||
flowchart TB
|
||||
subgraph Exe["reims-go.exe(可信核心)"]
|
||||
Reg["扩展点注册表\n依赖解析 · 可逆副作用 · Reconcile"]
|
||||
Builtin["内置扩展(编译期注册)\nmacOS/reims 驱动 · reims-vgpu 运行时种类 ·\n宿客桥接与兼容补偿 · 浅/深色主题"]
|
||||
Builtin["内置扩展(编译期注册)\n核心:reims 驱动 · 默认主题 · 启动准备 · 兼容补偿\n可选:宿客桥接 · 剪贴板 · 输入服务 · reims-vgpu 运行时种类"]
|
||||
Mgr["插件管理器\n清单校验 · 事务安装 · 状态 · 安全模式"]
|
||||
Broker["Host API 代理\n权限校验 · 脱敏 · 限流 · 审计"]
|
||||
Sup["进程监管器\nJob Object · 重启退避 · 健康检查"]
|
||||
@@ -104,7 +104,12 @@ flowchart TB
|
||||
|
||||
### 3.2 内置功能先插件化
|
||||
|
||||
扩展点先由内置功能使用一遍再对外开放:reims 驱动成为内置 `builtin.driver.reims-macos`,现有启动准备步骤与宿客桥接迁为内置扩展,经同一注册表注册、可独立启停、禁用后零残留。首批示例插件为默认开启的剪贴板互通(见 §5.4)。
|
||||
扩展点先由内置功能使用一遍再对外开放。内置功能分两类,判断标准是用户关掉它之后,是「少了一项功能」还是「已有功能坏掉」:
|
||||
|
||||
- **核心** `builtin.core`:Reims-Go 离开它就无法运行 macOS 虚拟机的部分,包括 reims 驱动(驱动 id 仍为 `builtin.driver.reims-macos`)、默认主题(主题 id 仍为 `builtin.theme.default`)、启动准备(离线辅助盘、恢复模式引导切换、引导语言重放)与宿主兼容补偿(WHPX 降级、Win10 冷重启)。它是**系统插件**:始终启用,不能停用或卸载,插件页显示为一行「始终启用」,不参与「使用中」检查。两项兼容补偿作为核心的应用级设置保留开关,仅供排障。启动准备在同一个 `vm.beforeStart` 处理器里按固定顺序执行,引导语言重放必须在恢复模式切换(可能重建 OpenCore)之后。
|
||||
- **可选内置扩展**:Guest Tools 传输服务、剪贴板互通、宿主输入服务。经同一注册表注册、可独立启停、停用后零残留,停用即真正停止(不被其他调用方重新拉起)。首批示例为默认开启的剪贴板互通(见 §5.4)。
|
||||
|
||||
核心由曾经拆开的七个内置插件合并而来(`builtin.RetiredIDs`)。启动时删除 `state.json` 中这些旧 ID 的记录,关闭过的兼容补偿转为对应的核心设置;启动 VM 时,参数归属账本中旧 ID 名下的片段移交给核心,继续沿用而不是被当作已卸载插件的残留剥离。
|
||||
|
||||
---
|
||||
|
||||
@@ -264,9 +269,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
| :--- | :--- | :--- |
|
||||
| `builtin.bridge.guest-tools` | `internal/guesttools`、`guesttools_flow.go` | 提供传输服务 + `vm.beforeStart`(注入桥接参数与环境变量)+ `vm.afterStart` + `vm.card`;共享文件夹、盘符共享、防休眠逐步拆为功能扩展 |
|
||||
| `builtin.input` | `host/ime_hook_windows.go` | 提供输入服务与 `inputFilters`;IME 桥成为其上的功能,停用时卸载钩子线程 |
|
||||
| `builtin.compat.win10-cold-reboot` | `app.go` 冷重启监视 | `vm.beforeStart`(`-no-reboot` 与独立 QMP 通道)+ `vm.afterStart` + `vm.afterStop` |
|
||||
| `builtin.compat.whpx-fallback` | `vmstart.applyProbedWHPXCompat` | `host.preflight` + `vm.beforeStart`(按运行时能力决定是否降级) |
|
||||
| `builtin.prep.offline-helper` / `recovery-boot` / `guest-lang` | `vmstart.Prepare` 其余步骤 | `vm.beforeStart` |
|
||||
| `builtin.core`(系统插件) | `driver/reims_adapter.go`、`vmstart.Prepare` 各步骤、`app.go` 冷重启监视 | `guestDrivers` + `themes` + `host.preflight` + 一个按序执行全部启动准备的 `vm.beforeStart`(离线辅助盘 → 恢复模式引导 → 引导语言 → WHPX 降级 → Win10 冷重启)+ `vm.afterStart` / `vm.afterStop`(冷重启监视);设置 `whpx_fallback`、`win10_cold_reboot` |
|
||||
|
||||
### 5.5 与上游补丁队列的边界
|
||||
|
||||
@@ -386,7 +389,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
| 入口 | 内容 |
|
||||
| :--- | :--- |
|
||||
| CLI | `reims-go plugin list / install / link <dir> / enable [--approve-high-risk] / disable / remove [--purge] / info / doctor / run <id> <command>`;`vm create --driver <id>` |
|
||||
| 应用设置 → 插件 | 分组展示内置扩展与第三方插件:来源与信任标签、许可证、权限摘要、启用开关、故障状态与日志入口、本地包导入 |
|
||||
| 应用设置 → 插件 | 分组展示内置插件与第三方插件:核心置顶、显示「始终启用」且无开关;其余显示来源与信任标签、权限摘要、启用开关、故障状态与日志入口;本地包导入 |
|
||||
| 插件设置页 | 由 `settings` Schema 渲染,复用现有设置控件,标注生效时机 |
|
||||
| VM 页面 | 按能力位显隐操作;`vm.toolbar` 菜单项支持 `when` 条件;`vm.card` 展示驱动或插件提供的键值信息 |
|
||||
| 创建向导 | 先选驱动,再按驱动 `CreateSchema` 渲染专属表单 |
|
||||
@@ -425,7 +428,7 @@ flowchart LR
|
||||
|
||||
| 阶段 | 范围 | 验收标准 |
|
||||
| :--- | :--- | :--- |
|
||||
| **Phase 0** | 注册表与可逆作用域;驱动抽象(reims 为内置驱动);启动准备与宿客桥接迁为内置扩展;Guest Tools 拆出传输服务与**剪贴板互通示例**;输入服务(IME 键盘钩子迁入);参数归属账本;UI 契约 v1(令牌单一来源、部件类名、状态属性) | `go test ./...` 与前端构建通过;存量 VM 零迁移、行为零回归;剪贴板互通可在 VM 运行中开关且关闭后零残留(无残留路由与剪贴板监视);其余内置扩展同样可独立停用且零残留;满足 §8.1 资源预算 |
|
||||
| **Phase 0** | 注册表与可逆作用域;驱动抽象(reims 为内置驱动);启动准备与宿客桥接迁为内置扩展;Guest Tools 拆出传输服务与**剪贴板互通示例**;输入服务(IME 键盘钩子迁入);参数归属账本;UI 契约 v1(令牌单一来源、部件类名、状态属性) | `go test ./...` 与前端构建通过;存量 VM 零迁移、行为零回归;剪贴板互通可在 VM 运行中开关且关闭后零残留(无残留路由与剪贴板监视);可选内置扩展同样可独立停用且零残留,核心始终启用;满足 §8.1 资源预算 |
|
||||
| **Phase 1** | 插件包与清单、事务安装、`state.json`、安全模式;插件管理页与 `reims-go plugin`;`inputFilters`;令牌主题与样式主题接口;图标、VM 模板、运行时源、规则 Hook | 以不发布的测试主题与示例声明式插件验证配色方案、字体、部件样式、状态装饰与启停零残留;损坏包与不兼容包在落盘前被拒绝;仍满足 §8.1 资源预算 |
|
||||
| **Phase 2** | 运行时种类注册表、`runtime_api` 与 `capabilities`、来源展示 | 第二种运行时与官方运行时并存切换;不兼容组合被拦截并给出提示 |
|
||||
| **Phase 3** | JSON-RPC 协议 v1、进程监管、反向 Host API、权限审批、代码 Hook、插件命令、排障采集、轻量 Go SDK | 死循环或崩溃的示例 Sidecar 不影响主窗口与运行中 VM;退出或禁用后无孤儿进程 |
|
||||
|
||||
@@ -910,6 +910,7 @@ export const App: React.FC = () => {
|
||||
canDark={canDark}
|
||||
onThemeMode={setThemeMode}
|
||||
onSetLocale={setLang}
|
||||
onCopy={copy}
|
||||
onRefresh={refresh}
|
||||
onError={fail}
|
||||
/>
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import { Download } from 'lucide-react'
|
||||
import { Copy, Download, ExternalLink } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { findOptimization, optBadgeClass, optStatusLabel } from '../lib/optimizations'
|
||||
import { AppState, AppUpdateInfo, Locale } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { Segmented, Switch } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
|
||||
export type ThemeMode = 'light' | 'dark' | 'system'
|
||||
|
||||
const QQ_GROUP_ID = '1136042744'
|
||||
|
||||
interface Props {
|
||||
state: AppState
|
||||
locale: Locale
|
||||
@@ -17,18 +19,22 @@ interface Props {
|
||||
canDark?: boolean
|
||||
onThemeMode: (mode: ThemeMode) => void
|
||||
onSetLocale: (l: Locale) => void
|
||||
onCopy?: (text: string) => void
|
||||
onRefresh: () => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
}
|
||||
|
||||
export const AppSettingsPage: React.FC<Props> = ({
|
||||
state, locale, themeMode, canLight = true, canDark = true, onThemeMode, onSetLocale, onRefresh, onError,
|
||||
state, locale, themeMode, canLight = true, canDark = true, onThemeMode, onSetLocale, onCopy, onRefresh, onError,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { host, config, optimizations } = state
|
||||
const [appUpdate, setAppUpdate] = useState<AppUpdateInfo | null>(null)
|
||||
const [checkingUpdate, setCheckingUpdate] = useState(false)
|
||||
const [updateErr, setUpdateErr] = useState('')
|
||||
const [qqInstalled, setQQInstalled] = useState<boolean | null>(null)
|
||||
const [openingQQ, setOpeningQQ] = useState(false)
|
||||
const [qqLaunchErr, setQQLaunchErr] = useState('')
|
||||
|
||||
const pcoreOpt = findOptimization(optimizations, 'pcore_pin')
|
||||
|
||||
@@ -47,6 +53,11 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
|
||||
useEffect(() => {
|
||||
void runUpdateCheck(false)
|
||||
let cancelled = false
|
||||
api.CanOpenQQGroup()
|
||||
.then((ok) => { if (!cancelled) setQQInstalled(!!ok) })
|
||||
.catch(() => { if (!cancelled) setQQInstalled(false) })
|
||||
return () => { cancelled = true }
|
||||
}, [])
|
||||
|
||||
const guard = (fn: () => Promise<unknown>) => async () => {
|
||||
@@ -63,6 +74,27 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
if (dir) await api.SetDataRoot(dir)
|
||||
})
|
||||
|
||||
const openURL = (url: string) => {
|
||||
api.OpenURL(url).catch((e) => onError(tr('failGeneric'), e))
|
||||
}
|
||||
|
||||
const openQQGroup = async () => {
|
||||
setOpeningQQ(true)
|
||||
setQQLaunchErr('')
|
||||
try {
|
||||
await api.OpenQQGroup()
|
||||
} catch (e) {
|
||||
const msg = String(e).replace(/^Error:\s*/, '')
|
||||
if (/qq not installed/i.test(msg)) {
|
||||
setQQInstalled(false)
|
||||
} else {
|
||||
setQQLaunchErr(msg)
|
||||
}
|
||||
} finally {
|
||||
setOpeningQQ(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page rg-p-settings">
|
||||
<header className="page-head">
|
||||
@@ -180,7 +212,7 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
<Button
|
||||
variant="primary"
|
||||
icon={<Download size={14} aria-hidden="true" />}
|
||||
onClick={() => guard(() => api.OpenURL(appUpdate.page_url || appUpdate.download_url || ''))()}
|
||||
onClick={() => openURL(appUpdate.page_url || appUpdate.download_url || '')}
|
||||
>
|
||||
{tr('appDownloadUpdate')}
|
||||
</Button>
|
||||
@@ -191,6 +223,51 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('aboutQQGroup')} <span className="mono">{QQ_GROUP_ID}</span>
|
||||
{qqInstalled === false && (
|
||||
<span className="badge">{tr('aboutQQNotInstalled')}</span>
|
||||
)}
|
||||
</div>
|
||||
{qqInstalled === false ? (
|
||||
<div className="row-sub">{tr('aboutQQNotInstalledSub')}</div>
|
||||
) : qqLaunchErr ? (
|
||||
<div className="row-sub" title={qqLaunchErr}>{tr('aboutQQLaunchFailed')}</div>
|
||||
) : (
|
||||
<div className="row-sub">{tr('aboutQQGroupSub')}</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{qqInstalled && !qqLaunchErr ? (
|
||||
<>
|
||||
{onCopy && (
|
||||
<IconButton
|
||||
small
|
||||
label={tr('aboutCopyQQGroup')}
|
||||
icon={<Copy size={14} aria-hidden="true" />}
|
||||
onClick={() => onCopy(QQ_GROUP_ID)}
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
busy={openingQQ}
|
||||
icon={<ExternalLink size={14} aria-hidden="true" />}
|
||||
onClick={() => void openQQGroup()}
|
||||
>
|
||||
{tr('aboutJoinQQGroup')}
|
||||
</Button>
|
||||
</>
|
||||
) : onCopy ? (
|
||||
<Button
|
||||
icon={<Copy size={14} aria-hidden="true" />}
|
||||
onClick={() => onCopy(QQ_GROUP_ID)}
|
||||
>
|
||||
{tr('aboutCopyQQGroup')}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {
|
||||
AlertTriangle, BadgeCheck, Clipboard, Code2, Cpu, Disc3, FolderOpen, Keyboard,
|
||||
AlertTriangle, BadgeCheck, Boxes, Clipboard, Code2, Cpu, Disc3, FolderOpen, Keyboard,
|
||||
Layers, Monitor, PackagePlus, Palette, Puzzle, RefreshCw, RotateCcw, Search,
|
||||
Settings2, Shield, ShieldAlert, ShieldCheck, Sparkles, Terminal, Trash2,
|
||||
} from 'lucide-react'
|
||||
@@ -33,6 +33,7 @@ interface PluginVisual {
|
||||
}
|
||||
|
||||
function resolvePluginVisual(p: PluginInfo): PluginVisual {
|
||||
if (p.system) return { tone: 'indigo', icon: <Boxes size={19} aria-hidden="true" /> }
|
||||
const id = p.id.toLowerCase()
|
||||
const perms = new Set((p.permissions ?? []).map((x) => x.name))
|
||||
if (id.includes('theme') || perms.has('ui:script')) {
|
||||
@@ -268,7 +269,11 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
return name.includes(q) || desc.includes(q) || p.id.toLowerCase().includes(q)
|
||||
}
|
||||
|
||||
const builtins = useMemo(() => plugins.filter((p) => p.source === 'builtin'), [plugins])
|
||||
// The always-on core goes first; the optional builtins keep backend order.
|
||||
const builtins = useMemo(
|
||||
() => plugins.filter((p) => p.source === 'builtin').sort((a, b) => Number(!!b.system) - Number(!!a.system)),
|
||||
[plugins],
|
||||
)
|
||||
const external = useMemo(() => plugins.filter((p) => p.source !== 'builtin'), [plugins])
|
||||
const filteredBuiltins = useMemo(() => builtins.filter(matchesFilter), [builtins, q, locale])
|
||||
const filteredExternal = useMemo(() => external.filter(matchesFilter), [external, q, locale])
|
||||
@@ -357,12 +362,16 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
onClick={() => setRemoveTarget(p)}
|
||||
/>
|
||||
)}
|
||||
<Switch
|
||||
label={locText(p.name, locale, p.id)}
|
||||
disabled={busyID === p.id || (p.enabled && p.in_use) || (!!safeMode && !isBuiltin)}
|
||||
checked={p.enabled}
|
||||
onChange={(checked) => void togglePlugin(p, checked)}
|
||||
/>
|
||||
{p.system ? (
|
||||
<span className="plugin-row-fixed">{tr('pluginAlwaysOn')}</span>
|
||||
) : (
|
||||
<Switch
|
||||
label={locText(p.name, locale, p.id)}
|
||||
disabled={busyID === p.id || (p.enabled && p.in_use) || (!!safeMode && !isBuiltin)}
|
||||
checked={p.enabled}
|
||||
onChange={(checked) => void togglePlugin(p, checked)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -722,11 +722,12 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
<Switch
|
||||
label={tr('driveShareMaster')}
|
||||
checked={!!driveSettings?.enabled}
|
||||
disabled={!driveSettings || driveBusy}
|
||||
disabled={!driveSettings || driveBusy || !!detail.guest_tools_disabled}
|
||||
onChange={(enabled) => void updateDriveShares(enabled, selectedDrives())}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{detail.guest_tools_disabled && <div className="notice">{tr('gtStatusOffTip')}</div>}
|
||||
{driveErr && <div className="notice" role="alert">{driveErr}</div>}
|
||||
{driveSettings?.enabled && selectedDrives().length > 0 &&
|
||||
(detail.guest_tools_agent_version ?? 0) < driveSettings.required_agent_version && (
|
||||
@@ -739,7 +740,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
key={drive.drive}
|
||||
title={title}
|
||||
desc={drive.system ? tr('driveShareSystem', { root: drive.root }) : tr('driveShareDrive', { root: drive.root })}
|
||||
disabled={!driveSettings?.enabled || driveBusy}
|
||||
disabled={!driveSettings?.enabled || driveBusy || !!detail.guest_tools_disabled}
|
||||
reason={!driveSettings?.enabled ? tr('driveShareMasterOff') : undefined}
|
||||
control={
|
||||
<Switch
|
||||
|
||||
@@ -756,12 +756,16 @@ export const VMPage: React.FC<Props> = ({
|
||||
const gtMountMode = stats?.guest_tools_mount_mode || detail.guest_tools_mount_mode || ''
|
||||
const gtSleepActive = stats?.guest_tools_sleep_guard ?? detail.guest_tools_sleep_active ?? false
|
||||
const needsUpgrade = gtConnected && (detail.guest_tools_agent_version ?? 0) > 0 && (detail.guest_tools_agent_version ?? 0) < 3
|
||||
// Plugin switched off: show the state and hide controls that would only fail.
|
||||
const gtOff = !!detail.guest_tools_disabled
|
||||
|
||||
// One status word per state; how files are shared goes in the tooltip.
|
||||
let gtTone: 'ok' | 'warn' | 'idle' = 'idle'
|
||||
let gtStatus: string
|
||||
let gtTip: string
|
||||
if (needsUpgrade) {
|
||||
if (gtOff) {
|
||||
gtStatus = tr('gtStatusOff'); gtTip = tr('gtStatusOffTip')
|
||||
} else if (needsUpgrade) {
|
||||
gtTone = 'warn'; gtStatus = tr('gtStatusUpgrade'); gtTip = tr('guestToolsUpgradeHint')
|
||||
} else if (gtConnected) {
|
||||
gtTone = 'ok'; gtStatus = tr('gtStatusConnected')
|
||||
@@ -772,7 +776,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
} else {
|
||||
gtStatus = tr('gtStatusNone'); gtTip = tr('gtNotInstalledDesc')
|
||||
}
|
||||
const showInstallCmd = detail.guest_tools_attached && (!gtConnected || needsUpgrade)
|
||||
const showInstallCmd = !gtOff && detail.guest_tools_attached && (!gtConnected || needsUpgrade)
|
||||
const sshText = sshUser ? `ssh -p ${detail.ssh_port} ${sshUser}@127.0.0.1` : sshCommand(detail.ssh_port)
|
||||
|
||||
return (
|
||||
@@ -830,7 +834,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
</Tip>
|
||||
</div>
|
||||
<div className="conn-ctrl">
|
||||
{detail.guest_tools_attached ? (
|
||||
{gtOff ? null : detail.guest_tools_attached ? (
|
||||
<Button busy={busyAction === 'detachGuestTools'} disabled={busy} onClick={() => onAction('detachGuestTools')}>
|
||||
{tr('detachGuestTools')}
|
||||
</Button>
|
||||
@@ -864,7 +868,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{tools && (
|
||||
{tools && !gtOff && (
|
||||
<div className="conn-row">
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">{tr('sharedFolder')}</span>
|
||||
@@ -876,7 +880,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{tools && (
|
||||
{tools && !gtOff && (
|
||||
<div className="conn-row">
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">{tr('guestToolsPreventSleep')}</span>
|
||||
|
||||
+28
-42
@@ -341,6 +341,13 @@ const dict = {
|
||||
appCheckUpdate: '检查更新',
|
||||
appDownloadUpdate: '前往下载',
|
||||
appUpdateLookupFailed: '暂时无法连接 GitHub 检查更新',
|
||||
aboutQQGroup: 'QQ 交流群',
|
||||
aboutQQGroupSub: '点击直接拉起 QQ 加群,交流使用与问题反馈',
|
||||
aboutQQNotInstalled: '未安装 QQ',
|
||||
aboutQQNotInstalledSub: '未检测到本地 QQ,可复制群号手动搜索加入',
|
||||
aboutQQLaunchFailed: '未能拉起 QQ,可复制群号手动搜索加入',
|
||||
aboutCopyQQGroup: '复制群号',
|
||||
aboutJoinQQGroup: '加入群聊',
|
||||
whpxTitle: 'WHPX',
|
||||
whpxReady: '就绪',
|
||||
whpxNoHvShort: '未激活',
|
||||
@@ -674,6 +681,8 @@ const dict = {
|
||||
gtStatusWaitingTip: '在 macOS 里运行安装命令后会自动连接',
|
||||
gtStatusEnabled: '已启用',
|
||||
gtStatusNone: '未安装',
|
||||
gtStatusOff: '已停用',
|
||||
gtStatusOffTip: 'Guest Tools 传输服务已在插件页停用,剪贴板、共享文件夹与防休眠都不可用',
|
||||
gtStatusUpgrade: '需要更新',
|
||||
gtInstall: '安装…',
|
||||
gtUpdate: '更新…',
|
||||
@@ -710,11 +719,9 @@ const dict = {
|
||||
pluginTrustVerified: '已审核',
|
||||
pluginTrustDev: '开发',
|
||||
pluginTrustCommunity: '社区',
|
||||
pluginStateActive: '已启用',
|
||||
pluginStateDegraded: '已降级',
|
||||
pluginStateFailed: '故障',
|
||||
pluginStatePending: '等待依赖',
|
||||
pluginStateOff: '已停用',
|
||||
pluginPermissionsLabel: '权限:{list}',
|
||||
pluginHighRiskNotice: '包含高危权限,启用前需确认',
|
||||
pluginViewLog: '查看日志',
|
||||
@@ -729,11 +736,10 @@ const dict = {
|
||||
pluginColorSchemes: '配色方案',
|
||||
pluginColorSchemesHint: '修改种子色派生整套界面色阶',
|
||||
pluginDeleteScheme: '删除方案',
|
||||
pluginExternalSection: '第三方与附带插件',
|
||||
pluginLinkDevBtn: '链接开发目录',
|
||||
pluginImportBtn: '导入本地包',
|
||||
pluginExternalEmpty: '尚未安装第三方插件',
|
||||
pluginBuiltinSection: '内置扩展',
|
||||
pluginExternalSection: '已安装插件',
|
||||
pluginLinkDevBtn: '链接插件开发目录',
|
||||
pluginImportBtn: '导入插件',
|
||||
pluginBuiltinSection: '内置插件',
|
||||
pluginPanelsSection: '插件面板',
|
||||
pluginApproveTitle: '高危权限确认',
|
||||
pluginApproveL3Warn: '此插件为原生可执行程序(L3 Sidecar),能够以当前 Windows 账户身份执行任意操作',
|
||||
@@ -750,26 +756,13 @@ const dict = {
|
||||
pluginAccentSeed: '强调种子色',
|
||||
pluginSurfaceSeed: '画布种子色(可选)',
|
||||
pluginSafeModeShort: '安全模式',
|
||||
pluginTabAll: '全部 ({count})',
|
||||
pluginTabInstalled: '已安装 ({count})',
|
||||
pluginTabThemes: '主题 ({count})',
|
||||
pluginTabBuiltin: '内置 ({count})',
|
||||
pluginSearchPlaceholder: '筛选插件',
|
||||
pluginSearchEmpty: '没有匹配的插件',
|
||||
pluginAlwaysOn: '始终启用',
|
||||
pluginSchemeDefault: '默认',
|
||||
pluginThemeEmptyHint: '导入本地主题包(.zip)后可在此切换外观与配色方案',
|
||||
pluginActiveCount: '已启用 {active} / {total}',
|
||||
pluginCategoryFilter: '按类别筛选',
|
||||
pluginCatAll: '全部类别',
|
||||
pluginCatDriver: '驱动与运行时',
|
||||
pluginCatTheme: '主题外观',
|
||||
pluginCatBridge: '输入与协作',
|
||||
pluginCatCompat: '兼容与工具',
|
||||
pluginCatOther: '扩展',
|
||||
pluginPermCount: '{count} 项权限',
|
||||
pluginExternalEmptyHint: '支持导入签名或本地 .zip 插件包,或链接开发目录实时调试',
|
||||
pluginInstallBarTitle: '安装本地插件',
|
||||
pluginInstallBarDesc: '导入 .zip 插件包或链接本地插件开发目录',
|
||||
themePluginDarkDisabled: '默认主题插件已停用,深色与跟随系统外观不可用',
|
||||
themePluginLightDisabled: '当前主题仅支持深色外观',
|
||||
|
||||
@@ -1108,6 +1101,13 @@ const dict = {
|
||||
appCheckUpdate: 'Check for updates',
|
||||
appDownloadUpdate: 'Download',
|
||||
appUpdateLookupFailed: 'Couldn’t check GitHub for updates',
|
||||
aboutQQGroup: 'QQ Group',
|
||||
aboutQQGroupSub: 'Launch QQ directly to join for community support and feedback',
|
||||
aboutQQNotInstalled: 'QQ not installed',
|
||||
aboutQQNotInstalledSub: 'Local QQ wasn’t detected — copy the group ID to join manually',
|
||||
aboutQQLaunchFailed: 'Couldn’t launch QQ — copy the group ID to join manually',
|
||||
aboutCopyQQGroup: 'Copy group ID',
|
||||
aboutJoinQQGroup: 'Join group',
|
||||
whpxTitle: 'WHPX',
|
||||
whpxReady: 'Ready',
|
||||
whpxNoHvShort: 'Inactive',
|
||||
@@ -1435,6 +1435,8 @@ const dict = {
|
||||
gtStatusWaitingTip: 'Connects once the install command has run in macOS',
|
||||
gtStatusEnabled: 'Enabled',
|
||||
gtStatusNone: 'Not installed',
|
||||
gtStatusOff: 'Off',
|
||||
gtStatusOffTip: 'Guest Tools Transport is turned off on the Plugins page; clipboard, shared folders and keep-awake are unavailable',
|
||||
gtStatusUpgrade: 'Update needed',
|
||||
gtInstall: 'Install…',
|
||||
gtUpdate: 'Update…',
|
||||
@@ -1474,11 +1476,9 @@ const dict = {
|
||||
pluginTrustVerified: 'Verified',
|
||||
pluginTrustDev: 'Dev',
|
||||
pluginTrustCommunity: 'Community',
|
||||
pluginStateActive: 'Active',
|
||||
pluginStateDegraded: 'Degraded',
|
||||
pluginStateFailed: 'Failed',
|
||||
pluginStatePending: 'Pending',
|
||||
pluginStateOff: 'Off',
|
||||
pluginPermissionsLabel: 'Permissions: {list}',
|
||||
pluginHighRiskNotice: 'Contains high-risk permissions; approval required before enabling',
|
||||
pluginViewLog: 'View log',
|
||||
@@ -1493,11 +1493,10 @@ const dict = {
|
||||
pluginColorSchemes: 'Color schemes',
|
||||
pluginColorSchemesHint: 'Seed colors derive the full surface, text, and accent ramp',
|
||||
pluginDeleteScheme: 'Delete scheme',
|
||||
pluginExternalSection: 'External & bundled plugins',
|
||||
pluginLinkDevBtn: 'Link dev folder',
|
||||
pluginImportBtn: 'Import package',
|
||||
pluginExternalEmpty: 'No external plugins installed',
|
||||
pluginBuiltinSection: 'Built-in extensions',
|
||||
pluginExternalSection: 'Installed plugins',
|
||||
pluginLinkDevBtn: 'Link plugin dev folder',
|
||||
pluginImportBtn: 'Import plugin',
|
||||
pluginBuiltinSection: 'Built-in plugins',
|
||||
pluginPanelsSection: 'Plugin panels',
|
||||
pluginApproveTitle: 'Approve high-risk permissions',
|
||||
pluginApproveL3Warn: 'This plugin runs native code (L3 Sidecar) and can perform arbitrary actions as your Windows user',
|
||||
@@ -1514,26 +1513,13 @@ const dict = {
|
||||
pluginAccentSeed: 'Accent seed',
|
||||
pluginSurfaceSeed: 'Surface seed (optional)',
|
||||
pluginSafeModeShort: 'Safe mode',
|
||||
pluginTabAll: 'All ({count})',
|
||||
pluginTabInstalled: 'Installed ({count})',
|
||||
pluginTabThemes: 'Themes ({count})',
|
||||
pluginTabBuiltin: 'Built-in ({count})',
|
||||
pluginSearchPlaceholder: 'Filter plugins',
|
||||
pluginSearchEmpty: 'No matching plugins',
|
||||
pluginAlwaysOn: 'Always on',
|
||||
pluginSchemeDefault: 'Default',
|
||||
pluginThemeEmptyHint: 'Import a local theme package (.zip) to switch visual themes and color schemes',
|
||||
pluginActiveCount: '{active} / {total} active',
|
||||
pluginCategoryFilter: 'Filter by category',
|
||||
pluginCatAll: 'All types',
|
||||
pluginCatDriver: 'Drivers & runtimes',
|
||||
pluginCatTheme: 'Themes',
|
||||
pluginCatBridge: 'Input & bridge',
|
||||
pluginCatCompat: 'Compatibility',
|
||||
pluginCatOther: 'Extensions',
|
||||
pluginPermCount: '{count} permissions',
|
||||
pluginExternalEmptyHint: 'Import a signed or local .zip package, or link a local dev folder',
|
||||
pluginInstallBarTitle: 'Install local plugin',
|
||||
pluginInstallBarDesc: 'Import a .zip plugin archive or link a local development directory',
|
||||
themePluginDarkDisabled: 'Default theme plugin is disabled; dark and system appearances are unavailable',
|
||||
themePluginLightDisabled: 'The active theme supports dark appearance only',
|
||||
|
||||
|
||||
@@ -1547,6 +1547,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
}
|
||||
.plugin-row-meta { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.plugin-row-alert { display: flex; align-items: center; gap: 5px; color: var(--warn-text); }
|
||||
.plugin-row-fixed { font-size: var(--fs-12); color: var(--text-3); white-space: nowrap; }
|
||||
.plugin-trust { display: inline-flex; align-items: center; gap: 3px; font-weight: var(--fw-medium); }
|
||||
.plugin-trust.is-official, .plugin-trust.is-verified { color: var(--ok-text); }
|
||||
.plugin-trust.is-dev { color: var(--accent-soft-text); }
|
||||
|
||||
Vendored
+4
@@ -15,6 +15,8 @@ export function AttachGuestTools(arg1:string):Promise<void>;
|
||||
|
||||
export function AttachInstaller(arg1:string,arg2:string):Promise<string>;
|
||||
|
||||
export function CanOpenQQGroup():Promise<boolean>;
|
||||
|
||||
export function CancelTask(arg1:string):Promise<void>;
|
||||
|
||||
export function CheckAppUpdate(arg1:boolean):Promise<version.UpdateInfo>;
|
||||
@@ -129,6 +131,8 @@ export function ListSnapshots(arg1:string):Promise<Array<reims.DiskSnapshot>>;
|
||||
|
||||
export function OpenProcessorScheduling():Promise<void>;
|
||||
|
||||
export function OpenQQGroup():Promise<void>;
|
||||
|
||||
export function OpenSSHTerminal(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function OpenSharedFolder(arg1:string):Promise<void>;
|
||||
|
||||
@@ -14,6 +14,10 @@ export function AttachInstaller(arg1, arg2) {
|
||||
return window['go']['app']['App']['AttachInstaller'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CanOpenQQGroup() {
|
||||
return window['go']['app']['App']['CanOpenQQGroup']();
|
||||
}
|
||||
|
||||
export function CancelTask(arg1) {
|
||||
return window['go']['app']['App']['CancelTask'](arg1);
|
||||
}
|
||||
@@ -242,6 +246,10 @@ export function OpenProcessorScheduling() {
|
||||
return window['go']['app']['App']['OpenProcessorScheduling']();
|
||||
}
|
||||
|
||||
export function OpenQQGroup() {
|
||||
return window['go']['app']['App']['OpenQQGroup']();
|
||||
}
|
||||
|
||||
export function OpenSSHTerminal(arg1, arg2) {
|
||||
return window['go']['app']['App']['OpenSSHTerminal'](arg1, arg2);
|
||||
}
|
||||
|
||||
@@ -1314,6 +1314,7 @@ export namespace plugin {
|
||||
state: string;
|
||||
enabled: boolean;
|
||||
removable: boolean;
|
||||
system?: boolean;
|
||||
in_use: boolean;
|
||||
error?: string;
|
||||
degraded_reason?: string;
|
||||
@@ -1349,6 +1350,7 @@ export namespace plugin {
|
||||
this.state = source["state"];
|
||||
this.enabled = source["enabled"];
|
||||
this.removable = source["removable"];
|
||||
this.system = source["system"];
|
||||
this.in_use = source["in_use"];
|
||||
this.error = source["error"];
|
||||
this.degraded_reason = source["degraded_reason"];
|
||||
@@ -1798,6 +1800,7 @@ export namespace reims {
|
||||
guest_tools_prevent_sleep: boolean;
|
||||
guest_tools_sleep_active: boolean;
|
||||
guest_tools_agent_version?: number;
|
||||
guest_tools_disabled?: boolean;
|
||||
shared_dir?: string;
|
||||
guest_lang?: string;
|
||||
|
||||
@@ -1844,6 +1847,7 @@ export namespace reims {
|
||||
this.guest_tools_prevent_sleep = source["guest_tools_prevent_sleep"];
|
||||
this.guest_tools_sleep_active = source["guest_tools_sleep_active"];
|
||||
this.guest_tools_agent_version = source["guest_tools_agent_version"];
|
||||
this.guest_tools_disabled = source["guest_tools_disabled"];
|
||||
this.shared_dir = source["shared_dir"];
|
||||
this.guest_lang = source["guest_lang"];
|
||||
}
|
||||
|
||||
+10
-2
@@ -131,11 +131,16 @@ func (a *App) startup(ctx context.Context) {
|
||||
a.stopPoll = cancel
|
||||
a.startTray()
|
||||
a.initPlugins()
|
||||
if a.getInputService() == nil {
|
||||
// Without a plugin manager, run the IME bridge and Guest Tools directly.
|
||||
// With one, their plugins own them, and a plugin switched off stays off.
|
||||
a.mu.Lock()
|
||||
pluginsUp := a.pluginMgr != nil
|
||||
a.mu.Unlock()
|
||||
if !pluginsUp {
|
||||
a.startIMEBridge()
|
||||
go a.registerExistingGuestTools(pollCtx)
|
||||
}
|
||||
a.startUIHealthWatchdog(pollCtx)
|
||||
go a.registerExistingGuestTools(pollCtx)
|
||||
go a.pollVMs(pollCtx)
|
||||
a.afterStartup()
|
||||
}
|
||||
@@ -1116,6 +1121,9 @@ func (a *App) StartVM(name string) error {
|
||||
a.emitLog(name, "Warning: could not read arg ledger: "+ledgerErr.Error())
|
||||
ledger = &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{}}
|
||||
}
|
||||
// Fragments written before the builtins were merged into the core
|
||||
// belong to the core now; carry them instead of re-adding them.
|
||||
builtin.MigrateLedger(ledger)
|
||||
// Adopt/strip pre-ledger or out-of-band managed fragments before reconciling
|
||||
// so upgrading existing VMs never duplicates QEMU device IDs (B1).
|
||||
// BeforeStartPayload above already saw the original curDetail.ExtraArgs.
|
||||
|
||||
@@ -2,6 +2,7 @@ package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -12,6 +13,8 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
@@ -30,12 +33,12 @@ func (a *App) guestToolsImagePath(name string) string {
|
||||
return filepath.Join(cacheDir, "reims-go", "guest-tools", name+"-tools.img")
|
||||
}
|
||||
|
||||
// ensureGuestToolsBridge starts the shared localhost HTTP bridge once and
|
||||
// registers any already-configured VMs so Guest Tools reconnects seamlessly
|
||||
// across reims-go restarts.
|
||||
func (a *App) ensureGuestToolsBridge() (*guesttools.Server, int, error) {
|
||||
// startGuestToolsServer starts the shared localhost HTTP bridge once. Only the
|
||||
// Guest Tools plugin and the no-plugin-manager fallback may call it; created
|
||||
// reports whether this call made a new server.
|
||||
func (a *App) startGuestToolsServer() (srv *guesttools.Server, port int, created bool, err error) {
|
||||
a.mu.Lock()
|
||||
srv := a.guestTools
|
||||
srv = a.guestTools
|
||||
if srv == nil {
|
||||
if a.pluginMgr != nil {
|
||||
srv = guesttools.NewTransportServer(nil)
|
||||
@@ -46,14 +49,43 @@ func (a *App) ensureGuestToolsBridge() (*guesttools.Server, int, error) {
|
||||
a.injectRemoteText(vmName, "", text)
|
||||
})
|
||||
a.guestTools = srv
|
||||
created = true
|
||||
}
|
||||
a.mu.Unlock()
|
||||
|
||||
port, err := srv.Start(guesttools.DefaultPort)
|
||||
port, err = srv.Start(guesttools.DefaultPort)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
return nil, 0, created, err
|
||||
}
|
||||
return srv, port, nil
|
||||
return srv, port, created, nil
|
||||
}
|
||||
|
||||
// ensureGuestToolsBridge returns the bridge for features built on Guest Tools.
|
||||
// With the plugin system up it only hands out the server the Guest Tools
|
||||
// plugin provides, so switching that plugin off really stops the localhost
|
||||
// listener instead of the next caller starting it again.
|
||||
func (a *App) ensureGuestToolsBridge() (*guesttools.Server, int, error) {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
loc := a.cfg.Locale
|
||||
a.mu.Unlock()
|
||||
if mgr != nil {
|
||||
raw, _ := mgr.Registry().LookupService(builtin.ServiceGuestToolsTransport)
|
||||
srv, _ := raw.(*guesttools.Server)
|
||||
if srv == nil || srv.Port() <= 0 {
|
||||
return nil, 0, errors.New(i18n.T(loc, "err.guest_tools_disabled"))
|
||||
}
|
||||
return srv, srv.Port(), nil
|
||||
}
|
||||
srv, port, _, err := a.startGuestToolsServer()
|
||||
return srv, port, err
|
||||
}
|
||||
|
||||
// guestToolsEnabled reports whether Guest Tools features are available right
|
||||
// now: always without a plugin manager, else only while its plugin is active.
|
||||
func (a *App) guestToolsEnabled() bool {
|
||||
_, _, err := a.ensureGuestToolsBridge()
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// inputBridgeEnv returns REIMS_GO_INPUT_URL and REIMS_GO_INPUT_TOKEN env vars
|
||||
@@ -83,6 +115,13 @@ func (a *App) registerExistingGuestTools(ctx context.Context) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
a.registerVMsWithBridge(ctx, srv, port)
|
||||
}
|
||||
|
||||
// registerVMsWithBridge registers every configured VM's token with srv, so a
|
||||
// guest agent that is already running reconnects after reims-go restarts or
|
||||
// the Guest Tools plugin is switched back on.
|
||||
func (a *App) registerVMsWithBridge(ctx context.Context, srv *guesttools.Server, port int) {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return
|
||||
@@ -114,6 +153,7 @@ func (a *App) populateGuestToolsDetail(d *reims.VMDetail) {
|
||||
return
|
||||
}
|
||||
d.GuestToolsAttached = reims.HasGuestToolsArgs(d.ExtraArgs)
|
||||
d.GuestToolsDisabled = !a.guestToolsEnabled()
|
||||
d.SharedDir = a.vmSharedDir(d.Name)
|
||||
if cfg, ok := guesttools.ReadVMConfig(d.Directory); ok {
|
||||
d.GuestToolsConfigured = true
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
)
|
||||
|
||||
// Switching the Guest Tools plugin off must stop the bridge for real: feature
|
||||
// calls get an error instead of quietly starting a new server.
|
||||
func TestGuestToolsBridgeFollowsPluginSwitch(t *testing.T) {
|
||||
dataRoot := t.TempDir()
|
||||
mgr, err := plugin.NewManager(plugin.ManagerOptions{DataRoot: dataRoot, HostVersion: "0.0.0"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer mgr.Close()
|
||||
cfg := config.Default()
|
||||
cfg.DataRoot = dataRoot
|
||||
cfg.Locale = i18n.EnUS
|
||||
a := &App{cfg: cfg, pluginMgr: mgr}
|
||||
|
||||
err = mgr.Registry().Register(plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{Schema: 1, ID: builtin.IDGuestTools, Version: "0.0.0"},
|
||||
Source: plugin.SourceBuiltin,
|
||||
Trust: plugin.TrustOfficial,
|
||||
Desired: false,
|
||||
Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
srv := guesttools.NewTransportServer(nil)
|
||||
if _, err := srv.Start(-1); err != nil {
|
||||
return err
|
||||
}
|
||||
sc.Provide(builtin.ServiceGuestToolsTransport, "1.0.0", srv)
|
||||
sc.OnDispose(func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
_ = srv.Close(ctx)
|
||||
})
|
||||
return nil
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr.Registry().Reconcile(context.Background())
|
||||
|
||||
if _, _, err := a.ensureGuestToolsBridge(); err == nil || !strings.Contains(err.Error(), "turned off") {
|
||||
t.Fatalf("plugin off: want a turned-off error, got %v", err)
|
||||
}
|
||||
if a.guestTools != nil {
|
||||
t.Fatal("plugin off: a feature call started the Guest Tools server")
|
||||
}
|
||||
|
||||
if err := mgr.Registry().SetDesired(context.Background(), builtin.IDGuestTools, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv, port, err := a.ensureGuestToolsBridge()
|
||||
if err != nil || srv == nil || port <= 0 {
|
||||
t.Fatalf("plugin on: want the plugin's server, got srv=%v port=%d err=%v", srv, port, err)
|
||||
}
|
||||
|
||||
if err := mgr.Registry().SetDesired(context.Background(), builtin.IDGuestTools, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a.guestToolsEnabled() {
|
||||
t.Fatal("plugin switched back off: Guest Tools still reported as available")
|
||||
}
|
||||
}
|
||||
@@ -20,9 +20,8 @@ func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) {
|
||||
|
||||
ledger := &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{}}
|
||||
active := map[string]bool{
|
||||
builtin.IDGuestTools: true,
|
||||
builtin.IDOfflineHelper: true,
|
||||
builtin.IDWin10ColdReboot: true,
|
||||
builtin.IDGuestTools: true,
|
||||
builtin.IDCore: true,
|
||||
}
|
||||
intents := []plugin.StartIntent{
|
||||
{
|
||||
@@ -33,16 +32,12 @@ func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) {
|
||||
}},
|
||||
},
|
||||
{
|
||||
PluginID: builtin.IDOfflineHelper,
|
||||
PluginID: builtin.IDCore,
|
||||
Args: []plugin.ArgFragment{{
|
||||
PluginID: builtin.IDOfflineHelper, Key: "reimshelp", Builtin: true, Priority: 85,
|
||||
PluginID: builtin.IDCore, Key: "reimshelp", Builtin: true, Priority: 85,
|
||||
Tokens: plugin.SplitShellTokens(reims.MergeOfflineHelperArgs("", `D:\Data\cache\reimshelp.img`)),
|
||||
}},
|
||||
},
|
||||
{
|
||||
PluginID: builtin.IDWin10ColdReboot,
|
||||
Args: []plugin.ArgFragment{{
|
||||
PluginID: builtin.IDWin10ColdReboot, Key: "win10-cold-reboot", Builtin: true, Priority: 95,
|
||||
}, {
|
||||
PluginID: builtin.IDCore, Key: "win10-cold-reboot", Builtin: true, Priority: 95,
|
||||
Tokens: plugin.SplitShellTokens(qmp.MergeWin10RebootUnixArgs("", `D:\Data\vms\mac\reims-go-reboot.sock`)),
|
||||
}},
|
||||
},
|
||||
@@ -63,8 +58,7 @@ func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) {
|
||||
// Simulate detaching Guest Tools & ejecting offline installer on next start.
|
||||
nextIntents := []plugin.StartIntent{
|
||||
{PluginID: builtin.IDGuestTools, ClearKeys: []string{"reimstools"}},
|
||||
{PluginID: builtin.IDOfflineHelper, ClearKeys: []string{"reimshelp"}},
|
||||
{PluginID: builtin.IDWin10ColdReboot, ClearKeys: []string{"win10-cold-reboot"}},
|
||||
{PluginID: builtin.IDCore, ClearKeys: []string{"reimshelp", "win10-cold-reboot"}},
|
||||
}
|
||||
base2 := stripLegacyManagedExtraArgs(res.ExtraArgs)
|
||||
res2 := plugin.ReconcileStartIntents(base2, ledger, active, nextIntents)
|
||||
@@ -80,3 +74,42 @@ func TestStripLegacyPreservesUserNoReboot(t *testing.T) {
|
||||
t.Fatalf("user -no-reboot was stripped unexpectedly: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A VM started before the builtins were merged has kernel-irqchip=off owned
|
||||
// by the retired whpx-fallback plugin. The core's WHPX step leaves an arg that
|
||||
// is already there alone, so without handing the fragment over it would be
|
||||
// stripped as belonging to a gone plugin and the next start could crash.
|
||||
func TestPreMergeLedgerFragmentsCarriedIntoCore(t *testing.T) {
|
||||
irq := plugin.ArgFragment{
|
||||
PluginID: "builtin.compat.whpx-fallback", Key: "kernel-irqchip", Builtin: true, Priority: 90,
|
||||
Tokens: []string{"-machine", "kernel-irqchip=off"},
|
||||
}
|
||||
extra := "-cpu host -machine kernel-irqchip=off"
|
||||
active := map[string]bool{builtin.IDCore: true}
|
||||
intents := []plugin.StartIntent{{PluginID: builtin.IDCore}}
|
||||
newLedger := func() *plugin.ArgLedger {
|
||||
return &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{
|
||||
"builtin.compat.whpx-fallback": {irq},
|
||||
}}
|
||||
}
|
||||
|
||||
unmigrated := plugin.ReconcileStartIntents(extra, newLedger(), active, intents)
|
||||
if strings.Contains(unmigrated.ExtraArgs, "kernel-irqchip") {
|
||||
t.Fatalf("test premise: an unmigrated ledger should drop the fragment, got %q", unmigrated.ExtraArgs)
|
||||
}
|
||||
|
||||
ledger := newLedger()
|
||||
if !builtin.MigrateLedger(ledger) {
|
||||
t.Fatal("MigrateLedger reported no change for a retired owner")
|
||||
}
|
||||
res := plugin.ReconcileStartIntents(extra, ledger, active, intents)
|
||||
if got := strings.Count(res.ExtraArgs, "kernel-irqchip=off"); got != 1 {
|
||||
t.Fatalf("want kernel-irqchip=off carried exactly once, got %d in %q", got, res.ExtraArgs)
|
||||
}
|
||||
if !strings.Contains(res.ExtraArgs, "-cpu host") {
|
||||
t.Fatalf("user arg lost: %q", res.ExtraArgs)
|
||||
}
|
||||
if builtin.MigrateLedger(ledger) {
|
||||
t.Fatal("MigrateLedger should be a no-op once migrated")
|
||||
}
|
||||
}
|
||||
@@ -82,9 +82,6 @@ func (a *App) initPlugins() {
|
||||
mgr.Registry().SetInUseChecker(func(pluginID string) (bool, string, error) {
|
||||
// Must not call Registry.Info/List here: both invoke this checker,
|
||||
// which recursed until the goroutine stack overflowed at startup.
|
||||
if pluginID == builtin.IDDriverReimsMacOS {
|
||||
return drvRouter.CheckDriverInUse(context.Background(), builtin.IDDriverReimsMacOS)
|
||||
}
|
||||
// Check all guest driver IDs declared by this plugin (even when disabled) plus pluginID itself.
|
||||
seen := map[string]bool{}
|
||||
candidates := append([]string{pluginID}, mgr.Registry().DeclaredDriverIDs(pluginID)...)
|
||||
@@ -115,7 +112,13 @@ func (a *App) initPlugins() {
|
||||
a.emitLog(source, line)
|
||||
},
|
||||
EnsureGuestTools: func() (*guesttools.Server, int, error) {
|
||||
return a.ensureGuestToolsBridge()
|
||||
srv, port, created, err := a.startGuestToolsServer()
|
||||
if err == nil && created {
|
||||
// A fresh server knows no VM tokens: at startup and when the
|
||||
// plugin is switched back on, re-register configured VMs.
|
||||
go a.registerVMsWithBridge(context.Background(), srv, port)
|
||||
}
|
||||
return srv, port, err
|
||||
},
|
||||
StopGuestTools: func() {
|
||||
a.mu.Lock()
|
||||
@@ -144,11 +147,18 @@ func (a *App) initPlugins() {
|
||||
GuestToolsImg: func(vmName string) string {
|
||||
return a.guestToolsImagePath(vmName)
|
||||
},
|
||||
GetSetting: func(pluginID, vmName, key string) (any, bool) {
|
||||
v, ok := mgr.GetSettings(pluginID, vmName, false)[key]
|
||||
return v, ok
|
||||
},
|
||||
}
|
||||
|
||||
if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
||||
a.emitLog("plugin", "Builtin extension register error: "+err.Error())
|
||||
}
|
||||
if err := builtin.MigrateRetired(mgr); err != nil {
|
||||
a.emitLog("plugin", "Could not migrate merged core plugin state: "+err.Error())
|
||||
}
|
||||
if err := mgr.LoadExternal(); err != nil {
|
||||
a.emitLog("plugin", "External plugin load warning: "+err.Error())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/netproxy"
|
||||
)
|
||||
|
||||
const (
|
||||
qqGroupID = "1136042744"
|
||||
qqGroupShortURL = "https://qm.qq.com/q/TBmRJlVbSo"
|
||||
qqGroupAuthCacheTTL = 10 * time.Minute
|
||||
qqGroupLookupTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
var errQQNotInstalled = errors.New("qq not installed")
|
||||
|
||||
type qqGroupAuth struct {
|
||||
groupCode string
|
||||
authKey string
|
||||
}
|
||||
|
||||
type qqGroupWPAParam struct {
|
||||
GroupUin string `json:"groupUin"`
|
||||
TimeStamp int64 `json:"timeStamp"`
|
||||
AuthKey string `json:"authKey"`
|
||||
Auth string `json:"auth"`
|
||||
}
|
||||
|
||||
var qqGroupAuthCache struct {
|
||||
sync.Mutex
|
||||
at time.Time
|
||||
auth *qqGroupAuth
|
||||
}
|
||||
|
||||
// CanOpenQQGroup reports whether a local QQ protocol handler is installed and
|
||||
// ready to be launched directly without opening a browser.
|
||||
func (a *App) CanOpenQQGroup() bool {
|
||||
return hasQQProtocolHandler()
|
||||
}
|
||||
|
||||
// OpenQQGroup launches the local QQ desktop client directly to the community
|
||||
// group join dialog via the tencent://groupwpa/ protocol. It returns an error
|
||||
// rather than falling back to a web browser when QQ is not installed or the
|
||||
// invite token cannot be resolved.
|
||||
func (a *App) OpenQQGroup() error {
|
||||
if !hasQQProtocolHandler() {
|
||||
return errQQNotInstalled
|
||||
}
|
||||
auth, err := resolveQQGroupAuth(a.baseCtx())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
schemeURL := buildQQGroupSchemeURL(auth.groupCode, auth.authKey, time.Now())
|
||||
return launchQQProtocol(schemeURL)
|
||||
}
|
||||
|
||||
func resolveQQGroupAuth(ctx context.Context) (qqGroupAuth, error) {
|
||||
qqGroupAuthCache.Lock()
|
||||
if qqGroupAuthCache.auth != nil && time.Since(qqGroupAuthCache.at) < qqGroupAuthCacheTTL {
|
||||
cached := *qqGroupAuthCache.auth
|
||||
qqGroupAuthCache.Unlock()
|
||||
return cached, nil
|
||||
}
|
||||
qqGroupAuthCache.Unlock()
|
||||
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
reqCtx, cancel := context.WithTimeout(ctx, qqGroupLookupTimeout)
|
||||
defer cancel()
|
||||
|
||||
req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, qqGroupShortURL, nil)
|
||||
if err != nil {
|
||||
return qqGroupAuth{}, err
|
||||
}
|
||||
client := &http.Client{
|
||||
Transport: netproxy.NewTransport(),
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return qqGroupAuth{}, fmt.Errorf("resolve QQ group invite: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
location := strings.TrimSpace(resp.Header.Get("Location"))
|
||||
if location == "" {
|
||||
return qqGroupAuth{}, fmt.Errorf("QQ group invite did not redirect (HTTP %d)", resp.StatusCode)
|
||||
}
|
||||
auth, err := parseQQGroupRedirect(location)
|
||||
if err != nil {
|
||||
return qqGroupAuth{}, err
|
||||
}
|
||||
|
||||
qqGroupAuthCache.Lock()
|
||||
copyAuth := auth
|
||||
qqGroupAuthCache.at = time.Now()
|
||||
qqGroupAuthCache.auth = ©Auth
|
||||
qqGroupAuthCache.Unlock()
|
||||
return auth, nil
|
||||
}
|
||||
|
||||
func parseQQGroupRedirect(location string) (qqGroupAuth, error) {
|
||||
u, err := url.Parse(strings.TrimSpace(location))
|
||||
if err != nil {
|
||||
return qqGroupAuth{}, fmt.Errorf("parse QQ group redirect: %w", err)
|
||||
}
|
||||
if !strings.EqualFold(u.Scheme, "https") {
|
||||
return qqGroupAuth{}, errors.New("unexpected non-HTTPS QQ group redirect")
|
||||
}
|
||||
q := u.Query()
|
||||
authKey := strings.TrimSpace(q.Get("authKey"))
|
||||
if authKey == "" {
|
||||
return qqGroupAuth{}, errors.New("QQ group redirect missing authKey")
|
||||
}
|
||||
|
||||
groupCode := qqGroupID
|
||||
if busiData := strings.TrimSpace(q.Get("busi_data")); busiData != "" {
|
||||
if decoded, ok := decodeBase64Flexible(busiData); ok {
|
||||
var payload struct {
|
||||
GroupCode string `json:"groupCode"`
|
||||
}
|
||||
if json.Unmarshal(decoded, &payload) == nil && isDigits(payload.GroupCode) {
|
||||
groupCode = payload.GroupCode
|
||||
}
|
||||
}
|
||||
}
|
||||
return qqGroupAuth{
|
||||
groupCode: groupCode,
|
||||
authKey: authKey,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func buildQQGroupSchemeURL(groupUin, authKey string, now time.Time) string {
|
||||
raw, _ := json.Marshal(qqGroupWPAParam{
|
||||
GroupUin: groupUin,
|
||||
TimeStamp: now.UnixMilli(),
|
||||
AuthKey: authKey,
|
||||
Auth: "",
|
||||
})
|
||||
return "tencent://groupwpa/?subcmd=all¶m=" + strings.ToUpper(hex.EncodeToString(raw)) + "&jump_from="
|
||||
}
|
||||
|
||||
func decodeBase64Flexible(s string) ([]byte, bool) {
|
||||
for _, enc := range []*base64.Encoding{
|
||||
base64.StdEncoding,
|
||||
base64.RawStdEncoding,
|
||||
base64.URLEncoding,
|
||||
base64.RawURLEncoding,
|
||||
} {
|
||||
if b, err := enc.DecodeString(s); err == nil {
|
||||
return b, true
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func isDigits(s string) bool {
|
||||
if s == "" {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] < '0' || s[i] > '9' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func extractCommandExecutable(cmd string) string {
|
||||
cmd = strings.TrimSpace(cmd)
|
||||
if cmd == "" {
|
||||
return ""
|
||||
}
|
||||
if cmd[0] == '"' {
|
||||
if end := strings.IndexByte(cmd[1:], '"'); end > 0 {
|
||||
return strings.TrimSpace(cmd[1 : 1+end])
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if sp := strings.IndexAny(cmd, " \t"); sp > 0 {
|
||||
return cmd[:sp]
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
//go:build !windows
|
||||
|
||||
package app
|
||||
|
||||
func hasQQProtocolHandler() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func launchQQProtocol(string) error {
|
||||
return errQQNotInstalled
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestParseQQGroupRedirect(t *testing.T) {
|
||||
loc := "https://qun.qq.com/universal-share/share?ac=1&authKey=0gmB8kE9XLpaQhm%2FxA2hrXECer6N8BpXCVjjDbYXyVdxHFmXNqtpw2ffMdFhqYKU&busi_data=eyJncm91cENvZGUiOiIxMTM2MDQyNzQ0IiwidG9rZW4iOiJ0ZXN0IiwidWluIjoiMTIzIn0%3D&svctype=5"
|
||||
auth, err := parseQQGroupRedirect(loc)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if auth.groupCode != "1136042744" {
|
||||
t.Fatalf("groupCode = %q, want 1136042744", auth.groupCode)
|
||||
}
|
||||
if auth.authKey != "0gmB8kE9XLpaQhm/xA2hrXECer6N8BpXCVjjDbYXyVdxHFmXNqtpw2ffMdFhqYKU" {
|
||||
t.Fatalf("authKey = %q", auth.authKey)
|
||||
}
|
||||
|
||||
if _, err := parseQQGroupRedirect("http://qun.qq.com/universal-share/share?authKey=abc"); err == nil {
|
||||
t.Fatal("expected error for non-HTTPS redirect")
|
||||
}
|
||||
if _, err := parseQQGroupRedirect("https://qun.qq.com/universal-share/share?ac=1"); err == nil {
|
||||
t.Fatal("expected error when authKey is missing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildQQGroupSchemeURL(t *testing.T) {
|
||||
ts := time.UnixMilli(1730000000123)
|
||||
got := buildQQGroupSchemeURL("1136042744", "key/with+chars", ts)
|
||||
const prefix = "tencent://groupwpa/?subcmd=all¶m="
|
||||
const suffix = "&jump_from="
|
||||
if !strings.HasPrefix(got, prefix) || !strings.HasSuffix(got, suffix) {
|
||||
t.Fatalf("unexpected scheme URL: %q", got)
|
||||
}
|
||||
hexPart := strings.TrimSuffix(strings.TrimPrefix(got, prefix), suffix)
|
||||
if hexPart != strings.ToUpper(hexPart) {
|
||||
t.Fatalf("expected uppercase hex param, got %q", hexPart)
|
||||
}
|
||||
raw, err := hex.DecodeString(hexPart)
|
||||
if err != nil {
|
||||
t.Fatalf("decode hex: %v", err)
|
||||
}
|
||||
var param qqGroupWPAParam
|
||||
if err := json.Unmarshal(raw, ¶m); err != nil {
|
||||
t.Fatalf("unmarshal param: %v", err)
|
||||
}
|
||||
if param.GroupUin != "1136042744" || param.TimeStamp != 1730000000123 || param.AuthKey != "key/with+chars" || param.Auth != "" {
|
||||
t.Fatalf("unexpected decoded param: %+v", param)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractCommandExecutable(t *testing.T) {
|
||||
cases := []struct {
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{`"D:\Program Files\Tencent\QQNT\versions\9.9.37-54395\resources\app\timwp.exe" "%1"`, `D:\Program Files\Tencent\QQNT\versions\9.9.37-54395\resources\app\timwp.exe`},
|
||||
{`C:\QQ\timwp.exe "%1"`, `C:\QQ\timwp.exe`},
|
||||
{` `, ``},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := extractCommandExecutable(tc.in); got != tc.want {
|
||||
t.Errorf("extractCommandExecutable(%q) = %q, want %q", tc.in, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
//go:build windows
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/windows/registry"
|
||||
)
|
||||
|
||||
var (
|
||||
qqShell32 = syscall.NewLazyDLL("shell32.dll")
|
||||
qqProcShellExecW = qqShell32.NewProc("ShellExecuteW")
|
||||
)
|
||||
|
||||
func hasQQProtocolHandler() bool {
|
||||
type regLoc struct {
|
||||
root registry.Key
|
||||
path string
|
||||
}
|
||||
locs := []regLoc{
|
||||
{registry.CURRENT_USER, `Software\Classes\tencent\shell\open\command`},
|
||||
{registry.CLASSES_ROOT, `tencent\shell\open\command`},
|
||||
}
|
||||
for _, loc := range locs {
|
||||
k, err := registry.OpenKey(loc.root, loc.path, registry.QUERY_VALUE)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
val, _, err := k.GetStringValue("")
|
||||
_ = k.Close()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
exe := extractCommandExecutable(val)
|
||||
if exe == "" {
|
||||
continue
|
||||
}
|
||||
if expanded, err := registry.ExpandString(exe); err == nil && expanded != "" {
|
||||
exe = expanded
|
||||
}
|
||||
if fi, err := os.Stat(exe); err == nil && !fi.IsDir() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func launchQQProtocol(uri string) error {
|
||||
trimmed := strings.TrimSpace(uri)
|
||||
if !strings.HasPrefix(trimmed, "tencent://groupwpa/") {
|
||||
return errors.New("refusing to open non-QQ-group protocol URL")
|
||||
}
|
||||
verb, err := syscall.UTF16PtrFromString("open")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
target, err := syscall.UTF16PtrFromString(trimmed)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r, _, callErr := qqProcShellExecW.Call(
|
||||
0,
|
||||
uintptr(unsafe.Pointer(verb)),
|
||||
uintptr(unsafe.Pointer(target)),
|
||||
0,
|
||||
0,
|
||||
1, // SW_SHOWNORMAL
|
||||
)
|
||||
if r <= 32 {
|
||||
return fmt.Errorf("ShellExecuteW tencent protocol failed (code %d): %w", r, callErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -44,9 +44,6 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, *
|
||||
return filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms")
|
||||
})
|
||||
mgr.Registry().SetInUseChecker(func(pluginID string) (bool, string, error) {
|
||||
if pluginID == builtin.IDDriverReimsMacOS {
|
||||
return router.CheckDriverInUse(context.Background(), builtin.IDDriverReimsMacOS)
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
candidates := append([]string{pluginID}, mgr.Registry().DeclaredDriverIDs(pluginID)...)
|
||||
for _, did := range candidates {
|
||||
@@ -64,6 +61,9 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, *
|
||||
mgr.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
if err := builtin.MigrateRetired(mgr); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "[plugin] could not migrate merged core plugin state: %v\n", err)
|
||||
}
|
||||
_ = mgr.LoadExternal()
|
||||
mgr.Registry().Reconcile(context.Background())
|
||||
|
||||
|
||||
@@ -13,6 +13,8 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
@@ -45,6 +47,9 @@ func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name s
|
||||
return startInWindow(ctx, cfg, name)
|
||||
}
|
||||
|
||||
// Honour the core plugin's WHPX setting, as the window does.
|
||||
st := plugin.ReadState(cfg.DataRoot)
|
||||
prep.SkipWHPXFallback = !builtin.CoreSettingOnInState(st, builtin.SettingWHPXFallback)
|
||||
prep.Prepare(ctx, name, rep, &d)
|
||||
if err := prep.Client.StartWithCompat(ctx, name, os.Stdout, os.Stderr, func(msg string) {
|
||||
fmt.Fprintln(os.Stderr, msg)
|
||||
|
||||
@@ -77,8 +77,10 @@ type VMDetail struct {
|
||||
GuestToolsPreventSleep bool `json:"guest_tools_prevent_sleep"`
|
||||
GuestToolsSleepActive bool `json:"guest_tools_sleep_active"`
|
||||
GuestToolsAgentVersion int `json:"guest_tools_agent_version,omitempty"`
|
||||
SharedDir string `json:"shared_dir,omitempty"`
|
||||
GuestLang string `json:"guest_lang,omitempty"`
|
||||
// GuestToolsDisabled is set when the Guest Tools plugin is switched off.
|
||||
GuestToolsDisabled bool `json:"guest_tools_disabled,omitempty"`
|
||||
SharedDir string `json:"shared_dir,omitempty"`
|
||||
GuestLang string `json:"guest_lang,omitempty"`
|
||||
}
|
||||
|
||||
type ValidationIssue struct {
|
||||
|
||||
@@ -297,8 +297,10 @@ func (s *Server) Start(preferredPort int) (int, error) {
|
||||
s.watcherCount.Add(1)
|
||||
go s.watchClipboardLoop(watchCtx)
|
||||
}
|
||||
// Close may clear s.httpSrv before this goroutine runs; serve the copy.
|
||||
hs := s.httpSrv
|
||||
go func() {
|
||||
_ = s.httpSrv.Serve(ln)
|
||||
_ = hs.Serve(ln)
|
||||
}()
|
||||
return s.port, nil
|
||||
}
|
||||
@@ -369,6 +371,7 @@ func (s *Server) Close(ctx context.Context) error {
|
||||
cancel := s.watchCancel
|
||||
s.httpSrv = nil
|
||||
s.listener = nil
|
||||
s.port = 0
|
||||
s.watchCancel = nil
|
||||
s.mu.Unlock()
|
||||
if cancel != nil {
|
||||
|
||||
@@ -85,6 +85,7 @@ var catalog = map[Locale]map[string]string{
|
||||
"vm.install_guide.step2": "2. 回到「恢复」窗口,选「重新安装 macOS」,装到刚抹掉的磁盘上(中途会自动重启几次)。",
|
||||
"vm.install_guide.step3": "3. 看到「设置助理」后,运行 `reims-go vm eject %s`(或在界面点「退出恢复模式」)移除安装盘,下次启动生效。",
|
||||
"err.runtime_not_installed": "未找到已激活的便携运行时,请先执行 `reims-go runtime install <归档路径>`",
|
||||
"err.guest_tools_disabled": "Guest Tools 传输服务已在插件页停用,启用后才能使用剪贴板、共享文件夹与防休眠",
|
||||
"err.commit_memory": "内存不够启动:这台虚拟机要 %.0f GB,Windows 现在只能再分配 %.1f GB。关掉一些程序再试,或在设置里把内存改为 %.0f GB",
|
||||
"installer.paused": "已暂停。再次运行 `reims-go installer download %s` 会从中断处继续。",
|
||||
"installer.done": "离线安装包已就绪:macOS %s -> %s",
|
||||
@@ -168,6 +169,7 @@ var catalog = map[Locale]map[string]string{
|
||||
"vm.install_guide.step2": "2. Back in the Recovery window, choose 'Reinstall macOS' and install onto the disk you erased (it restarts a few times).",
|
||||
"vm.install_guide.step3": "3. When Setup Assistant appears, run `reims-go vm eject %s` (or click 'Exit recovery mode') to remove the installer at next start.",
|
||||
"err.runtime_not_installed": "no active portable runtime found; run `reims-go runtime install <archive>` first",
|
||||
"err.guest_tools_disabled": "Guest Tools Transport is turned off on the Plugins page; turn it on to use clipboard, shared folders and keep-awake",
|
||||
"err.commit_memory": "Not enough memory to start: this VM needs %.0f GB and Windows can commit only %.1f GB more. Close some programs, or set its memory to %.0f GB",
|
||||
"installer.paused": "Paused. Run `reims-go installer download %s` again to continue where it stopped.",
|
||||
"installer.done": "Offline installer ready: macOS %s -> %s",
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
// Package builtin registers compiled-in Reims-Go extensions onto the unified
|
||||
// plugin Registry (docs/plugin-architecture.md §3.2, §5.4). Every builtin
|
||||
// extension runs through the same reversible Scope, service dependency graph,
|
||||
// and HookBus as external plugins so disabling any extension leaves zero residue.
|
||||
// runs through the same reversible Scope, service dependency graph and HookBus
|
||||
// as external plugins. The core (core.go) is always on; disabling any optional
|
||||
// extension leaves zero residue.
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
@@ -16,27 +15,21 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/opencore"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
// Builtin plugin IDs (§3.2, §5.4).
|
||||
// Builtin plugin IDs (§3.2, §5.4). IDCore lives in core.go.
|
||||
const (
|
||||
IDThemeDefault = "builtin.theme.default"
|
||||
// IDThemeDefault is the default theme's contribution ID; the core plugin
|
||||
// contributes it.
|
||||
IDThemeDefault = "builtin.theme.default"
|
||||
// IDDriverReimsMacOS is the guest driver ID of the reims macOS driver,
|
||||
// recorded in VM ownership markers; the core plugin registers it.
|
||||
IDDriverReimsMacOS = driver.BuiltinReimsMacOSDriverID
|
||||
IDGuestTools = "builtin.bridge.guest-tools"
|
||||
IDClipboard = "builtin.bridge.clipboard"
|
||||
IDInput = "builtin.input"
|
||||
IDWin10ColdReboot = "builtin.compat.win10-cold-reboot"
|
||||
IDWHPXFallback = "builtin.compat.whpx-fallback"
|
||||
IDOfflineHelper = "builtin.prep.offline-helper"
|
||||
IDRecoveryBoot = "builtin.prep.recovery-boot"
|
||||
IDGuestLang = "builtin.prep.guest-lang"
|
||||
)
|
||||
|
||||
// Service names provided by builtin extensions.
|
||||
@@ -70,7 +63,7 @@ func appVersion() string {
|
||||
return v
|
||||
}
|
||||
|
||||
// RegisterAll registers all Phase 0 builtin extensions into reg.
|
||||
// RegisterAll registers the core and the optional builtin extensions into reg.
|
||||
// desiredFn optionally overrides defaultEnabled (e.g. from state.json).
|
||||
func RegisterAll(reg *plugin.Registry, cb HostCallbacks, desiredFn func(id string, defaultEnabled bool) bool) error {
|
||||
if desiredFn == nil {
|
||||
@@ -78,16 +71,10 @@ func RegisterAll(reg *plugin.Registry, cb HostCallbacks, desiredFn func(id strin
|
||||
}
|
||||
ver := appVersion()
|
||||
defs := []plugin.PluginDef{
|
||||
defThemeDefault(ver, desiredFn),
|
||||
defDriverReimsMacOS(ver, cb, desiredFn),
|
||||
defCore(ver, cb),
|
||||
defGuestTools(ver, cb, desiredFn),
|
||||
defClipboard(ver, cb, desiredFn),
|
||||
defInput(ver, cb, desiredFn),
|
||||
defWin10ColdReboot(ver, cb, desiredFn),
|
||||
defWHPXFallback(ver, cb, desiredFn),
|
||||
defOfflineHelper(ver, cb, desiredFn),
|
||||
defRecoveryBoot(ver, cb, desiredFn),
|
||||
defGuestLang(ver, cb, desiredFn),
|
||||
}
|
||||
for _, d := range defs {
|
||||
if err := reg.Register(d); err != nil {
|
||||
@@ -97,61 +84,6 @@ func RegisterAll(reg *plugin.Registry, cb HostCallbacks, desiredFn func(id strin
|
||||
return nil
|
||||
}
|
||||
|
||||
func defThemeDefault(ver string, desiredFn func(string, bool) bool) plugin.PluginDef {
|
||||
return plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: IDThemeDefault,
|
||||
Version: ver,
|
||||
Name: plugin.LocalizedText{ZhCN: "默认浅色 / 深色主题", EnUS: "Default Light / Dark Theme"},
|
||||
Description: plugin.LocalizedText{
|
||||
ZhCN: "内置 macOS Tahoe 风格浅色与深色主题,零额外样式注入",
|
||||
EnUS: "Built-in macOS Tahoe light and dark themes with zero extra CSS overhead",
|
||||
},
|
||||
Publisher: "Reims-Go",
|
||||
License: "Apache-2.0",
|
||||
DefaultEnabled: true,
|
||||
Contributes: plugin.Contributes{
|
||||
Themes: []plugin.ThemeContribution{{
|
||||
ID: IDThemeDefault,
|
||||
Name: plugin.LocalizedText{ZhCN: "默认主题", EnUS: "Default"},
|
||||
Appearance: "both",
|
||||
}},
|
||||
},
|
||||
},
|
||||
Source: plugin.SourceBuiltin,
|
||||
Trust: plugin.TrustOfficial,
|
||||
Desired: desiredFn(IDThemeDefault, true),
|
||||
}
|
||||
}
|
||||
|
||||
func defDriverReimsMacOS(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
|
||||
return plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: IDDriverReimsMacOS,
|
||||
Version: ver,
|
||||
Name: plugin.LocalizedText{ZhCN: "macOS 虚拟机驱动 (Reims vGPU)", EnUS: "macOS VM Driver (Reims vGPU)"},
|
||||
Description: plugin.LocalizedText{
|
||||
ZhCN: "内置 reims-ctl / reims-vgpu macOS 虚拟机驱动,支持 Metal Vulkan 加速、OpenCore 与快照",
|
||||
EnUS: "Built-in reims-ctl / reims-vgpu macOS VM driver with Metal-to-Vulkan acceleration, OpenCore, and snapshots",
|
||||
},
|
||||
Publisher: "Reims-Go",
|
||||
License: "Apache-2.0",
|
||||
Permissions: []string{"driver:vm", "vm:control", "qmp:write"},
|
||||
DefaultEnabled: true,
|
||||
},
|
||||
Source: plugin.SourceBuiltin,
|
||||
Trust: plugin.TrustOfficial,
|
||||
Desired: desiredFn(IDDriverReimsMacOS, true),
|
||||
Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
drv := driver.NewReimsMacOSDriver(cb.GetConfig)
|
||||
sc.Registry().RegisterGuestDriver(sc, IDDriverReimsMacOS, drv)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func defGuestTools(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
|
||||
return plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{
|
||||
@@ -160,8 +92,8 @@ func defGuestTools(ver string, cb HostCallbacks, desiredFn func(string, bool) bo
|
||||
Version: ver,
|
||||
Name: plugin.LocalizedText{ZhCN: "Guest Tools 传输服务", EnUS: "Guest Tools Transport"},
|
||||
Description: plugin.LocalizedText{
|
||||
ZhCN: "提供本地回环鉴权宿客传输通道、REIMSTOOLS 辅助盘挂载、共享目录与防休眠支持",
|
||||
EnUS: "Provides localhost token-authenticated host-guest transport, REIMSTOOLS helper disk, shared folders, and prevent-sleep",
|
||||
ZhCN: "宿主与虚拟机之间的通信通道,支撑共享文件夹和防休眠",
|
||||
EnUS: "Host–guest channel behind shared folders and keep-awake",
|
||||
},
|
||||
Publisher: "Reims-Go",
|
||||
License: "Apache-2.0",
|
||||
@@ -265,8 +197,8 @@ func defClipboard(ver string, cb HostCallbacks, desiredFn func(string, bool) boo
|
||||
Version: ver,
|
||||
Name: plugin.LocalizedText{ZhCN: "剪贴板互通", EnUS: "Clipboard Sync"},
|
||||
Description: plugin.LocalizedText{
|
||||
ZhCN: "在 Windows 宿主与 macOS 虚拟机之间同步文本与截图;支持按方向与大小限制即时开关",
|
||||
EnUS: "Sync text and screenshots between Windows host and macOS VMs with per-VM direction and size controls",
|
||||
ZhCN: "在 Windows 和 macOS 之间同步复制的文本与截图",
|
||||
EnUS: "Sync copied text and screenshots between Windows and macOS",
|
||||
},
|
||||
Publisher: "Reims-Go",
|
||||
License: "Apache-2.0",
|
||||
@@ -379,8 +311,8 @@ func defInput(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) p
|
||||
Version: ver,
|
||||
Name: plugin.LocalizedText{ZhCN: "宿主输入服务与 IME 桥接", EnUS: "Host Input Service & IME Bridge"},
|
||||
Description: plugin.LocalizedText{
|
||||
ZhCN: "管理远程输入法键入钩子与声明式鼠标输入过滤器,停用后立即卸载钩子线程",
|
||||
EnUS: "Manages the remote IME keyboard hook and declarative mouse input filters; unloads hook threads on disable",
|
||||
ZhCN: "用 Windows 输入法直接向虚拟机输入文字",
|
||||
EnUS: "Type into the VM directly with the Windows IME",
|
||||
},
|
||||
Publisher: "Reims-Go",
|
||||
License: "Apache-2.0",
|
||||
@@ -406,367 +338,3 @@ func defInput(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) p
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func defWin10ColdReboot(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
|
||||
return plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: IDWin10ColdReboot,
|
||||
Version: ver,
|
||||
Name: plugin.LocalizedText{ZhCN: "Windows 10 冷重启补偿", EnUS: "Windows 10 Cold-Reboot Workaround"},
|
||||
Description: plugin.LocalizedText{
|
||||
ZhCN: "在缺少 WHvResetPartition 的 Windows 10 上通过独立 QMP 通道监听客体重启并自动重新拉起",
|
||||
EnUS: "Uses an isolated QMP channel with -no-reboot on Windows 10 to restart guests cleanly in a new Hyper-V partition",
|
||||
},
|
||||
Publisher: "Reims-Go",
|
||||
License: "Apache-2.0",
|
||||
Permissions: []string{"vm:intent", "qmp:write"},
|
||||
DefaultEnabled: true,
|
||||
},
|
||||
Source: plugin.SourceBuiltin,
|
||||
Trust: plugin.TrustOfficial,
|
||||
Desired: desiredFn(IDWin10ColdReboot, true),
|
||||
Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
|
||||
Event: plugin.EventVMBeforeStart,
|
||||
Builtin: true,
|
||||
Handler: func(_ context.Context, raw any) (any, error) {
|
||||
p, ok := raw.(plugin.BeforeStartPayload)
|
||||
if !ok || p.DriverID != IDDriverReimsMacOS {
|
||||
return nil, nil
|
||||
}
|
||||
needs, _ := p.HostFacts["host.needs_cold_reboot"].(bool)
|
||||
if !needs {
|
||||
return plugin.StartIntent{
|
||||
PluginID: IDWin10ColdReboot,
|
||||
ClearKeys: []string{"win10-cold-reboot"},
|
||||
}, nil
|
||||
}
|
||||
tmpDir := ""
|
||||
if cb.GetConfig != nil {
|
||||
cfg := cb.GetConfig()
|
||||
tmpDir = cfg.TempDir()
|
||||
}
|
||||
sockPath := qmp.RebootSocketPath(p.VMDir, tmpDir, p.VMName)
|
||||
_ = os.MkdirAll(filepath.Dir(sockPath), 0o755)
|
||||
_ = os.Remove(sockPath)
|
||||
tokens := plugin.SplitShellTokens(qmp.MergeWin10RebootUnixArgs("", sockPath))
|
||||
return plugin.StartIntent{
|
||||
PluginID: IDWin10ColdReboot,
|
||||
Args: []plugin.ArgFragment{{
|
||||
PluginID: IDWin10ColdReboot,
|
||||
Key: "win10-cold-reboot",
|
||||
Tokens: tokens,
|
||||
Builtin: true,
|
||||
Priority: 95,
|
||||
}},
|
||||
PostStart: []plugin.PostStartAction{{
|
||||
PluginID: IDWin10ColdReboot,
|
||||
Kind: "qmp.watch_cold_reboot",
|
||||
Params: map[string]any{"qmp_addr": "unix:" + sockPath},
|
||||
}},
|
||||
}, nil
|
||||
},
|
||||
})
|
||||
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
|
||||
Event: plugin.EventVMAfterStart,
|
||||
Builtin: true,
|
||||
Handler: func(_ context.Context, raw any) (any, error) {
|
||||
ev, ok := raw.(plugin.VMEventPayload)
|
||||
if ok && ev.QMPAddr != "" && cb.StartColdReboot != nil {
|
||||
cb.StartColdReboot(ev.VMName, ev.QMPAddr)
|
||||
}
|
||||
return nil, nil
|
||||
},
|
||||
})
|
||||
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
|
||||
Event: plugin.EventVMAfterStop,
|
||||
Builtin: true,
|
||||
Handler: func(_ context.Context, raw any) (any, error) {
|
||||
ev, ok := raw.(plugin.VMEventPayload)
|
||||
if ok && cb.CancelColdReboot != nil {
|
||||
cb.CancelColdReboot(ev.VMName)
|
||||
}
|
||||
return nil, nil
|
||||
},
|
||||
})
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func defWHPXFallback(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
|
||||
return plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: IDWHPXFallback,
|
||||
Version: ver,
|
||||
Name: plugin.LocalizedText{ZhCN: "WHPX 兼容降级", EnUS: "WHPX Compatibility Fallback"},
|
||||
Description: plugin.LocalizedText{
|
||||
ZhCN: "根据宿主嵌套虚拟化探测与运行时能力自动应用 kernel-irqchip=off 避免首次启动崩溃",
|
||||
EnUS: "Automatically applies kernel-irqchip=off based on host nested-virt probes and runtime capabilities",
|
||||
},
|
||||
Publisher: "Reims-Go",
|
||||
License: "Apache-2.0",
|
||||
Permissions: []string{"vm:intent"},
|
||||
DefaultEnabled: true,
|
||||
},
|
||||
Source: plugin.SourceBuiltin,
|
||||
Trust: plugin.TrustOfficial,
|
||||
Desired: desiredFn(IDWHPXFallback, true),
|
||||
Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
|
||||
Event: plugin.EventHostPreflight,
|
||||
Builtin: true,
|
||||
Handler: func(_ context.Context, raw any) (any, error) {
|
||||
p, ok := raw.(plugin.PreflightPayload)
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
needsCold, _ := p.HostFacts["host.needs_cold_reboot"].(bool)
|
||||
irqAvail, _ := p.HostFacts["host.whpx_irqchip"].(bool)
|
||||
nestedOK, _ := p.HostFacts["host.whpx_nested_virt"].(bool)
|
||||
hasCap := false
|
||||
if caps, ok := p.HostFacts["runtime.capabilities"].([]string); ok {
|
||||
for _, c := range caps {
|
||||
if strings.EqualFold(c, "nested-virt-nonfatal") {
|
||||
hasCap = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if !needsCold && irqAvail && !nestedOK && !hasCap {
|
||||
return plugin.PreflightResult{
|
||||
Advices: []string{"Host lacks nested-virt property and runtime lacks nested-virt-nonfatal capability; kernel-irqchip=off will be auto-applied"},
|
||||
}, nil
|
||||
}
|
||||
return nil, nil
|
||||
},
|
||||
})
|
||||
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
|
||||
Event: plugin.EventVMBeforeStart,
|
||||
Builtin: true,
|
||||
Handler: func(_ context.Context, raw any) (any, error) {
|
||||
p, ok := raw.(plugin.BeforeStartPayload)
|
||||
if !ok || p.DriverID != IDDriverReimsMacOS {
|
||||
return nil, nil
|
||||
}
|
||||
needsCold, _ := p.HostFacts["host.needs_cold_reboot"].(bool)
|
||||
irqAvail, _ := p.HostFacts["host.whpx_irqchip"].(bool)
|
||||
nestedOK, _ := p.HostFacts["host.whpx_nested_virt"].(bool)
|
||||
if needsCold || !irqAvail || nestedOK {
|
||||
return plugin.StartIntent{
|
||||
PluginID: IDWHPXFallback,
|
||||
ClearKeys: []string{"kernel-irqchip"},
|
||||
}, nil
|
||||
}
|
||||
for _, c := range p.RuntimeCaps {
|
||||
if strings.EqualFold(c, "nested-virt-nonfatal") {
|
||||
return plugin.StartIntent{
|
||||
PluginID: IDWHPXFallback,
|
||||
ClearKeys: []string{"kernel-irqchip"},
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
if reims.HasKernelIrqchipArg(p.ExtraArgs) {
|
||||
return nil, nil
|
||||
}
|
||||
return plugin.StartIntent{
|
||||
PluginID: IDWHPXFallback,
|
||||
Args: []plugin.ArgFragment{{
|
||||
PluginID: IDWHPXFallback,
|
||||
Key: "kernel-irqchip",
|
||||
Tokens: []string{"-machine", "kernel-irqchip=off"},
|
||||
Builtin: true,
|
||||
Priority: 90,
|
||||
}},
|
||||
Warnings: []string{"Host rejects nested-virtualization property; enabled kernel-irqchip=off automatically"},
|
||||
}, nil
|
||||
},
|
||||
})
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func defOfflineHelper(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
|
||||
return plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: IDOfflineHelper,
|
||||
Version: ver,
|
||||
Name: plugin.LocalizedText{ZhCN: "离线安装辅助盘", EnUS: "Offline Installer Helper Disk"},
|
||||
Description: plugin.LocalizedText{
|
||||
ZhCN: "在挂载离线安装器时自动准备并注入 REIMSHELP 辅助盘,弹出安装盘后自动剥离",
|
||||
EnUS: "Automatically prepares and attaches the REIMSHELP helper disk for offline installers and strips it on eject",
|
||||
},
|
||||
Publisher: "Reims-Go",
|
||||
License: "Apache-2.0",
|
||||
Permissions: []string{"vm:intent"},
|
||||
DefaultEnabled: true,
|
||||
},
|
||||
Source: plugin.SourceBuiltin,
|
||||
Trust: plugin.TrustOfficial,
|
||||
Desired: desiredFn(IDOfflineHelper, true),
|
||||
Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
|
||||
Event: plugin.EventVMBeforeStart,
|
||||
Builtin: true,
|
||||
Handler: func(_ context.Context, raw any) (any, error) {
|
||||
p, ok := raw.(plugin.BeforeStartPayload)
|
||||
if !ok || p.DriverID != IDDriverReimsMacOS {
|
||||
return nil, nil
|
||||
}
|
||||
if p.HasInstaller && reims.IsOfflineInstallerPath(p.InstallerPath) && cb.GetConfig != nil {
|
||||
cfg := cb.GetConfig()
|
||||
helperPath, err := installer.EnsureOfflineHelperImage(cfg.XDGCacheDir(), p.InstallerPath)
|
||||
if err != nil {
|
||||
return plugin.StartIntent{
|
||||
PluginID: IDOfflineHelper,
|
||||
Warnings: []string{"offline install helper disk skipped: " + err.Error()},
|
||||
}, nil
|
||||
}
|
||||
tokens := plugin.SplitShellTokens(reims.MergeOfflineHelperArgs("", helperPath))
|
||||
return plugin.StartIntent{
|
||||
PluginID: IDOfflineHelper,
|
||||
Args: []plugin.ArgFragment{{
|
||||
PluginID: IDOfflineHelper,
|
||||
Key: "reimshelp",
|
||||
Tokens: tokens,
|
||||
Builtin: true,
|
||||
Priority: 85,
|
||||
}},
|
||||
}, nil
|
||||
}
|
||||
return plugin.StartIntent{
|
||||
PluginID: IDOfflineHelper,
|
||||
ClearKeys: []string{"reimshelp"},
|
||||
}, nil
|
||||
},
|
||||
})
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func defRecoveryBoot(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
|
||||
return plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: IDRecoveryBoot,
|
||||
Version: ver,
|
||||
Name: plugin.LocalizedText{ZhCN: "恢复模式引导切换", EnUS: "Recovery Boot Picker Sync"},
|
||||
Description: plugin.LocalizedText{
|
||||
ZhCN: "在虚拟机启动前根据标记自动更新 OpenCore 引导菜单以进入或退出恢复模式",
|
||||
EnUS: "Updates OpenCore boot picker before start when entering or exiting macOS Recovery mode",
|
||||
},
|
||||
Publisher: "Reims-Go",
|
||||
License: "Apache-2.0",
|
||||
Permissions: []string{"vm:intent"},
|
||||
DefaultEnabled: true,
|
||||
},
|
||||
Source: plugin.SourceBuiltin,
|
||||
Trust: plugin.TrustOfficial,
|
||||
Desired: desiredFn(IDRecoveryBoot, true),
|
||||
Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
|
||||
Event: plugin.EventVMBeforeStart,
|
||||
Builtin: true,
|
||||
Handler: func(ctx context.Context, raw any) (any, error) {
|
||||
p, ok := raw.(plugin.BeforeStartPayload)
|
||||
if !ok || p.VMDir == "" || p.DriverID != IDDriverReimsMacOS || cb.GetConfig == nil {
|
||||
return nil, nil
|
||||
}
|
||||
marker := vmstart.ReadRecoveryMarker(p.VMDir)
|
||||
if marker != "want" && marker != "restore" {
|
||||
return nil, nil
|
||||
}
|
||||
cfg := cb.GetConfig()
|
||||
active, err := rt.ResolveActive(&cfg)
|
||||
if err != nil || active == nil {
|
||||
return nil, nil
|
||||
}
|
||||
c := reims.NewClient(&cfg, *active)
|
||||
show := marker == "want"
|
||||
nextMarker := ""
|
||||
if show {
|
||||
nextMarker = "on"
|
||||
}
|
||||
logFn := func(line string) {
|
||||
if cb.Log != nil {
|
||||
cb.Log(p.VMName, line)
|
||||
}
|
||||
}
|
||||
w := vmstart.LineWriter(logFn)
|
||||
if err := c.UpdateOpenCore(ctx, p.VMName, show, w, w); err != nil {
|
||||
return plugin.StartIntent{
|
||||
PluginID: IDRecoveryBoot,
|
||||
Warnings: []string{"could not update OpenCore boot picker: " + err.Error()},
|
||||
}, nil
|
||||
}
|
||||
vmstart.WriteRecoveryMarker(p.VMDir, nextMarker)
|
||||
return nil, nil
|
||||
},
|
||||
})
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func defGuestLang(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
|
||||
return plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: IDGuestLang,
|
||||
Version: ver,
|
||||
Name: plugin.LocalizedText{ZhCN: "macOS 引导语言重放", EnUS: "macOS Boot Language Replay"},
|
||||
Description: plugin.LocalizedText{
|
||||
ZhCN: "在启动前与 OpenCore 重建后自动写入已保存的 prev-lang:kbd 客体语言偏好",
|
||||
EnUS: "Replays the saved prev-lang:kbd language preference into OpenCore NVRAM before start",
|
||||
},
|
||||
Publisher: "Reims-Go",
|
||||
License: "Apache-2.0",
|
||||
Permissions: []string{"vm:intent"},
|
||||
DefaultEnabled: true,
|
||||
},
|
||||
Source: plugin.SourceBuiltin,
|
||||
Trust: plugin.TrustOfficial,
|
||||
Desired: desiredFn(IDGuestLang, true),
|
||||
Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
|
||||
Event: plugin.EventVMBeforeStart,
|
||||
Builtin: true,
|
||||
// Lower priority so it replays AFTER recovery-boot rebuilds OpenCore (§11.2).
|
||||
Priority: -10,
|
||||
Handler: func(ctx context.Context, raw any) (any, error) {
|
||||
p, ok := raw.(plugin.BeforeStartPayload)
|
||||
if !ok || p.VMDir == "" || p.DriverID != IDDriverReimsMacOS || cb.GetConfig == nil {
|
||||
return nil, nil
|
||||
}
|
||||
saved := opencore.ReadSavedGuestLang(p.VMDir)
|
||||
if saved == "" {
|
||||
return nil, nil
|
||||
}
|
||||
ocPath := opencore.ResolveOpenCorePath(p.VMDir)
|
||||
if ocPath == "" {
|
||||
return nil, nil
|
||||
}
|
||||
cfg := cb.GetConfig()
|
||||
active, err := rt.ResolveActive(&cfg)
|
||||
if err != nil || active == nil {
|
||||
return nil, nil
|
||||
}
|
||||
env := rt.BuildChildEnv(&cfg, *active)
|
||||
if _, err := opencore.PatchImagePrevLang(ctx, ocPath, saved, active.QemuImgPath(), env); err != nil {
|
||||
return plugin.StartIntent{
|
||||
PluginID: IDGuestLang,
|
||||
Warnings: []string{"could not apply macOS language to OpenCore: " + err.Error()},
|
||||
}, nil
|
||||
}
|
||||
return nil, nil
|
||||
},
|
||||
})
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -79,30 +79,6 @@ func TestBuiltinClipboardAndInputLifecycleZeroResidue(t *testing.T) {
|
||||
if _, ok := reg.LookupService(ServiceHostInput); ok {
|
||||
t.Fatal("expected host.input service removed after disable")
|
||||
}
|
||||
|
||||
// WHPX fallback hook uses runtime capability rather than patch name substring.
|
||||
intents, err := reg.Hooks().DispatchBeforeStart(context.Background(), plugin.BeforeStartPayload{
|
||||
VMName: "mac1",
|
||||
DriverID: IDDriverReimsMacOS,
|
||||
RuntimeCaps: []string{},
|
||||
HostFacts: map[string]any{
|
||||
"host.needs_cold_reboot": false,
|
||||
"host.whpx_irqchip": true,
|
||||
"host.whpx_nested_virt": false,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
foundIrq := false
|
||||
for _, in := range intents {
|
||||
if in.PluginID == IDWHPXFallback && len(in.Args) == 1 {
|
||||
foundIrq = true
|
||||
}
|
||||
}
|
||||
if !foundIrq {
|
||||
t.Fatalf("expected WHPX fallback intent, got %+v", intents)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInputServiceTypeCheck(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,391 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/opencore"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
// IDCore is the always-on builtin that holds everything Reims-Go needs to run
|
||||
// macOS VMs: the reims driver, the default theme, start preparation and the
|
||||
// host workarounds. Users can't switch it off; the two workarounds have their
|
||||
// own settings for troubleshooting.
|
||||
const IDCore = "builtin.core"
|
||||
|
||||
// Core app settings (x-scope "app").
|
||||
const (
|
||||
SettingWHPXFallback = "whpx_fallback"
|
||||
SettingWin10ColdReboot = "win10_cold_reboot"
|
||||
)
|
||||
|
||||
// RetiredIDs are the plugin IDs that were merged into IDCore. Their
|
||||
// state.json records and arg-ledger owners are migrated on startup.
|
||||
var RetiredIDs = []string{
|
||||
IDThemeDefault,
|
||||
driver.BuiltinReimsMacOSDriverID,
|
||||
"builtin.compat.win10-cold-reboot",
|
||||
"builtin.compat.whpx-fallback",
|
||||
"builtin.prep.offline-helper",
|
||||
"builtin.prep.recovery-boot",
|
||||
"builtin.prep.guest-lang",
|
||||
}
|
||||
|
||||
// retiredSettings maps a retired plugin that used to have its own switch to
|
||||
// the core setting that replaced it.
|
||||
var retiredSettings = map[string]string{
|
||||
"builtin.compat.whpx-fallback": SettingWHPXFallback,
|
||||
"builtin.compat.win10-cold-reboot": SettingWin10ColdReboot,
|
||||
}
|
||||
|
||||
// MigrateRetired drops state.json records of plugins merged into the core and
|
||||
// carries a switched-off workaround over to its core setting. Safe to call on
|
||||
// every start; it only writes when an old record is still there.
|
||||
func MigrateRetired(mgr *plugin.Manager) error {
|
||||
removed, err := mgr.RetireRecords(RetiredIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
off := map[string]any{}
|
||||
for id, rec := range removed {
|
||||
if key, ok := retiredSettings[id]; ok && rec != nil && !rec.Enabled {
|
||||
off[key] = false
|
||||
}
|
||||
}
|
||||
if len(off) == 0 {
|
||||
return nil
|
||||
}
|
||||
return mgr.SetSettings(IDCore, "", off)
|
||||
}
|
||||
|
||||
// MigrateLedger hands arg fragments owned by retired plugin IDs to the core,
|
||||
// so the next start carries them forward instead of stripping and re-adding
|
||||
// them. It reports whether the ledger changed.
|
||||
func MigrateLedger(l *plugin.ArgLedger) bool {
|
||||
return l.MergeOwners(RetiredIDs, IDCore)
|
||||
}
|
||||
|
||||
// CoreSettingOn reads a boolean core setting from vals. A missing or
|
||||
// non-boolean value counts as on, which is the default for both settings.
|
||||
func CoreSettingOn(vals map[string]any, key string) bool {
|
||||
if v, ok := vals[key].(bool); ok {
|
||||
return v
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// CoreSettingOnInState reads a core setting from a state.json snapshot, for
|
||||
// processes without a Manager. A workaround switched off under its retired
|
||||
// plugin ID still counts as off until MigrateRetired has run.
|
||||
func CoreSettingOnInState(st *plugin.StateFile, key string) bool {
|
||||
if st == nil {
|
||||
return true
|
||||
}
|
||||
for id, k := range retiredSettings {
|
||||
if rec := st.Plugins[id]; k == key && rec != nil && !rec.Enabled {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if rec := st.Plugins[IDCore]; rec != nil {
|
||||
return CoreSettingOn(rec.AppSettings, key)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func coreSettingOn(cb HostCallbacks, key string) bool {
|
||||
if cb.GetSetting == nil {
|
||||
return true
|
||||
}
|
||||
v, ok := cb.GetSetting(IDCore, "", key)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
return CoreSettingOn(map[string]any{key: v}, key)
|
||||
}
|
||||
|
||||
func defCore(ver string, cb HostCallbacks) plugin.PluginDef {
|
||||
return plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: IDCore,
|
||||
Version: ver,
|
||||
Name: plugin.LocalizedText{ZhCN: "Reims-Go 核心", EnUS: "Reims-Go Core"},
|
||||
Description: plugin.LocalizedText{
|
||||
ZhCN: "虚拟机驱动、默认外观、启动准备与宿主兼容补偿,始终启用",
|
||||
EnUS: "VM driver, default look, start preparation and host workarounds; always on",
|
||||
},
|
||||
Publisher: "Reims-Go",
|
||||
License: "Apache-2.0",
|
||||
Permissions: []string{"driver:vm", "vm:control", "vm:intent", "qmp:write"},
|
||||
DefaultEnabled: true,
|
||||
Contributes: plugin.Contributes{
|
||||
Themes: []plugin.ThemeContribution{{
|
||||
ID: IDThemeDefault,
|
||||
Name: plugin.LocalizedText{ZhCN: "默认主题", EnUS: "Default"},
|
||||
Appearance: "both",
|
||||
}},
|
||||
},
|
||||
Settings: &plugin.SettingsSchema{
|
||||
Title: plugin.LocalizedText{ZhCN: "宿主兼容补偿", EnUS: "Host workarounds"},
|
||||
Scope: "app",
|
||||
Order: []string{SettingWHPXFallback, SettingWin10ColdReboot},
|
||||
Properties: map[string]plugin.SettingProperty{
|
||||
SettingWHPXFallback: {
|
||||
Type: "boolean",
|
||||
Title: plugin.LocalizedText{ZhCN: "WHPX 兼容降级", EnUS: "WHPX compatibility fallback"},
|
||||
Description: plugin.LocalizedText{
|
||||
ZhCN: "宿主不支持嵌套虚拟化属性时自动加 kernel-irqchip=off,避免首次启动崩溃。只在排查问题时关闭",
|
||||
EnUS: "Adds kernel-irqchip=off when the host rejects the nested-virtualization property, avoiding a first-boot crash. Turn off only to troubleshoot",
|
||||
},
|
||||
Default: true,
|
||||
Effect: "next_start",
|
||||
Scope: "app",
|
||||
},
|
||||
SettingWin10ColdReboot: {
|
||||
Type: "boolean",
|
||||
Title: plugin.LocalizedText{ZhCN: "Windows 10 冷重启补偿", EnUS: "Windows 10 cold-reboot workaround"},
|
||||
Description: plugin.LocalizedText{
|
||||
ZhCN: "Windows 10 上 macOS 重启后自动重新启动虚拟机。只在排查问题时关闭",
|
||||
EnUS: "On Windows 10, starts the VM again after macOS reboots. Turn off only to troubleshoot",
|
||||
},
|
||||
Default: true,
|
||||
Effect: "next_start",
|
||||
Scope: "app",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
Source: plugin.SourceBuiltin,
|
||||
Trust: plugin.TrustOfficial,
|
||||
System: true,
|
||||
Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
drv := driver.NewReimsMacOSDriver(cb.GetConfig)
|
||||
sc.Registry().RegisterGuestDriver(sc, IDDriverReimsMacOS, drv)
|
||||
|
||||
hooks := sc.Registry().Hooks()
|
||||
hooks.Subscribe(sc, plugin.HookRegistration{
|
||||
Event: plugin.EventHostPreflight,
|
||||
Builtin: true,
|
||||
Handler: func(_ context.Context, raw any) (any, error) {
|
||||
p, ok := raw.(plugin.PreflightPayload)
|
||||
if !ok || !coreSettingOn(cb, SettingWHPXFallback) {
|
||||
return nil, nil
|
||||
}
|
||||
caps, _ := p.HostFacts["runtime.capabilities"].([]string)
|
||||
if whpxFallbackNeeded(p.HostFacts) && !hasCap(caps, "nested-virt-nonfatal") {
|
||||
return plugin.PreflightResult{
|
||||
Advices: []string{"Host lacks nested-virt property and runtime lacks nested-virt-nonfatal capability; kernel-irqchip=off will be auto-applied"},
|
||||
}, nil
|
||||
}
|
||||
return nil, nil
|
||||
},
|
||||
})
|
||||
// One handler runs every start step in a fixed order. Guest language
|
||||
// must follow the recovery step, which may rebuild OpenCore.
|
||||
hooks.Subscribe(sc, plugin.HookRegistration{
|
||||
Event: plugin.EventVMBeforeStart,
|
||||
Builtin: true,
|
||||
Handler: func(ctx context.Context, raw any) (any, error) {
|
||||
p, ok := raw.(plugin.BeforeStartPayload)
|
||||
if !ok || p.DriverID != IDDriverReimsMacOS {
|
||||
return nil, nil
|
||||
}
|
||||
in := plugin.StartIntent{PluginID: IDCore}
|
||||
stepOfflineHelper(cb, p, &in)
|
||||
stepRecoveryBoot(ctx, cb, p, &in)
|
||||
stepGuestLang(ctx, cb, p, &in)
|
||||
stepWHPXFallback(cb, p, &in)
|
||||
stepWin10ColdReboot(cb, p, &in)
|
||||
return in, nil
|
||||
},
|
||||
})
|
||||
hooks.Subscribe(sc, plugin.HookRegistration{
|
||||
Event: plugin.EventVMAfterStart,
|
||||
Builtin: true,
|
||||
Handler: func(_ context.Context, raw any) (any, error) {
|
||||
// QMPAddr is only set when stepWin10ColdReboot asked for the watcher.
|
||||
ev, ok := raw.(plugin.VMEventPayload)
|
||||
if ok && ev.QMPAddr != "" && cb.StartColdReboot != nil {
|
||||
cb.StartColdReboot(ev.VMName, ev.QMPAddr)
|
||||
}
|
||||
return nil, nil
|
||||
},
|
||||
})
|
||||
hooks.Subscribe(sc, plugin.HookRegistration{
|
||||
Event: plugin.EventVMAfterStop,
|
||||
Builtin: true,
|
||||
Handler: func(_ context.Context, raw any) (any, error) {
|
||||
ev, ok := raw.(plugin.VMEventPayload)
|
||||
if ok && cb.CancelColdReboot != nil {
|
||||
cb.CancelColdReboot(ev.VMName)
|
||||
}
|
||||
return nil, nil
|
||||
},
|
||||
})
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Arg-ledger keys owned by the core.
|
||||
const (
|
||||
keyOfflineHelper = "reimshelp"
|
||||
keyKernelIrqchip = "kernel-irqchip"
|
||||
keyWin10ColdReboot = "win10-cold-reboot"
|
||||
)
|
||||
|
||||
// stepOfflineHelper attaches the REIMSHELP helper disk while an offline
|
||||
// installer is attached and clears it otherwise.
|
||||
func stepOfflineHelper(cb HostCallbacks, p plugin.BeforeStartPayload, in *plugin.StartIntent) {
|
||||
if !p.HasInstaller || !reims.IsOfflineInstallerPath(p.InstallerPath) || cb.GetConfig == nil {
|
||||
in.ClearKeys = append(in.ClearKeys, keyOfflineHelper)
|
||||
return
|
||||
}
|
||||
cfg := cb.GetConfig()
|
||||
helperPath, err := installer.EnsureOfflineHelperImage(cfg.XDGCacheDir(), p.InstallerPath)
|
||||
if err != nil {
|
||||
in.Warnings = append(in.Warnings, "offline install helper disk skipped: "+err.Error())
|
||||
return
|
||||
}
|
||||
in.Args = append(in.Args, plugin.ArgFragment{
|
||||
PluginID: IDCore,
|
||||
Key: keyOfflineHelper,
|
||||
Tokens: plugin.SplitShellTokens(reims.MergeOfflineHelperArgs("", helperPath)),
|
||||
Builtin: true,
|
||||
Priority: 85,
|
||||
})
|
||||
}
|
||||
|
||||
// stepRecoveryBoot applies a recovery-mode switch recorded while the VM was
|
||||
// running; updating OpenCore needs a stopped VM.
|
||||
func stepRecoveryBoot(ctx context.Context, cb HostCallbacks, p plugin.BeforeStartPayload, in *plugin.StartIntent) {
|
||||
if p.VMDir == "" || cb.GetConfig == nil {
|
||||
return
|
||||
}
|
||||
marker := vmstart.ReadRecoveryMarker(p.VMDir)
|
||||
if marker != "want" && marker != "restore" {
|
||||
return
|
||||
}
|
||||
cfg := cb.GetConfig()
|
||||
active, err := rt.ResolveActive(&cfg)
|
||||
if err != nil || active == nil {
|
||||
return
|
||||
}
|
||||
show := marker == "want"
|
||||
next := ""
|
||||
if show {
|
||||
next = "on"
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) {
|
||||
if cb.Log != nil {
|
||||
cb.Log(p.VMName, line)
|
||||
}
|
||||
})
|
||||
if err := reims.NewClient(&cfg, *active).UpdateOpenCore(ctx, p.VMName, show, w, w); err != nil {
|
||||
in.Warnings = append(in.Warnings, "could not update OpenCore boot picker: "+err.Error())
|
||||
return
|
||||
}
|
||||
vmstart.WriteRecoveryMarker(p.VMDir, next)
|
||||
}
|
||||
|
||||
// stepGuestLang writes the saved macOS language into OpenCore NVRAM. It runs
|
||||
// after stepRecoveryBoot because rebuilding OpenCore drops it.
|
||||
func stepGuestLang(ctx context.Context, cb HostCallbacks, p plugin.BeforeStartPayload, in *plugin.StartIntent) {
|
||||
if p.VMDir == "" || cb.GetConfig == nil {
|
||||
return
|
||||
}
|
||||
saved := opencore.ReadSavedGuestLang(p.VMDir)
|
||||
if saved == "" {
|
||||
return
|
||||
}
|
||||
ocPath := opencore.ResolveOpenCorePath(p.VMDir)
|
||||
if ocPath == "" {
|
||||
return
|
||||
}
|
||||
cfg := cb.GetConfig()
|
||||
active, err := rt.ResolveActive(&cfg)
|
||||
if err != nil || active == nil {
|
||||
return
|
||||
}
|
||||
env := rt.BuildChildEnv(&cfg, *active)
|
||||
if _, err := opencore.PatchImagePrevLang(ctx, ocPath, saved, active.QemuImgPath(), env); err != nil {
|
||||
in.Warnings = append(in.Warnings, "could not apply macOS language to OpenCore: "+err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// whpxFallbackNeeded reports whether the host rejects the nested-virt property
|
||||
// while kernel-irqchip=off is available and the cold-reboot path isn't used.
|
||||
func whpxFallbackNeeded(facts map[string]any) bool {
|
||||
needsCold, _ := facts["host.needs_cold_reboot"].(bool)
|
||||
irqAvail, _ := facts["host.whpx_irqchip"].(bool)
|
||||
nestedOK, _ := facts["host.whpx_nested_virt"].(bool)
|
||||
return !needsCold && irqAvail && !nestedOK
|
||||
}
|
||||
|
||||
func hasCap(caps []string, want string) bool {
|
||||
for _, c := range caps {
|
||||
if strings.EqualFold(c, want) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// stepWHPXFallback adds kernel-irqchip=off on hosts that reject the
|
||||
// nested-virtualization property when the runtime can't tolerate that.
|
||||
func stepWHPXFallback(cb HostCallbacks, p plugin.BeforeStartPayload, in *plugin.StartIntent) {
|
||||
if !coreSettingOn(cb, SettingWHPXFallback) || !whpxFallbackNeeded(p.HostFacts) || hasCap(p.RuntimeCaps, "nested-virt-nonfatal") {
|
||||
in.ClearKeys = append(in.ClearKeys, keyKernelIrqchip)
|
||||
return
|
||||
}
|
||||
if reims.HasKernelIrqchipArg(p.ExtraArgs) {
|
||||
return // already there: ours from an earlier start, or written by the user
|
||||
}
|
||||
in.Args = append(in.Args, plugin.ArgFragment{
|
||||
PluginID: IDCore,
|
||||
Key: keyKernelIrqchip,
|
||||
Tokens: []string{"-machine", "kernel-irqchip=off"},
|
||||
Builtin: true,
|
||||
Priority: 90,
|
||||
})
|
||||
in.Warnings = append(in.Warnings, "Host rejects nested-virtualization property; enabled kernel-irqchip=off automatically")
|
||||
}
|
||||
|
||||
// stepWin10ColdReboot adds -no-reboot with a private QMP socket on Windows 10
|
||||
// hosts without WHvResetPartition and asks for the reboot watcher.
|
||||
func stepWin10ColdReboot(cb HostCallbacks, p plugin.BeforeStartPayload, in *plugin.StartIntent) {
|
||||
needs, _ := p.HostFacts["host.needs_cold_reboot"].(bool)
|
||||
if !needs || !coreSettingOn(cb, SettingWin10ColdReboot) {
|
||||
in.ClearKeys = append(in.ClearKeys, keyWin10ColdReboot)
|
||||
return
|
||||
}
|
||||
tmpDir := ""
|
||||
if cb.GetConfig != nil {
|
||||
cfg := cb.GetConfig()
|
||||
tmpDir = cfg.TempDir()
|
||||
}
|
||||
sockPath := qmp.RebootSocketPath(p.VMDir, tmpDir, p.VMName)
|
||||
_ = os.MkdirAll(filepath.Dir(sockPath), 0o755)
|
||||
_ = os.Remove(sockPath)
|
||||
in.Args = append(in.Args, plugin.ArgFragment{
|
||||
PluginID: IDCore,
|
||||
Key: keyWin10ColdReboot,
|
||||
Tokens: plugin.SplitShellTokens(qmp.MergeWin10RebootUnixArgs("", sockPath)),
|
||||
Builtin: true,
|
||||
Priority: 95,
|
||||
})
|
||||
in.PostStart = append(in.PostStart, plugin.PostStartAction{
|
||||
PluginID: IDCore,
|
||||
Kind: "qmp.watch_cold_reboot",
|
||||
Params: map[string]any{"qmp_addr": "unix:" + sockPath},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
func coreTestCallbacks(t *testing.T, settings map[string]any) HostCallbacks {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
return HostCallbacks{
|
||||
GetConfig: func() config.Config { return config.Config{DataRoot: root} },
|
||||
GetSetting: func(pluginID, _ string, key string) (any, bool) {
|
||||
if pluginID != IDCore {
|
||||
return nil, false
|
||||
}
|
||||
v, ok := settings[key]
|
||||
return v, ok
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoreIsSystemAndHoldsDriverAndTheme(t *testing.T) {
|
||||
reg := plugin.NewRegistry(nil)
|
||||
// desiredFn says "off" for everything: the core must ignore it.
|
||||
if err := RegisterAll(reg, coreTestCallbacks(t, nil), func(string, bool) bool { return false }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.Reconcile(context.Background())
|
||||
|
||||
if !reg.IsActive(IDCore) {
|
||||
t.Fatal("core must be active even when state says off")
|
||||
}
|
||||
info, ok := reg.Info(IDCore)
|
||||
if !ok || !info.System || info.Removable {
|
||||
t.Fatalf("core must be a non-removable system plugin, got %+v", info)
|
||||
}
|
||||
if err := reg.SetDesired(context.Background(), IDCore, false); err == nil {
|
||||
t.Fatal("disabling the core must fail")
|
||||
}
|
||||
if !reg.IsActive(IDCore) {
|
||||
t.Fatal("core went inactive after a refused disable")
|
||||
}
|
||||
if _, ok := reg.GuestDriver(IDDriverReimsMacOS); !ok {
|
||||
t.Fatal("core must register the reims macOS driver under its existing driver ID")
|
||||
}
|
||||
if !slices.ContainsFunc(reg.Themes(), func(th plugin.ThemeContribution) bool { return th.ID == IDThemeDefault }) {
|
||||
t.Fatal("core must contribute the default theme under its existing theme ID")
|
||||
}
|
||||
for _, id := range RetiredIDs {
|
||||
if _, ok := reg.Info(id); ok {
|
||||
t.Errorf("retired plugin %s is still registered", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func dispatchCoreStart(t *testing.T, settings map[string]any, facts map[string]any, caps []string) plugin.StartIntent {
|
||||
t.Helper()
|
||||
reg := plugin.NewRegistry(nil)
|
||||
if err := RegisterAll(reg, coreTestCallbacks(t, settings), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.Reconcile(context.Background())
|
||||
intents, err := reg.Hooks().DispatchBeforeStart(context.Background(), plugin.BeforeStartPayload{
|
||||
VMName: "mac1",
|
||||
VMDir: t.TempDir(),
|
||||
DriverID: IDDriverReimsMacOS,
|
||||
RuntimeCaps: caps,
|
||||
HostFacts: facts,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var core *plugin.StartIntent
|
||||
for i := range intents {
|
||||
if intents[i].PluginID == IDCore {
|
||||
if core != nil {
|
||||
t.Fatal("core returned more than one start intent")
|
||||
}
|
||||
core = &intents[i]
|
||||
}
|
||||
}
|
||||
if core == nil {
|
||||
t.Fatalf("no core start intent in %+v", intents)
|
||||
}
|
||||
return *core
|
||||
}
|
||||
|
||||
func argKeys(in plugin.StartIntent) []string {
|
||||
var keys []string
|
||||
for _, a := range in.Args {
|
||||
keys = append(keys, a.Key)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
var whpxHostFacts = map[string]any{
|
||||
"host.needs_cold_reboot": false,
|
||||
"host.whpx_irqchip": true,
|
||||
"host.whpx_nested_virt": false,
|
||||
}
|
||||
|
||||
func TestCoreStartStepsInOneIntent(t *testing.T) {
|
||||
in := dispatchCoreStart(t, nil, whpxHostFacts, nil)
|
||||
if !slices.Equal(argKeys(in), []string{keyKernelIrqchip}) {
|
||||
t.Fatalf("want only the kernel-irqchip arg, got %v", argKeys(in))
|
||||
}
|
||||
for _, k := range []string{keyOfflineHelper, keyWin10ColdReboot} {
|
||||
if !slices.Contains(in.ClearKeys, k) {
|
||||
t.Errorf("unneeded step %s should clear its key, got ClearKeys %v", k, in.ClearKeys)
|
||||
}
|
||||
}
|
||||
|
||||
// A runtime that tolerates the missing property needs no fallback.
|
||||
in = dispatchCoreStart(t, nil, whpxHostFacts, []string{"nested-virt-nonfatal"})
|
||||
if len(in.Args) != 0 || !slices.Contains(in.ClearKeys, keyKernelIrqchip) {
|
||||
t.Fatalf("nested-virt-nonfatal runtime: want kernel-irqchip cleared, got args %v clear %v", argKeys(in), in.ClearKeys)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoreWorkaroundSettings(t *testing.T) {
|
||||
off := map[string]any{SettingWHPXFallback: false, SettingWin10ColdReboot: false}
|
||||
|
||||
in := dispatchCoreStart(t, off, whpxHostFacts, nil)
|
||||
if len(in.Args) != 0 || !slices.Contains(in.ClearKeys, keyKernelIrqchip) {
|
||||
t.Fatalf("WHPX setting off: want kernel-irqchip cleared, got args %v clear %v", argKeys(in), in.ClearKeys)
|
||||
}
|
||||
|
||||
win10 := map[string]any{"host.needs_cold_reboot": true}
|
||||
in = dispatchCoreStart(t, nil, win10, nil)
|
||||
if !slices.Contains(argKeys(in), keyWin10ColdReboot) || len(in.PostStart) != 1 || in.PostStart[0].Kind != "qmp.watch_cold_reboot" {
|
||||
t.Fatalf("Win10 host: want cold-reboot args and watcher, got args %v post %+v", argKeys(in), in.PostStart)
|
||||
}
|
||||
in = dispatchCoreStart(t, off, win10, nil)
|
||||
if slices.Contains(argKeys(in), keyWin10ColdReboot) || len(in.PostStart) != 0 || !slices.Contains(in.ClearKeys, keyWin10ColdReboot) {
|
||||
t.Fatalf("cold-reboot setting off: want no args or watcher, got args %v post %+v clear %v", argKeys(in), in.PostStart, in.ClearKeys)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrateRetiredCarriesWorkaroundChoices(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
store := plugin.NewStateStore(plugin.NewPluginsLayout(root).Root)
|
||||
if err := store.Save(&plugin.StateFile{Plugins: map[string]*plugin.PluginRecord{
|
||||
"builtin.compat.whpx-fallback": {ID: "builtin.compat.whpx-fallback", Enabled: false},
|
||||
"builtin.prep.guest-lang": {ID: "builtin.prep.guest-lang", Enabled: false},
|
||||
IDThemeDefault: {ID: IDThemeDefault, Enabled: true},
|
||||
IDClipboard: {ID: IDClipboard, Enabled: false},
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr, err := plugin.NewManager(plugin.ManagerOptions{DataRoot: root, HostVersion: "0.0.0"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer mgr.Close()
|
||||
if err := RegisterAll(mgr.Registry(), coreTestCallbacks(t, nil), mgr.DesiredFor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Before migration the CLI still honours the old switch.
|
||||
if CoreSettingOnInState(plugin.ReadState(root), SettingWHPXFallback) {
|
||||
t.Fatal("unmigrated whpx-fallback=off must read as off")
|
||||
}
|
||||
|
||||
if err := MigrateRetired(mgr); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := plugin.ReadState(root)
|
||||
for _, id := range RetiredIDs {
|
||||
if _, ok := st.Plugins[id]; ok {
|
||||
t.Errorf("retired record %s left in state.json", id)
|
||||
}
|
||||
}
|
||||
if rec := st.Plugins[IDClipboard]; rec == nil || rec.Enabled {
|
||||
t.Error("migration must not touch records of plugins that still exist")
|
||||
}
|
||||
vals := mgr.GetSettings(IDCore, "", false)
|
||||
if CoreSettingOn(vals, SettingWHPXFallback) {
|
||||
t.Error("a switched-off whpx-fallback plugin must become whpx_fallback=false")
|
||||
}
|
||||
if !CoreSettingOn(vals, SettingWin10ColdReboot) {
|
||||
t.Error("cold reboot had no record and must stay on")
|
||||
}
|
||||
if CoreSettingOnInState(st, SettingWHPXFallback) || !CoreSettingOnInState(st, SettingWin10ColdReboot) {
|
||||
t.Error("state snapshot must read the migrated core settings")
|
||||
}
|
||||
if err := MigrateRetired(mgr); err != nil {
|
||||
t.Fatalf("second migration: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -77,6 +77,37 @@ type StartIntent struct {
|
||||
PostStart []PostStartAction `json:"post_start,omitempty"`
|
||||
}
|
||||
|
||||
// MergeOwners moves the fragments recorded for each ID in from over to owner
|
||||
// to, so fragments written by plugins that were merged into another one are
|
||||
// carried forward instead of being stripped as belonging to a gone plugin.
|
||||
// It reports whether anything moved.
|
||||
func (l *ArgLedger) MergeOwners(from []string, to string) bool {
|
||||
if l == nil || l.Owners == nil {
|
||||
return false
|
||||
}
|
||||
moved := false
|
||||
for _, id := range from {
|
||||
frags, ok := l.Owners[id]
|
||||
if !ok || id == to {
|
||||
continue
|
||||
}
|
||||
have := map[string]bool{}
|
||||
for _, f := range l.Owners[to] {
|
||||
have[f.Key] = true
|
||||
}
|
||||
for _, f := range frags {
|
||||
if have[f.Key] {
|
||||
continue
|
||||
}
|
||||
f.PluginID = to
|
||||
l.Owners[to] = append(l.Owners[to], f)
|
||||
}
|
||||
delete(l.Owners, id)
|
||||
moved = true
|
||||
}
|
||||
return moved
|
||||
}
|
||||
|
||||
// ArgLedger persists plugin-owned QEMU arg fragments in a VM directory so that
|
||||
// disabling/uninstalling a plugin strips its exact fragments while NEVER
|
||||
// touching unowned user `--extra-args` (§4.4).
|
||||
|
||||
@@ -671,6 +671,29 @@ func (m *Manager) Remove(ctx context.Context, id string, purgeData bool) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// RetireRecords drops state.json records for plugin IDs that no longer exist,
|
||||
// for example builtins merged into another plugin, and returns the removed
|
||||
// records so the caller can carry their choices over. Nothing is saved when
|
||||
// none of the IDs has a record.
|
||||
func (m *Manager) RetireRecords(ids []string) (map[string]*PluginRecord, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.state == nil {
|
||||
return nil, m.stateNotLoadedErr()
|
||||
}
|
||||
removed := map[string]*PluginRecord{}
|
||||
for _, id := range ids {
|
||||
if rec, ok := m.state.Plugins[id]; ok {
|
||||
removed[id] = rec
|
||||
delete(m.state.Plugins, id)
|
||||
}
|
||||
}
|
||||
if len(removed) == 0 {
|
||||
return removed, nil
|
||||
}
|
||||
return removed, m.store.Save(m.state)
|
||||
}
|
||||
|
||||
func (m *Manager) stateNotLoadedErr() error {
|
||||
if m.stateLoadErr != nil {
|
||||
return m.stateLoadErr
|
||||
|
||||
@@ -37,6 +37,9 @@ type PluginDef struct {
|
||||
ApprovedPermissions []string
|
||||
// NeedsApproval indicates high-risk permissions or community L3 awaiting approval.
|
||||
NeedsApproval bool
|
||||
// System marks a builtin that Reims-Go cannot work without: it is always
|
||||
// desired and cannot be disabled or removed.
|
||||
System bool
|
||||
}
|
||||
|
||||
type serviceRecord struct {
|
||||
@@ -177,6 +180,9 @@ func (r *Registry) Register(def PluginDef) error {
|
||||
if def.Manifest.Version == "" {
|
||||
def.Manifest.Version = "0.0.0"
|
||||
}
|
||||
if def.System {
|
||||
def.Desired = true
|
||||
}
|
||||
var oldScope *Scope
|
||||
r.mu.Lock()
|
||||
if existing, ok := r.entries[def.Manifest.ID]; ok {
|
||||
@@ -229,6 +235,13 @@ func (r *Registry) Unregister(ctx context.Context, id string) error {
|
||||
// SetDesired enables or disables a plugin and reconciles dependencies.
|
||||
func (r *Registry) SetDesired(ctx context.Context, id string, enabled bool) error {
|
||||
if !enabled {
|
||||
r.mu.RLock()
|
||||
e, ok := r.entries[id]
|
||||
system := ok && e.def.System
|
||||
r.mu.RUnlock()
|
||||
if system {
|
||||
return fmt.Errorf("plugin %q is part of Reims-Go core and cannot be disabled", id)
|
||||
}
|
||||
if err := r.checkNotInUse(id); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1288,7 +1301,9 @@ func (r *Registry) Info(pluginID string) (PluginInfo, bool) {
|
||||
}
|
||||
info := r.entryToInfoLocked(e)
|
||||
r.mu.RUnlock()
|
||||
if checker != nil {
|
||||
// System plugins can't be disabled or removed, so "in use" means nothing
|
||||
// for them, and the check can be costly (driver VM listing).
|
||||
if checker != nil && !info.System {
|
||||
if inUse, _, err := checker(pluginID); err != nil || inUse {
|
||||
info.InUse = true
|
||||
}
|
||||
@@ -1308,6 +1323,9 @@ func (r *Registry) List() []PluginInfo {
|
||||
|
||||
if checker != nil {
|
||||
for i := range out {
|
||||
if out[i].System {
|
||||
continue
|
||||
}
|
||||
if inUse, _, err := checker(out[i].ID); err != nil || inUse {
|
||||
out[i].InUse = true
|
||||
}
|
||||
@@ -1352,6 +1370,7 @@ func (r *Registry) entryToInfoLocked(e *pluginEntry) PluginInfo {
|
||||
State: e.state,
|
||||
Enabled: e.def.Desired,
|
||||
Removable: e.def.Removable,
|
||||
System: e.def.System,
|
||||
Error: e.errMsg,
|
||||
DegradedReason: e.degradedReason,
|
||||
Permissions: perms,
|
||||
|
||||
@@ -137,6 +137,18 @@ func (s *StateStore) Save(st *StateFile) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReadState reads `<dataRoot>/plugins/state.json` without starting a Manager,
|
||||
// for processes such as `vm start` that only need a setting or two. It returns
|
||||
// nil when the file is unreadable; callers then use their defaults, as the
|
||||
// GUI's Manager does.
|
||||
func ReadState(dataRoot string) *StateFile {
|
||||
st, err := NewStateStore(NewPluginsLayout(dataRoot).Root).Load()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// --- Safe-mode startup sentinel (§9) ---
|
||||
|
||||
// SentinelPath returns `<DataRoot>/plugins/.startup-sentinel`.
|
||||
|
||||
@@ -545,6 +545,7 @@ type PluginInfo struct {
|
||||
State State `json:"state"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Removable bool `json:"removable"`
|
||||
System bool `json:"system,omitempty"`
|
||||
InUse bool `json:"in_use"`
|
||||
Error string `json:"error,omitempty"`
|
||||
DegradedReason string `json:"degraded_reason,omitempty"`
|
||||
|
||||
@@ -32,8 +32,10 @@ import (
|
||||
type Prep struct {
|
||||
Client *reims.Client
|
||||
Runtime rt.Installed
|
||||
cfg config.Config
|
||||
log func(string)
|
||||
// SkipWHPXFallback mirrors the core plugin's WHPX setting being off.
|
||||
SkipWHPXFallback bool
|
||||
cfg config.Config
|
||||
log func(string)
|
||||
}
|
||||
|
||||
// New resolves the active runtime for cfg. It fails when none is installed.
|
||||
@@ -71,7 +73,9 @@ func (p *Prep) Prepare(ctx context.Context, name string, rep host.Report, cur *r
|
||||
p.syncOfflineHelper(ctx, name, cur)
|
||||
p.syncRecoveryBootPicker(ctx, name, cur)
|
||||
p.ReplayGuestLang(ctx, cur.Directory)
|
||||
p.applyProbedWHPXCompat(ctx, name, rep, cur)
|
||||
if !p.SkipWHPXFallback {
|
||||
p.applyProbedWHPXCompat(ctx, name, rep, cur)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Prep) setExtraArgs(ctx context.Context, name, args string) error {
|
||||
|
||||
Reference in new issue
Block a user