package app import ( "context" "errors" "fmt" "io" "math" "net/http" "os" "path/filepath" "strings" "time" "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/driver" "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/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" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) // 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"` VMTemplates []plugin.VMTemplateContribution `json:"vm_templates,omitempty"` Themes []plugin.ThemeContribution `json:"themes,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() { a.mu.Lock() dataRoot := a.cfg.DataRoot safeMode := a.launch.SafeMode a.mu.Unlock() mgr, err := plugin.NewManager(plugin.ManagerOptions{ DataRoot: dataRoot, HostVersion: version.Version, SafeMode: safeMode, RedactFn: reims.RedactText, Logger: func(source, line string) { a.emitLog(source, line) }, SidecarDriverFactory: func(contrib plugin.GuestDriverContribution, sup *plugin.SidecarSupervisor) any { return driver.NewSidecarDriver(contrib, sup) }, OnSettingsChanged: func(pluginID, vmName string) { a.onPluginSettingsChanged(pluginID, vmName) }, }) 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() dir := filepath.Join(a.cfg.XDGDataDir(), "reims-ctl", "vms") a.mu.Unlock() return dir }) mgr.Registry().SetInUseChecker(func(pluginID string) (bool, string, error) { // Must not call Registry.Info/List here: both invoke this checker, // which recursed until the goroutine stack overflowed at startup. // Check all guest driver IDs declared by this plugin (even when disabled) plus pluginID itself. seen := map[string]bool{} candidates := append([]string{pluginID}, mgr.Registry().DeclaredDriverIDs(pluginID)...) for _, did := range candidates { if did == "" || seen[did] { continue } seen[did] = true if inUse, reason, err := drvRouter.CheckDriverInUse(context.Background(), did); err != nil || inUse { return inUse, reason, err } } return false, "", nil }) mgr.Broker().SetNotifier(func(pluginID, title, body string) { a.emitLog("plugin:"+pluginID, title+": "+body) }) cb := builtin.HostCallbacks{ GetConfig: func() config.Config { a.mu.Lock() cp := *a.cfg a.mu.Unlock() return cp }, 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() } }, ValidateDriveConfig: validatedDriveConfig, 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) }, VMSharedDir: func(vmName string) string { return a.vmSharedDir(vmName) }, GuestToolsImg: func(vmName string) string { return a.guestToolsImagePath(vmName) }, GetSetting: func(pluginID, vmName, key string) (any, bool) { v, ok := mgr.GetSettings(pluginID, vmName, false)[key] return v, ok }, } if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil { a.emitLog("plugin", "Builtin extension register error: "+err.Error()) } if err := builtin.MigrateRetired(mgr); err != nil { a.emitLog("plugin", "Could not migrate merged core plugin state: "+err.Error()) } if err := mgr.LoadExternal(); err != nil { a.emitLog("plugin", "External plugin load warning: "+err.Error()) } // Sync runtime kinds and input filters whenever registry state changes. mgr.Registry().OnChange(func() { a.syncRuntimeKinds(kindReg, mgr.Registry()) a.syncInputFilters() a.syncClipboardPolicies() if a.ctx != nil { wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) } }) a.mu.Lock() a.pluginMgr = mgr a.driverRouter = drvRouter a.runtimeKinds = kindReg a.mu.Unlock() mgr.Registry().Reconcile(context.Background()) mgr.MarkBootComplete() a.syncInputFilters() a.syncClipboardPolicies() } func (a *App) shutdownPlugins() { a.mu.Lock() mgr := a.pluginMgr a.pluginMgr = nil a.mu.Unlock() if mgr != nil { mgr.Close() } } 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, 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() mgr := a.pluginMgr a.mu.Unlock() if mgr == nil { return nil } raw, ok := mgr.Registry().LookupService(builtin.ServiceHostInput) if !ok { return nil } svc, _ := raw.(*host.InputService) return svc } func (a *App) syncInputTargets(targets []host.IMETarget) { if svc := a.getInputService(); svc != nil { svc.SetTargets(targets) } } 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 _, vmName := range vmNames { vals := mgr.GetSettings(flt.PluginID, vmName, 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 + ":" + vmName, 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)) for vmName, vmVals := range mgr.SavedVMSettingsForPlugin(builtin.IDClipboard) { pol := clipboardPolicyFromMap(vmVals) gt.SetVMClipboardPolicy(vmName, &pol) } } func (a *App) onPluginSettingsChanged(pluginID, vmName string) { a.syncInputFilters() if pluginID == builtin.IDClipboard { a.mu.Lock() mgr := a.pluginMgr gt := a.guestTools a.mu.Unlock() if mgr != nil && gt != nil { vals := mgr.GetSettings(builtin.IDClipboard, vmName, false) pol := clipboardPolicyFromMap(vals) if vmName == "" { gt.SetGlobalClipboardPolicy(pol) } else { gt.SetVMClipboardPolicy(vmName, &pol) } } } if a.ctx != nil { wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) } } 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 } } return p } // PluginAssetHandler returns the HTTP handler mounted on Wails AssetServer for // `/plugin-assets///` (§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, reims.RedactText) } func buildHostFacts(rep host.Report, rtCaps []string) map[string]any { gpuKind := "unknown" if rep.RecommendedGPU != nil { gpuKind = string(rep.RecommendedGPU.Kind) } return 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, } } // --- 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 } return mgr.Registry().List() } 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.ctx != nil { wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) } 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.ctx != nil { wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) } 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") } return mgr.Disable(context.Background(), id) } 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") } return mgr.Remove(context.Background(), id, purgeData) } func (a *App) GetPluginSettings(pluginID, vmName string) map[string]any { a.mu.Lock() mgr := a.pluginMgr a.mu.Unlock() if mgr == nil { return map[string]any{} } return mgr.GetSettings(pluginID, vmName, true) } func (a *App) SetPluginSettings(pluginID, vmName 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, vmName, values) } func (a *App) GetVMPluginSettings(vmName 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(vmName) } 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() out := PluginUIContributions{ SafeMode: mgr.SafeMode(), CrashDetected: mgr.CrashDetected(), Menus: reg.Menus(""), VMCards: reg.VMCards(), SettingsPages: reg.SettingsPages(), StatusItems: reg.StatusItems(), Panels: reg.Panels(""), VMTemplates: reg.VMTemplates(), Themes: reg.Themes(), 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.ctx != nil { wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) } 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) ListRuntimeKinds() []rt.KindSpec { a.mu.Lock() kr := a.runtimeKinds a.mu.Unlock() if kr == nil { return rt.NewKindRegistry().List() } return kr.List() } func (a *App) CreateVMWithDriver(req driver.CreateRequest) error { 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.emitLog(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() if a.ctx != nil { wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) } return nil } func (a *App) ReadPluginLog(pluginID string) (string, error) { a.mu.Lock() mgr := a.pluginMgr a.mu.Unlock() if mgr == nil { return "", nil } if pluginID == "" || strings.ContainsAny(pluginID, `/\`) || strings.Contains(pluginID, "..") { return "", errors.New("invalid plugin id") } if _, ok := mgr.Registry().Info(pluginID); !ok { return "", fmt.Errorf("plugin %q not found", pluginID) } logsDir := filepath.Clean(mgr.Layout().LogsDir()) logPath := filepath.Clean(mgr.Layout().LogPath(pluginID)) if !strings.HasPrefix(strings.ToLower(logPath), strings.ToLower(logsDir+string(os.PathSeparator))) { return "", errors.New("invalid plugin log path") } f, err := os.Open(logPath) if err != nil { if errors.Is(err, os.ErrNotExist) { return "", nil } return "", err } defer f.Close() const maxLogReadBytes = 2 << 20 if st, statErr := f.Stat(); statErr == nil && st.Size() > maxLogReadBytes { _, _ = f.Seek(st.Size()-maxLogReadBytes, io.SeekStart) } raw, err := io.ReadAll(io.LimitReader(f, maxLogReadBytes)) if err != nil { return "", err } return reims.RedactText(string(raw)), nil } func (a *App) DoctorPlugin(pluginID string) []plugin.DoctorFinding { a.mu.Lock() mgr := a.pluginMgr a.mu.Unlock() if mgr == nil { return nil } info, ok := mgr.Registry().Info(pluginID) if !ok { return []plugin.DoctorFinding{{ Severity: "error", Check: "lookup", Message: fmt.Sprintf("plugin %q not found", pluginID), }} } if info.InstallDir == "" { return []plugin.DoctorFinding{{ Severity: "ok", Check: "builtin", Message: fmt.Sprintf("%s@%s (%s)", info.ID, info.Version, info.State), }} } return plugin.DoctorDirectory(info.InstallDir, version.Version, nil) } // PanelBridgeCall handles permission-checked, rate-limited, redacted Host API // reads 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 { return nil, fmt.Errorf("plugin %q has no active panel", pluginID) } switch method { 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 "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) default: return nil, fmt.Errorf("panel bridge method %q is not allowed", method) } }