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:
Nwflower committed 2026-11-29 09:54:51 -07:00
1 parent 007f2ac93c
commit 181c616909
35 files changed
+1432 -578

No files matched your search

+17 -449
View File
@@ -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
},
}
}
-24
View File
@@ -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) {
+391
View File
@@ -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},
})
}
+194
View File
@@ -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)
}
}
+31
View File
@@ -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).
+23
View File
@@ -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
+20 -1
View File
@@ -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,
+12
View File
@@ -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`.
+1
View File
@@ -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"`