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.

test: enforce core boundaries and document extension rules

Juan Denis3c5b948f2ea4
diff --git a/AGENTS.md b/AGENTS.md
index 6bc19648..9106c763 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -38,6 +38,11 @@ Default dev credentials: `admin` / `admin`
## Architecture
+For application startup and File Manager ownership rules, see
+[`docs/CORE_BOUNDARIES.md`](docs/CORE_BOUNDARIES.md). Keep startup as ordered
+bootstrap phases, file transport in the capability-checked adapter, and async
+File Manager state in its feature hooks. CI enforces these boundaries.
+
### Backend (`backend/`)
Flask app factory in `app/__init__.py` using `create_app()`. Three-layer architecture:
diff --git a/backend/app/bootstrap/configuration.py b/backend/app/bootstrap/configuration.py
index 2845c5ef..3baf33ba 100644
--- a/backend/app/bootstrap/configuration.py
+++ b/backend/app/bootstrap/configuration.py
@@ -112,4 +112,3 @@ def configure_application(app, db, migrate, jwt, limiter):
from app.middleware.rate_limit import get_rate_limit_key, register_rate_limit_headers
limiter._key_func = get_rate_limit_key
register_rate_limit_headers(app)
-
diff --git a/backend/app/bootstrap/http.py b/backend/app/bootstrap/http.py
index 70551a19..855ab2a9 100644
--- a/backend/app/bootstrap/http.py
+++ b/backend/app/bootstrap/http.py
@@ -98,4 +98,3 @@ def register_http_handlers(app):
if index and os.path.isfile(index):
return _spa_page()
return {'error': 'Not found'}, 404
-
diff --git a/backend/app/bootstrap/logging.py b/backend/app/bootstrap/logging.py
index 18d099b6..09bbac55 100644
--- a/backend/app/bootstrap/logging.py
+++ b/backend/app/bootstrap/logging.py
@@ -51,5 +51,3 @@ def configure_logging(app):
))
root.addHandler(handler)
_logging_configured = True
-
-
diff --git a/backend/app/bootstrap/persistence.py b/backend/app/bootstrap/persistence.py
index c5382119..3da1a06e 100644
--- a/backend/app/bootstrap/persistence.py
+++ b/backend/app/bootstrap/persistence.py
@@ -72,4 +72,3 @@ def prepare_persistence(app):
except Exception as e:
import logging
logging.getLogger(__name__).warning(f'Setup code unavailable: {e}')
-
diff --git a/backend/app/bootstrap/plugins.py b/backend/app/bootstrap/plugins.py
index d5d4677f..fac42346 100644
--- a/backend/app/bootstrap/plugins.py
+++ b/backend/app/bootstrap/plugins.py
@@ -61,4 +61,3 @@ def load_extensions(app):
except Exception as e:
import logging
logging.getLogger(__name__).warning(f'Extension backend acquisition: {e}')
-
diff --git a/backend/app/bootstrap/runtime.py b/backend/app/bootstrap/runtime.py
index be0c4dd1..915bc6da 100644
--- a/backend/app/bootstrap/runtime.py
+++ b/backend/app/bootstrap/runtime.py
@@ -81,4 +81,3 @@ def start_runtime(app):
# panel is paired.
from app.services import connect_client
connect_client.start_client_if_paired(app)
-
diff --git a/backend/tests/test_bootstrap_boundaries.py b/backend/tests/test_bootstrap_boundaries.py
index e9bf9af8..2aeb5512 100644
--- a/backend/tests/test_bootstrap_boundaries.py
+++ b/backend/tests/test_bootstrap_boundaries.py
@@ -62,7 +62,8 @@ def test_recovery_precedes_consumers_and_handlers_precede_jobs(monkeypatch, runt
'uptime', 'linked', 'relay']
-def test_factory_phase_order_and_context(monkeypatch):
[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
@@ -76,6 +77,8 @@ def test_factory_phase_order_and_context(monkeypatch):
def run(*args):
assert has_app_context() is context
calls.append(name)
+ if name == failed_phase:
+ raise RuntimeError('startup failed')
return run
monkeypatch.setattr(configuration, 'configure_application', phase('configuration'))
@@ -89,9 +92,25 @@ def test_factory_phase_order_and_context(monkeypatch):
monkeypatch.setattr(runtime, 'start_runtime', phase('runtime', True))
monkeypatch.setattr(http, 'register_http_handlers', phase('http'))
monkeypatch.setattr(application, 'socketio', application.socketio)
- application.create_app('testing')
- assert calls == ['configuration', 'socket', 'gateway', 'routes', 'recycle',
- 'restore', 'persistence', 'plugins', 'runtime', 'http']
+ expected = ['configuration', 'socket', 'gateway', 'routes', 'recycle',
+ 'restore', 'persistence', 'plugins', 'runtime', 'http']
+ if failed_phase:
+ with pytest.raises(RuntimeError, match='startup failed'):
+ application.create_app('testing')
+ assert calls == expected[:expected.index(failed_phase) + 1]
+ else:
+ application.create_app('testing')
+ assert calls == expected
+
+
+def test_monitor_failure_does_not_prevent_other_runtime_services(runtime_calls):
+ def fail(_app):
+ raise RuntimeError('monitor unavailable')
+ sys.modules['app.services.monitoring_service'].MonitoringService.resume_if_enabled = fail
+ logger = Mock()
+ runtime.start_runtime(SimpleNamespace(config={}, logger=logger))
+ logger.exception.assert_called_once()
+ assert runtime_calls[-3:] == ['uptime', 'linked', 'relay']
def test_bootstrap_is_an_assembly_layer_not_a_service_dependency():
diff --git a/docs/CORE_BOUNDARIES.md b/docs/CORE_BOUNDARIES.md
new file mode 100644
index 00000000..080a22d0
--- /dev/null
+++ b/docs/CORE_BOUNDARIES.md
@@ -0,0 +1,86 @@
+# Core boundaries
+
+## Backend application startup
+
+`backend/app/__init__.py` owns the public `create_app`, `db`, `jwt`, `migrate`,
+`limiter`, and `get_socketio` interfaces. Keep it as ordered composition.
+Do not put feature initialization or worker loops back into the factory.
+
+The assembly sequence is:
+
+1. Configure logging and Flask extensions/request middleware
+ (`bootstrap/logging.py`, `bootstrap/configuration.py`).
+2. Initialize Socket.IO and the agent gateway; register core blueprints and
+ restore adapters.
+3. Prepare the database and installation data (`bootstrap/persistence.py`).
+4. Load extensions and their compatibility upgrades (`bootstrap/plugins.py`).
+5. Recover interrupted jobs, register handlers and start the runtime
+ (`bootstrap/runtime.py`, `bootstrap/jobs.py`).
+6. Register SPA delivery and HTTP error handlers (`bootstrap/http.py`).
+
+Persistence, extension loading, and runtime startup execute inside the app
+context. Database preparation precedes extension queries; interrupted-job
+recovery precedes consumers; job handlers precede the job consumer. One-shot
+Flask commands and `SERVERKIT_SKIP_BACKGROUND` suppress runtime startup.
+The existing individual services retain their testing and singleton guards.
+
+Bootstrap may depend on services, models, middleware and jobs. Those layers
+must not import bootstrap. A feature exposes a registration/initialization
+function; its appropriate bootstrap phase invokes it. Existing migration
+policy and fail-soft extension behavior are preserved by this split.
+
+`backend/tests/test_bootstrap_boundaries.py` enforces dependency direction,
+factory composition, startup order, context, and CLI suppression. The core
+blueprint registry and API-error tests verify the assembled application.
+
+## File Manager
+
+The route in `frontend/src/pages/FileManager.jsx` composes the feature under
+`components/file-manager/`. Keep the existing shared components and SCSS.
+
+| Owner | Responsibility |
+| --- | --- |
+| `fileAdapter.js` | Select local/agent/S3 transport; reject unsupported operations without falling back to the local host |
+| `hooks/useDirectoryBrowser.js` | URL/path navigation, history, directory loading, search and request invalidation |
+| `hooks/useFileTree.js` | Tree expansion, cached child folders and target-aware refresh |
+| `hooks/useFileEditor.js` | Preview reads, editable contents and save lifecycle |
+| `hooks/useFileActions.js` | Folder/rename/permissions/delete actions and shared confirmation |
+| `hooks/useFileTransfers.js` | Upload batches, drag/drop, progress and timer cleanup |
+| `hooks/useFileSelection.js` | Selection and range-selection anchor |
+| `hooks/useFileListingModel.js` | Sorting, filtering, breadcrumbs and derived counts |
+| `hooks/useFilePreferences.js` | Persisted view/sidebar preferences |
+| `hooks/useFileTargets.js`, `useFileVolumes.js` | Target metadata and panel volume metadata |
+| `hooks/useImagePreview.js` | Thumbnail request and object-URL lifetime through the adapter |
+| `FileManager*.jsx`, `FileUploadTray.jsx` | Render sections and forward user actions through props |
+
+Add storage operations to the adapter and its explicit capability map. A
+disabled button is not sufficient protection: the adapter must reject an
+unsupported call. Authorization remains enforced by the backend.
+
+Async work stays in the owning hook. Before applying a result, validate that
+its request, path and target still match the current view. Keep an upload's
+original destination throughout its batch. Completion must not navigate the
+user back to the directory where the operation began. Failed saves retain the
+draft. Thumbnails must never use the panel's local-file endpoint for an agent.
+
+Views do not import the API service or route pages. Metadata hooks are the
+documented exception to adapter-only transport: they read storage configuration,
+panel version and panel volumes, not file contents. The route constructs the
+adapter but does not issue API calls or await requests.
+
+## Checks when extending these areas
+
+- `npm run lint` in `frontend`: includes File Manager dependency/composition
+ checks through `scripts/check-frontend-boundaries.mjs`.
+- `npm test`: adapter contracts and positive/negative boundary-check fixtures.
+- `npm run test:file-manager`: actual page in Chromium, covering navigation,
+ target switching, late results, editing, confirmations and uploads.
+- `npm run build`: verify the complete production import graph.
+- `python -m pytest tests/test_bootstrap_boundaries.py
+ tests/test_core_blueprint_registry.py tests/test_cli_skips_background.py
+ tests/test_api_error_shape.py` in `backend`: focused startup coverage.
+- Run the full backend suite for application assembly changes.
+
+These checks already run through the existing frontend/backend CI workflows.
+Do not raise a size ceiling or allow a new dependency just to make a check pass;
+first decide which existing owner should contain the behavior.
diff --git a/frontend/scripts/check-file-manager-boundaries.mjs b/frontend/scripts/check-file-manager-boundaries.mjs
index 14d69393..6baa16bb 100644
--- a/frontend/scripts/check-file-manager-boundaries.mjs
+++ b/frontend/scripts/check-file-manager-boundaries.mjs
@@ -33,7 +33,7 @@ export function inspectFileManagerSource(path, source) {
if ((page || view) && node.type === 'CallExpression' && node.callee?.object?.name === 'api') {
errors.push(`${path}: views must not call API methods`);
}
- if (view && node.type === 'CallExpression' && node.callee?.name === 'fetch') {
+ if ((page || view) && node.type === 'CallExpression' && node.callee?.name === 'fetch') {
errors.push(`${path}: views must not fetch`);
}
for (const value of Object.values(node)) {
diff --git a/frontend/src/components/file-manager/__tests__/boundaries.test.js b/frontend/src/components/file-manager/__tests__/boundaries.test.js
index 43bc2d59..94950f06 100644
--- a/frontend/src/components/file-manager/__tests__/boundaries.test.js
+++ b/frontend/src/components/file-manager/__tests__/boundaries.test.js
@@ -12,6 +12,7 @@ test('File Manager keeps transport, orchestration and views separate', () => {
test('boundary guard rejects dependencies that would recombine the feature', () => {
for (const [path, source] of [
['pages/FileManager.jsx', 'async function load() { await api.browseFiles(); }'],
+ ['pages/FileManager.jsx', "fetch('/api/v1/files').then(render);"],
['components/file-manager/FileManagerListing.jsx', "import { api } from '@/services/api';"],
['components/file-manager/hooks/useFileEditor.js', "import Page from '@/pages/FileManager';"],
['components/file-manager/FileManagerSidebar.jsx', "import useFileTree from './hooks/useFileTree';"],