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(services): support manual/local apps and zip uploads

Juan Denis70a70642c169
diff --git a/backend/app/api/apps.py b/backend/app/api/apps.py
index 847bf70c..17a36666 100644
--- a/backend/app/api/apps.py
+++ b/backend/app/api/apps.py
@@ -2,6 +2,7 @@ import os
import json
import re
import shutil
+from datetime import datetime
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import db
@@ -13,15 +14,53 @@ from app.services.repository_manifest_service import RepositoryManifestService
from app.services.source_connection_service import SourceConnectionService
from app.services.remote_docker_service import RemoteDockerService
from app.services.log_service import LogService
+from app.services.process_service import ProcessService
+from app.services.upload_service import (
+ ensure_app_dirs,
+ validate_zip,
+ extract_version,
+ preserve_existing_env,
+ switch_current_version,
+ backup_current,
+ save_upload_zip,
+ detect_app_type,
+ get_app_storage_dir,
+ list_versions,
+ get_current_version,
+)
from app import paths
apps_bp = Blueprint('apps', __name__)
def _compose_target(app):
+ """Return the effective compose file path for remote agent deployments."""
if app.server_id and app.root_path:
- return os.path.join(app.root_path, 'docker-compose.yml')
- return app.root_path
+ return os.path.join(app.root_path, app.compose_file or 'docker-compose.yml')
+ return os.path.join(app.root_path, app.compose_file or 'docker-compose.yml') if app.root_path else None
+
+
+def _local_compose_file(app):
+ """Return the compose file to pass to DockerService for local deployments."""
+ return app.compose_file if app.compose_file else None
+
+
+def _sync_manual_app_status(app):
+ """Update app.status from the real runtime for manual/local apps."""
+ if app.source != 'manual':
+ return
+ if app.managed_by == 'systemd' and app.systemd_unit:
+ status = ProcessService.get_systemd_unit_status(app.systemd_unit)
+ actual = 'running' if status.get('active') else 'stopped'
+ elif app.managed_by == 'docker_compose' and app.root_path:
+ status = ProcessService.get_compose_project_status(app.root_path, compose_file=app.compose_file)
+ actual = status.get('status', 'stopped')
+ else:
+ return
+
+ if actual in ('running', 'stopped') and app.status != actual:
+ app.status = actual
+ db.session.commit()
def _agent_result_failed(result):
@@ -663,6 +702,10 @@ def create_app():
port=data.get('port'),
root_path=data.get('root_path'),
docker_image=data.get('docker_image'),
+ source=data.get('source') or 'github',
+ compose_file=data.get('compose_file'),
+ systemd_unit=data.get('systemd_unit'),
+ managed_by=data.get('managed_by'),
user_id=current_user_id,
workspace_id=ws_id
)
@@ -676,6 +719,299 @@ def create_app():
}), 201
+@apps_bp.route('/manual', methods=['POST'])
+@jwt_required()
+def create_manual_app():
+ """Register an app that already exists on the server (manual/local)."""
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+ if not user or user.role != 'admin':
+ return jsonify({'error': 'Admin access required'}), 403
+
+ data = request.get_json() or {}
+ name = _service_slug(data.get('name'))
+ app_type = (data.get('app_type') or 'docker').strip().lower()
+ root_path = (data.get('root_path') or '').strip()
+ compose_file = (data.get('compose_file') or '').strip() or None
+ systemd_unit = (data.get('systemd_unit') or '').strip() or None
+ managed_by = (data.get('managed_by') or '').strip().lower() or None
+
+ if not name or len(name) < 2:
+ return jsonify({'error': 'Service name must be at least 2 characters'}), 400
+
+ valid_types = ['docker', 'flask', 'django', 'php', 'static', 'wordpress']
+ if app_type not in valid_types:
+ return jsonify({'error': f'Invalid app_type. Must be one of: {", ".join(valid_types)}'}), 400
+
+ if not root_path:
+ return jsonify({'error': 'root_path is required'}), 400
+
+ root_path = os.path.abspath(root_path)
+ if not os.path.isdir(root_path):
+ return jsonify({'error': f'Path does not exist: {root_path}'}), 400
+
+ # Auto-detect managed_by if not provided
+ if not managed_by:
+ if compose_file or os.path.exists(os.path.join(root_path, 'docker-compose.yml')):
+ managed_by = 'docker_compose'
+ elif systemd_unit:
+ managed_by = 'systemd'
+ else:
+ managed_by = 'docker_compose'
+
+ if managed_by not in ('docker_compose', 'systemd'):
+ return jsonify({'error': "managed_by must be 'docker_compose' or 'systemd'"}), 400
+
+ if managed_by == 'docker_compose' and not compose_file:
+ if not os.path.exists(os.path.join(root_path, 'docker-compose.yml')):
+ return jsonify({'error': 'docker-compose.yml not found and no compose_file provided'}), 400
+ compose_file = 'docker-compose.yml'
+
+ if Application.query.filter_by(name=name).first():
+ return jsonify({'error': f'An application named "{name}" already exists'}), 400
+
+ from app.services.workspace_service import WorkspaceService
+ ws_id = WorkspaceService.resolve_workspace_id(
+ user, request.headers.get('X-Workspace-Id') or request.args.get('workspace_id'))
+ if ws_id is None:
+ ws_id = WorkspaceService.ensure_default_workspace().id
+
+ app = Application(
+ name=name,
+ app_type=app_type,
+ status='stopped',
+ source='manual',
+ root_path=root_path,
+ compose_file=compose_file,
+ systemd_unit=systemd_unit,
+ managed_by=managed_by,
+ user_id=current_user_id,
+ workspace_id=ws_id,
+ )
+
+ db.session.add(app)
+ db.session.commit()
+
+ # Sync status immediately so the UI reflects reality
+ _sync_manual_app_status(app)
+
+ return jsonify({
+ 'message': 'Manual service registered',
+ 'app': _attach_deploy_config(app.to_dict(include_linked=True))
+ }), 201
+
+
+@apps_bp.route('/upload', methods=['POST'])
+@jwt_required()
+def upload_app_archive():
+ """Create or update an app by uploading a zip archive."""
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+ if not user or user.role != 'admin':
+ return jsonify({'error': 'Admin access required'}), 403
+
+ if 'file' not in request.files:
+ return jsonify({'error': 'No file provided'}), 400
+
+ uploaded = request.files['file']
+ if not uploaded or uploaded.filename == '':
+ return jsonify({'error': 'No file selected'}), 400
+
+ name = _service_slug(request.form.get('name') or uploaded.filename.rsplit('.', 1)[0])
+ app_type = (request.form.get('app_type') or 'auto').strip().lower()
+ auto_deploy = request.form.get('auto_deploy', 'true').lower() == 'true'
+
+ if not name or len(name) < 2:
+ return jsonify({'error': 'Service name must be at least 2 characters'}), 400
+
+ valid_types = ['auto', 'docker', 'flask', 'django', 'php', 'static', 'node']
+ if app_type not in valid_types:
+ return jsonify({'error': f'Invalid app_type. Must be one of: {", ".join(valid_types)}'}), 400
+
+ from app.services.workspace_service import WorkspaceService
+ ws_id = WorkspaceService.resolve_workspace_id(
+ user, request.headers.get('X-Workspace-Id') or request.args.get('workspace_id'))
+ if ws_id is None:
+ ws_id = WorkspaceService.ensure_default_workspace().id
+
+ existing = Application.query.filter_by(name=name).first()
+ is_update = existing is not None and existing.source == 'upload'
+
+ temp_dir = os.path.join(paths.SERVERKIT_CACHE_DIR, 'uploads')
+ os.makedirs(temp_dir, exist_ok=True)
+ timestamp = datetime.utcnow().strftime('%Y%m%d-%H%M%S-%f')
+ zippath = os.path.join(temp_dir, f'{name}-{timestamp}.zip')
+ uploaded.save(zippath)
+
+ validation = validate_zip(zippath)
+ if not validation.get('success'):
+ os.remove(zippath)
+ return jsonify({'error': validation.get('error', 'Invalid zip')}), 400
+
+ try:
+ app_dir = ensure_app_dirs(name)
+
+ if is_update:
+ app = existing
+ new_version = (app.version or 0) + 1
+ backup_path = backup_current(app_dir)
+ else:
+ if existing:
+ os.remove(zippath)
+ return jsonify({'error': f'An application named "{name}" already exists'}), 400
+ new_version = 1
+
+ version_dir = extract_version(app_dir, zippath, new_version)
+ upload_archive_path = save_upload_zip(app_dir, zippath, new_version)
+
+ if is_update:
+ preserve_existing_env(os.path.join(app_dir, 'current'), version_dir)
+
+ current_dir = switch_current_version(app_dir, new_version)
+
+ if app_type == 'auto':
+ detected = detect_app_type(current_dir)
+ else:
+ detected = app_type
+
+ if detected == 'node':
+ detected = 'docker'
+
+ compose_file = None
+ if detected == 'docker':
+ if os.path.exists(os.path.join(current_dir, 'docker-compose.yml')):
+ compose_file = 'docker-compose.yml'
+ elif os.path.exists(os.path.join(current_dir, 'Dockerfile')):
+ compose_file = None
+
+ if is_update:
+ app.app_type = detected
+ app.compose_file = compose_file
+ app.version = new_version
+ app.upload_path = upload_archive_path
+ app.root_path = current_dir
+ app.updated_at = datetime.utcnow()
+ else:
+ app = Application(
+ name=name,
+ app_type=detected,
+ status='stopped',
+ source='upload',
+ root_path=current_dir,
+ compose_file=compose_file,
+ managed_by='docker_compose' if detected == 'docker' else None,
+ version=new_version,
+ upload_path=upload_archive_path,
+ user_id=current_user_id,
+ workspace_id=ws_id,
+ )
+ db.session.add(app)
+
+ db.session.commit()
+
+ deploy_result = None
+ if auto_deploy and detected == 'docker' and compose_file:
+ deploy_result = DockerService.compose_up(current_dir, detach=True, build=True, compose_file=compose_file)
+ if deploy_result.get('success'):
+ app.status = 'running'
+ app.last_deployed_at = datetime.utcnow()
+ db.session.commit()
+
+ os.remove(zippath)
+
+ return jsonify({
+ 'message': 'Upload service updated' if is_update else 'Upload service created',
+ 'app': _attach_deploy_config(app.to_dict(include_linked=True)),
+ 'version': new_version,
+ 'detected_app_type': detected,
+ 'deploy_result': deploy_result,
+ }), 201 if not is_update else 200
+
+ except Exception as exc:
+ try:
+ os.remove(zippath)
+ except Exception:
+ pass
+ return jsonify({'error': str(exc)}), 400
+
+
+@apps_bp.route('/<int:app_id>/versions', methods=['GET'])
+@jwt_required()
+def get_app_versions(app_id):
+ """List versions for an uploaded app."""
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+ app = Application.query.get(app_id)
+
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+
+ if not _can_access_app(user, app):
+ return jsonify({'error': 'Access denied'}), 403
+
+ if app.source != 'upload':
+ return jsonify({'versions': [], 'current': None}), 200
+
+ try:
+ app_dir = get_app_storage_dir(app.name)
+ versions = list_versions(app_dir)
+ current = get_current_version(app_dir)
+ return jsonify({'versions': versions, 'current': current}), 200
+ except Exception as e:
+ return jsonify({'error': str(e)}), 400
+
+
+@apps_bp.route('/<int:app_id>/rollback', methods=['POST'])
+@jwt_required()
+def rollback_app_version(app_id):
+ """Roll an uploaded app back to a previous version."""
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+ app = Application.query.get(app_id)
+
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+
+ if not _can_edit_app(user, app):
+ return jsonify({'error': 'Access denied'}), 403
+
+ if app.source != 'upload':
+ return jsonify({'error': 'Rollback is only supported for upload-based apps'}), 400
+
+ data = request.get_json() or {}
+ target = data.get('version')
+ if target is None:
+ return jsonify({'error': 'version is required'}), 400
+
+ try:
+ target = int(target)
+ except (TypeError, ValueError):
+ return jsonify({'error': 'version must be an integer'}), 400
+
+ try:
+ app_dir = get_app_storage_dir(app.name)
+ current_dir = switch_current_version(app_dir, target)
+ app.root_path = current_dir
+ app.version = target
+ app.updated_at = datetime.utcnow()
+
+ if app.app_type == 'docker' and app.compose_file:
+ result = DockerService.compose_up(current_dir, detach=True, build=True, compose_file=app.compose_file)
+ if result.get('success'):
+ app.status = 'running'
+ app.last_deployed_at = datetime.utcnow()
+ else:
+ return jsonify({'error': result.get('error', 'Failed to start service'), 'app': app.to_dict()}), 400
+
+ db.session.commit()
+ return jsonify({
+ 'message': f'Rolled back to version {target}',
+ 'app': _attach_deploy_config(app.to_dict(include_linked=True))
+ }), 200
+ except Exception as e:
+ return jsonify({'error': str(e)}), 400
+
+
@apps_bp.route('/<int:app_id>', methods=['PUT'])
@jwt_required()
def update_app(app_id):
@@ -705,6 +1041,14 @@ def update_app(app_id):
app.root_path = data['root_path']
if 'docker_image' in data:
app.docker_image = data['docker_image']
+ if 'source' in data:
+ app.source = data['source']
+ if 'compose_file' in data:
+ app.compose_file = data['compose_file']
+ if 'systemd_unit' in data:
+ app.systemd_unit = data['systemd_unit']
+ if 'managed_by' in data:
+ app.managed_by = data['managed_by']
db.session.commit()
@@ -740,16 +1084,23 @@ def delete_app(app_id):
if app.app_type == 'docker' and app.root_path:
try:
# Stop and remove containers, networks, and volumes
- result = DockerService.compose_down(app.root_path, volumes=True, remove_orphans=True)
+ result = DockerService.compose_down(
+ app.root_path,
+ volumes=True,
+ remove_orphans=True,
+ compose_file=_local_compose_file(app)
+ )
cleanup_results['docker'] = result
except Exception as e:
cleanup_results['docker'] = {'error': str(e)}
- # Delete the app folder
+ # Delete the app folder only for ServerKit-managed uploads.
+ # Manual apps point at existing paths that must not be removed.
try:
- if app.root_path and app.root_path.startswith(paths.APPS_DIR):
- if os.path.exists(app.root_path):
- shutil.rmtree(app.root_path)
+ if app.source == 'upload' and app.root_path and app.root_path.startswith(paths.APPS_DIR):
+ app_storage = get_app_storage_dir(app.name)
+ if os.path.exists(app_storage):
+ shutil.rmtree(app_storage)
cleanup_results['folder'] = {'success': True}
except Exception as e:
cleanup_results['folder'] = {'error': str(e)}
@@ -795,7 +1146,11 @@ def start_app(app_id):
user_id=current_user_id
)
else:
- result = DockerService.compose_up(app.root_path, detach=True)
+ result = DockerService.compose_up(
+ app.root_path,
+ detach=True,
+ compose_file=_local_compose_file(app)
+ )
if not result.get('success') or _agent_result_failed(result):
return jsonify({'error': _agent_result_error(result, 'Failed to start containers')}), 400
@@ -830,7 +1185,10 @@ def stop_app(app_id):
user_id=current_user_id
)
else:
- result = DockerService.compose_down(app.root_path)
+ result = DockerService.compose_down(
+ app.root_path,
+ compose_file=_local_compose_file(app)
+ )
if not result.get('success') or _agent_result_failed(result):
return jsonify({'error': _agent_result_error(result, 'Failed to stop containers')}), 400
@@ -865,7 +1223,10 @@ def restart_app(app_id):
user_id=current_user_id
)
else:
- result = DockerService.compose_restart(app.root_path)
+ result = DockerService.compose_restart(
+ app.root_path,
+ compose_file=_local_compose_file(app)
+ )
if not result.get('success') or _agent_result_failed(result):
return jsonify({'error': _agent_result_error(result, 'Failed to restart containers')}), 400
@@ -906,7 +1267,9 @@ def get_app_logs(app_id):
)
return jsonify(result.get('data') if result.get('success') else result), 200 if result.get('success') else 400
- result = LogService.get_docker_app_logs(app.name, app.root_path, lines)
+ result = LogService.get_docker_app_logs(
+ app.name, app.root_path, lines, compose_file=_local_compose_file(app)
+ )
return jsonify(result), 200 if result.get('success') else 400
# For other apps, get nginx logs
@@ -1075,6 +1438,22 @@ def get_app_status(app_id):
if not _can_access_app(user, app):
return jsonify({'error': 'Access denied'}), 403
+ # Manual / local apps: ask the real runtime
+ if app.source == 'manual':
+ _sync_manual_app_status(app)
+ if app.managed_by == 'systemd' and app.systemd_unit:
+ unit_status = ProcessService.get_systemd_unit_status(app.systemd_unit)
+ return jsonify({
+ 'status': app.status,
+ 'unit_status': unit_status.get('status'),
+ 'active': unit_status.get('active'),
+ 'containers': [],
+ 'running': 1 if app.status == 'running' else 0,
+ 'total': 1,
+ 'port': app.port,
+ 'port_accessible': None,
+ }), 200
+
if app.app_type == 'docker' and app.root_path:
# Get container status from Docker
if app.server_id:
@@ -1087,7 +1466,10 @@ def get_app_status(app_id):
return jsonify(result), 503 if result.get('code') == 'AGENT_OFFLINE' else 400
containers = result.get('data', [])
else:
- containers = DockerService.compose_ps(app.root_path)
+ containers = DockerService.compose_ps(
+ app.root_path,
+ compose_file=_local_compose_file(app)
+ )
# Determine overall status
running_count = sum(1 for c in containers if c.get('Status', c.get('status', '')).startswith('Up'))
diff --git a/backend/app/models/application.py b/backend/app/models/application.py
index d8d2dded..dd39b3ac 100644
--- a/backend/app/models/application.py
+++ b/backend/app/models/application.py
@@ -20,6 +20,19 @@ class Application(db.Model):
docker_image = db.Column(db.String(200), nullable=True)
container_id = db.Column(db.String(100), nullable=True)
+ # Source / lifecycle: github (repo clone), template (built-in template),
+ # manual (local path already on server), upload (zip upload managed by ServerKit)
+ source = db.Column(db.String(20), default='github', nullable=False)
+
+ # Manual / local service configuration
+ compose_file = db.Column(db.String(200), nullable=True)
+ systemd_unit = db.Column(db.String(100), nullable=True)
+ managed_by = db.Column(db.String(20), nullable=True) # 'docker_compose', 'systemd'
+
+ # Upload versioning
+ version = db.Column(db.Integer, default=0, nullable=False)
+ upload_path = db.Column(db.String(500), nullable=True)
+
# Private URL feature
private_slug = db.Column(db.String(50), unique=True, nullable=True, index=True)
private_url_enabled = db.Column(db.Boolean, default=False)
@@ -60,6 +73,12 @@ class Application(db.Model):
'root_path': self.root_path,
'docker_image': self.docker_image,
'container_id': self.container_id,
+ 'source': self.source,
+ 'compose_file': self.compose_file,
+ 'systemd_unit': self.systemd_unit,
+ 'managed_by': self.managed_by,
+ 'version': self.version,
+ 'upload_path': self.upload_path,
'private_slug': self.private_slug,
'private_url_enabled': self.private_url_enabled,
'environment_type': self.environment_type,
diff --git a/backend/app/services/docker_service.py b/backend/app/services/docker_service.py
index 883f27f9..7684349a 100644
--- a/backend/app/services/docker_service.py
+++ b/backend/app/services/docker_service.py
@@ -324,54 +324,59 @@ class DockerService:
return None
@staticmethod
- def get_app_container_id(app):
+ def _app_attr(app, name):
+ """Read an attribute from a model instance or dict."""
+ if isinstance(app, dict):
+ return app.get(name)
+ return getattr(app, name, None)
+
+ @classmethod
+ def get_app_container_id(cls, app):
"""Get the main container ID for an application.
For apps with container_id set, use that directly.
For compose apps, query docker compose ps to find container.
Args:
- app: Application model instance (or dict with container_id and root_path)
+ app: Application model instance (or dict with container_id, root_path, compose_file)
Returns:
str: Container ID or name, or None if not found
"""
- # Handle both model instances and dicts
- container_id = getattr(app, 'container_id', None) or (app.get('container_id') if isinstance(app, dict) else None)
- root_path = getattr(app, 'root_path', None) or (app.get('root_path') if isinstance(app, dict) else None)
+ container_id = cls._app_attr(app, 'container_id')
+ root_path = cls._app_attr(app, 'root_path')
+ compose_file = cls._app_attr(app, 'compose_file')
if container_id:
return container_id
if root_path:
- # Get containers from docker compose
- containers = DockerService.compose_ps(root_path)
+ containers = cls.compose_ps(root_path, compose_file=compose_file)
if containers:
- # Return first container (main service)
- # Docker compose ps returns 'ID' or 'Name' depending on version
return containers[0].get('ID') or containers[0].get('Name') or containers[0].get('id')
return None
- @staticmethod
- def get_all_app_containers(app):
+ @classmethod
+ def get_all_app_containers(cls, app):
"""Get all container IDs for a compose application.
Args:
- app: Application model instance (or dict with root_path)
+ app: Application model instance (or dict with root_path, compose_file)
Returns:
list: List of container info dicts with 'id', 'name', 'service', 'state'
"""
- root_path = getattr(app, 'root_path', None) or (app.get('root_path') if isinstance(app, dict) else None)
+ root_path = cls._app_attr(app, 'root_path')
+ compose_file = cls._app_attr(app, 'compose_file')
if not root_path:
- container_id = getattr(app, 'container_id', None) or (app.get('container_id') if isinstance(app, dict) else None)
+ container_id = cls._app_attr(app, 'container_id')
if container_id:
return [{'id': container_id, 'name': container_id, 'service': 'main', 'state': 'unknown'}]
return []
- containers = DockerService.compose_ps(root_path)
+ containers = cls.compose_ps(root_path, compose_file=compose_file)
result = []
for c in containers:
result.append({
@@ -752,6 +757,16 @@ class DockerService:
# ==================== DOCKER COMPOSE ====================
+ @classmethod
+ def _compose_base_cmd(cls, compose_file=None):
+ """Build the base docker compose command, optionally targeting a
+ specific compose file. The file path may be absolute or relative to
+ the project directory."""
+ cmd = cls._get_compose_cmd()
+ if compose_file:
+ cmd = cmd + ['-f', compose_file]
+ return cmd
+
@classmethod
def compose_list(cls):
"""List Docker Compose projects known to the Docker CLI."""
@@ -843,10 +858,10 @@ class DockerService:
return []
@classmethod
- def compose_up(cls, project_path, detach=True, build=False):
+ def compose_up(cls, project_path, detach=True, build=False, compose_file=None):
"""Start Docker Compose services."""
try:
- cmd = cls._get_compose_cmd() + ['up']
+ cmd = cls._compose_base_cmd(compose_file) + ['up']
if detach:
cmd.append('-d')
if build:
@@ -863,10 +878,10 @@ class DockerService:
return {'success': False, 'error': str(e)}
@classmethod
- def compose_down(cls, project_path, volumes=False, remove_orphans=True):
+ def compose_down(cls, project_path, volumes=False, remove_orphans=True, compose_file=None):
"""Stop Docker Compose services."""
try:
- cmd = cls._get_compose_cmd() + ['down']
+ cmd = cls._compose_base_cmd(compose_file) + ['down']
if volumes:
cmd.append('-v')
if remove_orphans:
@@ -883,7 +898,7 @@ class DockerService:
return {'success': False, 'error': str(e)}
@classmethod
- def compose_ps(cls, project_path):
+ def compose_ps(cls, project_path, compose_file=None):
"""List Docker Compose services.
Handles multiple output formats from docker compose ps --format json:
@@ -895,7 +910,7 @@ class DockerService:
"""
try:
result = subprocess.run(
- cls._get_compose_cmd() + ['ps', '--format', 'json'],
+ cls._compose_base_cmd(compose_file) + ['ps', '--format', 'json'],
cwd=project_path,
capture_output=True, text=True
)
@@ -925,10 +940,10 @@ class DockerService:
return []
@classmethod
- def compose_logs(cls, project_path, service=None, tail=100):
+ def compose_logs(cls, project_path, service=None, tail=100, compose_file=None):
"""Get Docker Compose logs."""
try:
- cmd = cls._get_compose_cmd() + ['logs', '--tail', str(tail)]
+ cmd = cls._compose_base_cmd(compose_file) + ['logs', '--tail', str(tail)]
if service:
cmd.append(service)
@@ -941,10 +956,10 @@ class DockerService:
return {'success': False, 'error': str(e)}
@classmethod
- def compose_restart(cls, project_path, service=None):
+ def compose_restart(cls, project_path, service=None, compose_file=None):
"""Restart Docker Compose services."""
try:
- cmd = cls._get_compose_cmd() + ['restart']
+ cmd = cls._compose_base_cmd(compose_file) + ['restart']
if service:
cmd.append(service)
@@ -959,10 +974,10 @@ class DockerService:
return {'success': False, 'error': str(e)}
@classmethod
- def compose_pull(cls, project_path, service=None):
+ def compose_pull(cls, project_path, service=None, compose_file=None):
"""Pull Docker Compose images."""
try:
- cmd = cls._get_compose_cmd() + ['pull']
+ cmd = cls._compose_base_cmd(compose_file) + ['pull']
if service:
cmd.append(service)
@@ -977,11 +992,11 @@ class DockerService:
return {'success': False, 'error': str(e)}
@classmethod
- def validate_compose_file(cls, project_path):
+ def validate_compose_file(cls, project_path, compose_file=None):
"""Validate a Docker Compose file."""
try:
result = subprocess.run(
- cls._get_compose_cmd() + ['config', '--quiet'],
+ cls._compose_base_cmd(compose_file) + ['config', '--quiet'],
cwd=project_path,
capture_output=True, text=True
)
@@ -989,14 +1004,14 @@ class DockerService:
return {'valid': True}
return {'valid': False, 'error': result.stderr}
except Exception as e:
- return {'valid': False, 'error': str(e)}
+ return {'success': False, 'error': str(e)}
@classmethod
- def get_compose_config(cls, project_path):
+ def get_compose_config(cls, project_path, compose_file=None):
"""Get parsed Docker Compose configuration."""
try:
result = subprocess.run(
- cls._get_compose_cmd() + ['config'],
+ cls._compose_base_cmd(compose_file) + ['config'],
cwd=project_path,
capture_output=True, text=True
)
diff --git a/backend/app/services/log_service.py b/backend/app/services/log_service.py
index 43553fb8..e797082a 100644
--- a/backend/app/services/log_service.py
+++ b/backend/app/services/log_service.py
@@ -214,11 +214,17 @@ class LogService:
return cls.read_log(filepath, lines)
@classmethod
- def get_docker_app_logs(cls, app_name: str, app_dir: str, lines: int = 100) -> Dict:
+ def get_docker_app_logs(cls, app_name: str, app_dir: str, lines: int = 100,
+ compose_file: str = None) -> Dict:
"""Get logs for a Docker Compose application."""
try:
+ cmd = ['docker', 'compose']
+ if compose_file:
+ cmd.extend(['-f', compose_file])
+ cmd.extend(['logs', '--tail', str(lines), '--no-color'])
+
result = subprocess.run(
- ['docker', 'compose', 'logs', '--tail', str(lines), '--no-color'],
+ cmd,
capture_output=True,
text=True,
timeout=30,
@@ -230,8 +236,12 @@ class LogService:
return {**sourced_result(log_lines, 'docker', 'Docker Compose'), 'app_dir': app_dir}
else:
# Try with docker-compose (older syntax) as fallback
+ cmd = ['docker-compose']
+ if compose_file:
+ cmd.extend(['-f', compose_file])
+ cmd.extend(['logs', '--tail', str(lines), '--no-color'])
result = subprocess.run(
- ['docker-compose', 'logs', '--tail', str(lines), '--no-color'],
+ cmd,
capture_output=True,
text=True,
timeout=30,
diff --git a/backend/app/services/process_service.py b/backend/app/services/process_service.py
index 7dfb9209..f6020c25 100644
--- a/backend/app/services/process_service.py
+++ b/backend/app/services/process_service.py
@@ -174,3 +174,45 @@ class ProcessService:
"""Get recent logs for a service via LogService fallback chain."""
from app.services.log_service import LogService
return LogService.get_journalctl_logs(unit=service_name, lines=lines)
+
+ @classmethod
+ def get_systemd_unit_status(cls, unit_name: str) -> Dict:
+ """Check whether a systemd unit is active using systemctl."""
+ system = platform.system()
+ if system != 'Linux':
+ return {'success': True, 'status': 'unknown', 'active': False}
+
+ try:
+ result = subprocess.run(
+ ['systemctl', 'is-active', unit_name],
+ capture_output=True, text=True, timeout=10
+ )
+ active = result.returncode == 0 and result.stdout.strip() == 'active'
+ status = result.stdout.strip() if result.stdout else 'unknown'
+ return {'success': True, 'status': status, 'active': active}
+ except FileNotFoundError:
+ return {'success': False, 'error': 'systemctl not found'}
+ except subprocess.TimeoutExpired:
+ return {'success': False, 'error': 'Command timed out'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def get_compose_project_status(cls, project_path: str, compose_file: str = None) -> Dict:
+ """Return running/stopped status for a Docker Compose project directory."""
+ from app.services.docker_service import DockerService
+ containers = DockerService.compose_ps(project_path, compose_file=compose_file)
+ running = sum(
+ 1 for c in containers
+ if (c.get('Status', c.get('status', '')).startswith('Up'))
+ )
+ total = len(containers)
+ if total == 0:
+ actual = 'stopped'
+ elif running == total:
+ actual = 'running'
+ elif running > 0:
+ actual = 'partial'
+ else:
+ actual = 'stopped'
+ return {'success': True, 'status': actual, 'running': running, 'total': total, 'containers': containers}
diff --git a/backend/app/services/upload_service.py b/backend/app/services/upload_service.py
new file mode 100644
index 00000000..60b1a8f2
--- /dev/null
+++ b/backend/app/services/upload_service.py
@@ -0,0 +1,211 @@
+import os
+import re
+import shutil
+import zipfile
+import logging
+from datetime import datetime
+from werkzeug.utils import secure_filename
+
+from app import paths
+
+logger = logging.getLogger(__name__)
+
+# Maximum upload size is enforced by Flask config (100 MB), but we keep a
+# service-level guard too so callers can reason about limits independently.
+MAX_UPLOAD_SIZE = 100 * 1024 * 1024
+
+VALID_APP_TYPES = {'docker', 'flask', 'django', 'php', 'static', 'node'}
+
+
+def slugify(value):
+ return re.sub(r'[^a-z0-9-]+', '-', (value or '').strip().lower()).strip('-')
+
+
+def detect_app_type(directory):
+ """Inspect extracted archive contents and guess the runtime."""
+ if os.path.exists(os.path.join(directory, 'docker-compose.yml')):
+ return 'docker'
+ if os.path.exists(os.path.join(directory, 'Dockerfile')):
+ return 'docker'
+ if os.path.exists(os.path.join(directory, 'manage.py')):
+ return 'django'
+ if os.path.exists(os.path.join(directory, 'app.py')) or os.path.exists(os.path.join(directory, 'wsgi.py')):
+ return 'flask'
+ if os.path.exists(os.path.join(directory, 'package.json')):
+ return 'node'
+ if os.path.exists(os.path.join(directory, 'index.html')):
+ return 'static'
+ return 'docker'
+
+
+def validate_zip(zippath):
+ """Validate a service zip archive before extraction.
+
+ Returns a dict with success/error, total size, and file count.
+ """
+ try:
+ with zipfile.ZipFile(zippath, 'r') as zf:
+ infos = zf.infolist()
+ total_size = 0
+ file_count = 0
+ for info in infos:
+ # Zip-slip protection
+ if info.filename.startswith('/') or '..' in info.filename.split('/'):
+ return {'success': False, 'error': f'Unsafe path in archive: {info.filename}'}
+ total_size += info.file_size
+ file_count += 1
+ if total_size > MAX_UPLOAD_SIZE:
+ return {'success': False, 'error': 'Archive contents exceed maximum upload size'}
+ return {'success': True, 'total_size': total_size, 'file_count': file_count}
+ except zipfile.BadZipFile:
+ return {'success': False, 'error': 'Invalid or corrupted zip file'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+
+def get_app_storage_dir(name):
+ """Return the ServerKit-managed storage directory for an uploaded app."""
+ base = os.path.abspath(paths.APPS_DIR)
+ app_dir = os.path.abspath(os.path.join(base, name))
+ if app_dir != base and app_dir.startswith(base + os.sep):
+ return app_dir
+ raise ValueError('Invalid application name')
+
+
+def ensure_app_dirs(name):
+ app_dir = get_app_storage_dir(name)
+ for sub in ('uploads', 'versions', 'backups'):
+ os.makedirs(os.path.join(app_dir, sub), exist_ok=True)
+ return app_dir
+
+
+def extract_version(app_dir, zippath, version):
+ """Extract a zip into versions/v<N>."""
+ version_dir = os.path.join(app_dir, 'versions', f'v{version}')
+ if os.path.exists(version_dir):
+ shutil.rmtree(version_dir)
+ os.makedirs(version_dir, exist_ok=True)
+
+ with zipfile.ZipFile(zippath, 'r') as zf:
+ # If every top-level entry shares a single folder, strip it so the
+ # version directory contains the app files directly.
+ names = zf.namelist()
+ top = os.path.commonpath(names).split('/')[0] if names else ''
+ has_top_folder = top and all(n.startswith(top + '/') or n == top for n in names)
+
+ if has_top_folder:
+ for info in zf.infolist():
+ if info.is_dir():
+ continue
+ rel = info.filename[len(top):].lstrip('/')
+ if not rel:
+ continue
+ dest = os.path.join(version_dir, rel)
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
+ with zf.open(info) as src, open(dest, 'wb') as dst:
+ shutil.copyfileobj(src, dst)
+ else:
+ zf.extractall(version_dir)
+
+ return version_dir
+
+
+def preserve_existing_env(current_dir, version_dir):
+ """Keep an existing .env when updating so secrets are not overwritten."""
+ current_env = os.path.join(current_dir, '.env')
+ version_env = os.path.join(version_dir, '.env')
+ if os.path.exists(current_env) and os.path.exists(version_env):
+ shutil.copy2(current_env, version_env)
+ return True
+ return False
+
+
+def switch_current_version(app_dir, version):
+ """Point current/ to versions/v<N> using a junction/symlink or copy fallback."""
+ current_dir = os.path.join(app_dir, 'current')
+ version_dir = os.path.join(app_dir, 'versions', f'v{version}')
+
+ if not os.path.exists(version_dir):
+ raise ValueError(f'Version directory not found: {version_dir}')
+
+ # On Windows, symlinks may require privileges; fall back to a full copy.
+ try:
+ if os.path.islink(current_dir) or os.path.exists(current_dir):
+ is_junction = (
+ hasattr(os.path, 'isjunction') and os.path.isjunction(current_dir)
+ ) if os.name == 'nt' else False
+ if os.path.islink(current_dir) or is_junction:
+ os.remove(current_dir)
+ else:
+ shutil.rmtree(current_dir)
+ if os.name == 'nt':
+ os.symlink(version_dir, current_dir, target_is_directory=True)
+ else:
+ os.symlink(version_dir, current_dir)
+ except (OSError, NotImplementedError):
+ if os.path.exists(current_dir):
+ shutil.rmtree(current_dir)
+ shutil.copytree(version_dir, current_dir)
+
+ return current_dir
+
+
+def backup_current(app_dir):
+ """Backup current/ before overwriting. Returns the backup path or None."""
+ current_dir = os.path.join(app_dir, 'current')
+ if not os.path.exists(current_dir):
+ return None
+ backup_dir = os.path.join(app_dir, 'backups')
+ os.makedirs(backup_dir, exist_ok=True)
+ timestamp = datetime.utcnow().strftime('%Y%m%d-%H%M%S')
+ backup_path = os.path.join(backup_dir, f'backup-{timestamp}')
+ if os.path.exists(backup_path):
+ shutil.rmtree(backup_path)
+ shutil.copytree(current_dir, backup_path)
+ return backup_path
+
+
+def save_upload_zip(app_dir, zippath, version):
+ """Persist the uploaded zip in uploads/."""
+ uploads_dir = os.path.join(app_dir, 'uploads')
+ os.makedirs(uploads_dir, exist_ok=True)
+ dest = os.path.join(uploads_dir, f'v{version}.zip')
+ shutil.copy2(zippath, dest)
+ return dest
+
+
+def list_versions(app_dir):
+ """Return a sorted list of version dicts for an uploaded app."""
+ versions_dir = os.path.join(app_dir, 'versions')
+ if not os.path.exists(versions_dir):
+ return []
+ versions = []
+ for entry in sorted(os.listdir(versions_dir)):
+ if not entry.startswith('v'):
+ continue
+ try:
+ num = int(entry[1:])
+ except ValueError:
+ continue
+ path = os.path.join(versions_dir, entry)
+ versions.append({
+ 'version': num,
+ 'path': path,
+ 'created_at': datetime.utcfromtimestamp(os.path.getctime(path)).isoformat(),
+ })
+ return versions
+
+
+def get_current_version(app_dir):
+ """Return the currently active version number or None."""
+ current_dir = os.path.join(app_dir, 'current')
+ if not os.path.exists(current_dir):
+ return None
+ try:
+ target = os.path.realpath(current_dir)
+ name = os.path.basename(target)
+ if name.startswith('v'):
+ return int(name[1:])
+ except Exception:
+ pass
+ return None
diff --git a/backend/migrations/versions/017_manual_apps.py b/backend/migrations/versions/017_manual_apps.py
new file mode 100644
index 00000000..40707df5
--- /dev/null
+++ b/backend/migrations/versions/017_manual_apps.py
@@ -0,0 +1,75 @@
+"""Manual and upload-based application support.
+
+Adds:
+- applications.source (github | template | manual | upload)
+- applications.compose_file
+- applications.systemd_unit
+- applications.managed_by (docker_compose | systemd)
+- applications.version
+- applications.upload_path
+
+Idempotent: MigrationService._fix_missing_columns runs db.create_all() on boot
+before Alembic, so guard on the live schema like previous migrations.
+
+Revision ID: 017_manual_apps
+Revises: 016_resource_grants
+Create Date: 2026-06-19
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '017_manual_apps'
+down_revision = '016_resource_grants'
+branch_labels = None
+depends_on = None
+
+
+def _has_col(inspector, table, col):
+ if table not in inspector.get_table_names():
+ return False
+ return col in {c['name'] for c in inspector.get_columns(table)}
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+
+ if 'applications' not in inspector.get_table_names():
+ return
+
+ cols = [
+ ('source', sa.String(length=20)),
+ ('compose_file', sa.String(length=200)),
+ ('systemd_unit', sa.String(length=100)),
+ ('managed_by', sa.String(length=20)),
+ ('version', sa.Integer()),
+ ('upload_path', sa.String(length=500)),
+ ]
+
+ with op.batch_alter_table('applications') as batch_op:
+ for name, col_type in cols:
+ if not _has_col(inspector, 'applications', name):
+ kwargs = {}
+ if name == 'source':
+ kwargs['nullable'] = False
+ kwargs['server_default'] = 'github'
+ if name == 'version':
+ kwargs['nullable'] = False
+ kwargs['server_default'] = '0'
+ batch_op.add_column(sa.Column(name, col_type, **kwargs))
+
+ # Backfill existing rows that have no source set
+ conn.execute(sa.text("UPDATE applications SET source = 'github' WHERE source IS NULL OR source = ''"))
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+
+ if 'applications' not in inspector.get_table_names():
+ return
+
+ with op.batch_alter_table('applications') as batch_op:
+ for name in ('upload_path', 'version', 'managed_by', 'systemd_unit', 'compose_file', 'source'):
+ if _has_col(inspector, 'applications', name):
+ batch_op.drop_column(name)
diff --git a/frontend/src/pages/NewService.jsx b/frontend/src/pages/NewService.jsx
index 75546a67..7c089d57 100644
--- a/frontend/src/pages/NewService.jsx
+++ b/frontend/src/pages/NewService.jsx
@@ -4,6 +4,8 @@ import {
ArrowRight,
CheckCircle2,
ChevronDown,
+ FileArchive,
+ FolderOpen,
GitBranch,
Link2,
Lock,
@@ -138,6 +140,16 @@ const NewService = () => {
const [advancedOpen, setAdvancedOpen] = useState(false);
const [submitting, setSubmitting] = useState(false);
+ // Manual / local service fields
+ const [localPath, setLocalPath] = useState('');
+ const [composeFile, setComposeFile] = useState('');
+ const [systemdUnit, setSystemdUnit] = useState('');
+ const [managedBy, setManagedBy] = useState('auto');
+
+ // Upload fields
+ const [uploadFile, setUploadFile] = useState(null);
+ const [uploadDragOver, setUploadDragOver] = useState(false);
+
const githubConnection = githubStatus?.connection;
const githubConfigured = githubStatus?.configured;
const normalizedManualRepo = useMemo(() => normalizeManualRepo(manualRepoUrl), [manualRepoUrl]);
@@ -153,7 +165,11 @@ const NewService = () => {
? Boolean(githubConnection && selectedRepo && serviceName?.length >= 2)
: sourceMode === 'template'
? Boolean(selectedTemplate && serviceName?.length >= 2)
- : Boolean(normalizedManualRepo && serviceName?.length >= 2);
+ : sourceMode === 'local'
+ ? Boolean(serviceName?.length >= 2 && localPath?.length >= 1)
+ : sourceMode === 'upload'
+ ? Boolean(serviceName?.length >= 2 && uploadFile)
+ : Boolean(normalizedManualRepo && serviceName?.length >= 2);
const buildSummary = buildMethod === 'auto' && recommended.build_method
? `Auto -> ${formatBuildMethod(recommended.build_method)}`
: formatBuildMethod(buildMethod);
@@ -267,6 +283,12 @@ const NewService = () => {
if (mode === 'template' && !selectedTemplate) {
handleSelectTemplate(SERVICE_TEMPLATES[0]);
}
+ if (mode === 'local') {
+ setAppType('docker');
+ }
+ if (mode === 'upload') {
+ setAppType('auto');
+ }
}
function handleSelectTemplate(template) {
@@ -293,44 +315,72 @@ const NewService = () => {
async function handleSubmit(e) {
e.preventDefault();
if (!canSubmit) {
- toast.error(sourceMode === 'github'
+ const msg = sourceMode === 'github'
? 'Select a GitHub repository'
: sourceMode === 'template'
? 'Select a service template'
- : 'Repository URL is required');
+ : sourceMode === 'local'
+ ? 'Service name and server path are required'
+ : sourceMode === 'upload'
+ ? 'Service name and a zip file are required'
+ : 'Repository URL is required';
+ toast.error(msg);
return;
}
- const payload = {
- name: serviceName,
- branch: branch.trim() || null,
- app_type: appType,
- build_method: buildMethod,
- port: port ? Number(port) : null,
- auto_deploy: autoDeploy,
- };
- if (recommended.dockerfile_path) payload.dockerfile_path = recommended.dockerfile_path;
- if (recommended.custom_build_cmd) payload.custom_build_cmd = recommended.custom_build_cmd;
- if (recommended.custom_start_cmd) payload.custom_start_cmd = recommended.custom_start_cmd;
-
- if (sourceMode === 'github') {
- payload.source_connection_id = githubConnection.id;
- payload.repository_full_name = selectedRepo.full_name;
- payload.repo_url = `https://github.com/${selectedRepo.full_name}.git`;
- } else if (sourceMode === 'template') {
- payload.template_id = selectedTemplate.id;
- payload.repo_url = selectedTemplate.repoUrl;
- } else {
- payload.repo_url = normalizedManualRepo;
- }
-
setSubmitting(true);
try {
- const result = await api.createAppFromRepository(payload);
- toast.success('Repository service created');
- navigate(`/services/${result.app.id}`);
+ if (sourceMode === 'local') {
+ const payload = {
+ name: serviceName,
+ app_type: appType,
+ root_path: localPath.trim(),
+ compose_file: composeFile.trim() || undefined,
+ systemd_unit: systemdUnit.trim() || undefined,
+ managed_by: managedBy === 'auto' ? undefined : managedBy,
+ };
+ const result = await api.createManualApp(payload);
+ toast.success('Manual service registered');
+ navigate(`/services/${result.app.id}`);
+ } else if (sourceMode === 'upload') {
+ const formData = new FormData();
+ formData.append('file', uploadFile);
+ formData.append('name', serviceName);
+ formData.append('app_type', appType);
+ formData.append('auto_deploy', autoDeploy ? 'true' : 'false');
+ const result = await api.uploadAppZip(formData);
+ toast.success('Upload service created');
+ navigate(`/services/${result.app.id}`);
+ } else {
+ const payload = {
+ name: serviceName,
+ branch: branch.trim() || null,
+ app_type: appType,
+ build_method: buildMethod,
+ port: port ? Number(port) : null,
+ auto_deploy: autoDeploy,
+ };
+ if (recommended.dockerfile_path) payload.dockerfile_path = recommended.dockerfile_path;
+ if (recommended.custom_build_cmd) payload.custom_build_cmd = recommended.custom_build_cmd;
+ if (recommended.custom_start_cmd) payload.custom_start_cmd = recommended.custom_start_cmd;
+
+ if (sourceMode === 'github') {
+ payload.source_connection_id = githubConnection.id;
+ payload.repository_full_name = selectedRepo.full_name;
+ payload.repo_url = `https://github.com/${selectedRepo.full_name}.git`;
+ } else if (sourceMode === 'template') {
+ payload.template_id = selectedTemplate.id;
+ payload.repo_url = selectedTemplate.repoUrl;
+ } else {
+ payload.repo_url = normalizedManualRepo;
+ }
+
+ const result = await api.createAppFromRepository(payload);
+ toast.success('Repository service created');
+ navigate(`/services/${result.app.id}`);
+ }
} catch (err) {
- toast.error(err.message || 'Failed to create repository service');
+ toast.error(err.message || 'Failed to create service');
} finally {
setSubmitting(false);
}
@@ -375,6 +425,28 @@ const NewService = () => {
<span className="new-service-page__method-title">Other Git Remote</span>
<span className="new-service-page__method-sub">GitLab, Bitbucket, Gitea, or SSH</span>
</button>
+ <button
+ className={`new-service-page__method-card ${sourceMode === 'local' ? 'new-service-page__method-card--on' : ''}`}
+ type="button"
+ onClick={() => handleSourceModeChange('local')}
+ >
+ <span className="new-service-page__method-icon">
+ <FolderOpen size={21} />
+ </span>
+ <span className="new-service-page__method-title">Manual / Local</span>
+ <span className="new-service-page__method-sub">Register an app that already exists on the server</span>
+ </button>
+ <button
+ className={`new-service-page__method-card ${sourceMode === 'upload' ? 'new-service-page__method-card--on' : ''}`}
+ type="button"
+ onClick={() => handleSourceModeChange('upload')}
+ >
+ <span className="new-service-page__method-icon">
+ <FileArchive size={21} />
+ </span>
+ <span className="new-service-page__method-title">Upload ZIP</span>
+ <span className="new-service-page__method-sub">Deploy or update from a zip archive</span>
+ </button>
<button
className={`new-service-page__method-card ${sourceMode === 'template' ? 'new-service-page__method-card--on' : ''}`}
type="button"
@@ -392,7 +464,17 @@ const NewService = () => {
<section className="new-service-page__panel new-service-page__provider-panel">
<div className="new-service-page__section-heading">
<Link2 size={16} />
- <h2>{sourceMode === 'github' ? 'Pick Repository' : sourceMode === 'template' ? 'Choose Template' : 'Connect Source'}</h2>
+ <h2>
+ {sourceMode === 'github'
+ ? 'Pick Repository'
+ : sourceMode === 'template'
+ ? 'Choose Template'
+ : sourceMode === 'local'
+ ? 'Local Service'
+ : sourceMode === 'upload'
+ ? 'Upload Archive'
+ : 'Connect Source'}
+ </h2>
</div>
{sourceMode === 'github' ? (
@@ -516,6 +598,112 @@ const NewService = () => {
</Button>
</div>
</div>
+ ) : sourceMode === 'local' ? (
+ <div className="new-service-page__connect-box">
+ <div className="new-service-page__connect-heading">
+ <span className="new-service-page__connect-icon">
+ <FolderOpen size={18} />
+ </span>
+ <div>
+ <strong>Register an existing service</strong>
+ <span>Point ServerKit at a directory or systemd unit that is already on the server.</span>
+ </div>
+ </div>
+ <div className="new-service-page__field">
+ <Label htmlFor="local-path">Path on server</Label>
+ <Input
+ id="local-path"
+ value={localPath}
+ onChange={(e) => setLocalPath(e.target.value)}
+ placeholder="/opt/my-service"
+ autoComplete="off"
+ required={sourceMode === 'local'}
+ />
+ </div>
+ <div className="new-service-page__field">
+ <Label htmlFor="compose-file">Compose file (optional)</Label>
+ <Input
+ id="compose-file"
+ value={composeFile}
+ onChange={(e) => setComposeFile(e.target.value)}
+ placeholder="docker-compose.yml"
+ autoComplete="off"
+ />
+ </div>
+ <div className="new-service-page__field">
+ <Label htmlFor="systemd-unit">systemd unit (optional)</Label>
+ <Input
+ id="systemd-unit"
+ value={systemdUnit}
+ onChange={(e) => setSystemdUnit(e.target.value)}
+ placeholder="my-service"
+ autoComplete="off"
+ />
+ </div>
+ <div className="new-service-page__field">
+ <Label htmlFor="managed-by">Managed by</Label>
+ <select
+ id="managed-by"
+ value={managedBy}
+ onChange={(e) => setManagedBy(e.target.value)}
+ >
+ <option value="auto">Auto-detect</option>
+ <option value="docker_compose">Docker Compose</option>
+ <option value="systemd">systemd</option>
+ </select>
+ </div>
+ </div>
+ ) : sourceMode === 'upload' ? (
+ <div className="new-service-page__connect-box">
+ <div className="new-service-page__connect-heading">
+ <span className="new-service-page__connect-icon">
+ <FileArchive size={18} />
+ </span>
+ <div>
+ <strong>Upload a zip archive</strong>
+ <span>ServerKit will extract the archive, detect the runtime, and deploy it for you.</span>
+ </div>
+ </div>
+ <div
+ className={`new-service-page__upload-drop ${uploadDragOver ? 'new-service-page__upload-drop--over' : ''}`}
+ onDragOver={(e) => { e.preventDefault(); setUploadDragOver(true); }}
+ onDragLeave={() => setUploadDragOver(false)}
+ onDrop={(e) => {
+ e.preventDefault();
+ setUploadDragOver(false);
+ const file = e.dataTransfer.files[0];
+ if (file) {
+ setUploadFile(file);
+ if (!nameTouched) {
+ setName(slugify(file.name.replace(/\.zip$/i, '')));
+ }
+ }
+ }}
+ onClick={() => document.getElementById('upload-zip')?.click()}
+ >
+ <FileArchive size={32} />
+ <span>
+ {uploadFile
+ ? uploadFile.name
+ : 'Drag a zip here or click to browse'}
+ </span>
+ <input
+ id="upload-zip"
+ type="file"
+ accept=".zip,application/zip,application/x-zip-compressed"
+ className="sr-only"
+ onChange={(e) => {
+ const file = e.target.files[0];
+ if (file) {
+ setUploadFile(file);
+ if (!nameTouched) {
+ setName(slugify(file.name.replace(/\.zip$/i, '')));
+ }
+ }
+ }}
+ />
+ </div>
+ </div>
) : (
<div className="new-service-page__connect-box">
<div className="new-service-page__connect-heading">
@@ -541,19 +729,27 @@ const NewService = () => {
</div>
)}
- {(selectedRepo || sourceMode === 'manual' || selectedTemplate) && (
+ {(selectedRepo || sourceMode === 'manual' || sourceMode === 'local' || sourceMode === 'upload' || selectedTemplate) && (
<div className="new-service-page__repo-preview">
<div>
<span>Service</span>
- <strong>{serviceName || 'Auto-named from repo'}</strong>
- </div>
- <div>
- <span>Branch</span>
- <strong>{branch || 'main'}</strong>
+ <strong>{serviceName || 'Auto-named'}</strong>
</div>
+ {sourceMode !== 'local' && sourceMode !== 'upload' && (
+ <div>
+ <span>Branch</span>
+ <strong>{branch || 'main'}</strong>
+ </div>
+ )}
+ {sourceMode === 'local' && (
+ <div>
+ <span>Path</span>
+ <strong>{localPath || '—'}</strong>
+ </div>
+ )}
<div>
- <span>Build</span>
- <strong>{buildSummary}</strong>
+ <span>Type</span>
+ <strong>{sourceMode === 'upload' && appType === 'auto' ? 'Auto-detect' : formatAppType(appType)}</strong>
</div>
</div>
)}
@@ -565,15 +761,27 @@ const NewService = () => {
<Rocket size={18} />
</span>
<div>
- <h2>Ready to Import</h2>
- <p>ServerKit clones the selected repository, detects the runtime, configures builds, and records deployment settings.</p>
+ <h2>
+ {sourceMode === 'local'
+ ? 'Register Local Service'
+ : sourceMode === 'upload'
+ ? 'Deploy from Archive'
+ : 'Ready to Import'}
+ </h2>
+ <p>
+ {sourceMode === 'local'
+ ? 'ServerKit will link to the existing path or systemd unit and poll its real status.'
+ : sourceMode === 'upload'
+ ? 'ServerKit will extract the archive, detect the runtime, and deploy the service.'
+ : 'ServerKit clones the selected repository, detects the runtime, configures builds, and records deployment settings.'}
+ </p>
</div>
</div>
<div className="new-service-page__flow">
<div>
- <SiGithub size={16} />
- <span>Connect</span>
+ {sourceMode === 'local' ? <FolderOpen size={16} /> : sourceMode === 'upload' ? <FileArchive size={16} /> : <SiGithub size={16} />}
+ <span>{sourceMode === 'local' ? 'Path' : sourceMode === 'upload' ? 'Upload' : 'Connect'}</span>
</div>
<ArrowRight size={14} />
<div>
@@ -637,20 +845,38 @@ const NewService = () => {
<div className="new-service-page__summary">
<div>
<span>Source</span>
- <strong>{sourceMode === 'github' ? 'GitHub API' : sourceMode === 'template' ? 'Template' : 'Git remote'}</strong>
- </div>
- <div>
- <span>Repository</span>
- <strong>{selectedRepo?.full_name || selectedTemplate?.repoUrl || normalizedManualRepo || 'Not selected'}</strong>
+ <strong>
+ {sourceMode === 'github'
+ ? 'GitHub API'
+ : sourceMode === 'template'
+ ? 'Template'
+ : sourceMode === 'local'
+ ? 'Manual / Local'
+ : sourceMode === 'upload'
+ ? 'Upload'
+ : 'Git remote'}
+ </strong>
</div>
<div>
- <span>Build</span>
- <strong>{buildSummary}</strong>
+ <span>{sourceMode === 'local' ? 'Path' : sourceMode === 'upload' ? 'Archive' : 'Repository'}</span>
+ <strong>
+ {sourceMode === 'local'
+ ? localPath || 'Not set'
+ : sourceMode === 'upload'
+ ? uploadFile?.name || 'Not selected'
+ : selectedRepo?.full_name || selectedTemplate?.repoUrl || normalizedManualRepo || 'Not selected'}
+ </strong>
</div>
<div>
- <span>Auto-deploy</span>
- <strong>{autoDeploy ? 'On' : 'Off'}</strong>
+ <span>{sourceMode === 'upload' ? 'Detection' : 'Build'}</span>
+ <strong>{sourceMode === 'upload' ? (appType === 'auto' ? 'Auto-detect' : formatAppType(appType)) : buildSummary}</strong>
</div>
+ {sourceMode !== 'local' && (
+ <div>
+ <span>Auto-deploy</span>
+ <strong>{autoDeploy ? 'On' : 'Off'}</strong>
+ </div>
+ )}
</div>
<button
@@ -669,28 +895,30 @@ const NewService = () => {
{advancedOpen && (
<div className="new-service-page__advanced">
<div className="new-service-page__two-col">
- <div className="new-service-page__field">
- <Label htmlFor="branch">Branch</Label>
- {sourceMode === 'github' && branches.length > 0 ? (
- <select
- id="branch"
- value={branch}
- onChange={(e) => setBranch(e.target.value)}
- disabled={branchesLoading}
- >
- {branches.map(option => (
- <option key={option.name} value={option.name}>{option.name}</option>
- ))}
- </select>
- ) : (
- <Input
- id="branch"
- value={branch}
- onChange={(e) => setBranch(e.target.value)}
- placeholder="main"
- />
- )}
- </div>
+ {sourceMode !== 'local' && sourceMode !== 'upload' && (
+ <div className="new-service-page__field">
+ <Label htmlFor="branch">Branch</Label>
+ {sourceMode === 'github' && branches.length > 0 ? (
+ <select
+ id="branch"
+ value={branch}
+ onChange={(e) => setBranch(e.target.value)}
+ disabled={branchesLoading}
+ >
+ {branches.map(option => (
+ <option key={option.name} value={option.name}>{option.name}</option>
+ ))}
+ </select>
+ ) : (
+ <Input
+ id="branch"
+ value={branch}
+ onChange={(e) => setBranch(e.target.value)}
+ placeholder="main"
+ />
+ )}
+ </div>
+ )}
<div className="new-service-page__field">
<Label htmlFor="service-name">Service name</Label>
<Input
@@ -715,23 +943,26 @@ const NewService = () => {
value={appType}
onChange={(e) => setAppType(e.target.value)}
>
- {APP_TYPE_OPTIONS.map(option => (
- <option key={option.value} value={option.value}>{option.label}</option>
- ))}
- </select>
- </div>
- <div className="new-service-page__field">
- <Label htmlFor="build-method">Build method</Label>
- <select
- id="build-method"
- value={buildMethod}
- onChange={(e) => setBuildMethod(e.target.value)}
- >
- {BUILD_METHOD_OPTIONS.map(option => (
+ {sourceMode === 'upload' && <option value="auto">Auto-detect</option>}
+ {APP_TYPE_OPTIONS.filter(o => o.value !== 'auto').map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
</div>
+ {sourceMode !== 'local' && sourceMode !== 'upload' && (
+ <div className="new-service-page__field">
+ <Label htmlFor="build-method">Build method</Label>
+ <select
+ id="build-method"
+ value={buildMethod}
+ onChange={(e) => setBuildMethod(e.target.value)}
+ >
+ {BUILD_METHOD_OPTIONS.map(option => (
+ <option key={option.value} value={option.value}>{option.label}</option>
+ ))}
+ </select>
+ </div>
+ )}
</div>
<div className="new-service-page__two-col">
@@ -747,13 +978,15 @@ const NewService = () => {
max="65535"
/>
</div>
- <div className="new-service-page__toggle">
- <div>
- <Label>Auto-deploy</Label>
- <span>Webhook deployment for this branch.</span>
+ {sourceMode !== 'local' && (
+ <div className="new-service-page__toggle">
+ <div>
+ <Label>Auto-deploy</Label>
+ <span>{sourceMode === 'upload' ? 'Deploy immediately after upload.' : 'Webhook deployment for this branch.'}</span>
+ </div>
+ <Switch checked={autoDeploy} onCheckedChange={setAutoDeploy} />
</div>
- <Switch checked={autoDeploy} onCheckedChange={setAutoDeploy} />
- </div>
+ )}
</div>
</div>
)}
@@ -761,11 +994,17 @@ const NewService = () => {
<div className="new-service-page__notes">
<div className="new-service-page__note">
<ShieldCheck size={16} />
- <span>ServerKit checks serverkit.json, Docker Compose, Render, Railway, app.json, Dockerfile, and Nixpacks signals.</span>
+ <span>
+ {sourceMode === 'local'
+ ? 'ServerKit will read status from Docker Compose or systemd without modifying the original path.'
+ : sourceMode === 'upload'
+ ? 'Uploaded archives are versioned, so you can roll back to a previous release.'
+ : 'ServerKit checks serverkit.json, Docker Compose, Render, Railway, app.json, Dockerfile, and Nixpacks signals.'}
+ </span>
</div>
<div className="new-service-page__note">
<Lock size={16} />
- <span>Secret values from manifests stay empty until you add them to the service environment.</span>
+ <span>{sourceMode === 'upload' ? 'Existing .env files are preserved when uploading a new version.' : 'Secret values from manifests stay empty until you add them to the service environment.'}</span>
</div>
</div>
@@ -775,7 +1014,9 @@ const NewService = () => {
</Button>
<Button type="submit" disabled={!canSubmit || submitting}>
<Rocket size={16} />
- {submitting ? 'Importing...' : 'Import Repository'}
+ {submitting
+ ? (sourceMode === 'local' ? 'Registering...' : sourceMode === 'upload' ? 'Uploading...' : 'Importing...')
+ : (sourceMode === 'local' ? 'Register Service' : sourceMode === 'upload' ? 'Upload & Deploy' : 'Import Repository')}
</Button>
</div>
</aside>
diff --git a/frontend/src/pages/ServiceDetail.jsx b/frontend/src/pages/ServiceDetail.jsx
index c6b2610d..86415474 100644
--- a/frontend/src/pages/ServiceDetail.jsx
+++ b/frontend/src/pages/ServiceDetail.jsx
@@ -18,7 +18,7 @@ import CommandsTab from '../components/service-detail/CommandsTab';
import GitConnectModal from '../components/service-detail/GitConnectModal';
import OverviewTab from '../components/service-detail/OverviewTab';
import EmptyState from '../components/EmptyState';
-import { Layers } from 'lucide-react';
+import { Layers, FileArchive, RotateCcw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Pill, ServiceTile } from '@/components/ds';
@@ -55,6 +55,9 @@ const ServiceDetail = () => {
const [showMoreMenu, setShowMoreMenu] = useState(false);
const [showGitModal, setShowGitModal] = useState(false);
const [actionLoading, setActionLoading] = useState(null);
+ const [versions, setVersions] = useState([]);
+ const [currentVersion, setCurrentVersion] = useState(null);
+ const [versionsLoading, setVersionsLoading] = useState(false);
const deployMenuRef = useRef(null);
const moreMenuRef = useRef(null);
@@ -65,6 +68,19 @@ const ServiceDetail = () => {
}
}, [service, id, navigate]);
+ // Load upload versions
+ useEffect(() => {
+ if (!isUpload || !id) return;
+ setVersionsLoading(true);
+ api.getAppVersions(id)
+ .then(data => {
+ setVersions(data.versions || []);
+ setCurrentVersion(data.current);
+ })
+ .catch(() => toast.error('Failed to load versions'))
+ .finally(() => setVersionsLoading(false));
+ }, [isUpload, id, toast]);
+
// Close menus on outside click
useEffect(() => {
const handleClick = (e) => {
@@ -119,6 +135,45 @@ const ServiceDetail = () => {
}
}
+ async function handleRollback(version) {
+ setActionLoading(`rollback-${version}`);
+ try {
+ await api.rollbackAppVersion(service.id, version);
+ toast.success(`Rolled back to version ${version}`);
+ await reload();
+ const data = await api.getAppVersions(service.id);
+ setVersions(data.versions || []);
+ setCurrentVersion(data.current);
+ } catch (err) {
+ toast.error(err.message || 'Failed to rollback');
+ } finally {
+ setActionLoading(null);
+ }
+ }
+
+ async function handleUploadNewVersion(e) {
+ const file = e.target.files[0];
+ if (!file) return;
+ setActionLoading('upload-version');
+ try {
+ const formData = new FormData();
+ formData.append('file', file);
+ formData.append('name', service.name);
+ formData.append('app_type', 'auto');
+ formData.append('auto_deploy', 'true');
+ await api.uploadAppZip(formData);
+ toast.success('New version uploaded');
+ await reload();
+ const data = await api.getAppVersions(service.id);
+ setVersions(data.versions || []);
+ setCurrentVersion(data.current);
+ } catch (err) {
+ toast.error(err.message || 'Failed to upload new version');
+ } finally {
+ setActionLoading(null);
+ }
+ }
+
async function handleDelete() {
const firstConfirm = await confirm({ title: 'Delete Service', message: `Delete ${service.name}? This action cannot be undone.` });
if (!firstConfirm) return;
@@ -151,6 +206,9 @@ const ServiceDetail = () => {
}
const availableTabs = getTabsForType(service.app_type);
+ const isGitBased = service.source !== 'manual' && service.source !== 'upload';
+ const isUpload = service.source === 'upload';
+ const isManual = service.source === 'manual';
return (
<div className="page-container svc-detail">
@@ -216,7 +274,7 @@ const ServiceDetail = () => {
</svg>
Manual Deploy (Restart)
</button>
- {deployConfig && (
+ {isGitBased && deployConfig && (
<button onClick={handleDeployLatest} disabled={actionLoading === 'deploy-latest'}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<circle cx="18" cy="18" r="3"/>
@@ -310,7 +368,31 @@ const ServiceDetail = () => {
{/* Repo Connection Pill */}
<div className="svc-detail__repo-bar">
- {deployConfig ? (
+ {isUpload ? (
+ <span className="svc-detail__repo-pill svc-detail__repo-pill--static">
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
+ <polyline points="17 8 12 3 7 8"/>
+ <line x1="12" y1="3" x2="12" y2="15"/>
+ </svg>
+ <span className="svc-detail__repo-url">Upload</span>
+ <span className="svc-detail__repo-arrow">&rarr;</span>
+ <span className="svc-detail__repo-branch">Version {service.version || 1}</span>
+ </span>
+ ) : isManual ? (
+ <span className="svc-detail__repo-pill svc-detail__repo-pill--static">
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
+ <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
+ </svg>
+ <span className="svc-detail__repo-url">{service.root_path || 'Local service'}</span>
+ {service.managed_by && (
+ <>
+ <span className="svc-detail__repo-arrow">&rarr;</span>
+ <span className="svc-detail__repo-branch">{service.managed_by === 'docker_compose' ? 'Docker Compose' : 'systemd'}</span>
+ </>
+ )}
+ </span>
+ ) : deployConfig ? (
<div className="svc-detail__repo-pill" onClick={() => setShowGitModal(true)}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<circle cx="18" cy="18" r="3"/>
@@ -336,6 +418,50 @@ const ServiceDetail = () => {
)}
</div>
+ {/* Upload versions panel */}
+ {isUpload && (
+ <div className="svc-detail__versions">
+ <div className="svc-detail__versions-header">
+ <h3>Versions</h3>
+ <label className="svc-detail__upload-label">
+ <input
+ type="file"
+ accept=".zip,application/zip,application/x-zip-compressed"
+ onChange={handleUploadNewVersion}
+ disabled={actionLoading === 'upload-version'}
+ />
+ <FileArchive size={14} />
+ {actionLoading === 'upload-version' ? 'Uploading...' : 'Upload New Version'}
+ </label>
+ </div>
+ {versionsLoading ? (
+ <div className="svc-detail__versions-loading">Loading versions...</div>
+ ) : (
+ <ul className="svc-detail__versions-list">
+ {versions.slice().reverse().map(v => (
+ <li key={v.version} className={v.version === currentVersion ? 'is-current' : ''}>
+ <span className="svc-detail__version-name">v{v.version}</span>
+ <span className="svc-detail__version-date">{new Date(v.created_at).toLocaleString()}</span>
+ {v.version === currentVersion ? (
+ <span className="svc-detail__version-current">Current</span>
+ ) : (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => handleRollback(v.version)}
+ disabled={actionLoading === `rollback-${v.version}`}
+ >
+ <RotateCcw size={14} />
+ Rollback
+ </Button>
+ )}
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
+
{/* Tab Bar */}
<div className="svc-detail__tabs">
{availableTabs.map(tab => (
@@ -371,7 +497,7 @@ const ServiceDetail = () => {
</div>
{/* Git Connect Modal */}
- {showGitModal && (
+ {showGitModal && isGitBased && (
<GitConnectModal
appId={service.id}
deployConfig={deployConfig}
diff --git a/frontend/src/pages/Services.jsx b/frontend/src/pages/Services.jsx
index 0d86b7ae..5a92f571 100644
--- a/frontend/src/pages/Services.jsx
+++ b/frontend/src/pages/Services.jsx
@@ -1,6 +1,6 @@
import React, { useState, useEffect, useMemo } from 'react';
import { useNavigate, Link } from 'react-router-dom';
-import { Box, Layers, Plus, Activity, Square, Clock, Play, RotateCw, GitBranch, Github } from 'lucide-react';
+import { Box, Layers, Plus, Activity, Square, Clock, Play, RotateCw, GitBranch, Github, FolderOpen, FileArchive } from 'lucide-react';
import api from '../services/api';
import { useToast } from '../contexts/ToastContext';
import { getServiceType, getStatusConfig, formatRelativeTime } from '../utils/serviceTypes';
@@ -334,6 +334,16 @@ const Services = () => {
{isGithub ? <Github size={12} /> : <GitBranch size={12} />}
{extractRepoName(app.deploy_repo_url)}
</span>
+ ) : app.source === 'manual' ? (
+ <span className="services-page__src-badge services-page__src-badge--manual" title={app.root_path || ''}>
+ <FolderOpen size={12} />
+ Local
+ </span>
+ ) : app.source === 'upload' ? (
+ <span className="services-page__src-badge services-page__src-badge--upload" title={app.upload_path || ''}>
+ <FileArchive size={12} />
+ Upload v{app.version || 1}
+ </span>
) : (
<span className="services-page__nil">—</span>
)}
diff --git a/frontend/src/services/api/apps.js b/frontend/src/services/api/apps.js
index 0988acd1..719032c6 100644
--- a/frontend/src/services/api/apps.js
+++ b/frontend/src/services/api/apps.js
@@ -49,6 +49,32 @@ export async function createAppFromRepository(appData) {
});
}
+export async function createManualApp(appData) {
+ return this.request('/apps/manual', {
+ method: 'POST',
+ body: appData,
+ });
+}
+
+export async function uploadAppZip(formData) {
+ return this.request('/apps/upload', {
+ method: 'POST',
+ body: formData,
+ headers: {},
+ });
+}
+
+export async function getAppVersions(appId) {
+ return this.request(`/apps/${appId}/versions`);
+}
+
+export async function rollbackAppVersion(appId, version) {
+ return this.request(`/apps/${appId}/rollback`, {
+ method: 'POST',
+ body: { version },
+ });
+}
+
export async function updateApp(id, appData) {
return this.request(`/apps/${id}`, {
method: 'PUT',
diff --git a/frontend/src/styles/pages/_new-service.scss b/frontend/src/styles/pages/_new-service.scss
index 21301edb..e73858f4 100644
--- a/frontend/src/styles/pages/_new-service.scss
+++ b/frontend/src/styles/pages/_new-service.scss
@@ -54,6 +54,12 @@
margin-bottom: $space-4;
}
+ @media (max-width: $breakpoint-md) {
+ &__method-grid {
+ grid-template-columns: 1fr;
+ }
+ }
+
&__method-card {
display: block;
position: relative;
@@ -872,6 +878,37 @@
gap: $space-2;
padding-top: $space-1;
}
+
+ &__upload-drop {
+ display: grid;
+ place-items: center;
+ gap: $space-3;
+ min-height: 160px;
+ padding: $space-5;
+ background: $bg-elevated;
+ border: 2px dashed $border-subtle;
+ border-radius: $radius-lg;
+ color: $text-tertiary;
+ text-align: center;
+ cursor: pointer;
+ transition: border-color $transition-fast, background $transition-fast, color $transition-fast;
+
+ &:hover,
+ &--over {
+ background: var(--accent-bg, rgba(109, 124, 255, 0.08));
+ border-color: var(--accent-dim, $accent-primary);
+ color: $text-secondary;
+ }
+
+ span {
+ font-size: $font-size-sm;
+ font-weight: $font-weight-medium;
+ }
+
+ input {
+ display: none;
+ }
+ }
}
@media (max-width: $breakpoint-xl) {
diff --git a/frontend/src/styles/pages/_service-detail.scss b/frontend/src/styles/pages/_service-detail.scss
index ffc34bc1..023f8e63 100644
--- a/frontend/src/styles/pages/_service-detail.scss
+++ b/frontend/src/styles/pages/_service-detail.scss
@@ -208,6 +208,15 @@
border-color: var(--accent-dim);
background: var(--surface-2);
}
+
+ &--static {
+ cursor: default;
+
+ &:hover {
+ border-color: var(--border);
+ background: var(--surface);
+ }
+ }
}
&__repo-url {
@@ -257,6 +266,99 @@
}
}
+ &__versions {
+ margin-bottom: $space-5;
+ padding: $space-4;
+ background: var(--surface);
+ border: 1px solid var(--border);
+ border-radius: $radius-lg;
+ }
+
+ &__versions-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: $space-3;
+ margin-bottom: $space-3;
+
+ h3 {
+ margin: 0;
+ font-size: $font-size-sm;
+ font-weight: $font-weight-semibold;
+ color: var(--text-primary);
+ }
+ }
+
+ &__upload-label {
+ display: inline-flex;
+ align-items: center;
+ gap: $space-2;
+ padding: 6px $space-3;
+ background: var(--accent-bg-soft);
+ border: 1px solid var(--accent-dim);
+ border-radius: $radius-md;
+ color: var(--accent-bright);
+ font-size: $font-size-xs;
+ font-weight: $font-weight-medium;
+ cursor: pointer;
+ transition: background $transition-fast;
+
+ &:hover {
+ background: var(--accent-bg);
+ }
+
+ input {
+ display: none;
+ }
+ }
+
+ &__versions-list {
+ display: grid;
+ gap: $space-2;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+
+ li {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: $space-3;
+ padding: $space-3;
+ background: var(--surface-2);
+ border: 1px solid var(--border);
+ border-radius: $radius-md;
+
+ &.is-current {
+ border-color: rgba(61, 220, 151, 0.35);
+ background: rgba(61, 220, 151, 0.06);
+ }
+ }
+ }
+
+ &__version-name {
+ font-family: var(--mono);
+ font-size: $font-size-sm;
+ font-weight: $font-weight-semibold;
+ color: var(--text-primary);
+ }
+
+ &__version-date {
+ margin-left: auto;
+ color: var(--text-faint);
+ font-size: $font-size-xs;
+ }
+
+ &__version-current {
+ padding: 3px $space-2;
+ background: rgba(61, 220, 151, 0.1);
+ border: 1px solid rgba(61, 220, 151, 0.2);
+ border-radius: $radius-full;
+ color: #3ddc97;
+ font-size: $font-size-xs;
+ font-weight: $font-weight-medium;
+ }
+
// Tab strip — accent wash on the active chip
&__tabs {
display: flex;
diff --git a/frontend/src/styles/pages/_services.scss b/frontend/src/styles/pages/_services.scss
index 5d8b4b49..96dd02bf 100644
--- a/frontend/src/styles/pages/_services.scss
+++ b/frontend/src/styles/pages/_services.scss
@@ -146,6 +146,18 @@
white-space: nowrap;
svg { flex-shrink: 0; color: var(--text-faint); }
+
+ &--manual {
+ background: rgba(245, 185, 69, 0.08);
+ border-color: rgba(245, 185, 69, 0.2);
+ color: #f5b945;
+ }
+
+ &--upload {
+ background: rgba(176, 123, 245, 0.08);
+ border-color: rgba(176, 123, 245, 0.2);
+ color: #b07bf5;
+ }
}
&__nil { color: var(--text-ghost); }