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
refactor(frontend): Phase 4 §7.3 — split ServerDetail/ApplicationDetail/WordPressDetail monoliths
Juan Denisecde757115a9
diff --git a/frontend/src/components/appdetail/BuildTab.jsx b/frontend/src/components/appdetail/BuildTab.jsxnew file mode 100644index 00000000..2a774d31--- /dev/null+++ b/frontend/src/components/appdetail/BuildTab.jsx@@ -0,0 +1,366 @@+import { useState, useEffect } from 'react';+import api from '../../services/api';+import EmptyState from '../EmptyState';+import { useToast } from '../../contexts/ToastContext';+import { useConfirm } from '../../hooks/useConfirm';+import { InfoList, InfoItem } from '../InfoList';+import BuildpackPreview from '../buildpack/BuildpackPreview';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Pill } from '@/components/ds';+import Modal from '@/components/Modal';++const BuildTab = ({ appId, appPath, app }) => {+ const toast = useToast();+ const { confirm: confirmBuild } = useConfirm();+ const [buildConfig, setBuildConfig] = useState(null);+ const [detection, setDetection] = useState(null);+ const [deployments, setDeployments] = useState([]);+ const [currentDeployment, setCurrentDeployment] = useState(null);+ const [loading, setLoading] = useState(true);+ const [building, setBuilding] = useState(false);+ const [deploying, setDeploying] = useState(false);+ const [showConfigModal, setShowConfigModal] = useState(false);+ const [showLogsModal, setShowLogsModal] = useState(false);+ const [selectedLog, setSelectedLog] = useState(null);+ const [buildLogs, setBuildLogs] = useState([]);+ const [error, setError] = useState(null);+ const [bpDockerfile, setBpDockerfile] = useState(null);++ // When the app was created from a detected build pack, fetch a read-only+ // preview of the generated Dockerfile for transparency.+ useEffect(() => {+ let active = true;+ if (app?.buildpack_plan) {+ api.generateBuildpack(app.buildpack_plan, app.buildpack_overrides || {}, app.name)+ .then((res) => { if (active) setBpDockerfile(res?.dockerfile || null); })+ .catch(() => {});+ }+ return () => { active = false; };+ }, [app?.buildpack_plan, app?.buildpack_overrides, app?.name]);++ const [configForm, setConfigForm] = useState({+ buildMethod: 'auto',+ dockerfilePath: 'Dockerfile',+ customBuildCmd: '',+ customStartCmd: '',+ cacheEnabled: true,+ timeout: 600,+ keepDeployments: 5+ });++ useEffect(() => {+ loadData();+ }, [appId]);++ async function loadData() {+ try {+ setLoading(true);+ const [configRes, detectRes, deploymentsRes] = await Promise.all([+ api.getBuildConfig(appId),+ api.detectBuildMethod(appId),+ api.getDeployments(appId, 10)+ ]);++ setDetection(detectRes);++ if (configRes.configured) {+ setBuildConfig(configRes.config);+ setConfigForm({+ buildMethod: configRes.config.build_method || 'auto',+ dockerfilePath: configRes.config.dockerfile_path || 'Dockerfile',+ customBuildCmd: configRes.config.custom_build_cmd || '',+ customStartCmd: configRes.config.custom_start_cmd || '',+ cacheEnabled: configRes.config.cache_enabled !== false,+ timeout: configRes.config.timeout || 600,+ keepDeployments: configRes.config.keep_deployments || 5+ });+ }++ setDeployments(deploymentsRes.deployments || []);+ setCurrentDeployment(deploymentsRes.current);++ } catch (err) {+ setError(err.message);+ } finally {+ setLoading(false);+ }+ }++ async function handleConfigureBuild(e) {+ e.preventDefault();+ try {+ await api.configureBuild(appId, {+ build_method: configForm.buildMethod,+ dockerfile_path: configForm.dockerfilePath,+ custom_build_cmd: configForm.customBuildCmd || null,+ custom_start_cmd: configForm.customStartCmd || null,+ cache_enabled: configForm.cacheEnabled,+ timeout: configForm.timeout,+ keep_deployments: configForm.keepDeployments+ });+ setShowConfigModal(false);+ toast.success('Build configuration saved');+ loadData();+ } catch (err) {+ setError(err.message);+ }+ }++ async function handleBuild(noCache = false) {+ setBuilding(true);+ setError(null);+ try {+ const result = await api.triggerBuild(appId, noCache);+ if (result.success) {+ toast.success('Build completed successfully');+ } else {+ setError(result.error || 'Build failed');+ }+ loadData();+ } catch (err) {+ setError(err.message);+ } finally {+ setBuilding(false);+ }+ }++ async function handleDeploy(noCache = false) {+ setDeploying(true);+ setError(null);+ try {+ const result = await api.deployApp(appId, { no_cache: noCache });+ if (result.success) {+ toast.success(`Deployment v${result.deployment.version} successful!`);+ } else {+ setError(result.error || 'Deployment failed');+ }+ loadData();+ } catch (err) {+ setError(err.message);+ } finally {+ setDeploying(false);+ }+ }++ async function handleRollback(version = null) {+ const rollbackMsg = version+ ? `Rollback to version ${version}? This will replace the current deployment.`+ : 'Rollback to previous deployment?';+ const confirmed = await confirmBuild({ title: 'Rollback', message: rollbackMsg, variant: 'warning' });+ if (!confirmed) return;++ setDeploying(true);+ setError(null);+ try {+ const result = await api.rollback(appId, version);+ if (result.success) {+ toast.success('Rollback successful');+ } else {+ setError(result.error || 'Rollback failed');+ }+ loadData();+ } catch (err) {+ setError(err.message);+ } finally {+ setDeploying(false);+ }+ }++ function getStatusPillKind(status) {+ switch (status) {+ case 'live': return 'green';+ case 'building':+ case 'deploying':+ case 'pending': return 'amber';+ case 'failed': return 'red';+ case 'rolled_back': return 'gray';+ default: return 'gray';+ }+ }++ function formatDuration(seconds) {+ if (!seconds) return '-';+ if (seconds < 60) return `${Math.round(seconds)}s`;+ return `${Math.floor(seconds / 60)}m ${Math.round(seconds % 60)}s`;+ }++ if (loading) {+ return <EmptyState loading title="Loading build configuration..." />;+ }++ return (+ <div className="build-tab">+ {error && (+ <div className="alert alert-danger">+ {error}+ <button onClick={() => setError(null)} className="alert-close">×</button>+ </div>+ )}++ {detection && (+ <div className="card">+ <h3>Auto-Detection Results</h3>+ <div className="detection-results">+ <div className="detection-item">+ <span className="detection-label">Detected Method:</span>+ <span className="detection-value">{detection.detected_method || 'None'}</span>+ </div>+ {detection.dockerfile_exists && (+ <div className="detection-item">+ <span className="detection-label">Dockerfile:</span>+ <span className="detection-value">Found</span>+ </div>+ )}+ {detection.docker_compose_exists && (+ <div className="detection-item">+ <span className="detection-label">Docker Compose:</span>+ <span className="detection-value">Found</span>+ </div>+ )}+ </div>+ </div>+ )}++ {app?.buildpack_plan && (+ <div className="card">+ <h3>Build Pack</h3>+ <BuildpackPreview+ plan={app.buildpack_plan}+ dockerfile={bpDockerfile}+ overrides={app.buildpack_overrides || {}}+ />+ </div>+ )}++ <div className="card">+ <div className="card-header-row">+ <h3>Build Configuration</h3>+ <Button variant="outline" size="sm" onClick={() => setShowConfigModal(true)}>+ Configure+ </Button>+ </div>+ {buildConfig ? (+ <InfoList>+ <InfoItem label="Method" value={buildConfig.build_method} />+ <InfoItem label="Timeout" value={`${buildConfig.timeout}s`} />+ </InfoList>+ ) : (+ <p className="hint">No build configuration. Click Configure to set up.</p>+ )}+ <div className="card-actions">+ <Button+ onClick={() => handleDeploy(false)}+ disabled={deploying || building}+ >+ {deploying ? 'Deploying...' : 'Build & Deploy'}+ </Button>+ <Button+ variant="outline"+ onClick={() => handleBuild(false)}+ disabled={building || deploying}+ >+ {building ? 'Building...' : 'Build Only'}+ </Button>+ </div>+ </div>++ {deployments.length > 0 && (+ <div className="card">+ <h3>Deployment History</h3>+ <div className="deployments-list">+ {deployments.map(dep => (+ <div key={dep.version} className={`deployment-item ${dep.status === 'live' ? 'current' : ''}`}>+ <div className="deployment-info">+ <span className="deployment-version">v{dep.version}</span>+ <Pill kind={getStatusPillKind(dep.status)}>{dep.status}</Pill>+ </div>+ <div className="deployment-meta">+ <span>{new Date(dep.created_at).toLocaleString()}</span>+ <span>{formatDuration(dep.build_duration)}</span>+ </div>+ {dep.status !== 'live' && (+ <Button+ variant="outline"+ size="sm"+ onClick={() => handleRollback(dep.version)}+ disabled={deploying}+ >+ Rollback+ </Button>+ )}+ </div>+ ))}+ </div>+ </div>+ )}++ <Modal open={showConfigModal} onClose={() => setShowConfigModal(false)} title="Build Configuration">+ <form onSubmit={handleConfigureBuild}>+ <div className="form-group">+ <label>Build Method</label>+ <select+ value={configForm.buildMethod}+ onChange={e => setConfigForm({...configForm, buildMethod: e.target.value})}+ >+ <option value="auto">Auto-detect</option>+ <option value="dockerfile">Dockerfile</option>+ <option value="docker-compose">Docker Compose</option>+ <option value="custom">Custom</option>+ </select>+ </div>+ {configForm.buildMethod === 'dockerfile' && (+ <div className="form-group">+ <label>Dockerfile Path</label>+ <Input+ type="text"+ value={configForm.dockerfilePath}+ onChange={e => setConfigForm({...configForm, dockerfilePath: e.target.value})}+ />+ </div>+ )}+ {configForm.buildMethod === 'custom' && (+ <>+ <div className="form-group">+ <label>Build Command</label>+ <Input+ type="text"+ value={configForm.customBuildCmd}+ onChange={e => setConfigForm({...configForm, customBuildCmd: e.target.value})}+ placeholder="npm run build"+ />+ </div>+ <div className="form-group">+ <label>Start Command</label>+ <Input+ type="text"+ value={configForm.customStartCmd}+ onChange={e => setConfigForm({...configForm, customStartCmd: e.target.value})}+ placeholder="npm start"+ />+ </div>+ </>+ )}+ <div className="form-group">+ <label>Timeout (seconds)</label>+ <Input+ type="number"+ value={configForm.timeout}+ onChange={e => setConfigForm({...configForm, timeout: parseInt(e.target.value)})}+ />+ </div>+ <div className="modal-actions">+ <Button type="button" variant="outline" onClick={() => setShowConfigModal(false)}>+ Cancel+ </Button>+ <Button type="submit">+ Save Configuration+ </Button>+ </div>+ </form>+ </Modal>+ </div>+ );+};++export default BuildTab;diff --git a/frontend/src/components/appdetail/CommandsTab.jsx b/frontend/src/components/appdetail/CommandsTab.jsxnew file mode 100644index 00000000..b583b784--- /dev/null+++ b/frontend/src/components/appdetail/CommandsTab.jsx@@ -0,0 +1,89 @@+import { useState } from 'react';+import api from '../../services/api';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';++const CommandsTab = ({ appId, appType }) => {+ const [command, setCommand] = useState('');+ const [output, setOutput] = useState(null);+ const [running, setRunning] = useState(false);++ const quickCommands = appType === 'django' ? [+ { label: 'Run Migrations', cmd: 'python manage.py migrate' },+ { label: 'Collect Static', cmd: 'python manage.py collectstatic --noinput' },+ { label: 'Create Superuser', cmd: 'python manage.py createsuperuser' },+ { label: 'Shell', cmd: 'python manage.py shell' },+ { label: 'Check', cmd: 'python manage.py check' },+ ] : [+ { label: 'Flask Routes', cmd: 'flask routes' },+ { label: 'Flask Shell', cmd: 'flask shell' },+ { label: 'DB Upgrade', cmd: 'flask db upgrade' },+ { label: 'DB Migrate', cmd: 'flask db migrate' },+ ];++ async function handleRun(cmd) {+ const commandToRun = cmd || command;+ if (!commandToRun.trim()) return;++ setRunning(true);+ setOutput(null);++ try {+ const result = await api.runPythonCommand(appId, commandToRun);+ setOutput(result);+ } catch (err) {+ setOutput({ success: false, stderr: err.message });+ } finally {+ setRunning(false);+ }+ }++ return (+ <div>+ <h3 className="app-eyebrow">Run Commands</h3>+ <p className="hint">Commands run in the app's virtual environment context.</p>++ <div className="quick-commands">+ {quickCommands.map(({ label, cmd }) => (+ <Button+ key={cmd}+ variant="outline"+ size="sm"+ onClick={() => handleRun(cmd)}+ disabled={running}+ >+ {label}+ </Button>+ ))}+ </div>++ <div className="command-input">+ <Input+ type="text"+ value={command}+ onChange={(e) => setCommand(e.target.value)}+ placeholder="Enter command..."+ onKeyDown={(e) => e.key === 'Enter' && handleRun()}+ />+ <Button+ onClick={() => handleRun()}+ disabled={running}+ >+ {running ? 'Running...' : 'Run'}+ </Button>+ </div>++ {output && (+ <div className={`command-output ${output.success ? '' : 'error'}`}>+ {output.stdout && <pre>{output.stdout}</pre>}+ {output.stderr && <pre className="stderr">{output.stderr}</pre>}+ {!output.stdout && !output.stderr && (+ <pre>{output.success ? 'Command completed successfully' : 'Command failed'}</pre>+ )}+ </div>+ )}+ </div>+ );+};++export default CommandsTab;diff --git a/frontend/src/components/appdetail/DeployTab.jsx b/frontend/src/components/appdetail/DeployTab.jsxnew file mode 100644index 00000000..275a846d--- /dev/null+++ b/frontend/src/components/appdetail/DeployTab.jsx@@ -0,0 +1,313 @@+import { useState, useEffect } from 'react';+import { GitMerge } from 'lucide-react';+import api from '../../services/api';+import EmptyState from '../EmptyState';+import { useToast } from '../../contexts/ToastContext';+import { useConfirm } from '../../hooks/useConfirm';+import { InfoList, InfoItem } from '../InfoList';+import DeploymentTimeline from '../deployments/DeploymentTimeline';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Textarea } from '@/components/ui/textarea';+import { Pill } from '@/components/ds';+import Modal from '@/components/Modal';++const DeployTab = ({ appId, appPath }) => {+ const toast = useToast();+ const { confirm: confirmDeploy } = useConfirm();+ const [config, setConfig] = useState(null);+ const [gitStatus, setGitStatus] = useState(null);+ const [history, setHistory] = useState([]);+ const [loading, setLoading] = useState(true);+ const [deploying, setDeploying] = useState(false);+ const [showConfigModal, setShowConfigModal] = useState(false);+ const [loadingBranches, setLoadingBranches] = useState(false);+ const [branches, setBranches] = useState([]);+ const [error, setError] = useState(null);++ const [configForm, setConfigForm] = useState({+ repoUrl: '',+ branch: 'main',+ autoDeploy: true,+ preDeployScript: '',+ postDeployScript: ''+ });++ useEffect(() => {+ loadData();+ }, [appId]);++ async function loadData() {+ try {+ setLoading(true);+ const [configRes, historyRes] = await Promise.all([+ api.getDeployConfig(appId),+ api.getDeploymentHistory(appId, 20)+ ]);++ if (configRes.configured) {+ setConfig(configRes.config);+ setConfigForm({+ repoUrl: configRes.config.repo_url || '',+ branch: configRes.config.branch || 'main',+ autoDeploy: configRes.config.auto_deploy !== false,+ preDeployScript: configRes.config.pre_deploy_script || '',+ postDeployScript: configRes.config.post_deploy_script || ''+ });+ try {+ const statusRes = await api.getAppGitStatus(appId);+ setGitStatus(statusRes);+ } catch { /* git status is optional context for the deploy tab */ }+ } else {+ setConfig(null);+ }++ setHistory(historyRes.deployments || []);+ } catch (err) {+ setError(err.message);+ } finally {+ setLoading(false);+ }+ }++ async function handleConfigureDeployment(e) {+ e.preventDefault();+ try {+ await api.configureDeployment(+ appId,+ configForm.repoUrl,+ configForm.branch,+ configForm.autoDeploy,+ configForm.preDeployScript || null,+ configForm.postDeployScript || null+ );+ setShowConfigModal(false);+ loadData();+ } catch (err) {+ setError(err.message);+ }+ }++ async function handleRemoveDeployment() {+ const confirmed = await confirmDeploy({ title: 'Remove Deployment', message: 'Remove deployment configuration? This will not delete the repository files.', variant: 'warning' });+ if (!confirmed) return;+ try {+ await api.removeDeployment(appId);+ setConfig(null);+ setGitStatus(null);+ loadData();+ } catch (err) {+ setError(err.message);+ }+ }++ async function handleDeploy(force = false) {+ setDeploying(true);+ setError(null);+ try {+ const result = await api.triggerAppDeploy(appId, force);+ if (result.success) {+ toast.success('Deployment completed successfully!');+ } else {+ setError(result.error || 'Deployment failed');+ }+ loadData();+ } catch (err) {+ setError(err.message);+ } finally {+ setDeploying(false);+ }+ }++ async function handlePull() {+ setDeploying(true);+ setError(null);+ try {+ const result = await api.pullChanges(appId);+ if (result.success) {+ toast.success('Changes pulled successfully!');+ } else {+ setError(result.error || 'Pull failed');+ }+ loadData();+ } catch (err) {+ setError(err.message);+ } finally {+ setDeploying(false);+ }+ }++ function getStatusPillKind(status) {+ switch (status) {+ case 'success': return 'green';+ case 'failed': return 'red';+ case 'in_progress': return 'amber';+ default: return 'gray';+ }+ }++ if (loading) {+ return <EmptyState loading title="Loading deployment configuration..." />;+ }++ return (+ <div className="deploy-tab">+ {error && (+ <div className="alert alert-danger">+ {error}+ <button onClick={() => setError(null)} className="alert-close">×</button>+ </div>+ )}++ {!config ? (+ <div className="deploy-setup">+ <EmptyState+ icon={GitMerge}+ title="Git Deployment Not Configured"+ description="Connect a Git repository to enable automatic deployments via webhooks or manual triggers."+ action={<Button onClick={() => setShowConfigModal(true)}>Configure Deployment</Button>}+ />+ </div>+ ) : (+ <>+ <div className="deploy-header">+ <div className="deploy-status-card">+ <div className="deploy-repo-info">+ <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" fill="none" strokeWidth="2">+ <path d="M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"/>+ </svg>+ <div>+ <span className="repo-url">{config.repo_url}</span>+ <span className="repo-branch">Branch: {config.branch}</span>+ </div>+ </div>+ <div className="deploy-actions">+ <Button+ variant="outline"+ size="sm"+ onClick={handlePull}+ disabled={deploying}+ >+ Pull Only+ </Button>+ <Button+ onClick={() => handleDeploy(false)}+ disabled={deploying}+ >+ {deploying ? 'Deploying...' : 'Deploy Now'}+ </Button>+ </div>+ </div>+ </div>++ <div className="deploy-grid">+ <div className="card">+ <h3>Configuration</h3>+ <InfoList>+ <InfoItem label="Repository" value={config.repo_url} mono />+ <InfoItem label="Branch" value={config.branch} />+ <InfoItem label="Auto Deploy" value={config.auto_deploy ? 'Enabled' : 'Disabled'} />+ </InfoList>+ <div className="card-actions">+ <Button variant="outline" size="sm" onClick={() => setShowConfigModal(true)}>+ Edit+ </Button>+ <Button variant="destructive" size="sm" onClick={handleRemoveDeployment}>+ Remove+ </Button>+ </div>+ </div>++ {history.length > 0 && (+ <div className="card">+ <h3>Deployment History</h3>+ <div className="deployments-list">+ {history.slice(0, 5).map((dep, idx) => (+ <div key={idx} className="deployment-item">+ <Pill kind={getStatusPillKind(dep.status)}>{dep.status}</Pill>+ <span className="deployment-date">{new Date(dep.timestamp).toLocaleString()}</span>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+ </>+ )}++ {/* Config snapshot timeline + diff — additive, independent of git+ config so it shows the deploy history & config changes for any app. */}+ <div className="card deploy-timeline-card">+ <h3>Deployment Timeline</h3>+ <p className="deploy-timeline-card__hint">+ An immutable configuration snapshot (env keys, domains, image, build+ method, volumes) is captured before each deployment. Secret values are+ masked. Open a snapshot to diff it against the previous one or restore it.+ </p>+ <DeploymentTimeline appId={appId} />+ </div>++ <Modal open={showConfigModal} onClose={() => setShowConfigModal(false)} title="Configure Deployment">+ <form onSubmit={handleConfigureDeployment}>+ <div className="form-group">+ <label>Repository URL</label>+ <Input+ type="text"+ value={configForm.repoUrl}+ onChange={e => setConfigForm({...configForm, repoUrl: e.target.value})}+ placeholder="https://github.com/user/repo.git"+ required+ />+ </div>+ <div className="form-group">+ <label>Branch</label>+ <Input+ type="text"+ value={configForm.branch}+ onChange={e => setConfigForm({...configForm, branch: e.target.value})}+ placeholder="main"+ />+ </div>+ <div className="form-group">+ <label className="checkbox-label">+ <input+ type="checkbox"+ checked={configForm.autoDeploy}+ onChange={e => setConfigForm({...configForm, autoDeploy: e.target.checked})}+ />+ <span>Enable auto-deploy on push</span>+ </label>+ </div>+ <div className="form-group">+ <label>Pre-deploy Script</label>+ <Textarea+ value={configForm.preDeployScript}+ onChange={e => setConfigForm({...configForm, preDeployScript: e.target.value})}+ placeholder="npm install"+ rows={3}+ />+ </div>+ <div className="form-group">+ <label>Post-deploy Script</label>+ <Textarea+ value={configForm.postDeployScript}+ onChange={e => setConfigForm({...configForm, postDeployScript: e.target.value})}+ placeholder="npm run build"+ rows={3}+ />+ </div>+ <div className="modal-actions">+ <Button type="button" variant="outline" onClick={() => setShowConfigModal(false)}>+ Cancel+ </Button>+ <Button type="submit">+ Save Configuration+ </Button>+ </div>+ </form>+ </Modal>+ </div>+ );+};++export default DeployTab;diff --git a/frontend/src/components/appdetail/GunicornTab.jsx b/frontend/src/components/appdetail/GunicornTab.jsxnew file mode 100644index 00000000..f04080c3--- /dev/null+++ b/frontend/src/components/appdetail/GunicornTab.jsx@@ -0,0 +1,63 @@+import { useState, useEffect } from 'react';+import api from '../../services/api';+import EmptyState from '../EmptyState';+import { useToast } from '../../contexts/ToastContext';+import { Button } from '@/components/ui/button';++const GunicornTab = ({ appId }) => {+ const toast = useToast();+ const [config, setConfig] = useState('');+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);++ useEffect(() => {+ loadConfig();+ }, [appId]);++ async function loadConfig() {+ try {+ const data = await api.getGunicornConfig(appId);+ setConfig(data.content || '');+ } catch (err) {+ console.error('Failed to load config:', err);+ } finally {+ setLoading(false);+ }+ }++ async function handleSave() {+ setSaving(true);+ try {+ await api.updateGunicornConfig(appId, config);+ toast.success('Configuration saved. Restart the app to apply changes.');+ } catch (err) {+ toast.error('Failed to save configuration');+ console.error('Failed to save config:', err);+ } finally {+ setSaving(false);+ }+ }++ if (loading) {+ return <EmptyState loading title="Loading Gunicorn configuration..." />;+ }++ return (+ <div>+ <div className="section-header">+ <h3>Gunicorn Configuration</h3>+ <Button onClick={handleSave} disabled={saving}>+ {saving ? 'Saving...' : 'Save'}+ </Button>+ </div>+ <textarea+ className="code-editor"+ value={config}+ onChange={(e) => setConfig(e.target.value)}+ spellCheck={false}+ />+ </div>+ );+};++export default GunicornTab;diff --git a/frontend/src/components/appdetail/LogsTab.jsx b/frontend/src/components/appdetail/LogsTab.jsxnew file mode 100644index 00000000..22a714e2--- /dev/null+++ b/frontend/src/components/appdetail/LogsTab.jsx@@ -0,0 +1,71 @@+import { useState, useEffect } from 'react';+import api from '../../services/api';+import { Button } from '@/components/ui/button';++const LogsTab = ({ app }) => {+ const [logs, setLogs] = useState('');+ const [loading, setLoading] = useState(true);+ const [autoRefresh, setAutoRefresh] = useState(false);++ const isDockerApp = app.app_type === 'docker';+ const isPythonApp = ['flask', 'django'].includes(app.app_type);++ useEffect(() => {+ loadLogs();+ }, [app.id]);++ useEffect(() => {+ if (!autoRefresh) return;+ const interval = setInterval(loadLogs, 5000);+ return () => clearInterval(interval);+ }, [autoRefresh, app.id]);++ async function loadLogs() {+ try {+ let data;+ if (isDockerApp) {+ data = await api.getDockerAppLogs(app.id, 200);+ } else if (isPythonApp) {+ data = await api.getPythonAppLogs(app.id, 200);+ } else {+ data = { logs: 'Logs not available for this app type.' };+ }+ setLogs(data.logs || 'No logs available');+ } catch (err) {+ console.error('Failed to load logs:', err);+ setLogs('Failed to load logs');+ } finally {+ setLoading(false);+ }+ }++ return (+ <div className="logs-tab">+ <div className="logs-header">+ <h3>Application Logs</h3>+ <div className="logs-controls">+ {isPythonApp && (+ <span className="hint">Gunicorn/systemd Logs</span>+ )}+ {isDockerApp && (+ <span className="hint">Docker Compose Logs</span>+ )}+ <label className="checkbox-inline">+ <input+ type="checkbox"+ checked={autoRefresh}+ onChange={(e) => setAutoRefresh(e.target.checked)}+ />+ Auto-refresh+ </label>+ <Button variant="outline" size="sm" onClick={loadLogs}>+ Refresh+ </Button>+ </div>+ </div>+ <pre className="log-viewer">{loading ? 'Loading...' : logs}</pre>+ </div>+ );+};++export default LogsTab;diff --git a/frontend/src/components/appdetail/OverviewTab.jsx b/frontend/src/components/appdetail/OverviewTab.jsxnew file mode 100644index 00000000..2fcb1e68--- /dev/null+++ b/frontend/src/components/appdetail/OverviewTab.jsx@@ -0,0 +1,374 @@+import { useState, useEffect } from 'react';+import { useNavigate } from 'react-router-dom';+import api from '../../services/api';+import { formatBytes } from '@/utils/formatBytes';+import { useConfirm } from '../../hooks/useConfirm';+import PrivateURLSection from '../PrivateURLSection';+import LinkedAppsSection from '../LinkedAppsSection';+import LinkAppModal from '../LinkAppModal';+import TagsPanel from '../shared/TagsPanel';+import EnvironmentVariablesPanel from '../shared/EnvironmentVariablesPanel';+import { Button } from '@/components/ui/button';++// Overview Tab with new grid layout+const OverviewTab = ({ app, onUpdate }) => {+ const navigate = useNavigate();+ const { confirm: confirmOverview } = useConfirm();+ const [status, setStatus] = useState(null);+ const [appStatus, setAppStatus] = useState(null);+ const [linkedApps, setLinkedApps] = useState([]);+ const [showLinkModal, setShowLinkModal] = useState(false);+ const [linkLoading, setLinkLoading] = useState(false);+ const [containerStats, setContainerStats] = useState(null);++ useEffect(() => {+ if (['flask', 'django'].includes(app.app_type)) {+ loadStatus();+ }+ loadAppStatus();+ loadLinkedApps();+ if (app.app_type === 'docker') {+ loadContainerStats();+ }+ }, [app]);++ async function loadStatus() {+ try {+ const data = await api.getPythonAppStatus(app.id);+ setStatus(data);+ } catch (err) {+ console.error('Failed to load status:', err);+ }+ }++ async function loadAppStatus() {+ try {+ const data = await api.getAppStatus(app.id);+ setAppStatus(data);+ } catch (err) {+ console.error('Failed to load app status:', err);+ }+ }++ async function loadLinkedApps() {+ try {+ const data = await api.getLinkedApps(app.id);+ setLinkedApps(data.linked_apps || []);+ } catch (err) {+ console.error('Failed to load linked apps:', err);+ }+ }++ async function loadContainerStats() {+ try {+ // Try to get container stats for docker apps+ const containers = await api.getContainers(true);+ const appContainer = containers.containers?.find(c =>+ c.name?.includes(app.name) || c.name?.includes(app.slug)+ );+ if (appContainer && appContainer.state === 'running') {+ const stats = await api.getContainerStats(appContainer.id);+ setContainerStats(stats.stats);+ }+ } catch (err) {+ console.error('Failed to load container stats:', err);+ }+ }++ async function handleUnlink() {+ const confirmed = await confirmOverview({ title: 'Unlink Apps', message: 'Are you sure you want to unlink these apps? Database credentials will remain unchanged.', variant: 'warning' });+ if (!confirmed) {+ return;+ }+ setLinkLoading(true);+ try {+ await api.unlinkApp(app.id);+ onUpdate();+ loadLinkedApps();+ } catch (err) {+ console.error('Failed to unlink apps:', err);+ } finally {+ setLinkLoading(false);+ }+ }++ function handleLinked() {+ onUpdate();+ loadLinkedApps();+ }++ function parseResourceValue(value) {+ if (!value) return 0;+ return parseFloat(value.replace('%', '')) || 0;+ }++ return (+ <div className="app-overview-grid">+ {/* Left Column */}+ <div className="app-overview-left">+ {/* Application Info Panel */}+ <div className="app-panel">+ <div className="app-panel-header">Application Info</div>+ <div className="app-panel-body">+ <div className="app-info-grid">+ <div className="app-info-item">+ <span className="app-info-label">Type</span>+ <span className="app-info-value">{app.app_type === 'docker' ? 'Docker Container' : app.app_type.toUpperCase()}</span>+ </div>+ <div className="app-info-item">+ <span className="app-info-label">Port</span>+ <span className="app-info-value">+ {app.port || '-'}+ {appStatus && app.port && (+ <span className={`port-indicator ${appStatus.port_accessible ? 'accessible' : ''}`}>+ {appStatus.port_accessible ? ' (accessible)' : ' (not accessible)'}+ </span>+ )}+ </span>+ </div>+ {app.python_version && (+ <div className="app-info-item">+ <span className="app-info-label">Python Version</span>+ <span className="app-info-value">{app.python_version}</span>+ </div>+ )}+ {app.php_version && (+ <div className="app-info-item">+ <span className="app-info-label">PHP Version</span>+ <span className="app-info-value">{app.php_version}</span>+ </div>+ )}+ <div className="app-info-item full-width">+ <span className="app-info-label">Root Path</span>+ <div><span className="app-path-value">{app.root_path || `/var/serverkit/apps/${app.name}`}</span></div>+ </div>+ </div>+ </div>+ </div>++ {/* Routing Diagnostics Panel (Docker apps only) */}+ {app.app_type === 'docker' && (+ <RoutingDiagnosticsPanel appId={app.id} />+ )}++ {/* Environment Linking Panel */}+ <div className="app-panel">+ <div className="app-panel-header">Environment Linking</div>+ <div className="app-panel-body">+ <p className="app-panel-hint">+ Link this app to another to create a production/development pair. Linked apps can share database credentials.+ </p>+ <LinkedAppsSection+ app={app}+ linkedApps={linkedApps}+ onLink={() => setShowLinkModal(true)}+ onUnlink={handleUnlink}+ onNavigate={(appId) => navigate(`/apps/${appId}`)}+ loading={linkLoading}+ compact+ />+ </div>+ </div>++ {/* Process Status (Python apps) */}+ {status && (+ <div className="app-panel">+ <div className="app-panel-header">Process Status</div>+ <div className="app-panel-body">+ <div className="app-info-grid">+ <div className="app-info-item">+ <span className="app-info-label">Service</span>+ <span className="app-info-value mono">{status.service_name}</span>+ </div>+ <div className="app-info-item">+ <span className="app-info-label">State</span>+ <span className="app-info-value">{status.active_state} ({status.sub_state})</span>+ </div>+ {status.main_pid !== '0' && (+ <div className="app-info-item">+ <span className="app-info-label">PID</span>+ <span className="app-info-value mono">{status.main_pid}</span>+ </div>+ )}+ {status.memory && status.memory !== '0' && (+ <div className="app-info-item">+ <span className="app-info-label">Memory</span>+ <span className="app-info-value">{formatBytes(parseInt(status.memory))}</span>+ </div>+ )}+ </div>+ </div>+ </div>+ )}++ {/* Domains Panel */}+ {app.domains && app.domains.length > 0 && (+ <div className="app-panel">+ <div className="app-panel-header">Domains</div>+ <div className="app-panel-body">+ <div className="domains-list">+ {app.domains.map(domain => (+ <div key={domain.id} className="domain-item">+ <a href={`https://${domain.name}`} target="_blank" rel="noopener noreferrer">+ {domain.name}+ </a>+ {domain.ssl_enabled && (+ <span className="ssl-badge">SSL</span>+ )}+ </div>+ ))}+ </div>+ </div>+ </div>+ )}+ </div>++ {/* Right Column */}+ <div className="app-overview-right">+ {/* Private URL Panel (Docker apps with port) */}+ {app.app_type === 'docker' && app.port && (+ <PrivateURLSection app={app} onUpdate={onUpdate} />+ )}++ {/* Live Resources Panel */}+ {app.app_type === 'docker' && (+ <div className="app-panel">+ <div className="app-panel-header">Live Resources</div>+ <div className="app-panel-body">+ <div className="resource-bar-container">+ <div className="resource-bar-header">+ <span className="resource-bar-label">CPU Load</span>+ <span className="resource-bar-value">+ {containerStats ? `${parseResourceValue(containerStats.CPUPerc).toFixed(0)}%` : '-'}+ </span>+ </div>+ <div className="resource-bar-track">+ <div+ className="resource-bar-fill cpu"+ style={{ width: `${containerStats ? parseResourceValue(containerStats.CPUPerc) : 0}%` }}+ />+ </div>+ </div>+ <div className="resource-bar-container">+ <div className="resource-bar-header">+ <span className="resource-bar-label">RAM Usage</span>+ <span className="resource-bar-value">+ {containerStats?.MemUsage || '-'}+ </span>+ </div>+ <div className="resource-bar-track">+ <div+ className="resource-bar-fill ram"+ style={{ width: `${containerStats ? parseResourceValue(containerStats.MemPerc) : 0}%` }}+ />+ </div>+ </div>+ {!containerStats && app.status !== 'running' && (+ <p className="resource-hint">Start the container to see live resources.</p>+ )}+ </div>+ </div>+ )}++ {/* Tags Panel (polymorphic shared resource) */}+ <div className="app-panel">+ <div className="app-panel-header">Tags</div>+ <div className="app-panel-body">+ <TagsPanel resourceType="application" resourceId={app.id} />+ </div>+ </div>++ {/* Shared Variables Panel (resolved from attached groups) */}+ <div className="app-panel">+ <div className="app-panel-body">+ <EnvironmentVariablesPanel resourceType="application" resourceId={app.id} />+ </div>+ </div>+ </div>++ {showLinkModal && (+ <LinkAppModal+ app={app}+ onClose={() => setShowLinkModal(false)}+ onLinked={handleLinked}+ />+ )}+ </div>+ );+};++// Routing Diagnostics Panel+const RoutingDiagnosticsPanel = ({ appId }) => {+ const [diagnostics, setDiagnostics] = useState(null);+ const [loading, setLoading] = useState(false);+ const [lastChecked, setLastChecked] = useState(null);++ async function runDiagnostics() {+ setLoading(true);+ try {+ const response = await fetch(`/api/v1/domains/debug/diagnose/${appId}`, {+ headers: {+ 'Authorization': `Bearer ${localStorage.getItem('accessToken')}`+ }+ });+ const data = await response.json();+ setDiagnostics(data);+ setLastChecked(new Date());+ } catch (err) {+ console.error('Failed to run diagnostics:', err);+ } finally {+ setLoading(false);+ }+ }++ const isHealthy = diagnostics?.health?.overall;++ return (+ <div className="app-panel">+ <div className="app-panel-header">+ <span>Routing Diagnostics</span>+ <span className="app-panel-header-actions">+ <Button+ variant="ghost"+ size="sm"+ onClick={runDiagnostics}+ disabled={loading}+ >+ {loading ? 'Checking...' : 'Run Diagnostics'}+ </Button>+ </span>+ </div>+ <div className="app-panel-body">+ {diagnostics ? (+ <>+ <div className={`diag-status ${isHealthy ? 'healthy' : 'unhealthy'}`}>+ <div className={`diag-icon ${isHealthy ? 'healthy' : 'unhealthy'}`}>+ {isHealthy ? '✓' : '✗'}+ </div>+ <div className="diag-text">+ <h4>{isHealthy ? 'Configuration Healthy' : 'Issues Detected'}</h4>+ <p>+ {lastChecked && `Last checked: ${Math.round((Date.now() - lastChecked) / 60000)} minutes ago. `}+ {isHealthy ? 'No routing issues detected.' : 'Some checks failed.'}+ </p>+ </div>+ </div>+ {diagnostics.health?.issues?.length > 0 && (+ <ul className="diag-issues">+ {diagnostics.health.issues.map((issue, i) => (+ <li key={i}>{issue}</li>+ ))}+ </ul>+ )}+ </>+ ) : (+ <p className="app-panel-hint">+ Click "Run Diagnostics" to check routing configuration and identify issues.+ </p>+ )}+ </div>+ </div>+ );+};++export default OverviewTab;diff --git a/frontend/src/components/appdetail/PackagesTab.jsx b/frontend/src/components/appdetail/PackagesTab.jsxnew file mode 100644index 00000000..d2df274d--- /dev/null+++ b/frontend/src/components/appdetail/PackagesTab.jsx@@ -0,0 +1,93 @@+import { useState, useEffect } from 'react';+import api from '../../services/api';+import EmptyState from '../EmptyState';+import { useToast } from '../../contexts/ToastContext';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';++const PackagesTab = ({ appId }) => {+ const toast = useToast();+ const [packages, setPackages] = useState([]);+ const [loading, setLoading] = useState(true);+ const [installing, setInstalling] = useState(false);+ const [newPackage, setNewPackage] = useState('');++ useEffect(() => {+ loadPackages();+ }, [appId]);++ async function loadPackages() {+ try {+ const data = await api.getPythonPackages(appId);+ setPackages(data.packages || []);+ } catch (err) {+ console.error('Failed to load packages:', err);+ } finally {+ setLoading(false);+ }+ }++ async function handleInstall(e) {+ e.preventDefault();+ if (!newPackage.trim()) return;++ setInstalling(true);+ try {+ await api.installPythonPackages(appId, [newPackage.trim()]);+ setNewPackage('');+ loadPackages();+ } catch (err) {+ console.error('Failed to install package:', err);+ } finally {+ setInstalling(false);+ }+ }++ async function handleFreeze() {+ try {+ await api.freezePythonRequirements(appId);+ toast.success('requirements.txt updated');+ } catch (err) {+ toast.error('Failed to freeze requirements');+ console.error('Failed to freeze requirements:', err);+ }+ }++ if (loading) {+ return <EmptyState loading title="Loading packages..." />;+ }++ return (+ <div>+ <div className="section-header">+ <h3>Installed Packages</h3>+ <Button variant="outline" size="sm" onClick={handleFreeze}>+ Freeze to requirements.txt+ </Button>+ </div>++ <form className="install-form" onSubmit={handleInstall}>+ <Input+ type="text"+ value={newPackage}+ onChange={(e) => setNewPackage(e.target.value)}+ placeholder="Package name (e.g., requests, flask==2.0.0)"+ />+ <Button type="submit" disabled={installing}>+ {installing ? 'Installing...' : 'Install'}+ </Button>+ </form>++ <div className="packages-list">+ {packages.map(pkg => (+ <div key={pkg.name} className="package-item">+ <span className="package-name">{pkg.name}</span>+ <span className="package-version">{pkg.version}</span>+ </div>+ ))}+ </div>+ </div>+ );+};++export default PackagesTab;diff --git a/frontend/src/components/appdetail/SettingsTab.jsx b/frontend/src/components/appdetail/SettingsTab.jsxnew file mode 100644index 00000000..586156e5--- /dev/null+++ b/frontend/src/components/appdetail/SettingsTab.jsx@@ -0,0 +1,142 @@+import { useState } from 'react';+import { useNavigate } from 'react-router-dom';+import api from '../../services/api';+import { useConfirm } from '../../hooks/useConfirm';+import { DangerZone } from '../DangerZone';+import { Button } from '@/components/ui/button';+import { EnvTag } from '@/components/ds';++const SettingsTab = ({ app, onUpdate }) => {+ const navigate = useNavigate();+ const { confirm: confirmAppSettings } = useConfirm();+ const [deleting, setDeleting] = useState(false);+ const [environmentType, setEnvironmentType] = useState(app.environment_type || 'standalone');+ const [savingEnvironment, setSavingEnvironment] = useState(false);+ const [unlinking, setUnlinking] = useState(false);++ const envLabels = {+ standalone: 'Standalone',+ production: 'Production',+ development: 'Development',+ staging: 'Staging'+ };++ async function handleDelete() {+ const firstConfirm = await confirmAppSettings({ title: 'Delete Application', message: `Delete ${app.name}? This action cannot be undone.` });+ if (!firstConfirm) return;+ const secondConfirm = await confirmAppSettings({ title: 'Confirm Deletion', message: 'Are you sure? This will permanently delete the application and all its data.' });+ if (!secondConfirm) return;++ setDeleting(true);+ try {+ await api.deleteApp(app.id);+ navigate('/apps');+ } catch (err) {+ console.error('Failed to delete app:', err);+ setDeleting(false);+ }+ }++ async function handleEnvironmentChange(newType) {+ if (newType === app.environment_type) return;++ setSavingEnvironment(true);+ try {+ await api.updateAppEnvironment(app.id, newType);+ setEnvironmentType(newType);+ onUpdate();+ } catch (err) {+ console.error('Failed to update environment:', err);+ setEnvironmentType(app.environment_type || 'standalone');+ } finally {+ setSavingEnvironment(false);+ }+ }++ async function handleUnlink() {+ const confirmed = await confirmAppSettings({ title: 'Unlink Application', message: `Unlink ${app.name} from its linked application? Both apps will become standalone.`, variant: 'warning' });+ if (!confirmed) return;++ setUnlinking(true);+ try {+ await api.unlinkApp(app.id);+ onUpdate();+ } catch (err) {+ console.error('Failed to unlink app:', err);+ } finally {+ setUnlinking(false);+ }+ }++ return (+ <div>+ <h3 className="app-eyebrow">Application Settings</h3>++ <div className="card settings-section">+ <h4>Environment Configuration</h4>+ <div className="settings-row">+ <div className="settings-label">+ <span>Environment Type</span>+ <span className="settings-hint">+ {app.has_linked_app+ ? 'This app is linked. Unlink to change environment type.'+ : 'Set how this application is used in your workflow.'}+ </span>+ </div>+ <div className="settings-control">+ {app.has_linked_app ? (+ <EnvTag env={app.environment_type}>+ {envLabels[app.environment_type] || app.environment_type}+ </EnvTag>+ ) : (+ <select+ value={environmentType}+ onChange={(e) => handleEnvironmentChange(e.target.value)}+ disabled={savingEnvironment}+ className="settings-select"+ >+ <option value="standalone">Standalone</option>+ <option value="development">Development</option>+ <option value="staging">Staging</option>+ <option value="production">Production</option>+ </select>+ )}+ {savingEnvironment && <span className="settings-saving">Saving...</span>}+ </div>+ </div>++ {app.has_linked_app && (+ <div className="settings-row settings-linked-warning">+ <div className="settings-label">+ <span>Linked Application</span>+ <span className="settings-hint">+ This app is linked to another application. Unlinking will reset both apps to standalone mode.+ </span>+ </div>+ <div className="settings-control">+ <Button+ variant="outline"+ onClick={handleUnlink}+ disabled={unlinking}+ >+ {unlinking ? 'Unlinking...' : 'Unlink Application'}+ </Button>+ </div>+ </div>+ )}+ </div>++ <DangerZone+ title="Danger Zone"+ description="Once you delete an application, there is no going back."+ action={+ <Button variant="destructive" onClick={handleDelete} disabled={deleting}>+ {deleting ? 'Deleting...' : 'Delete Application'}+ </Button>+ }+ />+ </div>+ );+};++export default SettingsTab;diff --git a/frontend/src/components/appdetail/appDetailShared.jsx b/frontend/src/components/appdetail/appDetailShared.jsxnew file mode 100644index 00000000..7979e319--- /dev/null+++ b/frontend/src/components/appdetail/appDetailShared.jsx@@ -0,0 +1,16 @@+// statusInfo.dotClass → ds Pill kind+export const STATUS_PILL = {+ live: 'green',+ stopped: 'gray',+ deploying: 'amber',+ building: 'amber',+ failed: 'red',+};++// Ingress plane → label + Pill kind. Host Nginx is the neutral default;+// a managed proxy stack reads as the accent (cyan) choice. NULL/undefined+// reads as host Nginx, matching the backend.+export const INGRESS_META = {+ proxy_stack: { label: 'Proxy stack', kind: 'cyan' },+ nginx: { label: 'Nginx', kind: 'gray' },+};diff --git a/frontend/src/components/serverdetail/AlertsTab.jsx b/frontend/src/components/serverdetail/AlertsTab.jsxnew file mode 100644index 00000000..7065cb80--- /dev/null+++ b/frontend/src/components/serverdetail/AlertsTab.jsx@@ -0,0 +1,92 @@+import EmptyState from '../EmptyState';+import { BellRing } from 'lucide-react';+import {+ SecurityAlertItem,+ AlertIcon,+ InfoCircleIcon,+} from './serverDetailShared';++const AlertsTab = ({ notifications, securityAlerts, onAcknowledge, onResolve }) => {+ const sysItems = notifications || [];+ const secItems = securityAlerts || [];+ const openSec = secItems.filter(a => a.status === 'open');+ const ackSec = secItems.filter(a => a.status === 'acknowledged');++ if (sysItems.length === 0 && secItems.length === 0) {+ return (+ <div className="alerts-tab">+ <EmptyState+ icon={BellRing}+ title="All clear"+ description="No active alerts for this server."+ />+ </div>+ );+ }++ return (+ <div className="alerts-tab">+ {sysItems.length > 0 && (+ <section className="alerts-section">+ <header className="alerts-section__header">+ <h3>System</h3>+ <span className="alerts-section__count">{sysItems.length}</span>+ </header>+ <ul className="notifications-list">+ {sysItems.map((n) => (+ <li key={n.id} className={`notification notification--${n.severity || 'info'}`}>+ <span className="notification__icon">+ {n.severity === 'warning' || n.severity === 'danger' ? <AlertIcon /> : <InfoCircleIcon />}+ </span>+ <div className="notification__body">+ <div className="notification__title">{n.title}</div>+ <p className="notification__message">{n.message}</p>+ </div>+ </li>+ ))}+ </ul>+ </section>+ )}++ {openSec.length > 0 && (+ <section className="alerts-section">+ <header className="alerts-section__header">+ <h3>Security</h3>+ <span className="alerts-section__count">{openSec.length} open</span>+ </header>+ <ul className="notifications-list">+ {openSec.map(a => (+ <SecurityAlertItem+ key={a.id}+ alert={a}+ onAcknowledge={onAcknowledge}+ onResolve={onResolve}+ />+ ))}+ </ul>+ </section>+ )}++ {ackSec.length > 0 && (+ <section className="alerts-section alerts-section--muted">+ <header className="alerts-section__header">+ <h3>Acknowledged</h3>+ <span className="alerts-section__count">{ackSec.length}</span>+ </header>+ <ul className="notifications-list">+ {ackSec.map(a => (+ <SecurityAlertItem+ key={a.id}+ alert={a}+ onAcknowledge={onAcknowledge}+ onResolve={onResolve}+ />+ ))}+ </ul>+ </section>+ )}+ </div>+ );+};++export default AlertsTab;diff --git a/frontend/src/components/serverdetail/CloudflaredTab.jsx b/frontend/src/components/serverdetail/CloudflaredTab.jsxnew file mode 100644index 00000000..04aeaf3d--- /dev/null+++ b/frontend/src/components/serverdetail/CloudflaredTab.jsx@@ -0,0 +1,453 @@+import { useState, useEffect, useCallback } from 'react';+import api from '../../services/api';+import { useToast } from '../../contexts/ToastContext';+import { useConfirm } from '../../hooks/useConfirm';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Pill } from '../ds';+import EmptyState from '../EmptyState';+import { Cloud } from 'lucide-react';+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogFooter,+} from '@/components/ui/dialog';+import { Label } from '@/components/ui/label';+import {+ OfflineIcon,+ TrashIcon,+} from './serverDetailShared';++// CloudflaredTab — manage Cloudflare named tunnels via the agent.+//+// Auth model: the user runs `cloudflared tunnel login` once on the+// server. That writes ~/.cloudflared/cert.pem (or+// /etc/cloudflared/cert.pem when run as root). The panel never sees+// a Cloudflare API token — every action shells out to cloudflared+// using that cert. /status surfaces both "binary present" and+// "cert present" so we can show "log in first" before users hit+// CRUD actions and get confusing errors back.+const CloudflaredTab = ({ serverId, serverStatus }) => {+ const toast = useToast();+ const { confirm: confirmCf } = useConfirm();+ const [status, setStatus] = useState(null);+ const [tunnels, setTunnels] = useState([]);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState(null);++ const [showCreateModal, setShowCreateModal] = useState(false);+ const [createName, setCreateName] = useState('');+ const [creating, setCreating] = useState(false);++ const [showRouteModal, setShowRouteModal] = useState(false);+ const [routeTunnel, setRouteTunnel] = useState(null);+ const [routeHostname, setRouteHostname] = useState('');+ const [routing, setRouting] = useState(false);++ // Login flow: { channel, authUrl, status: 'starting'|'awaiting'|'done'|'error', error, certPath }+ const [login, setLogin] = useState(null);++ const loadStatus = useCallback(async () => {+ try {+ const s = await api.getRemoteCloudflaredStatus(serverId);+ setStatus(s);+ } catch (err) {+ console.error('Failed to load cloudflared status:', err);+ }+ }, [serverId]);++ const loadTunnels = useCallback(async () => {+ try {+ const data = await api.getRemoteCloudflaredTunnels(serverId);+ setTunnels(data?.tunnels || []);+ setError(null);+ } catch (err) {+ // Auth errors here are common when the user hasn't logged+ // in yet — the status banner already explains; don't show+ // a redundant scary alert.+ setError(err.message || 'Failed to load tunnels');+ }+ }, [serverId]);++ useEffect(() => {+ if (serverStatus !== 'online') {+ setLoading(false);+ return;+ }+ let cancelled = false;+ (async () => {+ setLoading(true);+ await loadStatus();+ await loadTunnels();+ if (!cancelled) setLoading(false);+ })();+ return () => { cancelled = true; };+ }, [serverStatus, loadStatus, loadTunnels]);++ async function handleCreate(e) {+ e.preventDefault();+ const name = createName.trim();+ if (!name) {+ toast.error('Name is required');+ return;+ }+ setCreating(true);+ try {+ await api.createRemoteCloudflaredTunnel(serverId, name);+ toast.success(`Tunnel "${name}" created`);+ setShowCreateModal(false);+ setCreateName('');+ loadTunnels();+ } catch (err) {+ toast.error(err.message || 'Failed to create tunnel');+ } finally {+ setCreating(false);+ }+ }++ async function handleRoute(e) {+ e.preventDefault();+ const hostname = routeHostname.trim();+ if (!hostname || !routeTunnel) return;+ setRouting(true);+ try {+ await api.routeRemoteCloudflaredTunnel(serverId, routeTunnel.id || routeTunnel.name, hostname);+ toast.success(`${hostname} → ${routeTunnel.name}`);+ setShowRouteModal(false);+ setRouteHostname('');+ setRouteTunnel(null);+ } catch (err) {+ toast.error(err.message || 'Failed to add route');+ } finally {+ setRouting(false);+ }+ }++ async function handleDelete(tunnel) {+ const ok = await confirmCf({+ title: 'Delete Tunnel',+ message: `Delete tunnel "${tunnel.name}"? Active connections will be force-closed.`,+ variant: 'danger',+ });+ if (!ok) return;+ try {+ await api.deleteRemoteCloudflaredTunnel(serverId, tunnel.id || tunnel.name);+ toast.success('Tunnel deleted');+ loadTunnels();+ } catch (err) {+ toast.error(err.message || 'Failed to delete tunnel');+ }+ }++ // Triggers `cloudflared tunnel login` on the agent and subscribes+ // to the streaming auth flow. The first event carries the auth URL+ // we surface as a clickable button; the final event flips us back+ // to ready state once cert.pem appears.+ async function handleStartLogin() {+ try {+ const res = await api.startRemoteCloudflaredLogin(serverId);+ const channel = res?.channel || `job:${res?.job_id}`;+ setLogin({ channel, status: 'starting', authUrl: null, error: null, certPath: null });++ // Reuse the live socket service to subscribe to the+ // server_stream room. We don't open the JobProgressModal+ // because the login flow needs a different shape (a single+ // big "Open URL" CTA, not a log tail).+ const { default: socketService } = await import('../../services/socket');+ if (!socketService.socket) socketService.connect();+ const sock = socketService.socket;+ if (!sock) {+ setLogin(null);+ toast.error('Socket not available');+ return;+ }+ const room = `server_${serverId}_${channel}`;+ const onStream = (msg) => {+ if (msg?.channel !== channel) return;+ const ev = msg.data || {};+ const url = ev?.extra?.auth_url;+ if (url) {+ setLogin((cur) => cur ? { ...cur, status: 'awaiting', authUrl: url } : cur);+ }+ if (ev.phase === 'done') {+ if (ev.error) {+ setLogin((cur) => cur ? { ...cur, status: 'error', error: ev.error } : cur);+ toast.error(`Login failed: ${ev.error}`);+ } else {+ setLogin((cur) => cur ? { ...cur, status: 'done', certPath: ev?.extra?.cert_path } : cur);+ toast.success('Cloudflare login complete');+ // Refresh capabilities + status so the tab unlocks+ // without a manual reload.+ api.refreshRemoteCapabilities(serverId).catch(() => {});+ loadStatus();+ loadTunnels();+ }+ sock.off('server_stream', onStream);+ sock.emit('leave_room', { room });+ }+ };+ sock.emit('join_room', { room });+ sock.on('server_stream', onStream);+ } catch (err) {+ toast.error(err.message || 'Failed to start login');+ setLogin(null);+ }+ }++ function handleCancelLogin() {+ setLogin(null);+ }++ if (serverStatus !== 'online') {+ return (+ <div className="offline-notice">+ <OfflineIcon />+ <h4>Server Offline</h4>+ <p>Tunnel management requires the server to be online.</p>+ </div>+ );+ }++ if (loading) {+ return <EmptyState loading title="Loading tunnels" />;+ }++ // Status banner — three distinct states the UI cares about:+ // 1. binary missing → "install cloudflared"+ // 2. binary, no cert → "log in once"+ // 3. binary + cert → ready to manage tunnels+ const notInstalled = status?.available === false;+ const notAuthed = status?.available && status?.authenticated === false;++ return (+ <div className="cloudflared-tab">+ <div className="cron-tab__header">+ <div className="cron-tab__status">+ {notInstalled ? (+ <Pill kind="amber">cloudflared not installed</Pill>+ ) : notAuthed ? (+ <Pill kind="amber">not authenticated — run cloudflared tunnel login</Pill>+ ) : (+ <Pill kind="green">cloudflared ready{status?.version ? ` (${status.version})` : ''}</Pill>+ )}+ <span className="cron-tab__count">{tunnels.length} tunnel{tunnels.length === 1 ? '' : 's'}</span>+ </div>+ <div className="cron-tab__actions">+ <Button variant="outline" onClick={loadTunnels} disabled={notInstalled}>Refresh</Button>+ <Button onClick={() => setShowCreateModal(true)} disabled={notInstalled || notAuthed}>+ Create Tunnel+ </Button>+ </div>+ </div>++ {(notInstalled || notAuthed) && (+ <div className="cloudflared-tab__hint">+ {notInstalled ? (+ <>+ Install cloudflared on the server, then return here. See the{' '}+ <a href="https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/get-started/" target="_blank" rel="noreferrer">+ Cloudflare docs+ </a>.+ </>+ ) : login ? (+ <CloudflaredLoginCard login={login} onCancel={handleCancelLogin} />+ ) : (+ <div className="cloudflared-login-prompt">+ <p>+ Cloudflare needs you to authorise this agent once. Click{' '}+ <strong>Login</strong> below — we'll start the OAuth flow on the+ server and surface the URL for you to open in your browser. Once you+ authorise, the agent picks up the cert.pem automatically and the+ rest of this tab unlocks.+ </p>+ <Button onClick={handleStartLogin}>Login to Cloudflare</Button>+ </div>+ )}+ </div>+ )}++ {error && !notAuthed && !notInstalled && (+ <div className="alert alert-danger">{error}</div>+ )}++ {!notInstalled && !notAuthed && (+ tunnels.length === 0 ? (+ <EmptyState+ icon={Cloud}+ title="No tunnels"+ description="No tunnels on this server. Use Create Tunnel to make one."+ />+ ) : (+ <table className="data-table">+ <thead>+ <tr>+ <th>Name</th>+ <th>ID</th>+ <th>Connections</th>+ <th className="actions-cell">Actions</th>+ </tr>+ </thead>+ <tbody>+ {tunnels.map(t => (+ <tr key={t.id || t.name}>+ <td><span className="cron-tab__name">{t.name}</span></td>+ <td className="mono">{(t.id || '').substring(0, 8)}…</td>+ <td>{t.connections?.length || 0}</td>+ <td className="actions-cell">+ <Button+ size="sm"+ variant="outline"+ onClick={() => { setRouteTunnel(t); setShowRouteModal(true); }}+ >+ Route subdomain+ </Button>+ <button+ className="btn-icon danger"+ onClick={() => handleDelete(t)}+ title="Delete"+ >+ <TrashIcon />+ </button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )+ )}++ <Dialog+ open={showCreateModal}+ onOpenChange={(open) => { if (!open && !creating) setShowCreateModal(false); }}+ >+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Create Tunnel</DialogTitle>+ <DialogDescription>+ Provisions a new Cloudflare Tunnel on this server.+ </DialogDescription>+ </DialogHeader>+ <form onSubmit={handleCreate} className="space-y-4">+ <div className="space-y-1.5">+ <Label htmlFor="cf-name">Tunnel Name</Label>+ <Input+ id="cf-name"+ value={createName}+ onChange={(e) => setCreateName(e.target.value)}+ placeholder="my-app"+ required+ autoFocus+ />+ <p className="text-xs text-muted-foreground">Letters, numbers, dashes, underscores. Up to 32 chars.</p>+ </div>+ <DialogFooter>+ <Button type="button" variant="outline" onClick={() => setShowCreateModal(false)} disabled={creating}>Cancel</Button>+ <Button type="submit" disabled={creating}>{creating ? 'Creating…' : 'Create'}</Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>++ <Dialog+ open={showRouteModal && !!routeTunnel}+ onOpenChange={(open) => { if (!open && !routing) setShowRouteModal(false); }}+ >+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Route Subdomain{routeTunnel ? ` → ${routeTunnel.name}` : ''}</DialogTitle>+ <DialogDescription>+ A CNAME for this hostname will be created in Cloudflare DNS, pointing at the tunnel.+ </DialogDescription>+ </DialogHeader>+ <form onSubmit={handleRoute} className="space-y-4">+ <div className="space-y-1.5">+ <Label htmlFor="cf-host">Hostname</Label>+ <Input+ id="cf-host"+ value={routeHostname}+ onChange={(e) => setRouteHostname(e.target.value)}+ placeholder="app.example.com"+ required+ autoFocus+ />+ </div>+ <DialogFooter>+ <Button type="button" variant="outline" onClick={() => setShowRouteModal(false)} disabled={routing}>Cancel</Button>+ <Button type="submit" disabled={routing}>{routing ? 'Adding…' : 'Add Route'}</Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ </div>+ );+};++// CloudflaredLoginCard renders the in-flight OAuth login state. The+// agent has spawned `cloudflared tunnel login` on the server and is+// streaming progress on a job channel; we render either a spinner+// (while we wait for the URL), the Open-in-Browser CTA (once the URL+// arrives), or a final success/error message.+const CloudflaredLoginCard = ({ login, onCancel }) => {+ if (!login) return null;+ if (login.status === 'starting') {+ return (+ <div className="cloudflared-login-card">+ <p>Asking the agent to start the Cloudflare login flow…</p>+ <Button variant="outline" size="sm" onClick={onCancel}>Cancel</Button>+ </div>+ );+ }+ if (login.status === 'awaiting' && login.authUrl) {+ return (+ <div className="cloudflared-login-card">+ <p>+ <strong>Step 1 / 2:</strong> open the following URL in your browser, sign in+ to Cloudflare, and pick the zone you want to associate with this agent.+ </p>+ <div className="cloudflared-login-card__actions">+ <a+ href={login.authUrl}+ target="_blank"+ rel="noreferrer"+ className="btn btn-primary"+ >+ Open Cloudflare login+ </a>+ <button+ type="button"+ className="btn btn-outline"+ onClick={() => navigator.clipboard?.writeText(login.authUrl)}+ >+ Copy URL+ </button>+ </div>+ <p className="cloudflared-login-card__hint">+ <strong>Step 2 / 2:</strong> waiting for the agent to receive cert.pem from+ Cloudflare. This page will refresh automatically once authorisation completes.+ </p>+ <Button variant="outline" size="sm" onClick={onCancel}>Cancel</Button>+ </div>+ );+ }+ if (login.status === 'done') {+ return (+ <div className="cloudflared-login-card cloudflared-login-card--success">+ Authenticated. Refreshing…+ </div>+ );+ }+ if (login.status === 'error') {+ return (+ <div className="cloudflared-login-card cloudflared-login-card--error">+ <strong>Login failed:</strong> {login.error || 'unknown error'}+ <Button variant="outline" size="sm" onClick={onCancel}>Dismiss</Button>+ </div>+ );+ }+ return null;+};++export default CloudflaredTab;diff --git a/frontend/src/components/serverdetail/CronTab.jsx b/frontend/src/components/serverdetail/CronTab.jsxnew file mode 100644index 00000000..da838678--- /dev/null+++ b/frontend/src/components/serverdetail/CronTab.jsx@@ -0,0 +1,306 @@+import { useState, useEffect, useCallback } from 'react';+import api from '../../services/api';+import { useToast } from '../../contexts/ToastContext';+import { useConfirm } from '../../hooks/useConfirm';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Textarea } from '@/components/ui/textarea';+import { Pill } from '../ds';+import EmptyState from '../EmptyState';+import { Clock3 } from 'lucide-react';+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogFooter,+} from '@/components/ui/dialog';+import { Label } from '@/components/ui/label';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';+import {+ PRESET_LABELS,+ OfflineIcon,+ StopIcon,+ PlayIcon,+ TrashIcon,+} from './serverDetailShared';++const CronTab = ({ serverId, serverStatus }) => {+ const toast = useToast();+ const { confirm: confirmCron } = useConfirm();+ const [status, setStatus] = useState(null);+ const [jobs, setJobs] = useState([]);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState(null);++ const [showAddModal, setShowAddModal] = useState(false);+ const [submitting, setSubmitting] = useState(false);+ const [form, setForm] = useState({+ name: '',+ schedule: '0 * * * *',+ command: '',+ });++ const loadJobs = useCallback(async () => {+ try {+ const data = await api.getRemoteCronJobs(serverId);+ setJobs(data?.jobs || []);+ setError(null);+ } catch (err) {+ setError(err.message || 'Failed to load cron jobs');+ }+ }, [serverId]);++ const loadStatus = useCallback(async () => {+ try {+ const s = await api.getRemoteCronStatus(serverId);+ setStatus(s);+ } catch (err) {+ // Non-critical — log but don't block the table.+ console.error('Failed to load cron status:', err);+ }+ }, [serverId]);++ useEffect(() => {+ if (serverStatus !== 'online') {+ setLoading(false);+ return;+ }+ let cancelled = false;+ (async () => {+ setLoading(true);+ await Promise.all([loadJobs(), loadStatus()]);+ if (!cancelled) setLoading(false);+ })();+ return () => { cancelled = true; };+ }, [serverStatus, loadJobs, loadStatus]);++ async function handleToggle(job) {+ try {+ await api.toggleRemoteCronJob(serverId, job.id, !job.enabled);+ toast.success(`Job ${!job.enabled ? 'enabled' : 'disabled'}`);+ loadJobs();+ } catch (err) {+ toast.error(err.message || 'Failed to toggle job');+ }+ }++ async function handleRemove(job) {+ const ok = await confirmCron({+ title: 'Remove Cron Job',+ message: `Remove this entry from the host crontab?\n\n${job.schedule} ${job.command}`,+ variant: 'danger',+ });+ if (!ok) return;+ try {+ await api.removeRemoteCronJob(serverId, job.id);+ toast.success('Cron job removed');+ loadJobs();+ } catch (err) {+ toast.error(err.message || 'Failed to remove job');+ }+ }++ async function handleSubmit(e) {+ e.preventDefault();+ if (!form.command.trim()) {+ toast.error('Command is required');+ return;+ }+ if (!form.schedule.trim()) {+ toast.error('Schedule is required');+ return;+ }+ setSubmitting(true);+ try {+ await api.addRemoteCronJob(serverId, {+ name: form.name.trim(),+ schedule: form.schedule.trim(),+ command: form.command.trim(),+ });+ toast.success('Cron job added');+ setShowAddModal(false);+ setForm({ name: '', schedule: '0 * * * *', command: '' });+ loadJobs();+ } catch (err) {+ toast.error(err.message || 'Failed to add cron job');+ } finally {+ setSubmitting(false);+ }+ }++ if (serverStatus !== 'online') {+ return (+ <div className="offline-notice">+ <OfflineIcon />+ <h4>Server Offline</h4>+ <p>Cron management requires the server to be online.</p>+ </div>+ );+ }++ if (loading) {+ return <EmptyState loading title="Loading cron jobs" />;+ }++ return (+ <div className="cron-tab">+ <div className="cron-tab__header">+ <div className="cron-tab__status">+ {status?.available === false ? (+ <Pill kind="amber">cron not available: {status.reason || 'unknown'}</Pill>+ ) : status?.running === false ? (+ <Pill kind="amber">cron daemon not running</Pill>+ ) : (+ <Pill kind="green">cron daemon active{status?.daemon ? ` (${status.daemon})` : ''}</Pill>+ )}+ <span className="cron-tab__count">{jobs.length} job{jobs.length === 1 ? '' : 's'}</span>+ </div>+ <div className="cron-tab__actions">+ <Button variant="outline" onClick={loadJobs}>Refresh</Button>+ <Button onClick={() => setShowAddModal(true)} disabled={status?.available === false}>+ Add Job+ </Button>+ </div>+ </div>++ {error && (+ <div className="alert alert-danger">{error}</div>+ )}++ {jobs.length === 0 ? (+ <EmptyState+ icon={Clock3}+ title="No cron jobs"+ description="No scheduled jobs on this server. Use Add Job to schedule one."+ />+ ) : (+ <table className="data-table">+ <thead>+ <tr>+ <th>Schedule</th>+ <th>Command</th>+ <th>Status</th>+ <th className="actions-cell">Actions</th>+ </tr>+ </thead>+ <tbody>+ {jobs.map(job => (+ <tr key={job.id} className={!job.enabled ? 'row-disabled' : ''}>+ <td>+ <span className="mono" title={job.schedule}>{job.schedule}</span>+ {job.description && job.description !== job.schedule && (+ <div className="cron-tab__description">{job.description}</div>+ )}+ </td>+ <td>+ {job.name && <div className="cron-tab__name">{job.name}</div>}+ <code className="cron-tab__command">{job.command}</code>+ </td>+ <td>+ <Pill kind={job.enabled ? 'green' : 'gray'}>+ {job.enabled ? 'enabled' : 'disabled'}+ </Pill>+ </td>+ <td className="actions-cell">+ <button+ className="btn-icon"+ onClick={() => handleToggle(job)}+ title={job.enabled ? 'Disable' : 'Enable'}+ >+ {job.enabled ? <StopIcon /> : <PlayIcon />}+ </button>+ <button+ className="btn-icon danger"+ onClick={() => handleRemove(job)}+ title="Remove"+ >+ <TrashIcon />+ </button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}++ <Dialog+ open={showAddModal}+ onOpenChange={(open) => { if (!open && !submitting) setShowAddModal(false); }}+ >+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Add Cron Job</DialogTitle>+ <DialogDescription>+ Schedule a command on the host crontab. Runs as the agent user.+ </DialogDescription>+ </DialogHeader>+ <form onSubmit={handleSubmit} className="space-y-4">+ <div className="space-y-1.5">+ <Label htmlFor="cron-name">Name (optional)</Label>+ <Input+ id="cron-name"+ value={form.name}+ onChange={(e) => setForm({ ...form, name: e.target.value })}+ placeholder="Backup database"+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="cron-schedule">Schedule</Label>+ <Select+ value={Object.keys(PRESET_LABELS).includes(form.schedule) ? form.schedule : 'custom'}+ onValueChange={(value) => {+ if (value === 'custom') return;+ setForm({ ...form, schedule: value });+ }}+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {Object.entries(PRESET_LABELS).map(([cron, label]) => (+ <SelectItem key={cron} value={cron}>{label} — {cron}</SelectItem>+ ))}+ <SelectItem value="custom">Custom…</SelectItem>+ </SelectContent>+ </Select>+ <Input+ id="cron-schedule"+ value={form.schedule}+ onChange={(e) => setForm({ ...form, schedule: e.target.value })}+ placeholder="* * * * *"+ className="font-mono"+ />+ <p className="text-xs text-muted-foreground">5 fields: minute, hour, day, month, weekday.</p>+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="cron-command">Command</Label>+ <Textarea+ id="cron-command"+ rows={3}+ value={form.command}+ onChange={(e) => setForm({ ...form, command: e.target.value })}+ placeholder="/usr/local/bin/my-script.sh"+ required+ />+ <p className="text-xs text-muted-foreground">Absolute path. Shell operators (;, &&, |, $(), >, <) are not allowed.</p>+ </div>+ <DialogFooter>+ <Button type="button" variant="outline" onClick={() => setShowAddModal(false)} disabled={submitting}>Cancel</Button>+ <Button type="submit" disabled={submitting}>{submitting ? 'Adding…' : 'Add Job'}</Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ </div>+ );+};++export default CronTab;diff --git a/frontend/src/components/serverdetail/ServerDockerTab.jsx b/frontend/src/components/serverdetail/ServerDockerTab.jsxnew file mode 100644index 00000000..9f1e7445--- /dev/null+++ b/frontend/src/components/serverdetail/ServerDockerTab.jsx@@ -0,0 +1,278 @@+import { useState, useEffect } from 'react';+import api from '../../services/api';+import { useToast } from '../../contexts/ToastContext';+import { useConfirm } from '../../hooks/useConfirm';+import { Button } from '@/components/ui/button';+import { Pill } from '../ds';+import EmptyState from '../EmptyState';+import { Boxes, Container } from 'lucide-react';+import {+ OfflineIcon,+ RefreshIcon,+ StopIcon,+ PlayIcon,+ TrashIcon,+} from './serverDetailShared';++// The /servers/<id>/docker/* endpoints return raw arrays from Flask+// (route extracts result.get('data') before jsonify). The agent envelope's+// {success, data} shape is gone by the time it reaches the client, so unwrap+// both forms defensively.+const unwrapList = (response) => {+ if (Array.isArray(response)) return response;+ if (response?.success && Array.isArray(response.data)) return response.data;+ return [];+};++// Docker exposes container ports as an array of {ip, private_port,+// public_port, type} objects. Render a compact "host:container/proto"+// string per binding, or fall back to "container/proto" when the port+// isn't mapped to the host. Older agents may already send a string.+const formatPorts = (ports) => {+ if (!ports) return '-';+ if (typeof ports === 'string') return ports || '-';+ if (!Array.isArray(ports) || ports.length === 0) return '-';+ const parts = ports.map((p) => {+ if (!p || typeof p !== 'object') return String(p);+ const proto = p.type || 'tcp';+ if (p.public_port) {+ const host = p.ip && p.ip !== '0.0.0.0' && p.ip !== '::' ? `${p.ip}:` : '';+ return `${host}${p.public_port}->${p.private_port}/${proto}`;+ }+ return `${p.private_port}/${proto}`;+ });+ return parts.join(', ');+};++const ServerDockerTab = ({ serverId, serverStatus, server }) => {+ const [containers, setContainers] = useState([]);+ const [images, setImages] = useState([]);+ const [loading, setLoading] = useState(true);+ const [loadError, setLoadError] = useState(null);+ const [subTab, setSubTab] = useState('containers');+ const toast = useToast();+ const { confirm: confirmDocker } = useConfirm();++ useEffect(() => {+ if (serverStatus === 'online') {+ loadDockerData();+ } else {+ setLoading(false);+ }+ }, [serverId, serverStatus]);++ async function loadDockerData() {+ setLoading(true);+ setLoadError(null);+ try {+ const [containersRes, imagesRes] = await Promise.all([+ api.getRemoteContainers(serverId, true),+ api.getRemoteImages(serverId)+ ]);++ setContainers(unwrapList(containersRes));+ setImages(unwrapList(imagesRes));+ } catch (err) {+ console.error('Failed to load Docker data:', err);+ setLoadError(err.message || 'Failed to load Docker data');+ } finally {+ setLoading(false);+ }+ }++ // If the agent reports docker capability false (Docker daemon not+ // reachable from the agent process — common on Windows when the+ // service hasn't been started, or on hosts where the agent user+ // isn't in the docker group), explain that instead of pretending+ // there are no containers.+ const dockerCapability = server?.capabilities?.docker;+ if (serverStatus === 'online' && server && dockerCapability === false) {+ return (+ <div className="docker-empty-state">+ <EmptyState+ icon={Container}+ title="Docker not reachable from this agent"+ description="The agent connected but could not talk to a Docker daemon. Make sure Docker is running on the host (and the agent user is in the docker group on Linux), then click Refresh on the Overview tab to re-probe capabilities."+ />+ <ul className="docker-empty-state__causes">+ <li>Docker Desktop / dockerd is not running on the host</li>+ <li>The agent user isn't in the <code>docker</code> group (Linux)</li>+ <li>The npipe socket <code>{'//./pipe/docker_engine'}</code> isn't accessible (Windows)</li>+ </ul>+ </div>+ );+ }++ async function handleContainerAction(containerId, action) {+ try {+ let result;+ if (action === 'start') {+ result = await api.startRemoteContainer(serverId, containerId);+ toast.success('Container started');+ } else if (action === 'stop') {+ result = await api.stopRemoteContainer(serverId, containerId);+ toast.success('Container stopped');+ } else if (action === 'restart') {+ result = await api.restartRemoteContainer(serverId, containerId);+ toast.success('Container restarted');+ } else if (action === 'remove') {+ const removeConfirmed = await confirmDocker({ title: 'Remove Container', message: 'Remove this container?' });+ if (!removeConfirmed) return;+ result = await api.removeRemoteContainer(serverId, containerId, true);+ toast.success('Container removed');+ }+ loadDockerData();+ } catch (err) {+ toast.error(err.message || `Failed to ${action} container`);+ }+ }++ if (serverStatus !== 'online') {+ return (+ <div className="offline-notice">+ <OfflineIcon />+ <h4>Server Offline</h4>+ <p>Docker management requires the server to be online.</p>+ </div>+ );+ }++ if (loading) {+ return <EmptyState loading title="Loading Docker data" />;+ }++ return (+ <div className="docker-tab">+ {loadError && (+ <div className="docker-tab__error">+ <strong>Couldn't load Docker data:</strong> {loadError}+ <Button size="sm" variant="outline" onClick={loadDockerData}>Retry</Button>+ </div>+ )}+ <div className="docker-sub-tabs">+ <button+ className={`sub-tab ${subTab === 'containers' ? 'active' : ''}`}+ onClick={() => setSubTab('containers')}+ >+ Containers ({containers.length})+ </button>+ <button+ className={`sub-tab ${subTab === 'images' ? 'active' : ''}`}+ onClick={() => setSubTab('images')}+ >+ Images ({images.length})+ </button>+ </div>++ {subTab === 'containers' && (+ <div className="containers-list">+ {containers.length === 0 ? (+ <EmptyState icon={Container} title="No containers" description="No containers are running on this server." />+ ) : (+ <table className="data-table">+ <thead>+ <tr>+ <th>Name</th>+ <th>Image</th>+ <th>Status</th>+ <th>Ports</th>+ <th>Actions</th>+ </tr>+ </thead>+ <tbody>+ {containers.map(container => {+ const isRunning = container.state === 'running';+ return (+ <tr key={container.id}>+ <td>+ <span className="container-name">{container.name}</span>+ <span className="container-id">{container.id?.substring(0, 12)}</span>+ </td>+ <td>{container.image}</td>+ <td>+ <Pill kind={isRunning ? 'green' : container.state === 'paused' || container.state === 'restarting' ? 'amber' : 'gray'}>+ {container.state}+ </Pill>+ </td>+ <td>{formatPorts(container.ports)}</td>+ <td className="actions-cell">+ {isRunning ? (+ <>+ <button+ className="btn-icon"+ onClick={() => handleContainerAction(container.id, 'restart')}+ title="Restart"+ >+ <RefreshIcon />+ </button>+ <button+ className="btn-icon danger"+ onClick={() => handleContainerAction(container.id, 'stop')}+ title="Stop"+ >+ <StopIcon />+ </button>+ </>+ ) : (+ <>+ <button+ className="btn-icon success"+ onClick={() => handleContainerAction(container.id, 'start')}+ title="Start"+ >+ <PlayIcon />+ </button>+ <button+ className="btn-icon danger"+ onClick={() => handleContainerAction(container.id, 'remove')}+ title="Remove"+ >+ <TrashIcon />+ </button>+ </>+ )}+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ )}+ </div>+ )}++ {subTab === 'images' && (+ <div className="images-list">+ {images.length === 0 ? (+ <EmptyState icon={Boxes} title="No images" description="No Docker images are present on this server." />+ ) : (+ <table className="data-table">+ <thead>+ <tr>+ <th>Repository</th>+ <th>Tag</th>+ <th>Image ID</th>+ <th>Size</th>+ <th>Created</th>+ </tr>+ </thead>+ <tbody>+ {images.map(image => (+ <tr key={image.id}>+ <td>{image.repository || '<none>'}</td>+ <td>{image.tag || '<none>'}</td>+ <td className="mono">{image.id?.substring(0, 12)}</td>+ <td>{image.size}</td>+ <td>{image.created}</td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </div>+ )}+ </div>+ );+};++export default ServerDockerTab;diff --git a/frontend/src/components/serverdetail/ServerMetricsTab.jsx b/frontend/src/components/serverdetail/ServerMetricsTab.jsxnew file mode 100644index 00000000..3b61f3a5--- /dev/null+++ b/frontend/src/components/serverdetail/ServerMetricsTab.jsx@@ -0,0 +1,46 @@+import MetricsGraph from '../MetricsGraph';+import { formatBytes } from '@/utils/formatBytes';++const ServerMetricsTab = ({ serverId, metrics }) => {+ return (+ <div className="metrics-tab">+ <MetricsGraph serverId={serverId} />++ {metrics && (+ <div className="metrics-live-stats">+ <div className="live-stat-card">+ <h4>Current Snapshot</h4>+ <div className="live-stats-grid">+ <div className="live-stat">+ <span className="live-stat-label">CPU</span>+ <span className="live-stat-value">{(metrics.cpu_percent || 0).toFixed(1)}%</span>+ </div>+ <div className="live-stat">+ <span className="live-stat-label">Memory</span>+ <span className="live-stat-value">{(metrics.memory_percent || 0).toFixed(1)}%</span>+ </div>+ <div className="live-stat">+ <span className="live-stat-label">Disk</span>+ <span className="live-stat-value">{(metrics.disk_percent || 0).toFixed(1)}%</span>+ </div>+ <div className="live-stat">+ <span className="live-stat-label">Net TX</span>+ <span className="live-stat-value">{formatBytes(metrics.network_sent, { defaultValue: 'N/A' })}/s</span>+ </div>+ <div className="live-stat">+ <span className="live-stat-label">Net RX</span>+ <span className="live-stat-value">{formatBytes(metrics.network_recv, { defaultValue: 'N/A' })}/s</span>+ </div>+ <div className="live-stat">+ <span className="live-stat-label">Containers</span>+ <span className="live-stat-value">{metrics.container_running || 0} / {metrics.container_count || 0}</span>+ </div>+ </div>+ </div>+ </div>+ )}+ </div>+ );+};++export default ServerMetricsTab;diff --git a/frontend/src/components/serverdetail/ServerOverviewTab.jsx b/frontend/src/components/serverdetail/ServerOverviewTab.jsxnew file mode 100644index 00000000..75e3d298--- /dev/null+++ b/frontend/src/components/serverdetail/ServerOverviewTab.jsx@@ -0,0 +1,173 @@+import { Pill } from '../ds';+import OnboardingWizard from '../server/OnboardingWizard';+import SystemStatusCard from './SystemStatusCard';+import { formatBytes } from '@/utils/formatBytes';+import {+ STATUS_PILL_KIND,+ InfoRow,+ KpiTile,+ KpiGauge,+ PulseIcon,+ ClockIcon,+ CpuIcon,+ MemoryIcon,+ DiskIcon,+ OfflineIcon,+ ServerIcon,+ HostIcon,+ NetworkIcon,+ FolderTinyIcon,+ ChipIcon,+ OsIcon,+ ArchIcon,+ AgentIcon,+ TagIcon,+ HashIcon,+ DockerMiniIcon,+} from './serverDetailShared';++const ServerOverviewTab = ({ server, metrics, systemInfo, onRefreshServer }) => {+ const formatUptime = (seconds) => {+ if (!seconds) return 'N/A';+ const days = Math.floor(seconds / 86400);+ const hours = Math.floor((seconds % 86400) / 3600);+ if (days > 0) return `${days}d ${hours}h`;+ const mins = Math.floor((seconds % 3600) / 60);+ return `${hours}h ${mins}m`;+ };++ const isOnline = server.status === 'online';+ const cpuCores = systemInfo?.cpu_cores || server.cpu_cores;+ const cpuModel = systemInfo?.cpu_model || server.cpu_model;+ const totalMemory = systemInfo?.total_memory || server.total_memory;+ const totalDisk = systemInfo?.total_disk || server.total_disk;+ const osLabel = `${systemInfo?.os || server.os_type || 'Unknown'}${systemInfo?.os_version || server.os_version ? ` ${systemInfo?.os_version || server.os_version}` : ''}`;++ // Surface the onboarding wizard while a server is still being+ // provisioned. Hidden once onboarding reaches 'ready' (or was never+ // started) so it doesn't clutter a healthy server's overview.+ const showOnboarding =+ server.onboarding_state &&+ !['ready', 'pending'].includes(server.onboarding_state);++ return (+ <div className="overview-tab">+ {showOnboarding && (+ <div className="overview-tab__onboarding">+ <OnboardingWizard+ serverId={server.id}+ initialState={server.onboarding_state}+ onStateChange={(newState) => {+ // Refresh the parent server payload when onboarding+ // reaches a terminal state so the card hides itself.+ if (newState === 'ready' || newState === 'failed') {+ onRefreshServer?.();+ }+ }}+ />+ </div>+ )}+ <div className="server-stats-strip">+ <KpiTile+ icon={<PulseIcon />}+ label="Status"+ value={server.status || 'pending'}+ tone={isOnline ? 'success' : server.status === 'connecting' ? 'warning' : 'danger'}+ />+ <KpiTile+ icon={<ClockIcon />}+ label="Uptime"+ value={isOnline ? formatUptime(metrics?.uptime) : '—'}+ sub={isOnline && metrics?.uptime ? 'since last boot' : null}+ />+ <KpiGauge+ icon={<CpuIcon />}+ label="CPU"+ percent={isOnline ? metrics?.cpu_percent : null}+ color="var(--accent-bright)"+ sub={cpuCores ? `${cpuCores} cores` : null}+ />+ <KpiGauge+ icon={<MemoryIcon />}+ label="Memory"+ percent={isOnline ? metrics?.memory_percent : null}+ color="var(--cyan)"+ sub={totalMemory ? formatBytes(totalMemory) : null}+ />+ <KpiGauge+ icon={<DiskIcon />}+ label="Disk"+ percent={isOnline ? metrics?.disk_percent : null}+ color="var(--green)"+ sub={totalDisk ? formatBytes(totalDisk) : null}+ />+ </div>++ {!isOnline && (+ <div className="info-card offline-card">+ <div className="offline-message">+ <OfflineIcon />+ <h4>Server Offline</h4>+ <p>+ {server.status === 'pending'+ ? 'Waiting for agent installation...'+ : 'Unable to connect to the server agent.'}+ </p>+ </div>+ </div>+ )}++ <div className="overview-grid">+ <div className="info-card">+ <h3><ServerIcon /> Server Information</h3>+ <ul className="info-rows">+ <InfoRow icon={<PulseIcon />} label="Status">+ <Pill kind={STATUS_PILL_KIND[server.status] || 'gray'}>{server.status}</Pill>+ </InfoRow>+ <InfoRow icon={<HostIcon />} label="Hostname" value={server.hostname || 'N/A'} mono />+ <InfoRow icon={<NetworkIcon />} label="IP Address" value={server.ip_address || 'N/A'} mono />+ <InfoRow icon={<FolderTinyIcon />} label="Group" value={server.group_name || 'Ungrouped'} />+ <InfoRow+ icon={<ClockIcon />}+ label="Last Seen"+ value={server.last_seen ? new Date(server.last_seen).toLocaleString() : 'Never'}+ />+ </ul>+ </div>++ <div className="info-card">+ <h3><ChipIcon /> System Information</h3>+ <ul className="info-rows">+ <InfoRow icon={<OsIcon />} label="Operating System" value={osLabel} />+ <InfoRow icon={<ArchIcon />} label="Architecture" value={systemInfo?.architecture || server.architecture || 'N/A'} mono />+ <InfoRow+ icon={<CpuIcon />}+ label="CPU"+ value={+ (cpuModel || 'N/A') + (cpuCores ? ` (${cpuCores} cores)` : '')+ }+ />+ <InfoRow icon={<MemoryIcon />} label="Total Memory" value={formatBytes(totalMemory, { defaultValue: 'N/A' })} mono />+ <InfoRow icon={<DiskIcon />} label="Total Disk" value={formatBytes(totalDisk, { defaultValue: 'N/A' })} mono />+ </ul>+ </div>++ <div className="info-card overview-grid__full">+ <h3><AgentIcon /> Agent Information</h3>+ <ul className="info-rows info-rows--columns">+ <InfoRow icon={<TagIcon />} label="Agent Version" value={server.agent_version || 'Not installed'} mono />+ <InfoRow icon={<HashIcon />} label="Agent ID" value={server.agent_id || 'N/A'} mono />+ <InfoRow icon={<DockerMiniIcon />} label="Docker Version" value={server.docker_version || systemInfo?.docker_version || 'N/A'} mono />+ <InfoRow icon={<ClockIcon />} label="Uptime" value={formatUptime(metrics?.uptime)} mono />+ </ul>+ </div>++ <div className="overview-grid__full">+ <SystemStatusCard server={server} onRefresh={onRefreshServer} />+ </div>+ </div>+ </div>+ );+};++export default ServerOverviewTab;diff --git a/frontend/src/components/serverdetail/ServerSettingsTab.jsx b/frontend/src/components/serverdetail/ServerSettingsTab.jsxnew file mode 100644index 00000000..9725b821--- /dev/null+++ b/frontend/src/components/serverdetail/ServerSettingsTab.jsx@@ -0,0 +1,518 @@+import { useState, useEffect } from 'react';+import api from '../../services/api';+import { useToast } from '../../contexts/ToastContext';+import { useConfirm } from '../../hooks/useConfirm';+import { DangerZone } from '../DangerZone';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Textarea } from '@/components/ui/textarea';+import { Pill } from '../ds';+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogFooter,+} from '@/components/ui/dialog';+import { Label } from '@/components/ui/label';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';+import TagsPanel from '../shared/TagsPanel';+import {+ TOKEN_EXPIRY_OPTIONS,+ KeyIcon,+ ServerIcon,+ NetworkIcon,+ TrashIcon,+ TagIcon,+ TerminalIcon,+ CopyIcon,+ WindowsIcon,+} from './serverDetailShared';++const AgentRegistrationSection = ({ server, onRegenerateToken }) => {+ const expires = server.registration_expires;+ const isExpired = expires && new Date(expires) < new Date();+ const isOnline = server.status === 'online';++ return (+ <div className="form-section form-section--accent">+ <div className="form-section__header">+ <span className="form-section__icon"><KeyIcon /></span>+ <div>+ <h3>Connection String</h3>+ <p className="section-description">+ Generate a fresh connection string to pair (or re-pair) this server.+ Useful after reinstalling the agent — old credentials are gone, but a+ new string brings the agent right back to this row.+ {isOnline && ' This server is currently online; regenerating only affects re-pairing.'}+ {isExpired && ' The previous token has expired.'}+ </p>+ </div>+ </div>+ <Button onClick={onRegenerateToken}>+ <KeyIcon /> Generate Connection String+ </Button>+ </div>+ );+};++const ServerSettingsTab = ({ server, onUpdate, onRegenerateToken, onDelete }) => {+ const { confirm: confirmSettings } = useConfirm();+ const [formData, setFormData] = useState({+ name: server.name || '',+ description: server.description || '',+ hostname: server.hostname || '',+ ip_address: server.ip_address || '',+ group_id: server.group_id || ''+ });+ const [groups, setGroups] = useState([]);+ const [loading, setLoading] = useState(false);+ const [allowedIPs, setAllowedIPs] = useState([]);+ const [newIP, setNewIP] = useState('');+ const [connectionInfo, setConnectionInfo] = useState(null);+ const [rotatingKey, setRotatingKey] = useState(false);+ const toast = useToast();++ useEffect(() => {+ loadGroups();+ loadSecurityData();+ }, []);++ async function loadGroups() {+ try {+ const data = await api.getServerGroups();+ setGroups(Array.isArray(data) ? data : []);+ } catch (err) {+ console.error('Failed to load groups:', err);+ }+ }++ async function loadSecurityData() {+ try {+ const [ipsData, connData] = await Promise.all([+ api.getAllowedIPs(server.id),+ api.getConnectionInfo(server.id),+ ]);+ setAllowedIPs(ipsData.allowed_ips || []);+ setConnectionInfo(connData);+ } catch (err) {+ console.error('Failed to load security data:', err);+ }+ }++ async function handleAddIP() {+ if (!newIP.trim()) return;+ const updated = [...allowedIPs, newIP.trim()];+ try {+ await api.updateAllowedIPs(server.id, updated);+ setAllowedIPs(updated);+ setNewIP('');+ toast.success('IP allowlist updated');+ } catch (err) {+ toast.error(err.details?.[0] || err.message || 'Invalid IP pattern');+ }+ }++ async function handleRemoveIP(ip) {+ const updated = allowedIPs.filter(i => i !== ip);+ try {+ await api.updateAllowedIPs(server.id, updated);+ setAllowedIPs(updated);+ toast.success('IP removed from allowlist');+ } catch (err) {+ toast.error(err.message || 'Failed to update allowlist');+ }+ }++ async function handleRotateKey() {+ const confirmed = await confirmSettings({ title: 'Rotate Credentials', message: 'Rotate API credentials? The agent must be online to receive new credentials.', variant: 'warning' });+ if (!confirmed) return;+ setRotatingKey(true);+ try {+ const result = await api.rotateAPIKey(server.id);+ if (result.success) {+ toast.success('Credential rotation initiated. Agent will update shortly.');+ } else {+ toast.error(result.error || 'Failed to rotate credentials');+ }+ } catch (err) {+ toast.error(err.message || 'Failed to rotate credentials');+ } finally {+ setRotatingKey(false);+ }+ }++ async function handleSubmit(e) {+ e.preventDefault();+ setLoading(true);++ try {+ await api.updateServer(server.id, formData);+ toast.success('Server updated successfully');+ onUpdate();+ } catch (err) {+ toast.error(err.message || 'Failed to update server');+ } finally {+ setLoading(false);+ }+ }++ function handleChange(e) {+ const { name, value } = e.target;+ setFormData(prev => ({ ...prev, [name]: value }));+ }++ return (+ <div className="settings-tab">+ <div className="settings-grid">+ <form onSubmit={handleSubmit} className="settings-form">+ <div className="form-section form-section--accent">+ <div className="form-section__header">+ <span className="form-section__icon"><ServerIcon /></span>+ <div>+ <h3>Basic Information</h3>+ <p className="section-description">Identity and grouping for this server.</p>+ </div>+ </div>+ <div className="form-group">+ <label>Server 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}+ rows={3}+ />+ </div>++ <div className="form-row">+ <div className="form-group">+ <label>Hostname</label>+ <Input+ type="text"+ name="hostname"+ value={formData.hostname}+ onChange={handleChange}+ />+ </div>+ <div className="form-group">+ <label>IP Address</label>+ <Input+ type="text"+ name="ip_address"+ value={formData.ip_address}+ onChange={handleChange}+ />+ </div>+ </div>++ <div className="form-group">+ <label>Group</label>+ <select name="group_id" value={formData.group_id} onChange={handleChange}>+ <option value="">No Group</option>+ {groups.map(group => (+ <option key={group.id} value={group.id}>{group.name}</option>+ ))}+ </select>+ </div>++ <Button type="submit" disabled={loading}>+ {loading ? 'Saving...' : 'Save Changes'}+ </Button>+ </div>+ </form>++ <AgentRegistrationSection+ server={server}+ onRegenerateToken={onRegenerateToken}+ />+ </div>++ <div className="security-grid">+ <div className="form-section form-section--accent">+ <div className="form-section__header">+ <span className="form-section__icon"><NetworkIcon /></span>+ <div>+ <h3>Connection & IP Allowlist</h3>+ <p className="section-description">+ Restrict which IPs can connect. Supports single IPs, CIDR notation, and wildcards.+ </p>+ </div>+ </div>++ {connectionInfo && (+ <div className="security-info-bar">+ <div className="security-info-item">+ <span className="security-info-label">Connection IP</span>+ <span className="security-info-value">+ <code>{connectionInfo.ip_address || 'Not connected'}</code>+ </span>+ </div>+ {connectionInfo.connected_since && (+ <div className="security-info-item">+ <span className="security-info-label">Connected Since</span>+ <span className="security-info-value">{new Date(connectionInfo.connected_since).toLocaleString()}</span>+ </div>+ )}+ </div>+ )}++ <div className="subsection">+ <div className="ip-list">+ {allowedIPs.length === 0 ? (+ <div className="ip-empty">No IP restrictions (all IPs allowed)</div>+ ) : (+ allowedIPs.map((ip, idx) => (+ <div key={idx} className="ip-item">+ <code>{ip}</code>+ {connectionInfo?.ip_address === ip && (+ <Pill kind="green" dot={false}>Current</Pill>+ )}+ <button+ className="btn-icon danger"+ onClick={() => handleRemoveIP(ip)}+ title="Remove"+ >+ <TrashIcon />+ </button>+ </div>+ ))+ )}+ </div>++ <div className="ip-add-form">+ <Input+ type="text"+ placeholder="IP address or CIDR (e.g., 192.168.1.0/24)"+ value={newIP}+ onChange={(e) => setNewIP(e.target.value)}+ onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), handleAddIP())}+ />+ <Button variant="outline" onClick={handleAddIP}>+ Add+ </Button>+ </div>++ {connectionInfo?.ip_address && allowedIPs.length > 0 && !allowedIPs.some(ip => {+ return ip === connectionInfo.ip_address || ip.includes('*') || ip.includes('/');+ }) && (+ <div className="security-warning">+ Current connection IP ({connectionInfo.ip_address}) may be blocked by these rules.+ </div>+ )}+ </div>+ </div>++ <div className="form-section form-section--accent">+ <div className="form-section__header">+ <span className="form-section__icon"><KeyIcon /></span>+ <div>+ <h3>API Key Rotation</h3>+ <p className="section-description">+ Rotate the API credentials used by the agent. The agent must be online to receive new credentials.+ </p>+ </div>+ </div>+ <div className="key-rotation-actions">+ <Button+ variant="outline"+ onClick={handleRotateKey}+ disabled={rotatingKey || server.status !== 'online'}+ >+ <KeyIcon /> {rotatingKey ? 'Rotating...' : 'Rotate API Key'}+ </Button>+ {server.api_key_last_rotated && (+ <span className="key-rotation-hint">Last rotated: {new Date(server.api_key_last_rotated).toLocaleString()}</span>+ )}+ </div>++ {server.status !== 'online' && (+ <div className="security-notice">+ Server must be online to rotate credentials.+ </div>+ )}+ </div>+ </div>++ <div className="form-section form-section--accent shared-resources-section">+ <div className="form-section__header">+ <span className="form-section__icon"><TagIcon /></span>+ <div>+ <h3>Tags</h3>+ <p className="section-description">+ Free-form labels for grouping and filtering this server across the panel.+ </p>+ </div>+ </div>+ <TagsPanel resourceType="server" resourceId={server.id} />+ </div>++ <DangerZone+ title="Danger Zone"+ description="Removing this server will disconnect the agent and delete all associated data."+ action={+ <Button variant="destructive" onClick={onDelete}>+ <TrashIcon /> Remove Server+ </Button>+ }+ />+ </div>+ );+};++export const TokenModal = ({ server, onClose, onGenerated }) => {+ const toast = useToast();+ const [expiresIn, setExpiresIn] = useState(7 * 24 * 60 * 60);+ const [generating, setGenerating] = useState(false);+ // Result of the most recent generation in *this* modal session. We+ // don't fall back to server.connection_string because the panel only+ // ever returns the connection string at create/regenerate time — once+ // the modal closes, the value is gone, so showing a stale one would+ // be misleading.+ const [result, setResult] = useState(null);++ async function handleGenerate() {+ setGenerating(true);+ try {+ const data = await api.generateRegistrationToken(server.id, { expires_in: expiresIn });+ setResult(data);+ onGenerated?.(data);+ toast.success('Connection string generated');+ } catch (err) {+ toast.error(err.message || 'Failed to generate connection string');+ } finally {+ setGenerating(false);+ }+ }++ function copyToClipboard(text) {+ navigator.clipboard.writeText(text);+ toast.success('Copied to clipboard');+ }++ const linuxScript = result ? `curl -fsSL ${window.location.origin}/api/v1/servers/install.sh | sudo bash -s -- \\+ --server "${window.location.origin}" \\+ --token "${result.registration_token}"` : '';+ const windowsScript = result ? `irm ${window.location.origin}/api/v1/servers/install.ps1 | iex+Install-ServerKitAgent -Server "${window.location.origin}" -Token "${result.registration_token}"` : '';++ return (+ <Dialog open onOpenChange={(open) => { if (!open) onClose(); }}>+ <DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">+ <DialogHeader>+ <DialogTitle>Connection String</DialogTitle>+ {!result && (+ <DialogDescription>+ Generate a single pasteable string the agent can consume.+ The token inside is single-use — burned the moment any+ agent registers with it.+ </DialogDescription>+ )}+ </DialogHeader>++ {!result ? (+ <>+ <div className="space-y-2">+ <Label htmlFor="token-expires">Token expires</Label>+ <Select value={String(expiresIn)} onValueChange={(v) => setExpiresIn(Number(v))}>+ <SelectTrigger id="token-expires">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {TOKEN_EXPIRY_OPTIONS.map(opt => (+ <SelectItem key={opt.value} value={String(opt.value)}>{opt.label}</SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>++ <DialogFooter>+ <Button variant="outline" onClick={onClose}>Cancel</Button>+ <Button onClick={handleGenerate} disabled={generating}>+ {generating ? 'Generating…' : 'Generate'}+ </Button>+ </DialogFooter>+ </>+ ) : (+ <>+ <div className="token-status">+ <span className="token-status-dot active" />+ <span>+ Active — expires {new Date(result.registration_expires).toLocaleString()}+ </span>+ </div>++ <div className="connection-string-field">+ <div className="connection-string-field__header">+ <KeyIcon />+ <span>Connection string</span>+ <Button variant="outline" size="sm" onClick={() => copyToClipboard(result.connection_string)}>+ <CopyIcon /> Copy+ </Button>+ </div>+ <pre className="connection-string-field__value">{result.connection_string}</pre>+ </div>++ <details className="install-fallback">+ <summary>Need to install the agent first? Use the one-liner installer.</summary>+ <div className="install-tabs" style={{ marginTop: '0.75rem' }}>+ <div className="install-tab">+ <div className="install-tab-header">+ <TerminalIcon />+ <div className="install-tab-title">+ <span>Linux</span>+ <span className="install-tab-description">curl, tar, sudo, and systemd</span>+ </div>+ <Button variant="outline" size="sm" onClick={() => copyToClipboard(linuxScript)}>+ <CopyIcon /> Copy+ </Button>+ </div>+ <pre className="install-script">{linuxScript}</pre>+ </div>+ <div className="install-tab">+ <div className="install-tab-header">+ <WindowsIcon />+ <div className="install-tab-title">+ <span>Windows (PowerShell)</span>+ <span className="install-tab-description">Run as Administrator</span>+ </div>+ <Button variant="outline" size="sm" onClick={() => copyToClipboard(windowsScript)}>+ <CopyIcon /> Copy+ </Button>+ </div>+ <pre className="install-script">{windowsScript}</pre>+ </div>+ </div>+ </details>++ <DialogFooter>+ <Button variant="outline" onClick={() => setResult(null)}>+ Generate another+ </Button>+ <Button onClick={onClose}>Done</Button>+ </DialogFooter>+ </>+ )}+ </DialogContent>+ </Dialog>+ );+};++export default ServerSettingsTab;diff --git a/frontend/src/components/serverdetail/serverDetailShared.jsx b/frontend/src/components/serverdetail/serverDetailShared.jsxnew file mode 100644index 00000000..15b6ad31--- /dev/null+++ b/frontend/src/components/serverdetail/serverDetailShared.jsx@@ -0,0 +1,349 @@+import { useToast } from '../../contexts/ToastContext';+import { Button } from '@/components/ui/button';+import { Gauge } from '../ds';++// Server status → ds Pill tone (shared by the header pill and the+// Overview "Status" row).+export const STATUS_PILL_KIND = {+ online: 'green',+ offline: 'red',+ connecting: 'amber',+ pending: 'gray',+};++export const PRESET_LABELS = {+ '* * * * *': 'Every minute',+ '*/5 * * * *': 'Every 5 minutes',+ '*/15 * * * *': 'Every 15 minutes',+ '*/30 * * * *': 'Every 30 minutes',+ '0 * * * *': 'Hourly',+ '0 0 * * *': 'Daily at midnight',+ '0 12 * * *': 'Daily at noon',+ '0 0 * * 0': 'Weekly (Sunday)',+ '0 0 1 * *': 'Monthly (1st)',+};++// Token-lifetime presets shown in the regenerate modal. Mirrors the values+// the Add Server modal uses (frontend/src/pages/Servers.jsx). Keep them in+// sync if you tweak either list.+export const TOKEN_EXPIRY_OPTIONS = [+ { label: '1 hour', value: 60 * 60 },+ { label: '24 hours', value: 24 * 60 * 60 },+ { label: '7 days', value: 7 * 24 * 60 * 60 },+ { label: '30 days', value: 30 * 24 * 60 * 60 },+ { label: 'Never', value: -1 },+];++export const SecurityAlertItem = ({ alert, onAcknowledge, onResolve }) => {+ const sev = (alert.severity || 'info').toLowerCase();+ const tone =+ sev === 'critical' || sev === 'high' ? 'danger' :+ sev === 'medium' || sev === 'warning' ? 'warning' : 'info';+ const title = (alert.alert_type || 'alert').replace(/_/g, ' ');+ return (+ <li className={`notification notification--${tone}`}>+ <span className="notification__icon">+ {tone === 'info' ? <InfoCircleIcon /> : <AlertIcon />}+ </span>+ <div className="notification__body">+ <div className="notification__head">+ <span className="notification__title">{title}</span>+ <span className={`severity-badge ${sev}`}>{sev}</span>+ <span className="notification__time">+ {alert.created_at ? new Date(alert.created_at).toLocaleString() : ''}+ </span>+ </div>+ <p className="notification__message">+ {alert.source_ip && <><strong>IP:</strong> {alert.source_ip}{' '}</>}+ {alert.details?.message || ''}+ {alert.details?.attempts ? ` (${alert.details.attempts} attempts)` : ''}+ </p>+ <div className="notification__actions">+ {alert.status === 'open' && (+ <Button variant="outline" size="sm" onClick={() => onAcknowledge(alert.id)}>+ Acknowledge+ </Button>+ )}+ <Button variant="outline" size="sm" onClick={() => onResolve(alert.id)}>+ Resolve+ </Button>+ </div>+ </div>+ </li>+ );+};++export const InfoRow = ({ icon, label, value, mono, children }) => (+ <li className="info-row">+ <span className="info-row__icon">{icon}</span>+ <span className="info-row__label">{label}</span>+ <span className={`info-row__value${mono ? ' mono' : ''}`}>+ {children ?? value}+ </span>+ </li>+);++export const KpiTile = ({ icon, label, value, sub, tone }) => (+ <div className={`kpi-tile${tone ? ` kpi-tile--${tone}` : ''}`}>+ <div className="kpi-tile__head">+ <span className="kpi-tile__icon">{icon}</span>+ <span className="kpi-tile__label">{label}</span>+ </div>+ <div className="kpi-tile__value">{value}</div>+ {sub && <div className="kpi-tile__sub">{sub}</div>}+ </div>+);++export const KpiGauge = ({ icon, label, percent, color, sub }) => {+ const has = percent !== null && percent !== undefined && Number.isFinite(percent);+ const safe = has ? Math.min(Math.max(percent, 0), 100) : 0;+ const danger = safe > 85;+ const warn = safe > 70 && !danger;+ const fillColor = danger ? 'var(--red)' : warn ? 'var(--amber)' : color;++ return (+ <div className={`kpi-tile kpi-tile--gauge${danger ? ' kpi-tile--danger' : warn ? ' kpi-tile--warn' : ''}`}>+ <div className="kpi-tile__head">+ <span className="kpi-tile__icon">{icon}</span>+ <span className="kpi-tile__label">{label}</span>+ </div>+ <div className="kpi-tile__value">{has ? `${safe.toFixed(1)}%` : '—'}</div>+ <Gauge className="kpi-tile__meter" value={safe} color={fillColor} />+ {sub && <div className="kpi-tile__sub">{sub}</div>}+ </div>+ );+};++export const CopyChip = ({ label, value, title, mono }) => {+ const toast = useToast();+ const handleCopy = (e) => {+ e.preventDefault();+ e.stopPropagation();+ if (!value) return;+ navigator.clipboard.writeText(value);+ toast.success(`${label[0].toUpperCase()}${label.slice(1)} copied`);+ };+ return (+ <button+ type="button"+ className={`copy-chip${mono ? ' copy-chip--mono' : ''}`}+ onClick={handleCopy}+ title={title || `Copy ${label}`}+ >+ <span className="copy-chip__label">{label}</span>+ <code className="copy-chip__value">{value}</code>+ <CopyIcon />+ </button>+ );+};++// Icons+export const FolderTinyIcon = () => (+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>+ </svg>+);++export const RefreshIcon = () => (+ <svg width="16" height="16" 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 const TrashIcon = () => (+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <polyline points="3 6 5 6 21 6"/>+ <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>+ </svg>+);++export const KeyIcon = () => (+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/>+ </svg>+);++export const OfflineIcon = () => (+ <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">+ <line x1="1" y1="1" x2="23" y2="23"/>+ <path d="M16.72 11.06A10.94 10.94 0 0 1 19 12.55"/>+ <path d="M5 12.55a10.94 10.94 0 0 1 5.17-2.39"/>+ <path d="M10.71 5.05A16 16 0 0 1 22.58 9"/>+ <path d="M1.42 9a15.91 15.91 0 0 1 4.7-2.88"/>+ <path d="M8.53 16.11a6 6 0 0 1 6.95 0"/>+ <line x1="12" y1="20" x2="12.01" y2="20"/>+ </svg>+);++export const StopIcon = () => (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">+ <rect x="6" y="6" width="12" height="12"/>+ </svg>+);++export const PlayIcon = () => (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">+ <polygon points="5 3 19 12 5 21 5 3"/>+ </svg>+);++export const TerminalIcon = () => (+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <polyline points="4 17 10 11 4 5"/>+ <line x1="12" y1="19" x2="20" y2="19"/>+ </svg>+);++export const CopyIcon = () => (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>+ <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>+ </svg>+);++export const WindowsIcon = () => (+ <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">+ <path d="M0 3.449L9.75 2.1v9.451H0m10.949-9.602L24 0v11.4H10.949M0 12.6h9.75v9.451L0 20.699M10.949 12.6H24V24l-12.9-1.801"/>+ </svg>+);++export const CpuIcon = () => (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <rect x="4" y="4" width="16" height="16" rx="2"/>+ <rect x="9" y="9" width="6" height="6"/>+ <line x1="9" y1="2" x2="9" y2="4"/><line x1="15" y1="2" x2="15" y2="4"/>+ <line x1="9" y1="20" x2="9" y2="22"/><line x1="15" y1="20" x2="15" y2="22"/>+ <line x1="20" y1="9" x2="22" y2="9"/><line x1="20" y1="14" x2="22" y2="14"/>+ <line x1="2" y1="9" x2="4" y2="9"/><line x1="2" y1="14" x2="4" y2="14"/>+ </svg>+);++export const MemoryIcon = () => (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <rect x="2" y="7" width="20" height="10" rx="2"/>+ <line x1="6" y1="7" x2="6" y2="17"/>+ <line x1="10" y1="7" x2="10" y2="17"/>+ <line x1="14" y1="7" x2="14" y2="17"/>+ <line x1="18" y1="7" x2="18" y2="17"/>+ </svg>+);++export const DiskIcon = () => (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <ellipse cx="12" cy="5" rx="9" ry="3"/>+ <path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/>+ <path d="M3 12c0 1.66 4 3 9 3s9-1.34 9-3"/>+ </svg>+);++export const ClockIcon = () => (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <circle cx="12" cy="12" r="10"/>+ <polyline points="12 6 12 12 16 14"/>+ </svg>+);++export const NetworkIcon = () => (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <circle cx="12" cy="12" r="10"/>+ <line x1="2" y1="12" x2="22" y2="12"/>+ <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"/>+ </svg>+);++export const ServerIcon = () => (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <rect x="2" y="3" width="20" height="7" rx="1"/>+ <rect x="2" y="14" width="20" height="7" rx="1"/>+ <line x1="6" y1="6.5" x2="6.01" y2="6.5"/>+ <line x1="6" y1="17.5" x2="6.01" y2="17.5"/>+ </svg>+);++export const HostIcon = () => (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>+ <polyline points="9 22 9 12 15 12 15 22"/>+ </svg>+);++export const OsIcon = () => (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <rect x="2" y="3" width="20" height="14" rx="2"/>+ <line x1="8" y1="21" x2="16" y2="21"/>+ <line x1="12" y1="17" x2="12" y2="21"/>+ </svg>+);++export const ArchIcon = () => (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <polyline points="16 18 22 12 16 6"/>+ <polyline points="8 6 2 12 8 18"/>+ </svg>+);++export const ChipIcon = () => (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <rect x="5" y="5" width="14" height="14" rx="1"/>+ <rect x="9" y="9" width="6" height="6"/>+ <path d="M3 9h2M3 15h2M19 9h2M19 15h2M9 3v2M15 3v2M9 19v2M15 19v2"/>+ </svg>+);++export const AgentIcon = () => (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M12 2a4 4 0 0 0-4 4v2H6a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2h-2V6a4 4 0 0 0-4-4z"/>+ <circle cx="9" cy="14" r="1"/>+ <circle cx="15" cy="14" r="1"/>+ </svg>+);++export const TagIcon = () => (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/>+ <line x1="7" y1="7" x2="7.01" y2="7"/>+ </svg>+);++export const HashIcon = () => (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <line x1="4" y1="9" x2="20" y2="9"/>+ <line x1="4" y1="15" x2="20" y2="15"/>+ <line x1="10" y1="3" x2="8" y2="21"/>+ <line x1="16" y1="3" x2="14" y2="21"/>+ </svg>+);++export const DockerMiniIcon = () => (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <rect x="3" y="10" width="3" height="3"/>+ <rect x="7" y="10" width="3" height="3"/>+ <rect x="11" y="10" width="3" height="3"/>+ <rect x="7" y="6" width="3" height="3"/>+ <rect x="11" y="6" width="3" height="3"/>+ <path d="M2 14c0 4 4 6 10 6s10-2 10-6"/>+ </svg>+);++export const PulseIcon = () => (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/>+ </svg>+);++export const AlertIcon = () => (+ <svg width="18" height="18" 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>+);++export const InfoCircleIcon = () => (+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <circle cx="12" cy="12" r="10"/>+ <line x1="12" y1="16" x2="12" y2="12"/>+ <line x1="12" y1="8" x2="12.01" y2="8"/>+ </svg>+);diff --git a/frontend/src/components/wordpress/detail/AnalyticsTab.jsx b/frontend/src/components/wordpress/detail/AnalyticsTab.jsxnew file mode 100644index 00000000..875fc13b--- /dev/null+++ b/frontend/src/components/wordpress/detail/AnalyticsTab.jsx@@ -0,0 +1,157 @@+import React, { useState, useEffect } from 'react';+import { ResponsiveContainer, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts';+import { BarChart3, Globe, HardDrive, AlertTriangle, Activity, FileText } from 'lucide-react';+import wordpressApi from '../../../services/wordpress';+import { useToast } from '../../../contexts/ToastContext';+import { MetricCard, SegControl } from '../../ds';+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);++ 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 <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">+ <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/components/wordpress/detail/BackupsTab.jsx b/frontend/src/components/wordpress/detail/BackupsTab.jsxnew file mode 100644index 00000000..f40a3fe4--- /dev/null+++ b/frontend/src/components/wordpress/detail/BackupsTab.jsx@@ -0,0 +1,16 @@+import ProtectionPanel from '../../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/components/wordpress/detail/DatabaseTab.jsx b/frontend/src/components/wordpress/detail/DatabaseTab.jsxnew file mode 100644index 00000000..532c6ad1--- /dev/null+++ b/frontend/src/components/wordpress/detail/DatabaseTab.jsx@@ -0,0 +1,217 @@+import { useState, useEffect } from 'react';+import { Database, Plus } from 'lucide-react';+import wordpressApi from '../../../services/wordpress';+import { useToast } from '../../../contexts/ToastContext';+import { SnapshotTable } from '../index';+import { ErrorState } from '../../ErrorBoundary';+import Modal from '@/components/Modal';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { Textarea } from '@/components/ui/textarea';++// 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/components/wordpress/detail/EnvironmentsTab.jsx b/frontend/src/components/wordpress/detail/EnvironmentsTab.jsxnew file mode 100644index 00000000..34e692b4--- /dev/null+++ b/frontend/src/components/wordpress/detail/EnvironmentsTab.jsx@@ -0,0 +1,308 @@+import { useState, useEffect } from 'react';+import { Plus } from 'lucide-react';+import wordpressApi from '../../../services/wordpress';+import { useToast } from '../../../contexts/ToastContext';+import { EnvironmentCard } from '../index';+import { ErrorState } from '../../ErrorBoundary';+import Modal from '@/components/Modal';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+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 (+ <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/components/wordpress/detail/GitTab.jsx b/frontend/src/components/wordpress/detail/GitTab.jsxnew file mode 100644index 00000000..9c335988--- /dev/null+++ b/frontend/src/components/wordpress/detail/GitTab.jsx@@ -0,0 +1,127 @@+import { useState, useEffect } from 'react';+import { RefreshCw } from 'lucide-react';+import wordpressApi from '../../../services/wordpress';+import { useToast } from '../../../contexts/ToastContext';+import { GitConnectForm, CommitList } from '../index';+import { ErrorState } from '../../ErrorBoundary';+import { Button } from '@/components/ui/button';++// 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 (+ <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/components/wordpress/detail/OverviewTab.jsx b/frontend/src/components/wordpress/detail/OverviewTab.jsxnew file mode 100644index 00000000..d9bd4b3c--- /dev/null+++ b/frontend/src/components/wordpress/detail/OverviewTab.jsx@@ -0,0 +1,400 @@+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 '../../../contexts/ToastContext';+import ActivityFeed from '../ActivityFeed';+import { MetricCard } from '../../ds';+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+ className="quick-action-btn"+ onClick={() => setShowEnvModal(true)}+ >+ <Plus size={16} />+ Create Environment+ </button>+ )}+ <button+ className="quick-action-btn"+ onClick={handleQuickSnapshot}+ disabled={creatingSnapshot}+ >+ <Database size={16} />+ {creatingSnapshot ? 'Creating...' : 'Create Snapshot'}+ </button>+ {site.environments?.length > 0 && (+ <button+ className="quick-action-btn"+ onClick={handleSyncAll}+ disabled={syncingAll}+ >+ <RefreshCw size={16} className={syncingAll ? 'spinning' : ''} />+ {syncingAll ? 'Syncing...' : 'Sync All Envs'}+ </button>+ )}+ <button+ className="quick-action-btn"+ onClick={handleFlushCache}+ disabled={flushingCache}+ >+ <Trash2 size={16} />+ {flushingCache ? 'Flushing...' : 'Purge Cache'}+ </button>+ <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+ className="quick-action-btn"+ onClick={() => setShowSearchReplace(true)}+ >+ <Replace size={16} />+ Search & Replace+ </button>+ <button+ className="quick-action-btn"+ onClick={handleHarden}+ disabled={hardening}+ >+ <ShieldCheck size={16} />+ {hardening ? 'Hardening...' : 'Harden'}+ </button>+ <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's parsed from the site'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/components/wordpress/detail/PhpTab.jsx b/frontend/src/components/wordpress/detail/PhpTab.jsxnew file mode 100644index 00000000..2bbbce06--- /dev/null+++ b/frontend/src/components/wordpress/detail/PhpTab.jsx@@ -0,0 +1,160 @@+import React, { useState, useEffect } from 'react';+import wordpressApi from '../../../services/wordpress';+import { useToast } from '../../../contexts/ToastContext';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+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 <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/components/wordpress/detail/PluginsTab.jsx b/frontend/src/components/wordpress/detail/PluginsTab.jsxnew file mode 100644index 00000000..a68d7af1--- /dev/null+++ b/frontend/src/components/wordpress/detail/PluginsTab.jsx@@ -0,0 +1,202 @@+import { useState, useEffect } from 'react';+import { Package, Download } from 'lucide-react';+import wordpressApi from '../../../services/wordpress';+import { useToast } from '../../../contexts/ToastContext';+import { ErrorState } from '../../ErrorBoundary';+import EmptyState from '../../EmptyState';+import { ServiceTile } from '../../ds';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Switch } from '@/components/ui/switch';+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++ useEffect(() => {+ loadPlugins();+ }, [siteId]);++ async function loadPlugins() {+ setLoading(true);+ setError(null);+ try {+ const data = await wordpressApi.getPlugins(siteId);+ setPlugins(data.plugins || []);+ } catch (err) {+ console.error('Failed to load plugins:', err);+ setError(err);+ } finally {+ setLoading(false);+ }+ }++ 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 (+ <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';+ return (+ <div className={`wp-asset-card ${isActive ? 'is-active' : ''}`} key={plugin.name}>+ <ServiceTile name={plugin.title || plugin.name} size={42} />+ <div className="wp-asset-card__body">+ <div className="wp-asset-card__name">{plugin.title || plugin.name}</div>+ <div className="wp-asset-card__sub">{plugin.name}</div>+ <div className="wp-asset-card__foot">+ <span className="wp-asset-card__ver">v{plugin.version}</span>+ {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/components/wordpress/detail/ReportsTab.jsx b/frontend/src/components/wordpress/detail/ReportsTab.jsxnew file mode 100644index 00000000..df1eee7a--- /dev/null+++ b/frontend/src/components/wordpress/detail/ReportsTab.jsx@@ -0,0 +1,360 @@+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 '../../../contexts/ToastContext';+import { useConfirm } from '../../../hooks/useConfirm';+import { Pill } from '../../ds';+import { Button } from '@/components/ui/button';+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 <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'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/components/wordpress/detail/SecurityTab.jsx b/frontend/src/components/wordpress/detail/SecurityTab.jsxnew file mode 100644index 00000000..5ac6956a--- /dev/null+++ b/frontend/src/components/wordpress/detail/SecurityTab.jsx@@ -0,0 +1,248 @@+import React, { useState, useEffect } from 'react';+import wordpressApi from '../../../services/wordpress';+import { useToast } from '../../../contexts/ToastContext';+import { Pill, ScoreGauge } from '../../ds';+import { Button } from '@/components/ui/button';+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 <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/components/wordpress/detail/SettingsTab.jsx b/frontend/src/components/wordpress/detail/SettingsTab.jsxnew file mode 100644index 00000000..49928300--- /dev/null+++ b/frontend/src/components/wordpress/detail/SettingsTab.jsx@@ -0,0 +1,354 @@+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 '../../../contexts/ToastContext';+import { useConfirm } from '../../../hooks/useConfirm';+import { DangerZone } from '../../DangerZone';+import Modal from '@/components/Modal';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+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 & 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/components/wordpress/detail/ThemesTab.jsx b/frontend/src/components/wordpress/detail/ThemesTab.jsxnew file mode 100644index 00000000..ec285cec--- /dev/null+++ b/frontend/src/components/wordpress/detail/ThemesTab.jsx@@ -0,0 +1,200 @@+import { useState, useEffect } from 'react';+import { Palette } from 'lucide-react';+import wordpressApi from '../../../services/wordpress';+import { useToast } from '../../../contexts/ToastContext';+import { ErrorState } from '../../ErrorBoundary';+import EmptyState from '../../EmptyState';+import { Pill } from '../../ds';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+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 (+ <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/components/wordpress/detail/UpdatesTab.jsx b/frontend/src/components/wordpress/detail/UpdatesTab.jsxnew file mode 100644index 00000000..190e49b2--- /dev/null+++ b/frontend/src/components/wordpress/detail/UpdatesTab.jsx@@ -0,0 +1,136 @@+import React, { useState, useEffect } from 'react';+import wordpressApi from '../../../services/wordpress';+import { useToast } from '../../../contexts/ToastContext';+import { Pill } from '../../ds';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+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 <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/components/wordpress/detail/UptimeTab.jsx b/frontend/src/components/wordpress/detail/UptimeTab.jsxnew file mode 100644index 00000000..f4c4b193--- /dev/null+++ b/frontend/src/components/wordpress/detail/UptimeTab.jsx@@ -0,0 +1,138 @@+import React, { useState, useEffect } from 'react';+import { Activity } from 'lucide-react';+import wordpressApi from '../../../services/wordpress';+import { useToast } from '../../../contexts/ToastContext';+import { HealthDot } from '../HealthStatusPanel';+import { MetricCard } from '../../ds';+import { Button } from '@/components/ui/button';+import { Label } from '@/components/ui/label';+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 <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/components/wordpress/detail/VulnerabilitiesTab.jsx b/frontend/src/components/wordpress/detail/VulnerabilitiesTab.jsxnew file mode 100644index 00000000..b33fd021--- /dev/null+++ b/frontend/src/components/wordpress/detail/VulnerabilitiesTab.jsx@@ -0,0 +1,137 @@+import React, { useState, useEffect } from 'react';+import { AlertTriangle } from 'lucide-react';+import wordpressApi from '../../../services/wordpress';+import { useToast } from '../../../contexts/ToastContext';+import { MetricCard } from '../../ds';+import { Button } from '@/components/ui/button';+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 <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 && (+ <div className="wp-kpis">+ <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" />+ )}+ </div>+ )}++ {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/components/wordpress/detail/wpDetailShared.jsx b/frontend/src/components/wordpress/detail/wpDetailShared.jsxnew file mode 100644index 00000000..b90c9d4b--- /dev/null+++ b/frontend/src/components/wordpress/detail/wpDetailShared.jsx@@ -0,0 +1,553 @@+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 '../../../services/api';+import wordpressApi from '../../../services/wordpress';+import { useToast } from '../../../contexts/ToastContext';+import { Pill } from '../../ds';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';++// 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} {rec.name} → {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'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'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/pages/ApplicationDetail.jsx b/frontend/src/pages/ApplicationDetail.jsxindex d607a800..21ffe8f8 100644--- a/frontend/src/pages/ApplicationDetail.jsx+++ b/frontend/src/pages/ApplicationDetail.jsx@@ -1,52 +1,29 @@import { useState, useEffect } from 'react';import { useParams, useNavigate, Link } from 'react-router-dom';-import { GitBranch, GitMerge, Boxes } from 'lucide-react';+import { GitBranch, Boxes } from 'lucide-react';import api from '../services/api';-import { formatBytes } from '@/utils/formatBytes';import EmptyState from '../components/EmptyState';import useTabParam from '../hooks/useTabParam';-import { useToast } from '../contexts/ToastContext';-import { useConfirm } from '../hooks/useConfirm';-import { DangerZone } from '../components/DangerZone';-import { InfoList, InfoItem } from '../components/InfoList';import EnvironmentVariables from '../components/EnvironmentVariables';-import PrivateURLSection from '../components/PrivateURLSection';-import LinkedAppsSection from '../components/LinkedAppsSection';-import LinkAppModal from '../components/LinkAppModal';import ContainerOpsPanel from '../components/apps/ContainerOpsPanel';import AppWafPanel from '../components/apps/AppWafPanel';import PreviewList from '../components/previews/PreviewList';-import DeploymentTimeline from '../components/deployments/DeploymentTimeline';-import BuildpackPreview from '../components/buildpack/BuildpackPreview';-import TagsPanel from '../components/shared/TagsPanel';-import EnvironmentVariablesPanel from '../components/shared/EnvironmentVariablesPanel';import { getServiceType, getStatusConfig } from '../utils/serviceTypes';import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Textarea } from '@/components/ui/textarea';import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';import { Pill, EnvTag } from '@/components/ds';-import Modal from '@/components/Modal';+import { STATUS_PILL, INGRESS_META } from '../components/appdetail/appDetailShared';+import OverviewTab from '../components/appdetail/OverviewTab';+import PackagesTab from '../components/appdetail/PackagesTab';+import GunicornTab from '../components/appdetail/GunicornTab';+import CommandsTab from '../components/appdetail/CommandsTab';+import BuildTab from '../components/appdetail/BuildTab';+import LogsTab from '../components/appdetail/LogsTab';+import SettingsTab from '../components/appdetail/SettingsTab';+import DeployTab from '../components/appdetail/DeployTab';const VALID_TABS = ['overview', 'environment', 'packages', 'gunicorn', 'commands', 'ops', 'waf', 'build', 'deploy', 'previews', 'logs', 'settings'];-// statusInfo.dotClass → ds Pill kind-const STATUS_PILL = {- live: 'green',- stopped: 'gray',- deploying: 'amber',- building: 'amber',- failed: 'red',-};--// Ingress plane → label + Pill kind. Host Nginx is the neutral default;-// a managed proxy stack reads as the accent (cyan) choice. NULL/undefined-// reads as host Nginx, matching the backend.-const INGRESS_META = {- proxy_stack: { label: 'Proxy stack', kind: 'cyan' },- nginx: { label: 'Nginx', kind: 'gray' },-};-const ApplicationDetail = () => {const { id } = useParams();const navigate = useNavigate();@@ -295,1443 +272,4 @@ const ApplicationDetail = () => {);};-// Overview Tab with new grid layout-const OverviewTab = ({ app, onUpdate }) => {- const navigate = useNavigate();- const { confirm: confirmOverview } = useConfirm();- const [status, setStatus] = useState(null);- const [appStatus, setAppStatus] = useState(null);- const [linkedApps, setLinkedApps] = useState([]);- const [showLinkModal, setShowLinkModal] = useState(false);- const [linkLoading, setLinkLoading] = useState(false);- const [containerStats, setContainerStats] = useState(null);-- useEffect(() => {- if (['flask', 'django'].includes(app.app_type)) {- loadStatus();- }- loadAppStatus();- loadLinkedApps();- if (app.app_type === 'docker') {- loadContainerStats();- }- }, [app]);-- async function loadStatus() {- try {- const data = await api.getPythonAppStatus(app.id);- setStatus(data);- } catch (err) {- console.error('Failed to load status:', err);- }- }-- async function loadAppStatus() {- try {- const data = await api.getAppStatus(app.id);- setAppStatus(data);- } catch (err) {- console.error('Failed to load app status:', err);- }- }-- async function loadLinkedApps() {- try {- const data = await api.getLinkedApps(app.id);- setLinkedApps(data.linked_apps || []);- } catch (err) {- console.error('Failed to load linked apps:', err);- }- }-- async function loadContainerStats() {- try {- // Try to get container stats for docker apps- const containers = await api.getContainers(true);- const appContainer = containers.containers?.find(c =>- c.name?.includes(app.name) || c.name?.includes(app.slug)- );- if (appContainer && appContainer.state === 'running') {- const stats = await api.getContainerStats(appContainer.id);- setContainerStats(stats.stats);- }- } catch (err) {- console.error('Failed to load container stats:', err);- }- }-- async function handleUnlink() {- const confirmed = await confirmOverview({ title: 'Unlink Apps', message: 'Are you sure you want to unlink these apps? Database credentials will remain unchanged.', variant: 'warning' });- if (!confirmed) {- return;- }- setLinkLoading(true);- try {- await api.unlinkApp(app.id);- onUpdate();- loadLinkedApps();- } catch (err) {- console.error('Failed to unlink apps:', err);- } finally {- setLinkLoading(false);- }- }-- function handleLinked() {- onUpdate();- loadLinkedApps();- }-- function parseResourceValue(value) {- if (!value) return 0;- return parseFloat(value.replace('%', '')) || 0;- }-- return (- <div className="app-overview-grid">- {/* Left Column */}- <div className="app-overview-left">- {/* Application Info Panel */}- <div className="app-panel">- <div className="app-panel-header">Application Info</div>- <div className="app-panel-body">- <div className="app-info-grid">- <div className="app-info-item">- <span className="app-info-label">Type</span>- <span className="app-info-value">{app.app_type === 'docker' ? 'Docker Container' : app.app_type.toUpperCase()}</span>- </div>- <div className="app-info-item">- <span className="app-info-label">Port</span>- <span className="app-info-value">- {app.port || '-'}- {appStatus && app.port && (- <span className={`port-indicator ${appStatus.port_accessible ? 'accessible' : ''}`}>- {appStatus.port_accessible ? ' (accessible)' : ' (not accessible)'}- </span>- )}- </span>- </div>- {app.python_version && (- <div className="app-info-item">- <span className="app-info-label">Python Version</span>- <span className="app-info-value">{app.python_version}</span>- </div>- )}- {app.php_version && (- <div className="app-info-item">- <span className="app-info-label">PHP Version</span>- <span className="app-info-value">{app.php_version}</span>- </div>- )}- <div className="app-info-item full-width">- <span className="app-info-label">Root Path</span>- <div><span className="app-path-value">{app.root_path || `/var/serverkit/apps/${app.name}`}</span></div>- </div>- </div>- </div>- </div>-- {/* Routing Diagnostics Panel (Docker apps only) */}- {app.app_type === 'docker' && (- <RoutingDiagnosticsPanel appId={app.id} />- )}-- {/* Environment Linking Panel */}- <div className="app-panel">- <div className="app-panel-header">Environment Linking</div>- <div className="app-panel-body">- <p className="app-panel-hint">- Link this app to another to create a production/development pair. Linked apps can share database credentials.- </p>- <LinkedAppsSection- app={app}- linkedApps={linkedApps}- onLink={() => setShowLinkModal(true)}- onUnlink={handleUnlink}- onNavigate={(appId) => navigate(`/apps/${appId}`)}- loading={linkLoading}- compact- />- </div>- </div>-- {/* Process Status (Python apps) */}- {status && (- <div className="app-panel">- <div className="app-panel-header">Process Status</div>- <div className="app-panel-body">- <div className="app-info-grid">- <div className="app-info-item">- <span className="app-info-label">Service</span>- <span className="app-info-value mono">{status.service_name}</span>- </div>- <div className="app-info-item">- <span className="app-info-label">State</span>- <span className="app-info-value">{status.active_state} ({status.sub_state})</span>- </div>- {status.main_pid !== '0' && (- <div className="app-info-item">- <span className="app-info-label">PID</span>- <span className="app-info-value mono">{status.main_pid}</span>- </div>- )}- {status.memory && status.memory !== '0' && (- <div className="app-info-item">- <span className="app-info-label">Memory</span>- <span className="app-info-value">{formatBytes(parseInt(status.memory))}</span>- </div>- )}- </div>- </div>- </div>- )}-- {/* Domains Panel */}- {app.domains && app.domains.length > 0 && (- <div className="app-panel">- <div className="app-panel-header">Domains</div>- <div className="app-panel-body">- <div className="domains-list">- {app.domains.map(domain => (- <div key={domain.id} className="domain-item">- <a href={`https://${domain.name}`} target="_blank" rel="noopener noreferrer">- {domain.name}- </a>- {domain.ssl_enabled && (- <span className="ssl-badge">SSL</span>- )}- </div>- ))}- </div>- </div>- </div>- )}- </div>-- {/* Right Column */}- <div className="app-overview-right">- {/* Private URL Panel (Docker apps with port) */}- {app.app_type === 'docker' && app.port && (- <PrivateURLSection app={app} onUpdate={onUpdate} />- )}-- {/* Live Resources Panel */}- {app.app_type === 'docker' && (- <div className="app-panel">- <div className="app-panel-header">Live Resources</div>- <div className="app-panel-body">- <div className="resource-bar-container">- <div className="resource-bar-header">- <span className="resource-bar-label">CPU Load</span>- <span className="resource-bar-value">- {containerStats ? `${parseResourceValue(containerStats.CPUPerc).toFixed(0)}%` : '-'}- </span>- </div>- <div className="resource-bar-track">- <div- className="resource-bar-fill cpu"- style={{ width: `${containerStats ? parseResourceValue(containerStats.CPUPerc) : 0}%` }}- />- </div>- </div>- <div className="resource-bar-container">- <div className="resource-bar-header">- <span className="resource-bar-label">RAM Usage</span>- <span className="resource-bar-value">- {containerStats?.MemUsage || '-'}- </span>- </div>- <div className="resource-bar-track">- <div- className="resource-bar-fill ram"- style={{ width: `${containerStats ? parseResourceValue(containerStats.MemPerc) : 0}%` }}- />- </div>- </div>- {!containerStats && app.status !== 'running' && (- <p className="resource-hint">Start the container to see live resources.</p>- )}- </div>- </div>- )}-- {/* Tags Panel (polymorphic shared resource) */}- <div className="app-panel">- <div className="app-panel-header">Tags</div>- <div className="app-panel-body">- <TagsPanel resourceType="application" resourceId={app.id} />- </div>- </div>-- {/* Shared Variables Panel (resolved from attached groups) */}- <div className="app-panel">- <div className="app-panel-body">- <EnvironmentVariablesPanel resourceType="application" resourceId={app.id} />- </div>- </div>- </div>-- {showLinkModal && (- <LinkAppModal- app={app}- onClose={() => setShowLinkModal(false)}- onLinked={handleLinked}- />- )}- </div>- );-};--// Routing Diagnostics Panel-const RoutingDiagnosticsPanel = ({ appId }) => {- const [diagnostics, setDiagnostics] = useState(null);- const [loading, setLoading] = useState(false);- const [lastChecked, setLastChecked] = useState(null);-- async function runDiagnostics() {- setLoading(true);- try {- const response = await fetch(`/api/v1/domains/debug/diagnose/${appId}`, {- headers: {- 'Authorization': `Bearer ${localStorage.getItem('accessToken')}`- }- });- const data = await response.json();- setDiagnostics(data);- setLastChecked(new Date());- } catch (err) {- console.error('Failed to run diagnostics:', err);- } finally {- setLoading(false);- }- }-- const isHealthy = diagnostics?.health?.overall;-- return (- <div className="app-panel">- <div className="app-panel-header">- <span>Routing Diagnostics</span>- <span className="app-panel-header-actions">- <Button- variant="ghost"- size="sm"- onClick={runDiagnostics}- disabled={loading}- >- {loading ? 'Checking...' : 'Run Diagnostics'}- </Button>- </span>- </div>- <div className="app-panel-body">- {diagnostics ? (- <>- <div className={`diag-status ${isHealthy ? 'healthy' : 'unhealthy'}`}>- <div className={`diag-icon ${isHealthy ? 'healthy' : 'unhealthy'}`}>- {isHealthy ? '✓' : '✗'}- </div>- <div className="diag-text">- <h4>{isHealthy ? 'Configuration Healthy' : 'Issues Detected'}</h4>- <p>- {lastChecked && `Last checked: ${Math.round((Date.now() - lastChecked) / 60000)} minutes ago. `}- {isHealthy ? 'No routing issues detected.' : 'Some checks failed.'}- </p>- </div>- </div>- {diagnostics.health?.issues?.length > 0 && (- <ul className="diag-issues">- {diagnostics.health.issues.map((issue, i) => (- <li key={i}>{issue}</li>- ))}- </ul>- )}- </>- ) : (- <p className="app-panel-hint">- Click "Run Diagnostics" to check routing configuration and identify issues.- </p>- )}- </div>- </div>- );-};--// ============================================-// EXISTING TAB COMPONENTS (preserved)-// ============================================--const PackagesTab = ({ appId }) => {- const toast = useToast();- const [packages, setPackages] = useState([]);- const [loading, setLoading] = useState(true);- const [installing, setInstalling] = useState(false);- const [newPackage, setNewPackage] = useState('');-- useEffect(() => {- loadPackages();- }, [appId]);-- async function loadPackages() {- try {- const data = await api.getPythonPackages(appId);- setPackages(data.packages || []);- } catch (err) {- console.error('Failed to load packages:', err);- } finally {- setLoading(false);- }- }-- async function handleInstall(e) {- e.preventDefault();- if (!newPackage.trim()) return;-- setInstalling(true);- try {- await api.installPythonPackages(appId, [newPackage.trim()]);- setNewPackage('');- loadPackages();- } catch (err) {- console.error('Failed to install package:', err);- } finally {- setInstalling(false);- }- }-- async function handleFreeze() {- try {- await api.freezePythonRequirements(appId);- toast.success('requirements.txt updated');- } catch (err) {- toast.error('Failed to freeze requirements');- console.error('Failed to freeze requirements:', err);- }- }-- if (loading) {- return <EmptyState loading title="Loading packages..." />;- }-- return (- <div>- <div className="section-header">- <h3>Installed Packages</h3>- <Button variant="outline" size="sm" onClick={handleFreeze}>- Freeze to requirements.txt- </Button>- </div>-- <form className="install-form" onSubmit={handleInstall}>- <Input- type="text"- value={newPackage}- onChange={(e) => setNewPackage(e.target.value)}- placeholder="Package name (e.g., requests, flask==2.0.0)"- />- <Button type="submit" disabled={installing}>- {installing ? 'Installing...' : 'Install'}- </Button>- </form>-- <div className="packages-list">- {packages.map(pkg => (- <div key={pkg.name} className="package-item">- <span className="package-name">{pkg.name}</span>- <span className="package-version">{pkg.version}</span>- </div>- ))}- </div>- </div>- );-};--const GunicornTab = ({ appId }) => {- const toast = useToast();- const [config, setConfig] = useState('');- const [loading, setLoading] = useState(true);- const [saving, setSaving] = useState(false);-- useEffect(() => {- loadConfig();- }, [appId]);-- async function loadConfig() {- try {- const data = await api.getGunicornConfig(appId);- setConfig(data.content || '');- } catch (err) {- console.error('Failed to load config:', err);- } finally {- setLoading(false);- }- }-- async function handleSave() {- setSaving(true);- try {- await api.updateGunicornConfig(appId, config);- toast.success('Configuration saved. Restart the app to apply changes.');- } catch (err) {- toast.error('Failed to save configuration');- console.error('Failed to save config:', err);- } finally {- setSaving(false);- }- }-- if (loading) {- return <EmptyState loading title="Loading Gunicorn configuration..." />;- }-- return (- <div>- <div className="section-header">- <h3>Gunicorn Configuration</h3>- <Button onClick={handleSave} disabled={saving}>- {saving ? 'Saving...' : 'Save'}- </Button>- </div>- <textarea- className="code-editor"- value={config}- onChange={(e) => setConfig(e.target.value)}- spellCheck={false}- />- </div>- );-};--const CommandsTab = ({ appId, appType }) => {- const [command, setCommand] = useState('');- const [output, setOutput] = useState(null);- const [running, setRunning] = useState(false);-- const quickCommands = appType === 'django' ? [- { label: 'Run Migrations', cmd: 'python manage.py migrate' },- { label: 'Collect Static', cmd: 'python manage.py collectstatic --noinput' },- { label: 'Create Superuser', cmd: 'python manage.py createsuperuser' },- { label: 'Shell', cmd: 'python manage.py shell' },- { label: 'Check', cmd: 'python manage.py check' },- ] : [- { label: 'Flask Routes', cmd: 'flask routes' },- { label: 'Flask Shell', cmd: 'flask shell' },- { label: 'DB Upgrade', cmd: 'flask db upgrade' },- { label: 'DB Migrate', cmd: 'flask db migrate' },- ];-- async function handleRun(cmd) {- const commandToRun = cmd || command;- if (!commandToRun.trim()) return;-- setRunning(true);- setOutput(null);-- try {- const result = await api.runPythonCommand(appId, commandToRun);- setOutput(result);- } catch (err) {- setOutput({ success: false, stderr: err.message });- } finally {- setRunning(false);- }- }-- return (- <div>- <h3 className="app-eyebrow">Run Commands</h3>- <p className="hint">Commands run in the app's virtual environment context.</p>-- <div className="quick-commands">- {quickCommands.map(({ label, cmd }) => (- <Button- key={cmd}- variant="outline"- size="sm"- onClick={() => handleRun(cmd)}- disabled={running}- >- {label}- </Button>- ))}- </div>-- <div className="command-input">- <Input- type="text"- value={command}- onChange={(e) => setCommand(e.target.value)}- placeholder="Enter command..."- onKeyDown={(e) => e.key === 'Enter' && handleRun()}- />- <Button- onClick={() => handleRun()}- disabled={running}- >- {running ? 'Running...' : 'Run'}- </Button>- </div>-- {output && (- <div className={`command-output ${output.success ? '' : 'error'}`}>- {output.stdout && <pre>{output.stdout}</pre>}- {output.stderr && <pre className="stderr">{output.stderr}</pre>}- {!output.stdout && !output.stderr && (- <pre>{output.success ? 'Command completed successfully' : 'Command failed'}</pre>- )}- </div>- )}- </div>- );-};--const BuildTab = ({ appId, appPath, app }) => {- const toast = useToast();- const { confirm: confirmBuild } = useConfirm();- const [buildConfig, setBuildConfig] = useState(null);- const [detection, setDetection] = useState(null);- const [deployments, setDeployments] = useState([]);- const [currentDeployment, setCurrentDeployment] = useState(null);- const [loading, setLoading] = useState(true);- const [building, setBuilding] = useState(false);- const [deploying, setDeploying] = useState(false);- const [showConfigModal, setShowConfigModal] = useState(false);- const [showLogsModal, setShowLogsModal] = useState(false);- const [selectedLog, setSelectedLog] = useState(null);- const [buildLogs, setBuildLogs] = useState([]);- const [error, setError] = useState(null);- const [bpDockerfile, setBpDockerfile] = useState(null);-- // When the app was created from a detected build pack, fetch a read-only- // preview of the generated Dockerfile for transparency.- useEffect(() => {- let active = true;- if (app?.buildpack_plan) {- api.generateBuildpack(app.buildpack_plan, app.buildpack_overrides || {}, app.name)- .then((res) => { if (active) setBpDockerfile(res?.dockerfile || null); })- .catch(() => {});- }- return () => { active = false; };- }, [app?.buildpack_plan, app?.buildpack_overrides, app?.name]);-- const [configForm, setConfigForm] = useState({- buildMethod: 'auto',- dockerfilePath: 'Dockerfile',- customBuildCmd: '',- customStartCmd: '',- cacheEnabled: true,- timeout: 600,- keepDeployments: 5- });-- useEffect(() => {- loadData();- }, [appId]);-- async function loadData() {- try {- setLoading(true);- const [configRes, detectRes, deploymentsRes] = await Promise.all([- api.getBuildConfig(appId),- api.detectBuildMethod(appId),- api.getDeployments(appId, 10)- ]);-- setDetection(detectRes);-- if (configRes.configured) {- setBuildConfig(configRes.config);- setConfigForm({- buildMethod: configRes.config.build_method || 'auto',- dockerfilePath: configRes.config.dockerfile_path || 'Dockerfile',- customBuildCmd: configRes.config.custom_build_cmd || '',- customStartCmd: configRes.config.custom_start_cmd || '',- cacheEnabled: configRes.config.cache_enabled !== false,- timeout: configRes.config.timeout || 600,- keepDeployments: configRes.config.keep_deployments || 5- });- }-- setDeployments(deploymentsRes.deployments || []);- setCurrentDeployment(deploymentsRes.current);-- } catch (err) {- setError(err.message);- } finally {- setLoading(false);- }- }-- async function handleConfigureBuild(e) {- e.preventDefault();- try {- await api.configureBuild(appId, {- build_method: configForm.buildMethod,- dockerfile_path: configForm.dockerfilePath,- custom_build_cmd: configForm.customBuildCmd || null,- custom_start_cmd: configForm.customStartCmd || null,- cache_enabled: configForm.cacheEnabled,- timeout: configForm.timeout,- keep_deployments: configForm.keepDeployments- });- setShowConfigModal(false);- toast.success('Build configuration saved');- loadData();- } catch (err) {- setError(err.message);- }- }-- async function handleBuild(noCache = false) {- setBuilding(true);- setError(null);- try {- const result = await api.triggerBuild(appId, noCache);- if (result.success) {- toast.success('Build completed successfully');- } else {- setError(result.error || 'Build failed');- }- loadData();- } catch (err) {- setError(err.message);- } finally {- setBuilding(false);- }- }-- async function handleDeploy(noCache = false) {- setDeploying(true);- setError(null);- try {- const result = await api.deployApp(appId, { no_cache: noCache });- if (result.success) {- toast.success(`Deployment v${result.deployment.version} successful!`);- } else {- setError(result.error || 'Deployment failed');- }- loadData();- } catch (err) {- setError(err.message);- } finally {- setDeploying(false);- }- }-- async function handleRollback(version = null) {- const rollbackMsg = version- ? `Rollback to version ${version}? This will replace the current deployment.`- : 'Rollback to previous deployment?';- const confirmed = await confirmBuild({ title: 'Rollback', message: rollbackMsg, variant: 'warning' });- if (!confirmed) return;-- setDeploying(true);- setError(null);- try {- const result = await api.rollback(appId, version);- if (result.success) {- toast.success('Rollback successful');- } else {- setError(result.error || 'Rollback failed');- }- loadData();- } catch (err) {- setError(err.message);- } finally {- setDeploying(false);- }- }-- function getStatusPillKind(status) {- switch (status) {- case 'live': return 'green';- case 'building':- case 'deploying':- case 'pending': return 'amber';- case 'failed': return 'red';- case 'rolled_back': return 'gray';- default: return 'gray';- }- }-- function formatDuration(seconds) {- if (!seconds) return '-';- if (seconds < 60) return `${Math.round(seconds)}s`;- return `${Math.floor(seconds / 60)}m ${Math.round(seconds % 60)}s`;- }-- if (loading) {- return <EmptyState loading title="Loading build configuration..." />;- }-- return (- <div className="build-tab">- {error && (- <div className="alert alert-danger">- {error}- <button onClick={() => setError(null)} className="alert-close">×</button>- </div>- )}-- {detection && (- <div className="card">- <h3>Auto-Detection Results</h3>- <div className="detection-results">- <div className="detection-item">- <span className="detection-label">Detected Method:</span>- <span className="detection-value">{detection.detected_method || 'None'}</span>- </div>- {detection.dockerfile_exists && (- <div className="detection-item">- <span className="detection-label">Dockerfile:</span>- <span className="detection-value">Found</span>- </div>- )}- {detection.docker_compose_exists && (- <div className="detection-item">- <span className="detection-label">Docker Compose:</span>- <span className="detection-value">Found</span>- </div>- )}- </div>- </div>- )}-- {app?.buildpack_plan && (- <div className="card">- <h3>Build Pack</h3>- <BuildpackPreview- plan={app.buildpack_plan}- dockerfile={bpDockerfile}- overrides={app.buildpack_overrides || {}}- />- </div>- )}-- <div className="card">- <div className="card-header-row">- <h3>Build Configuration</h3>- <Button variant="outline" size="sm" onClick={() => setShowConfigModal(true)}>- Configure- </Button>- </div>- {buildConfig ? (- <InfoList>- <InfoItem label="Method" value={buildConfig.build_method} />- <InfoItem label="Timeout" value={`${buildConfig.timeout}s`} />- </InfoList>- ) : (- <p className="hint">No build configuration. Click Configure to set up.</p>- )}- <div className="card-actions">- <Button- onClick={() => handleDeploy(false)}- disabled={deploying || building}- >- {deploying ? 'Deploying...' : 'Build & Deploy'}- </Button>- <Button- variant="outline"- onClick={() => handleBuild(false)}- disabled={building || deploying}- >- {building ? 'Building...' : 'Build Only'}- </Button>- </div>- </div>-- {deployments.length > 0 && (- <div className="card">- <h3>Deployment History</h3>- <div className="deployments-list">- {deployments.map(dep => (- <div key={dep.version} className={`deployment-item ${dep.status === 'live' ? 'current' : ''}`}>- <div className="deployment-info">- <span className="deployment-version">v{dep.version}</span>- <Pill kind={getStatusPillKind(dep.status)}>{dep.status}</Pill>- </div>- <div className="deployment-meta">- <span>{new Date(dep.created_at).toLocaleString()}</span>- <span>{formatDuration(dep.build_duration)}</span>- </div>- {dep.status !== 'live' && (- <Button- variant="outline"- size="sm"- onClick={() => handleRollback(dep.version)}- disabled={deploying}- >- Rollback- </Button>- )}- </div>- ))}- </div>- </div>- )}-- <Modal open={showConfigModal} onClose={() => setShowConfigModal(false)} title="Build Configuration">- <form onSubmit={handleConfigureBuild}>- <div className="form-group">- <label>Build Method</label>- <select- value={configForm.buildMethod}- onChange={e => setConfigForm({...configForm, buildMethod: e.target.value})}- >- <option value="auto">Auto-detect</option>- <option value="dockerfile">Dockerfile</option>- <option value="docker-compose">Docker Compose</option>- <option value="custom">Custom</option>- </select>- </div>- {configForm.buildMethod === 'dockerfile' && (- <div className="form-group">- <label>Dockerfile Path</label>- <Input- type="text"- value={configForm.dockerfilePath}- onChange={e => setConfigForm({...configForm, dockerfilePath: e.target.value})}- />- </div>- )}- {configForm.buildMethod === 'custom' && (- <>- <div className="form-group">- <label>Build Command</label>- <Input- type="text"- value={configForm.customBuildCmd}- onChange={e => setConfigForm({...configForm, customBuildCmd: e.target.value})}- placeholder="npm run build"- />- </div>- <div className="form-group">- <label>Start Command</label>- <Input- type="text"- value={configForm.customStartCmd}- onChange={e => setConfigForm({...configForm, customStartCmd: e.target.value})}- placeholder="npm start"- />- </div>- </>- )}- <div className="form-group">- <label>Timeout (seconds)</label>- <Input- type="number"- value={configForm.timeout}- onChange={e => setConfigForm({...configForm, timeout: parseInt(e.target.value)})}- />- </div>- <div className="modal-actions">- <Button type="button" variant="outline" onClick={() => setShowConfigModal(false)}>- Cancel- </Button>- <Button type="submit">- Save Configuration- </Button>- </div>- </form>- </Modal>- </div>- );-};--const LogsTab = ({ app }) => {- const [logs, setLogs] = useState('');- const [loading, setLoading] = useState(true);- const [autoRefresh, setAutoRefresh] = useState(false);-- const isDockerApp = app.app_type === 'docker';- const isPythonApp = ['flask', 'django'].includes(app.app_type);-- useEffect(() => {- loadLogs();- }, [app.id]);-- useEffect(() => {- if (!autoRefresh) return;- const interval = setInterval(loadLogs, 5000);- return () => clearInterval(interval);- }, [autoRefresh, app.id]);-- async function loadLogs() {- try {- let data;- if (isDockerApp) {- data = await api.getDockerAppLogs(app.id, 200);- } else if (isPythonApp) {- data = await api.getPythonAppLogs(app.id, 200);- } else {- data = { logs: 'Logs not available for this app type.' };- }- setLogs(data.logs || 'No logs available');- } catch (err) {- console.error('Failed to load logs:', err);- setLogs('Failed to load logs');- } finally {- setLoading(false);- }- }-- return (- <div className="logs-tab">- <div className="logs-header">- <h3>Application Logs</h3>- <div className="logs-controls">- {isPythonApp && (- <span className="hint">Gunicorn/systemd Logs</span>- )}- {isDockerApp && (- <span className="hint">Docker Compose Logs</span>- )}- <label className="checkbox-inline">- <input- type="checkbox"- checked={autoRefresh}- onChange={(e) => setAutoRefresh(e.target.checked)}- />- Auto-refresh- </label>- <Button variant="outline" size="sm" onClick={loadLogs}>- Refresh- </Button>- </div>- </div>- <pre className="log-viewer">{loading ? 'Loading...' : logs}</pre>- </div>- );-};--const SettingsTab = ({ app, onUpdate }) => {- const navigate = useNavigate();- const { confirm: confirmAppSettings } = useConfirm();- const [deleting, setDeleting] = useState(false);- const [environmentType, setEnvironmentType] = useState(app.environment_type || 'standalone');- const [savingEnvironment, setSavingEnvironment] = useState(false);- const [unlinking, setUnlinking] = useState(false);-- const envLabels = {- standalone: 'Standalone',- production: 'Production',- development: 'Development',- staging: 'Staging'- };-- async function handleDelete() {- const firstConfirm = await confirmAppSettings({ title: 'Delete Application', message: `Delete ${app.name}? This action cannot be undone.` });- if (!firstConfirm) return;- const secondConfirm = await confirmAppSettings({ title: 'Confirm Deletion', message: 'Are you sure? This will permanently delete the application and all its data.' });- if (!secondConfirm) return;-- setDeleting(true);- try {- await api.deleteApp(app.id);- navigate('/apps');- } catch (err) {- console.error('Failed to delete app:', err);- setDeleting(false);- }- }-- async function handleEnvironmentChange(newType) {- if (newType === app.environment_type) return;-- setSavingEnvironment(true);- try {- await api.updateAppEnvironment(app.id, newType);- setEnvironmentType(newType);- onUpdate();- } catch (err) {- console.error('Failed to update environment:', err);- setEnvironmentType(app.environment_type || 'standalone');- } finally {- setSavingEnvironment(false);- }- }-- async function handleUnlink() {- const confirmed = await confirmAppSettings({ title: 'Unlink Application', message: `Unlink ${app.name} from its linked application? Both apps will become standalone.`, variant: 'warning' });- if (!confirmed) return;-- setUnlinking(true);- try {- await api.unlinkApp(app.id);- onUpdate();- } catch (err) {- console.error('Failed to unlink app:', err);- } finally {- setUnlinking(false);- }- }-- return (- <div>- <h3 className="app-eyebrow">Application Settings</h3>-- <div className="card settings-section">- <h4>Environment Configuration</h4>- <div className="settings-row">- <div className="settings-label">- <span>Environment Type</span>- <span className="settings-hint">- {app.has_linked_app- ? 'This app is linked. Unlink to change environment type.'- : 'Set how this application is used in your workflow.'}- </span>- </div>- <div className="settings-control">- {app.has_linked_app ? (- <EnvTag env={app.environment_type}>- {envLabels[app.environment_type] || app.environment_type}- </EnvTag>- ) : (- <select- value={environmentType}- onChange={(e) => handleEnvironmentChange(e.target.value)}- disabled={savingEnvironment}- className="settings-select"- >- <option value="standalone">Standalone</option>- <option value="development">Development</option>- <option value="staging">Staging</option>- <option value="production">Production</option>- </select>- )}- {savingEnvironment && <span className="settings-saving">Saving...</span>}- </div>- </div>-- {app.has_linked_app && (- <div className="settings-row settings-linked-warning">- <div className="settings-label">- <span>Linked Application</span>- <span className="settings-hint">- This app is linked to another application. Unlinking will reset both apps to standalone mode.- </span>- </div>- <div className="settings-control">- <Button- variant="outline"- onClick={handleUnlink}- disabled={unlinking}- >- {unlinking ? 'Unlinking...' : 'Unlink Application'}- </Button>- </div>- </div>- )}- </div>-- <DangerZone- title="Danger Zone"- description="Once you delete an application, there is no going back."- action={- <Button variant="destructive" onClick={handleDelete} disabled={deleting}>- {deleting ? 'Deleting...' : 'Delete Application'}- </Button>- }- />- </div>- );-};--const DeployTab = ({ appId, appPath }) => {- const toast = useToast();- const { confirm: confirmDeploy } = useConfirm();- const [config, setConfig] = useState(null);- const [gitStatus, setGitStatus] = useState(null);- const [history, setHistory] = useState([]);- const [loading, setLoading] = useState(true);- const [deploying, setDeploying] = useState(false);- const [showConfigModal, setShowConfigModal] = useState(false);- const [loadingBranches, setLoadingBranches] = useState(false);- const [branches, setBranches] = useState([]);- const [error, setError] = useState(null);-- const [configForm, setConfigForm] = useState({- repoUrl: '',- branch: 'main',- autoDeploy: true,- preDeployScript: '',- postDeployScript: ''- });-- useEffect(() => {- loadData();- }, [appId]);-- async function loadData() {- try {- setLoading(true);- const [configRes, historyRes] = await Promise.all([- api.getDeployConfig(appId),- api.getDeploymentHistory(appId, 20)- ]);-- if (configRes.configured) {- setConfig(configRes.config);- setConfigForm({- repoUrl: configRes.config.repo_url || '',- branch: configRes.config.branch || 'main',- autoDeploy: configRes.config.auto_deploy !== false,- preDeployScript: configRes.config.pre_deploy_script || '',- postDeployScript: configRes.config.post_deploy_script || ''- });- try {- const statusRes = await api.getAppGitStatus(appId);- setGitStatus(statusRes);- } catch { /* git status is optional context for the deploy tab */ }- } else {- setConfig(null);- }-- setHistory(historyRes.deployments || []);- } catch (err) {- setError(err.message);- } finally {- setLoading(false);- }- }-- async function handleConfigureDeployment(e) {- e.preventDefault();- try {- await api.configureDeployment(- appId,- configForm.repoUrl,- configForm.branch,- configForm.autoDeploy,- configForm.preDeployScript || null,- configForm.postDeployScript || null- );- setShowConfigModal(false);- loadData();- } catch (err) {- setError(err.message);- }- }-- async function handleRemoveDeployment() {- const confirmed = await confirmDeploy({ title: 'Remove Deployment', message: 'Remove deployment configuration? This will not delete the repository files.', variant: 'warning' });- if (!confirmed) return;- try {- await api.removeDeployment(appId);- setConfig(null);- setGitStatus(null);- loadData();- } catch (err) {- setError(err.message);- }- }-- async function handleDeploy(force = false) {- setDeploying(true);- setError(null);- try {- const result = await api.triggerAppDeploy(appId, force);- if (result.success) {- toast.success('Deployment completed successfully!');- } else {- setError(result.error || 'Deployment failed');- }- loadData();- } catch (err) {- setError(err.message);- } finally {- setDeploying(false);- }- }-- async function handlePull() {- setDeploying(true);- setError(null);- try {- const result = await api.pullChanges(appId);- if (result.success) {- toast.success('Changes pulled successfully!');- } else {- setError(result.error || 'Pull failed');- }- loadData();- } catch (err) {- setError(err.message);- } finally {- setDeploying(false);- }- }-- function getStatusPillKind(status) {- switch (status) {- case 'success': return 'green';- case 'failed': return 'red';- case 'in_progress': return 'amber';- default: return 'gray';- }- }-- if (loading) {- return <EmptyState loading title="Loading deployment configuration..." />;- }-- return (- <div className="deploy-tab">- {error && (- <div className="alert alert-danger">- {error}- <button onClick={() => setError(null)} className="alert-close">×</button>- </div>- )}-- {!config ? (- <div className="deploy-setup">- <EmptyState- icon={GitMerge}- title="Git Deployment Not Configured"- description="Connect a Git repository to enable automatic deployments via webhooks or manual triggers."- action={<Button onClick={() => setShowConfigModal(true)}>Configure Deployment</Button>}- />- </div>- ) : (- <>- <div className="deploy-header">- <div className="deploy-status-card">- <div className="deploy-repo-info">- <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" fill="none" strokeWidth="2">- <path d="M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"/>- </svg>- <div>- <span className="repo-url">{config.repo_url}</span>- <span className="repo-branch">Branch: {config.branch}</span>- </div>- </div>- <div className="deploy-actions">- <Button- variant="outline"- size="sm"- onClick={handlePull}- disabled={deploying}- >- Pull Only- </Button>- <Button- onClick={() => handleDeploy(false)}- disabled={deploying}- >- {deploying ? 'Deploying...' : 'Deploy Now'}- </Button>- </div>- </div>- </div>-- <div className="deploy-grid">- <div className="card">- <h3>Configuration</h3>- <InfoList>- <InfoItem label="Repository" value={config.repo_url} mono />- <InfoItem label="Branch" value={config.branch} />- <InfoItem label="Auto Deploy" value={config.auto_deploy ? 'Enabled' : 'Disabled'} />- </InfoList>- <div className="card-actions">- <Button variant="outline" size="sm" onClick={() => setShowConfigModal(true)}>- Edit- </Button>- <Button variant="destructive" size="sm" onClick={handleRemoveDeployment}>- Remove- </Button>- </div>- </div>-- {history.length > 0 && (- <div className="card">- <h3>Deployment History</h3>- <div className="deployments-list">- {history.slice(0, 5).map((dep, idx) => (- <div key={idx} className="deployment-item">- <Pill kind={getStatusPillKind(dep.status)}>{dep.status}</Pill>- <span className="deployment-date">{new Date(dep.timestamp).toLocaleString()}</span>- </div>- ))}- </div>- </div>- )}- </div>- </>- )}-- {/* Config snapshot timeline + diff — additive, independent of git- config so it shows the deploy history & config changes for any app. */}- <div className="card deploy-timeline-card">- <h3>Deployment Timeline</h3>- <p className="deploy-timeline-card__hint">- An immutable configuration snapshot (env keys, domains, image, build- method, volumes) is captured before each deployment. Secret values are- masked. Open a snapshot to diff it against the previous one or restore it.- </p>- <DeploymentTimeline appId={appId} />- </div>-- <Modal open={showConfigModal} onClose={() => setShowConfigModal(false)} title="Configure Deployment">- <form onSubmit={handleConfigureDeployment}>- <div className="form-group">- <label>Repository URL</label>- <Input- type="text"- value={configForm.repoUrl}- onChange={e => setConfigForm({...configForm, repoUrl: e.target.value})}- placeholder="https://github.com/user/repo.git"- required- />- </div>- <div className="form-group">- <label>Branch</label>- <Input- type="text"- value={configForm.branch}- onChange={e => setConfigForm({...configForm, branch: e.target.value})}- placeholder="main"- />- </div>- <div className="form-group">- <label className="checkbox-label">- <input- type="checkbox"- checked={configForm.autoDeploy}- onChange={e => setConfigForm({...configForm, autoDeploy: e.target.checked})}- />- <span>Enable auto-deploy on push</span>- </label>- </div>- <div className="form-group">- <label>Pre-deploy Script</label>- <Textarea- value={configForm.preDeployScript}- onChange={e => setConfigForm({...configForm, preDeployScript: e.target.value})}- placeholder="npm install"- rows={3}- />- </div>- <div className="form-group">- <label>Post-deploy Script</label>- <Textarea- value={configForm.postDeployScript}- onChange={e => setConfigForm({...configForm, postDeployScript: e.target.value})}- placeholder="npm run build"- rows={3}- />- </div>- <div className="modal-actions">- <Button type="button" variant="outline" onClick={() => setShowConfigModal(false)}>- Cancel- </Button>- <Button type="submit">- Save Configuration- </Button>- </div>- </form>- </Modal>- </div>- );-};-export default ApplicationDetail;diff --git a/frontend/src/pages/ServerDetail.jsx b/frontend/src/pages/ServerDetail.jsxindex bd963b82..1f0135e2 100644--- a/frontend/src/pages/ServerDetail.jsx+++ b/frontend/src/pages/ServerDetail.jsx@@ -2,49 +2,28 @@ import { useState, useEffect, useCallback } from 'react';import { useParams, Link, useNavigate } from 'react-router-dom';import api from '../services/api';import { useToast } from '../contexts/ToastContext';-import MetricsGraph from '../components/MetricsGraph';import { useConfirm } from '../hooks/useConfirm';-import { DangerZone } from '../components/DangerZone';import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Textarea } from '@/components/ui/textarea';-import { Pill, Gauge } from '../components/ds';+import { Pill } from '../components/ds';import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';-import {- Dialog,- DialogContent,- DialogHeader,- DialogTitle,- DialogDescription,- DialogFooter,-} from '@/components/ui/dialog';-import { Label } from '@/components/ui/label';-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from '@/components/ui/select';import PackagesTab from '../components/serverdetail/PackagesTab';import ServicesTab from '../components/serverdetail/ServicesTab';-import SystemStatusCard from '../components/serverdetail/SystemStatusCard';-import OnboardingWizard from '../components/server/OnboardingWizard';+import ServerOverviewTab from '../components/serverdetail/ServerOverviewTab';+import AlertsTab from '../components/serverdetail/AlertsTab';+import ServerDockerTab from '../components/serverdetail/ServerDockerTab';+import CronTab from '../components/serverdetail/CronTab';+import CloudflaredTab from '../components/serverdetail/CloudflaredTab';+import ServerMetricsTab from '../components/serverdetail/ServerMetricsTab';+import ServerSettingsTab, { TokenModal } from '../components/serverdetail/ServerSettingsTab';+import {+ STATUS_PILL_KIND,+ CopyChip,+ FolderTinyIcon,+ RefreshIcon,+} from '../components/serverdetail/serverDetailShared';import ProxyStackPanel from '../components/proxy/ProxyStackPanel';import RemoteAccess from '../pages/RemoteAccess';-import TagsPanel from '../components/shared/TagsPanel';import EmptyState from '../components/EmptyState';-import { formatBytes } from '@/utils/formatBytes';-import { BellRing, Boxes, Container, Clock3, Cloud } from 'lucide-react';--// Server status → ds Pill tone (shared by the header pill and the-// Overview "Status" row).-const STATUS_PILL_KIND = {- online: 'green',- offline: 'red',- connecting: 'amber',- pending: 'gray',-};const ServerDetail = () => {const { id, tab } = useParams();@@ -339,7 +318,7 @@ const ServerDetail = () => {<div className="server-detail-content"><TabsContent value="overview">- <OverviewTab+ <ServerOverviewTabserver={server}metrics={metrics}systemInfo={systemInfo}@@ -347,7 +326,7 @@ const ServerDetail = () => {/></TabsContent><TabsContent value="docker">- <DockerTab serverId={id} serverStatus={server.status} server={server} />+ <ServerDockerTab serverId={id} serverStatus={server.status} server={server} /></TabsContent><TabsContent value="proxy"><ProxyStackPanel serverId={id} />@@ -373,7 +352,7 @@ const ServerDetail = () => {</TabsContent>)}<TabsContent value="metrics">- <MetricsTab serverId={id} metrics={metrics} />+ <ServerMetricsTab serverId={id} metrics={metrics} /></TabsContent><TabsContent value="alerts"><AlertsTab@@ -387,7 +366,7 @@ const ServerDetail = () => {<RemoteAccess serverId={id} /></TabsContent><TabsContent value="settings">- <SettingsTab+ <ServerSettingsTabserver={server}onUpdate={loadServer}onRegenerateToken={handleOpenTokenModal}@@ -408,2052 +387,4 @@ const ServerDetail = () => {);};-const OverviewTab = ({ server, metrics, systemInfo, onRefreshServer }) => {- const formatUptime = (seconds) => {- if (!seconds) return 'N/A';- const days = Math.floor(seconds / 86400);- const hours = Math.floor((seconds % 86400) / 3600);- if (days > 0) return `${days}d ${hours}h`;- const mins = Math.floor((seconds % 3600) / 60);- return `${hours}h ${mins}m`;- };-- const isOnline = server.status === 'online';- const cpuCores = systemInfo?.cpu_cores || server.cpu_cores;- const cpuModel = systemInfo?.cpu_model || server.cpu_model;- const totalMemory = systemInfo?.total_memory || server.total_memory;- const totalDisk = systemInfo?.total_disk || server.total_disk;- const osLabel = `${systemInfo?.os || server.os_type || 'Unknown'}${systemInfo?.os_version || server.os_version ? ` ${systemInfo?.os_version || server.os_version}` : ''}`;-- // Surface the onboarding wizard while a server is still being- // provisioned. Hidden once onboarding reaches 'ready' (or was never- // started) so it doesn't clutter a healthy server's overview.- const showOnboarding =- server.onboarding_state &&- !['ready', 'pending'].includes(server.onboarding_state);-- return (- <div className="overview-tab">- {showOnboarding && (- <div className="overview-tab__onboarding">- <OnboardingWizard- serverId={server.id}- initialState={server.onboarding_state}- onStateChange={(newState) => {- // Refresh the parent server payload when onboarding- // reaches a terminal state so the card hides itself.- if (newState === 'ready' || newState === 'failed') {- onRefreshServer?.();- }- }}- />- </div>- )}- <div className="server-stats-strip">- <KpiTile- icon={<PulseIcon />}- label="Status"- value={server.status || 'pending'}- tone={isOnline ? 'success' : server.status === 'connecting' ? 'warning' : 'danger'}- />- <KpiTile- icon={<ClockIcon />}- label="Uptime"- value={isOnline ? formatUptime(metrics?.uptime) : '—'}- sub={isOnline && metrics?.uptime ? 'since last boot' : null}- />- <KpiGauge- icon={<CpuIcon />}- label="CPU"- percent={isOnline ? metrics?.cpu_percent : null}- color="var(--accent-bright)"- sub={cpuCores ? `${cpuCores} cores` : null}- />- <KpiGauge- icon={<MemoryIcon />}- label="Memory"- percent={isOnline ? metrics?.memory_percent : null}- color="var(--cyan)"- sub={totalMemory ? formatBytes(totalMemory) : null}- />- <KpiGauge- icon={<DiskIcon />}- label="Disk"- percent={isOnline ? metrics?.disk_percent : null}- color="var(--green)"- sub={totalDisk ? formatBytes(totalDisk) : null}- />- </div>-- {!isOnline && (- <div className="info-card offline-card">- <div className="offline-message">- <OfflineIcon />- <h4>Server Offline</h4>- <p>- {server.status === 'pending'- ? 'Waiting for agent installation...'- : 'Unable to connect to the server agent.'}- </p>- </div>- </div>- )}-- <div className="overview-grid">- <div className="info-card">- <h3><ServerIcon /> Server Information</h3>- <ul className="info-rows">- <InfoRow icon={<PulseIcon />} label="Status">- <Pill kind={STATUS_PILL_KIND[server.status] || 'gray'}>{server.status}</Pill>- </InfoRow>- <InfoRow icon={<HostIcon />} label="Hostname" value={server.hostname || 'N/A'} mono />- <InfoRow icon={<NetworkIcon />} label="IP Address" value={server.ip_address || 'N/A'} mono />- <InfoRow icon={<FolderTinyIcon />} label="Group" value={server.group_name || 'Ungrouped'} />- <InfoRow- icon={<ClockIcon />}- label="Last Seen"- value={server.last_seen ? new Date(server.last_seen).toLocaleString() : 'Never'}- />- </ul>- </div>-- <div className="info-card">- <h3><ChipIcon /> System Information</h3>- <ul className="info-rows">- <InfoRow icon={<OsIcon />} label="Operating System" value={osLabel} />- <InfoRow icon={<ArchIcon />} label="Architecture" value={systemInfo?.architecture || server.architecture || 'N/A'} mono />- <InfoRow- icon={<CpuIcon />}- label="CPU"- value={- (cpuModel || 'N/A') + (cpuCores ? ` (${cpuCores} cores)` : '')- }- />- <InfoRow icon={<MemoryIcon />} label="Total Memory" value={formatBytes(totalMemory, { defaultValue: 'N/A' })} mono />- <InfoRow icon={<DiskIcon />} label="Total Disk" value={formatBytes(totalDisk, { defaultValue: 'N/A' })} mono />- </ul>- </div>-- <div className="info-card overview-grid__full">- <h3><AgentIcon /> Agent Information</h3>- <ul className="info-rows info-rows--columns">- <InfoRow icon={<TagIcon />} label="Agent Version" value={server.agent_version || 'Not installed'} mono />- <InfoRow icon={<HashIcon />} label="Agent ID" value={server.agent_id || 'N/A'} mono />- <InfoRow icon={<DockerMiniIcon />} label="Docker Version" value={server.docker_version || systemInfo?.docker_version || 'N/A'} mono />- <InfoRow icon={<ClockIcon />} label="Uptime" value={formatUptime(metrics?.uptime)} mono />- </ul>- </div>-- <div className="overview-grid__full">- <SystemStatusCard server={server} onRefresh={onRefreshServer} />- </div>- </div>- </div>- );-};--const AlertsTab = ({ notifications, securityAlerts, onAcknowledge, onResolve }) => {- const sysItems = notifications || [];- const secItems = securityAlerts || [];- const openSec = secItems.filter(a => a.status === 'open');- const ackSec = secItems.filter(a => a.status === 'acknowledged');-- if (sysItems.length === 0 && secItems.length === 0) {- return (- <div className="alerts-tab">- <EmptyState- icon={BellRing}- title="All clear"- description="No active alerts for this server."- />- </div>- );- }-- return (- <div className="alerts-tab">- {sysItems.length > 0 && (- <section className="alerts-section">- <header className="alerts-section__header">- <h3>System</h3>- <span className="alerts-section__count">{sysItems.length}</span>- </header>- <ul className="notifications-list">- {sysItems.map((n) => (- <li key={n.id} className={`notification notification--${n.severity || 'info'}`}>- <span className="notification__icon">- {n.severity === 'warning' || n.severity === 'danger' ? <AlertIcon /> : <InfoCircleIcon />}- </span>- <div className="notification__body">- <div className="notification__title">{n.title}</div>- <p className="notification__message">{n.message}</p>- </div>- </li>- ))}- </ul>- </section>- )}-- {openSec.length > 0 && (- <section className="alerts-section">- <header className="alerts-section__header">- <h3>Security</h3>- <span className="alerts-section__count">{openSec.length} open</span>- </header>- <ul className="notifications-list">- {openSec.map(a => (- <SecurityAlertItem- key={a.id}- alert={a}- onAcknowledge={onAcknowledge}- onResolve={onResolve}- />- ))}- </ul>- </section>- )}-- {ackSec.length > 0 && (- <section className="alerts-section alerts-section--muted">- <header className="alerts-section__header">- <h3>Acknowledged</h3>- <span className="alerts-section__count">{ackSec.length}</span>- </header>- <ul className="notifications-list">- {ackSec.map(a => (- <SecurityAlertItem- key={a.id}- alert={a}- onAcknowledge={onAcknowledge}- onResolve={onResolve}- />- ))}- </ul>- </section>- )}- </div>- );-};--const SecurityAlertItem = ({ alert, onAcknowledge, onResolve }) => {- const sev = (alert.severity || 'info').toLowerCase();- const tone =- sev === 'critical' || sev === 'high' ? 'danger' :- sev === 'medium' || sev === 'warning' ? 'warning' : 'info';- const title = (alert.alert_type || 'alert').replace(/_/g, ' ');- return (- <li className={`notification notification--${tone}`}>- <span className="notification__icon">- {tone === 'info' ? <InfoCircleIcon /> : <AlertIcon />}- </span>- <div className="notification__body">- <div className="notification__head">- <span className="notification__title">{title}</span>- <span className={`severity-badge ${sev}`}>{sev}</span>- <span className="notification__time">- {alert.created_at ? new Date(alert.created_at).toLocaleString() : ''}- </span>- </div>- <p className="notification__message">- {alert.source_ip && <><strong>IP:</strong> {alert.source_ip}{' '}</>}- {alert.details?.message || ''}- {alert.details?.attempts ? ` (${alert.details.attempts} attempts)` : ''}- </p>- <div className="notification__actions">- {alert.status === 'open' && (- <Button variant="outline" size="sm" onClick={() => onAcknowledge(alert.id)}>- Acknowledge- </Button>- )}- <Button variant="outline" size="sm" onClick={() => onResolve(alert.id)}>- Resolve- </Button>- </div>- </div>- </li>- );-};--const InfoRow = ({ icon, label, value, mono, children }) => (- <li className="info-row">- <span className="info-row__icon">{icon}</span>- <span className="info-row__label">{label}</span>- <span className={`info-row__value${mono ? ' mono' : ''}`}>- {children ?? value}- </span>- </li>-);--const KpiTile = ({ icon, label, value, sub, tone }) => (- <div className={`kpi-tile${tone ? ` kpi-tile--${tone}` : ''}`}>- <div className="kpi-tile__head">- <span className="kpi-tile__icon">{icon}</span>- <span className="kpi-tile__label">{label}</span>- </div>- <div className="kpi-tile__value">{value}</div>- {sub && <div className="kpi-tile__sub">{sub}</div>}- </div>-);--const KpiGauge = ({ icon, label, percent, color, sub }) => {- const has = percent !== null && percent !== undefined && Number.isFinite(percent);- const safe = has ? Math.min(Math.max(percent, 0), 100) : 0;- const danger = safe > 85;- const warn = safe > 70 && !danger;- const fillColor = danger ? 'var(--red)' : warn ? 'var(--amber)' : color;-- return (- <div className={`kpi-tile kpi-tile--gauge${danger ? ' kpi-tile--danger' : warn ? ' kpi-tile--warn' : ''}`}>- <div className="kpi-tile__head">- <span className="kpi-tile__icon">{icon}</span>- <span className="kpi-tile__label">{label}</span>- </div>- <div className="kpi-tile__value">{has ? `${safe.toFixed(1)}%` : '—'}</div>- <Gauge className="kpi-tile__meter" value={safe} color={fillColor} />- {sub && <div className="kpi-tile__sub">{sub}</div>}- </div>- );-};--// The /servers/<id>/docker/* endpoints return raw arrays from Flask-// (route extracts result.get('data') before jsonify). The agent envelope's-// {success, data} shape is gone by the time it reaches the client, so unwrap-// both forms defensively.-const unwrapList = (response) => {- if (Array.isArray(response)) return response;- if (response?.success && Array.isArray(response.data)) return response.data;- return [];-};--// Docker exposes container ports as an array of {ip, private_port,-// public_port, type} objects. Render a compact "host:container/proto"-// string per binding, or fall back to "container/proto" when the port-// isn't mapped to the host. Older agents may already send a string.-const formatPorts = (ports) => {- if (!ports) return '-';- if (typeof ports === 'string') return ports || '-';- if (!Array.isArray(ports) || ports.length === 0) return '-';- const parts = ports.map((p) => {- if (!p || typeof p !== 'object') return String(p);- const proto = p.type || 'tcp';- if (p.public_port) {- const host = p.ip && p.ip !== '0.0.0.0' && p.ip !== '::' ? `${p.ip}:` : '';- return `${host}${p.public_port}->${p.private_port}/${proto}`;- }- return `${p.private_port}/${proto}`;- });- return parts.join(', ');-};--const DockerTab = ({ serverId, serverStatus, server }) => {- const [containers, setContainers] = useState([]);- const [images, setImages] = useState([]);- const [loading, setLoading] = useState(true);- const [loadError, setLoadError] = useState(null);- const [subTab, setSubTab] = useState('containers');- const toast = useToast();- const { confirm: confirmDocker } = useConfirm();-- useEffect(() => {- if (serverStatus === 'online') {- loadDockerData();- } else {- setLoading(false);- }- }, [serverId, serverStatus]);-- async function loadDockerData() {- setLoading(true);- setLoadError(null);- try {- const [containersRes, imagesRes] = await Promise.all([- api.getRemoteContainers(serverId, true),- api.getRemoteImages(serverId)- ]);-- setContainers(unwrapList(containersRes));- setImages(unwrapList(imagesRes));- } catch (err) {- console.error('Failed to load Docker data:', err);- setLoadError(err.message || 'Failed to load Docker data');- } finally {- setLoading(false);- }- }-- // If the agent reports docker capability false (Docker daemon not- // reachable from the agent process — common on Windows when the- // service hasn't been started, or on hosts where the agent user- // isn't in the docker group), explain that instead of pretending- // there are no containers.- const dockerCapability = server?.capabilities?.docker;- if (serverStatus === 'online' && server && dockerCapability === false) {- return (- <div className="docker-empty-state">- <EmptyState- icon={Container}- title="Docker not reachable from this agent"- description="The agent connected but could not talk to a Docker daemon. Make sure Docker is running on the host (and the agent user is in the docker group on Linux), then click Refresh on the Overview tab to re-probe capabilities."- />- <ul className="docker-empty-state__causes">- <li>Docker Desktop / dockerd is not running on the host</li>- <li>The agent user isn't in the <code>docker</code> group (Linux)</li>- <li>The npipe socket <code>{'//./pipe/docker_engine'}</code> isn't accessible (Windows)</li>- </ul>- </div>- );- }-- async function handleContainerAction(containerId, action) {- try {- let result;- if (action === 'start') {- result = await api.startRemoteContainer(serverId, containerId);- toast.success('Container started');- } else if (action === 'stop') {- result = await api.stopRemoteContainer(serverId, containerId);- toast.success('Container stopped');- } else if (action === 'restart') {- result = await api.restartRemoteContainer(serverId, containerId);- toast.success('Container restarted');- } else if (action === 'remove') {- const removeConfirmed = await confirmDocker({ title: 'Remove Container', message: 'Remove this container?' });- if (!removeConfirmed) return;- result = await api.removeRemoteContainer(serverId, containerId, true);- toast.success('Container removed');- }- loadDockerData();- } catch (err) {- toast.error(err.message || `Failed to ${action} container`);- }- }-- if (serverStatus !== 'online') {- return (- <div className="offline-notice">- <OfflineIcon />- <h4>Server Offline</h4>- <p>Docker management requires the server to be online.</p>- </div>- );- }-- if (loading) {- return <EmptyState loading title="Loading Docker data" />;- }-- return (- <div className="docker-tab">- {loadError && (- <div className="docker-tab__error">- <strong>Couldn't load Docker data:</strong> {loadError}- <Button size="sm" variant="outline" onClick={loadDockerData}>Retry</Button>- </div>- )}- <div className="docker-sub-tabs">- <button- className={`sub-tab ${subTab === 'containers' ? 'active' : ''}`}- onClick={() => setSubTab('containers')}- >- Containers ({containers.length})- </button>- <button- className={`sub-tab ${subTab === 'images' ? 'active' : ''}`}- onClick={() => setSubTab('images')}- >- Images ({images.length})- </button>- </div>-- {subTab === 'containers' && (- <div className="containers-list">- {containers.length === 0 ? (- <EmptyState icon={Container} title="No containers" description="No containers are running on this server." />- ) : (- <table className="data-table">- <thead>- <tr>- <th>Name</th>- <th>Image</th>- <th>Status</th>- <th>Ports</th>- <th>Actions</th>- </tr>- </thead>- <tbody>- {containers.map(container => {- const isRunning = container.state === 'running';- return (- <tr key={container.id}>- <td>- <span className="container-name">{container.name}</span>- <span className="container-id">{container.id?.substring(0, 12)}</span>- </td>- <td>{container.image}</td>- <td>- <Pill kind={isRunning ? 'green' : container.state === 'paused' || container.state === 'restarting' ? 'amber' : 'gray'}>- {container.state}- </Pill>- </td>- <td>{formatPorts(container.ports)}</td>- <td className="actions-cell">- {isRunning ? (- <>- <button- className="btn-icon"- onClick={() => handleContainerAction(container.id, 'restart')}- title="Restart"- >- <RefreshIcon />- </button>- <button- className="btn-icon danger"- onClick={() => handleContainerAction(container.id, 'stop')}- title="Stop"- >- <StopIcon />- </button>- </>- ) : (- <>- <button- className="btn-icon success"- onClick={() => handleContainerAction(container.id, 'start')}- title="Start"- >- <PlayIcon />- </button>- <button- className="btn-icon danger"- onClick={() => handleContainerAction(container.id, 'remove')}- title="Remove"- >- <TrashIcon />- </button>- </>- )}- </td>- </tr>- );- })}- </tbody>- </table>- )}- </div>- )}-- {subTab === 'images' && (- <div className="images-list">- {images.length === 0 ? (- <EmptyState icon={Boxes} title="No images" description="No Docker images are present on this server." />- ) : (- <table className="data-table">- <thead>- <tr>- <th>Repository</th>- <th>Tag</th>- <th>Image ID</th>- <th>Size</th>- <th>Created</th>- </tr>- </thead>- <tbody>- {images.map(image => (- <tr key={image.id}>- <td>{image.repository || '<none>'}</td>- <td>{image.tag || '<none>'}</td>- <td className="mono">{image.id?.substring(0, 12)}</td>- <td>{image.size}</td>- <td>{image.created}</td>- </tr>- ))}- </tbody>- </table>- )}- </div>- )}- </div>- );-};--const PRESET_LABELS = {- '* * * * *': 'Every minute',- '*/5 * * * *': 'Every 5 minutes',- '*/15 * * * *': 'Every 15 minutes',- '*/30 * * * *': 'Every 30 minutes',- '0 * * * *': 'Hourly',- '0 0 * * *': 'Daily at midnight',- '0 12 * * *': 'Daily at noon',- '0 0 * * 0': 'Weekly (Sunday)',- '0 0 1 * *': 'Monthly (1st)',-};--const CronTab = ({ serverId, serverStatus }) => {- const toast = useToast();- const { confirm: confirmCron } = useConfirm();- const [status, setStatus] = useState(null);- const [jobs, setJobs] = useState([]);- const [loading, setLoading] = useState(true);- const [error, setError] = useState(null);-- const [showAddModal, setShowAddModal] = useState(false);- const [submitting, setSubmitting] = useState(false);- const [form, setForm] = useState({- name: '',- schedule: '0 * * * *',- command: '',- });-- const loadJobs = useCallback(async () => {- try {- const data = await api.getRemoteCronJobs(serverId);- setJobs(data?.jobs || []);- setError(null);- } catch (err) {- setError(err.message || 'Failed to load cron jobs');- }- }, [serverId]);-- const loadStatus = useCallback(async () => {- try {- const s = await api.getRemoteCronStatus(serverId);- setStatus(s);- } catch (err) {- // Non-critical — log but don't block the table.- console.error('Failed to load cron status:', err);- }- }, [serverId]);-- useEffect(() => {- if (serverStatus !== 'online') {- setLoading(false);- return;- }- let cancelled = false;- (async () => {- setLoading(true);- await Promise.all([loadJobs(), loadStatus()]);- if (!cancelled) setLoading(false);- })();- return () => { cancelled = true; };- }, [serverStatus, loadJobs, loadStatus]);-- async function handleToggle(job) {- try {- await api.toggleRemoteCronJob(serverId, job.id, !job.enabled);- toast.success(`Job ${!job.enabled ? 'enabled' : 'disabled'}`);- loadJobs();- } catch (err) {- toast.error(err.message || 'Failed to toggle job');- }- }-- async function handleRemove(job) {- const ok = await confirmCron({- title: 'Remove Cron Job',- message: `Remove this entry from the host crontab?\n\n${job.schedule} ${job.command}`,- variant: 'danger',- });- if (!ok) return;- try {- await api.removeRemoteCronJob(serverId, job.id);- toast.success('Cron job removed');- loadJobs();- } catch (err) {- toast.error(err.message || 'Failed to remove job');- }- }-- async function handleSubmit(e) {- e.preventDefault();- if (!form.command.trim()) {- toast.error('Command is required');- return;- }- if (!form.schedule.trim()) {- toast.error('Schedule is required');- return;- }- setSubmitting(true);- try {- await api.addRemoteCronJob(serverId, {- name: form.name.trim(),- schedule: form.schedule.trim(),- command: form.command.trim(),- });- toast.success('Cron job added');- setShowAddModal(false);- setForm({ name: '', schedule: '0 * * * *', command: '' });- loadJobs();- } catch (err) {- toast.error(err.message || 'Failed to add cron job');- } finally {- setSubmitting(false);- }- }-- if (serverStatus !== 'online') {- return (- <div className="offline-notice">- <OfflineIcon />- <h4>Server Offline</h4>- <p>Cron management requires the server to be online.</p>- </div>- );- }-- if (loading) {- return <EmptyState loading title="Loading cron jobs" />;- }-- return (- <div className="cron-tab">- <div className="cron-tab__header">- <div className="cron-tab__status">- {status?.available === false ? (- <Pill kind="amber">cron not available: {status.reason || 'unknown'}</Pill>- ) : status?.running === false ? (- <Pill kind="amber">cron daemon not running</Pill>- ) : (- <Pill kind="green">cron daemon active{status?.daemon ? ` (${status.daemon})` : ''}</Pill>- )}- <span className="cron-tab__count">{jobs.length} job{jobs.length === 1 ? '' : 's'}</span>- </div>- <div className="cron-tab__actions">- <Button variant="outline" onClick={loadJobs}>Refresh</Button>- <Button onClick={() => setShowAddModal(true)} disabled={status?.available === false}>- Add Job- </Button>- </div>- </div>-- {error && (- <div className="alert alert-danger">{error}</div>- )}-- {jobs.length === 0 ? (- <EmptyState- icon={Clock3}- title="No cron jobs"- description="No scheduled jobs on this server. Use Add Job to schedule one."- />- ) : (- <table className="data-table">- <thead>- <tr>- <th>Schedule</th>- <th>Command</th>- <th>Status</th>- <th className="actions-cell">Actions</th>- </tr>- </thead>- <tbody>- {jobs.map(job => (- <tr key={job.id} className={!job.enabled ? 'row-disabled' : ''}>- <td>- <span className="mono" title={job.schedule}>{job.schedule}</span>- {job.description && job.description !== job.schedule && (- <div className="cron-tab__description">{job.description}</div>- )}- </td>- <td>- {job.name && <div className="cron-tab__name">{job.name}</div>}- <code className="cron-tab__command">{job.command}</code>- </td>- <td>- <Pill kind={job.enabled ? 'green' : 'gray'}>- {job.enabled ? 'enabled' : 'disabled'}- </Pill>- </td>- <td className="actions-cell">- <button- className="btn-icon"- onClick={() => handleToggle(job)}- title={job.enabled ? 'Disable' : 'Enable'}- >- {job.enabled ? <StopIcon /> : <PlayIcon />}- </button>- <button- className="btn-icon danger"- onClick={() => handleRemove(job)}- title="Remove"- >- <TrashIcon />- </button>- </td>- </tr>- ))}- </tbody>- </table>- )}-- <Dialog- open={showAddModal}- onOpenChange={(open) => { if (!open && !submitting) setShowAddModal(false); }}- >- <DialogContent>- <DialogHeader>- <DialogTitle>Add Cron Job</DialogTitle>- <DialogDescription>- Schedule a command on the host crontab. Runs as the agent user.- </DialogDescription>- </DialogHeader>- <form onSubmit={handleSubmit} className="space-y-4">- <div className="space-y-1.5">- <Label htmlFor="cron-name">Name (optional)</Label>- <Input- id="cron-name"- value={form.name}- onChange={(e) => setForm({ ...form, name: e.target.value })}- placeholder="Backup database"- />- </div>- <div className="space-y-1.5">- <Label htmlFor="cron-schedule">Schedule</Label>- <Select- value={Object.keys(PRESET_LABELS).includes(form.schedule) ? form.schedule : 'custom'}- onValueChange={(value) => {- if (value === 'custom') return;- setForm({ ...form, schedule: value });- }}- >- <SelectTrigger>- <SelectValue />- </SelectTrigger>- <SelectContent>- {Object.entries(PRESET_LABELS).map(([cron, label]) => (- <SelectItem key={cron} value={cron}>{label} — {cron}</SelectItem>- ))}- <SelectItem value="custom">Custom…</SelectItem>- </SelectContent>- </Select>- <Input- id="cron-schedule"- value={form.schedule}- onChange={(e) => setForm({ ...form, schedule: e.target.value })}- placeholder="* * * * *"- className="font-mono"- />- <p className="text-xs text-muted-foreground">5 fields: minute, hour, day, month, weekday.</p>- </div>- <div className="space-y-1.5">- <Label htmlFor="cron-command">Command</Label>- <Textarea- id="cron-command"- rows={3}- value={form.command}- onChange={(e) => setForm({ ...form, command: e.target.value })}- placeholder="/usr/local/bin/my-script.sh"- required- />- <p className="text-xs text-muted-foreground">Absolute path. Shell operators (;, &&, |, $(), >, <) are not allowed.</p>- </div>- <DialogFooter>- <Button type="button" variant="outline" onClick={() => setShowAddModal(false)} disabled={submitting}>Cancel</Button>- <Button type="submit" disabled={submitting}>{submitting ? 'Adding…' : 'Add Job'}</Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>- </div>- );-};--// CloudflaredTab — manage Cloudflare named tunnels via the agent.-//-// Auth model: the user runs `cloudflared tunnel login` once on the-// server. That writes ~/.cloudflared/cert.pem (or-// /etc/cloudflared/cert.pem when run as root). The panel never sees-// a Cloudflare API token — every action shells out to cloudflared-// using that cert. /status surfaces both "binary present" and-// "cert present" so we can show "log in first" before users hit-// CRUD actions and get confusing errors back.-const CloudflaredTab = ({ serverId, serverStatus }) => {- const toast = useToast();- const { confirm: confirmCf } = useConfirm();- const [status, setStatus] = useState(null);- const [tunnels, setTunnels] = useState([]);- const [loading, setLoading] = useState(true);- const [error, setError] = useState(null);-- const [showCreateModal, setShowCreateModal] = useState(false);- const [createName, setCreateName] = useState('');- const [creating, setCreating] = useState(false);-- const [showRouteModal, setShowRouteModal] = useState(false);- const [routeTunnel, setRouteTunnel] = useState(null);- const [routeHostname, setRouteHostname] = useState('');- const [routing, setRouting] = useState(false);-- // Login flow: { channel, authUrl, status: 'starting'|'awaiting'|'done'|'error', error, certPath }- const [login, setLogin] = useState(null);-- const loadStatus = useCallback(async () => {- try {- const s = await api.getRemoteCloudflaredStatus(serverId);- setStatus(s);- } catch (err) {- console.error('Failed to load cloudflared status:', err);- }- }, [serverId]);-- const loadTunnels = useCallback(async () => {- try {- const data = await api.getRemoteCloudflaredTunnels(serverId);- setTunnels(data?.tunnels || []);- setError(null);- } catch (err) {- // Auth errors here are common when the user hasn't logged- // in yet — the status banner already explains; don't show- // a redundant scary alert.- setError(err.message || 'Failed to load tunnels');- }- }, [serverId]);-- useEffect(() => {- if (serverStatus !== 'online') {- setLoading(false);- return;- }- let cancelled = false;- (async () => {- setLoading(true);- await loadStatus();- await loadTunnels();- if (!cancelled) setLoading(false);- })();- return () => { cancelled = true; };- }, [serverStatus, loadStatus, loadTunnels]);-- async function handleCreate(e) {- e.preventDefault();- const name = createName.trim();- if (!name) {- toast.error('Name is required');- return;- }- setCreating(true);- try {- await api.createRemoteCloudflaredTunnel(serverId, name);- toast.success(`Tunnel "${name}" created`);- setShowCreateModal(false);- setCreateName('');- loadTunnels();- } catch (err) {- toast.error(err.message || 'Failed to create tunnel');- } finally {- setCreating(false);- }- }-- async function handleRoute(e) {- e.preventDefault();- const hostname = routeHostname.trim();- if (!hostname || !routeTunnel) return;- setRouting(true);- try {- await api.routeRemoteCloudflaredTunnel(serverId, routeTunnel.id || routeTunnel.name, hostname);- toast.success(`${hostname} → ${routeTunnel.name}`);- setShowRouteModal(false);- setRouteHostname('');- setRouteTunnel(null);- } catch (err) {- toast.error(err.message || 'Failed to add route');- } finally {- setRouting(false);- }- }-- async function handleDelete(tunnel) {- const ok = await confirmCf({- title: 'Delete Tunnel',- message: `Delete tunnel "${tunnel.name}"? Active connections will be force-closed.`,- variant: 'danger',- });- if (!ok) return;- try {- await api.deleteRemoteCloudflaredTunnel(serverId, tunnel.id || tunnel.name);- toast.success('Tunnel deleted');- loadTunnels();- } catch (err) {- toast.error(err.message || 'Failed to delete tunnel');- }- }-- // Triggers `cloudflared tunnel login` on the agent and subscribes- // to the streaming auth flow. The first event carries the auth URL- // we surface as a clickable button; the final event flips us back- // to ready state once cert.pem appears.- async function handleStartLogin() {- try {- const res = await api.startRemoteCloudflaredLogin(serverId);- const channel = res?.channel || `job:${res?.job_id}`;- setLogin({ channel, status: 'starting', authUrl: null, error: null, certPath: null });-- // Reuse the live socket service to subscribe to the- // server_stream room. We don't open the JobProgressModal- // because the login flow needs a different shape (a single- // big "Open URL" CTA, not a log tail).- const { default: socketService } = await import('../services/socket');- if (!socketService.socket) socketService.connect();- const sock = socketService.socket;- if (!sock) {- setLogin(null);- toast.error('Socket not available');- return;- }- const room = `server_${serverId}_${channel}`;- const onStream = (msg) => {- if (msg?.channel !== channel) return;- const ev = msg.data || {};- const url = ev?.extra?.auth_url;- if (url) {- setLogin((cur) => cur ? { ...cur, status: 'awaiting', authUrl: url } : cur);- }- if (ev.phase === 'done') {- if (ev.error) {- setLogin((cur) => cur ? { ...cur, status: 'error', error: ev.error } : cur);- toast.error(`Login failed: ${ev.error}`);- } else {- setLogin((cur) => cur ? { ...cur, status: 'done', certPath: ev?.extra?.cert_path } : cur);- toast.success('Cloudflare login complete');- // Refresh capabilities + status so the tab unlocks- // without a manual reload.- api.refreshRemoteCapabilities(serverId).catch(() => {});- loadStatus();- loadTunnels();- }- sock.off('server_stream', onStream);- sock.emit('leave_room', { room });- }- };- sock.emit('join_room', { room });- sock.on('server_stream', onStream);- } catch (err) {- toast.error(err.message || 'Failed to start login');- setLogin(null);- }- }-- function handleCancelLogin() {- setLogin(null);- }-- if (serverStatus !== 'online') {- return (- <div className="offline-notice">- <OfflineIcon />- <h4>Server Offline</h4>- <p>Tunnel management requires the server to be online.</p>- </div>- );- }-- if (loading) {- return <EmptyState loading title="Loading tunnels" />;- }-- // Status banner — three distinct states the UI cares about:- // 1. binary missing → "install cloudflared"- // 2. binary, no cert → "log in once"- // 3. binary + cert → ready to manage tunnels- const notInstalled = status?.available === false;- const notAuthed = status?.available && status?.authenticated === false;-- return (- <div className="cloudflared-tab">- <div className="cron-tab__header">- <div className="cron-tab__status">- {notInstalled ? (- <Pill kind="amber">cloudflared not installed</Pill>- ) : notAuthed ? (- <Pill kind="amber">not authenticated — run cloudflared tunnel login</Pill>- ) : (- <Pill kind="green">cloudflared ready{status?.version ? ` (${status.version})` : ''}</Pill>- )}- <span className="cron-tab__count">{tunnels.length} tunnel{tunnels.length === 1 ? '' : 's'}</span>- </div>- <div className="cron-tab__actions">- <Button variant="outline" onClick={loadTunnels} disabled={notInstalled}>Refresh</Button>- <Button onClick={() => setShowCreateModal(true)} disabled={notInstalled || notAuthed}>- Create Tunnel- </Button>- </div>- </div>-- {(notInstalled || notAuthed) && (- <div className="cloudflared-tab__hint">- {notInstalled ? (- <>- Install cloudflared on the server, then return here. See the{' '}- <a href="https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/get-started/" target="_blank" rel="noreferrer">- Cloudflare docs- </a>.- </>- ) : login ? (- <CloudflaredLoginCard login={login} onCancel={handleCancelLogin} />- ) : (- <div className="cloudflared-login-prompt">- <p>- Cloudflare needs you to authorise this agent once. Click{' '}- <strong>Login</strong> below — we'll start the OAuth flow on the- server and surface the URL for you to open in your browser. Once you- authorise, the agent picks up the cert.pem automatically and the- rest of this tab unlocks.- </p>- <Button onClick={handleStartLogin}>Login to Cloudflare</Button>- </div>- )}- </div>- )}-- {error && !notAuthed && !notInstalled && (- <div className="alert alert-danger">{error}</div>- )}-- {!notInstalled && !notAuthed && (- tunnels.length === 0 ? (- <EmptyState- icon={Cloud}- title="No tunnels"- description="No tunnels on this server. Use Create Tunnel to make one."- />- ) : (- <table className="data-table">- <thead>- <tr>- <th>Name</th>- <th>ID</th>- <th>Connections</th>- <th className="actions-cell">Actions</th>- </tr>- </thead>- <tbody>- {tunnels.map(t => (- <tr key={t.id || t.name}>- <td><span className="cron-tab__name">{t.name}</span></td>- <td className="mono">{(t.id || '').substring(0, 8)}…</td>- <td>{t.connections?.length || 0}</td>- <td className="actions-cell">- <Button- size="sm"- variant="outline"- onClick={() => { setRouteTunnel(t); setShowRouteModal(true); }}- >- Route subdomain- </Button>- <button- className="btn-icon danger"- onClick={() => handleDelete(t)}- title="Delete"- >- <TrashIcon />- </button>- </td>- </tr>- ))}- </tbody>- </table>- )- )}-- <Dialog- open={showCreateModal}- onOpenChange={(open) => { if (!open && !creating) setShowCreateModal(false); }}- >- <DialogContent>- <DialogHeader>- <DialogTitle>Create Tunnel</DialogTitle>- <DialogDescription>- Provisions a new Cloudflare Tunnel on this server.- </DialogDescription>- </DialogHeader>- <form onSubmit={handleCreate} className="space-y-4">- <div className="space-y-1.5">- <Label htmlFor="cf-name">Tunnel Name</Label>- <Input- id="cf-name"- value={createName}- onChange={(e) => setCreateName(e.target.value)}- placeholder="my-app"- required- autoFocus- />- <p className="text-xs text-muted-foreground">Letters, numbers, dashes, underscores. Up to 32 chars.</p>- </div>- <DialogFooter>- <Button type="button" variant="outline" onClick={() => setShowCreateModal(false)} disabled={creating}>Cancel</Button>- <Button type="submit" disabled={creating}>{creating ? 'Creating…' : 'Create'}</Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>-- <Dialog- open={showRouteModal && !!routeTunnel}- onOpenChange={(open) => { if (!open && !routing) setShowRouteModal(false); }}- >- <DialogContent>- <DialogHeader>- <DialogTitle>Route Subdomain{routeTunnel ? ` → ${routeTunnel.name}` : ''}</DialogTitle>- <DialogDescription>- A CNAME for this hostname will be created in Cloudflare DNS, pointing at the tunnel.- </DialogDescription>- </DialogHeader>- <form onSubmit={handleRoute} className="space-y-4">- <div className="space-y-1.5">- <Label htmlFor="cf-host">Hostname</Label>- <Input- id="cf-host"- value={routeHostname}- onChange={(e) => setRouteHostname(e.target.value)}- placeholder="app.example.com"- required- autoFocus- />- </div>- <DialogFooter>- <Button type="button" variant="outline" onClick={() => setShowRouteModal(false)} disabled={routing}>Cancel</Button>- <Button type="submit" disabled={routing}>{routing ? 'Adding…' : 'Add Route'}</Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>- </div>- );-};--// CloudflaredLoginCard renders the in-flight OAuth login state. The-// agent has spawned `cloudflared tunnel login` on the server and is-// streaming progress on a job channel; we render either a spinner-// (while we wait for the URL), the Open-in-Browser CTA (once the URL-// arrives), or a final success/error message.-const CloudflaredLoginCard = ({ login, onCancel }) => {- if (!login) return null;- if (login.status === 'starting') {- return (- <div className="cloudflared-login-card">- <p>Asking the agent to start the Cloudflare login flow…</p>- <Button variant="outline" size="sm" onClick={onCancel}>Cancel</Button>- </div>- );- }- if (login.status === 'awaiting' && login.authUrl) {- return (- <div className="cloudflared-login-card">- <p>- <strong>Step 1 / 2:</strong> open the following URL in your browser, sign in- to Cloudflare, and pick the zone you want to associate with this agent.- </p>- <div className="cloudflared-login-card__actions">- <a- href={login.authUrl}- target="_blank"- rel="noreferrer"- className="btn btn-primary"- >- Open Cloudflare login- </a>- <button- type="button"- className="btn btn-outline"- onClick={() => navigator.clipboard?.writeText(login.authUrl)}- >- Copy URL- </button>- </div>- <p className="cloudflared-login-card__hint">- <strong>Step 2 / 2:</strong> waiting for the agent to receive cert.pem from- Cloudflare. This page will refresh automatically once authorisation completes.- </p>- <Button variant="outline" size="sm" onClick={onCancel}>Cancel</Button>- </div>- );- }- if (login.status === 'done') {- return (- <div className="cloudflared-login-card cloudflared-login-card--success">- Authenticated. Refreshing…- </div>- );- }- if (login.status === 'error') {- return (- <div className="cloudflared-login-card cloudflared-login-card--error">- <strong>Login failed:</strong> {login.error || 'unknown error'}- <Button variant="outline" size="sm" onClick={onCancel}>Dismiss</Button>- </div>- );- }- return null;-};--const MetricsTab = ({ serverId, metrics }) => {- return (- <div className="metrics-tab">- <MetricsGraph serverId={serverId} />-- {metrics && (- <div className="metrics-live-stats">- <div className="live-stat-card">- <h4>Current Snapshot</h4>- <div className="live-stats-grid">- <div className="live-stat">- <span className="live-stat-label">CPU</span>- <span className="live-stat-value">{(metrics.cpu_percent || 0).toFixed(1)}%</span>- </div>- <div className="live-stat">- <span className="live-stat-label">Memory</span>- <span className="live-stat-value">{(metrics.memory_percent || 0).toFixed(1)}%</span>- </div>- <div className="live-stat">- <span className="live-stat-label">Disk</span>- <span className="live-stat-value">{(metrics.disk_percent || 0).toFixed(1)}%</span>- </div>- <div className="live-stat">- <span className="live-stat-label">Net TX</span>- <span className="live-stat-value">{formatBytes(metrics.network_sent, { defaultValue: 'N/A' })}/s</span>- </div>- <div className="live-stat">- <span className="live-stat-label">Net RX</span>- <span className="live-stat-value">{formatBytes(metrics.network_recv, { defaultValue: 'N/A' })}/s</span>- </div>- <div className="live-stat">- <span className="live-stat-label">Containers</span>- <span className="live-stat-value">{metrics.container_running || 0} / {metrics.container_count || 0}</span>- </div>- </div>- </div>- </div>- )}- </div>- );-};---const AgentRegistrationSection = ({ server, onRegenerateToken }) => {- const expires = server.registration_expires;- const isExpired = expires && new Date(expires) < new Date();- const isOnline = server.status === 'online';-- return (- <div className="form-section form-section--accent">- <div className="form-section__header">- <span className="form-section__icon"><KeyIcon /></span>- <div>- <h3>Connection String</h3>- <p className="section-description">- Generate a fresh connection string to pair (or re-pair) this server.- Useful after reinstalling the agent — old credentials are gone, but a- new string brings the agent right back to this row.- {isOnline && ' This server is currently online; regenerating only affects re-pairing.'}- {isExpired && ' The previous token has expired.'}- </p>- </div>- </div>- <Button onClick={onRegenerateToken}>- <KeyIcon /> Generate Connection String- </Button>- </div>- );-};--const SettingsTab = ({ server, onUpdate, onRegenerateToken, onDelete }) => {- const { confirm: confirmSettings } = useConfirm();- const [formData, setFormData] = useState({- name: server.name || '',- description: server.description || '',- hostname: server.hostname || '',- ip_address: server.ip_address || '',- group_id: server.group_id || ''- });- const [groups, setGroups] = useState([]);- const [loading, setLoading] = useState(false);- const [allowedIPs, setAllowedIPs] = useState([]);- const [newIP, setNewIP] = useState('');- const [connectionInfo, setConnectionInfo] = useState(null);- const [rotatingKey, setRotatingKey] = useState(false);- const toast = useToast();-- useEffect(() => {- loadGroups();- loadSecurityData();- }, []);-- async function loadGroups() {- try {- const data = await api.getServerGroups();- setGroups(Array.isArray(data) ? data : []);- } catch (err) {- console.error('Failed to load groups:', err);- }- }-- async function loadSecurityData() {- try {- const [ipsData, connData] = await Promise.all([- api.getAllowedIPs(server.id),- api.getConnectionInfo(server.id),- ]);- setAllowedIPs(ipsData.allowed_ips || []);- setConnectionInfo(connData);- } catch (err) {- console.error('Failed to load security data:', err);- }- }-- async function handleAddIP() {- if (!newIP.trim()) return;- const updated = [...allowedIPs, newIP.trim()];- try {- await api.updateAllowedIPs(server.id, updated);- setAllowedIPs(updated);- setNewIP('');- toast.success('IP allowlist updated');- } catch (err) {- toast.error(err.details?.[0] || err.message || 'Invalid IP pattern');- }- }-- async function handleRemoveIP(ip) {- const updated = allowedIPs.filter(i => i !== ip);- try {- await api.updateAllowedIPs(server.id, updated);- setAllowedIPs(updated);- toast.success('IP removed from allowlist');- } catch (err) {- toast.error(err.message || 'Failed to update allowlist');- }- }-- async function handleRotateKey() {- const confirmed = await confirmSettings({ title: 'Rotate Credentials', message: 'Rotate API credentials? The agent must be online to receive new credentials.', variant: 'warning' });- if (!confirmed) return;- setRotatingKey(true);- try {- const result = await api.rotateAPIKey(server.id);- if (result.success) {- toast.success('Credential rotation initiated. Agent will update shortly.');- } else {- toast.error(result.error || 'Failed to rotate credentials');- }- } catch (err) {- toast.error(err.message || 'Failed to rotate credentials');- } finally {- setRotatingKey(false);- }- }-- async function handleSubmit(e) {- e.preventDefault();- setLoading(true);-- try {- await api.updateServer(server.id, formData);- toast.success('Server updated successfully');- onUpdate();- } catch (err) {- toast.error(err.message || 'Failed to update server');- } finally {- setLoading(false);- }- }-- function handleChange(e) {- const { name, value } = e.target;- setFormData(prev => ({ ...prev, [name]: value }));- }-- return (- <div className="settings-tab">- <div className="settings-grid">- <form onSubmit={handleSubmit} className="settings-form">- <div className="form-section form-section--accent">- <div className="form-section__header">- <span className="form-section__icon"><ServerIcon /></span>- <div>- <h3>Basic Information</h3>- <p className="section-description">Identity and grouping for this server.</p>- </div>- </div>- <div className="form-group">- <label>Server 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}- rows={3}- />- </div>-- <div className="form-row">- <div className="form-group">- <label>Hostname</label>- <Input- type="text"- name="hostname"- value={formData.hostname}- onChange={handleChange}- />- </div>- <div className="form-group">- <label>IP Address</label>- <Input- type="text"- name="ip_address"- value={formData.ip_address}- onChange={handleChange}- />- </div>- </div>-- <div className="form-group">- <label>Group</label>- <select name="group_id" value={formData.group_id} onChange={handleChange}>- <option value="">No Group</option>- {groups.map(group => (- <option key={group.id} value={group.id}>{group.name}</option>- ))}- </select>- </div>-- <Button type="submit" disabled={loading}>- {loading ? 'Saving...' : 'Save Changes'}- </Button>- </div>- </form>-- <AgentRegistrationSection- server={server}- onRegenerateToken={onRegenerateToken}- />- </div>-- <div className="security-grid">- <div className="form-section form-section--accent">- <div className="form-section__header">- <span className="form-section__icon"><NetworkIcon /></span>- <div>- <h3>Connection & IP Allowlist</h3>- <p className="section-description">- Restrict which IPs can connect. Supports single IPs, CIDR notation, and wildcards.- </p>- </div>- </div>-- {connectionInfo && (- <div className="security-info-bar">- <div className="security-info-item">- <span className="security-info-label">Connection IP</span>- <span className="security-info-value">- <code>{connectionInfo.ip_address || 'Not connected'}</code>- </span>- </div>- {connectionInfo.connected_since && (- <div className="security-info-item">- <span className="security-info-label">Connected Since</span>- <span className="security-info-value">{new Date(connectionInfo.connected_since).toLocaleString()}</span>- </div>- )}- </div>- )}-- <div className="subsection">- <div className="ip-list">- {allowedIPs.length === 0 ? (- <div className="ip-empty">No IP restrictions (all IPs allowed)</div>- ) : (- allowedIPs.map((ip, idx) => (- <div key={idx} className="ip-item">- <code>{ip}</code>- {connectionInfo?.ip_address === ip && (- <Pill kind="green" dot={false}>Current</Pill>- )}- <button- className="btn-icon danger"- onClick={() => handleRemoveIP(ip)}- title="Remove"- >- <TrashIcon />- </button>- </div>- ))- )}- </div>-- <div className="ip-add-form">- <Input- type="text"- placeholder="IP address or CIDR (e.g., 192.168.1.0/24)"- value={newIP}- onChange={(e) => setNewIP(e.target.value)}- onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), handleAddIP())}- />- <Button variant="outline" onClick={handleAddIP}>- Add- </Button>- </div>-- {connectionInfo?.ip_address && allowedIPs.length > 0 && !allowedIPs.some(ip => {- return ip === connectionInfo.ip_address || ip.includes('*') || ip.includes('/');- }) && (- <div className="security-warning">- Current connection IP ({connectionInfo.ip_address}) may be blocked by these rules.- </div>- )}- </div>- </div>-- <div className="form-section form-section--accent">- <div className="form-section__header">- <span className="form-section__icon"><KeyIcon /></span>- <div>- <h3>API Key Rotation</h3>- <p className="section-description">- Rotate the API credentials used by the agent. The agent must be online to receive new credentials.- </p>- </div>- </div>- <div className="key-rotation-actions">- <Button- variant="outline"- onClick={handleRotateKey}- disabled={rotatingKey || server.status !== 'online'}- >- <KeyIcon /> {rotatingKey ? 'Rotating...' : 'Rotate API Key'}- </Button>- {server.api_key_last_rotated && (- <span className="key-rotation-hint">Last rotated: {new Date(server.api_key_last_rotated).toLocaleString()}</span>- )}- </div>-- {server.status !== 'online' && (- <div className="security-notice">- Server must be online to rotate credentials.- </div>- )}- </div>- </div>-- <div className="form-section form-section--accent shared-resources-section">- <div className="form-section__header">- <span className="form-section__icon"><TagIcon /></span>- <div>- <h3>Tags</h3>- <p className="section-description">- Free-form labels for grouping and filtering this server across the panel.- </p>- </div>- </div>- <TagsPanel resourceType="server" resourceId={server.id} />- </div>-- <DangerZone- title="Danger Zone"- description="Removing this server will disconnect the agent and delete all associated data."- action={- <Button variant="destructive" onClick={onDelete}>- <TrashIcon /> Remove Server- </Button>- }- />- </div>- );-};---// Token-lifetime presets shown in the regenerate modal. Mirrors the values-// the Add Server modal uses (frontend/src/pages/Servers.jsx). Keep them in-// sync if you tweak either list.-const TOKEN_EXPIRY_OPTIONS = [- { label: '1 hour', value: 60 * 60 },- { label: '24 hours', value: 24 * 60 * 60 },- { label: '7 days', value: 7 * 24 * 60 * 60 },- { label: '30 days', value: 30 * 24 * 60 * 60 },- { label: 'Never', value: -1 },-];--const TokenModal = ({ server, onClose, onGenerated }) => {- const toast = useToast();- const [expiresIn, setExpiresIn] = useState(7 * 24 * 60 * 60);- const [generating, setGenerating] = useState(false);- // Result of the most recent generation in *this* modal session. We- // don't fall back to server.connection_string because the panel only- // ever returns the connection string at create/regenerate time — once- // the modal closes, the value is gone, so showing a stale one would- // be misleading.- const [result, setResult] = useState(null);-- async function handleGenerate() {- setGenerating(true);- try {- const data = await api.generateRegistrationToken(server.id, { expires_in: expiresIn });- setResult(data);- onGenerated?.(data);- toast.success('Connection string generated');- } catch (err) {- toast.error(err.message || 'Failed to generate connection string');- } finally {- setGenerating(false);- }- }-- function copyToClipboard(text) {- navigator.clipboard.writeText(text);- toast.success('Copied to clipboard');- }-- const linuxScript = result ? `curl -fsSL ${window.location.origin}/api/v1/servers/install.sh | sudo bash -s -- \\- --server "${window.location.origin}" \\- --token "${result.registration_token}"` : '';- const windowsScript = result ? `irm ${window.location.origin}/api/v1/servers/install.ps1 | iex-Install-ServerKitAgent -Server "${window.location.origin}" -Token "${result.registration_token}"` : '';-- return (- <Dialog open onOpenChange={(open) => { if (!open) onClose(); }}>- <DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">- <DialogHeader>- <DialogTitle>Connection String</DialogTitle>- {!result && (- <DialogDescription>- Generate a single pasteable string the agent can consume.- The token inside is single-use — burned the moment any- agent registers with it.- </DialogDescription>- )}- </DialogHeader>-- {!result ? (- <>- <div className="space-y-2">- <Label htmlFor="token-expires">Token expires</Label>- <Select value={String(expiresIn)} onValueChange={(v) => setExpiresIn(Number(v))}>- <SelectTrigger id="token-expires">- <SelectValue />- </SelectTrigger>- <SelectContent>- {TOKEN_EXPIRY_OPTIONS.map(opt => (- <SelectItem key={opt.value} value={String(opt.value)}>{opt.label}</SelectItem>- ))}- </SelectContent>- </Select>- </div>-- <DialogFooter>- <Button variant="outline" onClick={onClose}>Cancel</Button>- <Button onClick={handleGenerate} disabled={generating}>- {generating ? 'Generating…' : 'Generate'}- </Button>- </DialogFooter>- </>- ) : (- <>- <div className="token-status">- <span className="token-status-dot active" />- <span>- Active — expires {new Date(result.registration_expires).toLocaleString()}- </span>- </div>-- <div className="connection-string-field">- <div className="connection-string-field__header">- <KeyIcon />- <span>Connection string</span>- <Button variant="outline" size="sm" onClick={() => copyToClipboard(result.connection_string)}>- <CopyIcon /> Copy- </Button>- </div>- <pre className="connection-string-field__value">{result.connection_string}</pre>- </div>-- <details className="install-fallback">- <summary>Need to install the agent first? Use the one-liner installer.</summary>- <div className="install-tabs" style={{ marginTop: '0.75rem' }}>- <div className="install-tab">- <div className="install-tab-header">- <TerminalIcon />- <div className="install-tab-title">- <span>Linux</span>- <span className="install-tab-description">curl, tar, sudo, and systemd</span>- </div>- <Button variant="outline" size="sm" onClick={() => copyToClipboard(linuxScript)}>- <CopyIcon /> Copy- </Button>- </div>- <pre className="install-script">{linuxScript}</pre>- </div>- <div className="install-tab">- <div className="install-tab-header">- <WindowsIcon />- <div className="install-tab-title">- <span>Windows (PowerShell)</span>- <span className="install-tab-description">Run as Administrator</span>- </div>- <Button variant="outline" size="sm" onClick={() => copyToClipboard(windowsScript)}>- <CopyIcon /> Copy- </Button>- </div>- <pre className="install-script">{windowsScript}</pre>- </div>- </div>- </details>-- <DialogFooter>- <Button variant="outline" onClick={() => setResult(null)}>- Generate another- </Button>- <Button onClick={onClose}>Done</Button>- </DialogFooter>- </>- )}- </DialogContent>- </Dialog>- );-};--const CopyChip = ({ label, value, title, mono }) => {- const toast = useToast();- const handleCopy = (e) => {- e.preventDefault();- e.stopPropagation();- if (!value) return;- navigator.clipboard.writeText(value);- toast.success(`${label[0].toUpperCase()}${label.slice(1)} copied`);- };- return (- <button- type="button"- className={`copy-chip${mono ? ' copy-chip--mono' : ''}`}- onClick={handleCopy}- title={title || `Copy ${label}`}- >- <span className="copy-chip__label">{label}</span>- <code className="copy-chip__value">{value}</code>- <CopyIcon />- </button>- );-};--// Icons-const FolderTinyIcon = () => (- <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">- <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>- </svg>-);--const RefreshIcon = () => (- <svg width="16" height="16" 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>-);--const TrashIcon = () => (- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <polyline points="3 6 5 6 21 6"/>- <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>- </svg>-);--const KeyIcon = () => (- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/>- </svg>-);--const OfflineIcon = () => (- <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">- <line x1="1" y1="1" x2="23" y2="23"/>- <path d="M16.72 11.06A10.94 10.94 0 0 1 19 12.55"/>- <path d="M5 12.55a10.94 10.94 0 0 1 5.17-2.39"/>- <path d="M10.71 5.05A16 16 0 0 1 22.58 9"/>- <path d="M1.42 9a15.91 15.91 0 0 1 4.7-2.88"/>- <path d="M8.53 16.11a6 6 0 0 1 6.95 0"/>- <line x1="12" y1="20" x2="12.01" y2="20"/>- </svg>-);--const StopIcon = () => (- <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">- <rect x="6" y="6" width="12" height="12"/>- </svg>-);--const PlayIcon = () => (- <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">- <polygon points="5 3 19 12 5 21 5 3"/>- </svg>-);--const TerminalIcon = () => (- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <polyline points="4 17 10 11 4 5"/>- <line x1="12" y1="19" x2="20" y2="19"/>- </svg>-);--const CopyIcon = () => (- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>- <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>- </svg>-);--const WindowsIcon = () => (- <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">- <path d="M0 3.449L9.75 2.1v9.451H0m10.949-9.602L24 0v11.4H10.949M0 12.6h9.75v9.451L0 20.699M10.949 12.6H24V24l-12.9-1.801"/>- </svg>-);--const CpuIcon = () => (- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <rect x="4" y="4" width="16" height="16" rx="2"/>- <rect x="9" y="9" width="6" height="6"/>- <line x1="9" y1="2" x2="9" y2="4"/><line x1="15" y1="2" x2="15" y2="4"/>- <line x1="9" y1="20" x2="9" y2="22"/><line x1="15" y1="20" x2="15" y2="22"/>- <line x1="20" y1="9" x2="22" y2="9"/><line x1="20" y1="14" x2="22" y2="14"/>- <line x1="2" y1="9" x2="4" y2="9"/><line x1="2" y1="14" x2="4" y2="14"/>- </svg>-);--const MemoryIcon = () => (- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <rect x="2" y="7" width="20" height="10" rx="2"/>- <line x1="6" y1="7" x2="6" y2="17"/>- <line x1="10" y1="7" x2="10" y2="17"/>- <line x1="14" y1="7" x2="14" y2="17"/>- <line x1="18" y1="7" x2="18" y2="17"/>- </svg>-);--const DiskIcon = () => (- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <ellipse cx="12" cy="5" rx="9" ry="3"/>- <path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/>- <path d="M3 12c0 1.66 4 3 9 3s9-1.34 9-3"/>- </svg>-);--const ClockIcon = () => (- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <circle cx="12" cy="12" r="10"/>- <polyline points="12 6 12 12 16 14"/>- </svg>-);--const NetworkIcon = () => (- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <circle cx="12" cy="12" r="10"/>- <line x1="2" y1="12" x2="22" y2="12"/>- <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"/>- </svg>-);--const ServerIcon = () => (- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <rect x="2" y="3" width="20" height="7" rx="1"/>- <rect x="2" y="14" width="20" height="7" rx="1"/>- <line x1="6" y1="6.5" x2="6.01" y2="6.5"/>- <line x1="6" y1="17.5" x2="6.01" y2="17.5"/>- </svg>-);--const HostIcon = () => (- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>- <polyline points="9 22 9 12 15 12 15 22"/>- </svg>-);--const OsIcon = () => (- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <rect x="2" y="3" width="20" height="14" rx="2"/>- <line x1="8" y1="21" x2="16" y2="21"/>- <line x1="12" y1="17" x2="12" y2="21"/>- </svg>-);--const ArchIcon = () => (- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <polyline points="16 18 22 12 16 6"/>- <polyline points="8 6 2 12 8 18"/>- </svg>-);--const ChipIcon = () => (- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <rect x="5" y="5" width="14" height="14" rx="1"/>- <rect x="9" y="9" width="6" height="6"/>- <path d="M3 9h2M3 15h2M19 9h2M19 15h2M9 3v2M15 3v2M9 19v2M15 19v2"/>- </svg>-);--const AgentIcon = () => (- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <path d="M12 2a4 4 0 0 0-4 4v2H6a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2h-2V6a4 4 0 0 0-4-4z"/>- <circle cx="9" cy="14" r="1"/>- <circle cx="15" cy="14" r="1"/>- </svg>-);--const TagIcon = () => (- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/>- <line x1="7" y1="7" x2="7.01" y2="7"/>- </svg>-);--const HashIcon = () => (- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <line x1="4" y1="9" x2="20" y2="9"/>- <line x1="4" y1="15" x2="20" y2="15"/>- <line x1="10" y1="3" x2="8" y2="21"/>- <line x1="16" y1="3" x2="14" y2="21"/>- </svg>-);--const DockerMiniIcon = () => (- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <rect x="3" y="10" width="3" height="3"/>- <rect x="7" y="10" width="3" height="3"/>- <rect x="11" y="10" width="3" height="3"/>- <rect x="7" y="6" width="3" height="3"/>- <rect x="11" y="6" width="3" height="3"/>- <path d="M2 14c0 4 4 6 10 6s10-2 10-6"/>- </svg>-);--const PulseIcon = () => (- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/>- </svg>-);--const AlertIcon = () => (- <svg width="18" height="18" 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>-);--const InfoCircleIcon = () => (- <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <circle cx="12" cy="12" r="10"/>- <line x1="12" y1="16" x2="12" y2="12"/>- <line x1="12" y1="8" x2="12.01" y2="8"/>- </svg>-);-export default ServerDetail;diff --git a/frontend/src/pages/WordPressDetail.jsx b/frontend/src/pages/WordPressDetail.jsxindex 72876d36..857a54a0 100644--- a/frontend/src/pages/WordPressDetail.jsx+++ b/frontend/src/pages/WordPressDetail.jsx@@ -1,224 +1,45 @@-import React, { useState, useEffect } from 'react';+import { 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, Activity, Globe, BarChart3, FileBarChart, Printer, Download, ChevronDown, Check, AlertTriangle, HardDrive, LayoutDashboard, Layers, Shield, ShieldAlert, CircleCheck, CircleX } from 'lucide-react';-import { ResponsiveContainer, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts';+import { Settings, Database, GitBranch, Package, Palette, FolderOpen, FileText, Lock, Activity, Globe, BarChart3, LayoutDashboard, Layers } from 'lucide-react';import useTabParam from '../hooks/useTabParam';import wordpressApi from '../services/wordpress';-import api from '../services/api';import { useToast } from '../contexts/ToastContext';import { useLogsDrawer } from '../contexts/LogsDrawerContext';-import { EnvironmentCard, SnapshotTable, GitConnectForm, CommitList } from '../components/wordpress';-import ProtectionPanel from '../components/backups/ProtectionPanel';-import ActivityFeed from '../components/wordpress/ActivityFeed';import ChangeUrlModal from '../components/wordpress/ChangeUrlModal';import AttachDomainModal from '../components/wordpress/AttachDomainModal';-import { HealthDot } from '../components/wordpress/HealthStatusPanel';-import { Pill, EnvTag, MetricCard, SegControl, ScoreGauge, ServiceTile, PageTopbar } from '../components/ds';-import { ErrorBoundary, ErrorState } from '../components/ErrorBoundary';-import { useConfirm } from '../hooks/useConfirm';-import { DangerZone } from '../components/DangerZone';+import { Pill, EnvTag, PageTopbar } from '../components/ds';+import { ErrorBoundary } from '../components/ErrorBoundary';import EmptyState from '../components/EmptyState';import Modal from '@/components/Modal';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';-import { Switch } from '@/components/ui/switch';import { Label } from '@/components/ui/label';-import { Textarea } from '@/components/ui/textarea';--// 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).-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>-);+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'];-// Environment-type → dot tint for the header environment switcher.-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).-const envTagLabel = (type) => (- type === 'production' ? 'PROD' : type === 'staging' ? 'STAGING' : 'DEV'-);--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).-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).-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>- );-};-const WordPressDetail = () => {const { id } = useParams();const navigate = useNavigate();@@ -629,3355 +450,6 @@ const WordPressDetail = () => {);};-// Friendly labels for the editable php.ini directives (#24 limits panel).-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',-};--// 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 <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>- );-};--// 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 <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>- );-};--// Updates Tab — safe update manager (#29): snapshot -> update -> health-check ->-// auto-rollback, plus a per-site schedule and a run-history report.-const UPDATE_SCHEDULES = [- { label: 'Off', value: '' },- { label: 'Weekly (Sun 3am)', value: '0 3 * * 0' },- { label: 'Daily (3am)', value: '0 3 * * *' },-];--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 <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>- );-};--// 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 <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>- );-};--// 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 <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 && (- <div className="wp-kpis">- <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" />- )}- </div>- )}-- {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>- );-};--// 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 ANALYTICS_PERIODS = [{ label: '24h', hours: 24 }, { label: '7d', hours: 168 }];--const AnalyticsTab = ({ siteId }) => {- const toast = useToast();- const [data, setData] = useState(null);- const [loading, setLoading] = useState(true);- const [hours, setHours] = useState(24);-- 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 <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">- <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>- );-};--// 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 <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'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>- );-};--// 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- className="quick-action-btn"- onClick={() => setShowEnvModal(true)}- >- <Plus size={16} />- Create Environment- </button>- )}- <button- className="quick-action-btn"- onClick={handleQuickSnapshot}- disabled={creatingSnapshot}- >- <Database size={16} />- {creatingSnapshot ? 'Creating...' : 'Create Snapshot'}- </button>- {site.environments?.length > 0 && (- <button- className="quick-action-btn"- onClick={handleSyncAll}- disabled={syncingAll}- >- <RefreshCw size={16} className={syncingAll ? 'spinning' : ''} />- {syncingAll ? 'Syncing...' : 'Sync All Envs'}- </button>- )}- <button- className="quick-action-btn"- onClick={handleFlushCache}- disabled={flushingCache}- >- <Trash2 size={16} />- {flushingCache ? 'Flushing...' : 'Purge Cache'}- </button>- <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- className="quick-action-btn"- onClick={() => setShowSearchReplace(true)}- >- <Replace size={16} />- Search & Replace- </button>- <button- className="quick-action-btn"- onClick={handleHarden}- disabled={hardening}- >- <ShieldCheck size={16} />- {hardening ? 'Hardening...' : 'Harden'}- </button>- <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's parsed from the site'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>- );-};--// SSL Certificate panel — guided one-click SSL that walks the user through the-// prerequisites (public domain, DNS, admin email) and then issues the cert.-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} {rec.name} → {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'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'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>- );-};--// Search & Replace Modal (DB string replacement, guarded by dry-run)-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>- );-};--// Reusable Skeleton Components for Tabs-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>-);--const ListItemSkeleton = () => (- <div className="skeleton" style={{ height: 48, borderRadius: 6, marginBottom: 8 }} />-);--// Generic panel skeleton — matches .app-panel + .app-panel-header + .app-panel-body-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-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>-);--// 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 (- <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-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>- );-};--// 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>- );-};--// 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-- useEffect(() => {- loadPlugins();- }, [siteId]);-- async function loadPlugins() {- setLoading(true);- setError(null);- try {- const data = await wordpressApi.getPlugins(siteId);- setPlugins(data.plugins || []);- } catch (err) {- console.error('Failed to load plugins:', err);- setError(err);- } finally {- setLoading(false);- }- }-- 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 (- <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';- return (- <div className={`wp-asset-card ${isActive ? 'is-active' : ''}`} key={plugin.name}>- <ServiceTile name={plugin.title || plugin.name} size={42} />- <div className="wp-asset-card__body">- <div className="wp-asset-card__name">{plugin.title || plugin.name}</div>- <div className="wp-asset-card__sub">{plugin.name}</div>- <div className="wp-asset-card__foot">- <span className="wp-asset-card__ver">v{plugin.version}</span>- {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>- );-};--// 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 (- <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>- );-};--// 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 (- <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>- );-};--// 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- />-);--// 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 & 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>- );-};-function extractRepoDisplay(url) {if (!url) return '';try {