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(panel): one-click self-update from the About tab

Juan Denis160bf6dab756
diff --git a/backend/app/api/system.py b/backend/app/api/system.py
index d1edda54..45244a8f 100644
--- a/backend/app/api/system.py
+++ b/backend/app/api/system.py
@@ -104,6 +104,42 @@ def check_update():
return jsonify(result), 200
+@system_bp.route('/update', methods=['GET'])
+@admin_required
+def get_panel_update_status():
+ """Self-update capability + live progress (poll target for the UI).
+
+ Stateless by design: the update restarts this very process, so the answer
+ is rebuilt each call from the transient unit's state and the updater's own
+ log file (see panel_update_service).
+ """
+ from app.services import panel_update_service as svc
+ try:
+ return jsonify(svc.get_status()), 200
+ except Exception as exc: # noqa: BLE001 - reported, not swallowed
+ return unexpected_response(exc)
+
+
+@system_bp.route('/update', methods=['POST'])
+@admin_required
+def start_panel_update():
+ """Launch scripts/update.sh detached from the panel's own systemd unit.
+
+ Body must carry ``{"confirm": true}`` — this restarts the panel backend.
+ """
+ data = request.get_json(silent=True) or {}
+ if data.get('confirm') is not True:
+ raise ValidationError('Confirmation required: pass {"confirm": true}.')
+
+ user = get_current_user()
+ from app.services import panel_update_service as svc
+ result = svc.start_update()
+ _audit('panel.update', user.id, target_type='host', target_id='panel',
+ details={'unit': result['unit'],
+ 'from_version': get_panel_version()})
+ return jsonify(result), 202
+
+
@system_bp.route('/metrics', methods=['GET'])
@jwt_required()
def get_metrics():
diff --git a/backend/app/services/panel_update_service.py b/backend/app/services/panel_update_service.py
new file mode 100644
index 00000000..3222e92a
--- /dev/null
+++ b/backend/app/services/panel_update_service.py
@@ -0,0 +1,185 @@
+"""Panel self-update — run scripts/update.sh from the UI.
+
+The hard parts of updating (blue/green slot switch, DB migration ordering,
+post-switch health check, automatic rollback) already live in
+``scripts/update.sh``. This service deliberately adds none of that; it only
+answers "can this install self-update?", launches the script, and reports
+progress from the script's own log.
+
+The one non-obvious mechanic is *how* the script is launched. The updater
+restarts the ``serverkit`` systemd unit — the very unit this process runs in.
+A plain ``subprocess.Popen`` child lives in that unit's cgroup, so
+``systemctl stop serverkit`` would kill the update mid-flight, exactly at the
+point of no return. ``systemd-run`` starts the script in its own transient
+unit (its own cgroup), so it survives the panel restart it performs.
+
+Status is stateless on purpose: an update restarts this process, so anything
+kept in memory would be lost at the most interesting moment. "Running" is the
+transient unit's state; progress is the tail of the ``update-*.log`` file the
+script already writes. Both survive the restart and are readable by the new
+process.
+"""
+import glob
+import os
+import re
+import shutil
+
+from app.exceptions import ConflictError, ValidationError
+from app.utils.system import run_checked
+from app.utils.version import get_install_dir, get_panel_version
+
+# Fixed transient-unit name: makes "is an update already running" a single
+# systemctl query and guarantees two concurrent starts collide loudly inside
+# systemd instead of racing each other through the updater.
+UPDATE_UNIT = 'serverkit-panel-update'
+
+# Must match LOG_DIR in scripts/update.sh — that is what writes update-*.log.
+LOG_DIR = '/var/log/serverkit'
+
+# Outcome markers printed by scripts/update.sh (see its summary and rollback()).
+_SUCCESS_MARKER = 'Update complete'
+_ROLLBACK_MARKER = 'Rolled back to'
+
+_ANSI_RE = re.compile(r'\x1b\[[0-9;]*[A-Za-z]')
+
+
+# Split out so tests can fake a platform without touching the real ``os``
+# module (a leaked os.name patch takes the whole pytest run down on Windows).
+def _is_windows():
+ return os.name == 'nt'
+
+
+def _in_docker():
+ return os.path.exists('/.dockerenv')
+
+
+def _is_root():
+ return hasattr(os, 'geteuid') and os.geteuid() == 0
+
+
+def get_capability():
+ """Whether — and how — this install can self-update.
+
+ ``mode`` is 'systemd' (one-click works), 'docker' (the panel container
+ cannot replace itself; the operator pulls a new image on the host), or
+ 'unsupported' (dev servers, missing tooling), with ``reason`` saying why.
+ """
+ if _is_windows():
+ return {'supported': False, 'mode': 'unsupported',
+ 'reason': 'Self-update requires a Linux install.'}
+
+ if _in_docker():
+ return {'supported': False, 'mode': 'docker',
+ 'reason': 'The panel runs in a container and cannot replace '
+ 'its own image. Update on the host with: '
+ 'docker compose pull && docker compose up -d'}
+
+ # Prod installs run the panel as root (templates/serverkit-backend.service.in);
+ # anything else is a dev server that must not get a working update button.
+ if not _is_root():
+ return {'supported': False, 'mode': 'unsupported',
+ 'reason': 'The panel is not running as root — this looks like '
+ 'a development server.'}
+
+ script = os.path.join(get_install_dir(), 'scripts', 'update.sh')
+ if not os.path.exists(script):
+ return {'supported': False, 'mode': 'unsupported',
+ 'reason': f'Updater script not found at {script}.'}
+
+ for tool in ('systemd-run', 'systemctl'):
+ if not shutil.which(tool):
+ return {'supported': False, 'mode': 'unsupported',
+ 'reason': f'{tool} not available — self-update needs a '
+ 'systemd host.'}
+
+ return {'supported': True, 'mode': 'systemd', 'reason': None,
+ 'script': script}
+
+
+def is_running():
+ """True while the transient update unit is executing."""
+ result = run_checked(['systemctl', 'is-active', UPDATE_UNIT], timeout=10)
+ # is-active exits non-zero for every state but 'active'; the output is the
+ # state either way. 'activating' covers Type=oneshot-style startup.
+ return result['output'].strip() in ('active', 'activating')
+
+
+def latest_log(max_bytes=8192):
+ """Newest update-*.log the script wrote, with an ANSI-stripped tail.
+
+ Returns None when no update has ever logged. ``outcome`` is a best-effort
+ hint parsed from the tail — 'success', 'rolled_back', or None while the
+ log has neither marker yet.
+ """
+ try:
+ logs = glob.glob(os.path.join(LOG_DIR, 'update-*.log'))
+ if not logs:
+ return None
+ path = max(logs, key=os.path.getmtime)
+ size = os.path.getsize(path)
+ with open(path, 'rb') as fh:
+ if size > max_bytes:
+ fh.seek(size - max_bytes)
+ tail = fh.read().decode('utf-8', errors='replace')
+ except OSError:
+ return None
+
+ tail = _ANSI_RE.sub('', tail)
+ outcome = None
+ if _SUCCESS_MARKER in tail:
+ outcome = 'success'
+ elif _ROLLBACK_MARKER in tail:
+ outcome = 'rolled_back'
+ return {
+ 'path': path,
+ 'mtime': os.path.getmtime(path),
+ 'tail': tail,
+ 'outcome': outcome,
+ }
+
+
+def get_status():
+ """One stateless snapshot the UI can poll before, during and after."""
+ capability = get_capability()
+ status = {
+ 'capability': capability,
+ 'running': False,
+ 'unit': UPDATE_UNIT,
+ 'version': get_panel_version(),
+ 'log': None,
+ }
+ if capability['supported']:
+ status['running'] = is_running()
+ status['log'] = latest_log()
+ return status
+
+
+def start_update():
+ """Launch scripts/update.sh in its own transient systemd unit.
+
+ Raises ValidationError when this install cannot self-update and
+ ConflictError when an update is already in flight.
+ """
+ capability = get_capability()
+ if not capability['supported']:
+ raise ValidationError(capability['reason'])
+ if is_running():
+ raise ConflictError('An update is already running.')
+
+ # A previous failed run can leave the fixed-name unit in 'failed' and make
+ # systemd-run refuse the name. Best-effort clear; harmless when clean.
+ run_checked(['systemctl', 'reset-failed', UPDATE_UNIT], timeout=10)
+
+ result = run_checked([
+ 'systemd-run',
+ '--unit', UPDATE_UNIT,
+ # Unload the unit when it finishes even on failure — outcome lives in
+ # the update-*.log, not in lingering unit state.
+ '--collect',
+ '/bin/bash', capability['script'],
+ ], timeout=30)
+ if not result['success']:
+ raise ValidationError(
+ f"Failed to launch the updater: {result['error'] or result['stderr']}")
+
+ return {'started': True, 'unit': UPDATE_UNIT}
diff --git a/backend/tests/test_panel_update.py b/backend/tests/test_panel_update.py
new file mode 100644
index 00000000..cc7286d4
--- /dev/null
+++ b/backend/tests/test_panel_update.py
@@ -0,0 +1,216 @@
+"""One-click panel self-update — capability gates, launch contract, API.
+
+Everything is faked: no test here touches systemd, the real updater script, or
+/var/log. The interesting contracts are (a) the capability gates that keep the
+button away from installs where the updater would be wrong or dangerous, and
+(b) that the launch goes through systemd-run (its own cgroup) — a plain child
+process would die when the updater restarts the panel's own unit.
+"""
+import os
+
+import pytest
+
+from app.services import panel_update_service as svc
+
+
+def _systemd_box(monkeypatch, tmp_path):
+ """Fake a root systemd install with the updater script present."""
+ script_dir = tmp_path / 'scripts'
+ script_dir.mkdir(parents=True, exist_ok=True)
+ (script_dir / 'update.sh').write_text('#!/bin/bash\n')
+ monkeypatch.setattr(svc, '_is_windows', lambda: False)
+ monkeypatch.setattr(svc, '_in_docker', lambda: False)
+ monkeypatch.setattr(svc, '_is_root', lambda: True)
+ monkeypatch.setattr(svc, 'get_install_dir', lambda: str(tmp_path))
+ monkeypatch.setattr(svc.shutil, 'which', lambda tool: f'/usr/bin/{tool}')
+
+
+# ── Capability gates ─────────────────────────────────────────────────────────
+
+def test_windows_dev_server_is_unsupported(monkeypatch):
+ monkeypatch.setattr(svc, '_is_windows', lambda: True)
+ cap = svc.get_capability()
+ assert cap == {'supported': False, 'mode': 'unsupported',
+ 'reason': 'Self-update requires a Linux install.'}
+
+
+def test_docker_install_reports_docker_mode_with_host_instructions(monkeypatch):
+ monkeypatch.setattr(svc, '_is_windows', lambda: False)
+ monkeypatch.setattr(svc, '_in_docker', lambda: True)
+ cap = svc.get_capability()
+ assert cap['supported'] is False
+ assert cap['mode'] == 'docker'
+ assert 'docker compose pull' in cap['reason']
+
+
+def test_non_root_process_is_unsupported(monkeypatch):
+ monkeypatch.setattr(svc, '_is_windows', lambda: False)
+ monkeypatch.setattr(svc, '_in_docker', lambda: False)
+ monkeypatch.setattr(svc, '_is_root', lambda: False)
+ cap = svc.get_capability()
+ assert cap['supported'] is False
+ assert 'root' in cap['reason']
+
+
+def test_missing_updater_script_is_unsupported(monkeypatch, tmp_path):
+ _systemd_box(monkeypatch, tmp_path)
+ os.remove(tmp_path / 'scripts' / 'update.sh')
+ cap = svc.get_capability()
+ assert cap['supported'] is False
+ assert 'update.sh' in cap['reason']
+
+
+def test_missing_systemd_run_is_unsupported(monkeypatch, tmp_path):
+ _systemd_box(monkeypatch, tmp_path)
+ monkeypatch.setattr(svc.shutil, 'which', lambda tool: None)
+ cap = svc.get_capability()
+ assert cap['supported'] is False
+ assert 'systemd-run' in cap['reason']
+
+
+def test_root_systemd_install_is_supported(monkeypatch, tmp_path):
+ _systemd_box(monkeypatch, tmp_path)
+ cap = svc.get_capability()
+ assert cap['supported'] is True
+ assert cap['mode'] == 'systemd'
+ assert cap['script'] == os.path.join(str(tmp_path), 'scripts', 'update.sh')
+
+
+# ── Launch contract ──────────────────────────────────────────────────────────
+
+def test_start_update_launches_through_systemd_run(monkeypatch, tmp_path):
+ _systemd_box(monkeypatch, tmp_path)
+ monkeypatch.setattr(svc, 'is_running', lambda: False)
+ calls = []
+
+ def fake_run(cmd, **kwargs):
+ calls.append(cmd)
+ return {'success': True, 'output': '', 'stderr': '', 'error': None,
+ 'returncode': 0}
+
+ monkeypatch.setattr(svc, 'run_checked', fake_run)
+ result = svc.start_update()
+
+ assert result == {'started': True, 'unit': svc.UPDATE_UNIT}
+ # reset-failed first (a stale failed unit blocks reusing the name) …
+ assert calls[0][:2] == ['systemctl', 'reset-failed']
+ # … then the actual launch, detached into its own transient unit.
+ launch = calls[1]
+ assert launch[0] == 'systemd-run'
+ assert '--unit' in launch and svc.UPDATE_UNIT in launch
+ assert '--collect' in launch
+ assert launch[-1].endswith('update.sh')
+
+
+def test_start_update_refuses_unsupported_install(monkeypatch):
+ monkeypatch.setattr(svc, '_is_windows', lambda: True)
+ from app.exceptions import ValidationError
+ with pytest.raises(ValidationError):
+ svc.start_update()
+
+
+def test_start_update_refuses_concurrent_run(monkeypatch, tmp_path):
+ _systemd_box(monkeypatch, tmp_path)
+ monkeypatch.setattr(svc, 'is_running', lambda: True)
+ from app.exceptions import ConflictError
+ with pytest.raises(ConflictError):
+ svc.start_update()
+
+
+def test_start_update_surfaces_launch_failure(monkeypatch, tmp_path):
+ _systemd_box(monkeypatch, tmp_path)
+ monkeypatch.setattr(svc, 'is_running', lambda: False)
+ monkeypatch.setattr(svc, 'run_checked', lambda cmd, **kw: {
+ 'success': False, 'output': '', 'stderr': 'unit exists',
+ 'error': 'systemd-run failed', 'returncode': 1})
+ from app.exceptions import ValidationError
+ with pytest.raises(ValidationError, match='systemd-run failed'):
+ svc.start_update()
+
+
+# ── Log parsing ──────────────────────────────────────────────────────────────
+
+def test_latest_log_strips_ansi_and_detects_outcome(monkeypatch, tmp_path):
+ log_dir = tmp_path / 'logs'
+ log_dir.mkdir()
+ monkeypatch.setattr(svc, 'LOG_DIR', str(log_dir))
+
+ (log_dir / 'update-20260830-010101.log').write_text('older run\n')
+ newest = log_dir / 'update-20260831-020202.log'
+ newest.write_text('step one\n\x1b[1m\x1b[32m✔ Update complete\x1b[0m\n',
+ encoding='utf-8')
+ os.utime(log_dir / 'update-20260830-010101.log', (1, 1))
+
+ log = svc.latest_log()
+ assert log['path'] == str(newest)
+ assert '\x1b' not in log['tail']
+ assert log['outcome'] == 'success'
+
+
+def test_latest_log_detects_rollback(monkeypatch, tmp_path):
+ log_dir = tmp_path / 'logs'
+ log_dir.mkdir()
+ monkeypatch.setattr(svc, 'LOG_DIR', str(log_dir))
+ (log_dir / 'update-20260831-030303.log').write_text(
+ 'Rolled back to /opt/serverkit-slots/a and it is healthy.\n')
+ assert svc.latest_log()['outcome'] == 'rolled_back'
+
+
+def test_latest_log_none_when_nothing_logged(monkeypatch, tmp_path):
+ monkeypatch.setattr(svc, 'LOG_DIR', str(tmp_path / 'nope'))
+ assert svc.latest_log() is None
+
+
+# ── API surface ──────────────────────────────────────────────────────────────
+
+def _fake_status():
+ return {'capability': {'supported': True, 'mode': 'systemd',
+ 'reason': None, 'script': '/x/update.sh'},
+ 'running': False, 'unit': svc.UPDATE_UNIT,
+ 'version': '9.9.9', 'log': None}
+
+
+def test_status_requires_admin(client, viewer_headers):
+ response = client.get('/api/v1/system/update', headers=viewer_headers)
+ assert response.status_code == 403
+
+
+def test_status_reports_snapshot(client, auth_headers, monkeypatch):
+ monkeypatch.setattr(svc, 'get_status', _fake_status)
+ response = client.get('/api/v1/system/update', headers=auth_headers)
+ assert response.status_code == 200
+ assert response.get_json()['version'] == '9.9.9'
+
+
+def test_start_requires_admin(client, viewer_headers):
+ response = client.post('/api/v1/system/update', headers=viewer_headers,
+ json={'confirm': True})
+ assert response.status_code == 403
+
+
+def test_start_requires_explicit_confirmation(client, auth_headers):
+ response = client.post('/api/v1/system/update', headers=auth_headers,
+ json={})
+ assert response.status_code == 400
+ assert 'confirm' in response.get_json()['error'].lower()
+
+
+def test_start_launches_and_returns_202(client, auth_headers, monkeypatch):
+ monkeypatch.setattr(svc, 'start_update',
+ lambda: {'started': True, 'unit': svc.UPDATE_UNIT})
+ response = client.post('/api/v1/system/update', headers=auth_headers,
+ json={'confirm': True})
+ assert response.status_code == 202
+ assert response.get_json() == {'started': True, 'unit': svc.UPDATE_UNIT}
+
+
+def test_start_conflict_when_already_running(client, auth_headers, monkeypatch):
+ from app.exceptions import ConflictError
+
+ def boom():
+ raise ConflictError('An update is already running.')
+
+ monkeypatch.setattr(svc, 'start_update', boom)
+ response = client.post('/api/v1/system/update', headers=auth_headers,
+ json={'confirm': True})
+ assert response.status_code == 409
diff --git a/docs/API_SURFACE.md b/docs/API_SURFACE.md
index af76bb0c..f74f3102 100644
--- a/docs/API_SURFACE.md
+++ b/docs/API_SURFACE.md
@@ -668,6 +668,7 @@ Regenerate (backend/):
- `GET /system/services`
- `GET /system/time`
- `GET /system/timezones`
+- `GET /system/update`
- `GET /system/version`
- `GET /telemetry/event-types`
- `GET /telemetry/events`
@@ -1217,6 +1218,7 @@ Regenerate (backend/):
- `POST /sso/saml/callback`
- `POST /support-bundle`
- `POST /system/disk/reclaim`
+- `POST /system/update`
- `POST /telemetry/events/test`
- `POST /templates/apps/{app_id}/update`
- `POST /templates/local`
diff --git a/frontend/src/components/settings/AboutTab.jsx b/frontend/src/components/settings/AboutTab.jsx
index 9334c926..1a9e6f1b 100644
--- a/frontend/src/components/settings/AboutTab.jsx
+++ b/frontend/src/components/settings/AboutTab.jsx
@@ -1,8 +1,8 @@
-import { useState, useEffect } from 'react';
+import { useState, useEffect, useRef } from 'react';
import api from '../../services/api';
import {
Github, FileText, HelpCircle, MessageSquare, Bug, Check, Download, CheckCircle,
- RefreshCw, ExternalLink, Star, X
+ RefreshCw, ExternalLink, Star, X, AlertTriangle
} from 'lucide-react';
import ServerKitLogo from '../ServerKitLogo';
import { Button } from '@/components/ui/button';
@@ -19,8 +19,18 @@ const AboutTab = () => {
const [showStarPrompt, setShowStarPrompt] = useState(() => {
return localStorage.getItem(STAR_PROMPT_KEY) !== 'true';
});
+ // One-click self-update. updatePhase: null (idle) | 'confirm' | 'starting'
+ // | 'running' | 'restarting' | 'done' | 'failed' | 'timeout'
+ const [updateStatus, setUpdateStatus] = useState(null);
+ const [updatePhase, setUpdatePhase] = useState(null);
+ const [updateLogTail, setUpdateLogTail] = useState('');
+ const [updatedVersion, setUpdatedVersion] = useState(null);
+ const [updateError, setUpdateError] = useState(null);
+ const cancelledRef = useRef(false);
const register = useSettingFocus();
+ useEffect(() => () => { cancelledRef.current = true; }, []);
+
useEffect(() => {
const fetchVersion = async () => {
try {
@@ -43,12 +53,76 @@ const AboutTab = () => {
try {
const data = await api.checkUpdate();
setUpdateInfo(data);
+ if (data.update_available) {
+ // Admin-only capability probe — a 403 just hides the button.
+ try {
+ setUpdateStatus(await api.getPanelUpdateStatus());
+ } catch {
+ setUpdateStatus(null);
+ }
+ }
} catch (error) {
setUpdateInfo({ error: 'Failed to check for updates' });
}
setCheckingUpdate(false);
};
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+ const runUpdate = async () => {
+ const startVersion = version;
+ setUpdatePhase('starting');
+ setUpdateError(null);
+ setUpdateLogTail('');
+ try {
+ await api.startPanelUpdate();
+ } catch (error) {
+ setUpdatePhase('failed');
+ setUpdateError(error?.message || t('app.aboutTab.updateStartFailed', 'Failed to start the update'));
+ return;
+ }
+ setUpdatePhase('running');
+ const started = Date.now();
+ let notRunningPolls = 0;
+ while (!cancelledRef.current && Date.now() - started < 15 * 60 * 1000) {
+ await sleep(3000);
+ if (cancelledRef.current) return;
+ try {
+ const st = await api.getPanelUpdateStatus();
+ if (st.log?.tail) setUpdateLogTail(st.log.tail);
+ if (st.version && st.version !== startVersion) {
+ // The backend that answered is already the new version.
+ setUpdatedVersion(st.version);
+ setUpdatePhase('done');
+ return;
+ }
+ if (st.running) {
+ notRunningPolls = 0;
+ setUpdatePhase('running');
+ } else {
+ // Grace for the transient unit not being visible yet;
+ // after that, same-version + not-running means it ended
+ // without switching (rollback or early failure).
+ notRunningPolls += 1;
+ if (st.log?.outcome === 'rolled_back') {
+ setUpdatePhase('failed');
+ setUpdateError(t('app.aboutTab.updateRolledBack', 'The update failed and was rolled back — the previous version is still running.'));
+ return;
+ }
+ if (notRunningPolls >= 5) {
+ setUpdatePhase('failed');
+ setUpdateError(t('app.aboutTab.updateDidNotComplete', 'The update ended without changing the version. Check the update log on the server.'));
+ return;
+ }
+ }
+ } catch {
+ // The panel restarts mid-update — unreachable is expected.
+ setUpdatePhase('restarting');
+ }
+ }
+ if (!cancelledRef.current) setUpdatePhase('timeout');
+ };
+
return (
<div className="settings-section">
<div className="section-header">
@@ -86,18 +160,80 @@ const AboutTab = () => {
<button type="button" className="btn-link" onClick={checkForUpdate}>{t('common.actions.retry', 'Retry')}</button>
</div>
) : updateInfo.update_available ? (
- <div className="update-status available">
- <Download size={16} />
- <span>{t('app.aboutTab.updateAvailable', 'Update available:')} <strong>v{updateInfo.latest_version}</strong></span>
- <a
- href={updateInfo.release_url}
- target="_blank"
- rel="noopener noreferrer"
- className="btn btn-accent btn-sm"
- >
- {t('app.aboutTab.viewRelease', 'View Release')} <ExternalLink size={12} />
- </a>
- </div>
+ updatePhase === null || updatePhase === 'confirm' ? (
+ <>
+ <div className="update-status available">
+ <Download size={16} />
+ <span>{t('app.aboutTab.updateAvailable', 'Update available:')} <strong>v{updateInfo.latest_version}</strong></span>
+ <a
+ href={updateInfo.release_url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className={updateStatus?.capability?.supported ? 'btn btn-secondary btn-sm' : 'btn btn-accent btn-sm'}
+ >
+ {t('app.aboutTab.viewRelease', 'View Release')} <ExternalLink size={12} />
+ </a>
+ {updateStatus?.capability?.supported && updatePhase === null && (
+ <Button
+ size="sm"
+ onClick={() => setUpdatePhase('confirm')}
+ disabled={updateStatus?.running}
+ >
+ <Download size={12} /> {t('app.aboutTab.updateNow', 'Update Now')}
+ </Button>
+ )}
+ </div>
+ {updatePhase === 'confirm' && (
+ <div className="update-confirm">
+ <AlertTriangle size={14} />
+ <span>{t('app.aboutTab.updateConfirm', 'This updates ServerKit and briefly restarts the panel. Hosted apps stay online. If the new version fails to start, it rolls back automatically.')}</span>
+ <Button size="sm" onClick={runUpdate}>
+ {t('app.aboutTab.updateNow', 'Update Now')}
+ </Button>
+ <Button variant="outline" size="sm" onClick={() => setUpdatePhase(null)}>
+ {t('common.actions.cancel', 'Cancel')}
+ </Button>
+ </div>
+ )}
+ {updateStatus && !updateStatus.capability?.supported && updateStatus.capability?.reason && (
+ <p className="update-capability-note">{updateStatus.capability.reason}</p>
+ )}
+ </>
+ ) : (
+ <div className="update-progress">
+ {updatePhase === 'done' ? (
+ <div className="update-status current">
+ <CheckCircle size={16} />
+ <span>{t('app.aboutTab.updateComplete', 'Updated to')} <strong>v{updatedVersion}</strong></span>
+ <Button size="sm" onClick={() => window.location.reload()}>
+ <RefreshCw size={12} /> {t('app.aboutTab.reloadPanel', 'Reload Panel')}
+ </Button>
+ </div>
+ ) : updatePhase === 'failed' ? (
+ <div className="update-status error">
+ <AlertTriangle size={16} />
+ <span>{updateError}</span>
+ </div>
+ ) : updatePhase === 'timeout' ? (
+ <div className="update-status error">
+ <AlertTriangle size={16} />
+ <span>{t('app.aboutTab.updateTimeout', 'The update is taking longer than expected. Check the update log on the server before retrying.')}</span>
+ </div>
+ ) : (
+ <div className="update-status running">
+ <RefreshCw size={16} className="spinning" />
+ <span>
+ {updatePhase === 'restarting'
+ ? t('app.aboutTab.updateRestarting', 'Restarting the panel…')
+ : t('app.aboutTab.updateRunning', 'Updating ServerKit…')}
+ </span>
+ </div>
+ )}
+ {updateLogTail && updatePhase !== 'done' && (
+ <pre className="update-log">{updateLogTail.trim().split('\n').slice(-12).join('\n')}</pre>
+ )}
+ </div>
+ )
) : (
<div className="update-status current">
<CheckCircle size={16} />
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index 4f5fb388..f123dc14 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -35,6 +35,7 @@
"ifYouFindServerkitUsefulConsider": "If you find ServerKit useful, consider starring the repository on GitHub. It helps others discover the project!",
"license": "License",
"links": "Links",
+ "reloadPanel": "Reload Panel",
"reportABug": "Report a Bug",
"serverManagementMadeSimple": "Server management made simple",
"serverkitIsOpenSourceSoftwareLicensed": "ServerKit is open source software licensed under the MIT License.",
@@ -42,6 +43,15 @@
"supportIssues": "Support & Issues",
"systemMonitoringAlerts": "System Monitoring & Alerts",
"updateAvailable": "Update available:",
+ "updateComplete": "Updated to",
+ "updateConfirm": "This updates ServerKit and briefly restarts the panel. Hosted apps stay online. If the new version fails to start, it rolls back automatically.",
+ "updateDidNotComplete": "The update ended without changing the version. Check the update log on the server.",
+ "updateNow": "Update Now",
+ "updateRestarting": "Restarting the panel…",
+ "updateRolledBack": "The update failed and was rolled back — the previous version is still running.",
+ "updateRunning": "Updating ServerKit…",
+ "updateStartFailed": "Failed to start the update",
+ "updateTimeout": "The update is taking longer than expected. Check the update log on the server before retrying.",
"viewRelease": "View Release",
"youReUpToDate": "You're up to date!"
},
diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json
index 8246a256..4a4127fc 100644
--- a/frontend/src/i18n/locales/es.json
+++ b/frontend/src/i18n/locales/es.json
@@ -35,6 +35,7 @@
"ifYouFindServerkitUsefulConsider": "Si ServerKit te resulta útil, considera marcar el repositorio con una estrella en GitHub. ¡Ayuda a que otros descubran el proyecto!",
"license": "Licencia",
"links": "Enlaces",
+ "reloadPanel": "Recargar panel",
"reportABug": "Reportar un error",
"serverManagementMadeSimple": "Gestión de servidores simplificada",
"serverkitIsOpenSourceSoftwareLicensed": "ServerKit es software de código abierto con licencia MIT.",
@@ -42,6 +43,15 @@
"supportIssues": "Soporte e incidencias",
"systemMonitoringAlerts": "Monitorización del sistema y alertas",
"updateAvailable": "Actualización disponible:",
+ "updateComplete": "Actualizado a",
+ "updateConfirm": "Esto actualiza ServerKit y reinicia brevemente el panel. Las aplicaciones alojadas siguen en línea. Si la nueva versión no arranca, se revierte automáticamente.",
+ "updateDidNotComplete": "La actualización terminó sin cambiar la versión. Revisa el registro de actualización en el servidor.",
+ "updateNow": "Actualizar ahora",
+ "updateRestarting": "Reiniciando el panel…",
+ "updateRolledBack": "La actualización falló y se revirtió — la versión anterior sigue en funcionamiento.",
+ "updateRunning": "Actualizando ServerKit…",
+ "updateStartFailed": "No se pudo iniciar la actualización",
+ "updateTimeout": "La actualización está tardando más de lo esperado. Revisa el registro de actualización en el servidor antes de reintentar.",
"viewRelease": "Ver el lanzamiento",
"youReUpToDate": "¡Estás al día!"
},
diff --git a/frontend/src/services/api/system.js b/frontend/src/services/api/system.js
index ea18bca8..11df5c1a 100644
--- a/frontend/src/services/api/system.js
+++ b/frontend/src/services/api/system.js
@@ -121,6 +121,17 @@ export async function checkUpdate() {
return this.request('/system/check-update');
}
+export async function getPanelUpdateStatus() {
+ return this.request('/system/update');
+}
+
+export async function startPanelUpdate() {
+ return this.request('/system/update', {
+ method: 'POST',
+ body: { confirm: true }
+ });
+}
+
export async function getSystemProcesses() {
return this.request('/system/processes');
}
diff --git a/frontend/src/styles/pages/_settings.scss b/frontend/src/styles/pages/_settings.scss
index 7133ec05..d0b0219d 100644
--- a/frontend/src/styles/pages/_settings.scss
+++ b/frontend/src/styles/pages/_settings.scss
@@ -1012,6 +1012,10 @@
}
}
+ &.running {
+ color: $text-secondary;
+ }
+
&.error {
color: $danger;
@@ -1031,6 +1035,49 @@
}
}
}
+
+ .update-confirm {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-wrap: wrap;
+ gap: $space-2;
+ margin-top: $space-3;
+ font-size: $font-size-xs;
+ color: $warning;
+
+ span {
+ max-width: 46ch;
+ text-align: start;
+ }
+ }
+
+ .update-capability-note {
+ margin-top: $space-2;
+ font-size: $font-size-xs;
+ color: $text-muted;
+ }
+
+ .update-progress {
+ .spinning {
+ animation: spin 1s linear infinite;
+ }
+
+ .update-log {
+ margin-top: $space-3;
+ max-height: 200px;
+ overflow: auto;
+ padding: $space-3;
+ background: $bg-elevated;
+ border: 1px solid $border-subtle;
+ border-radius: $radius-md;
+ font-size: $font-size-xs;
+ text-align: start;
+ white-space: pre-wrap;
+ word-break: break-word;
+ color: $text-secondary;
+ }
+ }
}
}