Skip to content

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

Add real preview deployments and strengthen core boundaries (#184)

Juan Denis6e096fa28625
diff --git a/.github/workflows/frontend-ci.yml b/.github/workflows/frontend-ci.yml
index 5518f496..ca928566 100644
--- a/.github/workflows/frontend-ci.yml
+++ b/.github/workflows/frontend-ci.yml
@@ -80,6 +80,15 @@ jobs:
- name: File Manager browser regressions
working-directory: frontend
run: npm run test:file-manager
+ - 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
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/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/VERSION b/VERSION
index f2a994ec..0ce40b95 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.11.24
+1.11.26
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/api/env_vars.py b/backend/app/api/env_vars.py
index 555f6cbe..a2fff981 100644
--- a/backend/app/api/env_vars.py
+++ b/backend/app/api/env_vars.py
@@ -26,6 +26,13 @@ def get_env_vars(app_id):
user = get_current_user()
app = require_app(app_id)
+ if request.args.get('view') == 'effective':
+ service = request.args.get('service') or None
+ if service is not None and (len(service) > 255 or not all(
+ c.isalnum() or c in '._-' for c in service)):
+ return jsonify({'error': 'Invalid service name'}), 400
+ return jsonify(EnvService.get_effective_env_view(app_id, service=service)), 200
+
# A read-only grant never sees secret values, whatever ?mask says.
mask_secrets = (request.args.get('mask', 'false').lower() == 'true'
or not ResourceGrantService.can_edit_app(user, app))
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('/<int:app_id>/previews/<int:preview_id>', 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('/<int:app_id>/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/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/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/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/configuration.py b/backend/app/bootstrap/configuration.py
new file mode 100644
index 00000000..3baf33ba
--- /dev/null
+++ b/backend/app/bootstrap/configuration.py
@@ -0,0 +1,114 @@
+"""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..855ab2a9
--- /dev/null
+++ b/backend/app/bootstrap/http.py
@@ -0,0 +1,100 @@
+"""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..09bbac55
--- /dev/null
+++ b/backend/app/bootstrap/logging.py
@@ -0,0 +1,53 @@
+"""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..3da1a06e
--- /dev/null
+++ b/backend/app/bootstrap/persistence.py
@@ -0,0 +1,74 @@
+"""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..fac42346
--- /dev/null
+++ b/backend/app/bootstrap/plugins.py
@@ -0,0 +1,63 @@
+"""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..d03908a4
--- /dev/null
+++ b/backend/app/bootstrap/runtime.py
@@ -0,0 +1,86 @@
+"""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')
+
+ 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():
+ 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/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/models/application_preview.py b/backend/app/models/application_preview.py
index 53201d25..4688adbb 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)
@@ -47,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)
@@ -59,17 +66,34 @@ 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
+ # 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': (
+ 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}' if self.domain else None),
- 'container_ids': self.get_container_ids(),
+ '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,
'short_sha': self.commit_sha[:7] if self.commit_sha else None,
'expires_at': self.expires_at.isoformat() if self.expires_at else None,
@@ -95,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)
@@ -108,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/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/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/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/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/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/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/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/env_service.py b/backend/app/services/env_service.py
index 2ff6e523..aaa32590 100644
--- a/backend/app/services/env_service.py
+++ b/backend/app/services/env_service.py
@@ -87,34 +87,79 @@ class EnvService:
if not app:
return {}
- merged = {}
+ entries, _ = EnvService._effective_entries(app)
+ return {key: entry['value'] for key, entry in entries.items()}
+
+ @staticmethod
+ def _effective_entries(app, service=None, metadata_only=False, local_vars=None):
+ """One precedence seam for deployment and the read-only provenance view.
- # 1) Shared variable groups — the base layer (lowest precedence).
+ Metadata mode never resolves local references or returns values. Shared
+ interpolation remains before local overrides, matching deployment.
+ """
+ merged = {}
+ complete = True
+ context = {
+ name: str(getattr(app, name)) if getattr(app, name) is not None else None
+ for name in ('workspace_id', 'project_id', 'environment_id')
+ }
try:
from app.services.shared_resource_service import SharedResourceService
- context = {
- # scope_id is stored as a string when groups are created, so
- # coerce the app's numeric ids to match on lookup.
- 'workspace_id': str(app.workspace_id) if app.workspace_id is not None else None,
- 'project_id': str(app.project_id) if app.project_id is not None else None,
- 'environment_id': str(app.environment_id) if app.environment_id is not None else None,
- }
resolved = SharedResourceService.resolve_hierarchical(
- 'application', application_id, context=context,
- mask_secrets=False, interpolate=True,
+ 'application', app.id, context=context, service=service,
+ mask_secrets=metadata_only, interpolate=not metadata_only,
)
for entry in resolved or []:
key = entry.get('key')
if key:
- merged[key] = entry.get('value')
- except Exception as e: # best-effort — never block a deploy on shared vars
- logger.warning('Shared variable resolution failed for app %s: %s', application_id, e)
-
- # 2) Local env vars — the override layer (highest precedence wins).
- for ev in EnvironmentVariable.query.filter_by(application_id=application_id).all():
- merged[ev.key] = EnvService._resolve_var_value(app, ev)
+ # Explicit projection: never carry resolver values or future
+ # sensitive fields into the metadata API.
+ merged[key] = {
+ field: entry.get(field) for field in (
+ 'key', 'source_scope', 'group_id', 'group_name',
+ 'target_service', 'is_secret',
+ )
+ }
+ if not metadata_only:
+ merged[key]['value'] = entry.get('value')
+ except Exception:
+ complete = False
+ merged.clear()
+ logger.warning('Shared variable resolution failed for app %s', app.id)
+
+ if local_vars is None:
+ local_vars = EnvironmentVariable.query.filter_by(application_id=app.id).all()
+ for ev in local_vars:
+ if service is not None and ev.target_service not in (None, '', service):
+ continue
+ inherited = merged.get(ev.key)
+ entry = {
+ 'key': ev.key, 'source_scope': 'local',
+ 'group_id': None, 'group_name': None,
+ 'target_service': ev.target_service,
+ 'is_secret': bool(ev.is_secret),
+ 'is_reference': bool(ev.value_from),
+ 'overrides': ({field: inherited.get(field) for field in
+ ('source_scope', 'group_id', 'group_name')}
+ if inherited else None),
+ }
+ if not metadata_only:
+ entry['value'] = EnvService._resolve_var_value(app, ev)
+ merged[ev.key] = entry
+ return merged, complete
- return merged
+ @staticmethod
+ def get_effective_env_view(application_id, service=None):
+ """Managed configuration provenance, not a live container inspection."""
+ app = Application.query_active().filter_by(id=application_id).first()
+ if not app:
+ return {'env_vars': [], 'count': 0, 'complete': False}
+ entries, complete = EnvService._effective_entries(
+ app, service=service, metadata_only=True,
+ )
+ rows = [entries[key] for key in sorted(entries)]
+ return {'env_vars': rows, 'count': len(rows), 'complete': complete,
+ 'service': service, 'values_hidden': True}
@staticmethod
def _resolve_var_value(app, ev):
@@ -203,36 +248,11 @@ class EnvService:
if not app or not service_names:
return {}
- context = {
- 'workspace_id': str(app.workspace_id) if app.workspace_id is not None else None,
- 'project_id': str(app.project_id) if app.project_id is not None else None,
- 'environment_id': str(app.environment_id) if app.environment_id is not None else None,
- }
local_vars = EnvironmentVariable.query.filter_by(application_id=application_id).all()
-
result = {}
for svc in service_names:
- env = {}
- # Shared groups applicable to this service (NULL-target + this svc).
- try:
- from app.services.shared_resource_service import SharedResourceService
- resolved = SharedResourceService.resolve_hierarchical(
- 'application', application_id, context=context,
- mask_secrets=False, interpolate=True, service=svc,
- )
- for entry in resolved or []:
- key = entry.get('key')
- if key:
- env[key] = entry.get('value')
- except Exception as e: # best-effort
- logger.warning('Shared resolution failed for app %s svc %s: %s',
- application_id, svc, e)
- # Local vars override; include all-services + this-service targets.
- for ev in local_vars:
- tgt = ev.target_service
- if tgt in (None, '') or tgt == svc:
- env[ev.key] = EnvService._resolve_var_value(app, ev)
- result[svc] = env
+ entries, _ = EnvService._effective_entries(app, service=svc, local_vars=local_vars)
+ result[svc] = {key: entry['value'] for key, entry in entries.items()}
return result
@staticmethod
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 <path>:``
+ 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 `^<HOST> -` filters) keeps matching; the timing
+# fields are appended after them. The app id is the log file itself
+# (/var/log/nginx/<app>.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};
-
- 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 `^<HOST> -` filters) keeps matching; the timing
- # fields are appended after them. The app id is the log file itself
- # (/var/log/nginx/<app>.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}
+ # 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
-{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 <path>:``
- 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:
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/app/services/preview_service.py b/backend/app/services/preview_service.py
index 90836b58..1ef19dca 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, 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, manual=not request_payload, log_callback=log_callback)
+
+ @classmethod
+ 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,
@@ -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')
@@ -272,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
@@ -280,18 +300,23 @@ 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()
# 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)
+ 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'):
+ preview.status = ApplicationPreview.STATUS_RUNNING
+ else:
+ 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:
@@ -303,14 +328,12 @@ 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': [...]}``.
- 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 runtimes have a separate
+ journalled provisioner reusing the standard container builders.
+ A provider must explicitly report success and return runtime identifiers.
"""
try:
if getattr(app, 'app_type', None) == 'wordpress':
@@ -323,29 +346,39 @@ 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)
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': True, 'container_ids': [],
- 'manifest_preview': manifest_preview}
+ from app.services.previews.provisioner import provision
+ 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': []}
@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)
+ 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
+ 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
@@ -354,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
@@ -367,6 +400,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:
@@ -390,7 +427,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):
@@ -411,26 +452,31 @@ 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,
).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)}
@@ -439,16 +485,16 @@ 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)
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 []
+ return None
@classmethod
def expire_stale(cls):
@@ -463,9 +509,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)}
@@ -482,18 +527,38 @@ class PreviewService:
app = Application.query_active().filter_by(
id=payload.get('application_id')).first()
if not app:
- return {'error': 'Service not found'}
- return cls.create_preview(app, payload.get('pr') or 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':
+ 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') or result.get('failed'):
+ raise RuntimeError(result.get('error') or 'Some preview operations failed')
+ 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/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/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..84d20e28
--- /dev/null
+++ b/backend/app/services/previews/provisioner.py
@@ -0,0 +1,71 @@
+"""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, log_callback=None):
+ 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)
+ 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', 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':
+ 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..72d0d39e
--- /dev/null
+++ b/backend/app/services/previews/requests.py
@@ -0,0 +1,60 @@
+"""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']
+
+
+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
new file mode 100644
index 00000000..50104d66
--- /dev/null
+++ b/backend/app/services/previews/runtime.py
@@ -0,0 +1,129 @@
+"""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, 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),
+ 'SERVERKIT_PREVIEW_BRANCH': preview.branch}
+ if 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::{container_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'{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.')
+ 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..b7a5f70b
--- /dev/null
+++ b/backend/app/services/previews/source.py
@@ -0,0 +1,50 @@
+"""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, 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']
+ 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, log_callback=log_callback,
+ )
+ if not result.get('success'):
+ raise PreviewError('Preview image build failed. See the preview job logs.')
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/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/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/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/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/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_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)
+
+
+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
+
+
[email protected]('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/backend/tests/test_bootstrap_boundaries.py b/backend/tests/test_bootstrap_boundaries.py
new file mode 100644
index 00000000..a3f2c47e
--- /dev/null
+++ b/backend/tests/test_bootstrap_boundaries.py
@@ -0,0 +1,140 @@
+"""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
+
+
+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.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')},
+ '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
+
+
[email protected]('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 == []
+
+
[email protected]('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', 'agents', 'metrics', 'webhooks', 'notifications',
+ 'analytics', 'handlers', 'jobs', 'monitoring',
+ 'uptime', 'linked', 'relay']
+
+
+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_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()
+
+
[email protected]('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'):
+ 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'
diff --git a/backend/tests/test_effective_env.py b/backend/tests/test_effective_env.py
index 94198dd2..18627485 100644
--- a/backend/tests/test_effective_env.py
+++ b/backend/tests/test_effective_env.py
@@ -135,3 +135,59 @@ def test_deploy_docker_injects_effective_env(app, monkeypatch):
assert env['SHARED_ONLY'] == 'from_group' # shared var reached the container
assert env['OVERRIDE_ME'] == 'local_value' # local won the collision
assert env['LOCAL_ONLY'] == 'local_only'
+
+
+def test_effective_view_matches_winners_without_values(app):
+ from app import db
+ from app.services.env_service import EnvService
+ with app.app_context():
+ a = _make_app(workspace_id=7)
+ _make_scoped_group('workspace', 7, 'SHARED', 'inherited-secret')
+ _make_scoped_group('workspace', 7, 'OVERRIDE', 'old-secret')
+ _set_local(a.id, 'OVERRIDE', 'new-secret', is_secret=True)
+ local = _set_local(a.id, 'TARGET', 'target-secret')
+ local.target_service = 'web'
+ db.session.commit()
+ for service in ('web', 'worker'):
+ view = EnvService.get_effective_env_view(a.id, service)
+ deployed = EnvService.get_effective_env_for_services(a.id, [service])[service]
+ assert view['complete'] and view['values_hidden']
+ assert {row['key'] for row in view['env_vars']} == set(deployed)
+ rows = {row['key']: row for row in view['env_vars']}
+ assert rows['SHARED']['source_scope'] == 'workspace'
+ assert rows['OVERRIDE']['source_scope'] == 'local'
+ assert rows['OVERRIDE']['overrides']['group_name'] == 'workspace-grp'
+ assert 'secret' not in str(view).replace('is_secret', '')
+ assert all('value' not in row for row in rows.values())
+
+
+def test_effective_view_reports_incomplete_shared_resolution(app, monkeypatch):
+ from app.services.env_service import EnvService
+ from app.services.shared_resource_service import SharedResourceService
+ with app.app_context():
+ a = _make_app()
+ _set_local(a.id, 'LOCAL', 'private')
+ def fail(*args, **kwargs):
+ raise RuntimeError('sensitive connection details')
+ monkeypatch.setattr(SharedResourceService, 'resolve_hierarchical', fail)
+ view = EnvService.get_effective_env_view(a.id)
+ assert view['complete'] is False
+ assert [row['key'] for row in view['env_vars']] == ['LOCAL']
+ assert 'sensitive' not in str(view)
+ assert EnvService.get_effective_env(a.id) == {'LOCAL': 'private'}
+
+
+def test_effective_view_never_resolves_local_references(app, monkeypatch):
+ from app import db
+ from app.services.env_service import EnvService
+ with app.app_context():
+ a = _make_app()
+ ev = _set_local(a.id, 'REF', '')
+ ev.set_reference({'kind': 'secret', 'secret': 'credential'})
+ db.session.commit()
+ def fail(*args):
+ raise AssertionError('metadata must not decrypt or resolve local values')
+ monkeypatch.setattr(EnvService, '_resolve_var_value', fail)
+ view = EnvService.get_effective_env_view(a.id)
+ assert view['env_vars'][0]['is_reference'] is True
+ assert 'credential' not in str(view)
diff --git a/backend/tests/test_env_vars_api.py b/backend/tests/test_env_vars_api.py
index bc16ce70..aecfc6f9 100644
--- a/backend/tests/test_env_vars_api.py
+++ b/backend/tests/test_env_vars_api.py
@@ -43,3 +43,49 @@ def test_null_description_clears_but_omitted_leaves_it(app, client):
headers=headers)
assert res.status_code == 200
assert res.get_json()['env_var']['description'] is None
+
+
+def test_effective_view_is_value_free_and_app_scoped(app, client):
+ from factories import headers_for, make_user
+ with app.app_context():
+ application, owner = _seed_var(app)
+ app_id = application.id
+ owner_headers = headers_for(owner)
+ stranger = make_user(db, role='viewer')
+ stranger_headers = headers_for(stranger)
+ url = f'/api/v1/apps/{app_id}/env?view=effective'
+ response = client.get(url, headers=owner_headers)
+ assert response.status_code == 200
+ data = response.get_json()
+ assert data['values_hidden'] and data['complete']
+ assert data['env_vars'][0]['key'] == 'API_URL'
+ assert 'https://api.example.test' not in response.get_data(as_text=True)
+ assert 'value' not in data['env_vars'][0]
+ assert client.get(url, headers=stranger_headers).status_code in (403, 404)
+ assert client.get(url).status_code == 401
+ assert client.get(url + '&service=bad/name', headers=owner_headers).status_code == 400
+
+
+def test_effective_view_grant_never_reveals_values_and_tombstone_denied(app, client):
+ from datetime import datetime
+ from factories import headers_for, make_user
+ from app.services.resource_grant_service import ResourceGrantService
+ from app.services.env_service import EnvService
+ with app.app_context():
+ application, owner = _seed_var(app)
+ EnvService.set_env_var(application.id, 'PASSWORD', 'super-private', is_secret=True)
+ viewer = make_user(db, role='viewer')
+ ResourceGrantService.grant(user_id=viewer.id, resource_type='application',
+ resource_id=application.id, granted_by=owner.id, role='viewer')
+ headers = headers_for(viewer)
+ app_id = application.id
+ url = f'/api/v1/apps/{app_id}/env?view=effective&mask=false'
+ response = client.get(url, headers=headers)
+ assert response.status_code == 200
+ assert 'super-private' not in response.get_data(as_text=True)
+ assert all('value' not in row for row in response.get_json()['env_vars'])
+ with app.app_context():
+ row = db.session.get(Application, app_id)
+ row.deleted_at = datetime.utcnow()
+ db.session.commit()
+ assert client.get(url, headers=headers).status_code == 404
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')
+
+
+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
+
+
[email protected]('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]
diff --git a/backend/tests/test_generic_previews.py b/backend/tests/test_generic_previews.py
new file mode 100644
index 00000000..66165798
--- /dev/null
+++ b/backend/tests/test_generic_previews.py
@@ -0,0 +1,387 @@
+"""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}
+
+
+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, **kwargs):
+ 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
+
+
[email protected]('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, **kwargs):
+ original(*args, **kwargs)
+ 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)
+
+
+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
+
+
+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'
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}'
+
+
[email protected]('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')
+
+
[email protected]('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/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()
+
+
[email protected]('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]
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()
+
+
[email protected]('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_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
+
+
[email protected]('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)]
+
+
[email protected]('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_previews.py b/backend/tests/test_previews.py
index 27cfdf3e..69126e7c 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_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_RUNNING
+ assert row is not None and row.status == ApplicationPreview.STATUS_FAILED
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/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', '[email protected]', 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/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):
[email protected]('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/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`
diff --git a/docs/CORE_BOUNDARIES.md b/docs/CORE_BOUNDARIES.md
new file mode 100644
index 00000000..5485f556
--- /dev/null
+++ b/docs/CORE_BOUNDARIES.md
@@ -0,0 +1,220 @@
+# 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.
+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` 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
+
+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.
+
+## 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
+ 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_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.
+- 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;
+first decide which existing owner should contain the behavior.
+
+
+## Effective environment and preview truthfulness
+
+`EnvService._effective_entries` owns the shared/local merge used by both
+single-container and per-service Compose deployment, and by the read-only
+`GET /api/v1/apps/<id>/env?view=effective&service=<name>` projection. Preserve
+workspace → project → environment → attached group → local precedence and
+filter service targets before merging. Shared interpolation precedes local
+overrides, as in the existing deployment path.
+
+The effective view is managed configuration for the next deploy/restart, not
+an inspection of the running container or of image/Compose-file defaults.
+Its explicit field allowlist excludes **all values**, including non-secret
+variables that could interpolate a secret. Local references are not resolved
+for this view. Existing app access checks apply; `mask=false` cannot enable
+values. A shared-resolution failure returns `complete: false`, with local
+rows only. Do not present that fallback as complete configuration.
+
+`components/environment/EnvironmentPanel` composes the existing local editor
+with `EffectiveEnvironment`. The view renders provenance; the hook owns service
+discovery, fetching and stale-response suppression. Keep precedence on the
+backend. A service-discovery request failure must not silently fall back to
+unfiltered winners. The existing discovery endpoint returns an empty list for
+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 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
+`node scripts/effective-environment-browser.mjs` (in `frontend`). The browser
+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/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 `<slug>__<name>`, 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/docs/MIGRATION_INVENTORY.md b/docs/MIGRATION_INVENTORY.md
index 85d2a556..9d6b3236 100644
--- a/docs/MIGRATION_INVENTORY.md
+++ b/docs/MIGRATION_INVENTORY.md
@@ -16,11 +16,11 @@ 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 | 395 | 398 | migrate when touched |
-| per-page toast.error extractions in pages/ | E1: query-layer error presentation | 199 | 206 | migrate when touched |
+| 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 |
| 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/package.json b/frontend/package.json
index 617f03a2..8e5f9374 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -15,6 +15,8 @@
"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: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 <><ToolCallCard call={call}/><ConfirmActionCard/></>;
+}
+createRoot(document.getElementById('root')).render(<React.StrictMode><App/></React.StrictMode>);
+`;
+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',
+ '<div id="root"></div><script type="module" src="/ai-operation-fixture.jsx"></script>'));
+ });
+ },
+ }, 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/scripts/check-file-manager-boundaries.mjs b/frontend/scripts/check-file-manager-boundaries.mjs
new file mode 100644
index 00000000..62044db3
--- /dev/null
+++ b/frontend/scripts/check-file-manager-boundaries.mjs
@@ -0,0 +1,66 @@
+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 || 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`);
+ }
+ 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..1bb3ca42 100644
--- a/frontend/scripts/check-frontend-boundaries.mjs
+++ b/frontend/scripts/check-frontend-boundaries.mjs
@@ -9,6 +9,12 @@
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import { dirname, extname, join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+// 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, '..');
@@ -119,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/effective-environment-browser.mjs b/frontend/scripts/effective-environment-browser.mjs
new file mode 100644
index 00000000..7883d99d
--- /dev/null
+++ b/frontend/scripts/effective-environment-browser.mjs
@@ -0,0 +1,135 @@
+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 from 'react';
+import {createRoot} from 'react-dom/client';
+import {MemoryRouter} from 'react-router-dom';
+import EnvironmentPanel from '/src/components/environment/EnvironmentPanel.jsx';
+import PreviewList from '/src/components/previews/PreviewList.jsx';
+import {ConfirmProvider} from '/src/contexts/ConfirmContext.jsx';
+window.pending=[]; window.calls=[]; window.toasts=[];
+window.answer=(service,data)=>window.pending.splice(window.pending.findIndex(x=>x.service===service),1)[0].resolve(data);
+window.testApi={
+ getEnvVars:()=>Promise.resolve({env_vars:[]}),
+ getComposeServices:()=>window.discoveryError?Promise.reject(Error('no discovery')):Promise.resolve({services:['web','worker']}),
+ getEffectiveEnvVars:(id,service)=>{window.calls.push(service);return new Promise((resolve,reject)=>window.pending.push({service,resolve,reject}));},
+ 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(<MemoryRouter><ConfirmProvider>{location.search==='?preview'?<PreviewList appId={1}/>:<EnvironmentPanel appId={1}/>}</ConfirmProvider></MemoryRouter>);
+`;
+const server = await createServer({
+ root, configFile: false, logLevel: 'error', resolve: { alias: { '@': path.join(root, 'src') } },
+ cacheDir: path.join(root, 'node_modules/.vite-effective-environment-regression'),
+ optimizeDeps: { entries: [] }, server: { host: '127.0.0.1', port: 0 },
+ plugins: [{
+ name: 'effective-environment-fixtures', enforce: 'pre',
+ resolveId(id) {
+ if (id === 'react-i18next') return '\0test-i18n';
+ if (id.endsWith('/env-fixture.jsx')) return path.join(root, 'env-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/contexts/useAuth.js')) return `import {createContext} from 'react';export const AuthContext=createContext(null);const auth={user:{id:1,role:'admin'},isAdmin:true,isAuthenticated:true,hasPermission:()=>true};export const useAuth=()=>auth;`;
+ if (normalized.endsWith('/src/contexts/useWorkspace.js')) return `const ws={activeWorkspaceId:null,workspaces:[],setActiveWorkspace(){}};export const useWorkspace=()=>ws;`;
+ if (normalized.endsWith('/src/contexts/useToast.js')) return `const toast={error(m){(window.toasts=window.toasts||[]).push(m)},success(m){(window.toasts=window.toasts||[]).push('SUCCESS:'+m)},info(){},warning(){}};export const useToast=()=>toast;`;
+ 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('/env-fixture.jsx')) return fixture;
+ },
+ configureServer(vite) {
+ vite.middlewares.use('/env-check', async (_req, res) => {
+ res.setHeader('Content-Type', 'text/html');
+ res.end(await vite.transformIndexHtml('/env-check', '<div id="root"></div><script type="module" src="/env-fixture.jsx"></script>'));
+ });
+ },
+ }, 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));
+ const url = `http://127.0.0.1:${server.httpServer.address().port}/env-check`;
+ await page.goto(url);
+ await page.getByRole('tab', {name:'Effective environment', exact:true}).click();
+ await page.waitForFunction(()=>window.pending.some(x=>x.service==='web'));
+ const choose = async name => {
+ await page.getByRole('combobox', {name:'Compose service'}).click();
+ await page.getByRole('option', {name, exact:true}).click();
+ };
+ await choose('worker');
+ await page.waitForFunction(()=>window.pending.some(x=>x.service==='worker'));
+ await page.evaluate(()=>window.answer('worker',{complete:true,env_vars:[{key:'WORKER_KEY',source_scope:'local',overrides:{source_scope:'workspace',group_name:'shared'},value:'DO-NOT-RENDER'}]}));
+ await page.getByText('WORKER_KEY',{exact:true}).waitFor();
+ await page.evaluate(()=>window.answer('web',{complete:true,env_vars:[{key:'STALE_WEB',source_scope:'project'}]}));
+ await page.waitForTimeout(150);
+ assert.equal(await page.getByText('STALE_WEB',{exact:true}).count(),0);
+ assert.equal(await page.getByText('DO-NOT-RENDER',{exact:true}).count(),0);
+ assert.equal(await page.getByText('Workspace / shared',{exact:true}).count(),1);
+ await page.getByRole('button',{name:'Refresh',exact:true}).click();
+ await page.waitForFunction(()=>window.pending.some(x=>x.service==='worker'));
+ assert.equal(await page.getByText('WORKER_KEY',{exact:true}).count(),0);
+ await page.evaluate(()=>window.answer('worker',{complete:false,env_vars:[{key:'LOCAL_ONLY',source_scope:'local'}]}));
+ await page.getByRole('alert').filter({hasText:'Incomplete:'}).waitFor();
+ await page.getByText('LOCAL_ONLY',{exact:true}).waitFor();
+ await page.getByRole('button',{name:'Refresh',exact:true}).click();
+ await page.waitForFunction(()=>window.pending.length>0);
+ await page.evaluate(()=>window.pending.shift().reject(Error('network')));
+ await page.getByRole('alert').filter({hasText:'Could not load'}).waitFor();
+ assert.equal(await page.getByText('LOCAL_ONLY',{exact:true}).count(),0);
+ // Failed service discovery must not silently use an unfiltered result.
+ const before = await page.evaluate(()=>window.calls.length);
+ await page.evaluate(()=>{window.discoveryError=true;});
+ await page.getByRole('button',{name:'Refresh',exact:true}).click();
+ await page.getByRole('alert').filter({hasText:'Could not load'}).waitFor();
+ assert.equal(await page.evaluate(()=>window.calls.length),before);
+ await page.getByRole('tab',{name:'Local variables',exact:true}).click();
+ await page.getByText('No environment variables',{exact:true}).waitFor();
+ assert.deepEqual(errors,[]);
+ console.log('PASS effective environment: service races, masking, overrides, incomplete/error/retry, local editor');
+
+ await page.goto(url+'?preview');
+ await page.getByText('unavailable',{exact:true}).waitFor();
+ assert.equal(await page.locator('a[href="https://unavailable.test"]').count(),0);
+ assert.equal(await page.locator('a[href="https://running.test"]').count()>0,true);
+ await page.getByRole('button',{name:'Redeploy',exact:true}).first().click();
+ await page.waitForFunction(()=>window.toasts.length>0);
+ assert.equal(await page.evaluate(()=>window.toasts.some(x=>x.includes('not deployed'))),true);
+ 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/scripts/file-manager-browser.mjs b/frontend/scripts/file-manager-browser.mjs
index f1039b94..cf92b3d3 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(<MemoryRouter initialEntries={['/files']}><FileManager/></MemoryRouter>);
+createRoot(document.getElementById('root')).render(<MemoryRouter initialEntries={[window.initialPath || '/files']}><ConfirmProvider><FileManager/></ConfirmProvider></MemoryRouter>);
`;
const server = await createServer({
root, configFile: false, logLevel: 'error', resolve: { alias: { '@': path.join(root, 'src') } },
@@ -150,6 +151,218 @@ 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.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, []);
+ console.log('PASS preview read races, failed-save draft retention and target reset');
+
+ // 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();
+ 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');
+
+ 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');
+
+ 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');
+
+ 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/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 <><SearchField value={query} onSearch={setQuery} placeholder="Reset search"/><button onClick={()=>setQuery('')}>Reset search</button><output id="query">{query}</output></>}
+const initial=page==='templates'?'/templates':page==='monitors'?'/monitors':page==='jobs'?'/jobs':page==='telemetry'?'/telemetry':'/services';
+const app=page==='field'?<FieldReset/>:<MemoryRouter initialEntries={[initial]}><Routes><Route element={<TabGroupLayout tabs={[{to:'/services',label:'Services'},{to:'/templates',label:'Templates'},{to:'/monitors',label:'Monitors'},{to:'/jobs',label:'Jobs'},{to:'/telemetry',label:'Telemetry'}]}/>}><Route path="/services" element={<Services/>}/><Route path="/templates" element={<Templates/>}/><Route path="/monitors" element={<Monitors/>}/><Route path="/jobs" element={<Jobs/>}/><Route path="/telemetry" element={<Telemetry/>}/></Route></Routes></MemoryRouter>;
+createRoot(document.getElementById('root')).render(page==='monitors'||page==='jobs'||page==='telemetry'?app:<React.StrictMode>{app}</React.StrictMode>);
+`;
+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', '<div id="root"></div><script type="module" src="/search-fixture.jsx"></script>'));
+ });
+ },
+ }, 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/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 (
<div className="sk-ai-confirm" role="group" aria-label={t('app.confirmActionCard.confirmAction', 'Confirm action')}>
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 "<prefix>__" 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'
? <Loader2 size={14} className="sk-ai-spin" />
@@ -48,6 +63,16 @@ const ToolCallCard = ({ call }) => {
</span>
<ChevronDown size={14} className={`sk-ai-tool-card__chev${expanded ? ' is-open' : ''}`} />
</SharedButton>
+ {operation && (
+ <div className="sk-ai-tool-card__body">
+ <SharedButton type="button" variant="ghost" size="sm" onClick={() => {
+ openTab('ops');
+ openRun('deploy', operation.id);
+ }}>
+ {t('ai.openOperation', 'Open in Operations')}
+ </SharedButton>
+ </div>
+ )}
{expanded && (
<div className="sk-ai-tool-card__body">
{Custom ? (
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/components/environment/EffectiveEnvironment.jsx b/frontend/src/components/environment/EffectiveEnvironment.jsx
new file mode 100644
index 00000000..e26f8a1f
--- /dev/null
+++ b/frontend/src/components/environment/EffectiveEnvironment.jsx
@@ -0,0 +1,47 @@
+import { useTranslation } from 'react-i18next';
+import DataTable from '../ds/DataTable';
+import DataTableFooter from '../ds/DataTableFooter';
+import ListToolbar from '../ds/ListToolbar';
+import { Button } from '../ui/button';
+import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from '../ui/select';
+import { useEffectiveEnvironment } from './useEffectiveEnvironment';
+
+export default function EffectiveEnvironment({ appId }) {
+ const { t } = useTranslation();
+ const { services, service, selectService, data, loading, error, refresh } = useEffectiveEnvironment(appId);
+ const scopes = {
+ local: t('effectiveEnv.local', 'Local variables'),
+ workspace: t('effectiveEnv.workspace', 'Workspace'),
+ project: t('effectiveEnv.project', 'Project'),
+ environment: t('effectiveEnv.environment', 'Environment'),
+ resource: t('effectiveEnv.resource', 'Attached group'),
+ direct: t('effectiveEnv.resource', 'Attached group'),
+ };
+ const source = row => [scopes[row.source_scope] || row.source_scope, row.group_name].filter(Boolean).join(' / ');
+ const rows = data?.env_vars || [];
+ const columns = [
+ { key: 'key', header: t('effectiveEnv.key', 'Key'), sortable: true, render: row => <code>{row.key}</code> },
+ { key: 'source_scope', header: t('effectiveEnv.source', 'Winning source'), render: source },
+ { key: 'overrides', header: t('effectiveEnv.overrides', 'Overrides inherited source'), render: row => row.overrides ? source(row.overrides) : '—' },
+ { key: 'target_service', header: t('effectiveEnv.target', 'Target service'), render: row => row.target_service || t('effectiveEnv.allServices', 'All services') },
+ { key: 'is_reference', header: t('effectiveEnv.value', 'Value'), render: row => row.is_reference ? t('effectiveEnv.reference', 'Reference · resolved at deployment') : t('effectiveEnv.hidden', 'Hidden') },
+ ];
+ return <div className="env-vars-container">
+ <p className="hint">{t('effectiveEnv.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.')}</p>
+ <ListToolbar tools={<Button variant="outline" onClick={refresh} disabled={loading}>{t('effectiveEnv.refresh', 'Refresh')}</Button>}>
+ {services.length > 0 ? <Select value={service || ''} onValueChange={selectService}>
+ <SelectTrigger aria-label={t('effectiveEnv.service', 'Compose service')}><SelectValue /></SelectTrigger>
+ <SelectContent>{services.map(name => <SelectItem key={name} value={name}>{name}</SelectItem>)}</SelectContent>
+ </Select> : !loading && !error && <span className="hint">{t('effectiveEnv.unfiltered', 'No Compose services discovered; showing configuration without a service filter.')}</span>}
+ </ListToolbar>
+ {loading ? <p role="status">{t('effectiveEnv.loading', 'Loading effective environment…')}</p>
+ : error ? <p role="alert" className="error-message">{t('effectiveEnv.error', 'Could not load the effective environment. Retry with Refresh.')}</p>
+ : <>
+ {data?.complete === false && <p role="alert" className="error-message">{t('effectiveEnv.incomplete', 'Incomplete: inherited variables could not be resolved. Only local configuration is shown; override information may be missing.')}</p>}
+ <DataTable columns={columns} data={rows} keyField="key"
+ emptyTitle={data?.complete === false ? t('effectiveEnv.incompleteTitle', 'Inherited configuration unavailable') : t('effectiveEnv.empty', 'No managed variables')}
+ emptyMessage={data?.complete === false ? t('effectiveEnv.incompleteEmpty', 'No local variables to show. Refresh to retry inherited configuration.') : t('effectiveEnv.emptyMessage', 'No local or inherited variables apply to this selection.')}
+ footer={<DataTableFooter shown={rows.length} total={rows.length} />} />
+ </>}
+ </div>;
+}
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 <>
+ <ListToolbar filters={<SegControl value={view} onChange={setView} options={[
+ { value: 'local', label: t('effectiveEnv.local', 'Local variables') },
+ { value: 'effective', label: t('effectiveEnv.title', 'Effective environment') },
+ ]} />} />
+ {view === 'local' ? <EnvironmentVariables key={appId} appId={appId} />
+ : <EffectiveEnvironment key={appId} appId={appId} />}
+ </>;
+}
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/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({
<div className="file-card-thumb">
{showThumb ? (
- <ImageThumb path={entry.path} isS3={isS3} fallback={<FileIcon entry={entry} size={36} />} />
+ <ImageThumb path={entry.path} fileApi={fileApi} fallback={<FileIcon entry={entry} size={36} />} />
) : (
<FileIcon entry={entry} size={36} />
)}
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' && (
+ <NamePromptModal
+ title={t('app.fileManager.createNewFolder', 'Create new folder')}
+ label={t('app.fileManager.folderName', 'Folder name')}
+ placeholder="new-folder"
+ hint={
+ <p className="text-muted">
+ {t('app.fileManager.willBeCreatedIn', 'Will be created in:')}{' '}
+ <code>{currentPath}</code>
+ </p>
+ }
+ submitLabel={t('app.fileManager.createFolder', 'Create folder')}
+ onSubmit={handleCreateFolder}
+ onClose={closeDialog}
+ />
+ )}
+ {dialog?.kind === 'rename' && (
+ <NamePromptModal
+ key={dialog.entry.path}
+ title={t('app.fileManager.rename2', 'Rename {{value}}', {
+ value: dialog.entry.is_dir ? 'Folder' : 'File',
+ })}
+ label={t('app.fileManager.newName', 'New name')}
+ initialValue={dialog.entry.name}
+ submitLabel={t('app.fileManager.rename', 'Rename')}
+ onSubmit={(name) => handleRename(dialog.entry, name)}
+ onClose={closeDialog}
+ />
+ )}
+ {dialog?.kind === 'permissions' && (
+ <PermissionsModal
+ key={dialog.entry.path}
+ entry={dialog.entry}
+ onSubmit={(mode) => 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 (
+ <>
+ <main className="file-manager-main">
+ <div
+ className="file-list-container"
+ onClick={(e) => {
+ if (e.target === e.currentTarget) clearSelection();
+ }}
+ >
+ {dragActive && (
+ <div className="drag-overlay">
+ <div className="drag-overlay-inner">
+ <CloudUpload size={56} strokeWidth={1.5} />
+ <h3>{t('app.fileManager.dropToUpload', 'Drop to upload')}</h3>
+ <p>
+ {t('app.fileManager.filesWillBeUploadedTo', 'Files will be uploaded to')}{' '}
+ <code>{currentPath}</code>
+ </p>
+ </div>
+ </div>
+ )}
+
+ {loading ? (
+ <EmptyState
+ loading
+ loadingVariant="tree"
+ title={t('app.fileManager.loadingFiles', 'Loading files')}
+ />
+ ) : dirError && !searchResults ? (
+ <ErrorState
+ title={t('app.fileManager.couldntOpenThisFolder', "Couldn't open this folder.")}
+ error={dirError}
+ onRetry={() => loadDirectory(currentPath)}
+ />
+ ) : sortedFiltered.length === 0 ? (
+ <EmptyState
+ icon={FolderOpen}
+ title={
+ searchResults
+ ? t('app.fileManager.noMatches', 'No matches')
+ : activeFilter !== 'all'
+ ? t('app.fileManager.noFiles', 'No {{activeFilter}} files', {
+ activeFilter: activeFilter,
+ })
+ : t('app.fileManager.thisFolderIsEmpty', 'This folder is empty')
+ }
+ description={
+ searchResults
+ ? t(
+ 'app.fileManager.tryADifferentSearchTermOr',
+ 'Try a different search term or browse another folder.',
+ )
+ : activeFilter !== 'all'
+ ? t('app.fileManager.tryADifferentFilter', 'Try a different filter.')
+ : t(
+ 'app.fileManager.dropFilesHereOrUseThe',
+ 'Drop files here, or use the buttons above to create something new.',
+ )
+ }
+ />
+ ) : viewMode === 'grid' ? (
+ <div className="file-grid">
+ {sortedFiltered.map((entry) => (
+ <FileCard
+ key={entry.path}
+ entry={entry}
+ selected={selectedPaths.has(entry.path)}
+ selectMode={selectMode}
+ onOpen={rowOpen}
+ onToggleSelect={rowToggleSelect}
+ onContext={rowContext}
+ isS3={isS3}
+ fileApi={fileApi}
+ />
+ ))}
+ </div>
+ ) : (
+ <div className="file-list">
+ <div className="file-list-header">
+ <span className="col-check">
+ <Button
+ variant="unstyled"
+ type="button"
+ className="checkbox-btn"
+ onClick={() => {
+ if (selectedPaths.size === sortedFiltered.length)
+ clearSelection();
+ else {
+ setSelectedPaths(new Set(sortedFiltered.map((x) => x.path)));
+ setSelectMode(sortedFiltered.length > 0);
+ }
+ }}
+ >
+ <span
+ className={`checkbox ${selectedPaths.size === sortedFiltered.length && sortedFiltered.length > 0 ? 'checked' : ''}`}
+ >
+ {selectedPaths.size === sortedFiltered.length &&
+ sortedFiltered.length > 0 && <Check size={12} />}
+ </span>
+ </Button>
+ </span>
+ <span className="col-name">{t('common.labels.name', 'Name')}</span>
+ <span className="col-size">{t('common.labels.size', 'Size')}</span>
+ <span className="col-modified">
+ {t('app.fileManager.modified', 'Modified')}
+ </span>
+ <span className="col-permissions">
+ {t('common.labels.permissions', 'Permissions')}
+ </span>
+ <span className="col-owner">{t('app.fileManager.owner', 'Owner')}</span>
+ <span className="col-actions">{t('common.labels.actions', 'Actions')}</span>
+ </div>
+ {sortedFiltered.map((entry) => (
+ <FileRow
+ key={entry.path}
+ entry={entry}
+ selected={selectedPaths.has(entry.path)}
+ selectMode={selectMode}
+ onOpen={rowOpen}
+ onToggleSelect={rowToggleSelect}
+ onContext={rowContext}
+ onDownload={rowDownload}
+ onRename={rowRename}
+ onPermissions={rowPermissions}
+ onDelete={rowDelete}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ </main>
+ </>
+ );
+}
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 && (
+ <aside className="file-manager-sidebar left">
+ <div className="file-manager-source">
+ <Button
+ variant="unstyled"
+ type="button"
+ className="file-manager-source__close"
+ onClick={() => setSidebarVisible(false)}
+ aria-label={t('app.fileManager.hideSidebar', 'Hide sidebar')}
+ >
+ <X size={14} />
+ </Button>
+ <ServerPicker
+ capability="files"
+ value={targetServerId(target)}
+ onChange={(id, server) =>
+ setTarget(serverTarget(id, server || (id === 's3' ? null : {})))
+ }
+ extraOptions={s3Options}
+ className="file-manager-source__picker"
+ />
+ <div className="file-manager-source__meta">
+ <span
+ className={`file-manager-source__dot${isS3 ? ' is-cloud' : ''}`}
+ aria-hidden="true"
+ />
+ <span>
+ {isRemote
+ ? t('app.fileManager.remoteAgent', 'Remote agent')
+ : isS3
+ ? t('app.fileManager.objectStorage', 'Object storage')
+ : t('app.fileManager.localPanelHost', 'Panel server')}
+ </span>
+ </div>
+ </div>
+
+ {!isRemote && !isS3 && (
+ <div className="sidebar-section sidebar-section--volumes">
+ <div className="sidebar-section-header sidebar-section-header--split">
+ <span
+ className="sidebar-section-title"
+ title={t('app.fileManager.diskUsage', 'Disk usage')}
+ >
+ <HardDrive size={13} />
+ <span>{t('app.fileManager.volumes', 'Volumes')}</span>
+ </span>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="sidebar-action-btn"
+ onClick={loadDiskMounts}
+ disabled={diskLoading}
+ title={t('common.actions.refresh', 'Refresh')}
+ >
+ <RefreshCw size={12} className={diskLoading ? 'spinning' : ''} />
+ </Button>
+ </div>
+ <div className="sidebar-section-content disk-mount-list">
+ {diskMounts.map((mount) => (
+ <Button
+ variant="unstyled"
+ type="button"
+ key={`${mount.device}:${mount.mountpoint}`}
+ className={`disk-mount-item${activeMount?.mountpoint === mount.mountpoint ? ' active' : ''}`}
+ onClick={() => navigateTo(mount.mountpoint)}
+ title={`${mount.device} · ${mount.used_human} / ${mount.total_human}`}
+ >
+ <div className="disk-mount-header">
+ <span className="disk-mount-point">
+ {mount.mountpoint === '/'
+ ? t('app.fileManager.rootDisk', 'Root disk')
+ : mountDisplayName(mount)}
+ </span>
+ <span className={`disk-percent ${getDiskColor(mount.percent)}`}>
+ {mount.percent}%
+ </span>
+ </div>
+ <div className={`disk-progress ${getDiskColor(mount.percent)}`}>
+ <span
+ className="disk-progress-fill"
+ style={{ width: `${mount.percent}%` }}
+ />
+ </div>
+ </Button>
+ ))}
+ {diskLastUpdated && (
+ <span className="disk-updated disk-updated--footer">
+ <Clock size={11} />
+ {t('app.fileManager.updatedAt', 'Updated {{time}}', {
+ time: formatTime(diskLastUpdated, { seconds: true }),
+ })}
+ </span>
+ )}
+ </div>
+ </div>
+ )}
+
+ {!isS3 && (
+ <>
+ <div className="sidebar-section">
+ <div className="sidebar-section-header static">
+ <Zap size={16} />
+ <span>{t('app.fileManager.quickAccess', 'Quick access')}</span>
+ </div>
+ <div className="sidebar-section-content quick-access-list">
+ {quickAccess.map((q) => (
+ <Button
+ variant="unstyled"
+ type="button"
+ key={q.label}
+ className={`quick-access-item ${currentPath === q.path ? 'active' : ''}`}
+ onClick={() => navigateTo(q.path)}
+ >
+ <q.icon size={14} />
+ <span>{q.label}</span>
+ </Button>
+ ))}
+ </div>
+ </div>
+
+ <div className="sidebar-section">
+ <div className="sidebar-section-header sidebar-section-header--split">
+ <Button
+ variant="unstyled"
+ type="button"
+ className="sidebar-section-toggle"
+ onClick={() => setTreeCollapsed(!treeCollapsed)}
+ title={t('app.fileManager.folders', 'Folders')}
+ >
+ <FolderTreeIcon size={16} />
+ <span>{t('app.fileManager.fileSystem', 'File system')}</span>
+ {treeCollapsed ? (
+ <ChevronRight size={16} />
+ ) : (
+ <ChevronDown size={16} />
+ )}
+ </Button>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="sidebar-action-btn"
+ onClick={() => setDialog({ kind: 'newFolder' })}
+ disabled={isRemote}
+ title={t('app.fileManager.newFolder', 'New folder')}
+ >
+ <FolderPlus size={14} />
+ </Button>
+ </div>
+ {!treeCollapsed && (
+ <div className="sidebar-section-content tree-content">
+ <FolderTree
+ roots={TREE_ROOTS}
+ expanded={treeExpanded}
+ treeCache={treeCache}
+ treeLoading={treeLoading}
+ currentPath={currentPath}
+ onNavigate={navigateTo}
+ onToggle={toggleTreeExpand}
+ />
+ </div>
+ )}
+ </div>
+ </>
+ )}
+ </aside>
+ )}
+ </>
+ );
+}
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 (
+ <>
+ <div className="status-bar">
+ <div className="status-bar-left">
+ <span className="status-item">
+ <span className="status-label">{t('app.fileManager.total', 'Total')}</span>
+ <span className="status-value">
+ {stats.total} item{stats.total !== 1 ? 's' : ''}
+ </span>
+ </span>
+ <span className="status-divider" />
+ <span className="status-item">
+ <Folder size={12} />
+ <span>
+ {stats.folders} folder{stats.folders !== 1 ? 's' : ''}
+ </span>
+ </span>
+ <span className="status-item">
+ <File size={12} />
+ <span>
+ {stats.files} file{stats.files !== 1 ? 's' : ''}
+ </span>
+ </span>
+ {stats.totalBytes > 0 && (
+ <>
+ <span className="status-divider" />
+ <span className="status-item">
+ <span className="status-label">{t('common.labels.size', 'Size')}</span>
+ <span className="status-value">{formatBytes(stats.totalBytes)}</span>
+ </span>
+ </>
+ )}
+ </div>
+ <div className="status-bar-right">
+ {stats.selectedCount > 0 && (
+ <span className="status-selection">
+ {stats.selectedCount} {t('app.fileManager.selected', 'selected ·')}{' '}
+ {formatBytes(stats.selectedBytes)}
+ </span>
+ )}
+ <span
+ className="status-shortcuts"
+ title={t('app.fileManager.keyboardShortcuts', 'Keyboard shortcuts')}
+ >
+ {t('app.fileManager.upDelDeleteF2RenameA', '⌫ Up · Del Delete · F2 Rename · ⌘A All')}
+ </span>
+ </div>
+ </div>
+ </>
+ );
+}
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 (
+ <>
+ <div className="file-manager-toolbar">
+ <div className="toolbar-left">
+ <Button
+ variant="unstyled"
+ type="button"
+ className="toolbar-icon-btn"
+ onClick={() => setSidebarVisible(!sidebarVisible)}
+ title={
+ sidebarVisible
+ ? t('app.fileManager.hideSidebar', 'Hide sidebar')
+ : t('app.fileManager.showSidebar', 'Show sidebar')
+ }
+ >
+ {sidebarVisible ? <PanelLeftClose size={14} /> : <PanelLeftOpen size={14} />}
+ </Button>
+ <div className="nav-buttons">
+ <Button
+ variant="unstyled"
+ type="button"
+ className="nav-btn"
+ onClick={goBack}
+ disabled={historyIdx === 0}
+ title={t('common.actions.back', 'Back')}
+ >
+ <ArrowLeft size={14} />
+ </Button>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="nav-btn"
+ onClick={goForward}
+ disabled={historyIdx >= history.length - 1}
+ title={t('app.fileManager.forward', 'Forward')}
+ >
+ <ArrowRight size={14} />
+ </Button>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="nav-btn"
+ onClick={goUp}
+ disabled={!parentPath}
+ title="Up"
+ >
+ <ArrowUp size={14} />
+ </Button>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="nav-btn"
+ onClick={() => navigateTo(isS3 ? '/' : '/home')}
+ title={t('app.fileManager.home', 'Home')}
+ >
+ <Home size={14} />
+ </Button>
+ </div>
+ <div className="path-breadcrumb">
+ {breadcrumbs.map((crumb, idx) => (
+ <span key={crumb.path + idx} className="crumb-segment">
+ {idx > 0 && <span className="crumb-separator">/</span>}
+ <Button
+ variant="unstyled"
+ type="button"
+ className={`crumb ${idx === breadcrumbs.length - 1 ? 'crumb-active' : ''}`}
+ onClick={() => navigateTo(crumb.path)}
+ >
+ {crumb.name}
+ </Button>
+ </span>
+ ))}
+ </div>
+ {activeMount && !isRemote && !isS3 && (
+ <span
+ className="file-mount-chip"
+ title={`${activeMount.device} · ${activeMount.total_human}`}
+ >
+ <HardDrive size={12} />
+ <span>
+ {activeMount.mountpoint === '/'
+ ? t('app.fileManager.rootDisk', 'Root disk')
+ : activeMount.mountpoint}
+ </span>
+ </span>
+ )}
+ </div>
+ <div className="toolbar-right">
+ <Select value={activeFilter} onValueChange={setActiveFilter}>
+ <SelectTrigger
+ className="file-toolbar-select"
+ title={t('app.fileManager.types', 'Types')}
+ aria-label={t('app.fileManager.types', 'Types')}
+ >
+ <File size={13} aria-hidden="true" />
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {FILTER_OPTIONS.map((option) => (
+ <SelectItem key={option.id} value={option.id}>
+ {filterLabels[option.id]} ({filterCounts[option.id] ?? 0})
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Select value={sortValue} onValueChange={handleSortChange}>
+ <SelectTrigger
+ className="file-toolbar-select"
+ title={t('app.fileManager.sort', 'Sort')}
+ aria-label={t('app.fileManager.sort', 'Sort')}
+ >
+ <ArrowUpDown size={13} aria-hidden="true" />
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="name-asc">
+ {t('app.fileManager.nameAZ', 'Name A-Z')}
+ </SelectItem>
+ <SelectItem value="name-desc">
+ {t('app.fileManager.nameZA', 'Name Z-A')}
+ </SelectItem>
+ <SelectItem value="modified-desc">
+ {t('app.fileManager.newest', 'Newest')}
+ </SelectItem>
+ <SelectItem value="modified-asc">
+ {t('app.fileManager.oldest', 'Oldest')}
+ </SelectItem>
+ <SelectItem value="size-desc">
+ {t('app.fileManager.largest', 'Largest')}
+ </SelectItem>
+ <SelectItem value="size-asc">
+ {t('app.fileManager.smallest', 'Smallest')}
+ </SelectItem>
+ <SelectItem value="type-asc">{t('common.labels.type', 'Type')}</SelectItem>
+ <SelectItem value="type-desc">
+ {t('app.fileManager.typeZA', 'Type Z-A')}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ <div className="search-field">
+ <Search size={14} className="search-field-icon" />
+ <input
+ type="text"
+ placeholder={t('app.fileManager.searchFiles', 'Search files…')}
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
+ />
+ {(searchResults || searchQuery) && (
+ <Button
+ variant="unstyled"
+ type="button"
+ className="search-field-clear"
+ onClick={clearSearch}
+ title={t('common.actions.clear', 'Clear')}
+ >
+ <X size={12} />
+ </Button>
+ )}
+ </div>
+ <div className="view-toggle">
+ <Button
+ variant="unstyled"
+ type="button"
+ className={`view-toggle-btn ${viewMode === 'grid' ? 'active' : ''}`}
+ onClick={() => setViewMode('grid')}
+ title={t('app.fileManager.gridView', 'Grid view')}
+ >
+ <LayoutGrid size={14} />
+ </Button>
+ <Button
+ variant="unstyled"
+ type="button"
+ className={`view-toggle-btn ${viewMode === 'list' ? 'active' : ''}`}
+ onClick={() => setViewMode('list')}
+ title={t('app.fileManager.listView', 'List view')}
+ >
+ <List size={14} />
+ </Button>
+ </div>
+ <Button
+ variant="unstyled"
+ type="button"
+ className={`toolbar-icon-btn ${showHidden ? 'active' : ''}`}
+ onClick={() => setShowHidden(!showHidden)}
+ title={t('app.fileManager.toggleHiddenFiles', 'Toggle hidden files')}
+ >
+ {showHidden ? <Eye size={14} /> : <EyeOff size={14} />}
+ </Button>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="toolbar-icon-btn"
+ onClick={() => loadDirectory(currentPath)}
+ title={t('common.actions.refresh', 'Refresh')}
+ >
+ <RefreshCw size={14} className={loading ? 'spinning' : ''} />
+ </Button>
+ </div>
+ </div>
+ </>
+ );
+}
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 && (
+ <div className="upload-tray">
+ <div className="upload-tray-header">
+ <CloudUpload size={16} />
+ <span>
+ {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')}
+ </span>
+ {activeUploads.length > 0 && (
+ <span className="upload-tray-percent">{Math.round(totalUploadProgress)}%</span>
+ )}
+ <Button
+ variant="unstyled"
+ type="button"
+ className="toolbar-icon-btn small"
+ onClick={() => setUploads([])}
+ title={t('common.actions.clear', 'Clear')}
+ >
+ <X size={14} />
+ </Button>
+ </div>
+ <div className="upload-tray-list">
+ {uploads.map((u) => (
+ <div key={u.id} className={`upload-tray-item status-${u.status}`}>
+ <span className="upload-name">{u.name}</span>
+ <div className="upload-bar">
+ <div className="upload-bar-fill" style={{ width: `${u.progress}%` }} />
+ </div>
+ <span className="upload-status">
+ {u.status === 'done'
+ ? t('common.actions.done', 'Done')
+ : u.status === 'error'
+ ? t('app.fileManager.uploadFailed', 'Failed')
+ : `${Math.round(u.progress)}%`}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </>
+ );
+}
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 <img>. 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 <img src={src} alt={alt} className={className} loading="lazy" />;
}
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({
<div className="preview-image-wrap">
<ImageThumb
path={file.path}
- isS3={isS3}
+ fileApi={fileApi}
fallback={
<div className="preview-unavailable">
<EyeOff size={48} strokeWidth={1.5} />
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..585fc02b
--- /dev/null
+++ b/frontend/src/components/file-manager/__tests__/boundaries.test.js
@@ -0,0 +1,23 @@
+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(); }'],
+ ['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';"],
+ ])
+ 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
new file mode 100644
index 00000000..978c0b1f
--- /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', 'preview');
+ 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..0561808f
--- /dev/null
+++ b/frontend/src/components/file-manager/fileAdapter.js
@@ -0,0 +1,51 @@
+// 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', 'preview'];
+
+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),
+ preview: async (path) => ({ blob: await api.getFileBlob(path) }),
+ };
+ 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),
+ preview: (path) => api.getS3DownloadUrl(path),
+ };
+ 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/components/file-manager/hooks/useDirectoryBrowser.js b/frontend/src/components/file-manager/hooks/useDirectoryBrowser.js
new file mode 100644
index 00000000..eb5743e1
--- /dev/null
+++ b/frontend/src/components/file-manager/hooks/useDirectoryBrowser.js
@@ -0,0 +1,278 @@
+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: target.kind, server_id: target.server_id });
+ // ─── 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('');
+ // 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')) {
+ 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..82258f36
--- /dev/null
+++ b/frontend/src/components/file-manager/hooks/useFileActions.js
@@ -0,0 +1,157 @@
+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 });
+ 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,
+ setDialog,
+ closeDialog,
+ handleCreateFolder,
+ handleDelete,
+ handleRename,
+ handleChangePermissions,
+ handleDownload,
+ downloadSelected,
+ 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..0b25a053
--- /dev/null
+++ b/frontend/src/components/file-manager/hooks/useFileEditor.js
@@ -0,0 +1,77 @@
+import { useEffect, useRef, useState } from 'react';
+import { errorReason } from '@/utils/errorMessage';
+
+export default function useFileEditor({ fileApi, toast, t, onSaved }) {
+ 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);
+ const activeApi = useRef(fileApi);
+ activeApi.current = fileApi;
+ useEffect(
+ () => () => {
+ generation.current++;
+ },
+ [],
+ );
+
+ const setPreviewFile = (entry) => {
+ generation.current++;
+ setPreview(entry ? { fileApi, entry } : null);
+ 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/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 <form onSubmit={submit} className="preview-settings">
+ <p className="preview-settings__hint">{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.')}</p>
+ <div className="form-row">
+ <FormField htmlFor="preview-pr-number" label={t('app.previewList.prNumber', 'PR number')}>
+ <Input id="preview-pr-number" type="number" min="1" step="1" required value={number} onChange={e => setNumber(e.target.value)} />
+ </FormField>
+ <FormField htmlFor="preview-branch" label={t('app.previewList.branch', 'Repository branch')}>
+ <Input id="preview-branch" required value={branch} onChange={e => setBranch(e.target.value)} />
+ </FormField>
+ <FormField htmlFor="preview-commit" label={t('app.previewList.commit', 'Full commit SHA')}>
+ <Input id="preview-commit" required pattern="[0-9a-fA-F]{40}|[0-9a-fA-F]{64}" value={sha} onChange={e => setSha(e.target.value)} />
+ </FormField>
+ </div>
+ <Button type="submit" disabled={busy}>{t('app.previewList.createPreview', 'Deploy preview')}</Button>
+ </form>;
+}
diff --git a/frontend/src/components/previews/PreviewList.jsx b/frontend/src/components/previews/PreviewList.jsx
index d56e8b29..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 () => {
@@ -87,8 +89,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);
@@ -97,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'),
@@ -107,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);
@@ -133,7 +154,7 @@ const PreviewList = ({ appId }) => {
<div>
<h3>{t('app.previewList.prPreviewEnvironments', 'PR preview environments')}</h3>
<p className="preview-settings__hint">
- {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.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.')}
</p>
</div>
</div>
@@ -175,9 +196,19 @@ const PreviewList = ({ appId }) => {
)}
</div>
+ {enabled && <>
+ <div className="preview-settings__toggle">
+ <Label htmlFor="preview-inherit">{t('app.previewList.inheritEnv', 'Inherit application environment (may grant access to production databases and services)')}</Label>
+ <Switch id="preview-inherit" checked={!!settings?.inherit_environment} disabled={saving}
+ onCheckedChange={inherit_environment => saveSettings({ inherit_environment })} />
+ </div>
+ <PreviewCreateForm onCreate={handleCreate} busy={creating} />
+ </>}
+
{/* Active previews */}
<div className="preview-list__toolbar">
<h4>{t('app.previewList.activePreviews', 'Active previews')}</h4>
+ <Button variant="ghost" onClick={load}>{t('app.previewList.refresh', 'Refresh status')}</Button>
<Button variant="ghost" onClick={handleSync} disabled={syncing}>
<RefreshCw size={15} className={syncing ? 'spin' : undefined} />
{t('app.previewList.syncWithOpenPrs', 'Sync with open PRs')}
@@ -190,7 +221,7 @@ const PreviewList = ({ appId }) => {
title={t('app.previewList.noActivePreviews', 'No active previews')}
description={
enabled
- ? t('app.previewList.openAPullRequestToSpin', 'Open a pull request to spin up a preview, or sync to reconcile now.')
+ ? t('app.previewList.createOrWebhook', 'Deploy a pinned branch above, or connect a signed PR webhook to this application.')
: t('app.previewList.enablePrPreviewsAboveToStart', 'Enable PR previews above to start deploying preview environments.')
}
/>
@@ -207,7 +238,7 @@ const PreviewList = ({ appId }) => {
<div className="preview-item__meta">
{p.branch && <span className="preview-item__branch mono">{p.branch}</span>}
{p.short_sha && <span className="preview-item__sha mono">{p.short_sha}</span>}
- {p.url && (
+ {p.url && p.status === 'running' && (
<a
className="preview-item__url"
href={p.url}
@@ -218,9 +249,15 @@ const PreviewList = ({ appId }) => {
</a>
)}
</div>
+ {p.status_reason && p.status !== 'running' && <p className="preview-settings__hint">{p.status_reason}</p>}
+ {p.status === 'unavailable' && !p.status_reason && (
+ <p className="preview-settings__hint">
+ {t('app.previewList.noRuntime', 'No provisioned runtime is recorded for this preview. Its URL is unavailable.')}
+ </p>
+ )}
</div>
<div className="preview-item__actions">
- {p.url && (
+ {p.url && p.status === 'running' && (
<Button variant="ghost" size="sm" asChild>
<a href={p.url} target="_blank" rel="noopener noreferrer">
<ExternalLink size={15} />
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/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json
index 5124228e..79553fa5 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": "تدمير المعاينة",
@@ -4432,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 817e0f3b..e509e9e5 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": "পূর্বরূপ ধ্বংস",
@@ -4432,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 064b5d65..b4e766af 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",
@@ -4432,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 8110a503..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",
@@ -4420,9 +4421,14 @@
},
"previewList": {
"activePreviews": "Active previews",
+ "branch": "Repository branch",
+ "commit": "Full commit SHA",
"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.",
+ "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",
@@ -4430,18 +4436,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",
- "openAPullRequestToSpin": "Open a pull request to spin up a preview, or sync to reconcile now.",
+ "noRuntime": "No provisioned runtime is recorded for this preview. Its URL is unavailable.",
+ "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}}",
+ "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."
@@ -8179,6 +8192,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..b2b09252 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",
@@ -4432,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 7ec01011..74d98fba 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",
@@ -4432,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 36df785e..508006ff 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",
@@ -4432,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 39114f3f..48e1f778 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",
@@ -4432,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 2689af1b..9ac6bcce 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": "미리보기 삭제",
@@ -4432,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 0ae63d31..edd33525 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",
@@ -4432,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 722b7e81..fc379fc3 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",
@@ -4432,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 2b7f26bb..094882ff 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": "Уничтожить предварительный просмотр",
@@ -4432,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 ea69ebf5..597ce1cd 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": "ทำลายการแสดงตัวอย่าง",
@@ -4432,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 efb29013..ed79b36d 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",
@@ -4432,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 78d5cc40..351caab8 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",
@@ -4432,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 3226ac89..0e967f9a 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": "销毁预览",
@@ -4432,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 b51ec35f..742c9ba2 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": "銷毀預覽",
@@ -4432,7 +4431,6 @@
"enabled": "已啟用",
"loadingPreviews": "正在載入預覽…",
"noActivePreviews": "沒有活動預覽",
- "openAPullRequestToSpin": "開啟 Pull Request 即可建立預覽環境,或立即同步以更新現有環境。",
"placeholders": "佔位符:",
"pr": "PR #",
"prPreviewEnvironments": "PR 預覽環境",
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"],
};
diff --git a/frontend/src/pages/FileManager.jsx b/frontend/src/pages/FileManager.jsx
index 7aa8d399..4e56eb96 100644
--- a/frontend/src/pages/FileManager.jsx
+++ b/frontend/src/pages/FileManager.jsx
@@ -1,152 +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 },
- ],
-};
-
-// 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
- // 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 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);
- 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
@@ -155,671 +43,184 @@ 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; };
- }, []);
-
- // 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]);
-
- // ─── 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 { s3Options, quickAccess } = useFileTargets({ target, isRemote, t });
+
+ const {
+ selectedPaths,
+ setSelectedPaths,
+ selectMode,
+ setSelectMode,
+ setLastClickedPath,
+ toggleSelect,
+ clearSelection,
+ } = useFileSelection();
+ const handleToggleSelect = (entry, event) => toggleSelect(entry, event, sortedFiltered);
+
+ 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]);
-
- // ─── 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));
+ 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;
}
- 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));
+ if (isS3 && !fileApi.supports(op)) {
+ toast.error(
+ t('app.fileManager.isnTAvailableOnS3Buckets', "{{op}} isn't available on S3 buckets", {
+ op: op,
+ }),
+ );
+ return true;
}
- return api.writeFile(path, content);
+ return false;
},
- 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 remoteGuard = useCallback((op) => {
- if (isRemote && !REMOTE_SUPPORTED.has(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)) {
- toast.error(t('app.fileManager.isnTAvailableOnS3Buckets', '{{op}} isn\'t available on S3 buckets', { op: op }));
- return true;
- }
- return false;
- }, [isRemote, isS3, 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);
- }
- } 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; });
- }
- }
- 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 api.searchFiles(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);
- };
+ [isRemote, isS3, fileApi, t, toast],
+ );
- // ─── ops ─────────────────────────────────────────────
- const handleSaveFile = async () => {
- if (!previewFile) return;
- try {
- await fileApi.write(previewFile.path, fileContent);
- toast.success(t('app.fileManager.fileSaved', 'File saved'));
+ 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);
- 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 api.createDirectory(`${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 api.browseFiles(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 api.renameFile(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 api.changeFilePermissions(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 = isS3 ? api.uploadS3 : api.uploadFile;
- 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;
+ },
+ remoteGuard,
+ toast,
+ t,
+ });
- 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 { treeExpanded, treeCache, refreshTree, treeLoading, toggleTreeExpand } = useFileTree({
+ fileApi,
+ currentPath,
+ });
- const selectedEntries = useMemo(
- () => sortedFiltered.filter((e) => selectedPaths.has(e.path)),
- [sortedFiltered, selectedPaths],
- );
+ const { diskMounts, diskLastUpdated, diskLoading, loadDiskMounts, activeMount } =
+ useFileVolumes(currentPath);
+
+ const {
+ dialog,
+ setDialog,
+ closeDialog,
+ handleCreateFolder,
+ handleDelete,
+ handleRename,
+ handleChangePermissions,
+ handleDownload,
+ downloadSelected,
+ 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(() => {
@@ -841,7 +242,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);
@@ -850,7 +254,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]);
@@ -871,50 +277,43 @@ function FileManager() {
const rowOpen = useStableHandler(handleOpen);
const rowToggleSelect = useStableHandler(handleToggleSelect);
const rowContext = useStableHandler(openContextMenu);
- const rowDownload = useStableHandler((entry) => fileApi.download(entry));
+ const rowDownload = useStableHandler(handleDownload);
const rowRename = useStableHandler(openRenameModal);
const rowPermissions = useStableHandler(openPermissionsModal);
const rowDelete = useStableHandler((entry) => handleDelete(entry));
const copyPathToClipboard = (path) => copyText(path);
- const downloadSelected = () => {
- 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(() => (
- <>
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => setDialog({ kind: 'newFolder' })}
- disabled={isRemote || isS3}
- >
- <FolderPlus size={14} /> {t('app.fileManager.newFolder', 'New folder')}
- </Button>
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => fileInputRef.current?.click()}
- disabled={isRemote}
- >
- <Upload size={14} /> {t('app.fileManager.upload', 'Upload')}
- </Button>
- {!isS3 && (
- <Button type="button" size="sm" onClick={() => navigate('/terminal')}>
- <Terminal size={14} /> {t('app.fileManager.terminal', 'Terminal')}
+ useTopbarActions(
+ () => (
+ <>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => setDialog({ kind: 'newFolder' })}
+ disabled={isRemote || isS3}
+ >
+ <FolderPlus size={14} /> {t('app.fileManager.newFolder', 'New folder')}
</Button>
- )}
- </>
- ), [isRemote, isS3, currentPath]);
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => fileInputRef.current?.click()}
+ disabled={isRemote}
+ >
+ <Upload size={14} /> {t('app.fileManager.upload', 'Upload')}
+ </Button>
+ {!isS3 && (
+ <Button type="button" size="sm" onClick={() => navigate('/terminal')}>
+ <Terminal size={14} /> {t('app.fileManager.terminal', 'Terminal')}
+ </Button>
+ )}
+ </>
+ ),
+ [isRemote, isS3, currentPath],
+ );
// ─── render ──────────────────────────────────────────
return (
@@ -925,216 +324,123 @@ function FileManager() {
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
- <input
- type="file"
- ref={fileInputRef}
- multiple
- className="hidden"
- onChange={handleUploadInput}
- />
+ <input type="file" ref={fileInputRef} multiple className="hidden" onChange={handleUploadInput} />
{isRemote && (
<div className="file-manager-target-banner">
- {t('app.fileManager.browsingOn', 'Browsing on')} <strong>{target.name}</strong> {t('app.fileManager.readWriteOnlyMkdirDeleteRename', "(read/write only). Mkdir/delete/rename/upload aren't yet supported on remote agents.")}
+ {t('app.fileManager.browsingOn', 'Browsing on')} <strong>{target.name}</strong>{' '}
+ {t(
+ 'app.fileManager.readWriteOnlyMkdirDeleteRename',
+ "(read/write only). Mkdir/delete/rename/upload aren't yet supported on remote agents.",
+ )}
</div>
)}
{isS3 && (
<div className="file-manager-target-banner">
- {t('app.fileManager.browsingYour', 'Browsing your')} <strong>{t('app.fileManager.s3Bucket', 'S3 bucket')}</strong>.{' '}
- {t('app.fileManager.s3SupportedOperations', "Upload, download, edit and delete work; folders, rename and permissions don't apply to object storage.")}
+ {t('app.fileManager.browsingYour', 'Browsing your')}{' '}
+ <strong>{t('app.fileManager.s3Bucket', 'S3 bucket')}</strong>.{' '}
+ {t(
+ 'app.fileManager.s3SupportedOperations',
+ "Upload, download, edit and delete work; folders, rename and permissions don't apply to object storage.",
+ )}
</div>
)}
- {uploads.length > 0 && (
- <div className="upload-tray">
- <div className="upload-tray-header">
- <CloudUpload size={16} />
- <span>
- {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')}
- </span>
- {activeUploads.length > 0 && (
- <span className="upload-tray-percent">{Math.round(totalUploadProgress)}%</span>
- )}
- <Button variant="unstyled" type="button" className="toolbar-icon-btn small" onClick={() => setUploads([])} title={t('common.actions.clear', 'Clear')}>
- <X size={14} />
- </Button>
- </div>
- <div className="upload-tray-list">
- {uploads.map((u) => (
- <div key={u.id} className={`upload-tray-item status-${u.status}`}>
- <span className="upload-name">{u.name}</span>
- <div className="upload-bar">
- <div className="upload-bar-fill" style={{ width: `${u.progress}%` }} />
- </div>
- <span className="upload-status">
- {u.status === 'done' ? t('common.actions.done', 'Done') : u.status === 'error' ? t('app.fileManager.uploadFailed', 'Failed') : `${Math.round(u.progress)}%`}
- </span>
- </div>
- ))}
- </div>
- </div>
- )}
+ <FileUploadTray
+ uploads={uploads}
+ activeUploads={activeUploads}
+ totalUploadProgress={totalUploadProgress}
+ setUploads={setUploads}
+ />
- <div className="file-manager-toolbar">
- <div className="toolbar-left">
- <Button variant="unstyled" type="button"
- className="toolbar-icon-btn"
- onClick={() => setSidebarVisible(!sidebarVisible)}
- title={sidebarVisible ? t('app.fileManager.hideSidebar', 'Hide sidebar') : t('app.fileManager.showSidebar', 'Show sidebar')}
- >
- {sidebarVisible ? <PanelLeftClose size={14} /> : <PanelLeftOpen size={14} />}
- </Button>
- <div className="nav-buttons">
- <Button variant="unstyled" type="button" className="nav-btn" onClick={goBack} disabled={historyIdx === 0} title={t('common.actions.back', 'Back')}>
- <ArrowLeft size={14} />
- </Button>
- <Button variant="unstyled" type="button" className="nav-btn" onClick={goForward} disabled={historyIdx >= history.length - 1} title={t('app.fileManager.forward', 'Forward')}>
- <ArrowRight size={14} />
- </Button>
- <Button variant="unstyled" type="button" className="nav-btn" onClick={goUp} disabled={!parentPath} title="Up">
- <ArrowUp size={14} />
- </Button>
- <Button variant="unstyled" type="button" className="nav-btn" onClick={() => navigateTo(isS3 ? '/' : '/home')} title={t('app.fileManager.home', 'Home')}>
- <Home size={14} />
- </Button>
- </div>
- <div className="path-breadcrumb">
- {breadcrumbs.map((crumb, idx) => (
- <span key={crumb.path + idx} className="crumb-segment">
- {idx > 0 && <span className="crumb-separator">/</span>}
- <Button variant="unstyled" type="button"
- className={`crumb ${idx === breadcrumbs.length - 1 ? 'crumb-active' : ''}`}
- onClick={() => navigateTo(crumb.path)}
- >
- {crumb.name}
- </Button>
- </span>
- ))}
- </div>
- {activeMount && !isRemote && !isS3 && (
- <span className="file-mount-chip" title={`${activeMount.device} · ${activeMount.total_human}`}>
- <HardDrive size={12} />
- <span>{activeMount.mountpoint === '/' ? t('app.fileManager.rootDisk', 'Root disk') : activeMount.mountpoint}</span>
- </span>
- )}
- </div>
- <div className="toolbar-right">
- <Select value={activeFilter} onValueChange={setActiveFilter}>
- <SelectTrigger
- className="file-toolbar-select"
- title={t('app.fileManager.types', 'Types')}
- aria-label={t('app.fileManager.types', 'Types')}
- >
- <File size={13} aria-hidden="true" />
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {FILTER_OPTIONS.map((option) => (
- <SelectItem key={option.id} value={option.id}>
- {filterLabels[option.id]} ({filterCounts[option.id] ?? 0})
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <Select value={sortValue} onValueChange={handleSortChange}>
- <SelectTrigger
- className="file-toolbar-select"
- title={t('app.fileManager.sort', 'Sort')}
- aria-label={t('app.fileManager.sort', 'Sort')}
- >
- <ArrowUpDown size={13} aria-hidden="true" />
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="name-asc">{t('app.fileManager.nameAZ', 'Name A-Z')}</SelectItem>
- <SelectItem value="name-desc">{t('app.fileManager.nameZA', 'Name Z-A')}</SelectItem>
- <SelectItem value="modified-desc">{t('app.fileManager.newest', 'Newest')}</SelectItem>
- <SelectItem value="modified-asc">{t('app.fileManager.oldest', 'Oldest')}</SelectItem>
- <SelectItem value="size-desc">{t('app.fileManager.largest', 'Largest')}</SelectItem>
- <SelectItem value="size-asc">{t('app.fileManager.smallest', 'Smallest')}</SelectItem>
- <SelectItem value="type-asc">{t('common.labels.type', 'Type')}</SelectItem>
- <SelectItem value="type-desc">{t('app.fileManager.typeZA', 'Type Z-A')}</SelectItem>
- </SelectContent>
- </Select>
- <div className="search-field">
- <Search size={14} className="search-field-icon" />
- <input
- type="text"
- placeholder={t('app.fileManager.searchFiles', 'Search files…')}
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
- />
- {(searchResults || searchQuery) && (
- <Button variant="unstyled" type="button"
- className="search-field-clear"
- onClick={() => { setSearchResults(null); setSearchQuery(''); }}
- title={t('common.actions.clear', 'Clear')}
- >
- <X size={12} />
- </Button>
- )}
- </div>
- <div className="view-toggle">
- <Button variant="unstyled" type="button"
- className={`view-toggle-btn ${viewMode === 'grid' ? 'active' : ''}`}
- onClick={() => setViewMode('grid')}
- title={t('app.fileManager.gridView', 'Grid view')}
- >
- <LayoutGrid size={14} />
- </Button>
- <Button variant="unstyled" type="button"
- className={`view-toggle-btn ${viewMode === 'list' ? 'active' : ''}`}
- onClick={() => setViewMode('list')}
- title={t('app.fileManager.listView', 'List view')}
- >
- <List size={14} />
- </Button>
- </div>
- <Button variant="unstyled" type="button"
- className={`toolbar-icon-btn ${showHidden ? 'active' : ''}`}
- onClick={() => setShowHidden(!showHidden)}
- title={t('app.fileManager.toggleHiddenFiles', 'Toggle hidden files')}
- >
- {showHidden ? <Eye size={14} /> : <EyeOff size={14} />}
- </Button>
- <Button variant="unstyled" type="button"
- className="toolbar-icon-btn"
- onClick={() => loadDirectory(currentPath)}
- title={t('common.actions.refresh', 'Refresh')}
- >
- <RefreshCw size={14} className={loading ? 'spinning' : ''} />
- </Button>
- </div>
- </div>
+ <FileManagerToolbar
+ setSidebarVisible={setSidebarVisible}
+ sidebarVisible={sidebarVisible}
+ goBack={goBack}
+ history={history}
+ historyIdx={historyIdx}
+ goForward={goForward}
+ goUp={goUp}
+ parentPath={parentPath}
+ navigateTo={navigateTo}
+ isS3={isS3}
+ breadcrumbs={breadcrumbs}
+ activeMount={activeMount}
+ isRemote={isRemote}
+ activeFilter={activeFilter}
+ setActiveFilter={setActiveFilter}
+ FILTER_OPTIONS={FILTER_OPTIONS}
+ filterLabels={filterLabels}
+ filterCounts={filterCounts}
+ sortValue={sortValue}
+ handleSortChange={handleSortChange}
+ searchQuery={searchQuery}
+ setSearchQuery={setSearchQuery}
+ handleSearch={handleSearch}
+ searchResults={searchResults}
+ clearSearch={clearSearch}
+ viewMode={viewMode}
+ setViewMode={setViewMode}
+ showHidden={showHidden}
+ setShowHidden={setShowHidden}
+ loadDirectory={loadDirectory}
+ currentPath={currentPath}
+ loading={loading}
+ />
{selectedPaths.size > 0 && (
<div className="bulk-bar">
<div className="bulk-bar-info">
<Check size={14} />
- <span>{selectedPaths.size} {t('app.fileManager.selected', 'selected ·')} {formatBytes(stats.selectedBytes)}</span>
+ <span>
+ {selectedPaths.size} {t('app.fileManager.selected', 'selected ·')}{' '}
+ {formatBytes(stats.selectedBytes)}
+ </span>
</div>
<div className="bulk-bar-actions">
- <Button variant="unstyled" type="button" className="bulk-btn" onClick={downloadSelected}>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="bulk-btn"
+ onClick={() => downloadSelected(selectedEntries)}
+ >
<Download size={14} /> {t('common.actions.download', 'Download')}
</Button>
{selectedEntries.length === 1 && (
<>
- <Button variant="unstyled" type="button" className="bulk-btn" onClick={() => openRenameModal(selectedEntries[0])}>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="bulk-btn"
+ onClick={() => openRenameModal(selectedEntries[0])}
+ >
<Edit3 size={14} /> {t('app.fileManager.rename', 'Rename')}
</Button>
- <Button variant="unstyled" type="button" className="bulk-btn" onClick={() => copyPathToClipboard(selectedEntries[0].path)}>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="bulk-btn"
+ onClick={() => copyPathToClipboard(selectedEntries[0].path)}
+ >
<Copy size={14} /> {t('app.fileManager.copyPath', 'Copy path')}
</Button>
</>
)}
- <Button variant="unstyled" type="button" className="bulk-btn danger" onClick={() => handleDelete(selectedEntries)}>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="bulk-btn danger"
+ onClick={() => handleDelete(selectedEntries)}
+ >
<Trash2 size={14} /> {t('common.actions.delete', 'Delete')}
</Button>
- <Button variant="unstyled" type="button" className="bulk-btn ghost" onClick={clearSelection}>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="bulk-btn ghost"
+ onClick={clearSelection}
+ >
<X size={14} /> {t('common.actions.clear', 'Clear')}
</Button>
</div>
@@ -1142,238 +448,59 @@ function FileManager() {
)}
<div className={`file-manager-body ${previewFile ? 'has-preview' : ''}`}>
- {sidebarVisible && (
- <aside className="file-manager-sidebar left">
- <div className="file-manager-source">
- <Button variant="unstyled"
- type="button"
- className="file-manager-source__close"
- onClick={() => setSidebarVisible(false)}
- aria-label={t('app.fileManager.hideSidebar', 'Hide sidebar')}
- >
- <X size={14} />
- </Button>
- <ServerPicker
- capability="files"
- value={targetServerId(target)}
- onChange={(id, server) => setTarget(serverTarget(id, server || (id === 's3' ? null : {})))}
- extraOptions={s3Options}
- className="file-manager-source__picker"
- />
- <div className="file-manager-source__meta">
- <span className={`file-manager-source__dot${isS3 ? ' is-cloud' : ''}`} aria-hidden="true" />
- <span>
- {isRemote
- ? t('app.fileManager.remoteAgent', 'Remote agent')
- : isS3
- ? t('app.fileManager.objectStorage', 'Object storage')
- : t('app.fileManager.localPanelHost', 'Panel server')}
- </span>
- </div>
- </div>
-
- {!isRemote && !isS3 && (
- <div className="sidebar-section sidebar-section--volumes">
- <div className="sidebar-section-header sidebar-section-header--split">
- <span className="sidebar-section-title" title={t('app.fileManager.diskUsage', 'Disk usage')}>
- <HardDrive size={13} />
- <span>{t('app.fileManager.volumes', 'Volumes')}</span>
- </span>
- <Button variant="unstyled" type="button" className="sidebar-action-btn" onClick={loadDiskMounts} disabled={diskLoading} title={t('common.actions.refresh', 'Refresh')}>
- <RefreshCw size={12} className={diskLoading ? 'spinning' : ''} />
- </Button>
- </div>
- <div className="sidebar-section-content disk-mount-list">
- {diskMounts.map((mount) => (
- <Button variant="unstyled"
- type="button"
- key={`${mount.device}:${mount.mountpoint}`}
- className={`disk-mount-item${activeMount?.mountpoint === mount.mountpoint ? ' active' : ''}`}
- onClick={() => navigateTo(mount.mountpoint)}
- title={`${mount.device} · ${mount.used_human} / ${mount.total_human}`}
- >
- <div className="disk-mount-header">
- <span className="disk-mount-point">
- {mount.mountpoint === '/'
- ? t('app.fileManager.rootDisk', 'Root disk')
- : mountDisplayName(mount)}
- </span>
- <span className={`disk-percent ${getDiskColor(mount.percent)}`}>
- {mount.percent}%
- </span>
- </div>
- <div className={`disk-progress ${getDiskColor(mount.percent)}`}>
- <span className="disk-progress-fill" style={{ width: `${mount.percent}%` }} />
- </div>
- </Button>
- ))}
- {diskLastUpdated && (
- <span className="disk-updated disk-updated--footer">
- <Clock size={11} />
- {t('app.fileManager.updatedAt', 'Updated {{time}}', { time: formatTime(diskLastUpdated, { seconds: true }) })}
- </span>
- )}
- </div>
- </div>
- )}
-
- {!isS3 && (<>
- <div className="sidebar-section">
- <div className="sidebar-section-header static">
- <Zap size={16} />
- <span>{t('app.fileManager.quickAccess', 'Quick access')}</span>
- </div>
- <div className="sidebar-section-content quick-access-list">
- {quickAccess.map(q => (
- <Button variant="unstyled" type="button"
- key={q.label}
- className={`quick-access-item ${currentPath === q.path ? 'active' : ''}`}
- onClick={() => navigateTo(q.path)}
- >
- <q.icon size={14} />
- <span>{q.label}</span>
- </Button>
- ))}
- </div>
- </div>
-
- <div className="sidebar-section">
- <div className="sidebar-section-header sidebar-section-header--split">
- <Button variant="unstyled"
- type="button"
- className="sidebar-section-toggle"
- onClick={() => setTreeCollapsed(!treeCollapsed)}
- title={t('app.fileManager.folders', 'Folders')}
- >
- <FolderTreeIcon size={16} />
- <span>{t('app.fileManager.fileSystem', 'File system')}</span>
- {treeCollapsed ? <ChevronRight size={16} /> : <ChevronDown size={16} />}
- </Button>
- <Button variant="unstyled" type="button"
- className="sidebar-action-btn"
- onClick={() => setDialog({ kind: 'newFolder' })}
- disabled={isRemote}
- title={t('app.fileManager.newFolder', 'New folder')}
- >
- <FolderPlus size={14} />
- </Button>
- </div>
- {!treeCollapsed && (
- <div className="sidebar-section-content tree-content">
- <FolderTree
- roots={TREE_ROOTS}
- expanded={treeExpanded}
- treeCache={treeCache}
- treeLoading={treeLoading}
- currentPath={currentPath}
- onNavigate={navigateTo}
- onToggle={toggleTreeExpand}
- />
- </div>
- )}
- </div>
- </>)}
-
- </aside>
- )}
-
- <main className="file-manager-main">
- <div
- className="file-list-container"
- onClick={(e) => {
- if (e.target === e.currentTarget) clearSelection();
- }}
- >
- {dragActive && (
- <div className="drag-overlay">
- <div className="drag-overlay-inner">
- <CloudUpload size={56} strokeWidth={1.5} />
- <h3>{t('app.fileManager.dropToUpload', 'Drop to upload')}</h3>
- <p>{t('app.fileManager.filesWillBeUploadedTo', 'Files will be uploaded to')} <code>{currentPath}</code></p>
- </div>
- </div>
- )}
+ <FileManagerSidebar
+ sidebarVisible={sidebarVisible}
+ setSidebarVisible={setSidebarVisible}
+ target={target}
+ setTarget={setTarget}
+ s3Options={s3Options}
+ isS3={isS3}
+ isRemote={isRemote}
+ loadDiskMounts={loadDiskMounts}
+ diskLoading={diskLoading}
+ diskMounts={diskMounts}
+ activeMount={activeMount}
+ navigateTo={navigateTo}
+ diskLastUpdated={diskLastUpdated}
+ quickAccess={quickAccess}
+ currentPath={currentPath}
+ setTreeCollapsed={setTreeCollapsed}
+ treeCollapsed={treeCollapsed}
+ setDialog={setDialog}
+ treeExpanded={treeExpanded}
+ treeCache={treeCache}
+ treeLoading={treeLoading}
+ toggleTreeExpand={toggleTreeExpand}
+ />
- {loading ? (
- <EmptyState loading loadingVariant="tree" title={t('app.fileManager.loadingFiles', 'Loading files')} />
- ) : dirError && !searchResults ? (
- <ErrorState
- title={t('app.fileManager.couldntOpenThisFolder', "Couldn't open this folder.")}
- error={dirError}
- onRetry={() => loadDirectory(currentPath)}
- />
- ) : sortedFiltered.length === 0 ? (
- <EmptyState
- icon={FolderOpen}
- title={searchResults ? t('app.fileManager.noMatches', 'No matches') : activeFilter !== 'all' ? t('app.fileManager.noFiles', 'No {{activeFilter}} files', { activeFilter: activeFilter }) : t('app.fileManager.thisFolderIsEmpty', 'This folder is empty')}
- description={searchResults
- ? t('app.fileManager.tryADifferentSearchTermOr', 'Try a different search term or browse another folder.')
- : activeFilter !== 'all'
- ? t('app.fileManager.tryADifferentFilter', 'Try a different filter.')
- : t('app.fileManager.dropFilesHereOrUseThe', 'Drop files here, or use the buttons above to create something new.')}
- />
- ) : viewMode === 'grid' ? (
- <div className="file-grid">
- {sortedFiltered.map((entry) => (
- <FileCard
- key={entry.path}
- entry={entry}
- selected={selectedPaths.has(entry.path)}
- selectMode={selectMode}
- onOpen={rowOpen}
- onToggleSelect={rowToggleSelect}
- onContext={rowContext}
- isS3={isS3}
- />
- ))}
- </div>
- ) : (
- <div className="file-list">
- <div className="file-list-header">
- <span className="col-check">
- <Button variant="unstyled" type="button"
- className="checkbox-btn"
- onClick={() => {
- if (selectedPaths.size === sortedFiltered.length) clearSelection();
- else {
- setSelectedPaths(new Set(sortedFiltered.map((x) => x.path)));
- setSelectMode(sortedFiltered.length > 0);
- }
- }}
- >
- <span className={`checkbox ${selectedPaths.size === sortedFiltered.length && sortedFiltered.length > 0 ? 'checked' : ''}`}>
- {selectedPaths.size === sortedFiltered.length && sortedFiltered.length > 0 && <Check size={12} />}
- </span>
- </Button>
- </span>
- <span className="col-name">{t('common.labels.name', 'Name')}</span>
- <span className="col-size">{t('common.labels.size', 'Size')}</span>
- <span className="col-modified">{t('app.fileManager.modified', 'Modified')}</span>
- <span className="col-permissions">{t('common.labels.permissions', 'Permissions')}</span>
- <span className="col-owner">{t('app.fileManager.owner', 'Owner')}</span>
- <span className="col-actions">{t('common.labels.actions', 'Actions')}</span>
- </div>
- {sortedFiltered.map((entry) => (
- <FileRow
- key={entry.path}
- entry={entry}
- selected={selectedPaths.has(entry.path)}
- selectMode={selectMode}
- onOpen={rowOpen}
- onToggleSelect={rowToggleSelect}
- onContext={rowContext}
- onDownload={rowDownload}
- onRename={rowRename}
- onPermissions={rowPermissions}
- onDelete={rowDelete}
- />
- ))}
- </div>
- )}
- </div>
- </main>
+ <FileManagerListing
+ fileApi={fileApi}
+ clearSelection={clearSelection}
+ dragActive={dragActive}
+ currentPath={currentPath}
+ loading={loading}
+ dirError={dirError}
+ searchResults={searchResults}
+ loadDirectory={loadDirectory}
+ sortedFiltered={sortedFiltered}
+ activeFilter={activeFilter}
+ viewMode={viewMode}
+ selectedPaths={selectedPaths}
+ selectMode={selectMode}
+ rowOpen={rowOpen}
+ rowToggleSelect={rowToggleSelect}
+ rowContext={rowContext}
+ isS3={isS3}
+ setSelectedPaths={setSelectedPaths}
+ setSelectMode={setSelectMode}
+ rowDownload={rowDownload}
+ rowRename={rowRename}
+ rowPermissions={rowPermissions}
+ rowDelete={rowDelete}
+ />
<PreviewDrawer
+ fileApi={fileApi}
inline
isS3={isS3}
file={previewFile}
@@ -1383,8 +510,11 @@ function FileManager() {
onStartEdit={() => setEditing(true)}
onCancelEdit={() => setEditing(false)}
onSave={handleSaveFile}
- onClose={() => { setPreviewFile(null); setEditing(false); }}
- onDownload={(e) => fileApi.download(e)}
+ onClose={() => {
+ setPreviewFile(null);
+ setEditing(false);
+ }}
+ onDownload={handleDownload}
onRename={openRenameModal}
onPermissions={openPermissionsModal}
onCopyPath={copyPathToClipboard}
@@ -1392,96 +522,28 @@ function FileManager() {
/>
</div>
- <div className="status-bar">
- <div className="status-bar-left">
- <span className="status-item">
- <span className="status-label">{t('app.fileManager.total', 'Total')}</span>
- <span className="status-value">{stats.total} item{stats.total !== 1 ? 's' : ''}</span>
- </span>
- <span className="status-divider" />
- <span className="status-item">
- <Folder size={12} />
- <span>{stats.folders} folder{stats.folders !== 1 ? 's' : ''}</span>
- </span>
- <span className="status-item">
- <File size={12} />
- <span>{stats.files} file{stats.files !== 1 ? 's' : ''}</span>
- </span>
- {stats.totalBytes > 0 && (
- <>
- <span className="status-divider" />
- <span className="status-item">
- <span className="status-label">{t('common.labels.size', 'Size')}</span>
- <span className="status-value">{formatBytes(stats.totalBytes)}</span>
- </span>
- </>
- )}
- </div>
- <div className="status-bar-right">
- {stats.selectedCount > 0 && (
- <span className="status-selection">
- {stats.selectedCount} {t('app.fileManager.selected', 'selected ·')} {formatBytes(stats.selectedBytes)}
- </span>
- )}
- <span className="status-shortcuts" title={t('app.fileManager.keyboardShortcuts', 'Keyboard shortcuts')}>
- {t('app.fileManager.upDelDeleteF2RenameA', '⌫ Up · Del Delete · F2 Rename · ⌘A All')}
- </span>
- </div>
- </div>
+ <FileManagerStatus stats={stats} />
<ContextMenu
menu={contextMenu}
selectionCount={selectedEntries.length}
onClose={() => setContextMenu(null)}
onOpen={handleOpen}
- onDownload={(e) => fileApi.download(e)}
+ onDownload={handleDownload}
onRename={openRenameModal}
onPermissions={openPermissionsModal}
onCopyPath={copyPathToClipboard}
onDelete={(e) => handleDelete(selectedEntries.length > 1 ? selectedEntries : e)}
/>
- {dialog?.kind === 'newFolder' && (
- <NamePromptModal
- title={t('app.fileManager.createNewFolder', 'Create new folder')}
- label={t('app.fileManager.folderName', 'Folder name')}
- placeholder="new-folder"
- hint={<p className="text-muted">{t('app.fileManager.willBeCreatedIn', 'Will be created in:')} <code>{currentPath}</code></p>}
- submitLabel={t('app.fileManager.createFolder', 'Create folder')}
- onSubmit={handleCreateFolder}
- onClose={closeDialog}
- />
- )}
- {dialog?.kind === 'rename' && (
- <NamePromptModal
- key={dialog.entry.path}
- title={t('app.fileManager.rename2', 'Rename {{value}}', { value: dialog.entry.is_dir ? 'Folder' : 'File' })}
- label={t('app.fileManager.newName', 'New name')}
- initialValue={dialog.entry.name}
- submitLabel={t('app.fileManager.rename', 'Rename')}
- onSubmit={(name) => handleRename(dialog.entry, name)}
- onClose={closeDialog}
- />
- )}
- {dialog?.kind === 'permissions' && (
- <PermissionsModal
- key={dialog.entry.path}
- entry={dialog.entry}
- onSubmit={(mode) => handleChangePermissions(dialog.entry, mode)}
- onClose={closeDialog}
- />
- )}
-
- {confirmDialog && (
- <ConfirmDialog
- title={confirmDialog.title}
- message={confirmDialog.message}
- confirmText={confirmDialog.confirmText}
- variant={confirmDialog.variant}
- onConfirm={confirmDialog.onConfirm}
- onCancel={confirmDialog.onCancel}
- />
- )}
+ <FileManagerDialogs
+ dialog={dialog}
+ currentPath={currentPath}
+ handleCreateFolder={handleCreateFolder}
+ closeDialog={closeDialog}
+ handleRename={handleRename}
+ handleChangePermissions={handleChangePermissions}
+ />
</div>
);
}
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/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/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 (
<div className="sk-tabgroup__inner">
+ {topbarChrome}
<EmptyState loading loadingVariant="cards" title={t('app.templates.loadingTemplates', 'Loading templates')} />
</div>
);
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}`);
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 });
+}