Skip to content

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.

refactor(wordpress): remove in-tree extension (extracted)

Juan Denise6008afb3848
diff --git a/builtin-extensions/serverkit-wordpress/backend/__init__.py b/builtin-extensions/serverkit-wordpress/backend/__init__.py
deleted file mode 100644
index 20eeca2f..00000000
--- a/builtin-extensions/serverkit-wordpress/backend/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-"""ServerKit WordPress extension backend package."""
diff --git a/builtin-extensions/serverkit-wordpress/backend/core_hooks.py b/builtin-extensions/serverkit-wordpress/backend/core_hooks.py
deleted file mode 100644
index e1981b1e..00000000
--- a/builtin-extensions/serverkit-wordpress/backend/core_hooks.py
+++ /dev/null
@@ -1,181 +0,0 @@
-"""Core-hook registrations for the WordPress extension (plan 52, D4).
-
-Core keeps the engines — backup policies/runs/restore, the event bus catalog,
-the template catalog/installer — and this extension supplies its entries at
-load time through the manifest ``core_hooks`` seam
-(``extension_lifecycle.register_capabilities`` calls :func:`register` at
-install and on every boot while the extension is active).
-
-Everything here is idempotent: ``register`` runs once per boot (and once per
-install), and possibly again after a test cleared a registry.
-
-Absent extension = feature absent, gracefully:
-- no ``wordpress_site`` backup target type (policies that reference it report
- "provider missing" instead of crashing),
-- no ``wordpress.*`` types in the event catalog,
-- no WordPress cards in the Templates grid, and template installs of the WP
- templates refuse with a clear provider-missing error.
-"""
-import logging
-import os
-
-logger = logging.getLogger(__name__)
-
-SLUG = 'serverkit-wordpress'
-
-# The wordpress.* lifecycle events this extension emits (emitted via
-# EventService.emit_wp from the git-deploy / create / safe-update flows).
-# Catalog registration only — emission never validates against the catalog.
-WP_EVENT_TYPES = [
- {'type': 'wordpress.site_down', 'category': 'WordPress', 'description': 'A WordPress site failed its health check'},
- {'type': 'wordpress.site_up', 'category': 'WordPress', 'description': 'A WordPress site recovered after a failed health check'},
- {'type': 'wordpress.created', 'category': 'WordPress', 'description': 'A WordPress site was created'},
- {'type': 'wordpress.deleted', 'category': 'WordPress', 'description': 'A WordPress site was deleted'},
- {'type': 'wordpress.backup_completed', 'category': 'WordPress', 'description': 'A WordPress site backup/snapshot completed'},
- {'type': 'wordpress.updated', 'category': 'WordPress', 'description': 'A WordPress safe-update completed'},
- {'type': 'wordpress.update_rolled_back', 'category': 'WordPress', 'description': 'A WordPress update was auto-rolled-back'},
- {'type': 'wordpress.deployed', 'category': 'WordPress', 'description': 'A WordPress git deploy completed'},
- {'type': 'wordpress.deploy_failed', 'category': 'WordPress', 'description': 'A WordPress git deploy failed'},
-]
-
-
-def register():
- """Register every WordPress entry into the core seams. Idempotent."""
- _register_backup_kind()
- _register_event_types()
- _register_template_provider()
-
-
-# --------------------------------------------------------------------------- #
-# Backup target kind: 'wordpress_site'
-# --------------------------------------------------------------------------- #
-
-def _register_backup_kind():
- from app.services import backup_kind_registry
- if backup_kind_registry.get('wordpress_site'):
- return
- backup_kind_registry.register(
- 'wordpress_site',
- resolve=_backup_resolve,
- execute=_backup_execute,
- restore=_backup_restore,
- label='WordPress site',
- restore_scopes=['full', 'files', 'database', 'tables'],
- )
-
-
-def _backup_resolve(policy):
- """Describe the live WordPress site behind a backup policy."""
- from app.models.wordpress_site import WordPressSite # core model (D1)
- from app.services.backup_policy_service import BackupPolicyError
- site = WordPressSite.query.get(policy.target_id)
- if not site:
- raise BackupPolicyError('WordPress site not found')
- app = site.application
- if not app or not app.root_path:
- raise BackupPolicyError('Target path not found')
- return {
- 'name': app.name, 'root_path': app.root_path,
- 'site': site, 'app': app,
- }
-
-
-def _backup_execute(policy, target, kind):
- """Produce a WordPress backup (files + database via wp-cli). Always full."""
- from app.services.backup_policy_service import (
- BackupPolicyError, BackupPolicyService,
- )
- from .wordpress_service import WordPressService
- result = WordPressService.backup_wordpress(target['root_path'], include_db=True)
- if not result.get('success'):
- raise BackupPolicyError(result.get('error') or 'WordPress backup failed')
- storage_path = result.get('backup_path')
- size = result.get('size') or BackupPolicyService._path_size(storage_path)
- meta = {
- 'kind': 'full', 'compression': 'gzip', 'incremental': False,
- 'backup_name': result.get('backup_name'), 'includes': ['files', 'database'],
- 'primary_archive': os.path.join(storage_path, 'files.tar.gz'),
- }
- return storage_path, size, meta
-
-
-def _backup_restore(policy, target, run, options):
- """Restore a WordPress backup. 'full' (and 'tables', for now) restores
- files + database; 'database' imports only the SQL dump; 'files' extracts
- only the file archive."""
- from app.services.backup_policy_service import BackupPolicyError
- from .wordpress_service import WordPressService
- scope = (options or {}).get('scope', 'full')
- meta = run.get_metadata() or {}
- backup_dir = run.storage_path
- root = target['root_path']
-
- if scope == 'database':
- db_sql = os.path.join(backup_dir or '', 'database.sql')
- if not os.path.exists(db_sql):
- raise BackupPolicyError('Database dump not found in this backup')
- result = WordPressService.wp_cli(root, ['db', 'import', db_sql])
- if not result.get('success'):
- raise BackupPolicyError(result.get('error') or 'Database restore failed')
- return
-
- if scope == 'files':
- files_archive = os.path.join(backup_dir or '', 'files.tar.gz')
- if not os.path.exists(files_archive):
- raise BackupPolicyError('Files archive not found in this backup')
- import tarfile
- with tarfile.open(files_archive, 'r:gz') as tar:
- tar.extractall(os.path.dirname(root.rstrip('/')) or '/', filter='data')
- return
-
- # full (or 'tables', approximated as full until per-table is implemented)
- backup_name = meta.get('backup_name') or (os.path.basename(backup_dir) if backup_dir else None)
- if not backup_name:
- raise BackupPolicyError('Backup archive not found')
- result = WordPressService.restore_backup(backup_name, root)
- if not result.get('success'):
- raise BackupPolicyError(result.get('error') or 'Restore failed')
-
-
-# --------------------------------------------------------------------------- #
-# Event catalog: wordpress.* types
-# --------------------------------------------------------------------------- #
-
-def _register_event_types():
- from app.services import event_service
- event_service.register_event_types(WP_EVENT_TYPES, source=SLUG)
-
-
-# --------------------------------------------------------------------------- #
-# Templates: 'wordpress' + 'wordpress-external-db'
-# --------------------------------------------------------------------------- #
-
-def _register_template_provider():
- from app.services.template_service import TemplateService
- TemplateService.register_template_provider(SLUG, validate=_validate_wp_template)
-
-
-def _validate_wp_template(template_id, variables):
- """Provider validate hook for the WP templates.
-
- The external-DB preflight (a live MySQL connection check before install)
- used to be a hardcoded ``template_id == 'wordpress-external-db'`` branch in
- core's TemplateService; it moved here with the rest of the WP coupling.
- Returns an error dict to veto the install, or None.
- """
- if template_id != 'wordpress-external-db':
- return None
- from app.services.template_service import TemplateService
- db_check = TemplateService.validate_mysql_connection(
- host=variables.get('DB_HOST'),
- port=variables.get('DB_PORT', '3306'),
- user=variables.get('DB_USER'),
- password=variables.get('DB_PASSWORD'),
- database=variables.get('DB_NAME'),
- )
- if not db_check.get('success'):
- return {
- 'success': False,
- 'error': f"Database connection failed: {db_check.get('error')}",
- }
- return None
diff --git a/builtin-extensions/serverkit-wordpress/backend/environment_pipeline.py b/builtin-extensions/serverkit-wordpress/backend/environment_pipeline.py
deleted file mode 100644
index d3dc7bbf..00000000
--- a/builtin-extensions/serverkit-wordpress/backend/environment_pipeline.py
+++ /dev/null
@@ -1,1716 +0,0 @@
-"""
-Environment Pipeline API
-
-REST endpoints for WordPress multi-environment management:
-- Project listing and pipeline overview
-- Environment CRUD and lifecycle (start/stop/restart)
-- Code/database promotion between environments
-- Sync from production
-- Environment comparison
-- Locking/unlocking
-- Activity log
-- Container logs
-"""
-
-import threading
-from flask import Blueprint, request, jsonify
-from flask_jwt_extended import jwt_required, get_jwt_identity
-
-from app import db, limiter
-from app.plugins_sdk import deploys
-from app.models.application import Application
-from app.models.wordpress_site import WordPressSite
-from app.models.environment_activity import EnvironmentActivity
-from app.models.promotion_job import PromotionJob
-from app.models.sanitization_profile import SanitizationProfile
-from app.services.environment_pipeline_service import EnvironmentPipelineService
-from app.services.environment_docker_service import EnvironmentDockerService
-from .git_wordpress_service import GitWordPressService
-
-environment_pipeline_bp = Blueprint('environment_pipeline', __name__)
-
-
-# =============================================================================
-# Helper: Verify ownership of a production site
-# =============================================================================
-
-def _get_production_site(prod_id, user_id):
- """Get a production site with ownership check.
-
- Returns (site, error_response) tuple.
- If site is found and owned by user, returns (site, None).
- Otherwise returns (None, error_response).
- """
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == prod_id,
- Application.user_id == user_id
- ).first()
-
- if not site:
- return None, (jsonify({'error': 'Project not found'}), 404)
-
- if not site.is_production and site.environment_type not in ('production', 'standalone'):
- return None, (jsonify({'error': 'Site is not a production environment'}), 400)
-
- return site, None
-
-
-def _get_environment_site(env_id, user_id):
- """Get an environment site with ownership check."""
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == env_id,
- Application.user_id == user_id
- ).first()
-
- if not site:
- return None, (jsonify({'error': 'Environment not found'}), 404)
-
- return site, None
-
-
-# =============================================================================
-# Project Listing
-# =============================================================================
-
-@environment_pipeline_bp.route('', methods=['GET'])
-@jwt_required()
-def list_projects():
- """List all WordPress projects with environment summary.
-
- Returns production sites with a count of child environments for each.
- """
- user_id = get_jwt_identity()
-
- sites = WordPressSite.query.join(Application).filter(
- Application.user_id == user_id,
- Application.app_type == 'wordpress',
- WordPressSite.is_production == True
- ).all()
-
- projects = []
- for site in sites:
- project = site.to_dict()
- project['environment_count'] = len(site.environments)
- project['environment_types'] = [
- e.environment_type for e in site.environments
- ]
- projects.append(project)
-
- return jsonify({
- 'projects': projects,
- 'total': len(projects)
- })
-
-
-# =============================================================================
-# Pipeline View
-# =============================================================================
-
-@environment_pipeline_bp.route('/<int:prod_id>/pipeline', methods=['GET'])
-@jwt_required()
-def get_pipeline(prod_id):
- """Get full pipeline view: all environments, statuses, last actions."""
- user_id = get_jwt_identity()
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- result = EnvironmentPipelineService.get_pipeline_status(prod_id)
- if not result.get('success'):
- return jsonify(result), 500
-
- return jsonify(result)
-
-
-# =============================================================================
-# Environment CRUD
-# =============================================================================
-
-@environment_pipeline_bp.route('/<int:prod_id>/environments', methods=['POST'])
-@jwt_required()
-def create_environment(prod_id):
- """Create a new environment (dev/staging/multidev).
-
- Body: {
- type: "development" | "staging" | "multidev",
- branch?: string, (required for multidev)
- domain?: string,
- clone_db?: boolean (default true),
- resource_limits?: { memory, cpus, db_memory, db_cpus },
- name?: string
- }
- """
- user_id = get_jwt_identity()
- data = request.get_json() or {}
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_type = data.get('type', 'development')
- if env_type not in ('development', 'staging', 'multidev'):
- return jsonify({'error': 'Invalid environment type. Must be development, staging, or multidev.'}), 400
-
- # Emit WebSocket event for operation start
- _emit_pipeline_event(prod_id, 'environment_creating', {
- 'type': env_type,
- 'message': f'Creating {env_type} environment...'
- })
-
- def progress_callback(progress_data):
- _emit_pipeline_event(prod_id, 'operation_progress', progress_data)
-
- result = EnvironmentPipelineService.create_project_environment(
- production_site_id=prod_id,
- env_type=env_type,
- config=data,
- user_id=user_id,
- progress_callback=progress_callback
- )
-
- # Emit completion event
- _emit_pipeline_event(prod_id, 'environment_created' if result.get('success') else 'environment_create_failed', {
- 'type': env_type,
- 'success': result.get('success', False),
- 'message': result.get('message') or result.get('error'),
- })
-
- if result.get('success'):
- return jsonify(result), 201
- else:
- return jsonify(result), 500
-
-
-@environment_pipeline_bp.route('/<int:prod_id>/environments/<int:env_id>', methods=['DELETE'])
-@jwt_required()
-def delete_environment(prod_id, env_id):
- """Delete an environment and all its resources."""
- user_id = get_jwt_identity()
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_site, error = _get_environment_site(env_id, user_id)
- if error:
- return error
-
- if env_site.production_site_id != prod_id:
- return jsonify({'error': 'Environment does not belong to this project'}), 400
-
- result = EnvironmentPipelineService.delete_environment(env_id, user_id=user_id)
-
- _emit_pipeline_event(prod_id, 'environment_deleted' if result.get('success') else 'environment_delete_failed', {
- 'env_id': env_id,
- 'success': result.get('success', False),
- 'message': result.get('message') or result.get('error'),
- })
-
- if result.get('success'):
- return jsonify(result)
- else:
- return jsonify(result), 500
-
-
-# =============================================================================
-# Container Lifecycle
-# =============================================================================
-
-@environment_pipeline_bp.route('/<int:prod_id>/environments/<int:env_id>/start', methods=['POST'])
-@jwt_required()
-def start_environment(prod_id, env_id):
- """Start an environment's containers."""
- user_id = get_jwt_identity()
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_site, error = _get_environment_site(env_id, user_id)
- if error:
- return error
-
- if env_site.production_site_id != prod_id:
- return jsonify({'error': 'Environment does not belong to this project'}), 400
-
- compose_path = EnvironmentPipelineService._get_compose_path(env_site)
- if not compose_path:
- return jsonify({'error': 'No Docker compose configuration found for this environment'}), 400
-
- result = EnvironmentDockerService.start_environment(compose_path)
-
- if result.get('success'):
- env_site.application.status = 'running'
- db.session.commit()
- _emit_pipeline_event(prod_id, 'environment_started', {'env_id': env_id})
-
- return jsonify(result) if result.get('success') else (jsonify(result), 500)
-
-
-@environment_pipeline_bp.route('/<int:prod_id>/environments/<int:env_id>/stop', methods=['POST'])
-@jwt_required()
-def stop_environment(prod_id, env_id):
- """Stop an environment's containers."""
- user_id = get_jwt_identity()
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_site, error = _get_environment_site(env_id, user_id)
- if error:
- return error
-
- if env_site.production_site_id != prod_id:
- return jsonify({'error': 'Environment does not belong to this project'}), 400
-
- compose_path = EnvironmentPipelineService._get_compose_path(env_site)
- if not compose_path:
- return jsonify({'error': 'No Docker compose configuration found for this environment'}), 400
-
- result = EnvironmentDockerService.stop_environment(compose_path)
-
- if result.get('success'):
- env_site.application.status = 'stopped'
- db.session.commit()
- _emit_pipeline_event(prod_id, 'environment_stopped', {'env_id': env_id})
-
- return jsonify(result) if result.get('success') else (jsonify(result), 500)
-
-
-@environment_pipeline_bp.route('/<int:prod_id>/environments/<int:env_id>/restart', methods=['POST'])
-@jwt_required()
-def restart_environment(prod_id, env_id):
- """Restart an environment's containers."""
- user_id = get_jwt_identity()
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_site, error = _get_environment_site(env_id, user_id)
- if error:
- return error
-
- if env_site.production_site_id != prod_id:
- return jsonify({'error': 'Environment does not belong to this project'}), 400
-
- compose_path = EnvironmentPipelineService._get_compose_path(env_site)
- if not compose_path:
- return jsonify({'error': 'No Docker compose configuration found for this environment'}), 400
-
- result = EnvironmentDockerService.restart_environment(compose_path)
-
- if result.get('success'):
- env_site.application.status = 'running'
- db.session.commit()
- _emit_pipeline_event(prod_id, 'environment_restarted', {'env_id': env_id})
-
- return jsonify(result) if result.get('success') else (jsonify(result), 500)
-
-
-# =============================================================================
-# Promotion
-# =============================================================================
-#
-# A promotion is deployment-shaped work: it takes minutes, changes what is
-# running, can fail halfway, and someone wants to watch it. So it runs as a
-# registered deployment kind (plugins_sdk.deploys) rather than in the request
-# thread — which gets it the Deploy Console, live logs, retry and a row in
-# Deploy Activity, and returns a job id the UI can open immediately.
-#
-# The PromotionJob rows the pipeline service writes are NOT replaced by this:
-# they carry pre_promotion_snapshot_id, the rollback pointer, which is WordPress
-# domain that a generic DeploymentJob has no business holding. The deployment
-# records which promotions it produced instead (see _promotions_since).
-
-PROMOTION_KIND = 'wordpress.promote'
-
-# Mirrors what EnvironmentPipelineService emits through progress_callback, so
-# the console's pipeline strip and its log lines agree step for step.
-_CODE_STEPS = ['Locking environments', 'Creating pre-promotion snapshot',
- 'Syncing code files', 'Flushing caches', 'Complete']
-_DATABASE_STEPS = ['Locking environments', 'Creating pre-promotion snapshot',
- 'Cloning database with transformations', 'Flushing caches', 'Complete']
-PROMOTION_STEPS = {
- 'code': _CODE_STEPS,
- 'database': _DATABASE_STEPS,
- # promote_full runs both halves back to back.
- 'full': [f'Code · {name}' for name in _CODE_STEPS]
- + [f'Database · {name}' for name in _DATABASE_STEPS],
-}
-
-
-def _promotion_progress(job, prod_id):
- """Bridge the pipeline service's progress into the console and the pipeline page.
-
- The service reports ``(step, total, message)``. A full promotion runs two
- five-step halves and restarts its numbering at 1 for the second, so copying
- the raw step number would send the console's strip backwards; carrying an
- offset across the reset keeps it moving forward. The original payload still
- goes out over the WebSocket, so the pipeline page's own progress bar behaves
- exactly as it did when this ran in the request thread.
- """
- state = {'last': 0, 'offset': 0}
-
- def emit(data):
- step = int(data.get('step') or 0)
- if step <= state['last']:
- state['offset'] += state['last']
- state['last'] = step
- deploys.progress(job, state['offset'] + step, data.get('message'))
- _emit_pipeline_event(prod_id, 'operation_progress', data)
-
- return emit
-
-
-def _promotions_since(watermark, source_id, target_id):
- """PromotionJob ids this run created, newest work last.
-
- Read by id watermark rather than from the service's return value because
- promote_* only reports the job on success — and a failed promotion is
- exactly when someone needs the row, since it holds the snapshot to roll
- back to.
- """
- rows = PromotionJob.query.filter(
- PromotionJob.id > watermark,
- PromotionJob.source_site_id == source_id,
- PromotionJob.target_site_id == target_id,
- ).order_by(PromotionJob.id).all()
- return [row.id for row in rows]
-
-
-def run_promotion(job):
- """Deployment handler for ``wordpress.promote``."""
- plan = job.get_plan() or {}
- prod_id = plan.get('prod_id')
- source_id = plan.get('source_env_id')
- target_id = plan.get('target_env_id')
- promotion_type = plan.get('promotion_type') or 'code'
-
- promote_fn = {
- 'code': EnvironmentPipelineService.promote_code,
- 'database': EnvironmentPipelineService.promote_database,
- 'full': EnvironmentPipelineService.promote_full,
- }.get(promotion_type)
- if promote_fn is None:
- # The endpoint validates the type, but a retry replays a stored plan.
- return {'success': False, 'error': f'Unknown promotion type: {promotion_type}'}
-
- watermark = db.session.query(db.func.max(PromotionJob.id)).scalar() or 0
- result = promote_fn(
- source_id, target_id,
- config=plan.get('config') or {},
- user_id=plan.get('user_id'),
- progress_callback=_promotion_progress(job, prod_id),
- ) or {}
-
- promotion_ids = _promotions_since(watermark, source_id, target_id)
- if promotion_ids:
- job.set_result({**(job.get_result() or {}), 'promotion_job_ids': promotion_ids})
- db.session.commit()
-
- succeeded = bool(result.get('success'))
- _emit_pipeline_event(prod_id, 'promotion_completed' if succeeded else 'promotion_failed', {
- 'source_env_id': source_id,
- 'target_env_id': target_id,
- 'type': promotion_type,
- 'success': succeeded,
- 'message': result.get('message') or result.get('error'),
- 'job_id': job.id,
- })
-
- if not succeeded:
- return {'success': False, 'error': result.get('error') or 'Promotion failed'}
-
- deploys.log(job, result.get('message') or 'Promotion complete')
- return {'success': True, 'message': result.get('message'),
- 'promotion_job_ids': promotion_ids}
-
-
-def register_deploy_kinds():
- """Contribute the promotion kind. Idempotent — safe to call per app setup."""
- deploys.register(PROMOTION_KIND, run_promotion, replace=True)
-
-
-register_deploy_kinds()
-
-
-@environment_pipeline_bp.route('/<int:prod_id>/promote', methods=['POST'])
-@jwt_required()
[email protected]("5 per minute")
-def promote(prod_id):
- """Queue a code/DB promotion between environments.
-
- Returns 202 with the deployment ``job_id`` — the work runs as a
- ``wordpress.promote`` deployment (see run_promotion above), so the caller
- can open /deployments/<job_id> for logs, steps and retry.
-
- Body: {
- source_env_id: int,
- target_env_id: int,
- type: "code" | "database" | "full",
- config: {
- include_plugins?: boolean,
- include_themes?: boolean,
- include_mu_plugins?: boolean,
- include_uploads?: boolean,
- backup_target_first?: boolean,
- search_replace?: { old: new },
- sanitize?: boolean,
- truncate_tables?: [string],
- exclude_tables?: [string]
- }
- }
- """
- user_id = get_jwt_identity()
- data = request.get_json() or {}
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- source_env_id = data.get('source_env_id')
- target_env_id = data.get('target_env_id')
- promotion_type = data.get('type', 'code')
-
- if not source_env_id or not target_env_id:
- return jsonify({'error': 'source_env_id and target_env_id are required'}), 400
-
- if promotion_type not in ('code', 'database', 'full'):
- return jsonify({'error': 'type must be code, database, or full'}), 400
-
- # Verify ownership of both environments
- source_site, error = _get_environment_site(source_env_id, user_id)
- if error:
- return error
-
- target_site, error = _get_environment_site(target_env_id, user_id)
- if error:
- return error
-
- # Verify both belong to this project (or are the production site itself)
- for env_site, label in [(source_site, 'Source'), (target_site, 'Target')]:
- if env_site.id != prod_id and env_site.production_site_id != prod_id:
- return jsonify({'error': f'{label} environment does not belong to this project'}), 400
-
- # The pipeline service checks the locks again when it runs (they can be
- # taken in between), but a lock we can already see should be answered here
- # rather than by sending the user to a console that fails a second later.
- for env_site, label in [(source_site, 'Source'), (target_site, 'Target')]:
- if env_site.is_locked:
- return jsonify({'error': f'{label} environment is locked: {env_site.locked_reason}'}), 400
-
- config = data.get('config', {})
-
- source_label = source_site.environment_type or 'source'
- target_label = target_site.environment_type or 'target'
-
- # Emit WebSocket event for operation start
- _emit_pipeline_event(prod_id, 'promotion_started', {
- 'source_env_id': source_env_id,
- 'target_env_id': target_env_id,
- 'type': promotion_type,
- 'message': f'Promoting {promotion_type} from {source_label} to {target_label}...'
- })
-
- result = deploys.start(
- PROMOTION_KIND,
- steps=PROMOTION_STEPS[promotion_type],
- app_id=target_site.application_id,
- user_id=user_id,
- plan={
- 'title': f'Promoting {promotion_type} from {source_label} to {target_label}',
- 'prod_id': prod_id,
- 'source_env_id': source_env_id,
- 'target_env_id': target_env_id,
- 'promotion_type': promotion_type,
- 'config': config,
- 'user_id': user_id,
- },
- )
-
- if not result.get('success'):
- # Queueing failed, so nothing will run — say so on the same channel a
- # failed promotion uses, or the page waits on an operation forever.
- _emit_pipeline_event(prod_id, 'promotion_failed', {
- 'source_env_id': source_env_id,
- 'target_env_id': target_env_id,
- 'type': promotion_type,
- 'success': False,
- 'message': result.get('error'),
- })
- return jsonify(result), 500
-
- # 202: the promotion is queued, not done. Progress arrives on the pipeline
- # socket as before, and job_id opens the full console at /deployments/<id>.
- return jsonify({
- 'success': True,
- 'queued': True,
- 'job_id': result['job_id'],
- 'message': f'Promotion queued: {promotion_type} from {source_label} to {target_label}',
- }), 202
-
-
-# =============================================================================
-# Sync from Production
-# =============================================================================
-
-@environment_pipeline_bp.route('/<int:prod_id>/environments/<int:env_id>/sync', methods=['POST'])
-@jwt_required()
[email protected]("5 per minute")
-def sync_environment(prod_id, env_id):
- """Pull from production into environment.
-
- Body: {
- type: "database" | "files" | "full",
- sanitize?: boolean,
- search_replace?: { old: new },
- truncate_tables?: [string],
- exclude_tables?: [string]
- }
- """
- user_id = get_jwt_identity()
- data = request.get_json() or {}
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_site, error = _get_environment_site(env_id, user_id)
- if error:
- return error
-
- if env_site.production_site_id != prod_id:
- return jsonify({'error': 'Environment does not belong to this project'}), 400
-
- sync_type = data.get('type', 'full')
- if sync_type not in ('database', 'files', 'full'):
- return jsonify({'error': 'type must be database, files, or full'}), 400
-
- _emit_pipeline_event(prod_id, 'sync_started', {
- 'env_id': env_id,
- 'type': sync_type,
- 'message': f'Syncing {sync_type} from production...'
- })
-
- def progress_callback(progress_data):
- _emit_pipeline_event(prod_id, 'operation_progress', progress_data)
-
- result = EnvironmentPipelineService.sync_from_production(
- env_site_id=env_id,
- sync_type=sync_type,
- options=data,
- user_id=user_id,
- progress_callback=progress_callback
- )
-
- _emit_pipeline_event(prod_id, 'sync_completed' if result.get('success') else 'sync_failed', {
- 'env_id': env_id,
- 'type': sync_type,
- 'success': result.get('success', False),
- 'message': result.get('message') or result.get('error'),
- })
-
- if result.get('success'):
- return jsonify(result)
- else:
- return jsonify(result), 500
-
-
-# =============================================================================
-# Environment Comparison
-# =============================================================================
-
-@environment_pipeline_bp.route('/<int:prod_id>/compare', methods=['GET'])
-@jwt_required()
-def compare_environments(prod_id):
- """Compare two environments (plugins, themes, versions).
-
- Query: ?env_a=:id&env_b=:id
- """
- user_id = get_jwt_identity()
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_a_id = request.args.get('env_a', type=int)
- env_b_id = request.args.get('env_b', type=int)
-
- if not env_a_id or not env_b_id:
- return jsonify({'error': 'env_a and env_b query parameters are required'}), 400
-
- # Verify ownership
- env_a, error = _get_environment_site(env_a_id, user_id)
- if error:
- return error
-
- env_b, error = _get_environment_site(env_b_id, user_id)
- if error:
- return error
-
- # Verify both belong to this project
- for env_site, label in [(env_a, 'env_a'), (env_b, 'env_b')]:
- if env_site.id != prod_id and env_site.production_site_id != prod_id:
- return jsonify({'error': f'{label} does not belong to this project'}), 400
-
- result = EnvironmentPipelineService.compare_environments(env_a_id, env_b_id)
- if result.get('success'):
- return jsonify(result)
- else:
- return jsonify(result), 500
-
-
-# =============================================================================
-# Environment Locking
-# =============================================================================
-
-@environment_pipeline_bp.route('/<int:prod_id>/environments/<int:env_id>/lock', methods=['POST'])
-@jwt_required()
-def lock_environment(prod_id, env_id):
- """Lock an environment.
-
- Body: {
- reason: string,
- duration_minutes?: int (default 30)
- }
- """
- user_id = get_jwt_identity()
- data = request.get_json() or {}
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_site, error = _get_environment_site(env_id, user_id)
- if error:
- return error
-
- if env_site.id != prod_id and env_site.production_site_id != prod_id:
- return jsonify({'error': 'Environment does not belong to this project'}), 400
-
- reason = data.get('reason', 'Manually locked')
- duration = data.get('duration_minutes', 30)
-
- result = EnvironmentPipelineService.lock_environment(
- site_id=env_id,
- reason=reason,
- user_id=user_id,
- duration_minutes=duration
- )
-
- if result.get('success'):
- _emit_pipeline_event(prod_id, 'environment_locked', {
- 'env_id': env_id,
- 'reason': reason,
- })
- return jsonify(result)
- else:
- return jsonify(result), 400
-
-
-@environment_pipeline_bp.route('/<int:prod_id>/environments/<int:env_id>/lock', methods=['DELETE'])
-@jwt_required()
-def unlock_environment(prod_id, env_id):
- """Unlock an environment."""
- user_id = get_jwt_identity()
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_site, error = _get_environment_site(env_id, user_id)
- if error:
- return error
-
- if env_site.id != prod_id and env_site.production_site_id != prod_id:
- return jsonify({'error': 'Environment does not belong to this project'}), 400
-
- result = EnvironmentPipelineService.unlock_environment(
- site_id=env_id,
- user_id=user_id
- )
-
- if result.get('success'):
- _emit_pipeline_event(prod_id, 'environment_unlocked', {'env_id': env_id})
- return jsonify(result)
- else:
- return jsonify(result), 400
-
-
-# =============================================================================
-# Activity Log
-# =============================================================================
-
-@environment_pipeline_bp.route('/<int:prod_id>/activity', methods=['GET'])
-@jwt_required()
-def get_activity(prod_id):
- """Activity log for all environments in project.
-
- Query: ?env_id=&action=&limit=50&offset=0
- """
- user_id = get_jwt_identity()
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- # Build query for all environments in this project
- env_ids = [prod_id] + [e.id for e in site.environments]
-
- # Filter by specific environment if requested
- filter_env_id = request.args.get('env_id', type=int)
- if filter_env_id:
- if filter_env_id not in env_ids:
- return jsonify({'error': 'Environment does not belong to this project'}), 400
- env_ids = [filter_env_id]
-
- query = EnvironmentActivity.query.filter(
- EnvironmentActivity.site_id.in_(env_ids)
- )
-
- # Filter by action
- action = request.args.get('action')
- if action:
- query = query.filter(EnvironmentActivity.action == action)
-
- # Pagination
- limit = request.args.get('limit', 50, type=int)
- offset = request.args.get('offset', 0, type=int)
-
- total = query.count()
- activities = query.order_by(
- EnvironmentActivity.created_at.desc()
- ).offset(offset).limit(limit).all()
-
- return jsonify({
- 'activities': [a.to_dict() for a in activities],
- 'total': total,
- 'limit': limit,
- 'offset': offset
- })
-
-
-# =============================================================================
-# Container Logs
-# =============================================================================
-
-@environment_pipeline_bp.route('/<int:prod_id>/environments/<int:env_id>/logs', methods=['GET'])
-@jwt_required()
-def get_container_logs(prod_id, env_id):
- """Docker container logs for environment.
-
- Query: ?service=wordpress|mysql&lines=100
- """
- user_id = get_jwt_identity()
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_site, error = _get_environment_site(env_id, user_id)
- if error:
- return error
-
- if env_site.production_site_id != prod_id:
- return jsonify({'error': 'Environment does not belong to this project'}), 400
-
- compose_path = EnvironmentPipelineService._get_compose_path(env_site)
- if not compose_path:
- return jsonify({'error': 'No Docker compose configuration found for this environment'}), 400
-
- service = request.args.get('service', 'wordpress')
- if service not in ('wordpress', 'db'):
- return jsonify({'error': 'service must be wordpress or db'}), 400
-
- lines = request.args.get('lines', 100, type=int)
- lines = min(lines, 1000) # Cap at 1000 lines
-
- result = EnvironmentDockerService.get_container_logs(compose_path, service=service, lines=lines)
- if result.get('success'):
- return jsonify(result)
- else:
- return jsonify(result), 500
-
-
-# =============================================================================
-# Promotion History
-# =============================================================================
-
-@environment_pipeline_bp.route('/<int:prod_id>/promotions', methods=['GET'])
-@jwt_required()
-def get_promotions(prod_id):
- """Get promotion history for a project.
-
- Query: ?limit=20&offset=0&status=
- """
- user_id = get_jwt_identity()
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_ids = [prod_id] + [e.id for e in site.environments]
-
- query = PromotionJob.query.filter(
- (PromotionJob.source_site_id.in_(env_ids)) |
- (PromotionJob.target_site_id.in_(env_ids))
- )
-
- status = request.args.get('status')
- if status:
- query = query.filter(PromotionJob.status == status)
-
- limit = request.args.get('limit', 20, type=int)
- offset = request.args.get('offset', 0, type=int)
-
- total = query.count()
- promotions = query.order_by(
- PromotionJob.created_at.desc()
- ).offset(offset).limit(limit).all()
-
- return jsonify({
- 'promotions': [p.to_dict() for p in promotions],
- 'total': total,
- 'limit': limit,
- 'offset': offset
- })
-
-
-@environment_pipeline_bp.route('/<int:prod_id>/promotions/<int:promotion_id>/rollback', methods=['POST'])
-@jwt_required()
[email protected]("5 per minute")
-def rollback_promotion(prod_id, promotion_id):
- """Restore a promotion's pre-promotion snapshot into its target environment."""
- user_id = get_jwt_identity()
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- job = PromotionJob.query.get(promotion_id)
- if not job:
- return jsonify({'error': 'Promotion not found'}), 404
-
- # The promotion must belong to this project (its source or target env).
- env_ids = [prod_id] + [e.id for e in site.environments]
- if job.source_site_id not in env_ids and job.target_site_id not in env_ids:
- return jsonify({'error': 'Promotion does not belong to this project'}), 400
-
- # Verify ownership of the target environment being restored.
- _, error = _get_environment_site(job.target_site_id, user_id)
- if error:
- return error
-
- _emit_pipeline_event(prod_id, 'rollback_started', {
- 'promotion_id': promotion_id,
- 'target_env_id': job.target_site_id,
- 'message': f'Rolling back promotion #{promotion_id}...',
- })
-
- result = EnvironmentPipelineService.rollback_promotion(
- promotion_id=promotion_id,
- user_id=user_id,
- )
-
- _emit_pipeline_event(prod_id, 'rollback_completed' if result.get('success') else 'rollback_failed', {
- 'promotion_id': promotion_id,
- 'target_env_id': job.target_site_id,
- 'success': result.get('success', False),
- 'message': result.get('message') or result.get('error'),
- })
-
- if result.get('success'):
- return jsonify(result)
- else:
- return jsonify(result), 500
-
-
-# =============================================================================
-# Environment Status (single environment detail)
-# =============================================================================
-
-@environment_pipeline_bp.route('/<int:prod_id>/environments/<int:env_id>', methods=['GET'])
-@jwt_required()
-def get_environment(prod_id, env_id):
- """Get detailed status for a single environment."""
- user_id = get_jwt_identity()
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_site, error = _get_environment_site(env_id, user_id)
- if error:
- return error
-
- if env_site.production_site_id != prod_id:
- return jsonify({'error': 'Environment does not belong to this project'}), 400
-
- env_data = env_site.to_dict(include_snapshots=True)
-
- # Add container status
- compose_path = EnvironmentPipelineService._get_compose_path(env_site)
- if compose_path:
- env_data['container_status'] = EnvironmentDockerService.get_environment_status(compose_path)
-
- # Add last promotion info
- last_promotion = PromotionJob.query.filter(
- (PromotionJob.source_site_id == env_id) |
- (PromotionJob.target_site_id == env_id)
- ).order_by(PromotionJob.created_at.desc()).first()
- if last_promotion:
- env_data['last_promotion'] = last_promotion.to_dict()
-
- # Add recent activity
- recent_activities = EnvironmentActivity.query.filter_by(
- site_id=env_id
- ).order_by(
- EnvironmentActivity.created_at.desc()
- ).limit(10).all()
- env_data['recent_activity'] = [a.to_dict() for a in recent_activities]
-
- return jsonify(env_data)
-
-
-# =============================================================================
-# Git Branches
-# =============================================================================
-
-@environment_pipeline_bp.route('/<int:prod_id>/git/branches', methods=['GET'])
-@jwt_required()
-def list_branches(prod_id):
- """List available git branches for multidev creation.
-
- Returns remote branches with latest commit info and whether
- a multidev environment already exists for each branch.
- """
- user_id = get_jwt_identity()
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- result = GitWordPressService.list_branches(prod_id)
- if result.get('success'):
- return jsonify(result)
- else:
- return jsonify(result), 400
-
-
-# =============================================================================
-# Multidev Cleanup
-# =============================================================================
-
-@environment_pipeline_bp.route('/<int:prod_id>/multidev/cleanup', methods=['POST'])
-@jwt_required()
-def cleanup_multidevs(prod_id):
- """Check for multidev environments with merged/deleted branches and clean them up.
-
- Body: {
- dry_run?: boolean (default true - only report, don't delete)
- }
- """
- user_id = get_jwt_identity()
- data = request.get_json() or {}
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- dry_run = data.get('dry_run', True)
-
- result = EnvironmentPipelineService.cleanup_stale_multidevs(
- production_site_id=prod_id,
- dry_run=dry_run,
- user_id=user_id
- )
-
- if result.get('success'):
- return jsonify(result)
- else:
- return jsonify(result), 500
-
-
-# =============================================================================
-# Sanitization Profiles
-# =============================================================================
-
-@environment_pipeline_bp.route('/sanitization-profiles', methods=['GET'])
-@jwt_required()
-def list_sanitization_profiles():
- """List all sanitization profiles for the current user.
-
- Automatically seeds built-in profiles on first access.
- """
- user_id = get_jwt_identity()
-
- # Seed built-in profiles if none exist
- existing = SanitizationProfile.query.filter_by(user_id=user_id).count()
- if existing == 0:
- SanitizationProfile.seed_builtins(user_id)
-
- profiles = SanitizationProfile.query.filter_by(
- user_id=user_id
- ).order_by(
- SanitizationProfile.is_builtin.desc(),
- SanitizationProfile.is_default.desc(),
- SanitizationProfile.name
- ).all()
-
- return jsonify({
- 'profiles': [p.to_dict() for p in profiles],
- 'total': len(profiles)
- })
-
-
-@environment_pipeline_bp.route('/sanitization-profiles', methods=['POST'])
-@jwt_required()
-def create_sanitization_profile():
- """Create a new sanitization profile.
-
- Body: {
- name: string,
- description?: string,
- config: { ... },
- is_default?: boolean
- }
- """
- user_id = get_jwt_identity()
- data = request.get_json() or {}
-
- name = data.get('name', '').strip()
- if not name:
- return jsonify({'error': 'Profile name is required'}), 400
-
- if len(name) > 100:
- return jsonify({'error': 'Profile name must be 100 characters or less'}), 400
-
- config = data.get('config', {})
- if not isinstance(config, dict):
- return jsonify({'error': 'Config must be a JSON object'}), 400
-
- # If setting as default, unset any existing default
- is_default = data.get('is_default', False)
- if is_default:
- SanitizationProfile.query.filter_by(
- user_id=user_id, is_default=True
- ).update({'is_default': False})
-
- import json
- profile = SanitizationProfile(
- user_id=user_id,
- name=name,
- description=data.get('description', ''),
- config=json.dumps(config),
- is_default=is_default,
- is_builtin=False,
- )
- db.session.add(profile)
- db.session.commit()
-
- return jsonify({
- 'success': True,
- 'profile': profile.to_dict()
- }), 201
-
-
-@environment_pipeline_bp.route('/sanitization-profiles/<int:profile_id>', methods=['PUT'])
-@jwt_required()
-def update_sanitization_profile(profile_id):
- """Update a sanitization profile.
-
- Body: {
- name?: string,
- description?: string,
- config?: { ... },
- is_default?: boolean
- }
- """
- user_id = get_jwt_identity()
- data = request.get_json() or {}
-
- profile = SanitizationProfile.query.filter_by(
- id=profile_id, user_id=user_id
- ).first()
-
- if not profile:
- return jsonify({'error': 'Profile not found'}), 404
-
- if 'name' in data:
- name = data['name'].strip()
- if not name:
- return jsonify({'error': 'Profile name is required'}), 400
- if len(name) > 100:
- return jsonify({'error': 'Profile name must be 100 characters or less'}), 400
- profile.name = name
-
- if 'description' in data:
- profile.description = data['description']
-
- if 'config' in data:
- if not isinstance(data['config'], dict):
- return jsonify({'error': 'Config must be a JSON object'}), 400
- import json
- profile.config = json.dumps(data['config'])
-
- if 'is_default' in data:
- if data['is_default']:
- SanitizationProfile.query.filter_by(
- user_id=user_id, is_default=True
- ).update({'is_default': False})
- profile.is_default = data['is_default']
-
- db.session.commit()
-
- return jsonify({
- 'success': True,
- 'profile': profile.to_dict()
- })
-
-
-@environment_pipeline_bp.route('/sanitization-profiles/<int:profile_id>', methods=['DELETE'])
-@jwt_required()
-def delete_sanitization_profile(profile_id):
- """Delete a sanitization profile. Built-in profiles cannot be deleted."""
- user_id = get_jwt_identity()
-
- profile = SanitizationProfile.query.filter_by(
- id=profile_id, user_id=user_id
- ).first()
-
- if not profile:
- return jsonify({'error': 'Profile not found'}), 404
-
- if profile.is_builtin:
- return jsonify({'error': 'Built-in profiles cannot be deleted'}), 400
-
- db.session.delete(profile)
- db.session.commit()
-
- return jsonify({
- 'success': True,
- 'message': f'Profile "{profile.name}" deleted'
- })
-
-
-# =============================================================================
-# Resource Limits
-# =============================================================================
-
-@environment_pipeline_bp.route('/<int:prod_id>/environments/<int:env_id>/resources', methods=['PUT'])
-@jwt_required()
-def update_resource_limits(prod_id, env_id):
- """Update memory/CPU limits for an environment, restart containers.
-
- Body: {
- memory: "512M",
- cpus: "1.0",
- db_memory: "384M",
- db_cpus: "0.5"
- }
- """
- user_id = get_jwt_identity()
- data = request.get_json() or {}
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_site, error = _get_environment_site(env_id, user_id)
- if error:
- return error
-
- if env_site.id != prod_id and env_site.production_site_id != prod_id:
- return jsonify({'error': 'Environment does not belong to this project'}), 400
-
- compose_path = EnvironmentPipelineService._get_compose_path(env_site)
- if not compose_path:
- return jsonify({'error': 'No Docker compose configuration found'}), 400
-
- import json as json_lib
- result = EnvironmentDockerService.update_resource_limits(compose_path, data)
-
- if result.get('success'):
- env_site.resource_limits = json_lib.dumps(data)
- db.session.commit()
- _emit_pipeline_event(prod_id, 'environment_restarted', {'env_id': env_id, 'reason': 'resource_limits_updated'})
- return jsonify({'success': True, 'message': 'Resource limits updated, containers restarted', 'limits': data})
- else:
- return jsonify(result), 500
-
-
-# =============================================================================
-# Basic Auth
-# =============================================================================
-
-@environment_pipeline_bp.route('/<int:prod_id>/environments/<int:env_id>/auth', methods=['POST'])
-@jwt_required()
-def enable_basic_auth(prod_id, env_id):
- """Enable Basic Auth for an environment. Returns generated credentials.
-
- Body: { username?: string } (password is auto-generated)
- """
- user_id = get_jwt_identity()
- data = request.get_json() or {}
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_site, error = _get_environment_site(env_id, user_id)
- if error:
- return error
-
- if env_site.id != prod_id and env_site.production_site_id != prod_id:
- return jsonify({'error': 'Environment does not belong to this project'}), 400
-
- from app.services.environment_domain_service import EnvironmentDomainService
- import secrets
- import string
-
- username = data.get('username', 'admin')
- password = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(16))
-
- # Determine site_name for Nginx config
- site_name = f'wp-{env_site.container_prefix}' if env_site.container_prefix else None
- if not site_name:
- return jsonify({'error': 'Cannot determine Nginx config name'}), 400
-
- result = EnvironmentDomainService.enable_basic_auth(site_name, username, password)
-
- if result.get('success'):
- env_site.basic_auth_enabled = True
- env_site.basic_auth_user = username
- env_site.basic_auth_password_hash = result.get('password_hash', '')
- db.session.commit()
-
- return jsonify({
- 'success': True,
- 'enabled': True,
- 'username': username,
- 'password': password,
- 'message': 'Basic Auth enabled. Save these credentials - password will not be shown again.'
- })
- else:
- return jsonify(result), 500
-
-
-@environment_pipeline_bp.route('/<int:prod_id>/environments/<int:env_id>/auth', methods=['DELETE'])
-@jwt_required()
-def disable_basic_auth(prod_id, env_id):
- """Disable Basic Auth for an environment."""
- user_id = get_jwt_identity()
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_site, error = _get_environment_site(env_id, user_id)
- if error:
- return error
-
- if env_site.id != prod_id and env_site.production_site_id != prod_id:
- return jsonify({'error': 'Environment does not belong to this project'}), 400
-
- from app.services.environment_domain_service import EnvironmentDomainService
-
- site_name = f'wp-{env_site.container_prefix}' if env_site.container_prefix else None
- if not site_name:
- return jsonify({'error': 'Cannot determine Nginx config name'}), 400
-
- result = EnvironmentDomainService.disable_basic_auth(site_name)
-
- if result.get('success'):
- env_site.basic_auth_enabled = False
- env_site.basic_auth_user = None
- env_site.basic_auth_password_hash = None
- db.session.commit()
- return jsonify({'success': True, 'enabled': False, 'message': 'Basic Auth disabled'})
- else:
- return jsonify(result), 500
-
-
-@environment_pipeline_bp.route('/<int:prod_id>/environments/<int:env_id>/auth', methods=['GET'])
-@jwt_required()
-def get_basic_auth_status(prod_id, env_id):
- """Get Basic Auth status for an environment."""
- user_id = get_jwt_identity()
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_site, error = _get_environment_site(env_id, user_id)
- if error:
- return error
-
- if env_site.id != prod_id and env_site.production_site_id != prod_id:
- return jsonify({'error': 'Environment does not belong to this project'}), 400
-
- return jsonify({
- 'enabled': env_site.basic_auth_enabled or False,
- 'username': env_site.basic_auth_user if env_site.basic_auth_enabled else None,
- })
-
-
-# =============================================================================
-# WP-CLI Execution
-# =============================================================================
-
-@environment_pipeline_bp.route('/<int:prod_id>/environments/<int:env_id>/exec', methods=['POST'])
-@jwt_required()
[email protected]("30 per minute")
-def execute_wp_cli(prod_id, env_id):
- """Execute a WP-CLI command in an environment container.
-
- Body: { command: "wp plugin list --format=table" }
- """
- user_id = get_jwt_identity()
- data = request.get_json() or {}
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_site, error = _get_environment_site(env_id, user_id)
- if error:
- return error
-
- if env_site.id != prod_id and env_site.production_site_id != prod_id:
- return jsonify({'error': 'Environment does not belong to this project'}), 400
-
- command = data.get('command', '').strip()
- if not command:
- return jsonify({'error': 'command is required'}), 400
-
- # Ensure command starts with 'wp'
- if not command.startswith('wp '):
- command = f'wp {command}'
-
- # Add --allow-root flag if not present
- if '--allow-root' not in command:
- command += ' --allow-root'
-
- compose_path = EnvironmentPipelineService._get_compose_path(env_site)
- if not compose_path:
- return jsonify({'error': 'No Docker compose configuration found'}), 400
-
- result = EnvironmentDockerService.exec_in_container(compose_path, 'wordpress', command)
-
- return jsonify({
- 'success': result.get('success', False),
- 'output': result.get('output', ''),
- 'error': result.get('error', ''),
- 'command': command,
- })
-
-
-# =============================================================================
-# Health Checks
-# =============================================================================
-
-@environment_pipeline_bp.route('/<int:prod_id>/environments/<int:env_id>/health', methods=['GET'])
-@jwt_required()
-def get_environment_health(prod_id, env_id):
- """Run and return health check results for an environment."""
- user_id = get_jwt_identity()
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_site, error = _get_environment_site(env_id, user_id)
- if error:
- return error
-
- if env_site.id != prod_id and env_site.production_site_id != prod_id:
- return jsonify({'error': 'Environment does not belong to this project'}), 400
-
- from app.services.environment_health_service import EnvironmentHealthService
- result = EnvironmentHealthService.check_health(env_id)
-
- if result.get('success'):
- return jsonify(result)
- else:
- return jsonify(result), 500
-
-
-@environment_pipeline_bp.route('/<int:prod_id>/health', methods=['GET'])
-@jwt_required()
-def get_project_health(prod_id):
- """Health summary for all project environments."""
- user_id = get_jwt_identity()
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- from app.services.environment_health_service import EnvironmentHealthService
- result = EnvironmentHealthService.check_all_project_health(prod_id)
-
- if result.get('success'):
- return jsonify(result)
- else:
- return jsonify(result), 500
-
-
-# =============================================================================
-# Disk Usage
-# =============================================================================
-
-@environment_pipeline_bp.route('/<int:prod_id>/environments/<int:env_id>/disk-usage', methods=['GET'])
-@jwt_required()
-def get_environment_disk_usage(prod_id, env_id):
- """Return disk usage breakdown for an environment."""
- user_id = get_jwt_identity()
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_site, error = _get_environment_site(env_id, user_id)
- if error:
- return error
-
- if env_site.id != prod_id and env_site.production_site_id != prod_id:
- return jsonify({'error': 'Environment does not belong to this project'}), 400
-
- from app.services.environment_health_service import EnvironmentHealthService
- result = EnvironmentHealthService.get_disk_usage(env_id)
-
- if result.get('success'):
- return jsonify(result)
- else:
- return jsonify(result), 500
-
-
-@environment_pipeline_bp.route('/<int:prod_id>/disk-usage', methods=['GET'])
-@jwt_required()
-def get_project_disk_usage(prod_id):
- """Disk usage for all project environments."""
- user_id = get_jwt_identity()
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- from app.services.environment_health_service import EnvironmentHealthService
- result = EnvironmentHealthService.get_disk_usage_for_project(prod_id)
-
- if result.get('success'):
- return jsonify(result)
- else:
- return jsonify(result), 500
-
-
-# =============================================================================
-# Bulk Operations
-# =============================================================================
-
-@environment_pipeline_bp.route('/<int:prod_id>/bulk', methods=['POST'])
-@jwt_required()
[email protected]("5 per minute")
-def bulk_operations(prod_id):
- """Execute bulk operations on multiple environments.
-
- Body: {
- operations: [
- { action: "stop"|"start"|"restart"|"sync", env_ids: [1, 2, 3] }
- ]
- }
- """
- user_id = get_jwt_identity()
- data = request.get_json() or {}
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- operations = data.get('operations', [])
- if not operations:
- return jsonify({'error': 'operations array is required'}), 400
-
- results = []
- env_ids_in_project = {prod_id} | {e.id for e in site.environments}
-
- for op in operations:
- action = op.get('action')
- env_ids = op.get('env_ids', [])
-
- if action not in ('stop', 'start', 'restart', 'sync'):
- results.append({'action': action, 'error': 'Invalid action'})
- continue
-
- op_results = []
- for env_id in env_ids:
- if env_id not in env_ids_in_project:
- op_results.append({'env_id': env_id, 'success': False, 'error': 'Not in this project'})
- continue
-
- env_site = WordPressSite.query.get(env_id)
- if not env_site:
- op_results.append({'env_id': env_id, 'success': False, 'error': 'Not found'})
- continue
-
- compose_path = EnvironmentPipelineService._get_compose_path(env_site)
- if not compose_path:
- op_results.append({'env_id': env_id, 'success': False, 'error': 'No compose config'})
- continue
-
- if action == 'stop':
- result = EnvironmentDockerService.stop_environment(compose_path)
- if result.get('success') and env_site.application:
- env_site.application.status = 'stopped'
- elif action == 'start':
- result = EnvironmentDockerService.start_environment(compose_path)
- if result.get('success') and env_site.application:
- env_site.application.status = 'running'
- elif action == 'restart':
- result = EnvironmentDockerService.restart_environment(compose_path)
- if result.get('success') and env_site.application:
- env_site.application.status = 'running'
- elif action == 'sync':
- result = EnvironmentPipelineService.sync_from_production(
- env_site_id=env_id, sync_type='full', user_id=user_id
- )
-
- op_results.append({
- 'env_id': env_id,
- 'success': result.get('success', False),
- 'message': result.get('message') or result.get('error'),
- })
-
- results.append({'action': action, 'results': op_results})
-
- db.session.commit()
-
- _emit_pipeline_event(prod_id, 'bulk_operation_completed', {
- 'operations': [op.get('action') for op in operations],
- })
-
- return jsonify({'success': True, 'results': results})
-
-
-# =============================================================================
-# Auto-Sync Schedule
-# =============================================================================
-
-@environment_pipeline_bp.route('/<int:prod_id>/environments/<int:env_id>/auto-sync', methods=['PUT'])
-@jwt_required()
-def update_auto_sync_schedule(prod_id, env_id):
- """Set/update auto-sync schedule for an environment.
-
- Body: {
- enabled: true,
- schedule: "0 3 * * *"
- }
- """
- user_id = get_jwt_identity()
- data = request.get_json() or {}
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_site, error = _get_environment_site(env_id, user_id)
- if error:
- return error
-
- if env_site.id != prod_id and env_site.production_site_id != prod_id:
- return jsonify({'error': 'Environment does not belong to this project'}), 400
-
- if env_site.is_production or env_site.environment_type == 'production':
- return jsonify({'error': 'Cannot set auto-sync on production environment'}), 400
-
- enabled = data.get('enabled', False)
- schedule = data.get('schedule', '')
-
- if enabled and not schedule:
- return jsonify({'error': 'schedule is required when enabled is true'}), 400
-
- # Validate cron expression
- if enabled and schedule:
- try:
- from croniter import croniter
- if not croniter.is_valid(schedule):
- return jsonify({'error': 'Invalid cron expression'}), 400
- except ImportError:
- # If croniter is not installed, do basic validation
- parts = schedule.split()
- if len(parts) != 5:
- return jsonify({'error': 'Invalid cron expression (must have 5 fields)'}), 400
-
- env_site.auto_sync_enabled = enabled
- env_site.auto_sync_schedule = schedule if enabled else None
- db.session.commit()
-
- return jsonify({
- 'success': True,
- 'enabled': enabled,
- 'schedule': schedule if enabled else None,
- 'message': f'Auto-sync {"enabled" if enabled else "disabled"}',
- })
-
-
-@environment_pipeline_bp.route('/<int:prod_id>/environments/<int:env_id>/auto-sync', methods=['GET'])
-@jwt_required()
-def get_auto_sync_schedule(prod_id, env_id):
- """Get current auto-sync schedule for an environment."""
- user_id = get_jwt_identity()
-
- site, error = _get_production_site(prod_id, user_id)
- if error:
- return error
-
- env_site, error = _get_environment_site(env_id, user_id)
- if error:
- return error
-
- if env_site.id != prod_id and env_site.production_site_id != prod_id:
- return jsonify({'error': 'Environment does not belong to this project'}), 400
-
- result = {
- 'enabled': env_site.auto_sync_enabled or False,
- 'schedule': env_site.auto_sync_schedule,
- }
-
- # Calculate next run times if enabled
- if env_site.auto_sync_enabled and env_site.auto_sync_schedule:
- try:
- from croniter import croniter
- from datetime import datetime
- cron = croniter(env_site.auto_sync_schedule, datetime.utcnow())
- result['next_runs'] = [
- cron.get_next(datetime).isoformat() for _ in range(3)
- ]
- except ImportError:
- result['next_runs'] = []
-
- return jsonify(result)
-
-
-# =============================================================================
-# WebSocket Helper
-# =============================================================================
-
-def _emit_pipeline_event(prod_id, event_type, data):
- """Emit a WebSocket event for pipeline operations.
-
- Events are broadcast to the room 'pipeline_{prod_id}'.
- """
- try:
- from app import get_socketio
- sio = get_socketio()
- if sio:
- import time
- sio.emit('pipeline_event', {
- 'project_id': prod_id,
- 'event': event_type,
- 'data': data,
- 'timestamp': time.time()
- }, room=f'pipeline_{prod_id}')
- except Exception:
- pass # WebSocket emit is best-effort, don't fail the request
diff --git a/builtin-extensions/serverkit-wordpress/backend/git_wordpress_service.py b/builtin-extensions/serverkit-wordpress/backend/git_wordpress_service.py
deleted file mode 100644
index e94cb3d7..00000000
--- a/builtin-extensions/serverkit-wordpress/backend/git_wordpress_service.py
+++ /dev/null
@@ -1,651 +0,0 @@
-"""
-Git WordPress Service
-
-Connect Git repositories to WordPress wp-content for theme/plugin management.
-Supports deployment from specific commits and creating dev environments for any revision.
-"""
-
-import os
-import subprocess
-import shutil
-import json
-from datetime import datetime
-from typing import Dict, List, Optional
-
-from app import db
-from app.models.wordpress_site import WordPressSite, DatabaseSnapshot
-from app.services.db_sync_service import DatabaseSyncService
-from .wordpress_env_service import WordPressEnvService
-
-
-class GitWordPressService:
- """Connect Git repositories to WordPress wp-content."""
-
- DEFAULT_PATHS = ['wp-content/themes', 'wp-content/plugins']
-
- @classmethod
- def connect_repo(cls, site_id: int, repo_url: str, branch: str = 'main',
- paths: List[str] = None, auto_deploy: bool = False) -> Dict:
- """
- Connect a Git repository to a WordPress site.
-
- Args:
- site_id: ID of the WordPressSite
- repo_url: Git repository URL (HTTPS or SSH)
- branch: Branch to track (default: main)
- paths: What to sync (default: ['wp-content/themes', 'wp-content/plugins'])
- auto_deploy: Enable automatic deployment on push
-
- Returns:
- Dict with success status
- """
- site = WordPressSite.query.get(site_id)
- if not site:
- return {'success': False, 'error': 'Site not found'}
-
- if not site.application or not site.application.root_path:
- return {'success': False, 'error': 'Site application path not found'}
-
- wp_path = site.application.root_path
- paths = paths or cls.DEFAULT_PATHS
-
- try:
- # Validate repository URL
- if not cls._validate_repo_url(repo_url):
- return {'success': False, 'error': 'Invalid repository URL'}
-
- # Test repository access
- test_result = cls._test_repo_access(repo_url)
- if not test_result['success']:
- return test_result
-
- # Initialize git in wp-content if not exists
- wp_content_path = os.path.join(wp_path, 'wp-content')
- git_result = cls._init_git_tracking(wp_content_path, repo_url, branch)
- if not git_result['success']:
- return git_result
-
- # Update site record
- site.git_repo_url = repo_url
- site.git_branch = branch
- site.git_paths = json.dumps(paths)
- site.auto_deploy = auto_deploy
-
- db.session.commit()
-
- return {
- 'success': True,
- 'message': f'Repository connected successfully',
- 'repo_url': repo_url,
- 'branch': branch,
- 'paths': paths
- }
-
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def disconnect_repo(cls, site_id: int) -> Dict:
- """
- Disconnect a Git repository from a WordPress site.
-
- Args:
- site_id: ID of the WordPressSite
-
- Returns:
- Dict with success status
- """
- site = WordPressSite.query.get(site_id)
- if not site:
- return {'success': False, 'error': 'Site not found'}
-
- try:
- # Remove git tracking from wp-content
- if site.application and site.application.root_path:
- wp_content_path = os.path.join(site.application.root_path, 'wp-content')
- git_dir = os.path.join(wp_content_path, '.git')
- if os.path.exists(git_dir):
- shutil.rmtree(git_dir)
-
- # Clear git settings
- site.git_repo_url = None
- site.git_branch = None
- site.git_paths = None
- site.auto_deploy = False
- site.last_deploy_commit = None
- site.last_deploy_at = None
-
- db.session.commit()
-
- return {'success': True, 'message': 'Repository disconnected'}
-
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def deploy_from_commit(cls, site_id: int, commit_sha: str = None,
- branch: str = None, create_snapshot: bool = True) -> Dict:
- """
- Deploy a specific commit or branch to the WordPress site.
-
- Args:
- site_id: ID of the WordPressSite
- commit_sha: Specific commit SHA to deploy (optional)
- branch: Branch name to deploy latest from (optional)
- create_snapshot: Create a database snapshot before deploying
-
- Returns:
- Dict with success status and deployment info
- """
- site = WordPressSite.query.get(site_id)
- if not site:
- return {'success': False, 'error': 'Site not found'}
-
- if not site.git_repo_url:
- return {'success': False, 'error': 'No repository connected'}
-
- if not site.application or not site.application.root_path:
- return {'success': False, 'error': 'Site application path not found'}
-
- wp_content_path = os.path.join(site.application.root_path, 'wp-content')
-
- try:
- # Create pre-deploy snapshot
- if create_snapshot:
- snapshot_result = DatabaseSyncService.create_snapshot(
- db_name=site.db_name,
- name=f"pre_deploy_{datetime.now().strftime('%Y%m%d_%H%M%S')}",
- tag='pre-deploy',
- commit_sha=site.last_deploy_commit,
- host=site.db_host,
- user=site.db_user,
- password=WordPressEnvService._get_db_password(site)
- )
-
- if snapshot_result['success']:
- # Save snapshot to database
- snapshot = DatabaseSnapshot(
- site_id=site.id,
- name=snapshot_result['snapshot']['name'],
- tag='pre-deploy',
- file_path=snapshot_result['snapshot']['file_path'],
- size_bytes=snapshot_result['snapshot']['size_bytes'],
- compressed=snapshot_result['snapshot']['compressed'],
- commit_sha=site.last_deploy_commit,
- tables_included=json.dumps(snapshot_result['snapshot'].get('tables', [])),
- row_count=snapshot_result['snapshot'].get('row_count', 0),
- status='completed'
- )
- db.session.add(snapshot)
-
- # Fetch latest from remote
- fetch_result = cls._run_git(wp_content_path, ['fetch', 'origin'])
- if not fetch_result['success']:
- return fetch_result
-
- # Determine what to checkout
- if commit_sha:
- target = commit_sha
- elif branch:
- target = f'origin/{branch}'
- else:
- target = f'origin/{site.git_branch}'
-
- # Checkout the target
- checkout_result = cls._run_git(wp_content_path, ['checkout', target, '--force'])
- if not checkout_result['success']:
- return checkout_result
-
- # Get the actual commit SHA we deployed
- rev_result = cls._run_git(wp_content_path, ['rev-parse', 'HEAD'])
- deployed_sha = rev_result['output'].strip() if rev_result['success'] else commit_sha
-
- # Get commit message
- msg_result = cls._run_git(wp_content_path, ['log', '-1', '--format=%s'])
- commit_message = msg_result['output'].strip() if msg_result['success'] else ''
-
- # Update site record
- site.last_deploy_commit = deployed_sha
- site.last_deploy_at = datetime.utcnow()
-
- db.session.commit()
-
- from app.services.event_service import EventService
- EventService.emit_wp('wordpress.deployed', site, commit_sha=deployed_sha, commit_message=commit_message)
- if create_snapshot and snapshot_result.get('success'):
- EventService.emit_wp('wordpress.backup_completed', site, tag='pre-deploy')
-
- return {
- 'success': True,
- 'message': 'Deployment successful',
- 'commit_sha': deployed_sha,
- 'commit_message': commit_message,
- 'pre_deploy_snapshot': snapshot_result.get('snapshot', {}).get('file_path') if create_snapshot else None
- }
-
- except Exception as e:
- db.session.rollback()
- try:
- from app.services.event_service import EventService
- EventService.emit_wp('wordpress.deploy_failed', site, error=str(e))
- except Exception:
- pass
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def create_dev_for_commit(cls, production_site_id: int, commit_sha: str,
- config: Dict, user_id: int) -> Dict:
- """
- Create a development environment for a specific commit.
-
- This creates a full dev environment with:
- - Database snapshot from nearest point in time (or current)
- - Code checked out at the specified commit
- - URL search-replace applied
-
- Args:
- production_site_id: ID of the production WordPressSite
- commit_sha: Git commit SHA to create dev for
- config: Environment configuration (name, domain, etc.)
- user_id: User ID creating the environment
-
- Returns:
- Dict with success status and dev environment info
- """
- prod_site = WordPressSite.query.get(production_site_id)
- if not prod_site:
- return {'success': False, 'error': 'Production site not found'}
-
- if not prod_site.is_production:
- return {'success': False, 'error': 'Source site is not a production site'}
-
- if not prod_site.git_repo_url:
- return {'success': False, 'error': 'No repository connected to production site'}
-
- try:
- # Get short SHA for naming
- short_sha = commit_sha[:7]
-
- # Set defaults in config
- if not config.get('name'):
- config['name'] = f"{prod_site.application.name} @ {short_sha}"
-
- if not config.get('domain'):
- # Try to create subdomain from production domain
- if prod_site.application.domains:
- prod_domain = prod_site.application.domains[0].domain
- config['domain'] = f"{short_sha}.dev.{prod_domain}"
-
- # Create the environment using WordPressEnvService
- env_result = WordPressEnvService.create_environment(
- production_site_id=production_site_id,
- env_type='development',
- config=config,
- user_id=user_id
- )
-
- if not env_result['success']:
- return env_result
-
- env_site_id = env_result['environment']['id']
- env_site = WordPressSite.query.get(env_site_id)
-
- # Checkout the specific commit
- if env_site and env_site.application:
- wp_content_path = os.path.join(env_site.application.root_path, 'wp-content')
-
- # Initialize git in the new environment
- init_result = cls._init_git_tracking(
- wp_content_path,
- prod_site.git_repo_url,
- prod_site.git_branch
- )
-
- if init_result['success']:
- # Fetch and checkout specific commit
- cls._run_git(wp_content_path, ['fetch', 'origin'])
- checkout_result = cls._run_git(wp_content_path, ['checkout', commit_sha, '--force'])
-
- if checkout_result['success']:
- env_site.last_deploy_commit = commit_sha
- env_site.last_deploy_at = datetime.utcnow()
- db.session.commit()
-
- return {
- 'success': True,
- 'message': f'Development environment created for commit {short_sha}',
- 'environment': env_site.to_dict() if env_site else env_result['environment'],
- 'commit_sha': commit_sha,
- 'url': f"https://{config.get('domain')}" if config.get('domain') else None
- }
-
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def get_recent_commits(cls, site_id: int, limit: int = 20) -> Dict:
- """
- Get recent commits from the repository.
-
- Args:
- site_id: ID of the WordPressSite
- limit: Maximum number of commits to return
-
- Returns:
- Dict with list of commits
- """
- site = WordPressSite.query.get(site_id)
- if not site:
- return {'success': False, 'error': 'Site not found'}
-
- if not site.git_repo_url:
- return {'success': False, 'error': 'No repository connected'}
-
- if not site.application or not site.application.root_path:
- return {'success': False, 'error': 'Site application path not found'}
-
- wp_content_path = os.path.join(site.application.root_path, 'wp-content')
-
- try:
- # Fetch latest
- cls._run_git(wp_content_path, ['fetch', 'origin'])
-
- # Get commit log
- log_format = '%H|%h|%s|%an|%ae|%ai'
- log_result = cls._run_git(wp_content_path, [
- 'log',
- f'origin/{site.git_branch}',
- f'-{limit}',
- f'--format={log_format}'
- ])
-
- if not log_result['success']:
- return log_result
-
- commits = []
- for line in log_result['output'].strip().split('\n'):
- if not line:
- continue
- parts = line.split('|')
- if len(parts) >= 6:
- commits.append({
- 'sha': parts[0],
- 'short_sha': parts[1],
- 'message': parts[2],
- 'author_name': parts[3],
- 'author_email': parts[4],
- 'date': parts[5],
- 'is_deployed': parts[0] == site.last_deploy_commit
- })
-
- return {
- 'success': True,
- 'commits': commits,
- 'current_deploy': site.last_deploy_commit
- }
-
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def list_branches(cls, site_id: int) -> Dict:
- """
- List remote branches for a site's connected repository.
-
- Args:
- site_id: ID of the WordPressSite
-
- Returns:
- Dict with list of branches and their latest commit info
- """
- site = WordPressSite.query.get(site_id)
- if not site:
- return {'success': False, 'error': 'Site not found'}
-
- if not site.git_repo_url:
- return {'success': False, 'error': 'No repository connected'}
-
- if not site.application or not site.application.root_path:
- return {'success': False, 'error': 'Site application path not found'}
-
- wp_content_path = os.path.join(site.application.root_path, 'wp-content')
- git_dir = os.path.join(wp_content_path, '.git')
-
- try:
- if os.path.exists(git_dir):
- # Fetch latest from remote
- cls._run_git(wp_content_path, ['fetch', '--prune', 'origin'])
-
- # List remote branches with latest commit info
- log_format = '%(refname:short)|%(objectname:short)|%(subject)|%(authorname)|%(creatordate:iso8601)'
- result = cls._run_git(wp_content_path, [
- 'for-each-ref',
- '--sort=-creatordate',
- f'--format={log_format}',
- 'refs/remotes/origin/'
- ])
- else:
- # No local clone — use ls-remote to list branches
- result = subprocess.run(
- ['git', 'ls-remote', '--heads', site.git_repo_url],
- capture_output=True, text=True, timeout=30
- )
- if result.returncode != 0:
- return {'success': False, 'error': f'Failed to list branches: {result.stderr}'}
-
- branches = []
- for line in result.stdout.strip().split('\n'):
- if not line:
- continue
- sha, ref = line.split('\t')
- branch_name = ref.replace('refs/heads/', '')
- branches.append({
- 'name': branch_name,
- 'short_sha': sha[:7],
- 'message': '',
- 'author': '',
- 'date': '',
- 'is_current': branch_name == site.git_branch,
- })
- return {'success': True, 'branches': branches}
-
- if not result['success']:
- return result
-
- branches = []
- existing_multidevs = set()
- for env in site.environments:
- if env.environment_type == 'multidev' and env.multidev_branch:
- existing_multidevs.add(env.multidev_branch)
-
- for line in result['output'].strip().split('\n'):
- if not line:
- continue
- parts = line.split('|')
- if len(parts) < 5:
- continue
-
- ref_name = parts[0]
- # Strip 'origin/' prefix
- branch_name = ref_name.replace('origin/', '', 1)
-
- # Skip HEAD pointer
- if branch_name == 'HEAD':
- continue
-
- branches.append({
- 'name': branch_name,
- 'short_sha': parts[1],
- 'message': parts[2],
- 'author': parts[3],
- 'date': parts[4],
- 'is_current': branch_name == site.git_branch,
- 'has_multidev': branch_name in existing_multidevs,
- })
-
- return {
- 'success': True,
- 'branches': branches,
- 'current_branch': site.git_branch,
- }
-
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def rollback_to_commit(cls, site_id: int, commit_sha: str) -> Dict:
- """
- Rollback a site to a previous commit.
-
- Args:
- site_id: ID of the WordPressSite
- commit_sha: Commit SHA to rollback to
-
- Returns:
- Dict with success status
- """
- # This is essentially the same as deploy_from_commit
- return cls.deploy_from_commit(site_id, commit_sha=commit_sha, create_snapshot=True)
-
- @classmethod
- def get_git_status(cls, site_id: int) -> Dict:
- """
- Get the Git status for a site.
-
- Args:
- site_id: ID of the WordPressSite
-
- Returns:
- Dict with Git status information
- """
- site = WordPressSite.query.get(site_id)
- if not site:
- return {'success': False, 'error': 'Site not found'}
-
- result = {
- 'success': True,
- 'connected': bool(site.git_repo_url),
- 'repo_url': site.git_repo_url,
- 'branch': site.git_branch,
- 'auto_deploy': site.auto_deploy,
- 'last_deploy_commit': site.last_deploy_commit,
- 'last_deploy_at': site.last_deploy_at.isoformat() if site.last_deploy_at else None,
- 'paths': json.loads(site.git_paths) if site.git_paths else None
- }
-
- if site.git_repo_url and site.application and site.application.root_path:
- wp_content_path = os.path.join(site.application.root_path, 'wp-content')
-
- # Check if there are uncommitted changes
- status_result = cls._run_git(wp_content_path, ['status', '--porcelain'])
- if status_result['success']:
- result['has_local_changes'] = bool(status_result['output'].strip())
-
- # Check if behind remote
- cls._run_git(wp_content_path, ['fetch', 'origin'])
- behind_result = cls._run_git(wp_content_path, [
- 'rev-list',
- '--count',
- f'HEAD..origin/{site.git_branch}'
- ])
- if behind_result['success']:
- result['commits_behind'] = int(behind_result['output'].strip() or 0)
-
- return result
-
- @classmethod
- def _validate_repo_url(cls, url: str) -> bool:
- """Validate a Git repository URL."""
- if not url:
- return False
-
- # Accept HTTPS URLs
- if url.startswith('https://'):
- return True
-
- # Accept SSH URLs
- if url.startswith('git@') or url.startswith('ssh://'):
- return True
-
- return False
-
- @classmethod
- def _test_repo_access(cls, repo_url: str) -> Dict:
- """Test if we can access the repository."""
- try:
- result = subprocess.run(
- ['git', 'ls-remote', '--exit-code', repo_url],
- capture_output=True,
- text=True,
- timeout=30
- )
-
- if result.returncode == 0:
- return {'success': True}
- else:
- return {
- 'success': False,
- 'error': f'Cannot access repository: {result.stderr or "Authentication failed or repository not found"}'
- }
-
- except subprocess.TimeoutExpired:
- return {'success': False, 'error': 'Connection to repository timed out'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def _init_git_tracking(cls, path: str, repo_url: str, branch: str) -> Dict:
- """Initialize Git tracking in a directory."""
- try:
- git_dir = os.path.join(path, '.git')
-
- if os.path.exists(git_dir):
- # Already initialized, just update remote
- cls._run_git(path, ['remote', 'set-url', 'origin', repo_url])
- else:
- # Initialize new repo
- init_result = cls._run_git(path, ['init'])
- if not init_result['success']:
- return init_result
-
- # Add remote
- remote_result = cls._run_git(path, ['remote', 'add', 'origin', repo_url])
- if not remote_result['success']:
- return remote_result
-
- # Fetch from remote
- fetch_result = cls._run_git(path, ['fetch', 'origin'])
- if not fetch_result['success']:
- return fetch_result
-
- return {'success': True}
-
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def _run_git(cls, cwd: str, args: List[str]) -> Dict:
- """Run a Git command."""
- try:
- cmd = ['git'] + args
- result = subprocess.run(
- cmd,
- cwd=cwd,
- capture_output=True,
- text=True,
- timeout=120
- )
-
- return {
- 'success': result.returncode == 0,
- 'output': result.stdout,
- 'error': result.stderr if result.returncode != 0 else None
- }
-
- except subprocess.TimeoutExpired:
- return {'success': False, 'error': 'Git command timed out'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
diff --git a/builtin-extensions/serverkit-wordpress/backend/wordpress.py b/builtin-extensions/serverkit-wordpress/backend/wordpress.py
deleted file mode 100644
index 70156b31..00000000
--- a/builtin-extensions/serverkit-wordpress/backend/wordpress.py
+++ /dev/null
@@ -1,1711 +0,0 @@
-# Bucket: PER-APP (plan 29 #9). Per-site WordPress routes gate on the linked
-# application's access seam: reads use can_access_app (owner/admin/any grant),
-# writes use can_edit_app (owner/admin/editor grant). The P0 <site_id> lifecycle
-# mutations and the previously-open <site_id>/<app_id> reads seal from open —
-# denial (or a missing resource) is an indistinguishable 404 (Decision 5). Host/
-# system ops (standalone install/uninstall/start/stop/restart, legacy install,
-# wp-cli, plugin library) stay @admin_required.
-import json
-from flask import Blueprint, request, jsonify
-from flask_jwt_extended import jwt_required, get_jwt_identity
-from app.middleware.rbac import admin_required, get_current_user
-from app.models import User, Application, WordPressSite
-from app.services.resource_grant_service import ResourceGrantService
-from .wordpress_service import WordPressService
-from app import db
-
-wordpress_bp = Blueprint('wordpress', __name__)
-
-
-def _resolve_app(site_or_app_id):
- """Resolve an ID to an Application. Tries WordPressSite first, then Application."""
- wp_site = WordPressSite.query.get(site_or_app_id)
- if wp_site and wp_site.application:
- return wp_site.application
- return Application.query.get(site_or_app_id)
-
-
-def _is_wp_app(app):
- """True if `app` is a WordPress-managed site. Containerized WP sites are
- stored with app_type 'docker' (see WordPressService), so app_type alone is
- not a reliable signal — a linked WordPressSite record is the source of truth.
- """
- if not app:
- return False
- if app.app_type == 'wordpress':
- return True
- return WordPressSite.query.filter_by(application_id=app.id).first() is not None
-
-
-def _guard_app(site_or_app_id, write=False):
- """Resolve a per-site WordPress route to its Application and enforce access,
- returning ``(app, None)`` or ``(None, error_response)``. Reads use
- can_access_app (owner/admin/any grant); writes use can_edit_app (owner/admin/
- editor grant). Denial is a 403 — used by the convergence reads that keep
- their status. A missing/non-WP resource is a 404."""
- app = _resolve_app(site_or_app_id)
- if not _is_wp_app(app):
- return None, (jsonify({'error': 'Application not found'}), 404)
- user = get_current_user()
- ok = (ResourceGrantService.can_edit_app(user, app) if write
- else ResourceGrantService.can_access_app(user, app))
- if not ok:
- return None, (jsonify({'error': 'Access denied'}), 403)
- return app, None
-
-
-def _guard_sealed_app(site_or_app_id, write=False):
- """Like :func:`_guard_app` but sealed-from-open (Decision 5): a missing
- resource OR an unauthorized caller both return an indistinguishable
- ``404 {'error': 'Not found'}`` so a foreign caller cannot probe existence.
- Used by the P0 <site_id> lifecycle mutations and the previously-open
- <site_id>/<app_id> reads."""
- app = _resolve_app(site_or_app_id)
- if not _is_wp_app(app):
- return None, (jsonify({'error': 'Not found'}), 404)
- user = get_current_user()
- ok = (ResourceGrantService.can_edit_app(user, app) if write
- else ResourceGrantService.can_access_app(user, app))
- if not ok:
- return None, (jsonify({'error': 'Not found'}), 404)
- return app, None
-
-
-# ==================== WORDPRESS SITES HUB ENDPOINTS ====================
-
-@wordpress_bp.route('/sites', methods=['GET'])
-@jwt_required()
-def list_sites():
- """List all WordPress sites (production sites with environment counts).
-
- Workspace-aware (#33): filters to the active workspace when one is supplied
- (X-Workspace-Id / ?workspace_id), via the site's parent application."""
- from app.services.workspace_service import WorkspaceService
- user = User.query.get(get_jwt_identity())
- ws_id = WorkspaceService.resolve_workspace_id(
- user, request.headers.get('X-Workspace-Id') or request.args.get('workspace_id'))
- result = WordPressService.get_sites(workspace_id=ws_id)
- return jsonify(result), 200
-
-
-@wordpress_bp.route('/sites', methods=['POST'])
-@jwt_required()
-def create_site():
- """Create a new WordPress site via Docker."""
- data = request.get_json() or {}
- name = data.get('name')
- admin_email = data.get('adminEmail', '')
- php_version = data.get('phpVersion') or None
- enable_page_cache = bool(data.get('enablePageCache'))
- enable_object_cache = bool(data.get('enableObjectCache'))
- domain = (data.get('domain') or '').strip()
- base_domain = (data.get('baseDomain') or data.get('base_domain') or '').strip()
-
- if not name:
- return jsonify({'error': 'Site name is required'}), 400
-
- if php_version and php_version not in WordPressService.get_available_php_versions():
- return jsonify({'error': f'Unsupported PHP version: {php_version}'}), 400
-
- current_user_id = get_jwt_identity()
- result = WordPressService.create_site(
- name, admin_email, current_user_id,
- php_version=php_version,
- enable_page_cache=enable_page_cache,
- enable_object_cache=enable_object_cache,
- domain=domain or None,
- base_domain=base_domain or None,
- )
-
- if result.get('success'):
- return jsonify(result), 201
- return jsonify(result), 400
-
-
-@wordpress_bp.route('/sites/import', methods=['POST'])
-@jwt_required()
-def import_site():
- """Import an existing WordPress site from an uploaded SQL dump plus an optional
- wp-content/full-site .zip (multipart)."""
- import os
- import tempfile
- name = request.form.get('name')
- admin_email = request.form.get('adminEmail', '')
- old_url = request.form.get('oldUrl', '').strip()
- if not name:
- return jsonify({'error': 'Site name is required'}), 400
- if not old_url:
- return jsonify({'error': 'Original site URL (old_url) is required for search-replace'}), 400
- if 'sql' not in request.files:
- return jsonify({'error': 'A .sql or .sql.gz database dump is required'}), 400
- sql_file = request.files['sql']
- if not sql_file.filename:
- return jsonify({'error': 'No SQL file selected'}), 400
- fname = sql_file.filename.lower()
- if not (fname.endswith('.sql') or fname.endswith('.sql.gz') or fname.endswith('.gz')):
- return jsonify({'error': 'Dump must be a .sql or .sql.gz file'}), 400
-
- # Optional wp-content / full-site zip (plugins/themes/uploads).
- zip_file = request.files.get('wp_content')
- if zip_file and zip_file.filename and not zip_file.filename.lower().endswith('.zip'):
- return jsonify({'error': 'wp-content archive must be a .zip file'}), 400
-
- suffix = '.sql.gz' if fname.endswith('.gz') else '.sql'
- fd, tmp_path = tempfile.mkstemp(suffix=suffix, prefix='wp_import_')
- os.close(fd)
- zip_tmp = None
- try:
- sql_file.save(tmp_path)
- if zip_file and zip_file.filename:
- zfd, zip_tmp = tempfile.mkstemp(suffix='.zip', prefix='wp_import_content_')
- os.close(zfd)
- zip_file.save(zip_tmp)
- current_user_id = get_jwt_identity()
- result = WordPressService.import_site(
- name=name,
- admin_email=admin_email,
- user_id=current_user_id,
- sql_path=tmp_path,
- old_url=old_url,
- wp_content_zip_path=zip_tmp,
- )
- finally:
- for p in (tmp_path, zip_tmp):
- if p:
- try:
- os.remove(p)
- except OSError:
- pass
- return (jsonify(result), 201) if result.get('success') else (jsonify(result), 400)
-
-
-@wordpress_bp.route('/sites/<int:site_id>', methods=['GET'])
-@jwt_required()
-def get_site(site_id):
- """Get site detail with environments."""
- _, err = _guard_sealed_app(site_id)
- if err:
- return err
- result = WordPressService.get_site(site_id)
- if 'error' in result:
- return jsonify(result), 404
- return jsonify(result), 200
-
-
-@wordpress_bp.route('/sites/<int:site_id>/clone', methods=['POST'])
-@jwt_required()
-def clone_site(site_id):
- """Clone a site into a new INDEPENDENT top-level site with fresh admin creds."""
- _, err = _guard_sealed_app(site_id, write=True)
- if err:
- return err
- data = request.get_json() or {}
- new_name = data.get('name')
- if not new_name:
- return jsonify({'error': 'New site name is required'}), 400
-
- current_user_id = get_jwt_identity()
- result = WordPressService.clone_site(site_id, new_name, current_user_id)
- if result.get('success'):
- return jsonify(result), 201
- return jsonify(result), 400
-
-
-@wordpress_bp.route('/sites/<int:site_id>/tags', methods=['PATCH'])
-@jwt_required()
-def set_site_tags(site_id):
- """Replace the tag list for a WordPress site."""
- _, err = _guard_sealed_app(site_id, write=True)
- if err:
- return err
- data = request.get_json() or {}
- tags = data.get('tags')
- if tags is None or not isinstance(tags, list):
- return jsonify({'error': 'tags must be a list'}), 400
-
- site = WordPressSite.query.get(site_id)
- if not site:
- return jsonify({'error': 'Site not found'}), 404
-
- # Normalize: strings only, trimmed, non-empty, de-duplicated (order-preserving)
- seen = set()
- cleaned = []
- for t in tags:
- if not isinstance(t, str):
- continue
- v = t.strip()
- if v and v.lower() not in seen:
- seen.add(v.lower())
- cleaned.append(v)
-
- import json as _json
- site.tags = _json.dumps(cleaned)
- db.session.commit()
- return jsonify({'success': True, 'tags': cleaned}), 200
-
-
-@wordpress_bp.route('/sites/<int:site_id>', methods=['DELETE'])
-@jwt_required()
-def delete_site(site_id):
- """Delete site and all its environments (takes a final backup by default)."""
- _, err = _guard_sealed_app(site_id, write=True)
- if err:
- return err
- # Back up before delete unless explicitly opted out via ?create_backup=false
- create_backup = request.args.get('create_backup', 'true').lower() != 'false'
- result = WordPressService.delete_site(site_id, create_backup=create_backup)
- if result.get('success'):
- return jsonify(result), 200
- return jsonify(result), 400
-
-
-@wordpress_bp.route('/sites/<int:site_id>/archive', methods=['POST'])
-@jwt_required()
-def archive_site(site_id):
- """Archive a site: stop the stack but keep all data. Reversible."""
- _, err = _guard_sealed_app(site_id, write=True)
- if err:
- return err
- result = WordPressService.archive_site(site_id)
- if result.get('success'):
- return jsonify(result), 200
- return jsonify(result), 400
-
-
-@wordpress_bp.route('/sites/<int:site_id>/unarchive', methods=['POST'])
-@jwt_required()
-def unarchive_site(site_id):
- """Restore a previously archived site."""
- _, err = _guard_sealed_app(site_id, write=True)
- if err:
- return err
- result = WordPressService.unarchive_site(site_id)
- if result.get('success'):
- return jsonify(result), 200
- return jsonify(result), 400
-
-
-@wordpress_bp.route('/sites/<int:site_id>/environments', methods=['GET'])
-@jwt_required()
-def list_environments(site_id):
- """List environments for a site."""
- _, err = _guard_sealed_app(site_id)
- if err:
- return err
- result = WordPressService.get_environments(site_id)
- if 'error' in result:
- return jsonify(result), 404
- return jsonify(result), 200
-
-
-@wordpress_bp.route('/sites/<int:site_id>/environments', methods=['POST'])
-@jwt_required()
-def create_environment(site_id):
- """Create a staging or development environment."""
- _, err = _guard_sealed_app(site_id, write=True)
- if err:
- return err
- data = request.get_json() or {}
- env_type = data.get('type', '')
-
- if not env_type:
- return jsonify({'error': 'Environment type is required'}), 400
-
- current_user_id = get_jwt_identity()
- result = WordPressService.create_environment(site_id, env_type, current_user_id)
-
- if result.get('success'):
- return jsonify(result), 201
- return jsonify(result), 400
-
-
-@wordpress_bp.route('/sites/<int:site_id>/environments/<int:env_id>', methods=['DELETE'])
-@jwt_required()
-def delete_environment(site_id, env_id):
- """Delete a non-production environment."""
- _, err = _guard_sealed_app(site_id, write=True)
- if err:
- return err
- result = WordPressService.delete_environment(env_id)
- if result.get('success'):
- return jsonify(result), 200
- return jsonify(result), 400
-
-
-# ==================== STANDALONE WORDPRESS (DOCKER) ENDPOINTS ====================
-
-@wordpress_bp.route('/standalone/status', methods=['GET'])
-@jwt_required()
-def get_standalone_status():
- """Get WordPress standalone installation status."""
- result = WordPressService.get_wordpress_standalone_status()
- return jsonify(result), 200
-
-
-@wordpress_bp.route('/standalone/requirements', methods=['GET'])
-@jwt_required()
-def get_standalone_requirements():
- """Get resource requirements for WordPress installation."""
- result = WordPressService.get_wordpress_resource_requirements()
- return jsonify(result), 200
-
-
-@wordpress_bp.route('/standalone/install', methods=['POST'])
-@jwt_required()
-@admin_required
-def install_standalone():
- """Install WordPress via Docker Compose."""
- data = request.get_json() or {}
-
- result = WordPressService.install_wordpress_standalone(
- admin_email=data.get('adminEmail')
- )
-
- if result.get('success'):
- return jsonify(result), 201
- return jsonify(result), 400
-
-
-@wordpress_bp.route('/standalone/uninstall', methods=['POST'])
-@jwt_required()
-@admin_required
-def uninstall_standalone():
- """Uninstall standalone WordPress and optionally remove data."""
- data = request.get_json() or {}
-
- result = WordPressService.uninstall_wordpress_standalone(
- remove_data=data.get('removeData', False)
- )
-
- if result.get('success'):
- return jsonify(result), 200
- return jsonify(result), 400
-
-
-@wordpress_bp.route('/standalone/start', methods=['POST'])
-@jwt_required()
-@admin_required
-def start_standalone():
- """Start WordPress containers."""
- result = WordPressService.start_wordpress_standalone()
-
- if result.get('success'):
- return jsonify(result), 200
- return jsonify(result), 400
-
-
-@wordpress_bp.route('/standalone/stop', methods=['POST'])
-@jwt_required()
-@admin_required
-def stop_standalone():
- """Stop WordPress containers."""
- result = WordPressService.stop_wordpress_standalone()
-
- if result.get('success'):
- return jsonify(result), 200
- return jsonify(result), 400
-
-
-@wordpress_bp.route('/standalone/restart', methods=['POST'])
-@jwt_required()
-@admin_required
-def restart_standalone():
- """Restart WordPress containers."""
- result = WordPressService.restart_wordpress_standalone()
-
- if result.get('success'):
- return jsonify(result), 200
- return jsonify(result), 400
-
-
-# ==================== LEGACY WP-CLI ENDPOINTS ====================
-
-
-@wordpress_bp.route('/install', methods=['POST'])
-@jwt_required()
-@admin_required
-def install_wordpress():
- """Install a new WordPress site."""
- data = request.get_json()
-
- if not data:
- return jsonify({'error': 'No data provided'}), 400
-
- required_fields = ['path', 'site_url', 'admin_email', 'db_name', 'db_user', 'db_password']
- missing = [f for f in required_fields if f not in data]
- if missing:
- return jsonify({'error': f'Missing required fields: {", ".join(missing)}'}), 400
-
- result = WordPressService.install_wordpress(data['path'], data)
-
- if result['success']:
- # Create application record
- current_user_id = get_jwt_identity()
- app = Application(
- name=data.get('site_title', 'WordPress Site'),
- app_type='wordpress',
- status='running',
- php_version=data.get('php_version', '8.2'),
- root_path=data['path'],
- user_id=current_user_id
- )
- db.session.add(app)
- db.session.commit()
- result['app_id'] = app.id
-
- return jsonify(result), 201 if result['success'] else 400
-
-
-@wordpress_bp.route('/sites/<int:app_id>/php', methods=['GET'])
-@jwt_required()
-def get_php(app_id):
- """Live PHP version + ini limits for a Docker WP site (read-only)."""
- current_user_id = get_jwt_identity()
- user = User.query.get(current_user_id)
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- if not ResourceGrantService.can_access_app(user, app):
- return jsonify({'error': 'Access denied'}), 403
- info = WordPressService.get_php_info(app.root_path)
- info['available_versions'] = WordPressService.get_available_php_versions()
- # The directives the limits panel may edit (#24 write side).
- info['editable_limits'] = list(WordPressService.get_php_limit_spec().keys())
- return jsonify({'php': info}), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/php', methods=['POST'])
-@jwt_required()
-@admin_required
-def set_php(app_id):
- """Switch the Docker WP site's PHP version (swaps image tag + recreates)."""
- app = _resolve_app(app_id)
- data = request.get_json() or {}
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- if app.app_type not in ('wordpress', 'docker'):
- return jsonify({'error': 'Application is not a WordPress site'}), 400
- version = data.get('version')
- if not version:
- return jsonify({'error': 'version is required'}), 400
- result = WordPressService.set_php_version(app.root_path, version)
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@wordpress_bp.route('/sites/<int:app_id>/php/limits', methods=['POST'])
-@jwt_required()
-@admin_required
-def set_php_limits(app_id):
- """Durably set per-site PHP ini limits (#24): writes a conf.d drop-in,
- bind-mounts it, and reloads the container. Body: {limits: {key: value, ...}}."""
- app = _resolve_app(app_id)
- data = request.get_json() or {}
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- if app.app_type not in ('wordpress', 'docker'):
- return jsonify({'error': 'Application is not a WordPress site'}), 400
- limits = data.get('limits')
- if not isinstance(limits, dict) or not limits:
- return jsonify({'error': 'limits object is required'}), 400
- result = WordPressService.set_php_limits(app.root_path, limits)
- return jsonify(result), 200 if result.get('success') else 400
-
-
-def _site_status_target(wp_site):
- """Best-effort public URL for a managed site's status-page component.
- Prefers a primary domain (https when SSL), falls back to the local port.
- The component is health-driven, so this is mainly cosmetic / manual-probe."""
- app = wp_site.application
- if not app:
- return ''
- try:
- domains = list(app.domains)
- except Exception:
- domains = []
- primary = next((d for d in domains if getattr(d, 'is_primary', False)),
- domains[0] if domains else None)
- if primary and getattr(primary, 'name', None):
- scheme = 'https' if getattr(primary, 'ssl_enabled', False) else 'http'
- return f'{scheme}://{primary.name}'
- # No public domain yet — leave the probe target empty rather than storing an
- # internal localhost:port (the component is health-driven, not network-probed).
- return ''
-
-
-@wordpress_bp.route('/sites/<int:app_id>/status-page', methods=['GET'])
-@jwt_required()
-def get_site_status_page(app_id):
- """Return the site's live health + bound status-page component (if any) and
- the status pages it can be attached to."""
- from app.models.status_page import StatusPage, StatusComponent
- current_user_id = get_jwt_identity()
- user = User.query.get(current_user_id)
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- if not ResourceGrantService.can_access_app(user, app):
- return jsonify({'error': 'Access denied'}), 403
- wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
- component = None
- if wp_site:
- comp = StatusComponent.query.filter_by(wordpress_site_id=wp_site.id).first()
- component = comp.to_dict() if comp else None
- pages = [{'id': p.id, 'name': p.name, 'slug': p.slug}
- for p in StatusPage.query.order_by(StatusPage.name).all()]
- return jsonify({
- 'health_status': wp_site.health_status if wp_site else None,
- 'last_health_check': (wp_site.last_health_check.isoformat()
- if wp_site and wp_site.last_health_check else None),
- 'component': component,
- 'pages': pages,
- }), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/status-page', methods=['POST'])
-@jwt_required()
-@admin_required
-def attach_site_status_page(app_id):
- """Attach a managed site to a status page as a health-driven component."""
- from app.models.status_page import StatusPage, StatusComponent
- from app.services.status_page_service import StatusPageService
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
- if not wp_site:
- return jsonify({'error': 'Not a WordPress site'}), 400
- if not wp_site.is_production:
- # The health poller only sweeps production sites, so a component bound to
- # a staging/dev environment would never accrue uptime — reject it.
- return jsonify({'error': 'Only production sites can be added to a status page'}), 400
- data = request.get_json() or {}
- page_id = data.get('page_id')
- if not page_id:
- return jsonify({'error': 'page_id is required'}), 400
- if not StatusPage.query.get(page_id):
- return jsonify({'error': 'Status page not found'}), 404
- existing = StatusComponent.query.filter_by(wordpress_site_id=wp_site.id).first()
- if existing:
- return jsonify({'error': 'Site is already on a status page',
- 'component': existing.to_dict()}), 409
- comp = StatusPageService.create_component(page_id, {
- 'name': app.name,
- 'group': 'WordPress',
- 'check_type': 'http',
- 'check_target': _site_status_target(wp_site),
- 'wordpress_site_id': wp_site.id,
- })
- return jsonify({'success': True, 'component': comp.to_dict()}), 201
-
-
-@wordpress_bp.route('/sites/<int:app_id>/status-page', methods=['DELETE'])
-@jwt_required()
-@admin_required
-def detach_site_status_page(app_id):
- """Detach a managed site from its status page (removes the bound component)."""
- from app.models.status_page import StatusComponent
- from app.services.status_page_service import StatusPageService
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
- if not wp_site:
- return jsonify({'error': 'Not a WordPress site'}), 400
- removed = 0
- for comp in StatusComponent.query.filter_by(wordpress_site_id=wp_site.id).all():
- StatusPageService.delete_component(comp.id)
- removed += 1
- return jsonify({'success': True, 'removed': removed}), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/analytics', methods=['GET'])
-@jwt_required()
-def get_site_analytics(app_id):
- """Per-site traffic + error analytics, parsed on-demand from the container's
- Apache access log (visits / bandwidth / status codes / 404s / bots / top URLs)."""
- from .wp_analytics_service import WpAnalyticsService
- current_user_id = get_jwt_identity()
- user = User.query.get(current_user_id)
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- if not ResourceGrantService.can_access_app(user, app):
- return jsonify({'error': 'Access denied'}), 403
- result = WpAnalyticsService.get_traffic(app.name, request.args.get('hours', 24))
- # PHP fatals/warnings from the WP_DEBUG log (#25 fatals; populated by #30's toggle).
- result['php_errors'] = WpAnalyticsService.get_php_errors(app.name)
- return jsonify(result), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/vulnerabilities', methods=['GET'])
-@jwt_required()
-def get_site_vulnerabilities(app_id):
- """Return persisted vulnerability findings + live scan status for a site."""
- from .wp_vulnerability_service import WpVulnerabilityService
- current_user_id = get_jwt_identity()
- user = User.query.get(current_user_id)
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- if not ResourceGrantService.can_access_app(user, app):
- return jsonify({'error': 'Access denied'}), 403
- wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
- if not wp_site:
- return jsonify({'error': 'Not a WordPress site'}), 400
- return jsonify(WpVulnerabilityService.get_results(wp_site)), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/vulnerabilities/scan', methods=['POST'])
-@jwt_required()
-@admin_required
-def scan_site_vulnerabilities(app_id):
- """Start a background vulnerability scan (cross-references the WPVulnerability feed)."""
- from .wp_vulnerability_service import WpVulnerabilityService
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
- if not wp_site:
- return jsonify({'error': 'Not a WordPress site'}), 400
- return jsonify(WpVulnerabilityService.start_scan(wp_site)), 200
-
-
-# ---- Per-site security depth (#30): file integrity, WP_DEBUG, WP-Cron ----
-
-def _owner_or_admin_app(app_id):
- """Resolve an app and enforce the access guard: owner, admin, or a user the
- app was shared with via a per-resource grant (#33). Returns (app, None) or
- (None, (response, status))."""
- user = User.query.get(get_jwt_identity())
- app = _resolve_app(app_id)
- if not app:
- return None, (jsonify({'error': 'Application not found'}), 404)
- # user.id (int), not the stringified token id; honor per-resource grants.
- if not user.is_admin and app.user_id != user.id:
- from app.services.resource_grant_service import ResourceGrantService
- if not ResourceGrantService.user_has_grant(user.id, 'application', app.id):
- return None, (jsonify({'error': 'Access denied'}), 403)
- return app, None
-
-
-@wordpress_bp.route('/sites/<int:app_id>/integrity', methods=['GET'])
-@jwt_required()
-def get_site_integrity(app_id):
- """Return the latest file-integrity result + scan status for a site."""
- from .wp_security_service import WpSecurityService
- app, err = _owner_or_admin_app(app_id)
- if err:
- return err
- wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
- if not wp_site:
- return jsonify({'error': 'Not a WordPress site'}), 400
- return jsonify(WpSecurityService.get_integrity(wp_site.id)), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/integrity/scan', methods=['POST'])
-@jwt_required()
-@admin_required
-def scan_site_integrity(app_id):
- """Start a background file-integrity check (wp core/plugin verify-checksums)."""
- from .wp_security_service import WpSecurityService
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
- if not wp_site:
- return jsonify({'error': 'Not a WordPress site'}), 400
- return jsonify(WpSecurityService.start_integrity_scan(wp_site)), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/debug', methods=['GET'])
-@jwt_required()
-def get_site_debug(app_id):
- """Return the site's WP_DEBUG / WP_DEBUG_LOG / SCRIPT_DEBUG state."""
- from .wp_security_service import WpSecurityService
- app, err = _owner_or_admin_app(app_id)
- if err:
- return err
- return jsonify(WpSecurityService.get_debug(app.root_path)), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/debug', methods=['POST'])
-@jwt_required()
-@admin_required
-def set_site_debug(app_id):
- """Toggle debug logging (WP_DEBUG/WP_DEBUG_LOG/SCRIPT_DEBUG on; display always off)."""
- from .wp_security_service import WpSecurityService
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- enabled = bool((request.get_json() or {}).get('enabled'))
- return jsonify(WpSecurityService.set_debug(app.root_path, enabled)), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/cron', methods=['GET'])
-@jwt_required()
-def get_site_cron(app_id):
- """Return WP-Cron status (DISABLE_WP_CRON + due events)."""
- from .wp_security_service import WpSecurityService
- app, err = _owner_or_admin_app(app_id)
- if err:
- return err
- return jsonify(WpSecurityService.get_cron(app.root_path)), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/cron/run', methods=['POST'])
-@jwt_required()
-@admin_required
-def run_site_cron(app_id):
- """Run all due WP-Cron events now."""
- from .wp_security_service import WpSecurityService
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- return jsonify(WpSecurityService.run_cron(app.root_path)), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/cron', methods=['POST'])
-@jwt_required()
-@admin_required
-def set_site_cron(app_id):
- """Enable/disable WP's pseudo-cron (DISABLE_WP_CRON)."""
- from .wp_security_service import WpSecurityService
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- disabled = bool((request.get_json() or {}).get('disabled'))
- return jsonify(WpSecurityService.set_cron_disabled(app.root_path, disabled)), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/security/bruteforce', methods=['GET'])
-@jwt_required()
-def get_site_bruteforce(app_id):
- """Per-site login brute-force status: fail2ban availability, jail on/off, bans."""
- from .wp_security_service import WpSecurityService
- app, err = _owner_or_admin_app(app_id)
- if err:
- return err
- wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
- if not wp_site:
- return jsonify({'error': 'Not a WordPress site'}), 400
- return jsonify(WpSecurityService.get_brute_force(wp_site)), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/security/bruteforce', methods=['POST'])
-@jwt_required()
-@admin_required
-def set_site_bruteforce(app_id):
- """Enable/disable the site's WP-login brute-force jail."""
- from .wp_security_service import WpSecurityService
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
- if not wp_site:
- return jsonify({'error': 'Not a WordPress site'}), 400
- enabled = bool((request.get_json() or {}).get('enabled'))
- return jsonify(WpSecurityService.set_brute_force(wp_site, enabled)), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/security/bruteforce/unban', methods=['POST'])
-@jwt_required()
-@admin_required
-def unban_site_bruteforce(app_id):
- """Unban an IP from the site's brute-force jail."""
- from .wp_security_service import WpSecurityService
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
- if not wp_site:
- return jsonify({'error': 'Not a WordPress site'}), 400
- ip = ((request.get_json() or {}).get('ip') or '').strip()
- if not ip:
- return jsonify({'error': 'ip is required'}), 400
- return jsonify(WpSecurityService.unban_brute_force(wp_site, ip)), 200
-
-
-# ---- Safe update manager (#29): run history, on-demand safe update, schedule ----
-
-@wordpress_bp.route('/sites/<int:app_id>/updates', methods=['GET'])
-@jwt_required()
-def get_site_updates(app_id):
- """Return safe-update run history + status + the site's update schedule."""
- from .wp_update_service import WpUpdateService
- app, err = _owner_or_admin_app(app_id)
- if err:
- return err
- wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
- if not wp_site:
- return jsonify({'error': 'Not a WordPress site'}), 400
- result = WpUpdateService.get_runs(wp_site)
- result['schedule'] = wp_site.auto_update_schedule
- result['exclude'] = json.loads(wp_site.auto_update_exclude) if wp_site.auto_update_exclude else []
- return jsonify(result), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/updates/run', methods=['POST'])
-@jwt_required()
-@admin_required
-def run_site_updates(app_id):
- """Start a background safe update (snapshot -> update -> health-check -> auto-rollback)."""
- from .wp_update_service import WpUpdateService
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
- if not wp_site:
- return jsonify({'error': 'Not a WordPress site'}), 400
- data = request.get_json() or {}
- targets = data.get('targets') or {'core': True, 'plugins': True, 'themes': True}
- exclude = data.get('exclude') or []
- return jsonify(WpUpdateService.start_update(wp_site, targets=targets, exclude=exclude)), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/updates/schedule', methods=['POST'])
-@jwt_required()
-@admin_required
-def set_site_update_schedule(app_id):
- """Set/clear the per-site auto-update cron schedule + exclusion list."""
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
- if not wp_site:
- return jsonify({'error': 'Not a WordPress site'}), 400
- data = request.get_json() or {}
- wp_site.auto_update_schedule = (data.get('schedule') or '').strip() or None
- if data.get('exclude') is not None:
- wp_site.auto_update_exclude = json.dumps(data.get('exclude'))
- db.session.commit()
- return jsonify({
- 'success': True,
- 'schedule': wp_site.auto_update_schedule,
- 'exclude': json.loads(wp_site.auto_update_exclude) if wp_site.auto_update_exclude else [],
- }), 200
-
-
-# ---- Monthly client reports (#33 agency slice): persisted per-month rollups ----
-
-@wordpress_bp.route('/sites/<int:app_id>/reports', methods=['GET'])
-@jwt_required()
-def get_site_reports(app_id):
- """Return all persisted monthly reports for a site (newest month first)."""
- from .wp_reports_service import WpReportsService
- app, err = _owner_or_admin_app(app_id)
- if err:
- return err
- wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
- if not wp_site:
- return jsonify({'error': 'Not a WordPress site'}), 400
- return jsonify(WpReportsService.get_reports(wp_site)), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/reports/generate', methods=['POST'])
-@jwt_required()
-@admin_required
-def generate_site_report(app_id):
- """Generate (or regenerate) the monthly report for a site. Body may carry
- {year, month}; defaults to the current UTC month."""
- from .wp_reports_service import WpReportsService
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
- if not wp_site:
- return jsonify({'error': 'Not a WordPress site'}), 400
- data = request.get_json() or {}
- result = WpReportsService.generate(wp_site, year=data.get('year'), month=data.get('month'))
- return jsonify(result), (200 if result.get('success') else 400)
-
-
-@wordpress_bp.route('/sites/<int:app_id>/reports/<int:report_id>', methods=['DELETE'])
-@jwt_required()
-@admin_required
-def delete_site_report(app_id, report_id):
- """Delete one persisted monthly report."""
- from .wp_reports_service import WpReportsService
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
- if not wp_site:
- return jsonify({'error': 'Not a WordPress site'}), 400
- result = WpReportsService.delete(wp_site, report_id)
- return jsonify(result), (200 if result.get('success') else 404)
-
-
-@wordpress_bp.route('/sites/<int:app_id>/info', methods=['GET'])
-@jwt_required()
-def get_wordpress_info(app_id):
- """Get WordPress site info."""
- current_user_id = get_jwt_identity()
- user = User.query.get(current_user_id)
- app = _resolve_app(app_id)
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- if not ResourceGrantService.can_access_app(user, app):
- return jsonify({'error': 'Access denied'}), 403
-
- if not _is_wp_app(app):
- return jsonify({'error': 'Application is not a WordPress site'}), 400
-
- info = WordPressService.get_wordpress_info(app.root_path)
- if not info:
- return jsonify({'error': 'Could not get WordPress info'}), 400
-
- return jsonify({'info': info}), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/update', methods=['POST'])
-@jwt_required()
-@admin_required
-def update_wordpress(app_id):
- """Update WordPress core."""
- app = _resolve_app(app_id)
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- if not _is_wp_app(app):
- return jsonify({'error': 'Application is not a WordPress site'}), 400
-
- result = WordPressService.update_wordpress(app.root_path)
- return jsonify(result), 200 if result['success'] else 400
-
-
-# Plugin management
-@wordpress_bp.route('/sites/<int:app_id>/plugins', methods=['GET'])
-@jwt_required()
-def get_plugins(app_id):
- """Get installed plugins."""
- current_user_id = get_jwt_identity()
- user = User.query.get(current_user_id)
- app = _resolve_app(app_id)
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- if not ResourceGrantService.can_access_app(user, app):
- return jsonify({'error': 'Access denied'}), 403
-
- plugins = WordPressService.get_plugins(app.root_path)
- return jsonify({'plugins': plugins}), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/plugins', methods=['POST'])
-@jwt_required()
-@admin_required
-def install_plugin(app_id):
- """Install a plugin."""
- app = _resolve_app(app_id)
- data = request.get_json()
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- if not data or 'plugin' not in data:
- return jsonify({'error': 'plugin is required'}), 400
-
- result = WordPressService.install_plugin(
- app.root_path,
- data['plugin'],
- data.get('activate', True)
- )
- return jsonify(result), 200 if result['success'] else 400
-
-
-@wordpress_bp.route('/sites/<int:app_id>/plugins/<plugin>', methods=['DELETE'])
-@jwt_required()
-@admin_required
-def uninstall_plugin(app_id, plugin):
- """Uninstall a plugin."""
- app = _resolve_app(app_id)
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- result = WordPressService.uninstall_plugin(app.root_path, plugin)
- return jsonify(result), 200 if result['success'] else 400
-
-
-@wordpress_bp.route('/sites/<int:app_id>/plugins/<plugin>/activate', methods=['POST'])
-@jwt_required()
-@admin_required
-def activate_plugin(app_id, plugin):
- """Activate a plugin."""
- app = _resolve_app(app_id)
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- result = WordPressService.activate_plugin(app.root_path, plugin)
- return jsonify(result), 200 if result['success'] else 400
-
-
-@wordpress_bp.route('/sites/<int:app_id>/plugins/<plugin>/deactivate', methods=['POST'])
-@jwt_required()
-@admin_required
-def deactivate_plugin(app_id, plugin):
- """Deactivate a plugin."""
- app = _resolve_app(app_id)
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- result = WordPressService.deactivate_plugin(app.root_path, plugin)
- return jsonify(result), 200 if result['success'] else 400
-
-
-@wordpress_bp.route('/sites/<int:app_id>/plugins/update', methods=['POST'])
-@jwt_required()
-@admin_required
-def update_plugins(app_id):
- """Update plugins."""
- app = _resolve_app(app_id)
- data = request.get_json()
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- plugins = data.get('plugins') if data else None
- result = WordPressService.update_plugins(app.root_path, plugins)
- return jsonify(result), 200 if result['success'] else 400
-
-
-# Theme management
-@wordpress_bp.route('/sites/<int:app_id>/themes', methods=['GET'])
-@jwt_required()
-def get_themes(app_id):
- """Get installed themes."""
- current_user_id = get_jwt_identity()
- user = User.query.get(current_user_id)
- app = _resolve_app(app_id)
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- if not ResourceGrantService.can_access_app(user, app):
- return jsonify({'error': 'Access denied'}), 403
-
- themes = WordPressService.get_themes(app.root_path)
- return jsonify({'themes': themes}), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/themes', methods=['POST'])
-@jwt_required()
-@admin_required
-def install_theme(app_id):
- """Install a theme."""
- app = _resolve_app(app_id)
- data = request.get_json()
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- if not data or 'theme' not in data:
- return jsonify({'error': 'theme is required'}), 400
-
- result = WordPressService.install_theme(
- app.root_path,
- data['theme'],
- data.get('activate', False)
- )
- return jsonify(result), 200 if result['success'] else 400
-
-
-@wordpress_bp.route('/sites/<int:app_id>/themes/update', methods=['POST'])
-@jwt_required()
-@admin_required
-def update_themes(app_id):
- """Update themes."""
- app = _resolve_app(app_id)
- data = request.get_json()
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- themes = data.get('themes') if data else None
- result = WordPressService.update_themes(app.root_path, themes)
- return jsonify(result), 200 if result['success'] else 400
-
-
-@wordpress_bp.route('/sites/<int:app_id>/themes/<theme>/activate', methods=['POST'])
-@jwt_required()
-@admin_required
-def activate_theme(app_id, theme):
- """Activate a theme."""
- app = _resolve_app(app_id)
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- result = WordPressService.activate_theme(app.root_path, theme)
- return jsonify(result), 200 if result['success'] else 400
-
-
-# Backup management
-@wordpress_bp.route('/sites/<int:app_id>/backup', methods=['POST'])
-@jwt_required()
-@admin_required
-def create_backup(app_id):
- """Create a backup."""
- app = _resolve_app(app_id)
- data = request.get_json() or {}
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- result = WordPressService.backup_wordpress(
- app.root_path,
- data.get('include_db', True)
- )
- return jsonify(result), 200 if result['success'] else 400
-
-
-@wordpress_bp.route('/sites/<int:app_id>/backups', methods=['GET'])
-@jwt_required()
-def list_backups(app_id):
- """List backups for a site."""
- current_user_id = get_jwt_identity()
- user = User.query.get(current_user_id)
- app = _resolve_app(app_id)
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- if not ResourceGrantService.can_access_app(user, app):
- return jsonify({'error': 'Access denied'}), 403
-
- import os
- site_name = os.path.basename(app.root_path)
- backups = WordPressService.list_backups(site_name)
- return jsonify({'backups': backups}), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/restore', methods=['POST'])
-@jwt_required()
-@admin_required
-def restore_backup(app_id):
- """Restore a backup."""
- app = _resolve_app(app_id)
- data = request.get_json()
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- if not data or 'backup_name' not in data:
- return jsonify({'error': 'backup_name is required'}), 400
-
- result = WordPressService.restore_backup(data['backup_name'], app.root_path)
- return jsonify(result), 200 if result['success'] else 400
-
-
-@wordpress_bp.route('/backups/<backup_name>', methods=['DELETE'])
-@jwt_required()
-@admin_required
-def delete_backup(backup_name):
- """Delete a backup."""
- result = WordPressService.delete_backup(backup_name)
- return jsonify(result), 200 if result['success'] else 400
-
-
-# Security and maintenance
-@wordpress_bp.route('/sites/<int:app_id>/harden', methods=['POST'])
-@jwt_required()
-@admin_required
-def harden_wordpress(app_id):
- """Apply security hardening."""
- app = _resolve_app(app_id)
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- result = WordPressService.harden_wordpress(app.root_path)
- return jsonify(result), 200 if result['success'] else 400
-
-
-@wordpress_bp.route('/sites/<int:app_id>/search-replace', methods=['POST'])
-@jwt_required()
-@admin_required
-def search_replace(app_id):
- """Search and replace in database."""
- app = _resolve_app(app_id)
- data = request.get_json()
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- if not data or 'search' not in data or 'replace' not in data:
- return jsonify({'error': 'search and replace are required'}), 400
-
- result = WordPressService.search_replace(
- app.root_path,
- data['search'],
- data['replace'],
- data.get('dry_run', True)
- )
- return jsonify(result), 200 if result['success'] else 400
-
-
-@wordpress_bp.route('/sites/<int:app_id>/url/preview', methods=['POST'])
-@jwt_required()
-@admin_required
-def preview_site_url(app_id):
- """Dry-run a site URL change: per-pair replacement counts, no mutation."""
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- data = request.get_json() or {}
- new_url = data.get('new_url')
- if not new_url:
- return jsonify({'error': 'new_url is required'}), 400
- result = WordPressService.preview_url_change(app, new_url)
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@wordpress_bp.route('/sites/<int:app_id>/url', methods=['POST'])
-@jwt_required()
-@admin_required
-def change_site_url(app_id):
- """Change a site's URL end to end: backup, serialization-safe DB rewrite,
- home/siteurl + cache flush, then re-point the Domain row + nginx vhost."""
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- data = request.get_json() or {}
- new_url = data.get('new_url')
- if not new_url:
- return jsonify({'error': 'new_url is required'}), 400
- keep_old = data.get('keep_old_redirect', True)
- result = WordPressService.change_site_url(app, new_url, keep_old_redirect=keep_old)
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@wordpress_bp.route('/sites/<int:app_id>/domain', methods=['POST'])
-@jwt_required()
-@admin_required
-def attach_custom_domain(app_id):
- """Attach a user-owned custom domain: auto-create the DNS A record (or return
- it to add manually), optional Let's Encrypt cert, then migrate the site URL."""
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- data = request.get_json() or {}
- domain = data.get('domain')
- if not domain:
- return jsonify({'error': 'domain is required'}), 400
- result = WordPressService.attach_custom_domain(
- app, domain,
- migrate=data.get('migrate', True),
- issue_ssl=data.get('issue_ssl', False),
- email=data.get('email'),
- )
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@wordpress_bp.route('/sites/<int:app_id>/optimize', methods=['POST'])
-@jwt_required()
-@admin_required
-def optimize_database(app_id):
- """Optimize WordPress database."""
- app = _resolve_app(app_id)
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- result = WordPressService.optimize_database(app.root_path)
- return jsonify(result), 200 if result['success'] else 400
-
-
-@wordpress_bp.route('/sites/<int:app_id>/page-cache', methods=['GET'])
-@jwt_required()
-def get_page_cache(app_id):
- """Report full-page cache plugin status for a site."""
- app, err = _guard_sealed_app(app_id)
- if err:
- return err
- return jsonify(WordPressService.get_page_cache_status(app.root_path)), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/page-cache', methods=['POST'])
-@jwt_required()
-@admin_required
-def enable_page_cache(app_id):
- """Enable the full-page cache for a site."""
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- result = WordPressService.enable_page_cache(app.root_path)
- if result.get('success'):
- wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
- if wp_site:
- cfg = json.loads(wp_site.sync_config) if wp_site.sync_config else {}
- cfg['page_cache_enabled'] = True
- wp_site.sync_config = json.dumps(cfg)
- db.session.commit()
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@wordpress_bp.route('/sites/<int:app_id>/page-cache', methods=['DELETE'])
-@jwt_required()
-@admin_required
-def disable_page_cache(app_id):
- """Disable the full-page cache for a site."""
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- result = WordPressService.disable_page_cache(app.root_path)
- if result.get('success'):
- wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
- if wp_site:
- cfg = json.loads(wp_site.sync_config) if wp_site.sync_config else {}
- cfg['page_cache_enabled'] = False
- wp_site.sync_config = json.dumps(cfg)
- db.session.commit()
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@wordpress_bp.route('/sites/<int:app_id>/object-cache', methods=['GET'])
-@jwt_required()
-def object_cache_status(app_id):
- """Report Redis object-cache state for a site."""
- app, err = _guard_sealed_app(app_id)
- if err:
- return err
- return jsonify(WordPressService.object_cache_status(app.root_path)), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/object-cache', methods=['POST'])
-@jwt_required()
-@admin_required
-def enable_object_cache(app_id):
- """Enable Redis object cache (adds a redis container if needed, activates plugin)."""
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- result = WordPressService.enable_object_cache(app.root_path)
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@wordpress_bp.route('/sites/<int:app_id>/object-cache', methods=['DELETE'])
-@jwt_required()
-@admin_required
-def disable_object_cache(app_id):
- """Disable Redis object cache (keeps the container + plugin)."""
- app = _resolve_app(app_id)
- if not app:
- return jsonify({'error': 'Application not found'}), 404
- result = WordPressService.disable_object_cache(app.root_path)
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@wordpress_bp.route('/sites/<int:app_id>/flush-cache', methods=['POST'])
-@jwt_required()
-@admin_required
-def flush_cache(app_id):
- """Flush WordPress cache."""
- app = _resolve_app(app_id)
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- result = WordPressService.flush_cache(app.root_path)
- return jsonify(result), 200 if result['success'] else 400
-
-
-# User management
-@wordpress_bp.route('/sites/<int:app_id>/users', methods=['POST'])
-@jwt_required()
-@admin_required
-def create_wp_user(app_id):
- """Create a WordPress user."""
- app = _resolve_app(app_id)
- data = request.get_json()
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- if not data or 'username' not in data or 'email' not in data:
- return jsonify({'error': 'username and email are required'}), 400
-
- result = WordPressService.create_user(
- app.root_path,
- data['username'],
- data['email'],
- data.get('role', 'subscriber'),
- data.get('password')
- )
- return jsonify(result), 201 if result['success'] else 400
-
-
-@wordpress_bp.route('/sites/<int:site_id>/login', methods=['POST'])
-@jwt_required()
-@admin_required
-def wp_auto_login(site_id):
- """Mint a one-time passwordless wp-admin login URL for the calling operator."""
- from app.services.audit_service import AuditService
- current_user_id = get_jwt_identity()
- operator = User.query.get(current_user_id)
- if not operator:
- return jsonify({'error': 'User not found'}), 404
-
- wp_site = WordPressSite.query.get(site_id)
- app = wp_site.application if wp_site else _resolve_app(site_id)
- if not app or not app.root_path:
- return jsonify({'error': 'Application not found'}), 404
- if not _is_wp_app(app):
- return jsonify({'error': 'Application is not a WordPress site'}), 400
-
- # Resolve a managed admin tied to the operator's panel email. Prefer the
- # site's recorded admin_user; otherwise derive a deterministic username
- # from the operator and create it via the WP-CLI bridge if absent.
- wp_user = (wp_site.admin_user if wp_site and wp_site.admin_user else None)
- if not wp_user:
- wp_user = (operator.username or operator.email.split('@')[0])
- exists = WordPressService.wp_cli(app.root_path, ['user', 'get', wp_user, '--field=ID'])
- if not exists.get('success'):
- created = WordPressService.create_user(
- app.root_path, wp_user, operator.email, role='administrator'
- )
- if not created.get('success'):
- return jsonify({'error': created.get('error') or 'Failed to provision admin'}), 400
- if wp_site:
- wp_site.admin_user = wp_user
- if not wp_site.admin_email:
- wp_site.admin_email = operator.email
- db.session.commit()
-
- result = WordPressService.create_login_url(app.root_path, wp_user)
- if not result.get('success'):
- return jsonify({'error': result.get('error') or 'Failed to create login URL'}), 400
-
- AuditService.log(
- action='wordpress.admin_login',
- user_id=current_user_id,
- target_type='app',
- target_id=app.id,
- details={'wp_user': wp_user, 'site_id': site_id, 'app_name': app.name},
- )
-
- return jsonify({'success': True, 'url': result['url']}), 200
-
-
-@wordpress_bp.route('/sites/<int:app_id>/users/<user>/reset-password', methods=['POST'])
-@jwt_required()
-@admin_required
-def reset_wp_password(app_id, user):
- """Reset a WordPress user's password."""
- app = _resolve_app(app_id)
- data = request.get_json() or {}
-
- if not app:
- return jsonify({'error': 'Application not found'}), 404
-
- result = WordPressService.reset_password(app.root_path, user, data.get('password'))
- return jsonify(result), 200 if result['success'] else 400
-
-
-# WP-CLI status
-@wordpress_bp.route('/wp-cli/status', methods=['GET'])
-@jwt_required()
-@admin_required
-def wp_cli_status():
- """Check WP-CLI installation status."""
- installed = WordPressService.is_wp_cli_installed()
- return jsonify({
- 'installed': installed,
- 'path': WordPressService.WP_CLI_PATH if installed else None
- }), 200
-
-
-@wordpress_bp.route('/wp-cli/install', methods=['POST'])
-@jwt_required()
-@admin_required
-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 .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 .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 .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 .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 .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 .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 .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 .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 .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 .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 .wordpress_plugin_library_service import WordPressPluginLibraryService
- _, err = _guard_sealed_app(app_id)
- if err:
- return err
- site = _resolve_wp_site(app_id)
- if not site:
- return jsonify({'error': 'Site not found'}), 404
- return jsonify({'managed': WordPressPluginLibraryService.managed_for_site(site)}), 200
diff --git a/builtin-extensions/serverkit-wordpress/backend/wordpress_env_service.py b/builtin-extensions/serverkit-wordpress/backend/wordpress_env_service.py
deleted file mode 100644
index c1b1d58c..00000000
--- a/builtin-extensions/serverkit-wordpress/backend/wordpress_env_service.py
+++ /dev/null
@@ -1,530 +0,0 @@
-"""
-WordPress Environment Service
-
-Manage WordPress production/development/staging environments.
-Handles environment creation, database cloning, and synchronization.
-
-For Docker-isolated environments (compose_project_name set), delegates to
-EnvironmentPipelineService. For legacy/standalone environments, handles
-directly using host MySQL and file system operations.
-"""
-
-import os
-import json
-import secrets
-import string
-import shutil
-from datetime import datetime
-from typing import Dict, List, Optional
-
-from app import db
-from app.models.application import Application
-from app.models.wordpress_site import WordPressSite, DatabaseSnapshot, SyncJob
-from app.services.db_sync_service import DatabaseSyncService
-from .wordpress_service import WordPressService
-from app.services.database_service import DatabaseService
-
-
-class WordPressEnvService:
- """Manage WordPress production/development/staging environments."""
-
- @classmethod
- def create_environment(cls, production_site_id: int, env_type: str,
- config: Dict, user_id: int) -> Dict:
- """
- Create a new environment linked to production.
-
- If config['isolated'] is True, delegates to EnvironmentPipelineService
- for full Docker-isolated environment creation. Otherwise uses the
- legacy shared-host approach.
-
- Args:
- production_site_id: ID of the production WordPressSite
- env_type: 'development' or 'staging'
- config: Dict with:
- - name: Environment name (e.g., 'My Site Dev')
- - domain: Domain for the environment (e.g., 'dev.mysite.com')
- - port: Optional custom port
- - clone_db: Whether to clone the production database
- - sync_schedule: Optional cron schedule for auto-sync
- - isolated: If True, use Docker-isolated pipeline (default False)
- user_id: User ID creating the environment
-
- Returns:
- Dict with success status and environment info
- """
- # Delegate to pipeline service for Docker-isolated environments
- if config.get('isolated'):
- from app.services.environment_pipeline_service import EnvironmentPipelineService
- return EnvironmentPipelineService.create_project_environment(
- production_site_id=production_site_id,
- env_type=env_type,
- config=config,
- user_id=user_id
- )
-
- # Validate environment type
- if env_type not in ['development', 'staging']:
- return {'success': False, 'error': 'Invalid environment type. Must be development or staging.'}
-
- # Get production site
- prod_site = WordPressSite.query.get(production_site_id)
- if not prod_site:
- return {'success': False, 'error': 'Production site not found'}
-
- if not prod_site.is_production:
- return {'success': False, 'error': 'Source site is not a production site'}
-
- prod_app = prod_site.application
- if not prod_app:
- return {'success': False, 'error': 'Production application not found'}
-
- try:
- # Generate names
- env_name = config.get('name', f"{prod_app.name} ({env_type.title()})")
- env_domain = config.get('domain')
-
- # Generate unique database name and prefix
- short_id = secrets.token_hex(4)
- env_db_name = f"{prod_site.db_name}_{env_type[:3]}_{short_id}"
- env_db_prefix = f"wp_{env_type[:3]}_"
-
- # Determine root path for new environment
- prod_path = prod_app.root_path
- base_path = os.path.dirname(prod_path)
- env_path = os.path.join(base_path, f"{os.path.basename(prod_path)}_{env_type}")
-
- # Step 1: Clone the database if requested
- if config.get('clone_db', True):
- # First create a snapshot
- snapshot_result = DatabaseSyncService.create_snapshot(
- db_name=prod_site.db_name,
- name=f"pre_env_create_{env_type}",
- tag=f"env-create-{env_type}",
- host=prod_site.db_host,
- user=prod_site.db_user,
- password=cls._get_db_password(prod_site)
- )
-
- if not snapshot_result['success']:
- return {'success': False, 'error': f"Failed to create snapshot: {snapshot_result.get('error')}"}
-
- # Clone with transformations
- clone_options = {
- 'table_prefix': env_db_prefix,
- 'truncate_tables': config.get('truncate_tables', [
- 'actionscheduler_actions',
- 'actionscheduler_logs',
- ])
- }
-
- # Add search-replace for domain if provided
- if env_domain and prod_app.domains:
- prod_domain = prod_app.domains[0].domain if prod_app.domains else None
- if prod_domain:
- clone_options['search_replace'] = {
- f'https://{prod_domain}': f'https://{env_domain}',
- f'http://{prod_domain}': f'http://{env_domain}',
- prod_domain: env_domain
- }
-
- clone_result = DatabaseSyncService.clone_database(
- source_db=prod_site.db_name,
- target_db=env_db_name,
- source_host=prod_site.db_host,
- target_host=prod_site.db_host,
- source_user=prod_site.db_user,
- target_user=prod_site.db_user,
- source_password=cls._get_db_password(prod_site),
- target_password=cls._get_db_password(prod_site),
- options=clone_options
- )
-
- if not clone_result['success']:
- return {'success': False, 'error': f"Failed to clone database: {clone_result.get('error')}"}
-
- # Step 2: Create the Application record
- env_app = Application(
- name=env_name,
- app_type='wordpress',
- status='deploying',
- php_version=prod_app.php_version,
- port=config.get('port'),
- root_path=env_path,
- environment_type=env_type,
- linked_app_id=prod_app.id,
- user_id=user_id
- )
- db.session.add(env_app)
- db.session.flush() # Get the ID
-
- # Step 3: Create the WordPressSite record
- env_site = WordPressSite(
- application_id=env_app.id,
- wp_version=prod_site.wp_version,
- multisite=prod_site.multisite,
- admin_user=prod_site.admin_user,
- admin_email=prod_site.admin_email,
- db_name=env_db_name,
- db_user=prod_site.db_user,
- db_host=prod_site.db_host,
- db_prefix=env_db_prefix,
- git_repo_url=prod_site.git_repo_url,
- git_branch=config.get('git_branch', prod_site.git_branch),
- git_paths=prod_site.git_paths,
- auto_deploy=config.get('auto_deploy', False),
- is_production=False,
- production_site_id=production_site_id
- )
- db.session.add(env_site)
-
- # Step 4: Copy WordPress files
- copy_result = cls._copy_wordpress_files(prod_path, env_path)
- if not copy_result['success']:
- db.session.rollback()
- return copy_result
-
- # Step 5: Update wp-config.php for new environment
- config_result = cls._update_wp_config(
- env_path,
- db_name=env_db_name,
- db_prefix=env_db_prefix,
- site_url=f"https://{env_domain}" if env_domain else None
- )
-
- if not config_result['success']:
- db.session.rollback()
- return config_result
-
- # Step 6: Create sync job if schedule provided
- if config.get('sync_schedule'):
- sync_job = SyncJob(
- source_site_id=production_site_id,
- target_site_id=env_site.id,
- name=f"Auto-sync {prod_app.name} to {env_name}",
- schedule=config['sync_schedule'],
- enabled=True,
- config=json.dumps({
- 'search_replace': clone_options.get('search_replace', {}),
- 'truncate_tables': clone_options.get('truncate_tables', [])
- })
- )
- db.session.add(sync_job)
-
- # Update application status
- env_app.status = 'running'
-
- db.session.commit()
-
- return {
- 'success': True,
- 'message': f'{env_type.title()} environment created successfully',
- 'environment': env_site.to_dict(),
- 'application': env_app.to_dict()
- }
-
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def sync_environment(cls, env_site_id: int, options: Dict = None) -> Dict:
- """
- Sync an environment from its production source.
-
- Docker-isolated environments (those with compose_project_name) are
- delegated to EnvironmentPipelineService for container-aware sync.
-
- Args:
- env_site_id: ID of the environment WordPressSite to sync
- options: Optional override options for sync
-
- Returns:
- Dict with success status
- """
- options = options or {}
-
- env_site = WordPressSite.query.get(env_site_id)
- if not env_site:
- return {'success': False, 'error': 'Environment not found'}
-
- if env_site.is_production:
- return {'success': False, 'error': 'Cannot sync a production site'}
-
- # Delegate Docker-isolated environments to pipeline service
- if env_site.compose_project_name:
- from app.services.environment_pipeline_service import EnvironmentPipelineService
- return EnvironmentPipelineService.sync_from_production(
- env_site_id=env_site_id,
- sync_type=options.pop('sync_type', 'full'),
- options=options,
- user_id=options.pop('user_id', None)
- )
-
- prod_site = env_site.production_site
- if not prod_site:
- return {'success': False, 'error': 'Production site not found'}
-
- try:
- # Get sync config
- sync_config = json.loads(env_site.sync_config) if env_site.sync_config else {}
- sync_config.update(options)
-
- # Create snapshot before sync
- snapshot_result = DatabaseSyncService.create_snapshot(
- db_name=env_site.db_name,
- name=f"pre_sync_{datetime.now().strftime('%Y%m%d_%H%M%S')}",
- tag='pre-sync',
- host=env_site.db_host,
- user=env_site.db_user,
- password=cls._get_db_password(env_site)
- )
-
- # Clone production to environment
- clone_options = {
- 'table_prefix': env_site.db_prefix,
- 'search_replace': sync_config.get('search_replace', {}),
- 'truncate_tables': sync_config.get('truncate_tables', []),
- 'anonymize': sync_config.get('anonymize', False)
- }
-
- clone_result = DatabaseSyncService.clone_database(
- source_db=prod_site.db_name,
- target_db=env_site.db_name,
- source_host=prod_site.db_host,
- target_host=env_site.db_host,
- source_user=prod_site.db_user,
- target_user=env_site.db_user,
- source_password=cls._get_db_password(prod_site),
- target_password=cls._get_db_password(env_site),
- options=clone_options
- )
-
- if not clone_result['success']:
- return clone_result
-
- # Update sync timestamp
- env_site.updated_at = datetime.utcnow()
- db.session.commit()
-
- return {
- 'success': True,
- 'message': 'Environment synced successfully',
- 'pre_sync_snapshot': snapshot_result.get('snapshot', {}).get('file_path')
- }
-
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def get_environment_status(cls, production_site_id: int) -> Dict:
- """
- Get status of all environments for a production site.
-
- Args:
- production_site_id: ID of the production WordPressSite
-
- Returns:
- Dict with production site and all environments
- """
- prod_site = WordPressSite.query.get(production_site_id)
- if not prod_site:
- return {'success': False, 'error': 'Production site not found'}
-
- environments = []
- for env in prod_site.environments:
- env_data = env.to_dict()
-
- # Get last sync info
- last_sync_job = SyncJob.query.filter_by(
- target_site_id=env.id
- ).order_by(SyncJob.last_run.desc()).first()
-
- if last_sync_job:
- env_data['last_sync'] = {
- 'time': last_sync_job.last_run.isoformat() if last_sync_job.last_run else None,
- 'status': last_sync_job.last_run_status,
- 'next_scheduled': last_sync_job.next_run.isoformat() if last_sync_job.next_run else None
- }
-
- environments.append(env_data)
-
- return {
- 'success': True,
- 'production': prod_site.to_dict(),
- 'environments': environments
- }
-
- @classmethod
- def delete_environment(cls, env_site_id: int, delete_files: bool = True,
- delete_database: bool = True, user_id: int = None) -> Dict:
- """
- Delete an environment.
-
- Docker-isolated environments are delegated to EnvironmentPipelineService
- for proper container and Nginx cleanup.
-
- Args:
- env_site_id: ID of the environment WordPressSite
- delete_files: Whether to delete WordPress files
- delete_database: Whether to drop the database
- user_id: ID of the user performing the deletion
-
- Returns:
- Dict with success status
- """
- env_site = WordPressSite.query.get(env_site_id)
- if not env_site:
- return {'success': False, 'error': 'Environment not found'}
-
- if env_site.is_production:
- return {'success': False, 'error': 'Cannot delete a production site this way'}
-
- # Delegate Docker-isolated environments to pipeline service
- if env_site.compose_project_name:
- from app.services.environment_pipeline_service import EnvironmentPipelineService
- return EnvironmentPipelineService.delete_environment(
- env_site_id=env_site_id,
- user_id=user_id
- )
-
- env_app = env_site.application
-
- try:
- # Delete database
- if delete_database and env_site.db_name:
- DatabaseService.mysql_execute(
- f"DROP DATABASE IF EXISTS `{env_site.db_name}`"
- )
-
- # Delete files
- if delete_files and env_app and env_app.root_path:
- if os.path.exists(env_app.root_path):
- shutil.rmtree(env_app.root_path)
-
- # Delete related sync jobs
- SyncJob.query.filter(
- (SyncJob.source_site_id == env_site_id) |
- (SyncJob.target_site_id == env_site_id)
- ).delete()
-
- # Delete snapshots
- for snapshot in env_site.snapshots:
- if os.path.exists(snapshot.file_path):
- os.remove(snapshot.file_path)
-
- # Delete records
- db.session.delete(env_site)
- if env_app:
- db.session.delete(env_app)
-
- db.session.commit()
-
- return {'success': True, 'message': 'Environment deleted successfully'}
-
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def _copy_wordpress_files(cls, source_path: str, target_path: str) -> Dict:
- """Copy WordPress files from source to target."""
- try:
- if os.path.exists(target_path):
- shutil.rmtree(target_path)
-
- shutil.copytree(source_path, target_path)
-
- # Set permissions
- import subprocess
- subprocess.run(['sudo', 'chown', '-R', 'www-data:www-data', target_path], capture_output=True)
-
- return {'success': True}
-
- except Exception as e:
- return {'success': False, 'error': f'Failed to copy files: {str(e)}'}
-
- @classmethod
- def _update_wp_config(cls, wp_path: str, db_name: str = None,
- db_prefix: str = None, site_url: str = None) -> Dict:
- """Update wp-config.php for the new environment."""
- config_path = os.path.join(wp_path, 'wp-config.php')
-
- if not os.path.exists(config_path):
- return {'success': False, 'error': 'wp-config.php not found'}
-
- try:
- with open(config_path, 'r') as f:
- content = f.read()
-
- # Update database name
- if db_name:
- content = cls._replace_define(content, 'DB_NAME', db_name)
-
- # Update table prefix
- if db_prefix:
- content = cls._replace_table_prefix(content, db_prefix)
-
- # Update site URL if provided
- if site_url:
- content = cls._replace_define(content, 'WP_HOME', site_url)
- content = cls._replace_define(content, 'WP_SITEURL', site_url)
-
- # Add debug mode for non-production
- if "define( 'WP_DEBUG'" not in content and "define('WP_DEBUG'" not in content:
- content = content.replace(
- "/* That's all",
- "define('WP_DEBUG', true);\ndefine('WP_DEBUG_LOG', true);\n\n/* That's all"
- )
-
- with open(config_path, 'w') as f:
- f.write(content)
-
- return {'success': True}
-
- except Exception as e:
- return {'success': False, 'error': f'Failed to update wp-config.php: {str(e)}'}
-
- @staticmethod
- def _replace_define(content: str, constant: str, value: str) -> str:
- """Replace a define() statement in wp-config.php."""
- import re
- # Match both styles: define('CONST', 'value') and define( 'CONST', 'value' )
- pattern = rf"define\s*\(\s*['\"]({constant})['\"]\s*,\s*['\"]([^'\"]*)['\"]"
- replacement = f"define('{constant}', '{value}'"
- return re.sub(pattern, replacement, content)
-
- @staticmethod
- def _replace_table_prefix(content: str, prefix: str) -> str:
- """Replace the table prefix in wp-config.php."""
- import re
- pattern = r"\$table_prefix\s*=\s*['\"]([^'\"]*)['\"]"
- replacement = f"$table_prefix = '{prefix}'"
- return re.sub(pattern, replacement, content)
-
- @staticmethod
- def _get_db_password(site: WordPressSite) -> Optional[str]:
- """Get database password for a site from wp-config.php."""
- if not site.application or not site.application.root_path:
- return None
-
- config_path = os.path.join(site.application.root_path, 'wp-config.php')
- if not os.path.exists(config_path):
- return None
-
- try:
- with open(config_path, 'r') as f:
- content = f.read()
-
- import re
- match = re.search(r"define\s*\(\s*['\"]DB_PASSWORD['\"]\s*,\s*['\"]([^'\"]*)['\"]", content)
- return match.group(1) if match else None
-
- except Exception:
- return None
-
- @staticmethod
- def _generate_password(length: int = 16) -> str:
- """Generate a secure random password."""
- alphabet = string.ascii_letters + string.digits + '!@#$%^&*'
- return ''.join(secrets.choice(alphabet) for _ in range(length))
diff --git a/builtin-extensions/serverkit-wordpress/backend/wordpress_plugin_library_service.py b/builtin-extensions/serverkit-wordpress/backend/wordpress_plugin_library_service.py
deleted file mode 100644
index ca6d8fc9..00000000
--- a/builtin-extensions/serverkit-wordpress/backend/wordpress_plugin_library_service.py
+++ /dev/null
@@ -1,508 +0,0 @@
-"""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 .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 < pl
diff --git a/builtin-extensions/serverkit-wordpress/backend/wordpress_service.py b/builtin-extensions/serverkit-wordpress/backend/wordpress_service.py
deleted file mode 100644
index 5c3aca2e..00000000
--- a/builtin-extensions/serverkit-wordpress/backend/wordpress_service.py
+++ /dev/null
@@ -1,2676 +0,0 @@
-import os
-import subprocess
-import secrets
-import string
-import shutil
-import json
-from datetime import datetime
-from typing import Dict, List, Optional
-from pathlib import Path
-
-from app import paths
-from app.utils.system import run_privileged, privileged_cmd
-
-
-class WordPressService:
- """Service for WordPress installation and management."""
-
- WP_CLI_PATH = '/usr/local/bin/wp'
- WP_DOWNLOAD_URL = 'https://wordpress.org/latest.tar.gz'
- BACKUP_DIR = paths.WP_BACKUP_DIR
-
- # Security headers for wp-config.php
- SECURITY_CONSTANTS = '''
-// ServerKit Security Hardening
-define('DISALLOW_FILE_EDIT', true);
-define('DISALLOW_FILE_MODS', false);
-define('FORCE_SSL_ADMIN', true);
-define('WP_AUTO_UPDATE_CORE', 'minor');
-
-// Security Keys (auto-generated)
-'''
-
- @classmethod
- def is_wp_cli_installed(cls) -> bool:
- """Check if WP-CLI is installed."""
- return os.path.exists(cls.WP_CLI_PATH)
-
- @classmethod
- def install_wp_cli(cls) -> Dict:
- """Install WP-CLI."""
- try:
- commands = [
- ['curl', '-O', 'https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar'],
- ['chmod', '+x', 'wp-cli.phar'],
- ]
-
- for cmd in commands:
- result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
- if result.returncode != 0:
- return {'success': False, 'error': result.stderr}
-
- result = run_privileged(['mv', 'wp-cli.phar', cls.WP_CLI_PATH], timeout=120)
- if result.returncode != 0:
- return {'success': False, 'error': result.stderr}
-
- return {'success': True, 'message': 'WP-CLI installed successfully'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def wp_cli(cls, path: str, command: List[str], user: str = 'www-data', timeout: int = None) -> Dict:
- """Execute a WP-CLI command. Auto-detects Docker-based sites.
-
- ``timeout`` overrides the default per-call wall-clock limit; pass a
- generous value for long operations like ``db export``/``db import`` so a
- large database is never truncated mid-restore.
- """
- # Check if this is a Docker-based site (has docker-compose.yml)
- compose_file = os.path.join(path, 'docker-compose.yml')
- if os.path.exists(compose_file):
- return cls._wp_cli_docker(path, command, timeout=timeout)
-
- if not cls.is_wp_cli_installed():
- install_result = cls.install_wp_cli()
- if not install_result['success']:
- return install_result
-
- try:
- cmd = privileged_cmd([cls.WP_CLI_PATH, '--path=' + path] + command, user=user)
- result = subprocess.run(
- cmd,
- capture_output=True,
- text=True,
- timeout=timeout or 300,
- cwd=path
- )
-
- return {
- 'success': result.returncode == 0,
- 'output': result.stdout,
- 'error': result.stderr if result.returncode != 0 else None
- }
- except subprocess.TimeoutExpired:
- return {'success': False, 'error': 'Command timed out'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def _wp_cli_docker(cls, path: str, command: List[str], timeout: int = None) -> Dict:
- """Execute a WP-CLI command inside a Docker WordPress container."""
- # Resolve container name from the Application record
- container_name = None
- from app.models import Application
- app = Application.query.filter_by(root_path=path).first()
- if app:
- container_name = app.name
-
- if not container_name:
- # Fallback: derive from directory name
- container_name = os.path.basename(path)
-
- try:
- # Ensure WP-CLI is available inside the container
- check = subprocess.run(
- ['docker', 'exec', container_name, 'which', 'wp'],
- capture_output=True, text=True, timeout=10
- )
- if check.returncode != 0:
- # Install WP-CLI inside the container
- install_cmd = (
- 'curl -sO https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar'
- ' && chmod +x wp-cli.phar && mv wp-cli.phar /usr/local/bin/wp'
- )
- install = subprocess.run(
- ['docker', 'exec', container_name, 'bash', '-c', install_cmd],
- capture_output=True, text=True, timeout=120
- )
- if install.returncode != 0:
- return {'success': False, 'error': f'Failed to install WP-CLI in container: {install.stderr}'}
-
- # Run wp-cli inside the WordPress container
- cmd = ['docker', 'exec', container_name, 'wp', '--allow-root'] + command
- result = subprocess.run(
- cmd,
- capture_output=True,
- text=True,
- timeout=timeout or 60
- )
-
- return {
- 'success': result.returncode == 0,
- 'output': result.stdout,
- 'error': result.stderr if result.returncode != 0 else None
- }
- except subprocess.TimeoutExpired:
- return {'success': False, 'error': 'Command timed out'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def install_wordpress(cls, path: str, config: Dict) -> Dict:
- """Install WordPress at the specified path."""
- site_url = config.get('site_url')
- site_title = config.get('site_title', 'My WordPress Site')
- admin_user = config.get('admin_user', 'admin')
- admin_password = config.get('admin_password') or cls._generate_password()
- admin_email = config.get('admin_email')
- db_name = config.get('db_name')
- db_user = config.get('db_user')
- db_password = config.get('db_password')
- db_host = config.get('db_host', 'localhost')
- db_prefix = config.get('db_prefix', 'wp_')
-
- if not all([site_url, admin_email, db_name, db_user, db_password]):
- return {'success': False, 'error': 'Missing required configuration'}
-
- try:
- # Create directory
- run_privileged(['mkdir', '-p', path])
- run_privileged(['chown', 'www-data:www-data', path])
-
- # Download WordPress
- download_result = cls.wp_cli(path, ['core', 'download', '--locale=en_US'])
- if not download_result['success']:
- return download_result
-
- # Create wp-config.php
- config_result = cls.wp_cli(path, [
- 'config', 'create',
- f'--dbname={db_name}',
- f'--dbuser={db_user}',
- f'--dbpass={db_password}',
- f'--dbhost={db_host}',
- f'--dbprefix={db_prefix}'
- ])
- if not config_result['success']:
- return config_result
-
- # Install WordPress
- install_result = cls.wp_cli(path, [
- 'core', 'install',
- f'--url={site_url}',
- f'--title={site_title}',
- f'--admin_user={admin_user}',
- f'--admin_password={admin_password}',
- f'--admin_email={admin_email}',
- '--skip-email'
- ])
- if not install_result['success']:
- return install_result
-
- # Set permissions
- cls._set_permissions(path)
-
- # Apply security hardening
- cls.harden_wordpress(path)
-
- return {
- 'success': True,
- 'message': 'WordPress installed successfully',
- 'admin_user': admin_user,
- 'admin_password': admin_password,
- 'path': path,
- 'url': site_url
- }
-
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def get_php_info(cls, path: str) -> Dict:
- """Read the LIVE PHP version + key ini limits from inside the running
- WordPress container via the Docker-aware wp_cli bridge. Read-only.
- """
- info = {}
- ver = cls.wp_cli(path, ['eval', 'echo phpversion();'])
- if ver.get('success'):
- info['php_version'] = (ver.get('output') or '').strip()
- php = (
- "foreach(['memory_limit','upload_max_filesize','post_max_size',"
- "'max_execution_time','max_input_time'] as $k){"
- "echo $k.'='.ini_get($k).\"\\n\";}"
- )
- limits = cls.wp_cli(path, ['eval', php])
- parsed = {}
- if limits.get('success'):
- for line in (limits.get('output') or '').splitlines():
- line = line.strip()
- if '=' in line:
- k, v = line.split('=', 1)
- parsed[k.strip()] = v.strip()
- info['limits'] = parsed
- info['source'] = 'container'
- return info
-
- @classmethod
- def get_available_php_versions(cls) -> List[str]:
- """Official wordpress image PHP variant tags we support switching to."""
- return ['8.1', '8.2', '8.3']
-
- @classmethod
- def set_php_version(cls, path: str, version: str) -> Dict:
- """Switch a Docker WP site to a different PHP by rewriting the compose
- image tag (wordpress:<wp>-php<version>-apache) and recreating the app
- container. Volumes/DB persist. NOT host php-fpm. Brief downtime.
- """
- from app.services.docker_service import DockerService
- if version not in cls.get_available_php_versions():
- return {'success': False, 'error': f'Unsupported PHP version: {version}'}
- compose_file = os.path.join(path, 'docker-compose.yml')
- if not os.path.exists(compose_file):
- return {'success': False, 'error': 'Not a Docker-stack site (no docker-compose.yml)'}
- try:
- with open(compose_file, 'r') as f:
- content = f.read()
- import re as _re
- m = _re.search(r'image:\s*wordpress:([^\s]+)', content)
- if not m:
- return {'success': False, 'error': 'wordpress image line not found in compose file'}
- current_tag = m.group(1)
- # Derive the WP core from the existing tag; fall back to the known core for
- # legacy compose files that still carry an unresolved ${VERSION...} literal,
- # so the switch never drops the core pin (e.g. -> php8.2-apache).
- wp_core = current_tag.split('-')[0] if current_tag and current_tag[0].isdigit() else cls.WP_CORE
- new_tag = f'{wp_core}-php{version}-apache'
- new_content = content.replace(f'image: wordpress:{current_tag}', f'image: wordpress:{new_tag}')
- with open(compose_file, 'w') as f:
- f.write(new_content)
- up = DockerService.compose_up(path, detach=True, build=False)
- if not up.get('success'):
- return {'success': False, 'error': up.get('error') or 'compose up failed', 'image_tag': new_tag}
- cls._wait_for_wp_ready(path)
- live = cls.get_php_info(path).get('php_version')
- return {'success': True, 'message': f'Switched to PHP {version}', 'image_tag': new_tag, 'php_version': live}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- # --- Per-site PHP ini limits (#24 write side) -------------------------------
- # The official wordpress:*-apache image is Apache + mod_php and scans
- # /usr/local/etc/php/conf.d for *.ini drop-ins. We persist a host-side ini and
- # BIND-MOUNT it into conf.d so it survives container recreate — a plain
- # `docker exec` write would be lost on the next `compose up`. Every directive is
- # whitelisted + regex-validated because the value is written as a raw php.ini line.
- PHP_LIMIT_SPEC = {
- 'memory_limit': r'^(-1|\d{1,5}[KMGkmg]?)$',
- 'upload_max_filesize': r'^\d{1,5}[KMGkmg]?$',
- 'post_max_size': r'^\d{1,5}[KMGkmg]?$',
- 'max_execution_time': r'^\d{1,5}$',
- 'max_input_time': r'^-?\d{1,5}$',
- 'max_input_vars': r'^\d{1,6}$',
- }
- PHP_CONF_DIR = 'php-conf'
- PHP_CONF_FILE = 'zz-serverkit.ini'
- PHP_CONF_CONTAINER = '/usr/local/etc/php/conf.d/zz-serverkit.ini'
-
- @classmethod
- def get_php_limit_spec(cls) -> Dict:
- """The editable php.ini directives (key -> validation regex) the limits
- panel may set. Exposed so the frontend renders exactly the safe set."""
- return dict(cls.PHP_LIMIT_SPEC)
-
- @staticmethod
- def _read_php_ini(ini_path: str) -> Dict:
- """Parse a simple `key = value` ini into a dict (comments/blank lines skipped).
- Never raises — a missing/garbled file just yields {}."""
- out = {}
- if os.path.exists(ini_path):
- try:
- with open(ini_path, 'r') as f:
- for line in f:
- line = line.strip()
- if not line or line.startswith(';') or '=' not in line:
- continue
- k, v = line.split('=', 1)
- out[k.strip()] = v.strip()
- except Exception:
- pass
- return out
-
- @classmethod
- def set_php_limits(cls, path: str, limits: Dict) -> Dict:
- """Durably set per-site PHP ini limits for a Docker WP site.
-
- Writes a host-side conf.d drop-in, bind-mounts it into the container's
- php conf.d (so it survives recreate), then reloads: a newly-added mount is
- applied via `compose up -d` (recreates the app container); a content-only
- change restarts the `wordpress` service so mod_php re-reads php.ini.
- Partial updates merge with any previously-set directives.
- """
- import re as _re
- import yaml
- from app.services.docker_service import DockerService
-
- compose_file = os.path.join(path, 'docker-compose.yml')
- if not os.path.exists(compose_file):
- return {'success': False, 'error': 'Not a Docker-stack site (no docker-compose.yml)'}
-
- # 1) Validate + sanitize against the whitelist (values become raw ini lines).
- clean = {}
- for k, v in (limits or {}).items():
- if k not in cls.PHP_LIMIT_SPEC:
- return {'success': False, 'error': f'Unknown PHP limit: {k}'}
- val = str(v).strip()
- # fullmatch (not match) so a value like "256M\nevil = 1" can never
- # smuggle an extra ini directive past the `$` anchor into the file.
- if not _re.fullmatch(cls.PHP_LIMIT_SPEC[k], val):
- return {'success': False, 'error': f'Invalid value for {k}: {val}'}
- clean[k] = val
- if not clean:
- return {'success': False, 'error': 'No valid limits provided'}
-
- try:
- # 2) Write the host ini FIRST — a single-file bind-mount needs the
- # source to exist before `compose up`, else Docker makes a dir.
- conf_dir = os.path.join(path, cls.PHP_CONF_DIR)
- os.makedirs(conf_dir, exist_ok=True)
- ini_path = os.path.join(conf_dir, cls.PHP_CONF_FILE)
- merged = cls._read_php_ini(ini_path)
- merged.update(clean)
- body = ['; Managed by ServerKit (#24) — per-site PHP limits. Do not edit by hand.']
- body += [f'{k} = {v}' for k, v in merged.items()]
- with open(ini_path, 'w') as f:
- f.write('\n'.join(body) + '\n')
-
- # 3) Ensure the wordpress service bind-mounts the ini into conf.d.
- with open(compose_file, 'r') as f:
- compose = yaml.safe_load(f) or {}
- wp = (compose.get('services') or {}).get('wordpress')
- if not isinstance(wp, dict):
- return {'success': False, 'error': 'wordpress service not found in compose file'}
- mount = f'./{cls.PHP_CONF_DIR}/{cls.PHP_CONF_FILE}:{cls.PHP_CONF_CONTAINER}:ro'
- vols = wp.get('volumes') or []
- mount_added = mount not in vols
- if mount_added:
- vols.append(mount)
- wp['volumes'] = vols
- with open(compose_file, 'w') as f:
- yaml.dump(compose, f, default_flow_style=False, sort_keys=False)
-
- # 4) Apply: recreate if the mount is new, else restart so php.ini reloads.
- if mount_added:
- res = DockerService.compose_up(path, detach=True, build=False)
- else:
- res = DockerService.compose_restart(path, service='wordpress')
- if not res.get('success'):
- return {'success': False, 'error': res.get('error') or 'Failed to apply PHP limits'}
- cls._wait_for_wp_ready(path)
- return {'success': True, 'message': 'PHP limits updated', 'limits': merged,
- 'applied': cls.get_php_info(path).get('limits', {})}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def is_multisite(cls, path: str) -> bool:
- """Return True if the WordPress install at ``path`` is a multisite network.
-
- Uses ``wp core is-multisite`` (exit 0 = multisite, non-zero = single).
- Routes through the Docker-aware wp_cli bridge automatically.
- """
- result = cls.wp_cli(path, ['core', 'is-multisite'])
- return bool(result.get('success'))
-
- @classmethod
- def get_wordpress_info(cls, path: str) -> Optional[Dict]:
- """Get WordPress installation info."""
- if not os.path.exists(os.path.join(path, 'wp-config.php')):
- return None
-
- info = {'path': path}
-
- # Get core version
- version_result = cls.wp_cli(path, ['core', 'version'])
- if version_result['success']:
- info['version'] = version_result['output'].strip()
-
- # Check for updates
- update_result = cls.wp_cli(path, ['core', 'check-update', '--format=json'])
- if update_result['success'] and update_result['output'].strip():
- try:
- updates = json.loads(update_result['output'])
- info['update_available'] = len(updates) > 0
- info['latest_version'] = updates[0]['version'] if updates else info.get('version')
- except Exception:
- info['update_available'] = False
-
- # Get site URL
- url_result = cls.wp_cli(path, ['option', 'get', 'siteurl'])
- if url_result['success']:
- info['url'] = url_result['output'].strip()
-
- # Get site title
- title_result = cls.wp_cli(path, ['option', 'get', 'blogname'])
- if title_result['success']:
- info['title'] = title_result['output'].strip()
-
- # Get admin email
- email_result = cls.wp_cli(path, ['option', 'get', 'admin_email'])
- if email_result['success']:
- info['admin_email'] = email_result['output'].strip()
-
- # Detect multisite (wp core is-multisite: exit 0 = multisite)
- info['multisite'] = cls.is_multisite(path)
-
- return info
-
- @classmethod
- def update_wordpress(cls, path: str) -> Dict:
- """Update WordPress core."""
- result = cls.wp_cli(path, ['core', 'update'])
- if result['success']:
- # Update database if needed
- cls.wp_cli(path, ['core', 'update-db'])
- return {'success': True, 'message': 'WordPress updated successfully'}
- return result
-
- @classmethod
- def get_plugins(cls, path: str) -> List[Dict]:
- """Get list of installed plugins."""
- result = cls.wp_cli(path, ['plugin', 'list', '--format=json'])
- if result['success']:
- try:
- return json.loads(result['output'])
- except Exception:
- return []
- return []
-
- @classmethod
- def install_plugin(cls, path: str, plugin: str, activate: bool = True) -> Dict:
- """Install a WordPress plugin."""
- cmd = ['plugin', 'install', plugin]
- if activate:
- cmd.append('--activate')
-
- result = cls.wp_cli(path, cmd)
- if result['success']:
- return {'success': True, 'message': f'Plugin {plugin} installed'}
- return result
-
- @classmethod
- def uninstall_plugin(cls, path: str, plugin: str) -> Dict:
- """Uninstall a WordPress plugin."""
- # Deactivate first
- cls.wp_cli(path, ['plugin', 'deactivate', plugin])
-
- result = cls.wp_cli(path, ['plugin', 'delete', plugin])
- if result['success']:
- return {'success': True, 'message': f'Plugin {plugin} uninstalled'}
- return result
-
- @classmethod
- def activate_plugin(cls, path: str, plugin: str) -> Dict:
- """Activate a plugin."""
- result = cls.wp_cli(path, ['plugin', 'activate', plugin])
- return result
-
- @classmethod
- def deactivate_plugin(cls, path: str, plugin: str) -> Dict:
- """Deactivate a plugin."""
- result = cls.wp_cli(path, ['plugin', 'deactivate', plugin])
- return result
-
- @classmethod
- def update_plugins(cls, path: str, plugins: List[str] = None) -> Dict:
- """Update plugins."""
- cmd = ['plugin', 'update']
- if plugins:
- cmd.extend(plugins)
- else:
- cmd.append('--all')
-
- result = cls.wp_cli(path, cmd)
- if result['success']:
- return {'success': True, 'message': 'Plugins updated'}
- return result
-
- @classmethod
- def update_themes(cls, path: str, themes: List[str] = None) -> Dict:
- """Update themes."""
- cmd = ['theme', 'update']
- if themes:
- cmd.extend(themes)
- else:
- cmd.append('--all')
-
- result = cls.wp_cli(path, cmd)
- if result['success']:
- return {'success': True, 'message': 'Themes updated'}
- return result
-
- @classmethod
- def get_themes(cls, path: str) -> List[Dict]:
- """Get list of installed themes."""
- result = cls.wp_cli(path, ['theme', 'list', '--format=json'])
- if result['success']:
- try:
- return json.loads(result['output'])
- except Exception:
- return []
- return []
-
- @classmethod
- def install_theme(cls, path: str, theme: str, activate: bool = False) -> Dict:
- """Install a WordPress theme."""
- cmd = ['theme', 'install', theme]
- if activate:
- cmd.append('--activate')
-
- result = cls.wp_cli(path, cmd)
- if result['success']:
- return {'success': True, 'message': f'Theme {theme} installed'}
- return result
-
- @classmethod
- def activate_theme(cls, path: str, theme: str) -> Dict:
- """Activate a theme."""
- result = cls.wp_cli(path, ['theme', 'activate', theme])
- return result
-
- @classmethod
- def backup_wordpress(cls, path: str, include_db: bool = True) -> Dict:
- """Create a backup of WordPress installation."""
- timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
- site_name = os.path.basename(path)
- backup_name = f'{site_name}_{timestamp}'
- backup_path = os.path.join(cls.BACKUP_DIR, backup_name)
-
- try:
- # Create backup directory
- run_privileged(['mkdir', '-p', backup_path])
-
- # Backup files
- files_backup = os.path.join(backup_path, 'files.tar.gz')
- run_privileged(
- ['tar', '-czf', files_backup, '-C', os.path.dirname(path), os.path.basename(path)],
- timeout=600
- )
-
- # Backup database
- if include_db:
- db_backup = os.path.join(backup_path, 'database.sql')
- result = cls.wp_cli(path, ['db', 'export', db_backup])
- if not result['success']:
- return {'success': False, 'error': f'Database backup failed: {result.get("error")}'}
-
- # Get backup size
- try:
- size = sum(os.path.getsize(os.path.join(backup_path, f))
- for f in os.listdir(backup_path)
- if os.path.isfile(os.path.join(backup_path, f)))
- except Exception:
- size = 0
-
- return {
- 'success': True,
- 'message': 'Backup created successfully',
- 'backup_path': backup_path,
- 'backup_name': backup_name,
- 'size': size,
- 'timestamp': timestamp
- }
-
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def list_backups(cls, site_name: str = None) -> List[Dict]:
- """List available backups."""
- backups = []
-
- if not os.path.exists(cls.BACKUP_DIR):
- return backups
-
- try:
- for name in os.listdir(cls.BACKUP_DIR):
- backup_path = os.path.join(cls.BACKUP_DIR, name)
- if os.path.isdir(backup_path):
- if site_name and not name.startswith(site_name):
- continue
-
- # Get backup info
- files_backup = os.path.join(backup_path, 'files.tar.gz')
- db_backup = os.path.join(backup_path, 'database.sql')
-
- size = 0
- for f in [files_backup, db_backup]:
- if os.path.exists(f):
- size += os.path.getsize(f)
-
- # Parse timestamp from name
- parts = name.rsplit('_', 2)
- if len(parts) >= 3:
- timestamp = f'{parts[-2]}_{parts[-1]}'
- else:
- timestamp = 'unknown'
-
- backups.append({
- 'name': name,
- 'path': backup_path,
- 'has_files': os.path.exists(files_backup),
- 'has_database': os.path.exists(db_backup),
- 'size': size,
- 'timestamp': timestamp
- })
- except Exception:
- pass
-
- return sorted(backups, key=lambda x: x['timestamp'], reverse=True)
-
- @classmethod
- def restore_backup(cls, backup_name: str, target_path: str) -> Dict:
- """Restore a WordPress backup."""
- backup_path = os.path.join(cls.BACKUP_DIR, backup_name)
-
- if not os.path.exists(backup_path):
- return {'success': False, 'error': 'Backup not found'}
-
- try:
- files_backup = os.path.join(backup_path, 'files.tar.gz')
- db_backup = os.path.join(backup_path, 'database.sql')
-
- # Restore files
- if os.path.exists(files_backup):
- # Remove existing files
- if os.path.exists(target_path):
- run_privileged(['rm', '-rf', target_path])
-
- # Extract backup
- run_privileged(
- ['tar', '-xzf', files_backup, '-C', os.path.dirname(target_path)],
- timeout=600
- )
-
- # Restore database
- if os.path.exists(db_backup):
- result = cls.wp_cli(target_path, ['db', 'import', db_backup])
- if not result['success']:
- return {'success': False, 'error': f'Database restore failed: {result.get("error")}'}
-
- # Fix permissions
- cls._set_permissions(target_path)
-
- return {'success': True, 'message': 'Backup restored successfully'}
-
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def delete_backup(cls, backup_name: str) -> Dict:
- """Delete a backup."""
- backup_path = os.path.join(cls.BACKUP_DIR, backup_name)
-
- if not os.path.exists(backup_path):
- return {'success': False, 'error': 'Backup not found'}
-
- try:
- run_privileged(['rm', '-rf', backup_path])
- return {'success': True, 'message': 'Backup deleted'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def _wait_for_wp_ready(cls, path: str, timeout: int = 60) -> bool:
- """Poll the WP container (via the Docker-aware wp_cli bridge) until
- WordPress core files + DB are reachable so `wp` commands can run.
-
- Returns True once `wp core version` succeeds, else False on timeout.
- """
- import time as _time
- deadline = _time.time() + timeout
- while _time.time() < deadline:
- check = cls.wp_cli(path, ['core', 'version'])
- if check.get('success'):
- return True
- _time.sleep(3)
- return False
-
- @classmethod
- def _harden_docker_site(cls, path: str) -> List[str]:
- """Apply container-valid security hardening via the Docker-aware wp_cli
- bridge. Filesystem hardening (chmod/.htaccess) does NOT apply to the
- named-volume Docker model and is intentionally skipped. FORCE_SSL_ADMIN
- is also skipped (these sites are http://localhost:PORT with no TLS).
- """
- actions = []
- if cls.wp_cli(path, ['config', 'set', 'DISALLOW_FILE_EDIT', 'true', '--raw']).get('success'):
- actions.append('Disabled in-admin file editing')
- if cls.wp_cli(path, ['config', 'set', 'XMLRPC_REQUEST', 'false', '--raw']).get('success'):
- actions.append('Disabled XML-RPC')
- if cls.wp_cli(path, ['config', 'shuffle-salts']).get('success'):
- actions.append('Regenerated security keys')
- return actions
-
- @classmethod
- def harden_wordpress(cls, path: str) -> Dict:
- """Apply security hardening to WordPress."""
- results = []
-
- try:
- # Disable file editing in admin
- cls.wp_cli(path, ['config', 'set', 'DISALLOW_FILE_EDIT', 'true', '--raw'])
- results.append('Disabled file editing')
-
- # Force SSL for admin
- cls.wp_cli(path, ['config', 'set', 'FORCE_SSL_ADMIN', 'true', '--raw'])
- results.append('Enabled SSL for admin')
-
- # Disable XML-RPC (common attack vector)
- cls.wp_cli(path, ['config', 'set', 'XMLRPC_REQUEST', 'false', '--raw'])
- results.append('Disabled XML-RPC')
-
- # Set secure file permissions
- cls._set_permissions(path)
- results.append('Set secure file permissions')
-
- # Create .htaccess security rules
- cls._create_htaccess_security(path)
- results.append('Added .htaccess security rules')
-
- # Regenerate security keys
- cls.wp_cli(path, ['config', 'shuffle-salts'])
- results.append('Regenerated security keys')
-
- return {'success': True, 'message': 'Security hardening applied', 'actions': results}
-
- except Exception as e:
- return {'success': False, 'error': str(e), 'partial_actions': results}
-
- @classmethod
- def _set_permissions(cls, path: str):
- """Set secure file permissions for WordPress."""
- try:
- # Set ownership
- run_privileged(['chown', '-R', 'www-data:www-data', path])
-
- # Set directory permissions
- run_privileged(
- ['find', path, '-type', 'd', '-exec', 'chmod', '755', '{}', ';']
- )
-
- # Set file permissions
- run_privileged(
- ['find', path, '-type', 'f', '-exec', 'chmod', '644', '{}', ';']
- )
-
- # Protect wp-config.php
- wp_config = os.path.join(path, 'wp-config.php')
- if os.path.exists(wp_config):
- run_privileged(['chmod', '600', wp_config])
-
- except Exception:
- pass
-
- @classmethod
- def _create_htaccess_security(cls, path: str):
- """Create security rules in .htaccess."""
- htaccess_path = os.path.join(path, '.htaccess')
-
- security_rules = '''
-# ServerKit Security Rules
-# Protect wp-config.php
-<files wp-config.php>
-order allow,deny
-deny from all
-</files>
-
-# Protect .htaccess
-<files .htaccess>
-order allow,deny
-deny from all
-</files>
-
-# Disable directory browsing
-Options -Indexes
-
-# Block access to sensitive files
-<FilesMatch "^(wp-config\\.php|\\.htaccess|readme\\.html|license\\.txt)$">
-Order allow,deny
-Deny from all
-</FilesMatch>
-
-# Block PHP execution in uploads
-<IfModule mod_rewrite.c>
-RewriteEngine On
-RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
-</IfModule>
-'''
-
- try:
- # Read existing htaccess
- existing = ''
- if os.path.exists(htaccess_path):
- with open(htaccess_path, 'r') as f:
- existing = f.read()
-
- # Only add if not already present
- if '# ServerKit Security Rules' not in existing:
- new_content = security_rules + '\n' + existing
- run_privileged(
- ['tee', htaccess_path],
- input=new_content
- )
- except Exception:
- pass
-
- @classmethod
- def search_replace(cls, path: str, search: str, replace: str, dry_run: bool = False) -> Dict:
- """Search and replace in WordPress database."""
- cmd = ['search-replace', search, replace, '--all-tables']
-
- if dry_run:
- cmd.append('--dry-run')
-
- result = cls.wp_cli(path, cmd)
- return result
-
- # ── URL swap tool ────────────────────────────────────────────────────────
- # Changing a WordPress site's URL is not a single UPDATE: the URL is embedded
- # across wp_options, post content, and PHP-serialized blobs whose byte-length
- # prefixes break under a naive REPLACE. WP-CLI `search-replace` is
- # serialization-safe, so it is the engine here (the pure-SQL path in
- # db_sync_service is the fallback for offline dumps only). We dry-run first,
- # back up before mutating, and roll back on failure.
-
- @staticmethod
- def _normalize_url(url: str) -> Optional[str]:
- """Canonicalise a user-supplied URL to ``scheme://host[/path]`` with no
- trailing slash. Returns None if it isn't a usable http(s) URL."""
- import re
- from urllib.parse import urlparse
- if not url:
- return None
- url = url.strip().rstrip('/')
- if '://' not in url:
- url = 'http://' + url
- p = urlparse(url)
- if p.scheme not in ('http', 'https') or not p.netloc:
- return None
- # Reject obviously-invalid hosts (spaces, etc.); allow hostname[:port].
- if not re.match(r'^[A-Za-z0-9.\-]+(:\d+)?$', p.netloc):
- return None
- return f'{p.scheme}://{p.netloc}{p.path.rstrip("/")}'
-
- @staticmethod
- def _host_of(url: str) -> str:
- from urllib.parse import urlparse
- return urlparse(url).netloc
-
- @classmethod
- def _url_swap_pairs(cls, old_url: str, new_url: str) -> List[tuple]:
- """search→replace pairs for a URL change: the full URL (covers scheme
- changes) plus a host-only pair (covers protocol-relative and bare-host
- references) when the host actually changes."""
- pairs = [(old_url, new_url)]
- old_host, new_host = cls._host_of(old_url), cls._host_of(new_url)
- if old_host and new_host and old_host != new_host:
- pairs.append((old_host, new_host))
- return pairs
-
- @staticmethod
- def _parse_sr_count(output: str) -> int:
- """Pull the replacement total out of WP-CLI search-replace output
- ('Success: 12 replacements to be made.' / 'Success: Made 12 replacements.')."""
- import re
- if not output:
- return 0
- for line in output.splitlines():
- if 'Success' in line:
- m = re.search(r'(\d[\d,]*)\s+replacement', line)
- if m:
- return int(m.group(1).replace(',', ''))
- return 0
-
- @classmethod
- def _site_current_url(cls, app) -> Optional[str]:
- """The site's live URL: prefer WordPress's own stored siteurl (source of
- truth for what must be search-replaced), else the canonical domain/port."""
- if app and app.root_path:
- res = cls.wp_cli(app.root_path, ['option', 'get', 'siteurl'])
- if res.get('success') and (res.get('output') or '').strip():
- return cls._normalize_url(res['output'].strip())
- return cls._canonical_site_url(app) if app else None
-
- @classmethod
- def preview_url_change(cls, app, new_url: str) -> Dict:
- """Dry-run a URL change: per-pair replacement counts, no mutation."""
- if not app or not app.root_path:
- return {'success': False, 'error': 'Site has no application/root path'}
- new_url = cls._normalize_url(new_url)
- if not new_url:
- return {'success': False, 'error': 'A valid new URL (including http:// or https://) is required'}
- old_url = cls._site_current_url(app)
- if not old_url:
- return {'success': False, 'error': 'Could not determine the current site URL'}
- if new_url == old_url:
- return {'success': False, 'error': 'The new URL is the same as the current one'}
-
- rows, total = [], 0
- for search, replace in cls._url_swap_pairs(old_url, new_url):
- res = cls.wp_cli(app.root_path, ['search-replace', search, replace,
- '--all-tables', '--skip-columns=guid',
- '--dry-run', '--report-changed-only'])
- if not res.get('success'):
- return {'success': False, 'error': res.get('error') or 'Preview failed',
- 'current_url': old_url, 'new_url': new_url}
- count = cls._parse_sr_count(res.get('output'))
- total += count
- rows.append({'search': search, 'replace': replace, 'replacements': count})
- return {'success': True, 'current_url': old_url, 'new_url': new_url,
- 'pairs': rows, 'total': total}
-
- @classmethod
- def change_site_url(cls, app, new_url: str, keep_old_redirect: bool = True) -> Dict:
- """Change a site's URL end to end: back up, serialization-safe DB rewrite,
- update home/siteurl, flush caches, then re-point the Domain row + nginx
- vhost. Rolls the database back from the backup if the rewrite fails.
-
- With ``keep_old_redirect`` the previous host keeps resolving (its vhost
- entry stays) so WordPress 301s it to the new canonical URL.
- """
- if not app or not app.root_path:
- return {'success': False, 'error': 'Site has no application/root path'}
- new_url = cls._normalize_url(new_url)
- if not new_url:
- return {'success': False, 'error': 'A valid new URL (including http:// or https://) is required'}
- old_url = cls._site_current_url(app)
- if not old_url:
- return {'success': False, 'error': 'Could not determine the current site URL'}
- if new_url == old_url:
- return {'success': False, 'error': 'The new URL is the same as the current one'}
-
- # 1) Backup first — this is the rollback point.
- backup = cls.backup_wordpress(app.root_path, include_db=True)
- if not backup.get('success'):
- return {'success': False, 'error': f"Backup failed, aborting URL change: {backup.get('error')}"}
-
- # 2) Serialization-safe DB rewrite, then finalize options + caches.
- total = 0
- try:
- for search, replace in cls._url_swap_pairs(old_url, new_url):
- res = cls.wp_cli(app.root_path, ['search-replace', search, replace,
- '--all-tables', '--skip-columns=guid'])
- if not res.get('success'):
- raise RuntimeError(res.get('error') or 'search-replace failed')
- total += cls._parse_sr_count(res.get('output'))
- cls.wp_cli(app.root_path, ['option', 'update', 'home', new_url])
- cls.wp_cli(app.root_path, ['option', 'update', 'siteurl', new_url])
- cls.wp_cli(app.root_path, ['cache', 'flush'])
- cls.wp_cli(app.root_path, ['rewrite', 'flush'])
- except Exception as e:
- restore = cls.restore_backup(backup['backup_name'], app.root_path)
- return {'success': False,
- 'error': f'URL change failed and the database was rolled back: {e}',
- 'rolled_back': restore.get('success', False),
- 'backup': backup['backup_name']}
-
- # 3) Re-point routing (best-effort; the DB change has already succeeded).
- warnings = []
- new_host = cls._host_of(new_url)
- rp = cls._repoint_primary_domain(app, new_host, keep_old=keep_old_redirect)
- if rp:
- warnings.append(rp)
- vhost = cls._write_app_vhost(app)
- if vhost.get('warning'):
- warnings.append(vhost['warning'])
-
- return {'success': True, 'old_url': old_url, 'new_url': new_url,
- 'replacements': total, 'backup': backup['backup_name'],
- 'kept_old_host': keep_old_redirect,
- 'warning': '; '.join(warnings) if warnings else None}
-
- @classmethod
- def _repoint_primary_domain(cls, app, new_host: str, keep_old: bool = True) -> Optional[str]:
- """Make ``new_host`` the app's primary Domain. With ``keep_old`` the other
- host rows are demoted (kept, so they still resolve); otherwise removed.
- Returns a warning string on failure, else None."""
- from app import db
- from app.models.domain import Domain
- if not new_host:
- return None
- try:
- found_new = False
- for d in Domain.query.filter_by(application_id=app.id).all():
- if d.name == new_host:
- d.is_primary = True
- found_new = True
- elif keep_old:
- d.is_primary = False
- else:
- db.session.delete(d)
- if not found_new:
- db.session.add(Domain(name=new_host, is_primary=True, application_id=app.id))
- db.session.commit()
- return None
- except Exception as e:
- db.session.rollback()
- return f'could not update domain rows: {e}'
-
- @classmethod
- def attach_custom_domain(cls, app, domain: str, migrate: bool = True,
- issue_ssl: bool = False, email: str = None) -> Dict:
- """Point a user-owned domain at a site, end to end.
-
- Auto-creates the domain's A record via a connected DNS provider (or
- returns the record to add manually), optionally obtains a Let's Encrypt
- certificate, then migrates the site URL to the domain by reusing
- ``change_site_url``. External steps (DNS, SSL) degrade to warnings rather
- than failing the attach; only a requested migration that errors aborts.
- """
- from app import db
- from app.models.domain import Domain
- from app.services.site_domain_service import SiteDomainService
- from app.services.dns_provider_service import DNSProviderService
-
- if not app or not app.root_path:
- return {'success': False, 'error': 'Site has no application/root path'}
-
- # Accept a bare host or a full URL; reduce to the host.
- host = cls._host_of(cls._normalize_url(domain) or '') or (domain or '').strip().lower().rstrip('/')
- if not host or '.' not in host:
- return {'success': False, 'error': 'A valid custom domain (e.g. example.com) is required'}
-
- # 1) DNS: auto-create the A record, or report what to add manually.
- dns = DNSProviderService.ensure_a_record(host, SiteDomainService.server_ip())
-
- # 2) Optional HTTPS. certbot --nginx validates over the host's :80 vhost,
- # so the host must already be served before the cert is requested.
- ssl_result = None
- use_https = False
- if issue_ssl:
- from app.services.ssl_service import SSLService
- if not Domain.query.filter_by(name=host).first():
- db.session.add(Domain(name=host, is_primary=False, application_id=app.id))
- db.session.commit()
- cls._write_app_vhost(app)
- ssl_result = SSLService.obtain_certificate([host], email or f'admin@{host}')
- use_https = bool(ssl_result and ssl_result.get('success'))
-
- # 3) Migrate the site URL to the domain (single rewrite to the final scheme).
- scheme = 'https' if use_https else 'http'
- migration = None
- if migrate:
- migration = cls.change_site_url(app, f'{scheme}://{host}', keep_old_redirect=True)
- if not migration.get('success'):
- return {'success': False,
- 'error': f"DNS handled but moving the site to {host} failed: {migration.get('error')}",
- 'dns': dns, 'ssl': ssl_result, 'migration': migration}
- else:
- # Attach the domain (primary + vhost) without rewriting WordPress.
- cls._repoint_primary_domain(app, host, keep_old=True)
- cls._write_app_vhost(app)
-
- warnings = []
- if not dns.get('created'):
- warnings.append(dns.get('message') or 'Add the DNS record manually.')
- if issue_ssl and not use_https:
- warnings.append('HTTPS is not set up yet — enable SSL once DNS has propagated to this server.')
- if migration and migration.get('warning'):
- warnings.append(migration['warning'])
-
- return {
- 'success': True,
- 'domain': host,
- 'url': (migration or {}).get('new_url') or f'{scheme}://{host}',
- 'dns': dns,
- 'ssl': ssl_result,
- 'migration': migration,
- 'warning': '; '.join(warnings) if warnings else None,
- }
-
- @classmethod
- def optimize_database(cls, path: str) -> Dict:
- """Optimize WordPress database."""
- result = cls.wp_cli(path, ['db', 'optimize'])
- return result
-
- PAGE_CACHE_PLUGIN = 'cache-enabler'
-
- @classmethod
- def get_page_cache_status(cls, path: str) -> Dict:
- """Report whether the full-page cache plugin is installed/active."""
- res = cls.wp_cli(path, ['plugin', 'get', cls.PAGE_CACHE_PLUGIN, '--field=status'])
- status = (res.get('output') or '').strip() if res.get('success') else ''
- return {
- 'success': True,
- 'plugin': cls.PAGE_CACHE_PLUGIN,
- 'installed': res.get('success', False),
- 'active': status == 'active',
- 'status': status,
- }
-
- @classmethod
- def enable_page_cache(cls, path: str) -> Dict:
- """Install + activate a full-page disk cache plugin with WP-aware skip rules."""
- inst = cls.install_plugin(path, cls.PAGE_CACHE_PLUGIN, activate=True)
- if not inst.get('success'):
- return {'success': False, 'error': 'Failed to install page-cache plugin: ' + (inst.get('error') or '')}
- opts = {
- 'cache_expires': 1,
- 'clear_on_upgrade': 1,
- 'excl_regexp': '/(wp-admin|wp-login|cart|checkout|my-account)/',
- 'excl_cookies': 'comment_author|wordpress_logged_in|wp-postpass|woocommerce_cart_hash|woocommerce_items_in_cart',
- }
- cls.wp_cli(path, ['option', 'update', cls.PAGE_CACHE_PLUGIN, json.dumps(opts), '--format=json'])
- cls.wp_cli(path, ['rewrite', 'flush'])
- return {'success': True, 'message': 'Page cache enabled', 'plugin': cls.PAGE_CACHE_PLUGIN}
-
- @classmethod
- def disable_page_cache(cls, path: str) -> Dict:
- """Purge then deactivate the page-cache plugin."""
- cls.purge_page_cache(path)
- res = cls.deactivate_plugin(path, cls.PAGE_CACHE_PLUGIN)
- if res.get('success'):
- return {'success': True, 'message': 'Page cache disabled'}
- return {'success': False, 'error': res.get('error') or 'Failed to disable page cache'}
-
- @classmethod
- def purge_page_cache(cls, path: str) -> bool:
- """Best-effort full-page cache purge. Never raises."""
- try:
- res = cls.wp_cli(path, ['cache-enabler', 'clear'])
- if res.get('success'):
- return True
- res = cls.wp_cli(path, ['eval', 'if (function_exists("cache_enabler_clear_complete_cache")) cache_enabler_clear_complete_cache();'])
- return bool(res.get('success'))
- except Exception:
- return False
-
- @classmethod
- def _ensure_redis_in_stack(cls, path: str) -> Dict:
- """Ensure the site's compose stack has a redis service, recreating the
- stack (additive compose up -d, no downtime) if one had to be injected.
- Idempotent — short-circuits when redis already present.
- """
- import yaml
- compose_file = os.path.join(path, 'docker-compose.yml')
- if not os.path.exists(compose_file):
- return {'success': False, 'error': 'Not a Docker-stack site (no docker-compose.yml)'}
- try:
- with open(compose_file, 'r') as f:
- compose = yaml.safe_load(f) or {}
- services = compose.setdefault('services', {})
- if 'redis' in services:
- return {'success': True, 'created': False}
- app_name = os.path.basename(path)
- from app.models import Application
- app = Application.query.filter_by(root_path=path).first()
- if app:
- app_name = app.name
- services['redis'] = {
- 'image': 'redis:7-alpine',
- 'container_name': f'{app_name}-redis',
- 'restart': 'unless-stopped',
- }
- wp = services.get('wordpress')
- if isinstance(wp, dict):
- deps = wp.get('depends_on') or []
- if isinstance(deps, list) and 'redis' not in deps:
- deps.append('redis')
- wp['depends_on'] = deps
- with open(compose_file, 'w') as f:
- yaml.dump(compose, f, default_flow_style=False, sort_keys=False)
- from app.services.docker_service import DockerService
- up = DockerService.compose_up(path, detach=True)
- if not up.get('success'):
- return {'success': False, 'error': 'Failed to recreate stack with redis: ' + (up.get('error') or '')}
- cls._wait_for_wp_ready(path)
- return {'success': True, 'created': True}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def enable_object_cache(cls, path: str) -> Dict:
- """Enable a Redis object cache: ensure a redis container, install+activate
- the redis-cache plugin, point WP at redis, and turn the drop-in on.
- """
- ensure = cls._ensure_redis_in_stack(path)
- if not ensure.get('success'):
- return ensure
- actions = []
- if ensure.get('created'):
- actions.append('Added redis container to stack')
- inst = cls.wp_cli(path, ['plugin', 'install', 'redis-cache', '--activate'])
- if not inst.get('success'):
- return {'success': False, 'error': 'Failed to install redis-cache plugin: ' + (inst.get('error') or '')}
- actions.append('Installed redis-cache plugin')
- cls.wp_cli(path, ['config', 'set', 'WP_REDIS_HOST', 'redis'])
- cls.wp_cli(path, ['config', 'set', 'WP_REDIS_PORT', '6379', '--raw'])
- enable = cls.wp_cli(path, ['redis', 'enable'])
- if not enable.get('success'):
- return {'success': False, 'error': 'Plugin installed but enabling the drop-in failed: ' + (enable.get('error') or ''), 'actions': actions}
- actions.append('Enabled Redis object cache drop-in')
- return {'success': True, 'message': 'Redis object cache enabled', 'actions': actions, 'status': cls.object_cache_status(path)}
-
- @classmethod
- def disable_object_cache(cls, path: str) -> Dict:
- """Turn the Redis object-cache drop-in off (keeps the container + plugin)."""
- res = cls.wp_cli(path, ['redis', 'disable'])
- if res.get('success'):
- return {'success': True, 'message': 'Redis object cache disabled'}
- return {'success': False, 'error': res.get('error') or 'Failed to disable object cache'}
-
- @classmethod
- def object_cache_status(cls, path: str) -> Dict:
- """Report object-cache state via `wp redis status`. Never raises."""
- compose_file = os.path.join(path, 'docker-compose.yml')
- if not os.path.exists(compose_file):
- return {'enabled': False, 'available': False, 'reason': 'not a Docker-stack site'}
- res = cls.wp_cli(path, ['redis', 'status'])
- if not res.get('success'):
- return {'enabled': False, 'available': False}
- out = (res.get('output') or '').lower()
- return {'enabled': 'connected' in out, 'available': True, 'raw': res.get('output', '').strip()}
-
- @classmethod
- def flush_cache(cls, path: str) -> Dict:
- """Flush WordPress cache."""
- results = []
-
- # Flush rewrite rules
- cls.wp_cli(path, ['rewrite', 'flush'])
- results.append('Flushed rewrite rules')
-
- # Flush transients
- cls.wp_cli(path, ['transient', 'delete', '--all'])
- results.append('Deleted transients')
-
- # Flush object cache if available
- cache_result = cls.wp_cli(path, ['cache', 'flush'])
- if cache_result['success']:
- results.append('Flushed object cache')
-
- # Flush the Redis object-cache drop-in if the plugin is active (Roadmap #23)
- redis_flush = cls.wp_cli(path, ['redis', 'flush'])
- if redis_flush.get('success'):
- results.append('Flushed Redis object cache')
-
- # Purge the full-page cache plugin if present (Roadmap #22)
- if cls.purge_page_cache(path):
- results.append('Purged page cache')
-
- return {'success': True, 'message': 'Cache flushed', 'actions': results}
-
- @classmethod
- def create_user(cls, path: str, username: str, email: str, role: str = 'subscriber', password: str = None) -> Dict:
- """Create a new WordPress user."""
- if not password:
- password = cls._generate_password()
-
- result = cls.wp_cli(path, [
- 'user', 'create', username, email,
- f'--role={role}',
- f'--user_pass={password}'
- ])
-
- if result['success']:
- return {
- 'success': True,
- 'message': f'User {username} created',
- 'password': password
- }
- return result
-
- @classmethod
- def reset_password(cls, path: str, user: str, password: str = None) -> Dict:
- """Reset a user's password."""
- if not password:
- password = cls._generate_password()
-
- result = cls.wp_cli(path, ['user', 'update', user, f'--user_pass={password}'])
-
- if result['success']:
- return {'success': True, 'message': 'Password reset', 'password': password}
- return result
-
- @classmethod
- def _get_login_url_slug(cls, path: str) -> str:
- """Return the site's real login URL (avoids hardcoding /wp-admin)."""
- res = cls.wp_cli(path, ['eval', 'echo wp_login_url();'])
- if res.get('success') and res.get('output', '').strip():
- return res['output'].strip()
- return ''
-
- @classmethod
- def _ensure_login_package(cls, path: str) -> Dict:
- """Make the wp-cli-login command + its launcher available, idempotently."""
- have = cls.wp_cli(path, ['login', '--help'])
- if not have.get('success'):
- inst = cls.wp_cli(path, ['package', 'install', 'aaemnnosttv/wp-cli-login-command'])
- if not inst.get('success'):
- return {'success': False, 'error': 'Failed to install wp-cli-login package: ' + (inst.get('error') or '')}
- # Ensure the companion launcher plugin is present AND active (idempotent).
- # Without --activate the plugin installs but stays inactive, and the
- # subsequent `wp login create` fails with "requires the companion plugin
- # to be installed and active".
- cls.wp_cli(path, ['login', 'install', '--activate', '--yes'])
- return {'success': True}
-
- @classmethod
- def create_login_url(cls, path: str, user: str) -> Dict:
- """Mint a one-time passwordless wp-admin login URL for ``user``."""
- pkg = cls._ensure_login_package(path)
- if not pkg.get('success'):
- return pkg
- res = cls.wp_cli(path, ['login', 'create', user, '--url-only'])
- if res.get('success'):
- url = (res.get('output') or '').strip()
- if not url:
- return {'success': False, 'error': 'Login URL was empty'}
- return {'success': True, 'url': url, 'login_slug': cls._get_login_url_slug(path)}
- return res
-
- @staticmethod
- def _generate_password(length: int = 16) -> str:
- """Generate a secure random password."""
- alphabet = string.ascii_letters + string.digits + '!@#$%^&*'
- return ''.join(secrets.choice(alphabet) for _ in range(length))
-
- @staticmethod
- def _read_env_value(root_path: str, key: str) -> Optional[str]:
- """Read a single KEY from a Docker stack's <root>/.env (None if absent)."""
- env_path = os.path.join(root_path, '.env')
- if not os.path.exists(env_path):
- return None
- try:
- with open(env_path, 'r') as f:
- for line in f:
- line = line.strip()
- if line.startswith(f'{key}='):
- return line.split('=', 1)[1]
- except Exception:
- pass
- return None
-
- @classmethod
- def _copy_wp_content_between_containers(cls, source_container: str, target_container: str) -> Dict:
- """Best-effort copy of /var/www/html/wp-content from source to target
- WordPress container using `docker cp` via a host tmp dir. Never raises.
- """
- import tempfile
- try:
- tmp = tempfile.mkdtemp(prefix='wpclone_')
- staged = os.path.join(tmp, 'wp-content')
- cp_out = subprocess.run(
- ['docker', 'cp', f'{source_container}:/var/www/html/wp-content', staged],
- capture_output=True, text=True, timeout=600,
- )
- if cp_out.returncode != 0:
- shutil.rmtree(tmp, ignore_errors=True)
- return {'success': False, 'error': cp_out.stderr}
- cp_in = subprocess.run(
- ['docker', 'cp', f'{staged}/.', f'{target_container}:/var/www/html/wp-content'],
- capture_output=True, text=True, timeout=600,
- )
- shutil.rmtree(tmp, ignore_errors=True)
- if cp_in.returncode != 0:
- return {'success': False, 'error': cp_in.stderr}
- return {'success': True}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @staticmethod
- def _safe_extract_zip(zip_path: str, dest_dir: str) -> Dict:
- """Extract a zip into dest_dir, rejecting any member whose path would
- escape it (zip-slip / absolute-path / `..` traversal). Returns {success}.
- """
- import zipfile
- try:
- dest_abs = os.path.abspath(dest_dir)
- with zipfile.ZipFile(zip_path) as zf:
- for member in zf.namelist():
- target = os.path.abspath(os.path.join(dest_abs, member))
- if target != dest_abs and not target.startswith(dest_abs + os.sep):
- return {'success': False, 'error': f'Unsafe path in archive: {member}'}
- zf.extractall(dest_abs)
- return {'success': True}
- except zipfile.BadZipFile:
- return {'success': False, 'error': 'Not a valid zip archive'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @staticmethod
- def _resolve_wp_content_dir(extracted_dir: str) -> Optional[str]:
- """Locate the wp-content directory inside an extracted archive — handles a
- zip OF wp-content, a full-site zip, or a single wrapper folder. Returns the
- path to use as wp-content, or None if none is recognizable."""
- markers = {'plugins', 'themes', 'uploads', 'mu-plugins'}
- candidates = [extracted_dir]
- try:
- for entry in os.listdir(extracted_dir):
- p = os.path.join(extracted_dir, entry)
- if os.path.isdir(p):
- candidates.append(p)
- except OSError:
- pass
- # 1) An explicit wp-content dir at the root or one level down.
- for base in candidates:
- wpc = os.path.join(base, 'wp-content')
- if os.path.isdir(wpc):
- return wpc
- # 2) The root (or a wrapper dir) IS wp-content (has plugins/themes/uploads).
- for base in candidates:
- try:
- if set(os.listdir(base)) & markers:
- return base
- except OSError:
- continue
- return None
-
- @classmethod
- def _import_wp_content_zip(cls, zip_path: str, target_container: str) -> Dict:
- """Extract an uploaded wp-content/full-site zip (zip-slip-guarded) and copy
- its wp-content into the target WordPress container via `docker cp`, then
- hand the files to the web user. Never raises."""
- import tempfile
- tmp = tempfile.mkdtemp(prefix='wpimport_')
- try:
- ext = cls._safe_extract_zip(zip_path, tmp)
- if not ext.get('success'):
- return ext
- wpc = cls._resolve_wp_content_dir(tmp)
- if not wpc:
- return {'success': False, 'error': 'No wp-content found in the archive'}
- cp = subprocess.run(
- ['docker', 'cp', f'{wpc}/.', f'{target_container}:/var/www/html/wp-content'],
- capture_output=True, text=True, timeout=600,
- )
- if cp.returncode != 0:
- return {'success': False, 'error': cp.stderr or 'docker cp failed'}
- # Imported files land root-owned; hand wp-content to the web user.
- subprocess.run(
- ['docker', 'exec', target_container, 'chown', '-R', 'www-data:www-data',
- '/var/www/html/wp-content'],
- capture_output=True, text=True, timeout=300,
- )
- return {'success': True}
- except Exception as e:
- return {'success': False, 'error': str(e)}
- finally:
- shutil.rmtree(tmp, ignore_errors=True)
-
- # ========================================
- # WORDPRESS STANDALONE (DOCKER) MANAGEMENT
- # ========================================
-
- WP_APP_NAME = 'serverkit-wordpress'
- WP_CONFIG_DIR = paths.SERVERKIT_CONFIG_DIR
- WP_CONFIG_FILE = os.path.join(WP_CONFIG_DIR, 'wordpress.json')
-
- @classmethod
- def get_wordpress_standalone_status(cls) -> Dict:
- """Check if standalone WordPress is installed and running."""
- from app.models import Application
-
- app = Application.query.filter_by(name=cls.WP_APP_NAME).first()
-
- if not app:
- return {
- 'installed': False,
- 'running': False,
- 'http_port': None,
- 'url': None,
- 'url_path': None
- }
-
- running = cls._is_wordpress_running()
- config = cls._load_wp_config()
-
- # Prefer the panel's canonical origin so the link works through a domain
- # and Cloudflare; fall back to the local port only when no domain is set.
- from app.services.site_domain_service import SiteDomainService
- panel_origin = SiteDomainService.panel_origin()
- if panel_origin:
- public_url = f"{panel_origin}/wordpress"
- elif app.port:
- public_url = f"http://localhost:{app.port}"
- else:
- public_url = None
-
- return {
- 'installed': True,
- 'running': running,
- 'http_port': app.port or config.get('http_port'),
- 'url_path': '/wordpress',
- 'url': public_url,
- 'app_id': app.id,
- 'version': config.get('version', '6.4')
- }
-
- @classmethod
- def _is_wordpress_running(cls) -> bool:
- """Check if WordPress container is running."""
- try:
- result = subprocess.run(
- ['docker', 'ps', '--filter', f'name={cls.WP_APP_NAME}', '--format', '{{.Names}}'],
- capture_output=True,
- text=True,
- timeout=10
- )
- return cls.WP_APP_NAME in result.stdout
- except Exception:
- return False
-
- @classmethod
- def _load_wp_config(cls) -> Dict:
- """Load WordPress standalone configuration."""
- if os.path.exists(cls.WP_CONFIG_FILE):
- try:
- with open(cls.WP_CONFIG_FILE, 'r') as f:
- return json.load(f)
- except Exception:
- pass
- return {}
-
- @classmethod
- def _save_wp_config(cls, config: Dict) -> bool:
- """Save WordPress standalone configuration."""
- try:
- os.makedirs(cls.WP_CONFIG_DIR, exist_ok=True)
- with open(cls.WP_CONFIG_FILE, 'w') as f:
- json.dump(config, f, indent=2)
- return True
- except Exception:
- return False
-
- @classmethod
- def get_wordpress_resource_requirements(cls) -> Dict:
- """Get resource requirements for WordPress installation."""
- return {
- 'memory_min': '512MB',
- 'memory_recommended': '1GB',
- 'storage_min': '2GB',
- 'storage_recommended': '10GB',
- 'components': [
- {'name': 'WordPress', 'memory': '~256MB', 'storage': '~500MB'},
- {'name': 'MySQL 8.0', 'memory': '~256MB', 'storage': '~1GB'}
- ],
- 'warning': 'Installation will spin up a MySQL database container'
- }
-
- @classmethod
- def install_wordpress_standalone(cls, admin_email: str = None) -> Dict:
- """Install WordPress as integrated ServerKit service via Docker."""
- from app.services.template_service import TemplateService
- from app.services.nginx_service import NginxService
-
- status = cls.get_wordpress_standalone_status()
- if status['installed']:
- return {'success': False, 'error': 'WordPress is already installed'}
-
- try:
- result = TemplateService.install_template(
- template_id='wordpress',
- app_name=cls.WP_APP_NAME,
- user_variables={},
- user_id=1
- )
-
- if not result.get('success'):
- return result
-
- variables = result.get('variables', {})
- http_port = variables.get('HTTP_PORT')
-
- # Create nginx config for /wordpress path
- nginx_result = NginxService.create_wordpress_config(int(http_port))
- if not nginx_result.get('success'):
- print(f"Warning: Failed to create WordPress nginx config: {nginx_result.get('error')}")
-
- config = {
- 'admin_email': admin_email,
- 'http_port': http_port,
- 'db_password': variables.get('DB_PASSWORD'),
- 'wp_db_password': variables.get('WP_DB_PASSWORD'),
- 'installed_at': datetime.now().isoformat(),
- 'version': '6.4',
- 'url_path': '/wordpress'
- }
- cls._save_wp_config(config)
-
- return {
- 'success': True,
- 'message': 'WordPress installed successfully',
- 'http_port': http_port,
- 'url_path': '/wordpress'
- }
-
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def uninstall_wordpress_standalone(cls, remove_data: bool = False) -> Dict:
- """Uninstall standalone WordPress."""
- from app import db
- from app.models import Application
- from app.services.docker_service import DockerService
- from app.services.nginx_service import NginxService
-
- app = Application.query.filter_by(name=cls.WP_APP_NAME).first()
- if not app:
- return {'success': False, 'error': 'WordPress is not installed'}
-
- try:
- NginxService.remove_wordpress_config()
-
- if app.root_path and os.path.exists(app.root_path):
- DockerService.compose_down(app.root_path, remove_volumes=remove_data)
-
- if remove_data:
- shutil.rmtree(app.root_path, ignore_errors=True)
-
- db.session.delete(app)
- db.session.commit()
-
- if os.path.exists(cls.WP_CONFIG_FILE):
- os.remove(cls.WP_CONFIG_FILE)
-
- return {
- 'success': True,
- 'message': 'WordPress uninstalled successfully',
- 'data_removed': remove_data
- }
-
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def start_wordpress_standalone(cls) -> Dict:
- """Start WordPress containers."""
- from app import db
- from app.models import Application
- from app.services.docker_service import DockerService
-
- app = Application.query.filter_by(name=cls.WP_APP_NAME).first()
- if not app:
- return {'success': False, 'error': 'WordPress is not installed'}
-
- if not app.root_path or not os.path.exists(app.root_path):
- return {'success': False, 'error': 'WordPress installation path not found'}
-
- try:
- result = DockerService.compose_up(app.root_path, detach=True)
- if result.get('success'):
- app.status = 'running'
- db.session.commit()
- return {'success': True, 'message': 'WordPress started'}
- return result
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def stop_wordpress_standalone(cls) -> Dict:
- """Stop WordPress containers."""
- from app import db
- from app.models import Application
- from app.services.docker_service import DockerService
-
- app = Application.query.filter_by(name=cls.WP_APP_NAME).first()
- if not app:
- return {'success': False, 'error': 'WordPress is not installed'}
-
- if not app.root_path or not os.path.exists(app.root_path):
- return {'success': False, 'error': 'WordPress installation path not found'}
-
- try:
- result = DockerService.compose_stop(app.root_path)
- if result.get('success'):
- app.status = 'stopped'
- db.session.commit()
- return {'success': True, 'message': 'WordPress stopped'}
- return result
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def restart_wordpress_standalone(cls) -> Dict:
- """Restart WordPress containers."""
- stop_result = cls.stop_wordpress_standalone()
- if not stop_result.get('success'):
- return stop_result
- return cls.start_wordpress_standalone()
-
- # ========================================
- # WORDPRESS SITES HUB (MULTI-SITE MANAGEMENT)
- # ========================================
-
- @classmethod
- def _enrich_site_data(cls, site, site_data: Dict) -> Dict:
- """Add runtime info (status, name, port, url) to site data dict."""
- if site.application:
- site_data['name'] = site.application.name
- site_data['port'] = site.application.port
- running = cls._check_container_running(site.application.name)
- if running and site.application.status != 'running':
- site.application.status = 'running'
- elif not running and site.application.status == 'running':
- site.application.status = 'stopped'
- site_data['status'] = site.application.status
-
- # Build access URL: prefer the primary domain, fall back to localhost:port
- domains = site.application.domains
- primary = next((d for d in domains if d.is_primary), None)
- if primary is None and domains:
- primary = domains[0]
- if primary is not None:
- scheme = 'https' if primary.ssl_enabled else 'http'
- site_data['url'] = f"{scheme}://{primary.name}"
- elif site.application.port:
- site_data['url'] = f"http://localhost:{site.application.port}"
- return site_data
-
- @classmethod
- def get_sites(cls, workspace_id=None) -> Dict:
- """Get all production WordPress sites with environment counts.
-
- Workspace scoping (#33): when workspace_id is given, only sites whose
- Application belongs to that workspace are returned (join-based, since WP
- sites carry no workspace_id of their own — they inherit their app's). The
- hub is global today, so with no workspace context this is unchanged.
- """
- from app.models import WordPressSite, Application
-
- query = WordPressSite.query.filter_by(is_production=True)
- if workspace_id is not None:
- query = query.join(Application, WordPressSite.application_id == Application.id) \
- .filter(Application.workspace_id == workspace_id)
- sites = query.all()
- result = []
-
- for site in sites:
- site_data = site.to_dict()
- env_count = WordPressSite.query.filter_by(production_site_id=site.id).count()
- site_data['environment_count'] = env_count
- cls._enrich_site_data(site, site_data)
- result.append(site_data)
-
- return {'sites': result}
-
- @classmethod
- def get_site(cls, site_id: int) -> Dict:
- """Get a single WordPress site with its environments."""
- from app.models import WordPressSite
-
- site = WordPressSite.query.get(site_id)
- if not site:
- return {'error': 'Site not found'}
-
- site_data = site.to_dict(include_environments=True)
- cls._enrich_site_data(site, site_data)
-
- # Refresh the multisite flag from reality (single-site detail only;
- # never added to the hot list endpoint get_sites). One cheap wp_cli probe.
- if site.application and site.application.root_path:
- detected = cls.is_multisite(site.application.root_path)
- if detected != site.multisite:
- site.multisite = detected
- from app import db
- db.session.commit()
- site_data['multisite'] = detected
-
- # Also enrich environment data
- if 'environments' in site_data:
- for env_data in site_data['environments']:
- env = WordPressSite.query.get(env_data.get('id'))
- if env:
- cls._enrich_site_data(env, env_data)
-
- return {'site': site_data}
-
- @classmethod
- def import_site(cls, name: str, admin_email: str, user_id: int, sql_path: str,
- old_url: str, wp_content_zip_path: str = None) -> Dict:
- """Import an existing WordPress site from a SQL dump into a fresh Docker stack.
-
- Stands up a normal blank stack via create_site (reusing the full Docker
- provisioning + Application/WordPressSite rows), then OVERWRITES its DB
- with the uploaded dump and rewrites the site URL to the new localhost
- port. ``sql_path`` is a host-side temp file owned by the caller.
- """
- from app import db
- from app.models import WordPressSite
- from app.services.db_sync_service import DatabaseSyncService
-
- # 1) Stand up a fresh stack (reuses all Docker provisioning + rows).
- result = cls.create_site(name, admin_email, user_id)
- if not result.get('success'):
- return result
- http_port = result.get('http_port')
- wp_site = WordPressSite.query.get(result['site']['id'])
- root_path = wp_site.application.root_path
- compose_file = os.path.join(root_path, 'docker-compose.yml')
-
- try:
- # 2) Overwrite the fresh DB with the user's dump. Root user, since a
- # real dump issues DROP/CREATE on the wordpress DB.
- db_password = cls._read_env_value(root_path, 'DB_PASSWORD')
- imp = DatabaseSyncService.import_to_container(
- compose_path=compose_file,
- snapshot_path=sql_path,
- db_name='wordpress',
- db_user='root',
- db_password=db_password,
- )
- if not imp.get('success'):
- return {'success': False,
- 'error': 'Database import failed: ' + (imp.get('error') or ''),
- 'site': wp_site.to_dict(), 'http_port': http_port}
-
- # 3) Rewrite the site URL to this server's localhost address.
- new_url = f'http://localhost:{http_port}' if http_port else 'http://localhost'
- cls.wp_cli(root_path, ['option', 'update', 'home', new_url])
- cls.wp_cli(root_path, ['option', 'update', 'siteurl', new_url])
- sr = cls.search_replace(root_path, old_url, new_url, dry_run=False)
-
- warnings = []
- if not sr.get('success'):
- warnings.append('Search-replace reported an issue; verify links inside wp-admin.')
-
- # 3.5) Optionally import wp-content (plugins/themes/uploads) from a zip.
- wp_content_imported = False
- if wp_content_zip_path:
- wpc = cls._import_wp_content_zip(wp_content_zip_path, wp_site.application.name)
- if wpc.get('success'):
- wp_content_imported = True
- else:
- warnings.append('Database imported, but wp-content import failed: '
- + (wpc.get('error') or 'unknown error'))
-
- cls.wp_cli(root_path, ['cache', 'flush'])
- cls.wp_cli(root_path, ['rewrite', 'flush'])
-
- # 4) The imported DB carries the source's users, so the create-time
- # admin no longer matches; clear it and re-detect multisite.
- wp_site.admin_user = None
- wp_site.multisite = cls.is_multisite(root_path)
- db.session.commit()
-
- out = {
- 'success': True,
- 'message': 'WordPress site imported successfully',
- 'site': wp_site.to_dict(),
- 'http_port': http_port,
- 'old_url': old_url,
- 'new_url': new_url,
- 'wp_content_imported': wp_content_imported,
- }
- if warnings:
- out['warning'] = '; '.join(warnings)
- return out
- except Exception as e:
- return {'success': False, 'error': str(e),
- 'site': wp_site.to_dict(), 'http_port': http_port}
-
- # WordPress core line baked into every managed stack's image tag. Kept in sync
- # with the template default (backend/templates/wordpress.yaml) and wp_version below.
- WP_CORE = '6.4'
-
- @classmethod
- def create_site(cls, name: str, admin_email: str, user_id: int, admin_user: str = 'admin',
- php_version: str = None, enable_page_cache: bool = False,
- enable_object_cache: bool = False, domain: str = None,
- base_domain: str = None) -> Dict:
- """Create a new WordPress site via Docker.
-
- One-click orchestration: provision the Docker stack on a chosen PHP version,
- finalize + harden the install, then optionally enable the full-page and/or
- Redis object cache — all in a single call. Cache enablement is best-effort
- and never fails the create. The generated admin password is returned ONCE.
- """
- from app import db
- from app.models import Application, WordPressSite
- from app.services.template_service import TemplateService
- from app.services.site_domain_service import SiteDomainService
-
- # Sanitize name for Docker
- safe_name = name.lower().replace(' ', '-')
- safe_name = ''.join(c for c in safe_name if c.isalnum() or c == '-')
-
- # Check for duplicate name
- existing = Application.query.filter_by(name=safe_name).first()
- if existing:
- return {'success': False, 'error': f'A site with name "{safe_name}" already exists'}
-
- # Bake the chosen PHP version into the initial image tag so the site is
- # created on the right PHP from the start (no post-create container recreate).
- # Invalid/empty values fall through to the template default (WP_CORE-apache).
- user_variables = {}
- if php_version and php_version in cls.get_available_php_versions():
- user_variables['VERSION'] = f'{cls.WP_CORE}-php{php_version}-apache'
-
- try:
- result = TemplateService.install_template(
- template_id='wordpress',
- app_name=safe_name,
- user_variables=user_variables,
- user_id=user_id
- )
-
- if not result.get('success'):
- return result
-
- variables = result.get('variables', {})
- http_port = variables.get('HTTP_PORT')
-
- # Find the Application record created by TemplateService
- app = Application.query.filter_by(name=safe_name).first()
- if not app:
- return {'success': False, 'error': 'Application record not created'}
-
- # Finalize the WordPress install inside the container: the official
- # wordpress image only generates wp-config from env vars; it does NOT
- # run the install, so no admin user exists. Do it via the Docker-aware
- # wp_cli bridge (host-filesystem hardening does not apply to volumes).
- admin_password = cls._generate_password()
- # Publish at a real hostname (<slug>.<base_domain>) instead of
- # localhost:<port>. WordPress bakes whatever --url we pass in as its
- # canonical home/siteurl, so this is what makes the site usable as an
- # actual website. Falls back to localhost when no base domain is set
- # (e.g. an unconfigured production install).
- site_host = SiteDomainService.subdomain_for(safe_name, base=base_domain)
- if site_host:
- base_used = SiteDomainService.covering_base(site_host)
- site_url = SiteDomainService.site_url(
- site_host, ssl=SiteDomainService.https_enabled(base_used))
- else:
- site_url = f'http://localhost:{http_port}' if http_port else 'http://localhost'
- wp_warning = None
- harden_actions = []
- cache_actions = []
- cache_warnings = []
- page_cache_on = False
- if cls._wait_for_wp_ready(app.root_path):
- install_res = cls.wp_cli(app.root_path, [
- 'core', 'install',
- f'--url={site_url}',
- f'--title={name}',
- f'--admin_user={admin_user}',
- f'--admin_password={admin_password}',
- f'--admin_email={admin_email}',
- '--skip-email',
- ])
- if install_res.get('success'):
- harden_actions = cls._harden_docker_site(app.root_path)
- # Optional caches (best-effort; never fail the create). These are
- # wp_cli calls inside the now-running container, so they must run
- # AFTER the core install has finalized.
- if enable_object_cache:
- oc = cls.enable_object_cache(app.root_path)
- # Record whatever work succeeded — the helper returns its partial
- # 'actions' even on failure (e.g. redis added + plugin installed
- # but the drop-in enable failed) — then note any failure non-fatally.
- cache_actions.extend(oc.get('actions') or [])
- if not oc.get('success'):
- cache_warnings.append('object cache: ' + (oc.get('error') or 'unknown error'))
- if enable_page_cache:
- pc = cls.enable_page_cache(app.root_path)
- if pc.get('success'):
- cache_actions.append('Enabled full-page cache')
- page_cache_on = True
- else:
- cache_warnings.append('page cache: ' + (pc.get('error') or 'unknown error'))
- else:
- admin_password = None
- wp_warning = (
- 'WordPress container did not accept the automated install; '
- 'complete setup via the WordPress wizard. '
- + (install_res.get('error') or '')
- ).strip()
- else:
- admin_password = None
- wp_warning = (
- 'WordPress container was not ready in time; the install was not '
- 'finalized. Complete setup via the WordPress wizard.'
- )
-
- # Detect multisite from the freshly installed site (cheap one-shot;
- # only meaningful if the automated install finalized).
- multisite = cls.is_multisite(app.root_path) if admin_password else False
-
- # Publish the site at its hostname: a Domain row + nginx reverse-proxy
- # vhost so <slug>.<base_domain> reaches the container. Best-effort — a
- # box without nginx (local dev) degrades to a warning, never failing
- # the create.
- routing = cls._provision_routing(app, site_host)
- if routing.get('warning'):
- wp_warning = (wp_warning + ' ' + routing['warning']) if wp_warning else routing['warning']
-
- # Surface any best-effort cache failures without failing the create.
- if cache_warnings:
- note = 'Site created, but some caches could not be enabled — ' + '; '.join(cache_warnings) + '.'
- wp_warning = (wp_warning + ' ' + note) if wp_warning else note
-
- # Create WordPressSite record. Persist the page-cache flag in sync_config
- # to mirror the per-site page-cache route (object cache + PHP are read live).
- wp_site = WordPressSite(
- application_id=app.id,
- admin_user=admin_user if admin_password else None,
- admin_email=admin_email,
- is_production=True,
- environment_type='production',
- wp_version=cls.WP_CORE,
- compose_project_name=safe_name,
- multisite=multisite,
- sync_config=json.dumps({'page_cache_enabled': True}) if page_cache_on else None,
- )
- db.session.add(wp_site)
- db.session.commit()
-
- try:
- from app.services.event_service import EventService
- EventService.emit_wp('wordpress.created', wp_site, php_version=php_version)
- except Exception:
- pass
-
- # If the caller supplied a custom domain, attach it and migrate the
- # WordPress site URL away from localhost:<port> / base subdomain.
- if domain:
- attach_res = cls.attach_custom_domain(
- app, domain, migrate=True, issue_ssl=False
- )
- if attach_res.get('success'):
- site_url = attach_res.get('url') or site_url
- site_host = attach_res.get('domain') or site_host
- if attach_res.get('warning'):
- wp_warning = (wp_warning + ' ' + attach_res['warning']) if wp_warning else attach_res['warning']
- else:
- attach_err = attach_res.get('error') or 'Custom domain could not be attached'
- wp_warning = (wp_warning + ' ' + attach_err) if wp_warning else attach_err
-
- # Nudge admins (in-app) if the site landed on localhost or the
- # base-domain/HTTPS/DNS config is only partly set up. Best-effort —
- # never let a notification failure affect the create result.
- try:
- SiteDomainService.notify_publishing_gaps()
- except Exception:
- pass
-
- result = {
- 'success': True,
- 'message': 'WordPress site created successfully',
- 'site': wp_site.to_dict(),
- 'http_port': http_port,
- 'url': site_url,
- 'domain': site_host,
- 'admin_user': admin_user if admin_password else None,
- 'admin_password': admin_password,
- 'hardening': harden_actions,
- 'cache': cache_actions,
- }
- if wp_warning:
- result['warning'] = wp_warning
- return result
-
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def _provision_routing(cls, app, site_host) -> Dict:
- """Publish a managed site at ``site_host`` via a primary Domain row + an
- nginx reverse-proxy vhost to the container's published port.
-
- Best-effort and never raises: a box without nginx (e.g. local Windows
- dev) records the Domain and returns a warning rather than failing site
- creation. Returns ``{'domain', 'nginx', 'warning'}``.
- """
- from app import db
- from app.models.domain import Domain
- from app.services.site_domain_service import SiteDomainService
-
- if not site_host:
- return {'domain': None, 'nginx': None, 'warning': None}
-
- warning = None
- try:
- if not Domain.query.filter_by(name=site_host).first():
- Domain.query.filter_by(application_id=app.id, is_primary=True).update({'is_primary': False})
- db.session.add(Domain(name=site_host, is_primary=True, application_id=app.id))
- db.session.commit()
- except Exception as e:
- db.session.rollback()
- warning = f'could not record domain {site_host}: {e}'
-
- # Per-site DNS mode: auto-create this site's A record via a connected
- # provider (wildcard mode relies on the single *.<base> record instead).
- dns = SiteDomainService.ensure_site_dns(site_host)
- if dns and not dns.get('skipped') and not dns.get('created') and dns.get('message'):
- warning = (warning + '; ' + dns['message']) if warning else dns['message']
-
- v = cls._write_app_vhost(app)
- if v.get('warning'):
- warning = (warning + '; ' + v['warning']) if warning else v['warning']
-
- # Brute-force protection is on by default: now that the per-site vhost (and
- # therefore its access log) exists, stand up the WP-login Fail2ban jail.
- # Best-effort and never fatal — a host without fail2ban (e.g. Windows dev)
- # is silently skipped; only a real failure (e.g. reload error) warns.
- try:
- from app.services.fail2ban_jail_service import Fail2banJailService
- jail = Fail2banJailService.enable_wp_jail(app)
- except Exception as e:
- jail = {'success': False, 'error': str(e)}
- if jail and not jail.get('success') and not jail.get('skipped') and jail.get('error'):
- msg = f"brute-force jail: {jail['error']}"
- warning = (warning + '; ' + msg) if warning else msg
-
- return {'domain': site_host, 'nginx': v.get('nginx'), 'warning': warning}
-
- @classmethod
- def _write_app_vhost(cls, app) -> Dict:
- """Write + enable the nginx reverse-proxy vhost for a WordPress site from
- its current Domain rows (server_name = every domain). Best-effort and
- never raises; returns ``{'nginx', 'warning'}``.
-
- Delegates to the shared ``SiteDomainService.write_app_vhost`` writer,
- forcing the docker proxy template: a managed WP site is always served by
- proxying to its container, never via the stock php-fpm ``wordpress``
- template. A portless site is a silent no-op (nothing to proxy to)."""
- from app.services.site_domain_service import SiteDomainService
-
- if not app.port:
- return {'nginx': None, 'warning': None}
- return SiteDomainService.write_app_vhost(app, force_type='docker')
-
- @classmethod
- def _canonical_site_url(cls, app) -> str:
- """The URL WordPress actually serves under — its primary domain if one
- exists, else the legacy localhost:<port> address it was installed with.
- Used to build correct search-replace pairs when cloning or swapping URLs,
- so it must reflect what's baked into the DB, not the panel's origin."""
- from app.models.domain import Domain
- d = (Domain.query.filter_by(application_id=app.id, is_primary=True).first()
- or Domain.query.filter_by(application_id=app.id).first())
- if d:
- scheme = 'https' if d.ssl_enabled else 'http'
- return f'{scheme}://{d.name}'
- if app.port:
- return f'http://localhost:{app.port}'
- return None
-
- @classmethod
- def clone_site(cls, source_site_id: int, new_name: str, user_id: int) -> Dict:
- """Clone an existing Docker WordPress site into a NEW independent top-level
- site (is_production=True, no production_site_id) with FRESH admin creds.
-
- (1) stand up a brand-new stack via create_site; (2) container-to-container
- clone the source DB into it with a URL search-replace to the new localhost
- URL; (3) best-effort copy wp-content between containers; (4) create a fresh
- admin user (new generated password) so the clone does NOT share the
- source's credentials. Returns the new admin_password ONCE.
- """
- from app import db
- from app.models import WordPressSite
- from app.services.db_sync_service import DatabaseSyncService
-
- source = WordPressSite.query.get(source_site_id)
- if not source:
- return {'success': False, 'error': 'Source site not found'}
- if not source.application or not source.application.root_path:
- return {'success': False, 'error': 'Source site has no application/root path'}
- source_root = source.application.root_path
- source_compose = os.path.join(source_root, 'docker-compose.yml')
- if not os.path.exists(source_compose):
- return {'success': False, 'error': 'Source is not a Docker-stack site (no docker-compose.yml)'}
-
- # 1) Stand up a NEW independent stack (fresh install + an admin we will replace).
- admin_email = source.admin_email or ''
- create_res = cls.create_site(new_name, admin_email, user_id)
- if not create_res.get('success'):
- return create_res
- new_site = WordPressSite.query.get(create_res['site']['id'])
- new_root = new_site.application.root_path
- new_compose = os.path.join(new_root, 'docker-compose.yml')
- http_port = create_res.get('http_port')
- new_url = create_res.get('url') or (f'http://localhost:{http_port}' if http_port else 'http://localhost')
-
- try:
- source_url = cls._canonical_site_url(source.application)
-
- # 2) Clone the source DB into the new stack (root user for a clean overwrite;
- # both stacks use db name 'wordpress'; root pw lives in each .env DB_PASSWORD).
- src_pw = cls._read_env_value(source_root, 'DB_PASSWORD')
- new_pw = cls._read_env_value(new_root, 'DB_PASSWORD')
- clone_options = {
- 'truncate_tables': ['actionscheduler_actions', 'actionscheduler_logs'],
- }
- if source_url and new_url and source_url != new_url:
- # Rewrite the source's URL to the clone's, both with and without
- # scheme so host-only and serialized references are covered.
- sr = {source_url: new_url}
- src_host = source_url.split('://', 1)[-1]
- new_host = new_url.split('://', 1)[-1]
- if src_host != new_host:
- sr[src_host] = new_host
- clone_options['search_replace'] = sr
- clone_res = DatabaseSyncService.clone_between_containers(
- source_compose_path=source_compose,
- target_compose_path=new_compose,
- source_db='wordpress', target_db='wordpress',
- source_user='root', target_user='root',
- source_password=src_pw, target_password=new_pw,
- options=clone_options,
- )
- if not clone_res.get('success'):
- return {'success': False, 'error': f"Database clone failed: {clone_res.get('error')}"}
-
- # 3) Best-effort copy wp-content from source container to the new one.
- cls._copy_wp_content_between_containers(source.application.name, new_site.application.name)
-
- # 4) Fresh admin: the DB import replaced users with the SOURCE users, so
- # create a brand-new administrator with a generated password.
- new_admin_user = 'admin'
- new_admin_pass = cls._generate_password()
- exists = cls.wp_cli(new_root, ['user', 'get', new_admin_user, '--field=ID'])
- if exists.get('success'):
- new_admin_user = f'admin_{new_site.id}'
- cu = cls.create_user(new_root, new_admin_user, admin_email or f'{new_admin_user}@example.com',
- role='administrator', password=new_admin_pass)
- if not cu.get('success'):
- return {'success': False, 'error': f"Failed to create fresh admin: {cu.get('error')}"}
-
- new_site.admin_user = new_admin_user
- if admin_email:
- new_site.admin_email = admin_email
- db.session.commit()
-
- return {
- 'success': True,
- 'message': f'Site cloned from "{source.application.name}" successfully',
- 'site': new_site.to_dict(),
- 'http_port': http_port,
- 'admin_user': new_admin_user,
- 'admin_password': new_admin_pass,
- }
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def delete_site(cls, site_id: int, create_backup: bool = True) -> Dict:
- """Delete a WordPress site and all its environments.
-
- By default a final files + database backup of the production site is
- captured to ``BACKUP_DIR`` before anything is torn down, so a deleted
- site stays restorable. The backup lives outside the site root, so it
- survives the filesystem teardown. Pass ``create_backup=False`` to skip.
- """
- from app import db
- from app.models import WordPressSite
-
- site = WordPressSite.query.get(site_id)
- if not site:
- return {'success': False, 'error': 'Site not found'}
-
- if not site.is_production:
- return {'success': False, 'error': 'Can only delete production sites from this endpoint. Use delete_environment for non-production.'}
-
- # Capture a final backup BEFORE any destructive action, while the
- # containers are still up (wp db export runs inside the running stack).
- backup_info = None
- if create_backup and site.application and site.application.root_path:
- backup_result = cls.backup_wordpress(site.application.root_path, include_db=True)
- if backup_result.get('success'):
- backup_info = {
- 'backup_name': backup_result.get('backup_name'),
- 'backup_path': backup_result.get('backup_path'),
- 'size': backup_result.get('size'),
- }
-
- try:
- # Delete all child environments first
- environments = WordPressSite.query.filter_by(production_site_id=site.id).all()
- for env in environments:
- cls._teardown_wp_site(env)
-
- # Delete the production site
- cls._teardown_wp_site(site)
-
- db.session.commit()
- return {
- 'success': True,
- 'message': 'Site and all environments deleted',
- 'backup': backup_info,
- }
-
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def archive_site(cls, site_id: int) -> Dict:
- """Archive a site: stop its stack but keep all data (volumes + files).
-
- Unlike delete, archiving is fully reversible via ``unarchive_site`` —
- the Docker volumes (database) and files are preserved, and a final
- backup is captured for safety. Applies to the production site and all
- of its child environments.
- """
- from app import db
- from app.models import WordPressSite
- from app.services.docker_service import DockerService
-
- site = WordPressSite.query.get(site_id)
- if not site:
- return {'success': False, 'error': 'Site not found'}
-
- if not site.is_production:
- return {'success': False, 'error': 'Only production sites can be archived'}
-
- # Best-effort safety backup (archiving keeps the data either way).
- backup_info = None
- if site.application and site.application.root_path:
- backup_result = cls.backup_wordpress(site.application.root_path, include_db=True)
- if backup_result.get('success'):
- backup_info = backup_result.get('backup_name')
-
- try:
- targets = [site] + WordPressSite.query.filter_by(production_site_id=site.id).all()
- for wp in targets:
- if (wp.application and wp.application.root_path
- and os.path.exists(wp.application.root_path)):
- # Keep volumes so the database/files survive.
- DockerService.compose_down(wp.application.root_path, volumes=False)
- if wp.application:
- wp.application.status = 'archived'
-
- db.session.commit()
- return {'success': True, 'message': 'Site archived', 'backup': backup_info}
-
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def unarchive_site(cls, site_id: int) -> Dict:
- """Bring an archived site back online by starting its stack again."""
- from app import db
- from app.models import WordPressSite
- from app.services.docker_service import DockerService
-
- site = WordPressSite.query.get(site_id)
- if not site:
- return {'success': False, 'error': 'Site not found'}
-
- if not site.is_production:
- return {'success': False, 'error': 'Only production sites can be unarchived'}
-
- try:
- targets = [site] + WordPressSite.query.filter_by(production_site_id=site.id).all()
- for wp in targets:
- if (wp.application and wp.application.root_path
- and os.path.exists(wp.application.root_path)):
- DockerService.compose_up(wp.application.root_path)
- if wp.application:
- wp.application.status = 'running'
-
- db.session.commit()
- return {'success': True, 'message': 'Site restored from archive'}
-
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def get_environments(cls, site_id: int) -> Dict:
- """Get all environments for a production WordPress site."""
- from app.models import WordPressSite
-
- site = WordPressSite.query.get(site_id)
- if not site:
- return {'error': 'Site not found'}
-
- if not site.is_production:
- return {'error': 'Not a production site'}
-
- # Production env first
- prod_data = site.to_dict()
- cls._enrich_site_data(site, prod_data)
- environments = [prod_data]
-
- # Child environments
- children = WordPressSite.query.filter_by(production_site_id=site.id).all()
- for child in children:
- env_data = child.to_dict()
- cls._enrich_site_data(child, env_data)
- environments.append(env_data)
-
- return {'environments': environments}
-
- @classmethod
- def create_environment(cls, site_id: int, env_type: str, user_id: int = 1) -> Dict:
- """Create a staging or development environment for a site."""
- from app import db
- from app.models import WordPressSite, Application
- from app.services.template_service import TemplateService
-
- site = WordPressSite.query.get(site_id)
- if not site:
- return {'success': False, 'error': 'Site not found'}
-
- if not site.is_production:
- return {'success': False, 'error': 'Can only create environments from a production site'}
-
- if env_type not in ('staging', 'development'):
- return {'success': False, 'error': 'Environment type must be staging or development'}
-
- # Check if this environment type already exists
- existing = WordPressSite.query.filter_by(
- production_site_id=site.id,
- environment_type=env_type
- ).first()
- if existing:
- return {'success': False, 'error': f'{env_type.capitalize()} environment already exists'}
-
- # Build name from parent
- parent_name = site.application.name if site.application else f'wp-site-{site.id}'
- env_name = f'{parent_name}-{env_type[:3]}' # e.g., mysite-sta, mysite-dev
-
- try:
- result = TemplateService.install_template(
- template_id='wordpress',
- app_name=env_name,
- user_variables={},
- user_id=user_id
- )
-
- if not result.get('success'):
- return result
-
- variables = result.get('variables', {})
- http_port = variables.get('HTTP_PORT')
-
- app = Application.query.filter_by(name=env_name).first()
- if not app:
- return {'success': False, 'error': 'Application record not created'}
-
- wp_env = WordPressSite(
- application_id=app.id,
- admin_email=site.admin_email,
- is_production=False,
- production_site_id=site.id,
- environment_type=env_type,
- wp_version=site.wp_version or '6.4',
- compose_project_name=env_name
- )
- db.session.add(wp_env)
- db.session.commit()
-
- return {
- 'success': True,
- 'message': f'{env_type.capitalize()} environment created',
- 'environment': wp_env.to_dict(),
- 'http_port': http_port
- }
-
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def delete_environment(cls, env_id: int) -> Dict:
- """Delete a non-production environment."""
- from app import db
- from app.models import WordPressSite
-
- env = WordPressSite.query.get(env_id)
- if not env:
- return {'success': False, 'error': 'Environment not found'}
-
- if env.is_production:
- return {'success': False, 'error': 'Cannot delete production environment. Delete the site instead.'}
-
- try:
- cls._teardown_wp_site(env)
- db.session.commit()
- return {'success': True, 'message': 'Environment deleted'}
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def _teardown_wp_site(cls, wp_site, remove_volumes: bool = True) -> None:
- """Tear down Docker stack and delete records for a WordPressSite."""
- from app import db
- from app.services.docker_service import DockerService
- from app.services.nginx_service import NginxService
-
- if wp_site.application and wp_site.application.root_path:
- root_path = wp_site.application.root_path
- if os.path.exists(root_path):
- DockerService.compose_down(root_path, volumes=remove_volumes)
- shutil.rmtree(root_path, ignore_errors=True)
-
- if wp_site.application:
- # Remove the reverse-proxy vhost we provisioned so a deleted site
- # doesn't leave dangling nginx config. The Domain rows cascade-delete
- # with the Application (Application.domains is delete-orphan).
- try:
- NginxService.delete_site(wp_site.application.name)
- except Exception:
- pass
- # Remove the per-site brute-force jail too, so a deleted site leaves no
- # dangling Fail2ban config. Best-effort (no-op without fail2ban).
- try:
- from app.services.fail2ban_jail_service import Fail2banJailService
- Fail2banJailService.disable_jail(wp_site.application)
- except Exception:
- pass
- db.session.delete(wp_site.application)
-
- db.session.delete(wp_site)
-
- @classmethod
- def _check_container_running(cls, app_name: str) -> bool:
- """Check if a Docker container is running by app name."""
- try:
- import subprocess
- result = subprocess.run(
- ['docker', 'ps', '--filter', f'name={app_name}', '--format', '{{.Names}}'],
- capture_output=True,
- text=True,
- timeout=10
- )
- return app_name in result.stdout
- except Exception:
- return False
-
- # ── PR Preview Environments (best-effort) ─────────────────────────────────
- # Hooks driven by PreviewService when a PR opens/closes against a WordPress
- # site. Cloning a full WordPress stack needs Docker + a DB; both may be
- # absent in dev/test, so every step is guarded and a missing dependency
- # degrades to "recorded but not provisioned" rather than raising.
-
- @classmethod
- def _preview_db_name(cls, site, pr_number: int) -> str:
- """Temporary DB name for a PR preview: ``wp_preview_<pr>`` (scoped per
- site so two sites' PR #1 previews don't collide)."""
- base = (getattr(site, 'db_name', None) or 'wp').strip() or 'wp'
- return f'{base}_preview_{int(pr_number)}'
-
- @classmethod
- def create_preview_instance(cls, site, pr_number, domain=None, branch=None) -> Dict:
- """Spin up an isolated preview of a WordPress site for a PR.
-
- Best-effort: clone the site files into a preview directory, create a
- temporary database copy (``wp_preview_<pr>``), and rewrite the site URL
- to the preview ``domain``. Never raises — returns a result dict with
- ``success`` reflecting how much could actually be provisioned. In an
- environment without WP-CLI/Docker this is a no-op that still reports the
- intended preview so the row can flip to running.
- """
- result = {'success': True, 'pr_number': int(pr_number) if pr_number is not None else None,
- 'domain': domain, 'db_name': None, 'preview_path': None,
- 'container_ids': [], 'provisioned': False, 'warnings': []}
- try:
- app = getattr(site, 'application', None)
- src_path = getattr(app, 'root_path', None) if app else None
- preview_db = cls._preview_db_name(site, pr_number)
- result['db_name'] = preview_db
-
- # 1) Clone files into a sibling preview directory (best-effort).
- if src_path and os.path.isdir(src_path):
- preview_path = f'{src_path.rstrip("/")}-preview-pr-{int(pr_number)}'
- result['preview_path'] = preview_path
- try:
- if not os.path.exists(preview_path):
- shutil.copytree(src_path, preview_path, symlinks=True)
- result['provisioned'] = True
- except Exception as exc:
- result['warnings'].append(f'file clone skipped: {exc}')
- else:
- result['warnings'].append('source path unavailable; files not cloned')
-
- # 2) Best-effort temp DB copy via WP-CLI (export from source, import
- # into the preview db). Both halves are guarded; failure leaves the
- # preview file-only.
- if result.get('preview_path') and src_path:
- try:
- cls.wp_cli(src_path, ['db', 'export', f'/tmp/{preview_db}.sql'])
- cls.wp_cli(result['preview_path'], ['db', 'create'])
- cls.wp_cli(result['preview_path'], ['db', 'import', f'/tmp/{preview_db}.sql'])
- except Exception as exc:
- result['warnings'].append(f'db copy skipped: {exc}')
-
- # 3) Rewrite the preview's site URL to the temporary domain.
- if domain and result.get('preview_path'):
- try:
- new_url = f'https://{domain}'
- cls.search_replace(result['preview_path'],
- cls._site_current_url(app) or '', new_url)
- cls.wp_cli(result['preview_path'], ['option', 'update', 'home', new_url])
- cls.wp_cli(result['preview_path'], ['option', 'update', 'siteurl', new_url])
- except Exception as exc:
- result['warnings'].append(f'url rewrite skipped: {exc}')
-
- return result
- except Exception as exc:
- # Never break the caller — record the failure and move on.
- return {'success': False, 'error': str(exc),
- 'pr_number': int(pr_number) if pr_number is not None else None,
- 'container_ids': []}
-
- @classmethod
- def destroy_preview_instance(cls, site, pr_number) -> Dict:
- """Tear down a WordPress PR preview: drop the temp DB and remove the
- cloned preview directory. Best-effort; never raises."""
- result = {'success': True, 'pr_number': int(pr_number) if pr_number is not None else None,
- 'warnings': []}
- try:
- app = getattr(site, 'application', None)
- src_path = getattr(app, 'root_path', None) if app else None
- if src_path:
- preview_path = f'{src_path.rstrip("/")}-preview-pr-{int(pr_number)}'
- # Drop the temp DB first (uses the preview's own wp-config).
- if os.path.isdir(preview_path):
- try:
- cls.wp_cli(preview_path, ['db', 'drop', '--yes'])
- except Exception as exc:
- result['warnings'].append(f'db drop skipped: {exc}')
- try:
- shutil.rmtree(preview_path, ignore_errors=True)
- except Exception as exc:
- result['warnings'].append(f'dir removal skipped: {exc}')
- return result
- except Exception as exc:
- return {'success': False, 'error': str(exc),
- 'pr_number': int(pr_number) if pr_number is not None else None}
diff --git a/builtin-extensions/serverkit-wordpress/backend/wordpress_sites.py b/builtin-extensions/serverkit-wordpress/backend/wordpress_sites.py
deleted file mode 100644
index 70a5855b..00000000
--- a/builtin-extensions/serverkit-wordpress/backend/wordpress_sites.py
+++ /dev/null
@@ -1,528 +0,0 @@
-"""
-WordPress Sites API — environment sync, database snapshots, and Git integration.
-
-ROUTING NOTE: the WordPress "hub" surface (list/create/get/delete sites,
-environment CRUD, plugins, themes, core update) is owned by ``wordpress_bp``
-(``app/api/wordpress.py``) — the Docker-stack model the UI actually creates
-against. This blueprint owns ONLY the routes that do not overlap with it:
-environment sync, database snapshots, clone-db, and Git integration. Both
-blueprints mount at ``/api/v1/wordpress``; their route paths are kept disjoint
-so neither shadows the other (a duplicate rule would be silently unreachable
-because Flask resolves the first-registered match).
-"""
-
-from flask import Blueprint, request, jsonify
-from app.middleware.rbac import auth_required, get_current_user
-import json
-
-from app import db
-from app.models.application import Application
-from app.models.wordpress_site import WordPressSite, DatabaseSnapshot
-from .wordpress_env_service import WordPressEnvService
-from app.services.db_sync_service import DatabaseSyncService
-from .git_wordpress_service import GitWordPressService
-from app.services.backup_policy_service import BackupPolicyService, BackupPolicyError
-
-wordpress_sites_bp = Blueprint('wordpress_sites', __name__)
-
-
-# =============================================================================
-# Environment Sync
-# =============================================================================
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/sync', methods=['POST'])
-@auth_required()
-def sync_environment(site_id):
- """Sync an environment from its production source."""
- user = get_current_user()
- user_id = user.id
- data = request.get_json() or {}
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site:
- return jsonify({'error': 'Site not found'}), 404
-
- if site.is_production:
- return jsonify({'error': 'Cannot sync a production site'}), 400
-
- result = WordPressEnvService.sync_environment(site_id, options=data)
- if result['success']:
- return jsonify(result)
- else:
- return jsonify(result), 500
-
-
-# =============================================================================
-# Database Operations
-# =============================================================================
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/snapshots', methods=['GET'])
-@auth_required()
-def list_snapshots(site_id):
- """List database snapshots for a site."""
- user = get_current_user()
- user_id = user.id
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site:
- return jsonify({'error': 'Site not found'}), 404
-
- snapshots = DatabaseSnapshot.query.filter_by(site_id=site_id).order_by(
- DatabaseSnapshot.created_at.desc()
- ).all()
-
- return jsonify({
- 'snapshots': [s.to_dict() for s in snapshots],
- 'total': len(snapshots)
- })
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/snapshots', methods=['POST'])
-@auth_required()
-def create_snapshot(site_id):
- """Create a database snapshot."""
- user = get_current_user()
- user_id = user.id
- data = request.get_json() or {}
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site:
- return jsonify({'error': 'Site not found'}), 404
-
- result = DatabaseSyncService.create_snapshot(
- db_name=site.db_name,
- name=data.get('name', f"{site.application.name}_{site.id}"),
- tag=data.get('tag'),
- commit_sha=site.last_deploy_commit,
- host=site.db_host,
- user=site.db_user,
- password=WordPressEnvService._get_db_password(site),
- exclude_tables=data.get('exclude_tables', [])
- )
-
- if result['success']:
- # Save to database
- snapshot = DatabaseSnapshot(
- site_id=site_id,
- name=result['snapshot']['name'],
- tag=data.get('tag'),
- file_path=result['snapshot']['file_path'],
- size_bytes=result['snapshot']['size_bytes'],
- compressed=result['snapshot']['compressed'],
- commit_sha=site.last_deploy_commit,
- tables_included=json.dumps(result['snapshot'].get('tables', [])),
- row_count=result['snapshot'].get('row_count', 0),
- status='completed'
- )
- db.session.add(snapshot)
- db.session.commit()
-
- # Best-effort offsite upload (no-op unless remote storage + auto_upload enabled)
- DatabaseSyncService.upload_snapshot_offsite(snapshot.file_path)
-
- return jsonify({
- 'success': True,
- 'snapshot': snapshot.to_dict()
- }), 201
- else:
- return jsonify(result), 500
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/snapshots/<int:snapshot_id>/restore', methods=['POST'])
-@auth_required()
-def restore_snapshot(site_id, snapshot_id):
- """Restore a database snapshot."""
- user = get_current_user()
- user_id = user.id
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site:
- return jsonify({'error': 'Site not found'}), 404
-
- snapshot = DatabaseSnapshot.query.filter_by(id=snapshot_id, site_id=site_id).first()
- if not snapshot:
- return jsonify({'error': 'Snapshot not found'}), 404
-
- # Create a backup before restoring
- backup_result = DatabaseSyncService.create_snapshot(
- db_name=site.db_name,
- name=f"pre_restore_{snapshot_id}",
- tag='pre-restore',
- host=site.db_host,
- user=site.db_user,
- password=WordPressEnvService._get_db_password(site)
- )
-
- # Restore the snapshot
- result = DatabaseSyncService.restore_snapshot(
- file_path=snapshot.file_path,
- target_db=site.db_name,
- host=site.db_host,
- user=site.db_user,
- password=WordPressEnvService._get_db_password(site),
- create_db=False
- )
-
- if result['success']:
- return jsonify({
- 'success': True,
- 'message': 'Snapshot restored',
- 'backup_path': backup_result.get('snapshot', {}).get('file_path') if backup_result.get('success') else None
- })
- else:
- return jsonify(result), 500
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/snapshots/<int:snapshot_id>', methods=['DELETE'])
-@auth_required()
-def delete_snapshot(site_id, snapshot_id):
- """Delete a database snapshot."""
- user = get_current_user()
- user_id = user.id
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site:
- return jsonify({'error': 'Site not found'}), 404
-
- snapshot = DatabaseSnapshot.query.filter_by(id=snapshot_id, site_id=site_id).first()
- if not snapshot:
- return jsonify({'error': 'Snapshot not found'}), 404
-
- # Delete file
- DatabaseSyncService.delete_snapshot(snapshot.file_path)
-
- # Delete record
- db.session.delete(snapshot)
- db.session.commit()
-
- return jsonify({'success': True, 'message': 'Snapshot deleted'})
-
-
-# =============================================================================
-# Backup Protection (policy + runs)
-# =============================================================================
-
-def _load_wp_site(site_id):
- """Load a site the current user owns, or None."""
- user = get_current_user()
- return WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user.id,
- ).first()
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/backup-policy', methods=['GET'])
-@auth_required()
-def get_wp_backup_policy(site_id):
- """Return the protection policy + status for a site (creating a default)."""
- if not _load_wp_site(site_id):
- return jsonify({'error': 'Site not found'}), 404
- policy = BackupPolicyService.get_or_create_policy('wordpress_site', site_id)
- return jsonify(BackupPolicyService.serialize_policy_view(policy))
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/backup-policy', methods=['PUT'])
-@auth_required()
-def update_wp_backup_policy(site_id):
- """Update the protection policy and re-sync its schedule."""
- if not _load_wp_site(site_id):
- return jsonify({'error': 'Site not found'}), 404
- policy = BackupPolicyService.get_or_create_policy('wordpress_site', site_id)
- try:
- BackupPolicyService.update_policy(policy, request.get_json() or {})
- except BackupPolicyError as e:
- return jsonify({'error': str(e)}), 400
- return jsonify(BackupPolicyService.serialize_policy_view(policy))
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/backups', methods=['POST'])
-@auth_required()
-def trigger_wp_backup(site_id):
- """Enqueue a one-off backup for the site."""
- if not _load_wp_site(site_id):
- return jsonify({'error': 'Site not found'}), 404
- policy = BackupPolicyService.get_or_create_policy('wordpress_site', site_id)
- try:
- job = BackupPolicyService.run_policy_now(policy, manual=True)
- except BackupPolicyError as e:
- return jsonify({'error': str(e)}), 409
- return jsonify({'success': True, 'job_id': job.id}), 202
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/backups', methods=['GET'])
-@auth_required()
-def list_wp_backups(site_id):
- """List backup runs for the site."""
- if not _load_wp_site(site_id):
- return jsonify({'error': 'Site not found'}), 404
- policy = BackupPolicyService.get_or_create_policy('wordpress_site', site_id)
- return jsonify({'runs': BackupPolicyService.list_runs(policy)})
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/backups/<int:run_id>/restore', methods=['POST'])
-@auth_required()
-def restore_wp_backup(site_id, run_id):
- """Enqueue a restore from a specific backup run."""
- if not _load_wp_site(site_id):
- return jsonify({'error': 'Site not found'}), 404
- policy = BackupPolicyService.get_or_create_policy('wordpress_site', site_id)
- try:
- job = BackupPolicyService.request_restore(policy, run_id, request.get_json() or {})
- except BackupPolicyError as e:
- return jsonify({'error': str(e)}), 400
- return jsonify({'success': True, 'job_id': job.id}), 202
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/backups/<int:run_id>/verify', methods=['POST'])
-@auth_required()
-def verify_wp_backup(site_id, run_id):
- """Verify the remote copy of a backup run."""
- if not _load_wp_site(site_id):
- return jsonify({'error': 'Site not found'}), 404
- policy = BackupPolicyService.get_or_create_policy('wordpress_site', site_id)
- try:
- result = BackupPolicyService.verify_run(policy, run_id)
- except BackupPolicyError as e:
- return jsonify({'error': str(e)}), 400
- return jsonify(result)
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/backups/<int:run_id>', methods=['DELETE'])
-@auth_required()
-def delete_wp_backup(site_id, run_id):
- """Delete a backup run (local + remote + record)."""
- if not _load_wp_site(site_id):
- return jsonify({'error': 'Site not found'}), 404
- policy = BackupPolicyService.get_or_create_policy('wordpress_site', site_id)
- try:
- BackupPolicyService.delete_run(policy, run_id)
- except BackupPolicyError as e:
- return jsonify({'error': str(e)}), 400
- return jsonify({'success': True})
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/clone-db', methods=['POST'])
-@auth_required()
-def clone_database(site_id):
- """Clone the database to another environment."""
- user = get_current_user()
- user_id = user.id
- data = request.get_json()
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site:
- return jsonify({'error': 'Site not found'}), 404
-
- target_site_id = data.get('target_site_id')
- if not target_site_id:
- return jsonify({'error': 'target_site_id is required'}), 400
-
- target_site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == target_site_id,
- Application.user_id == user_id
- ).first()
-
- if not target_site:
- return jsonify({'error': 'Target site not found'}), 404
-
- result = DatabaseSyncService.clone_database(
- source_db=site.db_name,
- target_db=target_site.db_name,
- source_host=site.db_host,
- target_host=target_site.db_host,
- source_user=site.db_user,
- target_user=target_site.db_user,
- source_password=WordPressEnvService._get_db_password(site),
- target_password=WordPressEnvService._get_db_password(target_site),
- options=data.get('options', {})
- )
-
- if result['success']:
- return jsonify(result)
- else:
- return jsonify(result), 500
-
-
-# =============================================================================
-# Git Integration
-# =============================================================================
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/git', methods=['GET'])
-@auth_required()
-def get_git_status(site_id):
- """Get Git integration status for a site."""
- user = get_current_user()
- user_id = user.id
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site:
- return jsonify({'error': 'Site not found'}), 404
-
- result = GitWordPressService.get_git_status(site_id)
- return jsonify(result)
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/git', methods=['POST'])
-@auth_required()
-def connect_repo(site_id):
- """Connect a Git repository to a site."""
- user = get_current_user()
- user_id = user.id
- data = request.get_json()
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site:
- return jsonify({'error': 'Site not found'}), 404
-
- repo_url = data.get('repo_url')
- if not repo_url:
- return jsonify({'error': 'repo_url is required'}), 400
-
- result = GitWordPressService.connect_repo(
- site_id=site_id,
- repo_url=repo_url,
- branch=data.get('branch', 'main'),
- paths=data.get('paths'),
- auto_deploy=data.get('auto_deploy', False)
- )
-
- if result['success']:
- return jsonify(result)
- else:
- return jsonify(result), 500
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/git', methods=['DELETE'])
-@auth_required()
-def disconnect_repo(site_id):
- """Disconnect Git repository from a site."""
- user = get_current_user()
- user_id = user.id
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site:
- return jsonify({'error': 'Site not found'}), 404
-
- result = GitWordPressService.disconnect_repo(site_id)
- if result['success']:
- return jsonify(result)
- else:
- return jsonify(result), 500
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/git/commits', methods=['GET'])
-@auth_required()
-def get_commits(site_id):
- """Get recent commits from the connected repository."""
- user = get_current_user()
- user_id = user.id
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site:
- return jsonify({'error': 'Site not found'}), 404
-
- limit = request.args.get('limit', 20, type=int)
- result = GitWordPressService.get_recent_commits(site_id, limit=limit)
- return jsonify(result)
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/git/deploy', methods=['POST'])
-@auth_required()
-def deploy_commit(site_id):
- """Deploy a specific commit or branch."""
- user = get_current_user()
- user_id = user.id
- data = request.get_json() or {}
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site:
- return jsonify({'error': 'Site not found'}), 404
-
- result = GitWordPressService.deploy_from_commit(
- site_id=site_id,
- commit_sha=data.get('commit_sha'),
- branch=data.get('branch'),
- create_snapshot=data.get('create_snapshot', True)
- )
-
- if result['success']:
- return jsonify(result)
- else:
- return jsonify(result), 500
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/git/dev-from-commit', methods=['POST'])
-@auth_required()
-def create_dev_from_commit(site_id):
- """Create a development environment for a specific commit."""
- user = get_current_user()
- user_id = user.id
- data = request.get_json()
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site:
- return jsonify({'error': 'Site not found'}), 404
-
- commit_sha = data.get('commit_sha')
- if not commit_sha:
- return jsonify({'error': 'commit_sha is required'}), 400
-
- result = GitWordPressService.create_dev_for_commit(
- production_site_id=site_id,
- commit_sha=commit_sha,
- config=data.get('config', {}),
- user_id=user_id
- )
-
- if result['success']:
- return jsonify(result), 201
- else:
- return jsonify(result), 500
diff --git a/builtin-extensions/serverkit-wordpress/backend/wp_analytics_service.py b/builtin-extensions/serverkit-wordpress/backend/wp_analytics_service.py
deleted file mode 100644
index 1f555341..00000000
--- a/builtin-extensions/serverkit-wordpress/backend/wp_analytics_service.py
+++ /dev/null
@@ -1,262 +0,0 @@
-"""Per-site WordPress traffic + error analytics (#25).
-
-Docker-correct: managed WP sites are official ``wordpress:*-apache`` containers
-that send the Apache *combined* access log to the container's stdout, so
-``docker logs <container>`` is the source (the in-container access.log is a
-symlink to stdout — exec-cat'ing it yields nothing). Analytics is computed
-**on demand** over a recent window; there is no separate store, so history is
-bounded by the container's retained log (it resets when the container is
-recreated, e.g. on a PHP-version switch — see #24).
-
-PHP fatals/warnings are sourced separately from the WP_DEBUG log
-(``/tmp/wp-debug.log``), populated only once the per-site WP_DEBUG toggle (#30)
-is on — see ``get_php_errors`` (they are not in the access log).
-
-Still NOT derived (deferred):
-- per-request response time / slow pages — need a ``%D`` LogFormat the official
- image does not emit.
-- cache hit ratio — a cache-plugin concern surfaced by #22/#23, not the access log.
-"""
-
-import re
-import subprocess
-from collections import Counter
-from datetime import datetime, timedelta, timezone
-
-from app.utils.formatting import format_bytes
-
-
-# Apache "combined" CustomLog (the official wordpress:*-apache default to stdout):
-# %h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"
-_ACCESS_RE = re.compile(
- r'^(?P<ip>\S+) \S+ \S+ \[(?P<time>[^\]]+)\] '
- r'"(?P<request>[^"]*)" (?P<status>\d{3}) (?P<bytes>\S+) '
- r'"(?P<referer>[^"]*)" "(?P<ua>[^"]*)"'
-)
-_BOT_RE = re.compile(
- r'bot|crawl|spider|slurp|mediapartners|facebookexternalhit|embedly|bingpreview|monitor|wget|curl|python-requests',
- re.IGNORECASE,
-)
-_APACHE_TIME_FMT = '%d/%b/%Y:%H:%M:%S %z'
-
-
-class WpAnalyticsService:
- """On-demand per-site traffic/error analytics from the apache access log."""
-
- MAX_HOURS = 168 # cap the window at 7 days
- TAIL_CAP = 20000 # cap the docker-logs pull so a busy site can't blow up memory
- LOG_TIMEOUT = 15 # seconds; bound the synchronous docker-logs pull (single-worker safety)
-
- @classmethod
- def get_traffic(cls, container_name, hours=24):
- try:
- hours = int(hours)
- except (TypeError, ValueError):
- hours = 24
- hours = max(1, min(hours, cls.MAX_HOURS))
-
- result = cls._empty(hours)
- if not container_name:
- result['note'] = 'No container is resolved for this site.'
- return result
-
- # Pull the access log straight from the container's stdout with a hard
- # timeout so a busy site / hung daemon can't block the (single) worker.
- # Reading only stdout cleanly separates the access log from the error_log
- # (which Apache sends to stderr).
- try:
- proc = subprocess.run(
- ['docker', 'logs', '--tail', str(cls.TAIL_CAP), '--since', f'{hours}h', container_name],
- capture_output=True, text=True, timeout=cls.LOG_TIMEOUT,
- )
- except subprocess.TimeoutExpired:
- result['note'] = 'Traffic log timed out — the site may be under heavy load; try a shorter window.'
- return result
- except (FileNotFoundError, OSError):
- result['note'] = 'Traffic log is unavailable on this host (Docker is not reachable).'
- return result
-
- if proc.returncode != 0:
- # e.g. "Error: No such container" — stopped / removed / on a remote agent.
- result['note'] = 'Traffic log is unavailable — the container may be stopped or running on another host.'
- return result
-
- lines = (proc.stdout or '').splitlines()
-
- # Pre-seed continuous hourly buckets so the chart x-axis has no gaps.
- now_hour = datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0)
- buckets = {now_hour - timedelta(hours=i): {'requests': 0, 'errors': 0}
- for i in range(hours, -1, -1)}
-
- ips = set()
- total = 0
- bytes_total = 0
- bots = 0
- not_found = 0
- status_buckets = {'2xx': 0, '3xx': 0, '4xx': 0, '5xx': 0}
- paths = Counter()
-
- for raw in lines:
- m = _ACCESS_RE.match(raw.strip())
- if not m:
- continue # error_log / PHP / non-access lines won't match
- status = int(m.group('status'))
- total += 1
- ips.add(m.group('ip'))
-
- b = m.group('bytes')
- if b.isdigit():
- bytes_total += int(b)
-
- bucket = f'{status // 100}xx'
- if bucket in status_buckets:
- status_buckets[bucket] += 1
- if status == 404:
- not_found += 1
- if _BOT_RE.search(m.group('ua')):
- bots += 1
-
- req_parts = m.group('request').split(' ')
- path = req_parts[1] if len(req_parts) >= 2 else m.group('request')
- paths[path.split('?', 1)[0]] += 1 # group by route; drop query strings (may carry tokens)
-
- try:
- t = datetime.strptime(m.group('time'), _APACHE_TIME_FMT).astimezone(timezone.utc)
- hk = t.replace(minute=0, second=0, microsecond=0)
- if hk in buckets:
- buckets[hk]['requests'] += 1
- if status >= 400:
- buckets[hk]['errors'] += 1
- except (ValueError, OverflowError):
- pass
-
- if total == 0:
- result['note'] = (
- f'No requests recorded in the last {hours}h — the site may be idle, '
- 'stopped, or recently recreated (the access log resets on recreate).'
- )
- return result
-
- errors = status_buckets['4xx'] + status_buckets['5xx']
- result.update({
- 'requests': total,
- 'unique_visitors': len(ips),
- 'bytes': bytes_total,
- 'bytes_human': cls._human_bytes(bytes_total),
- 'status': status_buckets,
- 'not_found': not_found,
- 'bot_requests': bots,
- 'bot_pct': round(bots / total * 100, 1),
- 'error_rate': round(errors / total * 100, 1),
- 'top_paths': [{'path': p, 'count': c} for p, c in paths.most_common(10)],
- 'series': [{'hour': k.isoformat(), 'requests': v['requests'], 'errors': v['errors']}
- for k, v in sorted(buckets.items())],
- 'note': None,
- })
- return result
-
- # --- PHP errors (#25 fatals) -------------------------------------------
- # Sourced from the WP_DEBUG log, NOT the access log. The log only exists once
- # the per-site WP_DEBUG toggle (#30) is on; its path is owned by WpSecurityService.
- DEBUG_LOG = '/tmp/wp-debug.log'
- PHP_ERR_TAIL = 200000 # bytes; bound the debug-log read so a noisy site can't blow up memory
- RECENT_CAP = 25 # most-recent entries returned
-
- # WP debug.log line: "[15-Jun-2026 12:34:56 UTC] PHP Fatal error: <message>"
- _PHP_ERR_RE = re.compile(r'^\[(?P<time>[^\]]+)\]\s+PHP\s+(?P<level>[A-Za-z][A-Za-z ]*?):\s+(?P<msg>.*)$')
-
- @staticmethod
- def _classify_php(level):
- l = level.lower()
- if 'fatal' in l or 'parse error' in l:
- return 'fatal'
- if 'warning' in l:
- return 'warning'
- if 'deprecated' in l:
- return 'deprecated'
- if 'notice' in l:
- return 'notice'
- return 'other'
-
- @classmethod
- def get_php_errors(cls, container_name):
- """Parse PHP fatals/warnings/notices from the container's WP_DEBUG log
- (``/tmp/wp-debug.log``, written only once the #30 WP_DEBUG toggle is on).
- On-demand like get_traffic, with a bounded read + hard timeout so the
- single worker never blocks. Never raises."""
- out = {'available': False, 'enabled': False, 'total': 0,
- 'counts': {'fatal': 0, 'warning': 0, 'notice': 0, 'deprecated': 0, 'other': 0},
- 'recent': [], 'note': None}
- if not container_name:
- out['note'] = 'No container is resolved for this site.'
- return out
-
- # One exec: print a marker IFF the log exists, then its (size-capped) tail.
- # Empty output => no log => WP_DEBUG logging not enabled (or never errored).
- marker = '__SK_WPDEBUG__'
- script = (f'if [ -f {cls.DEBUG_LOG} ]; then echo {marker}; '
- f'tail -c {cls.PHP_ERR_TAIL} {cls.DEBUG_LOG}; fi')
- try:
- proc = subprocess.run(
- ['docker', 'exec', container_name, 'sh', '-c', script],
- capture_output=True, text=True, timeout=cls.LOG_TIMEOUT,
- )
- except subprocess.TimeoutExpired:
- out['note'] = 'Debug log read timed out.'
- return out
- except (FileNotFoundError, OSError):
- out['note'] = 'Debug log is unavailable on this host (Docker is not reachable).'
- return out
- if proc.returncode != 0:
- out['note'] = 'Debug log is unavailable — the container may be stopped or on another host.'
- return out
-
- body = proc.stdout or ''
- if not body.startswith(marker):
- out['note'] = ('PHP error logging is off — enable WP_DEBUG logging on the '
- 'Security tab to collect PHP fatals and warnings.')
- return out
- out['available'] = True
- out['enabled'] = True
- content = body[len(marker):].lstrip('\n')
-
- recent = []
- for raw in content.splitlines():
- m = cls._PHP_ERR_RE.match(raw.strip())
- if not m:
- continue # stack-trace / continuation lines won't match
- sev = cls._classify_php(m.group('level'))
- out['counts'][sev] += 1
- out['total'] += 1
- recent.append({'time': m.group('time'), 'level': m.group('level').strip(),
- 'severity': sev, 'message': m.group('msg').strip()[:300]})
- out['recent'] = list(reversed(recent))[:cls.RECENT_CAP] # most-recent first
- if out['total'] == 0:
- out['note'] = 'WP_DEBUG logging is on; no PHP errors recorded yet.'
- return out
-
- @classmethod
- def _empty(cls, hours):
- now_hour = datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0)
- series = [{'hour': (now_hour - timedelta(hours=i)).isoformat(), 'requests': 0, 'errors': 0}
- for i in range(hours, -1, -1)]
- return {
- 'success': True,
- 'window_hours': hours,
- 'requests': 0,
- 'unique_visitors': 0,
- 'bytes': 0,
- 'bytes_human': '0 B',
- 'status': {'2xx': 0, '3xx': 0, '4xx': 0, '5xx': 0},
- 'not_found': 0,
- 'bot_requests': 0,
- 'bot_pct': 0.0,
- 'error_rate': 0.0,
- 'top_paths': [],
- 'series': series,
- 'note': None,
- }
-
- @staticmethod
- def _human_bytes(n):
- return format_bytes(n, suffix_sep=' ')
diff --git a/builtin-extensions/serverkit-wordpress/backend/wp_reports_service.py b/builtin-extensions/serverkit-wordpress/backend/wp_reports_service.py
deleted file mode 100644
index 86bd0c1d..00000000
--- a/builtin-extensions/serverkit-wordpress/backend/wp_reports_service.py
+++ /dev/null
@@ -1,363 +0,0 @@
-"""Monthly client reports for managed WordPress sites (#33 — agency-scale slice).
-
-Aggregates the per-site signals that already accrue elsewhere in the panel into
-a single, client-presentable monthly report and persists it (see the docstring
-on the WordPressReport model for *why* it's persisted rather than computed live).
-
-Data-source honesty (this is the whole point of the feature):
- * Uptime % + incidents (#26) -> TRUE month history, re-aggregated from the
- retained HealthCheck samples (90-day retention) for the exact month.
- * Update runs (#29) -> TRUE month history (WordPressUpdateRun rows).
- * Database snapshots/backups -> TRUE month history (DatabaseSnapshot rows).
- * Vulnerabilities (#28) -> CURRENT posture only (findings are
- deleted-and-replaced each scan), captured as-of generation time.
- * Health / disk -> CURRENT values, captured as-of generation.
- * Traffic (#25) / on-demand security scans (#30) -> point-in-time, omitted
- from monthly history (and a note says so).
-
-Generation is synchronous: it is pure DB aggregation (no WP-CLI, no external
-HTTP), so unlike the scan/update services it needs no background thread.
-"""
-
-import calendar
-import json
-from datetime import datetime, timedelta
-
-
-class WpReportsService:
- """Build + persist + fetch monthly client reports for a WordPress site."""
-
- # ---- public API -------------------------------------------------------
-
- @classmethod
- def get_reports(cls, site):
- """Return all persisted reports for a site, newest month first."""
- from app.models.wordpress_site import WordPressReport
- rows = (WordPressReport.query
- .filter_by(site_id=site.id)
- .order_by(WordPressReport.period_start.desc())
- .all())
- return {'success': True, 'reports': [r.to_dict() for r in rows]}
-
- @classmethod
- def generate(cls, site, year=None, month=None):
- """Compute + upsert the report for one calendar month (default: the
- current UTC month). Regenerating the same month replaces its row so the
- latest posture is captured. Returns {'success', 'report'} or an error."""
- from app import db
- from app.models.wordpress_site import WordPressReport
-
- now = datetime.utcnow()
- year = int(year) if year else now.year
- month = int(month) if month else now.month
- if month < 1 or month > 12:
- return {'success': False, 'error': 'Invalid month'}
- # Guard against generating a report for a future month (no data exists).
- if (year, month) > (now.year, now.month):
- return {'success': False, 'error': 'Cannot generate a report for a future month'}
-
- start, end = cls._month_bounds(year, month)
- label = f'{year:04d}-{month:02d}'
- data = cls._build(site, start, end, label)
-
- row = WordPressReport.query.filter_by(site_id=site.id, period_label=label).first()
- if row is None:
- row = WordPressReport(site_id=site.id, period_label=label,
- period_start=start, period_end=end)
- db.session.add(row)
- row.period_start = start
- row.period_end = end
- row.data = json.dumps(data)
- row.generated_at = now
- db.session.commit()
- return {'success': True, 'report': row.to_dict()}
-
- @classmethod
- def delete(cls, site, report_id):
- """Delete one persisted report belonging to this site."""
- from app import db
- from app.models.wordpress_site import WordPressReport
- row = WordPressReport.query.filter_by(id=report_id, site_id=site.id).first()
- if row is None:
- return {'success': False, 'error': 'Report not found'}
- db.session.delete(row)
- db.session.commit()
- return {'success': True}
-
- # ---- report builder ---------------------------------------------------
-
- @classmethod
- def _build(cls, site, start, end, label):
- now = datetime.utcnow()
- tags = []
- try:
- tags = json.loads(site.tags) if site.tags else []
- except (ValueError, TypeError):
- tags = []
-
- uptime, daily, incidents = cls._uptime_and_incidents(site, start, end, now)
- report = {
- 'period': {
- 'label': label,
- 'start': start.isoformat(),
- 'end': end.isoformat(),
- 'month_name': f'{calendar.month_name[start.month]} {start.year}',
- },
- 'generated_at': now.isoformat(),
- 'site': {
- 'id': site.id,
- 'name': site.application.name if site.application else f'site-{site.id}',
- 'url': cls._site_url(site),
- 'wp_version': site.wp_version,
- 'multisite': bool(site.multisite),
- 'tags': tags,
- 'client': cls._client_from_tags(tags),
- },
- 'uptime': uptime,
- 'uptime_daily': daily,
- 'incidents': incidents,
- 'incident_count': len(incidents),
- 'updates': cls._updates(site, start, end),
- 'backups': cls._backups(site, start, end),
- 'vulnerabilities': cls._vuln_posture(site),
- 'health': cls._health(site),
- 'notes': cls._notes(uptime),
- }
- return report
-
- # ---- sections ---------------------------------------------------------
-
- @classmethod
- def _uptime_and_incidents(cls, site, start, end, now):
- """Re-aggregate the month's uptime % + a daily series + the incidents that
- overlapped the month, from the bound status-page component's samples (#26).
- Returns (uptime_dict, daily_list, incidents_list)."""
- from app.models.status_page import StatusComponent, HealthCheck, StatusIncident
- from sqlalchemy import or_
-
- comp = StatusComponent.query.filter_by(wordpress_site_id=site.id).first()
- if comp is None:
- return ({'bound': False, 'percent': None, 'samples': 0,
- 'checks_up': 0, 'checks_down': 0, 'checks_degraded': 0,
- 'rolling_30d': None}, [], [])
-
- checks = (HealthCheck.query
- .filter(HealthCheck.component_id == comp.id,
- HealthCheck.checked_at >= start,
- HealthCheck.checked_at < end)
- .all())
- total = len(checks)
- up = sum(1 for c in checks if c.status == 'up')
- down = sum(1 for c in checks if c.status == 'down')
- degraded = sum(1 for c in checks if c.status == 'degraded')
- uptime = {
- 'bound': True,
- 'percent': round(up / total * 100, 2) if total else None,
- 'samples': total,
- 'checks_up': up,
- 'checks_down': down,
- 'checks_degraded': degraded,
- 'rolling_30d': comp.uptime_30d,
- }
-
- # Daily uptime series — only the up/total ratio per calendar day. Uses the
- # same "only 'up' counts" rule as recompute_uptime, so degraded reduces it.
- buckets = {}
- for c in checks:
- key = c.checked_at.date().isoformat()
- b = buckets.setdefault(key, {'up': 0, 'total': 0})
- b['total'] += 1
- if c.status == 'up':
- b['up'] += 1
- daily = []
- day = start
- # Stop at the end of *today* (today is included as a partial day) and never
- # emit a future day. Truncate `now` to its date first — otherwise its
- # time-of-day pushes the bound past tomorrow's midnight for a to-date month.
- today_end = datetime(now.year, now.month, now.day) + timedelta(days=1)
- last = min(end, today_end)
- while day < last:
- key = day.date().isoformat()
- b = buckets.get(key)
- daily.append({
- 'date': key,
- 'percent': round(b['up'] / b['total'] * 100, 2) if b and b['total'] else None,
- 'samples': b['total'] if b else 0,
- })
- day += timedelta(days=1)
-
- incident_rows = (StatusIncident.query
- .filter(StatusIncident.component_id == comp.id,
- StatusIncident.created_at < end,
- or_(StatusIncident.resolved_at.is_(None),
- StatusIncident.resolved_at >= start))
- .order_by(StatusIncident.created_at.desc())
- .all())
- incidents = []
- for inc in incident_rows:
- resolved = inc.resolved_at
- # Attribute only the in-month portion of the incident to this report:
- # clamp the window to [start, min(end, now)] so a still-open or
- # cross-month incident doesn't bleed its full elapsed time into the
- # month it's reported under. created_at/resolved_at below stay raw.
- if inc.created_at:
- ref_start = max(inc.created_at, start)
- ref_end = min(resolved or now, end, now)
- minutes = max(0, int((ref_end - ref_start).total_seconds() // 60))
- else:
- minutes = 0
- incidents.append({
- 'id': inc.id,
- 'title': inc.title,
- 'impact': inc.impact,
- 'status': inc.status,
- 'ongoing': resolved is None,
- 'created_at': inc.created_at.isoformat() if inc.created_at else None,
- 'resolved_at': resolved.isoformat() if resolved else None,
- 'duration_minutes': minutes,
- })
- return uptime, daily, incidents
-
- @classmethod
- def _updates(cls, site, start, end):
- from app.models.wordpress_site import WordPressUpdateRun
- runs = (WordPressUpdateRun.query
- .filter(WordPressUpdateRun.site_id == site.id,
- WordPressUpdateRun.started_at >= start,
- WordPressUpdateRun.started_at < end)
- .order_by(WordPressUpdateRun.started_at.desc())
- .all())
- out = {'total_runs': len(runs), 'completed': 0, 'rolled_back': 0,
- 'failed': 0, 'components_updated': 0, 'runs': []}
- for r in runs:
- if r.status in out:
- out[r.status] += 1
- try:
- details = json.loads(r.details) if r.details else {}
- except (ValueError, TypeError):
- details = {}
- updated = details.get('updated') or []
- out['components_updated'] += len(updated)
- out['runs'].append({
- 'id': r.id,
- 'status': r.status,
- 'trigger': r.trigger,
- 'started_at': r.started_at.isoformat() if r.started_at else None,
- 'finished_at': r.finished_at.isoformat() if r.finished_at else None,
- 'updated': updated,
- 'rolled_back': bool(details.get('rolled_back')),
- 'error': r.error,
- })
- return out
-
- @classmethod
- def _backups(cls, site, start, end):
- from app.models.wordpress_site import DatabaseSnapshot
- snaps = (DatabaseSnapshot.query
- .filter(DatabaseSnapshot.site_id == site.id,
- DatabaseSnapshot.created_at >= start,
- DatabaseSnapshot.created_at < end)
- .order_by(DatabaseSnapshot.created_at.desc())
- .all())
- total_bytes = sum((s.size_bytes or 0) for s in snaps)
- return {
- 'count': len(snaps),
- 'total_bytes': total_bytes,
- 'total_bytes_human': DatabaseSnapshot._format_size(total_bytes),
- 'snapshots': [{
- 'id': s.id,
- 'name': s.name,
- 'tag': s.tag,
- 'status': s.status,
- 'size_bytes': s.size_bytes,
- 'size_human': DatabaseSnapshot._format_size(s.size_bytes),
- 'created_at': s.created_at.isoformat() if s.created_at else None,
- } for s in snaps],
- }
-
- @classmethod
- def _vuln_posture(cls, site):
- """Current open-vulnerability posture as-of the last scan. NOT month
- history — findings are overwritten on each scan (see #28)."""
- from app.models.wordpress_site import WordPressVulnerability
- vulns = WordPressVulnerability.query.filter_by(site_id=site.id).all()
- by_sev = {'critical': 0, 'high': 0, 'medium': 0, 'low': 0, 'unknown': 0}
- items = []
- for v in vulns:
- sev = v.severity if v.severity in by_sev else 'unknown'
- by_sev[sev] += 1
- items.append({
- 'source': v.source,
- 'slug': v.slug,
- 'name': v.name,
- 'installed_version': v.installed_version,
- 'severity': v.severity,
- 'advisory_id': v.advisory_id,
- 'fixed_in': v.fixed_in,
- 'reference_url': v.reference_url,
- })
- return {
- 'as_of': site.last_vuln_scan_at.isoformat() if site.last_vuln_scan_at else None,
- 'total': len(items),
- 'by_severity': by_sev,
- 'items': items,
- }
-
- @classmethod
- def _health(cls, site):
- from app.models.wordpress_site import DatabaseSnapshot
- return {
- 'status': site.health_status,
- 'checked_at': site.last_health_check.isoformat() if site.last_health_check else None,
- 'disk_usage_bytes': site.disk_usage_bytes,
- 'disk_usage_human': (DatabaseSnapshot._format_size(site.disk_usage_bytes)
- if site.disk_usage_bytes else None),
- }
-
- @classmethod
- def _notes(cls, uptime):
- notes = [
- 'Vulnerability posture is the current snapshot as of the last scan, '
- 'not month-historical — findings are overwritten on each scan.',
- 'Traffic analytics and on-demand security scans are point-in-time and '
- 'are not included in monthly history.',
- ]
- if not uptime.get('bound'):
- notes.append('Uptime history is unavailable for this period — attach the '
- 'site to a status page (Uptime tab) so uptime % can accrue.')
- return notes
-
- # ---- helpers ----------------------------------------------------------
-
- @staticmethod
- def _month_bounds(year, month):
- """First-of-month .. first-of-next-month (exclusive), naive UTC."""
- start = datetime(year, month, 1)
- if month == 12:
- end = datetime(year + 1, 1, 1)
- else:
- end = datetime(year, month + 1, 1)
- return start, end
-
- @staticmethod
- def _client_from_tags(tags):
- """Derive a client name from a `client-<name>` / `client:<name>` tag (#20)."""
- for t in tags or []:
- if not isinstance(t, str):
- continue
- low = t.lower()
- if low.startswith('client-'):
- return t[len('client-'):] or None
- if low.startswith('client:'):
- return t[len('client:'):] or None
- return None
-
- @staticmethod
- def _site_url(site):
- app = site.application
- domains = list(getattr(app, 'domains', None) or []) if app else []
- if not domains:
- return None
- primary = next((d for d in domains if getattr(d, 'is_primary', False)), domains[0])
- scheme = 'https' if getattr(primary, 'ssl_enabled', False) else 'http'
- return f'{scheme}://{primary.name}'
diff --git a/builtin-extensions/serverkit-wordpress/backend/wp_security_service.py b/builtin-extensions/serverkit-wordpress/backend/wp_security_service.py
deleted file mode 100644
index add83d2a..00000000
--- a/builtin-extensions/serverkit-wordpress/backend/wp_security_service.py
+++ /dev/null
@@ -1,201 +0,0 @@
-"""Per-site WordPress security depth (#30): file-integrity verification,
-WP_DEBUG/SCRIPT_DEBUG toggling, and WP-Cron management — all via the Docker-aware
-WP-CLI bridge (WordPressService.wp_cli), so containerized sites work.
-
-Integrity runs in a background thread (verify-checksums fetches from wordpress.org
-and can be slow) so the single worker never blocks; debug/cron are quick.
-
-Brute-force protection (shipped): each managed site already has a per-site nginx
-reverse-proxy vhost whose access log records wp-login/xmlrpc hits with the real
-client IP, so a per-site Fail2ban jail can watch it. ``get_brute_force`` /
-``set_brute_force`` here are a thin WordPress-facing wrapper over
-``Fail2banJailService`` (the jail-management layer); the jail is enabled by default
-when a site is created and torn down when it is deleted.
-"""
-
-import json
-import logging
-import threading
-from datetime import datetime
-
-logger = logging.getLogger(__name__)
-
-
-class WpSecurityService:
- # In-memory latest integrity result per site (point-in-time, like the Lynis scan).
- _integrity = {}
- _integrity_lock = threading.Lock()
-
- # ---------- file integrity (background) ----------
-
- @classmethod
- def get_integrity(cls, site_id):
- with cls._integrity_lock:
- return dict(cls._integrity.get(site_id, {'status': 'idle'}))
-
- @classmethod
- def start_integrity_scan(cls, site):
- from flask import current_app
- with cls._integrity_lock:
- if cls._integrity.get(site.id, {}).get('status') == 'running':
- return {'success': True, 'status': 'running'}
- cls._integrity[site.id] = {'status': 'running'}
- app = current_app._get_current_object()
- path = site.application.root_path if site.application else None
- threading.Thread(
- target=cls._run_integrity, args=(app, site.id, path), daemon=True,
- name=f'wp-integrity-{site.id}'
- ).start()
- return {'success': True, 'status': 'running'}
-
- @classmethod
- def _run_integrity(cls, app, site_id, path):
- with app.app_context():
- from .wordpress_service import WordPressService
- try:
- if not path:
- raise RuntimeError('Site has no root path')
- core = WordPressService.wp_cli(path, ['core', 'verify-checksums'])
- plug = WordPressService.wp_cli(path, ['plugin', 'verify-checksums', '--all'])
- issues = cls._parse_checksum_issues(core) + cls._parse_checksum_issues(plug)
- result = {
- 'status': 'completed',
- 'core_ok': bool(core.get('success')),
- 'plugins_ok': bool(plug.get('success')),
- 'issues': issues,
- 'checked_at': datetime.utcnow().isoformat(),
- 'error': None,
- }
- except Exception as e:
- logger.error(f'Integrity scan failed for site {site_id}: {e}')
- result = {'status': 'error', 'error': str(e), 'issues': [],
- 'checked_at': datetime.utcnow().isoformat()}
- with cls._integrity_lock:
- cls._integrity[site_id] = result
-
- @staticmethod
- def _parse_checksum_issues(res):
- """Extract the Warning/Error lines verify-checksums emits for modified or
- unexpected files. A clean install emits only a 'Success:' line (no issues)."""
- issues = []
- text = (res.get('output') or '') + '\n' + (res.get('error') or '')
- for line in text.splitlines():
- s = line.strip()
- if s.startswith('Warning:') or s.startswith('Error:'):
- issues.append(s.split(':', 1)[1].strip())
- return issues
-
- # ---------- WP_DEBUG / SCRIPT_DEBUG ----------
-
- # Log OUTSIDE the web root: the default wp-content/debug.log is served by
- # apache (a public info leak), whereas /tmp is container-writable and never
- # web-accessible. (Ephemeral across container restarts, which is fine for a
- # debug log.)
- DEBUG_LOG_PATH = '/tmp/wp-debug.log'
-
- @classmethod
- def get_debug(cls, path):
- from .wordpress_service import WordPressService
-
- def _val(k):
- res = WordPressService.wp_cli(path, ['config', 'get', k])
- return (res.get('output') or '').strip() if res.get('success') else ''
-
- log_raw = _val('WP_DEBUG_LOG').lower()
- state = {
- 'WP_DEBUG': _val('WP_DEBUG').lower() in ('1', 'true'),
- 'WP_DEBUG_LOG': log_raw not in ('', 'false', '0'), # 'true' OR a path
- 'SCRIPT_DEBUG': _val('SCRIPT_DEBUG').lower() in ('1', 'true'),
- 'WP_DEBUG_DISPLAY': _val('WP_DEBUG_DISPLAY').lower() in ('1', 'true'),
- }
- return {'success': True, 'debug': state, 'enabled': state['WP_DEBUG']}
-
- @classmethod
- def set_debug(cls, path, enabled):
- from .wordpress_service import WordPressService
-
- def wp(*args):
- return WordPressService.wp_cli(path, ['config', 'set', *args])
-
- val = 'true' if enabled else 'false'
- # Gate on the primary write so a read-only wp-config / stopped container
- # reports an honest failure instead of a false "updated".
- primary = wp('WP_DEBUG', val, '--raw')
- if not primary.get('success'):
- return {'success': False,
- 'error': primary.get('error') or 'Failed to update wp-config (is the site running?)'}
- wp('SCRIPT_DEBUG', val, '--raw')
- if enabled:
- wp('WP_DEBUG_LOG', cls.DEBUG_LOG_PATH) # string path (not --raw)
- wp('WP_DEBUG_DISPLAY', 'false', '--raw') # never render errors on the page
- else:
- wp('WP_DEBUG_LOG', 'false', '--raw')
- return cls.get_debug(path)
-
- # ---------- WP-Cron ----------
-
- @classmethod
- def get_cron(cls, path):
- from .wordpress_service import WordPressService
- dis = WordPressService.wp_cli(path, ['config', 'get', 'DISABLE_WP_CRON'])
- disabled = (dis.get('output') or '').strip().lower() in ('1', 'true') if dis.get('success') else False
- events = []
- ev = WordPressService.wp_cli(path, ['cron', 'event', 'list', '--format=json'])
- if ev.get('success'):
- try:
- events = json.loads(ev.get('output') or '[]')
- except (ValueError, TypeError):
- events = []
- return {'success': True, 'disabled': disabled, 'events': events}
-
- @classmethod
- def run_cron(cls, path):
- from .wordpress_service import WordPressService
- res = WordPressService.wp_cli(path, ['cron', 'event', 'run', '--due-now'])
- return {
- 'success': bool(res.get('success')),
- 'output': (res.get('output') or '').strip(),
- 'error': res.get('error'),
- }
-
- @classmethod
- def set_cron_disabled(cls, path, disabled):
- from .wordpress_service import WordPressService
- val = 'true' if disabled else 'false'
- res = WordPressService.wp_cli(path, ['config', 'set', 'DISABLE_WP_CRON', val, '--raw'])
- if not res.get('success'):
- return {'success': False, 'error': res.get('error')}
- return cls.get_cron(path)
-
- # ---------- brute-force protection (per-site Fail2ban jail) ----------
-
- @classmethod
- def get_brute_force(cls, site):
- """Per-site login brute-force status (availability, on/off, live bans).
-
- Returns the jail layer's status verbatim, plus a ``no_application`` flag for
- the (unexpected) case of a site with no linked application."""
- from app.services.fail2ban_jail_service import Fail2banJailService
- app = getattr(site, 'application', None)
- if not app:
- return {'available': False, 'enabled': False, 'no_application': True}
- return Fail2banJailService.get_status(app)
-
- @classmethod
- def set_brute_force(cls, site, enabled):
- """Enable or disable the site's WP-login brute-force jail."""
- from app.services.fail2ban_jail_service import Fail2banJailService
- app = getattr(site, 'application', None)
- if not app:
- return {'success': False, 'error': 'Site has no linked application'}
- return (Fail2banJailService.enable_wp_jail(app) if enabled
- else Fail2banJailService.disable_jail(app))
-
- @classmethod
- def unban_brute_force(cls, site, ip):
- """Unban an IP from this site's brute-force jail."""
- from app.services.fail2ban_jail_service import Fail2banJailService
- app = getattr(site, 'application', None)
- if not app:
- return {'success': False, 'error': 'Site has no linked application'}
- return Fail2banJailService.unban(app, ip)
diff --git a/builtin-extensions/serverkit-wordpress/backend/wp_ssh_import.py b/builtin-extensions/serverkit-wordpress/backend/wp_ssh_import.py
deleted file mode 100644
index 937fa7f8..00000000
--- a/builtin-extensions/serverkit-wordpress/backend/wp_ssh_import.py
+++ /dev/null
@@ -1,76 +0,0 @@
-"""WordPress-over-SSH pull importer API (Panel Improvements #3).
-
-Admin-only surface:
-
-* ``POST /api/v1/wordpress/ssh-import/probe`` — connect to the source box,
- return the host-key fingerprint + site facts for operator confirmation.
-* ``POST /api/v1/wordpress/ssh-import`` — enqueue the import job (requires the
- probed fingerprint back: that confirmation IS the host-key trust decision).
-* ``GET /api/v1/wordpress/ssh-import/<job_id>`` — poll job status + step log.
-
-Mounted via ``plugin.json`` ``extra_blueprints`` at ``/api/v1/wordpress``.
-"""
-from flask import Blueprint, request, jsonify
-
-from app.middleware.rbac import admin_required, get_current_user
-
-from .wp_ssh_import_service import (
- JOB_KIND, WpSshImportError, WpSshImportService,
-)
-
-wp_ssh_import_bp = Blueprint('wp_ssh_import', __name__)
-
-# Belt-and-braces: the manifest declares the job handler too, but registering on
-# blueprint import guarantees the kind exists as soon as the API is mounted.
-WpSshImportService.register_jobs()
-
-
-@wp_ssh_import_bp.route('/ssh-import/probe', methods=['POST'])
-@admin_required
-def ssh_import_probe():
- """Probe a remote WordPress over SSH: host-key fingerprint + site facts."""
- data = request.get_json() or {}
- try:
- result = WpSshImportService.probe(
- host=data.get('host'),
- port=data.get('port') or 22,
- username=data.get('username'),
- auth=data.get('auth') or {},
- wp_path=data.get('wp_path'),
- )
- except WpSshImportError as e:
- return jsonify({'error': str(e)}), 400
- return jsonify(result)
-
-
-@wp_ssh_import_bp.route('/ssh-import', methods=['POST'])
-@admin_required
-def ssh_import_start():
- """Enqueue the pull-import job. Body: {connection, fingerprint, target, options}."""
- data = request.get_json() or {}
- user = get_current_user()
- try:
- job = WpSshImportService.enqueue_import(
- connection=data.get('connection') or {},
- fingerprint=(data.get('fingerprint') or '').strip(),
- target=data.get('target') or {},
- options=data.get('options') or {},
- user_id=user.id,
- )
- except WpSshImportError as e:
- return jsonify({'error': str(e)}), 400
- return jsonify({'success': True, 'job_id': job.id}), 202
-
-
-@wp_ssh_import_bp.route('/ssh-import/<job_id>', methods=['GET'])
-@admin_required
-def ssh_import_status(job_id):
- """Job status + step log for a running/finished SSH import."""
- from app.jobs.models import Job
- job = Job.query.get(job_id)
- if not job or job.kind != JOB_KIND:
- return jsonify({'error': 'Import job not found'}), 404
- out = job.to_dict() # payload excluded by default — never echo credentials
- result = job.get_result() or {}
- out['steps'] = result.get('steps') or []
- return jsonify(out)
diff --git a/builtin-extensions/serverkit-wordpress/backend/wp_ssh_import_service.py b/builtin-extensions/serverkit-wordpress/backend/wp_ssh_import_service.py
deleted file mode 100644
index 3f66624b..00000000
--- a/builtin-extensions/serverkit-wordpress/backend/wp_ssh_import_service.py
+++ /dev/null
@@ -1,657 +0,0 @@
-"""WordPress-over-SSH pull importer (Panel Improvements #3).
-
-Point the panel at any live WordPress site reachable over SSH and rebuild it as
-a managed site: probe the box (host-key fingerprint + wp-config facts), then a
-background job pulls the docroot with ``tar`` streamed over SSH, dumps the DB
-through the same tunnel, and hands everything to the extension's existing
-``WordPressService.import_site`` flow (fresh Docker stack + DB overwrite +
-URL search-replace + wp-content copy).
-
-Security posture:
-
-* **Host-key pinning** — the SHA256 fingerprint captured at probe time must be
- re-presented for the import; every later SSH connection re-scans the host and
- refuses to proceed on any mismatch (StrictHostKeyChecking=yes against a
- known_hosts file we write from the verified scan — never the user's).
-* **SSRF guard** — the target host is resolved before any connection and
- rejected when it lands on loopback, link-local (incl. the 169.254.169.254
- cloud metadata endpoint), unspecified or multicast space. Explicit private
- RFC1918/ULA addresses are ALLOWED on purpose: LAN-to-panel migrations are a
- legitimate use; only metadata/loopback tricks are blocked (assumption logged).
-* **No secrets on command lines or in logs** — the SSH key goes through a
- 0600 temp file, passwords through ``sshpass -e`` (env), the remote MySQL
- password through the remote process' stdin. Job step logs carry no secrets,
- and the job payload is scrubbed of credentials when the job finishes.
-* **Traversal-guarded extraction** — the pulled docroot tarball is unpacked
- with an explicit member filter (no absolute paths, no ``..``, no links that
- escape the destination, no device nodes).
-
-All process execution funnels through ``_run`` / ``_ssh_exec`` choke-points so
-the test suite can stub the remote side entirely.
-"""
-import base64
-import hashlib
-import ipaddress
-import logging
-import os
-import re
-import shutil
-import socket
-import subprocess
-import tarfile
-import tempfile
-import zipfile
-from typing import Dict, List, Optional
-
-logger = logging.getLogger(__name__)
-
-JOB_KIND = 'wordpress.ssh_import.run'
-
-# Preferred host-key algorithms for the pinned fingerprint, best first.
-_KEY_PREFERENCE = ['ssh-ed25519', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384',
- 'ecdsa-sha2-nistp521', 'rsa-sha2-512', 'rsa-sha2-256', 'ssh-rsa']
-
-_HOST_RE = re.compile(r'^[A-Za-z0-9._:\-\[\]]+$')
-_USER_RE = re.compile(r'^[A-Za-z0-9._\-]+$')
-
-
-class WpSshImportError(Exception):
- """Operator-facing failure (message is safe to surface)."""
-
-
-class WpSshImportService:
- """Probe + pull-import a remote WordPress site over SSH."""
-
- CONNECT_TIMEOUT = 15
- EXEC_TIMEOUT = 60
- TRANSFER_TIMEOUT = 3600
-
- # ------------------------------------------------------------------ #
- # Choke-points (stubbed in tests)
- # ------------------------------------------------------------------ #
-
- @classmethod
- def _run(cls, cmd: List[str], input_bytes: bytes = None, timeout: int = None,
- env: Dict = None, stdout_path: str = None) -> Dict:
- """Run a local process. Returns {'code', 'stdout', 'stderr'} (bytes-safe).
-
- When ``stdout_path`` is given, stdout is streamed to that file instead
- of being buffered (used for docroot/DB pulls).
- """
- full_env = dict(os.environ)
- if env:
- full_env.update(env)
- try:
- if stdout_path:
- with open(stdout_path, 'wb') as out:
- proc = subprocess.run(
- cmd, input=input_bytes, stdout=out,
- stderr=subprocess.PIPE, timeout=timeout or cls.EXEC_TIMEOUT,
- env=full_env,
- )
- return {'code': proc.returncode, 'stdout': b'',
- 'stderr': proc.stderr or b''}
- proc = subprocess.run(
- cmd, input=input_bytes, capture_output=True,
- timeout=timeout or cls.EXEC_TIMEOUT, env=full_env,
- )
- return {'code': proc.returncode, 'stdout': proc.stdout or b'',
- 'stderr': proc.stderr or b''}
- except subprocess.TimeoutExpired:
- return {'code': -1, 'stdout': b'', 'stderr': b'timed out'}
- except FileNotFoundError as e:
- return {'code': -1, 'stdout': b'', 'stderr': str(e).encode()}
-
- # ------------------------------------------------------------------ #
- # Host validation (SSRF guard)
- # ------------------------------------------------------------------ #
-
- @classmethod
- def validate_host(cls, host: str) -> str:
- """Return the cleaned host or raise WpSshImportError.
-
- Blocks loopback, link-local (incl. 169.254.169.254 metadata),
- unspecified and multicast targets. Private RFC1918/ULA addresses are
- allowed by design — LAN migrations are legitimate (logged).
- """
- host = (host or '').strip().strip('[]')
- if not host or host.startswith('-') or not _HOST_RE.match(host):
- raise WpSshImportError('Invalid host')
- if host.lower() in ('localhost', 'localhost.localdomain'):
- raise WpSshImportError('Refusing to import from loopback')
- try:
- infos = socket.getaddrinfo(host, 22, proto=socket.IPPROTO_TCP)
- except socket.gaierror:
- raise WpSshImportError(f'Host does not resolve: {host}')
- private_seen = False
- for info in infos:
- try:
- ip = ipaddress.ip_address(info[4][0])
- except ValueError:
- continue
- if ip.is_loopback or ip.is_unspecified or ip.is_multicast or ip.is_link_local:
- raise WpSshImportError(
- f'Refusing to import from {ip} (loopback/link-local/metadata range)')
- if ip.is_private:
- private_seen = True
- if private_seen:
- logger.info('wp ssh-import: %s resolves to a private address; '
- 'allowing (LAN migration assumed)', host)
- return host
-
- @classmethod
- def _validate_conn(cls, conn: Dict) -> Dict:
- host = cls.validate_host(conn.get('host'))
- username = (conn.get('username') or '').strip()
- if not username or not _USER_RE.match(username):
- raise WpSshImportError('Invalid username')
- try:
- port = int(conn.get('port') or 22)
- except (TypeError, ValueError):
- raise WpSshImportError('Invalid port')
- if not 1 <= port <= 65535:
- raise WpSshImportError('Invalid port')
- auth = conn.get('auth') or {}
- if not (auth.get('password') or auth.get('private_key')):
- raise WpSshImportError('A password or private key is required')
- return {'host': host, 'port': port, 'username': username, 'auth': auth}
-
- # ------------------------------------------------------------------ #
- # Host-key scan + pinning
- # ------------------------------------------------------------------ #
-
- @staticmethod
- def fingerprint_of(key_b64: str) -> str:
- """OpenSSH-style SHA256 fingerprint of a base64 host key blob."""
- digest = hashlib.sha256(base64.b64decode(key_b64)).digest()
- return 'SHA256:' + base64.b64encode(digest).decode().rstrip('=')
-
- @classmethod
- def _keyscan(cls, host: str, port: int) -> List[Dict]:
- """ssh-keyscan the host. Returns [{'type','key','line'}], best-first."""
- res = cls._run(['ssh-keyscan', '-T', str(cls.CONNECT_TIMEOUT),
- '-p', str(port), '--', host], timeout=cls.CONNECT_TIMEOUT + 10)
- keys = []
- for raw in (res.get('stdout') or b'').decode('utf-8', 'replace').splitlines():
- raw = raw.strip()
- if not raw or raw.startswith('#'):
- continue
- parts = raw.split()
- if len(parts) >= 3:
- keys.append({'type': parts[1], 'key': parts[2], 'line': raw})
- if not keys:
- raise WpSshImportError(f'Could not read an SSH host key from {host}:{port}')
-
- def rank(k):
- try:
- return _KEY_PREFERENCE.index(k['type'])
- except ValueError:
- return len(_KEY_PREFERENCE)
- keys.sort(key=rank)
- return keys
-
- @classmethod
- def scan_fingerprint(cls, host: str, port: int) -> Dict:
- """Scan and return {'fingerprint', 'key_type', 'known_hosts'} (all keys)."""
- keys = cls._keyscan(host, port)
- return {
- 'fingerprint': cls.fingerprint_of(keys[0]['key']),
- 'key_type': keys[0]['type'],
- 'known_hosts': '\n'.join(k['line'] for k in keys) + '\n',
- }
-
- @classmethod
- def assert_pinned(cls, host: str, port: int, expected_fingerprint: str) -> Dict:
- """Re-scan the host and require the pinned fingerprint.
-
- The pin is satisfied if ANY of the host's current keys matches (a box
- legitimately offers several algorithms; what matters is that the key
- the operator confirmed is still presented). Returns
- {'fingerprint','key_type','known_hosts'} built from this fresh scan."""
- keys = cls._keyscan(host, port)
- fps = [cls.fingerprint_of(k['key']) for k in keys]
- if expected_fingerprint not in fps:
- raise WpSshImportError(
- 'Host key mismatch: the server no longer presents the pinned '
- f'fingerprint {expected_fingerprint}. Refusing to connect.')
- return {
- 'fingerprint': fps[0],
- 'key_type': keys[0]['type'],
- 'known_hosts': '\n'.join(k['line'] for k in keys) + '\n',
- }
-
- # ------------------------------------------------------------------ #
- # SSH exec
- # ------------------------------------------------------------------ #
-
- @classmethod
- def _ssh_exec(cls, conn: Dict, known_hosts: str, remote_cmd: str,
- input_bytes: bytes = None, timeout: int = None,
- stdout_path: str = None) -> Dict:
- """Run ``remote_cmd`` on the pinned host. All SSH goes through here."""
- tmpdir = tempfile.mkdtemp(prefix='wpsshimp_')
- try:
- kh_path = os.path.join(tmpdir, 'known_hosts')
- with open(kh_path, 'w') as fh:
- fh.write(known_hosts)
- auth = conn.get('auth') or {}
- cmd = ['ssh',
- '-p', str(conn['port']),
- '-o', 'StrictHostKeyChecking=yes',
- '-o', f'UserKnownHostsFile={kh_path}',
- '-o', f'ConnectTimeout={cls.CONNECT_TIMEOUT}',
- '-o', 'NumberOfPasswordPrompts=1']
- env = None
- key_path = None
- if auth.get('private_key'):
- key_path = os.path.join(tmpdir, 'id_key')
- with open(key_path, 'w') as fh:
- fh.write(auth['private_key'].rstrip() + '\n')
- if os.name != 'nt':
- os.chmod(key_path, 0o600)
- cmd += ['-o', 'BatchMode=yes', '-o', 'IdentitiesOnly=yes',
- '-i', key_path]
- elif auth.get('password'):
- if not shutil.which('sshpass'):
- raise WpSshImportError(
- 'Password authentication needs the "sshpass" package on '
- 'the panel host — install it, or use an SSH private key.')
- env = {'SSHPASS': auth['password']}
- cmd = ['sshpass', '-e'] + cmd + ['-o', 'PubkeyAuthentication=no']
- cmd += ['--', f"{conn['username']}@{conn['host']}", remote_cmd]
- return cls._run(cmd, input_bytes=input_bytes,
- timeout=timeout or cls.EXEC_TIMEOUT,
- env=env, stdout_path=stdout_path)
- finally:
- shutil.rmtree(tmpdir, ignore_errors=True)
-
- # ------------------------------------------------------------------ #
- # wp-config parsing
- # ------------------------------------------------------------------ #
-
- _DEFINE_RE = r"define\s*\(\s*['\"]{name}['\"]\s*,\s*['\"](?P<val>[^'\"]*)['\"]\s*\)"
-
- @classmethod
- def parse_wp_config(cls, text: str) -> Dict:
- """Extract DB facts + table prefix from wp-config.php source."""
- out = {}
- for name, key in (('DB_NAME', 'db_name'), ('DB_USER', 'db_user'),
- ('DB_PASSWORD', 'db_password'), ('DB_HOST', 'db_host'),
- ('WP_HOME', 'wp_home'), ('WP_SITEURL', 'wp_siteurl')):
- m = re.search(cls._DEFINE_RE.format(name=name), text or '')
- if m:
- out[key] = m.group('val')
- m = re.search(r"\$table_prefix\s*=\s*['\"]([^'\"]+)['\"]", text or '')
- out['table_prefix'] = m.group(1) if m else 'wp_'
- return out
-
- # ------------------------------------------------------------------ #
- # Probe
- # ------------------------------------------------------------------ #
-
- @classmethod
- def probe(cls, host: str, port: int, username: str, auth: Dict,
- wp_path: str) -> Dict:
- """Connect, capture the host-key fingerprint and read site facts.
-
- Returns facts only — the remote DB password is intentionally NOT
- included (the import job re-reads wp-config itself)."""
- conn = cls._validate_conn({'host': host, 'port': port,
- 'username': username, 'auth': auth})
- wp_path = cls._clean_remote_path(wp_path)
- scan = cls.scan_fingerprint(conn['host'], conn['port'])
- kh = scan['known_hosts']
- q = cls._shq(wp_path)
-
- cfg_res = cls._ssh_exec(conn, kh, f'cat {q}/wp-config.php')
- if cfg_res['code'] != 0:
- err = (cfg_res['stderr'] or b'').decode('utf-8', 'replace').strip()
- raise WpSshImportError(
- f'Could not read {wp_path}/wp-config.php over SSH'
- + (f': {err.splitlines()[-1]}' if err else ''))
- cfg = cls.parse_wp_config(cfg_res['stdout'].decode('utf-8', 'replace'))
- if not cfg.get('db_name'):
- raise WpSshImportError('wp-config.php found but DB_NAME could not be parsed')
-
- # wp-cli availability + version + siteurl (fallbacks: version.php / config).
- wp_cli = cls._ssh_exec(conn, kh, 'command -v wp >/dev/null 2>&1 && echo yes || echo no')
- has_wp_cli = b'yes' in (wp_cli.get('stdout') or b'')
-
- wp_version = None
- site_url = cfg.get('wp_home') or cfg.get('wp_siteurl')
- if has_wp_cli:
- r = cls._ssh_exec(conn, kh, f'wp core version --path={q} 2>/dev/null')
- if r['code'] == 0:
- wp_version = r['stdout'].decode('utf-8', 'replace').strip() or None
- r = cls._ssh_exec(conn, kh, f'wp option get siteurl --path={q} 2>/dev/null')
- if r['code'] == 0:
- site_url = r['stdout'].decode('utf-8', 'replace').strip() or site_url
- if not wp_version:
- r = cls._ssh_exec(conn, kh,
- f"grep -oE \"wp_version = '[^']+'\" {q}/wp-includes/version.php 2>/dev/null")
- m = re.search(r"wp_version = '([^']+)'",
- (r.get('stdout') or b'').decode('utf-8', 'replace'))
- if m:
- wp_version = m.group(1)
-
- size_kb = None
- r = cls._ssh_exec(conn, kh, f'du -sk {q} 2>/dev/null')
- m = re.match(r'^(\d+)', (r.get('stdout') or b'').decode('utf-8', 'replace').strip())
- if m:
- size_kb = int(m.group(1))
-
- return {
- 'host_key_fingerprint': scan['fingerprint'],
- 'host_key_type': scan['key_type'],
- 'wp_version': wp_version,
- 'site_url': site_url,
- 'db_name': cfg['db_name'],
- 'db_user': cfg.get('db_user'),
- 'db_host': cfg.get('db_host') or 'localhost',
- 'table_prefix': cfg.get('table_prefix', 'wp_'),
- 'docroot_size_kb': size_kb,
- 'has_wp_cli': has_wp_cli,
- }
-
- # ------------------------------------------------------------------ #
- # Safe tar extraction
- # ------------------------------------------------------------------ #
-
- @staticmethod
- def safe_extract_tar(tar_path: str, dest: str) -> Dict:
- """Extract a tarball rejecting traversal, links out of dest, devices."""
- dest_real = os.path.realpath(dest)
- try:
- with tarfile.open(tar_path, 'r:*') as tf:
- for member in tf:
- name = member.name
- if name.startswith(('/', '\\')) or os.path.isabs(name) \
- or '..' in name.replace('\\', '/').split('/'):
- return {'success': False,
- 'error': f'Unsafe path in archive: {name}'}
- target = os.path.realpath(os.path.join(dest_real, name))
- if target != dest_real and not target.startswith(dest_real + os.sep):
- return {'success': False,
- 'error': f'Unsafe path in archive: {name}'}
- if member.isdev():
- continue # never extract device/fifo nodes
- if member.issym() or member.islnk():
- link = member.linkname
- base = os.path.dirname(os.path.join(dest_real, name))
- link_target = os.path.realpath(
- link if os.path.isabs(link) else os.path.join(base, link))
- if not link_target.startswith(dest_real):
- continue # drop links escaping the destination
- tf.extract(member, dest_real)
- return {'success': True}
- except (tarfile.TarError, EOFError, OSError) as e:
- return {'success': False, 'error': f'Not a valid tar archive: {e}'}
-
- # ------------------------------------------------------------------ #
- # Import job
- # ------------------------------------------------------------------ #
-
- @classmethod
- def enqueue_import(cls, connection: Dict, fingerprint: str, target: Dict,
- options: Dict, user_id: int):
- """Validate inputs and enqueue the import job. Returns the Job row."""
- from app.jobs.service import JobService
- conn = cls._validate_conn(connection or {})
- if not fingerprint:
- raise WpSshImportError('The probed host_key_fingerprint is required '
- '(probe first, then confirm the host key)')
- target = target or {}
- if not (target.get('site_name') or '').strip():
- raise WpSshImportError('target.site_name is required')
- payload = {
- 'connection': conn,
- 'fingerprint': fingerprint,
- 'target': {
- 'site_name': target['site_name'].strip(),
- 'admin_email': (target.get('admin_email') or '').strip(),
- },
- 'options': {
- 'wp_path': cls._clean_remote_path((options or {}).get('wp_path')),
- 'old_url': ((options or {}).get('old_url') or '').strip() or None,
- },
- 'user_id': user_id,
- }
- return JobService.enqueue(JOB_KIND, payload=payload, max_attempts=1,
- owner_type='wordpress_ssh_import', owner_id=user_id)
-
- @classmethod
- def run_import(cls, job) -> Dict:
- """Job handler for ``wordpress.ssh_import.run``. Steps are appended to
- the job result as it goes so the UI can poll progress."""
- payload = job.get_payload() or {}
- state = {'steps': []}
- workdir = tempfile.mkdtemp(prefix='wpsshimport_')
- try:
- result = cls._run_import_steps(job, payload, state, workdir)
- state.update(result)
- state['success'] = True
- return state
- except WpSshImportError as e:
- cls._step(job, state, 'failed', str(e))
- state['success'] = False
- state['error'] = str(e)
- raise
- finally:
- shutil.rmtree(workdir, ignore_errors=True)
- cls._scrub_job_secrets(job)
-
- @classmethod
- def _run_import_steps(cls, job, payload: Dict, state: Dict, workdir: str) -> Dict:
- conn = cls._validate_conn(payload.get('connection') or {})
- fingerprint = payload.get('fingerprint')
- target = payload.get('target') or {}
- options = payload.get('options') or {}
- wp_path = cls._clean_remote_path(options.get('wp_path'))
- user_id = payload.get('user_id')
- q = cls._shq(wp_path)
-
- # 1) Host-key pin check.
- cls._step(job, state, 'pin_check', f'Verifying pinned host key for {conn["host"]}')
- scan = cls.assert_pinned(conn['host'], conn['port'], fingerprint)
- kh = scan['known_hosts']
-
- # 2) Read remote facts (creds never leave this process).
- cls._step(job, state, 'read_config', 'Reading remote wp-config.php')
- cfg_res = cls._ssh_exec(conn, kh, f'cat {q}/wp-config.php')
- if cfg_res['code'] != 0:
- raise WpSshImportError('Could not read wp-config.php on the source host')
- cfg = cls.parse_wp_config(cfg_res['stdout'].decode('utf-8', 'replace'))
- if not cfg.get('db_name'):
- raise WpSshImportError('DB_NAME could not be parsed from wp-config.php')
- has_wp_cli = b'yes' in (cls._ssh_exec(
- conn, kh, 'command -v wp >/dev/null 2>&1 && echo yes || echo no'
- ).get('stdout') or b'')
-
- old_url = options.get('old_url')
- if not old_url and has_wp_cli:
- r = cls._ssh_exec(conn, kh, f'wp option get siteurl --path={q} 2>/dev/null')
- if r['code'] == 0:
- old_url = r['stdout'].decode('utf-8', 'replace').strip() or None
- if not old_url:
- old_url = cfg.get('wp_home') or cfg.get('wp_siteurl')
- if not old_url:
- raise WpSshImportError(
- 'Could not determine the source site URL — pass options.old_url')
-
- # 3) Pull the docroot as a tar stream (no rsync dependency).
- cls._step(job, state, 'pull_docroot', 'Pulling the docroot over SSH (tar stream)')
- tar_path = os.path.join(workdir, 'docroot.tar.gz')
- pull = cls._ssh_exec(conn, kh, f'tar czf - -C {q} .',
- timeout=cls.TRANSFER_TIMEOUT, stdout_path=tar_path)
- if pull['code'] != 0 or not os.path.getsize(tar_path):
- err = (pull.get('stderr') or b'').decode('utf-8', 'replace').strip()
- raise WpSshImportError('Docroot pull failed'
- + (f': {err.splitlines()[-1]}' if err else ''))
- extract_dir = os.path.join(workdir, 'docroot')
- os.makedirs(extract_dir, exist_ok=True)
- ext = cls.safe_extract_tar(tar_path, extract_dir)
- if not ext.get('success'):
- raise WpSshImportError(ext.get('error') or 'Docroot extraction failed')
-
- # Repack wp-content only: core files come from the managed image, and
- # the source wp-config must never override the managed stack's.
- wp_content_src = os.path.join(extract_dir, 'wp-content')
- wp_content_zip = None
- if os.path.isdir(wp_content_src):
- wp_content_zip = os.path.join(workdir, 'wp-content.zip')
- cls._zip_dir(wp_content_src, wp_content_zip, arc_root='wp-content')
- else:
- cls._step(job, state, 'pull_docroot',
- 'No wp-content directory found in the pulled docroot; '
- 'importing database only')
-
- # 4) Dump the DB through the tunnel (no remote temp files, no creds on argv).
- cls._step(job, state, 'dump_db', 'Dumping the source database over SSH')
- sql_path = os.path.join(workdir, 'source.sql')
- if has_wp_cli:
- dump = cls._ssh_exec(conn, kh, f'wp db export - --path={q} --single-transaction',
- timeout=cls.TRANSFER_TIMEOUT, stdout_path=sql_path)
- else:
- db_host = cfg.get('db_host') or 'localhost'
- host_part = db_host.split(':')[0] or 'localhost'
- remote = ('read -r MYSQL_PWD; export MYSQL_PWD; '
- f'exec mysqldump --single-transaction -h {cls._shq(host_part)} '
- f'-u {cls._shq(cfg.get("db_user") or "root")} '
- f'{cls._shq(cfg["db_name"])}')
- dump = cls._ssh_exec(conn, kh, remote,
- input_bytes=(cfg.get('db_password') or '').encode() + b'\n',
- timeout=cls.TRANSFER_TIMEOUT, stdout_path=sql_path)
- if dump['code'] != 0 or not os.path.getsize(sql_path):
- err = (dump.get('stderr') or b'').decode('utf-8', 'replace').strip()
- raise WpSshImportError('Database dump failed'
- + (f': {err.splitlines()[-1]}' if err else ''))
-
- # 5-7) Rebuild as a managed site: create stack, import DB, search-replace
- # old URL -> new URL, copy wp-content, flush caches — all via the
- # extension's existing import path.
- cls._step(job, state, 'rebuild_site',
- f'Creating managed site "{target.get("site_name")}" and importing')
- site_result = cls._import_into_panel(
- name=target.get('site_name'),
- admin_email=target.get('admin_email') or '',
- user_id=user_id,
- sql_path=sql_path,
- old_url=old_url,
- wp_content_zip_path=wp_content_zip,
- )
- if not site_result.get('success'):
- raise WpSshImportError(site_result.get('error') or 'Site rebuild failed')
-
- # 8) Validate: fetch the homepage via the local port (best-effort).
- cls._step(job, state, 'validate', 'Validating the imported site')
- http_port = site_result.get('http_port')
- homepage_ok = cls._check_homepage(http_port) if http_port else None
-
- cls._step(job, state, 'done', 'Import finished')
- out = {
- 'site': site_result.get('site'),
- 'http_port': http_port,
- 'old_url': old_url,
- 'new_url': site_result.get('new_url'),
- 'wp_content_imported': bool(site_result.get('wp_content_imported')),
- 'homepage_ok': homepage_ok,
- }
- if site_result.get('warning'):
- out['warning'] = site_result['warning']
- return out
-
- # ------------------------------------------------------------------ #
- # Helpers
- # ------------------------------------------------------------------ #
-
- @classmethod
- def _import_into_panel(cls, **kwargs) -> Dict:
- """Indirection over WordPressService.import_site (stubbed in tests)."""
- from .wordpress_service import WordPressService
- return WordPressService.import_site(**kwargs)
-
- @classmethod
- def _check_homepage(cls, http_port) -> Optional[bool]:
- import urllib.request
- try:
- req = urllib.request.Request(f'http://localhost:{http_port}/',
- method='GET')
- with urllib.request.urlopen(req, timeout=15) as resp:
- return 200 <= resp.status < 500
- except Exception:
- return False
-
- @staticmethod
- def _zip_dir(src_dir: str, zip_path: str, arc_root: str = ''):
- with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
- for root, _dirs, files in os.walk(src_dir):
- for fname in files:
- full = os.path.join(root, fname)
- rel = os.path.relpath(full, src_dir)
- arc = os.path.join(arc_root, rel) if arc_root else rel
- zf.write(full, arc.replace(os.sep, '/'))
-
- @staticmethod
- def _shq(value: str) -> str:
- """Single-quote a value for the remote POSIX shell."""
- return "'" + str(value or '').replace("'", "'\\''") + "'"
-
- @staticmethod
- def _clean_remote_path(path: str) -> str:
- path = (path or '').strip()
- if not path:
- raise WpSshImportError('The remote WordPress path (wp_path) is required')
- if not path.startswith('/'):
- raise WpSshImportError('wp_path must be an absolute path')
- if '\n' in path or '\r' in path:
- raise WpSshImportError('Invalid wp_path')
- return path.rstrip('/') or '/'
-
- @classmethod
- def _step(cls, job, state: Dict, name: str, message: str):
- """Append a progress step to the job result and persist (best-effort)."""
- from datetime import datetime
- entry = {'step': name, 'message': message,
- 'at': datetime.utcnow().isoformat() + 'Z'}
- state['steps'].append(entry)
- logger.info('wp ssh-import job %s: [%s] %s',
- getattr(job, 'id', '?'), name, message)
- try:
- from app import db
- job.set_result(state)
- db.session.commit()
- except Exception: # never let progress bookkeeping kill the import
- pass
-
- @classmethod
- def _scrub_job_secrets(cls, job):
- """Drop credentials from the persisted job payload once the job ends."""
- try:
- from app import db
- payload = job.get_payload() or {}
- conn = payload.get('connection') or {}
- if conn.get('auth'):
- conn['auth'] = {'scrubbed': True}
- payload['connection'] = conn
- job.set_payload(payload)
- db.session.commit()
- except Exception:
- pass
-
- # ------------------------------------------------------------------ #
- # Registration
- # ------------------------------------------------------------------ #
-
- @classmethod
- def register_jobs(cls):
- from app.jobs import registry
- registry.register(JOB_KIND, cls.run_import, replace=True)
-
-
-def run_wp_ssh_import_job(job):
- """Module-level handler target for the manifest ``jobs`` declaration."""
- return WpSshImportService.run_import(job)
-
-
-def register_jobs():
- WpSshImportService.register_jobs()
diff --git a/builtin-extensions/serverkit-wordpress/backend/wp_update_service.py b/builtin-extensions/serverkit-wordpress/backend/wp_update_service.py
deleted file mode 100644
index c7a4e601..00000000
--- a/builtin-extensions/serverkit-wordpress/backend/wp_update_service.py
+++ /dev/null
@@ -1,251 +0,0 @@
-"""Safe WordPress update manager (#29).
-
-Runs updates with a safety net, all via the Docker-aware WP-CLI bridge:
- 1. record the current core/plugin/theme versions
- 2. snapshot the DB (wp db export to a container-local /tmp path)
- 3. apply the requested updates (honouring an exclusion list)
- 4. health-check the site (EnvironmentHealthService)
- 5. if the update broke a previously-healthy site, AUTO-ROLLBACK: version-pin
- each updated component back (wp <type> update --version=<old> --force) and
- re-import the DB snapshot, then re-check health
- 6. persist a WordPressUpdateRun record (the report)
-
-The run executes in a background thread (updates are slow) so the single worker
-never blocks; the UI polls get_runs() for status.
-
-Deferred: staging-first promotion (update a staging env via the promote pipeline,
-validate, then promote to production) — needs a staging env + the full env
-pipeline orchestration; revisit on top of #15/#18.
-"""
-
-import json
-import logging
-import threading
-from datetime import datetime, timedelta
-
-logger = logging.getLogger(__name__)
-
-
-class WpUpdateService:
- STALE_RUN_MINUTES = 30 # a 'running' row older than this is treated as crashed
- DB_TIMEOUT = 600 # generous wall-clock for db export/import (never truncate a restore)
- MAX_CONCURRENT = 2 # bound simultaneous heavy updates (scheduler stampede protection)
- _run_semaphore = threading.Semaphore(MAX_CONCURRENT)
-
- # ---------- public API ----------
-
- @classmethod
- def get_runs(cls, site, limit=20):
- from app.models.wordpress_site import WordPressUpdateRun
- rows = (WordPressUpdateRun.query.filter_by(site_id=site.id)
- .order_by(WordPressUpdateRun.started_at.desc()).limit(limit).all())
- running = any(r.status == 'running' and not cls._is_stale(r) for r in rows)
- return {'success': True, 'runs': [r.to_dict() for r in rows], 'running': running}
-
- @classmethod
- def start_update(cls, site, targets=None, exclude=None, trigger='manual'):
- from flask import current_app
- from app import db
- from app.models.wordpress_site import WordPressUpdateRun
- existing = (WordPressUpdateRun.query.filter_by(site_id=site.id, status='running')
- .order_by(WordPressUpdateRun.started_at.desc()).first())
- if existing and not cls._is_stale(existing):
- return {'success': True, 'status': 'running', 'run_id': existing.id}
-
- targets = targets or {'core': True, 'plugins': True, 'themes': True}
- exclude = exclude or []
- run = WordPressUpdateRun(
- site_id=site.id, status='running', trigger=trigger,
- details=json.dumps({'targets': targets, 'excluded': exclude}),
- )
- db.session.add(run)
- db.session.commit()
- run_id = run.id
- app = current_app._get_current_object()
- path = site.application.root_path if site.application else None
- threading.Thread(
- target=cls._run, args=(app, site.id, run_id, path, targets, exclude),
- daemon=True, name=f'wp-update-{site.id}'
- ).start()
- return {'success': True, 'status': 'running', 'run_id': run_id}
-
- @staticmethod
- def _is_stale(run):
- if not run.started_at:
- return False
- return (datetime.utcnow() - run.started_at) > timedelta(minutes=WpUpdateService.STALE_RUN_MINUTES)
-
- # ---------- worker ----------
-
- @classmethod
- def _run(cls, app, site_id, run_id, path, targets, exclude):
- with app.app_context():
- from app import db
- from app.models.wordpress_site import WordPressSite, WordPressUpdateRun
- from .wordpress_service import WordPressService
- run = WordPressUpdateRun.query.get(run_id)
- details = json.loads(run.details) if run and run.details else {}
- snapshot = f'/tmp/wp-preupdate-{run_id}.sql'
- keep_snapshot = False
- # Bound concurrency so a shared 3am cron doesn't stampede the host.
- with cls._run_semaphore:
- try:
- if not path:
- raise RuntimeError('Site has no root path')
- site = WordPressSite.query.get(site_id)
- port = site.application.port if site and site.application else None
-
- health_before = cls._site_status(path, port)
- pre = cls._versions(path)
-
- # "Safe" requires a DB net — abort BEFORE touching anything if the
- # snapshot can't be taken (large DBs use a generous timeout).
- export = WordPressService.wp_cli(path, ['db', 'export', snapshot], timeout=cls.DB_TIMEOUT)
- if not export.get('success'):
- raise RuntimeError('Could not snapshot the database; aborting to stay safe. '
- + (export.get('error') or ''))
-
- cls._apply_updates(path, targets, exclude)
-
- post = cls._versions(path)
- updated = cls._diff(pre, post)
- health_after = cls._site_status(path, port)
-
- # Roll back if the update regressed a previously-healthy site
- # (degraded counts: a 5xx after an update is a regression).
- rolled_back = False
- if health_before == 'healthy' and health_after in ('unhealthy', 'degraded') and updated:
- cls._rollback(path, updated, snapshot)
- rolled_back = True
- health_after = cls._site_status(path, port)
-
- warning = None
- if health_before != 'healthy':
- warning = 'Baseline health could not be confirmed healthy, so auto-rollback was not attempted.'
- keep_snapshot = True
- if health_after != 'healthy':
- warning = ((warning + ' ') if warning else '') + \
- 'Site is not healthy after the update; the pre-update DB snapshot was kept for manual restore.'
- keep_snapshot = True
-
- details.update({
- 'updated': updated,
- 'health_before': health_before,
- 'health_after': health_after,
- 'rolled_back': rolled_back,
- 'warning': warning,
- })
- run.status = 'rolled_back' if rolled_back else 'completed'
- run.details = json.dumps(details)
- run.finished_at = datetime.utcnow()
- db.session.commit()
- try:
- from app.services.event_service import EventService
- evt = 'wordpress.update_rolled_back' if rolled_back else 'wordpress.updated'
- EventService.emit_wp(evt, site, updated=updated, health_after=health_after)
- except Exception:
- pass
- except Exception as e:
- logger.error(f'Safe update failed for site {site_id}: {e}')
- keep_snapshot = True # leave the snapshot for recovery
- try:
- if run is not None:
- run.status = 'failed'
- run.error = str(e)
- run.details = json.dumps(details)
- run.finished_at = datetime.utcnow()
- db.session.commit()
- except Exception:
- db.session.rollback()
- finally:
- # Only drop the snapshot when the site ended verified-healthy.
- if path and not keep_snapshot:
- try:
- WordPressService.wp_cli(path, ['eval', f"@unlink('{snapshot}');"])
- except Exception:
- pass
-
- # ---------- steps ----------
-
- @staticmethod
- def _versions(path):
- from .wordpress_service import WordPressService
- core = WordPressService.wp_cli(path, ['core', 'version'])
- return {
- 'core': (core.get('output') or '').strip() if core.get('success') else None,
- 'plugins': {p.get('name'): p.get('version')
- for p in (WordPressService.get_plugins(path) or []) if p.get('name')},
- 'themes': {t.get('name'): t.get('version')
- for t in (WordPressService.get_themes(path) or []) if t.get('name')},
- }
-
- @staticmethod
- def _site_status(path, port):
- """A quiet, SIDE-EFFECT-FREE liveness check (does NOT write health_status
- or fire #27 transition alerts, unlike EnvironmentHealthService.check_health
- — so an auto-rollback never pages on-call with spurious down/up). `wp eval`
- loads WP incl. plugins so a PHP fatal is caught; the HTTP probe catches a
- 5xx/connection regression. Returns healthy | degraded | unhealthy | unknown."""
- from .wordpress_service import WordPressService
- from app.services.environment_health_service import EnvironmentHealthService
- wp_ok = WordPressService.wp_cli(path, ['eval', "echo 'OK';"]).get('success', False)
- http_status = 'unknown'
- if port:
- http_status = (EnvironmentHealthService._check_wordpress_http(port) or {}).get('status', 'unknown')
- if not wp_ok or http_status == 'unhealthy':
- return 'unhealthy'
- if http_status == 'degraded':
- return 'degraded'
- if wp_ok and http_status in ('healthy', 'unknown'):
- return 'healthy'
- return 'unknown'
-
- @classmethod
- def _apply_updates(cls, path, targets, exclude):
- from .wordpress_service import WordPressService
- ex = set(exclude or [])
- if targets.get('core'):
- WordPressService.update_wordpress(path)
- if targets.get('plugins'):
- avail = [p.get('name') for p in (WordPressService.get_plugins(path) or [])
- if p.get('update') == 'available' and p.get('name') and p.get('name') not in ex]
- if avail:
- WordPressService.update_plugins(path, plugins=avail)
- if targets.get('themes'):
- avail = [t.get('name') for t in (WordPressService.get_themes(path) or [])
- if t.get('update') == 'available' and t.get('name') and t.get('name') not in ex]
- if avail:
- WordPressService.update_themes(path, themes=avail)
-
- @staticmethod
- def _diff(pre, post):
- updated = []
- if pre.get('core') and post.get('core') and pre['core'] != post['core']:
- updated.append({'type': 'core', 'slug': 'wordpress', 'from': pre['core'], 'to': post['core']})
- for kind in ('plugins', 'themes'):
- for slug, newv in (post.get(kind) or {}).items():
- oldv = (pre.get(kind) or {}).get(slug)
- if oldv and newv and oldv != newv:
- updated.append({'type': kind[:-1], 'slug': slug, 'from': oldv, 'to': newv})
- return updated
-
- @classmethod
- def _rollback(cls, path, updated, snapshot):
- """Version-pin each updated component back to its pre-update version, then
- re-import the DB snapshot. --skip-plugins/--skip-themes so the downgrade
- runs even if a bad update left the site fatally broken (a loaded plugin
- would otherwise crash wp-cli). Best-effort (a component not on
- wordpress.org can't be version-downgraded; the DB snapshot is the net)."""
- from .wordpress_service import WordPressService
- skip = ['--skip-plugins', '--skip-themes']
- for u in updated:
- t, slug, old = u.get('type'), u.get('slug'), u.get('from')
- if t == 'core':
- WordPressService.wp_cli(path, ['core', 'update', f'--version={old}', '--force'] + skip)
- WordPressService.wp_cli(path, ['core', 'update-db'] + skip)
- elif t == 'plugin':
- WordPressService.wp_cli(path, ['plugin', 'update', slug, f'--version={old}', '--force'] + skip)
- elif t == 'theme':
- WordPressService.wp_cli(path, ['theme', 'update', slug, f'--version={old}', '--force'] + skip)
- if snapshot:
- WordPressService.wp_cli(path, ['db', 'import', snapshot] + skip, timeout=cls.DB_TIMEOUT)
diff --git a/builtin-extensions/serverkit-wordpress/backend/wp_vulnerability_service.py b/builtin-extensions/serverkit-wordpress/backend/wp_vulnerability_service.py
deleted file mode 100644
index d905d1f1..00000000
--- a/builtin-extensions/serverkit-wordpress/backend/wp_vulnerability_service.py
+++ /dev/null
@@ -1,318 +0,0 @@
-"""Per-site WordPress vulnerability scanning (#28).
-
-Cross-references a site's installed plugin/theme/core slug+version against the
-keyless community WPVulnerability API (https://www.wpvulnerability.net) and
-persists findings as WordPressVulnerability rows.
-
-Docker-correct: installed versions are read via the Docker-aware WP-CLI bridge
-(WordPressService.get_plugins/get_themes/get_wordpress_info). The scan runs in a
-background thread (like the Lynis scan) so the single worker never blocks on the
-WP-CLI + external-HTTP work; the UI polls get_results() for status.
-
-Feed notes (see WPVulnerability docs):
-- endpoints: /plugin/<slug>/ , /theme/<slug>/ , /core/<version>/ (trailing slash).
-- 404 is NOT used for "no known vulns": a clean slug returns HTTP 200 with
- error=0 and data.vulnerability null/empty. Never treat HTTP 200 as vulnerable.
-- plugin/theme vulns carry an `operator` version-bounds object; core vulns do not
- (querying by exact version means every returned core vuln applies).
-- numeric-ish fields come back as strings; prefer cvss3.severity (full words).
-"""
-
-import logging
-import threading
-import time
-from datetime import datetime
-from urllib.parse import quote
-
-import requests
-
-logger = logging.getLogger(__name__)
-
-API_BASE = 'https://www.wpvulnerability.net'
-USER_AGENT = 'ServerKit-VulnScan/1.0 (+https://serverkit.ai)'
-HTTP_TIMEOUT = 8
-CACHE_TTL = 3600 # 1h, matching the feed's CDN cache
-
-
-class WpVulnerabilityService:
- # Feed cache: {(kind, key): (fetched_at_epoch, data_dict|None)}
- _feed_cache = {}
- _cache_lock = threading.Lock()
-
- # Per-site scan state: {site_id: {'status': 'running'|'completed'|'error', 'error': str|None}}
- _scans = {}
- _scan_lock = threading.Lock()
-
- _SEV_ORDER = {'critical': 0, 'high': 1, 'medium': 2, 'low': 3, 'unknown': 4}
-
- # ---------- public API ----------
-
- @classmethod
- def get_results(cls, site):
- """Return persisted findings + live scan status for a site."""
- from app.models import WordPressVulnerability
- rows = WordPressVulnerability.query.filter_by(site_id=site.id).all()
- findings = [r.to_dict() for r in rows]
- findings.sort(key=lambda f: cls._SEV_ORDER.get(f.get('severity'), 9))
- summary = {'critical': 0, 'high': 0, 'medium': 0, 'low': 0, 'unknown': 0, 'total': len(findings)}
- for f in findings:
- sev = f.get('severity') if f.get('severity') in summary else 'unknown'
- summary[sev] += 1
- with cls._scan_lock:
- state = dict(cls._scans.get(site.id, {}))
- return {
- 'success': True,
- 'vulnerabilities': findings,
- 'scanned_at': site.last_vuln_scan_at.isoformat() if site.last_vuln_scan_at else None,
- 'scan_status': state.get('status', 'idle'),
- 'scan_error': state.get('error'),
- 'summary': summary,
- }
-
- @classmethod
- def start_scan(cls, site):
- """Kick off a background scan for the site; returns immediately."""
- from flask import current_app
- with cls._scan_lock:
- if cls._scans.get(site.id, {}).get('status') == 'running':
- return {'success': True, 'status': 'running', 'message': 'A scan is already running.'}
- cls._scans[site.id] = {'status': 'running', 'error': None}
- app = current_app._get_current_object()
- threading.Thread(
- target=cls._run_scan, args=(app, site.id), daemon=True, name=f'wp-vuln-{site.id}'
- ).start()
- return {'success': True, 'status': 'running'}
-
- # ---------- scan worker ----------
-
- @classmethod
- def _run_scan(cls, app, site_id):
- with app.app_context():
- from app import db
- from app.models import WordPressSite, WordPressVulnerability
- try:
- site = WordPressSite.query.get(site_id)
- if not site or not site.application:
- raise RuntimeError('Site not found')
- findings = cls._scan_site(site.application.root_path)
- if findings is None:
- raise RuntimeError('Could not read WordPress (is the site running?)')
- # Replace the site's findings with the fresh set.
- WordPressVulnerability.query.filter_by(site_id=site_id).delete(synchronize_session=False)
- for f in findings:
- db.session.add(WordPressVulnerability(site_id=site_id, **f))
- site.last_vuln_scan_at = datetime.utcnow()
- db.session.commit()
- with cls._scan_lock:
- cls._scans[site_id] = {'status': 'completed', 'error': None}
- except Exception as e:
- logger.error(f'Vulnerability scan failed for site {site_id}: {e}')
- try:
- db.session.rollback()
- except Exception:
- pass
- with cls._scan_lock:
- cls._scans[site_id] = {'status': 'error', 'error': str(e)}
-
- @classmethod
- def _scan_site(cls, path):
- """Return a list of finding-dicts, or None if the install can't be read at
- all (container down / not WordPress).
-
- Reads core/plugins/themes via the Docker-aware WP-CLI bridge directly —
- NOT get_wordpress_info, whose host-filesystem wp-config.php check fails for
- volume-backed Docker sites (the primary managed model). Core is optional;
- we only bail when WP-CLI answers nothing at all."""
- from .wordpress_service import WordPressService
- core_res = WordPressService.wp_cli(path, ['core', 'version'])
- core_version = (core_res.get('output') or '').strip() if core_res.get('success') else None
- plugins = WordPressService.get_plugins(path) or []
- themes = WordPressService.get_themes(path) or []
- if not core_version and not plugins and not themes:
- return None
- findings = []
- if core_version:
- findings += cls._check_core(core_version)
- for p in plugins:
- slug, version = p.get('name'), p.get('version')
- if slug and version:
- findings += cls._check_component('plugin', slug, version)
- for t in themes:
- slug, version = t.get('name'), t.get('version')
- if slug and version:
- findings += cls._check_component('theme', slug, version)
- return findings
-
- # ---------- feed lookups ----------
-
- @classmethod
- def _fetch(cls, kind, key):
- """GET the feed for a plugin/theme slug or core version (cached).
- Returns the parsed 'data' dict, or None on miss/error/no-data."""
- ck = (kind, key)
- now = time.time()
- with cls._cache_lock:
- cached = cls._feed_cache.get(ck)
- if cached and (now - cached[0]) < CACHE_TTL:
- return cached[1]
- data = None
- try:
- resp = requests.get(
- f'{API_BASE}/{kind}/{quote(str(key), safe="")}/',
- headers={'User-Agent': USER_AGENT, 'Accept': 'application/json'},
- timeout=HTTP_TIMEOUT,
- )
- if resp.status_code == 200:
- body = resp.json()
- if isinstance(body, dict) and body.get('error') in (0, '0'):
- data = body.get('data') or None
- except Exception as e:
- logger.debug(f'Vuln feed fetch failed ({kind}/{key}): {e}')
- data = None
- with cls._cache_lock:
- cls._feed_cache[ck] = (now, data)
- return data
-
- @classmethod
- def _check_core(cls, version):
- data = cls._fetch('core', version)
- return [cls._finding('core', '', 'WordPress core', version, v, fixed_in=None)
- for v in ((data or {}).get('vulnerability') or [])]
-
- @classmethod
- def _check_component(cls, source, slug, version):
- data = cls._fetch(source, slug)
- if not data:
- return []
- name = data.get('name') or slug
- out = []
- for v in (data.get('vulnerability') or []):
- op = v.get('operator') or {}
- if cls._version_in_range(version, op):
- out.append(cls._finding(source, slug, name, version, v, fixed_in=cls._fixed_in(op)))
- return out
-
- # ---------- finding builder ----------
-
- # CVSS v2 short severity codes -> our scale.
- _CVSS_SHORT = {'c': 'critical', 'h': 'high', 'm': 'medium', 'l': 'low'}
-
- @classmethod
- def _severity_from_impact(cls, impact):
- """Best-effort (severity, score). Prefer cvss3.severity (full words), fall
- back to cvss.severity (short codes) or a numeric score, else 'unknown'.
- Guards against impact being null or a list (the feed is heterogeneous)."""
- if not isinstance(impact, dict):
- return 'unknown', None
- cvss3 = impact.get('cvss3') or {}
- sev = cvss3.get('severity')
- if sev in cls._SEV_ORDER:
- return sev, cvss3.get('score')
- cvss = impact.get('cvss') or {}
- mapped = cls._CVSS_SHORT.get(str(cvss.get('severity') or '').lower())
- if mapped in cls._SEV_ORDER:
- return mapped, cvss.get('score') or cvss3.get('score')
- score = cvss3.get('score') or cvss.get('score')
- try:
- s = float(score)
- if s >= 9.0:
- return 'critical', score
- if s >= 7.0:
- return 'high', score
- if s >= 4.0:
- return 'medium', score
- if s > 0:
- return 'low', score
- except (TypeError, ValueError):
- pass
- return 'unknown', score
-
- @classmethod
- def _finding(cls, source, slug, name, version, vuln, fixed_in):
- severity, score = cls._severity_from_impact(vuln.get('impact'))
-
- # Prefer a real CVE id + its reference; else fall back to the feed uuid.
- advisory_id = vuln.get('uuid')
- ref_url = None
- for src in (vuln.get('source') or []):
- sid = src.get('id') or ''
- if isinstance(sid, str) and sid.upper().startswith('CVE-'):
- advisory_id = sid
- ref_url = src.get('link') or ref_url
- break
- ref_url = ref_url or src.get('link')
-
- # Only keep http(s) references — the feed is third-party and the URL is
- # rendered as an href, so block javascript:/data: schemes.
- if ref_url and not str(ref_url).lower().startswith(('http://', 'https://')):
- ref_url = None
-
- return {
- 'source': source,
- 'slug': slug,
- 'name': (name or slug or '')[:255],
- 'installed_version': str(version)[:50],
- 'advisory_id': str(advisory_id)[:100] if advisory_id else None,
- 'title': vuln.get('name'),
- 'severity': severity,
- 'cvss_score': str(score)[:10] if score not in (None, '') else None,
- 'fixed_in': str(fixed_in)[:50] if fixed_in else None,
- 'reference_url': str(ref_url)[:500] if ref_url else None,
- }
-
- @staticmethod
- def _fixed_in(op):
- # With max_operator 'lt' the fix landed exactly at max_version.
- if op.get('max_operator') == 'lt' and op.get('max_version'):
- return op.get('max_version')
- return None
-
- # ---------- version matching ----------
-
- @staticmethod
- def _vtuple(v):
- parts = []
- for chunk in str(v).split('.'):
- num = ''
- for ch in chunk:
- if ch.isdigit():
- num += ch
- else:
- break
- parts.append(int(num) if num else 0)
- return tuple(parts)
-
- @classmethod
- def _vcmp(cls, a, b):
- ta, tb = cls._vtuple(a), cls._vtuple(b)
- n = max(len(ta), len(tb))
- ta += (0,) * (n - len(ta))
- tb += (0,) * (n - len(tb))
- return (ta > tb) - (ta < tb)
-
- @classmethod
- def _version_in_range(cls, installed, op):
- """True if the installed version satisfies the operator bounds (vulnerable).
- A null bound is unbounded on that side; an empty operator is treated as
- not-determinable (skip) to avoid false positives across all versions."""
- if not op:
- return False
- minv, mino = op.get('min_version'), op.get('min_operator')
- maxv, maxo = op.get('max_version'), op.get('max_operator')
- if minv:
- if mino not in ('ge', 'gt'):
- return False # unrecognized bound — skip rather than over-flag
- c = cls._vcmp(installed, minv)
- if mino == 'ge' and c < 0:
- return False
- if mino == 'gt' and c <= 0:
- return False
- if maxv:
- if maxo not in ('lt', 'le'):
- return False
- c = cls._vcmp(installed, maxv)
- if maxo == 'lt' and c >= 0:
- return False
- if maxo == 'le' and c > 0:
- return False
- return True
diff --git a/builtin-extensions/serverkit-wordpress/frontend/WordPressSshImport.jsx b/builtin-extensions/serverkit-wordpress/frontend/WordPressSshImport.jsx
deleted file mode 100644
index e5ad2418..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/WordPressSshImport.jsx
+++ /dev/null
@@ -1,299 +0,0 @@
-// Import a live WordPress site over SSH (Panel Improvements #3).
-//
-// Three-step surface rendered inside the WordPress tab group:
-// 1. Connection — host/port/user + password-or-key + remote WP path.
-// 2. Probe — the backend captures the SSH host-key fingerprint and reads
-// site facts (wp-config, version, size). The operator explicitly trusts
-// the fingerprint before anything else touches the box.
-// 3. Import — enqueues the pull-import job and polls its step log.
-//
-// After sync this file lives at frontend/src/plugins/serverkit-wordpress/, so
-// shared pieces come from the serverkit-sdk surface like other extensions.
-import { useEffect, useRef, useState } from 'react';
-import { Link } from 'react-router-dom';
-import { api, Spinner, useToast, Button, Input, Label } from 'serverkit-sdk';
-
-const POLL_MS = 2500;
-
-export default function WordPressSshImport() {
- const toast = useToast();
- const [conn, setConn] = useState({
- host: '', port: '22', username: 'root',
- authMethod: 'key', password: '', privateKey: '',
- wpPath: '/var/www/html',
- });
- const [probing, setProbing] = useState(false);
- const [probe, setProbe] = useState(null); // probe result (incl. fingerprint)
- const [trusted, setTrusted] = useState(false); // operator confirmed the host key
- const [target, setTarget] = useState({ siteName: '', adminEmail: '', oldUrl: '' });
- const [starting, setStarting] = useState(false);
- const [job, setJob] = useState(null); // { id, status, steps, result, error }
- const pollRef = useRef(null);
-
- useEffect(() => () => clearInterval(pollRef.current), []);
-
- const authPayload = () => (conn.authMethod === 'password'
- ? { password: conn.password }
- : { private_key: conn.privateKey });
-
- const handleProbe = async () => {
- setProbing(true);
- setProbe(null);
- setTrusted(false);
- try {
- const result = await api.request('/wordpress/ssh-import/probe', {
- method: 'POST',
- body: {
- host: conn.host.trim(),
- port: parseInt(conn.port, 10) || 22,
- username: conn.username.trim(),
- auth: authPayload(),
- wp_path: conn.wpPath.trim(),
- },
- });
- setProbe(result);
- setTarget(t => ({ ...t, oldUrl: t.oldUrl || result.site_url || '' }));
- } catch (error) {
- toast.error(error.message || 'Probe failed');
- } finally {
- setProbing(false);
- }
- };
-
- const pollJob = async (jobId) => {
- try {
- const status = await api.request(`/wordpress/ssh-import/${jobId}`);
- setJob(status);
- if (['completed', 'failed', 'dead'].includes(status.status)) {
- clearInterval(pollRef.current);
- pollRef.current = null;
- if (status.status === 'completed') {
- toast.success('WordPress site imported successfully');
- } else {
- toast.error(status.error || 'Import failed — see the step log');
- }
- }
- } catch {
- /* transient poll error — keep polling */
- }
- };
-
- const handleStart = async () => {
- if (!trusted) { toast.error('Confirm the host-key fingerprint first'); return; }
- if (!target.siteName.trim()) { toast.error('New site name is required'); return; }
- setStarting(true);
- try {
- const res = await api.request('/wordpress/ssh-import', {
- method: 'POST',
- body: {
- connection: {
- host: conn.host.trim(),
- port: parseInt(conn.port, 10) || 22,
- username: conn.username.trim(),
- auth: authPayload(),
- },
- fingerprint: probe.host_key_fingerprint,
- target: {
- site_name: target.siteName.trim(),
- admin_email: target.adminEmail.trim(),
- },
- options: {
- wp_path: conn.wpPath.trim(),
- old_url: target.oldUrl.trim() || undefined,
- },
- },
- });
- setJob({ id: res.job_id, status: 'pending', steps: [] });
- pollRef.current = setInterval(() => pollJob(res.job_id), POLL_MS);
- pollJob(res.job_id);
- } catch (error) {
- toast.error(error.message || 'Failed to start the import');
- } finally {
- setStarting(false);
- }
- };
-
- const running = job && !['completed', 'failed', 'dead'].includes(job.status);
- const canProbe = conn.host.trim() && conn.username.trim() && conn.wpPath.trim()
- && (conn.authMethod === 'password' ? conn.password : conn.privateKey);
- const facts = probe && [
- ['WordPress version', probe.wp_version || 'unknown'],
- ['Site URL', probe.site_url || 'unknown'],
- ['Database', probe.db_name],
- ['Table prefix', probe.table_prefix],
- ['Docroot size', probe.docroot_size_kb != null
- ? `${(probe.docroot_size_kb / 1024).toFixed(1)} MB` : 'unknown'],
- ['WP-CLI on source', probe.has_wp_cli ? 'yes' : 'no (fallbacks used)'],
- ];
-
- return (
- <div className="sk-tabgroup__inner wp-ssh-import">
- <div className="page-section">
- <h2 className="text-lg font-semibold">Import a live site over SSH</h2>
- <p className="text-sm text-muted-foreground">
- Point at any WordPress install you can reach over SSH. The panel pulls the
- files and database through the tunnel and rebuilds it as a managed site —
- nothing is installed on the source server.
- </p>
- </div>
-
- {/* Step 1 — connection */}
- <div className="card p-4 mb-4">
- <h3 className="font-medium mb-3">1. Source server</h3>
- <div className="grid grid-cols-2 gap-4">
- <div className="form-group">
- <Label>Host <span className="required">*</span></Label>
- <Input value={conn.host} disabled={running}
- onChange={e => setConn({ ...conn, host: e.target.value })}
- placeholder="203.0.113.10 or wp.example.com" />
- </div>
- <div className="form-group">
- <Label>Port</Label>
- <Input value={conn.port} disabled={running}
- onChange={e => setConn({ ...conn, port: e.target.value })}
- placeholder="22" />
- </div>
- <div className="form-group">
- <Label>Username <span className="required">*</span></Label>
- <Input value={conn.username} disabled={running}
- onChange={e => setConn({ ...conn, username: e.target.value })}
- placeholder="root" />
- </div>
- <div className="form-group">
- <Label>WordPress path <span className="required">*</span></Label>
- <Input value={conn.wpPath} disabled={running}
- onChange={e => setConn({ ...conn, wpPath: e.target.value })}
- placeholder="/var/www/html" />
- <span className="form-hint">Absolute path of the directory containing wp-config.php.</span>
- </div>
- </div>
- <div className="form-group">
- <Label>Authentication</Label>
- <div className="flex gap-4 mb-2">
- <label className="flex items-center gap-2 text-sm">
- <input type="radio" checked={conn.authMethod === 'key'} disabled={running}
- onChange={() => setConn({ ...conn, authMethod: 'key' })} />
- Private key
- </label>
- <label className="flex items-center gap-2 text-sm">
- <input type="radio" checked={conn.authMethod === 'password'} disabled={running}
- onChange={() => setConn({ ...conn, authMethod: 'password' })} />
- Password
- </label>
- </div>
- {conn.authMethod === 'key' ? (
- <>
- <textarea
- className="w-full font-mono text-xs"
- rows={5}
- value={conn.privateKey}
- disabled={running}
- onChange={e => setConn({ ...conn, privateKey: e.target.value })}
- placeholder={'-----BEGIN OPENSSH PRIVATE KEY-----\n…'}
- />
- <span className="form-hint">Used for this import only — never stored.</span>
- </>
- ) : (
- <>
- <Input type="password" value={conn.password} disabled={running}
- onChange={e => setConn({ ...conn, password: e.target.value })}
- placeholder="SSH password" />
- <span className="form-hint">Used for this import only — never stored. Password auth requires the sshpass package on the panel host.</span>
- </>
- )}
- </div>
- <Button onClick={handleProbe} disabled={!canProbe || probing || running}>
- {probing ? <><Spinner size="sm" /> Probing…</> : 'Probe server'}
- </Button>
- </div>
-
- {/* Step 2 — facts + host-key trust */}
- {probe && (
- <div className="card p-4 mb-4">
- <h3 className="font-medium mb-3">2. Confirm the host</h3>
- <div className="form-group">
- <Label>SSH host-key fingerprint ({probe.host_key_type})</Label>
- <code className="block font-mono text-xs break-all">{probe.host_key_fingerprint}</code>
- <span className="form-hint">
- Compare against the server you expect (ssh-keygen -lf on the source).
- Every step of the import is pinned to this exact key.
- </span>
- </div>
- <table className="text-sm">
- <tbody>
- {facts.map(([k, v]) => (
- <tr key={k}>
- <td className="pr-4 text-muted-foreground">{k}</td>
- <td className="font-mono">{String(v)}</td>
- </tr>
- ))}
- </tbody>
- </table>
- <label className="flex items-center gap-2 text-sm mt-3">
- <input type="checkbox" checked={trusted} disabled={running}
- onChange={e => setTrusted(e.target.checked)} />
- I recognize this fingerprint — trust this host for the import
- </label>
- </div>
- )}
-
- {/* Step 3 — target + run */}
- {probe && (
- <div className="card p-4 mb-4">
- <h3 className="font-medium mb-3">3. New managed site</h3>
- <div className="grid grid-cols-2 gap-4">
- <div className="form-group">
- <Label>Site name <span className="required">*</span></Label>
- <Input value={target.siteName} disabled={running}
- onChange={e => setTarget({ ...target, siteName: e.target.value })}
- placeholder="my-migrated-site" />
- <span className="form-hint">Letters, numbers, and hyphens only.</span>
- </div>
- <div className="form-group">
- <Label>Admin email</Label>
- <Input type="email" value={target.adminEmail} disabled={running}
- onChange={e => setTarget({ ...target, adminEmail: e.target.value })}
- placeholder="[email protected]" />
- </div>
- <div className="form-group">
- <Label>Original site URL</Label>
- <Input value={target.oldUrl} disabled={running}
- onChange={e => setTarget({ ...target, oldUrl: e.target.value })}
- placeholder="https://old-site.com" />
- <span className="form-hint">Rewritten to the new local address after import (detected automatically when possible).</span>
- </div>
- </div>
- <Button onClick={handleStart} disabled={!trusted || starting || running}>
- {starting ? <><Spinner size="sm" /> Starting…</> : 'Pull and import'}
- </Button>
- </div>
- )}
-
- {/* Job progress */}
- {job && (
- <div className="card p-4 mb-4">
- <h3 className="font-medium mb-3">
- Import job #{job.id} — {job.status}
- {running && <Spinner size="sm" />}
- </h3>
- <ul className="text-sm font-mono space-y-1">
- {(job.steps || []).map((s, i) => (
- <li key={i}>
- <span className="text-muted-foreground">[{s.step}]</span> {s.message}
- </li>
- ))}
- </ul>
- {job.status === 'failed' && job.error && (
- <p className="text-sm text-destructive mt-2">{job.error}</p>
- )}
- {job.status === 'completed' && (
- <p className="text-sm mt-2">
- Done. <Link to="/wordpress" className="underline">Open the WordPress sites list</Link>
- {job.result?.new_url && <> — new address: <code>{job.result.new_url}</code></>}
- </p>
- )}
- </div>
- )}
- </div>
- );
-}
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/ActivityFeed.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/ActivityFeed.jsx
deleted file mode 100644
index 6be25a8a..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/ActivityFeed.jsx
+++ /dev/null
@@ -1,130 +0,0 @@
-import { useState, useEffect } from 'react';
-import { ArrowUpRight, ArrowDownLeft, Database, GitBranch, Lock, Unlock, Trash2, Play, Square, RefreshCw, Camera, AlertCircle } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { formatRelativeTime } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Badge } from 'serverkit-sdk';
-import { Skeleton } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-
-const ACTION_ICONS = {
- create: Play,
- deploy: GitBranch,
- promote: ArrowUpRight,
- sync: ArrowDownLeft,
- lock: Lock,
- unlock: Unlock,
- destroy: Trash2,
- snapshot_created: Camera,
- snapshot_restored: Database,
- started: Play,
- stopped: Square,
- restarted: RefreshCw
-};
-
-const ACTION_BADGE_VARIANTS = {
- create: 'success',
- deploy: 'info',
- promote: 'default',
- sync: 'info',
- lock: 'warning',
- unlock: 'secondary',
- destroy: 'destructive',
- snapshot_created: 'info',
- snapshot_restored: 'warning',
- started: 'success',
- stopped: 'secondary',
- restarted: 'info'
-};
-
-const ActivityFeed = ({ projectId, envId, limit = 20, compact = false }) => {
- const [activities, setActivities] = useState([]);
- const [loading, setLoading] = useState(true);
- const [total, setTotal] = useState(0);
-
- useEffect(() => {
- loadActivities();
- }, [projectId, envId]);
-
- async function loadActivities() {
- setLoading(true);
- try {
- const params = { limit };
- if (envId) params.env_id = envId;
- const data = await wordpressApi.getProjectActivity(projectId, params);
- setActivities(data.activities || []);
- setTotal(data.total || 0);
- } catch (err) {
- console.error('Failed to load activities:', err);
- } finally {
- setLoading(false);
- }
- }
-
- const feedSkeleton = (
- <>
- {[1, 2, 3].map(i => (
- <div key={i} className="activity-item-skeleton">
- <Skeleton variant="circle" width={32} height={32} />
- <div className="skeleton-stack">
- <Skeleton variant="line" width="60%" />
- <Skeleton variant="line" width="40%" />
- </div>
- </div>
- ))}
- </>
- );
-
- if (!loading && activities.length === 0) {
- return (
- <div className="activity-feed-empty">
- <p>No activity recorded yet.</p>
- </div>
- );
- }
-
- return (
- <SkeletonBoundary
- className={`activity-feed ${compact ? 'compact' : ''}`.trim()}
- loading={loading}
- skeleton={feedSkeleton}
- >
- {activities.length > 0 && activities.map(activity => {
- const Icon = ACTION_ICONS[activity.action] || AlertCircle;
- const colorClass = ACTION_BADGE_VARIANTS[activity.action] || 'secondary';
-
- return (
- <div key={activity.id} className="activity-item">
- <div className={`activity-icon ${colorClass}`}>
- <Icon size={14} />
- </div>
- <div className="activity-content">
- <span className="activity-description">
- {activity.description || `${activity.action} performed`}
- </span>
- {activity.status === 'failed' && activity.error_message && (
- <span className="activity-error">{activity.error_message}</span>
- )}
- </div>
- <div className="activity-meta">
- <span className="activity-time">{formatRelativeTime(activity.created_at)}</span>
- {activity.status === 'failed' && (
- <Badge variant="destructive">Failed</Badge>
- )}
- {activity.status === 'running' && (
- <Badge variant="info">Running</Badge>
- )}
- </div>
- </div>
- );
- })}
- {total > activities.length && !compact && (
- <Button variant="ghost" size="sm" className="activity-load-more" onClick={loadActivities}>
- Load more
- </Button>
- )}
- </SkeletonBoundary>
- );
-};
-
-export default ActivityFeed;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/AttachDomainModal.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/AttachDomainModal.jsx
deleted file mode 100644
index a12e5a85..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/AttachDomainModal.jsx
+++ /dev/null
@@ -1,130 +0,0 @@
-import { useState } from 'react';
-import { Globe, AlertTriangle, CheckCircle2 } from 'lucide-react';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { Switch } from 'serverkit-sdk';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-
-// Attach a user-owned custom domain to a site: auto-create the DNS A record (or
-// show the exact record to add manually), optional HTTPS, then migrate the site
-// URL to it via the URL-swap tool. Shows the result inline so a manual DNS
-// record can be read/copied.
-export default function AttachDomainModal({ site, onClose, onChanged }) {
- const toast = useToast();
- const [domain, setDomain] = useState('');
- const [issueSsl, setIssueSsl] = useState(false);
- const [attaching, setAttaching] = useState(false);
- const [result, setResult] = useState(null);
-
- const valid = /^[a-z0-9.-]+\.[a-z]{2,}$/i.test(domain.trim());
-
- async function handleAttach(e) {
- e?.preventDefault();
- if (!valid || attaching) return;
- setAttaching(true);
- toast.info('Attaching domain — creating DNS and moving the site…', { duration: 5000 });
- try {
- const res = await wordpressApi.attachDomain(site.id, { domain: domain.trim(), issueSsl });
- if (res.success) {
- setResult(res);
- if (res.dns?.created) toast.success(`DNS A record created via ${res.dns.provider}`);
- else toast.warning('Domain attached — add the DNS record shown to finish.', { duration: 7000 });
- onChanged?.();
- } else {
- toast.error(res.error || 'Failed to attach domain');
- }
- } catch (err) {
- toast.error(err.message || 'Failed to attach domain');
- } finally {
- setAttaching(false);
- }
- }
-
- const rec = result?.dns?.record;
-
- return (
- <Modal open onClose={() => !attaching && onClose()} title={<><Globe size={18} /> Add Custom Domain</>}>
- {!result ? (
- <form onSubmit={handleAttach}>
- <div className="wp-url-swap">
- <div className="wp-url-swap__warning">
- <AlertTriangle size={18} aria-hidden="true" />
- <span>
- Points a domain you own at this site. If a connected DNS provider
- manages it, the A record is created automatically — otherwise
- you&apos;ll get the exact record to add. The site URL is then
- migrated to the domain (serialization-safe).
- </span>
- </div>
-
- <div className="form-group">
- <Label htmlFor="wp-domain">Domain</Label>
- <Input
- id="wp-domain"
- type="text"
- value={domain}
- onChange={(e) => setDomain(e.target.value)}
- placeholder="example.com"
- disabled={attaching}
- autoFocus
- />
- <span className="form-hint">A domain or subdomain you control, without http://</span>
- </div>
-
- <label className="wp-url-swap__keep">
- <Switch checked={issueSsl} onCheckedChange={setIssueSsl} disabled={attaching} />
- <span>
- Set up HTTPS now
- <small>Requests a Let&apos;s Encrypt certificate. Needs DNS to already resolve to this server.</small>
- </span>
- </label>
- </div>
-
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose} disabled={attaching}>Cancel</Button>
- <Button type="submit" disabled={!valid || attaching}>
- {attaching ? 'Attaching…' : 'Attach Domain'}
- </Button>
- </div>
- </form>
- ) : (
- <>
- <div className="wp-url-swap">
- <div className="wp-url-swap__result">
- <CheckCircle2 size={18} aria-hidden="true" />
- <span>Site is now at <code>{result.url}</code></span>
- </div>
-
- {result.dns?.created ? (
- <div className="form-hint">
- DNS A record created automatically via {result.dns.provider}
- {result.dns.zone ? ` (zone ${result.dns.zone})` : ''}.
- </div>
- ) : (
- <div className="wp-url-swap__dns-manual">
- <strong>Add this DNS record to finish:</strong>
- {rec?.value ? (
- <code className="wp-url-swap__record">
- {rec.type}&nbsp;&nbsp;{rec.name}&nbsp;→&nbsp;{rec.value}
- </code>
- ) : (
- <div className="form-hint">{result.dns?.message}</div>
- )}
- </div>
- )}
-
- {result.warning && (
- <div className="wp-url-swap__preview-error">{result.warning}</div>
- )}
- </div>
- <div className="modal-actions">
- <Button type="button" onClick={onClose}>Done</Button>
- </div>
- </>
- )}
- </Modal>
- );
-}
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/AutoSyncScheduleModal.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/AutoSyncScheduleModal.jsx
deleted file mode 100644
index 5a5488f4..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/AutoSyncScheduleModal.jsx
+++ /dev/null
@@ -1,181 +0,0 @@
-import { useState, useEffect } from 'react';
-import { RefreshCw } from 'lucide-react';
-import { Spinner } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { Switch } from 'serverkit-sdk';
-
-const SCHEDULE_PRESETS = [
- { label: 'Daily at 3 AM', value: '0 3 * * *' },
- { label: 'Weekly Sunday 3 AM', value: '0 3 * * 0' },
- { label: 'Every 6 hours', value: '0 */6 * * *' },
- { label: 'Every 12 hours', value: '0 */12 * * *' },
- { label: 'Custom', value: 'custom' },
-];
-
-const AutoSyncScheduleModal = ({ environment, prodId, onClose, api }) => {
- const [loading, setLoading] = useState(true);
- const [saving, setSaving] = useState(false);
- const [enabled, setEnabled] = useState(false);
- const [schedule, setSchedule] = useState('0 3 * * *');
- const [selectedPreset, setSelectedPreset] = useState('0 3 * * *');
- const [customCron, setCustomCron] = useState('');
- const [nextRuns, setNextRuns] = useState([]);
-
- useEffect(() => {
- loadSchedule();
- }, []);
-
- async function loadSchedule() {
- setLoading(true);
- try {
- const data = await api.getAutoSyncSchedule(prodId, environment.id);
- setEnabled(data.enabled || false);
- if (data.schedule) {
- const matchingPreset = SCHEDULE_PRESETS.find(p => p.value === data.schedule);
- if (matchingPreset) {
- setSelectedPreset(data.schedule);
- } else {
- setSelectedPreset('custom');
- setCustomCron(data.schedule);
- }
- setSchedule(data.schedule);
- }
- setNextRuns(data.next_runs || []);
- } catch {
- // Default values already set
- } finally {
- setLoading(false);
- }
- }
-
- function handlePresetChange(value) {
- setSelectedPreset(value);
- if (value !== 'custom') {
- setSchedule(value);
- }
- }
-
- function handleCustomCronChange(value) {
- setCustomCron(value);
- setSchedule(value);
- }
-
- async function handleSave() {
- setSaving(true);
- try {
- const finalSchedule = selectedPreset === 'custom' ? customCron : selectedPreset;
- await api.updateAutoSyncSchedule(prodId, environment.id, {
- enabled,
- schedule: finalSchedule,
- });
- onClose();
- } catch (err) {
- console.error('Failed to save auto-sync schedule:', err);
- } finally {
- setSaving(false);
- }
- }
-
- function formatDateTime(iso) {
- if (!iso) return '';
- const d = new Date(iso);
- return d.toLocaleString();
- }
-
- const envName = environment?.name || 'Environment';
-
- return (
- <Modal open={true} onClose={onClose} title="Auto-Sync Schedule" className="auto-sync-modal">
- {loading ? (
- <div className="auto-sync-loading">
- <Spinner size="sm" />
- <span>Loading schedule...</span>
- </div>
- ) : (
- <div className="auto-sync-body">
- <div className="auto-sync-env-name">{envName}</div>
-
- <div className="auto-sync-toggle">
- <label className="auto-sync-toggle-label">
- <span>Enable Auto-Sync from Production</span>
- <Switch checked={enabled} onCheckedChange={setEnabled} />
- </label>
- <p className="auto-sync-description">
- Automatically sync this environment from production on a schedule.
- </p>
- </div>
-
- {enabled && (
- <>
- <div className="form-group">
- <Label>Schedule</Label>
- <div className="auto-sync-presets">
- {SCHEDULE_PRESETS.map(preset => (
- <label key={preset.value} className="radio-label">
- <input
- type="radio"
- name="schedule-preset"
- checked={selectedPreset === preset.value}
- onChange={() => handlePresetChange(preset.value)}
- />
- <span className="radio-content">
- <strong>{preset.label}</strong>
- {preset.value !== 'custom' && (
- <span className="auto-sync-cron-display">{preset.value}</span>
- )}
- </span>
- </label>
- ))}
- </div>
- </div>
-
- {selectedPreset === 'custom' && (
- <div className="form-group">
- <Label>Custom Cron Expression</Label>
- <Input
- type="text"
- value={customCron}
- onChange={e => handleCustomCronChange(e.target.value)}
- placeholder="0 3 * * *"
- className="auto-sync-cron-input"
- />
- <span className="form-hint">
- Format: minute hour day-of-month month day-of-week
- </span>
- </div>
- )}
-
- {nextRuns.length > 0 && (
- <div className="auto-sync-next-runs">
- <h5>Next Scheduled Runs</h5>
- <ul>
- {nextRuns.map((run, i) => (
- <li key={i}>
- <RefreshCw size={10} />
- <span>{formatDateTime(run)}</span>
- </li>
- ))}
- </ul>
- </div>
- )}
- </>
- )}
- </div>
- )}
-
- <div className="modal-actions">
- <Button variant="outline" onClick={onClose} disabled={saving}>
- Cancel
- </Button>
- <Button onClick={handleSave} disabled={saving || loading}>
- {saving ? <><Spinner size="sm" /> Saving...</> : 'Save Schedule'}
- </Button>
- </div>
- </Modal>
- );
-};
-
-export default AutoSyncScheduleModal;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/BasicAuthModal.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/BasicAuthModal.jsx
deleted file mode 100644
index 07c366f9..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/BasicAuthModal.jsx
+++ /dev/null
@@ -1,156 +0,0 @@
-import { useState, useEffect } from 'react';
-import { Shield, Copy, Check, AlertTriangle } from 'lucide-react';
-import { Spinner } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Switch } from 'serverkit-sdk';
-
-const BasicAuthModal = ({ environment, prodId, onClose, api }) => {
- const [loading, setLoading] = useState(true);
- const [status, setStatus] = useState({ enabled: false, username: null });
- const [credentials, setCredentials] = useState(null);
- const [toggling, setToggling] = useState(false);
- const [copied, setCopied] = useState(null);
-
- useEffect(() => {
- loadStatus();
- }, []);
-
- async function loadStatus() {
- setLoading(true);
- try {
- const data = await api.getBasicAuthStatus(prodId, environment.id);
- setStatus(data);
- } catch {
- setStatus({ enabled: false, username: null });
- } finally {
- setLoading(false);
- }
- }
-
- async function handleEnable() {
- setToggling(true);
- try {
- const data = await api.enableBasicAuth(prodId, environment.id);
- if (data.success) {
- setStatus({ enabled: true, username: data.username });
- setCredentials({ username: data.username, password: data.password });
- }
- } catch (err) {
- console.error('Failed to enable basic auth:', err);
- } finally {
- setToggling(false);
- }
- }
-
- async function handleDisable() {
- setToggling(true);
- try {
- const data = await api.disableBasicAuth(prodId, environment.id);
- if (data.success) {
- setStatus({ enabled: false, username: null });
- setCredentials(null);
- }
- } catch (err) {
- console.error('Failed to disable basic auth:', err);
- } finally {
- setToggling(false);
- }
- }
-
- function copyToClipboard(text, field) {
- navigator.clipboard.writeText(text);
- setCopied(field);
- setTimeout(() => setCopied(null), 2000);
- }
-
- const envName = environment?.name || 'Environment';
-
- return (
- <Modal open={true} onClose={onClose} title="Basic Auth" className="basic-auth-modal">
- <div className="basic-auth-body">
- <div className="basic-auth-env-name">{envName}</div>
-
- {loading ? (
- <div className="basic-auth-loading">
- <Spinner size="sm" />
- <span>Loading status...</span>
- </div>
- ) : (
- <>
- <div className="basic-auth-toggle">
- <label className="basic-auth-toggle-label">
- <span>HTTP Basic Authentication</span>
- <Switch
- checked={status.enabled}
- onCheckedChange={status.enabled ? handleDisable : handleEnable}
- disabled={toggling}
- />
- </label>
- <p className="basic-auth-description">
- Adds password protection to the site. Visitors must enter credentials to access any page.
- </p>
- </div>
-
- {status.enabled && status.username && !credentials && (
- <div className="basic-auth-current">
- <div className="basic-auth-field">
- <label>Username</label>
- <div className="basic-auth-value">
- <code>{status.username}</code>
- </div>
- </div>
- <p className="basic-auth-hint">
- Password was shown when Basic Auth was first enabled. Disable and re-enable to generate new credentials.
- </p>
- </div>
- )}
-
- {credentials && (
- <div className="basic-auth-credentials">
- <div className="alert alert-warning">
- <AlertTriangle size={14} />
- <span>Save these credentials now. The password will not be shown again.</span>
- </div>
- <div className="basic-auth-field">
- <label>Username</label>
- <div className="basic-auth-value">
- <code>{credentials.username}</code>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => copyToClipboard(credentials.username, 'user')}
- >
- {copied === 'user' ? <Check size={12} /> : <Copy size={12} />}
- </Button>
- </div>
- </div>
- <div className="basic-auth-field">
- <label>Password</label>
- <div className="basic-auth-value">
- <code>{credentials.password}</code>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => copyToClipboard(credentials.password, 'pass')}
- >
- {copied === 'pass' ? <Check size={12} /> : <Copy size={12} />}
- </Button>
- </div>
- </div>
- </div>
- )}
- </>
- )}
- </div>
-
- <div className="modal-actions">
- <Button variant="outline" onClick={onClose}>
- Close
- </Button>
- </div>
- </Modal>
- );
-};
-
-export default BasicAuthModal;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/BulkActionsBar.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/BulkActionsBar.jsx
deleted file mode 100644
index 3fc66b9b..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/BulkActionsBar.jsx
+++ /dev/null
@@ -1,123 +0,0 @@
-import { useState } from 'react';
-import { Square, Play, RefreshCw, ArrowDownLeft, X } from 'lucide-react';
-import { Spinner } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-
-const BulkActionsBar = ({ selectedIds, environments, prodId, onClear, onExecute, api }) => {
- const [executing, setExecuting] = useState(false);
- const [confirmAction, setConfirmAction] = useState(null);
-
- if (!selectedIds || selectedIds.length === 0) return null;
-
- const selectedNames = selectedIds.map(id => {
- const env = environments.find(e => e.id === id);
- return env?.name || `#${id}`;
- });
-
- async function handleAction(action) {
- if (action === 'stop' || action === 'sync') {
- setConfirmAction(action);
- return;
- }
- await executeAction(action);
- }
-
- async function executeAction(action) {
- setExecuting(true);
- setConfirmAction(null);
- try {
- await onExecute(action, selectedIds);
- } finally {
- setExecuting(false);
- }
- }
-
- return (
- <div className="bulk-actions-bar">
- {confirmAction ? (
- <div className="bulk-actions-confirm">
- <span>
- {confirmAction === 'stop' && `Stop ${selectedIds.length} environment(s)?`}
- {confirmAction === 'sync' && `Sync ${selectedIds.length} environment(s) from production?`}
- </span>
- <Button
- size="sm"
- onClick={() => executeAction(confirmAction)}
- disabled={executing}
- >
- {executing ? <Spinner size="sm" /> : 'Confirm'}
- </Button>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => setConfirmAction(null)}
- disabled={executing}
- >
- Cancel
- </Button>
- </div>
- ) : (
- <>
- <div className="bulk-actions-info">
- <span className="bulk-actions-count">{selectedIds.length}</span>
- <span>selected</span>
- </div>
-
- <div className="bulk-actions-buttons">
- <Button
- variant="ghost"
- size="sm"
- onClick={() => handleAction('start')}
- disabled={executing}
- title="Start Selected"
- >
- <Play size={12} />
- Start
- </Button>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => handleAction('stop')}
- disabled={executing}
- title="Stop Selected"
- >
- <Square size={12} />
- Stop
- </Button>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => handleAction('restart')}
- disabled={executing}
- title="Restart Selected"
- >
- <RefreshCw size={12} />
- Restart
- </Button>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => handleAction('sync')}
- disabled={executing}
- title="Sync from Production"
- >
- <ArrowDownLeft size={12} />
- Sync from Prod
- </Button>
- </div>
-
- <Button
- variant="ghost"
- size="icon"
- className="bulk-actions-clear"
- onClick={onClear}
- >
- <X size={12} />
- </Button>
- </>
- )}
- </div>
- );
-};
-
-export default BulkActionsBar;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/ChangeUrlModal.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/ChangeUrlModal.jsx
deleted file mode 100644
index 3affb176..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/ChangeUrlModal.jsx
+++ /dev/null
@@ -1,146 +0,0 @@
-import { useState, useEffect } from 'react';
-import { Globe, AlertTriangle, ArrowRight } from 'lucide-react';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { Switch } from 'serverkit-sdk';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-
-// Change a WordPress site's URL safely: a debounced dry-run preview of the DB
-// rewrite, then a backed-up, serialization-safe apply (WP-CLI search-replace)
-// on confirm. The backend re-points the Domain row + nginx vhost afterwards.
-export default function ChangeUrlModal({ site, onClose, onChanged }) {
- const toast = useToast();
- const currentUrl = site.url || '';
- const [newUrl, setNewUrl] = useState(currentUrl);
- const [keepOld, setKeepOld] = useState(true);
- const [preview, setPreview] = useState(null);
- const [previewing, setPreviewing] = useState(false);
- const [applying, setApplying] = useState(false);
-
- const target = newUrl.trim();
- const dirty = target && target !== currentUrl;
-
- // Debounced dry-run preview whenever the target URL settles.
- useEffect(() => {
- if (!dirty) { setPreview(null); return undefined; }
- let cancelled = false;
- setPreviewing(true);
- const timer = setTimeout(async () => {
- try {
- const res = await wordpressApi.previewUrlChange(site.id, target);
- if (!cancelled) setPreview(res);
- } catch (err) {
- if (!cancelled) setPreview({ success: false, error: err.message || 'Preview failed' });
- } finally {
- if (!cancelled) setPreviewing(false);
- }
- }, 500);
- return () => { cancelled = true; clearTimeout(timer); };
- }, [target, dirty, site.id]);
-
- async function handleApply(e) {
- e?.preventDefault();
- if (!dirty || applying) return;
- setApplying(true);
- toast.info('Changing site URL — backing up and rewriting the database…', { duration: 5000 });
- try {
- const res = await wordpressApi.changeUrl(site.id, target, keepOld);
- if (res.success) {
- toast.success(`Site URL changed to ${res.new_url} (${res.replacements} replacement${res.replacements === 1 ? '' : 's'})`);
- if (res.warning) toast.warning(res.warning, { duration: 7000 });
- onChanged?.();
- onClose();
- } else {
- toast.error(res.error || 'Failed to change URL');
- }
- } catch (err) {
- toast.error(err.message || 'Failed to change URL');
- } finally {
- setApplying(false);
- }
- }
-
- return (
- <Modal open onClose={() => !applying && onClose()} title={<><Globe size={18} /> Change Site URL</>} size="lg">
- <form onSubmit={handleApply}>
- <div className="wp-url-swap">
- <div className="wp-url-swap__warning">
- <AlertTriangle size={18} aria-hidden="true" />
- <span>
- This rewrites every reference to the site URL across the database
- (posts, options, serialized data) with a serialization-safe
- search-replace. A database backup is taken first and restored
- automatically if anything fails.
- </span>
- </div>
-
- <div className="wp-url-swap__fromto">
- <code>{currentUrl || '—'}</code>
- <ArrowRight size={15} aria-hidden="true" />
- <code className={dirty ? 'is-new' : ''}>{target || '—'}</code>
- </div>
-
- <div className="form-group">
- <Label htmlFor="wp-new-url">New URL</Label>
- <Input
- id="wp-new-url"
- type="text"
- value={newUrl}
- onChange={(e) => setNewUrl(e.target.value)}
- placeholder="https://example.com"
- disabled={applying}
- autoFocus
- />
- <span className="form-hint">
- Include http:// or https://. Point this hostname&apos;s DNS at the server first.
- </span>
- </div>
-
- <label className="wp-url-swap__keep">
- <Switch checked={keepOld} onCheckedChange={setKeepOld} disabled={applying} />
- <span>
- Keep the old address working
- <small>The previous host keeps resolving; WordPress 301-redirects it to the new URL.</small>
- </span>
- </label>
-
- {dirty && (
- <div className="wp-url-swap__preview">
- {previewing && <span className="form-hint">Previewing changes…</span>}
- {!previewing && preview?.success && (
- <>
- <div className="wp-url-swap__preview-total">
- {preview.total} database replacement{preview.total === 1 ? '' : 's'} will be made
- </div>
- <ul className="wp-url-swap__preview-pairs">
- {preview.pairs.map((p, i) => (
- <li key={i}>
- <code>{p.search}</code>
- <ArrowRight size={12} aria-hidden="true" />
- <code>{p.replace}</code>
- <span className="wp-url-swap__count">{p.replacements}</span>
- </li>
- ))}
- </ul>
- </>
- )}
- {!previewing && preview && !preview.success && (
- <div className="wp-url-swap__preview-error">{preview.error}</div>
- )}
- </div>
- )}
- </div>
-
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose} disabled={applying}>Cancel</Button>
- <Button type="submit" disabled={!dirty || applying}>
- {applying ? 'Changing…' : 'Change URL'}
- </Button>
- </div>
- </form>
- </Modal>
- );
-}
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/CommitList.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/CommitList.jsx
deleted file mode 100644
index a3eed021..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/CommitList.jsx
+++ /dev/null
@@ -1,220 +0,0 @@
-import { useState } from 'react';
-import { GitCommit, Rocket, Copy, CheckCircle, ExternalLink } from 'lucide-react';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { detectProvider } from '@/components/git/GitProviders';
-import { EmptyState } from 'serverkit-sdk';
-
-// Build a web URL to a commit on the host from the clone URL + sha so the log is
-// clickable. Handles https + scp-style ssh remotes and Bitbucket's /commits path.
-function commitUrl(repoUrl, sha) {
- if (!repoUrl || !sha) return null;
- let base = repoUrl.trim().replace(/\.git$/i, '');
- const ssh = base.match(/^git@([^:]+):(.+)$/);
- if (ssh) base = `https://${ssh[1]}/${ssh[2]}`;
- if (!/^https?:\/\//i.test(base)) return null;
- const seg = detectProvider(repoUrl)?.key === 'bitbucket' ? 'commits' : 'commit';
- return `${base}/${seg}/${sha}`;
-}
-
-const CommitList = ({ commits, currentCommit, onDeploy, onCreateDev, loading = false, repoUrl }) => {
- const [actionLoading, setActionLoading] = useState({});
- const [showDevModal, setShowDevModal] = useState(null);
-
- function formatDate(dateString) {
- if (!dateString) return '-';
- const date = new Date(dateString);
- const now = new Date();
- const diffMs = now - date;
- const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
- const diffDays = Math.floor(diffHours / 24);
-
- if (diffHours < 1) return 'Just now';
- if (diffHours < 24) return `${diffHours}h ago`;
- if (diffDays < 7) return `${diffDays}d ago`;
- return date.toLocaleDateString();
- }
-
- async function handleDeploy(commit) {
- if (!confirm(`Deploy commit ${commit.sha.substring(0, 7)} to production?`)) {
- return;
- }
- setActionLoading(prev => ({ ...prev, [`deploy-${commit.sha}`]: true }));
- try {
- await onDeploy?.({ commit_sha: commit.sha });
- } finally {
- setActionLoading(prev => ({ ...prev, [`deploy-${commit.sha}`]: false }));
- }
- }
-
- async function handleCreateDev(commit, config) {
- setActionLoading(prev => ({ ...prev, [`dev-${commit.sha}`]: true }));
- try {
- await onCreateDev?.({
- commit_sha: commit.sha,
- config
- });
- setShowDevModal(null);
- } finally {
- setActionLoading(prev => ({ ...prev, [`dev-${commit.sha}`]: false }));
- }
- }
-
- if (loading) {
- return <EmptyState loading title="Loading commits..." />;
- }
-
- if (!commits || commits.length === 0) {
- return (
- <div className="empty-state-small">
- <p>No commits found.</p>
- <p className="hint">Push changes to your repository to see commits here.</p>
- </div>
- );
- }
-
- return (
- <div className="commit-list">
- {commits.map(commit => {
- const isCurrent = currentCommit === commit.sha;
- const isDeploying = actionLoading[`deploy-${commit.sha}`];
- const isCreatingDev = actionLoading[`dev-${commit.sha}`];
-
- return (
- <div key={commit.sha} className={`commit-item ${isCurrent ? 'current' : ''}`}>
- <div className="commit-icon">
- {isCurrent ? (
- <CheckCircle size={16} className="current-icon" />
- ) : (
- <GitCommit size={16} />
- )}
- </div>
-
- <div className="commit-info">
- <div className="commit-header">
- {commitUrl(repoUrl, commit.sha) ? (
- <a
- className="commit-sha mono commit-sha--link"
- href={commitUrl(repoUrl, commit.sha)}
- target="_blank"
- rel="noopener noreferrer"
- title="View this commit on the remote"
- >
- {commit.sha.substring(0, 7)}
- <ExternalLink size={11} />
- </a>
- ) : (
- <span className="commit-sha mono">{commit.sha.substring(0, 7)}</span>
- )}
- {isCurrent && <span className="current-badge">Deployed</span>}
- <span className="commit-date">{formatDate(commit.date)}</span>
- </div>
- <p className="commit-message">{commit.message}</p>
- {commit.author && (
- <span className="commit-author">{commit.author}</span>
- )}
- </div>
-
- <div className="commit-actions">
- {!isCurrent && (
- <Button
- size="sm"
- onClick={() => handleDeploy(commit)}
- disabled={isDeploying}
- title="Deploy this commit"
- >
- <Rocket size={12} />
- {isDeploying ? 'Deploying...' : 'Deploy'}
- </Button>
- )}
- <Button
- variant="outline"
- size="sm"
- onClick={() => setShowDevModal(commit)}
- disabled={isCreatingDev}
- title="Create dev environment from this commit"
- >
- <Copy size={12} />
- {isCreatingDev ? 'Creating...' : 'Create Dev'}
- </Button>
- </div>
- </div>
- );
- })}
-
- {showDevModal && (
- <CreateDevModal
- commit={showDevModal}
- onClose={() => setShowDevModal(null)}
- onCreate={(config) => handleCreateDev(showDevModal, config)}
- loading={actionLoading[`dev-${showDevModal.sha}`]}
- />
- )}
- </div>
- );
-};
-
-const CreateDevModal = ({ commit, onClose, onCreate, loading }) => {
- const [formData, setFormData] = useState({
- name: `dev-${commit.sha.substring(0, 7)}`,
- domain: ''
- });
-
- function handleChange(e) {
- const { name, value } = e.target;
- setFormData(prev => ({ ...prev, [name]: value }));
- }
-
- function handleSubmit(e) {
- e.preventDefault();
- onCreate(formData);
- }
-
- return (
- <Modal open={true} onClose={onClose} title="Create Dev Environment">
- <p className="hint">
- Create a development environment with code from commit{' '}
- <code>{commit.sha.substring(0, 7)}</code>
- </p>
- <p className="commit-message-preview">&ldquo;{commit.message}&rdquo;</p>
-
- <form onSubmit={handleSubmit}>
- <div className="form-group">
- <Label>Environment Name</Label>
- <Input
- type="text"
- name="name"
- value={formData.name}
- onChange={handleChange}
- placeholder="dev-abc1234"
- />
- </div>
-
- <div className="form-group">
- <Label>Domain (optional)</Label>
- <Input
- type="text"
- name="domain"
- value={formData.domain}
- onChange={handleChange}
- placeholder="dev.example.com"
- />
- <span className="form-hint">Leave empty to auto-generate</span>
- </div>
-
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose}>
- Cancel
- </Button>
- <Button type="submit" disabled={loading}>
- {loading ? 'Creating...' : 'Create Environment'}
- </Button>
- </div>
- </form>
- </Modal>
- );
-};
-
-export default CommitList;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/CompareView.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/CompareView.jsx
deleted file mode 100644
index 78cac4c3..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/CompareView.jsx
+++ /dev/null
@@ -1,215 +0,0 @@
-import { useState, useEffect } from 'react';
-import { GitCompare, Check, X, Minus, RefreshCw } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { Spinner } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-
-const CompareView = ({ projectId, envA, envB, onClose }) => {
- const [comparison, setComparison] = useState(null);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState(null);
-
- useEffect(() => {
- loadComparison();
- }, [envA?.id, envB?.id]);
-
- async function loadComparison() {
- if (!envA?.id || !envB?.id) return;
-
- setLoading(true);
- setError(null);
- try {
- const data = await wordpressApi.compareEnvironments(projectId, envA.id, envB.id);
- setComparison(data);
- } catch (err) {
- setError(err.message || 'Failed to compare environments');
- } finally {
- setLoading(false);
- }
- }
-
- const envAType = envA?.environment_type || 'production';
- const envBType = envB?.environment_type || 'development';
-
- return (
- <Modal open={true} onClose={onClose} title="Compare Environments" size="xl">
- <div className="compare-header">
- <div className={`compare-env-pill ${envAType}`}>
- <span className="compare-env-type">{envAType}</span>
- <span className="compare-env-name">{envA?.name || 'Environment A'}</span>
- </div>
- <GitCompare size={16} className="compare-vs-icon" />
- <div className={`compare-env-pill ${envBType}`}>
- <span className="compare-env-type">{envBType}</span>
- <span className="compare-env-name">{envB?.name || 'Environment B'}</span>
- </div>
- <Button variant="ghost" size="sm" onClick={loadComparison} disabled={loading}>
- <RefreshCw size={14} />
- </Button>
- </div>
-
- <div className="compare-body">
- {loading && (
- <div className="compare-loading">
- <Spinner size="md" />
- <span>Comparing environments...</span>
- </div>
- )}
-
- {error && (
- <div className="alert alert-danger">
- <p>{error}</p>
- <Button size="sm" onClick={loadComparison}>
- Retry
- </Button>
- </div>
- )}
-
- {!loading && !error && comparison && (
- <>
- {/* Version Comparison */}
- <CompareSection title="Versions">
- <CompareRow
- label="WordPress"
- valueA={comparison.env_a?.wp_version}
- valueB={comparison.env_b?.wp_version}
- />
- <CompareRow
- label="PHP"
- valueA={comparison.env_a?.php_version}
- valueB={comparison.env_b?.php_version}
- />
- <CompareRow
- label="Active Theme"
- valueA={comparison.env_a?.active_theme}
- valueB={comparison.env_b?.active_theme}
- />
- </CompareSection>
-
- {/* Plugins Comparison */}
- {comparison.plugins && (
- <CompareSection
- title="Plugins"
- summary={getPluginSummary(comparison.plugins)}
- >
- {comparison.plugins.map(plugin => (
- <CompareRow
- key={plugin.name}
- label={plugin.name}
- valueA={plugin.version_a || (plugin.in_a ? 'Installed' : null)}
- valueB={plugin.version_b || (plugin.in_b ? 'Installed' : null)}
- status={plugin.status}
- />
- ))}
- {comparison.plugins.length === 0 && (
- <div className="compare-empty-row">No plugin data available</div>
- )}
- </CompareSection>
- )}
-
- {/* Themes Comparison */}
- {comparison.themes && (
- <CompareSection
- title="Themes"
- summary={getThemeSummary(comparison.themes)}
- >
- {comparison.themes.map(theme => (
- <CompareRow
- key={theme.name}
- label={theme.name}
- valueA={theme.version_a || (theme.in_a ? 'Installed' : null)}
- valueB={theme.version_b || (theme.in_b ? 'Installed' : null)}
- status={theme.status}
- />
- ))}
- {comparison.themes.length === 0 && (
- <div className="compare-empty-row">No theme data available</div>
- )}
- </CompareSection>
- )}
- </>
- )}
- </div>
-
- <div className="modal-actions">
- <Button variant="outline" onClick={onClose}>Close</Button>
- </div>
- </Modal>
- );
-};
-
-const CompareSection = ({ title, summary, children }) => (
- <div className="compare-section">
- <div className="compare-section-header">
- <h4>{title}</h4>
- {summary && <span className="compare-section-summary">{summary}</span>}
- </div>
- <div className="compare-table">
- {children}
- </div>
- </div>
-);
-
-const CompareRow = ({ label, valueA, valueB, status }) => {
- const match = valueA === valueB && valueA != null;
- const onlyA = valueA && !valueB;
- const onlyB = !valueA && valueB;
- const different = valueA && valueB && valueA !== valueB;
-
- let statusClass = 'match';
- let StatusIcon = Check;
- if (different || status === 'different') {
- statusClass = 'different';
- StatusIcon = X;
- } else if (onlyA || status === 'only_a') {
- statusClass = 'only-a';
- StatusIcon = Minus;
- } else if (onlyB || status === 'only_b') {
- statusClass = 'only-b';
- StatusIcon = Minus;
- }
-
- return (
- <div className={`compare-row ${statusClass}`}>
- <div className="compare-row-label">
- <StatusIcon size={12} className="compare-row-icon" />
- {label}
- </div>
- <div className="compare-row-value-a">
- {valueA || <span className="compare-na">--</span>}
- </div>
- <div className="compare-row-value-b">
- {valueB || <span className="compare-na">--</span>}
- </div>
- </div>
- );
-};
-
-function getPluginSummary(plugins) {
- const match = plugins.filter(p => p.status === 'match').length;
- const diff = plugins.filter(p => p.status === 'different').length;
- const onlyA = plugins.filter(p => p.status === 'only_a').length;
- const onlyB = plugins.filter(p => p.status === 'only_b').length;
- const parts = [];
- if (match) parts.push(`${match} matching`);
- if (diff) parts.push(`${diff} different`);
- if (onlyA) parts.push(`${onlyA} only in A`);
- if (onlyB) parts.push(`${onlyB} only in B`);
- return parts.join(', ');
-}
-
-function getThemeSummary(themes) {
- const match = themes.filter(t => t.status === 'match').length;
- const diff = themes.filter(t => t.status === 'different').length;
- const onlyA = themes.filter(t => t.status === 'only_a').length;
- const onlyB = themes.filter(t => t.status === 'only_b').length;
- const parts = [];
- if (match) parts.push(`${match} matching`);
- if (diff) parts.push(`${diff} different`);
- if (onlyA) parts.push(`${onlyA} only in A`);
- if (onlyB) parts.push(`${onlyB} only in B`);
- return parts.join(', ');
-}
-
-export default CompareView;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/ContainerLogs.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/ContainerLogs.jsx
deleted file mode 100644
index 927a87ac..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/ContainerLogs.jsx
+++ /dev/null
@@ -1,132 +0,0 @@
-import { useState, useEffect, useRef } from 'react';
-import { Terminal, X, Download } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { Button } from 'serverkit-sdk';
-import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from 'serverkit-sdk';
-
-const ContainerLogs = ({ projectId, envId, onClose }) => {
- const [logs, setLogs] = useState([]);
- const [loading, setLoading] = useState(true);
- const [service, setService] = useState('wordpress');
- const [lines, setLines] = useState(100);
- const [autoScroll, setAutoScroll] = useState(true);
- const logsEndRef = useRef(null);
- const containerRef = useRef(null);
-
- useEffect(() => {
- loadLogs();
- }, [projectId, envId, service, lines]);
-
- useEffect(() => {
- if (autoScroll && logsEndRef.current) {
- logsEndRef.current.scrollIntoView({ behavior: 'smooth' });
- }
- }, [logs, autoScroll]);
-
- async function loadLogs() {
- setLoading(true);
- try {
- const data = await wordpressApi.getEnvironmentLogs(projectId, envId, { service, lines });
- setLogs(data.logs || []);
- } catch (err) {
- console.error('Failed to load logs:', err);
- setLogs([`Error loading logs: ${err.message}`]);
- } finally {
- setLoading(false);
- }
- }
-
- function handleScroll() {
- if (!containerRef.current) return;
- const { scrollTop, scrollHeight, clientHeight } = containerRef.current;
- setAutoScroll(scrollHeight - scrollTop - clientHeight < 50);
- }
-
- function handleDownload() {
- const text = logs.join('\n');
- const blob = new Blob([text], { type: 'text/plain' });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = `env-${envId}-${service}-logs.txt`;
- a.click();
- URL.revokeObjectURL(url);
- }
-
- return (
- <div className="container-logs-panel">
- <div className="container-logs-header">
- <div className="container-logs-title">
- <span className="container-logs-ico">
- <Terminal size={15} />
- </span>
- <div className="container-logs-titles">
- <span>Container Logs</span>
- <span className="container-logs-sub">env-{envId} · {service}</span>
- </div>
- </div>
- <div className="container-logs-controls">
- <Select value={service} onValueChange={setService}>
- <SelectTrigger className="logs-service-select">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="wordpress">WordPress</SelectItem>
- <SelectItem value="db">MySQL</SelectItem>
- </SelectContent>
- </Select>
- <Select value={String(lines)} onValueChange={(v) => setLines(Number(v))}>
- <SelectTrigger className="logs-lines-select">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="50">50 lines</SelectItem>
- <SelectItem value="100">100 lines</SelectItem>
- <SelectItem value="500">500 lines</SelectItem>
- </SelectContent>
- </Select>
- <Button variant="ghost" size="sm" onClick={loadLogs} title="Refresh">
- <RefreshIcon />
- </Button>
- <Button variant="ghost" size="sm" onClick={handleDownload} title="Download">
- <Download size={14} />
- </Button>
- {onClose && (
- <Button variant="ghost" size="sm" onClick={onClose}>
- <X size={14} />
- </Button>
- )}
- </div>
- </div>
- <div
- className="container-logs-body"
- ref={containerRef}
- onScroll={handleScroll}
- >
- {loading ? (
- <div className="logs-loading">Loading logs...</div>
- ) : logs.length === 0 ? (
- <div className="logs-empty">No logs available.</div>
- ) : (
- <pre className="logs-content">
- {logs.map((line, i) => (
- <div key={i} className="log-line">{line}</div>
- ))}
- <div ref={logsEndRef} />
- </pre>
- )}
- </div>
- </div>
- );
-};
-
-function RefreshIcon() {
- return (
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
- <polyline points="23 4 23 10 17 10" />
- <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10" />
- </svg>
- );
-}
-
-export default ContainerLogs;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/DiskUsageBar.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/DiskUsageBar.jsx
deleted file mode 100644
index f824b683..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/DiskUsageBar.jsx
+++ /dev/null
@@ -1,78 +0,0 @@
-import { HardDrive } from 'lucide-react';
-import { formatBytes } from 'serverkit-sdk';
-
-const REFERENCE_THRESHOLD = 10 * 1024 * 1024 * 1024; // 10 GB reference
-
-const DiskUsageBar = ({ usage, showBreakdown = true, compact = false }) => {
- if (!usage) return null;
-
- const total = usage.total || 0;
- const wordpress = usage.wordpress || 0;
- const mysql = usage.mysql || 0;
- const snapshots = usage.snapshots || 0;
-
- const percent = REFERENCE_THRESHOLD > 0
- ? Math.min((total / REFERENCE_THRESHOLD) * 100, 100)
- : 0;
-
- const wpPercent = total > 0 ? (wordpress / total) * percent : 0;
- const dbPercent = total > 0 ? (mysql / total) * percent : 0;
- const snapPercent = total > 0 ? (snapshots / total) * percent : 0;
-
- const colorClass = percent < 70 ? 'green' : percent < 90 ? 'yellow' : 'red';
-
- if (compact) {
- return (
- <div className="disk-usage-compact" title={`Disk: ${formatBytes(total)}`}>
- <HardDrive size={10} />
- <span className="disk-usage-compact-text">{formatBytes(total)}</span>
- </div>
- );
- }
-
- return (
- <div className="disk-usage-bar-container">
- <div className="disk-usage-header">
- <HardDrive size={14} />
- <span className="disk-usage-total">{formatBytes(total)}</span>
- </div>
-
- <div className="disk-usage-bar">
- <div
- className={`disk-usage-segment wordpress ${colorClass}`}
- style={{ width: `${wpPercent}%` }}
- title={`WordPress: ${formatBytes(wordpress)}`}
- />
- <div
- className="disk-usage-segment mysql"
- style={{ width: `${dbPercent}%` }}
- title={`MySQL: ${formatBytes(mysql)}`}
- />
- <div
- className="disk-usage-segment snapshots"
- style={{ width: `${snapPercent}%` }}
- title={`Snapshots: ${formatBytes(snapshots)}`}
- />
- </div>
-
- {showBreakdown && (
- <div className="disk-usage-legend">
- <div className="disk-usage-legend-item">
- <span className="disk-usage-legend-dot wordpress" />
- <span>WordPress {formatBytes(wordpress)}</span>
- </div>
- <div className="disk-usage-legend-item">
- <span className="disk-usage-legend-dot mysql" />
- <span>MySQL {formatBytes(mysql)}</span>
- </div>
- <div className="disk-usage-legend-item">
- <span className="disk-usage-legend-dot snapshots" />
- <span>Snapshots {formatBytes(snapshots)}</span>
- </div>
- </div>
- )}
- </div>
- );
-};
-
-export default DiskUsageBar;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/EnvironmentCard.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/EnvironmentCard.jsx
deleted file mode 100644
index 28a7348f..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/EnvironmentCard.jsx
+++ /dev/null
@@ -1,232 +0,0 @@
-import { useState } from 'react';
-import { ExternalLink, RefreshCw, Trash2, GitBranch, Clock, AlertTriangle, Calendar, FileText } from 'lucide-react';
-import { ConfirmDialog } from 'serverkit-sdk';
-import { Pill, EnvTag } from 'serverkit-sdk';
-
-const EnvironmentCard = ({ environment, productionUrl, onSync, onDelete, onViewLogs, isProduction = false }) => {
- const [syncing, setSyncing] = useState(false);
- const [deleting, setDeleting] = useState(false);
- const [showSyncConfirm, setShowSyncConfirm] = useState(false);
- const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
-
- const isRunning = environment.status === 'running';
- const envType = environment.type || environment.environment_type || (isProduction ? 'production' : 'development');
-
- // Helper functions
- function formatDate(dateString) {
- if (!dateString) return null;
- return new Date(dateString).toLocaleDateString();
- }
-
- function formatRelativeTime(dateString) {
- if (!dateString) return null;
- const date = new Date(dateString);
- const now = new Date();
- const diffMs = now - date;
- const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
-
- if (diffDays === 0) return 'Today';
- if (diffDays === 1) return 'Yesterday';
- if (diffDays < 7) return `${diffDays} days ago`;
- if (diffDays < 30) return `${Math.floor(diffDays / 7)} week(s) ago`;
- return `${Math.floor(diffDays / 30)} month(s) ago`;
- }
-
- function isStale() {
- if (!environment.last_sync || isProduction) return false;
- const lastSync = new Date(environment.last_sync);
- const now = new Date();
- const diffDays = Math.floor((now - lastSync) / (1000 * 60 * 60 * 24));
- return diffDays > 7; // Consider stale if not synced in 7 days
- }
-
- function formatSchedule(schedule) {
- if (!schedule) return null;
- const scheduleMap = {
- '0 3 * * 0': 'Weekly (Sunday 3am)',
- '0 3 * * *': 'Daily (3am)',
- '0 0 * * 0': 'Weekly (Sunday midnight)',
- '0 0 * * *': 'Daily (midnight)'
- };
- return scheduleMap[schedule] || schedule;
- }
-
- const stale = isStale();
-
- async function handleSync() {
- setShowSyncConfirm(false);
- setSyncing(true);
- try {
- await onSync?.(environment.id);
- } finally {
- setSyncing(false);
- }
- }
-
- async function handleDelete() {
- setShowDeleteConfirm(false);
- setDeleting(true);
- try {
- await onDelete?.(environment.id);
- } finally {
- setDeleting(false);
- }
- }
-
- function handleVisit() {
- if (environment.url) {
- window.open(environment.url, '_blank');
- }
- }
-
- const envTagLabel = envType === 'production' ? 'PROD'
- : envType === 'staging' ? 'STAGING'
- : envType === 'multidev' ? 'MULTIDEV'
- : 'DEV';
-
- return (
- <div className={`wp-env-card ${isProduction ? 'production' : ''} ${stale ? 'stale' : ''}`}>
- <div className="wp-env-header">
- <div className="wp-env-info">
- <EnvTag env={envTagLabel} />
- <h4 className="wp-env-name">{environment.name}</h4>
- </div>
- <div className="wp-env-status-group">
- {stale && (
- <span className="wp-env-stale-badge" title="Environment hasn't been synced in over 7 days">
- <AlertTriangle size={12} />
- Stale
- </span>
- )}
- <Pill kind={isRunning ? 'green' : 'gray'}>{isRunning ? 'Running' : 'Stopped'}</Pill>
- </div>
- </div>
-
- <div className="wp-env-body">
- {environment.url && (
- <div className="wp-env-url">
- <a href={environment.url} target="_blank" rel="noopener noreferrer">
- {environment.url}
- </a>
- </div>
- )}
-
- <div className="wp-env-meta">
- {environment.db_name && (
- <div className="wp-env-meta-item">
- <span className="meta-label">Database</span>
- <span className="meta-value mono">{environment.db_name}</span>
- </div>
- )}
- {environment.commit_sha && (
- <div className="wp-env-meta-item">
- <span className="meta-label">
- <GitBranch size={12} /> Commit
- </span>
- <span className="meta-value mono">{environment.commit_sha.substring(0, 7)}</span>
- </div>
- )}
- {!isProduction && environment.last_sync && (
- <div className="wp-env-meta-item">
- <span className="meta-label">
- <Clock size={12} /> Last Sync
- </span>
- <span className={`meta-value ${stale ? 'text-warning' : ''}`}>
- {formatRelativeTime(environment.last_sync)}
- </span>
- </div>
- )}
- {!isProduction && environment.sync_schedule && (
- <div className="wp-env-meta-item">
- <span className="meta-label">
- <Calendar size={12} /> Schedule
- </span>
- <span className="meta-value">
- {formatSchedule(environment.sync_schedule)}
- </span>
- </div>
- )}
- </div>
- </div>
-
- <div className="wp-env-footer">
- <button type="button"
- className="btn btn-ghost btn-sm"
- onClick={handleVisit}
- disabled={!environment.url}
- >
- <ExternalLink size={14} />
- Visit
- </button>
-
- {!isProduction && (
- <>
- <button type="button"
- className="btn btn-ghost btn-sm"
- onClick={() => setShowSyncConfirm(true)}
- disabled={syncing || !productionUrl}
- title="Sync from production"
- >
- <RefreshCw size={14} className={syncing ? 'spinning' : ''} />
- {syncing ? 'Syncing...' : 'Sync'}
- </button>
- {onViewLogs && (
- <button type="button"
- className="btn btn-ghost btn-sm"
- onClick={() => onViewLogs?.(environment.id)}
- title="View sync logs"
- >
- <FileText size={14} />
- Logs
- </button>
- )}
- <button type="button"
- className="btn btn-ghost btn-sm btn-danger"
- onClick={() => setShowDeleteConfirm(true)}
- disabled={deleting}
- >
- <Trash2 size={14} />
- {deleting ? 'Deleting...' : 'Delete'}
- </button>
- </>
- )}
- </div>
-
- <ConfirmDialog
- isOpen={showSyncConfirm}
- title="Sync from Production"
- message={`Sync "${environment.name}" from production?`}
- details={
- <ul>
- <li><strong>Warning:</strong> This will overwrite the current database</li>
- <li>All data in this environment will be replaced with production data</li>
- <li>URLs will be automatically updated for this environment</li>
- </ul>
- }
- confirmText="Sync Now"
- variant="warning"
- onConfirm={handleSync}
- onCancel={() => setShowSyncConfirm(false)}
- />
-
- <ConfirmDialog
- isOpen={showDeleteConfirm}
- title={`Delete ${envType.charAt(0).toUpperCase() + envType.slice(1)} Environment`}
- message={`Are you sure you want to delete "${environment.name}"?`}
- details={
- <ul>
- <li>All environment files will be permanently deleted</li>
- <li>Database <code>{environment.db_name || 'associated database'}</code> will be removed</li>
- <li>This action cannot be undone</li>
- </ul>
- }
- confirmText="Delete Environment"
- variant="danger"
- onConfirm={handleDelete}
- onCancel={() => setShowDeleteConfirm(false)}
- />
- </div>
- );
-};
-
-export default EnvironmentCard;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/EnvironmentStatusBadge.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/EnvironmentStatusBadge.jsx
deleted file mode 100644
index 6b4c5289..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/EnvironmentStatusBadge.jsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import { Lock } from 'lucide-react';
-
-const EnvironmentStatusBadge = ({ type, status, isLocked }) => {
- function getTypeBadgeClass() {
- switch (type) {
- case 'production': return 'env-production';
- case 'staging': return 'env-staging';
- case 'multidev': return 'env-multidev';
- default: return 'env-development';
- }
- }
-
- const isRunning = status === 'running';
-
- return (
- <div className="env-status-badge-group">
- <span className={`wp-env-badge ${getTypeBadgeClass()}`}>
- {type?.toUpperCase() || 'DEV'}
- </span>
- {isLocked && (
- <span className="env-locked-badge" title="Environment is locked">
- <Lock size={10} />
- </span>
- )}
- <span className={`wp-env-status ${isRunning ? 'running' : 'stopped'}`}>
- <span className="status-dot" />
- {isRunning ? 'Running' : 'Stopped'}
- </span>
- </div>
- );
-};
-
-export default EnvironmentStatusBadge;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/GitConnectForm.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/GitConnectForm.jsx
deleted file mode 100644
index e544d288..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/GitConnectForm.jsx
+++ /dev/null
@@ -1,21 +0,0 @@
-// WordPress-flavored wrapper over the shared RepoConnectForm: same form, just
-// pre-dressed with the WordPress intro copy and the wp-content tracked-path
-// defaults. The reusable component lives in components/git/RepoConnectForm.jsx.
-import RepoConnectForm from '@/components/git/RepoConnectForm';
-
-const GitConnectForm = (props) => (
- <RepoConnectForm
- {...props}
- idPrefix="wp"
- intro={{
- title: 'Connect a Git repository',
- subtitle: 'Manage themes and plugins for this site with version control — push to deploy.',
- }}
- showPaths
- defaultPaths={['wp-content/themes', 'wp-content/plugins']}
- pathsLabel="Tracked paths"
- pathsHint="Paths relative to the WordPress root that should be tracked."
- />
-);
-
-export default GitConnectForm;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/HealthStatusPanel.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/HealthStatusPanel.jsx
deleted file mode 100644
index 1256dc49..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/HealthStatusPanel.jsx
+++ /dev/null
@@ -1,137 +0,0 @@
-import { useState, useEffect, useRef } from 'react';
-import { Activity, RefreshCw, CheckCircle, AlertTriangle, XCircle, HelpCircle } from 'lucide-react';
-import { Spinner } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-
-const STATUS_CONFIG = {
- healthy: { icon: CheckCircle, color: 'green', label: 'Healthy' },
- degraded: { icon: AlertTriangle, color: 'yellow', label: 'Degraded' },
- unhealthy: { icon: XCircle, color: 'red', label: 'Unhealthy' },
- unknown: { icon: HelpCircle, color: 'gray', label: 'Unknown' },
-};
-
-const HealthDot = ({ status, size = 8 }) => {
- const colorMap = {
- healthy: 'var(--green, #3ddc97)',
- degraded: 'var(--amber, #f5b945)',
- unhealthy: 'var(--red, #fb6f6f)',
- unknown: 'var(--text-faint, #646b7a)',
- };
-
- return (
- <span
- className={`health-dot health-dot-${status}`}
- style={{
- width: size,
- height: size,
- borderRadius: '50%',
- display: 'inline-block',
- backgroundColor: colorMap[status] || colorMap.unknown,
- }}
- title={STATUS_CONFIG[status]?.label || 'Unknown'}
- />
- );
-};
-
-const HealthStatusPanel = ({ projectId, environments, api, compact = false }) => {
- const [healthData, setHealthData] = useState({});
- const [loading, setLoading] = useState(true);
- const intervalRef = useRef(null);
-
- useEffect(() => {
- loadHealth();
-
- // Auto-refresh every 30 seconds
- intervalRef.current = setInterval(loadHealth, 30000);
-
- return () => {
- if (intervalRef.current) clearInterval(intervalRef.current);
- };
- }, [projectId]);
-
- async function loadHealth() {
- try {
- const data = await api.getProjectHealth(projectId);
- if (data.success) {
- setHealthData(data.environments || {});
- }
- } catch {
- // Silently fail - health checks are optional
- } finally {
- setLoading(false);
- }
- }
-
- if (compact) {
- return null; // Dots are rendered directly via HealthDot export
- }
-
- if (loading) {
- return (
- <div className="health-status-panel">
- <div className="health-panel-loading">
- <Spinner size="sm" />
- <span>Checking health...</span>
- </div>
- </div>
- );
- }
-
- return (
- <div className="health-status-panel">
- <div className="health-panel-header">
- <h4>
- <Activity size={16} />
- Environment Health
- </h4>
- <Button variant="ghost" size="sm" onClick={loadHealth}>
- <RefreshCw size={12} />
- Refresh
- </Button>
- </div>
-
- <div className="health-panel-grid">
- {Object.entries(healthData).map(([envId, data]) => {
- const env = environments?.find(e => String(e.id) === String(envId));
- const envName = env?.name || `Environment ${envId}`;
- const overall = data?.overall_status || 'unknown';
- const checks = data?.checks || {};
-
- return (
- <div key={envId} className="health-panel-env">
- <div className="health-panel-env-header">
- <HealthDot status={overall} size={10} />
- <span className="health-panel-env-name">{envName}</span>
- <span className={`health-panel-overall health-${overall}`}>
- {STATUS_CONFIG[overall]?.label || 'Unknown'}
- </span>
- </div>
- <div className="health-panel-checks">
- {Object.entries(checks).map(([checkName, checkData]) => (
- <div key={checkName} className="health-panel-check">
- <HealthDot status={checkData.status} size={6} />
- <span className="health-panel-check-name">
- {checkName.charAt(0).toUpperCase() + checkName.slice(1)}
- </span>
- <span className="health-panel-check-msg">
- {checkData.message}
- </span>
- </div>
- ))}
- </div>
- </div>
- );
- })}
- </div>
-
- {Object.keys(healthData).length === 0 && (
- <div className="health-panel-empty">
- No health data available
- </div>
- )}
- </div>
- );
-};
-
-export { HealthDot };
-export default HealthStatusPanel;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/PipelineView.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/PipelineView.jsx
deleted file mode 100644
index fe2fe7a7..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/PipelineView.jsx
+++ /dev/null
@@ -1,589 +0,0 @@
-import { useState } from 'react';
-import {
- ExternalLink, Play, Square, RefreshCw, ArrowRight,
- ArrowDownLeft, Lock, Unlock, FileText, Trash2, MoreVertical,
- GitBranch, Plus, GitCompare, Cpu, Shield, Terminal, Clock,
- HardDrive, Settings
-} from 'lucide-react';
-import EnvironmentStatusBadge from './EnvironmentStatusBadge';
-import { HealthDot } from './HealthStatusPanel';
-import DiskUsageBar from './DiskUsageBar';
-import { Button } from 'serverkit-sdk';
-import { Checkbox } from 'serverkit-sdk';
-import { formatRelativeTime } from 'serverkit-sdk';
-
-const PipelineView = ({
- pipeline,
- onPromote,
- onSync,
- onStart,
- onStop,
- onRestart,
- onDelete,
- onLock,
- onUnlock,
- onViewLogs,
- onCreateMultidev,
- onCompare,
- onResourceLimits,
- onBasicAuth,
- onWpCli,
- onAutoSync,
- onHealthCheck,
- operationInProgress,
- healthData,
- diskUsageData,
- bulkSelected,
- onBulkToggle,
-}) => {
- if (!pipeline) return null;
-
- const { production, environments = [] } = pipeline;
- const devEnv = environments.find(e => e.environment_type === 'development');
- const stagingEnv = environments.find(e => e.environment_type === 'staging');
- const multidevEnvs = environments.filter(e => e.environment_type === 'multidev');
-
- return (
- <div className="pipeline-view">
- <div className="pipeline-row">
- {/* Development */}
- {devEnv ? (
- <PipelineCard
- env={devEnv}
- onStart={onStart}
- onStop={onStop}
- onRestart={onRestart}
- onDelete={onDelete}
- onLock={onLock}
- onUnlock={onUnlock}
- onViewLogs={onViewLogs}
- onResourceLimits={onResourceLimits}
- onBasicAuth={onBasicAuth}
- onWpCli={onWpCli}
- onAutoSync={onAutoSync}
- onHealthCheck={onHealthCheck}
- operationInProgress={operationInProgress}
- healthStatus={healthData?.[devEnv.id]?.overall_status}
- diskUsage={diskUsageData?.[devEnv.id]?.usage}
- bulkSelected={bulkSelected?.includes(devEnv.id)}
- onBulkToggle={onBulkToggle}
- />
- ) : (
- <EmptySlot type="development" />
- )}
-
- {/* Arrow: Dev -> Staging (Promote) */}
- <PipelineArrow
- label="Promote"
- direction="forward"
- disabled={!devEnv || !stagingEnv}
- onClick={() => devEnv && stagingEnv && onPromote?.(devEnv, stagingEnv)}
- />
-
- {/* Staging */}
- {stagingEnv ? (
- <PipelineCard
- env={stagingEnv}
- onStart={onStart}
- onStop={onStop}
- onRestart={onRestart}
- onDelete={onDelete}
- onLock={onLock}
- onUnlock={onUnlock}
- onViewLogs={onViewLogs}
- onResourceLimits={onResourceLimits}
- onBasicAuth={onBasicAuth}
- onWpCli={onWpCli}
- onAutoSync={onAutoSync}
- onHealthCheck={onHealthCheck}
- operationInProgress={operationInProgress}
- healthStatus={healthData?.[stagingEnv.id]?.overall_status}
- diskUsage={diskUsageData?.[stagingEnv.id]?.usage}
- bulkSelected={bulkSelected?.includes(stagingEnv.id)}
- onBulkToggle={onBulkToggle}
- />
- ) : (
- <EmptySlot type="staging" />
- )}
-
- {/* Arrow: Staging -> Production (Promote) */}
- <PipelineArrow
- label="Promote"
- direction="forward"
- disabled={!stagingEnv}
- onClick={() => stagingEnv && production && onPromote?.(stagingEnv, production)}
- />
-
- {/* Production */}
- {production && (
- <PipelineCard
- env={production}
- isProduction
- onStart={onStart}
- onStop={onStop}
- onRestart={onRestart}
- onLock={onLock}
- onUnlock={onUnlock}
- onViewLogs={onViewLogs}
- onResourceLimits={onResourceLimits}
- onBasicAuth={onBasicAuth}
- onWpCli={onWpCli}
- onHealthCheck={onHealthCheck}
- operationInProgress={operationInProgress}
- healthStatus={healthData?.[production.id]?.overall_status}
- diskUsage={diskUsageData?.[production.id]?.usage}
- />
- )}
- </div>
-
- {/* Sync arrows (below, reversed) */}
- <div className="pipeline-sync-row">
- {devEnv && (
- <div className="pipeline-sync-action">
- <Button
- variant="ghost"
- size="sm"
- onClick={() => onSync?.(devEnv)}
- title="Pull production data into development"
- >
- <ArrowDownLeft size={14} />
- Pull from Prod
- </Button>
- </div>
- )}
- {stagingEnv && (
- <div className="pipeline-sync-action">
- <Button
- variant="ghost"
- size="sm"
- onClick={() => onSync?.(stagingEnv)}
- title="Pull production data into staging"
- >
- <ArrowDownLeft size={14} />
- Pull from Prod
- </Button>
- </div>
- )}
- </div>
-
- {/* Compare row */}
- {onCompare && (devEnv || stagingEnv) && production && (
- <div className="pipeline-compare-row">
- {devEnv && (
- <Button
- variant="ghost"
- size="sm"
- className="pipeline-compare-btn"
- onClick={() => onCompare(devEnv, production)}
- title="Compare development vs production"
- >
- <GitCompare size={14} />
- Compare vs Prod
- </Button>
- )}
- {stagingEnv && (
- <Button
- variant="ghost"
- size="sm"
- className="pipeline-compare-btn"
- onClick={() => onCompare(stagingEnv, production)}
- title="Compare staging vs production"
- >
- <GitCompare size={14} />
- Compare vs Prod
- </Button>
- )}
- {devEnv && stagingEnv && (
- <Button
- variant="ghost"
- size="sm"
- className="pipeline-compare-btn"
- onClick={() => onCompare(devEnv, stagingEnv)}
- title="Compare development vs staging"
- >
- <GitCompare size={14} />
- Dev vs Staging
- </Button>
- )}
- </div>
- )}
-
- {/* Multidev section */}
- <div className="pipeline-multidev-section">
- <div className="pipeline-section-header">
- <h4 className="pipeline-section-title">
- <GitBranch size={16} />
- Multidev Environments
- {multidevEnvs.length > 0 && (
- <span className="pipeline-section-count">{multidevEnvs.length}</span>
- )}
- </h4>
- <Button
- variant="ghost"
- size="sm"
- onClick={onCreateMultidev}
- >
- <Plus size={14} />
- New Multidev
- </Button>
- </div>
- {multidevEnvs.length > 0 ? (
- <div className="pipeline-multidev-grid">
- {multidevEnvs.map(env => (
- <MultidevCard
- key={env.id}
- env={env}
- onStart={onStart}
- onStop={onStop}
- onRestart={onRestart}
- onDelete={onDelete}
- onPromote={onPromote}
- onSync={onSync}
- onLock={onLock}
- onUnlock={onUnlock}
- onViewLogs={onViewLogs}
- devEnv={devEnv}
- stagingEnv={stagingEnv}
- production={production}
- />
- ))}
- </div>
- ) : (
- <div className="pipeline-multidev-empty">
- <GitBranch size={24} />
- <p>No multidev environments yet</p>
- <span>Create branch-based environments for feature development and testing</span>
- <Button size="sm" onClick={onCreateMultidev}>
- <Plus size={14} />
- Create Multidev
- </Button>
- </div>
- )}
- </div>
- </div>
- );
-};
-
-const PipelineCard = ({
- env,
- isProduction = false,
- onStart,
- onStop,
- onRestart,
- onDelete,
- onLock,
- onUnlock,
- onViewLogs,
- onResourceLimits,
- onBasicAuth,
- onWpCli,
- onAutoSync,
- onHealthCheck,
- operationInProgress,
- healthStatus,
- diskUsage,
- bulkSelected,
- onBulkToggle,
-}) => {
- const [showMenu, setShowMenu] = useState(false);
- const isRunning = env.status === 'running' || env.application?.status === 'running';
- const envType = env.environment_type || (isProduction ? 'production' : 'development');
- const domain = env.application?.domains?.[0] || env.url || '';
-
- return (
- <div className={`pipeline-card ${isProduction ? 'production' : ''} ${env.is_locked ? 'locked' : ''}`}>
- <div className="pipeline-card-header">
- {onBulkToggle && !isProduction && (
- <Checkbox
- className="pipeline-card-checkbox"
- checked={bulkSelected || false}
- onCheckedChange={() => onBulkToggle(env.id)}
- />
- )}
- <EnvironmentStatusBadge
- type={envType}
- status={isRunning ? 'running' : 'stopped'}
- isLocked={env.is_locked}
- />
- {healthStatus && (
- <HealthDot status={healthStatus} size={8} />
- )}
- <div className="pipeline-card-menu-wrapper">
- <Button
- variant="ghost"
- size="sm"
- className="pipeline-card-menu-btn"
- onClick={() => setShowMenu(!showMenu)}
- >
- <MoreVertical size={14} />
- </Button>
- {showMenu && (
- <div className="pipeline-card-menu" onMouseLeave={() => setShowMenu(false)}>
- {isRunning ? (
- <>
- <button type="button" onClick={() => { onStop?.(env); setShowMenu(false); }}>
- <Square size={12} /> Stop
- </button>
- <button type="button" onClick={() => { onRestart?.(env); setShowMenu(false); }}>
- <RefreshCw size={12} /> Restart
- </button>
- </>
- ) : (
- <button type="button" onClick={() => { onStart?.(env); setShowMenu(false); }}>
- <Play size={12} /> Start
- </button>
- )}
- <button type="button" onClick={() => { onViewLogs?.(env); setShowMenu(false); }}>
- <FileText size={12} /> Logs
- </button>
- <div className="pipeline-card-menu-divider" />
- <button type="button" onClick={() => { onResourceLimits?.(env); setShowMenu(false); }}>
- <Cpu size={12} /> Resources
- </button>
- <button type="button" onClick={() => { onBasicAuth?.(env); setShowMenu(false); }}>
- <Shield size={12} /> Basic Auth
- </button>
- <button type="button" onClick={() => { onWpCli?.(env); setShowMenu(false); }}>
- <Terminal size={12} /> WP-CLI
- </button>
- {!isProduction && onAutoSync && (
- <button type="button" onClick={() => { onAutoSync?.(env); setShowMenu(false); }}>
- <Clock size={12} /> Auto-Sync
- </button>
- )}
- <div className="pipeline-card-menu-divider" />
- {env.is_locked ? (
- <button type="button" onClick={() => { onUnlock?.(env); setShowMenu(false); }}>
- <Unlock size={12} /> Unlock
- </button>
- ) : (
- <button type="button" onClick={() => { onLock?.(env); setShowMenu(false); }}>
- <Lock size={12} /> Lock
- </button>
- )}
- {!isProduction && (
- <button type="button" className="danger" onClick={() => { onDelete?.(env); setShowMenu(false); }}>
- <Trash2 size={12} /> Delete
- </button>
- )}
- </div>
- )}
- </div>
- </div>
-
- <div className="pipeline-card-body">
- <h4 className="pipeline-card-name">{env.name}</h4>
- {domain && (
- <a
- href={domain.startsWith('http') ? domain : `https://${domain}`}
- target="_blank"
- rel="noopener noreferrer"
- className="pipeline-card-domain"
- >
- {domain}
- </a>
- )}
- <div className="pipeline-card-meta">
- {env.wp_version && (
- <span className="pipeline-meta-item">v{env.wp_version}</span>
- )}
- {env.last_sync && !isProduction && (
- <span className="pipeline-meta-item">
- Synced {formatRelativeTime(env.last_sync)}
- </span>
- )}
- {diskUsage && (
- <DiskUsageBar usage={diskUsage} compact />
- )}
- </div>
- </div>
-
- <div className="pipeline-card-footer">
- {domain && (
- <a
- href={domain.startsWith('http') ? domain : `https://${domain}`}
- target="_blank"
- rel="noopener noreferrer"
- className="btn btn-ghost btn-sm"
- >
- <ExternalLink size={12} /> Visit
- </a>
- )}
- <Button variant="ghost" size="sm" onClick={() => onViewLogs?.(env)}>
- <FileText size={12} /> Logs
- </Button>
- </div>
-
- {env.is_locked && env.locked_reason && (
- <div className="alert alert-warning">
- <Lock size={10} />
- <span>{env.locked_reason}</span>
- </div>
- )}
- </div>
- );
-};
-
-const PipelineArrow = ({ label, direction, disabled, onClick }) => {
- return (
- <div className={`pipeline-arrow ${disabled ? 'disabled' : ''}`}>
- <button type="button"
- className="pipeline-arrow-btn"
- onClick={onClick}
- disabled={disabled}
- title={disabled ? 'Environment not available' : label}
- >
- <ArrowRight size={16} />
- <span className="pipeline-arrow-label">{label}</span>
- </button>
- </div>
- );
-};
-
-const EmptySlot = ({ type }) => {
- return (
- <div className="pipeline-card empty">
- <div className="pipeline-empty-content">
- <span className={`wp-env-badge env-${type}`}>
- {type.toUpperCase()}
- </span>
- <p>No {type} environment</p>
- </div>
- </div>
- );
-};
-
-const MultidevCard = ({
- env, onStart, onStop, onRestart, onDelete, onPromote,
- onSync, onLock, onUnlock, onViewLogs,
- devEnv, stagingEnv, production
-}) => {
- const [showMenu, setShowMenu] = useState(false);
- const isRunning = env.status === 'running' || env.application?.status === 'running';
- const domain = env.application?.domains?.[0] || env.url || '';
-
- const promoteTarget = devEnv || stagingEnv || production;
-
- return (
- <div className={`multidev-card ${env.is_locked ? 'locked' : ''}`}>
- <div className="multidev-card-header">
- <div className="multidev-card-header-left">
- <span className="wp-env-badge env-multidev">MULTIDEV</span>
- <span className={`wp-env-status ${isRunning ? 'running' : 'stopped'}`}>
- <span className="status-dot" />
- {isRunning ? 'Running' : 'Stopped'}
- </span>
- {env.is_locked && (
- <Lock size={12} className="multidev-lock-icon" />
- )}
- </div>
- <div className="multidev-card-menu-wrapper">
- <Button
- variant="ghost"
- size="sm"
- onClick={() => setShowMenu(!showMenu)}
- >
- <MoreVertical size={14} />
- </Button>
- {showMenu && (
- <div className="pipeline-card-menu" onMouseLeave={() => setShowMenu(false)}>
- {isRunning ? (
- <>
- <button type="button" onClick={() => { onStop?.(env); setShowMenu(false); }}>
- <Square size={12} /> Stop
- </button>
- <button type="button" onClick={() => { onRestart?.(env); setShowMenu(false); }}>
- <RefreshCw size={12} /> Restart
- </button>
- </>
- ) : (
- <button type="button" onClick={() => { onStart?.(env); setShowMenu(false); }}>
- <Play size={12} /> Start
- </button>
- )}
- <button type="button" onClick={() => { onSync?.(env); setShowMenu(false); }}>
- <ArrowDownLeft size={12} /> Sync from Prod
- </button>
- <button type="button" onClick={() => { onViewLogs?.(env); setShowMenu(false); }}>
- <FileText size={12} /> Logs
- </button>
- {env.is_locked ? (
- <button type="button" onClick={() => { onUnlock?.(env); setShowMenu(false); }}>
- <Unlock size={12} /> Unlock
- </button>
- ) : (
- <button type="button" onClick={() => { onLock?.(env); setShowMenu(false); }}>
- <Lock size={12} /> Lock
- </button>
- )}
- <button type="button" className="danger" onClick={() => { onDelete?.(env); setShowMenu(false); }}>
- <Trash2 size={12} /> Delete
- </button>
- </div>
- )}
- </div>
- </div>
- <div className="multidev-card-body">
- <h5 className="multidev-card-name">{env.name}</h5>
- {env.multidev_branch && (
- <span className="multidev-branch">
- <GitBranch size={12} />
- {env.multidev_branch}
- </span>
- )}
- {domain && (
- <a
- href={domain.startsWith('http') ? domain : `https://${domain}`}
- target="_blank"
- rel="noopener noreferrer"
- className="multidev-domain"
- >
- {domain}
- </a>
- )}
- <div className="multidev-card-meta">
- {env.created_at && (
- <span className="multidev-meta-item">
- Created {formatRelativeTime(env.created_at)}
- </span>
- )}
- </div>
- </div>
- <div className="multidev-card-footer">
- {domain && (
- <a
- href={domain.startsWith('http') ? domain : `https://${domain}`}
- target="_blank"
- rel="noopener noreferrer"
- className="btn btn-ghost btn-sm"
- >
- <ExternalLink size={12} /> Visit
- </a>
- )}
- <Button
- variant="ghost"
- size="sm"
- onClick={() => promoteTarget && onPromote?.(env, promoteTarget)}
- disabled={!promoteTarget}
- title={promoteTarget ? `Promote to ${promoteTarget.environment_type || 'production'}` : 'No target environment'}
- >
- <ArrowRight size={12} /> Promote
- </Button>
- <Button variant="ghost" size="icon" onClick={() => onViewLogs?.(env)}>
- <FileText size={12} />
- </Button>
- <Button variant="destructive" size="icon" onClick={() => onDelete?.(env)}>
- <Trash2 size={12} />
- </Button>
- </div>
- {env.is_locked && env.locked_reason && (
- <div className="alert alert-warning">
- <Lock size={10} />
- <span>{env.locked_reason}</span>
- </div>
- )}
- </div>
- );
-};
-
-export default PipelineView;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/PromoteModal.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/PromoteModal.jsx
deleted file mode 100644
index bebaabb3..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/PromoteModal.jsx
+++ /dev/null
@@ -1,270 +0,0 @@
-import { useState, useEffect } from 'react';
-import { ArrowRight, Shield } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { Spinner } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from 'serverkit-sdk';
-import { Checkbox } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-
-const PromoteModal = ({ sourceEnv, targetEnv, onClose, onPromote }) => {
- const [promotionType, setPromotionType] = useState('code');
- const [config, setConfig] = useState({
- include_plugins: true,
- include_themes: true,
- include_mu_plugins: true,
- include_uploads: false,
- backup_target_first: true,
- sanitize: false,
- sanitization_profile_id: '',
- exclude_tables: '',
- truncate_tables: ''
- });
- const [loading, setLoading] = useState(false);
- const [profiles, setProfiles] = useState([]);
-
- useEffect(() => {
- loadProfiles();
- }, []);
-
- async function loadProfiles() {
- try {
- const data = await wordpressApi.getSanitizationProfiles();
- setProfiles(data.profiles || []);
- const defaultProfile = (data.profiles || []).find(p => p.is_default);
- if (defaultProfile) {
- setConfig(prev => ({ ...prev, sanitization_profile_id: String(defaultProfile.id) }));
- }
- } catch {
- setProfiles([]);
- }
- }
-
- async function handleSubmit(e) {
- e.preventDefault();
- setLoading(true);
- try {
- const submitConfig = { ...config };
- if (submitConfig.sanitization_profile_id) {
- submitConfig.sanitization_profile_id = Number(submitConfig.sanitization_profile_id);
- } else {
- delete submitConfig.sanitization_profile_id;
- }
- const toList = (s) => (s || '').split(',').map(t => t.trim()).filter(Boolean);
- submitConfig.exclude_tables = toList(config.exclude_tables);
- submitConfig.truncate_tables = toList(config.truncate_tables);
- await onPromote({
- source_env_id: sourceEnv.id,
- target_env_id: targetEnv.id,
- type: promotionType,
- config: submitConfig
- });
- } finally {
- setLoading(false);
- }
- }
-
- function handleConfigChange(key, value) {
- setConfig(prev => ({ ...prev, [key]: value }));
- }
-
- const sourceType = sourceEnv.environment_type || 'development';
- const targetType = targetEnv.environment_type || 'staging';
-
- return (
- <Modal open={true} onClose={onClose} title="Promote Environment" size="lg">
- <form onSubmit={handleSubmit}>
- <div className="promote-direction">
- <div className={`promote-env-pill ${sourceType}`}>
- <span className="promote-env-type">{sourceType}</span>
- <span className="promote-env-name">{sourceEnv.name}</span>
- </div>
- <ArrowRight size={20} className="promote-arrow" />
- <div className={`promote-env-pill ${targetType}`}>
- <span className="promote-env-type">{targetType}</span>
- <span className="promote-env-name">{targetEnv.name}</span>
- </div>
- </div>
-
- <div className="form-group">
- <Label>Promotion Type</Label>
- <div className="radio-group">
- <label className="radio-label">
- <input
- type="radio"
- name="promotionType"
- value="code"
- checked={promotionType === 'code'}
- onChange={e => setPromotionType(e.target.value)}
- />
- <div className="radio-content">
- <strong>Code Only</strong>
- <span>Sync themes, plugins, and mu-plugins via rsync</span>
- </div>
- </label>
- <label className="radio-label">
- <input
- type="radio"
- name="promotionType"
- value="database"
- checked={promotionType === 'database'}
- onChange={e => setPromotionType(e.target.value)}
- />
- <div className="radio-content">
- <strong>Database Only</strong>
- <span>Export, transform, and import database</span>
- </div>
- </label>
- <label className="radio-label">
- <input
- type="radio"
- name="promotionType"
- value="full"
- checked={promotionType === 'full'}
- onChange={e => setPromotionType(e.target.value)}
- />
- <div className="radio-content">
- <strong>Full (Code + Database)</strong>
- <span>Complete environment promotion</span>
- </div>
- </label>
- </div>
- </div>
-
- {(promotionType === 'code' || promotionType === 'full') && (
- <div className="form-group">
- <Label>Code Options</Label>
- <div className="checkbox-group">
- <label className="checkbox-label">
- <Checkbox
- checked={config.include_plugins}
- onCheckedChange={v => handleConfigChange('include_plugins', v)}
- />
- <span>Include plugins</span>
- </label>
- <label className="checkbox-label">
- <Checkbox
- checked={config.include_themes}
- onCheckedChange={v => handleConfigChange('include_themes', v)}
- />
- <span>Include themes</span>
- </label>
- <label className="checkbox-label">
- <Checkbox
- checked={config.include_mu_plugins}
- onCheckedChange={v => handleConfigChange('include_mu_plugins', v)}
- />
- <span>Include mu-plugins</span>
- </label>
- <label className="checkbox-label">
- <Checkbox
- checked={config.include_uploads}
- onCheckedChange={v => handleConfigChange('include_uploads', v)}
- />
- <span>Include uploads (media files)</span>
- </label>
- </div>
- </div>
- )}
-
- {(promotionType === 'database' || promotionType === 'full') && (
- <>
- <div className="form-group">
- <label className="checkbox-label">
- <Checkbox
- checked={config.sanitize}
- onCheckedChange={v => handleConfigChange('sanitize', v)}
- />
- <span>Sanitize database during promotion</span>
- </label>
- </div>
-
- {config.sanitize && profiles.length > 0 && (
- <div className="form-group">
- <Label>
- <Shield size={14} style={{ marginRight: 4, verticalAlign: -2 }} />
- Sanitization Profile
- </Label>
- <Select
- value={config.sanitization_profile_id}
- onValueChange={v => handleConfigChange('sanitization_profile_id', v)}
- >
- <SelectTrigger>
- <SelectValue placeholder="Manual configuration" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="">Manual configuration</SelectItem>
- {profiles.map(p => (
- <SelectItem key={p.id} value={String(p.id)}>
- {p.name}{p.is_default ? ' (default)' : ''}{p.is_builtin ? '' : ' (custom)'}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- {config.sanitization_profile_id && (
- <span className="form-hint">
- {profiles.find(p => String(p.id) === config.sanitization_profile_id)?.description || ''}
- </span>
- )}
- </div>
- )}
-
- <div className="form-group">
- <Label>Exclude tables (optional)</Label>
- <Input
- value={config.exclude_tables}
- onChange={e => handleConfigChange('exclude_tables', e.target.value)}
- placeholder="e.g. wp_statistics, wp_actionscheduler_logs"
- />
- <span className="form-hint">Comma-separated table names to omit from the promotion entirely.</span>
- </div>
- <div className="form-group">
- <Label>Truncate tables (optional)</Label>
- <Input
- value={config.truncate_tables}
- onChange={e => handleConfigChange('truncate_tables', e.target.value)}
- placeholder="e.g. wp_sessions, wp_woocommerce_log"
- />
- <span className="form-hint">Comma-separated tables to keep but empty (structure promoted, rows dropped).</span>
- </div>
- </>
- )}
-
- <div className="form-group">
- <label className="checkbox-label">
- <Checkbox
- checked={config.backup_target_first}
- onCheckedChange={v => handleConfigChange('backup_target_first', v)}
- />
- <span>Create snapshot of target before promoting</span>
- </label>
- <span className="form-hint">Recommended. Allows rollback if something goes wrong.</span>
- </div>
-
- {targetType === 'production' && (
- <div className="alert alert-warning">
- <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
- <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
- <line x1="12" y1="9" x2="12" y2="13" />
- <line x1="12" y1="17" x2="12.01" y2="17" />
- </svg>
- <span>You are promoting to <strong>production</strong>. This will affect the live site.</span>
- </div>
- )}
-
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose} disabled={loading}>
- Cancel
- </Button>
- <Button type="submit" disabled={loading}>
- {loading ? <><Spinner size="sm" /> Promoting...</> : 'Promote'}
- </Button>
- </div>
- </form>
- </Modal>
- );
-};
-
-export default PromoteModal;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/ResourceLimitsModal.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/ResourceLimitsModal.jsx
deleted file mode 100644
index db45e39d..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/ResourceLimitsModal.jsx
+++ /dev/null
@@ -1,152 +0,0 @@
-import { useState } from 'react';
-import { HardDrive, AlertTriangle } from 'lucide-react';
-import { Spinner } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-
-const PRESETS = {
- low: { memory: '256M', cpus: '0.25', db_memory: '256M', db_cpus: '0.25' },
- standard: { memory: '512M', cpus: '1.0', db_memory: '384M', db_cpus: '0.5' },
- high: { memory: '2G', cpus: '2.0', db_memory: '1G', db_cpus: '1.0' },
-};
-
-const MEMORY_OPTIONS = ['256M', '384M', '512M', '768M', '1G', '1.5G', '2G'];
-const CPU_OPTIONS = ['0.25', '0.5', '1.0', '1.5', '2.0'];
-
-const ResourceLimitsModal = ({ environment, currentLimits, onClose, onApply }) => {
- const [limits, setLimits] = useState({
- memory: currentLimits?.memory || '512M',
- cpus: currentLimits?.cpus || '1.0',
- db_memory: currentLimits?.db_memory || '384M',
- db_cpus: currentLimits?.db_cpus || '0.5',
- });
- const [loading, setLoading] = useState(false);
-
- function applyPreset(preset) {
- setLimits({ ...PRESETS[preset] });
- }
-
- function handleChange(key, value) {
- setLimits(prev => ({ ...prev, [key]: value }));
- }
-
- async function handleSubmit(e) {
- e.preventDefault();
- setLoading(true);
- try {
- await onApply(limits);
- } finally {
- setLoading(false);
- }
- }
-
- const envName = environment?.name || 'Environment';
-
- return (
- <Modal open={true} onClose={onClose} title="Resource Limits" className="resource-limits-modal">
- <form onSubmit={handleSubmit}>
- <div className="resource-limits-env-name">{envName}</div>
-
- <div className="resource-limits-presets">
- <span className="resource-limits-presets-label">Presets:</span>
- {Object.entries(PRESETS).map(([key]) => (
- <Button
- key={key}
- type="button"
- variant="ghost"
- size="sm"
- className="resource-preset-btn"
- onClick={() => applyPreset(key)}
- >
- {key.charAt(0).toUpperCase() + key.slice(1)}
- </Button>
- ))}
- </div>
-
- <div className="resource-limits-section">
- <h4>
- <HardDrive size={14} />
- WordPress Container
- </h4>
- <div className="resource-limits-row">
- <Label>Memory</Label>
- <Select value={limits.memory} onValueChange={v => handleChange('memory', v)}>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {MEMORY_OPTIONS.map(opt => (
- <SelectItem key={opt} value={opt}>{opt}</SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- <div className="resource-limits-row">
- <Label>CPU Cores</Label>
- <Select value={limits.cpus} onValueChange={v => handleChange('cpus', v)}>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {CPU_OPTIONS.map(opt => (
- <SelectItem key={opt} value={opt}>{opt}</SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- </div>
-
- <div className="resource-limits-section">
- <h4>
- <HardDrive size={14} />
- Database Container
- </h4>
- <div className="resource-limits-row">
- <Label>Memory</Label>
- <Select value={limits.db_memory} onValueChange={v => handleChange('db_memory', v)}>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {MEMORY_OPTIONS.filter((_, i) => i < 5).map(opt => (
- <SelectItem key={opt} value={opt}>{opt}</SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- <div className="resource-limits-row">
- <Label>CPU Cores</Label>
- <Select value={limits.db_cpus} onValueChange={v => handleChange('db_cpus', v)}>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {CPU_OPTIONS.filter((_, i) => i < 4).map(opt => (
- <SelectItem key={opt} value={opt}>{opt}</SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- </div>
-
- <div className="alert alert-warning">
- <AlertTriangle size={14} />
- <span>Applying resource limits will restart the environment containers.</span>
- </div>
-
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose} disabled={loading}>
- Cancel
- </Button>
- <Button type="submit" disabled={loading}>
- {loading ? <><Spinner size="sm" /> Applying...</> : 'Apply Limits'}
- </Button>
- </div>
- </form>
- </Modal>
- );
-};
-
-export default ResourceLimitsModal;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/SanitizationProfileForm.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/SanitizationProfileForm.jsx
deleted file mode 100644
index 4d98702c..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/SanitizationProfileForm.jsx
+++ /dev/null
@@ -1,327 +0,0 @@
-import { useState, useEffect } from 'react';
-import { Shield, Plus, Trash2, Star, Edit3, Save } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { Spinner } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { Checkbox } from 'serverkit-sdk';
-
-const SanitizationProfileForm = ({ onClose, onProfilesChange }) => {
- const [profiles, setProfiles] = useState([]);
- const [loading, setLoading] = useState(true);
- const [editingProfile, setEditingProfile] = useState(null);
- const [showCreateForm, setShowCreateForm] = useState(false);
-
- useEffect(() => {
- loadProfiles();
- }, []);
-
- async function loadProfiles() {
- setLoading(true);
- try {
- const data = await wordpressApi.getSanitizationProfiles();
- setProfiles(data.profiles || []);
- } catch {
- setProfiles([]);
- } finally {
- setLoading(false);
- }
- }
-
- async function handleDelete(profileId) {
- try {
- await wordpressApi.deleteSanitizationProfile(profileId);
- setProfiles(prev => prev.filter(p => p.id !== profileId));
- onProfilesChange?.();
- } catch {
- // handled silently
- }
- }
-
- async function handleSetDefault(profileId) {
- try {
- await wordpressApi.updateSanitizationProfile(profileId, { is_default: true });
- setProfiles(prev => prev.map(p => ({
- ...p,
- is_default: p.id === profileId
- })));
- onProfilesChange?.();
- } catch {
- // handled silently
- }
- }
-
- async function handleSaveProfile(profileData) {
- try {
- if (editingProfile) {
- const result = await wordpressApi.updateSanitizationProfile(
- editingProfile.id,
- profileData
- );
- setProfiles(prev => prev.map(p =>
- p.id === editingProfile.id ? result.profile : p
- ));
- } else {
- const result = await wordpressApi.createSanitizationProfile(profileData);
- setProfiles(prev => [...prev, result.profile]);
- }
- setEditingProfile(null);
- setShowCreateForm(false);
- onProfilesChange?.();
- } catch {
- // handled silently
- }
- }
-
- return (
- <Modal open={true} onClose={onClose} title="Sanitization Profiles" size="lg">
- <div className="sanitization-profiles-body">
- {loading ? (
- <div className="sanitization-loading">
- <Spinner size="md" />
- </div>
- ) : (
- <>
- <div className="sanitization-profile-list">
- {profiles.map(profile => (
- <ProfileCard
- key={profile.id}
- profile={profile}
- onEdit={() => { setEditingProfile(profile); setShowCreateForm(false); }}
- onDelete={() => handleDelete(profile.id)}
- onSetDefault={() => handleSetDefault(profile.id)}
- />
- ))}
- </div>
-
- {!showCreateForm && !editingProfile && (
- <Button
- size="sm"
- className="sanitization-add-btn"
- onClick={() => setShowCreateForm(true)}
- >
- <Plus size={14} />
- Create Custom Profile
- </Button>
- )}
-
- {(showCreateForm || editingProfile) && (
- <ProfileEditor
- profile={editingProfile}
- onSave={handleSaveProfile}
- onCancel={() => { setEditingProfile(null); setShowCreateForm(false); }}
- />
- )}
- </>
- )}
- </div>
-
- <div className="modal-actions">
- <Button variant="outline" onClick={onClose}>Close</Button>
- </div>
- </Modal>
- );
-};
-
-const ProfileCard = ({ profile, onEdit, onDelete, onSetDefault }) => (
- <div className={`sanitization-profile-card ${profile.is_default ? 'default' : ''}`}>
- <div className="sanitization-profile-card-header">
- <div className="sanitization-profile-card-title">
- <h5>{profile.name}</h5>
- {profile.is_builtin && <span className="sanitization-tag builtin">Built-in</span>}
- {profile.is_default && <span className="sanitization-tag default">Default</span>}
- </div>
- <div className="sanitization-profile-card-actions">
- {!profile.is_default && (
- <Button variant="ghost" size="sm" onClick={onSetDefault} title="Set as default">
- <Star size={12} />
- </Button>
- )}
- <Button variant="ghost" size="sm" onClick={onEdit} title="Edit">
- <Edit3 size={12} />
- </Button>
- {!profile.is_builtin && (
- <Button variant="ghost" size="sm" onClick={onDelete} title="Delete">
- <Trash2 size={12} />
- </Button>
- )}
- </div>
- </div>
- {profile.description && (
- <p className="sanitization-profile-desc">{profile.description}</p>
- )}
- <div className="sanitization-profile-rules">
- <ProfileRuleTags config={profile.config} />
- </div>
- </div>
-);
-
-const ProfileRuleTags = ({ config }) => {
- const tags = [];
- if (config.anonymize_emails) tags.push('Anonymize emails');
- if (config.anonymize_names) tags.push('Anonymize names');
- if (config.reset_passwords) tags.push('Reset passwords');
- if (config.strip_payment_data) tags.push('Strip payments');
- if (config.remove_transients) tags.push('Clear transients');
- if (config.truncate_tables?.length > 0) tags.push(`Truncate ${config.truncate_tables.length} tables`);
- if (config.exclude_tables?.length > 0) tags.push(`Exclude ${config.exclude_tables.length} tables`);
- if (config.custom_search_replace && Object.keys(config.custom_search_replace).length > 0) {
- tags.push(`${Object.keys(config.custom_search_replace).length} replacements`);
- }
-
- return (
- <div className="sanitization-rule-tags">
- {tags.map(tag => (
- <span key={tag} className="sanitization-rule-tag">{tag}</span>
- ))}
- {tags.length === 0 && (
- <span className="sanitization-rule-tag empty">No rules configured</span>
- )}
- </div>
- );
-};
-
-const ProfileEditor = ({ profile, onSave, onCancel }) => {
- const [name, setName] = useState(profile?.name || '');
- const [description, setDescription] = useState(profile?.description || '');
- const [config, setConfig] = useState(profile?.config || {
- anonymize_emails: false,
- anonymize_names: false,
- reset_passwords: false,
- truncate_tables: [],
- exclude_tables: [],
- strip_payment_data: false,
- remove_transients: false,
- custom_search_replace: {},
- });
- const [truncateInput, setTruncateInput] = useState(
- (profile?.config?.truncate_tables || []).join(', ')
- );
- const [excludeInput, setExcludeInput] = useState(
- (profile?.config?.exclude_tables || []).join(', ')
- );
- const [saving, setSaving] = useState(false);
-
- function handleConfigToggle(key) {
- setConfig(prev => ({ ...prev, [key]: !prev[key] }));
- }
-
- async function handleSubmit(e) {
- e.preventDefault();
- setSaving(true);
- try {
- const finalConfig = {
- ...config,
- truncate_tables: truncateInput.split(',').map(s => s.trim()).filter(Boolean),
- exclude_tables: excludeInput.split(',').map(s => s.trim()).filter(Boolean),
- };
- await onSave({ name, description, config: finalConfig });
- } finally {
- setSaving(false);
- }
- }
-
- return (
- <form className="sanitization-editor" onSubmit={handleSubmit}>
- <h4>{profile ? 'Edit Profile' : 'Create Profile'}</h4>
-
- <div className="form-group">
- <Label>Profile Name *</Label>
- <Input
- type="text"
- value={name}
- onChange={e => setName(e.target.value)}
- placeholder="My Custom Profile"
- required
- disabled={profile?.is_builtin}
- />
- </div>
-
- <div className="form-group">
- <Label>Description</Label>
- <Input
- type="text"
- value={description}
- onChange={e => setDescription(e.target.value)}
- placeholder="What this profile does..."
- />
- </div>
-
- <div className="form-group">
- <Label>Data Sanitization</Label>
- <div className="checkbox-group">
- <label className="checkbox-label">
- <Checkbox
- checked={config.anonymize_emails || false}
- onCheckedChange={() => handleConfigToggle('anonymize_emails')}
- />
- <span>Anonymize email addresses</span>
- </label>
- <label className="checkbox-label">
- <Checkbox
- checked={config.anonymize_names || false}
- onCheckedChange={() => handleConfigToggle('anonymize_names')}
- />
- <span>Anonymize user names</span>
- </label>
- <label className="checkbox-label">
- <Checkbox
- checked={config.reset_passwords || false}
- onCheckedChange={() => handleConfigToggle('reset_passwords')}
- />
- <span>Reset all passwords</span>
- </label>
- <label className="checkbox-label">
- <Checkbox
- checked={config.strip_payment_data || false}
- onCheckedChange={() => handleConfigToggle('strip_payment_data')}
- />
- <span>Strip WooCommerce payment data</span>
- </label>
- <label className="checkbox-label">
- <Checkbox
- checked={config.remove_transients || false}
- onCheckedChange={() => handleConfigToggle('remove_transients')}
- />
- <span>Remove transients</span>
- </label>
- </div>
- </div>
-
- <div className="form-group">
- <Label>Truncate Tables (comma-separated)</Label>
- <Input
- type="text"
- value={truncateInput}
- onChange={e => setTruncateInput(e.target.value)}
- placeholder="actionscheduler_actions, actionscheduler_logs"
- />
- <span className="form-hint">Tables to empty (structure preserved, data removed)</span>
- </div>
-
- <div className="form-group">
- <Label>Exclude Tables (comma-separated)</Label>
- <Input
- type="text"
- value={excludeInput}
- onChange={e => setExcludeInput(e.target.value)}
- placeholder="wp_users, wp_usermeta"
- />
- <span className="form-hint">Tables to skip during sync/promote</span>
- </div>
-
- <div className="sanitization-editor-actions">
- <Button type="button" variant="outline" size="sm" onClick={onCancel}>
- Cancel
- </Button>
- <Button type="submit" size="sm" disabled={saving || !name.trim()}>
- {saving ? <><Spinner size="sm" /> Saving...</> : <><Save size={14} /> Save Profile</>}
- </Button>
- </div>
- </form>
- );
-};
-
-export default SanitizationProfileForm;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/SnapshotTable.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/SnapshotTable.jsx
deleted file mode 100644
index 4a046e23..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/SnapshotTable.jsx
+++ /dev/null
@@ -1,163 +0,0 @@
-import { useState } from 'react';
-import { Download, RotateCcw, Trash2, GitCommit, Tag } from 'lucide-react';
-import { ConfirmDialog } from 'serverkit-sdk';
-import { formatBytes } from 'serverkit-sdk';
-import { EmptyState } from 'serverkit-sdk';
-
-const SnapshotTable = ({ snapshots, onRestore, onDelete, loading = false }) => {
- const [actionLoading, setActionLoading] = useState({});
- const [confirmRestore, setConfirmRestore] = useState(null);
- const [confirmDelete, setConfirmDelete] = useState(null);
-
- function formatDate(dateString) {
- if (!dateString) return '-';
- return new Date(dateString).toLocaleString();
- }
-
- async function handleRestore(snapshot) {
- setConfirmRestore(null);
- setActionLoading(prev => ({ ...prev, [`restore-${snapshot.id}`]: true }));
- try {
- await onRestore?.(snapshot.id);
- } finally {
- setActionLoading(prev => ({ ...prev, [`restore-${snapshot.id}`]: false }));
- }
- }
-
- async function handleDelete(snapshot) {
- setConfirmDelete(null);
- setActionLoading(prev => ({ ...prev, [`delete-${snapshot.id}`]: true }));
- try {
- await onDelete?.(snapshot.id);
- } finally {
- setActionLoading(prev => ({ ...prev, [`delete-${snapshot.id}`]: false }));
- }
- }
-
- if (loading) {
- return <EmptyState loading title="Loading snapshots..." />;
- }
-
- if (!snapshots || snapshots.length === 0) {
- return (
- <div className="empty-state-small">
- <p>No database snapshots yet.</p>
- <p className="hint">Create a snapshot to backup your database.</p>
- </div>
- );
- }
-
- return (
- <div className="wp-table-card">
- <table className="sk-dtable wp-snapshot-table">
- <thead>
- <tr>
- <th>Snapshot</th>
- <th>Size</th>
- <th>Created</th>
- <th>Git Context</th>
- <th className="wp-th-right">Actions</th>
- </tr>
- </thead>
- <tbody>
- {snapshots.map(snapshot => (
- <tr key={snapshot.id}>
- <td>
- <div className="snapshot-name-cell">
- <span className="snapshot-name">{snapshot.name}</span>
- {snapshot.tag && (
- <span className="snapshot-tag">
- <Tag size={10} /> {snapshot.tag}
- </span>
- )}
- {snapshot.description && (
- <span className="snapshot-desc">{snapshot.description}</span>
- )}
- </div>
- </td>
- <td>
- <span className="mono">{formatBytes(snapshot.size_bytes)}</span>
- {snapshot.compressed && (
- <span className="compressed-badge" title="Compressed">gz</span>
- )}
- </td>
- <td><span className="snapshot-date">{formatDate(snapshot.created_at)}</span></td>
- <td>
- {snapshot.commit_sha ? (
- <div className="git-context">
- <GitCommit size={12} />
- <span className="mono git-context-sha">{snapshot.commit_sha.substring(0, 7)}</span>
- {snapshot.commit_message && (
- <span className="commit-msg" title={snapshot.commit_message}>
- {snapshot.commit_message.substring(0, 30)}
- {snapshot.commit_message.length > 30 && '...'}
- </span>
- )}
- </div>
- ) : (
- <span className="text-muted">-</span>
- )}
- </td>
- <td className="wp-cell-actions">
- <button type="button"
- className="wp-row-action"
- title="Restore"
- onClick={() => setConfirmRestore(snapshot)}
- disabled={actionLoading[`restore-${snapshot.id}`]}
- >
- <RotateCcw size={14} />
- </button>
- <button type="button"
- className="wp-row-action wp-row-action--danger"
- title="Delete"
- onClick={() => setConfirmDelete(snapshot)}
- disabled={actionLoading[`delete-${snapshot.id}`]}
- >
- <Trash2 size={14} />
- </button>
- </td>
- </tr>
- ))}
- </tbody>
- </table>
-
- <ConfirmDialog
- isOpen={!!confirmRestore}
- title="Restore Database Snapshot"
- message={`Restore database from "${confirmRestore?.name}"?`}
- details={
- <ul>
- <li><strong>Warning:</strong> This will overwrite your current database</li>
- <li>Snapshot size: <code>{formatBytes(confirmRestore?.size_bytes)}</code></li>
- <li>Created: {formatDate(confirmRestore?.created_at)}</li>
- {confirmRestore?.commit_sha && (
- <li>Git commit: <code>{confirmRestore.commit_sha.substring(0, 7)}</code></li>
- )}
- </ul>
- }
- confirmText="Restore Snapshot"
- variant="warning"
- onConfirm={() => handleRestore(confirmRestore)}
- onCancel={() => setConfirmRestore(null)}
- />
-
- <ConfirmDialog
- isOpen={!!confirmDelete}
- title="Delete Snapshot"
- message={`Delete snapshot "${confirmDelete?.name}"?`}
- details={
- <ul>
- <li>This snapshot will be permanently deleted</li>
- <li>This action cannot be undone</li>
- </ul>
- }
- confirmText="Delete Snapshot"
- variant="danger"
- onConfirm={() => handleDelete(confirmDelete)}
- onCancel={() => setConfirmDelete(null)}
- />
- </div>
- );
-};
-
-export default SnapshotTable;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/SyncModal.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/SyncModal.jsx
deleted file mode 100644
index 8628ef26..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/SyncModal.jsx
+++ /dev/null
@@ -1,221 +0,0 @@
-import { useState, useEffect } from 'react';
-import { ArrowDownLeft, Shield } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { Spinner } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from 'serverkit-sdk';
-import { Checkbox } from 'serverkit-sdk';
-
-const SyncModal = ({ environment, productionName, onClose, onSync }) => {
- const [syncType, setSyncType] = useState('database');
- const [config, setConfig] = useState({
- sanitize: false,
- truncate_tables: '',
- exclude_tables: '',
- sanitization_profile_id: ''
- });
- const [loading, setLoading] = useState(false);
- const [profiles, setProfiles] = useState([]);
-
- useEffect(() => {
- loadProfiles();
- }, []);
-
- async function loadProfiles() {
- try {
- const data = await wordpressApi.getSanitizationProfiles();
- setProfiles(data.profiles || []);
- const defaultProfile = (data.profiles || []).find(p => p.is_default);
- if (defaultProfile) {
- setConfig(prev => ({
- ...prev,
- sanitization_profile_id: String(defaultProfile.id),
- sanitize: true
- }));
- }
- } catch {
- setProfiles([]);
- }
- }
-
- async function handleSubmit(e) {
- e.preventDefault();
- setLoading(true);
- try {
- await onSync({
- type: syncType,
- sanitize: config.sanitize,
- sanitization_profile_id: config.sanitization_profile_id
- ? Number(config.sanitization_profile_id) : null,
- truncate_tables: config.truncate_tables
- ? config.truncate_tables.split(',').map(s => s.trim()).filter(Boolean)
- : [],
- exclude_tables: config.exclude_tables
- ? config.exclude_tables.split(',').map(s => s.trim()).filter(Boolean)
- : []
- });
- } finally {
- setLoading(false);
- }
- }
-
- function handleConfigChange(key, value) {
- setConfig(prev => ({ ...prev, [key]: value }));
- }
-
- const envType = environment.environment_type || 'development';
-
- return (
- <Modal open={true} onClose={onClose} title="Sync from Production">
- <form onSubmit={handleSubmit}>
- <div className="sync-direction">
- <div className="promote-env-pill production">
- <span className="promote-env-type">Production</span>
- <span className="promote-env-name">{productionName}</span>
- </div>
- <ArrowDownLeft size={20} className="promote-arrow" />
- <div className={`promote-env-pill ${envType}`}>
- <span className="promote-env-type">{envType}</span>
- <span className="promote-env-name">{environment.name}</span>
- </div>
- </div>
-
- <div className="form-group">
- <Label>Sync Type</Label>
- <div className="radio-group">
- <label className="radio-label">
- <input
- type="radio"
- name="syncType"
- value="database"
- checked={syncType === 'database'}
- onChange={e => setSyncType(e.target.value)}
- />
- <div className="radio-content">
- <strong>Database Only</strong>
- <span>Pull production database into this environment</span>
- </div>
- </label>
- <label className="radio-label">
- <input
- type="radio"
- name="syncType"
- value="files"
- checked={syncType === 'files'}
- onChange={e => setSyncType(e.target.value)}
- />
- <div className="radio-content">
- <strong>Files Only</strong>
- <span>Pull production files (wp-content) into this environment</span>
- </div>
- </label>
- <label className="radio-label">
- <input
- type="radio"
- name="syncType"
- value="full"
- checked={syncType === 'full'}
- onChange={e => setSyncType(e.target.value)}
- />
- <div className="radio-content">
- <strong>Full Sync</strong>
- <span>Pull both database and files from production</span>
- </div>
- </label>
- </div>
- </div>
-
- {(syncType === 'database' || syncType === 'full') && (
- <>
- <div className="form-group">
- <label className="checkbox-label">
- <Checkbox
- checked={config.sanitize}
- onCheckedChange={v => handleConfigChange('sanitize', v)}
- />
- <span>Sanitize data (anonymize emails, reset passwords)</span>
- </label>
- </div>
-
- {config.sanitize && profiles.length > 0 && (
- <div className="form-group">
- <Label>
- <Shield size={14} style={{ marginRight: 4, verticalAlign: -2 }} />
- Sanitization Profile
- </Label>
- <Select
- value={config.sanitization_profile_id}
- onValueChange={v => handleConfigChange('sanitization_profile_id', v)}
- >
- <SelectTrigger>
- <SelectValue placeholder="Manual configuration" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="">Manual configuration</SelectItem>
- {profiles.map(p => (
- <SelectItem key={p.id} value={String(p.id)}>
- {p.name}{p.is_default ? ' (default)' : ''}{p.is_builtin ? '' : ' (custom)'}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- {config.sanitization_profile_id && (
- <span className="form-hint">
- {profiles.find(p => String(p.id) === config.sanitization_profile_id)?.description || ''}
- </span>
- )}
- </div>
- )}
-
- <div className="form-group">
- <Label>Exclude Tables (comma-separated, optional)</Label>
- <Input
- type="text"
- value={config.exclude_tables}
- onChange={e => handleConfigChange('exclude_tables', e.target.value)}
- placeholder="wp_users, wp_usermeta"
- />
- <span className="form-hint">Tables to skip during sync</span>
- </div>
-
- <div className="form-group">
- <Label>Truncate Tables (comma-separated, optional)</Label>
- <Input
- type="text"
- value={config.truncate_tables}
- onChange={e => handleConfigChange('truncate_tables', e.target.value)}
- placeholder="wp_actionscheduler_actions, wp_actionscheduler_logs"
- />
- <span className="form-hint">Tables to empty (structure kept, data removed)</span>
- </div>
- </>
- )}
-
- <div className="sync-warning">
- <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
- <circle cx="12" cy="12" r="10" />
- <path d="M12 8v4M12 16h.01" />
- </svg>
- <div>
- <strong>This will overwrite data</strong>
- <p>The current {syncType === 'files' ? 'files' : syncType === 'database' ? 'database' : 'database and files'} in this environment will be replaced with production data. A snapshot will be created before syncing.</p>
- </div>
- </div>
-
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose} disabled={loading}>
- Cancel
- </Button>
- <Button type="submit" disabled={loading}>
- {loading ? <><Spinner size="sm" /> Syncing...</> : 'Sync Now'}
- </Button>
- </div>
- </form>
- </Modal>
- );
-};
-
-export default SyncModal;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/WordPressSiteCard.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/WordPressSiteCard.jsx
deleted file mode 100644
index edda8060..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/WordPressSiteCard.jsx
+++ /dev/null
@@ -1,154 +0,0 @@
-import { useState } from 'react';
-import { useNavigate } from 'react-router-dom';
-import { ExternalLink, Settings, Copy, Trash2 } from 'lucide-react';
-import { ConfirmDialog } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-
-const WordPressSiteCard = ({ site, onDelete }) => {
- const navigate = useNavigate();
- const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
- const isRunning = site.status === 'running';
-
- function getEnvironmentCount() {
- return site.environments?.length || 0;
- }
-
- function handleVisitSite(e) {
- e.stopPropagation();
- if (site.url) {
- window.open(site.url, '_blank');
- }
- }
-
- function handleOpenDashboard(e) {
- e.stopPropagation();
- if (site.url) {
- window.open(`${site.url}/wp-admin`, '_blank');
- }
- }
-
- function handleManage() {
- navigate(`/wordpress/${site.id}`);
- }
-
- function handleDelete(e) {
- e.stopPropagation();
- setShowDeleteConfirm(true);
- }
-
- function confirmDelete() {
- setShowDeleteConfirm(false);
- onDelete?.(site.id);
- }
-
- return (
- <div className="wp-site-card" onClick={handleManage}>
- <div className="wp-site-card-header">
- <div className="wp-site-icon">
- <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor">
- <path d="M12 2C6.486 2 2 6.486 2 12s4.486 10 10 10 10-4.486 10-10S17.514 2 12 2zm0 19.542c-5.261 0-9.542-4.281-9.542-9.542S6.739 2.458 12 2.458 21.542 6.739 21.542 12 17.261 21.542 12 21.542z"/>
- </svg>
- </div>
- <div className="wp-site-info">
- <h3 className="wp-site-name">{site.name}</h3>
- {site.url && (
- <span className="wp-site-url">{site.url}</span>
- )}
- </div>
- <span className={`wp-site-status ${isRunning ? 'running' : 'stopped'}`}>
- <span className="status-dot" />
- {isRunning ? 'Running' : 'Stopped'}
- </span>
- </div>
-
- <div className="wp-site-card-body">
- <div className="wp-site-meta">
- <div className="wp-site-meta-item">
- <span className="meta-label">Version</span>
- <span className="meta-value">{site.wp_version || 'Unknown'}</span>
- </div>
- <div className="wp-site-meta-item">
- <span className="meta-label">Environments</span>
- <span className="meta-value">{getEnvironmentCount() + 1}</span>
- </div>
- {site.git_repo_url && (
- <div className="wp-site-meta-item">
- <span className="meta-label">Git</span>
- <span className="meta-value git-connected">Connected</span>
- </div>
- )}
- </div>
-
- {site.is_production && (
- <span className="wp-site-badge production">Production</span>
- )}
- {!site.is_production && site.production_site_id && (
- <span className="wp-site-badge development">Development</span>
- )}
- </div>
-
- <div className="wp-site-card-footer">
- <Button
- variant="ghost"
- size="sm"
- onClick={handleVisitSite}
- disabled={!site.url}
- title="Visit Site"
- >
- <ExternalLink size={14} />
- Visit
- </Button>
- <Button
- variant="ghost"
- size="sm"
- onClick={handleOpenDashboard}
- disabled={!site.url}
- title="Open Dashboard"
- >
- <Settings size={14} />
- Dashboard
- </Button>
- <Button
- variant="ghost"
- size="sm"
- onClick={handleManage}
- title="Manage Site"
- >
- <Copy size={14} />
- Manage
- </Button>
- <Button
- variant="ghost"
- size="sm"
- onClick={handleDelete}
- title="Delete Site"
- className="text-destructive hover:text-destructive"
- >
- <Trash2 size={14} />
- </Button>
- </div>
-
- <ConfirmDialog
- isOpen={showDeleteConfirm}
- title="Delete WordPress Site"
- message={`Are you sure you want to delete "${site.name}"? This action cannot be undone.`}
- details={
- <ul>
- <li>All site files will be permanently deleted</li>
- <li>Database <code>{site.db_name || 'associated database'}</code> will be removed</li>
- {site.environments?.length > 0 && (
- <li>{site.environments.length} linked environment(s) will also be deleted</li>
- )}
- </ul>
- }
- confirmText="Delete Site"
- variant="danger"
- requireConfirmation={site.name}
- onConfirm={confirmDelete}
- onCancel={() => setShowDeleteConfirm(false)}
- />
- </div>
- );
-};
-
-export default WordPressSiteCard;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/WpCliTerminal.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/WpCliTerminal.jsx
deleted file mode 100644
index 0bd0354f..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/WpCliTerminal.jsx
+++ /dev/null
@@ -1,192 +0,0 @@
-import { useState, useRef, useEffect } from 'react';
-import { Play, Clock } from 'lucide-react';
-import { Spinner } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-
-const QUICK_COMMANDS = [
- { label: 'Plugin List', command: 'wp plugin list --format=table' },
- { label: 'Cache Flush', command: 'wp cache flush' },
- { label: 'DB Check', command: 'wp db check' },
- { label: 'Site URL', command: 'wp option get siteurl' },
-];
-
-const HISTORY_KEY = 'wp_cli_history';
-const MAX_HISTORY = 50;
-
-const WpCliTerminal = ({ environment, prodId, onClose, api }) => {
- const [command, setCommand] = useState('');
- const [output, setOutput] = useState([]);
- const [executing, setExecuting] = useState(false);
- const [showHistory, setShowHistory] = useState(false);
- const [historyIndex, setHistoryIndex] = useState(-1);
-
- const inputRef = useRef(null);
- const outputRef = useRef(null);
-
- const history = JSON.parse(localStorage.getItem(HISTORY_KEY) || '[]');
-
- useEffect(() => {
- inputRef.current?.focus();
- }, []);
-
- useEffect(() => {
- if (outputRef.current) {
- outputRef.current.scrollTop = outputRef.current.scrollHeight;
- }
- }, [output]);
-
- function saveToHistory(cmd) {
- const updated = [cmd, ...history.filter(h => h !== cmd)].slice(0, MAX_HISTORY);
- localStorage.setItem(HISTORY_KEY, JSON.stringify(updated));
- }
-
- async function executeCommand(cmd) {
- if (!cmd.trim()) return;
-
- const cmdStr = cmd.trim();
- setCommand('');
- setExecuting(true);
- saveToHistory(cmdStr);
- setHistoryIndex(-1);
-
- setOutput(prev => [...prev, { type: 'command', text: cmdStr }]);
-
- try {
- const result = await api.executeWpCli(prodId, environment.id, cmdStr);
- if (result.success) {
- setOutput(prev => [...prev, { type: 'output', text: result.output || '(no output)' }]);
- } else {
- setOutput(prev => [...prev, { type: 'error', text: result.error || 'Command failed' }]);
- }
- } catch (err) {
- setOutput(prev => [...prev, { type: 'error', text: err.message || 'Execution failed' }]);
- } finally {
- setExecuting(false);
- inputRef.current?.focus();
- }
- }
-
- function handleKeyDown(e) {
- if (e.key === 'Enter' && !executing) {
- executeCommand(command);
- } else if (e.key === 'ArrowUp') {
- e.preventDefault();
- if (history.length > 0) {
- const newIndex = Math.min(historyIndex + 1, history.length - 1);
- setHistoryIndex(newIndex);
- setCommand(history[newIndex]);
- }
- } else if (e.key === 'ArrowDown') {
- e.preventDefault();
- if (historyIndex > 0) {
- const newIndex = historyIndex - 1;
- setHistoryIndex(newIndex);
- setCommand(history[newIndex]);
- } else {
- setHistoryIndex(-1);
- setCommand('');
- }
- }
- }
-
- const envName = environment?.name || 'Environment';
-
- return (
- <Modal open={true} onClose={onClose} title={`WP-CLI - ${envName}`} className="wpcli-terminal-modal">
- <div className="wpcli-quick-actions">
- {QUICK_COMMANDS.map(qc => (
- <Button
- key={qc.command}
- variant="ghost"
- size="sm"
- onClick={() => executeCommand(qc.command)}
- disabled={executing}
- >
- {qc.label}
- </Button>
- ))}
- <Button
- variant="ghost"
- size="sm"
- onClick={() => setShowHistory(!showHistory)}
- title="Command history"
- >
- <Clock size={12} />
- </Button>
- </div>
-
- {showHistory && history.length > 0 && (
- <div className="wpcli-history">
- {history.slice(0, 10).map((cmd, i) => (
- <button type="button"
- key={i}
- className="wpcli-history-item"
- onClick={() => {
- setCommand(cmd);
- setShowHistory(false);
- inputRef.current?.focus();
- }}
- >
- <code>{cmd}</code>
- </button>
- ))}
- </div>
- )}
-
- <div className="wpcli-output" ref={outputRef}>
- {output.length === 0 && (
- <div className="wpcli-output-empty">
- Enter a WP-CLI command below or use the quick actions above.
- </div>
- )}
- {output.map((entry, i) => (
- <div key={i} className={`wpcli-output-entry ${entry.type}`}>
- {entry.type === 'command' && (
- <div className="wpcli-output-command">
- <span className="wpcli-prompt">$</span>
- <code>{entry.text}</code>
- </div>
- )}
- {entry.type === 'output' && (
- <pre className="wpcli-output-text">{entry.text}</pre>
- )}
- {entry.type === 'error' && (
- <pre className="wpcli-output-error">{entry.text}</pre>
- )}
- </div>
- ))}
- {executing && (
- <div className="wpcli-executing">
- <Spinner size="sm" />
- <span>Executing...</span>
- </div>
- )}
- </div>
-
- <div className="wpcli-input-row">
- <span className="wpcli-prompt">$</span>
- <Input
- ref={inputRef}
- type="text"
- value={command}
- onChange={e => setCommand(e.target.value)}
- onKeyDown={handleKeyDown}
- placeholder="wp plugin list --format=table"
- disabled={executing}
- className="wpcli-input"
- />
- <Button
- size="sm"
- onClick={() => executeCommand(command)}
- disabled={executing || !command.trim()}
- >
- <Play size={12} />
- </Button>
- </div>
- </Modal>
- );
-};
-
-export default WpCliTerminal;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/AnalyticsTab.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/AnalyticsTab.jsx
deleted file mode 100644
index 6e27835a..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/AnalyticsTab.jsx
+++ /dev/null
@@ -1,189 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import { Link } from 'react-router-dom';
-import { ResponsiveContainer, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts';
-import { BarChart3, Globe, HardDrive, AlertTriangle, Activity, FileText, LineChart, ExternalLink } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { api } from 'serverkit-sdk';
-import { useToast } from 'serverkit-sdk';
-import { MetricCard, SegControl } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { OverviewGridSkeleton, ANALYTICS_PERIODS } from './wpDetailShared';
-
-// Analytics Tab — per-site traffic + error analytics (#25), parsed on-demand from
-// the apache container access log. PHP fatals, response time, and cache hit ratio
-// are not in the default access log (deferred to #30 / #22-#23).
-const AnalyticsTab = ({ siteId }) => {
- const toast = useToast();
- const [data, setData] = useState(null);
- const [loading, setLoading] = useState(true);
- const [hours, setHours] = useState(24);
- // Feature-detect the serverkit-analytics extension so we can point users at
- // the persistent, privacy-first dashboard when it's installed. The on-demand
- // access-log view below stays as a complementary, always-available source.
- const [analyticsExt, setAnalyticsExt] = useState(false);
-
- useEffect(() => {
- let alive = true;
- api.getInstalledPlugins('active')
- .then((res) => {
- if (!alive) return;
- const on = (res?.plugins || []).some(
- (p) => p.slug === 'serverkit-analytics' && p.status === 'active');
- setAnalyticsExt(on);
- })
- .catch(() => { /* extension absent — silently keep the log view */ });
- return () => { alive = false; };
- }, []);
-
- const load = React.useCallback(async () => {
- setLoading(true);
- try {
- const res = await wordpressApi.getSiteAnalytics(siteId, hours);
- setData(res);
- } catch (err) {
- toast.error(err.message || 'Failed to load analytics');
- } finally {
- setLoading(false);
- }
- }, [siteId, hours, toast]);
-
- useEffect(() => { load(); }, [load]);
-
- if (loading) return <SkeletonBoundary loading skeleton={<OverviewGridSkeleton panels={3} />} />;
-
- const fmtHour = (iso) => {
- const d = new Date(iso);
- return hours <= 24
- ? d.toLocaleTimeString([], { hour: '2-digit', hour12: false })
- : d.toLocaleDateString([], { month: 'short', day: 'numeric' });
- };
- const clip = (p) => (p && p.length > 48 ? `${p.slice(0, 48)}…` : p);
- const clipMsg = (m) => (m && m.length > 80 ? `${m.slice(0, 80)}…` : m);
- const s = data?.status || {};
- const phpErr = data?.php_errors;
-
- return (
- <div className="app-overview-grid">
- <div className="app-overview-left">
- {analyticsExt && (
- <div className="wp-analytics-banner">
- <LineChart size={16} />
- <div className="wp-analytics-banner__text">
- <strong>Analytics is installed.</strong>
- <span> Add this site there for persistent, cookieless visitor tracking with a full dashboard. The view below is parsed on demand from access logs.</span>
- </div>
- <Link to="/analytics/sites" className="wp-analytics-banner__link">
- Open Analytics <ExternalLink size={13} />
- </Link>
- </div>
- )}
- <div className="wp-analytics-head">
- <h3 className="wp-eyebrow">Traffic · {hours <= 24 ? 'last 24 hours' : 'last 7 days'}</h3>
- <SegControl
- options={ANALYTICS_PERIODS.map(p => ({ value: p.hours, label: p.label }))}
- value={hours}
- onChange={setHours}
- />
- </div>
- {data?.note && <p className="hint">{data.note}</p>}
- <div className="wp-kpis">
- <MetricCard icon={<BarChart3 size={16} />} tone="accent" value={(data?.requests ?? 0).toLocaleString()} label="Requests" />
- <MetricCard icon={<Globe size={16} />} tone="cyan" value={(data?.unique_visitors ?? 0).toLocaleString()} label="Unique visitors" />
- <MetricCard icon={<HardDrive size={16} />} tone="violet" value={data?.bytes_human || '0 B'} label="Bandwidth" />
- <MetricCard icon={<AlertTriangle size={16} />} tone={(data?.error_rate ?? 0) > 5 ? 'red' : 'amber'} value={`${data?.error_rate ?? 0}%`} label="Error rate" />
- <MetricCard icon={<Activity size={16} />} tone="green" value={`${data?.bot_pct ?? 0}%`} label="Bot traffic" />
- <MetricCard icon={<FileText size={16} />} tone="red" value={(data?.not_found ?? 0).toLocaleString()} label="404s" />
- </div>
-
- <div className="app-panel">
- <div className="app-panel-header">Requests over time</div>
- <div className="app-panel-body">
- <ResponsiveContainer width="100%" height={220}>
- <AreaChart data={data?.series || []} margin={{ top: 8, right: 8, left: -16, bottom: 0 }}>
- <defs>
- <linearGradient id="wpReq" x1="0" y1="0" x2="0" y2="1">
- <stop offset="5%" stopColor="#6d7cff" stopOpacity={0.35} />
- <stop offset="95%" stopColor="#6d7cff" stopOpacity={0} />
- </linearGradient>
- <linearGradient id="wpErr" x1="0" y1="0" x2="0" y2="1">
- <stop offset="5%" stopColor="#fb6f6f" stopOpacity={0.35} />
- <stop offset="95%" stopColor="#fb6f6f" stopOpacity={0} />
- </linearGradient>
- </defs>
- <CartesianGrid strokeDasharray="3 3" stroke="#888" strokeOpacity={0.15} />
- <XAxis dataKey="hour" tickFormatter={fmtHour} tick={{ fontSize: 11, fill: '#888' }} minTickGap={24} axisLine={false} tickLine={false} />
- <YAxis allowDecimals={false} tick={{ fontSize: 11, fill: '#888' }} width={36} axisLine={false} tickLine={false} />
- <Tooltip labelFormatter={fmtHour} />
- <Area type="monotone" dataKey="requests" name="Requests" stroke="#8b93ff" fill="url(#wpReq)" strokeWidth={2} />
- <Area type="monotone" dataKey="errors" name="Errors" stroke="#fb6f6f" fill="url(#wpErr)" strokeWidth={2} />
- </AreaChart>
- </ResponsiveContainer>
- </div>
- </div>
-
- <div className="app-panel">
- <div className="app-panel-header">Status codes</div>
- <div className="app-panel-body">
- <div className="app-info-grid">
- <div className="app-info-item"><span className="app-info-label">2xx</span><span className="app-info-value">{(s['2xx'] ?? 0).toLocaleString()}</span></div>
- <div className="app-info-item"><span className="app-info-label">3xx</span><span className="app-info-value">{(s['3xx'] ?? 0).toLocaleString()}</span></div>
- <div className="app-info-item"><span className="app-info-label">4xx</span><span className="app-info-value">{(s['4xx'] ?? 0).toLocaleString()}</span></div>
- <div className="app-info-item"><span className="app-info-label">5xx</span><span className="app-info-value">{(s['5xx'] ?? 0).toLocaleString()}</span></div>
- </div>
- </div>
- </div>
-
- {data?.top_paths?.length > 0 && (
- <div className="app-panel">
- <div className="app-panel-header">Top URLs</div>
- <div className="app-panel-body">
- <div className="app-info-grid">
- {data.top_paths.map((row, i) => (
- <div className="app-info-item" key={i}>
- <span className="app-info-label" title={row.path}>{clip(row.path)}</span>
- <span className="app-info-value">{row.count.toLocaleString()}</span>
- </div>
- ))}
- </div>
- <p className="hint">Read live from the container access log; response-time metrics are not captured by the default log.</p>
- </div>
- </div>
- )}
-
- {phpErr && (
- <div className="app-panel">
- <div className="app-panel-header">PHP errors</div>
- <div className="app-panel-body">
- {!phpErr.available ? (
- <p className="hint">{phpErr.note || 'PHP error logging is off.'}</p>
- ) : (
- <>
- <div className="app-info-grid">
- <div className="app-info-item"><span className="app-info-label">Fatal</span><span className="app-info-value">{(phpErr.counts?.fatal ?? 0).toLocaleString()}</span></div>
- <div className="app-info-item"><span className="app-info-label">Warning</span><span className="app-info-value">{(phpErr.counts?.warning ?? 0).toLocaleString()}</span></div>
- <div className="app-info-item"><span className="app-info-label">Notice</span><span className="app-info-value">{(phpErr.counts?.notice ?? 0).toLocaleString()}</span></div>
- <div className="app-info-item"><span className="app-info-label">Deprecated</span><span className="app-info-value">{(phpErr.counts?.deprecated ?? 0).toLocaleString()}</span></div>
- </div>
- {phpErr.recent?.length > 0 ? (
- <div className="app-info-grid">
- {phpErr.recent.map((e, i) => (
- <div className="app-info-item" key={i}>
- <span className="app-info-label" title={e.message}>{e.level}: {clipMsg(e.message)}</span>
- <span className="app-info-value">{e.time}</span>
- </div>
- ))}
- </div>
- ) : (
- <p className="hint">{phpErr.note || 'No PHP errors recorded.'}</p>
- )}
- </>
- )}
- </div>
- </div>
- )}
- </div>
- </div>
- );
-};
-
-export default AnalyticsTab;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/BackupsTab.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/BackupsTab.jsx
deleted file mode 100644
index deb1d422..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/BackupsTab.jsx
+++ /dev/null
@@ -1,16 +0,0 @@
-import ProtectionPanel from '@/components/backups/ProtectionPanel';
-
-// Backups Tab
-// Backups tab — now the shared Protection panel (scheduled backups, cost,
-// one-click restore). Renders for both the top-level "Backups" tab and the
-// Settings → Backups section.
-const BackupsTab = ({ siteId, site }) => (
- <ProtectionPanel
- targetType="wordpress_site"
- targetId={siteId}
- targetName={site?.name}
- showMaintenanceModeOption
- />
-);
-
-export default BackupsTab;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/DatabaseTab.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/DatabaseTab.jsx
deleted file mode 100644
index 08b70438..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/DatabaseTab.jsx
+++ /dev/null
@@ -1,217 +0,0 @@
-import { useState, useEffect } from 'react';
-import { Database, Plus } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { SnapshotTable } from '../index';
-import { ErrorState } from '@/components/ErrorBoundary';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { Textarea } from 'serverkit-sdk';
-
-// Database Tab
-const DatabaseTab = ({ siteId, site }) => {
- const toast = useToast();
- const [snapshots, setSnapshots] = useState([]);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState(null);
- const [showCreateModal, setShowCreateModal] = useState(false);
-
- useEffect(() => {
- loadSnapshots();
- }, [siteId]);
-
- async function loadSnapshots() {
- setLoading(true);
- setError(null);
- try {
- const data = await wordpressApi.getSnapshots(siteId);
- setSnapshots(data.snapshots || []);
- } catch (err) {
- console.error('Failed to load snapshots:', err);
- setError(err);
- } finally {
- setLoading(false);
- }
- }
-
- async function handleCreateSnapshot(data) {
- toast.info('Creating snapshot...', { duration: 3000 });
- try {
- await wordpressApi.createSnapshot(siteId, data);
- toast.success('Snapshot created successfully');
- loadSnapshots();
- setShowCreateModal(false);
- } catch (err) {
- toast.error(err.message || 'Failed to create snapshot');
- }
- }
-
- async function handleRestore(snapId) {
- toast.info('Restoring database... This may take a moment.', { duration: 5000 });
- try {
- await wordpressApi.restoreSnapshot(siteId, snapId);
- toast.success('Database restored from snapshot');
- } catch (err) {
- toast.error(err.message || 'Failed to restore snapshot');
- }
- }
-
- async function handleDelete(snapId) {
- try {
- await wordpressApi.deleteSnapshot(siteId, snapId);
- toast.success('Snapshot deleted');
- loadSnapshots();
- } catch (err) {
- toast.error(err.message || 'Failed to delete snapshot');
- }
- }
-
- if (error) {
- return (
- <ErrorState
- title="Failed to load snapshots"
- error={error}
- onRetry={loadSnapshots}
- />
- );
- }
-
- return (
- <div className="database-tab">
- {/* Database Connection Info */}
- <div className="app-panel">
- <div className="app-panel-header">
- <Database size={16} />
- Database Connection
- </div>
- <div className="app-panel-body">
- <div className="app-info-grid">
- <div className="app-info-item">
- <span className="app-info-label">Database Name</span>
- <span className="app-info-value mono">{site?.db_name || 'wordpress'}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Database User</span>
- <span className="app-info-value mono">{site?.db_user || 'wordpress'}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Database Host</span>
- <span className="app-info-value mono">{site?.db_host || 'db'}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Table Prefix</span>
- <span className="app-info-value mono">{site?.db_prefix || 'wp_'}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Container</span>
- <span className="app-info-value mono">{site?.compose_project_name ? `${site.compose_project_name}-db` : '-'}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Engine</span>
- <span className="app-info-value">MySQL 8.0</span>
- </div>
- </div>
- </div>
- </div>
-
- {/* Snapshots */}
- <div className="section-header mt-6">
- <h3>Database Snapshots</h3>
- <Button onClick={() => setShowCreateModal(true)}>
- <Plus size={14} /> Create Snapshot
- </Button>
- </div>
-
- <SnapshotTable
- snapshots={snapshots}
- loading={loading}
- onRestore={handleRestore}
- onDelete={handleDelete}
- />
-
- {showCreateModal && (
- <CreateSnapshotModal
- onClose={() => setShowCreateModal(false)}
- onCreate={handleCreateSnapshot}
- />
- )}
- </div>
- );
-};
-
-// Create Snapshot Modal
-const CreateSnapshotModal = ({ onClose, onCreate }) => {
- const [formData, setFormData] = useState({
- name: `Snapshot ${new Date().toLocaleDateString()}`,
- description: '',
- tag: ''
- });
- const [loading, setLoading] = useState(false);
-
- function handleChange(e) {
- const { name, value } = e.target;
- setFormData(prev => ({ ...prev, [name]: value }));
- }
-
- async function handleSubmit(e) {
- e.preventDefault();
- setLoading(true);
- try {
- await onCreate(formData);
- } finally {
- setLoading(false);
- }
- }
-
- return (
- <Modal open onClose={onClose} title="Create Snapshot">
- <form onSubmit={handleSubmit}>
- <div className="form-group">
- <Label>Snapshot Name *</Label>
- <Input
- type="text"
- name="name"
- value={formData.name}
- onChange={handleChange}
- required
- />
- </div>
-
- <div className="form-group">
- <Label>Description</Label>
- <Textarea
- name="description"
- value={formData.description}
- onChange={handleChange}
- placeholder="Optional description..."
- rows={3}
- />
- </div>
-
- <div className="form-group">
- <Label>Tag</Label>
- <Input
- type="text"
- name="tag"
- value={formData.tag}
- onChange={handleChange}
- placeholder="e.g., v1.0.0, before-update"
- />
- </div>
-
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose}>
- Cancel
- </Button>
- <Button type="submit" disabled={loading}>
- {loading ? 'Creating...' : 'Create Snapshot'}
- </Button>
- </div>
- </form>
- </Modal>
- );
-};
-
-export default DatabaseTab;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/EnvironmentsTab.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/EnvironmentsTab.jsx
deleted file mode 100644
index e0e281a4..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/EnvironmentsTab.jsx
+++ /dev/null
@@ -1,311 +0,0 @@
-import { useState, useEffect } from 'react';
-import { Plus } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { EnvironmentCard } from '../index';
-import { ErrorState } from '@/components/ErrorBoundary';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { EnvironmentCardSkeleton } from './wpDetailShared';
-
-// Environments Tab
-const EnvironmentsTab = ({ siteId, site, onUpdate }) => {
- const toast = useToast();
- const [environments, setEnvironments] = useState([]);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState(null);
- const [showCreateModal, setShowCreateModal] = useState(false);
-
- useEffect(() => {
- loadEnvironments();
- }, [siteId]);
-
- async function loadEnvironments() {
- setLoading(true);
- setError(null);
- try {
- const data = await wordpressApi.getEnvironments(siteId);
- setEnvironments(data.environments || []);
- } catch (err) {
- console.error('Failed to load environments:', err);
- setError(err);
- } finally {
- setLoading(false);
- }
- }
-
- async function handleCreateEnvironment(data) {
- toast.info('Creating environment... This may take a moment.', { duration: 5000 });
- try {
- await wordpressApi.createEnvironment(siteId, data);
- toast.success('Environment created successfully');
- loadEnvironments();
- setShowCreateModal(false);
- } catch (err) {
- toast.error(err.message || 'Failed to create environment');
- }
- }
-
- async function handleSync(envId) {
- toast.info('Syncing from production...', { duration: 3000 });
- try {
- await wordpressApi.syncEnvironment(siteId, { environment_id: envId });
- toast.success('Environment synced from production');
- loadEnvironments();
- } catch (err) {
- toast.error(err.message || 'Failed to sync environment');
- }
- }
-
- async function handleDelete(envId) {
- toast.info('Deleting environment...', { duration: 2000 });
- try {
- await wordpressApi.deleteEnvironment(siteId, envId);
- toast.success('Environment deleted');
- loadEnvironments();
- } catch (err) {
- toast.error(err.message || 'Failed to delete environment');
- }
- }
-
- if (loading) {
- return (
- <SkeletonBoundary loading skeleton={(
- <div className="environments-tab">
- <div className="section-header">
- <div className="skeleton" style={{ width: 120, height: 24 }} />
- <div className="skeleton" style={{ width: 160, height: 36, borderRadius: 6 }} />
- </div>
- <div className="environments-grid">
- <EnvironmentCardSkeleton />
- <EnvironmentCardSkeleton />
- </div>
- </div>
- )} />
- );
- }
-
- if (error) {
- return (
- <ErrorState
- title="Failed to load environments"
- error={error}
- onRetry={loadEnvironments}
- />
- );
- }
-
- // Filter out production from the environments list (it's shown separately)
- const childEnvs = environments.filter(e => e.id !== site.id && !e.is_production);
- const hasStaging = childEnvs.some(e => e.environment_type === 'staging');
- const hasDev = childEnvs.some(e => e.environment_type === 'development');
- const canCreateMore = site.is_production && (!hasStaging || !hasDev);
-
- return (
- <div className="environments-tab">
- <div className="section-header">
- <h3>Environments</h3>
- {canCreateMore && (
- <Button onClick={() => setShowCreateModal(true)}>
- <Plus size={14} /> Create Environment
- </Button>
- )}
- </div>
-
- <div className="environments-grid">
- {/* Production environment (the current site) */}
- <EnvironmentCard
- environment={{
- id: site.id,
- name: site.name,
- url: site.url,
- status: site.status,
- db_name: site.db_name,
- type: 'production'
- }}
- isProduction={true}
- />
-
- {/* Dev/staging environments */}
- {childEnvs.map(env => (
- <EnvironmentCard
- key={env.id}
- environment={env}
- productionUrl={site.url}
- onSync={handleSync}
- onDelete={handleDelete}
- />
- ))}
-
- {/* Add-environment tile — sits inline next to the existing
- environments instead of a full-width "empty" block. */}
- {canCreateMore && (
- <button
- type="button"
- className="wp-env-add-tile"
- onClick={() => setShowCreateModal(true)}
- >
- <span className="wp-env-add-tile__icon"><Plus size={22} /></span>
- <span className="wp-env-add-tile__title">Create environment</span>
- <span className="wp-env-add-tile__hint">
- {childEnvs.length === 0
- ? 'Spin up a dev or staging copy to test changes safely before deploying to production.'
- : 'Add another dev or staging copy.'}
- </span>
- </button>
- )}
- </div>
-
- {showCreateModal && (
- <CreateEnvironmentModal
- onClose={() => setShowCreateModal(false)}
- onCreate={handleCreateEnvironment}
- productionDomain={site.url}
- hasStaging={hasStaging}
- hasDev={hasDev}
- />
- )}
- </div>
- );
-};
-
-// Create Environment Modal
-export const CreateEnvironmentModal = ({ onClose, onCreate, productionDomain, hasStaging = false, hasDev = false }) => {
- // Default to whichever type is still available
- const defaultType = !hasDev ? 'development' : !hasStaging ? 'staging' : 'development';
- const [formData, setFormData] = useState({
- type: defaultType,
- name: '',
- domain: '',
- cloneDb: true,
- syncSchedule: ''
- });
- const [loading, setLoading] = useState(false);
-
- // Generate suggested domain based on production domain
- function getSuggestedDomain() {
- if (!productionDomain) return '';
- try {
- const url = new URL(productionDomain);
- const prefix = formData.type === 'staging' ? 'staging' : 'dev';
- return `${prefix}.${url.hostname}`;
- } catch {
- return '';
- }
- }
-
- const suggestedDomain = getSuggestedDomain();
- const displayDomain = formData.domain || suggestedDomain;
-
- function handleChange(e) {
- const { name, value, type, checked } = e.target;
- setFormData(prev => ({
- ...prev,
- [name]: type === 'checkbox' ? checked : value
- }));
- }
-
- async function handleSubmit(e) {
- e.preventDefault();
- setLoading(true);
- try {
- await onCreate({
- type: formData.type,
- name: formData.name,
- domain: formData.domain || suggestedDomain,
- clone_db: formData.cloneDb,
- sync_schedule: formData.syncSchedule || null
- });
- } finally {
- setLoading(false);
- }
- }
-
- return (
- <Modal open onClose={onClose} title="Create Environment">
- <form onSubmit={handleSubmit}>
- <div className="form-group">
- <Label>Environment Type</Label>
- <select name="type" value={formData.type} onChange={handleChange}>
- {!hasDev && <option value="development">Development</option>}
- {!hasStaging && <option value="staging">Staging</option>}
- </select>
- </div>
-
- <div className="form-group">
- <Label>Environment Name *</Label>
- <Input
- type="text"
- name="name"
- value={formData.name}
- onChange={handleChange}
- placeholder="My Site Dev"
- required
- />
- </div>
-
- <div className="form-group">
- <Label>Domain</Label>
- <Input
- type="text"
- name="domain"
- value={formData.domain}
- onChange={handleChange}
- placeholder={suggestedDomain || 'dev.example.com'}
- />
- {suggestedDomain && !formData.domain && (
- <span className="form-hint form-hint-domain">
- Will use: <code>{suggestedDomain}</code>
- </span>
- )}
- {!suggestedDomain && !formData.domain && (
- <span className="form-hint">Enter a domain or leave empty to auto-generate</span>
- )}
- </div>
-
- {displayDomain && (
- <div className="env-preview-url">
- <span className="preview-label">Environment URL:</span>
- <span className="preview-url">https://{displayDomain}</span>
- </div>
- )}
-
- <div className="form-group">
- <label className="checkbox-label">
- <input
- type="checkbox"
- name="cloneDb"
- checked={formData.cloneDb}
- onChange={handleChange}
- />
- <span>Clone production database</span>
- </label>
- </div>
-
- <div className="form-group">
- <Label>Sync Schedule (optional)</Label>
- <select name="syncSchedule" value={formData.syncSchedule} onChange={handleChange}>
- <option value="">No automatic sync</option>
- <option value="0 3 * * 0">Weekly (Sunday 3am)</option>
- <option value="0 3 * * *">Daily (3am)</option>
- </select>
- <span className="form-hint">Automatically sync database from production</span>
- </div>
-
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose}>
- Cancel
- </Button>
- <Button type="submit" disabled={loading}>
- {loading ? 'Creating...' : 'Create Environment'}
- </Button>
- </div>
- </form>
- </Modal>
- );
-};
-
-export default EnvironmentsTab;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/GitTab.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/GitTab.jsx
deleted file mode 100644
index d34af5d7..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/GitTab.jsx
+++ /dev/null
@@ -1,130 +0,0 @@
-import { useState, useEffect } from 'react';
-import { RefreshCw } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { GitConnectForm, CommitList } from '../index';
-import { ErrorState } from '@/components/ErrorBoundary';
-import { Button } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-
-// Git Tab
-const GitTab = ({ siteId, site, onUpdate }) => {
- const toast = useToast();
- const [gitStatus, setGitStatus] = useState(null);
- const [commits, setCommits] = useState([]);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState(null);
-
- useEffect(() => {
- loadGitData();
- }, [siteId]);
-
- async function loadGitData() {
- setLoading(true);
- setError(null);
- try {
- const statusData = await wordpressApi.getGitStatus(siteId);
- setGitStatus(statusData);
-
- if (statusData.connected) {
- const commitsData = await wordpressApi.getCommits(siteId);
- setCommits(commitsData.commits || []);
- }
- } catch (err) {
- console.error('Failed to load git data:', err);
- setError(err);
- } finally {
- setLoading(false);
- }
- }
-
- async function handleConnect(data) {
- await wordpressApi.connectRepo(siteId, data);
- toast.success('Repository connected');
- loadGitData();
- onUpdate?.();
- }
-
- async function handleDisconnect() {
- await wordpressApi.disconnectRepo(siteId);
- toast.success('Repository disconnected');
- loadGitData();
- onUpdate?.();
- }
-
- async function handleDeploy(data) {
- try {
- await wordpressApi.deployCommit(siteId, data);
- toast.success('Deployment completed');
- loadGitData();
- onUpdate?.();
- } catch (err) {
- toast.error(err.message || 'Deployment failed');
- }
- }
-
- async function handleCreateDev(data) {
- try {
- await wordpressApi.createDevFromCommit(siteId, data);
- toast.success('Development environment created');
- } catch (err) {
- toast.error(err.message || 'Failed to create environment');
- }
- }
-
- if (loading) {
- return (
- <SkeletonBoundary loading skeleton={(
- <div className="git-tab">
- <div className="git-connect git-connect--card">
- <div className="skeleton" style={{ width: 200, height: 24, marginBottom: 16 }} />
- <div className="skeleton" style={{ height: 44, borderRadius: 6, marginBottom: 12 }} />
- <div className="skeleton" style={{ height: 44, borderRadius: 6, marginBottom: 12 }} />
- <div className="skeleton" style={{ width: 140, height: 36, borderRadius: 6 }} />
- </div>
- </div>
- )} />
- );
- }
-
- if (error) {
- return (
- <ErrorState
- title="Failed to load Git information"
- error={error}
- onRetry={loadGitData}
- />
- );
- }
-
- return (
- <div className="git-tab">
- <GitConnectForm
- gitStatus={gitStatus}
- onConnect={handleConnect}
- onDisconnect={handleDisconnect}
- />
-
- {gitStatus?.connected && (
- <div className="git-commits-section">
- <div className="section-header">
- <h3>Recent Commits</h3>
- <Button variant="outline" size="sm" onClick={loadGitData}>
- <RefreshCw size={14} /> Refresh
- </Button>
- </div>
-
- <CommitList
- commits={commits}
- currentCommit={site.last_deploy_commit}
- onDeploy={handleDeploy}
- onCreateDev={handleCreateDev}
- repoUrl={gitStatus?.repo_url}
- />
- </div>
- )}
- </div>
- );
-};
-
-export default GitTab;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/OverviewTab.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/OverviewTab.jsx
deleted file mode 100644
index 1ad169ab..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/OverviewTab.jsx
+++ /dev/null
@@ -1,400 +0,0 @@
-import { useState, useEffect } from 'react';
-import { ResponsiveContainer, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts';
-import { ExternalLink, Settings, RefreshCw, Plus, Database, Trash2, Replace, ShieldCheck, Zap, Activity, BarChart3, AlertTriangle, HardDrive } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import ActivityFeed from '../ActivityFeed';
-import { MetricCard } from 'serverkit-sdk';
-import { CreateEnvironmentModal } from './EnvironmentsTab';
-import { SearchReplaceModal } from './SettingsTab';
-
-// Overview Tab
-const OverviewTab = ({ site, onUpdate }) => {
- const toast = useToast();
- const [creatingSnapshot, setCreatingSnapshot] = useState(false);
- const [showEnvModal, setShowEnvModal] = useState(false);
- const [syncingAll, setSyncingAll] = useState(false);
- const [flushingCache, setFlushingCache] = useState(false);
- const [hardening, setHardening] = useState(false);
- const [pageCacheActive, setPageCacheActive] = useState(false);
- const [togglingPageCache, setTogglingPageCache] = useState(false);
- const [objectCache, setObjectCache] = useState(null);
- const [togglingCache, setTogglingCache] = useState(false);
- const [showSearchReplace, setShowSearchReplace] = useState(false);
- const [analytics, setAnalytics] = useState(null);
- const [uptime, setUptime] = useState(null);
-
- // Overview KPI + traffic data: uptime (status page) + analytics (access log).
- // Both can be slow or unconfigured, so treat as best-effort (null → "—").
- useEffect(() => {
- let cancelled = false;
- (async () => {
- const [analyticsRes, statusRes] = await Promise.all([
- wordpressApi.getSiteAnalytics(site.id, 168).catch(() => null),
- wordpressApi.getSiteStatusPage(site.id).catch(() => null),
- ]);
- if (cancelled) return;
- setAnalytics(analyticsRes);
- setUptime(statusRes?.component || null);
- })();
- return () => { cancelled = true; };
- }, [site.id]);
-
- async function handleQuickSnapshot() {
- setCreatingSnapshot(true);
- toast.info('Creating snapshot...', { duration: 2000 });
- try {
- await wordpressApi.createSnapshot(site.id, {
- name: `Quick Snapshot ${new Date().toLocaleDateString()}`,
- tag: 'quick',
- description: 'Created from Overview quick action'
- });
- toast.success('Snapshot created successfully');
- } catch (err) {
- toast.error(err.message || 'Failed to create snapshot');
- } finally {
- setCreatingSnapshot(false);
- }
- }
-
- async function handleSyncAll() {
- if (!site.environments?.length) return;
- setSyncingAll(true);
- toast.info(`Syncing ${site.environments.length} environment(s)...`, { duration: 3000 });
- try {
- // Sync each environment sequentially
- for (let i = 0; i < site.environments.length; i++) {
- const env = site.environments[i];
- await wordpressApi.syncEnvironment(site.id, { environment_id: env.id });
- }
- toast.success(`Synced ${site.environments.length} environment(s) from production`);
- onUpdate?.();
- } catch (err) {
- toast.error(err.message || 'Failed to sync environments');
- } finally {
- setSyncingAll(false);
- }
- }
-
- async function handleCreateEnvironment(data) {
- toast.info('Creating environment... This may take a moment.', { duration: 5000 });
- try {
- await wordpressApi.createEnvironment(site.id, data);
- toast.success('Environment created successfully');
- setShowEnvModal(false);
- onUpdate?.();
- } catch (err) {
- toast.error(err.message || 'Failed to create environment');
- }
- }
-
- useEffect(() => {
- let active = true;
- wordpressApi.getPageCache(site.id)
- .then(r => { if (active) setPageCacheActive(Boolean(r?.active)); })
- .catch(() => { /* best-effort; control just shows Enable */ });
- wordpressApi.getObjectCacheStatus(site.id)
- .then(s => { if (active) setObjectCache(s); })
- .catch(() => {});
- return () => { active = false; };
- }, [site.id]);
-
- async function handleTogglePageCache() {
- setTogglingPageCache(true);
- const enabling = !pageCacheActive;
- toast.info(enabling ? 'Enabling page cache...' : 'Disabling page cache...', { duration: 4000 });
- try {
- const res = enabling
- ? await wordpressApi.enablePageCache(site.id)
- : await wordpressApi.disablePageCache(site.id);
- if (res.success === false) {
- toast.error(res.error || 'Page cache change failed');
- } else {
- toast.success(res.message || (enabling ? 'Page cache enabled' : 'Page cache disabled'));
- setPageCacheActive(enabling);
- }
- } catch (err) {
- toast.error(err.message || 'Page cache change failed');
- } finally {
- setTogglingPageCache(false);
- }
- }
-
- async function handleToggleObjectCache() {
- setTogglingCache(true);
- const enabling = !objectCache?.enabled;
- toast.info(enabling ? 'Enabling Redis object cache...' : 'Disabling object cache...', { duration: 4000 });
- try {
- const res = enabling
- ? await wordpressApi.enableObjectCache(site.id)
- : await wordpressApi.disableObjectCache(site.id);
- if (res.success === false) {
- toast.error(res.error || 'Object cache change failed');
- } else {
- toast.success(res.message || (enabling ? 'Object cache enabled' : 'Object cache disabled'));
- const fresh = await wordpressApi.getObjectCacheStatus(site.id).catch(() => null);
- if (fresh) setObjectCache(fresh);
- }
- } catch (err) {
- toast.error(err.message || 'Object cache change failed');
- } finally {
- setTogglingCache(false);
- }
- }
-
- async function handleFlushCache() {
- setFlushingCache(true);
- toast.info('Flushing cache...', { duration: 2000 });
- try {
- const res = await wordpressApi.flushCache(site.id);
- toast.success(res.message || 'Cache flushed');
- } catch (err) {
- toast.error(err.message || 'Failed to flush cache');
- } finally {
- setFlushingCache(false);
- }
- }
-
- async function handleHarden() {
- if (!window.confirm('Apply security hardening? This disables file editing, the XML-RPC endpoint, forces SSL on wp-admin, tightens file permissions, and regenerates security keys (logs users out).')) {
- return;
- }
- setHardening(true);
- toast.info('Applying security hardening...', { duration: 4000 });
- try {
- const res = await wordpressApi.harden(site.id);
- toast.success(res.message || 'Security hardening applied');
- } catch (err) {
- toast.error(err.message || 'Failed to harden site');
- } finally {
- setHardening(false);
- }
- }
-
- async function handleSearchReplace(data) {
- // data = { search, replace, dry_run }
- toast.info(data.dry_run ? 'Running search-replace preview...' : 'Running search-replace...', { duration: 3000 });
- try {
- const res = await wordpressApi.searchReplace(site.id, data);
- if (res.success === false) {
- toast.error(res.error || res.message || 'Search-replace failed');
- return;
- }
- toast.success(data.dry_run ? 'Dry run complete - no changes written' : 'Search-replace complete');
- if (!data.dry_run) setShowSearchReplace(false);
- } catch (err) {
- toast.error(err.message || 'Search-replace failed');
- }
- }
-
- // ---- Overview KPI + Site-info derivations (real data, honest fallbacks) ----
- const compactNum = (n) => {
- if (n == null) return '—';
- if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`;
- if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`;
- return `${n}`;
- };
- const [diskVal, diskUnit] = (site.disk_usage_human || '').split(' ');
- const trafficSeries = analytics?.series || [];
- const fmtTrafficTick = (iso) => new Date(iso).toLocaleDateString([], { month: 'short', day: 'numeric' });
-
- return (
- <div className="wp-overview">
- {/* KPI row — deliberately NON-redundant: status + version already live
- in the page header, so the tiles surface uptime, traffic, error
- rate, and storage instead. */}
- <div className="wp-kpis">
- <MetricCard
- tone="green"
- icon={<Activity size={16} />}
- value={uptime?.uptime_30d != null ? uptime.uptime_30d.toFixed(2) : '—'}
- unit={uptime?.uptime_30d != null ? '%' : undefined}
- label="Uptime (30d)"
- />
- <MetricCard
- tone="accent"
- icon={<BarChart3 size={16} />}
- value={analytics ? compactNum(analytics.unique_visitors ?? 0) : '—'}
- label="Visitors (7d)"
- />
- <MetricCard
- tone={(analytics?.error_rate ?? 0) > 5 ? 'red' : 'amber'}
- icon={<AlertTriangle size={16} />}
- value={analytics ? `${analytics.error_rate ?? 0}` : '—'}
- unit={analytics ? '%' : undefined}
- label="Error rate (7d)"
- />
- <MetricCard
- tone="cyan"
- icon={<HardDrive size={16} />}
- value={diskVal || '—'}
- unit={diskUnit || undefined}
- label="Disk used"
- />
- </div>
-
- <div className="wp-overview-main">
- <div className="app-panel">
- <div className="app-panel-header">Quick Actions</div>
- <div className="app-panel-body">
- <div className="quick-actions-grid">
- {site.url && (
- <>
- <a
- href={site.url}
- target="_blank"
- rel="noopener noreferrer"
- className="quick-action-btn"
- >
- <ExternalLink size={16} />
- Visit Site
- </a>
- <a
- href={`${site.url}/wp-admin`}
- target="_blank"
- rel="noopener noreferrer"
- className="quick-action-btn"
- >
- <Settings size={16} />
- WP Admin
- </a>
- </>
- )}
- {site.is_production && (site.environments || []).length < 2 && (
- <button type="button"
- className="quick-action-btn"
- onClick={() => setShowEnvModal(true)}
- >
- <Plus size={16} />
- Create Environment
- </button>
- )}
- <button type="button"
- className="quick-action-btn"
- onClick={handleQuickSnapshot}
- disabled={creatingSnapshot}
- >
- <Database size={16} />
- {creatingSnapshot ? 'Creating...' : 'Create Snapshot'}
- </button>
- {site.environments?.length > 0 && (
- <button type="button"
- className="quick-action-btn"
- onClick={handleSyncAll}
- disabled={syncingAll}
- >
- <RefreshCw size={16} className={syncingAll ? 'spinning' : ''} />
- {syncingAll ? 'Syncing...' : 'Sync All Envs'}
- </button>
- )}
- <button type="button"
- className="quick-action-btn"
- onClick={handleFlushCache}
- disabled={flushingCache}
- >
- <Trash2 size={16} />
- {flushingCache ? 'Flushing...' : 'Purge Cache'}
- </button>
- <button type="button"
- className="quick-action-btn"
- onClick={handleTogglePageCache}
- disabled={togglingPageCache}
- title={pageCacheActive ? 'Full-page cache is active' : 'Enable a full-page cache for this site'}
- >
- <Zap size={16} />
- {togglingPageCache
- ? 'Working...'
- : (pageCacheActive ? 'Page Cache: On' : 'Enable Page Cache')}
- </button>
- <button type="button"
- className="quick-action-btn"
- onClick={() => setShowSearchReplace(true)}
- >
- <Replace size={16} />
- Search &amp; Replace
- </button>
- <button type="button"
- className="quick-action-btn"
- onClick={handleHarden}
- disabled={hardening}
- >
- <ShieldCheck size={16} />
- {hardening ? 'Hardening...' : 'Harden'}
- </button>
- <button type="button"
- className="quick-action-btn"
- onClick={handleToggleObjectCache}
- disabled={togglingCache}
- title={objectCache?.enabled ? 'Redis object cache is active' : 'Enable a Redis object cache for this site'}
- >
- <Database size={16} />
- {togglingCache
- ? (objectCache?.enabled ? 'Disabling...' : 'Enabling...')
- : (objectCache?.enabled ? 'Object Cache: On' : 'Enable Object Cache')}
- </button>
- </div>
- </div>
- </div>
-
- <div className="app-panel wp-traffic-panel">
- <div className="app-panel-header">
- Traffic
- <span className="wp-panel-sub">Last 7 days · unique visits</span>
- </div>
- <div className="app-panel-body">
- {trafficSeries.length > 0 ? (
- <ResponsiveContainer width="100%" height={250}>
- <AreaChart data={trafficSeries} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}>
- <defs>
- <linearGradient id="wpOvVisits" x1="0" y1="0" x2="0" y2="1">
- <stop offset="5%" stopColor="#6d7cff" stopOpacity={0.35} />
- <stop offset="95%" stopColor="#6d7cff" stopOpacity={0} />
- </linearGradient>
- </defs>
- <CartesianGrid strokeDasharray="3 3" stroke="#888" strokeOpacity={0.15} />
- <XAxis dataKey="hour" tickFormatter={fmtTrafficTick} tick={{ fontSize: 11, fill: '#888' }} minTickGap={28} axisLine={false} tickLine={false} />
- <YAxis allowDecimals={false} tickFormatter={(v) => (v >= 1000 ? `${(v / 1000).toFixed(0)}k` : `${v}`)} tick={{ fontSize: 11, fill: '#888' }} width={34} axisLine={false} tickLine={false} />
- <Tooltip labelFormatter={fmtTrafficTick} />
- <Area type="monotone" dataKey="requests" name="Visits" stroke="#8b93ff" fill="url(#wpOvVisits)" strokeWidth={2} />
- </AreaChart>
- </ResponsiveContainer>
- ) : (
- <p className="hint">No traffic recorded for this period yet — it&apos;s parsed from the site&apos;s access log.</p>
- )}
- </div>
- </div>
- </div>
-
- <div className="app-panel wp-activity-panel">
- <div className="app-panel-header">Recent activity</div>
- <div className="app-panel-body">
- <ActivityFeed projectId={site.id} limit={6} />
- </div>
- </div>
-
- {showEnvModal && (() => {
- const envs = site.environments || [];
- const modalHasStaging = envs.some(e => e.environment_type === 'staging');
- const modalHasDev = envs.some(e => e.environment_type === 'development');
- return (
- <CreateEnvironmentModal
- onClose={() => setShowEnvModal(false)}
- onCreate={handleCreateEnvironment}
- productionDomain={site.url}
- hasStaging={modalHasStaging}
- hasDev={modalHasDev}
- />
- );
- })()}
-
- {showSearchReplace && (
- <SearchReplaceModal
- onClose={() => setShowSearchReplace(false)}
- onSubmit={handleSearchReplace}
- />
- )}
- </div>
- );
-};
-
-export default OverviewTab;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/PhpTab.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/PhpTab.jsx
deleted file mode 100644
index 10fb0785..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/PhpTab.jsx
+++ /dev/null
@@ -1,161 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { OverviewGridSkeleton, PHP_LIMIT_LABELS } from './wpDetailShared';
-
-// PHP Tab — live PHP version + ini limits for the Docker (apache/mod_php) site.
-// Version is the image tag; switching recreates the container (volumes persist).
-// Limits are written as a durable conf.d drop-in (bind-mounted), editable below.
-const PhpTab = ({ siteId }) => {
- const toast = useToast();
- const [php, setPhp] = useState(null);
- const [loading, setLoading] = useState(true);
- const [switching, setSwitching] = useState(false);
- const [form, setForm] = useState({});
- const [saving, setSaving] = useState(false);
-
- const load = React.useCallback(async () => {
- setLoading(true);
- try {
- const data = await wordpressApi.getPhpInfo(siteId);
- const info = data.php || data;
- setPhp(info);
- // Seed the edit form from live values for the editable directives.
- const lim = info?.limits || {};
- const seed = {};
- (info?.editable_limits || []).forEach(k => { seed[k] = lim[k] || ''; });
- setForm(seed);
- } catch (err) {
- toast.error(err.message || 'Failed to load PHP info');
- } finally {
- setLoading(false);
- }
- }, [siteId, toast]);
-
- useEffect(() => { load(); }, [load]);
-
- async function handleSwitch(version) {
- if (!window.confirm(`Switch this site to PHP ${version}? This pulls the wordpress:php${version}-apache image and recreates the container (brief downtime; database and files are preserved).`)) return;
- setSwitching(true);
- toast.info(`Switching to PHP ${version}...`, { duration: 4000 });
- try {
- const res = await wordpressApi.setPhpVersion(siteId, version);
- if (res.success === false) { toast.error(res.error || 'Failed to switch PHP version'); return; }
- toast.success(res.message || `Switched to PHP ${version}`);
- await load();
- } catch (err) {
- toast.error(err.message || 'Failed to switch PHP version');
- } finally {
- setSwitching(false);
- }
- }
-
- async function handleSaveLimits() {
- // Send only the directives that changed from the live value (partial update).
- const live = php?.limits || {};
- const changed = {};
- Object.entries(form).forEach(([k, v]) => {
- const val = (v ?? '').toString().trim();
- if (val && val !== (live[k] || '')) changed[k] = val;
- });
- if (Object.keys(changed).length === 0) { toast.info('No changes to save'); return; }
- if (!window.confirm('Apply these PHP limits? The container reloads (brief downtime; database and files are preserved).')) return;
- setSaving(true);
- try {
- const res = await wordpressApi.setPhpLimits(siteId, changed);
- if (res.success === false) { toast.error(res.error || 'Failed to update PHP limits'); return; }
- toast.success(res.message || 'PHP limits updated');
- await load();
- } catch (err) {
- toast.error(err.message || 'Failed to update PHP limits');
- } finally {
- setSaving(false);
- }
- }
-
- if (loading) return <SkeletonBoundary loading skeleton={<OverviewGridSkeleton panels={2} />} />;
-
- const limits = php?.limits || {};
- const current = php?.php_version || 'Unknown';
- const versions = php?.available_versions || [];
- const editableKeys = php?.editable_limits || [];
-
- return (
- <div className="app-overview-grid">
- <div className="app-overview-left">
- <div className="app-panel">
- <div className="app-panel-header">PHP</div>
- <div className="app-panel-body">
- <div className="app-info-grid">
- <div className="app-info-item">
- <span className="app-info-label">PHP Version</span>
- <span className="app-info-value">{current}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Memory Limit</span>
- <span className="app-info-value">{limits.memory_limit || '-'}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Upload Max Filesize</span>
- <span className="app-info-value">{limits.upload_max_filesize || '-'}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Post Max Size</span>
- <span className="app-info-value">{limits.post_max_size || '-'}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Max Execution Time</span>
- <span className="app-info-value">{limits.max_execution_time || '-'}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Max Input Time</span>
- <span className="app-info-value">{limits.max_input_time || '-'}</span>
- </div>
- </div>
- </div>
- </div>
-
- {versions.length > 0 && (
- <div className="app-panel">
- <div className="app-panel-header">Change PHP Version</div>
- <div className="app-panel-body">
- <p className="hint">Switching rebuilds the container from the official wordpress php-apache image. The database and uploaded files are preserved.</p>
- <div className="app-detail-actions">
- {versions.map(v => (
- <Button key={v} variant="outline" size="sm" disabled={switching || current.startsWith(v)} onClick={() => handleSwitch(v)}>
- {current.startsWith(v) ? `PHP ${v} (current)` : `PHP ${v}`}
- </Button>
- ))}
- </div>
- </div>
- </div>
- )}
-
- {editableKeys.length > 0 && (
- <div className="app-panel">
- <div className="app-panel-header">Edit PHP Limits</div>
- <div className="app-panel-body">
- <p className="hint">Saved as a durable conf.d drop-in bind-mounted into the container, so limits survive a container recreate. Saving reloads the container (brief downtime).</p>
- {editableKeys.map(k => (
- <div className="form-group" key={k}>
- <Label>{PHP_LIMIT_LABELS[k] || k}</Label>
- <Input value={form[k] ?? ''} placeholder={limits[k] || ''} disabled={saving}
- onChange={e => setForm(f => ({ ...f, [k]: e.target.value }))} />
- </div>
- ))}
- <div className="app-detail-actions">
- <Button size="sm" onClick={handleSaveLimits} disabled={saving}>{saving ? 'Saving…' : 'Save limits'}</Button>
- </div>
- </div>
- </div>
- )}
- </div>
- </div>
- );
-};
-
-export default PhpTab;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/PluginsTab.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/PluginsTab.jsx
deleted file mode 100644
index aec9ba50..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/PluginsTab.jsx
+++ /dev/null
@@ -1,255 +0,0 @@
-import { useState, useEffect } from 'react';
-import { Package, Download } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { ErrorState } from '@/components/ErrorBoundary';
-import { EmptyState } from 'serverkit-sdk';
-import { ServiceTile } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Switch } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { ListItemSkeleton } from './wpDetailShared';
-
-// Plugins Tab
-const PluginsTab = ({ siteId }) => {
- const toast = useToast();
- const [plugins, setPlugins] = useState([]);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState(null);
- const [installing, setInstalling] = useState(false);
- 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();
- }, [siteId]);
-
- async function loadPlugins() {
- setLoading(true);
- setError(null);
- try {
- const data = await wordpressApi.getPlugins(siteId);
- setPlugins(data.plugins || []);
- loadManaged();
- } catch (err) {
- console.error('Failed to load plugins:', err);
- setError(err);
- } finally {
- setLoading(false);
- }
- }
-
- // 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;
-
- setInstalling(true);
- try {
- await wordpressApi.installPlugin(siteId, { slug: newPlugin.trim() });
- toast.success('Plugin installed successfully');
- setNewPlugin('');
- loadPlugins();
- } catch (err) {
- toast.error(err.message || 'Failed to install plugin');
- } finally {
- setInstalling(false);
- }
- }
-
- async function handleUpdate(pluginName) {
- setUpdating(pluginName || 'all');
- toast.info(pluginName ? `Updating ${pluginName}...` : 'Updating all plugins...', { duration: 4000 });
- try {
- const res = await wordpressApi.updatePlugins(siteId, pluginName ? [pluginName] : undefined);
- if (res.success === false) {
- toast.error(res.error || 'Plugin update failed');
- return;
- }
- toast.success(res.message || 'Plugins updated');
- loadPlugins();
- } catch (err) {
- toast.error(err.message || 'Plugin update failed');
- } finally {
- setUpdating(null);
- }
- }
-
- async function handleToggle(plugin) {
- const activating = plugin.status !== 'active';
- setToggling(plugin.name);
- try {
- const res = activating
- ? await wordpressApi.activatePlugin(siteId, plugin.name)
- : await wordpressApi.deactivatePlugin(siteId, plugin.name);
- if (res && res.success === false) {
- toast.error(res.error || `Failed to ${activating ? 'activate' : 'deactivate'} ${plugin.name}`);
- return;
- }
- toast.success(`${plugin.title || plugin.name} ${activating ? 'activated' : 'deactivated'}`);
- loadPlugins();
- } catch (err) {
- toast.error(err.message || `Failed to ${activating ? 'activate' : 'deactivate'} plugin`);
- } finally {
- setToggling(null);
- }
- }
-
- if (loading) {
- return (
- <SkeletonBoundary loading skeleton={(
- <div className="plugins-tab">
- <div className="section-header">
- <div className="skeleton" style={{ width: 80, height: 24 }} />
- </div>
- <div className="skeleton" style={{ height: 44, borderRadius: 6, marginBottom: 16 }} />
- <div className="plugins-list">
- <ListItemSkeleton />
- <ListItemSkeleton />
- <ListItemSkeleton />
- </div>
- </div>
- )} />
- );
- }
-
- if (error) {
- return (
- <ErrorState
- title="Failed to load plugins"
- error={error}
- onRetry={loadPlugins}
- />
- );
- }
-
- return (
- <div className="plugins-tab">
- <div className="section-header">
- <h3>Plugins</h3>
- </div>
-
- <form className="install-form" onSubmit={handleInstall}>
- <Input
- type="text"
- value={newPlugin}
- onChange={(e) => setNewPlugin(e.target.value)}
- placeholder="Plugin slug (e.g., akismet, woocommerce)"
- />
- <Button type="submit" disabled={installing}>
- {installing ? 'Installing...' : 'Install Plugin'}
- </Button>
- </form>
-
- {plugins.some(p => p.update === 'available') && (
- <div className="bulk-update-bar">
- <span>{plugins.filter(p => p.update === 'available').length} plugin update(s) available</span>
- <Button
- variant="outline"
- size="sm"
- onClick={() => handleUpdate(null)}
- disabled={updating !== null}
- >
- {updating === 'all' ? 'Updating...' : 'Update all'}
- </Button>
- </div>
- )}
-
- {plugins.length === 0 ? (
- <EmptyState icon={Package} title="No plugins installed" description="Install a plugin by entering its slug above." />
- ) : (
- <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}
- {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>
- {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' && (
- <button
- type="button"
- className="wp-update-flag"
- onClick={() => handleUpdate(plugin.name)}
- disabled={updating !== null}
- >
- <Download size={11} />
- {updating === plugin.name ? 'Updating…' : `Update${plugin.update_version ? ` ${plugin.update_version}` : ''}`}
- </button>
- )}
- </div>
- </div>
- <div className="wp-asset-card__toggle">
- <Switch
- checked={isActive}
- disabled={toggling === plugin.name}
- onCheckedChange={() => handleToggle(plugin)}
- aria-label={isActive ? `Deactivate ${plugin.name}` : `Activate ${plugin.name}`}
- />
- <span className={`wp-asset-card__state ${isActive ? 'is-on' : ''}`}>
- {isActive ? 'Active' : 'Inactive'}
- </span>
- </div>
- </div>
- );
- })}
- </div>
- )}
- </div>
- );
-};
-
-export default PluginsTab;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/ReportsTab.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/ReportsTab.jsx
deleted file mode 100644
index 4e2b329f..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/ReportsTab.jsx
+++ /dev/null
@@ -1,361 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import { ResponsiveContainer, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts';
-import { Printer, Download, Trash2 } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { useConfirm } from 'serverkit-sdk';
-import { Pill } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { OverviewGridSkeleton } from './wpDetailShared';
-
-// Reports Tab — monthly client reports (#33 agency slice). Aggregates the
-// per-site signals that already accrue (uptime/incidents #26, update runs #29,
-// backups, vulnerability posture #28) into a persisted, printable monthly report.
-const ReportsTab = ({ siteId }) => {
- const toast = useToast();
- const { confirm } = useConfirm();
- const [reports, setReports] = useState([]);
- const [selectedId, setSelectedId] = useState(null);
- const [loading, setLoading] = useState(true);
- const [busy, setBusy] = useState(false);
-
- // Last 12 months (current first) as {value:'YYYY-MM', label, year, month}.
- const monthOptions = React.useMemo(() => {
- const opts = [];
- const d = new Date();
- d.setDate(1);
- for (let i = 0; i < 12; i++) {
- const year = d.getFullYear();
- const month = d.getMonth() + 1;
- opts.push({
- value: `${year}-${String(month).padStart(2, '0')}`,
- label: d.toLocaleString([], { month: 'long', year: 'numeric' }),
- year, month,
- });
- d.setMonth(d.getMonth() - 1);
- }
- return opts;
- }, []);
- const [genMonth, setGenMonth] = useState(monthOptions[0].value);
-
- const load = React.useCallback(async (preferLabel) => {
- try {
- const res = await wordpressApi.getReports(siteId);
- const list = res.reports || [];
- setReports(list);
- setSelectedId(prev => {
- if (preferLabel) {
- const match = list.find(r => r.period_label === preferLabel);
- if (match) return match.id;
- }
- if (prev && list.some(r => r.id === prev)) return prev;
- return list.length ? list[0].id : null;
- });
- } catch (err) {
- toast.error(err.message || 'Failed to load reports');
- } finally {
- setLoading(false);
- }
- }, [siteId, toast]);
-
- useEffect(() => { load(); }, [load]);
-
- async function handleGenerate() {
- const opt = monthOptions.find(o => o.value === genMonth) || monthOptions[0];
- setBusy(true);
- try {
- // The API client throws on a non-2xx (e.g. the future-month guard's 400),
- // so a resolved call means success; failures surface via catch.
- await wordpressApi.generateReport(siteId, { year: opt.year, month: opt.month });
- toast.success(`Report generated for ${opt.label}`);
- await load(opt.value);
- } catch (err) {
- toast.error(err.message || 'Failed to generate report');
- } finally {
- setBusy(false);
- }
- }
-
- async function handleDelete(report) {
- const ok = await confirm({
- title: 'Delete report',
- message: `Delete the report for ${report.data?.period?.month_name || report.period_label}? This cannot be undone.`,
- confirmText: 'Delete',
- variant: 'danger',
- });
- if (!ok) return;
- try {
- await wordpressApi.deleteReport(siteId, report.id);
- toast.success('Report deleted');
- await load();
- } catch (err) {
- toast.error(err.message || 'Failed to delete report');
- }
- }
-
- function handleDownload(report) {
- const blob = new Blob([JSON.stringify(report.data, null, 2)], { type: 'application/json' });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = `wp-report-${siteId}-${report.period_label}.json`;
- a.click();
- URL.revokeObjectURL(url);
- }
-
- function handlePrint() {
- document.body.classList.add('wp-report-printing');
- // Clean up on whichever signal fires first: `afterprint` (most engines) or
- // the window regaining focus when the dialog closes (fallback for webviews
- // that don't dispatch afterprint). cleanup is idempotent.
- const cleanup = () => {
- document.body.classList.remove('wp-report-printing');
- window.removeEventListener('afterprint', cleanup);
- window.removeEventListener('focus', cleanup);
- };
- window.addEventListener('afterprint', cleanup);
- window.addEventListener('focus', cleanup, { once: true });
- window.print();
- }
-
- if (loading) return <SkeletonBoundary loading skeleton={<OverviewGridSkeleton panels={2} />} />;
-
- const selected = reports.find(r => r.id === selectedId) || null;
-
- return (
- <div className="app-overview-grid">
- <div className="app-overview-left">
- <div className="app-panel wp-report-no-print">
- <div className="app-panel-header">Generate monthly report</div>
- <div className="app-panel-body">
- <p className="hint">Snapshots this site&apos;s uptime, incidents, update runs, backups, and current security posture for a calendar month into a printable client report.</p>
- <div className="app-detail-actions">
- <select value={genMonth} onChange={e => setGenMonth(e.target.value)} disabled={busy}>
- {monthOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
- </select>
- <Button size="sm" onClick={handleGenerate} disabled={busy}>
- {busy ? 'Generating…' : 'Generate'}
- </Button>
- </div>
- {reports.length > 0 && (
- <div className="app-detail-actions wp-report-month-list">
- {reports.map(r => (
- <Button
- key={r.id}
- variant={r.id === selectedId ? 'default' : 'outline'}
- size="sm"
- onClick={() => setSelectedId(r.id)}
- >
- {r.data?.period?.month_name || r.period_label}
- </Button>
- ))}
- </div>
- )}
- </div>
- </div>
-
- {!selected ? (
- <div className="app-panel wp-report-no-print">
- <div className="app-panel-body">
- <p className="hint">No reports yet — pick a month above and click Generate.</p>
- </div>
- </div>
- ) : (
- <ReportView report={selected} onPrint={handlePrint} onDownload={() => handleDownload(selected)} onDelete={() => handleDelete(selected)} />
- )}
- </div>
- </div>
- );
-};
-
-// The printable rendering of a single monthly report. Wrapped in
-// .wp-report-printable so the print stylesheet can isolate it from the app chrome.
-const ReportView = ({ report, onPrint, onDownload, onDelete }) => {
- const d = report.data || {};
- const period = d.period || {};
- const site = d.site || {};
- const uptime = d.uptime || {};
- const updates = d.updates || {};
- const backups = d.backups || {};
- const vulns = d.vulnerabilities || {};
- const health = d.health || {};
- const sev = vulns.by_severity || {};
- const sevTone = (s) => ({ critical: 'red', high: 'red', medium: 'amber', low: 'cyan' }[s] || 'gray');
- const impactTone = (i) => ({ critical: 'red', major: 'red', minor: 'amber' }[i] || 'gray');
- const fmt = (iso) => (iso ? new Date(iso).toLocaleString() : '—');
- const fmtDay = (key) => {
- if (!key) return '';
- const parts = key.split('-');
- return parts.length === 3 ? Number(parts[2]).toString() : key;
- };
- const dailyHasData = (d.uptime_daily || []).some(x => x.percent !== null);
-
- return (
- <div className="wp-report-printable">
- <div className="app-panel">
- <div className="app-panel-header">
- Report — {period.month_name || report.period_label}
- <span className="wp-report-actions wp-report-no-print">
- <Button variant="outline" size="sm" onClick={onPrint}><Printer size={14} /> Print</Button>
- <Button variant="outline" size="sm" onClick={onDownload}><Download size={14} /> JSON</Button>
- <Button variant="outline" size="sm" onClick={onDelete}><Trash2 size={14} /> Delete</Button>
- </span>
- </div>
- <div className="app-panel-body">
- <div className="app-info-grid">
- <div className="app-info-item"><span className="app-info-label">Site</span><span className="app-info-value">{site.name || '—'}</span></div>
- {site.client && <div className="app-info-item"><span className="app-info-label">Client</span><span className="app-info-value">{site.client}</span></div>}
- <div className="app-info-item"><span className="app-info-label">URL</span><span className="app-info-value">{site.url ? <a href={site.url} target="_blank" rel="noopener noreferrer">{site.url}</a> : '—'}</span></div>
- <div className="app-info-item"><span className="app-info-label">WordPress</span><span className="app-info-value">{site.wp_version || '—'}{site.multisite ? ' · multisite' : ''}</span></div>
- <div className="app-info-item"><span className="app-info-label">Generated</span><span className="app-info-value">{fmt(d.generated_at)}</span></div>
- </div>
- </div>
- </div>
-
- <div className="app-panel">
- <div className="app-panel-header">Summary</div>
- <div className="app-panel-body">
- <div className="app-info-grid">
- <div className="app-info-item"><span className="app-info-label">Uptime</span><span className="app-info-value">{uptime.percent !== null && uptime.percent !== undefined ? `${uptime.percent}%` : 'N/A'}</span></div>
- <div className="app-info-item"><span className="app-info-label">Incidents</span><span className="app-info-value">{d.incident_count ?? 0}</span></div>
- <div className="app-info-item"><span className="app-info-label">Update runs</span><span className="app-info-value">{updates.total_runs ?? 0}</span></div>
- <div className="app-info-item"><span className="app-info-label">Components updated</span><span className="app-info-value">{updates.components_updated ?? 0}</span></div>
- <div className="app-info-item"><span className="app-info-label">Backups</span><span className="app-info-value">{backups.count ?? 0}{backups.count ? ` · ${backups.total_bytes_human}` : ''}</span></div>
- <div className="app-info-item"><span className="app-info-label">Open vulnerabilities</span><span className="app-info-value">{vulns.total ?? 0}</span></div>
- <div className="app-info-item"><span className="app-info-label">Current health</span><span className="app-info-value">{health.status || 'unknown'}</span></div>
- <div className="app-info-item"><span className="app-info-label">Disk usage</span><span className="app-info-value">{health.disk_usage_human || '—'}</span></div>
- </div>
- {(updates.rolled_back > 0 || updates.failed > 0) && (
- <div className="app-detail-actions">
- {updates.completed > 0 && <Pill kind="green">{updates.completed} completed</Pill>}
- {updates.rolled_back > 0 && <Pill kind="amber">{updates.rolled_back} rolled back</Pill>}
- {updates.failed > 0 && <Pill kind="red">{updates.failed} failed</Pill>}
- </div>
- )}
- </div>
- </div>
-
- {uptime.bound && dailyHasData && (
- <div className="app-panel">
- <div className="app-panel-header">Daily uptime</div>
- <div className="app-panel-body">
- <ResponsiveContainer width="100%" height={200}>
- <AreaChart data={d.uptime_daily || []} margin={{ top: 8, right: 8, left: -16, bottom: 0 }}>
- <defs>
- <linearGradient id="wpUptime" x1="0" y1="0" x2="0" y2="1">
- <stop offset="5%" stopColor="#3ddc97" stopOpacity={0.35} />
- <stop offset="95%" stopColor="#3ddc97" stopOpacity={0} />
- </linearGradient>
- </defs>
- <CartesianGrid strokeDasharray="3 3" stroke="#888" strokeOpacity={0.15} />
- <XAxis dataKey="date" tickFormatter={fmtDay} tick={{ fontSize: 11, fill: '#888' }} minTickGap={16} axisLine={false} tickLine={false} />
- <YAxis domain={[0, 100]} tick={{ fontSize: 11, fill: '#888' }} width={36} axisLine={false} tickLine={false} />
- <Tooltip formatter={(v) => (v === null ? 'no data' : `${v}%`)} />
- <Area connectNulls type="monotone" dataKey="percent" name="Uptime %" stroke="#3ddc97" fill="url(#wpUptime)" strokeWidth={2} />
- </AreaChart>
- </ResponsiveContainer>
- <p className="hint">Uptime recomputed from recorded health-check samples ({uptime.samples} this month). Rolling 30-day: {uptime.rolling_30d ?? '—'}%.</p>
- </div>
- </div>
- )}
-
- {(d.incidents || []).length > 0 && (
- <div className="app-panel">
- <div className="app-panel-header">Incidents</div>
- <div className="app-panel-body">
- {d.incidents.map(inc => (
- <div className="wp-run-row" key={inc.id}>
- <div className="wp-run-row-head">
- <Pill kind={impactTone(inc.impact)}>{inc.impact}</Pill>
- <strong>{inc.title}</strong>
- </div>
- <span className="form-hint">
- {fmt(inc.created_at)} → {inc.ongoing ? 'ongoing' : fmt(inc.resolved_at)} · {inc.duration_minutes} min · {inc.status}
- </span>
- </div>
- ))}
- </div>
- </div>
- )}
-
- {(updates.runs || []).length > 0 && (
- <div className="app-panel">
- <div className="app-panel-header">Update runs</div>
- <div className="app-panel-body">
- {updates.runs.map(r => {
- const n = (r.updated || []).length;
- const kind = ({ completed: 'green', rolled_back: 'amber', failed: 'red', running: 'cyan' }[r.status] || 'gray');
- return (
- <div className="wp-run-row" key={r.id}>
- <div className="wp-run-row-head">
- <Pill kind={kind}>{r.status.replace('_', ' ')}</Pill>
- <span className="wp-run-row-meta">{fmt(r.started_at)} · {r.trigger}</span>
- </div>
- <span className="form-hint">
- {n === 0 ? 'No components needed updating' : `${n} component${n === 1 ? '' : 's'} updated`}
- {r.rolled_back ? ' · auto-rolled back' : ''}
- {r.error ? ` · ${r.error}` : ''}
- </span>
- </div>
- );
- })}
- </div>
- </div>
- )}
-
- {(backups.snapshots || []).length > 0 && (
- <div className="app-panel">
- <div className="app-panel-header">Backups</div>
- <div className="app-panel-body">
- {backups.snapshots.map(s => (
- <div className="app-info-item" key={s.id}>
- <span className="app-info-label">{fmt(s.created_at)}{s.tag ? ` · ${s.tag}` : ''}</span>
- <span className="app-info-value">{s.size_human} · {s.status}</span>
- </div>
- ))}
- </div>
- </div>
- )}
-
- <div className="app-panel">
- <div className="app-panel-header">Security posture {vulns.as_of ? `(as of ${fmt(vulns.as_of)})` : ''}</div>
- <div className="app-panel-body">
- {vulns.total > 0 ? (
- <>
- <div className="app-detail-actions">
- {sev.critical > 0 && <Pill kind="red">{sev.critical} critical</Pill>}
- {sev.high > 0 && <Pill kind="red">{sev.high} high</Pill>}
- {sev.medium > 0 && <Pill kind="amber">{sev.medium} medium</Pill>}
- {sev.low > 0 && <Pill kind="cyan">{sev.low} low</Pill>}
- {sev.unknown > 0 && <Pill kind="gray">{sev.unknown} unrated</Pill>}
- </div>
- {(vulns.items || []).map((v, i) => (
- <div className="wp-run-row" key={i}>
- <div className="wp-run-row-head"><Pill kind={sevTone(v.severity)}>{v.severity}</Pill><strong>{v.name}</strong></div>
- <span className="form-hint">
- {v.source}{v.slug ? ` · ${v.slug}` : ''} · installed {v.installed_version}
- {v.fixed_in ? ` · fixed in ${v.fixed_in}` : ' · no fix yet'}
- {v.advisory_id ? ` · ${v.advisory_id}` : ''}
- </span>
- </div>
- ))}
- </>
- ) : (
- <p className="hint">{vulns.as_of ? 'No known vulnerabilities at last scan.' : 'No vulnerability scan has run for this site yet.'}</p>
- )}
- </div>
- </div>
-
- {(d.notes || []).length > 0 && (
- <div className="app-panel">
- <div className="app-panel-body">
- {d.notes.map((n, i) => <p className="hint" key={i}>{n}</p>)}
- </div>
- </div>
- )}
- </div>
- );
-};
-
-export default ReportsTab;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/SecurityTab.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/SecurityTab.jsx
deleted file mode 100644
index dea63841..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/SecurityTab.jsx
+++ /dev/null
@@ -1,249 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { Pill, ScoreGauge } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { OverviewGridSkeleton } from './wpDetailShared';
-
-// Security Tab — per-site security depth (#30): file-integrity verification,
-// WP_DEBUG toggle, and WP-Cron management, all via the Docker-aware WP-CLI bridge.
-const SecurityTab = ({ siteId }) => {
- const toast = useToast();
- const [integrity, setIntegrity] = useState(null);
- const [debug, setDebug] = useState(null);
- const [cron, setCron] = useState(null);
- const [vulns, setVulns] = useState(null);
- const [brute, setBrute] = useState(null);
- const [loading, setLoading] = useState(true);
- const [busy, setBusy] = useState(false);
-
- const loadAll = React.useCallback(async () => {
- try {
- const [i, d, c, v, b] = await Promise.all([
- wordpressApi.getIntegrity(siteId).catch(() => null),
- wordpressApi.getDebug(siteId).catch(() => null),
- wordpressApi.getCron(siteId).catch(() => null),
- wordpressApi.getVulnerabilities(siteId).catch(() => null),
- wordpressApi.getBruteForce(siteId).catch(() => null),
- ]);
- setIntegrity(i); setDebug(d); setCron(c); setVulns(v); setBrute(b);
- } finally {
- setLoading(false);
- }
- }, [siteId]);
-
- useEffect(() => { loadAll(); }, [loadAll]);
- useEffect(() => {
- if (integrity?.status !== 'running') return undefined;
- const t = setTimeout(() => {
- wordpressApi.getIntegrity(siteId).then(setIntegrity).catch(() => {});
- }, 2500);
- return () => clearTimeout(t);
- }, [integrity, siteId]);
-
- async function runIntegrity() {
- try {
- await wordpressApi.scanIntegrity(siteId);
- setIntegrity(await wordpressApi.getIntegrity(siteId));
- } catch (err) { toast.error(err.message || 'Failed to start check'); }
- }
- async function toggleDebug() {
- setBusy(true);
- try {
- const res = await wordpressApi.setDebug(siteId, !debug?.enabled);
- if (res.success === false) { toast.error(res.error || 'Failed to update debug setting'); return; }
- setDebug(res);
- toast.success('Debug setting updated');
- } catch (err) { toast.error(err.message || 'Failed to update debug setting'); }
- finally { setBusy(false); }
- }
- async function runCron() {
- setBusy(true);
- try {
- const r = await wordpressApi.runCron(siteId);
- toast[r.success ? 'success' : 'error'](r.success ? 'Ran due events' : (r.error || 'Failed to run cron'));
- setCron(await wordpressApi.getCron(siteId));
- } catch (err) { toast.error(err.message || 'Failed to run cron'); }
- finally { setBusy(false); }
- }
- async function toggleCron() {
- setBusy(true);
- try { setCron(await wordpressApi.setCronDisabled(siteId, !cron?.disabled)); }
- catch (err) { toast.error(err.message || 'Failed to update WP-Cron'); }
- finally { setBusy(false); }
- }
- async function toggleBrute() {
- const wasEnabled = brute?.enabled;
- setBusy(true);
- try {
- const res = await wordpressApi.setBruteForce(siteId, !wasEnabled);
- if (res.success === false) { toast.error(res.error || 'Failed to update protection'); return; }
- setBrute(await wordpressApi.getBruteForce(siteId));
- toast.success(wasEnabled ? 'Brute-force protection disabled' : 'Brute-force protection enabled');
- } catch (err) { toast.error(err.message || 'Failed to update protection'); }
- finally { setBusy(false); }
- }
- async function unbanIp(ip) {
- setBusy(true);
- try {
- const res = await wordpressApi.unbanBruteForceIp(siteId, ip);
- toast[res.success ? 'success' : 'error'](res.success ? `Unbanned ${ip}` : (res.error || 'Failed to unban'));
- setBrute(await wordpressApi.getBruteForce(siteId));
- } catch (err) { toast.error(err.message || 'Failed to unban'); }
- finally { setBusy(false); }
- }
-
- if (loading) return <SkeletonBoundary loading skeleton={<OverviewGridSkeleton panels={2} />} />;
-
- const intRunning = integrity?.status === 'running';
- const issues = integrity?.issues || [];
-
- // Posture checks — real signals only; checks that haven't run yet stay out
- // of the score (demo's posture ring, computed client-side).
- const vsum = vulns?.summary || {};
- const checks = [
- {
- label: 'Core & plugin files verified',
- state: integrity?.status === 'completed' ? (issues.length === 0 ? 'pass' : 'fail') : 'unknown',
- detail: integrity?.status === 'completed'
- ? (issues.length === 0 ? 'checksums clean' : `${issues.length} issue${issues.length === 1 ? '' : 's'}`)
- : 'not checked yet',
- },
- {
- label: 'WP_DEBUG disabled',
- state: debug ? (debug.debug?.WP_DEBUG ? 'fail' : 'pass') : 'unknown',
- detail: debug ? (debug.debug?.WP_DEBUG ? 'debug is on' : 'off') : 'unavailable',
- },
- {
- label: 'No critical / high vulnerabilities',
- state: vulns?.scanned_at ? (((vsum.critical ?? 0) + (vsum.high ?? 0)) === 0 ? 'pass' : 'fail') : 'unknown',
- detail: vulns?.scanned_at
- ? `${(vsum.critical ?? 0) + (vsum.high ?? 0)} found`
- : 'no scan yet',
- },
- {
- label: 'Login brute-force protection',
- state: brute?.available === false ? 'unknown' : (brute?.enabled ? 'pass' : 'fail'),
- detail: brute?.available === false ? 'fail2ban unavailable' : (brute?.enabled ? 'jail active' : 'not protected'),
- },
- ];
- const scored = checks.filter(c => c.state !== 'unknown');
- const score = scored.length ? Math.round(scored.filter(c => c.state === 'pass').length / scored.length * 100) : null;
- const scoreColor = score >= 80 ? 'var(--green)' : score >= 50 ? 'var(--amber)' : 'var(--red)';
- const CHECK_PILL = { pass: 'green', fail: 'red', unknown: 'gray' };
-
- return (
- <div className="app-overview-grid">
- <div className="app-overview-left">
- <div className="app-panel">
- <div className="app-panel-header">Security posture</div>
- <div className="app-panel-body wp-posture">
- {score !== null ? (
- <ScoreGauge value={score} size={110} stroke={9} color={scoreColor} label="posture" />
- ) : (
- <p className="hint">Run the checks below to compute a posture score.</p>
- )}
- <div className="wp-posture__checks">
- {checks.map(c => (
- <div key={c.label} className="wp-posture__check">
- <span className="wp-posture__label">{c.label}</span>
- <span className="wp-posture__detail">{c.detail}</span>
- <Pill kind={CHECK_PILL[c.state]}>{c.state === 'unknown' ? 'pending' : c.state}</Pill>
- </div>
- ))}
- </div>
- </div>
- </div>
-
- <div className="app-panel">
- <div className="app-panel-header">File integrity</div>
- <div className="app-panel-body">
- <div className="app-detail-actions">
- <Button size="sm" onClick={runIntegrity} disabled={intRunning}>{intRunning ? 'Checking…' : 'Verify checksums'}</Button>
- </div>
- {(!integrity || integrity.status === 'idle') && <p className="hint">Verifies WordPress core and wordpress.org plugins against official checksums to detect tampered or unexpected files.</p>}
- {integrity?.status === 'error' && <p className="hint">Check failed: {integrity.error}</p>}
- {integrity?.status === 'completed' && (
- issues.length === 0
- ? <p className="hint">All core and plugin files verify against official checksums.</p>
- : <>
- <div className="app-detail-actions"><Pill kind="red">{issues.length} issue{issues.length === 1 ? '' : 's'}</Pill></div>
- <div className="wp-code-list">
- {issues.slice(0, 50).map((line, i) => <div key={i}>{line}</div>)}
- </div>
- </>
- )}
- </div>
- </div>
-
- <div className="app-panel">
- <div className="app-panel-header">Debug mode</div>
- <div className="app-panel-body">
- <div className="app-info-grid">
- <div className="app-info-item"><span className="app-info-label">WP_DEBUG</span><span className="app-info-value"><Pill kind={debug?.debug?.WP_DEBUG ? 'amber' : 'gray'}>{debug?.debug?.WP_DEBUG ? 'on' : 'off'}</Pill></span></div>
- <div className="app-info-item"><span className="app-info-label">Debug log</span><span className="app-info-value">{debug?.debug?.WP_DEBUG_LOG ? 'on' : 'off'}</span></div>
- <div className="app-info-item"><span className="app-info-label">Script debug</span><span className="app-info-value">{debug?.debug?.SCRIPT_DEBUG ? 'on' : 'off'}</span></div>
- </div>
- <div className="app-detail-actions">
- <Button variant="outline" size="sm" onClick={toggleDebug} disabled={busy}>{debug?.enabled ? 'Disable debugging' : 'Enable debugging'}</Button>
- </div>
- <p className="hint">Logs errors to a private file outside the web root (never to the page or a public URL). Enable to capture PHP fatals; disable in production.</p>
- </div>
- </div>
-
- <div className="app-panel">
- <div className="app-panel-header">WP-Cron</div>
- <div className="app-panel-body">
- <div className="app-info-grid">
- <div className="app-info-item"><span className="app-info-label">Pseudo-cron</span><span className="app-info-value">{cron?.disabled ? 'disabled' : 'enabled'}</span></div>
- <div className="app-info-item"><span className="app-info-label">Scheduled events</span><span className="app-info-value">{(cron?.events || []).length}</span></div>
- </div>
- <div className="app-detail-actions">
- <Button variant="outline" size="sm" onClick={runCron} disabled={busy}>Run due events</Button>
- <Button variant="outline" size="sm" onClick={toggleCron} disabled={busy}>{cron?.disabled ? 'Enable WP-Cron' : 'Disable WP-Cron'}</Button>
- </div>
- <p className="hint">Disable WP-Cron only if a real system cron hits wp-cron.php — otherwise scheduled tasks (publishing, updates) will not run.</p>
- </div>
- </div>
-
- <div className="app-panel">
- <div className="app-panel-header">Brute-force protection</div>
- <div className="app-panel-body">
- {brute?.available === false ? (
- <p className="hint">Fail2ban isn’t installed on this server, so login brute-force protection is inactive. Install it from the <strong>Security → Fail2ban</strong> page to enable per-site jails.</p>
- ) : (
- <>
- <div className="app-info-grid">
- <div className="app-info-item"><span className="app-info-label">Login jail</span><span className="app-info-value"><Pill kind={brute?.enabled ? 'green' : 'gray'}>{brute?.enabled ? 'active' : 'off'}</Pill></span></div>
- <div className="app-info-item"><span className="app-info-label">Currently banned</span><span className="app-info-value">{brute?.currently_banned ?? 0}</span></div>
- <div className="app-info-item"><span className="app-info-label">Total bans</span><span className="app-info-value">{brute?.total_banned ?? 0}</span></div>
- </div>
- <div className="app-detail-actions">
- <Button variant="outline" size="sm" onClick={toggleBrute} disabled={busy}>{brute?.enabled ? 'Disable protection' : 'Enable protection'}</Button>
- </div>
- {(brute?.banned_ips?.length > 0) && (
- <div className="wp-banlist">
- {brute.banned_ips.map(ip => (
- <div key={ip} className="wp-banlist__row">
- <span className="wp-banlist__ip">{ip}</span>
- <Button variant="ghost" size="sm" onClick={() => unbanIp(ip)} disabled={busy}>Unban</Button>
- </div>
- ))}
- </div>
- )}
- <p className="hint">
- Bans IPs that repeatedly POST to <code>wp-login.php</code> or <code>xmlrpc.php</code>
- {brute?.thresholds ? ` (${brute.thresholds.maxretry} attempts / ${Math.round(brute.thresholds.findtime / 60)} min → ${Math.round(brute.thresholds.bantime / 60)} min ban)` : ''}.
- {brute?.available && brute?.fail2ban_running === false ? ' Fail2ban is installed but not running — start it on the Security page.' : ''}
- </p>
- </>
- )}
- </div>
- </div>
- </div>
- </div>
- );
-};
-
-export default SecurityTab;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/SettingsTab.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/SettingsTab.jsx
deleted file mode 100644
index 5b543050..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/SettingsTab.jsx
+++ /dev/null
@@ -1,354 +0,0 @@
-import { useState } from 'react';
-import { useParams, useNavigate } from 'react-router-dom';
-import { Plus, Globe, Copy, Settings, RefreshCw, Archive, GitBranch, Lock, Shield, ShieldCheck, ShieldAlert, FileBarChart, Trash2 } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { useConfirm } from 'serverkit-sdk';
-import { DangerZone } from '@/components/DangerZone';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { SiteSSLPanel } from './wpDetailShared';
-import PhpTab from './PhpTab';
-import UpdatesTab from './UpdatesTab';
-import BackupsTab from './BackupsTab';
-import GitTab from './GitTab';
-import SecurityTab from './SecurityTab';
-import VulnerabilitiesTab from './VulnerabilitiesTab';
-import ReportsTab from './ReportsTab';
-
-// Search & Replace Modal (DB string replacement, guarded by dry-run)
-export const SearchReplaceModal = ({ onClose, onSubmit }) => {
- const [search, setSearch] = useState('');
- const [replace, setReplace] = useState('');
- const [loading, setLoading] = useState(false);
-
- async function run(dryRun) {
- if (!search.trim() || !replace.trim()) return;
- setLoading(true);
- try {
- await onSubmit({ search: search.trim(), replace: replace.trim(), dry_run: dryRun });
- } finally {
- setLoading(false);
- }
- }
-
- return (
- <Modal open onClose={onClose} title="Search & Replace">
- <form onSubmit={(e) => { e.preventDefault(); run(false); }}>
- <p className="hint">Replaces a string across all database tables (e.g. an old domain). Always preview with a dry run first.</p>
-
- <div className="form-group">
- <Label>Search for *</Label>
- <Input
- type="text"
- value={search}
- onChange={(e) => setSearch(e.target.value)}
- placeholder="https://old-domain.com"
- required
- />
- </div>
-
- <div className="form-group">
- <Label>Replace with *</Label>
- <Input
- type="text"
- value={replace}
- onChange={(e) => setReplace(e.target.value)}
- placeholder="https://new-domain.com"
- required
- />
- </div>
-
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose}>
- Cancel
- </Button>
- <Button type="button" variant="outline" onClick={() => run(true)} disabled={loading || !search.trim() || !replace.trim()}>
- {loading ? 'Running...' : 'Dry Run'}
- </Button>
- <Button type="submit" disabled={loading || !search.trim() || !replace.trim()}>
- {loading ? 'Running...' : 'Run Replace'}
- </Button>
- </div>
- </form>
- </Modal>
- );
-};
-
-// Delete Site Modal (typed confirmation + optional final backup)
-const DeleteSiteModal = ({ siteName, onClose, onConfirm }) => {
- const [createBackup, setCreateBackup] = useState(true);
- const [typed, setTyped] = useState('');
- const [loading, setLoading] = useState(false);
- const canDelete = typed.trim() === siteName;
-
- async function handleSubmit(e) {
- e.preventDefault();
- if (!canDelete) return;
- setLoading(true);
- try {
- await onConfirm(createBackup);
- } finally {
- setLoading(false);
- }
- }
-
- return (
- <Modal open onClose={onClose} title="Delete Site">
- <form onSubmit={handleSubmit}>
- <p className="hint">This permanently deletes <strong>{siteName}</strong>, all its environments, files and databases. This cannot be undone.</p>
- <div className="form-group">
- <label className="checkbox-label">
- <input
- type="checkbox"
- checked={createBackup}
- onChange={(e) => setCreateBackup(e.target.checked)}
- />
- <span>Create a final files + database backup before deleting</span>
- </label>
- </div>
- <div className="form-group">
- <Label>Type <strong>{siteName}</strong> to confirm *</Label>
- <Input
- type="text"
- value={typed}
- onChange={(e) => setTyped(e.target.value)}
- placeholder={siteName}
- autoFocus
- />
- </div>
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose} disabled={loading}>
- Cancel
- </Button>
- <Button type="submit" variant="destructive" disabled={loading || !canDelete}>
- {loading ? 'Deleting...' : 'Delete Site'}
- </Button>
- </div>
- </form>
- </Modal>
- );
-};
-
-// Settings tab — a left sub-nav that consolidates per-site configuration which
-// used to be its own top-level tabs (PHP, safe Updates, …). Each section just
-// reuses the existing tab component, so behavior is unchanged — only the home
-// moves. Defined last so the section components above are already in scope.
-// General settings — site-level actions that don't warrant an everyday top-bar
-// button (point a domain, change the URL, clone the site). They open the modals
-// that already live in WordPressDetail, via handlers passed down through ctx.
-const GeneralSettings = ({ onAddDomain, onChangeUrl, onClone }) => (
- <div className="app-overview-grid">
- <div className="app-overview-left">
- <div className="app-panel">
- <div className="app-panel-header">Domains &amp; URL</div>
- <div className="app-panel-body">
- <p className="hint">Point a custom domain you own at this site (auto-DNS + migrate), or change its primary URL with a serialization-safe database rewrite.</p>
- <div className="app-detail-actions">
- <Button variant="outline" size="sm" onClick={onAddDomain}>
- <Plus size={15} /> Add Domain
- </Button>
- <Button variant="outline" size="sm" onClick={onChangeUrl}>
- <Globe size={15} /> Change URL
- </Button>
- </div>
- </div>
- </div>
- <div className="app-panel">
- <div className="app-panel-header">Duplicate site</div>
- <div className="app-panel-body">
- <p className="hint">Clone this site as a brand-new independent site (its own Docker stack and database) with fresh admin credentials.</p>
- <div className="app-detail-actions">
- <Button variant="outline" size="sm" onClick={onClone}>
- <Copy size={15} /> Clone site
- </Button>
- </div>
- </div>
- </div>
- </div>
- </div>
-);
-
-// Danger Zone settings — destructive site-level actions moved out of the
-// Overview tab into Settings so the daily dashboard isn't dominated by them.
-const DangerZoneSettings = ({ site, onUpdate }) => {
- const toast = useToast();
- const navigate = useNavigate();
- const { confirm } = useConfirm();
- const [archiving, setArchiving] = useState(false);
- const [showDeleteModal, setShowDeleteModal] = useState(false);
-
- async function handleArchive() {
- const ok = await confirm({
- title: 'Archive Site',
- message: `Stop and archive "${site.name}"? Containers are stopped but all files and the database are kept. You can unarchive it later.`,
- confirmText: 'Archive',
- variant: 'warning',
- });
- if (!ok) return;
- setArchiving(true);
- toast.info('Archiving site...', { duration: 3000 });
- try {
- await wordpressApi.archiveSite(site.id);
- toast.success('Site archived');
- onUpdate?.();
- } catch (err) {
- toast.error(err.message || 'Failed to archive site');
- } finally {
- setArchiving(false);
- }
- }
-
- async function handleUnarchive() {
- setArchiving(true);
- toast.info('Unarchiving site...', { duration: 3000 });
- try {
- await wordpressApi.unarchiveSite(site.id);
- toast.success('Site unarchived');
- onUpdate?.();
- } catch (err) {
- toast.error(err.message || 'Failed to unarchive site');
- } finally {
- setArchiving(false);
- }
- }
-
- async function handleDelete(createBackup) {
- toast.info(createBackup ? 'Creating final backup and deleting site...' : 'Deleting site...', { duration: 5000 });
- try {
- await wordpressApi.deleteSite(site.id, { createBackup });
- toast.success('Site deleted');
- setShowDeleteModal(false);
- navigate('/wordpress');
- } catch (err) {
- toast.error(err.message || 'Failed to delete site');
- }
- }
-
- return (
- <>
- {showDeleteModal && (
- <DeleteSiteModal
- siteName={site.name}
- onClose={() => setShowDeleteModal(false)}
- onConfirm={handleDelete}
- />
- )}
- <div className="app-overview-grid">
- <div className="app-overview-left">
- <div className="app-panel danger-zone-panel">
- <div className="app-panel-header">Danger Zone</div>
- <div className="app-panel-body danger-zone-body">
- {site.status === 'archived' ? (
- <DangerZone
- title="Unarchive Site"
- description="Restart this site's containers and bring it back online."
- action={(
- <Button variant="outline" onClick={handleUnarchive} disabled={archiving}>
- <Archive size={16} />
- {archiving ? 'Unarchiving...' : 'Unarchive'}
- </Button>
- )}
- />
- ) : (
- <DangerZone
- title="Archive Site"
- description="Stop the containers but keep all files and the database. Reversible."
- action={(
- <Button variant="outline" onClick={handleArchive} disabled={archiving}>
- <Archive size={16} />
- {archiving ? 'Archiving...' : 'Archive'}
- </Button>
- )}
- />
- )}
- <DangerZone
- title="Delete Site"
- description="Permanently remove this site, all environments, files and databases. A final backup is taken by default."
- action={(
- <Button variant="destructive" onClick={() => setShowDeleteModal(true)}>
- <Trash2 size={16} />
- Delete Site
- </Button>
- )}
- />
- </div>
- </div>
- </div>
- </div>
- </>
- );
-};
-
-// Grouped left nav for the Settings tab. Each item just re-renders the existing
-// per-feature component (passed a single `ctx`), so behavior is unchanged — only
-// the home moves here to keep the top tab strip short. Groups give the nav
-// structure (the user's "group section" idea) and room to grow.
-const WP_SETTINGS_GROUPS = [
- { label: 'General', items: [
- { id: 'general', label: 'General', icon: Globe, render: (ctx) => <GeneralSettings {...ctx} /> },
- ] },
- { label: 'Configuration', items: [
- { id: 'php', label: 'PHP', icon: Settings, render: (ctx) => <PhpTab siteId={ctx.siteId} /> },
- { id: 'updates', label: 'Updates', icon: RefreshCw, render: (ctx) => <UpdatesTab siteId={ctx.siteId} /> },
- ] },
- { label: 'Data', items: [
- { id: 'backups', label: 'Backups', icon: Archive, render: (ctx) => <BackupsTab siteId={ctx.siteId} site={ctx.site} /> },
- ] },
- { label: 'Connections', items: [
- { id: 'git', label: 'Git', icon: GitBranch, render: (ctx) => <GitTab siteId={ctx.siteId} site={ctx.site} onUpdate={ctx.onUpdate} /> },
- ] },
- { label: 'Security', items: [
- { id: 'security', label: 'Security', icon: Lock, render: (ctx) => <SecurityTab siteId={ctx.siteId} /> },
- { id: 'ssl', label: 'SSL', icon: Shield, render: (ctx) => <SiteSSLPanel site={ctx.site} onUpdate={ctx.onUpdate} /> },
- { id: 'vulnerabilities', label: 'Vulnerabilities', icon: ShieldCheck, render: (ctx) => <VulnerabilitiesTab siteId={ctx.siteId} /> },
- ] },
- { label: 'Reports', items: [
- { id: 'reports', label: 'Reports', icon: FileBarChart, render: (ctx) => <ReportsTab siteId={ctx.siteId} /> },
- ] },
- { label: 'Danger Zone', items: [
- { id: 'danger-zone', label: 'Danger Zone', icon: ShieldAlert, render: (ctx) => <DangerZoneSettings site={ctx.site} onUpdate={ctx.onUpdate} /> },
- ] },
-];
-
-const WP_SETTINGS_ITEMS = WP_SETTINGS_GROUPS.flatMap((g) => g.items);
-
-const SettingsTab = ({ siteId, site, onUpdate, onAddDomain, onChangeUrl, onClone }) => {
- // Section lives in the URL (/wordpress/:id/settings/:section) so it's
- // shareable and survives a refresh, instead of resetting to General.
- const { id, section: sectionParam } = useParams();
- const navigate = useNavigate();
- const section = WP_SETTINGS_ITEMS.some((s) => s.id === sectionParam) ? sectionParam : 'general';
- const setSection = (s) => navigate(`/wordpress/${id}/settings/${s}`, { replace: true });
- const active = WP_SETTINGS_ITEMS.find((s) => s.id === section) || WP_SETTINGS_ITEMS[0];
- const ctx = { siteId, site, onUpdate, onAddDomain, onChangeUrl, onClone };
- return (
- <div className="wp-settings">
- <nav className="wp-settings__nav" aria-label="WordPress settings sections">
- {WP_SETTINGS_GROUPS.map((g) => (
- <div className="wp-settings__group" key={g.label}>
- <div className="wp-settings__grouplabel">{g.label}</div>
- {g.items.map((s) => (
- <button
- type="button"
- key={s.id}
- className={`wp-settings__navitem ${section === s.id ? 'is-active' : ''}`}
- onClick={() => setSection(s.id)}
- >
- <s.icon size={15} />
- {s.label}
- </button>
- ))}
- </div>
- ))}
- </nav>
- <div className="wp-settings__content">
- {active.render(ctx)}
- </div>
- </div>
- );
-};
-
-export default SettingsTab;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/ThemesTab.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/ThemesTab.jsx
deleted file mode 100644
index c2d67667..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/ThemesTab.jsx
+++ /dev/null
@@ -1,203 +0,0 @@
-import { useState, useEffect } from 'react';
-import { Palette } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { ErrorState } from '@/components/ErrorBoundary';
-import { EmptyState } from 'serverkit-sdk';
-import { Pill } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { ListItemSkeleton } from './wpDetailShared';
-
-// Themes Tab
-const ThemesTab = ({ siteId }) => {
- const toast = useToast();
- const [themes, setThemes] = useState([]);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState(null);
- const [installing, setInstalling] = useState(false);
- const [updating, setUpdating] = useState(null); // theme name being updated, or 'all'
- const [newTheme, setNewTheme] = useState('');
- const [activating, setActivating] = useState(null); // theme name being activated
-
- useEffect(() => {
- loadThemes();
- }, [siteId]);
-
- async function loadThemes() {
- setLoading(true);
- setError(null);
- try {
- const data = await wordpressApi.getThemes(siteId);
- setThemes(data.themes || []);
- } catch (err) {
- console.error('Failed to load themes:', err);
- setError(err);
- } finally {
- setLoading(false);
- }
- }
-
- async function handleInstall(e) {
- e.preventDefault();
- if (!newTheme.trim()) return;
-
- setInstalling(true);
- try {
- await wordpressApi.installTheme(siteId, { slug: newTheme.trim() });
- toast.success('Theme installed successfully');
- setNewTheme('');
- loadThemes();
- } catch (err) {
- toast.error(err.message || 'Failed to install theme');
- } finally {
- setInstalling(false);
- }
- }
-
- async function handleUpdate(themeName) {
- setUpdating(themeName || 'all');
- toast.info(themeName ? `Updating ${themeName}...` : 'Updating all themes...', { duration: 4000 });
- try {
- const res = await wordpressApi.updateThemes(siteId, themeName ? [themeName] : undefined);
- if (res.success === false) {
- toast.error(res.error || 'Theme update failed');
- return;
- }
- toast.success(res.message || 'Themes updated');
- loadThemes();
- } catch (err) {
- toast.error(err.message || 'Theme update failed');
- } finally {
- setUpdating(null);
- }
- }
-
- async function handleActivate(theme) {
- setActivating(theme.name);
- try {
- const res = await wordpressApi.activateTheme(siteId, theme.name);
- if (res && res.success === false) {
- toast.error(res.error || `Failed to activate ${theme.name}`);
- return;
- }
- toast.success(`${theme.title || theme.name} activated`);
- loadThemes();
- } catch (err) {
- toast.error(err.message || 'Failed to activate theme');
- } finally {
- setActivating(null);
- }
- }
-
- if (loading) {
- return (
- <SkeletonBoundary loading skeleton={(
- <div className="themes-tab">
- <div className="section-header">
- <div className="skeleton" style={{ width: 80, height: 24 }} />
- </div>
- <div className="skeleton" style={{ height: 44, borderRadius: 6, marginBottom: 16 }} />
- <div className="themes-list">
- <ListItemSkeleton />
- <ListItemSkeleton />
- <ListItemSkeleton />
- </div>
- </div>
- )} />
- );
- }
-
- if (error) {
- return (
- <ErrorState
- title="Failed to load themes"
- error={error}
- onRetry={loadThemes}
- />
- );
- }
-
- return (
- <div className="themes-tab">
- <div className="section-header">
- <h3>Themes</h3>
- </div>
-
- <form className="install-form" onSubmit={handleInstall}>
- <Input
- type="text"
- value={newTheme}
- onChange={(e) => setNewTheme(e.target.value)}
- placeholder="Theme slug (e.g., twentytwentyfour)"
- />
- <Button type="submit" disabled={installing}>
- {installing ? 'Installing...' : 'Install Theme'}
- </Button>
- </form>
-
- {themes.some(t => t.update === 'available') && (
- <div className="bulk-update-bar">
- <span>{themes.filter(t => t.update === 'available').length} theme update(s) available</span>
- <Button
- variant="outline"
- size="sm"
- onClick={() => handleUpdate(null)}
- disabled={updating !== null}
- >
- {updating === 'all' ? 'Updating...' : 'Update all'}
- </Button>
- </div>
- )}
-
- {themes.length === 0 ? (
- <EmptyState icon={Palette} title="No themes installed" description="Install a theme by entering its slug above." />
- ) : (
- <div className="wp-theme-grid">
- {themes.map(theme => {
- const isActive = theme.status === 'active';
- return (
- <div className={`wp-theme-card ${isActive ? 'is-active' : ''}`} key={theme.name}>
- <div className="wp-theme-card__shot">
- <Palette size={26} />
- {isActive && <Pill kind="green">Active</Pill>}
- </div>
- <div className="wp-theme-card__meta">
- <div className="wp-theme-card__name">{theme.title || theme.name}</div>
- <div className="wp-theme-card__sub">{theme.name} · v{theme.version}</div>
- <div className="wp-theme-card__actions">
- {isActive ? (
- <span className="wp-theme-card__current">Current theme</span>
- ) : (
- <Button
- variant="outline"
- size="sm"
- onClick={() => handleActivate(theme)}
- disabled={activating === theme.name}
- >
- {activating === theme.name ? 'Activating…' : 'Activate'}
- </Button>
- )}
- {theme.update === 'available' && (
- <Button
- variant="ghost"
- size="sm"
- onClick={() => handleUpdate(theme.name)}
- disabled={updating !== null}
- >
- {updating === theme.name ? 'Updating…' : 'Update'}
- </Button>
- )}
- </div>
- </div>
- </div>
- );
- })}
- </div>
- )}
- </div>
- );
-};
-
-export default ThemesTab;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/UpdatesTab.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/UpdatesTab.jsx
deleted file mode 100644
index 79febcb4..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/UpdatesTab.jsx
+++ /dev/null
@@ -1,137 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { Pill } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { OverviewGridSkeleton, UPDATE_SCHEDULES } from './wpDetailShared';
-
-// Updates Tab — safe update manager (#29): snapshot -> update -> health-check ->
-// auto-rollback, plus a per-site schedule and a run-history report.
-const UpdatesTab = ({ siteId }) => {
- const toast = useToast();
- const [data, setData] = useState(null);
- const [loading, setLoading] = useState(true);
- const [busy, setBusy] = useState(false);
- const [schedule, setSchedule] = useState('');
- const [excludeText, setExcludeText] = useState('');
-
- const load = React.useCallback(async () => {
- try {
- const res = await wordpressApi.getUpdates(siteId);
- setData(res);
- setSchedule(res.schedule || '');
- setExcludeText((res.exclude || []).join(', '));
- } catch (err) {
- toast.error(err.message || 'Failed to load updates');
- } finally {
- setLoading(false);
- }
- }, [siteId, toast]);
-
- useEffect(() => { load(); }, [load]);
- useEffect(() => {
- if (!data?.running) return undefined;
- const t = setTimeout(() => { wordpressApi.getUpdates(siteId).then(setData).catch(() => {}); }, 3000);
- return () => clearTimeout(t);
- }, [data, siteId]);
-
- const toList = (s) => s.split(',').map(x => x.trim()).filter(Boolean);
-
- async function runUpdate() {
- if (!window.confirm('Run a safe update now? A database snapshot is taken first and the site auto-rolls-back if the update breaks it.')) return;
- setBusy(true);
- try {
- await wordpressApi.runUpdates(siteId, { exclude: toList(excludeText) });
- toast.info('Safe update started…');
- setData(await wordpressApi.getUpdates(siteId));
- } catch (err) { toast.error(err.message || 'Failed to start update'); }
- finally { setBusy(false); }
- }
- async function saveSchedule() {
- setBusy(true);
- try {
- await wordpressApi.setUpdateSchedule(siteId, { schedule, exclude: toList(excludeText) });
- toast.success('Schedule saved');
- await load();
- } catch (err) { toast.error(err.message || 'Failed to save schedule'); }
- finally { setBusy(false); }
- }
-
- if (loading) return <SkeletonBoundary loading skeleton={<OverviewGridSkeleton panels={2} />} />;
-
- const runs = data?.runs || [];
- const running = data?.running;
- const statusPill = (s) => ({ completed: 'green', rolled_back: 'amber', failed: 'red', running: 'cyan' }[s] || 'gray');
-
- return (
- <div className="app-overview-grid">
- <div className="app-overview-left">
- <div className="app-panel">
- <div className="app-panel-header">Safe update</div>
- <div className="app-panel-body">
- <p className="hint">Snapshots the database, updates core + plugins + themes, health-checks the site, and automatically rolls back (version-pin + DB restore) if the update breaks it.</p>
- <div className="form-group">
- <Label>Exclude (skip) plugins/themes</Label>
- <Input value={excludeText} onChange={e => setExcludeText(e.target.value)} placeholder="e.g. woocommerce, my-custom-plugin" />
- <span className="form-hint">Comma-separated slugs to never auto-update.</span>
- </div>
- <div className="app-detail-actions">
- <Button size="sm" onClick={runUpdate} disabled={busy || running}>{running ? 'Updating…' : 'Run safe update now'}</Button>
- </div>
- </div>
- </div>
-
- <div className="app-panel">
- <div className="app-panel-header">Schedule</div>
- <div className="app-panel-body">
- <div className="form-group">
- <Label>Automatic safe updates</Label>
- <select value={schedule} onChange={e => setSchedule(e.target.value)} disabled={busy}>
- {UPDATE_SCHEDULES.map(s => <option key={s.value} value={s.value}>{s.label}</option>)}
- {schedule && !UPDATE_SCHEDULES.some(s => s.value === schedule) && <option value={schedule}>{schedule}</option>}
- </select>
- <span className="form-hint">Runs the same safe update (with auto-rollback) on a schedule.</span>
- </div>
- <div className="app-detail-actions">
- <Button variant="outline" size="sm" onClick={saveSchedule} disabled={busy}>Save schedule</Button>
- </div>
- </div>
- </div>
-
- <div className="app-panel">
- <div className="app-panel-header">Update history</div>
- <div className="app-panel-body">
- {runs.length === 0 ? (
- <p className="hint">No updates have run yet.</p>
- ) : runs.map(r => {
- const d = r.details || {};
- const n = (d.updated || []).length;
- return (
- <div className="wp-run-row" key={r.id}>
- <div className="wp-run-row-head">
- <Pill kind={statusPill(r.status)}>{r.status.replace('_', ' ')}</Pill>
- <span className="wp-run-row-meta">{r.started_at ? new Date(r.started_at).toLocaleString() : ''} · {r.trigger}</span>
- </div>
- <span className="form-hint">
- {n === 0 ? 'No components needed updating' : `${n} component${n === 1 ? '' : 's'} updated`}
- {d.rolled_back ? ' · auto-rolled back (update regressed the site)' : ''}
- {r.error ? ` · ${r.error}` : ''}
- </span>
- {d.warning && <span className="form-hint">⚠ {d.warning}</span>}
- {(d.updated || []).slice(0, 10).map((u, i) => (
- <span className="form-hint wp-run-component" key={i}>{u.type} {u.slug}: {u.from} → {u.to}</span>
- ))}
- </div>
- );
- })}
- </div>
- </div>
- </div>
- </div>
- );
-};
-
-export default UpdatesTab;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/UptimeTab.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/UptimeTab.jsx
deleted file mode 100644
index a3f59202..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/UptimeTab.jsx
+++ /dev/null
@@ -1,139 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import { Activity } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { HealthDot } from '../HealthStatusPanel';
-import { MetricCard } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { OverviewGridSkeleton } from './wpDetailShared';
-
-// Uptime Tab — per-site health + uptime % via a bound status-page component (#26).
-// Health is polled server-side every 5 min; outages auto-open incidents and alert
-// the configured notification channels.
-const UptimeTab = ({ siteId }) => {
- const toast = useToast();
- const [data, setData] = useState(null);
- const [loading, setLoading] = useState(true);
- const [pageId, setPageId] = useState('');
- const [busy, setBusy] = useState(false);
-
- const load = React.useCallback(async () => {
- setLoading(true);
- try {
- const res = await wordpressApi.getSiteStatusPage(siteId);
- setData(res);
- } catch (err) {
- toast.error(err.message || 'Failed to load uptime info');
- } finally {
- setLoading(false);
- }
- }, [siteId, toast]);
-
- useEffect(() => { load(); }, [load]);
- useEffect(() => {
- if (data?.pages?.length) setPageId(prev => prev || String(data.pages[0].id));
- }, [data]);
-
- async function handleAttach() {
- if (!pageId) { toast.error('Choose a status page'); return; }
- setBusy(true);
- try {
- await wordpressApi.attachStatusPage(siteId, Number(pageId));
- toast.success('Added to status page');
- await load();
- } catch (err) {
- toast.error(err.message || 'Failed to add to status page');
- } finally { setBusy(false); }
- }
-
- async function handleDetach() {
- if (!window.confirm('Remove this site from its status page? Its uptime history and component will be deleted.')) return;
- setBusy(true);
- try {
- await wordpressApi.detachStatusPage(siteId);
- toast.success('Removed from status page');
- await load();
- } catch (err) {
- toast.error(err.message || 'Failed to remove from status page');
- } finally { setBusy(false); }
- }
-
- if (loading) return <SkeletonBoundary loading skeleton={<OverviewGridSkeleton panels={2} />} />;
-
- const comp = data?.component;
- const pages = data?.pages || [];
- const pct = (v) => (v != null ? `${v.toFixed(2)}%` : '—');
-
- return (
- <div className="app-overview-grid">
- <div className="app-overview-left">
- <div className="app-panel">
- <div className="app-panel-header">Health</div>
- <div className="app-panel-body">
- <div className="app-info-grid">
- <div className="app-info-item">
- <span className="app-info-label">Current Status</span>
- <span className="app-info-value">
- <HealthDot status={data?.health_status} /> {data?.health_status || 'unknown'}
- </span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Last Checked</span>
- <span className="app-info-value">{data?.last_health_check ? new Date(data.last_health_check).toLocaleString() : 'Never'}</span>
- </div>
- </div>
- <p className="hint">Health is polled automatically every 5 minutes. Outages and recoveries alert your configured notification channels.</p>
- </div>
- </div>
-
- {comp ? (
- <div className="app-panel">
- <div className="app-panel-header">Uptime</div>
- <div className="app-panel-body">
- {comp.last_check_at ? (
- <div className="wp-kpis">
- <MetricCard icon={<Activity size={16} />} tone="green" value={pct(comp.uptime_24h)} label="Uptime · 24 hours" />
- <MetricCard icon={<Activity size={16} />} tone="green" value={pct(comp.uptime_7d)} label="Uptime · 7 days" />
- <MetricCard icon={<Activity size={16} />} tone="cyan" value={pct(comp.uptime_30d)} label="Uptime · 30 days" />
- <MetricCard icon={<Activity size={16} />} tone="cyan" value={pct(comp.uptime_90d)} label="Uptime · 90 days" />
- </div>
- ) : (
- <p className="hint">Awaiting the first health check (runs within 5 minutes).</p>
- )}
- <p className="hint">Uptime accrues from the 5-minute health checks; only fully-healthy checks count, so degraded periods reduce it. This site appears on its status page and auto-opens an incident on an outage (auto-resolved on recovery).</p>
- <div className="app-detail-actions">
- <Button variant="outline" size="sm" disabled={busy} onClick={handleDetach}>Remove from status page</Button>
- </div>
- </div>
- </div>
- ) : (
- <div className="app-panel">
- <div className="app-panel-header">Add to status page</div>
- <div className="app-panel-body">
- {pages.length === 0 ? (
- <p className="hint">No status pages exist yet. Create one under Status Pages first, then add this site to track its uptime and auto-open incidents on outages.</p>
- ) : (
- <>
- <p className="hint">Track uptime for this site on a status page. It accrues a real uptime % and auto-opens/resolves incidents on outages.</p>
- <div className="form-group">
- <Label>Status Page</Label>
- <select value={pageId} onChange={e => setPageId(e.target.value)} disabled={busy}>
- {pages.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
- </select>
- </div>
- <div className="app-detail-actions">
- <Button size="sm" disabled={busy} onClick={handleAttach}>Add to status page</Button>
- </div>
- </>
- )}
- </div>
- </div>
- )}
- </div>
- </div>
- );
-};
-
-export default UptimeTab;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/VulnerabilitiesTab.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/VulnerabilitiesTab.jsx
deleted file mode 100644
index d4983ef2..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/VulnerabilitiesTab.jsx
+++ /dev/null
@@ -1,138 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import { AlertTriangle } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { KpiBand, MetricCard } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { OverviewGridSkeleton } from './wpDetailShared';
-
-// Vulnerabilities Tab — cross-references plugin/theme/core versions against the
-// keyless WPVulnerability community feed (#28). On-demand background scan + poll.
-const VulnerabilitiesTab = ({ siteId }) => {
- const toast = useToast();
- const [data, setData] = useState(null);
- const [loading, setLoading] = useState(true);
- const [scanning, setScanning] = useState(false);
-
- const load = React.useCallback(async () => {
- try {
- const res = await wordpressApi.getVulnerabilities(siteId);
- setData(res);
- } catch (err) {
- toast.error(err.message || 'Failed to load vulnerabilities');
- } finally {
- setLoading(false);
- }
- }, [siteId, toast]);
-
- useEffect(() => { load(); }, [load]);
- useEffect(() => {
- if (data?.scan_status !== 'running') return undefined;
- const t = setTimeout(() => { load(); }, 2500);
- return () => clearTimeout(t);
- }, [data, load]);
-
- async function handleScan() {
- setScanning(true);
- try {
- await wordpressApi.scanVulnerabilities(siteId);
- toast.info('Vulnerability scan started…');
- await load();
- } catch (err) {
- toast.error(err.message || 'Failed to start scan');
- } finally {
- setScanning(false);
- }
- }
-
- if (loading) return <SkeletonBoundary loading skeleton={<OverviewGridSkeleton panels={2} />} />;
-
- const running = data?.scan_status === 'running';
- const summary = data?.summary || {};
- const vulns = data?.vulnerabilities || [];
-
- return (
- <div className="app-overview-grid">
- <div className="app-overview-left">
- <div className="app-panel">
- <div className="app-panel-header">Vulnerability scan</div>
- <div className="app-panel-body">
- <div className="app-detail-actions">
- <Button size="sm" onClick={handleScan} disabled={scanning || running}>
- {running ? 'Scanning…' : 'Run scan'}
- </Button>
- </div>
- <div className="app-info-grid">
- <div className="app-info-item"><span className="app-info-label">Last scan</span><span className="app-info-value">{data?.scanned_at ? new Date(data.scanned_at).toLocaleString() : 'Never'}</span></div>
- <div className="app-info-item"><span className="app-info-label">Findings</span><span className="app-info-value">{summary.total ?? 0}</span></div>
- </div>
- {data?.scan_error && <p className="hint">Last scan error: {data.scan_error}</p>}
- <p className="hint">Cross-references installed plugin, theme, and core versions against the WPVulnerability community database. Re-run after updating.</p>
- </div>
- </div>
-
- {data?.scanned_at && (
- <KpiBand>
- <MetricCard icon={<AlertTriangle size={16} />} tone="red" value={summary.critical ?? 0} label="Critical" />
- <MetricCard icon={<AlertTriangle size={16} />} tone="red" value={summary.high ?? 0} label="High" />
- <MetricCard icon={<AlertTriangle size={16} />} tone="amber" value={summary.medium ?? 0} label="Medium" />
- <MetricCard icon={<AlertTriangle size={16} />} tone="cyan" value={summary.low ?? 0} label="Low" />
- {summary.unknown > 0 && (
- <MetricCard icon={<AlertTriangle size={16} />} tone="violet" value={summary.unknown} label="Unrated" />
- )}
- </KpiBand>
- )}
-
- {vulns.length === 0 ? (
- <div className="app-panel">
- <div className="app-panel-body">
- <p className="hint">{data?.scanned_at ? 'No known vulnerabilities found.' : 'No scan has run yet — click Run scan to check this site.'}</p>
- </div>
- </div>
- ) : (
- <div className="app-panel">
- <div className="app-panel-header">Findings</div>
- <table className="sk-dtable wp-vuln-table">
- <thead>
- <tr>
- <th>Severity</th>
- <th>Component</th>
- <th>Issue</th>
- <th>Installed</th>
- <th>Fixed in</th>
- <th>Advisory</th>
- </tr>
- </thead>
- <tbody>
- {vulns.map(v => (
- <tr key={v.id}>
- <td><span className={`wp-sev wp-sev--${v.severity || 'unknown'}`}><span className="d" />{v.severity || 'unrated'}</span></td>
- <td>
- <div className="sk-cell-name">{v.name}</div>
- <div className="sk-cell-sub">{v.source}{v.slug ? ` · ${v.slug}` : ''}</div>
- </td>
- <td className="wp-vuln-title">{v.title || '—'}</td>
- <td><span className="sk-cell-mono">{v.installed_version}</span></td>
- <td>
- {v.fixed_in
- ? <span className="wp-fix-chip">{v.fixed_in}</span>
- : <span className="wp-no-fix">no fix yet</span>}
- </td>
- <td>
- {v.reference_url
- ? <a className="wp-advisory-link" href={v.reference_url} target="_blank" rel="noopener noreferrer">{v.advisory_id || 'advisory'} ↗</a>
- : <span className="sk-cell-mono">{v.advisory_id || '—'}</span>}
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- )}
- </div>
- </div>
- );
-};
-
-export default VulnerabilitiesTab;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/wpDetailShared.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/wpDetailShared.jsx
deleted file mode 100644
index c7c6ef5f..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/detail/wpDetailShared.jsx
+++ /dev/null
@@ -1,553 +0,0 @@
-import { useState, useEffect } from 'react';
-import { Link } from 'react-router-dom';
-import { ChevronDown, Check, Lock, Globe, Shield, CircleCheck, CircleX } from 'lucide-react';
-import { api } from 'serverkit-sdk';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { Pill } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-
-// Detail Page Skeleton for initial loading
-// Mirrors the real page chrome (top bar, identity, repo pill, tabs) and the
-// Overview tab layout (KPIs, quick-actions + traffic grid, activity feed).
-export const DetailPageSkeleton = () => (
- <div className="wp-detail-page wp-detail-page--skeleton">
- {/* Top bar chrome */}
- <div className="sk-topbar-skeleton">
- <div className="sk-topbar-skeleton__icon" />
- <div className="sk-topbar-skeleton__title" />
- <div className="sk-topbar-skeleton__spacer" />
- <div className="sk-topbar-skeleton__actions">
- <div className="sk-topbar-skeleton__btn" />
- <div className="sk-topbar-skeleton__btn" />
- <div className="sk-topbar-skeleton__btn sk-topbar-skeleton__btn--primary" />
- </div>
- </div>
-
- <div className="app-detail-body">
- {/* Identity header */}
- <div className="app-detail-header">
- <div className="app-detail-icon wp-icon skeleton" style={{ width: 52, height: 52, borderRadius: 13 }} />
- <div className="app-detail-title-block">
- <div className="skeleton" style={{ width: 260, height: 24, marginBottom: 10 }} />
- <div className="skeleton" style={{ width: 340, height: 14 }} />
- </div>
- </div>
-
- {/* Repo pill placeholder */}
- <div className="wp-detail__repo-bar">
- <div className="wp-detail-skeleton-repo" />
- </div>
-
- {/* Tab strip */}
- <div className="app-detail-tabs">
- {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14].map(i => (
- <div key={i} className="skeleton app-detail-tab-skeleton" />
- ))}
- </div>
-
- {/* Overview tab content placeholder */}
- <div className="app-detail-content">
- <div className="wp-overview wp-overview--skeleton">
- {/* KPI row */}
- <div className="wp-kpis wp-kpis--skeleton">
- {[1, 2, 3, 4].map(i => (
- <div key={i} className="wp-detail-skeleton-kpi">
- <div className="wp-detail-skeleton-kpi__label" />
- <div className="wp-detail-skeleton-kpi__value" />
- </div>
- ))}
- </div>
-
- {/* Quick actions + traffic grid */}
- <div className="wp-overview-main">
- <div className="app-panel wp-detail-skeleton-panel">
- <div className="app-panel-header">
- <div className="skeleton" style={{ width: 100, height: 12 }} />
- </div>
- <div className="app-panel-body">
- <div className="quick-actions-grid">
- {[1, 2, 3, 4, 5, 6, 7, 8].map(i => (
- <div key={i} className="skeleton" style={{ height: 38, borderRadius: 8 }} />
- ))}
- </div>
- </div>
- </div>
-
- <div className="app-panel wp-detail-skeleton-panel wp-traffic-panel">
- <div className="app-panel-header">
- <div className="skeleton" style={{ width: 80, height: 12, marginBottom: 4 }} />
- <div className="skeleton" style={{ width: 140, height: 10 }} />
- </div>
- <div className="app-panel-body">
- <div className="wp-detail-skeleton-chart" />
- </div>
- </div>
- </div>
-
- {/* Recent activity panel */}
- <div className="app-panel wp-detail-skeleton-panel wp-activity-panel">
- <div className="app-panel-header">
- <div className="skeleton" style={{ width: 110, height: 12 }} />
- </div>
- <div className="app-panel-body">
- <div className="wp-detail-skeleton-activity">
- {[1, 2, 3, 4].map(i => (
- <div key={i} className="wp-detail-skeleton-activity__row">
- <div className="skeleton" style={{ width: 32, height: 32, borderRadius: '50%' }} />
- <div className="wp-detail-skeleton-activity__lines">
- <div className="skeleton" style={{ width: '40%', height: 12, marginBottom: 6 }} />
- <div className="skeleton" style={{ width: '65%', height: 10 }} />
- </div>
- </div>
- ))}
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
-);
-
-// Environment-type → dot tint for the header environment switcher.
-export const ENV_DOT_COLORS = {
- production: 'var(--green)',
- staging: 'var(--amber)',
- development: 'var(--cyan)',
- multidev: 'var(--violet)',
-};
-
-// Short label for an environment type tag (PROD / STAGING / DEV).
-export const envTagLabel = (type) => (
- type === 'production' ? 'PROD' : type === 'staging' ? 'STAGING' : 'DEV'
-);
-
-export const ENV_TYPE_LABELS = { production: 'Production', staging: 'Staging', development: 'Development', multidev: 'Multidev' };
-
-// Compact header environment switcher — navigates between the environment
-// site ids already present in the loaded payload (no extra fetches).
-export const EnvSwitcher = ({ options, onSelect }) => {
- const [open, setOpen] = useState(false);
-
- useEffect(() => {
- if (!open) return undefined;
- const close = () => setOpen(false);
- window.addEventListener('click', close);
- return () => window.removeEventListener('click', close);
- }, [open]);
-
- const current = options.find(o => o.current) || options[0];
-
- return (
- <div className="wp-envswitch-wrap">
- <button
- type="button"
- className={`wp-envswitch ${open ? 'open' : ''}`}
- onClick={(e) => { e.stopPropagation(); setOpen(o => !o); }}
- title="Switch environment"
- >
- <span className="ed" style={{ background: ENV_DOT_COLORS[current.type] || 'var(--text-faint)' }} />
- {ENV_TYPE_LABELS[current.type] || current.name}
- <ChevronDown size={13} className="chev" />
- </button>
- {open && (
- <div className="wp-envswitch-menu" onClick={e => e.stopPropagation()}>
- <div className="wp-envswitch-head">Switch environment</div>
- {options.map(o => (
- <button
- type="button"
- className="wp-envswitch-opt"
- key={o.id}
- onClick={() => { setOpen(false); if (!o.current) onSelect(o.id); }}
- >
- <span className="ed" style={{ background: ENV_DOT_COLORS[o.type] || 'var(--text-faint)' }} />
- <span className="wp-envswitch-opt-body">
- <span className="nm">{o.name}</span>
- <span className="meta">
- {envTagLabel(o.type)}
- {o.url ? ` · ${o.url.replace(/^https?:\/\//, '')}` : ''}
- </span>
- </span>
- {o.current && <Check size={14} className="check" />}
- </button>
- ))}
- </div>
- )}
- </div>
- );
-};
-
-// Header alert that nags the operator to secure the site when the primary
-// URL is not HTTPS. Clicking it jumps to SSL settings so the user can enable
-// HTTPS in one click (or see why it can't be issued yet, e.g. localhost).
-export const SSLAlert = ({ site }) => {
- const isHttps = (site.url || '').startsWith('https://');
-
- if (!site.url || isHttps) return null;
-
- return (
- <Link
- to={`/wordpress/${site.id}/settings/ssl`}
- className="sk-pill sk-pill--amber"
- >
- <span className="sk-pill__dot" />
- Not Secured
- </Link>
- );
-};
-
-// Friendly labels for the editable php.ini directives (#24 limits panel).
-export const PHP_LIMIT_LABELS = {
- memory_limit: 'Memory Limit',
- upload_max_filesize: 'Upload Max Filesize',
- post_max_size: 'Post Max Size',
- max_execution_time: 'Max Execution Time',
- max_input_time: 'Max Input Time',
- max_input_vars: 'Max Input Vars',
-};
-
-// Updates Tab — safe update schedule options (#29).
-export const UPDATE_SCHEDULES = [
- { label: 'Off', value: '' },
- { label: 'Weekly (Sun 3am)', value: '0 3 * * 0' },
- { label: 'Daily (3am)', value: '0 3 * * *' },
-];
-
-// Analytics Tab — period options (#25).
-export const ANALYTICS_PERIODS = [{ label: '24h', hours: 24 }, { label: '7d', hours: 168 }];
-
-// SSL Certificate panel — guided one-click SSL that walks the user through the
-// prerequisites (public domain, DNS, admin email) and then issues the cert.
-export const SiteSSLPanel = ({ site, onUpdate }) => {
- const toast = useToast();
- const domains = site.application?.domains || [];
- const primaryDomain = (domains.find(d => d.is_primary) || domains[0])?.name || null;
- // localhost / private-IP / no-domain sites cannot get a public certificate.
- const isPublicDomain = !!primaryDomain
- && !/^(localhost|127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(primaryDomain)
- && primaryDomain.includes('.');
- const hasAdminEmail = !!site.admin_email;
- const [health, setHealth] = useState(null);
- const [checking, setChecking] = useState(true);
- const [issuing, setIssuing] = useState(false);
-
- // Inline domain attach state (replaces the modal for the SSL flow).
- const [attachDomain, setAttachDomain] = useState('');
- const [attaching, setAttaching] = useState(false);
- const [attachResult, setAttachResult] = useState(null);
-
- // Connected DNS providers + ServerKit domains so the SSL panel feels linked
- // to the rest of the app.
- const [dnsProviders, setDnsProviders] = useState([]);
- const [serverkitDomains, setServerkitDomains] = useState([]);
- const [contextLoading, setContextLoading] = useState(true);
-
- useEffect(() => {
- if (!primaryDomain) { setChecking(false); return; }
- let cancelled = false;
- (async () => {
- setChecking(true);
- try {
- const res = await api.getSSLHealth(primaryDomain);
- if (!cancelled) setHealth(res);
- } catch (err) {
- if (!cancelled) setHealth({ valid: false, error: err.message });
- } finally {
- if (!cancelled) setChecking(false);
- }
- })();
- return () => { cancelled = true; };
- }, [primaryDomain]);
-
- useEffect(() => {
- let cancelled = false;
- (async () => {
- setContextLoading(true);
- try {
- const [providersRes, domainsRes] = await Promise.all([
- api.getEmailDNSProviders().then(d => d.providers || []).catch(() => []),
- api.getDomains().then(d => d.domains || []).catch(() => []),
- ]);
- if (!cancelled) {
- setDnsProviders(providersRes);
- setServerkitDomains(domainsRes);
- }
- } finally {
- if (!cancelled) setContextLoading(false);
- }
- })();
- return () => { cancelled = true; };
- }, [site.id]);
-
- async function handleEnableSSL() {
- if (!primaryDomain || !site.admin_email) return;
- setIssuing(true);
- toast.info(`Requesting certificate for ${primaryDomain}...`, { duration: 4000 });
- try {
- const res = await api.obtainCertificate({ domains: [primaryDomain], email: site.admin_email, use_nginx: true });
- if (res.success) {
- toast.success(res.message || 'Certificate issued');
- const updated = await api.getSSLHealth(primaryDomain);
- setHealth(updated);
- } else {
- toast.error(res.error || 'Certificate request failed');
- }
- } catch (err) {
- toast.error(err.message || 'Certificate request failed');
- } finally {
- setIssuing(false);
- }
- }
-
- async function handleAttachDomain(e) {
- e?.preventDefault();
- const domain = attachDomain.trim();
- if (!domain || attaching) return;
- setAttaching(true);
- toast.info('Attaching domain — creating DNS and moving the site…', { duration: 5000 });
- try {
- const res = await wordpressApi.attachDomain(site.id, { domain, issueSsl: true });
- if (res.success) {
- setAttachResult(res);
- if (res.dns?.created) toast.success(`DNS A record created via ${res.dns.provider}`);
- else toast.warning('Domain attached — add the DNS record shown to finish.', { duration: 7000 });
- onUpdate?.();
- } else {
- toast.error(res.error || 'Failed to attach domain');
- }
- } catch (err) {
- toast.error(err.message || 'Failed to attach domain');
- } finally {
- setAttaching(false);
- }
- }
-
- const issued = health?.valid;
- const attachValid = /^[a-z0-9.-]+\.[a-z]{2,}$/i.test(attachDomain.trim());
-
- const CheckItem = ({ ok, label }) => (
- <div className="ssl-check-item">
- {ok ? <CircleCheck size={14} className="ssl-check-icon ssl-check-icon--ok" /> : <CircleX size={14} className="ssl-check-icon ssl-check-icon--missing" />}
- <span className={ok ? 'ssl-check-label ssl-check-label--ok' : 'ssl-check-label'}>{label}</span>
- </div>
- );
-
- const rec = attachResult?.dns?.record;
-
- return (
- <div className="app-panel">
- <div className="app-panel-header"><Lock size={16} /> SSL Certificate</div>
- <div className="app-panel-body">
- <div className="app-info-grid">
- <div className="app-info-item">
- <span className="app-info-label">Primary Domain</span>
- <span className="app-info-value mono">{primaryDomain || 'None configured'}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Status</span>
- <span className="app-info-value">
- <Pill kind={checking ? 'gray' : issued ? 'green' : 'amber'}>
- {checking ? 'Checking...' : issued ? `Active (${health.grade})` : 'Not Secured'}
- </Pill>
- </span>
- </div>
- {issued && health.expires_at && (
- <div className="app-info-item">
- <span className="app-info-label">Expires</span>
- <span className="app-info-value">
- {new Date(health.expires_at).toLocaleDateString()}
- {typeof health.days_remaining === 'number' ? ` (${health.days_remaining}d)` : ''}
- </span>
- </div>
- )}
- {issued && health.issuer && (
- <div className="app-info-item">
- <span className="app-info-label">Issuer</span>
- <span className="app-info-value">{health.issuer}</span>
- </div>
- )}
- </div>
-
- {!isPublicDomain ? (
- <div className="ssl-guide">
- <p className="hint">SSL requires a public domain pointed at this server. This site is on <code>{primaryDomain || 'localhost'}</code>, so a certificate cannot be issued here.</p>
- <div className="ssl-checklist">
- <CheckItem ok={false} label="Public domain mapped to this site" />
- <CheckItem ok={hasAdminEmail} label="Admin email set for certificate expiry notices" />
- </div>
-
- {!attachResult ? (
- <form className="ssl-inline-attach" onSubmit={handleAttachDomain}>
- {contextLoading ? (
- <p className="hint">Loading domain connections…</p>
- ) : (
- <div className="ssl-context">
- {dnsProviders.length > 0 ? (
- <div className="ssl-provider-status ssl-provider-status--ok">
- <CircleCheck size={14} />
- DNS auto-managed via {dnsProviders.map(p => p.name || p.provider).join(', ')}
- </div>
- ) : (
- <div className="ssl-provider-status ssl-provider-status--missing">
- <CircleX size={14} />
- No DNS provider connected — add Cloudflare/Route53/etc. for automatic records, or add the DNS record manually after attaching.
- </div>
- )}
- <div className="ssl-context-links">
- <Link to="/settings/connections">DNS connections</Link>
- <span>·</span>
- <Link to="/domains">Manage domains</Link>
- </div>
- </div>
- )}
-
- <div className="form-group">
- <Label>Domain</Label>
- <Input
- type="text"
- value={attachDomain}
- onChange={(e) => setAttachDomain(e.target.value)}
- placeholder="example.com"
- disabled={attaching}
- list="ssl-existing-domains"
- />
- <datalist id="ssl-existing-domains">
- {serverkitDomains
- .filter(d => !domains.some(ad => ad.name === d.name))
- .map(d => (
- <option key={d.id} value={d.name}>
- {d.ssl_enabled ? 'SSL enabled' : 'No SSL'}
- </option>
- ))}
- </datalist>
- <span className="form-hint">Pick an existing ServerKit domain or type one you control, without http://</span>
- </div>
- <div className="app-detail-actions">
- <Button type="submit" disabled={!attachValid || attaching}>
- <Globe size={14} />
- {attaching ? 'Attaching…' : 'Attach Domain & Enable SSL'}
- </Button>
- </div>
- </form>
- ) : (
- <div className="ssl-attach-result">
- <div className="ssl-attach-result__success">
- <CircleCheck size={16} />
- Site is now at <code>{attachResult.url}</code>
- </div>
- {attachResult.dns?.created ? (
- <p className="hint">DNS A record created automatically via {attachResult.dns.provider}{attachResult.dns.zone ? ` (zone ${attachResult.dns.zone})` : ''}.</p>
- ) : (
- <div className="ssl-attach-result__manual">
- <strong>Add this DNS record to finish:</strong>
- {rec?.value ? (
- <code className="ssl-attach-result__record">{rec.type}&nbsp;&nbsp;{rec.name}&nbsp;→&nbsp;{rec.value}</code>
- ) : (
- <p className="hint">{attachResult.dns?.message}</p>
- )}
- </div>
- )}
- {attachResult.warning && <p className="hint">{attachResult.warning}</p>}
- </div>
- )}
- </div>
- ) : !hasAdminEmail ? (
- <div className="ssl-guide">
- <p className="hint">A public domain is configured, but an admin email is required before requesting a certificate.</p>
- <div className="ssl-checklist">
- <CheckItem ok label={`Domain ${primaryDomain} configured`} />
- <CheckItem ok={false} label="Admin email set" />
- </div>
- <p className="hint">Update the site&apos;s admin email in Settings → General, then return here to enable SSL.</p>
- </div>
- ) : (
- <div className="ssl-guide">
- {issued ? (
- <p className="hint">This site is secured with a valid SSL certificate. You can re-issue it if needed.</p>
- ) : (
- <>
- <p className="hint">Everything is ready. One click will request a free certificate from Let&apos;s Encrypt and configure the server.</p>
- <div className="ssl-checklist">
- <CheckItem ok label={`Domain ${primaryDomain} configured`} />
- <CheckItem ok label="Admin email set" />
- </div>
- </>
- )}
- <div className="app-detail-actions">
- <Button onClick={handleEnableSSL} disabled={issuing}>
- {issued ? <Shield size={14} /> : <Lock size={14} />}
- {issuing ? 'Requesting...' : issued ? 'Re-issue Certificate' : 'Enable SSL'}
- </Button>
- </div>
- </div>
- )}
- </div>
- </div>
- );
-};
-
-// Reusable Skeleton Components for Tabs
-export const EnvironmentCardSkeleton = () => (
- <div className="wp-env-card-skeleton">
- <div className="wp-env-card-skeleton-header">
- <div className="wp-env-card-skeleton-badge" />
- <div className="wp-env-card-skeleton-status" />
- </div>
- <div className="wp-env-card-skeleton-body">
- <div className="wp-env-card-skeleton-url" />
- <div className="wp-env-card-skeleton-meta">
- <div className="wp-env-card-skeleton-meta-item">
- <div className="skeleton-label" />
- <div className="skeleton-value" />
- </div>
- <div className="wp-env-card-skeleton-meta-item">
- <div className="skeleton-label" />
- <div className="skeleton-value" />
- </div>
- </div>
- </div>
- <div className="wp-env-card-skeleton-footer">
- <div className="skeleton" style={{ flex: 1, height: 28, borderRadius: 4 }} />
- <div className="skeleton" style={{ flex: 1, height: 28, borderRadius: 4 }} />
- </div>
- </div>
-);
-
-export const ListItemSkeleton = () => (
- <div className="skeleton" style={{ height: 48, borderRadius: 6, marginBottom: 8 }} />
-);
-
-// Generic panel skeleton — matches .app-panel + .app-panel-header + .app-panel-body
-export const PanelSkeleton = ({ headerWidth = 100, rows = 3, children }) => (
- <div className="app-panel wp-detail-skeleton-panel">
- <div className="app-panel-header">
- <div className="skeleton" style={{ width: headerWidth, height: 12 }} />
- </div>
- <div className="app-panel-body">
- {children || (
- <div className="wp-detail-skeleton-rows">
- {Array.from({ length: rows }).map((_, i) => (
- <div key={i} className="wp-detail-skeleton-row">
- <div className="skeleton" style={{ width: '35%', height: 10 }} />
- <div className="skeleton" style={{ width: '55%', height: 14 }} />
- </div>
- ))}
- </div>
- )}
- </div>
- </div>
-);
-
-// Skeleton used by tabs that render inside .app-overview-grid > .app-overview-left
-export const OverviewGridSkeleton = ({ panels = 2 }) => (
- <div className="app-overview-grid">
- <div className="app-overview-left">
- {Array.from({ length: panels }).map((_, i) => (
- <PanelSkeleton key={i} headerWidth={i === 0 ? 120 : 160} />
- ))}
- </div>
- </div>
-);
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/index.js b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/index.js
deleted file mode 100644
index 965680fc..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/index.js
+++ /dev/null
@@ -1,21 +0,0 @@
-export { default as WordPressSiteCard } from './WordPressSiteCard';
-export { default as EnvironmentCard } from './EnvironmentCard';
-export { default as SnapshotTable } from './SnapshotTable';
-export { default as GitConnectForm } from './GitConnectForm';
-export { default as CommitList } from './CommitList';
-export { default as PipelineView } from './PipelineView';
-export { default as PromoteModal } from './PromoteModal';
-export { default as SyncModal } from './SyncModal';
-export { default as ActivityFeed } from './ActivityFeed';
-export { default as ContainerLogs } from './ContainerLogs';
-export { default as EnvironmentStatusBadge } from './EnvironmentStatusBadge';
-export { default as CompareView } from './CompareView';
-export { default as SanitizationProfileForm } from './SanitizationProfileForm';
-export { default as ResourceLimitsModal } from './ResourceLimitsModal';
-export { default as BasicAuthModal } from './BasicAuthModal';
-export { default as WpCliTerminal } from './WpCliTerminal';
-export { default as HealthStatusPanel } from './HealthStatusPanel';
-export { HealthDot } from './HealthStatusPanel';
-export { default as DiskUsageBar } from './DiskUsageBar';
-export { default as AutoSyncScheduleModal } from './AutoSyncScheduleModal';
-export { default as BulkActionsBar } from './BulkActionsBar';
diff --git a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/wordpressTabs.jsx b/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/wordpressTabs.jsx
deleted file mode 100644
index 05e9f5a1..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/components/wordpress/wordpressTabs.jsx
+++ /dev/null
@@ -1,12 +0,0 @@
-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
-// top-bar layout replaces the old sidebar sub-menu (REDESIGN_MAP §6 dec. 3).
-// (The Pipeline tab was wpInstalled-gated in the sidebar; kept always-visible
-// 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/builtin-extensions/serverkit-wordpress/frontend/index.jsx b/builtin-extensions/serverkit-wordpress/frontend/index.jsx
deleted file mode 100644
index 6d7b0486..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/index.jsx
+++ /dev/null
@@ -1,75 +0,0 @@
-// WordPress UI, contributed through the extension system. Both halves now
-// live in this extension: the backend (the /api/v1/wordpress* blueprints +
-// services) under backend/, and the full frontend (5 pages + the
-// components/wordpress tree + styles/) here — moved out of the host's pages/
-// and styles/ in plan 52 Phase 4. After `sync-builtin-frontends.mjs` this
-// tree is baked at frontend/src/plugins/serverkit-wordpress/, where the host
-// build compiles it (the @/ alias imports that remain resolve there; the
-// runtime-ESM conversion that drops them is Phase 5).
-//
-// Styles ship with the extension: the three SCSS entries below are compiled
-// by the host build through this module graph (they import the host's
-// variables partial via a sync-safe relative path), replacing the former
-// main.scss partials.
-import './styles/wordpress.scss';
-import './styles/wordpress-pipeline.scss';
-import './styles/wordpress-plugin-library.scss';
-
-// The WordPress surface is a tab group + full-bleed detail pages. Contributed
-// routes are flat (there's no way to contribute a shared TabGroupLayout parent
-// inside the dashboard), so we contribute ONE splat route (`wordpress/*`) and
-// this component self-renders the whole WordPress sub-router — reproducing the
-// exact structure the core App.jsx used to own (TabGroupLayout + WORDPRESS_TABS
-// over the three list pages; full-bleed detail/pipeline routes as siblings;
-// the legacy /wordpress/projects → /wordpress/pipelines deprecation redirects).
-import { Routes, Route, Navigate, useParams } from 'react-router-dom';
-import { TabGroupLayout } from 'serverkit-sdk';
-
-import { WORDPRESS_TABS } from './components/wordpress/wordpressTabs';
-import WordPress from './pages/WordPress';
-import WordPressPluginLibrary from './pages/WordPressPluginLibrary';
-import WordPressProjects from './pages/WordPressProjects';
-import WordPressProject from './pages/WordPressProject';
-import WordPressDetail from './pages/WordPressDetail';
-import WordPressSshImport from './WordPressSshImport';
-
-// "WordPress Projects" was renamed to "Pipelines" (§2 unification). Forward old
-// deep links to the new space.
-function LegacyWpPipelineRedirect() {
- const { id, tab } = useParams();
- const suffix = [id, tab].filter(Boolean).join('/');
- return <Navigate to={`/wordpress/pipelines/${suffix}`} replace />;
-}
-
-export function WordPressExtension() {
- return (
- <Routes>
- {/* Tab group — list surfaces share one PageTopbar + WORDPRESS_TABS. */}
- <Route element={<TabGroupLayout tabs={WORDPRESS_TABS} />}>
- <Route index element={<WordPress />} />
- <Route path="plugins/library" element={<WordPressPluginLibrary />} />
- <Route path="pipelines" element={<WordPressProjects />} />
- {/* SSH pull-import (Panel Improvements #3) — shares the group
- chrome; reached via the command palette / direct link. */}
- <Route path="ssh-import" element={<WordPressSshImport />} />
- </Route>
- {/* Full-bleed pipeline detail (own chrome, outside the tab group). */}
- <Route path="pipelines/:id" element={<WordPressProject />} />
- <Route path="pipelines/:id/:tab" element={<WordPressProject />} />
- {/* Legacy "WordPress Projects" URLs → Pipelines (§2). */}
- <Route path="projects" element={<Navigate to="/wordpress/pipelines" replace />} />
- <Route path="projects/:id" element={<LegacyWpPipelineRedirect />} />
- <Route path="projects/:id/:tab" element={<LegacyWpPipelineRedirect />} />
- {/* Full-bleed site detail (own chrome, outside the tab group). The
- :tab/:section depth keeps the Settings sub-nav shareable. */}
- <Route path=":id" element={<WordPressDetail />} />
- <Route path=":id/:tab" element={<WordPressDetail />} />
- <Route path=":id/:tab/:section" element={<WordPressDetail />} />
- </Routes>
- );
-}
-
-// No default export on purpose: PluginLoader legacy-auto-renders any plugin
-// default export globally — this sub-router mounted that way runs outside its
-// route and swallows the current location ("/domains" → :id "domains").
-// The route contribution resolves the NAMED export via resolveComponent.
diff --git a/builtin-extensions/serverkit-wordpress/frontend/pages/WordPress.jsx b/builtin-extensions/serverkit-wordpress/frontend/pages/WordPress.jsx
deleted file mode 100644
index e47fffb5..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/pages/WordPress.jsx
+++ /dev/null
@@ -1,677 +0,0 @@
-import { useState, useEffect } from 'react';
-import { useNavigate } from 'react-router-dom';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import ResourceAdvisory from '@/components/ResourceAdvisory';
-import { Spinner } from 'serverkit-sdk';
-import ResourceListPage from '@/components/layouts/ResourceListPage';
-import { Globe, ChevronRight } from 'lucide-react';
-import { Pill, ServiceTile, Drawer } from 'serverkit-sdk';
-import { useTopbarActions } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { Checkbox } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-
-// Mirror the backend slug rule (a-z, 0-9, single dashes) so the create modal can
-// preview the exact <slug>.<base> host the site will be published at.
-function slugifyPreview(name) {
- return (name || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'site';
-}
-
-function WordPress() {
- const [sites, setSites] = useState([]);
- const [loading, setLoading] = useState(true);
- const [activeTag, setActiveTag] = useState(null); // null = show all
- const [statusFilter, setStatusFilter] = useState('all'); // all | running | stopped
- const [siteSearch, setSiteSearch] = useState(''); // client-side name/title/domain filter
- const [showCreateModal, setShowCreateModal] = useState(false);
- const [createLoading, setCreateLoading] = useState(false);
- const [createForm, setCreateForm] = useState({
- name: '', domain: '', adminEmail: '', phpVersion: '', enablePageCache: false, enableObjectCache: false,
- baseDomain: '',
- });
- // Base domains a new site can be published under (<slug>.<base>), loaded when
- // the create modal opens. Empty when site routing isn't configured.
- const [baseDomains, setBaseDomains] = useState([]);
- const [createdCreds, setCreatedCreds] = useState(null);
- // Where a freshly-created site is reachable, so we can tell the user it is
- // already live (at <slug>.<base>, HTTPS when the wildcard cert is set up)
- // rather than leaving them to wonder — or nudge them to set a base domain
- // when the site only came up on localhost.
- const [createdSite, setCreatedSite] = useState(null);
- const [showImportModal, setShowImportModal] = useState(false);
- const [importLoading, setImportLoading] = useState(false);
- const [importForm, setImportForm] = useState({ name: '', adminEmail: '', oldUrl: '' });
- const [importFile, setImportFile] = useState(null);
- const [wpContentFile, setWpContentFile] = useState(null);
- const [selectedIds, setSelectedIds] = useState(new Set());
- const [bulkLoading, setBulkLoading] = useState(false);
-
- const navigate = useNavigate();
- const toast = useToast();
-
- useEffect(() => {
- loadSites();
- }, []);
-
- // Load the available base domains when the create modal opens, and preselect
- // the default so the site publishes under it unless the user picks another.
- useEffect(() => {
- if (!showCreateModal) return;
- let cancelled = false;
- (async () => {
- try {
- const data = await wordpressApi.listBaseDomains();
- if (cancelled) return;
- const bases = data.base_domains || [];
- setBaseDomains(bases);
- setCreateForm(f => ({ ...f, baseDomain: f.baseDomain || data.default || '' }));
- } catch {
- if (!cancelled) setBaseDomains([]);
- }
- })();
- return () => { cancelled = true; };
- }, [showCreateModal]);
-
- const loadSites = async () => {
- setLoading(true);
- try {
- const data = await wordpressApi.getSites();
- setSites(data.sites || []);
- } catch (error) {
- console.error('Failed to load WordPress sites:', error);
- setSites([]);
- } finally {
- setLoading(false);
- }
- };
-
- const handleCreate = async () => {
- if (!createForm.name) {
- toast.error('Site name is required');
- return;
- }
-
- setCreateLoading(true);
- try {
- const result = await wordpressApi.createSite(createForm);
- if (result.success) {
- if (result.admin_password) {
- // The generated admin password is returned once — surface it.
- setCreatedCreds({ user: result.admin_user || 'admin', password: result.admin_password });
- }
- if (result.url) {
- setCreatedSite({ url: result.url, domain: result.domain || null });
- }
- if (result.warning) {
- toast.info(result.warning, { duration: 8000 });
- }
- toast.success('WordPress site created successfully');
- setShowCreateModal(false);
- setCreateForm({ name: '', domain: '', adminEmail: '', phpVersion: '', enablePageCache: false, enableObjectCache: false, baseDomain: '' });
- await loadSites();
- } else {
- toast.error(result.error || 'Failed to create site');
- }
- } catch (error) {
- toast.error(`Failed to create site: ${error.message}`);
- } finally {
- setCreateLoading(false);
- }
- };
-
- // Bulk ops fan out per-site (no bulk route yet — §5); `applies` filters the
- // selection to sites the action makes sense for.
- const bulkRun = async (label, fn, applies = () => true) => {
- const targets = sites.filter(s => selectedIds.has(s.id) && applies(s));
- if (targets.length === 0) {
- toast.info(`No selected sites need "${label}"`);
- return;
- }
- setBulkLoading(true);
- try {
- const results = await Promise.allSettled(targets.map(s => fn(s)));
- const failed = results.filter(r => r.status === 'rejected').length;
- if (failed) toast.error(`${label}: ${failed} of ${targets.length} failed`);
- else toast.success(`${label} sent to ${targets.length} site${targets.length === 1 ? '' : 's'}`);
- setSelectedIds(new Set());
- await loadSites();
- } finally {
- setBulkLoading(false);
- }
- };
-
- const handleImport = async () => {
- if (!importForm.name) { toast.error('Site name is required'); return; }
- if (!importForm.oldUrl) { toast.error('Original site URL is required'); return; }
- if (!importFile) { toast.error('A .sql or .sql.gz dump is required'); return; }
- setImportLoading(true);
- try {
- const result = await wordpressApi.importSite({
- name: importForm.name,
- adminEmail: importForm.adminEmail,
- oldUrl: importForm.oldUrl,
- sqlFile: importFile,
- wpContentFile: wpContentFile,
- });
- if (result.success) {
- toast.success('WordPress site imported successfully');
- if (result.wp_content_imported) toast.success('wp-content (plugins/themes/uploads) imported');
- if (result.warning) toast.info(result.warning, { duration: 8000 });
- setShowImportModal(false);
- setImportForm({ name: '', adminEmail: '', oldUrl: '' });
- setImportFile(null);
- setWpContentFile(null);
- await loadSites();
- } else {
- toast.error(result.error || 'Failed to import site');
- }
- } catch (error) {
- toast.error(`Failed to import site: ${error.message}`);
- } finally {
- setImportLoading(false);
- }
- };
-
- useTopbarActions(() =>
- <>
- <Button variant="outline" size="sm" onClick={() => navigate('/imports')}>
- Import a site
- </Button>
- <Button variant="outline" size="sm" onClick={() => setShowImportModal(true)}>
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
- Import Site
- </Button>
- <Button size="sm" onClick={() => setShowCreateModal(true)}>
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
- Create Site
- </Button>
- </>,
- []
- );
-
- const wpListSkeleton = (
- <div className="wp-sites-grid">
- {[1, 2, 3].map(i => (
- <div key={i} className="wp-site-card-skeleton">
- <div className="wp-site-card-skeleton-header">
- <div className="wp-site-card-skeleton-icon" />
- <div className="wp-site-card-skeleton-info">
- <div className="wp-site-card-skeleton-name" />
- <div className="wp-site-card-skeleton-url" />
- </div>
- <div className="wp-site-card-skeleton-status" />
- </div>
- <div className="wp-site-card-skeleton-body">
- <div className="wp-site-card-skeleton-meta">
- <div className="wp-site-card-skeleton-label" />
- <div className="wp-site-card-skeleton-value" />
- </div>
- <div className="wp-site-card-skeleton-meta">
- <div className="wp-site-card-skeleton-label" />
- <div className="wp-site-card-skeleton-value" />
- </div>
- </div>
- </div>
- ))}
- </div>
- );
-
- if (loading) {
- return (
- <SkeletonBoundary
- className="sk-tabgroup__inner wordpress-page"
- loading
- skeleton={wpListSkeleton}
- />
- );
- }
-
- const allTags = Array.from(new Set(sites.flatMap(s => s.tags || []))).sort();
- const runningCount = sites.filter(s => s.status === 'running').length;
- const q = siteSearch.trim().toLowerCase();
- const siteLabel = site => site.name || site.application?.name || `Site ${site.id}`;
- const shownSites = sites.filter(site => (
- (statusFilter === 'all'
- || (statusFilter === 'running' ? site.status === 'running' : site.status !== 'running'))
- && (activeTag === null || (site.tags || []).includes(activeTag))
- && (q === '' || [siteLabel(site), site.title, site.url, site.domain]
- .some(v => v && String(v).toLowerCase().includes(q)))
- ));
- const allSelected = shownSites.length > 0 && shownSites.every(s => selectedIds.has(s.id));
-
- const columns = [
- {
- key: '__select',
- className: 'wp-list__ck',
- cellClassName: 'wp-list__ck',
- header: (
- <Checkbox
- checked={allSelected}
- onCheckedChange={(checked) => setSelectedIds(checked ? new Set(shownSites.map(s => s.id)) : new Set())}
- aria-label="Select all sites"
- />
- ),
- render: (site) => (
- <div onClick={e => e.stopPropagation()}>
- <Checkbox
- checked={selectedIds.has(site.id)}
- onCheckedChange={(checked) => {
- setSelectedIds(prev => {
- const next = new Set(prev);
- if (checked) next.add(site.id);
- else next.delete(site.id);
- return next;
- });
- }}
- aria-label={`Select ${site.name || `site ${site.id}`}`}
- />
- </div>
- ),
- },
- {
- key: 'name',
- header: 'Site',
- render: (site) => (
- <div className="sk-cell-name">
- <ServiceTile name={siteLabel(site)} size={30} className="wp-list__tile" aria-hidden="true" />
- <span>
- <div>{siteLabel(site)}</div>
- {site.port && <div className="sk-cell-sub">:{site.port}</div>}
- </span>
- </div>
- ),
- },
- { key: 'environments', header: 'Environments', cellClassName: 'sk-cell-mono', render: (site) => (site.environment_count || 0) + 1 },
- { key: 'version', header: 'Version', cellClassName: 'sk-cell-mono', render: (site) => `WP ${site.wp_version || '6.4'}` },
- {
- key: 'status',
- header: 'Status',
- render: (site) => (
- <Pill kind={site.status === 'running' ? 'green' : 'gray'}>
- {site.status === 'running' ? 'Running' : 'Stopped'}
- </Pill>
- ),
- },
- {
- key: 'tags',
- header: 'Tags',
- render: (site) => (
- site.tags?.length
- ? site.tags.map(tag => <span key={tag} className="sk-tag">{tag}</span>)
- : <span className="wp-list__dash">—</span>
- ),
- },
- {
- key: '__links',
- header: '',
- width: 70,
- render: (site) => (
- site.url && site.status === 'running' ? (
- <div className="wp-list__links" onClick={e => e.stopPropagation()}>
- <a href={site.url} target="_blank" rel="noopener noreferrer" title="Open site" aria-label="Open site">
- <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
- </a>
- <a href={`${site.url}/wp-admin`} target="_blank" rel="noopener noreferrer" title="WP Admin" aria-label="WP Admin">
- <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
- </a>
- </div>
- ) : (
- <ChevronRight size={16} className="wp-list__chev" />
- )
- ),
- },
- ];
-
- return (
- <ResourceListPage
- className="wordpress-page"
- totalCount={sites.length}
- items={shownSites}
- columns={columns}
- keyField="id"
- onRowClick={(site) => navigate(`/wordpress/${site.id}`)}
- rowClassName={(site) => (selectedIds.has(site.id) ? 'is-selected' : '')}
- header={<>
- {/* Advisory, not a gate: a constrained server says so here and
- the operator still decides. */}
- <ResourceAdvisory workload="wordpress" />
- {(createdCreds || createdSite) && (
- <div className="wp-creds-banner">
- <div className="wp-creds-banner-text">
- {createdSite && (createdSite.domain ? (
- <span>
- Your site is live at{' '}
- <a href={createdSite.url} target="_blank" rel="noopener noreferrer"><code>{createdSite.domain}</code></a>
- {createdSite.url?.startsWith('https') ? ' — HTTPS is ready.' : '.'}
- </span>
- ) : (
- <span>
- Your site is running at{' '}
- <a href={createdSite.url} target="_blank" rel="noopener noreferrer"><code>{createdSite.url}</code></a>.
- {' '}Set a managed-sites base domain in Settings to publish it at a public URL.
- </span>
- ))}
- {createdCreds && (
- <>
- <strong>Save these admin credentials — they are shown only once.</strong>
- <span>Username: <code>{createdCreds.user}</code></span>
- <span>Password: <code>{createdCreds.password}</code></span>
- </>
- )}
- </div>
- <Button variant="ghost" onClick={() => { setCreatedCreds(null); setCreatedSite(null); }}>Dismiss</Button>
- </div>
- )}
- </>}
- filters={[
- { value: 'all', label: 'All', count: sites.length },
- { value: 'running', label: 'Running', count: runningCount },
- { value: 'stopped', label: 'Stopped', count: sites.length - runningCount },
- ]}
- activeFilter={statusFilter}
- onFilterChange={setStatusFilter}
- searchTerm={siteSearch}
- onSearchChange={setSiteSearch}
- searchPlaceholder="Search sites…"
- toolbarExtra={allTags.length > 0 && (
- <div className="wp-tag-filter">
- <button type="button"
- className={`wp-tag-chip wp-tag-chip--filter ${activeTag === null ? 'is-active' : ''}`}
- onClick={() => setActiveTag(null)}
- >
- All tags
- </button>
- {allTags.map(tag => (
- <button type="button"
- key={tag}
- className={`wp-tag-chip wp-tag-chip--filter ${activeTag === tag ? 'is-active' : ''}`}
- onClick={() => setActiveTag(tag)}
- >
- {tag}
- </button>
- ))}
- </div>
- )}
- selectedCount={selectedIds.size}
- onClearSelection={() => setSelectedIds(new Set())}
- bulkActions={
- <>
- <Button variant="outline" size="sm" disabled={bulkLoading}
- onClick={() => bulkRun('Start', s => wordpressApi.unarchiveSite(s.id), s => s.status !== 'running')}>
- Start
- </Button>
- <Button variant="outline" size="sm" disabled={bulkLoading}
- onClick={() => bulkRun('Stop', s => wordpressApi.archiveSite(s.id), s => s.status === 'running')}>
- Stop
- </Button>
- <Button variant="outline" size="sm" disabled={bulkLoading}
- onClick={() => bulkRun('Update core', s => wordpressApi.updateCore(s.id), s => s.status === 'running')}>
- Update
- </Button>
- <Button variant="outline" size="sm" disabled={bulkLoading}
- onClick={() => bulkRun('Backup', s => wordpressApi.createSnapshot(s.id, { name: 'bulk-backup' }), s => s.status === 'running')}>
- Backup
- </Button>
- <Button variant="outline" size="sm" disabled={bulkLoading}
- onClick={() => bulkRun('Clear cache', s => wordpressApi.flushCache(s.id), s => s.status === 'running')}>
- Clear cache
- </Button>
- </>
- }
- emptyIcon={Globe}
- emptyTitle="No WordPress Sites"
- emptyDescription="Create your first WordPress site powered by Docker. Each site gets its own isolated environment with MySQL."
- emptyAction={
- <Button onClick={() => setShowCreateModal(true)}>
- Create Site
- </Button>
- }
- filteredEmptyIcon={Globe}
- filteredEmptyTitle="No sites found"
- filteredEmptyDescription="Try adjusting your search or filter"
- >
- {/* Import Site Modal */}
- <Modal
- open={showImportModal}
- onClose={() => !importLoading && setShowImportModal(false)}
- title="Import WordPress Site"
- size="lg"
- >
- <div className="modal-body">
- <div className="install-warning">
- <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>
- <div>
- <strong>Imports a database dump into a new stack:</strong>
- <ul>
- <li>Provisions a fresh WordPress + MySQL container</li>
- <li>Loads your .sql / .sql.gz dump</li>
- <li>Rewrites the site URL to this server</li>
- </ul>
- </div>
- </div>
-
- <div className="form-group">
- <Label>Site Name <span className="required">*</span></Label>
- <Input
- type="text"
- value={importForm.name}
- onChange={e => setImportForm({ ...importForm, name: e.target.value })}
- placeholder="my-imported-site"
- disabled={importLoading}
- />
- <span className="form-hint">Used as the Docker project name. Letters, numbers, and hyphens only.</span>
- </div>
-
- <div className="form-group">
- <Label>Original Site URL <span className="required">*</span></Label>
- <Input
- type="text"
- value={importForm.oldUrl}
- onChange={e => setImportForm({ ...importForm, oldUrl: e.target.value })}
- placeholder="https://old-site.com"
- disabled={importLoading}
- />
- <span className="form-hint">The live URL in your dump; we rewrite it to the localhost address on this server.</span>
- </div>
-
- <div className="form-group">
- <Label>Admin Email</Label>
- <Input
- type="email"
- value={importForm.adminEmail}
- onChange={e => setImportForm({ ...importForm, adminEmail: e.target.value })}
- placeholder="[email protected]"
- disabled={importLoading}
- />
- </div>
-
- <div className="form-group">
- <Label>Database Dump <span className="required">*</span></Label>
- <input
- type="file"
- accept=".sql,.gz,.sql.gz"
- disabled={importLoading}
- onChange={e => setImportFile(e.target.files?.[0] || null)}
- />
- <span className="form-hint">Export via phpMyAdmin or the wp db export command. .sql.gz is supported and recommended (100MB upload limit).</span>
- </div>
-
- <div className="form-group">
- <Label>wp-content archive (optional)</Label>
- <input
- type="file"
- accept=".zip"
- disabled={importLoading}
- onChange={e => setWpContentFile(e.target.files?.[0] || null)}
- />
- <span className="form-hint">A .zip of wp-content (plugins/themes/uploads) or the full site. Copied into the new container after the database import. Leave empty to import the database only.</span>
- </div>
- </div>
- <div className="modal-footer">
- <Button variant="outline" onClick={() => setShowImportModal(false)} disabled={importLoading}>
- Cancel
- </Button>
- <Button onClick={handleImport} disabled={importLoading || !importForm.name || !importForm.oldUrl || !importFile}>
- {importLoading ? <><Spinner size="sm" /> Importing...</> : 'Import Site'}
- </Button>
- </div>
- </Modal>
-
- {/* Create Site — the same drawer shape the templates catalog uses, so
- creating a WordPress site and deploying a template feel like one
- product rather than two. */}
- <Drawer
- flush
- open={showCreateModal}
- onOpenChange={(next) => { if (!next && !createLoading) setShowCreateModal(false); }}
- title="Create WordPress Site"
- subtitle="WordPress + MySQL on an isolated Docker network"
- icon={<Globe size={20} />}
- width={560}
- className="sk-formdrawer"
- >
- <div className="sk-formdrawer__form">
- <div className="sk-formdrawer__body">
- <div className="sk-formdrawer__callout">
- <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>
- <div>
- <strong>This will create:</strong>
- <ul>
- <li>WordPress 6.4 (Apache) container</li>
- <li>MySQL 8.0 database container</li>
- <li>Isolated Docker network</li>
- </ul>
- </div>
- </div>
-
- <div className="sk-formdrawer__field">
- <Label>
- Site Name <span className="required">*</span>
- </Label>
- <Input
- type="text"
- value={createForm.name}
- onChange={e => setCreateForm({ ...createForm, name: e.target.value })}
- placeholder="my-wordpress-site"
- disabled={createLoading}
- />
- <span className="sk-formdrawer__hint">Used as the Docker project name. Letters, numbers, and hyphens only.</span>
- </div>
-
- {baseDomains.length > 0 ? (
- <div className="sk-formdrawer__field">
- <Label>Publish under</Label>
- <select
- value={createForm.baseDomain}
- onChange={e => setCreateForm({ ...createForm, baseDomain: e.target.value })}
- disabled={createLoading}
- >
- {baseDomains.map(b => (
- <option key={b.domain} value={b.domain}>
- {b.domain}{b.is_default ? ' (default)' : ''}{b.https_enabled ? ' — HTTPS' : ''}
- </option>
- ))}
- </select>
- <span className="sk-formdrawer__hint">
- {createForm.name
- ? <>The site will be live at <code>{slugifyPreview(createForm.name)}.{createForm.baseDomain}</code>.</>
- : <>Which base domain to publish this site under.</>}
- </span>
- </div>
- ) : (
- <div className="sk-formdrawer__field">
- <Label>Publish under</Label>
- <span className="sk-formdrawer__hint">No base domain configured — the site will be reachable at <code>localhost:&lt;port&gt;</code>. Add a managed-sites base domain in Settings to publish it at a real subdomain.</span>
- </div>
- )}
-
- <div className="sk-formdrawer__field">
- <Label>Custom Domain</Label>
- <Input
- type="text"
- value={createForm.domain}
- onChange={e => setCreateForm({ ...createForm, domain: e.target.value })}
- placeholder="example.com"
- disabled={createLoading}
- />
- <span className="sk-formdrawer__hint">Optional. Overrides the base domain above — the site is created and migrated to this domain.</span>
- </div>
-
- <div className="sk-formdrawer__field">
- <Label>Admin Email</Label>
- <Input
- type="email"
- value={createForm.adminEmail}
- onChange={e => setCreateForm({ ...createForm, adminEmail: e.target.value })}
- placeholder="[email protected]"
- disabled={createLoading}
- />
- </div>
-
- <div className="sk-formdrawer__field">
- <Label>PHP Version</Label>
- <select
- value={createForm.phpVersion}
- onChange={e => setCreateForm({ ...createForm, phpVersion: e.target.value })}
- disabled={createLoading}
- >
- <option value="">Default (latest for WordPress 6.4)</option>
- <option value="8.1">PHP 8.1</option>
- <option value="8.2">PHP 8.2</option>
- <option value="8.3">PHP 8.3</option>
- </select>
- <span className="sk-formdrawer__hint">Baked into the container image at creation. Changeable later from the PHP tab.</span>
- </div>
-
- <div className="sk-formdrawer__field">
- <label className="checkbox-label">
- <input
- type="checkbox"
- checked={createForm.enablePageCache}
- onChange={e => setCreateForm({ ...createForm, enablePageCache: e.target.checked })}
- disabled={createLoading}
- />
- Enable full-page cache
- </label>
- <span className="sk-formdrawer__hint">Disk page cache with WordPress-aware skip rules (admin, login, cart, checkout).</span>
- </div>
-
- <div className="sk-formdrawer__field">
- <label className="checkbox-label">
- <input
- type="checkbox"
- checked={createForm.enableObjectCache}
- onChange={e => setCreateForm({ ...createForm, enableObjectCache: e.target.checked })}
- disabled={createLoading}
- />
- Enable Redis object cache
- </label>
- <span className="sk-formdrawer__hint">Uses the bundled Redis container with the redis-cache drop-in.</span>
- </div>
- </div>
- <div className="sk-formdrawer__foot">
- <Button
- variant="outline"
- onClick={() => setShowCreateModal(false)}
- disabled={createLoading}
- >
- Cancel
- </Button>
- <Button
- onClick={handleCreate}
- disabled={createLoading || !createForm.name}
- >
- {createLoading ? <><Spinner size="sm" /> Creating...</> : 'Create Site'}
- </Button>
- </div>
- </div>
- </Drawer>
- </ResourceListPage>
- );
-}
-
-export default WordPress;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/pages/WordPressDetail.jsx b/builtin-extensions/serverkit-wordpress/frontend/pages/WordPressDetail.jsx
deleted file mode 100644
index c2781bdb..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/pages/WordPressDetail.jsx
+++ /dev/null
@@ -1,469 +0,0 @@
-import { useState, useEffect } from 'react';
-import { useParams, useNavigate, Link } from 'react-router-dom';
-import { Settings, Database, GitBranch, Package, Palette, FolderOpen, FileText, Lock, Activity, Globe, BarChart3, LayoutDashboard, Layers } from 'lucide-react';
-import { useTabParam } from 'serverkit-sdk';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { useLogsDrawer } from '@/contexts/LogsDrawerContext';
-import ChangeUrlModal from '../components/wordpress/ChangeUrlModal';
-import AttachDomainModal from '../components/wordpress/AttachDomainModal';
-import { Pill, EnvTag, PageTopbar } from 'serverkit-sdk';
-import { ErrorBoundary } from '@/components/ErrorBoundary';
-import { EmptyState } from 'serverkit-sdk';
-import PluginSlot from '@/components/PluginSlot';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import {
- DetailPageSkeleton,
- EnvSwitcher,
- SSLAlert,
- envTagLabel,
-} from '../components/wordpress/detail/wpDetailShared';
-import OverviewTab from '../components/wordpress/detail/OverviewTab';
-import EnvironmentsTab from '../components/wordpress/detail/EnvironmentsTab';
-import DatabaseTab from '../components/wordpress/detail/DatabaseTab';
-import PluginsTab from '../components/wordpress/detail/PluginsTab';
-import ThemesTab from '../components/wordpress/detail/ThemesTab';
-import GitTab from '../components/wordpress/detail/GitTab';
-import BackupsTab from '../components/wordpress/detail/BackupsTab';
-import UptimeTab from '../components/wordpress/detail/UptimeTab';
-import AnalyticsTab from '../components/wordpress/detail/AnalyticsTab';
-import VulnerabilitiesTab from '../components/wordpress/detail/VulnerabilitiesTab';
-import SecurityTab from '../components/wordpress/detail/SecurityTab';
-import UpdatesTab from '../components/wordpress/detail/UpdatesTab';
-import PhpTab from '../components/wordpress/detail/PhpTab';
-import ReportsTab from '../components/wordpress/detail/ReportsTab';
-import SettingsTab from '../components/wordpress/detail/SettingsTab';
-
-// 'php' and 'updates' no longer have their own top-level tab — they live inside
-// the Settings tab's left nav — but stay valid so existing deep links still work.
-const VALID_TABS = ['overview', 'environments', 'database', 'plugins', 'themes', 'git', 'backups', 'uptime', 'analytics', 'vulnerabilities', 'security', 'updates', 'php', 'reports', 'settings'];
-
-const WordPressDetail = () => {
- const { id } = useParams();
- const navigate = useNavigate();
- const toast = useToast();
- const { openDrawer } = useLogsDrawer();
- const [site, setSite] = useState(null);
- const [loading, setLoading] = useState(true);
- const [activeTab, setActiveTab] = useTabParam(`/wordpress/${id}`, VALID_TABS);
- const [autoLoggingIn, setAutoLoggingIn] = useState(false);
- const [showCloneModal, setShowCloneModal] = useState(false);
- const [showChangeUrl, setShowChangeUrl] = useState(false);
- const [showAddDomain, setShowAddDomain] = useState(false);
- const [cloning, setCloning] = useState(false);
- const [cloneName, setCloneName] = useState('');
- const [clonedCreds, setClonedCreds] = useState(null);
- const [gitStatus, setGitStatus] = useState(null);
-
- useEffect(() => {
- // Show the skeleton again when navigating between environment site ids
- // (env switcher / "Open new site") so stale data never renders.
- setLoading(true);
- loadSite();
- }, [id]);
-
- useEffect(() => {
- // Load Git connection summary so we can surface a repo pill in the header,
- // matching the Service detail page's "Connect a repository" affordance.
- if (!id) return;
- wordpressApi.getGitStatus(id)
- .then(setGitStatus)
- .catch(() => setGitStatus(null));
- }, [id]);
-
- async function loadSite() {
- try {
- const data = await wordpressApi.getSite(id);
- setSite(data.site || data);
- } catch (err) {
- console.error('Failed to load site:', err);
- toast.error('Failed to load WordPress site');
- } finally {
- setLoading(false);
- }
- }
-
- async function handleClone() {
- if (!cloneName.trim()) {
- toast.error('New site name is required');
- return;
- }
- setCloning(true);
- toast.info('Cloning site... this spins up a new stack and may take a minute.', { duration: 6000 });
- try {
- const res = await wordpressApi.cloneSite(site.id, { name: cloneName.trim() });
- if (res.success) {
- setShowCloneModal(false);
- setCloneName('');
- if (res.admin_password) {
- setClonedCreds({ user: res.admin_user || 'admin', password: res.admin_password, id: res.site?.id });
- }
- toast.success('Site cloned successfully');
- } else {
- toast.error(res.error || 'Failed to clone site');
- }
- } catch (err) {
- toast.error(err.message || 'Failed to clone site');
- } finally {
- setCloning(false);
- }
- }
-
- async function handleAutoLogin() {
- setAutoLoggingIn(true);
- toast.info('Creating one-time login link...', { duration: 3000 });
- try {
- const res = await wordpressApi.autoLogin(site.id);
- if (res && res.url) {
- window.open(res.url, '_blank', 'noopener,noreferrer');
- } else {
- toast.error('No login URL returned');
- }
- } catch (err) {
- toast.error(err.message || 'Failed to create login link');
- } finally {
- setAutoLoggingIn(false);
- }
- }
-
- if (loading) {
- return <SkeletonBoundary loading skeleton={<DetailPageSkeleton />} />;
- }
-
- if (!site) {
- return (
- <EmptyState
- icon={Globe}
- title="Site not found"
- description="This WordPress site does not exist or has been removed."
- action={<Button onClick={() => navigate('/wordpress')}>Back to WordPress Sites</Button>}
- />
- );
- }
-
- const isRunning = site.status === 'running';
-
- // Environment switcher options from data already in the payload:
- // production sites carry `environments`; child envs carry `production_site_id`.
- let envOptions = null;
- if (site.is_production && (site.environments || []).length > 0) {
- envOptions = [
- { id: site.id, name: site.name, type: 'production', url: site.url, current: true },
- ...site.environments.map(e => ({
- id: e.id,
- name: e.name || e.environment_type || `Environment ${e.id}`,
- type: e.environment_type || 'development',
- url: e.url,
- current: false,
- })),
- ];
- } else if (!site.is_production && site.production_site_id) {
- envOptions = [
- { id: site.production_site_id, name: 'Production', type: 'production', current: false },
- { id: site.id, name: site.name, type: site.environment_type || 'development', url: site.url, current: true },
- ];
- }
-
- return (
- <div className="app-detail-page app-detail-page--wide wp-detail-page">
- {/* One-time cloned-admin credentials banner */}
- {clonedCreds && (
- <div className="wp-creds-banner">
- <div className="wp-creds-banner-text">
- <strong>New site created — save these admin credentials, shown only once.</strong>
- <span>Username: <code>{clonedCreds.user}</code></span>
- <span>Password: <code>{clonedCreds.password}</code></span>
- {clonedCreds.id && (
- <Button variant="ghost" onClick={() => navigate(`/wordpress/${clonedCreds.id}`)}>Open new site</Button>
- )}
- </div>
- <Button variant="ghost" onClick={() => setClonedCreds(null)}>Dismiss</Button>
- </div>
- )}
-
- {/* Top bar — the canonical PageTopbar (.sk-topbar): the SAME chrome as
- the WordPress LIST page and every other page, so the top menu is
- consistent. Breadcrumb in the title slot, actions on the right. */}
- <PageTopbar
- className="wp-detail-topbar"
- icon={<Globe size={18} />}
- title={(
- <span className="wp-crumbs">
- <Link to="/wordpress">WordPress</Link>
- <span className="wp-crumbs__sep">/</span>
- <span className="wp-crumbs__cur">{site.name}</span>
- </span>
- )}
- actions={(
- <>
- <Button
- variant="ghost"
- onClick={() => navigate(`/files?path=${encodeURIComponent(site.application?.root_path || '/')}`)}
- disabled={!site.application?.root_path}
- title={site.application?.root_path ? `Open ${site.application.root_path} in the File Manager` : 'No root path configured for this site'}
- >
- <FolderOpen size={16} />
- Open Files
- </Button>
- {site.db_name && (
- <Button
- variant="ghost"
- onClick={() => navigate(`/databases/mysql?db=${encodeURIComponent(site.db_name)}`)}
- title={`Open ${site.db_name} in the Database manager`}
- >
- <Database size={16} />
- Open Database
- </Button>
- )}
- <Button
- variant="ghost"
- onClick={() => openDrawer({ name: site.name, containerId: site.application_id, appType: 'docker' })}
- title="View live container logs"
- >
- <FileText size={16} />
- View Logs
- </Button>
- {site.url && (
- <Button variant="ghost" asChild>
- <a
- href={`${site.url}/wp-admin`}
- target="_blank"
- rel="noopener noreferrer"
- >
- <Settings size={16} />
- Dashboard
- </a>
- </Button>
- )}
- <Button
- variant="default"
- onClick={handleAutoLogin}
- disabled={autoLoggingIn}
- title="Open wp-admin logged in, no password (one-time link)"
- >
- <Lock size={16} />
- {autoLoggingIn ? 'Signing in...' : 'Auto Login'}
- </Button>
- </>
- )}
- />
-
- {/* Everything below the full-bleed top bar is padded by .app-detail-body
- (the top bar itself spans edge-to-edge like the list page). */}
- <div className="app-detail-body">
- {/* Identity — icon + name + status + environment + version (no actions). */}
- <div className="app-detail-header">
- <div className="app-detail-icon wp-icon">
- <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" strokeWidth="2">
- <circle cx="12" cy="12" r="8" />
- </svg>
- <span className={`wp-head-dot ${isRunning ? 'running' : 'stopped'}`} />
- </div>
- <div className="app-detail-title-block">
- <h1>
- {site.name}
- <Pill kind={isRunning ? 'green' : 'gray'}>{isRunning ? 'Running' : 'Stopped'}</Pill>
- {site.is_production ? (
- <EnvTag env="PROD" />
- ) : site.production_site_id ? (
- <EnvTag env={envTagLabel(site.environment_type)} />
- ) : null}
- {envOptions && envOptions.length > 1 && (
- <EnvSwitcher options={envOptions} onSelect={(envId) => navigate(`/wordpress/${envId}`)} />
- )}
- <SSLAlert site={site} />
- </h1>
- <div className="app-detail-subtitle">
- <span>WordPress {site.wp_version || '—'}</span>
- {site.application?.php_version && (
- <>
- <span className="separator">·</span>
- <span>PHP {site.application.php_version}</span>
- </>
- )}
- {site.url && (
- <>
- <span className="separator">·</span>
- <a href={site.url} target="_blank" rel="noopener noreferrer">{site.url}</a>
- </>
- )}
- {site.multisite && (
- <>
- <span className="separator">·</span>
- <span>multisite</span>
- </>
- )}
- </div>
- </div>
- </div>
-
- {/* Repo Connection Pill — same prominent affordance as the service detail page. */}
- <div className="wp-detail__repo-bar">
- {gitStatus?.connected ? (
- <div
- className="wp-detail__repo-pill"
- onClick={() => navigate(`/wordpress/${id}/settings/git`)}
- title="Repository connected — open Git settings"
- >
- <GitBranch size={14} />
- <span className="wp-detail__repo-url">{extractRepoDisplay(gitStatus.repo_url)}</span>
- <span className="wp-detail__repo-arrow">→</span>
- <span className="wp-detail__repo-branch">{gitStatus.branch || 'main'}</span>
- {gitStatus.auto_deploy && (
- <span className="wp-detail__auto-deploy-badge">Auto</span>
- )}
- </div>
- ) : (
- <button type="button"
- className="wp-detail__connect-repo"
- onClick={() => navigate(`/wordpress/${id}/settings/git`)}
- >
- <GitBranch size={14} />
- Connect a repository
- </button>
- )}
- </div>
-
- {/* Tabs */}
- <div className="app-detail-tabs">
- <div
- className={`app-detail-tab ${activeTab === 'overview' ? 'active' : ''}`}
- onClick={() => setActiveTab('overview')}
- >
- <LayoutDashboard size={14} /> Overview
- </div>
- <div
- className={`app-detail-tab ${activeTab === 'environments' ? 'active' : ''}`}
- onClick={() => setActiveTab('environments')}
- >
- <Layers size={14} /> Env
- </div>
- <div
- className={`app-detail-tab ${activeTab === 'database' ? 'active' : ''}`}
- onClick={() => setActiveTab('database')}
- >
- <Database size={14} /> Database
- </div>
- <div
- className={`app-detail-tab ${activeTab === 'plugins' ? 'active' : ''}`}
- onClick={() => setActiveTab('plugins')}
- >
- <Package size={14} /> Plugins
- </div>
- <div
- className={`app-detail-tab ${activeTab === 'themes' ? 'active' : ''}`}
- onClick={() => setActiveTab('themes')}
- >
- <Palette size={14} /> Themes
- </div>
- <div
- className={`app-detail-tab ${activeTab === 'uptime' ? 'active' : ''}`}
- onClick={() => setActiveTab('uptime')}
- >
- <Activity size={14} /> Uptime
- </div>
- <div
- className={`app-detail-tab ${activeTab === 'analytics' ? 'active' : ''}`}
- onClick={() => setActiveTab('analytics')}
- >
- <BarChart3 size={14} /> Analytics
- </div>
- <div
- className={`app-detail-tab app-detail-tab--end ${activeTab === 'settings' ? 'active' : ''}`}
- onClick={() => setActiveTab('settings')}
- >
- <Settings size={14} /> Settings
- </div>
- </div>
-
- {showChangeUrl && (
- <ChangeUrlModal
- site={site}
- onClose={() => setShowChangeUrl(false)}
- onChanged={loadSite}
- />
- )}
-
- {showAddDomain && (
- <AttachDomainModal
- site={site}
- onClose={() => setShowAddDomain(false)}
- onChanged={loadSite}
- />
- )}
-
- {/* Clone Site Modal */}
- <Modal open={showCloneModal} onClose={() => !cloning && setShowCloneModal(false)} title="Clone Site">
- <form onSubmit={(e) => { e.preventDefault(); handleClone(); }}>
- <p className="hint">Creates a brand-new independent WordPress site (its own Docker stack and database) seeded from <strong>{site.name}</strong>, with fresh admin credentials shown once.</p>
- <div className="form-group">
- <Label>New Site Name *</Label>
- <Input
- type="text"
- value={cloneName}
- onChange={(e) => setCloneName(e.target.value)}
- placeholder={`${site.name}-copy`}
- autoFocus
- disabled={cloning}
- />
- </div>
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={() => setShowCloneModal(false)} disabled={cloning}>Cancel</Button>
- <Button type="submit" disabled={cloning || !cloneName.trim()}>{cloning ? 'Cloning...' : 'Clone Site'}</Button>
- </div>
- </form>
- </Modal>
-
- {/* Tab Content */}
- <div className="app-detail-content">
- <ErrorBoundary key={activeTab} onRetry={loadSite}>
- {activeTab === 'overview' && <OverviewTab site={site} onUpdate={loadSite} />}
- {activeTab === 'environments' && <EnvironmentsTab siteId={site.id} site={site} onUpdate={loadSite} />}
- {activeTab === 'database' && <DatabaseTab siteId={site.id} site={site} />}
- {activeTab === 'plugins' && <PluginsTab siteId={site.id} />}
- {activeTab === 'themes' && <ThemesTab siteId={site.id} />}
- {activeTab === 'git' && <GitTab siteId={site.id} site={site} onUpdate={loadSite} />}
- {activeTab === 'backups' && <BackupsTab siteId={site.id} site={site} />}
- {activeTab === 'uptime' && <UptimeTab siteId={site.id} />}
- {activeTab === 'analytics' && <AnalyticsTab siteId={site.id} />}
- {activeTab === 'vulnerabilities' && <VulnerabilitiesTab siteId={site.id} />}
- {activeTab === 'security' && <SecurityTab siteId={site.id} />}
- {activeTab === 'updates' && <UpdatesTab siteId={site.id} />}
- {activeTab === 'php' && <PhpTab siteId={site.id} />}
- {activeTab === 'reports' && <ReportsTab siteId={site.id} />}
- {activeTab === 'settings' && (
- <SettingsTab
- siteId={site.id}
- site={site}
- onUpdate={loadSite}
- onAddDomain={() => setShowAddDomain(true)}
- onChangeUrl={() => setShowChangeUrl(true)}
- onClone={() => setShowCloneModal(true)}
- />
- )}
- </ErrorBoundary>
- </div>
-
- {/* Extension slot: widgets contributed to the WordPress detail page */}
- <PluginSlot name="wordpress.detail.panel" context={{ site }} />
- </div>
- </div>
- );
-};
-
-function extractRepoDisplay(url) {
- if (!url) return '';
- try {
- const cleaned = url.replace(/\.git$/, '').replace(/^https?:\/\/[^@]+@/, 'https://');
- const parts = cleaned.split(/[/:]/).filter(Boolean);
- return parts.slice(-2).join('/');
- } catch {
- return url;
- }
-}
-
-export default WordPressDetail;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/pages/WordPressPluginLibrary.jsx b/builtin-extensions/serverkit-wordpress/frontend/pages/WordPressPluginLibrary.jsx
deleted file mode 100644
index 4ddd4a5b..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/pages/WordPressPluginLibrary.jsx
+++ /dev/null
@@ -1,353 +0,0 @@
-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 'serverkit-sdk';
-import { useAuth } from 'serverkit-sdk';
-import { EmptyState } from 'serverkit-sdk';
-import { Spinner } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Pill, ServiceTile } from 'serverkit-sdk';
-import { useTopbarActions } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { Switch } from 'serverkit-sdk';
-
-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/builtin-extensions/serverkit-wordpress/frontend/pages/WordPressProject.jsx b/builtin-extensions/serverkit-wordpress/frontend/pages/WordPressProject.jsx
deleted file mode 100644
index 39cf9169..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/pages/WordPressProject.jsx
+++ /dev/null
@@ -1,1042 +0,0 @@
-import { useState, useEffect, useCallback, useRef } from 'react';
-import { useParams, useNavigate, Link } from 'react-router-dom';
-import { Plus, ExternalLink, RefreshCw, GitBranch, Search, Shield, Activity, Settings, ArrowRight, RotateCcw } from 'lucide-react';
-import { useTabParam } from 'serverkit-sdk';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import {
- PipelineView,
- PromoteModal,
- SyncModal,
- ActivityFeed,
- ContainerLogs,
- CompareView,
- SanitizationProfileForm,
- ResourceLimitsModal,
- BasicAuthModal,
- WpCliTerminal,
- HealthStatusPanel,
- AutoSyncScheduleModal,
- BulkActionsBar,
-} from '../components/wordpress';
-import { ConfirmDialog } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Spinner } from 'serverkit-sdk';
-import { EmptyState } from 'serverkit-sdk';
-import { FolderGit2 } from 'lucide-react';
-import { io } from 'socket.io-client';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-
-const SOCKET_URL = import.meta.env.VITE_API_URL?.replace('/api/v1', '') || window.location.origin;
-
-const VALID_TABS = ['pipeline', 'activity', 'health'];
-
-const WordPressProject = () => {
- const { id } = useParams();
- const navigate = useNavigate();
- const toast = useToast();
-
- const [pipeline, setPipeline] = useState(null);
- const [loading, setLoading] = useState(true);
- const [activeTab, setActiveTab] = useTabParam(`/wordpress/pipelines/${id}`, VALID_TABS);
- const [showCreateEnvModal, setShowCreateEnvModal] = useState(false);
- const [promoteModal, setPromoteModal] = useState(null);
- const [syncModal, setSyncModal] = useState(null);
- const [logsPanel, setLogsPanel] = useState(null);
- const [confirmDialog, setConfirmDialog] = useState(null);
- const [operationInProgress, setOperationInProgress] = useState(null);
- const [operationProgress, setOperationProgress] = useState(null);
- const [compareModal, setCompareModal] = useState(null);
- const [showSanitizationProfiles, setShowSanitizationProfiles] = useState(false);
-
- // Phase 7 state
- const [resourceLimitsModal, setResourceLimitsModal] = useState(null);
- const [basicAuthModal, setBasicAuthModal] = useState(null);
- const [wpCliModal, setWpCliModal] = useState(null);
- const [autoSyncModal, setAutoSyncModal] = useState(null);
- const [healthData, setHealthData] = useState({});
- const [diskUsageData, setDiskUsageData] = useState({});
- const [bulkSelected, setBulkSelected] = useState([]);
-
- const socketRef = useRef(null);
-
- useEffect(() => {
- loadPipeline();
- connectSocket();
-
- return () => {
- if (socketRef.current) {
- socketRef.current.emit('unsubscribe_pipeline', { project_id: Number(id) });
- socketRef.current.disconnect();
- }
- };
- }, [id]);
-
- function connectSocket() {
- const token = localStorage.getItem('access_token');
- if (!token) return;
-
- const socket = io(SOCKET_URL, {
- auth: { token },
- transports: ['websocket', 'polling']
- });
-
- socket.on('connect', () => {
- socket.emit('subscribe_pipeline', { project_id: Number(id) });
- });
-
- socket.on('pipeline_event', (data) => {
- handlePipelineEvent(data);
- });
-
- socketRef.current = socket;
- }
-
- function handlePipelineEvent(data) {
- const { event, data: eventData } = data;
-
- switch (event) {
- case 'environment_created':
- case 'environment_deleted':
- case 'promotion_completed':
- case 'sync_completed':
- loadPipeline();
- if (eventData.success) {
- toast.success(eventData.message || `${event.replace(/_/g, ' ')} successfully`);
- }
- setOperationInProgress(null);
- break;
- case 'environment_create_failed':
- case 'environment_delete_failed':
- case 'promotion_failed':
- case 'sync_failed':
- loadPipeline();
- toast.error(eventData.message || `${event.replace(/_/g, ' ')}`);
- setOperationInProgress(null);
- break;
- case 'environment_started':
- case 'environment_stopped':
- case 'environment_restarted':
- case 'environment_locked':
- case 'environment_unlocked':
- loadPipeline();
- break;
- case 'promotion_started':
- case 'sync_started':
- case 'environment_creating':
- setOperationInProgress(event);
- setOperationProgress(null);
- break;
- case 'operation_progress':
- setOperationProgress(eventData);
- break;
- case 'bulk_operation_completed':
- loadPipeline();
- toast.success('Bulk operation completed');
- break;
- default:
- break;
- }
- }
-
- async function loadPipeline() {
- try {
- const data = await wordpressApi.getProjectPipeline(id);
- setPipeline(data);
- } catch (err) {
- console.error('Failed to load pipeline:', err);
- toast.error('Failed to load project pipeline');
- } finally {
- setLoading(false);
- }
- }
-
- const handlePromote = useCallback((sourceEnv, targetEnv) => {
- setPromoteModal({ sourceEnv, targetEnv });
- }, []);
-
- const handleDoPromote = useCallback(async (config) => {
- try {
- const res = await wordpressApi.promoteEnvironment(id, config);
- setPromoteModal(null);
- // A promotion is a deployment now: open its console, where the
- // steps, live log and retry live.
- if (res?.job_id) navigate(`/deployments/${res.job_id}`);
- else toast.info('Promotion queued');
- } catch (err) {
- toast.error(err.message || 'Promotion failed');
- }
- }, [id, navigate, toast]);
-
- const handleSync = useCallback((env) => {
- setSyncModal({ environment: env });
- }, []);
-
- const handleDoSync = useCallback(async (config) => {
- const env = syncModal.environment;
- toast.info('Starting sync...', { duration: 3000 });
- try {
- await wordpressApi.syncProjectEnvironment(id, env.id, config);
- setSyncModal(null);
- } catch (err) {
- toast.error(err.message || 'Sync failed');
- }
- }, [id, syncModal, toast]);
-
- const handleStart = useCallback(async (env) => {
- try {
- await wordpressApi.startEnvironment(id, env.id);
- toast.success('Environment started');
- loadPipeline();
- } catch (err) {
- toast.error(err.message || 'Failed to start environment');
- }
- }, [id, toast]);
-
- const handleStop = useCallback(async (env) => {
- setConfirmDialog({
- title: 'Stop Environment',
- message: `Stop the ${env.environment_type || ''} environment "${env.name}"?`,
- confirmText: 'Stop',
- variant: 'warning',
- onConfirm: async () => {
- try {
- await wordpressApi.stopEnvironment(id, env.id);
- toast.success('Environment stopped');
- loadPipeline();
- } catch (err) {
- toast.error(err.message || 'Failed to stop environment');
- } finally {
- setConfirmDialog(null);
- }
- },
- onCancel: () => setConfirmDialog(null)
- });
- }, [id, toast]);
-
- const handleRollback = useCallback((promotion) => {
- setConfirmDialog({
- title: 'Roll Back Promotion',
- message: `Restore the pre-promotion snapshot for "${promotion.target_site?.name || 'target environment'}"? This overwrites the target environment's current database with the snapshot taken just before promotion #${promotion.id}.`,
- confirmText: 'Roll Back',
- variant: 'danger',
- onConfirm: async () => {
- toast.info('Rolling back promotion...', { duration: 4000 });
- try {
- await wordpressApi.rollbackPromotion(id, promotion.id);
- toast.success('Promotion rolled back');
- loadPipeline();
- } catch (err) {
- toast.error(err.message || 'Rollback failed');
- } finally {
- setConfirmDialog(null);
- }
- },
- onCancel: () => setConfirmDialog(null),
- });
- }, [id, toast]);
-
- const handleRestart = useCallback(async (env) => {
- try {
- await wordpressApi.restartEnvironment(id, env.id);
- toast.success('Environment restarted');
- loadPipeline();
- } catch (err) {
- toast.error(err.message || 'Failed to restart environment');
- }
- }, [id, toast]);
-
- const handleDelete = useCallback((env) => {
- setConfirmDialog({
- title: 'Delete Environment',
- message: `Are you sure you want to delete "${env.name}"? This will remove all containers, files, and database for this environment.`,
- confirmText: 'Delete Environment',
- variant: 'danger',
- onConfirm: async () => {
- try {
- await wordpressApi.deleteProjectEnvironment(id, env.id);
- toast.success('Environment deleted');
- loadPipeline();
- } catch (err) {
- toast.error(err.message || 'Failed to delete environment');
- } finally {
- setConfirmDialog(null);
- }
- },
- onCancel: () => setConfirmDialog(null)
- });
- }, [id, toast]);
-
- const handleLock = useCallback(async (env) => {
- try {
- await wordpressApi.lockEnvironment(id, env.id, {
- reason: 'Manually locked',
- duration_minutes: 60
- });
- toast.success('Environment locked');
- loadPipeline();
- } catch (err) {
- toast.error(err.message || 'Failed to lock environment');
- }
- }, [id, toast]);
-
- const handleUnlock = useCallback(async (env) => {
- try {
- await wordpressApi.unlockEnvironment(id, env.id);
- toast.success('Environment unlocked');
- loadPipeline();
- } catch (err) {
- toast.error(err.message || 'Failed to unlock environment');
- }
- }, [id, toast]);
-
- const handleViewLogs = useCallback((env) => {
- setLogsPanel({ envId: env.id });
- }, []);
-
- const handleCompare = useCallback((envA, envB) => {
- setCompareModal({ envA, envB });
- }, []);
-
- // Phase 7 handlers
- const handleResourceLimits = useCallback((env) => {
- setResourceLimitsModal({ environment: env, currentLimits: env.resource_limits });
- }, []);
-
- const handleApplyResourceLimits = useCallback(async (limits) => {
- const env = resourceLimitsModal.environment;
- try {
- await wordpressApi.updateResourceLimits(id, env.id, limits);
- toast.success('Resource limits updated, containers restarting');
- setResourceLimitsModal(null);
- loadPipeline();
- } catch (err) {
- toast.error(err.message || 'Failed to update resource limits');
- }
- }, [id, resourceLimitsModal, toast]);
-
- const handleBasicAuth = useCallback((env) => {
- setBasicAuthModal({ environment: env });
- }, []);
-
- const handleWpCli = useCallback((env) => {
- setWpCliModal({ environment: env });
- }, []);
-
- const handleAutoSync = useCallback((env) => {
- setAutoSyncModal({ environment: env });
- }, []);
-
- const handleHealthCheck = useCallback(async (env) => {
- try {
- const data = await wordpressApi.getEnvironmentHealth(id, env.id);
- if (data.success) {
- setHealthData(prev => ({ ...prev, [env.id]: data }));
- toast.info(`${env.name}: ${data.overall_status}`);
- }
- } catch (err) {
- toast.error('Health check failed');
- }
- }, [id, toast]);
-
- const handleBulkToggle = useCallback((envId) => {
- setBulkSelected(prev =>
- prev.includes(envId)
- ? prev.filter(id => id !== envId)
- : [...prev, envId]
- );
- }, []);
-
- const handleBulkExecute = useCallback(async (action, envIds) => {
- try {
- await wordpressApi.executeBulkOperation(id, [{ action, env_ids: envIds }]);
- toast.success(`Bulk ${action} completed`);
- setBulkSelected([]);
- loadPipeline();
- } catch (err) {
- toast.error(err.message || `Bulk ${action} failed`);
- }
- }, [id, toast]);
-
- // Load health and disk usage data on pipeline load
- useEffect(() => {
- if (pipeline) {
- loadHealthData();
- loadDiskUsageData();
- }
- }, [pipeline]);
-
- async function loadHealthData() {
- try {
- const data = await wordpressApi.getProjectHealth(id);
- if (data.success) {
- setHealthData(data.environments || {});
- }
- } catch {
- // Health data is optional
- }
- }
-
- async function loadDiskUsageData() {
- try {
- const data = await wordpressApi.getProjectDiskUsage(id);
- if (data.success) {
- setDiskUsageData(data.environments || {});
- }
- } catch {
- // Disk usage data is optional
- }
- }
-
- const handleCreateEnvironment = useCallback(async (data) => {
- toast.info('Creating environment...', { duration: 5000 });
- try {
- await wordpressApi.createProjectEnvironment(id, data);
- setShowCreateEnvModal(false);
- } catch (err) {
- toast.error(err.message || 'Failed to create environment');
- }
- }, [id, toast]);
-
- if (loading) {
- return <EmptyState loading loadingVariant="detail" size="lg" title="Loading project pipeline" />;
- }
-
- if (!pipeline) {
- return (
- <EmptyState
- icon={FolderGit2}
- title="Pipeline not found"
- description="This WordPress pipeline does not exist or has been removed."
- action={<Button onClick={() => navigate('/wordpress/pipelines')}>Back to Pipelines</Button>}
- />
- );
- }
-
- const production = pipeline.production || pipeline;
- const projectName = production.name || 'WordPress Project';
- const projectDomain = production.application?.domains?.[0] || production.url || '';
-
- return (
- <div className="app-detail-page app-detail-page--wide wp-project-page">
- {/* Top Bar */}
- <div className="app-detail-topbar">
- <div className="app-detail-breadcrumbs">
- <Link to="/wordpress/pipelines">Pipelines</Link>
- <span>/</span>
- <span className="current">{projectName}</span>
- </div>
- <div className="app-detail-actions">
- {projectDomain && (
- <Button variant="ghost" asChild>
- <a
- href={projectDomain.startsWith('http') ? projectDomain : `https://${projectDomain}`}
- target="_blank"
- rel="noopener noreferrer"
- >
- <ExternalLink size={16} />
- Visit Site
- </a>
- </Button>
- )}
- <Button
- variant="ghost"
- onClick={() => setShowSanitizationProfiles(true)}
- title="Manage sanitization profiles"
- >
- <Shield size={16} />
- Profiles
- </Button>
- <Button
- onClick={() => setShowCreateEnvModal(true)}
- >
- <Plus size={16} />
- New Environment
- </Button>
- </div>
- </div>
-
- {/* Header */}
- <div className="app-detail-header">
- <div className="app-detail-icon wp-icon">
- <svg viewBox="0 0 24 24" width="28" height="28" fill="currentColor">
- <path d="M12 2C6.486 2 2 6.486 2 12s4.486 10 10 10 10-4.486 10-10S17.514 2 12 2zm0 19.542c-5.261 0-9.542-4.281-9.542-9.542S6.739 2.458 12 2.458 21.542 6.739 21.542 12 17.261 21.542 12 21.542z" />
- </svg>
- </div>
- <div className="app-detail-title-block">
- <h1>
- {projectName}
- <span className={`app-status-badge ${production.status === 'running' ? 'running' : 'stopped'}`}>
- <span className="pulse-dot" />
- {production.status === 'running' ? 'Running' : 'Stopped'}
- </span>
- </h1>
- <div className="app-detail-subtitle">
- {projectDomain && <span className="mono">{projectDomain}</span>}
- {production.wp_version && (
- <>
- <span className="separator">•</span>
- <span>WordPress {production.wp_version}</span>
- </>
- )}
- {pipeline.environments && (
- <>
- <span className="separator">•</span>
- <span>{(pipeline.environments?.length || 0) + 1} environments</span>
- </>
- )}
- </div>
- </div>
- </div>
-
- {/* Tabs */}
- <div className="app-detail-tabs">
- <div
- className={`app-detail-tab ${activeTab === 'pipeline' ? 'active' : ''}`}
- onClick={() => setActiveTab('pipeline')}
- >
- Pipeline
- </div>
- <div
- className={`app-detail-tab ${activeTab === 'activity' ? 'active' : ''}`}
- onClick={() => setActiveTab('activity')}
- >
- Activity
- </div>
- <div
- className={`app-detail-tab ${activeTab === 'health' ? 'active' : ''}`}
- onClick={() => setActiveTab('health')}
- >
- Health
- </div>
- </div>
-
- {/* Tab Content */}
- <div className="app-detail-content">
- {activeTab === 'pipeline' && (
- <div className="pipeline-tab">
- {operationInProgress && (
- <div className="pipeline-operation-banner">
- <Spinner size="sm" />
- <div className="operation-progress-content">
- <span>
- {operationInProgress === 'promotion_started' && 'Promotion in progress...'}
- {operationInProgress === 'sync_started' && 'Sync in progress...'}
- {operationInProgress === 'environment_creating' && 'Creating environment...'}
- </span>
- {operationProgress && (
- <div className="operation-progress">
- <div className="operation-progress-bar">
- <div
- className="operation-progress-fill"
- style={{ width: `${operationProgress.percent || 0}%` }}
- />
- </div>
- <span className="operation-progress-step">
- Step {operationProgress.step}/{operationProgress.total}: {operationProgress.message}
- </span>
- </div>
- )}
- </div>
- </div>
- )}
-
- {bulkSelected.length > 0 && (
- <BulkActionsBar
- selectedIds={bulkSelected}
- environments={[
- ...(pipeline.environments || []),
- pipeline.production
- ].filter(Boolean)}
- prodId={id}
- onClear={() => setBulkSelected([])}
- onExecute={handleBulkExecute}
- api={wordpressApi}
- />
- )}
-
- <PipelineView
- pipeline={pipeline}
- onPromote={handlePromote}
- onSync={handleSync}
- onStart={handleStart}
- onStop={handleStop}
- onRestart={handleRestart}
- onDelete={handleDelete}
- onLock={handleLock}
- onUnlock={handleUnlock}
- onViewLogs={handleViewLogs}
- onCompare={handleCompare}
- onCreateMultidev={() => {
- setShowCreateEnvModal(true);
- }}
- onResourceLimits={handleResourceLimits}
- onBasicAuth={handleBasicAuth}
- onWpCli={handleWpCli}
- onAutoSync={handleAutoSync}
- onHealthCheck={handleHealthCheck}
- operationInProgress={operationInProgress}
- healthData={healthData}
- diskUsageData={diskUsageData}
- bulkSelected={bulkSelected}
- onBulkToggle={handleBulkToggle}
- />
-
- {/* Promotion History (with rollback) */}
- <PromotionHistory projectId={id} onRollback={handleRollback} />
-
- {/* Recent Activity Preview */}
- <div className="pipeline-activity-preview">
- <div className="section-header">
- <h3>Recent Activity</h3>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => setActiveTab('activity')}
- >
- View All
- </Button>
- </div>
- <ActivityFeed projectId={id} limit={5} compact />
- </div>
- </div>
- )}
-
- {activeTab === 'activity' && (
- <div className="activity-tab">
- <div className="section-header">
- <h3>Activity Log</h3>
- <Button variant="ghost" size="sm" onClick={loadPipeline}>
- <RefreshCw size={14} /> Refresh
- </Button>
- </div>
- <ActivityFeed projectId={id} limit={50} />
- </div>
- )}
-
- {activeTab === 'health' && (
- <div className="health-tab">
- <HealthStatusPanel
- projectId={id}
- environments={[
- pipeline.production,
- ...(pipeline.environments || [])
- ].filter(Boolean)}
- api={wordpressApi}
- />
- </div>
- )}
- </div>
-
- {/* Logs Panel */}
- {logsPanel && (
- <div className="pipeline-logs-overlay">
- <ContainerLogs
- projectId={id}
- envId={logsPanel.envId}
- onClose={() => setLogsPanel(null)}
- />
- </div>
- )}
-
- {/* Modals */}
- {promoteModal && (
- <PromoteModal
- sourceEnv={promoteModal.sourceEnv}
- targetEnv={promoteModal.targetEnv}
- onClose={() => setPromoteModal(null)}
- onPromote={handleDoPromote}
- />
- )}
-
- {syncModal && (
- <SyncModal
- environment={syncModal.environment}
- productionName={projectName}
- onClose={() => setSyncModal(null)}
- onSync={handleDoSync}
- />
- )}
-
- {showCreateEnvModal && (
- <CreatePipelineEnvModal
- onClose={() => setShowCreateEnvModal(false)}
- onCreate={handleCreateEnvironment}
- productionDomain={projectDomain}
- existingTypes={(pipeline.environments || []).map(e => e.environment_type)}
- projectId={id}
- />
- )}
-
- {compareModal && (
- <CompareView
- projectId={id}
- envA={compareModal.envA}
- envB={compareModal.envB}
- onClose={() => setCompareModal(null)}
- />
- )}
-
- {showSanitizationProfiles && (
- <SanitizationProfileForm
- onClose={() => setShowSanitizationProfiles(false)}
- onProfilesChange={() => {}}
- />
- )}
-
- {resourceLimitsModal && (
- <ResourceLimitsModal
- environment={resourceLimitsModal.environment}
- currentLimits={resourceLimitsModal.currentLimits}
- onClose={() => setResourceLimitsModal(null)}
- onApply={handleApplyResourceLimits}
- />
- )}
-
- {basicAuthModal && (
- <BasicAuthModal
- environment={basicAuthModal.environment}
- prodId={id}
- onClose={() => setBasicAuthModal(null)}
- api={wordpressApi}
- />
- )}
-
- {wpCliModal && (
- <WpCliTerminal
- environment={wpCliModal.environment}
- prodId={id}
- onClose={() => setWpCliModal(null)}
- api={wordpressApi}
- />
- )}
-
- {autoSyncModal && (
- <AutoSyncScheduleModal
- environment={autoSyncModal.environment}
- prodId={id}
- onClose={() => setAutoSyncModal(null)}
- api={wordpressApi}
- />
- )}
-
- <ConfirmDialog
- isOpen={!!confirmDialog}
- title={confirmDialog?.title}
- message={confirmDialog?.message}
- confirmText={confirmDialog?.confirmText}
- variant={confirmDialog?.variant}
- onConfirm={confirmDialog?.onConfirm}
- onCancel={confirmDialog?.onCancel || (() => setConfirmDialog(null))}
- />
- </div>
- );
-};
-
-// Promotion History (lists past promotions; rollback available for completed promotions with a pre-promotion snapshot)
-const PromotionHistory = ({ projectId, onRollback }) => {
- const [promotions, setPromotions] = useState([]);
- const [loading, setLoading] = useState(true);
-
- const load = useCallback(async () => {
- setLoading(true);
- try {
- const data = await wordpressApi.getPromotionHistory(projectId, { limit: 20 });
- setPromotions(data.promotions || []);
- } catch {
- setPromotions([]);
- } finally {
- setLoading(false);
- }
- }, [projectId]);
-
- useEffect(() => { load(); }, [load]);
-
- if (loading || promotions.length === 0) {
- return null;
- }
-
- return (
- <div className="pipeline-promotion-history">
- <div className="section-header">
- <h3>Promotion History</h3>
- <Button variant="ghost" size="sm" onClick={load}>
- <RefreshCw size={14} /> Refresh
- </Button>
- </div>
- <div className="promotion-history-list">
- {promotions.map(p => {
- const canRollback = p.status === 'completed' && !!p.pre_promotion_snapshot_id;
- return (
- <div key={p.id} className="promotion-history-item">
- <div className="promotion-history-main">
- <span className={`promotion-status promotion-status-${p.status}`}>{p.status}</span>
- <span className="promotion-route">
- {p.source_site?.name || `#${p.source_site_id}`} <ArrowRight size={12} /> {p.target_site?.name || `#${p.target_site_id}`}
- </span>
- <span className="promotion-type">{p.promotion_type}</span>
- {p.created_at && (
- <span className="promotion-date">{new Date(p.created_at).toLocaleString()}</span>
- )}
- </div>
- {canRollback && (
- <Button variant="outline" size="sm" onClick={() => onRollback(p)}>
- <RotateCcw size={14} /> Rollback
- </Button>
- )}
- </div>
- );
- })}
- </div>
- </div>
- );
-};
-
-// Create Environment Modal (Pipeline version)
-const CreatePipelineEnvModal = ({ onClose, onCreate, productionDomain, existingTypes, projectId }) => {
- const [formData, setFormData] = useState({
- type: existingTypes.includes('development') ? 'staging' : 'development',
- name: '',
- branch: '',
- clone_db: true
- });
- const [loading, setLoading] = useState(false);
- const [branches, setBranches] = useState([]);
- const [branchesLoading, setBranchesLoading] = useState(false);
- const [branchSearch, setBranchSearch] = useState('');
- const [useCustomBranch, setUseCustomBranch] = useState(false);
-
- const availableTypes = [
- { value: 'development', label: 'Development', disabled: existingTypes.includes('development') },
- { value: 'staging', label: 'Staging', disabled: existingTypes.includes('staging') },
- { value: 'multidev', label: 'Multidev (branch-based)', disabled: false }
- ];
-
- useEffect(() => {
- if (formData.type === 'multidev' && branches.length === 0 && !branchesLoading) {
- loadBranches();
- }
- }, [formData.type]);
-
- async function loadBranches() {
- setBranchesLoading(true);
- try {
- const data = await wordpressApi.getBranches(projectId);
- setBranches(data.branches || []);
- } catch {
- setBranches([]);
- } finally {
- setBranchesLoading(false);
- }
- }
-
- function handleChange(e) {
- const { name, value, type, checked } = e.target;
- setFormData(prev => ({
- ...prev,
- [name]: type === 'checkbox' ? checked : value
- }));
- }
-
- function selectBranch(branchName) {
- setFormData(prev => ({ ...prev, branch: branchName }));
- setBranchSearch('');
- }
-
- async function handleSubmit(e) {
- e.preventDefault();
- setLoading(true);
- try {
- await onCreate(formData);
- } finally {
- setLoading(false);
- }
- }
-
- const filteredBranches = branches.filter(b => {
- if (!branchSearch) return true;
- return b.name.toLowerCase().includes(branchSearch.toLowerCase());
- });
-
- return (
- <Modal open onClose={onClose} title="Create Environment">
- <form onSubmit={handleSubmit}>
- <div className="form-group">
- <Label>Environment Type</Label>
- <select name="type" value={formData.type} onChange={handleChange}>
- {availableTypes.map(t => (
- <option key={t.value} value={t.value} disabled={t.disabled}>
- {t.label}{t.disabled ? ' (already exists)' : ''}
- </option>
- ))}
- </select>
- </div>
-
- {formData.type === 'multidev' && (
- <div className="form-group">
- <Label>
- <GitBranch size={14} className="mr-1" style={{ verticalAlign: -2 }} />
- Git Branch *
- </Label>
-
- {formData.branch && !useCustomBranch && (
- <div className="branch-selected">
- <GitBranch size={14} />
- <span className="branch-selected-name">{formData.branch}</span>
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={() => setFormData(prev => ({ ...prev, branch: '' }))}
- >
- Change
- </Button>
- </div>
- )}
-
- {!formData.branch && !useCustomBranch && (
- <>
- {branchesLoading ? (
- <div className="branch-picker-loading">
- <Spinner size="sm" />
- <span>Loading branches...</span>
- </div>
- ) : branches.length > 0 ? (
- <div className="branch-picker">
- <div className="branch-picker-search">
- <Search size={14} />
- <Input
- type="text"
- value={branchSearch}
- onChange={e => setBranchSearch(e.target.value)}
- placeholder="Search branches..."
- autoFocus
- />
- </div>
- <div className="branch-picker-list">
- {filteredBranches.map(b => (
- <button
- key={b.name}
- type="button"
- className={`branch-picker-item ${b.has_multidev ? 'has-env' : ''} ${b.is_current ? 'current' : ''}`}
- onClick={() => selectBranch(b.name)}
- disabled={b.has_multidev}
- title={b.has_multidev ? 'Multidev already exists for this branch' : ''}
- >
- <div className="branch-picker-item-main">
- <GitBranch size={12} />
- <span className="branch-name">{b.name}</span>
- {b.is_current && <span className="branch-tag">default</span>}
- {b.has_multidev && <span className="branch-tag env">has env</span>}
- </div>
- {b.message && (
- <div className="branch-picker-item-meta">
- <span className="branch-sha">{b.short_sha}</span>
- <span className="branch-msg">{b.message}</span>
- </div>
- )}
- </button>
- ))}
- {filteredBranches.length === 0 && (
- <div className="branch-picker-empty">
- No branches match &quot;{branchSearch}&quot;
- </div>
- )}
- </div>
- <Button
- type="button"
- variant="ghost"
- size="sm"
- className="branch-picker-custom"
- onClick={() => setUseCustomBranch(true)}
- >
- Enter branch name manually
- </Button>
- </div>
- ) : (
- <div>
- <Input
- type="text"
- name="branch"
- value={formData.branch}
- onChange={handleChange}
- placeholder="feature/my-branch"
- required
- />
- <span className="form-hint">No git repo connected or no branches found. Enter branch name manually.</span>
- </div>
- )}
- </>
- )}
-
- {useCustomBranch && (
- <div>
- <Input
- type="text"
- name="branch"
- value={formData.branch}
- onChange={handleChange}
- placeholder="feature/my-branch"
- required
- autoFocus
- />
- {branches.length > 0 && (
- <Button
- type="button"
- variant="ghost"
- size="sm"
- className="mt-1"
- onClick={() => { setUseCustomBranch(false); setFormData(prev => ({ ...prev, branch: '' })); }}
- >
- Back to branch list
- </Button>
- )}
- </div>
- )}
- </div>
- )}
-
- <div className="form-group">
- <Label>Environment Name</Label>
- <Input
- type="text"
- name="name"
- value={formData.name}
- onChange={handleChange}
- placeholder={formData.type === 'multidev' ? 'Auto-generated from branch' : `${formData.type} environment`}
- />
- <span className="form-hint">Leave empty to auto-generate</span>
- </div>
-
- <div className="form-group">
- <label className="checkbox-label">
- <input
- type="checkbox"
- name="clone_db"
- checked={formData.clone_db}
- onChange={handleChange}
- />
- <span>Clone production database</span>
- </label>
- <span className="form-hint">Creates a copy of the production database for this environment</span>
- </div>
-
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose} disabled={loading}>
- Cancel
- </Button>
- <Button
- type="submit"
- disabled={loading || (formData.type === 'multidev' && !formData.branch)}
- >
- {loading ? <><Spinner size="sm" /> Creating...</> : 'Create Environment'}
- </Button>
- </div>
- </form>
- </Modal>
- );
-};
-
-export default WordPressProject;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/pages/WordPressProjects.jsx b/builtin-extensions/serverkit-wordpress/frontend/pages/WordPressProjects.jsx
deleted file mode 100644
index 9eaf353d..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/pages/WordPressProjects.jsx
+++ /dev/null
@@ -1,181 +0,0 @@
-import { useState, useEffect } from 'react';
-import { useNavigate } from 'react-router-dom';
-import { GitBranch, Layers } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import ResourceListPage from '@/components/layouts/ResourceListPage';
-import { Pill, ServiceTile, EnvTag } from 'serverkit-sdk';
-
-// Environment badges, in promotion order — production is always present, the
-// rest only when the project actually has them.
-const ENV_TAGS = [
- ['staging', 'STG'],
- ['development', 'DEV'],
- ['multidev', 'MD'],
-];
-
-// A WordPress project = one site plus its environment chain. This lists which
-// projects HAVE a pipeline; the run history of what was promoted and when lives
-// in Deploy Activity, which answers a different question.
-const WordPressProjects = () => {
- const [projects, setProjects] = useState([]);
- const [loading, setLoading] = useState(true);
- const [search, setSearch] = useState('');
- const [statusFilter, setStatusFilter] = useState('all');
- const navigate = useNavigate();
- const toast = useToast();
-
- useEffect(() => {
- loadProjects();
- }, []);
-
- async function loadProjects() {
- setLoading(true);
- try {
- const data = await wordpressApi.getPipelines();
- setProjects(data.projects || []);
- } catch (err) {
- console.error('Failed to load projects:', err);
- toast.error('Failed to load WordPress projects');
- } finally {
- setLoading(false);
- }
- }
-
- const runningCount = projects.filter(p => p.status === 'running').length;
-
- const shown = projects.filter(p => {
- if (statusFilter === 'running' && p.status !== 'running') return false;
- if (statusFilter === 'stopped' && p.status === 'running') return false;
- const q = search.trim().toLowerCase();
- if (!q) return true;
- return [p.name, p.url, p.application?.domains?.[0]]
- .some(v => v && String(v).toLowerCase().includes(q));
- });
-
- const domainOf = (p) => p.application?.domains?.[0] || p.url || '';
- const envCount = (p) => (p.environment_count || 0) + 1;
-
- const columns = [
- {
- key: 'name',
- header: 'Project',
- render: (p) => (
- <div className="sk-cell-name">
- <ServiceTile name={p.name} size={30} aria-hidden="true" />
- <span>
- <div>{p.name}</div>
- {domainOf(p) && <div className="sk-cell-sub">{domainOf(p)}</div>}
- </span>
- </div>
- ),
- },
- {
- key: 'environments',
- header: 'Environments',
- render: (p) => (
- <span className="wp-projects-page__envs">
- <span className="wp-projects-page__envcount">
- <Layers size={13} aria-hidden="true" />
- {envCount(p)}
- </span>
- <EnvTag env="production">PROD</EnvTag>
- {ENV_TAGS.map(([type, label]) => (
- (p.environment_types || []).includes(type)
- ? <EnvTag key={type} env={type}>{label}</EnvTag>
- : null
- ))}
- </span>
- ),
- },
- {
- key: 'version',
- header: 'Version',
- cellClassName: 'sk-cell-mono',
- render: (p) => (p.wp_version ? `WP ${p.wp_version}` : '—'),
- },
- {
- key: 'source',
- header: 'Source',
- render: (p) => (
- p.git_repo_url
- ? <span className="wp-projects-page__git"><GitBranch size={12} /> Git connected</span>
- : <span className="wp-list__dash">—</span>
- ),
- },
- {
- key: 'status',
- header: 'Status',
- render: (p) => (
- <Pill kind={p.status === 'running' ? 'green' : 'gray'}>
- {p.status === 'running' ? 'Running' : 'Stopped'}
- </Pill>
- ),
- },
- ];
-
- return (
- <ResourceListPage
- className="wp-projects-page"
- loading={loading}
- loadingTitle="Loading WordPress pipelines"
- totalCount={projects.length}
- items={shown}
- columns={columns}
- keyField="id"
- onRowClick={(p) => navigate(`/wordpress/pipelines/${p.id}`)}
- filters={[
- { value: 'all', label: 'All', count: projects.length },
- { value: 'running', label: 'Running', count: runningCount },
- { value: 'stopped', label: 'Stopped', count: projects.length - runningCount },
- ]}
- activeFilter={statusFilter}
- onFilterChange={setStatusFilter}
- searchTerm={search}
- onSearchChange={setSearch}
- searchPlaceholder="Search pipelines…"
- emptyIcon={Layers}
- emptyTitle="No WordPress pipelines"
- emptyDescription="Sites with environment pipelines appear here. Create a WordPress site with environments enabled to get started."
- filteredEmptyIcon={Layers}
- filteredEmptyTitle="No pipelines found"
- filteredEmptyDescription="Try adjusting your search or filter."
- viewStorageKey="serverkit.wpPipelines.view"
- renderCard={(p) => (
- <>
- <div className="services-card__top">
- <ServiceTile name={p.name} size={40} aria-hidden="true" />
- <div className="services-card__id">
- <div className="services-card__name">{p.name}</div>
- <div className="sk-cell-sub">{p.wp_version ? `WordPress ${p.wp_version}` : 'WordPress'}</div>
- </div>
- <Pill kind={p.status === 'running' ? 'green' : 'gray'}>
- {p.status === 'running' ? 'Running' : 'Stopped'}
- </Pill>
- </div>
-
- <div className="services-card__domain">
- {domainOf(p) || <span className="wp-list__dash">No domain</span>}
- </div>
-
- <div className="services-card__stats">
- <div>
- <span className="l">Environments</span>
- <span className="v">{envCount(p)}</span>
- </div>
- <div>
- <span className="l">Source</span>
- <span className="v">{p.git_repo_url ? 'Git' : 'Local'}</span>
- </div>
- <div>
- <span className="l">Status</span>
- <span className="v">{p.status === 'running' ? 'Running' : 'Stopped'}</span>
- </div>
- </div>
- </>
- )}
- />
- );
-};
-
-export default WordPressProjects;
diff --git a/builtin-extensions/serverkit-wordpress/frontend/styles/wordpress-pipeline.scss b/builtin-extensions/serverkit-wordpress/frontend/styles/wordpress-pipeline.scss
deleted file mode 100644
index 3daeede8..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/styles/wordpress-pipeline.scss
+++ /dev/null
@@ -1,2351 +0,0 @@
-// Compiled through the extension's module graph (imported by index.jsx).
-// The host's design-token partial is imported via a sync-safe relative
-// path — the baked copy lives at frontend/src/plugins/serverkit-wordpress/,
-// so this resolves to frontend/src/styles/_variables.scss.
-@import '../../../styles/variables';
-
-// ============================================
-// WORDPRESS PIPELINE STYLES
-// ============================================
-
-// Page Loading
-.page-loading {
- display: flex;
- align-items: center;
- justify-content: center;
- min-height: 400px;
-}
-
-// Projects Page
-.wp-projects-page {
- padding: $space-4;
-
- .empty-state-large {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: 60px $space-6;
- background: $bg-card;
- border-radius: $radius-xl;
- text-align: center;
-
- .empty-icon {
- color: $text-tertiary;
- margin-bottom: $space-4;
- }
-
- h2 {
- font-size: $font-size-lg;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- margin: 0 0 $space-2;
- }
-
- p {
- font-size: $font-size-sm;
- color: $text-secondary;
- max-width: 460px;
- margin: 0;
- }
- }
-}
-
-
-// ============================================
-// PIPELINE DASHBOARD
-// ============================================
-
-.wp-project-page {
- .wp-icon {
- background: $color-wordpress !important;
- }
-}
-
-// Pipeline Tab
-.pipeline-tab {
- padding: $space-4 0;
-}
-
-.pipeline-operation-banner {
- display: flex;
- align-items: center;
- gap: $space-3;
- padding: $space-3 $space-4;
- background: fade($info-raw, 10%);
- border: 1px solid fade($info-raw, 25%);
- border-radius: $radius-md;
- margin-bottom: $space-4;
- font-size: $font-size-sm;
- color: $color-info;
-}
-
-// Pipeline View
-.pipeline-view {
- margin-bottom: $space-6;
-}
-
-.pipeline-row {
- display: flex;
- align-items: stretch;
- gap: 0;
- overflow-x: auto;
- padding-bottom: $space-2;
-}
-
-.pipeline-card {
- flex: 1;
- min-width: 220px;
- max-width: 320px;
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-lg;
- display: flex;
- flex-direction: column;
- position: relative;
-
- &.production {
- border-color: fade($danger-raw, 45%);
- }
-
- &.locked {
- opacity: 0.85;
- }
-
- &.empty {
- border-style: dashed;
- border-color: $border-subtle;
- display: flex;
- align-items: center;
- justify-content: center;
- min-height: 180px;
- }
-}
-
-.pipeline-empty-content {
- text-align: center;
- color: $text-tertiary;
-
- p {
- margin: $space-2 0 0;
- font-size: $font-size-sm;
- }
-}
-
-.pipeline-card-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: $space-3 $space-4;
- border-bottom: 1px solid $border-subtle;
-}
-
-.env-status-badge-group {
- display: flex;
- align-items: center;
- gap: $space-2;
-}
-
-.env-locked-badge {
- display: flex;
- align-items: center;
- padding: 2px 4px;
- background: fade($warning-raw, 15%);
- color: $color-warning;
- border-radius: $radius-sm;
-}
-
-.pipeline-card-menu-wrapper {
- position: relative;
-}
-
-.pipeline-card-menu-btn {
- padding: 4px !important;
-}
-
-.pipeline-card-menu {
- position: absolute;
- right: 0;
- top: 100%;
- background: $bg-elevated;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
- z-index: 100;
- min-width: 140px;
- padding: $space-1;
-
- button {
- display: flex;
- align-items: center;
- gap: $space-2;
- width: 100%;
- padding: $space-2 $space-3;
- border: none;
- background: none;
- color: $text-secondary;
- font-size: $font-size-sm;
- cursor: pointer;
- border-radius: $radius-sm;
- text-align: left;
-
- &:hover {
- background: $bg-hover;
- color: $text-primary;
- }
-
- &.danger {
- color: $color-danger;
-
- &:hover {
- background: fade($danger-raw, 10%);
- }
- }
- }
-}
-
-.pipeline-card-body {
- flex: 1;
- padding: $space-4;
-}
-
-.pipeline-card-name {
- font-size: $font-size-base;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- margin: 0 0 $space-2;
-}
-
-.pipeline-card-domain {
- display: block;
- font-size: $font-size-xs;
- font-family: $font-family-mono;
- color: $color-primary;
- margin-bottom: $space-2;
- text-decoration: none;
-
- &:hover {
- text-decoration: underline;
- }
-}
-
-.pipeline-card-meta {
- display: flex;
- flex-wrap: wrap;
- gap: $space-2;
-}
-
-.pipeline-meta-item {
- font-size: $font-size-xs;
- color: $text-tertiary;
-}
-
-.pipeline-card-footer {
- display: flex;
- gap: $space-2;
- padding: $space-2 $space-3;
- border-top: 1px solid $border-subtle;
- background: $bg-tertiary;
- border-radius: 0 0 $radius-lg $radius-lg;
-}
-
-.pipeline-card-lock-banner {
- display: flex;
- align-items: center;
- gap: $space-1;
- padding: $space-2 $space-3;
- background: fade($warning-raw, 10%);
- font-size: $font-size-xs;
- color: $color-warning;
- border-radius: 0 0 $radius-lg $radius-lg;
-}
-
-// Pipeline Arrows
-.pipeline-arrow {
- display: flex;
- align-items: center;
- justify-content: center;
- min-width: 80px;
- padding: 0 $space-2;
-
- &.disabled {
- opacity: 0.3;
- pointer-events: none;
- }
-}
-
-.pipeline-arrow-btn {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 4px;
- padding: $space-2 $space-3;
- border: 1px solid $border-subtle;
- background: $bg-card;
- border-radius: $radius-md;
- cursor: pointer;
- color: $text-secondary;
- transition: all 0.15s ease;
-
- &:hover:not(:disabled) {
- border-color: $color-primary;
- color: $color-primary;
- background: fade($accent-primary-raw, 5%);
- }
-
- &:disabled {
- cursor: not-allowed;
- opacity: 0.4;
- }
-}
-
-.pipeline-arrow-label {
- font-size: 10px;
- font-weight: $font-weight-medium;
- text-transform: uppercase;
- letter-spacing: 0.5px;
-}
-
-// Pipeline Sync Row
-.pipeline-sync-row {
- display: flex;
- gap: 0;
- margin-top: $space-2;
-
- .pipeline-sync-action {
- flex: 1;
- min-width: 220px;
- max-width: 320px;
- display: flex;
- justify-content: center;
- }
-}
-
-// Multidev Section
-.pipeline-multidev-section {
- margin-top: $space-6;
- padding-top: $space-4;
- border-top: 1px solid $border-subtle;
-}
-
-.pipeline-section-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- margin-bottom: $space-3;
-}
-
-.pipeline-section-title {
- display: flex;
- align-items: center;
- gap: $space-2;
- font-size: $font-size-sm;
- font-weight: $font-weight-semibold;
- color: $text-secondary;
- text-transform: uppercase;
- letter-spacing: 0.5px;
- margin: 0;
-}
-
-.pipeline-section-count {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- min-width: 20px;
- height: 20px;
- padding: 0 6px;
- background: fade($accent-primary-raw, 12%);
- color: $color-primary;
- border-radius: 10px;
- font-size: 11px;
- font-weight: $font-weight-bold;
- text-transform: none;
- letter-spacing: 0;
-}
-
-.pipeline-multidev-grid {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
- gap: $space-3;
-}
-
-.pipeline-multidev-empty {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: $space-8 $space-4;
- background: $bg-card;
- border: 1px dashed $border-subtle;
- border-radius: $radius-lg;
- text-align: center;
-
- > svg {
- color: $text-tertiary;
- margin-bottom: $space-3;
- }
-
- p {
- font-size: $font-size-base;
- font-weight: $font-weight-medium;
- color: $text-secondary;
- margin: 0 0 $space-1;
- }
-
- > span {
- font-size: $font-size-sm;
- color: $text-tertiary;
- margin-bottom: $space-4;
- }
-}
-
-.multidev-card {
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-lg;
- transition: border-color 0.15s ease;
-
- &:hover {
- border-color: $border-hover;
- }
-
- &.locked {
- opacity: 0.85;
- }
-}
-
-.multidev-card-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: $space-3 $space-4;
- border-bottom: 1px solid $border-subtle;
-}
-
-.multidev-card-header-left {
- display: flex;
- align-items: center;
- gap: $space-2;
-}
-
-.multidev-lock-icon {
- color: $color-warning;
-}
-
-.multidev-card-menu-wrapper {
- position: relative;
-}
-
-.multidev-card-body {
- padding: $space-3 $space-4;
-}
-
-.multidev-card-name {
- font-size: $font-size-sm;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- margin: 0 0 $space-2;
-}
-
-.multidev-branch {
- display: inline-flex;
- align-items: center;
- gap: 4px;
- font-size: $font-size-xs;
- font-family: $font-family-mono;
- color: $text-tertiary;
- background: $bg-tertiary;
- padding: 2px 8px;
- border-radius: $radius-sm;
- margin-bottom: $space-2;
-}
-
-.multidev-domain {
- display: block;
- font-size: $font-size-xs;
- font-family: $font-family-mono;
- color: $color-primary;
- text-decoration: none;
- margin-bottom: $space-2;
-
- &:hover {
- text-decoration: underline;
- }
-}
-
-.multidev-card-meta {
- display: flex;
- flex-wrap: wrap;
- gap: $space-2;
-}
-
-.multidev-meta-item {
- font-size: $font-size-xs;
- color: $text-tertiary;
-}
-
-.multidev-card-footer {
- display: flex;
- gap: $space-2;
- padding: $space-2 $space-3;
- border-top: 1px solid $border-subtle;
- background: $bg-tertiary;
- border-radius: 0 0 $radius-lg $radius-lg;
-}
-
-.wp-env-badge.env-multidev {
- background: fade($accent-primary-raw, 12%);
- color: $color-primary;
-}
-
-// ============================================
-// BRANCH PICKER
-// ============================================
-
-.branch-selected {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-3;
- background: fade($accent-primary-raw, 8%);
- border: 1px solid fade($accent-primary-raw, 25%);
- border-radius: $radius-md;
-
- svg {
- color: $color-primary;
- flex-shrink: 0;
- }
-}
-
-.branch-selected-name {
- flex: 1;
- font-family: $font-family-mono;
- font-size: $font-size-sm;
- font-weight: $font-weight-medium;
- color: $text-primary;
-}
-
-.branch-picker-loading {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-4;
- justify-content: center;
- color: $text-tertiary;
- font-size: $font-size-sm;
-}
-
-.branch-picker {
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- overflow: hidden;
-}
-
-.branch-picker-search {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-2 $space-3;
- border-bottom: 1px solid $border-subtle;
- background: $bg-tertiary;
-
- svg {
- color: $text-tertiary;
- flex-shrink: 0;
- }
-
- input {
- flex: 1;
- border: none;
- background: none;
- font-size: $font-size-sm;
- color: $text-primary;
- outline: none;
- padding: 0;
-
- &::placeholder {
- color: $text-tertiary;
- }
- }
-}
-
-.branch-picker-list {
- max-height: 240px;
- overflow-y: auto;
-}
-
-.branch-picker-item {
- display: flex;
- flex-direction: column;
- gap: 2px;
- width: 100%;
- padding: $space-2 $space-3;
- border: none;
- border-bottom: 1px solid $border-subtle;
- background: $bg-card;
- cursor: pointer;
- text-align: left;
- transition: background 0.1s ease;
-
- &:last-child {
- border-bottom: none;
- }
-
- &:hover:not(:disabled) {
- background: $bg-hover;
- }
-
- &:disabled {
- opacity: 0.5;
- cursor: not-allowed;
- }
-
- &.has-env {
- background: fade($text-tertiary-raw, 3%);
- }
-}
-
-.branch-picker-item-main {
- display: flex;
- align-items: center;
- gap: $space-2;
- font-size: $font-size-sm;
- color: $text-primary;
-
- svg {
- color: $text-tertiary;
- flex-shrink: 0;
- }
-}
-
-.branch-name {
- font-family: $font-family-mono;
- font-weight: $font-weight-medium;
-}
-
-.branch-tag {
- font-size: 10px;
- font-weight: $font-weight-medium;
- padding: 1px 6px;
- border-radius: $radius-sm;
- background: fade($text-tertiary-raw, 10%);
- color: $text-tertiary;
-
- &.env {
- background: fade($accent-primary-raw, 10%);
- color: $color-primary;
- }
-}
-
-.branch-picker-item-meta {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding-left: 20px;
-
- .branch-sha {
- font-family: $font-family-mono;
- font-size: 11px;
- color: $text-tertiary;
- }
-
- .branch-msg {
- font-size: 11px;
- color: $text-tertiary;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
-}
-
-.branch-picker-empty {
- padding: $space-4;
- text-align: center;
- font-size: $font-size-sm;
- color: $text-tertiary;
-}
-
-.branch-picker-custom {
- width: 100%;
- border-top: 1px solid $border-subtle;
- border-radius: 0 0 $radius-md $radius-md;
- justify-content: center;
- color: $color-primary !important;
-}
-
-// ============================================
-// PROMOTE / SYNC MODALS
-// ============================================
-
-.promote-direction,
-.sync-direction {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: $space-3;
- padding: $space-4;
- background: $bg-tertiary;
- border-radius: $radius-md;
- margin-bottom: $space-4;
-}
-
-.promote-env-pill {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 4px;
- padding: $space-3 $space-4;
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- min-width: 120px;
-
- .promote-env-type {
- font-size: $font-size-xs;
- font-weight: $font-weight-bold;
- text-transform: uppercase;
- letter-spacing: 0.5px;
- }
-
- .promote-env-name {
- font-size: $font-size-sm;
- color: $text-secondary;
- max-width: 150px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
-
- &.production .promote-env-type { color: $color-danger; }
- &.staging .promote-env-type { color: $color-warning; }
- &.development .promote-env-type { color: $color-info; }
- &.multidev .promote-env-type { color: $color-primary; }
-}
-
-.promote-arrow {
- color: $text-tertiary;
- flex-shrink: 0;
-}
-
-.promote-warning,
-.sync-warning {
- display: flex;
- align-items: flex-start;
- gap: $space-3;
- padding: $space-3 $space-4;
- background: fade($warning-raw, 8%);
- border: 1px solid fade($warning-raw, 20%);
- border-radius: $radius-md;
- margin-top: $space-4;
- font-size: $font-size-sm;
- color: $text-secondary;
-
- > svg {
- color: $color-warning;
- flex-shrink: 0;
- margin-top: 2px;
- }
-
- strong {
- color: $text-primary;
- }
-
- p {
- margin: $space-1 0 0;
- }
-}
-
-// Radio Group for promotion/sync type selection
-.radio-group {
- display: flex;
- flex-direction: column;
- gap: $space-2;
-}
-
-.radio-label {
- display: flex;
- align-items: flex-start;
- gap: $space-3;
- padding: $space-3;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- cursor: pointer;
- transition: all 0.15s ease;
-
- &:hover {
- border-color: $border-hover;
- background: $bg-hover;
- }
-
- &:has(input:checked) {
- border-color: $color-primary;
- background: fade($accent-primary-raw, 5%);
- }
-
- input[type="radio"] {
- margin-top: 4px;
- accent-color: var(--accent-primary, #3b82f6);
- }
-}
-
-.radio-content {
- display: flex;
- flex-direction: column;
- gap: 2px;
-
- strong {
- font-size: $font-size-sm;
- color: $text-primary;
- }
-
- span {
- font-size: $font-size-xs;
- color: $text-tertiary;
- }
-}
-
-.checkbox-group {
- display: flex;
- flex-direction: column;
- gap: $space-2;
-}
-
-// ============================================
-// ACTIVITY FEED
-// ============================================
-
-.activity-feed {
- display: flex;
- flex-direction: column;
- gap: 1px;
- background: $border-subtle;
- border: 1px solid $border-subtle;
- border-radius: $radius-lg;
- overflow: hidden;
-
- &.compact .activity-item {
- padding: $space-2 $space-3;
- }
-}
-
-.activity-feed-empty {
- padding: $space-6;
- text-align: center;
- color: $text-tertiary;
- font-size: $font-size-sm;
-}
-
-.activity-item {
- display: flex;
- align-items: center;
- gap: $space-3;
- padding: $space-3 $space-4;
- background: $bg-card;
-}
-
-.activity-item-skeleton {
- display: flex;
- align-items: center;
- gap: $space-3;
- padding: $space-3 $space-4;
-}
-
-.activity-icon {
- display: flex;
- align-items: center;
- justify-content: center;
- width: 28px;
- height: 28px;
- border-radius: 50%;
- flex-shrink: 0;
-
- &.success {
- background: fade($success-raw, 12%);
- color: $color-success;
- }
- &.danger {
- background: fade($danger-raw, 12%);
- color: $color-danger;
- }
- &.warning {
- background: fade($warning-raw, 12%);
- color: $color-warning;
- }
- &.info {
- background: fade($info-raw, 12%);
- color: $color-info;
- }
- &.primary {
- background: fade($accent-primary-raw, 12%);
- color: $color-primary;
- }
- &.default {
- background: fade($text-tertiary-raw, 12%);
- color: $text-tertiary;
- }
-}
-
-.activity-content {
- flex: 1;
- min-width: 0;
-}
-
-.activity-description {
- font-size: $font-size-sm;
- color: $text-primary;
- display: block;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.activity-error {
- font-size: $font-size-xs;
- color: $color-danger;
- display: block;
- margin-top: 2px;
-}
-
-.activity-meta {
- display: flex;
- align-items: center;
- gap: $space-2;
- flex-shrink: 0;
-}
-
-.activity-time {
- font-size: $font-size-xs;
- color: $text-tertiary;
- white-space: nowrap;
-}
-
-.activity-status-badge {
- font-size: 10px;
- font-weight: $font-weight-medium;
- padding: 2px 6px;
- border-radius: $radius-sm;
-
- &.failed {
- background: fade($danger-raw, 12%);
- color: $color-danger;
- }
-
- &.running {
- background: fade($info-raw, 12%);
- color: $color-info;
- }
-}
-
-.activity-load-more {
- background: $bg-card;
- padding: $space-3;
- text-align: center;
- width: 100%;
- justify-content: center;
-}
-
-// Pipeline Activity Preview
-.pipeline-activity-preview {
- margin-top: $space-6;
-}
-
-// ============================================
-// CONTAINER LOGS
-// ============================================
-
-.pipeline-logs-overlay {
- position: fixed;
- bottom: 0;
- right: 0;
- width: 600px;
- max-width: 100%;
- height: 400px;
- z-index: 200;
- // Up-facing variant of --shadow-lg (token shadows cast downward).
- box-shadow: 0 -16px 48px -12px rgba(0, 0, 0, 0.5);
- border-radius: var(--radius-lg) var(--radius-lg) 0 0;
- overflow: hidden;
-
- @media (max-width: $breakpoint-md) {
- width: 100%;
- }
-}
-
-.container-logs-panel {
- display: flex;
- flex-direction: column;
- height: 100%;
- background: var(--surface);
- border: 1px solid var(--border-strong);
- border-radius: var(--radius-lg) var(--radius-lg) 0 0;
-}
-
-.container-logs-header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: $space-3;
- padding: $space-2 $space-3;
- border-bottom: 1px solid var(--border-soft);
- background: var(--surface);
-}
-
-.container-logs-title {
- display: flex;
- align-items: center;
- gap: $space-3;
- min-width: 0;
- color: var(--text);
-}
-
-.container-logs-ico {
- width: 28px;
- height: 28px;
- border-radius: 8px;
- display: grid;
- place-items: center;
- background: var(--cyan-bg);
- color: var(--cyan);
- flex-shrink: 0;
-}
-
-.container-logs-titles {
- display: flex;
- flex-direction: column;
- min-width: 0;
- font-size: 13px;
- font-weight: $font-weight-semibold;
-}
-
-.container-logs-sub {
- font-family: var(--mono);
- font-size: 10.5px;
- font-weight: $font-weight-normal;
- color: var(--text-faint);
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.container-logs-controls {
- display: flex;
- align-items: center;
- gap: $space-2;
- flex-shrink: 0;
-}
-
-.logs-service-select,
-.logs-lines-select {
- padding: 4px $space-2;
- font-family: var(--mono);
- font-size: 11.5px;
- border: 1px solid var(--border);
- border-radius: $radius-md;
- background: var(--surface-2);
- color: var(--text-dim);
- transition: border-color $transition-fast, color $transition-fast;
-
- &:hover {
- border-color: var(--border-strong);
- color: var(--text);
- }
-}
-
-.container-logs-body {
- flex: 1;
- overflow-y: auto;
- background: var(--bg-code);
- scrollbar-width: thin;
-}
-
-.logs-loading,
-.logs-empty {
- padding: $space-6;
- text-align: center;
- color: var(--text-faint);
- font-family: var(--mono);
- font-size: $font-size-sm;
-}
-
-.logs-content {
- margin: 0;
- padding: $space-3 $space-4;
- font-family: var(--mono);
- font-size: 12px;
- line-height: 1.7;
- color: var(--text-dim);
- white-space: pre-wrap;
- word-break: break-all;
-}
-
-.log-line {
- padding: 1px 0;
-
- &:hover {
- background: fade($text-primary-raw, 5%);
- }
-}
-
-// ============================================
-// COMPARE VIEW
-// ============================================
-
-.compare-header {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: $space-3;
- padding: $space-4;
- background: $bg-tertiary;
- margin: 0 -$space-5;
- padding: $space-4 $space-5;
-}
-
-.compare-env-pill {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 4px;
- padding: $space-3 $space-4;
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- min-width: 120px;
-
- .compare-env-type {
- font-size: $font-size-xs;
- font-weight: $font-weight-bold;
- text-transform: uppercase;
- letter-spacing: 0.5px;
- }
-
- .compare-env-name {
- font-size: $font-size-sm;
- color: $text-secondary;
- max-width: 150px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
-
- &.production .compare-env-type { color: $color-danger; }
- &.staging .compare-env-type { color: $color-warning; }
- &.development .compare-env-type { color: $color-info; }
- &.multidev .compare-env-type { color: $color-primary; }
-}
-
-.compare-vs-icon {
- color: $text-tertiary;
- flex-shrink: 0;
-}
-
-.compare-body {
- padding: $space-4 0;
- max-height: 60vh;
- overflow-y: auto;
-}
-
-.compare-loading {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: $space-3;
- padding: $space-8;
- color: $text-tertiary;
- font-size: $font-size-sm;
-}
-
-.compare-error {
- text-align: center;
- padding: $space-6;
-
- p {
- color: $color-danger;
- margin: 0 0 $space-3;
- }
-}
-
-.compare-section {
- margin-bottom: $space-4;
-
- &:last-child {
- margin-bottom: 0;
- }
-}
-
-.compare-section-header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: $space-2 $space-3;
- background: $bg-tertiary;
- border-radius: $radius-md;
- margin-bottom: $space-2;
-
- h4 {
- margin: 0;
- font-size: $font-size-sm;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- }
-}
-
-.compare-section-summary {
- font-size: $font-size-xs;
- color: $text-tertiary;
-}
-
-.compare-table {
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- overflow: hidden;
-}
-
-.compare-row {
- display: grid;
- grid-template-columns: 1fr 1fr 1fr;
- gap: $space-2;
- padding: $space-2 $space-3;
- border-bottom: 1px solid $border-subtle;
- font-size: $font-size-sm;
- align-items: center;
-
- &:last-child {
- border-bottom: none;
- }
-
- &.match {
- .compare-row-icon { color: $color-success; }
- }
-
- &.different {
- background: fade($danger-raw, 5%);
- .compare-row-icon { color: $color-danger; }
- .compare-row-value-a,
- .compare-row-value-b {
- font-weight: $font-weight-medium;
- }
- }
-
- &.only-a {
- .compare-row-icon { color: $color-warning; }
- .compare-row-value-b { opacity: 0.4; }
- }
-
- &.only-b {
- .compare-row-icon { color: $color-warning; }
- .compare-row-value-a { opacity: 0.4; }
- }
-}
-
-.compare-row-label {
- display: flex;
- align-items: center;
- gap: $space-2;
- font-weight: $font-weight-medium;
- color: $text-primary;
-}
-
-.compare-row-icon {
- flex-shrink: 0;
-}
-
-.compare-row-value-a,
-.compare-row-value-b {
- font-size: $font-size-xs;
- color: $text-secondary;
- font-family: $font-family-mono;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.compare-na {
- color: $text-tertiary;
- font-style: italic;
-}
-
-.compare-empty-row {
- padding: $space-4;
- text-align: center;
- font-size: $font-size-sm;
- color: $text-tertiary;
-}
-
-// Pipeline Compare Row
-.pipeline-compare-row {
- display: flex;
- gap: $space-3;
- justify-content: center;
- margin-top: $space-2;
- padding: $space-2 0;
-}
-
-.pipeline-compare-btn {
- color: $text-tertiary !important;
- font-size: $font-size-xs !important;
-
- &:hover {
- color: $color-primary !important;
- }
-}
-
-// ============================================
-// SANITIZATION PROFILES
-// ============================================
-
-.sanitization-profiles-body {
- padding: $space-4 0;
- max-height: 60vh;
- overflow-y: auto;
-}
-
-.sanitization-loading {
- display: flex;
- align-items: center;
- justify-content: center;
- padding: $space-8;
-}
-
-.sanitization-profile-list {
- display: flex;
- flex-direction: column;
- gap: $space-3;
- margin-bottom: $space-4;
-}
-
-.sanitization-profile-card {
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- padding: $space-3 $space-4;
- transition: border-color 0.15s ease;
-
- &:hover {
- border-color: $border-hover;
- }
-
- &.default {
- border-color: fade($accent-primary-raw, 45%);
- }
-}
-
-.sanitization-profile-card-header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- margin-bottom: $space-2;
-}
-
-.sanitization-profile-card-title {
- display: flex;
- align-items: center;
- gap: $space-2;
-
- h5 {
- margin: 0;
- font-size: $font-size-sm;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- }
-}
-
-.sanitization-tag {
- font-size: 10px;
- font-weight: $font-weight-medium;
- padding: 1px 6px;
- border-radius: $radius-sm;
-
- &.builtin {
- background: fade($text-tertiary-raw, 10%);
- color: $text-tertiary;
- }
-
- &.default {
- background: fade($accent-primary-raw, 12%);
- color: $color-primary;
- }
-}
-
-.sanitization-profile-card-actions {
- display: flex;
- gap: $space-1;
-}
-
-.sanitization-profile-desc {
- font-size: $font-size-xs;
- color: $text-secondary;
- margin: 0 0 $space-2;
-}
-
-.sanitization-rule-tags {
- display: flex;
- flex-wrap: wrap;
- gap: 4px;
-}
-
-.sanitization-rule-tag {
- font-size: 10px;
- padding: 2px 8px;
- background: $bg-tertiary;
- border-radius: $radius-sm;
- color: $text-tertiary;
-
- &.empty {
- font-style: italic;
- }
-}
-
-.sanitization-add-btn {
- width: 100%;
- justify-content: center;
-}
-
-// Profile Editor
-.sanitization-editor {
- background: $bg-tertiary;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- padding: $space-4;
- margin-top: $space-3;
-
- h4 {
- margin: 0 0 $space-3;
- font-size: $font-size-sm;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- }
-
- .form-group {
- margin-bottom: $space-3;
-
- &:last-of-type {
- margin-bottom: $space-4;
- }
- }
-}
-
-.sanitization-editor-actions {
- display: flex;
- justify-content: flex-end;
- gap: $space-2;
- padding-top: $space-3;
- border-top: 1px solid $border-subtle;
-}
-
-// ============================================
-// RESPONSIVE
-// ============================================
-
-// ============================================
-// PIPELINE CARD ADDITIONS (Phase 7)
-// ============================================
-
-.pipeline-card-checkbox {
- margin-right: $space-1;
- accent-color: var(--accent-primary, #3b82f6);
-}
-
-.pipeline-card-menu-divider {
- height: 1px;
- background: $border-subtle;
- margin: $space-1 0;
-}
-
-// ============================================
-// RESOURCE LIMITS MODAL
-// ============================================
-
-.resource-limits-modal {
- max-width: 480px;
-}
-
-.resource-limits-env-name {
- font-size: $font-size-sm;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- padding-bottom: $space-3;
- border-bottom: 1px solid $border-subtle;
- margin-bottom: $space-3;
-}
-
-.resource-limits-presets {
- display: flex;
- align-items: center;
- gap: $space-2;
- margin-bottom: $space-4;
-}
-
-.resource-limits-presets-label {
- font-size: $font-size-sm;
- color: $text-secondary;
-}
-
-.resource-preset-btn {
- text-transform: capitalize;
-}
-
-.resource-limits-section {
- margin-bottom: $space-4;
-
- h4 {
- display: flex;
- align-items: center;
- gap: $space-2;
- font-size: $font-size-sm;
- font-weight: $font-weight-semibold;
- color: $text-secondary;
- margin: 0 0 $space-3;
- }
-}
-
-.resource-limits-row {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: $space-2 0;
-
- label {
- font-size: $font-size-sm;
- color: $text-primary;
- }
-
- select {
- width: 120px;
- padding: $space-1 $space-2;
- font-size: $font-size-sm;
- border: 1px solid $border-subtle;
- border-radius: $radius-sm;
- background: $bg-card;
- color: $text-primary;
- }
-}
-
-.resource-limits-warning {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-3;
- background: fade($warning-raw, 8%);
- border: 1px solid fade($warning-raw, 20%);
- border-radius: $radius-md;
- margin-top: $space-3;
- margin-bottom: $space-3;
- font-size: $font-size-xs;
- color: $color-warning;
-}
-
-// ============================================
-// BASIC AUTH MODAL
-// ============================================
-
-.basic-auth-modal {
- max-width: 460px;
-}
-
-.basic-auth-body {
- padding: $space-4 0;
-}
-
-.basic-auth-env-name {
- font-size: $font-size-sm;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- padding-bottom: $space-3;
- border-bottom: 1px solid $border-subtle;
- margin-bottom: $space-3;
-}
-
-.basic-auth-loading {
- display: flex;
- align-items: center;
- gap: $space-2;
- justify-content: center;
- padding: $space-4;
- color: $text-tertiary;
- font-size: $font-size-sm;
-}
-
-.basic-auth-toggle {
- margin-bottom: $space-4;
-}
-
-.basic-auth-toggle-label {
- display: flex;
- align-items: center;
- justify-content: space-between;
- cursor: pointer;
-
- span {
- font-size: $font-size-sm;
- font-weight: $font-weight-medium;
- color: $text-primary;
- }
-}
-
-.basic-auth-description {
- font-size: $font-size-xs;
- color: $text-tertiary;
- margin: $space-1 0 0;
-}
-
-.toggle-switch {
- position: relative;
- width: 44px;
- height: 24px;
- border: none;
- border-radius: 12px;
- background: $bg-tertiary;
- cursor: pointer;
- transition: background 0.2s ease;
- padding: 0;
-
- &.active {
- background: var(--accent-primary, #3b82f6);
- }
-}
-
-.toggle-switch-slider {
- position: absolute;
- top: 2px;
- left: 2px;
- width: 20px;
- height: 20px;
- border-radius: 50%;
- background: white;
- transition: transform 0.2s ease;
-
- .toggle-switch.active & {
- transform: translateX(20px);
- }
-}
-
-.basic-auth-current {
- padding: $space-3;
- background: $bg-tertiary;
- border-radius: $radius-md;
-}
-
-.basic-auth-credentials {
- display: flex;
- flex-direction: column;
- gap: $space-3;
-}
-
-.basic-auth-credential-warning {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-2 $space-3;
- background: fade($warning-raw, 10%);
- border: 1px solid fade($warning-raw, 20%);
- border-radius: $radius-md;
- font-size: $font-size-xs;
- color: $color-warning;
-}
-
-.basic-auth-field {
- display: flex;
- flex-direction: column;
- gap: $space-1;
-
- label {
- font-size: $font-size-xs;
- font-weight: $font-weight-medium;
- color: $text-tertiary;
- text-transform: uppercase;
- letter-spacing: 0.5px;
- }
-}
-
-.basic-auth-value {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-2 $space-3;
- background: $bg-tertiary;
- border-radius: $radius-sm;
-
- code {
- flex: 1;
- font-family: $font-family-mono;
- font-size: $font-size-sm;
- color: $text-primary;
- }
-}
-
-.basic-auth-hint {
- font-size: $font-size-xs;
- color: $text-tertiary;
- margin-top: $space-2;
-}
-
-// ============================================
-// WP-CLI TERMINAL
-// ============================================
-
-.wpcli-terminal-modal {
- max-width: 700px;
- height: 560px;
- display: flex;
- flex-direction: column;
-}
-
-.wpcli-quick-actions {
- display: flex;
- flex-wrap: wrap;
- gap: $space-1;
- padding: $space-2 $space-4;
- border-bottom: 1px solid $border-subtle;
- background: $bg-tertiary;
-}
-
-.wpcli-history {
- border-bottom: 1px solid $border-subtle;
- max-height: 200px;
- overflow-y: auto;
-}
-
-.wpcli-history-item {
- display: block;
- width: 100%;
- padding: $space-2 $space-4;
- border: none;
- background: none;
- text-align: left;
- cursor: pointer;
- border-bottom: 1px solid $border-subtle;
-
- &:last-child {
- border-bottom: none;
- }
-
- &:hover {
- background: $bg-hover;
- }
-
- code {
- font-family: $font-family-mono;
- font-size: $font-size-xs;
- color: $text-primary;
- }
-}
-
-.wpcli-output {
- flex: 1;
- overflow-y: auto;
- padding: $space-3;
- background: $bg-body;
- font-family: $font-family-mono;
- font-size: 12px;
- line-height: 1.6;
-}
-
-.wpcli-output-empty {
- color: $text-tertiary;
- text-align: center;
- padding: $space-6;
- font-size: $font-size-sm;
-}
-
-.wpcli-output-command {
- display: flex;
- gap: $space-2;
- color: $color-primary;
- margin-top: $space-2;
-
- &:first-child {
- margin-top: 0;
- }
-}
-
-.wpcli-output-text {
- margin: 0;
- color: $text-secondary;
- white-space: pre-wrap;
- word-break: break-all;
-}
-
-.wpcli-output-error {
- margin: 0;
- color: $color-danger;
- white-space: pre-wrap;
- word-break: break-all;
-}
-
-.wpcli-prompt {
- color: $color-success;
- font-weight: $font-weight-bold;
- user-select: none;
-}
-
-.wpcli-executing {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-2 0;
- color: $text-tertiary;
- font-size: $font-size-xs;
-}
-
-.wpcli-input-row {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-2 $space-3;
- border-top: 1px solid $border-subtle;
- background: $bg-elevated;
-}
-
-.wpcli-input {
- flex: 1;
- border: none;
- background: none;
- font-family: $font-family-mono;
- font-size: $font-size-sm;
- color: $text-primary;
- outline: none;
- padding: $space-1 0;
-
- &::placeholder {
- color: $text-tertiary;
- }
-}
-
-// ============================================
-// HEALTH STATUS PANEL
-// ============================================
-
-.health-status-panel {
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-lg;
- padding: $space-4;
-}
-
-.health-panel-loading {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: $space-2;
- padding: $space-6;
- color: $text-tertiary;
- font-size: $font-size-sm;
-}
-
-.health-panel-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- margin-bottom: $space-4;
-
- h4 {
- display: flex;
- align-items: center;
- gap: $space-2;
- margin: 0;
- font-size: $font-size-base;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- }
-}
-
-.health-panel-grid {
- display: flex;
- flex-direction: column;
- gap: $space-3;
-}
-
-.health-panel-env {
- padding: $space-3;
- background: $bg-tertiary;
- border-radius: $radius-md;
-}
-
-.health-panel-env-header {
- display: flex;
- align-items: center;
- gap: $space-2;
- margin-bottom: $space-2;
-}
-
-.health-panel-env-name {
- flex: 1;
- font-size: $font-size-sm;
- font-weight: $font-weight-semibold;
- color: $text-primary;
-}
-
-.health-panel-overall {
- font-size: $font-size-xs;
- font-weight: $font-weight-medium;
- padding: 2px 8px;
- border-radius: $radius-sm;
-
- &.health-healthy {
- background: fade($success-raw, 12%);
- color: $color-success;
- }
- &.health-degraded {
- background: fade($warning-raw, 12%);
- color: $color-warning;
- }
- &.health-unhealthy {
- background: fade($danger-raw, 12%);
- color: $color-danger;
- }
- &.health-unknown {
- background: fade($text-tertiary-raw, 12%);
- color: $text-tertiary;
- }
-}
-
-.health-panel-checks {
- display: flex;
- flex-direction: column;
- gap: $space-1;
-}
-
-.health-panel-check {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-1 0;
- font-size: $font-size-xs;
-}
-
-.health-panel-check-name {
- font-weight: $font-weight-medium;
- color: $text-secondary;
- min-width: 80px;
-}
-
-.health-panel-check-msg {
- color: $text-tertiary;
-}
-
-.health-panel-empty {
- text-align: center;
- padding: $space-6;
- color: $text-tertiary;
- font-size: $font-size-sm;
-}
-
-.health-dot {
- flex-shrink: 0;
-}
-
-// ============================================
-// DISK USAGE BAR
-// ============================================
-
-.disk-usage-compact {
- display: inline-flex;
- align-items: center;
- gap: 4px;
- font-size: $font-size-xs;
- color: $text-tertiary;
-}
-
-.disk-usage-compact-text {
- font-family: $font-family-mono;
-}
-
-.disk-usage-bar-container {
- padding: $space-3;
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
-}
-
-.disk-usage-header {
- display: flex;
- align-items: center;
- gap: $space-2;
- margin-bottom: $space-2;
- font-size: $font-size-sm;
- color: $text-primary;
-}
-
-.disk-usage-total {
- font-weight: $font-weight-semibold;
- font-family: $font-family-mono;
-}
-
-.disk-usage-bar {
- display: flex;
- height: 8px;
- border-radius: 4px;
- overflow: hidden;
- background: $bg-tertiary;
-}
-
-.disk-usage-segment {
- height: 100%;
- transition: width 0.3s ease;
-
- &.wordpress {
- &.green { background: $color-success; }
- &.yellow { background: $color-warning; }
- &.red { background: $color-danger; }
- }
-
- &.mysql {
- background: $color-info;
- }
-
- &.snapshots {
- background: fade($text-tertiary-raw, 30%);
- }
-}
-
-.disk-usage-legend {
- display: flex;
- flex-wrap: wrap;
- gap: $space-3;
- margin-top: $space-2;
-}
-
-.disk-usage-legend-item {
- display: flex;
- align-items: center;
- gap: 4px;
- font-size: $font-size-xs;
- color: $text-tertiary;
-}
-
-.disk-usage-legend-dot {
- width: 8px;
- height: 8px;
- border-radius: 2px;
-
- &.wordpress { background: $color-success; }
- &.mysql { background: $color-info; }
- &.snapshots { background: fade($text-tertiary-raw, 30%); }
-}
-
-// ============================================
-// AUTO-SYNC MODAL
-// ============================================
-
-.auto-sync-modal {
- max-width: 480px;
-}
-
-.auto-sync-loading {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: $space-2;
- padding: $space-6;
- color: $text-tertiary;
- font-size: $font-size-sm;
-}
-
-.auto-sync-body {
- padding: $space-4 0;
-}
-
-.auto-sync-env-name {
- font-size: $font-size-sm;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- padding-bottom: $space-3;
- border-bottom: 1px solid $border-subtle;
- margin-bottom: $space-3;
-}
-
-.auto-sync-toggle {
- margin-bottom: $space-4;
-}
-
-.auto-sync-toggle-label {
- display: flex;
- align-items: center;
- justify-content: space-between;
- cursor: pointer;
-
- span {
- font-size: $font-size-sm;
- font-weight: $font-weight-medium;
- color: $text-primary;
- }
-}
-
-.auto-sync-description {
- font-size: $font-size-xs;
- color: $text-tertiary;
- margin: $space-1 0 0;
-}
-
-.auto-sync-presets {
- display: flex;
- flex-direction: column;
- gap: $space-2;
-}
-
-.auto-sync-cron-display {
- font-family: $font-family-mono;
- font-size: $font-size-xs;
- color: $text-tertiary;
-}
-
-.auto-sync-cron-input {
- font-family: $font-family-mono;
-}
-
-.auto-sync-next-runs {
- margin-top: $space-4;
- padding: $space-3;
- background: $bg-tertiary;
- border-radius: $radius-md;
-
- h5 {
- margin: 0 0 $space-2;
- font-size: $font-size-xs;
- font-weight: $font-weight-semibold;
- color: $text-secondary;
- text-transform: uppercase;
- letter-spacing: 0.5px;
- }
-
- ul {
- list-style: none;
- margin: 0;
- padding: 0;
- }
-
- li {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-1 0;
- font-size: $font-size-xs;
- color: $text-secondary;
-
- svg {
- color: $text-tertiary;
- }
- }
-}
-
-// ============================================
-// BULK ACTIONS BAR
-// ============================================
-
-.bulk-actions-bar {
- display: flex;
- align-items: center;
- gap: $space-3;
- padding: $space-3 $space-4;
- background: fade($accent-primary-raw, 8%);
- border: 1px solid fade($accent-primary-raw, 20%);
- border-radius: $radius-md;
- margin-bottom: $space-4;
-}
-
-.bulk-actions-info {
- display: flex;
- align-items: center;
- gap: $space-1;
- font-size: $font-size-sm;
- color: $text-secondary;
-}
-
-.bulk-actions-count {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- min-width: 24px;
- height: 24px;
- padding: 0 6px;
- background: $color-primary;
- color: white;
- border-radius: 12px;
- font-size: $font-size-xs;
- font-weight: $font-weight-bold;
-}
-
-.bulk-actions-buttons {
- display: flex;
- gap: $space-1;
- flex: 1;
-}
-
-.bulk-actions-clear {
- color: $text-tertiary !important;
-}
-
-.bulk-actions-confirm {
- display: flex;
- align-items: center;
- gap: $space-3;
- width: 100%;
-
- span {
- flex: 1;
- font-size: $font-size-sm;
- color: $text-primary;
- font-weight: $font-weight-medium;
- }
-}
-
-// ============================================
-// OPERATION PROGRESS
-// ============================================
-
-.operation-progress-content {
- flex: 1;
- display: flex;
- flex-direction: column;
- gap: $space-2;
-}
-
-.operation-progress {
- display: flex;
- flex-direction: column;
- gap: $space-1;
-}
-
-.operation-progress-bar {
- height: 4px;
- background: fade($info-raw, 20%);
- border-radius: 2px;
- overflow: hidden;
-}
-
-.operation-progress-fill {
- height: 100%;
- background: $color-info;
- border-radius: 2px;
- transition: width 0.3s ease;
-}
-
-.operation-progress-step {
- font-size: $font-size-xs;
- color: $text-tertiary;
-}
-
-// ============================================
-// HEALTH TAB
-// ============================================
-
-.health-tab {
- padding: $space-4 0;
-}
-
-// ============================================
-// RESPONSIVE
-// ============================================
-
-@media (max-width: 900px) {
- .pipeline-row {
- flex-direction: column;
- align-items: stretch;
-
- .pipeline-card {
- max-width: none;
- }
- }
-
- .pipeline-arrow {
- min-width: auto;
- padding: $space-2 0;
-
- .pipeline-arrow-btn {
- flex-direction: row;
- }
-
- svg {
- transform: rotate(90deg);
- }
- }
-
- .pipeline-sync-row {
- flex-direction: column;
-
- .pipeline-sync-action {
- max-width: none;
- }
- }
-
- .bulk-actions-bar {
- flex-wrap: wrap;
- }
-
- .bulk-actions-buttons {
- flex-wrap: wrap;
- }
-}
-
-// ============================================
-// PROMOTION HISTORY (pipeline tab, with rollback)
-// ============================================
-.pipeline-promotion-history {
- margin-top: $space-6;
-
- .promotion-history-list {
- display: flex;
- flex-direction: column;
- gap: $space-2;
- margin-top: $space-3;
- }
-
- .promotion-history-item {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: $space-3;
- padding: $space-3 $space-4;
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- }
-
- .promotion-history-main {
- display: flex;
- align-items: center;
- gap: $space-3;
- flex-wrap: wrap;
- font-size: $font-size-sm;
- }
-
- .promotion-route {
- display: inline-flex;
- align-items: center;
- gap: $space-1;
- color: $text-primary;
- font-weight: $font-weight-medium;
- }
-
- .promotion-type,
- .promotion-date {
- color: $text-tertiary;
- font-size: $font-size-xs;
- }
-
- .promotion-status {
- text-transform: capitalize;
- font-size: $font-size-xs;
- font-weight: $font-weight-medium;
- padding: 2px 8px;
- border-radius: $radius-sm;
- background: fade($info-raw, 12%);
- color: $color-info;
-
- &.promotion-status-completed {
- background: fade($success-raw, 12%);
- color: $color-success;
- }
-
- &.promotion-status-failed {
- background: fade($danger-raw, 12%);
- color: $color-danger;
- }
-
- &.promotion-status-rolled_back {
- background: fade($warning-raw, 12%);
- color: $color-warning;
- }
- }
-}
diff --git a/builtin-extensions/serverkit-wordpress/frontend/styles/wordpress-plugin-library.scss b/builtin-extensions/serverkit-wordpress/frontend/styles/wordpress-plugin-library.scss
deleted file mode 100644
index 40940ff6..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/styles/wordpress-plugin-library.scss
+++ /dev/null
@@ -1,185 +0,0 @@
-// Compiled through the extension's module graph (imported by index.jsx).
-// The host's design-token partial is imported via a sync-safe relative
-// path — the baked copy lives at frontend/src/plugins/serverkit-wordpress/,
-// so this resolves to frontend/src/styles/_variables.scss.
-@import '../../../styles/variables';
-
-// 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/builtin-extensions/serverkit-wordpress/frontend/styles/wordpress.scss b/builtin-extensions/serverkit-wordpress/frontend/styles/wordpress.scss
deleted file mode 100644
index a3fb3b97..00000000
--- a/builtin-extensions/serverkit-wordpress/frontend/styles/wordpress.scss
+++ /dev/null
@@ -1,3376 +0,0 @@
-// Compiled through the extension's module graph (imported by index.jsx).
-// The host's design-token partial is imported via a sync-safe relative
-// path — the baked copy lives at frontend/src/plugins/serverkit-wordpress/,
-// so this resolves to frontend/src/styles/_variables.scss.
-@import '../../../styles/variables';
-
-// ============================================
-// WORDPRESS PAGE STYLES
-// ============================================
-
-// WordPress Standalone Page (Docker-based, mirrors Git page layout)
-.wordpress-standalone-page {
- // Inherits .git-page styles for layout, status cards, overview tab, etc.
-
- .empty-state-large {
- .empty-icon svg {
- stroke: $color-wordpress;
- }
- }
-
- .status-card.success {
- border-left-color: $color-success;
-
- .status-icon {
- color: $color-success;
- }
- }
-
- .status-card.danger {
- border-left-color: $color-danger;
-
- .status-icon {
- color: $color-danger;
- }
- }
-}
-
-// WordPress Page Layout (extends Docker page styles)
-.wordpress-page {
- .empty-state-large {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: 60px $space-6;
- background: $bg-card;
- border-radius: $radius-xl;
- text-align: center;
- margin: 0 $space-4;
-
- .empty-icon {
- color: $text-tertiary;
- margin-bottom: $space-6;
-
- svg {
- stroke: $color-wordpress;
- }
- }
-
- h2 {
- margin: 0 0 $space-3 0;
- font-size: $font-size-2xl;
- font-weight: $font-weight-semibold;
- }
-
- p {
- margin: 0 0 $space-6 0;
- color: $text-secondary;
- max-width: 460px;
- }
- }
-
- .install-warning {
- display: flex;
- gap: $space-3;
- padding: $space-4;
- background: fade($warning-raw, 8%);
- border: 1px solid fade($warning-raw, 20%);
- border-radius: $radius-md;
- margin-bottom: $space-4;
-
- > svg {
- flex-shrink: 0;
- color: $color-warning;
- margin-top: 2px;
- }
-
- strong {
- display: block;
- margin-bottom: $space-2;
- }
-
- ul {
- margin: 0;
- padding-left: $space-4;
- color: $text-secondary;
- font-size: $font-size-sm;
-
- li {
- margin-bottom: $space-1;
- }
- }
- }
-
- .form-hint {
- display: block;
- font-size: $font-size-xs;
- color: $text-tertiary;
- margin-top: $space-1;
- }
-
- .docker-empty {
- .wp-empty-icon {
- color: $text-tertiary;
- margin-bottom: $space-4;
-
- svg {
- stroke: currentColor;
- }
- }
- }
-}
-
-// Sites Grid
-.wp-sites-grid {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
- gap: $space-4;
- padding: $space-4;
-}
-
-// Redesign: dense WordPress site table (replaces the .wp-site-card grid).
-.wp-list {
- padding: $space-4;
-
- &__toolbar {
- display: flex;
- align-items: center;
- gap: $space-3;
- flex-wrap: wrap;
- margin-bottom: $space-3;
-
- .wp-tag-filter { margin: 0; }
- }
-
- // Client-side site search (name / title / domain). Mirrors the demo's
- // .input: leading icon + borderless field on a quiet surface.
- &__search {
- display: inline-flex;
- align-items: center;
- gap: $space-2;
- margin-left: auto;
- padding: 0 10px;
- width: 240px;
- max-width: 100%;
- height: 32px;
- background: var(--surface-2);
- border: 1px solid var(--border-soft);
- border-radius: 8px;
- color: var(--text-faint);
- transition: border-color 0.14s;
-
- &:focus-within { border-color: var(--accent-dim); }
-
- svg { flex-shrink: 0; }
-
- input {
- flex: 1;
- min-width: 0;
- border: none;
- background: none;
- color: var(--text);
- font-size: 13px;
-
- &::placeholder { color: var(--text-faint); }
- &:focus { outline: none; }
- }
- }
-
- // Count subtitle accent ("M running") in the PageTopbar meta slot.
- &__meta-running { color: var(--green); }
-
- // Table/cards switch — only rendered by pages that pass a card renderer to
- // ResourceListPage. It claims the free space so it stays right-aligned on
- // pages whose search lives in the top bar instead (Services); where a
- // toolbar search IS present that element already claims it, so the switch
- // gives the margin back and simply trails it.
- &__viewswitch {
- display: flex;
- gap: 2px;
- flex-shrink: 0;
- margin-left: auto;
- padding: 3px;
- background: var(--surface-2);
- border: 1px solid var(--border);
- border-radius: 9px;
-
- button {
- display: grid;
- place-items: center;
- padding: 6px 9px;
- background: none;
- border: none;
- border-radius: 6px;
- color: var(--text-faint);
- cursor: pointer;
- transition: background 0.14s, color 0.14s;
-
- &:hover { color: var(--text); }
- &.is-active { background: var(--surface-3); color: var(--text); }
- }
- }
-
- &__search + &__viewswitch { margin-left: 0; }
-
- // Card layout for the same rows the table shows.
- &__cards {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
- gap: 14px;
- }
-
- &__cardtile {
- display: flex;
- flex-direction: column;
- padding: $space-4;
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- cursor: pointer;
- transition: border-color 0.14s, transform 0.14s;
-
- &:hover { border-color: var(--border-strong); transform: translateY(-2px); }
- &.is-selected { border-color: var(--accent-dim); background: var(--accent-bg-soft); }
- }
-
- // bulk-select bar (demo's bulkbar) — appears once any row is checked
- &__bulkbar {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: $space-3;
- flex-wrap: wrap;
- padding: $space-2 $space-4;
- margin-bottom: $space-3;
- background: var(--accent-bg-soft);
- border: 1px solid var(--accent-dim);
- border-radius: var(--radius);
- }
-
- &__bulkcount {
- font-family: var(--mono);
- font-size: 12px;
- font-weight: $font-weight-medium;
- color: var(--accent-bright);
- }
-
- &__bulkactions {
- display: flex;
- align-items: center;
- gap: $space-2;
- flex-wrap: wrap;
- }
-
- &__ck {
- width: 36px;
- padding-right: 0;
- }
-
- &__action { width: 70px; }
-
- &__card {
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- overflow: hidden;
- }
-
- // Per-site gradient initial avatar (ds ServiceTile / .sk-tile). The tile
- // brings its own size + hue-hashed gradient inline; we only soften the
- // corner to the demo's small rounded-square look.
- &__tile {
- border-radius: 8px;
- }
-
- &__links {
- display: inline-flex;
- gap: $space-2;
-
- a {
- display: inline-flex;
- color: var(--text-faint);
- transition: color 0.14s;
- &:hover { color: var(--accent-bright); }
- }
- }
-
- &__dash { color: var(--text-ghost); font-family: var(--mono); font-size: 12px; }
- &__chev { color: var(--text-ghost); }
-
- .sk-tag + .sk-tag { margin-left: 4px; }
-}
-
-// Site tags / labels (chips + filter bar)
-.wp-tag-filter {
- display: flex;
- flex-wrap: wrap;
- gap: $space-2;
- margin: 0 $space-4 $space-4;
-}
-
-.wp-site-tags {
- display: flex;
- flex-wrap: wrap;
- gap: $space-1;
- margin-top: $space-3;
-}
-
-.wp-tag-chip {
- display: inline-flex;
- align-items: center;
- padding: 2px 10px;
- font-size: $font-size-xs;
- line-height: 1.4;
- border-radius: $radius-full;
- background: $bg-tertiary;
- color: $text-secondary;
- border: 1px solid $border-subtle;
-
- &--filter {
- cursor: pointer;
- background: $bg-card;
-
- &.is-active {
- background: $color-primary;
- color: #fff;
- border-color: $color-primary;
- }
- }
-}
-
-// Site Card
-.wp-site-card {
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-lg;
- cursor: pointer;
- transition: all 0.15s ease;
-
- &:hover {
- border-color: $border-hover;
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
- }
-}
-
-.wp-site-card-header {
- display: flex;
- align-items: center;
- gap: $space-3;
- padding: $space-4;
- border-bottom: 1px solid $border-subtle;
-}
-
-.wp-site-icon {
- width: 40px;
- height: 40px;
- background: $color-wordpress;
- border-radius: $radius-md;
- display: flex;
- align-items: center;
- justify-content: center;
- color: #fff;
- flex-shrink: 0;
-}
-
-.wp-site-info {
- flex: 1;
- min-width: 0;
-}
-
-.wp-site-name {
- font-size: $font-size-base;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- margin: 0;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.wp-site-url {
- font-size: $font-size-xs;
- color: $text-tertiary;
- font-family: $font-family-mono;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- display: block;
-}
-
-.wp-site-status {
- display: flex;
- align-items: center;
- gap: 6px;
- font-size: $font-size-xs;
- padding: 4px 10px;
- border-radius: $radius-full;
- font-weight: $font-weight-medium;
-
- .status-dot {
- width: 6px;
- height: 6px;
- border-radius: 50%;
- }
-
- &.running {
- background: fade($success-raw, 12%);
- color: $color-success;
-
- .status-dot {
- background: $color-success;
- }
- }
-
- &.stopped {
- background: fade($text-tertiary-raw, 12%);
- color: $text-tertiary;
-
- .status-dot {
- background: $text-tertiary;
- }
- }
-}
-
-.wp-site-card-body {
- padding: $space-4;
-}
-
-.wp-site-meta {
- display: grid;
- grid-template-columns: repeat(2, 1fr);
- gap: $space-3;
-}
-
-.wp-site-meta-item {
- .meta-label {
- display: block;
- font-size: $font-size-xs;
- color: $text-tertiary;
- margin-bottom: 2px;
- }
-
- .meta-value {
- font-size: $font-size-sm;
- color: $text-primary;
- font-weight: $font-weight-medium;
-
- &.git-connected {
- color: $color-success;
- }
- }
-}
-
-.wp-site-badge {
- display: inline-block;
- font-size: $font-size-xs;
- font-weight: $font-weight-medium;
- padding: 2px 8px;
- border-radius: $radius-sm;
- margin-top: $space-3;
-
- &.production {
- background: fade($danger-raw, 12%);
- color: $color-danger;
- }
-
- &.development {
- background: fade($info-raw, 12%);
- color: $color-info;
- }
-}
-
-.wp-site-card-links {
- display: flex;
- gap: $space-3;
- margin-top: $space-3;
- padding-top: $space-3;
- border-top: 1px solid $border-subtle;
-}
-
-.wp-site-link {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- font-size: $font-size-xs;
- font-weight: $font-weight-medium;
- color: $color-primary;
- text-decoration: none;
-
- &:hover {
- text-decoration: underline;
- }
-}
-
-.wp-site-card-footer {
- display: flex;
- gap: $space-2;
- padding: $space-3 $space-4;
- border-top: 1px solid $border-subtle;
- background: $bg-tertiary;
- border-radius: 0 0 $radius-lg $radius-lg;
-
- .btn {
- flex: 1;
- justify-content: center;
-
- &.btn-danger {
- flex: 0;
- color: $color-danger;
-
- &:hover {
- background: fade($danger-raw, 10%);
- }
- }
- }
-}
-
-// ============================================
-// WORDPRESS DETAIL PAGE (redesign — infra console look)
-// ============================================
-// Everything here is scoped under .wp-detail-page on purpose: the base
-// `app-*` classes (.app-panel, .app-info-grid, .app-detail-tabs, …) live in
-// _applications.scss and are ALSO rendered by the Applications detail page,
-// which keeps its current look until its own pass. Same pattern as the
-// `.server-detail-page` block in _servers.scss.
-
-// Run the detail page FULL-BLEED, like the WordPress list page: drop the
-// .main-content 40px frame so the .sk-topbar spans edge-to-edge. (Unlike the
-// generic full-bleed rule in _main-content.scss, we keep the normal scroll —
-// no height:100vh/overflow:hidden — because this is a long scrolling page, not
-// a self-managing two-pane tool.) .app-detail-body re-pads the content below.
-.main-content:has(.wp-detail-page) {
- padding: 0;
-
- // padding:0 also drops the base rule's mobile top-clearance, so restore it
- // (the fixed mobile header would otherwise overlap the top bar).
- @media (max-width: $breakpoint-md) {
- margin-top: calc(#{$mobile-header-height} + env(safe-area-inset-top));
- }
-}
-
-.wp-detail-page {
- // The full-bleed top bar sits flush above the padded body (no page gap).
- gap: 0;
-
- // Content below the full-bleed top bar: a CENTERED max-width column (like the
- // prototype), laid out as a flex column so identity / tabs / content are
- // evenly spaced (fixes the tab-touches-content gap).
- .app-detail-body {
- display: flex;
- flex-direction: column;
- gap: $space-5;
- width: 100%;
- max-width: 1200px;
- margin-inline: auto;
- padding: $space-6 $space-6 $space-10;
- }
-
- // ---- Breadcrumbs (mono trail) ----
- .app-detail-breadcrumbs {
- font-family: var(--mono);
- font-size: $font-size-sm;
-
- a {
- color: var(--text-faint);
-
- &:hover {
- color: var(--accent-bright);
- }
- }
-
- > span {
- color: var(--text-ghost);
- }
-
- .current {
- color: var(--text-dim);
- font-weight: $font-weight-medium;
- }
- }
-
- // ---- Header (demo .site-header: gradient surface + accent wash) ----
- // Identity row — NO card background (matches the prototype): just the icon +
- // name + status sitting directly on the page.
- .app-detail-header {
- position: relative;
- gap: $space-4;
- padding: 4px 0 0;
- background: none;
- border: none;
- border-radius: 0;
- }
-
- // The detail page uses the canonical PageTopbar (.sk-topbar) for its top bar
- // so the chrome matches the WordPress LIST page and every other page. Tweaks:
- // a breadcrumb title and a compact, wrapping action cluster (the detail page
- // carries more actions than a typical page).
- .wp-detail-topbar {
- // Full-bleed now that .main-content has no padding; match the list page's
- // sk-topbar inset. Many actions, so wrap the bar as a whole instead of
- // squeezing the title (which made the breadcrumb collide with a button).
- padding: 10px $space-4;
- flex-wrap: wrap;
- row-gap: 8px;
-
- // The bar's flex:1 spacer would force the actions onto their own line
- // every time; drop it and push the cluster right with margin instead, so
- // the actions sit beside the title when they fit and wrap only when not.
- .sk-topbar__spacer { display: none; }
-
- .sk-topbar__titles { flex-shrink: 0; }
-
- .wp-crumbs {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- white-space: nowrap;
-
- a {
- color: var(--text-dim);
- text-decoration: none;
- &:hover { color: var(--accent-bright); }
- }
- &__sep { color: var(--text-ghost); }
- &__cur { color: var(--text); }
- }
-
- .sk-topbar__actions {
- margin-left: auto;
- flex-wrap: wrap;
- justify-content: flex-end;
- row-gap: 6px;
-
- .ui-button {
- height: 32px;
- padding: 0 10px;
- font-size: 12.5px;
- gap: 6px;
- }
- }
- }
-
- // Overview top grid: Site information (left) + Traffic chart (right), matching
- // the mockup's ~40/60 split; collapses to one column on narrow screens.
- .wp-overview-main {
- display: grid;
- grid-template-columns: minmax(300px, 0.85fr) 1.15fr;
- gap: $space-4;
- margin-bottom: $space-4;
-
- @media (max-width: $breakpoint-lg) {
- grid-template-columns: 1fr;
- }
- }
-
- // Traffic panel: stack the title over a muted mono sub-label.
- .wp-traffic-panel {
- .app-panel-header {
- flex-direction: column;
- align-items: flex-start;
- gap: 2px;
- }
- .wp-panel-sub {
- font-family: var(--mono);
- font-size: 11px;
- font-weight: $font-weight-normal;
- letter-spacing: 0;
- text-transform: none;
- color: var(--text-faint);
- }
- }
-
- // Recent activity spans full width beneath the main grid.
- .wp-activity-panel { margin-bottom: $space-4; }
-
- // WP detail carries more tabs than fit one row at common widths, so let the
- // strip WRAP instead of scrolling — otherwise the right-pinned Settings tab
- // gets pushed off-screen and becomes unreachable.
- .app-detail-tabs {
- flex-wrap: wrap;
- overflow-x: visible;
- row-gap: 2px;
- }
-
- // Settings tab pinned to the far right of the tab strip (the mockup's gear).
- .app-detail-tab--end { margin-left: auto; }
-
- // Settings tab — left sub-nav + content (PHP, Updates, …).
- .wp-settings {
- display: grid;
- grid-template-columns: 200px 1fr;
- gap: $space-4;
- align-items: start;
-
- @media (max-width: $breakpoint-md) {
- grid-template-columns: 1fr;
- }
- }
-
- .wp-settings__nav {
- display: flex;
- flex-direction: column;
- gap: 2px;
- position: sticky;
- top: $space-4;
-
- @media (max-width: $breakpoint-md) {
- position: static;
- flex-direction: row;
- flex-wrap: wrap;
- }
- }
-
- .wp-settings__navitem {
- display: flex;
- width: 100%; // fill the nav column — a flex <button> otherwise shrinks
- // to its label, so each item's box was a different width
- align-items: center;
- gap: 9px;
- padding: 9px 12px;
- border: none;
- border-radius: 8px;
- background: none;
- color: var(--text-dim);
- font-size: 13.5px;
- font-weight: $font-weight-medium;
- text-align: left;
- cursor: pointer;
- transition: background 0.14s, color 0.14s;
-
- svg { color: var(--text-faint); flex-shrink: 0; }
-
- &:hover { background: var(--surface-hover); color: var(--text); }
- &.is-active {
- background: var(--accent-bg);
- color: var(--accent-bright);
- svg { color: var(--accent-bright); }
- }
- }
-
- .wp-settings__content { min-width: 0; }
-
- // Grouped left nav — an uppercase mono label per group (the sidebar-style
- // "group section" the user asked for).
- .wp-settings__group + .wp-settings__group { margin-top: $space-4; }
-
- .wp-settings__grouplabel {
- padding: 0 12px;
- margin-bottom: 6px;
- font-family: var(--mono);
- font-size: 10px;
- font-weight: $font-weight-semibold;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--text-faint);
- }
-
- .app-detail-icon {
- position: relative;
- width: 52px;
- height: 52px;
- border-radius: 13px;
- border: 1px solid fade(#fff, 8%);
- box-shadow: var(--shadow-sm);
- }
-
- .wp-icon {
- background: linear-gradient(150deg, lighten($color-wordpress, 12%), $color-wordpress) !important;
- }
-
- // Status dot pinned to the favicon corner (demo .site-favicon .badge)
- .wp-head-dot {
- position: absolute;
- bottom: -4px;
- right: -4px;
- width: 14px;
- height: 14px;
- border-radius: 50%;
- border: 2.5px solid var(--surface);
- background: var(--text-faint);
-
- &.running {
- background: var(--green);
- }
-
- &.stopped {
- background: var(--red);
- }
- }
-
- .app-detail-title-block h1 {
- font-size: 21px;
- font-weight: $font-weight-semibold;
- letter-spacing: -0.02em;
- gap: 14px;
- flex-wrap: wrap;
- align-items: center;
- }
-
- .app-detail-subtitle {
- display: flex;
- align-items: center;
- gap: 9px;
- flex-wrap: wrap;
- margin-top: 4px;
- font-family: var(--mono);
- font-size: 12px;
- color: var(--text-dim);
-
- a {
- color: var(--accent-bright);
- text-decoration: none;
-
- &:hover {
- text-decoration: underline;
- }
- }
-
- .separator {
- color: var(--text-ghost);
- }
- }
-
- // ---- Repo connection pill (mirrors service detail page) ----
- .wp-detail__repo-bar {
- display: flex;
- margin-top: -#{$space-2}; // tuck it up under the identity header a bit
- }
-
- .wp-detail__repo-pill {
- display: inline-flex;
- align-items: center;
- gap: $space-2;
- padding: 6px $space-3;
- background: var(--surface);
- border: 1px solid var(--border);
- border-radius: $radius-full;
- font-family: var(--mono);
- font-size: $font-size-sm;
- color: var(--text-dim);
- cursor: pointer;
- transition: border-color $transition-fast, background $transition-fast;
-
- svg { color: var(--text-faint); }
-
- &:hover {
- border-color: var(--accent-dim);
- background: var(--surface-2);
- }
- }
-
- .wp-detail__repo-url {
- font-size: $font-size-sm;
- color: $text-primary;
- }
-
- .wp-detail__repo-arrow {
- color: var(--text-ghost);
- }
-
- .wp-detail__repo-branch {
- font-size: $font-size-sm;
- color: var(--accent-bright);
- font-weight: $font-weight-medium;
- }
-
- .wp-detail__auto-deploy-badge {
- font-family: var(--mono);
- font-size: 10px;
- font-weight: $font-weight-semibold;
- letter-spacing: 0.05em;
- text-transform: uppercase;
- padding: 1px 6px;
- background: var(--green-bg);
- color: var(--green);
- border-radius: $radius-sm;
- }
-
- .wp-detail__connect-repo {
- display: inline-flex;
- align-items: center;
- gap: $space-2;
- padding: 6px $space-3;
- background: none;
- border: 1px dashed var(--border-strong);
- border-radius: $radius-full;
- font-size: $font-size-sm;
- color: var(--text-faint);
- cursor: pointer;
- transition: all $transition-fast;
-
- svg { color: var(--text-faint); }
-
- &:hover {
- border-color: var(--accent-dim);
- color: var(--accent-bright);
- background: var(--accent-bg-soft);
- }
- }
-
- // ---- Tab strip (segmented bar — pills in a bordered surface, matching the
- // shared .app-detail-tabs treatment in _applications.scss so every detail
- // page's nav reads the same) ----
- .app-detail-tabs {
- gap: 3px;
- background: var(--surface);
- border: 1px solid var(--border);
- border-radius: var(--radius);
- padding: 4px;
- overflow-x: auto;
-
- &::-webkit-scrollbar {
- height: 0;
- }
- }
-
- .app-detail-tab {
- display: flex;
- align-items: center;
- gap: 7px;
- padding: 8px 13px;
- border-radius: 7px;
- color: var(--text-dim);
- font-size: 13px;
- font-weight: $font-weight-medium;
- white-space: nowrap;
- transition: color 0.14s, background 0.14s;
-
- svg {
- color: var(--text-faint);
- transition: color 0.14s;
- flex-shrink: 0;
- }
-
- &:hover {
- background: var(--surface-2);
- color: var(--text);
-
- svg {
- color: var(--text-dim);
- }
- }
-
- &.active {
- background: var(--accent-bg);
- color: var(--accent-bright);
- font-weight: $font-weight-semibold;
-
- svg {
- color: var(--accent-bright);
- }
- }
- }
-
- // ---- Panels (quiet surface + mono eyebrow header) ----
- .app-panel {
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- }
-
- .app-panel-header {
- display: flex;
- align-items: center;
- justify-content: flex-start;
- gap: 7px;
- padding: 12px 17px;
- border-bottom: 1px solid var(--border-soft);
- font-family: var(--mono);
- font-size: 10.5px;
- font-weight: $font-weight-semibold;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--text-faint);
-
- svg {
- width: 13px;
- height: 13px;
- color: var(--accent-bright);
- }
- }
-
- .app-panel-body {
- padding: $space-4 17px;
-
- .hint:last-child {
- margin-bottom: 0;
- }
-
- .app-detail-actions {
- flex-wrap: wrap;
- align-items: center;
- margin-bottom: $space-3;
-
- &:last-child {
- margin-bottom: 0;
- }
- }
-
- .app-info-grid + .app-detail-actions,
- .app-info-grid + .hint {
- margin-top: $space-3;
- }
- }
-
- // Danger Zone panel — stack the rows with a gap so Archive and Delete don't
- // sit flush against each other.
- .danger-zone-body {
- display: flex;
- flex-direction: column;
- gap: $space-3;
-
- .danger-zone {
- margin-top: 0;
- }
- }
-
- // SSL guided flow — checklist + primary action.
- .ssl-guide {
- display: flex;
- flex-direction: column;
- gap: $space-3;
- margin-top: $space-3;
- }
-
- .ssl-checklist {
- display: flex;
- flex-direction: column;
- gap: $space-2;
- padding: $space-3;
- background: var(--surface-2);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- }
-
- .ssl-check-item {
- display: flex;
- align-items: center;
- gap: $space-2;
- font-size: $font-size-sm;
- color: var(--text-dim);
- }
-
- .ssl-check-icon {
- flex-shrink: 0;
-
- &--ok { color: var(--green); }
- &--missing { color: var(--amber); }
- }
-
- .ssl-check-label {
- &--ok { color: var(--text); }
- }
-
- // Inline domain attach inside the SSL panel — no modal needed.
- .ssl-inline-attach {
- display: flex;
- flex-direction: column;
- gap: $space-3;
- margin-top: $space-3;
- padding-top: $space-3;
- border-top: 1px solid var(--border-soft);
- }
-
- .ssl-context {
- display: flex;
- flex-direction: column;
- gap: $space-2;
- }
-
- .ssl-provider-status {
- display: inline-flex;
- align-items: center;
- gap: $space-2;
- font-size: $font-size-sm;
-
- &--ok {
- color: var(--green);
-
- svg { color: var(--green); }
- }
-
- &--missing {
- color: var(--amber);
-
- svg { color: var(--amber); }
- }
- }
-
- .ssl-context-links {
- display: flex;
- align-items: center;
- gap: $space-2;
- font-size: $font-size-xs;
- color: var(--text-faint);
-
- a {
- color: var(--accent-bright);
- text-decoration: none;
-
- &:hover { text-decoration: underline; }
- }
- }
-
- .ssl-attach-result {
- display: flex;
- flex-direction: column;
- gap: $space-3;
- margin-top: $space-3;
- padding: $space-3;
- background: var(--surface-2);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
-
- &__success {
- display: flex;
- align-items: center;
- gap: $space-2;
- font-size: $font-size-sm;
- color: var(--green);
-
- svg { color: var(--green); }
- }
-
- &__manual {
- display: flex;
- flex-direction: column;
- gap: $space-2;
- font-size: $font-size-sm;
- }
-
- &__record {
- display: block;
- padding: $space-2 $space-3;
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- font-family: var(--mono);
- font-size: $font-size-xs;
- color: var(--text);
- }
- }
-
- // ---- Info grids → k/v spec rows (.sk-info-row look, CSS-only) ----
- .app-info-grid {
- display: flex;
- flex-direction: column;
- gap: 0;
- }
-
- .app-info-item {
- flex-direction: row;
- justify-content: space-between;
- align-items: center;
- gap: $space-4;
- padding: 10px 0;
- border-top: 1px solid var(--border-soft);
-
- &:first-child {
- border-top: none;
- padding-top: 0;
- }
-
- &:last-child {
- padding-bottom: 0;
- }
- }
-
- .app-info-label {
- font-family: var(--mono);
- font-size: 12px;
- color: var(--text-faint);
- min-width: 0;
- overflow-wrap: anywhere;
- }
-
- .app-info-value {
- display: inline-flex;
- align-items: center;
- justify-content: flex-end;
- flex-wrap: wrap;
- gap: $space-2;
- font-family: var(--mono);
- font-size: 12.5px;
- color: var(--text);
- text-align: right;
- min-width: 0;
- overflow-wrap: anywhere;
-
- a {
- color: var(--accent-bright);
- text-decoration: none;
-
- &:hover {
- text-decoration: underline;
- }
- }
- }
-
- // ---- Section headers → mono eyebrows ----
- .section-header {
- margin-bottom: $space-4;
-
- h3 {
- display: flex;
- align-items: center;
- gap: 6px;
- margin: 0;
- font-family: var(--mono);
- font-size: 11px;
- font-weight: $font-weight-semibold;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--text-faint);
- }
- }
-
- // ---- KPI strip (ds MetricCard rows) ----
- .wp-kpis {
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
- gap: $space-4;
- }
-
- .wp-overview {
- display: flex;
- flex-direction: column;
- gap: $space-4;
- }
-
- // ---- Dense table chrome shared by plugins/themes/vulns ----
- .wp-asset-table,
- .wp-vuln-table {
- .sk-cell-name {
- font-size: 13px;
- }
-
- .sk-cell-sub {
- margin-top: 2px;
- }
- }
-
- .wp-vuln-title {
- font-size: 12.5px;
- color: var(--text-dim);
- max-width: 360px;
- overflow-wrap: anywhere;
- }
-
- // app-panel hosting a flush table (Findings)
- .app-panel > .sk-dtable {
- border-radius: 0 0 var(--radius) var(--radius);
- overflow: hidden;
- }
-
- // ---- Severity chips (prototype .sev / security ramp) ----
- .wp-sev {
- display: inline-flex;
- align-items: center;
- gap: 7px;
- font-family: var(--mono);
- font-size: 11px;
- font-weight: $font-weight-semibold;
- text-transform: uppercase;
- letter-spacing: 0.04em;
- white-space: nowrap;
-
- .d {
- width: 9px;
- height: 9px;
- border-radius: 3px;
- flex-shrink: 0;
- background: var(--text-ghost);
- }
-
- &--critical {
- color: var(--red);
-
- .d {
- background: var(--red);
- box-shadow: 0 0 6px var(--red);
- }
- }
-
- &--high {
- color: var(--red);
-
- .d {
- background: var(--red);
- }
- }
-
- &--medium {
- color: var(--amber);
-
- .d {
- background: var(--amber);
- }
- }
-
- &--low {
- color: var(--cyan);
-
- .d {
- background: var(--cyan);
- }
- }
-
- &--unknown {
- color: var(--text-faint);
-
- .d {
- background: var(--text-faint);
- }
- }
- }
-
- .wp-fix-chip {
- font-family: var(--mono);
- font-size: 10.5px;
- color: var(--accent-bright);
- background: var(--accent-bg);
- padding: 2px 7px;
- border-radius: 5px;
- white-space: nowrap;
- }
-
- .wp-no-fix {
- font-family: var(--mono);
- font-size: 11px;
- color: var(--text-faint);
- }
-
- .wp-advisory-link {
- font-family: var(--mono);
- font-size: 11.5px;
- color: var(--accent-bright);
- text-decoration: none;
-
- &:hover {
- text-decoration: underline;
- }
- }
-
- // ---- Update chips + bulk bar (amber wash, mono) ----
- .wp-update-badge {
- font-family: var(--mono);
- font-size: 10.5px;
- font-weight: $font-weight-medium;
- color: var(--amber);
- background: var(--amber-bg);
- padding: 2px 7px;
- border-radius: 5px;
- margin-left: $space-2;
- }
-
- .bulk-update-bar {
- background: var(--amber-bg);
- border: 1px solid fade($warning-raw, 25%);
- border-radius: var(--radius);
- font-family: var(--mono);
- font-size: 12px;
- color: var(--amber);
- }
-
- .install-form {
- margin-bottom: $space-4;
- }
-
- // ---- Security posture (ScoreGauge ring + checklist, demo Posture panel) ----
- .wp-posture {
- display: flex;
- align-items: center;
- gap: $space-6;
-
- &__checks {
- flex: 1;
- min-width: 0;
- }
-
- &__check {
- display: flex;
- align-items: center;
- gap: $space-3;
- padding: 10px 0;
- border-top: 1px solid var(--border-soft);
- font-size: 13px;
-
- &:first-child { border-top: none; }
- }
-
- &__label {
- flex: 1;
- min-width: 0;
- color: var(--text);
- }
-
- &__detail {
- font-family: var(--mono);
- font-size: 11.5px;
- color: var(--text-faint);
- white-space: nowrap;
- }
-
- @media (max-width: $breakpoint-md) {
- flex-direction: column;
- align-items: flex-start;
-
- &__checks { width: 100%; }
- }
- }
-
- // ---- Mono code well (integrity issue lines) ----
- .wp-code-list {
- margin-top: $space-3;
- padding: $space-3 $space-4;
- background: var(--bg-code);
- border: 1px solid var(--border-soft);
- border-radius: $radius-md;
- max-height: 320px;
- overflow-y: auto;
- font-family: var(--mono);
- font-size: 12px;
- line-height: 1.7;
- color: var(--text-code);
- overflow-wrap: anywhere;
- }
-
- // ---- Brute-force jail: banned-IP rows with an inline Unban action ----
- .wp-banlist {
- margin-top: $space-3;
- border: 1px solid var(--border-soft);
- border-radius: $radius-md;
- overflow: hidden;
- }
- .wp-banlist__row {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: $space-3;
- padding: 8px $space-4;
-
- & + & {
- border-top: 1px solid var(--border-soft);
- }
- }
- .wp-banlist__ip {
- font-family: var(--mono);
- font-size: 13px;
- color: var(--text-code);
- }
-
- // ---- Run-history / incident rows (Updates + Reports) ----
- .wp-run-row {
- display: flex;
- flex-direction: column;
- gap: 3px;
- padding: 11px 0;
- border-top: 1px solid var(--border-soft);
-
- &:first-child {
- border-top: none;
- padding-top: 0;
- }
-
- .form-hint {
- margin-top: 0;
- }
- }
-
- .wp-run-row-head {
- display: flex;
- align-items: center;
- gap: $space-2;
- flex-wrap: wrap;
-
- strong {
- font-size: 13px;
- }
- }
-
- .wp-run-row-meta {
- font-family: var(--mono);
- font-size: 11px;
- color: var(--text-faint);
- }
-
- .wp-run-component {
- font-family: var(--mono);
- }
-
- // ---- Analytics head (eyebrow + SegControl) ----
- .wp-analytics-banner {
- display: flex;
- align-items: center;
- gap: $space-3;
- margin-bottom: $space-4;
- padding: $space-3 $space-4;
- border: 1px solid rgba(129, 140, 248, 0.28);
- border-radius: var(--radius, 8px);
- background: rgba(129, 140, 248, 0.08);
- color: var(--text-primary);
- flex-wrap: wrap;
-
- svg { color: var(--accent-bright, #818cf8); flex-shrink: 0; }
-
- &__text { flex: 1 1 240px; font-size: 13px; line-height: 1.4; }
- &__text span { color: var(--text-secondary); }
-
- &__link {
- display: inline-flex;
- align-items: center;
- gap: 4px;
- white-space: nowrap;
- font-size: 13px;
- font-weight: $font-weight-semibold;
- color: var(--accent-bright, #818cf8);
- }
- }
-
- .wp-analytics-head {
- display: flex;
- justify-content: space-between;
- align-items: center;
- gap: $space-3;
- flex-wrap: wrap;
- }
-
- .wp-eyebrow {
- margin: 0;
- font-family: var(--mono);
- font-size: 11px;
- font-weight: $font-weight-semibold;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--text-faint);
- }
-
- // Recharts default tooltip → surface tokens (recharts inline-styles it)
- .recharts-default-tooltip {
- background: var(--surface-2) !important;
- border: 1px solid var(--border) !important;
- border-radius: var(--radius-sm);
- box-shadow: var(--shadow-md);
- font-family: var(--mono);
- font-size: 11.5px;
- }
-
- .recharts-tooltip-label {
- color: var(--text-faint) !important;
- }
-
- // ---- Report header actions keep normal type inside the eyebrow bar ----
- .wp-report-actions {
- font-family: $font-main;
- text-transform: none;
- letter-spacing: normal;
- }
-
- // ---- Commit list (scoped: Git.jsx renders .commit-item too) ----
- .commit-list {
- gap: 0;
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- overflow: hidden;
- max-width: 860px;
- }
-
- .commit-item {
- background: transparent;
- border: none;
- border-radius: 0;
- padding: 12px $space-4;
- transition: background 0.12s;
-
- & + .commit-item {
- border-top: 1px solid var(--border-soft);
- }
-
- &:hover {
- background: var(--surface-2);
- }
-
- &.current {
- background: fade($success-raw, 5%);
- }
- }
-
- .commit-icon {
- color: var(--text-faint);
-
- .current-icon {
- color: var(--green);
- }
- }
-
- .commit-sha {
- font-family: var(--mono);
- font-size: 11px;
- color: var(--accent-bright);
- background: var(--accent-bg);
- padding: 2px 7px;
- border-radius: 5px;
- }
- // Clickable SHA → the commit on the remote host.
- a.commit-sha--link {
- display: inline-flex;
- align-items: center;
- gap: 4px;
- text-decoration: none;
- transition: background 0.14s;
-
- svg { opacity: 0.6; }
- &:hover { background: var(--accent-bg-soft); text-decoration: underline; svg { opacity: 1; } }
- }
-
- .current-badge {
- font-family: var(--mono);
- font-size: 10px;
- font-weight: $font-weight-semibold;
- text-transform: uppercase;
- letter-spacing: 0.05em;
- background: var(--green-bg);
- color: var(--green);
- padding: 2px 7px;
- border-radius: 5px;
- }
-
- .commit-date {
- font-family: var(--mono);
- font-size: 10.5px;
- color: var(--text-faint);
- }
-
- .commit-message {
- font-size: 13px;
- font-weight: $font-weight-medium;
- }
-
- .commit-author {
- font-family: var(--mono);
- font-size: 11px;
- color: var(--text-faint);
- }
-
- // ---- DiskUsageBar container re-tint (styles live in _wordpress-pipeline) ----
- .app-health-disk .disk-usage-bar-container {
- background: var(--surface-2);
- border-color: var(--border-soft);
- }
-}
-
-// ---- Header environment switcher (prototype .env-switch / .env-menu) ----
-.wp-envswitch-wrap {
- position: relative;
- display: inline-flex;
-}
-
-.wp-envswitch {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- padding: 5px 10px 5px 11px;
- border: 1px solid var(--border-strong);
- border-radius: 8px;
- background: var(--surface-2);
- font-family: $font-main;
- font-size: 12.5px;
- font-weight: $font-weight-medium;
- letter-spacing: normal;
- color: var(--text);
- cursor: pointer;
- transition: border-color 0.14s, background 0.14s;
-
- .ed {
- width: 8px;
- height: 8px;
- border-radius: 50%;
- flex-shrink: 0;
- }
-
- .chev {
- color: var(--text-faint);
- transition: transform 0.15s;
- }
-
- &.open .chev {
- transform: rotate(180deg);
- }
-
- &:hover {
- background: var(--surface-3);
- border-color: var(--border-strong);
- }
-}
-
-.wp-envswitch-menu {
- position: absolute;
- top: 100%;
- left: 0;
- margin-top: 7px;
- z-index: $z-dropdown + 5;
- min-width: 280px;
- background: var(--surface-2);
- border: 1px solid var(--border-strong);
- border-radius: 12px;
- box-shadow: var(--shadow-lg);
- padding: 7px;
-}
-
-.wp-envswitch-head {
- font-family: var(--mono);
- font-size: 10px;
- letter-spacing: 0.12em;
- text-transform: uppercase;
- color: var(--text-ghost);
- padding: 7px 10px 5px;
-}
-
-.wp-envswitch-opt {
- display: flex;
- align-items: center;
- gap: 11px;
- width: 100%;
- padding: 9px 10px;
- border: none;
- border-radius: 9px;
- background: none;
- color: var(--text);
- font-family: $font-main;
- letter-spacing: normal;
- text-transform: none;
- text-align: left;
- cursor: pointer;
- transition: background 0.1s;
-
- &:hover {
- background: var(--surface-3);
- }
-
- .ed {
- width: 9px;
- height: 9px;
- border-radius: 50%;
- flex-shrink: 0;
- }
-
- .check {
- margin-left: auto;
- color: var(--accent-bright);
- flex-shrink: 0;
- }
-}
-
-.wp-envswitch-opt-body {
- flex: 1;
- min-width: 0;
-
- .nm {
- display: block;
- font-weight: $font-weight-medium;
- font-size: 13px;
- }
-
- .meta {
- display: block;
- font-family: var(--mono);
- font-size: 10.5px;
- color: var(--text-faint);
- margin-top: 1px;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- }
-}
-
-// ---- Surface card wrapper for dense tables (SnapshotTable & friends) ----
-.wp-table-card {
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- overflow: hidden;
-}
-
-.wp-th-right {
- text-align: right !important;
-}
-
-.wp-cell-actions {
- text-align: right;
- white-space: nowrap;
-}
-
-.wp-row-action {
- display: inline-grid;
- place-items: center;
- width: 28px;
- height: 28px;
- border: none;
- border-radius: 7px;
- background: none;
- color: var(--text-faint);
- cursor: pointer;
- transition: background 0.14s, color 0.14s;
-
- &:hover:not(:disabled) {
- background: var(--surface-3);
- color: var(--text);
- }
-
- &:disabled {
- opacity: 0.5;
- cursor: default;
- }
-
- &--danger:hover:not(:disabled) {
- background: var(--red-bg);
- color: var(--red);
- }
-}
-
-// Environment Cards (EnvironmentCard.jsx — WP detail Environments tab).
-// Restyled to the prototype's .env-card: quiet surface, accent border on
-// production, EnvTag/Pill rendered by the ds components.
-.environments-grid {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
- gap: $space-4;
- margin-top: $space-4;
-}
-
-// Dashed "add environment" tile — an in-grid affordance that reads as
-// intentional, replacing the old full-width empty-state block that looked
-// like an error sitting under the production card.
-.wp-env-add-tile {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- gap: $space-2;
- min-height: 150px;
- padding: $space-6;
- text-align: center;
- border: 1px dashed var(--border-strong);
- border-radius: var(--radius);
- background: transparent;
- color: var(--text-dim);
- cursor: pointer;
- transition: border-color 0.15s, color 0.15s, background 0.15s;
-
- &:hover {
- border-color: var(--accent);
- color: var(--text);
- background: var(--accent-bg-soft);
- }
-
- &__icon {
- display: grid;
- place-items: center;
- width: 40px;
- height: 40px;
- border-radius: var(--radius);
- background: var(--accent-bg);
- color: var(--accent-bright);
- }
-
- &__title {
- font-size: $font-size-base;
- font-weight: $font-weight-semibold;
- color: var(--text);
- }
-
- &__hint {
- font-size: $font-size-sm;
- line-height: $line-height-normal;
- max-width: 280px;
- }
-}
-
-.wp-env-card {
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- transition: border-color 0.15s;
-
- &:hover {
- border-color: var(--border-strong);
- }
-
- &.production {
- border-color: var(--accent-dim);
-
- &:hover {
- border-color: var(--accent-dim);
- }
- }
-
- &.stale {
- border-color: fade($warning-raw, 35%);
- }
-}
-
-.wp-env-status-group {
- display: flex;
- align-items: center;
- gap: $space-2;
-}
-
-.wp-env-stale-badge {
- display: flex;
- align-items: center;
- gap: 4px;
- font-family: var(--mono);
- font-size: 10.5px;
- font-weight: $font-weight-medium;
- padding: 2px 7px;
- border-radius: 5px;
- background: var(--amber-bg);
- color: var(--amber);
-
- svg {
- flex-shrink: 0;
- }
-}
-
-.text-warning {
- color: var(--amber) !important;
-}
-
-// Kept for the pipeline surfaces: PipelineView / WordPressProjects /
-// EnvironmentStatusBadge still render these classes (EnvironmentCard itself
-// now uses the ds EnvTag/Pill components instead).
-.wp-env-badge {
- font-size: $font-size-xs;
- font-weight: $font-weight-bold;
- padding: 2px 8px;
- border-radius: $radius-sm;
- text-transform: uppercase;
- letter-spacing: 0.5px;
-
- &.env-production {
- background: fade($danger-raw, 12%);
- color: $color-danger;
- }
-
- &.env-staging {
- background: fade($warning-raw, 12%);
- color: $color-warning;
- }
-
- &.env-development {
- background: fade($info-raw, 12%);
- color: $color-info;
- }
-}
-
-.wp-env-status {
- display: flex;
- align-items: center;
- gap: 6px;
- font-size: $font-size-xs;
- font-weight: $font-weight-medium;
-
- .status-dot {
- width: 6px;
- height: 6px;
- border-radius: 50%;
- }
-
- &.running {
- color: $color-success;
-
- .status-dot {
- background: $color-success;
- }
- }
-
- &.stopped {
- color: $text-tertiary;
-
- .status-dot {
- background: $text-tertiary;
- }
- }
-}
-
-.wp-env-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- gap: $space-2;
- padding: 14px 16px;
- border-bottom: 1px solid var(--border-soft);
-}
-
-.wp-env-info {
- display: flex;
- align-items: center;
- gap: $space-2;
- min-width: 0;
-}
-
-.wp-env-name {
- font-size: 14px;
- font-weight: $font-weight-semibold;
- color: var(--text);
- margin: 0;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.wp-env-body {
- padding: 14px 16px;
-}
-
-.wp-env-url {
- margin-bottom: $space-3;
-
- a {
- font-family: var(--mono);
- font-size: 12.5px;
- color: var(--accent-bright);
- text-decoration: none;
- overflow-wrap: anywhere;
-
- &:hover {
- text-decoration: underline;
- }
- }
-}
-
-.wp-env-meta {
- display: grid;
- grid-template-columns: repeat(2, 1fr);
- gap: $space-3 $space-2;
-}
-
-.wp-env-meta-item {
- .meta-label {
- display: flex;
- align-items: center;
- gap: 4px;
- font-family: var(--mono);
- font-size: 10.5px;
- letter-spacing: 0.05em;
- text-transform: uppercase;
- color: var(--text-faint);
- margin-bottom: 3px;
-
- svg {
- color: var(--text-ghost);
- }
- }
-
- .meta-value {
- font-size: 12.5px;
- color: var(--text);
-
- &.mono {
- font-family: var(--mono);
- font-size: 12px;
- }
- }
-}
-
-.wp-env-footer {
- display: flex;
- gap: $space-1;
- padding: 10px 12px;
- border-top: 1px solid var(--border-soft);
- background: transparent;
- border-radius: 0 0 var(--radius) var(--radius);
-}
-
-// Snapshot Table (SnapshotTable.jsx — now a .sk-dtable inside .wp-table-card)
-.wp-snapshot-table {
- .snapshot-name-cell {
- display: flex;
- flex-direction: column;
- gap: 3px;
- }
-
- .snapshot-name {
- font-weight: 550;
- font-size: 13px;
- color: var(--text);
- }
-
- .snapshot-tag {
- display: inline-flex;
- align-items: center;
- gap: 4px;
- font-family: var(--mono);
- font-size: 10.5px;
- color: var(--cyan);
- background: var(--cyan-bg);
- padding: 2px 7px;
- border-radius: 5px;
- width: fit-content;
- }
-
- .snapshot-desc {
- font-family: var(--mono);
- font-size: 11px;
- color: var(--text-faint);
- }
-
- .snapshot-date {
- font-family: var(--mono);
- font-size: 12px;
- color: var(--text-dim);
- }
-
- .mono {
- font-family: var(--mono);
- font-size: 12px;
- color: var(--text-dim);
- }
-
- .compressed-badge {
- display: inline-block;
- font-family: var(--mono);
- font-size: 10px;
- background: var(--green-bg);
- color: var(--green);
- padding: 1px 5px;
- border-radius: 4px;
- margin-left: $space-2;
- }
-
- .text-muted {
- color: var(--text-ghost);
- font-family: var(--mono);
- }
-
- .git-context {
- display: flex;
- align-items: center;
- gap: 6px;
- color: var(--text-dim);
-
- svg {
- color: var(--text-faint);
- flex-shrink: 0;
- }
-
- .git-context-sha {
- color: var(--accent-bright);
- background: var(--accent-bg);
- padding: 1px 6px;
- border-radius: 4px;
- font-size: 11px;
- }
-
- .commit-msg {
- font-size: 11.5px;
- color: var(--text-faint);
- margin-left: $space-1;
- }
- }
-}
-
-// Commit List
-.commit-list {
- display: flex;
- flex-direction: column;
- gap: $space-1;
- max-width: 800px;
-}
-
-.commit-item {
- display: flex;
- align-items: flex-start;
- gap: $space-3;
- padding: $space-3 $space-4;
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- transition: all 0.15s ease;
-
- &:hover {
- border-color: $border-hover;
- }
-
- &.current {
- border-color: fade($success-raw, 40%);
- background: fade($success-raw, 4%);
- }
-}
-
-.commit-icon {
- color: $text-tertiary;
- margin-top: 2px;
-
- .current-icon {
- color: $color-success;
- }
-}
-
-.commit-info {
- flex: 1;
- min-width: 0;
-}
-
-.commit-header {
- display: flex;
- align-items: center;
- gap: $space-2;
- margin-bottom: $space-1;
-}
-
-.commit-sha {
- font-size: $font-size-sm;
- font-weight: $font-weight-medium;
- color: $text-secondary;
-}
-
-.current-badge {
- font-size: $font-size-xs;
- background: $color-success;
- color: #fff;
- padding: 1px 6px;
- border-radius: $radius-sm;
-}
-
-.commit-date {
- font-size: $font-size-xs;
- color: $text-tertiary;
- margin-left: auto;
-}
-
-.commit-message {
- font-size: $font-size-sm;
- color: $text-primary;
- margin: 0;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.commit-author {
- font-size: $font-size-xs;
- color: $text-tertiary;
-}
-
-.commit-actions {
- display: flex;
- gap: $space-2;
- flex-shrink: 0;
-}
-
-.commit-message-preview {
- font-style: italic;
- color: $text-secondary;
- padding: $space-3;
- background: $bg-tertiary;
- border-radius: $radius-md;
- margin: $space-3 0;
-}
-
-// Git Commits Section
-.git-commits-section {
- margin-top: $space-6;
- padding-top: $space-6;
- border-top: 1px solid $border-subtle;
-}
-
-// Quick Actions (WP detail Overview — exclusive to this page)
-.quick-actions-grid {
- display: grid;
- grid-template-columns: repeat(2, 1fr);
- gap: $space-2;
-}
-
-.quick-action-btn {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 7px;
- padding: 10px $space-2;
- background: var(--surface-2);
- border: 1px solid var(--border-soft);
- border-radius: 8px;
- color: var(--text-dim);
- font-size: 12.5px;
- font-weight: $font-weight-medium;
- text-decoration: none;
- cursor: pointer;
- transition: background 0.14s, border-color 0.14s, color 0.14s;
-
- svg {
- color: var(--text-faint);
- flex-shrink: 0;
- transition: color 0.14s;
- }
-
- &:hover:not(:disabled) {
- background: var(--accent-bg-soft);
- border-color: var(--accent-dim);
- color: var(--text);
-
- svg {
- color: var(--accent-bright);
- }
- }
-
- &:disabled {
- opacity: 0.55;
- cursor: default;
- }
-}
-
-// Hint Box
-.hint-box {
- padding: $space-4;
- background: $bg-tertiary;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- margin-top: $space-4;
-
- p {
- margin: 0;
- color: $text-secondary;
- font-size: $font-size-sm;
-
- &:not(:last-child) {
- margin-bottom: $space-2;
- }
- }
-}
-
-// Empty State Small
-.empty-state-small {
- padding: $space-6;
- text-align: center;
- color: $text-tertiary;
-
- p {
- margin: 0;
-
- &:not(:last-child) {
- margin-bottom: $space-2;
- }
- }
-
- .hint {
- font-size: $font-size-sm;
- }
-}
-
-// Spinning animation for sync button
-@keyframes spin {
- from {
- transform: rotate(0deg);
- }
- to {
- transform: rotate(360deg);
- }
-}
-
-.spinning {
- animation: spin 1s linear infinite;
-}
-
-// ============================================
-// SKELETON LOADING STATES
-// ============================================
-
-@keyframes shimmer {
- 0% {
- background-position: -200% 0;
- }
- 100% {
- background-position: 200% 0;
- }
-}
-
-@mixin skeleton() {
- background: linear-gradient(
- 90deg,
- $bg-tertiary 25%,
- fade($border-subtle-raw, 50%) 50%,
- $bg-tertiary 75%
- );
- background-size: 200% 100%;
- animation: shimmer 1.5s infinite;
- border-radius: $radius-md;
-}
-
-.skeleton {
- @include skeleton();
-}
-
-// Skeleton Site Card
-.wp-site-card-skeleton {
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-lg;
-}
-
-.wp-site-card-skeleton-header {
- display: flex;
- align-items: center;
- gap: $space-3;
- padding: $space-4;
- border-bottom: 1px solid $border-subtle;
-}
-
-.wp-site-card-skeleton-icon {
- width: 40px;
- height: 40px;
- border-radius: $radius-md;
- @include skeleton();
-}
-
-.wp-site-card-skeleton-info {
- flex: 1;
- display: flex;
- flex-direction: column;
- gap: $space-2;
-}
-
-.wp-site-card-skeleton-name {
- width: 60%;
- height: 16px;
- @include skeleton();
-}
-
-.wp-site-card-skeleton-url {
- width: 80%;
- height: 12px;
- @include skeleton();
-}
-
-.wp-site-card-skeleton-status {
- width: 64px;
- height: 24px;
- border-radius: $radius-full;
- @include skeleton();
-}
-
-.wp-site-card-skeleton-body {
- padding: $space-4;
- display: grid;
- grid-template-columns: repeat(2, 1fr);
- gap: $space-3;
-}
-
-.wp-site-card-skeleton-meta {
- display: flex;
- flex-direction: column;
- gap: $space-1;
-}
-
-.wp-site-card-skeleton-label {
- width: 50%;
- height: 10px;
- @include skeleton();
-}
-
-.wp-site-card-skeleton-value {
- width: 70%;
- height: 14px;
- @include skeleton();
-}
-
-.wp-site-card-skeleton-footer {
- display: flex;
- gap: $space-2;
- padding: $space-3 $space-4;
- border-top: 1px solid $border-subtle;
- background: $bg-tertiary;
- border-radius: 0 0 $radius-lg $radius-lg;
-}
-
-.wp-site-card-skeleton-btn {
- flex: 1;
- height: 32px;
- @include skeleton();
-}
-
-// Skeleton Environment Card
-.wp-env-card-skeleton {
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-lg;
-}
-
-.wp-env-card-skeleton-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: $space-4;
- border-bottom: 1px solid $border-subtle;
-}
-
-.wp-env-card-skeleton-badge {
- width: 60px;
- height: 20px;
- border-radius: $radius-sm;
- @include skeleton();
-}
-
-.wp-env-card-skeleton-status {
- width: 64px;
- height: 20px;
- border-radius: $radius-sm;
- @include skeleton();
-}
-
-.wp-env-card-skeleton-body {
- padding: $space-4;
-}
-
-.wp-env-card-skeleton-url {
- width: 70%;
- height: 14px;
- margin-bottom: $space-3;
- @include skeleton();
-}
-
-.wp-env-card-skeleton-meta {
- display: grid;
- grid-template-columns: repeat(2, 1fr);
- gap: $space-2;
-}
-
-.wp-env-card-skeleton-meta-item {
- .skeleton-label {
- width: 40%;
- height: 10px;
- margin-bottom: 4px;
- @include skeleton();
- }
-
- .skeleton-value {
- width: 60%;
- height: 14px;
- @include skeleton();
- }
-}
-
-.wp-env-card-skeleton-footer {
- display: flex;
- gap: $space-2;
- padding: $space-3 $space-4;
- border-top: 1px solid $border-subtle;
- background: $bg-tertiary;
- border-radius: 0 0 $radius-lg $radius-lg;
-}
-
-// Skeleton Stat Card
-.docker-stat-card-skeleton {
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-lg;
- padding: $space-4;
- display: flex;
- flex-direction: column;
- gap: $space-2;
-}
-
-.docker-stat-card-skeleton-label {
- width: 60%;
- height: 12px;
- @include skeleton();
-}
-
-.docker-stat-card-skeleton-value {
- width: 40%;
- height: 28px;
- @include skeleton();
-}
-
-.docker-stat-card-skeleton-meta {
- width: 80%;
- height: 12px;
- @include skeleton();
-}
-
-// Skeleton Table Row
-.skeleton-table-row {
- display: flex;
- align-items: center;
- gap: $space-3;
- padding: $space-3 $space-4;
- border-bottom: 1px solid $border-subtle;
-
- .skeleton-cell {
- height: 16px;
- @include skeleton();
-
- &.cell-name { width: 25%; }
- &.cell-tag { width: 15%; }
- &.cell-size { width: 10%; }
- &.cell-date { width: 15%; }
- &.cell-actions { width: 20%; margin-left: auto; }
- }
-}
-
-// Tab Content Loading
-.tab-loading {
- display: flex;
- flex-direction: column;
- gap: $space-4;
- padding: $space-4;
-}
-
-.tab-loading-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- margin-bottom: $space-2;
-}
-
-.tab-loading-title {
- width: 120px;
- height: 24px;
- @include skeleton();
-}
-
-.tab-loading-btn {
- width: 140px;
- height: 36px;
- border-radius: $radius-md;
- @include skeleton();
-}
-
-// ============================================
-// WORDPRESS DETAIL PAGE SKELETON
-// Mirrors the real page chrome + Overview tab layout.
-// ============================================
-.wp-detail-page--skeleton {
- .sk-topbar-skeleton {
- display: flex;
- align-items: center;
- gap: 14px;
- min-height: 60px;
- padding: 10px $space-4;
- border-bottom: 1px solid var(--border-soft);
-
- &__icon {
- width: 18px;
- height: 18px;
- border-radius: 4px;
- @include skeleton();
- }
-
- &__title {
- width: 160px;
- height: 16px;
- border-radius: 4px;
- @include skeleton();
- }
-
- &__spacer { flex: 1; }
-
- &__actions {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- flex-shrink: 0;
- }
-
- &__btn {
- width: 90px;
- height: 32px;
- border-radius: $radius-md;
- @include skeleton();
-
- &--primary { width: 110px; }
- }
- }
-
- .wp-detail-skeleton-repo {
- width: 220px;
- height: 30px;
- border-radius: $radius-full;
- @include skeleton();
- }
-
- .app-detail-tab-skeleton {
- width: 80px;
- height: 32px;
- border-radius: 7px;
- @include skeleton();
- }
-
- .wp-kpis--skeleton {
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
- gap: $space-4;
- }
-
- .wp-detail-skeleton-kpi {
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- padding: $space-4 $space-5;
- display: flex;
- flex-direction: column;
- gap: $space-2;
-
- &__label {
- width: 70%;
- height: 11px;
- border-radius: 3px;
- @include skeleton();
- }
-
- &__value {
- width: 45%;
- height: 26px;
- border-radius: 4px;
- @include skeleton();
- }
- }
-
- .wp-detail-skeleton-panel {
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
-
- .app-panel-header {
- display: flex;
- flex-direction: column;
- align-items: flex-start;
- gap: 2px;
- padding: 12px 17px;
- border-bottom: 1px solid var(--border-soft);
- }
-
- .app-panel-body {
- padding: $space-4 17px;
- }
- }
-
- .wp-detail-skeleton-chart {
- height: 250px;
- border-radius: $radius-md;
- @include skeleton();
- }
-
- .wp-detail-skeleton-activity {
- display: flex;
- flex-direction: column;
- gap: $space-3;
-
- &__row {
- display: flex;
- align-items: center;
- gap: $space-3;
- }
-
- &__lines {
- flex: 1;
- min-width: 0;
- }
- }
-
- .wp-detail-skeleton-rows {
- display: flex;
- flex-direction: column;
- gap: $space-3;
- }
-
- .wp-detail-skeleton-row {
- display: flex;
- justify-content: space-between;
- align-items: center;
- gap: $space-4;
- }
-}
-
-// ============================================
-// ERROR STATES
-// ============================================
-
-.error-boundary,
-.error-state {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: $space-8;
- text-align: center;
- min-height: 200px;
-}
-
-.error-boundary-icon,
-.error-state-icon {
- color: $color-danger;
- margin-bottom: $space-4;
- padding: $space-3;
- background: fade($danger-raw, 10%);
- border-radius: 50%;
-}
-
-.error-boundary h3,
-.error-state-title {
- font-size: $font-size-lg;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- margin: 0 0 $space-2;
-}
-
-.error-boundary-message,
-.error-state-message {
- font-size: $font-size-sm;
- color: $text-secondary;
- margin: 0 0 $space-4;
- max-width: 400px;
-}
-
-.error-state-compact {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-3 $space-4;
- background: fade($danger-raw, 8%);
- border: 1px solid fade($danger-raw, 20%);
- border-radius: $radius-md;
- color: $color-danger;
- font-size: $font-size-sm;
-
- svg {
- flex-shrink: 0;
- }
-
- span {
- flex: 1;
- }
-
- .btn {
- flex-shrink: 0;
- }
-}
-
-// ============================================
-// CONFIRM DIALOG ENHANCEMENTS
-// ============================================
-
-.confirm-dialog-details {
- margin-top: $space-3;
- padding: $space-3;
- background: $bg-tertiary;
- border-radius: $radius-md;
- font-size: $font-size-sm;
- color: $text-secondary;
- text-align: left;
-
- ul {
- margin: 0;
- padding-left: $space-4;
-
- li {
- margin-bottom: $space-1;
-
- &:last-child {
- margin-bottom: 0;
- }
- }
- }
-
- strong {
- color: $text-primary;
- }
-
- code {
- background: $bg-code;
- padding: 2px 6px;
- border-radius: 3px;
- font-family: $font-family-mono;
- font-size: 0.9em;
- }
-}
-
-// Environment Preview URL in Create Modal
-.env-preview-url {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-3;
- background: fade($success-raw, 8%);
- border: 1px solid fade($success-raw, 20%);
- border-radius: $radius-md;
- margin-bottom: $space-4;
-
- .preview-label {
- font-size: $font-size-xs;
- color: $text-secondary;
- }
-
- .preview-url {
- font-family: $font-family-mono;
- font-size: $font-size-sm;
- color: $color-success;
- font-weight: $font-weight-medium;
- }
-}
-
-.form-hint-domain {
- code {
- background: $bg-code;
- padding: 2px 6px;
- border-radius: 3px;
- font-family: $font-family-mono;
- font-size: 0.9em;
- }
-}
-
-.confirm-dialog-input {
- margin-top: $space-4;
- text-align: left;
-
- label {
- display: block;
- font-size: $font-size-sm;
- color: $text-secondary;
- margin-bottom: $space-2;
-
- strong {
- color: $text-primary;
- font-family: $font-family-mono;
- }
- }
-
- input {
- width: 100%;
- padding: $space-3;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- font-size: $font-size-base;
- background: $bg-input;
- color: $text-primary;
-
- &:focus {
- outline: none;
- border-color: $color-primary;
- box-shadow: 0 0 0 3px fade($accent-primary-raw, 15%);
- }
-
- &::placeholder {
- color: $text-tertiary;
- }
- }
-}
-
-// ============================================
-// RESOURCE ADVISORY - INLINE CAPACITY WARNING
-// ============================================
-// Replaces the old blocked-state gate. Warns at the point of action and lets
-// the operator proceed; nothing here hides a control.
-
-.resource-advisory {
- display: flex;
- align-items: flex-start;
- gap: $space-3;
- padding: $space-4;
- margin-bottom: $space-4;
- background: fade($warning-raw, 8%);
- border: 1px solid $color-warning;
- border-radius: $radius-md;
-
- &__icon {
- flex-shrink: 0;
- margin-top: 2px;
- color: $color-warning;
- }
-
- &__title {
- font-size: $font-size-sm;
- font-weight: $font-weight-bold;
- color: $text-primary;
- margin-bottom: $space-1;
- }
-
- &__text {
- font-size: $font-size-sm;
- color: $text-secondary;
- line-height: $line-height-normal;
- margin: 0;
- }
-
- &__list {
- margin: $space-2 0 0;
- padding-left: $space-4;
- font-size: $font-size-xs;
- color: $text-tertiary;
- }
-}
-
-// One-time admin credentials banner (after site create)
-.wp-creds-banner {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: $space-4;
- margin: 0 $space-4 $space-4;
- padding: $space-4;
- background: fade($success-raw, 8%);
- border: 1px solid fade($success-raw, 25%);
- border-radius: $radius-md;
-
- .wp-creds-banner-text {
- display: flex;
- flex-direction: column;
- gap: $space-1;
- font-size: $font-size-sm;
-
- code {
- font-family: $font-family-mono;
- background: $bg-tertiary;
- padding: 1px 6px;
- border-radius: 3px;
- }
- }
-}
-
-// ============================================
-// SITE HEALTH + SSL PANEL HELPERS (Overview tab)
-// ============================================
-
-.app-health-stat {
- display: inline-flex;
- align-items: center;
- gap: $space-2;
-}
-
-.app-health-disk {
- margin-top: $space-4;
-
- .app-info-label {
- display: block;
- margin-bottom: $space-2;
- }
-}
-
-.ssl-action-btn {
- margin-top: $space-3;
-}
-
-// Plugin / Theme card grids (WP detail — replace the dense asset tables)
-.wp-detail-page {
- .wp-asset-grid {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
- gap: 14px;
- }
-
- .wp-asset-card {
- display: flex;
- gap: 13px;
- align-items: flex-start;
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- padding: 16px;
- transition: border-color 0.15s;
-
- &:hover { border-color: var(--border-strong); }
- &.is-active { border-color: var(--accent-dim); }
-
- &__body { flex: 1; min-width: 0; }
- &__name { font-weight: 600; font-size: 14px; }
- &__sub {
- font-family: var(--mono);
- font-size: 11px;
- color: var(--text-faint);
- margin-top: 2px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- &__foot {
- display: flex;
- align-items: center;
- gap: 10px;
- margin-top: 12px;
- flex-wrap: wrap;
- }
- &__ver { font-family: var(--mono); font-size: 11px; color: var(--text-faint); }
-
- &__toggle {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 6px;
- flex-shrink: 0;
- }
- &__state {
- font-family: var(--mono);
- font-size: 10px;
- text-transform: uppercase;
- letter-spacing: 0.04em;
- color: var(--text-faint);
- &.is-on { color: var(--green); }
- }
- }
-
- .wp-update-flag {
- display: inline-flex;
- align-items: center;
- gap: 5px;
- font-family: var(--mono);
- font-size: 10.5px;
- color: var(--amber);
- background: var(--amber-bg);
- padding: 2px 7px;
- border-radius: 5px;
- border: none;
- cursor: pointer;
- transition: opacity 0.12s;
-
- &: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 {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
- gap: 14px;
- }
-
- .wp-theme-card {
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- overflow: hidden;
- transition: border-color 0.15s, transform 0.15s;
-
- &:hover { border-color: var(--border-strong); transform: translateY(-2px); }
- &.is-active { border-color: var(--accent-dim); }
-
- &__shot {
- position: relative;
- height: 128px;
- display: grid;
- place-items: center;
- border-bottom: 1px solid var(--border-soft);
- background:
- repeating-linear-gradient(135deg, rgba(255, 255, 255, 0.018) 0 12px, transparent 12px 24px),
- var(--surface-2);
-
- svg { color: var(--text-ghost); }
- .pill { position: absolute; top: 10px; right: 10px; }
- }
-
- &__meta { padding: 14px 16px; }
- &__name { font-weight: 600; font-size: 14px; }
- &__sub {
- font-family: var(--mono);
- font-size: 11px;
- color: var(--text-faint);
- margin-top: 3px;
- }
- &__actions {
- display: flex;
- align-items: center;
- gap: 8px;
- margin-top: 12px;
- }
- &__current {
- font-family: var(--mono);
- font-size: 11px;
- color: var(--green);
- }
- }
-}
-
-// Change Site URL modal (URL-swap tool)
-.wp-url-swap {
- display: flex;
- flex-direction: column;
- gap: 16px;
- padding: 4px 0 8px;
-
- &__warning {
- display: flex;
- gap: 10px;
- padding: 12px 14px;
- border-radius: var(--radius);
- background: var(--surface-2);
- border: 1px solid var(--border-soft);
- font-size: 12.5px;
- line-height: 1.5;
- color: var(--text-faint);
-
- svg { flex-shrink: 0; color: var(--amber); margin-top: 1px; }
- }
-
- &__fromto {
- display: flex;
- align-items: center;
- gap: 10px;
- flex-wrap: wrap;
-
- code {
- font-family: var(--mono);
- font-size: 12px;
- padding: 4px 8px;
- border-radius: 6px;
- background: var(--surface-2);
- border: 1px solid var(--border-soft);
- color: var(--text-faint);
- word-break: break-all;
-
- &.is-new { color: var(--green); border-color: var(--accent-dim); }
- }
- svg { color: var(--text-ghost); flex-shrink: 0; }
- }
-
- &__keep {
- display: flex;
- align-items: flex-start;
- gap: 10px;
- cursor: pointer;
-
- > span {
- display: flex;
- flex-direction: column;
- font-size: 13px;
- font-weight: 500;
- }
- small {
- font-weight: 400;
- font-size: 11.5px;
- color: var(--text-faint);
- margin-top: 2px;
- }
- }
-
- &__preview {
- border-top: 1px solid var(--border-soft);
- padding-top: 12px;
- }
-
- &__preview-total {
- font-size: 13px;
- font-weight: 600;
- color: var(--text);
- margin-bottom: 8px;
- }
-
- &__preview-pairs {
- list-style: none;
- margin: 0;
- padding: 0;
- display: flex;
- flex-direction: column;
- gap: 6px;
-
- li {
- display: flex;
- align-items: center;
- gap: 8px;
- font-size: 11.5px;
-
- code {
- font-family: var(--mono);
- color: var(--text-faint);
- word-break: break-all;
- }
- svg { color: var(--text-ghost); flex-shrink: 0; }
- }
- }
-
- &__count {
- margin-left: auto;
- font-family: var(--mono);
- font-size: 11px;
- padding: 1px 8px;
- border-radius: 999px;
- background: var(--surface-2);
- border: 1px solid var(--border-soft);
- color: var(--text-faint);
- flex-shrink: 0;
- }
-
- &__preview-error {
- font-size: 12.5px;
- color: var(--red);
- }
-
- &__result {
- display: flex;
- gap: 10px;
- align-items: center;
- font-size: 13px;
-
- svg { color: var(--green); flex-shrink: 0; }
- code { font-family: var(--mono); color: var(--green); word-break: break-all; }
- }
-
- &__dns-manual {
- display: flex;
- flex-direction: column;
- gap: 6px;
- font-size: 12.5px;
- }
-
- &__record {
- font-family: var(--mono);
- font-size: 12px;
- padding: 8px 10px;
- border-radius: 6px;
- background: var(--surface-2);
- border: 1px solid var(--border-soft);
- color: var(--text);
- word-break: break-all;
- }
-}
-
-// Pipelines list — the few cells the shared list does not already style.
-.wp-projects-page {
- &__envs {
- display: inline-flex;
- align-items: center;
- gap: 5px;
- flex-wrap: wrap;
- }
-
- &__envcount {
- display: inline-flex;
- align-items: center;
- gap: 4px;
- margin-right: $space-1;
- color: $text-secondary;
- font-family: var(--mono);
- font-size: 12px;
- }
-
- &__git {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- color: $text-secondary;
- font-size: $font-size-sm;
-
- svg { color: $text-tertiary; }
- }
-}
diff --git a/builtin-extensions/serverkit-wordpress/plugin.json b/builtin-extensions/serverkit-wordpress/plugin.json
deleted file mode 100644
index f636d39b..00000000
--- a/builtin-extensions/serverkit-wordpress/plugin.json
+++ /dev/null
@@ -1,72 +0,0 @@
-{
- "name": "serverkit-wordpress",
- "display_name": "WordPress",
- "version": "1.0.0",
- "description": "The full WordPress suite, covering site provisioning, plugin library, environments/pipelines, updates, security hardening, vulnerability scanning, analytics and reports. Ships bundled and installed by default (a flagship), and can be uninstalled to slim the core.",
- "author": "ServerKit",
- "license": "MIT",
- "category": "integration",
- "homepage": "https://github.com/jhd3197/ServerKit",
- "permissions": ["shell", "filesystem", "network", "docker", "database"],
- "min_panel_version": "1.7.0",
- "featured": true,
- "feature_score": 80,
- "entry_point": "wordpress:wordpress_bp",
- "url_prefix": "/api/v1/wordpress",
- "extra_blueprints": [
- {
- "module": "wordpress_sites",
- "attr": "wordpress_sites_bp",
- "url_prefix": "/api/v1/wordpress"
- },
- {
- "module": "environment_pipeline",
- "attr": "environment_pipeline_bp",
- "url_prefix": "/api/v1/wordpress/projects"
- },
- {
- "module": "environment_pipeline",
- "attr": "environment_pipeline_bp",
- "url_prefix": "/api/v1/wordpress/pipelines",
- "name": "environment_pipeline_pipelines"
- },
- {
- "module": "wp_ssh_import",
- "attr": "wp_ssh_import_bp",
- "url_prefix": "/api/v1/wordpress"
- }
- ],
- "jobs": [
- {
- "kind": "wordpress.ssh_import.run",
- "handler": "wp_ssh_import_service:run_wp_ssh_import_job"
- }
- ],
- "core_hooks": "core_hooks:register",
- "icon": "<path d=\"M12 2a10 10 0 100 20 10 10 0 000-20zm-8 10a8 8 0 011.4-4.5l4.7 12.9A8 8 0 014 12zm8 8c-.8 0-1.6-.1-2.3-.3l2.4-7 2.5 6.8.1.1A8 8 0 0112 20zm1.1-11.8c.5 0 .9-.1.9-.1.4 0 .4-.6-.1-.6 0 0-1.4.1-2.3.1-.8 0-2.2-.1-2.2-.1-.5 0-.6.6-.1.6 0 0 .4.1.9.1l1.3 3.6-1.9 5.6L6.6 8.2c.5 0 .9-.1.9-.1.4 0 .4-.6-.1-.6 0 0-1.4.1-2.3.1h-.4A8 8 0 0112 4a8 8 0 016.5 3.3h-.3c-.8 0-1.4.7-1.4 1.5 0 .7.4 1.3.8 2 .3.6.7 1.3.7 2.3 0 .7-.3 1.6-.6 2.7l-.8 2.7-2.9-8.8z\"/>",
- "contributions": {
- "nav": [
- {
- "id": "wordpress",
- "label": "WordPress",
- "route": "/wordpress",
- "category": "infrastructure",
- "icon": "<circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z\"/><path d=\"M3.5 9h17M3.5 15h17\"/>"
- }
- ],
- "routes": [
- { "path": "wordpress/*", "component": "WordPressExtension" }
- ],
- "page_titles": {
- "/wordpress": "WordPress Sites",
- "/wordpress/plugins/library": "WordPress Plugin Library",
- "/wordpress/pipelines": "WordPress Pipelines",
- "/wordpress/ssh-import": "Import WordPress over SSH"
- },
- "command_palette": [
- { "label": "WordPress", "path": "/wordpress", "category": "Pages", "keywords": "wp sites" },
- { "label": "Import WordPress over SSH", "path": "/wordpress/ssh-import", "category": "Pages", "keywords": "wp migrate pull import ssh" },
- { "label": "WordPress Pipelines", "path": "/wordpress/pipelines", "category": "Pages", "keywords": "wp environments projects pipeline" }
- ]
- }
-}
diff --git a/frontend/src/plugins/serverkit-wordpress/WordPressSshImport.jsx b/frontend/src/plugins/serverkit-wordpress/WordPressSshImport.jsx
deleted file mode 100644
index e5ad2418..00000000
--- a/frontend/src/plugins/serverkit-wordpress/WordPressSshImport.jsx
+++ /dev/null
@@ -1,299 +0,0 @@
-// Import a live WordPress site over SSH (Panel Improvements #3).
-//
-// Three-step surface rendered inside the WordPress tab group:
-// 1. Connection — host/port/user + password-or-key + remote WP path.
-// 2. Probe — the backend captures the SSH host-key fingerprint and reads
-// site facts (wp-config, version, size). The operator explicitly trusts
-// the fingerprint before anything else touches the box.
-// 3. Import — enqueues the pull-import job and polls its step log.
-//
-// After sync this file lives at frontend/src/plugins/serverkit-wordpress/, so
-// shared pieces come from the serverkit-sdk surface like other extensions.
-import { useEffect, useRef, useState } from 'react';
-import { Link } from 'react-router-dom';
-import { api, Spinner, useToast, Button, Input, Label } from 'serverkit-sdk';
-
-const POLL_MS = 2500;
-
-export default function WordPressSshImport() {
- const toast = useToast();
- const [conn, setConn] = useState({
- host: '', port: '22', username: 'root',
- authMethod: 'key', password: '', privateKey: '',
- wpPath: '/var/www/html',
- });
- const [probing, setProbing] = useState(false);
- const [probe, setProbe] = useState(null); // probe result (incl. fingerprint)
- const [trusted, setTrusted] = useState(false); // operator confirmed the host key
- const [target, setTarget] = useState({ siteName: '', adminEmail: '', oldUrl: '' });
- const [starting, setStarting] = useState(false);
- const [job, setJob] = useState(null); // { id, status, steps, result, error }
- const pollRef = useRef(null);
-
- useEffect(() => () => clearInterval(pollRef.current), []);
-
- const authPayload = () => (conn.authMethod === 'password'
- ? { password: conn.password }
- : { private_key: conn.privateKey });
-
- const handleProbe = async () => {
- setProbing(true);
- setProbe(null);
- setTrusted(false);
- try {
- const result = await api.request('/wordpress/ssh-import/probe', {
- method: 'POST',
- body: {
- host: conn.host.trim(),
- port: parseInt(conn.port, 10) || 22,
- username: conn.username.trim(),
- auth: authPayload(),
- wp_path: conn.wpPath.trim(),
- },
- });
- setProbe(result);
- setTarget(t => ({ ...t, oldUrl: t.oldUrl || result.site_url || '' }));
- } catch (error) {
- toast.error(error.message || 'Probe failed');
- } finally {
- setProbing(false);
- }
- };
-
- const pollJob = async (jobId) => {
- try {
- const status = await api.request(`/wordpress/ssh-import/${jobId}`);
- setJob(status);
- if (['completed', 'failed', 'dead'].includes(status.status)) {
- clearInterval(pollRef.current);
- pollRef.current = null;
- if (status.status === 'completed') {
- toast.success('WordPress site imported successfully');
- } else {
- toast.error(status.error || 'Import failed — see the step log');
- }
- }
- } catch {
- /* transient poll error — keep polling */
- }
- };
-
- const handleStart = async () => {
- if (!trusted) { toast.error('Confirm the host-key fingerprint first'); return; }
- if (!target.siteName.trim()) { toast.error('New site name is required'); return; }
- setStarting(true);
- try {
- const res = await api.request('/wordpress/ssh-import', {
- method: 'POST',
- body: {
- connection: {
- host: conn.host.trim(),
- port: parseInt(conn.port, 10) || 22,
- username: conn.username.trim(),
- auth: authPayload(),
- },
- fingerprint: probe.host_key_fingerprint,
- target: {
- site_name: target.siteName.trim(),
- admin_email: target.adminEmail.trim(),
- },
- options: {
- wp_path: conn.wpPath.trim(),
- old_url: target.oldUrl.trim() || undefined,
- },
- },
- });
- setJob({ id: res.job_id, status: 'pending', steps: [] });
- pollRef.current = setInterval(() => pollJob(res.job_id), POLL_MS);
- pollJob(res.job_id);
- } catch (error) {
- toast.error(error.message || 'Failed to start the import');
- } finally {
- setStarting(false);
- }
- };
-
- const running = job && !['completed', 'failed', 'dead'].includes(job.status);
- const canProbe = conn.host.trim() && conn.username.trim() && conn.wpPath.trim()
- && (conn.authMethod === 'password' ? conn.password : conn.privateKey);
- const facts = probe && [
- ['WordPress version', probe.wp_version || 'unknown'],
- ['Site URL', probe.site_url || 'unknown'],
- ['Database', probe.db_name],
- ['Table prefix', probe.table_prefix],
- ['Docroot size', probe.docroot_size_kb != null
- ? `${(probe.docroot_size_kb / 1024).toFixed(1)} MB` : 'unknown'],
- ['WP-CLI on source', probe.has_wp_cli ? 'yes' : 'no (fallbacks used)'],
- ];
-
- return (
- <div className="sk-tabgroup__inner wp-ssh-import">
- <div className="page-section">
- <h2 className="text-lg font-semibold">Import a live site over SSH</h2>
- <p className="text-sm text-muted-foreground">
- Point at any WordPress install you can reach over SSH. The panel pulls the
- files and database through the tunnel and rebuilds it as a managed site —
- nothing is installed on the source server.
- </p>
- </div>
-
- {/* Step 1 — connection */}
- <div className="card p-4 mb-4">
- <h3 className="font-medium mb-3">1. Source server</h3>
- <div className="grid grid-cols-2 gap-4">
- <div className="form-group">
- <Label>Host <span className="required">*</span></Label>
- <Input value={conn.host} disabled={running}
- onChange={e => setConn({ ...conn, host: e.target.value })}
- placeholder="203.0.113.10 or wp.example.com" />
- </div>
- <div className="form-group">
- <Label>Port</Label>
- <Input value={conn.port} disabled={running}
- onChange={e => setConn({ ...conn, port: e.target.value })}
- placeholder="22" />
- </div>
- <div className="form-group">
- <Label>Username <span className="required">*</span></Label>
- <Input value={conn.username} disabled={running}
- onChange={e => setConn({ ...conn, username: e.target.value })}
- placeholder="root" />
- </div>
- <div className="form-group">
- <Label>WordPress path <span className="required">*</span></Label>
- <Input value={conn.wpPath} disabled={running}
- onChange={e => setConn({ ...conn, wpPath: e.target.value })}
- placeholder="/var/www/html" />
- <span className="form-hint">Absolute path of the directory containing wp-config.php.</span>
- </div>
- </div>
- <div className="form-group">
- <Label>Authentication</Label>
- <div className="flex gap-4 mb-2">
- <label className="flex items-center gap-2 text-sm">
- <input type="radio" checked={conn.authMethod === 'key'} disabled={running}
- onChange={() => setConn({ ...conn, authMethod: 'key' })} />
- Private key
- </label>
- <label className="flex items-center gap-2 text-sm">
- <input type="radio" checked={conn.authMethod === 'password'} disabled={running}
- onChange={() => setConn({ ...conn, authMethod: 'password' })} />
- Password
- </label>
- </div>
- {conn.authMethod === 'key' ? (
- <>
- <textarea
- className="w-full font-mono text-xs"
- rows={5}
- value={conn.privateKey}
- disabled={running}
- onChange={e => setConn({ ...conn, privateKey: e.target.value })}
- placeholder={'-----BEGIN OPENSSH PRIVATE KEY-----\n…'}
- />
- <span className="form-hint">Used for this import only — never stored.</span>
- </>
- ) : (
- <>
- <Input type="password" value={conn.password} disabled={running}
- onChange={e => setConn({ ...conn, password: e.target.value })}
- placeholder="SSH password" />
- <span className="form-hint">Used for this import only — never stored. Password auth requires the sshpass package on the panel host.</span>
- </>
- )}
- </div>
- <Button onClick={handleProbe} disabled={!canProbe || probing || running}>
- {probing ? <><Spinner size="sm" /> Probing…</> : 'Probe server'}
- </Button>
- </div>
-
- {/* Step 2 — facts + host-key trust */}
- {probe && (
- <div className="card p-4 mb-4">
- <h3 className="font-medium mb-3">2. Confirm the host</h3>
- <div className="form-group">
- <Label>SSH host-key fingerprint ({probe.host_key_type})</Label>
- <code className="block font-mono text-xs break-all">{probe.host_key_fingerprint}</code>
- <span className="form-hint">
- Compare against the server you expect (ssh-keygen -lf on the source).
- Every step of the import is pinned to this exact key.
- </span>
- </div>
- <table className="text-sm">
- <tbody>
- {facts.map(([k, v]) => (
- <tr key={k}>
- <td className="pr-4 text-muted-foreground">{k}</td>
- <td className="font-mono">{String(v)}</td>
- </tr>
- ))}
- </tbody>
- </table>
- <label className="flex items-center gap-2 text-sm mt-3">
- <input type="checkbox" checked={trusted} disabled={running}
- onChange={e => setTrusted(e.target.checked)} />
- I recognize this fingerprint — trust this host for the import
- </label>
- </div>
- )}
-
- {/* Step 3 — target + run */}
- {probe && (
- <div className="card p-4 mb-4">
- <h3 className="font-medium mb-3">3. New managed site</h3>
- <div className="grid grid-cols-2 gap-4">
- <div className="form-group">
- <Label>Site name <span className="required">*</span></Label>
- <Input value={target.siteName} disabled={running}
- onChange={e => setTarget({ ...target, siteName: e.target.value })}
- placeholder="my-migrated-site" />
- <span className="form-hint">Letters, numbers, and hyphens only.</span>
- </div>
- <div className="form-group">
- <Label>Admin email</Label>
- <Input type="email" value={target.adminEmail} disabled={running}
- onChange={e => setTarget({ ...target, adminEmail: e.target.value })}
- placeholder="[email protected]" />
- </div>
- <div className="form-group">
- <Label>Original site URL</Label>
- <Input value={target.oldUrl} disabled={running}
- onChange={e => setTarget({ ...target, oldUrl: e.target.value })}
- placeholder="https://old-site.com" />
- <span className="form-hint">Rewritten to the new local address after import (detected automatically when possible).</span>
- </div>
- </div>
- <Button onClick={handleStart} disabled={!trusted || starting || running}>
- {starting ? <><Spinner size="sm" /> Starting…</> : 'Pull and import'}
- </Button>
- </div>
- )}
-
- {/* Job progress */}
- {job && (
- <div className="card p-4 mb-4">
- <h3 className="font-medium mb-3">
- Import job #{job.id} — {job.status}
- {running && <Spinner size="sm" />}
- </h3>
- <ul className="text-sm font-mono space-y-1">
- {(job.steps || []).map((s, i) => (
- <li key={i}>
- <span className="text-muted-foreground">[{s.step}]</span> {s.message}
- </li>
- ))}
- </ul>
- {job.status === 'failed' && job.error && (
- <p className="text-sm text-destructive mt-2">{job.error}</p>
- )}
- {job.status === 'completed' && (
- <p className="text-sm mt-2">
- Done. <Link to="/wordpress" className="underline">Open the WordPress sites list</Link>
- {job.result?.new_url && <> — new address: <code>{job.result.new_url}</code></>}
- </p>
- )}
- </div>
- )}
- </div>
- );
-}
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/ActivityFeed.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/ActivityFeed.jsx
deleted file mode 100644
index 6be25a8a..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/ActivityFeed.jsx
+++ /dev/null
@@ -1,130 +0,0 @@
-import { useState, useEffect } from 'react';
-import { ArrowUpRight, ArrowDownLeft, Database, GitBranch, Lock, Unlock, Trash2, Play, Square, RefreshCw, Camera, AlertCircle } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { formatRelativeTime } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Badge } from 'serverkit-sdk';
-import { Skeleton } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-
-const ACTION_ICONS = {
- create: Play,
- deploy: GitBranch,
- promote: ArrowUpRight,
- sync: ArrowDownLeft,
- lock: Lock,
- unlock: Unlock,
- destroy: Trash2,
- snapshot_created: Camera,
- snapshot_restored: Database,
- started: Play,
- stopped: Square,
- restarted: RefreshCw
-};
-
-const ACTION_BADGE_VARIANTS = {
- create: 'success',
- deploy: 'info',
- promote: 'default',
- sync: 'info',
- lock: 'warning',
- unlock: 'secondary',
- destroy: 'destructive',
- snapshot_created: 'info',
- snapshot_restored: 'warning',
- started: 'success',
- stopped: 'secondary',
- restarted: 'info'
-};
-
-const ActivityFeed = ({ projectId, envId, limit = 20, compact = false }) => {
- const [activities, setActivities] = useState([]);
- const [loading, setLoading] = useState(true);
- const [total, setTotal] = useState(0);
-
- useEffect(() => {
- loadActivities();
- }, [projectId, envId]);
-
- async function loadActivities() {
- setLoading(true);
- try {
- const params = { limit };
- if (envId) params.env_id = envId;
- const data = await wordpressApi.getProjectActivity(projectId, params);
- setActivities(data.activities || []);
- setTotal(data.total || 0);
- } catch (err) {
- console.error('Failed to load activities:', err);
- } finally {
- setLoading(false);
- }
- }
-
- const feedSkeleton = (
- <>
- {[1, 2, 3].map(i => (
- <div key={i} className="activity-item-skeleton">
- <Skeleton variant="circle" width={32} height={32} />
- <div className="skeleton-stack">
- <Skeleton variant="line" width="60%" />
- <Skeleton variant="line" width="40%" />
- </div>
- </div>
- ))}
- </>
- );
-
- if (!loading && activities.length === 0) {
- return (
- <div className="activity-feed-empty">
- <p>No activity recorded yet.</p>
- </div>
- );
- }
-
- return (
- <SkeletonBoundary
- className={`activity-feed ${compact ? 'compact' : ''}`.trim()}
- loading={loading}
- skeleton={feedSkeleton}
- >
- {activities.length > 0 && activities.map(activity => {
- const Icon = ACTION_ICONS[activity.action] || AlertCircle;
- const colorClass = ACTION_BADGE_VARIANTS[activity.action] || 'secondary';
-
- return (
- <div key={activity.id} className="activity-item">
- <div className={`activity-icon ${colorClass}`}>
- <Icon size={14} />
- </div>
- <div className="activity-content">
- <span className="activity-description">
- {activity.description || `${activity.action} performed`}
- </span>
- {activity.status === 'failed' && activity.error_message && (
- <span className="activity-error">{activity.error_message}</span>
- )}
- </div>
- <div className="activity-meta">
- <span className="activity-time">{formatRelativeTime(activity.created_at)}</span>
- {activity.status === 'failed' && (
- <Badge variant="destructive">Failed</Badge>
- )}
- {activity.status === 'running' && (
- <Badge variant="info">Running</Badge>
- )}
- </div>
- </div>
- );
- })}
- {total > activities.length && !compact && (
- <Button variant="ghost" size="sm" className="activity-load-more" onClick={loadActivities}>
- Load more
- </Button>
- )}
- </SkeletonBoundary>
- );
-};
-
-export default ActivityFeed;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/AttachDomainModal.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/AttachDomainModal.jsx
deleted file mode 100644
index a12e5a85..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/AttachDomainModal.jsx
+++ /dev/null
@@ -1,130 +0,0 @@
-import { useState } from 'react';
-import { Globe, AlertTriangle, CheckCircle2 } from 'lucide-react';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { Switch } from 'serverkit-sdk';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-
-// Attach a user-owned custom domain to a site: auto-create the DNS A record (or
-// show the exact record to add manually), optional HTTPS, then migrate the site
-// URL to it via the URL-swap tool. Shows the result inline so a manual DNS
-// record can be read/copied.
-export default function AttachDomainModal({ site, onClose, onChanged }) {
- const toast = useToast();
- const [domain, setDomain] = useState('');
- const [issueSsl, setIssueSsl] = useState(false);
- const [attaching, setAttaching] = useState(false);
- const [result, setResult] = useState(null);
-
- const valid = /^[a-z0-9.-]+\.[a-z]{2,}$/i.test(domain.trim());
-
- async function handleAttach(e) {
- e?.preventDefault();
- if (!valid || attaching) return;
- setAttaching(true);
- toast.info('Attaching domain — creating DNS and moving the site…', { duration: 5000 });
- try {
- const res = await wordpressApi.attachDomain(site.id, { domain: domain.trim(), issueSsl });
- if (res.success) {
- setResult(res);
- if (res.dns?.created) toast.success(`DNS A record created via ${res.dns.provider}`);
- else toast.warning('Domain attached — add the DNS record shown to finish.', { duration: 7000 });
- onChanged?.();
- } else {
- toast.error(res.error || 'Failed to attach domain');
- }
- } catch (err) {
- toast.error(err.message || 'Failed to attach domain');
- } finally {
- setAttaching(false);
- }
- }
-
- const rec = result?.dns?.record;
-
- return (
- <Modal open onClose={() => !attaching && onClose()} title={<><Globe size={18} /> Add Custom Domain</>}>
- {!result ? (
- <form onSubmit={handleAttach}>
- <div className="wp-url-swap">
- <div className="wp-url-swap__warning">
- <AlertTriangle size={18} aria-hidden="true" />
- <span>
- Points a domain you own at this site. If a connected DNS provider
- manages it, the A record is created automatically — otherwise
- you&apos;ll get the exact record to add. The site URL is then
- migrated to the domain (serialization-safe).
- </span>
- </div>
-
- <div className="form-group">
- <Label htmlFor="wp-domain">Domain</Label>
- <Input
- id="wp-domain"
- type="text"
- value={domain}
- onChange={(e) => setDomain(e.target.value)}
- placeholder="example.com"
- disabled={attaching}
- autoFocus
- />
- <span className="form-hint">A domain or subdomain you control, without http://</span>
- </div>
-
- <label className="wp-url-swap__keep">
- <Switch checked={issueSsl} onCheckedChange={setIssueSsl} disabled={attaching} />
- <span>
- Set up HTTPS now
- <small>Requests a Let&apos;s Encrypt certificate. Needs DNS to already resolve to this server.</small>
- </span>
- </label>
- </div>
-
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose} disabled={attaching}>Cancel</Button>
- <Button type="submit" disabled={!valid || attaching}>
- {attaching ? 'Attaching…' : 'Attach Domain'}
- </Button>
- </div>
- </form>
- ) : (
- <>
- <div className="wp-url-swap">
- <div className="wp-url-swap__result">
- <CheckCircle2 size={18} aria-hidden="true" />
- <span>Site is now at <code>{result.url}</code></span>
- </div>
-
- {result.dns?.created ? (
- <div className="form-hint">
- DNS A record created automatically via {result.dns.provider}
- {result.dns.zone ? ` (zone ${result.dns.zone})` : ''}.
- </div>
- ) : (
- <div className="wp-url-swap__dns-manual">
- <strong>Add this DNS record to finish:</strong>
- {rec?.value ? (
- <code className="wp-url-swap__record">
- {rec.type}&nbsp;&nbsp;{rec.name}&nbsp;→&nbsp;{rec.value}
- </code>
- ) : (
- <div className="form-hint">{result.dns?.message}</div>
- )}
- </div>
- )}
-
- {result.warning && (
- <div className="wp-url-swap__preview-error">{result.warning}</div>
- )}
- </div>
- <div className="modal-actions">
- <Button type="button" onClick={onClose}>Done</Button>
- </div>
- </>
- )}
- </Modal>
- );
-}
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/AutoSyncScheduleModal.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/AutoSyncScheduleModal.jsx
deleted file mode 100644
index 5a5488f4..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/AutoSyncScheduleModal.jsx
+++ /dev/null
@@ -1,181 +0,0 @@
-import { useState, useEffect } from 'react';
-import { RefreshCw } from 'lucide-react';
-import { Spinner } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { Switch } from 'serverkit-sdk';
-
-const SCHEDULE_PRESETS = [
- { label: 'Daily at 3 AM', value: '0 3 * * *' },
- { label: 'Weekly Sunday 3 AM', value: '0 3 * * 0' },
- { label: 'Every 6 hours', value: '0 */6 * * *' },
- { label: 'Every 12 hours', value: '0 */12 * * *' },
- { label: 'Custom', value: 'custom' },
-];
-
-const AutoSyncScheduleModal = ({ environment, prodId, onClose, api }) => {
- const [loading, setLoading] = useState(true);
- const [saving, setSaving] = useState(false);
- const [enabled, setEnabled] = useState(false);
- const [schedule, setSchedule] = useState('0 3 * * *');
- const [selectedPreset, setSelectedPreset] = useState('0 3 * * *');
- const [customCron, setCustomCron] = useState('');
- const [nextRuns, setNextRuns] = useState([]);
-
- useEffect(() => {
- loadSchedule();
- }, []);
-
- async function loadSchedule() {
- setLoading(true);
- try {
- const data = await api.getAutoSyncSchedule(prodId, environment.id);
- setEnabled(data.enabled || false);
- if (data.schedule) {
- const matchingPreset = SCHEDULE_PRESETS.find(p => p.value === data.schedule);
- if (matchingPreset) {
- setSelectedPreset(data.schedule);
- } else {
- setSelectedPreset('custom');
- setCustomCron(data.schedule);
- }
- setSchedule(data.schedule);
- }
- setNextRuns(data.next_runs || []);
- } catch {
- // Default values already set
- } finally {
- setLoading(false);
- }
- }
-
- function handlePresetChange(value) {
- setSelectedPreset(value);
- if (value !== 'custom') {
- setSchedule(value);
- }
- }
-
- function handleCustomCronChange(value) {
- setCustomCron(value);
- setSchedule(value);
- }
-
- async function handleSave() {
- setSaving(true);
- try {
- const finalSchedule = selectedPreset === 'custom' ? customCron : selectedPreset;
- await api.updateAutoSyncSchedule(prodId, environment.id, {
- enabled,
- schedule: finalSchedule,
- });
- onClose();
- } catch (err) {
- console.error('Failed to save auto-sync schedule:', err);
- } finally {
- setSaving(false);
- }
- }
-
- function formatDateTime(iso) {
- if (!iso) return '';
- const d = new Date(iso);
- return d.toLocaleString();
- }
-
- const envName = environment?.name || 'Environment';
-
- return (
- <Modal open={true} onClose={onClose} title="Auto-Sync Schedule" className="auto-sync-modal">
- {loading ? (
- <div className="auto-sync-loading">
- <Spinner size="sm" />
- <span>Loading schedule...</span>
- </div>
- ) : (
- <div className="auto-sync-body">
- <div className="auto-sync-env-name">{envName}</div>
-
- <div className="auto-sync-toggle">
- <label className="auto-sync-toggle-label">
- <span>Enable Auto-Sync from Production</span>
- <Switch checked={enabled} onCheckedChange={setEnabled} />
- </label>
- <p className="auto-sync-description">
- Automatically sync this environment from production on a schedule.
- </p>
- </div>
-
- {enabled && (
- <>
- <div className="form-group">
- <Label>Schedule</Label>
- <div className="auto-sync-presets">
- {SCHEDULE_PRESETS.map(preset => (
- <label key={preset.value} className="radio-label">
- <input
- type="radio"
- name="schedule-preset"
- checked={selectedPreset === preset.value}
- onChange={() => handlePresetChange(preset.value)}
- />
- <span className="radio-content">
- <strong>{preset.label}</strong>
- {preset.value !== 'custom' && (
- <span className="auto-sync-cron-display">{preset.value}</span>
- )}
- </span>
- </label>
- ))}
- </div>
- </div>
-
- {selectedPreset === 'custom' && (
- <div className="form-group">
- <Label>Custom Cron Expression</Label>
- <Input
- type="text"
- value={customCron}
- onChange={e => handleCustomCronChange(e.target.value)}
- placeholder="0 3 * * *"
- className="auto-sync-cron-input"
- />
- <span className="form-hint">
- Format: minute hour day-of-month month day-of-week
- </span>
- </div>
- )}
-
- {nextRuns.length > 0 && (
- <div className="auto-sync-next-runs">
- <h5>Next Scheduled Runs</h5>
- <ul>
- {nextRuns.map((run, i) => (
- <li key={i}>
- <RefreshCw size={10} />
- <span>{formatDateTime(run)}</span>
- </li>
- ))}
- </ul>
- </div>
- )}
- </>
- )}
- </div>
- )}
-
- <div className="modal-actions">
- <Button variant="outline" onClick={onClose} disabled={saving}>
- Cancel
- </Button>
- <Button onClick={handleSave} disabled={saving || loading}>
- {saving ? <><Spinner size="sm" /> Saving...</> : 'Save Schedule'}
- </Button>
- </div>
- </Modal>
- );
-};
-
-export default AutoSyncScheduleModal;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/BasicAuthModal.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/BasicAuthModal.jsx
deleted file mode 100644
index 07c366f9..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/BasicAuthModal.jsx
+++ /dev/null
@@ -1,156 +0,0 @@
-import { useState, useEffect } from 'react';
-import { Shield, Copy, Check, AlertTriangle } from 'lucide-react';
-import { Spinner } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Switch } from 'serverkit-sdk';
-
-const BasicAuthModal = ({ environment, prodId, onClose, api }) => {
- const [loading, setLoading] = useState(true);
- const [status, setStatus] = useState({ enabled: false, username: null });
- const [credentials, setCredentials] = useState(null);
- const [toggling, setToggling] = useState(false);
- const [copied, setCopied] = useState(null);
-
- useEffect(() => {
- loadStatus();
- }, []);
-
- async function loadStatus() {
- setLoading(true);
- try {
- const data = await api.getBasicAuthStatus(prodId, environment.id);
- setStatus(data);
- } catch {
- setStatus({ enabled: false, username: null });
- } finally {
- setLoading(false);
- }
- }
-
- async function handleEnable() {
- setToggling(true);
- try {
- const data = await api.enableBasicAuth(prodId, environment.id);
- if (data.success) {
- setStatus({ enabled: true, username: data.username });
- setCredentials({ username: data.username, password: data.password });
- }
- } catch (err) {
- console.error('Failed to enable basic auth:', err);
- } finally {
- setToggling(false);
- }
- }
-
- async function handleDisable() {
- setToggling(true);
- try {
- const data = await api.disableBasicAuth(prodId, environment.id);
- if (data.success) {
- setStatus({ enabled: false, username: null });
- setCredentials(null);
- }
- } catch (err) {
- console.error('Failed to disable basic auth:', err);
- } finally {
- setToggling(false);
- }
- }
-
- function copyToClipboard(text, field) {
- navigator.clipboard.writeText(text);
- setCopied(field);
- setTimeout(() => setCopied(null), 2000);
- }
-
- const envName = environment?.name || 'Environment';
-
- return (
- <Modal open={true} onClose={onClose} title="Basic Auth" className="basic-auth-modal">
- <div className="basic-auth-body">
- <div className="basic-auth-env-name">{envName}</div>
-
- {loading ? (
- <div className="basic-auth-loading">
- <Spinner size="sm" />
- <span>Loading status...</span>
- </div>
- ) : (
- <>
- <div className="basic-auth-toggle">
- <label className="basic-auth-toggle-label">
- <span>HTTP Basic Authentication</span>
- <Switch
- checked={status.enabled}
- onCheckedChange={status.enabled ? handleDisable : handleEnable}
- disabled={toggling}
- />
- </label>
- <p className="basic-auth-description">
- Adds password protection to the site. Visitors must enter credentials to access any page.
- </p>
- </div>
-
- {status.enabled && status.username && !credentials && (
- <div className="basic-auth-current">
- <div className="basic-auth-field">
- <label>Username</label>
- <div className="basic-auth-value">
- <code>{status.username}</code>
- </div>
- </div>
- <p className="basic-auth-hint">
- Password was shown when Basic Auth was first enabled. Disable and re-enable to generate new credentials.
- </p>
- </div>
- )}
-
- {credentials && (
- <div className="basic-auth-credentials">
- <div className="alert alert-warning">
- <AlertTriangle size={14} />
- <span>Save these credentials now. The password will not be shown again.</span>
- </div>
- <div className="basic-auth-field">
- <label>Username</label>
- <div className="basic-auth-value">
- <code>{credentials.username}</code>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => copyToClipboard(credentials.username, 'user')}
- >
- {copied === 'user' ? <Check size={12} /> : <Copy size={12} />}
- </Button>
- </div>
- </div>
- <div className="basic-auth-field">
- <label>Password</label>
- <div className="basic-auth-value">
- <code>{credentials.password}</code>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => copyToClipboard(credentials.password, 'pass')}
- >
- {copied === 'pass' ? <Check size={12} /> : <Copy size={12} />}
- </Button>
- </div>
- </div>
- </div>
- )}
- </>
- )}
- </div>
-
- <div className="modal-actions">
- <Button variant="outline" onClick={onClose}>
- Close
- </Button>
- </div>
- </Modal>
- );
-};
-
-export default BasicAuthModal;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/BulkActionsBar.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/BulkActionsBar.jsx
deleted file mode 100644
index 3fc66b9b..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/BulkActionsBar.jsx
+++ /dev/null
@@ -1,123 +0,0 @@
-import { useState } from 'react';
-import { Square, Play, RefreshCw, ArrowDownLeft, X } from 'lucide-react';
-import { Spinner } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-
-const BulkActionsBar = ({ selectedIds, environments, prodId, onClear, onExecute, api }) => {
- const [executing, setExecuting] = useState(false);
- const [confirmAction, setConfirmAction] = useState(null);
-
- if (!selectedIds || selectedIds.length === 0) return null;
-
- const selectedNames = selectedIds.map(id => {
- const env = environments.find(e => e.id === id);
- return env?.name || `#${id}`;
- });
-
- async function handleAction(action) {
- if (action === 'stop' || action === 'sync') {
- setConfirmAction(action);
- return;
- }
- await executeAction(action);
- }
-
- async function executeAction(action) {
- setExecuting(true);
- setConfirmAction(null);
- try {
- await onExecute(action, selectedIds);
- } finally {
- setExecuting(false);
- }
- }
-
- return (
- <div className="bulk-actions-bar">
- {confirmAction ? (
- <div className="bulk-actions-confirm">
- <span>
- {confirmAction === 'stop' && `Stop ${selectedIds.length} environment(s)?`}
- {confirmAction === 'sync' && `Sync ${selectedIds.length} environment(s) from production?`}
- </span>
- <Button
- size="sm"
- onClick={() => executeAction(confirmAction)}
- disabled={executing}
- >
- {executing ? <Spinner size="sm" /> : 'Confirm'}
- </Button>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => setConfirmAction(null)}
- disabled={executing}
- >
- Cancel
- </Button>
- </div>
- ) : (
- <>
- <div className="bulk-actions-info">
- <span className="bulk-actions-count">{selectedIds.length}</span>
- <span>selected</span>
- </div>
-
- <div className="bulk-actions-buttons">
- <Button
- variant="ghost"
- size="sm"
- onClick={() => handleAction('start')}
- disabled={executing}
- title="Start Selected"
- >
- <Play size={12} />
- Start
- </Button>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => handleAction('stop')}
- disabled={executing}
- title="Stop Selected"
- >
- <Square size={12} />
- Stop
- </Button>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => handleAction('restart')}
- disabled={executing}
- title="Restart Selected"
- >
- <RefreshCw size={12} />
- Restart
- </Button>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => handleAction('sync')}
- disabled={executing}
- title="Sync from Production"
- >
- <ArrowDownLeft size={12} />
- Sync from Prod
- </Button>
- </div>
-
- <Button
- variant="ghost"
- size="icon"
- className="bulk-actions-clear"
- onClick={onClear}
- >
- <X size={12} />
- </Button>
- </>
- )}
- </div>
- );
-};
-
-export default BulkActionsBar;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/ChangeUrlModal.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/ChangeUrlModal.jsx
deleted file mode 100644
index 3affb176..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/ChangeUrlModal.jsx
+++ /dev/null
@@ -1,146 +0,0 @@
-import { useState, useEffect } from 'react';
-import { Globe, AlertTriangle, ArrowRight } from 'lucide-react';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { Switch } from 'serverkit-sdk';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-
-// Change a WordPress site's URL safely: a debounced dry-run preview of the DB
-// rewrite, then a backed-up, serialization-safe apply (WP-CLI search-replace)
-// on confirm. The backend re-points the Domain row + nginx vhost afterwards.
-export default function ChangeUrlModal({ site, onClose, onChanged }) {
- const toast = useToast();
- const currentUrl = site.url || '';
- const [newUrl, setNewUrl] = useState(currentUrl);
- const [keepOld, setKeepOld] = useState(true);
- const [preview, setPreview] = useState(null);
- const [previewing, setPreviewing] = useState(false);
- const [applying, setApplying] = useState(false);
-
- const target = newUrl.trim();
- const dirty = target && target !== currentUrl;
-
- // Debounced dry-run preview whenever the target URL settles.
- useEffect(() => {
- if (!dirty) { setPreview(null); return undefined; }
- let cancelled = false;
- setPreviewing(true);
- const timer = setTimeout(async () => {
- try {
- const res = await wordpressApi.previewUrlChange(site.id, target);
- if (!cancelled) setPreview(res);
- } catch (err) {
- if (!cancelled) setPreview({ success: false, error: err.message || 'Preview failed' });
- } finally {
- if (!cancelled) setPreviewing(false);
- }
- }, 500);
- return () => { cancelled = true; clearTimeout(timer); };
- }, [target, dirty, site.id]);
-
- async function handleApply(e) {
- e?.preventDefault();
- if (!dirty || applying) return;
- setApplying(true);
- toast.info('Changing site URL — backing up and rewriting the database…', { duration: 5000 });
- try {
- const res = await wordpressApi.changeUrl(site.id, target, keepOld);
- if (res.success) {
- toast.success(`Site URL changed to ${res.new_url} (${res.replacements} replacement${res.replacements === 1 ? '' : 's'})`);
- if (res.warning) toast.warning(res.warning, { duration: 7000 });
- onChanged?.();
- onClose();
- } else {
- toast.error(res.error || 'Failed to change URL');
- }
- } catch (err) {
- toast.error(err.message || 'Failed to change URL');
- } finally {
- setApplying(false);
- }
- }
-
- return (
- <Modal open onClose={() => !applying && onClose()} title={<><Globe size={18} /> Change Site URL</>} size="lg">
- <form onSubmit={handleApply}>
- <div className="wp-url-swap">
- <div className="wp-url-swap__warning">
- <AlertTriangle size={18} aria-hidden="true" />
- <span>
- This rewrites every reference to the site URL across the database
- (posts, options, serialized data) with a serialization-safe
- search-replace. A database backup is taken first and restored
- automatically if anything fails.
- </span>
- </div>
-
- <div className="wp-url-swap__fromto">
- <code>{currentUrl || '—'}</code>
- <ArrowRight size={15} aria-hidden="true" />
- <code className={dirty ? 'is-new' : ''}>{target || '—'}</code>
- </div>
-
- <div className="form-group">
- <Label htmlFor="wp-new-url">New URL</Label>
- <Input
- id="wp-new-url"
- type="text"
- value={newUrl}
- onChange={(e) => setNewUrl(e.target.value)}
- placeholder="https://example.com"
- disabled={applying}
- autoFocus
- />
- <span className="form-hint">
- Include http:// or https://. Point this hostname&apos;s DNS at the server first.
- </span>
- </div>
-
- <label className="wp-url-swap__keep">
- <Switch checked={keepOld} onCheckedChange={setKeepOld} disabled={applying} />
- <span>
- Keep the old address working
- <small>The previous host keeps resolving; WordPress 301-redirects it to the new URL.</small>
- </span>
- </label>
-
- {dirty && (
- <div className="wp-url-swap__preview">
- {previewing && <span className="form-hint">Previewing changes…</span>}
- {!previewing && preview?.success && (
- <>
- <div className="wp-url-swap__preview-total">
- {preview.total} database replacement{preview.total === 1 ? '' : 's'} will be made
- </div>
- <ul className="wp-url-swap__preview-pairs">
- {preview.pairs.map((p, i) => (
- <li key={i}>
- <code>{p.search}</code>
- <ArrowRight size={12} aria-hidden="true" />
- <code>{p.replace}</code>
- <span className="wp-url-swap__count">{p.replacements}</span>
- </li>
- ))}
- </ul>
- </>
- )}
- {!previewing && preview && !preview.success && (
- <div className="wp-url-swap__preview-error">{preview.error}</div>
- )}
- </div>
- )}
- </div>
-
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose} disabled={applying}>Cancel</Button>
- <Button type="submit" disabled={!dirty || applying}>
- {applying ? 'Changing…' : 'Change URL'}
- </Button>
- </div>
- </form>
- </Modal>
- );
-}
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/CommitList.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/CommitList.jsx
deleted file mode 100644
index a3eed021..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/CommitList.jsx
+++ /dev/null
@@ -1,220 +0,0 @@
-import { useState } from 'react';
-import { GitCommit, Rocket, Copy, CheckCircle, ExternalLink } from 'lucide-react';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { detectProvider } from '@/components/git/GitProviders';
-import { EmptyState } from 'serverkit-sdk';
-
-// Build a web URL to a commit on the host from the clone URL + sha so the log is
-// clickable. Handles https + scp-style ssh remotes and Bitbucket's /commits path.
-function commitUrl(repoUrl, sha) {
- if (!repoUrl || !sha) return null;
- let base = repoUrl.trim().replace(/\.git$/i, '');
- const ssh = base.match(/^git@([^:]+):(.+)$/);
- if (ssh) base = `https://${ssh[1]}/${ssh[2]}`;
- if (!/^https?:\/\//i.test(base)) return null;
- const seg = detectProvider(repoUrl)?.key === 'bitbucket' ? 'commits' : 'commit';
- return `${base}/${seg}/${sha}`;
-}
-
-const CommitList = ({ commits, currentCommit, onDeploy, onCreateDev, loading = false, repoUrl }) => {
- const [actionLoading, setActionLoading] = useState({});
- const [showDevModal, setShowDevModal] = useState(null);
-
- function formatDate(dateString) {
- if (!dateString) return '-';
- const date = new Date(dateString);
- const now = new Date();
- const diffMs = now - date;
- const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
- const diffDays = Math.floor(diffHours / 24);
-
- if (diffHours < 1) return 'Just now';
- if (diffHours < 24) return `${diffHours}h ago`;
- if (diffDays < 7) return `${diffDays}d ago`;
- return date.toLocaleDateString();
- }
-
- async function handleDeploy(commit) {
- if (!confirm(`Deploy commit ${commit.sha.substring(0, 7)} to production?`)) {
- return;
- }
- setActionLoading(prev => ({ ...prev, [`deploy-${commit.sha}`]: true }));
- try {
- await onDeploy?.({ commit_sha: commit.sha });
- } finally {
- setActionLoading(prev => ({ ...prev, [`deploy-${commit.sha}`]: false }));
- }
- }
-
- async function handleCreateDev(commit, config) {
- setActionLoading(prev => ({ ...prev, [`dev-${commit.sha}`]: true }));
- try {
- await onCreateDev?.({
- commit_sha: commit.sha,
- config
- });
- setShowDevModal(null);
- } finally {
- setActionLoading(prev => ({ ...prev, [`dev-${commit.sha}`]: false }));
- }
- }
-
- if (loading) {
- return <EmptyState loading title="Loading commits..." />;
- }
-
- if (!commits || commits.length === 0) {
- return (
- <div className="empty-state-small">
- <p>No commits found.</p>
- <p className="hint">Push changes to your repository to see commits here.</p>
- </div>
- );
- }
-
- return (
- <div className="commit-list">
- {commits.map(commit => {
- const isCurrent = currentCommit === commit.sha;
- const isDeploying = actionLoading[`deploy-${commit.sha}`];
- const isCreatingDev = actionLoading[`dev-${commit.sha}`];
-
- return (
- <div key={commit.sha} className={`commit-item ${isCurrent ? 'current' : ''}`}>
- <div className="commit-icon">
- {isCurrent ? (
- <CheckCircle size={16} className="current-icon" />
- ) : (
- <GitCommit size={16} />
- )}
- </div>
-
- <div className="commit-info">
- <div className="commit-header">
- {commitUrl(repoUrl, commit.sha) ? (
- <a
- className="commit-sha mono commit-sha--link"
- href={commitUrl(repoUrl, commit.sha)}
- target="_blank"
- rel="noopener noreferrer"
- title="View this commit on the remote"
- >
- {commit.sha.substring(0, 7)}
- <ExternalLink size={11} />
- </a>
- ) : (
- <span className="commit-sha mono">{commit.sha.substring(0, 7)}</span>
- )}
- {isCurrent && <span className="current-badge">Deployed</span>}
- <span className="commit-date">{formatDate(commit.date)}</span>
- </div>
- <p className="commit-message">{commit.message}</p>
- {commit.author && (
- <span className="commit-author">{commit.author}</span>
- )}
- </div>
-
- <div className="commit-actions">
- {!isCurrent && (
- <Button
- size="sm"
- onClick={() => handleDeploy(commit)}
- disabled={isDeploying}
- title="Deploy this commit"
- >
- <Rocket size={12} />
- {isDeploying ? 'Deploying...' : 'Deploy'}
- </Button>
- )}
- <Button
- variant="outline"
- size="sm"
- onClick={() => setShowDevModal(commit)}
- disabled={isCreatingDev}
- title="Create dev environment from this commit"
- >
- <Copy size={12} />
- {isCreatingDev ? 'Creating...' : 'Create Dev'}
- </Button>
- </div>
- </div>
- );
- })}
-
- {showDevModal && (
- <CreateDevModal
- commit={showDevModal}
- onClose={() => setShowDevModal(null)}
- onCreate={(config) => handleCreateDev(showDevModal, config)}
- loading={actionLoading[`dev-${showDevModal.sha}`]}
- />
- )}
- </div>
- );
-};
-
-const CreateDevModal = ({ commit, onClose, onCreate, loading }) => {
- const [formData, setFormData] = useState({
- name: `dev-${commit.sha.substring(0, 7)}`,
- domain: ''
- });
-
- function handleChange(e) {
- const { name, value } = e.target;
- setFormData(prev => ({ ...prev, [name]: value }));
- }
-
- function handleSubmit(e) {
- e.preventDefault();
- onCreate(formData);
- }
-
- return (
- <Modal open={true} onClose={onClose} title="Create Dev Environment">
- <p className="hint">
- Create a development environment with code from commit{' '}
- <code>{commit.sha.substring(0, 7)}</code>
- </p>
- <p className="commit-message-preview">&ldquo;{commit.message}&rdquo;</p>
-
- <form onSubmit={handleSubmit}>
- <div className="form-group">
- <Label>Environment Name</Label>
- <Input
- type="text"
- name="name"
- value={formData.name}
- onChange={handleChange}
- placeholder="dev-abc1234"
- />
- </div>
-
- <div className="form-group">
- <Label>Domain (optional)</Label>
- <Input
- type="text"
- name="domain"
- value={formData.domain}
- onChange={handleChange}
- placeholder="dev.example.com"
- />
- <span className="form-hint">Leave empty to auto-generate</span>
- </div>
-
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose}>
- Cancel
- </Button>
- <Button type="submit" disabled={loading}>
- {loading ? 'Creating...' : 'Create Environment'}
- </Button>
- </div>
- </form>
- </Modal>
- );
-};
-
-export default CommitList;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/CompareView.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/CompareView.jsx
deleted file mode 100644
index 78cac4c3..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/CompareView.jsx
+++ /dev/null
@@ -1,215 +0,0 @@
-import { useState, useEffect } from 'react';
-import { GitCompare, Check, X, Minus, RefreshCw } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { Spinner } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-
-const CompareView = ({ projectId, envA, envB, onClose }) => {
- const [comparison, setComparison] = useState(null);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState(null);
-
- useEffect(() => {
- loadComparison();
- }, [envA?.id, envB?.id]);
-
- async function loadComparison() {
- if (!envA?.id || !envB?.id) return;
-
- setLoading(true);
- setError(null);
- try {
- const data = await wordpressApi.compareEnvironments(projectId, envA.id, envB.id);
- setComparison(data);
- } catch (err) {
- setError(err.message || 'Failed to compare environments');
- } finally {
- setLoading(false);
- }
- }
-
- const envAType = envA?.environment_type || 'production';
- const envBType = envB?.environment_type || 'development';
-
- return (
- <Modal open={true} onClose={onClose} title="Compare Environments" size="xl">
- <div className="compare-header">
- <div className={`compare-env-pill ${envAType}`}>
- <span className="compare-env-type">{envAType}</span>
- <span className="compare-env-name">{envA?.name || 'Environment A'}</span>
- </div>
- <GitCompare size={16} className="compare-vs-icon" />
- <div className={`compare-env-pill ${envBType}`}>
- <span className="compare-env-type">{envBType}</span>
- <span className="compare-env-name">{envB?.name || 'Environment B'}</span>
- </div>
- <Button variant="ghost" size="sm" onClick={loadComparison} disabled={loading}>
- <RefreshCw size={14} />
- </Button>
- </div>
-
- <div className="compare-body">
- {loading && (
- <div className="compare-loading">
- <Spinner size="md" />
- <span>Comparing environments...</span>
- </div>
- )}
-
- {error && (
- <div className="alert alert-danger">
- <p>{error}</p>
- <Button size="sm" onClick={loadComparison}>
- Retry
- </Button>
- </div>
- )}
-
- {!loading && !error && comparison && (
- <>
- {/* Version Comparison */}
- <CompareSection title="Versions">
- <CompareRow
- label="WordPress"
- valueA={comparison.env_a?.wp_version}
- valueB={comparison.env_b?.wp_version}
- />
- <CompareRow
- label="PHP"
- valueA={comparison.env_a?.php_version}
- valueB={comparison.env_b?.php_version}
- />
- <CompareRow
- label="Active Theme"
- valueA={comparison.env_a?.active_theme}
- valueB={comparison.env_b?.active_theme}
- />
- </CompareSection>
-
- {/* Plugins Comparison */}
- {comparison.plugins && (
- <CompareSection
- title="Plugins"
- summary={getPluginSummary(comparison.plugins)}
- >
- {comparison.plugins.map(plugin => (
- <CompareRow
- key={plugin.name}
- label={plugin.name}
- valueA={plugin.version_a || (plugin.in_a ? 'Installed' : null)}
- valueB={plugin.version_b || (plugin.in_b ? 'Installed' : null)}
- status={plugin.status}
- />
- ))}
- {comparison.plugins.length === 0 && (
- <div className="compare-empty-row">No plugin data available</div>
- )}
- </CompareSection>
- )}
-
- {/* Themes Comparison */}
- {comparison.themes && (
- <CompareSection
- title="Themes"
- summary={getThemeSummary(comparison.themes)}
- >
- {comparison.themes.map(theme => (
- <CompareRow
- key={theme.name}
- label={theme.name}
- valueA={theme.version_a || (theme.in_a ? 'Installed' : null)}
- valueB={theme.version_b || (theme.in_b ? 'Installed' : null)}
- status={theme.status}
- />
- ))}
- {comparison.themes.length === 0 && (
- <div className="compare-empty-row">No theme data available</div>
- )}
- </CompareSection>
- )}
- </>
- )}
- </div>
-
- <div className="modal-actions">
- <Button variant="outline" onClick={onClose}>Close</Button>
- </div>
- </Modal>
- );
-};
-
-const CompareSection = ({ title, summary, children }) => (
- <div className="compare-section">
- <div className="compare-section-header">
- <h4>{title}</h4>
- {summary && <span className="compare-section-summary">{summary}</span>}
- </div>
- <div className="compare-table">
- {children}
- </div>
- </div>
-);
-
-const CompareRow = ({ label, valueA, valueB, status }) => {
- const match = valueA === valueB && valueA != null;
- const onlyA = valueA && !valueB;
- const onlyB = !valueA && valueB;
- const different = valueA && valueB && valueA !== valueB;
-
- let statusClass = 'match';
- let StatusIcon = Check;
- if (different || status === 'different') {
- statusClass = 'different';
- StatusIcon = X;
- } else if (onlyA || status === 'only_a') {
- statusClass = 'only-a';
- StatusIcon = Minus;
- } else if (onlyB || status === 'only_b') {
- statusClass = 'only-b';
- StatusIcon = Minus;
- }
-
- return (
- <div className={`compare-row ${statusClass}`}>
- <div className="compare-row-label">
- <StatusIcon size={12} className="compare-row-icon" />
- {label}
- </div>
- <div className="compare-row-value-a">
- {valueA || <span className="compare-na">--</span>}
- </div>
- <div className="compare-row-value-b">
- {valueB || <span className="compare-na">--</span>}
- </div>
- </div>
- );
-};
-
-function getPluginSummary(plugins) {
- const match = plugins.filter(p => p.status === 'match').length;
- const diff = plugins.filter(p => p.status === 'different').length;
- const onlyA = plugins.filter(p => p.status === 'only_a').length;
- const onlyB = plugins.filter(p => p.status === 'only_b').length;
- const parts = [];
- if (match) parts.push(`${match} matching`);
- if (diff) parts.push(`${diff} different`);
- if (onlyA) parts.push(`${onlyA} only in A`);
- if (onlyB) parts.push(`${onlyB} only in B`);
- return parts.join(', ');
-}
-
-function getThemeSummary(themes) {
- const match = themes.filter(t => t.status === 'match').length;
- const diff = themes.filter(t => t.status === 'different').length;
- const onlyA = themes.filter(t => t.status === 'only_a').length;
- const onlyB = themes.filter(t => t.status === 'only_b').length;
- const parts = [];
- if (match) parts.push(`${match} matching`);
- if (diff) parts.push(`${diff} different`);
- if (onlyA) parts.push(`${onlyA} only in A`);
- if (onlyB) parts.push(`${onlyB} only in B`);
- return parts.join(', ');
-}
-
-export default CompareView;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/ContainerLogs.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/ContainerLogs.jsx
deleted file mode 100644
index 927a87ac..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/ContainerLogs.jsx
+++ /dev/null
@@ -1,132 +0,0 @@
-import { useState, useEffect, useRef } from 'react';
-import { Terminal, X, Download } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { Button } from 'serverkit-sdk';
-import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from 'serverkit-sdk';
-
-const ContainerLogs = ({ projectId, envId, onClose }) => {
- const [logs, setLogs] = useState([]);
- const [loading, setLoading] = useState(true);
- const [service, setService] = useState('wordpress');
- const [lines, setLines] = useState(100);
- const [autoScroll, setAutoScroll] = useState(true);
- const logsEndRef = useRef(null);
- const containerRef = useRef(null);
-
- useEffect(() => {
- loadLogs();
- }, [projectId, envId, service, lines]);
-
- useEffect(() => {
- if (autoScroll && logsEndRef.current) {
- logsEndRef.current.scrollIntoView({ behavior: 'smooth' });
- }
- }, [logs, autoScroll]);
-
- async function loadLogs() {
- setLoading(true);
- try {
- const data = await wordpressApi.getEnvironmentLogs(projectId, envId, { service, lines });
- setLogs(data.logs || []);
- } catch (err) {
- console.error('Failed to load logs:', err);
- setLogs([`Error loading logs: ${err.message}`]);
- } finally {
- setLoading(false);
- }
- }
-
- function handleScroll() {
- if (!containerRef.current) return;
- const { scrollTop, scrollHeight, clientHeight } = containerRef.current;
- setAutoScroll(scrollHeight - scrollTop - clientHeight < 50);
- }
-
- function handleDownload() {
- const text = logs.join('\n');
- const blob = new Blob([text], { type: 'text/plain' });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = `env-${envId}-${service}-logs.txt`;
- a.click();
- URL.revokeObjectURL(url);
- }
-
- return (
- <div className="container-logs-panel">
- <div className="container-logs-header">
- <div className="container-logs-title">
- <span className="container-logs-ico">
- <Terminal size={15} />
- </span>
- <div className="container-logs-titles">
- <span>Container Logs</span>
- <span className="container-logs-sub">env-{envId} · {service}</span>
- </div>
- </div>
- <div className="container-logs-controls">
- <Select value={service} onValueChange={setService}>
- <SelectTrigger className="logs-service-select">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="wordpress">WordPress</SelectItem>
- <SelectItem value="db">MySQL</SelectItem>
- </SelectContent>
- </Select>
- <Select value={String(lines)} onValueChange={(v) => setLines(Number(v))}>
- <SelectTrigger className="logs-lines-select">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="50">50 lines</SelectItem>
- <SelectItem value="100">100 lines</SelectItem>
- <SelectItem value="500">500 lines</SelectItem>
- </SelectContent>
- </Select>
- <Button variant="ghost" size="sm" onClick={loadLogs} title="Refresh">
- <RefreshIcon />
- </Button>
- <Button variant="ghost" size="sm" onClick={handleDownload} title="Download">
- <Download size={14} />
- </Button>
- {onClose && (
- <Button variant="ghost" size="sm" onClick={onClose}>
- <X size={14} />
- </Button>
- )}
- </div>
- </div>
- <div
- className="container-logs-body"
- ref={containerRef}
- onScroll={handleScroll}
- >
- {loading ? (
- <div className="logs-loading">Loading logs...</div>
- ) : logs.length === 0 ? (
- <div className="logs-empty">No logs available.</div>
- ) : (
- <pre className="logs-content">
- {logs.map((line, i) => (
- <div key={i} className="log-line">{line}</div>
- ))}
- <div ref={logsEndRef} />
- </pre>
- )}
- </div>
- </div>
- );
-};
-
-function RefreshIcon() {
- return (
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
- <polyline points="23 4 23 10 17 10" />
- <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10" />
- </svg>
- );
-}
-
-export default ContainerLogs;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/DiskUsageBar.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/DiskUsageBar.jsx
deleted file mode 100644
index f824b683..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/DiskUsageBar.jsx
+++ /dev/null
@@ -1,78 +0,0 @@
-import { HardDrive } from 'lucide-react';
-import { formatBytes } from 'serverkit-sdk';
-
-const REFERENCE_THRESHOLD = 10 * 1024 * 1024 * 1024; // 10 GB reference
-
-const DiskUsageBar = ({ usage, showBreakdown = true, compact = false }) => {
- if (!usage) return null;
-
- const total = usage.total || 0;
- const wordpress = usage.wordpress || 0;
- const mysql = usage.mysql || 0;
- const snapshots = usage.snapshots || 0;
-
- const percent = REFERENCE_THRESHOLD > 0
- ? Math.min((total / REFERENCE_THRESHOLD) * 100, 100)
- : 0;
-
- const wpPercent = total > 0 ? (wordpress / total) * percent : 0;
- const dbPercent = total > 0 ? (mysql / total) * percent : 0;
- const snapPercent = total > 0 ? (snapshots / total) * percent : 0;
-
- const colorClass = percent < 70 ? 'green' : percent < 90 ? 'yellow' : 'red';
-
- if (compact) {
- return (
- <div className="disk-usage-compact" title={`Disk: ${formatBytes(total)}`}>
- <HardDrive size={10} />
- <span className="disk-usage-compact-text">{formatBytes(total)}</span>
- </div>
- );
- }
-
- return (
- <div className="disk-usage-bar-container">
- <div className="disk-usage-header">
- <HardDrive size={14} />
- <span className="disk-usage-total">{formatBytes(total)}</span>
- </div>
-
- <div className="disk-usage-bar">
- <div
- className={`disk-usage-segment wordpress ${colorClass}`}
- style={{ width: `${wpPercent}%` }}
- title={`WordPress: ${formatBytes(wordpress)}`}
- />
- <div
- className="disk-usage-segment mysql"
- style={{ width: `${dbPercent}%` }}
- title={`MySQL: ${formatBytes(mysql)}`}
- />
- <div
- className="disk-usage-segment snapshots"
- style={{ width: `${snapPercent}%` }}
- title={`Snapshots: ${formatBytes(snapshots)}`}
- />
- </div>
-
- {showBreakdown && (
- <div className="disk-usage-legend">
- <div className="disk-usage-legend-item">
- <span className="disk-usage-legend-dot wordpress" />
- <span>WordPress {formatBytes(wordpress)}</span>
- </div>
- <div className="disk-usage-legend-item">
- <span className="disk-usage-legend-dot mysql" />
- <span>MySQL {formatBytes(mysql)}</span>
- </div>
- <div className="disk-usage-legend-item">
- <span className="disk-usage-legend-dot snapshots" />
- <span>Snapshots {formatBytes(snapshots)}</span>
- </div>
- </div>
- )}
- </div>
- );
-};
-
-export default DiskUsageBar;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/EnvironmentCard.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/EnvironmentCard.jsx
deleted file mode 100644
index 28a7348f..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/EnvironmentCard.jsx
+++ /dev/null
@@ -1,232 +0,0 @@
-import { useState } from 'react';
-import { ExternalLink, RefreshCw, Trash2, GitBranch, Clock, AlertTriangle, Calendar, FileText } from 'lucide-react';
-import { ConfirmDialog } from 'serverkit-sdk';
-import { Pill, EnvTag } from 'serverkit-sdk';
-
-const EnvironmentCard = ({ environment, productionUrl, onSync, onDelete, onViewLogs, isProduction = false }) => {
- const [syncing, setSyncing] = useState(false);
- const [deleting, setDeleting] = useState(false);
- const [showSyncConfirm, setShowSyncConfirm] = useState(false);
- const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
-
- const isRunning = environment.status === 'running';
- const envType = environment.type || environment.environment_type || (isProduction ? 'production' : 'development');
-
- // Helper functions
- function formatDate(dateString) {
- if (!dateString) return null;
- return new Date(dateString).toLocaleDateString();
- }
-
- function formatRelativeTime(dateString) {
- if (!dateString) return null;
- const date = new Date(dateString);
- const now = new Date();
- const diffMs = now - date;
- const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
-
- if (diffDays === 0) return 'Today';
- if (diffDays === 1) return 'Yesterday';
- if (diffDays < 7) return `${diffDays} days ago`;
- if (diffDays < 30) return `${Math.floor(diffDays / 7)} week(s) ago`;
- return `${Math.floor(diffDays / 30)} month(s) ago`;
- }
-
- function isStale() {
- if (!environment.last_sync || isProduction) return false;
- const lastSync = new Date(environment.last_sync);
- const now = new Date();
- const diffDays = Math.floor((now - lastSync) / (1000 * 60 * 60 * 24));
- return diffDays > 7; // Consider stale if not synced in 7 days
- }
-
- function formatSchedule(schedule) {
- if (!schedule) return null;
- const scheduleMap = {
- '0 3 * * 0': 'Weekly (Sunday 3am)',
- '0 3 * * *': 'Daily (3am)',
- '0 0 * * 0': 'Weekly (Sunday midnight)',
- '0 0 * * *': 'Daily (midnight)'
- };
- return scheduleMap[schedule] || schedule;
- }
-
- const stale = isStale();
-
- async function handleSync() {
- setShowSyncConfirm(false);
- setSyncing(true);
- try {
- await onSync?.(environment.id);
- } finally {
- setSyncing(false);
- }
- }
-
- async function handleDelete() {
- setShowDeleteConfirm(false);
- setDeleting(true);
- try {
- await onDelete?.(environment.id);
- } finally {
- setDeleting(false);
- }
- }
-
- function handleVisit() {
- if (environment.url) {
- window.open(environment.url, '_blank');
- }
- }
-
- const envTagLabel = envType === 'production' ? 'PROD'
- : envType === 'staging' ? 'STAGING'
- : envType === 'multidev' ? 'MULTIDEV'
- : 'DEV';
-
- return (
- <div className={`wp-env-card ${isProduction ? 'production' : ''} ${stale ? 'stale' : ''}`}>
- <div className="wp-env-header">
- <div className="wp-env-info">
- <EnvTag env={envTagLabel} />
- <h4 className="wp-env-name">{environment.name}</h4>
- </div>
- <div className="wp-env-status-group">
- {stale && (
- <span className="wp-env-stale-badge" title="Environment hasn't been synced in over 7 days">
- <AlertTriangle size={12} />
- Stale
- </span>
- )}
- <Pill kind={isRunning ? 'green' : 'gray'}>{isRunning ? 'Running' : 'Stopped'}</Pill>
- </div>
- </div>
-
- <div className="wp-env-body">
- {environment.url && (
- <div className="wp-env-url">
- <a href={environment.url} target="_blank" rel="noopener noreferrer">
- {environment.url}
- </a>
- </div>
- )}
-
- <div className="wp-env-meta">
- {environment.db_name && (
- <div className="wp-env-meta-item">
- <span className="meta-label">Database</span>
- <span className="meta-value mono">{environment.db_name}</span>
- </div>
- )}
- {environment.commit_sha && (
- <div className="wp-env-meta-item">
- <span className="meta-label">
- <GitBranch size={12} /> Commit
- </span>
- <span className="meta-value mono">{environment.commit_sha.substring(0, 7)}</span>
- </div>
- )}
- {!isProduction && environment.last_sync && (
- <div className="wp-env-meta-item">
- <span className="meta-label">
- <Clock size={12} /> Last Sync
- </span>
- <span className={`meta-value ${stale ? 'text-warning' : ''}`}>
- {formatRelativeTime(environment.last_sync)}
- </span>
- </div>
- )}
- {!isProduction && environment.sync_schedule && (
- <div className="wp-env-meta-item">
- <span className="meta-label">
- <Calendar size={12} /> Schedule
- </span>
- <span className="meta-value">
- {formatSchedule(environment.sync_schedule)}
- </span>
- </div>
- )}
- </div>
- </div>
-
- <div className="wp-env-footer">
- <button type="button"
- className="btn btn-ghost btn-sm"
- onClick={handleVisit}
- disabled={!environment.url}
- >
- <ExternalLink size={14} />
- Visit
- </button>
-
- {!isProduction && (
- <>
- <button type="button"
- className="btn btn-ghost btn-sm"
- onClick={() => setShowSyncConfirm(true)}
- disabled={syncing || !productionUrl}
- title="Sync from production"
- >
- <RefreshCw size={14} className={syncing ? 'spinning' : ''} />
- {syncing ? 'Syncing...' : 'Sync'}
- </button>
- {onViewLogs && (
- <button type="button"
- className="btn btn-ghost btn-sm"
- onClick={() => onViewLogs?.(environment.id)}
- title="View sync logs"
- >
- <FileText size={14} />
- Logs
- </button>
- )}
- <button type="button"
- className="btn btn-ghost btn-sm btn-danger"
- onClick={() => setShowDeleteConfirm(true)}
- disabled={deleting}
- >
- <Trash2 size={14} />
- {deleting ? 'Deleting...' : 'Delete'}
- </button>
- </>
- )}
- </div>
-
- <ConfirmDialog
- isOpen={showSyncConfirm}
- title="Sync from Production"
- message={`Sync "${environment.name}" from production?`}
- details={
- <ul>
- <li><strong>Warning:</strong> This will overwrite the current database</li>
- <li>All data in this environment will be replaced with production data</li>
- <li>URLs will be automatically updated for this environment</li>
- </ul>
- }
- confirmText="Sync Now"
- variant="warning"
- onConfirm={handleSync}
- onCancel={() => setShowSyncConfirm(false)}
- />
-
- <ConfirmDialog
- isOpen={showDeleteConfirm}
- title={`Delete ${envType.charAt(0).toUpperCase() + envType.slice(1)} Environment`}
- message={`Are you sure you want to delete "${environment.name}"?`}
- details={
- <ul>
- <li>All environment files will be permanently deleted</li>
- <li>Database <code>{environment.db_name || 'associated database'}</code> will be removed</li>
- <li>This action cannot be undone</li>
- </ul>
- }
- confirmText="Delete Environment"
- variant="danger"
- onConfirm={handleDelete}
- onCancel={() => setShowDeleteConfirm(false)}
- />
- </div>
- );
-};
-
-export default EnvironmentCard;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/EnvironmentStatusBadge.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/EnvironmentStatusBadge.jsx
deleted file mode 100644
index 6b4c5289..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/EnvironmentStatusBadge.jsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import { Lock } from 'lucide-react';
-
-const EnvironmentStatusBadge = ({ type, status, isLocked }) => {
- function getTypeBadgeClass() {
- switch (type) {
- case 'production': return 'env-production';
- case 'staging': return 'env-staging';
- case 'multidev': return 'env-multidev';
- default: return 'env-development';
- }
- }
-
- const isRunning = status === 'running';
-
- return (
- <div className="env-status-badge-group">
- <span className={`wp-env-badge ${getTypeBadgeClass()}`}>
- {type?.toUpperCase() || 'DEV'}
- </span>
- {isLocked && (
- <span className="env-locked-badge" title="Environment is locked">
- <Lock size={10} />
- </span>
- )}
- <span className={`wp-env-status ${isRunning ? 'running' : 'stopped'}`}>
- <span className="status-dot" />
- {isRunning ? 'Running' : 'Stopped'}
- </span>
- </div>
- );
-};
-
-export default EnvironmentStatusBadge;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/GitConnectForm.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/GitConnectForm.jsx
deleted file mode 100644
index e544d288..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/GitConnectForm.jsx
+++ /dev/null
@@ -1,21 +0,0 @@
-// WordPress-flavored wrapper over the shared RepoConnectForm: same form, just
-// pre-dressed with the WordPress intro copy and the wp-content tracked-path
-// defaults. The reusable component lives in components/git/RepoConnectForm.jsx.
-import RepoConnectForm from '@/components/git/RepoConnectForm';
-
-const GitConnectForm = (props) => (
- <RepoConnectForm
- {...props}
- idPrefix="wp"
- intro={{
- title: 'Connect a Git repository',
- subtitle: 'Manage themes and plugins for this site with version control — push to deploy.',
- }}
- showPaths
- defaultPaths={['wp-content/themes', 'wp-content/plugins']}
- pathsLabel="Tracked paths"
- pathsHint="Paths relative to the WordPress root that should be tracked."
- />
-);
-
-export default GitConnectForm;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/HealthStatusPanel.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/HealthStatusPanel.jsx
deleted file mode 100644
index 1256dc49..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/HealthStatusPanel.jsx
+++ /dev/null
@@ -1,137 +0,0 @@
-import { useState, useEffect, useRef } from 'react';
-import { Activity, RefreshCw, CheckCircle, AlertTriangle, XCircle, HelpCircle } from 'lucide-react';
-import { Spinner } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-
-const STATUS_CONFIG = {
- healthy: { icon: CheckCircle, color: 'green', label: 'Healthy' },
- degraded: { icon: AlertTriangle, color: 'yellow', label: 'Degraded' },
- unhealthy: { icon: XCircle, color: 'red', label: 'Unhealthy' },
- unknown: { icon: HelpCircle, color: 'gray', label: 'Unknown' },
-};
-
-const HealthDot = ({ status, size = 8 }) => {
- const colorMap = {
- healthy: 'var(--green, #3ddc97)',
- degraded: 'var(--amber, #f5b945)',
- unhealthy: 'var(--red, #fb6f6f)',
- unknown: 'var(--text-faint, #646b7a)',
- };
-
- return (
- <span
- className={`health-dot health-dot-${status}`}
- style={{
- width: size,
- height: size,
- borderRadius: '50%',
- display: 'inline-block',
- backgroundColor: colorMap[status] || colorMap.unknown,
- }}
- title={STATUS_CONFIG[status]?.label || 'Unknown'}
- />
- );
-};
-
-const HealthStatusPanel = ({ projectId, environments, api, compact = false }) => {
- const [healthData, setHealthData] = useState({});
- const [loading, setLoading] = useState(true);
- const intervalRef = useRef(null);
-
- useEffect(() => {
- loadHealth();
-
- // Auto-refresh every 30 seconds
- intervalRef.current = setInterval(loadHealth, 30000);
-
- return () => {
- if (intervalRef.current) clearInterval(intervalRef.current);
- };
- }, [projectId]);
-
- async function loadHealth() {
- try {
- const data = await api.getProjectHealth(projectId);
- if (data.success) {
- setHealthData(data.environments || {});
- }
- } catch {
- // Silently fail - health checks are optional
- } finally {
- setLoading(false);
- }
- }
-
- if (compact) {
- return null; // Dots are rendered directly via HealthDot export
- }
-
- if (loading) {
- return (
- <div className="health-status-panel">
- <div className="health-panel-loading">
- <Spinner size="sm" />
- <span>Checking health...</span>
- </div>
- </div>
- );
- }
-
- return (
- <div className="health-status-panel">
- <div className="health-panel-header">
- <h4>
- <Activity size={16} />
- Environment Health
- </h4>
- <Button variant="ghost" size="sm" onClick={loadHealth}>
- <RefreshCw size={12} />
- Refresh
- </Button>
- </div>
-
- <div className="health-panel-grid">
- {Object.entries(healthData).map(([envId, data]) => {
- const env = environments?.find(e => String(e.id) === String(envId));
- const envName = env?.name || `Environment ${envId}`;
- const overall = data?.overall_status || 'unknown';
- const checks = data?.checks || {};
-
- return (
- <div key={envId} className="health-panel-env">
- <div className="health-panel-env-header">
- <HealthDot status={overall} size={10} />
- <span className="health-panel-env-name">{envName}</span>
- <span className={`health-panel-overall health-${overall}`}>
- {STATUS_CONFIG[overall]?.label || 'Unknown'}
- </span>
- </div>
- <div className="health-panel-checks">
- {Object.entries(checks).map(([checkName, checkData]) => (
- <div key={checkName} className="health-panel-check">
- <HealthDot status={checkData.status} size={6} />
- <span className="health-panel-check-name">
- {checkName.charAt(0).toUpperCase() + checkName.slice(1)}
- </span>
- <span className="health-panel-check-msg">
- {checkData.message}
- </span>
- </div>
- ))}
- </div>
- </div>
- );
- })}
- </div>
-
- {Object.keys(healthData).length === 0 && (
- <div className="health-panel-empty">
- No health data available
- </div>
- )}
- </div>
- );
-};
-
-export { HealthDot };
-export default HealthStatusPanel;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/PipelineView.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/PipelineView.jsx
deleted file mode 100644
index fe2fe7a7..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/PipelineView.jsx
+++ /dev/null
@@ -1,589 +0,0 @@
-import { useState } from 'react';
-import {
- ExternalLink, Play, Square, RefreshCw, ArrowRight,
- ArrowDownLeft, Lock, Unlock, FileText, Trash2, MoreVertical,
- GitBranch, Plus, GitCompare, Cpu, Shield, Terminal, Clock,
- HardDrive, Settings
-} from 'lucide-react';
-import EnvironmentStatusBadge from './EnvironmentStatusBadge';
-import { HealthDot } from './HealthStatusPanel';
-import DiskUsageBar from './DiskUsageBar';
-import { Button } from 'serverkit-sdk';
-import { Checkbox } from 'serverkit-sdk';
-import { formatRelativeTime } from 'serverkit-sdk';
-
-const PipelineView = ({
- pipeline,
- onPromote,
- onSync,
- onStart,
- onStop,
- onRestart,
- onDelete,
- onLock,
- onUnlock,
- onViewLogs,
- onCreateMultidev,
- onCompare,
- onResourceLimits,
- onBasicAuth,
- onWpCli,
- onAutoSync,
- onHealthCheck,
- operationInProgress,
- healthData,
- diskUsageData,
- bulkSelected,
- onBulkToggle,
-}) => {
- if (!pipeline) return null;
-
- const { production, environments = [] } = pipeline;
- const devEnv = environments.find(e => e.environment_type === 'development');
- const stagingEnv = environments.find(e => e.environment_type === 'staging');
- const multidevEnvs = environments.filter(e => e.environment_type === 'multidev');
-
- return (
- <div className="pipeline-view">
- <div className="pipeline-row">
- {/* Development */}
- {devEnv ? (
- <PipelineCard
- env={devEnv}
- onStart={onStart}
- onStop={onStop}
- onRestart={onRestart}
- onDelete={onDelete}
- onLock={onLock}
- onUnlock={onUnlock}
- onViewLogs={onViewLogs}
- onResourceLimits={onResourceLimits}
- onBasicAuth={onBasicAuth}
- onWpCli={onWpCli}
- onAutoSync={onAutoSync}
- onHealthCheck={onHealthCheck}
- operationInProgress={operationInProgress}
- healthStatus={healthData?.[devEnv.id]?.overall_status}
- diskUsage={diskUsageData?.[devEnv.id]?.usage}
- bulkSelected={bulkSelected?.includes(devEnv.id)}
- onBulkToggle={onBulkToggle}
- />
- ) : (
- <EmptySlot type="development" />
- )}
-
- {/* Arrow: Dev -> Staging (Promote) */}
- <PipelineArrow
- label="Promote"
- direction="forward"
- disabled={!devEnv || !stagingEnv}
- onClick={() => devEnv && stagingEnv && onPromote?.(devEnv, stagingEnv)}
- />
-
- {/* Staging */}
- {stagingEnv ? (
- <PipelineCard
- env={stagingEnv}
- onStart={onStart}
- onStop={onStop}
- onRestart={onRestart}
- onDelete={onDelete}
- onLock={onLock}
- onUnlock={onUnlock}
- onViewLogs={onViewLogs}
- onResourceLimits={onResourceLimits}
- onBasicAuth={onBasicAuth}
- onWpCli={onWpCli}
- onAutoSync={onAutoSync}
- onHealthCheck={onHealthCheck}
- operationInProgress={operationInProgress}
- healthStatus={healthData?.[stagingEnv.id]?.overall_status}
- diskUsage={diskUsageData?.[stagingEnv.id]?.usage}
- bulkSelected={bulkSelected?.includes(stagingEnv.id)}
- onBulkToggle={onBulkToggle}
- />
- ) : (
- <EmptySlot type="staging" />
- )}
-
- {/* Arrow: Staging -> Production (Promote) */}
- <PipelineArrow
- label="Promote"
- direction="forward"
- disabled={!stagingEnv}
- onClick={() => stagingEnv && production && onPromote?.(stagingEnv, production)}
- />
-
- {/* Production */}
- {production && (
- <PipelineCard
- env={production}
- isProduction
- onStart={onStart}
- onStop={onStop}
- onRestart={onRestart}
- onLock={onLock}
- onUnlock={onUnlock}
- onViewLogs={onViewLogs}
- onResourceLimits={onResourceLimits}
- onBasicAuth={onBasicAuth}
- onWpCli={onWpCli}
- onHealthCheck={onHealthCheck}
- operationInProgress={operationInProgress}
- healthStatus={healthData?.[production.id]?.overall_status}
- diskUsage={diskUsageData?.[production.id]?.usage}
- />
- )}
- </div>
-
- {/* Sync arrows (below, reversed) */}
- <div className="pipeline-sync-row">
- {devEnv && (
- <div className="pipeline-sync-action">
- <Button
- variant="ghost"
- size="sm"
- onClick={() => onSync?.(devEnv)}
- title="Pull production data into development"
- >
- <ArrowDownLeft size={14} />
- Pull from Prod
- </Button>
- </div>
- )}
- {stagingEnv && (
- <div className="pipeline-sync-action">
- <Button
- variant="ghost"
- size="sm"
- onClick={() => onSync?.(stagingEnv)}
- title="Pull production data into staging"
- >
- <ArrowDownLeft size={14} />
- Pull from Prod
- </Button>
- </div>
- )}
- </div>
-
- {/* Compare row */}
- {onCompare && (devEnv || stagingEnv) && production && (
- <div className="pipeline-compare-row">
- {devEnv && (
- <Button
- variant="ghost"
- size="sm"
- className="pipeline-compare-btn"
- onClick={() => onCompare(devEnv, production)}
- title="Compare development vs production"
- >
- <GitCompare size={14} />
- Compare vs Prod
- </Button>
- )}
- {stagingEnv && (
- <Button
- variant="ghost"
- size="sm"
- className="pipeline-compare-btn"
- onClick={() => onCompare(stagingEnv, production)}
- title="Compare staging vs production"
- >
- <GitCompare size={14} />
- Compare vs Prod
- </Button>
- )}
- {devEnv && stagingEnv && (
- <Button
- variant="ghost"
- size="sm"
- className="pipeline-compare-btn"
- onClick={() => onCompare(devEnv, stagingEnv)}
- title="Compare development vs staging"
- >
- <GitCompare size={14} />
- Dev vs Staging
- </Button>
- )}
- </div>
- )}
-
- {/* Multidev section */}
- <div className="pipeline-multidev-section">
- <div className="pipeline-section-header">
- <h4 className="pipeline-section-title">
- <GitBranch size={16} />
- Multidev Environments
- {multidevEnvs.length > 0 && (
- <span className="pipeline-section-count">{multidevEnvs.length}</span>
- )}
- </h4>
- <Button
- variant="ghost"
- size="sm"
- onClick={onCreateMultidev}
- >
- <Plus size={14} />
- New Multidev
- </Button>
- </div>
- {multidevEnvs.length > 0 ? (
- <div className="pipeline-multidev-grid">
- {multidevEnvs.map(env => (
- <MultidevCard
- key={env.id}
- env={env}
- onStart={onStart}
- onStop={onStop}
- onRestart={onRestart}
- onDelete={onDelete}
- onPromote={onPromote}
- onSync={onSync}
- onLock={onLock}
- onUnlock={onUnlock}
- onViewLogs={onViewLogs}
- devEnv={devEnv}
- stagingEnv={stagingEnv}
- production={production}
- />
- ))}
- </div>
- ) : (
- <div className="pipeline-multidev-empty">
- <GitBranch size={24} />
- <p>No multidev environments yet</p>
- <span>Create branch-based environments for feature development and testing</span>
- <Button size="sm" onClick={onCreateMultidev}>
- <Plus size={14} />
- Create Multidev
- </Button>
- </div>
- )}
- </div>
- </div>
- );
-};
-
-const PipelineCard = ({
- env,
- isProduction = false,
- onStart,
- onStop,
- onRestart,
- onDelete,
- onLock,
- onUnlock,
- onViewLogs,
- onResourceLimits,
- onBasicAuth,
- onWpCli,
- onAutoSync,
- onHealthCheck,
- operationInProgress,
- healthStatus,
- diskUsage,
- bulkSelected,
- onBulkToggle,
-}) => {
- const [showMenu, setShowMenu] = useState(false);
- const isRunning = env.status === 'running' || env.application?.status === 'running';
- const envType = env.environment_type || (isProduction ? 'production' : 'development');
- const domain = env.application?.domains?.[0] || env.url || '';
-
- return (
- <div className={`pipeline-card ${isProduction ? 'production' : ''} ${env.is_locked ? 'locked' : ''}`}>
- <div className="pipeline-card-header">
- {onBulkToggle && !isProduction && (
- <Checkbox
- className="pipeline-card-checkbox"
- checked={bulkSelected || false}
- onCheckedChange={() => onBulkToggle(env.id)}
- />
- )}
- <EnvironmentStatusBadge
- type={envType}
- status={isRunning ? 'running' : 'stopped'}
- isLocked={env.is_locked}
- />
- {healthStatus && (
- <HealthDot status={healthStatus} size={8} />
- )}
- <div className="pipeline-card-menu-wrapper">
- <Button
- variant="ghost"
- size="sm"
- className="pipeline-card-menu-btn"
- onClick={() => setShowMenu(!showMenu)}
- >
- <MoreVertical size={14} />
- </Button>
- {showMenu && (
- <div className="pipeline-card-menu" onMouseLeave={() => setShowMenu(false)}>
- {isRunning ? (
- <>
- <button type="button" onClick={() => { onStop?.(env); setShowMenu(false); }}>
- <Square size={12} /> Stop
- </button>
- <button type="button" onClick={() => { onRestart?.(env); setShowMenu(false); }}>
- <RefreshCw size={12} /> Restart
- </button>
- </>
- ) : (
- <button type="button" onClick={() => { onStart?.(env); setShowMenu(false); }}>
- <Play size={12} /> Start
- </button>
- )}
- <button type="button" onClick={() => { onViewLogs?.(env); setShowMenu(false); }}>
- <FileText size={12} /> Logs
- </button>
- <div className="pipeline-card-menu-divider" />
- <button type="button" onClick={() => { onResourceLimits?.(env); setShowMenu(false); }}>
- <Cpu size={12} /> Resources
- </button>
- <button type="button" onClick={() => { onBasicAuth?.(env); setShowMenu(false); }}>
- <Shield size={12} /> Basic Auth
- </button>
- <button type="button" onClick={() => { onWpCli?.(env); setShowMenu(false); }}>
- <Terminal size={12} /> WP-CLI
- </button>
- {!isProduction && onAutoSync && (
- <button type="button" onClick={() => { onAutoSync?.(env); setShowMenu(false); }}>
- <Clock size={12} /> Auto-Sync
- </button>
- )}
- <div className="pipeline-card-menu-divider" />
- {env.is_locked ? (
- <button type="button" onClick={() => { onUnlock?.(env); setShowMenu(false); }}>
- <Unlock size={12} /> Unlock
- </button>
- ) : (
- <button type="button" onClick={() => { onLock?.(env); setShowMenu(false); }}>
- <Lock size={12} /> Lock
- </button>
- )}
- {!isProduction && (
- <button type="button" className="danger" onClick={() => { onDelete?.(env); setShowMenu(false); }}>
- <Trash2 size={12} /> Delete
- </button>
- )}
- </div>
- )}
- </div>
- </div>
-
- <div className="pipeline-card-body">
- <h4 className="pipeline-card-name">{env.name}</h4>
- {domain && (
- <a
- href={domain.startsWith('http') ? domain : `https://${domain}`}
- target="_blank"
- rel="noopener noreferrer"
- className="pipeline-card-domain"
- >
- {domain}
- </a>
- )}
- <div className="pipeline-card-meta">
- {env.wp_version && (
- <span className="pipeline-meta-item">v{env.wp_version}</span>
- )}
- {env.last_sync && !isProduction && (
- <span className="pipeline-meta-item">
- Synced {formatRelativeTime(env.last_sync)}
- </span>
- )}
- {diskUsage && (
- <DiskUsageBar usage={diskUsage} compact />
- )}
- </div>
- </div>
-
- <div className="pipeline-card-footer">
- {domain && (
- <a
- href={domain.startsWith('http') ? domain : `https://${domain}`}
- target="_blank"
- rel="noopener noreferrer"
- className="btn btn-ghost btn-sm"
- >
- <ExternalLink size={12} /> Visit
- </a>
- )}
- <Button variant="ghost" size="sm" onClick={() => onViewLogs?.(env)}>
- <FileText size={12} /> Logs
- </Button>
- </div>
-
- {env.is_locked && env.locked_reason && (
- <div className="alert alert-warning">
- <Lock size={10} />
- <span>{env.locked_reason}</span>
- </div>
- )}
- </div>
- );
-};
-
-const PipelineArrow = ({ label, direction, disabled, onClick }) => {
- return (
- <div className={`pipeline-arrow ${disabled ? 'disabled' : ''}`}>
- <button type="button"
- className="pipeline-arrow-btn"
- onClick={onClick}
- disabled={disabled}
- title={disabled ? 'Environment not available' : label}
- >
- <ArrowRight size={16} />
- <span className="pipeline-arrow-label">{label}</span>
- </button>
- </div>
- );
-};
-
-const EmptySlot = ({ type }) => {
- return (
- <div className="pipeline-card empty">
- <div className="pipeline-empty-content">
- <span className={`wp-env-badge env-${type}`}>
- {type.toUpperCase()}
- </span>
- <p>No {type} environment</p>
- </div>
- </div>
- );
-};
-
-const MultidevCard = ({
- env, onStart, onStop, onRestart, onDelete, onPromote,
- onSync, onLock, onUnlock, onViewLogs,
- devEnv, stagingEnv, production
-}) => {
- const [showMenu, setShowMenu] = useState(false);
- const isRunning = env.status === 'running' || env.application?.status === 'running';
- const domain = env.application?.domains?.[0] || env.url || '';
-
- const promoteTarget = devEnv || stagingEnv || production;
-
- return (
- <div className={`multidev-card ${env.is_locked ? 'locked' : ''}`}>
- <div className="multidev-card-header">
- <div className="multidev-card-header-left">
- <span className="wp-env-badge env-multidev">MULTIDEV</span>
- <span className={`wp-env-status ${isRunning ? 'running' : 'stopped'}`}>
- <span className="status-dot" />
- {isRunning ? 'Running' : 'Stopped'}
- </span>
- {env.is_locked && (
- <Lock size={12} className="multidev-lock-icon" />
- )}
- </div>
- <div className="multidev-card-menu-wrapper">
- <Button
- variant="ghost"
- size="sm"
- onClick={() => setShowMenu(!showMenu)}
- >
- <MoreVertical size={14} />
- </Button>
- {showMenu && (
- <div className="pipeline-card-menu" onMouseLeave={() => setShowMenu(false)}>
- {isRunning ? (
- <>
- <button type="button" onClick={() => { onStop?.(env); setShowMenu(false); }}>
- <Square size={12} /> Stop
- </button>
- <button type="button" onClick={() => { onRestart?.(env); setShowMenu(false); }}>
- <RefreshCw size={12} /> Restart
- </button>
- </>
- ) : (
- <button type="button" onClick={() => { onStart?.(env); setShowMenu(false); }}>
- <Play size={12} /> Start
- </button>
- )}
- <button type="button" onClick={() => { onSync?.(env); setShowMenu(false); }}>
- <ArrowDownLeft size={12} /> Sync from Prod
- </button>
- <button type="button" onClick={() => { onViewLogs?.(env); setShowMenu(false); }}>
- <FileText size={12} /> Logs
- </button>
- {env.is_locked ? (
- <button type="button" onClick={() => { onUnlock?.(env); setShowMenu(false); }}>
- <Unlock size={12} /> Unlock
- </button>
- ) : (
- <button type="button" onClick={() => { onLock?.(env); setShowMenu(false); }}>
- <Lock size={12} /> Lock
- </button>
- )}
- <button type="button" className="danger" onClick={() => { onDelete?.(env); setShowMenu(false); }}>
- <Trash2 size={12} /> Delete
- </button>
- </div>
- )}
- </div>
- </div>
- <div className="multidev-card-body">
- <h5 className="multidev-card-name">{env.name}</h5>
- {env.multidev_branch && (
- <span className="multidev-branch">
- <GitBranch size={12} />
- {env.multidev_branch}
- </span>
- )}
- {domain && (
- <a
- href={domain.startsWith('http') ? domain : `https://${domain}`}
- target="_blank"
- rel="noopener noreferrer"
- className="multidev-domain"
- >
- {domain}
- </a>
- )}
- <div className="multidev-card-meta">
- {env.created_at && (
- <span className="multidev-meta-item">
- Created {formatRelativeTime(env.created_at)}
- </span>
- )}
- </div>
- </div>
- <div className="multidev-card-footer">
- {domain && (
- <a
- href={domain.startsWith('http') ? domain : `https://${domain}`}
- target="_blank"
- rel="noopener noreferrer"
- className="btn btn-ghost btn-sm"
- >
- <ExternalLink size={12} /> Visit
- </a>
- )}
- <Button
- variant="ghost"
- size="sm"
- onClick={() => promoteTarget && onPromote?.(env, promoteTarget)}
- disabled={!promoteTarget}
- title={promoteTarget ? `Promote to ${promoteTarget.environment_type || 'production'}` : 'No target environment'}
- >
- <ArrowRight size={12} /> Promote
- </Button>
- <Button variant="ghost" size="icon" onClick={() => onViewLogs?.(env)}>
- <FileText size={12} />
- </Button>
- <Button variant="destructive" size="icon" onClick={() => onDelete?.(env)}>
- <Trash2 size={12} />
- </Button>
- </div>
- {env.is_locked && env.locked_reason && (
- <div className="alert alert-warning">
- <Lock size={10} />
- <span>{env.locked_reason}</span>
- </div>
- )}
- </div>
- );
-};
-
-export default PipelineView;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/PromoteModal.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/PromoteModal.jsx
deleted file mode 100644
index bebaabb3..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/PromoteModal.jsx
+++ /dev/null
@@ -1,270 +0,0 @@
-import { useState, useEffect } from 'react';
-import { ArrowRight, Shield } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { Spinner } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from 'serverkit-sdk';
-import { Checkbox } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-
-const PromoteModal = ({ sourceEnv, targetEnv, onClose, onPromote }) => {
- const [promotionType, setPromotionType] = useState('code');
- const [config, setConfig] = useState({
- include_plugins: true,
- include_themes: true,
- include_mu_plugins: true,
- include_uploads: false,
- backup_target_first: true,
- sanitize: false,
- sanitization_profile_id: '',
- exclude_tables: '',
- truncate_tables: ''
- });
- const [loading, setLoading] = useState(false);
- const [profiles, setProfiles] = useState([]);
-
- useEffect(() => {
- loadProfiles();
- }, []);
-
- async function loadProfiles() {
- try {
- const data = await wordpressApi.getSanitizationProfiles();
- setProfiles(data.profiles || []);
- const defaultProfile = (data.profiles || []).find(p => p.is_default);
- if (defaultProfile) {
- setConfig(prev => ({ ...prev, sanitization_profile_id: String(defaultProfile.id) }));
- }
- } catch {
- setProfiles([]);
- }
- }
-
- async function handleSubmit(e) {
- e.preventDefault();
- setLoading(true);
- try {
- const submitConfig = { ...config };
- if (submitConfig.sanitization_profile_id) {
- submitConfig.sanitization_profile_id = Number(submitConfig.sanitization_profile_id);
- } else {
- delete submitConfig.sanitization_profile_id;
- }
- const toList = (s) => (s || '').split(',').map(t => t.trim()).filter(Boolean);
- submitConfig.exclude_tables = toList(config.exclude_tables);
- submitConfig.truncate_tables = toList(config.truncate_tables);
- await onPromote({
- source_env_id: sourceEnv.id,
- target_env_id: targetEnv.id,
- type: promotionType,
- config: submitConfig
- });
- } finally {
- setLoading(false);
- }
- }
-
- function handleConfigChange(key, value) {
- setConfig(prev => ({ ...prev, [key]: value }));
- }
-
- const sourceType = sourceEnv.environment_type || 'development';
- const targetType = targetEnv.environment_type || 'staging';
-
- return (
- <Modal open={true} onClose={onClose} title="Promote Environment" size="lg">
- <form onSubmit={handleSubmit}>
- <div className="promote-direction">
- <div className={`promote-env-pill ${sourceType}`}>
- <span className="promote-env-type">{sourceType}</span>
- <span className="promote-env-name">{sourceEnv.name}</span>
- </div>
- <ArrowRight size={20} className="promote-arrow" />
- <div className={`promote-env-pill ${targetType}`}>
- <span className="promote-env-type">{targetType}</span>
- <span className="promote-env-name">{targetEnv.name}</span>
- </div>
- </div>
-
- <div className="form-group">
- <Label>Promotion Type</Label>
- <div className="radio-group">
- <label className="radio-label">
- <input
- type="radio"
- name="promotionType"
- value="code"
- checked={promotionType === 'code'}
- onChange={e => setPromotionType(e.target.value)}
- />
- <div className="radio-content">
- <strong>Code Only</strong>
- <span>Sync themes, plugins, and mu-plugins via rsync</span>
- </div>
- </label>
- <label className="radio-label">
- <input
- type="radio"
- name="promotionType"
- value="database"
- checked={promotionType === 'database'}
- onChange={e => setPromotionType(e.target.value)}
- />
- <div className="radio-content">
- <strong>Database Only</strong>
- <span>Export, transform, and import database</span>
- </div>
- </label>
- <label className="radio-label">
- <input
- type="radio"
- name="promotionType"
- value="full"
- checked={promotionType === 'full'}
- onChange={e => setPromotionType(e.target.value)}
- />
- <div className="radio-content">
- <strong>Full (Code + Database)</strong>
- <span>Complete environment promotion</span>
- </div>
- </label>
- </div>
- </div>
-
- {(promotionType === 'code' || promotionType === 'full') && (
- <div className="form-group">
- <Label>Code Options</Label>
- <div className="checkbox-group">
- <label className="checkbox-label">
- <Checkbox
- checked={config.include_plugins}
- onCheckedChange={v => handleConfigChange('include_plugins', v)}
- />
- <span>Include plugins</span>
- </label>
- <label className="checkbox-label">
- <Checkbox
- checked={config.include_themes}
- onCheckedChange={v => handleConfigChange('include_themes', v)}
- />
- <span>Include themes</span>
- </label>
- <label className="checkbox-label">
- <Checkbox
- checked={config.include_mu_plugins}
- onCheckedChange={v => handleConfigChange('include_mu_plugins', v)}
- />
- <span>Include mu-plugins</span>
- </label>
- <label className="checkbox-label">
- <Checkbox
- checked={config.include_uploads}
- onCheckedChange={v => handleConfigChange('include_uploads', v)}
- />
- <span>Include uploads (media files)</span>
- </label>
- </div>
- </div>
- )}
-
- {(promotionType === 'database' || promotionType === 'full') && (
- <>
- <div className="form-group">
- <label className="checkbox-label">
- <Checkbox
- checked={config.sanitize}
- onCheckedChange={v => handleConfigChange('sanitize', v)}
- />
- <span>Sanitize database during promotion</span>
- </label>
- </div>
-
- {config.sanitize && profiles.length > 0 && (
- <div className="form-group">
- <Label>
- <Shield size={14} style={{ marginRight: 4, verticalAlign: -2 }} />
- Sanitization Profile
- </Label>
- <Select
- value={config.sanitization_profile_id}
- onValueChange={v => handleConfigChange('sanitization_profile_id', v)}
- >
- <SelectTrigger>
- <SelectValue placeholder="Manual configuration" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="">Manual configuration</SelectItem>
- {profiles.map(p => (
- <SelectItem key={p.id} value={String(p.id)}>
- {p.name}{p.is_default ? ' (default)' : ''}{p.is_builtin ? '' : ' (custom)'}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- {config.sanitization_profile_id && (
- <span className="form-hint">
- {profiles.find(p => String(p.id) === config.sanitization_profile_id)?.description || ''}
- </span>
- )}
- </div>
- )}
-
- <div className="form-group">
- <Label>Exclude tables (optional)</Label>
- <Input
- value={config.exclude_tables}
- onChange={e => handleConfigChange('exclude_tables', e.target.value)}
- placeholder="e.g. wp_statistics, wp_actionscheduler_logs"
- />
- <span className="form-hint">Comma-separated table names to omit from the promotion entirely.</span>
- </div>
- <div className="form-group">
- <Label>Truncate tables (optional)</Label>
- <Input
- value={config.truncate_tables}
- onChange={e => handleConfigChange('truncate_tables', e.target.value)}
- placeholder="e.g. wp_sessions, wp_woocommerce_log"
- />
- <span className="form-hint">Comma-separated tables to keep but empty (structure promoted, rows dropped).</span>
- </div>
- </>
- )}
-
- <div className="form-group">
- <label className="checkbox-label">
- <Checkbox
- checked={config.backup_target_first}
- onCheckedChange={v => handleConfigChange('backup_target_first', v)}
- />
- <span>Create snapshot of target before promoting</span>
- </label>
- <span className="form-hint">Recommended. Allows rollback if something goes wrong.</span>
- </div>
-
- {targetType === 'production' && (
- <div className="alert alert-warning">
- <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
- <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
- <line x1="12" y1="9" x2="12" y2="13" />
- <line x1="12" y1="17" x2="12.01" y2="17" />
- </svg>
- <span>You are promoting to <strong>production</strong>. This will affect the live site.</span>
- </div>
- )}
-
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose} disabled={loading}>
- Cancel
- </Button>
- <Button type="submit" disabled={loading}>
- {loading ? <><Spinner size="sm" /> Promoting...</> : 'Promote'}
- </Button>
- </div>
- </form>
- </Modal>
- );
-};
-
-export default PromoteModal;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/ResourceLimitsModal.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/ResourceLimitsModal.jsx
deleted file mode 100644
index db45e39d..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/ResourceLimitsModal.jsx
+++ /dev/null
@@ -1,152 +0,0 @@
-import { useState } from 'react';
-import { HardDrive, AlertTriangle } from 'lucide-react';
-import { Spinner } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-
-const PRESETS = {
- low: { memory: '256M', cpus: '0.25', db_memory: '256M', db_cpus: '0.25' },
- standard: { memory: '512M', cpus: '1.0', db_memory: '384M', db_cpus: '0.5' },
- high: { memory: '2G', cpus: '2.0', db_memory: '1G', db_cpus: '1.0' },
-};
-
-const MEMORY_OPTIONS = ['256M', '384M', '512M', '768M', '1G', '1.5G', '2G'];
-const CPU_OPTIONS = ['0.25', '0.5', '1.0', '1.5', '2.0'];
-
-const ResourceLimitsModal = ({ environment, currentLimits, onClose, onApply }) => {
- const [limits, setLimits] = useState({
- memory: currentLimits?.memory || '512M',
- cpus: currentLimits?.cpus || '1.0',
- db_memory: currentLimits?.db_memory || '384M',
- db_cpus: currentLimits?.db_cpus || '0.5',
- });
- const [loading, setLoading] = useState(false);
-
- function applyPreset(preset) {
- setLimits({ ...PRESETS[preset] });
- }
-
- function handleChange(key, value) {
- setLimits(prev => ({ ...prev, [key]: value }));
- }
-
- async function handleSubmit(e) {
- e.preventDefault();
- setLoading(true);
- try {
- await onApply(limits);
- } finally {
- setLoading(false);
- }
- }
-
- const envName = environment?.name || 'Environment';
-
- return (
- <Modal open={true} onClose={onClose} title="Resource Limits" className="resource-limits-modal">
- <form onSubmit={handleSubmit}>
- <div className="resource-limits-env-name">{envName}</div>
-
- <div className="resource-limits-presets">
- <span className="resource-limits-presets-label">Presets:</span>
- {Object.entries(PRESETS).map(([key]) => (
- <Button
- key={key}
- type="button"
- variant="ghost"
- size="sm"
- className="resource-preset-btn"
- onClick={() => applyPreset(key)}
- >
- {key.charAt(0).toUpperCase() + key.slice(1)}
- </Button>
- ))}
- </div>
-
- <div className="resource-limits-section">
- <h4>
- <HardDrive size={14} />
- WordPress Container
- </h4>
- <div className="resource-limits-row">
- <Label>Memory</Label>
- <Select value={limits.memory} onValueChange={v => handleChange('memory', v)}>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {MEMORY_OPTIONS.map(opt => (
- <SelectItem key={opt} value={opt}>{opt}</SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- <div className="resource-limits-row">
- <Label>CPU Cores</Label>
- <Select value={limits.cpus} onValueChange={v => handleChange('cpus', v)}>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {CPU_OPTIONS.map(opt => (
- <SelectItem key={opt} value={opt}>{opt}</SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- </div>
-
- <div className="resource-limits-section">
- <h4>
- <HardDrive size={14} />
- Database Container
- </h4>
- <div className="resource-limits-row">
- <Label>Memory</Label>
- <Select value={limits.db_memory} onValueChange={v => handleChange('db_memory', v)}>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {MEMORY_OPTIONS.filter((_, i) => i < 5).map(opt => (
- <SelectItem key={opt} value={opt}>{opt}</SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- <div className="resource-limits-row">
- <Label>CPU Cores</Label>
- <Select value={limits.db_cpus} onValueChange={v => handleChange('db_cpus', v)}>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {CPU_OPTIONS.filter((_, i) => i < 4).map(opt => (
- <SelectItem key={opt} value={opt}>{opt}</SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- </div>
-
- <div className="alert alert-warning">
- <AlertTriangle size={14} />
- <span>Applying resource limits will restart the environment containers.</span>
- </div>
-
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose} disabled={loading}>
- Cancel
- </Button>
- <Button type="submit" disabled={loading}>
- {loading ? <><Spinner size="sm" /> Applying...</> : 'Apply Limits'}
- </Button>
- </div>
- </form>
- </Modal>
- );
-};
-
-export default ResourceLimitsModal;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/SanitizationProfileForm.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/SanitizationProfileForm.jsx
deleted file mode 100644
index 4d98702c..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/SanitizationProfileForm.jsx
+++ /dev/null
@@ -1,327 +0,0 @@
-import { useState, useEffect } from 'react';
-import { Shield, Plus, Trash2, Star, Edit3, Save } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { Spinner } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { Checkbox } from 'serverkit-sdk';
-
-const SanitizationProfileForm = ({ onClose, onProfilesChange }) => {
- const [profiles, setProfiles] = useState([]);
- const [loading, setLoading] = useState(true);
- const [editingProfile, setEditingProfile] = useState(null);
- const [showCreateForm, setShowCreateForm] = useState(false);
-
- useEffect(() => {
- loadProfiles();
- }, []);
-
- async function loadProfiles() {
- setLoading(true);
- try {
- const data = await wordpressApi.getSanitizationProfiles();
- setProfiles(data.profiles || []);
- } catch {
- setProfiles([]);
- } finally {
- setLoading(false);
- }
- }
-
- async function handleDelete(profileId) {
- try {
- await wordpressApi.deleteSanitizationProfile(profileId);
- setProfiles(prev => prev.filter(p => p.id !== profileId));
- onProfilesChange?.();
- } catch {
- // handled silently
- }
- }
-
- async function handleSetDefault(profileId) {
- try {
- await wordpressApi.updateSanitizationProfile(profileId, { is_default: true });
- setProfiles(prev => prev.map(p => ({
- ...p,
- is_default: p.id === profileId
- })));
- onProfilesChange?.();
- } catch {
- // handled silently
- }
- }
-
- async function handleSaveProfile(profileData) {
- try {
- if (editingProfile) {
- const result = await wordpressApi.updateSanitizationProfile(
- editingProfile.id,
- profileData
- );
- setProfiles(prev => prev.map(p =>
- p.id === editingProfile.id ? result.profile : p
- ));
- } else {
- const result = await wordpressApi.createSanitizationProfile(profileData);
- setProfiles(prev => [...prev, result.profile]);
- }
- setEditingProfile(null);
- setShowCreateForm(false);
- onProfilesChange?.();
- } catch {
- // handled silently
- }
- }
-
- return (
- <Modal open={true} onClose={onClose} title="Sanitization Profiles" size="lg">
- <div className="sanitization-profiles-body">
- {loading ? (
- <div className="sanitization-loading">
- <Spinner size="md" />
- </div>
- ) : (
- <>
- <div className="sanitization-profile-list">
- {profiles.map(profile => (
- <ProfileCard
- key={profile.id}
- profile={profile}
- onEdit={() => { setEditingProfile(profile); setShowCreateForm(false); }}
- onDelete={() => handleDelete(profile.id)}
- onSetDefault={() => handleSetDefault(profile.id)}
- />
- ))}
- </div>
-
- {!showCreateForm && !editingProfile && (
- <Button
- size="sm"
- className="sanitization-add-btn"
- onClick={() => setShowCreateForm(true)}
- >
- <Plus size={14} />
- Create Custom Profile
- </Button>
- )}
-
- {(showCreateForm || editingProfile) && (
- <ProfileEditor
- profile={editingProfile}
- onSave={handleSaveProfile}
- onCancel={() => { setEditingProfile(null); setShowCreateForm(false); }}
- />
- )}
- </>
- )}
- </div>
-
- <div className="modal-actions">
- <Button variant="outline" onClick={onClose}>Close</Button>
- </div>
- </Modal>
- );
-};
-
-const ProfileCard = ({ profile, onEdit, onDelete, onSetDefault }) => (
- <div className={`sanitization-profile-card ${profile.is_default ? 'default' : ''}`}>
- <div className="sanitization-profile-card-header">
- <div className="sanitization-profile-card-title">
- <h5>{profile.name}</h5>
- {profile.is_builtin && <span className="sanitization-tag builtin">Built-in</span>}
- {profile.is_default && <span className="sanitization-tag default">Default</span>}
- </div>
- <div className="sanitization-profile-card-actions">
- {!profile.is_default && (
- <Button variant="ghost" size="sm" onClick={onSetDefault} title="Set as default">
- <Star size={12} />
- </Button>
- )}
- <Button variant="ghost" size="sm" onClick={onEdit} title="Edit">
- <Edit3 size={12} />
- </Button>
- {!profile.is_builtin && (
- <Button variant="ghost" size="sm" onClick={onDelete} title="Delete">
- <Trash2 size={12} />
- </Button>
- )}
- </div>
- </div>
- {profile.description && (
- <p className="sanitization-profile-desc">{profile.description}</p>
- )}
- <div className="sanitization-profile-rules">
- <ProfileRuleTags config={profile.config} />
- </div>
- </div>
-);
-
-const ProfileRuleTags = ({ config }) => {
- const tags = [];
- if (config.anonymize_emails) tags.push('Anonymize emails');
- if (config.anonymize_names) tags.push('Anonymize names');
- if (config.reset_passwords) tags.push('Reset passwords');
- if (config.strip_payment_data) tags.push('Strip payments');
- if (config.remove_transients) tags.push('Clear transients');
- if (config.truncate_tables?.length > 0) tags.push(`Truncate ${config.truncate_tables.length} tables`);
- if (config.exclude_tables?.length > 0) tags.push(`Exclude ${config.exclude_tables.length} tables`);
- if (config.custom_search_replace && Object.keys(config.custom_search_replace).length > 0) {
- tags.push(`${Object.keys(config.custom_search_replace).length} replacements`);
- }
-
- return (
- <div className="sanitization-rule-tags">
- {tags.map(tag => (
- <span key={tag} className="sanitization-rule-tag">{tag}</span>
- ))}
- {tags.length === 0 && (
- <span className="sanitization-rule-tag empty">No rules configured</span>
- )}
- </div>
- );
-};
-
-const ProfileEditor = ({ profile, onSave, onCancel }) => {
- const [name, setName] = useState(profile?.name || '');
- const [description, setDescription] = useState(profile?.description || '');
- const [config, setConfig] = useState(profile?.config || {
- anonymize_emails: false,
- anonymize_names: false,
- reset_passwords: false,
- truncate_tables: [],
- exclude_tables: [],
- strip_payment_data: false,
- remove_transients: false,
- custom_search_replace: {},
- });
- const [truncateInput, setTruncateInput] = useState(
- (profile?.config?.truncate_tables || []).join(', ')
- );
- const [excludeInput, setExcludeInput] = useState(
- (profile?.config?.exclude_tables || []).join(', ')
- );
- const [saving, setSaving] = useState(false);
-
- function handleConfigToggle(key) {
- setConfig(prev => ({ ...prev, [key]: !prev[key] }));
- }
-
- async function handleSubmit(e) {
- e.preventDefault();
- setSaving(true);
- try {
- const finalConfig = {
- ...config,
- truncate_tables: truncateInput.split(',').map(s => s.trim()).filter(Boolean),
- exclude_tables: excludeInput.split(',').map(s => s.trim()).filter(Boolean),
- };
- await onSave({ name, description, config: finalConfig });
- } finally {
- setSaving(false);
- }
- }
-
- return (
- <form className="sanitization-editor" onSubmit={handleSubmit}>
- <h4>{profile ? 'Edit Profile' : 'Create Profile'}</h4>
-
- <div className="form-group">
- <Label>Profile Name *</Label>
- <Input
- type="text"
- value={name}
- onChange={e => setName(e.target.value)}
- placeholder="My Custom Profile"
- required
- disabled={profile?.is_builtin}
- />
- </div>
-
- <div className="form-group">
- <Label>Description</Label>
- <Input
- type="text"
- value={description}
- onChange={e => setDescription(e.target.value)}
- placeholder="What this profile does..."
- />
- </div>
-
- <div className="form-group">
- <Label>Data Sanitization</Label>
- <div className="checkbox-group">
- <label className="checkbox-label">
- <Checkbox
- checked={config.anonymize_emails || false}
- onCheckedChange={() => handleConfigToggle('anonymize_emails')}
- />
- <span>Anonymize email addresses</span>
- </label>
- <label className="checkbox-label">
- <Checkbox
- checked={config.anonymize_names || false}
- onCheckedChange={() => handleConfigToggle('anonymize_names')}
- />
- <span>Anonymize user names</span>
- </label>
- <label className="checkbox-label">
- <Checkbox
- checked={config.reset_passwords || false}
- onCheckedChange={() => handleConfigToggle('reset_passwords')}
- />
- <span>Reset all passwords</span>
- </label>
- <label className="checkbox-label">
- <Checkbox
- checked={config.strip_payment_data || false}
- onCheckedChange={() => handleConfigToggle('strip_payment_data')}
- />
- <span>Strip WooCommerce payment data</span>
- </label>
- <label className="checkbox-label">
- <Checkbox
- checked={config.remove_transients || false}
- onCheckedChange={() => handleConfigToggle('remove_transients')}
- />
- <span>Remove transients</span>
- </label>
- </div>
- </div>
-
- <div className="form-group">
- <Label>Truncate Tables (comma-separated)</Label>
- <Input
- type="text"
- value={truncateInput}
- onChange={e => setTruncateInput(e.target.value)}
- placeholder="actionscheduler_actions, actionscheduler_logs"
- />
- <span className="form-hint">Tables to empty (structure preserved, data removed)</span>
- </div>
-
- <div className="form-group">
- <Label>Exclude Tables (comma-separated)</Label>
- <Input
- type="text"
- value={excludeInput}
- onChange={e => setExcludeInput(e.target.value)}
- placeholder="wp_users, wp_usermeta"
- />
- <span className="form-hint">Tables to skip during sync/promote</span>
- </div>
-
- <div className="sanitization-editor-actions">
- <Button type="button" variant="outline" size="sm" onClick={onCancel}>
- Cancel
- </Button>
- <Button type="submit" size="sm" disabled={saving || !name.trim()}>
- {saving ? <><Spinner size="sm" /> Saving...</> : <><Save size={14} /> Save Profile</>}
- </Button>
- </div>
- </form>
- );
-};
-
-export default SanitizationProfileForm;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/SnapshotTable.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/SnapshotTable.jsx
deleted file mode 100644
index 4a046e23..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/SnapshotTable.jsx
+++ /dev/null
@@ -1,163 +0,0 @@
-import { useState } from 'react';
-import { Download, RotateCcw, Trash2, GitCommit, Tag } from 'lucide-react';
-import { ConfirmDialog } from 'serverkit-sdk';
-import { formatBytes } from 'serverkit-sdk';
-import { EmptyState } from 'serverkit-sdk';
-
-const SnapshotTable = ({ snapshots, onRestore, onDelete, loading = false }) => {
- const [actionLoading, setActionLoading] = useState({});
- const [confirmRestore, setConfirmRestore] = useState(null);
- const [confirmDelete, setConfirmDelete] = useState(null);
-
- function formatDate(dateString) {
- if (!dateString) return '-';
- return new Date(dateString).toLocaleString();
- }
-
- async function handleRestore(snapshot) {
- setConfirmRestore(null);
- setActionLoading(prev => ({ ...prev, [`restore-${snapshot.id}`]: true }));
- try {
- await onRestore?.(snapshot.id);
- } finally {
- setActionLoading(prev => ({ ...prev, [`restore-${snapshot.id}`]: false }));
- }
- }
-
- async function handleDelete(snapshot) {
- setConfirmDelete(null);
- setActionLoading(prev => ({ ...prev, [`delete-${snapshot.id}`]: true }));
- try {
- await onDelete?.(snapshot.id);
- } finally {
- setActionLoading(prev => ({ ...prev, [`delete-${snapshot.id}`]: false }));
- }
- }
-
- if (loading) {
- return <EmptyState loading title="Loading snapshots..." />;
- }
-
- if (!snapshots || snapshots.length === 0) {
- return (
- <div className="empty-state-small">
- <p>No database snapshots yet.</p>
- <p className="hint">Create a snapshot to backup your database.</p>
- </div>
- );
- }
-
- return (
- <div className="wp-table-card">
- <table className="sk-dtable wp-snapshot-table">
- <thead>
- <tr>
- <th>Snapshot</th>
- <th>Size</th>
- <th>Created</th>
- <th>Git Context</th>
- <th className="wp-th-right">Actions</th>
- </tr>
- </thead>
- <tbody>
- {snapshots.map(snapshot => (
- <tr key={snapshot.id}>
- <td>
- <div className="snapshot-name-cell">
- <span className="snapshot-name">{snapshot.name}</span>
- {snapshot.tag && (
- <span className="snapshot-tag">
- <Tag size={10} /> {snapshot.tag}
- </span>
- )}
- {snapshot.description && (
- <span className="snapshot-desc">{snapshot.description}</span>
- )}
- </div>
- </td>
- <td>
- <span className="mono">{formatBytes(snapshot.size_bytes)}</span>
- {snapshot.compressed && (
- <span className="compressed-badge" title="Compressed">gz</span>
- )}
- </td>
- <td><span className="snapshot-date">{formatDate(snapshot.created_at)}</span></td>
- <td>
- {snapshot.commit_sha ? (
- <div className="git-context">
- <GitCommit size={12} />
- <span className="mono git-context-sha">{snapshot.commit_sha.substring(0, 7)}</span>
- {snapshot.commit_message && (
- <span className="commit-msg" title={snapshot.commit_message}>
- {snapshot.commit_message.substring(0, 30)}
- {snapshot.commit_message.length > 30 && '...'}
- </span>
- )}
- </div>
- ) : (
- <span className="text-muted">-</span>
- )}
- </td>
- <td className="wp-cell-actions">
- <button type="button"
- className="wp-row-action"
- title="Restore"
- onClick={() => setConfirmRestore(snapshot)}
- disabled={actionLoading[`restore-${snapshot.id}`]}
- >
- <RotateCcw size={14} />
- </button>
- <button type="button"
- className="wp-row-action wp-row-action--danger"
- title="Delete"
- onClick={() => setConfirmDelete(snapshot)}
- disabled={actionLoading[`delete-${snapshot.id}`]}
- >
- <Trash2 size={14} />
- </button>
- </td>
- </tr>
- ))}
- </tbody>
- </table>
-
- <ConfirmDialog
- isOpen={!!confirmRestore}
- title="Restore Database Snapshot"
- message={`Restore database from "${confirmRestore?.name}"?`}
- details={
- <ul>
- <li><strong>Warning:</strong> This will overwrite your current database</li>
- <li>Snapshot size: <code>{formatBytes(confirmRestore?.size_bytes)}</code></li>
- <li>Created: {formatDate(confirmRestore?.created_at)}</li>
- {confirmRestore?.commit_sha && (
- <li>Git commit: <code>{confirmRestore.commit_sha.substring(0, 7)}</code></li>
- )}
- </ul>
- }
- confirmText="Restore Snapshot"
- variant="warning"
- onConfirm={() => handleRestore(confirmRestore)}
- onCancel={() => setConfirmRestore(null)}
- />
-
- <ConfirmDialog
- isOpen={!!confirmDelete}
- title="Delete Snapshot"
- message={`Delete snapshot "${confirmDelete?.name}"?`}
- details={
- <ul>
- <li>This snapshot will be permanently deleted</li>
- <li>This action cannot be undone</li>
- </ul>
- }
- confirmText="Delete Snapshot"
- variant="danger"
- onConfirm={() => handleDelete(confirmDelete)}
- onCancel={() => setConfirmDelete(null)}
- />
- </div>
- );
-};
-
-export default SnapshotTable;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/SyncModal.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/SyncModal.jsx
deleted file mode 100644
index 8628ef26..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/SyncModal.jsx
+++ /dev/null
@@ -1,221 +0,0 @@
-import { useState, useEffect } from 'react';
-import { ArrowDownLeft, Shield } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { Spinner } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from 'serverkit-sdk';
-import { Checkbox } from 'serverkit-sdk';
-
-const SyncModal = ({ environment, productionName, onClose, onSync }) => {
- const [syncType, setSyncType] = useState('database');
- const [config, setConfig] = useState({
- sanitize: false,
- truncate_tables: '',
- exclude_tables: '',
- sanitization_profile_id: ''
- });
- const [loading, setLoading] = useState(false);
- const [profiles, setProfiles] = useState([]);
-
- useEffect(() => {
- loadProfiles();
- }, []);
-
- async function loadProfiles() {
- try {
- const data = await wordpressApi.getSanitizationProfiles();
- setProfiles(data.profiles || []);
- const defaultProfile = (data.profiles || []).find(p => p.is_default);
- if (defaultProfile) {
- setConfig(prev => ({
- ...prev,
- sanitization_profile_id: String(defaultProfile.id),
- sanitize: true
- }));
- }
- } catch {
- setProfiles([]);
- }
- }
-
- async function handleSubmit(e) {
- e.preventDefault();
- setLoading(true);
- try {
- await onSync({
- type: syncType,
- sanitize: config.sanitize,
- sanitization_profile_id: config.sanitization_profile_id
- ? Number(config.sanitization_profile_id) : null,
- truncate_tables: config.truncate_tables
- ? config.truncate_tables.split(',').map(s => s.trim()).filter(Boolean)
- : [],
- exclude_tables: config.exclude_tables
- ? config.exclude_tables.split(',').map(s => s.trim()).filter(Boolean)
- : []
- });
- } finally {
- setLoading(false);
- }
- }
-
- function handleConfigChange(key, value) {
- setConfig(prev => ({ ...prev, [key]: value }));
- }
-
- const envType = environment.environment_type || 'development';
-
- return (
- <Modal open={true} onClose={onClose} title="Sync from Production">
- <form onSubmit={handleSubmit}>
- <div className="sync-direction">
- <div className="promote-env-pill production">
- <span className="promote-env-type">Production</span>
- <span className="promote-env-name">{productionName}</span>
- </div>
- <ArrowDownLeft size={20} className="promote-arrow" />
- <div className={`promote-env-pill ${envType}`}>
- <span className="promote-env-type">{envType}</span>
- <span className="promote-env-name">{environment.name}</span>
- </div>
- </div>
-
- <div className="form-group">
- <Label>Sync Type</Label>
- <div className="radio-group">
- <label className="radio-label">
- <input
- type="radio"
- name="syncType"
- value="database"
- checked={syncType === 'database'}
- onChange={e => setSyncType(e.target.value)}
- />
- <div className="radio-content">
- <strong>Database Only</strong>
- <span>Pull production database into this environment</span>
- </div>
- </label>
- <label className="radio-label">
- <input
- type="radio"
- name="syncType"
- value="files"
- checked={syncType === 'files'}
- onChange={e => setSyncType(e.target.value)}
- />
- <div className="radio-content">
- <strong>Files Only</strong>
- <span>Pull production files (wp-content) into this environment</span>
- </div>
- </label>
- <label className="radio-label">
- <input
- type="radio"
- name="syncType"
- value="full"
- checked={syncType === 'full'}
- onChange={e => setSyncType(e.target.value)}
- />
- <div className="radio-content">
- <strong>Full Sync</strong>
- <span>Pull both database and files from production</span>
- </div>
- </label>
- </div>
- </div>
-
- {(syncType === 'database' || syncType === 'full') && (
- <>
- <div className="form-group">
- <label className="checkbox-label">
- <Checkbox
- checked={config.sanitize}
- onCheckedChange={v => handleConfigChange('sanitize', v)}
- />
- <span>Sanitize data (anonymize emails, reset passwords)</span>
- </label>
- </div>
-
- {config.sanitize && profiles.length > 0 && (
- <div className="form-group">
- <Label>
- <Shield size={14} style={{ marginRight: 4, verticalAlign: -2 }} />
- Sanitization Profile
- </Label>
- <Select
- value={config.sanitization_profile_id}
- onValueChange={v => handleConfigChange('sanitization_profile_id', v)}
- >
- <SelectTrigger>
- <SelectValue placeholder="Manual configuration" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="">Manual configuration</SelectItem>
- {profiles.map(p => (
- <SelectItem key={p.id} value={String(p.id)}>
- {p.name}{p.is_default ? ' (default)' : ''}{p.is_builtin ? '' : ' (custom)'}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- {config.sanitization_profile_id && (
- <span className="form-hint">
- {profiles.find(p => String(p.id) === config.sanitization_profile_id)?.description || ''}
- </span>
- )}
- </div>
- )}
-
- <div className="form-group">
- <Label>Exclude Tables (comma-separated, optional)</Label>
- <Input
- type="text"
- value={config.exclude_tables}
- onChange={e => handleConfigChange('exclude_tables', e.target.value)}
- placeholder="wp_users, wp_usermeta"
- />
- <span className="form-hint">Tables to skip during sync</span>
- </div>
-
- <div className="form-group">
- <Label>Truncate Tables (comma-separated, optional)</Label>
- <Input
- type="text"
- value={config.truncate_tables}
- onChange={e => handleConfigChange('truncate_tables', e.target.value)}
- placeholder="wp_actionscheduler_actions, wp_actionscheduler_logs"
- />
- <span className="form-hint">Tables to empty (structure kept, data removed)</span>
- </div>
- </>
- )}
-
- <div className="sync-warning">
- <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
- <circle cx="12" cy="12" r="10" />
- <path d="M12 8v4M12 16h.01" />
- </svg>
- <div>
- <strong>This will overwrite data</strong>
- <p>The current {syncType === 'files' ? 'files' : syncType === 'database' ? 'database' : 'database and files'} in this environment will be replaced with production data. A snapshot will be created before syncing.</p>
- </div>
- </div>
-
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose} disabled={loading}>
- Cancel
- </Button>
- <Button type="submit" disabled={loading}>
- {loading ? <><Spinner size="sm" /> Syncing...</> : 'Sync Now'}
- </Button>
- </div>
- </form>
- </Modal>
- );
-};
-
-export default SyncModal;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/WordPressSiteCard.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/WordPressSiteCard.jsx
deleted file mode 100644
index edda8060..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/WordPressSiteCard.jsx
+++ /dev/null
@@ -1,154 +0,0 @@
-import { useState } from 'react';
-import { useNavigate } from 'react-router-dom';
-import { ExternalLink, Settings, Copy, Trash2 } from 'lucide-react';
-import { ConfirmDialog } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-
-const WordPressSiteCard = ({ site, onDelete }) => {
- const navigate = useNavigate();
- const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
- const isRunning = site.status === 'running';
-
- function getEnvironmentCount() {
- return site.environments?.length || 0;
- }
-
- function handleVisitSite(e) {
- e.stopPropagation();
- if (site.url) {
- window.open(site.url, '_blank');
- }
- }
-
- function handleOpenDashboard(e) {
- e.stopPropagation();
- if (site.url) {
- window.open(`${site.url}/wp-admin`, '_blank');
- }
- }
-
- function handleManage() {
- navigate(`/wordpress/${site.id}`);
- }
-
- function handleDelete(e) {
- e.stopPropagation();
- setShowDeleteConfirm(true);
- }
-
- function confirmDelete() {
- setShowDeleteConfirm(false);
- onDelete?.(site.id);
- }
-
- return (
- <div className="wp-site-card" onClick={handleManage}>
- <div className="wp-site-card-header">
- <div className="wp-site-icon">
- <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor">
- <path d="M12 2C6.486 2 2 6.486 2 12s4.486 10 10 10 10-4.486 10-10S17.514 2 12 2zm0 19.542c-5.261 0-9.542-4.281-9.542-9.542S6.739 2.458 12 2.458 21.542 6.739 21.542 12 17.261 21.542 12 21.542z"/>
- </svg>
- </div>
- <div className="wp-site-info">
- <h3 className="wp-site-name">{site.name}</h3>
- {site.url && (
- <span className="wp-site-url">{site.url}</span>
- )}
- </div>
- <span className={`wp-site-status ${isRunning ? 'running' : 'stopped'}`}>
- <span className="status-dot" />
- {isRunning ? 'Running' : 'Stopped'}
- </span>
- </div>
-
- <div className="wp-site-card-body">
- <div className="wp-site-meta">
- <div className="wp-site-meta-item">
- <span className="meta-label">Version</span>
- <span className="meta-value">{site.wp_version || 'Unknown'}</span>
- </div>
- <div className="wp-site-meta-item">
- <span className="meta-label">Environments</span>
- <span className="meta-value">{getEnvironmentCount() + 1}</span>
- </div>
- {site.git_repo_url && (
- <div className="wp-site-meta-item">
- <span className="meta-label">Git</span>
- <span className="meta-value git-connected">Connected</span>
- </div>
- )}
- </div>
-
- {site.is_production && (
- <span className="wp-site-badge production">Production</span>
- )}
- {!site.is_production && site.production_site_id && (
- <span className="wp-site-badge development">Development</span>
- )}
- </div>
-
- <div className="wp-site-card-footer">
- <Button
- variant="ghost"
- size="sm"
- onClick={handleVisitSite}
- disabled={!site.url}
- title="Visit Site"
- >
- <ExternalLink size={14} />
- Visit
- </Button>
- <Button
- variant="ghost"
- size="sm"
- onClick={handleOpenDashboard}
- disabled={!site.url}
- title="Open Dashboard"
- >
- <Settings size={14} />
- Dashboard
- </Button>
- <Button
- variant="ghost"
- size="sm"
- onClick={handleManage}
- title="Manage Site"
- >
- <Copy size={14} />
- Manage
- </Button>
- <Button
- variant="ghost"
- size="sm"
- onClick={handleDelete}
- title="Delete Site"
- className="text-destructive hover:text-destructive"
- >
- <Trash2 size={14} />
- </Button>
- </div>
-
- <ConfirmDialog
- isOpen={showDeleteConfirm}
- title="Delete WordPress Site"
- message={`Are you sure you want to delete "${site.name}"? This action cannot be undone.`}
- details={
- <ul>
- <li>All site files will be permanently deleted</li>
- <li>Database <code>{site.db_name || 'associated database'}</code> will be removed</li>
- {site.environments?.length > 0 && (
- <li>{site.environments.length} linked environment(s) will also be deleted</li>
- )}
- </ul>
- }
- confirmText="Delete Site"
- variant="danger"
- requireConfirmation={site.name}
- onConfirm={confirmDelete}
- onCancel={() => setShowDeleteConfirm(false)}
- />
- </div>
- );
-};
-
-export default WordPressSiteCard;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/WpCliTerminal.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/WpCliTerminal.jsx
deleted file mode 100644
index 0bd0354f..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/WpCliTerminal.jsx
+++ /dev/null
@@ -1,192 +0,0 @@
-import { useState, useRef, useEffect } from 'react';
-import { Play, Clock } from 'lucide-react';
-import { Spinner } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-
-const QUICK_COMMANDS = [
- { label: 'Plugin List', command: 'wp plugin list --format=table' },
- { label: 'Cache Flush', command: 'wp cache flush' },
- { label: 'DB Check', command: 'wp db check' },
- { label: 'Site URL', command: 'wp option get siteurl' },
-];
-
-const HISTORY_KEY = 'wp_cli_history';
-const MAX_HISTORY = 50;
-
-const WpCliTerminal = ({ environment, prodId, onClose, api }) => {
- const [command, setCommand] = useState('');
- const [output, setOutput] = useState([]);
- const [executing, setExecuting] = useState(false);
- const [showHistory, setShowHistory] = useState(false);
- const [historyIndex, setHistoryIndex] = useState(-1);
-
- const inputRef = useRef(null);
- const outputRef = useRef(null);
-
- const history = JSON.parse(localStorage.getItem(HISTORY_KEY) || '[]');
-
- useEffect(() => {
- inputRef.current?.focus();
- }, []);
-
- useEffect(() => {
- if (outputRef.current) {
- outputRef.current.scrollTop = outputRef.current.scrollHeight;
- }
- }, [output]);
-
- function saveToHistory(cmd) {
- const updated = [cmd, ...history.filter(h => h !== cmd)].slice(0, MAX_HISTORY);
- localStorage.setItem(HISTORY_KEY, JSON.stringify(updated));
- }
-
- async function executeCommand(cmd) {
- if (!cmd.trim()) return;
-
- const cmdStr = cmd.trim();
- setCommand('');
- setExecuting(true);
- saveToHistory(cmdStr);
- setHistoryIndex(-1);
-
- setOutput(prev => [...prev, { type: 'command', text: cmdStr }]);
-
- try {
- const result = await api.executeWpCli(prodId, environment.id, cmdStr);
- if (result.success) {
- setOutput(prev => [...prev, { type: 'output', text: result.output || '(no output)' }]);
- } else {
- setOutput(prev => [...prev, { type: 'error', text: result.error || 'Command failed' }]);
- }
- } catch (err) {
- setOutput(prev => [...prev, { type: 'error', text: err.message || 'Execution failed' }]);
- } finally {
- setExecuting(false);
- inputRef.current?.focus();
- }
- }
-
- function handleKeyDown(e) {
- if (e.key === 'Enter' && !executing) {
- executeCommand(command);
- } else if (e.key === 'ArrowUp') {
- e.preventDefault();
- if (history.length > 0) {
- const newIndex = Math.min(historyIndex + 1, history.length - 1);
- setHistoryIndex(newIndex);
- setCommand(history[newIndex]);
- }
- } else if (e.key === 'ArrowDown') {
- e.preventDefault();
- if (historyIndex > 0) {
- const newIndex = historyIndex - 1;
- setHistoryIndex(newIndex);
- setCommand(history[newIndex]);
- } else {
- setHistoryIndex(-1);
- setCommand('');
- }
- }
- }
-
- const envName = environment?.name || 'Environment';
-
- return (
- <Modal open={true} onClose={onClose} title={`WP-CLI - ${envName}`} className="wpcli-terminal-modal">
- <div className="wpcli-quick-actions">
- {QUICK_COMMANDS.map(qc => (
- <Button
- key={qc.command}
- variant="ghost"
- size="sm"
- onClick={() => executeCommand(qc.command)}
- disabled={executing}
- >
- {qc.label}
- </Button>
- ))}
- <Button
- variant="ghost"
- size="sm"
- onClick={() => setShowHistory(!showHistory)}
- title="Command history"
- >
- <Clock size={12} />
- </Button>
- </div>
-
- {showHistory && history.length > 0 && (
- <div className="wpcli-history">
- {history.slice(0, 10).map((cmd, i) => (
- <button type="button"
- key={i}
- className="wpcli-history-item"
- onClick={() => {
- setCommand(cmd);
- setShowHistory(false);
- inputRef.current?.focus();
- }}
- >
- <code>{cmd}</code>
- </button>
- ))}
- </div>
- )}
-
- <div className="wpcli-output" ref={outputRef}>
- {output.length === 0 && (
- <div className="wpcli-output-empty">
- Enter a WP-CLI command below or use the quick actions above.
- </div>
- )}
- {output.map((entry, i) => (
- <div key={i} className={`wpcli-output-entry ${entry.type}`}>
- {entry.type === 'command' && (
- <div className="wpcli-output-command">
- <span className="wpcli-prompt">$</span>
- <code>{entry.text}</code>
- </div>
- )}
- {entry.type === 'output' && (
- <pre className="wpcli-output-text">{entry.text}</pre>
- )}
- {entry.type === 'error' && (
- <pre className="wpcli-output-error">{entry.text}</pre>
- )}
- </div>
- ))}
- {executing && (
- <div className="wpcli-executing">
- <Spinner size="sm" />
- <span>Executing...</span>
- </div>
- )}
- </div>
-
- <div className="wpcli-input-row">
- <span className="wpcli-prompt">$</span>
- <Input
- ref={inputRef}
- type="text"
- value={command}
- onChange={e => setCommand(e.target.value)}
- onKeyDown={handleKeyDown}
- placeholder="wp plugin list --format=table"
- disabled={executing}
- className="wpcli-input"
- />
- <Button
- size="sm"
- onClick={() => executeCommand(command)}
- disabled={executing || !command.trim()}
- >
- <Play size={12} />
- </Button>
- </div>
- </Modal>
- );
-};
-
-export default WpCliTerminal;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/AnalyticsTab.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/AnalyticsTab.jsx
deleted file mode 100644
index 6e27835a..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/AnalyticsTab.jsx
+++ /dev/null
@@ -1,189 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import { Link } from 'react-router-dom';
-import { ResponsiveContainer, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts';
-import { BarChart3, Globe, HardDrive, AlertTriangle, Activity, FileText, LineChart, ExternalLink } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { api } from 'serverkit-sdk';
-import { useToast } from 'serverkit-sdk';
-import { MetricCard, SegControl } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { OverviewGridSkeleton, ANALYTICS_PERIODS } from './wpDetailShared';
-
-// Analytics Tab — per-site traffic + error analytics (#25), parsed on-demand from
-// the apache container access log. PHP fatals, response time, and cache hit ratio
-// are not in the default access log (deferred to #30 / #22-#23).
-const AnalyticsTab = ({ siteId }) => {
- const toast = useToast();
- const [data, setData] = useState(null);
- const [loading, setLoading] = useState(true);
- const [hours, setHours] = useState(24);
- // Feature-detect the serverkit-analytics extension so we can point users at
- // the persistent, privacy-first dashboard when it's installed. The on-demand
- // access-log view below stays as a complementary, always-available source.
- const [analyticsExt, setAnalyticsExt] = useState(false);
-
- useEffect(() => {
- let alive = true;
- api.getInstalledPlugins('active')
- .then((res) => {
- if (!alive) return;
- const on = (res?.plugins || []).some(
- (p) => p.slug === 'serverkit-analytics' && p.status === 'active');
- setAnalyticsExt(on);
- })
- .catch(() => { /* extension absent — silently keep the log view */ });
- return () => { alive = false; };
- }, []);
-
- const load = React.useCallback(async () => {
- setLoading(true);
- try {
- const res = await wordpressApi.getSiteAnalytics(siteId, hours);
- setData(res);
- } catch (err) {
- toast.error(err.message || 'Failed to load analytics');
- } finally {
- setLoading(false);
- }
- }, [siteId, hours, toast]);
-
- useEffect(() => { load(); }, [load]);
-
- if (loading) return <SkeletonBoundary loading skeleton={<OverviewGridSkeleton panels={3} />} />;
-
- const fmtHour = (iso) => {
- const d = new Date(iso);
- return hours <= 24
- ? d.toLocaleTimeString([], { hour: '2-digit', hour12: false })
- : d.toLocaleDateString([], { month: 'short', day: 'numeric' });
- };
- const clip = (p) => (p && p.length > 48 ? `${p.slice(0, 48)}…` : p);
- const clipMsg = (m) => (m && m.length > 80 ? `${m.slice(0, 80)}…` : m);
- const s = data?.status || {};
- const phpErr = data?.php_errors;
-
- return (
- <div className="app-overview-grid">
- <div className="app-overview-left">
- {analyticsExt && (
- <div className="wp-analytics-banner">
- <LineChart size={16} />
- <div className="wp-analytics-banner__text">
- <strong>Analytics is installed.</strong>
- <span> Add this site there for persistent, cookieless visitor tracking with a full dashboard. The view below is parsed on demand from access logs.</span>
- </div>
- <Link to="/analytics/sites" className="wp-analytics-banner__link">
- Open Analytics <ExternalLink size={13} />
- </Link>
- </div>
- )}
- <div className="wp-analytics-head">
- <h3 className="wp-eyebrow">Traffic · {hours <= 24 ? 'last 24 hours' : 'last 7 days'}</h3>
- <SegControl
- options={ANALYTICS_PERIODS.map(p => ({ value: p.hours, label: p.label }))}
- value={hours}
- onChange={setHours}
- />
- </div>
- {data?.note && <p className="hint">{data.note}</p>}
- <div className="wp-kpis">
- <MetricCard icon={<BarChart3 size={16} />} tone="accent" value={(data?.requests ?? 0).toLocaleString()} label="Requests" />
- <MetricCard icon={<Globe size={16} />} tone="cyan" value={(data?.unique_visitors ?? 0).toLocaleString()} label="Unique visitors" />
- <MetricCard icon={<HardDrive size={16} />} tone="violet" value={data?.bytes_human || '0 B'} label="Bandwidth" />
- <MetricCard icon={<AlertTriangle size={16} />} tone={(data?.error_rate ?? 0) > 5 ? 'red' : 'amber'} value={`${data?.error_rate ?? 0}%`} label="Error rate" />
- <MetricCard icon={<Activity size={16} />} tone="green" value={`${data?.bot_pct ?? 0}%`} label="Bot traffic" />
- <MetricCard icon={<FileText size={16} />} tone="red" value={(data?.not_found ?? 0).toLocaleString()} label="404s" />
- </div>
-
- <div className="app-panel">
- <div className="app-panel-header">Requests over time</div>
- <div className="app-panel-body">
- <ResponsiveContainer width="100%" height={220}>
- <AreaChart data={data?.series || []} margin={{ top: 8, right: 8, left: -16, bottom: 0 }}>
- <defs>
- <linearGradient id="wpReq" x1="0" y1="0" x2="0" y2="1">
- <stop offset="5%" stopColor="#6d7cff" stopOpacity={0.35} />
- <stop offset="95%" stopColor="#6d7cff" stopOpacity={0} />
- </linearGradient>
- <linearGradient id="wpErr" x1="0" y1="0" x2="0" y2="1">
- <stop offset="5%" stopColor="#fb6f6f" stopOpacity={0.35} />
- <stop offset="95%" stopColor="#fb6f6f" stopOpacity={0} />
- </linearGradient>
- </defs>
- <CartesianGrid strokeDasharray="3 3" stroke="#888" strokeOpacity={0.15} />
- <XAxis dataKey="hour" tickFormatter={fmtHour} tick={{ fontSize: 11, fill: '#888' }} minTickGap={24} axisLine={false} tickLine={false} />
- <YAxis allowDecimals={false} tick={{ fontSize: 11, fill: '#888' }} width={36} axisLine={false} tickLine={false} />
- <Tooltip labelFormatter={fmtHour} />
- <Area type="monotone" dataKey="requests" name="Requests" stroke="#8b93ff" fill="url(#wpReq)" strokeWidth={2} />
- <Area type="monotone" dataKey="errors" name="Errors" stroke="#fb6f6f" fill="url(#wpErr)" strokeWidth={2} />
- </AreaChart>
- </ResponsiveContainer>
- </div>
- </div>
-
- <div className="app-panel">
- <div className="app-panel-header">Status codes</div>
- <div className="app-panel-body">
- <div className="app-info-grid">
- <div className="app-info-item"><span className="app-info-label">2xx</span><span className="app-info-value">{(s['2xx'] ?? 0).toLocaleString()}</span></div>
- <div className="app-info-item"><span className="app-info-label">3xx</span><span className="app-info-value">{(s['3xx'] ?? 0).toLocaleString()}</span></div>
- <div className="app-info-item"><span className="app-info-label">4xx</span><span className="app-info-value">{(s['4xx'] ?? 0).toLocaleString()}</span></div>
- <div className="app-info-item"><span className="app-info-label">5xx</span><span className="app-info-value">{(s['5xx'] ?? 0).toLocaleString()}</span></div>
- </div>
- </div>
- </div>
-
- {data?.top_paths?.length > 0 && (
- <div className="app-panel">
- <div className="app-panel-header">Top URLs</div>
- <div className="app-panel-body">
- <div className="app-info-grid">
- {data.top_paths.map((row, i) => (
- <div className="app-info-item" key={i}>
- <span className="app-info-label" title={row.path}>{clip(row.path)}</span>
- <span className="app-info-value">{row.count.toLocaleString()}</span>
- </div>
- ))}
- </div>
- <p className="hint">Read live from the container access log; response-time metrics are not captured by the default log.</p>
- </div>
- </div>
- )}
-
- {phpErr && (
- <div className="app-panel">
- <div className="app-panel-header">PHP errors</div>
- <div className="app-panel-body">
- {!phpErr.available ? (
- <p className="hint">{phpErr.note || 'PHP error logging is off.'}</p>
- ) : (
- <>
- <div className="app-info-grid">
- <div className="app-info-item"><span className="app-info-label">Fatal</span><span className="app-info-value">{(phpErr.counts?.fatal ?? 0).toLocaleString()}</span></div>
- <div className="app-info-item"><span className="app-info-label">Warning</span><span className="app-info-value">{(phpErr.counts?.warning ?? 0).toLocaleString()}</span></div>
- <div className="app-info-item"><span className="app-info-label">Notice</span><span className="app-info-value">{(phpErr.counts?.notice ?? 0).toLocaleString()}</span></div>
- <div className="app-info-item"><span className="app-info-label">Deprecated</span><span className="app-info-value">{(phpErr.counts?.deprecated ?? 0).toLocaleString()}</span></div>
- </div>
- {phpErr.recent?.length > 0 ? (
- <div className="app-info-grid">
- {phpErr.recent.map((e, i) => (
- <div className="app-info-item" key={i}>
- <span className="app-info-label" title={e.message}>{e.level}: {clipMsg(e.message)}</span>
- <span className="app-info-value">{e.time}</span>
- </div>
- ))}
- </div>
- ) : (
- <p className="hint">{phpErr.note || 'No PHP errors recorded.'}</p>
- )}
- </>
- )}
- </div>
- </div>
- )}
- </div>
- </div>
- );
-};
-
-export default AnalyticsTab;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/BackupsTab.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/BackupsTab.jsx
deleted file mode 100644
index deb1d422..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/BackupsTab.jsx
+++ /dev/null
@@ -1,16 +0,0 @@
-import ProtectionPanel from '@/components/backups/ProtectionPanel';
-
-// Backups Tab
-// Backups tab — now the shared Protection panel (scheduled backups, cost,
-// one-click restore). Renders for both the top-level "Backups" tab and the
-// Settings → Backups section.
-const BackupsTab = ({ siteId, site }) => (
- <ProtectionPanel
- targetType="wordpress_site"
- targetId={siteId}
- targetName={site?.name}
- showMaintenanceModeOption
- />
-);
-
-export default BackupsTab;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/DatabaseTab.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/DatabaseTab.jsx
deleted file mode 100644
index 08b70438..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/DatabaseTab.jsx
+++ /dev/null
@@ -1,217 +0,0 @@
-import { useState, useEffect } from 'react';
-import { Database, Plus } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { SnapshotTable } from '../index';
-import { ErrorState } from '@/components/ErrorBoundary';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { Textarea } from 'serverkit-sdk';
-
-// Database Tab
-const DatabaseTab = ({ siteId, site }) => {
- const toast = useToast();
- const [snapshots, setSnapshots] = useState([]);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState(null);
- const [showCreateModal, setShowCreateModal] = useState(false);
-
- useEffect(() => {
- loadSnapshots();
- }, [siteId]);
-
- async function loadSnapshots() {
- setLoading(true);
- setError(null);
- try {
- const data = await wordpressApi.getSnapshots(siteId);
- setSnapshots(data.snapshots || []);
- } catch (err) {
- console.error('Failed to load snapshots:', err);
- setError(err);
- } finally {
- setLoading(false);
- }
- }
-
- async function handleCreateSnapshot(data) {
- toast.info('Creating snapshot...', { duration: 3000 });
- try {
- await wordpressApi.createSnapshot(siteId, data);
- toast.success('Snapshot created successfully');
- loadSnapshots();
- setShowCreateModal(false);
- } catch (err) {
- toast.error(err.message || 'Failed to create snapshot');
- }
- }
-
- async function handleRestore(snapId) {
- toast.info('Restoring database... This may take a moment.', { duration: 5000 });
- try {
- await wordpressApi.restoreSnapshot(siteId, snapId);
- toast.success('Database restored from snapshot');
- } catch (err) {
- toast.error(err.message || 'Failed to restore snapshot');
- }
- }
-
- async function handleDelete(snapId) {
- try {
- await wordpressApi.deleteSnapshot(siteId, snapId);
- toast.success('Snapshot deleted');
- loadSnapshots();
- } catch (err) {
- toast.error(err.message || 'Failed to delete snapshot');
- }
- }
-
- if (error) {
- return (
- <ErrorState
- title="Failed to load snapshots"
- error={error}
- onRetry={loadSnapshots}
- />
- );
- }
-
- return (
- <div className="database-tab">
- {/* Database Connection Info */}
- <div className="app-panel">
- <div className="app-panel-header">
- <Database size={16} />
- Database Connection
- </div>
- <div className="app-panel-body">
- <div className="app-info-grid">
- <div className="app-info-item">
- <span className="app-info-label">Database Name</span>
- <span className="app-info-value mono">{site?.db_name || 'wordpress'}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Database User</span>
- <span className="app-info-value mono">{site?.db_user || 'wordpress'}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Database Host</span>
- <span className="app-info-value mono">{site?.db_host || 'db'}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Table Prefix</span>
- <span className="app-info-value mono">{site?.db_prefix || 'wp_'}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Container</span>
- <span className="app-info-value mono">{site?.compose_project_name ? `${site.compose_project_name}-db` : '-'}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Engine</span>
- <span className="app-info-value">MySQL 8.0</span>
- </div>
- </div>
- </div>
- </div>
-
- {/* Snapshots */}
- <div className="section-header mt-6">
- <h3>Database Snapshots</h3>
- <Button onClick={() => setShowCreateModal(true)}>
- <Plus size={14} /> Create Snapshot
- </Button>
- </div>
-
- <SnapshotTable
- snapshots={snapshots}
- loading={loading}
- onRestore={handleRestore}
- onDelete={handleDelete}
- />
-
- {showCreateModal && (
- <CreateSnapshotModal
- onClose={() => setShowCreateModal(false)}
- onCreate={handleCreateSnapshot}
- />
- )}
- </div>
- );
-};
-
-// Create Snapshot Modal
-const CreateSnapshotModal = ({ onClose, onCreate }) => {
- const [formData, setFormData] = useState({
- name: `Snapshot ${new Date().toLocaleDateString()}`,
- description: '',
- tag: ''
- });
- const [loading, setLoading] = useState(false);
-
- function handleChange(e) {
- const { name, value } = e.target;
- setFormData(prev => ({ ...prev, [name]: value }));
- }
-
- async function handleSubmit(e) {
- e.preventDefault();
- setLoading(true);
- try {
- await onCreate(formData);
- } finally {
- setLoading(false);
- }
- }
-
- return (
- <Modal open onClose={onClose} title="Create Snapshot">
- <form onSubmit={handleSubmit}>
- <div className="form-group">
- <Label>Snapshot Name *</Label>
- <Input
- type="text"
- name="name"
- value={formData.name}
- onChange={handleChange}
- required
- />
- </div>
-
- <div className="form-group">
- <Label>Description</Label>
- <Textarea
- name="description"
- value={formData.description}
- onChange={handleChange}
- placeholder="Optional description..."
- rows={3}
- />
- </div>
-
- <div className="form-group">
- <Label>Tag</Label>
- <Input
- type="text"
- name="tag"
- value={formData.tag}
- onChange={handleChange}
- placeholder="e.g., v1.0.0, before-update"
- />
- </div>
-
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose}>
- Cancel
- </Button>
- <Button type="submit" disabled={loading}>
- {loading ? 'Creating...' : 'Create Snapshot'}
- </Button>
- </div>
- </form>
- </Modal>
- );
-};
-
-export default DatabaseTab;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/EnvironmentsTab.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/EnvironmentsTab.jsx
deleted file mode 100644
index e0e281a4..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/EnvironmentsTab.jsx
+++ /dev/null
@@ -1,311 +0,0 @@
-import { useState, useEffect } from 'react';
-import { Plus } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { EnvironmentCard } from '../index';
-import { ErrorState } from '@/components/ErrorBoundary';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { EnvironmentCardSkeleton } from './wpDetailShared';
-
-// Environments Tab
-const EnvironmentsTab = ({ siteId, site, onUpdate }) => {
- const toast = useToast();
- const [environments, setEnvironments] = useState([]);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState(null);
- const [showCreateModal, setShowCreateModal] = useState(false);
-
- useEffect(() => {
- loadEnvironments();
- }, [siteId]);
-
- async function loadEnvironments() {
- setLoading(true);
- setError(null);
- try {
- const data = await wordpressApi.getEnvironments(siteId);
- setEnvironments(data.environments || []);
- } catch (err) {
- console.error('Failed to load environments:', err);
- setError(err);
- } finally {
- setLoading(false);
- }
- }
-
- async function handleCreateEnvironment(data) {
- toast.info('Creating environment... This may take a moment.', { duration: 5000 });
- try {
- await wordpressApi.createEnvironment(siteId, data);
- toast.success('Environment created successfully');
- loadEnvironments();
- setShowCreateModal(false);
- } catch (err) {
- toast.error(err.message || 'Failed to create environment');
- }
- }
-
- async function handleSync(envId) {
- toast.info('Syncing from production...', { duration: 3000 });
- try {
- await wordpressApi.syncEnvironment(siteId, { environment_id: envId });
- toast.success('Environment synced from production');
- loadEnvironments();
- } catch (err) {
- toast.error(err.message || 'Failed to sync environment');
- }
- }
-
- async function handleDelete(envId) {
- toast.info('Deleting environment...', { duration: 2000 });
- try {
- await wordpressApi.deleteEnvironment(siteId, envId);
- toast.success('Environment deleted');
- loadEnvironments();
- } catch (err) {
- toast.error(err.message || 'Failed to delete environment');
- }
- }
-
- if (loading) {
- return (
- <SkeletonBoundary loading skeleton={(
- <div className="environments-tab">
- <div className="section-header">
- <div className="skeleton" style={{ width: 120, height: 24 }} />
- <div className="skeleton" style={{ width: 160, height: 36, borderRadius: 6 }} />
- </div>
- <div className="environments-grid">
- <EnvironmentCardSkeleton />
- <EnvironmentCardSkeleton />
- </div>
- </div>
- )} />
- );
- }
-
- if (error) {
- return (
- <ErrorState
- title="Failed to load environments"
- error={error}
- onRetry={loadEnvironments}
- />
- );
- }
-
- // Filter out production from the environments list (it's shown separately)
- const childEnvs = environments.filter(e => e.id !== site.id && !e.is_production);
- const hasStaging = childEnvs.some(e => e.environment_type === 'staging');
- const hasDev = childEnvs.some(e => e.environment_type === 'development');
- const canCreateMore = site.is_production && (!hasStaging || !hasDev);
-
- return (
- <div className="environments-tab">
- <div className="section-header">
- <h3>Environments</h3>
- {canCreateMore && (
- <Button onClick={() => setShowCreateModal(true)}>
- <Plus size={14} /> Create Environment
- </Button>
- )}
- </div>
-
- <div className="environments-grid">
- {/* Production environment (the current site) */}
- <EnvironmentCard
- environment={{
- id: site.id,
- name: site.name,
- url: site.url,
- status: site.status,
- db_name: site.db_name,
- type: 'production'
- }}
- isProduction={true}
- />
-
- {/* Dev/staging environments */}
- {childEnvs.map(env => (
- <EnvironmentCard
- key={env.id}
- environment={env}
- productionUrl={site.url}
- onSync={handleSync}
- onDelete={handleDelete}
- />
- ))}
-
- {/* Add-environment tile — sits inline next to the existing
- environments instead of a full-width "empty" block. */}
- {canCreateMore && (
- <button
- type="button"
- className="wp-env-add-tile"
- onClick={() => setShowCreateModal(true)}
- >
- <span className="wp-env-add-tile__icon"><Plus size={22} /></span>
- <span className="wp-env-add-tile__title">Create environment</span>
- <span className="wp-env-add-tile__hint">
- {childEnvs.length === 0
- ? 'Spin up a dev or staging copy to test changes safely before deploying to production.'
- : 'Add another dev or staging copy.'}
- </span>
- </button>
- )}
- </div>
-
- {showCreateModal && (
- <CreateEnvironmentModal
- onClose={() => setShowCreateModal(false)}
- onCreate={handleCreateEnvironment}
- productionDomain={site.url}
- hasStaging={hasStaging}
- hasDev={hasDev}
- />
- )}
- </div>
- );
-};
-
-// Create Environment Modal
-export const CreateEnvironmentModal = ({ onClose, onCreate, productionDomain, hasStaging = false, hasDev = false }) => {
- // Default to whichever type is still available
- const defaultType = !hasDev ? 'development' : !hasStaging ? 'staging' : 'development';
- const [formData, setFormData] = useState({
- type: defaultType,
- name: '',
- domain: '',
- cloneDb: true,
- syncSchedule: ''
- });
- const [loading, setLoading] = useState(false);
-
- // Generate suggested domain based on production domain
- function getSuggestedDomain() {
- if (!productionDomain) return '';
- try {
- const url = new URL(productionDomain);
- const prefix = formData.type === 'staging' ? 'staging' : 'dev';
- return `${prefix}.${url.hostname}`;
- } catch {
- return '';
- }
- }
-
- const suggestedDomain = getSuggestedDomain();
- const displayDomain = formData.domain || suggestedDomain;
-
- function handleChange(e) {
- const { name, value, type, checked } = e.target;
- setFormData(prev => ({
- ...prev,
- [name]: type === 'checkbox' ? checked : value
- }));
- }
-
- async function handleSubmit(e) {
- e.preventDefault();
- setLoading(true);
- try {
- await onCreate({
- type: formData.type,
- name: formData.name,
- domain: formData.domain || suggestedDomain,
- clone_db: formData.cloneDb,
- sync_schedule: formData.syncSchedule || null
- });
- } finally {
- setLoading(false);
- }
- }
-
- return (
- <Modal open onClose={onClose} title="Create Environment">
- <form onSubmit={handleSubmit}>
- <div className="form-group">
- <Label>Environment Type</Label>
- <select name="type" value={formData.type} onChange={handleChange}>
- {!hasDev && <option value="development">Development</option>}
- {!hasStaging && <option value="staging">Staging</option>}
- </select>
- </div>
-
- <div className="form-group">
- <Label>Environment Name *</Label>
- <Input
- type="text"
- name="name"
- value={formData.name}
- onChange={handleChange}
- placeholder="My Site Dev"
- required
- />
- </div>
-
- <div className="form-group">
- <Label>Domain</Label>
- <Input
- type="text"
- name="domain"
- value={formData.domain}
- onChange={handleChange}
- placeholder={suggestedDomain || 'dev.example.com'}
- />
- {suggestedDomain && !formData.domain && (
- <span className="form-hint form-hint-domain">
- Will use: <code>{suggestedDomain}</code>
- </span>
- )}
- {!suggestedDomain && !formData.domain && (
- <span className="form-hint">Enter a domain or leave empty to auto-generate</span>
- )}
- </div>
-
- {displayDomain && (
- <div className="env-preview-url">
- <span className="preview-label">Environment URL:</span>
- <span className="preview-url">https://{displayDomain}</span>
- </div>
- )}
-
- <div className="form-group">
- <label className="checkbox-label">
- <input
- type="checkbox"
- name="cloneDb"
- checked={formData.cloneDb}
- onChange={handleChange}
- />
- <span>Clone production database</span>
- </label>
- </div>
-
- <div className="form-group">
- <Label>Sync Schedule (optional)</Label>
- <select name="syncSchedule" value={formData.syncSchedule} onChange={handleChange}>
- <option value="">No automatic sync</option>
- <option value="0 3 * * 0">Weekly (Sunday 3am)</option>
- <option value="0 3 * * *">Daily (3am)</option>
- </select>
- <span className="form-hint">Automatically sync database from production</span>
- </div>
-
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose}>
- Cancel
- </Button>
- <Button type="submit" disabled={loading}>
- {loading ? 'Creating...' : 'Create Environment'}
- </Button>
- </div>
- </form>
- </Modal>
- );
-};
-
-export default EnvironmentsTab;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/GitTab.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/GitTab.jsx
deleted file mode 100644
index d34af5d7..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/GitTab.jsx
+++ /dev/null
@@ -1,130 +0,0 @@
-import { useState, useEffect } from 'react';
-import { RefreshCw } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { GitConnectForm, CommitList } from '../index';
-import { ErrorState } from '@/components/ErrorBoundary';
-import { Button } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-
-// Git Tab
-const GitTab = ({ siteId, site, onUpdate }) => {
- const toast = useToast();
- const [gitStatus, setGitStatus] = useState(null);
- const [commits, setCommits] = useState([]);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState(null);
-
- useEffect(() => {
- loadGitData();
- }, [siteId]);
-
- async function loadGitData() {
- setLoading(true);
- setError(null);
- try {
- const statusData = await wordpressApi.getGitStatus(siteId);
- setGitStatus(statusData);
-
- if (statusData.connected) {
- const commitsData = await wordpressApi.getCommits(siteId);
- setCommits(commitsData.commits || []);
- }
- } catch (err) {
- console.error('Failed to load git data:', err);
- setError(err);
- } finally {
- setLoading(false);
- }
- }
-
- async function handleConnect(data) {
- await wordpressApi.connectRepo(siteId, data);
- toast.success('Repository connected');
- loadGitData();
- onUpdate?.();
- }
-
- async function handleDisconnect() {
- await wordpressApi.disconnectRepo(siteId);
- toast.success('Repository disconnected');
- loadGitData();
- onUpdate?.();
- }
-
- async function handleDeploy(data) {
- try {
- await wordpressApi.deployCommit(siteId, data);
- toast.success('Deployment completed');
- loadGitData();
- onUpdate?.();
- } catch (err) {
- toast.error(err.message || 'Deployment failed');
- }
- }
-
- async function handleCreateDev(data) {
- try {
- await wordpressApi.createDevFromCommit(siteId, data);
- toast.success('Development environment created');
- } catch (err) {
- toast.error(err.message || 'Failed to create environment');
- }
- }
-
- if (loading) {
- return (
- <SkeletonBoundary loading skeleton={(
- <div className="git-tab">
- <div className="git-connect git-connect--card">
- <div className="skeleton" style={{ width: 200, height: 24, marginBottom: 16 }} />
- <div className="skeleton" style={{ height: 44, borderRadius: 6, marginBottom: 12 }} />
- <div className="skeleton" style={{ height: 44, borderRadius: 6, marginBottom: 12 }} />
- <div className="skeleton" style={{ width: 140, height: 36, borderRadius: 6 }} />
- </div>
- </div>
- )} />
- );
- }
-
- if (error) {
- return (
- <ErrorState
- title="Failed to load Git information"
- error={error}
- onRetry={loadGitData}
- />
- );
- }
-
- return (
- <div className="git-tab">
- <GitConnectForm
- gitStatus={gitStatus}
- onConnect={handleConnect}
- onDisconnect={handleDisconnect}
- />
-
- {gitStatus?.connected && (
- <div className="git-commits-section">
- <div className="section-header">
- <h3>Recent Commits</h3>
- <Button variant="outline" size="sm" onClick={loadGitData}>
- <RefreshCw size={14} /> Refresh
- </Button>
- </div>
-
- <CommitList
- commits={commits}
- currentCommit={site.last_deploy_commit}
- onDeploy={handleDeploy}
- onCreateDev={handleCreateDev}
- repoUrl={gitStatus?.repo_url}
- />
- </div>
- )}
- </div>
- );
-};
-
-export default GitTab;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/OverviewTab.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/OverviewTab.jsx
deleted file mode 100644
index 1ad169ab..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/OverviewTab.jsx
+++ /dev/null
@@ -1,400 +0,0 @@
-import { useState, useEffect } from 'react';
-import { ResponsiveContainer, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts';
-import { ExternalLink, Settings, RefreshCw, Plus, Database, Trash2, Replace, ShieldCheck, Zap, Activity, BarChart3, AlertTriangle, HardDrive } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import ActivityFeed from '../ActivityFeed';
-import { MetricCard } from 'serverkit-sdk';
-import { CreateEnvironmentModal } from './EnvironmentsTab';
-import { SearchReplaceModal } from './SettingsTab';
-
-// Overview Tab
-const OverviewTab = ({ site, onUpdate }) => {
- const toast = useToast();
- const [creatingSnapshot, setCreatingSnapshot] = useState(false);
- const [showEnvModal, setShowEnvModal] = useState(false);
- const [syncingAll, setSyncingAll] = useState(false);
- const [flushingCache, setFlushingCache] = useState(false);
- const [hardening, setHardening] = useState(false);
- const [pageCacheActive, setPageCacheActive] = useState(false);
- const [togglingPageCache, setTogglingPageCache] = useState(false);
- const [objectCache, setObjectCache] = useState(null);
- const [togglingCache, setTogglingCache] = useState(false);
- const [showSearchReplace, setShowSearchReplace] = useState(false);
- const [analytics, setAnalytics] = useState(null);
- const [uptime, setUptime] = useState(null);
-
- // Overview KPI + traffic data: uptime (status page) + analytics (access log).
- // Both can be slow or unconfigured, so treat as best-effort (null → "—").
- useEffect(() => {
- let cancelled = false;
- (async () => {
- const [analyticsRes, statusRes] = await Promise.all([
- wordpressApi.getSiteAnalytics(site.id, 168).catch(() => null),
- wordpressApi.getSiteStatusPage(site.id).catch(() => null),
- ]);
- if (cancelled) return;
- setAnalytics(analyticsRes);
- setUptime(statusRes?.component || null);
- })();
- return () => { cancelled = true; };
- }, [site.id]);
-
- async function handleQuickSnapshot() {
- setCreatingSnapshot(true);
- toast.info('Creating snapshot...', { duration: 2000 });
- try {
- await wordpressApi.createSnapshot(site.id, {
- name: `Quick Snapshot ${new Date().toLocaleDateString()}`,
- tag: 'quick',
- description: 'Created from Overview quick action'
- });
- toast.success('Snapshot created successfully');
- } catch (err) {
- toast.error(err.message || 'Failed to create snapshot');
- } finally {
- setCreatingSnapshot(false);
- }
- }
-
- async function handleSyncAll() {
- if (!site.environments?.length) return;
- setSyncingAll(true);
- toast.info(`Syncing ${site.environments.length} environment(s)...`, { duration: 3000 });
- try {
- // Sync each environment sequentially
- for (let i = 0; i < site.environments.length; i++) {
- const env = site.environments[i];
- await wordpressApi.syncEnvironment(site.id, { environment_id: env.id });
- }
- toast.success(`Synced ${site.environments.length} environment(s) from production`);
- onUpdate?.();
- } catch (err) {
- toast.error(err.message || 'Failed to sync environments');
- } finally {
- setSyncingAll(false);
- }
- }
-
- async function handleCreateEnvironment(data) {
- toast.info('Creating environment... This may take a moment.', { duration: 5000 });
- try {
- await wordpressApi.createEnvironment(site.id, data);
- toast.success('Environment created successfully');
- setShowEnvModal(false);
- onUpdate?.();
- } catch (err) {
- toast.error(err.message || 'Failed to create environment');
- }
- }
-
- useEffect(() => {
- let active = true;
- wordpressApi.getPageCache(site.id)
- .then(r => { if (active) setPageCacheActive(Boolean(r?.active)); })
- .catch(() => { /* best-effort; control just shows Enable */ });
- wordpressApi.getObjectCacheStatus(site.id)
- .then(s => { if (active) setObjectCache(s); })
- .catch(() => {});
- return () => { active = false; };
- }, [site.id]);
-
- async function handleTogglePageCache() {
- setTogglingPageCache(true);
- const enabling = !pageCacheActive;
- toast.info(enabling ? 'Enabling page cache...' : 'Disabling page cache...', { duration: 4000 });
- try {
- const res = enabling
- ? await wordpressApi.enablePageCache(site.id)
- : await wordpressApi.disablePageCache(site.id);
- if (res.success === false) {
- toast.error(res.error || 'Page cache change failed');
- } else {
- toast.success(res.message || (enabling ? 'Page cache enabled' : 'Page cache disabled'));
- setPageCacheActive(enabling);
- }
- } catch (err) {
- toast.error(err.message || 'Page cache change failed');
- } finally {
- setTogglingPageCache(false);
- }
- }
-
- async function handleToggleObjectCache() {
- setTogglingCache(true);
- const enabling = !objectCache?.enabled;
- toast.info(enabling ? 'Enabling Redis object cache...' : 'Disabling object cache...', { duration: 4000 });
- try {
- const res = enabling
- ? await wordpressApi.enableObjectCache(site.id)
- : await wordpressApi.disableObjectCache(site.id);
- if (res.success === false) {
- toast.error(res.error || 'Object cache change failed');
- } else {
- toast.success(res.message || (enabling ? 'Object cache enabled' : 'Object cache disabled'));
- const fresh = await wordpressApi.getObjectCacheStatus(site.id).catch(() => null);
- if (fresh) setObjectCache(fresh);
- }
- } catch (err) {
- toast.error(err.message || 'Object cache change failed');
- } finally {
- setTogglingCache(false);
- }
- }
-
- async function handleFlushCache() {
- setFlushingCache(true);
- toast.info('Flushing cache...', { duration: 2000 });
- try {
- const res = await wordpressApi.flushCache(site.id);
- toast.success(res.message || 'Cache flushed');
- } catch (err) {
- toast.error(err.message || 'Failed to flush cache');
- } finally {
- setFlushingCache(false);
- }
- }
-
- async function handleHarden() {
- if (!window.confirm('Apply security hardening? This disables file editing, the XML-RPC endpoint, forces SSL on wp-admin, tightens file permissions, and regenerates security keys (logs users out).')) {
- return;
- }
- setHardening(true);
- toast.info('Applying security hardening...', { duration: 4000 });
- try {
- const res = await wordpressApi.harden(site.id);
- toast.success(res.message || 'Security hardening applied');
- } catch (err) {
- toast.error(err.message || 'Failed to harden site');
- } finally {
- setHardening(false);
- }
- }
-
- async function handleSearchReplace(data) {
- // data = { search, replace, dry_run }
- toast.info(data.dry_run ? 'Running search-replace preview...' : 'Running search-replace...', { duration: 3000 });
- try {
- const res = await wordpressApi.searchReplace(site.id, data);
- if (res.success === false) {
- toast.error(res.error || res.message || 'Search-replace failed');
- return;
- }
- toast.success(data.dry_run ? 'Dry run complete - no changes written' : 'Search-replace complete');
- if (!data.dry_run) setShowSearchReplace(false);
- } catch (err) {
- toast.error(err.message || 'Search-replace failed');
- }
- }
-
- // ---- Overview KPI + Site-info derivations (real data, honest fallbacks) ----
- const compactNum = (n) => {
- if (n == null) return '—';
- if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`;
- if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`;
- return `${n}`;
- };
- const [diskVal, diskUnit] = (site.disk_usage_human || '').split(' ');
- const trafficSeries = analytics?.series || [];
- const fmtTrafficTick = (iso) => new Date(iso).toLocaleDateString([], { month: 'short', day: 'numeric' });
-
- return (
- <div className="wp-overview">
- {/* KPI row — deliberately NON-redundant: status + version already live
- in the page header, so the tiles surface uptime, traffic, error
- rate, and storage instead. */}
- <div className="wp-kpis">
- <MetricCard
- tone="green"
- icon={<Activity size={16} />}
- value={uptime?.uptime_30d != null ? uptime.uptime_30d.toFixed(2) : '—'}
- unit={uptime?.uptime_30d != null ? '%' : undefined}
- label="Uptime (30d)"
- />
- <MetricCard
- tone="accent"
- icon={<BarChart3 size={16} />}
- value={analytics ? compactNum(analytics.unique_visitors ?? 0) : '—'}
- label="Visitors (7d)"
- />
- <MetricCard
- tone={(analytics?.error_rate ?? 0) > 5 ? 'red' : 'amber'}
- icon={<AlertTriangle size={16} />}
- value={analytics ? `${analytics.error_rate ?? 0}` : '—'}
- unit={analytics ? '%' : undefined}
- label="Error rate (7d)"
- />
- <MetricCard
- tone="cyan"
- icon={<HardDrive size={16} />}
- value={diskVal || '—'}
- unit={diskUnit || undefined}
- label="Disk used"
- />
- </div>
-
- <div className="wp-overview-main">
- <div className="app-panel">
- <div className="app-panel-header">Quick Actions</div>
- <div className="app-panel-body">
- <div className="quick-actions-grid">
- {site.url && (
- <>
- <a
- href={site.url}
- target="_blank"
- rel="noopener noreferrer"
- className="quick-action-btn"
- >
- <ExternalLink size={16} />
- Visit Site
- </a>
- <a
- href={`${site.url}/wp-admin`}
- target="_blank"
- rel="noopener noreferrer"
- className="quick-action-btn"
- >
- <Settings size={16} />
- WP Admin
- </a>
- </>
- )}
- {site.is_production && (site.environments || []).length < 2 && (
- <button type="button"
- className="quick-action-btn"
- onClick={() => setShowEnvModal(true)}
- >
- <Plus size={16} />
- Create Environment
- </button>
- )}
- <button type="button"
- className="quick-action-btn"
- onClick={handleQuickSnapshot}
- disabled={creatingSnapshot}
- >
- <Database size={16} />
- {creatingSnapshot ? 'Creating...' : 'Create Snapshot'}
- </button>
- {site.environments?.length > 0 && (
- <button type="button"
- className="quick-action-btn"
- onClick={handleSyncAll}
- disabled={syncingAll}
- >
- <RefreshCw size={16} className={syncingAll ? 'spinning' : ''} />
- {syncingAll ? 'Syncing...' : 'Sync All Envs'}
- </button>
- )}
- <button type="button"
- className="quick-action-btn"
- onClick={handleFlushCache}
- disabled={flushingCache}
- >
- <Trash2 size={16} />
- {flushingCache ? 'Flushing...' : 'Purge Cache'}
- </button>
- <button type="button"
- className="quick-action-btn"
- onClick={handleTogglePageCache}
- disabled={togglingPageCache}
- title={pageCacheActive ? 'Full-page cache is active' : 'Enable a full-page cache for this site'}
- >
- <Zap size={16} />
- {togglingPageCache
- ? 'Working...'
- : (pageCacheActive ? 'Page Cache: On' : 'Enable Page Cache')}
- </button>
- <button type="button"
- className="quick-action-btn"
- onClick={() => setShowSearchReplace(true)}
- >
- <Replace size={16} />
- Search &amp; Replace
- </button>
- <button type="button"
- className="quick-action-btn"
- onClick={handleHarden}
- disabled={hardening}
- >
- <ShieldCheck size={16} />
- {hardening ? 'Hardening...' : 'Harden'}
- </button>
- <button type="button"
- className="quick-action-btn"
- onClick={handleToggleObjectCache}
- disabled={togglingCache}
- title={objectCache?.enabled ? 'Redis object cache is active' : 'Enable a Redis object cache for this site'}
- >
- <Database size={16} />
- {togglingCache
- ? (objectCache?.enabled ? 'Disabling...' : 'Enabling...')
- : (objectCache?.enabled ? 'Object Cache: On' : 'Enable Object Cache')}
- </button>
- </div>
- </div>
- </div>
-
- <div className="app-panel wp-traffic-panel">
- <div className="app-panel-header">
- Traffic
- <span className="wp-panel-sub">Last 7 days · unique visits</span>
- </div>
- <div className="app-panel-body">
- {trafficSeries.length > 0 ? (
- <ResponsiveContainer width="100%" height={250}>
- <AreaChart data={trafficSeries} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}>
- <defs>
- <linearGradient id="wpOvVisits" x1="0" y1="0" x2="0" y2="1">
- <stop offset="5%" stopColor="#6d7cff" stopOpacity={0.35} />
- <stop offset="95%" stopColor="#6d7cff" stopOpacity={0} />
- </linearGradient>
- </defs>
- <CartesianGrid strokeDasharray="3 3" stroke="#888" strokeOpacity={0.15} />
- <XAxis dataKey="hour" tickFormatter={fmtTrafficTick} tick={{ fontSize: 11, fill: '#888' }} minTickGap={28} axisLine={false} tickLine={false} />
- <YAxis allowDecimals={false} tickFormatter={(v) => (v >= 1000 ? `${(v / 1000).toFixed(0)}k` : `${v}`)} tick={{ fontSize: 11, fill: '#888' }} width={34} axisLine={false} tickLine={false} />
- <Tooltip labelFormatter={fmtTrafficTick} />
- <Area type="monotone" dataKey="requests" name="Visits" stroke="#8b93ff" fill="url(#wpOvVisits)" strokeWidth={2} />
- </AreaChart>
- </ResponsiveContainer>
- ) : (
- <p className="hint">No traffic recorded for this period yet — it&apos;s parsed from the site&apos;s access log.</p>
- )}
- </div>
- </div>
- </div>
-
- <div className="app-panel wp-activity-panel">
- <div className="app-panel-header">Recent activity</div>
- <div className="app-panel-body">
- <ActivityFeed projectId={site.id} limit={6} />
- </div>
- </div>
-
- {showEnvModal && (() => {
- const envs = site.environments || [];
- const modalHasStaging = envs.some(e => e.environment_type === 'staging');
- const modalHasDev = envs.some(e => e.environment_type === 'development');
- return (
- <CreateEnvironmentModal
- onClose={() => setShowEnvModal(false)}
- onCreate={handleCreateEnvironment}
- productionDomain={site.url}
- hasStaging={modalHasStaging}
- hasDev={modalHasDev}
- />
- );
- })()}
-
- {showSearchReplace && (
- <SearchReplaceModal
- onClose={() => setShowSearchReplace(false)}
- onSubmit={handleSearchReplace}
- />
- )}
- </div>
- );
-};
-
-export default OverviewTab;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/PhpTab.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/PhpTab.jsx
deleted file mode 100644
index 10fb0785..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/PhpTab.jsx
+++ /dev/null
@@ -1,161 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { OverviewGridSkeleton, PHP_LIMIT_LABELS } from './wpDetailShared';
-
-// PHP Tab — live PHP version + ini limits for the Docker (apache/mod_php) site.
-// Version is the image tag; switching recreates the container (volumes persist).
-// Limits are written as a durable conf.d drop-in (bind-mounted), editable below.
-const PhpTab = ({ siteId }) => {
- const toast = useToast();
- const [php, setPhp] = useState(null);
- const [loading, setLoading] = useState(true);
- const [switching, setSwitching] = useState(false);
- const [form, setForm] = useState({});
- const [saving, setSaving] = useState(false);
-
- const load = React.useCallback(async () => {
- setLoading(true);
- try {
- const data = await wordpressApi.getPhpInfo(siteId);
- const info = data.php || data;
- setPhp(info);
- // Seed the edit form from live values for the editable directives.
- const lim = info?.limits || {};
- const seed = {};
- (info?.editable_limits || []).forEach(k => { seed[k] = lim[k] || ''; });
- setForm(seed);
- } catch (err) {
- toast.error(err.message || 'Failed to load PHP info');
- } finally {
- setLoading(false);
- }
- }, [siteId, toast]);
-
- useEffect(() => { load(); }, [load]);
-
- async function handleSwitch(version) {
- if (!window.confirm(`Switch this site to PHP ${version}? This pulls the wordpress:php${version}-apache image and recreates the container (brief downtime; database and files are preserved).`)) return;
- setSwitching(true);
- toast.info(`Switching to PHP ${version}...`, { duration: 4000 });
- try {
- const res = await wordpressApi.setPhpVersion(siteId, version);
- if (res.success === false) { toast.error(res.error || 'Failed to switch PHP version'); return; }
- toast.success(res.message || `Switched to PHP ${version}`);
- await load();
- } catch (err) {
- toast.error(err.message || 'Failed to switch PHP version');
- } finally {
- setSwitching(false);
- }
- }
-
- async function handleSaveLimits() {
- // Send only the directives that changed from the live value (partial update).
- const live = php?.limits || {};
- const changed = {};
- Object.entries(form).forEach(([k, v]) => {
- const val = (v ?? '').toString().trim();
- if (val && val !== (live[k] || '')) changed[k] = val;
- });
- if (Object.keys(changed).length === 0) { toast.info('No changes to save'); return; }
- if (!window.confirm('Apply these PHP limits? The container reloads (brief downtime; database and files are preserved).')) return;
- setSaving(true);
- try {
- const res = await wordpressApi.setPhpLimits(siteId, changed);
- if (res.success === false) { toast.error(res.error || 'Failed to update PHP limits'); return; }
- toast.success(res.message || 'PHP limits updated');
- await load();
- } catch (err) {
- toast.error(err.message || 'Failed to update PHP limits');
- } finally {
- setSaving(false);
- }
- }
-
- if (loading) return <SkeletonBoundary loading skeleton={<OverviewGridSkeleton panels={2} />} />;
-
- const limits = php?.limits || {};
- const current = php?.php_version || 'Unknown';
- const versions = php?.available_versions || [];
- const editableKeys = php?.editable_limits || [];
-
- return (
- <div className="app-overview-grid">
- <div className="app-overview-left">
- <div className="app-panel">
- <div className="app-panel-header">PHP</div>
- <div className="app-panel-body">
- <div className="app-info-grid">
- <div className="app-info-item">
- <span className="app-info-label">PHP Version</span>
- <span className="app-info-value">{current}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Memory Limit</span>
- <span className="app-info-value">{limits.memory_limit || '-'}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Upload Max Filesize</span>
- <span className="app-info-value">{limits.upload_max_filesize || '-'}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Post Max Size</span>
- <span className="app-info-value">{limits.post_max_size || '-'}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Max Execution Time</span>
- <span className="app-info-value">{limits.max_execution_time || '-'}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Max Input Time</span>
- <span className="app-info-value">{limits.max_input_time || '-'}</span>
- </div>
- </div>
- </div>
- </div>
-
- {versions.length > 0 && (
- <div className="app-panel">
- <div className="app-panel-header">Change PHP Version</div>
- <div className="app-panel-body">
- <p className="hint">Switching rebuilds the container from the official wordpress php-apache image. The database and uploaded files are preserved.</p>
- <div className="app-detail-actions">
- {versions.map(v => (
- <Button key={v} variant="outline" size="sm" disabled={switching || current.startsWith(v)} onClick={() => handleSwitch(v)}>
- {current.startsWith(v) ? `PHP ${v} (current)` : `PHP ${v}`}
- </Button>
- ))}
- </div>
- </div>
- </div>
- )}
-
- {editableKeys.length > 0 && (
- <div className="app-panel">
- <div className="app-panel-header">Edit PHP Limits</div>
- <div className="app-panel-body">
- <p className="hint">Saved as a durable conf.d drop-in bind-mounted into the container, so limits survive a container recreate. Saving reloads the container (brief downtime).</p>
- {editableKeys.map(k => (
- <div className="form-group" key={k}>
- <Label>{PHP_LIMIT_LABELS[k] || k}</Label>
- <Input value={form[k] ?? ''} placeholder={limits[k] || ''} disabled={saving}
- onChange={e => setForm(f => ({ ...f, [k]: e.target.value }))} />
- </div>
- ))}
- <div className="app-detail-actions">
- <Button size="sm" onClick={handleSaveLimits} disabled={saving}>{saving ? 'Saving…' : 'Save limits'}</Button>
- </div>
- </div>
- </div>
- )}
- </div>
- </div>
- );
-};
-
-export default PhpTab;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/PluginsTab.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/PluginsTab.jsx
deleted file mode 100644
index aec9ba50..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/PluginsTab.jsx
+++ /dev/null
@@ -1,255 +0,0 @@
-import { useState, useEffect } from 'react';
-import { Package, Download } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { ErrorState } from '@/components/ErrorBoundary';
-import { EmptyState } from 'serverkit-sdk';
-import { ServiceTile } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Switch } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { ListItemSkeleton } from './wpDetailShared';
-
-// Plugins Tab
-const PluginsTab = ({ siteId }) => {
- const toast = useToast();
- const [plugins, setPlugins] = useState([]);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState(null);
- const [installing, setInstalling] = useState(false);
- 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();
- }, [siteId]);
-
- async function loadPlugins() {
- setLoading(true);
- setError(null);
- try {
- const data = await wordpressApi.getPlugins(siteId);
- setPlugins(data.plugins || []);
- loadManaged();
- } catch (err) {
- console.error('Failed to load plugins:', err);
- setError(err);
- } finally {
- setLoading(false);
- }
- }
-
- // 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;
-
- setInstalling(true);
- try {
- await wordpressApi.installPlugin(siteId, { slug: newPlugin.trim() });
- toast.success('Plugin installed successfully');
- setNewPlugin('');
- loadPlugins();
- } catch (err) {
- toast.error(err.message || 'Failed to install plugin');
- } finally {
- setInstalling(false);
- }
- }
-
- async function handleUpdate(pluginName) {
- setUpdating(pluginName || 'all');
- toast.info(pluginName ? `Updating ${pluginName}...` : 'Updating all plugins...', { duration: 4000 });
- try {
- const res = await wordpressApi.updatePlugins(siteId, pluginName ? [pluginName] : undefined);
- if (res.success === false) {
- toast.error(res.error || 'Plugin update failed');
- return;
- }
- toast.success(res.message || 'Plugins updated');
- loadPlugins();
- } catch (err) {
- toast.error(err.message || 'Plugin update failed');
- } finally {
- setUpdating(null);
- }
- }
-
- async function handleToggle(plugin) {
- const activating = plugin.status !== 'active';
- setToggling(plugin.name);
- try {
- const res = activating
- ? await wordpressApi.activatePlugin(siteId, plugin.name)
- : await wordpressApi.deactivatePlugin(siteId, plugin.name);
- if (res && res.success === false) {
- toast.error(res.error || `Failed to ${activating ? 'activate' : 'deactivate'} ${plugin.name}`);
- return;
- }
- toast.success(`${plugin.title || plugin.name} ${activating ? 'activated' : 'deactivated'}`);
- loadPlugins();
- } catch (err) {
- toast.error(err.message || `Failed to ${activating ? 'activate' : 'deactivate'} plugin`);
- } finally {
- setToggling(null);
- }
- }
-
- if (loading) {
- return (
- <SkeletonBoundary loading skeleton={(
- <div className="plugins-tab">
- <div className="section-header">
- <div className="skeleton" style={{ width: 80, height: 24 }} />
- </div>
- <div className="skeleton" style={{ height: 44, borderRadius: 6, marginBottom: 16 }} />
- <div className="plugins-list">
- <ListItemSkeleton />
- <ListItemSkeleton />
- <ListItemSkeleton />
- </div>
- </div>
- )} />
- );
- }
-
- if (error) {
- return (
- <ErrorState
- title="Failed to load plugins"
- error={error}
- onRetry={loadPlugins}
- />
- );
- }
-
- return (
- <div className="plugins-tab">
- <div className="section-header">
- <h3>Plugins</h3>
- </div>
-
- <form className="install-form" onSubmit={handleInstall}>
- <Input
- type="text"
- value={newPlugin}
- onChange={(e) => setNewPlugin(e.target.value)}
- placeholder="Plugin slug (e.g., akismet, woocommerce)"
- />
- <Button type="submit" disabled={installing}>
- {installing ? 'Installing...' : 'Install Plugin'}
- </Button>
- </form>
-
- {plugins.some(p => p.update === 'available') && (
- <div className="bulk-update-bar">
- <span>{plugins.filter(p => p.update === 'available').length} plugin update(s) available</span>
- <Button
- variant="outline"
- size="sm"
- onClick={() => handleUpdate(null)}
- disabled={updating !== null}
- >
- {updating === 'all' ? 'Updating...' : 'Update all'}
- </Button>
- </div>
- )}
-
- {plugins.length === 0 ? (
- <EmptyState icon={Package} title="No plugins installed" description="Install a plugin by entering its slug above." />
- ) : (
- <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}
- {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>
- {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' && (
- <button
- type="button"
- className="wp-update-flag"
- onClick={() => handleUpdate(plugin.name)}
- disabled={updating !== null}
- >
- <Download size={11} />
- {updating === plugin.name ? 'Updating…' : `Update${plugin.update_version ? ` ${plugin.update_version}` : ''}`}
- </button>
- )}
- </div>
- </div>
- <div className="wp-asset-card__toggle">
- <Switch
- checked={isActive}
- disabled={toggling === plugin.name}
- onCheckedChange={() => handleToggle(plugin)}
- aria-label={isActive ? `Deactivate ${plugin.name}` : `Activate ${plugin.name}`}
- />
- <span className={`wp-asset-card__state ${isActive ? 'is-on' : ''}`}>
- {isActive ? 'Active' : 'Inactive'}
- </span>
- </div>
- </div>
- );
- })}
- </div>
- )}
- </div>
- );
-};
-
-export default PluginsTab;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/ReportsTab.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/ReportsTab.jsx
deleted file mode 100644
index 4e2b329f..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/ReportsTab.jsx
+++ /dev/null
@@ -1,361 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import { ResponsiveContainer, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts';
-import { Printer, Download, Trash2 } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { useConfirm } from 'serverkit-sdk';
-import { Pill } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { OverviewGridSkeleton } from './wpDetailShared';
-
-// Reports Tab — monthly client reports (#33 agency slice). Aggregates the
-// per-site signals that already accrue (uptime/incidents #26, update runs #29,
-// backups, vulnerability posture #28) into a persisted, printable monthly report.
-const ReportsTab = ({ siteId }) => {
- const toast = useToast();
- const { confirm } = useConfirm();
- const [reports, setReports] = useState([]);
- const [selectedId, setSelectedId] = useState(null);
- const [loading, setLoading] = useState(true);
- const [busy, setBusy] = useState(false);
-
- // Last 12 months (current first) as {value:'YYYY-MM', label, year, month}.
- const monthOptions = React.useMemo(() => {
- const opts = [];
- const d = new Date();
- d.setDate(1);
- for (let i = 0; i < 12; i++) {
- const year = d.getFullYear();
- const month = d.getMonth() + 1;
- opts.push({
- value: `${year}-${String(month).padStart(2, '0')}`,
- label: d.toLocaleString([], { month: 'long', year: 'numeric' }),
- year, month,
- });
- d.setMonth(d.getMonth() - 1);
- }
- return opts;
- }, []);
- const [genMonth, setGenMonth] = useState(monthOptions[0].value);
-
- const load = React.useCallback(async (preferLabel) => {
- try {
- const res = await wordpressApi.getReports(siteId);
- const list = res.reports || [];
- setReports(list);
- setSelectedId(prev => {
- if (preferLabel) {
- const match = list.find(r => r.period_label === preferLabel);
- if (match) return match.id;
- }
- if (prev && list.some(r => r.id === prev)) return prev;
- return list.length ? list[0].id : null;
- });
- } catch (err) {
- toast.error(err.message || 'Failed to load reports');
- } finally {
- setLoading(false);
- }
- }, [siteId, toast]);
-
- useEffect(() => { load(); }, [load]);
-
- async function handleGenerate() {
- const opt = monthOptions.find(o => o.value === genMonth) || monthOptions[0];
- setBusy(true);
- try {
- // The API client throws on a non-2xx (e.g. the future-month guard's 400),
- // so a resolved call means success; failures surface via catch.
- await wordpressApi.generateReport(siteId, { year: opt.year, month: opt.month });
- toast.success(`Report generated for ${opt.label}`);
- await load(opt.value);
- } catch (err) {
- toast.error(err.message || 'Failed to generate report');
- } finally {
- setBusy(false);
- }
- }
-
- async function handleDelete(report) {
- const ok = await confirm({
- title: 'Delete report',
- message: `Delete the report for ${report.data?.period?.month_name || report.period_label}? This cannot be undone.`,
- confirmText: 'Delete',
- variant: 'danger',
- });
- if (!ok) return;
- try {
- await wordpressApi.deleteReport(siteId, report.id);
- toast.success('Report deleted');
- await load();
- } catch (err) {
- toast.error(err.message || 'Failed to delete report');
- }
- }
-
- function handleDownload(report) {
- const blob = new Blob([JSON.stringify(report.data, null, 2)], { type: 'application/json' });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = `wp-report-${siteId}-${report.period_label}.json`;
- a.click();
- URL.revokeObjectURL(url);
- }
-
- function handlePrint() {
- document.body.classList.add('wp-report-printing');
- // Clean up on whichever signal fires first: `afterprint` (most engines) or
- // the window regaining focus when the dialog closes (fallback for webviews
- // that don't dispatch afterprint). cleanup is idempotent.
- const cleanup = () => {
- document.body.classList.remove('wp-report-printing');
- window.removeEventListener('afterprint', cleanup);
- window.removeEventListener('focus', cleanup);
- };
- window.addEventListener('afterprint', cleanup);
- window.addEventListener('focus', cleanup, { once: true });
- window.print();
- }
-
- if (loading) return <SkeletonBoundary loading skeleton={<OverviewGridSkeleton panels={2} />} />;
-
- const selected = reports.find(r => r.id === selectedId) || null;
-
- return (
- <div className="app-overview-grid">
- <div className="app-overview-left">
- <div className="app-panel wp-report-no-print">
- <div className="app-panel-header">Generate monthly report</div>
- <div className="app-panel-body">
- <p className="hint">Snapshots this site&apos;s uptime, incidents, update runs, backups, and current security posture for a calendar month into a printable client report.</p>
- <div className="app-detail-actions">
- <select value={genMonth} onChange={e => setGenMonth(e.target.value)} disabled={busy}>
- {monthOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
- </select>
- <Button size="sm" onClick={handleGenerate} disabled={busy}>
- {busy ? 'Generating…' : 'Generate'}
- </Button>
- </div>
- {reports.length > 0 && (
- <div className="app-detail-actions wp-report-month-list">
- {reports.map(r => (
- <Button
- key={r.id}
- variant={r.id === selectedId ? 'default' : 'outline'}
- size="sm"
- onClick={() => setSelectedId(r.id)}
- >
- {r.data?.period?.month_name || r.period_label}
- </Button>
- ))}
- </div>
- )}
- </div>
- </div>
-
- {!selected ? (
- <div className="app-panel wp-report-no-print">
- <div className="app-panel-body">
- <p className="hint">No reports yet — pick a month above and click Generate.</p>
- </div>
- </div>
- ) : (
- <ReportView report={selected} onPrint={handlePrint} onDownload={() => handleDownload(selected)} onDelete={() => handleDelete(selected)} />
- )}
- </div>
- </div>
- );
-};
-
-// The printable rendering of a single monthly report. Wrapped in
-// .wp-report-printable so the print stylesheet can isolate it from the app chrome.
-const ReportView = ({ report, onPrint, onDownload, onDelete }) => {
- const d = report.data || {};
- const period = d.period || {};
- const site = d.site || {};
- const uptime = d.uptime || {};
- const updates = d.updates || {};
- const backups = d.backups || {};
- const vulns = d.vulnerabilities || {};
- const health = d.health || {};
- const sev = vulns.by_severity || {};
- const sevTone = (s) => ({ critical: 'red', high: 'red', medium: 'amber', low: 'cyan' }[s] || 'gray');
- const impactTone = (i) => ({ critical: 'red', major: 'red', minor: 'amber' }[i] || 'gray');
- const fmt = (iso) => (iso ? new Date(iso).toLocaleString() : '—');
- const fmtDay = (key) => {
- if (!key) return '';
- const parts = key.split('-');
- return parts.length === 3 ? Number(parts[2]).toString() : key;
- };
- const dailyHasData = (d.uptime_daily || []).some(x => x.percent !== null);
-
- return (
- <div className="wp-report-printable">
- <div className="app-panel">
- <div className="app-panel-header">
- Report — {period.month_name || report.period_label}
- <span className="wp-report-actions wp-report-no-print">
- <Button variant="outline" size="sm" onClick={onPrint}><Printer size={14} /> Print</Button>
- <Button variant="outline" size="sm" onClick={onDownload}><Download size={14} /> JSON</Button>
- <Button variant="outline" size="sm" onClick={onDelete}><Trash2 size={14} /> Delete</Button>
- </span>
- </div>
- <div className="app-panel-body">
- <div className="app-info-grid">
- <div className="app-info-item"><span className="app-info-label">Site</span><span className="app-info-value">{site.name || '—'}</span></div>
- {site.client && <div className="app-info-item"><span className="app-info-label">Client</span><span className="app-info-value">{site.client}</span></div>}
- <div className="app-info-item"><span className="app-info-label">URL</span><span className="app-info-value">{site.url ? <a href={site.url} target="_blank" rel="noopener noreferrer">{site.url}</a> : '—'}</span></div>
- <div className="app-info-item"><span className="app-info-label">WordPress</span><span className="app-info-value">{site.wp_version || '—'}{site.multisite ? ' · multisite' : ''}</span></div>
- <div className="app-info-item"><span className="app-info-label">Generated</span><span className="app-info-value">{fmt(d.generated_at)}</span></div>
- </div>
- </div>
- </div>
-
- <div className="app-panel">
- <div className="app-panel-header">Summary</div>
- <div className="app-panel-body">
- <div className="app-info-grid">
- <div className="app-info-item"><span className="app-info-label">Uptime</span><span className="app-info-value">{uptime.percent !== null && uptime.percent !== undefined ? `${uptime.percent}%` : 'N/A'}</span></div>
- <div className="app-info-item"><span className="app-info-label">Incidents</span><span className="app-info-value">{d.incident_count ?? 0}</span></div>
- <div className="app-info-item"><span className="app-info-label">Update runs</span><span className="app-info-value">{updates.total_runs ?? 0}</span></div>
- <div className="app-info-item"><span className="app-info-label">Components updated</span><span className="app-info-value">{updates.components_updated ?? 0}</span></div>
- <div className="app-info-item"><span className="app-info-label">Backups</span><span className="app-info-value">{backups.count ?? 0}{backups.count ? ` · ${backups.total_bytes_human}` : ''}</span></div>
- <div className="app-info-item"><span className="app-info-label">Open vulnerabilities</span><span className="app-info-value">{vulns.total ?? 0}</span></div>
- <div className="app-info-item"><span className="app-info-label">Current health</span><span className="app-info-value">{health.status || 'unknown'}</span></div>
- <div className="app-info-item"><span className="app-info-label">Disk usage</span><span className="app-info-value">{health.disk_usage_human || '—'}</span></div>
- </div>
- {(updates.rolled_back > 0 || updates.failed > 0) && (
- <div className="app-detail-actions">
- {updates.completed > 0 && <Pill kind="green">{updates.completed} completed</Pill>}
- {updates.rolled_back > 0 && <Pill kind="amber">{updates.rolled_back} rolled back</Pill>}
- {updates.failed > 0 && <Pill kind="red">{updates.failed} failed</Pill>}
- </div>
- )}
- </div>
- </div>
-
- {uptime.bound && dailyHasData && (
- <div className="app-panel">
- <div className="app-panel-header">Daily uptime</div>
- <div className="app-panel-body">
- <ResponsiveContainer width="100%" height={200}>
- <AreaChart data={d.uptime_daily || []} margin={{ top: 8, right: 8, left: -16, bottom: 0 }}>
- <defs>
- <linearGradient id="wpUptime" x1="0" y1="0" x2="0" y2="1">
- <stop offset="5%" stopColor="#3ddc97" stopOpacity={0.35} />
- <stop offset="95%" stopColor="#3ddc97" stopOpacity={0} />
- </linearGradient>
- </defs>
- <CartesianGrid strokeDasharray="3 3" stroke="#888" strokeOpacity={0.15} />
- <XAxis dataKey="date" tickFormatter={fmtDay} tick={{ fontSize: 11, fill: '#888' }} minTickGap={16} axisLine={false} tickLine={false} />
- <YAxis domain={[0, 100]} tick={{ fontSize: 11, fill: '#888' }} width={36} axisLine={false} tickLine={false} />
- <Tooltip formatter={(v) => (v === null ? 'no data' : `${v}%`)} />
- <Area connectNulls type="monotone" dataKey="percent" name="Uptime %" stroke="#3ddc97" fill="url(#wpUptime)" strokeWidth={2} />
- </AreaChart>
- </ResponsiveContainer>
- <p className="hint">Uptime recomputed from recorded health-check samples ({uptime.samples} this month). Rolling 30-day: {uptime.rolling_30d ?? '—'}%.</p>
- </div>
- </div>
- )}
-
- {(d.incidents || []).length > 0 && (
- <div className="app-panel">
- <div className="app-panel-header">Incidents</div>
- <div className="app-panel-body">
- {d.incidents.map(inc => (
- <div className="wp-run-row" key={inc.id}>
- <div className="wp-run-row-head">
- <Pill kind={impactTone(inc.impact)}>{inc.impact}</Pill>
- <strong>{inc.title}</strong>
- </div>
- <span className="form-hint">
- {fmt(inc.created_at)} → {inc.ongoing ? 'ongoing' : fmt(inc.resolved_at)} · {inc.duration_minutes} min · {inc.status}
- </span>
- </div>
- ))}
- </div>
- </div>
- )}
-
- {(updates.runs || []).length > 0 && (
- <div className="app-panel">
- <div className="app-panel-header">Update runs</div>
- <div className="app-panel-body">
- {updates.runs.map(r => {
- const n = (r.updated || []).length;
- const kind = ({ completed: 'green', rolled_back: 'amber', failed: 'red', running: 'cyan' }[r.status] || 'gray');
- return (
- <div className="wp-run-row" key={r.id}>
- <div className="wp-run-row-head">
- <Pill kind={kind}>{r.status.replace('_', ' ')}</Pill>
- <span className="wp-run-row-meta">{fmt(r.started_at)} · {r.trigger}</span>
- </div>
- <span className="form-hint">
- {n === 0 ? 'No components needed updating' : `${n} component${n === 1 ? '' : 's'} updated`}
- {r.rolled_back ? ' · auto-rolled back' : ''}
- {r.error ? ` · ${r.error}` : ''}
- </span>
- </div>
- );
- })}
- </div>
- </div>
- )}
-
- {(backups.snapshots || []).length > 0 && (
- <div className="app-panel">
- <div className="app-panel-header">Backups</div>
- <div className="app-panel-body">
- {backups.snapshots.map(s => (
- <div className="app-info-item" key={s.id}>
- <span className="app-info-label">{fmt(s.created_at)}{s.tag ? ` · ${s.tag}` : ''}</span>
- <span className="app-info-value">{s.size_human} · {s.status}</span>
- </div>
- ))}
- </div>
- </div>
- )}
-
- <div className="app-panel">
- <div className="app-panel-header">Security posture {vulns.as_of ? `(as of ${fmt(vulns.as_of)})` : ''}</div>
- <div className="app-panel-body">
- {vulns.total > 0 ? (
- <>
- <div className="app-detail-actions">
- {sev.critical > 0 && <Pill kind="red">{sev.critical} critical</Pill>}
- {sev.high > 0 && <Pill kind="red">{sev.high} high</Pill>}
- {sev.medium > 0 && <Pill kind="amber">{sev.medium} medium</Pill>}
- {sev.low > 0 && <Pill kind="cyan">{sev.low} low</Pill>}
- {sev.unknown > 0 && <Pill kind="gray">{sev.unknown} unrated</Pill>}
- </div>
- {(vulns.items || []).map((v, i) => (
- <div className="wp-run-row" key={i}>
- <div className="wp-run-row-head"><Pill kind={sevTone(v.severity)}>{v.severity}</Pill><strong>{v.name}</strong></div>
- <span className="form-hint">
- {v.source}{v.slug ? ` · ${v.slug}` : ''} · installed {v.installed_version}
- {v.fixed_in ? ` · fixed in ${v.fixed_in}` : ' · no fix yet'}
- {v.advisory_id ? ` · ${v.advisory_id}` : ''}
- </span>
- </div>
- ))}
- </>
- ) : (
- <p className="hint">{vulns.as_of ? 'No known vulnerabilities at last scan.' : 'No vulnerability scan has run for this site yet.'}</p>
- )}
- </div>
- </div>
-
- {(d.notes || []).length > 0 && (
- <div className="app-panel">
- <div className="app-panel-body">
- {d.notes.map((n, i) => <p className="hint" key={i}>{n}</p>)}
- </div>
- </div>
- )}
- </div>
- );
-};
-
-export default ReportsTab;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/SecurityTab.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/SecurityTab.jsx
deleted file mode 100644
index dea63841..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/SecurityTab.jsx
+++ /dev/null
@@ -1,249 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { Pill, ScoreGauge } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { OverviewGridSkeleton } from './wpDetailShared';
-
-// Security Tab — per-site security depth (#30): file-integrity verification,
-// WP_DEBUG toggle, and WP-Cron management, all via the Docker-aware WP-CLI bridge.
-const SecurityTab = ({ siteId }) => {
- const toast = useToast();
- const [integrity, setIntegrity] = useState(null);
- const [debug, setDebug] = useState(null);
- const [cron, setCron] = useState(null);
- const [vulns, setVulns] = useState(null);
- const [brute, setBrute] = useState(null);
- const [loading, setLoading] = useState(true);
- const [busy, setBusy] = useState(false);
-
- const loadAll = React.useCallback(async () => {
- try {
- const [i, d, c, v, b] = await Promise.all([
- wordpressApi.getIntegrity(siteId).catch(() => null),
- wordpressApi.getDebug(siteId).catch(() => null),
- wordpressApi.getCron(siteId).catch(() => null),
- wordpressApi.getVulnerabilities(siteId).catch(() => null),
- wordpressApi.getBruteForce(siteId).catch(() => null),
- ]);
- setIntegrity(i); setDebug(d); setCron(c); setVulns(v); setBrute(b);
- } finally {
- setLoading(false);
- }
- }, [siteId]);
-
- useEffect(() => { loadAll(); }, [loadAll]);
- useEffect(() => {
- if (integrity?.status !== 'running') return undefined;
- const t = setTimeout(() => {
- wordpressApi.getIntegrity(siteId).then(setIntegrity).catch(() => {});
- }, 2500);
- return () => clearTimeout(t);
- }, [integrity, siteId]);
-
- async function runIntegrity() {
- try {
- await wordpressApi.scanIntegrity(siteId);
- setIntegrity(await wordpressApi.getIntegrity(siteId));
- } catch (err) { toast.error(err.message || 'Failed to start check'); }
- }
- async function toggleDebug() {
- setBusy(true);
- try {
- const res = await wordpressApi.setDebug(siteId, !debug?.enabled);
- if (res.success === false) { toast.error(res.error || 'Failed to update debug setting'); return; }
- setDebug(res);
- toast.success('Debug setting updated');
- } catch (err) { toast.error(err.message || 'Failed to update debug setting'); }
- finally { setBusy(false); }
- }
- async function runCron() {
- setBusy(true);
- try {
- const r = await wordpressApi.runCron(siteId);
- toast[r.success ? 'success' : 'error'](r.success ? 'Ran due events' : (r.error || 'Failed to run cron'));
- setCron(await wordpressApi.getCron(siteId));
- } catch (err) { toast.error(err.message || 'Failed to run cron'); }
- finally { setBusy(false); }
- }
- async function toggleCron() {
- setBusy(true);
- try { setCron(await wordpressApi.setCronDisabled(siteId, !cron?.disabled)); }
- catch (err) { toast.error(err.message || 'Failed to update WP-Cron'); }
- finally { setBusy(false); }
- }
- async function toggleBrute() {
- const wasEnabled = brute?.enabled;
- setBusy(true);
- try {
- const res = await wordpressApi.setBruteForce(siteId, !wasEnabled);
- if (res.success === false) { toast.error(res.error || 'Failed to update protection'); return; }
- setBrute(await wordpressApi.getBruteForce(siteId));
- toast.success(wasEnabled ? 'Brute-force protection disabled' : 'Brute-force protection enabled');
- } catch (err) { toast.error(err.message || 'Failed to update protection'); }
- finally { setBusy(false); }
- }
- async function unbanIp(ip) {
- setBusy(true);
- try {
- const res = await wordpressApi.unbanBruteForceIp(siteId, ip);
- toast[res.success ? 'success' : 'error'](res.success ? `Unbanned ${ip}` : (res.error || 'Failed to unban'));
- setBrute(await wordpressApi.getBruteForce(siteId));
- } catch (err) { toast.error(err.message || 'Failed to unban'); }
- finally { setBusy(false); }
- }
-
- if (loading) return <SkeletonBoundary loading skeleton={<OverviewGridSkeleton panels={2} />} />;
-
- const intRunning = integrity?.status === 'running';
- const issues = integrity?.issues || [];
-
- // Posture checks — real signals only; checks that haven't run yet stay out
- // of the score (demo's posture ring, computed client-side).
- const vsum = vulns?.summary || {};
- const checks = [
- {
- label: 'Core & plugin files verified',
- state: integrity?.status === 'completed' ? (issues.length === 0 ? 'pass' : 'fail') : 'unknown',
- detail: integrity?.status === 'completed'
- ? (issues.length === 0 ? 'checksums clean' : `${issues.length} issue${issues.length === 1 ? '' : 's'}`)
- : 'not checked yet',
- },
- {
- label: 'WP_DEBUG disabled',
- state: debug ? (debug.debug?.WP_DEBUG ? 'fail' : 'pass') : 'unknown',
- detail: debug ? (debug.debug?.WP_DEBUG ? 'debug is on' : 'off') : 'unavailable',
- },
- {
- label: 'No critical / high vulnerabilities',
- state: vulns?.scanned_at ? (((vsum.critical ?? 0) + (vsum.high ?? 0)) === 0 ? 'pass' : 'fail') : 'unknown',
- detail: vulns?.scanned_at
- ? `${(vsum.critical ?? 0) + (vsum.high ?? 0)} found`
- : 'no scan yet',
- },
- {
- label: 'Login brute-force protection',
- state: brute?.available === false ? 'unknown' : (brute?.enabled ? 'pass' : 'fail'),
- detail: brute?.available === false ? 'fail2ban unavailable' : (brute?.enabled ? 'jail active' : 'not protected'),
- },
- ];
- const scored = checks.filter(c => c.state !== 'unknown');
- const score = scored.length ? Math.round(scored.filter(c => c.state === 'pass').length / scored.length * 100) : null;
- const scoreColor = score >= 80 ? 'var(--green)' : score >= 50 ? 'var(--amber)' : 'var(--red)';
- const CHECK_PILL = { pass: 'green', fail: 'red', unknown: 'gray' };
-
- return (
- <div className="app-overview-grid">
- <div className="app-overview-left">
- <div className="app-panel">
- <div className="app-panel-header">Security posture</div>
- <div className="app-panel-body wp-posture">
- {score !== null ? (
- <ScoreGauge value={score} size={110} stroke={9} color={scoreColor} label="posture" />
- ) : (
- <p className="hint">Run the checks below to compute a posture score.</p>
- )}
- <div className="wp-posture__checks">
- {checks.map(c => (
- <div key={c.label} className="wp-posture__check">
- <span className="wp-posture__label">{c.label}</span>
- <span className="wp-posture__detail">{c.detail}</span>
- <Pill kind={CHECK_PILL[c.state]}>{c.state === 'unknown' ? 'pending' : c.state}</Pill>
- </div>
- ))}
- </div>
- </div>
- </div>
-
- <div className="app-panel">
- <div className="app-panel-header">File integrity</div>
- <div className="app-panel-body">
- <div className="app-detail-actions">
- <Button size="sm" onClick={runIntegrity} disabled={intRunning}>{intRunning ? 'Checking…' : 'Verify checksums'}</Button>
- </div>
- {(!integrity || integrity.status === 'idle') && <p className="hint">Verifies WordPress core and wordpress.org plugins against official checksums to detect tampered or unexpected files.</p>}
- {integrity?.status === 'error' && <p className="hint">Check failed: {integrity.error}</p>}
- {integrity?.status === 'completed' && (
- issues.length === 0
- ? <p className="hint">All core and plugin files verify against official checksums.</p>
- : <>
- <div className="app-detail-actions"><Pill kind="red">{issues.length} issue{issues.length === 1 ? '' : 's'}</Pill></div>
- <div className="wp-code-list">
- {issues.slice(0, 50).map((line, i) => <div key={i}>{line}</div>)}
- </div>
- </>
- )}
- </div>
- </div>
-
- <div className="app-panel">
- <div className="app-panel-header">Debug mode</div>
- <div className="app-panel-body">
- <div className="app-info-grid">
- <div className="app-info-item"><span className="app-info-label">WP_DEBUG</span><span className="app-info-value"><Pill kind={debug?.debug?.WP_DEBUG ? 'amber' : 'gray'}>{debug?.debug?.WP_DEBUG ? 'on' : 'off'}</Pill></span></div>
- <div className="app-info-item"><span className="app-info-label">Debug log</span><span className="app-info-value">{debug?.debug?.WP_DEBUG_LOG ? 'on' : 'off'}</span></div>
- <div className="app-info-item"><span className="app-info-label">Script debug</span><span className="app-info-value">{debug?.debug?.SCRIPT_DEBUG ? 'on' : 'off'}</span></div>
- </div>
- <div className="app-detail-actions">
- <Button variant="outline" size="sm" onClick={toggleDebug} disabled={busy}>{debug?.enabled ? 'Disable debugging' : 'Enable debugging'}</Button>
- </div>
- <p className="hint">Logs errors to a private file outside the web root (never to the page or a public URL). Enable to capture PHP fatals; disable in production.</p>
- </div>
- </div>
-
- <div className="app-panel">
- <div className="app-panel-header">WP-Cron</div>
- <div className="app-panel-body">
- <div className="app-info-grid">
- <div className="app-info-item"><span className="app-info-label">Pseudo-cron</span><span className="app-info-value">{cron?.disabled ? 'disabled' : 'enabled'}</span></div>
- <div className="app-info-item"><span className="app-info-label">Scheduled events</span><span className="app-info-value">{(cron?.events || []).length}</span></div>
- </div>
- <div className="app-detail-actions">
- <Button variant="outline" size="sm" onClick={runCron} disabled={busy}>Run due events</Button>
- <Button variant="outline" size="sm" onClick={toggleCron} disabled={busy}>{cron?.disabled ? 'Enable WP-Cron' : 'Disable WP-Cron'}</Button>
- </div>
- <p className="hint">Disable WP-Cron only if a real system cron hits wp-cron.php — otherwise scheduled tasks (publishing, updates) will not run.</p>
- </div>
- </div>
-
- <div className="app-panel">
- <div className="app-panel-header">Brute-force protection</div>
- <div className="app-panel-body">
- {brute?.available === false ? (
- <p className="hint">Fail2ban isn’t installed on this server, so login brute-force protection is inactive. Install it from the <strong>Security → Fail2ban</strong> page to enable per-site jails.</p>
- ) : (
- <>
- <div className="app-info-grid">
- <div className="app-info-item"><span className="app-info-label">Login jail</span><span className="app-info-value"><Pill kind={brute?.enabled ? 'green' : 'gray'}>{brute?.enabled ? 'active' : 'off'}</Pill></span></div>
- <div className="app-info-item"><span className="app-info-label">Currently banned</span><span className="app-info-value">{brute?.currently_banned ?? 0}</span></div>
- <div className="app-info-item"><span className="app-info-label">Total bans</span><span className="app-info-value">{brute?.total_banned ?? 0}</span></div>
- </div>
- <div className="app-detail-actions">
- <Button variant="outline" size="sm" onClick={toggleBrute} disabled={busy}>{brute?.enabled ? 'Disable protection' : 'Enable protection'}</Button>
- </div>
- {(brute?.banned_ips?.length > 0) && (
- <div className="wp-banlist">
- {brute.banned_ips.map(ip => (
- <div key={ip} className="wp-banlist__row">
- <span className="wp-banlist__ip">{ip}</span>
- <Button variant="ghost" size="sm" onClick={() => unbanIp(ip)} disabled={busy}>Unban</Button>
- </div>
- ))}
- </div>
- )}
- <p className="hint">
- Bans IPs that repeatedly POST to <code>wp-login.php</code> or <code>xmlrpc.php</code>
- {brute?.thresholds ? ` (${brute.thresholds.maxretry} attempts / ${Math.round(brute.thresholds.findtime / 60)} min → ${Math.round(brute.thresholds.bantime / 60)} min ban)` : ''}.
- {brute?.available && brute?.fail2ban_running === false ? ' Fail2ban is installed but not running — start it on the Security page.' : ''}
- </p>
- </>
- )}
- </div>
- </div>
- </div>
- </div>
- );
-};
-
-export default SecurityTab;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/SettingsTab.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/SettingsTab.jsx
deleted file mode 100644
index 5b543050..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/SettingsTab.jsx
+++ /dev/null
@@ -1,354 +0,0 @@
-import { useState } from 'react';
-import { useParams, useNavigate } from 'react-router-dom';
-import { Plus, Globe, Copy, Settings, RefreshCw, Archive, GitBranch, Lock, Shield, ShieldCheck, ShieldAlert, FileBarChart, Trash2 } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { useConfirm } from 'serverkit-sdk';
-import { DangerZone } from '@/components/DangerZone';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { SiteSSLPanel } from './wpDetailShared';
-import PhpTab from './PhpTab';
-import UpdatesTab from './UpdatesTab';
-import BackupsTab from './BackupsTab';
-import GitTab from './GitTab';
-import SecurityTab from './SecurityTab';
-import VulnerabilitiesTab from './VulnerabilitiesTab';
-import ReportsTab from './ReportsTab';
-
-// Search & Replace Modal (DB string replacement, guarded by dry-run)
-export const SearchReplaceModal = ({ onClose, onSubmit }) => {
- const [search, setSearch] = useState('');
- const [replace, setReplace] = useState('');
- const [loading, setLoading] = useState(false);
-
- async function run(dryRun) {
- if (!search.trim() || !replace.trim()) return;
- setLoading(true);
- try {
- await onSubmit({ search: search.trim(), replace: replace.trim(), dry_run: dryRun });
- } finally {
- setLoading(false);
- }
- }
-
- return (
- <Modal open onClose={onClose} title="Search & Replace">
- <form onSubmit={(e) => { e.preventDefault(); run(false); }}>
- <p className="hint">Replaces a string across all database tables (e.g. an old domain). Always preview with a dry run first.</p>
-
- <div className="form-group">
- <Label>Search for *</Label>
- <Input
- type="text"
- value={search}
- onChange={(e) => setSearch(e.target.value)}
- placeholder="https://old-domain.com"
- required
- />
- </div>
-
- <div className="form-group">
- <Label>Replace with *</Label>
- <Input
- type="text"
- value={replace}
- onChange={(e) => setReplace(e.target.value)}
- placeholder="https://new-domain.com"
- required
- />
- </div>
-
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose}>
- Cancel
- </Button>
- <Button type="button" variant="outline" onClick={() => run(true)} disabled={loading || !search.trim() || !replace.trim()}>
- {loading ? 'Running...' : 'Dry Run'}
- </Button>
- <Button type="submit" disabled={loading || !search.trim() || !replace.trim()}>
- {loading ? 'Running...' : 'Run Replace'}
- </Button>
- </div>
- </form>
- </Modal>
- );
-};
-
-// Delete Site Modal (typed confirmation + optional final backup)
-const DeleteSiteModal = ({ siteName, onClose, onConfirm }) => {
- const [createBackup, setCreateBackup] = useState(true);
- const [typed, setTyped] = useState('');
- const [loading, setLoading] = useState(false);
- const canDelete = typed.trim() === siteName;
-
- async function handleSubmit(e) {
- e.preventDefault();
- if (!canDelete) return;
- setLoading(true);
- try {
- await onConfirm(createBackup);
- } finally {
- setLoading(false);
- }
- }
-
- return (
- <Modal open onClose={onClose} title="Delete Site">
- <form onSubmit={handleSubmit}>
- <p className="hint">This permanently deletes <strong>{siteName}</strong>, all its environments, files and databases. This cannot be undone.</p>
- <div className="form-group">
- <label className="checkbox-label">
- <input
- type="checkbox"
- checked={createBackup}
- onChange={(e) => setCreateBackup(e.target.checked)}
- />
- <span>Create a final files + database backup before deleting</span>
- </label>
- </div>
- <div className="form-group">
- <Label>Type <strong>{siteName}</strong> to confirm *</Label>
- <Input
- type="text"
- value={typed}
- onChange={(e) => setTyped(e.target.value)}
- placeholder={siteName}
- autoFocus
- />
- </div>
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose} disabled={loading}>
- Cancel
- </Button>
- <Button type="submit" variant="destructive" disabled={loading || !canDelete}>
- {loading ? 'Deleting...' : 'Delete Site'}
- </Button>
- </div>
- </form>
- </Modal>
- );
-};
-
-// Settings tab — a left sub-nav that consolidates per-site configuration which
-// used to be its own top-level tabs (PHP, safe Updates, …). Each section just
-// reuses the existing tab component, so behavior is unchanged — only the home
-// moves. Defined last so the section components above are already in scope.
-// General settings — site-level actions that don't warrant an everyday top-bar
-// button (point a domain, change the URL, clone the site). They open the modals
-// that already live in WordPressDetail, via handlers passed down through ctx.
-const GeneralSettings = ({ onAddDomain, onChangeUrl, onClone }) => (
- <div className="app-overview-grid">
- <div className="app-overview-left">
- <div className="app-panel">
- <div className="app-panel-header">Domains &amp; URL</div>
- <div className="app-panel-body">
- <p className="hint">Point a custom domain you own at this site (auto-DNS + migrate), or change its primary URL with a serialization-safe database rewrite.</p>
- <div className="app-detail-actions">
- <Button variant="outline" size="sm" onClick={onAddDomain}>
- <Plus size={15} /> Add Domain
- </Button>
- <Button variant="outline" size="sm" onClick={onChangeUrl}>
- <Globe size={15} /> Change URL
- </Button>
- </div>
- </div>
- </div>
- <div className="app-panel">
- <div className="app-panel-header">Duplicate site</div>
- <div className="app-panel-body">
- <p className="hint">Clone this site as a brand-new independent site (its own Docker stack and database) with fresh admin credentials.</p>
- <div className="app-detail-actions">
- <Button variant="outline" size="sm" onClick={onClone}>
- <Copy size={15} /> Clone site
- </Button>
- </div>
- </div>
- </div>
- </div>
- </div>
-);
-
-// Danger Zone settings — destructive site-level actions moved out of the
-// Overview tab into Settings so the daily dashboard isn't dominated by them.
-const DangerZoneSettings = ({ site, onUpdate }) => {
- const toast = useToast();
- const navigate = useNavigate();
- const { confirm } = useConfirm();
- const [archiving, setArchiving] = useState(false);
- const [showDeleteModal, setShowDeleteModal] = useState(false);
-
- async function handleArchive() {
- const ok = await confirm({
- title: 'Archive Site',
- message: `Stop and archive "${site.name}"? Containers are stopped but all files and the database are kept. You can unarchive it later.`,
- confirmText: 'Archive',
- variant: 'warning',
- });
- if (!ok) return;
- setArchiving(true);
- toast.info('Archiving site...', { duration: 3000 });
- try {
- await wordpressApi.archiveSite(site.id);
- toast.success('Site archived');
- onUpdate?.();
- } catch (err) {
- toast.error(err.message || 'Failed to archive site');
- } finally {
- setArchiving(false);
- }
- }
-
- async function handleUnarchive() {
- setArchiving(true);
- toast.info('Unarchiving site...', { duration: 3000 });
- try {
- await wordpressApi.unarchiveSite(site.id);
- toast.success('Site unarchived');
- onUpdate?.();
- } catch (err) {
- toast.error(err.message || 'Failed to unarchive site');
- } finally {
- setArchiving(false);
- }
- }
-
- async function handleDelete(createBackup) {
- toast.info(createBackup ? 'Creating final backup and deleting site...' : 'Deleting site...', { duration: 5000 });
- try {
- await wordpressApi.deleteSite(site.id, { createBackup });
- toast.success('Site deleted');
- setShowDeleteModal(false);
- navigate('/wordpress');
- } catch (err) {
- toast.error(err.message || 'Failed to delete site');
- }
- }
-
- return (
- <>
- {showDeleteModal && (
- <DeleteSiteModal
- siteName={site.name}
- onClose={() => setShowDeleteModal(false)}
- onConfirm={handleDelete}
- />
- )}
- <div className="app-overview-grid">
- <div className="app-overview-left">
- <div className="app-panel danger-zone-panel">
- <div className="app-panel-header">Danger Zone</div>
- <div className="app-panel-body danger-zone-body">
- {site.status === 'archived' ? (
- <DangerZone
- title="Unarchive Site"
- description="Restart this site's containers and bring it back online."
- action={(
- <Button variant="outline" onClick={handleUnarchive} disabled={archiving}>
- <Archive size={16} />
- {archiving ? 'Unarchiving...' : 'Unarchive'}
- </Button>
- )}
- />
- ) : (
- <DangerZone
- title="Archive Site"
- description="Stop the containers but keep all files and the database. Reversible."
- action={(
- <Button variant="outline" onClick={handleArchive} disabled={archiving}>
- <Archive size={16} />
- {archiving ? 'Archiving...' : 'Archive'}
- </Button>
- )}
- />
- )}
- <DangerZone
- title="Delete Site"
- description="Permanently remove this site, all environments, files and databases. A final backup is taken by default."
- action={(
- <Button variant="destructive" onClick={() => setShowDeleteModal(true)}>
- <Trash2 size={16} />
- Delete Site
- </Button>
- )}
- />
- </div>
- </div>
- </div>
- </div>
- </>
- );
-};
-
-// Grouped left nav for the Settings tab. Each item just re-renders the existing
-// per-feature component (passed a single `ctx`), so behavior is unchanged — only
-// the home moves here to keep the top tab strip short. Groups give the nav
-// structure (the user's "group section" idea) and room to grow.
-const WP_SETTINGS_GROUPS = [
- { label: 'General', items: [
- { id: 'general', label: 'General', icon: Globe, render: (ctx) => <GeneralSettings {...ctx} /> },
- ] },
- { label: 'Configuration', items: [
- { id: 'php', label: 'PHP', icon: Settings, render: (ctx) => <PhpTab siteId={ctx.siteId} /> },
- { id: 'updates', label: 'Updates', icon: RefreshCw, render: (ctx) => <UpdatesTab siteId={ctx.siteId} /> },
- ] },
- { label: 'Data', items: [
- { id: 'backups', label: 'Backups', icon: Archive, render: (ctx) => <BackupsTab siteId={ctx.siteId} site={ctx.site} /> },
- ] },
- { label: 'Connections', items: [
- { id: 'git', label: 'Git', icon: GitBranch, render: (ctx) => <GitTab siteId={ctx.siteId} site={ctx.site} onUpdate={ctx.onUpdate} /> },
- ] },
- { label: 'Security', items: [
- { id: 'security', label: 'Security', icon: Lock, render: (ctx) => <SecurityTab siteId={ctx.siteId} /> },
- { id: 'ssl', label: 'SSL', icon: Shield, render: (ctx) => <SiteSSLPanel site={ctx.site} onUpdate={ctx.onUpdate} /> },
- { id: 'vulnerabilities', label: 'Vulnerabilities', icon: ShieldCheck, render: (ctx) => <VulnerabilitiesTab siteId={ctx.siteId} /> },
- ] },
- { label: 'Reports', items: [
- { id: 'reports', label: 'Reports', icon: FileBarChart, render: (ctx) => <ReportsTab siteId={ctx.siteId} /> },
- ] },
- { label: 'Danger Zone', items: [
- { id: 'danger-zone', label: 'Danger Zone', icon: ShieldAlert, render: (ctx) => <DangerZoneSettings site={ctx.site} onUpdate={ctx.onUpdate} /> },
- ] },
-];
-
-const WP_SETTINGS_ITEMS = WP_SETTINGS_GROUPS.flatMap((g) => g.items);
-
-const SettingsTab = ({ siteId, site, onUpdate, onAddDomain, onChangeUrl, onClone }) => {
- // Section lives in the URL (/wordpress/:id/settings/:section) so it's
- // shareable and survives a refresh, instead of resetting to General.
- const { id, section: sectionParam } = useParams();
- const navigate = useNavigate();
- const section = WP_SETTINGS_ITEMS.some((s) => s.id === sectionParam) ? sectionParam : 'general';
- const setSection = (s) => navigate(`/wordpress/${id}/settings/${s}`, { replace: true });
- const active = WP_SETTINGS_ITEMS.find((s) => s.id === section) || WP_SETTINGS_ITEMS[0];
- const ctx = { siteId, site, onUpdate, onAddDomain, onChangeUrl, onClone };
- return (
- <div className="wp-settings">
- <nav className="wp-settings__nav" aria-label="WordPress settings sections">
- {WP_SETTINGS_GROUPS.map((g) => (
- <div className="wp-settings__group" key={g.label}>
- <div className="wp-settings__grouplabel">{g.label}</div>
- {g.items.map((s) => (
- <button
- type="button"
- key={s.id}
- className={`wp-settings__navitem ${section === s.id ? 'is-active' : ''}`}
- onClick={() => setSection(s.id)}
- >
- <s.icon size={15} />
- {s.label}
- </button>
- ))}
- </div>
- ))}
- </nav>
- <div className="wp-settings__content">
- {active.render(ctx)}
- </div>
- </div>
- );
-};
-
-export default SettingsTab;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/ThemesTab.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/ThemesTab.jsx
deleted file mode 100644
index c2d67667..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/ThemesTab.jsx
+++ /dev/null
@@ -1,203 +0,0 @@
-import { useState, useEffect } from 'react';
-import { Palette } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { ErrorState } from '@/components/ErrorBoundary';
-import { EmptyState } from 'serverkit-sdk';
-import { Pill } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { ListItemSkeleton } from './wpDetailShared';
-
-// Themes Tab
-const ThemesTab = ({ siteId }) => {
- const toast = useToast();
- const [themes, setThemes] = useState([]);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState(null);
- const [installing, setInstalling] = useState(false);
- const [updating, setUpdating] = useState(null); // theme name being updated, or 'all'
- const [newTheme, setNewTheme] = useState('');
- const [activating, setActivating] = useState(null); // theme name being activated
-
- useEffect(() => {
- loadThemes();
- }, [siteId]);
-
- async function loadThemes() {
- setLoading(true);
- setError(null);
- try {
- const data = await wordpressApi.getThemes(siteId);
- setThemes(data.themes || []);
- } catch (err) {
- console.error('Failed to load themes:', err);
- setError(err);
- } finally {
- setLoading(false);
- }
- }
-
- async function handleInstall(e) {
- e.preventDefault();
- if (!newTheme.trim()) return;
-
- setInstalling(true);
- try {
- await wordpressApi.installTheme(siteId, { slug: newTheme.trim() });
- toast.success('Theme installed successfully');
- setNewTheme('');
- loadThemes();
- } catch (err) {
- toast.error(err.message || 'Failed to install theme');
- } finally {
- setInstalling(false);
- }
- }
-
- async function handleUpdate(themeName) {
- setUpdating(themeName || 'all');
- toast.info(themeName ? `Updating ${themeName}...` : 'Updating all themes...', { duration: 4000 });
- try {
- const res = await wordpressApi.updateThemes(siteId, themeName ? [themeName] : undefined);
- if (res.success === false) {
- toast.error(res.error || 'Theme update failed');
- return;
- }
- toast.success(res.message || 'Themes updated');
- loadThemes();
- } catch (err) {
- toast.error(err.message || 'Theme update failed');
- } finally {
- setUpdating(null);
- }
- }
-
- async function handleActivate(theme) {
- setActivating(theme.name);
- try {
- const res = await wordpressApi.activateTheme(siteId, theme.name);
- if (res && res.success === false) {
- toast.error(res.error || `Failed to activate ${theme.name}`);
- return;
- }
- toast.success(`${theme.title || theme.name} activated`);
- loadThemes();
- } catch (err) {
- toast.error(err.message || 'Failed to activate theme');
- } finally {
- setActivating(null);
- }
- }
-
- if (loading) {
- return (
- <SkeletonBoundary loading skeleton={(
- <div className="themes-tab">
- <div className="section-header">
- <div className="skeleton" style={{ width: 80, height: 24 }} />
- </div>
- <div className="skeleton" style={{ height: 44, borderRadius: 6, marginBottom: 16 }} />
- <div className="themes-list">
- <ListItemSkeleton />
- <ListItemSkeleton />
- <ListItemSkeleton />
- </div>
- </div>
- )} />
- );
- }
-
- if (error) {
- return (
- <ErrorState
- title="Failed to load themes"
- error={error}
- onRetry={loadThemes}
- />
- );
- }
-
- return (
- <div className="themes-tab">
- <div className="section-header">
- <h3>Themes</h3>
- </div>
-
- <form className="install-form" onSubmit={handleInstall}>
- <Input
- type="text"
- value={newTheme}
- onChange={(e) => setNewTheme(e.target.value)}
- placeholder="Theme slug (e.g., twentytwentyfour)"
- />
- <Button type="submit" disabled={installing}>
- {installing ? 'Installing...' : 'Install Theme'}
- </Button>
- </form>
-
- {themes.some(t => t.update === 'available') && (
- <div className="bulk-update-bar">
- <span>{themes.filter(t => t.update === 'available').length} theme update(s) available</span>
- <Button
- variant="outline"
- size="sm"
- onClick={() => handleUpdate(null)}
- disabled={updating !== null}
- >
- {updating === 'all' ? 'Updating...' : 'Update all'}
- </Button>
- </div>
- )}
-
- {themes.length === 0 ? (
- <EmptyState icon={Palette} title="No themes installed" description="Install a theme by entering its slug above." />
- ) : (
- <div className="wp-theme-grid">
- {themes.map(theme => {
- const isActive = theme.status === 'active';
- return (
- <div className={`wp-theme-card ${isActive ? 'is-active' : ''}`} key={theme.name}>
- <div className="wp-theme-card__shot">
- <Palette size={26} />
- {isActive && <Pill kind="green">Active</Pill>}
- </div>
- <div className="wp-theme-card__meta">
- <div className="wp-theme-card__name">{theme.title || theme.name}</div>
- <div className="wp-theme-card__sub">{theme.name} · v{theme.version}</div>
- <div className="wp-theme-card__actions">
- {isActive ? (
- <span className="wp-theme-card__current">Current theme</span>
- ) : (
- <Button
- variant="outline"
- size="sm"
- onClick={() => handleActivate(theme)}
- disabled={activating === theme.name}
- >
- {activating === theme.name ? 'Activating…' : 'Activate'}
- </Button>
- )}
- {theme.update === 'available' && (
- <Button
- variant="ghost"
- size="sm"
- onClick={() => handleUpdate(theme.name)}
- disabled={updating !== null}
- >
- {updating === theme.name ? 'Updating…' : 'Update'}
- </Button>
- )}
- </div>
- </div>
- </div>
- );
- })}
- </div>
- )}
- </div>
- );
-};
-
-export default ThemesTab;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/UpdatesTab.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/UpdatesTab.jsx
deleted file mode 100644
index 79febcb4..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/UpdatesTab.jsx
+++ /dev/null
@@ -1,137 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { Pill } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { OverviewGridSkeleton, UPDATE_SCHEDULES } from './wpDetailShared';
-
-// Updates Tab — safe update manager (#29): snapshot -> update -> health-check ->
-// auto-rollback, plus a per-site schedule and a run-history report.
-const UpdatesTab = ({ siteId }) => {
- const toast = useToast();
- const [data, setData] = useState(null);
- const [loading, setLoading] = useState(true);
- const [busy, setBusy] = useState(false);
- const [schedule, setSchedule] = useState('');
- const [excludeText, setExcludeText] = useState('');
-
- const load = React.useCallback(async () => {
- try {
- const res = await wordpressApi.getUpdates(siteId);
- setData(res);
- setSchedule(res.schedule || '');
- setExcludeText((res.exclude || []).join(', '));
- } catch (err) {
- toast.error(err.message || 'Failed to load updates');
- } finally {
- setLoading(false);
- }
- }, [siteId, toast]);
-
- useEffect(() => { load(); }, [load]);
- useEffect(() => {
- if (!data?.running) return undefined;
- const t = setTimeout(() => { wordpressApi.getUpdates(siteId).then(setData).catch(() => {}); }, 3000);
- return () => clearTimeout(t);
- }, [data, siteId]);
-
- const toList = (s) => s.split(',').map(x => x.trim()).filter(Boolean);
-
- async function runUpdate() {
- if (!window.confirm('Run a safe update now? A database snapshot is taken first and the site auto-rolls-back if the update breaks it.')) return;
- setBusy(true);
- try {
- await wordpressApi.runUpdates(siteId, { exclude: toList(excludeText) });
- toast.info('Safe update started…');
- setData(await wordpressApi.getUpdates(siteId));
- } catch (err) { toast.error(err.message || 'Failed to start update'); }
- finally { setBusy(false); }
- }
- async function saveSchedule() {
- setBusy(true);
- try {
- await wordpressApi.setUpdateSchedule(siteId, { schedule, exclude: toList(excludeText) });
- toast.success('Schedule saved');
- await load();
- } catch (err) { toast.error(err.message || 'Failed to save schedule'); }
- finally { setBusy(false); }
- }
-
- if (loading) return <SkeletonBoundary loading skeleton={<OverviewGridSkeleton panels={2} />} />;
-
- const runs = data?.runs || [];
- const running = data?.running;
- const statusPill = (s) => ({ completed: 'green', rolled_back: 'amber', failed: 'red', running: 'cyan' }[s] || 'gray');
-
- return (
- <div className="app-overview-grid">
- <div className="app-overview-left">
- <div className="app-panel">
- <div className="app-panel-header">Safe update</div>
- <div className="app-panel-body">
- <p className="hint">Snapshots the database, updates core + plugins + themes, health-checks the site, and automatically rolls back (version-pin + DB restore) if the update breaks it.</p>
- <div className="form-group">
- <Label>Exclude (skip) plugins/themes</Label>
- <Input value={excludeText} onChange={e => setExcludeText(e.target.value)} placeholder="e.g. woocommerce, my-custom-plugin" />
- <span className="form-hint">Comma-separated slugs to never auto-update.</span>
- </div>
- <div className="app-detail-actions">
- <Button size="sm" onClick={runUpdate} disabled={busy || running}>{running ? 'Updating…' : 'Run safe update now'}</Button>
- </div>
- </div>
- </div>
-
- <div className="app-panel">
- <div className="app-panel-header">Schedule</div>
- <div className="app-panel-body">
- <div className="form-group">
- <Label>Automatic safe updates</Label>
- <select value={schedule} onChange={e => setSchedule(e.target.value)} disabled={busy}>
- {UPDATE_SCHEDULES.map(s => <option key={s.value} value={s.value}>{s.label}</option>)}
- {schedule && !UPDATE_SCHEDULES.some(s => s.value === schedule) && <option value={schedule}>{schedule}</option>}
- </select>
- <span className="form-hint">Runs the same safe update (with auto-rollback) on a schedule.</span>
- </div>
- <div className="app-detail-actions">
- <Button variant="outline" size="sm" onClick={saveSchedule} disabled={busy}>Save schedule</Button>
- </div>
- </div>
- </div>
-
- <div className="app-panel">
- <div className="app-panel-header">Update history</div>
- <div className="app-panel-body">
- {runs.length === 0 ? (
- <p className="hint">No updates have run yet.</p>
- ) : runs.map(r => {
- const d = r.details || {};
- const n = (d.updated || []).length;
- return (
- <div className="wp-run-row" key={r.id}>
- <div className="wp-run-row-head">
- <Pill kind={statusPill(r.status)}>{r.status.replace('_', ' ')}</Pill>
- <span className="wp-run-row-meta">{r.started_at ? new Date(r.started_at).toLocaleString() : ''} · {r.trigger}</span>
- </div>
- <span className="form-hint">
- {n === 0 ? 'No components needed updating' : `${n} component${n === 1 ? '' : 's'} updated`}
- {d.rolled_back ? ' · auto-rolled back (update regressed the site)' : ''}
- {r.error ? ` · ${r.error}` : ''}
- </span>
- {d.warning && <span className="form-hint">⚠ {d.warning}</span>}
- {(d.updated || []).slice(0, 10).map((u, i) => (
- <span className="form-hint wp-run-component" key={i}>{u.type} {u.slug}: {u.from} → {u.to}</span>
- ))}
- </div>
- );
- })}
- </div>
- </div>
- </div>
- </div>
- );
-};
-
-export default UpdatesTab;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/UptimeTab.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/UptimeTab.jsx
deleted file mode 100644
index a3f59202..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/UptimeTab.jsx
+++ /dev/null
@@ -1,139 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import { Activity } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { HealthDot } from '../HealthStatusPanel';
-import { MetricCard } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { OverviewGridSkeleton } from './wpDetailShared';
-
-// Uptime Tab — per-site health + uptime % via a bound status-page component (#26).
-// Health is polled server-side every 5 min; outages auto-open incidents and alert
-// the configured notification channels.
-const UptimeTab = ({ siteId }) => {
- const toast = useToast();
- const [data, setData] = useState(null);
- const [loading, setLoading] = useState(true);
- const [pageId, setPageId] = useState('');
- const [busy, setBusy] = useState(false);
-
- const load = React.useCallback(async () => {
- setLoading(true);
- try {
- const res = await wordpressApi.getSiteStatusPage(siteId);
- setData(res);
- } catch (err) {
- toast.error(err.message || 'Failed to load uptime info');
- } finally {
- setLoading(false);
- }
- }, [siteId, toast]);
-
- useEffect(() => { load(); }, [load]);
- useEffect(() => {
- if (data?.pages?.length) setPageId(prev => prev || String(data.pages[0].id));
- }, [data]);
-
- async function handleAttach() {
- if (!pageId) { toast.error('Choose a status page'); return; }
- setBusy(true);
- try {
- await wordpressApi.attachStatusPage(siteId, Number(pageId));
- toast.success('Added to status page');
- await load();
- } catch (err) {
- toast.error(err.message || 'Failed to add to status page');
- } finally { setBusy(false); }
- }
-
- async function handleDetach() {
- if (!window.confirm('Remove this site from its status page? Its uptime history and component will be deleted.')) return;
- setBusy(true);
- try {
- await wordpressApi.detachStatusPage(siteId);
- toast.success('Removed from status page');
- await load();
- } catch (err) {
- toast.error(err.message || 'Failed to remove from status page');
- } finally { setBusy(false); }
- }
-
- if (loading) return <SkeletonBoundary loading skeleton={<OverviewGridSkeleton panels={2} />} />;
-
- const comp = data?.component;
- const pages = data?.pages || [];
- const pct = (v) => (v != null ? `${v.toFixed(2)}%` : '—');
-
- return (
- <div className="app-overview-grid">
- <div className="app-overview-left">
- <div className="app-panel">
- <div className="app-panel-header">Health</div>
- <div className="app-panel-body">
- <div className="app-info-grid">
- <div className="app-info-item">
- <span className="app-info-label">Current Status</span>
- <span className="app-info-value">
- <HealthDot status={data?.health_status} /> {data?.health_status || 'unknown'}
- </span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Last Checked</span>
- <span className="app-info-value">{data?.last_health_check ? new Date(data.last_health_check).toLocaleString() : 'Never'}</span>
- </div>
- </div>
- <p className="hint">Health is polled automatically every 5 minutes. Outages and recoveries alert your configured notification channels.</p>
- </div>
- </div>
-
- {comp ? (
- <div className="app-panel">
- <div className="app-panel-header">Uptime</div>
- <div className="app-panel-body">
- {comp.last_check_at ? (
- <div className="wp-kpis">
- <MetricCard icon={<Activity size={16} />} tone="green" value={pct(comp.uptime_24h)} label="Uptime · 24 hours" />
- <MetricCard icon={<Activity size={16} />} tone="green" value={pct(comp.uptime_7d)} label="Uptime · 7 days" />
- <MetricCard icon={<Activity size={16} />} tone="cyan" value={pct(comp.uptime_30d)} label="Uptime · 30 days" />
- <MetricCard icon={<Activity size={16} />} tone="cyan" value={pct(comp.uptime_90d)} label="Uptime · 90 days" />
- </div>
- ) : (
- <p className="hint">Awaiting the first health check (runs within 5 minutes).</p>
- )}
- <p className="hint">Uptime accrues from the 5-minute health checks; only fully-healthy checks count, so degraded periods reduce it. This site appears on its status page and auto-opens an incident on an outage (auto-resolved on recovery).</p>
- <div className="app-detail-actions">
- <Button variant="outline" size="sm" disabled={busy} onClick={handleDetach}>Remove from status page</Button>
- </div>
- </div>
- </div>
- ) : (
- <div className="app-panel">
- <div className="app-panel-header">Add to status page</div>
- <div className="app-panel-body">
- {pages.length === 0 ? (
- <p className="hint">No status pages exist yet. Create one under Status Pages first, then add this site to track its uptime and auto-open incidents on outages.</p>
- ) : (
- <>
- <p className="hint">Track uptime for this site on a status page. It accrues a real uptime % and auto-opens/resolves incidents on outages.</p>
- <div className="form-group">
- <Label>Status Page</Label>
- <select value={pageId} onChange={e => setPageId(e.target.value)} disabled={busy}>
- {pages.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
- </select>
- </div>
- <div className="app-detail-actions">
- <Button size="sm" disabled={busy} onClick={handleAttach}>Add to status page</Button>
- </div>
- </>
- )}
- </div>
- </div>
- )}
- </div>
- </div>
- );
-};
-
-export default UptimeTab;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/VulnerabilitiesTab.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/VulnerabilitiesTab.jsx
deleted file mode 100644
index d4983ef2..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/VulnerabilitiesTab.jsx
+++ /dev/null
@@ -1,138 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import { AlertTriangle } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { KpiBand, MetricCard } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { OverviewGridSkeleton } from './wpDetailShared';
-
-// Vulnerabilities Tab — cross-references plugin/theme/core versions against the
-// keyless WPVulnerability community feed (#28). On-demand background scan + poll.
-const VulnerabilitiesTab = ({ siteId }) => {
- const toast = useToast();
- const [data, setData] = useState(null);
- const [loading, setLoading] = useState(true);
- const [scanning, setScanning] = useState(false);
-
- const load = React.useCallback(async () => {
- try {
- const res = await wordpressApi.getVulnerabilities(siteId);
- setData(res);
- } catch (err) {
- toast.error(err.message || 'Failed to load vulnerabilities');
- } finally {
- setLoading(false);
- }
- }, [siteId, toast]);
-
- useEffect(() => { load(); }, [load]);
- useEffect(() => {
- if (data?.scan_status !== 'running') return undefined;
- const t = setTimeout(() => { load(); }, 2500);
- return () => clearTimeout(t);
- }, [data, load]);
-
- async function handleScan() {
- setScanning(true);
- try {
- await wordpressApi.scanVulnerabilities(siteId);
- toast.info('Vulnerability scan started…');
- await load();
- } catch (err) {
- toast.error(err.message || 'Failed to start scan');
- } finally {
- setScanning(false);
- }
- }
-
- if (loading) return <SkeletonBoundary loading skeleton={<OverviewGridSkeleton panels={2} />} />;
-
- const running = data?.scan_status === 'running';
- const summary = data?.summary || {};
- const vulns = data?.vulnerabilities || [];
-
- return (
- <div className="app-overview-grid">
- <div className="app-overview-left">
- <div className="app-panel">
- <div className="app-panel-header">Vulnerability scan</div>
- <div className="app-panel-body">
- <div className="app-detail-actions">
- <Button size="sm" onClick={handleScan} disabled={scanning || running}>
- {running ? 'Scanning…' : 'Run scan'}
- </Button>
- </div>
- <div className="app-info-grid">
- <div className="app-info-item"><span className="app-info-label">Last scan</span><span className="app-info-value">{data?.scanned_at ? new Date(data.scanned_at).toLocaleString() : 'Never'}</span></div>
- <div className="app-info-item"><span className="app-info-label">Findings</span><span className="app-info-value">{summary.total ?? 0}</span></div>
- </div>
- {data?.scan_error && <p className="hint">Last scan error: {data.scan_error}</p>}
- <p className="hint">Cross-references installed plugin, theme, and core versions against the WPVulnerability community database. Re-run after updating.</p>
- </div>
- </div>
-
- {data?.scanned_at && (
- <KpiBand>
- <MetricCard icon={<AlertTriangle size={16} />} tone="red" value={summary.critical ?? 0} label="Critical" />
- <MetricCard icon={<AlertTriangle size={16} />} tone="red" value={summary.high ?? 0} label="High" />
- <MetricCard icon={<AlertTriangle size={16} />} tone="amber" value={summary.medium ?? 0} label="Medium" />
- <MetricCard icon={<AlertTriangle size={16} />} tone="cyan" value={summary.low ?? 0} label="Low" />
- {summary.unknown > 0 && (
- <MetricCard icon={<AlertTriangle size={16} />} tone="violet" value={summary.unknown} label="Unrated" />
- )}
- </KpiBand>
- )}
-
- {vulns.length === 0 ? (
- <div className="app-panel">
- <div className="app-panel-body">
- <p className="hint">{data?.scanned_at ? 'No known vulnerabilities found.' : 'No scan has run yet — click Run scan to check this site.'}</p>
- </div>
- </div>
- ) : (
- <div className="app-panel">
- <div className="app-panel-header">Findings</div>
- <table className="sk-dtable wp-vuln-table">
- <thead>
- <tr>
- <th>Severity</th>
- <th>Component</th>
- <th>Issue</th>
- <th>Installed</th>
- <th>Fixed in</th>
- <th>Advisory</th>
- </tr>
- </thead>
- <tbody>
- {vulns.map(v => (
- <tr key={v.id}>
- <td><span className={`wp-sev wp-sev--${v.severity || 'unknown'}`}><span className="d" />{v.severity || 'unrated'}</span></td>
- <td>
- <div className="sk-cell-name">{v.name}</div>
- <div className="sk-cell-sub">{v.source}{v.slug ? ` · ${v.slug}` : ''}</div>
- </td>
- <td className="wp-vuln-title">{v.title || '—'}</td>
- <td><span className="sk-cell-mono">{v.installed_version}</span></td>
- <td>
- {v.fixed_in
- ? <span className="wp-fix-chip">{v.fixed_in}</span>
- : <span className="wp-no-fix">no fix yet</span>}
- </td>
- <td>
- {v.reference_url
- ? <a className="wp-advisory-link" href={v.reference_url} target="_blank" rel="noopener noreferrer">{v.advisory_id || 'advisory'} ↗</a>
- : <span className="sk-cell-mono">{v.advisory_id || '—'}</span>}
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- )}
- </div>
- </div>
- );
-};
-
-export default VulnerabilitiesTab;
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/wpDetailShared.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/wpDetailShared.jsx
deleted file mode 100644
index c7c6ef5f..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/detail/wpDetailShared.jsx
+++ /dev/null
@@ -1,553 +0,0 @@
-import { useState, useEffect } from 'react';
-import { Link } from 'react-router-dom';
-import { ChevronDown, Check, Lock, Globe, Shield, CircleCheck, CircleX } from 'lucide-react';
-import { api } from 'serverkit-sdk';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { Pill } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-
-// Detail Page Skeleton for initial loading
-// Mirrors the real page chrome (top bar, identity, repo pill, tabs) and the
-// Overview tab layout (KPIs, quick-actions + traffic grid, activity feed).
-export const DetailPageSkeleton = () => (
- <div className="wp-detail-page wp-detail-page--skeleton">
- {/* Top bar chrome */}
- <div className="sk-topbar-skeleton">
- <div className="sk-topbar-skeleton__icon" />
- <div className="sk-topbar-skeleton__title" />
- <div className="sk-topbar-skeleton__spacer" />
- <div className="sk-topbar-skeleton__actions">
- <div className="sk-topbar-skeleton__btn" />
- <div className="sk-topbar-skeleton__btn" />
- <div className="sk-topbar-skeleton__btn sk-topbar-skeleton__btn--primary" />
- </div>
- </div>
-
- <div className="app-detail-body">
- {/* Identity header */}
- <div className="app-detail-header">
- <div className="app-detail-icon wp-icon skeleton" style={{ width: 52, height: 52, borderRadius: 13 }} />
- <div className="app-detail-title-block">
- <div className="skeleton" style={{ width: 260, height: 24, marginBottom: 10 }} />
- <div className="skeleton" style={{ width: 340, height: 14 }} />
- </div>
- </div>
-
- {/* Repo pill placeholder */}
- <div className="wp-detail__repo-bar">
- <div className="wp-detail-skeleton-repo" />
- </div>
-
- {/* Tab strip */}
- <div className="app-detail-tabs">
- {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14].map(i => (
- <div key={i} className="skeleton app-detail-tab-skeleton" />
- ))}
- </div>
-
- {/* Overview tab content placeholder */}
- <div className="app-detail-content">
- <div className="wp-overview wp-overview--skeleton">
- {/* KPI row */}
- <div className="wp-kpis wp-kpis--skeleton">
- {[1, 2, 3, 4].map(i => (
- <div key={i} className="wp-detail-skeleton-kpi">
- <div className="wp-detail-skeleton-kpi__label" />
- <div className="wp-detail-skeleton-kpi__value" />
- </div>
- ))}
- </div>
-
- {/* Quick actions + traffic grid */}
- <div className="wp-overview-main">
- <div className="app-panel wp-detail-skeleton-panel">
- <div className="app-panel-header">
- <div className="skeleton" style={{ width: 100, height: 12 }} />
- </div>
- <div className="app-panel-body">
- <div className="quick-actions-grid">
- {[1, 2, 3, 4, 5, 6, 7, 8].map(i => (
- <div key={i} className="skeleton" style={{ height: 38, borderRadius: 8 }} />
- ))}
- </div>
- </div>
- </div>
-
- <div className="app-panel wp-detail-skeleton-panel wp-traffic-panel">
- <div className="app-panel-header">
- <div className="skeleton" style={{ width: 80, height: 12, marginBottom: 4 }} />
- <div className="skeleton" style={{ width: 140, height: 10 }} />
- </div>
- <div className="app-panel-body">
- <div className="wp-detail-skeleton-chart" />
- </div>
- </div>
- </div>
-
- {/* Recent activity panel */}
- <div className="app-panel wp-detail-skeleton-panel wp-activity-panel">
- <div className="app-panel-header">
- <div className="skeleton" style={{ width: 110, height: 12 }} />
- </div>
- <div className="app-panel-body">
- <div className="wp-detail-skeleton-activity">
- {[1, 2, 3, 4].map(i => (
- <div key={i} className="wp-detail-skeleton-activity__row">
- <div className="skeleton" style={{ width: 32, height: 32, borderRadius: '50%' }} />
- <div className="wp-detail-skeleton-activity__lines">
- <div className="skeleton" style={{ width: '40%', height: 12, marginBottom: 6 }} />
- <div className="skeleton" style={{ width: '65%', height: 10 }} />
- </div>
- </div>
- ))}
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
-);
-
-// Environment-type → dot tint for the header environment switcher.
-export const ENV_DOT_COLORS = {
- production: 'var(--green)',
- staging: 'var(--amber)',
- development: 'var(--cyan)',
- multidev: 'var(--violet)',
-};
-
-// Short label for an environment type tag (PROD / STAGING / DEV).
-export const envTagLabel = (type) => (
- type === 'production' ? 'PROD' : type === 'staging' ? 'STAGING' : 'DEV'
-);
-
-export const ENV_TYPE_LABELS = { production: 'Production', staging: 'Staging', development: 'Development', multidev: 'Multidev' };
-
-// Compact header environment switcher — navigates between the environment
-// site ids already present in the loaded payload (no extra fetches).
-export const EnvSwitcher = ({ options, onSelect }) => {
- const [open, setOpen] = useState(false);
-
- useEffect(() => {
- if (!open) return undefined;
- const close = () => setOpen(false);
- window.addEventListener('click', close);
- return () => window.removeEventListener('click', close);
- }, [open]);
-
- const current = options.find(o => o.current) || options[0];
-
- return (
- <div className="wp-envswitch-wrap">
- <button
- type="button"
- className={`wp-envswitch ${open ? 'open' : ''}`}
- onClick={(e) => { e.stopPropagation(); setOpen(o => !o); }}
- title="Switch environment"
- >
- <span className="ed" style={{ background: ENV_DOT_COLORS[current.type] || 'var(--text-faint)' }} />
- {ENV_TYPE_LABELS[current.type] || current.name}
- <ChevronDown size={13} className="chev" />
- </button>
- {open && (
- <div className="wp-envswitch-menu" onClick={e => e.stopPropagation()}>
- <div className="wp-envswitch-head">Switch environment</div>
- {options.map(o => (
- <button
- type="button"
- className="wp-envswitch-opt"
- key={o.id}
- onClick={() => { setOpen(false); if (!o.current) onSelect(o.id); }}
- >
- <span className="ed" style={{ background: ENV_DOT_COLORS[o.type] || 'var(--text-faint)' }} />
- <span className="wp-envswitch-opt-body">
- <span className="nm">{o.name}</span>
- <span className="meta">
- {envTagLabel(o.type)}
- {o.url ? ` · ${o.url.replace(/^https?:\/\//, '')}` : ''}
- </span>
- </span>
- {o.current && <Check size={14} className="check" />}
- </button>
- ))}
- </div>
- )}
- </div>
- );
-};
-
-// Header alert that nags the operator to secure the site when the primary
-// URL is not HTTPS. Clicking it jumps to SSL settings so the user can enable
-// HTTPS in one click (or see why it can't be issued yet, e.g. localhost).
-export const SSLAlert = ({ site }) => {
- const isHttps = (site.url || '').startsWith('https://');
-
- if (!site.url || isHttps) return null;
-
- return (
- <Link
- to={`/wordpress/${site.id}/settings/ssl`}
- className="sk-pill sk-pill--amber"
- >
- <span className="sk-pill__dot" />
- Not Secured
- </Link>
- );
-};
-
-// Friendly labels for the editable php.ini directives (#24 limits panel).
-export const PHP_LIMIT_LABELS = {
- memory_limit: 'Memory Limit',
- upload_max_filesize: 'Upload Max Filesize',
- post_max_size: 'Post Max Size',
- max_execution_time: 'Max Execution Time',
- max_input_time: 'Max Input Time',
- max_input_vars: 'Max Input Vars',
-};
-
-// Updates Tab — safe update schedule options (#29).
-export const UPDATE_SCHEDULES = [
- { label: 'Off', value: '' },
- { label: 'Weekly (Sun 3am)', value: '0 3 * * 0' },
- { label: 'Daily (3am)', value: '0 3 * * *' },
-];
-
-// Analytics Tab — period options (#25).
-export const ANALYTICS_PERIODS = [{ label: '24h', hours: 24 }, { label: '7d', hours: 168 }];
-
-// SSL Certificate panel — guided one-click SSL that walks the user through the
-// prerequisites (public domain, DNS, admin email) and then issues the cert.
-export const SiteSSLPanel = ({ site, onUpdate }) => {
- const toast = useToast();
- const domains = site.application?.domains || [];
- const primaryDomain = (domains.find(d => d.is_primary) || domains[0])?.name || null;
- // localhost / private-IP / no-domain sites cannot get a public certificate.
- const isPublicDomain = !!primaryDomain
- && !/^(localhost|127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(primaryDomain)
- && primaryDomain.includes('.');
- const hasAdminEmail = !!site.admin_email;
- const [health, setHealth] = useState(null);
- const [checking, setChecking] = useState(true);
- const [issuing, setIssuing] = useState(false);
-
- // Inline domain attach state (replaces the modal for the SSL flow).
- const [attachDomain, setAttachDomain] = useState('');
- const [attaching, setAttaching] = useState(false);
- const [attachResult, setAttachResult] = useState(null);
-
- // Connected DNS providers + ServerKit domains so the SSL panel feels linked
- // to the rest of the app.
- const [dnsProviders, setDnsProviders] = useState([]);
- const [serverkitDomains, setServerkitDomains] = useState([]);
- const [contextLoading, setContextLoading] = useState(true);
-
- useEffect(() => {
- if (!primaryDomain) { setChecking(false); return; }
- let cancelled = false;
- (async () => {
- setChecking(true);
- try {
- const res = await api.getSSLHealth(primaryDomain);
- if (!cancelled) setHealth(res);
- } catch (err) {
- if (!cancelled) setHealth({ valid: false, error: err.message });
- } finally {
- if (!cancelled) setChecking(false);
- }
- })();
- return () => { cancelled = true; };
- }, [primaryDomain]);
-
- useEffect(() => {
- let cancelled = false;
- (async () => {
- setContextLoading(true);
- try {
- const [providersRes, domainsRes] = await Promise.all([
- api.getEmailDNSProviders().then(d => d.providers || []).catch(() => []),
- api.getDomains().then(d => d.domains || []).catch(() => []),
- ]);
- if (!cancelled) {
- setDnsProviders(providersRes);
- setServerkitDomains(domainsRes);
- }
- } finally {
- if (!cancelled) setContextLoading(false);
- }
- })();
- return () => { cancelled = true; };
- }, [site.id]);
-
- async function handleEnableSSL() {
- if (!primaryDomain || !site.admin_email) return;
- setIssuing(true);
- toast.info(`Requesting certificate for ${primaryDomain}...`, { duration: 4000 });
- try {
- const res = await api.obtainCertificate({ domains: [primaryDomain], email: site.admin_email, use_nginx: true });
- if (res.success) {
- toast.success(res.message || 'Certificate issued');
- const updated = await api.getSSLHealth(primaryDomain);
- setHealth(updated);
- } else {
- toast.error(res.error || 'Certificate request failed');
- }
- } catch (err) {
- toast.error(err.message || 'Certificate request failed');
- } finally {
- setIssuing(false);
- }
- }
-
- async function handleAttachDomain(e) {
- e?.preventDefault();
- const domain = attachDomain.trim();
- if (!domain || attaching) return;
- setAttaching(true);
- toast.info('Attaching domain — creating DNS and moving the site…', { duration: 5000 });
- try {
- const res = await wordpressApi.attachDomain(site.id, { domain, issueSsl: true });
- if (res.success) {
- setAttachResult(res);
- if (res.dns?.created) toast.success(`DNS A record created via ${res.dns.provider}`);
- else toast.warning('Domain attached — add the DNS record shown to finish.', { duration: 7000 });
- onUpdate?.();
- } else {
- toast.error(res.error || 'Failed to attach domain');
- }
- } catch (err) {
- toast.error(err.message || 'Failed to attach domain');
- } finally {
- setAttaching(false);
- }
- }
-
- const issued = health?.valid;
- const attachValid = /^[a-z0-9.-]+\.[a-z]{2,}$/i.test(attachDomain.trim());
-
- const CheckItem = ({ ok, label }) => (
- <div className="ssl-check-item">
- {ok ? <CircleCheck size={14} className="ssl-check-icon ssl-check-icon--ok" /> : <CircleX size={14} className="ssl-check-icon ssl-check-icon--missing" />}
- <span className={ok ? 'ssl-check-label ssl-check-label--ok' : 'ssl-check-label'}>{label}</span>
- </div>
- );
-
- const rec = attachResult?.dns?.record;
-
- return (
- <div className="app-panel">
- <div className="app-panel-header"><Lock size={16} /> SSL Certificate</div>
- <div className="app-panel-body">
- <div className="app-info-grid">
- <div className="app-info-item">
- <span className="app-info-label">Primary Domain</span>
- <span className="app-info-value mono">{primaryDomain || 'None configured'}</span>
- </div>
- <div className="app-info-item">
- <span className="app-info-label">Status</span>
- <span className="app-info-value">
- <Pill kind={checking ? 'gray' : issued ? 'green' : 'amber'}>
- {checking ? 'Checking...' : issued ? `Active (${health.grade})` : 'Not Secured'}
- </Pill>
- </span>
- </div>
- {issued && health.expires_at && (
- <div className="app-info-item">
- <span className="app-info-label">Expires</span>
- <span className="app-info-value">
- {new Date(health.expires_at).toLocaleDateString()}
- {typeof health.days_remaining === 'number' ? ` (${health.days_remaining}d)` : ''}
- </span>
- </div>
- )}
- {issued && health.issuer && (
- <div className="app-info-item">
- <span className="app-info-label">Issuer</span>
- <span className="app-info-value">{health.issuer}</span>
- </div>
- )}
- </div>
-
- {!isPublicDomain ? (
- <div className="ssl-guide">
- <p className="hint">SSL requires a public domain pointed at this server. This site is on <code>{primaryDomain || 'localhost'}</code>, so a certificate cannot be issued here.</p>
- <div className="ssl-checklist">
- <CheckItem ok={false} label="Public domain mapped to this site" />
- <CheckItem ok={hasAdminEmail} label="Admin email set for certificate expiry notices" />
- </div>
-
- {!attachResult ? (
- <form className="ssl-inline-attach" onSubmit={handleAttachDomain}>
- {contextLoading ? (
- <p className="hint">Loading domain connections…</p>
- ) : (
- <div className="ssl-context">
- {dnsProviders.length > 0 ? (
- <div className="ssl-provider-status ssl-provider-status--ok">
- <CircleCheck size={14} />
- DNS auto-managed via {dnsProviders.map(p => p.name || p.provider).join(', ')}
- </div>
- ) : (
- <div className="ssl-provider-status ssl-provider-status--missing">
- <CircleX size={14} />
- No DNS provider connected — add Cloudflare/Route53/etc. for automatic records, or add the DNS record manually after attaching.
- </div>
- )}
- <div className="ssl-context-links">
- <Link to="/settings/connections">DNS connections</Link>
- <span>·</span>
- <Link to="/domains">Manage domains</Link>
- </div>
- </div>
- )}
-
- <div className="form-group">
- <Label>Domain</Label>
- <Input
- type="text"
- value={attachDomain}
- onChange={(e) => setAttachDomain(e.target.value)}
- placeholder="example.com"
- disabled={attaching}
- list="ssl-existing-domains"
- />
- <datalist id="ssl-existing-domains">
- {serverkitDomains
- .filter(d => !domains.some(ad => ad.name === d.name))
- .map(d => (
- <option key={d.id} value={d.name}>
- {d.ssl_enabled ? 'SSL enabled' : 'No SSL'}
- </option>
- ))}
- </datalist>
- <span className="form-hint">Pick an existing ServerKit domain or type one you control, without http://</span>
- </div>
- <div className="app-detail-actions">
- <Button type="submit" disabled={!attachValid || attaching}>
- <Globe size={14} />
- {attaching ? 'Attaching…' : 'Attach Domain & Enable SSL'}
- </Button>
- </div>
- </form>
- ) : (
- <div className="ssl-attach-result">
- <div className="ssl-attach-result__success">
- <CircleCheck size={16} />
- Site is now at <code>{attachResult.url}</code>
- </div>
- {attachResult.dns?.created ? (
- <p className="hint">DNS A record created automatically via {attachResult.dns.provider}{attachResult.dns.zone ? ` (zone ${attachResult.dns.zone})` : ''}.</p>
- ) : (
- <div className="ssl-attach-result__manual">
- <strong>Add this DNS record to finish:</strong>
- {rec?.value ? (
- <code className="ssl-attach-result__record">{rec.type}&nbsp;&nbsp;{rec.name}&nbsp;→&nbsp;{rec.value}</code>
- ) : (
- <p className="hint">{attachResult.dns?.message}</p>
- )}
- </div>
- )}
- {attachResult.warning && <p className="hint">{attachResult.warning}</p>}
- </div>
- )}
- </div>
- ) : !hasAdminEmail ? (
- <div className="ssl-guide">
- <p className="hint">A public domain is configured, but an admin email is required before requesting a certificate.</p>
- <div className="ssl-checklist">
- <CheckItem ok label={`Domain ${primaryDomain} configured`} />
- <CheckItem ok={false} label="Admin email set" />
- </div>
- <p className="hint">Update the site&apos;s admin email in Settings → General, then return here to enable SSL.</p>
- </div>
- ) : (
- <div className="ssl-guide">
- {issued ? (
- <p className="hint">This site is secured with a valid SSL certificate. You can re-issue it if needed.</p>
- ) : (
- <>
- <p className="hint">Everything is ready. One click will request a free certificate from Let&apos;s Encrypt and configure the server.</p>
- <div className="ssl-checklist">
- <CheckItem ok label={`Domain ${primaryDomain} configured`} />
- <CheckItem ok label="Admin email set" />
- </div>
- </>
- )}
- <div className="app-detail-actions">
- <Button onClick={handleEnableSSL} disabled={issuing}>
- {issued ? <Shield size={14} /> : <Lock size={14} />}
- {issuing ? 'Requesting...' : issued ? 'Re-issue Certificate' : 'Enable SSL'}
- </Button>
- </div>
- </div>
- )}
- </div>
- </div>
- );
-};
-
-// Reusable Skeleton Components for Tabs
-export const EnvironmentCardSkeleton = () => (
- <div className="wp-env-card-skeleton">
- <div className="wp-env-card-skeleton-header">
- <div className="wp-env-card-skeleton-badge" />
- <div className="wp-env-card-skeleton-status" />
- </div>
- <div className="wp-env-card-skeleton-body">
- <div className="wp-env-card-skeleton-url" />
- <div className="wp-env-card-skeleton-meta">
- <div className="wp-env-card-skeleton-meta-item">
- <div className="skeleton-label" />
- <div className="skeleton-value" />
- </div>
- <div className="wp-env-card-skeleton-meta-item">
- <div className="skeleton-label" />
- <div className="skeleton-value" />
- </div>
- </div>
- </div>
- <div className="wp-env-card-skeleton-footer">
- <div className="skeleton" style={{ flex: 1, height: 28, borderRadius: 4 }} />
- <div className="skeleton" style={{ flex: 1, height: 28, borderRadius: 4 }} />
- </div>
- </div>
-);
-
-export const ListItemSkeleton = () => (
- <div className="skeleton" style={{ height: 48, borderRadius: 6, marginBottom: 8 }} />
-);
-
-// Generic panel skeleton — matches .app-panel + .app-panel-header + .app-panel-body
-export const PanelSkeleton = ({ headerWidth = 100, rows = 3, children }) => (
- <div className="app-panel wp-detail-skeleton-panel">
- <div className="app-panel-header">
- <div className="skeleton" style={{ width: headerWidth, height: 12 }} />
- </div>
- <div className="app-panel-body">
- {children || (
- <div className="wp-detail-skeleton-rows">
- {Array.from({ length: rows }).map((_, i) => (
- <div key={i} className="wp-detail-skeleton-row">
- <div className="skeleton" style={{ width: '35%', height: 10 }} />
- <div className="skeleton" style={{ width: '55%', height: 14 }} />
- </div>
- ))}
- </div>
- )}
- </div>
- </div>
-);
-
-// Skeleton used by tabs that render inside .app-overview-grid > .app-overview-left
-export const OverviewGridSkeleton = ({ panels = 2 }) => (
- <div className="app-overview-grid">
- <div className="app-overview-left">
- {Array.from({ length: panels }).map((_, i) => (
- <PanelSkeleton key={i} headerWidth={i === 0 ? 120 : 160} />
- ))}
- </div>
- </div>
-);
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/index.js b/frontend/src/plugins/serverkit-wordpress/components/wordpress/index.js
deleted file mode 100644
index 965680fc..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/index.js
+++ /dev/null
@@ -1,21 +0,0 @@
-export { default as WordPressSiteCard } from './WordPressSiteCard';
-export { default as EnvironmentCard } from './EnvironmentCard';
-export { default as SnapshotTable } from './SnapshotTable';
-export { default as GitConnectForm } from './GitConnectForm';
-export { default as CommitList } from './CommitList';
-export { default as PipelineView } from './PipelineView';
-export { default as PromoteModal } from './PromoteModal';
-export { default as SyncModal } from './SyncModal';
-export { default as ActivityFeed } from './ActivityFeed';
-export { default as ContainerLogs } from './ContainerLogs';
-export { default as EnvironmentStatusBadge } from './EnvironmentStatusBadge';
-export { default as CompareView } from './CompareView';
-export { default as SanitizationProfileForm } from './SanitizationProfileForm';
-export { default as ResourceLimitsModal } from './ResourceLimitsModal';
-export { default as BasicAuthModal } from './BasicAuthModal';
-export { default as WpCliTerminal } from './WpCliTerminal';
-export { default as HealthStatusPanel } from './HealthStatusPanel';
-export { HealthDot } from './HealthStatusPanel';
-export { default as DiskUsageBar } from './DiskUsageBar';
-export { default as AutoSyncScheduleModal } from './AutoSyncScheduleModal';
-export { default as BulkActionsBar } from './BulkActionsBar';
diff --git a/frontend/src/plugins/serverkit-wordpress/components/wordpress/wordpressTabs.jsx b/frontend/src/plugins/serverkit-wordpress/components/wordpress/wordpressTabs.jsx
deleted file mode 100644
index 05e9f5a1..00000000
--- a/frontend/src/plugins/serverkit-wordpress/components/wordpress/wordpressTabs.jsx
+++ /dev/null
@@ -1,12 +0,0 @@
-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
-// top-bar layout replaces the old sidebar sub-menu (REDESIGN_MAP §6 dec. 3).
-// (The Pipeline tab was wpInstalled-gated in the sidebar; kept always-visible
-// 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/plugins/serverkit-wordpress/index.jsx b/frontend/src/plugins/serverkit-wordpress/index.jsx
deleted file mode 100644
index 6d7b0486..00000000
--- a/frontend/src/plugins/serverkit-wordpress/index.jsx
+++ /dev/null
@@ -1,75 +0,0 @@
-// WordPress UI, contributed through the extension system. Both halves now
-// live in this extension: the backend (the /api/v1/wordpress* blueprints +
-// services) under backend/, and the full frontend (5 pages + the
-// components/wordpress tree + styles/) here — moved out of the host's pages/
-// and styles/ in plan 52 Phase 4. After `sync-builtin-frontends.mjs` this
-// tree is baked at frontend/src/plugins/serverkit-wordpress/, where the host
-// build compiles it (the @/ alias imports that remain resolve there; the
-// runtime-ESM conversion that drops them is Phase 5).
-//
-// Styles ship with the extension: the three SCSS entries below are compiled
-// by the host build through this module graph (they import the host's
-// variables partial via a sync-safe relative path), replacing the former
-// main.scss partials.
-import './styles/wordpress.scss';
-import './styles/wordpress-pipeline.scss';
-import './styles/wordpress-plugin-library.scss';
-
-// The WordPress surface is a tab group + full-bleed detail pages. Contributed
-// routes are flat (there's no way to contribute a shared TabGroupLayout parent
-// inside the dashboard), so we contribute ONE splat route (`wordpress/*`) and
-// this component self-renders the whole WordPress sub-router — reproducing the
-// exact structure the core App.jsx used to own (TabGroupLayout + WORDPRESS_TABS
-// over the three list pages; full-bleed detail/pipeline routes as siblings;
-// the legacy /wordpress/projects → /wordpress/pipelines deprecation redirects).
-import { Routes, Route, Navigate, useParams } from 'react-router-dom';
-import { TabGroupLayout } from 'serverkit-sdk';
-
-import { WORDPRESS_TABS } from './components/wordpress/wordpressTabs';
-import WordPress from './pages/WordPress';
-import WordPressPluginLibrary from './pages/WordPressPluginLibrary';
-import WordPressProjects from './pages/WordPressProjects';
-import WordPressProject from './pages/WordPressProject';
-import WordPressDetail from './pages/WordPressDetail';
-import WordPressSshImport from './WordPressSshImport';
-
-// "WordPress Projects" was renamed to "Pipelines" (§2 unification). Forward old
-// deep links to the new space.
-function LegacyWpPipelineRedirect() {
- const { id, tab } = useParams();
- const suffix = [id, tab].filter(Boolean).join('/');
- return <Navigate to={`/wordpress/pipelines/${suffix}`} replace />;
-}
-
-export function WordPressExtension() {
- return (
- <Routes>
- {/* Tab group — list surfaces share one PageTopbar + WORDPRESS_TABS. */}
- <Route element={<TabGroupLayout tabs={WORDPRESS_TABS} />}>
- <Route index element={<WordPress />} />
- <Route path="plugins/library" element={<WordPressPluginLibrary />} />
- <Route path="pipelines" element={<WordPressProjects />} />
- {/* SSH pull-import (Panel Improvements #3) — shares the group
- chrome; reached via the command palette / direct link. */}
- <Route path="ssh-import" element={<WordPressSshImport />} />
- </Route>
- {/* Full-bleed pipeline detail (own chrome, outside the tab group). */}
- <Route path="pipelines/:id" element={<WordPressProject />} />
- <Route path="pipelines/:id/:tab" element={<WordPressProject />} />
- {/* Legacy "WordPress Projects" URLs → Pipelines (§2). */}
- <Route path="projects" element={<Navigate to="/wordpress/pipelines" replace />} />
- <Route path="projects/:id" element={<LegacyWpPipelineRedirect />} />
- <Route path="projects/:id/:tab" element={<LegacyWpPipelineRedirect />} />
- {/* Full-bleed site detail (own chrome, outside the tab group). The
- :tab/:section depth keeps the Settings sub-nav shareable. */}
- <Route path=":id" element={<WordPressDetail />} />
- <Route path=":id/:tab" element={<WordPressDetail />} />
- <Route path=":id/:tab/:section" element={<WordPressDetail />} />
- </Routes>
- );
-}
-
-// No default export on purpose: PluginLoader legacy-auto-renders any plugin
-// default export globally — this sub-router mounted that way runs outside its
-// route and swallows the current location ("/domains" → :id "domains").
-// The route contribution resolves the NAMED export via resolveComponent.
diff --git a/frontend/src/plugins/serverkit-wordpress/pages/WordPress.jsx b/frontend/src/plugins/serverkit-wordpress/pages/WordPress.jsx
deleted file mode 100644
index e47fffb5..00000000
--- a/frontend/src/plugins/serverkit-wordpress/pages/WordPress.jsx
+++ /dev/null
@@ -1,677 +0,0 @@
-import { useState, useEffect } from 'react';
-import { useNavigate } from 'react-router-dom';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import ResourceAdvisory from '@/components/ResourceAdvisory';
-import { Spinner } from 'serverkit-sdk';
-import ResourceListPage from '@/components/layouts/ResourceListPage';
-import { Globe, ChevronRight } from 'lucide-react';
-import { Pill, ServiceTile, Drawer } from 'serverkit-sdk';
-import { useTopbarActions } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { Checkbox } from 'serverkit-sdk';
-import { SkeletonBoundary } from 'serverkit-sdk';
-
-// Mirror the backend slug rule (a-z, 0-9, single dashes) so the create modal can
-// preview the exact <slug>.<base> host the site will be published at.
-function slugifyPreview(name) {
- return (name || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'site';
-}
-
-function WordPress() {
- const [sites, setSites] = useState([]);
- const [loading, setLoading] = useState(true);
- const [activeTag, setActiveTag] = useState(null); // null = show all
- const [statusFilter, setStatusFilter] = useState('all'); // all | running | stopped
- const [siteSearch, setSiteSearch] = useState(''); // client-side name/title/domain filter
- const [showCreateModal, setShowCreateModal] = useState(false);
- const [createLoading, setCreateLoading] = useState(false);
- const [createForm, setCreateForm] = useState({
- name: '', domain: '', adminEmail: '', phpVersion: '', enablePageCache: false, enableObjectCache: false,
- baseDomain: '',
- });
- // Base domains a new site can be published under (<slug>.<base>), loaded when
- // the create modal opens. Empty when site routing isn't configured.
- const [baseDomains, setBaseDomains] = useState([]);
- const [createdCreds, setCreatedCreds] = useState(null);
- // Where a freshly-created site is reachable, so we can tell the user it is
- // already live (at <slug>.<base>, HTTPS when the wildcard cert is set up)
- // rather than leaving them to wonder — or nudge them to set a base domain
- // when the site only came up on localhost.
- const [createdSite, setCreatedSite] = useState(null);
- const [showImportModal, setShowImportModal] = useState(false);
- const [importLoading, setImportLoading] = useState(false);
- const [importForm, setImportForm] = useState({ name: '', adminEmail: '', oldUrl: '' });
- const [importFile, setImportFile] = useState(null);
- const [wpContentFile, setWpContentFile] = useState(null);
- const [selectedIds, setSelectedIds] = useState(new Set());
- const [bulkLoading, setBulkLoading] = useState(false);
-
- const navigate = useNavigate();
- const toast = useToast();
-
- useEffect(() => {
- loadSites();
- }, []);
-
- // Load the available base domains when the create modal opens, and preselect
- // the default so the site publishes under it unless the user picks another.
- useEffect(() => {
- if (!showCreateModal) return;
- let cancelled = false;
- (async () => {
- try {
- const data = await wordpressApi.listBaseDomains();
- if (cancelled) return;
- const bases = data.base_domains || [];
- setBaseDomains(bases);
- setCreateForm(f => ({ ...f, baseDomain: f.baseDomain || data.default || '' }));
- } catch {
- if (!cancelled) setBaseDomains([]);
- }
- })();
- return () => { cancelled = true; };
- }, [showCreateModal]);
-
- const loadSites = async () => {
- setLoading(true);
- try {
- const data = await wordpressApi.getSites();
- setSites(data.sites || []);
- } catch (error) {
- console.error('Failed to load WordPress sites:', error);
- setSites([]);
- } finally {
- setLoading(false);
- }
- };
-
- const handleCreate = async () => {
- if (!createForm.name) {
- toast.error('Site name is required');
- return;
- }
-
- setCreateLoading(true);
- try {
- const result = await wordpressApi.createSite(createForm);
- if (result.success) {
- if (result.admin_password) {
- // The generated admin password is returned once — surface it.
- setCreatedCreds({ user: result.admin_user || 'admin', password: result.admin_password });
- }
- if (result.url) {
- setCreatedSite({ url: result.url, domain: result.domain || null });
- }
- if (result.warning) {
- toast.info(result.warning, { duration: 8000 });
- }
- toast.success('WordPress site created successfully');
- setShowCreateModal(false);
- setCreateForm({ name: '', domain: '', adminEmail: '', phpVersion: '', enablePageCache: false, enableObjectCache: false, baseDomain: '' });
- await loadSites();
- } else {
- toast.error(result.error || 'Failed to create site');
- }
- } catch (error) {
- toast.error(`Failed to create site: ${error.message}`);
- } finally {
- setCreateLoading(false);
- }
- };
-
- // Bulk ops fan out per-site (no bulk route yet — §5); `applies` filters the
- // selection to sites the action makes sense for.
- const bulkRun = async (label, fn, applies = () => true) => {
- const targets = sites.filter(s => selectedIds.has(s.id) && applies(s));
- if (targets.length === 0) {
- toast.info(`No selected sites need "${label}"`);
- return;
- }
- setBulkLoading(true);
- try {
- const results = await Promise.allSettled(targets.map(s => fn(s)));
- const failed = results.filter(r => r.status === 'rejected').length;
- if (failed) toast.error(`${label}: ${failed} of ${targets.length} failed`);
- else toast.success(`${label} sent to ${targets.length} site${targets.length === 1 ? '' : 's'}`);
- setSelectedIds(new Set());
- await loadSites();
- } finally {
- setBulkLoading(false);
- }
- };
-
- const handleImport = async () => {
- if (!importForm.name) { toast.error('Site name is required'); return; }
- if (!importForm.oldUrl) { toast.error('Original site URL is required'); return; }
- if (!importFile) { toast.error('A .sql or .sql.gz dump is required'); return; }
- setImportLoading(true);
- try {
- const result = await wordpressApi.importSite({
- name: importForm.name,
- adminEmail: importForm.adminEmail,
- oldUrl: importForm.oldUrl,
- sqlFile: importFile,
- wpContentFile: wpContentFile,
- });
- if (result.success) {
- toast.success('WordPress site imported successfully');
- if (result.wp_content_imported) toast.success('wp-content (plugins/themes/uploads) imported');
- if (result.warning) toast.info(result.warning, { duration: 8000 });
- setShowImportModal(false);
- setImportForm({ name: '', adminEmail: '', oldUrl: '' });
- setImportFile(null);
- setWpContentFile(null);
- await loadSites();
- } else {
- toast.error(result.error || 'Failed to import site');
- }
- } catch (error) {
- toast.error(`Failed to import site: ${error.message}`);
- } finally {
- setImportLoading(false);
- }
- };
-
- useTopbarActions(() =>
- <>
- <Button variant="outline" size="sm" onClick={() => navigate('/imports')}>
- Import a site
- </Button>
- <Button variant="outline" size="sm" onClick={() => setShowImportModal(true)}>
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
- Import Site
- </Button>
- <Button size="sm" onClick={() => setShowCreateModal(true)}>
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
- Create Site
- </Button>
- </>,
- []
- );
-
- const wpListSkeleton = (
- <div className="wp-sites-grid">
- {[1, 2, 3].map(i => (
- <div key={i} className="wp-site-card-skeleton">
- <div className="wp-site-card-skeleton-header">
- <div className="wp-site-card-skeleton-icon" />
- <div className="wp-site-card-skeleton-info">
- <div className="wp-site-card-skeleton-name" />
- <div className="wp-site-card-skeleton-url" />
- </div>
- <div className="wp-site-card-skeleton-status" />
- </div>
- <div className="wp-site-card-skeleton-body">
- <div className="wp-site-card-skeleton-meta">
- <div className="wp-site-card-skeleton-label" />
- <div className="wp-site-card-skeleton-value" />
- </div>
- <div className="wp-site-card-skeleton-meta">
- <div className="wp-site-card-skeleton-label" />
- <div className="wp-site-card-skeleton-value" />
- </div>
- </div>
- </div>
- ))}
- </div>
- );
-
- if (loading) {
- return (
- <SkeletonBoundary
- className="sk-tabgroup__inner wordpress-page"
- loading
- skeleton={wpListSkeleton}
- />
- );
- }
-
- const allTags = Array.from(new Set(sites.flatMap(s => s.tags || []))).sort();
- const runningCount = sites.filter(s => s.status === 'running').length;
- const q = siteSearch.trim().toLowerCase();
- const siteLabel = site => site.name || site.application?.name || `Site ${site.id}`;
- const shownSites = sites.filter(site => (
- (statusFilter === 'all'
- || (statusFilter === 'running' ? site.status === 'running' : site.status !== 'running'))
- && (activeTag === null || (site.tags || []).includes(activeTag))
- && (q === '' || [siteLabel(site), site.title, site.url, site.domain]
- .some(v => v && String(v).toLowerCase().includes(q)))
- ));
- const allSelected = shownSites.length > 0 && shownSites.every(s => selectedIds.has(s.id));
-
- const columns = [
- {
- key: '__select',
- className: 'wp-list__ck',
- cellClassName: 'wp-list__ck',
- header: (
- <Checkbox
- checked={allSelected}
- onCheckedChange={(checked) => setSelectedIds(checked ? new Set(shownSites.map(s => s.id)) : new Set())}
- aria-label="Select all sites"
- />
- ),
- render: (site) => (
- <div onClick={e => e.stopPropagation()}>
- <Checkbox
- checked={selectedIds.has(site.id)}
- onCheckedChange={(checked) => {
- setSelectedIds(prev => {
- const next = new Set(prev);
- if (checked) next.add(site.id);
- else next.delete(site.id);
- return next;
- });
- }}
- aria-label={`Select ${site.name || `site ${site.id}`}`}
- />
- </div>
- ),
- },
- {
- key: 'name',
- header: 'Site',
- render: (site) => (
- <div className="sk-cell-name">
- <ServiceTile name={siteLabel(site)} size={30} className="wp-list__tile" aria-hidden="true" />
- <span>
- <div>{siteLabel(site)}</div>
- {site.port && <div className="sk-cell-sub">:{site.port}</div>}
- </span>
- </div>
- ),
- },
- { key: 'environments', header: 'Environments', cellClassName: 'sk-cell-mono', render: (site) => (site.environment_count || 0) + 1 },
- { key: 'version', header: 'Version', cellClassName: 'sk-cell-mono', render: (site) => `WP ${site.wp_version || '6.4'}` },
- {
- key: 'status',
- header: 'Status',
- render: (site) => (
- <Pill kind={site.status === 'running' ? 'green' : 'gray'}>
- {site.status === 'running' ? 'Running' : 'Stopped'}
- </Pill>
- ),
- },
- {
- key: 'tags',
- header: 'Tags',
- render: (site) => (
- site.tags?.length
- ? site.tags.map(tag => <span key={tag} className="sk-tag">{tag}</span>)
- : <span className="wp-list__dash">—</span>
- ),
- },
- {
- key: '__links',
- header: '',
- width: 70,
- render: (site) => (
- site.url && site.status === 'running' ? (
- <div className="wp-list__links" onClick={e => e.stopPropagation()}>
- <a href={site.url} target="_blank" rel="noopener noreferrer" title="Open site" aria-label="Open site">
- <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
- </a>
- <a href={`${site.url}/wp-admin`} target="_blank" rel="noopener noreferrer" title="WP Admin" aria-label="WP Admin">
- <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
- </a>
- </div>
- ) : (
- <ChevronRight size={16} className="wp-list__chev" />
- )
- ),
- },
- ];
-
- return (
- <ResourceListPage
- className="wordpress-page"
- totalCount={sites.length}
- items={shownSites}
- columns={columns}
- keyField="id"
- onRowClick={(site) => navigate(`/wordpress/${site.id}`)}
- rowClassName={(site) => (selectedIds.has(site.id) ? 'is-selected' : '')}
- header={<>
- {/* Advisory, not a gate: a constrained server says so here and
- the operator still decides. */}
- <ResourceAdvisory workload="wordpress" />
- {(createdCreds || createdSite) && (
- <div className="wp-creds-banner">
- <div className="wp-creds-banner-text">
- {createdSite && (createdSite.domain ? (
- <span>
- Your site is live at{' '}
- <a href={createdSite.url} target="_blank" rel="noopener noreferrer"><code>{createdSite.domain}</code></a>
- {createdSite.url?.startsWith('https') ? ' — HTTPS is ready.' : '.'}
- </span>
- ) : (
- <span>
- Your site is running at{' '}
- <a href={createdSite.url} target="_blank" rel="noopener noreferrer"><code>{createdSite.url}</code></a>.
- {' '}Set a managed-sites base domain in Settings to publish it at a public URL.
- </span>
- ))}
- {createdCreds && (
- <>
- <strong>Save these admin credentials — they are shown only once.</strong>
- <span>Username: <code>{createdCreds.user}</code></span>
- <span>Password: <code>{createdCreds.password}</code></span>
- </>
- )}
- </div>
- <Button variant="ghost" onClick={() => { setCreatedCreds(null); setCreatedSite(null); }}>Dismiss</Button>
- </div>
- )}
- </>}
- filters={[
- { value: 'all', label: 'All', count: sites.length },
- { value: 'running', label: 'Running', count: runningCount },
- { value: 'stopped', label: 'Stopped', count: sites.length - runningCount },
- ]}
- activeFilter={statusFilter}
- onFilterChange={setStatusFilter}
- searchTerm={siteSearch}
- onSearchChange={setSiteSearch}
- searchPlaceholder="Search sites…"
- toolbarExtra={allTags.length > 0 && (
- <div className="wp-tag-filter">
- <button type="button"
- className={`wp-tag-chip wp-tag-chip--filter ${activeTag === null ? 'is-active' : ''}`}
- onClick={() => setActiveTag(null)}
- >
- All tags
- </button>
- {allTags.map(tag => (
- <button type="button"
- key={tag}
- className={`wp-tag-chip wp-tag-chip--filter ${activeTag === tag ? 'is-active' : ''}`}
- onClick={() => setActiveTag(tag)}
- >
- {tag}
- </button>
- ))}
- </div>
- )}
- selectedCount={selectedIds.size}
- onClearSelection={() => setSelectedIds(new Set())}
- bulkActions={
- <>
- <Button variant="outline" size="sm" disabled={bulkLoading}
- onClick={() => bulkRun('Start', s => wordpressApi.unarchiveSite(s.id), s => s.status !== 'running')}>
- Start
- </Button>
- <Button variant="outline" size="sm" disabled={bulkLoading}
- onClick={() => bulkRun('Stop', s => wordpressApi.archiveSite(s.id), s => s.status === 'running')}>
- Stop
- </Button>
- <Button variant="outline" size="sm" disabled={bulkLoading}
- onClick={() => bulkRun('Update core', s => wordpressApi.updateCore(s.id), s => s.status === 'running')}>
- Update
- </Button>
- <Button variant="outline" size="sm" disabled={bulkLoading}
- onClick={() => bulkRun('Backup', s => wordpressApi.createSnapshot(s.id, { name: 'bulk-backup' }), s => s.status === 'running')}>
- Backup
- </Button>
- <Button variant="outline" size="sm" disabled={bulkLoading}
- onClick={() => bulkRun('Clear cache', s => wordpressApi.flushCache(s.id), s => s.status === 'running')}>
- Clear cache
- </Button>
- </>
- }
- emptyIcon={Globe}
- emptyTitle="No WordPress Sites"
- emptyDescription="Create your first WordPress site powered by Docker. Each site gets its own isolated environment with MySQL."
- emptyAction={
- <Button onClick={() => setShowCreateModal(true)}>
- Create Site
- </Button>
- }
- filteredEmptyIcon={Globe}
- filteredEmptyTitle="No sites found"
- filteredEmptyDescription="Try adjusting your search or filter"
- >
- {/* Import Site Modal */}
- <Modal
- open={showImportModal}
- onClose={() => !importLoading && setShowImportModal(false)}
- title="Import WordPress Site"
- size="lg"
- >
- <div className="modal-body">
- <div className="install-warning">
- <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>
- <div>
- <strong>Imports a database dump into a new stack:</strong>
- <ul>
- <li>Provisions a fresh WordPress + MySQL container</li>
- <li>Loads your .sql / .sql.gz dump</li>
- <li>Rewrites the site URL to this server</li>
- </ul>
- </div>
- </div>
-
- <div className="form-group">
- <Label>Site Name <span className="required">*</span></Label>
- <Input
- type="text"
- value={importForm.name}
- onChange={e => setImportForm({ ...importForm, name: e.target.value })}
- placeholder="my-imported-site"
- disabled={importLoading}
- />
- <span className="form-hint">Used as the Docker project name. Letters, numbers, and hyphens only.</span>
- </div>
-
- <div className="form-group">
- <Label>Original Site URL <span className="required">*</span></Label>
- <Input
- type="text"
- value={importForm.oldUrl}
- onChange={e => setImportForm({ ...importForm, oldUrl: e.target.value })}
- placeholder="https://old-site.com"
- disabled={importLoading}
- />
- <span className="form-hint">The live URL in your dump; we rewrite it to the localhost address on this server.</span>
- </div>
-
- <div className="form-group">
- <Label>Admin Email</Label>
- <Input
- type="email"
- value={importForm.adminEmail}
- onChange={e => setImportForm({ ...importForm, adminEmail: e.target.value })}
- placeholder="[email protected]"
- disabled={importLoading}
- />
- </div>
-
- <div className="form-group">
- <Label>Database Dump <span className="required">*</span></Label>
- <input
- type="file"
- accept=".sql,.gz,.sql.gz"
- disabled={importLoading}
- onChange={e => setImportFile(e.target.files?.[0] || null)}
- />
- <span className="form-hint">Export via phpMyAdmin or the wp db export command. .sql.gz is supported and recommended (100MB upload limit).</span>
- </div>
-
- <div className="form-group">
- <Label>wp-content archive (optional)</Label>
- <input
- type="file"
- accept=".zip"
- disabled={importLoading}
- onChange={e => setWpContentFile(e.target.files?.[0] || null)}
- />
- <span className="form-hint">A .zip of wp-content (plugins/themes/uploads) or the full site. Copied into the new container after the database import. Leave empty to import the database only.</span>
- </div>
- </div>
- <div className="modal-footer">
- <Button variant="outline" onClick={() => setShowImportModal(false)} disabled={importLoading}>
- Cancel
- </Button>
- <Button onClick={handleImport} disabled={importLoading || !importForm.name || !importForm.oldUrl || !importFile}>
- {importLoading ? <><Spinner size="sm" /> Importing...</> : 'Import Site'}
- </Button>
- </div>
- </Modal>
-
- {/* Create Site — the same drawer shape the templates catalog uses, so
- creating a WordPress site and deploying a template feel like one
- product rather than two. */}
- <Drawer
- flush
- open={showCreateModal}
- onOpenChange={(next) => { if (!next && !createLoading) setShowCreateModal(false); }}
- title="Create WordPress Site"
- subtitle="WordPress + MySQL on an isolated Docker network"
- icon={<Globe size={20} />}
- width={560}
- className="sk-formdrawer"
- >
- <div className="sk-formdrawer__form">
- <div className="sk-formdrawer__body">
- <div className="sk-formdrawer__callout">
- <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>
- <div>
- <strong>This will create:</strong>
- <ul>
- <li>WordPress 6.4 (Apache) container</li>
- <li>MySQL 8.0 database container</li>
- <li>Isolated Docker network</li>
- </ul>
- </div>
- </div>
-
- <div className="sk-formdrawer__field">
- <Label>
- Site Name <span className="required">*</span>
- </Label>
- <Input
- type="text"
- value={createForm.name}
- onChange={e => setCreateForm({ ...createForm, name: e.target.value })}
- placeholder="my-wordpress-site"
- disabled={createLoading}
- />
- <span className="sk-formdrawer__hint">Used as the Docker project name. Letters, numbers, and hyphens only.</span>
- </div>
-
- {baseDomains.length > 0 ? (
- <div className="sk-formdrawer__field">
- <Label>Publish under</Label>
- <select
- value={createForm.baseDomain}
- onChange={e => setCreateForm({ ...createForm, baseDomain: e.target.value })}
- disabled={createLoading}
- >
- {baseDomains.map(b => (
- <option key={b.domain} value={b.domain}>
- {b.domain}{b.is_default ? ' (default)' : ''}{b.https_enabled ? ' — HTTPS' : ''}
- </option>
- ))}
- </select>
- <span className="sk-formdrawer__hint">
- {createForm.name
- ? <>The site will be live at <code>{slugifyPreview(createForm.name)}.{createForm.baseDomain}</code>.</>
- : <>Which base domain to publish this site under.</>}
- </span>
- </div>
- ) : (
- <div className="sk-formdrawer__field">
- <Label>Publish under</Label>
- <span className="sk-formdrawer__hint">No base domain configured — the site will be reachable at <code>localhost:&lt;port&gt;</code>. Add a managed-sites base domain in Settings to publish it at a real subdomain.</span>
- </div>
- )}
-
- <div className="sk-formdrawer__field">
- <Label>Custom Domain</Label>
- <Input
- type="text"
- value={createForm.domain}
- onChange={e => setCreateForm({ ...createForm, domain: e.target.value })}
- placeholder="example.com"
- disabled={createLoading}
- />
- <span className="sk-formdrawer__hint">Optional. Overrides the base domain above — the site is created and migrated to this domain.</span>
- </div>
-
- <div className="sk-formdrawer__field">
- <Label>Admin Email</Label>
- <Input
- type="email"
- value={createForm.adminEmail}
- onChange={e => setCreateForm({ ...createForm, adminEmail: e.target.value })}
- placeholder="[email protected]"
- disabled={createLoading}
- />
- </div>
-
- <div className="sk-formdrawer__field">
- <Label>PHP Version</Label>
- <select
- value={createForm.phpVersion}
- onChange={e => setCreateForm({ ...createForm, phpVersion: e.target.value })}
- disabled={createLoading}
- >
- <option value="">Default (latest for WordPress 6.4)</option>
- <option value="8.1">PHP 8.1</option>
- <option value="8.2">PHP 8.2</option>
- <option value="8.3">PHP 8.3</option>
- </select>
- <span className="sk-formdrawer__hint">Baked into the container image at creation. Changeable later from the PHP tab.</span>
- </div>
-
- <div className="sk-formdrawer__field">
- <label className="checkbox-label">
- <input
- type="checkbox"
- checked={createForm.enablePageCache}
- onChange={e => setCreateForm({ ...createForm, enablePageCache: e.target.checked })}
- disabled={createLoading}
- />
- Enable full-page cache
- </label>
- <span className="sk-formdrawer__hint">Disk page cache with WordPress-aware skip rules (admin, login, cart, checkout).</span>
- </div>
-
- <div className="sk-formdrawer__field">
- <label className="checkbox-label">
- <input
- type="checkbox"
- checked={createForm.enableObjectCache}
- onChange={e => setCreateForm({ ...createForm, enableObjectCache: e.target.checked })}
- disabled={createLoading}
- />
- Enable Redis object cache
- </label>
- <span className="sk-formdrawer__hint">Uses the bundled Redis container with the redis-cache drop-in.</span>
- </div>
- </div>
- <div className="sk-formdrawer__foot">
- <Button
- variant="outline"
- onClick={() => setShowCreateModal(false)}
- disabled={createLoading}
- >
- Cancel
- </Button>
- <Button
- onClick={handleCreate}
- disabled={createLoading || !createForm.name}
- >
- {createLoading ? <><Spinner size="sm" /> Creating...</> : 'Create Site'}
- </Button>
- </div>
- </div>
- </Drawer>
- </ResourceListPage>
- );
-}
-
-export default WordPress;
diff --git a/frontend/src/plugins/serverkit-wordpress/pages/WordPressDetail.jsx b/frontend/src/plugins/serverkit-wordpress/pages/WordPressDetail.jsx
deleted file mode 100644
index c2781bdb..00000000
--- a/frontend/src/plugins/serverkit-wordpress/pages/WordPressDetail.jsx
+++ /dev/null
@@ -1,469 +0,0 @@
-import { useState, useEffect } from 'react';
-import { useParams, useNavigate, Link } from 'react-router-dom';
-import { Settings, Database, GitBranch, Package, Palette, FolderOpen, FileText, Lock, Activity, Globe, BarChart3, LayoutDashboard, Layers } from 'lucide-react';
-import { useTabParam } from 'serverkit-sdk';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import { useLogsDrawer } from '@/contexts/LogsDrawerContext';
-import ChangeUrlModal from '../components/wordpress/ChangeUrlModal';
-import AttachDomainModal from '../components/wordpress/AttachDomainModal';
-import { Pill, EnvTag, PageTopbar } from 'serverkit-sdk';
-import { ErrorBoundary } from '@/components/ErrorBoundary';
-import { EmptyState } from 'serverkit-sdk';
-import PluginSlot from '@/components/PluginSlot';
-import { SkeletonBoundary } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import {
- DetailPageSkeleton,
- EnvSwitcher,
- SSLAlert,
- envTagLabel,
-} from '../components/wordpress/detail/wpDetailShared';
-import OverviewTab from '../components/wordpress/detail/OverviewTab';
-import EnvironmentsTab from '../components/wordpress/detail/EnvironmentsTab';
-import DatabaseTab from '../components/wordpress/detail/DatabaseTab';
-import PluginsTab from '../components/wordpress/detail/PluginsTab';
-import ThemesTab from '../components/wordpress/detail/ThemesTab';
-import GitTab from '../components/wordpress/detail/GitTab';
-import BackupsTab from '../components/wordpress/detail/BackupsTab';
-import UptimeTab from '../components/wordpress/detail/UptimeTab';
-import AnalyticsTab from '../components/wordpress/detail/AnalyticsTab';
-import VulnerabilitiesTab from '../components/wordpress/detail/VulnerabilitiesTab';
-import SecurityTab from '../components/wordpress/detail/SecurityTab';
-import UpdatesTab from '../components/wordpress/detail/UpdatesTab';
-import PhpTab from '../components/wordpress/detail/PhpTab';
-import ReportsTab from '../components/wordpress/detail/ReportsTab';
-import SettingsTab from '../components/wordpress/detail/SettingsTab';
-
-// 'php' and 'updates' no longer have their own top-level tab — they live inside
-// the Settings tab's left nav — but stay valid so existing deep links still work.
-const VALID_TABS = ['overview', 'environments', 'database', 'plugins', 'themes', 'git', 'backups', 'uptime', 'analytics', 'vulnerabilities', 'security', 'updates', 'php', 'reports', 'settings'];
-
-const WordPressDetail = () => {
- const { id } = useParams();
- const navigate = useNavigate();
- const toast = useToast();
- const { openDrawer } = useLogsDrawer();
- const [site, setSite] = useState(null);
- const [loading, setLoading] = useState(true);
- const [activeTab, setActiveTab] = useTabParam(`/wordpress/${id}`, VALID_TABS);
- const [autoLoggingIn, setAutoLoggingIn] = useState(false);
- const [showCloneModal, setShowCloneModal] = useState(false);
- const [showChangeUrl, setShowChangeUrl] = useState(false);
- const [showAddDomain, setShowAddDomain] = useState(false);
- const [cloning, setCloning] = useState(false);
- const [cloneName, setCloneName] = useState('');
- const [clonedCreds, setClonedCreds] = useState(null);
- const [gitStatus, setGitStatus] = useState(null);
-
- useEffect(() => {
- // Show the skeleton again when navigating between environment site ids
- // (env switcher / "Open new site") so stale data never renders.
- setLoading(true);
- loadSite();
- }, [id]);
-
- useEffect(() => {
- // Load Git connection summary so we can surface a repo pill in the header,
- // matching the Service detail page's "Connect a repository" affordance.
- if (!id) return;
- wordpressApi.getGitStatus(id)
- .then(setGitStatus)
- .catch(() => setGitStatus(null));
- }, [id]);
-
- async function loadSite() {
- try {
- const data = await wordpressApi.getSite(id);
- setSite(data.site || data);
- } catch (err) {
- console.error('Failed to load site:', err);
- toast.error('Failed to load WordPress site');
- } finally {
- setLoading(false);
- }
- }
-
- async function handleClone() {
- if (!cloneName.trim()) {
- toast.error('New site name is required');
- return;
- }
- setCloning(true);
- toast.info('Cloning site... this spins up a new stack and may take a minute.', { duration: 6000 });
- try {
- const res = await wordpressApi.cloneSite(site.id, { name: cloneName.trim() });
- if (res.success) {
- setShowCloneModal(false);
- setCloneName('');
- if (res.admin_password) {
- setClonedCreds({ user: res.admin_user || 'admin', password: res.admin_password, id: res.site?.id });
- }
- toast.success('Site cloned successfully');
- } else {
- toast.error(res.error || 'Failed to clone site');
- }
- } catch (err) {
- toast.error(err.message || 'Failed to clone site');
- } finally {
- setCloning(false);
- }
- }
-
- async function handleAutoLogin() {
- setAutoLoggingIn(true);
- toast.info('Creating one-time login link...', { duration: 3000 });
- try {
- const res = await wordpressApi.autoLogin(site.id);
- if (res && res.url) {
- window.open(res.url, '_blank', 'noopener,noreferrer');
- } else {
- toast.error('No login URL returned');
- }
- } catch (err) {
- toast.error(err.message || 'Failed to create login link');
- } finally {
- setAutoLoggingIn(false);
- }
- }
-
- if (loading) {
- return <SkeletonBoundary loading skeleton={<DetailPageSkeleton />} />;
- }
-
- if (!site) {
- return (
- <EmptyState
- icon={Globe}
- title="Site not found"
- description="This WordPress site does not exist or has been removed."
- action={<Button onClick={() => navigate('/wordpress')}>Back to WordPress Sites</Button>}
- />
- );
- }
-
- const isRunning = site.status === 'running';
-
- // Environment switcher options from data already in the payload:
- // production sites carry `environments`; child envs carry `production_site_id`.
- let envOptions = null;
- if (site.is_production && (site.environments || []).length > 0) {
- envOptions = [
- { id: site.id, name: site.name, type: 'production', url: site.url, current: true },
- ...site.environments.map(e => ({
- id: e.id,
- name: e.name || e.environment_type || `Environment ${e.id}`,
- type: e.environment_type || 'development',
- url: e.url,
- current: false,
- })),
- ];
- } else if (!site.is_production && site.production_site_id) {
- envOptions = [
- { id: site.production_site_id, name: 'Production', type: 'production', current: false },
- { id: site.id, name: site.name, type: site.environment_type || 'development', url: site.url, current: true },
- ];
- }
-
- return (
- <div className="app-detail-page app-detail-page--wide wp-detail-page">
- {/* One-time cloned-admin credentials banner */}
- {clonedCreds && (
- <div className="wp-creds-banner">
- <div className="wp-creds-banner-text">
- <strong>New site created — save these admin credentials, shown only once.</strong>
- <span>Username: <code>{clonedCreds.user}</code></span>
- <span>Password: <code>{clonedCreds.password}</code></span>
- {clonedCreds.id && (
- <Button variant="ghost" onClick={() => navigate(`/wordpress/${clonedCreds.id}`)}>Open new site</Button>
- )}
- </div>
- <Button variant="ghost" onClick={() => setClonedCreds(null)}>Dismiss</Button>
- </div>
- )}
-
- {/* Top bar — the canonical PageTopbar (.sk-topbar): the SAME chrome as
- the WordPress LIST page and every other page, so the top menu is
- consistent. Breadcrumb in the title slot, actions on the right. */}
- <PageTopbar
- className="wp-detail-topbar"
- icon={<Globe size={18} />}
- title={(
- <span className="wp-crumbs">
- <Link to="/wordpress">WordPress</Link>
- <span className="wp-crumbs__sep">/</span>
- <span className="wp-crumbs__cur">{site.name}</span>
- </span>
- )}
- actions={(
- <>
- <Button
- variant="ghost"
- onClick={() => navigate(`/files?path=${encodeURIComponent(site.application?.root_path || '/')}`)}
- disabled={!site.application?.root_path}
- title={site.application?.root_path ? `Open ${site.application.root_path} in the File Manager` : 'No root path configured for this site'}
- >
- <FolderOpen size={16} />
- Open Files
- </Button>
- {site.db_name && (
- <Button
- variant="ghost"
- onClick={() => navigate(`/databases/mysql?db=${encodeURIComponent(site.db_name)}`)}
- title={`Open ${site.db_name} in the Database manager`}
- >
- <Database size={16} />
- Open Database
- </Button>
- )}
- <Button
- variant="ghost"
- onClick={() => openDrawer({ name: site.name, containerId: site.application_id, appType: 'docker' })}
- title="View live container logs"
- >
- <FileText size={16} />
- View Logs
- </Button>
- {site.url && (
- <Button variant="ghost" asChild>
- <a
- href={`${site.url}/wp-admin`}
- target="_blank"
- rel="noopener noreferrer"
- >
- <Settings size={16} />
- Dashboard
- </a>
- </Button>
- )}
- <Button
- variant="default"
- onClick={handleAutoLogin}
- disabled={autoLoggingIn}
- title="Open wp-admin logged in, no password (one-time link)"
- >
- <Lock size={16} />
- {autoLoggingIn ? 'Signing in...' : 'Auto Login'}
- </Button>
- </>
- )}
- />
-
- {/* Everything below the full-bleed top bar is padded by .app-detail-body
- (the top bar itself spans edge-to-edge like the list page). */}
- <div className="app-detail-body">
- {/* Identity — icon + name + status + environment + version (no actions). */}
- <div className="app-detail-header">
- <div className="app-detail-icon wp-icon">
- <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" strokeWidth="2">
- <circle cx="12" cy="12" r="8" />
- </svg>
- <span className={`wp-head-dot ${isRunning ? 'running' : 'stopped'}`} />
- </div>
- <div className="app-detail-title-block">
- <h1>
- {site.name}
- <Pill kind={isRunning ? 'green' : 'gray'}>{isRunning ? 'Running' : 'Stopped'}</Pill>
- {site.is_production ? (
- <EnvTag env="PROD" />
- ) : site.production_site_id ? (
- <EnvTag env={envTagLabel(site.environment_type)} />
- ) : null}
- {envOptions && envOptions.length > 1 && (
- <EnvSwitcher options={envOptions} onSelect={(envId) => navigate(`/wordpress/${envId}`)} />
- )}
- <SSLAlert site={site} />
- </h1>
- <div className="app-detail-subtitle">
- <span>WordPress {site.wp_version || '—'}</span>
- {site.application?.php_version && (
- <>
- <span className="separator">·</span>
- <span>PHP {site.application.php_version}</span>
- </>
- )}
- {site.url && (
- <>
- <span className="separator">·</span>
- <a href={site.url} target="_blank" rel="noopener noreferrer">{site.url}</a>
- </>
- )}
- {site.multisite && (
- <>
- <span className="separator">·</span>
- <span>multisite</span>
- </>
- )}
- </div>
- </div>
- </div>
-
- {/* Repo Connection Pill — same prominent affordance as the service detail page. */}
- <div className="wp-detail__repo-bar">
- {gitStatus?.connected ? (
- <div
- className="wp-detail__repo-pill"
- onClick={() => navigate(`/wordpress/${id}/settings/git`)}
- title="Repository connected — open Git settings"
- >
- <GitBranch size={14} />
- <span className="wp-detail__repo-url">{extractRepoDisplay(gitStatus.repo_url)}</span>
- <span className="wp-detail__repo-arrow">→</span>
- <span className="wp-detail__repo-branch">{gitStatus.branch || 'main'}</span>
- {gitStatus.auto_deploy && (
- <span className="wp-detail__auto-deploy-badge">Auto</span>
- )}
- </div>
- ) : (
- <button type="button"
- className="wp-detail__connect-repo"
- onClick={() => navigate(`/wordpress/${id}/settings/git`)}
- >
- <GitBranch size={14} />
- Connect a repository
- </button>
- )}
- </div>
-
- {/* Tabs */}
- <div className="app-detail-tabs">
- <div
- className={`app-detail-tab ${activeTab === 'overview' ? 'active' : ''}`}
- onClick={() => setActiveTab('overview')}
- >
- <LayoutDashboard size={14} /> Overview
- </div>
- <div
- className={`app-detail-tab ${activeTab === 'environments' ? 'active' : ''}`}
- onClick={() => setActiveTab('environments')}
- >
- <Layers size={14} /> Env
- </div>
- <div
- className={`app-detail-tab ${activeTab === 'database' ? 'active' : ''}`}
- onClick={() => setActiveTab('database')}
- >
- <Database size={14} /> Database
- </div>
- <div
- className={`app-detail-tab ${activeTab === 'plugins' ? 'active' : ''}`}
- onClick={() => setActiveTab('plugins')}
- >
- <Package size={14} /> Plugins
- </div>
- <div
- className={`app-detail-tab ${activeTab === 'themes' ? 'active' : ''}`}
- onClick={() => setActiveTab('themes')}
- >
- <Palette size={14} /> Themes
- </div>
- <div
- className={`app-detail-tab ${activeTab === 'uptime' ? 'active' : ''}`}
- onClick={() => setActiveTab('uptime')}
- >
- <Activity size={14} /> Uptime
- </div>
- <div
- className={`app-detail-tab ${activeTab === 'analytics' ? 'active' : ''}`}
- onClick={() => setActiveTab('analytics')}
- >
- <BarChart3 size={14} /> Analytics
- </div>
- <div
- className={`app-detail-tab app-detail-tab--end ${activeTab === 'settings' ? 'active' : ''}`}
- onClick={() => setActiveTab('settings')}
- >
- <Settings size={14} /> Settings
- </div>
- </div>
-
- {showChangeUrl && (
- <ChangeUrlModal
- site={site}
- onClose={() => setShowChangeUrl(false)}
- onChanged={loadSite}
- />
- )}
-
- {showAddDomain && (
- <AttachDomainModal
- site={site}
- onClose={() => setShowAddDomain(false)}
- onChanged={loadSite}
- />
- )}
-
- {/* Clone Site Modal */}
- <Modal open={showCloneModal} onClose={() => !cloning && setShowCloneModal(false)} title="Clone Site">
- <form onSubmit={(e) => { e.preventDefault(); handleClone(); }}>
- <p className="hint">Creates a brand-new independent WordPress site (its own Docker stack and database) seeded from <strong>{site.name}</strong>, with fresh admin credentials shown once.</p>
- <div className="form-group">
- <Label>New Site Name *</Label>
- <Input
- type="text"
- value={cloneName}
- onChange={(e) => setCloneName(e.target.value)}
- placeholder={`${site.name}-copy`}
- autoFocus
- disabled={cloning}
- />
- </div>
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={() => setShowCloneModal(false)} disabled={cloning}>Cancel</Button>
- <Button type="submit" disabled={cloning || !cloneName.trim()}>{cloning ? 'Cloning...' : 'Clone Site'}</Button>
- </div>
- </form>
- </Modal>
-
- {/* Tab Content */}
- <div className="app-detail-content">
- <ErrorBoundary key={activeTab} onRetry={loadSite}>
- {activeTab === 'overview' && <OverviewTab site={site} onUpdate={loadSite} />}
- {activeTab === 'environments' && <EnvironmentsTab siteId={site.id} site={site} onUpdate={loadSite} />}
- {activeTab === 'database' && <DatabaseTab siteId={site.id} site={site} />}
- {activeTab === 'plugins' && <PluginsTab siteId={site.id} />}
- {activeTab === 'themes' && <ThemesTab siteId={site.id} />}
- {activeTab === 'git' && <GitTab siteId={site.id} site={site} onUpdate={loadSite} />}
- {activeTab === 'backups' && <BackupsTab siteId={site.id} site={site} />}
- {activeTab === 'uptime' && <UptimeTab siteId={site.id} />}
- {activeTab === 'analytics' && <AnalyticsTab siteId={site.id} />}
- {activeTab === 'vulnerabilities' && <VulnerabilitiesTab siteId={site.id} />}
- {activeTab === 'security' && <SecurityTab siteId={site.id} />}
- {activeTab === 'updates' && <UpdatesTab siteId={site.id} />}
- {activeTab === 'php' && <PhpTab siteId={site.id} />}
- {activeTab === 'reports' && <ReportsTab siteId={site.id} />}
- {activeTab === 'settings' && (
- <SettingsTab
- siteId={site.id}
- site={site}
- onUpdate={loadSite}
- onAddDomain={() => setShowAddDomain(true)}
- onChangeUrl={() => setShowChangeUrl(true)}
- onClone={() => setShowCloneModal(true)}
- />
- )}
- </ErrorBoundary>
- </div>
-
- {/* Extension slot: widgets contributed to the WordPress detail page */}
- <PluginSlot name="wordpress.detail.panel" context={{ site }} />
- </div>
- </div>
- );
-};
-
-function extractRepoDisplay(url) {
- if (!url) return '';
- try {
- const cleaned = url.replace(/\.git$/, '').replace(/^https?:\/\/[^@]+@/, 'https://');
- const parts = cleaned.split(/[/:]/).filter(Boolean);
- return parts.slice(-2).join('/');
- } catch {
- return url;
- }
-}
-
-export default WordPressDetail;
diff --git a/frontend/src/plugins/serverkit-wordpress/pages/WordPressPluginLibrary.jsx b/frontend/src/plugins/serverkit-wordpress/pages/WordPressPluginLibrary.jsx
deleted file mode 100644
index 4ddd4a5b..00000000
--- a/frontend/src/plugins/serverkit-wordpress/pages/WordPressPluginLibrary.jsx
+++ /dev/null
@@ -1,353 +0,0 @@
-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 'serverkit-sdk';
-import { useAuth } from 'serverkit-sdk';
-import { EmptyState } from 'serverkit-sdk';
-import { Spinner } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Pill, ServiceTile } from 'serverkit-sdk';
-import { useTopbarActions } from 'serverkit-sdk';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-import { Switch } from 'serverkit-sdk';
-
-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/plugins/serverkit-wordpress/pages/WordPressProject.jsx b/frontend/src/plugins/serverkit-wordpress/pages/WordPressProject.jsx
deleted file mode 100644
index 39cf9169..00000000
--- a/frontend/src/plugins/serverkit-wordpress/pages/WordPressProject.jsx
+++ /dev/null
@@ -1,1042 +0,0 @@
-import { useState, useEffect, useCallback, useRef } from 'react';
-import { useParams, useNavigate, Link } from 'react-router-dom';
-import { Plus, ExternalLink, RefreshCw, GitBranch, Search, Shield, Activity, Settings, ArrowRight, RotateCcw } from 'lucide-react';
-import { useTabParam } from 'serverkit-sdk';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import {
- PipelineView,
- PromoteModal,
- SyncModal,
- ActivityFeed,
- ContainerLogs,
- CompareView,
- SanitizationProfileForm,
- ResourceLimitsModal,
- BasicAuthModal,
- WpCliTerminal,
- HealthStatusPanel,
- AutoSyncScheduleModal,
- BulkActionsBar,
-} from '../components/wordpress';
-import { ConfirmDialog } from 'serverkit-sdk';
-import { Modal } from 'serverkit-sdk';
-import { Spinner } from 'serverkit-sdk';
-import { EmptyState } from 'serverkit-sdk';
-import { FolderGit2 } from 'lucide-react';
-import { io } from 'socket.io-client';
-import { Button } from 'serverkit-sdk';
-import { Input } from 'serverkit-sdk';
-import { Label } from 'serverkit-sdk';
-
-const SOCKET_URL = import.meta.env.VITE_API_URL?.replace('/api/v1', '') || window.location.origin;
-
-const VALID_TABS = ['pipeline', 'activity', 'health'];
-
-const WordPressProject = () => {
- const { id } = useParams();
- const navigate = useNavigate();
- const toast = useToast();
-
- const [pipeline, setPipeline] = useState(null);
- const [loading, setLoading] = useState(true);
- const [activeTab, setActiveTab] = useTabParam(`/wordpress/pipelines/${id}`, VALID_TABS);
- const [showCreateEnvModal, setShowCreateEnvModal] = useState(false);
- const [promoteModal, setPromoteModal] = useState(null);
- const [syncModal, setSyncModal] = useState(null);
- const [logsPanel, setLogsPanel] = useState(null);
- const [confirmDialog, setConfirmDialog] = useState(null);
- const [operationInProgress, setOperationInProgress] = useState(null);
- const [operationProgress, setOperationProgress] = useState(null);
- const [compareModal, setCompareModal] = useState(null);
- const [showSanitizationProfiles, setShowSanitizationProfiles] = useState(false);
-
- // Phase 7 state
- const [resourceLimitsModal, setResourceLimitsModal] = useState(null);
- const [basicAuthModal, setBasicAuthModal] = useState(null);
- const [wpCliModal, setWpCliModal] = useState(null);
- const [autoSyncModal, setAutoSyncModal] = useState(null);
- const [healthData, setHealthData] = useState({});
- const [diskUsageData, setDiskUsageData] = useState({});
- const [bulkSelected, setBulkSelected] = useState([]);
-
- const socketRef = useRef(null);
-
- useEffect(() => {
- loadPipeline();
- connectSocket();
-
- return () => {
- if (socketRef.current) {
- socketRef.current.emit('unsubscribe_pipeline', { project_id: Number(id) });
- socketRef.current.disconnect();
- }
- };
- }, [id]);
-
- function connectSocket() {
- const token = localStorage.getItem('access_token');
- if (!token) return;
-
- const socket = io(SOCKET_URL, {
- auth: { token },
- transports: ['websocket', 'polling']
- });
-
- socket.on('connect', () => {
- socket.emit('subscribe_pipeline', { project_id: Number(id) });
- });
-
- socket.on('pipeline_event', (data) => {
- handlePipelineEvent(data);
- });
-
- socketRef.current = socket;
- }
-
- function handlePipelineEvent(data) {
- const { event, data: eventData } = data;
-
- switch (event) {
- case 'environment_created':
- case 'environment_deleted':
- case 'promotion_completed':
- case 'sync_completed':
- loadPipeline();
- if (eventData.success) {
- toast.success(eventData.message || `${event.replace(/_/g, ' ')} successfully`);
- }
- setOperationInProgress(null);
- break;
- case 'environment_create_failed':
- case 'environment_delete_failed':
- case 'promotion_failed':
- case 'sync_failed':
- loadPipeline();
- toast.error(eventData.message || `${event.replace(/_/g, ' ')}`);
- setOperationInProgress(null);
- break;
- case 'environment_started':
- case 'environment_stopped':
- case 'environment_restarted':
- case 'environment_locked':
- case 'environment_unlocked':
- loadPipeline();
- break;
- case 'promotion_started':
- case 'sync_started':
- case 'environment_creating':
- setOperationInProgress(event);
- setOperationProgress(null);
- break;
- case 'operation_progress':
- setOperationProgress(eventData);
- break;
- case 'bulk_operation_completed':
- loadPipeline();
- toast.success('Bulk operation completed');
- break;
- default:
- break;
- }
- }
-
- async function loadPipeline() {
- try {
- const data = await wordpressApi.getProjectPipeline(id);
- setPipeline(data);
- } catch (err) {
- console.error('Failed to load pipeline:', err);
- toast.error('Failed to load project pipeline');
- } finally {
- setLoading(false);
- }
- }
-
- const handlePromote = useCallback((sourceEnv, targetEnv) => {
- setPromoteModal({ sourceEnv, targetEnv });
- }, []);
-
- const handleDoPromote = useCallback(async (config) => {
- try {
- const res = await wordpressApi.promoteEnvironment(id, config);
- setPromoteModal(null);
- // A promotion is a deployment now: open its console, where the
- // steps, live log and retry live.
- if (res?.job_id) navigate(`/deployments/${res.job_id}`);
- else toast.info('Promotion queued');
- } catch (err) {
- toast.error(err.message || 'Promotion failed');
- }
- }, [id, navigate, toast]);
-
- const handleSync = useCallback((env) => {
- setSyncModal({ environment: env });
- }, []);
-
- const handleDoSync = useCallback(async (config) => {
- const env = syncModal.environment;
- toast.info('Starting sync...', { duration: 3000 });
- try {
- await wordpressApi.syncProjectEnvironment(id, env.id, config);
- setSyncModal(null);
- } catch (err) {
- toast.error(err.message || 'Sync failed');
- }
- }, [id, syncModal, toast]);
-
- const handleStart = useCallback(async (env) => {
- try {
- await wordpressApi.startEnvironment(id, env.id);
- toast.success('Environment started');
- loadPipeline();
- } catch (err) {
- toast.error(err.message || 'Failed to start environment');
- }
- }, [id, toast]);
-
- const handleStop = useCallback(async (env) => {
- setConfirmDialog({
- title: 'Stop Environment',
- message: `Stop the ${env.environment_type || ''} environment "${env.name}"?`,
- confirmText: 'Stop',
- variant: 'warning',
- onConfirm: async () => {
- try {
- await wordpressApi.stopEnvironment(id, env.id);
- toast.success('Environment stopped');
- loadPipeline();
- } catch (err) {
- toast.error(err.message || 'Failed to stop environment');
- } finally {
- setConfirmDialog(null);
- }
- },
- onCancel: () => setConfirmDialog(null)
- });
- }, [id, toast]);
-
- const handleRollback = useCallback((promotion) => {
- setConfirmDialog({
- title: 'Roll Back Promotion',
- message: `Restore the pre-promotion snapshot for "${promotion.target_site?.name || 'target environment'}"? This overwrites the target environment's current database with the snapshot taken just before promotion #${promotion.id}.`,
- confirmText: 'Roll Back',
- variant: 'danger',
- onConfirm: async () => {
- toast.info('Rolling back promotion...', { duration: 4000 });
- try {
- await wordpressApi.rollbackPromotion(id, promotion.id);
- toast.success('Promotion rolled back');
- loadPipeline();
- } catch (err) {
- toast.error(err.message || 'Rollback failed');
- } finally {
- setConfirmDialog(null);
- }
- },
- onCancel: () => setConfirmDialog(null),
- });
- }, [id, toast]);
-
- const handleRestart = useCallback(async (env) => {
- try {
- await wordpressApi.restartEnvironment(id, env.id);
- toast.success('Environment restarted');
- loadPipeline();
- } catch (err) {
- toast.error(err.message || 'Failed to restart environment');
- }
- }, [id, toast]);
-
- const handleDelete = useCallback((env) => {
- setConfirmDialog({
- title: 'Delete Environment',
- message: `Are you sure you want to delete "${env.name}"? This will remove all containers, files, and database for this environment.`,
- confirmText: 'Delete Environment',
- variant: 'danger',
- onConfirm: async () => {
- try {
- await wordpressApi.deleteProjectEnvironment(id, env.id);
- toast.success('Environment deleted');
- loadPipeline();
- } catch (err) {
- toast.error(err.message || 'Failed to delete environment');
- } finally {
- setConfirmDialog(null);
- }
- },
- onCancel: () => setConfirmDialog(null)
- });
- }, [id, toast]);
-
- const handleLock = useCallback(async (env) => {
- try {
- await wordpressApi.lockEnvironment(id, env.id, {
- reason: 'Manually locked',
- duration_minutes: 60
- });
- toast.success('Environment locked');
- loadPipeline();
- } catch (err) {
- toast.error(err.message || 'Failed to lock environment');
- }
- }, [id, toast]);
-
- const handleUnlock = useCallback(async (env) => {
- try {
- await wordpressApi.unlockEnvironment(id, env.id);
- toast.success('Environment unlocked');
- loadPipeline();
- } catch (err) {
- toast.error(err.message || 'Failed to unlock environment');
- }
- }, [id, toast]);
-
- const handleViewLogs = useCallback((env) => {
- setLogsPanel({ envId: env.id });
- }, []);
-
- const handleCompare = useCallback((envA, envB) => {
- setCompareModal({ envA, envB });
- }, []);
-
- // Phase 7 handlers
- const handleResourceLimits = useCallback((env) => {
- setResourceLimitsModal({ environment: env, currentLimits: env.resource_limits });
- }, []);
-
- const handleApplyResourceLimits = useCallback(async (limits) => {
- const env = resourceLimitsModal.environment;
- try {
- await wordpressApi.updateResourceLimits(id, env.id, limits);
- toast.success('Resource limits updated, containers restarting');
- setResourceLimitsModal(null);
- loadPipeline();
- } catch (err) {
- toast.error(err.message || 'Failed to update resource limits');
- }
- }, [id, resourceLimitsModal, toast]);
-
- const handleBasicAuth = useCallback((env) => {
- setBasicAuthModal({ environment: env });
- }, []);
-
- const handleWpCli = useCallback((env) => {
- setWpCliModal({ environment: env });
- }, []);
-
- const handleAutoSync = useCallback((env) => {
- setAutoSyncModal({ environment: env });
- }, []);
-
- const handleHealthCheck = useCallback(async (env) => {
- try {
- const data = await wordpressApi.getEnvironmentHealth(id, env.id);
- if (data.success) {
- setHealthData(prev => ({ ...prev, [env.id]: data }));
- toast.info(`${env.name}: ${data.overall_status}`);
- }
- } catch (err) {
- toast.error('Health check failed');
- }
- }, [id, toast]);
-
- const handleBulkToggle = useCallback((envId) => {
- setBulkSelected(prev =>
- prev.includes(envId)
- ? prev.filter(id => id !== envId)
- : [...prev, envId]
- );
- }, []);
-
- const handleBulkExecute = useCallback(async (action, envIds) => {
- try {
- await wordpressApi.executeBulkOperation(id, [{ action, env_ids: envIds }]);
- toast.success(`Bulk ${action} completed`);
- setBulkSelected([]);
- loadPipeline();
- } catch (err) {
- toast.error(err.message || `Bulk ${action} failed`);
- }
- }, [id, toast]);
-
- // Load health and disk usage data on pipeline load
- useEffect(() => {
- if (pipeline) {
- loadHealthData();
- loadDiskUsageData();
- }
- }, [pipeline]);
-
- async function loadHealthData() {
- try {
- const data = await wordpressApi.getProjectHealth(id);
- if (data.success) {
- setHealthData(data.environments || {});
- }
- } catch {
- // Health data is optional
- }
- }
-
- async function loadDiskUsageData() {
- try {
- const data = await wordpressApi.getProjectDiskUsage(id);
- if (data.success) {
- setDiskUsageData(data.environments || {});
- }
- } catch {
- // Disk usage data is optional
- }
- }
-
- const handleCreateEnvironment = useCallback(async (data) => {
- toast.info('Creating environment...', { duration: 5000 });
- try {
- await wordpressApi.createProjectEnvironment(id, data);
- setShowCreateEnvModal(false);
- } catch (err) {
- toast.error(err.message || 'Failed to create environment');
- }
- }, [id, toast]);
-
- if (loading) {
- return <EmptyState loading loadingVariant="detail" size="lg" title="Loading project pipeline" />;
- }
-
- if (!pipeline) {
- return (
- <EmptyState
- icon={FolderGit2}
- title="Pipeline not found"
- description="This WordPress pipeline does not exist or has been removed."
- action={<Button onClick={() => navigate('/wordpress/pipelines')}>Back to Pipelines</Button>}
- />
- );
- }
-
- const production = pipeline.production || pipeline;
- const projectName = production.name || 'WordPress Project';
- const projectDomain = production.application?.domains?.[0] || production.url || '';
-
- return (
- <div className="app-detail-page app-detail-page--wide wp-project-page">
- {/* Top Bar */}
- <div className="app-detail-topbar">
- <div className="app-detail-breadcrumbs">
- <Link to="/wordpress/pipelines">Pipelines</Link>
- <span>/</span>
- <span className="current">{projectName}</span>
- </div>
- <div className="app-detail-actions">
- {projectDomain && (
- <Button variant="ghost" asChild>
- <a
- href={projectDomain.startsWith('http') ? projectDomain : `https://${projectDomain}`}
- target="_blank"
- rel="noopener noreferrer"
- >
- <ExternalLink size={16} />
- Visit Site
- </a>
- </Button>
- )}
- <Button
- variant="ghost"
- onClick={() => setShowSanitizationProfiles(true)}
- title="Manage sanitization profiles"
- >
- <Shield size={16} />
- Profiles
- </Button>
- <Button
- onClick={() => setShowCreateEnvModal(true)}
- >
- <Plus size={16} />
- New Environment
- </Button>
- </div>
- </div>
-
- {/* Header */}
- <div className="app-detail-header">
- <div className="app-detail-icon wp-icon">
- <svg viewBox="0 0 24 24" width="28" height="28" fill="currentColor">
- <path d="M12 2C6.486 2 2 6.486 2 12s4.486 10 10 10 10-4.486 10-10S17.514 2 12 2zm0 19.542c-5.261 0-9.542-4.281-9.542-9.542S6.739 2.458 12 2.458 21.542 6.739 21.542 12 17.261 21.542 12 21.542z" />
- </svg>
- </div>
- <div className="app-detail-title-block">
- <h1>
- {projectName}
- <span className={`app-status-badge ${production.status === 'running' ? 'running' : 'stopped'}`}>
- <span className="pulse-dot" />
- {production.status === 'running' ? 'Running' : 'Stopped'}
- </span>
- </h1>
- <div className="app-detail-subtitle">
- {projectDomain && <span className="mono">{projectDomain}</span>}
- {production.wp_version && (
- <>
- <span className="separator">•</span>
- <span>WordPress {production.wp_version}</span>
- </>
- )}
- {pipeline.environments && (
- <>
- <span className="separator">•</span>
- <span>{(pipeline.environments?.length || 0) + 1} environments</span>
- </>
- )}
- </div>
- </div>
- </div>
-
- {/* Tabs */}
- <div className="app-detail-tabs">
- <div
- className={`app-detail-tab ${activeTab === 'pipeline' ? 'active' : ''}`}
- onClick={() => setActiveTab('pipeline')}
- >
- Pipeline
- </div>
- <div
- className={`app-detail-tab ${activeTab === 'activity' ? 'active' : ''}`}
- onClick={() => setActiveTab('activity')}
- >
- Activity
- </div>
- <div
- className={`app-detail-tab ${activeTab === 'health' ? 'active' : ''}`}
- onClick={() => setActiveTab('health')}
- >
- Health
- </div>
- </div>
-
- {/* Tab Content */}
- <div className="app-detail-content">
- {activeTab === 'pipeline' && (
- <div className="pipeline-tab">
- {operationInProgress && (
- <div className="pipeline-operation-banner">
- <Spinner size="sm" />
- <div className="operation-progress-content">
- <span>
- {operationInProgress === 'promotion_started' && 'Promotion in progress...'}
- {operationInProgress === 'sync_started' && 'Sync in progress...'}
- {operationInProgress === 'environment_creating' && 'Creating environment...'}
- </span>
- {operationProgress && (
- <div className="operation-progress">
- <div className="operation-progress-bar">
- <div
- className="operation-progress-fill"
- style={{ width: `${operationProgress.percent || 0}%` }}
- />
- </div>
- <span className="operation-progress-step">
- Step {operationProgress.step}/{operationProgress.total}: {operationProgress.message}
- </span>
- </div>
- )}
- </div>
- </div>
- )}
-
- {bulkSelected.length > 0 && (
- <BulkActionsBar
- selectedIds={bulkSelected}
- environments={[
- ...(pipeline.environments || []),
- pipeline.production
- ].filter(Boolean)}
- prodId={id}
- onClear={() => setBulkSelected([])}
- onExecute={handleBulkExecute}
- api={wordpressApi}
- />
- )}
-
- <PipelineView
- pipeline={pipeline}
- onPromote={handlePromote}
- onSync={handleSync}
- onStart={handleStart}
- onStop={handleStop}
- onRestart={handleRestart}
- onDelete={handleDelete}
- onLock={handleLock}
- onUnlock={handleUnlock}
- onViewLogs={handleViewLogs}
- onCompare={handleCompare}
- onCreateMultidev={() => {
- setShowCreateEnvModal(true);
- }}
- onResourceLimits={handleResourceLimits}
- onBasicAuth={handleBasicAuth}
- onWpCli={handleWpCli}
- onAutoSync={handleAutoSync}
- onHealthCheck={handleHealthCheck}
- operationInProgress={operationInProgress}
- healthData={healthData}
- diskUsageData={diskUsageData}
- bulkSelected={bulkSelected}
- onBulkToggle={handleBulkToggle}
- />
-
- {/* Promotion History (with rollback) */}
- <PromotionHistory projectId={id} onRollback={handleRollback} />
-
- {/* Recent Activity Preview */}
- <div className="pipeline-activity-preview">
- <div className="section-header">
- <h3>Recent Activity</h3>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => setActiveTab('activity')}
- >
- View All
- </Button>
- </div>
- <ActivityFeed projectId={id} limit={5} compact />
- </div>
- </div>
- )}
-
- {activeTab === 'activity' && (
- <div className="activity-tab">
- <div className="section-header">
- <h3>Activity Log</h3>
- <Button variant="ghost" size="sm" onClick={loadPipeline}>
- <RefreshCw size={14} /> Refresh
- </Button>
- </div>
- <ActivityFeed projectId={id} limit={50} />
- </div>
- )}
-
- {activeTab === 'health' && (
- <div className="health-tab">
- <HealthStatusPanel
- projectId={id}
- environments={[
- pipeline.production,
- ...(pipeline.environments || [])
- ].filter(Boolean)}
- api={wordpressApi}
- />
- </div>
- )}
- </div>
-
- {/* Logs Panel */}
- {logsPanel && (
- <div className="pipeline-logs-overlay">
- <ContainerLogs
- projectId={id}
- envId={logsPanel.envId}
- onClose={() => setLogsPanel(null)}
- />
- </div>
- )}
-
- {/* Modals */}
- {promoteModal && (
- <PromoteModal
- sourceEnv={promoteModal.sourceEnv}
- targetEnv={promoteModal.targetEnv}
- onClose={() => setPromoteModal(null)}
- onPromote={handleDoPromote}
- />
- )}
-
- {syncModal && (
- <SyncModal
- environment={syncModal.environment}
- productionName={projectName}
- onClose={() => setSyncModal(null)}
- onSync={handleDoSync}
- />
- )}
-
- {showCreateEnvModal && (
- <CreatePipelineEnvModal
- onClose={() => setShowCreateEnvModal(false)}
- onCreate={handleCreateEnvironment}
- productionDomain={projectDomain}
- existingTypes={(pipeline.environments || []).map(e => e.environment_type)}
- projectId={id}
- />
- )}
-
- {compareModal && (
- <CompareView
- projectId={id}
- envA={compareModal.envA}
- envB={compareModal.envB}
- onClose={() => setCompareModal(null)}
- />
- )}
-
- {showSanitizationProfiles && (
- <SanitizationProfileForm
- onClose={() => setShowSanitizationProfiles(false)}
- onProfilesChange={() => {}}
- />
- )}
-
- {resourceLimitsModal && (
- <ResourceLimitsModal
- environment={resourceLimitsModal.environment}
- currentLimits={resourceLimitsModal.currentLimits}
- onClose={() => setResourceLimitsModal(null)}
- onApply={handleApplyResourceLimits}
- />
- )}
-
- {basicAuthModal && (
- <BasicAuthModal
- environment={basicAuthModal.environment}
- prodId={id}
- onClose={() => setBasicAuthModal(null)}
- api={wordpressApi}
- />
- )}
-
- {wpCliModal && (
- <WpCliTerminal
- environment={wpCliModal.environment}
- prodId={id}
- onClose={() => setWpCliModal(null)}
- api={wordpressApi}
- />
- )}
-
- {autoSyncModal && (
- <AutoSyncScheduleModal
- environment={autoSyncModal.environment}
- prodId={id}
- onClose={() => setAutoSyncModal(null)}
- api={wordpressApi}
- />
- )}
-
- <ConfirmDialog
- isOpen={!!confirmDialog}
- title={confirmDialog?.title}
- message={confirmDialog?.message}
- confirmText={confirmDialog?.confirmText}
- variant={confirmDialog?.variant}
- onConfirm={confirmDialog?.onConfirm}
- onCancel={confirmDialog?.onCancel || (() => setConfirmDialog(null))}
- />
- </div>
- );
-};
-
-// Promotion History (lists past promotions; rollback available for completed promotions with a pre-promotion snapshot)
-const PromotionHistory = ({ projectId, onRollback }) => {
- const [promotions, setPromotions] = useState([]);
- const [loading, setLoading] = useState(true);
-
- const load = useCallback(async () => {
- setLoading(true);
- try {
- const data = await wordpressApi.getPromotionHistory(projectId, { limit: 20 });
- setPromotions(data.promotions || []);
- } catch {
- setPromotions([]);
- } finally {
- setLoading(false);
- }
- }, [projectId]);
-
- useEffect(() => { load(); }, [load]);
-
- if (loading || promotions.length === 0) {
- return null;
- }
-
- return (
- <div className="pipeline-promotion-history">
- <div className="section-header">
- <h3>Promotion History</h3>
- <Button variant="ghost" size="sm" onClick={load}>
- <RefreshCw size={14} /> Refresh
- </Button>
- </div>
- <div className="promotion-history-list">
- {promotions.map(p => {
- const canRollback = p.status === 'completed' && !!p.pre_promotion_snapshot_id;
- return (
- <div key={p.id} className="promotion-history-item">
- <div className="promotion-history-main">
- <span className={`promotion-status promotion-status-${p.status}`}>{p.status}</span>
- <span className="promotion-route">
- {p.source_site?.name || `#${p.source_site_id}`} <ArrowRight size={12} /> {p.target_site?.name || `#${p.target_site_id}`}
- </span>
- <span className="promotion-type">{p.promotion_type}</span>
- {p.created_at && (
- <span className="promotion-date">{new Date(p.created_at).toLocaleString()}</span>
- )}
- </div>
- {canRollback && (
- <Button variant="outline" size="sm" onClick={() => onRollback(p)}>
- <RotateCcw size={14} /> Rollback
- </Button>
- )}
- </div>
- );
- })}
- </div>
- </div>
- );
-};
-
-// Create Environment Modal (Pipeline version)
-const CreatePipelineEnvModal = ({ onClose, onCreate, productionDomain, existingTypes, projectId }) => {
- const [formData, setFormData] = useState({
- type: existingTypes.includes('development') ? 'staging' : 'development',
- name: '',
- branch: '',
- clone_db: true
- });
- const [loading, setLoading] = useState(false);
- const [branches, setBranches] = useState([]);
- const [branchesLoading, setBranchesLoading] = useState(false);
- const [branchSearch, setBranchSearch] = useState('');
- const [useCustomBranch, setUseCustomBranch] = useState(false);
-
- const availableTypes = [
- { value: 'development', label: 'Development', disabled: existingTypes.includes('development') },
- { value: 'staging', label: 'Staging', disabled: existingTypes.includes('staging') },
- { value: 'multidev', label: 'Multidev (branch-based)', disabled: false }
- ];
-
- useEffect(() => {
- if (formData.type === 'multidev' && branches.length === 0 && !branchesLoading) {
- loadBranches();
- }
- }, [formData.type]);
-
- async function loadBranches() {
- setBranchesLoading(true);
- try {
- const data = await wordpressApi.getBranches(projectId);
- setBranches(data.branches || []);
- } catch {
- setBranches([]);
- } finally {
- setBranchesLoading(false);
- }
- }
-
- function handleChange(e) {
- const { name, value, type, checked } = e.target;
- setFormData(prev => ({
- ...prev,
- [name]: type === 'checkbox' ? checked : value
- }));
- }
-
- function selectBranch(branchName) {
- setFormData(prev => ({ ...prev, branch: branchName }));
- setBranchSearch('');
- }
-
- async function handleSubmit(e) {
- e.preventDefault();
- setLoading(true);
- try {
- await onCreate(formData);
- } finally {
- setLoading(false);
- }
- }
-
- const filteredBranches = branches.filter(b => {
- if (!branchSearch) return true;
- return b.name.toLowerCase().includes(branchSearch.toLowerCase());
- });
-
- return (
- <Modal open onClose={onClose} title="Create Environment">
- <form onSubmit={handleSubmit}>
- <div className="form-group">
- <Label>Environment Type</Label>
- <select name="type" value={formData.type} onChange={handleChange}>
- {availableTypes.map(t => (
- <option key={t.value} value={t.value} disabled={t.disabled}>
- {t.label}{t.disabled ? ' (already exists)' : ''}
- </option>
- ))}
- </select>
- </div>
-
- {formData.type === 'multidev' && (
- <div className="form-group">
- <Label>
- <GitBranch size={14} className="mr-1" style={{ verticalAlign: -2 }} />
- Git Branch *
- </Label>
-
- {formData.branch && !useCustomBranch && (
- <div className="branch-selected">
- <GitBranch size={14} />
- <span className="branch-selected-name">{formData.branch}</span>
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={() => setFormData(prev => ({ ...prev, branch: '' }))}
- >
- Change
- </Button>
- </div>
- )}
-
- {!formData.branch && !useCustomBranch && (
- <>
- {branchesLoading ? (
- <div className="branch-picker-loading">
- <Spinner size="sm" />
- <span>Loading branches...</span>
- </div>
- ) : branches.length > 0 ? (
- <div className="branch-picker">
- <div className="branch-picker-search">
- <Search size={14} />
- <Input
- type="text"
- value={branchSearch}
- onChange={e => setBranchSearch(e.target.value)}
- placeholder="Search branches..."
- autoFocus
- />
- </div>
- <div className="branch-picker-list">
- {filteredBranches.map(b => (
- <button
- key={b.name}
- type="button"
- className={`branch-picker-item ${b.has_multidev ? 'has-env' : ''} ${b.is_current ? 'current' : ''}`}
- onClick={() => selectBranch(b.name)}
- disabled={b.has_multidev}
- title={b.has_multidev ? 'Multidev already exists for this branch' : ''}
- >
- <div className="branch-picker-item-main">
- <GitBranch size={12} />
- <span className="branch-name">{b.name}</span>
- {b.is_current && <span className="branch-tag">default</span>}
- {b.has_multidev && <span className="branch-tag env">has env</span>}
- </div>
- {b.message && (
- <div className="branch-picker-item-meta">
- <span className="branch-sha">{b.short_sha}</span>
- <span className="branch-msg">{b.message}</span>
- </div>
- )}
- </button>
- ))}
- {filteredBranches.length === 0 && (
- <div className="branch-picker-empty">
- No branches match &quot;{branchSearch}&quot;
- </div>
- )}
- </div>
- <Button
- type="button"
- variant="ghost"
- size="sm"
- className="branch-picker-custom"
- onClick={() => setUseCustomBranch(true)}
- >
- Enter branch name manually
- </Button>
- </div>
- ) : (
- <div>
- <Input
- type="text"
- name="branch"
- value={formData.branch}
- onChange={handleChange}
- placeholder="feature/my-branch"
- required
- />
- <span className="form-hint">No git repo connected or no branches found. Enter branch name manually.</span>
- </div>
- )}
- </>
- )}
-
- {useCustomBranch && (
- <div>
- <Input
- type="text"
- name="branch"
- value={formData.branch}
- onChange={handleChange}
- placeholder="feature/my-branch"
- required
- autoFocus
- />
- {branches.length > 0 && (
- <Button
- type="button"
- variant="ghost"
- size="sm"
- className="mt-1"
- onClick={() => { setUseCustomBranch(false); setFormData(prev => ({ ...prev, branch: '' })); }}
- >
- Back to branch list
- </Button>
- )}
- </div>
- )}
- </div>
- )}
-
- <div className="form-group">
- <Label>Environment Name</Label>
- <Input
- type="text"
- name="name"
- value={formData.name}
- onChange={handleChange}
- placeholder={formData.type === 'multidev' ? 'Auto-generated from branch' : `${formData.type} environment`}
- />
- <span className="form-hint">Leave empty to auto-generate</span>
- </div>
-
- <div className="form-group">
- <label className="checkbox-label">
- <input
- type="checkbox"
- name="clone_db"
- checked={formData.clone_db}
- onChange={handleChange}
- />
- <span>Clone production database</span>
- </label>
- <span className="form-hint">Creates a copy of the production database for this environment</span>
- </div>
-
- <div className="modal-actions">
- <Button type="button" variant="outline" onClick={onClose} disabled={loading}>
- Cancel
- </Button>
- <Button
- type="submit"
- disabled={loading || (formData.type === 'multidev' && !formData.branch)}
- >
- {loading ? <><Spinner size="sm" /> Creating...</> : 'Create Environment'}
- </Button>
- </div>
- </form>
- </Modal>
- );
-};
-
-export default WordPressProject;
diff --git a/frontend/src/plugins/serverkit-wordpress/pages/WordPressProjects.jsx b/frontend/src/plugins/serverkit-wordpress/pages/WordPressProjects.jsx
deleted file mode 100644
index 9eaf353d..00000000
--- a/frontend/src/plugins/serverkit-wordpress/pages/WordPressProjects.jsx
+++ /dev/null
@@ -1,181 +0,0 @@
-import { useState, useEffect } from 'react';
-import { useNavigate } from 'react-router-dom';
-import { GitBranch, Layers } from 'lucide-react';
-import wordpressApi from '@/services/wordpress';
-import { useToast } from 'serverkit-sdk';
-import ResourceListPage from '@/components/layouts/ResourceListPage';
-import { Pill, ServiceTile, EnvTag } from 'serverkit-sdk';
-
-// Environment badges, in promotion order — production is always present, the
-// rest only when the project actually has them.
-const ENV_TAGS = [
- ['staging', 'STG'],
- ['development', 'DEV'],
- ['multidev', 'MD'],
-];
-
-// A WordPress project = one site plus its environment chain. This lists which
-// projects HAVE a pipeline; the run history of what was promoted and when lives
-// in Deploy Activity, which answers a different question.
-const WordPressProjects = () => {
- const [projects, setProjects] = useState([]);
- const [loading, setLoading] = useState(true);
- const [search, setSearch] = useState('');
- const [statusFilter, setStatusFilter] = useState('all');
- const navigate = useNavigate();
- const toast = useToast();
-
- useEffect(() => {
- loadProjects();
- }, []);
-
- async function loadProjects() {
- setLoading(true);
- try {
- const data = await wordpressApi.getPipelines();
- setProjects(data.projects || []);
- } catch (err) {
- console.error('Failed to load projects:', err);
- toast.error('Failed to load WordPress projects');
- } finally {
- setLoading(false);
- }
- }
-
- const runningCount = projects.filter(p => p.status === 'running').length;
-
- const shown = projects.filter(p => {
- if (statusFilter === 'running' && p.status !== 'running') return false;
- if (statusFilter === 'stopped' && p.status === 'running') return false;
- const q = search.trim().toLowerCase();
- if (!q) return true;
- return [p.name, p.url, p.application?.domains?.[0]]
- .some(v => v && String(v).toLowerCase().includes(q));
- });
-
- const domainOf = (p) => p.application?.domains?.[0] || p.url || '';
- const envCount = (p) => (p.environment_count || 0) + 1;
-
- const columns = [
- {
- key: 'name',
- header: 'Project',
- render: (p) => (
- <div className="sk-cell-name">
- <ServiceTile name={p.name} size={30} aria-hidden="true" />
- <span>
- <div>{p.name}</div>
- {domainOf(p) && <div className="sk-cell-sub">{domainOf(p)}</div>}
- </span>
- </div>
- ),
- },
- {
- key: 'environments',
- header: 'Environments',
- render: (p) => (
- <span className="wp-projects-page__envs">
- <span className="wp-projects-page__envcount">
- <Layers size={13} aria-hidden="true" />
- {envCount(p)}
- </span>
- <EnvTag env="production">PROD</EnvTag>
- {ENV_TAGS.map(([type, label]) => (
- (p.environment_types || []).includes(type)
- ? <EnvTag key={type} env={type}>{label}</EnvTag>
- : null
- ))}
- </span>
- ),
- },
- {
- key: 'version',
- header: 'Version',
- cellClassName: 'sk-cell-mono',
- render: (p) => (p.wp_version ? `WP ${p.wp_version}` : '—'),
- },
- {
- key: 'source',
- header: 'Source',
- render: (p) => (
- p.git_repo_url
- ? <span className="wp-projects-page__git"><GitBranch size={12} /> Git connected</span>
- : <span className="wp-list__dash">—</span>
- ),
- },
- {
- key: 'status',
- header: 'Status',
- render: (p) => (
- <Pill kind={p.status === 'running' ? 'green' : 'gray'}>
- {p.status === 'running' ? 'Running' : 'Stopped'}
- </Pill>
- ),
- },
- ];
-
- return (
- <ResourceListPage
- className="wp-projects-page"
- loading={loading}
- loadingTitle="Loading WordPress pipelines"
- totalCount={projects.length}
- items={shown}
- columns={columns}
- keyField="id"
- onRowClick={(p) => navigate(`/wordpress/pipelines/${p.id}`)}
- filters={[
- { value: 'all', label: 'All', count: projects.length },
- { value: 'running', label: 'Running', count: runningCount },
- { value: 'stopped', label: 'Stopped', count: projects.length - runningCount },
- ]}
- activeFilter={statusFilter}
- onFilterChange={setStatusFilter}
- searchTerm={search}
- onSearchChange={setSearch}
- searchPlaceholder="Search pipelines…"
- emptyIcon={Layers}
- emptyTitle="No WordPress pipelines"
- emptyDescription="Sites with environment pipelines appear here. Create a WordPress site with environments enabled to get started."
- filteredEmptyIcon={Layers}
- filteredEmptyTitle="No pipelines found"
- filteredEmptyDescription="Try adjusting your search or filter."
- viewStorageKey="serverkit.wpPipelines.view"
- renderCard={(p) => (
- <>
- <div className="services-card__top">
- <ServiceTile name={p.name} size={40} aria-hidden="true" />
- <div className="services-card__id">
- <div className="services-card__name">{p.name}</div>
- <div className="sk-cell-sub">{p.wp_version ? `WordPress ${p.wp_version}` : 'WordPress'}</div>
- </div>
- <Pill kind={p.status === 'running' ? 'green' : 'gray'}>
- {p.status === 'running' ? 'Running' : 'Stopped'}
- </Pill>
- </div>
-
- <div className="services-card__domain">
- {domainOf(p) || <span className="wp-list__dash">No domain</span>}
- </div>
-
- <div className="services-card__stats">
- <div>
- <span className="l">Environments</span>
- <span className="v">{envCount(p)}</span>
- </div>
- <div>
- <span className="l">Source</span>
- <span className="v">{p.git_repo_url ? 'Git' : 'Local'}</span>
- </div>
- <div>
- <span className="l">Status</span>
- <span className="v">{p.status === 'running' ? 'Running' : 'Stopped'}</span>
- </div>
- </div>
- </>
- )}
- />
- );
-};
-
-export default WordPressProjects;
diff --git a/frontend/src/plugins/serverkit-wordpress/plugin.json b/frontend/src/plugins/serverkit-wordpress/plugin.json
deleted file mode 100644
index 6ed8a55f..00000000
--- a/frontend/src/plugins/serverkit-wordpress/plugin.json
+++ /dev/null
@@ -1,95 +0,0 @@
-{
- "name": "serverkit-wordpress",
- "display_name": "WordPress",
- "version": "1.0.0",
- "description": "The full WordPress suite, covering site provisioning, plugin library, environments/pipelines, updates, security hardening, vulnerability scanning, analytics and reports. Ships bundled and installed by default (a flagship), and can be uninstalled to slim the core.",
- "author": "ServerKit",
- "license": "MIT",
- "category": "integration",
- "homepage": "https://github.com/jhd3197/ServerKit",
- "permissions": [
- "shell",
- "filesystem",
- "network",
- "docker",
- "database"
- ],
- "min_panel_version": "1.7.0",
- "featured": true,
- "feature_score": 80,
- "entry_point": "wordpress:wordpress_bp",
- "url_prefix": "/api/v1/wordpress",
- "extra_blueprints": [
- {
- "module": "wordpress_sites",
- "attr": "wordpress_sites_bp",
- "url_prefix": "/api/v1/wordpress"
- },
- {
- "module": "environment_pipeline",
- "attr": "environment_pipeline_bp",
- "url_prefix": "/api/v1/wordpress/projects"
- },
- {
- "module": "environment_pipeline",
- "attr": "environment_pipeline_bp",
- "url_prefix": "/api/v1/wordpress/pipelines",
- "name": "environment_pipeline_pipelines"
- },
- {
- "module": "wp_ssh_import",
- "attr": "wp_ssh_import_bp",
- "url_prefix": "/api/v1/wordpress"
- }
- ],
- "jobs": [
- {
- "kind": "wordpress.ssh_import.run",
- "handler": "wp_ssh_import_service:run_wp_ssh_import_job"
- }
- ],
- "icon": "<path d=\"M12 2a10 10 0 100 20 10 10 0 000-20zm-8 10a8 8 0 011.4-4.5l4.7 12.9A8 8 0 014 12zm8 8c-.8 0-1.6-.1-2.3-.3l2.4-7 2.5 6.8.1.1A8 8 0 0112 20zm1.1-11.8c.5 0 .9-.1.9-.1.4 0 .4-.6-.1-.6 0 0-1.4.1-2.3.1-.8 0-2.2-.1-2.2-.1-.5 0-.6.6-.1.6 0 0 .4.1.9.1l1.3 3.6-1.9 5.6L6.6 8.2c.5 0 .9-.1.9-.1.4 0 .4-.6-.1-.6 0 0-1.4.1-2.3.1h-.4A8 8 0 0112 4a8 8 0 016.5 3.3h-.3c-.8 0-1.4.7-1.4 1.5 0 .7.4 1.3.8 2 .3.6.7 1.3.7 2.3 0 .7-.3 1.6-.6 2.7l-.8 2.7-2.9-8.8z\"/>",
- "contributions": {
- "nav": [
- {
- "id": "wordpress",
- "label": "WordPress",
- "route": "/wordpress",
- "category": "infrastructure",
- "icon": "<circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z\"/><path d=\"M3.5 9h17M3.5 15h17\"/>"
- }
- ],
- "routes": [
- {
- "path": "wordpress/*",
- "component": "WordPressExtension"
- }
- ],
- "page_titles": {
- "/wordpress": "WordPress Sites",
- "/wordpress/plugins/library": "WordPress Plugin Library",
- "/wordpress/pipelines": "WordPress Pipelines",
- "/wordpress/ssh-import": "Import WordPress over SSH"
- },
- "command_palette": [
- {
- "label": "WordPress",
- "path": "/wordpress",
- "category": "Pages",
- "keywords": "wp sites"
- },
- {
- "label": "Import WordPress over SSH",
- "path": "/wordpress/ssh-import",
- "category": "Pages",
- "keywords": "wp migrate pull import ssh"
- },
- {
- "label": "WordPress Pipelines",
- "path": "/wordpress/pipelines",
- "category": "Pages",
- "keywords": "wp environments projects pipeline"
- }
- ]
- }
-}
diff --git a/frontend/src/plugins/serverkit-wordpress/styles/wordpress-pipeline.scss b/frontend/src/plugins/serverkit-wordpress/styles/wordpress-pipeline.scss
deleted file mode 100644
index 3daeede8..00000000
--- a/frontend/src/plugins/serverkit-wordpress/styles/wordpress-pipeline.scss
+++ /dev/null
@@ -1,2351 +0,0 @@
-// Compiled through the extension's module graph (imported by index.jsx).
-// The host's design-token partial is imported via a sync-safe relative
-// path — the baked copy lives at frontend/src/plugins/serverkit-wordpress/,
-// so this resolves to frontend/src/styles/_variables.scss.
-@import '../../../styles/variables';
-
-// ============================================
-// WORDPRESS PIPELINE STYLES
-// ============================================
-
-// Page Loading
-.page-loading {
- display: flex;
- align-items: center;
- justify-content: center;
- min-height: 400px;
-}
-
-// Projects Page
-.wp-projects-page {
- padding: $space-4;
-
- .empty-state-large {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: 60px $space-6;
- background: $bg-card;
- border-radius: $radius-xl;
- text-align: center;
-
- .empty-icon {
- color: $text-tertiary;
- margin-bottom: $space-4;
- }
-
- h2 {
- font-size: $font-size-lg;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- margin: 0 0 $space-2;
- }
-
- p {
- font-size: $font-size-sm;
- color: $text-secondary;
- max-width: 460px;
- margin: 0;
- }
- }
-}
-
-
-// ============================================
-// PIPELINE DASHBOARD
-// ============================================
-
-.wp-project-page {
- .wp-icon {
- background: $color-wordpress !important;
- }
-}
-
-// Pipeline Tab
-.pipeline-tab {
- padding: $space-4 0;
-}
-
-.pipeline-operation-banner {
- display: flex;
- align-items: center;
- gap: $space-3;
- padding: $space-3 $space-4;
- background: fade($info-raw, 10%);
- border: 1px solid fade($info-raw, 25%);
- border-radius: $radius-md;
- margin-bottom: $space-4;
- font-size: $font-size-sm;
- color: $color-info;
-}
-
-// Pipeline View
-.pipeline-view {
- margin-bottom: $space-6;
-}
-
-.pipeline-row {
- display: flex;
- align-items: stretch;
- gap: 0;
- overflow-x: auto;
- padding-bottom: $space-2;
-}
-
-.pipeline-card {
- flex: 1;
- min-width: 220px;
- max-width: 320px;
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-lg;
- display: flex;
- flex-direction: column;
- position: relative;
-
- &.production {
- border-color: fade($danger-raw, 45%);
- }
-
- &.locked {
- opacity: 0.85;
- }
-
- &.empty {
- border-style: dashed;
- border-color: $border-subtle;
- display: flex;
- align-items: center;
- justify-content: center;
- min-height: 180px;
- }
-}
-
-.pipeline-empty-content {
- text-align: center;
- color: $text-tertiary;
-
- p {
- margin: $space-2 0 0;
- font-size: $font-size-sm;
- }
-}
-
-.pipeline-card-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: $space-3 $space-4;
- border-bottom: 1px solid $border-subtle;
-}
-
-.env-status-badge-group {
- display: flex;
- align-items: center;
- gap: $space-2;
-}
-
-.env-locked-badge {
- display: flex;
- align-items: center;
- padding: 2px 4px;
- background: fade($warning-raw, 15%);
- color: $color-warning;
- border-radius: $radius-sm;
-}
-
-.pipeline-card-menu-wrapper {
- position: relative;
-}
-
-.pipeline-card-menu-btn {
- padding: 4px !important;
-}
-
-.pipeline-card-menu {
- position: absolute;
- right: 0;
- top: 100%;
- background: $bg-elevated;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
- z-index: 100;
- min-width: 140px;
- padding: $space-1;
-
- button {
- display: flex;
- align-items: center;
- gap: $space-2;
- width: 100%;
- padding: $space-2 $space-3;
- border: none;
- background: none;
- color: $text-secondary;
- font-size: $font-size-sm;
- cursor: pointer;
- border-radius: $radius-sm;
- text-align: left;
-
- &:hover {
- background: $bg-hover;
- color: $text-primary;
- }
-
- &.danger {
- color: $color-danger;
-
- &:hover {
- background: fade($danger-raw, 10%);
- }
- }
- }
-}
-
-.pipeline-card-body {
- flex: 1;
- padding: $space-4;
-}
-
-.pipeline-card-name {
- font-size: $font-size-base;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- margin: 0 0 $space-2;
-}
-
-.pipeline-card-domain {
- display: block;
- font-size: $font-size-xs;
- font-family: $font-family-mono;
- color: $color-primary;
- margin-bottom: $space-2;
- text-decoration: none;
-
- &:hover {
- text-decoration: underline;
- }
-}
-
-.pipeline-card-meta {
- display: flex;
- flex-wrap: wrap;
- gap: $space-2;
-}
-
-.pipeline-meta-item {
- font-size: $font-size-xs;
- color: $text-tertiary;
-}
-
-.pipeline-card-footer {
- display: flex;
- gap: $space-2;
- padding: $space-2 $space-3;
- border-top: 1px solid $border-subtle;
- background: $bg-tertiary;
- border-radius: 0 0 $radius-lg $radius-lg;
-}
-
-.pipeline-card-lock-banner {
- display: flex;
- align-items: center;
- gap: $space-1;
- padding: $space-2 $space-3;
- background: fade($warning-raw, 10%);
- font-size: $font-size-xs;
- color: $color-warning;
- border-radius: 0 0 $radius-lg $radius-lg;
-}
-
-// Pipeline Arrows
-.pipeline-arrow {
- display: flex;
- align-items: center;
- justify-content: center;
- min-width: 80px;
- padding: 0 $space-2;
-
- &.disabled {
- opacity: 0.3;
- pointer-events: none;
- }
-}
-
-.pipeline-arrow-btn {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 4px;
- padding: $space-2 $space-3;
- border: 1px solid $border-subtle;
- background: $bg-card;
- border-radius: $radius-md;
- cursor: pointer;
- color: $text-secondary;
- transition: all 0.15s ease;
-
- &:hover:not(:disabled) {
- border-color: $color-primary;
- color: $color-primary;
- background: fade($accent-primary-raw, 5%);
- }
-
- &:disabled {
- cursor: not-allowed;
- opacity: 0.4;
- }
-}
-
-.pipeline-arrow-label {
- font-size: 10px;
- font-weight: $font-weight-medium;
- text-transform: uppercase;
- letter-spacing: 0.5px;
-}
-
-// Pipeline Sync Row
-.pipeline-sync-row {
- display: flex;
- gap: 0;
- margin-top: $space-2;
-
- .pipeline-sync-action {
- flex: 1;
- min-width: 220px;
- max-width: 320px;
- display: flex;
- justify-content: center;
- }
-}
-
-// Multidev Section
-.pipeline-multidev-section {
- margin-top: $space-6;
- padding-top: $space-4;
- border-top: 1px solid $border-subtle;
-}
-
-.pipeline-section-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- margin-bottom: $space-3;
-}
-
-.pipeline-section-title {
- display: flex;
- align-items: center;
- gap: $space-2;
- font-size: $font-size-sm;
- font-weight: $font-weight-semibold;
- color: $text-secondary;
- text-transform: uppercase;
- letter-spacing: 0.5px;
- margin: 0;
-}
-
-.pipeline-section-count {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- min-width: 20px;
- height: 20px;
- padding: 0 6px;
- background: fade($accent-primary-raw, 12%);
- color: $color-primary;
- border-radius: 10px;
- font-size: 11px;
- font-weight: $font-weight-bold;
- text-transform: none;
- letter-spacing: 0;
-}
-
-.pipeline-multidev-grid {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
- gap: $space-3;
-}
-
-.pipeline-multidev-empty {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: $space-8 $space-4;
- background: $bg-card;
- border: 1px dashed $border-subtle;
- border-radius: $radius-lg;
- text-align: center;
-
- > svg {
- color: $text-tertiary;
- margin-bottom: $space-3;
- }
-
- p {
- font-size: $font-size-base;
- font-weight: $font-weight-medium;
- color: $text-secondary;
- margin: 0 0 $space-1;
- }
-
- > span {
- font-size: $font-size-sm;
- color: $text-tertiary;
- margin-bottom: $space-4;
- }
-}
-
-.multidev-card {
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-lg;
- transition: border-color 0.15s ease;
-
- &:hover {
- border-color: $border-hover;
- }
-
- &.locked {
- opacity: 0.85;
- }
-}
-
-.multidev-card-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: $space-3 $space-4;
- border-bottom: 1px solid $border-subtle;
-}
-
-.multidev-card-header-left {
- display: flex;
- align-items: center;
- gap: $space-2;
-}
-
-.multidev-lock-icon {
- color: $color-warning;
-}
-
-.multidev-card-menu-wrapper {
- position: relative;
-}
-
-.multidev-card-body {
- padding: $space-3 $space-4;
-}
-
-.multidev-card-name {
- font-size: $font-size-sm;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- margin: 0 0 $space-2;
-}
-
-.multidev-branch {
- display: inline-flex;
- align-items: center;
- gap: 4px;
- font-size: $font-size-xs;
- font-family: $font-family-mono;
- color: $text-tertiary;
- background: $bg-tertiary;
- padding: 2px 8px;
- border-radius: $radius-sm;
- margin-bottom: $space-2;
-}
-
-.multidev-domain {
- display: block;
- font-size: $font-size-xs;
- font-family: $font-family-mono;
- color: $color-primary;
- text-decoration: none;
- margin-bottom: $space-2;
-
- &:hover {
- text-decoration: underline;
- }
-}
-
-.multidev-card-meta {
- display: flex;
- flex-wrap: wrap;
- gap: $space-2;
-}
-
-.multidev-meta-item {
- font-size: $font-size-xs;
- color: $text-tertiary;
-}
-
-.multidev-card-footer {
- display: flex;
- gap: $space-2;
- padding: $space-2 $space-3;
- border-top: 1px solid $border-subtle;
- background: $bg-tertiary;
- border-radius: 0 0 $radius-lg $radius-lg;
-}
-
-.wp-env-badge.env-multidev {
- background: fade($accent-primary-raw, 12%);
- color: $color-primary;
-}
-
-// ============================================
-// BRANCH PICKER
-// ============================================
-
-.branch-selected {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-3;
- background: fade($accent-primary-raw, 8%);
- border: 1px solid fade($accent-primary-raw, 25%);
- border-radius: $radius-md;
-
- svg {
- color: $color-primary;
- flex-shrink: 0;
- }
-}
-
-.branch-selected-name {
- flex: 1;
- font-family: $font-family-mono;
- font-size: $font-size-sm;
- font-weight: $font-weight-medium;
- color: $text-primary;
-}
-
-.branch-picker-loading {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-4;
- justify-content: center;
- color: $text-tertiary;
- font-size: $font-size-sm;
-}
-
-.branch-picker {
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- overflow: hidden;
-}
-
-.branch-picker-search {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-2 $space-3;
- border-bottom: 1px solid $border-subtle;
- background: $bg-tertiary;
-
- svg {
- color: $text-tertiary;
- flex-shrink: 0;
- }
-
- input {
- flex: 1;
- border: none;
- background: none;
- font-size: $font-size-sm;
- color: $text-primary;
- outline: none;
- padding: 0;
-
- &::placeholder {
- color: $text-tertiary;
- }
- }
-}
-
-.branch-picker-list {
- max-height: 240px;
- overflow-y: auto;
-}
-
-.branch-picker-item {
- display: flex;
- flex-direction: column;
- gap: 2px;
- width: 100%;
- padding: $space-2 $space-3;
- border: none;
- border-bottom: 1px solid $border-subtle;
- background: $bg-card;
- cursor: pointer;
- text-align: left;
- transition: background 0.1s ease;
-
- &:last-child {
- border-bottom: none;
- }
-
- &:hover:not(:disabled) {
- background: $bg-hover;
- }
-
- &:disabled {
- opacity: 0.5;
- cursor: not-allowed;
- }
-
- &.has-env {
- background: fade($text-tertiary-raw, 3%);
- }
-}
-
-.branch-picker-item-main {
- display: flex;
- align-items: center;
- gap: $space-2;
- font-size: $font-size-sm;
- color: $text-primary;
-
- svg {
- color: $text-tertiary;
- flex-shrink: 0;
- }
-}
-
-.branch-name {
- font-family: $font-family-mono;
- font-weight: $font-weight-medium;
-}
-
-.branch-tag {
- font-size: 10px;
- font-weight: $font-weight-medium;
- padding: 1px 6px;
- border-radius: $radius-sm;
- background: fade($text-tertiary-raw, 10%);
- color: $text-tertiary;
-
- &.env {
- background: fade($accent-primary-raw, 10%);
- color: $color-primary;
- }
-}
-
-.branch-picker-item-meta {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding-left: 20px;
-
- .branch-sha {
- font-family: $font-family-mono;
- font-size: 11px;
- color: $text-tertiary;
- }
-
- .branch-msg {
- font-size: 11px;
- color: $text-tertiary;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
-}
-
-.branch-picker-empty {
- padding: $space-4;
- text-align: center;
- font-size: $font-size-sm;
- color: $text-tertiary;
-}
-
-.branch-picker-custom {
- width: 100%;
- border-top: 1px solid $border-subtle;
- border-radius: 0 0 $radius-md $radius-md;
- justify-content: center;
- color: $color-primary !important;
-}
-
-// ============================================
-// PROMOTE / SYNC MODALS
-// ============================================
-
-.promote-direction,
-.sync-direction {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: $space-3;
- padding: $space-4;
- background: $bg-tertiary;
- border-radius: $radius-md;
- margin-bottom: $space-4;
-}
-
-.promote-env-pill {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 4px;
- padding: $space-3 $space-4;
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- min-width: 120px;
-
- .promote-env-type {
- font-size: $font-size-xs;
- font-weight: $font-weight-bold;
- text-transform: uppercase;
- letter-spacing: 0.5px;
- }
-
- .promote-env-name {
- font-size: $font-size-sm;
- color: $text-secondary;
- max-width: 150px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
-
- &.production .promote-env-type { color: $color-danger; }
- &.staging .promote-env-type { color: $color-warning; }
- &.development .promote-env-type { color: $color-info; }
- &.multidev .promote-env-type { color: $color-primary; }
-}
-
-.promote-arrow {
- color: $text-tertiary;
- flex-shrink: 0;
-}
-
-.promote-warning,
-.sync-warning {
- display: flex;
- align-items: flex-start;
- gap: $space-3;
- padding: $space-3 $space-4;
- background: fade($warning-raw, 8%);
- border: 1px solid fade($warning-raw, 20%);
- border-radius: $radius-md;
- margin-top: $space-4;
- font-size: $font-size-sm;
- color: $text-secondary;
-
- > svg {
- color: $color-warning;
- flex-shrink: 0;
- margin-top: 2px;
- }
-
- strong {
- color: $text-primary;
- }
-
- p {
- margin: $space-1 0 0;
- }
-}
-
-// Radio Group for promotion/sync type selection
-.radio-group {
- display: flex;
- flex-direction: column;
- gap: $space-2;
-}
-
-.radio-label {
- display: flex;
- align-items: flex-start;
- gap: $space-3;
- padding: $space-3;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- cursor: pointer;
- transition: all 0.15s ease;
-
- &:hover {
- border-color: $border-hover;
- background: $bg-hover;
- }
-
- &:has(input:checked) {
- border-color: $color-primary;
- background: fade($accent-primary-raw, 5%);
- }
-
- input[type="radio"] {
- margin-top: 4px;
- accent-color: var(--accent-primary, #3b82f6);
- }
-}
-
-.radio-content {
- display: flex;
- flex-direction: column;
- gap: 2px;
-
- strong {
- font-size: $font-size-sm;
- color: $text-primary;
- }
-
- span {
- font-size: $font-size-xs;
- color: $text-tertiary;
- }
-}
-
-.checkbox-group {
- display: flex;
- flex-direction: column;
- gap: $space-2;
-}
-
-// ============================================
-// ACTIVITY FEED
-// ============================================
-
-.activity-feed {
- display: flex;
- flex-direction: column;
- gap: 1px;
- background: $border-subtle;
- border: 1px solid $border-subtle;
- border-radius: $radius-lg;
- overflow: hidden;
-
- &.compact .activity-item {
- padding: $space-2 $space-3;
- }
-}
-
-.activity-feed-empty {
- padding: $space-6;
- text-align: center;
- color: $text-tertiary;
- font-size: $font-size-sm;
-}
-
-.activity-item {
- display: flex;
- align-items: center;
- gap: $space-3;
- padding: $space-3 $space-4;
- background: $bg-card;
-}
-
-.activity-item-skeleton {
- display: flex;
- align-items: center;
- gap: $space-3;
- padding: $space-3 $space-4;
-}
-
-.activity-icon {
- display: flex;
- align-items: center;
- justify-content: center;
- width: 28px;
- height: 28px;
- border-radius: 50%;
- flex-shrink: 0;
-
- &.success {
- background: fade($success-raw, 12%);
- color: $color-success;
- }
- &.danger {
- background: fade($danger-raw, 12%);
- color: $color-danger;
- }
- &.warning {
- background: fade($warning-raw, 12%);
- color: $color-warning;
- }
- &.info {
- background: fade($info-raw, 12%);
- color: $color-info;
- }
- &.primary {
- background: fade($accent-primary-raw, 12%);
- color: $color-primary;
- }
- &.default {
- background: fade($text-tertiary-raw, 12%);
- color: $text-tertiary;
- }
-}
-
-.activity-content {
- flex: 1;
- min-width: 0;
-}
-
-.activity-description {
- font-size: $font-size-sm;
- color: $text-primary;
- display: block;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.activity-error {
- font-size: $font-size-xs;
- color: $color-danger;
- display: block;
- margin-top: 2px;
-}
-
-.activity-meta {
- display: flex;
- align-items: center;
- gap: $space-2;
- flex-shrink: 0;
-}
-
-.activity-time {
- font-size: $font-size-xs;
- color: $text-tertiary;
- white-space: nowrap;
-}
-
-.activity-status-badge {
- font-size: 10px;
- font-weight: $font-weight-medium;
- padding: 2px 6px;
- border-radius: $radius-sm;
-
- &.failed {
- background: fade($danger-raw, 12%);
- color: $color-danger;
- }
-
- &.running {
- background: fade($info-raw, 12%);
- color: $color-info;
- }
-}
-
-.activity-load-more {
- background: $bg-card;
- padding: $space-3;
- text-align: center;
- width: 100%;
- justify-content: center;
-}
-
-// Pipeline Activity Preview
-.pipeline-activity-preview {
- margin-top: $space-6;
-}
-
-// ============================================
-// CONTAINER LOGS
-// ============================================
-
-.pipeline-logs-overlay {
- position: fixed;
- bottom: 0;
- right: 0;
- width: 600px;
- max-width: 100%;
- height: 400px;
- z-index: 200;
- // Up-facing variant of --shadow-lg (token shadows cast downward).
- box-shadow: 0 -16px 48px -12px rgba(0, 0, 0, 0.5);
- border-radius: var(--radius-lg) var(--radius-lg) 0 0;
- overflow: hidden;
-
- @media (max-width: $breakpoint-md) {
- width: 100%;
- }
-}
-
-.container-logs-panel {
- display: flex;
- flex-direction: column;
- height: 100%;
- background: var(--surface);
- border: 1px solid var(--border-strong);
- border-radius: var(--radius-lg) var(--radius-lg) 0 0;
-}
-
-.container-logs-header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: $space-3;
- padding: $space-2 $space-3;
- border-bottom: 1px solid var(--border-soft);
- background: var(--surface);
-}
-
-.container-logs-title {
- display: flex;
- align-items: center;
- gap: $space-3;
- min-width: 0;
- color: var(--text);
-}
-
-.container-logs-ico {
- width: 28px;
- height: 28px;
- border-radius: 8px;
- display: grid;
- place-items: center;
- background: var(--cyan-bg);
- color: var(--cyan);
- flex-shrink: 0;
-}
-
-.container-logs-titles {
- display: flex;
- flex-direction: column;
- min-width: 0;
- font-size: 13px;
- font-weight: $font-weight-semibold;
-}
-
-.container-logs-sub {
- font-family: var(--mono);
- font-size: 10.5px;
- font-weight: $font-weight-normal;
- color: var(--text-faint);
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.container-logs-controls {
- display: flex;
- align-items: center;
- gap: $space-2;
- flex-shrink: 0;
-}
-
-.logs-service-select,
-.logs-lines-select {
- padding: 4px $space-2;
- font-family: var(--mono);
- font-size: 11.5px;
- border: 1px solid var(--border);
- border-radius: $radius-md;
- background: var(--surface-2);
- color: var(--text-dim);
- transition: border-color $transition-fast, color $transition-fast;
-
- &:hover {
- border-color: var(--border-strong);
- color: var(--text);
- }
-}
-
-.container-logs-body {
- flex: 1;
- overflow-y: auto;
- background: var(--bg-code);
- scrollbar-width: thin;
-}
-
-.logs-loading,
-.logs-empty {
- padding: $space-6;
- text-align: center;
- color: var(--text-faint);
- font-family: var(--mono);
- font-size: $font-size-sm;
-}
-
-.logs-content {
- margin: 0;
- padding: $space-3 $space-4;
- font-family: var(--mono);
- font-size: 12px;
- line-height: 1.7;
- color: var(--text-dim);
- white-space: pre-wrap;
- word-break: break-all;
-}
-
-.log-line {
- padding: 1px 0;
-
- &:hover {
- background: fade($text-primary-raw, 5%);
- }
-}
-
-// ============================================
-// COMPARE VIEW
-// ============================================
-
-.compare-header {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: $space-3;
- padding: $space-4;
- background: $bg-tertiary;
- margin: 0 -$space-5;
- padding: $space-4 $space-5;
-}
-
-.compare-env-pill {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 4px;
- padding: $space-3 $space-4;
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- min-width: 120px;
-
- .compare-env-type {
- font-size: $font-size-xs;
- font-weight: $font-weight-bold;
- text-transform: uppercase;
- letter-spacing: 0.5px;
- }
-
- .compare-env-name {
- font-size: $font-size-sm;
- color: $text-secondary;
- max-width: 150px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
-
- &.production .compare-env-type { color: $color-danger; }
- &.staging .compare-env-type { color: $color-warning; }
- &.development .compare-env-type { color: $color-info; }
- &.multidev .compare-env-type { color: $color-primary; }
-}
-
-.compare-vs-icon {
- color: $text-tertiary;
- flex-shrink: 0;
-}
-
-.compare-body {
- padding: $space-4 0;
- max-height: 60vh;
- overflow-y: auto;
-}
-
-.compare-loading {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: $space-3;
- padding: $space-8;
- color: $text-tertiary;
- font-size: $font-size-sm;
-}
-
-.compare-error {
- text-align: center;
- padding: $space-6;
-
- p {
- color: $color-danger;
- margin: 0 0 $space-3;
- }
-}
-
-.compare-section {
- margin-bottom: $space-4;
-
- &:last-child {
- margin-bottom: 0;
- }
-}
-
-.compare-section-header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: $space-2 $space-3;
- background: $bg-tertiary;
- border-radius: $radius-md;
- margin-bottom: $space-2;
-
- h4 {
- margin: 0;
- font-size: $font-size-sm;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- }
-}
-
-.compare-section-summary {
- font-size: $font-size-xs;
- color: $text-tertiary;
-}
-
-.compare-table {
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- overflow: hidden;
-}
-
-.compare-row {
- display: grid;
- grid-template-columns: 1fr 1fr 1fr;
- gap: $space-2;
- padding: $space-2 $space-3;
- border-bottom: 1px solid $border-subtle;
- font-size: $font-size-sm;
- align-items: center;
-
- &:last-child {
- border-bottom: none;
- }
-
- &.match {
- .compare-row-icon { color: $color-success; }
- }
-
- &.different {
- background: fade($danger-raw, 5%);
- .compare-row-icon { color: $color-danger; }
- .compare-row-value-a,
- .compare-row-value-b {
- font-weight: $font-weight-medium;
- }
- }
-
- &.only-a {
- .compare-row-icon { color: $color-warning; }
- .compare-row-value-b { opacity: 0.4; }
- }
-
- &.only-b {
- .compare-row-icon { color: $color-warning; }
- .compare-row-value-a { opacity: 0.4; }
- }
-}
-
-.compare-row-label {
- display: flex;
- align-items: center;
- gap: $space-2;
- font-weight: $font-weight-medium;
- color: $text-primary;
-}
-
-.compare-row-icon {
- flex-shrink: 0;
-}
-
-.compare-row-value-a,
-.compare-row-value-b {
- font-size: $font-size-xs;
- color: $text-secondary;
- font-family: $font-family-mono;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.compare-na {
- color: $text-tertiary;
- font-style: italic;
-}
-
-.compare-empty-row {
- padding: $space-4;
- text-align: center;
- font-size: $font-size-sm;
- color: $text-tertiary;
-}
-
-// Pipeline Compare Row
-.pipeline-compare-row {
- display: flex;
- gap: $space-3;
- justify-content: center;
- margin-top: $space-2;
- padding: $space-2 0;
-}
-
-.pipeline-compare-btn {
- color: $text-tertiary !important;
- font-size: $font-size-xs !important;
-
- &:hover {
- color: $color-primary !important;
- }
-}
-
-// ============================================
-// SANITIZATION PROFILES
-// ============================================
-
-.sanitization-profiles-body {
- padding: $space-4 0;
- max-height: 60vh;
- overflow-y: auto;
-}
-
-.sanitization-loading {
- display: flex;
- align-items: center;
- justify-content: center;
- padding: $space-8;
-}
-
-.sanitization-profile-list {
- display: flex;
- flex-direction: column;
- gap: $space-3;
- margin-bottom: $space-4;
-}
-
-.sanitization-profile-card {
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- padding: $space-3 $space-4;
- transition: border-color 0.15s ease;
-
- &:hover {
- border-color: $border-hover;
- }
-
- &.default {
- border-color: fade($accent-primary-raw, 45%);
- }
-}
-
-.sanitization-profile-card-header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- margin-bottom: $space-2;
-}
-
-.sanitization-profile-card-title {
- display: flex;
- align-items: center;
- gap: $space-2;
-
- h5 {
- margin: 0;
- font-size: $font-size-sm;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- }
-}
-
-.sanitization-tag {
- font-size: 10px;
- font-weight: $font-weight-medium;
- padding: 1px 6px;
- border-radius: $radius-sm;
-
- &.builtin {
- background: fade($text-tertiary-raw, 10%);
- color: $text-tertiary;
- }
-
- &.default {
- background: fade($accent-primary-raw, 12%);
- color: $color-primary;
- }
-}
-
-.sanitization-profile-card-actions {
- display: flex;
- gap: $space-1;
-}
-
-.sanitization-profile-desc {
- font-size: $font-size-xs;
- color: $text-secondary;
- margin: 0 0 $space-2;
-}
-
-.sanitization-rule-tags {
- display: flex;
- flex-wrap: wrap;
- gap: 4px;
-}
-
-.sanitization-rule-tag {
- font-size: 10px;
- padding: 2px 8px;
- background: $bg-tertiary;
- border-radius: $radius-sm;
- color: $text-tertiary;
-
- &.empty {
- font-style: italic;
- }
-}
-
-.sanitization-add-btn {
- width: 100%;
- justify-content: center;
-}
-
-// Profile Editor
-.sanitization-editor {
- background: $bg-tertiary;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- padding: $space-4;
- margin-top: $space-3;
-
- h4 {
- margin: 0 0 $space-3;
- font-size: $font-size-sm;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- }
-
- .form-group {
- margin-bottom: $space-3;
-
- &:last-of-type {
- margin-bottom: $space-4;
- }
- }
-}
-
-.sanitization-editor-actions {
- display: flex;
- justify-content: flex-end;
- gap: $space-2;
- padding-top: $space-3;
- border-top: 1px solid $border-subtle;
-}
-
-// ============================================
-// RESPONSIVE
-// ============================================
-
-// ============================================
-// PIPELINE CARD ADDITIONS (Phase 7)
-// ============================================
-
-.pipeline-card-checkbox {
- margin-right: $space-1;
- accent-color: var(--accent-primary, #3b82f6);
-}
-
-.pipeline-card-menu-divider {
- height: 1px;
- background: $border-subtle;
- margin: $space-1 0;
-}
-
-// ============================================
-// RESOURCE LIMITS MODAL
-// ============================================
-
-.resource-limits-modal {
- max-width: 480px;
-}
-
-.resource-limits-env-name {
- font-size: $font-size-sm;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- padding-bottom: $space-3;
- border-bottom: 1px solid $border-subtle;
- margin-bottom: $space-3;
-}
-
-.resource-limits-presets {
- display: flex;
- align-items: center;
- gap: $space-2;
- margin-bottom: $space-4;
-}
-
-.resource-limits-presets-label {
- font-size: $font-size-sm;
- color: $text-secondary;
-}
-
-.resource-preset-btn {
- text-transform: capitalize;
-}
-
-.resource-limits-section {
- margin-bottom: $space-4;
-
- h4 {
- display: flex;
- align-items: center;
- gap: $space-2;
- font-size: $font-size-sm;
- font-weight: $font-weight-semibold;
- color: $text-secondary;
- margin: 0 0 $space-3;
- }
-}
-
-.resource-limits-row {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: $space-2 0;
-
- label {
- font-size: $font-size-sm;
- color: $text-primary;
- }
-
- select {
- width: 120px;
- padding: $space-1 $space-2;
- font-size: $font-size-sm;
- border: 1px solid $border-subtle;
- border-radius: $radius-sm;
- background: $bg-card;
- color: $text-primary;
- }
-}
-
-.resource-limits-warning {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-3;
- background: fade($warning-raw, 8%);
- border: 1px solid fade($warning-raw, 20%);
- border-radius: $radius-md;
- margin-top: $space-3;
- margin-bottom: $space-3;
- font-size: $font-size-xs;
- color: $color-warning;
-}
-
-// ============================================
-// BASIC AUTH MODAL
-// ============================================
-
-.basic-auth-modal {
- max-width: 460px;
-}
-
-.basic-auth-body {
- padding: $space-4 0;
-}
-
-.basic-auth-env-name {
- font-size: $font-size-sm;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- padding-bottom: $space-3;
- border-bottom: 1px solid $border-subtle;
- margin-bottom: $space-3;
-}
-
-.basic-auth-loading {
- display: flex;
- align-items: center;
- gap: $space-2;
- justify-content: center;
- padding: $space-4;
- color: $text-tertiary;
- font-size: $font-size-sm;
-}
-
-.basic-auth-toggle {
- margin-bottom: $space-4;
-}
-
-.basic-auth-toggle-label {
- display: flex;
- align-items: center;
- justify-content: space-between;
- cursor: pointer;
-
- span {
- font-size: $font-size-sm;
- font-weight: $font-weight-medium;
- color: $text-primary;
- }
-}
-
-.basic-auth-description {
- font-size: $font-size-xs;
- color: $text-tertiary;
- margin: $space-1 0 0;
-}
-
-.toggle-switch {
- position: relative;
- width: 44px;
- height: 24px;
- border: none;
- border-radius: 12px;
- background: $bg-tertiary;
- cursor: pointer;
- transition: background 0.2s ease;
- padding: 0;
-
- &.active {
- background: var(--accent-primary, #3b82f6);
- }
-}
-
-.toggle-switch-slider {
- position: absolute;
- top: 2px;
- left: 2px;
- width: 20px;
- height: 20px;
- border-radius: 50%;
- background: white;
- transition: transform 0.2s ease;
-
- .toggle-switch.active & {
- transform: translateX(20px);
- }
-}
-
-.basic-auth-current {
- padding: $space-3;
- background: $bg-tertiary;
- border-radius: $radius-md;
-}
-
-.basic-auth-credentials {
- display: flex;
- flex-direction: column;
- gap: $space-3;
-}
-
-.basic-auth-credential-warning {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-2 $space-3;
- background: fade($warning-raw, 10%);
- border: 1px solid fade($warning-raw, 20%);
- border-radius: $radius-md;
- font-size: $font-size-xs;
- color: $color-warning;
-}
-
-.basic-auth-field {
- display: flex;
- flex-direction: column;
- gap: $space-1;
-
- label {
- font-size: $font-size-xs;
- font-weight: $font-weight-medium;
- color: $text-tertiary;
- text-transform: uppercase;
- letter-spacing: 0.5px;
- }
-}
-
-.basic-auth-value {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-2 $space-3;
- background: $bg-tertiary;
- border-radius: $radius-sm;
-
- code {
- flex: 1;
- font-family: $font-family-mono;
- font-size: $font-size-sm;
- color: $text-primary;
- }
-}
-
-.basic-auth-hint {
- font-size: $font-size-xs;
- color: $text-tertiary;
- margin-top: $space-2;
-}
-
-// ============================================
-// WP-CLI TERMINAL
-// ============================================
-
-.wpcli-terminal-modal {
- max-width: 700px;
- height: 560px;
- display: flex;
- flex-direction: column;
-}
-
-.wpcli-quick-actions {
- display: flex;
- flex-wrap: wrap;
- gap: $space-1;
- padding: $space-2 $space-4;
- border-bottom: 1px solid $border-subtle;
- background: $bg-tertiary;
-}
-
-.wpcli-history {
- border-bottom: 1px solid $border-subtle;
- max-height: 200px;
- overflow-y: auto;
-}
-
-.wpcli-history-item {
- display: block;
- width: 100%;
- padding: $space-2 $space-4;
- border: none;
- background: none;
- text-align: left;
- cursor: pointer;
- border-bottom: 1px solid $border-subtle;
-
- &:last-child {
- border-bottom: none;
- }
-
- &:hover {
- background: $bg-hover;
- }
-
- code {
- font-family: $font-family-mono;
- font-size: $font-size-xs;
- color: $text-primary;
- }
-}
-
-.wpcli-output {
- flex: 1;
- overflow-y: auto;
- padding: $space-3;
- background: $bg-body;
- font-family: $font-family-mono;
- font-size: 12px;
- line-height: 1.6;
-}
-
-.wpcli-output-empty {
- color: $text-tertiary;
- text-align: center;
- padding: $space-6;
- font-size: $font-size-sm;
-}
-
-.wpcli-output-command {
- display: flex;
- gap: $space-2;
- color: $color-primary;
- margin-top: $space-2;
-
- &:first-child {
- margin-top: 0;
- }
-}
-
-.wpcli-output-text {
- margin: 0;
- color: $text-secondary;
- white-space: pre-wrap;
- word-break: break-all;
-}
-
-.wpcli-output-error {
- margin: 0;
- color: $color-danger;
- white-space: pre-wrap;
- word-break: break-all;
-}
-
-.wpcli-prompt {
- color: $color-success;
- font-weight: $font-weight-bold;
- user-select: none;
-}
-
-.wpcli-executing {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-2 0;
- color: $text-tertiary;
- font-size: $font-size-xs;
-}
-
-.wpcli-input-row {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-2 $space-3;
- border-top: 1px solid $border-subtle;
- background: $bg-elevated;
-}
-
-.wpcli-input {
- flex: 1;
- border: none;
- background: none;
- font-family: $font-family-mono;
- font-size: $font-size-sm;
- color: $text-primary;
- outline: none;
- padding: $space-1 0;
-
- &::placeholder {
- color: $text-tertiary;
- }
-}
-
-// ============================================
-// HEALTH STATUS PANEL
-// ============================================
-
-.health-status-panel {
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-lg;
- padding: $space-4;
-}
-
-.health-panel-loading {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: $space-2;
- padding: $space-6;
- color: $text-tertiary;
- font-size: $font-size-sm;
-}
-
-.health-panel-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- margin-bottom: $space-4;
-
- h4 {
- display: flex;
- align-items: center;
- gap: $space-2;
- margin: 0;
- font-size: $font-size-base;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- }
-}
-
-.health-panel-grid {
- display: flex;
- flex-direction: column;
- gap: $space-3;
-}
-
-.health-panel-env {
- padding: $space-3;
- background: $bg-tertiary;
- border-radius: $radius-md;
-}
-
-.health-panel-env-header {
- display: flex;
- align-items: center;
- gap: $space-2;
- margin-bottom: $space-2;
-}
-
-.health-panel-env-name {
- flex: 1;
- font-size: $font-size-sm;
- font-weight: $font-weight-semibold;
- color: $text-primary;
-}
-
-.health-panel-overall {
- font-size: $font-size-xs;
- font-weight: $font-weight-medium;
- padding: 2px 8px;
- border-radius: $radius-sm;
-
- &.health-healthy {
- background: fade($success-raw, 12%);
- color: $color-success;
- }
- &.health-degraded {
- background: fade($warning-raw, 12%);
- color: $color-warning;
- }
- &.health-unhealthy {
- background: fade($danger-raw, 12%);
- color: $color-danger;
- }
- &.health-unknown {
- background: fade($text-tertiary-raw, 12%);
- color: $text-tertiary;
- }
-}
-
-.health-panel-checks {
- display: flex;
- flex-direction: column;
- gap: $space-1;
-}
-
-.health-panel-check {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-1 0;
- font-size: $font-size-xs;
-}
-
-.health-panel-check-name {
- font-weight: $font-weight-medium;
- color: $text-secondary;
- min-width: 80px;
-}
-
-.health-panel-check-msg {
- color: $text-tertiary;
-}
-
-.health-panel-empty {
- text-align: center;
- padding: $space-6;
- color: $text-tertiary;
- font-size: $font-size-sm;
-}
-
-.health-dot {
- flex-shrink: 0;
-}
-
-// ============================================
-// DISK USAGE BAR
-// ============================================
-
-.disk-usage-compact {
- display: inline-flex;
- align-items: center;
- gap: 4px;
- font-size: $font-size-xs;
- color: $text-tertiary;
-}
-
-.disk-usage-compact-text {
- font-family: $font-family-mono;
-}
-
-.disk-usage-bar-container {
- padding: $space-3;
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
-}
-
-.disk-usage-header {
- display: flex;
- align-items: center;
- gap: $space-2;
- margin-bottom: $space-2;
- font-size: $font-size-sm;
- color: $text-primary;
-}
-
-.disk-usage-total {
- font-weight: $font-weight-semibold;
- font-family: $font-family-mono;
-}
-
-.disk-usage-bar {
- display: flex;
- height: 8px;
- border-radius: 4px;
- overflow: hidden;
- background: $bg-tertiary;
-}
-
-.disk-usage-segment {
- height: 100%;
- transition: width 0.3s ease;
-
- &.wordpress {
- &.green { background: $color-success; }
- &.yellow { background: $color-warning; }
- &.red { background: $color-danger; }
- }
-
- &.mysql {
- background: $color-info;
- }
-
- &.snapshots {
- background: fade($text-tertiary-raw, 30%);
- }
-}
-
-.disk-usage-legend {
- display: flex;
- flex-wrap: wrap;
- gap: $space-3;
- margin-top: $space-2;
-}
-
-.disk-usage-legend-item {
- display: flex;
- align-items: center;
- gap: 4px;
- font-size: $font-size-xs;
- color: $text-tertiary;
-}
-
-.disk-usage-legend-dot {
- width: 8px;
- height: 8px;
- border-radius: 2px;
-
- &.wordpress { background: $color-success; }
- &.mysql { background: $color-info; }
- &.snapshots { background: fade($text-tertiary-raw, 30%); }
-}
-
-// ============================================
-// AUTO-SYNC MODAL
-// ============================================
-
-.auto-sync-modal {
- max-width: 480px;
-}
-
-.auto-sync-loading {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: $space-2;
- padding: $space-6;
- color: $text-tertiary;
- font-size: $font-size-sm;
-}
-
-.auto-sync-body {
- padding: $space-4 0;
-}
-
-.auto-sync-env-name {
- font-size: $font-size-sm;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- padding-bottom: $space-3;
- border-bottom: 1px solid $border-subtle;
- margin-bottom: $space-3;
-}
-
-.auto-sync-toggle {
- margin-bottom: $space-4;
-}
-
-.auto-sync-toggle-label {
- display: flex;
- align-items: center;
- justify-content: space-between;
- cursor: pointer;
-
- span {
- font-size: $font-size-sm;
- font-weight: $font-weight-medium;
- color: $text-primary;
- }
-}
-
-.auto-sync-description {
- font-size: $font-size-xs;
- color: $text-tertiary;
- margin: $space-1 0 0;
-}
-
-.auto-sync-presets {
- display: flex;
- flex-direction: column;
- gap: $space-2;
-}
-
-.auto-sync-cron-display {
- font-family: $font-family-mono;
- font-size: $font-size-xs;
- color: $text-tertiary;
-}
-
-.auto-sync-cron-input {
- font-family: $font-family-mono;
-}
-
-.auto-sync-next-runs {
- margin-top: $space-4;
- padding: $space-3;
- background: $bg-tertiary;
- border-radius: $radius-md;
-
- h5 {
- margin: 0 0 $space-2;
- font-size: $font-size-xs;
- font-weight: $font-weight-semibold;
- color: $text-secondary;
- text-transform: uppercase;
- letter-spacing: 0.5px;
- }
-
- ul {
- list-style: none;
- margin: 0;
- padding: 0;
- }
-
- li {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-1 0;
- font-size: $font-size-xs;
- color: $text-secondary;
-
- svg {
- color: $text-tertiary;
- }
- }
-}
-
-// ============================================
-// BULK ACTIONS BAR
-// ============================================
-
-.bulk-actions-bar {
- display: flex;
- align-items: center;
- gap: $space-3;
- padding: $space-3 $space-4;
- background: fade($accent-primary-raw, 8%);
- border: 1px solid fade($accent-primary-raw, 20%);
- border-radius: $radius-md;
- margin-bottom: $space-4;
-}
-
-.bulk-actions-info {
- display: flex;
- align-items: center;
- gap: $space-1;
- font-size: $font-size-sm;
- color: $text-secondary;
-}
-
-.bulk-actions-count {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- min-width: 24px;
- height: 24px;
- padding: 0 6px;
- background: $color-primary;
- color: white;
- border-radius: 12px;
- font-size: $font-size-xs;
- font-weight: $font-weight-bold;
-}
-
-.bulk-actions-buttons {
- display: flex;
- gap: $space-1;
- flex: 1;
-}
-
-.bulk-actions-clear {
- color: $text-tertiary !important;
-}
-
-.bulk-actions-confirm {
- display: flex;
- align-items: center;
- gap: $space-3;
- width: 100%;
-
- span {
- flex: 1;
- font-size: $font-size-sm;
- color: $text-primary;
- font-weight: $font-weight-medium;
- }
-}
-
-// ============================================
-// OPERATION PROGRESS
-// ============================================
-
-.operation-progress-content {
- flex: 1;
- display: flex;
- flex-direction: column;
- gap: $space-2;
-}
-
-.operation-progress {
- display: flex;
- flex-direction: column;
- gap: $space-1;
-}
-
-.operation-progress-bar {
- height: 4px;
- background: fade($info-raw, 20%);
- border-radius: 2px;
- overflow: hidden;
-}
-
-.operation-progress-fill {
- height: 100%;
- background: $color-info;
- border-radius: 2px;
- transition: width 0.3s ease;
-}
-
-.operation-progress-step {
- font-size: $font-size-xs;
- color: $text-tertiary;
-}
-
-// ============================================
-// HEALTH TAB
-// ============================================
-
-.health-tab {
- padding: $space-4 0;
-}
-
-// ============================================
-// RESPONSIVE
-// ============================================
-
-@media (max-width: 900px) {
- .pipeline-row {
- flex-direction: column;
- align-items: stretch;
-
- .pipeline-card {
- max-width: none;
- }
- }
-
- .pipeline-arrow {
- min-width: auto;
- padding: $space-2 0;
-
- .pipeline-arrow-btn {
- flex-direction: row;
- }
-
- svg {
- transform: rotate(90deg);
- }
- }
-
- .pipeline-sync-row {
- flex-direction: column;
-
- .pipeline-sync-action {
- max-width: none;
- }
- }
-
- .bulk-actions-bar {
- flex-wrap: wrap;
- }
-
- .bulk-actions-buttons {
- flex-wrap: wrap;
- }
-}
-
-// ============================================
-// PROMOTION HISTORY (pipeline tab, with rollback)
-// ============================================
-.pipeline-promotion-history {
- margin-top: $space-6;
-
- .promotion-history-list {
- display: flex;
- flex-direction: column;
- gap: $space-2;
- margin-top: $space-3;
- }
-
- .promotion-history-item {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: $space-3;
- padding: $space-3 $space-4;
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- }
-
- .promotion-history-main {
- display: flex;
- align-items: center;
- gap: $space-3;
- flex-wrap: wrap;
- font-size: $font-size-sm;
- }
-
- .promotion-route {
- display: inline-flex;
- align-items: center;
- gap: $space-1;
- color: $text-primary;
- font-weight: $font-weight-medium;
- }
-
- .promotion-type,
- .promotion-date {
- color: $text-tertiary;
- font-size: $font-size-xs;
- }
-
- .promotion-status {
- text-transform: capitalize;
- font-size: $font-size-xs;
- font-weight: $font-weight-medium;
- padding: 2px 8px;
- border-radius: $radius-sm;
- background: fade($info-raw, 12%);
- color: $color-info;
-
- &.promotion-status-completed {
- background: fade($success-raw, 12%);
- color: $color-success;
- }
-
- &.promotion-status-failed {
- background: fade($danger-raw, 12%);
- color: $color-danger;
- }
-
- &.promotion-status-rolled_back {
- background: fade($warning-raw, 12%);
- color: $color-warning;
- }
- }
-}
diff --git a/frontend/src/plugins/serverkit-wordpress/styles/wordpress-plugin-library.scss b/frontend/src/plugins/serverkit-wordpress/styles/wordpress-plugin-library.scss
deleted file mode 100644
index 40940ff6..00000000
--- a/frontend/src/plugins/serverkit-wordpress/styles/wordpress-plugin-library.scss
+++ /dev/null
@@ -1,185 +0,0 @@
-// Compiled through the extension's module graph (imported by index.jsx).
-// The host's design-token partial is imported via a sync-safe relative
-// path — the baked copy lives at frontend/src/plugins/serverkit-wordpress/,
-// so this resolves to frontend/src/styles/_variables.scss.
-@import '../../../styles/variables';
-
-// 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/plugins/serverkit-wordpress/styles/wordpress.scss b/frontend/src/plugins/serverkit-wordpress/styles/wordpress.scss
deleted file mode 100644
index a3fb3b97..00000000
--- a/frontend/src/plugins/serverkit-wordpress/styles/wordpress.scss
+++ /dev/null
@@ -1,3376 +0,0 @@
-// Compiled through the extension's module graph (imported by index.jsx).
-// The host's design-token partial is imported via a sync-safe relative
-// path — the baked copy lives at frontend/src/plugins/serverkit-wordpress/,
-// so this resolves to frontend/src/styles/_variables.scss.
-@import '../../../styles/variables';
-
-// ============================================
-// WORDPRESS PAGE STYLES
-// ============================================
-
-// WordPress Standalone Page (Docker-based, mirrors Git page layout)
-.wordpress-standalone-page {
- // Inherits .git-page styles for layout, status cards, overview tab, etc.
-
- .empty-state-large {
- .empty-icon svg {
- stroke: $color-wordpress;
- }
- }
-
- .status-card.success {
- border-left-color: $color-success;
-
- .status-icon {
- color: $color-success;
- }
- }
-
- .status-card.danger {
- border-left-color: $color-danger;
-
- .status-icon {
- color: $color-danger;
- }
- }
-}
-
-// WordPress Page Layout (extends Docker page styles)
-.wordpress-page {
- .empty-state-large {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: 60px $space-6;
- background: $bg-card;
- border-radius: $radius-xl;
- text-align: center;
- margin: 0 $space-4;
-
- .empty-icon {
- color: $text-tertiary;
- margin-bottom: $space-6;
-
- svg {
- stroke: $color-wordpress;
- }
- }
-
- h2 {
- margin: 0 0 $space-3 0;
- font-size: $font-size-2xl;
- font-weight: $font-weight-semibold;
- }
-
- p {
- margin: 0 0 $space-6 0;
- color: $text-secondary;
- max-width: 460px;
- }
- }
-
- .install-warning {
- display: flex;
- gap: $space-3;
- padding: $space-4;
- background: fade($warning-raw, 8%);
- border: 1px solid fade($warning-raw, 20%);
- border-radius: $radius-md;
- margin-bottom: $space-4;
-
- > svg {
- flex-shrink: 0;
- color: $color-warning;
- margin-top: 2px;
- }
-
- strong {
- display: block;
- margin-bottom: $space-2;
- }
-
- ul {
- margin: 0;
- padding-left: $space-4;
- color: $text-secondary;
- font-size: $font-size-sm;
-
- li {
- margin-bottom: $space-1;
- }
- }
- }
-
- .form-hint {
- display: block;
- font-size: $font-size-xs;
- color: $text-tertiary;
- margin-top: $space-1;
- }
-
- .docker-empty {
- .wp-empty-icon {
- color: $text-tertiary;
- margin-bottom: $space-4;
-
- svg {
- stroke: currentColor;
- }
- }
- }
-}
-
-// Sites Grid
-.wp-sites-grid {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
- gap: $space-4;
- padding: $space-4;
-}
-
-// Redesign: dense WordPress site table (replaces the .wp-site-card grid).
-.wp-list {
- padding: $space-4;
-
- &__toolbar {
- display: flex;
- align-items: center;
- gap: $space-3;
- flex-wrap: wrap;
- margin-bottom: $space-3;
-
- .wp-tag-filter { margin: 0; }
- }
-
- // Client-side site search (name / title / domain). Mirrors the demo's
- // .input: leading icon + borderless field on a quiet surface.
- &__search {
- display: inline-flex;
- align-items: center;
- gap: $space-2;
- margin-left: auto;
- padding: 0 10px;
- width: 240px;
- max-width: 100%;
- height: 32px;
- background: var(--surface-2);
- border: 1px solid var(--border-soft);
- border-radius: 8px;
- color: var(--text-faint);
- transition: border-color 0.14s;
-
- &:focus-within { border-color: var(--accent-dim); }
-
- svg { flex-shrink: 0; }
-
- input {
- flex: 1;
- min-width: 0;
- border: none;
- background: none;
- color: var(--text);
- font-size: 13px;
-
- &::placeholder { color: var(--text-faint); }
- &:focus { outline: none; }
- }
- }
-
- // Count subtitle accent ("M running") in the PageTopbar meta slot.
- &__meta-running { color: var(--green); }
-
- // Table/cards switch — only rendered by pages that pass a card renderer to
- // ResourceListPage. It claims the free space so it stays right-aligned on
- // pages whose search lives in the top bar instead (Services); where a
- // toolbar search IS present that element already claims it, so the switch
- // gives the margin back and simply trails it.
- &__viewswitch {
- display: flex;
- gap: 2px;
- flex-shrink: 0;
- margin-left: auto;
- padding: 3px;
- background: var(--surface-2);
- border: 1px solid var(--border);
- border-radius: 9px;
-
- button {
- display: grid;
- place-items: center;
- padding: 6px 9px;
- background: none;
- border: none;
- border-radius: 6px;
- color: var(--text-faint);
- cursor: pointer;
- transition: background 0.14s, color 0.14s;
-
- &:hover { color: var(--text); }
- &.is-active { background: var(--surface-3); color: var(--text); }
- }
- }
-
- &__search + &__viewswitch { margin-left: 0; }
-
- // Card layout for the same rows the table shows.
- &__cards {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
- gap: 14px;
- }
-
- &__cardtile {
- display: flex;
- flex-direction: column;
- padding: $space-4;
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- cursor: pointer;
- transition: border-color 0.14s, transform 0.14s;
-
- &:hover { border-color: var(--border-strong); transform: translateY(-2px); }
- &.is-selected { border-color: var(--accent-dim); background: var(--accent-bg-soft); }
- }
-
- // bulk-select bar (demo's bulkbar) — appears once any row is checked
- &__bulkbar {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: $space-3;
- flex-wrap: wrap;
- padding: $space-2 $space-4;
- margin-bottom: $space-3;
- background: var(--accent-bg-soft);
- border: 1px solid var(--accent-dim);
- border-radius: var(--radius);
- }
-
- &__bulkcount {
- font-family: var(--mono);
- font-size: 12px;
- font-weight: $font-weight-medium;
- color: var(--accent-bright);
- }
-
- &__bulkactions {
- display: flex;
- align-items: center;
- gap: $space-2;
- flex-wrap: wrap;
- }
-
- &__ck {
- width: 36px;
- padding-right: 0;
- }
-
- &__action { width: 70px; }
-
- &__card {
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- overflow: hidden;
- }
-
- // Per-site gradient initial avatar (ds ServiceTile / .sk-tile). The tile
- // brings its own size + hue-hashed gradient inline; we only soften the
- // corner to the demo's small rounded-square look.
- &__tile {
- border-radius: 8px;
- }
-
- &__links {
- display: inline-flex;
- gap: $space-2;
-
- a {
- display: inline-flex;
- color: var(--text-faint);
- transition: color 0.14s;
- &:hover { color: var(--accent-bright); }
- }
- }
-
- &__dash { color: var(--text-ghost); font-family: var(--mono); font-size: 12px; }
- &__chev { color: var(--text-ghost); }
-
- .sk-tag + .sk-tag { margin-left: 4px; }
-}
-
-// Site tags / labels (chips + filter bar)
-.wp-tag-filter {
- display: flex;
- flex-wrap: wrap;
- gap: $space-2;
- margin: 0 $space-4 $space-4;
-}
-
-.wp-site-tags {
- display: flex;
- flex-wrap: wrap;
- gap: $space-1;
- margin-top: $space-3;
-}
-
-.wp-tag-chip {
- display: inline-flex;
- align-items: center;
- padding: 2px 10px;
- font-size: $font-size-xs;
- line-height: 1.4;
- border-radius: $radius-full;
- background: $bg-tertiary;
- color: $text-secondary;
- border: 1px solid $border-subtle;
-
- &--filter {
- cursor: pointer;
- background: $bg-card;
-
- &.is-active {
- background: $color-primary;
- color: #fff;
- border-color: $color-primary;
- }
- }
-}
-
-// Site Card
-.wp-site-card {
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-lg;
- cursor: pointer;
- transition: all 0.15s ease;
-
- &:hover {
- border-color: $border-hover;
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
- }
-}
-
-.wp-site-card-header {
- display: flex;
- align-items: center;
- gap: $space-3;
- padding: $space-4;
- border-bottom: 1px solid $border-subtle;
-}
-
-.wp-site-icon {
- width: 40px;
- height: 40px;
- background: $color-wordpress;
- border-radius: $radius-md;
- display: flex;
- align-items: center;
- justify-content: center;
- color: #fff;
- flex-shrink: 0;
-}
-
-.wp-site-info {
- flex: 1;
- min-width: 0;
-}
-
-.wp-site-name {
- font-size: $font-size-base;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- margin: 0;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.wp-site-url {
- font-size: $font-size-xs;
- color: $text-tertiary;
- font-family: $font-family-mono;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- display: block;
-}
-
-.wp-site-status {
- display: flex;
- align-items: center;
- gap: 6px;
- font-size: $font-size-xs;
- padding: 4px 10px;
- border-radius: $radius-full;
- font-weight: $font-weight-medium;
-
- .status-dot {
- width: 6px;
- height: 6px;
- border-radius: 50%;
- }
-
- &.running {
- background: fade($success-raw, 12%);
- color: $color-success;
-
- .status-dot {
- background: $color-success;
- }
- }
-
- &.stopped {
- background: fade($text-tertiary-raw, 12%);
- color: $text-tertiary;
-
- .status-dot {
- background: $text-tertiary;
- }
- }
-}
-
-.wp-site-card-body {
- padding: $space-4;
-}
-
-.wp-site-meta {
- display: grid;
- grid-template-columns: repeat(2, 1fr);
- gap: $space-3;
-}
-
-.wp-site-meta-item {
- .meta-label {
- display: block;
- font-size: $font-size-xs;
- color: $text-tertiary;
- margin-bottom: 2px;
- }
-
- .meta-value {
- font-size: $font-size-sm;
- color: $text-primary;
- font-weight: $font-weight-medium;
-
- &.git-connected {
- color: $color-success;
- }
- }
-}
-
-.wp-site-badge {
- display: inline-block;
- font-size: $font-size-xs;
- font-weight: $font-weight-medium;
- padding: 2px 8px;
- border-radius: $radius-sm;
- margin-top: $space-3;
-
- &.production {
- background: fade($danger-raw, 12%);
- color: $color-danger;
- }
-
- &.development {
- background: fade($info-raw, 12%);
- color: $color-info;
- }
-}
-
-.wp-site-card-links {
- display: flex;
- gap: $space-3;
- margin-top: $space-3;
- padding-top: $space-3;
- border-top: 1px solid $border-subtle;
-}
-
-.wp-site-link {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- font-size: $font-size-xs;
- font-weight: $font-weight-medium;
- color: $color-primary;
- text-decoration: none;
-
- &:hover {
- text-decoration: underline;
- }
-}
-
-.wp-site-card-footer {
- display: flex;
- gap: $space-2;
- padding: $space-3 $space-4;
- border-top: 1px solid $border-subtle;
- background: $bg-tertiary;
- border-radius: 0 0 $radius-lg $radius-lg;
-
- .btn {
- flex: 1;
- justify-content: center;
-
- &.btn-danger {
- flex: 0;
- color: $color-danger;
-
- &:hover {
- background: fade($danger-raw, 10%);
- }
- }
- }
-}
-
-// ============================================
-// WORDPRESS DETAIL PAGE (redesign — infra console look)
-// ============================================
-// Everything here is scoped under .wp-detail-page on purpose: the base
-// `app-*` classes (.app-panel, .app-info-grid, .app-detail-tabs, …) live in
-// _applications.scss and are ALSO rendered by the Applications detail page,
-// which keeps its current look until its own pass. Same pattern as the
-// `.server-detail-page` block in _servers.scss.
-
-// Run the detail page FULL-BLEED, like the WordPress list page: drop the
-// .main-content 40px frame so the .sk-topbar spans edge-to-edge. (Unlike the
-// generic full-bleed rule in _main-content.scss, we keep the normal scroll —
-// no height:100vh/overflow:hidden — because this is a long scrolling page, not
-// a self-managing two-pane tool.) .app-detail-body re-pads the content below.
-.main-content:has(.wp-detail-page) {
- padding: 0;
-
- // padding:0 also drops the base rule's mobile top-clearance, so restore it
- // (the fixed mobile header would otherwise overlap the top bar).
- @media (max-width: $breakpoint-md) {
- margin-top: calc(#{$mobile-header-height} + env(safe-area-inset-top));
- }
-}
-
-.wp-detail-page {
- // The full-bleed top bar sits flush above the padded body (no page gap).
- gap: 0;
-
- // Content below the full-bleed top bar: a CENTERED max-width column (like the
- // prototype), laid out as a flex column so identity / tabs / content are
- // evenly spaced (fixes the tab-touches-content gap).
- .app-detail-body {
- display: flex;
- flex-direction: column;
- gap: $space-5;
- width: 100%;
- max-width: 1200px;
- margin-inline: auto;
- padding: $space-6 $space-6 $space-10;
- }
-
- // ---- Breadcrumbs (mono trail) ----
- .app-detail-breadcrumbs {
- font-family: var(--mono);
- font-size: $font-size-sm;
-
- a {
- color: var(--text-faint);
-
- &:hover {
- color: var(--accent-bright);
- }
- }
-
- > span {
- color: var(--text-ghost);
- }
-
- .current {
- color: var(--text-dim);
- font-weight: $font-weight-medium;
- }
- }
-
- // ---- Header (demo .site-header: gradient surface + accent wash) ----
- // Identity row — NO card background (matches the prototype): just the icon +
- // name + status sitting directly on the page.
- .app-detail-header {
- position: relative;
- gap: $space-4;
- padding: 4px 0 0;
- background: none;
- border: none;
- border-radius: 0;
- }
-
- // The detail page uses the canonical PageTopbar (.sk-topbar) for its top bar
- // so the chrome matches the WordPress LIST page and every other page. Tweaks:
- // a breadcrumb title and a compact, wrapping action cluster (the detail page
- // carries more actions than a typical page).
- .wp-detail-topbar {
- // Full-bleed now that .main-content has no padding; match the list page's
- // sk-topbar inset. Many actions, so wrap the bar as a whole instead of
- // squeezing the title (which made the breadcrumb collide with a button).
- padding: 10px $space-4;
- flex-wrap: wrap;
- row-gap: 8px;
-
- // The bar's flex:1 spacer would force the actions onto their own line
- // every time; drop it and push the cluster right with margin instead, so
- // the actions sit beside the title when they fit and wrap only when not.
- .sk-topbar__spacer { display: none; }
-
- .sk-topbar__titles { flex-shrink: 0; }
-
- .wp-crumbs {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- white-space: nowrap;
-
- a {
- color: var(--text-dim);
- text-decoration: none;
- &:hover { color: var(--accent-bright); }
- }
- &__sep { color: var(--text-ghost); }
- &__cur { color: var(--text); }
- }
-
- .sk-topbar__actions {
- margin-left: auto;
- flex-wrap: wrap;
- justify-content: flex-end;
- row-gap: 6px;
-
- .ui-button {
- height: 32px;
- padding: 0 10px;
- font-size: 12.5px;
- gap: 6px;
- }
- }
- }
-
- // Overview top grid: Site information (left) + Traffic chart (right), matching
- // the mockup's ~40/60 split; collapses to one column on narrow screens.
- .wp-overview-main {
- display: grid;
- grid-template-columns: minmax(300px, 0.85fr) 1.15fr;
- gap: $space-4;
- margin-bottom: $space-4;
-
- @media (max-width: $breakpoint-lg) {
- grid-template-columns: 1fr;
- }
- }
-
- // Traffic panel: stack the title over a muted mono sub-label.
- .wp-traffic-panel {
- .app-panel-header {
- flex-direction: column;
- align-items: flex-start;
- gap: 2px;
- }
- .wp-panel-sub {
- font-family: var(--mono);
- font-size: 11px;
- font-weight: $font-weight-normal;
- letter-spacing: 0;
- text-transform: none;
- color: var(--text-faint);
- }
- }
-
- // Recent activity spans full width beneath the main grid.
- .wp-activity-panel { margin-bottom: $space-4; }
-
- // WP detail carries more tabs than fit one row at common widths, so let the
- // strip WRAP instead of scrolling — otherwise the right-pinned Settings tab
- // gets pushed off-screen and becomes unreachable.
- .app-detail-tabs {
- flex-wrap: wrap;
- overflow-x: visible;
- row-gap: 2px;
- }
-
- // Settings tab pinned to the far right of the tab strip (the mockup's gear).
- .app-detail-tab--end { margin-left: auto; }
-
- // Settings tab — left sub-nav + content (PHP, Updates, …).
- .wp-settings {
- display: grid;
- grid-template-columns: 200px 1fr;
- gap: $space-4;
- align-items: start;
-
- @media (max-width: $breakpoint-md) {
- grid-template-columns: 1fr;
- }
- }
-
- .wp-settings__nav {
- display: flex;
- flex-direction: column;
- gap: 2px;
- position: sticky;
- top: $space-4;
-
- @media (max-width: $breakpoint-md) {
- position: static;
- flex-direction: row;
- flex-wrap: wrap;
- }
- }
-
- .wp-settings__navitem {
- display: flex;
- width: 100%; // fill the nav column — a flex <button> otherwise shrinks
- // to its label, so each item's box was a different width
- align-items: center;
- gap: 9px;
- padding: 9px 12px;
- border: none;
- border-radius: 8px;
- background: none;
- color: var(--text-dim);
- font-size: 13.5px;
- font-weight: $font-weight-medium;
- text-align: left;
- cursor: pointer;
- transition: background 0.14s, color 0.14s;
-
- svg { color: var(--text-faint); flex-shrink: 0; }
-
- &:hover { background: var(--surface-hover); color: var(--text); }
- &.is-active {
- background: var(--accent-bg);
- color: var(--accent-bright);
- svg { color: var(--accent-bright); }
- }
- }
-
- .wp-settings__content { min-width: 0; }
-
- // Grouped left nav — an uppercase mono label per group (the sidebar-style
- // "group section" the user asked for).
- .wp-settings__group + .wp-settings__group { margin-top: $space-4; }
-
- .wp-settings__grouplabel {
- padding: 0 12px;
- margin-bottom: 6px;
- font-family: var(--mono);
- font-size: 10px;
- font-weight: $font-weight-semibold;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--text-faint);
- }
-
- .app-detail-icon {
- position: relative;
- width: 52px;
- height: 52px;
- border-radius: 13px;
- border: 1px solid fade(#fff, 8%);
- box-shadow: var(--shadow-sm);
- }
-
- .wp-icon {
- background: linear-gradient(150deg, lighten($color-wordpress, 12%), $color-wordpress) !important;
- }
-
- // Status dot pinned to the favicon corner (demo .site-favicon .badge)
- .wp-head-dot {
- position: absolute;
- bottom: -4px;
- right: -4px;
- width: 14px;
- height: 14px;
- border-radius: 50%;
- border: 2.5px solid var(--surface);
- background: var(--text-faint);
-
- &.running {
- background: var(--green);
- }
-
- &.stopped {
- background: var(--red);
- }
- }
-
- .app-detail-title-block h1 {
- font-size: 21px;
- font-weight: $font-weight-semibold;
- letter-spacing: -0.02em;
- gap: 14px;
- flex-wrap: wrap;
- align-items: center;
- }
-
- .app-detail-subtitle {
- display: flex;
- align-items: center;
- gap: 9px;
- flex-wrap: wrap;
- margin-top: 4px;
- font-family: var(--mono);
- font-size: 12px;
- color: var(--text-dim);
-
- a {
- color: var(--accent-bright);
- text-decoration: none;
-
- &:hover {
- text-decoration: underline;
- }
- }
-
- .separator {
- color: var(--text-ghost);
- }
- }
-
- // ---- Repo connection pill (mirrors service detail page) ----
- .wp-detail__repo-bar {
- display: flex;
- margin-top: -#{$space-2}; // tuck it up under the identity header a bit
- }
-
- .wp-detail__repo-pill {
- display: inline-flex;
- align-items: center;
- gap: $space-2;
- padding: 6px $space-3;
- background: var(--surface);
- border: 1px solid var(--border);
- border-radius: $radius-full;
- font-family: var(--mono);
- font-size: $font-size-sm;
- color: var(--text-dim);
- cursor: pointer;
- transition: border-color $transition-fast, background $transition-fast;
-
- svg { color: var(--text-faint); }
-
- &:hover {
- border-color: var(--accent-dim);
- background: var(--surface-2);
- }
- }
-
- .wp-detail__repo-url {
- font-size: $font-size-sm;
- color: $text-primary;
- }
-
- .wp-detail__repo-arrow {
- color: var(--text-ghost);
- }
-
- .wp-detail__repo-branch {
- font-size: $font-size-sm;
- color: var(--accent-bright);
- font-weight: $font-weight-medium;
- }
-
- .wp-detail__auto-deploy-badge {
- font-family: var(--mono);
- font-size: 10px;
- font-weight: $font-weight-semibold;
- letter-spacing: 0.05em;
- text-transform: uppercase;
- padding: 1px 6px;
- background: var(--green-bg);
- color: var(--green);
- border-radius: $radius-sm;
- }
-
- .wp-detail__connect-repo {
- display: inline-flex;
- align-items: center;
- gap: $space-2;
- padding: 6px $space-3;
- background: none;
- border: 1px dashed var(--border-strong);
- border-radius: $radius-full;
- font-size: $font-size-sm;
- color: var(--text-faint);
- cursor: pointer;
- transition: all $transition-fast;
-
- svg { color: var(--text-faint); }
-
- &:hover {
- border-color: var(--accent-dim);
- color: var(--accent-bright);
- background: var(--accent-bg-soft);
- }
- }
-
- // ---- Tab strip (segmented bar — pills in a bordered surface, matching the
- // shared .app-detail-tabs treatment in _applications.scss so every detail
- // page's nav reads the same) ----
- .app-detail-tabs {
- gap: 3px;
- background: var(--surface);
- border: 1px solid var(--border);
- border-radius: var(--radius);
- padding: 4px;
- overflow-x: auto;
-
- &::-webkit-scrollbar {
- height: 0;
- }
- }
-
- .app-detail-tab {
- display: flex;
- align-items: center;
- gap: 7px;
- padding: 8px 13px;
- border-radius: 7px;
- color: var(--text-dim);
- font-size: 13px;
- font-weight: $font-weight-medium;
- white-space: nowrap;
- transition: color 0.14s, background 0.14s;
-
- svg {
- color: var(--text-faint);
- transition: color 0.14s;
- flex-shrink: 0;
- }
-
- &:hover {
- background: var(--surface-2);
- color: var(--text);
-
- svg {
- color: var(--text-dim);
- }
- }
-
- &.active {
- background: var(--accent-bg);
- color: var(--accent-bright);
- font-weight: $font-weight-semibold;
-
- svg {
- color: var(--accent-bright);
- }
- }
- }
-
- // ---- Panels (quiet surface + mono eyebrow header) ----
- .app-panel {
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- }
-
- .app-panel-header {
- display: flex;
- align-items: center;
- justify-content: flex-start;
- gap: 7px;
- padding: 12px 17px;
- border-bottom: 1px solid var(--border-soft);
- font-family: var(--mono);
- font-size: 10.5px;
- font-weight: $font-weight-semibold;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--text-faint);
-
- svg {
- width: 13px;
- height: 13px;
- color: var(--accent-bright);
- }
- }
-
- .app-panel-body {
- padding: $space-4 17px;
-
- .hint:last-child {
- margin-bottom: 0;
- }
-
- .app-detail-actions {
- flex-wrap: wrap;
- align-items: center;
- margin-bottom: $space-3;
-
- &:last-child {
- margin-bottom: 0;
- }
- }
-
- .app-info-grid + .app-detail-actions,
- .app-info-grid + .hint {
- margin-top: $space-3;
- }
- }
-
- // Danger Zone panel — stack the rows with a gap so Archive and Delete don't
- // sit flush against each other.
- .danger-zone-body {
- display: flex;
- flex-direction: column;
- gap: $space-3;
-
- .danger-zone {
- margin-top: 0;
- }
- }
-
- // SSL guided flow — checklist + primary action.
- .ssl-guide {
- display: flex;
- flex-direction: column;
- gap: $space-3;
- margin-top: $space-3;
- }
-
- .ssl-checklist {
- display: flex;
- flex-direction: column;
- gap: $space-2;
- padding: $space-3;
- background: var(--surface-2);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- }
-
- .ssl-check-item {
- display: flex;
- align-items: center;
- gap: $space-2;
- font-size: $font-size-sm;
- color: var(--text-dim);
- }
-
- .ssl-check-icon {
- flex-shrink: 0;
-
- &--ok { color: var(--green); }
- &--missing { color: var(--amber); }
- }
-
- .ssl-check-label {
- &--ok { color: var(--text); }
- }
-
- // Inline domain attach inside the SSL panel — no modal needed.
- .ssl-inline-attach {
- display: flex;
- flex-direction: column;
- gap: $space-3;
- margin-top: $space-3;
- padding-top: $space-3;
- border-top: 1px solid var(--border-soft);
- }
-
- .ssl-context {
- display: flex;
- flex-direction: column;
- gap: $space-2;
- }
-
- .ssl-provider-status {
- display: inline-flex;
- align-items: center;
- gap: $space-2;
- font-size: $font-size-sm;
-
- &--ok {
- color: var(--green);
-
- svg { color: var(--green); }
- }
-
- &--missing {
- color: var(--amber);
-
- svg { color: var(--amber); }
- }
- }
-
- .ssl-context-links {
- display: flex;
- align-items: center;
- gap: $space-2;
- font-size: $font-size-xs;
- color: var(--text-faint);
-
- a {
- color: var(--accent-bright);
- text-decoration: none;
-
- &:hover { text-decoration: underline; }
- }
- }
-
- .ssl-attach-result {
- display: flex;
- flex-direction: column;
- gap: $space-3;
- margin-top: $space-3;
- padding: $space-3;
- background: var(--surface-2);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
-
- &__success {
- display: flex;
- align-items: center;
- gap: $space-2;
- font-size: $font-size-sm;
- color: var(--green);
-
- svg { color: var(--green); }
- }
-
- &__manual {
- display: flex;
- flex-direction: column;
- gap: $space-2;
- font-size: $font-size-sm;
- }
-
- &__record {
- display: block;
- padding: $space-2 $space-3;
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- font-family: var(--mono);
- font-size: $font-size-xs;
- color: var(--text);
- }
- }
-
- // ---- Info grids → k/v spec rows (.sk-info-row look, CSS-only) ----
- .app-info-grid {
- display: flex;
- flex-direction: column;
- gap: 0;
- }
-
- .app-info-item {
- flex-direction: row;
- justify-content: space-between;
- align-items: center;
- gap: $space-4;
- padding: 10px 0;
- border-top: 1px solid var(--border-soft);
-
- &:first-child {
- border-top: none;
- padding-top: 0;
- }
-
- &:last-child {
- padding-bottom: 0;
- }
- }
-
- .app-info-label {
- font-family: var(--mono);
- font-size: 12px;
- color: var(--text-faint);
- min-width: 0;
- overflow-wrap: anywhere;
- }
-
- .app-info-value {
- display: inline-flex;
- align-items: center;
- justify-content: flex-end;
- flex-wrap: wrap;
- gap: $space-2;
- font-family: var(--mono);
- font-size: 12.5px;
- color: var(--text);
- text-align: right;
- min-width: 0;
- overflow-wrap: anywhere;
-
- a {
- color: var(--accent-bright);
- text-decoration: none;
-
- &:hover {
- text-decoration: underline;
- }
- }
- }
-
- // ---- Section headers → mono eyebrows ----
- .section-header {
- margin-bottom: $space-4;
-
- h3 {
- display: flex;
- align-items: center;
- gap: 6px;
- margin: 0;
- font-family: var(--mono);
- font-size: 11px;
- font-weight: $font-weight-semibold;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--text-faint);
- }
- }
-
- // ---- KPI strip (ds MetricCard rows) ----
- .wp-kpis {
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
- gap: $space-4;
- }
-
- .wp-overview {
- display: flex;
- flex-direction: column;
- gap: $space-4;
- }
-
- // ---- Dense table chrome shared by plugins/themes/vulns ----
- .wp-asset-table,
- .wp-vuln-table {
- .sk-cell-name {
- font-size: 13px;
- }
-
- .sk-cell-sub {
- margin-top: 2px;
- }
- }
-
- .wp-vuln-title {
- font-size: 12.5px;
- color: var(--text-dim);
- max-width: 360px;
- overflow-wrap: anywhere;
- }
-
- // app-panel hosting a flush table (Findings)
- .app-panel > .sk-dtable {
- border-radius: 0 0 var(--radius) var(--radius);
- overflow: hidden;
- }
-
- // ---- Severity chips (prototype .sev / security ramp) ----
- .wp-sev {
- display: inline-flex;
- align-items: center;
- gap: 7px;
- font-family: var(--mono);
- font-size: 11px;
- font-weight: $font-weight-semibold;
- text-transform: uppercase;
- letter-spacing: 0.04em;
- white-space: nowrap;
-
- .d {
- width: 9px;
- height: 9px;
- border-radius: 3px;
- flex-shrink: 0;
- background: var(--text-ghost);
- }
-
- &--critical {
- color: var(--red);
-
- .d {
- background: var(--red);
- box-shadow: 0 0 6px var(--red);
- }
- }
-
- &--high {
- color: var(--red);
-
- .d {
- background: var(--red);
- }
- }
-
- &--medium {
- color: var(--amber);
-
- .d {
- background: var(--amber);
- }
- }
-
- &--low {
- color: var(--cyan);
-
- .d {
- background: var(--cyan);
- }
- }
-
- &--unknown {
- color: var(--text-faint);
-
- .d {
- background: var(--text-faint);
- }
- }
- }
-
- .wp-fix-chip {
- font-family: var(--mono);
- font-size: 10.5px;
- color: var(--accent-bright);
- background: var(--accent-bg);
- padding: 2px 7px;
- border-radius: 5px;
- white-space: nowrap;
- }
-
- .wp-no-fix {
- font-family: var(--mono);
- font-size: 11px;
- color: var(--text-faint);
- }
-
- .wp-advisory-link {
- font-family: var(--mono);
- font-size: 11.5px;
- color: var(--accent-bright);
- text-decoration: none;
-
- &:hover {
- text-decoration: underline;
- }
- }
-
- // ---- Update chips + bulk bar (amber wash, mono) ----
- .wp-update-badge {
- font-family: var(--mono);
- font-size: 10.5px;
- font-weight: $font-weight-medium;
- color: var(--amber);
- background: var(--amber-bg);
- padding: 2px 7px;
- border-radius: 5px;
- margin-left: $space-2;
- }
-
- .bulk-update-bar {
- background: var(--amber-bg);
- border: 1px solid fade($warning-raw, 25%);
- border-radius: var(--radius);
- font-family: var(--mono);
- font-size: 12px;
- color: var(--amber);
- }
-
- .install-form {
- margin-bottom: $space-4;
- }
-
- // ---- Security posture (ScoreGauge ring + checklist, demo Posture panel) ----
- .wp-posture {
- display: flex;
- align-items: center;
- gap: $space-6;
-
- &__checks {
- flex: 1;
- min-width: 0;
- }
-
- &__check {
- display: flex;
- align-items: center;
- gap: $space-3;
- padding: 10px 0;
- border-top: 1px solid var(--border-soft);
- font-size: 13px;
-
- &:first-child { border-top: none; }
- }
-
- &__label {
- flex: 1;
- min-width: 0;
- color: var(--text);
- }
-
- &__detail {
- font-family: var(--mono);
- font-size: 11.5px;
- color: var(--text-faint);
- white-space: nowrap;
- }
-
- @media (max-width: $breakpoint-md) {
- flex-direction: column;
- align-items: flex-start;
-
- &__checks { width: 100%; }
- }
- }
-
- // ---- Mono code well (integrity issue lines) ----
- .wp-code-list {
- margin-top: $space-3;
- padding: $space-3 $space-4;
- background: var(--bg-code);
- border: 1px solid var(--border-soft);
- border-radius: $radius-md;
- max-height: 320px;
- overflow-y: auto;
- font-family: var(--mono);
- font-size: 12px;
- line-height: 1.7;
- color: var(--text-code);
- overflow-wrap: anywhere;
- }
-
- // ---- Brute-force jail: banned-IP rows with an inline Unban action ----
- .wp-banlist {
- margin-top: $space-3;
- border: 1px solid var(--border-soft);
- border-radius: $radius-md;
- overflow: hidden;
- }
- .wp-banlist__row {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: $space-3;
- padding: 8px $space-4;
-
- & + & {
- border-top: 1px solid var(--border-soft);
- }
- }
- .wp-banlist__ip {
- font-family: var(--mono);
- font-size: 13px;
- color: var(--text-code);
- }
-
- // ---- Run-history / incident rows (Updates + Reports) ----
- .wp-run-row {
- display: flex;
- flex-direction: column;
- gap: 3px;
- padding: 11px 0;
- border-top: 1px solid var(--border-soft);
-
- &:first-child {
- border-top: none;
- padding-top: 0;
- }
-
- .form-hint {
- margin-top: 0;
- }
- }
-
- .wp-run-row-head {
- display: flex;
- align-items: center;
- gap: $space-2;
- flex-wrap: wrap;
-
- strong {
- font-size: 13px;
- }
- }
-
- .wp-run-row-meta {
- font-family: var(--mono);
- font-size: 11px;
- color: var(--text-faint);
- }
-
- .wp-run-component {
- font-family: var(--mono);
- }
-
- // ---- Analytics head (eyebrow + SegControl) ----
- .wp-analytics-banner {
- display: flex;
- align-items: center;
- gap: $space-3;
- margin-bottom: $space-4;
- padding: $space-3 $space-4;
- border: 1px solid rgba(129, 140, 248, 0.28);
- border-radius: var(--radius, 8px);
- background: rgba(129, 140, 248, 0.08);
- color: var(--text-primary);
- flex-wrap: wrap;
-
- svg { color: var(--accent-bright, #818cf8); flex-shrink: 0; }
-
- &__text { flex: 1 1 240px; font-size: 13px; line-height: 1.4; }
- &__text span { color: var(--text-secondary); }
-
- &__link {
- display: inline-flex;
- align-items: center;
- gap: 4px;
- white-space: nowrap;
- font-size: 13px;
- font-weight: $font-weight-semibold;
- color: var(--accent-bright, #818cf8);
- }
- }
-
- .wp-analytics-head {
- display: flex;
- justify-content: space-between;
- align-items: center;
- gap: $space-3;
- flex-wrap: wrap;
- }
-
- .wp-eyebrow {
- margin: 0;
- font-family: var(--mono);
- font-size: 11px;
- font-weight: $font-weight-semibold;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--text-faint);
- }
-
- // Recharts default tooltip → surface tokens (recharts inline-styles it)
- .recharts-default-tooltip {
- background: var(--surface-2) !important;
- border: 1px solid var(--border) !important;
- border-radius: var(--radius-sm);
- box-shadow: var(--shadow-md);
- font-family: var(--mono);
- font-size: 11.5px;
- }
-
- .recharts-tooltip-label {
- color: var(--text-faint) !important;
- }
-
- // ---- Report header actions keep normal type inside the eyebrow bar ----
- .wp-report-actions {
- font-family: $font-main;
- text-transform: none;
- letter-spacing: normal;
- }
-
- // ---- Commit list (scoped: Git.jsx renders .commit-item too) ----
- .commit-list {
- gap: 0;
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- overflow: hidden;
- max-width: 860px;
- }
-
- .commit-item {
- background: transparent;
- border: none;
- border-radius: 0;
- padding: 12px $space-4;
- transition: background 0.12s;
-
- & + .commit-item {
- border-top: 1px solid var(--border-soft);
- }
-
- &:hover {
- background: var(--surface-2);
- }
-
- &.current {
- background: fade($success-raw, 5%);
- }
- }
-
- .commit-icon {
- color: var(--text-faint);
-
- .current-icon {
- color: var(--green);
- }
- }
-
- .commit-sha {
- font-family: var(--mono);
- font-size: 11px;
- color: var(--accent-bright);
- background: var(--accent-bg);
- padding: 2px 7px;
- border-radius: 5px;
- }
- // Clickable SHA → the commit on the remote host.
- a.commit-sha--link {
- display: inline-flex;
- align-items: center;
- gap: 4px;
- text-decoration: none;
- transition: background 0.14s;
-
- svg { opacity: 0.6; }
- &:hover { background: var(--accent-bg-soft); text-decoration: underline; svg { opacity: 1; } }
- }
-
- .current-badge {
- font-family: var(--mono);
- font-size: 10px;
- font-weight: $font-weight-semibold;
- text-transform: uppercase;
- letter-spacing: 0.05em;
- background: var(--green-bg);
- color: var(--green);
- padding: 2px 7px;
- border-radius: 5px;
- }
-
- .commit-date {
- font-family: var(--mono);
- font-size: 10.5px;
- color: var(--text-faint);
- }
-
- .commit-message {
- font-size: 13px;
- font-weight: $font-weight-medium;
- }
-
- .commit-author {
- font-family: var(--mono);
- font-size: 11px;
- color: var(--text-faint);
- }
-
- // ---- DiskUsageBar container re-tint (styles live in _wordpress-pipeline) ----
- .app-health-disk .disk-usage-bar-container {
- background: var(--surface-2);
- border-color: var(--border-soft);
- }
-}
-
-// ---- Header environment switcher (prototype .env-switch / .env-menu) ----
-.wp-envswitch-wrap {
- position: relative;
- display: inline-flex;
-}
-
-.wp-envswitch {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- padding: 5px 10px 5px 11px;
- border: 1px solid var(--border-strong);
- border-radius: 8px;
- background: var(--surface-2);
- font-family: $font-main;
- font-size: 12.5px;
- font-weight: $font-weight-medium;
- letter-spacing: normal;
- color: var(--text);
- cursor: pointer;
- transition: border-color 0.14s, background 0.14s;
-
- .ed {
- width: 8px;
- height: 8px;
- border-radius: 50%;
- flex-shrink: 0;
- }
-
- .chev {
- color: var(--text-faint);
- transition: transform 0.15s;
- }
-
- &.open .chev {
- transform: rotate(180deg);
- }
-
- &:hover {
- background: var(--surface-3);
- border-color: var(--border-strong);
- }
-}
-
-.wp-envswitch-menu {
- position: absolute;
- top: 100%;
- left: 0;
- margin-top: 7px;
- z-index: $z-dropdown + 5;
- min-width: 280px;
- background: var(--surface-2);
- border: 1px solid var(--border-strong);
- border-radius: 12px;
- box-shadow: var(--shadow-lg);
- padding: 7px;
-}
-
-.wp-envswitch-head {
- font-family: var(--mono);
- font-size: 10px;
- letter-spacing: 0.12em;
- text-transform: uppercase;
- color: var(--text-ghost);
- padding: 7px 10px 5px;
-}
-
-.wp-envswitch-opt {
- display: flex;
- align-items: center;
- gap: 11px;
- width: 100%;
- padding: 9px 10px;
- border: none;
- border-radius: 9px;
- background: none;
- color: var(--text);
- font-family: $font-main;
- letter-spacing: normal;
- text-transform: none;
- text-align: left;
- cursor: pointer;
- transition: background 0.1s;
-
- &:hover {
- background: var(--surface-3);
- }
-
- .ed {
- width: 9px;
- height: 9px;
- border-radius: 50%;
- flex-shrink: 0;
- }
-
- .check {
- margin-left: auto;
- color: var(--accent-bright);
- flex-shrink: 0;
- }
-}
-
-.wp-envswitch-opt-body {
- flex: 1;
- min-width: 0;
-
- .nm {
- display: block;
- font-weight: $font-weight-medium;
- font-size: 13px;
- }
-
- .meta {
- display: block;
- font-family: var(--mono);
- font-size: 10.5px;
- color: var(--text-faint);
- margin-top: 1px;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- }
-}
-
-// ---- Surface card wrapper for dense tables (SnapshotTable & friends) ----
-.wp-table-card {
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- overflow: hidden;
-}
-
-.wp-th-right {
- text-align: right !important;
-}
-
-.wp-cell-actions {
- text-align: right;
- white-space: nowrap;
-}
-
-.wp-row-action {
- display: inline-grid;
- place-items: center;
- width: 28px;
- height: 28px;
- border: none;
- border-radius: 7px;
- background: none;
- color: var(--text-faint);
- cursor: pointer;
- transition: background 0.14s, color 0.14s;
-
- &:hover:not(:disabled) {
- background: var(--surface-3);
- color: var(--text);
- }
-
- &:disabled {
- opacity: 0.5;
- cursor: default;
- }
-
- &--danger:hover:not(:disabled) {
- background: var(--red-bg);
- color: var(--red);
- }
-}
-
-// Environment Cards (EnvironmentCard.jsx — WP detail Environments tab).
-// Restyled to the prototype's .env-card: quiet surface, accent border on
-// production, EnvTag/Pill rendered by the ds components.
-.environments-grid {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
- gap: $space-4;
- margin-top: $space-4;
-}
-
-// Dashed "add environment" tile — an in-grid affordance that reads as
-// intentional, replacing the old full-width empty-state block that looked
-// like an error sitting under the production card.
-.wp-env-add-tile {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- gap: $space-2;
- min-height: 150px;
- padding: $space-6;
- text-align: center;
- border: 1px dashed var(--border-strong);
- border-radius: var(--radius);
- background: transparent;
- color: var(--text-dim);
- cursor: pointer;
- transition: border-color 0.15s, color 0.15s, background 0.15s;
-
- &:hover {
- border-color: var(--accent);
- color: var(--text);
- background: var(--accent-bg-soft);
- }
-
- &__icon {
- display: grid;
- place-items: center;
- width: 40px;
- height: 40px;
- border-radius: var(--radius);
- background: var(--accent-bg);
- color: var(--accent-bright);
- }
-
- &__title {
- font-size: $font-size-base;
- font-weight: $font-weight-semibold;
- color: var(--text);
- }
-
- &__hint {
- font-size: $font-size-sm;
- line-height: $line-height-normal;
- max-width: 280px;
- }
-}
-
-.wp-env-card {
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- transition: border-color 0.15s;
-
- &:hover {
- border-color: var(--border-strong);
- }
-
- &.production {
- border-color: var(--accent-dim);
-
- &:hover {
- border-color: var(--accent-dim);
- }
- }
-
- &.stale {
- border-color: fade($warning-raw, 35%);
- }
-}
-
-.wp-env-status-group {
- display: flex;
- align-items: center;
- gap: $space-2;
-}
-
-.wp-env-stale-badge {
- display: flex;
- align-items: center;
- gap: 4px;
- font-family: var(--mono);
- font-size: 10.5px;
- font-weight: $font-weight-medium;
- padding: 2px 7px;
- border-radius: 5px;
- background: var(--amber-bg);
- color: var(--amber);
-
- svg {
- flex-shrink: 0;
- }
-}
-
-.text-warning {
- color: var(--amber) !important;
-}
-
-// Kept for the pipeline surfaces: PipelineView / WordPressProjects /
-// EnvironmentStatusBadge still render these classes (EnvironmentCard itself
-// now uses the ds EnvTag/Pill components instead).
-.wp-env-badge {
- font-size: $font-size-xs;
- font-weight: $font-weight-bold;
- padding: 2px 8px;
- border-radius: $radius-sm;
- text-transform: uppercase;
- letter-spacing: 0.5px;
-
- &.env-production {
- background: fade($danger-raw, 12%);
- color: $color-danger;
- }
-
- &.env-staging {
- background: fade($warning-raw, 12%);
- color: $color-warning;
- }
-
- &.env-development {
- background: fade($info-raw, 12%);
- color: $color-info;
- }
-}
-
-.wp-env-status {
- display: flex;
- align-items: center;
- gap: 6px;
- font-size: $font-size-xs;
- font-weight: $font-weight-medium;
-
- .status-dot {
- width: 6px;
- height: 6px;
- border-radius: 50%;
- }
-
- &.running {
- color: $color-success;
-
- .status-dot {
- background: $color-success;
- }
- }
-
- &.stopped {
- color: $text-tertiary;
-
- .status-dot {
- background: $text-tertiary;
- }
- }
-}
-
-.wp-env-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- gap: $space-2;
- padding: 14px 16px;
- border-bottom: 1px solid var(--border-soft);
-}
-
-.wp-env-info {
- display: flex;
- align-items: center;
- gap: $space-2;
- min-width: 0;
-}
-
-.wp-env-name {
- font-size: 14px;
- font-weight: $font-weight-semibold;
- color: var(--text);
- margin: 0;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.wp-env-body {
- padding: 14px 16px;
-}
-
-.wp-env-url {
- margin-bottom: $space-3;
-
- a {
- font-family: var(--mono);
- font-size: 12.5px;
- color: var(--accent-bright);
- text-decoration: none;
- overflow-wrap: anywhere;
-
- &:hover {
- text-decoration: underline;
- }
- }
-}
-
-.wp-env-meta {
- display: grid;
- grid-template-columns: repeat(2, 1fr);
- gap: $space-3 $space-2;
-}
-
-.wp-env-meta-item {
- .meta-label {
- display: flex;
- align-items: center;
- gap: 4px;
- font-family: var(--mono);
- font-size: 10.5px;
- letter-spacing: 0.05em;
- text-transform: uppercase;
- color: var(--text-faint);
- margin-bottom: 3px;
-
- svg {
- color: var(--text-ghost);
- }
- }
-
- .meta-value {
- font-size: 12.5px;
- color: var(--text);
-
- &.mono {
- font-family: var(--mono);
- font-size: 12px;
- }
- }
-}
-
-.wp-env-footer {
- display: flex;
- gap: $space-1;
- padding: 10px 12px;
- border-top: 1px solid var(--border-soft);
- background: transparent;
- border-radius: 0 0 var(--radius) var(--radius);
-}
-
-// Snapshot Table (SnapshotTable.jsx — now a .sk-dtable inside .wp-table-card)
-.wp-snapshot-table {
- .snapshot-name-cell {
- display: flex;
- flex-direction: column;
- gap: 3px;
- }
-
- .snapshot-name {
- font-weight: 550;
- font-size: 13px;
- color: var(--text);
- }
-
- .snapshot-tag {
- display: inline-flex;
- align-items: center;
- gap: 4px;
- font-family: var(--mono);
- font-size: 10.5px;
- color: var(--cyan);
- background: var(--cyan-bg);
- padding: 2px 7px;
- border-radius: 5px;
- width: fit-content;
- }
-
- .snapshot-desc {
- font-family: var(--mono);
- font-size: 11px;
- color: var(--text-faint);
- }
-
- .snapshot-date {
- font-family: var(--mono);
- font-size: 12px;
- color: var(--text-dim);
- }
-
- .mono {
- font-family: var(--mono);
- font-size: 12px;
- color: var(--text-dim);
- }
-
- .compressed-badge {
- display: inline-block;
- font-family: var(--mono);
- font-size: 10px;
- background: var(--green-bg);
- color: var(--green);
- padding: 1px 5px;
- border-radius: 4px;
- margin-left: $space-2;
- }
-
- .text-muted {
- color: var(--text-ghost);
- font-family: var(--mono);
- }
-
- .git-context {
- display: flex;
- align-items: center;
- gap: 6px;
- color: var(--text-dim);
-
- svg {
- color: var(--text-faint);
- flex-shrink: 0;
- }
-
- .git-context-sha {
- color: var(--accent-bright);
- background: var(--accent-bg);
- padding: 1px 6px;
- border-radius: 4px;
- font-size: 11px;
- }
-
- .commit-msg {
- font-size: 11.5px;
- color: var(--text-faint);
- margin-left: $space-1;
- }
- }
-}
-
-// Commit List
-.commit-list {
- display: flex;
- flex-direction: column;
- gap: $space-1;
- max-width: 800px;
-}
-
-.commit-item {
- display: flex;
- align-items: flex-start;
- gap: $space-3;
- padding: $space-3 $space-4;
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- transition: all 0.15s ease;
-
- &:hover {
- border-color: $border-hover;
- }
-
- &.current {
- border-color: fade($success-raw, 40%);
- background: fade($success-raw, 4%);
- }
-}
-
-.commit-icon {
- color: $text-tertiary;
- margin-top: 2px;
-
- .current-icon {
- color: $color-success;
- }
-}
-
-.commit-info {
- flex: 1;
- min-width: 0;
-}
-
-.commit-header {
- display: flex;
- align-items: center;
- gap: $space-2;
- margin-bottom: $space-1;
-}
-
-.commit-sha {
- font-size: $font-size-sm;
- font-weight: $font-weight-medium;
- color: $text-secondary;
-}
-
-.current-badge {
- font-size: $font-size-xs;
- background: $color-success;
- color: #fff;
- padding: 1px 6px;
- border-radius: $radius-sm;
-}
-
-.commit-date {
- font-size: $font-size-xs;
- color: $text-tertiary;
- margin-left: auto;
-}
-
-.commit-message {
- font-size: $font-size-sm;
- color: $text-primary;
- margin: 0;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.commit-author {
- font-size: $font-size-xs;
- color: $text-tertiary;
-}
-
-.commit-actions {
- display: flex;
- gap: $space-2;
- flex-shrink: 0;
-}
-
-.commit-message-preview {
- font-style: italic;
- color: $text-secondary;
- padding: $space-3;
- background: $bg-tertiary;
- border-radius: $radius-md;
- margin: $space-3 0;
-}
-
-// Git Commits Section
-.git-commits-section {
- margin-top: $space-6;
- padding-top: $space-6;
- border-top: 1px solid $border-subtle;
-}
-
-// Quick Actions (WP detail Overview — exclusive to this page)
-.quick-actions-grid {
- display: grid;
- grid-template-columns: repeat(2, 1fr);
- gap: $space-2;
-}
-
-.quick-action-btn {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 7px;
- padding: 10px $space-2;
- background: var(--surface-2);
- border: 1px solid var(--border-soft);
- border-radius: 8px;
- color: var(--text-dim);
- font-size: 12.5px;
- font-weight: $font-weight-medium;
- text-decoration: none;
- cursor: pointer;
- transition: background 0.14s, border-color 0.14s, color 0.14s;
-
- svg {
- color: var(--text-faint);
- flex-shrink: 0;
- transition: color 0.14s;
- }
-
- &:hover:not(:disabled) {
- background: var(--accent-bg-soft);
- border-color: var(--accent-dim);
- color: var(--text);
-
- svg {
- color: var(--accent-bright);
- }
- }
-
- &:disabled {
- opacity: 0.55;
- cursor: default;
- }
-}
-
-// Hint Box
-.hint-box {
- padding: $space-4;
- background: $bg-tertiary;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- margin-top: $space-4;
-
- p {
- margin: 0;
- color: $text-secondary;
- font-size: $font-size-sm;
-
- &:not(:last-child) {
- margin-bottom: $space-2;
- }
- }
-}
-
-// Empty State Small
-.empty-state-small {
- padding: $space-6;
- text-align: center;
- color: $text-tertiary;
-
- p {
- margin: 0;
-
- &:not(:last-child) {
- margin-bottom: $space-2;
- }
- }
-
- .hint {
- font-size: $font-size-sm;
- }
-}
-
-// Spinning animation for sync button
-@keyframes spin {
- from {
- transform: rotate(0deg);
- }
- to {
- transform: rotate(360deg);
- }
-}
-
-.spinning {
- animation: spin 1s linear infinite;
-}
-
-// ============================================
-// SKELETON LOADING STATES
-// ============================================
-
-@keyframes shimmer {
- 0% {
- background-position: -200% 0;
- }
- 100% {
- background-position: 200% 0;
- }
-}
-
-@mixin skeleton() {
- background: linear-gradient(
- 90deg,
- $bg-tertiary 25%,
- fade($border-subtle-raw, 50%) 50%,
- $bg-tertiary 75%
- );
- background-size: 200% 100%;
- animation: shimmer 1.5s infinite;
- border-radius: $radius-md;
-}
-
-.skeleton {
- @include skeleton();
-}
-
-// Skeleton Site Card
-.wp-site-card-skeleton {
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-lg;
-}
-
-.wp-site-card-skeleton-header {
- display: flex;
- align-items: center;
- gap: $space-3;
- padding: $space-4;
- border-bottom: 1px solid $border-subtle;
-}
-
-.wp-site-card-skeleton-icon {
- width: 40px;
- height: 40px;
- border-radius: $radius-md;
- @include skeleton();
-}
-
-.wp-site-card-skeleton-info {
- flex: 1;
- display: flex;
- flex-direction: column;
- gap: $space-2;
-}
-
-.wp-site-card-skeleton-name {
- width: 60%;
- height: 16px;
- @include skeleton();
-}
-
-.wp-site-card-skeleton-url {
- width: 80%;
- height: 12px;
- @include skeleton();
-}
-
-.wp-site-card-skeleton-status {
- width: 64px;
- height: 24px;
- border-radius: $radius-full;
- @include skeleton();
-}
-
-.wp-site-card-skeleton-body {
- padding: $space-4;
- display: grid;
- grid-template-columns: repeat(2, 1fr);
- gap: $space-3;
-}
-
-.wp-site-card-skeleton-meta {
- display: flex;
- flex-direction: column;
- gap: $space-1;
-}
-
-.wp-site-card-skeleton-label {
- width: 50%;
- height: 10px;
- @include skeleton();
-}
-
-.wp-site-card-skeleton-value {
- width: 70%;
- height: 14px;
- @include skeleton();
-}
-
-.wp-site-card-skeleton-footer {
- display: flex;
- gap: $space-2;
- padding: $space-3 $space-4;
- border-top: 1px solid $border-subtle;
- background: $bg-tertiary;
- border-radius: 0 0 $radius-lg $radius-lg;
-}
-
-.wp-site-card-skeleton-btn {
- flex: 1;
- height: 32px;
- @include skeleton();
-}
-
-// Skeleton Environment Card
-.wp-env-card-skeleton {
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-lg;
-}
-
-.wp-env-card-skeleton-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: $space-4;
- border-bottom: 1px solid $border-subtle;
-}
-
-.wp-env-card-skeleton-badge {
- width: 60px;
- height: 20px;
- border-radius: $radius-sm;
- @include skeleton();
-}
-
-.wp-env-card-skeleton-status {
- width: 64px;
- height: 20px;
- border-radius: $radius-sm;
- @include skeleton();
-}
-
-.wp-env-card-skeleton-body {
- padding: $space-4;
-}
-
-.wp-env-card-skeleton-url {
- width: 70%;
- height: 14px;
- margin-bottom: $space-3;
- @include skeleton();
-}
-
-.wp-env-card-skeleton-meta {
- display: grid;
- grid-template-columns: repeat(2, 1fr);
- gap: $space-2;
-}
-
-.wp-env-card-skeleton-meta-item {
- .skeleton-label {
- width: 40%;
- height: 10px;
- margin-bottom: 4px;
- @include skeleton();
- }
-
- .skeleton-value {
- width: 60%;
- height: 14px;
- @include skeleton();
- }
-}
-
-.wp-env-card-skeleton-footer {
- display: flex;
- gap: $space-2;
- padding: $space-3 $space-4;
- border-top: 1px solid $border-subtle;
- background: $bg-tertiary;
- border-radius: 0 0 $radius-lg $radius-lg;
-}
-
-// Skeleton Stat Card
-.docker-stat-card-skeleton {
- background: $bg-card;
- border: 1px solid $border-subtle;
- border-radius: $radius-lg;
- padding: $space-4;
- display: flex;
- flex-direction: column;
- gap: $space-2;
-}
-
-.docker-stat-card-skeleton-label {
- width: 60%;
- height: 12px;
- @include skeleton();
-}
-
-.docker-stat-card-skeleton-value {
- width: 40%;
- height: 28px;
- @include skeleton();
-}
-
-.docker-stat-card-skeleton-meta {
- width: 80%;
- height: 12px;
- @include skeleton();
-}
-
-// Skeleton Table Row
-.skeleton-table-row {
- display: flex;
- align-items: center;
- gap: $space-3;
- padding: $space-3 $space-4;
- border-bottom: 1px solid $border-subtle;
-
- .skeleton-cell {
- height: 16px;
- @include skeleton();
-
- &.cell-name { width: 25%; }
- &.cell-tag { width: 15%; }
- &.cell-size { width: 10%; }
- &.cell-date { width: 15%; }
- &.cell-actions { width: 20%; margin-left: auto; }
- }
-}
-
-// Tab Content Loading
-.tab-loading {
- display: flex;
- flex-direction: column;
- gap: $space-4;
- padding: $space-4;
-}
-
-.tab-loading-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- margin-bottom: $space-2;
-}
-
-.tab-loading-title {
- width: 120px;
- height: 24px;
- @include skeleton();
-}
-
-.tab-loading-btn {
- width: 140px;
- height: 36px;
- border-radius: $radius-md;
- @include skeleton();
-}
-
-// ============================================
-// WORDPRESS DETAIL PAGE SKELETON
-// Mirrors the real page chrome + Overview tab layout.
-// ============================================
-.wp-detail-page--skeleton {
- .sk-topbar-skeleton {
- display: flex;
- align-items: center;
- gap: 14px;
- min-height: 60px;
- padding: 10px $space-4;
- border-bottom: 1px solid var(--border-soft);
-
- &__icon {
- width: 18px;
- height: 18px;
- border-radius: 4px;
- @include skeleton();
- }
-
- &__title {
- width: 160px;
- height: 16px;
- border-radius: 4px;
- @include skeleton();
- }
-
- &__spacer { flex: 1; }
-
- &__actions {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- flex-shrink: 0;
- }
-
- &__btn {
- width: 90px;
- height: 32px;
- border-radius: $radius-md;
- @include skeleton();
-
- &--primary { width: 110px; }
- }
- }
-
- .wp-detail-skeleton-repo {
- width: 220px;
- height: 30px;
- border-radius: $radius-full;
- @include skeleton();
- }
-
- .app-detail-tab-skeleton {
- width: 80px;
- height: 32px;
- border-radius: 7px;
- @include skeleton();
- }
-
- .wp-kpis--skeleton {
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
- gap: $space-4;
- }
-
- .wp-detail-skeleton-kpi {
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- padding: $space-4 $space-5;
- display: flex;
- flex-direction: column;
- gap: $space-2;
-
- &__label {
- width: 70%;
- height: 11px;
- border-radius: 3px;
- @include skeleton();
- }
-
- &__value {
- width: 45%;
- height: 26px;
- border-radius: 4px;
- @include skeleton();
- }
- }
-
- .wp-detail-skeleton-panel {
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
-
- .app-panel-header {
- display: flex;
- flex-direction: column;
- align-items: flex-start;
- gap: 2px;
- padding: 12px 17px;
- border-bottom: 1px solid var(--border-soft);
- }
-
- .app-panel-body {
- padding: $space-4 17px;
- }
- }
-
- .wp-detail-skeleton-chart {
- height: 250px;
- border-radius: $radius-md;
- @include skeleton();
- }
-
- .wp-detail-skeleton-activity {
- display: flex;
- flex-direction: column;
- gap: $space-3;
-
- &__row {
- display: flex;
- align-items: center;
- gap: $space-3;
- }
-
- &__lines {
- flex: 1;
- min-width: 0;
- }
- }
-
- .wp-detail-skeleton-rows {
- display: flex;
- flex-direction: column;
- gap: $space-3;
- }
-
- .wp-detail-skeleton-row {
- display: flex;
- justify-content: space-between;
- align-items: center;
- gap: $space-4;
- }
-}
-
-// ============================================
-// ERROR STATES
-// ============================================
-
-.error-boundary,
-.error-state {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: $space-8;
- text-align: center;
- min-height: 200px;
-}
-
-.error-boundary-icon,
-.error-state-icon {
- color: $color-danger;
- margin-bottom: $space-4;
- padding: $space-3;
- background: fade($danger-raw, 10%);
- border-radius: 50%;
-}
-
-.error-boundary h3,
-.error-state-title {
- font-size: $font-size-lg;
- font-weight: $font-weight-semibold;
- color: $text-primary;
- margin: 0 0 $space-2;
-}
-
-.error-boundary-message,
-.error-state-message {
- font-size: $font-size-sm;
- color: $text-secondary;
- margin: 0 0 $space-4;
- max-width: 400px;
-}
-
-.error-state-compact {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-3 $space-4;
- background: fade($danger-raw, 8%);
- border: 1px solid fade($danger-raw, 20%);
- border-radius: $radius-md;
- color: $color-danger;
- font-size: $font-size-sm;
-
- svg {
- flex-shrink: 0;
- }
-
- span {
- flex: 1;
- }
-
- .btn {
- flex-shrink: 0;
- }
-}
-
-// ============================================
-// CONFIRM DIALOG ENHANCEMENTS
-// ============================================
-
-.confirm-dialog-details {
- margin-top: $space-3;
- padding: $space-3;
- background: $bg-tertiary;
- border-radius: $radius-md;
- font-size: $font-size-sm;
- color: $text-secondary;
- text-align: left;
-
- ul {
- margin: 0;
- padding-left: $space-4;
-
- li {
- margin-bottom: $space-1;
-
- &:last-child {
- margin-bottom: 0;
- }
- }
- }
-
- strong {
- color: $text-primary;
- }
-
- code {
- background: $bg-code;
- padding: 2px 6px;
- border-radius: 3px;
- font-family: $font-family-mono;
- font-size: 0.9em;
- }
-}
-
-// Environment Preview URL in Create Modal
-.env-preview-url {
- display: flex;
- align-items: center;
- gap: $space-2;
- padding: $space-3;
- background: fade($success-raw, 8%);
- border: 1px solid fade($success-raw, 20%);
- border-radius: $radius-md;
- margin-bottom: $space-4;
-
- .preview-label {
- font-size: $font-size-xs;
- color: $text-secondary;
- }
-
- .preview-url {
- font-family: $font-family-mono;
- font-size: $font-size-sm;
- color: $color-success;
- font-weight: $font-weight-medium;
- }
-}
-
-.form-hint-domain {
- code {
- background: $bg-code;
- padding: 2px 6px;
- border-radius: 3px;
- font-family: $font-family-mono;
- font-size: 0.9em;
- }
-}
-
-.confirm-dialog-input {
- margin-top: $space-4;
- text-align: left;
-
- label {
- display: block;
- font-size: $font-size-sm;
- color: $text-secondary;
- margin-bottom: $space-2;
-
- strong {
- color: $text-primary;
- font-family: $font-family-mono;
- }
- }
-
- input {
- width: 100%;
- padding: $space-3;
- border: 1px solid $border-subtle;
- border-radius: $radius-md;
- font-size: $font-size-base;
- background: $bg-input;
- color: $text-primary;
-
- &:focus {
- outline: none;
- border-color: $color-primary;
- box-shadow: 0 0 0 3px fade($accent-primary-raw, 15%);
- }
-
- &::placeholder {
- color: $text-tertiary;
- }
- }
-}
-
-// ============================================
-// RESOURCE ADVISORY - INLINE CAPACITY WARNING
-// ============================================
-// Replaces the old blocked-state gate. Warns at the point of action and lets
-// the operator proceed; nothing here hides a control.
-
-.resource-advisory {
- display: flex;
- align-items: flex-start;
- gap: $space-3;
- padding: $space-4;
- margin-bottom: $space-4;
- background: fade($warning-raw, 8%);
- border: 1px solid $color-warning;
- border-radius: $radius-md;
-
- &__icon {
- flex-shrink: 0;
- margin-top: 2px;
- color: $color-warning;
- }
-
- &__title {
- font-size: $font-size-sm;
- font-weight: $font-weight-bold;
- color: $text-primary;
- margin-bottom: $space-1;
- }
-
- &__text {
- font-size: $font-size-sm;
- color: $text-secondary;
- line-height: $line-height-normal;
- margin: 0;
- }
-
- &__list {
- margin: $space-2 0 0;
- padding-left: $space-4;
- font-size: $font-size-xs;
- color: $text-tertiary;
- }
-}
-
-// One-time admin credentials banner (after site create)
-.wp-creds-banner {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: $space-4;
- margin: 0 $space-4 $space-4;
- padding: $space-4;
- background: fade($success-raw, 8%);
- border: 1px solid fade($success-raw, 25%);
- border-radius: $radius-md;
-
- .wp-creds-banner-text {
- display: flex;
- flex-direction: column;
- gap: $space-1;
- font-size: $font-size-sm;
-
- code {
- font-family: $font-family-mono;
- background: $bg-tertiary;
- padding: 1px 6px;
- border-radius: 3px;
- }
- }
-}
-
-// ============================================
-// SITE HEALTH + SSL PANEL HELPERS (Overview tab)
-// ============================================
-
-.app-health-stat {
- display: inline-flex;
- align-items: center;
- gap: $space-2;
-}
-
-.app-health-disk {
- margin-top: $space-4;
-
- .app-info-label {
- display: block;
- margin-bottom: $space-2;
- }
-}
-
-.ssl-action-btn {
- margin-top: $space-3;
-}
-
-// Plugin / Theme card grids (WP detail — replace the dense asset tables)
-.wp-detail-page {
- .wp-asset-grid {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
- gap: 14px;
- }
-
- .wp-asset-card {
- display: flex;
- gap: 13px;
- align-items: flex-start;
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- padding: 16px;
- transition: border-color 0.15s;
-
- &:hover { border-color: var(--border-strong); }
- &.is-active { border-color: var(--accent-dim); }
-
- &__body { flex: 1; min-width: 0; }
- &__name { font-weight: 600; font-size: 14px; }
- &__sub {
- font-family: var(--mono);
- font-size: 11px;
- color: var(--text-faint);
- margin-top: 2px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- &__foot {
- display: flex;
- align-items: center;
- gap: 10px;
- margin-top: 12px;
- flex-wrap: wrap;
- }
- &__ver { font-family: var(--mono); font-size: 11px; color: var(--text-faint); }
-
- &__toggle {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 6px;
- flex-shrink: 0;
- }
- &__state {
- font-family: var(--mono);
- font-size: 10px;
- text-transform: uppercase;
- letter-spacing: 0.04em;
- color: var(--text-faint);
- &.is-on { color: var(--green); }
- }
- }
-
- .wp-update-flag {
- display: inline-flex;
- align-items: center;
- gap: 5px;
- font-family: var(--mono);
- font-size: 10.5px;
- color: var(--amber);
- background: var(--amber-bg);
- padding: 2px 7px;
- border-radius: 5px;
- border: none;
- cursor: pointer;
- transition: opacity 0.12s;
-
- &: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 {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
- gap: 14px;
- }
-
- .wp-theme-card {
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- overflow: hidden;
- transition: border-color 0.15s, transform 0.15s;
-
- &:hover { border-color: var(--border-strong); transform: translateY(-2px); }
- &.is-active { border-color: var(--accent-dim); }
-
- &__shot {
- position: relative;
- height: 128px;
- display: grid;
- place-items: center;
- border-bottom: 1px solid var(--border-soft);
- background:
- repeating-linear-gradient(135deg, rgba(255, 255, 255, 0.018) 0 12px, transparent 12px 24px),
- var(--surface-2);
-
- svg { color: var(--text-ghost); }
- .pill { position: absolute; top: 10px; right: 10px; }
- }
-
- &__meta { padding: 14px 16px; }
- &__name { font-weight: 600; font-size: 14px; }
- &__sub {
- font-family: var(--mono);
- font-size: 11px;
- color: var(--text-faint);
- margin-top: 3px;
- }
- &__actions {
- display: flex;
- align-items: center;
- gap: 8px;
- margin-top: 12px;
- }
- &__current {
- font-family: var(--mono);
- font-size: 11px;
- color: var(--green);
- }
- }
-}
-
-// Change Site URL modal (URL-swap tool)
-.wp-url-swap {
- display: flex;
- flex-direction: column;
- gap: 16px;
- padding: 4px 0 8px;
-
- &__warning {
- display: flex;
- gap: 10px;
- padding: 12px 14px;
- border-radius: var(--radius);
- background: var(--surface-2);
- border: 1px solid var(--border-soft);
- font-size: 12.5px;
- line-height: 1.5;
- color: var(--text-faint);
-
- svg { flex-shrink: 0; color: var(--amber); margin-top: 1px; }
- }
-
- &__fromto {
- display: flex;
- align-items: center;
- gap: 10px;
- flex-wrap: wrap;
-
- code {
- font-family: var(--mono);
- font-size: 12px;
- padding: 4px 8px;
- border-radius: 6px;
- background: var(--surface-2);
- border: 1px solid var(--border-soft);
- color: var(--text-faint);
- word-break: break-all;
-
- &.is-new { color: var(--green); border-color: var(--accent-dim); }
- }
- svg { color: var(--text-ghost); flex-shrink: 0; }
- }
-
- &__keep {
- display: flex;
- align-items: flex-start;
- gap: 10px;
- cursor: pointer;
-
- > span {
- display: flex;
- flex-direction: column;
- font-size: 13px;
- font-weight: 500;
- }
- small {
- font-weight: 400;
- font-size: 11.5px;
- color: var(--text-faint);
- margin-top: 2px;
- }
- }
-
- &__preview {
- border-top: 1px solid var(--border-soft);
- padding-top: 12px;
- }
-
- &__preview-total {
- font-size: 13px;
- font-weight: 600;
- color: var(--text);
- margin-bottom: 8px;
- }
-
- &__preview-pairs {
- list-style: none;
- margin: 0;
- padding: 0;
- display: flex;
- flex-direction: column;
- gap: 6px;
-
- li {
- display: flex;
- align-items: center;
- gap: 8px;
- font-size: 11.5px;
-
- code {
- font-family: var(--mono);
- color: var(--text-faint);
- word-break: break-all;
- }
- svg { color: var(--text-ghost); flex-shrink: 0; }
- }
- }
-
- &__count {
- margin-left: auto;
- font-family: var(--mono);
- font-size: 11px;
- padding: 1px 8px;
- border-radius: 999px;
- background: var(--surface-2);
- border: 1px solid var(--border-soft);
- color: var(--text-faint);
- flex-shrink: 0;
- }
-
- &__preview-error {
- font-size: 12.5px;
- color: var(--red);
- }
-
- &__result {
- display: flex;
- gap: 10px;
- align-items: center;
- font-size: 13px;
-
- svg { color: var(--green); flex-shrink: 0; }
- code { font-family: var(--mono); color: var(--green); word-break: break-all; }
- }
-
- &__dns-manual {
- display: flex;
- flex-direction: column;
- gap: 6px;
- font-size: 12.5px;
- }
-
- &__record {
- font-family: var(--mono);
- font-size: 12px;
- padding: 8px 10px;
- border-radius: 6px;
- background: var(--surface-2);
- border: 1px solid var(--border-soft);
- color: var(--text);
- word-break: break-all;
- }
-}
-
-// Pipelines list — the few cells the shared list does not already style.
-.wp-projects-page {
- &__envs {
- display: inline-flex;
- align-items: center;
- gap: 5px;
- flex-wrap: wrap;
- }
-
- &__envcount {
- display: inline-flex;
- align-items: center;
- gap: 4px;
- margin-right: $space-1;
- color: $text-secondary;
- font-family: var(--mono);
- font-size: 12px;
- }
-
- &__git {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- color: $text-secondary;
- font-size: $font-size-sm;
-
- svg { color: $text-tertiary; }
- }
-}