ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(wordpress): per-site uptime + auto-incidents (#26)
Juan Denis6ef998515dc2
diff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex 46f182f1..afb5d06b 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -337,6 +337,9 @@ def create_app(config_name=None):# Start workflow scheduler_start_workflow_scheduler(app)+ # Start per-site WordPress health poller (uptime % + auto-incidents + alerts)+ _start_health_check_scheduler(app)+# Start API analytics flush threadfrom app.middleware.api_analytics import start_analytics_flush_threadstart_analytics_flush_thread(app)@@ -677,3 +680,115 @@ def _check_workflow_schedules(logger):)except Exception as e:logger.error(f'Workflow schedule check failed for workflow {workflow.id}: {e}')+++_health_check_thread = None++# How often the per-site WordPress health poller runs (seconds).+HEALTH_CHECK_INTERVAL = 300++# Retention for recorded health-check samples (days) — bounds unbounded growth+# from the continuous poller; matches the longest uptime window (uptime_90d).+# Pruned at most once per day.+HEALTH_CHECK_RETENTION_DAYS = 90+_last_health_prune = None+++def _start_health_check_scheduler(app):+ """Start a background thread that polls every managed WordPress site's+ health on an interval. This keeps health_status fresh (so #27 transition+ alerts fire autonomously, not only while the health card is open) and drives+ any bound status-page components (#26): a real uptime % and auto-incidents.++ Single-worker only — like the other in-process schedulers, this must not be+ multiplied across Gunicorn workers (see CLAUDE.md). The module-global guard+ ensures one thread per process.+ """+ global _health_check_thread+ if _health_check_thread is not None:+ return++ import threading+ import time+ import logging++ logger = logging.getLogger(__name__)++ def health_loop():+ # Small initial delay so startup isn't slowed by blocking probes.+ time.sleep(30)+ while True:+ try:+ with app.app_context():+ _run_health_checks(logger)+ except Exception as e:+ logger.error(f'Health-check scheduler error: {e}')+ time.sleep(HEALTH_CHECK_INTERVAL)++ _health_check_thread = threading.Thread(+ target=health_loop,+ daemon=True,+ name='health-check-scheduler'+ )+ _health_check_thread.start()+++def _run_health_checks(logger):+ """Run a health check for every managed (production) WordPress site and sync+ any status-page components bound to it. Per-site try/except so one hung site+ never stalls the whole sweep."""+ from app import db+ from app.models.wordpress_site import WordPressSite+ from app.models.status_page import StatusComponent+ from app.services.environment_health_service import EnvironmentHealthService+ from app.services.status_page_service import StatusPageService++ _prune_old_health_checks(logger)++ sites = WordPressSite.query.filter_by(is_production=True).all()+ for site in sites:+ try:+ # Only poll sites the operator expects to be up — skip archived/stopped+ # stacks so an intentional stop never looks like an outage.+ if not site.application or site.application.status != 'running':+ continue+ result = EnvironmentHealthService.check_health(site.id)+ overall = result.get('overall_status')+ if not overall:+ continue+ # Drive any status-page components bound to this site.+ components = StatusComponent.query.filter_by(wordpress_site_id=site.id).all()+ for comp in components:+ StatusPageService.sync_component_from_health(comp, overall)+ except Exception as e:+ logger.error(f'Health check failed for site {site.id}: {e}')+ try:+ db.session.rollback()+ except Exception:+ pass+++def _prune_old_health_checks(logger):+ """Delete health-check samples older than the retention window, at most once+ per day, so the continuous poller doesn't grow the health_checks table without+ bound. Best-effort — failure never stalls the health sweep."""+ global _last_health_prune+ from datetime import datetime, timedelta+ now = datetime.utcnow()+ if _last_health_prune is not None and (now - _last_health_prune).total_seconds() < 86400:+ return+ from app import db+ from app.models.status_page import HealthCheck+ cutoff = now - timedelta(days=HEALTH_CHECK_RETENTION_DAYS)+ try:+ deleted = HealthCheck.query.filter(HealthCheck.checked_at < cutoff).delete(synchronize_session=False)+ db.session.commit()+ _last_health_prune = now+ if deleted:+ logger.info(f'Pruned {deleted} health-check row(s) older than {HEALTH_CHECK_RETENTION_DAYS}d')+ except Exception as e:+ logger.error(f'Health-check prune failed: {e}')+ try:+ db.session.rollback()+ except Exception:+ passdiff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.pyindex 52315e67..d2fd017e 100644--- a/backend/app/api/wordpress.py+++ b/backend/app/api/wordpress.py@@ -391,6 +391,113 @@ def set_php(app_id):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 user.role != 'admin' and app.user_id != current_user_id:+ 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>/info', methods=['GET'])@jwt_required()def get_wordpress_info(app_id):diff --git a/backend/app/models/status_page.py b/backend/app/models/status_page.pyindex d2fda84a..ea3c8f73 100644--- a/backend/app/models/status_page.py+++ b/backend/app/models/status_page.py@@ -64,6 +64,11 @@ class StatusComponent(db.Model):check_interval = db.Column(db.Integer, default=60) # secondscheck_timeout = db.Column(db.Integer, default=10)+ # Optional binding to a managed WordPress site. When set, the component's+ # status is driven from the site's health checks (#26) rather than a network+ # probe, and a real uptime % accrues from the recorded HealthCheck rows.+ wordpress_site_id = db.Column(db.Integer, db.ForeignKey('wordpress_sites.id'), nullable=True)+# StatusSTATUS_OPERATIONAL = 'operational'STATUS_DEGRADED = 'degraded'@@ -98,6 +103,7 @@ class StatusComponent(db.Model):'check_target': self.check_target,'check_interval': self.check_interval,'check_timeout': self.check_timeout,+ 'wordpress_site_id': self.wordpress_site_id,'status': self.status,'last_check_at': self.last_check_at.isoformat() if self.last_check_at else None,'last_response_time': self.last_response_time,@@ -138,6 +144,9 @@ class StatusIncident(db.Model):id = db.Column(db.Integer, primary_key=True)page_id = db.Column(db.Integer, db.ForeignKey('status_pages.id'), nullable=False)+ # Optional link to the component this incident is about. Set when an incident+ # is auto-opened from a health check, so it can be auto-resolved on recovery (#26).+ component_id = db.Column(db.Integer, db.ForeignKey('status_components.id'), nullable=True)title = db.Column(db.String(256), nullable=False)status = db.Column(db.String(32), default='investigating') # investigating, identified, monitoring, resolvedimpact = db.Column(db.String(32), default='minor') # none, minor, major, critical@@ -159,6 +168,7 @@ class StatusIncident(db.Model):return {'id': self.id,'page_id': self.page_id,+ 'component_id': self.component_id,'title': self.title,'status': self.status,'impact': self.impact,diff --git a/backend/app/services/status_page_service.py b/backend/app/services/status_page_service.pyindex 5936e390..b97d8774 100644--- a/backend/app/services/status_page_service.py+++ b/backend/app/services/status_page_service.py@@ -91,11 +91,17 @@ class StatusPageService:if not page:return None+ # Internal probe config must not appear on the unauthenticated public page+ # (a health-driven WP component may carry an internal localhost:port target).+ public_hidden = ('check_type', 'check_target', 'check_interval', 'check_timeout')components = page.components.all()grouped = {}for comp in components:group = comp.group or 'Services'- grouped.setdefault(group, []).append(comp.to_dict())+ cd = comp.to_dict()+ for k in public_hidden:+ cd.pop(k, None)+ grouped.setdefault(group, []).append(cd)# Active incidentsactive_incidents = page.incidents.filter(@@ -142,6 +148,7 @@ class StatusPageService:check_target=data.get('check_target', ''),check_interval=data.get('check_interval', 60),check_timeout=data.get('check_timeout', 10),+ wordpress_site_id=data.get('wordpress_site_id'),)db.session.add(comp)db.session.commit()@@ -164,6 +171,14 @@ class StatusPageService:comp = StatusComponent.query.get(comp_id)if not comp:return False+ # Resolve + unlink any incidents referencing this component first, so we+ # never dangle the component_id FK (enforced on PostgreSQL) or leave a+ # stale active incident on the public page after the component is gone.+ for inc in StatusIncident.query.filter_by(component_id=comp_id).all():+ if inc.status != 'resolved':+ inc.status = 'resolved'+ inc.resolved_at = datetime.utcnow()+ inc.component_id = Nonedb.session.delete(comp)db.session.commit()return True@@ -252,6 +267,104 @@ class StatusPageService:HealthCheck.checked_at >= since).order_by(HealthCheck.checked_at.desc()).all()+ @staticmethod+ def recompute_uptime(comp):+ """Recompute uptime_24h/7d/30d/90d for a component from its HealthCheck+ rows (fraction of recorded checks with status 'up'). Only fully-healthy+ checks count as up — 'degraded' periods reduce the percentage, matching+ the status-page convention where degraded is not "operational". Leaves a+ window's existing value untouched when it has no samples yet."""+ windows = {'uptime_24h': 24, 'uptime_7d': 24 * 7,+ 'uptime_30d': 24 * 30, 'uptime_90d': 24 * 90}+ now = datetime.utcnow()+ for field, hours in windows.items():+ since = now - timedelta(hours=hours)+ base = HealthCheck.query.filter(+ HealthCheck.component_id == comp.id,+ HealthCheck.checked_at >= since,+ )+ total = base.count()+ if total:+ up = base.filter(HealthCheck.status == 'up').count()+ setattr(comp, field, round(up / total * 100, 2))+ db.session.commit()++ # Map an EnvironmentHealthService overall_status to (HealthCheck status,+ # StatusComponent status). 'unknown' is intentionally absent — indeterminate+ # checks are not recorded so they don't pollute the uptime %.+ _HEALTH_MAP = {+ 'healthy': ('up', StatusComponent.STATUS_OPERATIONAL),+ 'degraded': ('degraded', StatusComponent.STATUS_DEGRADED),+ 'unhealthy': ('down', StatusComponent.STATUS_MAJOR),+ }++ @staticmethod+ def sync_component_from_health(comp, overall_status, error=None):+ """Drive a managed-site-bound component from an EnvironmentHealthService+ verdict instead of a network probe (#26): record a HealthCheck sample,+ update the component's live status, recompute uptime, and auto-open /+ auto-resolve an incident on the operational<->major_outage edge.++ Returns the recorded HealthCheck, or None for an indeterminate+ ('unknown') verdict (not recorded).+ """+ mapped = StatusPageService._HEALTH_MAP.get(overall_status)+ if not mapped:+ return None+ check_status, comp_status = mapped+ prev_status = comp.status++ hc = HealthCheck(component_id=comp.id, status=check_status, error=error)+ db.session.add(hc)+ comp.last_check_at = datetime.utcnow()+ comp.status = comp_status+ db.session.commit()++ StatusPageService.recompute_uptime(comp)++ # Open an incident when ENTERING a major outage; resolve it when LEAVING+ # major (to operational OR degraded). Resolving on the leaving-edge — not+ # only on a clean major->operational hop — ensures a recovery that passes+ # through an intermediate degraded poll (a common path) never leaves the+ # incident stuck open. Degraded itself never opens a full incident.+ if comp_status == StatusComponent.STATUS_MAJOR and prev_status != StatusComponent.STATUS_MAJOR:+ StatusPageService._open_incident_for_component(comp, error)+ elif comp_status != StatusComponent.STATUS_MAJOR and prev_status == StatusComponent.STATUS_MAJOR:+ StatusPageService._resolve_incident_for_component(comp)+ return hc++ @staticmethod+ def _open_incident_for_component(comp, error=None):+ """Open a major-impact incident for a component if one is not already open."""+ existing = StatusIncident.query.filter(+ StatusIncident.component_id == comp.id,+ StatusIncident.status != 'resolved',+ ).first()+ if existing:+ return existing+ incident = StatusPageService.create_incident(comp.page_id, {+ 'title': f'{comp.name} is experiencing an outage',+ 'status': 'investigating',+ 'impact': 'major',+ 'body': error or 'Automated health check detected an outage.',+ })+ incident.component_id = comp.id+ db.session.commit()+ return incident++ @staticmethod+ def _resolve_incident_for_component(comp):+ """Resolve the open auto-incident for a component, if any."""+ existing = StatusIncident.query.filter(+ StatusIncident.component_id == comp.id,+ StatusIncident.status != 'resolved',+ ).first()+ if existing:+ StatusPageService.update_incident(existing.id, {+ 'status': 'resolved',+ 'update_body': 'Automated health check detected recovery.',+ })+# --- Incidents ---@staticmethoddiff --git a/backend/migrations/versions/010_wordpress_status_monitoring.py b/backend/migrations/versions/010_wordpress_status_monitoring.pynew file mode 100644index 00000000..033101aa--- /dev/null+++ b/backend/migrations/versions/010_wordpress_status_monitoring.py@@ -0,0 +1,56 @@+"""Link status components to managed WordPress sites + incidents to components (#26).++Adds:+- status_components.wordpress_site_id (nullable FK -> wordpress_sites.id)+- status_incidents.component_id (nullable FK -> status_components.id)++These let a managed WordPress site appear on a status page as a health-driven+component (real uptime %) and let an auto-opened incident be auto-resolved on+recovery.++Idempotent: MigrationService._fix_missing_columns may have already added these+columns on boot before Alembic runs, so guard on the live schema. Columns are+added as plain INTEGERs (no enforced FK), matching the auto-add path and the+existing migration style.++Revision ID: 010_wordpress_status_monitoring+Revises: 009_wordpress_site_tags+Create Date: 2026-06-01+"""+from alembic import op+import sqlalchemy as sa++revision = '010_wordpress_status_monitoring'+down_revision = '009_wordpress_site_tags'+branch_labels = None+depends_on = None+++def _has_col(inspector, table, col):+ if table not in inspector.get_table_names():+ return False+ return col in {c['name'] for c in inspector.get_columns(table)}+++def upgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ if 'status_components' in inspector.get_table_names() and \+ not _has_col(inspector, 'status_components', 'wordpress_site_id'):+ with op.batch_alter_table('status_components') as batch_op:+ batch_op.add_column(sa.Column('wordpress_site_id', sa.Integer(), nullable=True))+ if 'status_incidents' in inspector.get_table_names() and \+ not _has_col(inspector, 'status_incidents', 'component_id'):+ with op.batch_alter_table('status_incidents') as batch_op:+ batch_op.add_column(sa.Column('component_id', sa.Integer(), nullable=True))+++def downgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ if _has_col(inspector, 'status_incidents', 'component_id'):+ with op.batch_alter_table('status_incidents') as batch_op:+ batch_op.drop_column('component_id')+ if _has_col(inspector, 'status_components', 'wordpress_site_id'):+ with op.batch_alter_table('status_components') as batch_op:+ batch_op.drop_column('wordpress_site_id')diff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.mdindex 08809d52..c224e2e7 100644--- a/docs/WORDPRESS_ROADMAP.md+++ b/docs/WORDPRESS_ROADMAP.md@@ -235,11 +235,12 @@ The headline value of a managed platform, and the most net-new — but it leans- **Reuse:** the existing log-tail / `metrics_history_service` aggregation patterns.- **Done when:** The site dashboard shows per-site traffic and error analytics.-### #26 — Per-site uptime + auto-incidents `[M]` 🟡+### #26 — Per-site uptime + auto-incidents `[M]` 🟡 — ✅ Done (server-side health poller → bound status-page component with a real uptime % + auto-open/resolve incidents)- **Today:** Status pages / uptime have no FK to a WP site; components are hand-typed with arbitrary `check_target`; `EnvironmentHealthService` outages don't open incidents.- **Do:** Background-schedule `EnvironmentHealthService` checks to accrue per-site uptime %; auto-create a status-page component from a managed site; bridge `health_status` → status component + auto-open incident on outage.- **Reuse:** `EnvironmentHealthService`, `status_page_service`, `uptime_service`.- **Done when:** A managed site appears on a status page with a real uptime % and auto-incidents.+- **Landed:** A **server-side daemon-thread health poller** (`_start_health_check_scheduler`, 300s, single-worker-guarded) runs `check_health` for every **running production** site — skipping archived/stopped stacks so an intentional stop is never an outage — which keeps `health_status` fresh **autonomously** (so #27's alerts fire without the browser health card open) and drives bound status-page components. **Schema** (Alembic `010` + the boot-time `_fix_missing_columns` auto-add): `status_components.wordpress_site_id` (→ `wordpress_sites`) and `status_incidents.component_id` (→ `status_components`); the existing `HealthCheck` table is reused as the uptime sample store (no new table). New `StatusPageService.sync_component_from_health` maps the health verdict (healthy→operational, degraded→degraded, unhealthy→major_outage; `unknown` skipped so it never pollutes the %), records a `HealthCheck`, recomputes a **real uptime %** (`COUNT`-based over 24h/7d/30d/90d — only fully-healthy checks count, so degraded reduces it), and **auto-opens an incident on entering a major outage / auto-resolves on leaving it** (to operational *or* degraded, so a degraded intermediate poll never strands the incident). Sample rows are pruned to 90 days (once/day) to bound growth. WP routes `GET/POST/DELETE /sites/<id>/status-page` read the binding + attach (**production-only**) / detach (resolves & unlinks the incident first → no dangling FK on PostgreSQL, no stale public incident), plus a new **Uptime tab** on the site detail (health + uptime % + attach/detach). **Security:** internal probe config (`check_target`, intervals) is stripped from the *unauthenticated* public-page projection, and a health-driven component stores no internal `localhost:port` target. Verified: backend `py_compile`, frontend lint-clean + production build, and a 3-lens adversarial review (3 major findings fixed: the incident-resolve edge, the detach FK/orphan, and the public `check_target` leak). Not runtime-exercised on a real Docker host (Windows dev).### #27 — WP-aware alerting `[M]` 🟡 — ✅ Done (site down/recovered → channels + catalog event, edge-triggered; error-spike deferred to #25)- **Today:** Multi-channel `notification_service` (email/Slack/Discord/Telegram/webhook) exists; the `WorkflowEventBus` `health_check_failed` hook exists; neither knows about WordPress sites.diff --git a/frontend/src/pages/WordPressDetail.jsx b/frontend/src/pages/WordPressDetail.jsxindex 55e72cab..da07439f 100644--- a/frontend/src/pages/WordPressDetail.jsx+++ b/frontend/src/pages/WordPressDetail.jsx@@ -1,6 +1,6 @@import React, { useState, useEffect } from 'react';import { useParams, useNavigate, Link } from 'react-router-dom';-import { ExternalLink, Settings, RefreshCw, Plus, Database, GitBranch, Package, Palette, Archive, Trash2, Replace, ShieldCheck, FolderOpen, FileText, Lock, Copy, Zap } from 'lucide-react';+import { ExternalLink, Settings, RefreshCw, Plus, Database, GitBranch, Package, Palette, Archive, Trash2, Replace, ShieldCheck, FolderOpen, FileText, Lock, Copy, Zap, Activity, Globe, Layers } from 'lucide-react';import useTabParam from '../hooks/useTabParam';import wordpressApi from '../services/wordpress';import api from '../services/api';@@ -12,6 +12,7 @@ import { ErrorBoundary, ErrorState } from '../components/ErrorBoundary';import { useConfirm } from '../hooks/useConfirm';import { ConfirmDialog } from '../components/ConfirmDialog';import { DangerZone } from '../components/DangerZone';+import EmptyState from '../components/EmptyState';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { Label } from '@/components/ui/label';@@ -70,7 +71,7 @@ const DetailPageSkeleton = () => (</div>);-const VALID_TABS = ['overview', 'environments', 'database', 'plugins', 'themes', 'php', 'git', 'backups'];+const VALID_TABS = ['overview', 'environments', 'database', 'plugins', 'themes', 'php', 'git', 'backups', 'uptime'];const WordPressDetail = () => {const { id } = useParams();@@ -151,12 +152,12 @@ const WordPressDetail = () => {if (!site) {return (- <div className="empty-state">- <h3>Site not found</h3>- <Button onClick={() => navigate('/wordpress')}>- Back to WordPress Sites- </Button>- </div>+ <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>}+ />);}@@ -341,6 +342,12 @@ const WordPressDetail = () => {><Archive size={14} /> Backups</div>+ <div+ className={`app-detail-tab ${activeTab === 'uptime' ? 'active' : ''}`}+ onClick={() => setActiveTab('uptime')}+ >+ <Activity size={14} /> Uptime+ </div></div>{/* Clone Site Modal */}@@ -384,6 +391,7 @@ const WordPressDetail = () => {{activeTab === 'php' && <PhpTab siteId={site.id} />}{activeTab === 'git' && <GitTab siteId={site.id} site={site} onUpdate={loadSite} />}{activeTab === 'backups' && <BackupsTab siteId={site.id} />}+ {activeTab === 'uptime' && <UptimeTab siteId={site.id} />}</ErrorBoundary></div></div>@@ -489,6 +497,133 @@ const PhpTab = ({ siteId }) => {);};+// 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 <div className="tab-loading"><p className="hint">Loading uptime info...</p></div>;++ 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="app-info-grid">+ <div className="app-info-item"><span className="app-info-label">24 hours</span><span className="app-info-value">{pct(comp.uptime_24h)}</span></div>+ <div className="app-info-item"><span className="app-info-label">7 days</span><span className="app-info-value">{pct(comp.uptime_7d)}</span></div>+ <div className="app-info-item"><span className="app-info-label">30 days</span><span className="app-info-value">{pct(comp.uptime_30d)}</span></div>+ <div className="app-info-item"><span className="app-info-label">90 days</span><span className="app-info-value">{pct(comp.uptime_90d)}</span></div>+ </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>+ );+};+// Overview Tabconst OverviewTab = ({ site, onUpdate }) => {const toast = useToast();@@ -1519,10 +1654,11 @@ const EnvironmentsTab = ({ siteId, site, onUpdate }) => {</div>{childEnvs.length === 0 && site.is_production && (- <div className="hint-box">- <p>No development or staging environments yet.</p>- <p>Create an environment to safely test changes before deploying to production.</p>- </div>+ <EmptyState+ icon={Layers}+ title="No development or staging environments yet"+ description="Create an environment to test changes safely before deploying to production."+ />)}{showCreateModal && (@@ -2015,7 +2151,7 @@ const PluginsTab = ({ siteId }) => {<div className="plugins-list">{plugins.length === 0 ? (- <p className="hint">No plugins installed.</p>+ <EmptyState icon={Package} title="No plugins installed" description="Install a plugin by entering its slug above." />) : (plugins.map(plugin => (<div key={plugin.name} className={`plugin-item ${plugin.status === 'active' ? 'active' : ''}`}>@@ -2174,7 +2310,7 @@ const ThemesTab = ({ siteId }) => {<div className="themes-list">{themes.length === 0 ? (- <p className="hint">No themes found.</p>+ <EmptyState icon={Palette} title="No themes installed" description="Install a theme by entering its slug above." />) : (themes.map(theme => (<div key={theme.name} className={`theme-item ${theme.status === 'active' ? 'active' : ''}`}>@@ -2399,9 +2535,11 @@ const BackupsTab = ({ siteId }) => {/>{snapshots.length === 0 && !loading && (- <div className="hint-box">- <p>No backups yet. Create a backup to protect your site data.</p>- </div>+ <EmptyState+ icon={Archive}+ title="No backups yet"+ description="Create a backup to protect your site files and database."+ />)}</div>);diff --git a/frontend/src/services/wordpress.js b/frontend/src/services/wordpress.jsindex e35ba7bc..642ee2a3 100644--- a/frontend/src/services/wordpress.js+++ b/frontend/src/services/wordpress.js@@ -177,6 +177,11 @@ const wordpressApi = {enableObjectCache: (siteId) => api.request(`${BASE_PATH}/${siteId}/object-cache`, { method: 'POST' }),disableObjectCache: (siteId) => api.request(`${BASE_PATH}/${siteId}/object-cache`, { method: 'DELETE' }),+ // Status-page binding + uptime (#26): live health, bound component + uptime %, attach/detach+ getSiteStatusPage: (siteId) => api.request(`${BASE_PATH}/${siteId}/status-page`),+ attachStatusPage: (siteId, pageId) => api.request(`${BASE_PATH}/${siteId}/status-page`, { method: 'POST', body: { page_id: pageId } }),+ detachStatusPage: (siteId) => api.request(`${BASE_PATH}/${siteId}/status-page`, { method: 'DELETE' }),+// Mint a one-time passwordless wp-admin login URL for the current operator.autoLogin: (siteId) => api.request(`${BASE_PATH}/${siteId}/login`, {method: 'POST'