Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(backups): protection panel UI + global cost view

Juan Denis7b9ae4f93448
diff --git a/frontend/src/components/backups/BackupCalendar.jsx b/frontend/src/components/backups/BackupCalendar.jsx
new file mode 100644
index 00000000..78ac2706
--- /dev/null
+++ b/frontend/src/components/backups/BackupCalendar.jsx
@@ -0,0 +1,130 @@
+import { useState, useMemo } from 'react';
+import { ChevronLeft, ChevronRight } from 'lucide-react';
+import { statusKind } from './format';
+
+// Card of the backup "Protection" panel: a Monday-first month grid of backup
+// runs. Pairs with the .backup-calendar styles. Uses native Date math (no libs).
+
+// Monday-first weekday headers, matching the column order of the grid.
+const WEEKDAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
+
+// Worst-first status precedence for a day: failed > success > running.
+// `statusKind` is reused to keep the day's status vocabulary aligned with Pills.
+const STATUS_RANK = { failed: 2, success: 1, running: 0 };
+
+function pad(n) {
+ return String(n).padStart(2, '0');
+}
+
+// Local calendar-day key (YYYY-MM-DD) for a Date.
+function dayKey(d) {
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
+}
+
+function startOfMonth(d) {
+ return new Date(d.getFullYear(), d.getMonth(), 1);
+}
+
+function daysInMonth(year, month) {
+ // Day 0 of the next month is the last day of this month.
+ return new Date(year, month + 1, 0).getDate();
+}
+
+// Count of leading blank cells before day 1, with Monday as the first column.
+function leadingBlanks(year, month) {
+ return (new Date(year, month, 1).getDay() + 6) % 7;
+}
+
+// Collapse a run's status into one of the three day buckets used for ranking.
+function dayStatus(status) {
+ if (status === 'failed') return 'failed';
+ if (status === 'success') return 'success';
+ return 'running'; // covers 'running' and 'verifying'
+}
+
+export default function BackupCalendar({ runs, onDayClick }) {
+ const [cursor, setCursor] = useState(() => new Date());
+
+ // Map of dayKey -> { count, worst } built from all runs (month-independent).
+ const dayMap = useMemo(() => {
+ const map = new Map();
+ (runs || []).forEach((run) => {
+ if (!run || !run.started_at) return;
+ const d = new Date(run.started_at);
+ if (Number.isNaN(d.getTime())) return;
+ const key = dayKey(d);
+ const status = dayStatus(run.status);
+ const existing = map.get(key);
+ if (!existing) {
+ map.set(key, { count: 1, worst: status });
+ return;
+ }
+ existing.count += 1;
+ if (STATUS_RANK[status] > STATUS_RANK[existing.worst]) {
+ existing.worst = status;
+ }
+ });
+ return map;
+ }, [runs]);
+
+ // Cells for the visible month: leading/trailing blanks are null, real days
+ // carry their date, day number, and (if any) backup count + worst status.
+ const cells = useMemo(() => {
+ const year = cursor.getFullYear();
+ const month = cursor.getMonth();
+ const blanks = leadingBlanks(year, month);
+ const total = daysInMonth(year, month);
+ const result = [];
+
+ for (let i = 0; i < blanks; i += 1) {
+ result.push(null);
+ }
+ for (let day = 1; day <= total; day += 1) {
+ const date = new Date(year, month, day);
+ const info = dayMap.get(dayKey(date));
+ result.push({
+ date,
+ day,
+ count: info ? info.count : 0,
+ worst: info ? info.worst : null,
+ });
+ }
+ return result;
+ }, [cursor, dayMap]);
+
+ const monthLabel = cursor.toLocaleDateString(undefined, { month: 'long', year: 'numeric' });
+
+ const prevMonth = () => setCursor((c) => new Date(c.getFullYear(), c.getMonth() - 1, 1));
+ const nextMonth = () => setCursor((c) => new Date(c.getFullYear(), c.getMonth() + 1, 1));
+ const goToday = () => setCursor(startOfMonth(new Date()));
+
+ return (
+ <div className="backup-calendar">
+ <div className="backup-calendar__head">
+ <button type="button" className="backup-calendar__nav" onClick={prevMonth} aria-label="Previous month"><ChevronLeft size={16} /></button>
+ <span className="backup-calendar__month">{monthLabel}</span>
+ <button type="button" className="backup-calendar__nav" onClick={nextMonth} aria-label="Next month"><ChevronRight size={16} /></button>
+ <button type="button" className="backup-calendar__today" onClick={goToday}>Today</button>
+ </div>
+ <div className="backup-calendar__grid">
+ {WEEKDAYS.map((d) => <div key={d} className="backup-calendar__dow">{d}</div>)}
+ {cells.map((cell, i) => (
+ cell
+ ? (
+ <button
+ type="button"
+ key={i}
+ className={`backup-calendar__cell ${cell.count ? `backup-calendar__cell--has is-${cell.worst}` : ''}`}
+ disabled={!cell.count}
+ onClick={cell.count ? () => onDayClick(cell.date) : undefined}
+ >
+ <span className="backup-calendar__daynum">{cell.day}</span>
+ {cell.count > 0 && <span className="backup-calendar__badge">{cell.count}</span>}
+ </button>
+ )
+ : <span key={i} className="backup-calendar__cell backup-calendar__cell--empty" />
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/components/backups/BackupDetailDrawer.jsx b/frontend/src/components/backups/BackupDetailDrawer.jsx
new file mode 100644
index 00000000..af34e4c0
--- /dev/null
+++ b/frontend/src/components/backups/BackupDetailDrawer.jsx
@@ -0,0 +1,87 @@
+// Right-side drawer for the backup "Protection" panel: shows one backup run's
+// details (status, timing, size, cost, storage, verification) plus the run-level
+// actions (restore, verify remote, download, delete). Always renders the Drawer
+// so its open/close slide animation plays even when there's no run selected.
+import { Drawer, Pill } from '@/components/ds';
+import { Button } from '@/components/ui/button';
+import { Archive, RotateCcw, ShieldCheck, Download, Trash2, ExternalLink } from 'lucide-react';
+import { humanSize, formatMoney, formatDateTime, statusKind, storageLabel } from './format';
+
+export default function BackupDetailDrawer({ run, open, onClose, onRestore, onVerify, onDelete, onDownload }) {
+ // No run selected: render an empty Drawer so the close animation still plays.
+ if (!run) {
+ return (
+ <Drawer open={open} onOpenChange={(v) => !v && onClose()} title="Backup" width={560}>
+ <div />
+ </Drawer>
+ );
+ }
+
+ const title = run.metadata?.backup_name || `Backup #${run.id}`;
+ const verification = run.remote_key
+ ? (run.verified ? 'Verified' : 'Unverified')
+ : 'Local only';
+
+ return (
+ <Drawer
+ open={open}
+ onOpenChange={(v) => !v && onClose()}
+ title={title}
+ subtitle={run.kind}
+ icon={<Archive size={18} />}
+ width={560}
+ >
+ <div className="backup-detail-drawer">
+ <div className="backup-detail-drawer__head">
+ <Pill kind={statusKind(run.status)}>{run.status}</Pill>
+ {run.verified && <Pill kind="green" dot={false}>Verified</Pill>}
+ </div>
+
+ {run.status === 'failed' && run.error_message && (
+ <p className="backup-detail-drawer__error">{run.error_message}</p>
+ )}
+
+ <div className="backup-detail-drawer__meta">
+ <div className="backup-detail-drawer__row"><span>Created</span><span>{formatDateTime(run.started_at)}</span></div>
+ <div className="backup-detail-drawer__row"><span>Finished</span><span>{formatDateTime(run.finished_at)}</span></div>
+ <div className="backup-detail-drawer__row"><span>Duration</span><span>{run.duration_seconds != null ? `${run.duration_seconds}s` : '—'}</span></div>
+ <div className="backup-detail-drawer__row"><span>Type</span><span>{run.kind}</span></div>
+ <div className="backup-detail-drawer__row"><span>Compression</span><span>{run.compression || '—'}</span></div>
+ <div className="backup-detail-drawer__row"><span>Storage</span><span>{storageLabel(run)}</span></div>
+ <div className="backup-detail-drawer__row"><span>Size (local)</span><span>{humanSize(run.size_local)}</span></div>
+ <div className="backup-detail-drawer__row"><span>Size (remote)</span><span>{run.size_remote ? humanSize(run.size_remote) : '—'}</span></div>
+ <div className="backup-detail-drawer__row"><span>Verification</span><span>{verification}</span></div>
+ </div>
+
+ <div className="backup-detail-drawer__cost">
+ Estimated cost: {formatMoney(run.cost_local)} (local) + {formatMoney(run.cost_remote)} (remote) = {formatMoney(run.cost_total)} total
+ </div>
+
+ <div className="backup-detail-drawer__actions">
+ <Button variant="primary" size="sm" disabled={run.status !== 'success'} onClick={() => onRestore(run)}>
+ <RotateCcw size={14} /> Restore
+ </Button>
+ {run.remote_key && (
+ <Button variant="outline" size="sm" onClick={() => onVerify(run)}>
+ <ShieldCheck size={14} /> Verify remote
+ </Button>
+ )}
+ {onDownload && run.storage_path && (
+ <Button variant="outline" size="sm" onClick={() => onDownload(run)}>
+ <Download size={14} /> Download
+ </Button>
+ )}
+ <Button variant="destructive" size="sm" onClick={() => onDelete(run)}>
+ <Trash2 size={14} /> Delete
+ </Button>
+ </div>
+
+ {run.job_id && (
+ <a className="backup-detail-drawer__joblink" href="/jobs">
+ <ExternalLink size={13} /> View job
+ </a>
+ )}
+ </div>
+ </Drawer>
+ );
+}
diff --git a/frontend/src/components/backups/BackupHistoryList.jsx b/frontend/src/components/backups/BackupHistoryList.jsx
new file mode 100644
index 00000000..9694f6e9
--- /dev/null
+++ b/frontend/src/components/backups/BackupHistoryList.jsx
@@ -0,0 +1,100 @@
+import { Pill } from '@/components/ds';
+import { Button } from '@/components/ui/button';
+import EmptyState from '@/components/EmptyState';
+import { Archive, RotateCcw, ShieldCheck, Trash2, HardDrive, Cloud, Layers } from 'lucide-react';
+import { humanSize, formatMoney, formatWhen, statusKind, storageLabel } from './format';
+
+// Card 3 of the backup "Protection" panel: a data-table of backup runs.
+// Pairs with the .sk-dtable styles plus a .backup-history-list-scoped layer.
+function storageIcon(run) {
+ const label = storageLabel(run);
+ if (label === 'both') {
+ return (
+ <span className="backup-history-list__storage" title="Local + remote">
+ <Layers size={13} /> both
+ </span>
+ );
+ }
+ if (label === 'remote') {
+ return (
+ <span className="backup-history-list__storage" title="Remote">
+ <Cloud size={13} /> remote
+ </span>
+ );
+ }
+ return (
+ <span className="backup-history-list__storage" title="Local">
+ <HardDrive size={13} /> local
+ </span>
+ );
+}
+
+export default function BackupHistoryList({
+ runs,
+ loading,
+ onRestore,
+ onVerify,
+ onDelete,
+ onRowClick,
+}) {
+ if (loading && (!runs || runs.length === 0)) {
+ return <EmptyState icon={Archive} title="Loading backups…" loading />;
+ }
+
+ if (!loading && (!runs || runs.length === 0)) {
+ return (
+ <EmptyState
+ icon={Archive}
+ title="No backups yet"
+ description="Turn on protection or click Back up now."
+ />
+ );
+ }
+
+ return (
+ <table className="sk-dtable backup-history-list">
+ <thead>
+ <tr>
+ <th>Backup</th>
+ <th>Date</th>
+ <th>Size</th>
+ <th>Cost</th>
+ <th>Status</th>
+ <th>Storage</th>
+ <th aria-label="Actions" />
+ </tr>
+ </thead>
+ <tbody>
+ {runs.map((run) => (
+ <tr
+ key={run.id}
+ className={`backup-history-list__row ${onRowClick ? 'is-clickable' : ''}`}
+ onClick={onRowClick ? () => onRowClick(run) : undefined}
+ >
+ <td>
+ <div className="sk-cell-name">
+ <span className="backup-history-list__ico"><Archive size={14} /></span>
+ <span>{run.metadata?.backup_name || `Backup #${run.id}`}</span>
+ <Pill kind={run.kind === 'full' ? 'violet' : 'gray'} dot={false}>{run.kind}</Pill>
+ </div>
+ </td>
+ <td className="backup-history-list__when">{formatWhen(run.started_at)}</td>
+ <td className="sk-cell-mono">{humanSize(run.size_total)}</td>
+ <td className="sk-cell-mono">{formatMoney(run.cost_total)}</td>
+ <td><Pill kind={statusKind(run.status)}>{run.status}</Pill></td>
+ <td>{storageIcon(run)}</td>
+ <td>
+ <div className="backup-history-list__actions" onClick={(e) => e.stopPropagation()}>
+ <Button size="icon" variant="outline" title="Restore" disabled={run.status !== 'success'} onClick={() => onRestore(run)}><RotateCcw size={14} /></Button>
+ {run.remote_key && (
+ <Button size="icon" variant="outline" title="Verify remote copy" onClick={() => onVerify(run)}><ShieldCheck size={14} /></Button>
+ )}
+ <Button size="icon" variant="destructive" title="Delete" onClick={() => onDelete(run)}><Trash2 size={14} /></Button>
+ </div>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ );
+}
diff --git a/frontend/src/components/backups/ProtectionPanel.jsx b/frontend/src/components/backups/ProtectionPanel.jsx
new file mode 100644
index 00000000..d23aafff
--- /dev/null
+++ b/frontend/src/components/backups/ProtectionPanel.jsx
@@ -0,0 +1,282 @@
+// Shared "Protection" panel — the upgraded backup experience rendered for both
+// WordPress sites and applications (Services). Loads the backup policy + run
+// history and owns every mutation (toggle, schedule save, manual backup,
+// restore, verify, delete). Three stacked cards plus detail/restore drawers.
+import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
+import { useNavigate } from 'react-router-dom';
+import { History, RefreshCw, Loader2, List, CalendarDays, X } from 'lucide-react';
+
+import api from '@/services/api';
+import { useToast } from '@/contexts/ToastContext';
+import { useConfirm } from '@/hooks/useConfirm';
+import { ConfirmDialog } from '@/components/ConfirmDialog';
+import { Button } from '@/components/ui/button';
+
+import ProtectionStatusCard from './ProtectionStatusCard';
+import ScheduleCard from './ScheduleCard';
+import BackupHistoryList from './BackupHistoryList';
+import BackupCalendar from './BackupCalendar';
+import BackupDetailDrawer from './BackupDetailDrawer';
+import RestoreDrawer from './RestoreDrawer';
+
+function sameLocalDay(iso, date) {
+ if (!iso) return false;
+ const d = new Date(iso);
+ return d.getFullYear() === date.getFullYear()
+ && d.getMonth() === date.getMonth()
+ && d.getDate() === date.getDate();
+}
+
+export default function ProtectionPanel({ targetType, targetId, targetName, showMaintenanceModeOption = false }) {
+ const toast = useToast();
+ const navigate = useNavigate();
+ const { confirm, confirmState, handleConfirm, handleCancel } = useConfirm();
+
+ const [view, setView] = useState(null); // policy view payload
+ const [runs, setRuns] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [backingUp, setBackingUp] = useState(false);
+ const [historyView, setHistoryView] = useState('list'); // 'list' | 'calendar'
+ const [dayFilter, setDayFilter] = useState(null); // Date | null
+ const [detailRun, setDetailRun] = useState(null);
+ const [restoreRun, setRestoreRun] = useState(null);
+ const reloadTimers = useRef([]);
+
+ const load = useCallback(async () => {
+ if (!targetId) return;
+ try {
+ const [policyView, runsResp] = await Promise.all([
+ api.getBackupPolicy(targetType, targetId),
+ api.getBackupRuns(targetType, targetId),
+ ]);
+ setView(policyView);
+ setRuns(runsResp?.runs || []);
+ } catch (err) {
+ toast.error(err.message || 'Failed to load protection settings');
+ } finally {
+ setLoading(false);
+ }
+ }, [targetType, targetId, toast]);
+
+ useEffect(() => {
+ setLoading(true);
+ load();
+ }, [load]);
+
+ // Refresh when the tab regains focus (a background backup may have finished).
+ useEffect(() => {
+ const onFocus = () => load();
+ window.addEventListener('focus', onFocus);
+ return () => window.removeEventListener('focus', onFocus);
+ }, [load]);
+
+ // Clear any pending delayed reloads on unmount.
+ useEffect(() => () => reloadTimers.current.forEach(clearTimeout), []);
+
+ const scheduleReloads = useCallback(() => {
+ reloadTimers.current.forEach(clearTimeout);
+ reloadTimers.current = [setTimeout(load, 2500), setTimeout(load, 7000)];
+ }, [load]);
+
+ const handleToggle = useCallback(async (enabled) => {
+ setSaving(true);
+ try {
+ const updated = await api.updateBackupPolicy(targetType, targetId, { enabled });
+ setView(updated);
+ toast.success(enabled ? 'Automatic backups enabled' : 'Automatic backups disabled');
+ } catch (err) {
+ toast.error(err.message || 'Failed to update protection');
+ } finally {
+ setSaving(false);
+ }
+ }, [targetType, targetId, toast]);
+
+ const handleSaveSchedule = useCallback(async (fields) => {
+ setSaving(true);
+ try {
+ const updated = await api.updateBackupPolicy(targetType, targetId, fields);
+ setView(updated);
+ toast.success('Schedule saved');
+ } catch (err) {
+ toast.error(err.message || 'Failed to save schedule');
+ } finally {
+ setSaving(false);
+ }
+ }, [targetType, targetId, toast]);
+
+ const handleBackupNow = useCallback(async () => {
+ setBackingUp(true);
+ try {
+ await api.triggerBackup(targetType, targetId);
+ toast.success('Backup started');
+ scheduleReloads();
+ } catch (err) {
+ toast.error(err.message || 'Failed to start backup');
+ } finally {
+ setBackingUp(false);
+ }
+ }, [targetType, targetId, toast, scheduleReloads]);
+
+ // Restore is always initiated from a run — opening the restore drawer.
+ const openRestore = useCallback((run) => setRestoreRun(run), []);
+
+ const handleRestoreConfirm = useCallback(async (options) => {
+ if (!restoreRun) return;
+ try {
+ await api.restoreBackupRun(targetType, targetId, restoreRun.id, {
+ ...options,
+ maintenance_mode: showMaintenanceModeOption ? options.maintenance_mode : false,
+ });
+ toast.success('Restore started');
+ setRestoreRun(null);
+ setDetailRun(null);
+ scheduleReloads();
+ } catch (err) {
+ toast.error(err.message || 'Failed to start restore');
+ }
+ }, [restoreRun, targetType, targetId, showMaintenanceModeOption, toast, scheduleReloads]);
+
+ const handleVerify = useCallback(async (run) => {
+ try {
+ const result = await api.verifyBackupRun(targetType, targetId, run.id);
+ if (result?.verified) toast.success('Remote copy verified');
+ else toast.warning('Remote copy could not be verified');
+ load();
+ } catch (err) {
+ toast.error(err.message || 'Verification failed');
+ }
+ }, [targetType, targetId, toast, load]);
+
+ const handleDelete = useCallback(async (run) => {
+ const ok = await confirm({
+ title: 'Delete backup?',
+ message: 'This permanently deletes the backup, including any remote copy. This cannot be undone.',
+ confirmText: 'Delete',
+ variant: 'danger',
+ });
+ if (!ok) return;
+ try {
+ await api.deleteBackupRun(targetType, targetId, run.id);
+ toast.success('Backup deleted');
+ if (detailRun?.id === run.id) setDetailRun(null);
+ load();
+ } catch (err) {
+ toast.error(err.message || 'Failed to delete backup');
+ }
+ }, [confirm, targetType, targetId, toast, load, detailRun]);
+
+ const visibleRuns = useMemo(
+ () => (dayFilter ? runs.filter((r) => sameLocalDay(r.started_at, dayFilter)) : runs),
+ [runs, dayFilter],
+ );
+
+ return (
+ <div className="protection-panel app-overview-grid">
+ <div className="app-overview-left">
+ <ProtectionStatusCard
+ policyView={view}
+ onToggle={handleToggle}
+ onBackupNow={handleBackupNow}
+ onViewGlobal={() => navigate('/backups')}
+ onViewJobs={() => navigate('/jobs')}
+ busy={saving}
+ backingUp={backingUp}
+ />
+
+ <ScheduleCard
+ policy={view?.policy}
+ remoteConfigured={!!view?.remote_configured}
+ onSave={handleSaveSchedule}
+ saving={saving}
+ />
+
+ <div className="app-panel backup-history-card">
+ <div className="app-panel-header">
+ <History size={16} />
+ <span>Backup history</span>
+ <span className="app-panel-header-actions backup-history-card__tools">
+ {dayFilter && (
+ <button
+ type="button"
+ className="backup-history-card__chip"
+ onClick={() => setDayFilter(null)}
+ >
+ {dayFilter.toLocaleDateString()} <X size={12} />
+ </button>
+ )}
+ <div className="backup-history-card__toggle">
+ <button
+ type="button"
+ className={historyView === 'list' ? 'is-active' : ''}
+ onClick={() => setHistoryView('list')}
+ aria-label="List view"
+ >
+ <List size={14} />
+ </button>
+ <button
+ type="button"
+ className={historyView === 'calendar' ? 'is-active' : ''}
+ onClick={() => setHistoryView('calendar')}
+ aria-label="Calendar view"
+ >
+ <CalendarDays size={14} />
+ </button>
+ </div>
+ <Button size="sm" variant="outline" onClick={load} disabled={loading} title="Refresh">
+ {loading ? <Loader2 size={14} className="spin" /> : <RefreshCw size={14} />}
+ </Button>
+ </span>
+ </div>
+ <div className="app-panel-body">
+ {historyView === 'calendar' ? (
+ <BackupCalendar
+ runs={runs}
+ onDayClick={(date) => { setDayFilter(date); setHistoryView('list'); }}
+ />
+ ) : (
+ <BackupHistoryList
+ runs={visibleRuns}
+ loading={loading}
+ onRestore={openRestore}
+ onVerify={handleVerify}
+ onDelete={handleDelete}
+ onRowClick={(run) => setDetailRun(run)}
+ />
+ )}
+ </div>
+ </div>
+ </div>
+
+ <BackupDetailDrawer
+ run={detailRun}
+ open={!!detailRun}
+ onClose={() => setDetailRun(null)}
+ onRestore={(run) => { setDetailRun(null); openRestore(run); }}
+ onVerify={handleVerify}
+ onDelete={handleDelete}
+ />
+
+ <RestoreDrawer
+ run={restoreRun}
+ open={!!restoreRun}
+ onClose={() => setRestoreRun(null)}
+ onConfirm={handleRestoreConfirm}
+ targetName={targetName}
+ targetType={targetType}
+ showMaintenanceModeOption={showMaintenanceModeOption}
+ />
+
+ <ConfirmDialog
+ isOpen={confirmState.isOpen}
+ title={confirmState.title}
+ message={confirmState.message}
+ confirmText={confirmState.confirmText}
+ cancelText={confirmState.cancelText}
+ variant={confirmState.variant}
+ onConfirm={handleConfirm}
+ onCancel={handleCancel}
+ />
+ </div>
+ );
+}
diff --git a/frontend/src/components/backups/ProtectionStatusCard.jsx b/frontend/src/components/backups/ProtectionStatusCard.jsx
new file mode 100644
index 00000000..a4008b3d
--- /dev/null
+++ b/frontend/src/components/backups/ProtectionStatusCard.jsx
@@ -0,0 +1,156 @@
+import { Pill, MetricCard } from '@/components/ds';
+import { Switch } from '@/components/ui/switch';
+import { Button } from '@/components/ui/button';
+import { Archive, Clock, DollarSign, HardDrive, Play, ExternalLink, Loader2 } from 'lucide-react';
+import { humanSize, formatMoney, formatWhen, formatDateTime } from './format';
+
+// Card 1 of the backup "Protection" panel: a presentational status summary.
+// Derives a single status (Protected / Pending / Failed / Running / Off) from
+// the policy snapshot, then renders the toggle, status line, KPIs, and actions.
+// All data is pre-shaped by the parent (policyView); this component holds no
+// state and triggers behavior purely through the supplied callbacks.
+
+// Status kinds map to a Pill colour + the label shown both top-right and inline.
+const STATUS_PILL = {
+ protected: { kind: 'green', label: 'Protected' },
+ pending: { kind: 'amber', label: 'Pending' },
+ failed: { kind: 'red', label: 'Failed' },
+ running: { kind: 'cyan', label: 'Running' },
+ off: { kind: 'gray', label: 'Off' },
+};
+
+// Pick the status key from the policy snapshot. Failure wins over everything so
+// a broken last run is never hidden behind an "enabled" badge.
+function resolveStatus(policy, isRunning) {
+ if (policy.last_status === 'failed') return 'failed';
+ if (policy.enabled && (policy.last_status === 'running' || isRunning)) return 'running';
+ if (!policy.enabled) return 'off';
+ if (!policy.last_run) return 'pending';
+ if (policy.last_status === 'success') return 'protected';
+ // Enabled but no definitive status yet (e.g. queued first run).
+ return 'pending';
+}
+
+const ProtectionStatusCard = ({
+ policyView,
+ onToggle,
+ onBackupNow,
+ onViewGlobal,
+ onViewJobs,
+ busy,
+ backingUp,
+}) => {
+ if (!policyView) {
+ return (
+ <div className="app-panel protection-status-card">
+ <div className="app-panel-header">
+ <Archive size={16} />
+ <span>Protection</span>
+ </div>
+ <div className="app-panel-body" />
+ </div>
+ );
+ }
+
+ const policy = policyView.policy || {};
+ const enabled = !!policy.enabled;
+ const isRunning = !!policyView.is_running;
+ const nextRunAt = policyView.next_run_at;
+
+ const statusKey = resolveStatus(policy, isRunning);
+ const { kind, label } = STATUS_PILL[statusKey];
+ const statusPill = <Pill kind={kind}>{label}</Pill>;
+
+ const subtitle = enabled
+ ? 'Snapshots run on the configured schedule.'
+ : 'Turn on to back up this site automatically.';
+
+ // Inline status line (and, for the failed state, a deep-link to Jobs).
+ let statusLine = null;
+ let statusAction = null;
+ if (statusKey === 'failed') {
+ statusLine = `Last backup failed at ${formatWhen(policy.last_run_at)}`;
+ statusAction = (
+ <Button variant="ghost" size="sm" onClick={onViewJobs}>
+ View in Jobs
+ </Button>
+ );
+ } else if (statusKey === 'running') {
+ statusLine = 'A backup is in progress…';
+ } else if (statusKey === 'protected') {
+ const cost = formatMoney((policy.last_cost_local || 0) + (policy.last_cost_remote || 0));
+ statusLine = `Last backup: ${formatWhen(policy.last_run_at)} · ${humanSize(policy.last_size)} · ${cost}`;
+ } else if (statusKey === 'pending') {
+ statusLine = nextRunAt
+ ? `First backup will run at ${formatDateTime(nextRunAt)}`
+ : 'First backup will run soon';
+ } else {
+ statusLine = 'Backups are not running automatically';
+ }
+
+ const nextBackupValue = enabled && nextRunAt ? formatDateTime(nextRunAt) : '—';
+
+ return (
+ <div className="app-panel protection-status-card">
+ <div className="app-panel-header">
+ <Archive size={16} />
+ <span>Protection</span>
+ <span className="app-panel-header-actions">{statusPill}</span>
+ </div>
+ <div className="app-panel-body">
+ <div className="protection-status-card__toggle">
+ <Switch
+ id="auto-backups"
+ checked={enabled}
+ onCheckedChange={onToggle}
+ disabled={busy}
+ />
+ <label htmlFor="auto-backups">
+ <span className="protection-status-card__toggle-title">Automatic backups</span>
+ <span className="protection-status-card__toggle-sub">{subtitle}</span>
+ </label>
+ </div>
+
+ <div className="protection-status-card__status">
+ {statusPill}
+ <span>{statusLine}</span>
+ {statusAction}
+ </div>
+
+ <div className="protection-status-card__kpis">
+ <MetricCard
+ tone="accent"
+ icon={<Clock size={16} />}
+ value={nextBackupValue}
+ label="Next backup"
+ />
+ <MetricCard
+ tone="green"
+ icon={<DollarSign size={16} />}
+ value={policyView.monthly_cost_display}
+ label="Monthly cost"
+ />
+ <MetricCard
+ tone="cyan"
+ icon={<HardDrive size={16} />}
+ value={policyView.storage_used_human}
+ label="Storage used"
+ />
+ </div>
+
+ <div className="protection-status-card__actions">
+ <Button variant="primary" size="sm" onClick={onBackupNow} disabled={backingUp}>
+ {backingUp ? <Loader2 size={14} className="spin" /> : <Play size={14} />}
+ Back up now
+ </Button>
+ <Button variant="ghost" size="sm" onClick={onViewGlobal}>
+ <ExternalLink size={14} />
+ View in global backups
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default ProtectionStatusCard;
diff --git a/frontend/src/components/backups/RestoreDrawer.jsx b/frontend/src/components/backups/RestoreDrawer.jsx
new file mode 100644
index 00000000..1759aee8
--- /dev/null
+++ b/frontend/src/components/backups/RestoreDrawer.jsx
@@ -0,0 +1,194 @@
+import { useState, useEffect } from 'react';
+import { Drawer, SegControl } from '@/components/ds';
+import { Switch } from '@/components/ui/switch';
+import { Button } from '@/components/ui/button';
+import { ConfirmDialog } from '@/components/ConfirmDialog';
+import { RotateCcw, AlertTriangle } from 'lucide-react';
+
+// Right-side slide-over for the backup "Protection" panel: configure and confirm
+// a restore. The restore scope can be the whole site, just files, just the
+// database, or — for WordPress targets that expose their table list — a hand-
+// picked set of tables. Safety options (a pre-restore backup, permission copy,
+// optional maintenance mode) ride alongside. Because overwriting live data is
+// irreversible, the destructive action is gated behind a typed-confirmation
+// ConfirmDialog rather than a plain button.
+//
+// <RestoreDrawer run={run} open={open} onClose={close} onConfirm={doRestore}
+// targetName="my-site" siteTables={tables}
+// showMaintenanceModeOption />
+
+// Icon sizes are fixed by the drawer-head / inline-affordance conventions used
+// across the redesign primitives, so they live as named constants rather than
+// magic numbers sprinkled through the JSX.
+const HEAD_ICON_SIZE = 18;
+const ACTION_ICON_SIZE = 14;
+const WARNING_ICON_SIZE = 14;
+
+// Drawer width matches the other Protection-panel slide-overs.
+const DRAWER_WIDTH = 520;
+
+// Base scope choices, always available. Database/Selected-tables are appended
+// only for WordPress targets (applications are files-only).
+const BASE_SCOPE_OPTIONS = [
+ { value: 'full', label: 'Full site' },
+ { value: 'files', label: 'Files only' },
+];
+
+const RestoreDrawer = ({
+ run,
+ open,
+ onClose,
+ onConfirm,
+ targetName,
+ targetType,
+ siteTables,
+ showMaintenanceModeOption,
+}) => {
+ const [scope, setScope] = useState('full');
+ const [tables, setTables] = useState([]);
+ const [safetyBackup, setSafetyBackup] = useState(true);
+ const [copyPermissions, setCopyPermissions] = useState(false);
+ const [maintenanceMode, setMaintenanceMode] = useState(true);
+ const [confirmOpen, setConfirmOpen] = useState(false);
+
+ // Re-seed to defaults each time the drawer is opened, so a previous, possibly
+ // abandoned configuration never leaks into the next restore.
+ useEffect(() => {
+ if (!open) return;
+ setScope('full');
+ setTables([]);
+ setSafetyBackup(true);
+ setCopyPermissions(false);
+ setMaintenanceMode(true);
+ setConfirmOpen(false);
+ }, [open]);
+
+ const isWordPress = targetType === 'wordpress_site';
+ const hasTables = isWordPress && !!siteTables?.length;
+
+ const scopeOptions = [
+ ...BASE_SCOPE_OPTIONS,
+ ...(isWordPress ? [{ value: 'database', label: 'Database only' }] : []),
+ ...(hasTables ? [{ value: 'tables', label: 'Selected tables' }] : []),
+ ];
+
+ const toggleTable = (t) => {
+ setTables((prev) => (prev.includes(t) ? prev.filter((x) => x !== t) : [...prev, t]));
+ };
+
+ // Disable the restore action until there is a run to restore, and — when the
+ // scope is a table subset — until at least one table has been chosen.
+ const restoreDisabled = !run || (scope === 'tables' && tables.length === 0);
+
+ const handleConfirm = () => {
+ setConfirmOpen(false);
+ onConfirm({
+ scope,
+ tables,
+ safety_backup: safetyBackup,
+ copy_permissions: copyPermissions,
+ maintenance_mode: maintenanceMode,
+ });
+ };
+
+ const subtitle = run?.metadata?.backup_name || (run ? `Backup #${run.id}` : '');
+
+ return (
+ <Drawer
+ open={open}
+ onOpenChange={(v) => !v && onClose()}
+ title="Restore backup"
+ subtitle={subtitle}
+ icon={<RotateCcw size={HEAD_ICON_SIZE} />}
+ width={DRAWER_WIDTH}
+ >
+ <div className="restore-drawer">
+ <div className="restore-drawer__section">
+ <label className="restore-drawer__label">Scope</label>
+ <div className="restore-drawer__scope">
+ <SegControl options={scopeOptions} value={scope} onChange={setScope} />
+ </div>
+ </div>
+
+ {scope === 'tables' && hasTables && (
+ <div className="restore-drawer__tables">
+ {siteTables.map((t) => (
+ <label key={t}>
+ <input
+ type="checkbox"
+ checked={tables.includes(t)}
+ onChange={() => toggleTable(t)}
+ />
+ {t}
+ </label>
+ ))}
+ </div>
+ )}
+
+ <div className="restore-drawer__section">
+ <label className="restore-drawer__label">Safety options</label>
+ <div className="restore-drawer__options">
+ <div className="restore-drawer__option">
+ <Switch
+ id="safety-backup"
+ checked={safetyBackup}
+ onCheckedChange={setSafetyBackup}
+ />
+ <label htmlFor="safety-backup">Create a safety backup first</label>
+ </div>
+ <div className="restore-drawer__option">
+ <Switch
+ id="copy-perms"
+ checked={copyPermissions}
+ onCheckedChange={setCopyPermissions}
+ />
+ <label htmlFor="copy-perms">Copy original file permissions</label>
+ </div>
+ {showMaintenanceModeOption && (
+ <div className="restore-drawer__option">
+ <Switch
+ id="maint"
+ checked={maintenanceMode}
+ onCheckedChange={setMaintenanceMode}
+ />
+ <label htmlFor="maint">
+ Put site in maintenance mode during restore
+ </label>
+ </div>
+ )}
+ </div>
+ </div>
+
+ <p className="restore-drawer__warning">
+ <AlertTriangle size={WARNING_ICON_SIZE} />
+ This will overwrite the current site with the selected backup. This action cannot
+ be undone.
+ </p>
+
+ <Button
+ variant="destructive"
+ size="sm"
+ disabled={restoreDisabled}
+ onClick={() => setConfirmOpen(true)}
+ >
+ <RotateCcw size={ACTION_ICON_SIZE} />
+ Restore
+ </Button>
+
+ <ConfirmDialog
+ isOpen={confirmOpen}
+ title="Confirm restore"
+ message={`Type the name to confirm restoring ${targetName || 'this target'}. This overwrites current data.`}
+ confirmText="Restore"
+ variant="danger"
+ requireConfirmation={targetName || 'restore'}
+ confirmationPlaceholder={targetName}
+ onConfirm={handleConfirm}
+ onCancel={() => setConfirmOpen(false)}
+ />
+ </div>
+ </Drawer>
+ );
+};
+
+export default RestoreDrawer;
diff --git a/frontend/src/components/backups/ScheduleCard.jsx b/frontend/src/components/backups/ScheduleCard.jsx
new file mode 100644
index 00000000..bfb6c3be
--- /dev/null
+++ b/frontend/src/components/backups/ScheduleCard.jsx
@@ -0,0 +1,289 @@
+import { useState, useEffect, useMemo } from 'react';
+import { SegControl } from '@/components/ds';
+import { Switch } from '@/components/ui/switch';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Calendar, Save, Loader2 } from 'lucide-react';
+
+// Card 2 of the backup "Protection" panel: the editable schedule form.
+// The saved policy carries a raw cron string; this card translates it into a
+// friendly Daily / Weekly / Custom UI and back. Local state mirrors the form
+// while a useEffect re-seeds it whenever the parent reloads the policy, so an
+// external save stays in sync. Save is disabled until something actually
+// changes (dirty tracking) and shows a spinner while the request is in flight.
+
+// Canonical cron strings for the two preset frequencies (02:00 server time).
+const DAILY_CRON = '0 2 * * *';
+const WEEKLY_CRON = '0 2 * * 0'; // Sunday
+// Day-of-week chip labels; index 0 = Sunday … 6 = Saturday (cron dow order).
+const DOW_LABELS = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
+
+const DEFAULT_TIME = '02:00';
+const MIN_COUNT = 1; // floor shared by every numeric field (count/days/full-every)
+
+// Two-digit zero-pad for assembling/displaying HH:MM from cron integers.
+const pad = (n) => String(n).padStart(2, '0');
+
+// True when a cron token is a plain non-negative integer (e.g. "2", not "*").
+const isInt = (token) => /^\d+$/.test(token);
+
+// Coerce a numeric form field (kept as a string) to a number, treating empty
+// or sub-floor values as the minimum so we never persist 0 / NaN.
+const toNum = (value) => {
+ const n = Number(value);
+ return Number.isFinite(n) && n >= MIN_COUNT ? n : MIN_COUNT;
+};
+
+// Expand a cron day-of-week field into a sorted int array (0..6).
+// "*"/"?" -> [] (every day); supports comma lists and "a-b" ranges.
+function parseDow(field) {
+ if (!field || field === '*' || field === '?') return [];
+ const out = new Set();
+ for (const part of field.split(',')) {
+ const range = part.split('-');
+ if (range.length === 2 && isInt(range[0]) && isInt(range[1])) {
+ const lo = Number(range[0]);
+ const hi = Number(range[1]);
+ for (let d = lo; d <= hi; d += 1) {
+ if (d >= 0 && d <= 6) out.add(d);
+ }
+ } else if (isInt(part)) {
+ const d = Number(part);
+ if (d >= 0 && d <= 6) out.add(d);
+ }
+ }
+ return Array.from(out).sort((a, b) => a - b);
+}
+
+// Translate a saved cron string into the form's { frequency, time, days }.
+function deriveFromCron(cron) {
+ if (cron === DAILY_CRON) return { frequency: 'daily', time: DEFAULT_TIME, days: [] };
+ if (cron === WEEKLY_CRON) return { frequency: 'weekly', time: DEFAULT_TIME, days: [0] };
+
+ const fields = (cron || '').trim().split(/\s+/);
+ const min = fields[0];
+ const hour = fields[1];
+ const time = isInt(hour) && isInt(min) ? `${pad(Number(hour))}:${pad(Number(min))}` : DEFAULT_TIME;
+ return { frequency: 'custom', time, days: parseDow(fields[4]) };
+}
+
+// Assemble a cron string from the form state.
+function buildCron(frequency, time, days) {
+ if (frequency === 'daily') return DAILY_CRON;
+ if (frequency === 'weekly') return WEEKLY_CRON;
+
+ const [hour = '02', min = '00'] = (time || DEFAULT_TIME).split(':');
+ const dowField =
+ days.length > 0 && days.length < 7
+ ? days.slice().sort((a, b) => a - b).join(',')
+ : '*';
+ return `${Number(min)} ${Number(hour)} * * ${dowField}`;
+}
+
+const ScheduleCard = ({ policy, remoteConfigured, onSave, saving }) => {
+ const initial = deriveFromCron(policy.schedule_cron);
+
+ const [frequency, setFrequency] = useState(initial.frequency);
+ const [time, setTime] = useState(initial.time);
+ const [days, setDays] = useState(initial.days);
+ const [retentionCount, setRetentionCount] = useState(String(policy.retention_count));
+ const [retentionDays, setRetentionDays] = useState(String(policy.retention_days));
+ const [fullEvery, setFullEvery] = useState(String(policy.full_every_n_days));
+ const [compression, setCompression] = useState(policy.compression);
+ const [remoteCopy, setRemoteCopy] = useState(!!policy.remote_copy);
+
+ // Re-seed the form when the saved policy changes (e.g. external reload after
+ // a successful save). Keyed on the persisted values so it only fires when
+ // the source of truth actually moves, not on every render.
+ useEffect(() => {
+ const next = deriveFromCron(policy.schedule_cron);
+ setFrequency(next.frequency);
+ setTime(next.time);
+ setDays(next.days);
+ setRetentionCount(String(policy.retention_count));
+ setRetentionDays(String(policy.retention_days));
+ setFullEvery(String(policy.full_every_n_days));
+ setCompression(policy.compression);
+ setRemoteCopy(!!policy.remote_copy);
+ }, [
+ policy.schedule_cron,
+ policy.retention_count,
+ policy.retention_days,
+ policy.full_every_n_days,
+ policy.compression,
+ policy.remote_copy,
+ ]);
+
+ const currentCron = useMemo(() => buildCron(frequency, time, days), [frequency, time, days]);
+
+ const toggleDay = (i) => {
+ setDays((prev) =>
+ prev.includes(i) ? prev.filter((d) => d !== i) : [...prev, i].sort((a, b) => a - b)
+ );
+ };
+
+ // The form is dirty when any field diverges from the saved policy. Numeric
+ // fields are compared via toNum so an empty box reads as the floor (= what
+ // would actually be persisted), avoiding a phantom-dirty Save button.
+ const dirty =
+ currentCron !== policy.schedule_cron ||
+ toNum(retentionCount) !== policy.retention_count ||
+ toNum(retentionDays) !== policy.retention_days ||
+ toNum(fullEvery) !== policy.full_every_n_days ||
+ compression !== policy.compression ||
+ remoteCopy !== !!policy.remote_copy;
+
+ const handleSave = () => {
+ onSave({
+ schedule_cron: currentCron,
+ retention_count: toNum(retentionCount),
+ retention_days: toNum(retentionDays),
+ full_every_n_days: toNum(fullEvery),
+ compression,
+ remote_copy: remoteCopy,
+ });
+ };
+
+ return (
+ <div className="app-panel schedule-card">
+ <div className="app-panel-header">
+ <Calendar size={16} />
+ <span>Schedule</span>
+ <span className="app-panel-header-actions app-panel-hint">
+ Backups run quietly in the background.
+ </span>
+ </div>
+ <div className="app-panel-body">
+ <div className="schedule-card__field">
+ <label>Frequency</label>
+ <SegControl
+ options={[
+ { value: 'daily', label: 'Daily' },
+ { value: 'weekly', label: 'Weekly' },
+ { value: 'custom', label: 'Custom' },
+ ]}
+ value={frequency}
+ onChange={setFrequency}
+ />
+ </div>
+
+ {frequency === 'custom' && (
+ <>
+ <div className="schedule-card__field">
+ <label>Time</label>
+ <Input type="time" value={time} onChange={(e) => setTime(e.target.value)} />
+ </div>
+ <div className="schedule-card__field">
+ <label>Days</label>
+ <div className="schedule-card__days">
+ {DOW_LABELS.map((d, i) => (
+ <button
+ type="button"
+ key={i}
+ className={`schedule-card__day ${days.includes(i) ? 'is-active' : ''}`}
+ onClick={() => toggleDay(i)}
+ >
+ {d}
+ </button>
+ ))}
+ </div>
+ </div>
+ </>
+ )}
+
+ <div className="schedule-card__preview">
+ <span className="schedule-card__preview-label">Cron</span>
+ <code>{currentCron}</code>
+ </div>
+
+ <div className="schedule-card__field schedule-card__retention">
+ <label>Retention</label>
+ <div className="schedule-card__retention-row">
+ <span>Keep last</span>
+ <Input
+ type="number"
+ min={MIN_COUNT}
+ value={retentionCount}
+ onChange={(e) => setRetentionCount(e.target.value)}
+ />
+ <span>backups</span>
+ </div>
+ <div className="schedule-card__retention-row">
+ <span>Delete older than</span>
+ <Input
+ type="number"
+ min={MIN_COUNT}
+ value={retentionDays}
+ onChange={(e) => setRetentionDays(e.target.value)}
+ />
+ <span>days</span>
+ </div>
+ <p className="app-panel-hint">
+ Both rules apply. A backup is kept only if it is within the last N backups AND
+ within the last N days.
+ </p>
+ </div>
+
+ <div className="schedule-card__field">
+ <label>Full backup every</label>
+ <div className="schedule-card__retention-row">
+ <Input
+ type="number"
+ min={MIN_COUNT}
+ value={fullEvery}
+ onChange={(e) => setFullEvery(e.target.value)}
+ />
+ <span>days</span>
+ </div>
+ <p className="app-panel-hint">
+ A full backup is taken every N days; the rest are incremental.
+ </p>
+ </div>
+
+ <div className="schedule-card__field">
+ <label>Compression</label>
+ <SegControl
+ options={[
+ { value: 'fast', label: 'Fast' },
+ { value: 'balanced', label: 'Balanced' },
+ { value: 'max', label: 'Max' },
+ ]}
+ value={compression}
+ onChange={setCompression}
+ />
+ </div>
+
+ <div className="schedule-card__field schedule-card__remote">
+ <Switch
+ id="remote-copy"
+ checked={remoteCopy}
+ onCheckedChange={setRemoteCopy}
+ disabled={!remoteConfigured}
+ />
+ <label htmlFor="remote-copy">
+ <span>Copy backups to remote storage</span>
+ <span className="app-panel-hint">
+ {remoteConfigured
+ ? 'Uses the provider configured in Backups → Storage.'
+ : 'No remote storage configured. Set one up in Backups → Storage.'}
+ </span>
+ </label>
+ </div>
+
+ <div className="schedule-card__actions">
+ <Button
+ variant="primary"
+ size="sm"
+ disabled={!dirty || saving}
+ onClick={handleSave}
+ >
+ {saving ? <Loader2 size={14} className="spin" /> : <Save size={14} />}
+ Save schedule
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default ScheduleCard;
diff --git a/frontend/src/components/backups/format.js b/frontend/src/components/backups/format.js
new file mode 100644
index 00000000..174ab1fa
--- /dev/null
+++ b/frontend/src/components/backups/format.js
@@ -0,0 +1,65 @@
+// Shared formatting helpers for the backup "Protection" components.
+import { timeAgo } from '@/utils/timeAgo';
+
+const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
+
+// Human-readable byte size, e.g. "2.3 GB". Matches the global Backups page style.
+export function humanSize(bytes) {
+ if (!bytes || bytes < 0) return '0 B';
+ let size = bytes;
+ let i = 0;
+ while (size >= 1024 && i < UNITS.length - 1) {
+ size /= 1024;
+ i += 1;
+ }
+ return `${size.toFixed(1)} ${UNITS[i]}`;
+}
+
+// Money like "$0.04" / "$1.20"; falls back to 4 decimals for sub-cent values.
+export function formatMoney(value) {
+ const n = Number(value || 0);
+ if (n === 0 || n >= 0.01) return `$${n.toFixed(2)}`;
+ return `$${n.toFixed(4)}`;
+}
+
+// "Jan 15, 2026 · 4h ago" — absolute date plus a compact relative suffix.
+export function formatWhen(iso) {
+ if (!iso) return '—';
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return '—';
+ const date = d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
+ const rel = timeAgo(iso); // 'just now' | '4h' | '2d' | locale date
+ if (rel === 'just now') return `${date} · just now`;
+ if (/^\d+[mhd]$/.test(rel)) return `${date} · ${rel} ago`;
+ return date;
+}
+
+// "Jan 15, 2026, 02:00 AM"
+export function formatDateTime(iso) {
+ if (!iso) return '—';
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return '—';
+ return d.toLocaleString(undefined, {
+ month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit',
+ });
+}
+
+// Pill kind ('green'|'amber'|'red'|'cyan'|'gray') for a run/policy status.
+export function statusKind(status) {
+ switch (status) {
+ case 'success': return 'green';
+ case 'failed': return 'red';
+ case 'running': return 'cyan';
+ case 'verifying': return 'gray';
+ default: return 'gray';
+ }
+}
+
+// Where a run is stored, from its size/remote fields.
+export function storageLabel(run) {
+ const hasRemote = !!run.remote_key || (run.size_remote || 0) > 0;
+ const hasLocal = !!run.storage_path || (run.size_local || 0) > 0;
+ if (hasLocal && hasRemote) return 'both';
+ if (hasRemote) return 'remote';
+ return 'local';
+}
diff --git a/frontend/src/components/service-detail/SettingsTab.jsx b/frontend/src/components/service-detail/SettingsTab.jsx
index f5124c5b..38738f3d 100644
--- a/frontend/src/components/service-detail/SettingsTab.jsx
+++ b/frontend/src/components/service-detail/SettingsTab.jsx
@@ -7,6 +7,7 @@ import {
Globe,
Lock,
Shield,
+ Archive,
CircleCheck,
CircleX,
Sparkles,
@@ -15,6 +16,7 @@ import api from '../../services/api';
import { useToast } from '../../contexts/ToastContext';
import { DangerZone } from '../DangerZone';
import RepoConnectForm from '../git/RepoConnectForm';
+import ProtectionPanel from '../backups/ProtectionPanel';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
@@ -35,6 +37,7 @@ const SVC_SETTINGS_GROUPS = [
],
},
{ label: 'Connections', items: [{ id: 'git', label: 'Git', icon: GitBranch }] },
+ { label: 'Data', items: [{ id: 'backups', label: 'Backups', icon: Archive }] },
{ label: 'Advanced', items: [{ id: 'danger', label: 'Danger Zone', icon: AlertTriangle }] },
];
@@ -266,6 +269,20 @@ const SettingsTab = ({ app, deployConfig, domains, primaryDomain, onUpdate }) =>
</div>
)}
+ {/* Backups — the shared Protection panel (scheduled backups,
+ cost, one-click restore), same component the WordPress
+ detail page renders. */}
+ {section === 'backups' && (
+ <div className="svc-settings__section">
+ <h3 className="svc-settings__section-title">Backups</h3>
+ <ProtectionPanel
+ targetType="application"
+ targetId={app.id}
+ targetName={app.name}
+ />
+ </div>
+ )}
+
{/* Danger Zone */}
{section === 'danger' && (
<div className="svc-settings__section">
diff --git a/frontend/src/pages/Backups.jsx b/frontend/src/pages/Backups.jsx
index 6d158037..ccc2f420 100644
--- a/frontend/src/pages/Backups.jsx
+++ b/frontend/src/pages/Backups.jsx
@@ -1,6 +1,6 @@
import { useState, useEffect } from 'react';
import useTabParam from '../hooks/useTabParam';
-import { Upload, Check, AlertTriangle, Clock, Database, Package, FolderArchive, HardDrive, Cloud, CloudOff, RefreshCw, Trash2, Plus, CheckCircle, XCircle, FileArchive } from 'lucide-react';
+import { Upload, Check, AlertTriangle, Clock, Database, Package, FolderArchive, HardDrive, Cloud, CloudOff, RefreshCw, Trash2, Plus, CheckCircle, XCircle, FileArchive, DollarSign, TrendingUp } from 'lucide-react';
import api from '../services/api';
import { useToast } from '../contexts/ToastContext';
import { useConfirm } from '../hooks/useConfirm';
@@ -25,6 +25,7 @@ const Backups = () => {
const [schedules, setSchedules] = useState([]);
const [config, setConfig] = useState(null);
const [storageConfig, setStorageConfig] = useState(null);
+ const [costSummary, setCostSummary] = useState(null);
const [apps, setApps] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
@@ -69,6 +70,10 @@ const Backups = () => {
retention_days: 30
});
+ // Cost rates form state ($/GB/month). Local is the operator's own server disk.
+ const [ratesForm, setRatesForm] = useState({ local: 0, s3: 0.023, b2: 0.006 });
+ const [savingRates, setSavingRates] = useState(false);
+
// Storage config form state
const [storageForm, setStorageForm] = useState({
provider: 'local',
@@ -85,13 +90,15 @@ const Backups = () => {
const loadData = async () => {
try {
setLoading(true);
- const [backupsRes, statsRes, schedulesRes, configRes, appsRes, storageRes] = await Promise.all([
+ const [backupsRes, statsRes, schedulesRes, configRes, appsRes, storageRes, costRes, ratesRes] = await Promise.all([
api.getBackups(),
api.getBackupStats(),
api.getBackupSchedules(),
api.getBackupConfig(),
api.getApps(),
- api.getStorageConfig().catch(() => null)
+ api.getStorageConfig().catch(() => null),
+ api.getBackupCostSummary().catch(() => null),
+ api.getBackupCostRates().catch(() => null)
]);
setBackups(backupsRes.backups || []);
@@ -99,12 +106,21 @@ const Backups = () => {
setSchedules(schedulesRes.schedules || []);
setConfig(configRes);
setApps(appsRes.applications || []);
+ setCostSummary(costRes || null);
if (storageRes) {
setStorageConfig(storageRes);
setStorageForm(storageRes);
}
+ if (ratesRes?.rates) {
+ setRatesForm({
+ local: ratesRes.rates.local ?? 0,
+ s3: ratesRes.rates.s3 ?? 0,
+ b2: ratesRes.rates.b2 ?? 0
+ });
+ }
+
if (configRes) {
setConfigForm({
enabled: configRes.enabled || false,
@@ -258,6 +274,25 @@ const Backups = () => {
}
};
+ const handleSaveRates = async (e) => {
+ e.preventDefault();
+ setSavingRates(true);
+ try {
+ await api.updateBackupCostRates({
+ local: Number(ratesForm.local) || 0,
+ s3: Number(ratesForm.s3) || 0,
+ b2: Number(ratesForm.b2) || 0
+ });
+ toast.success('Storage cost rates saved');
+ const summary = await api.getBackupCostSummary().catch(() => null);
+ setCostSummary(summary || null);
+ } catch (err) {
+ toast.error(err.message);
+ } finally {
+ setSavingRates(false);
+ }
+ };
+
const handleSaveStorageConfig = async (e) => {
e.preventDefault();
try {
@@ -339,6 +374,11 @@ const Backups = () => {
return new Date(timestamp).toLocaleString();
};
+ const formatMoney = (n) => {
+ const v = Number(n || 0);
+ return v === 0 || v >= 0.01 ? `$${v.toFixed(2)}` : `$${v.toFixed(4)}`;
+ };
+
const getBackupIcon = (type) => {
switch (type) {
case 'application': return <Package size={16} />;
@@ -408,6 +448,12 @@ const Backups = () => {
)}
</MetricCard>
)}
+ <MetricCard tone="green" icon={<DollarSign size={16} />} value={formatMoney(costSummary?.total_cost ?? 0)} label="Est. storage cost / mo">
+ {costSummary?.total_cost_local === 0 && (
+ <div className="sk-kpi__sub"><span>local disk is free</span></div>
+ )}
+ </MetricCard>
+ <MetricCard tone="amber" icon={<TrendingUp size={16} />} value={formatMoney(costSummary?.projected_monthly_cost ?? 0)} label="Projected at full retention" />
</div>
{activeTab === 'backups' && (
@@ -445,9 +491,11 @@ const Backups = () => {
<tr>
<th>Name</th>
<th>Type</th>
+ <th>Site/Service</th>
<th>Size</th>
<th>Storage</th>
<th>Created</th>
+ <th>Cost</th>
<th aria-label="Actions" />
</tr>
</thead>
@@ -465,9 +513,11 @@ const Backups = () => {
<td>
<span className={`bk-type bk-type--${backup.type}`}>{backup.type}</span>
</td>
+ <td>{backup.app_name || backup.name?.split('_')[0] || '—'}</td>
<td className="sk-cell-mono">{formatSize(backup.size)}</td>
<td>{getRemoteStatusPill(backup.remote_status)}</td>
<td className="bk-when">{formatTimestamp(backup.timestamp)}</td>
+ <td className="sk-cell-mono">{formatMoney(((backup.size || 0) / (1024 ** 3)) * (costSummary?.cost_rates?.local || 0))}</td>
<td>
<div className="bk-actions">
{backup.type !== 'files' && (
@@ -876,6 +926,61 @@ const Backups = () => {
</form>
</div>
</div>
+
+ <div className="card">
+ <div className="card-header">
+ <h3>Storage cost rates</h3>
+ </div>
+ <div className="card-body">
+ <p className="form-help">
+ ServerKit is free &mdash; these are your own storage costs. Local is your server disk
+ (leave at 0 if you don&apos;t track it). S3/B2 are your cloud provider&apos;s $/GB/month.
+ </p>
+ <form onSubmit={handleSaveRates}>
+ <FormRow>
+ <FormField label="Local ($/GB/month)" htmlFor="rate-local" hint="Your server disk — usually free">
+ <Input
+ id="rate-local"
+ type="number"
+ min={0}
+ step="0.001"
+ value={ratesForm.local}
+ onChange={(e) => setRatesForm({...ratesForm, local: e.target.value})}
+ />
+ </FormField>
+ <FormField label="S3 ($/GB/month)" htmlFor="rate-s3">
+ <Input
+ id="rate-s3"
+ type="number"
+ min={0}
+ step="0.001"
+ value={ratesForm.s3}
+ onChange={(e) => setRatesForm({...ratesForm, s3: e.target.value})}
+ />
+ </FormField>
+ <FormField label="B2 ($/GB/month)" htmlFor="rate-b2">
+ <Input
+ id="rate-b2"
+ type="number"
+ min={0}
+ step="0.001"
+ value={ratesForm.b2}
+ onChange={(e) => setRatesForm({...ratesForm, b2: e.target.value})}
+ />
+ </FormField>
+ </FormRow>
+ <div className="form-actions">
+ <Button type="submit" disabled={savingRates}>
+ {savingRates ? (
+ <><RefreshCw size={16} className="spinning" /> Saving...</>
+ ) : (
+ <><DollarSign size={16} /> Save rates</>
+ )}
+ </Button>
+ </div>
+ </form>
+ </div>
+ </div>
</>
)}
diff --git a/frontend/src/pages/WordPressDetail.jsx b/frontend/src/pages/WordPressDetail.jsx
index 36d0c1e7..05bc3297 100644
--- a/frontend/src/pages/WordPressDetail.jsx
+++ b/frontend/src/pages/WordPressDetail.jsx
@@ -8,6 +8,7 @@ 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';
@@ -554,7 +555,7 @@ const WordPressDetail = () => {
{activeTab === 'plugins' && <PluginsTab siteId={site.id} />}
{activeTab === 'themes' && <ThemesTab siteId={site.id} />}
{activeTab === 'git' && <GitTab siteId={site.id} site={site} onUpdate={loadSite} />}
- {activeTab === 'backups' && <BackupsTab siteId={site.id} />}
+ {activeTab === 'backups' && <BackupsTab siteId={site.id} site={site} />}
{activeTab === 'uptime' && <UptimeTab siteId={site.id} />}
{activeTab === 'analytics' && <AnalyticsTab siteId={site.id} />}
{activeTab === 'vulnerabilities' && <VulnerabilitiesTab siteId={site.id} />}
@@ -3641,86 +3642,17 @@ const GitTab = ({ siteId, site, onUpdate }) => {
};
// Backups Tab
-const BackupsTab = ({ siteId }) => {
- const toast = useToast();
- const [snapshots, setSnapshots] = useState([]);
- const [loading, setLoading] = useState(true);
-
- useEffect(() => {
- loadSnapshots();
- }, [siteId]);
-
- async function loadSnapshots() {
- try {
- const data = await wordpressApi.getSnapshots(siteId);
- // Filter for backup-tagged snapshots
- setSnapshots((data.snapshots || []).filter(s => s.tag?.includes('backup')));
- } catch (err) {
- console.error('Failed to load backups:', err);
- } finally {
- setLoading(false);
- }
- }
-
- async function handleCreateBackup() {
- try {
- await wordpressApi.createSnapshot(siteId, {
- name: `Backup ${new Date().toISOString().split('T')[0]}`,
- tag: 'backup',
- description: 'Full site backup'
- });
- toast.success('Backup created');
- loadSnapshots();
- } catch (err) {
- toast.error(err.message || 'Failed to create backup');
- }
- }
-
- async function handleRestore(snapId) {
- try {
- await wordpressApi.restoreSnapshot(siteId, snapId);
- toast.success('Backup restored');
- } catch (err) {
- toast.error(err.message || 'Failed to restore backup');
- }
- }
-
- async function handleDelete(snapId) {
- try {
- await wordpressApi.deleteSnapshot(siteId, snapId);
- toast.success('Backup deleted');
- loadSnapshots();
- } catch (err) {
- toast.error(err.message || 'Failed to delete backup');
- }
- }
-
- return (
- <div className="backups-tab">
- <div className="section-header">
- <h3>Backups</h3>
- <Button onClick={handleCreateBackup}>
- <Plus size={14} /> Create Backup
- </Button>
- </div>
-
- {snapshots.length === 0 && !loading ? (
- <EmptyState
- icon={Archive}
- title="No backups yet"
- description="Create a backup to protect your site files and database."
- />
- ) : (
- <SnapshotTable
- snapshots={snapshots}
- loading={loading}
- onRestore={handleRestore}
- onDelete={handleDelete}
- />
- )}
- </div>
- );
-};
+// 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
@@ -3896,7 +3828,7 @@ const WP_SETTINGS_GROUPS = [
{ 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} /> },
+ { 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} /> },
diff --git a/frontend/src/services/api/backupProtection.js b/frontend/src/services/api/backupProtection.js
new file mode 100644
index 00000000..a2489801
--- /dev/null
+++ b/frontend/src/services/api/backupProtection.js
@@ -0,0 +1,48 @@
+// Backup "Protection" policy + runs API.
+//
+// Generic over the target so the shared ProtectionPanel can drive both
+// WordPress sites and applications with one set of methods. The backend mounts
+// the same endpoint shapes under /wordpress/sites/:id and /apps/:id.
+
+function policyBase(targetType, targetId) {
+ return targetType === 'wordpress_site'
+ ? `/wordpress/sites/${targetId}/backup-policy`
+ : `/apps/${targetId}/backup-policy`;
+}
+
+function runsBase(targetType, targetId) {
+ return targetType === 'wordpress_site'
+ ? `/wordpress/sites/${targetId}/backups`
+ : `/apps/${targetId}/backups`;
+}
+
+export async function getBackupPolicy(targetType, targetId) {
+ return this.request(policyBase(targetType, targetId));
+}
+
+export async function updateBackupPolicy(targetType, targetId, policy) {
+ return this.request(policyBase(targetType, targetId), { method: 'PUT', body: policy });
+}
+
+export async function triggerBackup(targetType, targetId) {
+ return this.request(runsBase(targetType, targetId), { method: 'POST' });
+}
+
+export async function getBackupRuns(targetType, targetId) {
+ return this.request(runsBase(targetType, targetId));
+}
+
+export async function restoreBackupRun(targetType, targetId, runId, options) {
+ return this.request(`${runsBase(targetType, targetId)}/${runId}/restore`, {
+ method: 'POST',
+ body: options || {},
+ });
+}
+
+export async function verifyBackupRun(targetType, targetId, runId) {
+ return this.request(`${runsBase(targetType, targetId)}/${runId}/verify`, { method: 'POST' });
+}
+
+export async function deleteBackupRun(targetType, targetId, runId) {
+ return this.request(`${runsBase(targetType, targetId)}/${runId}`, { method: 'DELETE' });
+}
diff --git a/frontend/src/services/api/index.js b/frontend/src/services/api/index.js
index ad239962..7c2d6ea3 100644
--- a/frontend/src/services/api/index.js
+++ b/frontend/src/services/api/index.js
@@ -22,6 +22,7 @@ import * as queueBusMethods from './queueBus.js';
import * as notificationMethods from './notifications.js';
import * as telemetryMethods from './telemetry.js';
import * as jobMethods from './jobs.js';
+import * as backupProtectionMethods from './backupProtection.js';
class ApiService extends ApiClient {
constructor() {
@@ -51,6 +52,7 @@ class ApiService extends ApiClient {
notificationMethods,
telemetryMethods,
jobMethods,
+ backupProtectionMethods,
];
for (const mod of modules) {
for (const [key, fn] of Object.entries(mod)) {
diff --git a/frontend/src/services/api/system.js b/frontend/src/services/api/system.js
index 4dc7641a..d11676ae 100644
--- a/frontend/src/services/api/system.js
+++ b/frontend/src/services/api/system.js
@@ -454,6 +454,20 @@ export async function getBackupConfig() {
return this.request('/backups/config');
}
+// Storage-cost rates ($/GB/month): local = your server disk (free by default),
+// s3/b2 = your real cloud-provider rate.
+export async function getBackupCostRates() {
+ return this.request('/backups/cost-rates');
+}
+
+export async function updateBackupCostRates(rates) {
+ return this.request('/backups/cost-rates', { method: 'PUT', body: { rates } });
+}
+
+export async function getBackupCostSummary() {
+ return this.request('/backups/cost-summary');
+}
+
export async function updateBackupConfig(config) {
return this.request('/backups/config', {
method: 'PUT',
diff --git a/frontend/src/styles/pages/_backups.scss b/frontend/src/styles/pages/_backups.scss
index 335fa890..aa8e04cb 100644
--- a/frontend/src/styles/pages/_backups.scss
+++ b/frontend/src/styles/pages/_backups.scss
@@ -310,3 +310,423 @@
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
+
+// Reusable inline spinner for the protection components (lucide <Loader2 className="spin" />).
+.spin { animation: spin 1s linear infinite; }
+
+// ============================================
+// PROTECTION PANEL (backup protection — WordPress + Services settings)
+// Rendered inside .app-overview-grid > .app-overview-left, so these styles are
+// top-level (not nested under .backups-page).
+// ============================================
+.protection-panel {
+ // Single column inside a settings pane (no right rail).
+ grid-template-columns: 1fr;
+
+ .app-overview-left {
+ display: flex;
+ flex-direction: column;
+ gap: $space-4;
+ }
+}
+
+// ── Card 1: status ──────────────────────────────────────────
+.protection-status-card {
+ &__toggle {
+ display: flex;
+ align-items: flex-start;
+ gap: $space-3;
+ padding-bottom: $space-4;
+ border-bottom: 1px solid var(--border-soft);
+
+ label {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ cursor: pointer;
+ }
+ }
+
+ &__toggle-title { font-weight: $font-weight-semibold; color: var(--text); }
+ &__toggle-sub { font-size: 12px; color: var(--text-faint); }
+
+ &__status {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: $space-2;
+ margin: $space-4 0;
+ font-size: 13px;
+ color: var(--text-dim);
+ }
+
+ &__kpis {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
+ gap: $space-3;
+ margin-bottom: $space-4;
+
+ @media (max-width: $breakpoint-sm) { grid-template-columns: 1fr; }
+ }
+
+ &__actions {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: $space-2;
+ }
+}
+
+// ── Card 2: schedule ────────────────────────────────────────
+.schedule-card {
+ .app-panel-body {
+ display: flex;
+ flex-direction: column;
+ gap: $space-4;
+ }
+
+ &__field {
+ display: flex;
+ flex-direction: column;
+ gap: $space-2;
+
+ > label {
+ font-size: 12px;
+ font-weight: $font-weight-semibold;
+ color: var(--text);
+ }
+ }
+
+ &__days {
+ display: flex;
+ gap: $space-2;
+ }
+
+ &__day {
+ width: 32px;
+ height: 32px;
+ border: 1px solid var(--border-soft);
+ background: var(--surface-2);
+ color: var(--text-dim);
+ border-radius: $radius-sm;
+ font-size: 12px;
+ font-weight: $font-weight-semibold;
+ cursor: pointer;
+ transition: border-color .12s ease, background .12s ease, color .12s ease;
+
+ &:hover { border-color: var(--accent-bright); }
+
+ &.is-active {
+ background: var(--accent-bg);
+ color: var(--accent-bright);
+ border-color: var(--accent-bright);
+ }
+ }
+
+ &__preview {
+ display: flex;
+ align-items: center;
+ gap: $space-2;
+
+ code {
+ font-family: var(--mono);
+ font-size: 12px;
+ color: var(--text);
+ background: var(--surface-2);
+ border: 1px solid var(--border-soft);
+ border-radius: $radius-sm;
+ padding: 2px 8px;
+ }
+ }
+
+ &__preview-label {
+ font-family: var(--mono);
+ font-size: 10.5px;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ color: var(--text-faint);
+ }
+
+ &__retention-row {
+ display: flex;
+ align-items: center;
+ gap: $space-2;
+ font-size: 13px;
+ color: var(--text-dim);
+
+ input { width: 80px; }
+ }
+
+ &__remote {
+ flex-direction: row;
+ align-items: flex-start;
+ gap: $space-3;
+
+ label {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ cursor: pointer;
+ }
+ }
+
+ &__actions { margin-top: $space-1; }
+}
+
+// ── Card 3: history list ────────────────────────────────────
+.backup-history-list {
+ width: 100%;
+
+ &__row.is-clickable { cursor: pointer; }
+
+ &__ico {
+ display: inline-flex;
+ color: var(--text-faint);
+ }
+
+ &__when {
+ color: var(--text-dim);
+ font-size: 13px;
+ white-space: nowrap;
+ }
+
+ &__actions {
+ display: flex;
+ justify-content: flex-end;
+ gap: $space-1;
+ }
+
+ &__storage {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ font-size: 12px;
+ color: var(--text-dim);
+ }
+}
+
+// ── History card chrome (list/calendar toggle + day-filter chip) ────
+.backup-history-card {
+ &__tools {
+ display: flex;
+ align-items: center;
+ gap: $space-2;
+ }
+
+ &__toggle {
+ display: inline-flex;
+ border: 1px solid var(--border-soft);
+ border-radius: $radius-sm;
+ overflow: hidden;
+
+ button {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 28px;
+ height: 26px;
+ background: var(--surface-2);
+ color: var(--text-dim);
+ border: none;
+ cursor: pointer;
+
+ &.is-active { background: var(--accent-bg); color: var(--accent-bright); }
+ & + button { border-left: 1px solid var(--border-soft); }
+ }
+ }
+
+ &__chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ padding: 2px 8px;
+ font-size: 12px;
+ color: var(--text-dim);
+ background: var(--surface-2);
+ border: 1px solid var(--border-soft);
+ border-radius: $radius-full;
+ cursor: pointer;
+
+ &:hover { color: var(--text); }
+ }
+}
+
+// ── Calendar view ───────────────────────────────────────────
+.backup-calendar {
+ &__head {
+ display: flex;
+ align-items: center;
+ gap: $space-2;
+ margin-bottom: $space-3;
+ }
+
+ &__month {
+ flex: 1;
+ font-weight: $font-weight-semibold;
+ color: var(--text);
+ }
+
+ &__nav,
+ &__today {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ height: 28px;
+ padding: 0 $space-2;
+ background: var(--surface-2);
+ border: 1px solid var(--border-soft);
+ border-radius: $radius-sm;
+ color: var(--text-dim);
+ cursor: pointer;
+
+ &:hover { border-color: var(--accent-bright); color: var(--text); }
+ }
+
+ &__grid {
+ display: grid;
+ grid-template-columns: repeat(7, 1fr);
+ gap: $space-1;
+ }
+
+ &__dow {
+ text-align: center;
+ font-family: var(--mono);
+ font-size: 10px;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ color: var(--text-faint);
+ padding-bottom: $space-1;
+ }
+
+ &__cell {
+ position: relative;
+ aspect-ratio: 1 / 1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ border: 1px solid var(--border-soft);
+ border-radius: $radius-sm;
+ background: var(--surface-2);
+ color: var(--text-dim);
+ font-size: 12px;
+
+ &--empty { background: transparent; border-color: transparent; }
+
+ &--has {
+ cursor: pointer;
+
+ &:hover { border-color: var(--accent-bright); }
+ &.is-success { border-color: var(--green); background: var(--green-bg); }
+ &.is-failed { border-color: var(--red); background: var(--red-bg); }
+ &.is-running { border-color: var(--cyan); background: var(--cyan-bg); }
+ }
+ }
+
+ &__badge {
+ position: absolute;
+ top: 2px;
+ right: 3px;
+ font-size: 9px;
+ font-weight: $font-weight-semibold;
+ color: var(--text-faint);
+ }
+}
+
+// ── Detail drawer ───────────────────────────────────────────
+.backup-detail-drawer {
+ display: flex;
+ flex-direction: column;
+ gap: $space-4;
+
+ &__error {
+ padding: $space-2 $space-3;
+ font-size: 13px;
+ color: var(--red);
+ background: var(--red-bg);
+ border: 1px solid var(--border-soft);
+ border-radius: $radius-sm;
+ }
+
+ &__meta {
+ display: grid;
+ gap: $space-1;
+ }
+
+ &__row {
+ display: flex;
+ justify-content: space-between;
+ gap: $space-3;
+ padding: 6px 0;
+ border-bottom: 1px solid var(--border-soft);
+ font-size: 13px;
+
+ span:first-child { color: var(--text-faint); }
+ span:last-child { color: var(--text); }
+ }
+
+ &__cost {
+ font-size: 13px;
+ color: var(--text-dim);
+ font-family: var(--mono);
+ }
+
+ &__actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: $space-2;
+ }
+
+ &__joblink {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ font-size: 13px;
+ color: var(--accent-bright);
+ }
+}
+
+// ── Restore drawer ──────────────────────────────────────────
+.restore-drawer {
+ display: flex;
+ flex-direction: column;
+ gap: $space-4;
+
+ &__section { display: flex; flex-direction: column; gap: $space-2; }
+ &__label { font-size: 12px; font-weight: $font-weight-semibold; color: var(--text); }
+
+ &__tables {
+ display: flex;
+ flex-direction: column;
+ gap: $space-1;
+ max-height: 180px;
+ overflow-y: auto;
+ padding: $space-2;
+ border: 1px solid var(--border-soft);
+ border-radius: $radius-sm;
+
+ label { display: flex; align-items: center; gap: $space-2; font-size: 13px; color: var(--text-dim); }
+ }
+
+ &__options { display: flex; flex-direction: column; gap: $space-3; }
+
+ &__option {
+ display: flex;
+ align-items: flex-start;
+ gap: $space-3;
+
+ label { display: flex; flex-direction: column; font-size: 13px; color: var(--text); cursor: pointer; }
+ }
+
+ &__warning {
+ display: flex;
+ align-items: flex-start;
+ gap: $space-2;
+ padding: $space-2 $space-3;
+ font-size: 13px;
+ color: var(--amber);
+ background: var(--amber-bg);
+ border: 1px solid var(--border-soft);
+ border-radius: $radius-sm;
+ }
+}