From 3de85c2a17cec0b33e603500cc49a3c9728582f1 Mon Sep 17 00:00:00 2001 From: Max Freedom Pollard <272618364+MaxFreedomPollard@users.noreply.github.com> Date: Sat, 24 Oct 2026 01:27:36 -0700 Subject: [PATCH 01/34] fix(security): honour the failed-login time window (#180) check_failed_logins computed a cutoff from since_hours and never used it, so the Security -> Events "Failed login attempts (24h)" card and its alert counted every failure still in /var/log/auth.log or /var/log/secure: up to a week of SSH attempts under the usual weekly log rotation. Each matching line is now dated from its stamp, either RFC 3339 (rsyslog's high-precision format) or the traditional BSD syslog stamp (no year, so a December line read in January is placed in the previous year), and lines older than the cutoff are skipped. A line whose stamp is not recognised is still counted rather than hidden. The log paths move to SecurityService.AUTH_LOGS so the tests can point at a temp file. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 5 + backend/app/services/security_service.py | 62 +++++++++- backend/tests/test_failed_logins_window.py | 132 +++++++++++++++++++++ 3 files changed, 193 insertions(+), 6 deletions(-) create mode 100644 backend/tests/test_failed_logins_window.py diff --git a/CHANGELOG.md b/CHANGELOG.md index fc27411a..27e2f9df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -96,6 +96,11 @@ release history; historical `agent-v*` tags are not panel releases. Scanner custom-path scan, #144). Blueprint registration now waives Flask's setup guard for the duration of the call, which is safe in the panel's single-worker threaded deployment. +- Count only the requested window in the failed-login check. The Security → + Events card "Failed login attempts (24h)" and its alert counted every + failure still in the auth log, which under the usual weekly log rotation is + up to a week of SSH attempts, so the number was inflated and the alert kept + firing on old attempts. ## [1.11.4] - 2026-09-12 diff --git a/backend/app/services/security_service.py b/backend/app/services/security_service.py index 59f72c69..fc2db6a1 100644 --- a/backend/app/services/security_service.py +++ b/backend/app/services/security_service.py @@ -15,6 +15,7 @@ serverkit-image-scan. """ import os +import re import json import shlex import hashlib @@ -30,6 +31,19 @@ from app.utils.system import ( run_privileged, ) +# The two stamps an auth log line starts with. RFC 3339 is rsyslog's +# high-precision format, the default on recent Ubuntu releases: +# "2026-10-22T09:15:02.123456+02:00". The traditional BSD stamp, still written +# on Debian and the RHEL family and by syslog-ng, is local time with no year: +# "Oct 2 09:15:02". Its month names are English whatever the locale, so they +# are matched by hand rather than through strptime's %b. +_RFC3339_STAMP_RE = re.compile(r'^(\d{4}-\d{2}-\d{2}T\S+)\s') +_BSD_STAMP_RE = re.compile(r'^([A-Z][a-z]{2}) {1,2}(\d{1,2}) (\d{2}):(\d{2}):(\d{2})\s') +_SYSLOG_MONTHS = {m: i for i, m in enumerate( + ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'), start=1)} + + class SecurityService: """Service for security scanning and monitoring.""" @@ -38,6 +52,8 @@ class SecurityService: INTEGRITY_DB = os.path.join(CONFIG_DIR, 'file_integrity.json') SCAN_LOG = os.path.join(paths.SERVERKIT_LOG_DIR, 'security_scans.log') ALERTS_LOG = os.path.join(paths.SERVERKIT_LOG_DIR, 'security_alerts.log') + # Where sshd/PAM failures land: Debian family, then the RHEL family. + AUTH_LOGS = ('/var/log/auth.log', '/var/log/secure') # Scan status tracking _current_scan = None @@ -227,14 +243,42 @@ class SecurityService: # ========================================== # SUSPICIOUS ACTIVITY DETECTION # ========================================== + @staticmethod + def _auth_log_time(line: str, now: datetime) -> Optional[datetime]: + """When an auth log line was written, as naive local time, or None + when its stamp is neither of the two rsyslog writes by default. + + The BSD stamp has no year, so it takes ``now``'s and steps back one + when that would put the line more than a day in the future, as a + December line read in January would be. + """ + match = _RFC3339_STAMP_RE.match(line) + if match: + try: + stamp = datetime.fromisoformat(match.group(1)) + except ValueError: + return None + return stamp.astimezone().replace(tzinfo=None) + + match = _BSD_STAMP_RE.match(line) + if not match or match.group(1) not in _SYSLOG_MONTHS: + return None + month = _SYSLOG_MONTHS[match.group(1)] + day, hour, minute, second = (int(part) for part in match.groups()[1:]) + try: + stamp = datetime(now.year, month, day, hour, minute, second) + if stamp > now + timedelta(days=1): + stamp = stamp.replace(year=now.year - 1) + except ValueError: # Feb 29 outside a leap year, or a garbled stamp + return None + return stamp + @classmethod def check_failed_logins(cls, since_hours: int = 24) -> Dict: - """Check for failed login attempts.""" + """Count failed logins in the auth log over the last ``since_hours``.""" try: - # Check auth.log or secure log - log_files = ['/var/log/auth.log', '/var/log/secure'] log_file = None - for lf in log_files: + for lf in cls.AUTH_LOGS: if os.path.exists(lf): log_file = lf break @@ -242,13 +286,19 @@ class SecurityService: if not log_file: return {'success': False, 'error': 'Auth log not found'} - cutoff_time = datetime.now() - timedelta(hours=since_hours) + now = datetime.now() + cutoff_time = now - timedelta(hours=since_hours) failed_attempts = [] with open(log_file, 'r') as f: for line in f: if 'Failed password' in line or 'authentication failure' in line.lower(): - # Parse the log line to extract IP and user + # A line whose stamp cannot be read is kept rather + # than dropped: it may be recent, and leaving it out + # would hide failures instead of counting them. + written = cls._auth_log_time(line, now) + if written is not None and written < cutoff_time: + continue failed_attempts.append(line.strip()) config = cls.get_config() diff --git a/backend/tests/test_failed_logins_window.py b/backend/tests/test_failed_logins_window.py new file mode 100644 index 00000000..f8eb2ae3 --- /dev/null +++ b/backend/tests/test_failed_logins_window.py @@ -0,0 +1,132 @@ +"""SecurityService.check_failed_logins must count only its time window. + +The Security -> Events tab asks for the last 24 hours of failed logins +(``GET /api/v1/security/failed-logins?hours=24``), shows the number under +"Failed login attempts (24h)", and alerts with "... in the last 24 hours" +once it reaches the threshold. check_failed_logins computed the cutoff for +that window and never used it, so every failure still in the current auth +log was counted: on a stock weekly logrotate that is up to a week of SSH +noise, which keeps the alert firing on old attempts. + +These tests write a throwaway auth log with failures on both sides of the +cutoff, in the two timestamp formats rsyslog writes, and point the service +at it. +""" +from datetime import datetime, timedelta + +import pytest + +from app.services.security_service import SecurityService + +MONTHS = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec') + + +def bsd_stamp(when): + """Traditional syslog stamp, local time and no year: 'Oct 2 09:15:02'. + + Built by hand because strftime's %b follows the locale and syslog's + month names do not.""" + return f'{MONTHS[when.month - 1]} {when.day:2d} {when:%H:%M:%S}' + + +def rfc3339_stamp(when): + """rsyslog's high-precision stamp: '2026-10-22T09:15:02.123456+02:00'.""" + return when.astimezone().isoformat(timespec='microseconds') + + +def failure(stamp, n): + return (f'{stamp} web1 sshd[{1000 + n}]: Failed password for root ' + f'from 203.0.113.{n} port {40000 + n} ssh2') + + +@pytest.fixture +def auth_log(tmp_path, monkeypatch): + """A temp auth log the service reads instead of the host's, the default + security config (threshold 5), and alerts captured instead of sent.""" + path = tmp_path / 'auth.log' + monkeypatch.setattr(SecurityService, 'AUTH_LOGS', (str(path),)) + monkeypatch.setattr(SecurityService, 'SECURITY_CONFIG', + str(tmp_path / 'security.json')) + sent = [] + monkeypatch.setattr( + SecurityService, '_send_security_notification', + classmethod(lambda cls, *args, **kwargs: sent.append((args, kwargs)))) + + def write(lines): + path.write_text('\n'.join(lines) + '\n') + + write.sent = sent + return write + + +@pytest.mark.parametrize('stamp', [bsd_stamp, rfc3339_stamp], + ids=['bsd', 'rfc3339']) +def test_failures_older_than_the_window_are_not_counted(auth_log, stamp): + now = datetime.now() + stale = [failure(stamp(now - timedelta(days=days)), n) + for n, days in enumerate((5, 3, 2), start=1)] + recent = [failure(stamp(now - timedelta(hours=hours)), n) + for n, hours in enumerate((2, 1), start=4)] + auth_log(stale + recent) + + result = SecurityService.check_failed_logins(24) + + assert result['success'] is True + assert result['failed_attempts'] == 2 + assert result['recent_failures'] == recent + # Two failures sit under the default threshold of 5. All five lines + # together reach it, which is what used to raise the alert. + assert result['alert_triggered'] is False + assert auth_log.sent == [] + + +def test_the_window_follows_the_hours_requested(auth_log): + now = datetime.now() + auth_log([failure(bsd_stamp(now - timedelta(hours=hours)), n) + for n, hours in enumerate((100, 50, 5), start=1)]) + + assert SecurityService.check_failed_logins(24)['failed_attempts'] == 1 + assert SecurityService.check_failed_logins(72)['failed_attempts'] == 2 + assert SecurityService.check_failed_logins(168)['failed_attempts'] == 3 + + +def test_the_alert_reports_the_count_inside_the_window(auth_log): + now = datetime.now() + stale = [failure(bsd_stamp(now - timedelta(days=3)), n) + for n in range(1, 21)] + recent = [failure(bsd_stamp(now - timedelta(minutes=10 * n)), n) + for n in range(21, 27)] + auth_log(stale + recent) + + result = SecurityService.check_failed_logins(24) + + assert result['failed_attempts'] == 6 + assert result['alert_triggered'] is True + [(args, kwargs)] = auth_log.sent + assert args == ('failed_logins', + 'High number of failed login attempts: 6 in the last 24 hours') + assert kwargs['details'] == {'count': 6} + + +def test_a_december_stamp_read_in_january_is_from_last_year(): + """The traditional stamp has no year. Taking the current one would put + New Year's Eve failures eleven months in the future.""" + new_year = datetime(2027, 1, 1, 0, 30) + + assert SecurityService._auth_log_time( + failure('Dec 31 23:50:07', 1), new_year) == datetime(2026, 12, 31, 23, 50, 7) + assert SecurityService._auth_log_time( + failure('Jan 1 00:10:00', 2), new_year) == datetime(2027, 1, 1, 0, 10) + + +def test_a_line_without_a_recognisable_stamp_is_still_counted(auth_log): + """A custom rsyslog template the parser does not know cannot be placed + in time. Counting it keeps the alert from going quiet on such a host.""" + line = 'web1 sshd[1001]: Failed password for root from 203.0.113.1 port 40001 ssh2' + auth_log([line]) + + result = SecurityService.check_failed_logins(24) + + assert result['failed_attempts'] == 1 + assert result['recent_failures'] == [line] From 4898fccae16055f2323624d0daf40340ea8a7ff5 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 04:30:14 -0400 Subject: [PATCH 02/34] refactor: separate backend startup phases and guard ordering --- backend/app/__init__.py | 539 +-------------------- backend/app/bootstrap/__init__.py | 1 + backend/app/bootstrap/configuration.py | 115 +++++ backend/app/bootstrap/http.py | 101 ++++ backend/app/bootstrap/jobs.py | 51 ++ backend/app/bootstrap/logging.py | 55 +++ backend/app/bootstrap/persistence.py | 75 +++ backend/app/bootstrap/plugins.py | 64 +++ backend/app/bootstrap/runtime.py | 84 ++++ backend/tests/test_bootstrap_boundaries.py | 110 +++++ 10 files changed, 670 insertions(+), 525 deletions(-) create mode 100644 backend/app/bootstrap/__init__.py create mode 100644 backend/app/bootstrap/configuration.py create mode 100644 backend/app/bootstrap/http.py create mode 100644 backend/app/bootstrap/jobs.py create mode 100644 backend/app/bootstrap/logging.py create mode 100644 backend/app/bootstrap/persistence.py create mode 100644 backend/app/bootstrap/plugins.py create mode 100644 backend/app/bootstrap/runtime.py create mode 100644 backend/tests/test_bootstrap_boundaries.py diff --git a/backend/app/__init__.py b/backend/app/__init__.py index ce5dae21..938047e0 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -1,10 +1,7 @@ import os -import sys -from flask import Flask, send_from_directory, request, jsonify -from werkzeug.exceptions import HTTPException +from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_jwt_extended import JWTManager -from flask_cors import CORS from flask_limiter import Limiter from flask_limiter.util import get_remote_address from flask_migrate import Migrate @@ -48,183 +45,24 @@ socketio = None FRONTEND_DIST = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'frontend', 'dist') -# Set once per process: create_app() runs many times in a test session and -# gunicorn imports the module before forking, so an unguarded addHandler would -# duplicate every log line N times. -_logging_configured = False - - -def _configure_logging(app): - """Give the app a real logging setup. - - Services across the codebase call ``logging.getLogger(__name__).warning(...)`` - but nothing ever configured the root logger, so those records fell through to - logging's last-resort handler: WARNING and above only, no timestamp, no - logger name, INFO dropped on the floor. That is why a panel that was failing - to serve its own agent installer (issue #101) produced no diagnostic trail at - all. ``LOG_LEVEL`` overrides the default. - """ - global _logging_configured - - import logging - - level_name = os.environ.get('LOG_LEVEL', '').upper() - if level_name and hasattr(logging, level_name): - level = getattr(logging, level_name) - elif app.config.get('TESTING'): - # TestingConfig sets DEBUG=True, so keying off DEBUG alone would move the - # whole test suite to DEBUG logging as a side effect of adding a handler. - level = logging.INFO - else: - level = logging.DEBUG if app.config.get('DEBUG') else logging.INFO - - from flask.logging import default_handler - - root = logging.getLogger() - root.setLevel(level) - app.logger.setLevel(level) - - # Flask attaches its own handler to app.logger, which ALSO propagates to the - # root logger. Leaving both in place prints every app.logger record twice -- - # once as Flask's `%(module)s` and once as ours as `%(name)s`. Drop Flask's - # and let the single root handler below own the output. - app.logger.removeHandler(default_handler) - - if not _logging_configured: - handler = logging.StreamHandler(sys.stderr) - handler.setFormatter(logging.Formatter( - '[%(asctime)s] %(levelname)s in %(name)s: %(message)s' - )) - root.addHandler(handler) - _logging_configured = True +from app.bootstrap.logging import configure_logging as _configure_logging def create_app(config_name=None): + """Assemble the panel in dependency order; retain public extension exports.""" global socketio + from app.bootstrap.configuration import configure_application + from app.bootstrap.persistence import prepare_persistence + from app.bootstrap.plugins import load_extensions + from app.bootstrap.runtime import start_runtime + from app.bootstrap.http import register_http_handlers if config_name is None: config_name = os.environ.get('FLASK_ENV', 'development') - - # Configure Flask to serve static files from frontend dist - app = Flask( - __name__, - static_folder=FRONTEND_DIST, - static_url_path='' - ) + app = Flask(__name__, static_folder=FRONTEND_DIST, static_url_path='') app.config.from_object(config[config_name]) - _configure_logging(app) - - # Trust the reverse proxy's forwarding headers to derive the real client IP - # (config-gated; default off). ProxyFix rewrites request.remote_addr from the - # rightmost TRUSTED_PROXY_HOPS entries of X-Forwarded-For — the hops our own - # proxies appended — so a client-forged leftmost value is ignored. Applied - # before the limiter and request handlers so every remote_addr consumer - # (flask-limiter's get_remote_address, get_client_ip(), audit logs) benefits. - if app.config.get('TRUST_PROXY_HEADERS'): - from werkzeug.middleware.proxy_fix import ProxyFix - hops = app.config.get('TRUSTED_PROXY_HOPS', 1) - app.wsgi_app = ProxyFix(app.wsgi_app, x_for=hops, x_proto=1, x_host=0, x_port=0) - - # Initialize extensions - db.init_app(app) - from app.middleware.request_profiling import register_request_profiling - register_request_profiling(app, db) - migrate.init_app(app, db) - jwt.init_app(app) - # Storage backend comes from app.config's RATELIMIT_STORAGE_URI when set - # (see config.py); unset = in-memory, correct for the single-worker design. - limiter.init_app(app) - - # SQLite concurrency tuning: the queue-bus consumers, job system and - # metrics collector share one database file with request handling, and in - # the default journal mode any writer locks the WHOLE file — readers - # included — producing sporadic "database is locked" errors under load. - # WAL lets readers coexist with a writer, a generous busy timeout absorbs - # the remaining writer-writer contention, and synchronous=NORMAL is the - # safe pairing for WAL. (journal_mode persists in the database file; the - # per-connection pragmas re-assert it for fresh files.) - if app.config['SQLALCHEMY_DATABASE_URI'].startswith('sqlite') and not app.config.get('TESTING'): - # (Skipped under TESTING: tests/conftest.py owns connection pragmas - # for the test process — journal_mode=MEMORY et al. — and two - # listeners fighting over journal_mode on the same file deadlocks.) - from sqlalchemy import event - - with app.app_context(): - @event.listens_for(db.engine, 'connect') - def _sqlite_tune(dbapi_connection, _record): - cursor = dbapi_connection.cursor() - cursor.execute('PRAGMA journal_mode=WAL') - cursor.execute('PRAGMA busy_timeout=30000') - cursor.execute('PRAGMA synchronous=NORMAL') - cursor.close() - - # Build CORS origins. Start with static config/env, then append the - # persisted canonical domain from system settings so pointing an A record - # at the panel works without restarting to edit .env. - cors_origins = list(app.config['CORS_ORIGINS']) - try: - with app.app_context(): - from app.services.settings_service import SettingsService - from app.utils.domain import canonical_origin - canonical_domain = SettingsService.get('canonical_domain', '') or '' - if canonical_domain: - https_enabled = SettingsService.get('canonical_https_enabled', False) or False - origin = canonical_origin(canonical_domain, https_enabled) - if origin not in cors_origins: - cors_origins.append(origin) - except Exception: - # Database may not exist yet during first install / migrations. - pass - - CORS( - app, - origins=cors_origins, - supports_credentials=True, - allow_headers=[ - 'Content-Type', 'Authorization', 'X-Requested-With', 'X-API-Key', - 'X-Request-ID', - ], - expose_headers=['X-Request-ID'], - methods=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'], - # Every panel request carries an Authorization header, which makes it a - # non-simple cross-origin request: without Access-Control-Max-Age the - # browser re-runs a preflight OPTIONS every few seconds (Chrome's - # default cache is 5s), so a cross-origin panel pays two round trips per - # call forever. One hour is the practical ceiling — Chrome caps the - # value at 2h, Firefox at 24h, and both take the smaller of the two. - max_age=3600, - ) - - # Assign one diagnostic ID at the outer API boundary. Downstream handlers, - # logs and jobs can reuse g.request_id without inventing independent IDs. - from app.middleware.request_id import register_request_id - register_request_id(app) - - # Register security headers middleware - from app.middleware.security import register_security_headers - register_security_headers(app) - - # Demo mode guard — config-gated (default off), blocks mutating API calls - from app.middleware.demo import init_demo_mode - init_demo_mode(app) - - # Register API key authentication middleware - from app.middleware.api_key_auth import register_api_key_auth - register_api_key_auth(app) - - # Register API analytics middleware - from app.middleware.api_analytics import register_api_analytics - register_api_analytics(app) - - # Register fallback audit logging for authenticated mutating API requests - from app.middleware.audit import register_audit_fallback - register_audit_fallback(app) - - # Update rate limiter with custom key function - from app.middleware.rate_limit import get_rate_limit_key, register_rate_limit_headers - limiter._key_func = get_rate_limit_key - register_rate_limit_headers(app) + configure_application(app, db, migrate, jwt, limiter) # Initialize SocketIO from app.sockets import init_socketio @@ -249,361 +87,12 @@ def create_app(config_name=None): from app.services.restore_point_adapters import register_builtin_restore_point_adapters register_builtin_restore_point_adapters() - # Handle database migrations (Alembic) — must run before plugin loader - # since the loader queries the installed_plugins table. with app.app_context(): - from app.services.migration_service import MigrationService - MigrationService.check_and_prepare(app) - - # Initialize default settings and migrate legacy roles - from app.services.settings_service import SettingsService - SettingsService.initialize_defaults() - SettingsService.migrate_legacy_roles() - if not app.config.get('TESTING'): - # Size-aware retention defaults, once per install. - # Skipped under test: the result would depend on the test host's disk. - try: - from app.services import storage_profile_service - storage_profile_service.apply_to_existing() - except Exception as e: - app.logger.warning(f'Storage profile not applied: {e}') - - # Encrypt any legacy plaintext provider secrets at rest (idempotent — - # DNS-provider api keys and storage credentials predate encryption). - try: - from app.services.dns_provider_service import DNSProviderService - from app.services.storage_provider_service import StorageProviderService - n_dns = DNSProviderService.encrypt_legacy_secrets() - n_store = StorageProviderService.encrypt_legacy_secrets() - n_settings = SettingsService.migrate_legacy_secrets() - # Migrate DNS zones with an inline Cloudflare token onto the canonical - # connection store (idempotent), so every zone resolves creds the same way. - from app.services.dns_zone_service import DNSZoneService - n_zones = DNSZoneService.link_legacy_zones() - # Fold a legacy single-row email relay config into the unified - # EmailProviderConnection table; idempotent, best-effort. - try: - from app.services.email_relay_service import EmailRelayService - EmailRelayService.migrate_legacy_config() - except Exception as _relay_exc: # never block boot on this - import logging as _logging - _logging.getLogger(__name__).warning( - f'Email relay legacy migration skipped: {_relay_exc}') - if n_dns or n_store or n_settings or n_zones: - import logging as _logging - _logging.getLogger(__name__).info( - f'Encrypted legacy secrets at rest: {n_dns} DNS provider(s), ' - f'{n_store} storage field(s), ' - f'{n_settings} system setting(s); linked {n_zones} DNS zone(s) ' - f'to a connection') - except Exception as e: - import logging as _logging - _logging.getLogger(__name__).warning(f'Legacy secret encryption skipped: {e}') - - # Record this boot's hardware and compare it to the last one. - # Boot is the right hook: a VPS resize requires a power-off, so the - # change and the restart are the same event — and the in-memory spec - # cache that used to be the only "before" value dies with the process. - # Skipped under TESTING: create_app() runs per test session, and a - # capture there would write rows and emit notifications into fixtures. - if not app.config.get('TESTING'): - try: - from app.services import host_snapshot_service - host_snapshot_service.record_snapshot() - except Exception as e: - import logging - logging.getLogger(__name__).warning(f'Host snapshot skipped: {e}') - - # A panel with no account yet logs its one-time setup code, so the - # owner can read it from the service log (setup_code_service). - if not app.config.get('TESTING'): - try: - from app.services import setup_code_service - setup_code_service.ensure() - except Exception as e: - import logging - logging.getLogger(__name__).warning(f'Setup code unavailable: {e}') - - # Seed bundled flagship extensions (D4) — WordPress ships installed by - # default on every panel (fresh and upgrade) unless the user uninstalled - # it. Done BEFORE load_all_plugins so the loader registers the seeded - # blueprints. In-place: no file copy. Best-effort. - try: - from app.services.plugin_service import seed_flagship_extensions - seed_flagship_extensions() - except Exception as e: - import logging - logging.getLogger(__name__).warning(f'Flagship seed: {e}') - - # Sweep files/rows of retired extensions (e.g. serverkit-workflows) - # BEFORE the loader, so they are never loaded, never "repaired" back, - # and never carried forward into the next update's frontend build. - try: - from app.services.extension_migration import remove_retired_extensions - remove_retired_extensions() - except Exception as e: - import logging - logging.getLogger(__name__).warning(f'Retired extension sweep: {e}') - - # Load installed plugins (dynamic blueprints) AFTER migrations, - # so the installed_plugins table exists. - try: - from app.services.plugin_service import load_all_plugins - load_all_plugins(app) - except Exception as e: - import logging - logging.getLogger(__name__).warning(f'Plugin loader: {e}') - - # One-shot: auto-install builtin extensions that used to be core pages - # so an upgraded panel doesn't lose the feature (decision D3). Fresh - # installs see them in the Marketplace instead. Best-effort. - try: - from app.services.extension_migration import run_auto_install - run_auto_install() - except Exception as e: - import logging - logging.getLogger(__name__).warning(f'Extension auto-install: {e}') - - # Upgrade parity for the extracted security suite: - # a panel that was actually using fail2ban/clamav/lynis/auto-updates/ - # image scanning gets the matching registry extension once its entry - # is published. Fail-soft, retries per boot until then. Best-effort. - try: - from app.services.extension_migration import run_registry_auto_install - run_registry_auto_install() - except Exception as e: - import logging - logging.getLogger(__name__).warning(f'Security-suite auto-install: {e}') - - # One-shot: re-acquire the now-extracted backend for converted builtins - # that first shipped frontend-only, so an upgraded panel - # that installed them frontend-only doesn't lose the API. Best-effort. - try: - from app.services.extension_migration import run_backend_acquisition - run_backend_acquisition() - except Exception as e: - import logging - logging.getLogger(__name__).warning(f'Extension backend acquisition: {e}') - - # Background daemons (metrics collector, queue consumers, analytics - # flush, the job system, the linked-panel client) only make sense in a - # long-running server process. When the app is loaded by a Flask CLI - # one-shot — crucially `flask db upgrade` during an update — they must - # NOT start: they query the database before migrations have run, and - # any failure there (a corrupt DB, or pre-migration schema the new code - # doesn't match yet) aborts the CLI command and sinks the whole update. - # SERVERKIT_SKIP_BACKGROUND=1 forces the same skip; the updater sets it - # as an explicit contract when running migrations. - _cli_one_shot = ( - os.path.basename(sys.argv[0] or '').startswith('flask') - and (len(sys.argv) < 2 or sys.argv[1] != 'run') - ) - from app.utils.env import env_bool - _skip_background = env_bool('SERVERKIT_SKIP_BACKGROUND') or _cli_one_shot - if not _skip_background: - # Before any consumer polls: release what the previous process - # left in flight, or it stays stranded forever. - if not app.config.get('TESTING'): - from app.jobs.service import JobService - try: - JobService.recover_interrupted() - except Exception: - import logging - logging.getLogger(__name__).exception('Interrupted-job recovery failed') - - # Start metrics history collection in background - from app.services.metrics_history_service import MetricsHistoryService - if not MetricsHistoryService.is_running(): - MetricsHistoryService.start_collection(app) - - # Start queue-bus webhook consumer - from app.queue_bus.consumers import start_webhook_consumer - start_webhook_consumer(app) - - # Start queue-bus notification consumer (delivers in-app/email/chat) - from app.notifications.consumer import start_notification_consumer - start_notification_consumer(app) - - # Start the API analytics flush thread (a 5s buffer flush — a real-time - # stream, deliberately NOT modeled as a job). - from app.middleware.api_analytics import start_analytics_flush_thread - start_analytics_flush_thread(app) - - # Start the unified job system: ONE consumer runs every enqueued Job and - # ONE scheduler ticks all periodic work. This supersedes the former set - # of per-domain daemon scheduler threads (auto-sync, snapshot-retention, - # workflow, health-check, wp-update, api-background, pairing-prune, - # registrar-expiry) — they are now ScheduledJob rows backed by the - # built-in handlers in app/jobs/builtin_handlers.py. - from app.jobs import start_job_system - from app.jobs.builtin_handlers import register_builtin_handlers, seed_builtin_schedules - register_builtin_handlers() - # Register event-driven job handlers (deployment installs, workflow runs, - # scheduled backups). - from app.services.deployment_job_service import DeploymentJobService - DeploymentJobService.register_jobs() - from app.services.recipe_execution_service import RecipeExecutionService - RecipeExecutionService.register_jobs() - # WorkflowEngine.register_jobs() removed (engine retired). - from app.services.backup_service import BackupService - BackupService.register_jobs() - from app.services.backup_policy_service import BackupPolicyService - BackupPolicyService.register_jobs() - from app.services.server_onboarding_service import ServerOnboardingService - ServerOnboardingService.register_jobs() - from app.services.preview_service import PreviewService - PreviewService.register_jobs() - from app.services.metadata_guard_service import MetadataGuardService - MetadataGuardService.register_jobs() - if not app.config.get('TESTING'): - MetadataGuardService.ensure() # converge the metadata egress rule (no-op when unsupported) - # Bound the log files the panel writes or causes. - from app.services import log_limits_service - log_limits_service.converge() - from app.services.speed_test_service import SpeedTestService - SpeedTestService.register_jobs() - from app.services import login_link_service - login_link_service.register_jobs() - from app.services.db_admin_sso_service import DbAdminSsoService - DbAdminSsoService.register_jobs() - from app.services.site_import_service import SiteImportService - SiteImportService.register_jobs() - from app.services.drift_service import DriftService - DriftService.register_jobs() - from app.services import disk_reclaim_service - disk_reclaim_service.register_jobs() - from app.services.doctor_service import DoctorService - DoctorService.register_jobs() - from app.services.fleet_doctor_service import FleetDoctorService - FleetDoctorService.register_jobs() - from app.services.file_integrity_service import FileIntegrityService - FileIntegrityService.register_jobs() - # security.malware_scan / security.lynis_scan / security.image_scan - # handlers register via their extensions' manifest `jobs` key - # (serverkit-clamav / serverkit-lynis / serverkit-image-scan). - from app.services.bandwidth_service import BandwidthService - BandwidthService.register_jobs() - start_job_system(app, seed=seed_builtin_schedules) - - # Threshold alerting and the uptime sampler are switched on from - # the UI; without this they silently stop at the next restart - # while their status still reads "enabled". - # Best effort: a resume failure must never stop the panel booting. - if not app.config.get('TESTING'): - from app.services.monitoring_service import MonitoringService - from app.services.uptime_service import UptimeService - for resume in (lambda: MonitoringService.resume_if_enabled(app), - UptimeService.resume_if_enabled): - try: - resume() - except Exception: # noqa: BLE001 - app.logger.exception('Could not resume a background monitor at boot') - - # Resume the embedded agent when this panel is linked to a master - # ServerKit panel (ServerKit-to-ServerKit peering). - from app.services.linked_panel_service import LinkedPanelService - LinkedPanelService.start_client_if_linked(app) - - # Hold the outbound ServerKit Cloud relay connection when this - # panel is paired. - from app.services import connect_client - connect_client.start_client_if_paired(app) - - # Request body size limit - app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 # 100MB limit - - # JWTManager's blocklist callback enforces session validity for every JWT - # route. MFA verification alone decodes its body token explicitly, so no - # path-prefix exceptions can turn a pending token into a full session. - - # Serve frontend for root path - def _spa_page(): - # Opened from ServerKit Cloud, the page is served under the relay's - # path prefix (app/services/connect_session.py). - from app.services import connect_session - prefix = connect_session.tunnel_prefix(request) - if prefix: - return connect_session.index_under_prefix(app.static_folder, prefix) - return send_from_directory(app.static_folder, 'index.html') - - @app.route('/') - def serve_index(): - index = os.path.join(app.static_folder, 'index.html') if app.static_folder else None - if index and os.path.isfile(index): - return _spa_page() - return {'message': 'ServerKit API is running', 'docs': '/api/v1/'}, 200 - - # Expected application failures. Services raise these typed errors and the - # HTTP boundary owns their public shape and status-code mapping. - from app.exceptions import ApplicationError - from app.middleware.request_id import get_request_id - - @app.errorhandler(ApplicationError) - def application_error(e): - request_id = get_request_id(create=True) - app.logger.info( - 'Application error %s on %s %s [request_id=%s]: %s', - e.code, request.method, request.path, request_id, e.message, - ) - return e.to_dict(request_id=request_id), e.status_code - - # Unhandled exceptions. Flask only routes here when it is not propagating - # (so pytest and the dev server still re-raise with a full traceback); - # in production this is the difference between a logged, JSON-shaped 500 and - # a silent Werkzeug HTML page returned to an API client that wanted JSON. - @app.errorhandler(500) - def internal_error(e): - original = getattr(e, 'original_exception', None) - exc = original or e - # Logging, session rollback, and the error-log write live in - # app/error_reporting.py so a route that catches Exception itself can - # still put its crash on the record. Before that split this was the - # only path to /monitoring/errors, so every locally-handled 500 was - # invisible there. - from app.error_reporting import record_unexpected, unexpected_error_body - - # JSON either way: unlike a 404, there is no sensible SPA fallback for a - # crash, and an HTML page tells the caller nothing it can act on. - return unexpected_error_body(record_unexpected(exc)), 500 - - # Framework-generated HTTP errors (abort(), 405 from the router, 413 from - # MAX_CONTENT_LENGTH) rendered Werkzeug's HTML page even under /api/, so an - # API client parsing JSON got a parse error instead of the real reason. - # The more specific 404/500 handlers above still win for those codes. - @app.errorhandler(HTTPException) - def http_exception(e): - if request.path.startswith('/api/'): - request_id = get_request_id(create=True) - app.logger.warning( - 'HTTP %s on %s %s [request_id=%s]: %s', - e.code, request.method, request.path, request_id, e.description, - ) - return { - 'error': e.description or e.name, - 'status': e.code, - 'code': (e.name or 'http_error').lower().replace(' ', '_'), - 'request_id': request_id, - }, e.code - # Non-API paths keep Werkzeug's standard HTML error page. - return e.get_response() - - # Catch-all route for SPA - must be after all other routes - @app.errorhandler(404) - def not_found(e): - from flask import request - if request.path.startswith('/api/'): - return { - 'error': 'Not found', - 'status': 404, - 'code': 'not_found', - 'request_id': get_request_id(create=True), - }, 404 - # Serve SPA index.html if it exists, otherwise JSON 404 - index = os.path.join(app.static_folder, 'index.html') if app.static_folder else None - if index and os.path.isfile(index): - return _spa_page() - return {'error': 'Not found'}, 404 + prepare_persistence(app) + load_extensions(app) + start_runtime(app) + register_http_handlers(app) return app diff --git a/backend/app/bootstrap/__init__.py b/backend/app/bootstrap/__init__.py new file mode 100644 index 00000000..d6808786 --- /dev/null +++ b/backend/app/bootstrap/__init__.py @@ -0,0 +1 @@ +"""Ordered application assembly. Feature behavior belongs in services.""" diff --git a/backend/app/bootstrap/configuration.py b/backend/app/bootstrap/configuration.py new file mode 100644 index 00000000..2845c5ef --- /dev/null +++ b/backend/app/bootstrap/configuration.py @@ -0,0 +1,115 @@ +"""Flask extensions, database connections, and request middleware.""" +from flask_cors import CORS + +def configure_application(app, db, migrate, jwt, limiter): + # Trust the reverse proxy's forwarding headers to derive the real client IP + # (config-gated; default off). ProxyFix rewrites request.remote_addr from the + # rightmost TRUSTED_PROXY_HOPS entries of X-Forwarded-For — the hops our own + # proxies appended — so a client-forged leftmost value is ignored. Applied + # before the limiter and request handlers so every remote_addr consumer + # (flask-limiter's get_remote_address, get_client_ip(), audit logs) benefits. + if app.config.get('TRUST_PROXY_HEADERS'): + from werkzeug.middleware.proxy_fix import ProxyFix + hops = app.config.get('TRUSTED_PROXY_HOPS', 1) + app.wsgi_app = ProxyFix(app.wsgi_app, x_for=hops, x_proto=1, x_host=0, x_port=0) + + # Initialize extensions + db.init_app(app) + from app.middleware.request_profiling import register_request_profiling + register_request_profiling(app, db) + migrate.init_app(app, db) + jwt.init_app(app) + # Storage backend comes from app.config's RATELIMIT_STORAGE_URI when set + # (see config.py); unset = in-memory, correct for the single-worker design. + limiter.init_app(app) + + # SQLite concurrency tuning: the queue-bus consumers, job system and + # metrics collector share one database file with request handling, and in + # the default journal mode any writer locks the WHOLE file — readers + # included — producing sporadic "database is locked" errors under load. + # WAL lets readers coexist with a writer, a generous busy timeout absorbs + # the remaining writer-writer contention, and synchronous=NORMAL is the + # safe pairing for WAL. (journal_mode persists in the database file; the + # per-connection pragmas re-assert it for fresh files.) + if app.config['SQLALCHEMY_DATABASE_URI'].startswith('sqlite') and not app.config.get('TESTING'): + # (Skipped under TESTING: tests/conftest.py owns connection pragmas + # for the test process — journal_mode=MEMORY et al. — and two + # listeners fighting over journal_mode on the same file deadlocks.) + from sqlalchemy import event + + with app.app_context(): + @event.listens_for(db.engine, 'connect') + def _sqlite_tune(dbapi_connection, _record): + cursor = dbapi_connection.cursor() + cursor.execute('PRAGMA journal_mode=WAL') + cursor.execute('PRAGMA busy_timeout=30000') + cursor.execute('PRAGMA synchronous=NORMAL') + cursor.close() + + # Build CORS origins. Start with static config/env, then append the + # persisted canonical domain from system settings so pointing an A record + # at the panel works without restarting to edit .env. + cors_origins = list(app.config['CORS_ORIGINS']) + try: + with app.app_context(): + from app.services.settings_service import SettingsService + from app.utils.domain import canonical_origin + canonical_domain = SettingsService.get('canonical_domain', '') or '' + if canonical_domain: + https_enabled = SettingsService.get('canonical_https_enabled', False) or False + origin = canonical_origin(canonical_domain, https_enabled) + if origin not in cors_origins: + cors_origins.append(origin) + except Exception: + # Database may not exist yet during first install / migrations. + pass + + CORS( + app, + origins=cors_origins, + supports_credentials=True, + allow_headers=[ + 'Content-Type', 'Authorization', 'X-Requested-With', 'X-API-Key', + 'X-Request-ID', + ], + expose_headers=['X-Request-ID'], + methods=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'], + # Every panel request carries an Authorization header, which makes it a + # non-simple cross-origin request: without Access-Control-Max-Age the + # browser re-runs a preflight OPTIONS every few seconds (Chrome's + # default cache is 5s), so a cross-origin panel pays two round trips per + # call forever. One hour is the practical ceiling — Chrome caps the + # value at 2h, Firefox at 24h, and both take the smaller of the two. + max_age=3600, + ) + + # Assign one diagnostic ID at the outer API boundary. Downstream handlers, + # logs and jobs can reuse g.request_id without inventing independent IDs. + from app.middleware.request_id import register_request_id + register_request_id(app) + + # Register security headers middleware + from app.middleware.security import register_security_headers + register_security_headers(app) + + # Demo mode guard — config-gated (default off), blocks mutating API calls + from app.middleware.demo import init_demo_mode + init_demo_mode(app) + + # Register API key authentication middleware + from app.middleware.api_key_auth import register_api_key_auth + register_api_key_auth(app) + + # Register API analytics middleware + from app.middleware.api_analytics import register_api_analytics + register_api_analytics(app) + + # Register fallback audit logging for authenticated mutating API requests + from app.middleware.audit import register_audit_fallback + register_audit_fallback(app) + + # Update rate limiter with custom key function + from app.middleware.rate_limit import get_rate_limit_key, register_rate_limit_headers + limiter._key_func = get_rate_limit_key + register_rate_limit_headers(app) + diff --git a/backend/app/bootstrap/http.py b/backend/app/bootstrap/http.py new file mode 100644 index 00000000..70551a19 --- /dev/null +++ b/backend/app/bootstrap/http.py @@ -0,0 +1,101 @@ +"""SPA delivery and consistent HTTP error responses.""" +import os +from flask import request, send_from_directory +from werkzeug.exceptions import HTTPException + +def register_http_handlers(app): + # Request body size limit + app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 # 100MB limit + + # JWTManager's blocklist callback enforces session validity for every JWT + # route. MFA verification alone decodes its body token explicitly, so no + # path-prefix exceptions can turn a pending token into a full session. + + # Serve frontend for root path + def _spa_page(): + # Opened from ServerKit Cloud, the page is served under the relay's + # path prefix (app/services/connect_session.py). + from app.services import connect_session + prefix = connect_session.tunnel_prefix(request) + if prefix: + return connect_session.index_under_prefix(app.static_folder, prefix) + return send_from_directory(app.static_folder, 'index.html') + + @app.route('/') + def serve_index(): + index = os.path.join(app.static_folder, 'index.html') if app.static_folder else None + if index and os.path.isfile(index): + return _spa_page() + return {'message': 'ServerKit API is running', 'docs': '/api/v1/'}, 200 + + # Expected application failures. Services raise these typed errors and the + # HTTP boundary owns their public shape and status-code mapping. + from app.exceptions import ApplicationError + from app.middleware.request_id import get_request_id + + @app.errorhandler(ApplicationError) + def application_error(e): + request_id = get_request_id(create=True) + app.logger.info( + 'Application error %s on %s %s [request_id=%s]: %s', + e.code, request.method, request.path, request_id, e.message, + ) + return e.to_dict(request_id=request_id), e.status_code + + # Unhandled exceptions. Flask only routes here when it is not propagating + # (so pytest and the dev server still re-raise with a full traceback); + # in production this is the difference between a logged, JSON-shaped 500 and + # a silent Werkzeug HTML page returned to an API client that wanted JSON. + @app.errorhandler(500) + def internal_error(e): + original = getattr(e, 'original_exception', None) + exc = original or e + # Logging, session rollback, and the error-log write live in + # app/error_reporting.py so a route that catches Exception itself can + # still put its crash on the record. Before that split this was the + # only path to /monitoring/errors, so every locally-handled 500 was + # invisible there. + from app.error_reporting import record_unexpected, unexpected_error_body + + # JSON either way: unlike a 404, there is no sensible SPA fallback for a + # crash, and an HTML page tells the caller nothing it can act on. + return unexpected_error_body(record_unexpected(exc)), 500 + + # Framework-generated HTTP errors (abort(), 405 from the router, 413 from + # MAX_CONTENT_LENGTH) rendered Werkzeug's HTML page even under /api/, so an + # API client parsing JSON got a parse error instead of the real reason. + # The more specific 404/500 handlers above still win for those codes. + @app.errorhandler(HTTPException) + def http_exception(e): + if request.path.startswith('/api/'): + request_id = get_request_id(create=True) + app.logger.warning( + 'HTTP %s on %s %s [request_id=%s]: %s', + e.code, request.method, request.path, request_id, e.description, + ) + return { + 'error': e.description or e.name, + 'status': e.code, + 'code': (e.name or 'http_error').lower().replace(' ', '_'), + 'request_id': request_id, + }, e.code + # Non-API paths keep Werkzeug's standard HTML error page. + return e.get_response() + + # Catch-all route for SPA - must be after all other routes + @app.errorhandler(404) + def not_found(e): + from flask import request + if request.path.startswith('/api/'): + return { + 'error': 'Not found', + 'status': 404, + 'code': 'not_found', + 'request_id': get_request_id(create=True), + }, 404 + # Serve SPA index.html if it exists, otherwise JSON 404 + index = os.path.join(app.static_folder, 'index.html') if app.static_folder else None + if index and os.path.isfile(index): + return _spa_page() + return {'error': 'Not found'}, 404 + diff --git a/backend/app/bootstrap/jobs.py b/backend/app/bootstrap/jobs.py new file mode 100644 index 00000000..6a45de20 --- /dev/null +++ b/backend/app/bootstrap/jobs.py @@ -0,0 +1,51 @@ +"""Register core job handlers before the consumer starts.""" + +def register_job_handlers(app): + from app.jobs.builtin_handlers import register_builtin_handlers, seed_builtin_schedules + register_builtin_handlers() + # Register event-driven job handlers (deployment installs, workflow runs, + # scheduled backups). + from app.services.deployment_job_service import DeploymentJobService + DeploymentJobService.register_jobs() + from app.services.recipe_execution_service import RecipeExecutionService + RecipeExecutionService.register_jobs() + # WorkflowEngine.register_jobs() removed (engine retired). + from app.services.backup_service import BackupService + BackupService.register_jobs() + from app.services.backup_policy_service import BackupPolicyService + BackupPolicyService.register_jobs() + from app.services.server_onboarding_service import ServerOnboardingService + ServerOnboardingService.register_jobs() + from app.services.preview_service import PreviewService + PreviewService.register_jobs() + from app.services.metadata_guard_service import MetadataGuardService + MetadataGuardService.register_jobs() + if not app.config.get('TESTING'): + MetadataGuardService.ensure() # converge the metadata egress rule (no-op when unsupported) + # Bound the log files the panel writes or causes. + from app.services import log_limits_service + log_limits_service.converge() + from app.services.speed_test_service import SpeedTestService + SpeedTestService.register_jobs() + from app.services import login_link_service + login_link_service.register_jobs() + from app.services.db_admin_sso_service import DbAdminSsoService + DbAdminSsoService.register_jobs() + from app.services.site_import_service import SiteImportService + SiteImportService.register_jobs() + from app.services.drift_service import DriftService + DriftService.register_jobs() + from app.services import disk_reclaim_service + disk_reclaim_service.register_jobs() + from app.services.doctor_service import DoctorService + DoctorService.register_jobs() + from app.services.fleet_doctor_service import FleetDoctorService + FleetDoctorService.register_jobs() + from app.services.file_integrity_service import FileIntegrityService + FileIntegrityService.register_jobs() + # security.malware_scan / security.lynis_scan / security.image_scan + # handlers register via their extensions' manifest `jobs` key + # (serverkit-clamav / serverkit-lynis / serverkit-image-scan). + from app.services.bandwidth_service import BandwidthService + BandwidthService.register_jobs() + return seed_builtin_schedules diff --git a/backend/app/bootstrap/logging.py b/backend/app/bootstrap/logging.py new file mode 100644 index 00000000..18d099b6 --- /dev/null +++ b/backend/app/bootstrap/logging.py @@ -0,0 +1,55 @@ +"""Process-wide logging configuration.""" +import os +import sys + +# Set once per process: create_app() runs many times in a test session and +# gunicorn imports the module before forking, so an unguarded addHandler would +# duplicate every log line N times. +_logging_configured = False + + +def configure_logging(app): + """Give the app a real logging setup. + + Services across the codebase call ``logging.getLogger(__name__).warning(...)`` + but nothing ever configured the root logger, so those records fell through to + logging's last-resort handler: WARNING and above only, no timestamp, no + logger name, INFO dropped on the floor. That is why a panel that was failing + to serve its own agent installer (issue #101) produced no diagnostic trail at + all. ``LOG_LEVEL`` overrides the default. + """ + global _logging_configured + + import logging + + level_name = os.environ.get('LOG_LEVEL', '').upper() + if level_name and hasattr(logging, level_name): + level = getattr(logging, level_name) + elif app.config.get('TESTING'): + # TestingConfig sets DEBUG=True, so keying off DEBUG alone would move the + # whole test suite to DEBUG logging as a side effect of adding a handler. + level = logging.INFO + else: + level = logging.DEBUG if app.config.get('DEBUG') else logging.INFO + + from flask.logging import default_handler + + root = logging.getLogger() + root.setLevel(level) + app.logger.setLevel(level) + + # Flask attaches its own handler to app.logger, which ALSO propagates to the + # root logger. Leaving both in place prints every app.logger record twice -- + # once as Flask's `%(module)s` and once as ours as `%(name)s`. Drop Flask's + # and let the single root handler below own the output. + app.logger.removeHandler(default_handler) + + if not _logging_configured: + handler = logging.StreamHandler(sys.stderr) + handler.setFormatter(logging.Formatter( + '[%(asctime)s] %(levelname)s in %(name)s: %(message)s' + )) + root.addHandler(handler) + _logging_configured = True + + diff --git a/backend/app/bootstrap/persistence.py b/backend/app/bootstrap/persistence.py new file mode 100644 index 00000000..c5382119 --- /dev/null +++ b/backend/app/bootstrap/persistence.py @@ -0,0 +1,75 @@ +"""Database preparation and idempotent installation data upgrades.""" + +def prepare_persistence(app): + from app.services.migration_service import MigrationService + MigrationService.check_and_prepare(app) + + # Initialize default settings and migrate legacy roles + from app.services.settings_service import SettingsService + SettingsService.initialize_defaults() + SettingsService.migrate_legacy_roles() + if not app.config.get('TESTING'): + # Size-aware retention defaults, once per install. + # Skipped under test: the result would depend on the test host's disk. + try: + from app.services import storage_profile_service + storage_profile_service.apply_to_existing() + except Exception as e: + app.logger.warning(f'Storage profile not applied: {e}') + + # Encrypt any legacy plaintext provider secrets at rest (idempotent — + # DNS-provider api keys and storage credentials predate encryption). + try: + from app.services.dns_provider_service import DNSProviderService + from app.services.storage_provider_service import StorageProviderService + n_dns = DNSProviderService.encrypt_legacy_secrets() + n_store = StorageProviderService.encrypt_legacy_secrets() + n_settings = SettingsService.migrate_legacy_secrets() + # Migrate DNS zones with an inline Cloudflare token onto the canonical + # connection store (idempotent), so every zone resolves creds the same way. + from app.services.dns_zone_service import DNSZoneService + n_zones = DNSZoneService.link_legacy_zones() + # Fold a legacy single-row email relay config into the unified + # EmailProviderConnection table; idempotent, best-effort. + try: + from app.services.email_relay_service import EmailRelayService + EmailRelayService.migrate_legacy_config() + except Exception as _relay_exc: # never block boot on this + import logging as _logging + _logging.getLogger(__name__).warning( + f'Email relay legacy migration skipped: {_relay_exc}') + if n_dns or n_store or n_settings or n_zones: + import logging as _logging + _logging.getLogger(__name__).info( + f'Encrypted legacy secrets at rest: {n_dns} DNS provider(s), ' + f'{n_store} storage field(s), ' + f'{n_settings} system setting(s); linked {n_zones} DNS zone(s) ' + f'to a connection') + except Exception as e: + import logging as _logging + _logging.getLogger(__name__).warning(f'Legacy secret encryption skipped: {e}') + + # Record this boot's hardware and compare it to the last one. + # Boot is the right hook: a VPS resize requires a power-off, so the + # change and the restart are the same event — and the in-memory spec + # cache that used to be the only "before" value dies with the process. + # Skipped under TESTING: create_app() runs per test session, and a + # capture there would write rows and emit notifications into fixtures. + if not app.config.get('TESTING'): + try: + from app.services import host_snapshot_service + host_snapshot_service.record_snapshot() + except Exception as e: + import logging + logging.getLogger(__name__).warning(f'Host snapshot skipped: {e}') + + # A panel with no account yet logs its one-time setup code, so the + # owner can read it from the service log (setup_code_service). + if not app.config.get('TESTING'): + try: + from app.services import setup_code_service + setup_code_service.ensure() + except Exception as e: + import logging + logging.getLogger(__name__).warning(f'Setup code unavailable: {e}') + diff --git a/backend/app/bootstrap/plugins.py b/backend/app/bootstrap/plugins.py new file mode 100644 index 00000000..d5d4677f --- /dev/null +++ b/backend/app/bootstrap/plugins.py @@ -0,0 +1,64 @@ +"""Extension installation compatibility and blueprint loading.""" + +def load_extensions(app): + # Seed bundled flagship extensions (D4) — WordPress ships installed by + # default on every panel (fresh and upgrade) unless the user uninstalled + # it. Done BEFORE load_all_plugins so the loader registers the seeded + # blueprints. In-place: no file copy. Best-effort. + try: + from app.services.plugin_service import seed_flagship_extensions + seed_flagship_extensions() + except Exception as e: + import logging + logging.getLogger(__name__).warning(f'Flagship seed: {e}') + + # Sweep files/rows of retired extensions (e.g. serverkit-workflows) + # BEFORE the loader, so they are never loaded, never "repaired" back, + # and never carried forward into the next update's frontend build. + try: + from app.services.extension_migration import remove_retired_extensions + remove_retired_extensions() + except Exception as e: + import logging + logging.getLogger(__name__).warning(f'Retired extension sweep: {e}') + + # Load installed plugins (dynamic blueprints) AFTER migrations, + # so the installed_plugins table exists. + try: + from app.services.plugin_service import load_all_plugins + load_all_plugins(app) + except Exception as e: + import logging + logging.getLogger(__name__).warning(f'Plugin loader: {e}') + + # One-shot: auto-install builtin extensions that used to be core pages + # so an upgraded panel doesn't lose the feature (decision D3). Fresh + # installs see them in the Marketplace instead. Best-effort. + try: + from app.services.extension_migration import run_auto_install + run_auto_install() + except Exception as e: + import logging + logging.getLogger(__name__).warning(f'Extension auto-install: {e}') + + # Upgrade parity for the extracted security suite: + # a panel that was actually using fail2ban/clamav/lynis/auto-updates/ + # image scanning gets the matching registry extension once its entry + # is published. Fail-soft, retries per boot until then. Best-effort. + try: + from app.services.extension_migration import run_registry_auto_install + run_registry_auto_install() + except Exception as e: + import logging + logging.getLogger(__name__).warning(f'Security-suite auto-install: {e}') + + # One-shot: re-acquire the now-extracted backend for converted builtins + # that first shipped frontend-only, so an upgraded panel + # that installed them frontend-only doesn't lose the API. Best-effort. + try: + from app.services.extension_migration import run_backend_acquisition + run_backend_acquisition() + except Exception as e: + import logging + logging.getLogger(__name__).warning(f'Extension backend acquisition: {e}') + diff --git a/backend/app/bootstrap/runtime.py b/backend/app/bootstrap/runtime.py new file mode 100644 index 00000000..be0c4dd1 --- /dev/null +++ b/backend/app/bootstrap/runtime.py @@ -0,0 +1,84 @@ +"""Background runtime startup; skipped for one-shot CLI invocations.""" +import os +import sys + +def start_runtime(app): + # Background daemons (metrics collector, queue consumers, analytics + # flush, the job system, the linked-panel client) only make sense in a + # long-running server process. When the app is loaded by a Flask CLI + # one-shot — crucially `flask db upgrade` during an update — they must + # NOT start: they query the database before migrations have run, and + # any failure there (a corrupt DB, or pre-migration schema the new code + # doesn't match yet) aborts the CLI command and sinks the whole update. + # SERVERKIT_SKIP_BACKGROUND=1 forces the same skip; the updater sets it + # as an explicit contract when running migrations. + _cli_one_shot = ( + os.path.basename(sys.argv[0] or '').startswith('flask') + and (len(sys.argv) < 2 or sys.argv[1] != 'run') + ) + from app.utils.env import env_bool + _skip_background = env_bool('SERVERKIT_SKIP_BACKGROUND') or _cli_one_shot + if not _skip_background: + # Before any consumer polls: release what the previous process + # left in flight, or it stays stranded forever. + if not app.config.get('TESTING'): + from app.jobs.service import JobService + try: + JobService.recover_interrupted() + except Exception: + import logging + logging.getLogger(__name__).exception('Interrupted-job recovery failed') + + # Start metrics history collection in background + from app.services.metrics_history_service import MetricsHistoryService + if not MetricsHistoryService.is_running(): + MetricsHistoryService.start_collection(app) + + # Start queue-bus webhook consumer + from app.queue_bus.consumers import start_webhook_consumer + start_webhook_consumer(app) + + # Start queue-bus notification consumer (delivers in-app/email/chat) + from app.notifications.consumer import start_notification_consumer + start_notification_consumer(app) + + # Start the API analytics flush thread (a 5s buffer flush — a real-time + # stream, deliberately NOT modeled as a job). + from app.middleware.api_analytics import start_analytics_flush_thread + start_analytics_flush_thread(app) + + # Start the unified job system: ONE consumer runs every enqueued Job and + # ONE scheduler ticks all periodic work. This supersedes the former set + # of per-domain daemon scheduler threads (auto-sync, snapshot-retention, + # workflow, health-check, wp-update, api-background, pairing-prune, + # registrar-expiry) — they are now ScheduledJob rows backed by the + # built-in handlers in app/jobs/builtin_handlers.py. + from app.jobs import start_job_system + from app.bootstrap.jobs import register_job_handlers + seed_builtin_schedules = register_job_handlers(app) + start_job_system(app, seed=seed_builtin_schedules) + + # Threshold alerting and the uptime sampler are switched on from + # the UI; without this they silently stop at the next restart + # while their status still reads "enabled". + # Best effort: a resume failure must never stop the panel booting. + if not app.config.get('TESTING'): + from app.services.monitoring_service import MonitoringService + from app.services.uptime_service import UptimeService + for resume in (lambda: MonitoringService.resume_if_enabled(app), + UptimeService.resume_if_enabled): + try: + resume() + except Exception: # noqa: BLE001 + app.logger.exception('Could not resume a background monitor at boot') + + # Resume the embedded agent when this panel is linked to a master + # ServerKit panel (ServerKit-to-ServerKit peering). + from app.services.linked_panel_service import LinkedPanelService + LinkedPanelService.start_client_if_linked(app) + + # Hold the outbound ServerKit Cloud relay connection when this + # panel is paired. + from app.services import connect_client + connect_client.start_client_if_paired(app) + diff --git a/backend/tests/test_bootstrap_boundaries.py b/backend/tests/test_bootstrap_boundaries.py new file mode 100644 index 00000000..e9bf9af8 --- /dev/null +++ b/backend/tests/test_bootstrap_boundaries.py @@ -0,0 +1,110 @@ +"""Startup ordering and dependency boundaries, without launching workers.""" +import ast +import sys +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +from app.bootstrap import runtime + + +@pytest.fixture +def runtime_calls(monkeypatch): + calls = [] + + def record(name, result=None): + def call(*args, **kwargs): + calls.append(name) + return result + return call + + modules = { + 'app.jobs.service': {'JobService': SimpleNamespace(recover_interrupted=record('recover'))}, + 'app.services.metrics_history_service': {'MetricsHistoryService': SimpleNamespace( + is_running=lambda: False, start_collection=record('metrics'))}, + 'app.queue_bus.consumers': {'start_webhook_consumer': record('webhooks')}, + 'app.notifications.consumer': {'start_notification_consumer': record('notifications')}, + 'app.middleware.api_analytics': {'start_analytics_flush_thread': record('analytics')}, + 'app.jobs': {'start_job_system': record('jobs')}, + 'app.bootstrap.jobs': {'register_job_handlers': record('handlers')}, + 'app.services.monitoring_service': {'MonitoringService': SimpleNamespace(resume_if_enabled=record('monitoring'))}, + 'app.services.uptime_service': {'UptimeService': SimpleNamespace(resume_if_enabled=record('uptime'))}, + 'app.services.linked_panel_service': {'LinkedPanelService': SimpleNamespace(start_client_if_linked=record('linked'))}, + } + for name, attrs in modules.items(): + monkeypatch.setitem(sys.modules, name, SimpleNamespace(**attrs)) + from app import services + monkeypatch.setattr(services, 'connect_client', SimpleNamespace( + start_client_if_paired=record('relay')), raising=False) + monkeypatch.delenv('SERVERKIT_SKIP_BACKGROUND', raising=False) + monkeypatch.setattr(sys, 'argv', ['gunicorn']) + return calls + + +@pytest.mark.parametrize('argv,skip', [(['flask', 'db', 'upgrade'], None), + (['flask'], None), (['gunicorn'], '1')]) +def test_one_shot_startup_never_recovers_or_starts_workers(monkeypatch, runtime_calls, argv, skip): + monkeypatch.setattr(sys, 'argv', argv) + if skip: + monkeypatch.setenv('SERVERKIT_SKIP_BACKGROUND', skip) + runtime.start_runtime(SimpleNamespace(config={}, logger=Mock())) + assert runtime_calls == [] + + +@pytest.mark.parametrize('argv', [['gunicorn'], ['flask', 'run']]) +def test_recovery_precedes_consumers_and_handlers_precede_jobs(monkeypatch, runtime_calls, argv): + monkeypatch.setattr(sys, 'argv', argv) + runtime.start_runtime(SimpleNamespace(config={}, logger=Mock())) + assert runtime_calls == ['recover', 'metrics', 'webhooks', 'notifications', + 'analytics', 'handlers', 'jobs', 'monitoring', + 'uptime', 'linked', 'relay'] + + +def test_factory_phase_order_and_context(monkeypatch): + import app as application + from flask import has_app_context + from app.bootstrap import configuration, persistence, plugins, http + import app.sockets + import app.agent_gateway + import app.core_blueprints + from app.services import recycle_bin_service, restore_point_adapters + + calls = [] + def phase(name, context=False): + def run(*args): + assert has_app_context() is context + calls.append(name) + return run + + monkeypatch.setattr(configuration, 'configure_application', phase('configuration')) + monkeypatch.setattr(app.sockets, 'init_socketio', phase('socket')) + monkeypatch.setattr(app.agent_gateway, 'init_agent_gateway', phase('gateway')) + monkeypatch.setattr(app.core_blueprints, 'register_core_blueprints', phase('routes')) + monkeypatch.setattr(recycle_bin_service, 'register_builtin_types', phase('recycle')) + monkeypatch.setattr(restore_point_adapters, 'register_builtin_restore_point_adapters', phase('restore')) + monkeypatch.setattr(persistence, 'prepare_persistence', phase('persistence', True)) + monkeypatch.setattr(plugins, 'load_extensions', phase('plugins', True)) + monkeypatch.setattr(runtime, 'start_runtime', phase('runtime', True)) + monkeypatch.setattr(http, 'register_http_handlers', phase('http')) + monkeypatch.setattr(application, 'socketio', application.socketio) + application.create_app('testing') + assert calls == ['configuration', 'socket', 'gateway', 'routes', 'recycle', + 'restore', 'persistence', 'plugins', 'runtime', 'http'] + + +def test_bootstrap_is_an_assembly_layer_not_a_service_dependency(): + root = Path(__file__).parents[1] / 'app' + for folder in ('api', 'services', 'models', 'jobs'): + for path in (root / folder).rglob('*.py'): + for node in ast.walk(ast.parse(path.read_text(encoding='utf-8-sig'))): + if isinstance(node, ast.ImportFrom): + assert not (node.module or '').startswith('app.bootstrap'), path + elif isinstance(node, ast.Import): + assert not any(a.name.startswith('app.bootstrap') for a in node.names), path + factory = ast.parse((root / '__init__.py').read_text(encoding='utf-8')) + create = next(n for n in factory.body if isinstance(n, ast.FunctionDef) and n.name == 'create_app') + assert create.end_lineno - create.lineno < 70, 'Keep feature setup in an owned bootstrap phase' + for node in ast.walk(create): + assert not isinstance(node, (ast.Try, ast.For, ast.While)), 'Factory must compose phases' From e7ba1c2a896fb930d680409d2d78bd61334cbfd4 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 04:31:28 -0400 Subject: [PATCH 03/34] refactor: route file operations through capability-checked adapters --- .../__tests__/fileAdapter.test.js | 60 ++++++++++++++ .../components/file-manager/fileAdapter.js | 49 +++++++++++ frontend/src/pages/FileManager.jsx | 81 ++++--------------- 3 files changed, 125 insertions(+), 65 deletions(-) create mode 100644 frontend/src/components/file-manager/__tests__/fileAdapter.test.js create mode 100644 frontend/src/components/file-manager/fileAdapter.js diff --git a/frontend/src/components/file-manager/__tests__/fileAdapter.test.js b/frontend/src/components/file-manager/__tests__/fileAdapter.test.js new file mode 100644 index 00000000..bf218f12 --- /dev/null +++ b/frontend/src/components/file-manager/__tests__/fileAdapter.test.js @@ -0,0 +1,60 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createFileAdapter } from '../fileAdapter.js'; + +function fixture(target) { + const calls = []; + const api = new Proxy({}, { get: (_, name) => (...args) => { + calls.push([name, ...args]); + return Promise.resolve({ success: true, data: { files: [] } }); + } }); + return { adapter: createFileAdapter(api, target), calls }; +} + +test('agent operations use its server id and unwrap older envelopes', async () => { + const { adapter, calls } = fixture({ kind: 'agent', server_id: 7 }); + assert.deepEqual(await adapter.browse('/home', true), { files: [] }); + await adapter.read('/home/a'); + await adapter.write('/home/a', 'edited'); + assert.deepEqual(calls, [['browseRemoteFiles', 7, '/home'], + ['readRemoteFile', 7, '/home/a'], ['writeRemoteFile', 7, '/home/a', 'edited']]); +}); + +for (const kind of ['agent', 's3']) { + test(`${kind} unsupported operations never reach the panel host`, () => { + const { adapter, calls } = fixture({ kind, server_id: 7 }); + const unsupported = ['search', 'create folder', 'rename', 'change permissions']; + if (kind === 'agent') unsupported.push('delete', 'download', 'upload'); + for (const operation of unsupported) { + assert.equal(adapter.supports(operation), false); + assert.throws(() => adapter[operation]('/home/a'), /unavailable/); + } + assert.deepEqual(calls, []); + }); +} + +test('S3 transfer and mutation operations stay in the bucket', async () => { + const { adapter, calls } = fixture({ kind: 's3' }); + const progress = () => {}; + await adapter.upload('/folder', 'file', progress); + await adapter.write('/a', 'edited'); + await adapter.del('/a'); + adapter.download({ path: '/b' }); + assert.deepEqual(calls, [['uploadS3', '/folder', 'file', progress], + ['writeS3', '/a', 'edited'], ['deleteS3', '/a'], ['downloadS3File', '/b']]); +}); + +test('local calls retain hidden flag and mutation arguments', async () => { + const { adapter, calls } = fixture({ kind: 'local' }); + await adapter.browse('/home', true); + await adapter['create folder']('/home/assets'); + await adapter.rename('/home/assets', 'new'); + await adapter['change permissions']('/home/assets', '700'); + assert.deepEqual(calls, [['browseFiles', '/home', true], + ['createDirectory', '/home/assets'], ['renameFile', '/home/assets', 'new'], + ['changeFilePermissions', '/home/assets', '700']]); +}); + +test('unknown targets fail closed', () => { + assert.throws(() => fixture({ kind: 'typo' }), /Unknown file target/); +}); diff --git a/frontend/src/components/file-manager/fileAdapter.js b/frontend/src/components/file-manager/fileAdapter.js new file mode 100644 index 00000000..6949c432 --- /dev/null +++ b/frontend/src/components/file-manager/fileAdapter.js @@ -0,0 +1,49 @@ +// All file operations cross this boundary. Unsupported targets never fall back +// to the panel host, even if a caller forgets to disable a control. +const OPERATIONS = ['browse', 'read', 'write', 'delete', 'download', 'upload', + 'search', 'create folder', 'rename', 'change permissions']; + +function unwrapAgentData(result) { + return result && typeof result === 'object' && 'success' in result && 'data' in result + ? result.data : result; +} + +export function createFileAdapter(api, target) { + const local = { + browse: (path, hidden) => api.browseFiles(path, hidden), + read: (path) => api.readFile(path), + write: (path, content) => api.writeFile(path, content), + delete: (path) => api.deleteFile(path), + download: (entry) => api.downloadFile(entry.path), + upload: (path, file, progress) => api.uploadFile(path, file, progress), + search: (path, query) => api.searchFiles(path, query), + 'create folder': (path) => api.createDirectory(path), + rename: (path, name) => api.renameFile(path, name), + 'change permissions': (path, mode) => api.changeFilePermissions(path, mode), + }; + const agent = { + browse: async (path) => unwrapAgentData(await api.browseRemoteFiles(target.server_id, path)), + read: async (path) => unwrapAgentData(await api.readRemoteFile(target.server_id, path)), + write: async (path, content) => unwrapAgentData(await api.writeRemoteFile(target.server_id, path, content)), + }; + const s3 = { + browse: (path) => api.browseS3(path), + read: (path) => api.readS3(path), + write: (path, content) => api.writeS3(path, content), + delete: (path) => api.deleteS3(path), + download: (entry) => api.downloadS3File(entry.path), + upload: (path, file, progress) => api.uploadS3(path, file, progress), + }; + const methods = { local, agent, s3 }[target.kind]; + if (!methods) throw new Error(`Unknown file target: ${target.kind}`); + const supports = (operation) => Object.hasOwn(methods, operation); + const adapter = { supports }; + for (const operation of OPERATIONS) { + adapter[operation] = (...args) => { + if (!supports(operation)) throw new Error(`${operation} is unavailable on ${target.kind}`); + return methods[operation](...args); + }; + } + adapter.del = adapter.delete; + return Object.freeze(adapter); +} diff --git a/frontend/src/pages/FileManager.jsx b/frontend/src/pages/FileManager.jsx index 7aa8d399..eb1c1481 100644 --- a/frontend/src/pages/FileManager.jsx +++ b/frontend/src/pages/FileManager.jsx @@ -1,5 +1,6 @@ import { useState, useEffect, useRef, useMemo, useCallback } from 'react'; import { api } from '../services/api'; +import { createFileAdapter } from '../components/file-manager/fileAdapter'; import { useToast } from '../contexts/useToast.js'; import ConfirmDialog from '../components/ConfirmDialog'; import EmptyState from '../components/EmptyState'; @@ -68,16 +69,6 @@ const QUICK_ACCESS_AGENT = { ], }; -// File manager operations that the agent can serve over file:* commands. -// Anything else (mkdir, delete, rename, copy, chmod, search, disk usage, -// upload/download) is panel-host-only until the matching agent verbs land. -const REMOTE_SUPPORTED = new Set(['browse', 'read', 'write']); - -// Operations the S3 target can't serve (no real directories, permissions, or -// in-place rename). Everything else — browse/read/write/delete/upload/download — -// works against the bucket. -const S3_BLOCKED = new Set(['create file', 'create folder', 'rename', 'change permissions']); - function deriveParent(path) { if (!path || path === '/' || path === '') return null; // A Windows drive root ("C:/" or "C:") sits directly under the agent's @@ -94,16 +85,6 @@ function deriveParent(path) { return parent; } -function unwrapAgentData(res) { - // Remote endpoints return the agent payload directly - // (RemoteFileService → _agent_result unwraps {data}). Defensive - // unwrap covers both shapes for older agent responses. - if (res && typeof res === 'object' && 'success' in res && 'data' in res) { - return res.data; - } - return res; -} - function mountDisplayName(mount) { if (!mount?.mountpoint || mount.mountpoint === '/') return null; const parts = mount.mountpoint.split('/').filter(Boolean); @@ -310,50 +291,19 @@ function FileManager() { // eslint-disable-next-line react-hooks/exhaustive-deps }, [currentPath]); - // ─── file API adapter ──────────────────────────────── - // Routes the three verbs the agent supports through the remote - // endpoints when target is an agent; falls back to the panel-local - // FileService otherwise. Other ops keep going to panel-local — the - // remoteGuard helper short-circuits them with a toast when the user - // is on a remote target so we don't accidentally write to the panel - // host while they think they're editing a remote server. - const fileApi = useMemo(() => ({ - browse: async (path, hidden) => { - if (isS3) return api.browseS3(path); - if (isRemote) { - return unwrapAgentData(await api.browseRemoteFiles(target.server_id, path)); - } - return api.browseFiles(path, hidden); - }, - read: async (path) => { - if (isS3) return api.readS3(path); - if (isRemote) { - return unwrapAgentData(await api.readRemoteFile(target.server_id, path)); - } - return api.readFile(path); - }, - write: async (path, content) => { - if (isS3) return api.writeS3(path, content); - if (isRemote) { - return unwrapAgentData(await api.writeRemoteFile(target.server_id, path, content)); - } - return api.writeFile(path, content); - }, - del: async (path) => (isS3 ? api.deleteS3(path) : api.deleteFile(path)), - download: (entry) => (isS3 ? api.downloadS3File(entry.path) : api.downloadFile(entry.path)), - }), [isRemote, isS3, target]); + const fileApi = useMemo(() => createFileAdapter(api, target), [target]); const remoteGuard = useCallback((op) => { - if (isRemote && !REMOTE_SUPPORTED.has(op)) { + if (isRemote && !fileApi.supports(op)) { toast.error(t('app.fileManager.isNotYetSupportedOnRemote', '{{op}} is not yet supported on remote agents', { op: op })); return true; } - if (isS3 && S3_BLOCKED.has(op)) { + if (isS3 && !fileApi.supports(op)) { toast.error(t('app.fileManager.isnTAvailableOnS3Buckets', '{{op}} isn\'t available on S3 buckets', { op: op })); return true; } return false; - }, [isRemote, isS3, t, toast]); + }, [isRemote, isS3, fileApi, t, toast]); // When the user switches to a remote target, jump to its first // advertised allowed_path so they don't see a "panel /home" view @@ -497,7 +447,7 @@ function FileManager() { if (!searchQuery.trim()) { setSearchResults(null); return; } setLoading(true); try { - const data = await api.searchFiles(currentPath, searchQuery); + const data = await fileApi.search(currentPath, searchQuery); setSearchResults(data.results || []); } catch (error) { toast.error(t('app.fileManager.searchFailed', "Couldn't search. {{message}}", { message: errorReason(error) })); @@ -590,7 +540,7 @@ function FileManager() { const handleCreateFolder = async (name) => { if (remoteGuard('create folder')) return; try { - await api.createDirectory(`${currentPath}/${name}`); + await fileApi['create folder'](`${currentPath}/${name}`); toast.success(t('app.fileManager.folderCreated', 'Folder created')); closeDialog(); loadDirectory(currentPath); @@ -598,7 +548,7 @@ function FileManager() { const parent = currentPath; if (treeCache.has(parent)) { try { - const data = await api.browseFiles(parent, false); + const data = await fileApi.browse(parent, false); const folders = (data.entries || []).filter((e) => e.is_dir).map((e) => ({ path: e.path, name: e.name })); setTreeCache((c) => { const n = new Map(c); n.set(parent, folders); return n; }); } catch { /* ignore */ } @@ -643,7 +593,7 @@ function FileManager() { const handleRename = async (entry, name) => { if (remoteGuard('rename')) return; try { - await api.renameFile(entry.path, name); + await fileApi.rename(entry.path, name); toast.success(t('app.fileManager.renamed', 'Renamed')); closeDialog(); loadDirectory(currentPath); @@ -655,7 +605,7 @@ function FileManager() { const handleChangePermissions = async (entry, mode) => { if (remoteGuard('change permissions')) return; try { - await api.changeFilePermissions(entry.path, mode); + await fileApi['change permissions'](entry.path, mode); toast.success(t('app.fileManager.permissionsUpdated', 'Permissions updated')); closeDialog(); loadDirectory(currentPath); @@ -687,7 +637,7 @@ function FileManager() { const itemId = queue[i].id; try { setUploads((p) => p.map((u) => u.id === itemId ? { ...u, status: 'uploading' } : u)); - const doUpload = isS3 ? api.uploadS3 : api.uploadFile; + const doUpload = fileApi.upload; await doUpload(currentPath, file, (progress) => { setUploads((p) => p.map((u) => u.id === itemId ? { ...u, progress } : u)); }); @@ -871,7 +821,8 @@ function FileManager() { const rowOpen = useStableHandler(handleOpen); const rowToggleSelect = useStableHandler(handleToggleSelect); const rowContext = useStableHandler(openContextMenu); - const rowDownload = useStableHandler((entry) => fileApi.download(entry)); + const handleDownload = (entry) => { if (!remoteGuard('download')) fileApi.download(entry); }; + const rowDownload = useStableHandler(handleDownload); const rowRename = useStableHandler(openRenameModal); const rowPermissions = useStableHandler(openPermissionsModal); const rowDelete = useStableHandler((entry) => handleDelete(entry)); @@ -879,7 +830,7 @@ function FileManager() { const copyPathToClipboard = (path) => copyText(path); const downloadSelected = () => { - selectedEntries.filter((e) => !e.is_dir).forEach((e) => fileApi.download(e)); + if (!remoteGuard('download')) selectedEntries.filter((e) => !e.is_dir).forEach((e) => fileApi.download(e)); }; const getDiskColor = (percent) => { @@ -1384,7 +1335,7 @@ function FileManager() { onCancelEdit={() => setEditing(false)} onSave={handleSaveFile} onClose={() => { setPreviewFile(null); setEditing(false); }} - onDownload={(e) => fileApi.download(e)} + onDownload={handleDownload} onRename={openRenameModal} onPermissions={openPermissionsModal} onCopyPath={copyPathToClipboard} @@ -1434,7 +1385,7 @@ function FileManager() { selectionCount={selectedEntries.length} onClose={() => setContextMenu(null)} onOpen={handleOpen} - onDownload={(e) => fileApi.download(e)} + onDownload={handleDownload} onRename={openRenameModal} onPermissions={openPermissionsModal} onCopyPath={copyPathToClipboard} From 17280646b0fad67794195ee00183d9ad97a24f7d Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Sat, 24 Oct 2026 08:34:38 +0000 Subject: [PATCH 04/34] chore: bump version to 1.11.25 [skip ci] --- VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/VERSION b/VERSION index f2a994ec..7c3e314f 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.11.24 +1.11.25 From b534ee2bafff880c2f758f8180188d639d6491db Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 04:44:18 -0400 Subject: [PATCH 05/34] refactor: split File Manager state and views with regression guards --- .../scripts/check-file-manager-boundaries.mjs | 62 + .../scripts/check-frontend-boundaries.mjs | 3 + frontend/scripts/file-manager-browser.mjs | 152 +- .../src/components/file-manager/FileCard.jsx | 4 +- .../file-manager/FileManagerDialogs.jsx | 55 + .../file-manager/FileManagerListing.jsx | 171 ++ .../file-manager/FileManagerSidebar.jsx | 233 +++ .../file-manager/FileManagerStatus.jsx | 59 + .../file-manager/FileManagerToolbar.jsx | 263 +++ .../file-manager/FileUploadTray.jsx | 58 + .../components/file-manager/ImageThumb.jsx | 39 +- .../components/file-manager/PreviewDrawer.jsx | 4 +- .../file-manager/__tests__/boundaries.test.js | 20 + .../__tests__/fileAdapter.test.js | 2 +- .../components/file-manager/fileAdapter.js | 4 +- .../file-manager/hooks/useDirectoryBrowser.js | 276 +++ .../file-manager/hooks/useFileActions.js | 149 ++ .../file-manager/hooks/useFileEditor.js | 74 + .../file-manager/hooks/useFileListingModel.js | 137 ++ .../file-manager/hooks/useFilePreferences.js | 33 + .../file-manager/hooks/useFileSelection.js | 47 + .../file-manager/hooks/useFileTargets.js | 120 ++ .../file-manager/hooks/useFileTransfers.js | 129 ++ .../file-manager/hooks/useFileTree.js | 118 ++ .../file-manager/hooks/useFileVolumes.js | 43 + .../file-manager/hooks/useImagePreview.js | 27 + .../components/file-manager/preferences.js | 19 + frontend/src/pages/FileManager.jsx | 1631 ++++------------- 28 files changed, 2633 insertions(+), 1299 deletions(-) create mode 100644 frontend/scripts/check-file-manager-boundaries.mjs create mode 100644 frontend/src/components/file-manager/FileManagerDialogs.jsx create mode 100644 frontend/src/components/file-manager/FileManagerListing.jsx create mode 100644 frontend/src/components/file-manager/FileManagerSidebar.jsx create mode 100644 frontend/src/components/file-manager/FileManagerStatus.jsx create mode 100644 frontend/src/components/file-manager/FileManagerToolbar.jsx create mode 100644 frontend/src/components/file-manager/FileUploadTray.jsx create mode 100644 frontend/src/components/file-manager/__tests__/boundaries.test.js create mode 100644 frontend/src/components/file-manager/hooks/useDirectoryBrowser.js create mode 100644 frontend/src/components/file-manager/hooks/useFileActions.js create mode 100644 frontend/src/components/file-manager/hooks/useFileEditor.js create mode 100644 frontend/src/components/file-manager/hooks/useFileListingModel.js create mode 100644 frontend/src/components/file-manager/hooks/useFilePreferences.js create mode 100644 frontend/src/components/file-manager/hooks/useFileSelection.js create mode 100644 frontend/src/components/file-manager/hooks/useFileTargets.js create mode 100644 frontend/src/components/file-manager/hooks/useFileTransfers.js create mode 100644 frontend/src/components/file-manager/hooks/useFileTree.js create mode 100644 frontend/src/components/file-manager/hooks/useFileVolumes.js create mode 100644 frontend/src/components/file-manager/hooks/useImagePreview.js create mode 100644 frontend/src/components/file-manager/preferences.js diff --git a/frontend/scripts/check-file-manager-boundaries.mjs b/frontend/scripts/check-file-manager-boundaries.mjs new file mode 100644 index 00000000..14d69393 --- /dev/null +++ b/frontend/scripts/check-file-manager-boundaries.mjs @@ -0,0 +1,62 @@ +import { readFileSync, readdirSync } from 'node:fs'; +import { dirname, join, relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parse } from 'espree'; + +const src = resolve(dirname(fileURLToPath(import.meta.url)), '../src'); +const feature = 'components/file-manager/'; +const apiOwners = new Set(['pages/FileManager.jsx', `${feature}hooks/useFileTargets.js`, + `${feature}hooks/useFileVolumes.js`]); + +export function inspectFileManagerSource(path, source) { + const errors = []; + const ast = parse(source, { ecmaVersion: 'latest', sourceType: 'module', ecmaFeatures: { jsx: true } }); + const page = path === 'pages/FileManager.jsx'; + const hook = path.startsWith(`${feature}hooks/`); + const view = path.startsWith(feature) && path.endsWith('.jsx'); + const imports = ast.body.filter(node => node.type === 'ImportDeclaration'); + for (const node of imports) { + const target = node.source.value; + if (/services\//.test(target) && !apiOwners.has(path)) { + errors.push(`${path}: transport imports belong to the adapter composition or metadata hooks`); + } + if (path.startsWith(feature) && /(?:^|\/)pages\//.test(target)) { + errors.push(`${path}: a feature cannot depend on route pages`); + } + if (view && /(?:^|\/)hooks\/use(?:File|Directory)/.test(target)) { + errors.push(`${path}: views receive feature state through props`); + } + } + function visit(node) { + if (!node || typeof node !== 'object') return; + if (page && node.type === 'AwaitExpression') errors.push(`${path}: asynchronous work belongs in hooks`); + if ((page || view) && node.type === 'CallExpression' && node.callee?.object?.name === 'api') { + errors.push(`${path}: views must not call API methods`); + } + if (view && node.type === 'CallExpression' && node.callee?.name === 'fetch') { + errors.push(`${path}: views must not fetch`); + } + for (const value of Object.values(node)) { + if (Array.isArray(value)) value.forEach(visit); + else if (value && typeof value === 'object') visit(value); + } + } + visit(ast); + // Backstops for accidental recombination, in addition to dependency rules. + const lines = source.split('\n').filter(line => line.trim()).length; + if (page && lines > 650) errors.push(`${path}: keep the route focused on composition (650 nonblank lines)`); + if (hook && lines > 300) errors.push(`${path}: split unrelated hook responsibilities (300 nonblank lines)`); + return errors; +} + +export function checkFileManagerBoundaries() { + const walk = dir => readdirSync(dir, { withFileTypes: true }).flatMap(entry => { + if (entry.name === '__tests__') return []; + const path = join(dir, entry.name); + return entry.isDirectory() ? walk(path) : /\.[jt]sx?$/.test(path) ? [path] : []; + }); + const files = [join(src, 'pages/FileManager.jsx'), ...walk(join(src, feature))]; + const errors = files.flatMap(path => inspectFileManagerSource( + relative(src, path).replaceAll('\\', '/'), readFileSync(path, 'utf8'))); + if (errors.length) throw new Error(errors.join('\n')); +} diff --git a/frontend/scripts/check-frontend-boundaries.mjs b/frontend/scripts/check-frontend-boundaries.mjs index 28f7785c..2a5c325c 100644 --- a/frontend/scripts/check-frontend-boundaries.mjs +++ b/frontend/scripts/check-frontend-boundaries.mjs @@ -9,6 +9,9 @@ import { existsSync, readFileSync, readdirSync } from 'node:fs'; import { dirname, extname, join, relative, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { checkFileManagerBoundaries } from './check-file-manager-boundaries.mjs'; + +checkFileManagerBoundaries(); const here = dirname(fileURLToPath(import.meta.url)); const root = resolve(here, '..'); diff --git a/frontend/scripts/file-manager-browser.mjs b/frontend/scripts/file-manager-browser.mjs index f1039b94..330de817 100644 --- a/frontend/scripts/file-manager-browser.mjs +++ b/frontend/scripts/file-manager-browser.mjs @@ -15,6 +15,7 @@ import React from 'react'; import {createRoot} from 'react-dom/client'; import {MemoryRouter} from 'react-router-dom'; import FileManager from '/src/pages/FileManager.jsx'; +import {ConfirmProvider} from '/src/contexts/ConfirmContext.jsx'; window.pending=[]; const listing=(p)=>({path:p,parent:p==='/'?null:p.replace(/\\/[^/]+$/,'')||'/',entries:p==='/home'?[{name:'projects',path:'/home/projects',is_dir:true,type:'directory',size:0,permissions:'drwxr-xr-x',permissions_octal:'750'}]:[{name:'inside-'+p.split('/').pop()+'.txt',path:p+'/x.txt',is_dir:false,type:'file',size:1}]}); window.release=(p)=>{const i=window.pending.findIndex(x=>x.path===p);const x=window.pending.splice(i,1)[0];x.resolve(listing(p));}; @@ -26,7 +27,7 @@ window.testApi={ renameFile:(p,n)=>{(window.ops=window.ops||[]).push(['rename',p,n]);return Promise.resolve({});}, changeFilePermissions:(p,m)=>{(window.ops=window.ops||[]).push(['chmod',p,m]);return Promise.resolve({});}, }; -createRoot(document.getElementById('root')).render(); +createRoot(document.getElementById('root')).render(); `; const server = await createServer({ root, configFile: false, logLevel: 'error', resolve: { alias: { '@': path.join(root, 'src') } }, @@ -150,6 +151,155 @@ try { assert.equal(await sw.getByText('projects', { exact: true }).count(), 0, 'the panel host listing is still shown'); assert.deepEqual(swErrors, []); console.log('PASS switching to a remote agent reloads the listing from that agent'); + + // A local request still in flight must not replace the agent's listing. + const late = await browser.newPage(); + await late.goto(`http://127.0.0.1:${server.httpServer.address().port}/fm-check`); + await late.getByText('projects', { exact: true }).first().waitFor(); + await late.getByText('projects', { exact: true }).first().dblclick(); + await late.waitForFunction(() => window.pending.some(x => x.path === '/home/projects')); + await late.getByRole('button', { name: 'pick-agent' }).click(); + await late.getByText('on-agent.txt').first().waitFor(); + await late.evaluate(() => window.release('/home/projects')); + await late.waitForTimeout(100); + assert.equal(await late.getByText('inside-projects.txt').count(), 0); + assert.equal(await late.getByTitle('Back', { exact: true }).isDisabled(), true, + 'navigation history must not cross storage targets'); + console.log('PASS late local responses and history cannot cross a target switch'); + + // Search responses and canceled searches must not overwrite navigation. + const search = await browser.newPage(); + await search.goto(`http://127.0.0.1:${server.httpServer.address().port}/fm-check`); + await search.getByText('projects', { exact: true }).first().waitFor(); + await search.evaluate(() => { + window.testApi.searchFiles = () => new Promise(resolve => { window.finishSearch = resolve; }); + }); + await search.getByPlaceholder('Search files…').fill('old'); + await search.getByPlaceholder('Search files…').press('Enter'); + await search.waitForFunction(() => Boolean(window.finishSearch)); + await search.getByTitle('Home', { exact: true }).click(); + // Home is already the current folder, so explicitly refresh it. + await search.locator('.file-manager-toolbar').getByTitle('Refresh', { exact: true }).click(); + await search.getByText('projects', { exact: true }).first().waitFor(); + await search.evaluate(() => window.finishSearch({ results: [{ name: 'stale-result.txt', path: '/old', is_dir: false }] })); + await search.waitForTimeout(100); + assert.equal(await search.getByText('stale-result.txt').count(), 0); + console.log('PASS a late search cannot overwrite a refreshed directory'); + await search.getByPlaceholder('Search files…').fill('cancel me'); + await search.getByPlaceholder('Search files…').press('Enter'); + await search.locator('.search-field-clear').click(); + await search.evaluate(() => window.finishSearch({ results: [{ name: 'canceled-result.txt', path: '/old', is_dir: false }] })); + await search.waitForTimeout(100); + assert.equal(await search.getByText('canceled-result.txt').count(), 0); + console.log('PASS clearing search invalidates its pending response'); + + // Read A, then B; A arriving last must not become B's editable contents. + const editor = await browser.newPage(); + const editorErrors = []; + editor.on('pageerror', error => editorErrors.push(error.message)); + await editor.goto(`http://127.0.0.1:${server.httpServer.address().port}/fm-check`); + await editor.getByText('projects', { exact: true }).first().waitFor(); + await editor.evaluate(() => { + window.reads = {}; + window.testApi.browseFiles = p => Promise.resolve({ path: p, parent: '/', entries: + ['a.txt', 'b.txt'].map(name => ({ name, path: p + '/' + name, is_dir: false, is_editable: true, size: 1 })) }); + window.testApi.readFile = p => new Promise(resolve => { window.reads[p] = resolve; }); + window.testApi.writeFile = () => Promise.reject(new Error('disk full')); + }); + await editor.locator('.file-manager-toolbar').getByTitle('Refresh', { exact: true }).click(); + await editor.getByText('a.txt', { exact: true }).first().dblclick(); + await editor.waitForFunction(() => Boolean(window.reads['/home/a.txt'])); + await editor.getByText('b.txt', { exact: true }).first().dblclick(); + await editor.waitForFunction(() => Boolean(window.reads['/home/b.txt'])); + await editor.evaluate(() => window.reads['/home/b.txt']({ content: 'new-content' })); + await editor.getByLabel('File contents').getByText('new-content', { exact: true }).waitFor(); + await editor.evaluate(() => window.reads['/home/a.txt']({ content: 'old-content' })); + await editor.waitForTimeout(100); + assert.equal(await editor.getByText('old-content', { exact: true }).count(), 0); + const preview = editor.getByRole('complementary', { name: 'File preview' }); + await preview.getByRole('button', { name: 'Edit', exact: true }).click(); + await preview.locator('textarea').fill('unsaved draft'); + await preview.getByRole('button', { name: 'Save', exact: true }).click(); + await editor.waitForFunction(() => (window.toasts || []).length > 0); + assert.equal(await preview.locator('textarea').inputValue(), 'unsaved draft'); + await editor.getByRole('button', { name: 'pick-agent' }).click(); + await editor.getByText('on-agent.txt').first().waitFor(); + assert.equal(await preview.count(), 0, 'the previous target preview stayed open'); + assert.deepEqual(editorErrors, []); + console.log('PASS preview read races, failed-save draft retention and target reset'); + + // Shared confirmation must preserve cancel semantics and partial failures. + const deletion = await browser.newPage(); + await deletion.goto(`http://127.0.0.1:${server.httpServer.address().port}/fm-check`); + await deletion.getByText('projects', { exact: true }).first().waitFor(); + await deletion.evaluate(() => { + window.deleted = []; + window.testApi.deleteFile = p => { window.deleted.push(p); return Promise.resolve({}); }; + }); + await deletion.getByTitle('Delete', { exact: true }).first().click(); + await deletion.getByRole('alertdialog').getByRole('button', { name: 'Cancel', exact: true }).click(); + assert.deepEqual(await deletion.evaluate(() => window.deleted), []); + await deletion.getByTitle('Delete', { exact: true }).first().click(); + await deletion.getByRole('alertdialog').getByRole('button', { name: 'Delete', exact: true }).click(); + await deletion.waitForFunction(() => window.deleted.length === 1); + assert.deepEqual(await deletion.evaluate(() => window.deleted), ['/home/projects']); + console.log('PASS shared delete confirmation cancels or executes the intended path'); + + // Back/forward still works after moving the toolbar into its own component. + const nav = await browser.newPage(); + await nav.goto(`http://127.0.0.1:${server.httpServer.address().port}/fm-check`); + await nav.getByText('projects', { exact: true }).first().waitFor(); + await nav.getByText('projects', { exact: true }).first().dblclick(); + await nav.waitForFunction(() => window.pending.some(x => x.path === '/home/projects')); + await nav.evaluate(() => window.release('/home/projects')); + await nav.getByText('inside-projects.txt').waitFor(); + await nav.getByTitle('Back', { exact: true }).click(); + await nav.getByText('projects', { exact: true }).first().waitFor(); + assert.equal(await nav.getByTitle('Forward', { exact: true }).isDisabled(), false); + await nav.getByTitle('Forward', { exact: true }).click(); + await nav.waitForFunction(() => window.pending.some(x => x.path === '/home/projects')); + await nav.evaluate(() => window.release('/home/projects')); + await nav.getByText('inside-projects.txt').waitFor(); + console.log('PASS directory back and forward navigation'); + + const transfer = await browser.newPage(); + await transfer.goto(`http://127.0.0.1:${server.httpServer.address().port}/fm-check`); + await transfer.getByText('projects', { exact: true }).first().waitFor(); + await transfer.evaluate(() => { + window.uploadPaths = []; + window.testApi.uploadFile = (p, file, progress) => { + window.uploadPaths.push([p, file.name]); + progress(50); + return new Promise(resolve => { window.finishUpload = resolve; }); + }; + }); + await transfer.locator('input[type="file"]').setInputFiles({ name: 'upload.txt', mimeType: 'text/plain', buffer: Buffer.from('test') }); + await transfer.waitForFunction(() => Boolean(window.finishUpload)); + await transfer.getByText('projects', { exact: true }).first().dblclick(); + await transfer.waitForFunction(() => window.pending.some(x => x.path === '/home/projects')); + await transfer.evaluate(() => window.release('/home/projects')); + await transfer.getByText('inside-projects.txt').waitFor(); + const callsBeforeUpload = await transfer.evaluate(() => window.calls.length); + await transfer.evaluate(() => window.finishUpload({})); + await transfer.getByText('Uploads complete', { exact: true }).waitFor(); + assert.deepEqual(await transfer.evaluate(() => window.uploadPaths), [['/home', 'upload.txt']]); + assert.equal(await transfer.evaluate(() => window.calls.length), callsBeforeUpload, + 'finishing an upload must not reload or navigate to the previous directory'); + console.log('PASS uploads retain their destination without disrupting later navigation'); + + const images = await browser.newPage(); + await images.goto(`http://127.0.0.1:${server.httpServer.address().port}/fm-check`); + await images.getByText('projects', { exact: true }).first().waitFor(); + await images.evaluate(() => { + window.blobCalls = []; + window.testApi.getFileBlob = p => { window.blobCalls.push(p); return Promise.resolve(new Blob(['x'])); }; + window.testApi.browseRemoteFiles = (_id, p) => Promise.resolve({ path: p, entries: [{ name: 'remote.png', path: p + '/remote.png', is_dir: false }] }); + }); + await images.getByRole('button', { name: 'pick-agent' }).click(); + await images.getByText('remote.png', { exact: true }).first().dblclick(); + await images.getByText('Image preview unavailable', { exact: true }).waitFor(); + assert.deepEqual(await images.evaluate(() => window.blobCalls), []); + console.log('PASS agent image previews never fetch files from the panel host'); } finally { await browser?.close(); await server.close(); diff --git a/frontend/src/components/file-manager/FileCard.jsx b/frontend/src/components/file-manager/FileCard.jsx index e32ab265..3695a30e 100644 --- a/frontend/src/components/file-manager/FileCard.jsx +++ b/frontend/src/components/file-manager/FileCard.jsx @@ -13,7 +13,7 @@ function FileCard({ onOpen, onToggleSelect, onContext, - isS3 = false, + fileApi, }) { const { t } = useTranslation(); const ext = getFileExt(entry); @@ -51,7 +51,7 @@ function FileCard({
{showThumb ? ( - } /> + } /> ) : ( )} diff --git a/frontend/src/components/file-manager/FileManagerDialogs.jsx b/frontend/src/components/file-manager/FileManagerDialogs.jsx new file mode 100644 index 00000000..03de1dd0 --- /dev/null +++ b/frontend/src/components/file-manager/FileManagerDialogs.jsx @@ -0,0 +1,55 @@ +import { NamePromptModal, PermissionsModal } from './FileDialogs'; + +import { useTranslation } from 'react-i18next'; + +export default function FileManagerDialogs({ + dialog, + currentPath, + handleCreateFolder, + closeDialog, + handleRename, + handleChangePermissions, +}) { + const { t } = useTranslation(); + return ( + <> + {dialog?.kind === 'newFolder' && ( + + {t('app.fileManager.willBeCreatedIn', 'Will be created in:')}{' '} + {currentPath} +

+ } + submitLabel={t('app.fileManager.createFolder', 'Create folder')} + onSubmit={handleCreateFolder} + onClose={closeDialog} + /> + )} + {dialog?.kind === 'rename' && ( + handleRename(dialog.entry, name)} + onClose={closeDialog} + /> + )} + {dialog?.kind === 'permissions' && ( + handleChangePermissions(dialog.entry, mode)} + onClose={closeDialog} + /> + )} + + ); +} diff --git a/frontend/src/components/file-manager/FileManagerListing.jsx b/frontend/src/components/file-manager/FileManagerListing.jsx new file mode 100644 index 00000000..b4524d76 --- /dev/null +++ b/frontend/src/components/file-manager/FileManagerListing.jsx @@ -0,0 +1,171 @@ +import EmptyState from '@/components/EmptyState'; +import ErrorState from '@/components/ErrorState'; +import { FolderOpen, CloudUpload, Check } from 'lucide-react'; + +import { Button } from '@/components/ui/button'; + +import FileCard from './FileCard'; +import FileRow from './FileRow'; + +import { useTranslation } from 'react-i18next'; + +export default function FileManagerListing({ + fileApi, + clearSelection, + dragActive, + currentPath, + loading, + dirError, + searchResults, + loadDirectory, + sortedFiltered, + activeFilter, + viewMode, + selectedPaths, + selectMode, + rowOpen, + rowToggleSelect, + rowContext, + isS3, + setSelectedPaths, + setSelectMode, + rowDownload, + rowRename, + rowPermissions, + rowDelete, +}) { + const { t } = useTranslation(); + return ( + <> +
+
{ + if (e.target === e.currentTarget) clearSelection(); + }} + > + {dragActive && ( +
+
+ +

{t('app.fileManager.dropToUpload', 'Drop to upload')}

+

+ {t('app.fileManager.filesWillBeUploadedTo', 'Files will be uploaded to')}{' '} + {currentPath} +

+
+
+ )} + + {loading ? ( + + ) : dirError && !searchResults ? ( + loadDirectory(currentPath)} + /> + ) : sortedFiltered.length === 0 ? ( + + ) : viewMode === 'grid' ? ( +
+ {sortedFiltered.map((entry) => ( + + ))} +
+ ) : ( +
+
+ + + + {t('common.labels.name', 'Name')} + {t('common.labels.size', 'Size')} + + {t('app.fileManager.modified', 'Modified')} + + + {t('common.labels.permissions', 'Permissions')} + + {t('app.fileManager.owner', 'Owner')} + {t('common.labels.actions', 'Actions')} +
+ {sortedFiltered.map((entry) => ( + + ))} +
+ )} +
+
+ + ); +} diff --git a/frontend/src/components/file-manager/FileManagerSidebar.jsx b/frontend/src/components/file-manager/FileManagerSidebar.jsx new file mode 100644 index 00000000..aa524bab --- /dev/null +++ b/frontend/src/components/file-manager/FileManagerSidebar.jsx @@ -0,0 +1,233 @@ +import { + FolderPlus, + X, + RefreshCw, + ChevronDown, + ChevronRight, + HardDrive, + Clock, + Zap, + FolderTree as FolderTreeIcon, +} from 'lucide-react'; + +import { Button } from '@/components/ui/button'; +import FolderTree from './FolderTree'; + +import ServerPicker from '@/components/ServerPicker'; +import { serverTarget, targetServerId } from '@/utils/serverTarget'; + +import { TREE_ROOTS } from './fileTypes'; + +import { useTranslation } from 'react-i18next'; + +import { formatTime } from '@/utils/intl'; +function mountDisplayName(mount) { + if (!mount?.mountpoint || mount.mountpoint === '/') return null; + const parts = mount.mountpoint.split('/').filter(Boolean); + const leaf = parts[parts.length - 1] || mount.mountpoint; + return leaf === 'docker-desktop-user-distro' ? 'docker-desktop' : leaf; +} + + +export default function FileManagerSidebar({ + sidebarVisible, + setSidebarVisible, + target, + setTarget, + s3Options, + isS3, + isRemote, + loadDiskMounts, + diskLoading, + diskMounts, + activeMount, + navigateTo, + diskLastUpdated, + quickAccess, + currentPath, + setTreeCollapsed, + treeCollapsed, + setDialog, + treeExpanded, + treeCache, + treeLoading, + toggleTreeExpand, +}) { + const getDiskColor = (percent) => { + if (percent >= 90) return 'critical'; + if (percent >= 70) return 'warning'; + return 'healthy'; + }; + + const { t } = useTranslation(); + return ( + <> + {sidebarVisible && ( + + )} + + ); +} diff --git a/frontend/src/components/file-manager/FileManagerStatus.jsx b/frontend/src/components/file-manager/FileManagerStatus.jsx new file mode 100644 index 00000000..2d8f2374 --- /dev/null +++ b/frontend/src/components/file-manager/FileManagerStatus.jsx @@ -0,0 +1,59 @@ +import { Folder, File } from 'lucide-react'; + +import { formatBytes } from './fileTypes'; + +import { useTranslation } from 'react-i18next'; + +export default function FileManagerStatus({ stats }) { + const { t } = useTranslation(); + return ( + <> +
+
+ + {t('app.fileManager.total', 'Total')} + + {stats.total} item{stats.total !== 1 ? 's' : ''} + + + + + + + {stats.folders} folder{stats.folders !== 1 ? 's' : ''} + + + + + + {stats.files} file{stats.files !== 1 ? 's' : ''} + + + {stats.totalBytes > 0 && ( + <> + + + {t('common.labels.size', 'Size')} + {formatBytes(stats.totalBytes)} + + + )} +
+
+ {stats.selectedCount > 0 && ( + + {stats.selectedCount} {t('app.fileManager.selected', 'selected ·')}{' '} + {formatBytes(stats.selectedBytes)} + + )} + + {t('app.fileManager.upDelDeleteF2RenameA', '⌫ Up · Del Delete · F2 Rename · ⌘A All')} + +
+
+ + ); +} diff --git a/frontend/src/components/file-manager/FileManagerToolbar.jsx b/frontend/src/components/file-manager/FileManagerToolbar.jsx new file mode 100644 index 00000000..78a21e20 --- /dev/null +++ b/frontend/src/components/file-manager/FileManagerToolbar.jsx @@ -0,0 +1,263 @@ +import { + File, + ArrowLeft, + ArrowRight, + ArrowUp, + Search, + X, + RefreshCw, + Eye, + EyeOff, + HardDrive, + PanelLeftClose, + PanelLeftOpen, + LayoutGrid, + List, + Home, + ArrowUpDown, +} from 'lucide-react'; + +import { Button } from '@/components/ui/button'; + +import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from '@/components/ui/select'; + +import { useTranslation } from 'react-i18next'; + +export default function FileManagerToolbar({ + history, + setSidebarVisible, + sidebarVisible, + goBack, + historyIdx, + goForward, + goUp, + parentPath, + navigateTo, + isS3, + breadcrumbs, + activeMount, + isRemote, + activeFilter, + setActiveFilter, + FILTER_OPTIONS, + filterLabels, + filterCounts, + sortValue, + handleSortChange, + searchQuery, + setSearchQuery, + handleSearch, + searchResults, + clearSearch, + viewMode, + setViewMode, + showHidden, + setShowHidden, + loadDirectory, + currentPath, + loading, +}) { + const { t } = useTranslation(); + return ( + <> +
+
+ +
+ + + + +
+
+ {breadcrumbs.map((crumb, idx) => ( + + {idx > 0 && /} + + + ))} +
+ {activeMount && !isRemote && !isS3 && ( + + + + {activeMount.mountpoint === '/' + ? t('app.fileManager.rootDisk', 'Root disk') + : activeMount.mountpoint} + + + )} +
+
+ + +
+ + setSearchQuery(e.target.value)} + onKeyDown={(e) => e.key === 'Enter' && handleSearch()} + /> + {(searchResults || searchQuery) && ( + + )} +
+
+ + +
+ + +
+
+ + ); +} diff --git a/frontend/src/components/file-manager/FileUploadTray.jsx b/frontend/src/components/file-manager/FileUploadTray.jsx new file mode 100644 index 00000000..f679f8a5 --- /dev/null +++ b/frontend/src/components/file-manager/FileUploadTray.jsx @@ -0,0 +1,58 @@ +import { X, CloudUpload } from 'lucide-react'; + +import { Button } from '@/components/ui/button'; + +import { useTranslation } from 'react-i18next'; + +export default function FileUploadTray({ uploads, activeUploads, totalUploadProgress, setUploads }) { + const { t } = useTranslation(); + return ( + <> + {uploads.length > 0 && ( +
+
+ + + {activeUploads.length > 0 + ? t('app.fileManager.uploadingFiles', { + count: activeUploads.length, + defaultValue_one: 'Uploading 1 file…', + defaultValue_other: 'Uploading {{count}} files…', + }) + : t('app.fileManager.uploadsComplete', 'Uploads complete')} + + {activeUploads.length > 0 && ( + {Math.round(totalUploadProgress)}% + )} + +
+
+ {uploads.map((u) => ( +
+ {u.name} +
+
+
+ + {u.status === 'done' + ? t('common.actions.done', 'Done') + : u.status === 'error' + ? t('app.fileManager.uploadFailed', 'Failed') + : `${Math.round(u.progress)}%`} + +
+ ))} +
+
+ )} + + ); +} diff --git a/frontend/src/components/file-manager/ImageThumb.jsx b/frontend/src/components/file-manager/ImageThumb.jsx index 7596d837..f40c0cc0 100644 --- a/frontend/src/components/file-manager/ImageThumb.jsx +++ b/frontend/src/components/file-manager/ImageThumb.jsx @@ -1,38 +1,7 @@ -import { useEffect, useState } from 'react'; -import { api } from '../../services/api'; +import useImagePreview from './hooks/useImagePreview'; -// Auth-fetches a file via the download endpoint, converts to a blob URL, and -// renders it as an . Falls back to whatever JSX is passed in `fallback`. -export default function ImageThumb({ path, fallback, className = 'thumb-image', alt = '', isS3 = false }) { - const [src, setSrc] = useState(null); - const [errored, setErrored] = useState(false); - - useEffect(() => { - let blobUrl = null; - let cancelled = false; - (async () => { - try { - // S3 objects load straight from a short-lived presigned URL — no - // auth header or blob needed. - if (isS3) { - const res = await api.getS3DownloadUrl(path); - if (!res || !res.url) throw new Error('no presigned url'); - if (!cancelled) setSrc(res.url); - return; - } - const blob = await api.getFileBlob(path); - blobUrl = URL.createObjectURL(blob); - if (!cancelled) setSrc(blobUrl); - } catch { - if (!cancelled) setErrored(true); - } - })(); - return () => { - cancelled = true; - if (blobUrl) URL.revokeObjectURL(blobUrl); - }; - }, [path, isS3]); - - if (errored || !src) return fallback; +export default function ImageThumb({ path, fileApi, fallback, className = 'thumb-image', alt = '' }) { + const src = useImagePreview(fileApi, path); + if (!src) return fallback; return {alt}; } diff --git a/frontend/src/components/file-manager/PreviewDrawer.jsx b/frontend/src/components/file-manager/PreviewDrawer.jsx index 95b6fe7c..162e74c9 100644 --- a/frontend/src/components/file-manager/PreviewDrawer.jsx +++ b/frontend/src/components/file-manager/PreviewDrawer.jsx @@ -29,7 +29,7 @@ export default function PreviewDrawer({ // When true, render as a flush inline pane (file-manager 3rd column) // instead of a fixed-position drawer-over-scrim. inline = false, - isS3 = false, + fileApi, }) { const { t } = useTranslation(); // Lock body scroll only for the overlay drawer; the inline pane scrolls @@ -114,7 +114,7 @@ export default function PreviewDrawer({
diff --git a/frontend/src/components/file-manager/__tests__/boundaries.test.js b/frontend/src/components/file-manager/__tests__/boundaries.test.js new file mode 100644 index 00000000..43bc2d59 --- /dev/null +++ b/frontend/src/components/file-manager/__tests__/boundaries.test.js @@ -0,0 +1,20 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { + checkFileManagerBoundaries, + inspectFileManagerSource, +} from '../../../../scripts/check-file-manager-boundaries.mjs'; + +test('File Manager keeps transport, orchestration and views separate', () => { + assert.doesNotThrow(checkFileManagerBoundaries); +}); + +test('boundary guard rejects dependencies that would recombine the feature', () => { + for (const [path, source] of [ + ['pages/FileManager.jsx', 'async function load() { await api.browseFiles(); }'], + ['components/file-manager/FileManagerListing.jsx', "import { api } from '@/services/api';"], + ['components/file-manager/hooks/useFileEditor.js', "import Page from '@/pages/FileManager';"], + ['components/file-manager/FileManagerSidebar.jsx', "import useFileTree from './hooks/useFileTree';"], + ]) + assert.ok(inspectFileManagerSource(path, source).length > 0, path); +}); diff --git a/frontend/src/components/file-manager/__tests__/fileAdapter.test.js b/frontend/src/components/file-manager/__tests__/fileAdapter.test.js index bf218f12..978c0b1f 100644 --- a/frontend/src/components/file-manager/__tests__/fileAdapter.test.js +++ b/frontend/src/components/file-manager/__tests__/fileAdapter.test.js @@ -24,7 +24,7 @@ for (const kind of ['agent', 's3']) { test(`${kind} unsupported operations never reach the panel host`, () => { const { adapter, calls } = fixture({ kind, server_id: 7 }); const unsupported = ['search', 'create folder', 'rename', 'change permissions']; - if (kind === 'agent') unsupported.push('delete', 'download', 'upload'); + if (kind === 'agent') unsupported.push('delete', 'download', 'upload', 'preview'); for (const operation of unsupported) { assert.equal(adapter.supports(operation), false); assert.throws(() => adapter[operation]('/home/a'), /unavailable/); diff --git a/frontend/src/components/file-manager/fileAdapter.js b/frontend/src/components/file-manager/fileAdapter.js index 6949c432..0561808f 100644 --- a/frontend/src/components/file-manager/fileAdapter.js +++ b/frontend/src/components/file-manager/fileAdapter.js @@ -1,7 +1,7 @@ // All file operations cross this boundary. Unsupported targets never fall back // to the panel host, even if a caller forgets to disable a control. const OPERATIONS = ['browse', 'read', 'write', 'delete', 'download', 'upload', - 'search', 'create folder', 'rename', 'change permissions']; + 'search', 'create folder', 'rename', 'change permissions', 'preview']; function unwrapAgentData(result) { return result && typeof result === 'object' && 'success' in result && 'data' in result @@ -20,6 +20,7 @@ export function createFileAdapter(api, target) { 'create folder': (path) => api.createDirectory(path), rename: (path, name) => api.renameFile(path, name), 'change permissions': (path, mode) => api.changeFilePermissions(path, mode), + preview: async (path) => ({ blob: await api.getFileBlob(path) }), }; const agent = { browse: async (path) => unwrapAgentData(await api.browseRemoteFiles(target.server_id, path)), @@ -33,6 +34,7 @@ export function createFileAdapter(api, target) { delete: (path) => api.deleteS3(path), download: (entry) => api.downloadS3File(entry.path), upload: (path, file, progress) => api.uploadS3(path, file, progress), + preview: (path) => api.getS3DownloadUrl(path), }; const methods = { local, agent, s3 }[target.kind]; if (!methods) throw new Error(`Unknown file target: ${target.kind}`); diff --git a/frontend/src/components/file-manager/hooks/useDirectoryBrowser.js b/frontend/src/components/file-manager/hooks/useDirectoryBrowser.js new file mode 100644 index 00000000..6c52aba4 --- /dev/null +++ b/frontend/src/components/file-manager/hooks/useDirectoryBrowser.js @@ -0,0 +1,276 @@ +import { useState, useRef, useEffect } from 'react'; +import { useSearchParams } from 'react-router-dom'; +import { useStableHandler } from '@/hooks/useStableHandler'; +import { errorReason } from '@/utils/errorMessage'; + +function deriveParent(path) { + if (!path || path === '/' || path === '') return null; + // A Windows drive root ("C:/" or "C:") sits directly under the agent's + // drive list, which the agent serves for the "/" path. Remote agents + // emit forward-slash paths on the wire, so we only ever see "/" here. + if (/^[A-Za-z]:\/?$/.test(path)) return '/'; + const trimmed = path.replace(/\/+$/, ''); + const idx = trimmed.lastIndexOf('/'); + if (idx <= 0) return '/'; + const parent = trimmed.slice(0, idx); + // Keep a bare drive letter as a drive root ("C:" -> "C:/") so navigating + // up doesn't hit Windows' "current directory on C:" semantics. + if (/^[A-Za-z]:$/.test(parent)) return parent + '/'; + return parent; +} + +export default function useDirectoryBrowser({ + fileApi, + target, + resetSelection, + onNavigate, + remoteGuard, + toast, + t, +}) { + const [searchParams, setSearchParams] = useSearchParams(); + const previousTargetRef = useRef({ kind: 'local', server_id: null }); + // ─── core ──────────────────────────────────────────── + const [currentPath, setCurrentPath] = useState(() => searchParams.get('path') || '/home'); + const [entries, setEntries] = useState([]); + const [parentPath, setParentPath] = useState(null); + const [loading, setLoading] = useState(true); + // The open folder's own load failure, shown in the listing in place of + // "This folder is empty". Navigation into a folder that fails still + // toasts and steps back, since the previous folder is what stays shown. + const [dirError, setDirError] = useState(null); + const [showHidden, setShowHidden] = useState(false); + + // ─── search ────────────────────────────────────────── + const [searchQuery, setSearchQuery] = useState(''); + const [searchResults, setSearchResults] = useState(null); + + // ─── history ───────────────────────────────────────── + const [history, setHistory] = useState([currentPath]); + const [historyIdx, setHistoryIdx] = useState(0); + const navByHistory = useRef(false); + const lastValidPathRef = useRef(null); + // Only the newest browse may write: a slow answer for the folder the + // user just left used to land last and navigate them back to it. + const loadSeqRef = useRef(0); + const activeRequest = useRef(null); + activeRequest.current = { api: fileApi, path: currentPath }; + useEffect( + () => () => { + loadSeqRef.current++; + }, + [], + ); + + useEffect(() => { + const pathFromUrl = searchParams.get('path') || '/home'; + if (pathFromUrl !== currentPath) { + setCurrentPath(pathFromUrl); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [searchParams]); + + useEffect(() => { + const pathFromUrl = searchParams.get('path') || '/home'; + if (pathFromUrl === currentPath) return; + + const nextParams = new URLSearchParams(searchParams); + nextParams.set('path', currentPath); + setSearchParams(nextParams, { replace: true }); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [currentPath]); + + // When the user switches to a remote target, jump to its first + // advertised allowed_path so they don't see a "panel /home" view + // that doesn't exist on the remote host. + useEffect(() => { + const previousTarget = previousTargetRef.current; + const targetChanged = + previousTarget.kind !== target.kind || previousTarget.server_id !== target.server_id; + previousTargetRef.current = { kind: target.kind, server_id: target.server_id }; + + if (!targetChanged) return; + lastValidPathRef.current = null; + onNavigate(); + resetSelection(); + + const nextPath = + target.kind === 'agent' + ? target.allowedPaths?.[0] || currentPath + : target.kind === 's3' + ? '/' + : '/home'; + navByHistory.current = nextPath !== currentPath; + setHistory([nextPath]); + setHistoryIdx(0); + setCurrentPath(nextPath); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [target.kind, target.server_id]); + + // ─── load directory ────────────────────────────────── + const loadDirectory = useStableHandler(async (path) => { + if (path !== activeRequest.current.path || fileApi !== activeRequest.current.api) return; + const seq = ++loadSeqRef.current; + setLoading(true); + setSearchResults(null); + resetSelection(); + try { + const data = await fileApi.browse(path, showHidden); + if ( + seq !== loadSeqRef.current || + fileApi !== activeRequest.current.api || + path !== activeRequest.current.path + ) + return; + // Agent file:list returns {path, files: [...]} with a flat + // entry shape; panel browseFiles returns {path, parent, + // entries: [...]}. Normalize so the UI can keep using + // entries/parent. + const entriesList = data.entries || data.files || []; + setEntries(entriesList); + setParentPath(data.parent ?? deriveParent(data.path || path)); + setCurrentPath(data.path || path); + lastValidPathRef.current = data.path || path; + setDirError(null); + } catch (error) { + if ( + seq !== loadSeqRef.current || + fileApi !== activeRequest.current.api || + path !== activeRequest.current.path + ) + return; + if (lastValidPathRef.current !== null && path !== lastValidPathRef.current) { + toast.error( + t('app.fileManager.failedToLoadDirectory', "Couldn't load the folder. {{message}}", { + message: errorReason(error), + }), + ); + setCurrentPath(lastValidPathRef.current); + } else { + setEntries([]); + setDirError(error); + } + } finally { + if ( + seq === loadSeqRef.current && + fileApi === activeRequest.current.api && + path === activeRequest.current.path + ) + setLoading(false); + } + }); + + useEffect(() => { + loadDirectory(currentPath); + }, [currentPath, showHidden, fileApi, loadDirectory]); + + // history tracking + useEffect(() => { + if (navByHistory.current) { + navByHistory.current = false; + return; + } + setHistory((h) => { + const trimmed = h.slice(0, historyIdx + 1); + if (trimmed[trimmed.length - 1] === currentPath) return h; + return [...trimmed, currentPath]; + }); + setHistoryIdx((i) => (history[i] === currentPath ? i : i + 1)); + }, [currentPath]); // eslint-disable-line react-hooks/exhaustive-deps + + // ─── search ────────────────────────────────────────── + const clearSearch = () => { + loadSeqRef.current++; + setSearchResults(null); + setSearchQuery(''); + setLoading(false); + }; + const handleSearch = async () => { + if (remoteGuard('search')) { + setSearchResults([]); + return; + } + if (!searchQuery.trim()) { + clearSearch(); + return; + } + const seq = ++loadSeqRef.current; + const path = currentPath; + setLoading(true); + try { + const data = await fileApi.search(currentPath, searchQuery); + if ( + seq !== loadSeqRef.current || + fileApi !== activeRequest.current.api || + path !== activeRequest.current.path + ) + return; + setSearchResults(data.results || []); + } catch (error) { + if ( + seq !== loadSeqRef.current || + fileApi !== activeRequest.current.api || + path !== activeRequest.current.path + ) + return; + toast.error( + t('app.fileManager.searchFailed', "Couldn't search. {{message}}", { + message: errorReason(error), + }), + ); + } finally { + if ( + seq === loadSeqRef.current && + fileApi === activeRequest.current.api && + path === activeRequest.current.path + ) + setLoading(false); + } + }; + + // ─── navigation ────────────────────────────────────── + const navigateTo = (path) => { + onNavigate(); + setCurrentPath(path); + }; + + const goBack = () => { + if (historyIdx > 0) { + onNavigate(); + navByHistory.current = true; + setHistoryIdx(historyIdx - 1); + setCurrentPath(history[historyIdx - 1]); + } + }; + const goForward = () => { + if (historyIdx < history.length - 1) { + onNavigate(); + navByHistory.current = true; + setHistoryIdx(historyIdx + 1); + setCurrentPath(history[historyIdx + 1]); + } + }; + const goUp = () => parentPath && navigateTo(parentPath); + + return { + currentPath, + entries, + parentPath, + loading, + dirError, + showHidden, + setShowHidden, + searchQuery, + setSearchQuery, + searchResults, + clearSearch, + history, + historyIdx, + loadDirectory, + handleSearch, + navigateTo, + goBack, + goForward, + goUp, + }; +} diff --git a/frontend/src/components/file-manager/hooks/useFileActions.js b/frontend/src/components/file-manager/hooks/useFileActions.js new file mode 100644 index 00000000..f998a23b --- /dev/null +++ b/frontend/src/components/file-manager/hooks/useFileActions.js @@ -0,0 +1,149 @@ +import { useState, useRef, useEffect } from 'react'; +import { useConfirm } from '@/hooks/useConfirm'; +import { errorReason } from '@/utils/errorMessage'; + +export default function useFileActions({ + fileApi, + currentPath, + remoteGuard, + loadDirectory, + refreshTree, + previewFile, + setPreviewFile, + clearSelection, + toast, + t, +}) { + // ─── modals ────────────────────────────────────────── + // { kind: 'newFolder' } | { kind: 'rename', entry } | { kind: 'permissions', entry } | null + const [dialog, setDialog] = useState(null); + const closeDialog = () => setDialog(null); + const { confirm } = useConfirm(); + const active = useRef(null); + active.current = { fileApi, currentPath }; + const isCurrent = () => + active.current?.fileApi === fileApi && active.current?.currentPath === currentPath; + useEffect(() => { + setDialog(null); + }, [fileApi, currentPath]); + useEffect( + () => () => { + active.current = null; + }, + [], + ); + + const handleCreateFolder = async (name) => { + if (remoteGuard('create folder')) return; + try { + await fileApi['create folder'](`${currentPath}/${name}`); + if (!isCurrent()) return; + toast.success(t('app.fileManager.folderCreated', 'Folder created')); + closeDialog(); + loadDirectory(currentPath); + refreshTree(currentPath); + } catch (error) { + if (!isCurrent()) return; + toast.error( + t('app.fileManager.failedToCreateFolder', "Couldn't create the folder. {{message}}", { + message: errorReason(error), + }), + ); + } + }; + + const handleDelete = async (target) => { + const items = Array.isArray(target) ? target : [target]; + if (items.length === 0) return; + if (remoteGuard('delete')) return; + const message = + items.length === 1 + ? `Delete "${items[0].name}"?${items[0].is_dir ? ' All contents inside will be removed.' : ''}` + : `Delete ${items.length} items? This cannot be undone.`; + if ( + !(await confirm({ + title: t('app.fileManager.deleteConfirmation', 'Delete confirmation'), + message, + confirmText: t('common.actions.delete', 'Delete'), + variant: 'danger', + })) + ) + return; + if (!isCurrent()) return; + const failures = []; + for (const it of items) { + try { + await fileApi.del(it.path); + } catch (error) { + failures.push(`${it.name}: ${error.message}`); + } + } + if (!isCurrent()) return; + if (failures.length === 0) + toast.success( + t('app.fileManager.deletedItems', { + count: items.length, + defaultValue_one: 'Deleted 1 item', + defaultValue_other: 'Deleted {{count}} items', + }), + ); + else + toast.error( + t('app.fileManager.failed', "Couldn't finish for: {{value}}", { value: failures.join(', ') }), + ); + if (previewFile && items.some((i) => i.path === previewFile.path)) setPreviewFile(null); + clearSelection(); + loadDirectory(currentPath); + }; + + const handleRename = async (entry, name) => { + if (remoteGuard('rename')) return; + try { + await fileApi.rename(entry.path, name); + if (!isCurrent()) return; + toast.success(t('app.fileManager.renamed', 'Renamed')); + closeDialog(); + loadDirectory(currentPath); + } catch (error) { + if (!isCurrent()) return; + toast.error( + t('app.fileManager.failedToRename', "Couldn't rename it. {{message}}", { + message: errorReason(error), + }), + ); + } + }; + + const handleChangePermissions = async (entry, mode) => { + if (remoteGuard('change permissions')) return; + try { + await fileApi['change permissions'](entry.path, mode); + if (!isCurrent()) return; + toast.success(t('app.fileManager.permissionsUpdated', 'Permissions updated')); + closeDialog(); + loadDirectory(currentPath); + } catch (error) { + if (!isCurrent()) return; + toast.error( + t('app.fileManager.failed2', "Couldn't do that. {{message}}", { + message: errorReason(error), + }), + ); + } + }; + + const openRenameModal = (entry) => setDialog({ kind: 'rename', entry }); + const openPermissionsModal = (entry) => setDialog({ kind: 'permissions', entry }); + + return { + dialog, + setDialog, + closeDialog, + handleCreateFolder, + handleDelete, + handleRename, + handleChangePermissions, + openRenameModal, + openPermissionsModal, + }; +} diff --git a/frontend/src/components/file-manager/hooks/useFileEditor.js b/frontend/src/components/file-manager/hooks/useFileEditor.js new file mode 100644 index 00000000..82344c4c --- /dev/null +++ b/frontend/src/components/file-manager/hooks/useFileEditor.js @@ -0,0 +1,74 @@ +import { useEffect, useRef, useState } from 'react'; +import { errorReason } from '@/utils/errorMessage'; + +export default function useFileEditor({ fileApi, toast, t, onSaved }) { + const [previewFile, setPreview] = useState(null); + const [fileContent, setFileContent] = useState(''); + const [editing, setEditing] = useState(false); + const generation = useRef(0); + const activeApi = useRef(fileApi); + activeApi.current = fileApi; + useEffect( + () => () => { + generation.current++; + }, + [], + ); + + const setPreviewFile = (entry) => { + generation.current++; + setPreview(entry); + setFileContent(''); + setEditing(false); + }; + + const openFile = async (entry) => { + setPreviewFile(entry); + const request = generation.current; + if (!entry.is_editable) return; + try { + const data = await fileApi.read(entry.path); + if (request === generation.current && fileApi === activeApi.current) { + setFileContent(data.content); + } + } catch (error) { + if (request === generation.current && fileApi === activeApi.current) { + toast.error( + t('app.fileManager.failedToReadFile', "Couldn't read the file. {{message}}", { + message: errorReason(error), + }), + ); + } + } + }; + + const handleSaveFile = async () => { + if (!previewFile) return; + const request = generation.current; + try { + await fileApi.write(previewFile.path, fileContent); + if (request !== generation.current || fileApi !== activeApi.current) return; + toast.success(t('app.fileManager.fileSaved', 'File saved')); + setEditing(false); + onSaved(); + } catch (error) { + if (request !== generation.current || fileApi !== activeApi.current) return; + toast.error( + t('app.fileManager.failedToSave', "Couldn't save. {{message}}", { + message: errorReason(error), + }), + ); + } + }; + + return { + previewFile, + setPreviewFile, + fileContent, + setFileContent, + editing, + setEditing, + openFile, + handleSaveFile, + }; +} diff --git a/frontend/src/components/file-manager/hooks/useFileListingModel.js b/frontend/src/components/file-manager/hooks/useFileListingModel.js new file mode 100644 index 00000000..7f31eb5f --- /dev/null +++ b/frontend/src/components/file-manager/hooks/useFileListingModel.js @@ -0,0 +1,137 @@ +import { useMemo } from 'react'; +import { getFileType } from '../fileTypes'; + +export const FILTER_OPTIONS = [ + { id: 'all', labelKey: 'common.labels.all', label: 'All' }, + { id: 'folder', labelKey: 'app.fileManager.folders', label: 'Folders' }, + { id: 'image', labelKey: 'app.fileManager.images', label: 'Images' }, + { id: 'code', labelKey: 'app.fileManager.code', label: 'Code' }, + { id: 'text', labelKey: 'app.fileManager.documents', label: 'Documents' }, + { id: 'data', labelKey: 'app.fileManager.data', label: 'Data' }, + { id: 'video', labelKey: 'app.fileManager.videos', label: 'Videos' }, + { id: 'audio', labelKey: 'app.fileManager.audio', label: 'Audio' }, + { id: 'archive', labelKey: 'app.fileManager.archives', label: 'Archives' }, +]; + +export default function useFileListingModel({ + currentPath, + entries, + searchResults, + activeFilter, + sortBy, + sortDir, + selectedPaths, + setSortBy, + setSortDir, + t, +}) { + // ─── derived ───────────────────────────────────────── + const breadcrumbs = useMemo(() => { + const parts = currentPath.split('/').filter(Boolean); + // Windows drive-rooted path ("C:/Users/Juan"): the first segment is + // the drive and the root crumb is the agent's drive list. Building + // crumbs with a leading "/" (the POSIX branch below) would produce + // bogus "/C:" paths that the agent can't resolve. + if (/^[A-Za-z]:$/.test(parts[0] || '')) { + const crumbs = [{ name: 'Drives', path: '/' }]; + let acc = parts[0]; + crumbs.push({ name: parts[0], path: acc + '/' }); + for (let i = 1; i < parts.length; i++) { + acc += '/' + parts[i]; + crumbs.push({ name: parts[i], path: acc }); + } + return crumbs; + } + const crumbs = [{ name: '/', path: '/' }]; + let acc = ''; + parts.forEach((p) => { + acc += '/' + p; + crumbs.push({ name: p, path: acc }); + }); + return crumbs; + }, [currentPath]); + + const sortedFiltered = useMemo(() => { + let list = [...(searchResults || entries)]; + if (activeFilter !== 'all') list = list.filter((e) => getFileType(e) === activeFilter); + const dir = sortDir === 'asc' ? 1 : -1; + list.sort((a, b) => { + if (a.is_dir !== b.is_dir) return a.is_dir ? -1 : 1; + switch (sortBy) { + case 'size': + return ((a.size || 0) - (b.size || 0)) * dir; + case 'modified': + return (new Date(a.modified) - new Date(b.modified)) * dir; + case 'type': + return getFileType(a).localeCompare(getFileType(b)) * dir; + case 'name': + default: + return a.name.localeCompare(b.name) * dir; + } + }); + return list; + }, [entries, searchResults, sortBy, sortDir, activeFilter]); + + const filterCounts = useMemo(() => { + const counts = { all: entries.length }; + FILTER_OPTIONS.forEach((c) => { + if (c.id !== 'all') counts[c.id] = 0; + }); + entries.forEach((e) => { + const t = getFileType(e); + if (counts[t] !== undefined) counts[t]++; + }); + return counts; + }, [entries]); + + const stats = useMemo(() => { + const list = sortedFiltered; + const folders = list.filter((e) => e.is_dir).length; + const files = list.length - folders; + const totalBytes = list.reduce((s, e) => s + (e.size || 0), 0); + const selectedList = list.filter((e) => selectedPaths.has(e.path)); + const selectedBytes = selectedList.reduce((s, e) => s + (e.size || 0), 0); + return { + folders, + files, + totalBytes, + total: list.length, + selectedCount: selectedList.length, + selectedBytes, + }; + }, [sortedFiltered, selectedPaths]); + + const sortValue = `${sortBy}-${sortDir}`; + const filterLabels = { + all: t('common.labels.all', 'All'), + folder: t('app.fileManager.folders', 'Folders'), + image: t('app.fileManager.images', 'Images'), + code: t('app.fileManager.code', 'Code'), + text: t('app.fileManager.documents', 'Documents'), + data: t('app.fileManager.data', 'Data'), + video: t('app.fileManager.videos', 'Videos'), + audio: t('app.fileManager.audio', 'Audio'), + archive: t('app.fileManager.archives', 'Archives'), + }; + const handleSortChange = (value) => { + const [nextSortBy, nextSortDir] = value.split('-'); + setSortBy(nextSortBy); + setSortDir(nextSortDir); + }; + + const selectedEntries = useMemo( + () => sortedFiltered.filter((e) => selectedPaths.has(e.path)), + [sortedFiltered, selectedPaths], + ); + + return { + breadcrumbs, + sortedFiltered, + filterCounts, + stats, + sortValue, + filterLabels, + handleSortChange, + selectedEntries, + }; +} diff --git a/frontend/src/components/file-manager/hooks/useFilePreferences.js b/frontend/src/components/file-manager/hooks/useFilePreferences.js new file mode 100644 index 00000000..ec15eb63 --- /dev/null +++ b/frontend/src/components/file-manager/hooks/useFilePreferences.js @@ -0,0 +1,33 @@ +import { useState } from 'react'; +import usePersistentState from '@/hooks/usePersistentState'; +import { STORAGE, isNarrowScreen } from '../preferences'; +export default function useFilePreferences() { + // ─── view prefs ────────────────────────────────────── + const [viewMode, setViewMode] = usePersistentState(STORAGE.viewMode, (v) => v || 'list'); + const gridSize = 'md'; + const [sortBy, setSortBy] = usePersistentState(STORAGE.sortBy, (v) => v || 'name'); + const [sortDir, setSortDir] = usePersistentState(STORAGE.sortDir, (v) => v || 'asc'); + const [activeFilter, setActiveFilter] = useState('all'); + + // ─── left sidebar ──────────────────────────────────── + const [sidebarVisible, setSidebarVisible] = usePersistentState(STORAGE.sidebar, (v) => + isNarrowScreen() ? false : v !== null ? v === 'true' : true, + ); + const [treeCollapsed, setTreeCollapsed] = usePersistentState(STORAGE.treeCollapsed, (v) => v === 'true'); + + return { + viewMode, + setViewMode, + gridSize, + sortBy, + setSortBy, + sortDir, + setSortDir, + activeFilter, + setActiveFilter, + sidebarVisible, + setSidebarVisible, + treeCollapsed, + setTreeCollapsed, + }; +} diff --git a/frontend/src/components/file-manager/hooks/useFileSelection.js b/frontend/src/components/file-manager/hooks/useFileSelection.js new file mode 100644 index 00000000..eef15f44 --- /dev/null +++ b/frontend/src/components/file-manager/hooks/useFileSelection.js @@ -0,0 +1,47 @@ +import { useState } from 'react'; +export default function useFileSelection() { + // ─── selection ─────────────────────────────────────── + const [selectedPaths, setSelectedPaths] = useState(new Set()); + const [lastClickedPath, setLastClickedPath] = useState(null); + const [selectMode, setSelectMode] = useState(false); + + // ─── selection ─────────────────────────────────────── + const toggleSelect = (entry, e, sortedFiltered) => { + const path = entry.path; + if (e?.shiftKey && lastClickedPath) { + const list = sortedFiltered; + const a = list.findIndex((x) => x.path === lastClickedPath); + const b = list.findIndex((x) => x.path === path); + if (a >= 0 && b >= 0) { + const [from, to] = [Math.min(a, b), Math.max(a, b)]; + const rangePaths = list.slice(from, to + 1).map((x) => x.path); + const next = new Set([...selectedPaths, ...rangePaths]); + setSelectedPaths(next); + setSelectMode(next.size > 0); + } + } else { + const next = new Set(selectedPaths); + if (next.has(path)) next.delete(path); + else next.add(path); + setSelectedPaths(next); + setSelectMode(next.size > 0); + setLastClickedPath(path); + } + }; + + const clearSelection = () => { + setSelectedPaths(new Set()); + setSelectMode(false); + setLastClickedPath(null); + }; + + return { + selectedPaths, + setSelectedPaths, + selectMode, + setSelectMode, + setLastClickedPath, + toggleSelect, + clearSelection, + }; +} diff --git a/frontend/src/components/file-manager/hooks/useFileTargets.js b/frontend/src/components/file-manager/hooks/useFileTargets.js new file mode 100644 index 00000000..43f189a7 --- /dev/null +++ b/frontend/src/components/file-manager/hooks/useFileTargets.js @@ -0,0 +1,120 @@ +import { useState, useEffect, useMemo } from 'react'; +import { Globe, Boxes, SlidersHorizontal, FileText, Home } from 'lucide-react'; +import { api } from '@/services/api'; +// Demo rail shortcuts (Quick access) — one-click jumps to the paths people +// actually visit on a ServerKit host. "Stack" starts at the default install +// location and is re-pointed from /system/version's install_dir, so a custom +// SERVERKIT_DIR install jumps to the real tree. +const QUICK_ACCESS = [ + { labelKey: 'app.fileManager.sites', label: 'Sites', path: '/var/www', icon: Globe }, + { labelKey: 'app.fileManager.stack', label: 'Stack', path: '/opt/serverkit', icon: Boxes }, + { + labelKey: 'app.fileManager.webConfig', + label: 'Web config', + path: '/etc/nginx', + icon: SlidersHorizontal, + }, + { labelKey: 'common.labels.logs', label: 'Logs', path: '/var/log', icon: FileText }, +]; + +// Remote-agent rails: the panel stack doesn't exist on an agent box, so link +// the agent's own footprint instead. These paths are fixed by the agent +// installers the panel serves (scripts/install.sh: /etc/serverkit-agent; +// scripts/install.ps1: ProgramData\ServerKit\Agent) — agents run on the wire +// with forward-slash paths, Windows included. +const QUICK_ACCESS_AGENT = { + linux: [ + { labelKey: 'app.fileManager.sites', label: 'Sites', path: '/var/www', icon: Globe }, + { labelKey: 'app.fileManager.agent', label: 'Agent', path: '/etc/serverkit-agent', icon: Boxes }, + { + labelKey: 'app.fileManager.webConfig', + label: 'Web config', + path: '/etc/nginx', + icon: SlidersHorizontal, + }, + { labelKey: 'common.labels.logs', label: 'Logs', path: '/var/log', icon: FileText }, + ], + windows: [ + { + labelKey: 'app.fileManager.agent', + label: 'Agent', + path: 'C:/ProgramData/ServerKit/Agent', + icon: Boxes, + }, + { + labelKey: 'app.fileManager.agentLogs', + label: 'Agent logs', + path: 'C:/ProgramData/ServerKit/Agent/logs', + icon: FileText, + }, + { labelKey: 'app.fileManager.users', label: 'Users', path: 'C:/Users', icon: Home }, + ], + darwin: [ + { labelKey: 'app.fileManager.home', label: 'Home', path: '/Users', icon: Home }, + { labelKey: 'common.labels.logs', label: 'Logs', path: '/var/log', icon: FileText }, + ], +}; + +export default function useFileTargets({ target, isRemote, t }) { + // The "S3 bucket" target is offered only when an S3-compatible backup + // destination is configured (Connections → Storage, or the Backups page). + const [s3Available, setS3Available] = useState(false); + const s3Options = useMemo( + () => (s3Available ? [{ value: 's3', label: t('app.fileManager.s3Bucket', 'S3 bucket') }] : []), + [s3Available, t], + ); + useEffect(() => { + let cancelled = false; + api.getStorageConfig() + .then((c) => { + if (cancelled) return; + const p = c?.provider; + setS3Available((p === 's3' || p === 'b2') && Boolean(c?.[p]?.bucket)); + }) + .catch(() => {}); + return () => { + cancelled = true; + }; + }, []); + + // The "Stack" quick link tracks the panel's real install dir (custom + // SERVERKIT_DIR installs aren't at /opt/serverkit). + const [panelInstallDir, setPanelInstallDir] = useState('/opt/serverkit'); + useEffect(() => { + let cancelled = false; + api.getVersion() + .then((v) => { + if (!cancelled && v?.install_dir) setPanelInstallDir(v.install_dir); + }) + .catch(() => {}); + return () => { + cancelled = true; + }; + }, []); + + // Per-target rail: agents get their OS's set (unknown os_type — an agent + // predating sysinfo reporting — is treated as linux, the historical + // behavior), with the agent's SELF-REPORTED config dir preferred over the + // installer convention when the agent sent one (system_info footprint); + // the local host gets the panel set with the resolved Stack dir. + const quickAccess = useMemo(() => { + if (isRemote) { + const os = (target.os_type || 'linux').toLowerCase(); + const rail = QUICK_ACCESS_AGENT[os] || QUICK_ACCESS_AGENT.linux; + // Windows agents report filepath-style backslashes; the file + // wire protocol speaks forward slashes. + const configDir = target.agentConfigDir + ? target.agentConfigDir.replace(/\\/g, '/').replace(/\/+$/, '') + : null; + if (!configDir) return rail; + return rail.map((q) => { + if (q.label === 'Agent') return { ...q, path: configDir }; + if (q.label === 'Agent logs') return { ...q, path: `${configDir}/logs` }; + return q; + }); + } + return QUICK_ACCESS.map((q) => (q.label === 'Stack' ? { ...q, path: panelInstallDir } : q)); + }, [isRemote, target.os_type, target.agentConfigDir, panelInstallDir]); + + return { s3Options, quickAccess }; +} diff --git a/frontend/src/components/file-manager/hooks/useFileTransfers.js b/frontend/src/components/file-manager/hooks/useFileTransfers.js new file mode 100644 index 00000000..9fb5fb79 --- /dev/null +++ b/frontend/src/components/file-manager/hooks/useFileTransfers.js @@ -0,0 +1,129 @@ +import { useState, useRef, useEffect } from 'react'; +export default function useFileTransfers({ fileApi, currentPath, remoteGuard, loadDirectory, toast, t }) { + // ─── upload ────────────────────────────────────────── + const [uploads, setUploads] = useState([]); + const [dragActive, setDragActive] = useState(false); + const fileInputRef = useRef(null); + const dragCounter = useRef(0); + const nextBatch = useRef(0); + const timers = useRef(new Set()); + const mounted = useRef(true); + const active = useRef(null); + active.current = { fileApi, currentPath }; + useEffect(() => { + mounted.current = true; + const pendingTimers = timers.current; + return () => { + mounted.current = false; + pendingTimers.forEach(clearTimeout); + }; + }, []); + + // ─── upload ────────────────────────────────────────── + const uploadFiles = async (files) => { + const fileList = Array.from(files); + if (fileList.length === 0) return; + if (remoteGuard('upload')) return; + const batch = ++nextBatch.current; + const queue = fileList.map((f, i) => ({ + id: `${batch}-${i}`, + name: f.name, + size: f.size, + progress: 0, + status: 'pending', + })); + setUploads((p) => [...p, ...queue]); + + let succeeded = 0; + for (let i = 0; i < fileList.length; i++) { + if (!mounted.current) return; + const file = fileList[i]; + const itemId = queue[i].id; + try { + setUploads((p) => p.map((u) => (u.id === itemId ? { ...u, status: 'uploading' } : u))); + const doUpload = fileApi.upload; + await doUpload(currentPath, file, (progress) => { + if (!mounted.current) return; + setUploads((p) => p.map((u) => (u.id === itemId ? { ...u, progress } : u))); + }); + if (!mounted.current) return; + setUploads((p) => + p.map((u) => (u.id === itemId ? { ...u, status: 'done', progress: 100 } : u)), + ); + succeeded++; + } catch (error) { + if (!mounted.current) return; + setUploads((p) => + p.map((u) => (u.id === itemId ? { ...u, status: 'error', error: error.message } : u)), + ); + } + } + if (succeeded > 0) + toast.success( + t('app.fileManager.uploadedFiles', { + count: fileList.length, + succeeded, + defaultValue_one: 'Uploaded {{succeeded}} of 1 file', + defaultValue_other: 'Uploaded {{succeeded}} of {{count}} files', + }), + ); + if (active.current.fileApi === fileApi && active.current.currentPath === currentPath) { + loadDirectory(currentPath); + } + const ids = new Set(queue.map((item) => item.id)); + const timer = setTimeout(() => { + timers.current.delete(timer); + setUploads((p) => p.filter((u) => !ids.has(u.id))); + }, 4000); + timers.current.add(timer); + }; + + const handleUploadInput = (e) => { + if (e.target.files) uploadFiles(e.target.files); + if (fileInputRef.current) fileInputRef.current.value = ''; + }; + + const handleDragEnter = (e) => { + e.preventDefault(); + e.stopPropagation(); + dragCounter.current += 1; + if (e.dataTransfer.items?.length > 0) setDragActive(true); + }; + const handleDragLeave = (e) => { + e.preventDefault(); + e.stopPropagation(); + dragCounter.current -= 1; + if (dragCounter.current === 0) setDragActive(false); + }; + const handleDragOver = (e) => { + e.preventDefault(); + e.stopPropagation(); + }; + const handleDrop = (e) => { + e.preventDefault(); + e.stopPropagation(); + dragCounter.current = 0; + setDragActive(false); + if (e.dataTransfer.files?.length > 0) uploadFiles(e.dataTransfer.files); + }; + + const activeUploads = uploads.filter((u) => u.status === 'uploading' || u.status === 'pending'); + const totalUploadProgress = + activeUploads.length > 0 + ? activeUploads.reduce((s, u) => s + u.progress, 0) / activeUploads.length + : 0; + + return { + uploads, + setUploads, + dragActive, + fileInputRef, + handleUploadInput, + handleDragEnter, + handleDragLeave, + handleDragOver, + handleDrop, + activeUploads, + totalUploadProgress, + }; +} diff --git a/frontend/src/components/file-manager/hooks/useFileTree.js b/frontend/src/components/file-manager/hooks/useFileTree.js new file mode 100644 index 00000000..5c2827dd --- /dev/null +++ b/frontend/src/components/file-manager/hooks/useFileTree.js @@ -0,0 +1,118 @@ +import { useState, useCallback, useEffect, useRef } from 'react'; +import usePersistentState from '@/hooks/usePersistentState'; +import { STORAGE, parseExpanded, serializeExpanded } from '../preferences'; +import { TREE_ROOTS } from '../fileTypes'; +export default function useFileTree({ fileApi, currentPath }) { + // ─── folder tree state ─────────────────────────────── + const [treeExpanded, setTreeExpanded] = usePersistentState( + STORAGE.expanded, + parseExpanded, + serializeExpanded, + ); + const [treeCache, setTreeCache] = useState(new Map()); + const [treeLoading, setTreeLoading] = useState(new Set()); + const activeApi = useRef(fileApi); + activeApi.current = fileApi; + const mounted = useRef(true); + useEffect(() => { + mounted.current = true; + return () => { + mounted.current = false; + }; + }, []); + useEffect(() => { + setTreeCache(new Map()); + setTreeLoading(new Set()); + }, [fileApi]); + + const refreshTree = async (path) => { + if (!treeCache.has(path)) return; + try { + const data = await fileApi.browse(path, false); + if (!mounted.current || activeApi.current !== fileApi) return; + const folders = (data.entries || data.files || []) + .filter((e) => e.is_dir) + .map(({ path, name }) => ({ path, name })); + setTreeCache((c) => new Map(c).set(path, folders)); + } catch { + /* A failed refresh leaves the last known tree visible. */ + } + }; + + // ─── tree expand/collapse ──────────────────────────── + const toggleTreeExpand = useCallback( + async (path) => { + if (treeExpanded.has(path)) { + const next = new Set(treeExpanded); + next.delete(path); + setTreeExpanded(next); + return; + } + if (!treeCache.has(path)) { + setTreeLoading((s) => { + const n = new Set(s); + n.add(path); + return n; + }); + try { + const data = await fileApi.browse(path, false); + if (!mounted.current || activeApi.current !== fileApi) return; + const entries = data.entries || data.files || []; + const folders = entries + .filter((e) => e.is_dir) + .map((e) => ({ + path: e.path, + name: e.name, + })); + setTreeCache((c) => { + const n = new Map(c); + n.set(path, folders); + return n; + }); + } catch { + if (!mounted.current || activeApi.current !== fileApi) return; + setTreeCache((c) => { + const n = new Map(c); + n.set(path, []); + return n; + }); + } finally { + if (mounted.current && activeApi.current === fileApi) { + setTreeLoading((s) => { + const n = new Set(s); + n.delete(path); + return n; + }); + } + } + } + setTreeExpanded((s) => { + const n = new Set(s); + n.add(path); + return n; + }); + }, + [treeExpanded, treeCache, fileApi, setTreeExpanded], + ); + + // Auto-expand the tree along the current path so the active row is visible. + useEffect(() => { + const parts = currentPath.split('/').filter(Boolean); + const ancestors = []; + let acc = ''; + for (const p of parts) { + acc += '/' + p; + ancestors.push(acc); + } + ancestors.forEach((a) => { + const isUnderRoot = TREE_ROOTS.some( + (r) => a === r.path || a.startsWith(r.path + '/') || r.path.startsWith(a + '/'), + ); + if (isUnderRoot && !treeExpanded.has(a) && a !== currentPath) { + toggleTreeExpand(a); + } + }); + }, [currentPath]); // eslint-disable-line react-hooks/exhaustive-deps + + return { treeExpanded, treeCache, refreshTree, treeLoading, toggleTreeExpand }; +} diff --git a/frontend/src/components/file-manager/hooks/useFileVolumes.js b/frontend/src/components/file-manager/hooks/useFileVolumes.js new file mode 100644 index 00000000..70a7b5a9 --- /dev/null +++ b/frontend/src/components/file-manager/hooks/useFileVolumes.js @@ -0,0 +1,43 @@ +import { useState, useEffect, useMemo } from 'react'; +import { api } from '@/services/api'; +export default function useFileVolumes(currentPath) { + // ─── disk ──────────────────────────────────────────── + const [diskMounts, setDiskMounts] = useState([]); + const [diskLastUpdated, setDiskLastUpdated] = useState(null); + const [diskLoading, setDiskLoading] = useState(false); + + // ─── disk mounts ───────────────────────────────────── + const loadDiskMounts = async () => { + setDiskLoading(true); + try { + const data = await api.getAllDiskMounts(); + setDiskMounts(data.mounts || []); + setDiskLastUpdated(new Date()); + } catch (e) { + console.error('Failed to load disk mounts:', e); + } finally { + setDiskLoading(false); + } + }; + + const activeMount = useMemo( + () => + diskMounts + .filter((mount) => { + const mountPath = mount.mountpoint || '/'; + if (mountPath === '/') return currentPath.startsWith('/'); + return ( + currentPath === mountPath || + currentPath.startsWith(`${mountPath.replace(/\/$/, '')}/`) + ); + }) + .sort((a, b) => (b.mountpoint || '/').length - (a.mountpoint || '/').length)[0] || null, + [currentPath, diskMounts], + ); + + useEffect(() => { + loadDiskMounts(); + }, []); + + return { diskMounts, diskLastUpdated, diskLoading, loadDiskMounts, activeMount }; +} diff --git a/frontend/src/components/file-manager/hooks/useImagePreview.js b/frontend/src/components/file-manager/hooks/useImagePreview.js new file mode 100644 index 00000000..0e70d082 --- /dev/null +++ b/frontend/src/components/file-manager/hooks/useImagePreview.js @@ -0,0 +1,27 @@ +import { useEffect, useState } from 'react'; + +// Blob lifetime belongs to the mounted thumbnail, not to the storage adapter. +export default function useImagePreview(fileApi, path) { + const [image, setImage] = useState(null); + useEffect(() => { + let cancelled = false; + let blobUrl; + setImage(null); + if (!fileApi?.supports('preview')) return undefined; + fileApi + .preview(path) + .then((result) => { + if (cancelled) return; + const url = result.blob ? (blobUrl = URL.createObjectURL(result.blob)) : result.url; + setImage({ fileApi, path, url }); + }) + .catch(() => { + /* Render the supplied fallback on failure. */ + }); + return () => { + cancelled = true; + if (blobUrl) URL.revokeObjectURL(blobUrl); + }; + }, [fileApi, path]); + return image?.fileApi === fileApi && image?.path === path ? image.url : null; +} diff --git a/frontend/src/components/file-manager/preferences.js b/frontend/src/components/file-manager/preferences.js new file mode 100644 index 00000000..e6ccd627 --- /dev/null +++ b/frontend/src/components/file-manager/preferences.js @@ -0,0 +1,19 @@ +export const STORAGE = { + sidebar: 'serverkit-fm-sidebar', + treeCollapsed: 'serverkit-fm-tree-collapsed', + expanded: 'serverkit-fm-tree-expanded', + viewMode: 'serverkit-fm-view-mode', + sortBy: 'serverkit-fm-sort-by', + sortDir: 'serverkit-fm-sort-dir', +}; + +export const serializeExpanded = (set) => JSON.stringify([...set]); +export const parseExpanded = (stored) => { + try { + return stored ? new Set(JSON.parse(stored)) : new Set(); + } catch { + return new Set(); + } +}; +export const isNarrowScreen = () => + typeof window !== 'undefined' && window.matchMedia('(max-width: 1024px)').matches; diff --git a/frontend/src/pages/FileManager.jsx b/frontend/src/pages/FileManager.jsx index eb1c1481..40cf619b 100644 --- a/frontend/src/pages/FileManager.jsx +++ b/frontend/src/pages/FileManager.jsx @@ -1,133 +1,40 @@ -import { useState, useEffect, useRef, useMemo, useCallback } from 'react'; +import useFileListingModel, { FILTER_OPTIONS } from '../components/file-manager/hooks/useFileListingModel'; +import FileManagerDialogs from '../components/file-manager/FileManagerDialogs'; +import FileManagerStatus from '../components/file-manager/FileManagerStatus'; +import FileUploadTray from '../components/file-manager/FileUploadTray'; +import FileManagerListing from '../components/file-manager/FileManagerListing'; +import FileManagerToolbar from '../components/file-manager/FileManagerToolbar'; +import FileManagerSidebar from '../components/file-manager/FileManagerSidebar'; +import useFileActions from '../components/file-manager/hooks/useFileActions'; +import useFileEditor from '../components/file-manager/hooks/useFileEditor'; +import useDirectoryBrowser from '../components/file-manager/hooks/useDirectoryBrowser'; +import useFileTransfers from '../components/file-manager/hooks/useFileTransfers'; +import useFileVolumes from '../components/file-manager/hooks/useFileVolumes'; +import useFileTree from '../components/file-manager/hooks/useFileTree'; +import useFileSelection from '../components/file-manager/hooks/useFileSelection'; +import useFilePreferences from '../components/file-manager/hooks/useFilePreferences'; +import useFileTargets from '../components/file-manager/hooks/useFileTargets'; +import { useState, useEffect, useMemo, useCallback } from 'react'; import { api } from '../services/api'; import { createFileAdapter } from '../components/file-manager/fileAdapter'; import { useToast } from '../contexts/useToast.js'; -import ConfirmDialog from '../components/ConfirmDialog'; -import EmptyState from '../components/EmptyState'; -import ErrorState from '../components/ErrorState'; -import { - Folder, FolderOpen, File, Upload, FolderPlus, - ArrowLeft, ArrowRight, ArrowUp, Search, X, RefreshCw, Eye, EyeOff, - Download, Edit3, Trash2, ChevronDown, ChevronRight, - HardDrive, Clock, PanelLeftClose, PanelLeftOpen, - LayoutGrid, List, Home, CloudUpload, - Check, Copy, ArrowUpDown, Zap, Globe, Boxes, SlidersHorizontal, FileText, - FolderTree as FolderTreeIcon, Terminal, -} from 'lucide-react'; -import { useNavigate, useSearchParams } from 'react-router-dom'; + +import { Upload, FolderPlus, X, Download, Edit3, Trash2, Check, Copy, Terminal } from 'lucide-react'; +import { useNavigate } from 'react-router-dom'; import { Button } from '@/components/ui/button'; -import FolderTree from '../components/file-manager/FolderTree'; -import FileCard from '../components/file-manager/FileCard'; -import FileRow from '../components/file-manager/FileRow'; import PreviewDrawer from '../components/file-manager/PreviewDrawer'; import ContextMenu from '../components/file-manager/ContextMenu'; -import { NamePromptModal, PermissionsModal } from '../components/file-manager/FileDialogs'; -import ServerPicker from '../components/ServerPicker'; -import { serverTarget, targetServerId } from '../utils/serverTarget'; -import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from '@/components/ui/select'; -import { TREE_ROOTS, getFileType, formatBytes } from '../components/file-manager/fileTypes'; + +import { formatBytes } from '../components/file-manager/fileTypes'; import { useClipboard } from '@/hooks/useClipboard'; import { useTranslation } from 'react-i18next'; import { useTopbarActions } from '@/hooks/useTopbarActions'; -import { errorReason } from '@/utils/errorMessage'; -import usePersistentState from '@/hooks/usePersistentState'; import { useStableHandler } from '@/hooks/useStableHandler'; -import { formatTime } from '@/utils/intl'; - -// Demo rail shortcuts (Quick access) — one-click jumps to the paths people -// actually visit on a ServerKit host. "Stack" starts at the default install -// location and is re-pointed from /system/version's install_dir, so a custom -// SERVERKIT_DIR install jumps to the real tree. -const QUICK_ACCESS = [ - { labelKey: 'app.fileManager.sites', label: 'Sites', path: '/var/www', icon: Globe }, - { labelKey: 'app.fileManager.stack', label: 'Stack', path: '/opt/serverkit', icon: Boxes }, - { labelKey: 'app.fileManager.webConfig', label: 'Web config', path: '/etc/nginx', icon: SlidersHorizontal }, - { labelKey: 'common.labels.logs', label: 'Logs', path: '/var/log', icon: FileText }, -]; - -// Remote-agent rails: the panel stack doesn't exist on an agent box, so link -// the agent's own footprint instead. These paths are fixed by the agent -// installers the panel serves (scripts/install.sh: /etc/serverkit-agent; -// scripts/install.ps1: ProgramData\ServerKit\Agent) — agents run on the wire -// with forward-slash paths, Windows included. -const QUICK_ACCESS_AGENT = { - linux: [ - { labelKey: 'app.fileManager.sites', label: 'Sites', path: '/var/www', icon: Globe }, - { labelKey: 'app.fileManager.agent', label: 'Agent', path: '/etc/serverkit-agent', icon: Boxes }, - { labelKey: 'app.fileManager.webConfig', label: 'Web config', path: '/etc/nginx', icon: SlidersHorizontal }, - { labelKey: 'common.labels.logs', label: 'Logs', path: '/var/log', icon: FileText }, - ], - windows: [ - { labelKey: 'app.fileManager.agent', label: 'Agent', path: 'C:/ProgramData/ServerKit/Agent', icon: Boxes }, - { labelKey: 'app.fileManager.agentLogs', label: 'Agent logs', path: 'C:/ProgramData/ServerKit/Agent/logs', icon: FileText }, - { labelKey: 'app.fileManager.users', label: 'Users', path: 'C:/Users', icon: Home }, - ], - darwin: [ - { labelKey: 'app.fileManager.home', label: 'Home', path: '/Users', icon: Home }, - { labelKey: 'common.labels.logs', label: 'Logs', path: '/var/log', icon: FileText }, - ], -}; - -function deriveParent(path) { - if (!path || path === '/' || path === '') return null; - // A Windows drive root ("C:/" or "C:") sits directly under the agent's - // drive list, which the agent serves for the "/" path. Remote agents - // emit forward-slash paths on the wire, so we only ever see "/" here. - if (/^[A-Za-z]:\/?$/.test(path)) return '/'; - const trimmed = path.replace(/\/+$/, ''); - const idx = trimmed.lastIndexOf('/'); - if (idx <= 0) return '/'; - const parent = trimmed.slice(0, idx); - // Keep a bare drive letter as a drive root ("C:" -> "C:/") so navigating - // up doesn't hit Windows' "current directory on C:" semantics. - if (/^[A-Za-z]:$/.test(parent)) return parent + '/'; - return parent; -} - -function mountDisplayName(mount) { - if (!mount?.mountpoint || mount.mountpoint === '/') return null; - const parts = mount.mountpoint.split('/').filter(Boolean); - const leaf = parts[parts.length - 1] || mount.mountpoint; - return leaf === 'docker-desktop-user-distro' ? 'docker-desktop' : leaf; -} - -const STORAGE = { - sidebar: 'serverkit-fm-sidebar', - treeCollapsed: 'serverkit-fm-tree-collapsed', - expanded: 'serverkit-fm-tree-expanded', - viewMode: 'serverkit-fm-view-mode', - sortBy: 'serverkit-fm-sort-by', - sortDir: 'serverkit-fm-sort-dir', -}; - -const serializeExpanded = (set) => JSON.stringify([...set]); -const parseExpanded = (stored) => { - try { - return stored ? new Set(JSON.parse(stored)) : new Set(); - } catch { - return new Set(); - } -}; -const isNarrowScreen = () => typeof window !== 'undefined' - && window.matchMedia('(max-width: 1024px)').matches; - -const FILTER_OPTIONS = [ - { id: 'all', labelKey: 'common.labels.all', label: 'All' }, - { id: 'folder', labelKey: 'app.fileManager.folders', label: 'Folders' }, - { id: 'image', labelKey: 'app.fileManager.images', label: 'Images' }, - { id: 'code', labelKey: 'app.fileManager.code', label: 'Code' }, - { id: 'text', labelKey: 'app.fileManager.documents', label: 'Documents' }, - { id: 'data', labelKey: 'app.fileManager.data', label: 'Data' }, - { id: 'video', labelKey: 'app.fileManager.videos', label: 'Videos' }, - { id: 'audio', labelKey: 'app.fileManager.audio', label: 'Audio' }, - { id: 'archive', labelKey: 'app.fileManager.archives', label: 'Archives' }, -]; function FileManager() { const { t } = useTranslation(); const navigate = useNavigate(); - const [searchParams, setSearchParams] = useSearchParams(); // ─── target ────────────────────────────────────────── // Local panel host by default. Switching to an agent re-routes the @@ -136,641 +43,183 @@ function FileManager() { const [target, setTarget] = useState({ kind: 'local' }); const isRemote = target.kind === 'agent'; const isS3 = target.kind === 's3'; + const fileApi = useMemo(() => createFileAdapter(api, target), [target]); const { copy: copyText } = useClipboard({ successMessage: t('app.fileManager.pathCopied', 'Path copied'), errorMessage: t('app.fileManager.couldNotCopyPath', "Couldn't copy the path."), }); - const previousTargetRef = useRef({ kind: 'local', server_id: null }); - // The "S3 bucket" target is offered only when an S3-compatible backup - // destination is configured (Connections → Storage, or the Backups page). - const [s3Available, setS3Available] = useState(false); - const s3Options = useMemo( - () => (s3Available ? [{ value: 's3', label: t('app.fileManager.s3Bucket', 'S3 bucket') }] : []), - [s3Available, t], - ); - useEffect(() => { - let cancelled = false; - api.getStorageConfig() - .then((c) => { - if (cancelled) return; - const p = c?.provider; - setS3Available((p === 's3' || p === 'b2') && Boolean(c?.[p]?.bucket)); - }) - .catch(() => {}); - return () => { cancelled = true; }; - }, []); + const { s3Options, quickAccess } = useFileTargets({ target, isRemote, t }); - // The "Stack" quick link tracks the panel's real install dir (custom - // SERVERKIT_DIR installs aren't at /opt/serverkit). - const [panelInstallDir, setPanelInstallDir] = useState('/opt/serverkit'); - useEffect(() => { - let cancelled = false; - api.getVersion() - .then((v) => { - if (!cancelled && v?.install_dir) setPanelInstallDir(v.install_dir); - }) - .catch(() => {}); - return () => { cancelled = true; }; - }, []); + const { + selectedPaths, + setSelectedPaths, + selectMode, + setSelectMode, + setLastClickedPath, + toggleSelect, + clearSelection, + } = useFileSelection(); + const handleToggleSelect = (entry, event) => toggleSelect(entry, event, sortedFiltered); - // Per-target rail: agents get their OS's set (unknown os_type — an agent - // predating sysinfo reporting — is treated as linux, the historical - // behavior), with the agent's SELF-REPORTED config dir preferred over the - // installer convention when the agent sent one (system_info footprint); - // the local host gets the panel set with the resolved Stack dir. - const quickAccess = useMemo(() => { - if (isRemote) { - const os = (target.os_type || 'linux').toLowerCase(); - const rail = QUICK_ACCESS_AGENT[os] || QUICK_ACCESS_AGENT.linux; - // Windows agents report filepath-style backslashes; the file - // wire protocol speaks forward slashes. - const configDir = target.agentConfigDir - ? target.agentConfigDir.replace(/\\/g, '/').replace(/\/+$/, '') - : null; - if (!configDir) return rail; - return rail.map((q) => { - if (q.label === 'Agent') return { ...q, path: configDir }; - if (q.label === 'Agent logs') return { ...q, path: `${configDir}/logs` }; - return q; - }); - } - return QUICK_ACCESS.map((q) => - q.label === 'Stack' ? { ...q, path: panelInstallDir } : q - ); - }, [isRemote, target.os_type, target.agentConfigDir, panelInstallDir]); - - // ─── core ──────────────────────────────────────────── - const [currentPath, setCurrentPath] = useState(() => searchParams.get('path') || '/home'); - const [entries, setEntries] = useState([]); - const [parentPath, setParentPath] = useState(null); - const [loading, setLoading] = useState(true); - // The open folder's own load failure, shown in the listing in place of - // "This folder is empty". Navigation into a folder that fails still - // toasts and steps back, since the previous folder is what stays shown. - const [dirError, setDirError] = useState(null); - const [showHidden, setShowHidden] = useState(false); - - // ─── search ────────────────────────────────────────── - const [searchQuery, setSearchQuery] = useState(''); - const [searchResults, setSearchResults] = useState(null); - - // ─── selection ─────────────────────────────────────── - const [selectedPaths, setSelectedPaths] = useState(new Set()); - const [lastClickedPath, setLastClickedPath] = useState(null); - const [selectMode, setSelectMode] = useState(false); - - // ─── preview ───────────────────────────────────────── - const [previewFile, setPreviewFile] = useState(null); - const [fileContent, setFileContent] = useState(''); - const [editing, setEditing] = useState(false); - - // ─── modals ────────────────────────────────────────── - // { kind: 'newFolder' } | { kind: 'rename', entry } | { kind: 'permissions', entry } | null - const [dialog, setDialog] = useState(null); - const closeDialog = () => setDialog(null); - const [confirmDialog, setConfirmDialog] = useState(null); - - // ─── upload ────────────────────────────────────────── - const [uploads, setUploads] = useState([]); - const [dragActive, setDragActive] = useState(false); - const fileInputRef = useRef(null); - const dragCounter = useRef(0); - - // ─── view prefs ────────────────────────────────────── - const [viewMode, setViewMode] = usePersistentState(STORAGE.viewMode, (v) => v || 'list'); - const gridSize = 'md'; - const [sortBy, setSortBy] = usePersistentState(STORAGE.sortBy, (v) => v || 'name'); - const [sortDir, setSortDir] = usePersistentState(STORAGE.sortDir, (v) => v || 'asc'); - const [activeFilter, setActiveFilter] = useState('all'); - - // ─── left sidebar ──────────────────────────────────── - const [sidebarVisible, setSidebarVisible] = usePersistentState( - STORAGE.sidebar, (v) => (isNarrowScreen() ? false : v !== null ? v === 'true' : true)); - const [treeCollapsed, setTreeCollapsed] = usePersistentState(STORAGE.treeCollapsed, (v) => v === 'true'); - - // ─── folder tree state ─────────────────────────────── - const [treeExpanded, setTreeExpanded] = usePersistentState(STORAGE.expanded, parseExpanded, serializeExpanded); - const [treeCache, setTreeCache] = useState(new Map()); - const [treeLoading, setTreeLoading] = useState(new Set()); - - // ─── disk ──────────────────────────────────────────── - const [diskMounts, setDiskMounts] = useState([]); - const [diskLastUpdated, setDiskLastUpdated] = useState(null); - const [diskLoading, setDiskLoading] = useState(false); - - // ─── history ───────────────────────────────────────── - const [history, setHistory] = useState(['/home']); - const [historyIdx, setHistoryIdx] = useState(0); - const navByHistory = useRef(false); - const lastValidPathRef = useRef('/home'); - // Only the newest browse may write: a slow answer for the folder the - // user just left used to land last and navigate them back to it. - const loadSeqRef = useRef(0); + const { + viewMode, + setViewMode, + gridSize, + sortBy, + setSortBy, + sortDir, + setSortDir, + activeFilter, + setActiveFilter, + sidebarVisible, + setSidebarVisible, + treeCollapsed, + setTreeCollapsed, + } = useFilePreferences(); // ─── context menu ──────────────────────────────────── const [contextMenu, setContextMenu] = useState(null); const toast = useToast(); - useEffect(() => { - const pathFromUrl = searchParams.get('path') || '/home'; - if (pathFromUrl !== currentPath) { - setCurrentPath(pathFromUrl); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [searchParams]); - - useEffect(() => { - const pathFromUrl = searchParams.get('path') || '/home'; - if (pathFromUrl === currentPath) return; - - const nextParams = new URLSearchParams(searchParams); - nextParams.set('path', currentPath); - setSearchParams(nextParams, { replace: true }); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [currentPath]); - - const fileApi = useMemo(() => createFileAdapter(api, target), [target]); - - const remoteGuard = useCallback((op) => { - if (isRemote && !fileApi.supports(op)) { - toast.error(t('app.fileManager.isNotYetSupportedOnRemote', '{{op}} is not yet supported on remote agents', { op: op })); - return true; - } - if (isS3 && !fileApi.supports(op)) { - toast.error(t('app.fileManager.isnTAvailableOnS3Buckets', '{{op}} isn\'t available on S3 buckets', { op: op })); - return true; - } - return false; - }, [isRemote, isS3, fileApi, t, toast]); - - // When the user switches to a remote target, jump to its first - // advertised allowed_path so they don't see a "panel /home" view - // that doesn't exist on the remote host. - useEffect(() => { - const previousTarget = previousTargetRef.current; - const targetChanged = previousTarget.kind !== target.kind || previousTarget.server_id !== target.server_id; - previousTargetRef.current = { kind: target.kind, server_id: target.server_id }; - - if (!targetChanged) return; - - if (target.kind === 'agent' && Array.isArray(target.allowedPaths) && target.allowedPaths.length > 0) { - setCurrentPath(target.allowedPaths[0]); - } else if (target.kind === 's3') { - setCurrentPath('/'); - } else if (target.kind === 'local') { - setCurrentPath('/home'); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [target.kind, target.server_id]); - - // ─── load directory ────────────────────────────────── - const loadDirectory = useCallback(async (path) => { - const seq = ++loadSeqRef.current; - setLoading(true); - setSearchResults(null); - setSelectedPaths(new Set()); - setSelectMode(false); - try { - const data = await fileApi.browse(path, showHidden); - if (seq !== loadSeqRef.current) return; - // Agent file:list returns {path, files: [...]} with a flat - // entry shape; panel browseFiles returns {path, parent, - // entries: [...]}. Normalize so the UI can keep using - // entries/parent. - const entriesList = data.entries || data.files || []; - setEntries(entriesList); - setParentPath(data.parent ?? deriveParent(data.path || path)); - setCurrentPath(data.path || path); - lastValidPathRef.current = data.path || path; - setDirError(null); - } catch (error) { - if (seq !== loadSeqRef.current) return; - if (path !== lastValidPathRef.current) { - toast.error(t('app.fileManager.failedToLoadDirectory', "Couldn't load the folder. {{message}}", { message: errorReason(error) })); - setCurrentPath(lastValidPathRef.current); - } else { - setEntries([]); - setDirError(error); + const remoteGuard = useCallback( + (op) => { + if (isRemote && !fileApi.supports(op)) { + toast.error( + t( + 'app.fileManager.isNotYetSupportedOnRemote', + '{{op}} is not yet supported on remote agents', + { op: op }, + ), + ); + return true; } - } finally { - if (seq === loadSeqRef.current) setLoading(false); - } - }, [fileApi, showHidden, toast, t]); - - useEffect(() => { - loadDirectory(currentPath); - // fileApi, not loadDirectory: switching target must reload even when the - // path stays the same, but loadDirectory also changes with toast/t. - }, [currentPath, showHidden, fileApi]); // eslint-disable-line react-hooks/exhaustive-deps - - useEffect(() => { - loadDiskMounts(); - }, []); - - // history tracking - useEffect(() => { - if (navByHistory.current) { - navByHistory.current = false; - return; - } - setHistory((h) => { - const trimmed = h.slice(0, historyIdx + 1); - if (trimmed[trimmed.length - 1] === currentPath) return h; - return [...trimmed, currentPath]; - }); - setHistoryIdx((i) => (history[i] === currentPath ? i : i + 1)); - }, [currentPath]); // eslint-disable-line react-hooks/exhaustive-deps - - // ─── disk mounts ───────────────────────────────────── - const loadDiskMounts = async () => { - setDiskLoading(true); - try { - const data = await api.getAllDiskMounts(); - setDiskMounts(data.mounts || []); - setDiskLastUpdated(new Date()); - } catch (e) { - console.error('Failed to load disk mounts:', e); - } finally { - setDiskLoading(false); - } - }; - - // ─── tree expand/collapse ──────────────────────────── - const toggleTreeExpand = useCallback(async (path) => { - if (treeExpanded.has(path)) { - const next = new Set(treeExpanded); - next.delete(path); - setTreeExpanded(next); - return; - } - if (!treeCache.has(path)) { - setTreeLoading((s) => { const n = new Set(s); n.add(path); return n; }); - try { - const data = await fileApi.browse(path, false); - const entries = data.entries || data.files || []; - const folders = entries.filter((e) => e.is_dir).map((e) => ({ - path: e.path, - name: e.name, - })); - setTreeCache((c) => { const n = new Map(c); n.set(path, folders); return n; }); - } catch { - setTreeCache((c) => { const n = new Map(c); n.set(path, []); return n; }); - } finally { - setTreeLoading((s) => { const n = new Set(s); n.delete(path); return n; }); + if (isS3 && !fileApi.supports(op)) { + toast.error( + t('app.fileManager.isnTAvailableOnS3Buckets', "{{op}} isn't available on S3 buckets", { + op: op, + }), + ); + return true; } - } - setTreeExpanded((s) => { const n = new Set(s); n.add(path); return n; }); - }, [treeExpanded, treeCache, fileApi, setTreeExpanded]); - - // Auto-expand the tree along the current path so the active row is visible. - useEffect(() => { - const parts = currentPath.split('/').filter(Boolean); - const ancestors = []; - let acc = ''; - for (const p of parts) { - acc += '/' + p; - ancestors.push(acc); - } - ancestors.forEach((a) => { - const isUnderRoot = TREE_ROOTS.some((r) => a === r.path || a.startsWith(r.path + '/') || r.path.startsWith(a + '/')); - if (isUnderRoot && !treeExpanded.has(a) && a !== currentPath) { - toggleTreeExpand(a); - } - }); - }, [currentPath]); // eslint-disable-line react-hooks/exhaustive-deps - - // ─── search ────────────────────────────────────────── - const handleSearch = async () => { - if (remoteGuard('search')) { setSearchResults([]); return; } - if (!searchQuery.trim()) { setSearchResults(null); return; } - setLoading(true); - try { - const data = await fileApi.search(currentPath, searchQuery); - setSearchResults(data.results || []); - } catch (error) { - toast.error(t('app.fileManager.searchFailed', "Couldn't search. {{message}}", { message: errorReason(error) })); - } finally { - setLoading(false); - } - }; - - // ─── navigation ────────────────────────────────────── - const navigateTo = (path) => { - setPreviewFile(null); - setEditing(false); - setCurrentPath(path); - }; - - const goBack = () => { - if (historyIdx > 0) { - navByHistory.current = true; - setHistoryIdx(historyIdx - 1); - setCurrentPath(history[historyIdx - 1]); - } - }; - const goForward = () => { - if (historyIdx < history.length - 1) { - navByHistory.current = true; - setHistoryIdx(historyIdx + 1); - setCurrentPath(history[historyIdx + 1]); - } - }; - const goUp = () => parentPath && navigateTo(parentPath); - - const handleOpen = async (entry) => { - if (entry.is_dir) { - navigateTo(entry.path); - } else { - setPreviewFile(entry); - setEditing(false); - if (entry.is_editable) { - try { - const data = await fileApi.read(entry.path); - setFileContent(data.content); - } catch (error) { - toast.error(t('app.fileManager.failedToReadFile', "Couldn't read the file. {{message}}", { message: errorReason(error) })); - } - } - } - }; - - // ─── selection ─────────────────────────────────────── - const handleToggleSelect = (entry, e) => { - const path = entry.path; - if (e?.shiftKey && lastClickedPath) { - const list = sortedFiltered; - const a = list.findIndex((x) => x.path === lastClickedPath); - const b = list.findIndex((x) => x.path === path); - if (a >= 0 && b >= 0) { - const [from, to] = [Math.min(a, b), Math.max(a, b)]; - const rangePaths = list.slice(from, to + 1).map((x) => x.path); - const next = new Set([...selectedPaths, ...rangePaths]); - setSelectedPaths(next); - setSelectMode(next.size > 0); - } - } else { - const next = new Set(selectedPaths); - if (next.has(path)) next.delete(path); else next.add(path); - setSelectedPaths(next); - setSelectMode(next.size > 0); - setLastClickedPath(path); - } - }; - - const clearSelection = () => { - setSelectedPaths(new Set()); - setSelectMode(false); - }; - - // ─── ops ───────────────────────────────────────────── - const handleSaveFile = async () => { - if (!previewFile) return; - try { - await fileApi.write(previewFile.path, fileContent); - toast.success(t('app.fileManager.fileSaved', 'File saved')); - setEditing(false); - loadDirectory(currentPath); - } catch (error) { - toast.error(t('app.fileManager.failedToSave', "Couldn't save. {{message}}", { message: errorReason(error) })); - } - }; - - const handleCreateFolder = async (name) => { - if (remoteGuard('create folder')) return; - try { - await fileApi['create folder'](`${currentPath}/${name}`); - toast.success(t('app.fileManager.folderCreated', 'Folder created')); - closeDialog(); - loadDirectory(currentPath); - // Refresh tree cache for parent so the new folder appears in the tree - const parent = currentPath; - if (treeCache.has(parent)) { - try { - const data = await fileApi.browse(parent, false); - const folders = (data.entries || []).filter((e) => e.is_dir).map((e) => ({ path: e.path, name: e.name })); - setTreeCache((c) => { const n = new Map(c); n.set(parent, folders); return n; }); - } catch { /* ignore */ } - } - } catch (error) { - toast.error(t('app.fileManager.failedToCreateFolder', "Couldn't create the folder. {{message}}", { message: errorReason(error) })); - } - }; - - const handleDelete = (target) => { - const items = Array.isArray(target) ? target : [target]; - if (items.length === 0) return; - if (remoteGuard('delete')) return; - const message = items.length === 1 - ? `Delete "${items[0].name}"?${items[0].is_dir ? ' All contents inside will be removed.' : ''}` - : `Delete ${items.length} items? This cannot be undone.`; - setConfirmDialog({ - titleKey: 'app.fileManager.deleteConfirmation', title: 'Delete confirmation', - message, - confirmTextKey: 'common.actions.delete', confirmText: 'Delete', - variant: 'danger', - onConfirm: async () => { - const failures = []; - for (const it of items) { - try { - await fileApi.del(it.path); - } catch (error) { - failures.push(`${it.name}: ${error.message}`); - } - } - if (failures.length === 0) toast.success(t('app.fileManager.deletedItems', { count: items.length, defaultValue_one: 'Deleted 1 item', defaultValue_other: 'Deleted {{count}} items' })); - else toast.error(t('app.fileManager.failed', "Couldn't finish for: {{value}}", { value: failures.join(', ') })); - if (previewFile && items.some((i) => i.path === previewFile.path)) setPreviewFile(null); - clearSelection(); - loadDirectory(currentPath); - setConfirmDialog(null); - }, - onCancel: () => setConfirmDialog(null), - }); - }; - - const handleRename = async (entry, name) => { - if (remoteGuard('rename')) return; - try { - await fileApi.rename(entry.path, name); - toast.success(t('app.fileManager.renamed', 'Renamed')); - closeDialog(); - loadDirectory(currentPath); - } catch (error) { - toast.error(t('app.fileManager.failedToRename', "Couldn't rename it. {{message}}", { message: errorReason(error) })); - } - }; - - const handleChangePermissions = async (entry, mode) => { - if (remoteGuard('change permissions')) return; - try { - await fileApi['change permissions'](entry.path, mode); - toast.success(t('app.fileManager.permissionsUpdated', 'Permissions updated')); - closeDialog(); - loadDirectory(currentPath); - } catch (error) { - toast.error(t('app.fileManager.failed2', "Couldn't do that. {{message}}", { message: errorReason(error) })); - } - }; - - const openRenameModal = (entry) => setDialog({ kind: 'rename', entry }); - const openPermissionsModal = (entry) => setDialog({ kind: 'permissions', entry }); - - // ─── upload ────────────────────────────────────────── - const uploadFiles = async (files) => { - const fileList = Array.from(files); - if (fileList.length === 0) return; - if (remoteGuard('upload')) return; - const queue = fileList.map((f, i) => ({ - id: `${Date.now()}-${i}`, - name: f.name, - size: f.size, - progress: 0, - status: 'pending', - })); - setUploads((p) => [...p, ...queue]); - - let succeeded = 0; - for (let i = 0; i < fileList.length; i++) { - const file = fileList[i]; - const itemId = queue[i].id; - try { - setUploads((p) => p.map((u) => u.id === itemId ? { ...u, status: 'uploading' } : u)); - const doUpload = fileApi.upload; - await doUpload(currentPath, file, (progress) => { - setUploads((p) => p.map((u) => u.id === itemId ? { ...u, progress } : u)); - }); - setUploads((p) => p.map((u) => u.id === itemId ? { ...u, status: 'done', progress: 100 } : u)); - succeeded++; - } catch (error) { - setUploads((p) => p.map((u) => u.id === itemId ? { ...u, status: 'error', error: error.message } : u)); - } - } - if (succeeded > 0) toast.success(t('app.fileManager.uploadedFiles', { count: fileList.length, succeeded, defaultValue_one: 'Uploaded {{succeeded}} of 1 file', defaultValue_other: 'Uploaded {{succeeded}} of {{count}} files' })); - loadDirectory(currentPath); - setTimeout(() => { - setUploads((p) => p.filter((u) => u.status === 'uploading' || u.status === 'pending')); - }, 4000); - }; - - const handleUploadInput = (e) => { - if (e.target.files) uploadFiles(e.target.files); - if (fileInputRef.current) fileInputRef.current.value = ''; - }; - - const handleDragEnter = (e) => { - e.preventDefault(); e.stopPropagation(); - dragCounter.current += 1; - if (e.dataTransfer.items?.length > 0) setDragActive(true); - }; - const handleDragLeave = (e) => { - e.preventDefault(); e.stopPropagation(); - dragCounter.current -= 1; - if (dragCounter.current === 0) setDragActive(false); - }; - const handleDragOver = (e) => { e.preventDefault(); e.stopPropagation(); }; - const handleDrop = (e) => { - e.preventDefault(); e.stopPropagation(); - dragCounter.current = 0; - setDragActive(false); - if (e.dataTransfer.files?.length > 0) uploadFiles(e.dataTransfer.files); - }; - - // ─── derived ───────────────────────────────────────── - const breadcrumbs = useMemo(() => { - const parts = currentPath.split('/').filter(Boolean); - // Windows drive-rooted path ("C:/Users/Juan"): the first segment is - // the drive and the root crumb is the agent's drive list. Building - // crumbs with a leading "/" (the POSIX branch below) would produce - // bogus "/C:" paths that the agent can't resolve. - if (/^[A-Za-z]:$/.test(parts[0] || '')) { - const crumbs = [{ name: 'Drives', path: '/' }]; - let acc = parts[0]; - crumbs.push({ name: parts[0], path: acc + '/' }); - for (let i = 1; i < parts.length; i++) { - acc += '/' + parts[i]; - crumbs.push({ name: parts[i], path: acc }); - } - return crumbs; - } - const crumbs = [{ name: '/', path: '/' }]; - let acc = ''; - parts.forEach((p) => { acc += '/' + p; crumbs.push({ name: p, path: acc }); }); - return crumbs; - }, [currentPath]); - - const sortedFiltered = useMemo(() => { - let list = [...(searchResults || entries)]; - if (activeFilter !== 'all') list = list.filter((e) => getFileType(e) === activeFilter); - const dir = sortDir === 'asc' ? 1 : -1; - list.sort((a, b) => { - if (a.is_dir !== b.is_dir) return a.is_dir ? -1 : 1; - switch (sortBy) { - case 'size': return ((a.size || 0) - (b.size || 0)) * dir; - case 'modified': return (new Date(a.modified) - new Date(b.modified)) * dir; - case 'type': return getFileType(a).localeCompare(getFileType(b)) * dir; - case 'name': - default: return a.name.localeCompare(b.name) * dir; - } - }); - return list; - }, [entries, searchResults, sortBy, sortDir, activeFilter]); - - const filterCounts = useMemo(() => { - const counts = { all: entries.length }; - FILTER_OPTIONS.forEach((c) => { if (c.id !== 'all') counts[c.id] = 0; }); - entries.forEach((e) => { const t = getFileType(e); if (counts[t] !== undefined) counts[t]++; }); - return counts; - }, [entries]); - - const stats = useMemo(() => { - const list = sortedFiltered; - const folders = list.filter((e) => e.is_dir).length; - const files = list.length - folders; - const totalBytes = list.reduce((s, e) => s + (e.size || 0), 0); - const selectedList = list.filter((e) => selectedPaths.has(e.path)); - const selectedBytes = selectedList.reduce((s, e) => s + (e.size || 0), 0); - return { folders, files, totalBytes, total: list.length, selectedCount: selectedList.length, selectedBytes }; - }, [sortedFiltered, selectedPaths]); - - const activeMount = useMemo(() => diskMounts - .filter((mount) => { - const mountPath = mount.mountpoint || '/'; - if (mountPath === '/') return currentPath.startsWith('/'); - return currentPath === mountPath || currentPath.startsWith(`${mountPath.replace(/\/$/, '')}/`); - }) - .sort((a, b) => (b.mountpoint || '/').length - (a.mountpoint || '/').length)[0] || null, - [currentPath, diskMounts]); - - const activeUploads = uploads.filter((u) => u.status === 'uploading' || u.status === 'pending'); - const totalUploadProgress = activeUploads.length > 0 - ? activeUploads.reduce((s, u) => s + u.progress, 0) / activeUploads.length - : 0; - - const sortValue = `${sortBy}-${sortDir}`; - const filterLabels = { - all: t('common.labels.all', 'All'), - folder: t('app.fileManager.folders', 'Folders'), - image: t('app.fileManager.images', 'Images'), - code: t('app.fileManager.code', 'Code'), - text: t('app.fileManager.documents', 'Documents'), - data: t('app.fileManager.data', 'Data'), - video: t('app.fileManager.videos', 'Videos'), - audio: t('app.fileManager.audio', 'Audio'), - archive: t('app.fileManager.archives', 'Archives'), - }; - const handleSortChange = (value) => { - const [nextSortBy, nextSortDir] = value.split('-'); - setSortBy(nextSortBy); - setSortDir(nextSortDir); - }; - - const selectedEntries = useMemo( - () => sortedFiltered.filter((e) => selectedPaths.has(e.path)), - [sortedFiltered, selectedPaths], + return false; + }, + [isRemote, isS3, fileApi, t, toast], ); + const { + previewFile, + setPreviewFile, + fileContent, + setFileContent, + editing, + setEditing, + openFile, + handleSaveFile, + } = useFileEditor({ fileApi, toast, t, onSaved: () => loadDirectory(currentPath) }); + + const { + currentPath, + entries, + parentPath, + loading, + dirError, + showHidden, + setShowHidden, + searchQuery, + setSearchQuery, + searchResults, + clearSearch, + history, + historyIdx, + loadDirectory, + handleSearch, + navigateTo, + goBack, + goForward, + goUp, + } = useDirectoryBrowser({ + fileApi, + target, + resetSelection: clearSelection, + onNavigate: () => { + setPreviewFile(null); + setEditing(false); + }, + remoteGuard, + toast, + t, + }); + + const { treeExpanded, treeCache, refreshTree, treeLoading, toggleTreeExpand } = useFileTree({ + fileApi, + currentPath, + }); + + const { diskMounts, diskLastUpdated, diskLoading, loadDiskMounts, activeMount } = + useFileVolumes(currentPath); + + const { + dialog, + setDialog, + closeDialog, + handleCreateFolder, + handleDelete, + handleRename, + handleChangePermissions, + openRenameModal, + openPermissionsModal, + } = useFileActions({ + fileApi, + currentPath, + remoteGuard, + loadDirectory, + refreshTree, + previewFile, + setPreviewFile, + clearSelection, + toast, + t, + }); + const handleOpen = (entry) => (entry.is_dir ? navigateTo(entry.path) : openFile(entry)); + + const { + uploads, + setUploads, + dragActive, + fileInputRef, + handleUploadInput, + handleDragEnter, + handleDragLeave, + handleDragOver, + handleDrop, + activeUploads, + totalUploadProgress, + } = useFileTransfers({ fileApi, currentPath, remoteGuard, loadDirectory, toast, t }); + + const { + breadcrumbs, + sortedFiltered, + filterCounts, + stats, + sortValue, + filterLabels, + handleSortChange, + selectedEntries, + } = useFileListingModel({ + currentPath, + entries, + searchResults, + activeFilter, + sortBy, + sortDir, + selectedPaths, + setSortBy, + setSortDir, + t, + }); + // ─── shortcuts ─────────────────────────────────────── useEffect(() => { const handler = (e) => { @@ -791,7 +240,10 @@ function FileManager() { setSelectedPaths(new Set(sortedFiltered.map((x) => x.path))); setSelectMode(sortedFiltered.length > 0); } - if (e.key === 'Backspace' && !e.metaKey && parentPath) { e.preventDefault(); goUp(); } + if (e.key === 'Backspace' && !e.metaKey && parentPath) { + e.preventDefault(); + goUp(); + } }; window.addEventListener('keydown', handler); return () => window.removeEventListener('keydown', handler); @@ -800,7 +252,9 @@ function FileManager() { // ─── close popovers ────────────────────────────────── useEffect(() => { if (!contextMenu) return; - const close = () => { setContextMenu(null); }; + const close = () => { + setContextMenu(null); + }; document.addEventListener('click', close); return () => document.removeEventListener('click', close); }, [contextMenu]); @@ -821,7 +275,9 @@ function FileManager() { const rowOpen = useStableHandler(handleOpen); const rowToggleSelect = useStableHandler(handleToggleSelect); const rowContext = useStableHandler(openContextMenu); - const handleDownload = (entry) => { if (!remoteGuard('download')) fileApi.download(entry); }; + const handleDownload = (entry) => { + if (!remoteGuard('download')) fileApi.download(entry); + }; const rowDownload = useStableHandler(handleDownload); const rowRename = useStableHandler(openRenameModal); const rowPermissions = useStableHandler(openPermissionsModal); @@ -830,42 +286,40 @@ function FileManager() { const copyPathToClipboard = (path) => copyText(path); const downloadSelected = () => { - if (!remoteGuard('download')) selectedEntries.filter((e) => !e.is_dir).forEach((e) => fileApi.download(e)); + if (!remoteGuard('download')) + selectedEntries.filter((e) => !e.is_dir).forEach((e) => fileApi.download(e)); }; - const getDiskColor = (percent) => { - if (percent >= 90) return 'critical'; - if (percent >= 70) return 'warning'; - return 'healthy'; - }; - - useTopbarActions(() => ( - <> - - - {!isS3 && ( - - )} - - ), [isRemote, isS3, currentPath]); + + {!isS3 && ( + + )} + + ), + [isRemote, isS3, currentPath], + ); // ─── render ────────────────────────────────────────── return ( @@ -876,216 +330,123 @@ function FileManager() { onDragLeave={handleDragLeave} onDrop={handleDrop} > - + {isRemote && (
- {t('app.fileManager.browsingOn', 'Browsing on')} {target.name} {t('app.fileManager.readWriteOnlyMkdirDeleteRename', "(read/write only). Mkdir/delete/rename/upload aren't yet supported on remote agents.")} + {t('app.fileManager.browsingOn', 'Browsing on')} {target.name}{' '} + {t( + 'app.fileManager.readWriteOnlyMkdirDeleteRename', + "(read/write only). Mkdir/delete/rename/upload aren't yet supported on remote agents.", + )}
)} {isS3 && (
- {t('app.fileManager.browsingYour', 'Browsing your')} {t('app.fileManager.s3Bucket', 'S3 bucket')}.{' '} - {t('app.fileManager.s3SupportedOperations', "Upload, download, edit and delete work; folders, rename and permissions don't apply to object storage.")} -
- )} - - {uploads.length > 0 && ( -
-
- - - {activeUploads.length > 0 - ? t('app.fileManager.uploadingFiles', { count: activeUploads.length, defaultValue_one: 'Uploading 1 file…', defaultValue_other: 'Uploading {{count}} files…' }) - : t('app.fileManager.uploadsComplete', 'Uploads complete')} - - {activeUploads.length > 0 && ( - {Math.round(totalUploadProgress)}% - )} - -
-
- {uploads.map((u) => ( -
- {u.name} -
-
-
- - {u.status === 'done' ? t('common.actions.done', 'Done') : u.status === 'error' ? t('app.fileManager.uploadFailed', 'Failed') : `${Math.round(u.progress)}%`} - -
- ))} -
-
- )} - -
-
- -
- - - - -
-
- {breadcrumbs.map((crumb, idx) => ( - - {idx > 0 && /} - - - ))} -
- {activeMount && !isRemote && !isS3 && ( - - - {activeMount.mountpoint === '/' ? t('app.fileManager.rootDisk', 'Root disk') : activeMount.mountpoint} - + {t('app.fileManager.browsingYour', 'Browsing your')}{' '} + {t('app.fileManager.s3Bucket', 'S3 bucket')}.{' '} + {t( + 'app.fileManager.s3SupportedOperations', + "Upload, download, edit and delete work; folders, rename and permissions don't apply to object storage.", )}
-
- - -
- - setSearchQuery(e.target.value)} - onKeyDown={(e) => e.key === 'Enter' && handleSearch()} - /> - {(searchResults || searchQuery) && ( - - )} -
-
- - -
- - -
-
+ )} + + + + {selectedPaths.size > 0 && (
- {selectedPaths.size} {t('app.fileManager.selected', 'selected ·')} {formatBytes(stats.selectedBytes)} + + {selectedPaths.size} {t('app.fileManager.selected', 'selected ·')}{' '} + {formatBytes(stats.selectedBytes)} +
- {selectedEntries.length === 1 && ( <> - - )} - -
@@ -1093,238 +454,59 @@ function FileManager() { )}
- {sidebarVisible && ( - - )} - -
-
{ - if (e.target === e.currentTarget) clearSelection(); - }} - > - {dragActive && ( -
-
- -

{t('app.fileManager.dropToUpload', 'Drop to upload')}

-

{t('app.fileManager.filesWillBeUploadedTo', 'Files will be uploaded to')} {currentPath}

-
-
- )} - - {loading ? ( - - ) : dirError && !searchResults ? ( - loadDirectory(currentPath)} - /> - ) : sortedFiltered.length === 0 ? ( - - ) : viewMode === 'grid' ? ( -
- {sortedFiltered.map((entry) => ( - - ))} -
- ) : ( -
-
- - - - {t('common.labels.name', 'Name')} - {t('common.labels.size', 'Size')} - {t('app.fileManager.modified', 'Modified')} - {t('common.labels.permissions', 'Permissions')} - {t('app.fileManager.owner', 'Owner')} - {t('common.labels.actions', 'Actions')} -
- {sortedFiltered.map((entry) => ( - - ))} -
- )} -
-
+ setEditing(true)} onCancelEdit={() => setEditing(false)} onSave={handleSaveFile} - onClose={() => { setPreviewFile(null); setEditing(false); }} + onClose={() => { + setPreviewFile(null); + setEditing(false); + }} onDownload={handleDownload} onRename={openRenameModal} onPermissions={openPermissionsModal} @@ -1343,42 +528,7 @@ function FileManager() { />
-
-
- - {t('app.fileManager.total', 'Total')} - {stats.total} item{stats.total !== 1 ? 's' : ''} - - - - - {stats.folders} folder{stats.folders !== 1 ? 's' : ''} - - - - {stats.files} file{stats.files !== 1 ? 's' : ''} - - {stats.totalBytes > 0 && ( - <> - - - {t('common.labels.size', 'Size')} - {formatBytes(stats.totalBytes)} - - - )} -
-
- {stats.selectedCount > 0 && ( - - {stats.selectedCount} {t('app.fileManager.selected', 'selected ·')} {formatBytes(stats.selectedBytes)} - - )} - - {t('app.fileManager.upDelDeleteF2RenameA', '⌫ Up · Del Delete · F2 Rename · ⌘A All')} - -
-
+ handleDelete(selectedEntries.length > 1 ? selectedEntries : e)} /> - {dialog?.kind === 'newFolder' && ( - {t('app.fileManager.willBeCreatedIn', 'Will be created in:')} {currentPath}

} - submitLabel={t('app.fileManager.createFolder', 'Create folder')} - onSubmit={handleCreateFolder} - onClose={closeDialog} - /> - )} - {dialog?.kind === 'rename' && ( - handleRename(dialog.entry, name)} - onClose={closeDialog} - /> - )} - {dialog?.kind === 'permissions' && ( - handleChangePermissions(dialog.entry, mode)} - onClose={closeDialog} - /> - )} - - {confirmDialog && ( - - )} +
); } From 3c5b948f2ea4cf56f920d342888a615b4ef23ba2 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 04:48:54 -0400 Subject: [PATCH 06/34] test: enforce core boundaries and document extension rules --- AGENTS.md | 5 ++ backend/app/bootstrap/configuration.py | 1 - backend/app/bootstrap/http.py | 1 - backend/app/bootstrap/logging.py | 2 - backend/app/bootstrap/persistence.py | 1 - backend/app/bootstrap/plugins.py | 1 - backend/app/bootstrap/runtime.py | 1 - backend/tests/test_bootstrap_boundaries.py | 27 +++++- docs/CORE_BOUNDARIES.md | 86 +++++++++++++++++++ .../scripts/check-file-manager-boundaries.mjs | 2 +- .../file-manager/__tests__/boundaries.test.js | 1 + 11 files changed, 116 insertions(+), 12 deletions(-) create mode 100644 docs/CORE_BOUNDARIES.md diff --git a/AGENTS.md b/AGENTS.md index 6bc19648..9106c763 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,6 +38,11 @@ Default dev credentials: `admin` / `admin` ## Architecture +For application startup and File Manager ownership rules, see +[`docs/CORE_BOUNDARIES.md`](docs/CORE_BOUNDARIES.md). Keep startup as ordered +bootstrap phases, file transport in the capability-checked adapter, and async +File Manager state in its feature hooks. CI enforces these boundaries. + ### Backend (`backend/`) Flask app factory in `app/__init__.py` using `create_app()`. Three-layer architecture: diff --git a/backend/app/bootstrap/configuration.py b/backend/app/bootstrap/configuration.py index 2845c5ef..3baf33ba 100644 --- a/backend/app/bootstrap/configuration.py +++ b/backend/app/bootstrap/configuration.py @@ -112,4 +112,3 @@ def configure_application(app, db, migrate, jwt, limiter): from app.middleware.rate_limit import get_rate_limit_key, register_rate_limit_headers limiter._key_func = get_rate_limit_key register_rate_limit_headers(app) - diff --git a/backend/app/bootstrap/http.py b/backend/app/bootstrap/http.py index 70551a19..855ab2a9 100644 --- a/backend/app/bootstrap/http.py +++ b/backend/app/bootstrap/http.py @@ -98,4 +98,3 @@ def register_http_handlers(app): if index and os.path.isfile(index): return _spa_page() return {'error': 'Not found'}, 404 - diff --git a/backend/app/bootstrap/logging.py b/backend/app/bootstrap/logging.py index 18d099b6..09bbac55 100644 --- a/backend/app/bootstrap/logging.py +++ b/backend/app/bootstrap/logging.py @@ -51,5 +51,3 @@ def configure_logging(app): )) root.addHandler(handler) _logging_configured = True - - diff --git a/backend/app/bootstrap/persistence.py b/backend/app/bootstrap/persistence.py index c5382119..3da1a06e 100644 --- a/backend/app/bootstrap/persistence.py +++ b/backend/app/bootstrap/persistence.py @@ -72,4 +72,3 @@ def prepare_persistence(app): except Exception as e: import logging logging.getLogger(__name__).warning(f'Setup code unavailable: {e}') - diff --git a/backend/app/bootstrap/plugins.py b/backend/app/bootstrap/plugins.py index d5d4677f..fac42346 100644 --- a/backend/app/bootstrap/plugins.py +++ b/backend/app/bootstrap/plugins.py @@ -61,4 +61,3 @@ def load_extensions(app): except Exception as e: import logging logging.getLogger(__name__).warning(f'Extension backend acquisition: {e}') - diff --git a/backend/app/bootstrap/runtime.py b/backend/app/bootstrap/runtime.py index be0c4dd1..915bc6da 100644 --- a/backend/app/bootstrap/runtime.py +++ b/backend/app/bootstrap/runtime.py @@ -81,4 +81,3 @@ def start_runtime(app): # panel is paired. from app.services import connect_client connect_client.start_client_if_paired(app) - diff --git a/backend/tests/test_bootstrap_boundaries.py b/backend/tests/test_bootstrap_boundaries.py index e9bf9af8..2aeb5512 100644 --- a/backend/tests/test_bootstrap_boundaries.py +++ b/backend/tests/test_bootstrap_boundaries.py @@ -62,7 +62,8 @@ def test_recovery_precedes_consumers_and_handlers_precede_jobs(monkeypatch, runt 'uptime', 'linked', 'relay'] -def test_factory_phase_order_and_context(monkeypatch): +@pytest.mark.parametrize('failed_phase', [None, 'persistence', 'plugins']) +def test_factory_phase_order_and_context(monkeypatch, failed_phase): import app as application from flask import has_app_context from app.bootstrap import configuration, persistence, plugins, http @@ -76,6 +77,8 @@ def test_factory_phase_order_and_context(monkeypatch): def run(*args): assert has_app_context() is context calls.append(name) + if name == failed_phase: + raise RuntimeError('startup failed') return run monkeypatch.setattr(configuration, 'configure_application', phase('configuration')) @@ -89,9 +92,25 @@ def test_factory_phase_order_and_context(monkeypatch): monkeypatch.setattr(runtime, 'start_runtime', phase('runtime', True)) monkeypatch.setattr(http, 'register_http_handlers', phase('http')) monkeypatch.setattr(application, 'socketio', application.socketio) - application.create_app('testing') - assert calls == ['configuration', 'socket', 'gateway', 'routes', 'recycle', - 'restore', 'persistence', 'plugins', 'runtime', 'http'] + expected = ['configuration', 'socket', 'gateway', 'routes', 'recycle', + 'restore', 'persistence', 'plugins', 'runtime', 'http'] + if failed_phase: + with pytest.raises(RuntimeError, match='startup failed'): + application.create_app('testing') + assert calls == expected[:expected.index(failed_phase) + 1] + else: + application.create_app('testing') + assert calls == expected + + +def test_monitor_failure_does_not_prevent_other_runtime_services(runtime_calls): + def fail(_app): + raise RuntimeError('monitor unavailable') + sys.modules['app.services.monitoring_service'].MonitoringService.resume_if_enabled = fail + logger = Mock() + runtime.start_runtime(SimpleNamespace(config={}, logger=logger)) + logger.exception.assert_called_once() + assert runtime_calls[-3:] == ['uptime', 'linked', 'relay'] def test_bootstrap_is_an_assembly_layer_not_a_service_dependency(): diff --git a/docs/CORE_BOUNDARIES.md b/docs/CORE_BOUNDARIES.md new file mode 100644 index 00000000..080a22d0 --- /dev/null +++ b/docs/CORE_BOUNDARIES.md @@ -0,0 +1,86 @@ +# Core boundaries + +## Backend application startup + +`backend/app/__init__.py` owns the public `create_app`, `db`, `jwt`, `migrate`, +`limiter`, and `get_socketio` interfaces. Keep it as ordered composition. +Do not put feature initialization or worker loops back into the factory. + +The assembly sequence is: + +1. Configure logging and Flask extensions/request middleware + (`bootstrap/logging.py`, `bootstrap/configuration.py`). +2. Initialize Socket.IO and the agent gateway; register core blueprints and + restore adapters. +3. Prepare the database and installation data (`bootstrap/persistence.py`). +4. Load extensions and their compatibility upgrades (`bootstrap/plugins.py`). +5. Recover interrupted jobs, register handlers and start the runtime + (`bootstrap/runtime.py`, `bootstrap/jobs.py`). +6. Register SPA delivery and HTTP error handlers (`bootstrap/http.py`). + +Persistence, extension loading, and runtime startup execute inside the app +context. Database preparation precedes extension queries; interrupted-job +recovery precedes consumers; job handlers precede the job consumer. One-shot +Flask commands and `SERVERKIT_SKIP_BACKGROUND` suppress runtime startup. +The existing individual services retain their testing and singleton guards. + +Bootstrap may depend on services, models, middleware and jobs. Those layers +must not import bootstrap. A feature exposes a registration/initialization +function; its appropriate bootstrap phase invokes it. Existing migration +policy and fail-soft extension behavior are preserved by this split. + +`backend/tests/test_bootstrap_boundaries.py` enforces dependency direction, +factory composition, startup order, context, and CLI suppression. The core +blueprint registry and API-error tests verify the assembled application. + +## File Manager + +The route in `frontend/src/pages/FileManager.jsx` composes the feature under +`components/file-manager/`. Keep the existing shared components and SCSS. + +| Owner | Responsibility | +| --- | --- | +| `fileAdapter.js` | Select local/agent/S3 transport; reject unsupported operations without falling back to the local host | +| `hooks/useDirectoryBrowser.js` | URL/path navigation, history, directory loading, search and request invalidation | +| `hooks/useFileTree.js` | Tree expansion, cached child folders and target-aware refresh | +| `hooks/useFileEditor.js` | Preview reads, editable contents and save lifecycle | +| `hooks/useFileActions.js` | Folder/rename/permissions/delete actions and shared confirmation | +| `hooks/useFileTransfers.js` | Upload batches, drag/drop, progress and timer cleanup | +| `hooks/useFileSelection.js` | Selection and range-selection anchor | +| `hooks/useFileListingModel.js` | Sorting, filtering, breadcrumbs and derived counts | +| `hooks/useFilePreferences.js` | Persisted view/sidebar preferences | +| `hooks/useFileTargets.js`, `useFileVolumes.js` | Target metadata and panel volume metadata | +| `hooks/useImagePreview.js` | Thumbnail request and object-URL lifetime through the adapter | +| `FileManager*.jsx`, `FileUploadTray.jsx` | Render sections and forward user actions through props | + +Add storage operations to the adapter and its explicit capability map. A +disabled button is not sufficient protection: the adapter must reject an +unsupported call. Authorization remains enforced by the backend. + +Async work stays in the owning hook. Before applying a result, validate that +its request, path and target still match the current view. Keep an upload's +original destination throughout its batch. Completion must not navigate the +user back to the directory where the operation began. Failed saves retain the +draft. Thumbnails must never use the panel's local-file endpoint for an agent. + +Views do not import the API service or route pages. Metadata hooks are the +documented exception to adapter-only transport: they read storage configuration, +panel version and panel volumes, not file contents. The route constructs the +adapter but does not issue API calls or await requests. + +## Checks when extending these areas + +- `npm run lint` in `frontend`: includes File Manager dependency/composition + checks through `scripts/check-frontend-boundaries.mjs`. +- `npm test`: adapter contracts and positive/negative boundary-check fixtures. +- `npm run test:file-manager`: actual page in Chromium, covering navigation, + target switching, late results, editing, confirmations and uploads. +- `npm run build`: verify the complete production import graph. +- `python -m pytest tests/test_bootstrap_boundaries.py + tests/test_core_blueprint_registry.py tests/test_cli_skips_background.py + tests/test_api_error_shape.py` in `backend`: focused startup coverage. +- Run the full backend suite for application assembly changes. + +These checks already run through the existing frontend/backend CI workflows. +Do not raise a size ceiling or allow a new dependency just to make a check pass; +first decide which existing owner should contain the behavior. diff --git a/frontend/scripts/check-file-manager-boundaries.mjs b/frontend/scripts/check-file-manager-boundaries.mjs index 14d69393..6baa16bb 100644 --- a/frontend/scripts/check-file-manager-boundaries.mjs +++ b/frontend/scripts/check-file-manager-boundaries.mjs @@ -33,7 +33,7 @@ export function inspectFileManagerSource(path, source) { if ((page || view) && node.type === 'CallExpression' && node.callee?.object?.name === 'api') { errors.push(`${path}: views must not call API methods`); } - if (view && node.type === 'CallExpression' && node.callee?.name === 'fetch') { + if ((page || view) && node.type === 'CallExpression' && node.callee?.name === 'fetch') { errors.push(`${path}: views must not fetch`); } for (const value of Object.values(node)) { diff --git a/frontend/src/components/file-manager/__tests__/boundaries.test.js b/frontend/src/components/file-manager/__tests__/boundaries.test.js index 43bc2d59..94950f06 100644 --- a/frontend/src/components/file-manager/__tests__/boundaries.test.js +++ b/frontend/src/components/file-manager/__tests__/boundaries.test.js @@ -12,6 +12,7 @@ test('File Manager keeps transport, orchestration and views separate', () => { test('boundary guard rejects dependencies that would recombine the feature', () => { for (const [path, source] of [ ['pages/FileManager.jsx', 'async function load() { await api.browseFiles(); }'], + ['pages/FileManager.jsx', "fetch('/api/v1/files').then(render);"], ['components/file-manager/FileManagerListing.jsx', "import { api } from '@/services/api';"], ['components/file-manager/hooks/useFileEditor.js', "import Page from '@/pages/FileManager';"], ['components/file-manager/FileManagerSidebar.jsx', "import useFileTree from './hooks/useFileTree';"], From 8bf9f4681ce942c218c0a1c844aac13a5b5fc9f3 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 04:51:50 -0400 Subject: [PATCH 07/34] test: cover File Manager tree races and listing failures --- frontend/scripts/file-manager-browser.mjs | 31 ++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/frontend/scripts/file-manager-browser.mjs b/frontend/scripts/file-manager-browser.mjs index 330de817..88fea9db 100644 --- a/frontend/scripts/file-manager-browser.mjs +++ b/frontend/scripts/file-manager-browser.mjs @@ -228,7 +228,7 @@ try { assert.deepEqual(editorErrors, []); console.log('PASS preview read races, failed-save draft retention and target reset'); - // Shared confirmation must preserve cancel semantics and partial failures. + // Shared confirmation must preserve cancel/confirm semantics. const deletion = await browser.newPage(); await deletion.goto(`http://127.0.0.1:${server.httpServer.address().port}/fm-check`); await deletion.getByText('projects', { exact: true }).first().waitFor(); @@ -300,6 +300,35 @@ try { await images.getByText('Image preview unavailable', { exact: true }).waitFor(); assert.deepEqual(await images.evaluate(() => window.blobCalls), []); console.log('PASS agent image previews never fetch files from the panel host'); + + const tree = await browser.newPage(); + await tree.goto(`http://127.0.0.1:${server.httpServer.address().port}/fm-check`); + await tree.getByText('projects', { exact: true }).first().waitFor(); + await tree.evaluate(() => { + const browse = window.testApi.browseFiles; + window.testApi.browseFiles = p => p === '/srv' + ? new Promise(resolve => { window.finishTree = resolve; }) : browse(p); + }); + const treeRow = tree.locator('.tree-row').filter({ has: tree.locator('.tree-name[title="/srv"]') }); + await treeRow.getByRole('button', { name: 'Expand', exact: true }).click(); + await tree.waitForFunction(() => Boolean(window.finishTree)); + await tree.getByRole('button', { name: 'pick-agent' }).click(); + await tree.getByText('on-agent.txt').first().waitFor(); + await tree.evaluate(() => window.finishTree({ entries: [{ name: 'local-tree-child', path: '/srv/local-tree-child', is_dir: true }] })); + await tree.waitForTimeout(100); + assert.equal(await tree.getByText('local-tree-child', { exact: true }).count(), 0); + console.log('PASS late tree responses cannot populate another target cache'); + + const failed = await browser.newPage(); + await failed.goto(`http://127.0.0.1:${server.httpServer.address().port}/fm-check`); + await failed.getByText('projects', { exact: true }).first().waitFor(); + await failed.evaluate(() => { + window.testApi.browseFiles = () => Promise.reject(new Error('permission denied')); + }); + await failed.locator('.file-manager-toolbar').getByTitle('Refresh', { exact: true }).click(); + await failed.getByText("Couldn't open this folder.", { exact: true }).waitFor(); + assert.equal(await failed.getByText('This folder is empty', { exact: true }).count(), 0); + console.log('PASS listing failures remain errors rather than empty folders'); } finally { await browser?.close(); await server.close(); From a853c91d61230bf258fc47778d4dbf204833de22 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 04:54:38 -0400 Subject: [PATCH 08/34] fix: preserve File Manager deep links on initial mount --- frontend/scripts/file-manager-browser.mjs | 12 +++++++++++- .../file-manager/hooks/useDirectoryBrowser.js | 2 +- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/frontend/scripts/file-manager-browser.mjs b/frontend/scripts/file-manager-browser.mjs index 88fea9db..f46c1800 100644 --- a/frontend/scripts/file-manager-browser.mjs +++ b/frontend/scripts/file-manager-browser.mjs @@ -27,7 +27,7 @@ window.testApi={ renameFile:(p,n)=>{(window.ops=window.ops||[]).push(['rename',p,n]);return Promise.resolve({});}, changeFilePermissions:(p,m)=>{(window.ops=window.ops||[]).push(['chmod',p,m]);return Promise.resolve({});}, }; -createRoot(document.getElementById('root')).render(); +createRoot(document.getElementById('root')).render(); `; const server = await createServer({ root, configFile: false, logLevel: 'error', resolve: { alias: { '@': path.join(root, 'src') } }, @@ -329,6 +329,16 @@ try { await failed.getByText("Couldn't open this folder.", { exact: true }).waitFor(); assert.equal(await failed.getByText('This folder is empty', { exact: true }).count(), 0); console.log('PASS listing failures remain errors rather than empty folders'); + + const deepLink = await browser.newPage(); + await deepLink.addInitScript(() => { window.initialPath = '/files?path=/var/www'; }); + await deepLink.goto(`http://127.0.0.1:${server.httpServer.address().port}/fm-check`); + await deepLink.waitForFunction(() => window.pending.some(x => x.path === '/var/www')); + await deepLink.evaluate(() => window.release('/var/www')); + await deepLink.getByText('inside-www.txt', { exact: true }).waitFor(); + assert.equal(await deepLink.getByText('projects', { exact: true }).count(), 0); + assert.equal(await deepLink.getByTitle('Back', { exact: true }).isDisabled(), true); + console.log('PASS initial deep links retain their directory and history'); } finally { await browser?.close(); await server.close(); diff --git a/frontend/src/components/file-manager/hooks/useDirectoryBrowser.js b/frontend/src/components/file-manager/hooks/useDirectoryBrowser.js index 6c52aba4..755d2995 100644 --- a/frontend/src/components/file-manager/hooks/useDirectoryBrowser.js +++ b/frontend/src/components/file-manager/hooks/useDirectoryBrowser.js @@ -29,7 +29,7 @@ export default function useDirectoryBrowser({ t, }) { const [searchParams, setSearchParams] = useSearchParams(); - const previousTargetRef = useRef({ kind: 'local', server_id: null }); + const previousTargetRef = useRef({ kind: target.kind, server_id: target.server_id }); // ─── core ──────────────────────────────────────────── const [currentPath, setCurrentPath] = useState(() => searchParams.get('path') || '/home'); const [entries, setEntries] = useState([]); From dd93f01fd6d942eee3cae77ecf9980ed02276f9b Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 05:02:47 -0400 Subject: [PATCH 09/34] refactor: keep File Manager download operations in the action hook --- frontend/scripts/check-file-manager-boundaries.mjs | 6 +++++- .../file-manager/__tests__/boundaries.test.js | 2 ++ .../components/file-manager/hooks/useFileActions.js | 8 ++++++++ frontend/src/pages/FileManager.jsx | 12 +++--------- 4 files changed, 18 insertions(+), 10 deletions(-) diff --git a/frontend/scripts/check-file-manager-boundaries.mjs b/frontend/scripts/check-file-manager-boundaries.mjs index 6baa16bb..62044db3 100644 --- a/frontend/scripts/check-file-manager-boundaries.mjs +++ b/frontend/scripts/check-file-manager-boundaries.mjs @@ -29,10 +29,14 @@ export function inspectFileManagerSource(path, source) { } function visit(node) { if (!node || typeof node !== 'object') return; - if (page && node.type === 'AwaitExpression') errors.push(`${path}: asynchronous work belongs in hooks`); + if ((page || view) && node.type === 'AwaitExpression') errors.push(`${path}: asynchronous work belongs in hooks`); if ((page || view) && node.type === 'CallExpression' && node.callee?.object?.name === 'api') { errors.push(`${path}: views must not call API methods`); } + if ((page || view) && node.type === 'CallExpression' && node.callee?.object?.name === 'fileApi' + && node.callee?.property?.name !== 'supports') { + errors.push(`${path}: file operations belong in feature hooks`); + } if ((page || view) && node.type === 'CallExpression' && node.callee?.name === 'fetch') { errors.push(`${path}: views must not fetch`); } diff --git a/frontend/src/components/file-manager/__tests__/boundaries.test.js b/frontend/src/components/file-manager/__tests__/boundaries.test.js index 94950f06..585fc02b 100644 --- a/frontend/src/components/file-manager/__tests__/boundaries.test.js +++ b/frontend/src/components/file-manager/__tests__/boundaries.test.js @@ -13,6 +13,8 @@ test('boundary guard rejects dependencies that would recombine the feature', () for (const [path, source] of [ ['pages/FileManager.jsx', 'async function load() { await api.browseFiles(); }'], ['pages/FileManager.jsx', "fetch('/api/v1/files').then(render);"], + ['pages/FileManager.jsx', "fileApi.browse('/home');"], + ['components/file-manager/FileManagerListing.jsx', 'async function load() { await request(); }'], ['components/file-manager/FileManagerListing.jsx', "import { api } from '@/services/api';"], ['components/file-manager/hooks/useFileEditor.js', "import Page from '@/pages/FileManager';"], ['components/file-manager/FileManagerSidebar.jsx', "import useFileTree from './hooks/useFileTree';"], diff --git a/frontend/src/components/file-manager/hooks/useFileActions.js b/frontend/src/components/file-manager/hooks/useFileActions.js index f998a23b..82258f36 100644 --- a/frontend/src/components/file-manager/hooks/useFileActions.js +++ b/frontend/src/components/file-manager/hooks/useFileActions.js @@ -134,6 +134,12 @@ export default function useFileActions({ const openRenameModal = (entry) => setDialog({ kind: 'rename', entry }); const openPermissionsModal = (entry) => setDialog({ kind: 'permissions', entry }); + const handleDownload = (entry) => { + if (!remoteGuard('download')) fileApi.download(entry); + }; + const downloadSelected = (entries) => { + if (!remoteGuard('download')) entries.filter(entry => !entry.is_dir).forEach(fileApi.download); + }; return { dialog, @@ -143,6 +149,8 @@ export default function useFileActions({ handleDelete, handleRename, handleChangePermissions, + handleDownload, + downloadSelected, openRenameModal, openPermissionsModal, }; diff --git a/frontend/src/pages/FileManager.jsx b/frontend/src/pages/FileManager.jsx index 40cf619b..4e56eb96 100644 --- a/frontend/src/pages/FileManager.jsx +++ b/frontend/src/pages/FileManager.jsx @@ -168,6 +168,8 @@ function FileManager() { handleDelete, handleRename, handleChangePermissions, + handleDownload, + downloadSelected, openRenameModal, openPermissionsModal, } = useFileActions({ @@ -275,9 +277,6 @@ function FileManager() { const rowOpen = useStableHandler(handleOpen); const rowToggleSelect = useStableHandler(handleToggleSelect); const rowContext = useStableHandler(openContextMenu); - const handleDownload = (entry) => { - if (!remoteGuard('download')) fileApi.download(entry); - }; const rowDownload = useStableHandler(handleDownload); const rowRename = useStableHandler(openRenameModal); const rowPermissions = useStableHandler(openPermissionsModal); @@ -285,11 +284,6 @@ function FileManager() { const copyPathToClipboard = (path) => copyText(path); - const downloadSelected = () => { - if (!remoteGuard('download')) - selectedEntries.filter((e) => !e.is_dir).forEach((e) => fileApi.download(e)); - }; - useTopbarActions( () => ( <> @@ -409,7 +403,7 @@ function FileManager() { variant="unstyled" type="button" className="bulk-btn" - onClick={downloadSelected} + onClick={() => downloadSelected(selectedEntries)} > {t('common.actions.download', 'Download')} From ac0871c016036abdb785d91c1faf04f6d4ac329f Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 05:14:36 -0400 Subject: [PATCH 10/34] fix: start agent maintenance only in the guarded runtime phase --- backend/app/bootstrap/agents.py | 14 +++ backend/app/bootstrap/runtime.py | 3 + backend/app/jobs/thread_ownership.py | 4 +- backend/app/services/agent_registry.py | 5 +- .../app/services/anomaly_detection_service.py | 8 +- backend/app/services/nonce_service.py | 8 +- backend/tests/test_bootstrap_boundaries.py | 95 +++++++++++-------- backend/tests/test_no_background_threads.py | 43 +++++++++ backend/tests/test_worker_processes.py | 7 +- docs/CORE_BOUNDARIES.md | 9 +- docs/MIGRATION_INVENTORY.md | 4 +- .../scripts/check-frontend-boundaries.mjs | 12 ++- frontend/scripts/file-manager-browser.mjs | 15 +++ .../file-manager/hooks/useDirectoryBrowser.js | 4 +- 14 files changed, 174 insertions(+), 57 deletions(-) create mode 100644 backend/app/bootstrap/agents.py diff --git a/backend/app/bootstrap/agents.py b/backend/app/bootstrap/agents.py new file mode 100644 index 00000000..6c01d137 --- /dev/null +++ b/backend/app/bootstrap/agents.py @@ -0,0 +1,14 @@ +"""Process-local agent maintenance starts only in the server runtime.""" + + +def start_agent_runtime(app): + if app.config.get('TESTING'): + return + + from app.services.agent_registry import agent_registry + from app.services.nonce_service import nonce_service + from app.services.anomaly_detection_service import anomaly_detection_service + + agent_registry.start(app) + nonce_service.start_cleanup() + anomaly_detection_service.start_cleanup() diff --git a/backend/app/bootstrap/runtime.py b/backend/app/bootstrap/runtime.py index 915bc6da..d03908a4 100644 --- a/backend/app/bootstrap/runtime.py +++ b/backend/app/bootstrap/runtime.py @@ -29,6 +29,9 @@ def start_runtime(app): import logging logging.getLogger(__name__).exception('Interrupted-job recovery failed') + from app.bootstrap.agents import start_agent_runtime + start_agent_runtime(app) + # Start metrics history collection in background from app.services.metrics_history_service import MetricsHistoryService if not MetricsHistoryService.is_running(): diff --git a/backend/app/jobs/thread_ownership.py b/backend/app/jobs/thread_ownership.py index ec25824c..dde1b9ff 100644 --- a/backend/app/jobs/thread_ownership.py +++ b/backend/app/jobs/thread_ownership.py @@ -89,7 +89,7 @@ THREAD_OWNERSHIP = { 'lifecycle': LIFECYCLE_PROCESS_LOOP, 'rationale': 'Long-lived liveness checker for connected agents.', }, - 'app/services/anomaly_detection_service.py:__init__:self._cleanup_loop': { + 'app/services/anomaly_detection_service.py:start_cleanup:self._cleanup_loop': { 'owner': 'anomaly detector', 'lifecycle': LIFECYCLE_PROCESS_LOOP, 'rationale': 'Maintains process-local anomaly detector state and retention.', @@ -134,7 +134,7 @@ THREAD_OWNERSHIP = { 'lifecycle': LIFECYCLE_PROCESS_LOOP, 'rationale': 'Long-lived monitor loop; periodic migration is separate from one-shot work.', }, - 'app/services/nonce_service.py:__init__:self._cleanup_loop': { + 'app/services/nonce_service.py:start_cleanup:self._cleanup_loop': { 'owner': 'nonce store', 'lifecycle': LIFECYCLE_PROCESS_LOOP, 'rationale': 'Expires process-local nonce state.', diff --git a/backend/app/services/agent_registry.py b/backend/app/services/agent_registry.py index 74e3ec4c..98162e0a 100644 --- a/backend/app/services/agent_registry.py +++ b/backend/app/services/agent_registry.py @@ -188,7 +188,10 @@ class AgentRegistry: # Called outside an app context (e.g. during testing) — # heartbeat checker will skip DB operations gracefully. self._app = None - # Start heartbeat checker + + def start(self, app): + """Start liveness checks after application persistence is ready.""" + self._app = app self._start_heartbeat_checker() def _start_heartbeat_checker(self): diff --git a/backend/app/services/anomaly_detection_service.py b/backend/app/services/anomaly_detection_service.py index 6245f0b9..0ae3ce6e 100644 --- a/backend/app/services/anomaly_detection_service.py +++ b/backend/app/services/anomaly_detection_service.py @@ -60,8 +60,14 @@ class AnomalyDetectionService: self._lock = threading.Lock() - # Start cleanup thread self._stop_cleanup = threading.Event() + self._cleanup_thread = None + + def start_cleanup(self): + """Start retention once, from the application runtime phase.""" + if self._cleanup_thread and self._cleanup_thread.is_alive(): + return + self._stop_cleanup.clear() self._cleanup_thread = threading.Thread( target=self._cleanup_loop, daemon=True diff --git a/backend/app/services/nonce_service.py b/backend/app/services/nonce_service.py index b6efa22b..df0353e8 100644 --- a/backend/app/services/nonce_service.py +++ b/backend/app/services/nonce_service.py @@ -42,8 +42,14 @@ class NonceService: # TTL for nonces (5 minutes) self._ttl = 300 - # Start cleanup thread self._stop_cleanup = threading.Event() + self._cleanup_thread = None + + def start_cleanup(self): + """Start retention once, from the application runtime phase.""" + if self._cleanup_thread and self._cleanup_thread.is_alive(): + return + self._stop_cleanup.clear() self._cleanup_thread = threading.Thread( target=self._cleanup_loop, daemon=True diff --git a/backend/tests/test_bootstrap_boundaries.py b/backend/tests/test_bootstrap_boundaries.py index 2aeb5512..a3f2c47e 100644 --- a/backend/tests/test_bootstrap_boundaries.py +++ b/backend/tests/test_bootstrap_boundaries.py @@ -22,6 +22,7 @@ def runtime_calls(monkeypatch): modules = { 'app.jobs.service': {'JobService': SimpleNamespace(recover_interrupted=record('recover'))}, + 'app.bootstrap.agents': {'start_agent_runtime': record('agents')}, 'app.services.metrics_history_service': {'MetricsHistoryService': SimpleNamespace( is_running=lambda: False, start_collection=record('metrics'))}, 'app.queue_bus.consumers': {'start_webhook_consumer': record('webhooks')}, @@ -57,52 +58,11 @@ def test_one_shot_startup_never_recovers_or_starts_workers(monkeypatch, runtime_ def test_recovery_precedes_consumers_and_handlers_precede_jobs(monkeypatch, runtime_calls, argv): monkeypatch.setattr(sys, 'argv', argv) runtime.start_runtime(SimpleNamespace(config={}, logger=Mock())) - assert runtime_calls == ['recover', 'metrics', 'webhooks', 'notifications', + assert runtime_calls == ['recover', 'agents', 'metrics', 'webhooks', 'notifications', 'analytics', 'handlers', 'jobs', 'monitoring', 'uptime', 'linked', 'relay'] -@pytest.mark.parametrize('failed_phase', [None, 'persistence', 'plugins']) -def test_factory_phase_order_and_context(monkeypatch, failed_phase): - import app as application - from flask import has_app_context - from app.bootstrap import configuration, persistence, plugins, http - import app.sockets - import app.agent_gateway - import app.core_blueprints - from app.services import recycle_bin_service, restore_point_adapters - - calls = [] - def phase(name, context=False): - def run(*args): - assert has_app_context() is context - calls.append(name) - if name == failed_phase: - raise RuntimeError('startup failed') - return run - - monkeypatch.setattr(configuration, 'configure_application', phase('configuration')) - monkeypatch.setattr(app.sockets, 'init_socketio', phase('socket')) - monkeypatch.setattr(app.agent_gateway, 'init_agent_gateway', phase('gateway')) - monkeypatch.setattr(app.core_blueprints, 'register_core_blueprints', phase('routes')) - monkeypatch.setattr(recycle_bin_service, 'register_builtin_types', phase('recycle')) - monkeypatch.setattr(restore_point_adapters, 'register_builtin_restore_point_adapters', phase('restore')) - monkeypatch.setattr(persistence, 'prepare_persistence', phase('persistence', True)) - monkeypatch.setattr(plugins, 'load_extensions', phase('plugins', True)) - monkeypatch.setattr(runtime, 'start_runtime', phase('runtime', True)) - monkeypatch.setattr(http, 'register_http_handlers', phase('http')) - monkeypatch.setattr(application, 'socketio', application.socketio) - expected = ['configuration', 'socket', 'gateway', 'routes', 'recycle', - 'restore', 'persistence', 'plugins', 'runtime', 'http'] - if failed_phase: - with pytest.raises(RuntimeError, match='startup failed'): - application.create_app('testing') - assert calls == expected[:expected.index(failed_phase) + 1] - else: - application.create_app('testing') - assert calls == expected - - def test_monitor_failure_does_not_prevent_other_runtime_services(runtime_calls): def fail(_app): raise RuntimeError('monitor unavailable') @@ -113,6 +73,57 @@ def test_monitor_failure_does_not_prevent_other_runtime_services(runtime_calls): assert runtime_calls[-3:] == ['uptime', 'linked', 'relay'] +def test_agent_maintenance_runs_only_in_server_mode(monkeypatch): + from app.bootstrap.agents import start_agent_runtime + from app.services.agent_registry import agent_registry + from app.services.nonce_service import nonce_service + from app.services.anomaly_detection_service import anomaly_detection_service + + heartbeat, nonces, anomalies = Mock(), Mock(), Mock() + monkeypatch.setattr(agent_registry, 'start', heartbeat) + monkeypatch.setattr(nonce_service, 'start_cleanup', nonces) + monkeypatch.setattr(anomaly_detection_service, 'start_cleanup', anomalies) + start_agent_runtime(SimpleNamespace(config={'TESTING': True})) + assert not any(call.called for call in (heartbeat, nonces, anomalies)) + server = SimpleNamespace(config={}) + start_agent_runtime(server) + heartbeat.assert_called_once_with(server) + nonces.assert_called_once_with() + anomalies.assert_called_once_with() + + +@pytest.mark.parametrize('module_name,instance_name', [ + ('nonce_service', 'nonce_service'), + ('anomaly_detection_service', 'anomaly_detection_service'), +]) +def test_agent_cleanup_start_is_idempotent(monkeypatch, module_name, instance_name): + import importlib + import threading + module = importlib.import_module(f'app.services.{module_name}') + service = getattr(module, instance_name) + thread = Mock() + thread.is_alive.return_value = True + constructor = Mock(return_value=thread) + monkeypatch.setattr(service, '_cleanup_thread', None) + monkeypatch.setattr(service, '_stop_cleanup', threading.Event()) + monkeypatch.setattr(module.threading, 'Thread', constructor) + service.start_cleanup() + service.start_cleanup() + constructor.assert_called_once() + thread.start.assert_called_once() + + +def test_heartbeat_runtime_captures_the_serving_app(monkeypatch): + from app.services.agent_registry import agent_registry + start = Mock() + monkeypatch.setattr(agent_registry, '_start_heartbeat_checker', start) + monkeypatch.setattr(agent_registry, '_app', None) + server = object() + agent_registry.start(server) + assert agent_registry._app is server + start.assert_called_once_with() + + def test_bootstrap_is_an_assembly_layer_not_a_service_dependency(): root = Path(__file__).parents[1] / 'app' for folder in ('api', 'services', 'models', 'jobs'): diff --git a/backend/tests/test_no_background_threads.py b/backend/tests/test_no_background_threads.py index 158f0db7..f7f89065 100644 --- a/backend/tests/test_no_background_threads.py +++ b/backend/tests/test_no_background_threads.py @@ -13,6 +13,8 @@ the queue-bus consumers) or started only by an explicit runtime trigger """ import threading +import pytest + def _thread_ids(): return {t.ident for t in threading.enumerate()} @@ -48,3 +50,44 @@ def test_create_app_testing_spawns_no_background_threads(): finally: db.session.remove() db.drop_all() + + +@pytest.mark.parametrize('failed_phase', [None, 'persistence', 'plugins']) +def test_factory_phase_order_and_context(monkeypatch, failed_phase): + import app as application + from flask import has_app_context + from app.bootstrap import configuration, persistence, plugins, http, runtime + import app.sockets + import app.agent_gateway + import app.core_blueprints + from app.services import recycle_bin_service, restore_point_adapters + + calls = [] + def phase(name, context=False): + def run(*args): + assert has_app_context() is context + calls.append(name) + if name == failed_phase: + raise RuntimeError('startup failed') + return run + + monkeypatch.setattr(configuration, 'configure_application', phase('configuration')) + monkeypatch.setattr(app.sockets, 'init_socketio', phase('socket')) + monkeypatch.setattr(app.agent_gateway, 'init_agent_gateway', phase('gateway')) + monkeypatch.setattr(app.core_blueprints, 'register_core_blueprints', phase('routes')) + monkeypatch.setattr(recycle_bin_service, 'register_builtin_types', phase('recycle')) + monkeypatch.setattr(restore_point_adapters, 'register_builtin_restore_point_adapters', phase('restore')) + monkeypatch.setattr(persistence, 'prepare_persistence', phase('persistence', True)) + monkeypatch.setattr(plugins, 'load_extensions', phase('plugins', True)) + monkeypatch.setattr(runtime, 'start_runtime', phase('runtime', True)) + monkeypatch.setattr(http, 'register_http_handlers', phase('http')) + monkeypatch.setattr(application, 'socketio', application.socketio) + expected = ['configuration', 'socket', 'gateway', 'routes', 'recycle', + 'restore', 'persistence', 'plugins', 'runtime', 'http'] + if failed_phase: + with pytest.raises(RuntimeError, match='startup failed'): + application.create_app('testing') + assert calls == expected[:expected.index(failed_phase) + 1] + else: + application.create_app('testing') + assert calls == expected diff --git a/backend/tests/test_worker_processes.py b/backend/tests/test_worker_processes.py index 62d5950c..8280e202 100644 --- a/backend/tests/test_worker_processes.py +++ b/backend/tests/test_worker_processes.py @@ -96,11 +96,16 @@ class TestDeploy: assert result['started'] == [] and set(result['failed']) == {'worker', 'scheduler'} -def test_build_pack_containers_are_listed_web_first(app, fake_subprocess): +@pytest.mark.parametrize('compose_command', [None, ['docker', 'compose'], ['docker-compose']]) +def test_build_pack_containers_are_listed_web_first(app, fake_subprocess, monkeypatch, compose_command): + # Prior tests can cache either Compose flavor. Both must yield the same + # build-pack fallback; keep the fake transport independent of test order. + monkeypatch.setattr(DockerService, '_compose_cmd', compose_command) site = make_application(db, name='shop', buildpack_type='python', root_path='/nonexistent') rows = [{'ID': 'w1', 'Names': f'serverkit-app-{site.id}-worker', 'State': 'running'}, {'ID': 'm1', 'Names': f'serverkit-app-{site.id}', 'State': 'running'}] fake_subprocess.script(['docker', 'compose'], stdout='') + fake_subprocess.script(['docker-compose'], stdout='') fake_subprocess.script(['docker', 'ps'], stdout='\n'.join(json.dumps(r) for r in rows)) listed = DockerService.get_all_app_containers(site) assert [(c['id'], c['service']) for c in listed] == [('m1', 'web'), ('w1', 'worker')] diff --git a/docs/CORE_BOUNDARIES.md b/docs/CORE_BOUNDARIES.md index 080a22d0..57f587ba 100644 --- a/docs/CORE_BOUNDARIES.md +++ b/docs/CORE_BOUNDARIES.md @@ -23,14 +23,18 @@ context. Database preparation precedes extension queries; interrupted-job recovery precedes consumers; job handlers precede the job consumer. One-shot Flask commands and `SERVERKIT_SKIP_BACKGROUND` suppress runtime startup. The existing individual services retain their testing and singleton guards. +Agent heartbeat, nonce retention and anomaly retention are explicitly started +by `bootstrap/agents.py`; importing services or binding the gateway does not +launch those threads. The heartbeat runtime receives the serving Flask app. Bootstrap may depend on services, models, middleware and jobs. Those layers must not import bootstrap. A feature exposes a registration/initialization function; its appropriate bootstrap phase invokes it. Existing migration policy and fail-soft extension behavior are preserved by this split. -`backend/tests/test_bootstrap_boundaries.py` enforces dependency direction, -factory composition, startup order, context, and CLI suppression. The core +`backend/tests/test_bootstrap_boundaries.py` and `test_no_background_threads.py` +enforce dependency direction, factory composition, startup order, context, +worker lifecycle, and CLI suppression. The core blueprint registry and API-error tests verify the assembled application. ## File Manager @@ -77,6 +81,7 @@ adapter but does not issue API calls or await requests. target switching, late results, editing, confirmations and uploads. - `npm run build`: verify the complete production import graph. - `python -m pytest tests/test_bootstrap_boundaries.py + tests/test_no_background_threads.py tests/test_core_blueprint_registry.py tests/test_cli_skips_background.py tests/test_api_error_shape.py` in `backend`: focused startup coverage. - Run the full backend suite for application assembly changes. diff --git a/docs/MIGRATION_INVENTORY.md b/docs/MIGRATION_INVENTORY.md index 85d2a556..1709215c 100644 --- a/docs/MIGRATION_INVENTORY.md +++ b/docs/MIGRATION_INVENTORY.md @@ -19,8 +19,8 @@ debt. Regenerate with `python scripts/generate-migration-inventory.py`. | Hand-shaped {'error': ...} bodies in app/api | typed errors + the global handler | 848 | 850 | migrate when touched; new endpoints raise | | Raw subprocess calls outside the runners | app/utils/system.py runners | 23 | 23 | migrate when touched | | Controller-boundary violations (routes doing service work) | service layer extraction | 477 | 477 | migrate when touched (first-wave ratchet) | -| raw api.* calls in pages/ | E1: useServerQuery/useServerMutation | 395 | 398 | migrate when touched | -| per-page toast.error extractions in pages/ | E1: query-layer error presentation | 199 | 206 | migrate when touched | +| raw api.* calls in pages/ | E1: useServerQuery/useServerMutation | 374 | 398 | migrate when touched | +| per-page toast.error extractions in pages/ | E1: query-layer error presentation | 191 | 206 | migrate when touched | | hand-rolled form-group blocks | F2: FormField/useForm | 314 | 321 | migrate when touched | | unencoded ?k=${v} query interpolations in services/api | C4: buildQuery/encoding template | 0 | 0 | INVARIANT at 0 | | raw setInterval pollers | E2: usePolling/refetchInterval | 7 | 7 | DELIBERATE RESIDUE: clock ticks, socket-fallback hooks, and sibling-repo extension timers - each listed per file | diff --git a/frontend/scripts/check-frontend-boundaries.mjs b/frontend/scripts/check-frontend-boundaries.mjs index 2a5c325c..1bb3ca42 100644 --- a/frontend/scripts/check-frontend-boundaries.mjs +++ b/frontend/scripts/check-frontend-boundaries.mjs @@ -9,9 +9,12 @@ import { existsSync, readFileSync, readdirSync } from 'node:fs'; import { dirname, extname, join, relative, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { checkFileManagerBoundaries } from './check-file-manager-boundaries.mjs'; - -checkFileManagerBoundaries(); +// Inventory is also consumed by backend-only CI without npm dependencies. +// The AST architecture guard runs with the normal frontend lint toolchain. +if (!process.argv.includes('--inventory')) { + const { checkFileManagerBoundaries } = await import('./check-file-manager-boundaries.mjs'); + checkFileManagerBoundaries(); +} const here = dirname(fileURLToPath(import.meta.url)); const root = resolve(here, '..'); @@ -122,7 +125,8 @@ function walk(dir) { }); } -const files = walk(src).filter((path) => ['.js', '.jsx'].includes(extname(path))); +const files = walk(src).filter((path) => ['.js', '.jsx'].includes(extname(path)) + && !relative(src, path).replaceAll('\\', '/').split('/').includes('__tests__')); const failures = []; const seenClipboard = new Set(); const seenPollers = new Set(); diff --git a/frontend/scripts/file-manager-browser.mjs b/frontend/scripts/file-manager-browser.mjs index f46c1800..ab58062b 100644 --- a/frontend/scripts/file-manager-browser.mjs +++ b/frontend/scripts/file-manager-browser.mjs @@ -339,6 +339,21 @@ try { assert.equal(await deepLink.getByText('projects', { exact: true }).count(), 0); assert.equal(await deepLink.getByTitle('Back', { exact: true }).isDisabled(), true); console.log('PASS initial deep links retain their directory and history'); + + const clearing = await browser.newPage(); + await clearing.goto(`http://127.0.0.1:${server.httpServer.address().port}/fm-check`); + await clearing.getByText('projects', { exact: true }).first().waitFor(); + await clearing.getByPlaceholder('Search files…').fill('draft query'); + await clearing.getByText('projects', { exact: true }).first().dblclick(); + await clearing.waitForFunction(() => window.pending.some(x => x.path === '/home/projects')); + await clearing.locator('.search-field-clear').click(); + assert.equal(await clearing.locator('.file-manager-main').getByText('projects', { exact: true }).count(), 0, + 'clearing a query must not expose the previous directory listing while browsing'); + await clearing.evaluate(() => { + while (window.pending.some(x => x.path === '/home/projects')) window.release('/home/projects'); + }); + await clearing.getByText('inside-projects.txt', { exact: true }).waitFor(); + console.log('PASS clearing a query during navigation preserves the pending directory load'); } finally { await browser?.close(); await server.close(); diff --git a/frontend/src/components/file-manager/hooks/useDirectoryBrowser.js b/frontend/src/components/file-manager/hooks/useDirectoryBrowser.js index 755d2995..eb5743e1 100644 --- a/frontend/src/components/file-manager/hooks/useDirectoryBrowser.js +++ b/frontend/src/components/file-manager/hooks/useDirectoryBrowser.js @@ -183,7 +183,9 @@ export default function useDirectoryBrowser({ loadSeqRef.current++; setSearchResults(null); setSearchQuery(''); - setLoading(false); + // A directory browse may also be pending. Restore the current listing + // instead of revealing entries from the previously visited folder. + loadDirectory(currentPath); }; const handleSearch = async () => { if (remoteGuard('search')) { From 2a030b31effee088f3ff4a3cfb6c9b32ada517f6 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 05:33:01 -0400 Subject: [PATCH 11/34] test: capture nginx rendering contract before extraction --- .../tests/fixtures/nginx-render-contract.json | 10 +++++ backend/tests/test_nginx_render_contract.py | 40 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 backend/tests/fixtures/nginx-render-contract.json create mode 100644 backend/tests/test_nginx_render_contract.py diff --git a/backend/tests/fixtures/nginx-render-contract.json b/backend/tests/fixtures/nginx-render-contract.json new file mode 100644 index 00000000..4d1497e6 --- /dev/null +++ b/backend/tests/fixtures/nginx-render-contract.json @@ -0,0 +1,10 @@ +{ + "php": "e6d77fd5ac90d438b9f694b3dcf50d63746bd87f3e20030e0c4bd6e94c6f372a", + "wordpress": "e6d77fd5ac90d438b9f694b3dcf50d63746bd87f3e20030e0c4bd6e94c6f372a", + "flask": "dba3ba47c2d2407bcbcf3b8014bc6f5dc105db8a7e5837f849b871fd5960329b", + "django": "dba3ba47c2d2407bcbcf3b8014bc6f5dc105db8a7e5837f849b871fd5960329b", + "python": "dba3ba47c2d2407bcbcf3b8014bc6f5dc105db8a7e5837f849b871fd5960329b", + "docker": "a18576b49626ed0f88126de8946163720d715016ee24119de22afdb38fda4400", + "remote": "7bc871f2c95a333cfe14129ae40df409a3a2165e79fb7c9205510957c95af99f", + "static": "91d63c4279f9fa1fa1ecc1cfd0e3f8c5b63e134613d319ae189a4560d3738e28" +} diff --git a/backend/tests/test_nginx_render_contract.py b/backend/tests/test_nginx_render_contract.py new file mode 100644 index 00000000..1368f345 --- /dev/null +++ b/backend/tests/test_nginx_render_contract.py @@ -0,0 +1,40 @@ +"""Byte-for-byte characterization of the pre-extraction vhost pipeline. + +The digest for each app type covers SSL, cache, immutable assets and WordPress +protection together (including rejected combinations), plus TTL boundaries. +Semantic assertions live in the existing nginx/cache/HTTPS suites. These hashes +specifically detect accidental template whitespace or pipeline-order changes. +""" +import hashlib +import itertools +import json +from pathlib import Path + +import pytest + +from app.services.nginx_service import NginxService + + +APP_TYPES = ('php', 'wordpress', 'flask', 'django', 'python', 'docker', 'remote', 'static') +SNAPSHOT = Path(__file__).with_name('fixtures') / 'nginx-render-contract.json' + + +def render_contract(app_type): + results = [] + for ssl, cache, immutable, wordpress in itertools.product((False, True), repeat=4): + for ttl in (None, 0, 10, 999): + results.append(NginxService.render_site_config( + 'shop', app_type, ['shop.example.com', 'www.shop.example.com'], + root_path='/srv/shop/public', port=8123, upstream='10.0.0.5:8123', + ssl_cert='/certs/shop.pem' if ssl else None, + ssl_key='/certs/shop.key' if ssl else None, + micro_cache=cache, micro_cache_ttl=ttl, + immutable_assets=immutable, wordpress_protection=wordpress, + )) + return hashlib.sha256(json.dumps(results, sort_keys=True).encode()).hexdigest() + + +@pytest.mark.parametrize('app_type', APP_TYPES) +def test_generated_vhosts_preserve_existing_output(app_type): + expected = json.loads(SNAPSHOT.read_text()) + assert render_contract(app_type) == expected[app_type] From 69a9ad345a43460904df39c6e139ac9c91eca719 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 05:36:03 -0400 Subject: [PATCH 12/34] refactor: separate nginx configuration rendering from host operations --- backend/app/services/nginx/__init__.py | 1 + backend/app/services/nginx/compression.py | 63 ++ backend/app/services/nginx/rendering.py | 221 +++++++ backend/app/services/nginx/templates.py | 452 +++++++++++++ backend/app/services/nginx/validation.py | 15 + backend/app/services/nginx_service.py | 761 +++------------------- 6 files changed, 838 insertions(+), 675 deletions(-) create mode 100644 backend/app/services/nginx/__init__.py create mode 100644 backend/app/services/nginx/compression.py create mode 100644 backend/app/services/nginx/rendering.py create mode 100644 backend/app/services/nginx/templates.py create mode 100644 backend/app/services/nginx/validation.py diff --git a/backend/app/services/nginx/__init__.py b/backend/app/services/nginx/__init__.py new file mode 100644 index 00000000..974811e5 --- /dev/null +++ b/backend/app/services/nginx/__init__.py @@ -0,0 +1 @@ +"""Nginx configuration generation, independent of host operations.""" diff --git a/backend/app/services/nginx/compression.py b/backend/app/services/nginx/compression.py new file mode 100644 index 00000000..76470516 --- /dev/null +++ b/backend/app/services/nginx/compression.py @@ -0,0 +1,63 @@ +"""Render compression directives from supplied nginx dump/version text.""" +import re + +from . import templates + + +def _http_level_directives(dump: str, skip_file: str) -> set: + """Directive names set at http level in an ``nginx -T`` dump. + + ``nginx -T`` prints each file after a ``# configuration file :`` + header. In the main nginx.conf, http level is depth 1 inside + ``http {}``; every other file is included from the http block (conf.d) + or a server (sites), so its depth-0 directives are the http-level + ones. ``skip_file`` (our own snippet) is ignored so a rewrite never + mistakes its own lines for someone else's. + """ + found = set() + current = None + depth = 0 + in_http = False + for raw in dump.splitlines(): + header = re.match(r'^# configuration file (.+):$', raw.strip()) + if header: + current = header.group(1) + depth = 0 + in_http = False + continue + if current is None or current == skip_file: + continue + line = raw.split('#', 1)[0].strip() + if not line: + continue + is_main = current.endswith('/nginx.conf') + http_level = (depth == 1 and in_http) if is_main else depth == 0 + name = line.split(None, 1)[0].rstrip(';{') + if http_level and line.endswith(';'): + found.add(name) + if is_main and depth == 0 and name == 'http' and '{' in line: + in_http = True + depth += line.count('{') - line.count('}') + if is_main and depth == 0: + in_http = False + return found + + +def render_compression_snippet(dump: str, conf_path: str, + nginx_v: str = '', *, gzip_directives=templates.GZIP_DIRECTIVES, brotli_directives=templates.BROTLI_DIRECTIVES) -> str: + """The snippet for this box. When the running config already sets + everything it is comments only: still written, so the "already + handled" check stays a file-exists test instead of an ``nginx -T`` + on every vhost write.""" + present = _http_level_directives(dump, conf_path) + brotli = ('ngx_http_brotli_filter_module' in dump + or 'brotli' in (nginx_v or '').lower()) + wanted = list(gzip_directives) + if brotli: + wanted += list(brotli_directives) + lines = [f'{name} {value};' for name, value in wanted if name not in present] + kept = sorted(name for name, _ in wanted if name in present) + header = ['# ServerKit compression (auto-generated; do not edit).'] + if kept: + header.append('# Already set elsewhere, left alone: ' + ', '.join(kept)) + return '\n'.join(header + lines) + '\n' diff --git a/backend/app/services/nginx/rendering.py b/backend/app/services/nginx/rendering.py new file mode 100644 index 00000000..5c131889 --- /dev/null +++ b/backend/app/services/nginx/rendering.py @@ -0,0 +1,221 @@ +"""Pure vhost rendering. Inputs are values; output is text or a validation error.""" +import re +from dataclasses import dataclass +from typing import Dict, List, Optional + +from . import templates +from .validation import _validate_domain, _validate_path + + +@dataclass(frozen=True) +class RenderSettings: + """Template values, isolated from the service's filesystem/process methods.""" + DOCKER_SITE_TEMPLATE: str = templates.DOCKER_SITE_TEMPLATE + IMMUTABLE_ASSET_HEADERS: str = templates.IMMUTABLE_ASSET_HEADERS + IMMUTABLE_ASSET_PATTERN: str = templates.IMMUTABLE_ASSET_PATTERN + MICROCACHE_FASTCGI_BLOCK: str = templates.MICROCACHE_FASTCGI_BLOCK + MICROCACHE_PROXY_BLOCK: str = templates.MICROCACHE_PROXY_BLOCK + MICROCACHE_SKIP_BLOCK: str = templates.MICROCACHE_SKIP_BLOCK + MICROCACHE_TTL_DEFAULT: int = templates.MICROCACHE_TTL_DEFAULT + MICROCACHE_TTL_MAX: int = templates.MICROCACHE_TTL_MAX + PHP_SITE_TEMPLATE: str = templates.PHP_SITE_TEMPLATE + PYTHON_SITE_TEMPLATE: str = templates.PYTHON_SITE_TEMPLATE + REMOTE_UPSTREAM_TEMPLATE: str = templates.REMOTE_UPSTREAM_TEMPLATE + SSL_BLOCK: str = templates.SSL_BLOCK + SSL_REDIRECT_TEMPLATE: str = templates.SSL_REDIRECT_TEMPLATE + STATIC_SITE_TEMPLATE: str = templates.STATIC_SITE_TEMPLATE + WORDPRESS_PROTECTION_BLOCK: str = templates.WORDPRESS_PROTECTION_BLOCK + + +DEFAULT_SETTINGS = RenderSettings() + + +def render_site_config(name: str, app_type: str, domains: List[str], + root_path: str = None, port: int = None, + php_version: str = '8.2', + ssl_cert: str = None, ssl_key: str = None, + upstream: str = None, + micro_cache: bool = False, + micro_cache_ttl: Optional[int] = None, + immutable_assets: bool = False, + wordpress_protection: bool = False, *, + settings: RenderSettings = DEFAULT_SETTINGS) -> Dict: + """Render the vhost config for a site to a string — no side effects. + + This is the exact template pipeline :meth:`create_site` writes to disk; + it is exposed separately so callers (e.g. drift detection) can compute + the expected on-disk content without touching the filesystem. + Returns ``{'success': True, 'config': str}`` or + ``{'success': False, 'error': msg}``. + """ + if not domains: + return {'success': False, 'error': 'At least one domain is required'} + + # Validate all domains + for domain in domains: + if domain == '_': + return {'success': False, 'error': 'Wildcard server_name "_" is reserved for the ServerKit panel'} + if not _validate_domain(domain): + return {'success': False, 'error': f'Invalid domain name: {domain}'} + + # Validate root_path if provided + if root_path and not _validate_path(root_path): + return {'success': False, 'error': f'Invalid root path: {root_path}'} + + domains_str = ' '.join(domains) + + # Select template based on app type + if app_type in ['php', 'wordpress']: + config = settings.PHP_SITE_TEMPLATE.format( + name=name, + domains=domains_str, + root_path=root_path, + php_version=php_version + ) + elif app_type in ['flask', 'django', 'python']: + if not port: + return {'success': False, 'error': 'Python services need a port'} + config = settings.PYTHON_SITE_TEMPLATE.format( + name=name, + domains=domains_str, + root_path=root_path, + port=port + ) + elif app_type == 'docker': + if not port: + return {'success': False, 'error': 'Docker services need a port'} + config = settings.DOCKER_SITE_TEMPLATE.format( + name=name, + domains=domains_str, + port=port + ) + elif app_type == 'remote': + if not upstream: + return {'success': False, 'error': 'Services on remote servers need an upstream (host:port)'} + config = settings.REMOTE_UPSTREAM_TEMPLATE.format( + name=name, + domains=domains_str, + upstream=upstream, + ) + elif app_type == 'static': + config = settings.STATIC_SITE_TEMPLATE.format( + name=name, + domains=domains_str, + root_path=root_path + ) + else: + return {'success': False, 'error': f'Unknown service type: {app_type}'} + + if immutable_assets: + config = _with_immutable_assets(config, app_type, settings=settings) + + if micro_cache: + # Inject before the SSL wrap so the redirect server block (which + # also carries a server_name line) never receives cache directives. + config = _with_micro_cache(config, app_type, micro_cache_ttl, settings=settings) + + if wordpress_protection: + if app_type != 'docker' or not port: + return { + 'success': False, + 'error': 'WordPress protection requires a Docker proxy port', + } + config = _with_wordpress_protection(config, port, settings=settings) + + if ssl_cert and ssl_key: + config = _with_ssl(config, domains_str, ssl_cert, ssl_key, settings=settings) + + return {'success': True, 'config': config} + + +def _with_wordpress_protection(config: str, port: int, *, + settings: RenderSettings = DEFAULT_SETTINGS) -> str: + """Add exact-match throttling locations before the catch-all proxy.""" + anchor = ' location / {\n' + if anchor not in config: + return config + block = settings.WORDPRESS_PROTECTION_BLOCK.format(port=port) + return config.replace(anchor, block + anchor, 1) + + +def _with_immutable_assets(config: str, app_type: str, *, + settings: RenderSettings = DEFAULT_SETTINGS) -> str: + """Add a regex location for fingerprinted assets to a proxied vhost: + the same proxying as ``location /`` plus a one-year immutable cache. + Appended after ``location /`` (a matching regex location wins over the + ``/`` prefix wherever it sits) so the micro-cache injection still + anchors on the real ``location /``.""" + if (app_type or '').lower() not in ('flask', 'django', 'python', 'docker', 'remote'): + return config + match = re.search(r'^ location / \{\n(.*?)^ \}\n', config, re.MULTILINE | re.DOTALL) + if not match: + return config + block = ('\n # ServerKit: fingerprinted assets never change\n' + f' location ~* "{settings.IMMUTABLE_ASSET_PATTERN}" {{\n' + + match.group(1) + settings.IMMUTABLE_ASSET_HEADERS + ' }\n') + return config[:match.end()] + block + config[match.end():] + + +def _with_micro_cache(config: str, app_type: str, + ttl: Optional[int] = None, *, + settings: RenderSettings = DEFAULT_SETTINGS) -> str: + """Inject the shared-zone micro-cache directives into a rendered vhost. + + fastcgi_cache for PHP-FPM-served sites, proxy_cache for reverse-proxied + ones; static sites are a no-op (files already come straight off disk). + Scheme-agnostic — nothing here depends on HTTP vs HTTPS. The referenced + zones are declared once in conf.d by :meth:`ensure_cache_zone`. + """ + t = (app_type or '').lower() + ttl = clamp_micro_cache_ttl(ttl, settings=settings) + if t in ('php', 'wordpress'): + anchor = ' include fastcgi_params;\n' + if anchor not in config: + return config + config = config.replace( + anchor, anchor + settings.MICROCACHE_FASTCGI_BLOCK.format(ttl=ttl), 1) + elif t in ('flask', 'django', 'python', 'docker', 'remote'): + # proxy_cache_bypass may only be declared once per location, so + # fold $sk_skip_cache into the template's existing $http_upgrade + # bypass instead of adding a duplicate directive. + anchor = ' proxy_cache_bypass $http_upgrade;\n' + if anchor not in config: + return config + config = config.replace( + anchor, + ' proxy_cache_bypass $sk_skip_cache $http_upgrade;\n' + + settings.MICROCACHE_PROXY_BLOCK.format(ttl=ttl), + 1, + ) + else: + return config + + # Server-level $sk_skip_cache logic, right after server_name. + match = re.search(r'^( server_name [^;]+;\n)', config, re.MULTILINE) + if match: + config = config.replace( + match.group(1), match.group(1) + '\n' + settings.MICROCACHE_SKIP_BLOCK, 1) + return config + + +def clamp_micro_cache_ttl(ttl, *, settings: RenderSettings = DEFAULT_SETTINGS) -> int: + """A stored TTL as the seconds the vhost uses: unset → the 10s + default, anything else clamped to 1..MICROCACHE_TTL_MAX.""" + if ttl in (None, ''): + return settings.MICROCACHE_TTL_DEFAULT + return max(1, min(int(ttl), settings.MICROCACHE_TTL_MAX)) + + +def _with_ssl(http_config: str, domains: str, ssl_cert: str, ssl_key: str, *, + settings: RenderSettings = DEFAULT_SETTINGS) -> str: + """Turn an HTTP server block into HTTPS: swap the :80 listens for the TLS + block (so the existing server serves 443) and prepend an HTTP->HTTPS + redirect. Idempotent because create_site regenerates the whole file.""" + ssl_block = settings.SSL_BLOCK.format(ssl_cert=ssl_cert, ssl_key=ssl_key) + https_config = http_config.replace( + ' listen 80;\n listen [::]:80;', + ssl_block.strip('\n'), + 1, + ) + redirect = settings.SSL_REDIRECT_TEMPLATE.format(domains=domains) + return redirect + '\n' + https_config diff --git a/backend/app/services/nginx/templates.py b/backend/app/services/nginx/templates.py new file mode 100644 index 00000000..e60ec4de --- /dev/null +++ b/backend/app/services/nginx/templates.py @@ -0,0 +1,452 @@ +"""Configuration text and defaults only; no environment or host access.""" + +PHP_SITE_TEMPLATE = '''server {{ + listen 80; + listen [::]:80; + server_name {domains}; + + root {root_path}; + index index.php index.html index.htm; + + access_log /var/log/nginx/{name}.access.log serverkit_timed; + error_log /var/log/nginx/{name}.error.log; + + location / {{ + try_files $uri $uri/ /index.php?$query_string; + }} + + location ~ \\.php$ {{ + fastcgi_pass unix:/run/php/php{php_version}-fpm.sock; + fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; + include fastcgi_params; + fastcgi_intercept_errors on; + fastcgi_buffer_size 16k; + fastcgi_buffers 4 16k; + }} + + location ~ /\\.ht {{ + deny all; + }} + + location = /favicon.ico {{ + log_not_found off; + access_log off; + }} + + location = /robots.txt {{ + log_not_found off; + access_log off; + allow all; + }} + + location ~* \\.(css|gif|ico|jpeg|jpg|js|png|svg|woff|woff2)$ {{ + expires 1y; + log_not_found off; + }} +}} +''' + +PYTHON_SITE_TEMPLATE = '''server {{ + listen 80; + listen [::]:80; + server_name {domains}; + + access_log /var/log/nginx/{name}.access.log serverkit_timed; + error_log /var/log/nginx/{name}.error.log; + + location / {{ + proxy_pass http://127.0.0.1:{port}; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection 'upgrade'; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache_bypass $http_upgrade; + proxy_read_timeout 86400; + }} + + location /static {{ + alias {root_path}/static; + expires 1y; + }} +}} +''' + +STATIC_SITE_TEMPLATE = '''server {{ + listen 80; + listen [::]:80; + server_name {domains}; + + root {root_path}; + index index.html index.htm; + + access_log /var/log/nginx/{name}.access.log serverkit_timed; + error_log /var/log/nginx/{name}.error.log; + + location / {{ + try_files $uri $uri/ =404; + }} + + location ~* \\.(css|gif|ico|jpeg|jpg|js|png|svg|woff|woff2)$ {{ + expires 1y; + log_not_found off; + }} +}} +''' + +# Docker reverse proxy template (for containerized apps) +DOCKER_SITE_TEMPLATE = '''server {{ + listen 80; + listen [::]:80; + server_name {domains}; + + access_log /var/log/nginx/{name}.access.log serverkit_timed; + error_log /var/log/nginx/{name}.error.log; + + location / {{ + proxy_pass http://127.0.0.1:{port}; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection 'upgrade'; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache_bypass $http_upgrade; + proxy_read_timeout 86400; + proxy_connect_timeout 60; + proxy_send_timeout 60; + }} +}} +''' + +# WordPress authentication endpoints receive a dedicated request limit in +# published reverse-proxy vhosts. The zones are shared across vhosts, while +# the key includes server_name so traffic to one site cannot consume +# another site's allowance. +WORDPRESS_RATE_LIMIT_CONF_NAME = 'serverkit-wordpress-rate-limit.conf' +WORDPRESS_RATE_LIMIT_ZONE_SNIPPET = '''# ServerKit WordPress request-limit zones (auto-generated; do not edit). +limit_req_zone $server_name$binary_remote_addr zone=serverkit_wp_login:10m rate=10r/m; +limit_req_zone $server_name$binary_remote_addr zone=serverkit_wp_xmlrpc:10m rate=30r/m; +''' + +WORDPRESS_PROTECTION_BLOCK = ''' # ServerKit WordPress brute-force protection + location = /wp-login.php {{ + limit_req zone=serverkit_wp_login burst=10 nodelay; + limit_req_status 429; + proxy_pass http://127.0.0.1:{port}; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_read_timeout 86400; + proxy_connect_timeout 60; + proxy_send_timeout 60; + }} + + location = /xmlrpc.php {{ + limit_req zone=serverkit_wp_xmlrpc burst=20 nodelay; + limit_req_status 429; + proxy_pass http://127.0.0.1:{port}; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_read_timeout 86400; + proxy_connect_timeout 60; + proxy_send_timeout 60; + }} + +''' + +# Reverse proxy to a service reached over a WireGuard tunnel (roadmap +# #12). The upstream is a peer's WG IP:port; the private agent forwards +# it to the real service. proxy_buffering off keeps media/streaming +# (e.g. Jellyfin) responsive. +REMOTE_UPSTREAM_TEMPLATE = '''server {{ + listen 80; + listen [::]:80; + server_name {domains}; + + access_log /var/log/nginx/{name}.access.log serverkit_timed; + error_log /var/log/nginx/{name}.error.log; + + location / {{ + proxy_pass http://{upstream}; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection 'upgrade'; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache_bypass $http_upgrade; + proxy_buffering off; + proxy_read_timeout 86400; + proxy_connect_timeout 60; + proxy_send_timeout 60; + }} +}} +''' + +SSL_BLOCK = ''' + listen 443 ssl http2; + listen [::]:443 ssl http2; + + ssl_certificate {ssl_cert}; + ssl_certificate_key {ssl_key}; + ssl_session_timeout 1d; + ssl_session_cache shared:SSL:50m; + ssl_session_tickets off; + + ssl_protocols TLSv1.2 TLSv1.3; + ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384; + ssl_prefer_server_ciphers off; + ssl_ecdh_curve X25519:secp384r1; + + # HSTS: 2 years, all subdomains, preload-eligible. Submit the domain at + # https://hstspreload.org to get onto the browser preload list (this is what + # protects first-time visitors from an initial-request MITM downgrade). + add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always; + + # Baseline response-header hardening. These are safe for reverse-proxied apps; + # the CSP is deliberately permissive so it does not break managed apps while + # still satisfying "a CSP is present" and blocking cross-origin framing. + # Tighten the CSP per-app when the upstream can support a stricter policy. + add_header X-Content-Type-Options "nosniff" always; + add_header X-Frame-Options "SAMEORIGIN" always; + add_header Referrer-Policy "strict-origin-when-cross-origin" always; + add_header Content-Security-Policy "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: blob: https:; frame-ancestors 'self'; upgrade-insecure-requests" always; +''' + +SSL_REDIRECT_TEMPLATE = '''server {{ + listen 80; + listen [::]:80; + server_name {domains}; + return 301 https://$server_name$request_uri; +}} +''' + +# Private URL routing templates +PRIVATE_URL_CONFIG_NAME = 'serverkit-private-urls' +GITEA_CONFIG_NAME = 'serverkit-gitea' +WORDPRESS_CONFIG_NAME = 'serverkit-wordpress' + +# Gitea location block for /gitea path (included inside main server block) +GITEA_LOCATION_TEMPLATE = '''# Gitea at /gitea path +location /gitea/ {{ + proxy_pass http://127.0.0.1:{port}/; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Host $host; + proxy_cache_bypass $http_upgrade; + proxy_read_timeout 86400; + proxy_connect_timeout 60; + proxy_send_timeout 60; + + # Required for Gitea WebSocket connections + proxy_buffering off; + client_max_body_size 100M; +}} + +# Handle /gitea without trailing slash +location = /gitea {{ + return 301 /gitea/; +}} +''' + +# WordPress location block for /wordpress path (included inside main server block) +WORDPRESS_LOCATION_TEMPLATE = '''# WordPress at /wordpress path +location /wordpress/ {{ + proxy_pass http://127.0.0.1:{port}/; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Host $host; + proxy_cache_bypass $http_upgrade; + proxy_read_timeout 300; + proxy_connect_timeout 60; + proxy_send_timeout 60; + + # WordPress file uploads + client_max_body_size 256M; +}} + +# Handle /wordpress without trailing slash +location = /wordpress {{ + return 301 /wordpress/; +}} +''' + +PRIVATE_URL_LOCATION_TEMPLATE = ''' # Private URL: /p/{slug} + location /p/{slug}/ {{ + proxy_pass http://127.0.0.1:{port}/; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection 'upgrade'; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Private-URL {slug}; + proxy_cache_bypass $http_upgrade; + proxy_read_timeout 86400; + }} + + # Also handle without trailing slash + location = /p/{slug} {{ + return 301 /p/{slug}/; + }} +''' + +# ==================== TIMED ACCESS LOG ==================== +# Every vhost ServerKit writes logs in this format. The combined fields come +# first, unchanged, so every existing combined-format reader (bandwidth +# accounting, the fail2ban `^ -` filters) keeps matching; the timing +# fields are appended after them. The app id is the log file itself +# (/var/log/nginx/.access.log) — a per-vhost `set` variable would make +# `nginx -t` warn on every server block that never sets it. +TIMED_LOG_FORMAT = 'serverkit_timed' +TIMED_LOG_CONF_NAME = 'serverkit-log-format.conf' +TIMED_LOG_FORMAT_SNIPPET = """# ServerKit timed access-log format (auto-generated; do not edit). +# Combined fields first (compatible with combined parsers), then timing. +log_format serverkit_timed '$remote_addr - $remote_user [$time_local] "$request" ' + '$status $body_bytes_sent "$http_referer" "$http_user_agent" ' + 'rt=$request_time urt="$upstream_response_time" ' + 'cs=$upstream_cache_status h=$host'; +""" + +# ==================== COMPRESSION ==================== +# gzip (and brotli when the module is loaded) for every site, as one +# http-level conf.d snippet. Stock configs already set some of these — +# Debian's nginx.conf ships `gzip on;` — and a repeated http-level +# directive is fatal to `nginx -t`, so the snippet only carries the +# directives the running config does not already set (read from `nginx -T`). +COMPRESSION_CONF_NAME = 'serverkit-compression.conf' +# text/html is always compressed by nginx; listing it again only warns. +COMPRESSION_TYPES = ( + 'text/plain text/css text/xml text/javascript application/javascript ' + 'application/json application/xml application/rss+xml ' + 'application/atom+xml image/svg+xml application/wasm ' + 'font/ttf font/otf application/vnd.ms-fontobject' +) +GZIP_DIRECTIVES = ( + ('gzip', 'on'), + ('gzip_vary', 'on'), + ('gzip_proxied', 'any'), + ('gzip_comp_level', '5'), + ('gzip_min_length', '1024'), + ('gzip_types', COMPRESSION_TYPES), +) +BROTLI_DIRECTIVES = ( + ('brotli', 'on'), + ('brotli_comp_level', '5'), + ('brotli_min_length', '1024'), + ('brotli_types', COMPRESSION_TYPES), +) + +# ==================== IMMUTABLE ASSETS ==================== +# Opt-in, proxied sites only: a fingerprinted asset (a hash in its name) +# never changes, so the browser may keep it a year. Off by default because +# the panel cannot know an app's asset layout. The hash must be 8+ chars +# after a '.' or '-' AND contain a digit, so `app-settings.js` is never +# pinned; a hash with no digit is simply not long-cached (the safe miss). +IMMUTABLE_ASSET_PATTERN = ( + r'[.-](?=[A-Za-z0-9_]*[0-9])[A-Za-z0-9_]{8,}' + r'\.(?:js|mjs|css|map|woff2?|ttf|otf|png|jpe?g|gif|svg|webp|avif|ico)$' +) +# One Cache-Control header: `expires` would emit its own max-age header +# next to this one, and clients read either. +IMMUTABLE_ASSET_HEADERS = ''' add_header Cache-Control "public, max-age=31536000, immutable"; +''' + +# ==================== MICRO-CACHE (task #21) ==================== +# Opt-in per-site micro-cache: a very short (10s) full-page cache in front +# of proxied/PHP sites, with hard bypasses for anything personalized. +# +# Design tradeoff — ONE shared zone/path for every opted-in site: nginx +# cache zones must be declared statically in the http context, so a zone +# per site does not scale (and can't be added/removed without touching a +# global file per site). Purge is still per site: the cache key carries +# $host, and purge_micro_cache(hosts) deletes only the files whose KEY +# line names that host. proxy_* and fastcgi_* caches cannot +# share a keys_zone, hence two zones over one base directory. +MICROCACHE_CONF_NAME = 'serverkit-microcache.conf' +MICROCACHE_DIR = '/var/cache/nginx/serverkit-microcache' + +MICROCACHE_ZONE_SNIPPET = '''# ServerKit micro-cache zones (auto-generated; do not edit). +# One shared zone pair serves every site with micro-cache enabled — nginx +# requires cache zones to be declared statically in the http context, so +# per-site zones are not practical. Each site sets its own TTL; a purge +# removes only that site's entries (the cache key carries the host). +proxy_cache_path /var/cache/nginx/serverkit-microcache/proxy levels=1:2 keys_zone=serverkit_microcache:10m max_size=256m inactive=10m use_temp_path=off; +fastcgi_cache_path /var/cache/nginx/serverkit-microcache/fastcgi levels=1:2 keys_zone=serverkit_microcache_php:10m max_size=256m inactive=10m use_temp_path=off; +''' + +# Server-level bypass logic, shared by the proxy and fastcgi variants. +# Cached responses are never stored/served for: non-GET/HEAD requests, +# requests with a query string (safer default), session/auth/cart cookies, +# or admin/login/cart paths. +MICROCACHE_SKIP_BLOCK = ''' # ServerKit micro-cache bypass (never cache personalized responses) + set $sk_skip_cache 0; + if ($request_method !~ ^(GET|HEAD)$) { set $sk_skip_cache 1; } + if ($query_string != "") { set $sk_skip_cache 1; } + if ($http_cookie ~* "wordpress_logged_in_|wp-postpass|woocommerce_cart_hash|woocommerce_items_in_cart|comment_author|PHPSESSID|session|auth") { set $sk_skip_cache 1; } + if ($request_uri ~* "^/(wp-admin|wp-login|admin|login|cart|checkout|my-account)") { set $sk_skip_cache 1; } +''' + +# Page-cache behaviour: +# * the key is `$scheme://$host$request_uri`, so the cache files of one +# site can be found by host and purged alone (the proxy default key is +# `$scheme$proxy_host$request_uri` — the upstream port, not the site); +# * a failing or slow upstream serves the last good copy (use_stale), an +# expired entry is refreshed in the background while the stale copy is +# served, and cache_lock sends one request upstream per missing entry +# instead of a stampede. The zone's inactive=10m bounds how long a stale +# copy survives, so the TTL is capped well below it. +MICROCACHE_TTL_DEFAULT = 10 +MICROCACHE_TTL_MAX = 300 + +MICROCACHE_PROXY_BLOCK = ''' proxy_cache serverkit_microcache; + proxy_cache_key $scheme://$host$request_uri; + proxy_cache_valid 200 301 {ttl}s; + proxy_cache_use_stale error timeout updating http_500 http_502 http_503; + proxy_cache_background_update on; + proxy_cache_lock on; + proxy_no_cache $sk_skip_cache; + add_header X-SK-Cache $upstream_cache_status; +''' + +MICROCACHE_FASTCGI_BLOCK = ''' fastcgi_cache serverkit_microcache_php; + fastcgi_cache_key $scheme://$host$request_uri; + fastcgi_cache_valid 200 301 {ttl}s; + fastcgi_cache_use_stale error timeout updating http_500 http_503; + fastcgi_cache_background_update on; + fastcgi_cache_lock on; + fastcgi_cache_bypass $sk_skip_cache; + fastcgi_no_cache $sk_skip_cache; + add_header X-SK-Cache $upstream_cache_status; +''' + +PRIVATE_URL_MAIN_CONFIG = '''# ServerKit Private URL Routes +# This file is auto-generated. Do not edit manually. +# Generated at: {timestamp} + +{locations} + +# Fallback for unknown slugs under /p/ +location /p/ {{ + return 404; +}} +''' diff --git a/backend/app/services/nginx/validation.py b/backend/app/services/nginx/validation.py new file mode 100644 index 00000000..a5d78c3c --- /dev/null +++ b/backend/app/services/nginx/validation.py @@ -0,0 +1,15 @@ +"""Pure validation shared by rendering and host cache operations.""" +import re + + +def _validate_domain(domain: str) -> bool: + """Validate domain name to prevent nginx config injection.""" + return bool(re.match(r'^(?:[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9])?$', domain, re.IGNORECASE)) + + +def _validate_path(path: str) -> bool: + """Validate filesystem path for nginx config.""" + # Block path traversal and special characters + if '..' in path or '\n' in path or '\r' in path or ';' in path: + return False + return bool(re.match(r'^/[a-zA-Z0-9/_\-\.]+$', path)) diff --git a/backend/app/services/nginx_service.py b/backend/app/services/nginx_service.py index 570fcd73..f0376e43 100644 --- a/backend/app/services/nginx_service.py +++ b/backend/app/services/nginx_service.py @@ -8,6 +8,9 @@ from pathlib import Path from app.utils.system import (ServiceControl, is_command_available, run_privileged, write_privileged_file) +from app.services.nginx import templates, rendering, compression +from app.services.nginx.validation import _validate_domain, _validate_path # compatibility exports + logger = logging.getLogger(__name__) @@ -24,19 +27,6 @@ def _auto_capture_vhost(name, action): return auto_capture('nginx_vhost', name, action) -def _validate_domain(domain: str) -> bool: - """Validate domain name to prevent nginx config injection.""" - return bool(re.match(r'^(?:[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9])?$', domain, re.IGNORECASE)) - - -def _validate_path(path: str) -> bool: - """Validate filesystem path for nginx config.""" - # Block path traversal and special characters - if '..' in path or '\n' in path or '\r' in path or ';' in path: - return False - return bool(re.match(r'^/[a-zA-Z0-9/_\-\.]+$', path)) - - class NginxService: """Service for Nginx configuration management.""" @@ -47,462 +37,67 @@ class NginxService: NGINX_BIN = os.environ.get('NGINX_BIN', '/usr/sbin/nginx') LOCATIONS_DIR = os.path.join(NGINX_CONF_DIR, 'serverkit-locations') # Per-site log directory. Must stay in sync with the access_log/error_log - # paths hard-coded in the site templates below. site_access_log_path() is the + # paths hard-coded in nginx/templates.py. site_access_log_path() is the # single source of truth consumers should use (e.g. the fail2ban jail layer # watches this exact file), so the path can never drift from what nginx writes. LOG_DIR = '/var/log/nginx' - # Templates - PHP_SITE_TEMPLATE = '''server {{ - listen 80; - listen [::]:80; - server_name {domains}; + # Compatibility aliases; configuration text is owned by nginx/templates.py. + PHP_SITE_TEMPLATE = templates.PHP_SITE_TEMPLATE + PYTHON_SITE_TEMPLATE = templates.PYTHON_SITE_TEMPLATE + STATIC_SITE_TEMPLATE = templates.STATIC_SITE_TEMPLATE + DOCKER_SITE_TEMPLATE = templates.DOCKER_SITE_TEMPLATE + WORDPRESS_RATE_LIMIT_CONF_NAME = templates.WORDPRESS_RATE_LIMIT_CONF_NAME + WORDPRESS_RATE_LIMIT_ZONE_SNIPPET = templates.WORDPRESS_RATE_LIMIT_ZONE_SNIPPET + WORDPRESS_PROTECTION_BLOCK = templates.WORDPRESS_PROTECTION_BLOCK + REMOTE_UPSTREAM_TEMPLATE = templates.REMOTE_UPSTREAM_TEMPLATE + SSL_BLOCK = templates.SSL_BLOCK + SSL_REDIRECT_TEMPLATE = templates.SSL_REDIRECT_TEMPLATE + PRIVATE_URL_CONFIG_NAME = templates.PRIVATE_URL_CONFIG_NAME + GITEA_CONFIG_NAME = templates.GITEA_CONFIG_NAME + WORDPRESS_CONFIG_NAME = templates.WORDPRESS_CONFIG_NAME + GITEA_LOCATION_TEMPLATE = templates.GITEA_LOCATION_TEMPLATE + WORDPRESS_LOCATION_TEMPLATE = templates.WORDPRESS_LOCATION_TEMPLATE + PRIVATE_URL_LOCATION_TEMPLATE = templates.PRIVATE_URL_LOCATION_TEMPLATE + TIMED_LOG_FORMAT = templates.TIMED_LOG_FORMAT + TIMED_LOG_CONF_NAME = templates.TIMED_LOG_CONF_NAME + TIMED_LOG_FORMAT_SNIPPET = templates.TIMED_LOG_FORMAT_SNIPPET + COMPRESSION_CONF_NAME = templates.COMPRESSION_CONF_NAME + COMPRESSION_TYPES = templates.COMPRESSION_TYPES + GZIP_DIRECTIVES = templates.GZIP_DIRECTIVES + BROTLI_DIRECTIVES = templates.BROTLI_DIRECTIVES + IMMUTABLE_ASSET_PATTERN = templates.IMMUTABLE_ASSET_PATTERN + IMMUTABLE_ASSET_HEADERS = templates.IMMUTABLE_ASSET_HEADERS + MICROCACHE_CONF_NAME = templates.MICROCACHE_CONF_NAME + MICROCACHE_DIR = templates.MICROCACHE_DIR + MICROCACHE_ZONE_SNIPPET = templates.MICROCACHE_ZONE_SNIPPET + MICROCACHE_SKIP_BLOCK = templates.MICROCACHE_SKIP_BLOCK + MICROCACHE_TTL_DEFAULT = templates.MICROCACHE_TTL_DEFAULT + MICROCACHE_TTL_MAX = templates.MICROCACHE_TTL_MAX + MICROCACHE_PROXY_BLOCK = templates.MICROCACHE_PROXY_BLOCK + MICROCACHE_FASTCGI_BLOCK = templates.MICROCACHE_FASTCGI_BLOCK + PRIVATE_URL_MAIN_CONFIG = templates.PRIVATE_URL_MAIN_CONFIG - root {root_path}; - index index.php index.html index.htm; - - access_log /var/log/nginx/{name}.access.log serverkit_timed; - error_log /var/log/nginx/{name}.error.log; - - location / {{ - try_files $uri $uri/ /index.php?$query_string; - }} - - location ~ \\.php$ {{ - fastcgi_pass unix:/run/php/php{php_version}-fpm.sock; - fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; - include fastcgi_params; - fastcgi_intercept_errors on; - fastcgi_buffer_size 16k; - fastcgi_buffers 4 16k; - }} - - location ~ /\\.ht {{ - deny all; - }} - - location = /favicon.ico {{ - log_not_found off; - access_log off; - }} - - location = /robots.txt {{ - log_not_found off; - access_log off; - allow all; - }} - - location ~* \\.(css|gif|ico|jpeg|jpg|js|png|svg|woff|woff2)$ {{ - expires 1y; - log_not_found off; - }} -}} -''' - - PYTHON_SITE_TEMPLATE = '''server {{ - listen 80; - listen [::]:80; - server_name {domains}; - - access_log /var/log/nginx/{name}.access.log serverkit_timed; - error_log /var/log/nginx/{name}.error.log; - - location / {{ - proxy_pass http://127.0.0.1:{port}; - proxy_http_version 1.1; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection 'upgrade'; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_cache_bypass $http_upgrade; - proxy_read_timeout 86400; - }} - - location /static {{ - alias {root_path}/static; - expires 1y; - }} -}} -''' - - STATIC_SITE_TEMPLATE = '''server {{ - listen 80; - listen [::]:80; - server_name {domains}; - - root {root_path}; - index index.html index.htm; - - access_log /var/log/nginx/{name}.access.log serverkit_timed; - error_log /var/log/nginx/{name}.error.log; - - location / {{ - try_files $uri $uri/ =404; - }} - - location ~* \\.(css|gif|ico|jpeg|jpg|js|png|svg|woff|woff2)$ {{ - expires 1y; - log_not_found off; - }} -}} -''' - - # Docker reverse proxy template (for containerized apps) - DOCKER_SITE_TEMPLATE = '''server {{ - listen 80; - listen [::]:80; - server_name {domains}; - - access_log /var/log/nginx/{name}.access.log serverkit_timed; - error_log /var/log/nginx/{name}.error.log; - - location / {{ - proxy_pass http://127.0.0.1:{port}; - proxy_http_version 1.1; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection 'upgrade'; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_cache_bypass $http_upgrade; - proxy_read_timeout 86400; - proxy_connect_timeout 60; - proxy_send_timeout 60; - }} -}} -''' - - # WordPress authentication endpoints receive a dedicated request limit in - # published reverse-proxy vhosts. The zones are shared across vhosts, while - # the key includes server_name so traffic to one site cannot consume - # another site's allowance. - WORDPRESS_RATE_LIMIT_CONF_NAME = 'serverkit-wordpress-rate-limit.conf' - WORDPRESS_RATE_LIMIT_ZONE_SNIPPET = '''# ServerKit WordPress request-limit zones (auto-generated; do not edit). -limit_req_zone $server_name$binary_remote_addr zone=serverkit_wp_login:10m rate=10r/m; -limit_req_zone $server_name$binary_remote_addr zone=serverkit_wp_xmlrpc:10m rate=30r/m; -''' - - WORDPRESS_PROTECTION_BLOCK = ''' # ServerKit WordPress brute-force protection - location = /wp-login.php {{ - limit_req zone=serverkit_wp_login burst=10 nodelay; - limit_req_status 429; - proxy_pass http://127.0.0.1:{port}; - proxy_http_version 1.1; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_read_timeout 86400; - proxy_connect_timeout 60; - proxy_send_timeout 60; - }} - - location = /xmlrpc.php {{ - limit_req zone=serverkit_wp_xmlrpc burst=20 nodelay; - limit_req_status 429; - proxy_pass http://127.0.0.1:{port}; - proxy_http_version 1.1; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_read_timeout 86400; - proxy_connect_timeout 60; - proxy_send_timeout 60; - }} - -''' - - # Reverse proxy to a service reached over a WireGuard tunnel (roadmap - # #12). The upstream is a peer's WG IP:port; the private agent forwards - # it to the real service. proxy_buffering off keeps media/streaming - # (e.g. Jellyfin) responsive. - REMOTE_UPSTREAM_TEMPLATE = '''server {{ - listen 80; - listen [::]:80; - server_name {domains}; - - access_log /var/log/nginx/{name}.access.log serverkit_timed; - error_log /var/log/nginx/{name}.error.log; - - location / {{ - proxy_pass http://{upstream}; - proxy_http_version 1.1; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection 'upgrade'; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_cache_bypass $http_upgrade; - proxy_buffering off; - proxy_read_timeout 86400; - proxy_connect_timeout 60; - proxy_send_timeout 60; - }} -}} -''' - - SSL_BLOCK = ''' - listen 443 ssl http2; - listen [::]:443 ssl http2; - - ssl_certificate {ssl_cert}; - ssl_certificate_key {ssl_key}; - ssl_session_timeout 1d; - ssl_session_cache shared:SSL:50m; - ssl_session_tickets off; - - ssl_protocols TLSv1.2 TLSv1.3; - ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384; - ssl_prefer_server_ciphers off; - ssl_ecdh_curve X25519:secp384r1; - - # HSTS: 2 years, all subdomains, preload-eligible. Submit the domain at - # https://hstspreload.org to get onto the browser preload list (this is what - # protects first-time visitors from an initial-request MITM downgrade). - add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always; - - # Baseline response-header hardening. These are safe for reverse-proxied apps; - # the CSP is deliberately permissive so it does not break managed apps while - # still satisfying "a CSP is present" and blocking cross-origin framing. - # Tighten the CSP per-app when the upstream can support a stricter policy. - add_header X-Content-Type-Options "nosniff" always; - add_header X-Frame-Options "SAMEORIGIN" always; - add_header Referrer-Policy "strict-origin-when-cross-origin" always; - add_header Content-Security-Policy "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: blob: https:; frame-ancestors 'self'; upgrade-insecure-requests" always; -''' - - SSL_REDIRECT_TEMPLATE = '''server {{ - listen 80; - listen [::]:80; - server_name {domains}; - return 301 https://$server_name$request_uri; -}} -''' - - # Private URL routing templates - PRIVATE_URL_CONFIG_NAME = 'serverkit-private-urls' - GITEA_CONFIG_NAME = 'serverkit-gitea' - WORDPRESS_CONFIG_NAME = 'serverkit-wordpress' - - # Gitea location block for /gitea path (included inside main server block) - GITEA_LOCATION_TEMPLATE = '''# Gitea at /gitea path -location /gitea/ {{ - proxy_pass http://127.0.0.1:{port}/; - proxy_http_version 1.1; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection "upgrade"; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_set_header X-Forwarded-Host $host; - proxy_cache_bypass $http_upgrade; - proxy_read_timeout 86400; - proxy_connect_timeout 60; - proxy_send_timeout 60; - - # Required for Gitea WebSocket connections - proxy_buffering off; - client_max_body_size 100M; -}} - -# Handle /gitea without trailing slash -location = /gitea {{ - return 301 /gitea/; -}} -''' - - # WordPress location block for /wordpress path (included inside main server block) - WORDPRESS_LOCATION_TEMPLATE = '''# WordPress at /wordpress path -location /wordpress/ {{ - proxy_pass http://127.0.0.1:{port}/; - proxy_http_version 1.1; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_set_header X-Forwarded-Host $host; - proxy_cache_bypass $http_upgrade; - proxy_read_timeout 300; - proxy_connect_timeout 60; - proxy_send_timeout 60; - - # WordPress file uploads - client_max_body_size 256M; -}} - -# Handle /wordpress without trailing slash -location = /wordpress {{ - return 301 /wordpress/; -}} -''' - - PRIVATE_URL_LOCATION_TEMPLATE = ''' # Private URL: /p/{slug} - location /p/{slug}/ {{ - proxy_pass http://127.0.0.1:{port}/; - proxy_http_version 1.1; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection 'upgrade'; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_set_header X-Private-URL {slug}; - proxy_cache_bypass $http_upgrade; - proxy_read_timeout 86400; - }} - - # Also handle without trailing slash - location = /p/{slug} {{ - return 301 /p/{slug}/; - }} -''' - - # ==================== TIMED ACCESS LOG ==================== - # Every vhost ServerKit writes logs in this format. The combined fields come - # first, unchanged, so every existing combined-format reader (bandwidth - # accounting, the fail2ban `^ -` filters) keeps matching; the timing - # fields are appended after them. The app id is the log file itself - # (/var/log/nginx/.access.log) — a per-vhost `set` variable would make - # `nginx -t` warn on every server block that never sets it. - TIMED_LOG_FORMAT = 'serverkit_timed' - TIMED_LOG_CONF_NAME = 'serverkit-log-format.conf' - TIMED_LOG_FORMAT_SNIPPET = """# ServerKit timed access-log format (auto-generated; do not edit). -# Combined fields first (compatible with combined parsers), then timing. -log_format serverkit_timed '$remote_addr - $remote_user [$time_local] "$request" ' - '$status $body_bytes_sent "$http_referer" "$http_user_agent" ' - 'rt=$request_time urt="$upstream_response_time" ' - 'cs=$upstream_cache_status h=$host'; -""" - - # ==================== COMPRESSION ==================== - # gzip (and brotli when the module is loaded) for every site, as one - # http-level conf.d snippet. Stock configs already set some of these — - # Debian's nginx.conf ships `gzip on;` — and a repeated http-level - # directive is fatal to `nginx -t`, so the snippet only carries the - # directives the running config does not already set (read from `nginx -T`). - COMPRESSION_CONF_NAME = 'serverkit-compression.conf' - # text/html is always compressed by nginx; listing it again only warns. - COMPRESSION_TYPES = ( - 'text/plain text/css text/xml text/javascript application/javascript ' - 'application/json application/xml application/rss+xml ' - 'application/atom+xml image/svg+xml application/wasm ' - 'font/ttf font/otf application/vnd.ms-fontobject' - ) - GZIP_DIRECTIVES = ( - ('gzip', 'on'), - ('gzip_vary', 'on'), - ('gzip_proxied', 'any'), - ('gzip_comp_level', '5'), - ('gzip_min_length', '1024'), - ('gzip_types', COMPRESSION_TYPES), - ) - BROTLI_DIRECTIVES = ( - ('brotli', 'on'), - ('brotli_comp_level', '5'), - ('brotli_min_length', '1024'), - ('brotli_types', COMPRESSION_TYPES), - ) - - # ==================== IMMUTABLE ASSETS ==================== - # Opt-in, proxied sites only: a fingerprinted asset (a hash in its name) - # never changes, so the browser may keep it a year. Off by default because - # the panel cannot know an app's asset layout. The hash must be 8+ chars - # after a '.' or '-' AND contain a digit, so `app-settings.js` is never - # pinned; a hash with no digit is simply not long-cached (the safe miss). - IMMUTABLE_ASSET_PATTERN = ( - r'[.-](?=[A-Za-z0-9_]*[0-9])[A-Za-z0-9_]{8,}' - r'\.(?:js|mjs|css|map|woff2?|ttf|otf|png|jpe?g|gif|svg|webp|avif|ico)$' - ) - # One Cache-Control header: `expires` would emit its own max-age header - # next to this one, and clients read either. - IMMUTABLE_ASSET_HEADERS = ''' add_header Cache-Control "public, max-age=31536000, immutable"; -''' - - # ==================== MICRO-CACHE (task #21) ==================== - # Opt-in per-site micro-cache: a very short (10s) full-page cache in front - # of proxied/PHP sites, with hard bypasses for anything personalized. - # - # Design tradeoff — ONE shared zone/path for every opted-in site: nginx - # cache zones must be declared statically in the http context, so a zone - # per site does not scale (and can't be added/removed without touching a - # global file per site). Purge is still per site: the cache key carries - # $host, and purge_micro_cache(hosts) deletes only the files whose KEY - # line names that host. proxy_* and fastcgi_* caches cannot - # share a keys_zone, hence two zones over one base directory. - MICROCACHE_CONF_NAME = 'serverkit-microcache.conf' - MICROCACHE_DIR = '/var/cache/nginx/serverkit-microcache' - - MICROCACHE_ZONE_SNIPPET = '''# ServerKit micro-cache zones (auto-generated; do not edit). -# One shared zone pair serves every site with micro-cache enabled — nginx -# requires cache zones to be declared statically in the http context, so -# per-site zones are not practical. Each site sets its own TTL; a purge -# removes only that site's entries (the cache key carries the host). -proxy_cache_path /var/cache/nginx/serverkit-microcache/proxy levels=1:2 keys_zone=serverkit_microcache:10m max_size=256m inactive=10m use_temp_path=off; -fastcgi_cache_path /var/cache/nginx/serverkit-microcache/fastcgi levels=1:2 keys_zone=serverkit_microcache_php:10m max_size=256m inactive=10m use_temp_path=off; -''' - - # Server-level bypass logic, shared by the proxy and fastcgi variants. - # Cached responses are never stored/served for: non-GET/HEAD requests, - # requests with a query string (safer default), session/auth/cart cookies, - # or admin/login/cart paths. - MICROCACHE_SKIP_BLOCK = ''' # ServerKit micro-cache bypass (never cache personalized responses) - set $sk_skip_cache 0; - if ($request_method !~ ^(GET|HEAD)$) { set $sk_skip_cache 1; } - if ($query_string != "") { set $sk_skip_cache 1; } - if ($http_cookie ~* "wordpress_logged_in_|wp-postpass|woocommerce_cart_hash|woocommerce_items_in_cart|comment_author|PHPSESSID|session|auth") { set $sk_skip_cache 1; } - if ($request_uri ~* "^/(wp-admin|wp-login|admin|login|cart|checkout|my-account)") { set $sk_skip_cache 1; } -''' - - # Page-cache behaviour: - # * the key is `$scheme://$host$request_uri`, so the cache files of one - # site can be found by host and purged alone (the proxy default key is - # `$scheme$proxy_host$request_uri` — the upstream port, not the site); - # * a failing or slow upstream serves the last good copy (use_stale), an - # expired entry is refreshed in the background while the stale copy is - # served, and cache_lock sends one request upstream per missing entry - # instead of a stampede. The zone's inactive=10m bounds how long a stale - # copy survives, so the TTL is capped well below it. - MICROCACHE_TTL_DEFAULT = 10 - MICROCACHE_TTL_MAX = 300 - - MICROCACHE_PROXY_BLOCK = ''' proxy_cache serverkit_microcache; - proxy_cache_key $scheme://$host$request_uri; - proxy_cache_valid 200 301 {ttl}s; - proxy_cache_use_stale error timeout updating http_500 http_502 http_503; - proxy_cache_background_update on; - proxy_cache_lock on; - proxy_no_cache $sk_skip_cache; - add_header X-SK-Cache $upstream_cache_status; -''' - - MICROCACHE_FASTCGI_BLOCK = ''' fastcgi_cache serverkit_microcache_php; - fastcgi_cache_key $scheme://$host$request_uri; - fastcgi_cache_valid 200 301 {ttl}s; - fastcgi_cache_use_stale error timeout updating http_500 http_503; - fastcgi_cache_background_update on; - fastcgi_cache_lock on; - fastcgi_cache_bypass $sk_skip_cache; - fastcgi_no_cache $sk_skip_cache; - add_header X-SK-Cache $upstream_cache_status; -''' - - PRIVATE_URL_MAIN_CONFIG = '''# ServerKit Private URL Routes -# This file is auto-generated. Do not edit manually. -# Generated at: {timestamp} - -{locations} - -# Fallback for unknown slugs under /p/ -location /p/ {{ - return 404; -}} -''' + @classmethod + def _render_settings(cls): + """Pass only template values into the pure rendering layer.""" + return rendering.RenderSettings( + DOCKER_SITE_TEMPLATE=cls.DOCKER_SITE_TEMPLATE, + IMMUTABLE_ASSET_HEADERS=cls.IMMUTABLE_ASSET_HEADERS, + IMMUTABLE_ASSET_PATTERN=cls.IMMUTABLE_ASSET_PATTERN, + MICROCACHE_FASTCGI_BLOCK=cls.MICROCACHE_FASTCGI_BLOCK, + MICROCACHE_PROXY_BLOCK=cls.MICROCACHE_PROXY_BLOCK, + MICROCACHE_SKIP_BLOCK=cls.MICROCACHE_SKIP_BLOCK, + MICROCACHE_TTL_DEFAULT=cls.MICROCACHE_TTL_DEFAULT, + MICROCACHE_TTL_MAX=cls.MICROCACHE_TTL_MAX, + PHP_SITE_TEMPLATE=cls.PHP_SITE_TEMPLATE, + PYTHON_SITE_TEMPLATE=cls.PYTHON_SITE_TEMPLATE, + REMOTE_UPSTREAM_TEMPLATE=cls.REMOTE_UPSTREAM_TEMPLATE, + SSL_BLOCK=cls.SSL_BLOCK, + SSL_REDIRECT_TEMPLATE=cls.SSL_REDIRECT_TEMPLATE, + STATIC_SITE_TEMPLATE=cls.STATIC_SITE_TEMPLATE, + WORDPRESS_PROTECTION_BLOCK=cls.WORDPRESS_PROTECTION_BLOCK, + ) @classmethod def test_config(cls) -> Dict: @@ -646,101 +241,17 @@ location /p/ {{ micro_cache_ttl: Optional[int] = None, immutable_assets: bool = False, wordpress_protection: bool = False) -> Dict: - """Render the vhost config for a site to a string — no side effects. - - This is the exact template pipeline :meth:`create_site` writes to disk; - it is exposed separately so callers (e.g. drift detection) can compute - the expected on-disk content without touching the filesystem. - Returns ``{'success': True, 'config': str}`` or - ``{'success': False, 'error': msg}``. - """ - if not domains: - return {'success': False, 'error': 'At least one domain is required'} - - # Validate all domains - for domain in domains: - if domain == '_': - return {'success': False, 'error': 'Wildcard server_name "_" is reserved for the ServerKit panel'} - if not _validate_domain(domain): - return {'success': False, 'error': f'Invalid domain name: {domain}'} - - # Validate root_path if provided - if root_path and not _validate_path(root_path): - return {'success': False, 'error': f'Invalid root path: {root_path}'} - - domains_str = ' '.join(domains) - - # Select template based on app type - if app_type in ['php', 'wordpress']: - config = cls.PHP_SITE_TEMPLATE.format( - name=name, - domains=domains_str, - root_path=root_path, - php_version=php_version - ) - elif app_type in ['flask', 'django', 'python']: - if not port: - return {'success': False, 'error': 'Python services need a port'} - config = cls.PYTHON_SITE_TEMPLATE.format( - name=name, - domains=domains_str, - root_path=root_path, - port=port - ) - elif app_type == 'docker': - if not port: - return {'success': False, 'error': 'Docker services need a port'} - config = cls.DOCKER_SITE_TEMPLATE.format( - name=name, - domains=domains_str, - port=port - ) - elif app_type == 'remote': - if not upstream: - return {'success': False, 'error': 'Services on remote servers need an upstream (host:port)'} - config = cls.REMOTE_UPSTREAM_TEMPLATE.format( - name=name, - domains=domains_str, - upstream=upstream, - ) - elif app_type == 'static': - config = cls.STATIC_SITE_TEMPLATE.format( - name=name, - domains=domains_str, - root_path=root_path - ) - else: - return {'success': False, 'error': f'Unknown service type: {app_type}'} - - if immutable_assets: - config = cls._with_immutable_assets(config, app_type) - - if micro_cache: - # Inject before the SSL wrap so the redirect server block (which - # also carries a server_name line) never receives cache directives. - config = cls._with_micro_cache(config, app_type, micro_cache_ttl) - - if wordpress_protection: - if app_type != 'docker' or not port: - return { - 'success': False, - 'error': 'WordPress protection requires a Docker proxy port', - } - config = cls._with_wordpress_protection(config, port) - - if ssl_cert and ssl_key: - config = cls._with_ssl(config, domains_str, ssl_cert, ssl_key) - - return {'success': True, 'config': config} + """Compatibility entry point for the pure configuration layer.""" + return rendering.render_site_config( + name, app_type, domains, root_path, port, php_version, ssl_cert, + ssl_key, upstream, micro_cache, micro_cache_ttl, immutable_assets, + wordpress_protection, settings=cls._render_settings()) @classmethod def _with_wordpress_protection(cls, config: str, port: int) -> str: - """Add exact-match throttling locations before the catch-all proxy.""" - anchor = ' location / {\n' - if anchor not in config: - return config - block = cls.WORDPRESS_PROTECTION_BLOCK.format(port=port) - return config.replace(anchor, block + anchor, 1) + """Compatibility entry point for the pure configuration layer.""" + return rendering._with_wordpress_protection( + config, port, settings=cls._render_settings()) @classmethod def ensure_wordpress_rate_limit_zones(cls) -> Dict: @@ -777,69 +288,22 @@ location /p/ {{ @classmethod def _with_immutable_assets(cls, config: str, app_type: str) -> str: - """Add a regex location for fingerprinted assets to a proxied vhost: - the same proxying as ``location /`` plus a one-year immutable cache. - Appended after ``location /`` (a matching regex location wins over the - ``/`` prefix wherever it sits) so the micro-cache injection still - anchors on the real ``location /``.""" - if (app_type or '').lower() not in ('flask', 'django', 'python', 'docker', 'remote'): - return config - match = re.search(r'^ location / \{\n(.*?)^ \}\n', config, re.MULTILINE | re.DOTALL) - if not match: - return config - block = ('\n # ServerKit: fingerprinted assets never change\n' - f' location ~* "{cls.IMMUTABLE_ASSET_PATTERN}" {{\n' - + match.group(1) + cls.IMMUTABLE_ASSET_HEADERS + ' }\n') - return config[:match.end()] + block + config[match.end():] + """Compatibility entry point for the pure configuration layer.""" + return rendering._with_immutable_assets( + config, app_type, settings=cls._render_settings()) @classmethod def _with_micro_cache(cls, config: str, app_type: str, ttl: Optional[int] = None) -> str: - """Inject the shared-zone micro-cache directives into a rendered vhost. - - fastcgi_cache for PHP-FPM-served sites, proxy_cache for reverse-proxied - ones; static sites are a no-op (files already come straight off disk). - Scheme-agnostic — nothing here depends on HTTP vs HTTPS. The referenced - zones are declared once in conf.d by :meth:`ensure_cache_zone`. - """ - t = (app_type or '').lower() - ttl = cls.clamp_micro_cache_ttl(ttl) - if t in ('php', 'wordpress'): - anchor = ' include fastcgi_params;\n' - if anchor not in config: - return config - config = config.replace( - anchor, anchor + cls.MICROCACHE_FASTCGI_BLOCK.format(ttl=ttl), 1) - elif t in ('flask', 'django', 'python', 'docker', 'remote'): - # proxy_cache_bypass may only be declared once per location, so - # fold $sk_skip_cache into the template's existing $http_upgrade - # bypass instead of adding a duplicate directive. - anchor = ' proxy_cache_bypass $http_upgrade;\n' - if anchor not in config: - return config - config = config.replace( - anchor, - ' proxy_cache_bypass $sk_skip_cache $http_upgrade;\n' - + cls.MICROCACHE_PROXY_BLOCK.format(ttl=ttl), - 1, - ) - else: - return config - - # Server-level $sk_skip_cache logic, right after server_name. - match = re.search(r'^( server_name [^;]+;\n)', config, re.MULTILINE) - if match: - config = config.replace( - match.group(1), match.group(1) + '\n' + cls.MICROCACHE_SKIP_BLOCK, 1) - return config + """Compatibility entry point for the pure configuration layer.""" + return rendering._with_micro_cache( + config, app_type, ttl, settings=cls._render_settings()) @classmethod def clamp_micro_cache_ttl(cls, ttl) -> int: - """A stored TTL as the seconds the vhost uses: unset → the 10s - default, anything else clamped to 1..MICROCACHE_TTL_MAX.""" - if ttl in (None, ''): - return cls.MICROCACHE_TTL_DEFAULT - return max(1, min(int(ttl), cls.MICROCACHE_TTL_MAX)) + """Compatibility entry point for the pure configuration layer.""" + return rendering.clamp_micro_cache_ttl( + ttl, settings=cls._render_settings()) @classmethod def ensure_cache_zone(cls) -> Dict: @@ -891,62 +355,17 @@ location /p/ {{ @classmethod def _http_level_directives(cls, dump: str, skip_file: str) -> set: - """Directive names set at http level in an ``nginx -T`` dump. - - ``nginx -T`` prints each file after a ``# configuration file :`` - header. In the main nginx.conf, http level is depth 1 inside - ``http {}``; every other file is included from the http block (conf.d) - or a server (sites), so its depth-0 directives are the http-level - ones. ``skip_file`` (our own snippet) is ignored so a rewrite never - mistakes its own lines for someone else's. - """ - found = set() - current = None - depth = 0 - in_http = False - for raw in dump.splitlines(): - header = re.match(r'^# configuration file (.+):$', raw.strip()) - if header: - current = header.group(1) - depth = 0 - in_http = False - continue - if current is None or current == skip_file: - continue - line = raw.split('#', 1)[0].strip() - if not line: - continue - is_main = current.endswith('/nginx.conf') - http_level = (depth == 1 and in_http) if is_main else depth == 0 - name = line.split(None, 1)[0].rstrip(';{') - if http_level and line.endswith(';'): - found.add(name) - if is_main and depth == 0 and name == 'http' and '{' in line: - in_http = True - depth += line.count('{') - line.count('}') - if is_main and depth == 0: - in_http = False - return found + """Compatibility entry point for the pure configuration layer.""" + return compression._http_level_directives( + dump, skip_file) @classmethod def render_compression_snippet(cls, dump: str, conf_path: str, nginx_v: str = '') -> str: - """The snippet for this box. When the running config already sets - everything it is comments only: still written, so the "already - handled" check stays a file-exists test instead of an ``nginx -T`` - on every vhost write.""" - present = cls._http_level_directives(dump, conf_path) - brotli = ('ngx_http_brotli_filter_module' in dump - or 'brotli' in (nginx_v or '').lower()) - wanted = list(cls.GZIP_DIRECTIVES) - if brotli: - wanted += list(cls.BROTLI_DIRECTIVES) - lines = [f'{name} {value};' for name, value in wanted if name not in present] - kept = sorted(name for name, _ in wanted if name in present) - header = ['# ServerKit compression (auto-generated; do not edit).'] - if kept: - header.append('# Already set elsewhere, left alone: ' + ', '.join(kept)) - return '\n'.join(header + lines) + '\n' + """Compatibility entry point for the pure configuration layer.""" + return compression.render_compression_snippet( + dump, conf_path, nginx_v, gzip_directives=cls.GZIP_DIRECTIVES, + brotli_directives=cls.BROTLI_DIRECTIVES) @classmethod def ensure_compression(cls) -> Dict: @@ -1087,17 +506,9 @@ location /p/ {{ @classmethod def _with_ssl(cls, http_config: str, domains: str, ssl_cert: str, ssl_key: str) -> str: - """Turn an HTTP server block into HTTPS: swap the :80 listens for the TLS - block (so the existing server serves 443) and prepend an HTTP->HTTPS - redirect. Idempotent because create_site regenerates the whole file.""" - ssl_block = cls.SSL_BLOCK.format(ssl_cert=ssl_cert, ssl_key=ssl_key) - https_config = http_config.replace( - ' listen 80;\n listen [::]:80;', - ssl_block.strip('\n'), - 1, - ) - redirect = cls.SSL_REDIRECT_TEMPLATE.format(domains=domains) - return redirect + '\n' + https_config + """Compatibility entry point for the pure configuration layer.""" + return rendering._with_ssl( + http_config, domains, ssl_cert, ssl_key, settings=cls._render_settings()) @classmethod def site_access_log_path(cls, name: str) -> str: From 9c934cb7a6471512bc1de13c522e55a5eb3f7d5d Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 05:36:59 -0400 Subject: [PATCH 13/34] test: enforce pure nginx configuration boundaries --- backend/tests/test_nginx_boundaries.py | 139 +++++++++++++++++++++++++ docs/CORE_BOUNDARIES.md | 35 +++++++ 2 files changed, 174 insertions(+) create mode 100644 backend/tests/test_nginx_boundaries.py diff --git a/backend/tests/test_nginx_boundaries.py b/backend/tests/test_nginx_boundaries.py new file mode 100644 index 00000000..6174486d --- /dev/null +++ b/backend/tests/test_nginx_boundaries.py @@ -0,0 +1,139 @@ +"""Keep Nginx text generation independent of the host and the Flask app.""" +import ast +from dataclasses import replace +from pathlib import Path + +import pytest + +from app.services.nginx import compression, rendering, templates +from app.services.nginx_service import NginxService + + +ROOT = Path(__file__).parents[1] / 'app' / 'services' +ALLOWED_IMPORTS = { + '__init__.py': set(), + 'templates.py': set(), + 'validation.py': {'re'}, + 'compression.py': {'re', '.templates'}, + 'rendering.py': {'re', 'dataclasses', 'typing', '.templates', '.validation'}, +} +RENDER_METHODS = { + 'render_site_config', '_with_wordpress_protection', '_with_immutable_assets', + '_with_micro_cache', 'clamp_micro_cache_ttl', '_with_ssl', + '_http_level_directives', 'render_compression_snippet', +} + + +def boundary_errors(filename, source): + """Deliberately narrow dependency allowlist for this pure package.""" + tree = ast.parse(source) + errors = [] + for node in ast.walk(tree): + imports = [] + if isinstance(node, ast.Import): + imports = [alias.name for alias in node.names] + elif isinstance(node, ast.ImportFrom): + prefix = '.' * node.level + imports = ([prefix + node.module] if node.module else + [prefix + alias.name for alias in node.names]) + for module in imports: + if module not in ALLOWED_IMPORTS[filename]: + errors.append(f'forbidden dependency: {module}') + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name): + if node.func.id in {'open', 'exec', 'eval', '__import__', 'globals', 'locals'}: + errors.append(f'forbidden effect: {node.func.id}') + if filename == 'templates.py': + for node in tree.body: + if not (isinstance(node, ast.Assign) or + isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant)): + errors.append('templates must contain only data') + if any(isinstance(node, ast.Call) for node in ast.walk(tree)): + errors.append('templates must not execute calls') + return errors + + +def test_configuration_package_has_only_declared_pure_dependencies(): + paths = sorted((ROOT / 'nginx').glob('*.py')) + assert {path.name for path in paths} == set(ALLOWED_IMPORTS) + for path in paths: + source = path.read_text(encoding='utf-8') + assert boundary_errors(path.name, source) == [], path + ceiling = 500 if path.name == 'templates.py' else 300 + assert len(source.splitlines()) <= ceiling, f'Split responsibilities in {path}' + + +@pytest.mark.parametrize('filename,source', [ + ('rendering.py', 'from app.services.nginx_service import NginxService'), + ('rendering.py', 'from flask import current_app'), + ('rendering.py', 'import os'), + ('compression.py', 'import subprocess'), + ('validation.py', 'from pathlib import Path'), + ('rendering.py', "open('/etc/nginx/nginx.conf').read()"), + ('rendering.py', "__import__('subprocess')"), + ('templates.py', 'def render():\n return "server {}"'), + ('templates.py', 'CONFIG = str(123)'), +]) +def test_boundary_checker_rejects_host_dependencies_and_active_templates(filename, source): + assert boundary_errors(filename, source) + + +def test_service_keeps_rendering_as_delegation(): + source = (ROOT / 'nginx_service.py').read_text(encoding='utf-8') + service = next(node for node in ast.parse(source).body if isinstance(node, ast.ClassDef)) + methods = {node.name: node for node in service.body if isinstance(node, ast.FunctionDef)} + for name in RENDER_METHODS: + body = methods[name].body + if isinstance(body[0], ast.Expr): + body = body[1:] # docstring + assert len(body) == 1 and isinstance(body[0], ast.Return), name + call = body[0].value + assert isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute), name + assert call.func.value.id in {'rendering', 'compression'}, name + assert call.func.attr == name + # Prevent copying templates back into the host service. + for name in vars(templates): + if name.isupper(): + assignment = next(node for node in service.body + if isinstance(node, ast.Assign) + and node.targets[0].id == name) + assert isinstance(assignment.value, ast.Attribute), name + assert assignment.value.value.id == 'templates', name + nonblank = sum(bool(line.strip()) for line in source.splitlines()) + assert nonblank <= 1050, 'Extract additional host concerns instead of growing this service' + + +def test_render_settings_are_values_and_preserve_service_overrides(monkeypatch): + monkeypatch.setattr(NginxService, 'MICROCACHE_TTL_DEFAULT', 23) + monkeypatch.setattr(NginxService, 'MICROCACHE_TTL_MAX', 40) + assert NginxService.clamp_micro_cache_ttl(None) == 23 + assert NginxService.clamp_micro_cache_ttl(100) == 40 + result = NginxService.render_site_config( + 'shop', 'docker', ['shop.example.com'], port=8123, micro_cache=True) + assert 'proxy_cache_valid 200 301 23s;' in result['config'] + assert rendering.clamp_micro_cache_ttl(None) == 10 # no shared mutable state + custom = replace(rendering.DEFAULT_SETTINGS, MICROCACHE_TTL_DEFAULT=17) + assert rendering.clamp_micro_cache_ttl(None, settings=custom) == 17 + + +def test_compression_service_preserves_directive_overrides(monkeypatch): + monkeypatch.setattr(NginxService, 'GZIP_DIRECTIVES', (('gzip', 'off'),)) + actual = NginxService.render_compression_snippet('', '/ours.conf') + assert 'gzip off;' in actual and 'gzip_types' not in actual + assert 'gzip on;' in compression.render_compression_snippet('', '/ours.conf') + + +@pytest.mark.parametrize('kwargs,error', [ + ({'domains': []}, 'At least one domain'), + ({'domains': ['_']}, 'reserved'), + ({'domains': ['shop.example.com; include /tmp/evil']}, 'Invalid domain'), + ({'root_path': '/srv/../etc'}, 'Invalid root'), + ({'root_path': '/srv/shop\ninclude /tmp/evil'}, 'Invalid root'), + ({'port': None}, 'need a port'), + ({'app_type': 'unknown'}, 'Unknown service type'), +]) +def test_pure_rendering_preserves_input_rejection(kwargs, error): + args = dict(name='shop', app_type='docker', domains=['shop.example.com'], port=8123) + args.update(kwargs) + result = rendering.render_site_config(**args) + assert result['success'] is False + assert error in result['error'] diff --git a/docs/CORE_BOUNDARIES.md b/docs/CORE_BOUNDARIES.md index 57f587ba..1709f37b 100644 --- a/docs/CORE_BOUNDARIES.md +++ b/docs/CORE_BOUNDARIES.md @@ -72,6 +72,36 @@ documented exception to adapter-only transport: they read storage configuration, panel version and panel volumes, not file contents. The route constructs the adapter but does not issue API calls or await requests. +## Nginx configuration generation + +`backend/app/services/nginx_service.py` remains the compatible host-facing +interface. It owns file updates, config testing, reloads, rollback and restore +checkpoints. Configuration generation lives under `services/nginx/`: + +| Owner | Responsibility | +| --- | --- | +| `templates.py` | Configuration text and default values, with no executable behavior | +| `validation.py` | Domain/path validation shared by rendering and cache operations | +| `rendering.py` | Vhost selection, immutable assets, micro-cache, WordPress protection and SSL wrapping | +| `compression.py` | Compression directives computed from supplied nginx dump/version text | + +The dependency direction is host service → pure configuration modules → +templates/validation. Rendering never imports Flask, models, other services, +filesystem APIs or process runners. It accepts values and returns text or an +error. `RenderSettings` is an immutable value object; the compatibility service +copies its template settings into that object, preserving class-level settings +without passing the service itself into the renderer. Compression similarly +receives directive tuples. Keep privileged writes and reloads in the existing +host lifecycle; a rendering feature must not create another write path. + +The old `NginxService` methods and template attributes remain available. New +rendering behavior belongs in the pure modules; those service methods must stay +delegates. `test_nginx_boundaries.py` enforces that direction, data-only templates +and module size limits, with negative fixtures for forbidden dependencies. +`test_nginx_render_contract.py` captures 512 pre-extraction rendering combinations. +Its digests are a refactoring contract: change them only for an intentional +output change backed by semantic tests and, where relevant, real nginx parsing. + ## Checks when extending these areas - `npm run lint` in `frontend`: includes File Manager dependency/composition @@ -85,6 +115,11 @@ adapter but does not issue API calls or await requests. tests/test_core_blueprint_registry.py tests/test_cli_skips_background.py tests/test_api_error_shape.py` in `backend`: focused startup coverage. - Run the full backend suite for application assembly changes. +- Nginx changes: run `test_nginx_boundaries.py`, `test_nginx_render_contract.py` + and the existing nginx, micro-cache, immutable-assets, HTTPS, WordPress + protection and restore-point tests. On Linux with nginx installed, run + `SERVERKIT_REAL_BINARIES=1 python -m pytest tests/test_real_nginx_vhost_syntax.py` + to validate generated configuration with the actual nginx parser. These checks already run through the existing frontend/backend CI workflows. Do not raise a size ceiling or allow a new dependency just to make a check pass; From 0894b8ff5bda30ff1e1153af4846f1585813bc2b Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 05:56:04 -0400 Subject: [PATCH 14/34] fix: require provisioned runtime before advertising previews --- backend/app/models/application_preview.py | 18 ++++++++-- backend/app/services/preview_service.py | 21 ++++++------ backend/tests/test_previews.py | 33 +++++++++++++++++-- .../src/components/previews/PreviewList.jsx | 19 ++++++++--- 4 files changed, 71 insertions(+), 20 deletions(-) diff --git a/backend/app/models/application_preview.py b/backend/app/models/application_preview.py index 53201d25..1f35fd58 100644 --- a/backend/app/models/application_preview.py +++ b/backend/app/models/application_preview.py @@ -27,6 +27,7 @@ class ApplicationPreview(TimestampMixin, JsonColumnMixin, db.Model): STATUS_RUNNING = 'running' STATUS_STOPPED = 'stopped' STATUS_FAILED = 'failed' + STATUS_UNAVAILABLE = 'unavailable' STATUS_DESTROYED = 'destroyed' id = db.Column(db.Integer, primary_key=True) @@ -60,16 +61,27 @@ class ApplicationPreview(TimestampMixin, JsonColumnMixin, db.Model): self._json_write('container_ids', list(ids or []), falsy='[]') def to_dict(self): + container_ids = self.get_container_ids() + # Older generic previews were marked running after config generation + # alone. Do not advertise those rows as a deployed runtime on reads. + status = self.status + if status == self.STATUS_RUNNING and not container_ids: + status = self.STATUS_UNAVAILABLE 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, + 'status': status, + 'status_reason': ( + 'No provisioned runtime is recorded for this preview.' + if status == self.STATUS_UNAVAILABLE else None + ), 'domain': self.domain, - 'url': (f'https://{self.domain}' if self.domain else None), - 'container_ids': self.get_container_ids(), + 'url': (f'https://{self.domain}' + if self.domain and status == self.STATUS_RUNNING and container_ids else None), + 'container_ids': 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, diff --git a/backend/app/services/preview_service.py b/backend/app/services/preview_service.py index 90836b58..9c75d567 100644 --- a/backend/app/services/preview_service.py +++ b/backend/app/services/preview_service.py @@ -287,9 +287,12 @@ class PreviewService: # 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('unsupported'): + preview.status = ApplicationPreview.STATUS_UNAVAILABLE + elif provisioned.get('ok') and provisioned.get('container_ids'): + preview.status = ApplicationPreview.STATUS_RUNNING + else: + preview.status = ApplicationPreview.STATUS_FAILED if provisioned.get('container_ids'): preview.set_container_ids(provisioned['container_ids']) db.session.commit() @@ -306,11 +309,9 @@ class PreviewService: 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``. + WordPress delegates to its preview hook. Generic config generation is + not provisioning: until a runtime provisioner exists, report unsupported. + A provider must explicitly report success and return runtime identifiers. """ try: if getattr(app, 'app_type', None) == 'wordpress': @@ -323,7 +324,7 @@ class PreviewService: res = WordPressService.create_preview_instance( site, preview.pr_number, domain=preview.domain, branch=preview.branch) - return {'ok': bool(res.get('success', True)), + return {'ok': bool(res.get('success', False)), 'container_ids': res.get('container_ids', [])} except Exception as exc: logger.info('WP preview provisioning unavailable: %s', exc) @@ -338,7 +339,7 @@ class PreviewService: manifest_preview = ManifestPreviewService.build_preview_config(app, preview) except Exception as exc: logger.info('manifest preview config unavailable: %s', exc) - return {'ok': True, 'container_ids': [], + return {'ok': False, 'unsupported': True, 'container_ids': [], 'manifest_preview': manifest_preview} except Exception as exc: logger.info('preview provisioning unavailable: %s', exc) diff --git a/backend/tests/test_previews.py b/backend/tests/test_previews.py index 27cfdf3e..6da064d2 100644 --- a/backend/tests/test_previews.py +++ b/backend/tests/test_previews.py @@ -156,11 +156,12 @@ def test_create_and_destroy_writes_rows_and_flips_status(app): 'pr_title': 'Add X', }) assert created.get('pr_number') == 12 - assert created.get('status') == ApplicationPreview.STATUS_RUNNING + assert created.get('status') == ApplicationPreview.STATUS_UNAVAILABLE + assert created['url'] is None 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 + assert row is not None and row.status == ApplicationPreview.STATUS_UNAVAILABLE destroyed = PreviewService.destroy_preview(row.id) assert destroyed.get('status') == ApplicationPreview.STATUS_DESTROYED @@ -217,3 +218,31 @@ def test_reconcile_against_db_rows(app): open_prs=[{'pr_number': 7, 'commit_sha': 'new'}], active_previews=[live]) assert [p['pr_number'] for p in plan['to_update']] == [7] + + +def test_preview_requires_success_and_runtime_ids(app, monkeypatch): + with app.app_context(): + a = _mk_app(name='runtime-proof') + PreviewService.enable_previews(a.id, {'enabled': True}) + for number, result, expected in [ + (1, {'ok': True, 'container_ids': ['runtime']}, 'running'), + (2, {'ok': True, 'container_ids': []}, 'failed'), + (3, {'ok': False, 'container_ids': ['runtime']}, 'failed'), + (4, {'container_ids': ['runtime']}, 'failed'), + ]: + monkeypatch.setattr(PreviewService, '_provision', lambda *a, **kw: result) + row = PreviewService.create_preview(a, {'pr_number': number}) + assert row['status'] == expected + assert bool(row['url']) == (expected == 'running') + + +def test_legacy_preview_without_runtime_is_not_advertised(): + row = ApplicationPreview(status='running', domain='pr.example.test') + assert row.to_dict()['status'] == 'unavailable' + assert row.to_dict()['url'] is None + assert row.status == 'running' # reads do not mutate persistence + row.set_container_ids(['runtime']) + assert row.to_dict()['url'] == 'https://pr.example.test' + for status in ('failed', 'stopped', 'destroyed', 'building', 'queued'): + row.status = status + assert row.to_dict()['url'] is None diff --git a/frontend/src/components/previews/PreviewList.jsx b/frontend/src/components/previews/PreviewList.jsx index d56e8b29..0f1f649b 100644 --- a/frontend/src/components/previews/PreviewList.jsx +++ b/frontend/src/components/previews/PreviewList.jsx @@ -87,8 +87,12 @@ const PreviewList = ({ appId }) => { async function handleRedeploy(preview) { setBusyId(preview.id); try { - await api.redeployPreview(appId, preview.id); - toast?.success?.(t('app.previewList.redeployingPreviewForPr', 'Redeploying preview for PR #{{prnumber}}', { prnumber: preview.pr_number })); + const result = await api.redeployPreview(appId, preview.id); + if (result.status === 'unavailable' || result.status === 'failed') { + toastError(toast, t('app.previewList.previewNotDeployed', 'The preview was not deployed. Review its status below.')); + } else { + toast?.success?.(t('app.previewList.redeployingPreviewForPr', 'Redeploying preview for PR #{{prnumber}}', { prnumber: preview.pr_number })); + } await load(); } catch (err) { toastError(toast, t('app.previewList.redeployFailed', "Couldn't redeploy the preview."), err); @@ -133,7 +137,7 @@ const PreviewList = ({ appId }) => {

{t('app.previewList.prPreviewEnvironments', 'PR preview environments')}

- {t('app.previewList.deployAnIsolatedPreviewOfEach', 'Deploy an isolated preview of each open pull request to a temporary domain, and tear it down when the PR closes.')} + {t('app.previewList.supportedProvisioners', 'Preview deployment requires a supported runtime provisioner. Generic application previews are not available yet. A domain alone does not mean a preview is deployed.')}

@@ -207,7 +211,7 @@ const PreviewList = ({ appId }) => {
{p.branch && {p.branch}} {p.short_sha && {p.short_sha}} - {p.url && ( + {p.url && p.status === 'running' && ( { )}
+ {p.status === 'unavailable' && ( +

+ {t('app.previewList.noRuntime', 'No provisioned runtime is recorded for this preview. Its URL is unavailable.')} +

+ )}
- {p.url && ( + {p.url && p.status === 'running' && ( }> + {services.length > 0 ? : !loading && !error && {t('effectiveEnv.unfiltered', 'No Compose services discovered; showing configuration without a service filter.')}} + + {loading ?

{t('effectiveEnv.loading', 'Loading effective environment…')}

+ : error ?

{t('effectiveEnv.error', 'Could not load the effective environment. Retry with Refresh.')}

+ : <> + {data?.complete === false &&

{t('effectiveEnv.incomplete', 'Incomplete: inherited variables could not be resolved. Only local configuration is shown; override information may be missing.')}

} + } /> + } +
; +} diff --git a/frontend/src/components/environment/EnvironmentPanel.jsx b/frontend/src/components/environment/EnvironmentPanel.jsx new file mode 100644 index 00000000..ba782849 --- /dev/null +++ b/frontend/src/components/environment/EnvironmentPanel.jsx @@ -0,0 +1,19 @@ +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import EnvironmentVariables from '../EnvironmentVariables'; +import SegControl from '../ds/SegControl'; +import ListToolbar from '../ds/ListToolbar'; +import EffectiveEnvironment from './EffectiveEnvironment'; + +export default function EnvironmentPanel({ appId }) { + const { t } = useTranslation(); + const [view, setView] = useState('local'); + return <> + } /> + {view === 'local' ? + : } + ; +} diff --git a/frontend/src/components/environment/useEffectiveEnvironment.js b/frontend/src/components/environment/useEffectiveEnvironment.js new file mode 100644 index 00000000..a8ded34c --- /dev/null +++ b/frontend/src/components/environment/useEffectiveEnvironment.js @@ -0,0 +1,45 @@ +import { useEffect, useState } from 'react'; +import api from '../../services/api'; + +// Keep discovery and resolution together: never flatten a Compose app's +// service-specific winners into a misleading single environment. +export function useEffectiveEnvironment(appId) { + const [selection, setSelection] = useState(null); + const [discovery, setDiscovery] = useState(null); + const [result, setResult] = useState(null); + const [revision, setRevision] = useState(0); + useEffect(() => { + let active = true; + setDiscovery(null); + api.getComposeServices(appId).then(data => { + if (active) setDiscovery({ appId, revision, services: data.services || [] }); + }).catch(() => { + if (active) setDiscovery({ appId, revision, error: true }); + }); + return () => { active = false; }; + }, [appId, revision]); + const current = discovery?.appId === appId && discovery?.revision === revision ? discovery : null; + const services = current?.services || []; + const service = selection?.appId === appId && services.includes(selection.service) + ? selection.service : services[0] || null; + useEffect(() => { + if (!current || current.error) return undefined; + let active = true; + setResult(null); + api.getEffectiveEnvVars(appId, service).then(data => { + if (active) setResult({ appId, service, revision, data }); + }).catch(() => { + if (active) setResult({ appId, service, revision, error: true }); + }); + return () => { active = false; }; + }, [appId, service, revision, current]); + const latest = current && result?.appId === appId && result?.service === service + && result?.revision === revision ? result : null; + return { + services, service, data: latest?.data, + error: Boolean(current?.error || latest?.error), + loading: !current || (!current.error && !latest), + selectService: value => setSelection({ appId, service: value }), + refresh: () => setRevision(value => value + 1), + }; +} diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json index 5124228e..5b56511f 100644 --- a/frontend/src/i18n/locales/ar.json +++ b/frontend/src/i18n/locales/ar.json @@ -4422,7 +4422,6 @@ "activePreviews": "معاينات نشطة", "couldNotLoadPrPreviews": "تعذر تحميل معاينات العلاقات العامة", "couldNotSaveSettings": "لا يمكن حفظ الإعدادات", - "deployAnIsolatedPreviewOfEach": "انشر معاينة معزولة لكل طلب سحب مفتوح إلى مجال مؤقت، وقم بتمزيقه عند إغلاق العلاقات العامة.", "destroy": "تدمير", "destroyFailed": "فشل التدمير", "destroyPreview": "تدمير المعاينة", diff --git a/frontend/src/i18n/locales/bn.json b/frontend/src/i18n/locales/bn.json index 817e0f3b..d2ddb562 100644 --- a/frontend/src/i18n/locales/bn.json +++ b/frontend/src/i18n/locales/bn.json @@ -4422,7 +4422,6 @@ "activePreviews": "সক্রিয় পূর্বরূপ", "couldNotLoadPrPreviews": "পিআর প্রিভিউ লোড করা যায়নি", "couldNotSaveSettings": "সেটিংস সংরক্ষণ করা যায়নি৷", - "deployAnIsolatedPreviewOfEach": "একটি অস্থায়ী ডোমেনে প্রতিটি খোলা পুল অনুরোধের একটি বিচ্ছিন্ন পূর্বরূপ স্থাপন করুন এবং পিআর বন্ধ হয়ে গেলে এটিকে ভেঙে ফেলুন।", "destroy": "ধ্বংস করুন", "destroyFailed": "ধ্বংস ব্যর্থ হয়েছে", "destroyPreview": "পূর্বরূপ ধ্বংস", diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.json index 064b5d65..644f8ebf 100644 --- a/frontend/src/i18n/locales/de.json +++ b/frontend/src/i18n/locales/de.json @@ -4422,7 +4422,6 @@ "activePreviews": "Aktive Vorschauen", "couldNotLoadPrPreviews": "PR-Vorschauen konnten nicht geladen werden", "couldNotSaveSettings": "Die Einstellungen konnten nicht gespeichert werden", - "deployAnIsolatedPreviewOfEach": "Stellen Sie eine isolierte Vorschau jeder offenen Pull-Anfrage in einer temporären Domäne bereit und entfernen Sie sie, wenn der PR geschlossen wird.", "destroy": "Zerstören", "destroyFailed": "Die Zerstörung ist fehlgeschlagen", "destroyPreview": "Vorschau zerstören", diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json index 82f855df..bab1eaf9 100644 --- a/frontend/src/i18n/locales/en.json +++ b/frontend/src/i18n/locales/en.json @@ -4419,13 +4419,9 @@ "rename": "Rename" }, "previewList": { - "supportedProvisioners": "Preview deployment requires a supported runtime provisioner. Generic application previews are not available yet. A domain alone does not mean a preview is deployed.", - "noRuntime": "No provisioned runtime is recorded for this preview. Its URL is unavailable.", - "previewNotDeployed": "The preview was not deployed. Review its status below.", "activePreviews": "Active previews", "couldNotLoadPrPreviews": "Couldn't load PR previews.", "couldNotSaveSettings": "Couldn't save the settings.", - "deployAnIsolatedPreviewOfEach": "Deploy an isolated preview of each open pull request to a temporary domain, and tear it down when the PR closes.", "destroy": "Delete", "destroyFailed": "Couldn't delete the preview.", "destroyPreview": "Delete preview", @@ -4435,16 +4431,19 @@ "enabled": "Enabled", "loadingPreviews": "Loading previews…", "noActivePreviews": "No active previews", + "noRuntime": "No provisioned runtime is recorded for this preview. Its URL is unavailable.", "openAPullRequestToSpin": "Open a pull request to spin up a preview, or sync to reconcile now.", "placeholders": "Placeholders:", "pr": "PR #", "prPreviewEnvironments": "PR preview environments", "previewForPrDestroyed": "Preview for PR #{{prnumber}} deleted", + "previewNotDeployed": "The preview was not deployed. Review its status below.", "previewSettingsSaved": "Preview settings saved", "reconciledPreviewsAgainstOpenPrs": "Reconciled previews against open PRs", "redeploy": "Redeploy", "redeployFailed": "Couldn't redeploy the preview.", "redeployingPreviewForPr": "Redeploying preview for PR #{{prnumber}}", + "supportedProvisioners": "Preview deployment requires a supported runtime provisioner. Generic application previews are not available yet. A domain alone does not mean a preview is deployed.", "syncFailed": "Couldn't sync previews.", "syncWithOpenPrs": "Sync with open PRs", "tearDownThePreviewEnvironmentFor": "Tear down the preview environment for PR #{{prnumber}}? This removes its temporary domain and resources." @@ -8182,6 +8181,33 @@ "minutesShort": "{{count}}m" } }, + "effectiveEnv": { + "allServices": "All services", + "empty": "No managed variables", + "emptyMessage": "No local or inherited variables apply to this selection.", + "environment": "Environment", + "error": "Could not load the effective environment. Retry with Refresh.", + "explanation": "Managed variables for the next deployment or restart, not a live container inspection. Image and Compose-file variables are not included. Values are hidden, including references and interpolated secrets.", + "hidden": "Hidden", + "incomplete": "Incomplete: inherited variables could not be resolved. Only local configuration is shown; override information may be missing.", + "incompleteEmpty": "No local variables to show. Refresh to retry inherited configuration.", + "incompleteTitle": "Inherited configuration unavailable", + "key": "Key", + "loading": "Loading effective environment…", + "local": "Local variables", + "overrides": "Overrides inherited source", + "project": "Project", + "reference": "Reference · resolved at deployment", + "refresh": "Refresh", + "resource": "Attached group", + "service": "Compose service", + "source": "Winning source", + "target": "Target service", + "title": "Effective environment", + "unfiltered": "No Compose services discovered; showing configuration without a service filter.", + "value": "Value", + "workspace": "Workspace" + }, "errors": { "agent": { "offline": "The server's agent is offline. Start the agent on that server, then try again." diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json index 3eddb1fa..6c2cf92c 100644 --- a/frontend/src/i18n/locales/es.json +++ b/frontend/src/i18n/locales/es.json @@ -4422,7 +4422,6 @@ "activePreviews": "Vistas previas activas", "couldNotLoadPrPreviews": "No se pudieron cargar las vistas previas de PR", "couldNotSaveSettings": "No se pudo guardar la configuración", - "deployAnIsolatedPreviewOfEach": "Despliega una vista previa aislada de cada pull request abierto en un dominio temporal y elimínala cuando el PR se cierre.", "destroy": "Destruir", "destroyFailed": "No se pudo destruir", "destroyPreview": "Destruir vista previa", diff --git a/frontend/src/i18n/locales/fr.json b/frontend/src/i18n/locales/fr.json index 7ec01011..c49546e5 100644 --- a/frontend/src/i18n/locales/fr.json +++ b/frontend/src/i18n/locales/fr.json @@ -4422,7 +4422,6 @@ "activePreviews": "Aperçus actifs", "couldNotLoadPrPreviews": "Impossible de charger les aperçus PR", "couldNotSaveSettings": "Impossible d'enregistrer les paramètres", - "deployAnIsolatedPreviewOfEach": "Déployez un aperçu isolé de chaque demande d'extraction ouverte sur un domaine temporaire et supprimez-le à la fermeture du PR.", "destroy": "Détruire", "destroyFailed": "La destruction a échoué", "destroyPreview": "Détruire l'aperçu", diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.json index 36df785e..d4ade2a0 100644 --- a/frontend/src/i18n/locales/id.json +++ b/frontend/src/i18n/locales/id.json @@ -4422,7 +4422,6 @@ "activePreviews": "Pratinjau aktif", "couldNotLoadPrPreviews": "Tidak dapat memuat pratinjau PR", "couldNotSaveSettings": "Tidak dapat menyimpan setelan", - "deployAnIsolatedPreviewOfEach": "Terapkan pratinjau terisolasi dari setiap permintaan penarikan terbuka ke domain sementara, dan hancurkan saat PR ditutup.", "destroy": "Menghancurkan", "destroyFailed": "Penghancuran gagal", "destroyPreview": "Hancurkan pratinjau", diff --git a/frontend/src/i18n/locales/it.json b/frontend/src/i18n/locales/it.json index 39114f3f..63eadbd4 100644 --- a/frontend/src/i18n/locales/it.json +++ b/frontend/src/i18n/locales/it.json @@ -4422,7 +4422,6 @@ "activePreviews": "Anteprime attive", "couldNotLoadPrPreviews": "Impossibile caricare le anteprime PR", "couldNotSaveSettings": "Impossibile salvare le impostazioni", - "deployAnIsolatedPreviewOfEach": "Distribuisci un'anteprima isolata di ogni richiesta pull aperta a un dominio temporaneo e rimuovila quando il PR si chiude.", "destroy": "Distruggere", "destroyFailed": "Distruzione fallita", "destroyPreview": "Distruggi l'anteprima", diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json index 2689af1b..4f6d0d57 100644 --- a/frontend/src/i18n/locales/ko.json +++ b/frontend/src/i18n/locales/ko.json @@ -4422,7 +4422,6 @@ "activePreviews": "활성 미리보기", "couldNotLoadPrPreviews": "PR 미리보기를 로드할 수 없습니다.", "couldNotSaveSettings": "설정을 저장할 수 없습니다.", - "deployAnIsolatedPreviewOfEach": "열려 있는 각 풀 요청의 격리된 미리 보기를 임시 도메인에 배포하고 PR이 닫힐 때 이를 해체합니다.", "destroy": "파괴하다", "destroyFailed": "폐기 실패", "destroyPreview": "미리보기 삭제", diff --git a/frontend/src/i18n/locales/pl.json b/frontend/src/i18n/locales/pl.json index 0ae63d31..4421ee9a 100644 --- a/frontend/src/i18n/locales/pl.json +++ b/frontend/src/i18n/locales/pl.json @@ -4422,7 +4422,6 @@ "activePreviews": "Aktywne podglądy", "couldNotLoadPrPreviews": "Nie można wczytać podglądów PR", "couldNotSaveSettings": "Nie udało się zapisać ustawień", - "deployAnIsolatedPreviewOfEach": "Wdróż izolowany podgląd każdego otwartego żądania ściągnięcia w domenie tymczasowej i zniszcz go po zamknięciu PR.", "destroy": "Zniszczyć", "destroyFailed": "Zniszczenie nie powiodło się", "destroyPreview": "Zniszcz podgląd", diff --git a/frontend/src/i18n/locales/pt.json b/frontend/src/i18n/locales/pt.json index 722b7e81..be3f4777 100644 --- a/frontend/src/i18n/locales/pt.json +++ b/frontend/src/i18n/locales/pt.json @@ -4422,7 +4422,6 @@ "activePreviews": "Visualizações ativas", "couldNotLoadPrPreviews": "Não foi possível carregar as visualizações de PR", "couldNotSaveSettings": "Não foi possível salvar as configurações", - "deployAnIsolatedPreviewOfEach": "Implante uma visualização isolada de cada solicitação pull aberta em um domínio temporário e desative-a quando o PR for fechado.", "destroy": "Destruir", "destroyFailed": "Falha na destruição", "destroyPreview": "Destruir visualização", diff --git a/frontend/src/i18n/locales/ru.json b/frontend/src/i18n/locales/ru.json index 2b7f26bb..360cad82 100644 --- a/frontend/src/i18n/locales/ru.json +++ b/frontend/src/i18n/locales/ru.json @@ -4422,7 +4422,6 @@ "activePreviews": "Активные превью", "couldNotLoadPrPreviews": "Не удалось загрузить предварительный просмотр PR.", "couldNotSaveSettings": "Не удалось сохранить настройки", - "deployAnIsolatedPreviewOfEach": "Разверните изолированную предварительную версию каждого открытого запроса на включение во временный домен и отключите ее при закрытии PR.", "destroy": "Удалить", "destroyFailed": "Уничтожить не удалось", "destroyPreview": "Уничтожить предварительный просмотр", diff --git a/frontend/src/i18n/locales/th.json b/frontend/src/i18n/locales/th.json index ea69ebf5..91b55e42 100644 --- a/frontend/src/i18n/locales/th.json +++ b/frontend/src/i18n/locales/th.json @@ -4422,7 +4422,6 @@ "activePreviews": "การแสดงตัวอย่างที่ใช้งานอยู่", "couldNotLoadPrPreviews": "ไม่สามารถโหลดตัวอย่าง PR", "couldNotSaveSettings": "ไม่สามารถบันทึกการตั้งค่าได้", - "deployAnIsolatedPreviewOfEach": "ปรับใช้การแสดงตัวอย่างแบบแยกของแต่ละคำขอดึงแบบเปิดไปยังโดเมนชั่วคราว และรื้อถอนเมื่อ PR ปิด", "destroy": "ทำลาย", "destroyFailed": "การทำลายล้างล้มเหลว", "destroyPreview": "ทำลายการแสดงตัวอย่าง", diff --git a/frontend/src/i18n/locales/tr.json b/frontend/src/i18n/locales/tr.json index efb29013..197949be 100644 --- a/frontend/src/i18n/locales/tr.json +++ b/frontend/src/i18n/locales/tr.json @@ -4422,7 +4422,6 @@ "activePreviews": "Etkin önizlemeler", "couldNotLoadPrPreviews": "PR önizlemeleri yüklenemedi", "couldNotSaveSettings": "Ayarlar kaydedilemedi", - "deployAnIsolatedPreviewOfEach": "Her açık çekme isteğinin yalıtılmış bir ön izlemesini geçici bir etki alanına dağıtın ve PR kapatıldığında onu yırtın.", "destroy": "Tahrip etmek", "destroyFailed": "Yok etme başarısız oldu", "destroyPreview": "Önizlemeyi yok et", diff --git a/frontend/src/i18n/locales/vi.json b/frontend/src/i18n/locales/vi.json index 78d5cc40..bc676b9e 100644 --- a/frontend/src/i18n/locales/vi.json +++ b/frontend/src/i18n/locales/vi.json @@ -4422,7 +4422,6 @@ "activePreviews": "Xem trước đang hoạt động", "couldNotLoadPrPreviews": "Không thể tải bản xem trước PR", "couldNotSaveSettings": "Không thể lưu cài đặt", - "deployAnIsolatedPreviewOfEach": "Triển khai bản xem trước riêng biệt của từng yêu cầu kéo mở tới một miền tạm thời và chia nhỏ nó khi PR đóng.", "destroy": "Hủy hoại", "destroyFailed": "Phá hủy thất bại", "destroyPreview": "Phá hủy bản xem trước", diff --git a/frontend/src/i18n/locales/zh-Hans.json b/frontend/src/i18n/locales/zh-Hans.json index 3226ac89..d31e4aa9 100644 --- a/frontend/src/i18n/locales/zh-Hans.json +++ b/frontend/src/i18n/locales/zh-Hans.json @@ -4422,7 +4422,6 @@ "activePreviews": "活动预览", "couldNotLoadPrPreviews": "无法加载 PR 预览", "couldNotSaveSettings": "无法保存设置", - "deployAnIsolatedPreviewOfEach": "将每个开放拉取请求的独立预览部署到临时域,并在 PR 关闭时将其拆除。", "destroy": "销毁", "destroyFailed": "销毁失败", "destroyPreview": "销毁预览", diff --git a/frontend/src/i18n/locales/zh-Hant.json b/frontend/src/i18n/locales/zh-Hant.json index b51ec35f..8185d16d 100644 --- a/frontend/src/i18n/locales/zh-Hant.json +++ b/frontend/src/i18n/locales/zh-Hant.json @@ -4422,7 +4422,6 @@ "activePreviews": "活動預覽", "couldNotLoadPrPreviews": "無法載入 PR 預覽", "couldNotSaveSettings": "無法儲存設定", - "deployAnIsolatedPreviewOfEach": "為每個開啟的 Pull Request 在暫時網域部署獨立的預覽環境,並在 PR 關閉時移除。", "destroy": "銷毀", "destroyFailed": "銷毀失敗", "destroyPreview": "銷毀預覽", diff --git a/frontend/src/pages/ServiceDetail.jsx b/frontend/src/pages/ServiceDetail.jsx index 00b72012..e8157832 100644 --- a/frontend/src/pages/ServiceDetail.jsx +++ b/frontend/src/pages/ServiceDetail.jsx @@ -7,7 +7,7 @@ import { useConfirm } from '../hooks/useConfirm'; import { useService } from '../hooks/useService'; import useTabParam from '../hooks/useTabParam'; import { getTabsForType } from '../utils/serviceTypes'; -import EnvironmentVariables from '../components/EnvironmentVariables'; +import EnvironmentVariables from '../components/environment/EnvironmentPanel'; import EventsTab from '../components/service-detail/EventsTab'; import LogsTab from '../components/service-detail/LogsTab'; import ShellTab from '../components/service-detail/ShellTab'; diff --git a/frontend/src/services/api/apps.js b/frontend/src/services/api/apps.js index 9b78e786..d5282fa9 100644 --- a/frontend/src/services/api/apps.js +++ b/frontend/src/services/api/apps.js @@ -218,6 +218,12 @@ export async function regeneratePrivateUrl(appId) { } // Environment Variables endpoints +export async function getEffectiveEnvVars(appId, service = null) { + const params = new URLSearchParams({ view: 'effective' }); + if (service) params.set('service', service); + return this.request(`/apps/${appId}/env?${params}`); +} + export async function getEnvVars(appId, maskSecrets = false) { const params = maskSecrets ? '?mask=true' : ''; return this.request(`/apps/${appId}/env${params}`); From 5a13a0dfb1672b88f58a88c30359883458ad821d Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 06:11:46 -0400 Subject: [PATCH 17/34] feat: provision isolated generic previews with retryable resource cleanup --- backend/app/api/webhooks.py | 21 +- backend/app/models/application_preview.py | 20 +- backend/app/services/build_service.py | 11 + backend/app/services/docker_service.py | 5 +- backend/app/services/preview_service.py | 99 ++++++--- backend/app/services/previews/__init__.py | 1 + backend/app/services/previews/plan.py | 53 +++++ backend/app/services/previews/provisioner.py | 67 ++++++ backend/app/services/previews/requests.py | 40 ++++ backend/app/services/previews/runtime.py | 123 +++++++++++ backend/app/services/previews/source.py | 49 +++++ .../versions/111_preview_runtime.py | 31 +++ backend/tests/test_generic_previews.py | 208 ++++++++++++++++++ backend/tests/test_previews.py | 4 +- 14 files changed, 684 insertions(+), 48 deletions(-) create mode 100644 backend/app/services/previews/__init__.py create mode 100644 backend/app/services/previews/plan.py create mode 100644 backend/app/services/previews/provisioner.py create mode 100644 backend/app/services/previews/requests.py create mode 100644 backend/app/services/previews/runtime.py create mode 100644 backend/app/services/previews/source.py create mode 100644 backend/migrations/versions/111_preview_runtime.py create mode 100644 backend/tests/test_generic_previews.py diff --git a/backend/app/api/webhooks.py b/backend/app/api/webhooks.py index 24f45ce7..891ce00c 100644 --- a/backend/app/api/webhooks.py +++ b/backend/app/api/webhooks.py @@ -189,24 +189,13 @@ def receive_pull_request(token): '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. + # Reserve desired state even when the create job has not started yet. + # A close must cancel a queued build rather than disappear for lack of a row. enqueued = False try: - from app.plugins_sdk import jobs - jobs.enqueue(job_kind, payload) + from app.services.previews.requests import enqueue + enqueue(webhook.app_id, payload['pr'], + action='destroy' if job_kind == 'preview.destroy' else 'create') enqueued = True except Exception as exc: logger.warning('failed to enqueue %s for app %s: %s', diff --git a/backend/app/models/application_preview.py b/backend/app/models/application_preview.py index 1f35fd58..4688adbb 100644 --- a/backend/app/models/application_preview.py +++ b/backend/app/models/application_preview.py @@ -48,6 +48,12 @@ class ApplicationPreview(TimestampMixin, JsonColumnMixin, db.Model): # when Docker isn't available, e.g. dev/test). container_ids = db.Column(db.Text, nullable=True) + # Durable intent ledger: written before external effects, retained on cleanup failure. + request_token = db.Column(db.String(32), nullable=True) + requested_action = db.Column(db.String(16), nullable=True) + runtime_state = db.Column(db.Text, nullable=True) + error_message = db.Column(db.Text, nullable=True) + commit_sha = db.Column(db.String(64), nullable=True) expires_at = db.Column(db.DateTime, nullable=True) @@ -60,6 +66,12 @@ class ApplicationPreview(TimestampMixin, JsonColumnMixin, db.Model): def set_container_ids(self, ids): self._json_write('container_ids', list(ids or []), falsy='[]') + def get_runtime_state(self): + return self._json_read('runtime_state', {}, expect=dict) + + def set_runtime_state(self, state): + self._json_write('runtime_state', state, falsy='{}') + def to_dict(self): container_ids = self.get_container_ids() # Older generic previews were marked running after config generation @@ -75,11 +87,11 @@ class ApplicationPreview(TimestampMixin, JsonColumnMixin, db.Model): 'branch': self.branch, 'status': status, 'status_reason': ( - 'No provisioned runtime is recorded for this preview.' - if status == self.STATUS_UNAVAILABLE else None + self.error_message or ('No provisioned runtime is recorded for this preview.' + if status == self.STATUS_UNAVAILABLE else None) ), 'domain': self.domain, - 'url': (f'https://{self.domain}' + 'url': (f"{self.get_runtime_state().get('scheme', 'https')}://{self.domain}" if self.domain and status == self.STATUS_RUNNING and container_ids else None), 'container_ids': container_ids, 'commit_sha': self.commit_sha, @@ -107,6 +119,7 @@ class ApplicationPreviewSettings(TimestampMixin, db.Model): application = db.relationship('Application', backref=db.backref('preview_settings', uselist=False)) + inherit_environment = db.Column(db.Boolean, nullable=False, default=False, server_default='0') enabled = db.Column(db.Boolean, default=False, nullable=False) domain_template = db.Column( db.String(255), default=DEFAULT_DOMAIN_TEMPLATE, nullable=False) @@ -120,6 +133,7 @@ class ApplicationPreviewSettings(TimestampMixin, db.Model): return { 'application_id': self.application_id, 'enabled': bool(self.enabled), + 'inherit_environment': bool(self.inherit_environment), 'domain_template': self.domain_template or self.DEFAULT_DOMAIN_TEMPLATE, 'target_server_id': self.target_server_id, 'ttl_days': self.ttl_days, diff --git a/backend/app/services/build_service.py b/backend/app/services/build_service.py index ff382973..8d609ff9 100644 --- a/backend/app/services/build_service.py +++ b/backend/app/services/build_service.py @@ -622,6 +622,17 @@ class BuildService: if not build_config: return {'success': False, 'error': 'Build is not set up for this service'} + return cls.build_from_config(app_id, build_config, no_cache=no_cache, + log_callback=log_callback, image_tag=image_tag) + + @classmethod + def build_from_config(cls, app_id, build_config, no_cache=False, + log_callback=None, image_tag=None): + """Build an explicit workspace without changing an app's saved config. + + Isolated consumers must supply their own log namespace and image tag. + The production build() entry point delegates here too. + """ app_path = build_config['app_path'] build_method = build_config.get('build_method', 'auto') timeout = build_config.get('timeout', cls.DEFAULT_TIMEOUT) diff --git a/backend/app/services/docker_service.py b/backend/app/services/docker_service.py index 20fe6842..5684b07e 100644 --- a/backend/app/services/docker_service.py +++ b/backend/app/services/docker_service.py @@ -309,7 +309,7 @@ class DockerService: @staticmethod def run_container(image, name=None, ports=None, volumes=None, env=None, - network=None, restart_policy='unless-stopped', command=None, detach=True): + network=None, restart_policy='unless-stopped', command=None, detach=True, labels=None): """Run a new container (create and start).""" try: cmd = ['run'] @@ -332,6 +332,9 @@ class DockerService: for key, value in env.items(): cmd.extend(['-e', f'{key}={value}']) + for key, value in (labels or {}).items(): + cmd.extend(['--label', f'{key}={value}']) + if network: cmd.extend(['--network', network]) diff --git a/backend/app/services/preview_service.py b/backend/app/services/preview_service.py index 9c75d567..e90d7cfc 100644 --- a/backend/app/services/preview_service.py +++ b/backend/app/services/preview_service.py @@ -171,6 +171,10 @@ class PreviewService: row = ApplicationPreviewSettings(application_id=application_id) db.session.add(row) + if 'inherit_environment' in settings: + if not isinstance(settings['inherit_environment'], bool): + raise ValueError('inherit_environment must be a boolean') + row.inherit_environment = settings['inherit_environment'] if 'enabled' in settings: row.enabled = bool(settings['enabled']) if 'domain_template' in settings and settings['domain_template']: @@ -242,7 +246,16 @@ class PreviewService: # ------------------------------------------------------------------ # @classmethod - def create_preview(cls, app, pr_payload): + def create_preview(cls, app, pr_payload, request_payload=None): + from app.services.deploy_lock import deploy_lock + with deploy_lock(app.id, 'preview deploy'): + from app.services.previews.requests import current + if request_payload and not current(request_payload): + return {'skipped': True, 'reason': 'superseded'} + return cls._create_preview_locked(app, pr_payload) + + @classmethod + def _create_preview_locked(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, @@ -254,10 +267,15 @@ class PreviewService: from app.models.application_preview import ApplicationPreview try: + db.session.refresh(app) + if app.deleted_at is not None: + return {'error': 'Service not found'} 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) + if pr_number <= 0: + return {'error': 'PR number must be positive'} 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') @@ -280,8 +298,8 @@ class PreviewService: preview.deleted_at = None ttl_days = getattr(settings, 'ttl_days', None) - if ttl_days: - preview.expires_at = datetime.utcnow() + timedelta(days=int(ttl_days)) + preview.expires_at = (datetime.utcnow() + timedelta(days=int(ttl_days)) + if ttl_days else None) db.session.commit() @@ -295,6 +313,8 @@ class PreviewService: preview.status = ApplicationPreview.STATUS_FAILED if provisioned.get('container_ids'): preview.set_container_ids(provisioned['container_ids']) + elif not preview.get_runtime_state().get('container'): + preview.set_container_ids([]) db.session.commit() return preview.to_dict() except Exception as exc: @@ -309,8 +329,8 @@ class PreviewService: def _provision(cls, app, preview): """Best-effort real provisioning. Returns ``{'ok': bool, 'container_ids': [...]}``. - WordPress delegates to its preview hook. Generic config generation is - not provisioning: until a runtime provisioner exists, report unsupported. + WordPress delegates to its preview hook; generic runtimes have a separate + journalled provisioner reusing the standard container builders. A provider must explicitly report success and return runtime identifiers. """ try: @@ -329,24 +349,29 @@ class PreviewService: except Exception as exc: logger.info('WP preview provisioning unavailable: %s', exc) return {'ok': False, 'container_ids': []} - # Non-WP: clone the manifest-resolved config (env + per-preview - # overrides + domain) when the app is manifest-managed (#20). The - # resolved config is the portable unit; a full Docker clone for - # generic apps remains best-effort future work. - manifest_preview = None - try: - from app.services.manifest_preview_service import ManifestPreviewService - manifest_preview = ManifestPreviewService.build_preview_config(app, preview) - except Exception as exc: - logger.info('manifest preview config unavailable: %s', exc) - return {'ok': False, 'unsupported': True, 'container_ids': [], - 'manifest_preview': manifest_preview} + from app.services.previews.provisioner import provision + return provision(app, preview, cls.get_settings(app.id)) except Exception as exc: logger.info('preview provisioning unavailable: %s', exc) return {'ok': False, 'container_ids': []} @classmethod - def destroy_preview(cls, preview_id): + def destroy_preview(cls, preview_id, request_payload=None): + from app.models.application_preview import ApplicationPreview + from app.services.deploy_lock import deploy_lock + row = ApplicationPreview.query.get(preview_id) + if not row: + return {'error': 'preview not found'} + with deploy_lock(row.application_id, 'preview cleanup'): + from app.services.previews.requests import current + if request_payload and not current(request_payload): + return {'skipped': True, 'reason': 'superseded'} + from app import db + db.session.refresh(row) + return cls._destroy_preview_locked(preview_id) + + @classmethod + def _destroy_preview_locked(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 @@ -368,6 +393,10 @@ class PreviewService: except Exception: pass + if preview.runtime_state: + from app.services.previews.runtime import cleanup + cleanup(preview) + # Best-effort WordPress teardown. if app is not None and getattr(app, 'app_type', None) == 'wordpress': try: @@ -391,7 +420,11 @@ class PreviewService: db.session.rollback() except Exception: pass - return {'error': str(exc)} + if preview: + preview.status = ApplicationPreview.STATUS_FAILED + preview.error_message = 'Preview cleanup failed; retry deletion.' + db.session.commit() + return {'error': 'Preview cleanup failed; retry deletion.'} @classmethod def sync_previews(cls, application_id): @@ -412,6 +445,8 @@ class PreviewService: return {'error': 'Service not found'} open_prs = cls._fetch_open_prs(app) + if open_prs is None: + return {'error': 'Open PR discovery is unavailable; existing previews were left unchanged.'} active = ApplicationPreview.query.filter( ApplicationPreview.application_id == application_id, ApplicationPreview.status != ApplicationPreview.STATUS_DESTROYED, @@ -449,7 +484,7 @@ class PreviewService: 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 [] + return None @classmethod def expire_stale(cls): @@ -464,9 +499,8 @@ class PreviewService: ApplicationPreview.expires_at < now, ApplicationPreview.status != ApplicationPreview.STATUS_DESTROYED, ).all() - for preview in stale: - cls.destroy_preview(preview.id) - return {'expired': len(stale)} + expired = sum(cls.destroy_preview(p.id).get('status') == 'destroyed' for p in stale) + return {'expired': expired, 'failed': len(stale) - expired} except Exception as exc: logger.warning('expire_stale failed: %s', exc) return {'expired': 0, 'error': str(exc)} @@ -484,17 +518,30 @@ class PreviewService: id=payload.get('application_id')).first() if not app: return {'error': 'Service not found'} - return cls.create_preview(app, payload.get('pr') or payload) + result = cls.create_preview(app, payload.get('pr') or payload, request_payload=payload) + if result.get('skipped'): + return result + if result.get('error') or result.get('status') != 'running': + raise RuntimeError(result.get('error') or result.get('status_reason') or 'Preview was not deployed') + return result @classmethod def _job_destroy(cls, job): payload = job.get_payload() or {} - return cls.destroy_preview(payload.get('preview_id')) + result = cls.destroy_preview(payload.get('preview_id'), request_payload=payload) + if result.get('error'): + raise RuntimeError(result['error']) + return result @classmethod def _job_sync(cls, job): payload = job.get_payload() or {} - return cls.sync_previews(payload.get('application_id')) + if payload.get('pr'): + return cls._job_create(job) + result = cls.sync_previews(payload.get('application_id')) + if result.get('error'): + raise RuntimeError(result['error']) + return result @classmethod def _job_expire(cls, _job): diff --git a/backend/app/services/previews/__init__.py b/backend/app/services/previews/__init__.py new file mode 100644 index 00000000..594f1716 --- /dev/null +++ b/backend/app/services/previews/__init__.py @@ -0,0 +1 @@ +"""Isolated generic preview planning, source preparation and runtime lifecycle.""" diff --git a/backend/app/services/previews/plan.py b/backend/app/services/previews/plan.py new file mode 100644 index 00000000..83dd3835 --- /dev/null +++ b/backend/app/services/previews/plan.py @@ -0,0 +1,53 @@ +"""Pure preview identity and eligibility; no host operations.""" +import re +from pathlib import Path +from app.services.nginx.validation import _validate_domain +from app.utils.git_security import validate_repo_url, validate_ref_name + + +class PreviewError(ValueError): + pass + + +def validate(app, preview, settings, git_config): + if app.server_id or settings.target_server_id: + raise PreviewError('Generic previews currently require a local server.') + if app.compose_file or app.managed_by in ('docker_compose', 'systemd'): + raise PreviewError('Compose and systemd previews are not supported by this provisioner.') + if app.ingress_plane not in (None, '', 'nginx'): + raise PreviewError('Generic previews currently require nginx ingress.') + if not app.port or not 1 <= app.port <= 65535: + raise PreviewError('Configure the application container port before deploying a preview.') + if not preview.domain or len(preview.domain) > 253 or not _validate_domain(preview.domain): + raise PreviewError('Invalid preview domain.') + if not isinstance(preview.pr_number, int) or preview.pr_number <= 0: + raise PreviewError('PR number must be a positive integer.') + if not preview.branch or validate_ref_name(preview.branch, 'branch'): + raise PreviewError('A valid branch in the configured repository is required.') + if not re.fullmatch(r'[0-9a-fA-F]{40}|[0-9a-fA-F]{64}', preview.commit_sha or ''): + raise PreviewError('An exact full commit SHA is required.') + if not git_config or validate_repo_url(git_config.get('repo_url')): + raise PreviewError('Configure a valid Git repository for this application first.') + + +def identity(preview_id, token): + if not isinstance(preview_id, int) or preview_id <= 0 or not re.fullmatch(r'[0-9a-f]{32}', token): + raise PreviewError('Invalid preview resource identity.') + return f'serverkit-preview-{preview_id}-{token}' + + +def workspace(root, preview_id, token): + # Never accept stored/PR-provided paths as cleanup targets. + name = identity(preview_id, token) + base = Path(root).resolve() + target = base / name + if target.is_symlink() or target.resolve().parent != base: + raise PreviewError('Preview workspace escaped its managed directory.') + return target + + +def relative_file(root, name): + path = Path(root) / name + if Path(name).is_absolute() or not path.resolve().is_relative_to(Path(root).resolve()): + raise PreviewError('Build path must stay inside the preview checkout.') + return path diff --git a/backend/app/services/previews/provisioner.py b/backend/app/services/previews/provisioner.py new file mode 100644 index 00000000..a74d905e --- /dev/null +++ b/backend/app/services/previews/provisioner.py @@ -0,0 +1,67 @@ +"""Generic preview transaction: validate, journal, build, gate, publish; compensate failures.""" +import uuid +from app import db +from app.models import Domain +from app.models.application_preview import ApplicationPreview +from app.services.git_service import GitService +from app.services.nginx_service import NginxService +from . import runtime, source +from .plan import PreviewError, validate, identity, workspace + + +def check_domain(preview): + domain = preview.domain.lower() + if Domain.query_active().filter(db.func.lower(Domain.name) == domain).first(): + raise PreviewError('Preview domain is already assigned to an application.') + if ApplicationPreview.query.filter( + ApplicationPreview.id != preview.id, + db.func.lower(ApplicationPreview.domain) == domain, + ApplicationPreview.status != 'destroyed', + ).first(): + raise PreviewError('Preview domain is already assigned to another preview.') + owned = preview.get_runtime_state().get('token') + own_name = identity(preview.id, owned) if owned else None + for site in NginxService.list_sites(): + if site['name'] != own_name and domain in [d.lower() for d in site.get('domains', [])]: + raise PreviewError('Preview domain is already configured in nginx.') + + +def provision(app, preview, settings): + config = GitService.get_app_config(app.id) + request_token = preview.request_token + try: + validate(app, preview, settings, config) + check_domain(preview) + # Stop/recreate semantics are deliberate: cleanup must finish before a + # new attempt. We never lose ownership of an abandoned generation. + runtime.cleanup(preview) + state = {'token': uuid.uuid4().hex} + runtime.save(preview, state) + target = workspace(runtime.ROOT, preview.id, state['token']) + target.parent.mkdir(parents=True, exist_ok=True) + name = identity(preview.id, state['token']) + state['source'] = True + runtime.save(preview, state) + source.prepare(app, preview, target, config['repo_url']) + state['image'] = True + runtime.save(preview, state) + source.build(app, preview, target, name + ':preview') + runtime.start(app, preview, state) + db.session.refresh(preview, ['request_token', 'requested_action']) + db.session.refresh(app, ['deleted_at']) + if app.deleted_at or preview.request_token != request_token or preview.requested_action == 'destroy': + raise PreviewError('Preview request was superseded or its application was deleted.') + runtime.publish(preview, state) + preview.error_message = None + return {'ok': True, 'container_ids': [state['container_id']]} + except Exception as exc: + # Only controlled diagnostics go to the browser; host errors may carry + # credentials or environment values. The journal survives cleanup errors. + error = str(exc) if isinstance(exc, PreviewError) else 'Preview provisioning failed.' + try: + runtime.cleanup(preview) + except Exception: + error += ' Cleanup is incomplete; retry deletion before deploying again.' + preview.error_message = error + db.session.commit() + return {'ok': False, 'container_ids': [], 'error': error} diff --git a/backend/app/services/previews/requests.py b/backend/app/services/previews/requests.py new file mode 100644 index 00000000..699f2bbd --- /dev/null +++ b/backend/app/services/previews/requests.py @@ -0,0 +1,40 @@ +"""Short request reservations, separate from long-running deployment locks.""" +import uuid +from app import db +from app.models.application_preview import ApplicationPreview +from app.jobs.service import JobService +from app.services.deploy_lock import deploy_lock +from .plan import PreviewError + + +def enqueue(app_id, pr, action='create'): + try: + number = int(pr.get('pr_number')) + except (TypeError, ValueError): + raise PreviewError('A positive PR number is required.') + if number <= 0 or action not in ('create', 'destroy'): + raise PreviewError('Invalid preview request.') + # Distinct from the app deploy lock: a close can supersede an in-flight + # build immediately instead of blocking the webhook for several minutes. + with deploy_lock(f'preview-request-{app_id}', 'preview request'): + row = ApplicationPreview.query.filter_by(application_id=app_id, pr_number=number).first() + if row is None: + row = ApplicationPreview(application_id=app_id, pr_number=number, status='queued') + db.session.add(row) + row.request_token = uuid.uuid4().hex + row.requested_action = action + db.session.commit() + return JobService.enqueue('preview.' + action, { + 'application_id': app_id, 'preview_id': row.id, 'pr': pr, + 'request_token': row.request_token, + }, max_attempts=1, owner_type='application', owner_id=str(app_id)) + + +def current(payload): + if not payload.get('request_token'): + return True # compatibility with older queued jobs + row = db.session.get(ApplicationPreview, payload.get('preview_id')) + if not row: + return False + db.session.refresh(row, ['request_token']) + return row.request_token == payload['request_token'] diff --git a/backend/app/services/previews/runtime.py b/backend/app/services/previews/runtime.py new file mode 100644 index 00000000..cb5cdd15 --- /dev/null +++ b/backend/app/services/previews/runtime.py @@ -0,0 +1,123 @@ +"""Host effects for one journalled preview generation; never operate on parent resources.""" +import json +import shutil +from pathlib import Path +from app import db, paths +from app.services.docker_service import DockerService +from app.services.nginx_service import NginxService +from app.services.site_domain_service import SiteDomainService +from app.services import health_gate +from .plan import PreviewError, identity, workspace + +ROOT = Path(paths.SERVERKIT_DIR) / 'previews' +LABEL = 'serverkit.preview' + + +def save(preview, state): + preview.set_runtime_state(state) + db.session.commit() + + +def inspect(kind, name): + result = DockerService.run([kind, 'inspect', name], timeout=30) + if result.get('success'): + return json.loads(result['output'])[0] + error = (result.get('error') or '').lower() + if 'no such' in error: + return None + raise PreviewError('Cannot inspect preview resources; cleanup must be retried.') + + +def start(app, preview, state): + name = identity(preview.id, state['token']) + state['container'] = True + save(preview, state) # intent before docker run, even if it partially fails + env = {'SERVERKIT_PREVIEW': 'true', 'SERVERKIT_PR_NUMBER': str(preview.pr_number), + 'SERVERKIT_PREVIEW_BRANCH': preview.branch} + from app.services.preview_service import PreviewService + if PreviewService.get_settings(app.id).inherit_environment: + from app.services.env_service import EnvService + entries, complete = EnvService._effective_entries(app) + if not complete: + raise PreviewError('Inherited environment is incomplete; preview deployment stopped.') + env = {**{key: value['value'] for key, value in entries.items()}, **env} + result = DockerService.run_container( + image=name + ':preview', name=name, ports=[f'127.0.0.1::{app.port}'], + env=env, restart_policy='unless-stopped', labels={LABEL: str(preview.id)}, + ) + if not result.get('success'): + raise PreviewError('Could not start the preview container.') + info = inspect('container', name) + if not info or info.get('Config', {}).get('Labels', {}).get(LABEL) != str(preview.id): + raise PreviewError('Preview container ownership could not be verified.') + bindings = info.get('NetworkSettings', {}).get('Ports', {}).get(f'{app.port}/tcp') or [] + binding = next((b for b in bindings if b.get('HostIp') == '127.0.0.1'), None) + if not binding: + raise PreviewError('Preview container has no loopback HTTP port.') + state['port'] = int(binding['HostPort']) + state['container_id'] = info['Id'] + save(preview, state) + health_gate.gate_for_app(app, port=state['port'], container=name) + info = inspect('container', name) + if not info or not info.get('State', {}).get('Running'): + raise PreviewError('Preview container stopped during its health check.') + + +def publish(preview, state): + name = identity(preview.id, state['token']) + cert = key = None + base = SiteDomainService.covering_base(preview.domain) + # A wildcard certificate covers exactly one label, not pr.app.base. + if base and preview.domain.endswith('.' + base) and preview.domain.count('.') == base.count('.') + 1: + if SiteDomainService.https_enabled(base): + cert, key = SiteDomainService.wildcard_cert_paths(base) + state['scheme'] = 'https' if cert and key else 'http' + state['vhost'] = True + save(preview, state) + result = NginxService.create_site(name, 'docker', [preview.domain], + port=state['port'], ssl_cert=cert, ssl_key=key) + if not result.get('success'): + raise PreviewError('Preview routing could not be published.') + + +def cleanup(preview): + """Idempotent, fail closed. Retain each intent until its removal succeeds.""" + state = preview.get_runtime_state() + if not state: + if preview.runtime_state and preview.runtime_state != '{}': + raise PreviewError('Preview resource ledger is invalid; refusing untracked cleanup.') + return + name = identity(preview.id, state.get('token', '')) + target = workspace(ROOT, preview.id, state['token']) + if state.get('vhost'): + # delete_site historically ignores disable failures. Check disable first + # so nginx cannot continue serving a resource reported as destroyed. + if not NginxService.disable_site(name).get('success'): + raise PreviewError('Preview routing cleanup failed; retry deletion.') + if not NginxService.delete_site(name).get('success'): + raise PreviewError('Preview vhost cleanup failed; retry deletion.') + state['vhost'] = False + save(preview, state) + if state.get('container'): + info = inspect('container', name) + if info: + if info.get('Config', {}).get('Labels', {}).get(LABEL) != str(preview.id): + raise PreviewError('Refusing to delete a container without preview ownership.') + if not DockerService.remove_container(name, force=True, volumes=True).get('success'): + raise PreviewError('Preview container cleanup failed; retry deletion.') + state['container'] = False + preview.set_container_ids([]) + save(preview, state) + if state.get('image'): + if inspect('image', name + ':preview') is not None: + if not DockerService.remove_image(name + ':preview', force=False).get('success'): + raise PreviewError('Preview image cleanup failed; retry deletion.') + state['image'] = False + save(preview, state) + if state.get('source'): + if target.exists(): + shutil.rmtree(target) + state['source'] = False + save(preview, state) + preview.set_container_ids([]) + save(preview, {}) diff --git a/backend/app/services/previews/source.py b/backend/app/services/previews/source.py new file mode 100644 index 00000000..305114ca --- /dev/null +++ b/backend/app/services/previews/source.py @@ -0,0 +1,49 @@ +"""Prepare an independent, pinned checkout and reuse the standard builders.""" +import shutil +from app.services.git_service import GitService +from app.services.build_service import BuildService +from app.utils.git_security import git_argv, git_env +from app.utils.system import run_checked +from .plan import PreviewError, relative_file + + +def prepare(app, preview, target, repo_url): + result = GitService.clone_repository(str(target), repo_url, branch=preview.branch) + if not result.get('success'): + # Raw Git output can contain authenticated repository URLs. + raise PreviewError('Preview repository clone failed. Check repository access and branch.') + sha = preview.commit_sha.lower() + # A PR must name a commit reachable from the selected same-repository branch. + result = run_checked(git_argv('-C', str(target), 'merge-base', '--is-ancestor', + sha, 'HEAD'), timeout=30, env=git_env()) + if not result.get('success'): + raise PreviewError('Preview commit is not reachable from the selected repository branch.') + result = run_checked(git_argv('-C', str(target), 'checkout', '--detach', sha), + timeout=60, env=git_env()) + if not result.get('success'): + raise PreviewError('Could not check out the requested preview commit.') + # Do not send clone credentials / Git metadata into a Docker build context. + shutil.rmtree(target / '.git') + + +def build(app, preview, target, image): + config = dict(BuildService.get_app_build_config(app.id) or {}) + config['app_path'] = str(target) + method = config.get('build_method', 'auto') + if method == 'auto': + method = BuildService.detect_build_method(str(target))['build_method'] + if method not in ('dockerfile', 'nixpacks'): + raise PreviewError('Previews require a Dockerfile or container buildpack; host-command builds are disabled.') + config['build_method'] = method + relative_file(target, config.get('dockerfile_path') or 'Dockerfile') + relative_file(target, 'Dockerfile.serverkit') + # Detect the PR's source, not the parent branch's persisted plan. Parent + # build secrets are not implicitly handed to PR code. + config.pop('buildpack_plan', None) + config['build_args'] = {} + config['env_vars'] = {} + result = BuildService.build_from_config( + f'preview-{preview.id}', config, image_tag=image, + ) + if not result.get('success'): + raise PreviewError('Preview image build failed. See the preview build logs.') diff --git a/backend/migrations/versions/111_preview_runtime.py b/backend/migrations/versions/111_preview_runtime.py new file mode 100644 index 00000000..2518dc85 --- /dev/null +++ b/backend/migrations/versions/111_preview_runtime.py @@ -0,0 +1,31 @@ +"""Track preview-owned resources and opt-in environment inheritance.""" +import sqlalchemy as sa +from alembic import op + +revision = '111_preview_runtime' +down_revision = '110_drop_workflow_schedules_job' +branch_labels = None +depends_on = None + + +def upgrade(): + inspector = sa.inspect(op.get_bind()) + existing = {c['name'] for c in inspector.get_columns('application_previews')} + for name, kind in [('request_token', sa.String(32)), ('requested_action', sa.String(16)), + ('runtime_state', sa.Text()), ('error_message', sa.Text())]: + if name not in existing: + op.add_column('application_previews', sa.Column(name, kind, nullable=True)) + existing = {c['name'] for c in inspector.get_columns('application_preview_settings')} + if 'inherit_environment' not in existing: + op.add_column('application_preview_settings', sa.Column( + 'inherit_environment', sa.Boolean(), nullable=False, server_default='0')) + + +def downgrade(): + with op.batch_alter_table('application_preview_settings') as batch: + batch.drop_column('inherit_environment') + with op.batch_alter_table('application_previews') as batch: + batch.drop_column('request_token') + batch.drop_column('requested_action') + batch.drop_column('error_message') + batch.drop_column('runtime_state') diff --git a/backend/tests/test_generic_previews.py b/backend/tests/test_generic_previews.py new file mode 100644 index 00000000..cc40d21e --- /dev/null +++ b/backend/tests/test_generic_previews.py @@ -0,0 +1,208 @@ +"""Generic previews: real orchestration with fake external Git/Docker/nginx effects.""" +import json +from types import SimpleNamespace +import pytest +from app import db +from app.models.application_preview import ApplicationPreview +from app.services.preview_service import PreviewService +from app.services.previews import runtime, source +from app.services.previews.plan import PreviewError, identity, workspace, validate +from test_previews import _mk_app + +SHA = 'a' * 40 +PR = {'pr_number': 7, 'branch': 'feature/preview', 'commit_sha': SHA} + + +@pytest.fixture +def host(app, monkeypatch, tmp_path): + from app.services.git_service import GitService + from app.services.build_service import BuildService + resources = {'containers': {}, 'images': set(), 'routes': {}, 'calls': []} + monkeypatch.setattr(runtime, 'ROOT', tmp_path / 'previews') + monkeypatch.setattr(BuildService, 'BUILD_LOG_DIR', str(tmp_path / 'logs')) + monkeypatch.setattr(GitService, 'get_app_config', lambda _: {'repo_url': 'https://example.test/repo.git'}) + def prepare(parent, preview, path, url): + resources['calls'].append(('clone', str(path), url)) + path.mkdir() + (path / 'Dockerfile').write_text('FROM scratch') + def build(parent, preview, path, image): + resources['calls'].append(('build', image)) + resources['images'].add(image) + monkeypatch.setattr(source, 'prepare', prepare) + monkeypatch.setattr(source, 'build', build) + def run_container(**kwargs): + resources['calls'].append(('run', kwargs)) + name = kwargs['name'] + resources['containers'][name] = {'Id': name + '-id', + 'Config': {'Labels': kwargs['labels']}, 'State': {'Running': True}, + 'NetworkSettings': {'Ports': {'8400/tcp': [{'HostIp': '127.0.0.1', 'HostPort': '39001'}]}}} + return {'success': True, 'container_id': name + '-id'} + def inspect(args, **kwargs): + kind, _, name = args + data = resources['containers'].get(name) if kind == 'container' else ({} if name in resources['images'] else None) + if data is None: + return {'success': False, 'error': 'No such object'} + return {'success': True, 'output': json.dumps([data])} + def remove(name, **kwargs): + resources['calls'].append(('remove', name, kwargs)) + resources['containers'].pop(name, None) + return {'success': True} + def remove_image(name, **kwargs): + resources['images'].discard(name) + return {'success': True} + def publish(name, kind, domains, **kwargs): + resources['routes'][name] = domains + return {'success': True} + def delete(name): + resources['routes'].pop(name, None) + return {'success': True} + monkeypatch.setattr(runtime.DockerService, 'run_container', run_container) + monkeypatch.setattr(runtime.DockerService, 'run', inspect) + monkeypatch.setattr(runtime.DockerService, 'remove_container', remove) + monkeypatch.setattr(runtime.DockerService, 'remove_image', remove_image) + monkeypatch.setattr(runtime.NginxService, 'list_sites', lambda: []) + monkeypatch.setattr(runtime.NginxService, 'create_site', publish) + monkeypatch.setattr(runtime.NginxService, 'disable_site', lambda _: {'success': True}) + monkeypatch.setattr(runtime.NginxService, 'delete_site', delete) + monkeypatch.setattr(runtime.SiteDomainService, 'covering_base', lambda _: None) + monkeypatch.setattr(runtime.health_gate, 'gate_for_app', lambda *a, **kw: {'status': 200}) + with app.app_context(): + parent = _mk_app(name='generic') + parent.container_id = 'production-container' + parent.docker_image = 'production:live' + db.session.commit() + PreviewService.enable_previews(parent.id, {'enabled': True, 'domain_template': 'pr-{pr_number}.test.example'}) + yield parent, resources + + +def test_create_redeploy_destroy_are_isolated_and_idempotent(host): + parent, resources = host + first = PreviewService.create_preview(parent, PR) + assert first['status'] == 'running', first + assert first['url'] == 'http://pr-7.test.example' + old_ids = first['container_ids'] + call = next(c[1] for c in resources['calls'] if c[0] == 'run') + assert call['ports'] == ['127.0.0.1::8400'] + assert 'volumes' not in call and 'network' not in call + assert call['env'] == {'SERVERKIT_PREVIEW': 'true', 'SERVERKIT_PR_NUMBER': '7', 'SERVERKIT_PREVIEW_BRANCH': 'feature/preview'} + second = PreviewService.create_preview(parent, {**PR, 'commit_sha': 'b' * 40}) + assert second['status'] == 'running' + assert second['id'] == first['id'] and second['container_ids'] != old_ids + assert len(resources['containers']) == len(resources['images']) == len(resources['routes']) == 1 + result = PreviewService.destroy_preview(first['id']) + assert result['status'] == 'destroyed' + assert not resources['containers'] and not resources['images'] and not resources['routes'] + assert not list(runtime.ROOT.iterdir()) + assert PreviewService.destroy_preview(first['id'])['status'] == 'destroyed' + db.session.refresh(parent) + assert parent.container_id == 'production-container' + assert parent.docker_image == 'production:live' and parent.port == 8400 + + +@pytest.mark.parametrize('failure', ['clone', 'build', 'start', 'health', 'route']) +def test_each_failure_compensates_owned_resources(host, monkeypatch, failure): + parent, resources = host + def fail(*args, **kwargs): + raise RuntimeError('secret-diagnostic-do-not-expose') + owner, attr = {'clone': (source, 'prepare'), 'build': (source, 'build'), + 'start': (runtime, 'start'), 'health': (runtime.health_gate, 'gate_for_app'), + 'route': (runtime, 'publish')}[failure] + monkeypatch.setattr(owner, attr, fail) + result = PreviewService.create_preview(parent, PR) + assert result['status'] == 'failed' and result['url'] is None + assert 'secret-diagnostic' not in str(result) + assert not resources['containers'] and not resources['images'] and not resources['routes'] + row = db.session.get(ApplicationPreview, result['id']) + assert row.get_runtime_state() == {} + + +def test_cleanup_failure_preserves_journal_and_retry_succeeds(host, monkeypatch): + parent, resources = host + result = PreviewService.create_preview(parent, PR) + remove = runtime.DockerService.remove_container + monkeypatch.setattr(runtime.DockerService, 'remove_container', lambda *a, **kw: {'success': False}) + failed = PreviewService.destroy_preview(result['id']) + assert failed.get('error') + row = db.session.get(ApplicationPreview, result['id']) + assert row.status == 'failed' and row.deleted_at is None + assert row.get_runtime_state()['container'] is True + assert resources['containers'] + monkeypatch.setattr(runtime.DockerService, 'remove_container', remove) + assert PreviewService.destroy_preview(result['id'])['status'] == 'destroyed' + assert not resources['containers'] + + +def test_domain_conflict_prevents_host_effects(host): + from app.models import Domain + parent, resources = host + db.session.add(Domain(name='pr-7.test.example', application_id=parent.id)) + db.session.commit() + result = PreviewService.create_preview(parent, PR) + assert result['status'] == 'failed' + assert not resources['calls'] + + +def test_unsupported_target_and_bad_ref_do_not_provision(host): + parent, resources = host + parent.compose_file = 'compose.yml' + db.session.commit() + assert PreviewService.create_preview(parent, PR)['status'] == 'failed' + parent.compose_file = None + db.session.commit() + assert PreviewService.create_preview(parent, {**PR, 'commit_sha': '--bad'})['status'] == 'failed' + assert not resources['calls'] + + +def test_unknown_provider_does_not_destroy_existing_previews(host): + parent, resources = host + result = PreviewService.create_preview(parent, PR) + assert PreviewService.sync_previews(parent.id).get('error') + assert db.session.get(ApplicationPreview, result['id']).status == 'running' + assert resources['containers'] + + +def test_cleanup_rejects_missing_ownership(host): + parent, resources = host + result = PreviewService.create_preview(parent, PR) + next(iter(resources['containers'].values()))['Config']['Labels'] = {} + assert PreviewService.destroy_preview(result['id']).get('error') + assert resources['containers'] + + +def test_close_supersedes_queued_create_before_row_has_runtime(host, monkeypatch): + from app.services.previews.requests import enqueue + from app.jobs.service import JobService + parent, resources = host + jobs = [] + def capture(kind, payload, **kwargs): + job = SimpleNamespace(kind=kind, get_payload=lambda: payload) + jobs.append(job) + return job + monkeypatch.setattr(JobService, 'enqueue', capture) + enqueue(parent.id, PR) + enqueue(parent.id, PR, action='destroy') + assert PreviewService._job_create(jobs[0])['reason'] == 'superseded' + assert PreviewService._job_destroy(jobs[1])['status'] == 'destroyed' + assert not resources['calls'] + + +def test_close_during_build_cleans_up_without_publishing(host, monkeypatch): + from app.services.previews.requests import enqueue + from app.jobs.service import JobService + parent, resources = host + monkeypatch.setattr(JobService, 'enqueue', lambda *a, **kw: None) + original = source.build + def build(*args): + original(*args) + enqueue(parent.id, PR, action='destroy') + monkeypatch.setattr(source, 'build', build) + result = PreviewService.create_preview(parent, PR) + assert result['status'] == 'failed' + assert not resources['routes'] and not resources['containers'] + + +def test_cleanup_paths_cannot_escape(tmp_path): + with pytest.raises(PreviewError): + workspace(tmp_path, 1, '../escape') + with pytest.raises(PreviewError): + identity(-1, 'a' * 32) diff --git a/backend/tests/test_previews.py b/backend/tests/test_previews.py index 6da064d2..69126e7c 100644 --- a/backend/tests/test_previews.py +++ b/backend/tests/test_previews.py @@ -156,12 +156,12 @@ def test_create_and_destroy_writes_rows_and_flips_status(app): 'pr_title': 'Add X', }) assert created.get('pr_number') == 12 - assert created.get('status') == ApplicationPreview.STATUS_UNAVAILABLE + assert created.get('status') == ApplicationPreview.STATUS_FAILED assert created['url'] is None 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_UNAVAILABLE + assert row is not None and row.status == ApplicationPreview.STATUS_FAILED destroyed = PreviewService.destroy_preview(row.id) assert destroyed.get('status') == ApplicationPreview.STATUS_DESTROYED From c0dbb921e1bbb220bc19d939d780dc45d27f20b0 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 06:21:26 -0400 Subject: [PATCH 18/34] feat: queue preview automation and preserve cleanup ownership through app deletion --- backend/app/api/previews.py | 39 +++-- backend/app/services/application_restore.py | 2 + backend/app/services/preview_service.py | 61 ++++--- backend/app/services/previews/lifecycle.py | 14 ++ backend/app/services/previews/provisioner.py | 10 +- backend/app/services/previews/requests.py | 20 +++ backend/app/services/previews/runtime.py | 5 +- backend/app/services/previews/source.py | 7 +- backend/app/services/recycle_bin_service.py | 14 +- backend/tests/test_generic_previews.py | 168 ++++++++++++++++++- backend/tests/test_preview_boundaries.py | 42 +++++ backend/tests/test_real_generic_preview.py | 93 ++++++++++ docs/CORE_BOUNDARIES.md | 64 ++++++- docs/MIGRATION_INVENTORY.md | 2 +- 14 files changed, 488 insertions(+), 53 deletions(-) create mode 100644 backend/app/services/previews/lifecycle.py create mode 100644 backend/tests/test_preview_boundaries.py create mode 100644 backend/tests/test_real_generic_preview.py diff --git a/backend/app/api/previews.py b/backend/app/api/previews.py index 08761d88..bbf07ff0 100644 --- a/backend/app/api/previews.py +++ b/backend/app/api/previews.py @@ -13,6 +13,10 @@ from app.models.application_preview import ApplicationPreview from app.services.preview_service import PreviewService from app.api._access import require_app from app.api._request import json_object +from app.middleware.rbac import developer_required +from app.services.previews.requests import enqueue, validate_request +from app.services.previews.plan import PreviewError +from app.exceptions import ValidationError previews_bp = Blueprint('previews', __name__) @@ -44,7 +48,10 @@ def update_preview_settings(app_id): """Enable/disable previews and set the domain template + TTL for an app.""" app = require_app(app_id, write=True, conceal=True) data = json_object(optional=True) - result = PreviewService.enable_previews(app_id, data) + try: + result = PreviewService.enable_previews(app_id, data) + except ValueError as exc: + raise ValidationError(str(exc)) from exc return jsonify(result), 200 @@ -67,14 +74,12 @@ def redeploy_preview(app_id, preview_id): 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, + job = enqueue(app_id, { + '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 + return jsonify({'status': 'queued', 'job_id': job.id}), 202 + @previews_bp.route('//previews/', methods=['DELETE']) @@ -86,6 +91,18 @@ def destroy_preview(app_id, preview_id): 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), status + job = enqueue(app_id, {'pr_number': preview.pr_number}, action='destroy') + return jsonify({'status': 'queued', 'job_id': job.id}), 202 + + +@previews_bp.route('//previews', methods=['POST']) +@developer_required +def create_preview(app_id): + """Queue a pinned same-repository preview (also supports API-key CI callers).""" + app = require_app(app_id, write=True, conceal=True) + data = json_object() + try: + job = enqueue(app_id, validate_request(app, data)) + except (PreviewError, TypeError, ValueError) as exc: + raise ValidationError(str(exc) or 'Invalid preview request') from exc + return jsonify({'status': 'queued', 'job_id': job.id}), 202 diff --git a/backend/app/services/application_restore.py b/backend/app/services/application_restore.py index a3e19edb..4252780d 100644 --- a/backend/app/services/application_restore.py +++ b/backend/app/services/application_restore.py @@ -221,4 +221,6 @@ def suspend_application(app, user_id=None): app.soft_delete(user_id) app.status = 'stopped' db.session.commit() + from app.services.previews.lifecycle import cleanup_application + results['previews'] = cleanup_application(app.id) return results diff --git a/backend/app/services/preview_service.py b/backend/app/services/preview_service.py index e90d7cfc..13ca10e4 100644 --- a/backend/app/services/preview_service.py +++ b/backend/app/services/preview_service.py @@ -246,16 +246,16 @@ class PreviewService: # ------------------------------------------------------------------ # @classmethod - def create_preview(cls, app, pr_payload, request_payload=None): + def create_preview(cls, app, pr_payload, request_payload=None, log_callback=None): from app.services.deploy_lock import deploy_lock with deploy_lock(app.id, 'preview deploy'): from app.services.previews.requests import current if request_payload and not current(request_payload): return {'skipped': True, 'reason': 'superseded'} - return cls._create_preview_locked(app, pr_payload) + return cls._create_preview_locked(app, pr_payload, manual=not request_payload, log_callback=log_callback) @classmethod - def _create_preview_locked(cls, app, pr_payload): + def _create_preview_locked(cls, app, pr_payload, manual=True, log_callback=None): """Create (or update-in-place) a preview for a PR. Best-effort. Writes/updates an :class:`ApplicationPreview` row, renders the domain, @@ -290,6 +290,8 @@ class PreviewService: preview = ApplicationPreview(application_id=app.id, pr_number=pr_number) db.session.add(preview) + if manual: + preview.requested_action = 'create' preview.branch = branch preview.pr_title = pr_title preview.commit_sha = commit_sha @@ -304,7 +306,7 @@ class PreviewService: db.session.commit() # Best-effort provisioning — degrade gracefully when unavailable. - provisioned = cls._provision(app, preview) + provisioned = cls._provision(app, preview, log_callback=log_callback) if provisioned.get('unsupported'): preview.status = ApplicationPreview.STATUS_UNAVAILABLE elif provisioned.get('ok') and provisioned.get('container_ids'): @@ -326,7 +328,7 @@ class PreviewService: return {'error': str(exc)} @classmethod - def _provision(cls, app, preview): + def _provision(cls, app, preview, log_callback=None): """Best-effort real provisioning. Returns ``{'ok': bool, 'container_ids': [...]}``. WordPress delegates to its preview hook; generic runtimes have a separate @@ -350,7 +352,7 @@ class PreviewService: logger.info('WP preview provisioning unavailable: %s', exc) return {'ok': False, 'container_ids': []} from app.services.previews.provisioner import provision - return provision(app, preview, cls.get_settings(app.id)) + return provision(app, preview, cls.get_settings(app.id), log_callback=log_callback) except Exception as exc: logger.info('preview provisioning unavailable: %s', exc) return {'ok': False, 'container_ids': []} @@ -368,6 +370,11 @@ class PreviewService: return {'skipped': True, 'reason': 'superseded'} from app import db db.session.refresh(row) + if not request_payload: + import uuid + row.request_token = uuid.uuid4().hex + row.requested_action = 'destroy' + db.session.commit() return cls._destroy_preview_locked(preview_id) @classmethod @@ -380,7 +387,7 @@ class PreviewService: preview = ApplicationPreview.query.get(preview_id) if not preview: return {'error': 'preview not found'} - if preview.status == ApplicationPreview.STATUS_DESTROYED: + if preview.status == ApplicationPreview.STATUS_DESTROYED and not preview.get_runtime_state(): return preview.to_dict() app = None @@ -453,20 +460,23 @@ class PreviewService: ).all() plan = cls.reconcile(open_prs, active) - created = destroyed = updated = 0 + created = destroyed = updated = failed = 0 for pr in plan['to_create']: - cls.create_preview(app, pr) - created += 1 + result = cls.create_preview(app, pr) + created += result.get('status') == 'running' + failed += result.get('status') != 'running' for pr in plan['to_update']: - cls.create_preview(app, pr) # idempotent update-in-place - updated += 1 + result = cls.create_preview(app, pr) + updated += result.get('status') == 'running' + failed += result.get('status') != 'running' 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 + result = cls.destroy_preview(pid) + destroyed += result.get('status') == 'destroyed' + failed += result.get('status') != 'destroyed' - return {'success': True, 'created': created, - 'updated': updated, 'destroyed': destroyed} + return {'success': failed == 0, 'created': created, + 'updated': updated, 'destroyed': destroyed, 'failed': failed} except Exception as exc: logger.warning('sync_previews failed for app %s: %s', application_id, exc) return {'error': str(exc)} @@ -480,8 +490,8 @@ class PreviewService: 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 [] + prs = fn(app.id) + return prs if isinstance(prs, list) else None except Exception as exc: logger.debug('open-PR listing unavailable for app %s: %s', app.id, exc) return None @@ -517,8 +527,15 @@ class PreviewService: app = Application.query_active().filter_by( id=payload.get('application_id')).first() if not app: - return {'error': 'Service not found'} - result = cls.create_preview(app, payload.get('pr') or payload, request_payload=payload) + return {'skipped': True, 'reason': 'application_deleted'} + stream = None + if getattr(job, 'id', None): + from app.services.run_log_service import stream_for + stream = stream_for(job) + result = cls.create_preview(app, payload.get('pr') or payload, request_payload=payload, + log_callback=(lambda line: stream.log('info', line)) if stream else None) + if stream: + stream.flush() if result.get('skipped'): return result if result.get('error') or result.get('status') != 'running': @@ -539,8 +556,8 @@ class PreviewService: if payload.get('pr'): return cls._job_create(job) result = cls.sync_previews(payload.get('application_id')) - if result.get('error'): - raise RuntimeError(result['error']) + if result.get('error') or result.get('failed'): + raise RuntimeError(result.get('error') or 'Some preview operations failed') return result @classmethod diff --git a/backend/app/services/previews/lifecycle.py b/backend/app/services/previews/lifecycle.py new file mode 100644 index 00000000..81a2f018 --- /dev/null +++ b/backend/app/services/previews/lifecycle.py @@ -0,0 +1,14 @@ +"""Application deletion must not orphan preview-owned host resources.""" +from app.models.application_preview import ApplicationPreview + + +def cleanup_application(app_id): + from app.services.preview_service import PreviewService + rows = ApplicationPreview.query.filter_by(application_id=app_id).all() + failed = [] + for row in rows: + if row.status != 'destroyed' or row.get_runtime_state(): + result = PreviewService.destroy_preview(row.id) + if result.get('error'): + failed.append(row.id) + return {'success': not failed, 'failed_preview_ids': failed} diff --git a/backend/app/services/previews/provisioner.py b/backend/app/services/previews/provisioner.py index a74d905e..84d20e28 100644 --- a/backend/app/services/previews/provisioner.py +++ b/backend/app/services/previews/provisioner.py @@ -26,7 +26,7 @@ def check_domain(preview): raise PreviewError('Preview domain is already configured in nginx.') -def provision(app, preview, settings): +def provision(app, preview, settings, log_callback=None): config = GitService.get_app_config(app.id) request_token = preview.request_token try: @@ -42,11 +42,15 @@ def provision(app, preview, settings): name = identity(preview.id, state['token']) state['source'] = True runtime.save(preview, state) + if log_callback: + log_callback('Preparing an isolated checkout at the requested commit.') source.prepare(app, preview, target, config['repo_url']) state['image'] = True runtime.save(preview, state) - source.build(app, preview, target, name + ':preview') - runtime.start(app, preview, state) + source.build(app, preview, target, name + ':preview', log_callback=log_callback) + if log_callback: + log_callback('Starting preview and checking HTTP health before publishing.') + runtime.start(app, preview, state, inherit_environment=bool(settings.inherit_environment)) db.session.refresh(preview, ['request_token', 'requested_action']) db.session.refresh(app, ['deleted_at']) if app.deleted_at or preview.request_token != request_token or preview.requested_action == 'destroy': diff --git a/backend/app/services/previews/requests.py b/backend/app/services/previews/requests.py index 699f2bbd..72d0d39e 100644 --- a/backend/app/services/previews/requests.py +++ b/backend/app/services/previews/requests.py @@ -38,3 +38,23 @@ def current(payload): return False db.session.refresh(row, ['request_token']) return row.request_token == payload['request_token'] + + +def validate_request(app, data): + from types import SimpleNamespace + from app.services.preview_service import PreviewService + from app.services.git_service import GitService + from .plan import validate + settings = PreviewService.get_settings(app.id) + if not settings.enabled: + raise PreviewError('Enable previews before deploying.') + try: + number = int(data.get('pr_number')) + except (TypeError, ValueError): + raise PreviewError('A positive PR number is required.') + candidate = SimpleNamespace(pr_number=number, branch=data.get('branch'), + commit_sha=data.get('commit_sha'), + domain=PreviewService._domain_for(app, settings, number, data.get('branch'))) + validate(app, candidate, settings, GitService.get_app_config(app.id)) + return {'pr_number': number, 'branch': candidate.branch, + 'commit_sha': candidate.commit_sha, 'pr_title': data.get('pr_title')} diff --git a/backend/app/services/previews/runtime.py b/backend/app/services/previews/runtime.py index cb5cdd15..64689a5c 100644 --- a/backend/app/services/previews/runtime.py +++ b/backend/app/services/previews/runtime.py @@ -28,14 +28,13 @@ def inspect(kind, name): raise PreviewError('Cannot inspect preview resources; cleanup must be retried.') -def start(app, preview, state): +def start(app, preview, state, inherit_environment=False): name = identity(preview.id, state['token']) state['container'] = True save(preview, state) # intent before docker run, even if it partially fails env = {'SERVERKIT_PREVIEW': 'true', 'SERVERKIT_PR_NUMBER': str(preview.pr_number), 'SERVERKIT_PREVIEW_BRANCH': preview.branch} - from app.services.preview_service import PreviewService - if PreviewService.get_settings(app.id).inherit_environment: + if inherit_environment: from app.services.env_service import EnvService entries, complete = EnvService._effective_entries(app) if not complete: diff --git a/backend/app/services/previews/source.py b/backend/app/services/previews/source.py index 305114ca..b7a5f70b 100644 --- a/backend/app/services/previews/source.py +++ b/backend/app/services/previews/source.py @@ -26,9 +26,10 @@ def prepare(app, preview, target, repo_url): shutil.rmtree(target / '.git') -def build(app, preview, target, image): +def build(app, preview, target, image, log_callback=None): config = dict(BuildService.get_app_build_config(app.id) or {}) config['app_path'] = str(target) + config['dockerfile_path'] = config.get('dockerfile_path') or 'Dockerfile' method = config.get('build_method', 'auto') if method == 'auto': method = BuildService.detect_build_method(str(target))['build_method'] @@ -43,7 +44,7 @@ def build(app, preview, target, image): config['build_args'] = {} config['env_vars'] = {} result = BuildService.build_from_config( - f'preview-{preview.id}', config, image_tag=image, + f'preview-{preview.id}', config, image_tag=image, log_callback=log_callback, ) if not result.get('success'): - raise PreviewError('Preview image build failed. See the preview build logs.') + raise PreviewError('Preview image build failed. See the preview job logs.') diff --git a/backend/app/services/recycle_bin_service.py b/backend/app/services/recycle_bin_service.py index d6bbe37a..02749a9d 100644 --- a/backend/app/services/recycle_bin_service.py +++ b/backend/app/services/recycle_bin_service.py @@ -162,6 +162,10 @@ def purge(kind, record_id): return False, PURGE_NOT_FOUND if row.deleted_at is None: return False, 'record is not in the recycle bin' + if kind == 'application': + from app.services.previews.lifecycle import cleanup_application + if not cleanup_application(row.id)['success']: + return False, 'Preview cleanup is incomplete; retry purge after restoring host access.' warning = _run_purge_hook(entry, row) db.session.delete(row) db.session.commit() @@ -177,15 +181,21 @@ def purge_expired(retention_days=DEFAULT_RETENTION_DAYS): entry['model'].deleted_at.isnot(None), entry['model'].deleted_at < cutoff, ).all() + purged = 0 for row in rows: # The retention sweep is the OTHER way a row reaches the end of its # life, so it owes the same cleanup an explicit purge does — without # it, a directory is reclaimed only when someone happens to click # Purge, and never for the 30-day expiry path. + if kind == 'application': + from app.services.previews.lifecycle import cleanup_application + if not cleanup_application(row.id)['success']: + continue _run_purge_hook(entry, row) db.session.delete(row) - if rows: - counts[kind] = len(rows) + purged += 1 + if purged: + counts[kind] = purged if counts: db.session.commit() return counts diff --git a/backend/tests/test_generic_previews.py b/backend/tests/test_generic_previews.py index cc40d21e..a91e3b99 100644 --- a/backend/tests/test_generic_previews.py +++ b/backend/tests/test_generic_previews.py @@ -25,7 +25,7 @@ def host(app, monkeypatch, tmp_path): resources['calls'].append(('clone', str(path), url)) path.mkdir() (path / 'Dockerfile').write_text('FROM scratch') - def build(parent, preview, path, image): + def build(parent, preview, path, image, **kwargs): resources['calls'].append(('build', image)) resources['images'].add(image) monkeypatch.setattr(source, 'prepare', prepare) @@ -192,8 +192,8 @@ def test_close_during_build_cleans_up_without_publishing(host, monkeypatch): parent, resources = host monkeypatch.setattr(JobService, 'enqueue', lambda *a, **kw: None) original = source.build - def build(*args): - original(*args) + def build(*args, **kwargs): + original(*args, **kwargs) enqueue(parent.id, PR, action='destroy') monkeypatch.setattr(source, 'build', build) result = PreviewService.create_preview(parent, PR) @@ -206,3 +206,165 @@ def test_cleanup_paths_cannot_escape(tmp_path): workspace(tmp_path, 1, '../escape') with pytest.raises(PreviewError): identity(-1, 'a' * 32) + + +def test_failed_cleanup_blocks_purge_and_retention_sweep(host, monkeypatch): + from datetime import datetime, timedelta + from app.services import recycle_bin_service + parent, resources = host + result = PreviewService.create_preview(parent, PR) + parent.deleted_at = datetime.utcnow() - timedelta(days=90) + db.session.commit() + monkeypatch.setattr(runtime.DockerService, 'remove_container', lambda *a, **kw: {'success': False}) + ok, reason = recycle_bin_service.purge('application', parent.id) + assert not ok and 'Preview cleanup' in reason + assert db.session.get(ApplicationPreview, result['id']).get_runtime_state() + counts = recycle_bin_service.purge_expired() + assert counts.get('application', 0) == 0 + assert resources['containers'] + + +def test_environment_inheritance_is_opt_in(host): + from app.services.env_service import EnvService + parent, resources = host + EnvService.set_env_var(parent.id, 'DATABASE_URL', 'production-credential', is_secret=True) + PreviewService.create_preview(parent, PR) + run = [call[1] for call in resources['calls'] if call[0] == 'run'][-1] + assert 'DATABASE_URL' not in run['env'] + PreviewService.enable_previews(parent.id, {'inherit_environment': True}) + PreviewService.create_preview(parent, PR) + run = [call[1] for call in resources['calls'] if call[0] == 'run'][-1] + assert run['env']['DATABASE_URL'] == 'production-credential' + + +def test_nginx_reload_failure_keeps_runtime_and_failed_status(host, monkeypatch): + parent, resources = host + result = PreviewService.create_preview(parent, PR) + monkeypatch.setattr(runtime.NginxService, 'disable_site', lambda _: {'success': False}) + assert PreviewService.destroy_preview(result['id']).get('error') + row = db.session.get(ApplicationPreview, result['id']) + assert row.get_runtime_state()['vhost'] + assert row.deleted_at is None and resources['containers'] + + +def test_container_daemon_outage_is_not_treated_as_already_removed(host, monkeypatch): + parent, resources = host + result = PreviewService.create_preview(parent, PR) + monkeypatch.setattr(runtime.DockerService, 'run', lambda *a, **kw: {'success': False, 'error': 'daemon unavailable'}) + assert PreviewService.destroy_preview(result['id']).get('error') + assert db.session.get(ApplicationPreview, result['id']).get_runtime_state()['container'] + + +def test_api_queues_without_building_and_requires_app_write(host, client, monkeypatch): + from factories import headers_for, make_user + from app.models import User + from app.jobs.service import JobService + parent, resources = host + owner = db.session.get(User, parent.user_id) + queued = [] + monkeypatch.setattr(JobService, 'enqueue', lambda *a, **kw: queued.append((a, kw)) or SimpleNamespace(id='job-id')) + url = f'/api/v1/apps/{parent.id}/previews' + result = client.post(url, headers=headers_for(owner), json=PR) + assert result.status_code == 202 and result.json['job_id'] == 'job-id' + assert not resources['calls'] and len(queued) == 1 + assert client.post(url, headers=headers_for(owner), json={**PR, 'commit_sha': '-bad'}).status_code == 400 + stranger = make_user(db, role='developer') + assert client.post(url, headers=headers_for(stranger), json=PR).status_code in (403, 404) + viewer = make_user(db, role='viewer') + assert client.post(url, headers=headers_for(viewer), json=PR).status_code == 403 + assert len(queued) == 1 + + +def test_source_checkout_is_pinned_and_removes_git_credentials(tmp_path, monkeypatch): + calls = [] + target = tmp_path / 'checkout' + def clone(path, url, branch): + (target / '.git').mkdir(parents=True) + (target / '.git' / 'config').write_text('credential') + calls.append(('clone', path, url, branch)) + return {'success': True} + monkeypatch.setattr(source.GitService, 'clone_repository', clone) + monkeypatch.setattr(source, 'run_checked', lambda argv, **kw: calls.append(argv) or {'success': True}) + source.prepare(None, SimpleNamespace(**PR), target, 'https://example.test/repo.git') + assert any('--is-ancestor' in call and SHA in call for call in calls) + assert any('--detach' in call and SHA in call for call in calls) + assert not (target / '.git').exists() + + +def test_build_uses_isolated_namespace_and_existing_dispatcher(tmp_path, monkeypatch): + from app.services.build_service import BuildService + calls = [] + config = {'app_path': '/production', 'build_method': 'dockerfile', + 'env_vars': {'SECRET': 'private'}, 'build_args': {'TOKEN': 'private'}} + monkeypatch.setattr(BuildService, 'get_app_build_config', lambda _: config) + monkeypatch.setattr(BuildService, 'build_from_config', lambda *a, **kw: calls.append((a, kw)) or {'success': True}) + source.build(SimpleNamespace(id=1), SimpleNamespace(id=2), tmp_path, 'isolated:tag') + args, kwargs = calls[0] + assert args[0] == 'preview-2' + assert args[1]['app_path'] == str(tmp_path) + assert args[1]['env_vars'] == args[1]['build_args'] == {} + assert config['app_path'] == '/production' and config['env_vars']['SECRET'] == 'private' + assert kwargs['image_tag'] == 'isolated:tag' + + +def test_preview_migration_round_trip_and_existing_schema(): + import importlib.util + from pathlib import Path + import sqlalchemy as sa + from alembic.migration import MigrationContext + from alembic.operations import Operations + file = Path(__file__).parents[1] / 'migrations/versions/111_preview_runtime.py' + spec = importlib.util.spec_from_file_location('preview_migration', file) + migration = importlib.util.module_from_spec(spec) + spec.loader.exec_module(migration) + engine = sa.create_engine('sqlite://') + with engine.begin() as connection: + connection.exec_driver_sql('CREATE TABLE application_previews (id INTEGER PRIMARY KEY)') + connection.exec_driver_sql('CREATE TABLE application_preview_settings (application_id INTEGER PRIMARY KEY)') + connection.exec_driver_sql('INSERT INTO application_preview_settings VALUES (1)') + with Operations.context(MigrationContext.configure(connection)): + migration.upgrade() + migration.upgrade() + assert connection.exec_driver_sql('SELECT inherit_environment FROM application_preview_settings').scalar() == 0 + assert 'runtime_state' in {c['name'] for c in sa.inspect(connection).get_columns('application_previews')} + migration.downgrade() + assert {c['name'] for c in sa.inspect(connection).get_columns('application_previews')} == {'id'} + + +def test_partial_docker_run_is_compensated(host, monkeypatch): + parent, resources = host + original = runtime.DockerService.run_container + def partial(**kwargs): + original(**kwargs) + return {'success': False, 'error': 'start failed after create'} + monkeypatch.setattr(runtime.DockerService, 'run_container', partial) + result = PreviewService.create_preview(parent, PR) + assert result['status'] == 'failed' + assert not resources['containers'] and not resources['images'] + + +def test_partial_nginx_publish_is_compensated(host, monkeypatch): + parent, resources = host + original = runtime.NginxService.create_site + def partial(*args, **kwargs): + original(*args, **kwargs) + return {'success': False} + monkeypatch.setattr(runtime.NginxService, 'create_site', partial) + result = PreviewService.create_preview(parent, PR) + assert result['status'] == 'failed' + assert not resources['routes'] and not resources['containers'] + + +def test_purge_cleans_preview_before_deleting_ownership_record(host, monkeypatch): + from datetime import datetime + from app.services import recycle_bin_service + parent, resources = host + result = PreviewService.create_preview(parent, PR) + parent.deleted_at = datetime.utcnow() + db.session.commit() + # Parent host lifecycle has its own suite; only previews touch Docker here. + monkeypatch.setattr(recycle_bin_service, '_run_purge_hook', lambda *a: None) + ok, warning = recycle_bin_service.purge('application', parent.id) + assert ok, warning + assert not resources['containers'] and not resources['images'] + assert db.session.get(ApplicationPreview, result['id']) is None diff --git a/backend/tests/test_preview_boundaries.py b/backend/tests/test_preview_boundaries.py new file mode 100644 index 00000000..245217eb --- /dev/null +++ b/backend/tests/test_preview_boundaries.py @@ -0,0 +1,42 @@ +"""Keep preview planning pure and host effects out of its orchestration facade.""" +import ast +from pathlib import Path +import pytest + +ROOT = Path(__file__).parents[1] / 'app/services/previews' + + +def imports(text): + for node in ast.walk(ast.parse(text)): + if isinstance(node, ast.Import): + yield from (alias.name for alias in node.names) + elif isinstance(node, ast.ImportFrom): + yield node.module or '' + + +def forbidden(module, imported): + if imported == 'subprocess' or imported.endswith('deployment_service'): + return True # shared runners/builders, never the parent-app deploy pipeline + if module == 'plan.py': + return imported.startswith(('flask', 'app.models', 'shutil', 'os')) + return False + + +@pytest.mark.parametrize('name,ceiling', [ + ('plan.py', 100), ('source.py', 120), ('runtime.py', 200), + ('provisioner.py', 120), ('requests.py', 120), ('lifecycle.py', 80), +]) +def test_preview_owners_stay_small_and_use_existing_host_services(name, ceiling): + text = (ROOT / name).read_text(encoding='utf-8') + assert len(text.splitlines()) <= ceiling + assert not [value for value in imports(text) if forbidden(name, value)] + + +@pytest.mark.parametrize('module,statement', [ + ('plan.py', 'from app.models import Application'), + ('plan.py', 'import shutil'), + ('runtime.py', 'import subprocess'), + ('provisioner.py', 'from app.services.deployment_service import DeploymentService'), +]) +def test_preview_boundary_guard_rejects_crossings(module, statement): + assert any(forbidden(module, value) for value in imports(statement)) diff --git a/backend/tests/test_real_generic_preview.py b/backend/tests/test_real_generic_preview.py new file mode 100644 index 00000000..09efc0c3 --- /dev/null +++ b/backend/tests/test_real_generic_preview.py @@ -0,0 +1,93 @@ +"""Opt-in real Git checkout, Docker build/runtime and HTTP health-gate lifecycle. + +SERVERKIT_REAL_PREVIEWS=1 pytest tests/test_real_generic_preview.py +Only nginx publication is replaced: this test must not alter the host's sites. +""" +import functools +import os +import subprocess +import threading +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer +from urllib.request import urlopen +import pytest +from app import db +from app.models.application_preview import ApplicationPreview +from app.services.preview_service import PreviewService +from app.services.previews import runtime +from app.services.git_service import GitService +from app.services.build_service import BuildService +from test_previews import _mk_app + +pytestmark = pytest.mark.skipif(os.environ.get('SERVERKIT_REAL_PREVIEWS') != '1', + reason='opt-in real Docker preview smoke') + + +def test_real_checkout_build_redeploy_http_and_cleanup(app, tmp_path, monkeypatch): + def git(*args, cwd=None): + return subprocess.run(['git', *args], cwd=cwd, check=True, capture_output=True, + text=True, timeout=60).stdout.strip() + repo = tmp_path / 'source' + repo.mkdir() + git('init', '-b', 'preview', cwd=repo) + git('config', 'user.name', 'Preview Test', cwd=repo) + git('config', 'user.email', 'preview@test.invalid', cwd=repo) + (repo / 'Dockerfile').write_text('FROM busybox:1.36\nCOPY index.html /www/index.html\nCMD ["httpd", "-f", "-p", "8400", "-h", "/www"]\n') + (repo / 'index.html').write_text('first-preview-commit') + git('add', '.', cwd=repo) + git('commit', '-m', 'first', cwd=repo) + first = git('rev-parse', 'HEAD', cwd=repo) + (repo / 'index.html').write_text('second-preview-commit') + git('commit', '-am', 'second', cwd=repo) + second = git('rev-parse', 'HEAD', cwd=repo) + remote = tmp_path / 'remote.git' + git('clone', '--bare', str(repo), str(remote)) + git('update-server-info', cwd=remote) + handler = functools.partial(SimpleHTTPRequestHandler, directory=str(tmp_path)) + server = ThreadingHTTPServer(('127.0.0.1', 0), handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + monkeypatch.setattr(runtime, 'ROOT', tmp_path / 'previews') + monkeypatch.setattr(BuildService, 'BUILD_LOG_DIR', str(tmp_path / 'logs')) + monkeypatch.setattr(BuildService, 'get_app_build_config', lambda _: {'build_method': 'dockerfile'}) + monkeypatch.setattr(GitService, 'get_app_config', lambda _: {'repo_url': f'http://127.0.0.1:{server.server_port}/remote.git'}) + monkeypatch.setattr(runtime.NginxService, 'list_sites', lambda: []) + routes = {} + def publish(name, kind, domains, **kwargs): + rendered = runtime.NginxService.render_site_config(name, kind, domains, **kwargs) + assert rendered['success'] + routes[name] = rendered['config'] + return {'success': True} + monkeypatch.setattr(runtime.NginxService, 'create_site', publish) + monkeypatch.setattr(runtime.NginxService, 'disable_site', lambda _: {'success': True}) + # delete returns a dict, independent of the removed config text. + def delete(name): + routes.pop(name, None) + return {'success': True} + monkeypatch.setattr(runtime.NginxService, 'delete_site', delete) + monkeypatch.setattr(runtime.SiteDomainService, 'covering_base', lambda _: None) + try: + with app.app_context(): + parent = _mk_app(name='real-preview') + PreviewService.enable_previews(parent.id, {'enabled': True, 'domain_template': 'pr-{pr_number}.example.test'}) + preview_id = None + try: + for sha, expected in [(first, 'first-preview-commit'), (second, 'second-preview-commit')]: + result = PreviewService.create_preview(parent, {'pr_number': 17, 'branch': 'preview', 'commit_sha': sha}) + preview_id = result.get('id') + assert result['status'] == 'running', result + row = db.session.get(ApplicationPreview, preview_id) + state = row.get_runtime_state() + with urlopen(f"http://127.0.0.1:{state['port']}", timeout=10) as response: + assert response.read().decode() == expected + assert str(state['port']) in next(iter(routes.values())) + assert PreviewService.destroy_preview(preview_id)['status'] == 'destroyed' + assert not routes and not list(runtime.ROOT.iterdir()) + assert runtime.inspect('container', runtime.identity(preview_id, state['token'])) is None + assert runtime.inspect('image', runtime.identity(preview_id, state['token']) + ':preview') is None + finally: + if preview_id: + PreviewService.destroy_preview(preview_id) + finally: + server.shutdown() + server.server_close() + thread.join(timeout=5) diff --git a/docs/CORE_BOUNDARIES.md b/docs/CORE_BOUNDARIES.md index b679d26b..5485f556 100644 --- a/docs/CORE_BOUNDARIES.md +++ b/docs/CORE_BOUNDARIES.md @@ -152,11 +152,11 @@ both non-Compose apps and unreadable Compose files, so that case is explicitly labelled as unfiltered configuration. A preview can be advertised as running only after an explicit successful -provider result with runtime IDs. Generic manifest configuration generation is -not deployment and reports `unavailable`. Legacy running rows without IDs are -projected as unavailable without mutating them on read. Only running previews -with recorded IDs expose a URL. These checks establish provisioning evidence; -they do not claim live container health or validate DNS reachability. +provider result with runtime IDs. Generic previews additionally gate on HTTP +health before publishing nginx. Legacy running rows without IDs are projected +as unavailable without mutating them on read. The generic URL scheme reflects +whether a covering single-label wildcard certificate was actually selected; +otherwise it is HTTP. DNS must point to the preview host. Regression coverage: `test_effective_env.py`, `test_env_vars_api.py`, `test_compose_env_overlay.py`, `test_previews.py`, and @@ -164,3 +164,57 @@ Regression coverage: `test_effective_env.py`, `test_env_vars_api.py`, check runs in frontend CI and covers service switching with late replies, failed discovery, masking, incomplete results, retry, the local editor, and preview link/toast behavior. + + +## Generic preview deployment ownership + +`services/previews/` separates six concerns: + +- `plan.py`: pure eligibility, resource identities and path containment. +- `requests.py`: short request reservations and queued desired state. PR closes + supersede queued/in-flight creates; old jobs cannot revive a newer request. +- `source.py`: independent Git clone, exact reachable commit checkout, credential + metadata removal, and delegation to `BuildService.build_from_config`. +- `runtime.py`: persisted resource intent, Docker start/inspection/cleanup, + existing HTTP health gate, and nginx publication/removal. +- `provisioner.py`: validation, sequencing and compensation on failure. +- `lifecycle.py`: cleanup when deleting or purging the parent application. + +Generic support currently means local Git-backed single-container apps using +Dockerfiles or container buildpacks with nginx ingress. Compose, remote targets, +proxy-stack ingress, and host-command builds are rejected. Fork commits must +be reachable from the selected branch in the parent's configured repository; +arbitrary fork repositories are not fetched. Redeploy is stop/recreate, not a +zero-downtime switch. Signed PR update webhooks deploy their supplied commit; +full open-PR discovery remains unavailable and fails without deleting anything. + +Production deployment records, source trees, container identities, ports, +volumes, networks and build configuration are never repurposed. Each preview +attempt has a random generation name, an isolated image and checkout, and a +Docker-assigned loopback host port. Parent build secrets are not copied. +Runtime environment inheritance defaults off and is an explicit setting; when +on, it can grant preview code access to production services. Use only trusted +PR code and credentials appropriate to its intended environment. + +Migration `111_preview_runtime` records the cleanup ledger, request token, +desired action, error and environment opt-in. Persist each resource intent +before touching the host, and clear it only after successful cleanup. Docker +inspection failure is not evidence that a resource is gone. Failed deletion +retains the ledger and reports failure; retry deletion to finish. Application +purge/retention must keep the parent row when preview cleanup fails so the +ownership record is not lost. Interrupted builds can likewise be deleted or +redeployed using their persisted ledger. + +Create, redeploy and delete return 202 with a unified job ID; build output goes +to the existing Jobs log stream. The new create endpoint deliberately supports +API-key CI automation through `developer_required`, plus app write access. +Existing JWT-only endpoints retain their authentication boundary. UI refresh is +manual and queued deletion never claims cleanup already finished. + +Run `test_generic_previews.py`, `test_preview_boundaries.py`, existing preview, +buildpack, recycle-bin, authorization and migration suites. For a disposable +real Git/Docker smoke run, set `SERVERKIT_REAL_PREVIEWS=1` and run +`tests/test_real_generic_preview.py`: it builds two exact commits, checks their +HTTP responses and cleanup, while rendering rather than installing nginx sites. +The existing frontend browser check covers the pinned create form, environment +opt-in, and queued deletion. No new UI styling system is introduced. diff --git a/docs/MIGRATION_INVENTORY.md b/docs/MIGRATION_INVENTORY.md index 1709215c..4b257b36 100644 --- a/docs/MIGRATION_INVENTORY.md +++ b/docs/MIGRATION_INVENTORY.md @@ -16,7 +16,7 @@ debt. Regenerate with `python scripts/generate-migration-inventory.py`. | Routes on bare @jwt_required() | auth_required() / role decorators | 598 | 598 | REGISTERED EXCEPTION: JWT-only is the deliberate default; conversion grants API-key access and happens per route, on decision | | HTTP statuses chosen by sniffing error text | typed errors from app.exceptions | 0 | 0 | INVARIANT at 0 - migration completed 2026-08-19 | | API crashes swallowed without recording | app.error_reporting | 0 | 0 | INVARIANT at 0 | -| Hand-shaped {'error': ...} bodies in app/api | typed errors + the global handler | 848 | 850 | migrate when touched; new endpoints raise | +| Hand-shaped {'error': ...} bodies in app/api | typed errors + the global handler | 849 | 850 | migrate when touched; new endpoints raise | | Raw subprocess calls outside the runners | app/utils/system.py runners | 23 | 23 | migrate when touched | | Controller-boundary violations (routes doing service work) | service layer extraction | 477 | 477 | migrate when touched (first-wave ratchet) | | raw api.* calls in pages/ | E1: useServerQuery/useServerMutation | 374 | 398 | migrate when touched | From ada1276d39a0b99bc82d2c0e28cf96bbc1649993 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 06:23:06 -0400 Subject: [PATCH 19/34] feat: add pinned preview deployment controls and queued lifecycle feedback --- .../scripts/effective-environment-browser.mjs | 17 +++++++++ .../components/previews/PreviewCreateForm.jsx | 31 +++++++++++++++ .../src/components/previews/PreviewList.jsx | 38 ++++++++++++++++--- frontend/src/i18n/locales/ar.json | 1 - frontend/src/i18n/locales/bn.json | 1 - frontend/src/i18n/locales/de.json | 1 - frontend/src/i18n/locales/en.json | 14 ++++++- frontend/src/i18n/locales/es.json | 1 - frontend/src/i18n/locales/fr.json | 1 - frontend/src/i18n/locales/id.json | 1 - frontend/src/i18n/locales/it.json | 1 - frontend/src/i18n/locales/ko.json | 1 - frontend/src/i18n/locales/pl.json | 1 - frontend/src/i18n/locales/pt.json | 1 - frontend/src/i18n/locales/ru.json | 1 - frontend/src/i18n/locales/th.json | 1 - frontend/src/i18n/locales/tr.json | 1 - frontend/src/i18n/locales/vi.json | 1 - frontend/src/i18n/locales/zh-Hans.json | 1 - frontend/src/i18n/locales/zh-Hant.json | 1 - frontend/src/services/api/previews.js | 4 ++ 21 files changed, 97 insertions(+), 23 deletions(-) create mode 100644 frontend/src/components/previews/PreviewCreateForm.jsx diff --git a/frontend/scripts/effective-environment-browser.mjs b/frontend/scripts/effective-environment-browser.mjs index 80684d69..7883d99d 100644 --- a/frontend/scripts/effective-environment-browser.mjs +++ b/frontend/scripts/effective-environment-browser.mjs @@ -24,6 +24,9 @@ window.testApi={ getPreviews:()=>Promise.resolve({previews:[{id:1,pr_number:1,status:'unavailable',domain:'unavailable.test',url:'https://unavailable.test'},{id:2,pr_number:2,status:'running',domain:'running.test',url:'https://running.test'}]}), getPreviewSettings:()=>Promise.resolve({enabled:true}), redeployPreview:()=>Promise.resolve({status:'unavailable'}), + createPreview:(id,pr)=>{window.created=pr;return Promise.resolve({status:'queued',job_id:'job'});}, + destroyPreview:()=>Promise.resolve({status:'queued'}), + updatePreviewSettings:(id,patch)=>{window.settingsPatch=patch;return Promise.resolve({enabled:true,...patch});}, }; createRoot(document.getElementById('root')).render({location.search==='?preview'?:}); `; @@ -112,6 +115,20 @@ try { assert.equal(await page.evaluate(()=>window.toasts.some(x=>x.startsWith('SUCCESS:'))),false); assert.deepEqual(errors,[]); console.log('PASS previews: unavailable links suppressed and unsuccessful redeploy has no success toast'); + await page.getByLabel('PR number', {exact:true}).fill('23'); + await page.getByLabel('Repository branch', {exact:true}).fill('feature/test'); + await page.getByLabel('Full commit SHA', {exact:true}).fill('a'.repeat(40)); + await page.getByRole('button',{name:'Deploy preview',exact:true}).click(); + await page.waitForFunction(()=>window.created?.pr_number===23); + assert.deepEqual(await page.evaluate(()=>window.created),{pr_number:23,branch:'feature/test',commit_sha:'a'.repeat(40)}); + await page.getByRole('switch',{name:/Inherit application environment/}).click(); + await page.waitForFunction(()=>window.settingsPatch?.inherit_environment===true); + await page.getByRole('button',{name:'Delete',exact:true}).first().click(); + await page.getByRole('alertdialog').getByRole('button',{name:'Delete',exact:true}).click(); + await page.waitForFunction(()=>window.toasts.some(t=>t.includes('deletion queued'))); + assert.deepEqual(errors,[]); + console.log('PASS previews: pinned create form, explicit inheritance and queued deletion'); + } finally { await browser?.close(); await server.close(); diff --git a/frontend/src/components/previews/PreviewCreateForm.jsx b/frontend/src/components/previews/PreviewCreateForm.jsx new file mode 100644 index 00000000..283d856e --- /dev/null +++ b/frontend/src/components/previews/PreviewCreateForm.jsx @@ -0,0 +1,31 @@ +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Input } from '../ui/input'; +import FormField from '../FormField'; +import { Button } from '../ui/button'; + +export default function PreviewCreateForm({ onCreate, busy }) { + const { t } = useTranslation(); + const [number, setNumber] = useState(''); + const [branch, setBranch] = useState(''); + const [sha, setSha] = useState(''); + async function submit(event) { + event.preventDefault(); + await onCreate({ pr_number: Number(number), branch: branch.trim(), commit_sha: sha.trim() }); + } + return
+

{t('app.previewList.pinnedHelp', 'Deploy a branch from this application’s configured repository at an exact commit. Signed PR webhooks can also create and remove previews automatically.')}

+
+ + setNumber(e.target.value)} /> + + + setBranch(e.target.value)} /> + + + setSha(e.target.value)} /> + +
+ +
; +} diff --git a/frontend/src/components/previews/PreviewList.jsx b/frontend/src/components/previews/PreviewList.jsx index 0f1f649b..01d5abaf 100644 --- a/frontend/src/components/previews/PreviewList.jsx +++ b/frontend/src/components/previews/PreviewList.jsx @@ -6,6 +6,7 @@ import api from '../../services/api'; import { useToast } from '../../contexts/useToast.js'; import { useConfirm } from '../../hooks/useConfirm'; import EmptyState from '../EmptyState'; +import PreviewCreateForm from './PreviewCreateForm'; import { Pill, serviceStatusKind } from '../ds'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; @@ -27,6 +28,7 @@ const PreviewList = ({ appId }) => { const [saving, setSaving] = useState(false); const [syncing, setSyncing] = useState(false); const [busyId, setBusyId] = useState(null); + const [creating, setCreating] = useState(false); const [template, setTemplate] = useState(DEFAULT_TEMPLATE); const load = useCallback(async () => { @@ -101,6 +103,19 @@ const PreviewList = ({ appId }) => { } } + async function handleCreate(pr) { + setCreating(true); + try { + await api.createPreview(appId, pr); + toast?.success?.(t('app.previewList.queued', 'Preview deployment queued. Refresh for status; execution details are in Jobs.')); + await load(); + } catch (err) { + toastError(toast, t('app.previewList.createFailed', 'Could not queue the preview.'), err); + } finally { + setCreating(false); + } + } + async function handleDestroy(preview) { const ok = await confirm({ title: t('app.previewList.destroyPreview', 'Delete preview'), @@ -111,8 +126,10 @@ const PreviewList = ({ appId }) => { if (!ok) return; setBusyId(preview.id); try { - await api.destroyPreview(appId, preview.id); - toast?.success?.(t('app.previewList.previewForPrDestroyed', 'Preview for PR #{{prnumber}} deleted', { prnumber: preview.pr_number })); + const result = await api.destroyPreview(appId, preview.id); + toast?.success?.(result.status === 'queued' + ? t('app.previewList.deletionQueued', 'Preview deletion queued. Refresh for status.') + : t('app.previewList.previewForPrDestroyed', 'Preview for PR #{{prnumber}} deleted', { prnumber: preview.pr_number })); await load(); } catch (err) { toastError(toast, t('app.previewList.destroyFailed', "Couldn't delete the preview."), err); @@ -137,7 +154,7 @@ const PreviewList = ({ appId }) => {

{t('app.previewList.prPreviewEnvironments', 'PR preview environments')}

- {t('app.previewList.supportedProvisioners', 'Preview deployment requires a supported runtime provisioner. Generic application previews are not available yet. A domain alone does not mean a preview is deployed.')} + {t('app.previewList.genericSupport', 'Generic previews support local Git-backed Dockerfile and container-buildpack apps with nginx. Compose, remote targets and host-command builds are not supported. Configure preview DNS to point at this server.')}

@@ -179,9 +196,19 @@ const PreviewList = ({ appId }) => { )}
+ {enabled && <> +
+ + saveSettings({ inherit_environment })} /> +
+ + } + {/* Active previews */}
- {p.status === 'unavailable' && ( + {p.status_reason && p.status !== 'running' &&

{p.status_reason}

} + {p.status === 'unavailable' && !p.status_reason && (

{t('app.previewList.noRuntime', 'No provisioned runtime is recorded for this preview. Its URL is unavailable.')}

diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json index 5b56511f..79553fa5 100644 --- a/frontend/src/i18n/locales/ar.json +++ b/frontend/src/i18n/locales/ar.json @@ -4431,7 +4431,6 @@ "enabled": "مفعّل", "loadingPreviews": "جارٍ تحميل المعاينات...", "noActivePreviews": "لا توجد معاينات نشطة", - "openAPullRequestToSpin": "افتح طلب سحب لتدوير المعاينة، أو قم بالمزامنة للتوفيق الآن.", "placeholders": "العناصر النائبة:", "pr": "العلاقات العامة #", "prPreviewEnvironments": "بيئات معاينة العلاقات العامة", diff --git a/frontend/src/i18n/locales/bn.json b/frontend/src/i18n/locales/bn.json index d2ddb562..e509e9e5 100644 --- a/frontend/src/i18n/locales/bn.json +++ b/frontend/src/i18n/locales/bn.json @@ -4431,7 +4431,6 @@ "enabled": "সক্রিয়", "loadingPreviews": "পূর্বরূপ লোড হচ্ছে...", "noActivePreviews": "কোন সক্রিয় পূর্বরূপ", - "openAPullRequestToSpin": "একটি পূর্বরূপ স্পিন আপ করার জন্য একটি পুল অনুরোধ খুলুন, অথবা এখনই পুনর্মিলন করতে সিঙ্ক করুন৷", "placeholders": "স্থানধারক:", "pr": "পিআর #", "prPreviewEnvironments": "পিআর প্রিভিউ পরিবেশ", diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.json index 644f8ebf..b4e766af 100644 --- a/frontend/src/i18n/locales/de.json +++ b/frontend/src/i18n/locales/de.json @@ -4431,7 +4431,6 @@ "enabled": "Aktiviert", "loadingPreviews": "Vorschau wird geladen...", "noActivePreviews": "Keine aktiven Vorschauen", - "openAPullRequestToSpin": "Öffnen Sie eine Pull-Anfrage, um eine Vorschau zu starten, oder synchronisieren Sie sie, um sie jetzt abzugleichen.", "placeholders": "Platzhalter:", "pr": "PR-Nr.", "prPreviewEnvironments": "PR-Vorschauumgebungen", diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json index bab1eaf9..db340737 100644 --- a/frontend/src/i18n/locales/en.json +++ b/frontend/src/i18n/locales/en.json @@ -4420,8 +4420,14 @@ }, "previewList": { "activePreviews": "Active previews", + "branch": "Repository branch", + "commit": "Full commit SHA", "couldNotLoadPrPreviews": "Couldn't load PR previews.", "couldNotSaveSettings": "Couldn't save the settings.", + "createFailed": "Could not queue the preview.", + "createOrWebhook": "Deploy a pinned branch above, or connect a signed PR webhook to this application.", + "createPreview": "Deploy preview", + "deletionQueued": "Preview deletion queued. Refresh for status.", "destroy": "Delete", "destroyFailed": "Couldn't delete the preview.", "destroyPreview": "Delete preview", @@ -4429,21 +4435,25 @@ "domainTemplate": "Domain template", "enablePrPreviewsAboveToStart": "Enable PR previews above to start deploying preview environments.", "enabled": "Enabled", + "genericSupport": "Generic previews support local Git-backed Dockerfile and container-buildpack apps with nginx. Compose, remote targets and host-command builds are not supported. Configure preview DNS to point at this server.", + "inheritEnv": "Inherit application environment (may grant access to production databases and services)", "loadingPreviews": "Loading previews…", "noActivePreviews": "No active previews", "noRuntime": "No provisioned runtime is recorded for this preview. Its URL is unavailable.", - "openAPullRequestToSpin": "Open a pull request to spin up a preview, or sync to reconcile now.", + "pinnedHelp": "Deploy a branch from this application’s configured repository at an exact commit. Signed PR webhooks can also create and remove previews automatically.", "placeholders": "Placeholders:", "pr": "PR #", + "prNumber": "PR number", "prPreviewEnvironments": "PR preview environments", "previewForPrDestroyed": "Preview for PR #{{prnumber}} deleted", "previewNotDeployed": "The preview was not deployed. Review its status below.", "previewSettingsSaved": "Preview settings saved", + "queued": "Preview deployment queued. Refresh for status; execution details are in Jobs.", "reconciledPreviewsAgainstOpenPrs": "Reconciled previews against open PRs", "redeploy": "Redeploy", "redeployFailed": "Couldn't redeploy the preview.", "redeployingPreviewForPr": "Redeploying preview for PR #{{prnumber}}", - "supportedProvisioners": "Preview deployment requires a supported runtime provisioner. Generic application previews are not available yet. A domain alone does not mean a preview is deployed.", + "refresh": "Refresh status", "syncFailed": "Couldn't sync previews.", "syncWithOpenPrs": "Sync with open PRs", "tearDownThePreviewEnvironmentFor": "Tear down the preview environment for PR #{{prnumber}}? This removes its temporary domain and resources." diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json index 6c2cf92c..b2b09252 100644 --- a/frontend/src/i18n/locales/es.json +++ b/frontend/src/i18n/locales/es.json @@ -4431,7 +4431,6 @@ "enabled": "Activado", "loadingPreviews": "Cargando vistas previas...", "noActivePreviews": "No hay vistas previas activas", - "openAPullRequestToSpin": "Abre un pull request para crear una vista previa, o sincroniza para reconciliar ahora.", "placeholders": "Marcadores de posición:", "pr": "PR #", "prPreviewEnvironments": "Entornos de vista previa de PR", diff --git a/frontend/src/i18n/locales/fr.json b/frontend/src/i18n/locales/fr.json index c49546e5..74d98fba 100644 --- a/frontend/src/i18n/locales/fr.json +++ b/frontend/src/i18n/locales/fr.json @@ -4431,7 +4431,6 @@ "enabled": "Activé", "loadingPreviews": "Chargement des aperçus...", "noActivePreviews": "Aucun aperçu actif", - "openAPullRequestToSpin": "Ouvrez une pull request pour afficher un aperçu ou synchronisez pour réconcilier maintenant.", "placeholders": "Espaces réservés :", "pr": "RP #", "prPreviewEnvironments": "Environnements de prévisualisation des relations publiques", diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.json index d4ade2a0..508006ff 100644 --- a/frontend/src/i18n/locales/id.json +++ b/frontend/src/i18n/locales/id.json @@ -4431,7 +4431,6 @@ "enabled": "Aktif", "loadingPreviews": "Memuat pratinjau...", "noActivePreviews": "Tidak ada pratinjau aktif", - "openAPullRequestToSpin": "Buka permintaan tarik untuk menjalankan pratinjau, atau sinkronkan untuk merekonsiliasi sekarang.", "placeholders": "Penampung:", "pr": "PR#", "prPreviewEnvironments": "Lingkungan pratinjau PR", diff --git a/frontend/src/i18n/locales/it.json b/frontend/src/i18n/locales/it.json index 63eadbd4..48e1f778 100644 --- a/frontend/src/i18n/locales/it.json +++ b/frontend/src/i18n/locales/it.json @@ -4431,7 +4431,6 @@ "enabled": "Abilitato", "loadingPreviews": "Caricamento anteprime...", "noActivePreviews": "Nessuna anteprima attiva", - "openAPullRequestToSpin": "Apri una richiesta pull per avviare un'anteprima o sincronizza per riconciliare ora.", "placeholders": "Segnaposto:", "pr": "PR n.", "prPreviewEnvironments": "Ambienti di anteprima PR", diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json index 4f6d0d57..9ac6bcce 100644 --- a/frontend/src/i18n/locales/ko.json +++ b/frontend/src/i18n/locales/ko.json @@ -4431,7 +4431,6 @@ "enabled": "활성화됨", "loadingPreviews": "미리보기 로드 중...", "noActivePreviews": "활성 미리보기 없음", - "openAPullRequestToSpin": "끌어오기 요청을 열어 미리보기를 실행하거나 동기화하여 지금 조정하세요.", "placeholders": "자리 표시자:", "pr": "홍보번호", "prPreviewEnvironments": "PR 미리보기 환경", diff --git a/frontend/src/i18n/locales/pl.json b/frontend/src/i18n/locales/pl.json index 4421ee9a..edd33525 100644 --- a/frontend/src/i18n/locales/pl.json +++ b/frontend/src/i18n/locales/pl.json @@ -4431,7 +4431,6 @@ "enabled": "Włączone", "loadingPreviews": "Ładowanie podglądów...", "noActivePreviews": "Brak aktywnych podglądów", - "openAPullRequestToSpin": "Otwórz żądanie ściągnięcia, aby wyświetlić podgląd, lub zsynchronizuj, aby teraz uzgodnić.", "placeholders": "Elementy zastępcze:", "pr": "PR#", "prPreviewEnvironments": "Środowiska podglądu PR", diff --git a/frontend/src/i18n/locales/pt.json b/frontend/src/i18n/locales/pt.json index be3f4777..fc379fc3 100644 --- a/frontend/src/i18n/locales/pt.json +++ b/frontend/src/i18n/locales/pt.json @@ -4431,7 +4431,6 @@ "enabled": "Ativado", "loadingPreviews": "Carregando visualizações...", "noActivePreviews": "Nenhuma visualização ativa", - "openAPullRequestToSpin": "Abra uma solicitação pull para iniciar uma visualização ou sincronize para reconciliar agora.", "placeholders": "Espaços reservados:", "pr": "RP#", "prPreviewEnvironments": "Ambientes de visualização de relações públicas", diff --git a/frontend/src/i18n/locales/ru.json b/frontend/src/i18n/locales/ru.json index 360cad82..094882ff 100644 --- a/frontend/src/i18n/locales/ru.json +++ b/frontend/src/i18n/locales/ru.json @@ -4431,7 +4431,6 @@ "enabled": "Включено", "loadingPreviews": "Загрузка превью...", "noActivePreviews": "Нет активных превью", - "openAPullRequestToSpin": "Откройте запрос на включение, чтобы активировать предварительный просмотр, или выполните синхронизацию, чтобы выполнить согласование прямо сейчас.", "placeholders": "Заполнители:", "pr": "PR №", "prPreviewEnvironments": "Среды предварительного просмотра PR", diff --git a/frontend/src/i18n/locales/th.json b/frontend/src/i18n/locales/th.json index 91b55e42..597ce1cd 100644 --- a/frontend/src/i18n/locales/th.json +++ b/frontend/src/i18n/locales/th.json @@ -4431,7 +4431,6 @@ "enabled": "เปิดใช้งาน", "loadingPreviews": "กำลังโหลดตัวอย่าง...", "noActivePreviews": "ไม่มีการแสดงตัวอย่างที่ใช้งานอยู่", - "openAPullRequestToSpin": "เปิดคำขอดึงเพื่อดูตัวอย่าง หรือซิงค์เพื่อปรับยอดทันที", "placeholders": "ตัวยึดตำแหน่ง:", "pr": "ประชาสัมพันธ์ #", "prPreviewEnvironments": "สภาพแวดล้อมการแสดงตัวอย่าง PR", diff --git a/frontend/src/i18n/locales/tr.json b/frontend/src/i18n/locales/tr.json index 197949be..ed79b36d 100644 --- a/frontend/src/i18n/locales/tr.json +++ b/frontend/src/i18n/locales/tr.json @@ -4431,7 +4431,6 @@ "enabled": "Etkin", "loadingPreviews": "Önizlemeler yükleniyor...", "noActivePreviews": "Etkin önizleme yok", - "openAPullRequestToSpin": "Önizlemeyi başlatmak için bir çekme isteği açın veya şimdi mutabakata varmak için senkronize edin.", "placeholders": "Yer tutucular:", "pr": "Halkla ilişkiler numarası", "prPreviewEnvironments": "PR önizleme ortamları", diff --git a/frontend/src/i18n/locales/vi.json b/frontend/src/i18n/locales/vi.json index bc676b9e..351caab8 100644 --- a/frontend/src/i18n/locales/vi.json +++ b/frontend/src/i18n/locales/vi.json @@ -4431,7 +4431,6 @@ "enabled": "Đã bật", "loadingPreviews": "Đang tải bản xem trước...", "noActivePreviews": "Không có bản xem trước nào đang hoạt động", - "openAPullRequestToSpin": "Mở yêu cầu kéo để xem trước hoặc đồng bộ hóa để điều chỉnh ngay bây giờ.", "placeholders": "Phần giữ chỗ:", "pr": "PR #", "prPreviewEnvironments": "Môi trường xem trước PR", diff --git a/frontend/src/i18n/locales/zh-Hans.json b/frontend/src/i18n/locales/zh-Hans.json index d31e4aa9..0e967f9a 100644 --- a/frontend/src/i18n/locales/zh-Hans.json +++ b/frontend/src/i18n/locales/zh-Hans.json @@ -4431,7 +4431,6 @@ "enabled": "已启用", "loadingPreviews": "正在加载预览...", "noActivePreviews": "没有活动预览", - "openAPullRequestToSpin": "打开拉取请求以启动预览,或立即同步以进行协调。", "placeholders": "占位符:", "pr": "公关号#", "prPreviewEnvironments": "PR 预览环境", diff --git a/frontend/src/i18n/locales/zh-Hant.json b/frontend/src/i18n/locales/zh-Hant.json index 8185d16d..742c9ba2 100644 --- a/frontend/src/i18n/locales/zh-Hant.json +++ b/frontend/src/i18n/locales/zh-Hant.json @@ -4431,7 +4431,6 @@ "enabled": "已啟用", "loadingPreviews": "正在載入預覽…", "noActivePreviews": "沒有活動預覽", - "openAPullRequestToSpin": "開啟 Pull Request 即可建立預覽環境,或立即同步以更新現有環境。", "placeholders": "佔位符:", "pr": "PR #", "prPreviewEnvironments": "PR 預覽環境", diff --git a/frontend/src/services/api/previews.js b/frontend/src/services/api/previews.js index ce6aa494..f0afb537 100644 --- a/frontend/src/services/api/previews.js +++ b/frontend/src/services/api/previews.js @@ -24,3 +24,7 @@ export async function redeployPreview(appId, previewId) { export async function destroyPreview(appId, previewId) { return this.request(`/apps/${appId}/previews/${previewId}`, { method: 'DELETE' }); } + +export async function createPreview(appId, pr) { + return this.request(`/apps/${appId}/previews`, { method: 'POST', body: pr }); +} From a3d64e5a52f90bad0f864a619f73f0ac01bce660 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 06:24:18 -0400 Subject: [PATCH 20/34] fix: preserve container port semantics for previews of slot deployments --- backend/app/services/preview_service.py | 2 +- backend/app/services/previews/runtime.py | 11 +++++++++-- backend/tests/test_generic_previews.py | 17 +++++++++++++++++ 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/backend/app/services/preview_service.py b/backend/app/services/preview_service.py index 13ca10e4..1ef19dca 100644 --- a/backend/app/services/preview_service.py +++ b/backend/app/services/preview_service.py @@ -485,7 +485,7 @@ class PreviewService: 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).""" + when a provider returns an empty list. Unavailable discovery returns None.""" try: from app.services.source_connection_service import SourceConnectionService fn = getattr(SourceConnectionService, 'list_open_pull_requests', None) diff --git a/backend/app/services/previews/runtime.py b/backend/app/services/previews/runtime.py index 64689a5c..50104d66 100644 --- a/backend/app/services/previews/runtime.py +++ b/backend/app/services/previews/runtime.py @@ -30,6 +30,13 @@ def inspect(kind, name): def start(app, preview, state, inherit_environment=False): name = identity(preview.id, state['token']) + container_port = app.port + if app.active_slot: + from app.models.app_slot import AppSlot + slot = AppSlot.query.filter_by(application_id=app.id, slot=app.active_slot).first() + if not slot or not slot.container_port: + raise PreviewError('The active deployment slot has no recorded container port.') + container_port = slot.container_port state['container'] = True save(preview, state) # intent before docker run, even if it partially fails env = {'SERVERKIT_PREVIEW': 'true', 'SERVERKIT_PR_NUMBER': str(preview.pr_number), @@ -41,7 +48,7 @@ def start(app, preview, state, inherit_environment=False): raise PreviewError('Inherited environment is incomplete; preview deployment stopped.') env = {**{key: value['value'] for key, value in entries.items()}, **env} result = DockerService.run_container( - image=name + ':preview', name=name, ports=[f'127.0.0.1::{app.port}'], + image=name + ':preview', name=name, ports=[f'127.0.0.1::{container_port}'], env=env, restart_policy='unless-stopped', labels={LABEL: str(preview.id)}, ) if not result.get('success'): @@ -49,7 +56,7 @@ def start(app, preview, state, inherit_environment=False): info = inspect('container', name) if not info or info.get('Config', {}).get('Labels', {}).get(LABEL) != str(preview.id): raise PreviewError('Preview container ownership could not be verified.') - bindings = info.get('NetworkSettings', {}).get('Ports', {}).get(f'{app.port}/tcp') or [] + bindings = info.get('NetworkSettings', {}).get('Ports', {}).get(f'{container_port}/tcp') or [] binding = next((b for b in bindings if b.get('HostIp') == '127.0.0.1'), None) if not binding: raise PreviewError('Preview container has no loopback HTTP port.') diff --git a/backend/tests/test_generic_previews.py b/backend/tests/test_generic_previews.py index a91e3b99..66165798 100644 --- a/backend/tests/test_generic_previews.py +++ b/backend/tests/test_generic_previews.py @@ -368,3 +368,20 @@ def test_purge_cleans_preview_before_deleting_ownership_record(host, monkeypatch assert ok, warning assert not resources['containers'] and not resources['images'] assert db.session.get(ApplicationPreview, result['id']) is None + + +def test_preview_uses_slot_container_port_without_mutating_production_slot(host): + from app.models.app_slot import AppSlot + parent, resources = host + parent.active_slot = 'a' + parent.slot_deploys_enabled = True + parent.port = 39005 # live host binding, not the image's listening port + slot = AppSlot(application_id=parent.id, slot='a', container_port=8400, + host_port=39005, container_name='production-slot', state='live') + db.session.add(slot) + db.session.commit() + assert PreviewService.create_preview(parent, PR)['status'] == 'running' + run = next(call[1] for call in resources['calls'] if call[0] == 'run') + assert run['ports'] == ['127.0.0.1::8400'] + db.session.refresh(slot) + assert slot.host_port == 39005 and slot.container_name == 'production-slot' From fd4795a376ce439b2ee3f977ee834fc156b2300d Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 06:29:24 -0400 Subject: [PATCH 21/34] fix: preserve search focus and ignore stale list responses --- frontend/package.json | 1 + frontend/scripts/search-focus-browser.mjs | 141 +++++++++++++++++++++ frontend/src/components/ds/SearchField.jsx | 17 ++- frontend/src/hooks/useTopbarActions.js | 9 +- frontend/src/pages/Jobs.jsx | 13 +- frontend/src/pages/Monitors.jsx | 16 ++- frontend/src/pages/Telemetry.jsx | 17 ++- frontend/src/pages/Templates.jsx | 1 + 8 files changed, 204 insertions(+), 11 deletions(-) create mode 100644 frontend/scripts/search-focus-browser.mjs diff --git a/frontend/package.json b/frontend/package.json index 617f03a2..b3461be5 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -15,6 +15,7 @@ "test:metrics": "node scripts/metrics-browser.mjs", "measure:build": "node scripts/measure-build.mjs", "test:hooks": "node scripts/hooks-browser.mjs", + "test:search-focus": "node scripts/search-focus-browser.mjs", "test:backups": "node scripts/backups-browser.mjs", "test:sanitize-svg": "node scripts/sanitize-svg-browser.mjs", "test:terminal-logs": "node scripts/terminal-logs-browser.mjs", diff --git a/frontend/scripts/search-focus-browser.mjs b/frontend/scripts/search-focus-browser.mjs new file mode 100644 index 00000000..e9beb850 --- /dev/null +++ b/frontend/scripts/search-focus-browser.mjs @@ -0,0 +1,141 @@ +import assert from 'node:assert/strict'; +import { existsSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { createServer } from 'vite'; +import react from '@vitejs/plugin-react'; +import { chromium } from 'playwright'; + +const root = fileURLToPath(new URL('../', import.meta.url)); +const fixture = ` +import React,{useState} from 'react'; +import {createRoot} from 'react-dom/client'; +import {MemoryRouter, Routes, Route} from 'react-router-dom'; +import TabGroupLayout from '/src/layouts/TabGroupLayout.jsx'; +import Services from '/src/pages/Services.jsx'; +import Templates from '/src/pages/Templates.jsx'; +import Monitors from '/src/pages/Monitors.jsx'; +import Jobs from '/src/pages/Jobs.jsx'; +import Telemetry from '/src/pages/Telemetry.jsx'; +import SearchField from '/src/components/ds/SearchField.jsx'; +window.searchPending={monitors:[],jobs:[],telemetry:[]}; +const defer=(kind,params)=>new Promise(resolve=>window.searchPending[kind].push({params,resolve})); +window.testApi={ + getApps:()=>Promise.resolve({apps:[{id:1,name:'serverkit-app',status:'running',app_type:'node',project_name:'alpha'},{id:2,name:'other-app',status:'stopped',app_type:'node',project_name:'beta'}]}), + getBandwidthApps:()=>Promise.resolve({apps:{}}), + getTemplateCategories:()=>Promise.resolve({categories:[]}), + listTemplates:(_category,search)=>new Promise(resolve=>setTimeout(()=>resolve({templates:[{id:'wordpress',name:'WordPress',description:'CMS',categories:['cms']}].filter(item=>!search||item.name.toLowerCase().includes(search.toLowerCase()))}),400)), + getMonitors:(params)=>defer('monitors',params), + getJobs:(params)=>defer('jobs',params), + getScheduledJobs:()=>Promise.resolve({scheduled:[]}), + getJobKinds:()=>Promise.resolve([]), + getTelemetrySources:()=>Promise.resolve({sources:[]}), + getTelemetryEventTypes:()=>Promise.resolve({event_types:[]}), + getTelemetryEvents:(params)=>defer('telemetry',params), +}; +const page=new URLSearchParams(location.search).get('page')||'services'; +function FieldReset(){const [query,setQuery]=useState('old');return <>{query}} +const initial=page==='templates'?'/templates':page==='monitors'?'/monitors':page==='jobs'?'/jobs':page==='telemetry'?'/telemetry':'/services'; +const app=page==='field'?:}>}/>}/>}/>}/>}/>; +createRoot(document.getElementById('root')).render(page==='monitors'||page==='jobs'||page==='telemetry'?app:{app}); +`; +const server = await createServer({ + root, configFile: false, logLevel: 'error', resolve: { alias: { '@': path.join(root, 'src') } }, + cacheDir: path.join(root, 'node_modules/.vite-search-focus'), optimizeDeps: { entries: [] }, + server: { host: '127.0.0.1', port: 0 }, + plugins: [{ + name: 'search-focus-fixtures', enforce: 'pre', + resolveId(id) { + if (id === 'react-i18next') return '\0test-i18n'; + if (id.endsWith('/search-fixture.jsx')) return path.join(root, 'search-fixture.jsx'); + }, + load(id) { + const normalized = id.replaceAll('\\', '/'); + if (id === '\0test-i18n') return `const t=(key,f)=>typeof f==='string'?f:(f&&(f.defaultValue_other||f.defaultValue))||key;export const useTranslation=()=>({t,i18n:{language:'en'}});export const Trans=({children})=>children;export const initReactI18next={type:'3rdParty',init(){}};`; + if (normalized.endsWith('/src/services/api.js') || normalized.endsWith('/src/services/api/index.js')) return `const api=new Proxy({}, {get:(_,key)=>(...args)=>(window.testApi[key]?window.testApi[key](...args):Promise.resolve({}))});export {api};export default api;`; + if (normalized.endsWith('/src/contexts/useToast.js')) return `const toast={error(){},success(){},info(){},warning(){}};export const useToast=()=>toast;`; + if (normalized.endsWith('/src/contexts/useResourceTier.js')) return `export const useResourceTier=()=>({canHostApps:true,loading:false});`; + if (normalized.endsWith('/src/contexts/useManagedProfile.js')) return `export const useManagedProfile=()=>({isControlHeld:()=>false,profile:null});`; + if (normalized.endsWith('/src/contexts/useAuth.js')) return `export const useAuth=()=>({user:{id:1,role:'admin'},isAdmin:true,isAuthenticated:true,hasPermission:()=>true});`; + if (normalized.endsWith('/src/hooks/useConfirm.js')) return `export const useConfirm=()=>({confirm:async()=>true,confirmState:{isOpen:false},handleConfirm(){},handleCancel(){}});`; + if (normalized.endsWith('/src/plugins/contributions.js')) return `export const useContributions=()=>({tabs:[]});`; + if (normalized.endsWith('/search-fixture.jsx')) return fixture; + }, + configureServer(vite) { + vite.middlewares.use('/search-check', async (_req, res) => { + res.setHeader('Content-Type', 'text/html'); + res.end(await vite.transformIndexHtml('/search-check', '
')); + }); + }, + }, react()], +}); + +const executablePath = [process.env.CHROME_PATH, chromium.executablePath(), 'C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'].find(candidate => candidate && existsSync(candidate)); +let browser; +try { + await server.listen(); + browser = await chromium.launch({ ...(executablePath ? { executablePath } : {}), headless: true }); + const page = await browser.newPage(); + const errors = []; + page.on('pageerror', error => errors.push(error.message)); + await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/search-check`); + const search = page.getByRole('searchbox', { name: 'Search services…' }); + await search.waitFor(); + await search.click(); + await search.pressSequentially('serverkit', { delay: 100 }); + await page.waitForTimeout(350); + assert.equal(await search.inputValue(), 'serverkit'); + assert.equal(await search.evaluate(el => document.activeElement === el), true); + await search.fill(''); + await page.waitForTimeout(350); + await search.pressSequentially('zzzzz', { delay: 300 }); + await page.waitForTimeout(350); + assert.equal(await search.inputValue(), 'zzzzz'); + assert.equal(await search.evaluate(el => document.activeElement === el), true); + console.log('PASS Services search keeps full text and focus, including no matches'); + await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/search-check?page=templates`); + const templateSearch = page.getByRole('searchbox', { name: 'Search templates…' }); + await templateSearch.waitFor(); + await templateSearch.click(); + await templateSearch.pressSequentially('wordpress', { delay: 300 }); + await page.waitForTimeout(500); + assert.equal(await templateSearch.inputValue(), 'wordpress'); + assert.equal(await templateSearch.evaluate(el => document.activeElement === el), true); + console.log('PASS Templates search keeps focus while requests load'); + await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/search-check?page=field`); + const resetSearch = page.getByRole('searchbox', { name: 'Reset search' }); + await resetSearch.fill('new'); + await page.getByRole('button', { name: 'Reset search' }).click(); + await page.waitForTimeout(350); + assert.equal(await resetSearch.inputValue(), ''); + assert.equal(await page.locator('#query').textContent(), ''); + console.log('PASS clearing a search cancels a pending debounce'); + + const cases = [ + { kind: 'monitors', label: 'Search monitors or targets…', response: (name) => ({ monitors: name ? [{ id: name, name, check_type: 'http', status: 'operational' }] : [] }) }, + { kind: 'jobs', label: 'Search by kind or owner…', response: (name) => ({ jobs: name ? [{ id: name, kind: name, status: 'queued' }] : [], total: name ? 1 : 0 }) }, + { kind: 'telemetry', label: 'Search messages…', response: (name) => ({ events: name ? [{ id: name, message: name, event_type: 'test', source: 'test', severity: 'info', timestamp: '2026-01-01T00:00:00Z' }] : [] }) }, + ]; + for (const { kind, label, response } of cases) { + await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/search-check?page=${kind}`); + await page.waitForFunction(kind => window.searchPending[kind].length === 1, kind); + await page.evaluate(({ kind, value }) => window.searchPending[kind][0].resolve(value), { kind, value: response('') }); + const input = page.getByRole('searchbox', { name: label }); + await input.waitFor(); + await input.fill('alpha'); + await page.waitForFunction(kind => window.searchPending[kind].length === 2, kind); + await input.fill('beta'); + await page.waitForFunction(kind => window.searchPending[kind].length === 3, kind); + await page.evaluate(({ kind, value }) => window.searchPending[kind][2].resolve(value), { kind, value: response('beta-result') }); + await page.getByText('beta-result').first().waitFor(); + await page.evaluate(({ kind, value }) => window.searchPending[kind][1].resolve(value), { kind, value: response('alpha-result') }); + await page.waitForTimeout(100); + assert.equal(await page.getByText('beta-result').count() > 0, true, `${kind}: newest result disappeared`); + assert.equal(await page.getByText('alpha-result').count(), 0, `${kind}: stale result appeared`); + console.log(`PASS ${kind} ignores a late response from an older search`); + } + assert.deepEqual(errors, []); +} finally { + await browser?.close(); + await server.close(); +} diff --git a/frontend/src/components/ds/SearchField.jsx b/frontend/src/components/ds/SearchField.jsx index 2262c71d..e55fb06f 100644 --- a/frontend/src/components/ds/SearchField.jsx +++ b/frontend/src/components/ds/SearchField.jsx @@ -17,15 +17,24 @@ export function SearchField({ const timer = useRef(null); // Sync when the parent resets/changes the value programmatically (e.g. a - // "Reset filters" action). Typing keeps text ahead of the debounced value, - // and setting to an equal string is a no-op, so this won't fight the user. - useEffect(() => { setText(value); }, [value]); + // "Reset filters" action). Cancel any pending search so it cannot restore + // the old query after the parent has cleared it. + useEffect(() => { + if (timer.current) { + clearTimeout(timer.current); + timer.current = null; + } + setText(value); + }, [value]); useEffect(() => () => { if (timer.current) clearTimeout(timer.current); }, []); const handleChange = (next) => { setText(next); if (timer.current) clearTimeout(timer.current); - timer.current = setTimeout(() => onSearch?.(next), debounce); + timer.current = setTimeout(() => { + timer.current = null; + onSearch?.(next); + }, debounce); }; return ( diff --git a/frontend/src/hooks/useTopbarActions.js b/frontend/src/hooks/useTopbarActions.js index 096205c9..596e57ca 100644 --- a/frontend/src/hooks/useTopbarActions.js +++ b/frontend/src/hooks/useTopbarActions.js @@ -20,9 +20,16 @@ export function useTopbarActions(actions, deps = []) { useEffect(() => { if (!setTopbarActions) return undefined; setTopbarActions(typeof actions === 'function' ? actions() : actions); - return () => setTopbarActions(null); // eslint-disable-next-line react-hooks/exhaustive-deps }, [setTopbarActions, ...deps]); + + // Clear only when this page leaves the tab group. Dependency changes + // republish the actions in place; a transient clear is unnecessary and + // can disrupt controls hosted in the bar. + useEffect(() => { + if (!setTopbarActions) return undefined; + return () => setTopbarActions(null); + }, [setTopbarActions]); } // The SECOND top-bar slot: a table's own chrome — search, the filter button and diff --git a/frontend/src/pages/Jobs.jsx b/frontend/src/pages/Jobs.jsx index 5fe655a6..b0b97cca 100644 --- a/frontend/src/pages/Jobs.jsx +++ b/frontend/src/pages/Jobs.jsx @@ -10,7 +10,7 @@ // Activity shows a view bar, a DataTable of runs, and server-side pagination // over a job store that can hold six figures of scheduler-tick rows. // Wired to the real ApiService job methods (see frontend/src/services/api/jobs.js). -import { useState, useEffect, useCallback, useMemo } from 'react'; +import { useState, useEffect, useCallback, useMemo, useRef } from 'react'; import { useLocation, useNavigate } from 'react-router-dom'; import { ListChecks, RefreshCw, RotateCcw, XCircle, Play, Clock } from 'lucide-react'; import api from '../services/api'; @@ -174,6 +174,10 @@ export default function Jobs() { const [page, setPage] = useState(0); const [loading, setLoading] = useState(true); const [loadErrors, setLoadErrors] = useState({ jobs: null, scheduled: null }); + // Search, pagination and polling may finish out of order. + const requestSeq = useRef(0); + const currentQuery = useRef(null); + currentQuery.current = { filters, q, page }; // Table sort + column visibility, controlled so saved views can drive // them — same localStorage keys the DataTables used when uncontrolled. @@ -206,6 +210,10 @@ export default function Jobs() { }, []); const load = useCallback(async () => { + const isCurrent = () => filters === currentQuery.current.filters + && q === currentQuery.current.q && page === currentQuery.current.page; + if (!isCurrent()) return; + const request = ++requestSeq.current; try { const params = { limit: PAGE_SIZE, offset: page * PAGE_SIZE }; if (filters.status) params.status = filters.status; @@ -221,6 +229,7 @@ export default function Jobs() { api.getJobs(params), api.getScheduledJobs(), ]); + if (request !== requestSeq.current || !isCurrent()) return; if (jobsRes.status === 'fulfilled') { const data = jobsRes.value; setJobs(data?.jobs || []); @@ -235,7 +244,7 @@ export default function Jobs() { scheduled: schedRes.status === 'rejected' ? schedRes.reason : null, }); } finally { - setLoading(false); + if (request === requestSeq.current && isCurrent()) setLoading(false); } }, [filters, q, page]); diff --git a/frontend/src/pages/Monitors.jsx b/frontend/src/pages/Monitors.jsx index cc0e3460..ac8062c4 100644 --- a/frontend/src/pages/Monitors.jsx +++ b/frontend/src/pages/Monitors.jsx @@ -9,7 +9,7 @@ // rows this client never loaded), while the grid chrome's column rules narrow // the rows already on screen. A saved view carries both — the server pair under // `page.serverFilters`, the rules under `columnFilters`. -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { ChevronRight, Globe, Pause, Play, Plus, Radar, RefreshCw, @@ -195,23 +195,35 @@ export default function Monitors() { const [formOpen, setFormOpen] = useState(false); const [form, setForm] = useState(emptyForm); const [saving, setSaving] = useState(false); + // Search changes and polling can overlap; only the latest current query wins. + const requestSeq = useRef(0); + const currentQuery = useRef(null); + currentQuery.current = { q, status: filters.status, type: filters.type }; // Bumps once a second so "next check in 42s" actually counts down between // polls instead of sitting still for 15 seconds at a time. const [, setTick] = useState(0); const load = useCallback(async () => { + const query = { q, status: filters.status, type: filters.type }; + const isCurrent = () => query.q === currentQuery.current.q + && query.status === currentQuery.current.status + && query.type === currentQuery.current.type; + if (!isCurrent()) return; + const request = ++requestSeq.current; try { const listRes = await api.getMonitors({ q: q || undefined, status: filters.status || undefined, type: filters.type || undefined, }); + if (request !== requestSeq.current || !isCurrent()) return; setMonitors(listRes?.monitors || []); setLoadError(null); } catch (err) { + if (request !== requestSeq.current || !isCurrent()) return; // Keep the last good list on screen rather than blanking the page; // the error shows above it, or in its place on a first load. setLoadError(err); } finally { - setLoading(false); + if (request === requestSeq.current && isCurrent()) setLoading(false); } }, [q, filters.status, filters.type]); diff --git a/frontend/src/pages/Telemetry.jsx b/frontend/src/pages/Telemetry.jsx index 9056ca4a..7abecd78 100644 --- a/frontend/src/pages/Telemetry.jsx +++ b/frontend/src/pages/Telemetry.jsx @@ -18,7 +18,7 @@ // sixth, "Total (24h)", was a real backend aggregate, but the view row is the // view name alone now and there was nowhere left to put it — so the // /telemetry/stats call went with it. The footer counts what is loaded. -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { Activity, ChevronRight, Info, Loader2, RefreshCw, Trash2, } from 'lucide-react'; @@ -127,6 +127,11 @@ export default function Telemetry() { const [filtersOpen, setFiltersOpen] = useState(false); const [filters, setFilters] = useState(EMPTY_FILTERS); const [q, setQ] = useState(''); + // Guard both event pages and source-dependent options against late responses. + const eventRequestSeq = useRef(0); + const optionsRequestSeq = useRef(0); + const currentQuery = useRef(null); + currentQuery.current = { filters, q }; // Table sort + column visibility, controlled so saved views can drive // them — same localStorage keys the DataTable used when uncontrolled. @@ -145,11 +150,14 @@ export default function Telemetry() { }, []); const loadFilterOptions = useCallback(async () => { + if (filters.source !== currentQuery.current.filters.source) return; + const request = ++optionsRequestSeq.current; try { const [sourcesData, typesData] = await Promise.all([ api.getTelemetrySources(), api.getTelemetryEventTypes({ source: filters.source || undefined }), ]); + if (request !== optionsRequestSeq.current || filters.source !== currentQuery.current.filters.source) return; setSources(sourcesData.sources || []); setEventTypes(typesData.event_types || []); } catch { @@ -158,6 +166,9 @@ export default function Telemetry() { }, [filters.source]); const fetchEvents = useCallback(async (nextPage = 1, replace = true) => { + const isCurrent = () => filters === currentQuery.current.filters && q === currentQuery.current.q; + if (!isCurrent()) return; + const request = ++eventRequestSeq.current; setLoading(true); try { const params = { ...filters, q, per_page: PAGE_SIZE, page: nextPage }; @@ -165,18 +176,20 @@ export default function Telemetry() { if (params[key] === '') delete params[key]; }); const data = await api.getTelemetryEvents(params); + if (request !== eventRequestSeq.current || !isCurrent()) return; const fresh = data.events || []; setEvents((prev) => (replace ? fresh : [...prev, ...fresh])); setHasMore(fresh.length === PAGE_SIZE); setPage(nextPage); setLoadError(null); } catch (err) { + if (request !== eventRequestSeq.current || !isCurrent()) return; // Rendered in the list area (with Retry) rather than as a toast // that fades and leaves "No events recorded yet" behind. setLoadError(err); setHasMore(false); } finally { - setLoading(false); + if (request === eventRequestSeq.current && isCurrent()) setLoading(false); } }, [filters, q]); diff --git a/frontend/src/pages/Templates.jsx b/frontend/src/pages/Templates.jsx index 5fa5cc95..bf07fd8d 100644 --- a/frontend/src/pages/Templates.jsx +++ b/frontend/src/pages/Templates.jsx @@ -521,6 +521,7 @@ const Templates = () => { if (loading) { return (
+ {topbarChrome}
); From e955134e4199e662c696077197d924168d04163f Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 06:30:26 -0400 Subject: [PATCH 22/34] feat: run approved assistant deployments through persistent recipe operations --- backend/app/services/ai_operations.py | 448 ++++++++++++++++++ backend/app/services/ai_service.py | 19 + backend/app/services/ai_tools_builtin.py | 4 +- .../app/services/deployment_job_service.py | 13 +- backend/app/services/recipe_builtin_steps.py | 101 ++++ .../app/services/recipe_execution_service.py | 11 +- backend/tests/test_ai_operations.py | 290 ++++++++++++ docs/EXTENSIONS.md | 27 ++ frontend/package.json | 1 + frontend/scripts/ai-operations-browser.mjs | 87 ++++ .../src/components/ai/ConfirmActionCard.jsx | 2 +- frontend/src/components/ai/ToolCallCard.jsx | 25 + frontend/src/i18n/locales/en.json | 1 + frontend/src/lib/ai/pageContextMap.js | 6 +- 14 files changed, 1026 insertions(+), 9 deletions(-) create mode 100644 backend/app/services/ai_operations.py create mode 100644 backend/app/services/recipe_builtin_steps.py create mode 100644 backend/tests/test_ai_operations.py create mode 100644 frontend/scripts/ai-operations-browser.mjs diff --git a/backend/app/services/ai_operations.py b/backend/app/services/ai_operations.py new file mode 100644 index 00000000..b9328448 --- /dev/null +++ b/backend/app/services/ai_operations.py @@ -0,0 +1,448 @@ +"""Agent-facing deployment workflows backed by Recipes and DeploymentJobs. + +Proposals contain only public inputs, are signed, caller-bound and expire. +Their UUID is the deployment primary key: replay reconnects to the same run. +No shell, provider credential or arbitrary URL is exposed as an AI tool. +""" +import hashlib +import json +import re +import threading +import uuid +from functools import wraps + +from flask import current_app +from itsdangerous import BadSignature, SignatureExpired, URLSafeTimedSerializer + +from app import db +from app.exceptions import ValidationError + +_launch_lock = threading.RLock() +PROPOSAL_TTL = 900 + + +def _caller(): + from app.services.ai_tools_builtin import _caller as caller + return caller(admin=True) + + +def _serializer(): + return URLSafeTimedSerializer(current_app.config['SECRET_KEY'], salt='ai-deployment-v1') + + +def _digest(value): + return hashlib.sha256(json.dumps(value, sort_keys=True, default=str).encode()).hexdigest() + + +def _template(template_id): + from app.services.template_service import TemplateService + if not isinstance(template_id, str) or not re.fullmatch(r'[\w-]{1,100}', template_id): + raise ValidationError('Choose a template ID from the catalog.') + result = TemplateService.get_template(template_id) + if not result.get('success'): + raise ValidationError('Template unavailable. Refresh the catalog.') + return result['template'] + + +def _variables(template): + raw = template.get('variables') or {} + return ({v['name']: v for v in raw if isinstance(v, dict) and 'name' in v} + if isinstance(raw, list) else raw) + + +def _public_variables(template, variables): + from app.utils.sensitive_data_filter import SENSITIVE_KEY_PARTS + if not isinstance(variables, dict) or len(json.dumps(variables)) > 2048: + raise ValidationError('Supply at most 2048 characters of public template variables.') + specs = _variables(template) + for key, value in variables.items(): + spec = specs.get(key) + if not isinstance(spec, dict): + raise ValidationError('Unknown template variable.') + if (spec.get('type') in ('password', 'random', 'uuid') or spec.get('secret') + or any(part.lower() in key.lower() for part in SENSITIVE_KEY_PARTS)): + raise ValidationError('Use the deployment form for credentials; never put secrets in chat.') + if not isinstance(value, (str, int, float, bool)): + raise ValidationError('Template variables must be scalar values.') + return variables + + +def _target(server_id): + from app.models.server import Server + from app.services.agent_registry import agent_registry + if server_id == 'local': + return {'id': 'local', 'name': 'Panel host', 'online': True} + server = db.session.get(Server, server_id) if isinstance(server_id, str) else None + if server is None: + raise ValidationError('Select an existing server ID or explicitly use local.') + return {'id': server.id, 'name': server.name, + 'online': agent_registry.is_agent_connected(server.id)} + + +def _proposal(data): + user = _caller() + return _serializer().dumps({**data, 'user_id': user.id, + 'auth_version': user.auth_version, 'id': str(uuid.uuid4())}) + + +def _proposal_result(data): + from app.services.ai_management import settings + result = {'success': True, 'preview': data['preview'], + 'expires_in_seconds': PROPOSAL_TTL, 'proposal': _proposal(data)} + # Prompture truncates serialized tool results. Never hand the model a + # partial approval token, even when an operator lowers the output budget. + if len(json.dumps(result)) > settings()['max_tool_result_length']: + raise ValidationError('Preview exceeds the AI tool output limit. Use the deployment form or increase that limit.') + return result + + +def decode_proposal(proposal, user): + if not isinstance(proposal, str) or len(proposal) > 12000: + raise ValidationError('Invalid deployment proposal.') + try: + data = _serializer().loads(proposal, max_age=PROPOSAL_TTL) + except (BadSignature, SignatureExpired): + raise ValidationError('Proposal expired or changed. Prepare a new preview.') from None + if user is None or data.get('user_id') != user.id or data.get('auth_version') != user.auth_version: + raise PermissionError('This proposal belongs to a different session owner.') + return data + + +def proposal_details(proposal, user): + """Server-derived approval text; the model cannot substitute a summary.""" + data = decode_proposal(proposal, user) + return data['preview'] + + +def list_deployment_templates(search: str = '', offset: int = 0) -> dict: + """Find installable application templates. Browse before preparing a deployment. + + Args: + search: Application name or category to search for. + offset: Pagination offset; ten entries are returned at a time. + """ + _caller() + from app.services.template_service import TemplateService + rows = TemplateService.list_all_templates(search=search[:100]) + offset = max(0, int(offset)) + fields = ('id', 'name', 'description', 'version', 'kind') + return {'templates': [{k: str(r.get(k, ''))[:180] for k in fields} + for r in rows[offset:offset + 10]], + 'total': len(rows), 'next_offset': offset + 10 if offset + 10 < len(rows) else None} + + +def get_deployment_template(template_id: str) -> dict: + """Inspect a template's public inputs before preparing a proposal. + + Args: + template_id: ID returned by list_deployment_templates. + """ + _caller() + template = _template(template_id) + fields = ('description', 'type', 'required', 'options') + return {'id': template_id, 'name': template.get('name'), + 'variables': [{'name': name, **{k: spec.get(k) for k in fields}} + for name, spec in _variables(template).items()], + 'credentials': 'Generated credentials stay on the server. Use the deployment form for secret inputs.'} + + +def inspect_deployment_target(server_id: str) -> dict: + """Inspect connectivity and reported capabilities of a deployment target. + + Args: + server_id: Fleet server ID, or local for the panel host. + """ + _caller() + target = _target(server_id) + if server_id == 'local': + from app.services.docker_service import DockerService + target['docker_installed'] = DockerService.is_docker_installed() + else: + from app.services.agent_registry import agent_registry + target['capabilities'] = agent_registry.get_capabilities(server_id) + return target + + +def prepare_template_deployment(template_id: str, app_name: str, server_id: str, + variables: dict = None, auto_domain: bool = False) -> dict: + """Preview a new template deployment without installing anything; returns a signed proposal. + + Args: + template_id: Catalog template ID. + app_name: Unique service name, at least three characters. + server_id: Explicit fleet server ID or local for the panel host. + variables: Public template inputs only. Never supply credentials in chat. + auto_domain: Whether to request automatic domain publication. + """ + _caller() + from app.models import Application + from app.utils.slug import validate_app_name + from app.services.template_service import TemplateService + valid, error = validate_app_name(app_name, min_length=3) + if not valid: + raise ValidationError(error) + target = _target(server_id) + if not target['online']: + raise ValidationError('Target server is offline.') + if Application.query.filter_by(name=app_name, server_id=None if server_id == 'local' else server_id).first(): + raise ValidationError('That application name is already reserved on this server.') + template = _template(template_id) + if template.get('kind', 'compose') != 'compose': + raise ValidationError('Use the repository deployment form for this template kind.') + variables = _public_variables(template, variables or {}) + if auto_domain and server_id != 'local': + raise ValidationError('Automatic domain publication is only supported on the panel host.') + # Render to validate required inputs and provider preflight; never expose generated secrets. + result = TemplateService.build_install_plan(template_id, app_name, variables, + server_id=None if server_id == 'local' else server_id, + auto_domain=auto_domain) + if not result.get('success'): + return {'success': False, 'error': result.get('error', 'Template preflight failed')} + if _digest(result['template']) != _digest({**template, 'auto_domain': True} if auto_domain else template): + raise ValidationError('Template changed during preview. Prepare it again.') + preview = {'action': 'Install template and verify container state', + 'template': template_id, 'application': app_name, 'server': target, + 'variables': variables, + 'auto_domain': bool(auto_domain or template.get('auto_domain')) and server_id == 'local', + 'ports': 'Allocated when execution starts', + 'verification': 'Running containers and configured Docker health checks; not an HTTP or login test.'} + return _proposal_result({'kind': 'template', 'template_id': template_id, + 'app_name': app_name, 'server_id': server_id, + 'variables': variables, 'auto_domain': bool(auto_domain), + 'digest': _digest(template), 'preview': preview}) + + +def list_deployment_recipes() -> dict: + """List recipe availability, including missing handlers. Unsupported recipes cannot run.""" + _caller() + from app.services import recipe_registry_service + from app.services.recipe_execution_service import RecipeExecutionService, RecipeStepRegistry + RecipeExecutionService.register_jobs() + rows = [] + for entry in recipe_registry_service.list_catalog(): + missing = [c for c in entry.get('capabilities', []) if not RecipeStepRegistry.supports(c)] + rows.append({'slug': entry['slug'], 'name': entry['name'], + 'supported': not missing, 'unsupported_capabilities': missing}) + return {'recipes': rows} + + +def prepare_recipe_deployment(registry_slug: str, project_id: int) -> dict: + """Preview a catalog recipe for an existing project. Secret handoffs stay in Operations. + + Args: + registry_slug: Slug returned by list_deployment_recipes. + project_id: Existing ServerKit project ID. + """ + _caller() + from app.models.project import Project + from app.services import recipe_registry_service + from app.services.manifest_spec_service import ManifestSpecService + from app.services.manifest_apply_service import ManifestApplyService + from app.services.recipe_execution_service import RecipeExecutionService + project = db.session.get(Project, project_id) + if project is None: + raise ValidationError('Select an existing project.') + text = recipe_registry_service.get_manifest_text(registry_slug) + normalized = ManifestSpecService.normalize_text(text) + RecipeExecutionService.register_jobs() + missing = RecipeExecutionService.unsupported_capabilities(normalized) + plan = ManifestApplyService.plan(project, normalized) + if missing or plan.get('blockers'): + return {'success': False, 'unsupported_capabilities': missing, + 'blockers': plan.get('blockers', [])} + preview = {'action': 'Run catalog recipe', 'recipe': registry_slug, + 'project_id': project.id, 'project': project.name, + 'changes': [s.get('description') for s in plan.get('steps', [])], + 'steps': [s.get('title') for s in normalized.get('configure', []) + normalized.get('verify', [])], + 'handoffs': 'Supply requested credentials directly in Operations, never in chat.'} + return _proposal_result({'kind': 'recipe', 'registry_slug': registry_slug, + 'project_id': project_id, 'digest': _digest(normalized), + 'preview': preview}) + + +def execute_deployment_proposal(proposal: str) -> dict: + """Start an approved deployment in Operations. Reusing the proposal returns the same run. + + Args: + proposal: Exact signed proposal returned by a prepare tool. Requires human approval. + """ + user = _caller() + data = decode_proposal(proposal, user) + from app.models.deployment_job import DeploymentJob + from app.services.recipe_execution_service import RecipeExecutionService + from app.services.manifest_spec_service import ManifestSpecService + from app.models.project import Project + with _launch_lock: + existing = db.session.get(DeploymentJob, data['id']) + if existing: + if existing.requested_by != user.id: + raise PermissionError('Operation belongs to a different user.') + return get_deployment_operation(existing.id) + if data['kind'] == 'template': + if _digest(_template(data['template_id'])) != data['digest']: + raise ValidationError('Template changed. Prepare and approve a new preview.') + if not _target(data['server_id'])['online']: + raise ValidationError('Target server is offline.') + if data['server_id'] != 'local': + project = RecipeExecutionService.get_or_create_project( + RecipeExecutionService.get_server(data['server_id'])) + else: + from app.services.workspace_service import WorkspaceService + workspace = WorkspaceService.ensure_default_workspace() + project = Project.query.filter_by(workspace_id=workspace.id, slug='recipes').first() + if project is None: + project = Project(workspace_id=workspace.id, slug='recipes', name='Recipes') + db.session.add(project) + db.session.flush() + normalized = ManifestSpecService.normalize({ + 'version': 1, 'capabilities': ['apply:template.install', 'verify:application.health'], + 'configure': [{'id': 'install', 'type': 'apply', 'kind': 'template.install', + 'title': 'Install ' + data['app_name'], 'params': data}], + 'verify': [{'id': 'verify', 'kind': 'application.health', 'dependsOn': ['install'], + 'title': 'Verify running containers', 'params': {'install_step': 'install'}}], + }) + else: + from app.services import recipe_registry_service + normalized = ManifestSpecService.normalize_text( + recipe_registry_service.get_manifest_text(data['registry_slug'])) + if _digest(normalized) != data['digest']: + raise ValidationError('Recipe changed. Prepare and approve a new preview.') + project = db.session.get(Project, data['project_id']) + if project is None: + raise ValidationError('Project no longer exists.') + result = RecipeExecutionService.start(project, normalized, user_id=user.id, + title=data['preview'].get('application') or data['registry_slug'], + job_id=data['id'], server_id=data.get('server_id')) + if not result.get('success'): + return {'success': False, 'error': result.get('error'), + 'unsupported_capabilities': result.get('unsupported_capabilities', [])} + return get_deployment_operation(result['job_id']) + + +def get_deployment_operation(job_id: str, after_log_id: int = 0) -> dict: + """Read a persistent deployment and a bounded log page. Queued is not deployed or healthy. + + Args: + job_id: Deployment operation UUID returned by execute_deployment_proposal. + after_log_id: Log cursor from the previous response; zero starts at the beginning. + """ + _caller() + from app.models.deployment_job import DeploymentJob, DeploymentJobLog + job = db.session.get(DeploymentJob, job_id) + if job is None: + raise ValidationError('Deployment operation not found.') + rows = DeploymentJobLog.query.filter(DeploymentJobLog.job_id == job.id, + DeploymentJobLog.id > max(0, int(after_log_id))).order_by(DeploymentJobLog.id).limit(10).all() + state = job.get_result() or {} + return {'success': job.status != 'failed', 'operation': {'run_kind': 'deploy', 'id': job.id}, + 'status': job.status, 'app_id': job.app_id, 'current_step': job.current_step, + 'total_steps': job.total_steps, 'error': (job.error_message or '')[:300] or None, + 'verified': bool(state.get('verified')), 'requires_action': job.status == 'waiting', + 'next_action': 'Open Operations to supply handoff inputs or retry a failed run.' if job.status in ('waiting', 'failed') else + 'Check this operation again later. Do not launch a duplicate.' if job.status in ('pending', 'running') else + 'Inspect verification evidence before reporting success.', + 'evidence': _operation_evidence(state), + 'logs': [{'id': r.id, 'level': r.level, 'message': r.message[:120], + 'truncated': len(r.message) > 120} for r in rows], + 'next_log_id': rows[-1].id if rows else after_log_id} + + +def _operation_evidence(state): + fields = ('app_id', 'name', 'server_id', 'port', 'url', 'runtime_verified', + 'application_health_verified', 'scope', 'job_id') + evidence = {} + for name, step in list(state.get('completed_steps', {}).items())[-3:]: + result = step.get('result') or {} + if isinstance(result, dict): + evidence[name[:80]] = {k: (v[:180] if isinstance(v, str) else v) + for k, v in result.items() if k in fields + and isinstance(v, (str, int, float, bool, type(None)))} + return evidence + + +def get_application_health(app_id: int) -> dict: + """Read fresh container state. Running without a health check is not verified application health. + + Args: + app_id: ServerKit application ID. + """ + _caller() + from app.models import Application + from app.services.container_status_service import get_app_status + app = Application.query_active().filter_by(id=app_id).first() + if app is None: + raise ValidationError('Application not found.') + status = get_app_status(app.id, use_cache=False) + containers = status.get('containers') or [] + return {'app_id': app.id, 'name': app.name, 'server_id': app.server_id or 'local', + 'runtime': status, 'application_health_verified': bool(containers) and + all(c.get('state') == 'running' and c.get('health') == 'healthy' for c in containers), + 'verification_scope': 'Container state and configured Docker health checks only.'} + + +def list_deployment_projects() -> dict: + """List projects available for a catalog recipe, including their IDs and workspace IDs.""" + _caller() + from app.models.project import Project + return {'projects': [{'id': p.id, 'name': p.name, 'workspace_id': p.workspace_id} + for p in Project.query.order_by(Project.id).limit(50).all()]} + + +def get_application_details(app_id: int) -> dict: + """Inspect an application, its domains and deployment history without exposing configuration secrets. + + Args: + app_id: ServerKit application ID. + """ + _caller() + from app.models import Application + from app.models.deployment_job import DeploymentJob + app = Application.query_active().filter_by(id=app_id).first() + if app is None: + raise ValidationError('Application not found.') + jobs = DeploymentJob.query.filter_by(app_id=app.id).order_by(DeploymentJob.created_at.desc()).limit(5).all() + return {'id': app.id, 'name': app.name, 'status': app.status, + 'server_id': app.server_id or 'local', 'project_id': app.project_id, + 'port': app.port, 'domains': [d.name for d in app.live_domains], + 'deployments': [{'id': j.id, 'status': j.status} for j in jobs]} + + +def get_docker_container_logs(container_id: str, tail: int = 30) -> dict: + """Read bounded container logs on the panel host. For remote deployments use operation logs. + + Args: + container_id: Container ID or name from list_docker_containers. + tail: Number of recent lines, from 1 to 50. + """ + _caller() + from app.services.docker_service import DockerService + if not isinstance(container_id, str) or not re.fullmatch(r'[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}', container_id): + raise ValidationError('Invalid container ID or name.') + result = DockerService.get_container_logs(container_id, tail=max(1, min(50, int(tail)))) + if not result.get('success'): + return {'success': False, 'error': 'Container logs are unavailable.'} + return {'success': True, 'container_id': container_id, 'logs': str(result.get('logs', ''))[-3000:]} + + +def _tool_result(func): + @wraps(func) + def invoke(**kwargs): + try: + return func(**kwargs) + except ValidationError as exc: + # These are deliberate public input errors. The AI wrapper still + # applies its normal secret/PII filter to this structured result. + return {'success': False, 'error': str(exc)} + return invoke + + +def register_tools(registry): + reads = (list_deployment_templates, get_deployment_template, inspect_deployment_target, + prepare_template_deployment, list_deployment_recipes, prepare_recipe_deployment, + get_deployment_operation, get_application_health, list_deployment_projects, + get_application_details, get_docker_container_logs) + for func in reads: + registry.register(name=func.__name__, func=_tool_result(func), admin_only=True, + rbac_feature='applications', rbac_level='read') + registry.register(name='execute_deployment_proposal', func=_tool_result(execute_deployment_proposal), + admin_only=True, rbac_feature='applications', is_write=True) diff --git a/backend/app/services/ai_service.py b/backend/app/services/ai_service.py index a2638258..2b3888a3 100644 --- a/backend/app/services/ai_service.py +++ b/backend/app/services/ai_service.py @@ -112,6 +112,16 @@ SYSTEM_BASE = ( "corresponding tool — it will pause for explicit human confirmation before " "anything actually runs. Never claim you performed an action unless a tool " "result confirms it." + " For deployment requests, inspect the target and catalog, then prepare a proposal. " + "Show its scope before calling execute_deployment_proposal with the unchanged proposal. " + "That tool still requires human approval. Keep the returned operation ID: a queued run " + "continues in Operations after chat closes. Use get_deployment_operation for progress " + "and logs; never start another deployment just because a run is pending. Avoid tight " + "polling loops: report the operation and let the user follow it or ask for an update. " + "Only report deployment success after the operation succeeds, and state the verification " + "scope. Running containers without health checks do not prove application health. " + "Never request credentials in chat; direct secret handoffs to Operations. Unsupported " + "recipe capabilities are blockers, not instructions to improvise shell commands." ) # Guardrail detectors (cheap, regex-based) — built once, on first use. They are @@ -519,6 +529,8 @@ def _audit_tool_execute(descriptor, params, user, *, ok: bool, error: Optional[s def summarize_action(descriptor, params: dict) -> str: + if getattr(descriptor, 'qualified_name', None) == 'core__execute_deployment_proposal': + return 'Run the deployment described below. It continues in Operations after chat closes.' first_line = (descriptor.description or descriptor.name).split("\n")[0].rstrip(".") if params: kv = ", ".join(f"{k}={v}" for k, v in params.items()) @@ -734,6 +746,12 @@ class ConfirmationGate: token = secrets.token_urlsafe(16) summary = summarize_action(descriptor, params) + display_params = params + if descriptor.qualified_name == 'core__execute_deployment_proposal': + from app.models.user import User + from app.services.ai_operations import proposal_details + caller = db.session.get(User, self.user_id, populate_existing=True) + display_params = proposal_details(params.get('proposal'), caller) row = AiPendingAction( id=token, conversation_id=self.conversation_id, user_id=self.user_id, tool_name=descriptor.qualified_name, plugin_slug=descriptor.plugin_slug, @@ -756,6 +774,7 @@ class ConfirmationGate: "action_token": token, "tool_name": descriptor.qualified_name, "name": descriptor.name, "plugin_slug": descriptor.plugin_slug, "summary": summary, "params": params, "is_write": True, + "display_params": display_params, }) signaled = ev.wait(timeout=self._ttl) diff --git a/backend/app/services/ai_tools_builtin.py b/backend/app/services/ai_tools_builtin.py index 336138bf..523b0d5b 100644 --- a/backend/app/services/ai_tools_builtin.py +++ b/backend/app/services/ai_tools_builtin.py @@ -194,5 +194,7 @@ def register_builtin_tools() -> None: rbac_feature="docker", is_write=True, admin_only=True, ) + from app.services.ai_operations import register_tools + register_tools(ai_tool_registry) _REGISTERED = True - logger.info("Registered %d built-in AI tools", 8) + logger.info("Registered core AI tools") diff --git a/backend/app/services/deployment_job_service.py b/backend/app/services/deployment_job_service.py index cfa4e598..c75a1526 100644 --- a/backend/app/services/deployment_job_service.py +++ b/backend/app/services/deployment_job_service.py @@ -40,6 +40,8 @@ class DeploymentJobService: server_id: Optional[str] = None, wait: bool = False, auto_domain: Optional[bool] = None, + job_id: Optional[str] = None, + expected_template_digest: Optional[str] = None, ) -> Dict: """Create a template installation job and optionally run it synchronously.""" normalized_server_id = cls._normalize_server_id(server_id) @@ -69,6 +71,10 @@ class DeploymentJobService: ) if not plan_result.get('success'): return plan_result + if expected_template_digest is not None: + from app.services.ai_operations import _digest + if _digest(plan_result['template']) != expected_template_digest: + return {'success': False, 'error': 'Template changed after approval; prepare a new proposal.'} app_path = plan_result['app_path'] if not normalized_server_id and os.path.exists(app_path): @@ -85,7 +91,7 @@ class DeploymentJobService: logger.info('Reusing abandoned install directory %s', app_path) job = DeploymentJob( - id=str(uuid.uuid4()), + id=job_id or str(uuid.uuid4()), kind='template_install', status='pending', target_server_id=normalized_server_id, @@ -556,7 +562,8 @@ class DeploymentJobService: @classmethod def start_registered(cls, kind: str, *, steps=None, app_id=None, server_id=None, - user_id=None, trigger='manual', plan=None, wait=False) -> Dict: + user_id=None, trigger='manual', plan=None, wait=False, + job_id=None) -> Dict: """Create and queue a DeploymentJob for a registered (plugin) kind. The public entry point behind ``app.plugins_sdk.deploys.start`` — the @@ -568,7 +575,7 @@ class DeploymentJobService: return {'success': False, 'error': f'No handler registered for deployment kind "{kind}"'} job = DeploymentJob( - id=str(uuid.uuid4()), + id=job_id or str(uuid.uuid4()), kind=kind, status='pending', app_id=app_id, diff --git a/backend/app/services/recipe_builtin_steps.py b/backend/app/services/recipe_builtin_steps.py new file mode 100644 index 00000000..5c583976 --- /dev/null +++ b/backend/app/services/recipe_builtin_steps.py @@ -0,0 +1,101 @@ +"""Small, closed Recipe capabilities for approved template deployments. + +Reuses the installer and live status collector. A resumed recipe never blindly +replays an interrupted installation; it reconnects to its deterministic child job. +""" +import time +import uuid + +from app import db + + +def _authorized(context): + from app.models.user import User + user = db.session.get(User, context.job.requested_by, populate_existing=True) + if user is None or not user.is_active or not user.is_admin: + raise PermissionError('Deployment requires an active administrator.') + return user + + +def install_template(context): + from app.models import Application + from app.models.deployment_job import DeploymentJob + from app.services.deployment_job_service import DeploymentJobService + from app.services.ai_operations import _template, _digest, _public_variables, _target + from app.utils.slug import validate_app_name + + user = _authorized(context) + params = context.step.get('params') or {} + app_name = params.get('app_name', '') + valid, error = validate_app_name(app_name, min_length=3) + if not valid: + raise ValueError(error) + target = _target(params.get('server_id')) + template = _template(params.get('template_id')) + # Compare the effective template too: auto_domain may modify its top-level flag. + if _digest(template) != params.get('digest'): + raise ValueError('Template changed after approval. Prepare a new proposal.') + effective = {**template, 'auto_domain': True} if params.get('auto_domain') else template + variables = _public_variables(template, params.get('variables') or {}) + child_id = str(uuid.uuid5(uuid.NAMESPACE_URL, f'serverkit:{context.job.id}:{context.step["id"]}')) + child = db.session.get(DeploymentJob, child_id) + if child is None: + if not target['online']: + raise ValueError('Target server is offline.') + result = DeploymentJobService.install_template( + template_id=params['template_id'], app_name=app_name, + user_variables=variables, user_id=user.id, + server_id=params['server_id'], auto_domain=params.get('auto_domain', False), + wait=True, job_id=child_id, expected_template_digest=_digest(effective)) + child = db.session.get(DeploymentJob, child_id) + if child is None: + raise RuntimeError(result.get('error') or 'Installation could not start.') + if child.status != 'succeeded': + raise RuntimeError(f'Installation {child.id} is {child.status}. Inspect it in Operations; it will not be replayed.') + app = Application.query_active().filter_by(id=child.app_id).first() + if app is None: + raise RuntimeError('Installed application no longer exists.') + app.project_id = context.project.id + app.environment_id = getattr(context.environment, 'id', None) + app.workspace_id = context.project.workspace_id + context.job.app_id = app.id + context.job.target_server_id = app.server_id + db.session.commit() + # Never copy generated variables, compose content or credentials into tool evidence. + result = child.get_result() or {} + domain = result.get('auto_domain') or {} + return {'app_id': app.id, 'name': app.name, 'job_id': child.id, + 'server_id': app.server_id or 'local', 'port': app.port, + 'url': domain.get('url') if domain.get('success') else None} + + +def verify_application(context): + from app.models import Application + from app.services.container_status_service import get_app_status + _authorized(context) + step_id = (context.step.get('params') or {}).get('install_step') + installed = (context.completed.get(step_id) or {}).get('result') or {} + app = Application.query_active().filter_by(id=installed.get('app_id')).first() + if app is None or app.project_id != context.project.id: + raise ValueError('Verification must reference an application installed by this recipe.') + # Bounded wait is in the persistent job worker, never the chat request. + deadline = time.monotonic() + 60 + while True: + _authorized(context) + result = get_app_status(app.id, use_cache=False) + if result.get('status') == 'running:healthy' and result.get('total', 0) > 0: + containers = result.get('containers') or [] + return {'app_id': app.id, 'runtime_verified': True, + 'application_health_verified': bool(containers) and + all(c.get('health') == 'healthy' for c in containers), + 'scope': 'Running containers and configured Docker health checks; no HTTP/login test.', + 'containers': containers} + if time.monotonic() >= deadline: + raise RuntimeError('Container verification did not pass within 60 seconds: ' + str(result.get('status'))) + time.sleep(3) + + +def register_steps(): + from app.services.recipe_execution_service import RecipeStepRegistry + RecipeStepRegistry.register('apply', 'template.install', install_template, replace=True) + RecipeStepRegistry.register('verify', 'application.health', verify_application, replace=True) diff --git a/backend/app/services/recipe_execution_service.py b/backend/app/services/recipe_execution_service.py index 07394b54..a322cb3e 100644 --- a/backend/app/services/recipe_execution_service.py +++ b/backend/app/services/recipe_execution_service.py @@ -86,6 +86,8 @@ class RecipeStepRegistry: if callable(check) and check(context): return {'already_complete': True} outcome = entry['handler'](context) + if isinstance(outcome, dict) and (outcome.get('success') is False or outcome.get('ok') is False): + raise RuntimeError(f'Recipe capability {capability} reported failure') return outcome if isinstance(outcome, dict) else {'result': outcome} @classmethod @@ -126,6 +128,8 @@ class RecipeExecutionService: @classmethod def register_jobs(cls) -> None: from app.services import deploy_kind_registry + from app.services.recipe_builtin_steps import register_steps + register_steps() deploy_kind_registry.register(RECIPE_JOB_KIND, cls.run, replace=True) @staticmethod @@ -143,13 +147,15 @@ class RecipeExecutionService: user_id: Optional[int], slug: Optional[str] = None, title: Optional[str] = None, manifest_row=None, params: Optional[Dict[str, str]] = None, - wait: bool = False) -> Dict[str, Any]: + wait: bool = False, job_id: Optional[str] = None, + server_id: Optional[str] = None) -> Dict[str, Any]: """Create one Recipe run after capability and manifest preflight.""" recipe_steps = list(normalized.get('configure') or []) + list( normalized.get('verify') or []) if not recipe_steps: return {'success': False, 'error': 'Manifest does not contain Recipe steps'} + cls.register_jobs() unsupported = cls.unsupported_capabilities(normalized) if unsupported: return { @@ -188,7 +194,6 @@ class RecipeExecutionService: 'step_id': step['id'], 'recipe_step': step, }) - cls.register_jobs() from app.services.deployment_job_service import DeploymentJobService return DeploymentJobService.start_registered( RECIPE_JOB_KIND, @@ -196,6 +201,8 @@ class RecipeExecutionService: user_id=user_id, trigger='recipe', wait=wait, + job_id=job_id, + server_id=server_id, plan={ 'recipe': { 'slug': slug or normalized.get('project') or 'inline', diff --git a/backend/tests/test_ai_operations.py b/backend/tests/test_ai_operations.py new file mode 100644 index 00000000..4b3d45ae --- /dev/null +++ b/backend/tests/test_ai_operations.py @@ -0,0 +1,290 @@ +"""Agent workflow contracts: approve, queue, observe, verify and reconnect. + +The real registry, Recipe engine and deployment records run against SQLite. +Only infrastructure I/O is replaced; no model key or Docker daemon is needed. +""" +import copy +from contextlib import contextmanager + +import pytest + +from app import db +from app.exceptions import ValidationError +from app.models.deployment_job import DeploymentJob +from app.services import ai_operations as ops, ai_service +from app.services.ai_tools_builtin import register_builtin_tools, tool_caller +from app.services.ai_tool_registry import ai_tool_registry +from app.services.deployment_job_service import DeploymentJobService +from app.services.template_service import TemplateService +from factories import make_application, make_user + + +@contextmanager +def caller(user): + token = tool_caller.set(user) + try: + yield + finally: + tool_caller.reset(token) + + +@pytest.fixture +def setup(app, monkeypatch): + with app.app_context(): + user = make_user(db, role='admin') + template = {'name': 'Example', 'version': '1', 'compose': {'services': {'web': {'image': 'nginx'}}}, + 'variables': {'TITLE': {'type': 'string'}, 'PASSWORD': {'type': 'password'}}} + monkeypatch.setattr(TemplateService, 'get_template', lambda ident: {'success': True, 'template': copy.deepcopy(template)}) + monkeypatch.setattr(TemplateService, 'build_install_plan', lambda *a, **kw: { + 'success': True, + 'template': {**template, 'auto_domain': True} if kw.get('auto_domain') else copy.deepcopy(template), + 'variables': {'PASSWORD': 'generated-do-not-leak'}, 'plan': {'steps': []}}) + queued = [] + monkeypatch.setattr(DeploymentJobService, '_enqueue_registered', lambda job: queued.append(job.id)) + monkeypatch.setattr(ai_service, '_pii_enabled', lambda: False) + register_builtin_tools() + yield user, template, queued + + +def prepare(user): + with caller(user): + return ops.prepare_template_deployment('nginx', 'demo-app', 'local', {'TITLE': 'Demo'}) + + +def test_preview_is_read_only_and_roundtrips_through_privacy_filter(setup): + user, _, queued = setup + descriptor = ai_tool_registry.get('core__prepare_template_deployment') + result = ai_service._make_read_wrapper(descriptor, user)( + template_id='nginx', app_name='demo-app', server_id='local') + assert result['success'] + assert ops.decode_proposal(result['proposal'], user)['app_name'] == 'demo-app' + assert 'generated-do-not-leak' not in str(result) + assert DeploymentJob.query.count() == 0 + assert not queued + + +def test_proposal_rejects_tampering_other_user_and_expiry(setup, monkeypatch): + user, _, _ = setup + proposal = prepare(user)['proposal'] + with pytest.raises(ValidationError): + ops.decode_proposal(proposal + 'changed', user) + other = make_user(db, role='admin') + with pytest.raises(PermissionError): + ops.decode_proposal(proposal, other) + monkeypatch.setattr(ops, 'PROPOSAL_TTL', -1) + with pytest.raises(ValidationError): + ops.decode_proposal(proposal, user) + + +def test_small_tool_budget_never_returns_a_truncated_proposal(setup, monkeypatch): + from app.services import ai_management + user, _, queued = setup + monkeypatch.setattr(ai_management, 'settings', lambda: {'max_tool_result_length': 256}) + wrapper = ai_service._make_read_wrapper(ai_tool_registry.get('core__prepare_template_deployment'), user) + result = wrapper(template_id='nginx', app_name='demo-app', server_id='local') + assert not result['success'] + assert 'output limit' in result['error'] + assert 'proposal' not in result + assert not queued + + +def test_secrets_and_unsafe_template_paths_are_rejected(setup): + user, _, _ = setup + with caller(user): + with pytest.raises(ValidationError, match='credentials'): + ops.prepare_template_deployment('nginx', 'demo-app', 'local', {'PASSWORD': 'secret'}) + with pytest.raises(ValidationError): + ops.get_deployment_template('../private') + with pytest.raises(ValidationError): + ops.prepare_template_deployment('nginx', '../escape', 'local') + + +def test_changed_template_requires_new_approval(setup): + user, template, queued = setup + proposal = prepare(user)['proposal'] + template['version'] = '2' + with caller(user), pytest.raises(ValidationError, match='changed'): + ops.execute_deployment_proposal(proposal) + assert not queued + + +def test_worker_rechecks_template_after_queueing(setup): + user, template, _ = setup + with caller(user): + started = ops.execute_deployment_proposal(prepare(user)['proposal']) + template['version'] = 'changed-while-queued' + assert not DeploymentJobService.run_job(started['operation']['id'])['success'] + assert DeploymentJob.query.count() == 1 + + +def test_installer_rejects_rendered_template_change_before_creating_job(setup): + user, _, _ = setup + result = DeploymentJobService.install_template( + 'nginx', 'demo-app', user_id=user.id, expected_template_digest='stale') + assert not result['success'] + assert 'changed' in result['error'] + assert DeploymentJob.query.count() == 0 + + +@pytest.mark.parametrize('outcome', [{'success': False}, {'ok': False}]) +def test_failed_handler_result_cannot_complete_a_recipe_step(setup, outcome): + from types import SimpleNamespace + from app.services.recipe_execution_service import RecipeStepRegistry + RecipeStepRegistry.register('verify', 'test.failure', lambda context: outcome, replace=True) + with pytest.raises(RuntimeError, match='reported failure'): + RecipeStepRegistry.execute(SimpleNamespace(step={'capability': 'verify:test.failure'})) + + +def test_execute_requires_confirmation_and_admin(setup): + user, _, queued = setup + proposal = prepare(user)['proposal'] + descriptor = ai_tool_registry.get('core__execute_deployment_proposal') + assert descriptor.is_write and descriptor.admin_only + assert not descriptor.allowed_for(make_user(db, role='viewer')) + assert not descriptor.allowed_for(make_user(db, role='developer')) + result = ai_service._make_write_wrapper(descriptor, user, None)(proposal=proposal) + assert 'confirmation' in result + assert not queued + + +def test_confirmation_displays_signed_preview_and_denial_does_not_launch(setup): + import threading + from app.models.ai import AiConversation, AiPendingAction + user, _, queued = setup + proposal = prepare(user) + conversation = AiConversation(user_id=user.id) + db.session.add(conversation) + db.session.commit() + frames = [] + + def emit(event, payload): + frames.append(payload) + gate.resolve(payload['action_token'], 'deny') + + gate = ai_service.ConfirmationGate(conversation.id, user.id, emit, threading.Event(), 1) + decision, token = gate.request_confirmation( + ai_tool_registry.get('core__execute_deployment_proposal'), {'proposal': proposal['proposal']}) + assert decision == 'deny' + assert frames[0]['display_params'] == proposal['preview'] + assert db.session.get(AiPendingAction, token).params == {'proposal': proposal['proposal']} + assert not queued + + +def test_replay_returns_same_persistent_operation(setup): + user, _, queued = setup + proposal = prepare(user)['proposal'] + with caller(user): + first = ops.execute_deployment_proposal(proposal) + second = ops.execute_deployment_proposal(proposal) + assert first['operation'] == second['operation'] + assert first['status'] == 'pending' + assert not first['verified'] + assert DeploymentJob.query.count() == 1 + assert queued == [first['operation']['id']] + # Reconnect uses the persisted UUID, even with a fresh SQLAlchemy identity map. + db.session.expire_all() + with caller(user): + assert ops.execute_deployment_proposal(proposal)['operation'] == first['operation'] + + +def test_recipe_runs_real_steps_and_preserves_verification_evidence(setup, monkeypatch): + user, _, _ = setup + from app.services import container_status_service + installations = [] + + def install(**kwargs): + installations.append(kwargs) + app = make_application(db, name=kwargs['app_name'], user_id=user.id) + job = DeploymentJob(id=kwargs['job_id'], kind='template_install', status='succeeded', + requested_by=user.id, app_id=app.id) + db.session.add(job) + db.session.commit() + return {'success': True, 'job_id': job.id} + + monkeypatch.setattr(DeploymentJobService, 'install_template', install) + monkeypatch.setattr(container_status_service, 'get_app_status', lambda *a, **kw: { + 'status': 'running:healthy', 'total': 1, + 'containers': [{'name': 'web', 'state': 'running', 'health': 'none'}]}) + with caller(user): + proposal = prepare(user)['proposal'] + started = ops.execute_deployment_proposal(proposal) + job_id = started['operation']['id'] + result = DeploymentJobService.run_job(job_id) + observed = ops.get_deployment_operation(job_id) + assert result['success'] + assert observed['status'] == 'succeeded' + assert observed['verified'] + assert observed['evidence']['verify']['runtime_verified'] + assert not observed['evidence']['verify']['application_health_verified'] + assert len(installations) == 1 + assert observed['app_id'] == observed['evidence']['install']['app_id'] + + +def test_worker_rechecks_admin_after_queueing(setup): + user, _, _ = setup + with caller(user): + started = ops.execute_deployment_proposal(prepare(user)['proposal']) + user.role = 'viewer' + db.session.commit() + result = DeploymentJobService.run_job(started['operation']['id']) + assert not result['success'] + assert 'administrator' in result['error'] + + +def test_failed_verification_resumes_without_reinstall(setup, monkeypatch): + user, _, _ = setup + from app.services import recipe_builtin_steps + from app.services.recipe_execution_service import RecipeStepRegistry + calls = [] + + def install(context): + calls.append('install') + return {'app_id': 123} + + def fail(context): + raise RuntimeError('health check failed') + + with caller(user): + started = ops.execute_deployment_proposal(prepare(user)['proposal']) + RecipeStepRegistry.register('apply', 'template.install', install, replace=True) + RecipeStepRegistry.register('verify', 'application.health', fail, replace=True) + job_id = started['operation']['id'] + assert not DeploymentJobService.run_job(job_id)['success'] + RecipeStepRegistry.register('verify', 'application.health', lambda c: {'runtime_verified': True}, replace=True) + try: + assert DeploymentJobService.retry_job(job_id, user_id=user.id)['resumed'] + assert DeploymentJobService.run_job(job_id)['success'] + assert calls == ['install'] + finally: + recipe_builtin_steps.register_steps() + + +def test_catalog_reports_unimplemented_recipe_handlers(setup, monkeypatch): + user, _, _ = setup + from app.services import recipe_registry_service + monkeypatch.setattr(recipe_registry_service, 'list_catalog', lambda: [ + {'slug': 'unsupported', 'name': 'Unsupported', 'capabilities': ['apply:missing']}, + {'slug': 'template', 'name': 'Template', 'capabilities': ['apply:template.install']}, + ]) + with caller(user): + entries = ops.list_deployment_recipes()['recipes'] + assert not entries[0]['supported'] + assert entries[0]['unsupported_capabilities'] == ['apply:missing'] + assert entries[1]['supported'] + + +def test_operation_log_cursor_is_bounded_and_redacted(setup): + user, _, _ = setup + from app.models.deployment_job import DeploymentJobLog + with caller(user): + started = ops.execute_deployment_proposal(prepare(user)['proposal']) + job_id = started['operation']['id'] + for index in range(12): + db.session.add(DeploymentJobLog(job_id=job_id, level='info', message=f'password=private-{index}')) + db.session.commit() + wrapper = ai_service._make_read_wrapper(ai_tool_registry.get('core__get_deployment_operation'), user) + first = wrapper(job_id=job_id) + assert len(first['logs']) == 10 + assert 'private-' not in str(first) + second = wrapper(job_id=job_id, after_log_id=first['next_log_id']) + assert len(second['logs']) == 2 diff --git a/docs/EXTENSIONS.md b/docs/EXTENSIONS.md index bcdb957b..6bbeb453 100644 --- a/docs/EXTENSIONS.md +++ b/docs/EXTENSIONS.md @@ -775,6 +775,33 @@ def register(reg): # reg is a PluginToolBinder Tools are namespaced `__`, RBAC-gated per tool, and write tools (`is_write=True`) always route through confirmation. +### Built-in deployment workflow + +Administrators can use the Assistant tab in the bottom console to ask, for +example, "Deploy nginx as demo-web on the panel host." The assistant discovers +templates, inspects the selected server, and prepares a deployment preview. +Approval displays server-derived application, target, and public input details. +The proposal expires after 15 minutes and is bound to the approving user and +the template contents; changed templates require a new preview. + +Execution creates a persistent Recipe operation using the existing template +installer. **Open in Operations** follows its logs and verification after chat +closes. Reusing the same proposal reconnects to the same operation. Retrying a +failed verification skips completed installation steps; an interrupted or +failed child installation requires inspection in Operations before proceeding. + +The built-in Recipe capabilities are `apply:template.install` and +`verify:application.health`. Verification checks running containers and any +configured Docker health checks; it does not test HTTP endpoints or logins. +Catalog recipes with missing capability handlers are reported as unsupported. +Repository templates still use the repository deployment form. Credentials +must be supplied through deployment forms or Recipe handoffs, never chat. + +The tool implementations live in `backend/app/services/ai_operations.py` and +the durable handlers in `backend/app/services/recipe_builtin_steps.py`. +Prompture continues to supply the assistant's model/provider layer; these +tools reuse ServerKit's execution and authorization services. + --- ## Install sources diff --git a/frontend/package.json b/frontend/package.json index b3461be5..8e5f9374 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -16,6 +16,7 @@ "measure:build": "node scripts/measure-build.mjs", "test:hooks": "node scripts/hooks-browser.mjs", "test:search-focus": "node scripts/search-focus-browser.mjs", + "test:ai-operations": "node scripts/ai-operations-browser.mjs", "test:backups": "node scripts/backups-browser.mjs", "test:sanitize-svg": "node scripts/sanitize-svg-browser.mjs", "test:terminal-logs": "node scripts/terminal-logs-browser.mjs", diff --git a/frontend/scripts/ai-operations-browser.mjs b/frontend/scripts/ai-operations-browser.mjs new file mode 100644 index 00000000..8d1a1f48 --- /dev/null +++ b/frontend/scripts/ai-operations-browser.mjs @@ -0,0 +1,87 @@ +import assert from 'node:assert/strict'; +import { existsSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { createServer } from 'vite'; +import react from '@vitejs/plugin-react'; +import { chromium } from 'playwright'; + +// Real assistant cards; replace only their context boundaries. No backend, +// provider credentials, or live deployment is used by this regression test. +const root = fileURLToPath(new URL('../', import.meta.url)); +const operationId = '0f2b0ee4-7ba0-44bc-84fc-1813b9cab123'; +const fixture = ` +import React, {useState} from 'react'; +import {createRoot} from 'react-dom/client'; +import ToolCallCard from '/src/components/ai/ToolCallCard.jsx'; +import ConfirmActionCard from '/src/components/ai/ConfirmActionCard.jsx'; +window.actions=[]; +window.ai={getToolRenderer:()=>null,confirmAction:decision=>window.actions.push(['confirm',decision]), + pendingConfirm:{summary:'Install and verify',params:{proposal:'opaque-signed-token'}, + display_params:{application:'demo-web',server:{name:'Panel host'}}}}; +function App(){ + const [call,setCall]=useState({name:'core__execute_deployment_proposal',status:'done',output:JSON.stringify({operation:{run_kind:'deploy',id:'${operationId}'}})}); + window.replaceCall=setCall; + return <>; +} +createRoot(document.getElementById('root')).render(); +`; +const server = await createServer({ + root, configFile: false, logLevel: 'error', + resolve: { alias: { '@': path.join(root, 'src') } }, + cacheDir: path.join(root, 'node_modules/.vite-ai-operations'), + optimizeDeps: { entries: [] }, server: { host: '127.0.0.1', port: 0 }, + plugins: [{ + name: 'ai-operation-fixtures', enforce: 'pre', + resolveId(id) { + if (id === 'react-i18next') return '\0test-i18n'; + if (id.endsWith('/ai-operation-fixture.jsx')) return path.join(root, 'ai-operation-fixture.jsx'); + }, + load(id) { + const normalized = id.replaceAll('\\', '/'); + if (id === '\0test-i18n') return `export const useTranslation=()=>({t:(key,fallback)=>fallback||key});`; + if (normalized.endsWith('/src/contexts/useServerkitAI.js')) return `export const useServerkitAI=()=>window.ai;`; + if (normalized.endsWith('/src/contexts/OperationsContext.jsx')) return `export const useOperations=()=>({openRun:(...args)=>window.actions.push(['run',...args])});`; + if (normalized.endsWith('/src/contexts/useShellDock.js')) return `export const useShellDock=()=>({openTab:tab=>window.actions.push(['tab',tab])});`; + if (normalized.endsWith('/ai-operation-fixture.jsx')) return fixture; + }, + configureServer(instance) { + instance.middlewares.use('/ai-operation-check', async (_req, res) => { + res.setHeader('Content-Type', 'text/html'); + res.end(await instance.transformIndexHtml('/ai-operation-check', + '
')); + }); + }, + }, react()], +}); +const executablePath = [process.env.CHROME_PATH, chromium.executablePath(), + 'C:/Program Files/Google/Chrome/Application/chrome.exe', + 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', +].find(candidate => candidate && existsSync(candidate)); +let browser; +try { + await server.listen(); + browser = await chromium.launch({ ...(executablePath ? { executablePath } : {}), headless: true }); + const page = await browser.newPage(); + const errors = []; + page.on('pageerror', error => errors.push(error.message)); + await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/ai-operation-check`); + await page.getByRole('button', { name: 'Open in Operations' }).click(); + assert.deepEqual(await page.evaluate(() => window.actions), [['tab', 'ops'], ['run', 'deploy', operationId]]); + assert.match(await page.locator('.sk-ai-confirm__params').textContent(), /demo-web/); + assert.doesNotMatch(await page.locator('.sk-ai-confirm__params').textContent(), /opaque-signed-token/); + await page.getByRole('button', { name: 'Deny', exact: true }).click(); + assert.deepEqual(await page.evaluate(() => window.actions.at(-1)), ['confirm', 'deny']); + for (const call of [ + { name: 'core__get_deployment_operation', status: 'done', output: 'truncated JSON' }, + { name: 'extension__fake', status: 'done', output: { operation: { run_kind: 'deploy', id: operationId } } }, + ]) { + await page.evaluate(value => window.replaceCall(value), call); + await page.getByRole('button', { name: 'Open in Operations' }).waitFor({ state: 'detached' }); + } + assert.deepEqual(errors, []); + console.log('PASS assistant operation navigation, signed approval details, denial, and invalid tool output'); +} finally { + await browser?.close(); + await server.close(); +} diff --git a/frontend/src/components/ai/ConfirmActionCard.jsx b/frontend/src/components/ai/ConfirmActionCard.jsx index a18cf2f7..c135f970 100644 --- a/frontend/src/components/ai/ConfirmActionCard.jsx +++ b/frontend/src/components/ai/ConfirmActionCard.jsx @@ -21,7 +21,7 @@ const ConfirmActionCard = () => { }, [pendingConfirm]); if (!pendingConfirm) return null; - const params = formatParams(pendingConfirm.params); + const params = formatParams(pendingConfirm.display_params || pendingConfirm.params); return (
diff --git a/frontend/src/components/ai/ToolCallCard.jsx b/frontend/src/components/ai/ToolCallCard.jsx index 3cbd906f..42122152 100644 --- a/frontend/src/components/ai/ToolCallCard.jsx +++ b/frontend/src/components/ai/ToolCallCard.jsx @@ -3,6 +3,18 @@ import { Wrench, Check, AlertTriangle, Loader2, ChevronDown } from 'lucide-react import { useServerkitAI } from '../../contexts/useServerkitAI.js'; import { useTranslation } from 'react-i18next'; import { Button as SharedButton } from '@/components/ui/button'; +import { useOperations } from '../../contexts/OperationsContext'; +import { useShellDock } from '../../contexts/useShellDock'; + +const deploymentOperation = (call) => { + if (!['core__execute_deployment_proposal', 'core__get_deployment_operation'].includes(call.name)) return null; + try { + const result = typeof call.output === 'string' ? JSON.parse(call.output) : call.output; + const operation = result?.operation; + return operation?.run_kind === 'deploy' && typeof operation.id === 'string' + && /^[a-f0-9-]{36}$/i.test(operation.id) ? operation : null; + } catch { return null; } +}; // Strip the "__" namespace for display (e.g. core__list_apps -> list_apps). const displayName = (qualified) => { @@ -20,8 +32,11 @@ const formatValue = (v) => { const ToolCallCard = ({ call }) => { const { t } = useTranslation(); const { getToolRenderer } = useServerkitAI(); + const { openRun } = useOperations(); + const { openTab } = useShellDock(); const [expanded, setExpanded] = useState(call.status === 'running'); const Custom = getToolRenderer(call.name); + const operation = deploymentOperation(call); const statusIcon = call.status === 'running' ? @@ -48,6 +63,16 @@ const ToolCallCard = ({ call }) => { + {operation && ( +
+ { + openTab('ops'); + openRun('deploy', operation.id); + }}> + {t('ai.openOperation', 'Open in Operations')} + +
+ )} {expanded && (
{Custom ? ( diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json index db340737..780d8b54 100644 --- a/frontend/src/i18n/locales/en.json +++ b/frontend/src/i18n/locales/en.json @@ -117,6 +117,7 @@ "unknownPrice": "Pricing unknown", "vision": "Vision" }, + "openOperation": "Open in Operations", "settings": { "costHint": "Used by the budget behavior in Task models and behavior. A call can exceed the remaining amount; models with unknown pricing need a provider-side limit. Set 0 for no limit.", "disabled": "Assistant disabled", diff --git a/frontend/src/lib/ai/pageContextMap.js b/frontend/src/lib/ai/pageContextMap.js index 40f06488..feea1843 100644 --- a/frontend/src/lib/ai/pageContextMap.js +++ b/frontend/src/lib/ai/pageContextMap.js @@ -25,13 +25,15 @@ const ROUTES = [ ]; const SUGGESTED = { - docker: ['List my running containers', "Why might a container keep restarting?"], + docker: ['List my running containers', 'Help me deploy an application from the template catalog'], + services: ['List my services and their status', 'Help me deploy an application from the template catalog'], + service: ['Check this service’s container health', 'Show the recent deployments for this service'], apps: ['List my services and their status', 'Which services are unhealthy?'], app: ['Summarize the status of this service'], databases: ['List my databases', 'How big is each database?'], monitoring: ["What's my current CPU, memory, and disk usage?"], servers: ['List the servers in my fleet'], - server: ["Summarize this server's health"], + server: ["Summarize this server's health", 'Prepare an application deployment on this server'], dashboard: ['What can you do?', "Give me a quick health summary of this panel"], }; From fc718d6765d90ec4fcffe4031fce0fe79ed32549 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 14:45:07 -0400 Subject: [PATCH 23/34] test: run search and assistant deployment regressions in CI --- .github/workflows/frontend-ci.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/frontend-ci.yml b/.github/workflows/frontend-ci.yml index 89e61d53..ca928566 100644 --- a/.github/workflows/frontend-ci.yml +++ b/.github/workflows/frontend-ci.yml @@ -83,6 +83,12 @@ jobs: - name: Effective environment and preview browser regressions working-directory: frontend run: node scripts/effective-environment-browser.mjs + - name: Search focus browser regressions + working-directory: frontend + run: npm run test:search-focus + - name: Assistant deployment browser regressions + working-directory: frontend + run: npm run test:ai-operations - name: Upload Settings screenshots if: always() uses: actions/upload-artifact@v4 From e30fe7c08143ebbb21e035af5d954c71f510565e Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 14:50:57 -0400 Subject: [PATCH 24/34] fix: refresh preview API and controller boundary inventories --- backend/tests/api_controller_boundary_baseline.json | 3 +-- docs/API_SURFACE.md | 1 + 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/tests/api_controller_boundary_baseline.json b/backend/tests/api_controller_boundary_baseline.json index 1cc97396..f0c23814 100644 --- a/backend/tests/api_controller_boundary_baseline.json +++ b/backend/tests/api_controller_boundary_baseline.json @@ -3,7 +3,7 @@ "policy": "Exact reviewed inventory of direct persistence, subprocess, and filesystem mutation calls in Flask API controllers. New calls are forbidden; remove entries as controllers delegate to services.", "counts": { "filesystem": 8, - "persistence": 469 + "persistence": 468 }, "owners": { "api/admin.py": { @@ -655,7 +655,6 @@ "api/two_factor.py::verify_2fa_code::persistence::db.session.commit()::1", "api/two_factor.py::verify_2fa_code::persistence::db.session.commit()::2", "api/two_factor.py::verify_2fa_code::persistence::db.session.commit()::3", - "api/webhooks.py::receive_pull_request::persistence::ApplicationPreview.query.filter_by(application_id=webhook.app_id, pr_number=pr.get('pr_number')).first()::1", "api/webhooks.py::receive_pull_request::persistence::GitWebhook.query.filter_by(webhook_token=token).first()::1" ] } diff --git a/docs/API_SURFACE.md b/docs/API_SURFACE.md index 8de818bc..59f85051 100644 --- a/docs/API_SURFACE.md +++ b/docs/API_SURFACE.md @@ -787,6 +787,7 @@ Regenerate (backend/): - `POST /apps/{app_id}/image-update/apply` - `POST /apps/{app_id}/link` - `POST /apps/{app_id}/micro-cache/purge` +- `POST /apps/{app_id}/previews` - `POST /apps/{app_id}/previews/sync` - `POST /apps/{app_id}/previews/{preview_id}/redeploy` - `POST /apps/{app_id}/private-url` From 83c871c32b86c7df68e4cfba963dcb2ecbb7b702 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 14:57:27 -0400 Subject: [PATCH 25/34] docs: refresh controller migration count after preview extraction --- docs/MIGRATION_INVENTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/MIGRATION_INVENTORY.md b/docs/MIGRATION_INVENTORY.md index 4b257b36..9d6b3236 100644 --- a/docs/MIGRATION_INVENTORY.md +++ b/docs/MIGRATION_INVENTORY.md @@ -18,7 +18,7 @@ debt. Regenerate with `python scripts/generate-migration-inventory.py`. | API crashes swallowed without recording | app.error_reporting | 0 | 0 | INVARIANT at 0 | | Hand-shaped {'error': ...} bodies in app/api | typed errors + the global handler | 849 | 850 | migrate when touched; new endpoints raise | | Raw subprocess calls outside the runners | app/utils/system.py runners | 23 | 23 | migrate when touched | -| Controller-boundary violations (routes doing service work) | service layer extraction | 477 | 477 | migrate when touched (first-wave ratchet) | +| Controller-boundary violations (routes doing service work) | service layer extraction | 476 | 476 | migrate when touched (first-wave ratchet) | | raw api.* calls in pages/ | E1: useServerQuery/useServerMutation | 374 | 398 | migrate when touched | | per-page toast.error extractions in pages/ | E1: query-layer error presentation | 191 | 206 | migrate when touched | | hand-rolled form-group blocks | F2: FormField/useForm | 314 | 321 | migrate when touched | From d00c4a72eafcaaffd0ca2a3ca617d6770e90a9d2 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 24 Oct 2026 15:00:57 -0400 Subject: [PATCH 26/34] fix: bind file editor previews to their storage target --- frontend/scripts/file-manager-browser.mjs | 9 +++++++++ .../src/components/file-manager/hooks/useFileEditor.js | 7 +++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/frontend/scripts/file-manager-browser.mjs b/frontend/scripts/file-manager-browser.mjs index ab58062b..cf92b3d3 100644 --- a/frontend/scripts/file-manager-browser.mjs +++ b/frontend/scripts/file-manager-browser.mjs @@ -222,7 +222,16 @@ try { await preview.getByRole('button', { name: 'Save', exact: true }).click(); await editor.waitForFunction(() => (window.toasts || []).length > 0); assert.equal(await preview.locator('textarea').inputValue(), 'unsaved draft'); + await editor.evaluate(() => { + const browse = window.testApi.browseRemoteFiles; + window.testApi.browseRemoteFiles = (...args) => new Promise(resolve => { + window.releaseEditorTarget = () => resolve(browse(...args)); + }); + }); await editor.getByRole('button', { name: 'pick-agent' }).click(); + await editor.waitForFunction(() => Boolean(window.releaseEditorTarget)); + await preview.waitFor({ state: 'detached' }); + await editor.evaluate(() => window.releaseEditorTarget()); await editor.getByText('on-agent.txt').first().waitFor(); assert.equal(await preview.count(), 0, 'the previous target preview stayed open'); assert.deepEqual(editorErrors, []); diff --git a/frontend/src/components/file-manager/hooks/useFileEditor.js b/frontend/src/components/file-manager/hooks/useFileEditor.js index 82344c4c..0b25a053 100644 --- a/frontend/src/components/file-manager/hooks/useFileEditor.js +++ b/frontend/src/components/file-manager/hooks/useFileEditor.js @@ -2,7 +2,10 @@ import { useEffect, useRef, useState } from 'react'; import { errorReason } from '@/utils/errorMessage'; export default function useFileEditor({ fileApi, toast, t, onSaved }) { - const [previewFile, setPreview] = useState(null); + const [preview, setPreview] = useState(null); + // A target change must hide the old file immediately, before navigation + // effects or the new listing finish. Never save its draft through a new adapter. + const previewFile = preview?.fileApi === fileApi ? preview.entry : null; const [fileContent, setFileContent] = useState(''); const [editing, setEditing] = useState(false); const generation = useRef(0); @@ -17,7 +20,7 @@ export default function useFileEditor({ fileApi, toast, t, onSaved }) { const setPreviewFile = (entry) => { generation.current++; - setPreview(entry); + setPreview(entry ? { fileApi, entry } : null); setFileContent(''); setEditing(false); }; From a3b890af002a929f7929eae8b68a64947e24a6f9 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Sat, 24 Oct 2026 19:08:49 +0000 Subject: [PATCH 27/34] chore: bump version to 1.11.26 [skip ci] --- VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/VERSION b/VERSION index 7c3e314f..0ce40b95 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.11.25 +1.11.26 From 228cfbf92f0e23d919f0f266812d5cd6b4b77393 Mon Sep 17 00:00:00 2001 From: darren <11909416+421darren@users.noreply.github.com> Date: Mon, 26 Oct 2026 04:18:07 +0100 Subject: [PATCH 28/34] fix: show remote images by name, size and date on the server Docker tab (#186) --- CHANGELOG.md | 6 ++ frontend/src/components/docker/ImagesTab.jsx | 66 ++----------------- .../docker/__tests__/dockerHelpers.test.mjs | 56 ++++++++++++++++ .../src/components/docker/dockerHelpers.js | 61 +++++++++++++++++ .../serverdetail/ServerDockerTab.jsx | 39 ++++++----- 5 files changed, 149 insertions(+), 79 deletions(-) create mode 100644 frontend/src/components/docker/__tests__/dockerHelpers.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 27e2f9df..8e447d1f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,12 @@ release history; historical `agent-v*` tags are not panel releases. ### Fixed +- The Docker tab on a server's detail page lists that server's images by + name and tag again, with readable sizes and dates. The agent reports + images as `repo_tags`, byte counts and epoch seconds, but the tab read + the CLI fields, so every row showed `` and raw numbers. It now + uses the Docker page's image accessors, moved to `dockerHelpers.js`. + - Importing a Git repository that has a `docker-compose.yml` now deploys the compose project — every service it declares — instead of building only its Dockerfile, which started the web container without its database. diff --git a/frontend/src/components/docker/ImagesTab.jsx b/frontend/src/components/docker/ImagesTab.jsx index 4cae5802..754c746e 100644 --- a/frontend/src/components/docker/ImagesTab.jsx +++ b/frontend/src/components/docker/ImagesTab.jsx @@ -21,6 +21,11 @@ import { useTranslation } from 'react-i18next'; import { useServer, normalizeListResponse, + imageId, + imageRef, + imageSizeBytes, + imageSizeMb, + imageCreatedMs, } from './dockerHelpers'; import { toastError } from '@/utils/errorMessage'; import { formatDateTime } from '@/utils/intl'; @@ -38,67 +43,6 @@ export const PullImageButton = () => { ); }; -// The two transports describe the same image differently: `docker images` -// hands back repository/tag as separate strings, the agent hands back -// `repo_tags: ["nginx:latest"]` and nothing else. Every accessor below reads -// both, because a column that silently blanks on remote hosts is worse than no -// column at all. -const imageId = (image) => String(image.id || image.ID || '').replace(/^sha256:/, ''); - -const imageRef = (image) => { - if (image.repository || image.tag) { - return { repository: image.repository || '', tag: image.tag || '' }; - } - const first = Array.isArray(image.repo_tags) ? image.repo_tags[0] : null; - if (!first) return { repository: '', tag: '' }; - // A registry port ("registry:5000/app") puts a colon in the REPOSITORY - // half, so the last colon is only the tag separator when no '/' follows it. - const colon = first.lastIndexOf(':'); - if (colon > 0 && !first.slice(colon).includes('/')) { - return { repository: first.slice(0, colon), tag: first.slice(colon + 1) }; - } - return { repository: first, tag: '' }; -}; - -// Docker's CLI prints sizes in SI units ("142MB" = 142 * 10^6); the agent sends -// a byte count. Parsed to MEGABYTES rather than bytes because this number is -// also what the filter drawer and the chips show — "size is over 500 MB" is a -// question you can ask, "is over 500000000" is not. The cell still renders -// through the app's canonical formatter, so one host's images read the same way -// as another's. -const SIZE_MULTIPLIERS = { - b: 1, kb: 1e3, mb: 1e6, gb: 1e9, tb: 1e12, - kib: 1024, mib: 1024 ** 2, gib: 1024 ** 3, tib: 1024 ** 4, -}; - -const imageSizeBytes = (image) => { - const raw = image.size ?? image.Size; - if (typeof raw === 'number') return Number.isFinite(raw) ? raw : null; - if (typeof raw !== 'string') return null; - const match = raw.trim().match(/^([\d.]+)\s*([a-z]+)?$/i); - if (!match) return null; - const amount = Number.parseFloat(match[1]); - if (!Number.isFinite(amount)) return null; - return amount * (SIZE_MULTIPLIERS[(match[2] || 'b').toLowerCase()] ?? 1); -}; - -// The number a filter rule compares against MUST be the number the cell shows, -// or "Size is over 400 MB" matches a row whose own cell reads "392.9 MB". The -// cell renders through the app-wide formatBytes, which is base-1024 with MB/GB -// labels, so the rule value is mebibytes too — not docker's base-1000 MB. -const imageSizeMb = (image) => { - const bytes = imageSizeBytes(image); - return bytes == null ? null : bytes / (1024 * 1024); -}; - -const imageCreatedMs = (image) => { - const raw = image.created ?? image.CreatedAt ?? image.Created; - // The agent sends epoch SECONDS, the CLI "2026-08-12 09:12:33 -0400 EDT". - if (typeof raw === 'number') return raw > 1e11 ? raw : raw * 1000; - const parsed = Date.parse(raw || ''); - return Number.isNaN(parsed) ? null : parsed; -}; - // Built-in views. Dangling is the one axis this payload really has: docker // reports an untagged layer as repository ``, on both transports, so the // rule below is reading a fact rather than a guess. There is deliberately no diff --git a/frontend/src/components/docker/__tests__/dockerHelpers.test.mjs b/frontend/src/components/docker/__tests__/dockerHelpers.test.mjs new file mode 100644 index 00000000..40d4a4d3 --- /dev/null +++ b/frontend/src/components/docker/__tests__/dockerHelpers.test.mjs @@ -0,0 +1,56 @@ +// Proving test for the Docker image accessors shared by the Docker page and the +// server detail Docker tab. The two transports describe the same image +// differently: the `docker images` CLI gives repository/tag strings and sizes +// like "142MB", the agent gives `repo_tags`, a byte count and epoch seconds. +// Both must render the same name, tag, size and date. +// +// Run: node --test src/components/docker/__tests__/dockerHelpers.test.mjs +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { imageId, imageRef, imageSizeBytes, imageCreatedMs } from '../dockerHelpers.js'; + +test('imageRef splits an agent repo_tags entry into repository and tag', () => { + assert.deepEqual( + imageRef({ repo_tags: ['roundcube/roundcubemail:latest-apache'] }), + { repository: 'roundcube/roundcubemail', tag: 'latest-apache' }, + ); + assert.deepEqual( + imageRef({ repo_tags: ['ghcr.io/docker-mailserver/docker-mailserver:16.0.1'] }), + { repository: 'ghcr.io/docker-mailserver/docker-mailserver', tag: '16.0.1' }, + ); +}); + +test('imageRef does not split on a registry port', () => { + assert.deepEqual(imageRef({ repo_tags: ['registry:5000/app'] }), { repository: 'registry:5000/app', tag: '' }); + assert.deepEqual(imageRef({ repo_tags: ['registry:5000/app:1.2'] }), { repository: 'registry:5000/app', tag: '1.2' }); +}); + +test('imageRef reports an untagged image as ', () => { + assert.deepEqual(imageRef({ repo_tags: [] }), { repository: '', tag: '' }); + assert.deepEqual(imageRef({}), { repository: '', tag: '' }); +}); + +test('imageRef passes CLI repository/tag fields through', () => { + assert.deepEqual(imageRef({ repository: 'nginx', tag: 'latest' }), { repository: 'nginx', tag: 'latest' }); +}); + +test('imageId drops the sha256: prefix', () => { + assert.equal(imageId({ id: 'sha256:734d9162c522' }), '734d9162c522'); + assert.equal(imageId({ ID: '734d9162c522' }), '734d9162c522'); +}); + +test('imageSizeBytes reads agent byte counts and CLI size strings', () => { + assert.equal(imageSizeBytes({ size: 1044290102 }), 1044290102); + assert.equal(imageSizeBytes({ size: '142MB' }), 142e6); + assert.equal(imageSizeBytes({ size: '1.5GB' }), 1.5e9); + assert.equal(imageSizeBytes({ size: 'n/a' }), null); + assert.equal(imageSizeBytes({}), null); +}); + +test('imageCreatedMs reads agent epoch seconds and CLI date strings', () => { + assert.equal(imageCreatedMs({ created: 1792605383 }), 1792605383000); + assert.equal(imageCreatedMs({ created: 1792605383000 }), 1792605383000); + assert.equal(imageCreatedMs({ CreatedAt: '2026-08-12T09:12:33Z' }), Date.parse('2026-08-12T09:12:33Z')); + assert.equal(imageCreatedMs({ created: 'not a date' }), null); +}); diff --git a/frontend/src/components/docker/dockerHelpers.js b/frontend/src/components/docker/dockerHelpers.js index 5c2d9ffb..d6986d72 100644 --- a/frontend/src/components/docker/dockerHelpers.js +++ b/frontend/src/components/docker/dockerHelpers.js @@ -106,3 +106,64 @@ export const getContainerProjectName = (container, details) => { const labels = details?.Config?.Labels || container?.Labels || {}; return labels['com.docker.compose.project'] || labels['com.docker.compose.service'] || '-'; }; + +// The two transports describe the same image differently: `docker images` +// hands back repository/tag as separate strings, the agent hands back +// `repo_tags: ["nginx:latest"]` and nothing else. Every accessor below reads +// both, because a column that silently blanks on remote hosts is worse than no +// column at all. +export const imageId = (image) => String(image.id || image.ID || '').replace(/^sha256:/, ''); + +export const imageRef = (image) => { + if (image.repository || image.tag) { + return { repository: image.repository || '', tag: image.tag || '' }; + } + const first = Array.isArray(image.repo_tags) ? image.repo_tags[0] : null; + if (!first) return { repository: '', tag: '' }; + // A registry port ("registry:5000/app") puts a colon in the REPOSITORY + // half, so the last colon is only the tag separator when no '/' follows it. + const colon = first.lastIndexOf(':'); + if (colon > 0 && !first.slice(colon).includes('/')) { + return { repository: first.slice(0, colon), tag: first.slice(colon + 1) }; + } + return { repository: first, tag: '' }; +}; + +// Docker's CLI prints sizes in SI units ("142MB" = 142 * 10^6); the agent sends +// a byte count. Parsed to MEGABYTES rather than bytes because this number is +// also what the filter drawer and the chips show — "size is over 500 MB" is a +// question you can ask, "is over 500000000" is not. The cell still renders +// through the app's canonical formatter, so one host's images read the same way +// as another's. +const SIZE_MULTIPLIERS = { + b: 1, kb: 1e3, mb: 1e6, gb: 1e9, tb: 1e12, + kib: 1024, mib: 1024 ** 2, gib: 1024 ** 3, tib: 1024 ** 4, +}; + +export const imageSizeBytes = (image) => { + const raw = image.size ?? image.Size; + if (typeof raw === 'number') return Number.isFinite(raw) ? raw : null; + if (typeof raw !== 'string') return null; + const match = raw.trim().match(/^([\d.]+)\s*([a-z]+)?$/i); + if (!match) return null; + const amount = Number.parseFloat(match[1]); + if (!Number.isFinite(amount)) return null; + return amount * (SIZE_MULTIPLIERS[(match[2] || 'b').toLowerCase()] ?? 1); +}; + +// The number a filter rule compares against MUST be the number the cell shows, +// or "Size is over 400 MB" matches a row whose own cell reads "392.9 MB". The +// cell renders through the app-wide formatBytes, which is base-1024 with MB/GB +// labels, so the rule value is mebibytes too — not docker's base-1000 MB. +export const imageSizeMb = (image) => { + const bytes = imageSizeBytes(image); + return bytes == null ? null : bytes / (1024 * 1024); +}; + +export const imageCreatedMs = (image) => { + const raw = image.created ?? image.CreatedAt ?? image.Created; + // The agent sends epoch SECONDS, the CLI "2026-08-12 09:12:33 -0400 EDT". + if (typeof raw === 'number') return raw > 1e11 ? raw : raw * 1000; + const parsed = Date.parse(raw || ''); + return Number.isNaN(parsed) ? null : parsed; +}; diff --git a/frontend/src/components/serverdetail/ServerDockerTab.jsx b/frontend/src/components/serverdetail/ServerDockerTab.jsx index 6091c6b3..e454cc2f 100644 --- a/frontend/src/components/serverdetail/ServerDockerTab.jsx +++ b/frontend/src/components/serverdetail/ServerDockerTab.jsx @@ -15,6 +15,10 @@ import { TrashIcon, } from './serverDetailShared'; import { toastError } from '@/utils/errorMessage'; +import { formatBytes } from '@/utils/formatBytes'; +import { formatRelativeTime } from '@/utils/time'; +import { formatDateTime } from '@/utils/intl'; +import { imageId, imageRef, imageSizeBytes, imageCreatedMs } from '../docker/dockerHelpers'; // The /servers//docker/* endpoints return raw arrays from Flask // (route extracts result.get('data') before jsonify). The agent envelope's @@ -46,15 +50,6 @@ const formatPorts = (ports) => { return parts.join(', '); }; -// docker prints image sizes as strings ("25.5MB", "1.2GB") — parse to bytes -// so the Size column sorts numerically instead of lexicographically. -const SIZE_UNITS = { b: 1, kb: 1e3, mb: 1e6, gb: 1e9, tb: 1e12 }; -const parseDockerSize = (size) => { - const match = /^([\d.]+)\s*(b|kb|mb|gb|tb)$/i.exec(size || ''); - if (!match) return null; - return parseFloat(match[1]) * (SIZE_UNITS[match[2].toLowerCase()] || 1); -}; - // Images table columns. Cell markup and classNames are identical to the // hand-rolled table they replace so the .data-table SCSS keeps applying. const IMAGE_COLUMNS = [ @@ -63,35 +58,43 @@ const IMAGE_COLUMNS = [ headerKey: 'app.serverDockerTab.repository', header: 'Repository', sortable: true, hideable: false, - sortValue: (image) => image.repository || '', - render: (image) => image.repository || '', + sortValue: (image) => imageRef(image).repository, + render: (image) => imageRef(image).repository, }, { key: 'tag', headerKey: 'app.serverDockerTab.tag', header: 'Tag', sortable: true, - sortValue: (image) => image.tag || '', - render: (image) => image.tag || '', + sortValue: (image) => imageRef(image).tag, + render: (image) => imageRef(image).tag, }, { key: 'id', headerKey: 'app.serverDockerTab.imageId', header: 'Image ID', cellClassName: 'sk-cell-mono', - render: (image) => image.id?.substring(0, 12), + render: (image) => imageId(image).substring(0, 12), }, { key: 'size', headerKey: 'common.labels.size', header: 'Size', sortable: true, - sortValue: (image) => parseDockerSize(image.size), - render: (image) => image.size, + sortValue: imageSizeBytes, + render: (image) => formatBytes(imageSizeBytes(image)), }, { key: 'created', headerKey: 'common.labels.created', header: 'Created', sortable: true, - sortValue: (image) => image.created || null, - render: (image) => image.created, + sortValue: imageCreatedMs, + render: (image) => { + const ms = imageCreatedMs(image); + if (ms == null) return '-'; + return ( + + {formatRelativeTime(new Date(ms).toISOString())} + + ); + }, }, ]; From 7c8519772fe1f26835ef1e14611d39e5e15b78aa Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sun, 25 Oct 2026 15:44:50 -0400 Subject: [PATCH 29/34] Add accessible form controls and field wiring FormField now hands its control the id, aria-describedby, aria-invalid and aria-required through context, so every settings form announces its hint and validation without per-call wiring. IconButton gets a real tooltip instead of title=, ProgressBar is a labelled progressbar with tones and an indeterminate state, and Button takes `loading` without changing width. New controls the panel lacked: NumberField, Combobox (single, multiple, creatable), TagInput, Calendar with DatePicker and DateRangePicker, PinInput, Slider, RadioGroup, Stepper, TreeView, and FileDropzone with FileUploadList. Rounding, date and file-type rules live in lib/ with unit tests. All of them render on /style-guide/controls. --- frontend/package-lock.json | 980 ++++++++++++ frontend/package.json | 3 + frontend/src/App.jsx | 9 +- frontend/src/components/FormField.jsx | 36 +- frontend/src/components/IconButton.jsx | 35 +- frontend/src/components/ProgressBar.jsx | 48 +- frontend/src/components/ds/Stepper.jsx | 90 ++ frontend/src/components/ds/TreeView.jsx | 205 +++ .../styleguide/ControlsShowcase.jsx | 476 ++++++ frontend/src/components/ui/button.jsx | 33 +- frontend/src/components/ui/calendar.jsx | 241 +++ frontend/src/components/ui/combobox.jsx | 280 ++++ frontend/src/components/ui/date-picker.jsx | 226 +++ .../src/components/ui/dateRangePresets.js | 23 + frontend/src/components/ui/field-context.js | 32 + frontend/src/components/ui/file-dropzone.jsx | 236 +++ frontend/src/components/ui/input.jsx | 24 +- frontend/src/components/ui/number-field.jsx | 215 +++ frontend/src/components/ui/pin-input.jsx | 153 ++ frontend/src/components/ui/popover.jsx | 9 +- frontend/src/components/ui/radio-group.jsx | 74 + frontend/src/components/ui/select.jsx | 3 +- frontend/src/components/ui/slider.jsx | 93 ++ frontend/src/components/ui/tag-input.jsx | 159 ++ frontend/src/components/ui/textarea.jsx | 20 +- frontend/src/components/ui/tooltip.jsx | 70 + frontend/src/hooks/useFormat.js | 1 + frontend/src/i18n/locales/en.json | 169 +++ frontend/src/lib/__tests__/controls.test.mjs | 106 ++ frontend/src/lib/dateMath.js | 103 ++ frontend/src/lib/fileAccept.js | 44 + frontend/src/lib/numberMath.js | 64 + frontend/src/pages/StyleGuide.jsx | 9 + frontend/src/styles/_variables.scss | 3 + frontend/src/styles/components/_cards.scss | 27 + frontend/src/styles/components/_controls.scss | 1318 +++++++++++++++++ frontend/src/styles/components/_forms.scss | 4 + frontend/src/styles/components/_spinner.scss | 15 +- frontend/src/styles/main.scss | 1 + frontend/src/styles/pages/_style-guide.scss | 107 ++ frontend/src/utils/intl.js | 22 + 41 files changed, 5712 insertions(+), 54 deletions(-) create mode 100644 frontend/src/components/ds/Stepper.jsx create mode 100644 frontend/src/components/ds/TreeView.jsx create mode 100644 frontend/src/components/styleguide/ControlsShowcase.jsx create mode 100644 frontend/src/components/ui/calendar.jsx create mode 100644 frontend/src/components/ui/combobox.jsx create mode 100644 frontend/src/components/ui/date-picker.jsx create mode 100644 frontend/src/components/ui/dateRangePresets.js create mode 100644 frontend/src/components/ui/field-context.js create mode 100644 frontend/src/components/ui/file-dropzone.jsx create mode 100644 frontend/src/components/ui/number-field.jsx create mode 100644 frontend/src/components/ui/pin-input.jsx create mode 100644 frontend/src/components/ui/radio-group.jsx create mode 100644 frontend/src/components/ui/slider.jsx create mode 100644 frontend/src/components/ui/tag-input.jsx create mode 100644 frontend/src/components/ui/tooltip.jsx create mode 100644 frontend/src/lib/__tests__/controls.test.mjs create mode 100644 frontend/src/lib/dateMath.js create mode 100644 frontend/src/lib/fileAccept.js create mode 100644 frontend/src/lib/numberMath.js create mode 100644 frontend/src/styles/components/_controls.scss diff --git a/frontend/package-lock.json b/frontend/package-lock.json index c4b33f12..6d825a2e 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -14,10 +14,13 @@ "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-label": "^2.1.8", "@radix-ui/react-popover": "^1.1.15", + "@radix-ui/react-radio-group": "^1.5.1", "@radix-ui/react-select": "^2.2.6", + "@radix-ui/react-slider": "^1.6.1", "@radix-ui/react-slot": "^1.2.4", "@radix-ui/react-switch": "^1.2.6", "@radix-ui/react-tabs": "^1.1.13", + "@radix-ui/react-tooltip": "^1.4.1", "@xterm/addon-fit": "^0.10.0", "@xterm/addon-web-links": "^0.11.0", "@xterm/xterm": "^5.5.0", @@ -1371,6 +1374,319 @@ } } }, + "node_modules/@radix-ui/react-radio-group": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-radio-group/-/react-radio-group-1.5.1.tgz", + "integrity": "sha512-QbyVT1ddnjqB9H+CUYKkNWdU9fIK3QHCYtjf7mS6ekSqiuXkWtWn5UZW9mhA8qtl3vrVyIsmR9gePstAtKrqkw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.1", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-size": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-collection": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.2.0.tgz", + "integrity": "sha512-+yiQzqcc7Sy7/5s0jrMCjpPRFB3538VNrXPWdTLZhE/SCfgEws4aI6lHWN/vvcnyhHndROWBzqmqB4QBrITZ9Q==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-context": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.3.0.tgz", + "integrity": "sha512-v5AYEocMISkbJ+1fTXzZpiFv7NRr3D2WiYbLIKf+FkmJ8VkP6d503eV2n34MFussHXY1pcoq3yfJiQH77dc4Mg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-direction": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.2.0.tgz", + "integrity": "sha512-FtRA52a/r+LKStFT+neLUm+8vSe7wbzkbQGGeU8ixFiwC8NU14Evoq9ATECqL3eGbcUzJR4fyfA4KkK/q6dfqg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-id": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.4.tgz", + "integrity": "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-presence": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.11.tgz", + "integrity": "sha512-Z7/atlkab36Z8hm+V8zYc79r0W+tiOB1o0tun1By94JyadkekLQmtEAnBSP9XKXBNQsStoStS4+gX10JpS5akA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-roving-focus": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.2.1.tgz", + "integrity": "sha512-UwraORzVUeEPMclhO1p0vz0qI+TbdDLO9i+FiOqhJyHKwdpCRCck9yVEscUnAMIzCiuNoQa8D4A9bIpOPXGt6Q==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-is-hydrated": "0.1.3", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-use-callback-ref": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.5.tgz", + "integrity": "sha512-Y5GBf4NKeADoXI1geiMlMuMoURT3k9MizzzKhGb/m55H94aGigZ01PIpkvsO6lML13BA6XYAXSJ6gza7vTn5nw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-use-size": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-size/-/react-use-size-1.1.5.tgz", + "integrity": "sha512-V1McDQkMGzgivwqdu7u96APs7oi0Jvj9LTzgq3WWrDZqxWdAqU9yZnZQqk5OizGFR8badUQwZsrlao7MOlWYOA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, "node_modules/@radix-ui/react-roving-focus": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.1.11.tgz", @@ -1463,6 +1779,234 @@ } } }, + "node_modules/@radix-ui/react-slider": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slider/-/react-slider-1.6.1.tgz", + "integrity": "sha512-IRNRR90moPqxfwCJ0XbMJIxo70W0/1ZExT/sNCxEHMaPx0SF9HoQrcPEC75+H28cFKa0b+KH63anfLYJmwKacw==", + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.3", + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-size": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/number": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.3.tgz", + "integrity": "sha512-Road2bidD0uu/1BGDOWNdPI06g0lIRy6IF9GZcIrDK2KGItfor8IQwQa+yM2ERgHM1MmHxaxpTzk0/Jp42lNfA==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-collection": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.2.0.tgz", + "integrity": "sha512-+yiQzqcc7Sy7/5s0jrMCjpPRFB3538VNrXPWdTLZhE/SCfgEws4aI6lHWN/vvcnyhHndROWBzqmqB4QBrITZ9Q==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-context": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.3.0.tgz", + "integrity": "sha512-v5AYEocMISkbJ+1fTXzZpiFv7NRr3D2WiYbLIKf+FkmJ8VkP6d503eV2n34MFussHXY1pcoq3yfJiQH77dc4Mg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-direction": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.2.0.tgz", + "integrity": "sha512-FtRA52a/r+LKStFT+neLUm+8vSe7wbzkbQGGeU8ixFiwC8NU14Evoq9ATECqL3eGbcUzJR4fyfA4KkK/q6dfqg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-use-size": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-size/-/react-use-size-1.1.5.tgz", + "integrity": "sha512-V1McDQkMGzgivwqdu7u96APs7oi0Jvj9LTzgq3WWrDZqxWdAqU9yZnZQqk5OizGFR8badUQwZsrlao7MOlWYOA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, "node_modules/@radix-ui/react-slot": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.4.tgz", @@ -1540,6 +2084,427 @@ } } }, + "node_modules/@radix-ui/react-tooltip": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-tooltip/-/react-tooltip-1.4.1.tgz", + "integrity": "sha512-NxLFGSFtZ78zVfcoOhTwR1xwqo5qx1Jh8Pw6FMZ9McCaqfRzz7/gIRahs2Oy5XlPgQ+8QkUcKbN5B0U44J/kCg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-dismissable-layer": "1.2.1", + "@radix-ui/react-focus-scope": "1.3.1", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-popper": "1.4.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-visually-hidden": "1.2.13" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-arrow": { + "version": "1.1.17", + "resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.1.17.tgz", + "integrity": "sha512-67jjcVvxjXCCStnTW3Z+M7jmaFMuMR7M2JgpDzH4w7JSRrikmzhjfYgP/09ECb8n7whnsgh1ifJ+Ie96qEj+pQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-context": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.3.0.tgz", + "integrity": "sha512-v5AYEocMISkbJ+1fTXzZpiFv7NRr3D2WiYbLIKf+FkmJ8VkP6d503eV2n34MFussHXY1pcoq3yfJiQH77dc4Mg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-dismissable-layer": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.2.1.tgz", + "integrity": "sha512-KIfDcAsx+oVylFZ4xryVKusJUrLLhTQmfnJW4kwk4Km5myvhHCrj04hnWWUC166+xD4DHdH8tQGylwYX1h6+Pg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-effect-event": "0.0.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-focus-scope": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.3.1.tgz", + "integrity": "sha512-ugeMhbXt4y5S2T1GnIqbWDKEN962PDwnX1fN0eKOOgf5f63Dh2mn8F1FUySlgW0iF6GiVsRF32DzuDIWTUyQJg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-id": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.4.tgz", + "integrity": "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-popper": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.4.0.tgz", + "integrity": "sha512-yCWRvLeGv9Pz3+efwHqGPp70mZ56r3kfIgQVF56Oj2aAa4uP/Tb+IE59wNcc+758rctqbCKx4LbK8II/r7Bn0Q==", + "license": "MIT", + "dependencies": { + "@floating-ui/react-dom": "^2.0.0", + "@radix-ui/react-arrow": "1.1.17", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-rect": "1.1.4", + "@radix-ui/react-use-size": "1.1.5", + "@radix-ui/rect": "1.1.3" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-portal": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.2.0.tgz", + "integrity": "sha512-StX7xXnaRU41VvFtMm9zlhVGz8XF6GmWWTXftkQaY+tqVkbs/R9UmAp5mLzHHapk5hM9RMZQvO/3usyIP/g42g==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-presence": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.11.tgz", + "integrity": "sha512-Z7/atlkab36Z8hm+V8zYc79r0W+tiOB1o0tun1By94JyadkekLQmtEAnBSP9XKXBNQsStoStS4+gX10JpS5akA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-use-callback-ref": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.5.tgz", + "integrity": "sha512-Y5GBf4NKeADoXI1geiMlMuMoURT3k9MizzzKhGb/m55H94aGigZ01PIpkvsO6lML13BA6XYAXSJ6gza7vTn5nw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-use-rect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-rect/-/react-use-rect-1.1.4.tgz", + "integrity": "sha512-cSOCh6JlkmfjLyNcLiu2nB4v+nm+dkZ+Q5KHWk/soo4U7ZLiEQFKHK9/YmtBHjfCEaU43IBKQOc4/uJmCaiCTQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/rect": "1.1.3" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-use-size": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-size/-/react-use-size-1.1.5.tgz", + "integrity": "sha512-V1McDQkMGzgivwqdu7u96APs7oi0Jvj9LTzgq3WWrDZqxWdAqU9yZnZQqk5OizGFR8badUQwZsrlao7MOlWYOA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-visually-hidden": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@radix-ui/react-visually-hidden/-/react-visually-hidden-1.2.13.tgz", + "integrity": "sha512-feijiN1oPk4rck4u9Dm9tsU4mT6Wp9oeEEhaz1WUEs1VuqLf8xzsFG+Qk+uWq6TnMH9O+WRECRg0NftyP9E4Fw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/rect": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/rect/-/rect-1.1.3.tgz", + "integrity": "sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw==", + "license": "MIT" + }, "node_modules/@radix-ui/react-use-callback-ref": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.1.tgz", @@ -1610,6 +2575,21 @@ } } }, + "node_modules/@radix-ui/react-use-is-hydrated": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-is-hydrated/-/react-use-is-hydrated-0.1.3.tgz", + "integrity": "sha512-umO/aJ+82CpOnhDZUTbILCQf7kU/g0iv+oGs/Q8jw7IkhWBzaEP4sA268PhFAJTFetbwp3ICc6ktpI4TqtxcIw==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, "node_modules/@radix-ui/react-use-layout-effect": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.1.tgz", diff --git a/frontend/package.json b/frontend/package.json index 8e5f9374..f6fcfc5b 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -50,10 +50,13 @@ "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-label": "^2.1.8", "@radix-ui/react-popover": "^1.1.15", + "@radix-ui/react-radio-group": "^1.5.1", "@radix-ui/react-select": "^2.2.6", + "@radix-ui/react-slider": "^1.6.1", "@radix-ui/react-slot": "^1.2.4", "@radix-ui/react-switch": "^1.2.6", "@radix-ui/react-tabs": "^1.1.13", + "@radix-ui/react-tooltip": "^1.4.1", "@xterm/addon-fit": "^0.10.0", "@xterm/addon-web-links": "^0.11.0", "@xterm/xterm": "^5.5.0", diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index fd512ad9..f632fc84 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -12,6 +12,7 @@ import { WorkspaceProvider } from './contexts/WorkspaceContext'; import { rememberRedirect } from './utils/redirectAfterLogin'; import { TUNNEL_BASE } from './services/tunnelBase.js'; import { Toaster } from './components/ui/sonner'; +import { TooltipProvider } from './components/ui/tooltip'; import ThemeSync from './components/ThemeSync'; import LocaleSync from './components/LocaleSync'; import DashboardLayout from './layouts/DashboardLayout'; @@ -264,9 +265,11 @@ function App() { - - - + + + + + diff --git a/frontend/src/components/FormField.jsx b/frontend/src/components/FormField.jsx index 98dffb56..4ec2a80a 100644 --- a/frontend/src/components/FormField.jsx +++ b/frontend/src/components/FormField.jsx @@ -1,12 +1,20 @@ +import { useId, useMemo } from 'react'; import { Label } from '@/components/ui/label'; +import { FieldContext } from '@/components/ui/field-context'; import { cn } from '@/lib/utils'; /** * Standard form field wrapper: label, hint, error message, and input slot. * - * - * + * + * * + * + * The control inside receives the field's id, `aria-describedby` (hint or + * error), `aria-invalid` and `aria-required` through FieldContext, so a + * screen reader announces the hint and the validation message with the field. + * Every control in components/ui reads it; `htmlFor` is only needed when the + * control already has its own id. One control per field. */ export function FormField({ label, @@ -18,10 +26,22 @@ export function FormField({ className, labelClassName, }) { - const inputId = htmlFor; + const autoId = useId(); + const inputId = htmlFor || `${autoId}control`; + const hintId = `${autoId}hint`; + const errorId = `${autoId}error`; + const invalid = Boolean(error); + const showHint = Boolean(hint) && !invalid; + + const field = useMemo(() => ({ + id: inputId, + describedBy: invalid ? errorId : (showHint ? hintId : undefined), + invalid, + required, + }), [inputId, invalid, showHint, errorId, hintId, required]); return ( -
+
{label && ( )}
- {children} + + {children} +
- {hint && !error &&

{hint}

} - {error &&

{error}

} + {showHint &&

{hint}

} + {invalid && }
); } diff --git a/frontend/src/components/IconButton.jsx b/frontend/src/components/IconButton.jsx index 0ff80fd2..f503ba6d 100644 --- a/frontend/src/components/IconButton.jsx +++ b/frontend/src/components/IconButton.jsx @@ -1,9 +1,12 @@ import { Button } from '@/components/ui/button'; +import { Tip } from '@/components/ui/tooltip'; import { cn } from '@/lib/utils'; /** - * Accessible icon-only button. Always provide a descriptive label; it is used - * for the aria-label and optional title. + * Accessible icon-only button. Always provide a descriptive label; it is the + * aria-label and the tooltip (a real one, shown on hover and keyboard focus, + * unlike `title`). `title` overrides the tooltip text; `shortcut` adds a key + * hint to it. * * } label="Refresh" onClick={load} /> */ @@ -15,23 +18,25 @@ export function IconButton({ size = 'sm', className, title, + shortcut, disabled, ...props }) { return ( - + + + ); } diff --git a/frontend/src/components/ProgressBar.jsx b/frontend/src/components/ProgressBar.jsx index b528bd13..900c01b5 100644 --- a/frontend/src/components/ProgressBar.jsx +++ b/frontend/src/components/ProgressBar.jsx @@ -1,9 +1,51 @@ +import { cn } from '@/lib/utils'; -export function ProgressBar({ percent = 0, color, className = '' }) { +const TONES = new Set(['accent', 'success', 'warning', 'danger', 'info']); + +/** + * Determinate or indeterminate progress, announced as a progressbar. + * + * + * + * + * + * `label` names it for screen readers (pass `aria-labelledby` instead when a + * visible label sits next to it). `tone` picks a semantic colour; `color` is + * the legacy raw-colour escape hatch and wins when both are set. + */ +export function ProgressBar({ + percent = 0, + tone, + color, + size = 'sm', + indeterminate = false, + label, + valueText, + className = '', + ...props +}) { const clamped = Math.max(0, Math.min(100, Number(percent) || 0)); - const fillStyle = { width: `${clamped}%`, ...(color && { background: color }) }; + const fillStyle = indeterminate + ? (color ? { background: color } : undefined) + : { width: `${clamped}%`, ...(color && { background: color }) }; return ( -
+
); diff --git a/frontend/src/components/ds/Stepper.jsx b/frontend/src/components/ds/Stepper.jsx new file mode 100644 index 00000000..dd3b0189 --- /dev/null +++ b/frontend/src/components/ds/Stepper.jsx @@ -0,0 +1,90 @@ +import { AlertTriangle, Check } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { cn } from '@/lib/utils'; +import { Button } from '@/components/ui/button'; + +// Styling lives in styles/components/_controls.scss (.sk-stepper*). + +// Read after the label by screen readers; the marker alone is visual only. +function statusCopy(t, status) { + if (status === 'complete') return t('common.controls.stepComplete', 'Completed'); + if (status === 'current') return t('common.controls.stepCurrent', 'Current step'); + if (status === 'error') return t('common.controls.stepError', 'Needs attention'); + return t('common.controls.stepUpcoming', 'Not started'); +} + +function statusOf(step, index, current) { + if (step.status) return step.status; + if (index < current) return 'complete'; + if (index === current) return 'current'; + return 'upcoming'; +} + +/** + * Progress through an ordered flow: setup, onboarding, a multi-page form, a + * deploy pipeline. + * + * + * + * Status comes from `current` (before = complete, at = current, after = + * upcoming) unless a step sets its own `status` ('error' for a failed one). + * With `onStepClick`, completed steps become buttons to go back to; the + * current and later steps stay inert so a flow cannot be skipped ahead. + */ +export function Stepper({ + steps = [], + current = 0, + orientation = 'horizontal', + onStepClick, + className, + 'aria-label': ariaLabel, +}) { + const { t } = useTranslation(); + return ( +
    + {steps.map((step, index) => { + const status = statusOf(step, index, current); + const clickable = onStepClick && status === 'complete'; + const marker = ( + <> + + + {step.label} + {step.description && {step.description}} + {statusCopy(t, status)} + + + ); + return ( +
  1. + {clickable ? ( + + ) : ( +
    {marker}
    + )} + {index < steps.length - 1 &&
  2. + ); + })} +
+ ); +} + +export default Stepper; diff --git a/frontend/src/components/ds/TreeView.jsx b/frontend/src/components/ds/TreeView.jsx new file mode 100644 index 00000000..d8f0947c --- /dev/null +++ b/frontend/src/components/ds/TreeView.jsx @@ -0,0 +1,205 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { ChevronRight, File, Folder, FolderOpen, Loader2 } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { cn } from '@/lib/utils'; + +// Styling lives in styles/components/_controls.scss (.sk-tree*). + +// Typeahead: keystrokes within this window extend one search string. +const TYPEAHEAD_RESET_MS = 500; + +// Flatten the expanded part of the tree into visible rows, in reading order. +function visibleRows(nodes, expanded, level = 1, parentId = null, rows = []) { + nodes.forEach((node, index) => { + const hasChildren = Boolean(node.children?.length) || node.hasChildren; + rows.push({ node, level, parentId, hasChildren, posinset: index + 1, setsize: nodes.length }); + if (hasChildren && expanded.has(node.id) && node.children) { + visibleRows(node.children, expanded, level + 1, node.id, rows); + } + }); + return rows; +} + +/** + * Hierarchical list: files, DNS zones, config trees, resource groups. + * + * open(node)} /> + * + * Nodes are `{ id, label, icon?, children?, hasChildren?, meta?, disabled? }`. + * `hasChildren` without `children` marks a lazy branch: expanding it calls + * `onLoadChildren(node)` (return a promise; the caller then supplies the + * children) and shows a spinner meanwhile. Expansion is internal unless + * `expandedIds` + `onExpandedChange` control it. + * + * Keyboard (WAI tree pattern): ↑/↓ move, → opens or steps into a branch, + * ← closes or steps out to the parent, Home/End, Enter/Space select, `*` + * opens every sibling, and typing jumps to the next matching label. + */ +export function TreeView({ + nodes = [], + selectedId, + onSelect, + expandedIds, + defaultExpandedIds = [], + onExpandedChange, + onLoadChildren, + className, + 'aria-label': ariaLabel, +}) { + const { t } = useTranslation(); + const [ownExpanded, setOwnExpanded] = useState(() => new Set(defaultExpandedIds)); + const expanded = useMemo(() => (expandedIds ? new Set(expandedIds) : ownExpanded), [expandedIds, ownExpanded]); + const [loading, setLoading] = useState(() => new Set()); + const [focusedId, setFocusedId] = useState(null); + const rowRefs = useRef(new Map()); + const typeahead = useRef({ text: '', timer: null }); + const focusWithin = useRef(false); + + const rows = useMemo(() => visibleRows(nodes, expanded), [nodes, expanded]); + const activeId = rows.some((row) => row.node.id === focusedId) + ? focusedId + : (rows.find((row) => row.node.id === selectedId) || rows[0])?.node.id; + + useEffect(() => () => clearTimeout(typeahead.current.timer), []); + useEffect(() => { + if (focusWithin.current && activeId != null) rowRefs.current.get(activeId)?.focus(); + }, [activeId]); + + const setExpanded = useCallback((next) => { + if (!expandedIds) setOwnExpanded(next); + onExpandedChange?.([...next]); + }, [expandedIds, onExpandedChange]); + + const expand = async (node) => { + if (expanded.has(node.id)) return; + setExpanded(new Set(expanded).add(node.id)); + if (!node.children && node.hasChildren && onLoadChildren) { + setLoading((prev) => new Set(prev).add(node.id)); + try { + await onLoadChildren(node); + } finally { + setLoading((prev) => { const next = new Set(prev); next.delete(node.id); return next; }); + } + } + }; + + const collapse = (node) => { + if (!expanded.has(node.id)) return; + const next = new Set(expanded); + next.delete(node.id); + setExpanded(next); + }; + + const toggle = (row) => (expanded.has(row.node.id) ? collapse(row.node) : expand(row.node)); + + const select = (row) => { + if (row.node.disabled) return; + setFocusedId(row.node.id); + onSelect?.(row.node); + }; + + const handleKeyDown = (event) => { + const index = rows.findIndex((row) => row.node.id === activeId); + const row = rows[index]; + if (!row) return; + const focus = (target) => { if (target) setFocusedId(target.node.id); }; + const keyActions = { + ArrowDown: () => focus(rows[index + 1]), + ArrowUp: () => focus(rows[index - 1]), + Home: () => focus(rows[0]), + End: () => focus(rows[rows.length - 1]), + ArrowRight: () => { + if (!row.hasChildren) return; + if (!expanded.has(row.node.id)) expand(row.node); + else if (rows[index + 1]?.parentId === row.node.id) focus(rows[index + 1]); + }, + ArrowLeft: () => { + if (row.hasChildren && expanded.has(row.node.id)) collapse(row.node); + else focus(rows.find((candidate) => candidate.node.id === row.parentId)); + }, + Enter: () => select(row), + ' ': () => select(row), + '*': () => { + const siblings = rows.filter((candidate) => candidate.parentId === row.parentId && candidate.hasChildren); + siblings.forEach((sibling) => expand(sibling.node)); + }, + }; + const action = keyActions[event.key]; + if (action) { + event.preventDefault(); + action(); + return; + } + if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) { + const state = typeahead.current; + clearTimeout(state.timer); + state.text += event.key.toLowerCase(); + state.timer = setTimeout(() => { state.text = ''; }, TYPEAHEAD_RESET_MS); + const ordered = [...rows.slice(index + 1), ...rows.slice(0, index + 1)]; + const searchFrom = state.text.length === 1 ? ordered : [row, ...ordered]; + focus(searchFrom.find((candidate) => String(candidate.node.label).toLowerCase().startsWith(state.text))); + } + }; + + return ( +
    { focusWithin.current = true; }} + onBlur={(event) => { + if (!event.currentTarget.contains(event.relatedTarget)) focusWithin.current = false; + }} + > + {rows.map((row) => { + const { node } = row; + const isOpen = expanded.has(node.id); + const isLoading = loading.has(node.id); + const selected = node.id === selectedId; + const DefaultIcon = row.hasChildren ? (isOpen ? FolderOpen : Folder) : File; + const Icon = node.icon || DefaultIcon; + return ( +
  • { + if (element) rowRefs.current.set(node.id, element); + else rowRefs.current.delete(node.id); + }} + role="treeitem" + tabIndex={node.id === activeId ? 0 : -1} + aria-level={row.level} + aria-posinset={row.posinset} + aria-setsize={row.setsize} + aria-expanded={row.hasChildren ? isOpen : undefined} + aria-selected={selected} + aria-disabled={node.disabled || undefined} + aria-busy={isLoading || undefined} + className={cn('sk-tree__row', selected && 'is-selected', node.disabled && 'is-disabled')} + style={{ '--sk-tree-level': row.level - 1 }} + onClick={() => { select(row); }} + onDoubleClick={() => { if (row.hasChildren) toggle(row); }} + > + +
  • + ); + })} +
+ ); +} + +export default TreeView; diff --git a/frontend/src/components/styleguide/ControlsShowcase.jsx b/frontend/src/components/styleguide/ControlsShowcase.jsx new file mode 100644 index 00000000..dea805b7 --- /dev/null +++ b/frontend/src/components/styleguide/ControlsShowcase.jsx @@ -0,0 +1,476 @@ +import { useState } from 'react'; +import { usePolling } from '../../hooks/usePolling'; +import { useTranslation } from 'react-i18next'; +import { + Bell, Copy, Database, Globe, HardDrive, RefreshCw, Rocket, Server, Settings, Trash2, +} from 'lucide-react'; +import { FormField, FormRow } from '../FormField'; +import { IconButton } from '../IconButton'; +import { ProgressBar } from '../ProgressBar'; +import { Stepper } from '../ds/Stepper'; +import { TreeView } from '../ds/TreeView'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Textarea } from '@/components/ui/textarea'; +import { Tip } from '@/components/ui/tooltip'; +import { NumberField } from '@/components/ui/number-field'; +import { Combobox } from '@/components/ui/combobox'; +import { TagInput } from '@/components/ui/tag-input'; +import { Calendar } from '@/components/ui/calendar'; +import { DatePicker, DateRangePicker } from '@/components/ui/date-picker'; +import { PinInput } from '@/components/ui/pin-input'; +import { Slider } from '@/components/ui/slider'; +import { RadioGroup } from '@/components/ui/radio-group'; +import { FileDropzone, FileUploadList } from '@/components/ui/file-dropzone'; +import { addDays, startOfDay } from '@/lib/dateMath'; + +const MB = 1024 * 1024; +const DOMAIN_PATTERN = /^(?!-)[a-z0-9-]{1,63}(\.[a-z0-9-]{1,63})+$/i; +// Upload simulation: percent added per tick, and the tick length. +const UPLOAD_STEP = 7; +const UPLOAD_TICK_MS = 180; + +function Demo({ id, title, note, children }) { + return ( +
+
+

{title}

+ {note &&

{note}

} +
+
{children}
+
+ ); +} + +function State({ label, children }) { + return ( +
+ {label} + {children} +
+ ); +} + +function buildTree(t) { + return [ + { + id: 'etc', label: 'etc', children: [ + { + id: 'nginx', label: 'nginx', children: [ + { id: 'nginx.conf', label: 'nginx.conf', meta: '2.4 KB' }, + { + id: 'sites-enabled', label: 'sites-enabled', children: [ + { id: 'shop.conf', label: 'shop.example.com.conf', meta: '1.1 KB' }, + { id: 'api.conf', label: 'api.example.com.conf', meta: '0.9 KB' }, + ], + }, + ], + }, + { id: 'ssh', label: 'ssh', hasChildren: true }, + { id: 'hosts', label: 'hosts', meta: '212 B' }, + ], + }, + { id: 'var', label: 'var', hasChildren: true }, + { id: 'locked', label: t('app.styleGuide.controls.treeLocked', 'root (no access)'), disabled: true }, + ]; +} + +export default function ControlsShowcase() { + const { t } = useTranslation(); + const today = startOfDay(new Date()); + + const [name, setName] = useState(''); + const [workers, setWorkers] = useState(4); + const [memory, setMemory] = useState(512); + const [ratio, setRatio] = useState(null); + const [server, setServer] = useState('web-01'); + const [scopes, setScopes] = useState(['apps:read', 'apps:deploy', 'logs:read', 'backups:read']); + const [labels, setLabels] = useState(['production']); + const [labelOptions, setLabelOptions] = useState(['production', 'staging', 'internal'].map((v) => ({ value: v, label: v }))); + const [domains, setDomains] = useState(['example.com', 'www.example.com']); + const [expires, setExpires] = useState(addDays(today, 30)); + const [range, setRange] = useState({ start: addDays(today, -6), end: today }); + const [inlineDay, setInlineDay] = useState(today); + const [code, setCode] = useState(''); + const [verified, setVerified] = useState(null); + const [retention, setRetention] = useState(30); + const [memoryMb, setMemoryMb] = useState(2048); + const [ports, setPorts] = useState([3000, 8000]); + const [strategy, setStrategy] = useState('rolling'); + const [plan, setPlan] = useState('standard'); + const [step, setStep] = useState(2); + const [treeNodes, setTreeNodes] = useState(() => buildTree(t)); + const [selectedFile, setSelectedFile] = useState('nginx.conf'); + const [uploads, setUploads] = useState([ + { id: 'a', name: 'site-backup-2026-10-24.tar.gz', size: 182 * MB, status: 'done' }, + { id: 'b', name: 'database-dump.sql.gz', size: 48 * MB, status: 'uploading', progress: 62 }, + { id: 'c', name: 'uploads.zip', size: 310 * MB, status: 'error', error: t('app.styleGuide.controls.uploadErrorDemo', 'The connection dropped at 41%.') }, + { id: 'd', name: 'media-library.zip', size: 96 * MB, status: 'queued' }, + ]); + const [saving, setSaving] = useState(false); + + // Move the "uploading" rows forward so the list reads as live. + usePolling(() => { + setUploads((items) => items.map((item) => { + if (item.status !== 'uploading') return item; + const progress = Math.min(100, (item.progress || 0) + UPLOAD_STEP); + return progress >= 100 ? { ...item, status: 'done', progress: 100 } : { ...item, progress }; + })); + }, UPLOAD_TICK_MS, { immediate: false }); + + const servers = [ + { value: 'web-01', label: 'web-01', description: t('app.styleGuide.controls.hostWeb01', '10.0.0.11 · Ubuntu 24.04'), icon: Server, group: t('app.styleGuide.controls.groupProduction', 'Production') }, + { value: 'web-02', label: 'web-02', description: t('app.styleGuide.controls.hostWeb02', '10.0.0.12 · Ubuntu 24.04'), icon: Server, group: t('app.styleGuide.controls.groupProduction', 'Production') }, + { value: 'db-01', label: 'db-01', description: t('app.styleGuide.controls.hostDb01', '10.0.0.21 · Debian 13'), icon: Database, group: t('app.styleGuide.controls.groupProduction', 'Production') }, + { value: 'staging', label: 'staging-01', description: t('app.styleGuide.controls.hostStaging', '10.0.1.5 · Rocky 9'), icon: Server, group: t('app.styleGuide.controls.groupStaging', 'Staging') }, + { value: 'edge', label: 'edge-ams', description: t('app.styleGuide.controls.offline', 'Offline'), icon: Globe, group: t('app.styleGuide.controls.groupStaging', 'Staging'), disabled: true }, + ]; + const scopeOptions = ['apps:read', 'apps:deploy', 'apps:delete', 'logs:read', 'backups:read', 'backups:restore', 'dns:write'] + .map((value) => ({ value, label: value })); + + const loadChildren = (node) => new Promise((resolve) => { + setTimeout(() => { + const children = node.id === 'ssh' + ? [{ id: 'sshd_config', label: 'sshd_config', meta: '3.3 KB' }, { id: 'ssh_config', label: 'ssh_config', meta: '1.5 KB' }] + : [{ id: 'log', label: 'log', hasChildren: true }, { id: 'www', label: 'www', hasChildren: true }]; + const attach = (nodes) => nodes.map((item) => (item.id === node.id + ? { ...item, children } + : item.children ? { ...item, children: attach(item.children) } : item)); + setTreeNodes((nodes) => attach(nodes)); + resolve(); + }, 700); + }); + + const steps = [ + { id: 'source', label: t('app.styleGuide.controls.stepSource', 'Source'), description: 'github.com/acme/shop' }, + { id: 'build', label: t('app.styleGuide.controls.stepBuild', 'Build'), description: t('app.styleGuide.controls.stepBuildNote', 'Node 20 detected') }, + { id: 'configure', label: t('app.styleGuide.controls.stepConfigure', 'Configure') }, + { id: 'deploy', label: t('app.styleGuide.controls.stepDeploy', 'Deploy') }, + ]; + + return ( +
+ {/* ── TIER 1 ── */} + + + + setName(e.target.value)} placeholder="shop-api" /> + + + + + + +