Files
Reims-Go/internal/plugin/manager.go
T
Nwflower 181c616909 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.
2026-11-29 09:54:51 -07:00

1034 lines
28 KiB
Go

package plugin
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
)
// SidecarDriverFactory builds a guest driver proxy from a Sidecar contribution
// and supervisor without importing internal/driver into internal/plugin.
type SidecarDriverFactory func(contrib GuestDriverContribution, sup *SidecarSupervisor) any
// ManagerOptions configures the high-level Plugin Manager.
type ManagerOptions struct {
DataRoot string
HostVersion string
SafeMode bool
Keyring []SigningKey
RedactFn func(string) string
Logger func(source, line string)
SidecarDriverFactory SidecarDriverFactory
OnSettingsChanged func(pluginID, vmName string)
}
// ActiveThemePayload is sent to the frontend to apply L1/L2/Tier-3 themes (§5.1).
type ActiveThemePayload struct {
ThemeID string `json:"theme_id"`
PluginID string `json:"plugin_id,omitempty"`
ActiveScheme string `json:"active_scheme,omitempty"`
Theme *ThemeContribution `json:"theme,omitempty"`
CustomSchemes []CustomThemeScheme `json:"custom_schemes,omitempty"`
CSS string `json:"css,omitempty"`
AssetBaseURL string `json:"asset_base_url,omitempty"`
UIScriptURL string `json:"ui_script_url,omitempty"`
UIScriptTrust TrustLevel `json:"ui_script_trust,omitempty"`
}
// Manager coordinates Registry, StateStore, package installation, safe mode,
// settings, themes, AssetServer, Broker, and L3 Sidecar supervisors.
type Manager struct {
opts ManagerOptions
layout PluginsLayout
store *StateStore
registry *Registry
broker *Broker
assets *AssetServer
mu sync.RWMutex
state *StateFile
stateLoadErr error
safeMode bool
crashDetected bool
installDirs map[string]string // pluginID -> dir (for AssetServer)
supervisors map[string]*SidecarSupervisor
}
// NewManager initializes the Plugin Manager for DataRoot. If state.json is
// corrupt, stateLoadErr is recorded and returned on load rather than wiping state (§6.1).
func NewManager(opts ManagerOptions) (*Manager, error) {
layout := NewPluginsLayout(opts.DataRoot)
reg := NewRegistry(opts.Logger)
broker := NewBroker(layout, reg, opts.RedactFn)
m := &Manager{
opts: opts,
layout: layout,
store: NewStateStore(layout.Root),
registry: reg,
broker: broker,
safeMode: opts.SafeMode,
crashDetected: DidLastStartupCrash(layout.Root),
installDirs: make(map[string]string),
supervisors: make(map[string]*SidecarSupervisor),
}
m.assets = NewAssetServer(func(pluginID string) (string, bool) {
m.mu.RLock()
dir, ok := m.installDirs[pluginID]
m.mu.RUnlock()
return dir, ok
})
st, err := m.store.Load()
if err != nil {
m.stateLoadErr = err
return m, err
}
m.state = st
return m, nil
}
func (m *Manager) Registry() *Registry { return m.registry }
func (m *Manager) Broker() *Broker { return m.broker }
func (m *Manager) Assets() *AssetServer { return m.assets }
func (m *Manager) Layout() PluginsLayout { return m.layout }
func (m *Manager) SafeMode() bool { return m.safeMode }
func (m *Manager) CrashDetected() bool { return m.crashDetected }
// DesiredFor returns whether pluginID should be enabled according to state.json,
// falling back to defaultEnabled if no saved record exists.
func (m *Manager) DesiredFor(id string, defaultEnabled bool) bool {
m.mu.RLock()
defer m.mu.RUnlock()
if m.state != nil {
if rec, ok := m.state.Plugins[id]; ok {
return rec.Enabled
}
}
return defaultEnabled
}
// LoadBundled registers official L1 plugins embedded inside reims-go.exe (§9).
func (m *Manager) LoadBundled(manifests []Manifest) error {
for _, man := range manifests {
if err := ValidateManifest(man, m.opts.HostVersion, true); err != nil {
return fmt.Errorf("invalid bundled plugin %s: %w", man.ID, err)
}
desired := m.DesiredFor(man.ID, man.DefaultEnabled)
if m.safeMode {
// Bundled official L1 plugins obey safe mode too if non-builtin?
// §9: safe mode skips all third-party plugins; bundled official defaults to off anyway.
if !man.DefaultEnabled {
desired = false
}
}
if err := m.registry.Register(PluginDef{
Manifest: man,
Source: SourceBundled,
Trust: TrustOfficial,
Removable: false,
Desired: desired,
LogPath: m.layout.LogPath(man.ID),
}); err != nil {
return err
}
}
return nil
}
// LoadExternal loads all installed packages and dev links from state.json.
// In SafeMode, external plugins are registered as disabled (off) so the user
// can inspect and remove/disable faulty plugins safely (§9).
func (m *Manager) LoadExternal() error {
m.mu.RLock()
st := m.state
safe := m.safeMode
var devMode bool
var activeThemeID string
type extEntry struct {
id string
rec PluginRecord
}
var entries []extEntry
if st != nil {
devMode = st.DeveloperMode
activeThemeID = st.ActiveThemeID
for id, rec := range st.Plugins {
if rec == nil || rec.Source == SourceBuiltin || rec.Source == SourceBundled {
continue
}
cp := *rec
cp.ApprovedPermissions = append([]string(nil), rec.ApprovedPermissions...)
entries = append(entries, extEntry{id: id, rec: cp})
}
}
m.mu.RUnlock()
if st == nil {
return m.stateLoadErr
}
if !safe {
_ = BeginStartupInit(m.layout.Root)
}
for _, item := range entries {
id := item.id
rec := item.rec
var dir string
switch rec.Source {
case SourceDevLink:
if !devMode {
continue
}
dir = rec.DevPath
default:
if rec.Version == "" || !reReverseDomainID.MatchString(id) {
continue
}
if _, err := ParseSemVer(rec.Version); err != nil {
continue
}
safeDir, err := safeJoin(m.layout.PkgsDir(), id+"/"+rec.Version)
if err != nil {
continue
}
dir = safeDir
}
if dir == "" {
continue
}
if err := m.registerExternalDir(dir, &rec, safe); err != nil && m.opts.Logger != nil {
m.opts.Logger("plugin", fmt.Sprintf("skipped external plugin %s: %v", id, err))
}
}
// Restore active theme unless in safe mode (§5.1: safe mode always reverts to builtin theme).
if !safe && activeThemeID != "" {
_ = m.registry.SetActiveTheme(activeThemeID)
}
return nil
}
func (m *Manager) registerExternalDir(dir string, rec *PluginRecord, safeMode bool) error {
raw, err := os.ReadFile(filepath.Join(dir, "plugin.json"))
if err != nil {
return err
}
var man Manifest
if err := json.Unmarshal(raw, &man); err != nil {
return err
}
if err := ValidateManifest(man, m.opts.HostVersion, false); err != nil {
return err
}
if rec.ID != "" && man.ID != rec.ID {
return fmt.Errorf("manifest plugin id %q does not match state record %q", man.ID, rec.ID)
}
trust := rec.Trust
if trust == "" {
trust = TrustCommunity
}
if rec.Source == SourceDevLink {
trust = TrustDev
}
entryRel := man.Entry.Sidecar
if entryRel == "" {
entryRel = man.Entry.UIScript
}
if entryRel == "" {
entryRel = man.Entry.Script
}
entryAbs := ""
entryHash := ""
if entryRel != "" {
full, err := safeJoin(dir, entryRel)
if err != nil {
return fmt.Errorf("invalid plugin entry path %q: %w", entryRel, err)
}
entryAbs = full
entryHash, _ = fileSHA256Hex(full)
}
needsApproval := computeNeedsApproval(man, trust, rec.ApprovedPermissions, rec.ApprovedEntryHash, entryHash)
desired := rec.Enabled && !safeMode && !needsApproval
m.mu.Lock()
m.installDirs[man.ID] = dir
m.mu.Unlock()
tier := man.InferTier(false)
var activate Activator
if tier == TierL3 && entryAbs != "" {
activate = m.buildSidecarActivator(man, entryAbs, rec.BlockingGuardOK)
}
return m.registry.Register(PluginDef{
Manifest: man,
Source: rec.Source,
Trust: trust,
InstallDir: dir,
EntryPath: entryAbs,
EntryHash: entryHash,
LogPath: m.layout.LogPath(man.ID),
Removable: true,
Desired: desired,
ApprovedPermissions: append([]string(nil), rec.ApprovedPermissions...),
NeedsApproval: needsApproval,
Activate: activate,
})
}
func computeNeedsApproval(m Manifest, trust TrustLevel, approvedPerms []string, approvedHash, currentHash string) bool {
if trust == TrustOfficial {
return false
}
approvedSet := make(map[string]bool, len(approvedPerms))
for _, p := range approvedPerms {
approvedSet[p] = true
}
// Any unapproved high-risk permission requires explicit confirmation (§7.1).
for _, hp := range HighRiskPermissions(m.Permissions) {
if !approvedSet[hp] {
return true
}
}
// Community L3 sidecar requires explicit hash approval (§7.2).
if trust == TrustCommunity && m.InferTier(false) == TierL3 {
if currentHash == "" || approvedHash != currentHash {
return true
}
}
return false
}
func (m *Manager) buildSidecarActivator(man Manifest, exePath string, blockingAllowed bool) Activator {
return func(ctx context.Context, sc *Scope) error {
pid := man.ID
sup := NewSidecarSupervisor(SidecarOptions{
PluginID: pid,
ExePath: exePath,
DataDir: m.layout.DataDir(pid),
Broker: m.broker,
Registry: m.registry,
IdleTimeout: 5 * time.Minute,
})
m.mu.Lock()
m.supervisors[pid] = sup
m.mu.Unlock()
sc.OnDispose(func() {
sup.Stop()
m.mu.Lock()
if m.supervisors[pid] == sup {
delete(m.supervisors, pid)
}
m.mu.Unlock()
})
// Wire Sidecar hooks.
for _, hk := range man.Contributes.Hooks {
h := hk
m.registry.Hooks().Subscribe(sc, HookRegistration{
PluginID: pid,
Event: h.Event,
Priority: h.Priority,
Blocking: h.Blocking,
BlockingAllowed: blockingAllowed,
Handler: func(hctx context.Context, payload any) (any, error) {
switch h.Event {
case EventVMBeforeStart:
var intent StartIntent
if err := sup.Call(hctx, "hook/"+h.Event, payload, &intent); err != nil {
return nil, err
}
intent.PluginID = pid
return intent, nil
case EventHostPreflight:
var pr PreflightResult
if err := sup.Call(hctx, "hook/"+h.Event, payload, &pr); err != nil {
return nil, err
}
return pr, nil
case EventVMBeforeCreate:
var bcr BeforeCreateResult
if err := sup.Call(hctx, "hook/"+h.Event, payload, &bcr); err != nil {
return nil, err
}
return bcr, nil
default:
var out any
err := sup.Call(hctx, "hook/"+h.Event, payload, &out)
return out, err
}
},
})
}
// Wire Sidecar commands.
for _, cmd := range man.Contributes.Commands {
c := cmd
m.registry.RegisterCommand(sc, c, func(cctx context.Context, args map[string]any) (any, error) {
var out any
err := sup.Call(cctx, "command/invoke", map[string]any{
"command": c.ID,
"args": args,
}, &out)
return out, err
})
}
// Wire Sidecar diagnostics collectors.
for _, diag := range man.Contributes.Diagnostics {
dg := diag
m.registry.RegisterDiagnostics(sc, dg, func(dctx context.Context, vmName string) (DiagnosticsEntry, error) {
var entry DiagnosticsEntry
err := sup.Call(dctx, "diagnostics/collect", map[string]any{
"id": dg.ID,
"vm_name": vmName,
}, &entry)
return entry, err
})
}
// Wire Sidecar guest drivers.
if m.opts.SidecarDriverFactory != nil {
for _, gd := range man.Contributes.GuestDrivers {
drv := m.opts.SidecarDriverFactory(gd, sup)
if drv != nil {
m.registry.RegisterGuestDriver(sc, gd.ID, drv)
}
}
}
// Eagerly start only if activation explicitly includes "onStartup" (§8).
for _, act := range man.Activation {
if strings.EqualFold(act, "onStartup") {
if err := sup.EnsureStarted(ctx); err != nil {
return err
}
break
}
}
return nil
}
}
// InstallLocalArchive transactionally installs a local .zip plugin package and
// records it in state.json (disabled by default until user enables/approves it).
func (m *Manager) InstallLocalArchive(ctx context.Context, archivePath string, opts PackageInstallOptions) (*PluginInfo, error) {
if opts.HostVersion == "" {
opts.HostVersion = m.opts.HostVersion
}
if len(opts.Keyring) == 0 {
opts.Keyring = m.opts.Keyring
}
opts.AllowUnsigned = true
installed, err := InstallArchive(m.layout, archivePath, opts)
if err != nil {
return nil, err
}
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
return nil, errors.New("plugin state not loaded")
}
rec := m.state.Plugins[installed.Manifest.ID]
if rec == nil {
rec = &PluginRecord{
ID: installed.Manifest.ID,
Source: SourceLocal,
Enabled: false,
}
m.state.Plugins[installed.Manifest.ID] = rec
}
// Preserve previously installed versions for rollback (§9).
foundVer := false
for _, v := range rec.InstalledVersions {
if v == installed.Manifest.Version {
foundVer = true
break
}
}
if !foundVer {
rec.InstalledVersions = append(rec.InstalledVersions, installed.Manifest.Version)
}
rec.Version = installed.Manifest.Version
rec.Source = SourceLocal
rec.Trust = installed.Trust
rec.UpdatedAt = time.Now()
// If upgrade introduces unapproved high-risk permissions or changed binary hash, pause it (§7.1).
if computeNeedsApproval(installed.Manifest, installed.Trust, rec.ApprovedPermissions, rec.ApprovedEntryHash, installed.EntryHash) {
rec.Enabled = false
}
if err := m.store.Save(m.state); err != nil {
m.mu.Unlock()
return nil, err
}
recCopy := *rec
m.mu.Unlock()
if err := m.registerExternalDir(installed.InstallDir, &recCopy, m.safeMode); err != nil {
return nil, err
}
m.registry.Reconcile(ctx)
info, _ := m.registry.Info(installed.Manifest.ID)
return &info, nil
}
// LinkDev links a local plugin directory in developer mode (trust=dev, §5.1, §9).
func (m *Manager) LinkDev(ctx context.Context, dir string) (*PluginInfo, error) {
absDir, err := filepath.Abs(dir)
if err != nil {
return nil, err
}
raw, err := os.ReadFile(filepath.Join(absDir, "plugin.json"))
if err != nil {
return nil, fmt.Errorf("read plugin.json: %w", err)
}
var man Manifest
if err := json.Unmarshal(raw, &man); err != nil {
return nil, fmt.Errorf("parse plugin.json: %w", err)
}
if err := ValidateManifest(man, m.opts.HostVersion, false); err != nil {
return nil, err
}
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
return nil, m.stateNotLoadedErr()
}
m.state.DeveloperMode = true
rec := m.state.Plugins[man.ID]
if rec == nil {
rec = &PluginRecord{ID: man.ID}
m.state.Plugins[man.ID] = rec
}
rec.Source = SourceDevLink
rec.Trust = TrustDev
rec.Version = man.Version
rec.DevPath = absDir
rec.Enabled = false
rec.UpdatedAt = time.Now()
if err := m.store.Save(m.state); err != nil {
m.mu.Unlock()
return nil, err
}
recCopy := *rec
m.mu.Unlock()
if err := m.registerExternalDir(absDir, &recCopy, m.safeMode); err != nil {
return nil, err
}
m.registry.Reconcile(ctx)
info, _ := m.registry.Info(man.ID)
return &info, nil
}
// Enable activates a plugin, optionally recording high-risk permission approval (§7.1, §7.2).
func (m *Manager) Enable(ctx context.Context, id string, approveHighRisk bool) error {
info, ok := m.registry.Info(id)
if !ok {
return fmt.Errorf("plugin %q not found", id)
}
if m.safeMode && info.Source != SourceBuiltin {
return errors.New("cannot enable third-party plugins in safe mode")
}
if info.NeedsApproval && !approveHighRisk {
return fmt.Errorf("plugin %q requires explicit high-risk permission approval", id)
}
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
return m.stateNotLoadedErr()
}
rec := m.state.Plugins[id]
if rec == nil {
rec = &PluginRecord{ID: id, Source: info.Source, Trust: info.Trust, Version: info.Version}
m.state.Plugins[id] = rec
}
prevEnabled := rec.Enabled
prevApprovedPerms := append([]string(nil), rec.ApprovedPermissions...)
prevApprovedHash := rec.ApprovedEntryHash
rec.Enabled = true
rec.UpdatedAt = time.Now()
if approveHighRisk {
perms := make([]string, 0, len(info.Permissions))
for _, p := range info.Permissions {
perms = append(perms, p.Name)
}
rec.ApprovedPermissions = perms
rec.ApprovedEntryHash = info.EntryHash
}
dir := info.InstallDir
recCopy := *rec
recCopy.ApprovedPermissions = append([]string(nil), rec.ApprovedPermissions...)
m.mu.Unlock()
if approveHighRisk && dir != "" && info.Source != SourceBuiltin && info.Source != SourceBundled {
if err := m.registerExternalDir(dir, &recCopy, false); err != nil {
m.mu.Lock()
rec.Enabled = prevEnabled
rec.ApprovedPermissions = prevApprovedPerms
rec.ApprovedEntryHash = prevApprovedHash
m.mu.Unlock()
return err
}
}
if err := m.registry.SetDesired(ctx, id, true); err != nil {
m.mu.Lock()
rec.Enabled = prevEnabled
rec.ApprovedPermissions = prevApprovedPerms
rec.ApprovedEntryHash = prevApprovedHash
m.mu.Unlock()
return err
}
m.mu.Lock()
err := m.store.Save(m.state)
m.mu.Unlock()
return err
}
// Disable turns off a plugin (if not in use) and persists the state.
func (m *Manager) Disable(ctx context.Context, id string) error {
if err := m.registry.SetDesired(ctx, id, false); err != nil {
return err
}
activeThemeNil := m.registry.ActiveTheme() == nil
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
return m.stateNotLoadedErr()
}
rec := m.state.Plugins[id]
if rec == nil {
rec = &PluginRecord{ID: id}
m.state.Plugins[id] = rec
}
rec.Enabled = false
rec.UpdatedAt = time.Now()
if m.state.ActiveThemeID != "" && activeThemeNil {
// If disabling the active theme's plugin, fall back to builtin default theme (§5.1).
m.state.ActiveThemeID = ""
}
err := m.store.Save(m.state)
m.mu.Unlock()
return err
}
// MarkBootComplete clears the plugin startup crash sentinel AFTER Reconcile
// has activated plugins cleanly (M8, §9).
func (m *Manager) MarkBootComplete() {
EndStartupInit(m.layout.Root)
}
// Remove uninstalls a removable external plugin (refusing builtins/bundled or in-use plugins).
// Also allows removing orphaned/failed records present only in state.json (M8).
func (m *Manager) Remove(ctx context.Context, id string, purgeData bool) error {
if info, ok := m.registry.Info(id); ok {
if !info.Removable {
return fmt.Errorf("plugin %q is built-in or bundled and cannot be uninstalled (disable it instead)", id)
}
if err := m.registry.Unregister(ctx, id); err != nil {
return err
}
} else {
m.mu.RLock()
existsInState := m.state != nil && m.state.Plugins[id] != nil
m.mu.RUnlock()
if !existsInState {
return fmt.Errorf("plugin %q not found", id)
}
}
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
return m.stateNotLoadedErr()
}
delete(m.state.Plugins, id)
delete(m.installDirs, id)
err := m.store.Save(m.state)
m.mu.Unlock()
if err != nil {
return err
}
_ = os.RemoveAll(filepath.Join(m.layout.PkgsDir(), id))
if purgeData {
_ = os.RemoveAll(m.layout.DataDir(id))
_ = os.Remove(m.layout.LogPath(id))
}
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
}
return errors.New("plugin state not loaded")
}
// --- Settings store (app-scoped & vm-scoped, hiding x-secret on readback) ---
func (m *Manager) GetSettings(pluginID, vmName string, maskSecrets bool) map[string]any {
var schema *SettingsSchema
if info, ok := m.registry.Info(pluginID); ok {
schema = info.Settings
}
m.mu.RLock()
defer m.mu.RUnlock()
out := map[string]any{}
// Seed defaults from schema.
if schema != nil {
for k, prop := range schema.Properties {
if prop.Default != nil {
out[k] = prop.Default
}
}
}
if m.state != nil {
if rec := m.state.Plugins[pluginID]; rec != nil {
if vmName == "" {
for k, v := range rec.AppSettings {
out[k] = v
}
} else if vmMap := rec.VMSettings[vmName]; vmMap != nil {
for k, v := range vmMap {
out[k] = v
}
}
}
}
if maskSecrets && schema != nil {
for k, prop := range schema.Properties {
if prop.Secret {
if _, exists := out[k]; exists && out[k] != "" {
out[k] = "••••••••"
}
}
}
}
return out
}
func (m *Manager) SetSettings(pluginID, vmName string, values map[string]any) error {
info, hasInfo := m.registry.Info(pluginID)
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
return m.stateNotLoadedErr()
}
rec := m.state.Plugins[pluginID]
if rec == nil {
rec = &PluginRecord{ID: pluginID}
if hasInfo {
rec.Source = info.Source
rec.Trust = info.Trust
rec.Enabled = info.Enabled
}
m.state.Plugins[pluginID] = rec
}
isSecretMask := func(k string, v any) bool {
if info.Settings == nil {
return false
}
prop, ok := info.Settings.Properties[k]
if !ok || !prop.Secret {
return false
}
s, ok := v.(string)
return ok && s == "••••••••"
}
if vmName == "" {
if rec.AppSettings == nil {
rec.AppSettings = map[string]any{}
}
for k, v := range values {
if isSecretMask(k, v) {
continue
}
rec.AppSettings[k] = v
}
} else {
if rec.VMSettings == nil {
rec.VMSettings = map[string]map[string]any{}
}
if rec.VMSettings[vmName] == nil {
rec.VMSettings[vmName] = map[string]any{}
}
for k, v := range values {
if isSecretMask(k, v) {
continue
}
rec.VMSettings[vmName][k] = v
}
}
rec.UpdatedAt = time.Now()
err := m.store.Save(m.state)
cb := m.opts.OnSettingsChanged
m.mu.Unlock()
if err == nil && cb != nil {
cb(pluginID, vmName)
}
return err
}
// SavedVMSettingsForPlugin returns a copy of all saved per-VM setting maps for pluginID.
func (m *Manager) SavedVMSettingsForPlugin(pluginID string) map[string]map[string]any {
m.mu.RLock()
defer m.mu.RUnlock()
if m.state == nil {
return nil
}
rec := m.state.Plugins[pluginID]
if rec == nil || len(rec.VMSettings) == 0 {
return nil
}
out := make(map[string]map[string]any, len(rec.VMSettings))
for vmName, kv := range rec.VMSettings {
cp := make(map[string]any, len(kv))
for k, v := range kv {
cp[k] = v
}
out[vmName] = cp
}
return out
}
// GetAllVMSettings returns pluginID -> settings map for vmName across active plugins.
func (m *Manager) GetAllVMSettings(vmName string) map[string]map[string]any {
out := map[string]map[string]any{}
for _, info := range m.registry.List() {
if info.State != StateActive && info.State != StateDegraded {
continue
}
if info.Settings == nil {
continue
}
hasVMProp := info.Settings.Scope == "vm"
if !hasVMProp {
for _, p := range info.Settings.Properties {
if p.Scope == "vm" {
hasVMProp = true
break
}
}
}
if hasVMProp {
out[info.ID] = m.GetSettings(info.ID, vmName, true)
}
}
return out
}
// --- Theme Management (§5.1) ---
func (m *Manager) SetActiveTheme(themeID, schemeID string) error {
if m.safeMode && themeID != "" && themeID != "builtin.theme.default" {
return errors.New("custom themes are disabled in safe mode")
}
if err := m.registry.SetActiveTheme(themeID); err != nil {
return err
}
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
return m.stateNotLoadedErr()
}
m.state.ActiveThemeID = themeID
m.state.ActiveSchemeID = schemeID
err := m.store.Save(m.state)
m.mu.Unlock()
return err
}
func (m *Manager) SaveCustomThemeScheme(scheme CustomThemeScheme) error {
if strings.TrimSpace(scheme.ID) == "" || strings.TrimSpace(scheme.Name) == "" {
return errors.New("scheme id and name required")
}
for k, v := range scheme.Seeds {
if err := ValidateCSSTokenValue(v); err != nil {
return fmt.Errorf("invalid seed %q: %w", k, err)
}
}
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
return m.stateNotLoadedErr()
}
updated := false
for i := range m.state.CustomSchemes {
if m.state.CustomSchemes[i].ID == scheme.ID {
m.state.CustomSchemes[i] = scheme
updated = true
break
}
}
if !updated {
m.state.CustomSchemes = append(m.state.CustomSchemes, scheme)
}
err := m.store.Save(m.state)
m.mu.Unlock()
return err
}
func (m *Manager) DeleteCustomThemeScheme(schemeID string) error {
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
return m.stateNotLoadedErr()
}
kept := m.state.CustomSchemes[:0]
for _, s := range m.state.CustomSchemes {
if s.ID != schemeID {
kept = append(kept, s)
}
}
m.state.CustomSchemes = kept
if m.state.ActiveSchemeID == schemeID {
m.state.ActiveSchemeID = ""
}
err := m.store.Save(m.state)
m.mu.Unlock()
return err
}
// ActiveThemePayload builds the resolved theme bundle for the frontend (§5.1).
// Returns an empty/default payload when using the builtin theme (zero extra CSS).
func (m *Manager) ActiveThemePayload() ActiveThemePayload {
m.mu.RLock()
activeScheme := ""
var customSchemes []CustomThemeScheme
if m.state != nil {
activeScheme = m.state.ActiveSchemeID
customSchemes = append([]CustomThemeScheme(nil), m.state.CustomSchemes...)
}
m.mu.RUnlock()
if m.safeMode {
return ActiveThemePayload{ThemeID: "builtin.theme.default", CustomSchemes: customSchemes}
}
th := m.registry.ActiveTheme()
if th == nil || th.ID == "builtin.theme.default" {
return ActiveThemePayload{ThemeID: "builtin.theme.default", CustomSchemes: customSchemes}
}
payload := ActiveThemePayload{
ThemeID: th.ID,
PluginID: th.PluginID,
ActiveScheme: activeScheme,
Theme: th,
CustomSchemes: customSchemes,
AssetBaseURL: "/plugin-assets/" + m.assets.Token() + "/" + th.PluginID + "/",
}
m.mu.RLock()
installDir := m.installDirs[th.PluginID]
m.mu.RUnlock()
if installDir != "" && th.Stylesheet != "" {
if full, err := safeJoin(installDir, th.Stylesheet); err == nil {
if raw, err := os.ReadFile(full); err == nil {
if ValidateThemeCSSSafetyInDir(string(raw), filepath.Dir(full)) == nil {
payload.CSS = string(raw)
}
}
}
}
if th.UIScript != "" && validateSafeManifestAsset(th.UIScript, "") == nil {
if info, ok := m.registry.Info(th.PluginID); ok {
hasPerm := false
for _, p := range info.Permissions {
if p.Name == "ui:script" {
hasPerm = true
break
}
}
approved := info.Trust == TrustOfficial || info.Source == SourceBuiltin
if !approved && !info.NeedsApproval {
for _, ap := range info.ApprovedPermissions {
if ap == "ui:script" {
approved = true
break
}
}
}
// Enforce §5.1 trust boundary: ui:script requires declared and approved permission.
if hasPerm && approved {
payload.UIScriptURL = m.assets.AssetURL(th.PluginID, th.UIScript)
payload.UIScriptTrust = info.Trust
}
}
}
return payload
}
// ActiveVMNamesWithSetting scans saved VM settings for pluginID where key==true.
func (m *Manager) ActiveVMNamesWithSetting(pluginID, key string) []string {
m.mu.RLock()
defer m.mu.RUnlock()
if m.state == nil {
return nil
}
rec := m.state.Plugins[pluginID]
if rec == nil || len(rec.VMSettings) == 0 {
return nil
}
var out []string
for vmName, kv := range rec.VMSettings {
if b, ok := kv[key].(bool); ok && b {
out = append(out, vmName)
}
}
sort.Strings(out)
return out
}
// Close shuts down all active plugins and Sidecar supervisors cleanly.
func (m *Manager) Close() {
m.registry.DisposeAll()
m.mu.Lock()
sups := make([]*SidecarSupervisor, 0, len(m.supervisors))
for id, sup := range m.supervisors {
sups = append(sups, sup)
delete(m.supervisors, id)
}
m.mu.Unlock()
for _, sup := range sups {
sup.Stop()
}
}