Files
Reims-Go/internal/app/plugins_flow.go
T
千川白浪 d55241cba2 feat(plugin): catalog the Host API, open secret typing and extend the SDK
Give the Sidecar Host API one authoritative catalog in pkg/pluginproto: every
host/* method's status, required permissions, handshake feature and request and
result shapes. The host, pkg/pluginsdk and plugins share those types, so a field
can no longer exist on one side only, and permissions come from the catalog
instead of from each handler. Tests gate that every served method is
catalogued, every stable catalogued method is served, and every catalogued
permission is one the host recognizes.

Open the interface up instead of adding consent gates. Typing a secret setting
is no longer reserved for reims.agent: any plugin that holds qmp:write and that
the user authorized for the VM can have the host type the plugin's own setting,
which the plugin never reads back. Restoring a snapshot works on any authorized
VM, a plugin names its own clones, a held key may carry modifiers, and a
screenshot width outside the supported range is brought into range rather than
refused. Deleting a VM stays limited to the temporary VMs a plugin created.

Record the keys and pointer buttons each plugin holds per VM and lift them when
the plugin's process exits, its scope is disposed, the VM stops or it stops
calling, so a guest never stays stuck with a modifier down. Requests from
plugins that declare pluginApi 1.3 or newer are decoded strictly and answer an
undefined field with JSON-RPC -32602, while older plugins keep tolerant
decoding.

Add typed VM and console methods to pkg/pluginsdk so a plugin no longer needs
its own JSON-RPC client. A method the contract does not catalog, or one the
host did not advertise in the handshake, is refused before it is sent, and the
host's JSON-RPC error code reaches the caller.
2026-12-05 01:43:28 -07:00

1350 lines
38 KiB
Go

package app
import (
"context"
"errors"
"fmt"
"math"
"net/http"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"time"
"unicode"
"unicode/utf8"
"github.com/Nwflower/reims-go/internal/downloader"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/fetch"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/macos/guest"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/version"
"github.com/Nwflower/reims-go/internal/vmstart"
)
// PluginUIContributions aggregates all active declarative plugin UI contributions
// for the frontend in a single round-trip (§4.2, §10).
type PluginUIContributions struct {
SafeMode bool `json:"safe_mode"`
CrashDetected bool `json:"crash_detected"`
Menus []plugin.MenuContribution `json:"menus,omitempty"`
VMCards []plugin.VMCardContribution `json:"vm_cards,omitempty"`
SettingsPages []plugin.SettingsPageContribution `json:"settings_pages,omitempty"`
StatusItems []plugin.StatusItemContribution `json:"status_items,omitempty"`
Panels []plugin.PanelContribution `json:"panels,omitempty"`
Views []plugin.ViewContribution `json:"views,omitempty"`
ImageSources []plugin.ImageSourceContribution `json:"image_sources,omitempty"`
VMTemplates []plugin.VMTemplateContribution `json:"vm_templates,omitempty"`
Themes []plugin.ThemeContribution `json:"themes,omitempty"`
Locales []plugin.ResolvedLocalePack `json:"locales,omitempty"`
RuntimeSources []plugin.RuntimeSourceContribution `json:"runtime_sources,omitempty"`
RuntimeKinds []rt.KindSpec `json:"runtime_kinds,omitempty"`
Drivers []driver.DriverSummary `json:"drivers,omitempty"`
AssetToken string `json:"asset_token,omitempty"`
}
func (a *App) initPlugins() {
// Plugins keep their state in the data folder. Before setup there is no
// chosen folder, and a read-only folder must not be written; the app runs
// without a plugin manager then (see startup).
if !a.dataRootUsable() {
return
}
a.mu.Lock()
dataRoot := a.cfg.DataRoot
safeMode := a.launch.SafeMode
a.mu.Unlock()
// Idempotent fallback for tests or embedders that construct a Manager directly;
// normal startup already ran this as data layout v3 in dataroot.Open.
if err := guest.MigrateFiles(dataRoot); err != nil {
a.emitLog("plugin", "Could not migrate macOS guest state: "+err.Error())
return
}
var mgr *plugin.Manager
mgr, err := plugin.NewManager(plugin.ManagerOptions{
DataRoot: dataRoot,
HostVersion: version.Version,
SafeMode: safeMode,
RedactFn: host.RedactText,
LocaleFn: a.locale,
Logger: func(source, line string) {
a.emitLog(source, line)
},
SidecarDriverFactory: func(contrib plugin.GuestDriverContribution, sup *plugin.SidecarSupervisor) any {
return driver.NewSidecarDriver(contrib, sup)
},
HostHandlers: func(pluginID string) map[string]plugin.RPCRequestHandler {
a.mu.Lock()
current := a.pluginMgr
a.mu.Unlock()
return a.hostHandlers(current, pluginID)
},
OnSettingsChanged: func(pluginID, vmName string) {
a.onPluginSettingsChanged(pluginID, vmName)
},
OnSidecarStopped: func(pluginID string) {
// A plugin that held a key or a pointer button in a guest can no
// longer release it, so the host lifts what it left down.
a.releaseHeldForPlugin(pluginID)
},
})
if err != nil {
a.emitLog("plugin", "Plugin state warning: "+err.Error())
if mgr == nil {
return
}
}
kindReg := rt.NewKindRegistry()
drvRouter := driver.NewRouter(mgr.Registry(), func() string {
a.mu.Lock()
defer a.mu.Unlock()
return a.cfg.DataRoot
}, guest.VMInventory())
mgr.Registry().SetInUseChecker(drvRouter.PluginInUseChecker())
mgr.Registry().SetBusyChecker(drvRouter.PluginBusyChecker())
// Drivers push the state of the VMs they host; the router merges the table
// into what the drivers return. A spawned VM's exit wakes the poll at once.
stateTable := driver.NewStateTable()
drvRouter.SetStateTable(stateTable)
mgr.Broker().SetVMStateHandler(func(_ string, rep plugin.ReportedVMState) error {
if err := stateTable.Report(driver.ReportedStateFromPlugin(rep)); err != nil {
return err
}
a.wakePoll()
a.emitStateChanged()
return nil
})
mgr.Broker().SetVMExitHandler(func(string, string) { a.wakePoll() })
mgr.Broker().SetLogger(a.emitLog)
mgr.Broker().SetNotifier(func(pluginID, title, body string) {
a.emitLog("plugin:"+pluginID, title+": "+body)
})
cb := builtin.HostCallbacks{
GetConfig: a.runtimeConfig,
Log: func(source, line string) {
a.emitLog(source, line)
},
EnsureGuestTools: func() (*guesttools.Server, int, error) {
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()
gt := a.guestTools
a.guestTools = nil
a.mu.Unlock()
if gt != nil {
shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
_ = gt.Close(shutCtx)
cancel()
}
},
LoadAndRegisterGuestTools: func(srv *guesttools.Server, port int, dir, name string) (guesttools.VMConfig, error) {
epoch := a.vmDeleteEpoch(name)
// The start hook can receive a directory read before the VM was deleted.
if epoch != 0 {
vms, err := a.listVMsInternal(context.Background())
if err != nil {
return guesttools.VMConfig{}, err
}
if !slices.ContainsFunc(vms, func(vm driver.VMListItem) bool {
return strings.EqualFold(vm.Name, name) && filepath.Clean(vm.Dir) == filepath.Clean(dir)
}) {
return guesttools.VMConfig{}, os.ErrNotExist
}
}
return a.loadAndRegisterNetworkGuestTools(srv, port, dir, name, epoch)
},
OnIMEText: func(target host.IMETarget, text string) {
go a.injectRemoteText(target.VMName, target.VMDir, text)
},
StartColdReboot: func(vmName, qmpAddr string) {
a.watchWin10ColdReboot(vmName, qmpAddr)
},
CancelColdReboot: func(vmName string) {
a.cancelRebootWatcher(vmName)
},
GuestToolsImg: func(vmName string) string {
return a.guestToolsImagePath(vmName)
},
BuildGuestToolsImage: a.buildGuestToolsImage,
OpenAppWindow: a.openAppWindow,
PrepareVMNetwork: a.prepareManagedVMNetwork,
RestorePacketBridges: func(ctx context.Context) func() {
return a.startPacketBridgeRestore(ctx, func(ctx context.Context) {
if a.dataRootUsable() {
a.registerExistingPacketBridges(ctx)
}
})
},
StopPacketBridges: a.closePacketBridges,
OnInstallGuidesChanged: func() {
a.emitStateChanged()
},
SyncInstallGuides: func() {
a.wakePoll()
},
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 := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
a.emitLog("plugin", "macOS guest plugin register error: "+err.Error())
}
if err := mgr.LoadExternal(); err != nil {
a.emitLog("plugin", "External plugin load warning: "+err.Error())
}
// Sync runtime kinds, input filters, clipboard policies, and locales whenever registry state changes.
mgr.Registry().OnChange(func() {
active := map[string]bool{}
for id := range mgr.Registry().GuestDrivers() {
active[id] = true
}
stateTable.PruneDrivers(active)
a.syncRuntimeKinds(kindReg, mgr.Registry())
a.syncInputFilters()
a.syncKeymapRules()
a.syncClipboardPolicies()
a.syncLocales()
a.wakePoll()
a.emitStateChanged()
})
a.keymapMu.Lock()
a.mu.Lock()
fallback := a.fallbackInputSvc
a.fallbackInputSvc = nil
a.pluginMgr = mgr
a.driverRouter = drvRouter
a.vmStateTable = stateTable
a.lifecycleSvc = vmlifecycle.New(mgr.Registry(), drvRouter, a.startHookPayload)
a.runtimeKinds = kindReg
a.mu.Unlock()
if fallback != nil {
fallback.Close()
}
a.keymapMu.Unlock()
fetch.SetDefaultDownloader(a.activeDownloader)
mgr.Registry().Reconcile(context.Background())
if err := a.restoreComputerUseOwnedVMs(context.Background()); err != nil {
a.emitLog("plugin", "Could not restore temporary computer-use VM ownership: "+err.Error())
}
mgr.MarkBootComplete()
a.syncInputFilters()
a.syncKeymapRules()
a.syncClipboardPolicies()
a.syncLocales()
a.startPluginControlServer()
}
// activeDownloader returns the highest-priority active downloader plugin provider,
// or nil when all downloader plugins are disabled.
func (a *App) activeDownloader() downloader.Provider {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return nil
}
_, prov, ok := mgr.Registry().ActiveDownloader()
if !ok {
return nil
}
return prov
}
func (a *App) shutdownPlugins() {
fetch.SetDefaultDownloader(nil)
a.mu.Lock()
mgr := a.pluginMgr
a.pluginMgr = nil
a.pluginMarket = nil
a.lifecycleSvc = nil
a.driverRouter = nil
a.vmStateTable = nil
a.mu.Unlock()
i18n.SetPluginCatalogs(nil)
if mgr != nil {
mgr.Close()
}
}
func (a *App) getPluginMarket() *plugin.MarketClient {
a.mu.Lock()
defer a.mu.Unlock()
if a.needsSetup {
// The first-run screen has not chosen a data folder yet (a.cfg holds
// only the default suggestion), so nothing may be cached or
// downloaded into it. A throwaway client keeps the index in memory;
// the first call after setup builds the real one.
return plugin.NewMarketClient(plugin.MarketClientOptions{HostVersion: version.Version})
}
if a.pluginMarket != nil {
return a.pluginMarket
}
dataRoot := ""
if a.cfg != nil {
dataRoot = a.cfg.DataRoot
}
a.pluginMarket = plugin.NewMarketClient(plugin.MarketClientOptions{
Layout: plugin.NewPluginsLayout(dataRoot),
HostVersion: version.Version,
})
return a.pluginMarket
}
// reloadPlugins tears down the existing Plugin Manager (if running) and
// re-initializes plugins and language packs against the current a.cfg.DataRoot.
func (a *App) reloadPlugins() {
a.mu.Lock()
hadPlugins := a.pluginMgr != nil
hasCtx := a.ctx != nil
ib := a.imeBridge
a.imeBridge = nil
a.mu.Unlock()
if ib != nil {
ib.Close()
}
if !hadPlugins && !hasCtx {
// Headless unit test without initialized app runtime: load static locale packs only.
a.mu.Lock()
dr := ""
if a.cfg != nil {
dr = a.cfg.DataRoot
}
a.mu.Unlock()
plugin.LoadStaticLocalePacks(dr)
return
}
a.shutdownPlugins()
a.initPlugins()
}
func (a *App) syncLocales() {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
i18n.SetPluginCatalogs(nil)
return
}
uiPacks, backendPacks := mgr.ResolvedLocalePacks()
if len(uiPacks) > 0 {
if backendPacks == nil {
backendPacks = make(map[i18n.Locale]i18n.PluginCatalog)
}
for _, up := range uiPacks {
if !up.HasUIMessages {
continue
}
loc := i18n.Locale(up.Locale)
if _, exists := backendPacks[loc]; !exists {
backendPacks[loc] = i18n.PluginCatalog{
Fallback: i18n.Locale(up.Fallback),
}
}
}
}
i18n.SetPluginCatalogs(backendPacks)
go mgr.NotifyLocaleChanged(mgr.CurrentLocale())
}
func (a *App) syncRuntimeKinds(kr *rt.KindRegistry, reg *plugin.Registry) {
if kr == nil || reg == nil {
return
}
activeKinds := map[string]bool{rt.DefaultKind: true}
for _, rk := range reg.RuntimeKinds() {
activeKinds[rk.Kind] = true
_ = kr.Register(rt.KindSpec{
Kind: rk.Kind,
Name: rk.Name,
NameZh: rk.Name.ZhCN,
NameEn: rk.Name.EnUS,
RequiredFiles: rk.RequiredFiles,
DefaultAPIVersion: rk.DefaultAPIVer,
PluginID: rk.PluginID,
})
}
for _, existing := range kr.List() {
if !existing.Builtin && !activeKinds[existing.Kind] {
kr.Unregister(existing.Kind, "")
}
}
}
func (a *App) getInputService() *host.InputService {
a.mu.Lock()
if a.inputShuttingDown {
a.mu.Unlock()
return nil
}
mgr := a.pluginMgr
if mgr == nil {
if a.fallbackInputSvc == nil {
a.fallbackInputSvc = host.NewInputService(nil)
}
svc := a.fallbackInputSvc
a.mu.Unlock()
return svc
}
a.mu.Unlock()
raw, ok := mgr.Registry().LookupService(builtin.ServiceHostInput)
if !ok {
return nil
}
svc, _ := raw.(*host.InputService)
return svc
}
func (a *App) syncInputFilters() {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return
}
svc := a.getInputService()
if svc == nil {
return
}
contribs := mgr.Registry().InputFilters()
var rules []host.InputFilterRule
for _, flt := range contribs {
if flt.Event != "mouse_wheel" {
continue
}
settingKey := flt.SettingKey
if settingKey == "" {
settingKey = "enabled"
}
vmNames := mgr.ActiveVMNamesWithSetting(flt.PluginID, settingKey)
if len(vmNames) == 0 {
continue
}
for _, vmKey := range vmNames {
ref, ok := driver.ParseVMRef(vmKey)
if !ok {
ref = driver.NewVMRef("", vmKey)
}
vmName := ref.Name
vals := mgr.GetSettings(flt.PluginID, vmKey, false)
vert := true
if flt.VertKey != "" {
if v, ok := vals[flt.VertKey].(bool); ok {
vert = v
}
}
horiz := false
if flt.HorizKey != "" {
if h, ok := vals[flt.HorizKey].(bool); ok {
horiz = h
}
}
if !vert && !horiz {
continue
}
axis := flt.Axis
if flt.VertKey != "" || flt.HorizKey != "" {
// Explicit per-axis booleans govern; clear Axis so vertical=false is respected.
axis = ""
}
rules = append(rules, host.InputFilterRule{
ID: flt.ID + ":" + ref.Key(),
PluginID: flt.PluginID,
Event: flt.Event,
Axis: axis,
Transform: flt.Transform,
Scope: flt.Scope,
VMNames: map[string]bool{vmName: true},
Vertical: vert,
Horizontal: horiz,
})
}
}
svc.SetFilterRules(rules)
}
func (a *App) syncClipboardPolicies() {
a.mu.Lock()
mgr := a.pluginMgr
gt := a.guestTools
a.mu.Unlock()
if mgr == nil || gt == nil {
return
}
if !mgr.Registry().IsActive(builtin.IDClipboard) {
return
}
globalVals := mgr.GetSettings(builtin.IDClipboard, "", false)
gt.SetGlobalClipboardPolicy(clipboardPolicyFromMap(globalVals))
}
func (a *App) onPluginSettingsChanged(pluginID, vmName string) {
a.syncInputFilters()
if pluginID == builtin.IDClipboard {
a.syncClipboardPolicies()
}
if pluginID == guest.ID && vmName == "" {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr != nil {
wantGuide := guest.SettingOn(mgr.GetSettings(guest.ID, "", false), guest.SettingInstallGuide)
if wantGuide != a.installGuideEnabled() {
a.reloadPlugins()
}
}
}
a.emitStateChanged()
}
func clipboardPolicyFromMap(vals map[string]any) guesttools.ClipboardPolicy {
p := guesttools.DefaultClipboardPolicy()
if v, ok := vals["enabled"].(bool); ok {
p.Enabled = v
}
if v, ok := vals["direction"].(string); ok && v != "" {
p.Direction = guesttools.ClipboardDirection(v)
}
if v, ok := vals["sync_images"].(bool); ok {
p.SyncImages = v
}
switch v := vals["max_image_mb"].(type) {
case float64:
if v > 0 && !math.IsNaN(v) && !math.IsInf(v, 0) {
mb := int(math.Round(v))
if mb < 1 {
mb = 1
}
if mb > 16 {
mb = 16
}
p.MaxImageBytes = mb << 20
}
case int:
if v > 0 {
if v > 16 {
v = 16
}
p.MaxImageBytes = v << 20
}
}
if v, ok := vals["sync_files"].(bool); ok {
p.SyncFiles = v
}
var fileMB float64
switch v := vals["max_file_mb"].(type) {
case int:
fileMB = float64(v)
case float64:
fileMB = v
}
if fileMB > 0 && !math.IsInf(fileMB, 0) {
p.MaxFileBytes = int(math.Round(min(max(fileMB, guesttools.MinClipboardMaxFileMB), guesttools.MaxClipboardMaxFileMB))) << 20
}
return p
}
// PluginAssetHandler returns the HTTP handler mounted on Wails AssetServer for
// `/plugin-assets/<runToken>/<pluginID>/<relPath>` (§7.3).
func (a *App) PluginAssetHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.HasPrefix(r.URL.Path, "/plugin-assets/") {
http.NotFound(w, r)
return
}
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil || mgr.Assets() == nil {
http.NotFound(w, r)
return
}
mgr.Assets().ServeHTTP(w, r)
})
}
func (a *App) emitPluginLogLine(vmName, source, line string) {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr != nil {
mgr.Registry().Hooks().EmitLogLine(vmName, source, line)
}
}
func (a *App) collectPluginDiagnostics(ctx context.Context, vmName string) []plugin.DiagnosticsEntry {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return nil
}
return mgr.Registry().CollectDiagnostics(ctx, vmName, host.RedactText)
}
func buildHostFacts(rep host.Report, rtCaps []string) map[string]any {
gpuKind := "unknown"
if rep.RecommendedGPU != nil {
gpuKind = string(rep.RecommendedGPU.Kind)
}
facts := map[string]any{
"host.os": rep.OS,
"host.arch": rep.Arch,
"host.whpx": string(rep.WHPX),
"host.whpx_irqchip": rep.WHPXCaps.KernelIrqchipAvailable,
"host.whpx_nested_virt": rep.WHPXCaps.NestedVirtProperty,
"host.needs_cold_reboot": rep.NeedsColdRebootWorkaround,
"host.gpu_kind": gpuKind,
"runtime.capabilities": rtCaps,
}
if rep.MemorySpec != nil && rep.MemorySpec.SpeedMHz > 0 {
facts["host.memory_speed_mhz"] = rep.MemorySpec.SpeedMHz
if rep.MemorySpec.MemoryType > 0 {
facts["host.memory_type"] = rep.MemorySpec.MemoryType
}
}
return facts
}
// --- Wails-bound Plugin & Driver APIs (§10) ---
func (a *App) ListPlugins() []plugin.PluginInfo {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return nil
}
cfg := a.runtimeConfig()
reg := mgr.Registry()
infos := mgr.LocalizePluginInfos(reg.ListVisible())
active, _ := rt.ResolveActive(&cfg)
if active == nil {
return infos
}
caps := active.Manifest.EffectiveCapabilities()
locale := i18n.EffectiveLocale(cfg.Locale)
for i := range infos {
info := &infos[i]
if info.State != plugin.StateActive && info.State != plugin.StateDegraded {
continue
}
manifest, ok := reg.ManifestOf(info.ID)
if !ok {
continue
}
manifest.Settings = info.Settings
if settings := plugin.RuntimeUnavailableSettings(manifest, caps, locale); len(settings) > 0 {
info.RuntimeWarning = i18n.M(locale, "plugin.runtime_settings_skipped", i18n.Vars{
"settings": strings.Join(settings, ", "),
})
}
}
return infos
}
func (a *App) InstallPluginArchive(archivePath string) (*plugin.PluginInfo, error) {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return nil, errors.New("plugin manager not initialized")
}
info, err := mgr.InstallLocalArchive(context.Background(), archivePath, plugin.PackageInstallOptions{})
if err == nil {
a.emitStateChanged()
}
return info, err
}
func (a *App) LinkPluginDev(dir string) (*plugin.PluginInfo, error) {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return nil, errors.New("plugin manager not initialized")
}
info, err := mgr.LinkDev(context.Background(), dir)
if err == nil {
a.emitStateChanged()
}
return info, err
}
func (a *App) EnablePlugin(id string, approveHighRisk bool) error {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return errors.New("plugin manager not initialized")
}
return mgr.Enable(context.Background(), id, approveHighRisk)
}
func (a *App) DisablePlugin(id string) error {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return errors.New("plugin manager not initialized")
}
if err := mgr.Disable(context.Background(), id); err != nil {
return err
}
a.revokePluginFiles(id)
cancelPluginTasks(id)
return nil
}
func (a *App) RemovePlugin(id string, purgeData bool) error {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return errors.New("plugin manager not initialized")
}
if err := mgr.Remove(context.Background(), id, purgeData); err != nil {
return err
}
a.revokePluginFiles(id)
cancelPluginTasks(id)
return nil
}
func (a *App) GetPluginSettings(pluginID, vmKey string) map[string]any {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return map[string]any{}
}
return mgr.GetSettings(pluginID, vmKey, true)
}
func (a *App) SetPluginSettings(pluginID, vmKey string, values map[string]any) error {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return errors.New("plugin manager not initialized")
}
return mgr.SetSettings(pluginID, vmKey, values)
}
func (a *App) GetVMPluginSettings(vmKey string) map[string]map[string]any {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return map[string]map[string]any{}
}
return mgr.GetAllVMSettings(vmKey)
}
func (a *App) GetPluginUIContributions() PluginUIContributions {
a.mu.Lock()
mgr := a.pluginMgr
kr := a.runtimeKinds
dr := a.driverRouter
a.mu.Unlock()
if mgr == nil {
return PluginUIContributions{}
}
reg := mgr.Registry()
uiLocales, _ := mgr.ResolvedLocalePacks()
out := PluginUIContributions{
SafeMode: mgr.SafeMode(),
CrashDetected: mgr.CrashDetected(),
Menus: mgr.LocalizeMenus(reg.Menus("")),
VMCards: mgr.LocalizeVMCards(reg.VMCards()),
SettingsPages: mgr.LocalizeSettingsPages(reg.SettingsPages()),
StatusItems: mgr.LocalizeStatusItems(reg.StatusItems()),
Panels: mgr.LocalizePanels(reg.Panels("")),
Views: mgr.LocalizeViews(reg.Views("")),
ImageSources: mgr.LocalizeImageSources(reg.ImageSources()),
VMTemplates: reg.VMTemplates(),
Themes: reg.Themes(),
Locales: uiLocales,
RuntimeSources: reg.RuntimeSources(),
AssetToken: mgr.Assets().Token(),
}
if kr != nil {
out.RuntimeKinds = kr.List()
}
if dr != nil {
out.Drivers = dr.Summaries()
}
return out
}
func (a *App) InvokePluginCommand(pluginID, commandID string, args map[string]any) (any, error) {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return nil, errors.New("plugin manager not initialized")
}
return mgr.Registry().InvokeCommand(context.Background(), pluginID, commandID, args)
}
func (a *App) GetActiveTheme() plugin.ActiveThemePayload {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return plugin.ActiveThemePayload{ThemeID: builtin.IDThemeDefault}
}
return mgr.ActiveThemePayload()
}
func (a *App) SetActiveTheme(themeID, schemeID string) error {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return errors.New("plugin manager not initialized")
}
err := mgr.SetActiveTheme(themeID, schemeID)
if err == nil {
a.emitStateChanged()
}
return err
}
func (a *App) SaveCustomThemeScheme(scheme plugin.CustomThemeScheme) error {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return errors.New("plugin manager not initialized")
}
return mgr.SaveCustomThemeScheme(scheme)
}
func (a *App) DeleteCustomThemeScheme(schemeID string) error {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return errors.New("plugin manager not initialized")
}
return mgr.DeleteCustomThemeScheme(schemeID)
}
func (a *App) ListDrivers() []driver.DriverSummary {
a.mu.Lock()
dr := a.driverRouter
a.mu.Unlock()
if dr == nil {
return nil
}
return dr.Summaries()
}
func (a *App) CreateVMWithDriver(req driver.CreateRequest) error {
if err := a.requireWritableDataRoot(); err != nil {
return err
}
a.mu.Lock()
dr := a.driverRouter
mgr := a.pluginMgr
a.mu.Unlock()
if dr == nil {
return errors.New("driver router not initialized")
}
drv, err := dr.DriverByID(req.DriverID)
if err != nil {
return err
}
ctx := context.Background()
if mgr != nil {
res := mgr.Registry().Hooks().DispatchBeforeCreate(ctx, plugin.BeforeCreatePayload{
VMName: req.Name,
DriverID: drv.ID(),
Options: req.Options,
})
if len(res.Errors) > 0 {
return errors.New(res.Errors[0])
}
if len(res.Patches) > 0 {
if req.Options == nil {
req.Options = map[string]any{}
}
for k, v := range res.Patches {
if _, exists := req.Options[k]; !exists {
req.Options[k] = v
}
}
}
}
if issues := drv.ValidateCreate(ctx, req); len(issues) > 0 {
return errors.New(issues[0].Message)
}
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(req.DriverID, req.Name, line) })
if err := drv.Create(ctx, req, w, w); err != nil {
return err
}
if mgr != nil {
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterCreate, plugin.VMEventPayload{
VMName: req.Name,
DriverID: drv.ID(),
})
}
a.wakePoll()
a.emitStateChanged()
return nil
}
// InspectPluginArchive runs the unified static security scanner on a local .zip
// package before installing it so the UI can display hard blockers, capabilities,
// and L3 native execution notices.
func (a *App) InspectPluginArchive(archivePath string) (plugin.ScanReport, error) {
a.mu.Lock()
mgr := a.pluginMgr
dataRoot := ""
if a.cfg != nil {
dataRoot = a.cfg.DataRoot
}
a.mu.Unlock()
tmpDir := plugin.NewPluginsLayout(dataRoot).TmpDir()
if mgr != nil {
tmpDir = mgr.Layout().TmpDir()
}
return plugin.ScanArchive(archivePath, tmpDir, version.Version, plugin.ScanOptions{
Keyring: plugin.DefaultKeyring(),
})
}
// ScanInstalledPlugin runs the unified static risk report against an installed
// or dev-linked plugin directory.
func (a *App) ScanInstalledPlugin(pluginID string) (plugin.ScanReport, error) {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return plugin.ScanReport{}, errors.New("plugin manager not initialized")
}
info, ok := mgr.Registry().Info(pluginID)
if !ok {
return plugin.ScanReport{}, fmt.Errorf("plugin %q not found", pluginID)
}
if info.InstallDir == "" {
return plugin.ScanReport{
PluginID: info.ID,
Version: info.Version,
Name: info.Name,
Tier: info.Tier,
Trust: info.Trust,
Publisher: info.Publisher,
License: info.License,
Passed: true,
Headline: plugin.LocalizedText{
ZhCN: "内置插件状态正常",
EnUS: "Built-in plugin is healthy",
},
}, nil
}
rep := plugin.ScanDirectory(info.InstallDir, version.Version, plugin.ScanOptions{
Keyring: plugin.DefaultKeyring(),
})
if info.Trust == plugin.TrustDev {
rep.Trust = plugin.TrustDev
}
return rep, nil
}
// BrowsePluginMarket lazily queries the remote/cached/fallback plugin market
// index (never called at app startup, §8.1, §9).
func (a *App) BrowsePluginMarket(query, kind string, includeAlpha, forceRefresh bool) plugin.MarketBrowseResult {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
var installed []plugin.PluginInfo
if mgr != nil {
installed = mgr.Registry().List()
}
return a.getPluginMarket().Browse(context.Background(), installed, plugin.MarketBrowseOptions{
Query: query,
Kind: kind,
IncludeAlpha: includeAlpha,
ForceRefresh: forceRefresh,
})
}
// PeekPluginMarket returns the market from memory, disk cache or the embedded
// fallback with no network I/O, so the page can paint before
// BrowsePluginMarket revalidates.
func (a *App) PeekPluginMarket(query, kind string) plugin.MarketBrowseResult {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
var installed []plugin.PluginInfo
if mgr != nil {
installed = mgr.Registry().List()
}
return a.getPluginMarket().Peek(installed, plugin.MarketBrowseOptions{Query: query, Kind: kind, IncludeAlpha: true})
}
// SuggestLanguagePack looks up the market once for a language pack matching
// the OS language, for the first-run screen to offer. It is the one market
// request made without the user opening the market (§8.1), and returns nil
// when a built-in language already covers the OS language, the market is
// unreachable or turned off, or nothing matches.
func (a *App) SuggestLanguagePack() *plugin.MarketCatalogItem {
tag := i18n.DetectOSLocaleTag()
if builtinCoversLocale(string(tag)) {
return nil
}
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
var installed []plugin.PluginInfo
if mgr != nil {
installed = mgr.Registry().List()
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
return a.getPluginMarket().SuggestLocalePack(ctx, installed, string(tag))
}
// builtinCoversLocale reports whether the built-in zh-CN or en-US catalogs
// already serve tag well enough that a language pack adds nothing.
func builtinCoversLocale(tag string) bool {
s := strings.ToLower(strings.TrimSpace(tag))
if s == "" || s == "en" || strings.HasPrefix(s, "en-") {
return true
}
switch s {
case "zh", "zh-cn", "zh-sg", "zh-hans", "zh-hans-cn", "zh-hans-sg":
return true
}
return false
}
// MarketInstallProgress is emitted as "reims:plugin-install" while
// InstallMarketPlugin runs. Total is 0 when the size is unknown.
type MarketInstallProgress struct {
ID string `json:"id"`
Phase string `json:"phase"` // "download" | "install"
Done int64 `json:"done"`
Total int64 `json:"total"`
}
// InstallMarketPlugin downloads, verifies SHA-256, static-scans, and installs
// a plugin from the market index.
func (a *App) InstallMarketPlugin(pluginID string, includeAlpha bool) (*plugin.PluginInfo, error) {
return a.installMarketPlugin(pluginID, "", includeAlpha)
}
// InstallMarketPluginVersion downloads, verifies SHA-256, static-scans, and
// installs a specific version of a plugin from the market index.
func (a *App) InstallMarketPluginVersion(pluginID, ver string) (*plugin.PluginInfo, error) {
return a.installMarketPlugin(pluginID, ver, true)
}
func (a *App) installMarketPlugin(pluginID, ver string, includeAlpha bool) (*plugin.PluginInfo, error) {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return nil, errors.New("plugin manager not initialized")
}
var (
progMu sync.Mutex
phase = plugin.MarketPhaseDownload
lastEmit time.Time
)
emit := func(p MarketInstallProgress) {
a.emit("reims:plugin-install", p)
}
info, err := a.getPluginMarket().InstallFromMarket(context.Background(), mgr, pluginID, plugin.MarketInstallOptions{
Version: ver,
IncludeAlpha: includeAlpha,
OnPhase: func(ph string) {
progMu.Lock()
phase = ph
progMu.Unlock()
emit(MarketInstallProgress{ID: pluginID, Phase: ph})
},
OnProgress: func(done, total int64) {
progMu.Lock()
// ~12 updates a second is smooth enough; always send the last one.
now := time.Now()
if now.Sub(lastEmit) < 80*time.Millisecond && (total <= 0 || done < total) {
progMu.Unlock()
return
}
lastEmit = now
ph := phase
progMu.Unlock()
emit(MarketInstallProgress{ID: pluginID, Phase: ph, Done: done, Total: total})
},
})
if err == nil {
a.emitStateChanged()
}
return info, err
}
type panelConfirmRequest struct {
Title string `json:"title,omitempty"`
Message string `json:"message"`
ConfirmLabel string `json:"confirmLabel,omitempty"`
CancelLabel string `json:"cancelLabel,omitempty"`
Danger bool `json:"danger,omitempty"`
}
type panelCopyRequest struct {
Text string `json:"text"`
}
func panelTextParam(params map[string]any, key string, required bool, maxBytes int, multiline bool) (string, error) {
raw, ok := params[key]
if !ok || raw == nil {
if required {
return "", fmt.Errorf("%s is required", key)
}
return "", nil
}
value, ok := raw.(string)
if !ok || !utf8.ValidString(value) || len(value) > maxBytes || (required && strings.TrimSpace(value) == "") {
return "", fmt.Errorf("invalid %s", key)
}
for _, r := range value {
if !unicode.IsControl(r) {
continue
}
if multiline && (r == '\n' || r == '\r' || r == '\t') {
continue
}
return "", fmt.Errorf("invalid control character in %s", key)
}
return value, nil
}
// PanelBridgeCall handles permission-checked, rate-limited, redacted Host API
// requests from sandboxed L4 iframe panels (§7.3).
func (a *App) PanelBridgeCall(pluginID, method string, params map[string]any) (any, error) {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return nil, errors.New("plugin manager not initialized")
}
hasPanel := false
for _, p := range mgr.Registry().Panels("") {
if p.PluginID == pluginID {
hasPanel = true
break
}
}
if !hasPanel {
for _, view := range mgr.Registry().Views("") {
if view.PluginID == pluginID {
hasPanel = true
break
}
}
}
if !hasPanel {
return nil, fmt.Errorf("plugin %q has no active panel or view", pluginID)
}
method, spec, known := plugin.ResolveBridgeMethod(method)
if !known {
return nil, fmt.Errorf("panel bridge method %q is not allowed", method)
}
if spec.Status != plugin.ContractStable {
return nil, fmt.Errorf("panel bridge method %q is experimental and not available in bridgeApi %s", method, plugin.BridgeAPIVersion)
}
switch method {
case "hello":
if err := mgr.Broker().AllowRate(pluginID); err != nil {
return nil, err
}
eff := mgr.CurrentLocale()
return map[string]any{
"bridgeApi": plugin.BridgeAPIVersion,
"uiApi": plugin.UIAPIVersion,
"features": plugin.HostFeatures(),
"locale": string(eff),
"dir": i18n.DirOf(eff),
}, nil
case "i18n.getBundle":
if err := mgr.Broker().AllowRate(pluginID); err != nil {
return nil, err
}
eff := mgr.CurrentLocale()
msgs := mgr.PluginL10nBundle(pluginID, eff)
if msgs == nil {
msgs = map[string]string{}
}
return map[string]any{
"locale": string(eff),
"dir": i18n.DirOf(eff),
"messages": msgs,
}, nil
case "vm.list":
if err := mgr.Broker().Authorize(pluginID, "vm:read"); err != nil {
return nil, err
}
vms, err := a.polledVMs(context.Background())
if err != nil {
return nil, err
}
out := make([]map[string]any, 0, len(vms))
for _, v := range vms {
out = append(out, map[string]any{
"name": v.Name,
"state": v.State,
})
}
return out, nil
case "ui.notify":
title, _ := params["title"].(string)
body, _ := params["body"].(string)
if err := mgr.Broker().Notify(pluginID, title, body); err != nil {
return nil, err
}
return map[string]any{"ok": true}, nil
case "command.invoke":
if err := mgr.Broker().Authorize(pluginID, "ui:slot"); err != nil {
return nil, err
}
cmdID, _ := params["command"].(string)
cmdArgs, _ := params["args"].(map[string]any)
mgr.Broker().Audit(pluginID, "PANEL_CMD", cmdID)
return mgr.Registry().InvokeCommand(context.Background(), pluginID, cmdID, cmdArgs)
case "ui.confirm":
if err := mgr.Broker().Authorize(pluginID, spec.Permission); err != nil {
return nil, err
}
req := panelConfirmRequest{}
var err error
if req.Title, err = panelTextParam(params, "title", false, 200, false); err != nil {
return nil, err
}
if req.Message, err = panelTextParam(params, "message", true, 4000, true); err != nil {
return nil, err
}
if req.ConfirmLabel, err = panelTextParam(params, "confirmLabel", false, 80, false); err != nil {
return nil, err
}
if req.CancelLabel, err = panelTextParam(params, "cancelLabel", false, 80, false); err != nil {
return nil, err
}
if rawDanger, ok := params["danger"]; ok && rawDanger != nil {
danger, ok := rawDanger.(bool)
if !ok {
return nil, errors.New("invalid danger")
}
req.Danger = danger
}
return req, nil
case "ui.copy":
if err := mgr.Broker().Authorize(pluginID, spec.Permission); err != nil {
return nil, err
}
if _, ok := params["text"]; !ok {
return nil, errors.New("text is required")
}
text, err := panelTextParam(params, "text", false, 1<<20, true)
if err != nil {
return nil, err
}
return panelCopyRequest{Text: text}, nil
case "ui.openExternal":
if err := mgr.Broker().Authorize(pluginID, spec.Permission); err != nil {
return nil, err
}
rawURL, err := panelTextParam(params, "url", true, 2048, false)
if err != nil {
return nil, err
}
if err := a.OpenURL(rawURL); err != nil {
return nil, err
}
mgr.Broker().Audit(pluginID, "PANEL_UI", method)
return map[string]any{"ok": true}, nil
case "storage.get", "storage.set", "storage.list", "storage.delete":
if err := mgr.Broker().Authorize(pluginID, spec.Permission); err != nil {
return nil, err
}
if method == "storage.list" {
keys, err := mgr.ViewStorageList(pluginID)
if err != nil {
return nil, err
}
return map[string]any{"keys": keys}, nil
}
key, err := panelTextParam(params, "key", true, 128, false)
if err != nil {
return nil, err
}
switch method {
case "storage.get":
value, found, err := mgr.ViewStorageGet(pluginID, key)
if err != nil {
return nil, err
}
return map[string]any{"value": value, "found": found}, nil
case "storage.set":
if err := mgr.ViewStorageSet(pluginID, key, params["value"]); err != nil {
return nil, err
}
return map[string]any{"ok": true}, nil
case "storage.delete":
deleted, err := mgr.ViewStorageDelete(pluginID, key)
if err != nil {
return nil, err
}
return map[string]any{"deleted": deleted}, nil
}
case "ui.showForm", "ui.setTitle", "ui.setBadge", "ui.openView", "ui.close", "ui.navigate":
return panelUICall(mgr, pluginID, method, params)
case "vm.get":
return a.panelVMGet(mgr, pluginID, params)
case "settings.get", "settings.set":
return a.panelSettingsCall(mgr, pluginID, method, params)
case "file.pick", "file.save", "file.read", "file.write":
return a.panelFileCall(mgr, pluginID, method, params)
case "task.start", "task.update", "task.finish":
return a.panelTaskCall(mgr, pluginID, method, params)
case "net.fetch":
return panelNetFetch(mgr, pluginID, params)
case "events.subscribe", "events.unsubscribe":
return panelEventsCall(mgr, pluginID, method, params)
default:
return nil, fmt.Errorf("panel bridge method %q is not allowed", method)
}
return nil, fmt.Errorf("panel bridge method %q is not allowed", method)
}