ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(wordpress): global plugin library for operator-owned plugins
Juan Denis6b35bb996db8
diff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.pyindex 176b1db3..6c700429 100644--- a/backend/app/api/wordpress.py+++ b/backend/app/api/wordpress.py@@ -1454,3 +1454,181 @@ def install_wp_cli():"""Install WP-CLI."""result = WordPressService.install_wp_cli()return jsonify(result), 200 if result['success'] else 400+++# ==================== GLOBAL PLUGIN LIBRARY ====================+# A global layer over the per-site plugin management above: operators register+# their own plugins (GitHub repo / local path) once, then install or update them+# across any number of managed WordPress sites from one place.++def _resolve_wp_site(site_or_app_id):+ """Resolve an ID to a WordPressSite (accepts a WordPressSite.id or Application.id)."""+ site = WordPressSite.query.get(site_or_app_id)+ if site:+ return site+ return WordPressSite.query.filter_by(application_id=site_or_app_id).first()+++@wordpress_bp.route('/plugins/library', methods=['GET'])+@jwt_required()+def list_library_plugins():+ """List all plugins in the global library."""+ from app.services.wordpress_plugin_library_service import WordPressPluginLibraryService+ return jsonify({'plugins': WordPressPluginLibraryService.list_plugins()}), 200+++@wordpress_bp.route('/plugins/library', methods=['POST'])+@jwt_required()+@admin_required+def add_library_plugin():+ """Register a new plugin in the library and sync it into the cache."""+ from app.services.wordpress_plugin_library_service import (+ WordPressPluginLibraryService, PluginLibraryError)+ data = request.get_json() or {}+ try:+ result = WordPressPluginLibraryService.add_plugin(data, user_id=get_jwt_identity())+ return jsonify(result), 201+ except PluginLibraryError as e:+ return jsonify({'error': str(e)}), 400+++@wordpress_bp.route('/plugins/library/<int:plugin_id>', methods=['GET'])+@jwt_required()+def get_library_plugin(plugin_id):+ """Library plugin detail, including per-site installations."""+ from app.services.wordpress_plugin_library_service import WordPressPluginLibraryService+ data = WordPressPluginLibraryService.get_plugin(plugin_id)+ if not data:+ return jsonify({'error': 'Plugin not found'}), 404+ return jsonify(data), 200+++@wordpress_bp.route('/plugins/library/<int:plugin_id>', methods=['PUT'])+@jwt_required()+@admin_required+def update_library_plugin(plugin_id):+ """Update a library plugin's source / branch / active state."""+ from app.services.wordpress_plugin_library_service import (+ WordPressPluginLibraryService, PluginLibraryError)+ data = request.get_json() or {}+ try:+ result = WordPressPluginLibraryService.update_plugin(+ plugin_id, data, user_id=get_jwt_identity())+ return jsonify(result), 200+ except PluginLibraryError as e:+ return jsonify({'error': str(e)}), 400+++@wordpress_bp.route('/plugins/library/<int:plugin_id>', methods=['DELETE'])+@jwt_required()+@admin_required+def delete_library_plugin(plugin_id):+ """Remove a plugin from the library (and delete its cache directory)."""+ from app.services.wordpress_plugin_library_service import (+ WordPressPluginLibraryService, PluginLibraryError)+ try:+ return jsonify(WordPressPluginLibraryService.delete_plugin(plugin_id)), 200+ except PluginLibraryError as e:+ return jsonify({'error': str(e)}), 400+++@wordpress_bp.route('/plugins/library/<int:plugin_id>/sync', methods=['POST'])+@jwt_required()+@admin_required+def sync_library_plugin(plugin_id):+ """Pull the latest source into the cache and re-parse the plugin header."""+ from app.services.wordpress_plugin_library_service import WordPressPluginLibraryService+ from app.models import WordPressCustomPlugin+ plugin = WordPressCustomPlugin.query.get(plugin_id)+ if not plugin:+ return jsonify({'error': 'Plugin not found'}), 404+ result = WordPressPluginLibraryService.sync_plugin(plugin, user_id=get_jwt_identity())+ return jsonify(result), 200 if result.get('success') else 400+++@wordpress_bp.route('/plugins/library/<int:plugin_id>/install', methods=['POST'])+@jwt_required()+@admin_required+def install_library_plugin(plugin_id):+ """Install (or update) a library plugin on a specific site."""+ from app.services.wordpress_plugin_library_service import (+ WordPressPluginLibraryService, PluginLibraryError)+ from app.models import WordPressCustomPlugin+ data = request.get_json() or {}+ site_id = data.get('site_id')+ if not site_id:+ return jsonify({'error': 'site_id is required'}), 400++ plugin = WordPressCustomPlugin.query.get(plugin_id)+ if not plugin:+ return jsonify({'error': 'Plugin not found'}), 404+ site = _resolve_wp_site(site_id)+ if not site:+ return jsonify({'error': 'Site not found'}), 404++ try:+ result = WordPressPluginLibraryService.install_on_site(+ plugin, site, activate=data.get('activate', True))+ return jsonify(result), 200+ except PluginLibraryError as e:+ return jsonify({'error': str(e)}), 400+++@wordpress_bp.route('/plugins/library/<int:plugin_id>/bulk-update', methods=['POST'])+@jwt_required()+@admin_required+def bulk_update_library_plugin(plugin_id):+ """Push the latest cached version to every site that has the plugin."""+ from app.services.wordpress_plugin_library_service import WordPressPluginLibraryService+ from app.models import WordPressCustomPlugin+ plugin = WordPressCustomPlugin.query.get(plugin_id)+ if not plugin:+ return jsonify({'error': 'Plugin not found'}), 404+ return jsonify(WordPressPluginLibraryService.bulk_update(plugin)), 200+++@wordpress_bp.route('/plugins/library/<int:plugin_id>/uninstall', methods=['POST'])+@jwt_required()+@admin_required+def uninstall_library_plugin(plugin_id):+ """Remove a library plugin from a specific site."""+ from app.services.wordpress_plugin_library_service import (+ WordPressPluginLibraryService, PluginLibraryError)+ from app.models import WordPressCustomPlugin+ data = request.get_json() or {}+ site_id = data.get('site_id')+ if not site_id:+ return jsonify({'error': 'site_id is required'}), 400+ plugin = WordPressCustomPlugin.query.get(plugin_id)+ if not plugin:+ return jsonify({'error': 'Plugin not found'}), 404+ site = _resolve_wp_site(site_id)+ if not site:+ return jsonify({'error': 'Site not found'}), 404+ try:+ return jsonify(WordPressPluginLibraryService.uninstall_from_site(plugin, site)), 200+ except PluginLibraryError as e:+ return jsonify({'error': str(e)}), 400+++@wordpress_bp.route('/sites/<int:app_id>/plugins/library-scan', methods=['POST'])+@jwt_required()+@admin_required+def scan_site_library_plugins(app_id):+ """Scan a site and tag which installed plugins are library-managed."""+ from app.services.wordpress_plugin_library_service import WordPressPluginLibraryService+ site = _resolve_wp_site(app_id)+ if not site:+ return jsonify({'error': 'Site not found'}), 404+ return jsonify(WordPressPluginLibraryService.scan_site(site)), 200+++@wordpress_bp.route('/sites/<int:app_id>/plugins/managed', methods=['GET'])+@jwt_required()+def get_site_managed_plugins(app_id):+ """Which of a site's installed plugins are library-managed (+ update state)."""+ from app.services.wordpress_plugin_library_service import WordPressPluginLibraryService+ site = _resolve_wp_site(app_id)+ if not site:+ return jsonify({'error': 'Site not found'}), 404+ return jsonify({'managed': WordPressPluginLibraryService.managed_for_site(site)}), 200diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex 6e69383b..6eb59917 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -21,6 +21,7 @@ from app.models.server import Server, ServerGroup, ServerMetrics, ServerCommand,from app.models.server_onboarding_log import ServerOnboardingLogfrom app.models.security_alert import SecurityAlertfrom app.models.wordpress_site import WordPressSite, DatabaseSnapshot, SyncJob, WordPressVulnerability+from app.models.wordpress_custom_plugin import WordPressCustomPlugin, WordPressSitePluginfrom app.models.environment_activity import EnvironmentActivityfrom app.models.promotion_job import PromotionJobfrom app.models.sanitization_profile import SanitizationProfile@@ -68,6 +69,7 @@ __all__ = ['MetricsHistory', 'Workflow', 'WorkflowExecution', 'WorkflowLog', 'GitWebhook', 'WebhookLog', 'GitDeployment','Server', 'ServerGroup', 'ServerMetrics', 'ServerCommand', 'AgentSession', 'AgentVersion', 'AgentRollout', 'ServerOnboardingLog', 'SecurityAlert','WordPressSite', 'DatabaseSnapshot', 'SyncJob', 'WordPressVulnerability',+ 'WordPressCustomPlugin', 'WordPressSitePlugin','EnvironmentActivity', 'PromotionJob', 'SanitizationProfile','EmailDomain', 'EmailAccount', 'EmailAlias', 'EmailForwardingRule', 'DNSProviderConfig', 'EmailRelayConfig','OAuthIdentity', 'SourceConnection', 'RegistrarConnection', 'ApiKey', 'ApiUsageLog', 'ApiUsageSummary',diff --git a/backend/app/models/wordpress_custom_plugin.py b/backend/app/models/wordpress_custom_plugin.pynew file mode 100644index 00000000..5e54f8e8--- /dev/null+++ b/backend/app/models/wordpress_custom_plugin.py@@ -0,0 +1,117 @@+"""WordPress Global Plugin Library models.++A thin global layer on top of the existing per-site WP-CLI plugin management:++- ``WordPressCustomPlugin`` — one row per operator-owned plugin registered in the+ global library (sourced from a GitHub repo or a local path).+- ``WordPressSitePlugin`` — one row per (library plugin, site) installation, so+ the panel knows which installed plugins are library-managed and whether a site+ is behind the library version.+"""++from datetime import datetime+from app import db+++class WordPressCustomPlugin(db.Model):+ """An operator-owned plugin in the global library."""++ __tablename__ = 'wordpress_custom_plugins'++ id = db.Column(db.Integer, primary_key=True)++ # Plugin folder slug, e.g. ``my-custom-plugin`` (the wp-content/plugins dir name)+ slug = db.Column(db.String(200), nullable=False, unique=True, index=True)++ # Parsed from the plugin header on sync+ name = db.Column(db.String(255))+ description = db.Column(db.Text)+ version = db.Column(db.String(50))+ author = db.Column(db.String(255))++ # Source+ source_type = db.Column(db.String(20), nullable=False, default='github') # github | local+ source_url = db.Column(db.String(500), nullable=False) # owner/repo, git URL, or local path+ branch = db.Column(db.String(100), default='main') # branch or tag to track+ # Optional source connection for authenticated (private) GitHub/GitLab clones+ connection_id = db.Column(db.Integer, nullable=True)++ is_active = db.Column(db.Boolean, default=True)++ last_synced_at = db.Column(db.DateTime)+ sync_error = db.Column(db.Text)++ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++ installations = db.relationship(+ 'WordPressSitePlugin',+ backref='plugin',+ lazy='dynamic',+ cascade='all, delete-orphan',+ )++ def install_count(self):+ return self.installations.filter(+ WordPressSitePlugin.status != 'not_installed'+ ).count()++ def to_dict(self, include_installations=False):+ result = {+ 'id': self.id,+ 'slug': self.slug,+ 'name': self.name,+ 'description': self.description,+ 'version': self.version,+ 'author': self.author,+ 'source_type': self.source_type,+ 'source_url': self.source_url,+ 'branch': self.branch,+ 'connection_id': self.connection_id,+ 'is_active': self.is_active,+ 'last_synced_at': self.last_synced_at.isoformat() if self.last_synced_at else None,+ 'sync_error': self.sync_error,+ 'install_count': self.install_count(),+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,+ }+ if include_installations:+ result['installations'] = [i.to_dict() for i in self.installations]+ return result++ def __repr__(self):+ return f'<WordPressCustomPlugin {self.id} {self.slug}>'+++class WordPressSitePlugin(db.Model):+ """A library plugin installed on a specific WordPress site."""++ __tablename__ = 'wordpress_site_plugins'+ __table_args__ = (+ db.UniqueConstraint('wordpress_site_id', 'custom_plugin_id',+ name='uq_site_custom_plugin'),+ )++ id = db.Column(db.Integer, primary_key=True)+ wordpress_site_id = db.Column(+ db.Integer, db.ForeignKey('wordpress_sites.id'), nullable=False, index=True)+ custom_plugin_id = db.Column(+ db.Integer, db.ForeignKey('wordpress_custom_plugins.id'), nullable=False, index=True)++ installed_version = db.Column(db.String(50))+ status = db.Column(db.String(20), default='not_installed') # active | inactive | not_installed | error++ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++ def to_dict(self):+ return {+ 'id': self.id,+ 'wordpress_site_id': self.wordpress_site_id,+ 'custom_plugin_id': self.custom_plugin_id,+ 'installed_version': self.installed_version,+ 'status': self.status,+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,+ }++ def __repr__(self):+ return f'<WordPressSitePlugin site={self.wordpress_site_id} plugin={self.custom_plugin_id} {self.status}>'diff --git a/backend/app/paths.py b/backend/app/paths.pyindex fd2f1635..6f6501c6 100644--- a/backend/app/paths.py+++ b/backend/app/paths.py@@ -14,6 +14,7 @@ DEPLOYMENTS_DIR = os.path.join(SERVERKIT_DIR, 'deployments')TEMPLATES_DIR = os.path.join(SERVERKIT_CONFIG_DIR, 'templates')BUILD_LOG_DIR = os.path.join(SERVERKIT_LOG_DIR, 'builds')BUILD_CACHE_DIR = os.path.join(SERVERKIT_CACHE_DIR, 'builds')+WP_PLUGIN_CACHE_DIR = os.path.join(SERVERKIT_CACHE_DIR, 'wp-plugins')DB_BACKUP_DIR = os.path.join(SERVERKIT_BACKUP_DIR, 'databases')WP_BACKUP_DIR = os.path.join(SERVERKIT_BACKUP_DIR, 'wordpress')SNAPSHOT_DIR = os.path.join(SERVERKIT_BACKUP_DIR, 'snapshots')diff --git a/backend/app/services/wordpress_plugin_library_service.py b/backend/app/services/wordpress_plugin_library_service.pynew file mode 100644index 00000000..0393a350--- /dev/null+++ b/backend/app/services/wordpress_plugin_library_service.py@@ -0,0 +1,508 @@+"""WordPress Global Plugin Library service.++A thin global layer on top of the existing per-site WP-CLI plugin management+(:class:`WordPressService`). It lets an operator register their own plugins from+a GitHub repo or a local path in a global library, cache a snapshot on disk, and+install/update those plugins across any number of managed WordPress sites.++Design notes+------------+- The cache lives at ``paths.WP_PLUGIN_CACHE_DIR/<slug>/`` and holds a working+ copy of the plugin folder (a git clone for GitHub sources, an rsync/copy+ snapshot for local sources — never a symlink, which is brittle across Docker+ volume mounts and deployments).+- Installing copies the cache dir into ``<site_root>/wp-content/plugins/<slug>``+ on the host. For Docker sites that host dir is bind-mounted into the container,+ so the copy is visible to WP-CLI, which auto-detects Docker via+ :meth:`WordPressService.wp_cli`.+"""++import os+import re+import shutil+import subprocess+from datetime import datetime+from typing import Dict, List, Optional++from app import db, paths+from app.models.wordpress_custom_plugin import WordPressCustomPlugin, WordPressSitePlugin+from app.models.wordpress_site import WordPressSite+from app.services.wordpress_service import WordPressService+from app.utils.system import run_privileged++# Slug rule: lowercase letters, digits, single dashes (a wp-content/plugins dir name).+_SLUG_RE = re.compile(r'^[a-z0-9]+(?:-[a-z0-9]+)*$')+++class PluginLibraryError(Exception):+ """Raised for validation / operation failures the API should surface as 400."""+++class WordPressPluginLibraryService:++ CACHE_DIR = paths.WP_PLUGIN_CACHE_DIR++ # ------------------------------------------------------------------+ # Helpers+ # ------------------------------------------------------------------+ @classmethod+ def cache_path(cls, slug: str) -> str:+ return os.path.join(cls.CACHE_DIR, slug)++ @staticmethod+ def slugify(value: str) -> str:+ value = (value or '').lower()+ value = re.sub(r'[^a-z0-9]+', '-', value).strip('-')+ return value++ @staticmethod+ def validate_slug(slug: str) -> str:+ slug = (slug or '').strip()+ if not slug or not _SLUG_RE.match(slug):+ raise PluginLibraryError(+ 'Invalid slug: use lowercase letters, digits and single dashes')+ return slug++ @classmethod+ def _github_clone_url(cls, plugin: WordPressCustomPlugin, user_id: Optional[int]) -> str:+ """Resolve the git URL to clone/pull for a GitHub source.++ Supports ``owner/repo``, a full ``https://…`` / ``git@…`` URL, and an+ authenticated URL via an OAuth source connection when ``connection_id``+ is set.+ """+ src = (plugin.source_url or '').strip()++ if plugin.connection_id and user_id is not None:+ # owner/repo is required to resolve an authenticated URL+ full_name = src+ if src.startswith('http'):+ # strip scheme/host to get owner/repo+ full_name = re.sub(r'^https?://[^/]+/', '', src)+ full_name = re.sub(r'\.git$', '', full_name)+ try:+ from app.services.source_connection_service import SourceConnectionService+ info = SourceConnectionService.get_authenticated_clone_url(+ user_id, plugin.connection_id, full_name)+ return info['clone_url']+ except Exception as e:+ raise PluginLibraryError(f'Could not resolve authenticated repo URL: {e}')++ if src.startswith('http') or src.startswith('git@'):+ return src+ # Bare owner/repo → public GitHub HTTPS URL+ if re.match(r'^[\w.-]+/[\w.-]+$', src):+ return f'https://github.com/{src}.git'+ raise PluginLibraryError('Invalid GitHub source: use owner/repo or a git URL')++ # ------------------------------------------------------------------+ # Header parsing+ # ------------------------------------------------------------------+ _HEADER_FIELDS = {+ 'name': 'Plugin Name',+ 'version': 'Version',+ 'description': 'Description',+ 'author': 'Author',+ }++ @classmethod+ def parse_plugin_header(cls, cache_path: str, slug: str) -> Dict[str, Optional[str]]:+ """Read the plugin header block from ``<slug>.php`` or the first PHP file.++ WordPress only reads the first 8 KB of the main file for headers, so we+ do the same rather than scanning entire files.+ """+ candidate = os.path.join(cache_path, f'{slug}.php')+ php_file = candidate if os.path.isfile(candidate) else None++ if php_file is None and os.path.isdir(cache_path):+ for entry in sorted(os.listdir(cache_path)):+ if entry.lower().endswith('.php'):+ php_file = os.path.join(cache_path, entry)+ break++ result: Dict[str, Optional[str]] = {k: None for k in cls._HEADER_FIELDS}+ if not php_file or not os.path.isfile(php_file):+ return result++ try:+ with open(php_file, 'r', encoding='utf-8', errors='replace') as fh:+ blob = fh.read(8192)+ except OSError:+ return result++ for key, label in cls._HEADER_FIELDS.items():+ # e.g. * Plugin Name: My Plugin+ m = re.search(rf'^[ \t/*#@]*{re.escape(label)}\s*:\s*(.+)$', blob, re.MULTILINE)+ if m:+ result[key] = m.group(1).strip()+ return result++ # ------------------------------------------------------------------+ # Sync (fetch source into cache)+ # ------------------------------------------------------------------+ @classmethod+ def sync_plugin(cls, plugin: WordPressCustomPlugin, user_id: Optional[int] = None) -> Dict:+ """Refresh the cached copy from source and re-parse the plugin header."""+ dest = cls.cache_path(plugin.slug)+ try:+ os.makedirs(cls.CACHE_DIR, exist_ok=True)++ if plugin.source_type == 'github':+ cls._sync_github(plugin, dest, user_id)+ elif plugin.source_type == 'local':+ cls._sync_local(plugin, dest)+ else:+ raise PluginLibraryError(f'Unknown source_type: {plugin.source_type}')++ header = cls.parse_plugin_header(dest, plugin.slug)+ if header.get('name'):+ plugin.name = header['name']+ if header.get('version'):+ plugin.version = header['version']+ if header.get('description'):+ plugin.description = header['description']+ if header.get('author'):+ plugin.author = header['author']++ plugin.last_synced_at = datetime.utcnow()+ plugin.sync_error = None+ db.session.commit()+ return {'success': True, 'plugin': plugin.to_dict()}+ except PluginLibraryError as e:+ plugin.sync_error = str(e)+ db.session.commit()+ return {'success': False, 'error': str(e)}+ except Exception as e:+ plugin.sync_error = str(e)+ db.session.commit()+ return {'success': False, 'error': str(e)}++ @classmethod+ def _sync_github(cls, plugin: WordPressCustomPlugin, dest: str, user_id: Optional[int]):+ url = cls._github_clone_url(plugin, user_id)+ branch = plugin.branch or 'main'+ git_dir = os.path.join(dest, '.git')++ if os.path.isdir(git_dir):+ # Existing clone → fetch + hard reset to the tracked branch/tag.+ subprocess.run(['git', '-C', dest, 'remote', 'set-url', 'origin', url],+ capture_output=True, text=True, timeout=30)+ fetch = subprocess.run(['git', '-C', dest, 'fetch', '--depth', '1', 'origin', branch],+ capture_output=True, text=True, timeout=180)+ if fetch.returncode != 0:+ raise PluginLibraryError(f'git fetch failed: {fetch.stderr.strip()}')+ reset = subprocess.run(['git', '-C', dest, 'reset', '--hard', 'FETCH_HEAD'],+ capture_output=True, text=True, timeout=60)+ if reset.returncode != 0:+ raise PluginLibraryError(f'git reset failed: {reset.stderr.strip()}')+ else:+ if os.path.exists(dest):+ shutil.rmtree(dest, ignore_errors=True)+ clone = subprocess.run(+ ['git', 'clone', '--depth', '1', '--branch', branch, url, dest],+ capture_output=True, text=True, timeout=300)+ if clone.returncode != 0:+ # Retry without --branch (repo default branch / tag mismatch)+ shutil.rmtree(dest, ignore_errors=True)+ clone = subprocess.run(['git', 'clone', '--depth', '1', url, dest],+ capture_output=True, text=True, timeout=300)+ if clone.returncode != 0:+ raise PluginLibraryError(f'git clone failed: {clone.stderr.strip()}')++ @classmethod+ def _sync_local(cls, plugin: WordPressCustomPlugin, dest: str):+ src = (plugin.source_url or '').strip()+ if not src or not os.path.isdir(src):+ raise PluginLibraryError(f'Local source path not found: {src}')+ # Snapshot copy (not a symlink) so the site never depends on the live path.+ if os.path.exists(dest):+ shutil.rmtree(dest, ignore_errors=True)+ shutil.copytree(src, dest)++ # ------------------------------------------------------------------+ # Library CRUD+ # ------------------------------------------------------------------+ @classmethod+ def add_plugin(cls, data: Dict, user_id: Optional[int] = None) -> Dict:+ source_type = (data.get('source_type') or 'github').strip()+ if source_type not in ('github', 'local'):+ raise PluginLibraryError('source_type must be "github" or "local"')++ source_url = (data.get('source_url') or '').strip()+ if not source_url:+ raise PluginLibraryError('source_url is required')++ # Derive a slug if not supplied: last path segment of the source.+ slug = (data.get('slug') or '').strip()+ if not slug:+ base = os.path.basename(source_url.rstrip('/')).replace('.git', '')+ slug = cls.slugify(base)+ slug = cls.validate_slug(slug)++ if WordPressCustomPlugin.query.filter_by(slug=slug).first():+ raise PluginLibraryError(f'A plugin with slug "{slug}" already exists')++ plugin = WordPressCustomPlugin(+ slug=slug,+ source_type=source_type,+ source_url=source_url,+ branch=(data.get('branch') or 'main').strip(),+ connection_id=data.get('connection_id'),+ name=data.get('name'),+ is_active=True,+ )+ db.session.add(plugin)+ db.session.commit()++ sync = cls.sync_plugin(plugin, user_id)+ result = plugin.to_dict()+ if not sync.get('success'):+ result['sync_error'] = sync.get('error')+ return result++ @classmethod+ def update_plugin(cls, plugin_id: int, data: Dict, user_id: Optional[int] = None) -> Dict:+ plugin = WordPressCustomPlugin.query.get(plugin_id)+ if not plugin:+ raise PluginLibraryError('Plugin not found')++ resync = False+ if 'source_url' in data and data['source_url']:+ plugin.source_url = data['source_url'].strip()+ resync = True+ if 'source_type' in data and data['source_type']:+ if data['source_type'] not in ('github', 'local'):+ raise PluginLibraryError('source_type must be "github" or "local"')+ plugin.source_type = data['source_type']+ resync = True+ if 'branch' in data and data['branch']:+ plugin.branch = data['branch'].strip()+ resync = True+ if 'connection_id' in data:+ plugin.connection_id = data['connection_id']+ resync = True+ if 'is_active' in data:+ plugin.is_active = bool(data['is_active'])+ db.session.commit()++ if resync:+ cls.sync_plugin(plugin, user_id)+ return plugin.to_dict()++ @classmethod+ def delete_plugin(cls, plugin_id: int) -> Dict:+ plugin = WordPressCustomPlugin.query.get(plugin_id)+ if not plugin:+ raise PluginLibraryError('Plugin not found')+ dest = cls.cache_path(plugin.slug)+ if os.path.isdir(dest):+ shutil.rmtree(dest, ignore_errors=True)+ db.session.delete(plugin)+ db.session.commit()+ return {'success': True}++ @classmethod+ def list_plugins(cls) -> List[Dict]:+ plugins = WordPressCustomPlugin.query.order_by(+ WordPressCustomPlugin.created_at.desc()).all()+ return [p.to_dict() for p in plugins]++ @classmethod+ def get_plugin(cls, plugin_id: int) -> Optional[Dict]:+ plugin = WordPressCustomPlugin.query.get(plugin_id)+ if not plugin:+ return None+ data = plugin.to_dict(include_installations=True)+ # Enrich installations with site names for the detail view.+ for inst in data['installations']:+ site = WordPressSite.query.get(inst['wordpress_site_id'])+ inst['site_name'] = (+ site.application.name if site and site.application else None)+ return data++ # ------------------------------------------------------------------+ # Per-site operations+ # ------------------------------------------------------------------+ @staticmethod+ def _site_root(site: WordPressSite) -> str:+ if not site.application or not site.application.root_path:+ raise PluginLibraryError('Site has no root path')+ return site.application.root_path++ @classmethod+ def _copy_into_site(cls, plugin: WordPressCustomPlugin, site: WordPressSite) -> str:+ """Copy the cached plugin folder into the site's wp-content/plugins."""+ cache = cls.cache_path(plugin.slug)+ if not os.path.isdir(cache):+ raise PluginLibraryError('Plugin is not synced yet — sync it first')++ target = os.path.join(cls._site_root(site), 'wp-content', 'plugins', plugin.slug)+ # Fresh copy: remove any prior version, then copy the cache (minus .git).+ run_privileged(['rm', '-rf', target])+ run_privileged(['mkdir', '-p', os.path.dirname(target)])+ run_privileged(['cp', '-a', cache, target])+ git_dir = os.path.join(target, '.git')+ if os.path.exists(git_dir):+ run_privileged(['rm', '-rf', git_dir])+ # WordPress files must be owned by the web user.+ run_privileged(['chown', '-R', 'www-data:www-data', target])+ return target++ @classmethod+ def _upsert_installation(cls, plugin: WordPressCustomPlugin, site: WordPressSite,+ status: str, version: Optional[str]) -> WordPressSitePlugin:+ row = WordPressSitePlugin.query.filter_by(+ wordpress_site_id=site.id, custom_plugin_id=plugin.id).first()+ if not row:+ row = WordPressSitePlugin(+ wordpress_site_id=site.id, custom_plugin_id=plugin.id)+ db.session.add(row)+ row.status = status+ row.installed_version = version+ db.session.commit()+ return row++ @classmethod+ def install_on_site(cls, plugin: WordPressCustomPlugin, site: WordPressSite,+ activate: bool = True) -> Dict:+ root = cls._site_root(site)+ cls._copy_into_site(plugin, site)++ status = 'inactive'+ if activate:+ act = WordPressService.wp_cli(root, ['plugin', 'activate', plugin.slug])+ status = 'active' if act.get('success') else 'inactive'++ cls._upsert_installation(plugin, site, status, plugin.version)+ return {'success': True, 'status': status, 'slug': plugin.slug}++ @classmethod+ def update_on_site(cls, plugin: WordPressCustomPlugin, site: WordPressSite) -> Dict:+ root = cls._site_root(site)+ row = WordPressSitePlugin.query.filter_by(+ wordpress_site_id=site.id, custom_plugin_id=plugin.id).first()+ was_active = bool(row and row.status == 'active')++ cls._copy_into_site(plugin, site)++ status = 'inactive'+ if was_active:+ act = WordPressService.wp_cli(root, ['plugin', 'activate', plugin.slug])+ status = 'active' if act.get('success') else 'inactive'++ cls._upsert_installation(plugin, site, status, plugin.version)+ return {'success': True, 'status': status, 'slug': plugin.slug}++ @classmethod+ def uninstall_from_site(cls, plugin: WordPressCustomPlugin, site: WordPressSite) -> Dict:+ root = cls._site_root(site)+ WordPressService.wp_cli(root, ['plugin', 'deactivate', plugin.slug])+ WordPressService.wp_cli(root, ['plugin', 'delete', plugin.slug])++ row = WordPressSitePlugin.query.filter_by(+ wordpress_site_id=site.id, custom_plugin_id=plugin.id).first()+ if row:+ db.session.delete(row)+ db.session.commit()+ return {'success': True}++ @classmethod+ def bulk_update(cls, plugin: WordPressCustomPlugin) -> Dict:+ """Push the latest cached version to every site that has it installed."""+ rows = WordPressSitePlugin.query.filter(+ WordPressSitePlugin.custom_plugin_id == plugin.id,+ WordPressSitePlugin.status != 'not_installed',+ ).all()++ results = []+ for row in rows:+ site = WordPressSite.query.get(row.wordpress_site_id)+ if not site:+ continue+ try:+ res = cls.update_on_site(plugin, site)+ results.append({'site_id': site.id, 'success': res.get('success', False)})+ except Exception as e:+ row.status = 'error'+ db.session.commit()+ results.append({'site_id': site.id, 'success': False, 'error': str(e)})++ updated = sum(1 for r in results if r.get('success'))+ return {'success': True, 'updated': updated, 'total': len(results), 'results': results}++ @classmethod+ def scan_site(cls, site: WordPressSite) -> Dict:+ """Compare WP-CLI ``plugin list`` against the library and upsert rows.++ Lets the per-site Plugins tab know which installed plugins are managed by+ the library (and whether they are behind the library version).+ """+ root = cls._site_root(site)+ installed = {p.get('name'): p for p in WordPressService.get_plugins(root)}++ managed = []+ for plugin in WordPressCustomPlugin.query.all():+ info = installed.get(plugin.slug)+ if info is None:+ # Not on the site — drop any stale row.+ row = WordPressSitePlugin.query.filter_by(+ wordpress_site_id=site.id, custom_plugin_id=plugin.id).first()+ if row:+ db.session.delete(row)+ db.session.commit()+ continue+ status = 'active' if info.get('status') == 'active' else 'inactive'+ cls._upsert_installation(plugin, site, status, info.get('version'))+ managed.append(plugin.slug)++ return {'success': True, 'managed_slugs': managed}++ @classmethod+ def managed_for_site(cls, site: WordPressSite) -> List[Dict]:+ """Return managed-plugin metadata for a site, keyed for the Plugins tab.++ Each entry: slug, installed_version, library_version, update_available.+ """+ rows = WordPressSitePlugin.query.filter(+ WordPressSitePlugin.wordpress_site_id == site.id,+ WordPressSitePlugin.status != 'not_installed',+ ).all()+ out = []+ for row in rows:+ plugin = WordPressCustomPlugin.query.get(row.custom_plugin_id)+ if not plugin:+ continue+ out.append({+ 'slug': plugin.slug,+ 'plugin_id': plugin.id,+ 'installed_version': row.installed_version,+ 'library_version': plugin.version,+ 'status': row.status,+ 'update_available': cls._version_behind(row.installed_version, plugin.version),+ })+ return out++ @staticmethod+ def _version_behind(installed: Optional[str], library: Optional[str]) -> bool:+ """True when the installed version is older than the library version.++ Best-effort numeric compare (falls back to string inequality) — plugin+ versions are overwhelmingly dotted numerics.+ """+ if not installed or not library:+ return False+ if installed == library:+ return False++ def parts(v):+ nums = re.findall(r'\d+', v)+ return [int(n) for n in nums]++ pi, pl = parts(installed), parts(library)+ if not pi or not pl:+ return installed != library+ length = max(len(pi), len(pl))+ pi += [0] * (length - len(pi))+ pl += [0] * (length - len(pl))+ return pi < pldiff --git a/backend/migrations/versions/041_wordpress_plugin_library.py b/backend/migrations/versions/041_wordpress_plugin_library.pynew file mode 100644index 00000000..01af38f1--- /dev/null+++ b/backend/migrations/versions/041_wordpress_plugin_library.py@@ -0,0 +1,82 @@+"""WordPress global plugin library.++Adds:+- wordpress_custom_plugins (operator-owned plugins registered in the library)+- wordpress_site_plugins (per-site installations of library plugins)++Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on boot+before Alembic, so guard on the live schema.++Revision ID: 041_wordpress_plugin_library+Revises: 040_site_base_domains+Create Date: 2026-07-01+"""+from alembic import op+import sqlalchemy as sa++revision = '041_wordpress_plugin_library'+down_revision = '040_site_base_domains'+branch_labels = None+depends_on = None+++def upgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ existing = set(inspector.get_table_names())++ if 'wordpress_custom_plugins' not in existing:+ op.create_table(+ 'wordpress_custom_plugins',+ sa.Column('id', sa.Integer, nullable=False),+ sa.Column('slug', sa.String(200), nullable=False),+ sa.Column('name', sa.String(255), nullable=True),+ sa.Column('description', sa.Text, nullable=True),+ sa.Column('version', sa.String(50), nullable=True),+ sa.Column('author', sa.String(255), nullable=True),+ sa.Column('source_type', sa.String(20), nullable=False, server_default='github'),+ sa.Column('source_url', sa.String(500), nullable=False),+ sa.Column('branch', sa.String(100), nullable=True, server_default='main'),+ sa.Column('connection_id', sa.Integer, nullable=True),+ sa.Column('is_active', sa.Boolean, nullable=False, server_default=sa.true()),+ sa.Column('last_synced_at', sa.DateTime, nullable=True),+ sa.Column('sync_error', sa.Text, nullable=True),+ sa.Column('created_at', sa.DateTime, nullable=True),+ sa.Column('updated_at', sa.DateTime, nullable=True),+ sa.PrimaryKeyConstraint('id'),+ sa.UniqueConstraint('slug', name='uq_wp_custom_plugin_slug'),+ )+ op.create_index('ix_wordpress_custom_plugins_slug',+ 'wordpress_custom_plugins', ['slug'])++ if 'wordpress_site_plugins' not in existing:+ op.create_table(+ 'wordpress_site_plugins',+ sa.Column('id', sa.Integer, nullable=False),+ sa.Column('wordpress_site_id', sa.Integer, nullable=False),+ sa.Column('custom_plugin_id', sa.Integer, nullable=False),+ sa.Column('installed_version', sa.String(50), nullable=True),+ sa.Column('status', sa.String(20), nullable=True, server_default='not_installed'),+ sa.Column('updated_at', sa.DateTime, nullable=True),+ sa.PrimaryKeyConstraint('id'),+ sa.ForeignKeyConstraint(['wordpress_site_id'], ['wordpress_sites.id'],+ ondelete='CASCADE'),+ sa.ForeignKeyConstraint(['custom_plugin_id'], ['wordpress_custom_plugins.id'],+ ondelete='CASCADE'),+ sa.UniqueConstraint('wordpress_site_id', 'custom_plugin_id',+ name='uq_site_custom_plugin'),+ )+ op.create_index('ix_wordpress_site_plugins_site',+ 'wordpress_site_plugins', ['wordpress_site_id'])+ op.create_index('ix_wordpress_site_plugins_plugin',+ 'wordpress_site_plugins', ['custom_plugin_id'])+++def downgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ existing = set(inspector.get_table_names())+ if 'wordpress_site_plugins' in existing:+ op.drop_table('wordpress_site_plugins')+ if 'wordpress_custom_plugins' in existing:+ op.drop_table('wordpress_custom_plugins')diff --git a/backend/tests/test_wp_plugin_library.py b/backend/tests/test_wp_plugin_library.pynew file mode 100644index 00000000..aaac82d0--- /dev/null+++ b/backend/tests/test_wp_plugin_library.py@@ -0,0 +1,278 @@+"""Tests for the WordPress global plugin library service + API."""+import os+import shutil++import pytest+++PLUGIN_PHP = """<?php+/*+ * Plugin Name: My Custom Plugin+ * Description: Does a very custom thing.+ * Version: 1.2.3+ * Author: Acme Corp+ */+"""+++def _make_local_plugin(tmp_path, slug='my-plugin', body=PLUGIN_PHP):+ """Create a local plugin source folder with a header PHP file."""+ src = tmp_path / f'src-{slug}'+ src.mkdir()+ (src / f'{slug}.php').write_text(body, encoding='utf-8')+ return str(src)+++def _fake_privileged(cmd, *args, **kwargs):+ """Minimal python implementation of the shell verbs the service shells out to."""+ if cmd[:2] == ['rm', '-rf']:+ shutil.rmtree(cmd[2], ignore_errors=True)+ elif cmd[:2] == ['mkdir', '-p']:+ os.makedirs(cmd[2], exist_ok=True)+ elif cmd[:2] == ['cp', '-a']:+ src, dst = cmd[2], cmd[3]+ if os.path.isdir(src):+ shutil.copytree(src, dst, dirs_exist_ok=True)+ else:+ shutil.copy2(src, dst)+ # chown is a no-op off Linux+ return {'success': True}+++# --------------------------------------------------------------------------+# Pure helpers+# --------------------------------------------------------------------------+def test_slug_validation():+ from app.services.wordpress_plugin_library_service import (+ WordPressPluginLibraryService as S, PluginLibraryError)+ assert S.validate_slug('my-plugin') == 'my-plugin'+ assert S.slugify('My Cool Plugin!') == 'my-cool-plugin'+ with pytest.raises(PluginLibraryError):+ S.validate_slug('Bad Slug')+ with pytest.raises(PluginLibraryError):+ S.validate_slug('')+++def test_version_behind():+ from app.services.wordpress_plugin_library_service import WordPressPluginLibraryService as S+ assert S._version_behind('1.0.0', '1.0.1') is True+ assert S._version_behind('1.2.0', '1.10.0') is True+ assert S._version_behind('2.0.0', '1.9.9') is False+ assert S._version_behind('1.2.3', '1.2.3') is False+ assert S._version_behind(None, '1.0.0') is False+ assert S._version_behind('1.0.0', None) is False+++def test_parse_plugin_header(tmp_path):+ from app.services.wordpress_plugin_library_service import WordPressPluginLibraryService as S+ src = _make_local_plugin(tmp_path, 'my-plugin')+ header = S.parse_plugin_header(src, 'my-plugin')+ assert header['name'] == 'My Custom Plugin'+ assert header['version'] == '1.2.3'+ assert header['author'] == 'Acme Corp'+ assert header['description'] == 'Does a very custom thing.'+++def test_parse_plugin_header_falls_back_to_first_php(tmp_path):+ from app.services.wordpress_plugin_library_service import WordPressPluginLibraryService as S+ src = tmp_path / 'src'+ src.mkdir()+ (src / 'main.php').write_text(PLUGIN_PHP, encoding='utf-8')+ header = S.parse_plugin_header(str(src), 'mismatched-slug')+ assert header['version'] == '1.2.3'+++# --------------------------------------------------------------------------+# Service: sync + CRUD (local source)+# --------------------------------------------------------------------------+def test_add_and_sync_local_plugin(app, tmp_path, monkeypatch):+ import app.services.wordpress_plugin_library_service as mod+ from app.services.wordpress_plugin_library_service import WordPressPluginLibraryService as S++ monkeypatch.setattr(S, 'CACHE_DIR', str(tmp_path / 'cache'))+ src = _make_local_plugin(tmp_path, 'my-plugin')++ result = S.add_plugin({'source_type': 'local', 'source_url': src, 'slug': 'my-plugin'})+ assert result['slug'] == 'my-plugin'+ assert result['version'] == '1.2.3'+ assert result['name'] == 'My Custom Plugin'++ # Cache snapshot exists and is a copy (not the source path)+ cache = S.cache_path('my-plugin')+ assert os.path.isfile(os.path.join(cache, 'my-plugin.php'))++ # Duplicate slug rejected+ from app.services.wordpress_plugin_library_service import PluginLibraryError+ with pytest.raises(PluginLibraryError):+ S.add_plugin({'source_type': 'local', 'source_url': src, 'slug': 'my-plugin'})+++def test_sync_reparses_updated_version(app, tmp_path, monkeypatch):+ from app.services.wordpress_plugin_library_service import WordPressPluginLibraryService as S+ monkeypatch.setattr(S, 'CACHE_DIR', str(tmp_path / 'cache'))+ src_dir = tmp_path / 'src'+ src_dir.mkdir()+ php = src_dir / 'my-plugin.php'+ php.write_text(PLUGIN_PHP, encoding='utf-8')++ added = S.add_plugin({'source_type': 'local', 'source_url': str(src_dir), 'slug': 'my-plugin'})+ assert added['version'] == '1.2.3'++ # Bump the source version and re-sync+ php.write_text(PLUGIN_PHP.replace('1.2.3', '2.0.0'), encoding='utf-8')+ from app.models import WordPressCustomPlugin+ plugin = WordPressCustomPlugin.query.get(added['id'])+ res = S.sync_plugin(plugin)+ assert res['success'] is True+ assert plugin.version == '2.0.0'+++# --------------------------------------------------------------------------+# Service: install on a site + scan+# --------------------------------------------------------------------------+def _make_site(app, tmp_path, name='acme'):+ from app import db+ from app.models import Application, WordPressSite, User+ from werkzeug.security import generate_password_hash+ user = User.query.filter_by(username=f'owner-{name}').first()+ if not user:+ user = User(email=f'{name}@test.local', username=f'owner-{name}',+ password_hash=generate_password_hash('x'),+ role=User.ROLE_ADMIN, is_active=True)+ db.session.add(user)+ db.session.commit()+ root = tmp_path / f'site-{name}'+ (root / 'wp-content' / 'plugins').mkdir(parents=True)+ app_row = Application(name=name, app_type='wordpress', user_id=user.id, root_path=str(root))+ db.session.add(app_row)+ db.session.commit()+ site = WordPressSite(application_id=app_row.id, wp_version='6.5')+ db.session.add(site)+ db.session.commit()+ return app_row, site+++def test_install_on_site_copies_and_records(app, tmp_path, monkeypatch):+ import app.services.wordpress_plugin_library_service as mod+ from app.services.wordpress_plugin_library_service import WordPressPluginLibraryService as S+ from app.services.wordpress_service import WordPressService+ from app.models import WordPressSitePlugin++ monkeypatch.setattr(S, 'CACHE_DIR', str(tmp_path / 'cache'))+ monkeypatch.setattr(mod, 'run_privileged', _fake_privileged)+ calls = []+ monkeypatch.setattr(WordPressService, 'wp_cli',+ classmethod(lambda cls, path, cmd, **kw: (calls.append(cmd) or {'success': True})))++ src = _make_local_plugin(tmp_path, 'my-plugin')+ added = S.add_plugin({'source_type': 'local', 'source_url': src, 'slug': 'my-plugin'})++ from app.models import WordPressCustomPlugin+ plugin = WordPressCustomPlugin.query.get(added['id'])+ _, site = _make_site(app, tmp_path)++ res = S.install_on_site(plugin, site, activate=True)+ assert res['success'] is True+ assert res['status'] == 'active'++ # File landed in the site's wp-content/plugins/<slug>+ target = os.path.join(site.application.root_path, 'wp-content', 'plugins', 'my-plugin', 'my-plugin.php')+ assert os.path.isfile(target)++ # Installation row recorded+ row = WordPressSitePlugin.query.filter_by(+ wordpress_site_id=site.id, custom_plugin_id=plugin.id).first()+ assert row is not None and row.status == 'active'+ assert ['plugin', 'activate', 'my-plugin'] in calls+++def test_scan_site_tags_managed(app, tmp_path, monkeypatch):+ from app.services.wordpress_plugin_library_service import WordPressPluginLibraryService as S+ from app.services.wordpress_service import WordPressService+ monkeypatch.setattr(S, 'CACHE_DIR', str(tmp_path / 'cache'))++ src = _make_local_plugin(tmp_path, 'my-plugin')+ added = S.add_plugin({'source_type': 'local', 'source_url': src, 'slug': 'my-plugin'})+ from app.models import WordPressCustomPlugin+ plugin = WordPressCustomPlugin.query.get(added['id'])+ _, site = _make_site(app, tmp_path)++ # WP-CLI reports the plugin installed & active, at an older version.+ monkeypatch.setattr(WordPressService, 'get_plugins', classmethod(lambda cls, path: [+ {'name': 'my-plugin', 'status': 'active', 'version': '1.0.0'},+ {'name': 'akismet', 'status': 'inactive', 'version': '5.0'},+ ]))++ res = S.scan_site(site)+ assert 'my-plugin' in res['managed_slugs']++ managed = S.managed_for_site(site)+ entry = next(m for m in managed if m['slug'] == 'my-plugin')+ assert entry['installed_version'] == '1.0.0'+ assert entry['library_version'] == '1.2.3'+ assert entry['update_available'] is True+++# --------------------------------------------------------------------------+# API: CRUD + bulk update+# --------------------------------------------------------------------------+def test_api_library_crud(app, client, auth_headers, tmp_path, monkeypatch):+ from app.services.wordpress_plugin_library_service import WordPressPluginLibraryService as S+ monkeypatch.setattr(S, 'CACHE_DIR', str(tmp_path / 'cache'))+ src = _make_local_plugin(tmp_path, 'api-plugin')++ # Create+ r = client.post('/api/v1/wordpress/plugins/library',+ json={'source_type': 'local', 'source_url': src, 'slug': 'api-plugin'},+ headers=auth_headers)+ assert r.status_code == 201, r.get_json()+ pid = r.get_json()['id']++ # List+ r = client.get('/api/v1/wordpress/plugins/library', headers=auth_headers)+ assert r.status_code == 200+ assert any(p['slug'] == 'api-plugin' for p in r.get_json()['plugins'])++ # Detail+ r = client.get(f'/api/v1/wordpress/plugins/library/{pid}', headers=auth_headers)+ assert r.status_code == 200+ assert r.get_json()['version'] == '1.2.3'++ # Delete+ r = client.delete(f'/api/v1/wordpress/plugins/library/{pid}', headers=auth_headers)+ assert r.status_code == 200+ r = client.get(f'/api/v1/wordpress/plugins/library/{pid}', headers=auth_headers)+ assert r.status_code == 404+++def test_api_add_requires_source(app, client, auth_headers, tmp_path, monkeypatch):+ from app.services.wordpress_plugin_library_service import WordPressPluginLibraryService as S+ monkeypatch.setattr(S, 'CACHE_DIR', str(tmp_path / 'cache'))+ r = client.post('/api/v1/wordpress/plugins/library',+ json={'source_type': 'github'}, headers=auth_headers)+ assert r.status_code == 400+++def test_api_bulk_update(app, client, auth_headers, tmp_path, monkeypatch):+ import app.services.wordpress_plugin_library_service as mod+ from app.services.wordpress_plugin_library_service import WordPressPluginLibraryService as S+ from app.services.wordpress_service import WordPressService++ monkeypatch.setattr(S, 'CACHE_DIR', str(tmp_path / 'cache'))+ monkeypatch.setattr(mod, 'run_privileged', _fake_privileged)+ monkeypatch.setattr(WordPressService, 'wp_cli',+ classmethod(lambda cls, path, cmd, **kw: {'success': True}))++ src = _make_local_plugin(tmp_path, 'bulk-plugin')+ added = S.add_plugin({'source_type': 'local', 'source_url': src, 'slug': 'bulk-plugin'})+ from app.models import WordPressCustomPlugin+ plugin = WordPressCustomPlugin.query.get(added['id'])+ _, site = _make_site(app, tmp_path, name='bulk-site')+ S.install_on_site(plugin, site, activate=False)++ r = client.post(f'/api/v1/wordpress/plugins/library/{added["id"]}/bulk-update',+ headers=auth_headers)+ assert r.status_code == 200+ body = r.get_json()+ assert body['total'] == 1+ assert body['updated'] == 1diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 6aad9227..a4a4eafd 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -49,6 +49,7 @@ import Downloads from './pages/Downloads';import WordPress from './pages/WordPress';import WordPressDetail from './pages/WordPressDetail';import WordPressProjects from './pages/WordPressProjects';+import WordPressPluginLibrary from './pages/WordPressPluginLibrary';import WordPressProject from './pages/WordPressProject';import SSLCertificates from './pages/SSLCertificates';import Email from './pages/Email';@@ -96,6 +97,7 @@ const PAGE_TITLES = {'/shared-variables': 'Shared Variables','/fleet-proxy': 'Fleet Proxy','/wordpress': 'WordPress Sites',+ '/wordpress/plugins/library': 'WordPress Plugin Library','/wordpress/pipelines': 'WordPress Pipelines','/templates': 'Templates','/deployments': 'Deployment Activity',@@ -341,6 +343,7 @@ function AppRoutes() {<Route path="apps/:id/:tab" element={<LegacyAppRedirect />} /><Route element={<TabGroupLayout tabs={WORDPRESS_TABS} />}><Route path="wordpress" element={<WordPress />} />+ <Route path="wordpress/plugins/library" element={<WordPressPluginLibrary />} /><Route path="wordpress/pipelines" element={<WordPressProjects />} /></Route><Route path="wordpress/pipelines/:id" element={<WordPressProject />} />diff --git a/frontend/src/components/wordpress/detail/PluginsTab.jsx b/frontend/src/components/wordpress/detail/PluginsTab.jsxindex a68d7af1..9db483e8 100644--- a/frontend/src/components/wordpress/detail/PluginsTab.jsx+++ b/frontend/src/components/wordpress/detail/PluginsTab.jsx@@ -20,6 +20,8 @@ const PluginsTab = ({ siteId }) => {const [updating, setUpdating] = useState(null); // plugin name being updated, or 'all'const [newPlugin, setNewPlugin] = useState('');const [toggling, setToggling] = useState(null); // plugin name being activated/deactivated+ // Map of slug -> managed metadata (installed/library version, update_available).+ const [managed, setManaged] = useState({});useEffect(() => {loadPlugins();@@ -31,6 +33,7 @@ const PluginsTab = ({ siteId }) => {try {const data = await wordpressApi.getPlugins(siteId);setPlugins(data.plugins || []);+ loadManaged();} catch (err) {console.error('Failed to load plugins:', err);setError(err);@@ -39,6 +42,38 @@ const PluginsTab = ({ siteId }) => {}}+ // Which installed plugins are library-managed. Best-effort: a scan first so the+ // mapping reflects the live site, then read it back keyed by slug.+ async function loadManaged() {+ try {+ await wordpressApi.scanManagedPlugins(siteId);+ const data = await wordpressApi.getManagedPlugins(siteId);+ const map = {};+ (data.managed || []).forEach(m => { map[m.slug] = m; });+ setManaged(map);+ } catch {+ // Library layer is optional — never block the plugins list on it.+ setManaged({});+ }+ }++ async function handleLibraryUpdate(slug) {+ const m = managed[slug];+ if (!m) return;+ setUpdating(slug);+ toast.info(`Updating ${slug} from library…`, { duration: 4000 });+ try {+ const res = await wordpressApi.installLibraryPluginOnSite(m.plugin_id, siteId, m.status === 'active');+ if (res.success === false) { toast.error(res.error || 'Library update failed'); return; }+ toast.success(`${slug} updated to library version`);+ loadPlugins();+ } catch (err) {+ toast.error(err.message || 'Library update failed');+ } finally {+ setUpdating(null);+ }+ }+async function handleInstall(e) {e.preventDefault();if (!newPlugin.trim()) return;@@ -158,15 +193,30 @@ const PluginsTab = ({ siteId }) => {<div className="wp-asset-grid">{plugins.map(plugin => {const isActive = plugin.status === 'active';+ const mgd = managed[plugin.name];return (<div className={`wp-asset-card ${isActive ? 'is-active' : ''}`} key={plugin.name}><ServiceTile name={plugin.title || plugin.name} size={42} /><div className="wp-asset-card__body">- <div className="wp-asset-card__name">{plugin.title || plugin.name}</div>+ <div className="wp-asset-card__name">+ {plugin.title || plugin.name}+ {mgd && <span className="wp-managed-pill">Managed</span>}+ </div><div className="wp-asset-card__sub">{plugin.name}</div><div className="wp-asset-card__foot"><span className="wp-asset-card__ver">v{plugin.version}</span>- {plugin.update === 'available' && (+ {mgd && mgd.update_available ? (+ <button+ type="button"+ className="wp-update-flag wp-update-flag--library"+ onClick={() => handleLibraryUpdate(plugin.name)}+ disabled={updating !== null}+ title={`Library has v${mgd.library_version}`}+ >+ <Download size={11} />+ {updating === plugin.name ? 'Updating…' : `Update from library ${mgd.library_version}`}+ </button>+ ) : plugin.update === 'available' && (<buttontype="button"className="wp-update-flag"diff --git a/frontend/src/components/wordpress/wordpressTabs.jsx b/frontend/src/components/wordpress/wordpressTabs.jsxindex f47623b9..05e9f5a1 100644--- a/frontend/src/components/wordpress/wordpressTabs.jsx+++ b/frontend/src/components/wordpress/wordpressTabs.jsx@@ -1,4 +1,4 @@-import { Globe, GitBranch } from 'lucide-react';+import { Globe, GitBranch, Package } from 'lucide-react';// Shared sub-nav for the WordPress page group (WordPress sites / Pipeline).// Rendered in each page's <PageTopbar tabs={WORDPRESS_TABS}> — the demo's@@ -7,5 +7,6 @@ import { Globe, GitBranch } from 'lucide-react';// here for simplicity — the pipeline page shows an empty state when unused.)export const WORDPRESS_TABS = [{ to: '/wordpress', label: 'WordPress', end: true, icon: <Globe size={15} /> },+ { to: '/wordpress/plugins/library', label: 'Plugin Library', icon: <Package size={15} /> },{ to: '/wordpress/pipelines', label: 'Pipeline', icon: <GitBranch size={15} /> },];diff --git a/frontend/src/pages/WordPressPluginLibrary.jsx b/frontend/src/pages/WordPressPluginLibrary.jsxnew file mode 100644index 00000000..9a8e5d8b--- /dev/null+++ b/frontend/src/pages/WordPressPluginLibrary.jsx@@ -0,0 +1,353 @@+import { useState, useEffect } from 'react';+import { Package, RefreshCw, Download, Trash2, Github, FolderGit2, Pencil, Server } from 'lucide-react';+import wordpressApi from '../services/wordpress';+import { useToast } from '../contexts/ToastContext';+import { useAuth } from '../contexts/AuthContext';+import EmptyState from '../components/EmptyState';+import Spinner from '../components/Spinner';+import Modal from '@/components/Modal';+import { Pill, ServiceTile } from '@/components/ds';+import { useTopbarActions } from '@/hooks/useTopbarActions';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { Switch } from '@/components/ui/switch';++const EMPTY_FORM = { source_type: 'github', source_url: '', slug: '', branch: 'main' };++function WordPressPluginLibrary() {+ const toast = useToast();+ const { user } = useAuth();+ const isAdmin = user?.role === 'admin';++ const [plugins, setPlugins] = useState([]);+ const [loading, setLoading] = useState(true);+ const [busy, setBusy] = useState(null); // `${action}:${id}` currently running++ const [showAdd, setShowAdd] = useState(false);+ const [editing, setEditing] = useState(null); // plugin being edited, or null+ const [form, setForm] = useState(EMPTY_FORM);+ const [saving, setSaving] = useState(false);++ const [installFor, setInstallFor] = useState(null); // plugin selected for "install on site"+ const [sites, setSites] = useState([]);+ const [installSiteId, setInstallSiteId] = useState('');+ const [installActivate, setInstallActivate] = useState(true);++ useEffect(() => { loadPlugins(); }, []);++ async function loadPlugins() {+ setLoading(true);+ try {+ const data = await wordpressApi.getLibraryPlugins();+ setPlugins(data.plugins || []);+ } catch (err) {+ toast.error(err.message || 'Failed to load plugin library');+ setPlugins([]);+ } finally {+ setLoading(false);+ }+ }++ function openAdd() {+ setEditing(null);+ setForm(EMPTY_FORM);+ setShowAdd(true);+ }++ function openEdit(plugin) {+ setEditing(plugin);+ setForm({+ source_type: plugin.source_type,+ source_url: plugin.source_url,+ slug: plugin.slug,+ branch: plugin.branch || 'main',+ });+ setShowAdd(true);+ }++ async function handleSave() {+ if (!form.source_url.trim()) {+ toast.error(form.source_type === 'local' ? 'A local path is required' : 'A repo (owner/repo or git URL) is required');+ return;+ }+ setSaving(true);+ try {+ if (editing) {+ await wordpressApi.updateLibraryPlugin(editing.id, form);+ toast.success('Plugin updated');+ } else {+ const res = await wordpressApi.addLibraryPlugin(form);+ if (res.sync_error) toast.info(`Added, but sync failed: ${res.sync_error}`, { duration: 8000 });+ else toast.success('Plugin added to library');+ }+ setShowAdd(false);+ await loadPlugins();+ } catch (err) {+ toast.error(err.message || 'Failed to save plugin');+ } finally {+ setSaving(false);+ }+ }++ async function handleSync(plugin) {+ setBusy(`sync:${plugin.id}`);+ try {+ const res = await wordpressApi.syncLibraryPlugin(plugin.id);+ if (res.success === false) toast.error(res.error || 'Sync failed');+ else toast.success(`Synced ${plugin.slug} (v${res.plugin?.version || '?'})`);+ await loadPlugins();+ } catch (err) {+ toast.error(err.message || 'Sync failed');+ } finally {+ setBusy(null);+ }+ }++ async function handleBulkUpdate(plugin) {+ setBusy(`bulk:${plugin.id}`);+ try {+ const res = await wordpressApi.bulkUpdateLibraryPlugin(plugin.id);+ toast.success(`Updated ${res.updated} of ${res.total} site(s)`);+ await loadPlugins();+ } catch (err) {+ toast.error(err.message || 'Bulk update failed');+ } finally {+ setBusy(null);+ }+ }++ async function handleDelete(plugin) {+ if (!window.confirm(`Remove "${plugin.slug}" from the library? Installed copies on sites are left untouched.`)) return;+ setBusy(`delete:${plugin.id}`);+ try {+ await wordpressApi.deleteLibraryPlugin(plugin.id);+ toast.success('Plugin removed from library');+ await loadPlugins();+ } catch (err) {+ toast.error(err.message || 'Failed to remove plugin');+ } finally {+ setBusy(null);+ }+ }++ async function openInstall(plugin) {+ setInstallFor(plugin);+ setInstallSiteId('');+ setInstallActivate(true);+ try {+ const data = await wordpressApi.getSites();+ setSites(data.sites || []);+ } catch {+ setSites([]);+ }+ }++ async function handleInstall() {+ if (!installSiteId) { toast.error('Pick a site'); return; }+ setBusy(`install:${installFor.id}`);+ try {+ const res = await wordpressApi.installLibraryPluginOnSite(installFor.id, Number(installSiteId), installActivate);+ if (res.success === false) toast.error(res.error || 'Install failed');+ else toast.success(`Installed ${installFor.slug} (${res.status})`);+ setInstallFor(null);+ await loadPlugins();+ } catch (err) {+ toast.error(err.message || 'Install failed');+ } finally {+ setBusy(null);+ }+ }++ useTopbarActions(() => (+ isAdmin ? (+ <Button size="sm" onClick={openAdd}>+ <Package size={16} /> Add Plugin+ </Button>+ ) : null+ ), [isAdmin]);++ if (loading) {+ return (+ <div className="sk-tabgroup__inner wp-plugin-library">+ <div className="wp-plugin-library__loading"><Spinner /></div>+ </div>+ );+ }++ return (+ <div className="sk-tabgroup__inner wp-plugin-library">+ {plugins.length === 0 ? (+ <EmptyState+ icon={Package}+ title="No plugins in the library yet"+ description="Register your own plugins from a GitHub repo or a local path, then install or update them across every managed WordPress site from here."+ action={isAdmin ? <Button onClick={openAdd}><Package size={16} /> Add Plugin</Button> : null}+ />+ ) : (+ <div className="wp-plib-grid">+ {plugins.map(plugin => {+ const SourceIcon = plugin.source_type === 'github' ? Github : FolderGit2;+ return (+ <div className={`wp-plib-card ${plugin.is_active ? '' : 'is-disabled'}`} key={plugin.id}>+ <div className="wp-plib-card__head">+ <ServiceTile name={plugin.name || plugin.slug} size={40} />+ <div className="wp-plib-card__title">+ <div className="wp-plib-card__name">{plugin.name || plugin.slug}</div>+ <div className="wp-plib-card__slug">{plugin.slug}</div>+ </div>+ {plugin.version && <Pill kind="gray">v{plugin.version}</Pill>}+ </div>++ {plugin.description && (+ <p className="wp-plib-card__desc">{plugin.description}</p>+ )}++ <div className="wp-plib-card__meta">+ <span className="wp-plib-card__source" title={plugin.source_url}>+ <SourceIcon size={13} /> {plugin.source_url}+ </span>+ <span className="wp-plib-card__branch">{plugin.branch}</span>+ </div>++ <div className="wp-plib-card__stats">+ <span><Server size={13} /> {plugin.install_count} site{plugin.install_count === 1 ? '' : 's'}</span>+ {plugin.sync_error+ ? <Pill kind="red" title={plugin.sync_error}>Sync error</Pill>+ : plugin.last_synced_at+ ? <span className="wp-plib-card__synced">Synced</span>+ : <Pill kind="amber">Not synced</Pill>}+ </div>++ {isAdmin && (+ <div className="wp-plib-card__actions">+ <Button variant="outline" size="sm" disabled={busy === `sync:${plugin.id}`} onClick={() => handleSync(plugin)}>+ <RefreshCw size={14} className={busy === `sync:${plugin.id}` ? 'spin' : ''} /> Sync+ </Button>+ <Button variant="outline" size="sm" onClick={() => openInstall(plugin)}>+ <Download size={14} /> Install+ </Button>+ <Button variant="outline" size="sm" disabled={!plugin.install_count || busy === `bulk:${plugin.id}`} onClick={() => handleBulkUpdate(plugin)}>+ Bulk update+ </Button>+ <Button variant="ghost" size="sm" onClick={() => openEdit(plugin)} aria-label="Edit">+ <Pencil size={14} />+ </Button>+ <Button variant="ghost" size="sm" onClick={() => handleDelete(plugin)} aria-label="Delete">+ <Trash2 size={14} />+ </Button>+ </div>+ )}+ </div>+ );+ })}+ </div>+ )}++ {/* Add / Edit modal */}+ <Modal+ open={showAdd}+ onClose={() => setShowAdd(false)}+ title={editing ? `Edit ${editing.slug}` : 'Add plugin to library'}+ >+ <div className="wp-plib-form">+ <div className="wp-plib-form__row">+ <Label>Source</Label>+ <div className="wp-plib-form__toggle">+ <button+ type="button"+ className={form.source_type === 'github' ? 'is-on' : ''}+ onClick={() => setForm(f => ({ ...f, source_type: 'github' }))}+ ><Github size={14} /> GitHub</button>+ <button+ type="button"+ className={form.source_type === 'local' ? 'is-on' : ''}+ onClick={() => setForm(f => ({ ...f, source_type: 'local' }))}+ ><FolderGit2 size={14} /> Local path</button>+ </div>+ </div>++ <div className="wp-plib-form__row">+ <Label htmlFor="plib-src">+ {form.source_type === 'github' ? 'Repository (owner/repo or git URL)' : 'Absolute local path'}+ </Label>+ <Input+ id="plib-src"+ value={form.source_url}+ onChange={e => setForm(f => ({ ...f, source_url: e.target.value }))}+ placeholder={form.source_type === 'github' ? 'acme/my-plugin' : '/srv/plugins/my-plugin'}+ />+ </div>++ <div className="wp-plib-form__row">+ <Label htmlFor="plib-slug">Plugin slug <span className="wp-plib-form__hint">(folder name; auto-derived if blank)</span></Label>+ <Input+ id="plib-slug"+ value={form.slug}+ onChange={e => setForm(f => ({ ...f, slug: e.target.value }))}+ placeholder="my-plugin"+ disabled={!!editing}+ />+ </div>++ {form.source_type === 'github' && (+ <div className="wp-plib-form__row">+ <Label htmlFor="plib-branch">Branch or tag</Label>+ <Input+ id="plib-branch"+ value={form.branch}+ onChange={e => setForm(f => ({ ...f, branch: e.target.value }))}+ placeholder="main"+ />+ </div>+ )}++ <div className="wp-plib-form__footer">+ <Button variant="outline" onClick={() => setShowAdd(false)}>Cancel</Button>+ <Button onClick={handleSave} disabled={saving}>+ {saving ? 'Saving…' : editing ? 'Save' : 'Add & sync'}+ </Button>+ </div>+ </div>+ </Modal>++ {/* Install-on-site modal */}+ <Modal+ open={!!installFor}+ onClose={() => setInstallFor(null)}+ title={installFor ? `Install ${installFor.slug} on a site` : ''}+ >+ <div className="wp-plib-form">+ <div className="wp-plib-form__row">+ <Label htmlFor="plib-site">Target site</Label>+ <select+ id="plib-site"+ className="wp-plib-form__select"+ value={installSiteId}+ onChange={e => setInstallSiteId(e.target.value)}+ >+ <option value="">Select a site…</option>+ {sites.map(s => (+ <option key={s.id} value={s.id}>+ {s.name || s.application?.name || `Site ${s.id}`}+ </option>+ ))}+ </select>+ </div>+ <div className="wp-plib-form__row wp-plib-form__row--inline">+ <Switch checked={installActivate} onCheckedChange={setInstallActivate} id="plib-activate" />+ <Label htmlFor="plib-activate">Activate after install</Label>+ </div>+ <div className="wp-plib-form__footer">+ <Button variant="outline" onClick={() => setInstallFor(null)}>Cancel</Button>+ <Button onClick={handleInstall} disabled={busy === `install:${installFor?.id}`}>+ {busy === `install:${installFor?.id}` ? 'Installing…' : 'Install'}+ </Button>+ </div>+ </div>+ </Modal>+ </div>+ );+}++export default WordPressPluginLibrary;diff --git a/frontend/src/services/wordpress.js b/frontend/src/services/wordpress.jsindex 155357e0..df1a5ecc 100644--- a/frontend/src/services/wordpress.js+++ b/frontend/src/services/wordpress.js@@ -151,6 +151,58 @@ const wordpressApi = {method: 'POST'}),+ // =========================================+ // Global Plugin Library+ // =========================================+ LIBRARY_PATH: '/wordpress/plugins/library',++ getLibraryPlugins: () => api.request('/wordpress/plugins/library'),++ getLibraryPlugin: (id) => api.request(`/wordpress/plugins/library/${id}`),++ addLibraryPlugin: (data) => api.request('/wordpress/plugins/library', {+ method: 'POST',+ body: data+ }),++ updateLibraryPlugin: (id, data) => api.request(`/wordpress/plugins/library/${id}`, {+ method: 'PUT',+ body: data+ }),++ deleteLibraryPlugin: (id) => api.request(`/wordpress/plugins/library/${id}`, {+ method: 'DELETE'+ }),++ syncLibraryPlugin: (id) => api.request(`/wordpress/plugins/library/${id}/sync`, {+ method: 'POST'+ }),++ // Install/update a library plugin on a specific site.+ installLibraryPluginOnSite: (id, siteId, activate = true) =>+ api.request(`/wordpress/plugins/library/${id}/install`, {+ method: 'POST',+ body: { site_id: siteId, activate }+ }),++ uninstallLibraryPluginFromSite: (id, siteId) =>+ api.request(`/wordpress/plugins/library/${id}/uninstall`, {+ method: 'POST',+ body: { site_id: siteId }+ }),++ // Push the latest cached version to every site that has the plugin.+ bulkUpdateLibraryPlugin: (id) => api.request(`/wordpress/plugins/library/${id}/bulk-update`, {+ method: 'POST'+ }),++ // Per-site: which installed plugins are library-managed (+ update state).+ getManagedPlugins: (siteId) => api.request(`${BASE_PATH}/${siteId}/plugins/managed`),++ scanManagedPlugins: (siteId) => api.request(`${BASE_PATH}/${siteId}/plugins/library-scan`, {+ method: 'POST'+ }),+// ThemesgetThemes: (siteId) => api.request(`${BASE_PATH}/${siteId}/themes`),diff --git a/frontend/src/styles/main.scss b/frontend/src/styles/main.scssindex 0e923ca7..6b5e0830 100644--- a/frontend/src/styles/main.scss+++ b/frontend/src/styles/main.scss@@ -108,6 +108,7 @@@import 'pages/_downloads';@import 'pages/_wordpress';@import 'pages/_wordpress-pipeline';+@import 'pages/_wordpress-plugin-library';@import 'pages/_ssl';@import 'pages/_email';@import 'pages/_setup-wizard';diff --git a/frontend/src/styles/pages/_wordpress-plugin-library.scss b/frontend/src/styles/pages/_wordpress-plugin-library.scssnew file mode 100644index 00000000..5eceeafc--- /dev/null+++ b/frontend/src/styles/pages/_wordpress-plugin-library.scss@@ -0,0 +1,179 @@+// WordPress Global Plugin Library page.+.wp-plugin-library {++ &__loading {+ display: grid;+ place-items: center;+ min-height: 240px;+ }++ .wp-plib-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));+ gap: 16px;+ }++ .wp-plib-card {+ display: flex;+ flex-direction: column;+ gap: 10px;+ background: var(--surface);+ border: 1px solid var(--border-soft);+ border-radius: var(--radius);+ padding: 16px;+ transition: border-color 0.15s, transform 0.15s;++ &:hover { border-color: var(--border-strong); }+ &.is-disabled { opacity: 0.6; }++ &__head {+ display: flex;+ align-items: center;+ gap: 12px;+ }++ &__title { flex: 1; min-width: 0; }++ &__name {+ font-weight: 600;+ font-size: 14px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ &__slug {+ font-family: var(--mono);+ font-size: 11px;+ color: var(--text-dim);+ }++ &__desc {+ font-size: 12.5px;+ color: var(--text-dim);+ margin: 0;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+ }++ &__meta {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ font-size: 11.5px;+ color: var(--text-dim);+ }++ &__source {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ font-family: var(--mono);+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ &__branch {+ font-family: var(--mono);+ background: var(--surface-2, rgba(127, 127, 127, 0.1));+ padding: 1px 7px;+ border-radius: 4px;+ flex-shrink: 0;+ }++ &__stats {+ display: flex;+ align-items: center;+ justify-content: space-between;+ font-size: 12px;+ color: var(--text-dim);++ span { display: inline-flex; align-items: center; gap: 5px; }+ }++ &__synced { color: var(--green, #22c55e); }++ &__actions {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+ padding-top: 8px;+ border-top: 1px solid var(--border-soft);+ }+ }++ .spin { animation: wp-plib-spin 0.9s linear infinite; }+}++@keyframes wp-plib-spin { to { transform: rotate(360deg); } }++// Shared by both modals on the library page.+.wp-plib-form {+ display: flex;+ flex-direction: column;+ gap: 16px;++ &__row {+ display: flex;+ flex-direction: column;+ gap: 6px;++ &--inline {+ flex-direction: row;+ align-items: center;+ gap: 10px;+ }+ }++ &__hint {+ font-weight: 400;+ font-size: 11px;+ color: var(--text-dim);+ }++ &__toggle {+ display: inline-flex;+ gap: 6px;++ button {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ font-size: 12.5px;+ padding: 6px 12px;+ border-radius: 6px;+ border: 1px solid var(--border-soft);+ background: transparent;+ color: var(--text-dim);+ cursor: pointer;++ &.is-on {+ border-color: var(--accent);+ color: var(--accent);+ background: var(--accent-bg, rgba(99, 102, 241, 0.12));+ }+ }+ }++ &__select {+ width: 100%;+ padding: 8px 10px;+ font-size: 13px;+ border-radius: 6px;+ border: 1px solid var(--border-soft);+ background: var(--surface);+ color: var(--text);+ }++ &__footer {+ display: flex;+ justify-content: flex-end;+ gap: 8px;+ padding-top: 4px;+ }+}diff --git a/frontend/src/styles/pages/_wordpress.scss b/frontend/src/styles/pages/_wordpress.scssindex 66695993..c5f83e1d 100644--- a/frontend/src/styles/pages/_wordpress.scss+++ b/frontend/src/styles/pages/_wordpress.scss@@ -3277,6 +3277,28 @@&:hover { opacity: 0.85; }&:disabled { opacity: 0.55; cursor: default; }++ // Library-backed update uses the accent tone to distinguish it from the+ // generic wp.org update flag.+ &--library {+ color: var(--accent);+ background: var(--accent-bg, rgba(99, 102, 241, 0.12));+ }+ }++ // "Managed" badge on plugins tracked by the global plugin library.+ .wp-managed-pill {+ display: inline-block;+ margin-left: 7px;+ font-size: 9.5px;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--accent);+ background: var(--accent-bg, rgba(99, 102, 241, 0.12));+ padding: 1px 6px;+ border-radius: 4px;+ vertical-align: middle;}.wp-theme-grid {