Files
Reims-Go/internal/app/plugins_flow.go
T
球球 7fd1947bef feat(plugin,host,macos,ui): 实现 Agent 受控接管、受保护阶段确认、离线预配置与自动装机基础 (#103, #105, #129) (#134)
* feat(plugin,host,ui): add agent session takeover, protected-phase confirmation, and autoinstall host foundation

* feat(macos,ui,cli): add offline REIMSPROV first-boot provisioning to skip Setup Assistant (#129)

Builds a per-VM read-only REIMSPROV disk image containing a pure-Go XAR Distribution flat package (provision.pkg) and an offline Recovery fallback script (provision-offline.sh). Passwords are hashed in memory to Apple SALTED-SHA512-PBKDF2 bplist00 ShadowHashData (never persisted in plaintext, no auto-login or NOPASSWD sudo). Uses native OpenDirectory.framework (JXA NSData) + dseditgroup under SIP-enabled live bootinstalld and dslocal plist + PlistBuddy under offline Recovery, skips Setup Assistant and Keyboard Setup Assistant, pre-stages Guest Tools, integrates with CreateWizard / VMPage / vm provision CLI / StartAutoInstall, and zero-wipes on finish_install, normal cold start, or DeleteVM.

* feat(autoinstall,host,ui): add input-locked session shield, recovery-only mode, and restart grace cap

Adds the real-machine end-to-end verified baseline for automatic macOS installation: (1) takeover_policy 'lock' with transparent Win32 VM client-area input shield, low-level key/mouse lock preserving host escape shortcuts (Alt+Tab/Alt+Esc/Win), HUD & UI Pause/Resume controls, and write guards while paused; (2) decoupled recovery_only vs full (REIMSPROV) modes in StartAutoInstall, CreateWizard, and VMAutoInstallPanel; (3) graceful_timeout_sec cap (default 10s) on automated built-in macOS host/vm.restart so Setup Assistant/Login Window restarts do not stall 90s on ACPI; (4) additional modifier aliases in console manager and agent-session/telemetry cleanup on VM deletion.

* feat(autoinstall,overlay,plugin): add built-in macOS auto-install plugin, dynamic island overlay, and review fixes

* fix(app,host,macos,ui): address PR #134 automated review findings

- Frontend & i18n:
  - Fix UTF-8/GBK mojibake in VMPage.tsx.
  - Emit reims:confirm-resolved on timeout/cancel/resolve so frontend modals auto-close and surface errors cleanly; stop submitCreate from continuing after PrepareVMProvision failure.
  - Gate AutoInstallPanel RapidOCR download button on preflight can_download_ocr when pinned default assets are unavailable.
- App / Sessions / Confirm / Lifecycle:
  - Add 30s denial cooldown for protected-phase confirmation prompts and revoke (pluginID, vmKey) grants on non-completed session exits.
  - Fix sessionOverlay / activeAgentSessions data race, remove duplicate permission-denied invocation, guard against clobbering other sessions or completed overlays, and unify VM key normalization.
  - Grant protected-phase confirmation and attach lock-mode session + watcher when resuming auto-install without an active session.
  - Unify FinishInstall and host/vm.finishInstall result handling and persist .reims-go-provision-ready across restarts.
  - Preserve non-timeout stop errors in restartMacOSVMLocked instead of force-killing.
- Host Takeover Hooks:
  - Require both keyboard and mouse WH_*_LL hooks (rolling back partial installs), initialize thread message queue before ready, reset started state on error/exit for retry, and report hook failures.
- macOS Provisioning & Autoinstall Engine:
  - Track REIMSPROV staged/wipe-pending/ready lifecycle markers, exclude "restore" recovery marker from re-attaching REIMSPROV, fail explicitly on offline admin plist creation failure, and report wipe failures.
  - Serialize per-VM Start/Stop/Resume with stop generation tokens, guard ROI fast-path against maxDim overflow, switch hostclient early-event buffer to FIFO eviction, fix untyped nil Engine return, tighten negation & high-risk fuzzy matching, preserve ackedQemuErrors across RebootWindow resets, and re-orient/expire stale inherited running checkpoints.
  - Document verified Windows SDK IDL vtable slots for WinOCR (live-tested on Windows) and add regression tests across app, host, macosdriver, startprep, installer, and autoinstall packages.

* fix(app,cli,host,macos,ui): address PR #134 second automated review findings

- CLI & Desktop Control Channel:
  - Add __reims_host__ / autoinstall desktop control channel with data_root verification so CLI status, resume, and stop talk directly to the live desktop runner instead of splitting checkpoint state or launching doomed short-lived CLI runners.
  - Merge live runners with on-disk checkpoints when listing status without a VM argument.
- App Sessions, Confirmations, Downloads & Telemetry:
  - Scope single-VM not_authorized errors to the target VM in handleSessionBegin and resolveComputerUseVM so active sessions on other VMs are not aborted.
  - Exclude stopped and suspended VMs from hasUnboundAgentSession fast-polling.
  - Revoke protected-phase grants when a VM disappears from poll results.
  - Require manifest Secret:true validation before storing auto-install passwords and remove the unsafe default account_password fallback.
  - Reject userinfo URLs in allow_custom_mirror, gate custom-mirror exemption strictly on plugin.ErrNetOriginNotDeclared, and keep redirect SSRF checks enabled on loopback custom mirrors.
  - Preserve VM telemetry milestones across suspend-resume and Win10 cold-reboot restarts while still resetting on fresh cold boots.
  - Log a warning when Guest Tools bridge is unavailable while preparing REIMSPROV.
  - Clarify CallHostAPI authorization/audit contract and add regression test proving built-in plugins enforce catalog permissions and audit logging.
- Host Takeover & Guest Tools:
  - Track locked mouse button presses via a 5-button bitmask so ButtonUp events from drags started outside the VM window are never swallowed.
  - Align active-window-reporter.js permissions to 0o100755 across ToolsDiskFiles, ToolsProvisionFiles, and postinstall.
- macOS Provisioning & Autoinstall Engine (OCR / Vision / Rules / Runner):
  - Never delete an unwiped REIMSPROV image on OpenFile/Write/Sync failure; persist wipe-pending marker and return error for retry.
  - Harden live postinstall preference writes with chmod 600, plutil -lint, chown, and cfprefsd flush.
  - Rewrite Windows RapidOCR C ABI structs and result extraction to match RapidAI/RapidOcrOnnx@675e73fe4c include/OcrLiteCApi.h:27-70 and src/OcrLiteCApi.cpp:12-160 (5-arg OcrInit verified).
  - Inspect PE32/PE32+ IMAGE_DIRECTORY_ENTRY_IMPORT directly to require onnxruntime.dll only for dynamically linked RapidOcrOnnx.dll builds.
  - Validate cfg.VM and use collision-free SHA-256-suffixed checkpoint paths with read fallback; redact PII/paths/UUIDs/MACs/IPs/tokens in diagnostic summaries; snapshot checkpoints before releasing r.mu for serialized disk I/O.
  - Add contrast/border/focus-ring ok return to DetectInputFieldNearLabel, enforce mask-dots verification in fillAccountForm and login screens, refuse blind password typing on clock-only lock screens, confirm shell readiness before typing install.sh, and prefer isolated button lines over modal prose in FindHit.
- Frontend:
  - Require explicit Apple SLA confirmation in both recovery_only and full modes across AutoInstallPanel and CreateWizard, with unit tests in frontend/scripts/test-autoinstall.mjs.

* fix(app,cli,host,macos,ui): address PR #134 third automated review findings

Addresses all confirmed findings from Review #6204465334 (commit d516350)
with targeted regression tests and hardens verified COM vtable bindings:

- App & Session Lifecycle:
  - Track hostPaused separately in agentSession so plugin host/session.update
    (paused_for_user=false) cannot clear physical user takeover or explicit
    PauseAgentSession holds; only host ResumeAgentSession or timed takeover
    expiry clears them.
  - Give each auto-install session watcher a monotonic watchGen + cancelable
    child context so restarting/resuming auto-install on the same VM cancels
    any superseded watcher and prevents stale timeout or secret cleanup.
  - Bound fast 500ms unbound-PID discovery for running VMs to
    sessionDiscoverGraceWindow via unboundSince (refreshed on restart/rebind).
  - Keep non-blocking buffered confirm resolution send inside confirmMu for
    clear mutual exclusion with cancelPendingConfirmations.
  - Clear cold-reboot telemetry preserveNextBoot via defer on all early-return
    and StartVM-failure paths in watchColdReboot.
  - Rebuild REIMSPROV with current StartAutoInstall credentials (preserving
    install_guest_tools) whenever VM is stopped instead of reusing stale images.
- CLI & macOS Provisioning / StartPrep:
  - Refuse `vm provision --clear` and overwriting existing REIMSPROV while the
    VM is running or paused.
  - Guard live "/" root in postinstall against macOS Recovery/Installer
    (/System/Installation/CDIS), forbid "/" in provision-offline.sh, and scope
    chmod 644 strictly to com.apple.keyboardtype.plist.
  - Reject unknown -* options in REIMSHELP/install.sh (including after --erase).
  - Defer clearing the one-shot REIMSPROV staged marker until after
    setExtraArgs (startprep) and StartWithCompat (macosdriver) succeed.
  - Preserve pending RestartFrom guards in AdvancePostInstallHandoff when
    checkpoint is already at StepDesktop.
- Host Input & Session Overlay:
  - Filter injected keyboard events (LLKHF_INJECTED / LLKHF_LOWER_IL_INJECTED)
    in locked-input mode consistently with the mouse hook.
  - Clean up exited overlay entries in entry.run() and recreate dead entries on
    Manager.Upsert when CreateWindowExW fails or exits early.
  - Cache the static island base surface (shell + icons + DirectWrite text) and
    measured text metrics across breathing frames, raising timerBreathMs to 100ms.
  - Replace magic Direct2D/DirectWrite vtable indices with named d2d1.h /
    dwrite.h constants, check EndDraw HRESULT, and add a live Windows DirectWrite
    rendering smoke test.
- Autoinstall OCR, Rules, Watchdog & Runner:
  - Persist and verify a per-file SHA-256 manifest.json in <dataDir>/ocr/
    before loading RapidOcrOnnx.dll / onnxruntime.dll; reject duplicate
    whitelisted basenames in offline zip imports.
  - Signal WinOCREngine.Close() before acquiring e.mu and add bounded wait +
    channel wakeup in Recognize so Close() immediately cancels in-flight OCR.
  - Fall back to installed RapidOCR when WinOCR initialization fails in Open(),
    and distinguish needs_rapidocr_import from needs_rapidocr_download in Probe.
  - Pause instead of pressing Return when post-TypeSecret login screenshot fails.
  - Re-baseline ColdRebootCount in Watchdog.ResetRebootWindow / ResetAfterResume.
  - Tighten recovery.main specificity (drop bare "Disk Utility"), guard 4-5 char
    pure-ASCII needles from sliding-window fuzzy collisions, use Unicode word
    boundaries for short names (<4 runes) in RedactDiagnosticText, and honor
    rule verify.wait_change_ms with early exit on visual frame diff.

* fix(autoinstall): handle CJK short-name redaction, sh-3.2 prompt bound, and OCR re-import pruning
2026-12-06 15:46:39 +08:00

1398 lines
39 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"
"github.com/Nwflower/reims-go/internal/plugin/market"
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
var drvRouter *driver.Router
mgr, drvRouter, err := builtin.BootstrapKernel(builtin.KernelBootstrapOptions{
DataRoot: dataRoot,
DataRootFn: func() string {
a.mu.Lock()
defer a.mu.Unlock()
return a.cfg.DataRoot
},
SafeMode: safeMode,
LocaleFn: a.locale,
Logger: func(source, line string) {
a.emitLog(source, line)
},
HostHandlers: func(pluginID string) map[string]plugin.RPCRequestHandler {
a.mu.Lock()
current := a.pluginMgr
a.mu.Unlock()
if current == nil {
current = mgr
}
return a.hostAPISvc().Handlers(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)
},
VMInventories: guest.VMInventories(),
Callbacks: 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()
},
},
RegisterGuest: guest.RegisterForHost,
})
if err != nil {
a.emitLog("plugin", "Could not initialize plugin manager: "+err.Error())
return
}
kindReg := rt.NewKindRegistry()
// 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)
})
// 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.syncClipboardPolicies()
a.syncLocales()
a.stopAgentSessionsForInactivePlugins(mgr)
a.wakePoll()
a.emitStateChanged()
})
a.mu.Lock()
a.pluginMgr = mgr
a.driverRouter = drvRouter
a.vmStateTable = stateTable
a.lifecycleSvc = vmlifecycle.New(mgr.Registry(), drvRouter, a.startHookPayload)
a.runtimeKinds = kindReg
a.mu.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.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() *market.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 market.NewMarketClient(market.MarketClientOptions{HostVersion: version.Version})
}
if a.pluginMarket != nil {
return a.pluginMarket
}
dataRoot := ""
if a.cfg != nil {
dataRoot = a.cfg.DataRoot
}
a.pluginMarket = market.NewMarketClient(market.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
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) 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) normalizeVMKey(vmRef string) string {
vmRef = strings.TrimSpace(vmRef)
if vmRef == "" {
return ""
}
if vm, err := a.resolveComputerUseVMInfo(vmRef); err == nil {
return vm.Ref().Key()
}
if ref, ok := driver.ParseVMRef(vmRef); ok {
return ref.Key()
}
return vmKeyForDriver("", vmRef)
}
func (a *App) onPluginSettingsChanged(pluginID, vmName string) {
a.syncInputFilters()
if pluginID == builtin.IDClipboard {
a.syncClipboardPolicies()
}
if vmName != "" && pluginID != "" {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr != nil {
vmKey := a.normalizeVMKey(vmName)
if a.hasActiveAgentSessionOwnedBy(vmKey, pluginID) && !a.computerUseVMAccessEnabled(mgr, pluginID, vmKey) {
a.handlePluginPermissionDeniedForVM(mgr, pluginID, vmKey, "", "permission_denied")
}
}
}
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()
}
out.Drivers = desktopDriverSummaries(dr)
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()
return desktopDriverSummaries(dr)
}
func desktopDriverSummaries(router *driver.Router) []driver.DriverSummary {
list := router.Summaries()
if !guest.UsesAppleVirtualization() {
return list
}
for i := range list {
if list[i].ID == guest.AppleDriverID() {
list[i].Builtin = true
list[0], list[i] = list[i], list[0]
break
}
}
return list
}
func (a *App) nativeVirtualizationStatus() *host.AppleVirtualizationStatus {
if !guest.UsesAppleVirtualization() {
return nil
}
a.appleVZProbeOnce.Do(func() {
ctx, cancel := context.WithTimeout(a.baseCtx(), 5*time.Second)
defer cancel()
if err := guest.ProbeAppleVirtualization(ctx); err != nil {
a.appleVZProbe.Detail = host.RedactText(err.Error())
return
}
a.appleVZProbe.Ready = true
})
status := a.appleVZProbe
return &status
}
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(drv.ID(), req.Name, line) })
if drv.ID() == guest.AppleDriverID() {
if err := a.restoreAppleVM(dr, drv, req, w); err != nil {
return err
}
} else 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
}
func (a *App) restoreAppleVM(router *driver.Router, drv driver.Driver, req driver.CreateRequest, w vmstart.LineWriter) error {
ctx, cancel := context.WithCancel(a.baseCtx())
defer cancel()
a.selectionMu.Lock()
a.mu.Lock()
stillCurrent := a.driverRouter == router && !a.allowQuit && a.quitMode == ""
a.mu.Unlock()
if !stillCurrent {
a.selectionMu.Unlock()
return errors.New("virtual machine restore could not start because the workspace changed")
}
a.ensureTaskEmitter()
id := tasks.start("vm-restore", req.Name, driver.NewVMRef(drv.ID(), req.Name).Key(), cancel)
a.selectionMu.Unlock()
defer func() {
a.wakePoll()
a.emitStateChanged()
}()
err := drv.Create(ctx, req, w, w)
tasks.finish(id, req.Name, err)
return err
}
// 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) market.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, market.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) market.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, market.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() *market.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 = market.MarketPhaseDownload
lastEmit time.Time
)
emit := func(p MarketInstallProgress) {
a.emit("reims:plugin-install", p)
}
info, err := a.getPluginMarket().InstallFromMarket(context.Background(), mgr, pluginID, market.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)
}