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
Add plugin contributions system, SDK, and integration
Juan Denisddcf0b2f5ff4
diff --git a/.gitignore b/.gitignoreindex 02d1c9d4..fcc34551 100644--- a/.gitignore+++ b/.gitignore@@ -113,3 +113,4 @@ UI_REPORT.mddocs/PLAN_AGENT_FLEET.md/docs/plans/.agents+/.extension-platform-plan/diff --git a/backend/app/api/marketplace.py b/backend/app/api/marketplace.pyindex c40fd5a8..5a0874bb 100644--- a/backend/app/api/marketplace.py+++ b/backend/app/api/marketplace.py@@ -91,6 +91,12 @@ def delete_extension(ext_id):@jwt_required()def install_extension(ext_id):user = get_current_user()+ # Marketplace installs now trigger a real plugin install when the+ # extension carries a source URL — that runs arbitrary downloaded+ # code and writes to disk, so it must require admin. /plugins/install+ # already enforces this; we mirror the check here.+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403data = request.get_json() or {}try:install = MarketplaceService.install_extension(ext_id, user.id, data.get('config'))diff --git a/backend/app/api/plugins.py b/backend/app/api/plugins.pyindex d33dc5b3..11deaa9d 100644--- a/backend/app/api/plugins.py+++ b/backend/app/api/plugins.py@@ -221,3 +221,104 @@ def disable_plugin(plugin_id):if not plugin:return jsonify({'error': 'Plugin not found'}), 404return jsonify(plugin.to_dict())+++@plugins_bp.route('/manifest-spec', methods=['GET'])+@jwt_required()+def get_manifest_spec():+ """Return the documented plugin.json contract.++ Used by SDK tooling, marketplace submissions, and the in-panel+ plugin developer UI to validate a manifest before install. The+ spec mirrors what `plugin_service` actually consumes — keep them+ in sync when extending the contract.+ """+ return jsonify({+ 'schema_version': '1.0',+ 'required': ['name', 'display_name', 'version'],+ 'fields': {+ 'name': {'type': 'string', 'pattern': '^[a-zA-Z0-9_-]+$',+ 'description': 'Filesystem-safe slug; also used as URL prefix default.'},+ 'display_name': {'type': 'string'},+ 'slug': {'type': 'string', 'description': 'Optional; defaults to `name`.'},+ 'version': {'type': 'string', 'description': 'Semver recommended.'},+ 'description': {'type': 'string'},+ 'author': {'type': 'string'},+ 'homepage': {'type': 'string'},+ 'repository': {'type': 'string'},+ 'license': {'type': 'string'},+ 'category': {'type': 'string',+ 'description': "monitoring|security|deployment|integration|ui|utility"},+ 'entry_point': {'type': 'string',+ 'description': "Backend blueprint ref, format 'module:bp_var'."},+ 'url_prefix': {'type': 'string',+ 'description': 'Defaults to /api/v1/<slug>.'},+ 'frontend_entry': {'type': 'string',+ 'description': 'Optional path within the frontend bundle (informational).'},+ 'permissions': {'type': 'array', 'items': {'type': 'string'},+ 'description': 'Declared host permissions (docker, shell, filesystem, network, db). Informational; surfaced to admins on install.'},+ 'templates': {'type': 'array',+ 'description': 'App-template ids to install on plugin install. String or {id, app_name?, variables?}.'},+ 'lifecycle': {'type': 'object',+ 'properties': {+ 'install': {'type': 'string', 'description': "module:func — runs after install."},+ 'uninstall': {'type': 'string', 'description': "module:func — runs before uninstall."},+ }},+ 'contributions': {+ 'type': 'object',+ 'properties': {+ 'nav': {'type': 'array', 'description': 'Sidebar items: {id, label, route, category, icon}.'},+ 'routes': {'type': 'array', 'description': 'SPA routes: {path, component}. component matches a named export of the plugin index module.'},+ 'page_titles': {'type': 'object', 'description': 'Map of route path → document title.'},+ 'command_palette': {'type': 'array', 'description': '{label, path, category, keywords}.'},+ 'widgets': {'type': 'array', 'description': '{slot, component}. slot=global renders globally inside DashboardLayout.'},+ },+ },+ },+ 'example': {+ 'name': 'serverkit-git',+ 'display_name': 'Git Server',+ 'version': '1.0.0',+ 'entry_point': 'blueprint:git_bp',+ 'url_prefix': '/api/v1/git',+ 'permissions': ['docker', 'filesystem'],+ 'templates': ['gitea'],+ 'lifecycle': {'install': 'lifecycle:on_install'},+ 'contributions': {+ 'nav': [{'id': 'git', 'label': 'Git', 'route': '/git',+ 'category': 'infrastructure',+ 'icon': '<circle cx="18" cy="18" r="3"/>'}],+ 'routes': [+ {'path': 'git', 'component': 'GitPage'},+ {'path': 'git/:tab', 'component': 'GitPage'},+ ],+ 'page_titles': {'/git': 'Git Repositories'},+ 'command_palette': [+ {'label': 'Git', 'path': '/git', 'category': 'Pages',+ 'keywords': 'repos deploy'},+ ],+ },+ },+ })+++@plugins_bp.route('/contributions', methods=['GET'])+@jwt_required()+def get_contributions():+ """Return merged UI contributions from all active plugins.++ Shape:+ {+ "nav": [...],+ "routes": [...],+ "page_titles": {...},+ "command_palette": [...],+ "widgets": [...]+ }++ Each item in the lists carries a `plugin` field with the source slug+ so the frontend can resolve component references against the correct+ plugin module.+ """+ from app.services.contribution_service import get_active_contributions+ return jsonify(get_active_contributions())diff --git a/backend/app/models/marketplace.py b/backend/app/models/marketplace.pyindex 9fb1e42f..484d7a81 100644--- a/backend/app/models/marketplace.py+++ b/backend/app/models/marketplace.py@@ -117,6 +117,28 @@ class ExtensionInstall(db.Model):self.config_json = json.dumps(v)def to_dict(self):+ # If a marketplace install also created an InstalledPlugin row+ # (because the marketplace bridge handed off to plugin_service),+ # surface the linked plugin's status so the UI can distinguish+ # "metadata-only install" from "files installed and serving" from+ # "install errored". Lookup is by extension slug (not FK) — same+ # source URL but kept loose to avoid coupling schemas.+ linked = None+ try:+ from app.models.plugin import InstalledPlugin+ ext = self.extension+ if ext:+ row = InstalledPlugin.query.filter_by(slug=ext.slug).first()+ if row:+ linked = {+ 'plugin_id': row.id,+ 'status': row.status,+ 'has_backend': row.has_backend,+ 'has_frontend': row.has_frontend,+ 'error_message': row.error_message,+ }+ except Exception:+ linked = Nonereturn {'id': self.id,'extension_id': self.extension_id,@@ -124,5 +146,6 @@ class ExtensionInstall(db.Model):'installed_version': self.installed_version,'config': self.config,'is_active': self.is_active,+ 'plugin': linked,'installed_at': self.installed_at.isoformat() if self.installed_at else None,}diff --git a/backend/app/models/plugin.py b/backend/app/models/plugin.pyindex b98b1170..9f04fa14 100644--- a/backend/app/models/plugin.py+++ b/backend/app/models/plugin.py@@ -64,6 +64,7 @@ class InstalledPlugin(db.Model):self.manifest_json = json.dumps(v)def to_dict(self):+ manifest = self.manifest or {}return {'id': self.id,'name': self.name,@@ -84,6 +85,13 @@ class InstalledPlugin(db.Model):'has_backend': self.has_backend,'status': self.status,'error_message': self.error_message,+ # Surface declarative manifest fields so the install UI can+ # show the user what they're approving without making a+ # second round-trip to fetch the manifest.+ 'permissions': manifest.get('permissions') or [],+ 'contributions': manifest.get('contributions') or {},+ 'templates': manifest.get('templates') or [],+ 'lifecycle': manifest.get('lifecycle') or {},'installed_at': self.installed_at.isoformat() if self.installed_at else None,'updated_at': self.updated_at.isoformat() if self.updated_at else None,}diff --git a/backend/app/plugins_sdk/__init__.py b/backend/app/plugins_sdk/__init__.pynew file mode 100644index 00000000..934e02d0--- /dev/null+++ b/backend/app/plugins_sdk/__init__.py@@ -0,0 +1,96 @@+"""+ServerKit Backend Plugin SDK.++Plugins should depend on names re-exported here rather than reaching into+host internals directly. As long as this surface stays stable, host-side+refactors don't break installed plugins.++Typical plugin module:++ from flask import Blueprint, request, jsonify+ from app.plugins_sdk import (+ db, jwt_required, current_user, audit, logger,+ )++ my_bp = Blueprint('my_plugin', __name__)+ log = logger(__name__)++ @my_bp.route('/things', methods=['GET'])+ @jwt_required()+ def list_things():+ user = current_user()+ # ... do work, use db.session, etc ...+ return jsonify({'ok': True})++The lifecycle hook contract (called by plugin_service when installing /+uninstalling): a single positional arg — the InstalledPlugin row.++ # In plugins/<slug>/lifecycle.py+ from app.plugins_sdk import db, logger+ log = logger(__name__)++ def on_install(plugin):+ log.info(f'Setting up {plugin.slug}')++ def on_uninstall(plugin):+ log.info(f'Tearing down {plugin.slug}')+"""+import logging++from app import db, jwt+from flask_jwt_extended import jwt_required, get_jwt_identity, get_jwt+++def current_user():+ """Return the current authenticated user, or None if no JWT context.++ Resolves the JWT identity (a stringified user id, per the host's+ @jwt.user_identity_loader) into a User row.+ """+ try:+ uid = get_jwt_identity()+ except Exception:+ return None+ if uid is None:+ return None+ from app.models.user import User+ try:+ return User.query.get(int(uid))+ except (TypeError, ValueError):+ return None+++def logger(name):+ """Return a logger scoped to a plugin module name."""+ return logging.getLogger(name)+++def audit(action, target_type, target_id=None, details=None, user_id=None):+ """Write an audit log entry from a plugin.++ Thin wrapper around AuditService so plugins don't have to know its+ import path. `user_id` defaults to the current authenticated user.+ """+ if user_id is None:+ u = current_user()+ user_id = u.id if u else None+ from app.services.audit_service import AuditService+ return AuditService.log(+ action=action,+ user_id=user_id,+ target_type=target_type,+ target_id=target_id,+ details=details or {},+ )+++__all__ = [+ 'db',+ 'jwt',+ 'jwt_required',+ 'get_jwt_identity',+ 'get_jwt',+ 'current_user',+ 'logger',+ 'audit',+]diff --git a/backend/app/services/contribution_service.py b/backend/app/services/contribution_service.pynew file mode 100644index 00000000..2720aa7d--- /dev/null+++ b/backend/app/services/contribution_service.py@@ -0,0 +1,68 @@+"""+Contribution Service - Aggregate active-plugin contributions for the UI.++A plugin manifest may declare a `contributions` block with any subset of:++ {+ "nav": [{ id, label, route, category, icon, ... }],+ "routes": [{ path, component }],+ "page_titles": { "/some-path": "Title" },+ "command_palette":[{ label, path, category, keywords }],+ "widgets": [{ slot, component }]+ }++Each entry is tagged with the source plugin's slug so the frontend knows+which plugin a contribution came from (for error attribution + matching+the `component` string against modules discovered by import.meta.glob).++Only plugins with status == 'active' contribute. A plugin without a+contributions block is silently skipped.+"""+from app.models.plugin import InstalledPlugin+++def _tag(items, slug):+ out = []+ for item in items or []:+ if not isinstance(item, dict):+ continue+ item = dict(item)+ item['plugin'] = slug+ out.append(item)+ return out+++def get_active_contributions():+ plugins = InstalledPlugin.query.filter_by(+ status=InstalledPlugin.STATUS_ACTIVE,+ ).all()++ nav = []+ routes = []+ page_titles = {}+ command_palette = []+ widgets = []++ for p in plugins:+ contrib = (p.manifest or {}).get('contributions') or {}+ if not isinstance(contrib, dict):+ continue++ nav.extend(_tag(contrib.get('nav'), p.slug))+ routes.extend(_tag(contrib.get('routes'), p.slug))+ command_palette.extend(_tag(contrib.get('command_palette'), p.slug))+ widgets.extend(_tag(contrib.get('widgets'), p.slug))++ titles = contrib.get('page_titles')+ if isinstance(titles, dict):+ for path, title in titles.items():+ if isinstance(path, str) and isinstance(title, str):+ page_titles[path] = title++ return {+ 'nav': nav,+ 'routes': routes,+ 'page_titles': page_titles,+ 'command_palette': command_palette,+ 'widgets': widgets,+ }diff --git a/backend/app/services/marketplace_service.py b/backend/app/services/marketplace_service.pyindex 154872f1..912d53bb 100644--- a/backend/app/services/marketplace_service.py+++ b/backend/app/services/marketplace_service.py@@ -132,6 +132,29 @@ class MarketplaceService:ext.download_count += 1db.session.commit()++ # Hand off to the plugin installer if we have a source we can fetch.+ # Marketplace rows historically only stored metadata; if a source+ # URL is set we now actually install the plugin so it contributes+ # its routes/sidebar/api like any other plugin.+ # `entry_point` doubles as a source URL for marketplace-hosted+ # plugins (the field is reused — admins paste a github/zip URL).+ source_url = (ext.entry_point or ext.repository or '').strip()+ if source_url:+ try:+ from app.services import plugin_service+ plugin_service.install_from_url(source_url, user_id=user_id)+ except Exception as e:+ # Roll back the marketplace install row so the user can+ # retry cleanly. The download counter increment also gets+ # undone via the rollback.+ db.session.rollback()+ logger.warning(+ f'Marketplace ext {ext.slug}: plugin install from '+ f'{source_url} failed: {e}'+ )+ raise ValueError(f'Plugin install failed: {e}')+return install@staticmethoddiff --git a/backend/app/services/plugin_service.py b/backend/app/services/plugin_service.pyindex 1accebde..2b9e46e3 100644--- a/backend/app/services/plugin_service.py+++ b/backend/app/services/plugin_service.py@@ -430,7 +430,21 @@ def _install_from_buffer(buf, source_url, source_type, user_id=None):if has_frontend:_regenerate_frontend_manifest()+ # Install template dependencies declared in manifest+ # (e.g. a "git-server" extension declaring "templates": ["gitea"]).+ # Best effort — record per-template result on the plugin row so the+ # UI can show what happened, but a template install failure does+ # not roll back the plugin install.+ template_results = _install_template_dependencies(plugin, manifest)++ # Run plugin's lifecycle.install hook if declared. Failure here is+ # also non-fatal — the plugin is installed; the hook is for+ # convenience setup (e.g. creating default rows).+ _run_lifecycle_hook(plugin, manifest, 'install')+logger.info(f'Plugin {slug} v{manifest["version"]} installed successfully')+ if template_results:+ plugin._template_install_results = template_results # surfaced via to_dict if neededreturn pluginexcept Exception as e:@@ -580,6 +594,11 @@ def uninstall_plugin(plugin_id):return Falseslug = plugin.slug+ manifest = plugin.manifest or {}++ # Run lifecycle.uninstall hook *before* we delete the files (the hook+ # may need to read its own files). Best effort — never block teardown.+ _run_lifecycle_hook(plugin, manifest, 'uninstall')# Remove backend filesbackend_dest = os.path.join(BACKEND_PLUGINS_DIR, slug)@@ -624,6 +643,110 @@ def disable_plugin(plugin_id):return plugin+def _run_lifecycle_hook(plugin, manifest, phase):+ """Execute a plugin's lifecycle hook.++ Manifest format:+ "lifecycle": { "install": "module:func", "uninstall": "module:func" }++ The module path is resolved under ``app.plugins.<slug>``. The hook+ receives the InstalledPlugin row as its single positional arg. Return+ value is ignored. Failure is logged and swallowed — lifecycle hooks+ are convenience, not correctness.+ """+ lifecycle = (manifest or {}).get('lifecycle') or {}+ target = lifecycle.get(phase)+ if not target or ':' not in target:+ return++ module_name, func_name = target.split(':', 1)+ full_module = f'app.plugins.{plugin.slug}.{module_name}'++ try:+ import importlib+ mod = importlib.import_module(full_module)+ func = getattr(mod, func_name, None)+ if not callable(func):+ logger.warning(+ f'Lifecycle {phase} hook {target} for {plugin.slug} is not callable'+ )+ return+ func(plugin)+ logger.info(f'Ran lifecycle.{phase} hook for {plugin.slug}')+ except Exception as e:+ logger.warning(f'Lifecycle {phase} hook for {plugin.slug} failed: {e}')+++def _install_template_dependencies(plugin, manifest):+ """Install app templates declared in the manifest's `templates` key.++ Format:+ "templates": ["gitea", "umami"] # template ids+ "templates": [{ "id": "gitea",+ "app_name": "git-server", # default: template id+ "variables": {"PORT": "3000"} }]++ Returns a list of {template_id, success, message} dicts. Failures are+ logged but do not abort the plugin install — the user can install the+ template manually from /templates if it didn't auto-install.+ """+ deps = (manifest or {}).get('templates') or []+ if not deps:+ return []++ try:+ from app.services.template_service import TemplateService+ except Exception as e:+ logger.warning(f'TemplateService unavailable; skipping template deps: {e}')+ return []++ results = []+ for dep in deps:+ if isinstance(dep, str):+ template_id, app_name, variables = dep, dep, {}+ elif isinstance(dep, dict):+ template_id = dep.get('id') or dep.get('template_id')+ app_name = dep.get('app_name') or template_id+ variables = dep.get('variables') or {}+ else:+ continue++ if not template_id:+ continue++ try:+ res = TemplateService.install_template(+ template_id=template_id,+ app_name=app_name,+ user_variables=variables,+ user_id=plugin.installed_by,+ )+ ok = bool(res and res.get('success'))+ results.append({+ 'template_id': template_id,+ 'success': ok,+ 'message': res.get('error') if not ok else 'installed',+ })+ if ok:+ logger.info(f'Plugin {plugin.slug} installed template {template_id}')+ else:+ logger.warning(+ f'Plugin {plugin.slug} template dep {template_id} failed: '+ f'{res.get("error")}'+ )+ except Exception as e:+ logger.warning(+ f'Plugin {plugin.slug} template dep {template_id} raised: {e}'+ )+ results.append({+ 'template_id': template_id,+ 'success': False,+ 'message': str(e),+ })++ return results++def list_plugins(status=None):"""List installed plugins."""query = InstalledPlugin.querydiff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex cb811e6a..496ecec9 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -24,10 +24,10 @@ import FTPServer from './pages/FTPServer';// Firewall is now part of Security pageimport Git from './pages/Git';import CronJobs from './pages/CronJobs';-import Security from './pages/Security';-import Services from './pages/Services';-import NewService from './pages/NewService';-import ServiceDetail from './pages/ServiceDetail';+import Security from './pages/Security';+import Services from './pages/Services';+import NewService from './pages/NewService';+import ServiceDetail from './pages/ServiceDetail';import Templates from './pages/Templates';import WorkflowBuilder from './pages/WorkflowBuilder';import Servers from './pages/Servers';@@ -41,8 +41,8 @@ import WordPressProjects from './pages/WordPressProjects';import WordPressProject from './pages/WordPressProject';import SSLCertificates from './pages/SSLCertificates';import Email from './pages/Email';-import SSOCallback from './pages/SSOCallback';-import SourceConnectionCallback from './pages/SourceConnectionCallback';+import SSOCallback from './pages/SSOCallback';+import SourceConnectionCallback from './pages/SourceConnectionCallback';import DatabaseMigration from './pages/DatabaseMigration';import AgentPlugins from './pages/AgentPlugins';import ServerTemplates from './pages/ServerTemplates';@@ -55,6 +55,8 @@ import StyleGuide from './pages/StyleGuide';import AppMap from './pages/AppMap';import Documentation from './pages/Documentation';import Deployments from './pages/Deployments';+import useExtensionRoutes from './plugins/ExtensionRoutes';+import { useContributions } from './plugins/contributions';// Page title mappingconst PAGE_TITLES = {@@ -62,13 +64,13 @@ const PAGE_TITLES = {'/login': 'Login','/register': 'Register','/setup': 'Setup',- '/services': 'Services',- '/services/new': 'New Service',+ '/services': 'Services',+ '/services/new': 'New Service','/apps': 'Applications','/wordpress': 'WordPress Sites','/wordpress/projects': 'WordPress Projects','/templates': 'Templates',- '/deployments': 'Deployment Activity',+ '/deployments': 'Deployment Activity','/workflow': 'Workflow Builder','/domains': 'Domains','/databases': 'Databases',@@ -85,8 +87,8 @@ const PAGE_TITLES = {'/security': 'Security','/email': 'Email Server','/terminal': 'Terminal',- '/settings': 'Settings',- '/connections/callback/github': 'GitHub Connection',+ '/settings': 'Settings',+ '/connections/callback/github': 'GitHub Connection','/migrate': 'Database Migration','/fleet': 'Agent Fleet','/fleet-monitor': 'Fleet Monitor',@@ -104,10 +106,11 @@ const PAGE_TITLES = {function PageTitleUpdater() {const location = useLocation();+ const { page_titles: pluginTitles } = useContributions();useEffect(() => {const path = location.pathname;- let title = PAGE_TITLES[path];+ let title = PAGE_TITLES[path] || (pluginTitles && pluginTitles[path]);// Handle dynamic routes and tab sub-routesif (!title) {@@ -115,6 +118,8 @@ function PageTitleUpdater() {const basePath = '/' + path.split('/')[1];if (PAGE_TITLES[basePath]) {title = PAGE_TITLES[basePath];+ } else if (pluginTitles && pluginTitles[basePath]) {+ title = pluginTitles[basePath];} else if (path.startsWith('/services/')) title = 'Service Details';else if (path.startsWith('/apps/')) title = 'Application Details';else if (path.startsWith('/servers/')) title = 'Server Details';@@ -124,7 +129,7 @@ function PageTitleUpdater() {}document.title = title ? `${title} | ServerKit` : 'ServerKit';- }, [location]);+ }, [location, pluginTitles]);return null;}@@ -183,6 +188,7 @@ function SetupRoute({ children }) {}function AppRoutes() {+ const extensionRoutes = useExtensionRoutes();return (<Routes><Route path="/migrate" element={<DatabaseMigration />} />@@ -201,25 +207,25 @@ function AppRoutes() {<SSOCallback /></PublicRoute>} />- <Route path="/register" element={- <PublicRoute>- <Register />- </PublicRoute>- } />- <Route path="/connections/callback/:provider" element={- <PrivateRoute>- <SourceConnectionCallback />- </PrivateRoute>- } />- <Route path="/" element={+ <Route path="/register" element={+ <PublicRoute>+ <Register />+ </PublicRoute>+ } />+ <Route path="/connections/callback/:provider" element={+ <PrivateRoute>+ <SourceConnectionCallback />+ </PrivateRoute>+ } />+ <Route path="/" element={<PrivateRoute><DashboardLayout /></PrivateRoute>}><Route index element={<Dashboard />} />- <Route path="services" element={<Services />} />- <Route path="services/new" element={<NewService />} />- <Route path="services/:id" element={<ServiceDetail />} />+ <Route path="services" element={<Services />} />+ <Route path="services/new" element={<NewService />} />+ <Route path="services/:id" element={<ServiceDetail />} /><Route path="apps" element={<Navigate to="/services" replace />} /><Route path="apps/:id" element={<ApplicationDetail />} /><Route path="apps/:id/:tab" element={<ApplicationDetail />} />@@ -276,6 +282,7 @@ function AppRoutes() {<Route path="terminal/:tab" element={<Terminal />} /><Route path="settings" element={<Settings />} /><Route path="settings/:tab" element={<Settings />} />+ {extensionRoutes}</Route></Routes>);diff --git a/frontend/src/components/CommandPalette.jsx b/frontend/src/components/CommandPalette.jsxindex ad930801..e21fb1eb 100644--- a/frontend/src/components/CommandPalette.jsx+++ b/frontend/src/components/CommandPalette.jsx@@ -9,6 +9,7 @@ import {CommandGroup,CommandItem,} from '@/components/ui/command';+import { useContributions } from '../plugins/contributions';const STATIC_PAGES = [{ label: 'Services', path: '/services', category: 'Pages', keywords: 'apps containers' },@@ -68,6 +69,7 @@ const CommandPalette = ({ open, onClose }) => {const [query, setQuery] = useState('');const [dynamicItems, setDynamicItems] = useState([]);const navigate = useNavigate();+ const { command_palette: pluginPaletteItems } = useContributions();// Fetch dynamic items (services/containers + servers) when openeduseEffect(() => {@@ -110,7 +112,17 @@ const CommandPalette = ({ open, onClose }) => {return () => { cancelled = true; };}, [open]);- const allItems = useMemo(() => [...STATIC_PAGES, ...dynamicItems], [dynamicItems]);+ const allItems = useMemo(() => {+ const fromPlugins = (pluginPaletteItems || [])+ .filter((it) => it && it.label && it.path)+ .map((it) => ({+ label: it.label,+ path: it.path,+ category: it.category || 'Extensions',+ keywords: it.keywords || '',+ }));+ return [...STATIC_PAGES, ...fromPlugins, ...dynamicItems];+ }, [dynamicItems, pluginPaletteItems]);const results = useMemo(() => {if (!query.trim()) return allItems.slice(0, 20);diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsxindex 4f828664..3501131a 100644--- a/frontend/src/components/Sidebar.jsx+++ b/frontend/src/components/Sidebar.jsx@@ -6,6 +6,7 @@ import { Star, Settings, LogOut, Sun, Moon, Monitor, ChevronRight, ChevronDown,import { api } from '../services/api';import ServerKitLogo from './ServerKitLogo';import { SIDEBAR_CATEGORIES, CATEGORY_LABELS, SIDEBAR_PRESETS, getVisibleItems, SIDEBAR_ITEMS } from './sidebarItems';+import { useContributions } from '../plugins/contributions';const Sidebar = () => {const { user, logout, updateUser } = useAuth();@@ -89,10 +90,22 @@ const Sidebar = () => {api.updateCurrentUser({ sidebar_config: config }).catch(() => {});};- const visibleItems = useMemo(- () => getVisibleItems(user?.sidebar_config),- [user?.sidebar_config]- );+ const { nav: pluginNav } = useContributions();++ const visibleItems = useMemo(() => {+ const core = getVisibleItems(user?.sidebar_config);+ // Merge contributed nav items, dedup by id (core wins). Plugins+ // can claim a category; default to 'system' so they always land+ // somewhere visible.+ const existingIds = new Set(core.map((i) => i.id));+ const fromPlugins = (pluginNav || [])+ .filter((item) => item && item.id && item.route && !existingIds.has(item.id))+ .map((item) => ({+ ...item,+ category: item.category || 'system',+ }));+ return [...core, ...fromPlugins];+ }, [user?.sidebar_config, pluginNav]);// Group visible items by categoryconst groupedItems = useMemo(() => {diff --git a/frontend/src/layouts/DashboardLayout.jsx b/frontend/src/layouts/DashboardLayout.jsxindex eb7a0a77..c7b0e9fe 100644--- a/frontend/src/layouts/DashboardLayout.jsx+++ b/frontend/src/layouts/DashboardLayout.jsx@@ -5,6 +5,7 @@ import CommandPalette from '../components/CommandPalette';import LogsDrawer from '../components/LogsDrawer';import { LogsDrawerProvider } from '../contexts/LogsDrawerContext';import PluginLoader from '../plugins/PluginLoader';+import { refreshContributions } from '../plugins/contributions';import api from '../services/api';const FULL_PAGE_ROUTES = ['/workflow', '/files', '/docker'];@@ -28,6 +29,13 @@ const DashboardLayout = () => {return () => document.removeEventListener('keydown', handleKeyDown);}, [handleKeyDown]);+ // Load plugin contributions once we're authenticated. Subscribers+ // (Sidebar, CommandPalette, ExtensionRoutes, PageTitleUpdater) all+ // pick up the result via useContributions().+ useEffect(() => {+ refreshContributions();+ }, []);+return (<LogsDrawerProvider><div className="dashboard-layout">diff --git a/frontend/src/plugins/ExtensionRoutes.jsx b/frontend/src/plugins/ExtensionRoutes.jsxnew file mode 100644index 00000000..757a9cfe--- /dev/null+++ b/frontend/src/plugins/ExtensionRoutes.jsx@@ -0,0 +1,43 @@+/**+ * Renders <Route> entries for each contributed route from active plugins.+ *+ * Used by App.jsx inside the authenticated dashboard branch — extension+ * routes are protected by the same PrivateRoute guard as core pages.+ *+ * A contributed route is { path, component, layout? }. We resolve+ * `component` against the plugin's index module exports. Routes whose+ * components don't resolve are silently skipped (logged in dev) so a+ * misconfigured plugin can't blow up the whole route tree.+ */+import { Route } from 'react-router-dom';+import { useContributions, resolveComponent } from './contributions';++function buildRoute(contrib, key) {+ const Component = resolveComponent(contrib.plugin, contrib.component);+ if (!Component) {+ if (import.meta.env.DEV) {+ console.warn(+ `[plugins] Cannot resolve component "${contrib.component}" `+ + `for plugin "${contrib.plugin}" (route ${contrib.path})`+ );+ }+ return null;+ }+ return (+ <Route+ key={key}+ path={contrib.path}+ element={<Component />}+ />+ );+}++// React Router v6 requires Route children to be static JSX siblings —+// returning a fragment of <Route>s from a function works because the+// parent <Routes> walks the tree.+export default function useExtensionRoutes() {+ const { routes } = useContributions();+ return (routes || [])+ .map((c, i) => buildRoute(c, `${c.plugin}:${c.path}:${i}`))+ .filter(Boolean);+}diff --git a/frontend/src/plugins/PluginLoader.jsx b/frontend/src/plugins/PluginLoader.jsxindex 34cc093e..1c154322 100644--- a/frontend/src/plugins/PluginLoader.jsx+++ b/frontend/src/plugins/PluginLoader.jsx@@ -1,77 +1,84 @@/**- * PluginLoader - Dynamically loads installed plugin components.+ * PluginLoader - Renders installed plugin widgets in the global slot.*- * Uses Vite's import.meta.glob to discover plugin entry points at build time.- * Plugins installed via the plugin system are placed in src/plugins/<slug>/- * and their components are auto-discovered here.+ * Two ways a plugin can show a widget:*- * Each plugin's index.js should export:- * - A default component (the widget/UI to render)- * - Optionally a Provider component for context wrapping+ * 1. Declarative (preferred): manifest contributions block —+ * "contributions": { "widgets": [{ "slot": "global",+ * "component": "MyWidget" }] }+ * The host fetches contributions at runtime and resolves the+ * `component` name against the plugin's index module exports.+ *+ * 2. Legacy auto-render: any plugin with a default export from+ * index.js gets rendered globally with no manifest required.+ * Kept for backward compatibility with plugins that predate+ * the contribution model.+ *+ * Plugins that declare a widget contribution opt out of the legacy+ * auto-render to avoid double-rendering.*/-import React, { Suspense, useMemo } from 'react';+import { useMemo } from 'react';+import { useContributions, resolveComponent, getPluginModule } from './contributions';-// Vite glob import: discovers all plugin index.js files at build time-// Each returns { default: Component, Provider?: Component }-const pluginModules = import.meta.glob('./**/index.js', { eager: true });+const pluginModules = import.meta.glob('./*/index.{js,jsx}', { eager: true });-/**- * Get all discovered plugins with their components.- */export function getInstalledPlugins() {const plugins = [];-for (const [path, mod] of Object.entries(pluginModules)) {- // path looks like "./serverkit-ai/index.js"- const match = path.match(/^\.\/([^/]+)\/index\.js$/);+ const match = path.match(/^\.\/([^/]+)\/index\.(?:js|jsx)$/);if (!match) continue;-const slug = match[1];- // Skip internal files- if (slug === 'PluginLoader') continue;-+ if (slug === 'PluginLoader' || slug === 'sdk') continue;plugins.push({slug,- Component: mod.default || mod.AiAssistant || null,- Provider: mod.AiAssistantProvider || mod.Provider || null,+ Component: mod.default || null,+ Provider: mod.Provider || null,module: mod,});}-return plugins;}-/**- * Renders all installed plugin widgets.- * Wraps each in its Provider if one is exported.- *- * @param {object} props- * @param {object} props.api - The ApiService instance to pass to plugins- */const PluginLoader = ({ api }) => {- const plugins = useMemo(() => getInstalledPlugins(), []);+ const { widgets } = useContributions();+ const legacyPlugins = useMemo(() => getInstalledPlugins(), []);- if (plugins.length === 0) return null;+ // Plugins that declare a widget contribution own their rendering+ // through that path; skip the legacy auto-render for them.+ const slugsWithDeclared = useMemo(() => {+ const set = new Set();+ for (const w of widgets || []) {+ if (w && w.plugin) set.add(w.plugin);+ }+ return set;+ }, [widgets]);- return (- <>- {plugins.map(({ slug, Component, Provider }) => {- if (!Component) return null;+ const declaredWidgets = (widgets || [])+ .filter((w) => w && (w.slot || 'global') === 'global')+ .map((w, i) => {+ const Component = resolveComponent(w.plugin, w.component);+ if (!Component) return null;+ const mod = getPluginModule(w.plugin);+ const Provider = (mod && mod.Provider) || null;+ const node = <Component key={`${w.plugin}:${w.component}:${i}`} api={api} />;+ return Provider+ ? <Provider key={`provider:${w.plugin}:${i}`}>{node}</Provider>+ : node;+ })+ .filter(Boolean);- const widget = <Component key={slug} api={api} />;+ const legacyWidgets = legacyPlugins+ .filter(({ slug, Component }) => Component && !slugsWithDeclared.has(slug))+ .map(({ slug, Component, Provider }) => {+ const node = <Component key={slug} api={api} />;+ return Provider+ ? <Provider key={`legacy-provider:${slug}`}>{node}</Provider>+ : node;+ });- if (Provider) {- return (- <Provider key={`provider-${slug}`}>- {widget}- </Provider>- );- }+ if (declaredWidgets.length === 0 && legacyWidgets.length === 0) return null;- return widget;- })}- </>- );+ return <>{declaredWidgets}{legacyWidgets}</>;};export default PluginLoader;diff --git a/frontend/src/plugins/contributions.js b/frontend/src/plugins/contributions.jsnew file mode 100644index 00000000..3167c0e2--- /dev/null+++ b/frontend/src/plugins/contributions.js@@ -0,0 +1,100 @@+/**+ * Plugin contribution loader.+ *+ * Source of truth for what an installed plugin contributes to the host UI:+ * - sidebar items+ * - SPA routes+ * - page titles+ * - command-palette entries+ * - global widgets+ *+ * The backend exposes the merged contribution envelope at+ * /api/v1/plugins/contributions. Each contribution carries the source+ * `plugin` slug; we resolve `component` strings against the plugin's+ * own index module (discovered at build time via import.meta.glob).+ *+ * Build-time discovery means a freshly installed plugin's frontend code+ * still requires `npm run build` to ship — that's the existing constraint+ * of the plugin system, not new here. Contribution metadata is dynamic+ * though, so toggling plugins on/off updates the UI without a rebuild.+ */+import { useEffect, useState } from 'react';+import api from '../services/api';++// Discover every plugin module at build time. Each plugin is expected to+// expose its components from src/plugins/<slug>/index.{js,jsx}.+const pluginModules = import.meta.glob('../plugins/*/index.{js,jsx}', { eager: true });++const moduleBySlug = (() => {+ const out = {};+ for (const [path, mod] of Object.entries(pluginModules)) {+ const m = path.match(/\/plugins\/([^/]+)\/index\.(?:js|jsx)$/);+ if (!m) continue;+ out[m[1]] = mod;+ }+ return out;+})();++export function getPluginModule(slug) {+ return moduleBySlug[slug] || null;+}++// Resolve a contribution's `component` string to an actual React component.+// `component` may be:+// - "default" → mod.default+// - "Foo" → mod.Foo (named export)+// Returns null if no match; caller decides whether to skip + warn.+export function resolveComponent(slug, name) {+ const mod = moduleBySlug[slug];+ if (!mod) return null;+ if (!name || name === 'default') return mod.default || null;+ return mod[name] || null;+}++const EMPTY = {+ nav: [],+ routes: [],+ page_titles: {},+ command_palette: [],+ widgets: [],+};++let cachedPromise = null;+let cachedValue = null;+const subscribers = new Set();++function notify(value) {+ cachedValue = value;+ for (const cb of subscribers) {+ try { cb(value); } catch { /* swallow subscriber errors */ }+ }+}++export function refreshContributions() {+ cachedPromise = api.getPluginContributions()+ .then((data) => {+ const merged = { ...EMPTY, ...(data || {}) };+ notify(merged);+ return merged;+ })+ .catch(() => {+ // No active plugins / endpoint missing / unauthenticated —+ // fall back to an empty envelope so the host renders normally.+ notify(EMPTY);+ return EMPTY;+ });+ return cachedPromise;+}++export function useContributions() {+ const [value, setValue] = useState(cachedValue || EMPTY);++ useEffect(() => {+ subscribers.add(setValue);+ if (!cachedPromise) refreshContributions();+ else if (cachedValue) setValue(cachedValue);+ return () => subscribers.delete(setValue);+ }, []);++ return value;+}diff --git a/frontend/src/plugins/sdk/index.js b/frontend/src/plugins/sdk/index.jsnew file mode 100644index 00000000..bc6b3a91--- /dev/null+++ b/frontend/src/plugins/sdk/index.js@@ -0,0 +1,48 @@+/**+ * ServerKit Plugin SDK+ *+ * Re-exports the core building blocks plugins need so they don't have to+ * reach into deep host paths. Plugins should import from this entry only:+ *+ * import { api, useToast, Button } from '../../sdk';+ *+ * If we ever rename or restructure the host, plugins keep working as+ * long as the SDK surface stays stable.+ *+ * What a plugin's frontend can ship:+ *+ * index.js / index.jsx — main module, exports named React+ * components matched by `component`+ * references in the manifest's+ * `contributions` block.+ * plugin.json — copy of the manifest, written by the+ * backend installer; included so Vite+ * can read static metadata at build+ * time if a plugin wants to.+ * styles/*.scss|css|less — auto-discovered and listed in+ * plugins-manifest.json.+ *+ * The host fetches /api/v1/plugins/contributions at runtime; each+ * contribution's `component` field is matched against the named exports+ * of this plugin's index module. A contribution with no matching export+ * is skipped (and logged in dev).+ */++export { api, default as defaultApi } from '../../services/api';++// Common UI primitives plugins are likely to want. Re-exports kept thin+// on purpose — plugins can still reach for niche components directly,+// but the everyday surface lives here.+export { useToast } from '../../contexts/ToastContext';+export { useAuth } from '../../contexts/AuthContext';+export { useTheme } from '../../contexts/ThemeContext';++// Routing helpers — plugin pages need these to navigate within the SPA.+export {+ Link,+ NavLink,+ useNavigate,+ useLocation,+ useParams,+ Outlet,+} from 'react-router-dom';diff --git a/frontend/src/services/api/plugins.js b/frontend/src/services/api/plugins.jsindex d0190942..419a277b 100644--- a/frontend/src/services/api/plugins.js+++ b/frontend/src/services/api/plugins.js@@ -49,3 +49,11 @@ export async function disablePlugin(pluginId) {method: 'POST',});}++// Returns the merged contribution envelope for active plugins:+// { nav, routes, page_titles, command_palette, widgets }+// Each list item carries a `plugin` slug field so the UI can resolve+// `component` references against the right plugin module.+export async function getPluginContributions() {+ return this.request('/plugins/contributions');+}diff --git a/frontend/vite.config.js b/frontend/vite.config.jsindex 0e8c1086..5526f13b 100644--- a/frontend/vite.config.js+++ b/frontend/vite.config.js@@ -12,6 +12,11 @@ export default defineConfig(({ mode }) => {resolve: {alias: {'@': fileURLToPath(new URL('./src', import.meta.url)),+ // Stable import path for plugin code:+ // import { api, useAuth } from 'serverkit-sdk';+ // Internal restructures of src/plugins/sdk are invisible+ // to plugins as long as the named exports stay stable.+ 'serverkit-sdk': fileURLToPath(new URL('./src/plugins/sdk/index.js', import.meta.url)),},},server: {