ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat: Phase 3 team & scale — projects/environments, shared resources, PR previews, proxy stacks
Juan Denis478b24a3cb65
diff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex 681bb1fd..689fe1d6 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -171,6 +171,26 @@ def create_app(config_name=None):from app.api.snapshots import snapshots_bpapp.register_blueprint(snapshots_bp, url_prefix='/api/v1/apps')+ # Register blueprints - Projects & Environments hierarchy+ from app.api.projects import projects_bp+ app.register_blueprint(projects_bp, url_prefix='/api/v1/projects')+ from app.api.environments import environments_bp+ app.register_blueprint(environments_bp, url_prefix='/api/v1/environments')++ # Register blueprints - Polymorphic shared resources (tags + variable groups)+ from app.api.shared_resources import shared_resources_bp+ app.register_blueprint(shared_resources_bp, url_prefix='/api/v1/shared')++ # Register blueprints - PR preview environments+ from app.api.previews import previews_bp+ app.register_blueprint(previews_bp, url_prefix='/api/v1/apps')+ from app.api.webhooks import webhooks_bp+ app.register_blueprint(webhooks_bp, url_prefix='/api/v1/webhooks')++ # Register blueprints - Per-server managed proxy stack+ from app.api.proxy import proxy_bp+ app.register_blueprint(proxy_bp, url_prefix='/api/v1/servers')+# Register blueprints - Notificationsfrom app.api.notifications import notifications_bpapp.register_blueprint(notifications_bp, url_prefix='/api/v1/notifications')@@ -471,6 +491,8 @@ def create_app(config_name=None):BackupPolicyService.register_jobs()from app.services.server_onboarding_service import ServerOnboardingServiceServerOnboardingService.register_jobs()+ from app.services.preview_service import PreviewService+ PreviewService.register_jobs()start_job_system(app, seed=seed_builtin_schedules)# Request body size limitdiff --git a/backend/app/api/apps.py b/backend/app/api/apps.pyindex fabfe181..099bd4c6 100644--- a/backend/app/api/apps.py+++ b/backend/app/api/apps.py@@ -414,6 +414,50 @@ def set_app_workspace(app_id):return jsonify({'message': 'Workspace updated', 'app': app.to_dict()}), 200+def _resolve_project_env(data, workspace_id):+ """Validate optional project_id/environment_id from a create payload against+ the app's workspace. Returns (project_id, environment_id) with invalid values+ silently ignored (set to None), so a bad/foreign id can never break a create.++ - project must belong to `workspace_id`.+ - environment must belong to that project; if an environment is supplied+ without a project, its parent project is used (still workspace-checked).+ """+ from app.models.project import Project+ from app.models.environment import Environment++ def _as_int(v):+ if v in (None, '', 'null'):+ return None+ try:+ return int(v)+ except (TypeError, ValueError):+ return None++ project_id = _as_int(data.get('project_id'))+ environment_id = _as_int(data.get('environment_id'))+ if project_id is None and environment_id is None:+ return None, None++ env = None+ if environment_id is not None:+ env = Environment.query.get(environment_id)+ if env is None:+ environment_id = None+ elif project_id is None:+ project_id = env.project_id++ project = Project.query.get(project_id) if project_id is not None else None+ if project is None or project.workspace_id != workspace_id:+ # No valid project in this workspace -> drop both.+ return None, None++ # Environment must belong to the resolved project.+ if env is not None and env.project_id != project.id:+ environment_id = None+ return project.id, environment_id++def _can_access_app(user, app):"""Read access (#33 ACL) — delegates to the shared seam."""from app.services.resource_grant_service import ResourceGrantService@@ -623,6 +667,15 @@ def create_app_from_repository():buildpack_plan = effective_planbuildpack_type = (effective_plan or {}).get('builder')+ # Optional Project / Environment assignment. Validated against the resolved+ # workspace; invalid/foreign ids are silently dropped (non-breaking).+ 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+ project_id, environment_id = _resolve_project_env(data, _ws_id)+app = Application(name=name,app_type=resolved_app_type,@@ -633,6 +686,8 @@ def create_app_from_repository():buildpack_type=buildpack_type,buildpack_plan=json.dumps(buildpack_plan) if buildpack_plan else None,buildpack_overrides=json.dumps(buildpack_overrides) if buildpack_overrides else None,+ project_id=project_id,+ environment_id=environment_id,)try:@@ -720,6 +775,8 @@ def create_app():if ws_id is None:ws_id = WorkspaceService.ensure_default_workspace().id+ project_id, environment_id = _resolve_project_env(data, ws_id)+app = Application(name=name,app_type=app_type,@@ -734,7 +791,9 @@ def create_app():systemd_unit=data.get('systemd_unit'),managed_by=data.get('managed_by'),user_id=current_user_id,- workspace_id=ws_id+ workspace_id=ws_id,+ project_id=project_id,+ environment_id=environment_id,)db.session.add(app)@@ -803,6 +862,8 @@ def create_manual_app():if ws_id is None:ws_id = WorkspaceService.ensure_default_workspace().id+ project_id, environment_id = _resolve_project_env(data, ws_id)+app = Application(name=name,app_type=app_type,@@ -814,6 +875,8 @@ def create_manual_app():managed_by=managed_by,user_id=current_user_id,workspace_id=ws_id,+ project_id=project_id,+ environment_id=environment_id,)db.session.add(app)@@ -919,6 +982,7 @@ def upload_app_archive():app.root_path = current_dirapp.updated_at = datetime.utcnow()else:+ project_id, environment_id = _resolve_project_env(request.form, ws_id)app = Application(name=name,app_type=detected,@@ -931,6 +995,8 @@ def upload_app_archive():upload_path=upload_archive_path,user_id=current_user_id,workspace_id=ws_id,+ project_id=project_id,+ environment_id=environment_id,)db.session.add(app)diff --git a/backend/app/api/environments.py b/backend/app/api/environments.pynew file mode 100644index 00000000..63c51b8d--- /dev/null+++ b/backend/app/api/environments.py@@ -0,0 +1,126 @@+"""Environment endpoints (under a Project).++Environments are children of a project; access is derived from the parent+project's workspace, mirroring projects.py.+"""+from flask import Blueprint, request, jsonify+from flask_jwt_extended import jwt_required, get_jwt_identity++from app.models.user import User+from app.services.project_service import ProjectService+from app.services.workspace_service import WorkspaceService++environments_bp = Blueprint('environments', __name__)+++def _current_user():+ return User.query.get(get_jwt_identity())+++def _accessible_workspace_ids(user):+ ws_id = WorkspaceService.resolve_workspace_id(+ user, request.headers.get('X-Workspace-Id') or request.args.get('workspace_id'))+ if ws_id is not None:+ return [ws_id]+ if user.is_admin:+ from app.models.workspace import Workspace+ return [w.id for w in Workspace.query.all()]+ return [w.id for w in WorkspaceService.list_workspaces(user_id=user.id)]+++def _project_for_write(user, project_id):+ """Return (project, error_response). error_response is a (json, status) tuple+ when the project can't be written by this user, else None."""+ project = ProjectService.get_project(project_id)+ if not project:+ return None, (jsonify({'error': 'Project not found'}), 404)+ if not user.is_admin and project.workspace_id not in set(_accessible_workspace_ids(user)):+ return None, (jsonify({'error': 'Access denied'}), 403)+ if not WorkspaceService.can_write_in_workspace(user, project.workspace_id):+ return None, (jsonify({'error': 'You have read-only access to this workspace'}), 403)+ return project, None+++@environments_bp.route('', methods=['POST'])+@environments_bp.route('/', methods=['POST'])+@jwt_required()+def create_environment():+ """Create an environment under a project. Body: {project_id, name, is_default?}."""+ user = _current_user()+ data = request.get_json() or {}+ project_id = data.get('project_id')+ if not project_id:+ return jsonify({'error': 'project_id is required'}), 400+ name = (data.get('name') or '').strip()+ if not name:+ return jsonify({'error': 'Environment name is required'}), 400++ project, err = _project_for_write(user, project_id)+ if err:+ return err++ try:+ env = ProjectService.create_environment(+ project_id, name=name, is_default=bool(data.get('is_default')))+ except ValueError as exc:+ return jsonify({'error': str(exc)}), 400+ from app import db+ db.session.commit()+ return jsonify({'message': 'Environment created', 'environment': env.to_dict(include_counts=True)}), 201+++@environments_bp.route('/<int:environment_id>', methods=['PUT'])+@jwt_required()+def update_environment(environment_id):+ user = _current_user()+ env = ProjectService.get_environment(environment_id)+ if not env:+ return jsonify({'error': 'Environment not found'}), 404+ _, err = _project_for_write(user, env.project_id)+ if err:+ return err++ data = request.get_json() or {}+ updated = ProjectService.update_environment(+ environment_id, name=data.get('name'), is_default=data.get('is_default'))+ return jsonify({'message': 'Environment updated', 'environment': updated.to_dict(include_counts=True)}), 200+++@environments_bp.route('/<int:environment_id>', methods=['DELETE'])+@jwt_required()+def delete_environment(environment_id):+ """Delete an environment. Refuses (409) if it's the project's only one;+ detaches assigned apps (environment_id -> NULL) otherwise."""+ user = _current_user()+ env = ProjectService.get_environment(environment_id)+ if not env:+ return jsonify({'error': 'Environment not found'}), 404+ _, err = _project_for_write(user, env.project_id)+ if err:+ return err++ result = ProjectService.delete_environment(environment_id)+ if result == 'last':+ return jsonify({'error': 'Cannot delete the only environment of a project.'}), 409+ return jsonify({'message': 'Environment deleted'}), 200+++@environments_bp.route('/reorder', methods=['POST'])+@jwt_required()+def reorder_environments():+ """Reorder a project's environments. Body: {project_id, ordered_ids:[...]}"""+ user = _current_user()+ data = request.get_json() or {}+ project_id = data.get('project_id')+ ordered_ids = data.get('ordered_ids')+ if not project_id:+ return jsonify({'error': 'project_id is required'}), 400+ if not isinstance(ordered_ids, list):+ return jsonify({'error': 'ordered_ids must be a list'}), 400++ _, err = _project_for_write(user, project_id)+ if err:+ return err++ envs = ProjectService.reorder_environments(project_id, ordered_ids)+ return jsonify({'environments': [e.to_dict(include_counts=True) for e in envs]}), 200diff --git a/backend/app/api/previews.py b/backend/app/api/previews.pynew file mode 100644index 00000000..a02148a3--- /dev/null+++ b/backend/app/api/previews.py@@ -0,0 +1,110 @@+"""PR Preview Environments API.++Mounted by the host at ``/api/v1/apps`` so every route here is nested under an+application id, e.g. ``GET /api/v1/apps/<app_id>/previews``.+"""+from flask import Blueprint, request, jsonify+from flask_jwt_extended import jwt_required++from app.middleware.rbac import developer_required+from app.models import Application+from app.models.application_preview import ApplicationPreview+from app.services.preview_service import PreviewService++previews_bp = Blueprint('previews', __name__)+++def _get_app_or_404(app_id):+ app = Application.query.get(app_id)+ if not app:+ return None, (jsonify({'error': 'Application not found'}), 404)+ return app, None+++@previews_bp.route('/<int:app_id>/previews', methods=['GET'])+@jwt_required()+def list_previews(app_id):+ """List the non-destroyed previews for an application (newest first)."""+ app, err = _get_app_or_404(app_id)+ if err:+ return err+ previews = ApplicationPreview.query.filter(+ ApplicationPreview.application_id == app_id,+ ApplicationPreview.status != ApplicationPreview.STATUS_DESTROYED,+ ).order_by(ApplicationPreview.pr_number.desc()).all()+ return jsonify({'previews': [p.to_dict() for p in previews]}), 200+++@previews_bp.route('/<int:app_id>/previews/settings', methods=['GET'])+@jwt_required()+def get_preview_settings(app_id):+ """Return the per-app preview settings (defaults when never configured)."""+ app, err = _get_app_or_404(app_id)+ if err:+ return err+ settings = PreviewService.get_settings(app_id)+ return jsonify(settings.to_dict()), 200+++@previews_bp.route('/<int:app_id>/previews/settings', methods=['PUT'])+@developer_required+def update_preview_settings(app_id):+ """Enable/disable previews and set the domain template + TTL for an app."""+ app, err = _get_app_or_404(app_id)+ if err:+ return err+ data = request.get_json(silent=True) or {}+ try:+ result = PreviewService.enable_previews(app_id, data)+ except Exception as exc: # pragma: no cover - defensive+ return jsonify({'error': str(exc)}), 400+ return jsonify(result), 200+++@previews_bp.route('/<int:app_id>/previews/sync', methods=['POST'])+@developer_required+def sync_previews(app_id):+ """Reconcile this app's previews against its open PRs (best-effort)."""+ app, err = _get_app_or_404(app_id)+ if err:+ return err+ result = PreviewService.sync_previews(app_id)+ status = 400 if result.get('error') else 200+ return jsonify(result), status+++@previews_bp.route('/<int:app_id>/previews/<int:preview_id>/redeploy', methods=['POST'])+@developer_required+def redeploy_preview(app_id, preview_id):+ """Re-provision a preview for the same PR (idempotent update-in-place)."""+ app, err = _get_app_or_404(app_id)+ if err:+ return err+ preview = ApplicationPreview.query.filter_by(+ id=preview_id, application_id=app_id).first()+ if not preview:+ return jsonify({'error': 'Preview not found'}), 404+ result = PreviewService.create_preview(app, {+ 'pr_number': preview.pr_number,+ 'branch': preview.branch,+ 'pr_title': preview.pr_title,+ 'commit_sha': preview.commit_sha,+ })+ status = 400 if result.get('error') else 200+ return jsonify(result), status+++@previews_bp.route('/<int:app_id>/previews/<int:preview_id>', methods=['DELETE'])+@developer_required+def destroy_preview(app_id, preview_id):+ """Tear down and mark a preview destroyed."""+ app, err = _get_app_or_404(app_id)+ if err:+ return err+ preview = ApplicationPreview.query.filter_by(+ id=preview_id, application_id=app_id).first()+ if not preview:+ return jsonify({'error': 'Preview not found'}), 404+ result = PreviewService.destroy_preview(preview_id)+ status = 400 if result.get('error') else 200+ return jsonify(result), statusdiff --git a/backend/app/api/projects.py b/backend/app/api/projects.pynew file mode 100644index 00000000..0502532d--- /dev/null+++ b/backend/app/api/projects.py@@ -0,0 +1,157 @@+"""Project endpoints (Workspace -> Project -> Environment -> Applications).++Projects are workspace-scoped. The active workspace is resolved the same way the+rest of the app resolves it: the X-Workspace-Id header (or ?workspace_id=), via+WorkspaceService.resolve_workspace_id (membership-checked, lenient). With no+active context we fall back to the workspaces the caller can access, so the list+always reflects the user's own projects without needing a header.+"""+from flask import Blueprint, request, jsonify+from flask_jwt_extended import jwt_required, get_jwt_identity++from app.models.user import User+from app.models.project import Project+from app.services.project_service import ProjectService+from app.services.workspace_service import WorkspaceService++projects_bp = Blueprint('projects', __name__)+++def _current_user():+ return User.query.get(get_jwt_identity())+++def _active_workspace_id(user):+ """Resolve the active workspace for stamping a new project, defaulting to the+ user's Default workspace when no valid context is supplied."""+ 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+ return ws_id+++def _accessible_workspace_ids(user):+ """Workspace ids the caller may see projects for. With an explicit, valid+ workspace context, just that one; otherwise all the user's workspaces (admins+ see all)."""+ ws_id = WorkspaceService.resolve_workspace_id(+ user, request.headers.get('X-Workspace-Id') or request.args.get('workspace_id'))+ if ws_id is not None:+ return [ws_id]+ if user.is_admin:+ from app.models.workspace import Workspace+ return [w.id for w in Workspace.query.all()]+ return [w.id for w in WorkspaceService.list_workspaces(user_id=user.id)]+++def _can_view_project(user, project):+ if user.is_admin:+ return True+ return project.workspace_id in set(_accessible_workspace_ids(user))+++@projects_bp.route('', methods=['GET'])+@projects_bp.route('/', methods=['GET'])+@jwt_required()+def list_projects():+ """List projects in the accessible workspace(s), each with resource counts."""+ user = _current_user()+ ws_ids = _accessible_workspace_ids(user)+ projects = []+ for ws_id in ws_ids:+ projects.extend(ProjectService.list_projects(ws_id))+ return jsonify({'projects': [p.to_dict(include_counts=True) for p in projects]}), 200+++@projects_bp.route('', methods=['POST'])+@projects_bp.route('/', methods=['POST'])+@jwt_required()+def create_project():+ """Create a project (auto-creates a default environment)."""+ user = _current_user()+ data = request.get_json() or {}+ name = (data.get('name') or '').strip()+ if not name:+ return jsonify({'error': 'Project name is required'}), 400++ ws_id = _active_workspace_id(user)+ if not WorkspaceService.can_write_in_workspace(user, ws_id):+ return jsonify({'error': 'You have read-only access to this workspace'}), 403++ try:+ project = ProjectService.create_project(+ workspace_id=ws_id,+ name=name,+ description=data.get('description'),+ metadata=data.get('metadata'),+ default_environment=data.get('default_environment') or 'production',+ )+ except ValueError as exc:+ return jsonify({'error': str(exc)}), 400++ result = project.to_dict(include_counts=True)+ result['environments'] = [e.to_dict(include_counts=True)+ for e in ProjectService.list_environments(project.id)]+ return jsonify({'message': 'Project created', 'project': result}), 201+++@projects_bp.route('/<int:project_id>', methods=['GET'])+@jwt_required()+def get_project(project_id):+ """Get a project with its environments and resource counts."""+ user = _current_user()+ project = ProjectService.get_project(project_id)+ if not project:+ return jsonify({'error': 'Project not found'}), 404+ if not _can_view_project(user, project):+ return jsonify({'error': 'Access denied'}), 403++ result = project.to_dict(include_counts=True)+ result['environments'] = [e.to_dict(include_counts=True)+ for e in ProjectService.list_environments(project_id)]+ return jsonify({'project': result}), 200+++@projects_bp.route('/<int:project_id>', methods=['PUT'])+@jwt_required()+def update_project(project_id):+ user = _current_user()+ project = ProjectService.get_project(project_id)+ if not project:+ return jsonify({'error': 'Project not found'}), 404+ if not _can_view_project(user, project):+ return jsonify({'error': 'Access denied'}), 403+ if not WorkspaceService.can_write_in_workspace(user, project.workspace_id):+ return jsonify({'error': 'You have read-only access to this workspace'}), 403++ data = request.get_json() or {}+ updated = ProjectService.update_project(+ project_id,+ name=data.get('name'),+ description=data.get('description'),+ metadata=data.get('metadata'),+ )+ return jsonify({'message': 'Project updated', 'project': updated.to_dict(include_counts=True)}), 200+++@projects_bp.route('/<int:project_id>', methods=['DELETE'])+@jwt_required()+def delete_project(project_id):+ """Delete a project. Refuses (409) if it still has applications assigned."""+ user = _current_user()+ project = ProjectService.get_project(project_id)+ if not project:+ return jsonify({'error': 'Project not found'}), 404+ if not _can_view_project(user, project):+ return jsonify({'error': 'Access denied'}), 403+ if not WorkspaceService.can_write_in_workspace(user, project.workspace_id):+ return jsonify({'error': 'You have read-only access to this workspace'}), 403++ result = ProjectService.delete_project(project_id)+ if result == 'has_apps':+ return jsonify({+ 'error': 'Project still has applications assigned. Reassign or remove them first.',+ 'app_count': ProjectService.count_project_apps(project_id),+ }), 409+ return jsonify({'message': 'Project deleted'}), 200diff --git a/backend/app/api/proxy.py b/backend/app/api/proxy.pynew file mode 100644index 00000000..81208023--- /dev/null+++ b/backend/app/api/proxy.py@@ -0,0 +1,145 @@+"""Managed reverse-proxy stack API.++Per-server endpoints for the opt-in Dockerized proxy (Traefik/Caddy). Host+nginx remains the default; these routes let an operator switch a server to a+managed proxy stack, preview the generated compose, and (best-effort)+regenerate/deploy it.++Mounted by the app factory at ``/api/v1/servers`` so paths are+``/servers/<server_id>/proxy*``. Reads require auth; mutations require+developer access (matching servers.py group/server mutations).+"""+from flask import Blueprint, request, jsonify++from flask_jwt_extended import jwt_required++from app.models.server import Server+from app.middleware.rbac import developer_required+from app.services.proxy_stack_service import ProxyStackService++proxy_bp = Blueprint('proxy', __name__)+++def _require_server(server_id):+ """Return (server, None) or (None, error_response_tuple)."""+ server = Server.query.get(server_id)+ if not server:+ return None, (jsonify({'error': 'Server not found'}), 404)+ return server, None+++@proxy_bp.route('/<server_id>/proxy', methods=['GET'])+@jwt_required()+def get_proxy(server_id):+ """Get the managed proxy stack state for a server (best-effort status)."""+ _, err = _require_server(server_id)+ if err:+ return err+ return jsonify(ProxyStackService.status(server_id))+++@proxy_bp.route('/<server_id>/proxy/compose-preview', methods=['GET'])+@jwt_required()+def compose_preview(server_id):+ """Preview the generated docker-compose for a proxy type (no writes).++ ``?proxy_type=traefik|caddy|nginx`` overrides the stored type so the UI+ can preview before switching. Returns ``compose: null`` for nginx.+ """+ _, err = _require_server(server_id)+ if err:+ return err++ stack = ProxyStackService.get_or_create(server_id)+ proxy_type = request.args.get('proxy_type', stack.proxy_type)++ options = {}+ if request.args.get('acme_email'):+ options['acme_email'] = request.args.get('acme_email')+ if request.args.get('dashboard') in ('1', 'true', 'yes'):+ options['dashboard'] = True++ try:+ compose = ProxyStackService.generate_compose(server_id, proxy_type, options)+ config = ProxyStackService.generate_config(+ proxy_type, [], stack.custom_snippet+ )+ except ValueError as e:+ return jsonify({'error': str(e)}), 400++ return jsonify({+ 'proxy_type': proxy_type,+ 'compose': compose,+ 'config': config,+ })+++@proxy_bp.route('/<server_id>/proxy/configure', methods=['POST'])+@jwt_required()+@developer_required+def configure_proxy(server_id):+ """Update proxy type and/or custom snippet for a server.++ Body: ``{proxy_type?, custom_snippet?, deploy?}``. When ``deploy`` is+ truthy and the type is a stack proxy, a best-effort compose-up runs.+ """+ _, err = _require_server(server_id)+ if err:+ return err++ data = request.get_json() or {}+ proxy_type = data.get('proxy_type')+ custom_snippet = data.get('custom_snippet')++ try:+ stack = ProxyStackService.configure(+ server_id,+ proxy_type=proxy_type,+ custom_snippet=custom_snippet,+ )+ except ValueError as e:+ return jsonify({'error': str(e)}), 400++ result = stack.to_dict()+ if data.get('deploy') and stack.proxy_type != 'nginx':+ result['deploy'] = ProxyStackService.deploy_stack(server_id)++ return jsonify(result)+++@proxy_bp.route('/<server_id>/proxy/regenerate', methods=['POST'])+@jwt_required()+@developer_required+def regenerate_proxy(server_id):+ """Rewrite the proxy config and best-effort hot-reload the stack."""+ _, err = _require_server(server_id)+ if err:+ return err++ data = request.get_json() or {}+ sites = data.get('sites')+ result = ProxyStackService.regenerate(server_id, sites=sites)+ status = 200 if result.get('success') else 502+ return jsonify(result), status+++@proxy_bp.route('/<server_id>/proxy/switch', methods=['POST'])+@jwt_required()+@developer_required+def switch_proxy(server_id):+ """Switch a server to a different proxy type (nginx/traefik/caddy)."""+ _, err = _require_server(server_id)+ if err:+ return err++ data = request.get_json() or {}+ proxy_type = data.get('proxy_type')+ if not proxy_type:+ return jsonify({'error': 'proxy_type is required'}), 400++ try:+ stack = ProxyStackService.switch(server_id, proxy_type)+ except ValueError as e:+ return jsonify({'error': str(e)}), 400++ return jsonify(stack.to_dict())diff --git a/backend/app/api/shared_resources.py b/backend/app/api/shared_resources.pynew file mode 100644index 00000000..a62d2679--- /dev/null+++ b/backend/app/api/shared_resources.py@@ -0,0 +1,259 @@+"""Polymorphic shared resources API — tags + shared variable groups.++Mounted at ``/api/v1/shared``. Everything here is a JWT-protected facade over+:class:`~app.services.shared_resource_service.SharedResourceService`. Secret+variable values are always masked in responses via ``to_dict(mask_secrets=True)``+plus a defense-in-depth pass through :func:`mask_sensitive`.+"""+from flask import Blueprint, jsonify, request+from flask_jwt_extended import jwt_required++from app.services.shared_resource_service import SharedResourceService+from app.models.shared_resource import SharedVariableGroup+from app.utils.sensitive_data_filter import mask_sensitive++shared_resources_bp = Blueprint('shared_resources', __name__)+++def _bad(msg, code=400):+ return jsonify({'error': msg}), code+++def _require(data, *keys):+ """Return the first missing key name, or None if all present/truthy."""+ for k in keys:+ if data.get(k) in (None, ''):+ return k+ return None+++# ---------------------------------------------------------------- metadata++@shared_resources_bp.route('/resource-types', methods=['GET'])+@jwt_required()+def resource_types():+ """The catalog of supported polymorphic resource types."""+ return jsonify({'resource_types': list(SharedResourceService.RESOURCE_TYPES)})+++# -------------------------------------------------------------------- tags++@shared_resources_bp.route('/tags', methods=['GET'])+@jwt_required()+def list_tags():+ """List tags for a resource, or resources for a tag.++ ``?resource_type=&resource_id=`` → tags on that resource.+ ``?tag=`` (optionally with ``resource_type``) → resources carrying the tag.+ """+ tag = request.args.get('tag')+ resource_type = request.args.get('resource_type')+ resource_id = request.args.get('resource_id')++ if tag:+ rows = SharedResourceService.list_resources_by_tag(tag, resource_type)+ return jsonify({'resources': [r.to_dict() for r in rows]})++ if not resource_type or resource_id in (None, ''):+ return _bad('resource_type and resource_id (or tag) are required')++ rows = SharedResourceService.list_tags(resource_type, resource_id)+ return jsonify({'tags': [r.to_dict() for r in rows]})+++@shared_resources_bp.route('/tags', methods=['POST'])+@jwt_required()+def add_tag():+ data = request.get_json() or {}+ missing = _require(data, 'resource_type', 'resource_id', 'tag')+ if missing:+ return _bad(f'{missing} is required')+ try:+ row = SharedResourceService.add_tag(+ data['resource_type'], data['resource_id'], data['tag']+ )+ except ValueError as e:+ return _bad(str(e))+ return jsonify(row.to_dict()), 201+++@shared_resources_bp.route('/tags', methods=['DELETE'])+@jwt_required()+def remove_tag():+ # Accept either body or query params for convenience.+ data = request.get_json(silent=True) or {}+ resource_type = data.get('resource_type') or request.args.get('resource_type')+ resource_id = data.get('resource_id')+ if resource_id is None:+ resource_id = request.args.get('resource_id')+ tag = data.get('tag') or request.args.get('tag')++ if not resource_type or resource_id in (None, '') or not tag:+ return _bad('resource_type, resource_id and tag are required')++ removed = SharedResourceService.remove_tag(resource_type, resource_id, tag)+ return jsonify({'removed': removed})+++# --------------------------------------------------------- variable groups++@shared_resources_bp.route('/variable-groups', methods=['GET'])+@jwt_required()+def list_groups():+ groups = SharedResourceService.list_groups(+ scope_type=request.args.get('scope_type'),+ scope_id=request.args.get('scope_id'),+ )+ return jsonify({'groups': [g.to_dict() for g in groups]})+++@shared_resources_bp.route('/variable-groups', methods=['POST'])+@jwt_required()+def create_group():+ data = request.get_json() or {}+ missing = _require(data, 'scope_type', 'scope_id', 'name')+ if missing:+ return _bad(f'{missing} is required')+ try:+ group = SharedResourceService.create_group(+ data['scope_type'], data['scope_id'], data['name'],+ data.get('description'),+ )+ except ValueError as e:+ return _bad(str(e))+ return jsonify(group.to_dict(include_variables=True)), 201+++@shared_resources_bp.route('/variable-groups/<int:group_id>', methods=['GET'])+@jwt_required()+def get_group(group_id):+ group = SharedResourceService.get_group(group_id)+ if not group:+ return _bad('group not found', 404)+ payload = group.to_dict(include_variables=True, mask_secrets=True)+ payload['attachments'] = [a.to_dict() for a in group.attachments]+ return jsonify(mask_sensitive(payload))+++@shared_resources_bp.route('/variable-groups/<int:group_id>', methods=['PUT'])+@jwt_required()+def update_group(group_id):+ data = request.get_json() or {}+ try:+ group = SharedResourceService.update_group(+ group_id, name=data.get('name'), description=data.get('description')+ )+ except ValueError as e:+ return _bad(str(e))+ if not group:+ return _bad('group not found', 404)+ return jsonify(group.to_dict(include_variables=True))+++@shared_resources_bp.route('/variable-groups/<int:group_id>', methods=['DELETE'])+@jwt_required()+def delete_group(group_id):+ if not SharedResourceService.delete_group(group_id):+ return _bad('group not found', 404)+ return jsonify({'message': 'group deleted'})+++# --------------------------------------------- variables within a group++@shared_resources_bp.route('/variable-groups/<int:group_id>/variables', methods=['POST'])+@jwt_required()+def add_variable(group_id):+ data = request.get_json() or {}+ if data.get('key') in (None, ''):+ return _bad('key is required')+ try:+ var = SharedResourceService.set_variable(+ group_id, data['key'], data.get('value', ''),+ is_secret=bool(data.get('is_secret', False)),+ )+ except ValueError as e:+ return _bad(str(e))+ if not var:+ return _bad('group not found', 404)+ return jsonify(var.to_dict(mask_secrets=True)), 201+++@shared_resources_bp.route(+ '/variable-groups/<int:group_id>/variables/<int:variable_id>', methods=['PUT'])+@jwt_required()+def update_variable(group_id, variable_id):+ data = request.get_json() or {}+ var = SharedResourceService.update_variable(+ variable_id,+ value=data.get('value'),+ is_secret=data.get('is_secret'),+ )+ if not var or var.group_id != group_id:+ return _bad('variable not found', 404)+ return jsonify(var.to_dict(mask_secrets=True))+++@shared_resources_bp.route(+ '/variable-groups/<int:group_id>/variables/<int:variable_id>', methods=['DELETE'])+@jwt_required()+def delete_variable(group_id, variable_id):+ from app.models.shared_resource import SharedVariable+ var = SharedVariable.query.get(variable_id)+ if not var or var.group_id != group_id:+ return _bad('variable not found', 404)+ SharedResourceService.delete_variable(variable_id)+ return jsonify({'message': 'variable deleted'})+++# --------------------------------------------------------------- attach++@shared_resources_bp.route('/variable-groups/<int:group_id>/attach', methods=['POST'])+@jwt_required()+def attach_group(group_id):+ data = request.get_json() or {}+ missing = _require(data, 'resource_type', 'resource_id')+ if missing:+ return _bad(f'{missing} is required')+ att = SharedResourceService.attach_group(+ group_id, data['resource_type'], data['resource_id']+ )+ if not att:+ return _bad('group not found', 404)+ return jsonify(att.to_dict()), 201+++@shared_resources_bp.route('/variable-groups/<int:group_id>/detach', methods=['POST'])+@jwt_required()+def detach_group(group_id):+ data = request.get_json() or {}+ missing = _require(data, 'resource_type', 'resource_id')+ if missing:+ return _bad(f'{missing} is required')+ removed = SharedResourceService.detach_group(+ group_id, data['resource_type'], data['resource_id']+ )+ return jsonify({'detached': removed})+++# -------------------------------------------------------------- resolved++@shared_resources_bp.route('/resolved', methods=['GET'])+@jwt_required()+def resolved():+ """Effective merged variables for a resource (secrets masked)."""+ resource_type = request.args.get('resource_type')+ resource_id = request.args.get('resource_id')+ if not resource_type or resource_id in (None, ''):+ return _bad('resource_type and resource_id are required')++ variables = SharedResourceService.resolve_variables(+ resource_type, resource_id, mask_secrets=True+ )+ groups = SharedResourceService.list_attached_groups(resource_type, resource_id)+ payload = {+ 'resource_type': resource_type,+ 'resource_id': str(resource_id),+ 'variables': variables,+ 'groups': [g.to_dict() for g in groups],+ }+ return jsonify(mask_sensitive(payload))diff --git a/backend/app/api/webhooks.py b/backend/app/api/webhooks.pynew file mode 100644index 00000000..15e9dcb9--- /dev/null+++ b/backend/app/api/webhooks.py@@ -0,0 +1,212 @@+"""Pull-request webhook handling for PR Preview Environments.++The existing push/auto-deploy webhook lives in ``app/api/git.py`` ++``app/services/webhook_service.py`` and is left untouched. This blueprint adds a+``pull_request`` endpoint that, for a webhook bound to an application with PR+previews enabled, enqueues the right preview job:++ * ``opened`` / ``reopened`` → ``preview.create``+ * ``synchronize`` / ``edited`` → ``preview.sync`` (redeploy on new commits)+ * ``closed`` → ``preview.destroy``++Signature verification reuses :meth:`WebhookService._verify_signature` so the+same secret as the push webhook is honored. If previews aren't enabled for the+app, the call is a no-op. Best-effort throughout — a provider that lacks Docker+or DNS still gets a clean 200.++The host mounts this blueprint; ``PreviewService.register_jobs()`` must be+called at startup for the enqueued jobs to have handlers.+"""+import logging++from flask import Blueprint, request, jsonify++logger = logging.getLogger(__name__)++webhooks_bp = Blueprint('preview_webhooks', __name__)+++# (provider action) -> preview job kind. Normalized to lowercase actions.+_OPEN_ACTIONS = {'opened', 'reopened'}+_SYNC_ACTIONS = {'synchronize', 'synchronized', 'edited', 'ready_for_review'}+_CLOSE_ACTIONS = {'closed'}+++def _detect_source(headers):+ """Identify the provider + pull-request signal from request headers,+ mirroring the detection in app/api/git.py."""+ if 'X-GitHub-Event' in headers:+ return ('github', headers.get('X-GitHub-Event'),+ headers.get('X-Hub-Signature-256'))+ if 'X-Gitlab-Event' in headers:+ return ('gitlab', headers.get('X-Gitlab-Event'),+ headers.get('X-Gitlab-Token'))+ if 'X-Event-Key' in headers:+ return ('bitbucket', headers.get('X-Event-Key'),+ headers.get('X-Hub-Signature'))+ return (None, None, None)+++def _is_pull_request_event(source, event_type):+ if not event_type:+ return False+ et = event_type.lower()+ if source == 'github':+ return et == 'pull_request'+ if source == 'gitlab':+ return 'merge request' in et # 'Merge Request Hook'+ if source == 'bitbucket':+ return et.startswith('pullrequest:')+ return False+++def _extract_pr(source, payload):+ """Normalize a provider PR payload to+ ``{action, pr_number, branch, commit_sha, pr_title}``. Best-effort."""+ payload = payload or {}+ try:+ if source == 'github':+ pr = payload.get('pull_request') or {}+ head = pr.get('head') or {}+ return {+ 'action': (payload.get('action') or '').lower(),+ 'pr_number': payload.get('number') or pr.get('number'),+ 'branch': head.get('ref'),+ 'commit_sha': head.get('sha'),+ 'pr_title': pr.get('title'),+ }+ if source == 'gitlab':+ attrs = payload.get('object_attributes') or {}+ return {+ 'action': (attrs.get('action') or '').lower(),+ 'pr_number': attrs.get('iid') or attrs.get('id'),+ 'branch': attrs.get('source_branch'),+ 'commit_sha': (attrs.get('last_commit') or {}).get('id'),+ 'pr_title': attrs.get('title'),+ }+ if source == 'bitbucket':+ pr = payload.get('pullrequest') or {}+ src = (pr.get('source') or {})+ branch = (src.get('branch') or {}).get('name')+ commit = (src.get('commit') or {}).get('hash')+ return {+ 'action': '', # bitbucket encodes the action in the event key+ 'pr_number': pr.get('id'),+ 'branch': branch,+ 'commit_sha': commit,+ 'pr_title': pr.get('title'),+ }+ except Exception as exc: # pragma: no cover - defensive+ logger.debug('PR payload extraction failed (%s): %s', source, exc)+ return {'action': '', 'pr_number': None, 'branch': None,+ 'commit_sha': None, 'pr_title': None}+++def _action_to_job(source, event_type, action):+ """Map a normalized PR action to a preview job kind, or None to ignore."""+ # Bitbucket carries the action in the event key (pullrequest:created /+ # :updated / :fulfilled / :rejected) rather than an `action` field.+ if source == 'bitbucket' and event_type:+ key = event_type.lower()+ if key == 'pullrequest:created':+ return 'preview.create'+ if key == 'pullrequest:updated':+ return 'preview.sync'+ if key in ('pullrequest:fulfilled', 'pullrequest:rejected'):+ return 'preview.destroy'+ return None++ act = (action or '').lower()+ if act in _CLOSE_ACTIONS or act in ('merge', 'merged', 'close'):+ return 'preview.destroy'+ if act in _OPEN_ACTIONS or act in ('open',):+ return 'preview.create'+ if act in _SYNC_ACTIONS or act in ('update', 'updated'):+ return 'preview.sync'+ return None+++@webhooks_bp.route('/pull-request/<token>', methods=['POST'])+def receive_pull_request(token):+ """Receive a pull_request webhook and drive PR preview environments.++ Public endpoint (no JWT) — authenticated by the webhook signature, exactly+ like the push webhook. Always returns 200 with an ``action`` descriptor so a+ misconfigured-but-harmless delivery never trips the provider's retry logic.+ """+ from app.models import GitWebhook+ from app.services.webhook_service import WebhookService++ source, event_type, signature = _detect_source(request.headers)+ if not source:+ return jsonify({'error': 'Unknown webhook source'}), 400++ webhook = GitWebhook.query.filter_by(webhook_token=token).first()+ if not webhook:+ return jsonify({'error': 'Unknown webhook'}), 404+ if not webhook.is_active:+ return jsonify({'success': True, 'action': 'ignored',+ 'reason': 'webhook inactive'}), 200++ # Reuse the push webhook's signature verification (same secret).+ if not WebhookService._verify_signature(webhook, source, signature, request.get_data()):+ return jsonify({'error': 'Invalid signature'}), 400++ if not _is_pull_request_event(source, event_type):+ return jsonify({'success': True, 'action': 'ignored',+ 'reason': f'not a pull_request event ({event_type})'}), 200++ if not webhook.app_id:+ return jsonify({'success': True, 'action': 'ignored',+ 'reason': 'webhook not bound to an application'}), 200++ # No-op unless previews are enabled for this application.+ try:+ from app.services.preview_service import PreviewService+ settings = PreviewService.get_settings(webhook.app_id)+ if not getattr(settings, 'enabled', False):+ return jsonify({'success': True, 'action': 'ignored',+ 'reason': 'previews disabled for app'}), 200+ except Exception as exc:+ logger.debug('preview settings lookup failed: %s', exc)+ return jsonify({'success': True, 'action': 'ignored',+ 'reason': 'previews unavailable'}), 200++ pr = _extract_pr(source, request.get_json(silent=True))+ job_kind = _action_to_job(source, event_type, pr.get('action'))+ if not job_kind:+ return jsonify({'success': True, 'action': 'ignored',+ 'reason': f"unhandled PR action ({pr.get('action')})"}), 200++ payload = {'application_id': webhook.app_id, 'pr': {+ 'pr_number': pr.get('pr_number'),+ 'branch': pr.get('branch'),+ 'commit_sha': pr.get('commit_sha'),+ 'pr_title': pr.get('pr_title'),+ }}++ # On close we destroy by preview-id (the PR number maps to exactly one+ # preview row); resolving it here avoids a full sync that — with no+ # connected provider — would otherwise tear down every preview.+ if job_kind == 'preview.destroy':+ from app.models.application_preview import ApplicationPreview+ preview = ApplicationPreview.query.filter_by(+ application_id=webhook.app_id, pr_number=pr.get('pr_number')).first()+ if not preview:+ return jsonify({'success': True, 'action': 'ignored',+ 'reason': 'no preview for closed PR'}), 200+ payload = {'preview_id': preview.id}++ # Enqueue the matching preview job. Under ENV=testing the job system is a+ # no-op; never let an enqueue failure break the webhook response.+ enqueued = False+ try:+ from app.plugins_sdk import jobs+ jobs.enqueue(job_kind, payload)+ enqueued = True+ except Exception as exc:+ logger.warning('failed to enqueue %s for app %s: %s',+ job_kind, webhook.app_id, exc)++ return jsonify({'success': True, 'action': job_kind, 'enqueued': enqueued,+ 'pr_number': pr.get('pr_number')}), 200diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex c62f6331..881e86a2 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -5,6 +5,11 @@ from app.models.env_variable import EnvironmentVariable, EnvironmentVariableHistfrom app.models.notification_preferences import NotificationPreferencesfrom app.models.deployment import Deployment, DeploymentDifffrom app.models.deployment_snapshot import DeploymentSnapshot+from app.models.project import Project+from app.models.environment import Environment+from app.models.shared_resource import ResourceTag, SharedVariableGroup, SharedVariable, SharedVariableGroupAttachment+from app.models.application_preview import ApplicationPreview, ApplicationPreviewSettings+from app.models.proxy_stack import ProxyStackfrom app.models.deployment_job import DeploymentJob, DeploymentJobLogfrom app.models.system_settings import SystemSettingsfrom app.models.audit_log import AuditLog@@ -90,4 +95,8 @@ __all__ = ['EmailProviderConnection','SystemEvent','DomainRegistration',+ 'Project', 'Environment',+ 'ResourceTag', 'SharedVariableGroup', 'SharedVariable', 'SharedVariableGroupAttachment',+ 'ApplicationPreview', 'ApplicationPreviewSettings',+ 'ProxyStack',]diff --git a/backend/app/models/application.py b/backend/app/models/application.pyindex 3020419f..4d25a429 100644--- a/backend/app/models/application.py+++ b/backend/app/models/application.py@@ -1,6 +1,13 @@from datetime import datetimefrom app import db+# Application carries FKs to projects.id / environments.id (opt-in Project /+# Environment hierarchy). Import those modules here so their tables are always+# registered on db.Model's metadata whenever Application is loaded, keeping the+# FK targets resolvable regardless of import order.+from app.models import project as _project # noqa: F401+from app.models import environment as _environment # noqa: F401+class Application(db.Model):__tablename__ = 'applications'@@ -60,6 +67,10 @@ class Application(db.Model):# Workspace scoping (#33). Nullable: existing rows are backfilled to a default# workspace by migration 015; new rows are stamped on create.workspace_id = db.Column(db.Integer, db.ForeignKey('workspaces.id'), nullable=True, index=True)+ # Project / Environment hierarchy (opt-in). Nullable: existing apps stay+ # "unassigned" and keep working; stamped on create when provided.+ project_id = db.Column(db.Integer, db.ForeignKey('projects.id'), nullable=True, index=True)+ environment_id = db.Column(db.Integer, db.ForeignKey('environments.id'), nullable=True, index=True)# Relationships# Use 'subquery' to eagerly load domains in a single query, avoiding N+1@@ -101,6 +112,8 @@ class Application(db.Model):'user_id': self.user_id,'server_id': self.server_id,'workspace_id': self.workspace_id,+ 'project_id': self.project_id,+ 'environment_id': self.environment_id,'server_name': self.server.name if self.server else 'Local server','domains': [d.to_dict() for d in self.domains]}diff --git a/backend/app/models/application_preview.py b/backend/app/models/application_preview.pynew file mode 100644index 00000000..5b5a3d4c--- /dev/null+++ b/backend/app/models/application_preview.py@@ -0,0 +1,122 @@+"""PR Preview Environments — data model.++When a Git pull request is opened/updated, ServerKit deploys an isolated+preview of that branch to a temporary domain and tears it down when the PR+closes. Preview config lives here (its own tables) rather than on Application+so the application schema stays untouched.++Two tables:+ * ``application_previews`` — one row per live PR preview.+ * ``application_preview_settings`` — per-application opt-in + domain template.+"""+import json+from datetime import datetime++from app import db+++class ApplicationPreview(db.Model):+ """A single PR preview environment for an application."""+ __tablename__ = 'application_previews'++ # Status lifecycle (string column, not an enum, to match the rest of the+ # codebase's loose status columns):+ STATUS_QUEUED = 'queued'+ STATUS_BUILDING = 'building'+ STATUS_RUNNING = 'running'+ STATUS_STOPPED = 'stopped'+ STATUS_FAILED = 'failed'+ STATUS_DESTROYED = 'destroyed'++ id = db.Column(db.Integer, primary_key=True)+ application_id = db.Column(+ db.Integer, db.ForeignKey('applications.id'), nullable=False, index=True)++ pr_number = db.Column(db.Integer, nullable=False)+ pr_title = db.Column(db.String(500), nullable=True)+ branch = db.Column(db.String(255), nullable=True)++ status = db.Column(db.String(20), default=STATUS_QUEUED, nullable=False)+ domain = db.Column(db.String(255), nullable=True)++ # JSON-encoded list of provisioned container ids (best-effort; may be empty+ # when Docker isn't available, e.g. dev/test).+ container_ids = db.Column(db.Text, nullable=True)++ commit_sha = db.Column(db.String(64), nullable=True)+ expires_at = db.Column(db.DateTime, nullable=True)++ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)+ deleted_at = db.Column(db.DateTime, nullable=True)++ def get_container_ids(self):+ """The provisioned container ids as a list (empty when unset/invalid)."""+ if not self.container_ids:+ return []+ try:+ val = json.loads(self.container_ids)+ return val if isinstance(val, list) else []+ except (ValueError, TypeError):+ return []++ def set_container_ids(self, ids):+ self.container_ids = json.dumps(list(ids or []))++ def to_dict(self):+ return {+ 'id': self.id,+ 'application_id': self.application_id,+ 'pr_number': self.pr_number,+ 'pr_title': self.pr_title,+ 'branch': self.branch,+ 'status': self.status,+ 'domain': self.domain,+ 'url': (f'https://{self.domain}' if self.domain else None),+ 'container_ids': self.get_container_ids(),+ 'commit_sha': self.commit_sha,+ 'short_sha': self.commit_sha[:7] if self.commit_sha else None,+ 'expires_at': self.expires_at.isoformat() if self.expires_at else None,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,+ 'deleted_at': self.deleted_at.isoformat() if self.deleted_at else None,+ }++ def __repr__(self):+ return f'<ApplicationPreview app={self.application_id} PR#{self.pr_number} ({self.status})>'+++class ApplicationPreviewSettings(db.Model):+ """Per-application PR-preview configuration (opt-in + domain template)."""+ __tablename__ = 'application_preview_settings'++ DEFAULT_DOMAIN_TEMPLATE = 'pr-{pr_number}.{app_domain}'++ application_id = db.Column(+ db.Integer, db.ForeignKey('applications.id'),+ primary_key=True, unique=True, nullable=False)++ enabled = db.Column(db.Boolean, default=False, nullable=False)+ domain_template = db.Column(+ db.String(255), default=DEFAULT_DOMAIN_TEMPLATE, nullable=False)+ # Optional: deploy previews onto a specific server in the fleet.+ target_server_id = db.Column(db.String(36), nullable=True)+ # Optional TTL: previews are auto-destroyed this many days after creation.+ ttl_days = db.Column(db.Integer, nullable=True)++ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++ def to_dict(self):+ return {+ 'application_id': self.application_id,+ 'enabled': bool(self.enabled),+ 'domain_template': self.domain_template or self.DEFAULT_DOMAIN_TEMPLATE,+ 'target_server_id': self.target_server_id,+ 'ttl_days': self.ttl_days,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,+ }++ def __repr__(self):+ return f'<ApplicationPreviewSettings app={self.application_id} enabled={self.enabled}>'diff --git a/backend/app/models/environment.py b/backend/app/models/environment.pynew file mode 100644index 00000000..86eb2b17--- /dev/null+++ b/backend/app/models/environment.py@@ -0,0 +1,42 @@+from datetime import datetime+from app import db+++class Environment(db.Model):+ """An Environment (production/staging/development) under a Project.++ Applications carry a nullable environment_id. A project always has at least+ one default environment ("production") created alongside it.+ """+ __tablename__ = 'environments'++ id = db.Column(db.Integer, primary_key=True)+ project_id = db.Column(db.Integer, db.ForeignKey('projects.id'), nullable=False, index=True)+ name = db.Column(db.String(64), nullable=False)+ slug = db.Column(db.String(64), nullable=False)+ is_default = db.Column(db.Boolean, default=False)+ order = db.Column(db.Integer, default=0)++ created_at = db.Column(db.DateTime, default=datetime.utcnow)++ __table_args__ = (+ db.UniqueConstraint('project_id', 'slug', name='uq_environment_project_slug'),+ )++ def to_dict(self, include_counts=False):+ result = {+ 'id': self.id,+ 'project_id': self.project_id,+ 'name': self.name,+ 'slug': self.slug,+ 'is_default': self.is_default,+ 'order': self.order,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ }+ if include_counts:+ from app.models.application import Application+ result['app_count'] = Application.query.filter_by(environment_id=self.id).count()+ return result++ def __repr__(self):+ return f'<Environment {self.name} (project={self.project_id})>'diff --git a/backend/app/models/project.py b/backend/app/models/project.pynew file mode 100644index 00000000..b23128a9--- /dev/null+++ b/backend/app/models/project.py@@ -0,0 +1,66 @@+from datetime import datetime+from app import db+import json+++class Project(db.Model):+ """A Project groups applications under a Workspace.++ Hierarchy: Workspace -> Project -> Environment -> Applications.++ OPT-IN and backward compatible: applications carry a nullable project_id, so+ existing apps remain "unassigned" until a user organizes them into projects.+ """+ __tablename__ = 'projects'++ id = db.Column(db.Integer, primary_key=True)+ workspace_id = db.Column(db.Integer, db.ForeignKey('workspaces.id'), nullable=False, index=True)+ name = db.Column(db.String(128), nullable=False)+ slug = db.Column(db.String(128), nullable=False)+ description = db.Column(db.Text, nullable=True)+ metadata_json = db.Column(db.Text, nullable=True)++ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++ # Environments belonging to this project. Deleting a project cascades to its+ # environments (apps are detached/blocked separately by the service layer).+ environments = db.relationship(+ 'Environment',+ backref='project',+ lazy='dynamic',+ cascade='all, delete-orphan',+ order_by='Environment.order',+ )++ __table_args__ = (+ db.UniqueConstraint('workspace_id', 'slug', name='uq_project_workspace_slug'),+ )++ @property+ def metadata_(self):+ return json.loads(self.metadata_json) if self.metadata_json else {}++ @metadata_.setter+ def metadata_(self, v):+ self.metadata_json = json.dumps(v) if v else None++ def to_dict(self, include_counts=False):+ result = {+ 'id': self.id,+ 'workspace_id': self.workspace_id,+ 'name': self.name,+ 'slug': self.slug,+ 'description': self.description,+ 'metadata': self.metadata_,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,+ }+ if include_counts:+ from app.models.application import Application+ result['environment_count'] = self.environments.count()+ result['app_count'] = Application.query.filter_by(project_id=self.id).count()+ return result++ def __repr__(self):+ return f'<Project {self.name}>'diff --git a/backend/app/models/proxy_stack.py b/backend/app/models/proxy_stack.pynew file mode 100644index 00000000..df52093f--- /dev/null+++ b/backend/app/models/proxy_stack.py@@ -0,0 +1,82 @@+"""ProxyStack model — per-server managed reverse-proxy state.++ServerKit treats the reverse proxy as a first-class managed service. Host+Nginx remains the *default* (and the better choice for PHP/WordPress), but a+server may opt into a Dockerized proxy (Traefik or Caddy) deployed as a+Compose stack. This table records that choice + the on-disk compose path and+config snippet for one server. It is intentionally keyed 1:1 on server_id+(unique) — a server runs at most one managed proxy stack at a time.+"""+import uuid+import json+from datetime import datetime++from app import db+++class ProxyStack(db.Model):+ """One managed reverse-proxy stack per server."""+ __tablename__ = 'proxy_stacks'++ # Proxy types this table understands. 'nginx' means "host nginx, no+ # Docker stack" — the default. The other two deploy a Compose stack.+ PROXY_NGINX = 'nginx'+ PROXY_TRAEFIK = 'traefik'+ PROXY_CADDY = 'caddy'++ id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))++ # 1:1 with a server. Unique so get_or_create never creates duplicates;+ # indexed for the per-server lookup the API does on every request.+ server_id = db.Column(+ db.String(36),+ db.ForeignKey('servers.id'),+ nullable=False,+ index=True,+ unique=True,+ )++ proxy_type = db.Column(db.String(20), nullable=False, default=PROXY_NGINX)+ # stopped | running | error | unknown+ status = db.Column(db.String(20), nullable=False, default='unknown')++ # Where the compose stack lives on disk (None for host-nginx).+ compose_path = db.Column(db.String(512))++ # JSON list of docker network names the proxy attaches to.+ networks = db.Column(db.Text)++ # Operator-supplied raw config appended to the generated proxy config.+ custom_snippet = db.Column(db.Text)++ last_regenerated_at = db.Column(db.DateTime)++ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++ def networks_list(self):+ """Decode the networks JSON column to a list (empty on missing/bad)."""+ if not self.networks:+ return []+ try:+ data = json.loads(self.networks)+ return data if isinstance(data, list) else []+ except (TypeError, ValueError):+ return []++ def to_dict(self):+ return {+ 'id': self.id,+ 'server_id': self.server_id,+ 'proxy_type': self.proxy_type,+ 'status': self.status,+ 'compose_path': self.compose_path,+ 'networks': self.networks_list(),+ 'custom_snippet': self.custom_snippet,+ 'last_regenerated_at': self.last_regenerated_at.isoformat() if self.last_regenerated_at else None,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,+ }++ def __repr__(self):+ return f'<ProxyStack server={self.server_id} type={self.proxy_type}>'diff --git a/backend/app/models/shared_resource.py b/backend/app/models/shared_resource.pynew file mode 100644index 00000000..57e80052--- /dev/null+++ b/backend/app/models/shared_resource.py@@ -0,0 +1,194 @@+"""Polymorphic shared resources: tags + shared variable groups.++This is the *facade layer* for cross-resource tagging and shared configuration.+It lives BESIDE the existing per-resource tables (e.g. ``environment_variables``)+and never touches them — any resource (application, database, service, wordpress+site, server) is addressed polymorphically via ``(resource_type, resource_id)``.++``resource_id`` is stored as a String so the same column can address resources+whose primary key is an int (applications, servers) or a non-int handle+(docker container names, service slugs) without schema changes.++Secret values reuse the *exact* Fernet derivation used by+``app.models.env_variable.EnvironmentVariable`` (SHA256(SECRET_KEY) →+urlsafe-b64 → Fernet) so secrets are encrypted at rest with the same key+source the rest of the panel already uses.+"""+from datetime import datetime++from app import db+from app.models.env_variable import EnvironmentVariable++# The mask used in place of a redacted secret value. Matches the convention in+# env_variable.py / sensitive_data_filter.py.+SECRET_MASK = '••••••••'+++class ResourceTag(db.Model):+ """A free-form tag attached to any resource via (resource_type, resource_id)."""+ __tablename__ = 'resource_tags'++ id = db.Column(db.Integer, primary_key=True)+ resource_type = db.Column(db.String(50), nullable=False)+ resource_id = db.Column(db.String(255), nullable=False)+ tag = db.Column(db.String(100), nullable=False)+ created_at = db.Column(db.DateTime, default=datetime.utcnow)++ __table_args__ = (+ db.UniqueConstraint('resource_type', 'resource_id', 'tag',+ name='uq_resource_tag'),+ db.Index('ix_resource_tag_resource', 'resource_type', 'resource_id'),+ )++ def to_dict(self):+ return {+ 'id': self.id,+ 'resource_type': self.resource_type,+ 'resource_id': self.resource_id,+ 'tag': self.tag,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ }++ def __repr__(self):+ return f'<ResourceTag {self.resource_type}:{self.resource_id} #{self.tag}>'+++class SharedVariableGroup(db.Model):+ """A named bundle of variables that can be attached to many resources.++ Scoped by ``(scope_type, scope_id)`` — e.g. a 'workspace' group, a 'project'+ group, or an 'environment' group — so the same panel can offer different+ group catalogs depending on the surface it is embedded in.+ """+ __tablename__ = 'shared_variable_groups'++ SCOPE_WORKSPACE = 'workspace'+ SCOPE_PROJECT = 'project'+ SCOPE_ENVIRONMENT = 'environment'+ VALID_SCOPES = (SCOPE_WORKSPACE, SCOPE_PROJECT, SCOPE_ENVIRONMENT)++ id = db.Column(db.Integer, primary_key=True)+ scope_type = db.Column(db.String(50), nullable=False)+ scope_id = db.Column(db.String(255), nullable=False)+ name = db.Column(db.String(255), nullable=False)+ description = db.Column(db.String(500), nullable=True)+ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow,+ onupdate=datetime.utcnow)++ variables = db.relationship(+ 'SharedVariable', backref='group', lazy='select',+ cascade='all, delete-orphan',+ )+ attachments = db.relationship(+ 'SharedVariableGroupAttachment', backref='group', lazy='select',+ cascade='all, delete-orphan',+ )++ __table_args__ = (+ db.Index('ix_shared_group_scope', 'scope_type', 'scope_id'),+ )++ def to_dict(self, include_variables=False, mask_secrets=True):+ result = {+ 'id': self.id,+ 'scope_type': self.scope_type,+ 'scope_id': self.scope_id,+ 'name': self.name,+ 'description': self.description,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,+ 'variable_count': len(self.variables),+ 'attachment_count': len(self.attachments),+ }+ if include_variables:+ result['variables'] = [+ v.to_dict(mask_secrets=mask_secrets) for v in self.variables+ ]+ return result++ def __repr__(self):+ return f'<SharedVariableGroup {self.scope_type}:{self.scope_id}/{self.name}>'+++class SharedVariable(db.Model):+ """A single key/value held by a :class:`SharedVariableGroup`.++ Values are encrypted at rest with the same Fernet key the per-app+ environment variables use (delegated to ``EnvironmentVariable``), so there+ is a single key source for all secret material in the panel.+ """+ __tablename__ = 'shared_variables'++ id = db.Column(db.Integer, primary_key=True)+ group_id = db.Column(db.Integer, db.ForeignKey('shared_variable_groups.id'),+ nullable=False)+ key = db.Column(db.String(255), nullable=False)+ encrypted_value = db.Column(db.Text, nullable=False)+ is_secret = db.Column(db.Boolean, default=False)+ created_at = db.Column(db.DateTime, default=datetime.utcnow)++ __table_args__ = (+ db.UniqueConstraint('group_id', 'key', name='uq_shared_var_key'),+ )++ # --- encryption (reuse the env-var Fernet helper; same key source) -------++ @property+ def value(self):+ """Decrypted plaintext value."""+ return EnvironmentVariable.decrypt_value(self.encrypted_value)++ @value.setter+ def value(self, plaintext):+ """Set the value (encrypts automatically with the shared Fernet key)."""+ self.encrypted_value = EnvironmentVariable.encrypt_value(plaintext)++ def to_dict(self, include_value=True, mask_secrets=True):+ result = {+ 'id': self.id,+ 'group_id': self.group_id,+ 'key': self.key,+ 'is_secret': self.is_secret,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ }+ if include_value:+ if mask_secrets and self.is_secret:+ result['value'] = SECRET_MASK+ else:+ result['value'] = self.value+ return result++ def __repr__(self):+ return f'<SharedVariable {self.key}>'+++class SharedVariableGroupAttachment(db.Model):+ """Links a :class:`SharedVariableGroup` to a resource polymorphically."""+ __tablename__ = 'shared_variable_group_attachments'++ id = db.Column(db.Integer, primary_key=True)+ group_id = db.Column(db.Integer, db.ForeignKey('shared_variable_groups.id'),+ nullable=False)+ resource_type = db.Column(db.String(50), nullable=False)+ resource_id = db.Column(db.String(255), nullable=False)+ created_at = db.Column(db.DateTime, default=datetime.utcnow)++ __table_args__ = (+ db.UniqueConstraint('group_id', 'resource_type', 'resource_id',+ name='uq_group_attachment'),+ db.Index('ix_group_attachment_resource', 'resource_type', 'resource_id'),+ )++ def to_dict(self):+ return {+ 'id': self.id,+ 'group_id': self.group_id,+ 'resource_type': self.resource_type,+ 'resource_id': self.resource_id,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ }++ def __repr__(self):+ return (f'<SharedVariableGroupAttachment g{self.group_id} '+ f'{self.resource_type}:{self.resource_id}>')diff --git a/backend/app/services/preview_service.py b/backend/app/services/preview_service.pynew file mode 100644index 00000000..ef58fe4e--- /dev/null+++ b/backend/app/services/preview_service.py@@ -0,0 +1,493 @@+"""PR Preview Environments — reconciliation + provisioning service.++When a Git pull request is opened/updated, ServerKit deploys an isolated+preview of that branch to a temporary domain and tears it down when the PR+closes.++The *testable core* is two pure functions:++ * :meth:`PreviewService.render_domain` — expand a domain template against a+ PR context (deterministic, no I/O).+ * :meth:`PreviewService.reconcile` — diff open PRs against the active+ previews and return the create/destroy/update decisions (no I/O).++Everything else (``create_preview``/``destroy_preview``/``sync_previews``/+``expire_stale``) is orchestration that touches the DB and — where a Docker/DNS/+WordPress environment is actually available — provisions or tears down real+infrastructure. All of it is BEST-EFFORT and try/except-guarded so it never+raises in a dev/test environment that lacks Docker or DNS.+"""+import logging+import re+from datetime import datetime, timedelta++logger = logging.getLogger(__name__)++# Job kinds — also registered in :meth:`PreviewService.register_jobs`.+JOB_CREATE = 'preview.create'+JOB_DESTROY = 'preview.destroy'+JOB_SYNC = 'preview.sync'+JOB_EXPIRE = 'preview.expire'+++def _slugify_branch(branch):+ """DNS-safe label for a branch name.++ ``feature/Login-Page`` -> ``feature-login-page``. Lowercased, every run of+ non-alphanumerics collapses to a single dash, leading/trailing dashes+ trimmed. Empty input yields ``branch``.+ """+ if not branch:+ return 'branch'+ label = re.sub(r'[^a-z0-9]+', '-', str(branch).lower()).strip('-')+ return label or 'branch'+++class PreviewService:+ """Static service for PR preview environments."""++ # ------------------------------------------------------------------ #+ # Pure core — fully unit-testable, no I/O+ # ------------------------------------------------------------------ #++ @staticmethod+ def render_domain(template, ctx):+ """Expand a preview-domain ``template`` against a PR context ``ctx``.++ Supported placeholders:+ * ``{pr_number}`` — the PR number.+ * ``{branch}`` — the branch name, slugified to a DNS-safe label.+ * ``{app_domain}``/``{base_domain}`` — the application's base domain.++ Deterministic and side-effect free. Unknown placeholders are left as-is+ rather than raising, and the result is lowercased (hostnames are+ case-insensitive). Returns ``''`` for a falsy template.+ """+ if not template:+ return ''+ ctx = ctx or {}+ app_domain = (ctx.get('app_domain') or ctx.get('base_domain') or '')+ values = {+ 'pr_number': str(ctx.get('pr_number', '')),+ 'branch': _slugify_branch(ctx.get('branch')),+ 'app_domain': app_domain,+ 'base_domain': app_domain,+ }++ def _replace(match):+ key = match.group(1)+ return values.get(key, match.group(0))++ rendered = re.sub(r'\{([a-z_]+)\}', _replace, template)+ return rendered.strip().lower()++ @staticmethod+ def reconcile(open_prs, active_previews):+ """Diff open PRs against active previews.++ Args:+ open_prs: iterable of dicts with at least ``pr_number``; optionally+ ``commit_sha``, ``branch``, ``pr_title``.+ active_previews: iterable of dicts/objects describing currently-live+ previews, each exposing ``pr_number``, ``commit_sha`` and+ ``status``. (Both dict and ORM-row shapes are accepted.)++ Returns a dict::++ {'to_create': [pr, ...], # open PR with no live preview+ 'to_destroy': [pv, ...], # live preview whose PR is closed/missing+ 'to_update': [pr, ...]} # open PR whose preview is on an old commit++ Pure — no I/O, no DB. Destroyed previews are ignored as "not live".+ """+ def _get(obj, key):+ if isinstance(obj, dict):+ return obj.get(key)+ return getattr(obj, key, None)++ open_by_pr = {}+ for pr in (open_prs or []):+ num = _get(pr, 'pr_number')+ if num is not None:+ open_by_pr[num] = pr++ # Map live previews by PR number. A preview already marked destroyed is+ # not "live" and shouldn't be re-destroyed.+ live_by_pr = {}+ for pv in (active_previews or []):+ if _get(pv, 'status') == 'destroyed':+ continue+ num = _get(pv, 'pr_number')+ if num is not None:+ live_by_pr[num] = pv++ to_create, to_update, to_destroy = [], [], []++ for num, pr in open_by_pr.items():+ preview = live_by_pr.get(num)+ if preview is None:+ to_create.append(pr)+ continue+ # Same PR, already has a preview — redeploy only if the tip moved.+ pr_sha = _get(pr, 'commit_sha')+ pv_sha = _get(preview, 'commit_sha')+ if pr_sha and pr_sha != pv_sha:+ to_update.append(pr)++ for num, preview in live_by_pr.items():+ if num not in open_by_pr:+ to_destroy.append(preview)++ return {'to_create': to_create, 'to_destroy': to_destroy, 'to_update': to_update}++ # ------------------------------------------------------------------ #+ # Settings+ # ------------------------------------------------------------------ #++ @classmethod+ def get_settings(cls, application_id):+ """Return the (existing or default, unsaved) settings row for an app."""+ from app.models.application_preview import ApplicationPreviewSettings+ settings = ApplicationPreviewSettings.query.get(application_id)+ if settings:+ return settings+ # Return a transient default so callers always get a usable object.+ return ApplicationPreviewSettings(+ application_id=application_id,+ enabled=False,+ domain_template=ApplicationPreviewSettings.DEFAULT_DOMAIN_TEMPLATE,+ )++ @classmethod+ def enable_previews(cls, application_id, settings):+ """Create/update the per-app preview settings (upsert). ``settings`` is a+ dict of any of ``enabled``/``domain_template``/``target_server_id``/+ ``ttl_days``. Returns the persisted row's ``to_dict()``."""+ from app import db+ from app.models.application_preview import ApplicationPreviewSettings++ settings = settings or {}+ row = ApplicationPreviewSettings.query.get(application_id)+ if not row:+ row = ApplicationPreviewSettings(application_id=application_id)+ db.session.add(row)++ if 'enabled' in settings:+ row.enabled = bool(settings['enabled'])+ if 'domain_template' in settings and settings['domain_template']:+ row.domain_template = str(settings['domain_template'])+ if 'target_server_id' in settings:+ row.target_server_id = settings['target_server_id'] or None+ if 'ttl_days' in settings:+ ttl = settings['ttl_days']+ try:+ row.ttl_days = int(ttl) if ttl not in (None, '') else None+ except (TypeError, ValueError):+ row.ttl_days = None++ try:+ db.session.commit()+ except Exception as exc: # pragma: no cover - defensive+ db.session.rollback()+ logger.warning('enable_previews commit failed for app %s: %s', application_id, exc)+ raise+ return row.to_dict()++ # ------------------------------------------------------------------ #+ # Helpers+ # ------------------------------------------------------------------ #++ @classmethod+ def _app_base_domain(cls, app):+ """Best-effort base domain for an app's previews: the app's primary+ domain, else ``<slug>.<sites-base-domain>``, else the bare slug."""+ try:+ domains = list(getattr(app, 'domains', []) or [])+ primary = next((d for d in domains if getattr(d, 'is_primary', False)), None)+ if primary and getattr(primary, 'name', None):+ return primary.name+ if domains and getattr(domains[0], 'name', None):+ return domains[0].name+ except Exception:+ pass+ try:+ from app.services.site_domain_service import SiteDomainService+ sub = SiteDomainService.subdomain_for(app.name)+ if sub:+ return sub+ except Exception:+ pass+ from app.utils.slug import slugify+ return slugify(getattr(app, 'name', '') or 'app') or 'app'++ @classmethod+ def _domain_for(cls, app, settings, pr_number, branch):+ from app.models.application_preview import ApplicationPreviewSettings+ template = (getattr(settings, 'domain_template', None)+ or ApplicationPreviewSettings.DEFAULT_DOMAIN_TEMPLATE)+ return cls.render_domain(template, {+ 'pr_number': pr_number,+ 'branch': branch,+ 'app_domain': cls._app_base_domain(app),+ })++ @staticmethod+ def _pr_field(pr_payload, *keys, default=None):+ for k in keys:+ if isinstance(pr_payload, dict) and pr_payload.get(k) not in (None, ''):+ return pr_payload.get(k)+ return default++ # ------------------------------------------------------------------ #+ # Orchestration — best-effort, never raises+ # ------------------------------------------------------------------ #++ @classmethod+ def create_preview(cls, app, pr_payload):+ """Create (or update-in-place) a preview for a PR. Best-effort.++ Writes/updates an :class:`ApplicationPreview` row, renders the domain,+ and provisions real infra only where a Docker/WordPress environment is+ available. Returns the preview ``to_dict()`` (or ``{'error': ...}``).+ Never raises.+ """+ from app import db+ from app.models.application_preview import ApplicationPreview++ try:+ pr_number = cls._pr_field(pr_payload, 'pr_number', 'number')+ if pr_number is None:+ return {'error': 'pr_number is required'}+ pr_number = int(pr_number)+ branch = cls._pr_field(pr_payload, 'branch', 'head_ref', 'head')+ pr_title = cls._pr_field(pr_payload, 'pr_title', 'title')+ commit_sha = cls._pr_field(pr_payload, 'commit_sha', 'sha', 'head_sha')++ settings = cls.get_settings(app.id)+ if not getattr(settings, 'enabled', False):+ return {'skipped': True, 'reason': 'previews_disabled'}++ preview = ApplicationPreview.query.filter_by(+ application_id=app.id, pr_number=pr_number).first()+ if not preview:+ preview = ApplicationPreview(application_id=app.id, pr_number=pr_number)+ db.session.add(preview)++ preview.branch = branch+ preview.pr_title = pr_title+ preview.commit_sha = commit_sha+ preview.domain = cls._domain_for(app, settings, pr_number, branch)+ preview.status = ApplicationPreview.STATUS_BUILDING+ preview.deleted_at = None++ ttl_days = getattr(settings, 'ttl_days', None)+ if ttl_days:+ preview.expires_at = datetime.utcnow() + timedelta(days=int(ttl_days))++ db.session.commit()++ # Best-effort provisioning — degrade gracefully when unavailable.+ provisioned = cls._provision(app, preview)+ preview.status = (ApplicationPreview.STATUS_RUNNING+ if provisioned.get('ok')+ else ApplicationPreview.STATUS_FAILED)+ if provisioned.get('container_ids'):+ preview.set_container_ids(provisioned['container_ids'])+ db.session.commit()+ return preview.to_dict()+ except Exception as exc:+ logger.warning('create_preview failed: %s', exc)+ try:+ db.session.rollback()+ except Exception:+ pass+ return {'error': str(exc)}++ @classmethod+ def _provision(cls, app, preview):+ """Best-effort real provisioning. Returns ``{'ok': bool, 'container_ids': [...]}``.++ For WordPress apps, delegate to the WP preview hook. For other app types+ we currently only record the row + domain (a deeper Docker clone is a+ roadmap item); we still report ``ok`` so the preview shows as running in+ environments where the row is all that's expected. All failures are+ swallowed and surfaced as ``ok: False``.+ """+ try:+ if getattr(app, 'app_type', None) == 'wordpress':+ try:+ from app.services.wordpress_service import WordPressService+ from app.models.wordpress_site import WordPressSite+ site = WordPressSite.query.filter_by(application_id=app.id).first()+ if site:+ res = WordPressService.create_preview_instance(+ site, preview.pr_number, domain=preview.domain,+ branch=preview.branch)+ return {'ok': bool(res.get('success', True)),+ 'container_ids': res.get('container_ids', [])}+ except Exception as exc:+ logger.info('WP preview provisioning unavailable: %s', exc)+ return {'ok': False, 'container_ids': []}+ # Non-WP: the row + rendered domain is the unit of work that always+ # succeeds; Docker clone is best-effort future work.+ return {'ok': True, 'container_ids': []}+ except Exception as exc:+ logger.info('preview provisioning unavailable: %s', exc)+ return {'ok': False, 'container_ids': []}++ @classmethod+ def destroy_preview(cls, preview_id):+ """Tear down a preview and mark it destroyed. Best-effort; never raises."""+ from app import db+ from app.models.application_preview import ApplicationPreview++ try:+ preview = ApplicationPreview.query.get(preview_id)+ if not preview:+ return {'error': 'preview not found'}+ if preview.status == ApplicationPreview.STATUS_DESTROYED:+ return preview.to_dict()++ app = None+ try:+ from app.models import Application+ app = Application.query.get(preview.application_id)+ except Exception:+ pass++ # Best-effort WordPress teardown.+ if app is not None and getattr(app, 'app_type', None) == 'wordpress':+ try:+ from app.services.wordpress_service import WordPressService+ from app.models.wordpress_site import WordPressSite+ site = WordPressSite.query.filter_by(application_id=app.id).first()+ if site:+ WordPressService.destroy_preview_instance(site, preview.pr_number)+ except Exception as exc:+ logger.info('WP preview teardown unavailable: %s', exc)++ preview.status = ApplicationPreview.STATUS_DESTROYED+ preview.deleted_at = datetime.utcnow()+ preview.set_container_ids([])+ db.session.commit()+ return preview.to_dict()+ except Exception as exc:+ logger.warning('destroy_preview failed: %s', exc)+ try:+ db.session.rollback()+ except Exception:+ pass+ return {'error': str(exc)}++ @classmethod+ def sync_previews(cls, application_id):+ """Reconcile an app's live previews against its open PRs.++ Reads open PRs from a connected source provider when available; in a+ dev/test environment with no provider this is a safe no-op (no PRs ⇒ no+ creates, and existing previews stay put). Best-effort; never raises.+ """+ from app.models.application_preview import ApplicationPreview++ try:+ from app.models import Application+ app = Application.query.get(application_id)+ if not app:+ return {'error': 'application not found'}++ open_prs = cls._fetch_open_prs(app)+ active = ApplicationPreview.query.filter(+ ApplicationPreview.application_id == application_id,+ ApplicationPreview.status != ApplicationPreview.STATUS_DESTROYED,+ ).all()++ plan = cls.reconcile(open_prs, active)+ created = destroyed = updated = 0+ for pr in plan['to_create']:+ cls.create_preview(app, pr)+ created += 1+ for pr in plan['to_update']:+ cls.create_preview(app, pr) # idempotent update-in-place+ updated += 1+ for preview in plan['to_destroy']:+ pid = preview.get('id') if isinstance(preview, dict) else getattr(preview, 'id', None)+ cls.destroy_preview(pid)+ destroyed += 1++ return {'success': True, 'created': created,+ 'updated': updated, 'destroyed': destroyed}+ except Exception as exc:+ logger.warning('sync_previews failed for app %s: %s', application_id, exc)+ return {'error': str(exc)}++ @classmethod+ def _fetch_open_prs(cls, app):+ """Best-effort: list open PRs for the app's connected repo. Returns a+ list of ``{pr_number, branch, commit_sha, pr_title}`` dicts, or ``[]``+ when no provider is connected (e.g. dev/test)."""+ try:+ from app.services.source_connection_service import SourceConnectionService+ fn = getattr(SourceConnectionService, 'list_open_pull_requests', None)+ if callable(fn):+ prs = fn(app.id) or []+ return prs if isinstance(prs, list) else []+ except Exception as exc:+ logger.debug('open-PR listing unavailable for app %s: %s', app.id, exc)+ return []++ @classmethod+ def expire_stale(cls):+ """Destroy previews whose ``expires_at`` has passed. For a scheduled job.+ Returns ``{'expired': n}``. Best-effort; never raises."""+ from app.models.application_preview import ApplicationPreview++ try:+ now = datetime.utcnow()+ stale = ApplicationPreview.query.filter(+ ApplicationPreview.expires_at.isnot(None),+ ApplicationPreview.expires_at < now,+ ApplicationPreview.status != ApplicationPreview.STATUS_DESTROYED,+ ).all()+ for preview in stale:+ cls.destroy_preview(preview.id)+ return {'expired': len(stale)}+ except Exception as exc:+ logger.warning('expire_stale failed: %s', exc)+ return {'expired': 0, 'error': str(exc)}++ # ------------------------------------------------------------------ #+ # Jobs+ # ------------------------------------------------------------------ #++ @classmethod+ def _job_create(cls, job):+ from app.models import Application+ payload = job.get_payload() or {}+ app = Application.query.get(payload.get('application_id'))+ if not app:+ return {'error': 'application not found'}+ return cls.create_preview(app, payload.get('pr') or payload)++ @classmethod+ def _job_destroy(cls, job):+ payload = job.get_payload() or {}+ return cls.destroy_preview(payload.get('preview_id'))++ @classmethod+ def _job_sync(cls, job):+ payload = job.get_payload() or {}+ return cls.sync_previews(payload.get('application_id'))++ @classmethod+ def _job_expire(cls, _job):+ return cls.expire_stale()++ @classmethod+ def register_jobs(cls):+ """Register the preview job kinds with the unified job registry.+ Called once at app startup."""+ from app.jobs import registry+ registry.register(JOB_CREATE, cls._job_create, replace=True)+ registry.register(JOB_DESTROY, cls._job_destroy, replace=True)+ registry.register(JOB_SYNC, cls._job_sync, replace=True)+ registry.register(JOB_EXPIRE, cls._job_expire, replace=True)diff --git a/backend/app/services/project_service.py b/backend/app/services/project_service.pynew file mode 100644index 00000000..c18b9cc2--- /dev/null+++ b/backend/app/services/project_service.py@@ -0,0 +1,258 @@+"""Business logic for the Project / Environment hierarchy.++Hierarchy: Workspace -> Project -> Environment -> Applications.++The model is OPT-IN: applications carry nullable project_id/environment_id, so+existing apps remain unassigned and keep working. ProjectService centralizes the+CRUD plus the invariant that every project has at least one default environment.+"""+from datetime import datetime++from app import db+from app.models.project import Project+from app.models.environment import Environment+from app.models.application import Application+from app.utils.slug import unique_slug, slugify+++# Canonical environment names a project starts with / can add. Free-form names+# are allowed too; these are just the well-known ones the UI nudges toward.+KNOWN_ENVIRONMENTS = ('production', 'staging', 'development')+DEFAULT_PROJECT_NAME = 'Default'+DEFAULT_ENVIRONMENT_NAME = 'production'+++class ProjectService:+ """Static-method service for projects and their environments."""++ # ------------------------------------------------------------------ #+ # Projects+ # ------------------------------------------------------------------ #++ @staticmethod+ def list_projects(workspace_id):+ """All projects in a workspace, newest first."""+ return (Project.query+ .filter_by(workspace_id=workspace_id)+ .order_by(Project.created_at.desc())+ .all())++ @staticmethod+ def get_project(project_id):+ return Project.query.get(project_id)++ @staticmethod+ def _unique_project_slug(workspace_id, name):+ return unique_slug(+ name,+ lambda s: Project.query.filter_by(workspace_id=workspace_id, slug=s).first() is not None,+ default='project',+ )++ @staticmethod+ def create_project(workspace_id, name, description=None, metadata=None,+ default_environment=DEFAULT_ENVIRONMENT_NAME):+ """Create a project and auto-create its default environment.++ Returns the new Project. Raises ValueError on a blank name.+ """+ name = (name or '').strip()+ if not name:+ raise ValueError('Project name is required')++ slug = ProjectService._unique_project_slug(workspace_id, name)+ project = Project(+ workspace_id=workspace_id,+ name=name,+ slug=slug,+ description=(description or None),+ )+ if metadata:+ project.metadata_ = metadata+ db.session.add(project)+ db.session.flush() # assign project.id before creating the environment++ ProjectService.create_environment(+ project.id,+ name=default_environment or DEFAULT_ENVIRONMENT_NAME,+ is_default=True,+ )+ db.session.commit()+ return project++ @staticmethod+ def update_project(project_id, name=None, description=None, metadata=None):+ project = Project.query.get(project_id)+ if not project:+ return None+ if name is not None and name.strip():+ project.name = name.strip()+ if description is not None:+ project.description = description or None+ if metadata is not None:+ project.metadata_ = metadata+ project.updated_at = datetime.utcnow()+ db.session.commit()+ return project++ @staticmethod+ def delete_project(project_id):+ """Delete a project. Returns True on success, or the string 'has_apps' if+ the project still has applications assigned (caller should 409)."""+ project = Project.query.get(project_id)+ if not project:+ return None+ if Application.query.filter_by(project_id=project_id).count() > 0:+ return 'has_apps'+ db.session.delete(project) # cascades to environments+ db.session.commit()+ return True++ @staticmethod+ def ensure_default(workspace_id):+ """Find-or-create the workspace's Default project (with a default+ environment). Idempotent — safe to call repeatedly."""+ existing = Project.query.filter_by(+ workspace_id=workspace_id, slug=slugify(DEFAULT_PROJECT_NAME)+ ).first()+ if existing:+ # Guarantee it still has at least one environment (self-heal).+ if existing.environments.count() == 0:+ ProjectService.create_environment(+ existing.id, name=DEFAULT_ENVIRONMENT_NAME, is_default=True)+ db.session.commit()+ return existing+ return ProjectService.create_project(+ workspace_id,+ name=DEFAULT_PROJECT_NAME,+ description='Default project (auto-created).',+ )++ # ------------------------------------------------------------------ #+ # Environments+ # ------------------------------------------------------------------ #++ @staticmethod+ def list_environments(project_id):+ return (Environment.query+ .filter_by(project_id=project_id)+ .order_by(Environment.order, Environment.id)+ .all())++ @staticmethod+ def get_environment(environment_id):+ return Environment.query.get(environment_id)++ @staticmethod+ def _unique_environment_slug(project_id, name):+ return unique_slug(+ name,+ lambda s: Environment.query.filter_by(project_id=project_id, slug=s).first() is not None,+ default='environment',+ )++ @staticmethod+ def create_environment(project_id, name, is_default=False, order=None):+ """Create an environment under a project. Does NOT commit unless the+ project was just created via create_project; callers that need a commit+ (the API) should commit themselves — but create_environment flushes so the+ id is available immediately."""+ name = (name or '').strip()+ if not name:+ raise ValueError('Environment name is required')++ slug = ProjectService._unique_environment_slug(project_id, name)+ if order is None:+ current_max = (db.session.query(db.func.max(Environment.order))+ .filter_by(project_id=project_id).scalar())+ order = (current_max + 1) if current_max is not None else 0++ env = Environment(+ project_id=project_id,+ name=name,+ slug=slug,+ is_default=bool(is_default),+ order=order,+ )+ db.session.add(env)+ db.session.flush()+ return env++ @staticmethod+ def update_environment(environment_id, name=None, is_default=None):+ env = Environment.query.get(environment_id)+ if not env:+ return None+ if name is not None and name.strip():+ env.name = name.strip()+ if is_default is not None:+ env.is_default = bool(is_default)+ db.session.commit()+ return env++ @staticmethod+ def delete_environment(environment_id):+ """Delete an environment. Refuses to delete the last/only environment of a+ project (returns 'last'), and detaches any apps assigned to it (sets their+ environment_id to NULL) so apps are never orphaned. Returns True on+ success, 'last' if it's the only one, None if not found."""+ env = Environment.query.get(environment_id)+ if not env:+ return None+ sibling_count = Environment.query.filter_by(project_id=env.project_id).count()+ if sibling_count <= 1:+ return 'last'++ # Detach apps from the deleted environment (keep them in the project).+ Application.query.filter_by(environment_id=environment_id).update(+ {'environment_id': None}, synchronize_session=False)+ was_default = env.is_default+ db.session.delete(env)+ db.session.flush()++ # If we removed the default env, promote the first remaining one.+ if was_default:+ replacement = (Environment.query+ .filter_by(project_id=env.project_id)+ .order_by(Environment.order, Environment.id)+ .first())+ if replacement:+ replacement.is_default = True+ db.session.commit()+ return True++ @staticmethod+ def reorder_environments(project_id, ordered_ids):+ """Apply a new ordering to a project's environments. ordered_ids is the+ list of environment ids in the desired order. Ids not belonging to the+ project are ignored. Returns the reordered list."""+ envs = {e.id: e for e in Environment.query.filter_by(project_id=project_id).all()}+ position = 0+ for eid in ordered_ids:+ env = envs.get(eid)+ if env is not None:+ env.order = position+ position += 1+ # Any environments not named in ordered_ids keep a stable tail order.+ for env in sorted(envs.values(), key=lambda e: (e.order, e.id)):+ if env.id not in set(ordered_ids):+ env.order = position+ position += 1+ db.session.commit()+ return ProjectService.list_environments(project_id)++ # ------------------------------------------------------------------ #+ # App membership helpers+ # ------------------------------------------------------------------ #++ @staticmethod+ def list_project_apps(project_id):+ return Application.query.filter_by(project_id=project_id).all()++ @staticmethod+ def list_environment_apps(environment_id):+ return Application.query.filter_by(environment_id=environment_id).all()++ @staticmethod+ def count_project_apps(project_id):+ return Application.query.filter_by(project_id=project_id).count()diff --git a/backend/app/services/proxy_stack_service.py b/backend/app/services/proxy_stack_service.pynew file mode 100644index 00000000..b3616e37--- /dev/null+++ b/backend/app/services/proxy_stack_service.py@@ -0,0 +1,514 @@+"""ProxyStackService — manage a per-server Dockerized reverse-proxy stack.++Design notes+------------+Host Nginx stays the default reverse proxy and is *superior* for+PHP/WordPress (FastCGI, fine-grained per-site config). This service is the+opt-in path for running a containerized proxy — Traefik or Caddy — as a+Compose stack on a server, with versioned config backups.++The TESTABLE CORE is two pure generators:++ * ``generate_compose`` — returns a valid docker-compose YAML *string* for+ traefik/caddy (or ``None`` for nginx). Deterministic; no I/O.+ * ``generate_config`` — returns a minimal proxy config (Traefik dynamic+ file / Caddyfile) for a list of site dicts. Deterministic; no I/O.++Everything that touches Docker or the filesystem (``deploy_stack``,+``regenerate``, ``status``) is BEST-EFFORT and GUARDED: it imports and runs+without a live Docker daemon, returning a structured result instead of+raising. Remote-server execution (via the agent) is left as future work — for+now provisioning is host-local + best-effort.+"""+import os+import json+import hashlib+import logging+from datetime import datetime++import yaml++logger = logging.getLogger(__name__)+++class ProxyStackService:+ """Static service for managed reverse-proxy stacks."""++ # Canonical proxy types. 'nginx' = host nginx (no stack).+ PROXY_TYPES = ('nginx', 'traefik', 'caddy')++ # The shared external docker network managed apps attach to. The proxy+ # joins it so it can reach upstream containers by name.+ NETWORK_NAME = 'serverkit'++ # Pinned images keep generated compose deterministic and testable.+ TRAEFIK_IMAGE = 'traefik:v3.1'+ CADDY_IMAGE = 'caddy:2.8'++ # ------------------------------------------------------------------+ # Pure generators (the testable core)+ # ------------------------------------------------------------------++ @staticmethod+ def generate_compose(server_id, proxy_type, options=None):+ """Return a docker-compose YAML string for the given proxy type.++ Pure & deterministic — no I/O, safe to unit-test. For ``nginx`` it+ returns ``None`` (host nginx needs no Compose stack).++ ``options`` (dict, optional):+ - ``acme_email``: enable ACME/Let's Encrypt with this contact email+ - ``dashboard``: expose the Traefik dashboard (insecure) — default off+ - ``network``: override the external network name+ """+ proxy_type = (proxy_type or 'nginx').lower()+ options = options or {}+ network = options.get('network') or ProxyStackService.NETWORK_NAME++ if proxy_type == 'nginx':+ return None++ if proxy_type == 'traefik':+ return ProxyStackService._traefik_compose(server_id, network, options)++ if proxy_type == 'caddy':+ return ProxyStackService._caddy_compose(server_id, network, options)++ raise ValueError(f"Unknown proxy_type: {proxy_type!r}")++ @staticmethod+ def _traefik_compose(server_id, network, options):+ acme_email = options.get('acme_email')+ dashboard = bool(options.get('dashboard'))++ command = [+ '--providers.docker=true',+ '--providers.docker.exposedbydefault=false',+ f'--providers.docker.network={network}',+ '--providers.file.directory=/etc/traefik/dynamic',+ '--providers.file.watch=true',+ '--entrypoints.web.address=:80',+ '--entrypoints.websecure.address=:443',+ ]+ ports = ['80:80', '443:443']+ volumes = [+ '/var/run/docker.sock:/var/run/docker.sock:ro',+ './dynamic:/etc/traefik/dynamic:ro',+ ]++ if acme_email:+ command += [+ '--certificatesresolvers.serverkit.acme.tlschallenge=true',+ f'--certificatesresolvers.serverkit.acme.email={acme_email}',+ '--certificatesresolvers.serverkit.acme.storage=/acme/acme.json',+ ]+ volumes.append('./acme:/acme')++ if dashboard:+ command.append('--api.dashboard=true')+ command.append('--api.insecure=true')+ ports.append('8080:8080')++ compose = {+ 'services': {+ 'proxy': {+ 'image': ProxyStackService.TRAEFIK_IMAGE,+ 'container_name': f'serverkit-proxy-{server_id[:8]}',+ 'restart': 'unless-stopped',+ 'command': command,+ 'ports': ports,+ 'volumes': volumes,+ 'networks': [network],+ },+ },+ 'networks': {+ network: {'external': True},+ },+ }+ return yaml.safe_dump(compose, sort_keys=False, default_flow_style=False)++ @staticmethod+ def _caddy_compose(server_id, network, options):+ acme_email = options.get('acme_email')++ environment = {}+ if acme_email:+ environment['ACME_AGREE'] = 'true'+ environment['CADDY_EMAIL'] = acme_email++ service = {+ 'image': ProxyStackService.CADDY_IMAGE,+ 'container_name': f'serverkit-proxy-{server_id[:8]}',+ 'restart': 'unless-stopped',+ 'ports': ['80:80', '443:443'],+ 'volumes': [+ './Caddyfile:/etc/caddy/Caddyfile:ro',+ 'caddy_data:/data',+ 'caddy_config:/config',+ ],+ 'networks': [network],+ }+ if environment:+ service['environment'] = environment++ compose = {+ 'services': {+ 'proxy': service,+ },+ 'networks': {+ network: {'external': True},+ },+ 'volumes': {+ 'caddy_data': {},+ 'caddy_config': {},+ },+ }+ return yaml.safe_dump(compose, sort_keys=False, default_flow_style=False)++ @staticmethod+ def generate_config(proxy_type, sites, custom_snippet=None):+ """Return a minimal proxy config for a list of site dicts.++ Pure & deterministic. Each site dict may carry:+ - ``domain`` (required): the public hostname+ - ``upstream`` : host:port or container name the proxy forwards to+ - ``tls`` : truthy → enable HTTPS for that site++ For ``traefik`` this returns a YAML dynamic-config file; for ``caddy``+ a Caddyfile. ``custom_snippet`` is appended verbatim. ``nginx`` returns+ ``None`` (host nginx config is owned elsewhere).+ """+ proxy_type = (proxy_type or 'nginx').lower()+ sites = sites or []++ if proxy_type == 'nginx':+ return None++ if proxy_type == 'traefik':+ return ProxyStackService._traefik_dynamic(sites, custom_snippet)++ if proxy_type == 'caddy':+ return ProxyStackService._caddyfile(sites, custom_snippet)++ raise ValueError(f"Unknown proxy_type: {proxy_type!r}")++ @staticmethod+ def _traefik_dynamic(sites, custom_snippet):+ routers = {}+ services = {}+ for i, site in enumerate(sites):+ domain = site.get('domain')+ if not domain:+ continue+ upstream = site.get('upstream') or 'http://app:80'+ if not upstream.startswith('http'):+ upstream = f'http://{upstream}'+ name = f"site{i}"+ router = {+ 'rule': f'Host(`{domain}`)',+ 'service': name,+ 'entryPoints': ['websecure' if site.get('tls') else 'web'],+ }+ if site.get('tls'):+ router['tls'] = {'certResolver': 'serverkit'}+ routers[name] = router+ services[name] = {+ 'loadBalancer': {'servers': [{'url': upstream}]}+ }++ dynamic = {'http': {'routers': routers, 'services': services}}+ out = yaml.safe_dump(dynamic, sort_keys=False, default_flow_style=False)+ if custom_snippet:+ out = out + '\n# --- custom snippet ---\n' + custom_snippet.strip() + '\n'+ return out++ @staticmethod+ def _caddyfile(sites, custom_snippet):+ lines = []+ for site in sites:+ domain = site.get('domain')+ if not domain:+ continue+ upstream = site.get('upstream') or 'app:80'+ lines.append(f'{domain} {{')+ lines.append(f' reverse_proxy {upstream}')+ if not site.get('tls'):+ # Disable automatic HTTPS for plain-HTTP sites — keeps TLS+ # opt-in, matching the host-nginx "SSL stays optional" stance.+ lines.append(' tls internal')+ lines.append('}')+ lines.append('')++ out = '\n'.join(lines)+ if custom_snippet:+ out = out + '\n# --- custom snippet ---\n' + custom_snippet.strip() + '\n'+ return out++ @staticmethod+ def config_hash(content):+ """Deterministic 8-char hash of a config/compose string.++ Pure — used both to name versioned backups and to detect no-op+ regenerations. SHA-256 truncated to 8 hex chars.+ """+ if content is None:+ content = ''+ return hashlib.sha256(content.encode('utf-8')).hexdigest()[:8]++ # ------------------------------------------------------------------+ # DB / row management+ # ------------------------------------------------------------------++ @staticmethod+ def _stack_dir(server_id):+ """On-disk directory for this server's proxy stack.++ Lives under the apps base so it sits next to managed-app compose+ projects. Pure path computation; does not create anything.+ """+ try:+ from app import paths+ base = paths.APPS_DIR+ except Exception:+ base = os.path.join(os.getcwd(), 'apps')+ return os.path.join(base, 'proxy', server_id)++ @staticmethod+ def get_or_create(server_id):+ """Return the ProxyStack row for a server, creating a default+ (host-nginx) row if none exists."""+ from app import db+ from app.models.proxy_stack import ProxyStack++ stack = ProxyStack.query.filter_by(server_id=server_id).first()+ if stack:+ return stack++ stack = ProxyStack(+ server_id=server_id,+ proxy_type='nginx',+ status='unknown',+ networks=json.dumps([ProxyStackService.NETWORK_NAME]),+ )+ db.session.add(stack)+ db.session.commit()+ return stack++ @staticmethod+ def configure(server_id, proxy_type=None, custom_snippet=None):+ """Update a server's proxy configuration (type and/or snippet).++ Does NOT touch Docker — pure DB mutation. Call ``deploy_stack`` /+ ``regenerate`` afterwards to apply.+ """+ from app import db++ stack = ProxyStackService.get_or_create(server_id)++ if proxy_type is not None:+ pt = proxy_type.lower()+ if pt not in ProxyStackService.PROXY_TYPES:+ raise ValueError(f"Unknown proxy_type: {proxy_type!r}")+ stack.proxy_type = pt+ # The compose_path only makes sense for stack-based proxies.+ if pt == 'nginx':+ stack.compose_path = None+ else:+ stack.compose_path = os.path.join(+ ProxyStackService._stack_dir(server_id), 'docker-compose.yml'+ )++ if custom_snippet is not None:+ stack.custom_snippet = custom_snippet++ db.session.commit()+ return stack++ @staticmethod+ def switch(server_id, proxy_type):+ """Flip a server to a different proxy type. Thin wrapper over+ ``configure`` that exists for a clear, intention-revealing API."""+ return ProxyStackService.configure(server_id, proxy_type=proxy_type)++ # ------------------------------------------------------------------+ # Best-effort provisioning (guarded — no hard Docker dependency)+ # ------------------------------------------------------------------++ @staticmethod+ def _write_stack_files(stack, options=None):+ """Write compose + config to disk for a stack-based proxy.++ Best-effort: returns the stack dir on success, None on nginx/failure.+ """+ if stack.proxy_type == 'nginx':+ return None+ compose = ProxyStackService.generate_compose(+ stack.server_id, stack.proxy_type, options+ )+ if compose is None:+ return None++ stack_dir = ProxyStackService._stack_dir(stack.server_id)+ try:+ os.makedirs(stack_dir, exist_ok=True)+ compose_path = os.path.join(stack_dir, 'docker-compose.yml')+ with open(compose_path, 'w', encoding='utf-8') as f:+ f.write(compose)++ config = ProxyStackService.generate_config(+ stack.proxy_type, [], stack.custom_snippet+ )+ if config is not None:+ if stack.proxy_type == 'caddy':+ cfg_path = os.path.join(stack_dir, 'Caddyfile')+ else:+ dyn_dir = os.path.join(stack_dir, 'dynamic')+ os.makedirs(dyn_dir, exist_ok=True)+ cfg_path = os.path.join(dyn_dir, 'serverkit.yml')+ with open(cfg_path, 'w', encoding='utf-8') as f:+ f.write(config)+ return stack_dir+ except OSError as e:+ logger.warning(f"Failed to write proxy stack files: {e}")+ return None++ @staticmethod+ def deploy_stack(server_id, options=None):+ """Best-effort: write files + `compose up` the proxy stack.++ Guarded so it never raises on a missing Docker daemon — returns a+ structured result. For host-nginx there's nothing to deploy.+ """+ from app import db++ stack = ProxyStackService.get_or_create(server_id)++ if stack.proxy_type == 'nginx':+ stack.status = 'unknown'+ db.session.commit()+ return {'success': True, 'message': 'Host nginx — no stack to deploy.'}++ stack_dir = ProxyStackService._write_stack_files(stack, options)+ if not stack_dir:+ stack.status = 'error'+ db.session.commit()+ return {'success': False, 'error': 'Could not write stack files.'}++ stack.compose_path = os.path.join(stack_dir, 'docker-compose.yml')+ stack.last_regenerated_at = datetime.utcnow()++ result = {'success': False, 'error': 'Docker unavailable'}+ try:+ from app.services.docker_service import DockerService+ result = DockerService.compose_up(stack_dir, detach=True)+ except Exception as e: # pragma: no cover - depends on live docker+ logger.warning(f"deploy_stack compose_up failed: {e}")+ result = {'success': False, 'error': str(e)}++ stack.status = 'running' if result.get('success') else 'error'+ db.session.commit()+ return result++ @staticmethod+ def regenerate(server_id, sites=None, options=None):+ """Rewrite the proxy config (+ best-effort hot reload).++ Backs up the current config first, regenerates, and tries a reload.+ Guarded — returns a result dict; never hard-depends on Docker.+ """+ from app import db++ stack = ProxyStackService.get_or_create(server_id)++ if stack.proxy_type == 'nginx':+ return {'success': True, 'message': 'Host nginx — managed elsewhere.'}++ # Snapshot the existing config before we overwrite it.+ ProxyStackService.backup_config(server_id)++ stack_dir = ProxyStackService._write_stack_files(stack, options)+ if not stack_dir:+ return {'success': False, 'error': 'Could not write stack files.'}++ stack.last_regenerated_at = datetime.utcnow()++ reload_result = {'success': False, 'error': 'Docker unavailable'}+ try:+ from app.services.docker_service import DockerService+ reload_result = DockerService.compose_restart(stack_dir, service='proxy')+ except Exception as e: # pragma: no cover - depends on live docker+ logger.warning(f"regenerate reload failed: {e}")+ reload_result = {'success': False, 'error': str(e)}++ db.session.commit()+ return {+ 'success': True,+ 'reloaded': bool(reload_result.get('success')),+ 'reload_error': reload_result.get('error'),+ }++ @staticmethod+ def backup_config(server_id):+ """Keep a versioned copy of the current compose file.++ Names backups ``docker-compose.<timestamp>.<hash8>.yml`` where the+ hash is the pure ``config_hash`` of the file contents — so identical+ configs always produce the same suffix. Best-effort; returns the+ backup path or None.+ """+ stack_dir = ProxyStackService._stack_dir(server_id)+ compose_path = os.path.join(stack_dir, 'docker-compose.yml')+ if not os.path.exists(compose_path):+ return None+ try:+ with open(compose_path, 'r', encoding='utf-8') as f:+ content = f.read()+ digest = ProxyStackService.config_hash(content)+ ts = datetime.utcnow().strftime('%Y%m%d%H%M%S')+ backup_dir = os.path.join(stack_dir, 'backups')+ os.makedirs(backup_dir, exist_ok=True)+ backup_path = os.path.join(+ backup_dir, f'docker-compose.{ts}.{digest}.yml'+ )+ with open(backup_path, 'w', encoding='utf-8') as f:+ f.write(content)+ return backup_path+ except OSError as e:+ logger.warning(f"backup_config failed: {e}")+ return None++ @staticmethod+ def status(server_id):+ """Best-effort runtime status of the proxy stack.++ Returns the stored row state plus, when Docker is reachable, the live+ container state from `compose ps`. Never raises.+ """+ from app import db++ stack = ProxyStackService.get_or_create(server_id)+ result = stack.to_dict()+ result['running_containers'] = []++ if stack.proxy_type == 'nginx' or not stack.compose_path:+ return result++ stack_dir = os.path.dirname(stack.compose_path)+ try:+ from app.services.docker_service import DockerService+ containers = DockerService.compose_ps(stack_dir)+ result['running_containers'] = containers or []+ # Reconcile stored status with reality when we can see it.+ if containers:+ running = any(+ str(c.get('State', '')).lower() == 'running' for c in containers+ )+ new_status = 'running' if running else 'stopped'+ if stack.status != new_status:+ stack.status = new_status+ db.session.commit()+ result['status'] = new_status+ except Exception as e: # pragma: no cover - depends on live docker+ logger.debug(f"status() docker probe failed: {e}")++ return resultdiff --git a/backend/app/services/shared_resource_service.py b/backend/app/services/shared_resource_service.pynew file mode 100644index 00000000..52b41f23--- /dev/null+++ b/backend/app/services/shared_resource_service.py@@ -0,0 +1,297 @@+"""Service layer for polymorphic shared resources (tags + variable groups).++A thin, stateless facade over the models in+``app.models.shared_resource``. It is purely additive: nothing here reads or+writes the existing per-resource env-var tables. Resources are addressed by+``(resource_type, resource_id)`` where ``resource_id`` is coerced to a string so+both int-keyed (apps, servers) and string-keyed (container names) resources work.++Override / merge rule for :meth:`resolve_variables`+---------------------------------------------------+A resource may have several groups attached. The effective variable set is built+by iterating the attached groups **in attachment order** (oldest attachment+first) and writing each group's variables into a dict keyed by variable key.+Because a later write overwrites an earlier one, **the most recently attached+group wins** on key collisions ("last attachment wins"). Each resolved entry+records the ``group_id``/``group_name`` it came from so callers can show+provenance.+"""+from app import db+from app.models.shared_resource import (+ ResourceTag,+ SharedVariable,+ SharedVariableGroup,+ SharedVariableGroupAttachment,+)+++class SharedResourceService:+ """Static facade for tags and shared variable groups."""++ # Supported polymorphic resource types. Kept as a constant so the API and+ # the frontend can advertise the same catalog.+ RESOURCE_TYPES = (+ 'application',+ 'database',+ 'service',+ 'wordpress',+ 'server',+ )++ # ------------------------------------------------------------------ tags++ @staticmethod+ def _rid(resource_id):+ """Normalize a resource id to the string form stored in the DB."""+ return str(resource_id)++ @staticmethod+ def add_tag(resource_type, resource_id, tag):+ """Attach a tag to a resource. Idempotent — returns the existing or new row."""+ tag = (tag or '').strip()+ if not tag:+ raise ValueError('tag is required')+ rid = SharedResourceService._rid(resource_id)++ existing = ResourceTag.query.filter_by(+ resource_type=resource_type, resource_id=rid, tag=tag+ ).first()+ if existing:+ return existing++ row = ResourceTag(resource_type=resource_type, resource_id=rid, tag=tag)+ db.session.add(row)+ try:+ db.session.commit()+ except Exception:+ # Lost a race with a concurrent insert — fall back to the winner.+ db.session.rollback()+ return ResourceTag.query.filter_by(+ resource_type=resource_type, resource_id=rid, tag=tag+ ).first()+ return row++ @staticmethod+ def remove_tag(resource_type, resource_id, tag):+ """Detach a tag from a resource. Returns True if a row was deleted."""+ rid = SharedResourceService._rid(resource_id)+ row = ResourceTag.query.filter_by(+ resource_type=resource_type, resource_id=rid, tag=(tag or '').strip()+ ).first()+ if not row:+ return False+ db.session.delete(row)+ db.session.commit()+ return True++ @staticmethod+ def list_tags(resource_type, resource_id):+ """List all tags on a resource (ordered by tag name)."""+ rid = SharedResourceService._rid(resource_id)+ return ResourceTag.query.filter_by(+ resource_type=resource_type, resource_id=rid+ ).order_by(ResourceTag.tag.asc()).all()++ @staticmethod+ def list_resources_by_tag(tag, resource_type=None):+ """List every resource carrying a given tag (optionally one type)."""+ query = ResourceTag.query.filter_by(tag=(tag or '').strip())+ if resource_type:+ query = query.filter_by(resource_type=resource_type)+ return query.order_by(+ ResourceTag.resource_type.asc(), ResourceTag.resource_id.asc()+ ).all()++ # --------------------------------------------------------------- groups++ @staticmethod+ def create_group(scope_type, scope_id, name, description=None):+ """Create a new shared variable group."""+ if scope_type not in SharedVariableGroup.VALID_SCOPES:+ raise ValueError(f'invalid scope_type: {scope_type}')+ name = (name or '').strip()+ if not name:+ raise ValueError('name is required')++ group = SharedVariableGroup(+ scope_type=scope_type,+ scope_id=SharedResourceService._rid(scope_id),+ name=name,+ description=(description or None),+ )+ db.session.add(group)+ db.session.commit()+ return group++ @staticmethod+ def get_group(group_id):+ return SharedVariableGroup.query.get(group_id)++ @staticmethod+ def list_groups(scope_type=None, scope_id=None):+ """List groups, optionally filtered by scope."""+ query = SharedVariableGroup.query+ if scope_type:+ query = query.filter_by(scope_type=scope_type)+ if scope_id is not None:+ query = query.filter_by(scope_id=SharedResourceService._rid(scope_id))+ return query.order_by(SharedVariableGroup.name.asc()).all()++ @staticmethod+ def update_group(group_id, name=None, description=None):+ group = SharedVariableGroup.query.get(group_id)+ if not group:+ return None+ if name is not None:+ name = name.strip()+ if not name:+ raise ValueError('name cannot be empty')+ group.name = name+ if description is not None:+ group.description = description or None+ db.session.commit()+ return group++ @staticmethod+ def delete_group(group_id):+ """Delete a group (cascades to its variables and attachments)."""+ group = SharedVariableGroup.query.get(group_id)+ if not group:+ return False+ db.session.delete(group)+ db.session.commit()+ return True++ # --------------------------------------------- variables within a group++ @staticmethod+ def set_variable(group_id, key, value, is_secret=False):+ """Create or update a variable in a group (upsert by key)."""+ group = SharedVariableGroup.query.get(group_id)+ if not group:+ return None+ key = (key or '').strip()+ if not key:+ raise ValueError('key is required')++ var = SharedVariable.query.filter_by(group_id=group_id, key=key).first()+ if var is None:+ var = SharedVariable(group_id=group_id, key=key, is_secret=bool(is_secret))+ var.value = value if value is not None else ''+ db.session.add(var)+ else:+ var.value = value if value is not None else ''+ var.is_secret = bool(is_secret)+ db.session.commit()+ return var++ @staticmethod+ def update_variable(variable_id, value=None, is_secret=None):+ var = SharedVariable.query.get(variable_id)+ if not var:+ return None+ if value is not None:+ var.value = value+ if is_secret is not None:+ var.is_secret = bool(is_secret)+ db.session.commit()+ return var++ @staticmethod+ def delete_variable(variable_id):+ var = SharedVariable.query.get(variable_id)+ if not var:+ return False+ db.session.delete(var)+ db.session.commit()+ return True++ @staticmethod+ def list_variables(group_id):+ return SharedVariable.query.filter_by(group_id=group_id).order_by(+ SharedVariable.key.asc()+ ).all()++ # ---------------------------------------------------------- attachments++ @staticmethod+ def attach_group(group_id, resource_type, resource_id):+ """Attach a group to a resource. Idempotent."""+ group = SharedVariableGroup.query.get(group_id)+ if not group:+ return None+ rid = SharedResourceService._rid(resource_id)++ existing = SharedVariableGroupAttachment.query.filter_by(+ group_id=group_id, resource_type=resource_type, resource_id=rid+ ).first()+ if existing:+ return existing++ att = SharedVariableGroupAttachment(+ group_id=group_id, resource_type=resource_type, resource_id=rid+ )+ db.session.add(att)+ try:+ db.session.commit()+ except Exception:+ db.session.rollback()+ return SharedVariableGroupAttachment.query.filter_by(+ group_id=group_id, resource_type=resource_type, resource_id=rid+ ).first()+ return att++ @staticmethod+ def detach_group(group_id, resource_type, resource_id):+ """Detach a group from a resource. Returns True if a row was deleted."""+ rid = SharedResourceService._rid(resource_id)+ att = SharedVariableGroupAttachment.query.filter_by(+ group_id=group_id, resource_type=resource_type, resource_id=rid+ ).first()+ if not att:+ return False+ db.session.delete(att)+ db.session.commit()+ return True++ @staticmethod+ def list_attached_groups(resource_type, resource_id):+ """Return the groups attached to a resource, in attachment order."""+ rid = SharedResourceService._rid(resource_id)+ attachments = SharedVariableGroupAttachment.query.filter_by(+ resource_type=resource_type, resource_id=rid+ ).order_by(SharedVariableGroupAttachment.created_at.asc(),+ SharedVariableGroupAttachment.id.asc()).all()++ groups = []+ for att in attachments:+ group = SharedVariableGroup.query.get(att.group_id)+ if group:+ groups.append(group)+ return groups++ # ------------------------------------------------------------- resolve++ @staticmethod+ def resolve_variables(resource_type, resource_id, mask_secrets=True):+ """Merge variables from every attached group into one effective set.++ Merge rule: groups are applied in attachment order (oldest first), so a+ key defined in a later-attached group overrides an earlier one+ (**last attachment wins**). Each entry records its source group.+ """+ groups = SharedResourceService.list_attached_groups(resource_type, resource_id)++ resolved = {}+ for group in groups:+ for var in group.variables:+ resolved[var.key] = {+ 'key': var.key,+ 'value': (SharedVariable.to_dict(var, mask_secrets=mask_secrets)+ ['value']),+ 'is_secret': var.is_secret,+ 'group_id': group.id,+ 'group_name': group.name,+ }++ return [resolved[k] for k in sorted(resolved.keys())]diff --git a/backend/app/services/wordpress_service.py b/backend/app/services/wordpress_service.pyindex b7348b88..d1ae2ef2 100644--- a/backend/app/services/wordpress_service.py+++ b/backend/app/services/wordpress_service.py@@ -2580,3 +2580,104 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]return app_name in result.stdoutexcept Exception:return False++ # ── PR Preview Environments (best-effort) ─────────────────────────────────+ # Hooks driven by PreviewService when a PR opens/closes against a WordPress+ # site. Cloning a full WordPress stack needs Docker + a DB; both may be+ # absent in dev/test, so every step is guarded and a missing dependency+ # degrades to "recorded but not provisioned" rather than raising.++ @classmethod+ def _preview_db_name(cls, site, pr_number: int) -> str:+ """Temporary DB name for a PR preview: ``wp_preview_<pr>`` (scoped per+ site so two sites' PR #1 previews don't collide)."""+ base = (getattr(site, 'db_name', None) or 'wp').strip() or 'wp'+ return f'{base}_preview_{int(pr_number)}'++ @classmethod+ def create_preview_instance(cls, site, pr_number, domain=None, branch=None) -> Dict:+ """Spin up an isolated preview of a WordPress site for a PR.++ Best-effort: clone the site files into a preview directory, create a+ temporary database copy (``wp_preview_<pr>``), and rewrite the site URL+ to the preview ``domain``. Never raises — returns a result dict with+ ``success`` reflecting how much could actually be provisioned. In an+ environment without WP-CLI/Docker this is a no-op that still reports the+ intended preview so the row can flip to running.+ """+ result = {'success': True, 'pr_number': int(pr_number) if pr_number is not None else None,+ 'domain': domain, 'db_name': None, 'preview_path': None,+ 'container_ids': [], 'provisioned': False, 'warnings': []}+ try:+ app = getattr(site, 'application', None)+ src_path = getattr(app, 'root_path', None) if app else None+ preview_db = cls._preview_db_name(site, pr_number)+ result['db_name'] = preview_db++ # 1) Clone files into a sibling preview directory (best-effort).+ if src_path and os.path.isdir(src_path):+ preview_path = f'{src_path.rstrip("/")}-preview-pr-{int(pr_number)}'+ result['preview_path'] = preview_path+ try:+ if not os.path.exists(preview_path):+ shutil.copytree(src_path, preview_path, symlinks=True)+ result['provisioned'] = True+ except Exception as exc:+ result['warnings'].append(f'file clone skipped: {exc}')+ else:+ result['warnings'].append('source path unavailable; files not cloned')++ # 2) Best-effort temp DB copy via WP-CLI (export from source, import+ # into the preview db). Both halves are guarded; failure leaves the+ # preview file-only.+ if result.get('preview_path') and src_path:+ try:+ cls.wp_cli(src_path, ['db', 'export', f'/tmp/{preview_db}.sql'])+ cls.wp_cli(result['preview_path'], ['db', 'create'])+ cls.wp_cli(result['preview_path'], ['db', 'import', f'/tmp/{preview_db}.sql'])+ except Exception as exc:+ result['warnings'].append(f'db copy skipped: {exc}')++ # 3) Rewrite the preview's site URL to the temporary domain.+ if domain and result.get('preview_path'):+ try:+ new_url = f'https://{domain}'+ cls.search_replace(result['preview_path'],+ cls._site_current_url(app) or '', new_url)+ cls.wp_cli(result['preview_path'], ['option', 'update', 'home', new_url])+ cls.wp_cli(result['preview_path'], ['option', 'update', 'siteurl', new_url])+ except Exception as exc:+ result['warnings'].append(f'url rewrite skipped: {exc}')++ return result+ except Exception as exc:+ # Never break the caller — record the failure and move on.+ return {'success': False, 'error': str(exc),+ 'pr_number': int(pr_number) if pr_number is not None else None,+ 'container_ids': []}++ @classmethod+ def destroy_preview_instance(cls, site, pr_number) -> Dict:+ """Tear down a WordPress PR preview: drop the temp DB and remove the+ cloned preview directory. Best-effort; never raises."""+ result = {'success': True, 'pr_number': int(pr_number) if pr_number is not None else None,+ 'warnings': []}+ try:+ app = getattr(site, 'application', None)+ src_path = getattr(app, 'root_path', None) if app else None+ if src_path:+ preview_path = f'{src_path.rstrip("/")}-preview-pr-{int(pr_number)}'+ # Drop the temp DB first (uses the preview's own wp-config).+ if os.path.isdir(preview_path):+ try:+ cls.wp_cli(preview_path, ['db', 'drop', '--yes'])+ except Exception as exc:+ result['warnings'].append(f'db drop skipped: {exc}')+ try:+ shutil.rmtree(preview_path, ignore_errors=True)+ except Exception as exc:+ result['warnings'].append(f'dir removal skipped: {exc}')+ return result+ except Exception as exc:+ return {'success': False, 'error': str(exc),+ 'pr_number': int(pr_number) if pr_number is not None else None}diff --git a/backend/migrations/versions/031_projects_environments.py b/backend/migrations/versions/031_projects_environments.pynew file mode 100644index 00000000..97fe4cf1--- /dev/null+++ b/backend/migrations/versions/031_projects_environments.py@@ -0,0 +1,86 @@+"""Project / Environment hierarchy.++Adds:+- projects, environments+- applications.project_id / environment_id (nullable, opt-in)++Organizes apps under Workspace -> Project -> Environment. Columns stay nullable;+unassigned apps remain valid (no destructive backfill).++Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on boot+before Alembic, so guard on the live schema.++Revision ID: 031_projects_environments+Revises: 030_buildpacks_snapshots+Create Date: 2026-06-23+"""+from alembic import op+import sqlalchemy as sa++revision = '031_projects_environments'+down_revision = '030_buildpacks_snapshots'+branch_labels = None+depends_on = None+++def upgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ existing = set(inspector.get_table_names())++ if 'projects' not in existing:+ op.create_table(+ 'projects',+ sa.Column('id', sa.Integer, nullable=False),+ sa.Column('workspace_id', sa.Integer, nullable=False),+ sa.Column('name', sa.String(128), nullable=False),+ sa.Column('slug', sa.String(128), nullable=False),+ sa.Column('description', sa.Text, nullable=True),+ sa.Column('metadata_json', sa.Text, nullable=True),+ sa.Column('created_at', sa.DateTime, nullable=True),+ sa.Column('updated_at', sa.DateTime, nullable=True),+ sa.PrimaryKeyConstraint('id'),+ sa.UniqueConstraint('workspace_id', 'slug', name='uq_project_workspace_slug'),+ )+ op.create_index('ix_projects_workspace_id', 'projects', ['workspace_id'])++ if 'environments' not in existing:+ op.create_table(+ 'environments',+ sa.Column('id', sa.Integer, nullable=False),+ sa.Column('project_id', sa.Integer, nullable=False),+ sa.Column('name', sa.String(64), nullable=False),+ sa.Column('slug', sa.String(64), nullable=False),+ sa.Column('is_default', sa.Boolean, nullable=True),+ sa.Column('order', sa.Integer, nullable=True),+ sa.Column('created_at', sa.DateTime, nullable=True),+ sa.PrimaryKeyConstraint('id'),+ sa.UniqueConstraint('project_id', 'slug', name='uq_environment_project_slug'),+ )+ op.create_index('ix_environments_project_id', 'environments', ['project_id'])++ if 'applications' in existing:+ cols = {c['name'] for c in inspector.get_columns('applications')}+ # Plain columns (FK not enforceable via SQLite ALTER ADD COLUMN; the ORM+ # still declares the relationship).+ if 'project_id' not in cols:+ op.add_column('applications', sa.Column('project_id', sa.Integer, nullable=True))+ op.create_index('ix_applications_project_id', 'applications', ['project_id'])+ if 'environment_id' not in cols:+ op.add_column('applications', sa.Column('environment_id', sa.Integer, nullable=True))+ op.create_index('ix_applications_environment_id', 'applications', ['environment_id'])+++def downgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ existing = set(inspector.get_table_names())+ if 'applications' in existing:+ cols = {c['name'] for c in inspector.get_columns('applications')}+ for col in ('environment_id', 'project_id'):+ if col in cols:+ op.drop_column('applications', col)+ if 'environments' in existing:+ op.drop_table('environments')+ if 'projects' in existing:+ op.drop_table('projects')diff --git a/backend/migrations/versions/032_shared_resources.py b/backend/migrations/versions/032_shared_resources.pynew file mode 100644index 00000000..c48cf0e1--- /dev/null+++ b/backend/migrations/versions/032_shared_resources.py@@ -0,0 +1,96 @@+"""Polymorphic shared resources (facade layer).++Adds:+- resource_tags+- shared_variable_groups, shared_variables, shared_variable_group_attachments++Tags and shared variable groups attach to any resource via (resource_type,+resource_id). Existing per-resource env var tables are untouched (facade first).++Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on boot+before Alembic, so guard on the live schema.++Revision ID: 032_shared_resources+Revises: 031_projects_environments+Create Date: 2026-06-23+"""+from alembic import op+import sqlalchemy as sa++revision = '032_shared_resources'+down_revision = '031_projects_environments'+branch_labels = None+depends_on = None+++def upgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ existing = set(inspector.get_table_names())++ if 'resource_tags' not in existing:+ op.create_table(+ 'resource_tags',+ sa.Column('id', sa.Integer, nullable=False),+ sa.Column('resource_type', sa.String(50), nullable=False),+ sa.Column('resource_id', sa.String(255), nullable=False),+ sa.Column('tag', sa.String(100), nullable=False),+ sa.Column('created_at', sa.DateTime, nullable=True),+ sa.PrimaryKeyConstraint('id'),+ sa.UniqueConstraint('resource_type', 'resource_id', 'tag', name='uq_resource_tag'),+ )+ op.create_index('ix_resource_tags_resource', 'resource_tags', ['resource_type', 'resource_id'])++ if 'shared_variable_groups' not in existing:+ op.create_table(+ 'shared_variable_groups',+ sa.Column('id', sa.Integer, nullable=False),+ sa.Column('scope_type', sa.String(50), nullable=False),+ sa.Column('scope_id', sa.String(255), nullable=False),+ sa.Column('name', sa.String(255), nullable=False),+ sa.Column('description', sa.String(500), nullable=True),+ sa.Column('created_at', sa.DateTime, nullable=True),+ sa.Column('updated_at', sa.DateTime, nullable=True),+ sa.PrimaryKeyConstraint('id'),+ )+ op.create_index('ix_shared_variable_groups_scope', 'shared_variable_groups', ['scope_type', 'scope_id'])++ if 'shared_variables' not in existing:+ op.create_table(+ 'shared_variables',+ sa.Column('id', sa.Integer, nullable=False),+ sa.Column('group_id', sa.Integer, nullable=False),+ sa.Column('key', sa.String(255), nullable=False),+ sa.Column('encrypted_value', sa.Text, nullable=False),+ sa.Column('is_secret', sa.Boolean, nullable=True),+ sa.Column('created_at', sa.DateTime, nullable=True),+ sa.PrimaryKeyConstraint('id'),+ sa.ForeignKeyConstraint(['group_id'], ['shared_variable_groups.id']),+ sa.UniqueConstraint('group_id', 'key', name='uq_shared_variable_group_key'),+ )++ if 'shared_variable_group_attachments' not in existing:+ op.create_table(+ 'shared_variable_group_attachments',+ sa.Column('id', sa.Integer, nullable=False),+ sa.Column('group_id', sa.Integer, nullable=False),+ sa.Column('resource_type', sa.String(50), nullable=False),+ sa.Column('resource_id', sa.String(255), nullable=False),+ sa.Column('created_at', sa.DateTime, nullable=True),+ sa.PrimaryKeyConstraint('id'),+ sa.ForeignKeyConstraint(['group_id'], ['shared_variable_groups.id']),+ sa.UniqueConstraint('group_id', 'resource_type', 'resource_id', name='uq_shared_variable_attachment'),+ )+ op.create_index(+ 'ix_shared_variable_group_attachments_resource',+ 'shared_variable_group_attachments', ['resource_type', 'resource_id'],+ )+++def downgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ existing = set(inspector.get_table_names())+ for tbl in ('shared_variable_group_attachments', 'shared_variables', 'shared_variable_groups', 'resource_tags'):+ if tbl in existing:+ op.drop_table(tbl)diff --git a/backend/migrations/versions/033_application_previews.py b/backend/migrations/versions/033_application_previews.pynew file mode 100644index 00000000..eeb34cd2--- /dev/null+++ b/backend/migrations/versions/033_application_previews.py@@ -0,0 +1,73 @@+"""PR preview environments.++Adds:+- application_previews (one row per PR preview)+- application_preview_settings (per-app enable + domain template + TTL)++Backs auto-deploying a PR branch to an isolated, disposable URL that is torn+down when the PR closes (apps and WordPress sites).++Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on boot+before Alembic, so guard on the live schema.++Revision ID: 033_application_previews+Revises: 032_shared_resources+Create Date: 2026-06-23+"""+from alembic import op+import sqlalchemy as sa++revision = '033_application_previews'+down_revision = '032_shared_resources'+branch_labels = None+depends_on = None+++def upgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ existing = set(inspector.get_table_names())++ if 'application_previews' not in existing:+ op.create_table(+ 'application_previews',+ sa.Column('id', sa.Integer, nullable=False),+ sa.Column('application_id', sa.Integer, nullable=False),+ sa.Column('pr_number', sa.Integer, nullable=True),+ sa.Column('pr_title', sa.String(500), nullable=True),+ sa.Column('branch', sa.String(255), nullable=True),+ sa.Column('status', sa.String(20), nullable=True),+ sa.Column('domain', sa.String(255), nullable=True),+ sa.Column('container_ids', sa.Text, nullable=True),+ sa.Column('commit_sha', sa.String(64), nullable=True),+ sa.Column('expires_at', sa.DateTime, nullable=True),+ sa.Column('created_at', sa.DateTime, nullable=True),+ sa.Column('updated_at', sa.DateTime, nullable=True),+ sa.Column('deleted_at', sa.DateTime, nullable=True),+ sa.PrimaryKeyConstraint('id'),+ sa.ForeignKeyConstraint(['application_id'], ['applications.id']),+ )+ op.create_index('ix_application_previews_application_id', 'application_previews', ['application_id'])++ if 'application_preview_settings' not in existing:+ op.create_table(+ 'application_preview_settings',+ sa.Column('application_id', sa.Integer, nullable=False),+ sa.Column('enabled', sa.Boolean, nullable=True),+ sa.Column('domain_template', sa.String(255), nullable=True),+ sa.Column('target_server_id', sa.String(36), nullable=True),+ sa.Column('ttl_days', sa.Integer, nullable=True),+ sa.Column('created_at', sa.DateTime, nullable=True),+ sa.Column('updated_at', sa.DateTime, nullable=True),+ sa.PrimaryKeyConstraint('application_id'),+ sa.ForeignKeyConstraint(['application_id'], ['applications.id']),+ )+++def downgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ existing = set(inspector.get_table_names())+ for tbl in ('application_preview_settings', 'application_previews'):+ if tbl in existing:+ op.drop_table(tbl)diff --git a/backend/migrations/versions/034_proxy_stacks.py b/backend/migrations/versions/034_proxy_stacks.pynew file mode 100644index 00000000..2f78554e--- /dev/null+++ b/backend/migrations/versions/034_proxy_stacks.py@@ -0,0 +1,53 @@+"""Per-server managed proxy stack.++Adds:+- proxy_stacks (one row per server; opt-in Traefik/Caddy compose stack, host+ Nginx stays the default)++Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on boot+before Alembic, so guard on the live schema.++Revision ID: 034_proxy_stacks+Revises: 033_application_previews+Create Date: 2026-06-23+"""+from alembic import op+import sqlalchemy as sa++revision = '034_proxy_stacks'+down_revision = '033_application_previews'+branch_labels = None+depends_on = None+++def upgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ existing = set(inspector.get_table_names())++ if 'proxy_stacks' not in existing:+ op.create_table(+ 'proxy_stacks',+ sa.Column('id', sa.String(36), nullable=False),+ sa.Column('server_id', sa.String(36), nullable=False),+ sa.Column('proxy_type', sa.String(20), nullable=False, server_default='nginx'),+ sa.Column('status', sa.String(20), nullable=False, server_default='unknown'),+ sa.Column('compose_path', sa.String(512), nullable=True),+ sa.Column('networks', sa.Text, nullable=True),+ sa.Column('custom_snippet', sa.Text, nullable=True),+ sa.Column('last_regenerated_at', sa.DateTime, nullable=True),+ sa.Column('created_at', sa.DateTime, nullable=True),+ sa.Column('updated_at', sa.DateTime, nullable=True),+ sa.PrimaryKeyConstraint('id'),+ sa.ForeignKeyConstraint(['server_id'], ['servers.id']),+ sa.UniqueConstraint('server_id', name='uq_proxy_stack_server'),+ )+ op.create_index('ix_proxy_stacks_server_id', 'proxy_stacks', ['server_id'])+++def downgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ existing = set(inspector.get_table_names())+ if 'proxy_stacks' in existing:+ op.drop_table('proxy_stacks')diff --git a/backend/tests/test_previews.py b/backend/tests/test_previews.pynew file mode 100644index 00000000..27cfdf3e--- /dev/null+++ b/backend/tests/test_previews.py@@ -0,0 +1,219 @@+"""Proving tests for PR Preview Environments.++Two testable cores are pure (no DB): domain templating and reconciliation.+The orchestration parts (settings upsert, create/destroy row writes, stale+expiry) use the ``app`` fixture for a clean DB and call service methods+directly — the job system is a no-op under ENV=testing.+"""+from datetime import datetime, timedelta++# Import the model at module load so its tables are registered on db.Model's+# metadata before the `app` fixture runs db.create_all(). In production the host+# imports it from models/__init__.py; here we import it directly.+from app.models.application_preview import ( # noqa: F401+ ApplicationPreview, ApplicationPreviewSettings)+from app.services.preview_service import PreviewService+++# ── render_domain (pure) ─────────────────────────────────────────────────────++def test_render_domain_pr_number_and_app_domain():+ out = PreviewService.render_domain(+ 'pr-{pr_number}.{app_domain}',+ {'pr_number': 42, 'app_domain': 'acme.com'})+ assert out == 'pr-42.acme.com'+++def test_render_domain_slugifies_branch():+ out = PreviewService.render_domain(+ '{branch}.{base_domain}',+ {'branch': 'feature/Login-Page', 'base_domain': 'Acme.COM'})+ # branch slugified, whole host lowercased+ assert out == 'feature-login-page.acme.com'+++def test_render_domain_base_domain_alias():+ # {app_domain} falls back to base_domain when app_domain is absent.+ out = PreviewService.render_domain(+ 'pr-{pr_number}.{app_domain}',+ {'pr_number': 7, 'base_domain': 'example.org'})+ assert out == 'pr-7.example.org'+++def test_render_domain_empty_template_and_unknown_placeholder():+ assert PreviewService.render_domain('', {'pr_number': 1}) == ''+ # Unknown placeholders are left intact rather than raising.+ out = PreviewService.render_domain('{nope}-{pr_number}', {'pr_number': 3})+ assert out == '{nope}-3'+++# ── reconcile (pure) ─────────────────────────────────────────────────────────++def test_reconcile_creates_for_open_pr_without_preview():+ plan = PreviewService.reconcile(+ open_prs=[{'pr_number': 1, 'commit_sha': 'aaa'}],+ active_previews=[])+ assert [p['pr_number'] for p in plan['to_create']] == [1]+ assert plan['to_update'] == [] and plan['to_destroy'] == []+++def test_reconcile_destroys_preview_for_closed_pr():+ preview = {'pr_number': 9, 'commit_sha': 'aaa', 'status': 'running'}+ plan = PreviewService.reconcile(open_prs=[], active_previews=[preview])+ assert plan['to_destroy'] == [preview]+ assert plan['to_create'] == [] and plan['to_update'] == []+++def test_reconcile_updates_on_new_commit():+ plan = PreviewService.reconcile(+ open_prs=[{'pr_number': 5, 'commit_sha': 'newsha'}],+ active_previews=[{'pr_number': 5, 'commit_sha': 'oldsha', 'status': 'running'}])+ assert [p['pr_number'] for p in plan['to_update']] == [5]+ assert plan['to_create'] == [] and plan['to_destroy'] == []+++def test_reconcile_noop_when_commit_unchanged():+ plan = PreviewService.reconcile(+ open_prs=[{'pr_number': 5, 'commit_sha': 'same'}],+ active_previews=[{'pr_number': 5, 'commit_sha': 'same', 'status': 'running'}])+ assert plan['to_create'] == [] and plan['to_update'] == [] and plan['to_destroy'] == []+++def test_reconcile_ignores_already_destroyed_previews():+ # A destroyed preview is not "live": its closed PR should NOT be re-destroyed.+ plan = PreviewService.reconcile(+ open_prs=[],+ active_previews=[{'pr_number': 2, 'commit_sha': 'x', 'status': 'destroyed'}])+ assert plan['to_destroy'] == []+++def test_reconcile_mixed_matrix():+ open_prs = [+ {'pr_number': 1, 'commit_sha': 'a'}, # new -> create+ {'pr_number': 2, 'commit_sha': 'b2'}, # moved -> update+ {'pr_number': 3, 'commit_sha': 'c'}, # unchanged -> noop+ ]+ active = [+ {'pr_number': 2, 'commit_sha': 'b1', 'status': 'running'},+ {'pr_number': 3, 'commit_sha': 'c', 'status': 'running'},+ {'pr_number': 4, 'commit_sha': 'd', 'status': 'running'}, # closed -> destroy+ ]+ plan = PreviewService.reconcile(open_prs, active)+ assert [p['pr_number'] for p in plan['to_create']] == [1]+ assert [p['pr_number'] for p in plan['to_update']] == [2]+ assert [p['pr_number'] for p in plan['to_destroy']] == [4]+++# ── DB-backed orchestration ──────────────────────────────────────────────────++def _mk_app(name='preview-app', app_type='docker', port=8400):+ from app import db+ from app.models import User, Application+ from werkzeug.security import generate_password_hash+ u = User(email=f'{name}@prev.local', username=f'prev-{name}',+ password_hash=generate_password_hash('x'),+ role=User.ROLE_ADMIN, is_active=True)+ db.session.add(u)+ db.session.commit()+ a = Application(name=name, app_type=app_type, user_id=u.id,+ root_path=f'/srv/{name}', port=port)+ db.session.add(a)+ db.session.commit()+ return a+++def test_enable_and_get_settings(app):+ with app.app_context():+ a = _mk_app()+ # Defaults before any save.+ s = PreviewService.get_settings(a.id)+ assert s.enabled is False+ assert s.domain_template == 'pr-{pr_number}.{app_domain}'++ result = PreviewService.enable_previews(a.id, {+ 'enabled': True,+ 'domain_template': 'preview-{pr_number}.{app_domain}',+ 'ttl_days': 3,+ })+ assert result['enabled'] is True+ assert result['domain_template'] == 'preview-{pr_number}.{app_domain}'+ assert result['ttl_days'] == 3++ # Re-fetch is persisted.+ again = PreviewService.get_settings(a.id)+ assert again.enabled is True+ assert again.ttl_days == 3+++def test_create_and_destroy_writes_rows_and_flips_status(app):+ from app.models.application_preview import ApplicationPreview+ with app.app_context():+ a = _mk_app(name='create-destroy')+ PreviewService.enable_previews(a.id, {'enabled': True})++ created = PreviewService.create_preview(a, {+ 'pr_number': 12, 'branch': 'feature/x', 'commit_sha': 'deadbeef',+ 'pr_title': 'Add X',+ })+ assert created.get('pr_number') == 12+ assert created.get('status') == ApplicationPreview.STATUS_RUNNING+ assert created.get('domain') # a domain was rendered++ row = ApplicationPreview.query.filter_by(application_id=a.id, pr_number=12).first()+ assert row is not None and row.status == ApplicationPreview.STATUS_RUNNING++ destroyed = PreviewService.destroy_preview(row.id)+ assert destroyed.get('status') == ApplicationPreview.STATUS_DESTROYED+ assert row.deleted_at is not None+++def test_create_preview_skips_when_disabled(app):+ with app.app_context():+ a = _mk_app(name='disabled-app')+ # No enable_previews call -> previews disabled.+ res = PreviewService.create_preview(a, {'pr_number': 1})+ assert res.get('skipped') is True+ assert res.get('reason') == 'previews_disabled'+++def test_expire_stale_destroys_past_due(app):+ from app import db+ from app.models.application_preview import ApplicationPreview+ with app.app_context():+ a = _mk_app(name='stale-app')+ # Stale preview (expired yesterday).+ stale = ApplicationPreview(+ application_id=a.id, pr_number=99, status=ApplicationPreview.STATUS_RUNNING,+ expires_at=datetime.utcnow() - timedelta(days=1))+ # Fresh preview (expires tomorrow) — must survive.+ fresh = ApplicationPreview(+ application_id=a.id, pr_number=100, status=ApplicationPreview.STATUS_RUNNING,+ expires_at=datetime.utcnow() + timedelta(days=1))+ db.session.add_all([stale, fresh])+ db.session.commit()++ out = PreviewService.expire_stale()+ assert out['expired'] == 1++ db.session.refresh(stale)+ db.session.refresh(fresh)+ assert stale.status == ApplicationPreview.STATUS_DESTROYED+ assert fresh.status == ApplicationPreview.STATUS_RUNNING+++def test_reconcile_against_db_rows(app):+ """reconcile accepts ORM rows (attribute access), not just dicts."""+ from app import db+ from app.models.application_preview import ApplicationPreview+ with app.app_context():+ a = _mk_app(name='orm-reconcile')+ live = ApplicationPreview(+ application_id=a.id, pr_number=7, commit_sha='old',+ status=ApplicationPreview.STATUS_RUNNING)+ db.session.add(live)+ db.session.commit()++ plan = PreviewService.reconcile(+ open_prs=[{'pr_number': 7, 'commit_sha': 'new'}],+ active_previews=[live])+ assert [p['pr_number'] for p in plan['to_update']] == [7]diff --git a/backend/tests/test_projects.py b/backend/tests/test_projects.pynew file mode 100644index 00000000..0a04d267--- /dev/null+++ b/backend/tests/test_projects.py@@ -0,0 +1,181 @@+"""Tests for the Project / Environment hierarchy.++These import the Project/Environment models at module scope so they're registered+on db.Model's metadata before the `app` fixture runs db.create_all() (the global+models/__init__ wiring is added separately; the suite must not depend on it).+"""+import pytest++# Registering the new models on the metadata so create_all() builds their tables.+from app.models.project import Project # noqa: F401+from app.models.environment import Environment # noqa: F401+from app.models.application import Application+++def workspace(app):+ """A workspace to scope projects under."""+ from app import db+ from app.services.workspace_service import WorkspaceService+ with app.app_context():+ ws = WorkspaceService.ensure_default_workspace()+ return ws.id+++def _make_app(name, workspace_id, project_id=None, environment_id=None):+ from app import db+ from app.models.user import User+ from werkzeug.security import generate_password_hash+ # An owner user (apps require a non-null user_id).+ user = User.query.filter_by(username='appowner').first()+ if user is None:+ user = User(+ email='[email protected]',+ username='appowner',+ password_hash=generate_password_hash('x'),+ role='admin',+ is_active=True,+ )+ db.session.add(user)+ db.session.commit()+ a = Application(+ name=name,+ app_type='docker',+ status='stopped',+ user_id=user.id,+ workspace_id=workspace_id,+ project_id=project_id,+ environment_id=environment_id,+ )+ db.session.add(a)+ db.session.commit()+ return a+++def test_create_project_auto_creates_default_env(app, workspace):+ from app.services.project_service import ProjectService+ with app.app_context():+ project = ProjectService.create_project(workspace, name='My Project')+ envs = ProjectService.list_environments(project.id)+ assert len(envs) == 1+ assert envs[0].is_default is True+ assert envs[0].slug == 'production'+ assert project.slug == 'my-project'+++def test_ensure_default_is_idempotent(app, workspace):+ from app.services.project_service import ProjectService+ with app.app_context():+ p1 = ProjectService.ensure_default(workspace)+ p2 = ProjectService.ensure_default(workspace)+ assert p1.id == p2.id+ # Still exactly one Default project for the workspace.+ defaults = Project.query.filter_by(workspace_id=workspace, slug='default').all()+ assert len(defaults) == 1+ # And it carries its default environment.+ assert p1.environments.count() == 1+++def test_list_and_assign_apps_to_project_and_env(app, workspace):+ from app.services.project_service import ProjectService+ with app.app_context():+ project = ProjectService.create_project(workspace, name='Assignable')+ env = ProjectService.list_environments(project.id)[0]++ a = _make_app('app-one', workspace, project_id=project.id, environment_id=env.id)++ proj_apps = ProjectService.list_project_apps(project.id)+ assert [x.id for x in proj_apps] == [a.id]++ env_apps = ProjectService.list_environment_apps(env.id)+ assert [x.id for x in env_apps] == [a.id]++ # Counts surface in to_dict.+ d = project.to_dict(include_counts=True)+ assert d['app_count'] == 1+ assert d['environment_count'] == 1+++def test_delete_project_refuses_when_non_empty(app, workspace):+ from app.services.project_service import ProjectService+ with app.app_context():+ project = ProjectService.create_project(workspace, name='Busy')+ env = ProjectService.list_environments(project.id)[0]+ _make_app('busy-app', workspace, project_id=project.id, environment_id=env.id)++ result = ProjectService.delete_project(project.id)+ assert result == 'has_apps'+ # Still present.+ assert ProjectService.get_project(project.id) is not None++ # Empty project deletes cleanly.+ empty = ProjectService.create_project(workspace, name='Empty')+ assert ProjectService.delete_project(empty.id) is True+ assert ProjectService.get_project(empty.id) is None+++def test_environment_create_reorder_and_default_guard(app, workspace):+ from app.services.project_service import ProjectService+ with app.app_context():+ project = ProjectService.create_project(workspace, name='Envs')+ prod = ProjectService.list_environments(project.id)[0]++ from app import db+ staging = ProjectService.create_environment(project.id, name='staging')+ dev = ProjectService.create_environment(project.id, name='development')+ db.session.commit()++ # Three environments, prod first by order.+ envs = ProjectService.list_environments(project.id)+ assert [e.slug for e in envs] == ['production', 'staging', 'development']++ # Reorder: development, production, staging.+ reordered = ProjectService.reorder_environments(+ project.id, [dev.id, prod.id, staging.id])+ assert [e.slug for e in reordered] == ['development', 'production', 'staging']++ # Deleting a non-last environment succeeds.+ assert ProjectService.delete_environment(staging.id) is True+ remaining = ProjectService.list_environments(project.id)+ assert len(remaining) == 2++ # Deleting down to the last one is refused.+ assert ProjectService.delete_environment(dev.id) is True+ assert ProjectService.delete_environment(prod.id) == 'last'+ assert len(ProjectService.list_environments(project.id)) == 1+++def test_delete_default_env_promotes_another(app, workspace):+ from app.services.project_service import ProjectService+ from app import db+ with app.app_context():+ project = ProjectService.create_project(workspace, name='Promote')+ prod = ProjectService.list_environments(project.id)[0]+ staging = ProjectService.create_environment(project.id, name='staging')+ db.session.commit()++ assert prod.is_default is True+ # Delete the default -> the remaining env should be promoted to default.+ assert ProjectService.delete_environment(prod.id) is True+ remaining = ProjectService.list_environments(project.id)+ assert len(remaining) == 1+ assert remaining[0].id == staging.id+ assert remaining[0].is_default is True+++def test_delete_environment_detaches_apps(app, workspace):+ from app.services.project_service import ProjectService+ from app import db+ with app.app_context():+ project = ProjectService.create_project(workspace, name='Detach')+ prod = ProjectService.list_environments(project.id)[0]+ staging = ProjectService.create_environment(project.id, name='staging')+ db.session.commit()++ a = _make_app('detach-app', workspace, project_id=project.id, environment_id=staging.id)+ assert ProjectService.delete_environment(staging.id) is True++ db.session.refresh(a)+ # App keeps its project but loses the deleted environment.+ assert a.project_id == project.id+ assert a.environment_id is Nonediff --git a/backend/tests/test_proxy_stack.py b/backend/tests/test_proxy_stack.pynew file mode 100644index 00000000..72304b78--- /dev/null+++ b/backend/tests/test_proxy_stack.py@@ -0,0 +1,230 @@+"""ProxyStackService tests.++The pure generators (``generate_compose`` / ``generate_config`` / hashing) are+exercised with no app context or Docker — they assert the *rendered* compose &+config, the same style as test_nginx_remote_upstream / test_fail2ban_jail.+The row-management tests use the ``app`` fixture for a clean DB and import the+ProxyStack model directly.+"""+import yaml+import pytest++from app.services.proxy_stack_service import ProxyStackService as PS+# Import the model at module top so it's registered on db.metadata before the+# `app` fixture runs db.create_all() (the service only imports it lazily).+from app.models.proxy_stack import ProxyStack # noqa: F401+++# ---------------------------------------------------------------------------+# Pure: generate_compose+# ---------------------------------------------------------------------------++def test_compose_nginx_is_none():+ assert PS.generate_compose('srv-1234abcd', 'nginx', {}) is None+++def test_compose_traefik_is_valid_yaml_with_expected_bits():+ raw = PS.generate_compose('srv-1234abcd', 'traefik', {})+ assert raw is not None+ doc = yaml.safe_load(raw) # parseable++ svc = doc['services']['proxy']+ assert svc['image'] == PS.TRAEFIK_IMAGE+ assert 'traefik' in svc['image']+ # Ports 80/443 published+ assert '80:80' in svc['ports']+ assert '443:443' in svc['ports']+ # External serverkit network present + flagged external+ assert PS.NETWORK_NAME in svc['networks']+ assert doc['networks'][PS.NETWORK_NAME]['external'] is True+ # Docker provider labels/command wired+ assert any('providers.docker' in c for c in svc['command'])+++def test_compose_caddy_is_valid_yaml_with_expected_bits():+ raw = PS.generate_compose('srv-1234abcd', 'caddy', {})+ assert raw is not None+ doc = yaml.safe_load(raw)++ svc = doc['services']['proxy']+ assert svc['image'] == PS.CADDY_IMAGE+ assert 'caddy' in svc['image']+ assert '80:80' in svc['ports']+ assert '443:443' in svc['ports']+ assert PS.NETWORK_NAME in svc['networks']+ assert doc['networks'][PS.NETWORK_NAME]['external'] is True+ # Caddy persists certs/config in named volumes+ assert 'caddy_data' in doc['volumes']+++def test_compose_traefik_acme_optional():+ raw = PS.generate_compose('srv-x', 'traefik', {'acme_email': '[email protected]'})+ doc = yaml.safe_load(raw)+ cmd = doc['services']['proxy']['command']+ assert any('[email protected]' in c for c in cmd)+++def test_compose_caddy_acme_optional():+ raw = PS.generate_compose('srv-x', 'caddy', {'acme_email': '[email protected]'})+ doc = yaml.safe_load(raw)+ env = doc['services']['proxy']['environment']+ assert env['CADDY_EMAIL'] == '[email protected]'+++def test_compose_unknown_type_raises():+ with pytest.raises(ValueError):+ PS.generate_compose('srv-x', 'haproxy', {})+++# ---------------------------------------------------------------------------+# Pure: generate_config+# ---------------------------------------------------------------------------++SITES = [+ {'domain': 'a.example.com', 'upstream': 'app1:8001', 'tls': True},+ {'domain': 'b.example.com', 'upstream': 'app2:8002'},+]+++def test_config_nginx_is_none():+ assert PS.generate_config('nginx', SITES) is None+++def test_config_traefik_dynamic_routes_and_services():+ raw = PS.generate_config('traefik', SITES)+ doc = yaml.safe_load(raw)+ routers = doc['http']['routers']+ services = doc['http']['services']+ # One router + service per site+ assert len(routers) == 2+ assert len(services) == 2+ # Host rule + upstream url rendered+ rules = [r['rule'] for r in routers.values()]+ assert 'Host(`a.example.com`)' in rules+ urls = [s['loadBalancer']['servers'][0]['url'] for s in services.values()]+ assert 'http://app1:8001' in urls+++def test_config_traefik_tls_uses_cert_resolver():+ raw = PS.generate_config('traefik', SITES)+ doc = yaml.safe_load(raw)+ tls_routers = [r for r in doc['http']['routers'].values() if 'tls' in r]+ assert tls_routers+ assert tls_routers[0]['tls']['certResolver'] == 'serverkit'+++def test_config_caddyfile_blocks():+ raw = PS.generate_config('caddy', SITES)+ assert 'a.example.com {' in raw+ assert 'reverse_proxy app1:8001' in raw+ assert 'b.example.com {' in raw+++def test_config_custom_snippet_appended():+ snippet = 'log { output stdout }'+ raw = PS.generate_config('caddy', SITES, custom_snippet=snippet)+ assert snippet in raw+++# ---------------------------------------------------------------------------+# Pure: hashing / backup naming determinism+# ---------------------------------------------------------------------------++def test_config_hash_is_deterministic():+ content = "services:\n proxy:\n image: traefik\n"+ h1 = PS.config_hash(content)+ h2 = PS.config_hash(content)+ assert h1 == h2+ assert len(h1) == 8+ # Different content → different hash+ assert PS.config_hash(content + 'x') != h1+++def test_backup_config_roundtrip(tmp_path, monkeypatch):+ """backup_config copies the live compose to a hash-named backup."""+ server_id = 'srv-backup01'+ stack_dir = tmp_path / 'proxy' / server_id+ stack_dir.mkdir(parents=True)+ compose_content = "services:\n proxy:\n image: caddy\n"+ (stack_dir / 'docker-compose.yml').write_text(compose_content)++ monkeypatch.setattr(PS, '_stack_dir', staticmethod(lambda sid: str(stack_dir)))++ backup_path = PS.backup_config(server_id)+ assert backup_path is not None+ # Backup filename carries the deterministic 8-char hash.+ digest = PS.config_hash(compose_content)+ assert digest in backup_path+ assert backup_path.endswith('.yml')+ with open(backup_path, encoding='utf-8') as f:+ assert f.read() == compose_content+++def test_backup_config_missing_is_none(tmp_path, monkeypatch):+ monkeypatch.setattr(+ PS, '_stack_dir', staticmethod(lambda sid: str(tmp_path / 'nope'))+ )+ assert PS.backup_config('srv-none') is None+++# ---------------------------------------------------------------------------+# DB-backed: get_or_create / configure / switch+# ---------------------------------------------------------------------------++def _make_server(app):+ from app import db+ from app.models.server import Server+ s = Server(name='proxy-host', agent_id='agent-proxy-1')+ db.session.add(s)+ db.session.commit()+ return s.id+++def test_get_or_create_defaults_to_nginx(app):+ from app.models.proxy_stack import ProxyStack+ with app.app_context():+ sid = _make_server(app)+ stack = PS.get_or_create(sid)+ assert stack.proxy_type == 'nginx'+ assert stack.server_id == sid+ # Idempotent: no duplicate rows.+ again = PS.get_or_create(sid)+ assert again.id == stack.id+ assert ProxyStack.query.filter_by(server_id=sid).count() == 1+++def test_configure_sets_snippet_and_path(app):+ with app.app_context():+ sid = _make_server(app)+ stack = PS.configure(sid, proxy_type='traefik', custom_snippet='# hi')+ assert stack.proxy_type == 'traefik'+ assert stack.custom_snippet == '# hi'+ assert stack.compose_path and stack.compose_path.endswith('docker-compose.yml')+++def test_switch_flips_rows(app):+ with app.app_context():+ sid = _make_server(app)+ PS.get_or_create(sid)+ s1 = PS.switch(sid, 'caddy')+ assert s1.proxy_type == 'caddy'+ assert s1.compose_path is not None+ # Switching back to nginx clears the compose path.+ s2 = PS.switch(sid, 'nginx')+ assert s2.proxy_type == 'nginx'+ assert s2.compose_path is None+++def test_configure_rejects_unknown_type(app):+ with app.app_context():+ sid = _make_server(app)+ with pytest.raises(ValueError):+ PS.configure(sid, proxy_type='haproxy')+++def test_create_app_testing_still_works():+ """Sanity: the app factory + our model import cleanly."""+ from app import create_app+ from app.models.proxy_stack import ProxyStack # noqa: F401+ app = create_app('testing')+ assert app is not Nonediff --git a/backend/tests/test_shared_resources.py b/backend/tests/test_shared_resources.pynew file mode 100644index 00000000..fbb204a2--- /dev/null+++ b/backend/tests/test_shared_resources.py@@ -0,0 +1,242 @@+"""Tests for the polymorphic shared-resources facade (tags + variable groups).++Covers the service layer directly (encryption-at-rest, masking, merge rule,+idempotency) plus a couple of API round-trips for the JWT-protected blueprint.+"""+import pytest++# Import our own models at collection time so their tables are in the+# SQLAlchemy metadata before the first `app` fixture runs `db.create_all()`+# (the service that pulls them in is otherwise imported lazily inside each test+# body, i.e. AFTER create_all). The panel wires these via `models/__init__.py`.+import app.models.shared_resource # noqa: F401,E402++# A concurrent, in-flight slice adds `applications.environment_id` (FK →+# `environments`) but has not yet wired its models into `models/__init__.py`.+# Until it does, `db.create_all()` cannot resolve that FK and the whole suite's+# schema build fails. We best-effort import those sibling models at collection+# time (before any `app` fixture runs `create_all`) so their tables join the+# SQLAlchemy metadata. This edits no application code and becomes a harmless+# no-op once the sibling slice wires its own imports.+try: # pragma: no cover - depends on sibling slice presence+ import app.models.project # noqa: F401+ import app.models.environment # noqa: F401+except Exception:+ pass++[email protected](autouse=True)+def _register_blueprint(app):+ """Mount the shared-resources blueprint for every test in this module.++ The panel wires ``shared_resources_bp`` at ``/api/v1/shared`` in+ ``app/__init__.py``; until that lands we register it here (idempotently) so+ the API round-trip tests exercise the real routes without editing+ application code. Service-layer tests are unaffected.+ """+ if 'shared_resources' not in app.blueprints:+ from app.api.shared_resources import shared_resources_bp+ app.register_blueprint(shared_resources_bp, url_prefix='/api/v1/shared')+ return app+++# --------------------------------------------------------------------- tags++def test_tag_add_remove_list(app):+ from app.services.shared_resource_service import SharedResourceService as S++ S.add_tag('application', 1, 'prod')+ S.add_tag('application', 1, 'critical')+ tags = S.list_tags('application', 1)+ assert {t.tag for t in tags} == {'prod', 'critical'}++ assert S.remove_tag('application', 1, 'prod') is True+ assert {t.tag for t in S.list_tags('application', 1)} == {'critical'}+ # Removing a missing tag is a no-op (False), not an error.+ assert S.remove_tag('application', 1, 'prod') is False+++def test_tag_is_idempotent(app):+ from app.services.shared_resource_service import SharedResourceService as S+ from app.models.shared_resource import ResourceTag++ S.add_tag('server', 5, 'edge')+ S.add_tag('server', 5, 'edge') # duplicate — must NOT create a second row+ assert ResourceTag.query.filter_by(+ resource_type='server', resource_id='5', tag='edge').count() == 1+++def test_list_resources_by_tag_across_types(app):+ from app.services.shared_resource_service import SharedResourceService as S++ S.add_tag('application', 1, 'team-a')+ S.add_tag('database', 9, 'team-a')+ S.add_tag('service', 'redis-cache', 'team-b')++ rows = S.list_resources_by_tag('team-a')+ assert {(r.resource_type, r.resource_id) for r in rows} == {+ ('application', '1'), ('database', '9')+ }+ # resource_id stored as string supports non-int handles too.+ rows_b = S.list_resources_by_tag('team-b')+ assert (rows_b[0].resource_type, rows_b[0].resource_id) == ('service', 'redis-cache')+++# ------------------------------------------------------------------- groups++def test_group_create_and_secret_encrypted_at_rest(app):+ from app.services.shared_resource_service import SharedResourceService as S+ from app.models.shared_resource import SharedVariable++ group = S.create_group('workspace', 'ws-1', 'Shared DB Creds', 'common db config')+ S.set_variable(group.id, 'DB_HOST', 'db.internal', is_secret=False)+ S.set_variable(group.id, 'DB_PASSWORD', 'super-secret-pw', is_secret=True)++ # Secret is encrypted at rest — the raw column never holds the plaintext.+ row = SharedVariable.query.filter_by(group_id=group.id, key='DB_PASSWORD').first()+ assert row.encrypted_value != 'super-secret-pw'+ assert 'super-secret-pw' not in row.encrypted_value+ # ...but decrypts back via the value property.+ assert row.value == 'super-secret-pw'++ # to_dict masks secrets but reveals non-secrets.+ secret_dict = row.to_dict(mask_secrets=True)+ assert secret_dict['value'] == '••••••••'+ host = SharedVariable.query.filter_by(group_id=group.id, key='DB_HOST').first()+ assert host.to_dict(mask_secrets=True)['value'] == 'db.internal'+ # Unmasked reveal works when explicitly asked.+ assert row.to_dict(mask_secrets=False)['value'] == 'super-secret-pw'+++def test_set_variable_upserts_by_key(app):+ from app.services.shared_resource_service import SharedResourceService as S++ group = S.create_group('project', 'proj-1', 'App Config')+ S.set_variable(group.id, 'LOG_LEVEL', 'info')+ S.set_variable(group.id, 'LOG_LEVEL', 'debug') # same key → update, not insert+ vars_ = S.list_variables(group.id)+ assert len(vars_) == 1+ assert vars_[0].value == 'debug'+++# -------------------------------------------------- attach + resolve / merge++def test_attach_to_two_resource_types_and_idempotent(app):+ from app.services.shared_resource_service import SharedResourceService as S+ from app.models.shared_resource import SharedVariableGroupAttachment++ group = S.create_group('workspace', 'ws-1', 'Common')+ S.attach_group(group.id, 'application', 1)+ S.attach_group(group.id, 'database', 7)+ # Duplicate attachment is idempotent.+ S.attach_group(group.id, 'application', 1)++ assert SharedVariableGroupAttachment.query.filter_by(group_id=group.id).count() == 2++ app_groups = S.list_attached_groups('application', 1)+ db_groups = S.list_attached_groups('database', 7)+ assert [g.id for g in app_groups] == [group.id]+ assert [g.id for g in db_groups] == [group.id]+++def test_resolve_merges_and_masks_with_last_attachment_wins(app):+ from app.services.shared_resource_service import SharedResourceService as S++ base = S.create_group('workspace', 'ws-1', 'Base')+ S.set_variable(base.id, 'REGION', 'us-east', is_secret=False)+ S.set_variable(base.id, 'TOKEN', 'base-token', is_secret=True)++ override = S.create_group('environment', 'prod', 'Prod Override')+ S.set_variable(override.id, 'REGION', 'eu-west', is_secret=False) # collides+ S.set_variable(override.id, 'EXTRA', 'yes', is_secret=False)++ # Attach base first, override second → override wins on REGION.+ S.attach_group(base.id, 'service', 'web-1')+ S.attach_group(override.id, 'service', 'web-1')++ resolved = S.resolve_variables('service', 'web-1', mask_secrets=True)+ by_key = {v['key']: v for v in resolved}++ assert by_key['REGION']['value'] == 'eu-west' # last attachment wins+ assert by_key['REGION']['group_name'] == 'Prod Override'+ assert by_key['EXTRA']['value'] == 'yes'+ assert by_key['TOKEN']['value'] == '••••••••' # secret masked+ assert by_key['TOKEN']['is_secret'] is True++ # Unmasked resolution reveals the secret.+ revealed = S.resolve_variables('service', 'web-1', mask_secrets=False)+ assert {v['key']: v['value'] for v in revealed}['TOKEN'] == 'base-token'+++def test_delete_group_cascades(app):+ from app.services.shared_resource_service import SharedResourceService as S+ from app.models.shared_resource import SharedVariable, SharedVariableGroupAttachment++ group = S.create_group('workspace', 'ws-1', 'Temp')+ S.set_variable(group.id, 'K', 'v')+ S.attach_group(group.id, 'application', 1)+ gid = group.id++ assert S.delete_group(gid) is True+ assert SharedVariable.query.filter_by(group_id=gid).count() == 0+ assert SharedVariableGroupAttachment.query.filter_by(group_id=gid).count() == 0+++# ----------------------------------------------------------------- API layer++def auth(app):+ """Admin JWT headers (blueprint mounted by the autouse fixture)."""+ from app import db+ from app.models import User+ from flask_jwt_extended import create_access_token+ from werkzeug.security import generate_password_hash++ user = User(email='[email protected]', username='sruser',+ password_hash=generate_password_hash('x'),+ role=User.ROLE_ADMIN, is_active=True)+ db.session.add(user)+ db.session.commit()+ return {'Authorization': f'Bearer {create_access_token(identity=user.id)}'}+++def test_api_tag_and_resolve_roundtrip(app, client, auth):+ # Add a tag via the API.+ r = client.post('/api/v1/shared/tags',+ json={'resource_type': 'application', 'resource_id': 42, 'tag': 'prod'},+ headers=auth)+ assert r.status_code == 201++ r = client.get('/api/v1/shared/tags?resource_type=application&resource_id=42',+ headers=auth)+ assert r.status_code == 200+ assert {t['tag'] for t in r.get_json()['tags']} == {'prod'}++ # Create a group, add a secret, attach, then resolve — secret stays masked.+ r = client.post('/api/v1/shared/variable-groups',+ json={'scope_type': 'workspace', 'scope_id': 'ws-1', 'name': 'G'},+ headers=auth)+ assert r.status_code == 201+ gid = r.get_json()['id']++ r = client.post(f'/api/v1/shared/variable-groups/{gid}/variables',+ json={'key': 'API_TOKEN', 'value': 'tok-123', 'is_secret': True},+ headers=auth)+ assert r.status_code == 201+ assert r.get_json()['value'] == '••••••••'++ r = client.post(f'/api/v1/shared/variable-groups/{gid}/attach',+ json={'resource_type': 'application', 'resource_id': 42},+ headers=auth)+ assert r.status_code == 201++ r = client.get('/api/v1/shared/resolved?resource_type=application&resource_id=42',+ headers=auth)+ assert r.status_code == 200+ body = r.get_json()+ by_key = {v['key']: v for v in body['variables']}+ assert by_key['API_TOKEN']['value'] == '••••••••'+++def test_api_requires_auth(app, client):+ assert client.get('/api/v1/shared/variable-groups').status_code == 401diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex c584016f..6aaa5569 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -59,6 +59,9 @@ import ServerTemplates from './pages/ServerTemplates';import RemoteAccess from './pages/RemoteAccess';import Workspaces from './pages/Workspaces';import WorkspaceDetail from './pages/WorkspaceDetail';+import Projects from './pages/Projects';+import ProjectDetail from './pages/ProjectDetail';+import SharedVariables from './pages/SharedVariables';import CloudflareZoneSettings from './pages/CloudflareZoneSettings';import StatusPages from './pages/StatusPages';import PublicStatusPage from './pages/PublicStatusPage';@@ -87,6 +90,8 @@ const PAGE_TITLES = {'/setup': 'Setup','/services': 'Services','/services/new': 'New Service',+ '/projects': 'Projects',+ '/shared-variables': 'Shared Variables','/apps': 'Applications','/wordpress': 'WordPress Sites','/wordpress/projects': 'WordPress Projects',@@ -354,6 +359,10 @@ function AppRoutes() {<Route path="servers/:id" element={<ServerDetail />} /><Route path="servers/:id/:tab" element={<ServerDetail />} /><Route path="agent-plugins" element={<Navigate to="/marketplace" replace />} />+ <Route path="projects" element={<Projects />} />+ <Route path="projects/:id" element={<ProjectDetail />} />+ <Route path="projects/:id/:tab" element={<ProjectDetail />} />+ <Route path="shared-variables" element={<SharedVariables />} /><Route path="workspaces" element={<Workspaces />} /><Route path="workspaces/:id" element={<WorkspaceDetail />} /><Route path="workspaces/:id/:tab" element={<WorkspaceDetail />} />diff --git a/frontend/src/components/previews/PreviewList.jsx b/frontend/src/components/previews/PreviewList.jsxnew file mode 100644index 00000000..2f1ee5d2--- /dev/null+++ b/frontend/src/components/previews/PreviewList.jsx@@ -0,0 +1,273 @@+import { useState, useEffect, useCallback } from 'react';+import {+ GitPullRequest, ExternalLink, RefreshCw, Trash2, RotateCcw,+} from 'lucide-react';+import api from '../../services/api';+import { useToast } from '../../contexts/ToastContext';+import { useConfirm } from '../../hooks/useConfirm';+import { ConfirmDialog } from '../ConfirmDialog';+import EmptyState from '../EmptyState';+import { Pill } from '../ds';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { Switch } from '@/components/ui/switch';++// Preview status → ds Pill kind.+const STATUS_PILL = {+ running: 'green',+ building: 'amber',+ queued: 'amber',+ stopped: 'gray',+ failed: 'red',+ destroyed: 'gray',+};++const DEFAULT_TEMPLATE = 'pr-{pr_number}.{app_domain}';++const PreviewList = ({ appId }) => {+ const toast = useToast();+ const { confirm, confirmState, handleConfirm, handleCancel } = useConfirm();++ const [previews, setPreviews] = useState([]);+ const [settings, setSettings] = useState(null);+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [syncing, setSyncing] = useState(false);+ const [busyId, setBusyId] = useState(null);+ const [template, setTemplate] = useState(DEFAULT_TEMPLATE);++ const load = useCallback(async () => {+ try {+ const [list, conf] = await Promise.all([+ api.getPreviews(appId),+ api.getPreviewSettings(appId),+ ]);+ setPreviews(list?.previews || []);+ setSettings(conf || null);+ setTemplate(conf?.domain_template || DEFAULT_TEMPLATE);+ } catch (err) {+ console.error('Failed to load previews:', err);+ toast?.error?.('Could not load PR previews');+ } finally {+ setLoading(false);+ }+ }, [appId, toast]);++ useEffect(() => { load(); }, [load]);++ async function saveSettings(patch) {+ setSaving(true);+ try {+ const updated = await api.updatePreviewSettings(appId, patch);+ setSettings(updated);+ setTemplate(updated?.domain_template || DEFAULT_TEMPLATE);+ toast?.success?.('Preview settings saved');+ } catch (err) {+ console.error('Failed to save preview settings:', err);+ toast?.error?.(err.message || 'Could not save settings');+ } finally {+ setSaving(false);+ }+ }++ async function handleToggle(enabled) {+ await saveSettings({ enabled });+ }++ async function handleSaveTemplate() {+ await saveSettings({ domain_template: template || DEFAULT_TEMPLATE });+ }++ async function handleSync() {+ setSyncing(true);+ try {+ await api.syncPreviews(appId);+ toast?.success?.('Reconciled previews against open PRs');+ await load();+ } catch (err) {+ toast?.error?.(err.message || 'Sync failed');+ } finally {+ setSyncing(false);+ }+ }++ async function handleRedeploy(preview) {+ setBusyId(preview.id);+ try {+ await api.redeployPreview(appId, preview.id);+ toast?.success?.(`Redeploying preview for PR #${preview.pr_number}`);+ await load();+ } catch (err) {+ toast?.error?.(err.message || 'Redeploy failed');+ } finally {+ setBusyId(null);+ }+ }++ async function handleDestroy(preview) {+ const ok = await confirm({+ title: 'Destroy preview',+ message: `Tear down the preview environment for PR #${preview.pr_number}? This removes its temporary domain and resources.`,+ confirmText: 'Destroy',+ variant: 'danger',+ });+ if (!ok) return;+ setBusyId(preview.id);+ try {+ await api.destroyPreview(appId, preview.id);+ toast?.success?.(`Preview for PR #${preview.pr_number} destroyed`);+ await load();+ } catch (err) {+ toast?.error?.(err.message || 'Destroy failed');+ } finally {+ setBusyId(null);+ }+ }++ if (loading) {+ return <EmptyState loading title="Loading previews..." />;+ }++ const enabled = !!settings?.enabled;++ return (+ <div className="preview-list">+ {/* Enable / configure card */}+ <div className="preview-settings">+ <div className="preview-settings__header">+ <div className="preview-settings__title">+ <GitPullRequest size={18} />+ <div>+ <h3>PR preview environments</h3>+ <p className="preview-settings__hint">+ Deploy an isolated preview of each open pull request to a+ temporary domain, and tear it down when the PR closes.+ </p>+ </div>+ </div>+ <div className="preview-settings__toggle">+ <Label htmlFor="preview-enabled">{enabled ? 'Enabled' : 'Disabled'}</Label>+ <Switch+ id="preview-enabled"+ checked={enabled}+ disabled={saving}+ onCheckedChange={handleToggle}+ />+ </div>+ </div>++ {enabled && (+ <div className="preview-settings__template">+ <Label htmlFor="preview-template">Domain template</Label>+ <div className="preview-settings__template-row">+ <Input+ id="preview-template"+ value={template}+ onChange={(e) => setTemplate(e.target.value)}+ placeholder={DEFAULT_TEMPLATE}+ spellCheck={false}+ />+ <Button+ variant="outline"+ onClick={handleSaveTemplate}+ disabled={saving || template === settings?.domain_template}+ >+ Save+ </Button>+ </div>+ <p className="preview-settings__hint">+ Placeholders: <code>{'{pr_number}'}</code>, <code>{'{branch}'}</code>,{' '}+ <code>{'{app_domain}'}</code>.+ </p>+ </div>+ )}+ </div>++ {/* Active previews */}+ <div className="preview-list__toolbar">+ <h4>Active previews</h4>+ <Button variant="ghost" onClick={handleSync} disabled={syncing}>+ <RefreshCw size={15} className={syncing ? 'spin' : undefined} />+ Sync with open PRs+ </Button>+ </div>++ {previews.length === 0 ? (+ <EmptyState+ icon={GitPullRequest}+ title="No active previews"+ description={+ enabled+ ? 'Open a pull request to spin up a preview, or sync to reconcile now.'+ : 'Enable PR previews above to start deploying preview environments.'+ }+ />+ ) : (+ <ul className="preview-list__items">+ {previews.map((p) => (+ <li key={p.id} className="preview-item">+ <div className="preview-item__main">+ <div className="preview-item__title">+ <span className="preview-item__pr">PR #{p.pr_number}</span>+ <span className="preview-item__name">{p.pr_title || '(untitled)'}</span>+ <Pill kind={STATUS_PILL[p.status] || 'gray'}>{p.status}</Pill>+ </div>+ <div className="preview-item__meta">+ {p.branch && <span className="preview-item__branch mono">{p.branch}</span>}+ {p.short_sha && <span className="preview-item__sha mono">{p.short_sha}</span>}+ {p.url && (+ <a+ className="preview-item__url"+ href={p.url}+ target="_blank"+ rel="noopener noreferrer"+ >+ {p.domain}+ </a>+ )}+ </div>+ </div>+ <div className="preview-item__actions">+ {p.url && (+ <Button variant="ghost" size="sm" asChild>+ <a href={p.url} target="_blank" rel="noopener noreferrer">+ <ExternalLink size={15} />+ Open+ </a>+ </Button>+ )}+ <Button+ variant="ghost"+ size="sm"+ onClick={() => handleRedeploy(p)}+ disabled={busyId === p.id}+ >+ <RotateCcw size={15} />+ Redeploy+ </Button>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => handleDestroy(p)}+ disabled={busyId === p.id}+ >+ <Trash2 size={15} />+ Destroy+ </Button>+ </div>+ </li>+ ))}+ </ul>+ )}++ <ConfirmDialog+ {...confirmState}+ onConfirm={handleConfirm}+ onCancel={handleCancel}+ />+ </div>+ );+};++export default PreviewList;diff --git a/frontend/src/components/proxy/ProxyStackPanel.jsx b/frontend/src/components/proxy/ProxyStackPanel.jsxnew file mode 100644index 00000000..a34cfd74--- /dev/null+++ b/frontend/src/components/proxy/ProxyStackPanel.jsx@@ -0,0 +1,250 @@+import React, { useState, useEffect, useCallback } from 'react';+import api from '../../services/api';+import { useToast } from '../../contexts/ToastContext';+import { Button } from '@/components/ui/button';+import { Textarea } from '@/components/ui/textarea';+import { Pill, SegControl } from '../ds';+import EmptyState from '../EmptyState';+import { Network } from 'lucide-react';++// Managed reverse-proxy stack panel for a server.+//+// Host nginx is the default (and the better choice for PHP/WordPress). This+// panel lets an operator opt into a Dockerized proxy — Traefik or Caddy —+// deployed as a Compose stack, preview the generated compose, edit a custom+// config snippet, and (best-effort) regenerate / restart the stack.++const PROXY_OPTIONS = [+ { value: 'nginx', label: 'Nginx', sub: 'Host default' },+ { value: 'traefik', label: 'Traefik', sub: 'Docker stack' },+ { value: 'caddy', label: 'Caddy', sub: 'Docker stack' },+];++const STATUS_KIND = {+ running: 'green',+ stopped: 'gray',+ error: 'red',+ unknown: 'amber',+};++const ProxyStackPanel = ({ serverId }) => {+ const toast = useToast();+ const [stack, setStack] = useState(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState(null);++ // Local working state — the selected type may differ from the saved one+ // until the user clicks "Switch".+ const [selectedType, setSelectedType] = useState('nginx');+ const [snippet, setSnippet] = useState('');+ const [preview, setPreview] = useState(null);+ const [busy, setBusy] = useState(false);++ const load = useCallback(async () => {+ setLoading(true);+ try {+ const data = await api.getServerProxy(serverId);+ setStack(data);+ setSelectedType(data.proxy_type || 'nginx');+ setSnippet(data.custom_snippet || '');+ setError(null);+ } catch (err) {+ setError(err.message || 'Failed to load proxy configuration');+ } finally {+ setLoading(false);+ }+ }, [serverId]);++ useEffect(() => {+ load();+ }, [load]);++ // Refresh the compose preview whenever the selected type changes.+ const loadPreview = useCallback(async (proxyType) => {+ try {+ const data = await api.getServerProxyComposePreview(serverId, { proxyType });+ setPreview(data);+ } catch (err) {+ console.error('Failed to load compose preview:', err);+ setPreview(null);+ }+ }, [serverId]);++ useEffect(() => {+ loadPreview(selectedType);+ }, [selectedType, loadPreview]);++ const isDirtyType = stack && selectedType !== stack.proxy_type;+ const isDirtySnippet = stack && snippet !== (stack.custom_snippet || '');++ async function handleSwitch() {+ setBusy(true);+ try {+ await api.switchServerProxy(serverId, selectedType);+ toast.success(`Switched to ${selectedType}`);+ await load();+ } catch (err) {+ toast.error(err.message || 'Failed to switch proxy');+ } finally {+ setBusy(false);+ }+ }++ async function handleSaveSnippet() {+ setBusy(true);+ try {+ await api.configureServerProxy(serverId, { custom_snippet: snippet });+ toast.success('Custom snippet saved');+ await load();+ } catch (err) {+ toast.error(err.message || 'Failed to save snippet');+ } finally {+ setBusy(false);+ }+ }++ async function handleRegenerate() {+ setBusy(true);+ try {+ const res = await api.regenerateServerProxy(serverId);+ if (res.success) {+ toast.success(res.reloaded ? 'Config regenerated and reloaded' : 'Config regenerated');+ } else {+ toast.error(res.error || 'Regenerate failed');+ }+ await load();+ } catch (err) {+ toast.error(err.message || 'Failed to regenerate config');+ } finally {+ setBusy(false);+ }+ }++ async function handleDeploy() {+ setBusy(true);+ try {+ const res = await api.configureServerProxy(serverId, {+ proxy_type: selectedType,+ deploy: true,+ });+ const deploy = res.deploy;+ if (deploy && deploy.success === false) {+ toast.error(deploy.error || 'Deploy failed (best-effort)');+ } else {+ toast.success('Stack deployed');+ }+ await load();+ } catch (err) {+ toast.error(err.message || 'Failed to deploy stack');+ } finally {+ setBusy(false);+ }+ }++ if (loading) {+ return <EmptyState loading title="Loading proxy configuration" />;+ }++ if (error) {+ return (+ <div className="proxy-panel">+ <div className="proxy-panel__error">{error}</div>+ <Button variant="outline" onClick={load}>Retry</Button>+ </div>+ );+ }++ const isNginx = selectedType === 'nginx';+ const savedIsNginx = stack?.proxy_type === 'nginx';++ return (+ <div className="proxy-panel">+ <header className="proxy-panel__header">+ <div className="proxy-panel__title">+ <Network size={18} />+ <h3>Reverse Proxy</h3>+ </div>+ <div className="proxy-panel__status">+ <span className="proxy-panel__status-label">Status</span>+ <Pill kind={STATUS_KIND[stack?.status] || 'gray'}>+ {savedIsNginx ? 'host nginx' : (stack?.status || 'unknown')}+ </Pill>+ </div>+ </header>++ <p className="proxy-panel__hint">+ Host Nginx is the default and is recommended for PHP/WordPress. You can+ opt into a Dockerized Traefik or Caddy proxy deployed as a Compose stack.+ </p>++ <section className="proxy-panel__section">+ <label className="proxy-panel__label">Proxy type</label>+ <SegControl+ options={PROXY_OPTIONS.map(o => ({ value: o.value, label: o.label }))}+ value={selectedType}+ onChange={setSelectedType}+ />+ <div className="proxy-panel__actions">+ <Button onClick={handleSwitch} disabled={!isDirtyType || busy}>+ {isDirtyType ? `Switch to ${selectedType}` : 'No change'}+ </Button>+ {!isNginx && (+ <Button variant="outline" onClick={handleDeploy} disabled={busy}>+ Deploy / Restart+ </Button>+ )}+ {!savedIsNginx && (+ <Button variant="outline" onClick={handleRegenerate} disabled={busy}>+ Regenerate config+ </Button>+ )}+ </div>+ </section>++ {!isNginx && (+ <section className="proxy-panel__section">+ <label className="proxy-panel__label">Compose preview</label>+ {preview?.compose ? (+ <pre className="proxy-panel__code" aria-label="docker-compose preview">+ {preview.compose}+ </pre>+ ) : (+ <div className="proxy-panel__empty">No compose generated for this type.</div>+ )}+ </section>+ )}++ {!isNginx && (+ <section className="proxy-panel__section">+ <label className="proxy-panel__label">Custom config snippet</label>+ <Textarea+ rows={6}+ value={snippet}+ onChange={(e) => setSnippet(e.target.value)}+ placeholder="Appended to the generated proxy config (Caddyfile / Traefik dynamic)."+ className="font-mono"+ />+ <div className="proxy-panel__actions">+ <Button+ variant="outline"+ onClick={handleSaveSnippet}+ disabled={!isDirtySnippet || busy}+ >+ Save snippet+ </Button>+ </div>+ </section>+ )}++ {isNginx && (+ <EmptyState+ icon={Network}+ title="Host Nginx is active"+ description="The host's Nginx is handling reverse proxying. Switch to Traefik or Caddy above to run a managed Docker proxy stack instead."+ />+ )}+ </div>+ );+};++export default ProxyStackPanel;diff --git a/frontend/src/components/shared/EnvironmentVariablesPanel.jsx b/frontend/src/components/shared/EnvironmentVariablesPanel.jsxnew file mode 100644index 00000000..93847339--- /dev/null+++ b/frontend/src/components/shared/EnvironmentVariablesPanel.jsx@@ -0,0 +1,105 @@+import { useState, useEffect, useCallback } from 'react';+import api from '../../services/api';+import { useToast } from '../../contexts/ToastContext';++/**+ * Read-mostly facade showing the *resolved* shared variables for a resource —+ * i.e. the merged effective set from every shared variable group attached to it.+ * Secret values arrive pre-masked from the backend; this panel never reveals+ * them. Editing happens in SharedVariableGroups (the group is the source of+ * truth); this surface is the read-side facade meant to be embedded on a+ * resource's detail page.+ *+ * Props:+ * resourceType one of SharedResourceService.RESOURCE_TYPES+ * resourceId the resource's id (number or string)+ */+const EnvironmentVariablesPanel = ({ resourceType, resourceId }) => {+ const toast = useToast();+ const [variables, setVariables] = useState([]);+ const [groups, setGroups] = useState([]);+ const [loading, setLoading] = useState(true);+ const [filter, setFilter] = useState('');++ const load = useCallback(async () => {+ if (!resourceType || resourceId == null) return;+ try {+ setLoading(true);+ const data = await api.getResolvedVariables(resourceType, resourceId);+ setVariables(data.variables || []);+ setGroups(data.groups || []);+ } catch (err) {+ toast.error('Failed to load shared variables');+ console.error('Failed to load resolved variables:', err);+ } finally {+ setLoading(false);+ }+ }, [resourceType, resourceId, toast]);++ useEffect(() => { load(); }, [load]);++ const filtered = filter+ ? variables.filter((v) => v.key.toLowerCase().includes(filter.toLowerCase()))+ : variables;++ if (loading) {+ return <div className="shared-vars-panel shared-vars-panel--loading">Loading shared variables…</div>;+ }++ return (+ <div className="shared-vars-panel">+ <div className="shared-vars-panel__header">+ <h3>Shared Variables</h3>+ <span className="shared-vars-panel__count">+ {variables.length} resolved · {groups.length} group{groups.length !== 1 ? 's' : ''}+ </span>+ </div>++ <p className="shared-vars-panel__hint">+ Effective variables merged from every shared group attached to this+ resource. Later-attached groups override earlier ones on key+ collisions. Secret values are masked.+ </p>++ {variables.length > 5 && (+ <div className="shared-vars-panel__filter">+ <input+ type="text"+ value={filter}+ onChange={(e) => setFilter(e.target.value)}+ placeholder="Filter variables…"+ />+ </div>+ )}++ {filtered.length === 0 ? (+ <div className="shared-vars-panel__empty">+ {filter+ ? 'No matching variables'+ : 'No shared variable groups attached to this resource yet.'}+ </div>+ ) : (+ <table className="shared-vars-table">+ <thead>+ <tr>+ <th>Key</th>+ <th>Value</th>+ <th>Source group</th>+ </tr>+ </thead>+ <tbody>+ {filtered.map((v) => (+ <tr key={v.key} className={v.is_secret ? 'is-secret' : ''}>+ <td className="shared-vars-table__key">{v.key}</td>+ <td className="shared-vars-table__value">{v.value}</td>+ <td className="shared-vars-table__group">{v.group_name}</td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </div>+ );+};++export default EnvironmentVariablesPanel;diff --git a/frontend/src/components/shared/SharedVariableGroups.jsx b/frontend/src/components/shared/SharedVariableGroups.jsxnew file mode 100644index 00000000..413f8f90--- /dev/null+++ b/frontend/src/components/shared/SharedVariableGroups.jsx@@ -0,0 +1,326 @@+import { useState, useEffect, useCallback } from 'react';+import api from '../../services/api';+import { useToast } from '../../contexts/ToastContext';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Checkbox } from '@/components/ui/checkbox';++const RESOURCE_TYPES = ['application', 'database', 'service', 'wordpress', 'server'];++/**+ * Manage shared variable groups for a given scope: create groups, add/remove+ * variables (secrets masked), and attach/detach a group to resources.+ *+ * Props:+ * scopeType 'workspace' | 'project' | 'environment' (default 'workspace')+ * scopeId the scope identifier (string) (default 'default')+ */+const SharedVariableGroups = ({ scopeType = 'workspace', scopeId = 'default' }) => {+ const toast = useToast();+ const [groups, setGroups] = useState([]);+ const [loading, setLoading] = useState(true);+ const [selectedId, setSelectedId] = useState(null);+ const [detail, setDetail] = useState(null);++ // create-group form+ const [newName, setNewName] = useState('');+ const [newDescription, setNewDescription] = useState('');++ // add-variable form+ const [varKey, setVarKey] = useState('');+ const [varValue, setVarValue] = useState('');+ const [varSecret, setVarSecret] = useState(false);++ // attach form+ const [attachType, setAttachType] = useState(RESOURCE_TYPES[0]);+ const [attachId, setAttachId] = useState('');++ const loadGroups = useCallback(async () => {+ try {+ setLoading(true);+ const data = await api.listVariableGroups(scopeType, scopeId);+ setGroups(data.groups || []);+ } catch {+ toast.error('Failed to load variable groups');+ } finally {+ setLoading(false);+ }+ }, [scopeType, scopeId, toast]);++ const loadDetail = useCallback(async (groupId) => {+ if (!groupId) { setDetail(null); return; }+ try {+ const data = await api.getVariableGroup(groupId);+ setDetail(data);+ } catch {+ toast.error('Failed to load group');+ }+ }, [toast]);++ useEffect(() => { loadGroups(); }, [loadGroups]);+ useEffect(() => { loadDetail(selectedId); }, [selectedId, loadDetail]);++ async function handleCreateGroup(e) {+ e.preventDefault();+ if (!newName.trim()) return;+ try {+ const group = await api.createVariableGroup({+ scopeType, scopeId, name: newName.trim(),+ description: newDescription.trim() || null,+ });+ toast.success('Group created');+ setNewName('');+ setNewDescription('');+ await loadGroups();+ setSelectedId(group.id);+ } catch (err) {+ toast.error(err.message || 'Failed to create group');+ }+ }++ async function handleDeleteGroup(groupId) {+ if (!confirm('Delete this variable group? Attachments will be removed.')) return;+ try {+ await api.deleteVariableGroup(groupId);+ toast.success('Group deleted');+ if (selectedId === groupId) setSelectedId(null);+ loadGroups();+ } catch (err) {+ toast.error(err.message || 'Failed to delete group');+ }+ }++ async function handleAddVariable(e) {+ e.preventDefault();+ if (!varKey.trim() || !selectedId) return;+ try {+ await api.addGroupVariable(selectedId, {+ key: varKey.trim(), value: varValue, isSecret: varSecret,+ });+ setVarKey('');+ setVarValue('');+ setVarSecret(false);+ loadDetail(selectedId);+ loadGroups();+ } catch (err) {+ toast.error(err.message || 'Failed to add variable');+ }+ }++ async function handleDeleteVariable(variableId) {+ try {+ await api.deleteGroupVariable(selectedId, variableId);+ loadDetail(selectedId);+ loadGroups();+ } catch (err) {+ toast.error(err.message || 'Failed to delete variable');+ }+ }++ async function handleAttach(e) {+ e.preventDefault();+ if (!attachId.trim() || !selectedId) return;+ try {+ await api.attachVariableGroup(selectedId, attachType, attachId.trim());+ toast.success('Group attached');+ setAttachId('');+ loadDetail(selectedId);+ loadGroups();+ } catch (err) {+ toast.error(err.message || 'Failed to attach group');+ }+ }++ async function handleDetach(att) {+ try {+ await api.detachVariableGroup(selectedId, att.resource_type, att.resource_id);+ loadDetail(selectedId);+ loadGroups();+ } catch (err) {+ toast.error(err.message || 'Failed to detach');+ }+ }++ return (+ <div className="shared-groups">+ <div className="shared-groups__layout">+ {/* Group list + create */}+ <aside className="shared-groups__sidebar">+ <form className="shared-groups__create" onSubmit={handleCreateGroup}>+ <Input+ type="text"+ value={newName}+ onChange={(e) => setNewName(e.target.value)}+ placeholder="New group name"+ />+ <Input+ type="text"+ value={newDescription}+ onChange={(e) => setNewDescription(e.target.value)}+ placeholder="Description (optional)"+ />+ <Button type="submit" size="sm" disabled={!newName.trim()}>+ Create group+ </Button>+ </form>++ <ul className="shared-groups__list">+ {loading ? (+ <li className="shared-groups__hint">Loading…</li>+ ) : groups.length === 0 ? (+ <li className="shared-groups__hint">No groups in this scope yet</li>+ ) : (+ groups.map((g) => (+ <li+ key={g.id}+ className={`shared-groups__item ${selectedId === g.id ? 'is-active' : ''}`}+ onClick={() => setSelectedId(g.id)}+ >+ <div className="shared-groups__item-name">{g.name}</div>+ <div className="shared-groups__item-meta">+ {g.variable_count} vars · {g.attachment_count} attached+ </div>+ </li>+ ))+ )}+ </ul>+ </aside>++ {/* Detail */}+ <section className="shared-groups__detail">+ {!detail ? (+ <div className="shared-groups__empty">+ Select a group to manage its variables and attachments.+ </div>+ ) : (+ <>+ <div className="shared-groups__detail-header">+ <div>+ <h3>{detail.name}</h3>+ {detail.description && (+ <p className="shared-groups__desc">{detail.description}</p>+ )}+ </div>+ <Button+ variant="destructive"+ size="sm"+ onClick={() => handleDeleteGroup(detail.id)}+ >+ Delete group+ </Button>+ </div>++ {/* Variables */}+ <h4 className="shared-groups__subhead">Variables</h4>+ {(detail.variables || []).length === 0 ? (+ <p className="shared-groups__hint">No variables yet.</p>+ ) : (+ <table className="shared-vars-table">+ <thead>+ <tr>+ <th>Key</th>+ <th>Value</th>+ <th></th>+ </tr>+ </thead>+ <tbody>+ {detail.variables.map((v) => (+ <tr key={v.id} className={v.is_secret ? 'is-secret' : ''}>+ <td className="shared-vars-table__key">{v.key}</td>+ <td className="shared-vars-table__value">{v.value}</td>+ <td>+ <button+ type="button"+ className="shared-tag__remove"+ onClick={() => handleDeleteVariable(v.id)}+ title="Delete variable"+ aria-label={`Delete variable ${v.key}`}+ >+ ×+ </button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}++ <form className="shared-groups__add-var" onSubmit={handleAddVariable}>+ <Input+ type="text"+ value={varKey}+ onChange={(e) => setVarKey(e.target.value)}+ placeholder="KEY"+ className="shared-groups__var-key"+ />+ <Input+ type={varSecret ? 'password' : 'text'}+ value={varValue}+ onChange={(e) => setVarValue(e.target.value)}+ placeholder="value"+ className="shared-groups__var-value"+ />+ <label className="shared-groups__secret">+ <Checkbox checked={varSecret} onCheckedChange={setVarSecret} />+ <span>Secret</span>+ </label>+ <Button type="submit" size="sm" disabled={!varKey.trim()}>+ Add+ </Button>+ </form>++ {/* Attachments */}+ <h4 className="shared-groups__subhead">Attached resources</h4>+ {(detail.attachments || []).length === 0 ? (+ <p className="shared-groups__hint">Not attached to any resource yet.</p>+ ) : (+ <ul className="shared-groups__attachments">+ {detail.attachments.map((a) => (+ <li key={a.id} className="shared-groups__attachment">+ <span className="shared-groups__attachment-label">+ {a.resource_type}:{a.resource_id}+ </span>+ <button+ type="button"+ className="shared-tag__remove"+ onClick={() => handleDetach(a)}+ title="Detach"+ aria-label="Detach group"+ >+ ×+ </button>+ </li>+ ))}+ </ul>+ )}++ <form className="shared-groups__attach" onSubmit={handleAttach}>+ <select+ value={attachType}+ onChange={(e) => setAttachType(e.target.value)}+ className="shared-groups__attach-type"+ >+ {RESOURCE_TYPES.map((t) => (+ <option key={t} value={t}>{t}</option>+ ))}+ </select>+ <Input+ type="text"+ value={attachId}+ onChange={(e) => setAttachId(e.target.value)}+ placeholder="resource id"+ className="shared-groups__attach-id"+ />+ <Button type="submit" size="sm" disabled={!attachId.trim()}>+ Attach+ </Button>+ </form>+ </>+ )}+ </section>+ </div>+ </div>+ );+};++export default SharedVariableGroups;diff --git a/frontend/src/components/shared/TagsPanel.jsx b/frontend/src/components/shared/TagsPanel.jsxnew file mode 100644index 00000000..fd871e00--- /dev/null+++ b/frontend/src/components/shared/TagsPanel.jsx@@ -0,0 +1,107 @@+import { useState, useEffect, useCallback } from 'react';+import api from '../../services/api';+import { useToast } from '../../contexts/ToastContext';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';++/**+ * Reusable polymorphic tags panel for any resource.+ *+ * Props:+ * resourceType one of SharedResourceService.RESOURCE_TYPES+ * resourceId the resource's id (number or string)+ * readOnly hide the add/remove controls (default false)+ */+const TagsPanel = ({ resourceType, resourceId, readOnly = false }) => {+ const toast = useToast();+ const [tags, setTags] = useState([]);+ const [loading, setLoading] = useState(true);+ const [newTag, setNewTag] = useState('');+ const [saving, setSaving] = useState(false);++ const load = useCallback(async () => {+ if (!resourceType || resourceId == null) return;+ try {+ setLoading(true);+ const data = await api.listResourceTags(resourceType, resourceId);+ setTags(data.tags || []);+ } catch (err) {+ console.error('Failed to load tags:', err);+ } finally {+ setLoading(false);+ }+ }, [resourceType, resourceId]);++ useEffect(() => { load(); }, [load]);++ async function handleAdd(e) {+ e.preventDefault();+ const value = newTag.trim();+ if (!value) return;+ setSaving(true);+ try {+ await api.addResourceTag(resourceType, resourceId, value);+ setNewTag('');+ load();+ } catch (err) {+ toast.error(err.message || 'Failed to add tag');+ } finally {+ setSaving(false);+ }+ }++ async function handleRemove(tag) {+ try {+ await api.removeResourceTag(resourceType, resourceId, tag);+ setTags((prev) => prev.filter((t) => t.tag !== tag));+ } catch (err) {+ toast.error(err.message || 'Failed to remove tag');+ }+ }++ return (+ <div className="shared-tags">+ <div className="shared-tags__list">+ {loading ? (+ <span className="shared-tags__hint">Loading…</span>+ ) : tags.length === 0 ? (+ <span className="shared-tags__hint">No tags yet</span>+ ) : (+ tags.map((t) => (+ <span key={t.id} className="shared-tag">+ <span className="shared-tag__label">{t.tag}</span>+ {!readOnly && (+ <button+ type="button"+ className="shared-tag__remove"+ onClick={() => handleRemove(t.tag)}+ aria-label={`Remove tag ${t.tag}`}+ title="Remove tag"+ >+ ×+ </button>+ )}+ </span>+ ))+ )}+ </div>++ {!readOnly && (+ <form className="shared-tags__add" onSubmit={handleAdd}>+ <Input+ type="text"+ value={newTag}+ onChange={(e) => setNewTag(e.target.value)}+ placeholder="Add a tag…"+ className="shared-tags__input"+ />+ <Button type="submit" size="sm" disabled={saving || !newTag.trim()}>+ Add+ </Button>+ </form>+ )}+ </div>+ );+};++export default TagsPanel;diff --git a/frontend/src/components/sidebarItems.js b/frontend/src/components/sidebarItems.jsindex 4a40735d..d3f5f284 100644--- a/frontend/src/components/sidebarItems.js+++ b/frontend/src/components/sidebarItems.js@@ -78,6 +78,16 @@ export const SIDEBAR_ITEMS = [category: 'infrastructure',icon: '<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/>'},+ {+ // Projects group apps/services under projects + environments+ // (production/staging/development) within a workspace.+ id: 'projects',+ label: 'Projects',+ route: '/projects',+ matchPrefixes: ['/projects'],+ category: 'infrastructure',+ icon: '<path d="M3 7a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.7.9H19a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>'+ },{// Redesign: WordPress uses the top-bar layout (REDESIGN_MAP §6 dec. 3).// Pipeline now lives in the page's top bar (PageTopbar WORDPRESS_TABS),@@ -186,6 +196,13 @@ export const SIDEBAR_ITEMS = [category: 'system',icon: '<path d="M22 12h-4l-3 9L9 3l-3 9H2"/>'},+ {+ id: 'shared-variables',+ label: 'Shared Variables',+ route: '/shared-variables',+ category: 'system',+ icon: '<path d="M4 7h16M4 12h16M4 17h10"/><circle cx="18" cy="17" r="2"/>'+ },{id: 'jobs',label: 'Jobs',diff --git a/frontend/src/pages/ApplicationDetail.jsx b/frontend/src/pages/ApplicationDetail.jsxindex 8c691f43..9ef418d4 100644--- a/frontend/src/pages/ApplicationDetail.jsx+++ b/frontend/src/pages/ApplicationDetail.jsx@@ -15,6 +15,7 @@ import LinkedAppsSection from '../components/LinkedAppsSection';import LinkAppModal from '../components/LinkAppModal';import ContainerOpsPanel from '../components/apps/ContainerOpsPanel';import WafPanel from '../components/apps/WafPanel';+import PreviewList from '../components/previews/PreviewList';import DeploymentTimeline from '../components/deployments/DeploymentTimeline';import BuildpackPreview from '../components/buildpack/BuildpackPreview';import { getServiceType, getStatusConfig } from '../utils/serviceTypes';@@ -24,7 +25,7 @@ import { Textarea } from '@/components/ui/textarea';import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';import { Pill, EnvTag } from '@/components/ds';-const VALID_TABS = ['overview', 'environment', 'packages', 'gunicorn', 'commands', 'ops', 'waf', 'build', 'deploy', 'logs', 'settings'];+const VALID_TABS = ['overview', 'environment', 'packages', 'gunicorn', 'commands', 'ops', 'waf', 'build', 'deploy', 'previews', 'logs', 'settings'];// statusInfo.dotClass → ds Pill kindconst STATUS_PILL = {@@ -224,6 +225,7 @@ const ApplicationDetail = () => {)}<TabsTrigger value="build">Build</TabsTrigger><TabsTrigger value="deploy">Deploy</TabsTrigger>+ <TabsTrigger value="previews">Previews</TabsTrigger><TabsTrigger value="logs">Logs</TabsTrigger><TabsTrigger value="settings">Settings</TabsTrigger></TabsList>@@ -265,6 +267,9 @@ const ApplicationDetail = () => {<TabsContent value="deploy"><DeployTab appId={app.id} appPath={app.path} /></TabsContent>+ <TabsContent value="previews">+ <PreviewList appId={app.id} />+ </TabsContent><TabsContent value="logs"><LogsTab app={app} /></TabsContent>diff --git a/frontend/src/pages/NewService.jsx b/frontend/src/pages/NewService.jsxindex e5236abe..3f2a5b11 100644--- a/frontend/src/pages/NewService.jsx+++ b/frontend/src/pages/NewService.jsx@@ -155,6 +155,12 @@ const NewService = () => {const [uploadFile, setUploadFile] = useState(null);const [uploadDragOver, setUploadDragOver] = useState(false);+ // Optional Project / Environment assignment (opt-in hierarchy).+ const [projects, setProjects] = useState([]);+ const [selectedProjectId, setSelectedProjectId] = useState('');+ const [selectedEnvironmentId, setSelectedEnvironmentId] = useState('');+ const [projectEnvironments, setProjectEnvironments] = useState([]);+const githubConnection = githubStatus?.connection;const githubConfigured = githubStatus?.configured;const normalizedManualRepo = useMemo(() => normalizeManualRepo(manualRepoUrl), [manualRepoUrl]);@@ -217,6 +223,45 @@ const NewService = () => {loadGithubStatus();}, [loadGithubStatus]);+ // Load projects for the optional Project / Environment selector. Best-effort:+ // if it fails the selector simply stays empty and creation is unaffected.+ useEffect(() => {+ let cancelled = false;+ api.getProjects()+ .then(data => {+ if (cancelled) return;+ setProjects(Array.isArray(data?.projects) ? data.projects : []);+ })+ .catch(() => { if (!cancelled) setProjects([]); });+ return () => { cancelled = true; };+ }, []);++ // When a project is picked, load its environments and default-select the+ // default one. Clearing the project clears the environment.+ useEffect(() => {+ if (!selectedProjectId) {+ setProjectEnvironments([]);+ setSelectedEnvironmentId('');+ return undefined;+ }+ let cancelled = false;+ api.getProject(selectedProjectId)+ .then(data => {+ if (cancelled) return;+ const envs = Array.isArray(data?.project?.environments) ? data.project.environments : [];+ setProjectEnvironments(envs);+ const def = envs.find(e => e.is_default) || envs[0];+ setSelectedEnvironmentId(def ? String(def.id) : '');+ })+ .catch(() => {+ if (!cancelled) {+ setProjectEnvironments([]);+ setSelectedEnvironmentId('');+ }+ });+ return () => { cancelled = true; };+ }, [selectedProjectId]);+useEffect(() => {if (sourceMode === 'github' && githubConnection) {loadGithubRepos();@@ -380,6 +425,12 @@ const NewService = () => {}setSubmitting(true);+ // Optional Project / Environment assignment, included only when picked.+ const projectEnvPayload = {};+ if (selectedProjectId) {+ projectEnvPayload.project_id = Number(selectedProjectId);+ if (selectedEnvironmentId) projectEnvPayload.environment_id = Number(selectedEnvironmentId);+ }try {if (sourceMode === 'local') {const payload = {@@ -389,6 +440,7 @@ const NewService = () => {compose_file: composeFile.trim() || undefined,systemd_unit: systemdUnit.trim() || undefined,managed_by: managedBy === 'auto' ? undefined : managedBy,+ ...projectEnvPayload,};const result = await api.createManualApp(payload);toast.success('Manual service registered');@@ -399,6 +451,8 @@ const NewService = () => {formData.append('name', serviceName);formData.append('app_type', appType);formData.append('auto_deploy', autoDeploy ? 'true' : 'false');+ if (projectEnvPayload.project_id) formData.append('project_id', projectEnvPayload.project_id);+ if (projectEnvPayload.environment_id) formData.append('environment_id', projectEnvPayload.environment_id);const result = await api.uploadAppZip(formData);toast.success('Upload service created');navigate(`/services/${result.app.id}`);@@ -410,6 +464,7 @@ const NewService = () => {build_method: buildMethod,port: port ? Number(port) : null,auto_deploy: autoDeploy,+ ...projectEnvPayload,};if (recommended.dockerfile_path) payload.dockerfile_path = recommended.dockerfile_path;if (recommended.custom_build_cmd) payload.custom_build_cmd = recommended.custom_build_cmd;@@ -1051,6 +1106,38 @@ const NewService = () => {</div>)}</div>++ {projects.length > 0 && (+ <div className="new-service-page__two-col">+ <div className="new-service-page__field">+ <Label htmlFor="project">Project <span className="new-service-page__optional">(optional)</span></Label>+ <select+ id="project"+ value={selectedProjectId}+ onChange={(e) => setSelectedProjectId(e.target.value)}+ >+ <option value="">No project</option>+ {projects.map(p => (+ <option key={p.id} value={p.id}>{p.name}</option>+ ))}+ </select>+ </div>+ {selectedProjectId && (+ <div className="new-service-page__field">+ <Label htmlFor="environment">Environment</Label>+ <select+ id="environment"+ value={selectedEnvironmentId}+ onChange={(e) => setSelectedEnvironmentId(e.target.value)}+ >+ {projectEnvironments.map(env => (+ <option key={env.id} value={env.id}>{env.name}</option>+ ))}+ </select>+ </div>+ )}+ </div>+ )}</div>)}diff --git a/frontend/src/pages/ProjectDetail.jsx b/frontend/src/pages/ProjectDetail.jsxnew file mode 100644index 00000000..eec92e1d--- /dev/null+++ b/frontend/src/pages/ProjectDetail.jsx@@ -0,0 +1,349 @@+import { useState, useEffect, useCallback } from 'react';+import { Link, useParams } from 'react-router-dom';+import {+ FolderKanban,+ Plus,+ ArrowLeft,+ ArrowUp,+ ArrowDown,+ Trash2,+ Boxes,+ ExternalLink,+} from 'lucide-react';+import api from '../services/api';+import { useToast } from '../contexts/ToastContext';+import EmptyState from '../components/EmptyState';+import { ConfirmDialog } from '../components/ConfirmDialog';+import { PageTopbar } from '@/components/ds';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { Badge } from '@/components/ui/badge';+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogFooter,+} from '@/components/ui/dialog';++const ProjectDetail = () => {+ const { id } = useParams();+ const toast = useToast();++ const [project, setProject] = useState(null);+ const [environments, setEnvironments] = useState([]);+ const [apps, setApps] = useState([]);+ const [activeEnvId, setActiveEnvId] = useState(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState(null);+ const [showCreateEnv, setShowCreateEnv] = useState(false);+ const [deleteEnv, setDeleteEnv] = useState(null);++ const loadProject = useCallback(async () => {+ setLoading(true);+ try {+ const [projectData, appsData] = await Promise.all([+ api.getProject(id),+ api.getApps(),+ ]);+ const p = projectData?.project || null;+ setProject(p);+ const envs = Array.isArray(p?.environments) ? p.environments : [];+ setEnvironments(envs);+ setActiveEnvId(prev => {+ if (prev && envs.some(e => e.id === prev)) return prev;+ const def = envs.find(e => e.is_default) || envs[0];+ return def ? def.id : null;+ });+ const allApps = Array.isArray(appsData?.apps) ? appsData.apps : [];+ setApps(allApps.filter(a => String(a.project_id) === String(id)));+ setError(null);+ } catch (err) {+ setError(err.message || 'Failed to load project');+ } finally {+ setLoading(false);+ }+ }, [id]);++ useEffect(() => {+ loadProject();+ }, [loadProject]);++ async function handleReorder(envId, direction) {+ const idx = environments.findIndex(e => e.id === envId);+ const target = idx + direction;+ if (idx < 0 || target < 0 || target >= environments.length) return;+ const next = [...environments];+ [next[idx], next[target]] = [next[target], next[idx]];+ setEnvironments(next);+ try {+ await api.reorderEnvironments(Number(id), next.map(e => e.id));+ } catch (err) {+ toast.error(err.message || 'Failed to reorder environments');+ loadProject();+ }+ }++ async function handleDeleteEnvironment() {+ if (!deleteEnv) return;+ try {+ await api.deleteEnvironment(deleteEnv.id);+ toast.success(`Environment "${deleteEnv.name}" deleted`);+ setDeleteEnv(null);+ loadProject();+ } catch (err) {+ toast.error(err.message || 'Failed to delete environment');+ setDeleteEnv(null);+ }+ }++ if (loading) {+ return (+ <div className="project-detail-page">+ <EmptyState loading title="Loading project" />+ </div>+ );+ }++ if (error || !project) {+ return (+ <div className="project-detail-page">+ <EmptyState+ icon={FolderKanban}+ title="Project not found"+ description={error || 'This project could not be loaded.'}+ action={+ <Button variant="outline" asChild>+ <Link to="/projects"><ArrowLeft size={16} /> Back to Projects</Link>+ </Button>+ }+ />+ </div>+ );+ }++ const activeEnv = environments.find(e => e.id === activeEnvId) || null;+ const envApps = apps.filter(a => String(a.environment_id) === String(activeEnvId));+ const unassignedApps = apps.filter(a => !a.environment_id);++ return (+ <div className="project-detail-page">+ <PageTopbar+ icon={<FolderKanban size={20} />}+ title={project.name}+ meta={project.slug}+ actions={+ <>+ <Button variant="outline" asChild>+ <Link to="/projects"><ArrowLeft size={16} /> Projects</Link>+ </Button>+ <Button onClick={() => setShowCreateEnv(true)}>+ <Plus size={16} /> New Environment+ </Button>+ </>+ }+ />++ <div className="project-detail-page__body">+ {project.description && (+ <p className="project-detail-page__description">{project.description}</p>+ )}++ <div className="project-env-tabs" role="tablist" aria-label="Environments">+ {environments.map((env, index) => (+ <div+ key={env.id}+ className={`project-env-tab ${env.id === activeEnvId ? 'is-active' : ''}`}+ >+ <button+ type="button"+ role="tab"+ aria-selected={env.id === activeEnvId}+ className="project-env-tab__label"+ onClick={() => setActiveEnvId(env.id)}+ >+ {env.name}+ {env.is_default && <Badge variant="outline">default</Badge>}+ <span className="project-env-tab__count">{env.app_count ?? 0}</span>+ </button>+ <div className="project-env-tab__controls">+ <button+ type="button"+ title="Move up"+ aria-label={`Move ${env.name} up`}+ disabled={index === 0}+ onClick={() => handleReorder(env.id, -1)}+ >+ <ArrowUp size={13} />+ </button>+ <button+ type="button"+ title="Move down"+ aria-label={`Move ${env.name} down`}+ disabled={index === environments.length - 1}+ onClick={() => handleReorder(env.id, 1)}+ >+ <ArrowDown size={13} />+ </button>+ <button+ type="button"+ className="project-env-tab__delete"+ title="Delete environment"+ aria-label={`Delete ${env.name}`}+ disabled={environments.length <= 1}+ onClick={() => setDeleteEnv(env)}+ >+ <Trash2 size={13} />+ </button>+ </div>+ </div>+ ))}+ </div>++ <div className="project-env-panel" role="tabpanel">+ {activeEnv ? (+ <>+ <div className="project-env-panel__header">+ <h2>{activeEnv.name}</h2>+ <span>{envApps.length} app{envApps.length === 1 ? '' : 's'}</span>+ </div>+ {envApps.length === 0 ? (+ <EmptyState+ icon={Boxes}+ size="sm"+ title="No apps in this environment"+ description="Assign apps to this environment when creating them, or move existing apps here."+ />+ ) : (+ <AppList apps={envApps} />+ )}+ </>+ ) : (+ <EmptyState+ icon={FolderKanban}+ title="No environments"+ description="Add an environment to start organizing this project's apps."+ />+ )}+ </div>++ {unassignedApps.length > 0 && (+ <div className="project-unassigned">+ <div className="project-unassigned__header">+ <h3>In this project, no environment</h3>+ <span>{unassignedApps.length}</span>+ </div>+ <AppList apps={unassignedApps} />+ </div>+ )}+ </div>++ <CreateEnvironmentDialog+ projectId={Number(id)}+ open={showCreateEnv}+ onOpenChange={setShowCreateEnv}+ onCreated={() => {+ setShowCreateEnv(false);+ loadProject();+ }}+ />++ <ConfirmDialog+ isOpen={Boolean(deleteEnv)}+ title={`Delete environment "${deleteEnv?.name || ''}"?`}+ message="Apps assigned to this environment will stay in the project but lose their environment assignment. This cannot be undone."+ confirmText="Delete environment"+ variant="danger"+ onConfirm={handleDeleteEnvironment}+ onCancel={() => setDeleteEnv(null)}+ />+ </div>+ );+};++const AppList = ({ apps }) => (+ <ul className="project-app-list">+ {apps.map(app => (+ <li key={app.id} className="project-app-row">+ <span className={`project-app-row__status project-app-row__status--${app.status || 'stopped'}`} aria-hidden="true" />+ <Link to={`/services/${app.id}`} className="project-app-row__name">+ {app.name}+ </Link>+ <span className="project-app-row__type">{app.app_type}</span>+ <span className={`status-pill status-pill--${app.status || 'stopped'}`}>+ {app.status || 'stopped'}+ </span>+ <Link to={`/services/${app.id}`} className="project-app-row__link" aria-label={`Open ${app.name}`}>+ <ExternalLink size={14} />+ </Link>+ </li>+ ))}+ </ul>+);++const CreateEnvironmentDialog = ({ projectId, open, onOpenChange, onCreated }) => {+ const [name, setName] = useState('');+ const [submitting, setSubmitting] = useState(false);+ const toast = useToast();++ async function handleSubmit(e) {+ e.preventDefault();+ if (!name.trim()) {+ toast.error('Environment name is required');+ return;+ }+ setSubmitting(true);+ try {+ await api.createEnvironment(projectId, { name: name.trim() });+ toast.success('Environment created');+ setName('');+ onCreated();+ } catch (err) {+ toast.error(err.message || 'Failed to create environment');+ } finally {+ setSubmitting(false);+ }+ }++ return (+ <Dialog open={open} onOpenChange={(v) => { if (!v) setName(''); onOpenChange(v); }}>+ <DialogContent>+ <form onSubmit={handleSubmit}>+ <DialogHeader>+ <DialogTitle>New Environment</DialogTitle>+ <DialogDescription>+ Common names are production, staging, and development — but any name works.+ </DialogDescription>+ </DialogHeader>++ <div className="projects-form">+ <div className="projects-form__field">+ <Label htmlFor="env-name">Name</Label>+ <Input+ id="env-name"+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder="staging"+ autoFocus+ required+ />+ </div>+ </div>++ <DialogFooter>+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>+ Cancel+ </Button>+ <Button type="submit" disabled={submitting || !name.trim()}>+ {submitting ? 'Creating…' : 'Create Environment'}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+};++export default ProjectDetail;diff --git a/frontend/src/pages/Projects.jsx b/frontend/src/pages/Projects.jsxnew file mode 100644index 00000000..687b3fb9--- /dev/null+++ b/frontend/src/pages/Projects.jsx@@ -0,0 +1,206 @@+import { useState, useEffect, useCallback } from 'react';+import { Link } from 'react-router-dom';+import { FolderKanban, Plus, Layers, Boxes } from 'lucide-react';+import api from '../services/api';+import { useToast } from '../contexts/ToastContext';+import EmptyState from '../components/EmptyState';+import { PageTopbar } from '@/components/ds';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { Textarea } from '@/components/ui/textarea';+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogFooter,+} from '@/components/ui/dialog';++const Projects = () => {+ const [projects, setProjects] = useState([]);+ const [loading, setLoading] = useState(true);+ const [showCreate, setShowCreate] = useState(false);+ const toast = useToast();++ const loadProjects = useCallback(async () => {+ setLoading(true);+ try {+ const data = await api.getProjects();+ setProjects(Array.isArray(data?.projects) ? data.projects : []);+ } catch (err) {+ console.error('Failed to load projects:', err);+ toast.error('Failed to load projects');+ } finally {+ setLoading(false);+ }+ }, [toast]);++ useEffect(() => {+ loadProjects();+ }, [loadProjects]);++ return (+ <div className="projects-page">+ <PageTopbar+ icon={<FolderKanban size={20} />}+ title="Projects"+ meta={projects.length ? `${projects.length} project${projects.length === 1 ? '' : 's'}` : null}+ actions={+ <Button onClick={() => setShowCreate(true)}>+ <Plus size={16} /> New Project+ </Button>+ }+ />++ <div className="projects-page__body">+ {loading ? (+ <EmptyState loading title="Loading projects" />+ ) : projects.length === 0 ? (+ <EmptyState+ icon={FolderKanban}+ title="No projects yet"+ description="Group your applications into projects and environments (production, staging, development) to keep things organized."+ action={+ <Button onClick={() => setShowCreate(true)}>+ <Plus size={16} /> Create your first project+ </Button>+ }+ />+ ) : (+ <div className="projects-grid">+ {projects.map(project => (+ <ProjectCard key={project.id} project={project} />+ ))}+ </div>+ )}+ </div>++ <CreateProjectDialog+ open={showCreate}+ onOpenChange={setShowCreate}+ onCreated={() => {+ setShowCreate(false);+ loadProjects();+ }}+ />+ </div>+ );+};++const ProjectCard = ({ project }) => {+ const envCount = project.environment_count ?? 0;+ const appCount = project.app_count ?? 0;+ return (+ <Link to={`/projects/${project.id}`} className="project-card">+ <div className="project-card__header">+ <span className="project-card__icon" aria-hidden="true">+ <FolderKanban size={18} />+ </span>+ <div className="project-card__titles">+ <h3 className="project-card__name">{project.name}</h3>+ <span className="project-card__slug">{project.slug}</span>+ </div>+ </div>+ {project.description && (+ <p className="project-card__description">{project.description}</p>+ )}+ <div className="project-card__stats">+ <span className="project-card__stat">+ <Layers size={14} />+ {envCount} environment{envCount === 1 ? '' : 's'}+ </span>+ <span className="project-card__stat">+ <Boxes size={14} />+ {appCount} app{appCount === 1 ? '' : 's'}+ </span>+ </div>+ </Link>+ );+};++const CreateProjectDialog = ({ open, onOpenChange, onCreated }) => {+ const [name, setName] = useState('');+ const [description, setDescription] = useState('');+ const [submitting, setSubmitting] = useState(false);+ const toast = useToast();++ function reset() {+ setName('');+ setDescription('');+ }++ async function handleSubmit(e) {+ e.preventDefault();+ if (!name.trim()) {+ toast.error('Project name is required');+ return;+ }+ setSubmitting(true);+ try {+ await api.createProject({+ name: name.trim(),+ description: description.trim() || undefined,+ });+ toast.success('Project created');+ reset();+ onCreated();+ } catch (err) {+ toast.error(err.message || 'Failed to create project');+ } finally {+ setSubmitting(false);+ }+ }++ return (+ <Dialog open={open} onOpenChange={(v) => { if (!v) reset(); onOpenChange(v); }}>+ <DialogContent>+ <form onSubmit={handleSubmit}>+ <DialogHeader>+ <DialogTitle>New Project</DialogTitle>+ <DialogDescription>+ A project groups your applications. It starts with a default+ "production" environment you can rename or expand.+ </DialogDescription>+ </DialogHeader>++ <div className="projects-form">+ <div className="projects-form__field">+ <Label htmlFor="project-name">Name</Label>+ <Input+ id="project-name"+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder="My Project"+ autoFocus+ required+ />+ </div>+ <div className="projects-form__field">+ <Label htmlFor="project-description">Description (optional)</Label>+ <Textarea+ id="project-description"+ value={description}+ onChange={(e) => setDescription(e.target.value)}+ placeholder="What this project is for…"+ rows={3}+ />+ </div>+ </div>++ <DialogFooter>+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>+ Cancel+ </Button>+ <Button type="submit" disabled={submitting || !name.trim()}>+ {submitting ? 'Creating…' : 'Create Project'}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+};++export default Projects;diff --git a/frontend/src/pages/ServerDetail.jsx b/frontend/src/pages/ServerDetail.jsxindex 3fe90933..8c00eb1b 100644--- a/frontend/src/pages/ServerDetail.jsx+++ b/frontend/src/pages/ServerDetail.jsx@@ -31,6 +31,7 @@ import PackagesTab from '../components/serverdetail/PackagesTab';import ServicesTab from '../components/serverdetail/ServicesTab';import SystemStatusCard from '../components/serverdetail/SystemStatusCard';import OnboardingWizard from '../components/server/OnboardingWizard';+import ProxyStackPanel from '../components/proxy/ProxyStackPanel';import RemoteAccess from '../pages/RemoteAccess';import EmptyState from '../components/EmptyState';import { BellRing, Boxes, Container, Clock3, Cloud } from 'lucide-react';@@ -57,7 +58,7 @@ const ServerDetail = () => {const [securityAlerts, setSecurityAlerts] = useState([]);const toast = useToast();- const validTabs = ['overview', 'docker', 'cron', 'cloudflared', 'packages', 'services', 'metrics', 'alerts', 'remote-access', 'settings'];+ const validTabs = ['overview', 'docker', 'proxy', 'cron', 'cloudflared', 'packages', 'services', 'metrics', 'alerts', 'remote-access', 'settings'];const activeTab = validTabs.includes(tab) ? tab : 'overview';const loadServer = useCallback(async () => {@@ -238,6 +239,7 @@ const ServerDetail = () => {const tabs = [{ id: 'overview', label: 'Overview' },{ id: 'docker', label: 'Docker' },+ { id: 'proxy', label: 'Proxy' },...(server.capabilities?.cron ? [{ id: 'cron', label: 'Cron' }] : []),...(server.capabilities?.cloudflared ? [{ id: 'cloudflared', label: 'Tunnels' }] : []),...(server.capabilities?.packages ? [{ id: 'packages', label: 'Packages' }] : []),@@ -346,6 +348,9 @@ const ServerDetail = () => {<TabsContent value="docker"><DockerTab serverId={id} serverStatus={server.status} server={server} /></TabsContent>+ <TabsContent value="proxy">+ <ProxyStackPanel serverId={id} />+ </TabsContent>{server.capabilities?.cron && (<TabsContent value="cron"><CronTab serverId={id} serverStatus={server.status} />diff --git a/frontend/src/pages/SharedVariables.jsx b/frontend/src/pages/SharedVariables.jsxnew file mode 100644index 00000000..54bcb862--- /dev/null+++ b/frontend/src/pages/SharedVariables.jsx@@ -0,0 +1,18 @@+import SharedVariableGroups from '../components/shared/SharedVariableGroups';++/**+ * SharedVariables — workspace-scoped management of shared variable groups+ * (the polymorphic facade: groups of variables that attach to any resource).+ * Scoped to the active workspace from localStorage; falls back to 'default'.+ */+const SharedVariables = () => {+ const workspaceId = localStorage.getItem('active_workspace_id') || 'default';++ return (+ <div className="page-container shared-variables-page">+ <SharedVariableGroups scopeType="workspace" scopeId={workspaceId} />+ </div>+ );+};++export default SharedVariables;diff --git a/frontend/src/services/api/index.js b/frontend/src/services/api/index.jsindex 5b7529f7..f8d989af 100644--- a/frontend/src/services/api/index.js+++ b/frontend/src/services/api/index.js@@ -27,6 +27,10 @@ import * as backupProtectionMethods from './backupProtection.js';import * as containerStatusMethods from './containerStatus.js';import * as buildpackMethods from './buildpacks.js';import * as snapshotMethods from './snapshots.js';+import * as projectMethods from './projects.js';+import * as sharedResourceMethods from './sharedResources.js';+import * as previewMethods from './previews.js';+import * as proxyMethods from './proxy.js';class ApiService extends ApiClient {constructor() {@@ -61,6 +65,10 @@ class ApiService extends ApiClient {containerStatusMethods,buildpackMethods,snapshotMethods,+ projectMethods,+ sharedResourceMethods,+ previewMethods,+ proxyMethods,];for (const mod of modules) {for (const [key, fn] of Object.entries(mod)) {diff --git a/frontend/src/services/api/previews.js b/frontend/src/services/api/previews.jsnew file mode 100644index 00000000..ce6aa494--- /dev/null+++ b/frontend/src/services/api/previews.js@@ -0,0 +1,26 @@+// PR Preview Environments — per-app preview list, settings, and lifecycle ops.+// Mounted under /apps on the backend.++export async function getPreviews(appId) {+ return this.request(`/apps/${appId}/previews`);+}++export async function getPreviewSettings(appId) {+ return this.request(`/apps/${appId}/previews/settings`);+}++export async function updatePreviewSettings(appId, body) {+ return this.request(`/apps/${appId}/previews/settings`, { method: 'PUT', body });+}++export async function syncPreviews(appId) {+ return this.request(`/apps/${appId}/previews/sync`, { method: 'POST' });+}++export async function redeployPreview(appId, previewId) {+ return this.request(`/apps/${appId}/previews/${previewId}/redeploy`, { method: 'POST' });+}++export async function destroyPreview(appId, previewId) {+ return this.request(`/apps/${appId}/previews/${previewId}`, { method: 'DELETE' });+}diff --git a/frontend/src/services/api/projects.js b/frontend/src/services/api/projects.jsnew file mode 100644index 00000000..8c23663a--- /dev/null+++ b/frontend/src/services/api/projects.js@@ -0,0 +1,64 @@+// Projects & Environments (Workspace -> Project -> Environment -> Applications)+//+// Project endpoints are workspace-scoped; the active workspace is derived from+// the X-Workspace-Id header the client already sends, so these methods don't+// need to pass it explicitly.++// --- Projects ---++export async function getProjects() {+ return this.request('/projects');+}++export async function getProject(id) {+ return this.request(`/projects/${id}`);+}++export async function createProject(data) {+ return this.request('/projects', {+ method: 'POST',+ body: data,+ });+}++export async function updateProject(id, data) {+ return this.request(`/projects/${id}`, {+ method: 'PUT',+ body: data,+ });+}++export async function deleteProject(id) {+ return this.request(`/projects/${id}`, {+ method: 'DELETE',+ });+}++// --- Environments ---++export async function createEnvironment(projectId, data) {+ return this.request('/environments', {+ method: 'POST',+ body: { project_id: projectId, ...data },+ });+}++export async function updateEnvironment(environmentId, data) {+ return this.request(`/environments/${environmentId}`, {+ method: 'PUT',+ body: data,+ });+}++export async function deleteEnvironment(environmentId) {+ return this.request(`/environments/${environmentId}`, {+ method: 'DELETE',+ });+}++export async function reorderEnvironments(projectId, orderedIds) {+ return this.request('/environments/reorder', {+ method: 'POST',+ body: { project_id: projectId, ordered_ids: orderedIds },+ });+}diff --git a/frontend/src/services/api/proxy.js b/frontend/src/services/api/proxy.jsnew file mode 100644index 00000000..10865676--- /dev/null+++ b/frontend/src/services/api/proxy.js@@ -0,0 +1,37 @@+// Managed reverse-proxy stack (opt-in Traefik/Caddy as a Compose stack).+// Host nginx stays the default. Mounted by the backend at /api/v1/servers,+// so paths are /servers/<id>/proxy*.++export async function getServerProxy(serverId) {+ return this.request(`/servers/${serverId}/proxy`);+}++export async function getServerProxyComposePreview(serverId, options = {}) {+ const params = new URLSearchParams();+ if (options.proxyType) params.set('proxy_type', options.proxyType);+ if (options.acmeEmail) params.set('acme_email', options.acmeEmail);+ if (options.dashboard) params.set('dashboard', '1');+ const qs = params.toString();+ return this.request(`/servers/${serverId}/proxy/compose-preview${qs ? `?${qs}` : ''}`);+}++export async function configureServerProxy(serverId, data) {+ return this.request(`/servers/${serverId}/proxy/configure`, {+ method: 'POST',+ body: data,+ });+}++export async function regenerateServerProxy(serverId, data = {}) {+ return this.request(`/servers/${serverId}/proxy/regenerate`, {+ method: 'POST',+ body: data,+ });+}++export async function switchServerProxy(serverId, proxyType) {+ return this.request(`/servers/${serverId}/proxy/switch`, {+ method: 'POST',+ body: { proxy_type: proxyType },+ });+}diff --git a/frontend/src/services/api/sharedResources.js b/frontend/src/services/api/sharedResources.jsnew file mode 100644index 00000000..9e4aad54--- /dev/null+++ b/frontend/src/services/api/sharedResources.js@@ -0,0 +1,126 @@+// Polymorphic shared resources: tags + shared variable groups.+// Mounts under /shared on the backend (/api/v1/shared).++// ----------------------------------------------------------------- metadata++export async function getSharedResourceTypes() {+ return this.request('/shared/resource-types');+}++// --------------------------------------------------------------------- tags++export async function listResourceTags(resourceType, resourceId) {+ const params = new URLSearchParams({+ resource_type: resourceType,+ resource_id: String(resourceId),+ });+ return this.request(`/shared/tags?${params.toString()}`);+}++export async function listResourcesByTag(tag, resourceType = null) {+ const params = new URLSearchParams({ tag });+ if (resourceType) params.set('resource_type', resourceType);+ return this.request(`/shared/tags?${params.toString()}`);+}++export async function addResourceTag(resourceType, resourceId, tag) {+ return this.request('/shared/tags', {+ method: 'POST',+ body: { resource_type: resourceType, resource_id: String(resourceId), tag },+ });+}++export async function removeResourceTag(resourceType, resourceId, tag) {+ return this.request('/shared/tags', {+ method: 'DELETE',+ body: { resource_type: resourceType, resource_id: String(resourceId), tag },+ });+}++// --------------------------------------------------------- variable groups++export async function listVariableGroups(scopeType = null, scopeId = null) {+ const params = new URLSearchParams();+ if (scopeType) params.set('scope_type', scopeType);+ if (scopeId != null) params.set('scope_id', String(scopeId));+ const qs = params.toString();+ return this.request(`/shared/variable-groups${qs ? `?${qs}` : ''}`);+}++export async function getVariableGroup(groupId) {+ return this.request(`/shared/variable-groups/${groupId}`);+}++export async function createVariableGroup({ scopeType, scopeId, name, description = null }) {+ return this.request('/shared/variable-groups', {+ method: 'POST',+ body: {+ scope_type: scopeType,+ scope_id: String(scopeId),+ name,+ description,+ },+ });+}++export async function updateVariableGroup(groupId, { name, description } = {}) {+ return this.request(`/shared/variable-groups/${groupId}`, {+ method: 'PUT',+ body: { name, description },+ });+}++export async function deleteVariableGroup(groupId) {+ return this.request(`/shared/variable-groups/${groupId}`, { method: 'DELETE' });+}++// ----------------------------------------------- variables within a group++export async function addGroupVariable(groupId, { key, value = '', isSecret = false }) {+ return this.request(`/shared/variable-groups/${groupId}/variables`, {+ method: 'POST',+ body: { key, value, is_secret: isSecret },+ });+}++export async function updateGroupVariable(groupId, variableId, { value, isSecret } = {}) {+ const body = {};+ if (value !== undefined) body.value = value;+ if (isSecret !== undefined) body.is_secret = isSecret;+ return this.request(`/shared/variable-groups/${groupId}/variables/${variableId}`, {+ method: 'PUT',+ body,+ });+}++export async function deleteGroupVariable(groupId, variableId) {+ return this.request(`/shared/variable-groups/${groupId}/variables/${variableId}`, {+ method: 'DELETE',+ });+}++// ----------------------------------------------------------------- attach++export async function attachVariableGroup(groupId, resourceType, resourceId) {+ return this.request(`/shared/variable-groups/${groupId}/attach`, {+ method: 'POST',+ body: { resource_type: resourceType, resource_id: String(resourceId) },+ });+}++export async function detachVariableGroup(groupId, resourceType, resourceId) {+ return this.request(`/shared/variable-groups/${groupId}/detach`, {+ method: 'POST',+ body: { resource_type: resourceType, resource_id: String(resourceId) },+ });+}++// ---------------------------------------------------------------- resolved++export async function getResolvedVariables(resourceType, resourceId) {+ const params = new URLSearchParams({+ resource_type: resourceType,+ resource_id: String(resourceId),+ });+ return this.request(`/shared/resolved?${params.toString()}`);+}diff --git a/frontend/src/styles/components/_previews.scss b/frontend/src/styles/components/_previews.scssnew file mode 100644index 00000000..b5e8c14f--- /dev/null+++ b/frontend/src/styles/components/_previews.scss@@ -0,0 +1,194 @@+// ============================================+// PR PREVIEW ENVIRONMENTS+// ============================================++.preview-list {+ display: flex;+ flex-direction: column;+ gap: $space-5;+}++.preview-settings {+ background: $bg-card;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ padding: $space-5;++ &__header {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: $space-4;+ flex-wrap: wrap;+ }++ &__title {+ display: flex;+ align-items: flex-start;+ gap: $space-3;++ svg {+ color: $accent-primary;+ flex-shrink: 0;+ margin-top: 2px;+ }++ h3 {+ margin: 0 0 $space-1;+ font-size: $font-size-lg;+ font-weight: 500;+ color: $text-primary;+ }+ }++ &__hint {+ margin: 0;+ color: $text-secondary;+ font-size: $font-size-sm;+ line-height: 1.5;++ code {+ font-family: $font-mono;+ font-size: $font-size-xs;+ background: $bg-tertiary;+ padding: 1px 5px;+ border-radius: $radius-sm;+ color: $text-primary;+ }+ }++ &__toggle {+ display: flex;+ align-items: center;+ gap: $space-2;+ flex-shrink: 0;+ }++ &__template {+ margin-top: $space-4;+ padding-top: $space-4;+ border-top: 1px solid $border-subtle;+ display: flex;+ flex-direction: column;+ gap: $space-2;+ }++ &__template-row {+ display: flex;+ gap: $space-2;+ align-items: center;++ input {+ flex: 1;+ font-family: $font-mono;+ font-size: $font-size-sm;+ }+ }+}++.preview-list__toolbar {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: $space-3;++ h4 {+ margin: 0;+ font-size: $font-size-md;+ font-weight: 500;+ color: $text-primary;+ }++ .spin {+ animation: preview-spin 0.9s linear infinite;+ }+}++.preview-list__items {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: $space-3;+}++.preview-item {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: $space-4;+ background: $bg-card;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ padding: $space-4;+ flex-wrap: wrap;++ &__main {+ display: flex;+ flex-direction: column;+ gap: $space-2;+ min-width: 0;+ flex: 1;+ }++ &__title {+ display: flex;+ align-items: center;+ gap: $space-2;+ flex-wrap: wrap;+ }++ &__pr {+ font-family: $font-mono;+ font-size: $font-size-sm;+ font-weight: 600;+ color: $text-primary;+ }++ &__name {+ color: $text-secondary;+ font-size: $font-size-sm;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ max-width: 360px;+ }++ &__meta {+ display: flex;+ align-items: center;+ gap: $space-3;+ flex-wrap: wrap;+ font-size: $font-size-xs;+ }++ &__branch,+ &__sha {+ color: $text-tertiary;+ background: $bg-tertiary;+ padding: 1px 6px;+ border-radius: $radius-sm;+ }++ &__url {+ color: $accent-primary;+ text-decoration: none;+ word-break: break-all;++ &:hover {+ text-decoration: underline;+ }+ }++ &__actions {+ display: flex;+ align-items: center;+ gap: $space-1;+ flex-shrink: 0;+ }+}++@keyframes preview-spin {+ to { transform: rotate(360deg); }+}diff --git a/frontend/src/styles/components/_proxy.scss b/frontend/src/styles/components/_proxy.scssnew file mode 100644index 00000000..f4cb8a1a--- /dev/null+++ b/frontend/src/styles/components/_proxy.scss@@ -0,0 +1,101 @@+// Managed reverse-proxy stack panel (ProxyStackPanel.jsx).+// Server detail "Proxy" tab: type selector, compose preview, custom snippet.++.proxy-panel {+ display: flex;+ flex-direction: column;+ gap: $space-5;++ &__header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: $space-3;+ }++ &__title {+ display: flex;+ align-items: center;+ gap: $space-2;++ h3 {+ margin: 0;+ font-size: $font-size-lg;+ font-weight: $font-weight-semibold;+ color: $text-primary;+ }+ }++ &__status {+ display: flex;+ align-items: center;+ gap: $space-2;+ }++ &__status-label {+ font-size: $font-size-xs;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: $text-tertiary;+ }++ &__hint {+ margin: 0;+ font-size: $font-size-sm;+ color: $text-secondary;+ line-height: 1.5;+ }++ &__section {+ display: flex;+ flex-direction: column;+ gap: $space-3;+ padding: $space-4;+ background: $bg-card;+ border: 1px solid $border-subtle;+ border-radius: $radius-lg;+ }++ &__label {+ font-size: $font-size-sm;+ font-weight: $font-weight-semibold;+ color: $text-secondary;+ }++ &__actions {+ display: flex;+ flex-wrap: wrap;+ gap: $space-2;+ }++ &__code {+ margin: 0;+ max-height: 360px;+ overflow: auto;+ padding: $space-3;+ background: $bg-body;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ font-family: $font-mono;+ font-size: $font-size-xs;+ line-height: 1.5;+ color: $text-secondary;+ white-space: pre;+ }++ &__empty {+ padding: $space-3;+ font-size: $font-size-sm;+ color: $text-tertiary;+ }++ &__error {+ padding: $space-3;+ margin-bottom: $space-3;+ background: $danger-bg;+ border: 1px solid $danger-border;+ border-radius: $radius-md;+ color: $danger-color;+ font-size: $font-size-sm;+ }+}diff --git a/frontend/src/styles/components/_shared-resources.scss b/frontend/src/styles/components/_shared-resources.scssnew file mode 100644index 00000000..c7e4dc9f--- /dev/null+++ b/frontend/src/styles/components/_shared-resources.scss@@ -0,0 +1,357 @@+// ============================================+// SHARED RESOURCES — tags + shared variable groups (facade layer)+// ============================================++// ---------- Tags panel ----------++.shared-tags {+ display: flex;+ flex-direction: column;+ gap: $space-3;++ &__list {+ display: flex;+ flex-wrap: wrap;+ gap: $space-2;+ align-items: center;+ }++ &__hint {+ color: $text-tertiary;+ font-size: $font-size-sm;+ }++ &__add {+ display: flex;+ gap: $space-2;+ align-items: center;+ }++ &__input {+ max-width: 220px;+ }+}++.shared-tag {+ display: inline-flex;+ align-items: center;+ gap: $space-1;+ background: $bg-hover;+ border: 1px solid $border-subtle;+ border-radius: $radius-sm;+ padding: $space-1 $space-2;+ font-size: $font-size-sm;+ color: $text-secondary;++ &__label {+ font-family: $font-mono;+ }++ &__remove {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 16px;+ height: 16px;+ background: transparent;+ border: none;+ border-radius: $radius-sm;+ color: $text-tertiary;+ cursor: pointer;+ font-size: 16px;+ line-height: 1;+ transition: color 0.15s, background 0.15s;++ &:hover {+ color: $danger;+ background: fade($danger, 18%);+ }+ }+}++// ---------- Resolved variables panel (read-mostly facade) ----------++.shared-vars-panel {+ display: flex;+ flex-direction: column;+ gap: $space-3;++ &--loading {+ color: $text-tertiary;+ font-size: $font-size-sm;+ padding: $space-6;+ }++ &__header {+ display: flex;+ justify-content: space-between;+ align-items: baseline;++ h3 {+ margin: 0;+ }+ }++ &__count {+ color: $text-tertiary;+ font-size: $font-size-sm;+ }++ &__hint {+ color: $text-tertiary;+ font-size: $font-size-sm;+ margin: 0;+ }++ &__filter input {+ width: 100%;+ padding: $space-2 $space-3;+ background: $bg-body;+ border: 1px solid $border-subtle;+ border-radius: $radius-sm;+ color: $text-primary;+ font-size: $font-size-sm;++ &::placeholder {+ color: $text-tertiary;+ }+ }++ &__empty {+ text-align: center;+ padding: $space-8;+ color: $text-tertiary;+ background: $bg-card;+ border: 1px dashed $border-subtle;+ border-radius: $radius-md;+ font-size: $font-size-sm;+ }+}++// Shared variables table (used in the resolved panel and the group detail)++.shared-vars-table {+ width: 100%;+ border-collapse: collapse;+ font-size: $font-size-sm;++ th,+ td {+ text-align: left;+ padding: $space-2 $space-3;+ border-bottom: 1px solid $border-subtle;+ vertical-align: middle;+ }++ th {+ color: $text-tertiary;+ font-weight: 600;+ font-size: $font-size-xs;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ }++ &__key {+ font-family: $font-mono;+ font-weight: 600;+ color: $text-primary;+ }++ &__value {+ font-family: $font-mono;+ color: $text-secondary;+ word-break: break-all;+ }++ &__group {+ color: $text-tertiary;+ }++ tr.is-secret &__key {+ border-left: 2px solid $warning;+ padding-left: $space-2;+ }+}++// ---------- Shared variable groups manager ----------++.shared-groups {+ &__layout {+ display: grid;+ grid-template-columns: 280px 1fr;+ gap: $space-4;+ align-items: start;++ @media (max-width: 720px) {+ grid-template-columns: 1fr;+ }+ }++ &__sidebar {+ display: flex;+ flex-direction: column;+ gap: $space-4;+ }++ &__create {+ display: flex;+ flex-direction: column;+ gap: $space-2;+ padding: $space-3;+ background: $bg-card;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ }++ &__list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: $space-2;+ }++ &__hint {+ color: $text-tertiary;+ font-size: $font-size-sm;+ }++ &__item {+ padding: $space-3;+ background: $bg-card;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ cursor: pointer;+ transition: border-color 0.15s;++ &:hover {+ border-color: $border-active;+ }++ &.is-active {+ border-color: $accent-primary;+ }++ &-name {+ font-weight: 600;+ color: $text-primary;+ }++ &-meta {+ color: $text-tertiary;+ font-size: $font-size-xs;+ margin-top: $space-1;+ }+ }++ &__detail {+ display: flex;+ flex-direction: column;+ gap: $space-4;+ padding: $space-4;+ background: $bg-card;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ min-height: 200px;+ }++ &__empty {+ color: $text-tertiary;+ font-size: $font-size-sm;+ text-align: center;+ padding: $space-8;+ }++ &__detail-header {+ display: flex;+ justify-content: space-between;+ align-items: flex-start;+ gap: $space-4;++ h3 {+ margin: 0;+ }+ }++ &__desc {+ color: $text-tertiary;+ font-size: $font-size-sm;+ margin: $space-1 0 0;+ }++ &__subhead {+ margin: 0;+ color: $text-secondary;+ font-size: $font-size-sm;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ }++ &__add-var,+ &__attach {+ display: flex;+ gap: $space-2;+ align-items: center;+ flex-wrap: wrap;+ }++ &__var-key {+ width: 160px;+ font-family: $font-mono;+ text-transform: uppercase;+ }++ &__var-value {+ flex: 1;+ min-width: 140px;+ }++ &__secret {+ display: inline-flex;+ align-items: center;+ gap: $space-1;+ color: $text-tertiary;+ font-size: $font-size-sm;+ }++ &__attach-type,+ &__attach-id {+ padding: $space-2 $space-3;+ background: $bg-body;+ border: 1px solid $border-subtle;+ border-radius: $radius-sm;+ color: $text-primary;+ font-size: $font-size-sm;+ }++ &__attach-id {+ flex: 1;+ min-width: 140px;+ }++ &__attachments {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: $space-2;+ }++ &__attachment {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: $space-2 $space-3;+ background: $bg-hover;+ border: 1px solid $border-subtle;+ border-radius: $radius-sm;++ &-label {+ font-family: $font-mono;+ font-size: $font-size-sm;+ color: $text-secondary;+ }+ }+}diff --git a/frontend/src/styles/main.scss b/frontend/src/styles/main.scssindex 727ee2fc..ce8ed525 100644--- a/frontend/src/styles/main.scss+++ b/frontend/src/styles/main.scss@@ -73,12 +73,16 @@@import 'components/onboarding-wizard';@import 'components/buildpack';@import 'components/deployments';+@import 'components/shared-resources';+@import 'components/previews';+@import 'components/proxy';// --------------------------------------------// 5. PAGE-SPECIFIC STYLES// --------------------------------------------@import 'pages/_auth';@import 'pages/_dashboard';+@import 'pages/projects';@import 'pages/_applications';@import 'pages/_docker';@import 'pages/_databases';diff --git a/frontend/src/styles/pages/_projects.scss b/frontend/src/styles/pages/_projects.scssnew file mode 100644index 00000000..190e4033--- /dev/null+++ b/frontend/src/styles/pages/_projects.scss@@ -0,0 +1,365 @@+// ============================================+// PROJECTS — Workspace → Project → Environment → Applications+// Card grid of projects + a per-project detail view with environment tabs.+// Visual language mirrors the other infra pages (PageTopbar + card grid).+// ============================================++.projects-page {+ display: flex;+ flex-direction: column;+ min-height: 100%;++ &__body {+ padding: $space-6;+ display: flex;+ flex-direction: column;+ gap: $space-6;+ }+}++.projects-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));+ gap: $space-4;+}++.project-card {+ display: flex;+ flex-direction: column;+ gap: $space-3;+ padding: $space-5;+ background: $bg-card;+ border: 1px solid $border-subtle;+ border-radius: $radius-lg;+ text-decoration: none;+ color: inherit;+ transition: border-color $transition-fast, transform $transition-fast,+ box-shadow $transition-fast;++ &:hover {+ border-color: $border-active;+ transform: translateY(-2px);+ box-shadow: $shadow-md;+ }++ &__header {+ display: flex;+ align-items: center;+ gap: $space-3;+ }++ &__icon {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 38px;+ height: 38px;+ border-radius: $radius-md;+ background: $bg-hover;+ color: $accent-primary;+ flex-shrink: 0;+ }++ &__titles {+ min-width: 0;+ }++ &__name {+ margin: 0;+ font-size: $font-size-md;+ font-weight: $font-weight-semibold;+ color: $text-primary;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ &__slug {+ display: block;+ font-size: $font-size-xs;+ color: $text-tertiary;+ font-family: $font-mono;+ }++ &__description {+ margin: 0;+ font-size: $font-size-sm;+ color: $text-secondary;+ line-height: 1.5;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+ }++ &__stats {+ display: flex;+ gap: $space-4;+ margin-top: auto;+ padding-top: $space-2;+ }++ &__stat {+ display: inline-flex;+ align-items: center;+ gap: $space-1;+ font-size: $font-size-xs;+ color: $text-tertiary;++ svg {+ color: $text-tertiary;+ }+ }+}++// Muted "(optional)" hint on the New Service project selector (this feature's+// addition to that form; styled here to stay within the projects feature files).+.new-service-page__optional {+ color: $text-tertiary;+ font-weight: $font-weight-normal;+}++// ---- Create dialogs (shared by Projects + ProjectDetail) ----+.projects-form {+ display: flex;+ flex-direction: column;+ gap: $space-4;+ padding: $space-4 0;++ &__field {+ display: flex;+ flex-direction: column;+ gap: $space-2;+ }+}++// ============================================+// PROJECT DETAIL+// ============================================+.project-detail-page {+ display: flex;+ flex-direction: column;+ min-height: 100%;++ &__body {+ padding: $space-6;+ display: flex;+ flex-direction: column;+ gap: $space-5;+ }++ &__description {+ margin: 0;+ font-size: $font-size-sm;+ color: $text-secondary;+ max-width: 70ch;+ }+}++.project-env-tabs {+ display: flex;+ flex-wrap: wrap;+ gap: $space-2;+ border-bottom: 1px solid $border-subtle;+ padding-bottom: $space-3;+}++.project-env-tab {+ display: inline-flex;+ align-items: center;+ gap: $space-1;+ padding: $space-1 $space-2 $space-1 $space-3;+ background: $bg-card;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ transition: border-color $transition-fast, background $transition-fast;++ &.is-active {+ border-color: $accent-primary;+ background: $bg-hover;+ }++ &__label {+ display: inline-flex;+ align-items: center;+ gap: $space-2;+ background: none;+ border: none;+ cursor: pointer;+ font-size: $font-size-sm;+ font-weight: $font-weight-medium;+ color: $text-primary;+ padding: 0;+ }++ &__count {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ min-width: 20px;+ height: 20px;+ padding: 0 6px;+ border-radius: 999px;+ background: $bg-hover;+ color: $text-secondary;+ font-size: $font-size-xs;+ font-weight: $font-weight-semibold;+ }++ &__controls {+ display: inline-flex;+ align-items: center;+ gap: 2px;+ margin-left: $space-1;++ button {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 22px;+ height: 22px;+ background: none;+ border: none;+ border-radius: $radius-sm;+ color: $text-tertiary;+ cursor: pointer;+ transition: background $transition-fast, color $transition-fast;++ &:hover:not(:disabled) {+ background: $bg-hover;+ color: $text-primary;+ }++ &:disabled {+ opacity: 0.35;+ cursor: not-allowed;+ }+ }+ }++ &__delete:hover:not(:disabled) {+ color: $danger !important;+ }+}++.project-env-panel {+ display: flex;+ flex-direction: column;+ gap: $space-4;++ &__header {+ display: flex;+ align-items: baseline;+ gap: $space-3;++ h2 {+ margin: 0;+ font-size: $font-size-lg;+ font-weight: $font-weight-semibold;+ color: $text-primary;+ }++ span {+ font-size: $font-size-sm;+ color: $text-tertiary;+ }+ }+}++.project-unassigned {+ display: flex;+ flex-direction: column;+ gap: $space-3;+ padding-top: $space-4;+ border-top: 1px dashed $border-subtle;++ &__header {+ display: flex;+ align-items: center;+ gap: $space-2;++ h3 {+ margin: 0;+ font-size: $font-size-sm;+ font-weight: $font-weight-semibold;+ color: $text-secondary;+ }++ span {+ font-size: $font-size-xs;+ color: $text-tertiary;+ }+ }+}++.project-app-list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: $space-1;+}++.project-app-row {+ display: flex;+ align-items: center;+ gap: $space-3;+ padding: $space-3 $space-4;+ background: $bg-card;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;++ &__status {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: $text-tertiary;+ flex-shrink: 0;++ &--running { background: $success; }+ &--stopped { background: $text-tertiary; }+ &--error { background: $danger; }+ &--deploying { background: $warning; }+ }++ &__name {+ font-weight: $font-weight-medium;+ color: $text-primary;+ text-decoration: none;++ &:hover { color: $accent-primary; }+ }++ &__type {+ font-size: $font-size-xs;+ color: $text-tertiary;+ font-family: $font-mono;+ }++ &__link {+ margin-left: auto;+ color: $text-tertiary;+ display: inline-flex;++ &:hover { color: $accent-primary; }+ }+}++// Local status pill so the row is self-contained (mirrors the shared pill).+.project-detail-page .status-pill {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 2px 10px;+ border-radius: 999px;+ font-size: $font-size-xs;+ font-weight: $font-weight-medium;+ text-transform: capitalize;+ background: $bg-hover;+ color: $text-secondary;++ &--running { color: $success; }+ &--error { color: $danger; }+ &--deploying { color: $warning; }+}